PageRenderTime 44ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/gcc/share/tcl8.4/http1.0/http.tcl

http://github.com/yangsiwei880813/RealTime
TCL | 379 lines | 337 code | 15 blank | 27 comment | 83 complexity | e1f7adcfb99a49d712b7cfa41fe1dd37 MD5 | raw file
Possible License(s): 0BSD, AGPL-3.0, GPL-2.0
  1. # http.tcl
  2. # Client-side HTTP for GET, POST, and HEAD commands.
  3. # These routines can be used in untrusted code that uses the Safesock
  4. # security policy.
  5. # These procedures use a callback interface to avoid using vwait,
  6. # which is not defined in the safe base.
  7. #
  8. # RCS: @(#) $Id: http.tcl,v 1.4 2000/02/01 11:48:30 hobbs Exp $
  9. #
  10. # See the http.n man page for documentation
  11. package provide http 1.0
  12. array set http {
  13. -accept */*
  14. -proxyhost {}
  15. -proxyport {}
  16. -useragent {Tcl http client package 1.0}
  17. -proxyfilter httpProxyRequired
  18. }
  19. proc http_config {args} {
  20. global http
  21. set options [lsort [array names http -*]]
  22. set usage [join $options ", "]
  23. if {[llength $args] == 0} {
  24. set result {}
  25. foreach name $options {
  26. lappend result $name $http($name)
  27. }
  28. return $result
  29. }
  30. regsub -all -- - $options {} options
  31. set pat ^-([join $options |])$
  32. if {[llength $args] == 1} {
  33. set flag [lindex $args 0]
  34. if {[regexp -- $pat $flag]} {
  35. return $http($flag)
  36. } else {
  37. return -code error "Unknown option $flag, must be: $usage"
  38. }
  39. } else {
  40. foreach {flag value} $args {
  41. if {[regexp -- $pat $flag]} {
  42. set http($flag) $value
  43. } else {
  44. return -code error "Unknown option $flag, must be: $usage"
  45. }
  46. }
  47. }
  48. }
  49. proc httpFinish { token {errormsg ""} } {
  50. upvar #0 $token state
  51. global errorInfo errorCode
  52. if {[string length $errormsg] != 0} {
  53. set state(error) [list $errormsg $errorInfo $errorCode]
  54. set state(status) error
  55. }
  56. catch {close $state(sock)}
  57. catch {after cancel $state(after)}
  58. if {[info exists state(-command)]} {
  59. if {[catch {eval $state(-command) {$token}} err]} {
  60. if {[string length $errormsg] == 0} {
  61. set state(error) [list $err $errorInfo $errorCode]
  62. set state(status) error
  63. }
  64. }
  65. unset state(-command)
  66. }
  67. }
  68. proc http_reset { token {why reset} } {
  69. upvar #0 $token state
  70. set state(status) $why
  71. catch {fileevent $state(sock) readable {}}
  72. httpFinish $token
  73. if {[info exists state(error)]} {
  74. set errorlist $state(error)
  75. unset state(error)
  76. eval error $errorlist
  77. }
  78. }
  79. proc http_get { url args } {
  80. global http
  81. if {![info exists http(uid)]} {
  82. set http(uid) 0
  83. }
  84. set token http#[incr http(uid)]
  85. upvar #0 $token state
  86. http_reset $token
  87. array set state {
  88. -blocksize 8192
  89. -validate 0
  90. -headers {}
  91. -timeout 0
  92. state header
  93. meta {}
  94. currentsize 0
  95. totalsize 0
  96. type text/html
  97. body {}
  98. status ""
  99. }
  100. set options {-blocksize -channel -command -handler -headers \
  101. -progress -query -validate -timeout}
  102. set usage [join $options ", "]
  103. regsub -all -- - $options {} options
  104. set pat ^-([join $options |])$
  105. foreach {flag value} $args {
  106. if {[regexp $pat $flag]} {
  107. # Validate numbers
  108. if {[info exists state($flag)] && \
  109. [regexp {^[0-9]+$} $state($flag)] && \
  110. ![regexp {^[0-9]+$} $value]} {
  111. return -code error "Bad value for $flag ($value), must be integer"
  112. }
  113. set state($flag) $value
  114. } else {
  115. return -code error "Unknown option $flag, can be: $usage"
  116. }
  117. }
  118. if {! [regexp -nocase {^(http://)?([^/:]+)(:([0-9]+))?(/.*)?$} $url \
  119. x proto host y port srvurl]} {
  120. error "Unsupported URL: $url"
  121. }
  122. if {[string length $port] == 0} {
  123. set port 80
  124. }
  125. if {[string length $srvurl] == 0} {
  126. set srvurl /
  127. }
  128. if {[string length $proto] == 0} {
  129. set url http://$url
  130. }
  131. set state(url) $url
  132. if {![catch {$http(-proxyfilter) $host} proxy]} {
  133. set phost [lindex $proxy 0]
  134. set pport [lindex $proxy 1]
  135. }
  136. if {$state(-timeout) > 0} {
  137. set state(after) [after $state(-timeout) [list http_reset $token timeout]]
  138. }
  139. if {[info exists phost] && [string length $phost]} {
  140. set srvurl $url
  141. set s [socket $phost $pport]
  142. } else {
  143. set s [socket $host $port]
  144. }
  145. set state(sock) $s
  146. # Send data in cr-lf format, but accept any line terminators
  147. fconfigure $s -translation {auto crlf} -buffersize $state(-blocksize)
  148. # The following is disallowed in safe interpreters, but the socket
  149. # is already in non-blocking mode in that case.
  150. catch {fconfigure $s -blocking off}
  151. set len 0
  152. set how GET
  153. if {[info exists state(-query)]} {
  154. set len [string length $state(-query)]
  155. if {$len > 0} {
  156. set how POST
  157. }
  158. } elseif {$state(-validate)} {
  159. set how HEAD
  160. }
  161. puts $s "$how $srvurl HTTP/1.0"
  162. puts $s "Accept: $http(-accept)"
  163. puts $s "Host: $host"
  164. puts $s "User-Agent: $http(-useragent)"
  165. foreach {key value} $state(-headers) {
  166. regsub -all \[\n\r\] $value {} value
  167. set key [string trim $key]
  168. if {[string length $key]} {
  169. puts $s "$key: $value"
  170. }
  171. }
  172. if {$len > 0} {
  173. puts $s "Content-Length: $len"
  174. puts $s "Content-Type: application/x-www-form-urlencoded"
  175. puts $s ""
  176. fconfigure $s -translation {auto binary}
  177. puts -nonewline $s $state(-query)
  178. } else {
  179. puts $s ""
  180. }
  181. flush $s
  182. fileevent $s readable [list httpEvent $token]
  183. if {! [info exists state(-command)]} {
  184. http_wait $token
  185. }
  186. return $token
  187. }
  188. proc http_data {token} {
  189. upvar #0 $token state
  190. return $state(body)
  191. }
  192. proc http_status {token} {
  193. upvar #0 $token state
  194. return $state(status)
  195. }
  196. proc http_code {token} {
  197. upvar #0 $token state
  198. return $state(http)
  199. }
  200. proc http_size {token} {
  201. upvar #0 $token state
  202. return $state(currentsize)
  203. }
  204. proc httpEvent {token} {
  205. upvar #0 $token state
  206. set s $state(sock)
  207. if {[eof $s]} {
  208. httpEof $token
  209. return
  210. }
  211. if {$state(state) == "header"} {
  212. set n [gets $s line]
  213. if {$n == 0} {
  214. set state(state) body
  215. if {![regexp -nocase ^text $state(type)]} {
  216. # Turn off conversions for non-text data
  217. fconfigure $s -translation binary
  218. if {[info exists state(-channel)]} {
  219. fconfigure $state(-channel) -translation binary
  220. }
  221. }
  222. if {[info exists state(-channel)] &&
  223. ![info exists state(-handler)]} {
  224. # Initiate a sequence of background fcopies
  225. fileevent $s readable {}
  226. httpCopyStart $s $token
  227. }
  228. } elseif {$n > 0} {
  229. if {[regexp -nocase {^content-type:(.+)$} $line x type]} {
  230. set state(type) [string trim $type]
  231. }
  232. if {[regexp -nocase {^content-length:(.+)$} $line x length]} {
  233. set state(totalsize) [string trim $length]
  234. }
  235. if {[regexp -nocase {^([^:]+):(.+)$} $line x key value]} {
  236. lappend state(meta) $key $value
  237. } elseif {[regexp ^HTTP $line]} {
  238. set state(http) $line
  239. }
  240. }
  241. } else {
  242. if {[catch {
  243. if {[info exists state(-handler)]} {
  244. set n [eval $state(-handler) {$s $token}]
  245. } else {
  246. set block [read $s $state(-blocksize)]
  247. set n [string length $block]
  248. if {$n >= 0} {
  249. append state(body) $block
  250. }
  251. }
  252. if {$n >= 0} {
  253. incr state(currentsize) $n
  254. }
  255. } err]} {
  256. httpFinish $token $err
  257. } else {
  258. if {[info exists state(-progress)]} {
  259. eval $state(-progress) {$token $state(totalsize) $state(currentsize)}
  260. }
  261. }
  262. }
  263. }
  264. proc httpCopyStart {s token} {
  265. upvar #0 $token state
  266. if {[catch {
  267. fcopy $s $state(-channel) -size $state(-blocksize) -command \
  268. [list httpCopyDone $token]
  269. } err]} {
  270. httpFinish $token $err
  271. }
  272. }
  273. proc httpCopyDone {token count {error {}}} {
  274. upvar #0 $token state
  275. set s $state(sock)
  276. incr state(currentsize) $count
  277. if {[info exists state(-progress)]} {
  278. eval $state(-progress) {$token $state(totalsize) $state(currentsize)}
  279. }
  280. if {([string length $error] != 0)} {
  281. httpFinish $token $error
  282. } elseif {[eof $s]} {
  283. httpEof $token
  284. } else {
  285. httpCopyStart $s $token
  286. }
  287. }
  288. proc httpEof {token} {
  289. upvar #0 $token state
  290. if {$state(state) == "header"} {
  291. # Premature eof
  292. set state(status) eof
  293. } else {
  294. set state(status) ok
  295. }
  296. set state(state) eof
  297. httpFinish $token
  298. }
  299. proc http_wait {token} {
  300. upvar #0 $token state
  301. if {![info exists state(status)] || [string length $state(status)] == 0} {
  302. vwait $token\(status)
  303. }
  304. if {[info exists state(error)]} {
  305. set errorlist $state(error)
  306. unset state(error)
  307. eval error $errorlist
  308. }
  309. return $state(status)
  310. }
  311. # Call http_formatQuery with an even number of arguments, where the first is
  312. # a name, the second is a value, the third is another name, and so on.
  313. proc http_formatQuery {args} {
  314. set result ""
  315. set sep ""
  316. foreach i $args {
  317. append result $sep [httpMapReply $i]
  318. if {$sep != "="} {
  319. set sep =
  320. } else {
  321. set sep &
  322. }
  323. }
  324. return $result
  325. }
  326. # do x-www-urlencoded character mapping
  327. # The spec says: "non-alphanumeric characters are replaced by '%HH'"
  328. # 1 leave alphanumerics characters alone
  329. # 2 Convert every other character to an array lookup
  330. # 3 Escape constructs that are "special" to the tcl parser
  331. # 4 "subst" the result, doing all the array substitutions
  332. proc httpMapReply {string} {
  333. global httpFormMap
  334. set alphanumeric a-zA-Z0-9
  335. if {![info exists httpFormMap]} {
  336. for {set i 1} {$i <= 256} {incr i} {
  337. set c [format %c $i]
  338. if {![string match \[$alphanumeric\] $c]} {
  339. set httpFormMap($c) %[format %.2x $i]
  340. }
  341. }
  342. # These are handled specially
  343. array set httpFormMap {
  344. " " + \n %0d%0a
  345. }
  346. }
  347. regsub -all \[^$alphanumeric\] $string {$httpFormMap(&)} string
  348. regsub -all \n $string {\\n} string
  349. regsub -all \t $string {\\t} string
  350. regsub -all {[][{})\\]\)} $string {\\&} string
  351. return [subst $string]
  352. }
  353. # Default proxy filter.
  354. proc httpProxyRequired {host} {
  355. global http
  356. if {[info exists http(-proxyhost)] && [string length $http(-proxyhost)]} {
  357. if {![info exists http(-proxyport)] || ![string length $http(-proxyport)]} {
  358. set http(-proxyport) 8080
  359. }
  360. return [list $http(-proxyhost) $http(-proxyport)]
  361. } else {
  362. return {}
  363. }
  364. }