NAME

TclCurl - Transfer data to and from URLs using FTP, FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, FILE, LDAP, LDAPS, IMAP, IMAPS, POP, POP3, SMTP, SMTPS, and GOPHER.

SYNOPSIS

curl::init
curl::transfer ?options?
curl::version
curl::escape url
curl::unescape url
curl::curlConfig option
curl::versioninfo option
curl::easystrerror errorCode
curlHandle configure ?options?
curlHandle perform
curlHandle getinfo curlinfo_option
curlHandle cleanup
curlHandle reset
curlHandle duphandle
curlHandle pause
curlHandle resume

DESCRIPTION

The TclCurl extension gives Tcl programmers access to the libcurl library written by Daniel Stenberg. With TclCurl, you can download from URLs, upload to them, and perform many other network transfer operations. For more information, see http://curl.haxx.se.

curl::init

This procedure must be called first. It returns a curlHandle, which you use to invoke TclCurl procedures. Calling init initializes TclCurl, and each call to init MUST have a corresponding call to cleanup when the operation is complete.

You should perform all sequential file transfers using the same curlHandle. This allows TclCurl to reuse persistent connections when possible.

RETURN VALUE

The curlHandle to use.

curlHandle configure ?OPTIONS?

configure

is used to set the options for a transfer. Most operations in TclCurl have default behavior, and you can change that behavior by setting the appropriate options as documented. Each option is specified as the option followed by a parameter.

Notes:

The options set with this procedure apply to subsequent data transfers performed when you invoke perform.

The options are not reset between transfers (except where noted), so if you want subsequent transfers with different options, you must change them between the transfers. You can optionally reset all options back to the internal default with curlHandle reset.

curlHandle is the value returned by the curl::init call.

OPTIONS

BEHAVIOUR OPTIONS

-verbose

Set this option to 1 to make the library display detailed information about its operations. This option is useful when debugging libcurl and protocol-related problems.

You will rarely want to enable this in production, but it is often helpful when debugging or reporting problems. Another useful debugging option is

-debugproc

-header

Set this option to 1 to include headers in the body output. This is relevant only for protocols that actually send headers before the data, such as HTTP.

-noprogress

Set this option to 1 to disable the progress meter completely. It also prevents progressproc from being called.

-nosignal

Set this option to 1 to make TclCurl avoid functions that install signal handlers or cause signals to be sent to the process. This option exists mainly so that multi-threaded Unix applications can still use timeout options without risking signal-related side effects.

If this option is set and libcurl has been built with the standard name resolver, timeouts will not occur while name resolution is in progress. Consider building libcurl with c-ares support to enable asynchronous DNS lookups, which allows proper timeouts for name resolution without signals.

Setting nosignal to 1 makes libcurl stop asking the system to ignore SIGPIPE signals. Such signals may otherwise be sent by the system when data is written to a socket that has been closed by the peer. libcurl tries to avoid triggering SIGPIPE, but some operating systems provide no reliable way to prevent it, and even on those that do, some corner cases remain. In addition, using ntlm_Wb authentication may cause a SIGCHLD signal to be raised.

-wildcard

Set this option to 1 to transfer multiple files that match a file name pattern. The pattern can be specified as part of the -url option, using an fnmatch-like pattern (shell pattern matching) in the last part of the URL, that is, the file name.

By default, TclCurl uses its internal wildcard matching implementation. You can provide your own matching function with the -fnmatchproc option.

At present, this feature is supported only for FTP downloads.

A brief introduction of its syntax follows:

ftp://example.com/some/path/***.txt** (for all .txt files from the root directory) - ? - QUESTION MARK

The question mark matches any single character.

ftp://example.com/some/path/**photo?.jpeg** - [ - BRACKET EXPRESSION

The left bracket opens a bracket expression. The question mark and asterisk have no special meaning in a bracket expression. Each bracket expression ends by the right bracket and matches exactly one character. Some examples follow:

[a-zA-Z0-9] or [f-gF-G] - character interval

[abc] - character enumeration

[^abc] or [!abc] - negation

[[:name:]] class expression. Supported classes are alnum,lower, space, alpha, digit, print, upper, blank, graph, xdigit.

[][-!^] - special case - matches only ‘-’, ‘]’, ‘[‘, ‘!’ or ‘^’. These characters have no special purpose.

[\[\]\\] - escape syntax. Matches ‘[‘, ‘]’ or ‘\‘.

Using the rules above, a file name pattern can be constructed:

ftp://example.com/some/path/**[a-z[:upper:]\\\\].jpeg**

CALLBACK OPTIONS

-writeproc

Sets a Tcl procedure that TclCurl invokes whenever received data is available to be handled. The callback procedure must have a single argument. When the procedure is invoked, that argument refers to the contents of a data buffer managed by libcurl.

NOTE: The amount of data passed on each invocation is not fixed. The callback may be invoked with an empty buffer, or with a buffer containing a large amount of data.

-file

File in which the transferred data will be saved.

-readproc

Sets a Tcl procedure that TclCurl calls whenever it needs to read data to send to the peer. The procedure must take one parameter, which contains the maximum number of bytes to read. It should return the actual number of bytes read, or 0 if you want to stop the transfer.

If you stop the current transfer by returning 0 prematurely, for example after indicating that you would upload N bytes but uploading fewer than N, the server may appear to hang while waiting for the remaining data.

When doing TFTP uploads, you must return exactly the amount of data requested by the callback. Otherwise, the server may treat it as the final packet and end the transfer.

-infile

File from which the data will be transferred.

-progressproc

Name of the Tcl procedure that TclCurl invokes at regular intervals during an operation, roughly once per second or more often, whether or not data is currently being transferred. Unknown or unused argument values passed to the callback are set to zero. For example, if you only download data, the upload size remains 0. The procedure must have the following prototype:

proc ProgressCallback {dltotal dlnow ultotal ulnow}

For this option to work, you must set the -noprogress option to 0. Setting this option to the empty string restores the original progress function.

If you transfer data with the multi interface, this procedure will not be called during periods of idleness unless you call the appropriate procedure that performs transfers.

You can pause and resume a transfer from within this procedure using the pause and resume commands.

-writeheader

Pass the file name to which the header part of the received data will be written. Headers are written to this file one by one, and only complete lines are written. This makes header parsing straightforward.

See also the -headervar option to get the headers into an array.

-debugproc

Name of the procedure that receives the debug data produced by the -verbose option. The callback procedure must have two arguments:

debugProc {infoType data}

The infoType argument identifies the kind of debug information: 0 text, 1 incoming header, 2 outgoing header, 3 incoming data, 4 outgoing data, 5 incoming SSL data, and 6 outgoing SSL data. The data argument contains the corresponding data buffer.

-chunkbgnproc

Name of the procedure that is called before a file is transferred by FTP. The callback procedure must have one argument:

ChunkBgnProc {remains}

The remains argument is the number of files left to be transferred or skipped.

This callback makes sense only when using the -wildcard option.

-chunkbgnvar

Name of the variable in the global scope that will contain the data for the file about to be transferred. If you do not use this option, ::fileData is used.

The available data is: filename, filetype (file, directory, symlink, device block, device char, named pipe, socket, door, or error if it could not be identified), time, perm, uid, gid, size, hardlinks, and flags.

-chunkendproc

Name of the procedure that is called after a file has been transferred or skipped by FTP. The callback procedure takes no arguments:

ChunkEndProc {}

It should return 0 if everything is fine and 1 if an error occurred.

-fnmatchProc

Name of the procedure that is called instead of the internal wildcard matching function. The callback procedure must have two arguments:

FnMatchProc {pattern string}

The pattern argument contains the pattern to be matched. The string argument contains the candidate string. The procedure must return 0 if the string matches the pattern and 1 otherwise.

ERROR OPTIONS

-errorbuffer

Pass the name of a variable in which TclCurl may store human-readable error messages. This can provide more information than the command return code alone.

-stderr

Pass a file name. TclCurl uses this stream instead of stderr when reporting errors.

-failonerror

Set this option to 1 to make the transfer fail if the returned HTTP status code is 400 or greater. By default, TclCurl returns the page normally and does not treat such status codes as transfer errors.

This behavior is not fail-safe, and in some cases non-successful response codes may still pass through, especially when authentication is involved, as with status codes 401 and 407.

Some header data may be transferred before this condition is detected. For example, a 100-continue response may be received for a POST or PUT request before a subsequent 401 or 407 response is returned.

NETWORK OPTIONS

-url

The URL to use for the transfer.

If the URL does not include a protocol part, such as http:// or ftp://, TclCurl attempts to guess the protocol from the host name. If the protocol specified in the URL is not supported, TclCurl returns the unsupported protocol error when you call perform. Use curl::versioninfo for detailed information about the supported protocols.

Starting with version 7.22.0, the fragment part of the URI is no longer sent as part of the path, unlike earlier versions.

NOTE: This is the only option that must be set before perform is called.

-protocols

Pass a lowercase list of protocols to limit which protocols TclCurl may use for the transfer. This allows a TclCurl build that supports a wide range of protocols to be restricted for specific transfers to a subset of them.

Accepted protocols are http, https, ftp, ftps, scp, sftp, telnet, ldap, ldaps, dict, file, tftp, imap, imaps, pop, pop3, smtp, smtps, gopher, and all.

-redirprotocols

Pass a lowercase list of accepted protocols to limit which protocols TclCurl may use when following a redirect with -followlocation enabled. This allows specific transfers to be restricted to a subset of protocols for redirections.

By default, TclCurl allows all protocols except FILE and SCP. This differs from versions before 7.19.4, which would follow redirects to all supported protocols unconditionally.

-proxy

If you need to use an HTTP proxy, set the proxy string with this option. To specify a port number in the string, append :[port] to the end of the host name. The proxy string may be prefixed with [protocol]://, although such a prefix is ignored unless noted otherwise below.

When you configure an HTTP proxy, TclCurl transparently converts operations to HTTP even if you specify an FTP URL or another protocol. This may affect which library features are available. For example, quote and similar FTP-specific features do not work unless you tunnel through the HTTP proxy. Such tunneling is enabled with -proxytunnel.

TclCurl respects the environment variables http_proxy, ftp_proxy, all_proxy, and others of the same kind, if they are set. Using this option overrides any such environment variables.

Setting the proxy string to "" explicitly disables proxy use, even if a corresponding environment variable is set.

The proxy host string can be specified in the same way as the proxy environment variables, including a protocol prefix such as http:// and embedded user name and password information.

Since 7.22.0, the proxy string may include a protocol:// prefix to specify alternative proxy protocols. Use socks4://, socks4a://, socks5://, or socks5h:// to request a specific SOCKS version. The last form enables SOCKS5 and asks the proxy to perform name resolution. If no protocol is specified, and for http:// and all other prefixes, the proxy is treated as an HTTP proxy.

-proxyport

Use this option to set the proxy port unless it is already specified in the proxy string passed with -proxy. If not specified, TclCurl uses port 1080 by default.

-proxytype

Pass the proxy type. Available values are http, http1.0, socks4, socks4a, socks5, and socks5h. The default is http.

If you set it to http1.0, it will only affect how libcurl speaks to a proxy when CONNECT is used. The HTTP version used for ordinary HTTP requests is instead controlled by httpversion.

-noproxy

Pass a string containing a comma-separated list of hosts that should not use a proxy, if one is specified. The only wildcard is a single * character, which matches all hosts and effectively disables the proxy. Each name in this list is matched either as a domain containing the host name, or as the host name itself. For example, local.com matches local.com, local.com:80, and www.local.com, but not www.notlocal.com.

-httpproxytunnel

Set this option to 1 to tunnel all non-HTTP operations through the given HTTP proxy. Using a proxy and tunneling through a proxy are different behaviors. This option should be enabled only when that distinction is required.

-socks5gssapiservice

Pass the service name. The default service name for a SOCKS5 server is rcmd/server-fqdn. This option allows you to change it.

-socks5gssapinec

Pass 1 to enable this option or 0 to disable it. As part of the GSSAPI negotiation, a protection mode is negotiated. RFC 1961 specifies in sections 4.3 and 4.4 that this exchange should be protected, but the NEC reference implementation does not do so. When enabled, this option allows the protection mode negotiation to be exchanged unprotected.

-interface

Pass the interface name to use as the outgoing network interface. The name may be an interface name, an IP address, or a host name.

-localport

Sets the local port number of the socket used for the connection. This can be used together with -interface, and it is recommended to use -localportrange as well when this option is set. Valid port numbers are 1 through 65535.

-localportrange

Number of attempts TclCurl should make to find a working local port number. It starts with the port specified by -localport and increments it by one for each retry. Setting this value to 1 or less makes TclCurl try only one port number. Because port numbers are a limited resource and may already be in use, setting this value too low may cause unnecessary connection setup failures.

-dnscachetimeout

Pass the timeout in seconds. Name resolution results are kept in memory for this number of seconds. Set this option to 0 to disable caching completely, or to -1 to keep cached entries indefinitely. By default, TclCurl caches this information for 60 seconds.

The name resolution functions in various libc implementations do not re-read name server information unless explicitly told to do so, for example by calling res_init(3). As a result, TclCurl may continue to use older server information even after DHCP has updated it, which may appear to be a DNS cache issue.

-dnsuseglobalcache

If this option is set to 1, TclCurl uses a global DNS cache that survives the creation and deletion of curl handles. This is not thread-safe because it relies on a global variable. This option was deprecated in libcurl v7.11.1 and is disabled by default in the TclCurl build. See README.md for instructions on how to re-enable it.

WARNING: This option is obsolete. Use the share interface instead. See tclcurl_share.

-buffersize

Pass the preferred size for the TclCurl receive buffer. A smaller buffer may cause the write callback to be invoked more often with smaller chunks. This value is treated as a request, not as a guarantee.

-port

Pass the remote port number to connect to instead of the port specified in the URL or the default port for the protocol in use.

-tcpnodelay

Pass a number to specify whether the TCP_NODELAY option should be set or cleared (1 = set, 0 = clear). This option is cleared by default. It has no effect after the connection has been established.

Setting this option will disable TCP’s Nagle algorithm. The purpose of this algorithm is to try to minimize the number of small packets on the network (where “small packets” means TCP segments less than the Maximum Segment Size (MSS) for the network).

Maximizing the amount of data sent per TCP segment is good because it amortizes the overhead of the send. However, in some cases (most notably telnet or rlogin) small segments may need to be sent without delay. This is less efficient than sending larger amounts of data at a time, and can contribute to congestion on the network if overdone.

-addressscope

Pass a number specifying the scope_id value to use when connecting to IPv6 link-local or site-local addresses.

NAMES AND PASSWORDS OPTIONS

-netrc

Set this option to make TclCurl scan your ~/.netrc file for the user name and password of the remote site you are about to access. TclCurl does not verify that the file has the correct properties set, as the standard Unix ftp client does. Only machine name, user name, and password are taken into account; init macros and similar entries are not supported.

Accepted values:

optional
Use of ~/.netrc is optional, and information in the URL takes precedence. The file is searched using the host and user name, to find the password only, or using the host name alone, to find the first user name and password for that machine, depending on which information is not specified in the URL.

Undefined values for this option have the same effect.

ignored
TclCurl ignores the file and uses only the information in the URL. This is the default.
required
TclCurl requires use of the file, ignores the information in the URL, and searches the file using the host name only.
-netrcfile

Pass a string containing the full path name of the file to use as the .netrc file. For this option to work, you must set -netrc to required. If this option is omitted and -netrc is set, TclCurl attempts to find a .netrc file in the current user’s home directory.

-userpwd

Pass a string in the form [username]:[password] to use for the connection. Use -httpauth to select the authentication method.

When using NTLM, you can specify a domain by prepending it to the user name and separating the domain and name with a forward slash (/) or backward slash (\\), for example domain/user:password or domain\\user:password. Some HTTP servers on Windows also support this form for Basic authentication.

When using HTTP and -followlocation, TclCurl might perform several requests to possibly different hosts. TclCurl will only send this user and password information to hosts using the initial host name (unless -unrestrictedauth is set), so if TclCurl follows locations to other hosts it will not send the user and password to those. This is enforced to prevent accidental information leakage.

-proxyuserpwd

Pass a string in the form [username]:[password] to use for the connection to the HTTP proxy.

-username

Pass a string containing the user name to use for the transfer. It sets the user name used in protocol authentication. This option should not be used together with the older -userpwd option.

To specify the password to use together with the user name, use the -password option.

-password

Pass a string containing the password to use for the transfer.

This option should be used together with -username.

-proxyusername

Pass a string containing the user name to use for the transfer while connecting to the proxy.

This option is used in the same way as -proxyuserpwd, except that it allows the user name to contain a colon, as in sip:user@example.com.

-proxyusername is an alternative way to set the user name while connecting to the proxy. It should not be used together with -proxyuserpwd.

-proxypassword

Pass a string containing the password to use for the transfer while connecting to the proxy. This option is intended to be used together with -proxyusername.

-httpauth

Set this option to the authentication method to use. Accepted values are:

basic
HTTP Basic authentication. This is the default choice and the only method in widespread use that is supported almost everywhere. It sends the user name and password over the network in plain text.
digest
HTTP Digest authentication. Over public networks, this is generally more secure than Basic authentication.
digestie
HTTP Digest authentication with an Internet Explorer-specific variant. TclCurl uses a compatibility behavior known to have been used by Internet Explorer before version 7 and still required by some servers.
gssnegotiate
HTTP GSS-Negotiate authentication. This method, also known simply as Negotiate, was designed by Microsoft and is used in Microsoft web applications. It is primarily intended to support Kerberos 5 authentication, but it may also be used with other authentication methods.
ntlm
HTTP NTLM authentication. This is a proprietary protocol developed and used by Microsoft. It uses a challenge-response mechanism and hashing, similar to Digest, to avoid sending the password in clear text.
ntlmwb
NTLM delegated to the winbind helper. Authentication is performed by a separate binary application that is executed when needed. The name of that application is specified when libcurl is built, but it is typically /usr/bin/ntlm_auth.

Note that libcurl will fork when necessary to run the winbind application and kill it when complete, calling waitpid() to await its exit when done. On POSIX operating systems, killing the process will cause a SIGCHLD signal to be raised (regardless of whether -nosignal is set). This behavior is subject to change in future versions of libcurl.

any
TclCurl automatically selects the method it considers the most secure.
anysafe
TclCurl may use any method except Basic and automatically selects the one it considers the most secure.
-tlsauthtype

Selects the authentication method to use for TLS authentication.

Accepted values:

tlsauthsrp
Uses TLS-SRP authentication. Secure Remote Password authentication for TLS is defined in RFC 5054 and provides mutual authentication if both sides share a secret. To use this value, you must also set -tlsauthusername and -tlsauthpassword.

libcurl must be built with GnuTLS or with OpenSSL support for TLS-SRP for this to work.

-tlsauthusername

Pass a string containing the user name to use for the TLS authentication method specified with -tlsauthtype. This option requires -tlsauthpassword to be set as well.

-tlsauthpassword

Pass a string containing the password to use for the TLS authentication method specified with -tlsauthtype. This option requires -tlsauthusername to be set as well.

-proxyauth

Use this option to tell TclCurl which authentication method to use for proxy authentication. For some methods, this causes an extra network round trip. Set the actual user name and password with -proxyuserpwd.

The methods are those listed above for the httpauth option. As of this writing, only Basic and NTLM work.

HTTP OPTIONS

-autoreferer

Set this option to 1 to enable automatic updates of the Referer: header when TclCurl follows a Location: redirect.

-encoding

Sets the contents of the Accept-Encoding: header sent in an HTTP request, and enables decoding of a response when a Content-Encoding: header is received.

Accepted values:

identity
Requests no encoding.
deflate
Requests compression using the zlib algorithm.
gzip
Requests gzip compression.
all
Sends an Accept-Encoding: header containing all supported encodings.

This is a request, not a requirement; the server may or may not honor it. This option must be set or any unsolicited encoding used by the server is ignored. See lib/README.encoding in the libcurl documentation for details.

-transferencoding

Adds a request for compressed Transfer-Encoding in the outgoing HTTP request. If the server supports this and chooses to use it, the response may use a compressed Transfer-Encoding, which TclCurl then decompresses automatically when receiving the data.

Transfer-Encoding differs from the Content-Encoding requested with -encoding in that Transfer-Encoding applies strictly to the transfer and therefore must be decoded before the data reaches the client. Traditionally, Transfer-Encoding has been used less widely and is less consistently supported by HTTP clients and servers.

-followlocation

Set this option to 1 to make TclCurl follow any

Location: header

sent by the server as part of an HTTP response.

TclCurl resends the request to the new location and continues to follow further Location: headers until no more are returned. Use -maxredirs to limit the number of redirects TclCurl follows.

Since 7.19.4, TclCurl can also restrict which protocols it follows automatically. The accepted protocols are set with -redirprotocols. By default, the FILE protocol is excluded.

-unrestrictedauth

Set this option to 1 to allow TclCurl to continue sending authentication credentials when following redirects, even if the host name changes. This option is meaningful only when -followlocation is enabled.

-maxredirs

Sets the redirection limit. After that many redirects have been followed, the next redirect causes an error. This option is meaningful only when -followlocation is enabled. Set the limit to 0 to refuse all redirects. Set it to -1 for an unlimited number of redirects, which is the default.

-postredir

Controls how TclCurl acts on redirects after POST requests that receive a 301, 302, or 303 response. Accepted values are 301, 302, 303, and all. The values 301, 302, and 303 make TclCurl preserve the POST request method for the corresponding redirect status code. The value all enables all three behaviors.

The non-RFC behavior is common in web browsers, so TclCurl performs this conversion by default to maintain consistency. However, a server may require a POST to remain a POST after such a redirection.

This option is meaningful only when -followlocation is enabled.

The legacy alias -post301 is accepted for compatibility and uses the same values.

-put

Set this option to 1 to make TclCurl upload a file using HTTP PUT. The file to upload must be specified with -infile and -infilesize.

This option is deprecated as of version 0.12.1. Use -upload.

This option does not limit how much data TclCurl will actually send, as that is controlled entirely by what the read callback returns.

-post

Set this option to 1 to make TclCurl perform a regular HTTP POST request using the application/x-www-form-urlencoded format commonly used by HTML forms. Use -postfields to specify the data to post and -postfieldsize to specify its size.

Use the -postfields option to specify what data to post and -postfieldsize to set the data size. Optionally, you can also provide POST data using -readproc.

You can override the default POST Content-Type: header by setting your own with -httpheader.

Using POST with HTTP 1.1 implies the use of an Expect: 100-continue header. You can disable this header with -httpheader as usual.

If you use POST with an HTTP 1.1 server, you can send data without knowing the size in advance by using chunked encoding. Enable this by adding a header such as Transfer-Encoding: chunked with -httpheader. With HTTP 1.0, or without chunked transfer encoding, you must specify the size in the request.

Setting -post to 1 also sets -nobody to 0.

NOTE: If you have issued a POST request and later want to make a HEAD or GET request instead, you must explicitly select the new request type with -nobody, -httpget, or a similar option.

-postfields

Pass a string containing the complete data to send in an HTTP POST request. You must ensure that the data is formatted exactly as you want the server to receive it. TclCurl does not convert or encode it for you. Most web servers assume this data is URL-encoded.

This is the normal application/x-www-form-urlencoded form, which is the most commonly used one by HTML forms.

If you want to do a zero-byte POST, you need to set -postfieldsize explicitly to zero, because setting -postfields to NULL or "" effectively disables sending the specified string. TclCurl then assumes that the POST data is supplied through the read callback.

Using POST with HTTP 1.1 implies the use of an Expect: 100-continue header. You can disable this header with -httpheader as usual.

NOTE: To make multipart/form-data posts, see -httppost.

-postfieldsize

Use this option to post data without letting TclCurl call strlen() to determine the data size. This is also required if you want to post fully binary data, which would otherwise likely fail. If this size is set to zero, the library uses strlen() to determine the data size.

-httppost

Makes TclCurl perform an HTTP multipart/form-data POST request. The data to send is described through a Tcl list.

This is the only case where the data is reset after a transfer.

Each part consists of at least a NAME and a CONTENTS part. If the part is used for file upload, it may also contain CONTENT-TYPE and FILENAME information.

The list must contain a ‘name’ tag followed by the section name. The section value can then be described with ‘value’, followed by a string containing the data to post, ‘file’, followed by the name of the file to post, or ‘contenttype’, followed by the content type (text/plain, image/jpg, and so on). You can also supply an alternate file name with ‘filename’. This is useful if the server checks whether the provided file name is valid, or if you want to include the full path of the file being posted. You can also post the contents of a variable as if it were a file by using ‘bufferName’ and ‘buffer’, or use ‘filecontent’ followed by a file name to read that file and use its contents as data.

To specify additional headers for a form section, use ‘contentheader’ followed by a list of headers.

See httpPost.tcl and httpBufferPost.tcl for examples.

Return values:

1
If the memory allocation fails.
2
If one option is given twice for one form.
3
If an empty string was given.
4
If an unknown option was used.
5
If some form information is incomplete or invalid.
6
If an illegal option is used in an array.
7
If TclCurl has no HTTP support.
-referer

Pass a string to set the Referer: header in the HTTP request sent to the remote server.

The Referer: header identifies the resource from which the target URI was obtained. Servers may use it for logging, analytics, backlink generation, caching decisions, or request-flow checks.

This option is useful when a scripted client must reproduce the request context normally sent by a web browser, or when a server expects a specific referring URI.

The header value should normally be a URI identifying the referring resource. Fragments and userinfo components are not part of a valid Referer: field value.

The field name Referer is a historical misspelling of referrer, but the misspelled form is the standardized HTTP header name.

Because this header may reveal navigation context or sensitive URI data, it should be set with care. It should not be relied upon as a secure means of authentication or access control.

You can also set this header through -httpheader.

-useragent

Pass a string to set the User-Agent: header in the HTTP request sent to the remote server. You can also set custom headers with -httpheader.

-httpheader

Pass a list of HTTP headers to send in the request. If you add a header that TclCurl would otherwise generate internally, your header is used instead. If you add a header with no value, such as Accept:, the internal header is disabled. This option can therefore be used to add, replace, or remove internal headers.

This option is useful when the request must include headers not exposed by dedicated TclCurl options, or when you need exact control over the final HTTP request. Common uses include setting custom authentication-related headers, API-specific headers, cache-control directives, or overriding headers such as Content-Type: or Accept:.

The headers in the list must not be CRLF-terminated, because TclCurl adds CRLF after each header item. If you include CRLF yourself, the server will likely ignore part of the headers you specified.

The first line of a request, containing the method, usually GET or POST, is not a header and cannot be replaced with this option. Only the lines following the request line are headers. Adding the method line to this list causes an invalid header to be sent.

NOTE: The most commonly replaced headers have dedicated shortcut options: -cookie, -useragent, and -referer.

-http200aliases

Pass a list of aliases to be treated as valid HTTP 200 responses. Some servers return a custom response line. For example, IceCast servers may return ICY 200 OK. If you include such a string in the list, it is treated as a valid HTTP status line such as HTTP/1.0 200 OK.

NOTE: The alias itself is not parsed for a version string. Before version 7.16.3, TclCurl used the value set by -httpversion, but since 7.16.3 the protocol is assumed to match HTTP 1.0 when an alias matches.

-cookie

Pass a string to set a cookie in the HTTP request. The string should use the format [NAME]=[CONTENTS];, where NAME is the cookie name and CONTENTS is the cookie value.

If you need to set multiple cookies, you must set them all in a single option value by concatenating them into one string, for example name1=content1; name2=content2;.

This option sets the cookie header explicitly in the outgoing request(s). If multiple requests are performed because of authentication, redirects, or similar causes, they all receive this cookie header.

If this option is used multiple times, only the last value is kept.

-cookiefile

Pass the name of a file containing cookie data. The cookie data may be in Netscape cookie file format or in regular HTTP-style headers written to a file.

If the file is empty or does not exist, this option still enables cookies for the handle, causing TclCurl to parse received cookies and use matching cookies in later requests.

If you use this option multiple times, each use adds another file to read.

-cookiejar

Pass a file name to which TclCurl writes all internally known cookies when curlHandle cleanup is called. If no cookies are known, no file is created. Specify - to write the cookies to standard output.

Using this option also enables cookies for the session, so matching cookies are sent on later requests, including those caused by redirects.

TclCurl cannot report an error if writing the cookie jar fails. If -verbose is enabled, a warning is displayed, but that is the only visible feedback in this case.

-cookiesession

Set this option to 1 to mark the current run as a new cookie session. This makes TclCurl ignore session cookies loaded from a previous session. By default, TclCurl stores and loads all cookies, including session cookies. Session cookies are cookies without an expiry date and are meant to exist only for the current session.

-cookielist

Pass a string containing a cookie. The cookie may be in Netscape/Mozilla format or in regular HTTP-style header form, such as Set-Cookie: .... If the cookie engine is not enabled, it is enabled automatically.

Special values are ALL, which erases all known cookies, and FLUSH, which writes all known cookies to the file specified by -cookiejar.

-httpget

Set this option to 1 to force the HTTP request method back to GET. This is useful if POST, PUT, or a custom request has previously been used with the same handle.

Setting -httpget to 1 also sets -nobody to 0.

-httpversion

Selects the HTTP version to use. This option should be used only when it is necessary to override the default behavior because of server-side requirements.

Accepted values:

none
Lets TclCurl use the HTTP version it considers appropriate.
1.0
Enforce HTTP 1.0 requests.
1.1
Enforce HTTP 1.1 requests.
2.0
Enforce HTTP version 2 requests.
2TLS
Enforce version 2 requests for HTTPS, version 1.1 for HTTP.
2_PRIOR_KNOWLEDGE
Enforce HTTP 2 requests without performing an HTTP/1.1 Upgrade first.
-ignorecontentlength

Ignores the Content-Length header. This is useful for Apache 1.x and similar servers, which may report an incorrect content length for files larger than 2 gigabytes. If this option is used, TclCurl cannot report progress accurately and stops the download only when the server closes the connection.

-httpcontentdecoding

Set this option to 0 to disable content decoding, or to 1 to enable it. TclCurl does not enable content decoding by default; for that, you must also use -encoding.

-httptransferencoding

Set this option to 0 to disable transfer decoding, or to 1 to enable it. The default is 1. TclCurl performs chunked transfer decoding by default unless this option is disabled.

SMTP OPTIONS

-mailfrom

Pass a string specifying the sender address to use in the SMTP envelope.

This option controls the envelope sender used at the SMTP protocol level. It does not set or modify the From: header field in the message body.

-mailrcpt

Pass a list of recipient addresses to use in the SMTP envelope.

This option controls the envelope recipients used at the SMTP protocol level. It does not set or modify message header fields such as To:, Cc:, or Bcc:.

In SMTP, recipients are specified with angle brackets (<>). If a recipient value does not begin with an angle bracket, TclCurl assumes that it is a plain email address and adds the angle brackets automatically.

TFTP OPTION

-tftpblksize

Specifies the block size to use for TFTP data transmission. According to RFC 2348, valid values range from 8 to 65464 bytes. If this option is not specified, the default block size is 512 bytes.

The requested block size is used only if the remote server supports it. If the server does not return an option acknowledgment, or if it returns an acknowledgment without a block size value, the default of 512 bytes is used.

FTP OPTIONS

-ftpport

Pass a string identifying the address to use for the FTP PORT instruction. The PORT instruction tells the remote server to connect to the specified client address. The string may be a plain IP address, a host name, a network interface name on Unix, or simply - to let the library use the system’s default IP address. By default, FTP transfers are passive, so PORT is not used.

The address can be followed by : and a port number, optionally followed by - and a port range. If the port specified is 0, the operating system chooses a free port. If a range is provided and no port in that range is available, libcurl reports CURLE_FTP_PORT_FAILED for the handle. Invalid port or port-range settings are ignored. IPv6 addresses followed by a port or port range must be enclosed in brackets. IPv6 addresses without a port or port range may also be enclosed in brackets.

Examples:

eth0:0 192.168.1.2:32000-33000 curl.se:32123 [::1]:1234-4567

To disable PORT and return to passive mode, set this option to the empty string.

-quote

Pass a list of FTP or SFTP commands to send to the server before the FTP transfer request. These commands are sent before any other FTP commands, including CWD. If you do not want to transfer any files, set -nobody to 1 and -header to 0.

Prefix a command with an asterisk (*) to make TclCurl continue even if that command fails. By default, a failure stops the transfer.

To disable this option, set it to the empty string.

The commands must be raw FTP commands. For example, to create a directory you must send mkd Test, not mkdir Test.

Valid SFTP commands are chgrp, chmod, chown, ln, mkdir, pwd, rename, rm, rmdir, and symlink.

-postquote

Pass a list of FTP commands to send to the server after the FTP transfer request. If you do not want to transfer any files, set -nobody to 1 and -header to 0.

-prequote

Pass a list of FTP or SFTP commands to send to the server after the transfer type has been set.

-dirlistonly

Set this option to 1 to list only file names in a directory instead of requesting a full directory listing with file sizes, dates, and similar information. This option works with both FTP and SFTP URLs.

For FTP, this causes an NLST command to be sent. Some FTP servers return only files in response to NLST, and may omit subdirectories and symbolic links.

Setting this option to 1 also implies a directory listing even if the URL does not end with a slash, which would otherwise be required.

Do not use this option together with -wildcardmatch, as it effectively disables that feature.

-append

Set this option to 1 to append to the remote file instead of overwriting it. This is useful only when uploading to an FTP site.

-ftpuseeprt

Set this option to 1 to make TclCurl use the EPRT and LPRT commands for active FTP transfers, which are enabled with -ftpport. When this option is enabled, TclCurl first attempts EPRT, then LPRT, and only then falls back to PORT. If this option is set to 0, only PORT is used.

-ftpuseepsv

Set this option to 1 to make TclCurl use the EPSV command for passive FTP transfers. This is the default behavior. When enabled, TclCurl first attempts EPSV before using PASV. If this option is set to 0, TclCurl uses only PASV.

-ftpusepret

Set this option to 1 to make TclCurl send a PRET command before PASV or EPSV. Some FTP servers, especially drftpd, require this non-standard command for directory listings and uploads or downloads in passive mode. This option has no effect for active FTP transfers.

-ftpcreatemissingdirs

Controls whether TclCurl should attempt to create a remote directory when the transfer requires that directory to exist, but a CWD command shows that it does not yet exist or cannot yet be entered.

This setting also applies to SFTP connections. TclCurl attempts to create the remote directory if it cannot obtain a handle to the target location. Creation fails if a file with the same name already exists, or if permissions do not allow directory creation.

Accepted values:

1
After a failed CWD, TclCurl attempts to create the missing remote directory and then continues with the transfer.
2
After a failed CWD, TclCurl attempts to create the missing remote directory. If the subsequent MKD command fails, TclCurl retries the CWD command before giving up. This is useful when multiple simultaneous connections target the same server and another connection may have created the directory in the meantime.
-ftpresponsetimeout

Sets a timeout, in seconds, for how long the server may take to return a response to an FTP command before the session is considered hung. While TclCurl is waiting for such a response, this value overrides -timeout. If both options are used, -ftpresponsetimeout should normally be set to a value smaller than -timeout.

-ftpalternativetouser

Pass a string to use for authentication if the usual FTP USER user and PASS password negotiation fails. This is known to be required in some cases when connecting to Tumbleweed Secure Transport FTPS servers that use client-certificate authentication.

-ftpskippasvip

Set this option to 1 to make TclCurl ignore the IP address suggested by the server in its 227 response to TclCurl’s PASV command when opening the data connection. TclCurl instead reuses the same IP address already in use for the control connection, while still using the port number from the 227 response.

This option has no effect if PORT, EPRT, or EPSV is used instead of PASV.

-ftpsslauth

Selects how TclCurl issues AUTH TLS or AUTH SSL when FTP over SSL is enabled with -ftpssl.

This option may be needed for servers such as BSDFTPD-SSL, which do not handle AUTH SSL correctly and require AUTH TLS instead.

Accepted values:

default
Lets TclCurl choose.
ssl
Tries AUTH SSL first, and tries AUTH TLS only if that fails.
tls
Tries AUTH TLS first, and tries AUTH SSL only if that fails.
-ftpsslccc

Controls use of CCC (Clear Command Channel). CCC shuts down the SSL/TLS layer after authentication, so the remainder of the control channel is unencrypted. This can allow NAT routers to inspect the FTP control channel.

Accepted values are:

none
Do not attempt to use CCC.
passive
Do not initiate the shutdown. Wait for the server to do so, and do not send a reply.
active
Initiate the shutdown and wait for a reply.
-ftpaccount

Pass a string containing account data, or "" to disable it. If an FTP server requests account data after the user name and password have been provided, TclCurl sends this value with the ACCT command.

-ftpfilemethod

Selects how TclCurl navigates FTP paths. Accepted values are:

multicwd
The default. TclCurl performs one CWD operation for each path component in the URL. For deep hierarchies this may require many commands. This is the method described by RFC 1738.
nocwd
TclCurl does not perform CWD at all. Instead it sends commands such as SIZE, RETR, and STOR with the full path.
singlecwd
TclCurl performs one CWD to the full target directory and then operates on the file normally. This is somewhat more standards compliant than nocwd, without the full overhead of multicwd.

PROTOCOL OPTIONS

-transfertext

Set this option to 1 to use ASCII mode for FTP transfers instead of the default binary transfer mode. On Win32 systems, this does not set stdout to binary mode. This option can be useful when transferring text data between systems that treat characters such as newlines differently.

NOTE: TclCurl does not perform full ASCII conversion during ASCII FTP transfers. It simply sets the transfer mode to ASCII and performs a normal transfer.

-proxytransfermode

Set this option to 1 to make TclCurl set the transfer mode, binary or ASCII, for FTP transfers performed through an HTTP proxy by appending ;type=a or ;type=i to the URL. If this option is omitted or set to 0, -transfertext has no effect for FTP transfers performed through an HTTP proxy. Not all proxies support this feature.

-crlf

Set this option to 1 to make TclCurl convert Unix newlines to CRLF newlines during transfers. Set it to 0 to disable this behavior.

-range

Pass a string specifying the requested range. The format is X-Y, where either X or Y may be omitted. HTTP transfers also support multiple ranges separated by commas, as in X-Y,N-M. When multiple ranges are requested over HTTP, the server returns the response document in pieces using standard MIME separation rules.

Range requests are supported only for HTTP, FTP, and FILE transfers.

-resumefrom

Pass the offset, in bytes, at which the transfer should start. Set this option to 0 to start the transfer from the beginning, which disables resume behavior.

For FTP, set this option to -1 to start from the end of the target file, which is useful when continuing an interrupted upload.

For FTP uploads, the resume position specifies where in the local source file TclCurl should resume reading. The data read from that point is then appended to the remote target file.

-customrequest

Pass a string containing the request method to use instead of the default method, such as GET or HEAD, when making an HTTP request. This is useful for methods such as DELETE and other less common HTTP requests. Use this option only when the server is known to support the specified method.

TclCurl still behaves internally according to the type of request it would otherwise have used. As a result, changing the request method with this option can produce inconsistent behavior if the corresponding request type is not selected through the usual dedicated option. For example, to make a proper HEAD request, use -nobody. To make a proper POST request, use -post or -postfields.

-filetime

Set this option to 1 to make TclCurl attempt to obtain the modification time of the remote document during the transfer. This requires the remote server either to send the time directly or to support a command for querying it. After the transfer, the filetime value can be retrieved with the getinfo procedure.

For FTP transfers, this typically means that the server must support a command for querying the remote file modification time, such as MDTM. If the server does not provide this information, the transfer can still succeed, but the retrieved filetime value remains unknown.

-nobody

Set this option to 1 to omit the body from the output. This is relevant only for protocols that distinguish between a header part and a body part. For HTTP and HTTPS, this causes TclCurl to issue a HEAD request.

To change the request back to GET, use -httpget. To switch to POST, use -post or a related option.

-infilesize

Use this option when uploading a file to specify the expected size of the input file.

This option is mandatory for uploads performed with SCP.

-upload

Set this option to 1 to prepare for an upload. The -infile and -infilesize options are also relevant for uploads. If the protocol is HTTP, uploading means using the PUT request unless you tell TclCurl otherwise.

Using PUT with HTTP 1.1 implies the use of a “Expect: 100-continue” header. You can disable this header with -httpheader as usual.

If you use PUT to a HTTP 1.1 server, you can upload data without knowing the size before starting the transfer if you use chunked encoding. You enable this by adding a header like “Transfer-Encoding: chunked” with -httpheader. With HTTP 1.0 or without chunked transfer, you must specify the size.

-maxfilesize

This allows you to specify the maximum size (in bytes) of a file to download. If the file requested is larger than this value, the transfer will not start and error ‘filesize exceeded’ (63) will be returned.

NOTE: The file size is not always known prior to download, and for such files this option has no effect even if the file transfer ends up being larger than this given limit. This concerns both FTP and HTTP transfers.

-timecondition

Defines how the timevalue value is treated. Accepted values are ifmodsince and ifunmodsince. This feature applies to HTTP, FTP, and FILE.

-timevalue

This should be the time in seconds since 1 jan 1970, and the time will be used in a condition as specified with timecondition.

CONNECTION OPTIONS

-timeout

Pass the maximum time, in seconds, that a TclCurl transfer operation may take. Name resolution alone may take a noticeable amount of time, so setting this value too low can abort otherwise normal operations.

This option may cause libcurl to use SIGALRM to interrupt blocking system calls. On Unix-like systems, signals may therefore be used unless -nosignal is enabled.

-timeoutms

Like -timeout, but takes a value in milliseconds. If libcurl is built to use the standard system name resolver, name resolution still uses full-second timeout granularity.

-lowspeedlimit

Pass the speed, in bytes per second, below which the transfer rate must remain during -lowspeedtime seconds before TclCurl considers the transfer too slow and aborts it.

-lowspeedtime

Pass the number of seconds during which the transfer speed must stay below -lowspeedlimit before TclCurl considers the transfer too slow and aborts it.

-maxsendspeed

Pass a speed in bytes per second. If an upload exceeds this average speed during the transfer, TclCurl pauses the transfer as needed to keep the average rate less than or equal to the specified value. The default is unlimited speed.

-maxrecvspeed

Pass a speed in bytes per second. If a download exceeds this average speed during the transfer, TclCurl pauses the transfer as needed to keep the average rate less than or equal to the specified value. The default is unlimited speed.

-maxconnects

Sets the size of the persistent connection cache for protocols that support persistent connections. This value is the maximum number of simultaneous connections TclCurl may cache in the easy handle. The default is 5.

When the maximum is reached, TclCurl closes the oldest cached connection to prevent the number of open connections from increasing further.

NOTE: If transfers have already been performed with this easy handle, reducing -maxconnects may cause existing open connections to be closed earlier than expected.

If this easy handle is added to a multi handle, this setting is ignored. In that case, configure the corresponding maxconnects option on the multi handle instead.

-connecttimeout

Pass the maximum time, in seconds, that the connection phase may take. This limits only the time required to establish the connection. Once the connection has been established, this option no longer applies. Set it to 0 to disable the connection timeout.

On Unix-like systems, signals may be used unless -nosignal is enabled.

-connecttimeoutms

Like -connecttimeout, but takes a value in milliseconds. If libcurl is built to use the standard system name resolver, name resolution still uses full-second timeout granularity.

-ipresolve

Selects which IP address families may be used when resolving host names. This option is relevant only when a host name resolves to more than one IP version.

Accepted values are:

whatever
The default. Resolves addresses using all IP versions supported by the system.
v4
Resolves only IPv4 addresses.
v6
Resolves only IPv6 addresses.
-resolve

Pass a list of host name resolution entries to use for requests made with this handle.

Each entry must use the format HOST:PORT:ADDRESS, where HOST is the name TclCurl tries to resolve, PORT is the destination service port, and ADDRESS is the numeric IP address to use. If libcurl supports IPv6, ADDRESS may be either an IPv4 or an IPv6 address.

This option effectively pre-populates the DNS cache with entries for a given HOST:PORT pair, so redirects and other requests to the same HOST:PORT use the supplied ADDRESS.

To remove an entry from the DNS cache, include a string in the form -HOST:PORT. The host name must be prefixed with a dash, and both the host name and port must exactly match an entry added earlier.

-usessl

Selects the desired level of SSL or TLS use for the transfer. This option is relevant for protocols such as FTP, SMTP, POP3, and IMAP.

You can also use ftps:// URLs to enable SSL/TLS explicitly for both the control connection and the data connection.

Accepted values:

nope
Do not attempt to use SSL.
try
Attempt to use SSL, but continue even if it cannot be negotiated.
control
Use SSL for the control connection, or fail with use ssl failed (64).
all
Use SSL for all communication, or fail with use ssl failed (64).

SSL AND SECURITY OPTIONS

-sslcert

Pass a string containing the file name of the certificate to use. The default format is PEM, and it can be changed with -sslcerttype.

When libcurl is built against NSS, this value is the nickname of the certificate to use for authentication. To use a file in the current directory in that case, prefix it with ./ to avoid confusion with a nickname.

-sslcerttype

Pass a string specifying the format of the certificate given with -sslcert.

Accepted values are:

PEM
PEM format.
DER
DER format.
-sslkey

Pass a string containing the file name of the private key to use. The default format is PEM, and it can be changed with -sslkeytype.

-sslkeytype

Pass a string specifying the format of the private key given with -sslkey.

Accepted values are:

PEM
PEM format.
DER
DER format.
ENG
Uses a crypto engine. In this case -sslkey is interpreted as an identifier passed to the engine, and -sslengine must also be set.

NOTE: The DER private-key format may not work with some OpenSSL versions because of upstream limitations.

-keypasswd

Pass a string containing the passphrase required to use the private key specified with -sslkey or -sshprivatekeyfile.

A passphrase is not needed to load a certificate itself, but it may be needed to load the corresponding private key.

This option was formerly known as -sslkeypasswd and -sslcertpasswd.

-sslengine

Pass a string containing the identifier of the crypto engine to use for private-key operations.

NOTE: If the crypto engine cannot be loaded, TclCurl returns an error.

-sslenginedefault

Set this option to 1 to make the selected crypto engine the default for asymmetric cryptographic operations.

NOTE: If the crypto engine cannot be made the default, TclCurl returns an error.

-sslversion

Selects the SSL or TLS protocol version to use.

Accepted values are:

default
Uses the default behavior. TclCurl attempts to negotiate an appropriate protocol version with the remote server.
tlsv1
Requires TLSv1 or later.
sslv2
Requires SSLv2.
sslv3
Requires SSLv3.
tlsv1_0
Requires TLSv1.0 or later.
tlsv1_1
Requires TLSv1.1 or later.
tlsv1_2
Requires TLSv1.2 or later.
tlsv1_3
Requires TLSv1.3 or later.
maxdefault
Uses the maximum TLS version supported by libcurl or by the SSL backend’s default configuration.
maxtlsv1_0
Sets the maximum supported TLS version to TLSv1.0.
maxtlsv1_1
Sets the maximum supported TLS version to TLSv1.1.
maxtlsv1_2
Sets the maximum supported TLS version to TLSv1.2.
maxtlsv1_3
Sets the maximum supported TLS version to TLSv1.3.
-sslverifypeer

Controls whether TclCurl verifies the authenticity of the peer certificate. Set this option to 1 to enable verification or to 0 to disable it. The default is 1.

During the SSL or TLS handshake, the server sends a certificate declaring its identity. TclCurl verifies that certificate against a chain of trust rooted in one or more certification authority (CA) certificates.

TclCurl uses the default CA bundle provided by libcurl, but you can specify alternate certificates with -cainfo or -capath.

If -sslverifypeer is nonzero and verification fails, the connection fails. If this option is 0, peer-certificate verification is skipped.

Certificate verification alone does not confirm that the peer is the specific host you intended to contact. Use -sslverifyhost to control host-name verification.

-cainfo

Pass the name of a file containing one or more CA certificates used to verify the peer certificate.

This option is meaningful primarily together with -sslverifypeer. If peer verification is disabled, -cainfo does not need to name an accessible file.

By default, this option is set to the system path of libcurl’s CA bundle, as determined when libcurl was built.

When libcurl is built against NSS, this value refers to the directory containing the NSS certificate database.

-issuercert

Pass the name of a file containing a CA certificate in PEM format. If this option is set, an additional check is performed to verify that the peer certificate was issued by the CA certificate provided here.

This is useful in multi-level PKI environments where the peer certificate must be constrained to a specific branch of the certificate hierarchy.

This option is meaningful only when used together with -sslverifypeer. Otherwise, failure of this additional check is not treated as a connection failure.

-capath

Pass the name of a directory containing multiple CA certificates to use when verifying the peer certificate.

When libcurl is built against OpenSSL, this directory must be prepared with the openssl c_rehash utility. This option is meaningful primarily together with -sslverifypeer. If peer verification is disabled, -capath does not need to name an accessible directory.

This option is OpenSSL-specific and has no effect when libcurl is built against GnuTLS. NSS-based libcurl provides it only for backward compatibility.

On Windows, this option may not work because of OpenSSL limitations.

-crlfile

Pass the name of a file containing one or more certificate revocation lists in PEM format to use during certificate validation.

When libcurl is built against NSS or GnuTLS, there is no supported way to influence revocation checking with this option. When libcurl is built with OpenSSL support, both X509_V_FLAG_CRL_CHECK and X509_V_FLAG_CRL_CHECK_ALL are enabled if a CRL file is provided, so CRL checking is applied throughout the certificate chain.

This option is meaningful only when used together with -sslverifypeer.

If the CRL file cannot be loaded, the SSL exchange fails with the specific error code CURLE_SSL_CRL_BADFILE. A certificate-verification failure caused by revocation information in the CRL does not produce that specific error code.

-sslverifyhost

Controls whether TclCurl verifies that the server certificate matches the host name you intended to contact.

During the SSL or TLS handshake, the server sends a certificate declaring its identity.

When -sslverifyhost is set to 2, the certificate must identify the intended server or the connection fails. TclCurl considers the server to match when the Common Name field or a Subject Alternative Name field in the certificate matches the host name in the URL.

When this option is set to 1, the certificate must contain a Common Name field, but the specific name is not checked. This setting is generally not useful.

When this option is set to 0, the connection succeeds regardless of the names contained in the certificate.

The default value is 2.

This option verifies the host identity claimed by the certificate. To verify that the certificate itself is trusted, use -sslverifypeer. If libcurl is built against NSS and -sslverifypeer is 0, -sslverifyhost is ignored.

-certinfo

Set this option to 1 to enable collection of certificate-chain information. When enabled, TclCurl, if built against OpenSSL, extracts certificate details from the chain used in the SSL connection.

That information can be retrieved after the transfer with the getinfo command and its certinfo option.

-randomfile

Pass a file name. TclCurl uses this file as a source of randomness for the SSL random engine. This option was deprecated in libcurl v7.84 and is disabled by default in the TclCurl build. See README.md for instructions on how to re-enable it.

-egdsocket

Pass the path name of an Entropy Gathering Daemon socket. TclCurl uses it as a source of randomness for the SSL random engine. This option was deprecated in libcurl v7.84 and is disabled by default in the TclCurl build. See README.md for instructions on how to re-enable it.

-sslcipherlist

Pass a string containing the cipher list to use for the SSL or TLS connection. The list consists of one or more cipher strings separated normally by colons, although commas or spaces are also accepted. The characters !, -, and + may also be used as operators.

With OpenSSL and GnuTLS, valid examples include RC4-SHA, SHA1+DES, TLSv1, and DEFAULT. The default list is usually defined by the SSL backend at build time.

With NSS, valid examples include rsa_rc4_128_md5 and rsa_aes_128_sha. NSS does not support incremental add or remove semantics for ciphers. If this option is used, all known ciphers are disabled and only the ciphers listed here are enabled.

For details about cipher-list syntax, see: http://www.openssl.org/docs/apps/ciphers.html

For NSS-specific cipher-list details, see: http://directory.fedora.redhat.com/docs/mod_nss.html

-sslsessionidcache

Set this option to 0 to disable TclCurl’s use of SSL session-ID caching, or to 1 to enable it. The default is 1.

In normal circumstances, reusing SSL session IDs is harmless and may improve performance. However, some broken SSL implementations may require this option to be disabled.

-krblevel

Selects the Kerberos security level for FTP and thereby also enables Kerberos awareness.

Accepted values are clear, safe, confidential, and private. If the string does not match one of these values, private is used.

Set the string to NULL to disable Kerberos 4. Set it to "" to disable Kerberos support for FTP.

-gssapidelegation

Selects the GSSAPI credential delegation mode.

Accepted values are:

flag
Allows unconditional delegation.
policyflag
Delegates only if the OK-AS-DELEGATE flag is set in the service ticket, provided that this feature is supported by the GSSAPI implementation and that GSS_C_DELEG_POLICY_FLAG was available at compile time.

Delegation is disabled by default since 7.21.7.

SSH OPTIONS

-sshauthtypes

Selects the allowed SSH authentication types.

Accepted values are:

publickey
Use public-key authentication.
password
Use password authentication.
host
Use host-based authentication.
keyboard
Use keyboard-interactive authentication.
any
Let TclCurl select an authentication method automatically.
-sshhostpublickeymd5

Pass a string containing 32 hexadecimal digits. The string must be the 128-bit MD5 checksum of the remote host public key. TclCurl rejects the connection unless the checksum matches.

This option applies only to SCP and SFTP transfers.

-sshpublickeyfile

Pass the file name of the public key to use.

If this option is not used, TclCurl defaults to $HOME/.ssh/id_dsa.pub when the HOME environment variable is set, and to id_dsa.pub in the current directory otherwise.

-sshprivatekeyfile

Pass the file name of the private key to use.

If this option is not used, TclCurl defaults to $HOME/.ssh/id_dsa when the HOME environment variable is set, and to id_dsa in the current directory otherwise.

If the private key is passphrase-protected, use -keypasswd to specify the passphrase.

-sshknownhosts

Pass a string containing the file name of the known_hosts file to use. The file must use the OpenSSH known_hosts format supported by libssh2.

If this option is set, TclCurl accepts connections only to hosts that are present in that file with a matching public key. Use -sshkeyproc to override the default behavior for host and key matching.

-sshkeyproc

Pass the name of a callback procedure that TclCurl invokes after known_hosts matching has been performed, so that the application can decide how the connection should proceed.

The callback is invoked only if -sshknownhosts is also set.

The callback receives a list with three elements:

  1. A list containing the key type from the known_hosts file and the key itself.
  2. A list containing the key type presented by the remote host and the key itself.
  3. A value describing TclCurl’s matching result.

Possible key-type values are rsa, rsa1, dss, and unknown.

Possible match-result values are match, mismatch, missing, and error.

Return values:

0
Accept the host and key. TclCurl appends the host and key to the known_hosts file before continuing with the connection. If the host and key are not already present in the in-memory known-hosts pool, TclCurl also adds them there. Updating the file is done by replacing it with a new copy, so the file permissions must allow that.
1
Accept the host and key, and continue with the connection. If the host and key are not already present in the in-memory known-hosts pool, TclCurl also adds them there.
2
Reject the host and key. TclCurl closes the connection.
3
Reject the host and key, but keep the SSH connection alive. This can be useful if the application needs to inspect the host or key state and then retry without incurring the full setup cost again.

Any other return value causes TclCurl to close the connection.

OTHER OPTIONS

-headervar

Name of the Tcl array variable in which TclCurl stores the headers returned by the server.

-bodyvar

Name of the Tcl variable in which TclCurl stores the requested file contents. The stored data may be either text or binary data.

-canceltransvarname

Name of a Tcl variable used together with -progressproc. If the progress callback sets this variable to 1, the transfer is canceled.

-command

Executes the given command after the transfer has completed.

This option works only with blocking transfers and therefore has limited practical use.

-share

Pass a share handle. The share handle must have been created previously by calling curl::shareinit.

Setting this option causes the easy handle to use data from the shared handle instead of keeping its own separate copy. See tclcurl_share for details.

-newfileperms

Pass a numeric value specifying the permissions assigned to newly created files on the remote server. The default value is 0644, but any valid value may be used.

This option applies only to sftp://, scp://, and file:// transfers.

-newdirectoryperms

Pass a numeric value specifying the permissions assigned to newly created directories on the remote server. The default value is 0755, but any valid value may be used.

This option applies only to sftp://, scp://, and file:// transfers.

TELNET OPTIONS

-telnetoptions
Pass a list with variables to pass to the telnet negotiations. The variables should be in the format . TclCurl supports the options ‘TTYPE’, ‘XDISPLOC’ and ‘NEW_ENV’. See the TELNET standard for details.

NOT SUPPORTED

Some of the options libcurl offers are not supported, I don’t think them worth supporting in TclCurl but if you need one of them don’t forget to complain:

CURLOPTFRESHCONNECT, CURLOPTFORBIDREUSE, CURLOPT_PRIVATE,

CURLOPTSSLCTXFUNCTION, CURLOPTSSLCTXDATA, CURLOPTSSLCTX_FUNCTION and

CURLOPTCONNECTONLY, CURLOPTOPENSOCKETFUNCTION, CURLOPTOPENSOCKETDATA.

curlHandle perform

This procedure is called after the

init

and all the

configure

calls are made, and will perform the transfer as described in the options.

It must be called with the same curlHandle curl::init call returned. You can do any amount of calls to perform while using the same handle. If you intend to transfer more than one file, you are even encouraged to do so. TclCurl will then attempt to re-use the same connection for the following transfers, thus making the operations faster, less CPU intense and using less network resources. Just note that you will have to use configure between the invokes to set options for the following perform.

You must never call this procedure simultaneously from two places using the same handle. Let it return first before invoking it another time. If you want parallel transfers, you must use several curl handles.

RETURN VALUE

0 if all went well, non-zero if it didn’t. In case of error, if the errorbuffer was set with configure there will be a readable error message. The error codes are:

1
Unsupported protocol. This build of TclCurl has no support for this protocol.
2
Very early initialization code failed. This is likely to be and internal error or a resource problem where something fundamental couldn’t get done at init time.
3
URL malformat. The syntax was not correct.
4
A requested feature, protocol or option was not found built-in in this libcurl due to a build-time decision. This means that a feature or option was not enabled or explicitly disabled when libcurl was built and in order to get it to function you have to get a rebuilt libcurl.
5
Couldn’t resolve proxy. The given proxy host could not be resolved.
6
Couldn’t resolve host. The given remote host was not resolved.
7
Failed to connect to host or proxy.
8
FTP weird server reply. The server sent data TclCurl couldn’t parse. The given remote server is probably not an OK FTP server.
9
We were denied access to the resource given in the URL. For FTP, this occurs while trying to change to the remote directory.
11
FTP weird PASS reply. TclCurl couldn’t parse the reply sent to the PASS request.
13
FTP weird PASV reply, TclCurl couldn’t parse the reply sent to the PASV or EPSV request.
14
FTP weird 227 format. TclCurl couldn’t parse the 227-line the server sent.
15
FTP can’t get host. Couldn’t resolve the host IP we got in the 227-line.
17
FTP couldn’t set type. Couldn’t change transfer method to either binary or ascii.
18
Partial file. Only a part of the file was transferred, this happens when the server first reports an expected transfer size and then delivers data that doesn’t match the given size.
19
FTP couldn’t RETR file, we either got a weird reply to a ‘RETR’ command or a zero byte transfer.
21
Quote error. A custom ‘QUOTE’ returned error code 400 or higher (for FTP) or otherwise indicated unsuccessful completion of the command.
22
HTTP returned error. This return code only appears if -failonerror is used and the HTTP server returns an error code that is 400 or higher.
23
Write error. TclCurl couldn’t write data to a local filesystem or an error was returned from a write callback.
25
Failed upload failed. For FTP, the server typcially denied the STOR command. The error buffer usually contains the server’s explanation to this.
26
Read error. There was a problem reading from a local file or an error was returned from the read callback.
27
Out of memory. A memory allocation request failed. This should never happen unless something weird is going on in your computer.
28
Operation timeout. The specified time-out period was reached according to the conditions.
30
The FTP PORT command failed, not all FTP servers support the PORT command, try doing a transfer using PASV instead!.
31
FTP couldn’t use REST. This command is used for resumed FTP transfers.
33
Range error. The server doesn’t support or accept range requests.
34
HTTP post error. Internal post-request generation error.
35
SSL connect error. The SSL handshaking failed, the error buffer may have a clue to the reason, could be certificates, passwords, …
36
The download could not be resumed because the specified offset was out of the file boundary.
37
A file given with FILE:// couldn’t be read. Did you checked the permissions?
38
LDAP cannot bind. LDAP bind operation failed.
39
LDAP search failed.
41
A required zlib function was not found.
42
Aborted by callback. An application told TclCurl to abort the operation.
43
Internal error. A function was called with a bad parameter.
45
Interface error. A specified outgoing interface could not be used.
47
Too many redirects. When following redirects, TclCurl hit the maximum amount, set your limit with –maxredirs
48
An option passed to TclCurl is not recognized/known. Refer to the appropriate documentation. This is most likely a problem in the program that uses TclCurl. The error buffer might contain more specific information about which exact option it concerns.
49
A telnet option string was illegally formatted.
51
The remote peer’s SSL certificate or SSH md5 fingerprint wasn’t ok
52
The server didn’t reply anything, which here is considered an error.
53
The specified crypto engine wasn’t found.
54
Failed setting the selected SSL crypto engine as default!
55
Failed sending network data.
56
Failure with receiving network data.
58
Problem with the local client certificate.
59
Couldn’t use specified SSL cipher.
60
Peer certificate cannot be authenticated with known CA certificates.
61
Unrecognized transfer encoding.
62
Invalid LDAP URL.
63
Maximum file size exceeded.
64
SSL use failed.
65
Sending the data requires a rewind that failed, since TclCurl should take care of it for you, it means you found a bug.
66
Failed to initialise ssl engine.
67
Failed to login, user password or similar was not accepted.
68
File not found on TFTP server.
69
There is a permission problem with the TFTP request.
70
The remote server has run out of space.
71
Illegal TFTP operation.
72
Unknown transfer ID.
73
TFTP file already exists and will not be overwritten.
74
No such user in the TFTP server and good behaving TFTP servers should never return this.
75
Character conversion failed.
77
Problem with reading the SSL CA cert (path? access rights?).
78
Remote file not found
79
Error from the SSH layer
80
Failed to shut down the SSL connection
82
Failed to load CRL file
83
Issuer check failed
84
The FTP server does not understand the PRET command at all or does not support the given argument. Be careful when using -customrequest, a custom LIST command will be sent with PRET CMD before PASV as well.
85
Mismatch of RTSP CSeq numbers.
86
Mismatch of RTSP Session Identifiers.
87
Unable to parse FTP file list (during FTP wildcard downloading).
88
Chunk callback reported error.

curlHandle getinfo OPTION

Request internal information from the curl session with this procedure. This procedure is intended to get used AFTER a performed transfer, and can be relied upon only if the perform returns 0. Use this function AFTER a performed transfer if you want to get transfer-oriented data.

The following information can be extracted:

effectiveurl

Returns the last used effective URL.

responsecode

Returns the last received HTTP or FTP code. This will be zero if no server response code has been received. Note that a proxy’s CONNECT response should be read with httpconnectcode and not this.

httpconnectcode

Returns the last received proxy response code to a CONNECT request.

filetime

Returns the remote time of the retrieved document (in number of seconds since 1 jan 1970 in the GMT/UTC time zone). If you get -1, it can be because of many reasons (unknown, the server hides it or the server doesn’t support the command that tells document time etc) and the time of the document is unknown.

In order for this to work you have to set the -filetime option before the transfer.

namelookuptime

Returns the time, in seconds, it took from the start until the name resolving was completed.

connecttime

Returns the time, in seconds, it took from the start until the connect to the remote host (or proxy) was completed.

appconnecttime

Returns the time, in seconds, it took from the start until the SSL/SSH connect/handshake to the remote host was completed. This time is most often very near to the PRETRANSFER time, except for cases such as HTTP pippelining where the pretransfer time can be delayed due to waits in line for the pipeline and more.

pretransfertime

Returns the time, in seconds, it took from the start until the file transfer is just about to begin. This includes all pre-transfer commands and negotiations that are specific to the particular protocol(s) involved.

starttransfertime

Returns the time, in seconds, it took from the start until the first byte is just about to be transferred. This includes the pretransfertime, and also the time the server needs to calculate the result.

totaltime

Returns the total transaction time, in seconds, for the previous transfer, including name resolving, TCP connect etc.

redirecturl

Returns the URL a redirect would take you to if you enable followlocation. This can come very handy if you think using the built-in libcurl redirect logic isn’t good enough for you but you would still prefer to avoid implementing all the magic of figuring out the new URL.

redirecttime

Returns the total time, in seconds, it took for all redirection steps including name lookup, connect, pretransfer and transfer before the final transaction was started, it returns the complete execution time for multiple redirections, so it returns zero if no redirections were needed.

redirectcount

Returns the total number of redirections that were actually followed.

numconnects

Returns how many new connections TclCurl had to create to achieve the previous transfer (only the successful connects are counted). Combined with redirectcount you are able to know how many times TclCurl successfully reused existing connection(s) or not. See the Connection Options of setopt to see how TclCurl tries to make persistent connections to save time.

primaryip

Returns the IP address of the most recent connection done with this handle. This string may be IPv6 if that’s enabled.

primaryport

Returns the destination port of the most recent connection done with this handle.

localip

Returns the local (source) IP address of the most recent connection done with this handle. This string may be IPv6 if that’s enabled.

localport

Returns the local (source) port of the most recent connection done with this handle.

sizeupload

Returns the total amount of bytes that were uploaded.

sizedownload

Returns the total amount of bytes that were downloaded. The amount is only for the latest transfer and will be reset again for each new transfer.

speeddownload

Returns the average download speed, measured in bytes/second, for the complete download.

speedupload

Returns the average upload speed, measured in bytes/second, for the complete upload.

headersize

Returns the total size in bytes of all the headers received.

requestsize

Returns the total size of the issued requests. This is so far only for HTTP requests. Note that this may be more than one request if followLocation is true.

sslverifyresult

Returns the result of the certification verification that was requested (using the -sslverifypeer option to configure).

sslengines

Returns a list of the OpenSSL crypto-engines supported. Note that engines are normally implemented in separate dynamic libraries. Hence not all the returned engines may be available at run-time.

contentlengthdownload

Returns the content-length of the download. This is the value read from the Content-Length: field. If the size isn’t known, it returns -1.

contentlengthupload

Returns the specified size of the upload.

contenttype

Returns the content-type of the downloaded object. This is the value read from the Content-Type: field. If you get an empty string, it means the server didn’t send a valid Content-Type header or that the protocol used doesn’t support this.

httpauthavail

Returns a list with the authentication method(s) available.

proxyauthavail

Returns a list with the authentication method(s) available for your proxy athentication.

oserrno

Returns the errno value from a connect failure. This value is only set on failure, it is no reset after a successful operation.

cookielist

Returns a list of all cookies TclCurl knows (expired ones, too). If there are no cookies (cookies for the handle have not been enabled or simply none have been received) the list will be empty.

ftpentrypath

Returns a string holding the path of the entry path. That is the initial path TclCurl ended up in when logging on to the remote FTP server. Returns an empty string if something is wrong.

certinfo

Returns list with information about the certificate chain, assuming you had the -certinfo option enabled when the previous request was done. The list first item reports how many certs it found and then you can extract info for each of those certs by following the list. The info chain is provided in a series of data in the format “name:content” where the content is for the specific named data.

NOTE: this option is only available in libcurl built with OpenSSL support.

conditionunmet

Returns the number 1 if the condition provided in the previous request didn’t match (see timecondition), you will get a zero if the condition instead was met.

curlHandle cleanup

This procedure must be the last one to call for a curl session. It is the opposite of the curl::init procedure and must be called with the same curlhandle as input as the curl::init call returned. This will effectively close all connections TclCurl has used and possibly has kept open until now. Don’t call this procedure if you intend to transfer more files.

curlHandle reset

Re-initializes all options previously set on a specified handle to the default values.

This puts back the handle to the same state as it was in when it was just created with curl::init.

It does not change the following information kept in the handle: live connections, the Session ID cache, the DNS cache, the cookies and shares.

curlHandle duphandle

This procedure will return a new curl handle, a duplicate, using all the options previously set in the input curl handle. Both handles can subsequently be used independently and they must both be freed with cleanup.

The new handle will not inherit any state information, connections, SSL sessions or cookies.

RETURN VALUE
A new curl handle or an error message if the copy fails.

curlHandle pause

You can use this command from within a progress callback procedure to pause the transfer.

curlHandle resume

Resumes a transfer paused with curlhandle pause

curl::transfer

In case you do not want to use persistent connections you can use this command, it takes the same arguments as the curlHandle configure and will init, configure, perform and cleanup a connection for you.

You can also get the getinfo information by using -infooption variable pairs, after the transfer variable will contain the value that would have been returned by $curlHandle getinfo option.

RETURN VALUE
The same error code perform would return.

curl::version

Returns a string with the version number of tclcurl, libcurl and some of its important components (like OpenSSL version).

RETURN VALUE
The string with the version info.

curl::escape URL

This procedure will convert the given input string to an URL encoded string and return that. All input characters that are not a-z, A-Z or 0-9 will be converted to their “URL escaped” version (%NN where NN is a two-digit hexadecimal number)

RETURN VALUE
The converted string.

curl::unescape URL

This procedure will convert the given URL encoded input string to a “plain string” and return that. All input characters that are URL encoded (%XX where XX is a two-digit hexadecimal number) will be converted to their plain text versions.

RETURN VALUE
The string unencoded.

curl::curlConfig OPTION

Returns some information about how you have cURL installed.

-prefix
Returns the directory root where you installed cURL.
-feature
Returns a list containing particular main features the installed libcurl was built with. The list may include SSL, KRB4 or IPv6, do not assume any particular order.
-vernum
Outputs version information about the installed libcurl, in numerical mode. This outputs the version number, in hexadecimal, with 8 bits for each part; major, minor, patch. So that libcurl 7.7.4 would appear as 070704 and libcurl 12.13.14 would appear as 0c0d0e…

curl::versioninfo OPTION

Returns information about various run-time features in TclCurl.

Applications should use this information to judge if things are possible to do or not, instead of using compile-time checks, as dynamic/DLL libraries can be changed independent of applications.

-version

Returns the version of libcurl we are using.

-versionnum

Returns the version of libcurl we are using in hexadecimal with 8 bits for each part; major, minor, patch. So that libcurl 7.7.4 would appear as 070704 and libcurl 12.13.14 would appear as 0c0d0e… Note that the initial zero might be omitted.

-host

Returns a string with the host information as discovered by a configure script or set by the build environment.

-features

Returns a list with the features compiled into libcurl, the possible elements are:

ASYNCHDNS

Libcurl was built with support for asynchronous name lookups, which allows more exact timeouts (even on Windows) and less blocking when using the multi interface.

CONV

Libcurl was built with support for character conversions.

DEBUG

Libcurl was built with extra debug capabilities built-in. This is mainly of interest for libcurl hackers.

GSSNEGOTIATE

Supports HTTP GSS-Negotiate.

IDN

Supports IDNA, domain names with international letters.

IPV6

Supports IPv6.

KERBEROS4

Supports kerberos4 (when using FTP).

LARGEFILE

Libcurl was built with support for large files.

LIBZ

Supports HTTP deflate using libz.

NTML

Supports HTTP NTLM

SPNEGO

Libcurl was built with support for SPNEGO authentication (Simple and Protected GSS-API Negotiation Mechanism, defined in RFC 2478)

SSL

Supports SSL (HTTPS/FTPS)

SSPI

Libcurl was built with support for SSPI. This is only available on Windows and makes libcurl use Windows-provided functions for NTLM authentication. It also allows libcurl to use the current user and the current user’s password without the app having to pass them on.

TLSAUTH_SRP

Libcurl was built with support for TLS-SRP.

NTLM_WB

Libcurl was built with support for NTLM delegation to a winbind helper.

Do not assume any particular order.

-sslversion

Returns a string with the OpenSSL version used, like OpenSSL/0.9.6b.

-sslversionnum

Returns the numerical OpenSSL version value as defined by the OpenSSL project. If libcurl has no SSL support, this is 0.

-libzversion

Returns a string, there is no numerical version, for example: 1.1.3.

-protocols

Lists what particular protocols the installed TclCurl was built to support. At the time of writing, this list may include HTTP, HTTPS, FTP, FTPS, FILE, TELNET, LDAP, DICT. Do not assume any particular order. The protocols will be listed using uppercase. There may be none, one or several protocols in the list.

curl::easystrerror errorCode

This procedure returns a string describing the error code passed in the argument.

EXAMPLES

The examples in this section assume you are running from the root of the TclCurl source tree.

To start the local HTTP test server used in the examples, run:

tclsh testservers/testserver.tcl

By default, this starts an HTTP server on http://127.0.0.1:8990/.

The path http://127.0.0.1:8990/tclcurl-man returns the HTML version of this manual page from doc/tclcurl.html, which makes it a convenient target for a basic GET example.

BASIC HTTP GET

The file examples/http_get.tcl contains a minimal HTTP GET example. It performs a simple request, stores the response body in a Tcl variable, and prints both the HTTP response code and the size of the returned document.

If the request succeeds, rc is 0, responsecode is 200, and body contains the HTML document returned by the server.

AUTHORS

Andres Garcia Garcia

Massimo Manghi

SEE ALSO

curl, The art of HTTP scripting (at http://curl.haxx.se), RFC 2396,