home *** CD-ROM | disk | FTP | other *** search
/ Chip: Linux Special / CorelLinux_CHIP.iso / VMware / bin / vmware-wizard / lib / tcl8.0 / http2.0 / http.tcl next >
Encoding:
Text File  |  1999-02-24  |  11.2 KB  |  467 lines

  1. # http.tcl --
  2. #
  3. #    Client-side HTTP for GET, POST, and HEAD commands.
  4. #    These routines can be used in untrusted code that uses 
  5. #    the Safesock security policy.  These procedures use a 
  6. #    callback interface to avoid using vwait, which is not 
  7. #    defined in the safe base.
  8. #
  9. # See the file "license.terms" for information on usage and
  10. # redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
  11. #
  12. # RCS: @(#) $Id: http.tcl,v 1.5 1999/02/02 22:28:30 stanton Exp $
  13.  
  14. package provide http 2.0    ;# This uses Tcl namespaces
  15.  
  16. namespace eval http {
  17.     variable http
  18.  
  19.     array set http {
  20.     -accept */*
  21.     -proxyhost {}
  22.     -proxyport {}
  23.     -useragent {Tcl http client package 2.0}
  24.     -proxyfilter http::ProxyRequired
  25.     }
  26.  
  27.     variable formMap
  28.     set alphanumeric    a-zA-Z0-9
  29.  
  30.     for {set i 1} {$i <= 256} {incr i} {
  31.     set c [format %c $i]
  32.     if {![string match \[$alphanumeric\] $c]} {
  33.         set formMap($c) %[format %.2x $i]
  34.     }
  35.     }
  36.     # These are handled specially
  37.     array set formMap {
  38.     " " +   \n %0d%0a
  39.     }
  40.  
  41.     namespace export geturl config reset wait formatQuery 
  42.     # Useful, but not exported: data size status code
  43. }
  44.  
  45. # http::config --
  46. #
  47. #    See documentaion for details.
  48. #
  49. # Arguments:
  50. #    args        Options parsed by the procedure.
  51. # Results:
  52. #        TODO
  53.  
  54. proc http::config {args} {
  55.     variable http
  56.     set options [lsort [array names http -*]]
  57.     set usage [join $options ", "]
  58.     if {[llength $args] == 0} {
  59.     set result {}
  60.     foreach name $options {
  61.         lappend result $name $http($name)
  62.     }
  63.     return $result
  64.     }
  65.     regsub -all -- - $options {} options
  66.     set pat ^-([join $options |])$
  67.     if {[llength $args] == 1} {
  68.     set flag [lindex $args 0]
  69.     if {[regexp -- $pat $flag]} {
  70.         return $http($flag)
  71.     } else {
  72.         return -code error "Unknown option $flag, must be: $usage"
  73.     }
  74.     } else {
  75.     foreach {flag value} $args {
  76.         if {[regexp -- $pat $flag]} {
  77.         set http($flag) $value
  78.         } else {
  79.         return -code error "Unknown option $flag, must be: $usage"
  80.         }
  81.     }
  82.     }
  83. }
  84.  
  85.  proc http::Finish { token {errormsg ""} } {
  86.     variable $token
  87.     upvar 0 $token state
  88.     global errorInfo errorCode
  89.     if {[string length $errormsg] != 0} {
  90.     set state(error) [list $errormsg $errorInfo $errorCode]
  91.     set state(status) error
  92.     }
  93.     catch {close $state(sock)}
  94.     catch {after cancel $state(after)}
  95.     if {[info exists state(-command)]} {
  96.     if {[catch {eval $state(-command) {$token}} err]} {
  97.         if {[string length $errormsg] == 0} {
  98.         set state(error) [list $err $errorInfo $errorCode]
  99.         set state(status) error
  100.         }
  101.     }
  102.     if {[info exist state(-command)]} {
  103.         # Command callback may already have unset our state
  104.         unset state(-command)
  105.     }
  106.     }
  107. }
  108.  
  109. # http::reset --
  110. #
  111. #    See documentaion for details.
  112. #
  113. # Arguments:
  114. #    token    Connection token.
  115. #    why    Status info.
  116. # Results:
  117. #        TODO
  118.  
  119. proc http::reset { token {why reset} } {
  120.     variable $token
  121.     upvar 0 $token state
  122.     set state(status) $why
  123.     catch {fileevent $state(sock) readable {}}
  124.     Finish $token
  125.     if {[info exists state(error)]} {
  126.     set errorlist $state(error)
  127.     unset state(error)
  128.     eval error $errorlist
  129.     }
  130. }
  131.  
  132. # http::geturl --
  133. #
  134. #    Establishes a connection to a remote url via http.
  135. #
  136. # Arguments:
  137. #        url        The http URL to goget.
  138. #        args        Option value pairs. Valid options include:
  139. #                -blocksize, -validate, -headers, -timeout
  140. # Results:
  141. #        Returns a token for this connection.
  142.  
  143.  
  144. proc http::geturl { url args } {
  145.     variable http
  146.     if {![info exists http(uid)]} {
  147.     set http(uid) 0
  148.     }
  149.     set token [namespace current]::[incr http(uid)]
  150.     variable $token
  151.     upvar 0 $token state
  152.     reset $token
  153.     array set state {
  154.     -blocksize     8192
  155.     -validate     0
  156.     -headers     {}
  157.     -timeout     0
  158.     state        header
  159.     meta        {}
  160.     currentsize    0
  161.     totalsize    0
  162.         type            text/html
  163.         body            {}
  164.     status        ""
  165.     }
  166.     set options {-blocksize -channel -command -handler -headers \
  167.         -progress -query -validate -timeout}
  168.     set usage [join $options ", "]
  169.     regsub -all -- - $options {} options
  170.     set pat ^-([join $options |])$
  171.     foreach {flag value} $args {
  172.     if {[regexp $pat $flag]} {
  173.         # Validate numbers
  174.         if {[info exists state($flag)] && \
  175.             [regexp {^[0-9]+$} $state($flag)] && \
  176.             ![regexp {^[0-9]+$} $value]} {
  177.         return -code error "Bad value for $flag ($value), must be integer"
  178.         }
  179.         set state($flag) $value
  180.     } else {
  181.         return -code error "Unknown option $flag, can be: $usage"
  182.     }
  183.     }
  184.     if {! [regexp -nocase {^(http://)?([^/:]+)(:([0-9]+))?(/.*)?$} $url \
  185.         x proto host y port srvurl]} {
  186.     error "Unsupported URL: $url"
  187.     }
  188.     if {[string length $port] == 0} {
  189.     set port 80
  190.     }
  191.     if {[string length $srvurl] == 0} {
  192.     set srvurl /
  193.     }
  194.     if {[string length $proto] == 0} {
  195.     set url http://$url
  196.     }
  197.     set state(url) $url
  198.     if {![catch {$http(-proxyfilter) $host} proxy]} {
  199.     set phost [lindex $proxy 0]
  200.     set pport [lindex $proxy 1]
  201.     }
  202.     if {$state(-timeout) > 0} {
  203.     set state(after) [after $state(-timeout) [list http::reset $token timeout]]
  204.     }
  205.     if {[info exists phost] && [string length $phost]} {
  206.     set srvurl $url
  207.     set s [socket $phost $pport]
  208.     } else {
  209.     set s [socket $host $port]
  210.     }
  211.     set state(sock) $s
  212.  
  213.     # Send data in cr-lf format, but accept any line terminators
  214.  
  215.     fconfigure $s -translation {auto crlf} -buffersize $state(-blocksize)
  216.  
  217.     # The following is disallowed in safe interpreters, but the socket
  218.     # is already in non-blocking mode in that case.
  219.  
  220.     catch {fconfigure $s -blocking off}
  221.     set len 0
  222.     set how GET
  223.     if {[info exists state(-query)]} {
  224.     set len [string length $state(-query)]
  225.     if {$len > 0} {
  226.         set how POST
  227.     }
  228.     } elseif {$state(-validate)} {
  229.     set how HEAD
  230.     }
  231.     puts $s "$how $srvurl HTTP/1.0"
  232.     puts $s "Accept: $http(-accept)"
  233.     puts $s "Host: $host"
  234.     puts $s "User-Agent: $http(-useragent)"
  235.     foreach {key value} $state(-headers) {
  236.     regsub -all \[\n\r\]  $value {} value
  237.     set key [string trim $key]
  238.     if {[string length $key]} {
  239.         puts $s "$key: $value"
  240.     }
  241.     }
  242.     if {$len > 0} {
  243.     puts $s "Content-Length: $len"
  244.     puts $s "Content-Type: application/x-www-form-urlencoded"
  245.     puts $s ""
  246.     fconfigure $s -translation {auto binary}
  247.     puts $s $state(-query)
  248.     } else {
  249.     puts $s ""
  250.     }
  251.     flush $s
  252.     fileevent $s readable [list http::Event $token]
  253.     if {! [info exists state(-command)]} {
  254.     wait $token
  255.     }
  256.     return $token
  257. }
  258.  
  259. # Data access functions:
  260. # Data - the URL data
  261. # Status - the transaction status: ok, reset, eof, timeout
  262. # Code - the HTTP transaction code, e.g., 200
  263. # Size - the size of the URL data
  264.  
  265. proc http::data {token} {
  266.     variable $token
  267.     upvar 0 $token state
  268.     return $state(body)
  269. }
  270. proc http::status {token} {
  271.     variable $token
  272.     upvar 0 $token state
  273.     return $state(status)
  274. }
  275. proc http::code {token} {
  276.     variable $token
  277.     upvar 0 $token state
  278.     return $state(http)
  279. }
  280. proc http::size {token} {
  281.     variable $token
  282.     upvar 0 $token state
  283.     return $state(currentsize)
  284. }
  285.  
  286.  proc http::Event {token} {
  287.     variable $token
  288.     upvar 0 $token state
  289.     set s $state(sock)
  290.  
  291.      if {[::eof $s]} {
  292.     Eof $token
  293.     return
  294.     }
  295.     if {$state(state) == "header"} {
  296.     set n [gets $s line]
  297.     if {$n == 0} {
  298.         set state(state) body
  299.         if {![regexp -nocase ^text $state(type)]} {
  300.         # Turn off conversions for non-text data
  301.         fconfigure $s -translation binary
  302.         if {[info exists state(-channel)]} {
  303.             fconfigure $state(-channel) -translation binary
  304.         }
  305.         }
  306.         if {[info exists state(-channel)] &&
  307.             ![info exists state(-handler)]} {
  308.         # Initiate a sequence of background fcopies
  309.         fileevent $s readable {}
  310.         CopyStart $s $token
  311.         }
  312.     } elseif {$n > 0} {
  313.         if {[regexp -nocase {^content-type:(.+)$} $line x type]} {
  314.         set state(type) [string trim $type]
  315.         }
  316.         if {[regexp -nocase {^content-length:(.+)$} $line x length]} {
  317.         set state(totalsize) [string trim $length]
  318.         }
  319.         if {[regexp -nocase {^([^:]+):(.+)$} $line x key value]} {
  320.         lappend state(meta) $key $value
  321.         } elseif {[regexp ^HTTP $line]} {
  322.         set state(http) $line
  323.         }
  324.     }
  325.     } else {
  326.     if {[catch {
  327.         if {[info exists state(-handler)]} {
  328.         set n [eval $state(-handler) {$s $token}]
  329.         } else {
  330.         set block [read $s $state(-blocksize)]
  331.         set n [string length $block]
  332.         if {$n >= 0} {
  333.             append state(body) $block
  334.         }
  335.         }
  336.         if {$n >= 0} {
  337.         incr state(currentsize) $n
  338.         }
  339.     } err]} {
  340.         Finish $token $err
  341.     } else {
  342.         if {[info exists state(-progress)]} {
  343.         eval $state(-progress) {$token $state(totalsize) $state(currentsize)}
  344.         }
  345.     }
  346.     }
  347. }
  348.  proc http::CopyStart {s token} {
  349.     variable $token
  350.     upvar 0 $token state
  351.     if {[catch {
  352.     fcopy $s $state(-channel) -size $state(-blocksize) -command \
  353.         [list http::CopyDone $token]
  354.     } err]} {
  355.     Finish $token $err
  356.     }
  357. }
  358.  proc http::CopyDone {token count {error {}}} {
  359.     variable $token
  360.     upvar 0 $token state
  361.     set s $state(sock)
  362.     incr state(currentsize) $count
  363.     if {[info exists state(-progress)]} {
  364.     eval $state(-progress) {$token $state(totalsize) $state(currentsize)}
  365.     }
  366.     # At this point the token may have been reset
  367.     if {([string length $error] != 0)} {
  368.     Finish $token $error
  369.     } elseif {[catch {::eof $s} iseof] || $iseof} {
  370.     Eof $token
  371.     } else {
  372.     CopyStart $s $token
  373.     }
  374. }
  375.  proc http::Eof {token} {
  376.     variable $token
  377.     upvar 0 $token state
  378.     if {$state(state) == "header"} {
  379.     # Premature eof
  380.     set state(status) eof
  381.     } else {
  382.     set state(status) ok
  383.     }
  384.     set state(state) eof
  385.     Finish $token
  386. }
  387.  
  388. # http::wait --
  389. #
  390. #    See documentaion for details.
  391. #
  392. # Arguments:
  393. #    token    Connection token.
  394. # Results:
  395. #        The status after the wait.
  396.  
  397. proc http::wait {token} {
  398.     variable $token
  399.     upvar 0 $token state
  400.  
  401.     if {![info exists state(status)] || [string length $state(status)] == 0} {
  402.     vwait $token\(status)
  403.     }
  404.     if {[info exists state(error)]} {
  405.     set errorlist $state(error)
  406.     unset state(error)
  407.     eval error $errorlist
  408.     }
  409.     return $state(status)
  410. }
  411.  
  412. # http::formatQuery --
  413. #
  414. #    See documentaion for details.
  415. #    Call http::formatQuery with an even number of arguments, where 
  416. #    the first is a name, the second is a value, the third is another 
  417. #    name, and so on.
  418. #
  419. # Arguments:
  420. #    args    A list of name-value pairs.
  421. # Results:
  422. #        TODO
  423.  
  424. proc http::formatQuery {args} {
  425.     set result ""
  426.     set sep ""
  427.     foreach i $args {
  428.     append result  $sep [mapReply $i]
  429.     if {$sep != "="} {
  430.         set sep =
  431.     } else {
  432.         set sep &
  433.     }
  434.     }
  435.     return $result
  436. }
  437.  
  438. # do x-www-urlencoded character mapping
  439. # The spec says: "non-alphanumeric characters are replaced by '%HH'"
  440. # 1 leave alphanumerics characters alone
  441. # 2 Convert every other character to an array lookup
  442. # 3 Escape constructs that are "special" to the tcl parser
  443. # 4 "subst" the result, doing all the array substitutions
  444.  
  445.  proc http::mapReply {string} {
  446.     variable formMap
  447.     set alphanumeric    a-zA-Z0-9
  448.     regsub -all \[^$alphanumeric\] $string {$formMap(&)} string
  449.     regsub -all \n $string {\\n} string
  450.     regsub -all \t $string {\\t} string
  451.     regsub -all {[][{})\\]\)} $string {\\&} string
  452.     return [subst $string]
  453. }
  454.  
  455. # Default proxy filter. 
  456.  proc http::ProxyRequired {host} {
  457.     variable http
  458.     if {[info exists http(-proxyhost)] && [string length $http(-proxyhost)]} {
  459.     if {![info exists http(-proxyport)] || ![string length $http(-proxyport)]} {
  460.         set http(-proxyport) 8080
  461.     }
  462.     return [list $http(-proxyhost) $http(-proxyport)]
  463.     } else {
  464.     return {}
  465.     }
  466. }
  467.