Debian Codegraph @

doc/http.n

raw
1 '\"
2 '\" Copyright (c) 1995-1997 Sun Microsystems, Inc.
3 '\" Copyright (c) 1998-2000 Ajuba Solutions.
4 '\" Copyright (c) 2004 ActiveState Corporation.
5 '\"
6 '\" See the file "license.terms" for information on usage and redistribution
7 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
8 '\"
9 .TH "http" n 2.9 http "Tcl Bundled Packages"
10 .so man.macros
11 .BS
12 '\" Note: do not modify the .SH NAME line immediately below!
13 .SH NAME
14 http \- Client-side implementation of the HTTP/1.1 protocol
15 .SH SYNOPSIS
16 \fBpackage require http ?2.9?\fR
17 .\" See Also -useragent option documentation in body!
18 .sp
19 \fB::http::config ?\fI\-option value\fR ...?
20 .sp
21 \fB::http::geturl \fIurl\fR ?\fI\-option value\fR ...?
22 .sp
23 \fB::http::formatQuery\fR \fIkey value\fR ?\fIkey value\fR ...?
24 .sp
25 \fB::http::quoteString\fR \fIvalue\fR
26 .sp
27 \fB::http::reset\fR \fItoken\fR ?\fIwhy\fR?
28 .sp
29 \fB::http::wait \fItoken\fR
30 .sp
31 \fB::http::status \fItoken\fR
32 .sp
33 \fB::http::size \fItoken\fR
34 .sp
35 \fB::http::code \fItoken\fR
36 .sp
37 \fB::http::ncode \fItoken\fR
38 .sp
39 \fB::http::meta \fItoken\fR
40 .sp
41 \fB::http::data \fItoken\fR
42 .sp
43 \fB::http::error \fItoken\fR
44 .sp
45 \fB::http::cleanup \fItoken\fR
46 .sp
47 \fB::http::register \fIproto port command\fR
48 .sp
49 \fB::http::registerError \fIport\fR ?\fImessage\fR?
50 .sp
51 \fB::http::unregister \fIproto\fR
52 .SH "EXPORTED COMMANDS"
53 .PP
54 Namespace \fBhttp\fR exports the commands \fBconfig\fR, \fBformatQuery\fR,
55 \fBgeturl\fR, \fBquoteString\fR, \fBregister\fR, \fBregisterError\fR,
56 \fBreset\fR, \fBunregister\fR, and \fBwait\fR.
57 .PP
58 It does not export the commands \fBcleanup\fR, \fBcode\fR, \fBdata\fR,
59 \fBerror\fR, \fBmeta\fR, \fBncode\fR, \fBsize\fR, or \fBstatus\fR.
60 .BE
61 .SH DESCRIPTION
62 .PP
63 The \fBhttp\fR package provides the client side of the HTTP/1.1
64 protocol, as defined in RFC 7230 to RFC 7235, which supersede RFC 2616.
65 The package implements the GET, POST, and HEAD operations
66 of HTTP/1.1. It allows configuration of a proxy host to get through
67 firewalls. The package is compatible with the \fBSafesock\fR security
68 policy, so it can be used by untrusted applets to do URL fetching from
69 a restricted set of hosts. This package can be extended to support
70 additional HTTP transport protocols, such as HTTPS, by providing
71 a custom \fBsocket\fR command, via \fB::http::register\fR.
72 .PP
73 The \fB::http::geturl\fR procedure does a HTTP transaction.
74 Its \fIoptions \fR determine whether a GET, POST, or HEAD transaction
75 is performed.
76 The return value of \fB::http::geturl\fR is a token for the transaction.
77 The value is also the name of an array in the ::http namespace
78 that contains state information about the transaction. The elements
79 of this array are described in the \fBSTATE ARRAY\fR section.
80 .PP
81 If the \fB\-command\fR option is specified, then
82 the HTTP operation is done in the background.
83 \fB::http::geturl\fR returns immediately after generating the
84 HTTP request and the callback is invoked
85 when the transaction completes. For this to work, the Tcl event loop
86 must be active. In Tk applications this is always true. For pure-Tcl
87 applications, the caller can use \fB::http::wait\fR after calling
88 \fB::http::geturl\fR to start the event loop.
89 .PP
90 \fBNote:\fR The event queue is even used without the \fB\-command\fR option.
91 As a side effect, arbitrary commands may be processed while \fBhttp::geturl\fR
92 is running.
93 .SH COMMANDS
94 .TP
95 \fB::http::config\fR ?\fIoptions\fR?
96 .
97 The \fB::http::config\fR command is used to set and query the name of the
98 proxy server and port, and the User-Agent name used in the HTTP
99 requests. If no options are specified, then the current configuration
100 is returned. If a single argument is specified, then it should be one
101 of the flags described below. In this case the current value of
102 that setting is returned. Otherwise, the options should be a set of
103 flags and values that define the configuration:
104 .RS
105 .TP
106 \fB\-accept\fR \fImimetypes\fR
107 .
108 The Accept header of the request. The default is */*, which means that
109 all types of documents are accepted. Otherwise you can supply a
110 comma-separated list of mime type patterns that you are
111 willing to receive. For example,
112 .QW "image/gif, image/jpeg, text/*" .
113 .TP
114 \fB\-pipeline\fR \fIboolean\fR
115 .
116 Specifies whether HTTP/1.1 transactions on a persistent socket will be
117 pipelined. See the \fBPERSISTENT SOCKETS\fR section for details. The default
118 is 1.
119 .TP
120 \fB\-postfresh\fR \fIboolean\fR
121 .
122 Specifies whether requests that use the \fBPOST\fR method will always use a
123 fresh socket, overriding the \fB\-keepalive\fR option of
124 command \fBhttp::geturl\fR. See the \fBPERSISTENT SOCKETS\fR section for
125 details. The default is 0.
126 .TP
127 \fB\-proxyhost\fR \fIhostname\fR
128 .
129 The name of the proxy host, if any. If this value is the
130 empty string, the URL host is contacted directly.
131 .TP
132 \fB\-proxyport\fR \fInumber\fR
133 .
134 The proxy port number.
135 .TP
136 \fB\-proxyfilter\fR \fIcommand\fR
137 .
138 The command is a callback that is made during
139 \fB::http::geturl\fR
140 to determine if a proxy is required for a given host. One argument, a
141 host name, is added to \fIcommand\fR when it is invoked. If a proxy
142 is required, the callback should return a two-element list containing
143 the proxy server and proxy port. Otherwise the filter should return
144 an empty list. The default filter returns the values of the
145 \fB\-proxyhost\fR and \fB\-proxyport\fR settings if they are
146 non-empty.
147 .RS
148 .PP
149 The \fB::http::geturl\fR command runs the \fB\-proxyfilter\fR callback inside
150 a \fBcatch\fR command. Therefore an error in the callback command does
151 not call the \fBbgerror\fR handler. See the \fBERRORS\fR section for
152 details.
153 .RE
154 .TP
155 \fB\-repost\fR \fIboolean\fR
156 .
157 Specifies what to do if a POST request over a persistent connection fails
158 because the server has half-closed the connection. If boolean \fBtrue\fR, the
159 request
160 will be automatically retried; if boolean \fBfalse\fR it will not, and the
161 application
162 that uses \fBhttp::geturl\fR is expected to seek user confirmation before
163 retrying the POST. The value \fBtrue\fR should be used only under certain
164 conditions. See the \fBPERSISTENT SOCKETS\fR section for details. The
165 default is 0.
166 .TP
167 \fB\-urlencoding\fR \fIencoding\fR
168 .
169 The \fIencoding\fR used for creating the x-url-encoded URLs with
170 \fB::http::formatQuery\fR and \fB::http::quoteString\fR.
171 The default is \fButf-8\fR, as specified by RFC
172 2718. Prior to http 2.5 this was unspecified, and that behavior can be
173 returned by specifying the empty string (\fB{}\fR), although
174 \fIiso8859-1\fR is recommended to restore similar behavior but without the
175 \fB::http::formatQuery\fR or \fB::http::quoteString\fR
176 throwing an error processing non-latin-1 characters.
177 .TP
178 \fB\-useragent\fR \fIstring\fR
179 .
180 The value of the User-Agent header in the HTTP request. In an unsafe
181 interpreter, the default value depends upon the operating system, and
182 the version numbers of \fBhttp\fR and \fBTcl\fR, and is (for example)
183 .QW "\fBMozilla/5.0 (Windows; U; Windows NT 10.0) http/2.9.0 Tcl/8.6.9\fR" .
184 A safe interpreter cannot determine its operating system, and so the default
185 in a safe interpreter is to use a Windows 10 value with the current version
186 numbers of \fBhttp\fR and \fBTcl\fR.
187 .TP
188 \fB\-zip\fR \fIboolean\fR
189 .
190 If the value is boolean \fBtrue\fR, then by default requests will send a header
191 .QW "\fBAccept-Encoding: gzip,deflate,compress\fR" .
192 If the value is boolean \fBfalse\fR, then by default this header will not be
193 sent. In either case the default can be overridden for an individual request by
194 supplying a custom \fBAccept-Encoding\fR header in the \fB\-headers\fR option
195 of \fBhttp::geturl\fR. The default is 1.
196 .RE
197 .TP
198 \fB::http::geturl\fR \fIurl\fR ?\fIoptions\fR?
199 .
200 The \fB::http::geturl\fR command is the main procedure in the package.
201 The \fB\-query\fR option causes a POST operation and
202 the \fB\-validate\fR option causes a HEAD operation;
203 otherwise, a GET operation is performed. The \fB::http::geturl\fR command
204 returns a \fItoken\fR value that can be used to get
205 information about the transaction. See the \fBSTATE ARRAY\fR and
206 \fBERRORS\fR section for
207 details. The \fB::http::geturl\fR command blocks until the operation
208 completes, unless the \fB\-command\fR option specifies a callback
209 that is invoked when the HTTP transaction completes.
210 \fB::http::geturl\fR takes several options:
211 .RS
212 .TP
213 \fB\-binary\fR \fIboolean\fR
214 .
215 Specifies whether to force interpreting the URL data as binary. Normally
216 this is auto-detected (anything not beginning with a \fBtext\fR content
217 type or whose content encoding is \fBgzip\fR or \fBcompress\fR is
218 considered binary data).
219 .TP
220 \fB\-blocksize\fR \fIsize\fR
221 .
222 The block size used when reading the URL.
223 At most \fIsize\fR bytes are read at once. After each block, a call to the
224 \fB\-progress\fR callback is made (if that option is specified).
225 .TP
226 \fB\-channel\fR \fIname\fR
227 .
228 Copy the URL contents to channel \fIname\fR instead of saving it in
229 \fBstate(body)\fR.
230 .TP
231 \fB\-command\fR \fIcallback\fR
232 .
233 Invoke \fIcallback\fR after the HTTP transaction completes.
234 This option causes \fB::http::geturl\fR to return immediately.
235 The \fIcallback\fR gets an additional argument that is the \fItoken\fR returned
236 from \fB::http::geturl\fR. This token is the name of an array that is
237 described in the \fBSTATE ARRAY\fR section. Here is a template for the
238 callback:
239 .RS
240 .PP
241 .CS
242 proc httpCallback {token} {
243 upvar #0 $token state
244 # Access state as a Tcl array
245 }
246 .CE
247 .PP
248 The \fB::http::geturl\fR command runs the \fB\-command\fR callback inside
249 a \fBcatch\fR command. Therefore an error in the callback command does
250 not call the \fBbgerror\fR handler. See the \fBERRORS\fR section for
251 details.
252 .RE
253 .TP
254 \fB\-handler\fR \fIcallback\fR
255 .
256 Invoke \fIcallback\fR whenever HTTP data is available; if present, nothing
257 else will be done with the HTTP data. This procedure gets two additional
258 arguments: the socket for the HTTP data and the \fItoken\fR returned from
259 \fB::http::geturl\fR. The token is the name of a global array that is
260 described in the \fBSTATE ARRAY\fR section. The procedure is expected
261 to return the number of bytes read from the socket. Here is a
262 template for the callback:
263 .RS
264 .PP
265 .CS
266 proc httpHandlerCallback {socket token} {
267 upvar #0 $token state
268 # Access socket, and state as a Tcl array
269 # For example...
270 ...
271 set data [read $socket 1000]
272 set nbytes [string length $data]
273 ...
274 return $nbytes
275 }
276 .CE
277 .PP
278 The \fBhttp::geturl\fR code for the \fB\-handler\fR option is not compatible
279 with either compression or chunked transfer-encoding. If \fB\-handler\fR is
280 specified, then to work around these issues \fBhttp::geturl\fR will reduce the
281 HTTP protocol to 1.0, and override the \fB\-zip\fR option (i.e. it will not
282 send the header "\fBAccept-Encoding: gzip,deflate,compress\fR").
283 .PP
284 If options \fB\-handler\fR and \fB\-channel\fR are used together, the handler
285 is responsible for copying the data from the HTTP socket to the specified
286 channel. The name of the channel is available to the handler as element
287 \fB\-channel\fR of the token array.
288 .PP
289 The \fB::http::geturl\fR command runs the \fB\-handler\fR callback inside
290 a \fBcatch\fR command. Therefore an error in the callback command does
291 not call the \fBbgerror\fR handler. See the \fBERRORS\fR section for
292 details.
293 .RE
294 .TP
295 \fB\-headers\fR \fIkeyvaluelist\fR
296 .
297 This option is used to add headers not already specified
298 by \fB::http::config\fR to the HTTP request. The
299 \fIkeyvaluelist\fR argument must be a list with an even number of
300 elements that alternate between keys and values. The keys become
301 header field names. Newlines are stripped from the values so the
302 header cannot be corrupted. For example, if \fIkeyvaluelist\fR is
303 \fBPragma no-cache\fR then the following header is included in the
304 HTTP request:
305 .RS
306 .PP
307 .CS
308 Pragma: no-cache
309 .CE
310 .RE
311 .TP
312 \fB\-keepalive\fR \fIboolean\fR
313 .
314 If boolean \fBtrue\fR, attempt to keep the connection open for servicing
315 multiple requests. Default is 0.
316 .TP
317 \fB\-method\fR \fItype\fR
318 .
319 Force the HTTP request method to \fItype\fR. \fB::http::geturl\fR will
320 auto-select GET, POST or HEAD based on other options, but this option overrides
321 that selection and enables choices like PUT and DELETE for WebDAV support.
322 .RS
323 .PP
324 It is the caller's responsibility to ensure that the headers and request body
325 (if any) conform to the requirements of the request method. For example, if
326 using \fB\-method\fR \fIPOST\fR to send a POST with an empty request body, the
327 caller must also supply the option
328 .QW "\-headers {Content-Length 0}" .
329 .RE
330 .TP
331 \fB\-myaddr\fR \fIaddress\fR
332 .
333 Pass an specific local address to the underlying \fBsocket\fR call in case
334 multiple interfaces are available.
335 .TP
336 \fB\-progress\fR \fIcallback\fR
337 .
338 The \fIcallback\fR is made after each transfer of data from the URL.
339 The callback gets three additional arguments: the \fItoken\fR from
340 \fB::http::geturl\fR, the expected total size of the contents from the
341 \fBContent-Length\fR meta-data, and the current number of bytes
342 transferred so far. The expected total size may be unknown, in which
343 case zero is passed to the callback. Here is a template for the
344 progress callback:
345 .RS
346 .PP
347 .CS
348 proc httpProgress {token total current} {
349 upvar #0 $token state
350 }
351 .CE
352 .RE
353 .TP
354 \fB\-protocol\fR \fIversion\fR
355 .
356 Select the HTTP protocol version to use. This should be 1.0 or 1.1 (the
357 default). Should only be necessary for servers that do not understand or
358 otherwise complain about HTTP/1.1.
359 .TP
360 \fB\-query\fR \fIquery\fR
361 .
362 This flag (if the value is non-empty) causes \fB::http::geturl\fR to do a
363 POST request that passes the string
364 \fIquery\fR verbatim to the server as the request payload.
365 The content format (and encoding) of \fIquery\fR is announced by the request
366 header \fBContent-Type\fR which is set by the option \fB\-type\fR. Any value
367 of \fB\-type\fR is permitted, and it is the responsibility of the caller to
368 supply \fIquery\fR in the correct format.
369 .RS
370 .PP
371 If \fB\-type\fR is not specified, it defaults to
372 \fIapplication/x-www-form-urlencoded\fR, which requires \fIquery\fR to be an
373 x-url-encoding formatted query-string (this \fB\-type\fR and query format are
374 used in a POST submitted from an html form). The \fB::http::formatQuery\fR
375 procedure can be used to do the formatting.
376 .RE
377 .TP
378 \fB\-queryblocksize\fR \fIsize\fR
379 .
380 The block size used when posting query data to the URL.
381 At most
382 \fIsize\fR
383 bytes are written at once. After each block, a call to the
384 \fB\-queryprogress\fR
385 callback is made (if that option is specified).
386 .TP
387 \fB\-querychannel\fR \fIchannelID\fR
388 .
389 This flag causes \fB::http::geturl\fR to do a POST request that passes the
390 data contained in \fIchannelID\fR to the server. The data contained in
391 \fIchannelID\fR must be an x-url-encoding
392 formatted query unless the \fB\-type\fR option below is used.
393 If a Content-Length header is not specified via the \fB\-headers\fR options,
394 \fB::http::geturl\fR attempts to determine the size of the post data
395 in order to create that header. If it is
396 unable to determine the size, it returns an error.
397 .TP
398 \fB\-queryprogress\fR \fIcallback\fR
399 .
400 The \fIcallback\fR is made after each transfer of data to the URL
401 (i.e. POST) and acts exactly like the \fB\-progress\fR option (the
402 callback format is the same).
403 .TP
404 \fB\-strict\fR \fIboolean\fR
405 .
406 Whether to enforce RFC 3986 URL validation on the request. Default is 1.
407 .TP
408 \fB\-timeout\fR \fImilliseconds\fR
409 .
410 If \fImilliseconds\fR is non-zero, then \fB::http::geturl\fR sets up a timeout
411 to occur after the specified number of milliseconds.
412 A timeout results in a call to \fB::http::reset\fR and to
413 the \fB\-command\fR callback, if specified.
414 The return value of \fB::http::status\fR is \fBtimeout\fR
415 after a timeout has occurred.
416 .TP
417 \fB\-type\fR \fImime-type\fR
418 .
419 Use \fImime-type\fR as the \fBContent-Type\fR value, instead of the
420 default value (\fBapplication/x-www-form-urlencoded\fR) during a
421 POST operation.
422 .TP
423 \fB\-validate\fR \fIboolean\fR
424 .
425 If \fIboolean\fR is non-zero, then \fB::http::geturl\fR does an HTTP HEAD
426 request. This request returns meta information about the URL, but the
427 contents are not returned. The meta information is available in the
428 \fBstate(meta) \fR variable after the transaction. See the
429 \fBSTATE ARRAY\fR section for details.
430 .RE
431 .TP
432 \fB::http::formatQuery\fR \fIkey value\fR ?\fIkey value\fR ...?
433 .
434 This procedure does x-url-encoding of query data. It takes an even
435 number of arguments that are the keys and values of the query. It
436 encodes the keys and values, and generates one string that has the
437 proper & and = separators. The result is suitable for the
438 \fB\-query\fR value passed to \fB::http::geturl\fR.
439 .TP
440 \fB::http::quoteString\fR \fIvalue\fR
441 .
442 This procedure does x-url-encoding of string. It takes a single argument and
443 encodes it.
444 .TP
445 \fB::http::reset\fR \fItoken\fR ?\fIwhy\fR?
446 .
447 This command resets the HTTP transaction identified by \fItoken\fR, if any.
448 This sets the \fBstate(status)\fR value to \fIwhy\fR, which defaults to
449 \fBreset\fR, and then calls the registered \fB\-command\fR callback.
450 .TP
451 \fB::http::wait\fR \fItoken\fR
452 .
453 This is a convenience procedure that blocks and waits for the
454 transaction to complete. This only works in trusted code because it
455 uses \fBvwait\fR. Also, it is not useful for the case where
456 \fB::http::geturl\fR is called \fIwithout\fR the \fB\-command\fR option
457 because in this case the \fB::http::geturl\fR call does not return
458 until the HTTP transaction is complete, and thus there is nothing to
459 wait for.
460 .TP
461 \fB::http::data\fR \fItoken\fR
462 .
463 This is a convenience procedure that returns the \fBbody\fR element
464 (i.e., the URL data) of the state array.
465 .TP
466 \fB::http::error\fR \fItoken\fR
467 .
468 This is a convenience procedure that returns the \fBerror\fR element
469 of the state array.
470 .TP
471 \fB::http::status\fR \fItoken\fR
472 .
473 This is a convenience procedure that returns the \fBstatus\fR element of
474 the state array.
475 .TP
476 \fB::http::code\fR \fItoken\fR
477 .
478 This is a convenience procedure that returns the \fBhttp\fR element of the
479 state array.
480 .TP
481 \fB::http::ncode\fR \fItoken\fR
482 .
483 This is a convenience procedure that returns just the numeric return
484 code (200, 404, etc.) from the \fBhttp\fR element of the state array.
485 .TP
486 \fB::http::size\fR \fItoken\fR
487 .
488 This is a convenience procedure that returns the \fBcurrentsize\fR
489 element of the state array, which represents the number of bytes
490 received from the URL in the \fB::http::geturl\fR call.
491 .TP
492 \fB::http::meta\fR \fItoken\fR
493 .
494 This is a convenience procedure that returns the \fBmeta\fR
495 element of the state array which contains the HTTP response
496 headers. See below for an explanation of this element.
497 .TP
498 \fB::http::cleanup\fR \fItoken\fR
499 .
500 This procedure cleans up the state associated with the connection
501 identified by \fItoken\fR. After this call, the procedures
502 like \fB::http::data\fR cannot be used to get information
503 about the operation. It is \fIstrongly\fR recommended that you call
504 this function after you are done with a given HTTP request. Not doing
505 so will result in memory not being freed, and if your app calls
506 \fB::http::geturl\fR enough times, the memory leak could cause a
507 performance hit...or worse.
508 .TP
509 \fB::http::register\fR \fIproto port command\fR
510 .
511 This procedure allows one to provide custom HTTP transport types
512 such as HTTPS, by registering a prefix, the default port, and the
513 command to execute to create the Tcl \fBchannel\fR. E.g.:
514 .RS
515 .PP
516 .CS
517 package require http
518 package require tls
519
520 ::http::register https 443 ::tls::socket
521
522 set token [::http::geturl https://my.secure.site/]
523 .CE
524 .RE
525 .TP
526 \fB::http::registerError\fR \fIport\fR ?\fImessage\fR?
527 .
528 This procedure allows a registered protocol handler to deliver an error
529 message for use by \fBhttp\fR. Calling this command does not raise an
530 error. The command is useful when a registered protocol detects an problem
531 (for example, an invalid TLS certificate) that will cause an error to
532 propagate to \fBhttp\fR. The command allows \fBhttp\fR to provide a
533 precise error message rather than a general one. The command returns the
534 value provided by the last call with argument \fImessage\fR, or the empty
535 string if no such call has been made.
536 .TP
537 \fB::http::unregister\fR \fIproto\fR
538 .
539 This procedure unregisters a protocol handler that was previously
540 registered via \fB::http::register\fR, returning a two-item list of
541 the default port and handler command that was previously installed
542 (via \fB::http::register\fR) if there was such a handler, and an error if
543 there was no such handler.
544 .SH ERRORS
545 The \fB::http::geturl\fR procedure will raise errors in the following cases:
546 invalid command line options,
547 an invalid URL,
548 a URL on a non-existent host,
549 or a URL at a bad port on an existing host.
550 These errors mean that it
551 cannot even start the network transaction.
552 It will also raise an error if it gets an I/O error while
553 writing out the HTTP request header.
554 For synchronous \fB::http::geturl\fR calls (where \fB\-command\fR is
555 not specified), it will raise an error if it gets an I/O error while
556 reading the HTTP reply headers or data. Because \fB::http::geturl\fR
557 does not return a token in these cases, it does all the required
558 cleanup and there is no issue of your app having to call
559 \fB::http::cleanup\fR.
560 .PP
561 For asynchronous \fB::http::geturl\fR calls, all of the above error
562 situations apply, except that if there is any error while reading the
563 HTTP reply headers or data, no exception is thrown. This is because
564 after writing the HTTP headers, \fB::http::geturl\fR returns, and the
565 rest of the HTTP transaction occurs in the background. The command
566 callback can check if any error occurred during the read by calling
567 \fB::http::status\fR to check the status and if its \fIerror\fR,
568 calling \fB::http::error\fR to get the error message.
569 .PP
570 Alternatively, if the main program flow reaches a point where it needs
571 to know the result of the asynchronous HTTP request, it can call
572 \fB::http::wait\fR and then check status and error, just as the
573 callback does.
574 .PP
575 The \fB::http::geturl\fR command runs the \fB\-command\fR, \fB\-handler\fR,
576 and \fB\-proxyfilter\fR callbacks inside a \fBcatch\fR command. Therefore
577 an error in the callback command does not call the \fBbgerror\fR handler.
578 When debugging one of these
579 callbacks, it may be convenient to report errors by using a
580 \fBcatch\fR command within the callback command itself, e.g. to write
581 an error message to stdout.
582 .PP
583 In any case, you must still call
584 \fB::http::cleanup\fR to delete the state array when you are done.
585 .PP
586 There are other possible results of the HTTP transaction
587 determined by examining the status from \fB::http::status\fR.
588 These are described below.
589 .TP
590 \fBok\fR
591 .
592 If the HTTP transaction completes entirely, then status will be \fBok\fR.
593 However, you should still check the \fB::http::code\fR value to get
594 the HTTP status. The \fB::http::ncode\fR procedure provides just
595 the numeric error (e.g., 200, 404 or 500) while the \fB::http::code\fR
596 procedure returns a value like
597 .QW "HTTP 404 File not found" .
598 .TP
599 \fBeof\fR
600 .
601 If the server closes the socket without replying, then no error
602 is raised, but the status of the transaction will be \fBeof\fR.
603 .TP
604 \fBerror\fR
605 .
606 The error message will also be stored in the \fBerror\fR status
607 array element, accessible via \fB::http::error\fR.
608 .TP
609 \fBtimeout\fR
610 .
611 A timeout occurred before the transaction could complete
612 .TP
613 \fBreset\fR
614 .
615 user-reset
616 .PP
617 Another error possibility is that \fB::http::geturl\fR is unable to
618 write all the post query data to the server before the server
619 responds and closes the socket.
620 The error message is saved in the \fBposterror\fR status array
621 element and then \fB::http::geturl\fR attempts to complete the
622 transaction.
623 If it can read the server's response
624 it will end up with an \fBok\fR status, otherwise it will have
625 an \fBeof\fR status.
626 .SH "STATE ARRAY"
627 The \fB::http::geturl\fR procedure returns a \fItoken\fR that can be used to
628 get to the state of the HTTP transaction in the form of a Tcl array.
629 Use this construct to create an easy-to-use array variable:
630 .PP
631 .CS
632 upvar #0 $token state
633 .CE
634 .PP
635 Once the data associated with the URL is no longer needed, the state
636 array should be unset to free up storage.
637 The \fB::http::cleanup\fR procedure is provided for that purpose.
638 The following elements of
639 the array are supported:
640 .RS
641 .TP
642 \fBbinary\fR
643 .
644 This is boolean \fBtrue\fR if (after decoding any compression specified
645 by the
646 .QW "Content-Encoding"
647 response header) the HTTP response is binary. It is boolean \fBfalse\fR
648 if the HTTP response is text.
649 .TP
650 \fBbody\fR
651 .
652 The contents of the URL. This will be empty if the \fB\-channel\fR
653 option has been specified. This value is returned by the \fB::http::data\fR
654 command.
655 .TP
656 \fBcharset\fR
657 .
658 The value of the charset attribute from the \fBContent-Type\fR meta-data
659 value. If none was specified, this defaults to the RFC standard
660 \fBiso8859-1\fR, or the value of \fB$::http::defaultCharset\fR. Incoming
661 text data will be automatically converted from this charset to utf-8.
662 .TP
663 \fBcoding\fR
664 .
665 A copy of the \fBContent-Encoding\fR meta-data value.
666 .TP
667 \fBcurrentsize\fR
668 .
669 The current number of bytes fetched from the URL.
670 This value is returned by the \fB::http::size\fR command.
671 .TP
672 \fBerror\fR
673 .
674 If defined, this is the error string seen when the HTTP transaction
675 was aborted.
676 .TP
677 \fBhttp\fR
678 .
679 The HTTP status reply from the server. This value
680 is returned by the \fB::http::code\fR command. The format of this value is:
681 .RS
682 .PP
683 .CS
684 \fIHTTP/1.1 code string\fR
685 .CE
686 .PP
687 The \fIcode\fR is a three-digit number defined in the HTTP standard.
688 A code of 200 is OK. Codes beginning with 4 or 5 indicate errors.
689 Codes beginning with 3 are redirection errors. In this case the
690 \fBLocation\fR meta-data specifies a new URL that contains the
691 requested information.
692 .RE
693 .TP
694 \fBmeta\fR
695 .
696 The HTTP protocol returns meta-data that describes the URL contents.
697 The \fBmeta\fR element of the state array is a list of the keys and
698 values of the meta-data. This is in a format useful for initializing
699 an array that just contains the meta-data:
700 .RS
701 .PP
702 .CS
703 array set meta $state(meta)
704 .CE
705 .PP
706 Some of the meta-data keys are listed below, but the HTTP standard defines
707 more, and servers are free to add their own.
708 .TP
709 \fBContent-Type\fR
710 .
711 The type of the URL contents. Examples include \fBtext/html\fR,
712 \fBimage/gif,\fR \fBapplication/postscript\fR and
713 \fBapplication/x-tcl\fR.
714 .TP
715 \fBContent-Length\fR
716 .
717 The advertised size of the contents. The actual size obtained by
718 \fB::http::geturl\fR is available as \fBstate(currentsize)\fR.
719 .TP
720 \fBLocation\fR
721 .
722 An alternate URL that contains the requested data.
723 .RE
724 .TP
725 \fBposterror\fR
726 .
727 The error, if any, that occurred while writing
728 the post query data to the server.
729 .TP
730 \fBstatus\fR
731 .
732 See description in the chapter \fBERRORS\fR above for a
733 list and description of \fBstatus\fR.
734 During the transaction this value is the empty string.
735 .TP
736 \fBtotalsize\fR
737 .
738 A copy of the \fBContent-Length\fR meta-data value.
739 .TP
740 \fBtype\fR
741 .
742 A copy of the \fBContent-Type\fR meta-data value.
743 .TP
744 \fBurl\fR
745 .
746 The requested URL.
747 .RE
748 .SH "PERSISTENT CONNECTIONS"
749 .PP
750 .SS "BASICS"
751 .PP
752 See RFC 7230 Sec 6, which supersedes RFC 2616 Sec 8.1.
753 .PP
754 A persistent connection allows multiple HTTP/1.1 transactions to be
755 carried over the same TCP connection. Pipelining allows a
756 client to make multiple requests over a persistent connection without
757 waiting for each response. The server sends responses in the same order
758 that the requests were received.
759 .PP
760 If a POST request fails to complete, typically user confirmation is
761 needed before sending the request again. The user may wish to verify
762 whether the server was modified by the failed POST request, before
763 sending the same request again.
764 .PP
765 A HTTP request will use a persistent socket if the call to
766 \fBhttp::geturl\fR has the option \fB\-keepalive true\fR. It will use
767 pipelining where permitted if the \fBhttp::config\fR option
768 \fB\-pipeline\fR is boolean \fBtrue\fR (its default value).
769 .PP
770 The http package maintains no more than one persistent connection to each
771 server (i.e. each value of
772 .QW "domain:port" ).
773 If \fBhttp::geturl\fR is called to make a request over a persistent
774 connection while the connection is busy with another request, the new
775 request will be held in a queue until the connection is free.
776 .PP
777 The http package does not support HTTP/1.0 persistent connections
778 controlled by the \fBKeep-Alive\fR header.
779 .SS "SPECIAL CASES"
780 .PP
781 This subsection discusses issues related to closure of the
782 persistent connection by the server, automatic retry of failed requests,
783 the special treatment necessary for POST requests, and the options for
784 dealing with these cases.
785 .PP
786 In accordance with RFC 7230, \fBhttp::geturl\fR does not pipeline
787 requests that use the POST method. If a POST uses a persistent
788 connection and is not the first request on that connection,
789 \fBhttp::geturl\fR waits until it has received the response for the previous
790 request; or (if \fBhttp::config\fR option \fB\-postfresh\fR is boolean
791 \fBtrue\fR) it uses a new connection for each POST.
792 .PP
793 If the server is processing a number of pipelined requests, and sends a
794 response header
795 .QW "\fBConnection: close\fR"
796 with one of the responses (other than the last), then subsequent responses
797 are unfulfilled. \fBhttp::geturl\fR will send the unfulfilled requests again
798 over a new connection.
799 .PP
800 A difficulty arises when a HTTP client sends a request over a persistent
801 connection that has been idle for a while. The HTTP server may
802 half-close an apparently idle connection while the client is sending a
803 request, but before the request arrives at the server: in this case (an
804 .QW "asynchronous close event" )
805 the request will fail. The difficulty arises because the client cannot
806 be certain whether the POST modified the state of the server. For HEAD or
807 GET requests, \fBhttp::geturl\fR opens another connection and retransmits
808 the failed request. However, if the request was a POST, RFC 7230 forbids
809 automatic retry by default, suggesting either user confirmation, or
810 confirmation by user-agent software that has semantic understanding of
811 the application. The \fBhttp::config\fR option \fB\-repost\fR allows for
812 either possibility.
813 .PP
814 Asynchronous close events can occur only in a short interval of time. The
815 \fBhttp\fR package monitors each persistent connection for closure by the
816 server. Upon detection, the connection is also closed at the client end,
817 and subsequent requests will use a fresh connection.
818 .PP
819 If the \fBhttp::geturl\fR command is called with option \fB\-keepalive true\fR,
820 then it will both try to use an existing persistent connection
821 (if one is available), and it will send the server a
822 .QW "\fBConnection: keep-alive\fR"
823 request header asking to keep the connection open for future requests.
824 .PP
825 The \fBhttp::config\fR options \fB\-pipeline\fR, \fB\-postfresh\fR, and
826 \fB\-repost\fR relate to persistent connections.
827 .PP
828 Option \fB\-pipeline\fR, if boolean \fBtrue\fR, will pipeline GET and HEAD
829 requests made over a persistent connection. POST requests will not be
830 pipelined - if the
831 POST is not the first transaction on the connection, its request will not
832 be sent until the previous response has finished. GET and HEAD requests
833 made after a POST will not be sent until the POST response has been
834 delivered, and will not be sent if the POST fails.
835 .PP
836 Option \fB\-postfresh\fR, if boolean \fBtrue\fR, will override the
837 \fBhttp::geturl\fR option \fB\-keepalive\fR, and always open a fresh connection
838 for a POST request.
839 .PP
840 Option \fB\-repost\fR, if \fBtrue\fR, permits automatic retry of a POST request
841 that fails because it uses a persistent connection that the server has
842 half-closed (an
843 .QW "asynchronous close event" ).
844 Subsequent GET and HEAD requests in a failed pipeline will also be retried.
845 \fIThe \-repost option should be used only if the application understands
846 that the retry is appropriate\fR - specifically, the application must know
847 that if the failed POST successfully modified the state of the server, a repeat
848 POST would have no adverse effect.
849 .SH "PROTOCOL UPGRADES"
850 .PP
851 The HTTP/1.1 \fBConnection\fR and \fBUpgrade\fR client headers inform the server
852 that the client wishes to change the protocol used over the existing connection
853 (RFC 7230). This mechanism can be used to request a WebSocket (RFC 6455), a
854 higher version of the HTTP protocol (HTTP 2), or TLS encryption. If the
855 server accepts the upgrade request, its response code will be 101.
856 .PP
857 To request a protocol upgrade when calling \fBhttp::geturl\fR, the \fB\-headers\fR
858 option must supply appropriate values for \fBConnection\fR and \fBUpgrade\fR, and
859 the \fB\-command\fR option must supply a command that implements the requested
860 protocol and can also handle the server response if the server refuses the
861 protocol upgrade. For upgrade requests \fBhttp::geturl\fR ignores the value of
862 option \fB\-keepalive\fR, and always uses the value \fB0\fR so that the upgrade
863 request is not made over a connection that is intended for multiple HTTP requests.
864 .PP
865 The Tcllib library \fBwebsocket\fR implements WebSockets, and makes the necessary
866 calls to commands in the \fBhttp\fR package.
867 .PP
868 There is currently no native Tcl client library for HTTP/2.
869 .PP
870 The \fBUpgrade\fR mechanism is not used to request TLS in web browsers, because
871 \fBhttp\fR and \fBhttps\fR are served over different ports. It is used by
872 protocols such as Internet Printing Protocol (IPP) that are built on top of
873 \fBhttp(s)\fR and use the same TCP port number for both secure and insecure
874 traffic.
875 .PP
876 In browsers, opportunistic encryption is instead implemented by the
877 \fBUpgrade-Insecure-Requests\fR client header. If a secure service is available,
878 the server response code is a 307 redirect, and the response header
879 \fBLocation\fR specifies the target URL. The browser must call \fBhttp::geturl\fR
880 again in order to fetch this URL.
881 See https://w3c.github.io/webappsec-upgrade-insecure-requests/
882 .PP
883 .SH EXAMPLE
884 .PP
885 This example creates a procedure to copy a URL to a file while printing a
886 progress meter, and prints the meta-data associated with the URL.
887 .PP
888 .CS
889 proc httpcopy { url file {chunk 4096} } {
890 set out [open $file w]
891 set token [\fB::http::geturl\fR $url -channel $out \e
892 -progress httpCopyProgress -blocksize $chunk]
893 close $out
894
895 # This ends the line started by httpCopyProgress
896 puts stderr ""
897
898 upvar #0 $token state
899 set max 0
900 foreach {name value} $state(meta) {
901 if {[string length $name] > $max} {
902 set max [string length $name]
903 }
904 if {[regexp -nocase ^location$ $name]} {
905 # Handle URL redirects
906 puts stderr "Location:$value"
907 return [httpcopy [string trim $value] $file $chunk]
908 }
909 }
910 incr max
911 foreach {name value} $state(meta) {
912 puts [format "%-*s %s" $max $name: $value]
913 }
914
915 return $token
916 }
917 proc httpCopyProgress {args} {
918 puts \-nonewline stderr .
919 flush stderr
920 }
921 .CE
922 .SH "SEE ALSO"
923 safe(n), socket(n), safesock(n)
924 .SH KEYWORDS
925 internet, security policy, socket, www
926 '\" Local Variables:
927 '\" mode: nroff
928 '\" End: