OpenCores
URL https://opencores.org/ocsvn/or1k/or1k/trunk

Subversion Repositories or1k

[/] [or1k/] [trunk/] [insight/] [tcl/] [library/] [http2.0/] [http.tcl] - Blame information for rev 1765

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 578 markom
# 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.1.1.1 2002-01-16 10:25:30 markom 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
        unset state(-command)
103
    }
104
}
105
 
106
# http::reset --
107
#
108
#       See documentaion for details.
109
#
110
# Arguments:
111
#       token   Connection token.
112
#       why     Status info.
113
# Results:
114
#        TODO
115
 
116
proc http::reset { token {why reset} } {
117
    variable $token
118
    upvar 0 $token state
119
    set state(status) $why
120
    catch {fileevent $state(sock) readable {}}
121
    Finish $token
122
    if {[info exists state(error)]} {
123
        set errorlist $state(error)
124
        unset state(error)
125
        eval error $errorlist
126
    }
127
}
128
 
129
# http::geturl --
130
#
131
#       Establishes a connection to a remote url via http.
132
#
133
# Arguments:
134
#        url            The http URL to goget.
135
#        args           Option value pairs. Valid options include:
136
#                               -blocksize, -validate, -headers, -timeout
137
# Results:
138
#        Returns a token for this connection.
139
 
140
 
141
proc http::geturl { url args } {
142
    variable http
143
    if {![info exists http(uid)]} {
144
        set http(uid) 0
145
    }
146
    set token [namespace current]::[incr http(uid)]
147
    variable $token
148
    upvar 0 $token state
149
    reset $token
150
    array set state {
151
        -blocksize      8192
152
        -validate       0
153
        -headers        {}
154
        -timeout        0
155
        state           header
156
        meta            {}
157
        currentsize     0
158
        totalsize       0
159
        type            text/html
160
        body            {}
161
        status          ""
162
    }
163
    set options {-blocksize -channel -command -handler -headers \
164
                -progress -query -validate -timeout}
165
    set usage [join $options ", "]
166
    regsub -all -- - $options {} options
167
    set pat ^-([join $options |])$
168
    foreach {flag value} $args {
169
        if {[regexp $pat $flag]} {
170
            # Validate numbers
171
            if {[info exists state($flag)] && \
172
                    [regexp {^[0-9]+$} $state($flag)] && \
173
                    ![regexp {^[0-9]+$} $value]} {
174
                return -code error "Bad value for $flag ($value), must be integer"
175
            }
176
            set state($flag) $value
177
        } else {
178
            return -code error "Unknown option $flag, can be: $usage"
179
        }
180
    }
181
    if {! [regexp -nocase {^(http://)?([^/:]+)(:([0-9]+))?(/.*)?$} $url \
182
            x proto host y port srvurl]} {
183
        error "Unsupported URL: $url"
184
    }
185
    if {[string length $port] == 0} {
186
        set port 80
187
    }
188
    if {[string length $srvurl] == 0} {
189
        set srvurl /
190
    }
191
    if {[string length $proto] == 0} {
192
        set url http://$url
193
    }
194
    set state(url) $url
195
    if {![catch {$http(-proxyfilter) $host} proxy]} {
196
        set phost [lindex $proxy 0]
197
        set pport [lindex $proxy 1]
198
    }
199
    if {$state(-timeout) > 0} {
200
        set state(after) [after $state(-timeout) [list http::reset $token timeout]]
201
    }
202
    if {[info exists phost] && [string length $phost]} {
203
        set srvurl $url
204
        set s [socket $phost $pport]
205
    } else {
206
        set s [socket $host $port]
207
    }
208
    set state(sock) $s
209
 
210
    # Send data in cr-lf format, but accept any line terminators
211
 
212
    fconfigure $s -translation {auto crlf} -buffersize $state(-blocksize)
213
 
214
    # The following is disallowed in safe interpreters, but the socket
215
    # is already in non-blocking mode in that case.
216
 
217
    catch {fconfigure $s -blocking off}
218
    set len 0
219
    set how GET
220
    if {[info exists state(-query)]} {
221
        set len [string length $state(-query)]
222
        if {$len > 0} {
223
            set how POST
224
        }
225
    } elseif {$state(-validate)} {
226
        set how HEAD
227
    }
228
    puts $s "$how $srvurl HTTP/1.0"
229
    puts $s "Accept: $http(-accept)"
230
    puts $s "Host: $host"
231
    puts $s "User-Agent: $http(-useragent)"
232
    foreach {key value} $state(-headers) {
233
        regsub -all \[\n\r\]  $value {} value
234
        set key [string trim $key]
235
        if {[string length $key]} {
236
            puts $s "$key: $value"
237
        }
238
    }
239
    if {$len > 0} {
240
        puts $s "Content-Length: $len"
241
        puts $s "Content-Type: application/x-www-form-urlencoded"
242
        puts $s ""
243
        fconfigure $s -translation {auto binary}
244
        puts $s $state(-query)
245
    } else {
246
        puts $s ""
247
    }
248
    flush $s
249
    fileevent $s readable [list http::Event $token]
250
    if {! [info exists state(-command)]} {
251
        wait $token
252
    }
253
    return $token
254
}
255
 
256
# Data access functions:
257
# Data - the URL data
258
# Status - the transaction status: ok, reset, eof, timeout
259
# Code - the HTTP transaction code, e.g., 200
260
# Size - the size of the URL data
261
 
262
proc http::data {token} {
263
    variable $token
264
    upvar 0 $token state
265
    return $state(body)
266
}
267
proc http::status {token} {
268
    variable $token
269
    upvar 0 $token state
270
    return $state(status)
271
}
272
proc http::code {token} {
273
    variable $token
274
    upvar 0 $token state
275
    return $state(http)
276
}
277
proc http::size {token} {
278
    variable $token
279
    upvar 0 $token state
280
    return $state(currentsize)
281
}
282
 
283
 proc http::Event {token} {
284
    variable $token
285
    upvar 0 $token state
286
    set s $state(sock)
287
 
288
     if {[::eof $s]} {
289
        Eof $token
290
        return
291
    }
292
    if {$state(state) == "header"} {
293
        set n [gets $s line]
294
        if {$n == 0} {
295
            set state(state) body
296
            if {![regexp -nocase ^text $state(type)]} {
297
                # Turn off conversions for non-text data
298
                fconfigure $s -translation binary
299
                if {[info exists state(-channel)]} {
300
                    fconfigure $state(-channel) -translation binary
301
                }
302
            }
303
            if {[info exists state(-channel)] &&
304
                    ![info exists state(-handler)]} {
305
                # Initiate a sequence of background fcopies
306
                fileevent $s readable {}
307
                CopyStart $s $token
308
            }
309
        } elseif {$n > 0} {
310
            if {[regexp -nocase {^content-type:(.+)$} $line x type]} {
311
                set state(type) [string trim $type]
312
            }
313
            if {[regexp -nocase {^content-length:(.+)$} $line x length]} {
314
                set state(totalsize) [string trim $length]
315
            }
316
            if {[regexp -nocase {^([^:]+):(.+)$} $line x key value]} {
317
                lappend state(meta) $key $value
318
            } elseif {[regexp ^HTTP $line]} {
319
                set state(http) $line
320
            }
321
        }
322
    } else {
323
        if {[catch {
324
            if {[info exists state(-handler)]} {
325
                set n [eval $state(-handler) {$s $token}]
326
            } else {
327
                set block [read $s $state(-blocksize)]
328
                set n [string length $block]
329
                if {$n >= 0} {
330
                    append state(body) $block
331
                }
332
            }
333
            if {$n >= 0} {
334
                incr state(currentsize) $n
335
            }
336
        } err]} {
337
            Finish $token $err
338
        } else {
339
            if {[info exists state(-progress)]} {
340
                eval $state(-progress) {$token $state(totalsize) $state(currentsize)}
341
            }
342
        }
343
    }
344
}
345
 proc http::CopyStart {s token} {
346
    variable $token
347
    upvar 0 $token state
348
    if {[catch {
349
        fcopy $s $state(-channel) -size $state(-blocksize) -command \
350
            [list http::CopyDone $token]
351
    } err]} {
352
        Finish $token $err
353
    }
354
}
355
 proc http::CopyDone {token count {error {}}} {
356
    variable $token
357
    upvar 0 $token state
358
    set s $state(sock)
359
    incr state(currentsize) $count
360
    if {[info exists state(-progress)]} {
361
        eval $state(-progress) {$token $state(totalsize) $state(currentsize)}
362
    }
363
    if {([string length $error] != 0)} {
364
        Finish $token $error
365
    } elseif {[::eof $s]} {
366
        Eof $token
367
    } else {
368
        CopyStart $s $token
369
    }
370
}
371
 proc http::Eof {token} {
372
    variable $token
373
    upvar 0 $token state
374
    if {$state(state) == "header"} {
375
        # Premature eof
376
        set state(status) eof
377
    } else {
378
        set state(status) ok
379
    }
380
    set state(state) eof
381
    Finish $token
382
}
383
 
384
# http::wait --
385
#
386
#       See documentaion for details.
387
#
388
# Arguments:
389
#       token   Connection token.
390
# Results:
391
#        The status after the wait.
392
 
393
proc http::wait {token} {
394
    variable $token
395
    upvar 0 $token state
396
 
397
    if {![info exists state(status)] || [string length $state(status)] == 0} {
398
        vwait $token\(status)
399
    }
400
    if {[info exists state(error)]} {
401
        set errorlist $state(error)
402
        unset state(error)
403
        eval error $errorlist
404
    }
405
    return $state(status)
406
}
407
 
408
# http::formatQuery --
409
#
410
#       See documentaion for details.
411
#       Call http::formatQuery with an even number of arguments, where 
412
#       the first is a name, the second is a value, the third is another 
413
#       name, and so on.
414
#
415
# Arguments:
416
#       args    A list of name-value pairs.
417
# Results:
418
#        TODO
419
 
420
proc http::formatQuery {args} {
421
    set result ""
422
    set sep ""
423
    foreach i $args {
424
        append result  $sep [mapReply $i]
425
        if {$sep != "="} {
426
            set sep =
427
        } else {
428
            set sep &
429
        }
430
    }
431
    return $result
432
}
433
 
434
# do x-www-urlencoded character mapping
435
# The spec says: "non-alphanumeric characters are replaced by '%HH'"
436
# 1 leave alphanumerics characters alone
437
# 2 Convert every other character to an array lookup
438
# 3 Escape constructs that are "special" to the tcl parser
439
# 4 "subst" the result, doing all the array substitutions
440
 
441
 proc http::mapReply {string} {
442
    variable formMap
443
    set alphanumeric    a-zA-Z0-9
444
    regsub -all \[^$alphanumeric\] $string {$formMap(&)} string
445
    regsub -all \n $string {\\n} string
446
    regsub -all \t $string {\\t} string
447
    regsub -all {[][{})\\]\)} $string {\\&} string
448
    return [subst $string]
449
}
450
 
451
# Default proxy filter. 
452
 proc http::ProxyRequired {host} {
453
    variable http
454
    if {[info exists http(-proxyhost)] && [string length $http(-proxyhost)]} {
455
        if {![info exists http(-proxyport)] || ![string length $http(-proxyport)]} {
456
            set http(-proxyport) 8080
457
        }
458
        return [list $http(-proxyhost) $http(-proxyport)]
459
    } else {
460
        return {}
461
    }
462
}

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.