Skip to content
Tcl Source Code Artifact [8c2c899817]
Login

Artifact [8c2c899817]

Artifact 8c2c89981775e26ded0418d4cb9d75c5b7378b981313a26d733a35569dedd0c8:



CommandName: http ManualSection: n Version: 2.10 TclPart: http TclDescription: Tcl Bundled Packages Links:

Name

http - Client-side implementation of the HTTP/1.1 protocol

Synopsis

::: {.synopsis} ::: [package]{.cmd} [require]{.sub} [http]{.lit} [2.10]{.optlit}

[::http::config]{.cmd} [-option value]{.optdot} [::http::geturl]{.cmd} [url]{.arg} [-option value]{.optdot} [::http::formatQuery]{.cmd} [key]{.arg} [value]{.arg} [key value]{.optdot} [::http::quoteString]{.cmd} [value]{.arg} [::http::reset]{.cmd} [token]{.arg} [why]{.optarg} [::http::wait]{.cmd} [token]{.arg} [::http::status]{.cmd} [token]{.arg} [::http::size]{.cmd} [token]{.arg} [::http::error]{.cmd} [token]{.arg} [::http::postError]{.cmd} [token]{.arg} [::http::cleanup]{.cmd} [token]{.arg} [::http::requestLine]{.cmd} [token]{.arg} [::http::requestHeaders]{.cmd} [token]{.arg} [headerName]{.optarg} [::http::requestHeaderValue]{.cmd} [token]{.arg} [headerName]{.arg} [::http::responseLine]{.cmd} [token]{.arg} [::http::responseCode]{.cmd} [token]{.arg} [::http::reasonPhrase]{.cmd} [code]{.arg} [::http::responseHeaders]{.cmd} [token]{.arg} [headerName]{.optarg} [::http::responseHeaderValue]{.cmd} [token]{.arg} [headerName]{.arg} [::http::responseInfo]{.cmd} [token]{.arg} [::http::responseBody]{.cmd} [token]{.arg} [::http::register]{.cmd} [proto]{.arg} [port]{.arg} [command]{.arg} [socketCmdVarName]{.optarg} [useSockThread]{.optarg} [endToEndProxy]{.optarg} [::http::registerError]{.cmd} [sock]{.arg} [message]{.optarg} [::http::unregister]{.cmd} [proto]{.arg} [::http::code]{.cmd} [token]{.arg} [::http::data]{.cmd} [token]{.arg} [::http::meta]{.cmd} [token]{.arg} [headerName]{.optarg} [::http::metaValue]{.cmd} [token]{.arg} [headerName]{.arg} [::http::ncode]{.cmd} [token]{.arg} :::

Exported commands

Namespace fBhttpfR exports the commands fBconfigfR, fBformatQueryfR, fBgeturlfR, fBpostErrorfR, fBquoteStringfR, fBreasonPhrasefR, fBregisterfR, fBregisterErrorfR, fBrequestHeadersfR, fBrequestHeaderValuefR, fBrequestLinefR, fBresponseBodyfR, fBresponseCodefR, fBresponseHeadersfR, fBresponseHeaderValuefR, fBresponseInfofR, fBresponseLinefR, fBresetfR, fBunregisterfR, and fBwaitfR.

It does not export the commands fBcleanupfR, fBcodefR, fBdatafR, fBerrorfR, fBmetafR, fBmetaValuefR, fBncodefR, fBsizefR, or fBstatusfR.

Description

The fBhttpfR package provides the client side of the HTTP/1.1 protocol, as defined in RFC 9110 to 9112, which supersede RFC 7230 to RFC 7235, which in turn supersede RFC 2616. The package implements the GET, POST, and HEAD operations of HTTP/1.1. It allows configuration of a proxy host to get through firewalls. The package is compatible with the fBSafesockfR security policy, so it can be used by untrusted applets to do URL fetching from a restricted set of hosts. This package can be extended to support additional HTTP transport protocols, such as HTTPS, by providing a custom fBsocketfR command, via fB::http::registerfR.

The fB::http::geturlfR procedure does a HTTP transaction. Its fIoptionsfR determine whether a GET, POST, or HEAD transaction is performed. The return value of fB::http::geturlfR is a token for the transaction. The token can be supplied as an argument to other commands, to manage the transaction and examine its results.

If the fB-commandfR option is specified, then the HTTP operation is done in the background. fB::http::geturlfR returns immediately after generating the HTTP request and the fB-commandfR callback is invoked when the transaction completes. For this to work, the Tcl event loop must be active. In Tk applications this is always true. For pure-Tcl applications, the caller can use fB::http::waitfR after calling fB::http::geturlfR to start the event loop.

Note: The event queue is even used without the fB-commandfR option. As a side effect, arbitrary commands may be processed while fBhttp::geturlfR is running.

When the HTTP server has replied to the request, call the command fB::http::responseInfofR, which returns a fBdictfR of metadata that is essential for identifying a successful transaction and making use of the response. See section fBMETADATAfR for details of the information returned. The response itself is returned by command fB::http::responseBodyfR, unless it has been redirected to a file by the fI-channelfR option of fB::http::geturlfR.

Commands

::http::config ?fIoptionsfR? : The fB::http::configfR command is used to set and query the name of the proxy server and port, and the User-Agent name used in the HTTP requests. If no options are specified, then the current configuration is returned. If a single argument is specified, then it should be one of the flags described below. In this case the current value of that setting is returned. Otherwise, the options should be a set of flags and values that define the configuration:

-accept fImimetypesfR : The Accept header of the request. The default is /, which means that all types of documents are accepted. Otherwise you can supply a comma-separated list of mime type patterns that you are willing to receive. For example, "image/gif, image/jpeg, text/*".

-cookiejar fIcommandfR : The cookie store for the package to use to manage HTTP cookies. fIcommandfR is a command prefix list; if the empty list (the default value) is used, no cookies will be sent by requests or stored from responses. The command indicated by fIcommandfR, if supplied, must obey the fBCOOKIE JAR PROTOCOLfR described below.

-pipeline fIbooleanfR : Specifies whether HTTP/1.1 transactions on a persistent socket will be pipelined. See the fBPERSISTENT SOCKETSfR section for details. The default is 1.

-postfresh fIbooleanfR : Specifies whether requests that use the fBPOSTfR method will always use a fresh socket, overriding the fB-keepalivefR option of command fBhttp::geturlfR. See the fBPERSISTENT SOCKETSfR section for details. The default is 0.

-proxyauth fIstringfR : If non-empty, the string is supplied to the proxy server as the value of the request header Proxy-Authorization. This option can be used for HTTP Basic Authentication. If the proxy server requires authentication by another technique, e.g. Digest Authentication, the fB-proxyauthfR option is not useful. In that case the caller must expect a 407 response from the proxy, compute the authentication value to be supplied, and use the fB-headersfR option to supply it as the value of the Proxy-Authorization header.

-proxyfilter fIcommandfR : The command is a callback that is made during fB::http::geturlfR to determine if a proxy is required for a given host. One argument, a host name, is added to fIcommandfR when it is invoked. If a proxy is required, the callback should return a two-element list containing the proxy server and proxy port. Otherwise the filter command should return an empty list.

The default value of \fB-proxyfilter\fR is \fBhttp::ProxyRequired\fR, and this command returns the values of the \fB-proxyhost\fR and \fB-proxyport\fR settings if they are non-empty.  The options \fB-proxyhost\fR, \fB-proxyport\fR, and \fB-proxynot\fR are used only by \fBhttp::ProxyRequired\fR, and nowhere else in \fB::http::geturl\fR. A user-supplied \fB-proxyfilter\fR command may use these options, or alternatively it may obtain values from elsewhere in the calling script. In the latter case, any values provided for \fB-proxyhost\fR, \fB-proxyport\fR, and \fB-proxynot\fR are unused.
The \fB::http::geturl\fR command runs the \fB-proxyfilter\fR callback inside a \fBcatch\fR command.  Therefore an error in the callback command does not call the \fBbgerror\fR handler.  See the \fBERRORS\fR section for details.

-proxyhost fIhostnamefR : The host name or IP address of the proxy server, if any. If this value is the empty string, the URL host is contacted directly. See fB-proxyfilterfR for how the value is used.

-proxynot fIlistfR : A Tcl list of domain names and IP addresses that should be accessed directly, not through the proxy server. The target hostname is compared with each list element using a case-insensitive fBstring matchfR. It is often convenient to use the wildcard "" at the start of a domain name (e.g. *.example.com) or at the end of an IP address (e.g. 192.168.0.). See fB-proxyfilterfR for how the value is used.

-proxyport fInumberfR : The port number of the proxy server. See fB-proxyfilterfR for how the value is used.

-repost fIbooleanfR : Specifies what to do if a POST request over a persistent connection fails because the server has half-closed the connection. If boolean fBtruefR, the request will be automatically retried; if boolean fBfalsefR it will not, and the application that uses fBhttp::geturlfR is expected to seek user confirmation before retrying the POST. The value fBtruefR should be used only under certain conditions. See the fBPERSISTENT SOCKETSfR section for details. The default is 0.

-threadlevel fIlevelfR : Specifies whether and how to use the fBThreadfR package. Possible values of fIlevelfR are 0, 1 or 2.

0 : (the default) do not use Thread

1 : use Thread if it is available, do not use it if it is unavailable

2 : use Thread if it is available, raise an error if it is unavailable

The Tcl \fBsocket -async\fR command can block in adverse cases (e.g. a slow DNS lookup).  Using the Thread package works around this problem, for both HTTP and HTTPS transactions.  Values of \fIlevel\fR other than 0 are available only to the main interpreter in each thread.  See section \fBTHREADS\fR for more information.

-urlencoding fIencodingfR : The fIencodingfR used for creating the x-url-encoded URLs with fB::http::formatQueryfR and fB::http::quoteStringfR. The default is fButf-8fR, as specified by RFC 2718.

-useragent fIstringfR : The value of the User-Agent header in the HTTP request. In an unsafe interpreter, the default value depends upon the operating system, and the version numbers of fBhttpfR and fBTclfR, and is (for example) "Mozilla/5.0 (Windows; U; Windows NT 10.0) http/2.10.0 Tcl/9.0.0". A safe interpreter cannot determine its operating system, and so the default in a safe interpreter is to use a Windows 10 value with the current version numbers of fBhttpfR and fBTclfR.

-zip fIbooleanfR : If the value is boolean fBtruefR, then by default requests will send a header "Accept-Encoding: gzip,deflate". If the value is boolean fBfalsefR, then by default requests will send a header "Accept-Encoding: identity". In either case the default can be overridden for an individual request by supplying a custom fBAccept-EncodingfR header in the fB-headersfR option of fBhttp::geturlfR. The default value is 1.

::http::geturl fIurlfR ?fIoptionsfR? : The fB::http::geturlfR command is the main procedure in the package. The fB-queryfR or fB-querychannelfR option causes a POST operation and the fB-validatefR option causes a HEAD operation; otherwise, a GET operation is performed. The fB::http::geturlfR command returns a fItokenfR value that can be passed as an argument to other commands to get information about the transaction. See the fBMETADATAfR and fBERRORSfR section for details. The fB::http::geturlfR command blocks until the operation completes, unless the fB-commandfR option specifies a callback that is invoked when the HTTP transaction completes. fB::http::geturlfR takes several options:

-binary fIbooleanfR : Specifies whether to force interpreting the URL data as binary. Normally this is auto-detected (anything not beginning with a fBtextfR content type or whose content encoding is fBgzipfR or fBdeflatefR is considered binary data).

-blocksize fIsizefR : The block size used when reading the URL. At most fIsizefR bytes are read at once. After each block, a call to the fB-progressfR callback is made (if that option is specified).

-channel fInamefR : Copy the URL contents to channel fInamefR instead of saving it in a Tcl variable for retrieval by fB::http::responseBodyfR.

-command fIcallbackfR : The presence of this option causes fB::http::geturlfR to return immediately. After the HTTP transaction completes, the value of fIcallbackfR is expanded, an additional argument is added, and the resulting command is evaluated. The additional argument is the fItokenfR returned from fB::http::geturlfR. This token is the name of an array that is described in the fBSTATE ARRAYfR section. Here is a template for the callback:

```
proc httpCallback {token} {
    upvar 0 $token state
    # Access state as a Tcl array defined in this proc
    ...
    return
}
```
The \fB::http::geturl\fR command runs the \fB-command\fR callback inside a \fBcatch\fR command.  Therefore an error in the callback command does not call the \fBbgerror\fR handler.  See the \fBERRORS\fR section for details.

-guesstype fIbooleanfR : Attempt to guess the fBContent-TypefR and character set when a misconfigured server provides no information. The default value is fIfalsefR (do nothing). If boolean fItruefR then, if the server does not send a fBContent-TypefR header, or if it sends the value "application/octet-stream", fBhttp::geturlfR will attempt to guess appropriate values. This is not intended to become a general-purpose tool, and currently it is limited to detecting XML documents that begin with an XML declaration. In this case the fBContent-TypefR is changed to "application/xml", the binary flag state(binary) is changed to 0, and the character set is changed to the one specified by the "encoding" tag of the XML line, or to utf-8 if no encoding is specified. Not used if a fB-channelfR is specified.

-handler fIcallbackfR : If this option is absent, fBhttp::geturlfR processes incoming data itself, either appending it to the state(body) variable or writing it to the -channel. But if the fB-handlerfR option is present, fBhttp::geturlfR does not do this processing and instead calls fIcallbackfR. Whenever HTTP data is available, the value of fIcallbackfR is expanded, an additional two arguments are added, and the resulting command is evaluated. The two additional arguments are: the socket for the HTTP data and the fItokenfR returned from fB::http::geturlfR. The token is the name of a global array that is described in the fBSTATE ARRAYfR section. The procedure is expected to return the number of bytes read from the socket. Here is a template for the callback:

```
proc httpHandlerCallback {socket token} {
    upvar 0 $token state
    # Access socket, and state as a Tcl array defined in this proc
    # For example...
    ...
    set data [read $socket 1000]
    set nbytes [string length $data]
    ...
    return $nbytes
}
```
The \fBhttp::geturl\fR code for the \fB-handler\fR option is not compatible with either compression or chunked transfer-encoding.  If \fB-handler\fR is specified, then to work around these issues \fBhttp::geturl\fR will reduce the HTTP protocol to 1.0, and override the \fB-zip\fR option (i.e. it will send the header \fBAccept-Encoding: identity\fR instead of \fBAccept-Encoding: gzip,deflate\fR).
If options \fB-handler\fR and \fB-channel\fR are used together, the handler is responsible for copying the data from the HTTP socket to the specified channel.  The name of the channel is available to the handler as element \fB-channel\fR of the token array.
The \fB::http::geturl\fR command runs the \fB-handler\fR callback inside a \fBcatch\fR command.  Therefore an error in the callback command does not call the \fBbgerror\fR handler.  See the \fBERRORS\fR section for details.

-headers fIkeyvaluelistfR : This option is used to add headers not already specified by fB::http::configfR to the HTTP request. The fIkeyvaluelistfR argument must be a list with an even number of elements that alternate between keys and values. The keys become header field names. Newlines are stripped from the values so the header cannot be corrupted. For example, if fIkeyvaluelistfR is fBPragma no-cachefR then the following header is included in the HTTP request:

```
Pragma: no-cache
```

-keepalive fIbooleanfR : If boolean fBtruefR, attempt to keep the connection open for servicing multiple requests. Default is 0.

-method fItypefR : Force the HTTP request method to fItypefR. fB::http::geturlfR will auto-select GET, POST or HEAD based on other options, but this option overrides that selection and enables choices like PUT and DELETE for WebDAV support. It is the caller's responsibility to ensure that the headers and request body (if any) conform to the requirements of the request method. For example, if using fB-methodfR fIPOSTfR to send a POST with an empty request body, the caller must also supply the option

```
\-headers {Content-Length 0}
```

-myaddr fIaddressfR : Pass an specific local address to the underlying fBsocketfR call in case multiple interfaces are available.

-progress fIcallbackfR : If the fB-progressfR option is present, then the fIcallbackfR is made after each transfer of data from the URL. The value of fIcallbackfR is expanded, an additional three arguments are added, and the resulting command is evaluated. The three additional arguments are: the fItokenfR returned from fB::http::geturlfR, the expected total size of the contents from the fBContent-LengthfR response header, and the current number of bytes transferred so far. The token is the name of a global array that is described in the fBSTATE ARRAYfR section. The expected total size may be unknown, in which case zero is passed to the callback. Here is a template for the progress callback:

```
proc httpProgress {token total current} {
    upvar 0 $token state
    # Access state as a Tcl array defined in this proc
    ...
    return
}
```

-protocol fIversionfR : Select the HTTP protocol version to use. This should be 1.0 or 1.1 (the default). Should only be necessary for servers that do not understand or otherwise complain about HTTP/1.1.

-query fIqueryfR : This flag (if the value is non-empty) causes fB::http::geturlfR to do a POST request that passes the string fIqueryfR verbatim to the server as the request payload. The content format (and encoding) of fIqueryfR is announced by the request header fBContent-TypefR which is set by the option fB-typefR. Any value of fB-typefR is permitted, and it is the responsibility of the caller to supply fIqueryfR in the correct format. If fB-typefR is not specified, it defaults to fIapplication/x-www-form-urlencodedfR, which requires fIqueryfR to be an x-url-encoding formatted query-string (this fB-typefR and query format are used in a POST submitted from an html form). The fB::http::formatQueryfR procedure can be used to do the formatting.

-queryblocksize fIsizefR : The block size used when posting query data to the URL. At most fIsizefR bytes are written at once. After each block, a call to the fB-queryprogressfR callback is made (if that option is specified).

-querychannel fIchannelIDfR : This flag causes fB::http::geturlfR to do a POST request that passes the data contained in fIchannelIDfR to the server. The data contained in fIchannelIDfR must be an x-url-encoding formatted query unless the fB-typefR option below is used. If a fBContent-LengthfR header is not specified via the fB-headersfR options, fB::http::geturlfR attempts to determine the size of the post data in order to create that header. If it is unable to determine the size, it returns an error.

-queryprogress fIcallbackfR : If the fB-queryprogressfR option is present, then the fIcallbackfR is made after each transfer of data to the URL in a POST request (i.e. a call to fB::http::geturlfR with option fB-queryfR or fB-querychannelfR) and acts exactly like the fB-progressfR option (the callback format is the same).

-strict fIbooleanfR : If true then the command will test that the URL complies with RFC 3986, i.e. that it has no characters that should be "x-url-encoded" (e.g. a space should be encoded to "%20"). Default value is 1.

-timeout fImillisecondsfR : If fImillisecondsfR is non-zero, then fB::http::geturlfR sets up a timeout to occur after the specified number of milliseconds. A timeout results in a call to fB::http::resetfR and to the fB-commandfR callback, if specified. The return value of fB::http::statusfR (and the value of the fIstatusfR key in the dictionary returned by fB::http::responseInfofR) is fBtimeoutfR after a timeout has occurred.

-type fImime-typefR : Use fImime-typefR as the fBContent-TypefR value, instead of the default value (fBapplication/x-www-form-urlencodedfR) during a POST operation.

-validate fIbooleanfR : If fIbooleanfR is non-zero, then fB::http::geturlfR does an HTTP HEAD request. This server returns the same status line and response headers as it would for a HTTP GET request, but omits the response entity (the URL "contents"). The response headers are available after the transaction using command fB::http::responseHeadersfR or, for selected information, fB::http::responseInfofR.

::http::formatQuery fIkey valuefR ?fIkey valuefR ...? : This procedure does x-url-encoding of query data. It takes an even number of arguments that are the keys and values of the query. It encodes the keys and values, and generates one string that has the proper & and = separators. The result is suitable for the fB-queryfR value passed to fB::http::geturlfR.

::http::quoteString fIvaluefR : This procedure does x-url-encoding of string. It takes a single argument and encodes it.

::http::reset fItokenfR ?fIwhyfR? : This command resets the HTTP transaction identified by fItokenfR, if any. This sets the fBstate(status)fR value to fIwhyfR, which defaults to fBresetfR, and then calls the registered fB-commandfR callback.

::http::wait fItokenfR : This command blocks and waits for the transaction to complete. This only works in trusted code because it uses fBvwaitfR. Also, it is not useful for the case where fB::http::geturlfR is called fIwithoutfR the fB-commandfR option because in this case the fB::http::geturlfR call does not return until the HTTP transaction is complete, and thus there is nothing to wait for.

::http::status fItokenfR : This command returns a description of the status of the HTTP transaction. The return value is the empty string until the HTTP transaction is completed; after completion it has one of the values ok, eof, error, timeout, and reset. The meaning of these values is described in the section fBERRORSfR (below).

The name "status" is not related to the terms "status line" and "status code" that are defined for a HTTP response.

::http::size fItokenfR : This command returns the number of bytes received so far from the URL in the fB::http::geturlfR call.

::http::error fItokenfR : This command returns the error information if the HTTP transaction failed, or the empty string if there was no error. The information is a Tcl list of the error message, stack trace, and error code.

::http::postError fItokenfR : A POST request is a call to fB::http::geturlfR with either the fB-queryfR or fB-querychannelfR option. The fB::http::postErrorfR command returns the error information generated when a HTTP POST request sends its request-body to the server; or the empty string if there was no error. The information is a Tcl list of the error message, stack trace, and error code. When this type of error occurs, the fB::http::geturlfR command continues the transaction and attempts to receive a response from the server.

::http::cleanup fItokenfR : This procedure cleans up the state associated with the connection identified by fItokenfR. After this call, the procedures like fB::http::responseBodyfR cannot be used to get information about the operation. It is fIstronglyfR recommended that you call this function after you are done with a given HTTP request. Not doing so will result in memory not being freed, and if your app calls fB::http::geturlfR enough times, the memory leak could cause a performance hit...or worse.

::http::requestLine fItokenfR : This command returns the "request line" sent to the server. The "request line" is the first line of a HTTP client request, and has three elements separated by spaces: the HTTP method, the URL relative to the server, and the HTTP version. Examples:

GET / HTTP/1.1 GET /introduction.html?subject=plumbing HTTP/1.1 POST /forms/order.html HTTP/1.1

::http::requestHeaders fItokenfR ?fIheaderNamefR? : This command returns the HTTP request header names and values, in the order that they were sent to the server, as a Tcl list of the form ?name value ...? Header names are case-insensitive and are converted to lower case. The return value is not a fBdictfR because some header names may occur more than once. If one argument is supplied, all request headers are returned. If two arguments are supplied, the second provides the value of a header name. Only headers with the requested name (converted to lower case) are returned. If no such headers are found, an empty list is returned.

::http::requestHeaderValue fItoken headerNamefR : This command returns the value of the HTTP request header named fIheaderNamefR. Header names are case-insensitive and are converted to lower case. If no such header exists, the return value is the empty string. If there are multiple headers named fIheaderNamefR, the result is obtained by joining the individual values with the string ", " (comma and space), preserving their order.

::http::responseLine fItokenfR : This command returns the first line of the server response: the HTTP "status line". The "status line" has three elements separated by spaces: the HTTP version, a three-digit numerical "status code", and a "reason phrase". Only the reason phrase may contain spaces. Examples:

HTTP/1.1 200 OK HTTP/1.0 404 Not Found The "status code" is a three-digit number in the range 100 to 599. A value of 200 is the normal return from a GET request, and its matching "reason phrase" is "OK". Codes beginning with 4 or 5 indicate errors. Codes beginning with 3 are redirection errors. In this case the fBLocationfR response header specifies a new URL that contains the requested information.

The "reason phrase" is a textual description of the "status code": it may vary from server to server, and can be changed without affecting the HTTP protocol. The recommended values (RFC 7231 and IANA assignments) for each code are provided by the command fB::http::reasonPhrasefR.

::http::responseCode fItokenfR : This command returns the "status code" (200, 404, etc.) of the server "status line". If a three-digit code cannot be found, the full status line is returned. See command fB::http::responseLinefR for more information on the "status line".

::http::reasonPhrase fIcodefR : This command returns the IANA recommended "reason phrase" for a particular "status code" returned by a HTTP server. The argument fIcodefR is a valid status code, and therefore is an integer in the range 100 to 599 inclusive. For numbers in this range with no assigned meaning, the command returns the value "Unassigned". Several status codes are used only in response to the methods defined by HTTP extensions such as WebDAV, and not in response to a HEAD, GET, or POST request method.

The "reason phrase" returned by a HTTP server may differ from the recommended value, without affecting the HTTP protocol. The value returned by fB::http::geturlfR can be obtained by calling either command fB::http::responseLinefR (which returns the full status line) or command fB::http::responseInfofR (which returns a dictionary, with the "reason phrase" stored in key fIreasonPhrasefR).

A registry of valid status codes is maintained at https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml

::http::responseHeaders fItokenfR ?fIheaderNamefR? : The response from a HTTP server includes metadata headers that describe the response body and the transaction itself. This command returns the HTTP response header names and values, in the order that they were received from the server, as a Tcl list of the form ?name value ...? Header names are case-insensitive and are converted to lower case. The return value is not a fBdictfR because some header names may occur more than once, notably fBSet-CookiefR. If the second argument is not supplied, all response headers are returned. If the second argument is supplied, it provides the value of a header name. Only headers with the requested name (converted to lower case) are returned. If no such headers are found, an empty list is returned. See section fBMETADATAfR for more information.

::http::responseHeaderValue fItoken headerNamefR : This command returns the value of the HTTP response header named fIheaderNamefR. Header names are case-insensitive and are converted to lower case. If no such header exists, the return value is the empty string. If there are multiple headers named fIheaderNamefR, the result is obtained by joining the individual values with the string ", " (comma and space), preserving their order. Multiple headers with the same name may be processed in this manner, except fBSet-CookiefR which does not conform to the comma-separated-list syntax and cannot be combined into a single value. Each fBSet-CookiefR header must be treated individually, e.g. by processing the return value of fB::http::responseHeadersfR fItokenfR fBSet-CookiefR.

::http::responseInfo fItokenfR : This command returns a fBdictfR of selected response metadata that are essential for identifying a successful transaction and making use of the response, along with other metadata that are informational. The keys of the fBdictfR are fIstagefR, fIstatusfR, fIresponseCodefR, fIreasonPhrasefR, fIcontentTypefR, fIbinaryfR, fIredirectionfR, fIupgradefR, fIerrorfR, fIpostErrorfR, fImethodfR, fIcharsetfR, fIcompressionfR, fIhttpRequestfR, fIhttpResponsefR, fIurlfR, fIconnectionRequestfR, fIconnectionResponsefR, fIconnectionActualfR, fItransferEncodingfR, fItotalPostfR, fIcurrentPostfR, fItotalSizefR, and fIcurrentSizefR. The meaning of these keys is described in the section fBMETADATAfR below. It is always worth checking the value of fIbinaryfR after a HTTP transaction, to determine whether a misconfigured server has caused http to interpret a text resource as a binary, or vice versa. After a POST transaction, check the value of fIpostErrorfR to verify that the request body was uploaded without error.

::http::responseBody fItokenfR : This command returns the entity sent by the HTTP server (unless fI-channelfR was used, in which case the entity was delivered to the channel, and the command returns the empty string). Other terms for "entity", with varying precision, include "representation of resource", "resource", "response body after decoding", "payload", "message body after decoding", "content(s)", and "file".

::http::register fIproto port commandfR ?fIsocketCmdVarNamefR? ?fIuseSockThreadfR? ?fIendToEndProxyfR? : This procedure allows one to provide custom HTTP transport types such as HTTPS, by registering a prefix, the default port, and the command to execute to create the Tcl fBchannelfR. The optional arguments configure how fBhttpfR uses the custom transport, and have default values that are compatible with older versions of fBhttpfR in which fB::http::registerfR has no optional arguments. Argument fIsocketCmdVarNamefR is the name of a variable provided by the transport, whose value is the command used by the transport to open a socket. Its default value is set by the transport and is "::socket", but if the name of the variable is supplied to fB::http::registerfR, then fBhttpfR will set a new value in order to make optional facilities available. These facilities are enabled by the optional arguments fIuseSockThreadfR, fIendToEndProxyfR, which take boolean values with default value fIfalsefR. Iff argument fIuseSockThreadfR is supplied and is boolean fItruefR, then iff permitted by the value [fBhttp::configfR fI-threadlevelfR] and by the availability of package fBThreadfR, sockets created for the transport will be opened in a different thread so that a slow DNS lookup will not cause the script to block. Iff argument fIendToEndProxyfR is supplied and is boolean fItruefR, then when fBhttp::geturlfR accesses a server via a proxy, it will open a channel by sending a CONNECT request to the proxy, and it will then make its request over this channel. This allows end-to-end encryption for HTTPS requests made through a proxy. For example,

```
package require http
package require tls

::http::register https 443 ::tls::socket ::tls::socketCmd 1 1

set token [::http::geturl https://my.secure.site/]
```

::http::registerError fIsockfR ?fImessagefR? : This procedure allows a registered protocol handler to deliver an error message for use by fBhttpfR. Calling this command does not raise an error. The command is useful when a registered protocol detects an problem (for example, an invalid TLS certificate) that will cause an error to propagate to fBhttpfR. The command allows fBhttpfR to provide a precise error message rather than a general one. The command returns the value provided by the last call with argument fImessagefR, or the empty string if no such call has been made.

::http::unregister fIprotofR : This procedure unregisters a protocol handler that was previously registered via fB::http::registerfR, returning a six-item list of the values that were previously supplied to fB::http::registerfR if there was such a handler, and an error if there was no such handler.

::http::code fItokenfR : An alternative name for the command fB::http::responseLinefR

::http::data fItokenfR : An alternative name for the command fB::http::responseBodyfR.

::http::meta fItokenfR ?fIheaderNamefR? : An alternative name for the command fB::http::responseHeadersfR

::http::ncode fItokenfR : An alternative name for the command fB::http::responseCodefR

Errors

The fB::http::geturlfR procedure will raise errors in the following cases: invalid command line options, or an invalid URL. These errors mean that it cannot even start the network transaction. For synchronous fB::http::geturlfR calls (where fB-commandfR is not specified), it will raise an error if the URL is on a non-existent host or at a bad port on an existing host. It will also raise an error for any I/O errors while writing out the HTTP request line and headers, or reading the HTTP reply headers or data. Because fB::http::geturlfR does not return a token in these cases, it does all the required cleanup and there is no issue of your app having to call fB::http::cleanupfR.

For asynchronous fB::http::geturlfR calls, all of the above error situations apply, except that if there is any error while reading the HTTP reply headers or data, no exception is thrown. This is because after writing the HTTP headers, fB::http::geturlfR returns, and the rest of the HTTP transaction occurs in the background. The command callback can check if any error occurred during the read by calling fB::http::responseInfofR to check the transaction status.

Alternatively, if the main program flow reaches a point where it needs to know the result of the asynchronous HTTP request, it can call fB::http::waitfR and then check status and error, just as the synchronous call does.

The fB::http::geturlfR command runs the fB-commandfR, fB-handlerfR, and fB-proxyfilterfR callbacks inside a fBcatchfR command. Therefore an error in the callback command does not call the fBbgerrorfR handler. When debugging one of these callbacks, it may be convenient to report errors by using a fBcatchfR command within the callback command itself, e.g. to write an error message to stdout.

In any case, you must still call fB::http::cleanupfR to delete the state array when you are done.

There are other possible results of the HTTP transaction determined by examining the status from fB::http::statusfR (or the value of the fIstatusfR key in the dictionary returned by fB::http::responseInfofR). These are described below.

ok : If the HTTP transaction completes entirely, then status will be fBokfR. However, you should still check the fB::http::responseLinefR value to get the HTTP status. The fB::http::responseCodefR procedure provides just the numeric error (e.g., 200, 404 or 500) while the fB::http::responseLinefR procedure returns a value like "HTTP 404 File not found".

eof : If the server closes the socket without replying, then no error is raised, but the status of the transaction will be fBeoffR.

error : The error message, stack trace, and error code are accessible via fB::http::errorfR. The error message is also provided by the value of the fIerrorfR key in the dictionary returned by fB::http::responseInfofR.

timeout : A timeout occurred before the transaction could complete.

reset : The user has called fB::http::resetfR.

"" : (empty string) The transaction has not yet finished.

Another error possibility is that fB::http::geturlfR failed to write the whole of the POST request body (fB-queryfR or fB-querychannelfR data) to the server. fB::http::geturlfR stores the error message for later retrieval by the fB::http::postErrorfR or fB::http::responseInfofR commands, and then attempts to complete the transaction. If it can read the server's response the status will be fBokfR, but it is important to call fB::http::postErrorfR or fB::http::responseInfofR after every POST to check that the data was sent in full. If the server has closed the connection the status will be fBeoffR.

Metadata

Most useful metadata

When a HTTP server responds to a request, it supplies not only the entity requested, but also metadata. This is provided by the first line (the "status line") of the response, and by a number of HTTP headers. Further metadata relates to how fB::http::geturlfR has processed the response from the server.

The most important metadata can be accessed with the command fB::http::responseInfofR. This command returns a fBdictfR of metadata that are essential for identifying a successful transaction and making use of the response, along with other metadata that are informational. The keys of the fBdictfR are:

===== Essential Values =====

stage : This value, set by fB::http::geturlfR, describes the stage that the transaction has reached. Values, in order of the transaction lifecycle, are: "created", "connecting", "header", "body", and "complete". The other fBdictfR keys will not be available until the value of fBstagefR is "body" or "complete". The key fBcurrentSizefR has its final value only when fBstagefR is "complete".

status : This value, set by fB::http::geturlfR, is "ok" for a successful transaction; "eof", "error", "timeout", or "reset" for an unsuccessful transaction; or "" if the transaction is still in progress. The value is the same as that returned by command fB::http::statusfR. The meaning of these values is described in the section fBERRORSfR (above).

responseCode : The "HTTP status code" sent by the server in the first line (the "status line") of the response. If the value cannot be extracted from the status line, the full status line is returned.

reasonPhrase : The "reason phrase" sent by the server as a description of the HTTP status code. If the value cannot be extracted from the status line, the full status line is returned.

contentType : The value of the fBContent-TypefR response header or, if the header was not supplied, the default value "application/octet-stream".

binary : This boolean value, set by fB::http::geturlfR, describes how the command has interpreted the entity returned by the server (after decoding any compression specified by the fBContent-EncodingfR response header). This decoded entity is accessible as the return value of the command fB::http::responseBodyfR.

The value is fBtruefR if http has interpreted the decoded entity as binary. The value returned by fB::http::responseBodyfR is a Tcl binary string. This is a suitable format for image data, zip files, etc. fB::http::geturlfR chooses this value if the user has requested a binary interpretation by passing the option fB-binaryfR to the command, or if the server has supplied a binary content type in a fBContent-TypefR response header, or if the server has not supplied any fBContent-TypefR header.

The value is fBfalsefR in other cases, and this means that http has interpreted the decoded entity as text. The text has been converted, from the character set notified by the server, into Tcl's internal Unicode format; the value returned by fB::http::responseBodyfR is an ordinary Tcl string.

It is always worth checking the value of "binary" after a HTTP transaction, to determine whether a misconfigured server has caused http to interpret a text resource as a binary, or vice versa.

redirection : The URL that is the redirection target. The value is that of the fBLocationfR response header. This header is sent when a response has status code 3XX (redirection).

upgrade : If not empty, the value indicates the protocol(s) to which the server will switch after completion of this transaction, while continuing to use the same connection. When the server intends to switch protocols, it will also send the value "101" as the status code (the fBresponseCodefR key), and the word "upgrade" as an element of the fBConnectionfR response header (the fBconnectionResponsefR key), and it will not send a response body. See the section fBPROTOCOL UPGRADESfR for more information.

error : The error message, if there is one. Further information, including a stack trace and error code, are available from command fB::http::errorfR.

postError : The error message (if any) generated when a HTTP POST request sends its request-body to the server. Further information, including a stack trace and error code, are available from command fB::http::postErrorfR. A POST transaction may appear complete, according to the keys fBstagefR, fBstatusfR, and fBresponseCodefR, but it is important to check this fBpostErrorfR key in case an error occurred when uploading the request-body.

===== Informational Values =====

method : The HTTP method used in the request.

charset : The value of the charset attribute of the fBContent-TypefR response header. The charset value is used only for a text resource. If the server did not specify a charset, the value defaults to that of the variable fB::http::defaultCharsetfR, which unless it has been deliberately modified by the caller is fBiso8859-1fR. Incoming text data is automatically converted from the character set defined by fBcharsetfR to Tcl's internal Unicode representation, i.e. to a Tcl string.

compression : A copy of the fBContent-EncodingfR response-header value.

httpRequest : The version of HTTP specified in the request (i.e. sent in the request line). The value is that of the option fB-protocolfR supplied to fB::http::geturlfR (default value "1.1"), unless the command reduced the value to "1.0" because it was passed the fB-handlerfR option.

httpResponse : The version of HTTP used by the server (obtained from the response "status line"). The server uses this version of HTTP in its response, but ensures that this response is compatible with the HTTP version specified in the client's request. If the value cannot be extracted from the status line, the full status line is returned.

url : The requested URL, typically the URL supplied as an argument to fB::http::geturlfR but without its "fragment" (the final part of the URL beginning with "#").

connectionRequest : The value, if any, sent to the server in fBConnectionfR request header(s).

connectionResponse : The value, if any, received from the server in fBConnectionfR response header(s).

connectionActual : This value, set by fB::http::geturlfR, reports whether the connection was closed after the transaction (value "close"), or left open (value "keep-alive").

transferEncoding : The value of the Transfer-Encoding response header, if it is present. The value is either "chunked" (indicating HTTP/1.1 "chunked encoding") or the empty string.

totalPost : The total length of the request body in a POST request.

currentPost : The number of bytes of the POST request body sent to the server so far. The value is the same as that returned by command fB::http::sizefR.

totalSize : A copy of the fBContent-LengthfR response-header value. The number of bytes specified in a fBContent-LengthfR header, if one was sent. If none was sent, the value is 0. A correctly configured server omits this header if the transfer-encoding is "chunked", or (for older servers) if the server closes the connection when it reaches the end of the resource.

currentSize : The number of bytes fetched from the server so far.

More metadata

The dictionary returned by fB::http::responseInfofR is the most useful subset of the available metadata. Other metadata include:

  1. The full "status line" of the response, available as the return value of command fB::http::responseLinefR.

  2. The full response headers, available as the return value of command fB::http::responseHeadersfR. This return value is a list of the response-header names and values, in the order that they were received from the server.

The return value is not a fBdictfR because some header names may occur more than once, notably fBSet-CookiefR. If the value is read into a fBdictfR or into an array (using array set), only the last header with each name will be preserved.

Some of the header names (metadata keys) are listed below, but the HTTP standard defines several more, and servers are free to add their own. When a dictionary key is mentioned below, this refers to the fBdictfR value returned by command fB::http::responseInfofR.

Content-Type : The content type of the URL contents. Examples include fBtext/htmlfR, fBimage/gif,fR fBapplication/postscriptfR and fBapplication/x-tclfR. Text values typically specify a character set, e.g. fBtext/html; charset=UTF-8fR. Dictionary key fIcontentTypefR.

Content-Length : The advertised size in bytes of the contents, available as dictionary key fItotalSizefR. The actual number of bytes read by fB::http::geturlfR so far is available as dictionary key fBcurrentSizefR.

Content-Encoding : The compression algorithm used for the contents. Examples include fBgzipfR, fBdeflatefR. Dictionary key fIcontentfR.

Location : This header is sent when a response has status code 3XX (redirection). It provides the URL that is the redirection target. Dictionary key fIredirectionfR.

Set-Cookie : This header is sent to offer a cookie to the client. Cookie management is done by the fB::http::configfR option fB-cookiejarfR, and so the fBSet-CookiefR headers need not be parsed by user scripts. See section fBCOOKIE JAR PROTOCOLfR.

Connection : The value can be supplied as a comma-separated list, or by multiple headers. The list often has only one element, either "close" or "keep-alive". The value "upgrade" indicates a successful upgrade request and is typically combined with the status code 101, an fBUpgradefR response header, and no response body. Dictionary key fIconnectionResponsefR.

Upgrade : The value indicates the protocol(s) to which the server will switch immediately after the empty line that terminates the 101 response headers. Dictionary key fIupgradefR.

Even more metadata

1. : Details of the HTTP request. The request is determined by the options supplied to fB::http::geturlfR and fB::http::configfR. However, it is sometimes helpful to examine what fB::http::geturlfR actually sent to the server, and this information is available through commands fB::http::requestHeadersfR and fB::http::requestLinefR.

2. : The state array: the internal variables of fB::http::geturlfR. It may sometimes be helpful to examine this array. Details are given in the next section.

State array

The fB::http::geturlfR procedure returns a fItokenfR that can be used as an argument to other fB::http::*fR commands, which examine and manage the state of the HTTP transaction. For most purposes these commands are sufficient. The fItokenfR can also be used to access the internal state of the transaction, which is stored in a Tcl array. This facility is most useful when writing callback commands for the options fB-commandfR, fB-handlerfR, fB-progressfR, or fB-queryprogressfR. Use the following command inside the proc to define an easy-to-use array fIstatefR as a local variable within the proc

upvar 0 $token state

Once the data associated with the URL is no longer needed, the state array should be unset to free up storage. The fB::http::cleanupfR procedure is provided for that purpose.

The following elements of the array are supported, and are the origin of the values returned by commands as described below. When a dictionary key is mentioned below, this refers to the fBdictfR value returned by command fB::http::responseInfofR.

binary : For dictionary key fIbinaryfR.

body : For command fB::http::responseBodyfR.

charset : For dictionary key fIcharsetfR.

coding : For dictionary key fIcompressionfR.

connection : For dictionary key fIconnectionActualfR.

currentsize : For command fB::http::sizefR; and for dictionary key fIcurrentSizefR.

error : For command fB::http::errorfR; part is used in dictionary key fIerrorfR.

http : For command fB::http::responseLinefR.

httpResponse : For dictionary key fIhttpResponsefR.

meta : For command fB::http::responseHeadersfR. Further discussion above in the section fBMORE METADATAfR.

method : For dictionary key fImethodfR.

posterror : For dictionary key fIpostErrorfR.

postErrorFull : For command fB::http::postErrorfR.

-protocol : For dictionary key fIhttpRequestfR.

querylength : For dictionary key fItotalPostfR.

queryoffset : For dictionary key fIcurrentPostfR.

reasonPhrase : For dictionary key fIreasonPhrasefR.

requestHeaders : For command fB::http::requestHeadersfR.

requestLine : For command fB::http::requestLinefR.

responseCode : For dictionary key fIresponseCodefR.

state : For dictionary key fIstagefR.

status : For command fB::http::statusfR; and for dictionary key fIstatusfR.

totalsize : For dictionary key fItotalSizefR.

transfer : For dictionary key fItransferEncodingfR.

type : For dictionary key fIcontentTypefR.

upgrade : For dictionary key fIupgradefR.

url : For dictionary key fIurlfR.

Persistent connections

Basics

See RFC 7230 Sec 6, which supersedes RFC 2616 Sec 8.1.

A persistent connection allows multiple HTTP/1.1 transactions to be carried over the same TCP connection. Pipelining allows a client to make multiple requests over a persistent connection without waiting for each response. The server sends responses in the same order that the requests were received.

If a POST request fails to complete, typically user confirmation is needed before sending the request again. The user may wish to verify whether the server was modified by the failed POST request, before sending the same request again.

A HTTP request will use a persistent socket if the call to fBhttp::geturlfR has the option fB-keepalive truefR. It will use pipelining where permitted if the fBhttp::configfR option fB-pipelinefR is boolean fBtruefR (its default value).

The http package maintains no more than one persistent connection to each server (i.e. each value of "domain:port"). If fBhttp::geturlfR is called to make a request over a persistent connection while the connection is busy with another request, the new request will be held in a queue until the connection is free.

The http package does not support HTTP/1.0 persistent connections controlled by the fBKeep-AlivefR header.

Special cases

This subsection discusses issues related to closure of the persistent connection by the server, automatic retry of failed requests, the special treatment necessary for POST requests, and the options for dealing with these cases.

In accordance with RFC 7230, fBhttp::geturlfR does not pipeline requests that use the POST method. If a POST uses a persistent connection and is not the first request on that connection, fBhttp::geturlfR waits until it has received the response for the previous request; or (if fBhttp::configfR option fB-postfreshfR is boolean fBtruefR) it uses a new connection for each POST.

If the server is processing a number of pipelined requests, and sends a response header "Connection: close" with one of the responses (other than the last), then subsequent responses are unfulfilled. fBhttp::geturlfR will send the unfulfilled requests again over a new connection.

A difficulty arises when a HTTP client sends a request over a persistent connection that has been idle for a while. The HTTP server may half-close an apparently idle connection while the client is sending a request, but before the request arrives at the server: in this case (an "asynchronous close event") the request will fail. The difficulty arises because the client cannot be certain whether the POST modified the state of the server. For HEAD or GET requests, fBhttp::geturlfR opens another connection and retransmits the failed request. However, if the request was a POST, RFC 7230 forbids automatic retry by default, suggesting either user confirmation, or confirmation by user-agent software that has semantic understanding of the application. The fBhttp::configfR option fB-repostfR allows for either possibility.

Asynchronous close events can occur only in a short interval of time. The fBhttpfR package monitors each persistent connection for closure by the server. Upon detection, the connection is also closed at the client end, and subsequent requests will use a fresh connection.

If the fBhttp::geturlfR command is called with option fB-keepalive truefR, then it will both try to use an existing persistent connection (if one is available), and it will send the server a "Connection: keep-alive" request header asking to keep the connection open for future requests.

The fBhttp::configfR options fB-pipelinefR, fB-postfreshfR, and fB-repostfR relate to persistent connections.

Option fB-pipelinefR, if boolean fBtruefR, will pipeline GET and HEAD requests made over a persistent connection. POST requests will not be pipelined - if the POST is not the first transaction on the connection, its request will not be sent until the previous response has finished. GET and HEAD requests made after a POST will not be sent until the POST response has been delivered, and will not be sent if the POST fails.

Option fB-postfreshfR, if boolean fBtruefR, will override the fBhttp::geturlfR option fB-keepalivefR, and always open a fresh connection for a POST request.

Option fB-repostfR, if fBtruefR, permits automatic retry of a POST request that fails because it uses a persistent connection that the server has half-closed (an "asynchronous close event"). Subsequent GET and HEAD requests in a failed pipeline will also be retried. fIThefR fB-repostfR fIoption should be used only if the application understands that the retry is appropriatefR - specifically, the application must know that if the failed POST successfully modified the state of the server, a repeat POST would have no adverse effect.

Cookie jar protocol

Cookies are short key-value pairs used to implement sessions within the otherwise-stateless HTTP protocol. (See RFC 6265 for details; Tcl does not implement the Cookie2 protocol as that is rarely seen in the wild.)

Cookie storage management commands (em "cookie jars" (em must support these subcommands which form the HTTP cookie storage management protocol. Note that fIcookieJarfR below does not have to be a command name; it is properly a command prefix (a Tcl list of words that will be expanded in place) and admits many possible implementations.

Though not formally part of the protocol, it is expected that particular values of fIcookieJarfR will correspond to sessions; it is up to the caller of fB::http::configfR to decide what session applies and to manage the deletion of said sessions when they are no longer desired (which should be when they not configured as the current cookie jar).

cookieJar fBgetCookiesfR fIprotocol host requestPathfR : This command asks the cookie jar what cookies should be supplied for a particular request. It should take the fIprotocolfR (typically fBhttpfR or fBhttpsfR), fIhostfR name and fIrequestPathfR (parsed from the fIurlfR argument to fB::http::geturlfR) and return a list of cookie keys and values that describe the cookies to supply to the remote host. The list must have an even number of elements. There should only ever be at most one cookie with a particular key for any request (typically the one with the most specific fIhostfR/domain match and most specific fIrequestPathfR/path match), but there may be many cookies with different names in any request.

cookieJar fBstoreCookiefR fIcookieDictionaryfR : This command asks the cookie jar to store a particular cookie that was returned by a request; the result of this command is ignored. The cookie (which will have been parsed by the http package) is described by a dictionary, fIcookieDictionaryfR, that may have the following keys:

domain : This is always present. Its value describes the domain hostname fIor prefixfR that the cookie should be returned for. The checking of the domain against the origin (below) should be careful since sites that issue cookies should only do so for domains related to themselves. Cookies that do not obey a relevant origin matching rule should be ignored.

expires : This is optional. If present, the cookie is intended to be a persistent cookie and the value of the option is the Tcl timestamp (in seconds from the same base as fBclock secondsfR) of when the cookie expires (which may be in the past, which should result in the cookie being deleted immediately). If absent, the cookie is intended to be a session cookie that should be not persisted beyond the lifetime of the cookie jar.

hostonly : This is always present. Its value is a boolean that describes whether the cookie is a single host cookie (true) or a domain-level cookie (false).

httponly : This is always present. Its value is a boolean that is true when the site wishes the cookie to only ever be used with HTTP (or HTTPS) traffic.

key : This is always present. Its value is the fIkeyfR of the cookie, which is part of the information that must be return when sending this cookie back in a future request.

origin : This is always present. Its value describes where the http package believes it received the cookie from, which may be useful for checking whether the cookie's domain is valid.

path : This is always present. Its value describes the path prefix of requests to the cookie domain where the cookie should be returned.

secure : This is always present. Its value is a boolean that is true when the cookie should only used on requests sent over secure channels (typically HTTPS).

value : This is always present. Its value is the value of the cookie, which is part of the information that must be return when sending this cookie back in a future request.

Other keys may always be ignored; they have no meaning in this protocol.

Protocol upgrades

The HTTP/1.1 fBConnectionfR and fBUpgradefR request headers inform the server that the client wishes to change the protocol used over the existing connection (RFC 7230). This mechanism can be used to request a WebSocket (RFC 6455), a higher version of the HTTP protocol (HTTP 2), or TLS encryption. If the server accepts the upgrade request, its response code will be 101.

To request a protocol upgrade when calling fBhttp::geturlfR, the fB-headersfR option must supply appropriate values for fBConnectionfR and fBUpgradefR, and the fB-commandfR option must supply a command that implements the requested protocol and can also handle the server response if the server refuses the protocol upgrade. For upgrade requests fBhttp::geturlfR ignores the value of option fB-keepalivefR, and always uses the value fB0fR so that the upgrade request is not made over a connection that is intended for multiple HTTP requests.

The Tcllib library fBwebsocketfR implements WebSockets, and makes the necessary calls to commands in the fBhttpfR package.

There is currently no native Tcl client library for HTTP/2.

The fBUpgradefR mechanism is not used to request TLS in web browsers, because fBhttpfR and fBhttpsfR are served over different ports. It is used by protocols such as Internet Printing Protocol (IPP) that are built on top of fBhttp(s)fR and use the same TCP port number for both secure and insecure traffic.

In browsers, opportunistic encryption is instead implemented by the fBUpgrade-Insecure-RequestsfR client header. If a secure service is available, the server response code is a 307 redirect, and the response header fBLocationfR specifies the target URL. The browser must call fBhttp::geturlfR again in order to fetch this URL. See https://w3c.github.io/webappsec-upgrade-insecure-requests/

Threads

Purpose

Command fB::http::geturlfR uses the Tcl fB::socketfR command with the fB-asyncfR option to connect to a remote server, but the return from this command can be delayed in adverse cases (e.g. a slow DNS lookup), preventing the event loop from processing other events. This delay is avoided if the fB::socketfR command is evaluated in another thread. The Thread package is not part of Tcl but is provided in "Batteries Included" distributions. Instead of the fB::socketfR command, the http package uses fB::http::socketfR which makes connections in the manner specified by the value of fB-threadlevelfR and the availability of package Thread.

With tls (https)

The same fB-threadlevelfR configuration applies to both HTTP and HTTPS connections. HTTPS is enabled by using the fBhttp::registerfR command, typically by specifying the fB::tls::socketfR command of the tls package to handle TLS cryptography. The fB::tls::socketfR command connects to the remote server by using the command specified by the value of variable fB::tls::socketCmdfR, and this value defaults to "::socket". If http::geturl finds that fB::tls::socketCmdfR has this value, it replaces it with the value "::http::socket". If fB::tls::socketCmdfR has a value other than "::socket", i.e. if the script or the Tcl installation has replaced the value "::socket" with the name of a different command, then http does not change the value. The script or installation that modified fB::tls::socketCmdfR is responsible for integrating fB::http::socketfR into its own replacement command.

With a child interpreter

The peer thread can transfer the socket only to the main interpreter of the script's thread. Therefore the thread-based fB::http::socketfR works with non-zero fB-threadlevelfR values only if the script runs in the main interpreter. A child interpreter must use fB-threadlevel 0fR unless the parent interpreter has provided alternative facilities. The main parent interpreter may grant full fB-threadlevelfR facilities to a child interpreter, for example by aliasing, to fB::http::socketfR in the child, a command that runs fBhttp::socketfR in the parent, and then transfers the socket to the child.

Example

This example creates a procedure to copy a URL to a file while printing a progress meter, and prints the response headers associated with the URL.

proc httpcopy { url file {chunk 4096} } {
    set out [open $file w]
    set token [::http::geturl $url -channel $out \
            -progress httpCopyProgress -blocksize $chunk]
    close $out

    # This ends the line started by httpCopyProgress
    puts stderr ""

    upvar 0 $token state
    set max 0
    foreach {name value} $state(meta) {
        if {[string length $name] > $max} {
            set max [string length $name]
        }
        if {[regexp -nocase ^location$ $name]} {
            # Handle URL redirects
            puts stderr "Location:$value"
            return [httpcopy [string trim $value] $file $chunk]
        }
    }
    incr max
    foreach {name value} $state(meta) {
        puts [format "%-*s %s" $max $name: $value]
    }

    return $token
}
proc httpCopyProgress {args} {
    puts -nonewline stderr .
    flush stderr
}