forked from franzinc/aserve
-
Notifications
You must be signed in to change notification settings - Fork 1
/
proxy.cl
2942 lines (2315 loc) · 85.7 KB
/
proxy.cl
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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;; -*- mode: common-lisp; package: net.aserve -*-
;;
;; proxy.cl
;;
;; See the file LICENSE for the full license governing this code.
;;
;;
;; Description:
;; aserve's proxy and proxy cache
;;- This code in this file obeys the Lisp Coding Standard found in
;;- http://www.franz.com/~jkf/coding_standards.html
;;-
(in-package :net.aserve)
(eval-when (compile) (declaim (optimize (speed 3))))
(check-smp-consistency)
(defmacro with-mp-locked-connection-cache ((s) &rest body)
(smp-case
((t :macros) `(with-locked-structure (,s :non-smp :without-scheduling)
,@body))
(nil `(si::without-scheduling ,s ,@body)))) ;; in a #-smp block
(defmacro with-mp-locked-pcache-ent ((s) &rest body)
(smp-case
((t :macros) `(with-locked-structure (,s :non-smp :without-scheduling)
,@body))
(nil `(si::without-scheduling ,s ,@body)))) ;; in a #-smp block
(defmacro with-fast-mp-locked-pcache-ent ((s) &rest body)
(smp-case
((t :macros) `(with-locked-structure (,s :non-smp :atomically)
,@body))
(nil `(excl::atomically ,s ,@body)))) ;; in a #-smp block
(defmacro with-mp-locked-pcache ((s) &rest body)
(smp-case
((t :macros) `(with-locked-structure (,s :non-smp :without-scheduling)
,@body))
(nil `(si::without-scheduling ,s ,@body)))) ;; in a #-smp block
(defmacro with-mp-locked-pcache-queue ((s) &rest body)
(smp-case
((t :macros) `(with-locked-structure (,s :non-smp :without-scheduling)
,@body))
(nil `(si::without-scheduling ,s ,@body)))) ;; in a #-smp block
; denotes a request from the browser
(defconstant *browser-level* 100) ;
(defparameter *extra-lifetime-factor* 1.1)
; number of seconds to add to expiration time of any entry in cache
(defparameter *extra-lifetime* 0)
; true if we are to save cached connections
(defparameter *connection-caching* t)
; statistics about connection caching
(defparameter *connections-cached* 0) ; number of connections put in to cache
(defparameter *connections-made* 0) ; number of make-socket calls made
(defparameter *connections-used-cached* 0) ; number of cached connections used
; the cache
(defparameter *connection-cache-queue* (cons nil nil)) ; (first . last) queue of conn-cache objects
(defparameter *connection-cache-expire* 10) ; number of seconds to live
(defparameter *connection-cache-lock*
(smp-case
((t :macros) (excl::make-basic-lock :name "connection-cache"))
(nil nil)))
; number of seconds we wait for a connect before we consider it timed
; out. Given the chance Linux seems to wait forever for a connection
; so we need to shut it down ourselves.
(defparameter *connection-timed-out-wait* 30)
(defstruct (pcache
#+smp-macros (:include synchronizing-structure)
)
;; proxy cache
table ; hash table mapping to pcache-ent objects
disk-caches ; list of pcache-disk items
cleaner ; process doing housecleaning
(cleaner-lock (mp:make-process-lock :name "cache cleaner"))
size ; specified size of the cache (in blocks)
high-water ; when blocks in cache gets above this start flushing to disk
low-water ; when blocks in cache get below this stop flushing
(dead-items 0) ; total number of objects on the dead-ent list
(level0-time 0) ; last time level0 access was done
queueobj ; queue object holding in-memory cache objects
dead-ent ; linked list of dead pcache-ents, linked by next field only
; hash table of handlers for uris, keyed by host
uri-info-table
; pointer to linkscan object if we are doing automatic link scanning
; in the proxy cache
linkscan
entry-cached-hook ; funcalled with pcache, pcache-ent and level
; requests that completely bypass the cache
(r-direct 0)
; ims or non-ims where there is no entry that mathes this url
; and the request headers
(r-miss 0)
; like r-miss except the level is greater than 0 thus this is a
; cache fill rather than a direct user request
(r-cache-fill 0)
; non-ims request. value within the min-freshness contstraints
; ims request where we know that the value in the cache is fresh
; and has been modified since the ims time
(r-fast-hit 0)
; non-ims request. value is stale but after checking with the
; origin server we find that our value is up to date
(r-slow-hit 0)
; ims request made and cached value is fresh and based on that
; we know that the client's version is fresh so send
; not-modified response back
(r-fast-validation 0)
; ims request where we return not-modified after checking with
; the origin server
(r-slow-validation 0)
; stale copy in the cache, we check with the origin server
; and find that our copy was inconsistent and get a new copy to cache
(r-consistency-miss 0)
)
(defstruct pcache-disk
;; for each disk file on which we are caching
filename
stream
blocks ; total blocks in cache
free-blocks ; number of blocks remaining
free-list ; list of (start . end) blocks that are free
high-water ; when free blocks is less than this start flushing
low-water ; when free blocks is more than this stop flushing
(lock (mp:make-process-lock :name "disk pcache"))
; doubly linked list of pcache-ents in this cache
queueobj
)
; each pcache entry holds the information on a 200 response
; use state
; --- ------
; >=0 nil in memory cache entry. linked to mru-ent
; >0 :dead in memory entry in use but which will no longer be used
; after the uses are over. linked to dead-ent
; nil :dead in memory entry which is ready to be reclaimed along
; with all the blocks it points to. linked to dead-ent
;
(defstruct (pcache-ent
#+smp-macros (:include synchronizing-structure)
)
key ; the string form of the uri
uri ; the actual uri
last-modified-string ; last modified time from the header
last-modified ; universal time entry was last modified
expires ; universal time when this entry expires
data ; data blocks (first is the response header block)
data-length ; number of octets of data
blocks ; number of cache blocks (length of the value in data slot)
code ; response code. 200 or 302
comment ; response comment
cookie ; the cookie if any with this request
; count of the internal use of this
use ; nil - dead entry. >= 0 - current users of this entry
(state :new) ; nil - normal ,
; :dead - trying to kill off,
; :new - filling the entry
;; scanned ; true when link scanning has been done
; number of times this entry was returned due to a request
(returned 0)
; if cached to the disk this tells where
disk-location
pcache-disk
loading-flag ; true when we are loading in from the disk
; linked list of pcache-ents
queueobj ; queue object we're stored in
prev
next
; scanning for links
; notes:
; links is initially nil and once the page has been scanned for links
; it is t or a list of uri objects
; or it is :scanning when then pcache-ent is in the to be link scanned
; level is non-zero when this entry is on the link-scan queue or
; uri-scan queue.
; scan-next is valid (nil or non-nil) when this entry is on the
; link-scan queue or uri-scan queue.
;
links ; nil or list of uris to img's then list of uris from a links
links-left ; list of uris still to scan
level ; level at which to scan these links
scan-next ; next pcache-ent to scan
(autoscan-time 0) ; univeral time when last scanned by the link scanner
)
(defstruct queueobj
(items 0) ; number of items in the queue (aside from dummy ones)
(bytes 0) ; number of data bytes cached
(blocks 0) ; number of buffer blocks
mru ; points to dummy pcache-ent at the head of the queue
lru ; points to dummy pcache-ent at the tail of the quee
)
(defstruct uri-info
;; information on how to handle a uri or set of uris
host ; string naming the host of the uri
(port 80)
path ; string in regexp form denoting the path. nil means all
path-regexp ; compiled regular expression for the path (or nil)
; nil or number of extra seconds of lifetime to add to uri
; nil means use systemwide default
extra-lifetime
; nil or default depth for link scanning
; nil means use systemwide default
scan-depth
exclude ; list of regexps for links to not scan
exclude-regexp ; compiled regexp versions of dont-follow
; called on links to determine at which level they should be followed
scan-function
; true if we should follow links to a site different than this page
offsite
)
(defclass locator-proxy (locator)
;; denotes sending the request to another machine
;;
())
(defclass proxy-control ()
;; used to control if proxy will operate or will send back a 500 error
(
;; nil or a location-authorizer object to do request location checking
(location :initarg :location :accessor proxy-control-location
:initform nil)
;; nil (meaning everything allowed)
;; or a non-empty list of hostname to which proxying is allowed, or a hash table of
;; hostnames to which proxying is allwoed
(destinations :initarg :destinations
:accessor proxy-control-destinations
:initform nil)
))
(defun enable-proxy (&key (server *wserver*)
proxy-proxy)
;;
(let ((locator-proxy-obj
(make-instance 'locator-proxy
:name :proxy
:extra (make-instance 'computed-entity
:function #'(lambda (req ent)
(if* (authorize-proxy-request
req ent (wserver-proxy-control server))
then (do-proxy-request req ent)
else (denied-request req)))
:extra (if* proxy-proxy
then (multiple-value-bind (host port)
(get-host-port proxy-proxy)
(if* (null host)
then (error "bad host port specification: ~s" proxy-proxy))
(cons host port)))
:will-handle-expect-continue t))))
; must be first as other locators may not ignore absolute proxy urls
(pushnew locator-proxy-obj (wserver-locators server))
))
(defmethod standard-locator ((req http-request) (locator locator-proxy))
;; see if this is a proxy request and if so return the entity that
;; denotes we're proxying
(if* (uri-scheme (request-raw-uri req))
then ; compute entity object
(locator-extra locator)))
(defmethod authorize-proxy-request ((req http-request) (ent entity) (proxy-control proxy-control))
;; return true iff this proxy request can be done
;;
; first check where request is from
(let ((location (proxy-control-location proxy-control)))
(if* location
then (if* (null (authorize location req ent))
then (return-from authorize-proxy-request nil))))
; and now where it's going
(let ((destinations (proxy-control-destinations proxy-control)))
(if* destinations
then (let ((hostname (net.uri:uri-host (request-raw-uri req)))
(port (net.uri:uri-port (request-raw-uri req))))
(if* (consp destinations)
then ; ("hostname" port1 port2 ...)
(dolist (dest destinations)
(if* (consp dest)
then (if* (and (equalp (car dest) hostname)
(member (or port 80)
(cdr dest)))
then (return t))
elseif (equalp dest hostname)
then (return t)))
elseif (hash-table-p destinations)
then (let ((ports (gethash hostname destinations)))
; ports is t (for all) or a list
; of valid ports
(or (eq ports t)
(and (consp ports)
(member (or port 80) ports))))))
else t ; ok by default
)))
(defmethod authorize-proxy-request ((req http-request) (ent entity) (no-proxy-control (eql nil)))
t)
(defun do-proxy-request (req ent)
;; a request has come in which has a uri with a scheme part,
;; thus denoting a request to be proxied (unless it's on our machine).
(let* ((uri (request-raw-uri req))
(scheme (uri-scheme uri))
(host (uri-host uri))
(port (or (uri-port uri) 80))
)
(if* (or (not (eq scheme :http))
(null host))
then (with-http-response (req ent :response *response-bad-request*)
(with-http-body (req ent)
(html (:html (:head (:title "Bad Request"))
(:body "This url isn't a valid proxy request "
(:princ-safe (net.uri:render-uri uri nil)))))))
else ; see if it's a local request
(let ((ipaddr (ignore-errors (socket:lookup-hostname host))))
(if* (null ipaddr)
then (with-http-response (req ent :response
*response-not-found*)
(with-http-body (req ent)
(html
(:html
(:head (:title "404 - Not Found"))
(:body
(:h1 "Host not found")
"The proxy failed to find the address for host "
(:b (:princ-safe host)))))))
(return-from do-proxy-request))
(if* (and ipaddr
(member ipaddr
(wserver-ipaddrs *wserver*))
(eq port
(socket:local-port (wserver-socket *wserver*)))
)
then ; it's us, make it into into a local request
; and look it up again
(setf (request-raw-uri req)
(net.uri:copy-uri uri :scheme nil :host nil))
(handle-request req)
else ; must really proxy
(check-cache-then-proxy-request
req ent t *browser-level*))))))
(defmethod unpublish-locator ((locator locator-proxy))
nil)
(defun proxy-request (req ent &key pcache-ent (respond t)
(level *browser-level*))
;; a request has come in with an http scheme given in uri
;; and a machine name which isn't ours.
;;
;; the headers have been parsed.
;;
;; send out the request
;; get the response and if respond is true send back the response
;;
(let* ((request-body (get-request-body req))
(outbuf (get-header-block))
(outend)
(clibuf)
(cliend)
(sock)
(uri (request-raw-uri req))
(host (uri-host uri))
(port (uri-port uri))
(method (request-method req))
(protocol :http/1.0)
(state :pre-send)
(keep-alive)
(cached-connection)
(phostport (and ent (entity-extra ent)))
(otherheaders))
(if* phostport
then ; we're proxying to a proxy. yikes
(setq host (car phostport)
port (cdr phostport)))
(unwind-protect
(tagbody
retry-proxy
(handler-bind ((error
#'(lambda (cond)
(logmess
(format nil "error during proxy: ~a ~% with ~
cached connection = ~s~%" cond cached-connection))
(if* cached-connection
then ; retry
(logmess "retry proxy")
(if* sock
then (ignore-errors
(close sock :abort t)))
(go retry-proxy))
(if* pcache-ent
then (kill-pcache-ent pcache-ent))
(if* (not (member :notrap *debug-current*
:test #'eq))
then ; we want to auto-handle the error
(if* (eq state :pre-send)
then ; haven't sent anything
; so send failed response
(ignore-errors
(proxy-failure-response req ent)))
(return-from proxy-request nil)))))
(setq keep-alive nil ; assume not keep alive
cached-connection nil)
; create outgoing headers by copying
(copy-headers (request-header-block req) outbuf
*header-client-array*)
;; now insert new headers
;; content-length is inserted if this is put or post method
;; and others if there is a body.
(if* (or (member method '(:put :post :patch) :test #'eq)
;; On PUT or POST we always send a content-length.
;; For other requests, send content-length if a body
;; was present. [rfe15456]
request-body)
then (insert-header outbuf :content-length
(format nil "~d"
(if* request-body
then (length request-body)
else 0))))
; connection we'll set to 'close' for now but at some point
; we'll connection caching so we'll want to do some keep-alive'ing
;
(insert-header outbuf :connection
(if* *connection-caching*
then "Keep-Alive"
else "close"))
;(logmess "outbuf now")
;(dump-header-block outbuf *initial-terminal-io*)
; send host header
(let ((host (or (request-header-host req)
(header-buffer-header-value
(request-header-block req) :host)
(if* port
then (format nil "~a:~d"
host port)
else host))))
(insert-header outbuf :host host))
; if the proxier decides to check authorization before
; doing a proxy then the authorization header will appear
; in the request-headers list and we want to prevent the
; authorization header from being sent twice in this case:
; [spr33532]
(dolist (header (request-headers req))
(if* (not (eq (car header) :authorization))
then (insert-non-standard-header outbuf (car header) (cdr header))))
(setq outend (add-trailing-crlf outbuf 1))
; time to make a call to the server
(handler-case
(multiple-value-setq (sock cached-connection)
(get-possibly-cached-connection
host (or port 80)))
(error (cond)
(declare (ignore cond))
(if* respond
then (with-http-response (req ent :response
*response-not-found*)
(with-http-body (req ent)
(html
(:html
(:head (:title "404 - Not Found"))
(:body
(:h1 "404 - Not Found")
"The proxy failed to connect to machine "
(:b (:princ-safe host))
" on port "
(:b (:princ-safe (or port 80)))))))))
(return-from proxy-request)))
(if* *watch-for-open-sockets*
then (schedule-finalization
sock
#'check-for-open-socket-before-gc))
;; there are bogus ip redirectors out there that want to
;; see the whole request in the packet. (e.g www.cbs.com)
;; so we build as much as we can and then blast that out
; this is written in this non-pretty way for speed
(let ((firstbuf (get-header-block))
(ind 0)
rest-of-headers-ind
(cmdstrings
'((:get . #.(make-array 3
:element-type '(unsigned-byte 8)
:initial-contents
(list
(char-int #\G)
(char-int #\E)
(char-int #\T))))
(:post . #.(make-array 4
:element-type '(unsigned-byte 8)
:initial-contents
(list
(char-int #\P)
(char-int #\O)
(char-int #\S)
(char-int #\T))))
))
(prot-strings
'((:http/1.0 . #.(make-array 8
:element-type '(unsigned-byte 8)
:initial-contents
(list
(char-int #\H)
(char-int #\T)
(char-int #\T)
(char-int #\P)
(char-int #\/)
(char-int #\1)
(char-int #\.)
(char-int #\0)
)))
(:http/1.1 . #.(make-array 8
:element-type '(unsigned-byte 8)
:initial-contents
(list
(char-int #\H)
(char-int #\T)
(char-int #\T)
(char-int #\P)
(char-int #\/)
(char-int #\1)
(char-int #\.)
(char-int #\1)
)))))
)
(let ((cmd (cdr (assoc method cmdstrings :test #'eq))))
; write method
(if* cmd
then (dotimes (i (length cmd))
(setf (ausb8 firstbuf i) (ausb8 cmd i)))
(incf ind (length cmd))
else ; unusual method, turn method into a string
(let ((str (string-upcase (string method))))
(dotimes (i (length str))
(setf (ausb8 firstbuf i)
(char-int (schar str i))))
(incf ind (length str))))
(setf (ausb8 firstbuf ind) #.(char-int #\space))
(incf ind)
; now the uri
(let ((str (if* phostport
then ; proxying so send http://...
(net.uri:render-uri (request-raw-uri req)
nil)
else (net.aserve.client::uri-path-etc uri))))
(dotimes (i (length str))
; should do string-to-octets...
(setf (ausb8 firstbuf ind)
(char-int (schar str i)))
(incf ind)))
(setf (ausb8 firstbuf ind) #.(char-int #\space))
(incf ind)
; now the protocol
(let ((cmd (cdr (assoc protocol prot-strings :test #'eq))))
(if* (null cmd)
then (error "can't proxy protocol ~s" protocol))
(dotimes (i (length cmd))
(setf (ausb8 firstbuf ind) (ausb8 cmd i))
(incf ind)))
(setf (ausb8 firstbuf ind) #.(char-int #\return))
(incf ind)
(setf (ausb8 firstbuf ind) #.(char-int #\linefeed))
(incf ind)
(debug-format :xmit-proxy-client-request-command "~s"
(octets-to-string firstbuf :end ind
:external-format :octets))
(setq rest-of-headers-ind ind)
; now add as much of the headers as we can
(do ((i 0 (1+ i))
(tocopy (min (- (length firstbuf) ind) outend)))
((>= i tocopy)
(maybe-accumulate-log (:xmit-proxy-client-request-headers "~s")
(debug-format :xmit-proxy-client-request-headers "~a"
(octets-to-string firstbuf
:start rest-of-headers-ind
:end ind
:external-format :octets))
(write-sequence firstbuf sock :end ind)
(if* (< i outend)
then ; still more from original buffer left
(debug-format :xmit-proxy-client-request-headers "~a"
(octets-to-string
outbuf :start i :end outend
:external-format :octets))
(write-sequence outbuf sock
:start i
:end outend)))
)
(setf (ausb8 firstbuf ind) (ausb8 outbuf i))
(incf ind))
(free-header-block firstbuf)))
; now the body if any
(if* request-body
then (debug-format :xmit-proxy-client-request-body "~s"
(octets-to-string request-body
:external-format :octets))
(write-sequence request-body sock))
(force-output sock)
; a shutdown would make sense here but it seems to confuse
; the aol servers
;(socket:shutdown sock :direction :output)
(let (protocol response comment header-start given-content-length
body-buffers body-length)
(loop
; loop until we don't get a 100 continue
;
; now read the response and the following headers
(setq outend (read-headers-into-buffer sock outbuf))
(debug-format :xmit-proxy-client-response-headers "~s"
(octets-to-string outbuf :end outend
:external-format :octets))
(if* (null outend)
then ; response coming back was truncated
(error "truncated proxy response"))
(multiple-value-setq (protocol response comment header-start)
(parse-response-buffer outbuf))
(if* (null protocol)
then ; bogus response
(return-from proxy-request
(proxy-failure-response req ent)))
(if* (not (eql response 100)) then (return)))
(setf (request-reply-code req)
(code-to-response response)) ; for the logging
(setq otherheaders
(parse-header-block outbuf header-start outend))
; Get the body of the message if any.
; there is never a response to a :head request although the header
; fields may imply there is.
; These response codes don't have a message body:
; 1xx, 204, 304
; All other responses include a message body which may be of zero size
;
(if* (setq given-content-length
(header-buffer-header-value outbuf :content-length))
then (setq given-content-length
(net.aserve.client::quick-convert-to-integer
given-content-length)))
(if* (not (or (eq (request-method req) :head)
(<= 100 response 199)
(eq response 204)
(eq response 304)))
then ; got to read the body
(multiple-value-setq (body-buffers body-length)
(read-into-block-buffers sock
given-content-length))
(if* (and given-content-length
(not (eql body-length given-content-length)))
then (warn "content-length ~s but body length ~d"
given-content-length body-length))
(setq given-content-length body-length))
(setf (request-reply-content-length req)
(or body-length given-content-length 0))
(setq keep-alive
(equalp (header-buffer-header-value outbuf :connection)
"keep-alive"))
(if* keep-alive
then (add-to-connection-cache sock
host
(or port 80))
else (close sock))
(setq sock nil)
; convert the header we received from the server into one
; to send to the client
(setq clibuf (get-sresource *header-block-sresource*))
(copy-headers outbuf clibuf *header-server-array*)
; add content-length if known
(if* given-content-length
then (insert-header clibuf :content-length
(format nil "~s" given-content-length)))
; should add a 'via' line
; transfer-encoding -
; we won't chunk back since we know the content length
(dolist (header otherheaders)
(insert-non-standard-header clibuf (car header) (cdr header)))
(setq cliend (add-trailing-crlf clibuf 2))
; do the response
(setq state :post-send)
(if* respond
then (ignore-errors
(let ((rsock (request-socket req)))
(debug-format
:xmit-proxy-server-response-headers
"~s"
(concatenate 'string
(format nil "HTTP/1.1 ~d ~a~a" response
(and comment (octets-to-string comment)) *crlf*)
(octets-to-string clibuf :end cliend
:external-format :octets)))
(format rsock "HTTP/1.1 ~d ~a~a" response (and comment (octets-to-string comment)) *crlf*)
(write-sequence clibuf rsock :end cliend)
(if* body-length
then (write-body-buffers rsock body-buffers
body-length))
(force-output rsock))))
(if* (and pcache-ent
(eq (request-method req) :get))
then ; we are caching
(let ((tmp-clibuf clibuf)
(tmp-body-buffers body-buffers))
(setf clibuf nil
body-buffers nil)
(cache-response req pcache-ent
response comment tmp-clibuf
tmp-body-buffers body-length level)
; these buffers have been saved in the cache
; so nil them out so they aren't freed
))
(dolist (block body-buffers) (free-header-block block))
)))
;; cleanup forms
(if* sock
then (ignore-errors (force-output sock))
(ignore-errors (close sock :abort t)))
(free-header-block outbuf)
(free-header-block clibuf))))
(defun parse-response-buffer (buff)
;; the buffer should contain the first line of an http respose
;; and a response code, a crlf and then headers (but not including
;; the crlf after the headers)
;;
(let (protocol response-code comment beginc)
(flet ((match (array list)
; test if the list of bytes matches the prefix of the array
(do ((i 0 (1+ i))
(ll list (cdr ll)))
((null ll) t)
(if* (not (eq (aref array i) (car ll)))
then (return nil)))))
;;
(if* (match buff '(#.(char-int #\H)
#.(char-int #\T)
#.(char-int #\T)
#.(char-int #\P)
#.(char-int #\/)
#.(char-int #\1)
#.(char-int #\.)))
then (case (aref buff 7)
(#.(char-int #\0) (setq protocol :http/1.0))
(#.(char-int #\1) (setq protocol :http/1.1)))
(if* (null protocol)
then (return-from parse-response-buffer nil)))
; compute response code
(let ((val 0)
(i 8))
(loop
(let ((chv (aref buff i)))
(if* (<= #.(char-code #\0) chv #.(char-code #\9))
then (setq val (+ (* val 10) (- chv #.(char-code #\0))))
elseif (member chv '(#.(char-code #\space)
#.(char-code #\return)
#.(char-code #\linefeed))
:test #'eq)
then (if* (not (zerop val))
then (return) ; whitespace after value, get out
)
else ; bogus response code
(return-from parse-response-buffer nil))
(incf i)))
(setq response-code val)
; search for begining of comment
(loop
(let ((chv (aref buff i)))
(if* (member chv '(#.(char-code #\return)
#.(char-code #\linefeed))
:test #'eq)
then ; end of line before seeing a comment
(return)
elseif (not (eq chv #.(char-code #\space)))
then ; beginning of comment
(setq beginc i)
(return))
(incf i)))
(if* beginc
then ; found beginning, search for end
(loop (let ((chv (aref buff i)))
(if* (member chv '(#.(char-code #\return)
#.(char-code #\linefeed))
:test #'eq)
then ; hit the end
(return))
(incf i))))
; we have what we need
(if* beginc
then (let ((str (make-array (- i beginc)
:element-type '(unsigned-byte 8))))
(do ((jj beginc (1+ jj))
(ii 0 (1+ ii)))
((>= jj i))
(setf (aref str ii)
(aref buff jj)))
(setq comment str)))
(values protocol response-code comment i)))))
(defun read-into-block-buffers (sock size)
;; read up to size bytes from sock into a sequnce of block
;; buffers.
;; if size is nil then read until end of file.
;; return a list of block buffers with all full except perhaps
;; the last one
;; return a second value which is the number of bytes read
(if* (eql size 0)
then (return-from read-into-block-buffers (values nil 0)))
(let (res block len bytesleft (bytesread 0) (start 0))