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