-
Notifications
You must be signed in to change notification settings - Fork 5
/
rewrite.lisp
772 lines (728 loc) · 43 KB
/
rewrite.lisp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
(in-package :drakma-async)
(defmacro rewrite-http-request (defun-form)
"This macro automates the conversion from drakma:http-request to be
asynchronous (http-request-async). It does this by performing recursive tree
searches on the main http-request defun and replacing certain pieces with
async-ready code.
It was built because I had to keep porting new versions of drakma over by
hand. This is all fine and dandy, but why do it by hand when you can
automate it. Now I can copy and paste http-request from any drakma version
into a (rewrite-http-request ...) macro and all is well in async land."
(macrolet ((do-replace (form fn)
`(let ((replacement (tree-search-replace defun-form ,form ,fn)))
(if replacement
(setf defun-form replacement)
(format t "rewrite-http-request: form not found: ~s~%" ,form)))))
;; rename http-request -> http-request-async
(do-replace '(defun http-request :...)
(lambda (form)
(setf (cadr form) 'http-request-async)
form))
;; drop all the stream processing stuff, we are ONLY allowing a stream to be
;; passed in.
(do-replace '(setq http-stream (or stream :...) :...)
(lambda (form)
;; the (or ...) is in caddr
(setf (caddr form)
'(or stream
(error "Stream not passed into http-request-async (required).")))
form))
;; make it so you can proxy even if a stream is passed in
(do-replace '(and proxy (null stream) (not proxying-https-p) (not real-host))
(lambda (form)
(remove '(null stream) form :test #'equal)))
;; disable SSL within drakma (this is handled by drakma-async/cl-async)
(do-replace '(use-ssl (and (not proxying-https-p)
(or force-ssl
(eq (puri:uri-scheme uri) :https))))
(lambda (form)
'(use-ssl nil)))
;; make sure finish-request returns a lambda when it's finished (instead of
;; trying to process a request that hasn't been received yet).
(do-replace '(with-character-stream-semantics :...)
(lambda (form)
`(lambda ()
(block http-request
,form))))
;; remove some items we aren't going to forward in the args variable when
;; forwarding.
(do-replace '(unless re-use-stream (ignore-errors (close http-stream)))
(lambda (form)
;'(unless re-use-stream
; (remf args :close)
; (remf args :stream)
; (ignore-errors (close http-stream)))
`(progn (setf re-use-stream nil) ,form)))
;; re-write the part that follows HTTP forwards/redirects
(do-replace '(return-from http-request
(let (:...)
(apply #'http-request new-uri :...)))
(lambda (form)
(declare (ignore form))
'(return-from http-request
(let ((method (if (and (member status-code drakma::+redirect-to-get-codes+)
(member method drakma::+redirect-to-get-methods+))
:get
method)))
(apply (if re-use-stream
'http-request-async
'drakma-async:http-request)
(append
(list
new-uri
:method method
:redirect (cond ((integerp redirect) (1- redirect))
(t redirect))
:additional-headers additional-headers
;; don't send GET parameters again in redirect
:parameters (and (not (eq method :get)) parameters)
;; don't send form-data from a POST redirect to a GET
:form-data (and (not (eq method :get)) form-data)
:preserve-uri t)
(when re-use-stream
(list :stream http-stream))
args))))))
;; support content :continuation
(do-replace '(when (eq content :continuation)
(return-from http-request #'finish-request))
(lambda (form)
(declare (ignore form))
'(when (eq content :continuation)
(return-from http-request-async #'finish-request))))
;; make sure the http-stream is NEVER closed before it gets a full response.
;; so here, we make sure the logic that decides whether or not to close it
;; always returns nil.
(do-replace '(when (and http-stream :...) (ignore-errors (close http-stream)))
(lambda (form)
(declare (ignore form))
;; make sure the form always fails
'(when nil nil)))
defun-form))
;; The http-request form can be pasted here, verbatim, and rewrite-http-request
;; will automatically make any adjustments it needs to convert it to async.
(rewrite-http-request
(defun http-request (uri &rest args
&key (protocol :http/1.1)
(method :get)
force-ssl
certificate
key
certificate-password
verify
max-depth
ca-file
ca-directory
parameters
(url-encoder #'url-encode)
content
(content-type "application/x-www-form-urlencoded")
(content-length nil content-length-provided-p)
form-data
cookie-jar
basic-authorization
(user-agent :drakma)
(accept "*/*")
range
(proxy *default-http-proxy*)
(no-proxy-domains *no-proxy-domains*)
proxy-basic-authorization
real-host
vhost
additional-headers
(redirect 5)
auto-referer
keep-alive
(close t)
(external-format-out *drakma-default-external-format*)
(external-format-in *drakma-default-external-format*)
force-binary
want-stream
stream
preserve-uri
#+(or abcl clisp lispworks mcl openmcl sbcl)
(connection-timeout 20)
#+:lispworks (read-timeout 20)
#+(and :lispworks (not :lw-does-not-have-write-timeout))
(write-timeout 20 write-timeout-provided-p)
#+:openmcl
deadline
&aux (unparsed-uri (if (stringp uri) (copy-seq uri) (puri:copy-uri uri))))
"Sends a HTTP request to a web server and returns its reply. URI
is where the request is sent to, and it is either a string denoting a
uniform resource identifier or a PURI:URI object. The scheme of URI
must be `http' or `https'. The function returns SEVEN values - the
body of the reply \(but see below), the status code as an integer, an
alist of the headers sent by the server where for each element the car
\(the name of the header) is a keyword and the cdr \(the value of the
header) is a string, the URI the reply comes from \(which might be
different from the URI the request was sent to in case of redirects),
the stream the reply was read from, a generalized boolean which
denotes whether the stream should be closed \(and which you can
usually ignore), and finally the reason phrase from the status line as
a string.
PROTOCOL is the HTTP protocol which is going to be used in the
request line, it must be one of the keywords :HTTP/1.0 or
:HTTP/1.1. METHOD is the method used in the request line, a
keyword \(like :GET or :HEAD) denoting a valid HTTP/1.1 or WebDAV
request method, or :REPORT, as described in the Versioning
Extensions to WebDAV. Additionally, you can also use the pseudo
method :OPTIONS* which is like :OPTIONS but means that an
\"OPTIONS *\" request line will be sent, i.e. the URI's path and
query parts will be ignored.
If FORCE-SSL is true, SSL will be attached to the socket stream
which connects Drakma with the web server. Usually, you don't
have to provide this argument, as SSL will be attached anyway if
the scheme of URI is `https'.
CERTIFICATE is the file name of the PEM encoded client certificate to
present to the server when making a SSL connection. KEY specifies the
file name of the PEM encoded private key matching the certificate.
CERTIFICATE-PASSWORD specifies the pass phrase to use to decrypt the
private key.
VERIFY can be specified to force verification of the certificate that
is presented by the server in an SSL connection. It can be specified
either as NIL if no check should be performed, :OPTIONAL to verify the
server's certificate if it presented one or :REQUIRED to verify the
server's certificate and fail if an invalid or no certificate was
presented.
MAX-DEPTH can be specified to change the maximum allowed certificate
signing depth that is accepted. The default is 10.
CA-FILE and CA-DIRECTORY can be specified to set the certificate
authority bundle file or directory to use for certificate validation.
The CERTIFICATE, KEY, CERTIFICATE-PASSWORD, VERIFY, MAX-DEPTH, CA-FILE
and CA-DIRECTORY parameters are ignored for non-SSL requests. They
are also ignored on LispWorks.
PARAMETERS is an alist of name/value pairs \(the car and the cdr each
being a string) which denotes the parameters which are added to the
query part of the URL or \(in the case of a POST request) comprise the
body of the request. (But see CONTENT below.) The values can also be
NIL in which case only the name \(without an equal sign) is used in
the query string. The name/value pairs are URL-encoded using the
FLEXI-STREAMS external format EXTERNAL-FORMAT-OUT before they are sent
to the server unless FORM-DATA is true in which case the POST request
body is sent as `multipart/form-data' using EXTERNAL-FORMAT-OUT. The
values of the PARAMETERS alist can also be pathnames, open binary
input streams, unary functions, or lists where the first element is of
one of the former types. These values denote files which should be
sent as part of the request body. If files are present in PARAMETERS,
the content type of the request is always `multipart/form-data'. If
the value is a list, the part of the list behind the first element is
treated as a plist which can be used to specify a content type and/or
a filename for the file, i.e. such a value could look like, e.g.,
\(#p\"/tmp/my_file.doc\" :content-type \"application/msword\"
:filename \"upload.doc\").
URL-ENCODER specifies a custom URL encoder function which will be used
by drakma to URL-encode parameter names and values. It needs to be a
function of one argument. The argument is the string to encode, the
return value must be the URL-encoded string. This can be used if
specific encoding rules are required.
CONTENT, if not NIL, is used as the request body - PARAMETERS is
ignored in this case. CONTENT can be a string, a sequence of
octets, a pathname, an open binary input stream, or a function
designator. If CONTENT is a sequence, it will be directly sent
to the server \(using EXTERNAL-FORMAT-OUT in the case of
strings). If CONTENT is a pathname, the binary contents of the
corresponding file will be sent to the server. If CONTENT is a
stream, everything that can be read from the stream until EOF
will be sent to the server. If CONTENT is a function designator,
the corresponding function will be called with one argument, the
stream to the server, to which it should send data.
Finally, CONTENT can also be the keyword :CONTINUATION in which case
HTTP-REQUEST returns only one value - a `continuation' function. This
function has one required argument and one optional argument. The
first argument will be interpreted like CONTENT above \(but it cannot
be a keyword), i.e. it will be sent to the server according to its
type. If the second argument is true, the continuation function can
be called again to send more content, if it is NIL the continuation
function returns what HTTP-REQUEST would have returned.
If CONTENT is a sequence, Drakma will use LENGTH to determine its
length and will use the result for the `Content-Length' header sent to
the server. You can overwrite this with the CONTENT-LENGTH parameter
\(a non-negative integer) which you can also use for the cases where
Drakma can't or won't determine the content length itself. You can
also explicitly provide a CONTENT-LENGTH argument of NIL which will
imply that no `Content-Length' header will be sent in any case. If no
`Content-Length' header is sent, Drakma will use chunked encoding to
send the content body. Note that this will not work with older web
servers.
Providing a true CONTENT-LENGTH argument which is not a non-negative
integer means that Drakma /must/ build the request body in RAM and
compute the content length even if it would have otherwise used
chunked encoding, for example in the case of file uploads.
CONTENT-TYPE is the corresponding `Content-Type' header to be sent and
will be ignored unless CONTENT is provided as well.
Note that a query already contained in URI will always be sent with
the request line anyway in addition to other parameters sent by
Drakma.
COOKIE-JAR is a cookie jar containing cookies which will
potentially be sent to the server \(if the domain matches, if
they haven't expired, etc.) - this cookie jar will be modified
according to the `Set-Cookie' header\(s) sent back by the server.
BASIC-AUTHORIZATION, if not NIL, should be a list of two strings
\(username and password) which will be sent to the server for
basic authorization. USER-AGENT, if not NIL, denotes which
`User-Agent' header will be sent with the request. It can be one
of the keywords :DRAKMA, :FIREFOX, :EXPLORER, :OPERA, or :SAFARI
which denote the current version of Drakma or, in the latter four
cases, a fixed string corresponding to a more or less recent \(as
of August 2006) version of the corresponding browser. Or it can
be a string which is used directly.
ACCEPT, if not NIL, specifies the contents of the `Accept' header
sent.
RANGE optionally specifies a subrange of the resource to be requested.
It must be specified as a list of two integers which indicate the
start and \(inclusive) end offset of the requested range, in bytes
\(i.e. octets).
If PROXY is not NIL, it should be a string denoting a proxy
server through which the request should be sent. Or it can be a
list of two values - a string denoting the proxy server and an
integer denoting the port to use \(which will default to 80
otherwise). Defaults to *default-http-proxy*.
PROXY-BASIC-AUTHORIZATION is used like
BASIC-AUTHORIZATION, but for the proxy, and only if PROXY is
true. If the host portion of the uri is present in the
*no-proxy-domains* or the NO-PROXY-DOMAINS list then the proxy
setting will be ignored for this request.
If NO-PROXY-DOMAINS is set then it will supersede the
*no-proxy-domains* variable. Inserting domains into this list will
allow them to ignore the proxy setting.
If REAL-HOST is not NIL, request is sent to the denoted host instead
of the URI host. When specified, REAL-HOST supersedes PROXY.
ADDITIONAL-HEADERS is a name/value alist of additional HTTP headers
which should be sent with the request. Unlike in PARAMETERS, the cdrs
can not only be strings but also designators for unary functions
\(which should in turn return a string) in which case the function is
called each time the header is written.
If REDIRECT is not NIL, it must be a non-negative integer or T.
If REDIRECT is true, Drakma will follow redirects \(return codes
301, 302, 303, or 307) unless REDIRECT is 0. If REDIRECT is an
integer, it will be decreased by 1 with each redirect.
Furthermore, if AUTO-REFERER is true when following redirects,
Drakma will populate the `Referer' header with the URI that
triggered the redirection, overwriting an existing `Referer'
header \(in ADDITIONAL-HEADERS) if necessary.
If KEEP-ALIVE is T, the server will be asked to keep the
connection alive, i.e. not to close it after the reply has been
sent. \(Note that this not necessary if both the client and the
server use HTTP 1.1.) If CLOSE is T, the server is explicitly
asked to close the connection after the reply has been sent.
KEEP-ALIVE and CLOSE are obviously mutually exclusive.
If the message body sent by the server has a text content type, Drakma
will try to return it as a Lisp string. It'll first check if the
`Content-Type' header denotes an encoding to be used, or otherwise it
will use the EXTERNAL-FORMAT-IN argument. The body is decoded using
FLEXI-STREAMS. If FLEXI-STREAMS doesn't know the external format, the
body is returned as an array of octets. If the body is empty, Drakma
will return NIL.
If the message body doesn't have a text content type or if
FORCE-BINARY is true, the body is always returned as an array of
octets.
If WANT-STREAM is true, the message body is NOT read and instead the
\(open) socket stream is returned as the first return value. If the
sixth value of HTTP-REQUEST is true, the stream should be closed \(and
not be re-used) after the body has been read. The stream returned is
a flexi stream \(see http://weitz.de/flexi-streams/) with a chunked
stream \(see http://weitz.de/chunga/) as its underlying stream. If
you want to read binary data from this stream, read from the
underlying stream which you can get with FLEXI-STREAM-STREAM.
Drakma will usually create a new socket connection for each HTTP
request. However, you can use the STREAM argument to provide an
open socket stream which should be re-used. STREAM MUST be a
stream returned by a previous invocation of HTTP-REQUEST where
the sixth return value wasn't true. Obviously, it must also be
connected to the correct server and at the right position
\(i.e. the message body, if any, must have been read). Drakma
will NEVER attach SSL to a stream provided as the STREAM
argument.
CONNECTION-TIMEOUT is the time \(in seconds) Drakma will wait until it
considers an attempt to connect to a server as a failure. It is
supported only on some platforms \(currently abcl, clisp, LispWorks,
mcl, openmcl and sbcl). READ-TIMEOUT and WRITE-TIMEOUT are the read
and write timeouts \(in seconds) for the socket stream to the server.
All three timeout arguments can also be NIL \(meaning no timeout), and
they don't apply if an existing stream is re-used. READ-TIMEOUT
argument is only available for LispWorks, WRITE-TIMEOUT is only
available for LispWorks 5.0 or higher.
DEADLINE, a time in the future, specifies the time until which the
request should be finished. The deadline is specified in internal
time units. If the server fails to respond until that time, a
COMMUNICATION-DEADLINE-EXPIRED condition is signalled. DEADLINE is
only available on CCL 1.2 and later.
If PRESERVE-URI is not NIL, the given URI will not be processed. This
means that the URI will be sent as-is to the remote server and it is
the responsibility of the client to make sure that all parameters are
encoded properly. Note that if this parameter is given, and the
request is not a POST with a content-type of `multipart/form-data',
PARAMETERS will not be used."
#+lispworks
(declare (ignore certificate key certificate-password verify max-depth ca-file ca-directory))
(unless (member protocol '(:http/1.0 :http/1.1) :test #'eq)
(parameter-error "Don't know how to handle protocol ~S." protocol))
(setq uri (cond ((puri:uri-p uri) (puri:copy-uri uri))
(t (puri:parse-uri uri))))
(unless (member method +known-methods+ :test #'eq)
(parameter-error "Don't know how to handle method ~S." method))
(unless (member (puri:uri-scheme uri) '(:http :https) :test #'eq)
(parameter-error "Don't know how to handle scheme ~S." (puri:uri-scheme uri)))
(when (and close keep-alive)
(parameter-error "CLOSE and KEEP-ALIVE must not be both true."))
(when (and form-data (not (member method '(:post :report) :test #'eq)))
(parameter-error "FORM-DATA only makes sense with POST requests."))
(when range
(unless (and (listp range)
(integerp (first range))
(integerp (second range))
(<= (first range) (second range)))
(parameter-error "RANGE parameter must be specified as list of two integers, with the second larger or equal to the first")))
;; supersede PROXY with REAL-HOST
(when real-host
(setq proxy real-host))
;; convert PROXY argument to canonical form
(when proxy
(when (atom proxy)
(setq proxy (list proxy 80))))
;; Ignore the proxy for whitelisted hosts.
(when (member (puri:uri-host uri) no-proxy-domains :test #'string=)
(setq proxy '()))
;; make sure we don't get :CRLF on Windows
(let ((*default-eol-style* :lf)
(file-parameters-p (find-if-not (lambda (thing)
(or (stringp thing)
(null thing)))
parameters :key #'cdr))
parameters-used-p)
(when (and file-parameters-p (not (eq method :post)))
(parameter-error "Don't know how to handle parameters in ~S, as this is not a POST request."
parameters))
(when (eq method :post)
;; create content body for POST unless it was provided
(unless content
;; mark PARAMETERS argument as used up, so we don't use it
;; again below
(setq parameters-used-p t)
(cond ((or form-data file-parameters-p)
(let ((boundary (format nil "----------~A" (make-random-string))))
(setq content (make-form-data-function parameters boundary external-format-out)
content-type (format nil "multipart/form-data; boundary=~A" boundary)))
(unless (or file-parameters-p content-length-provided-p)
(setq content-length (or content-length t))))
(t
(setq content (alist-to-url-encoded-string parameters external-format-out url-encoder)
content-type "application/x-www-form-urlencoded")))))
(let ((proxying-https-p (and proxy (not stream) (eq :https (puri:uri-scheme uri))))
http-stream raw-http-stream must-close done)
(unwind-protect
(progn
(let ((host (or (and proxy (first proxy))
(puri:uri-host uri)))
(port (cond (proxy (second proxy))
((puri:uri-port uri))
(t (default-port uri))))
(use-ssl (and (not proxying-https-p)
(or force-ssl
(eq (puri:uri-scheme uri) :https)))))
#+(and :lispworks5.0 :mswindows
(not :lw-does-not-have-write-timeout))
(when use-ssl
(when (and write-timeout write-timeout-provided-p)
(drakma-warn "Disabling WRITE-TIMEOUT because it doesn't mix well with SSL."))
(setq write-timeout nil))
(setq http-stream (or stream
#+:lispworks
(comm:open-tcp-stream host port
:element-type 'octet
:timeout connection-timeout
:read-timeout read-timeout
#-:lw-does-not-have-write-timeout
:write-timeout
#-:lw-does-not-have-write-timeout
write-timeout
:errorp t)
#-:lispworks
(usocket:socket-stream
(usocket:socket-connect host port
:element-type 'octet
#+:openmcl :deadline
#+:openmcl deadline
#+(or abcl clisp lispworks mcl openmcl sbcl)
:timeout
#+(or abcl clisp lispworks mcl openmcl sbcl)
connection-timeout
:nodelay :if-supported)))
raw-http-stream http-stream)
#+:openmcl
(when deadline
;; it is correct to set the deadline here even though
;; it may have been initialized by SOCKET-CONNECT
;; already - the stream may have been passed in by the
;; user and the user may want to adjust the deadline
;; for every request
(setf (ccl:stream-deadline http-stream) deadline))
(labels ((write-http-line (fmt &rest args)
(when *header-stream*
(format *header-stream* "~?~%" fmt args))
(format http-stream "~?~C~C" fmt args #\Return #\Linefeed))
(write-header (name value-fmt &rest value-args)
(write-http-line "~A: ~?" name value-fmt value-args))
(wrap-stream (http-stream)
(make-flexi-stream (make-chunked-stream http-stream)
:external-format +latin-1+)))
(when (and use-ssl
;; don't attach SSL to existing streams
(not stream))
#+:lispworks
(comm:attach-ssl http-stream :ssl-side :client)
#-:lispworks
(setq http-stream (make-ssl-stream http-stream
:certificate certificate
:key key
:certificate-password certificate-password
:verify verify
:max-depth max-depth
:ca-file ca-file
:ca-directory ca-directory)))
(cond (stream
(setf (flexi-stream-element-type http-stream)
#+:lispworks 'lw:simple-char #-:lispworks 'character
(flexi-stream-external-format http-stream) +latin-1+))
(t
(setq http-stream (wrap-stream http-stream))))
(when proxying-https-p
;; set up a tunnel through the proxy server to the
;; final destination
(write-http-line "CONNECT ~A:~:[443~;~:*~A~] HTTP/1.1"
(puri:uri-host uri) (puri:uri-port uri))
(write-http-line "Host: ~A:~:[443~;~:*~A~]"
(or vhost (puri:uri-host uri)) (puri:uri-port uri))
(write-http-line "")
(force-output http-stream)
;; check we get a 200 response before proceeding
(unless (eql (second (read-status-line http-stream *header-stream*)) 200)
(error "Unable to establish HTTPS tunnel through proxy."))
;; got a connection; we have to read a blank line,
;; turn on SSL, and then we can transmit
(read-line* http-stream)
#+:lispworks
(comm:attach-ssl raw-http-stream :ssl-side :client)
#-:lispworks
(setq http-stream (wrap-stream (make-ssl-stream raw-http-stream))))
(when-let (all-get-parameters
(and (not preserve-uri)
(append (dissect-query (puri:uri-query uri))
(and (not parameters-used-p) parameters))))
(setf (puri:uri-query uri)
(alist-to-url-encoded-string all-get-parameters external-format-out url-encoder)))
(when (eq method :options*)
;; special pseudo-method
(setf method :options
(puri:uri-path uri) "*"
(puri:uri-query uri) nil))
(write-http-line "~A ~A ~A"
(string-upcase method)
(if (and preserve-uri
(stringp unparsed-uri))
(trivial-uri-path unparsed-uri)
(puri:render-uri (if (and proxy
(null stream)
(not proxying-https-p)
(not real-host))
uri
(make-instance 'puri:uri
:path (or (puri:uri-path uri) "/")
:query (puri:uri-query uri)))
nil))
(string-upcase protocol))
(write-header "Host" "~A~@[:~A~]" (or vhost (puri:uri-host uri)) (non-default-port uri))
(when user-agent
(write-header "User-Agent" "~A" (user-agent-string user-agent)))
(when basic-authorization
(write-header "Authorization" "Basic ~A"
(base64:string-to-base64-string
(format nil "~A:~A"
(first basic-authorization)
(second basic-authorization)))))
(when (and proxy proxy-basic-authorization)
(write-header "Proxy-Authorization" "Basic ~A"
(base64:string-to-base64-string
(format nil "~A:~A"
(first proxy-basic-authorization)
(second proxy-basic-authorization)))))
(when accept
(write-header "Accept" "~A" accept))
(when range
(write-header "Range" "bytes=~A-~A" (first range) (second range)))
(when cookie-jar
;; write all cookies in one fell swoop, so even Sun's
;; web server has a chance to get it
(when-let (cookies (loop for cookie in (cookie-jar-cookies cookie-jar)
when (send-cookie-p cookie uri force-ssl)
collect (cookie-name cookie) and
collect (cookie-value cookie)))
(write-header "Cookie" "~{~A=~A~^; ~}" cookies)))
(when keep-alive
(write-header "Connection" "Keep-Alive"))
(when close
(setq must-close close)
(write-header "Connection" "close"))
(loop for (name . value) in additional-headers
do (write-header name "~A"
(cond ((or (functionp value)
(and (symbolp value)
(fboundp value)))
(funcall value))
(t value))))
(when content
(when content-type
(write-header "Content-Type" "~A" content-type))
(when (or (and (not content-length-provided-p)
(stringp content))
(and content-length
(not (or (and (integerp content-length)
(not (minusp content-length)))
(typep content '(or (vector octet) list))
(eq content :continuation)))))
;; CONTENT-LENGTH forces us to compute request body
;; in RAM
(setq content
(with-output-to-sequence (bin-out)
(let ((out (make-flexi-stream bin-out :external-format +latin-1+)))
(send-content content out external-format-out)))))
(when (and (or (not content-length-provided-p)
(eq content-length t))
(typep content '(or (vector octet) list)))
(setq content-length (length content)))
(cond (content-length
(write-header "Content-Length" "~D" content-length))
(t
(write-header "Transfer-Encoding" "chunked"))))
;; end of request headers
(when *header-stream*
(terpri *header-stream*))
(format http-stream "~C~C" #\Return #\Linefeed)
(force-output http-stream)
(when (and content (null content-length))
(setf (chunked-stream-output-chunking-p
(flexi-stream-stream http-stream)) t))
(labels ((finish-request (content &optional continuep)
(send-content content http-stream external-format-out)
(when continuep
(force-output http-stream)
(return-from finish-request))
(setf (chunked-stream-output-chunking-p
(flexi-stream-stream http-stream)) nil)
(finish-output http-stream)
(with-character-stream-semantics
(multiple-value-bind (server-protocol status-code status-text)
;; loop until status is NOT 100
(loop for (server-protocol status-code status-text)
= (read-status-line http-stream *header-stream*)
when (= status-code 100)
;; ignore headers sent until non-100 status is seen
do (read-http-headers http-stream *header-stream*)
until (/= status-code 100)
finally (return (values server-protocol status-code status-text)))
(let ((headers (read-http-headers http-stream *header-stream*))
body external-format-body)
(let ((connections (header-value :connection headers)))
(when connections
(setq connections (split-tokens connections)))
(when (or (member "close" connections :test #'string-equal)
(not (or (and (eq protocol :http/1.1)
(eq server-protocol :http/1.1))
(member "Keep-Alive" connections
:test #'string-equal))))
(setq must-close t)))
(when cookie-jar
(update-cookies (get-cookies headers uri) cookie-jar))
(when (and redirect
(member status-code +redirect-codes+)
(header-value :location headers))
(unless (or (eq redirect t)
(and (integerp redirect)
(plusp redirect)))
(cerror "Continue anyway."
'drakma-simple-error
:format-control "Status code was ~A, but ~
~:[REDIRECT is ~S~;redirection limit has been exceeded~]."
:format-arguments (list status-code (integerp redirect) redirect)))
(when auto-referer
(setq additional-headers (set-referer uri additional-headers)))
(let* ((location (header-value :location headers))
(new-uri (puri:merge-uris location uri))
;; can we re-use the stream?
(old-server-p (and (string= (puri:uri-host new-uri)
(puri:uri-host uri))
(eql (puri:uri-port new-uri)
(puri:uri-port uri))
(eq (puri:uri-scheme new-uri)
(puri:uri-scheme uri)))))
(unless old-server-p
(setq must-close t
want-stream nil))
;; try to re-use the stream, but only
;; if the user hasn't opted for a
;; connection which is always secure
(let ((re-use-stream (and old-server-p
(not must-close)
(not force-ssl))))
;; close stream if we can't re-use it
(unless re-use-stream
(ignore-errors (close http-stream)))
(setq done t)
(return-from http-request
(let ((method (if (and (member status-code +redirect-to-get-codes+)
(member method +redirect-to-get-methods+))
:get
method)))
(apply #'http-request new-uri
:method method
:redirect (cond ((integerp redirect) (1- redirect))
(t redirect))
:stream (and re-use-stream http-stream)
:additional-headers additional-headers
:parameters parameters
:preserve-uri t
:form-data (if (eq method :get)
nil
form-data)
args))))))
(let ((transfer-encodings (header-value :transfer-encoding headers)))
(when transfer-encodings
(setq transfer-encodings (split-tokens transfer-encodings)))
(when (member "chunked" transfer-encodings :test #'equalp)
(setf (chunked-stream-input-chunking-p
(flexi-stream-stream http-stream)) t)))
(when (setq external-format-body
(and (not force-binary)
(funcall *body-format-function*
headers external-format-in)))
(setf (flexi-stream-external-format http-stream)
external-format-body))
(when force-binary
(setf (flexi-stream-element-type http-stream) 'octet))
(unless (or want-stream (eq method :head))
(let (trailers)
(multiple-value-setq (body trailers)
(read-body http-stream headers external-format-body))
(when trailers
(drakma-warn "Adding trailers from chunked encoding to HTTP headers.")
(setq headers (nconc headers trailers)))))
(setq done t)
(values (cond (want-stream http-stream)
(t body))
status-code
headers
uri
http-stream
must-close
status-text))))))
(when (eq content :continuation)
(return-from http-request #'finish-request))
(finish-request content)))))
;; the cleanup form of the UNWIND-PROTECT above
(when (and http-stream
(or (not done)
(and must-close
(not want-stream)))
(not (eq content :continuation)))
(ignore-errors (close http-stream)))))))
)