-
-
Notifications
You must be signed in to change notification settings - Fork 41
/
usocket.lisp
811 lines (780 loc) · 39.7 KB
/
usocket.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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
(in-package :cl-user)
(defpackage dexador.backend.usocket
(:nicknames :dex.usocket)
(:use :cl
:dexador.restarts
:dexador.encoding
:dexador.util)
(:import-from :dexador.connection-cache
:steal-connection
:push-connection)
(:import-from :dexador.decoding-stream
:make-decoding-stream)
(:import-from :dexador.keep-alive-stream
:make-keep-alive-stream)
(:import-from :dexador.body
#:with-content-caches
#:decompress-body
#:decode-body
#:write-multipart-content
#:content-length
#:multipart-content-length
#:multipart-value-content-type)
(:import-from :dexador.error
:http-request-failed
:http-request-not-found
:socks5-proxy-request-failed)
(:import-from :usocket
:socket-connect
:socket-stream)
(:import-from :fast-http
:make-http-response
:make-parser
:http-status
:http-headers)
(:import-from :fast-io
:make-output-buffer
:finish-output-buffer
:with-fast-output
:fast-write-sequence
:fast-write-byte)
(:import-from :chunga
:chunked-stream-input-chunking-p
:chunked-stream-output-chunking-p
:make-chunked-stream)
(:import-from :trivial-mimes
:mime)
(:import-from :cl-cookie
:merge-cookies
:parse-set-cookie-header
:cookie-jar-host-cookies
:write-cookie-header)
(:import-from :quri
:uri-p
:uri-host
:uri-port
:uri-path
:uri-authority
:uri-scheme
:url-encode
:url-encode-params
:merge-uris)
(:import-from :cl-base64
:string-to-base64-string)
#-dexador-no-ssl
(:import-from :cl+ssl
:with-global-context
:make-context
:make-ssl-client-stream
:ensure-initialized
:ssl-check-verify-p)
(:import-from :alexandria
:copy-stream
:if-let
:when-let
:ensure-list
:ends-with-subseq)
(:import-from :uiop)
(:export :request
:*ca-bundle*))
(in-package :dexador.backend.usocket)
(defparameter *ca-bundle* nil)
(defun-speedy read-until-crlf*2 (stream)
(with-fast-output (buf)
(tagbody
read-cr
(loop for byte of-type (or (unsigned-byte 8) null) = (read-byte stream nil nil)
if byte
do (fast-write-byte byte buf)
else
do (go eof)
until (= byte (char-code #\Return)))
read-lf
(let ((next-byte (read-byte stream nil nil)))
(unless next-byte
(go eof))
(locally (declare (type (unsigned-byte 8) next-byte))
(cond
((= next-byte (char-code #\Newline))
(fast-write-byte next-byte buf)
(go read-cr2))
((= next-byte (char-code #\Return))
(fast-write-byte next-byte buf)
(go read-lf))
(T
(fast-write-byte next-byte buf)
(go read-cr)))))
read-cr2
(let ((next-byte (read-byte stream nil nil)))
(unless next-byte
(go eof))
(locally (declare (type (unsigned-byte 8) next-byte))
(cond
((= next-byte (char-code #\Return))
(fast-write-byte next-byte buf)
(go read-lf2))
(T
(fast-write-byte next-byte buf)
(go read-cr)))))
read-lf2
(let ((next-byte (read-byte stream nil nil)))
(unless next-byte
(go eof))
(locally (declare (type (unsigned-byte 8) next-byte))
(cond
((= next-byte (char-code #\Newline))
(fast-write-byte next-byte buf))
((= next-byte (char-code #\Return))
(fast-write-byte next-byte buf)
(go read-lf))
(T
(fast-write-byte next-byte buf)
(go read-cr)))))
eof)))
(defvar +empty-body+
(make-array 0 :element-type '(unsigned-byte 8)))
(defun read-response (stream has-body collect-headers read-body)
(let* ((http (make-http-response))
body
body-data
(headers-data (and collect-headers
(make-output-buffer)))
(header-finished-p nil)
(finishedp nil)
(content-length nil)
(transfer-encoding-p)
(parser (make-parser http
:header-callback
(lambda (headers)
(setq header-finished-p t
content-length (gethash "content-length" headers)
transfer-encoding-p (gethash "transfer-encoding" headers))
(unless (and has-body
(or content-length
transfer-encoding-p))
(setq finishedp t)))
:body-callback
(lambda (data start end)
(when body-data
(fast-write-sequence data body-data start end)))
:finish-callback
(lambda ()
(setq finishedp t)))))
(let ((buf (read-until-crlf*2 stream)))
(declare (type octets buf))
(when collect-headers
(fast-write-sequence buf headers-data))
(funcall parser buf))
(unless header-finished-p
(error "maybe invalid header"))
(cond
((not read-body)
(setq body stream))
((not has-body)
(setq body +empty-body+))
((and content-length (not transfer-encoding-p))
(let ((buf (make-array (etypecase content-length
(integer content-length)
(string (parse-integer content-length)))
:element-type '(unsigned-byte 8))))
(read-sequence buf stream)
(setq body buf)))
((let ((status (http-status http)))
(or (= status 100) ;; Continue
(= status 101) ;; Switching Protocols
(= status 204) ;; No Content
(= status 304))) ;; Not Modified
(setq body +empty-body+))
(T
(setq body-data (make-output-buffer))
(loop for buf of-type octets = (read-until-crlf*2 stream)
do (funcall parser buf)
until (or finishedp
(zerop (length buf)))
finally
(setq body (finish-output-buffer body-data)))))
(values http
body
(and collect-headers
(finish-output-buffer headers-data))
transfer-encoding-p)))
(defun print-verbose-data (direction &rest data)
(flet ((boundary-line ()
(let ((char (ecase direction
(:incoming #\<)
(:outgoing #\>))))
(fresh-line)
(dotimes (i 50)
(write-char char))
(fresh-line))))
(boundary-line)
(dolist (d data)
(map nil (lambda (byte)
(princ (code-char byte)))
d))
(boundary-line)))
(defun convert-body (body content-encoding content-type content-length chunkedp force-binary force-string keep-alive-p on-close)
(when (streamp body)
(cond
((and keep-alive-p chunkedp)
(setf body (make-keep-alive-stream body :chunked-stream
(let ((chunked-stream (chunga:make-chunked-stream body)))
(setf (chunga:chunked-stream-input-chunking-p chunked-stream) t)
chunked-stream) :on-close-or-eof on-close)))
((and keep-alive-p content-length)
(setf body (make-keep-alive-stream body :end content-length :on-close-or-eof on-close)))
(chunkedp
(let ((chunked-stream (chunga:make-chunked-stream body)))
(setf (chunga:chunked-stream-input-chunking-p chunked-stream) t)
(setf body chunked-stream)))))
(let ((body (decompress-body content-encoding body)))
(if force-binary
body
(decode-body content-type body
:default-charset (if force-string
babel:*default-character-encoding*
nil)))))
(defun content-disposition (key val)
(if (pathnamep val)
(let* ((filename (file-namestring val))
(utf8-filename-p (find-if (lambda (char)
(< 127 (char-code char)))
filename)))
(format nil "Content-Disposition: form-data; name=\"~A\"; ~:[filename=\"~A\"~;filename*=UTF-8''~A~]~C~C"
key
utf8-filename-p
(if utf8-filename-p
(url-encode filename :encoding :utf-8)
filename)
#\Return #\Newline))
(format nil "Content-Disposition: form-data; name=\"~A\"~C~C"
key
#\Return #\Newline)))
(defun build-cookie-headers (uri cookie-jar)
(with-header-output (buffer)
(let ((cookies (cookie-jar-host-cookies cookie-jar (uri-host uri) (or (uri-path uri) "/")
:securep (string= (uri-scheme uri) "https"))))
(when cookies
(fast-write-sequence (ascii-string-to-octets "Cookie: ") buffer)
(fast-write-sequence
(ascii-string-to-octets (write-cookie-header cookies))
buffer)
(fast-write-sequence +crlf+ buffer)))))
(defun make-connect-stream (uri version stream &optional proxy-auth)
(let ((header (with-fast-output (buffer)
(write-connect-header uri version buffer proxy-auth))))
(write-sequence header stream)
(force-output stream)
(read-until-crlf*2 stream)
stream))
(defun make-proxy-authorization (uri)
(let ((proxy-auth (quri:uri-userinfo uri)))
(when proxy-auth
(format nil "Basic ~A"
(string-to-base64-string proxy-auth)))))
(defconstant +socks5-version+ 5)
(defconstant +socks5-reserved+ 0)
(defconstant +socks5-no-auth+ 0)
(defconstant +socks5-connect+ 1)
(defconstant +socks5-domainname+ 3)
(defconstant +socks5-succeeded+ 0)
(defconstant +socks5-ipv4+ 1)
(defconstant +socks5-ipv6+ 4)
(defun ensure-socks5-connected (input output uri http-method)
(labels ((fail (condition &key reason)
(error (make-condition condition
:body nil :status nil :headers nil
:uri uri
:method http-method
:reason reason)))
(exact (n reason)
(unless (eql n (read-byte input nil 'eof))
(fail 'dexador.error:socks5-proxy-request-failed :reason reason)))
(drop (n reason)
(dotimes (i n)
(when (eq (read-byte input nil 'eof) 'eof)
(fail 'dexador.error:socks5-proxy-request-failed :reason reason)))))
;; Send Version + Auth Method
;; Currently, only supports no-auth method.
(write-byte +socks5-version+ output)
(write-byte 1 output)
(write-byte +socks5-no-auth+ output)
(finish-output output)
;; Receive Auth Method
(exact +socks5-version+ "Unexpected version")
(exact +socks5-no-auth+ "Unsupported auth method")
;; Send domainname Request
(let* ((host (babel:string-to-octets (uri-host uri)))
(hostlen (length host))
(port (uri-port uri)))
(unless (<= 1 hostlen 255)
(fail 'dexador.error:socks5-proxy-request-failed :reason "domainname too long"))
(unless (<= 1 port 65535)
(fail 'dexador.error:socks5-proxy-request-failed :reason "Invalid port"))
(write-byte +socks5-version+ output)
(write-byte +socks5-connect+ output)
(write-byte +socks5-reserved+ output)
(write-byte +socks5-domainname+ output)
(write-byte hostlen output)
(write-sequence host output)
(write-byte (ldb (byte 8 8) port) output)
(write-byte (ldb (byte 8 0) port) output)
(finish-output output)
;; Receive reply
(exact +socks5-version+ "Unexpected version")
(exact +socks5-succeeded+ "Unexpected result code")
(drop 1 "Should be reserved byte")
(let ((atyp (read-byte input nil 'eof)))
(cond
((eql atyp +socks5-ipv4+)
(drop 6 "Should be IPv4 address and port"))
((eql atyp +socks5-ipv6+)
(drop 18 "Should be IPv6 address and port"))
((eql atyp +socks5-domainname+)
(let ((n (read-byte input nil 'eof)))
(when (eq n 'eof)
(fail 'dexador.error:socks5-proxy-request-failed :reason "Invalid domainname length"))
(drop n "Should be domainname and port")))
(t
(fail 'dexador.error:socks5-proxy-request-failed :reason "Unknown address")))))))
(defun make-ssl-stream (stream ca-path ssl-key-file ssl-cert-file ssl-key-password hostname insecure)
#+dexador-no-ssl
(error "SSL not supported. Remove :dexador-no-ssl from *features* to enable SSL.")
#-dexador-no-ssl
(progn
(cl+ssl:ensure-initialized)
(let ((ctx (cl+ssl:make-context :verify-mode
(if insecure
cl+ssl:+ssl-verify-none+
cl+ssl:+ssl-verify-peer+)
:verify-location
(cond
(ca-path (uiop:native-namestring ca-path))
((and *ca-bundle* (probe-file *ca-bundle*)) *ca-bundle*)
;; In executable environment, perhaps *ca-bundle* doesn't exist.
(t :default))))
(ssl-cert-pem-p (and ssl-cert-file
(ends-with-subseq ".pem" ssl-cert-file))))
(cl+ssl:with-global-context (ctx :auto-free-p t)
(when ssl-cert-pem-p
(cl+ssl:use-certificate-chain-file ssl-cert-file))
(cl+ssl:make-ssl-client-stream stream
:hostname hostname
:verify (not insecure)
:key ssl-key-file
:certificate (and (not ssl-cert-pem-p)
ssl-cert-file)
:password ssl-key-password)))))
(defstruct usocket-wrapped-stream
stream)
;; Forward methods the user might want to use on this.
;; User is not meant to interact with this object except
;; potentially to close it when they decide they don't
;; need the :keep-alive connection anymore.
(defmethod close ((u usocket-wrapped-stream) &key abort)
(close (usocket-wrapped-stream-stream u) :abort abort))
(defmethod open-stream-p ((u usocket-wrapped-stream))
(open-stream-p (usocket-wrapped-stream-stream u)))
(defun-careful request (uri &rest args
&key (method :get) (version 1.1)
content headers
basic-auth bearer-auth
cookie-jar
(connect-timeout *default-connect-timeout*) (read-timeout *default-read-timeout*)
(keep-alive t) (use-connection-pool t)
(max-redirects 5)
ssl-key-file ssl-cert-file ssl-key-password
stream (verbose *verbose*)
force-binary
force-string
want-stream
(proxy *default-proxy*)
(insecure *not-verify-ssl*)
ca-path
&aux
(proxy-uri (and proxy (quri:uri proxy)))
(original-user-supplied-stream stream)
(user-supplied-stream (if (usocket-wrapped-stream-p stream) (usocket-wrapped-stream-stream stream) stream)))
(declare (ignorable ssl-key-file ssl-cert-file ssl-key-password
connect-timeout ca-path)
(type real version)
(type fixnum max-redirects))
(with-content-caches
(labels ((make-new-connection (uri)
(restart-case
(let* ((con-uri (quri:uri (or proxy uri)))
(connection (usocket:socket-connect (uri-host con-uri)
(uri-port con-uri)
#-(or ecl clasp clisp allegro) :timeout #-(or ecl clasp clisp allegro) connect-timeout
:element-type '(unsigned-byte 8)))
(stream
(usocket:socket-stream connection))
(scheme (uri-scheme uri)))
(declare (type string scheme))
(when read-timeout
#+lispworks(setf (stream:stream-read-timeout stream) read-timeout)
#-lispworks(setf (usocket:socket-option connection :receive-timeout) read-timeout))
(when (socks5-proxy-p proxy-uri)
(ensure-socks5-connected stream stream uri method))
(if (string= scheme "https")
(make-ssl-stream (if (http-proxy-p proxy-uri)
(make-connect-stream uri version stream (make-proxy-authorization con-uri))
stream) ca-path ssl-key-file ssl-cert-file ssl-key-password (uri-host uri) insecure)
stream))
(retry-request ()
:report "Retry the same request."
(return-from request
(apply #'request uri :use-connection-pool nil args)))
(retry-insecure ()
:report "Retry the same request without checking for SSL certificate validity."
(return-from request
(apply #'request uri :use-connection-pool nil :insecure t args)))))
(http-proxy-p (uri)
(and uri
(let ((scheme (uri-scheme uri)))
(and (stringp scheme)
(or (string= scheme "http")
(string= scheme "https"))))))
(socks5-proxy-p (uri)
(and uri
(let ((scheme (uri-scheme uri)))
(and (stringp scheme)
(string= scheme "socks5")))))
(connection-keep-alive-p (connection-header)
(and keep-alive
(or (and (= (the real version) 1.0)
(equalp connection-header "keep-alive"))
(not (equalp connection-header "close")))))
(return-stream-to-pool (stream uri)
(push-connection (format nil "~A://~A"
(uri-scheme uri)
(uri-authority uri)) stream #'close))
(return-stream-to-pool-or-close (stream connection-header uri)
(if (and (not user-supplied-stream) use-connection-pool (connection-keep-alive-p connection-header))
(return-stream-to-pool stream uri)
(when (open-stream-p stream)
(close stream))))
(finalize-connection (stream connection-header uri)
"If KEEP-ALIVE is in the connection-header and the user is not requesting a stream,
we will push the connection to our connection pool if allowed, otherwise we return
the stream back to the user who must close it."
(unless want-stream
(cond
((and use-connection-pool (connection-keep-alive-p connection-header) (not user-supplied-stream))
(return-stream-to-pool stream uri))
((not (connection-keep-alive-p connection-header))
(when (open-stream-p stream)
(close stream)))))))
(let* ((uri (quri:uri uri))
(proxy (when (http-proxy-p proxy-uri) proxy))
(content-type (cdr (find :content-type headers :key #'car :test #'string-equal)))
(multipart-p (or (and content-type
(>= (length content-type) 10)
(string= content-type "multipart/" :end1 10))
(and (not content-type)
(consp content)
(find-if #'pathnamep content :key #'cdr))))
(form-urlencoded-p (or (string= content-type "application/x-www-form-urlencoded")
(and (not content-type)
(consp content)
(not multipart-p))))
(boundary (and multipart-p
(make-random-string 12)))
(content (if (and form-urlencoded-p (not (stringp content))) ;; user can provide already encoded content, trust them.
(quri:url-encode-params content)
content))
(stream (or user-supplied-stream
(and use-connection-pool
(steal-connection (format nil "~A://~A"
(uri-scheme uri)
(uri-authority uri))))))
(reusing-stream-p (not (null stream))) ;; user provided or from connection-pool
(stream (or stream
(make-new-connection uri)))
(content-length
(assoc :content-length headers :test #'string-equal))
(transfer-encoding
(assoc :transfer-encoding headers :test #'string-equal))
(chunkedp (or (and transfer-encoding
(equalp (cdr transfer-encoding) "chunked"))
(and content-length
(null (cdr content-length)))))
(first-line-data
(with-fast-output (buffer)
(write-first-line method uri version buffer)))
(headers-data
(flet ((write-header* (name value)
(let ((header (assoc name headers :test #'string-equal)))
(if header
(when (cdr header)
(write-header name (cdr header)))
(write-header name value)))
(values)))
(with-header-output (buffer)
(write-header* :user-agent #.*default-user-agent*)
(write-header* :host (uri-authority uri))
(write-header* :accept "*/*")
(cond
((and keep-alive
(= (the real version) 1.0))
(write-header* :connection "keep-alive"))
((and (not keep-alive)
(= (the real version) 1.1))
(write-header* :connection "close")))
(cond ((and bearer-auth basic-auth)
(error "You should only use one Authorization header."))
(basic-auth
(write-header* :authorization
(format nil "Basic ~A"
(string-to-base64-string
(format nil "~A:~A"
(car basic-auth)
(cdr basic-auth))))))
(bearer-auth
(write-header* :authorization
(format nil "Bearer ~A" bearer-auth))))
(when proxy
(let ((scheme (quri:uri-scheme uri)))
(when (string= scheme "http")
(let* ((uri (quri:uri proxy))
(proxy-authorization (make-proxy-authorization uri)))
(when proxy-authorization
(write-header* :proxy-authorization proxy-authorization))))))
(cond
(multipart-p
(write-header :content-type (format nil "~A; boundary=~A"
(or content-type "multipart/form-data")
boundary))
(unless chunkedp
(write-header :content-length
(multipart-content-length content boundary))))
(form-urlencoded-p
(write-header* :content-type "application/x-www-form-urlencoded")
(unless chunkedp
(write-header* :content-length (length (the string content)))))
(t
(etypecase content
(null
(unless chunkedp
(write-header* :content-length 0)))
(string
(write-header* :content-type (or content-type "text/plain"))
(unless chunkedp
(write-header* :content-length (content-length content))))
((array (unsigned-byte 8) *)
(write-header* :content-type (or content-type "text/plain"))
(unless chunkedp
(write-header* :content-length (length content))))
(pathname
(write-header* :content-type (or content-type (dexador.body:content-type content)))
(unless chunkedp
(write-header :content-length
(or (cdr (assoc :content-length headers :test #'string-equal))
(content-length content))))))))
;; Transfer-Encoding: chunked
(when (and chunkedp
(not transfer-encoding))
(write-header* :transfer-encoding "chunked"))
;; Custom headers
(loop for (name . value) in headers
unless (member name '(:user-agent :host :accept
:connection
:content-type :content-length) :test #'string-equal)
do (write-header name value)))))
(cookie-headers (and cookie-jar
(build-cookie-headers uri cookie-jar))))
(macrolet ((maybe-try-again-without-reusing-stream (&optional (force nil))
`(progn ;; retrying by go retry avoids generating the header, parsing, etc.
(when (open-stream-p stream)
(close stream :abort t)
(setf stream nil))
(when ,(or force 'reusing-stream-p)
(setf reusing-stream-p nil
user-supplied-stream nil
stream (make-new-connection uri))
(go retry))))
(try-again-without-reusing-stream ()
`(maybe-try-again-without-reusing-stream t))
(with-retrying (&body body)
`(restart-case
(handler-bind (((and error
;; We should not retry errors received from the server.
;; Only technical errors such as disconnection or some
;; problems with the protocol should be retried automatically.
;; This solves https://github.com/fukamachi/dexador/issues/137 issue.
(not http-request-failed))
(lambda (e)
(declare (ignorable e))
(maybe-try-again-without-reusing-stream))))
,@body)
(retry-request () :report "Retry the same request."
(return-from request (apply #'request uri args)))
(ignore-and-continue () :report "Ignore the error and continue."))))
(tagbody
retry
(unless (open-stream-p stream)
(try-again-without-reusing-stream))
(with-retrying
(write-sequence first-line-data stream)
(write-sequence headers-data stream)
(when cookie-headers
(write-sequence cookie-headers stream))
(write-sequence +crlf+ stream)
(force-output stream))
;; Sending the content
(when content
(let ((encoding-stream (if chunkedp
(chunga:make-chunked-stream stream)
stream)))
(when chunkedp
(setf (chunga:chunked-stream-output-chunking-p encoding-stream) t))
(with-retrying
(if (consp content)
(dexador.body:write-multipart-content content boundary encoding-stream)
(dexador.body:write-as-octets encoding-stream content))
(when chunkedp
(setf (chunga:chunked-stream-output-chunking-p encoding-stream) nil))
(finish-output encoding-stream))))
start-reading
(multiple-value-bind (http body response-headers-data transfer-encoding-p)
(with-retrying
(read-response stream (not (eq method :head)) verbose (not want-stream)))
(let* ((status (http-status http))
(response-headers (http-headers http))
(content-length (gethash "content-length" response-headers))
(content-length (etypecase content-length
(null content-length)
(string (parse-integer content-length))
(integer content-length))))
(when (= status 0)
(with-retrying
(http-request-failed status
:body body
:headers headers
:uri uri
:method method)))
(when verbose
(print-verbose-data :outgoing first-line-data headers-data cookie-headers +crlf+)
(print-verbose-data :incoming response-headers-data))
(when cookie-jar
(when-let (set-cookies (append (gethash "set-cookie" response-headers)
(ensure-list (gethash "set-cookie2" response-headers))))
(merge-cookies cookie-jar
(remove nil (mapcar (lambda (cookie)
(declare (type string cookie))
(unless (= (length cookie) 0)
(parse-set-cookie-header cookie
(uri-host uri)
(uri-path uri))))
set-cookies)))))
(when (and (member status '(301 302 303 307 308) :test #'=)
(gethash "location" response-headers)
(/= max-redirects 0))
;; Need to read the response body
(when (and want-stream
(not (eq method :head)))
(cond
((integerp content-length)
(dotimes (i content-length)
(loop until (read-byte body nil nil))))
(transfer-encoding-p
(read-until-crlf*2 body))))
(let* ((location-uri (quri:uri (gethash "location" response-headers)))
(same-server-p (or (null (uri-host location-uri))
(and (string= (uri-scheme location-uri)
(uri-scheme uri))
(string= (uri-host location-uri)
(uri-host uri))
(eql (uri-port location-uri)
(uri-port uri))))))
(if (and same-server-p
(or (= status 307) (= status 308)
(member method '(:get :head) :test #'eq)))
(progn ;; redirection to the same host
(setq uri (merge-uris location-uri uri))
(setq first-line-data
(with-fast-output (buffer)
(write-first-line method uri version buffer)))
(when cookie-jar
;; Rebuild cookie-headers.
(setq cookie-headers (build-cookie-headers uri cookie-jar)))
(decf max-redirects)
(if (equalp (gethash "connection" response-headers) "close")
(try-again-without-reusing-stream)
(progn
(setq reusing-stream-p t)
(go retry))))
(progn ;; this is a redirection to a different host
(setf location-uri (quri:merge-uris location-uri uri))
;; Close connection if it isn't from our connection pool or from the user and we aren't going to
;; pass it to our new call.
(when (not same-server-p) (return-stream-to-pool-or-close stream (gethash "connection" response-headers) uri))
(setf (getf args :headers)
(nconc `((:host . ,(uri-host location-uri))) headers))
(setf (getf args :max-redirects)
(1- max-redirects))
;; Redirect as GET if it's 301, 302, 303
(unless (or (= status 307) (= status 308)
(member method '(:get :head) :test #'eq))
(setf (getf args :method) :get))
(return-from request
(apply #'request location-uri (if same-server-p
args
(progn (remf args :stream) args))))))))
(unwind-protect
(let* ((keep-connection-alive (connection-keep-alive-p
(gethash "connection" response-headers)))
(body (convert-body body
(gethash "content-encoding" response-headers)
(gethash "content-type" response-headers)
content-length
transfer-encoding-p
force-binary
force-string
keep-connection-alive
(if (and use-connection-pool keep-connection-alive (not user-supplied-stream) (streamp body))
(lambda (underlying-stream abort)
(declare (ignore abort))
(when (and underlying-stream (open-stream-p underlying-stream))
;; read any left overs the user may have not read (in case of errors on user side?)
(loop while (ignore-errors (listen underlying-stream)) ;; ssl streams may close
do (read-byte underlying-stream nil nil))
(when (open-stream-p underlying-stream)
(push-connection (format nil "~A://~A"
(uri-scheme uri)
(uri-authority uri)) underlying-stream #'close))))
#'dexador.keep-alive-stream:keep-alive-stream-close-underlying-stream))))
;; Raise an error when the HTTP response status code is 4xx or 50x.
(when (<= 400 status)
(with-retrying
(http-request-failed status
:body body
:headers response-headers
:uri uri
:method method)))
;; Have to be a little careful with the fifth value stream we return --
;; the user may be not aware that keep-alive t without use-connection-pool can leak
;; sockets, so we wrap the returned last value so when it is garbage
;; collected it gets closed. If the user is getting a stream back as BODY,
;; then we instead add a finalizer to that stream to close it when garbage collected
(return-from request
(values body
status
response-headers
uri
(when (and keep-alive
(not (equalp (gethash "connection" response-headers) "close"))
(or (not use-connection-pool) user-supplied-stream))
(or (and original-user-supplied-stream ;; user provided a stream
(if (usocket-wrapped-stream-p original-user-supplied-stream) ;; but, it came from us
(eql (usocket-wrapped-stream-stream original-user-supplied-stream) stream) ;; and we used it
(eql original-user-supplied-stream stream)) ;; user provided a bare stream
original-user-supplied-stream) ;; return what the user sent without wrapping it
(if want-stream ;; add a finalizer to the body to close the stream
(progn
(trivial-garbage:finalize body (lambda () (close stream)))
stream)
(let ((wrapped-stream (make-usocket-wrapped-stream :stream stream)))
(trivial-garbage:finalize wrapped-stream (lambda () (close stream)))
wrapped-stream)))))))
(finalize-connection stream (gethash "connection" response-headers) uri))))))))))