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