]> git.ipfire.org Git - thirdparty/squid.git/blob - src/http.cc
change 'sizeof sockaddr_in' to sizeof S' and make connect()
[thirdparty/squid.git] / src / http.cc
1
2 /*
3 * $Id: http.cc,v 1.452 2005/08/17 15:57:26 wessels Exp $
4 *
5 * DEBUG: section 11 Hypertext Transfer Protocol (HTTP)
6 * AUTHOR: Harvest Derived
7 *
8 * SQUID Web Proxy Cache http://www.squid-cache.org/
9 * ----------------------------------------------------------
10 *
11 * Squid is the result of efforts by numerous individuals from
12 * the Internet community; see the CONTRIBUTORS file for full
13 * details. Many organizations have provided support for Squid's
14 * development; see the SPONSORS file for full details. Squid is
15 * Copyrighted (C) 2001 by the Regents of the University of
16 * California; see the COPYRIGHT file for full details. Squid
17 * incorporates software developed and/or copyrighted by other
18 * sources; see the CREDITS file for full details.
19 *
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 2 of the License, or
23 * (at your option) any later version.
24 *
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
29 *
30 * You should have received a copy of the GNU General Public License
31 * along with this program; if not, write to the Free Software
32 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
33 *
34 */
35
36 /*
37 * Anonymizing patch by lutz@as-node.jena.thur.de
38 * have a look into http-anon.c to get more informations.
39 */
40
41 #include "squid.h"
42 #include "http.h"
43 #include "AuthUserRequest.h"
44 #include "Store.h"
45 #include "HttpReply.h"
46 #include "HttpRequest.h"
47 #include "MemObject.h"
48 #include "HttpHdrContRange.h"
49 #include "ACLChecklist.h"
50 #include "fde.h"
51 #if DELAY_POOLS
52 #include "DelayPools.h"
53 #endif
54
55 CBDATA_TYPE(HttpStateData);
56
57
58 static const char *const crlf = "\r\n";
59
60 static CWCB httpSendRequestEntity;
61
62 static IOCB httpReadReply;
63 static void httpSendRequest(HttpStateData *);
64 static PF httpStateFree;
65 static PF httpTimeout;
66 static void httpCacheNegatively(StoreEntry *);
67 static void httpMakePrivate(StoreEntry *);
68 static void httpMakePublic(StoreEntry *);
69 static void httpMaybeRemovePublic(StoreEntry *, http_status);
70 static void copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, String strConnection, HttpRequest * request, HttpRequest * orig_request,
71 HttpHeader * hdr_out, int we_do_ranges, http_state_flags);
72 static int decideIfWeDoRanges (HttpRequest * orig_request);
73
74
75 static void
76 httpStateFree(int fd, void *data)
77 {
78 HttpStateData *httpState = static_cast<HttpStateData *>(data);
79
80 if (httpState == NULL)
81 return;
82
83 if (httpState->body_buf) {
84 if (httpState->orig_request->body_connection.getRaw()) {
85 clientAbortBody(httpState->orig_request);
86 }
87
88 if (httpState->body_buf) {
89 memFree(httpState->body_buf, MEM_8K_BUF);
90 httpState->body_buf = NULL;
91 }
92 }
93
94 storeUnlockObject(httpState->entry);
95
96 if (!memBufIsNull(&httpState->reply_hdr)) {
97 memBufClean(&httpState->reply_hdr);
98 }
99
100 requestUnlink(httpState->request);
101 requestUnlink(httpState->orig_request);
102 httpState->request = NULL;
103 httpState->orig_request = NULL;
104 cbdataFree(httpState);
105 }
106
107 int
108 httpCachable(method_t method)
109 {
110 /* GET and HEAD are cachable. Others are not. */
111
112 if (method != METHOD_GET && method != METHOD_HEAD)
113 return 0;
114
115 /* else cachable */
116 return 1;
117 }
118
119 static void
120 httpTimeout(int fd, void *data)
121 {
122 HttpStateData *httpState = static_cast<HttpStateData *>(data);
123 StoreEntry *entry = httpState->entry;
124 debug(11, 4) ("httpTimeout: FD %d: '%s'\n", fd, storeUrl(entry));
125
126 if (entry->store_status == STORE_PENDING) {
127 if (entry->isEmpty()) {
128 fwdFail(httpState->fwd,
129 errorCon(ERR_READ_TIMEOUT, HTTP_GATEWAY_TIMEOUT));
130 }
131 }
132
133 comm_close(fd);
134 }
135
136 /* This object can be cached for a long time */
137 static void
138 httpMakePublic(StoreEntry * entry)
139 {
140 if (EBIT_TEST(entry->flags, ENTRY_CACHABLE))
141 storeSetPublicKey(entry);
142 }
143
144 /* This object should never be cached at all */
145 static void
146 httpMakePrivate(StoreEntry * entry)
147 {
148 storeExpireNow(entry);
149 storeReleaseRequest(entry); /* delete object when not used */
150 /* storeReleaseRequest clears ENTRY_CACHABLE flag */
151 }
152
153 /* This object may be negatively cached */
154 static void
155 httpCacheNegatively(StoreEntry * entry)
156 {
157 storeNegativeCache(entry);
158
159 if (EBIT_TEST(entry->flags, ENTRY_CACHABLE))
160 storeSetPublicKey(entry);
161 }
162
163 static void
164 httpMaybeRemovePublic(StoreEntry * e, http_status status)
165 {
166
167 int remove
168 = 0;
169
170 int forbidden = 0;
171
172 StoreEntry *pe;
173
174 if (!EBIT_TEST(e->flags, KEY_PRIVATE))
175 return;
176
177 switch (status) {
178
179 case HTTP_OK:
180
181 case HTTP_NON_AUTHORITATIVE_INFORMATION:
182
183 case HTTP_MULTIPLE_CHOICES:
184
185 case HTTP_MOVED_PERMANENTLY:
186
187 case HTTP_MOVED_TEMPORARILY:
188
189 case HTTP_GONE:
190
191 case HTTP_NOT_FOUND:
192
193 remove
194 = 1;
195
196 break;
197
198 case HTTP_FORBIDDEN:
199
200 case HTTP_METHOD_NOT_ALLOWED:
201 forbidden = 1;
202
203 break;
204
205 #if WORK_IN_PROGRESS
206
207 case HTTP_UNAUTHORIZED:
208 forbidden = 1;
209
210 break;
211
212 #endif
213
214 default:
215 #if QUESTIONABLE
216 /*
217 * Any 2xx response should eject previously cached entities...
218 */
219
220 if (status >= 200 && status < 300)
221 remove
222 = 1;
223
224 #endif
225
226 break;
227 }
228
229 if (!remove
230 && !forbidden)
231 return;
232
233 assert(e->mem_obj);
234
235 if (e->mem_obj->request)
236 pe = storeGetPublicByRequest(e->mem_obj->request);
237 else
238 pe = storeGetPublic(e->mem_obj->url, e->mem_obj->method);
239
240 if (pe != NULL) {
241 assert(e != pe);
242 storeRelease(pe);
243 }
244
245 /*
246 * Also remove any cached HEAD response in case the object has
247 * changed.
248 */
249 if (e->mem_obj->request)
250 pe = storeGetPublicByRequestMethod(e->mem_obj->request, METHOD_HEAD);
251 else
252 pe = storeGetPublic(e->mem_obj->url, METHOD_HEAD);
253
254 if (pe != NULL) {
255 assert(e != pe);
256 storeRelease(pe);
257 }
258
259 if (forbidden)
260 return;
261
262 switch (e->mem_obj->method) {
263
264 case METHOD_PUT:
265
266 case METHOD_DELETE:
267
268 case METHOD_PROPPATCH:
269
270 case METHOD_MKCOL:
271
272 case METHOD_MOVE:
273
274 case METHOD_BMOVE:
275
276 case METHOD_BDELETE:
277 /*
278 * Remove any cached GET object if it is beleived that the
279 * object may have changed as a result of other methods
280 */
281
282 if (e->mem_obj->request)
283 pe = storeGetPublicByRequestMethod(e->mem_obj->request, METHOD_GET);
284 else
285 pe = storeGetPublic(e->mem_obj->url, METHOD_GET);
286
287 if (pe != NULL) {
288 assert(e != pe);
289 storeRelease(pe);
290 }
291
292 break;
293
294 default:
295 /* Keep GCC happy. The methods above are all mutating HTTP methods
296 */
297 break;
298 }
299 }
300
301 void
302 HttpStateData::processSurrogateControl(HttpReply *reply)
303 {
304 #if ESI
305
306 if (request->flags.accelerated && reply->surrogate_control) {
307 HttpHdrScTarget *sctusable =
308 httpHdrScGetMergedTarget(reply->surrogate_control,
309 Config.Accel.surrogate_id);
310
311 if (sctusable) {
312 if (EBIT_TEST(sctusable->mask, SC_NO_STORE) ||
313 (Config.onoff.surrogate_is_remote
314 && EBIT_TEST(sctusable->mask, SC_NO_STORE_REMOTE))) {
315 surrogateNoStore = true;
316 httpMakePrivate(entry);
317 }
318
319 /* The HttpHeader logic cannot tell if the header it's parsing is a reply to an
320 * accelerated request or not...
321 * Still, this is an abtraction breach. - RC
322 */
323 if (sctusable->max_age != -1) {
324 if (sctusable->max_age < sctusable->max_stale)
325 reply->expires = reply->date + sctusable->max_age;
326 else
327 reply->expires = reply->date + sctusable->max_stale;
328
329 /* And update the timestamps */
330 storeTimestampsSet(entry);
331 }
332
333 /* We ignore cache-control directives as per the Surrogate specification */
334 ignoreCacheControl = true;
335
336 httpHdrScTargetDestroy(sctusable);
337 }
338 }
339
340 #endif
341 }
342
343 int
344 HttpStateData::cacheableReply()
345 {
346 HttpReply const *rep = entry->getReply();
347 HttpHeader const *hdr = &rep->header;
348 const int cc_mask = (rep->cache_control) ? rep->cache_control->mask : 0;
349 const char *v;
350 #if HTTP_VIOLATIONS
351
352 const refresh_t *R = NULL;
353 #endif
354
355 if (surrogateNoStore)
356 return 0;
357
358 if (!ignoreCacheControl) {
359 if (EBIT_TEST(cc_mask, CC_PRIVATE)) {
360 #if HTTP_VIOLATIONS
361
362 if (!R)
363 R = refreshLimits(entry->mem_obj->url);
364
365 if (R && !R->flags.ignore_private)
366 #endif
367
368 return 0;
369 }
370
371 if (EBIT_TEST(cc_mask, CC_NO_CACHE)) {
372 #if HTTP_VIOLATIONS
373
374 if (!R)
375 R = refreshLimits(entry->mem_obj->url);
376
377 if (R && !R->flags.ignore_no_cache)
378 #endif
379
380 return 0;
381 }
382
383 if (EBIT_TEST(cc_mask, CC_NO_STORE)) {
384 #if HTTP_VIOLATIONS
385
386 if (!R)
387 R = refreshLimits(entry->mem_obj->url);
388
389 if (R && !R->flags.ignore_no_store)
390 #endif
391
392 return 0;
393 }
394 }
395
396 if (request->flags.auth) {
397 /*
398 * Responses to requests with authorization may be cached
399 * only if a Cache-Control: public reply header is present.
400 * RFC 2068, sec 14.9.4
401 */
402
403 if (!EBIT_TEST(cc_mask, CC_PUBLIC)) {
404 #if HTTP_VIOLATIONS
405
406 if (!R)
407 R = refreshLimits(entry->mem_obj->url);
408
409 if (R && !R->flags.ignore_auth)
410 #endif
411
412 return 0;
413 }
414 }
415
416 /* Pragma: no-cache in _replies_ is not documented in HTTP,
417 * but servers like "Active Imaging Webcast/2.0" sure do use it */
418 if (httpHeaderHas(hdr, HDR_PRAGMA)) {
419 String s = httpHeaderGetList(hdr, HDR_PRAGMA);
420 const int no_cache = strListIsMember(&s, "no-cache", ',');
421 s.clean();
422
423 if (no_cache) {
424 #if HTTP_VIOLATIONS
425
426 if (!R)
427 R = refreshLimits(entry->mem_obj->url);
428
429 if (R && !R->flags.ignore_no_cache)
430 #endif
431
432 return 0;
433 }
434 }
435
436 /*
437 * The "multipart/x-mixed-replace" content type is used for
438 * continuous push replies. These are generally dynamic and
439 * probably should not be cachable
440 */
441 if ((v = httpHeaderGetStr(hdr, HDR_CONTENT_TYPE)))
442 if (!strncasecmp(v, "multipart/x-mixed-replace", 25))
443 return 0;
444
445 switch (entry->getReply()->sline.status) {
446 /* Responses that are cacheable */
447
448 case HTTP_OK:
449
450 case HTTP_NON_AUTHORITATIVE_INFORMATION:
451
452 case HTTP_MULTIPLE_CHOICES:
453
454 case HTTP_MOVED_PERMANENTLY:
455
456 case HTTP_GONE:
457 /*
458 * Don't cache objects that need to be refreshed on next request,
459 * unless we know how to refresh it.
460 */
461
462 if (!refreshIsCachable(entry))
463 return 0;
464
465 /* don't cache objects from peers w/o LMT, Date, or Expires */
466 /* check that is it enough to check headers @?@ */
467 if (rep->date > -1)
468 return 1;
469 else if (rep->last_modified > -1)
470 return 1;
471 else if (!_peer)
472 return 1;
473
474 /* @?@ (here and 302): invalid expires header compiles to squid_curtime */
475 else if (rep->expires > -1)
476 return 1;
477 else
478 return 0;
479
480 /* NOTREACHED */
481 break;
482
483 /* Responses that only are cacheable if the server says so */
484
485 case HTTP_MOVED_TEMPORARILY:
486 if (rep->expires > -1)
487 return 1;
488 else
489 return 0;
490
491 /* NOTREACHED */
492 break;
493
494 /* Errors can be negatively cached */
495
496 case HTTP_NO_CONTENT:
497
498 case HTTP_USE_PROXY:
499
500 case HTTP_BAD_REQUEST:
501
502 case HTTP_FORBIDDEN:
503
504 case HTTP_NOT_FOUND:
505
506 case HTTP_METHOD_NOT_ALLOWED:
507
508 case HTTP_REQUEST_URI_TOO_LARGE:
509
510 case HTTP_INTERNAL_SERVER_ERROR:
511
512 case HTTP_NOT_IMPLEMENTED:
513
514 case HTTP_BAD_GATEWAY:
515
516 case HTTP_SERVICE_UNAVAILABLE:
517
518 case HTTP_GATEWAY_TIMEOUT:
519 return -1;
520
521 /* NOTREACHED */
522 break;
523
524 /* Some responses can never be cached */
525
526 case HTTP_PARTIAL_CONTENT: /* Not yet supported */
527
528 case HTTP_SEE_OTHER:
529
530 case HTTP_NOT_MODIFIED:
531
532 case HTTP_UNAUTHORIZED:
533
534 case HTTP_PROXY_AUTHENTICATION_REQUIRED:
535
536 case HTTP_INVALID_HEADER: /* Squid header parsing error */
537
538 case HTTP_HEADER_TOO_LARGE:
539 return 0;
540
541 default: /* Unknown status code */
542 debug (11,0)("HttpStateData::cacheableReply: unknown http status code in reply\n");
543
544 return 0;
545
546 /* NOTREACHED */
547 break;
548 }
549
550 /* NOTREACHED */
551 }
552
553 /*
554 * For Vary, store the relevant request headers as
555 * virtual headers in the reply
556 * Returns false if the variance cannot be stored
557 */
558 const char *
559 httpMakeVaryMark(HttpRequest * request, HttpReply const * reply)
560 {
561 String vary, hdr;
562 const char *pos = NULL;
563 const char *item;
564 const char *value;
565 int ilen;
566 static String vstr;
567
568 vstr.clean();
569 vary = httpHeaderGetList(&reply->header, HDR_VARY);
570
571 while (strListGetItem(&vary, ',', &item, &ilen, &pos)) {
572 char *name = (char *)xmalloc(ilen + 1);
573 xstrncpy(name, item, ilen + 1);
574 Tolower(name);
575
576 if (strcmp(name, "*") == 0) {
577 /* Can not handle "Vary: *" withtout ETag support */
578 safe_free(name);
579 vstr.clean();
580 break;
581 }
582
583 strListAdd(&vstr, name, ',');
584 hdr = httpHeaderGetByName(&request->header, name);
585 safe_free(name);
586 value = hdr.buf();
587
588 if (value) {
589 value = rfc1738_escape_part(value);
590 vstr.append("=\"", 2);
591 vstr.append(value);
592 vstr.append("\"", 1);
593 }
594
595 hdr.clean();
596 }
597
598 vary.clean();
599 #if X_ACCELERATOR_VARY
600
601 pos = NULL;
602 vary = httpHeaderGetList(&reply->header, HDR_X_ACCELERATOR_VARY);
603
604 while (strListGetItem(&vary, ',', &item, &ilen, &pos)) {
605 char *name = (char *)xmalloc(ilen + 1);
606 xstrncpy(name, item, ilen + 1);
607 Tolower(name);
608 strListAdd(&vstr, name, ',');
609 hdr = httpHeaderGetByName(&request->header, name);
610 safe_free(name);
611 value = hdr.buf();
612
613 if (value) {
614 value = rfc1738_escape_part(value);
615 vstr.append("=\"", 2);
616 vstr.append(value);
617 vstr.append("\"", 1);
618 }
619
620 hdr.clean();
621 }
622
623 vary.clean();
624 #endif
625
626 debug(11, 3) ("httpMakeVaryMark: %s\n", vstr.buf());
627 return vstr.buf();
628 }
629
630 void
631 HttpStateData::failReply(HttpReply *reply, http_status const & status)
632 {
633 reply->sline.version = HttpVersion(1, 0);
634 reply->sline.status = status;
635 storeEntryReplaceObject (entry, reply);
636
637 if (eof == 1) {
638 fwdComplete(fwd);
639 comm_close(fd);
640 }
641 }
642
643 /* rewrite this later using new interfaces @?@
644 * This creates the error page itself.. its likely
645 * that the forward ported reply header max size patch
646 * generates non http conformant error pages - in which
647 * case the errors where should be 'BAD_GATEWAY' etc
648 */
649 void
650 HttpStateData::processReplyHeader(const char *buf, int size)
651 {
652 size_t hdr_len;
653 size_t hdr_size;
654 /* Creates a blank header. If this routine is made incremental, this will
655 * not do
656 */
657 HttpReply *reply = httpReplyCreate();
658 Ctx ctx = ctx_enter(entry->mem_obj->url);
659 debug(11, 3) ("httpProcessReplyHeader: key '%s'\n",
660 entry->getMD5Text());
661
662 if (memBufIsNull(&reply_hdr))
663 memBufDefInit(&reply_hdr);
664
665 assert(reply_hdr_state == 0);
666
667 memBufAppend(&reply_hdr, buf, size);
668
669 hdr_len = reply_hdr.size;
670
671 if (hdr_len > 4 && strncmp(reply_hdr.buf, "HTTP/", 5)) {
672 debugs(11, 3, "httpProcessReplyHeader: Non-HTTP-compliant header: '" << reply_hdr.buf << "'");
673 reply_hdr_state += 2;
674 memBufClean(&reply_hdr);
675 failReply (reply, HTTP_INVALID_HEADER);
676 ctx_exit(ctx);
677 return;
678 }
679
680 hdr_size = headersEnd(reply_hdr.buf, hdr_len);
681
682 if (hdr_size)
683 hdr_len = hdr_size;
684
685 if (hdr_len > Config.maxReplyHeaderSize) {
686 debugs(11, 1, "httpProcessReplyHeader: Too large reply header");
687
688 if (!memBufIsNull(&reply_hdr))
689 memBufClean(&reply_hdr);
690
691 failReply (reply, HTTP_HEADER_TOO_LARGE);
692
693 reply_hdr_state += 2;
694
695 ctx_exit(ctx);
696
697 return;
698 }
699
700 /* headers can be incomplete only if object still arriving */
701 if (!hdr_size) {
702 if (eof)
703 hdr_size = hdr_len;
704 else {
705 ctx_exit(ctx);
706 return; /* headers not complete */
707 }
708 }
709
710 /* Cut away any excess body data (only needed for debug?) */
711 memBufAppend(&reply_hdr, "\0", 1);
712
713 reply_hdr.buf[hdr_size] = '\0';
714
715 reply_hdr_state++;
716
717 assert(reply_hdr_state == 1);
718
719 reply_hdr_state++;
720
721 debug(11, 9) ("GOT HTTP REPLY HDR:\n---------\n%s\n----------\n",
722 reply_hdr.buf);
723
724 /* Parse headers into reply structure */
725 /* what happens if we fail to parse here? */
726 httpReplyParse(reply, reply_hdr.buf, hdr_size);
727
728 if (reply->sline.status >= HTTP_INVALID_HEADER) {
729 debugs(11, 3, "httpProcessReplyHeader: Non-HTTP-compliant header: '" << reply_hdr.buf << "'");
730 failReply (reply, HTTP_INVALID_HEADER);
731 ctx_exit(ctx);
732 return;
733 }
734
735 processSurrogateControl (reply);
736 /* TODO: we need our own reply * in the httpState, as we probably don't want to replace
737 * the storeEntry with interim headers
738 */
739
740 /* TODO: IF the reply is a 1.0 reply, AND it has a Connection: Header
741 * Parse the header and remove all referenced headers
742 */
743
744 storeEntryReplaceObject(entry, reply);
745 /* DO NOT USE reply now */
746 reply = NULL;
747
748 if (entry->getReply()->sline.status == HTTP_PARTIAL_CONTENT &&
749 entry->getReply()->content_range)
750 currentOffset = entry->getReply()->content_range->spec.offset;
751
752 storeTimestampsSet(entry);
753
754 /* Check if object is cacheable or not based on reply code */
755 debug(11, 3) ("httpProcessReplyHeader: HTTP CODE: %d\n", entry->getReply()->sline.status);
756
757 if (neighbors_do_private_keys)
758 httpMaybeRemovePublic(entry, entry->getReply()->sline.status);
759
760 if (httpHeaderHas(&entry->getReply()->header, HDR_VARY)
761 #if X_ACCELERATOR_VARY
762 || httpHeaderHas(&entry->getReply()->header, HDR_X_ACCELERATOR_VARY)
763 #endif
764 ) {
765 const char *vary = httpMakeVaryMark(orig_request, entry->getReply());
766
767 if (!vary) {
768 httpMakePrivate(entry);
769 goto no_cache;
770
771 }
772
773 entry->mem_obj->vary_headers = xstrdup(vary);
774 }
775
776 switch (cacheableReply()) {
777
778 case 1:
779 httpMakePublic(entry);
780 break;
781
782 case 0:
783 httpMakePrivate(entry);
784 break;
785
786 case -1:
787
788 if (Config.negativeTtl > 0)
789 httpCacheNegatively(entry);
790 else
791 httpMakePrivate(entry);
792
793 break;
794
795 default:
796 assert(0);
797
798 break;
799 }
800
801 no_cache:
802
803 if (!ignoreCacheControl && entry->getReply()->cache_control) {
804 if (EBIT_TEST(entry->getReply()->cache_control->mask, CC_PROXY_REVALIDATE))
805 EBIT_SET(entry->flags, ENTRY_REVALIDATE);
806 else if (EBIT_TEST(entry->getReply()->cache_control->mask, CC_MUST_REVALIDATE))
807 EBIT_SET(entry->flags, ENTRY_REVALIDATE);
808 }
809
810 if (flags.keepalive)
811 if (_peer)
812 _peer->stats.n_keepalives_sent++;
813
814 if (entry->getReply()->keep_alive) {
815 if (_peer)
816 _peer->stats.n_keepalives_recv++;
817
818 if (Config.onoff.detect_broken_server_pconns && httpReplyBodySize(request->method, reply) == -1) {
819 debug(11, 1) ("httpProcessReplyHeader: Impossible keep-alive header from '%s'\n", storeUrl(entry));
820 debug(11, 2) ("GOT HTTP REPLY HDR:\n---------\n%s\n----------\n", reply_hdr.buf);
821 flags.keepalive_broken = 1;
822 }
823 }
824
825 if (entry->getReply()->date > -1 && !_peer) {
826 int skew = abs((int)(entry->getReply()->date - squid_curtime));
827
828 if (skew > 86400)
829 debug(11, 3) ("%s's clock is skewed by %d seconds!\n",
830 request->host, skew);
831 }
832
833 ctx_exit(ctx);
834 #if HEADERS_LOG
835
836 headersLog(1, 0, request->method, entry->getReply());
837 #endif
838
839 if (eof == 1) {
840 fwdComplete(fwd);
841 comm_close(fd);
842 }
843 }
844
845 HttpStateData::ConnectionStatus
846 HttpStateData::statusIfComplete() const
847 {
848 HttpReply const *reply = entry->getReply();
849 /* If the reply wants to close the connection, it takes precedence */
850
851 if (httpHeaderHasConnDir(&reply->header, "close"))
852 return COMPLETE_NONPERSISTENT_MSG;
853
854 /* If we didn't send a keep-alive request header, then this
855 * can not be a persistent connection.
856 */
857 if (!flags.keepalive)
858 return COMPLETE_NONPERSISTENT_MSG;
859
860 /*
861 * If we haven't sent the whole request then this can not be a persistent
862 * connection.
863 */
864 if (!flags.request_sent) {
865 debug(11, 1) ("statusIfComplete: Request not yet fully sent \"%s %s\"\n",
866 RequestMethodStr[orig_request->method],
867 storeUrl(entry));
868 return COMPLETE_NONPERSISTENT_MSG;
869 }
870
871 /*
872 * What does the reply have to say about keep-alive?
873 */
874 /*
875 * XXX BUG?
876 * If the origin server (HTTP/1.0) does not send a keep-alive
877 * header, but keeps the connection open anyway, what happens?
878 * We'll return here and http.c waits for an EOF before changing
879 * store_status to STORE_OK. Combine this with ENTRY_FWD_HDR_WAIT
880 * and an error status code, and we might have to wait until
881 * the server times out the socket.
882 */
883 if (!reply->keep_alive)
884 return COMPLETE_NONPERSISTENT_MSG;
885
886 return COMPLETE_PERSISTENT_MSG;
887 }
888
889 HttpStateData::ConnectionStatus
890 HttpStateData::persistentConnStatus() const
891 {
892 HttpReply const *reply = entry->getReply();
893 int clen;
894 debug(11, 3) ("httpPconnTransferDone: FD %d\n", fd);
895 ConnectionStatus result = statusIfComplete();
896 debug(11, 5) ("httpPconnTransferDone: content_length=%d\n",
897 reply->content_length);
898 /* If we haven't seen the end of reply headers, we are not done */
899
900 if (reply_hdr_state < 2)
901 return INCOMPLETE_MSG;
902
903 clen = httpReplyBodySize(request->method, reply);
904
905 /* If there is no message body, we can be persistent */
906 if (0 == clen)
907 return result;
908
909 /* If the body size is unknown we must wait for EOF */
910 if (clen < 0)
911 return INCOMPLETE_MSG;
912
913 /* If the body size is known, we must wait until we've gotten all of it. */
914 if (entry->mem_obj->endOffset() < reply->content_length + reply->hdr_sz)
915 return INCOMPLETE_MSG;
916
917 /* We got it all */
918 return result;
919 }
920
921 static void
922 httpReadReply(int fd, char *buf, size_t len, comm_err_t flag, int xerrno,void *data)
923 {
924 HttpStateData *httpState = static_cast<HttpStateData *>(data);
925 assert (fd == httpState->fd);
926 PROF_start(HttpStateData_readReply);
927 httpState->readReply (fd, buf, len, flag, xerrno, data);
928 PROF_stop(HttpStateData_readReply);
929 }
930
931 /* This will be called when data is ready to be read from fd. Read until
932 * error or connection closed. */
933 /* XXX this function is too long! */
934 void
935 HttpStateData::readReply (int fd, char *readBuf, size_t len, comm_err_t flag, int xerrno,void *data)
936 {
937 int bin;
938 int clen;
939 do_next_read = 0;
940
941
942 assert(buf == readBuf);
943
944 /* Bail out early on COMM_ERR_CLOSING - close handlers will tidy up for us
945 */
946
947 if (flag == COMM_ERR_CLOSING) {
948 debug (11,3)("http socket closing\n");
949 return;
950 }
951
952 if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
953 maybeReadData();
954 return;
955 }
956
957 errno = 0;
958 /* prepare the read size for the next read (if any) */
959 #if DELAY_POOLS
960
961 DelayId delayId = entry->mem_obj->mostBytesAllowed();
962
963 #endif
964
965 debug(11, 5) ("httpReadReply: FD %d: len %d.\n", fd, (int)len);
966
967 if (flag == COMM_OK && len > 0) {
968 #if DELAY_POOLS
969 delayId.bytesIn(len);
970 #endif
971
972 kb_incr(&statCounter.server.all.kbytes_in, len);
973 kb_incr(&statCounter.server.http.kbytes_in, len);
974 IOStats.Http.reads++;
975
976 for (clen = len - 1, bin = 0; clen; bin++)
977 clen >>= 1;
978
979 IOStats.Http.read_hist[bin]++;
980 }
981
982 /* here the RFC says we should ignore whitespace between replies, but we can't as
983 * doing so breaks HTTP/0.9 replies beginning with witespace, and in addition
984 * the response splitting countermeasures is extremely likely to trigger on this,
985 * not allowing connection reuse in the first place.
986 */
987 #if DONT_DO_THIS
988 if (reply_hdr_state == 0 && flag == COMM_OK && len > 0 && fd_table[fd].uses > 1) {
989 /* Skip whitespace between replies */
990
991 while (len > 0 && isspace(*buf))
992 xmemmove(buf, buf + 1, len--);
993
994 if (len == 0) {
995 /* Continue to read... */
996 /* Timeout NOT increased. This whitespace was from previous reply */
997 do_next_read = 1;
998 maybeReadData();
999 return;
1000 }
1001 }
1002
1003 #endif
1004
1005 if (flag != COMM_OK || len < 0) {
1006 debug(50, 2) ("httpReadReply: FD %d: read failure: %s.\n",
1007 fd, xstrerror());
1008
1009 if (ignoreErrno(errno)) {
1010 do_next_read = 1;
1011 } else if (entry->isEmpty()) {
1012 ErrorState *err;
1013 err = errorCon(ERR_READ_ERROR, HTTP_BAD_GATEWAY);
1014 err->request = requestLink((HttpRequest *) request);
1015 err->xerrno = errno;
1016 fwdFail(fwd, err);
1017 do_next_read = 0;
1018 comm_close(fd);
1019 } else {
1020 do_next_read = 0;
1021 comm_close(fd);
1022 }
1023 } else if (flag == COMM_OK && len == 0 && entry->isEmpty()) {
1024 ErrorState *err;
1025 err = errorCon(ERR_ZERO_SIZE_OBJECT, HTTP_BAD_GATEWAY);
1026 err->xerrno = errno;
1027 err->request = requestLink((HttpRequest *) request);
1028 fwdFail(fwd, err);
1029 eof = 1;
1030 do_next_read = 0;
1031 comm_close(fd);
1032 } else if (flag == COMM_OK && len == 0) {
1033 /* Connection closed; retrieval done. */
1034 eof = 1;
1035
1036 if (reply_hdr_state < 2)
1037 /*
1038 * Yes Henrik, there is a point to doing this. When we
1039 * called httpProcessReplyHeader() before, we didn't find
1040 * the end of headers, but now we are definately at EOF, so
1041 * we want to process the reply headers.
1042 */
1043 /* doesn't return */
1044 processReplyHeader(buf, len);
1045 else if (entry->getReply()->sline.status == HTTP_INVALID_HEADER && HttpVersion(0,9) != entry->getReply()->sline.version) {
1046 ErrorState *err;
1047 err = errorCon(ERR_INVALID_RESP, HTTP_BAD_GATEWAY);
1048 err->request = requestLink((HttpRequest *) request);
1049 fwdFail(fwd, err);
1050 do_next_read = 0;
1051 } else {
1052 if (entry->mem_obj->getReply()->sline.status == HTTP_HEADER_TOO_LARGE) {
1053 ErrorState *err;
1054 storeEntryReset(entry);
1055 err = errorCon(ERR_TOO_BIG, HTTP_BAD_GATEWAY);
1056 err->request = requestLink((HttpRequest *) request);
1057 fwdFail(fwd, err);
1058 fwd->flags.dont_retry = 1;
1059 } else {
1060 fwdComplete(fwd);
1061 }
1062
1063 do_next_read = 0;
1064 comm_close(fd);
1065 }
1066 } else {
1067 if (reply_hdr_state < 2) {
1068 processReplyHeader(buf, len);
1069
1070 if (reply_hdr_state == 2) {
1071 http_status s = entry->getReply()->sline.status;
1072 HttpVersion httpver = entry->getReply()->sline.version;
1073
1074 if (s == HTTP_INVALID_HEADER && httpver != HttpVersion(0,9)) {
1075 ErrorState *err;
1076 storeEntryReset(entry);
1077 err = errorCon(ERR_INVALID_RESP, HTTP_BAD_GATEWAY);
1078 err->request = requestLink((HttpRequest *) request);
1079 fwdFail(fwd, err);
1080 comm_close(fd);
1081 return;
1082 }
1083
1084 #if WIP_FWD_LOG
1085
1086 fwdStatus(fwd, s);
1087
1088 #endif
1089 /*
1090 * If its not a reply that we will re-forward, then
1091 * allow the client to get it.
1092 */
1093
1094 if (!fwdReforwardableStatus(s))
1095 EBIT_CLR(entry->flags, ENTRY_FWD_HDR_WAIT);
1096 }
1097 }
1098
1099 PROF_start(HttpStateData_processReplyData);
1100 processReplyData(buf, len);
1101 PROF_stop(HttpStateData_processReplyData);
1102 }
1103 }
1104
1105 void
1106 HttpStateData::processReplyData(const char *buf, size_t len)
1107 {
1108 if (reply_hdr_state < 2) {
1109 do_next_read = 1;
1110 maybeReadData();
1111 return;
1112 }
1113
1114 StoreIOBuffer tempBuffer;
1115
1116 if (!flags.headers_pushed) {
1117 /* The first block needs us to skip the headers */
1118 /* TODO: make this cleaner. WE should push the headers, NOT the parser */
1119 size_t end = headersEnd (buf, len);
1120 /* IF len > end, we need to append data after the
1121 * out of band update to the store
1122 */
1123
1124 if (len > end) {
1125 tempBuffer.data = (char *)buf+end;
1126 tempBuffer.length = len - end;
1127 tempBuffer.offset = currentOffset;
1128 currentOffset += tempBuffer.length;
1129 entry->write (tempBuffer);
1130 }
1131
1132 flags.headers_pushed = 1;
1133 } else {
1134 tempBuffer.data = (char *)buf;
1135 tempBuffer.length = len;
1136 tempBuffer.offset = currentOffset;
1137 currentOffset += len;
1138 entry->write(tempBuffer);
1139 }
1140
1141 if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
1142 /*
1143 * the above storeAppend() call could ABORT this entry,
1144 * in that case, the server FD should already be closed.
1145 * there's nothing for us to do.
1146 */
1147 (void) 0;
1148 } else
1149 switch (persistentConnStatus()) {
1150
1151 case INCOMPLETE_MSG:
1152 /* Wait for more data or EOF condition */
1153
1154 if (flags.keepalive_broken) {
1155 commSetTimeout(fd, 10, NULL, NULL);
1156 } else {
1157 commSetTimeout(fd, Config.Timeout.read, NULL, NULL);
1158 }
1159
1160 do_next_read = 1;
1161 break;
1162
1163 case COMPLETE_PERSISTENT_MSG:
1164 /* yes we have to clear all these! */
1165 commSetTimeout(fd, -1, NULL, NULL);
1166 do_next_read = 0;
1167
1168 comm_remove_close_handler(fd, httpStateFree, this);
1169 fwdUnregister(fd, fwd);
1170
1171 if (_peer) {
1172 if (_peer->options.originserver)
1173 pconnPush(fd, _peer->name, orig_request->port, orig_request->host);
1174 else
1175 pconnPush(fd, _peer->name, _peer->http_port, NULL);
1176 } else {
1177 pconnPush(fd, request->host, request->port, NULL);
1178 }
1179
1180 fwdComplete(fwd);
1181 fd = -1;
1182 httpStateFree(fd, this);
1183 return;
1184
1185 case COMPLETE_NONPERSISTENT_MSG:
1186 /* close the connection ourselves */
1187 /* yes - same as for a complete persistent conn here */
1188 commSetTimeout(fd, -1, NULL, NULL);
1189 commSetSelect(fd, COMM_SELECT_READ, NULL, NULL, 0);
1190 comm_remove_close_handler(fd, httpStateFree, this);
1191 fwdUnregister(fd, fwd);
1192 fwdComplete(fwd);
1193 /* TODO: check that fd is still open here */
1194 comm_close (fd);
1195 fd = -1;
1196 httpStateFree(fd, this);
1197 return;
1198 }
1199
1200 maybeReadData();
1201 }
1202
1203 void
1204 HttpStateData::maybeReadData()
1205 {
1206 if (do_next_read) {
1207 do_next_read = 0;
1208 entry->delayAwareRead(fd, buf, SQUID_TCP_SO_RCVBUF, httpReadReply, this);
1209 }
1210 }
1211
1212 /* This will be called when request write is complete. Schedule read of
1213 * reply. */
1214 void
1215 HttpStateData::SendComplete(int fd, char *bufnotused, size_t size, comm_err_t errflag, void *data)
1216 {
1217 HttpStateData *httpState = static_cast<HttpStateData *>(data);
1218 StoreEntry *entry = httpState->entry;
1219 ErrorState *err;
1220 debug(11, 5) ("httpSendComplete: FD %d: size %d: errflag %d.\n",
1221 fd, (int) size, errflag);
1222 #if URL_CHECKSUM_DEBUG
1223
1224 entry->mem_obj->checkUrlChecksum();
1225 #endif
1226
1227 if (size > 0) {
1228 fd_bytes(fd, size, FD_WRITE);
1229 kb_incr(&statCounter.server.all.kbytes_out, size);
1230 kb_incr(&statCounter.server.http.kbytes_out, size);
1231 }
1232
1233 if (errflag == COMM_ERR_CLOSING)
1234 return;
1235
1236 if (errflag) {
1237 err = errorCon(ERR_WRITE_ERROR, HTTP_BAD_GATEWAY);
1238 err->xerrno = errno;
1239 err->request = requestLink(httpState->orig_request);
1240 errorAppendEntry(entry, err);
1241 comm_close(fd);
1242 return;
1243 } else {
1244 /*
1245 * Set the read timeout here because it hasn't been set yet.
1246 * We only set the read timeout after the request has been
1247 * fully written to the server-side. If we start the timeout
1248 * after connection establishment, then we are likely to hit
1249 * the timeout for POST/PUT requests that have very large
1250 * request bodies.
1251 */
1252 commSetTimeout(fd, Config.Timeout.read, httpTimeout, httpState);
1253 }
1254
1255 httpState->flags.request_sent = 1;
1256 }
1257
1258 /*
1259 * build request headers and append them to a given MemBuf
1260 * used by httpBuildRequestPrefix()
1261 * note: initialised the HttpHeader, the caller is responsible for Clean()-ing
1262 */
1263 void
1264 httpBuildRequestHeader(HttpRequest * request,
1265 HttpRequest * orig_request,
1266 StoreEntry * entry,
1267 HttpHeader * hdr_out,
1268 http_state_flags flags)
1269 {
1270 /* building buffer for complex strings */
1271 #define BBUF_SZ (MAX_URL+32)
1272 LOCAL_ARRAY(char, bbuf, BBUF_SZ);
1273 const HttpHeader *hdr_in = &orig_request->header;
1274 const HttpHeaderEntry *e;
1275 String strFwd;
1276 HttpHeaderPos pos = HttpHeaderInitPos;
1277 assert (hdr_out->owner == hoRequest);
1278 /* append our IMS header */
1279
1280 if (request->lastmod > -1 && request->method == METHOD_GET)
1281 httpHeaderPutTime(hdr_out, HDR_IF_MODIFIED_SINCE, request->lastmod);
1282
1283 bool we_do_ranges = decideIfWeDoRanges (orig_request);
1284
1285 String strConnection (httpHeaderGetList(hdr_in, HDR_CONNECTION));
1286
1287 while ((e = httpHeaderGetEntry(hdr_in, &pos)))
1288 copyOneHeaderFromClientsideRequestToUpstreamRequest(e, strConnection, request, orig_request, hdr_out, we_do_ranges, flags);
1289
1290 /* Abstraction break: We should interpret multipart/byterange responses
1291 * into offset-length data, and this works around our inability to do so.
1292 */
1293 if (!we_do_ranges && orig_request->multipartRangeRequest()) {
1294 /* don't cache the result */
1295 orig_request->flags.cachable = 0;
1296 /* pretend it's not a range request */
1297 delete orig_request->range;
1298 orig_request->range = NULL;
1299 orig_request->flags.range = 0;
1300 }
1301
1302
1303 /* append Via */
1304 if (Config.onoff.via) {
1305 String strVia;
1306 strVia = httpHeaderGetList(hdr_in, HDR_VIA);
1307 snprintf(bbuf, BBUF_SZ, "%d.%d %s",
1308 orig_request->http_ver.major,
1309 orig_request->http_ver.minor, ThisCache);
1310 strListAdd(&strVia, bbuf, ',');
1311 httpHeaderPutStr(hdr_out, HDR_VIA, strVia.buf());
1312 strVia.clean();
1313 }
1314
1315 #if ESI
1316 {
1317 /* Append Surrogate-Capabilities */
1318 String strSurrogate (httpHeaderGetList(hdr_in, HDR_SURROGATE_CAPABILITY));
1319 snprintf(bbuf, BBUF_SZ, "%s=\"Surrogate/1.0 ESI/1.0\"",
1320 Config.Accel.surrogate_id);
1321 strListAdd(&strSurrogate, bbuf, ',');
1322 httpHeaderPutStr(hdr_out, HDR_SURROGATE_CAPABILITY, strSurrogate.buf());
1323 }
1324 #endif
1325
1326 /* append X-Forwarded-For */
1327 strFwd = httpHeaderGetList(hdr_in, HDR_X_FORWARDED_FOR);
1328
1329 if (opt_forwarded_for && orig_request->client_addr.s_addr != no_addr.s_addr)
1330 strListAdd(&strFwd, inet_ntoa(orig_request->client_addr), ',');
1331 else
1332 strListAdd(&strFwd, "unknown", ',');
1333
1334 httpHeaderPutStr(hdr_out, HDR_X_FORWARDED_FOR, strFwd.buf());
1335
1336 strFwd.clean();
1337
1338 /* append Host if not there already */
1339 if (!httpHeaderHas(hdr_out, HDR_HOST)) {
1340 if (orig_request->peer_domain) {
1341 httpHeaderPutStr(hdr_out, HDR_HOST, orig_request->peer_domain);
1342 } else if (orig_request->port == urlDefaultPort(orig_request->protocol)) {
1343 /* use port# only if not default */
1344 httpHeaderPutStr(hdr_out, HDR_HOST, orig_request->host);
1345 } else {
1346 httpHeaderPutStrf(hdr_out, HDR_HOST, "%s:%d",
1347 orig_request->host, (int) orig_request->port);
1348 }
1349 }
1350
1351 /* append Authorization if known in URL, not in header and going direct */
1352 if (!httpHeaderHas(hdr_out, HDR_AUTHORIZATION)) {
1353 if (!request->flags.proxying && *request->login) {
1354 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1355 base64_encode(request->login));
1356 }
1357 }
1358
1359 /* append Proxy-Authorization if configured for peer, and proxying */
1360 if (request->flags.proxying && orig_request->peer_login &&
1361 !httpHeaderHas(hdr_out, HDR_PROXY_AUTHORIZATION)) {
1362 if (*orig_request->peer_login == '*') {
1363 /* Special mode, to pass the username to the upstream cache */
1364 char loginbuf[256];
1365 const char *username = "-";
1366
1367 if (orig_request->auth_user_request)
1368 username = orig_request->auth_user_request->username();
1369 else if (orig_request->extacl_user.size())
1370 username = orig_request->extacl_user.buf();
1371
1372 snprintf(loginbuf, sizeof(loginbuf), "%s%s", username, orig_request->peer_login + 1);
1373
1374 httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Basic %s",
1375 base64_encode(loginbuf));
1376 } else if (strcmp(orig_request->peer_login, "PASS") == 0) {
1377 if (orig_request->extacl_user.size() && orig_request->extacl_passwd.size()) {
1378 char loginbuf[256];
1379 snprintf(loginbuf, sizeof(loginbuf), "%s:%s", orig_request->extacl_user.buf(), orig_request->extacl_passwd.buf());
1380 httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Basic %s",
1381 base64_encode(loginbuf));
1382 }
1383 } else if (strcmp(orig_request->peer_login, "PROXYPASS") == 0) {
1384 /* Nothing to do */
1385 } else {
1386 httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Basic %s",
1387 base64_encode(orig_request->peer_login));
1388 }
1389 }
1390
1391 /* append WWW-Authorization if configured for peer */
1392 if (flags.originpeer && orig_request->peer_login &&
1393 !httpHeaderHas(hdr_out, HDR_AUTHORIZATION)) {
1394 if (strcmp(orig_request->peer_login, "PASS") == 0) {
1395 /* No credentials to forward.. (should have been done above if available) */
1396 } else if (strcmp(orig_request->peer_login, "PROXYPASS") == 0) {
1397 /* Special mode, convert proxy authentication to WWW authentication
1398 * (also applies to authentication provided by external acl)
1399 */
1400 const char *auth = httpHeaderGetStr(hdr_in, HDR_PROXY_AUTHORIZATION);
1401
1402 if (auth && strncasecmp(auth, "basic ", 6) == 0) {
1403 httpHeaderPutStr(hdr_out, HDR_AUTHORIZATION, auth);
1404 } else if (orig_request->extacl_user.size() && orig_request->extacl_passwd.size()) {
1405 char loginbuf[256];
1406 snprintf(loginbuf, sizeof(loginbuf), "%s:%s", orig_request->extacl_user.buf(), orig_request->extacl_passwd.buf());
1407 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1408 base64_encode(loginbuf));
1409 }
1410 } else if (*orig_request->peer_login == '*') {
1411 /* Special mode, to pass the username to the upstream cache */
1412 char loginbuf[256];
1413 const char *username = "-";
1414
1415 if (orig_request->auth_user_request)
1416 username = orig_request->auth_user_request->username();
1417 else if (orig_request->extacl_user.size())
1418 username = orig_request->extacl_user.buf();
1419
1420 snprintf(loginbuf, sizeof(loginbuf), "%s%s", username, orig_request->peer_login + 1);
1421
1422 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1423 base64_encode(loginbuf));
1424 } else {
1425 /* Fixed login string */
1426 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1427 base64_encode(orig_request->peer_login));
1428 }
1429 }
1430
1431 /* append Cache-Control, add max-age if not there already */ {
1432 HttpHdrCc *cc = httpHeaderGetCc(hdr_in);
1433
1434 if (!cc)
1435 cc = httpHdrCcCreate();
1436
1437 if (!EBIT_TEST(cc->mask, CC_MAX_AGE)) {
1438 const char *url =
1439 entry ? storeUrl(entry) : urlCanonical(orig_request);
1440 httpHdrCcSetMaxAge(cc, getMaxAge(url));
1441
1442 if (request->urlpath.size())
1443 assert(strstr(url, request->urlpath.buf()));
1444 }
1445
1446 /* Set no-cache if determined needed but not found */
1447 if (orig_request->flags.nocache && !httpHeaderHas(hdr_in, HDR_PRAGMA))
1448 EBIT_SET(cc->mask, CC_NO_CACHE);
1449
1450 /* Enforce sibling relations */
1451 if (flags.only_if_cached)
1452 EBIT_SET(cc->mask, CC_ONLY_IF_CACHED);
1453
1454 httpHeaderPutCc(hdr_out, cc);
1455
1456 httpHdrCcDestroy(cc);
1457 }
1458
1459 /* maybe append Connection: keep-alive */
1460 if (flags.keepalive) {
1461 if (flags.proxying) {
1462 httpHeaderPutStr(hdr_out, HDR_PROXY_CONNECTION, "keep-alive");
1463 } else {
1464 httpHeaderPutStr(hdr_out, HDR_CONNECTION, "keep-alive");
1465 }
1466 }
1467
1468 /* append Front-End-Https */
1469 if (flags.front_end_https) {
1470 if (flags.front_end_https == 1 || request->protocol == PROTO_HTTPS)
1471 httpHeaderPutStr(hdr_out, HDR_FRONT_END_HTTPS, "On");
1472 }
1473
1474 /* Now mangle the headers. */
1475 httpHdrMangleList(hdr_out, request, ROR_REQUEST);
1476
1477 strConnection.clean();
1478 }
1479
1480
1481 void
1482 copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, String strConnection, HttpRequest * request, HttpRequest * orig_request, HttpHeader * hdr_out, int we_do_ranges, http_state_flags flags)
1483 {
1484 debug(11, 5) ("httpBuildRequestHeader: %s: %s\n",
1485 e->name.buf(), e->value.buf());
1486
1487 if (!httpRequestHdrAllowed(e, &strConnection)) {
1488 debug(11, 2) ("'%s' header denied by anonymize_headers configuration\n",+ e->name.buf());
1489 return;
1490 }
1491
1492 switch (e->id) {
1493
1494 case HDR_PROXY_AUTHORIZATION:
1495 /* Only pass on proxy authentication to peers for which
1496 * authentication forwarding is explicitly enabled
1497 */
1498
1499 if (flags.proxying && orig_request->peer_login &&
1500 (strcmp(orig_request->peer_login, "PASS") == 0 ||
1501 strcmp(orig_request->peer_login, "PROXYPASS") == 0)) {
1502 httpHeaderAddEntry(hdr_out, httpHeaderEntryClone(e));
1503 }
1504
1505 break;
1506
1507 case HDR_AUTHORIZATION:
1508 /* Pass on WWW authentication */
1509
1510 if (!flags.originpeer) {
1511 httpHeaderAddEntry(hdr_out, httpHeaderEntryClone(e));
1512 } else {
1513 /* In accelerators, only forward authentication if enabled
1514 * (see also below for proxy->server authentication)
1515 */
1516
1517 if (orig_request->peer_login &&
1518 (strcmp(orig_request->peer_login, "PASS") == 0 ||
1519 strcmp(orig_request->peer_login, "PROXYPASS") == 0)) {
1520 httpHeaderAddEntry(hdr_out, httpHeaderEntryClone(e));
1521 }
1522 }
1523
1524 break;
1525
1526 case HDR_HOST:
1527 /*
1528 * Normally Squid rewrites the Host: header.
1529 * However, there is one case when we don't: If the URL
1530 * went through our redirector and the admin configured
1531 * 'redir_rewrites_host' to be off.
1532 */
1533
1534 if (request->flags.redirected && !Config.onoff.redir_rewrites_host)
1535 httpHeaderAddEntry(hdr_out, httpHeaderEntryClone(e));
1536 else {
1537 /* use port# only if not default */
1538
1539 if (orig_request->port == urlDefaultPort(orig_request->protocol)) {
1540 httpHeaderPutStr(hdr_out, HDR_HOST, orig_request->host);
1541 } else {
1542 httpHeaderPutStrf(hdr_out, HDR_HOST, "%s:%d",
1543 orig_request->host, (int) orig_request->port);
1544 }
1545 }
1546
1547 break;
1548
1549 case HDR_IF_MODIFIED_SINCE:
1550 /* append unless we added our own;
1551 * note: at most one client's ims header can pass through */
1552
1553 if (!httpHeaderHas(hdr_out, HDR_IF_MODIFIED_SINCE))
1554 httpHeaderAddEntry(hdr_out, httpHeaderEntryClone(e));
1555
1556 break;
1557
1558 case HDR_MAX_FORWARDS:
1559 if (orig_request->method == METHOD_TRACE) {
1560 const int hops = httpHeaderEntryGetInt(e);
1561
1562 if (hops > 0)
1563 httpHeaderPutInt(hdr_out, HDR_MAX_FORWARDS, hops - 1);
1564 }
1565
1566 break;
1567
1568 case HDR_VIA:
1569 /* If Via is disabled then forward any received header as-is */
1570
1571 if (!Config.onoff.via)
1572 httpHeaderAddEntry(hdr_out, httpHeaderEntryClone(e));
1573
1574 break;
1575
1576 case HDR_RANGE:
1577
1578 case HDR_IF_RANGE:
1579
1580 case HDR_REQUEST_RANGE:
1581 if (!we_do_ranges)
1582 httpHeaderAddEntry(hdr_out, httpHeaderEntryClone(e));
1583
1584 break;
1585
1586 case HDR_PROXY_CONNECTION:
1587
1588 case HDR_CONNECTION:
1589
1590 case HDR_X_FORWARDED_FOR:
1591
1592 case HDR_CACHE_CONTROL:
1593 /* append these after the loop if needed */
1594 break;
1595
1596 case HDR_FRONT_END_HTTPS:
1597 if (!flags.front_end_https)
1598 httpHeaderAddEntry(hdr_out, httpHeaderEntryClone(e));
1599
1600 break;
1601
1602 default:
1603 /* pass on all other header fields */
1604 httpHeaderAddEntry(hdr_out, httpHeaderEntryClone(e));
1605 }
1606 }
1607
1608 int
1609 decideIfWeDoRanges (HttpRequest * orig_request)
1610 {
1611 int result = 1;
1612 /* decide if we want to do Ranges ourselves
1613 * and fetch the whole object now)
1614 * We want to handle Ranges ourselves iff
1615 * - we can actually parse client Range specs
1616 * - the specs are expected to be simple enough (e.g. no out-of-order ranges)
1617 * - reply will be cachable
1618 * (If the reply will be uncachable we have to throw it away after
1619 * serving this request, so it is better to forward ranges to
1620 * the server and fetch only the requested content)
1621 */
1622
1623 if (NULL == orig_request->range || !orig_request->flags.cachable
1624 || orig_request->range->offsetLimitExceeded())
1625 result = 0;
1626
1627 debug(11, 8) ("decideIfWeDoRanges: range specs: %p, cachable: %d; we_do_ranges: %d\n",
1628 orig_request->range, orig_request->flags.cachable, result);
1629
1630 return result;
1631 }
1632
1633
1634 /* build request prefix and append it to a given MemBuf;
1635 * return the length of the prefix */
1636 mb_size_t
1637 httpBuildRequestPrefix(HttpRequest * request,
1638 HttpRequest * orig_request,
1639 StoreEntry * entry,
1640 MemBuf * mb,
1641 http_state_flags flags)
1642 {
1643 const int offset = mb->size;
1644 HttpVersion httpver(1, 0);
1645 memBufPrintf(mb, "%s %s HTTP/%d.%d\r\n",
1646 RequestMethodStr[request->method],
1647 request->urlpath.size() ? request->urlpath.buf() : "/",
1648 httpver.major,httpver.minor);
1649 /* build and pack headers */
1650 {
1651 HttpHeader hdr(hoRequest);
1652 Packer p;
1653 httpBuildRequestHeader(request, orig_request, entry, &hdr, flags);
1654 packerToMemInit(&p, mb);
1655 httpHeaderPackInto(&hdr, &p);
1656 httpHeaderClean(&hdr);
1657 packerClean(&p);
1658 }
1659 /* append header terminator */
1660 memBufAppend(mb, crlf, 2);
1661 return mb->size - offset;
1662 }
1663
1664 /* This will be called when connect completes. Write request. */
1665 static void
1666 httpSendRequest(HttpStateData * httpState)
1667 {
1668 MemBuf mb;
1669 HttpRequest *req = httpState->request;
1670 StoreEntry *entry = httpState->entry;
1671 peer *p = httpState->_peer;
1672 CWCB *sendHeaderDone;
1673 int fd = httpState->fd;
1674
1675 debug(11, 5) ("httpSendRequest: FD %d: httpState %p.\n", fd,
1676 httpState);
1677
1678 /* Schedule read reply. */
1679 commSetTimeout(fd, Config.Timeout.lifetime, httpTimeout, httpState);
1680 entry->delayAwareRead(fd, httpState->buf, SQUID_TCP_SO_RCVBUF, httpReadReply, httpState);
1681
1682 if (httpState->orig_request->body_connection.getRaw() != NULL)
1683 sendHeaderDone = httpSendRequestEntity;
1684 else
1685 sendHeaderDone = HttpStateData::SendComplete;
1686
1687 if (p != NULL) {
1688 if (p->options.originserver) {
1689 httpState->flags.proxying = 0;
1690 httpState->flags.originpeer = 1;
1691 } else {
1692 httpState->flags.proxying = 1;
1693 httpState->flags.originpeer = 0;
1694 }
1695 } else {
1696 httpState->flags.proxying = 0;
1697 httpState->flags.originpeer = 0;
1698 }
1699
1700 /*
1701 * Is keep-alive okay for all request methods?
1702 */
1703 if (!Config.onoff.server_pconns)
1704 httpState->flags.keepalive = 0;
1705 else if (p == NULL)
1706 httpState->flags.keepalive = 1;
1707 else if (p->stats.n_keepalives_sent < 10)
1708 httpState->flags.keepalive = 1;
1709 else if ((double) p->stats.n_keepalives_recv /
1710 (double) p->stats.n_keepalives_sent > 0.50)
1711 httpState->flags.keepalive = 1;
1712
1713 if (httpState->_peer) {
1714 if (neighborType(httpState->_peer, httpState->request) == PEER_SIBLING &&
1715 !httpState->_peer->options.allow_miss)
1716 httpState->flags.only_if_cached = 1;
1717
1718 httpState->flags.front_end_https = httpState->_peer->front_end_https;
1719 }
1720
1721 memBufDefInit(&mb);
1722 httpBuildRequestPrefix(req,
1723 httpState->orig_request,
1724 entry,
1725 &mb,
1726 httpState->flags);
1727 debug(11, 6) ("httpSendRequest: FD %d:\n%s\n", fd, mb.buf);
1728 comm_old_write_mbuf(fd, mb, sendHeaderDone, httpState);
1729 }
1730
1731 void
1732 httpStart(FwdState * fwd)
1733 {
1734 int fd = fwd->server_fd;
1735 HttpStateData *httpState;
1736 HttpRequest *proxy_req;
1737 HttpRequest *orig_req = fwd->request;
1738 debug(11, 3) ("httpStart: \"%s %s\"\n",
1739 RequestMethodStr[orig_req->method],
1740 storeUrl(fwd->entry));
1741 CBDATA_INIT_TYPE(HttpStateData);
1742 httpState = cbdataAlloc(HttpStateData);
1743 httpState->ignoreCacheControl = false;
1744 httpState->surrogateNoStore = false;
1745 storeLockObject(fwd->entry);
1746 httpState->fwd = fwd;
1747 httpState->entry = fwd->entry;
1748 httpState->fd = fd;
1749
1750 if (fwd->servers)
1751 httpState->_peer = fwd->servers->_peer; /* might be NULL */
1752
1753 if (httpState->_peer) {
1754 const char *url;
1755
1756 if (httpState->_peer->options.originserver)
1757 url = orig_req->urlpath.buf();
1758 else
1759 url = storeUrl(httpState->entry);
1760
1761 proxy_req = requestCreate(orig_req->method,
1762 orig_req->protocol, url);
1763
1764 xstrncpy(proxy_req->host, httpState->_peer->host, SQUIDHOSTNAMELEN);
1765
1766 proxy_req->port = httpState->_peer->http_port;
1767
1768 proxy_req->flags = orig_req->flags;
1769
1770 proxy_req->lastmod = orig_req->lastmod;
1771
1772 httpState->request = requestLink(proxy_req);
1773
1774 httpState->orig_request = requestLink(orig_req);
1775
1776 proxy_req->flags.proxying = 1;
1777
1778 /*
1779 * This NEIGHBOR_PROXY_ONLY check probably shouldn't be here.
1780 * We might end up getting the object from somewhere else if,
1781 * for example, the request to this neighbor fails.
1782 */
1783 if (httpState->_peer->options.proxy_only)
1784 storeReleaseRequest(httpState->entry);
1785
1786 #if DELAY_POOLS
1787
1788 httpState->entry->setNoDelay(httpState->_peer->options.no_delay);
1789
1790 #endif
1791
1792 } else {
1793 httpState->request = requestLink(orig_req);
1794 httpState->orig_request = requestLink(orig_req);
1795 }
1796
1797 /*
1798 * register the handler to free HTTP state data when the FD closes
1799 */
1800 comm_add_close_handler(fd, httpStateFree, httpState);
1801
1802 statCounter.server.all.requests++;
1803
1804 statCounter.server.http.requests++;
1805
1806 httpSendRequest(httpState);
1807
1808 /*
1809 * We used to set the read timeout here, but not any more.
1810 * Now its set in httpSendComplete() after the full request,
1811 * including request body, has been written to the server.
1812 */
1813 }
1814
1815 static void
1816 httpSendRequestEntityDone(int fd, void *data)
1817 {
1818 HttpStateData *httpState = static_cast<HttpStateData *>(data);
1819 ACLChecklist ch;
1820 debug(11, 5) ("httpSendRequestEntityDone: FD %d\n", fd);
1821 ch.request = requestLink(httpState->request);
1822
1823 if (Config.accessList.brokenPosts)
1824 ch.accessList = cbdataReference(Config.accessList.brokenPosts);
1825
1826 if (!Config.accessList.brokenPosts) {
1827 debug(11, 5) ("httpSendRequestEntityDone: No brokenPosts list\n");
1828 HttpStateData::SendComplete(fd, NULL, 0, COMM_OK, data);
1829 } else if (!ch.fastCheck()) {
1830 debug(11, 5) ("httpSendRequestEntityDone: didn't match brokenPosts\n");
1831 HttpStateData::SendComplete(fd, NULL, 0, COMM_OK, data);
1832 } else {
1833 debug(11, 2) ("httpSendRequestEntityDone: matched brokenPosts\n");
1834 comm_old_write(fd, "\r\n", 2, HttpStateData::SendComplete, data, NULL);
1835 }
1836
1837 ch.accessList = NULL;
1838 }
1839
1840 static void
1841 httpRequestBodyHandler(char *buf, ssize_t size, void *data)
1842 {
1843 HttpStateData *httpState = (HttpStateData *) data;
1844 httpState->body_buf = NULL;
1845
1846 if (size > 0) {
1847 if (httpState->reply_hdr_state >= 2 && !httpState->flags.abuse_detected) {
1848 httpState->flags.abuse_detected = 1;
1849 debug(11, 1) ("httpSendRequestEntryDone: Likely proxy abuse detected '%s' -> '%s'\n",
1850 inet_ntoa(httpState->orig_request->client_addr),
1851 storeUrl(httpState->entry));
1852
1853 if (httpState->entry->getReply()->sline.status == HTTP_INVALID_HEADER) {
1854 memFree8K(buf);
1855 comm_close(httpState->fd);
1856 return;
1857 }
1858 }
1859
1860 comm_old_write(httpState->fd, buf, size, httpSendRequestEntity, data, memFree8K);
1861 } else if (size == 0) {
1862 /* End of body */
1863 memFree8K(buf);
1864 httpSendRequestEntityDone(httpState->fd, data);
1865 } else {
1866 /* Failed to get whole body, probably aborted */
1867 memFree8K(buf);
1868 HttpStateData::SendComplete(httpState->fd, NULL, 0, COMM_ERR_CLOSING, data);
1869 }
1870 }
1871
1872 static void
1873 httpSendRequestEntity(int fd, char *bufnotused, size_t size, comm_err_t errflag, void *data)
1874 {
1875 HttpStateData *httpState = static_cast<HttpStateData *>(data);
1876 StoreEntry *entry = httpState->entry;
1877 ErrorState *err;
1878 debug(11, 5) ("httpSendRequestEntity: FD %d: size %d: errflag %d.\n",
1879 fd, (int) size, errflag);
1880
1881 if (size > 0) {
1882 fd_bytes(fd, size, FD_WRITE);
1883 kb_incr(&statCounter.server.all.kbytes_out, size);
1884 kb_incr(&statCounter.server.http.kbytes_out, size);
1885 }
1886
1887 if (errflag == COMM_ERR_CLOSING)
1888 return;
1889
1890 if (errflag) {
1891 err = errorCon(ERR_WRITE_ERROR, HTTP_BAD_GATEWAY);
1892 err->xerrno = errno;
1893 err->request = requestLink(httpState->orig_request);
1894 errorAppendEntry(entry, err);
1895 comm_close(fd);
1896 return;
1897 }
1898
1899 if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
1900 comm_close(fd);
1901 return;
1902 }
1903
1904 httpState->body_buf = (char *)memAllocate(MEM_8K_BUF);
1905 clientReadBody(httpState->orig_request, httpState->body_buf, 8192, httpRequestBodyHandler, httpState);
1906 }
1907
1908 void
1909 httpBuildVersion(HttpVersion * version, unsigned int major, unsigned int minor)
1910 {
1911 version->major = major;
1912 version->minor = minor;
1913 }