| 1 |
# http.tcl -- |
| 2 |
# |
| 3 |
# Client-side HTTP for GET, POST, and HEAD commands. These routines can |
| 4 |
# be used in untrusted code that uses the Safesock security policy. |
| 5 |
# These procedures use a callback interface to avoid using vwait, which |
| 6 |
# is not defined in the safe base. |
| 7 |
# |
| 8 |
# See the file "license.terms" for information on usage and redistribution of |
| 9 |
# this file, and for a DISCLAIMER OF ALL WARRANTIES. |
| 10 |
|
| 11 |
package require Tcl 8.6- |
| 12 |
# Keep this in sync with pkgIndex.tcl and with the install directories in |
| 13 |
# Makefiles |
| 14 |
package provide http 2.9.9 |
| 15 |
|
| 16 |
namespace eval http { |
| 17 |
# Allow resourcing to not clobber existing data |
| 18 |
|
| 19 |
variable http |
| 20 |
if {![info exists http]} { |
| 21 |
array set http { |
| 22 |
-accept */* |
| 23 |
-pipeline 1 |
| 24 |
-postfresh 0 |
| 25 |
-proxyhost {} |
| 26 |
-proxyport {} |
| 27 |
-proxyfilter http::ProxyRequired |
| 28 |
-repost 0 |
| 29 |
-urlencoding utf-8 |
| 30 |
-zip 1 |
| 31 |
} |
| 32 |
# We need a useragent string of this style or various servers will |
| 33 |
# refuse to send us compressed content even when we ask for it. This |
| 34 |
# follows the de-facto layout of user-agent strings in current browsers. |
| 35 |
# Safe interpreters do not have ::tcl_platform(os) or |
| 36 |
# ::tcl_platform(osVersion). |
| 37 |
if {[interp issafe]} { |
| 38 |
set http(-useragent) "Mozilla/5.0\ |
| 39 |
(Windows; U;\ |
| 40 |
Windows NT 10.0)\ |
| 41 |
http/[package provide http] Tcl/[package provide Tcl]" |
| 42 |
} else { |
| 43 |
set http(-useragent) "Mozilla/5.0\ |
| 44 |
([string totitle $::tcl_platform(platform)]; U;\ |
| 45 |
$::tcl_platform(os) $::tcl_platform(osVersion))\ |
| 46 |
http/[package provide http] Tcl/[package provide Tcl]" |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
proc init {} { |
| 51 |
# Set up the map for quoting chars. RFC3986 Section 2.3 say percent |
| 52 |
# encode all except: "... percent-encoded octets in the ranges of |
| 53 |
# ALPHA (%41-%5A and %61-%7A), DIGIT (%30-%39), hyphen (%2D), period |
| 54 |
# (%2E), underscore (%5F), or tilde (%7E) should not be created by URI |
| 55 |
# producers ..." |
| 56 |
for {set i 0} {$i <= 256} {incr i} { |
| 57 |
set c [format %c $i] |
| 58 |
if {![string match {[-._~a-zA-Z0-9]} $c]} { |
| 59 |
set map($c) %[format %.2X $i] |
| 60 |
} |
| 61 |
} |
| 62 |
# These are handled specially |
| 63 |
set map(\n) %0D%0A |
| 64 |
variable formMap [array get map] |
| 65 |
|
| 66 |
# Create a map for HTTP/1.1 open sockets |
| 67 |
variable socketMapping |
| 68 |
variable socketRdState |
| 69 |
variable socketWrState |
| 70 |
variable socketRdQueue |
| 71 |
variable socketWrQueue |
| 72 |
variable socketClosing |
| 73 |
variable socketPlayCmd |
| 74 |
if {[info exists socketMapping]} { |
| 75 |
# Close open sockets on re-init. Do not permit retries. |
| 76 |
foreach {url sock} [array get socketMapping] { |
| 77 |
unset -nocomplain socketClosing($url) |
| 78 |
unset -nocomplain socketPlayCmd($url) |
| 79 |
CloseSocket $sock |
| 80 |
} |
| 81 |
} |
| 82 |
|
| 83 |
# CloseSocket should have unset the socket* arrays, one element at |
| 84 |
# a time. Now unset anything that was overlooked. |
| 85 |
# Traces on "unset socketRdState(*)" will call CancelReadPipeline and |
| 86 |
# cancel any queued responses. |
| 87 |
# Traces on "unset socketWrState(*)" will call CancelWritePipeline and |
| 88 |
# cancel any queued requests. |
| 89 |
array unset socketMapping |
| 90 |
array unset socketRdState |
| 91 |
array unset socketWrState |
| 92 |
array unset socketRdQueue |
| 93 |
array unset socketWrQueue |
| 94 |
array unset socketClosing |
| 95 |
array unset socketPlayCmd |
| 96 |
array set socketMapping {} |
| 97 |
array set socketRdState {} |
| 98 |
array set socketWrState {} |
| 99 |
array set socketRdQueue {} |
| 100 |
array set socketWrQueue {} |
| 101 |
array set socketClosing {} |
| 102 |
array set socketPlayCmd {} |
| 103 |
} |
| 104 |
init |
| 105 |
|
| 106 |
variable urlTypes |
| 107 |
if {![info exists urlTypes]} { |
| 108 |
set urlTypes(http) [list 80 ::socket] |
| 109 |
} |
| 110 |
|
| 111 |
variable encodings [string tolower [encoding names]] |
| 112 |
# This can be changed, but iso8859-1 is the RFC standard. |
| 113 |
variable defaultCharset |
| 114 |
if {![info exists defaultCharset]} { |
| 115 |
set defaultCharset "iso8859-1" |
| 116 |
} |
| 117 |
|
| 118 |
# Force RFC 3986 strictness in geturl url verification? |
| 119 |
variable strict |
| 120 |
if {![info exists strict]} { |
| 121 |
set strict 1 |
| 122 |
} |
| 123 |
|
| 124 |
# Let user control default keepalive for compatibility |
| 125 |
variable defaultKeepalive |
| 126 |
if {![info exists defaultKeepalive]} { |
| 127 |
set defaultKeepalive 0 |
| 128 |
} |
| 129 |
|
| 130 |
namespace export geturl config reset wait formatQuery quoteString |
| 131 |
namespace export register unregister registerError |
| 132 |
# - Useful, but not exported: data, size, status, code, cleanup, error, |
| 133 |
# meta, ncode, mapReply, init. Comments suggest that "init" can be used |
| 134 |
# for re-initialisation, although the command is undocumented. |
| 135 |
# - Not exported, probably should be upper-case initial letter as part |
| 136 |
# of the internals: getTextLine, make-transformation-chunked. |
| 137 |
} |
| 138 |
|
| 139 |
# http::Log -- |
| 140 |
# |
| 141 |
# Debugging output -- define this to observe HTTP/1.1 socket usage. |
| 142 |
# Should echo any args received. |
| 143 |
# |
| 144 |
# Arguments: |
| 145 |
# msg Message to output |
| 146 |
# |
| 147 |
if {[info command http::Log] eq {}} {proc http::Log {args} {}} |
| 148 |
|
| 149 |
# http::register -- |
| 150 |
# |
| 151 |
# See documentation for details. |
| 152 |
# |
| 153 |
# Arguments: |
| 154 |
# proto URL protocol prefix, e.g. https |
| 155 |
# port Default port for protocol |
| 156 |
# command Command to use to create socket |
| 157 |
# Results: |
| 158 |
# list of port and command that was registered. |
| 159 |
|
| 160 |
proc http::register {proto port command} { |
| 161 |
variable urlTypes |
| 162 |
set urlTypes([string tolower $proto]) [list $port $command] |
| 163 |
} |
| 164 |
|
| 165 |
# http::unregister -- |
| 166 |
# |
| 167 |
# Unregisters URL protocol handler |
| 168 |
# |
| 169 |
# Arguments: |
| 170 |
# proto URL protocol prefix, e.g. https |
| 171 |
# Results: |
| 172 |
# list of port and command that was unregistered. |
| 173 |
|
| 174 |
proc http::unregister {proto} { |
| 175 |
variable urlTypes |
| 176 |
set lower [string tolower $proto] |
| 177 |
if {![info exists urlTypes($lower)]} { |
| 178 |
return -code error "unsupported url type \"$proto\"" |
| 179 |
} |
| 180 |
set old $urlTypes($lower) |
| 181 |
unset urlTypes($lower) |
| 182 |
return $old |
| 183 |
} |
| 184 |
|
| 185 |
# http::config -- |
| 186 |
# |
| 187 |
# See documentation for details. |
| 188 |
# |
| 189 |
# Arguments: |
| 190 |
# args Options parsed by the procedure. |
| 191 |
# Results: |
| 192 |
# TODO |
| 193 |
|
| 194 |
proc http::config {args} { |
| 195 |
variable http |
| 196 |
set options [lsort [array names http -*]] |
| 197 |
set usage [join $options ", "] |
| 198 |
if {[llength $args] == 0} { |
| 199 |
set result {} |
| 200 |
foreach name $options { |
| 201 |
lappend result $name $http($name) |
| 202 |
} |
| 203 |
return $result |
| 204 |
} |
| 205 |
set options [string map {- ""} $options] |
| 206 |
set pat ^-(?:[join $options |])$ |
| 207 |
if {[llength $args] == 1} { |
| 208 |
set flag [lindex $args 0] |
| 209 |
if {![regexp -- $pat $flag]} { |
| 210 |
return -code error "Unknown option $flag, must be: $usage" |
| 211 |
} |
| 212 |
return $http($flag) |
| 213 |
} else { |
| 214 |
foreach {flag value} $args { |
| 215 |
if {![regexp -- $pat $flag]} { |
| 216 |
return -code error "Unknown option $flag, must be: $usage" |
| 217 |
} |
| 218 |
set http($flag) $value |
| 219 |
} |
| 220 |
} |
| 221 |
} |
| 222 |
|
| 223 |
# http::Finish -- |
| 224 |
# |
| 225 |
# Clean up the socket and eval close time callbacks |
| 226 |
# |
| 227 |
# Arguments: |
| 228 |
# token Connection token. |
| 229 |
# errormsg (optional) If set, forces status to error. |
| 230 |
# skipCB (optional) If set, don't call the -command callback. This |
| 231 |
# is useful when geturl wants to throw an exception instead |
| 232 |
# of calling the callback. That way, the same error isn't |
| 233 |
# reported to two places. |
| 234 |
# |
| 235 |
# Side Effects: |
| 236 |
# May close the socket. |
| 237 |
|
| 238 |
proc http::Finish {token {errormsg ""} {skipCB 0}} { |
| 239 |
variable socketMapping |
| 240 |
variable socketRdState |
| 241 |
variable socketWrState |
| 242 |
variable socketRdQueue |
| 243 |
variable socketWrQueue |
| 244 |
variable socketClosing |
| 245 |
variable socketPlayCmd |
| 246 |
|
| 247 |
variable $token |
| 248 |
upvar 0 $token state |
| 249 |
global errorInfo errorCode |
| 250 |
set closeQueue 0 |
| 251 |
if {$errormsg ne ""} { |
| 252 |
set state(error) [list $errormsg $errorInfo $errorCode] |
| 253 |
set state(status) "error" |
| 254 |
} |
| 255 |
if {[info commands ${token}EventCoroutine] ne {}} { |
| 256 |
rename ${token}EventCoroutine {} |
| 257 |
} |
| 258 |
|
| 259 |
# Is this an upgrade request/response? |
| 260 |
set upgradeResponse \ |
| 261 |
[expr { [info exists state(upgradeRequest)] && $state(upgradeRequest) |
| 262 |
&& [info exists state(http)] && [ncode $token] eq {101} |
| 263 |
&& [info exists state(connection)] && "upgrade" in $state(connection) |
| 264 |
&& [info exists state(upgrade)] && "" ne $state(upgrade)}] |
| 265 |
|
| 266 |
if { ($state(status) eq "timeout") |
| 267 |
|| ($state(status) eq "error") |
| 268 |
|| ($state(status) eq "eof") |
| 269 |
} { |
| 270 |
set closeQueue 1 |
| 271 |
set connId $state(socketinfo) |
| 272 |
set sock $state(sock) |
| 273 |
CloseSocket $state(sock) $token |
| 274 |
} elseif {$upgradeResponse} { |
| 275 |
# Special handling for an upgrade request/response. |
| 276 |
# - geturl ensures that this is not a "persistent" socket used for |
| 277 |
# multiple HTTP requests, so a call to KeepSocket is not needed. |
| 278 |
# - Leave socket open, so a call to CloseSocket is not needed either. |
| 279 |
# - Remove fileevent bindings. The caller will set its own bindings. |
| 280 |
# - THE CALLER MUST PROCESS THE UPGRADED SOCKET IN THE CALLBACK COMMAND |
| 281 |
# PASSED TO http::geturl AS -command callback. |
| 282 |
catch {fileevent $state(sock) readable {}} |
| 283 |
catch {fileevent $state(sock) writable {}} |
| 284 |
} elseif {([info exists state(-keepalive)] && !$state(-keepalive)) |
| 285 |
|| ([info exists state(connection)] && ("close" in $state(connection))) |
| 286 |
} { |
| 287 |
set closeQueue 1 |
| 288 |
set connId $state(socketinfo) |
| 289 |
set sock $state(sock) |
| 290 |
CloseSocket $state(sock) $token |
| 291 |
} elseif { |
| 292 |
([info exists state(-keepalive)] && $state(-keepalive)) |
| 293 |
&& ([info exists state(connection)] && ("close" ni $state(connection))) |
| 294 |
} { |
| 295 |
KeepSocket $token |
| 296 |
} |
| 297 |
if {[info exists state(after)]} { |
| 298 |
after cancel $state(after) |
| 299 |
unset state(after) |
| 300 |
} |
| 301 |
if {[info exists state(-command)] && (!$skipCB) |
| 302 |
&& (![info exists state(done-command-cb)])} { |
| 303 |
set state(done-command-cb) yes |
| 304 |
if {[catch {eval $state(-command) {$token}} err] && $errormsg eq ""} { |
| 305 |
set state(error) [list $err $errorInfo $errorCode] |
| 306 |
set state(status) error |
| 307 |
} |
| 308 |
} |
| 309 |
|
| 310 |
if { $closeQueue |
| 311 |
&& [info exists socketMapping($connId)] |
| 312 |
&& ($socketMapping($connId) eq $sock) |
| 313 |
} { |
| 314 |
http::CloseQueuedQueries $connId $token |
| 315 |
} |
| 316 |
} |
| 317 |
|
| 318 |
# http::KeepSocket - |
| 319 |
# |
| 320 |
# Keep a socket in the persistent sockets table and connect it to its next |
| 321 |
# queued task if possible. Otherwise leave it idle and ready for its next |
| 322 |
# use. |
| 323 |
# |
| 324 |
# If $socketClosing(*), then ("close" in $state(connection)) and therefore |
| 325 |
# this command will not be called by Finish. |
| 326 |
# |
| 327 |
# Arguments: |
| 328 |
# token Connection token. |
| 329 |
|
| 330 |
proc http::KeepSocket {token} { |
| 331 |
variable http |
| 332 |
variable socketMapping |
| 333 |
variable socketRdState |
| 334 |
variable socketWrState |
| 335 |
variable socketRdQueue |
| 336 |
variable socketWrQueue |
| 337 |
variable socketClosing |
| 338 |
variable socketPlayCmd |
| 339 |
|
| 340 |
variable $token |
| 341 |
upvar 0 $token state |
| 342 |
set tk [namespace tail $token] |
| 343 |
|
| 344 |
# Keep this socket open for another request ("Keep-Alive"). |
| 345 |
# React if the server half-closes the socket. |
| 346 |
# Discussion is in http::geturl. |
| 347 |
catch {fileevent $state(sock) readable [list http::CheckEof $state(sock)]} |
| 348 |
|
| 349 |
# The line below should not be changed in production code. |
| 350 |
# It is edited by the test suite. |
| 351 |
set TEST_EOF 0 |
| 352 |
if {$TEST_EOF} { |
| 353 |
# ONLY for testing reaction to server eof. |
| 354 |
# No server timeouts will be caught. |
| 355 |
catch {fileevent $state(sock) readable {}} |
| 356 |
} |
| 357 |
|
| 358 |
if { [info exists state(socketinfo)] |
| 359 |
&& [info exists socketMapping($state(socketinfo))] |
| 360 |
} { |
| 361 |
set connId $state(socketinfo) |
| 362 |
# The value "Rready" is set only here. |
| 363 |
set socketRdState($connId) Rready |
| 364 |
|
| 365 |
if { $state(-pipeline) |
| 366 |
&& [info exists socketRdQueue($connId)] |
| 367 |
&& [llength $socketRdQueue($connId)] |
| 368 |
} { |
| 369 |
# The usual case for pipelined responses - if another response is |
| 370 |
# queued, arrange to read it. |
| 371 |
set token3 [lindex $socketRdQueue($connId) 0] |
| 372 |
set socketRdQueue($connId) [lrange $socketRdQueue($connId) 1 end] |
| 373 |
variable $token3 |
| 374 |
upvar 0 $token3 state3 |
| 375 |
set tk2 [namespace tail $token3] |
| 376 |
|
| 377 |
#Log pipelined, GRANT read access to $token3 in KeepSocket |
| 378 |
set socketRdState($connId) $token3 |
| 379 |
ReceiveResponse $token3 |
| 380 |
|
| 381 |
# Other pipelined cases. |
| 382 |
# - The test above ensures that, for the pipelined cases in the two |
| 383 |
# tests below, the read queue is empty. |
| 384 |
# - In those two tests, check whether the next write will be |
| 385 |
# nonpipeline. |
| 386 |
} elseif { |
| 387 |
$state(-pipeline) |
| 388 |
&& [info exists socketWrState($connId)] |
| 389 |
&& ($socketWrState($connId) eq "peNding") |
| 390 |
|
| 391 |
&& [info exists socketWrQueue($connId)] |
| 392 |
&& [llength $socketWrQueue($connId)] |
| 393 |
&& (![set token3 [lindex $socketWrQueue($connId) 0] |
| 394 |
set ${token3}(-pipeline) |
| 395 |
] |
| 396 |
) |
| 397 |
} { |
| 398 |
# This case: |
| 399 |
# - Now it the time to run the "pending" request. |
| 400 |
# - The next token in the write queue is nonpipeline, and |
| 401 |
# socketWrState has been marked "pending" (in |
| 402 |
# http::NextPipelinedWrite or http::geturl) so a new pipelined |
| 403 |
# request cannot jump the queue. |
| 404 |
# |
| 405 |
# Tests: |
| 406 |
# - In this case the read queue (tested above) is empty and this |
| 407 |
# "pending" write token is in front of the rest of the write |
| 408 |
# queue. |
| 409 |
# - The write state is not Wready and therefore appears to be busy, |
| 410 |
# but because it is "pending" we know that it is reserved for the |
| 411 |
# first item in the write queue, a non-pipelined request that is |
| 412 |
# waiting for the read queue to empty. That has now happened: so |
| 413 |
# give that request read and write access. |
| 414 |
variable $token3 |
| 415 |
set conn [set ${token3}(tmpConnArgs)] |
| 416 |
#Log nonpipeline, GRANT r/w access to $token3 in KeepSocket |
| 417 |
set socketRdState($connId) $token3 |
| 418 |
set socketWrState($connId) $token3 |
| 419 |
set socketWrQueue($connId) [lrange $socketWrQueue($connId) 1 end] |
| 420 |
# Connect does its own fconfigure. |
| 421 |
fileevent $state(sock) writable [list http::Connect $token3 {*}$conn] |
| 422 |
#Log ---- $state(sock) << conn to $token3 for HTTP request (c) |
| 423 |
|
| 424 |
} elseif { |
| 425 |
$state(-pipeline) |
| 426 |
&& [info exists socketWrState($connId)] |
| 427 |
&& ($socketWrState($connId) eq "peNding") |
| 428 |
|
| 429 |
} { |
| 430 |
# Should not come here. The second block in the previous "elseif" |
| 431 |
# test should be tautologous (but was needed in an earlier |
| 432 |
# implementation) and will be removed after testing. |
| 433 |
# If we get here, the value "pending" was assigned in error. |
| 434 |
# This error would block the queue for ever. |
| 435 |
Log ^X$tk <<<<< Error in queueing of requests >>>>> - token $token |
| 436 |
|
| 437 |
} elseif { |
| 438 |
$state(-pipeline) |
| 439 |
&& [info exists socketWrState($connId)] |
| 440 |
&& ($socketWrState($connId) eq "Wready") |
| 441 |
|
| 442 |
&& [info exists socketWrQueue($connId)] |
| 443 |
&& [llength $socketWrQueue($connId)] |
| 444 |
&& (![set token3 [lindex $socketWrQueue($connId) 0] |
| 445 |
set ${token3}(-pipeline) |
| 446 |
] |
| 447 |
) |
| 448 |
} { |
| 449 |
# This case: |
| 450 |
# - The next token in the write queue is nonpipeline, and |
| 451 |
# socketWrState is Wready. Get the next event from socketWrQueue. |
| 452 |
# Tests: |
| 453 |
# - In this case the read state (tested above) is Rready and the |
| 454 |
# write state (tested here) is Wready - there is no "pending" |
| 455 |
# request. |
| 456 |
# Code: |
| 457 |
# - The code is the same as the code below for the nonpipelined |
| 458 |
# case with a queued request. |
| 459 |
variable $token3 |
| 460 |
set conn [set ${token3}(tmpConnArgs)] |
| 461 |
#Log nonpipeline, GRANT r/w access to $token3 in KeepSocket |
| 462 |
set socketRdState($connId) $token3 |
| 463 |
set socketWrState($connId) $token3 |
| 464 |
set socketWrQueue($connId) [lrange $socketWrQueue($connId) 1 end] |
| 465 |
# Connect does its own fconfigure. |
| 466 |
fileevent $state(sock) writable [list http::Connect $token3 {*}$conn] |
| 467 |
#Log ---- $state(sock) << conn to $token3 for HTTP request (c) |
| 468 |
|
| 469 |
} elseif { |
| 470 |
(!$state(-pipeline)) |
| 471 |
&& [info exists socketWrQueue($connId)] |
| 472 |
&& [llength $socketWrQueue($connId)] |
| 473 |
&& ("close" ni $state(connection)) |
| 474 |
} { |
| 475 |
# If not pipelined, (socketRdState eq Rready) tells us that we are |
| 476 |
# ready for the next write - there is no need to check |
| 477 |
# socketWrState. Write the next request, if one is waiting. |
| 478 |
# If the next request is pipelined, it receives premature read |
| 479 |
# access to the socket. This is not a problem. |
| 480 |
set token3 [lindex $socketWrQueue($connId) 0] |
| 481 |
variable $token3 |
| 482 |
set conn [set ${token3}(tmpConnArgs)] |
| 483 |
#Log nonpipeline, GRANT r/w access to $token3 in KeepSocket |
| 484 |
set socketRdState($connId) $token3 |
| 485 |
set socketWrState($connId) $token3 |
| 486 |
set socketWrQueue($connId) [lrange $socketWrQueue($connId) 1 end] |
| 487 |
# Connect does its own fconfigure. |
| 488 |
fileevent $state(sock) writable [list http::Connect $token3 {*}$conn] |
| 489 |
#Log ---- $state(sock) << conn to $token3 for HTTP request (d) |
| 490 |
|
| 491 |
} elseif {(!$state(-pipeline))} { |
| 492 |
set socketWrState($connId) Wready |
| 493 |
# Rready and Wready and idle: nothing to do. |
| 494 |
} |
| 495 |
|
| 496 |
} else { |
| 497 |
CloseSocket $state(sock) $token |
| 498 |
# There is no socketMapping($state(socketinfo)), so it does not matter |
| 499 |
# that CloseQueuedQueries is not called. |
| 500 |
} |
| 501 |
} |
| 502 |
|
| 503 |
# http::CheckEof - |
| 504 |
# |
| 505 |
# Read from a socket and close it if eof. |
| 506 |
# The command is bound to "fileevent readable" on an idle socket, and |
| 507 |
# "eof" is the only event that should trigger the binding, occurring when |
| 508 |
# the server times out and half-closes the socket. |
| 509 |
# |
| 510 |
# A read is necessary so that [eof] gives a meaningful result. |
| 511 |
# Any bytes sent are junk (or a bug). |
| 512 |
|
| 513 |
proc http::CheckEof {sock} { |
| 514 |
set junk [read $sock] |
| 515 |
set n [string length $junk] |
| 516 |
if {$n} { |
| 517 |
Log "WARNING: $n bytes received but no HTTP request sent" |
| 518 |
} |
| 519 |
|
| 520 |
if {[catch {eof $sock} res] || $res} { |
| 521 |
# The server has half-closed the socket. |
| 522 |
# If a new write has started, its transaction will fail and |
| 523 |
# will then be error-handled. |
| 524 |
CloseSocket $sock |
| 525 |
} |
| 526 |
} |
| 527 |
|
| 528 |
# http::CloseSocket - |
| 529 |
# |
| 530 |
# Close a socket and remove it from the persistent sockets table. If |
| 531 |
# possible an http token is included here but when we are called from a |
| 532 |
# fileevent on remote closure we need to find the correct entry - hence |
| 533 |
# the "else" block of the first "if" command. |
| 534 |
|
| 535 |
proc http::CloseSocket {s {token {}}} { |
| 536 |
variable socketMapping |
| 537 |
variable socketRdState |
| 538 |
variable socketWrState |
| 539 |
variable socketRdQueue |
| 540 |
variable socketWrQueue |
| 541 |
variable socketClosing |
| 542 |
variable socketPlayCmd |
| 543 |
|
| 544 |
set tk [namespace tail $token] |
| 545 |
|
| 546 |
catch {fileevent $s readable {}} |
| 547 |
set connId {} |
| 548 |
if {$token ne ""} { |
| 549 |
variable $token |
| 550 |
upvar 0 $token state |
| 551 |
if {[info exists state(socketinfo)]} { |
| 552 |
set connId $state(socketinfo) |
| 553 |
} |
| 554 |
} else { |
| 555 |
set map [array get socketMapping] |
| 556 |
set ndx [lsearch -exact $map $s] |
| 557 |
if {$ndx >= 0} { |
| 558 |
incr ndx -1 |
| 559 |
set connId [lindex $map $ndx] |
| 560 |
} |
| 561 |
} |
| 562 |
if { ($connId ne {}) |
| 563 |
&& [info exists socketMapping($connId)] |
| 564 |
&& ($socketMapping($connId) eq $s) |
| 565 |
} { |
| 566 |
Log "Closing connection $connId (sock $socketMapping($connId))" |
| 567 |
if {[catch {close $socketMapping($connId)} err]} { |
| 568 |
Log "Error closing connection: $err" |
| 569 |
} |
| 570 |
if {$token eq {}} { |
| 571 |
# Cases with a non-empty token are handled by Finish, so the tokens |
| 572 |
# are finished in connection order. |
| 573 |
http::CloseQueuedQueries $connId |
| 574 |
} |
| 575 |
} else { |
| 576 |
Log "Closing socket $s (no connection info)" |
| 577 |
if {[catch {close $s} err]} { |
| 578 |
Log "Error closing socket: $err" |
| 579 |
} |
| 580 |
} |
| 581 |
} |
| 582 |
|
| 583 |
# http::CloseQueuedQueries |
| 584 |
# |
| 585 |
# connId - identifier "domain:port" for the connection |
| 586 |
# token - (optional) used only for logging |
| 587 |
# |
| 588 |
# Called from http::CloseSocket and http::Finish, after a connection is closed, |
| 589 |
# to clear the read and write queues if this has not already been done. |
| 590 |
|
| 591 |
proc http::CloseQueuedQueries {connId {token {}}} { |
| 592 |
variable socketMapping |
| 593 |
variable socketRdState |
| 594 |
variable socketWrState |
| 595 |
variable socketRdQueue |
| 596 |
variable socketWrQueue |
| 597 |
variable socketClosing |
| 598 |
variable socketPlayCmd |
| 599 |
|
| 600 |
if {![info exists socketMapping($connId)]} { |
| 601 |
# Command has already been called. |
| 602 |
# Don't come here again - especially recursively. |
| 603 |
return |
| 604 |
} |
| 605 |
|
| 606 |
# Used only for logging. |
| 607 |
if {$token eq {}} { |
| 608 |
set tk {} |
| 609 |
} else { |
| 610 |
set tk [namespace tail $token] |
| 611 |
} |
| 612 |
|
| 613 |
if { [info exists socketPlayCmd($connId)] |
| 614 |
&& ($socketPlayCmd($connId) ne {ReplayIfClose Wready {} {}}) |
| 615 |
} { |
| 616 |
# Before unsetting, there is some unfinished business. |
| 617 |
# - If the server sent "Connection: close", we have stored the command |
| 618 |
# for retrying any queued requests in socketPlayCmd, so copy that |
| 619 |
# value for execution below. socketClosing(*) was also set. |
| 620 |
# - Also clear the queues to prevent calls to Finish that would set the |
| 621 |
# state for the requests that will be retried to "finished with error |
| 622 |
# status". |
| 623 |
set unfinished $socketPlayCmd($connId) |
| 624 |
set socketRdQueue($connId) {} |
| 625 |
set socketWrQueue($connId) {} |
| 626 |
} else { |
| 627 |
set unfinished {} |
| 628 |
} |
| 629 |
|
| 630 |
Unset $connId |
| 631 |
|
| 632 |
if {$unfinished ne {}} { |
| 633 |
Log ^R$tk Any unfinished transactions (excluding $token) failed \ |
| 634 |
- token $token |
| 635 |
{*}$unfinished |
| 636 |
} |
| 637 |
} |
| 638 |
|
| 639 |
# http::Unset |
| 640 |
# |
| 641 |
# The trace on "unset socketRdState(*)" will call CancelReadPipeline |
| 642 |
# and cancel any queued responses. |
| 643 |
# The trace on "unset socketWrState(*)" will call CancelWritePipeline |
| 644 |
# and cancel any queued requests. |
| 645 |
|
| 646 |
proc http::Unset {connId} { |
| 647 |
variable socketMapping |
| 648 |
variable socketRdState |
| 649 |
variable socketWrState |
| 650 |
variable socketRdQueue |
| 651 |
variable socketWrQueue |
| 652 |
variable socketClosing |
| 653 |
variable socketPlayCmd |
| 654 |
|
| 655 |
unset socketMapping($connId) |
| 656 |
unset socketRdState($connId) |
| 657 |
unset socketWrState($connId) |
| 658 |
unset -nocomplain socketRdQueue($connId) |
| 659 |
unset -nocomplain socketWrQueue($connId) |
| 660 |
unset -nocomplain socketClosing($connId) |
| 661 |
unset -nocomplain socketPlayCmd($connId) |
| 662 |
} |
| 663 |
|
| 664 |
# http::reset -- |
| 665 |
# |
| 666 |
# See documentation for details. |
| 667 |
# |
| 668 |
# Arguments: |
| 669 |
# token Connection token. |
| 670 |
# why Status info. |
| 671 |
# |
| 672 |
# Side Effects: |
| 673 |
# See Finish |
| 674 |
|
| 675 |
proc http::reset {token {why reset}} { |
| 676 |
variable $token |
| 677 |
upvar 0 $token state |
| 678 |
set state(status) $why |
| 679 |
catch {fileevent $state(sock) readable {}} |
| 680 |
catch {fileevent $state(sock) writable {}} |
| 681 |
Finish $token |
| 682 |
if {[info exists state(error)]} { |
| 683 |
set errorlist $state(error) |
| 684 |
unset state |
| 685 |
eval ::error $errorlist |
| 686 |
} |
| 687 |
} |
| 688 |
|
| 689 |
# http::geturl -- |
| 690 |
# |
| 691 |
# Establishes a connection to a remote url via http. |
| 692 |
# |
| 693 |
# Arguments: |
| 694 |
# url The http URL to goget. |
| 695 |
# args Option value pairs. Valid options include: |
| 696 |
# -blocksize, -validate, -headers, -timeout |
| 697 |
# Results: |
| 698 |
# Returns a token for this connection. This token is the name of an |
| 699 |
# array that the caller should unset to garbage collect the state. |
| 700 |
|
| 701 |
proc http::geturl {url args} { |
| 702 |
variable http |
| 703 |
variable urlTypes |
| 704 |
variable defaultCharset |
| 705 |
variable defaultKeepalive |
| 706 |
variable strict |
| 707 |
|
| 708 |
# Initialize the state variable, an array. We'll return the name of this |
| 709 |
# array as the token for the transaction. |
| 710 |
|
| 711 |
if {![info exists http(uid)]} { |
| 712 |
set http(uid) 0 |
| 713 |
} |
| 714 |
set token [namespace current]::[incr http(uid)] |
| 715 |
##Log Starting http::geturl - token $token |
| 716 |
variable $token |
| 717 |
upvar 0 $token state |
| 718 |
set tk [namespace tail $token] |
| 719 |
reset $token |
| 720 |
Log ^A$tk URL $url - token $token |
| 721 |
|
| 722 |
# Process command options. |
| 723 |
|
| 724 |
array set state { |
| 725 |
-binary false |
| 726 |
-blocksize 8192 |
| 727 |
-queryblocksize 8192 |
| 728 |
-validate 0 |
| 729 |
-headers {} |
| 730 |
-timeout 0 |
| 731 |
-type application/x-www-form-urlencoded |
| 732 |
-queryprogress {} |
| 733 |
-protocol 1.1 |
| 734 |
binary 0 |
| 735 |
state created |
| 736 |
meta {} |
| 737 |
method {} |
| 738 |
coding {} |
| 739 |
currentsize 0 |
| 740 |
totalsize 0 |
| 741 |
querylength 0 |
| 742 |
queryoffset 0 |
| 743 |
type text/html |
| 744 |
body {} |
| 745 |
status "" |
| 746 |
http "" |
| 747 |
connection keep-alive |
| 748 |
} |
| 749 |
set state(-keepalive) $defaultKeepalive |
| 750 |
set state(-strict) $strict |
| 751 |
# These flags have their types verified [Bug 811170] |
| 752 |
array set type { |
| 753 |
-binary boolean |
| 754 |
-blocksize integer |
| 755 |
-queryblocksize integer |
| 756 |
-strict boolean |
| 757 |
-timeout integer |
| 758 |
-validate boolean |
| 759 |
-headers list |
| 760 |
} |
| 761 |
set state(charset) $defaultCharset |
| 762 |
set options { |
| 763 |
-binary -blocksize -channel -command -handler -headers -keepalive |
| 764 |
-method -myaddr -progress -protocol -query -queryblocksize |
| 765 |
-querychannel -queryprogress -strict -timeout -type -validate |
| 766 |
} |
| 767 |
set usage [join [lsort $options] ", "] |
| 768 |
set options [string map {- ""} $options] |
| 769 |
set pat ^-(?:[join $options |])$ |
| 770 |
foreach {flag value} $args { |
| 771 |
if {[regexp -- $pat $flag]} { |
| 772 |
# Validate numbers |
| 773 |
if { [info exists type($flag)] |
| 774 |
&& (![string is $type($flag) -strict $value]) |
| 775 |
} { |
| 776 |
unset $token |
| 777 |
return -code error \ |
| 778 |
"Bad value for $flag ($value), must be $type($flag)" |
| 779 |
} |
| 780 |
if {($flag eq "-headers") && ([llength $value] % 2 != 0)} { |
| 781 |
unset $token |
| 782 |
return -code error \ |
| 783 |
"Bad value for $flag ($value), number of list elements must be even" |
| 784 |
} |
| 785 |
set state($flag) $value |
| 786 |
} else { |
| 787 |
unset $token |
| 788 |
return -code error "Unknown option $flag, can be: $usage" |
| 789 |
} |
| 790 |
} |
| 791 |
|
| 792 |
# Make sure -query and -querychannel aren't both specified |
| 793 |
|
| 794 |
set isQueryChannel [info exists state(-querychannel)] |
| 795 |
set isQuery [info exists state(-query)] |
| 796 |
if {$isQuery && $isQueryChannel} { |
| 797 |
unset $token |
| 798 |
return -code error "Can't combine -query and -querychannel options!" |
| 799 |
} |
| 800 |
|
| 801 |
# Validate URL, determine the server host and port, and check proxy case |
| 802 |
# Recognize user:pass@host URLs also, although we do not do anything with |
| 803 |
# that info yet. |
| 804 |
|
| 805 |
# URLs have basically four parts. |
| 806 |
# First, before the colon, is the protocol scheme (e.g. http) |
| 807 |
# Second, for HTTP-like protocols, is the authority |
| 808 |
# The authority is preceded by // and lasts up to (but not including) |
| 809 |
# the following / or ? and it identifies up to four parts, of which |
| 810 |
# only one, the host, is required (if an authority is present at all). |
| 811 |
# All other parts of the authority (user name, password, port number) |
| 812 |
# are optional. |
| 813 |
# Third is the resource name, which is split into two parts at a ? |
| 814 |
# The first part (from the single "/" up to "?") is the path, and the |
| 815 |
# second part (from that "?" up to "#") is the query. *HOWEVER*, we do |
| 816 |
# not need to separate them; we send the whole lot to the server. |
| 817 |
# Both, path and query are allowed to be missing, including their |
| 818 |
# delimiting character. |
| 819 |
# Fourth is the fragment identifier, which is everything after the first |
| 820 |
# "#" in the URL. The fragment identifier MUST NOT be sent to the server |
| 821 |
# and indeed, we don't bother to validate it (it could be an error to |
| 822 |
# pass it in here, but it's cheap to strip). |
| 823 |
# |
| 824 |
# An example of a URL that has all the parts: |
| 825 |
# |
| 826 |
# http://jschmoe:[email protected]:8000/foo/bar.tml?q=foo#changes |
| 827 |
# |
| 828 |
# The "http" is the protocol, the user is "jschmoe", the password is |
| 829 |
# "xyzzy", the host is "www.bogus.net", the port is "8000", the path is |
| 830 |
# "/foo/bar.tml", the query is "q=foo", and the fragment is "changes". |
| 831 |
# |
| 832 |
# Note that the RE actually combines the user and password parts, as |
| 833 |
# recommended in RFC 3986. Indeed, that RFC states that putting passwords |
| 834 |
# in URLs is a Really Bad Idea, something with which I would agree utterly. |
| 835 |
# |
| 836 |
# From a validation perspective, we need to ensure that the parts of the |
| 837 |
# URL that are going to the server are correctly encoded. This is only |
| 838 |
# done if $state(-strict) is true (inherited from $::http::strict). |
| 839 |
|
| 840 |
set URLmatcher {(?x) # this is _expanded_ syntax |
| 841 |
^ |
| 842 |
(?: (\w+) : ) ? # <protocol scheme> |
| 843 |
(?: // |
| 844 |
(?: |
| 845 |
( |
| 846 |
[^@/\#?]+ # <userinfo part of authority> |
| 847 |
) @ |
| 848 |
)? |
| 849 |
( # <host part of authority> |
| 850 |
[^/:\#?]+ | # host name or IPv4 address |
| 851 |
\[ [^/\#?]+ \] # IPv6 address in square brackets |
| 852 |
) |
| 853 |
(?: : (\d+) )? # <port part of authority> |
| 854 |
)? |
| 855 |
( [/\?] [^\#]*)? # <path> (including query) |
| 856 |
(?: \# (.*) )? # <fragment> |
| 857 |
$ |
| 858 |
} |
| 859 |
|
| 860 |
# Phase one: parse |
| 861 |
if {![regexp -- $URLmatcher $url -> proto user host port srvurl]} { |
| 862 |
unset $token |
| 863 |
return -code error "Unsupported URL: $url" |
| 864 |
} |
| 865 |
# Phase two: validate |
| 866 |
set host [string trim $host {[]}]; # strip square brackets from IPv6 address |
| 867 |
if {$host eq ""} { |
| 868 |
# Caller has to provide a host name; we do not have a "default host" |
| 869 |
# that would enable us to handle relative URLs. |
| 870 |
unset $token |
| 871 |
return -code error "Missing host part: $url" |
| 872 |
# Note that we don't check the hostname for validity here; if it's |
| 873 |
# invalid, we'll simply fail to resolve it later on. |
| 874 |
} |
| 875 |
if {$port ne "" && $port > 65535} { |
| 876 |
unset $token |
| 877 |
return -code error "Invalid port number: $port" |
| 878 |
} |
| 879 |
# The user identification and resource identification parts of the URL can |
| 880 |
# have encoded characters in them; take care! |
| 881 |
if {$user ne ""} { |
| 882 |
# Check for validity according to RFC 3986, Appendix A |
| 883 |
set validityRE {(?xi) |
| 884 |
^ |
| 885 |
(?: [-\w.~!$&'()*+,;=:] | %[0-9a-f][0-9a-f] )+ |
| 886 |
$ |
| 887 |
} |
| 888 |
if {$state(-strict) && ![regexp -- $validityRE $user]} { |
| 889 |
unset $token |
| 890 |
# Provide a better error message in this error case |
| 891 |
if {[regexp {(?i)%(?![0-9a-f][0-9a-f]).?.?} $user bad]} { |
| 892 |
return -code error \ |
| 893 |
"Illegal encoding character usage \"$bad\" in URL user" |
| 894 |
} |
| 895 |
return -code error "Illegal characters in URL user" |
| 896 |
} |
| 897 |
} |
| 898 |
if {$srvurl ne ""} { |
| 899 |
# RFC 3986 allows empty paths (not even a /), but servers |
| 900 |
# return 400 if the path in the HTTP request doesn't start |
| 901 |
# with / , so add it here if needed. |
| 902 |
if {[string index $srvurl 0] ne "/"} { |
| 903 |
set srvurl /$srvurl |
| 904 |
} |
| 905 |
# Check for validity according to RFC 3986, Appendix A |
| 906 |
set validityRE {(?xi) |
| 907 |
^ |
| 908 |
# Path part (already must start with / character) |
| 909 |
(?: [-\w.~!$&'()*+,;=:@/] | %[0-9a-f][0-9a-f] )* |
| 910 |
# Query part (optional, permits ? characters) |
| 911 |
(?: \? (?: [-\w.~!$&'()*+,;=:@/?] | %[0-9a-f][0-9a-f] )* )? |
| 912 |
$ |
| 913 |
} |
| 914 |
if {$state(-strict) && ![regexp -- $validityRE $srvurl]} { |
| 915 |
unset $token |
| 916 |
# Provide a better error message in this error case |
| 917 |
if {[regexp {(?i)%(?![0-9a-f][0-9a-f])..} $srvurl bad]} { |
| 918 |
return -code error \ |
| 919 |
"Illegal encoding character usage \"$bad\" in URL path" |
| 920 |
} |
| 921 |
return -code error "Illegal characters in URL path" |
| 922 |
} |
| 923 |
if {![regexp {^[^?#]+} $srvurl state(path)]} { |
| 924 |
set state(path) / |
| 925 |
} |
| 926 |
} else { |
| 927 |
set srvurl / |
| 928 |
set state(path) / |
| 929 |
} |
| 930 |
if {$proto eq ""} { |
| 931 |
set proto http |
| 932 |
} |
| 933 |
set lower [string tolower $proto] |
| 934 |
if {![info exists urlTypes($lower)]} { |
| 935 |
unset $token |
| 936 |
return -code error "Unsupported URL type \"$proto\"" |
| 937 |
} |
| 938 |
set defport [lindex $urlTypes($lower) 0] |
| 939 |
set defcmd [lindex $urlTypes($lower) 1] |
| 940 |
|
| 941 |
if {$port eq ""} { |
| 942 |
set port $defport |
| 943 |
} |
| 944 |
if {![catch {$http(-proxyfilter) $host} proxy]} { |
| 945 |
set phost [lindex $proxy 0] |
| 946 |
set pport [lindex $proxy 1] |
| 947 |
} |
| 948 |
|
| 949 |
# OK, now reassemble into a full URL |
| 950 |
set url ${proto}:// |
| 951 |
if {$user ne ""} { |
| 952 |
append url $user |
| 953 |
append url @ |
| 954 |
} |
| 955 |
append url $host |
| 956 |
if {$port != $defport} { |
| 957 |
append url : $port |
| 958 |
} |
| 959 |
append url $srvurl |
| 960 |
# Don't append the fragment! |
| 961 |
set state(url) $url |
| 962 |
|
| 963 |
set sockopts [list -async] |
| 964 |
|
| 965 |
# If we are using the proxy, we must pass in the full URL that includes |
| 966 |
# the server name. |
| 967 |
|
| 968 |
if {[info exists phost] && ($phost ne "")} { |
| 969 |
set srvurl $url |
| 970 |
set targetAddr [list $phost $pport] |
| 971 |
} else { |
| 972 |
set targetAddr [list $host $port] |
| 973 |
} |
| 974 |
# Proxy connections aren't shared among different hosts. |
| 975 |
set state(socketinfo) $host:$port |
| 976 |
|
| 977 |
# Save the accept types at this point to prevent a race condition. [Bug |
| 978 |
# c11a51c482] |
| 979 |
set state(accept-types) $http(-accept) |
| 980 |
|
| 981 |
# Check whether this is an Upgrade request. |
| 982 |
set connectionValues [SplitCommaSeparatedFieldValue \ |
| 983 |
[GetFieldValue $state(-headers) Connection]] |
| 984 |
set connectionValues [string tolower $connectionValues] |
| 985 |
set upgradeValues [SplitCommaSeparatedFieldValue \ |
| 986 |
[GetFieldValue $state(-headers) Upgrade]] |
| 987 |
set state(upgradeRequest) [expr { "upgrade" in $connectionValues |
| 988 |
&& [llength $upgradeValues] >= 1}] |
| 989 |
|
| 990 |
if {$isQuery || $isQueryChannel} { |
| 991 |
# It's a POST. |
| 992 |
# A client wishing to send a non-idempotent request SHOULD wait to send |
| 993 |
# that request until it has received the response status for the |
| 994 |
# previous request. |
| 995 |
if {$http(-postfresh)} { |
| 996 |
# Override -keepalive for a POST. Use a new connection, and thus |
| 997 |
# avoid the small risk of a race against server timeout. |
| 998 |
set state(-keepalive) 0 |
| 999 |
} else { |
| 1000 |
# Allow -keepalive but do not -pipeline - wait for the previous |
| 1001 |
# transaction to finish. |
| 1002 |
# There is a small risk of a race against server timeout. |
| 1003 |
set state(-pipeline) 0 |
| 1004 |
} |
| 1005 |
} elseif {$state(upgradeRequest)} { |
| 1006 |
# It's an upgrade request. Method must be GET (untested). |
| 1007 |
# Force -keepalive to 0 so the connection is not made over a persistent |
| 1008 |
# socket, i.e. one used for multiple HTTP requests. |
| 1009 |
set state(-keepalive) 0 |
| 1010 |
} else { |
| 1011 |
# It's a non-upgrade GET or HEAD. |
| 1012 |
set state(-pipeline) $http(-pipeline) |
| 1013 |
} |
| 1014 |
|
| 1015 |
# We cannot handle chunked encodings with -handler, so force HTTP/1.0 |
| 1016 |
# until we can manage this. |
| 1017 |
if {[info exists state(-handler)]} { |
| 1018 |
set state(-protocol) 1.0 |
| 1019 |
} |
| 1020 |
|
| 1021 |
# RFC 7320 A.1 - HTTP/1.0 Keep-Alive is problematic. We do not support it. |
| 1022 |
if {$state(-protocol) eq "1.0"} { |
| 1023 |
set state(connection) close |
| 1024 |
set state(-keepalive) 0 |
| 1025 |
} |
| 1026 |
|
| 1027 |
# See if we are supposed to use a previously opened channel. |
| 1028 |
# - In principle, ANY call to http::geturl could use a previously opened |
| 1029 |
# channel if it is available - the "Connection: keep-alive" header is a |
| 1030 |
# request to leave the channel open AFTER completion of this call. |
| 1031 |
# - In fact, we try to use an existing channel only if -keepalive 1 -- this |
| 1032 |
# means that at most one channel is left open for each value of |
| 1033 |
# $state(socketinfo). This property simplifies the mapping of open |
| 1034 |
# channels. |
| 1035 |
set reusing 0 |
| 1036 |
set alreadyQueued 0 |
| 1037 |
if {$state(-keepalive)} { |
| 1038 |
variable socketMapping |
| 1039 |
variable socketRdState |
| 1040 |
variable socketWrState |
| 1041 |
variable socketRdQueue |
| 1042 |
variable socketWrQueue |
| 1043 |
variable socketClosing |
| 1044 |
variable socketPlayCmd |
| 1045 |
|
| 1046 |
if {[info exists socketMapping($state(socketinfo))]} { |
| 1047 |
# - If the connection is idle, it has a "fileevent readable" binding |
| 1048 |
# to http::CheckEof, in case the server times out and half-closes |
| 1049 |
# the socket (http::CheckEof closes the other half). |
| 1050 |
# - We leave this binding in place until just before the last |
| 1051 |
# puts+flush in http::Connected (GET/HEAD) or http::Write (POST), |
| 1052 |
# after which the HTTP response might be generated. |
| 1053 |
|
| 1054 |
if { [info exists socketClosing($state(socketinfo))] |
| 1055 |
&& $socketClosing($state(socketinfo)) |
| 1056 |
} { |
| 1057 |
# socketClosing(*) is set because the server has sent a |
| 1058 |
# "Connection: close" header. |
| 1059 |
# Do not use the persistent socket again. |
| 1060 |
# Since we have only one persistent socket per server, and the |
| 1061 |
# old socket is not yet dead, add the request to the write queue |
| 1062 |
# of the dying socket, which will be replayed by ReplayIfClose. |
| 1063 |
# Also add it to socketWrQueue(*) which is used only if an error |
| 1064 |
# causes a call to Finish. |
| 1065 |
set reusing 1 |
| 1066 |
set sock $socketMapping($state(socketinfo)) |
| 1067 |
Log "reusing socket $sock for $state(socketinfo) - token $token" |
| 1068 |
|
| 1069 |
set alreadyQueued 1 |
| 1070 |
lassign $socketPlayCmd($state(socketinfo)) com0 com1 com2 com3 |
| 1071 |
lappend com3 $token |
| 1072 |
set socketPlayCmd($state(socketinfo)) [list $com0 $com1 $com2 $com3] |
| 1073 |
lappend socketWrQueue($state(socketinfo)) $token |
| 1074 |
} elseif {[catch {fconfigure $socketMapping($state(socketinfo))}]} { |
| 1075 |
# FIXME Is it still possible for this code to be executed? If |
| 1076 |
# so, this could be another place to call TestForReplay, |
| 1077 |
# rather than discarding the queued transactions. |
| 1078 |
Log "WARNING: socket for $state(socketinfo) was closed\ |
| 1079 |
- token $token" |
| 1080 |
Log "WARNING - if testing, pay special attention to this\ |
| 1081 |
case (GH) which is seldom executed - token $token" |
| 1082 |
|
| 1083 |
# This will call CancelReadPipeline, CancelWritePipeline, and |
| 1084 |
# cancel any queued requests, responses. |
| 1085 |
Unset $state(socketinfo) |
| 1086 |
} else { |
| 1087 |
# Use the persistent socket. |
| 1088 |
# The socket may not be ready to write: an earlier request might |
| 1089 |
# still be still writing (in the pipelined case) or |
| 1090 |
# writing/reading (in the nonpipeline case). This possibility |
| 1091 |
# is handled by socketWrQueue later in this command. |
| 1092 |
set reusing 1 |
| 1093 |
set sock $socketMapping($state(socketinfo)) |
| 1094 |
Log "reusing socket $sock for $state(socketinfo) - token $token" |
| 1095 |
|
| 1096 |
} |
| 1097 |
# Do not automatically close the connection socket. |
| 1098 |
set state(connection) keep-alive |
| 1099 |
} |
| 1100 |
} |
| 1101 |
|
| 1102 |
if {$reusing} { |
| 1103 |
# Define state(tmpState) and state(tmpOpenCmd) for use |
| 1104 |
# by http::ReplayIfDead if the persistent connection has died. |
| 1105 |
set state(tmpState) [array get state] |
| 1106 |
|
| 1107 |
# Pass -myaddr directly to the socket command |
| 1108 |
if {[info exists state(-myaddr)]} { |
| 1109 |
lappend sockopts -myaddr $state(-myaddr) |
| 1110 |
} |
| 1111 |
|
| 1112 |
set state(tmpOpenCmd) [list {*}$defcmd {*}$sockopts {*}$targetAddr] |
| 1113 |
} |
| 1114 |
|
| 1115 |
set state(reusing) $reusing |
| 1116 |
# Excluding ReplayIfDead and the decision whether to call it, there are four |
| 1117 |
# places outside http::geturl where state(reusing) is used: |
| 1118 |
# - Connected - if reusing and not pipelined, start the state(-timeout) |
| 1119 |
# timeout (when writing). |
| 1120 |
# - DoneRequest - if reusing and pipelined, send the next pipelined write |
| 1121 |
# - Event - if reusing and pipelined, start the state(-timeout) |
| 1122 |
# timeout (when reading). |
| 1123 |
# - Event - if (not reusing) and pipelined, send the next pipelined |
| 1124 |
# write |
| 1125 |
|
| 1126 |
# See comments above re the start of this timeout in other cases. |
| 1127 |
if {(!$state(reusing)) && ($state(-timeout) > 0)} { |
| 1128 |
set state(after) [after $state(-timeout) \ |
| 1129 |
[list http::reset $token timeout]] |
| 1130 |
} |
| 1131 |
|
| 1132 |
if {![info exists sock]} { |
| 1133 |
# Pass -myaddr directly to the socket command |
| 1134 |
if {[info exists state(-myaddr)]} { |
| 1135 |
lappend sockopts -myaddr $state(-myaddr) |
| 1136 |
} |
| 1137 |
set pre [clock milliseconds] |
| 1138 |
##Log pre socket opened, - token $token |
| 1139 |
##Log [concat $defcmd $sockopts $targetAddr] - token $token |
| 1140 |
if {[catch {eval $defcmd $sockopts $targetAddr} sock errdict]} { |
| 1141 |
# Something went wrong while trying to establish the connection. |
| 1142 |
# Clean up after events and such, but DON'T call the command |
| 1143 |
# callback (if available) because we're going to throw an |
| 1144 |
# exception from here instead. |
| 1145 |
|
| 1146 |
set state(sock) NONE |
| 1147 |
Finish $token $sock 1 |
| 1148 |
cleanup $token |
| 1149 |
dict unset errdict -level |
| 1150 |
return -options $errdict $sock |
| 1151 |
} else { |
| 1152 |
# Initialisation of a new socket. |
| 1153 |
##Log post socket opened, - token $token |
| 1154 |
##Log socket opened, now fconfigure - token $token |
| 1155 |
set delay [expr {[clock milliseconds] - $pre}] |
| 1156 |
if {$delay > 3000} { |
| 1157 |
Log socket delay $delay - token $token |
| 1158 |
} |
| 1159 |
fconfigure $sock -translation {auto crlf} \ |
| 1160 |
-buffersize $state(-blocksize) |
| 1161 |
##Log socket opened, DONE fconfigure - token $token |
| 1162 |
} |
| 1163 |
} |
| 1164 |
# Command [socket] is called with -async, but takes 5s to 5.1s to return, |
| 1165 |
# with probability of order 1 in 10,000. This may be a bizarre scheduling |
| 1166 |
# issue with my (KJN's) system (Fedora Linux). |
| 1167 |
# This does not cause a problem (unless the request times out when this |
| 1168 |
# command returns). |
| 1169 |
|
| 1170 |
set state(sock) $sock |
| 1171 |
Log "Using $sock for $state(socketinfo) - token $token" \ |
| 1172 |
[expr {$state(-keepalive)?"keepalive":""}] |
| 1173 |
|
| 1174 |
if { $state(-keepalive) |
| 1175 |
&& (![info exists socketMapping($state(socketinfo))]) |
| 1176 |
} { |
| 1177 |
# Freshly-opened socket that we would like to become persistent. |
| 1178 |
set socketMapping($state(socketinfo)) $sock |
| 1179 |
|
| 1180 |
if {![info exists socketRdState($state(socketinfo))]} { |
| 1181 |
set socketRdState($state(socketinfo)) {} |
| 1182 |
set varName ::http::socketRdState($state(socketinfo)) |
| 1183 |
trace add variable $varName unset ::http::CancelReadPipeline |
| 1184 |
} |
| 1185 |
if {![info exists socketWrState($state(socketinfo))]} { |
| 1186 |
set socketWrState($state(socketinfo)) {} |
| 1187 |
set varName ::http::socketWrState($state(socketinfo)) |
| 1188 |
trace add variable $varName unset ::http::CancelWritePipeline |
| 1189 |
} |
| 1190 |
|
| 1191 |
if {$state(-pipeline)} { |
| 1192 |
#Log new, init for pipelined, GRANT write access to $token in geturl |
| 1193 |
# Also grant premature read access to the socket. This is OK. |
| 1194 |
set socketRdState($state(socketinfo)) $token |
| 1195 |
set socketWrState($state(socketinfo)) $token |
| 1196 |
} else { |
| 1197 |
# socketWrState is not used by this non-pipelined transaction. |
| 1198 |
# We cannot leave it as "Wready" because the next call to |
| 1199 |
# http::geturl with a pipelined transaction would conclude that the |
| 1200 |
# socket is available for writing. |
| 1201 |
#Log new, init for nonpipeline, GRANT r/w access to $token in geturl |
| 1202 |
set socketRdState($state(socketinfo)) $token |
| 1203 |
set socketWrState($state(socketinfo)) $token |
| 1204 |
} |
| 1205 |
|
| 1206 |
set socketRdQueue($state(socketinfo)) {} |
| 1207 |
set socketWrQueue($state(socketinfo)) {} |
| 1208 |
set socketClosing($state(socketinfo)) 0 |
| 1209 |
set socketPlayCmd($state(socketinfo)) {ReplayIfClose Wready {} {}} |
| 1210 |
} |
| 1211 |
|
| 1212 |
if {![info exists phost]} { |
| 1213 |
set phost "" |
| 1214 |
} |
| 1215 |
if {$reusing} { |
| 1216 |
# For use by http::ReplayIfDead if the persistent connection has died. |
| 1217 |
# Also used by NextPipelinedWrite. |
| 1218 |
set state(tmpConnArgs) [list $proto $phost $srvurl] |
| 1219 |
} |
| 1220 |
|
| 1221 |
# The element socketWrState($connId) has a value which is either the name of |
| 1222 |
# the token that is permitted to write to the socket, or "Wready" if no |
| 1223 |
# token is permitted to write. |
| 1224 |
# |
| 1225 |
# The code that sets the value to Wready immediately calls |
| 1226 |
# http::NextPipelinedWrite, which examines socketWrQueue($connId) and |
| 1227 |
# processes the next request in the queue, if there is one. The value |
| 1228 |
# Wready is not found when the interpreter is in the event loop unless the |
| 1229 |
# socket is idle. |
| 1230 |
# |
| 1231 |
# The element socketRdState($connId) has a value which is either the name of |
| 1232 |
# the token that is permitted to read from the socket, or "Rready" if no |
| 1233 |
# token is permitted to read. |
| 1234 |
# |
| 1235 |
# The code that sets the value to Rready then examines |
| 1236 |
# socketRdQueue($connId) and processes the next request in the queue, if |
| 1237 |
# there is one. The value Rready is not found when the interpreter is in |
| 1238 |
# the event loop unless the socket is idle. |
| 1239 |
|
| 1240 |
if {$alreadyQueued} { |
| 1241 |
# A write may or may not be in progress. There is no need to set |
| 1242 |
# socketWrState to prevent another call stealing write access - all |
| 1243 |
# subsequent calls on this socket will come here because the socket |
| 1244 |
# will close after the current read, and its |
| 1245 |
# socketClosing($connId) is 1. |
| 1246 |
##Log "HTTP request for token $token is queued" |
| 1247 |
|
| 1248 |
} elseif { $reusing |
| 1249 |
&& $state(-pipeline) |
| 1250 |
&& ($socketWrState($state(socketinfo)) ne "Wready") |
| 1251 |
} { |
| 1252 |
##Log "HTTP request for token $token is queued for pipelined use" |
| 1253 |
lappend socketWrQueue($state(socketinfo)) $token |
| 1254 |
|
| 1255 |
} elseif { $reusing |
| 1256 |
&& (!$state(-pipeline)) |
| 1257 |
&& ($socketWrState($state(socketinfo)) ne "Wready") |
| 1258 |
} { |
| 1259 |
# A write is queued or in progress. Lappend to the write queue. |
| 1260 |
##Log "HTTP request for token $token is queued for nonpipeline use" |
| 1261 |
lappend socketWrQueue($state(socketinfo)) $token |
| 1262 |
|
| 1263 |
} elseif { $reusing |
| 1264 |
&& (!$state(-pipeline)) |
| 1265 |
&& ($socketWrState($state(socketinfo)) eq "Wready") |
| 1266 |
&& ($socketRdState($state(socketinfo)) ne "Rready") |
| 1267 |
} { |
| 1268 |
# A read is queued or in progress, but not a write. Cannot start the |
| 1269 |
# nonpipeline transaction, but must set socketWrState to prevent a |
| 1270 |
# pipelined request jumping the queue. |
| 1271 |
##Log "HTTP request for token $token is queued for nonpipeline use" |
| 1272 |
#Log re-use nonpipeline, GRANT delayed write access to $token in geturl |
| 1273 |
|
| 1274 |
set socketWrState($state(socketinfo)) peNding |
| 1275 |
lappend socketWrQueue($state(socketinfo)) $token |
| 1276 |
|
| 1277 |
} else { |
| 1278 |
if {$reusing && $state(-pipeline)} { |
| 1279 |
#Log re-use pipelined, GRANT write access to $token in geturl |
| 1280 |
set socketWrState($state(socketinfo)) $token |
| 1281 |
|
| 1282 |
} elseif {$reusing} { |
| 1283 |
# Cf tests above - both are ready. |
| 1284 |
#Log re-use nonpipeline, GRANT r/w access to $token in geturl |
| 1285 |
set socketRdState($state(socketinfo)) $token |
| 1286 |
set socketWrState($state(socketinfo)) $token |
| 1287 |
} |
| 1288 |
|
| 1289 |
# All (!$reusing) cases come here, and also some $reusing cases if the |
| 1290 |
# connection is ready. |
| 1291 |
#Log ---- $state(socketinfo) << conn to $token for HTTP request (a) |
| 1292 |
# Connect does its own fconfigure. |
| 1293 |
fileevent $sock writable \ |
| 1294 |
[list http::Connect $token $proto $phost $srvurl] |
| 1295 |
} |
| 1296 |
|
| 1297 |
# Wait for the connection to complete. |
| 1298 |
if {![info exists state(-command)]} { |
| 1299 |
# geturl does EVERYTHING asynchronously, so if the user |
| 1300 |
# calls it synchronously, we just do a wait here. |
| 1301 |
http::wait $token |
| 1302 |
|
| 1303 |
if {![info exists state]} { |
| 1304 |
# If we timed out then Finish has been called and the users |
| 1305 |
# command callback may have cleaned up the token. If so we end up |
| 1306 |
# here with nothing left to do. |
| 1307 |
return $token |
| 1308 |
} elseif {$state(status) eq "error"} { |
| 1309 |
# Something went wrong while trying to establish the connection. |
| 1310 |
# Clean up after events and such, but DON'T call the command |
| 1311 |
# callback (if available) because we're going to throw an |
| 1312 |
# exception from here instead. |
| 1313 |
set err [lindex $state(error) 0] |
| 1314 |
cleanup $token |
| 1315 |
return -code error $err |
| 1316 |
} |
| 1317 |
} |
| 1318 |
##Log Leaving http::geturl - token $token |
| 1319 |
return $token |
| 1320 |
} |
| 1321 |
|
| 1322 |
# http::Connected -- |
| 1323 |
# |
| 1324 |
# Callback used when the connection to the HTTP server is actually |
| 1325 |
# established. |
| 1326 |
# |
| 1327 |
# Arguments: |
| 1328 |
# token State token. |
| 1329 |
# proto What protocol (http, https, etc.) was used to connect. |
| 1330 |
# phost Are we using keep-alive? Non-empty if yes. |
| 1331 |
# srvurl Service-local URL that we're requesting |
| 1332 |
# Results: |
| 1333 |
# None. |
| 1334 |
|
| 1335 |
proc http::Connected {token proto phost srvurl} { |
| 1336 |
variable http |
| 1337 |
variable urlTypes |
| 1338 |
variable socketMapping |
| 1339 |
variable socketRdState |
| 1340 |
variable socketWrState |
| 1341 |
variable socketRdQueue |
| 1342 |
variable socketWrQueue |
| 1343 |
variable socketClosing |
| 1344 |
variable socketPlayCmd |
| 1345 |
|
| 1346 |
variable $token |
| 1347 |
upvar 0 $token state |
| 1348 |
set tk [namespace tail $token] |
| 1349 |
|
| 1350 |
if {$state(reusing) && (!$state(-pipeline)) && ($state(-timeout) > 0)} { |
| 1351 |
set state(after) [after $state(-timeout) \ |
| 1352 |
[list http::reset $token timeout]] |
| 1353 |
} |
| 1354 |
|
| 1355 |
# Set back the variables needed here. |
| 1356 |
set sock $state(sock) |
| 1357 |
set isQueryChannel [info exists state(-querychannel)] |
| 1358 |
set isQuery [info exists state(-query)] |
| 1359 |
regexp {^(.+):([^:]+)$} $state(socketinfo) {} host port |
| 1360 |
|
| 1361 |
set lower [string tolower $proto] |
| 1362 |
set defport [lindex $urlTypes($lower) 0] |
| 1363 |
|
| 1364 |
# Send data in cr-lf format, but accept any line terminators. |
| 1365 |
# Initialisation to {auto *} now done in geturl, KeepSocket and DoneRequest. |
| 1366 |
# We are concerned here with the request (write) not the response (read). |
| 1367 |
lassign [fconfigure $sock -translation] trRead trWrite |
| 1368 |
fconfigure $sock -translation [list $trRead crlf] \ |
| 1369 |
-buffersize $state(-blocksize) |
| 1370 |
|
| 1371 |
# The following is disallowed in safe interpreters, but the socket is |
| 1372 |
# already in non-blocking mode in that case. |
| 1373 |
|
| 1374 |
catch {fconfigure $sock -blocking off} |
| 1375 |
set how GET |
| 1376 |
if {$isQuery} { |
| 1377 |
set state(querylength) [string length $state(-query)] |
| 1378 |
if {$state(querylength) > 0} { |
| 1379 |
set how POST |
| 1380 |
set contDone 0 |
| 1381 |
} else { |
| 1382 |
# There's no query data. |
| 1383 |
unset state(-query) |
| 1384 |
set isQuery 0 |
| 1385 |
} |
| 1386 |
} elseif {$state(-validate)} { |
| 1387 |
set how HEAD |
| 1388 |
} elseif {$isQueryChannel} { |
| 1389 |
set how POST |
| 1390 |
# The query channel must be blocking for the async Write to |
| 1391 |
# work properly. |
| 1392 |
fconfigure $state(-querychannel) -blocking 1 -translation binary |
| 1393 |
set contDone 0 |
| 1394 |
} |
| 1395 |
if {[info exists state(-method)] && ($state(-method) ne "")} { |
| 1396 |
set how $state(-method) |
| 1397 |
} |
| 1398 |
set accept_types_seen 0 |
| 1399 |
|
| 1400 |
Log ^B$tk begin sending request - token $token |
| 1401 |
|
| 1402 |
if {[catch { |
| 1403 |
set state(method) $how |
| 1404 |
puts $sock "$how $srvurl HTTP/$state(-protocol)" |
| 1405 |
set hostValue [GetFieldValue $state(-headers) Host] |
| 1406 |
if {$hostValue ne {}} { |
| 1407 |
# Allow Host spoofing. [Bug 928154] |
| 1408 |
regexp {^[^:]+} $hostValue state(host) |
| 1409 |
puts $sock "Host: $hostValue" |
| 1410 |
} elseif {$port == $defport} { |
| 1411 |
# Don't add port in this case, to handle broken servers. [Bug |
| 1412 |
# #504508] |
| 1413 |
set state(host) $host |
| 1414 |
puts $sock "Host: $host" |
| 1415 |
} else { |
| 1416 |
set state(host) $host |
| 1417 |
puts $sock "Host: $host:$port" |
| 1418 |
} |
| 1419 |
puts $sock "User-Agent: $http(-useragent)" |
| 1420 |
if {($state(-protocol) > 1.0) && $state(-keepalive)} { |
| 1421 |
# Send this header, because a 1.1 server is not compelled to treat |
| 1422 |
# this as the default. |
| 1423 |
puts $sock "Connection: keep-alive" |
| 1424 |
} |
| 1425 |
if {($state(-protocol) > 1.0) && !$state(-keepalive)} { |
| 1426 |
puts $sock "Connection: close" ;# RFC2616 sec 8.1.2.1 |
| 1427 |
} |
| 1428 |
if {($state(-protocol) < 1.1)} { |
| 1429 |
# RFC7230 A.1 |
| 1430 |
# Some server implementations of HTTP/1.0 have a faulty |
| 1431 |
# implementation of RFC 2068 Keep-Alive. |
| 1432 |
# Don't leave this to chance. |
| 1433 |
# For HTTP/1.0 we have already "set state(connection) close" |
| 1434 |
# and "state(-keepalive) 0". |
| 1435 |
puts $sock "Connection: close" |
| 1436 |
} |
| 1437 |
# RFC7230 A.1 - "clients are encouraged not to send the |
| 1438 |
# Proxy-Connection header field in any requests" |
| 1439 |
set accept_encoding_seen 0 |
| 1440 |
set content_type_seen 0 |
| 1441 |
foreach {key value} $state(-headers) { |
| 1442 |
set value [string map [list \n "" \r ""] $value] |
| 1443 |
set key [string map {" " -} [string trim $key]] |
| 1444 |
if {[string equal -nocase $key "host"]} { |
| 1445 |
continue |
| 1446 |
} |
| 1447 |
if {[string equal -nocase $key "accept-encoding"]} { |
| 1448 |
set accept_encoding_seen 1 |
| 1449 |
} |
| 1450 |
if {[string equal -nocase $key "accept"]} { |
| 1451 |
set accept_types_seen 1 |
| 1452 |
} |
| 1453 |
if {[string equal -nocase $key "content-type"]} { |
| 1454 |
set content_type_seen 1 |
| 1455 |
} |
| 1456 |
if {[string equal -nocase $key "content-length"]} { |
| 1457 |
set contDone 1 |
| 1458 |
set state(querylength) $value |
| 1459 |
} |
| 1460 |
if {[string length $key]} { |
| 1461 |
puts $sock "$key: $value" |
| 1462 |
} |
| 1463 |
} |
| 1464 |
# Allow overriding the Accept header on a per-connection basis. Useful |
| 1465 |
# for working with REST services. [Bug c11a51c482] |
| 1466 |
if {!$accept_types_seen} { |
| 1467 |
puts $sock "Accept: $state(accept-types)" |
| 1468 |
} |
| 1469 |
if { (!$accept_encoding_seen) |
| 1470 |
&& (![info exists state(-handler)]) |
| 1471 |
&& $http(-zip) |
| 1472 |
} { |
| 1473 |
puts $sock "Accept-Encoding: gzip,deflate,compress" |
| 1474 |
} |
| 1475 |
if {$isQueryChannel && ($state(querylength) == 0)} { |
| 1476 |
# Try to determine size of data in channel. If we cannot seek, the |
| 1477 |
# surrounding catch will trap us |
| 1478 |
|
| 1479 |
set start [tell $state(-querychannel)] |
| 1480 |
seek $state(-querychannel) 0 end |
| 1481 |
set state(querylength) \ |
| 1482 |
[expr {[tell $state(-querychannel)] - $start}] |
| 1483 |
seek $state(-querychannel) $start |
| 1484 |
} |
| 1485 |
|
| 1486 |
# Flush the request header and set up the fileevent that will either |
| 1487 |
# push the POST data or read the response. |
| 1488 |
# |
| 1489 |
# fileevent note: |
| 1490 |
# |
| 1491 |
# It is possible to have both the read and write fileevents active at |
| 1492 |
# this point. The only scenario it seems to affect is a server that |
| 1493 |
# closes the connection without reading the POST data. (e.g., early |
| 1494 |
# versions TclHttpd in various error cases). Depending on the |
| 1495 |
# platform, the client may or may not be able to get the response from |
| 1496 |
# the server because of the error it will get trying to write the post |
| 1497 |
# data. Having both fileevents active changes the timing and the |
| 1498 |
# behavior, but no two platforms (among Solaris, Linux, and NT) behave |
| 1499 |
# the same, and none behave all that well in any case. Servers should |
| 1500 |
# always read their POST data if they expect the client to read their |
| 1501 |
# response. |
| 1502 |
|
| 1503 |
if {$isQuery || $isQueryChannel} { |
| 1504 |
# POST method. |
| 1505 |
if {!$content_type_seen} { |
| 1506 |
puts $sock "Content-Type: $state(-type)" |
| 1507 |
} |
| 1508 |
if {!$contDone} { |
| 1509 |
puts $sock "Content-Length: $state(querylength)" |
| 1510 |
} |
| 1511 |
puts $sock "" |
| 1512 |
flush $sock |
| 1513 |
# Flush flushes the error in the https case with a bad handshake: |
| 1514 |
# else the socket never becomes writable again, and hangs until |
| 1515 |
# timeout (if any). |
| 1516 |
|
| 1517 |
lassign [fconfigure $sock -translation] trRead trWrite |
| 1518 |
fconfigure $sock -translation [list $trRead binary] |
| 1519 |
fileevent $sock writable [list http::Write $token] |
| 1520 |
# The http::Write command decides when to make the socket readable, |
| 1521 |
# using the same test as the GET/HEAD case below. |
| 1522 |
} else { |
| 1523 |
# GET or HEAD method. |
| 1524 |
if { (![catch {fileevent $sock readable} binding]) |
| 1525 |
&& ($binding eq [list http::CheckEof $sock]) |
| 1526 |
} { |
| 1527 |
# Remove the "fileevent readable" binding of an idle persistent |
| 1528 |
# socket to http::CheckEof. We can no longer treat bytes |
| 1529 |
# received as junk. The server might still time out and |
| 1530 |
# half-close the socket if it has not yet received the first |
| 1531 |
# "puts". |
| 1532 |
fileevent $sock readable {} |
| 1533 |
} |
| 1534 |
puts $sock "" |
| 1535 |
flush $sock |
| 1536 |
Log ^C$tk end sending request - token $token |
| 1537 |
# End of writing (GET/HEAD methods). The request has been sent. |
| 1538 |
|
| 1539 |
DoneRequest $token |
| 1540 |
} |
| 1541 |
|
| 1542 |
} err]} { |
| 1543 |
# The socket probably was never connected, OR the connection dropped |
| 1544 |
# later, OR https handshake error, which may be discovered as late as |
| 1545 |
# the "flush" command above... |
| 1546 |
Log "WARNING - if testing, pay special attention to this\ |
| 1547 |
case (GI) which is seldom executed - token $token" |
| 1548 |
if {[info exists state(reusing)] && $state(reusing)} { |
| 1549 |
# The socket was closed at the server end, and closed at |
| 1550 |
# this end by http::CheckEof. |
| 1551 |
if {[TestForReplay $token write $err a]} { |
| 1552 |
return |
| 1553 |
} else { |
| 1554 |
Finish $token {failed to re-use socket} |
| 1555 |
} |
| 1556 |
|
| 1557 |
# else: |
| 1558 |
# This is NOT a persistent socket that has been closed since its |
| 1559 |
# last use. |
| 1560 |
# If any other requests are in flight or pipelined/queued, they will |
| 1561 |
# be discarded. |
| 1562 |
} elseif {$state(status) eq ""} { |
| 1563 |
# ...https handshake errors come here. |
| 1564 |
set msg [registerError $sock] |
| 1565 |
registerError $sock {} |
| 1566 |
if {$msg eq {}} { |
| 1567 |
set msg {failed to use socket} |
| 1568 |
} |
| 1569 |
Finish $token $msg |
| 1570 |
} elseif {$state(status) ne "error"} { |
| 1571 |
Finish $token $err |
| 1572 |
} |
| 1573 |
} |
| 1574 |
} |
| 1575 |
|
| 1576 |
# http::registerError |
| 1577 |
# |
| 1578 |
# Called (for example when processing TclTLS activity) to register |
| 1579 |
# an error for a connection on a specific socket. This helps |
| 1580 |
# http::Connected to deliver meaningful error messages, e.g. when a TLS |
| 1581 |
# certificate fails verification. |
| 1582 |
# |
| 1583 |
# Usage: http::registerError socket ?newValue? |
| 1584 |
# |
| 1585 |
# "set" semantics, except that a "get" (a call without a new value) for a |
| 1586 |
# non-existent socket returns {}, not an error. |
| 1587 |
|
| 1588 |
proc http::registerError {sock args} { |
| 1589 |
variable registeredErrors |
| 1590 |
|
| 1591 |
if { ([llength $args] == 0) |
| 1592 |
&& (![info exists registeredErrors($sock)]) |
| 1593 |
} { |
| 1594 |
return |
| 1595 |
} elseif { ([llength $args] == 1) |
| 1596 |
&& ([lindex $args 0] eq {}) |
| 1597 |
} { |
| 1598 |
unset -nocomplain registeredErrors($sock) |
| 1599 |
return |
| 1600 |
} |
| 1601 |
set registeredErrors($sock) {*}$args |
| 1602 |
} |
| 1603 |
|
| 1604 |
# http::DoneRequest -- |
| 1605 |
# |
| 1606 |
# Command called when a request has been sent. It will arrange the |
| 1607 |
# next request and/or response as appropriate. |
| 1608 |
# |
| 1609 |
# If this command is called when $socketClosing(*), the request $token |
| 1610 |
# that calls it must be pipelined and destined to fail. |
| 1611 |
|
| 1612 |
proc http::DoneRequest {token} { |
| 1613 |
variable http |
| 1614 |
variable socketMapping |
| 1615 |
variable socketRdState |
| 1616 |
variable socketWrState |
| 1617 |
variable socketRdQueue |
| 1618 |
variable socketWrQueue |
| 1619 |
variable socketClosing |
| 1620 |
variable socketPlayCmd |
| 1621 |
|
| 1622 |
variable $token |
| 1623 |
upvar 0 $token state |
| 1624 |
set tk [namespace tail $token] |
| 1625 |
set sock $state(sock) |
| 1626 |
|
| 1627 |
# If pipelined, connect the next HTTP request to the socket. |
| 1628 |
if {$state(reusing) && $state(-pipeline)} { |
| 1629 |
# Enable next token (if any) to write. |
| 1630 |
# The value "Wready" is set only here, and |
| 1631 |
# in http::Event after reading the response-headers of a |
| 1632 |
# non-reusing transaction. |
| 1633 |
# Previous value is $token. It cannot be pending. |
| 1634 |
set socketWrState($state(socketinfo)) Wready |
| 1635 |
|
| 1636 |
# Now ready to write the next pipelined request (if any). |
| 1637 |
http::NextPipelinedWrite $token |
| 1638 |
} else { |
| 1639 |
# If pipelined, this is the first transaction on this socket. We wait |
| 1640 |
# for the response headers to discover whether the connection is |
| 1641 |
# persistent. (If this is not done and the connection is not |
| 1642 |
# persistent, we SHOULD retry and then MUST NOT pipeline before knowing |
| 1643 |
# that we have a persistent connection |
| 1644 |
# (rfc2616 8.1.2.2)). |
| 1645 |
} |
| 1646 |
|
| 1647 |
# Connect to receive the response, unless the socket is pipelined |
| 1648 |
# and another response is being sent. |
| 1649 |
# This code block is separate from the code below because there are |
| 1650 |
# cases where socketRdState already has the value $token. |
| 1651 |
if { $state(-keepalive) |
| 1652 |
&& $state(-pipeline) |
| 1653 |
&& [info exists socketRdState($state(socketinfo))] |
| 1654 |
&& ($socketRdState($state(socketinfo)) eq "Rready") |
| 1655 |
} { |
| 1656 |
#Log pipelined, GRANT read access to $token in Connected |
| 1657 |
set socketRdState($state(socketinfo)) $token |
| 1658 |
} |
| 1659 |
|
| 1660 |
if { $state(-keepalive) |
| 1661 |
&& $state(-pipeline) |
| 1662 |
&& [info exists socketRdState($state(socketinfo))] |
| 1663 |
&& ($socketRdState($state(socketinfo)) ne $token) |
| 1664 |
} { |
| 1665 |
# Do not read from the socket until it is ready. |
| 1666 |
##Log "HTTP response for token $token is queued for pipelined use" |
| 1667 |
# If $socketClosing(*), then the caller will be a pipelined write and |
| 1668 |
# execution will come here. |
| 1669 |
# This token has already been recorded as "in flight" for writing. |
| 1670 |
# When the socket is closed, the read queue will be cleared in |
| 1671 |
# CloseQueuedQueries and so the "lappend" here has no effect. |
| 1672 |
lappend socketRdQueue($state(socketinfo)) $token |
| 1673 |
} else { |
| 1674 |
# In the pipelined case, connection for reading depends on the |
| 1675 |
# value of socketRdState. |
| 1676 |
# In the nonpipeline case, connection for reading always occurs. |
| 1677 |
ReceiveResponse $token |
| 1678 |
} |
| 1679 |
} |
| 1680 |
|
| 1681 |
# http::ReceiveResponse |
| 1682 |
# |
| 1683 |
# Connects token to its socket for reading. |
| 1684 |
|
| 1685 |
proc http::ReceiveResponse {token} { |
| 1686 |
variable $token |
| 1687 |
upvar 0 $token state |
| 1688 |
set tk [namespace tail $token] |
| 1689 |
set sock $state(sock) |
| 1690 |
|
| 1691 |
#Log ---- $state(socketinfo) >> conn to $token for HTTP response |
| 1692 |
lassign [fconfigure $sock -translation] trRead trWrite |
| 1693 |
fconfigure $sock -translation [list auto $trWrite] \ |
| 1694 |
-buffersize $state(-blocksize) |
| 1695 |
Log ^D$tk begin receiving response - token $token |
| 1696 |
|
| 1697 |
coroutine ${token}EventCoroutine http::Event $sock $token |
| 1698 |
if {[info exists state(-handler)] || [info exists state(-progress)]} { |
| 1699 |
fileevent $sock readable [list http::EventGateway $sock $token] |
| 1700 |
} else { |
| 1701 |
fileevent $sock readable ${token}EventCoroutine |
| 1702 |
} |
| 1703 |
return |
| 1704 |
} |
| 1705 |
|
| 1706 |
|
| 1707 |
# http::EventGateway |
| 1708 |
# |
| 1709 |
# Bug [c2dc1da315]. |
| 1710 |
# - Recursive launch of the coroutine can occur if a -handler or -progress |
| 1711 |
# callback is used, and the callback command enters the event loop. |
| 1712 |
# - To prevent this, the fileevent "binding" is disabled while the |
| 1713 |
# coroutine is in flight. |
| 1714 |
# - If a recursive call occurs despite these precautions, it is not |
| 1715 |
# trapped and discarded here, because it is better to report it as a |
| 1716 |
# bug. |
| 1717 |
# - Although this solution is believed to be sufficiently general, it is |
| 1718 |
# used only if -handler or -progress is specified. In other cases, |
| 1719 |
# the coroutine is called directly. |
| 1720 |
|
| 1721 |
proc http::EventGateway {sock token} { |
| 1722 |
variable $token |
| 1723 |
upvar 0 $token state |
| 1724 |
fileevent $sock readable {} |
| 1725 |
catch {${token}EventCoroutine} res opts |
| 1726 |
if {[info commands ${token}EventCoroutine] ne {}} { |
| 1727 |
# The coroutine can be deleted by completion (a non-yield return), by |
| 1728 |
# http::Finish (when there is a premature end to the transaction), by |
| 1729 |
# http::reset or http::cleanup, or if the caller set option -channel |
| 1730 |
# but not option -handler: in the last case reading from the socket is |
| 1731 |
# now managed by commands ::http::Copy*, http::ReceiveChunked, and |
| 1732 |
# http::make-transformation-chunked. |
| 1733 |
# |
| 1734 |
# Catch in case the coroutine has closed the socket. |
| 1735 |
catch {fileevent $sock readable [list http::EventGateway $sock $token]} |
| 1736 |
} |
| 1737 |
|
| 1738 |
# If there was an error, re-throw it. |
| 1739 |
return -options $opts $res |
| 1740 |
} |
| 1741 |
|
| 1742 |
|
| 1743 |
# http::NextPipelinedWrite |
| 1744 |
# |
| 1745 |
# - Connecting a socket to a token for writing is done by this command and by |
| 1746 |
# command KeepSocket. |
| 1747 |
# - If another request has a pipelined write scheduled for $token's socket, |
| 1748 |
# and if the socket is ready to accept it, connect the write and update |
| 1749 |
# the queue accordingly. |
| 1750 |
# - This command is called from http::DoneRequest and http::Event, |
| 1751 |
# IF $state(-pipeline) AND (the current transfer has reached the point at |
| 1752 |
# which the socket is ready for the next request to be written). |
| 1753 |
# - This command is called when a token has write access and is pipelined and |
| 1754 |
# keep-alive, and sets socketWrState to Wready. |
| 1755 |
# - The command need not consider the case where socketWrState is set to a token |
| 1756 |
# that does not yet have write access. Such a token is waiting for Rready, |
| 1757 |
# and the assignment of the connection to the token will be done elsewhere (in |
| 1758 |
# http::KeepSocket). |
| 1759 |
# - This command cannot be called after socketWrState has been set to a |
| 1760 |
# "pending" token value (that is then overwritten by the caller), because that |
| 1761 |
# value is set by this command when it is called by an earlier token when it |
| 1762 |
# relinquishes its write access, and the pending token is always the next in |
| 1763 |
# line to write. |
| 1764 |
|
| 1765 |
proc http::NextPipelinedWrite {token} { |
| 1766 |
variable http |
| 1767 |
variable socketRdState |
| 1768 |
variable socketWrState |
| 1769 |
variable socketWrQueue |
| 1770 |
variable socketClosing |
| 1771 |
variable $token |
| 1772 |
upvar 0 $token state |
| 1773 |
set connId $state(socketinfo) |
| 1774 |
|
| 1775 |
if { [info exists socketClosing($connId)] |
| 1776 |
&& $socketClosing($connId) |
| 1777 |
} { |
| 1778 |
# socketClosing(*) is set because the server has sent a |
| 1779 |
# "Connection: close" header. |
| 1780 |
# Behave as if the queues are empty - so do nothing. |
| 1781 |
} elseif { $state(-pipeline) |
| 1782 |
&& [info exists socketWrState($connId)] |
| 1783 |
&& ($socketWrState($connId) eq "Wready") |
| 1784 |
|
| 1785 |
&& [info exists socketWrQueue($connId)] |
| 1786 |
&& [llength $socketWrQueue($connId)] |
| 1787 |
&& ([set token2 [lindex $socketWrQueue($connId) 0] |
| 1788 |
set ${token2}(-pipeline) |
| 1789 |
] |
| 1790 |
) |
| 1791 |
} { |
| 1792 |
# - The usual case for a pipelined connection, ready for a new request. |
| 1793 |
#Log pipelined, GRANT write access to $token2 in NextPipelinedWrite |
| 1794 |
set conn [set ${token2}(tmpConnArgs)] |
| 1795 |
set socketWrState($connId) $token2 |
| 1796 |
set socketWrQueue($connId) [lrange $socketWrQueue($connId) 1 end] |
| 1797 |
# Connect does its own fconfigure. |
| 1798 |
fileevent $state(sock) writable [list http::Connect $token2 {*}$conn] |
| 1799 |
#Log ---- $connId << conn to $token2 for HTTP request (b) |
| 1800 |
|
| 1801 |
# In the tests below, the next request will be nonpipeline. |
| 1802 |
} elseif { $state(-pipeline) |
| 1803 |
&& [info exists socketWrState($connId)] |
| 1804 |
&& ($socketWrState($connId) eq "Wready") |
| 1805 |
|
| 1806 |
&& [info exists socketWrQueue($connId)] |
| 1807 |
&& [llength $socketWrQueue($connId)] |
| 1808 |
&& (![ set token3 [lindex $socketWrQueue($connId) 0] |
| 1809 |
set ${token3}(-pipeline) |
| 1810 |
] |
| 1811 |
) |
| 1812 |
|
| 1813 |
&& [info exists socketRdState($connId)] |
| 1814 |
&& ($socketRdState($connId) eq "Rready") |
| 1815 |
} { |
| 1816 |
# The case in which the next request will be non-pipelined, and the read |
| 1817 |
# and write queues is ready: which is the condition for a non-pipelined |
| 1818 |
# write. |
| 1819 |
variable $token3 |
| 1820 |
upvar 0 $token3 state3 |
| 1821 |
set conn [set ${token3}(tmpConnArgs)] |
| 1822 |
#Log nonpipeline, GRANT r/w access to $token3 in NextPipelinedWrite |
| 1823 |
set socketRdState($connId) $token3 |
| 1824 |
set socketWrState($connId) $token3 |
| 1825 |
set socketWrQueue($connId) [lrange $socketWrQueue($connId) 1 end] |
| 1826 |
# Connect does its own fconfigure. |
| 1827 |
fileevent $state(sock) writable [list http::Connect $token3 {*}$conn] |
| 1828 |
#Log ---- $state(sock) << conn to $token3 for HTTP request (c) |
| 1829 |
|
| 1830 |
} elseif { $state(-pipeline) |
| 1831 |
&& [info exists socketWrState($connId)] |
| 1832 |
&& ($socketWrState($connId) eq "Wready") |
| 1833 |
|
| 1834 |
&& [info exists socketWrQueue($connId)] |
| 1835 |
&& [llength $socketWrQueue($connId)] |
| 1836 |
&& (![set token2 [lindex $socketWrQueue($connId) 0] |
| 1837 |
set ${token2}(-pipeline) |
| 1838 |
] |
| 1839 |
) |
| 1840 |
} { |
| 1841 |
# - The case in which the next request will be non-pipelined, but the |
| 1842 |
# read queue is NOT ready. |
| 1843 |
# - A read is queued or in progress, but not a write. Cannot start the |
| 1844 |
# nonpipeline transaction, but must set socketWrState to prevent a new |
| 1845 |
# pipelined request (in http::geturl) jumping the queue. |
| 1846 |
# - Because socketWrState($connId) is not set to Wready, the assignment |
| 1847 |
# of the connection to $token2 will be done elsewhere - by command |
| 1848 |
# http::KeepSocket when $socketRdState($connId) is set to "Rready". |
| 1849 |
|
| 1850 |
#Log re-use nonpipeline, GRANT delayed write access to $token in NextP.. |
| 1851 |
set socketWrState($connId) peNding |
| 1852 |
} |
| 1853 |
} |
| 1854 |
|
| 1855 |
# http::CancelReadPipeline |
| 1856 |
# |
| 1857 |
# Cancel pipelined responses on a closing "Keep-Alive" socket. |
| 1858 |
# |
| 1859 |
# - Called by a variable trace on "unset socketRdState($connId)". |
| 1860 |
# - The variable relates to a Keep-Alive socket, which has been closed. |
| 1861 |
# - Cancels all pipelined responses. The requests have been sent, |
| 1862 |
# the responses have not yet been received. |
| 1863 |
# - This is a hard cancel that ends each transaction with error status, |
| 1864 |
# and closes the connection. Do not use it if you want to replay failed |
| 1865 |
# transactions. |
| 1866 |
# - N.B. Always delete ::http::socketRdState($connId) before deleting |
| 1867 |
# ::http::socketRdQueue($connId), or this command will do nothing. |
| 1868 |
# |
| 1869 |
# Arguments |
| 1870 |
# As for a trace command on a variable. |
| 1871 |
|
| 1872 |
proc http::CancelReadPipeline {name1 connId op} { |
| 1873 |
variable socketRdQueue |
| 1874 |
##Log CancelReadPipeline $name1 $connId $op |
| 1875 |
if {[info exists socketRdQueue($connId)]} { |
| 1876 |
set msg {the connection was closed by CancelReadPipeline} |
| 1877 |
foreach token $socketRdQueue($connId) { |
| 1878 |
set tk [namespace tail $token] |
| 1879 |
Log ^X$tk end of response "($msg)" - token $token |
| 1880 |
set ${token}(status) eof |
| 1881 |
Finish $token ;#$msg |
| 1882 |
} |
| 1883 |
set socketRdQueue($connId) {} |
| 1884 |
} |
| 1885 |
} |
| 1886 |
|
| 1887 |
# http::CancelWritePipeline |
| 1888 |
# |
| 1889 |
# Cancel queued events on a closing "Keep-Alive" socket. |
| 1890 |
# |
| 1891 |
# - Called by a variable trace on "unset socketWrState($connId)". |
| 1892 |
# - The variable relates to a Keep-Alive socket, which has been closed. |
| 1893 |
# - In pipelined or nonpipeline case: cancels all queued requests. The |
| 1894 |
# requests have not yet been sent, the responses are not due. |
| 1895 |
# - This is a hard cancel that ends each transaction with error status, |
| 1896 |
# and closes the connection. Do not use it if you want to replay failed |
| 1897 |
# transactions. |
| 1898 |
# - N.B. Always delete ::http::socketWrState($connId) before deleting |
| 1899 |
# ::http::socketWrQueue($connId), or this command will do nothing. |
| 1900 |
# |
| 1901 |
# Arguments |
| 1902 |
# As for a trace command on a variable. |
| 1903 |
|
| 1904 |
proc http::CancelWritePipeline {name1 connId op} { |
| 1905 |
variable socketWrQueue |
| 1906 |
|
| 1907 |
##Log CancelWritePipeline $name1 $connId $op |
| 1908 |
if {[info exists socketWrQueue($connId)]} { |
| 1909 |
set msg {the connection was closed by CancelWritePipeline} |
| 1910 |
foreach token $socketWrQueue($connId) { |
| 1911 |
set tk [namespace tail $token] |
| 1912 |
Log ^X$tk end of response "($msg)" - token $token |
| 1913 |
set ${token}(status) eof |
| 1914 |
Finish $token ;#$msg |
| 1915 |
} |
| 1916 |
set socketWrQueue($connId) {} |
| 1917 |
} |
| 1918 |
} |
| 1919 |
|
| 1920 |
# http::ReplayIfDead -- |
| 1921 |
# |
| 1922 |
# - A query on a re-used persistent socket failed at the earliest opportunity, |
| 1923 |
# because the socket had been closed by the server. Keep the token, tidy up, |
| 1924 |
# and try to connect on a fresh socket. |
| 1925 |
# - The connection is monitored for eof by the command http::CheckEof. Thus |
| 1926 |
# http::ReplayIfDead is needed only when a server event (half-closing an |
| 1927 |
# apparently idle connection), and a client event (sending a request) occur at |
| 1928 |
# almost the same time, and neither client nor server detects the other's |
| 1929 |
# action before performing its own (an "asynchronous close event"). |
| 1930 |
# - To simplify testing of http::ReplayIfDead, set TEST_EOF 1 in |
| 1931 |
# http::KeepSocket, and then http::ReplayIfDead will be called if http::geturl |
| 1932 |
# is called at any time after the server timeout. |
| 1933 |
# |
| 1934 |
# Arguments: |
| 1935 |
# token Connection token. |
| 1936 |
# |
| 1937 |
# Side Effects: |
| 1938 |
# Use the same token, but try to open a new socket. |
| 1939 |
|
| 1940 |
proc http::ReplayIfDead {tokenArg doing} { |
| 1941 |
variable socketMapping |
| 1942 |
variable socketRdState |
| 1943 |
variable socketWrState |
| 1944 |
variable socketRdQueue |
| 1945 |
variable socketWrQueue |
| 1946 |
variable socketClosing |
| 1947 |
variable socketPlayCmd |
| 1948 |
|
| 1949 |
variable $tokenArg |
| 1950 |
upvar 0 $tokenArg stateArg |
| 1951 |
|
| 1952 |
Log running http::ReplayIfDead for $tokenArg $doing |
| 1953 |
|
| 1954 |
# 1. Merge the tokens for transactions in flight, the read (response) queue, |
| 1955 |
# and the write (request) queue. |
| 1956 |
|
| 1957 |
set InFlightR {} |
| 1958 |
set InFlightW {} |
| 1959 |
|
| 1960 |
# Obtain the tokens for transactions in flight. |
| 1961 |
if {$stateArg(-pipeline)} { |
| 1962 |
# Two transactions may be in flight. The "read" transaction was first. |
| 1963 |
# It is unlikely that the server would close the socket if a response |
| 1964 |
# was pending; however, an earlier request (as well as the present |
| 1965 |
# request) may have been sent and ignored if the socket was half-closed |
| 1966 |
# by the server. |
| 1967 |
|
| 1968 |
if { [info exists socketRdState($stateArg(socketinfo))] |
| 1969 |
&& ($socketRdState($stateArg(socketinfo)) ne "Rready") |
| 1970 |
} { |
| 1971 |
lappend InFlightR $socketRdState($stateArg(socketinfo)) |
| 1972 |
} elseif {($doing eq "read")} { |
| 1973 |
lappend InFlightR $tokenArg |
| 1974 |
} |
| 1975 |
|
| 1976 |
if { [info exists socketWrState($stateArg(socketinfo))] |
| 1977 |
&& $socketWrState($stateArg(socketinfo)) ni {Wready peNding} |
| 1978 |
} { |
| 1979 |
lappend InFlightW $socketWrState($stateArg(socketinfo)) |
| 1980 |
} elseif {($doing eq "write")} { |
| 1981 |
lappend InFlightW $tokenArg |
| 1982 |
} |
| 1983 |
|
| 1984 |
# Report any inconsistency of $tokenArg with socket*state. |
| 1985 |
if { ($doing eq "read") |
| 1986 |
&& [info exists socketRdState($stateArg(socketinfo))] |
| 1987 |
&& ($tokenArg ne $socketRdState($stateArg(socketinfo))) |
| 1988 |
} { |
| 1989 |
Log WARNING - ReplayIfDead pipelined tokenArg $tokenArg $doing \ |
| 1990 |
ne socketRdState($stateArg(socketinfo)) \ |
| 1991 |
$socketRdState($stateArg(socketinfo)) |
| 1992 |
|
| 1993 |
} elseif { |
| 1994 |
($doing eq "write") |
| 1995 |
&& [info exists socketWrState($stateArg(socketinfo))] |
| 1996 |
&& ($tokenArg ne $socketWrState($stateArg(socketinfo))) |
| 1997 |
} { |
| 1998 |
Log WARNING - ReplayIfDead pipelined tokenArg $tokenArg $doing \ |
| 1999 |
ne socketWrState($stateArg(socketinfo)) \ |
| 2000 |
$socketWrState($stateArg(socketinfo)) |
| 2001 |
} |
| 2002 |
} else { |
| 2003 |
# One transaction should be in flight. |
| 2004 |
# socketRdState, socketWrQueue are used. |
| 2005 |
# socketRdQueue should be empty. |
| 2006 |
|
| 2007 |
# Report any inconsistency of $tokenArg with socket*state. |
| 2008 |
if {$tokenArg ne $socketRdState($stateArg(socketinfo))} { |
| 2009 |
Log WARNING - ReplayIfDead nonpipeline tokenArg $tokenArg $doing \ |
| 2010 |
ne socketRdState($stateArg(socketinfo)) \ |
| 2011 |
$socketRdState($stateArg(socketinfo)) |
| 2012 |
} |
| 2013 |
|
| 2014 |
# Report the inconsistency that socketRdQueue is non-empty. |
| 2015 |
if { [info exists socketRdQueue($stateArg(socketinfo))] |
| 2016 |
&& ($socketRdQueue($stateArg(socketinfo)) ne {}) |
| 2017 |
} { |
| 2018 |
Log WARNING - ReplayIfDead nonpipeline tokenArg $tokenArg $doing \ |
| 2019 |
has read queue socketRdQueue($stateArg(socketinfo)) \ |
| 2020 |
$socketRdQueue($stateArg(socketinfo)) ne {} |
| 2021 |
} |
| 2022 |
|
| 2023 |
lappend InFlightW $socketRdState($stateArg(socketinfo)) |
| 2024 |
set socketRdQueue($stateArg(socketinfo)) {} |
| 2025 |
} |
| 2026 |
|
| 2027 |
set newQueue {} |
| 2028 |
lappend newQueue {*}$InFlightR |
| 2029 |
lappend newQueue {*}$socketRdQueue($stateArg(socketinfo)) |
| 2030 |
lappend newQueue {*}$InFlightW |
| 2031 |
lappend newQueue {*}$socketWrQueue($stateArg(socketinfo)) |
| 2032 |
|
| 2033 |
|
| 2034 |
# 2. Tidy up tokenArg. This is a cut-down form of Finish/CloseSocket. |
| 2035 |
# Do not change state(status). |
| 2036 |
# No need to after cancel stateArg(after) - either this is done in |
| 2037 |
# ReplayCore/ReInit, or Finish is called. |
| 2038 |
|
| 2039 |
catch {close $stateArg(sock)} |
| 2040 |
|
| 2041 |
# 2a. Tidy the tokens in the queues - this is done in ReplayCore/ReInit. |
| 2042 |
# - Transactions, if any, that are awaiting responses cannot be completed. |
| 2043 |
# They are listed for re-sending in newQueue. |
| 2044 |
# - All tokens are preserved for re-use by ReplayCore, and their variables |
| 2045 |
# will be re-initialised by calls to ReInit. |
| 2046 |
# - The relevant element of socketMapping, socketRdState, socketWrState, |
| 2047 |
# socketRdQueue, socketWrQueue, socketClosing, socketPlayCmd will be set |
| 2048 |
# to new values in ReplayCore. |
| 2049 |
|
| 2050 |
ReplayCore $newQueue |
| 2051 |
} |
| 2052 |
|
| 2053 |
# http::ReplayIfClose -- |
| 2054 |
# |
| 2055 |
# A request on a socket that was previously "Connection: keep-alive" has |
| 2056 |
# received a "Connection: close" response header. The server supplies |
| 2057 |
# that response correctly, but any later requests already queued on this |
| 2058 |
# connection will be lost when the socket closes. |
| 2059 |
# |
| 2060 |
# This command takes arguments that represent the socketWrState, |
| 2061 |
# socketRdQueue and socketWrQueue for this connection. The socketRdState |
| 2062 |
# is not needed because the server responds in full to the request that |
| 2063 |
# received the "Connection: close" response header. |
| 2064 |
# |
| 2065 |
# Existing request tokens $token (::http::$n) are preserved. The caller |
| 2066 |
# will be unaware that the request was processed this way. |
| 2067 |
|
| 2068 |
proc http::ReplayIfClose {Wstate Rqueue Wqueue} { |
| 2069 |
Log running http::ReplayIfClose for $Wstate $Rqueue $Wqueue |
| 2070 |
|
| 2071 |
if {$Wstate in $Rqueue || $Wstate in $Wqueue} { |
| 2072 |
Log WARNING duplicate token in http::ReplayIfClose - token $Wstate |
| 2073 |
set Wstate Wready |
| 2074 |
} |
| 2075 |
|
| 2076 |
# 1. Create newQueue |
| 2077 |
set InFlightW {} |
| 2078 |
if {$Wstate ni {Wready peNding}} { |
| 2079 |
lappend InFlightW $Wstate |
| 2080 |
} |
| 2081 |
|
| 2082 |
set newQueue {} |
| 2083 |
lappend newQueue {*}$Rqueue |
| 2084 |
lappend newQueue {*}$InFlightW |
| 2085 |
lappend newQueue {*}$Wqueue |
| 2086 |
|
| 2087 |
# 2. Cleanup - none needed, done by the caller. |
| 2088 |
|
| 2089 |
ReplayCore $newQueue |
| 2090 |
} |
| 2091 |
|
| 2092 |
# http::ReInit -- |
| 2093 |
# |
| 2094 |
# Command to restore a token's state to a condition that |
| 2095 |
# makes it ready to replay a request. |
| 2096 |
# |
| 2097 |
# Command http::geturl stores extra state in state(tmp*) so |
| 2098 |
# we don't need to do the argument processing again. |
| 2099 |
# |
| 2100 |
# The caller must: |
| 2101 |
# - Set state(reusing) and state(sock) to their new values after calling |
| 2102 |
# this command. |
| 2103 |
# - Unset state(tmpState), state(tmpOpenCmd) if future calls to ReplayCore |
| 2104 |
# or ReInit are inappropriate for this token. Typically only one retry |
| 2105 |
# is allowed. |
| 2106 |
# The caller may also unset state(tmpConnArgs) if this value (and the |
| 2107 |
# token) will be used immediately. The value is needed by tokens that |
| 2108 |
# will be stored in a queue. |
| 2109 |
# |
| 2110 |
# Arguments: |
| 2111 |
# token Connection token. |
| 2112 |
# |
| 2113 |
# Return Value: (boolean) true iff the re-initialisation was successful. |
| 2114 |
|
| 2115 |
proc http::ReInit {token} { |
| 2116 |
variable $token |
| 2117 |
upvar 0 $token state |
| 2118 |
|
| 2119 |
if {!( |
| 2120 |
[info exists state(tmpState)] |
| 2121 |
&& [info exists state(tmpOpenCmd)] |
| 2122 |
&& [info exists state(tmpConnArgs)] |
| 2123 |
) |
| 2124 |
} { |
| 2125 |
Log FAILED in http::ReInit via ReplayCore - NO tmp vars for $token |
| 2126 |
return 0 |
| 2127 |
} |
| 2128 |
|
| 2129 |
if {[info exists state(after)]} { |
| 2130 |
after cancel $state(after) |
| 2131 |
unset state(after) |
| 2132 |
} |
| 2133 |
|
| 2134 |
# Don't alter state(status) - this would trigger http::wait if it is in use. |
| 2135 |
set tmpState $state(tmpState) |
| 2136 |
set tmpOpenCmd $state(tmpOpenCmd) |
| 2137 |
set tmpConnArgs $state(tmpConnArgs) |
| 2138 |
foreach name [array names state] { |
| 2139 |
if {$name ne "status"} { |
| 2140 |
unset state($name) |
| 2141 |
} |
| 2142 |
} |
| 2143 |
|
| 2144 |
# Don't alter state(status). |
| 2145 |
# Restore state(tmp*) - the caller may decide to unset them. |
| 2146 |
# Restore state(tmpConnArgs) which is needed for connection. |
| 2147 |
# state(tmpState), state(tmpOpenCmd) are needed only for retries. |
| 2148 |
|
| 2149 |
dict unset tmpState status |
| 2150 |
array set state $tmpState |
| 2151 |
set state(tmpState) $tmpState |
| 2152 |
set state(tmpOpenCmd) $tmpOpenCmd |
| 2153 |
set state(tmpConnArgs) $tmpConnArgs |
| 2154 |
|
| 2155 |
return 1 |
| 2156 |
} |
| 2157 |
|
| 2158 |
# http::ReplayCore -- |
| 2159 |
# |
| 2160 |
# Command to replay a list of requests, using existing connection tokens. |
| 2161 |
# |
| 2162 |
# Abstracted from http::geturl which stores extra state in state(tmp*) so |
| 2163 |
# we don't need to do the argument processing again. |
| 2164 |
# |
| 2165 |
# Arguments: |
| 2166 |
# newQueue List of connection tokens. |
| 2167 |
# |
| 2168 |
# Side Effects: |
| 2169 |
# Use existing tokens, but try to open a new socket. |
| 2170 |
|
| 2171 |
proc http::ReplayCore {newQueue} { |
| 2172 |
variable socketMapping |
| 2173 |
variable socketRdState |
| 2174 |
variable socketWrState |
| 2175 |
variable socketRdQueue |
| 2176 |
variable socketWrQueue |
| 2177 |
variable socketClosing |
| 2178 |
variable socketPlayCmd |
| 2179 |
|
| 2180 |
if {[llength $newQueue] == 0} { |
| 2181 |
# Nothing to do. |
| 2182 |
return |
| 2183 |
} |
| 2184 |
|
| 2185 |
##Log running ReplayCore for {*}$newQueue |
| 2186 |
set newToken [lindex $newQueue 0] |
| 2187 |
set newQueue [lrange $newQueue 1 end] |
| 2188 |
|
| 2189 |
# 3. Use newToken, and restore its values of state(*). Do not restore |
| 2190 |
# elements tmp* - we try again only once. |
| 2191 |
|
| 2192 |
set token $newToken |
| 2193 |
variable $token |
| 2194 |
upvar 0 $token state |
| 2195 |
|
| 2196 |
if {![ReInit $token]} { |
| 2197 |
Log FAILED in http::ReplayCore - NO tmp vars |
| 2198 |
Finish $token {cannot send this request again} |
| 2199 |
return |
| 2200 |
} |
| 2201 |
|
| 2202 |
set tmpState $state(tmpState) |
| 2203 |
set tmpOpenCmd $state(tmpOpenCmd) |
| 2204 |
set tmpConnArgs $state(tmpConnArgs) |
| 2205 |
unset state(tmpState) |
| 2206 |
unset state(tmpOpenCmd) |
| 2207 |
unset state(tmpConnArgs) |
| 2208 |
|
| 2209 |
set state(reusing) 0 |
| 2210 |
|
| 2211 |
if {$state(-timeout) > 0} { |
| 2212 |
set resetCmd [list http::reset $token timeout] |
| 2213 |
set state(after) [after $state(-timeout) $resetCmd] |
| 2214 |
} |
| 2215 |
|
| 2216 |
set pre [clock milliseconds] |
| 2217 |
##Log pre socket opened, - token $token |
| 2218 |
##Log $tmpOpenCmd - token $token |
| 2219 |
# 4. Open a socket. |
| 2220 |
if {[catch {eval $tmpOpenCmd} sock]} { |
| 2221 |
# Something went wrong while trying to establish the connection. |
| 2222 |
Log FAILED - $sock |
| 2223 |
set state(sock) NONE |
| 2224 |
Finish $token $sock |
| 2225 |
return |
| 2226 |
} |
| 2227 |
##Log post socket opened, - token $token |
| 2228 |
set delay [expr {[clock milliseconds] - $pre}] |
| 2229 |
if {$delay > 3000} { |
| 2230 |
Log socket delay $delay - token $token |
| 2231 |
} |
| 2232 |
# Command [socket] is called with -async, but takes 5s to 5.1s to return, |
| 2233 |
# with probability of order 1 in 10,000. This may be a bizarre scheduling |
| 2234 |
# issue with my (KJN's) system (Fedora Linux). |
| 2235 |
# This does not cause a problem (unless the request times out when this |
| 2236 |
# command returns). |
| 2237 |
|
| 2238 |
# 5. Configure the persistent socket data. |
| 2239 |
if {$state(-keepalive)} { |
| 2240 |
set socketMapping($state(socketinfo)) $sock |
| 2241 |
|
| 2242 |
if {![info exists socketRdState($state(socketinfo))]} { |
| 2243 |
set socketRdState($state(socketinfo)) {} |
| 2244 |
set varName ::http::socketRdState($state(socketinfo)) |
| 2245 |
trace add variable $varName unset ::http::CancelReadPipeline |
| 2246 |
} |
| 2247 |
|
| 2248 |
if {![info exists socketWrState($state(socketinfo))]} { |
| 2249 |
set socketWrState($state(socketinfo)) {} |
| 2250 |
set varName ::http::socketWrState($state(socketinfo)) |
| 2251 |
trace add variable $varName unset ::http::CancelWritePipeline |
| 2252 |
} |
| 2253 |
|
| 2254 |
if {$state(-pipeline)} { |
| 2255 |
#Log new, init for pipelined, GRANT write acc to $token ReplayCore |
| 2256 |
set socketRdState($state(socketinfo)) $token |
| 2257 |
set socketWrState($state(socketinfo)) $token |
| 2258 |
} else { |
| 2259 |
#Log new, init for nonpipeline, GRANT r/w acc to $token ReplayCore |
| 2260 |
set socketRdState($state(socketinfo)) $token |
| 2261 |
set socketWrState($state(socketinfo)) $token |
| 2262 |
} |
| 2263 |
|
| 2264 |
set socketRdQueue($state(socketinfo)) {} |
| 2265 |
set socketWrQueue($state(socketinfo)) $newQueue |
| 2266 |
set socketClosing($state(socketinfo)) 0 |
| 2267 |
set socketPlayCmd($state(socketinfo)) {ReplayIfClose Wready {} {}} |
| 2268 |
} |
| 2269 |
|
| 2270 |
##Log pre newQueue ReInit, - token $token |
| 2271 |
# 6. Configure sockets in the queue. |
| 2272 |
foreach tok $newQueue { |
| 2273 |
if {[ReInit $tok]} { |
| 2274 |
set ${tok}(reusing) 1 |
| 2275 |
set ${tok}(sock) $sock |
| 2276 |
} else { |
| 2277 |
set ${tok}(reusing) 1 |
| 2278 |
set ${tok}(sock) NONE |
| 2279 |
Finish $token {cannot send this request again} |
| 2280 |
} |
| 2281 |
} |
| 2282 |
|
| 2283 |
# 7. Configure the socket for newToken to send a request. |
| 2284 |
set state(sock) $sock |
| 2285 |
Log "Using $sock for $state(socketinfo) - token $token" \ |
| 2286 |
[expr {$state(-keepalive)?"keepalive":""}] |
| 2287 |
|
| 2288 |
# Initialisation of a new socket. |
| 2289 |
##Log socket opened, now fconfigure - token $token |
| 2290 |
fconfigure $sock -translation {auto crlf} -buffersize $state(-blocksize) |
| 2291 |
##Log socket opened, DONE fconfigure - token $token |
| 2292 |
|
| 2293 |
# Connect does its own fconfigure. |
| 2294 |
fileevent $sock writable [list http::Connect $token {*}$tmpConnArgs] |
| 2295 |
#Log ---- $sock << conn to $token for HTTP request (e) |
| 2296 |
} |
| 2297 |
|
| 2298 |
# Data access functions: |
| 2299 |
# Data - the URL data |
| 2300 |
# Status - the transaction status: ok, reset, eof, timeout, error |
| 2301 |
# Code - the HTTP transaction code, e.g., 200 |
| 2302 |
# Size - the size of the URL data |
| 2303 |
|
| 2304 |
proc http::data {token} { |
| 2305 |
variable $token |
| 2306 |
upvar 0 $token state |
| 2307 |
return $state(body) |
| 2308 |
} |
| 2309 |
proc http::status {token} { |
| 2310 |
if {![info exists $token]} { |
| 2311 |
return "error" |
| 2312 |
} |
| 2313 |
variable $token |
| 2314 |
upvar 0 $token state |
| 2315 |
return $state(status) |
| 2316 |
} |
| 2317 |
proc http::code {token} { |
| 2318 |
variable $token |
| 2319 |
upvar 0 $token state |
| 2320 |
return $state(http) |
| 2321 |
} |
| 2322 |
proc http::ncode {token} { |
| 2323 |
variable $token |
| 2324 |
upvar 0 $token state |
| 2325 |
if {[regexp {[0-9]{3}} $state(http) numeric_code]} { |
| 2326 |
return $numeric_code |
| 2327 |
} else { |
| 2328 |
return $state(http) |
| 2329 |
} |
| 2330 |
} |
| 2331 |
proc http::size {token} { |
| 2332 |
variable $token |
| 2333 |
upvar 0 $token state |
| 2334 |
return $state(currentsize) |
| 2335 |
} |
| 2336 |
proc http::meta {token} { |
| 2337 |
variable $token |
| 2338 |
upvar 0 $token state |
| 2339 |
return $state(meta) |
| 2340 |
} |
| 2341 |
proc http::error {token} { |
| 2342 |
variable $token |
| 2343 |
upvar 0 $token state |
| 2344 |
if {[info exists state(error)]} { |
| 2345 |
return $state(error) |
| 2346 |
} |
| 2347 |
return "" |
| 2348 |
} |
| 2349 |
|
| 2350 |
# http::cleanup |
| 2351 |
# |
| 2352 |
# Garbage collect the state associated with a transaction |
| 2353 |
# |
| 2354 |
# Arguments |
| 2355 |
# token The token returned from http::geturl |
| 2356 |
# |
| 2357 |
# Side Effects |
| 2358 |
# Unsets the state array. |
| 2359 |
|
| 2360 |
proc http::cleanup {token} { |
| 2361 |
variable $token |
| 2362 |
upvar 0 $token state |
| 2363 |
if {[info commands ${token}EventCoroutine] ne {}} { |
| 2364 |
rename ${token}EventCoroutine {} |
| 2365 |
} |
| 2366 |
if {[info exists state(after)]} { |
| 2367 |
after cancel $state(after) |
| 2368 |
unset state(after) |
| 2369 |
} |
| 2370 |
if {[info exists state]} { |
| 2371 |
unset state |
| 2372 |
} |
| 2373 |
} |
| 2374 |
|
| 2375 |
# http::Connect |
| 2376 |
# |
| 2377 |
# This callback is made when an asynchronous connection completes. |
| 2378 |
# |
| 2379 |
# Arguments |
| 2380 |
# token The token returned from http::geturl |
| 2381 |
# |
| 2382 |
# Side Effects |
| 2383 |
# Sets the status of the connection, which unblocks |
| 2384 |
# the waiting geturl call |
| 2385 |
|
| 2386 |
proc http::Connect {token proto phost srvurl} { |
| 2387 |
variable $token |
| 2388 |
upvar 0 $token state |
| 2389 |
set tk [namespace tail $token] |
| 2390 |
set err "due to unexpected EOF" |
| 2391 |
if { |
| 2392 |
[eof $state(sock)] || |
| 2393 |
[set err [fconfigure $state(sock) -error]] ne "" |
| 2394 |
} { |
| 2395 |
Log "WARNING - if testing, pay special attention to this\ |
| 2396 |
case (GJ) which is seldom executed - token $token" |
| 2397 |
if {[info exists state(reusing)] && $state(reusing)} { |
| 2398 |
# The socket was closed at the server end, and closed at |
| 2399 |
# this end by http::CheckEof. |
| 2400 |
if {[TestForReplay $token write $err b]} { |
| 2401 |
return |
| 2402 |
} |
| 2403 |
|
| 2404 |
# else: |
| 2405 |
# This is NOT a persistent socket that has been closed since its |
| 2406 |
# last use. |
| 2407 |
# If any other requests are in flight or pipelined/queued, they will |
| 2408 |
# be discarded. |
| 2409 |
} |
| 2410 |
Finish $token "connect failed $err" |
| 2411 |
} else { |
| 2412 |
set state(state) connecting |
| 2413 |
fileevent $state(sock) writable {} |
| 2414 |
::http::Connected $token $proto $phost $srvurl |
| 2415 |
} |
| 2416 |
} |
| 2417 |
|
| 2418 |
# http::Write |
| 2419 |
# |
| 2420 |
# Write POST query data to the socket |
| 2421 |
# |
| 2422 |
# Arguments |
| 2423 |
# token The token for the connection |
| 2424 |
# |
| 2425 |
# Side Effects |
| 2426 |
# Write the socket and handle callbacks. |
| 2427 |
|
| 2428 |
proc http::Write {token} { |
| 2429 |
variable http |
| 2430 |
variable socketMapping |
| 2431 |
variable socketRdState |
| 2432 |
variable socketWrState |
| 2433 |
variable socketRdQueue |
| 2434 |
variable socketWrQueue |
| 2435 |
variable socketClosing |
| 2436 |
variable socketPlayCmd |
| 2437 |
|
| 2438 |
variable $token |
| 2439 |
upvar 0 $token state |
| 2440 |
set tk [namespace tail $token] |
| 2441 |
set sock $state(sock) |
| 2442 |
|
| 2443 |
# Output a block. Tcl will buffer this if the socket blocks |
| 2444 |
set done 0 |
| 2445 |
if {[catch { |
| 2446 |
# Catch I/O errors on dead sockets |
| 2447 |
|
| 2448 |
if {[info exists state(-query)]} { |
| 2449 |
# Chop up large query strings so queryprogress callback can give |
| 2450 |
# smooth feedback. |
| 2451 |
if { $state(queryoffset) + $state(-queryblocksize) |
| 2452 |
>= $state(querylength) |
| 2453 |
} { |
| 2454 |
# This will be the last puts for the request-body. |
| 2455 |
if { (![catch {fileevent $sock readable} binding]) |
| 2456 |
&& ($binding eq [list http::CheckEof $sock]) |
| 2457 |
} { |
| 2458 |
# Remove the "fileevent readable" binding of an idle |
| 2459 |
# persistent socket to http::CheckEof. We can no longer |
| 2460 |
# treat bytes received as junk. The server might still time |
| 2461 |
# out and half-close the socket if it has not yet received |
| 2462 |
# the first "puts". |
| 2463 |
fileevent $sock readable {} |
| 2464 |
} |
| 2465 |
} |
| 2466 |
puts -nonewline $sock \ |
| 2467 |
[string range $state(-query) $state(queryoffset) \ |
| 2468 |
[expr {$state(queryoffset) + $state(-queryblocksize) - 1}]] |
| 2469 |
incr state(queryoffset) $state(-queryblocksize) |
| 2470 |
if {$state(queryoffset) >= $state(querylength)} { |
| 2471 |
set state(queryoffset) $state(querylength) |
| 2472 |
set done 1 |
| 2473 |
} |
| 2474 |
} else { |
| 2475 |
# Copy blocks from the query channel |
| 2476 |
|
| 2477 |
set outStr [read $state(-querychannel) $state(-queryblocksize)] |
| 2478 |
if {[eof $state(-querychannel)]} { |
| 2479 |
# This will be the last puts for the request-body. |
| 2480 |
if { (![catch {fileevent $sock readable} binding]) |
| 2481 |
&& ($binding eq [list http::CheckEof $sock]) |
| 2482 |
} { |
| 2483 |
# Remove the "fileevent readable" binding of an idle |
| 2484 |
# persistent socket to http::CheckEof. We can no longer |
| 2485 |
# treat bytes received as junk. The server might still time |
| 2486 |
# out and half-close the socket if it has not yet received |
| 2487 |
# the first "puts". |
| 2488 |
fileevent $sock readable {} |
| 2489 |
} |
| 2490 |
} |
| 2491 |
puts -nonewline $sock $outStr |
| 2492 |
incr state(queryoffset) [string length $outStr] |
| 2493 |
if {[eof $state(-querychannel)]} { |
| 2494 |
set done 1 |
| 2495 |
} |
| 2496 |
} |
| 2497 |
} err]} { |
| 2498 |
# Do not call Finish here, but instead let the read half of the socket |
| 2499 |
# process whatever server reply there is to get. |
| 2500 |
|
| 2501 |
set state(posterror) $err |
| 2502 |
set done 1 |
| 2503 |
} |
| 2504 |
|
| 2505 |
if {$done} { |
| 2506 |
catch {flush $sock} |
| 2507 |
fileevent $sock writable {} |
| 2508 |
Log ^C$tk end sending request - token $token |
| 2509 |
# End of writing (POST method). The request has been sent. |
| 2510 |
|
| 2511 |
DoneRequest $token |
| 2512 |
} |
| 2513 |
|
| 2514 |
# Callback to the client after we've completely handled everything. |
| 2515 |
|
| 2516 |
if {[string length $state(-queryprogress)]} { |
| 2517 |
eval $state(-queryprogress) \ |
| 2518 |
[list $token $state(querylength) $state(queryoffset)] |
| 2519 |
} |
| 2520 |
} |
| 2521 |
|
| 2522 |
# http::Event |
| 2523 |
# |
| 2524 |
# Handle input on the socket. This command is the core of |
| 2525 |
# the coroutine commands ${token}EventCoroutine that are |
| 2526 |
# bound to "fileevent $sock readable" and process input. |
| 2527 |
# |
| 2528 |
# Arguments |
| 2529 |
# sock The socket receiving input. |
| 2530 |
# token The token returned from http::geturl |
| 2531 |
# |
| 2532 |
# Side Effects |
| 2533 |
# Read the socket and handle callbacks. |
| 2534 |
|
| 2535 |
proc http::Event {sock token} { |
| 2536 |
variable http |
| 2537 |
variable socketMapping |
| 2538 |
variable socketRdState |
| 2539 |
variable socketWrState |
| 2540 |
variable socketRdQueue |
| 2541 |
variable socketWrQueue |
| 2542 |
variable socketClosing |
| 2543 |
variable socketPlayCmd |
| 2544 |
|
| 2545 |
variable $token |
| 2546 |
upvar 0 $token state |
| 2547 |
set tk [namespace tail $token] |
| 2548 |
while 1 { |
| 2549 |
yield |
| 2550 |
##Log Event call - token $token |
| 2551 |
|
| 2552 |
if {![info exists state]} { |
| 2553 |
Log "Event $sock with invalid token '$token' - remote close?" |
| 2554 |
if {![eof $sock]} { |
| 2555 |
if {[set d [read $sock]] ne ""} { |
| 2556 |
Log "WARNING: additional data left on closed socket\ |
| 2557 |
- token $token" |
| 2558 |
} |
| 2559 |
} |
| 2560 |
Log ^X$tk end of response (token error) - token $token |
| 2561 |
CloseSocket $sock |
| 2562 |
return |
| 2563 |
} |
| 2564 |
if {$state(state) eq "connecting"} { |
| 2565 |
##Log - connecting - token $token |
| 2566 |
if { $state(reusing) |
| 2567 |
&& $state(-pipeline) |
| 2568 |
&& ($state(-timeout) > 0) |
| 2569 |
&& (![info exists state(after)]) |
| 2570 |
} { |
| 2571 |
set state(after) [after $state(-timeout) \ |
| 2572 |
[list http::reset $token timeout]] |
| 2573 |
} |
| 2574 |
|
| 2575 |
if {[catch {gets $sock state(http)} nsl]} { |
| 2576 |
Log "WARNING - if testing, pay special attention to this\ |
| 2577 |
case (GK) which is seldom executed - token $token" |
| 2578 |
if {[info exists state(reusing)] && $state(reusing)} { |
| 2579 |
# The socket was closed at the server end, and closed at |
| 2580 |
# this end by http::CheckEof. |
| 2581 |
|
| 2582 |
if {[TestForReplay $token read $nsl c]} { |
| 2583 |
return |
| 2584 |
} |
| 2585 |
|
| 2586 |
# else: |
| 2587 |
# This is NOT a persistent socket that has been closed since |
| 2588 |
# its last use. |
| 2589 |
# If any other requests are in flight or pipelined/queued, |
| 2590 |
# they will be discarded. |
| 2591 |
} else { |
| 2592 |
Log ^X$tk end of response (error) - token $token |
| 2593 |
Finish $token $nsl |
| 2594 |
return |
| 2595 |
} |
| 2596 |
} elseif {$nsl >= 0} { |
| 2597 |
##Log - connecting 1 - token $token |
| 2598 |
set state(state) "header" |
| 2599 |
} elseif { [eof $sock] |
| 2600 |
&& [info exists state(reusing)] |
| 2601 |
&& $state(reusing) |
| 2602 |
} { |
| 2603 |
# The socket was closed at the server end, and we didn't notice. |
| 2604 |
# This is the first read - where the closure is usually first |
| 2605 |
# detected. |
| 2606 |
|
| 2607 |
if {[TestForReplay $token read {} d]} { |
| 2608 |
return |
| 2609 |
} |
| 2610 |
|
| 2611 |
# else: |
| 2612 |
# This is NOT a persistent socket that has been closed since its |
| 2613 |
# last use. |
| 2614 |
# If any other requests are in flight or pipelined/queued, they |
| 2615 |
# will be discarded. |
| 2616 |
} |
| 2617 |
} elseif {$state(state) eq "header"} { |
| 2618 |
if {[catch {gets $sock line} nhl]} { |
| 2619 |
##Log header failed - token $token |
| 2620 |
Log ^X$tk end of response (error) - token $token |
| 2621 |
Finish $token $nhl |
| 2622 |
return |
| 2623 |
} elseif {$nhl == 0} { |
| 2624 |
##Log header done - token $token |
| 2625 |
Log ^E$tk end of response headers - token $token |
| 2626 |
# We have now read all headers |
| 2627 |
# We ignore HTTP/1.1 100 Continue returns. RFC2616 sec 8.2.3 |
| 2628 |
if { ($state(http) eq "") |
| 2629 |
|| ([regexp {^\S+\s(\d+)} $state(http) {} x] && $x == 100) |
| 2630 |
} { |
| 2631 |
set state(state) "connecting" |
| 2632 |
continue |
| 2633 |
# This was a "return" in the pre-coroutine code. |
| 2634 |
} |
| 2635 |
|
| 2636 |
if { ([info exists state(connection)]) |
| 2637 |
&& ([info exists socketMapping($state(socketinfo))]) |
| 2638 |
&& ("keep-alive" in $state(connection)) |
| 2639 |
&& ($state(-keepalive)) |
| 2640 |
&& (!$state(reusing)) |
| 2641 |
&& ($state(-pipeline)) |
| 2642 |
} { |
| 2643 |
# Response headers received for first request on a |
| 2644 |
# persistent socket. Now ready for pipelined writes (if |
| 2645 |
# any). |
| 2646 |
# Previous value is $token. It cannot be "pending". |
| 2647 |
set socketWrState($state(socketinfo)) Wready |
| 2648 |
http::NextPipelinedWrite $token |
| 2649 |
} |
| 2650 |
|
| 2651 |
# Once a "close" has been signaled, the client MUST NOT send any |
| 2652 |
# more requests on that connection. |
| 2653 |
# |
| 2654 |
# If either the client or the server sends the "close" token in |
| 2655 |
# the Connection header, that request becomes the last one for |
| 2656 |
# the connection. |
| 2657 |
|
| 2658 |
if { ([info exists state(connection)]) |
| 2659 |
&& ([info exists socketMapping($state(socketinfo))]) |
| 2660 |
&& ("close" in $state(connection)) |
| 2661 |
&& ($state(-keepalive)) |
| 2662 |
} { |
| 2663 |
# The server warns that it will close the socket after this |
| 2664 |
# response. |
| 2665 |
##Log WARNING - socket will close after response for $token |
| 2666 |
# Prepare data for a call to ReplayIfClose. |
| 2667 |
if { ($socketRdQueue($state(socketinfo)) ne {}) |
| 2668 |
|| ($socketWrQueue($state(socketinfo)) ne {}) |
| 2669 |
|| ($socketWrState($state(socketinfo)) ni |
| 2670 |
[list Wready peNding $token]) |
| 2671 |
} { |
| 2672 |
set InFlightW $socketWrState($state(socketinfo)) |
| 2673 |
if {$InFlightW in [list Wready peNding $token]} { |
| 2674 |
set InFlightW Wready |
| 2675 |
} else { |
| 2676 |
set msg "token ${InFlightW} is InFlightW" |
| 2677 |
##Log $msg - token $token |
| 2678 |
} |
| 2679 |
|
| 2680 |
set socketPlayCmd($state(socketinfo)) \ |
| 2681 |
[list ReplayIfClose $InFlightW \ |
| 2682 |
$socketRdQueue($state(socketinfo)) \ |
| 2683 |
$socketWrQueue($state(socketinfo))] |
| 2684 |
|
| 2685 |
# - All tokens are preserved for re-use by ReplayCore. |
| 2686 |
# - Queues are preserved in case of Finish with error, |
| 2687 |
# but are not used for anything else because |
| 2688 |
# socketClosing(*) is set below. |
| 2689 |
# - Cancel the state(after) timeout events. |
| 2690 |
foreach tokenVal $socketRdQueue($state(socketinfo)) { |
| 2691 |
if {[info exists ${tokenVal}(after)]} { |
| 2692 |
after cancel [set ${tokenVal}(after)] |
| 2693 |
unset ${tokenVal}(after) |
| 2694 |
} |
| 2695 |
} |
| 2696 |
|
| 2697 |
} else { |
| 2698 |
set socketPlayCmd($state(socketinfo)) \ |
| 2699 |
{ReplayIfClose Wready {} {}} |
| 2700 |
} |
| 2701 |
|
| 2702 |
# Do not allow further connections on this socket. |
| 2703 |
set socketClosing($state(socketinfo)) 1 |
| 2704 |
} |
| 2705 |
|
| 2706 |
set state(state) body |
| 2707 |
|
| 2708 |
# According to |
| 2709 |
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Connection |
| 2710 |
# any comma-separated "Connection:" list implies keep-alive, but I |
| 2711 |
# don't see this in the RFC so we'll play safe and |
| 2712 |
# scan any list for "close". |
| 2713 |
# Done here to support combining duplicate header field's values. |
| 2714 |
if { [info exists state(connection)] |
| 2715 |
&& ("close" ni $state(connection)) |
| 2716 |
&& ("keep-alive" ni $state(connection)) |
| 2717 |
} { |
| 2718 |
lappend state(connection) "keep-alive" |
| 2719 |
} |
| 2720 |
|
| 2721 |
# If doing a HEAD, then we won't get any body |
| 2722 |
if {$state(-validate)} { |
| 2723 |
Log ^F$tk end of response for HEAD request - token $token |
| 2724 |
set state(state) complete |
| 2725 |
Eot $token |
| 2726 |
return |
| 2727 |
} |
| 2728 |
|
| 2729 |
# - For non-chunked transfer we may have no body - in this case |
| 2730 |
# we may get no further file event if the connection doesn't |
| 2731 |
# close and no more data is sent. We can tell and must finish |
| 2732 |
# up now - not later - the alternative would be to wait until |
| 2733 |
# the server times out. |
| 2734 |
# - In this case, the server has NOT told the client it will |
| 2735 |
# close the connection, AND it has NOT indicated the resource |
| 2736 |
# length EITHER by setting the Content-Length (totalsize) OR |
| 2737 |
# by using chunked Transfer-Encoding. |
| 2738 |
# - Do not worry here about the case (Connection: close) because |
| 2739 |
# the server should close the connection. |
| 2740 |
# - IF (NOT Connection: close) AND (NOT chunked encoding) AND |
| 2741 |
# (totalsize == 0). |
| 2742 |
|
| 2743 |
if { (!( [info exists state(connection)] |
| 2744 |
&& ("close" in $state(connection)) |
| 2745 |
) |
| 2746 |
) |
| 2747 |
&& (![info exists state(transfer)]) |
| 2748 |
&& ($state(totalsize) == 0) |
| 2749 |
} { |
| 2750 |
set msg {body size is 0 and no events likely - complete} |
| 2751 |
Log "$msg - token $token" |
| 2752 |
set msg {(length unknown, set to 0)} |
| 2753 |
Log ^F$tk end of response body {*}$msg - token $token |
| 2754 |
set state(state) complete |
| 2755 |
Eot $token |
| 2756 |
return |
| 2757 |
} |
| 2758 |
|
| 2759 |
# We have to use binary translation to count bytes properly. |
| 2760 |
lassign [fconfigure $sock -translation] trRead trWrite |
| 2761 |
fconfigure $sock -translation [list binary $trWrite] |
| 2762 |
|
| 2763 |
if { |
| 2764 |
$state(-binary) || [IsBinaryContentType $state(type)] |
| 2765 |
} { |
| 2766 |
# Turn off conversions for non-text data. |
| 2767 |
set state(binary) 1 |
| 2768 |
} |
| 2769 |
if {[info exists state(-channel)]} { |
| 2770 |
if {$state(binary) || [llength [ContentEncoding $token]]} { |
| 2771 |
fconfigure $state(-channel) -translation binary |
| 2772 |
} |
| 2773 |
if {![info exists state(-handler)]} { |
| 2774 |
# Initiate a sequence of background fcopies. |
| 2775 |
fileevent $sock readable {} |
| 2776 |
rename ${token}EventCoroutine {} |
| 2777 |
CopyStart $sock $token |
| 2778 |
return |
| 2779 |
} |
| 2780 |
} |
| 2781 |
} elseif {$nhl > 0} { |
| 2782 |
# Process header lines. |
| 2783 |
##Log header - token $token - $line |
| 2784 |
if {[regexp -nocase {^([^:]+):(.+)$} $line x key value]} { |
| 2785 |
switch -- [string tolower $key] { |
| 2786 |
content-type { |
| 2787 |
set state(type) [string trim [string tolower $value]] |
| 2788 |
# Grab the optional charset information. |
| 2789 |
if {[regexp -nocase \ |
| 2790 |
{charset\s*=\s*\"((?:[^""]|\\\")*)\"} \ |
| 2791 |
$state(type) -> cs]} { |
| 2792 |
set state(charset) [string map {{\"} \"} $cs] |
| 2793 |
} else { |
| 2794 |
regexp -nocase {charset\s*=\s*(\S+?);?} \ |
| 2795 |
$state(type) -> state(charset) |
| 2796 |
} |
| 2797 |
} |
| 2798 |
content-length { |
| 2799 |
set state(totalsize) [string trim $value] |
| 2800 |
} |
| 2801 |
content-encoding { |
| 2802 |
set state(coding) [string trim $value] |
| 2803 |
} |
| 2804 |
transfer-encoding { |
| 2805 |
set state(transfer) \ |
| 2806 |
[string trim [string tolower $value]] |
| 2807 |
} |
| 2808 |
proxy-connection - |
| 2809 |
connection { |
| 2810 |
# RFC 7230 Section 6.1 states that a comma-separated |
| 2811 |
# list is an acceptable value. |
| 2812 |
foreach el [SplitCommaSeparatedFieldValue $value] { |
| 2813 |
lappend state(connection) [string tolower $el] |
| 2814 |
} |
| 2815 |
} |
| 2816 |
upgrade { |
| 2817 |
set state(upgrade) [string trim $value] |
| 2818 |
} |
| 2819 |
} |
| 2820 |
lappend state(meta) $key [string trim $value] |
| 2821 |
} |
| 2822 |
} |
| 2823 |
} else { |
| 2824 |
# Now reading body |
| 2825 |
##Log body - token $token |
| 2826 |
if {[catch { |
| 2827 |
if {[info exists state(-handler)]} { |
| 2828 |
set n [eval $state(-handler) [list $sock $token]] |
| 2829 |
##Log handler $n - token $token |
| 2830 |
# N.B. the protocol has been set to 1.0 because the -handler |
| 2831 |
# logic is not expected to handle chunked encoding. |
| 2832 |
# FIXME Allow -handler with 1.1 on dechunked stacked chan. |
| 2833 |
if {$state(totalsize) == 0} { |
| 2834 |
# We know the transfer is complete only when the server |
| 2835 |
# closes the connection - i.e. eof is not an error. |
| 2836 |
set state(state) complete |
| 2837 |
} |
| 2838 |
if {![string is integer -strict $n]} { |
| 2839 |
if 1 { |
| 2840 |
# Do not tolerate bad -handler - fail with error |
| 2841 |
# status. |
| 2842 |
set msg {the -handler command for http::geturl must\ |
| 2843 |
return an integer (the number of bytes\ |
| 2844 |
read)} |
| 2845 |
Log ^X$tk end of response (handler error) -\ |
| 2846 |
token $token |
| 2847 |
Eot $token $msg |
| 2848 |
} else { |
| 2849 |
# Tolerate the bad -handler, and continue. The |
| 2850 |
# penalty: |
| 2851 |
# (a) Because the handler returns nonsense, we know |
| 2852 |
# the transfer is complete only when the server |
| 2853 |
# closes the connection - i.e. eof is not an |
| 2854 |
# error. |
| 2855 |
# (b) http::size will not be accurate. |
| 2856 |
# (c) The transaction is already downgraded to 1.0 |
| 2857 |
# to avoid chunked transfer encoding. It MUST |
| 2858 |
# also be forced to "Connection: close" or the |
| 2859 |
# HTTP/1.0 equivalent; or it MUST fail (as |
| 2860 |
# above) if the server sends |
| 2861 |
# "Connection: keep-alive" or the HTTP/1.0 |
| 2862 |
# equivalent. |
| 2863 |
set n 0 |
| 2864 |
set state(state) complete |
| 2865 |
} |
| 2866 |
} |
| 2867 |
} elseif {[info exists state(transfer_final)]} { |
| 2868 |
# This code forgives EOF in place of the final CRLF. |
| 2869 |
set line [getTextLine $sock] |
| 2870 |
set n [string length $line] |
| 2871 |
set state(state) complete |
| 2872 |
if {$n > 0} { |
| 2873 |
# - HTTP trailers (late response headers) are permitted |
| 2874 |
# by Chunked Transfer-Encoding, and can be safely |
| 2875 |
# ignored. |
| 2876 |
# - Do not count these bytes in the total received for |
| 2877 |
# the response body. |
| 2878 |
Log "trailer of $n bytes after final chunk -\ |
| 2879 |
token $token" |
| 2880 |
append state(transfer_final) $line |
| 2881 |
set n 0 |
| 2882 |
} else { |
| 2883 |
Log ^F$tk end of response body (chunked) - token $token |
| 2884 |
Log "final chunk part - token $token" |
| 2885 |
Eot $token |
| 2886 |
} |
| 2887 |
} elseif { [info exists state(transfer)] |
| 2888 |
&& ($state(transfer) eq "chunked") |
| 2889 |
} { |
| 2890 |
##Log chunked - token $token |
| 2891 |
set size 0 |
| 2892 |
set hexLenChunk [getTextLine $sock] |
| 2893 |
#set ntl [string length $hexLenChunk] |
| 2894 |
if {[string trim $hexLenChunk] ne ""} { |
| 2895 |
scan $hexLenChunk %x size |
| 2896 |
if {$size != 0} { |
| 2897 |
##Log chunk-measure $size - token $token |
| 2898 |
set chunk [BlockingRead $sock $size] |
| 2899 |
set n [string length $chunk] |
| 2900 |
if {$n >= 0} { |
| 2901 |
append state(body) $chunk |
| 2902 |
incr state(log_size) [string length $chunk] |
| 2903 |
##Log chunk $n cumul $state(log_size) -\ |
| 2904 |
token $token |
| 2905 |
} |
| 2906 |
if {$size != [string length $chunk]} { |
| 2907 |
Log "WARNING: mis-sized chunk:\ |
| 2908 |
was [string length $chunk], should be\ |
| 2909 |
$size - token $token" |
| 2910 |
set n 0 |
| 2911 |
set state(connection) close |
| 2912 |
Log ^X$tk end of response (chunk error) \ |
| 2913 |
- token $token |
| 2914 |
set msg {error in chunked encoding - fetch\ |
| 2915 |
terminated} |
| 2916 |
Eot $token $msg |
| 2917 |
} |
| 2918 |
# CRLF that follows chunk. |
| 2919 |
# If eof, this is handled at the end of this proc. |
| 2920 |
getTextLine $sock |
| 2921 |
} else { |
| 2922 |
set n 0 |
| 2923 |
set state(transfer_final) {} |
| 2924 |
} |
| 2925 |
} else { |
| 2926 |
# Line expected to hold chunk length is empty, or eof. |
| 2927 |
##Log bad-chunk-measure - token $token |
| 2928 |
set n 0 |
| 2929 |
set state(connection) close |
| 2930 |
Log ^X$tk end of response (chunk error) - token $token |
| 2931 |
Eot $token {error in chunked encoding -\ |
| 2932 |
fetch terminated} |
| 2933 |
} |
| 2934 |
} else { |
| 2935 |
##Log unchunked - token $token |
| 2936 |
if {$state(totalsize) == 0} { |
| 2937 |
# We know the transfer is complete only when the server |
| 2938 |
# closes the connection. |
| 2939 |
set state(state) complete |
| 2940 |
set reqSize $state(-blocksize) |
| 2941 |
} else { |
| 2942 |
# Ask for the whole of the unserved response-body. |
| 2943 |
# This works around a problem with a tls::socket - for |
| 2944 |
# https in keep-alive mode, and a request for |
| 2945 |
# $state(-blocksize) bytes, the last part of the |
| 2946 |
# resource does not get read until the server times out. |
| 2947 |
set reqSize [expr { $state(totalsize) |
| 2948 |
- $state(currentsize)}] |
| 2949 |
|
| 2950 |
# The workaround fails if reqSize is |
| 2951 |
# capped at $state(-blocksize). |
| 2952 |
# set reqSize [expr {min($reqSize, $state(-blocksize))}] |
| 2953 |
} |
| 2954 |
set c $state(currentsize) |
| 2955 |
set t $state(totalsize) |
| 2956 |
##Log non-chunk currentsize $c of totalsize $t -\ |
| 2957 |
token $token |
| 2958 |
set block [read $sock $reqSize] |
| 2959 |
set n [string length $block] |
| 2960 |
if {$n >= 0} { |
| 2961 |
append state(body) $block |
| 2962 |
##Log non-chunk [string length $state(body)] -\ |
| 2963 |
token $token |
| 2964 |
} |
| 2965 |
} |
| 2966 |
# This calculation uses n from the -handler, chunked, or |
| 2967 |
# unchunked case as appropriate. |
| 2968 |
if {[info exists state]} { |
| 2969 |
if {$n >= 0} { |
| 2970 |
incr state(currentsize) $n |
| 2971 |
set c $state(currentsize) |
| 2972 |
set t $state(totalsize) |
| 2973 |
##Log another $n currentsize $c totalsize $t -\ |
| 2974 |
token $token |
| 2975 |
} |
| 2976 |
# If Content-Length - check for end of data. |
| 2977 |
if { |
| 2978 |
($state(totalsize) > 0) |
| 2979 |
&& ($state(currentsize) >= $state(totalsize)) |
| 2980 |
} { |
| 2981 |
Log ^F$tk end of response body (unchunked) -\ |
| 2982 |
token $token |
| 2983 |
set state(state) complete |
| 2984 |
Eot $token |
| 2985 |
} |
| 2986 |
} |
| 2987 |
} err]} { |
| 2988 |
Log ^X$tk end of response (error ${err}) - token $token |
| 2989 |
Finish $token $err |
| 2990 |
return |
| 2991 |
} else { |
| 2992 |
if {[info exists state(-progress)]} { |
| 2993 |
eval $state(-progress) \ |
| 2994 |
[list $token $state(totalsize) $state(currentsize)] |
| 2995 |
} |
| 2996 |
} |
| 2997 |
} |
| 2998 |
|
| 2999 |
# catch as an Eot above may have closed the socket already |
| 3000 |
# $state(state) may be connecting, header, body, or complete |
| 3001 |
if {![set cc [catch {eof $sock} eof]] && $eof} { |
| 3002 |
##Log eof - token $token |
| 3003 |
if {[info exists $token]} { |
| 3004 |
set state(connection) close |
| 3005 |
if {$state(state) eq "complete"} { |
| 3006 |
# This includes all cases in which the transaction |
| 3007 |
# can be completed by eof. |
| 3008 |
# The value "complete" is set only in http::Event, and it is |
| 3009 |
# used only in the test above. |
| 3010 |
Log ^F$tk end of response body (unchunked, eof) -\ |
| 3011 |
token $token |
| 3012 |
Eot $token |
| 3013 |
} else { |
| 3014 |
# Premature eof. |
| 3015 |
Log ^X$tk end of response (unexpected eof) - token $token |
| 3016 |
Eot $token eof |
| 3017 |
} |
| 3018 |
} else { |
| 3019 |
# open connection closed on a token that has been cleaned up. |
| 3020 |
Log ^X$tk end of response (token error) - token $token |
| 3021 |
CloseSocket $sock |
| 3022 |
} |
| 3023 |
} elseif {$cc} { |
| 3024 |
return |
| 3025 |
} |
| 3026 |
} |
| 3027 |
} |
| 3028 |
|
| 3029 |
# http::TestForReplay |
| 3030 |
# |
| 3031 |
# Command called if eof is discovered when a socket is first used for a |
| 3032 |
# new transaction. Typically this occurs if a persistent socket is used |
| 3033 |
# after a period of idleness and the server has half-closed the socket. |
| 3034 |
# |
| 3035 |
# token - the connection token returned by http::geturl |
| 3036 |
# doing - "read" or "write" |
| 3037 |
# err - error message, if any |
| 3038 |
# caller - code to identify the caller - used only in logging |
| 3039 |
# |
| 3040 |
# Return Value: boolean, true iff the command calls http::ReplayIfDead. |
| 3041 |
|
| 3042 |
proc http::TestForReplay {token doing err caller} { |
| 3043 |
variable http |
| 3044 |
variable $token |
| 3045 |
upvar 0 $token state |
| 3046 |
set tk [namespace tail $token] |
| 3047 |
if {$doing eq "read"} { |
| 3048 |
set code Q |
| 3049 |
set action response |
| 3050 |
set ing reading |
| 3051 |
} else { |
| 3052 |
set code P |
| 3053 |
set action request |
| 3054 |
set ing writing |
| 3055 |
} |
| 3056 |
|
| 3057 |
if {$err eq {}} { |
| 3058 |
set err "detect eof when $ing (server timed out?)" |
| 3059 |
} |
| 3060 |
|
| 3061 |
if {$state(method) eq "POST" && !$http(-repost)} { |
| 3062 |
# No Replay. |
| 3063 |
# The present transaction will end when Finish is called. |
| 3064 |
# That call to Finish will abort any other transactions |
| 3065 |
# currently in the write queue. |
| 3066 |
# For calls from http::Event this occurs when execution |
| 3067 |
# reaches the code block at the end of that proc. |
| 3068 |
set msg {no retry for POST with http::config -repost 0} |
| 3069 |
Log reusing socket failed "($caller)" - $msg - token $token |
| 3070 |
Log error - $err - token $token |
| 3071 |
Log ^X$tk end of $action (error) - token $token |
| 3072 |
return 0 |
| 3073 |
} else { |
| 3074 |
# Replay. |
| 3075 |
set msg {try a new socket} |
| 3076 |
Log reusing socket failed "($caller)" - $msg - token $token |
| 3077 |
Log error - $err - token $token |
| 3078 |
Log ^$code$tk Any unfinished (incl this one) failed - token $token |
| 3079 |
ReplayIfDead $token $doing |
| 3080 |
return 1 |
| 3081 |
} |
| 3082 |
} |
| 3083 |
|
| 3084 |
# http::IsBinaryContentType -- |
| 3085 |
# |
| 3086 |
# Determine if the content-type means that we should definitely transfer |
| 3087 |
# the data as binary. [Bug 838e99a76d] |
| 3088 |
# |
| 3089 |
# Arguments |
| 3090 |
# type The content-type of the data. |
| 3091 |
# |
| 3092 |
# Results: |
| 3093 |
# Boolean, true if we definitely should be binary. |
| 3094 |
|
| 3095 |
proc http::IsBinaryContentType {type} { |
| 3096 |
lassign [split [string tolower $type] "/;"] major minor |
| 3097 |
if {$major eq "text"} { |
| 3098 |
return false |
| 3099 |
} |
| 3100 |
# There's a bunch of XML-as-application-format things about. See RFC 3023 |
| 3101 |
# and so on. |
| 3102 |
if {$major eq "application"} { |
| 3103 |
set minor [string trimright $minor] |
| 3104 |
if {$minor in {"json" "xml" "xml-external-parsed-entity" "xml-dtd"}} { |
| 3105 |
return false |
| 3106 |
} |
| 3107 |
} |
| 3108 |
# Not just application/foobar+xml but also image/svg+xml, so let us not |
| 3109 |
# restrict things for now... |
| 3110 |
if {[string match "*+xml" $minor]} { |
| 3111 |
return false |
| 3112 |
} |
| 3113 |
return true |
| 3114 |
} |
| 3115 |
|
| 3116 |
# http::getTextLine -- |
| 3117 |
# |
| 3118 |
# Get one line with the stream in crlf mode. |
| 3119 |
# Used if Transfer-Encoding is chunked. |
| 3120 |
# Empty line is not distinguished from eof. The caller must |
| 3121 |
# be able to handle this. |
| 3122 |
# |
| 3123 |
# Arguments |
| 3124 |
# sock The socket receiving input. |
| 3125 |
# |
| 3126 |
# Results: |
| 3127 |
# The line of text, without trailing newline |
| 3128 |
|
| 3129 |
proc http::getTextLine {sock} { |
| 3130 |
set tr [fconfigure $sock -translation] |
| 3131 |
lassign $tr trRead trWrite |
| 3132 |
fconfigure $sock -translation [list crlf $trWrite] |
| 3133 |
set r [BlockingGets $sock] |
| 3134 |
fconfigure $sock -translation $tr |
| 3135 |
return $r |
| 3136 |
} |
| 3137 |
|
| 3138 |
# http::BlockingRead |
| 3139 |
# |
| 3140 |
# Replacement for a blocking read. |
| 3141 |
# The caller must be a coroutine. |
| 3142 |
|
| 3143 |
proc http::BlockingRead {sock size} { |
| 3144 |
if {$size < 1} { |
| 3145 |
return |
| 3146 |
} |
| 3147 |
set result {} |
| 3148 |
while 1 { |
| 3149 |
set need [expr {$size - [string length $result]}] |
| 3150 |
set block [read $sock $need] |
| 3151 |
set eof [eof $sock] |
| 3152 |
append result $block |
| 3153 |
if {[string length $result] >= $size || $eof} { |
| 3154 |
return $result |
| 3155 |
} else { |
| 3156 |
yield |
| 3157 |
} |
| 3158 |
} |
| 3159 |
} |
| 3160 |
|
| 3161 |
# http::BlockingGets |
| 3162 |
# |
| 3163 |
# Replacement for a blocking gets. |
| 3164 |
# The caller must be a coroutine. |
| 3165 |
# Empty line is not distinguished from eof. The caller must |
| 3166 |
# be able to handle this. |
| 3167 |
|
| 3168 |
proc http::BlockingGets {sock} { |
| 3169 |
while 1 { |
| 3170 |
set count [gets $sock line] |
| 3171 |
set eof [eof $sock] |
| 3172 |
if {$count >= 0 || $eof} { |
| 3173 |
return $line |
| 3174 |
} else { |
| 3175 |
yield |
| 3176 |
} |
| 3177 |
} |
| 3178 |
} |
| 3179 |
|
| 3180 |
# http::CopyStart |
| 3181 |
# |
| 3182 |
# Error handling wrapper around fcopy |
| 3183 |
# |
| 3184 |
# Arguments |
| 3185 |
# sock The socket to copy from |
| 3186 |
# token The token returned from http::geturl |
| 3187 |
# |
| 3188 |
# Side Effects |
| 3189 |
# This closes the connection upon error |
| 3190 |
|
| 3191 |
proc http::CopyStart {sock token {initial 1}} { |
| 3192 |
upvar #0 $token state |
| 3193 |
if {[info exists state(transfer)] && $state(transfer) eq "chunked"} { |
| 3194 |
foreach coding [ContentEncoding $token] { |
| 3195 |
lappend state(zlib) [zlib stream $coding] |
| 3196 |
} |
| 3197 |
make-transformation-chunked $sock [namespace code [list CopyChunk $token]] |
| 3198 |
} else { |
| 3199 |
if {$initial} { |
| 3200 |
foreach coding [ContentEncoding $token] { |
| 3201 |
zlib push $coding $sock |
| 3202 |
} |
| 3203 |
} |
| 3204 |
if {[catch { |
| 3205 |
# FIXME Keep-Alive on https tls::socket with unchunked transfer |
| 3206 |
# hangs until the server times out. A workaround is possible, as for |
| 3207 |
# the case without -channel, but it does not use the neat "fcopy" |
| 3208 |
# solution. |
| 3209 |
fcopy $sock $state(-channel) -size $state(-blocksize) -command \ |
| 3210 |
[list http::CopyDone $token] |
| 3211 |
} err]} { |
| 3212 |
Finish $token $err |
| 3213 |
} |
| 3214 |
} |
| 3215 |
} |
| 3216 |
|
| 3217 |
proc http::CopyChunk {token chunk} { |
| 3218 |
upvar 0 $token state |
| 3219 |
if {[set count [string length $chunk]]} { |
| 3220 |
incr state(currentsize) $count |
| 3221 |
if {[info exists state(zlib)]} { |
| 3222 |
foreach stream $state(zlib) { |
| 3223 |
set chunk [$stream add $chunk] |
| 3224 |
} |
| 3225 |
} |
| 3226 |
puts -nonewline $state(-channel) $chunk |
| 3227 |
if {[info exists state(-progress)]} { |
| 3228 |
eval [linsert $state(-progress) end \ |
| 3229 |
$token $state(totalsize) $state(currentsize)] |
| 3230 |
} |
| 3231 |
} else { |
| 3232 |
Log "CopyChunk Finish - token $token" |
| 3233 |
if {[info exists state(zlib)]} { |
| 3234 |
set excess "" |
| 3235 |
foreach stream $state(zlib) { |
| 3236 |
catch {set excess [$stream add -finalize $excess]} |
| 3237 |
} |
| 3238 |
puts -nonewline $state(-channel) $excess |
| 3239 |
foreach stream $state(zlib) { $stream close } |
| 3240 |
unset state(zlib) |
| 3241 |
} |
| 3242 |
Eot $token ;# FIX ME: pipelining. |
| 3243 |
} |
| 3244 |
} |
| 3245 |
|
| 3246 |
# http::CopyDone |
| 3247 |
# |
| 3248 |
# fcopy completion callback |
| 3249 |
# |
| 3250 |
# Arguments |
| 3251 |
# token The token returned from http::geturl |
| 3252 |
# count The amount transferred |
| 3253 |
# |
| 3254 |
# Side Effects |
| 3255 |
# Invokes callbacks |
| 3256 |
|
| 3257 |
proc http::CopyDone {token count {error {}}} { |
| 3258 |
variable $token |
| 3259 |
upvar 0 $token state |
| 3260 |
set sock $state(sock) |
| 3261 |
incr state(currentsize) $count |
| 3262 |
if {[info exists state(-progress)]} { |
| 3263 |
eval $state(-progress) \ |
| 3264 |
[list $token $state(totalsize) $state(currentsize)] |
| 3265 |
} |
| 3266 |
# At this point the token may have been reset. |
| 3267 |
if {[string length $error]} { |
| 3268 |
Finish $token $error |
| 3269 |
} elseif {[catch {eof $sock} iseof] || $iseof} { |
| 3270 |
Eot $token |
| 3271 |
} else { |
| 3272 |
CopyStart $sock $token 0 |
| 3273 |
} |
| 3274 |
} |
| 3275 |
|
| 3276 |
# http::Eot |
| 3277 |
# |
| 3278 |
# Called when either: |
| 3279 |
# a. An eof condition is detected on the socket. |
| 3280 |
# b. The client decides that the response is complete. |
| 3281 |
# c. The client detects an inconsistency and aborts the transaction. |
| 3282 |
# |
| 3283 |
# Does: |
| 3284 |
# 1. Set state(status) |
| 3285 |
# 2. Reverse any Content-Encoding |
| 3286 |
# 3. Convert charset encoding and line ends if necessary |
| 3287 |
# 4. Call http::Finish |
| 3288 |
# |
| 3289 |
# Arguments |
| 3290 |
# token The token returned from http::geturl |
| 3291 |
# force (previously) optional, has no effect |
| 3292 |
# reason - "eof" means premature EOF (not EOF as the natural end of |
| 3293 |
# the response) |
| 3294 |
# - "" means completion of response, with or without EOF |
| 3295 |
# - anything else describes an error condition other than |
| 3296 |
# premature EOF. |
| 3297 |
# |
| 3298 |
# Side Effects |
| 3299 |
# Clean up the socket |
| 3300 |
|
| 3301 |
proc http::Eot {token {reason {}}} { |
| 3302 |
variable $token |
| 3303 |
upvar 0 $token state |
| 3304 |
if {$reason eq "eof"} { |
| 3305 |
# Premature eof. |
| 3306 |
set state(status) eof |
| 3307 |
set reason {} |
| 3308 |
} elseif {$reason ne ""} { |
| 3309 |
# Abort the transaction. |
| 3310 |
set state(status) $reason |
| 3311 |
} else { |
| 3312 |
# The response is complete. |
| 3313 |
set state(status) ok |
| 3314 |
} |
| 3315 |
|
| 3316 |
if {[string length $state(body)] > 0} { |
| 3317 |
if {[catch { |
| 3318 |
foreach coding [ContentEncoding $token] { |
| 3319 |
set state(body) [zlib $coding $state(body)] |
| 3320 |
} |
| 3321 |
} err]} { |
| 3322 |
Log "error doing decompression for token $token: $err" |
| 3323 |
Finish $token $err |
| 3324 |
return |
| 3325 |
} |
| 3326 |
|
| 3327 |
if {!$state(binary)} { |
| 3328 |
# If we are getting text, set the incoming channel's encoding |
| 3329 |
# correctly. iso8859-1 is the RFC default, but this could be any |
| 3330 |
# IANA charset. However, we only know how to convert what we have |
| 3331 |
# encodings for. |
| 3332 |
|
| 3333 |
set enc [CharsetToEncoding $state(charset)] |
| 3334 |
if {$enc ne "binary"} { |
| 3335 |
set state(body) [encoding convertfrom $enc $state(body)] |
| 3336 |
} |
| 3337 |
|
| 3338 |
# Translate text line endings. |
| 3339 |
set state(body) [string map {\r\n \n \r \n} $state(body)] |
| 3340 |
} |
| 3341 |
} |
| 3342 |
Finish $token $reason |
| 3343 |
} |
| 3344 |
|
| 3345 |
# http::wait -- |
| 3346 |
# |
| 3347 |
# See documentation for details. |
| 3348 |
# |
| 3349 |
# Arguments: |
| 3350 |
# token Connection token. |
| 3351 |
# |
| 3352 |
# Results: |
| 3353 |
# The status after the wait. |
| 3354 |
|
| 3355 |
proc http::wait {token} { |
| 3356 |
variable $token |
| 3357 |
upvar 0 $token state |
| 3358 |
|
| 3359 |
if {![info exists state(status)] || $state(status) eq ""} { |
| 3360 |
# We must wait on the original variable name, not the upvar alias |
| 3361 |
vwait ${token}(status) |
| 3362 |
} |
| 3363 |
|
| 3364 |
return [status $token] |
| 3365 |
} |
| 3366 |
|
| 3367 |
# http::formatQuery -- |
| 3368 |
# |
| 3369 |
# See documentation for details. Call http::formatQuery with an even |
| 3370 |
# number of arguments, where the first is a name, the second is a value, |
| 3371 |
# the third is another name, and so on. |
| 3372 |
# |
| 3373 |
# Arguments: |
| 3374 |
# args A list of name-value pairs. |
| 3375 |
# |
| 3376 |
# Results: |
| 3377 |
# TODO |
| 3378 |
|
| 3379 |
proc http::formatQuery {args} { |
| 3380 |
if {[llength $args] % 2} { |
| 3381 |
return \ |
| 3382 |
-code error \ |
| 3383 |
-errorcode [list HTTP BADARGCNT $args] \ |
| 3384 |
{Incorrect number of arguments, must be an even number.} |
| 3385 |
} |
| 3386 |
set result "" |
| 3387 |
set sep "" |
| 3388 |
foreach i $args { |
| 3389 |
append result $sep [mapReply $i] |
| 3390 |
if {$sep eq "="} { |
| 3391 |
set sep & |
| 3392 |
} else { |
| 3393 |
set sep = |
| 3394 |
} |
| 3395 |
} |
| 3396 |
return $result |
| 3397 |
} |
| 3398 |
|
| 3399 |
# http::mapReply -- |
| 3400 |
# |
| 3401 |
# Do x-www-urlencoded character mapping |
| 3402 |
# |
| 3403 |
# Arguments: |
| 3404 |
# string The string the needs to be encoded |
| 3405 |
# |
| 3406 |
# Results: |
| 3407 |
# The encoded string |
| 3408 |
|
| 3409 |
proc http::mapReply {string} { |
| 3410 |
variable http |
| 3411 |
variable formMap |
| 3412 |
|
| 3413 |
# The spec says: "non-alphanumeric characters are replaced by '%HH'". Use |
| 3414 |
# a pre-computed map and [string map] to do the conversion (much faster |
| 3415 |
# than [regsub]/[subst]). [Bug 1020491] |
| 3416 |
|
| 3417 |
if {$http(-urlencoding) ne ""} { |
| 3418 |
set string [encoding convertto $http(-urlencoding) $string] |
| 3419 |
return [string map $formMap $string] |
| 3420 |
} |
| 3421 |
set converted [string map $formMap $string] |
| 3422 |
if {[string match "*\[\u0100-\uffff\]*" $converted]} { |
| 3423 |
regexp "\[\u0100-\uffff\]" $converted badChar |
| 3424 |
# Return this error message for maximum compatibility... :^/ |
| 3425 |
return -code error \ |
| 3426 |
"can't read \"formMap($badChar)\": no such element in array" |
| 3427 |
} |
| 3428 |
return $converted |
| 3429 |
} |
| 3430 |
interp alias {} http::quoteString {} http::mapReply |
| 3431 |
|
| 3432 |
# http::ProxyRequired -- |
| 3433 |
# Default proxy filter. |
| 3434 |
# |
| 3435 |
# Arguments: |
| 3436 |
# host The destination host |
| 3437 |
# |
| 3438 |
# Results: |
| 3439 |
# The current proxy settings |
| 3440 |
|
| 3441 |
proc http::ProxyRequired {host} { |
| 3442 |
variable http |
| 3443 |
if {[info exists http(-proxyhost)] && [string length $http(-proxyhost)]} { |
| 3444 |
if { |
| 3445 |
![info exists http(-proxyport)] || |
| 3446 |
![string length $http(-proxyport)] |
| 3447 |
} { |
| 3448 |
set http(-proxyport) 8080 |
| 3449 |
} |
| 3450 |
return [list $http(-proxyhost) $http(-proxyport)] |
| 3451 |
} |
| 3452 |
} |
| 3453 |
|
| 3454 |
# http::CharsetToEncoding -- |
| 3455 |
# |
| 3456 |
# Tries to map a given IANA charset to a tcl encoding. If no encoding |
| 3457 |
# can be found, returns binary. |
| 3458 |
# |
| 3459 |
|
| 3460 |
proc http::CharsetToEncoding {charset} { |
| 3461 |
variable encodings |
| 3462 |
|
| 3463 |
set charset [string tolower $charset] |
| 3464 |
if {[regexp {iso-?8859-([0-9]+)} $charset -> num]} { |
| 3465 |
set encoding "iso8859-$num" |
| 3466 |
} elseif {[regexp {iso-?2022-(jp|kr)} $charset -> ext]} { |
| 3467 |
set encoding "iso2022-$ext" |
| 3468 |
} elseif {[regexp {shift[-_]?jis} $charset]} { |
| 3469 |
set encoding "shiftjis" |
| 3470 |
} elseif {[regexp {(?:windows|cp)-?([0-9]+)} $charset -> num]} { |
| 3471 |
set encoding "cp$num" |
| 3472 |
} elseif {$charset eq "us-ascii"} { |
| 3473 |
set encoding "ascii" |
| 3474 |
} elseif {[regexp {(?:iso-?)?lat(?:in)?-?([0-9]+)} $charset -> num]} { |
| 3475 |
switch -- $num { |
| 3476 |
5 {set encoding "iso8859-9"} |
| 3477 |
1 - 2 - 3 { |
| 3478 |
set encoding "iso8859-$num" |
| 3479 |
} |
| 3480 |
default { |
| 3481 |
set encoding "binary" |
| 3482 |
} |
| 3483 |
} |
| 3484 |
} else { |
| 3485 |
# other charset, like euc-xx, utf-8,... may directly map to encoding |
| 3486 |
set encoding $charset |
| 3487 |
} |
| 3488 |
set idx [lsearch -exact $encodings $encoding] |
| 3489 |
if {$idx >= 0} { |
| 3490 |
return $encoding |
| 3491 |
} else { |
| 3492 |
return "binary" |
| 3493 |
} |
| 3494 |
} |
| 3495 |
|
| 3496 |
# Return the list of content-encoding transformations we need to do in order. |
| 3497 |
proc http::ContentEncoding {token} { |
| 3498 |
upvar 0 $token state |
| 3499 |
set r {} |
| 3500 |
if {[info exists state(coding)]} { |
| 3501 |
foreach coding [split $state(coding) ,] { |
| 3502 |
switch -exact -- $coding { |
| 3503 |
deflate { lappend r inflate } |
| 3504 |
gzip - x-gzip { lappend r gunzip } |
| 3505 |
compress - x-compress { lappend r decompress } |
| 3506 |
identity {} |
| 3507 |
br { |
| 3508 |
return -code error\ |
| 3509 |
"content-encoding \"br\" not implemented" |
| 3510 |
} |
| 3511 |
default { |
| 3512 |
Log "unknown content-encoding \"$coding\" ignored" |
| 3513 |
} |
| 3514 |
} |
| 3515 |
} |
| 3516 |
} |
| 3517 |
return $r |
| 3518 |
} |
| 3519 |
|
| 3520 |
proc http::ReceiveChunked {chan command} { |
| 3521 |
set data "" |
| 3522 |
set size -1 |
| 3523 |
yield |
| 3524 |
while {1} { |
| 3525 |
chan configure $chan -translation {crlf binary} |
| 3526 |
while {[gets $chan line] < 1} { yield } |
| 3527 |
chan configure $chan -translation {binary binary} |
| 3528 |
if {[scan $line %x size] != 1} { |
| 3529 |
return -code error "invalid size: \"$line\"" |
| 3530 |
} |
| 3531 |
set chunk "" |
| 3532 |
while {$size && ![chan eof $chan]} { |
| 3533 |
set part [chan read $chan $size] |
| 3534 |
incr size -[string length $part] |
| 3535 |
append chunk $part |
| 3536 |
} |
| 3537 |
if {[catch { |
| 3538 |
uplevel #0 [linsert $command end $chunk] |
| 3539 |
}]} { |
| 3540 |
http::Log "Error in callback: $::errorInfo" |
| 3541 |
} |
| 3542 |
if {[string length $chunk] == 0} { |
| 3543 |
# channel might have been closed in the callback |
| 3544 |
catch {chan event $chan readable {}} |
| 3545 |
return |
| 3546 |
} |
| 3547 |
} |
| 3548 |
} |
| 3549 |
|
| 3550 |
# http::SplitCommaSeparatedFieldValue -- |
| 3551 |
# Return the individual values of a comma-separated field value. |
| 3552 |
# |
| 3553 |
# Arguments: |
| 3554 |
# fieldValue Comma-separated header field value. |
| 3555 |
# |
| 3556 |
# Results: |
| 3557 |
# List of values. |
| 3558 |
proc http::SplitCommaSeparatedFieldValue {fieldValue} { |
| 3559 |
set r {} |
| 3560 |
foreach el [split $fieldValue ,] { |
| 3561 |
lappend r [string trim $el] |
| 3562 |
} |
| 3563 |
return $r |
| 3564 |
} |
| 3565 |
|
| 3566 |
|
| 3567 |
# http::GetFieldValue -- |
| 3568 |
# Return the value of a header field. |
| 3569 |
# |
| 3570 |
# Arguments: |
| 3571 |
# headers Headers key-value list |
| 3572 |
# fieldName Name of header field whose value to return. |
| 3573 |
# |
| 3574 |
# Results: |
| 3575 |
# The value of the fieldName header field |
| 3576 |
# |
| 3577 |
# Field names are matched case-insensitively (RFC 7230 Section 3.2). |
| 3578 |
# |
| 3579 |
# If the field is present multiple times, it is assumed that the field is |
| 3580 |
# defined as a comma-separated list and the values are combined (by separating |
| 3581 |
# them with commas, see RFC 7230 Section 3.2.2) and returned at once. |
| 3582 |
proc http::GetFieldValue {headers fieldName} { |
| 3583 |
set r {} |
| 3584 |
foreach {field value} $headers { |
| 3585 |
if {[string equal -nocase $fieldName $field]} { |
| 3586 |
if {$r eq {}} { |
| 3587 |
set r $value |
| 3588 |
} else { |
| 3589 |
append r ", $value" |
| 3590 |
} |
| 3591 |
} |
| 3592 |
} |
| 3593 |
return $r |
| 3594 |
} |
| 3595 |
|
| 3596 |
proc http::make-transformation-chunked {chan command} { |
| 3597 |
coroutine [namespace current]::dechunk$chan ::http::ReceiveChunked $chan $command |
| 3598 |
chan event $chan readable [namespace current]::dechunk$chan |
| 3599 |
} |
| 3600 |
|
| 3601 |
# Local variables: |
| 3602 |
# indent-tabs-mode: t |
| 3603 |
# End: |