]> git.ipfire.org Git - thirdparty/squid.git/blob - src/http.cc
Merged with trunk
[thirdparty/squid.git] / src / http.cc
1
2 /*
3 * $Id$
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
43 #include "acl/FilledChecklist.h"
44 #include "auth/UserRequest.h"
45 #if DELAY_POOLS
46 #include "DelayPools.h"
47 #endif
48 #include "errorpage.h"
49 #include "fde.h"
50 #include "http.h"
51 #include "HttpHdrContRange.h"
52 #include "HttpHdrSc.h"
53 #include "HttpHdrScTarget.h"
54 #include "HttpReply.h"
55 #include "HttpRequest.h"
56 #include "MemBuf.h"
57 #include "MemObject.h"
58 #include "protos.h"
59 #include "rfc1738.h"
60 #include "SquidTime.h"
61 #include "Store.h"
62 #include "TextException.h"
63
64
65 #define SQUID_ENTER_THROWING_CODE() try {
66 #define SQUID_EXIT_THROWING_CODE(status) \
67 status = true; \
68 } \
69 catch (const std::exception &e) { \
70 debugs (11, 1, "Exception error:" << e.what()); \
71 status = false; \
72 }
73
74 CBDATA_CLASS_INIT(HttpStateData);
75
76 static const char *const crlf = "\r\n";
77
78 static void httpMaybeRemovePublic(StoreEntry *, http_status);
79 static void copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, const String strConnection, HttpRequest * request, const HttpRequest * orig_request,
80 HttpHeader * hdr_out, const int we_do_ranges, const http_state_flags);
81
82 HttpStateData::HttpStateData(FwdState *theFwdState) : AsyncJob("HttpStateData"), ServerStateData(theFwdState),
83 lastChunk(0), header_bytes_read(0), reply_bytes_read(0),
84 body_bytes_truncated(0), httpChunkDecoder(NULL)
85 {
86 debugs(11,5,HERE << "HttpStateData " << this << " created");
87 ignoreCacheControl = false;
88 surrogateNoStore = false;
89 fd = fwd->server_fd;
90 readBuf = new MemBuf;
91 readBuf->init();
92 orig_request = HTTPMSGLOCK(fwd->request);
93
94 // reset peer response time stats for %<pt
95 orig_request->hier.peer_http_request_sent.tv_sec = 0;
96 orig_request->hier.peer_http_request_sent.tv_usec = 0;
97
98 if (fwd->servers)
99 _peer = fwd->servers->_peer; /* might be NULL */
100
101 if (_peer) {
102 const char *url;
103
104 if (_peer->options.originserver)
105 url = orig_request->urlpath.termedBuf();
106 else
107 url = entry->url();
108
109 HttpRequest * proxy_req = new HttpRequest(orig_request->method,
110 orig_request->protocol, url);
111
112 proxy_req->SetHost(_peer->host);
113
114 proxy_req->port = _peer->http_port;
115
116 proxy_req->flags = orig_request->flags;
117
118 proxy_req->lastmod = orig_request->lastmod;
119
120 proxy_req->flags.proxying = 1;
121
122 HTTPMSGUNLOCK(request);
123
124 request = HTTPMSGLOCK(proxy_req);
125
126 /*
127 * This NEIGHBOR_PROXY_ONLY check probably shouldn't be here.
128 * We might end up getting the object from somewhere else if,
129 * for example, the request to this neighbor fails.
130 */
131 if (_peer->options.proxy_only)
132 entry->releaseRequest();
133
134 #if DELAY_POOLS
135
136 entry->setNoDelay(_peer->options.no_delay);
137
138 #endif
139 }
140
141 /*
142 * register the handler to free HTTP state data when the FD closes
143 */
144 typedef CommCbMemFunT<HttpStateData, CommCloseCbParams> Dialer;
145 closeHandler = asyncCall(9, 5, "httpStateData::httpStateConnClosed",
146 Dialer(this,&HttpStateData::httpStateConnClosed));
147 comm_add_close_handler(fd, closeHandler);
148 }
149
150 HttpStateData::~HttpStateData()
151 {
152 /*
153 * don't forget that ~ServerStateData() gets called automatically
154 */
155
156 if (!readBuf->isNull())
157 readBuf->clean();
158
159 delete readBuf;
160
161 if (httpChunkDecoder)
162 delete httpChunkDecoder;
163
164 HTTPMSGUNLOCK(orig_request);
165
166 debugs(11,5, HERE << "HttpStateData " << this << " destroyed; FD " << fd);
167 }
168
169 int
170 HttpStateData::dataDescriptor() const
171 {
172 return fd;
173 }
174 /*
175 static void
176 httpStateFree(int fd, void *data)
177 {
178 HttpStateData *httpState = static_cast<HttpStateData *>(data);
179 debugs(11, 5, "httpStateFree: FD " << fd << ", httpState=" << data);
180 delete httpState;
181 }*/
182
183 void
184 HttpStateData::httpStateConnClosed(const CommCloseCbParams &params)
185 {
186 debugs(11, 5, "httpStateFree: FD " << params.fd << ", httpState=" << params.data);
187 deleteThis("HttpStateData::httpStateConnClosed");
188 }
189
190 int
191 httpCachable(const HttpRequestMethod& method)
192 {
193 /* GET and HEAD are cachable. Others are not. */
194
195 // TODO: replase to HttpRequestMethod::isCachable() ?
196 if (method != METHOD_GET && method != METHOD_HEAD)
197 return 0;
198
199 /* else cachable */
200 return 1;
201 }
202
203 void
204 HttpStateData::httpTimeout(const CommTimeoutCbParams &params)
205 {
206 debugs(11, 4, "httpTimeout: FD " << fd << ": '" << entry->url() << "'" );
207
208 if (entry->store_status == STORE_PENDING) {
209 fwd->fail(errorCon(ERR_READ_TIMEOUT, HTTP_GATEWAY_TIMEOUT, fwd->request));
210 }
211
212 comm_close(fd);
213 }
214
215 static void
216 httpMaybeRemovePublic(StoreEntry * e, http_status status)
217 {
218 int remove = 0;
219 int forbidden = 0;
220 StoreEntry *pe;
221
222 if (!EBIT_TEST(e->flags, KEY_PRIVATE))
223 return;
224
225 switch (status) {
226
227 case HTTP_OK:
228
229 case HTTP_NON_AUTHORITATIVE_INFORMATION:
230
231 case HTTP_MULTIPLE_CHOICES:
232
233 case HTTP_MOVED_PERMANENTLY:
234
235 case HTTP_MOVED_TEMPORARILY:
236
237 case HTTP_GONE:
238
239 case HTTP_NOT_FOUND:
240 remove = 1;
241
242 break;
243
244 case HTTP_FORBIDDEN:
245
246 case HTTP_METHOD_NOT_ALLOWED:
247 forbidden = 1;
248
249 break;
250
251 #if WORK_IN_PROGRESS
252
253 case HTTP_UNAUTHORIZED:
254 forbidden = 1;
255
256 break;
257
258 #endif
259
260 default:
261 #if QUESTIONABLE
262 /*
263 * Any 2xx response should eject previously cached entities...
264 */
265
266 if (status >= 200 && status < 300)
267 remove = 1;
268
269 #endif
270
271 break;
272 }
273
274 if (!remove && !forbidden)
275 return;
276
277 assert(e->mem_obj);
278
279 if (e->mem_obj->request)
280 pe = storeGetPublicByRequest(e->mem_obj->request);
281 else
282 pe = storeGetPublic(e->mem_obj->url, e->mem_obj->method);
283
284 if (pe != NULL) {
285 assert(e != pe);
286 #if USE_HTCP
287 neighborsHtcpClear(e, NULL, e->mem_obj->request, e->mem_obj->method, HTCP_CLR_INVALIDATION);
288 #endif
289 pe->release();
290 }
291
292 /** \par
293 * Also remove any cached HEAD response in case the object has
294 * changed.
295 */
296 if (e->mem_obj->request)
297 pe = storeGetPublicByRequestMethod(e->mem_obj->request, METHOD_HEAD);
298 else
299 pe = storeGetPublic(e->mem_obj->url, METHOD_HEAD);
300
301 if (pe != NULL) {
302 assert(e != pe);
303 #if USE_HTCP
304 neighborsHtcpClear(e, NULL, e->mem_obj->request, HttpRequestMethod(METHOD_HEAD), HTCP_CLR_INVALIDATION);
305 #endif
306 pe->release();
307 }
308 }
309
310 void
311 HttpStateData::processSurrogateControl(HttpReply *reply)
312 {
313 #if USE_SQUID_ESI
314
315 if (request->flags.accelerated && reply->surrogate_control) {
316 HttpHdrScTarget *sctusable =
317 httpHdrScGetMergedTarget(reply->surrogate_control,
318 Config.Accel.surrogate_id);
319
320 if (sctusable) {
321 if (EBIT_TEST(sctusable->mask, SC_NO_STORE) ||
322 (Config.onoff.surrogate_is_remote
323 && EBIT_TEST(sctusable->mask, SC_NO_STORE_REMOTE))) {
324 surrogateNoStore = true;
325 entry->makePrivate();
326 }
327
328 /* The HttpHeader logic cannot tell if the header it's parsing is a reply to an
329 * accelerated request or not...
330 * Still, this is an abtraction breach. - RC
331 */
332 if (sctusable->max_age != -1) {
333 if (sctusable->max_age < sctusable->max_stale)
334 reply->expires = reply->date + sctusable->max_age;
335 else
336 reply->expires = reply->date + sctusable->max_stale;
337
338 /* And update the timestamps */
339 entry->timestampsSet();
340 }
341
342 /* We ignore cache-control directives as per the Surrogate specification */
343 ignoreCacheControl = true;
344
345 httpHdrScTargetDestroy(sctusable);
346 }
347 }
348
349 #endif
350 }
351
352 int
353 HttpStateData::cacheableReply()
354 {
355 HttpReply const *rep = finalReply();
356 HttpHeader const *hdr = &rep->header;
357 const int cc_mask = (rep->cache_control) ? rep->cache_control->mask : 0;
358 const char *v;
359 #if HTTP_VIOLATIONS
360
361 const refresh_t *R = NULL;
362
363 /* This strange looking define first looks up the refresh pattern
364 * and then checks if the specified flag is set. The main purpose
365 * of this is to simplify the refresh pattern lookup and HTTP_VIOLATIONS
366 * condition
367 */
368 #define REFRESH_OVERRIDE(flag) \
369 ((R = (R ? R : refreshLimits(entry->mem_obj->url))) , \
370 (R && R->flags.flag))
371 #else
372 #define REFRESH_OVERRIDE(flag) 0
373 #endif
374
375 if (surrogateNoStore)
376 return 0;
377
378 if (!ignoreCacheControl) {
379 if (EBIT_TEST(cc_mask, CC_PRIVATE)) {
380 if (!REFRESH_OVERRIDE(ignore_private))
381 return 0;
382 }
383
384 if (EBIT_TEST(cc_mask, CC_NO_CACHE)) {
385 if (!REFRESH_OVERRIDE(ignore_no_cache))
386 return 0;
387 }
388
389 if (EBIT_TEST(cc_mask, CC_NO_STORE)) {
390 if (!REFRESH_OVERRIDE(ignore_no_store))
391 return 0;
392 }
393 }
394
395 if (request->flags.auth || request->flags.auth_sent) {
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 (!REFRESH_OVERRIDE(ignore_auth))
404 return 0;
405 }
406 }
407
408 /* Pragma: no-cache in _replies_ is not documented in HTTP,
409 * but servers like "Active Imaging Webcast/2.0" sure do use it */
410 if (hdr->has(HDR_PRAGMA)) {
411 String s = hdr->getList(HDR_PRAGMA);
412 const int no_cache = strListIsMember(&s, "no-cache", ',');
413 s.clean();
414
415 if (no_cache) {
416 if (!REFRESH_OVERRIDE(ignore_no_cache))
417 return 0;
418 }
419 }
420
421 /*
422 * The "multipart/x-mixed-replace" content type is used for
423 * continuous push replies. These are generally dynamic and
424 * probably should not be cachable
425 */
426 if ((v = hdr->getStr(HDR_CONTENT_TYPE)))
427 if (!strncasecmp(v, "multipart/x-mixed-replace", 25))
428 return 0;
429
430 switch (rep->sline.status) {
431 /* Responses that are cacheable */
432
433 case HTTP_OK:
434
435 case HTTP_NON_AUTHORITATIVE_INFORMATION:
436
437 case HTTP_MULTIPLE_CHOICES:
438
439 case HTTP_MOVED_PERMANENTLY:
440
441 case HTTP_GONE:
442 /*
443 * Don't cache objects that need to be refreshed on next request,
444 * unless we know how to refresh it.
445 */
446
447 if (!refreshIsCachable(entry)) {
448 debugs(22, 3, "refreshIsCachable() returned non-cacheable..");
449 return 0;
450 }
451
452 /* don't cache objects from peers w/o LMT, Date, or Expires */
453 /* check that is it enough to check headers @?@ */
454 if (rep->date > -1)
455 return 1;
456 else if (rep->last_modified > -1)
457 return 1;
458 else if (!_peer)
459 return 1;
460
461 /* @?@ (here and 302): invalid expires header compiles to squid_curtime */
462 else if (rep->expires > -1)
463 return 1;
464 else
465 return 0;
466
467 /* NOTREACHED */
468 break;
469
470 /* Responses that only are cacheable if the server says so */
471
472 case HTTP_MOVED_TEMPORARILY:
473 case HTTP_TEMPORARY_REDIRECT:
474 if (rep->expires > rep->date && rep->date > 0)
475 return 1;
476 else
477 return 0;
478
479 /* NOTREACHED */
480 break;
481
482 /* Errors can be negatively cached */
483
484 case HTTP_NO_CONTENT:
485
486 case HTTP_USE_PROXY:
487
488 case HTTP_BAD_REQUEST:
489
490 case HTTP_FORBIDDEN:
491
492 case HTTP_NOT_FOUND:
493
494 case HTTP_METHOD_NOT_ALLOWED:
495
496 case HTTP_REQUEST_URI_TOO_LARGE:
497
498 case HTTP_INTERNAL_SERVER_ERROR:
499
500 case HTTP_NOT_IMPLEMENTED:
501
502 case HTTP_BAD_GATEWAY:
503
504 case HTTP_SERVICE_UNAVAILABLE:
505
506 case HTTP_GATEWAY_TIMEOUT:
507 return -1;
508
509 /* NOTREACHED */
510 break;
511
512 /* Some responses can never be cached */
513
514 case HTTP_PARTIAL_CONTENT: /* Not yet supported */
515
516 case HTTP_SEE_OTHER:
517
518 case HTTP_NOT_MODIFIED:
519
520 case HTTP_UNAUTHORIZED:
521
522 case HTTP_PROXY_AUTHENTICATION_REQUIRED:
523
524 case HTTP_INVALID_HEADER: /* Squid header parsing error */
525
526 case HTTP_HEADER_TOO_LARGE:
527
528 case HTTP_PAYMENT_REQUIRED:
529 case HTTP_NOT_ACCEPTABLE:
530 case HTTP_REQUEST_TIMEOUT:
531 case HTTP_CONFLICT:
532 case HTTP_LENGTH_REQUIRED:
533 case HTTP_PRECONDITION_FAILED:
534 case HTTP_REQUEST_ENTITY_TOO_LARGE:
535 case HTTP_UNSUPPORTED_MEDIA_TYPE:
536 case HTTP_UNPROCESSABLE_ENTITY:
537 case HTTP_LOCKED:
538 case HTTP_FAILED_DEPENDENCY:
539 case HTTP_INSUFFICIENT_STORAGE:
540 case HTTP_REQUESTED_RANGE_NOT_SATISFIABLE:
541 case HTTP_EXPECTATION_FAILED:
542
543 return 0;
544
545 default:
546 /* RFC 2616 section 6.1.1: an unrecognized response MUST NOT be cached. */
547 debugs (11, 3, HERE << "Unknown HTTP status code " << rep->sline.status << ". Not cacheable.");
548
549 return 0;
550
551 /* NOTREACHED */
552 break;
553 }
554
555 /* NOTREACHED */
556 }
557
558 /*
559 * For Vary, store the relevant request headers as
560 * virtual headers in the reply
561 * Returns false if the variance cannot be stored
562 */
563 const char *
564 httpMakeVaryMark(HttpRequest * request, HttpReply const * reply)
565 {
566 String vary, hdr;
567 const char *pos = NULL;
568 const char *item;
569 const char *value;
570 int ilen;
571 static String vstr;
572
573 vstr.clean();
574 vary = reply->header.getList(HDR_VARY);
575
576 while (strListGetItem(&vary, ',', &item, &ilen, &pos)) {
577 char *name = (char *)xmalloc(ilen + 1);
578 xstrncpy(name, item, ilen + 1);
579 Tolower(name);
580
581 if (strcmp(name, "*") == 0) {
582 /* Can not handle "Vary: *" withtout ETag support */
583 safe_free(name);
584 vstr.clean();
585 break;
586 }
587
588 strListAdd(&vstr, name, ',');
589 hdr = request->header.getByName(name);
590 safe_free(name);
591 value = hdr.termedBuf();
592
593 if (value) {
594 value = rfc1738_escape_part(value);
595 vstr.append("=\"", 2);
596 vstr.append(value);
597 vstr.append("\"", 1);
598 }
599
600 hdr.clean();
601 }
602
603 vary.clean();
604 #if X_ACCELERATOR_VARY
605
606 pos = NULL;
607 vary = reply->header.getList(HDR_X_ACCELERATOR_VARY);
608
609 while (strListGetItem(&vary, ',', &item, &ilen, &pos)) {
610 char *name = (char *)xmalloc(ilen + 1);
611 xstrncpy(name, item, ilen + 1);
612 Tolower(name);
613 strListAdd(&vstr, name, ',');
614 hdr = request->header.getByName(name);
615 safe_free(name);
616 value = hdr.termedBuf();
617
618 if (value) {
619 value = rfc1738_escape_part(value);
620 vstr.append("=\"", 2);
621 vstr.append(value);
622 vstr.append("\"", 1);
623 }
624
625 hdr.clean();
626 }
627
628 vary.clean();
629 #endif
630
631 debugs(11, 3, "httpMakeVaryMark: " << vstr);
632 return vstr.termedBuf();
633 }
634
635 void
636 HttpStateData::keepaliveAccounting(HttpReply *reply)
637 {
638 if (flags.keepalive)
639 if (_peer)
640 _peer->stats.n_keepalives_sent++;
641
642 if (reply->keep_alive) {
643 if (_peer)
644 _peer->stats.n_keepalives_recv++;
645
646 if (Config.onoff.detect_broken_server_pconns
647 && reply->bodySize(request->method) == -1 && !flags.chunked) {
648 debugs(11, 1, "keepaliveAccounting: Impossible keep-alive header from '" << entry->url() << "'" );
649 // debugs(11, 2, "GOT HTTP REPLY HDR:\n---------\n" << readBuf->content() << "\n----------" );
650 flags.keepalive_broken = 1;
651 }
652 }
653 }
654
655 void
656 HttpStateData::checkDateSkew(HttpReply *reply)
657 {
658 if (reply->date > -1 && !_peer) {
659 int skew = abs((int)(reply->date - squid_curtime));
660
661 if (skew > 86400)
662 debugs(11, 3, "" << request->GetHost() << "'s clock is skewed by " << skew << " seconds!");
663 }
664 }
665
666 /**
667 * This creates the error page itself.. its likely
668 * that the forward ported reply header max size patch
669 * generates non http conformant error pages - in which
670 * case the errors where should be 'BAD_GATEWAY' etc
671 */
672 void
673 HttpStateData::processReplyHeader()
674 {
675 /** Creates a blank header. If this routine is made incremental, this will not do */
676 Ctx ctx = ctx_enter(entry->mem_obj->url);
677 debugs(11, 3, "processReplyHeader: key '" << entry->getMD5Text() << "'");
678
679 assert(!flags.headers_parsed);
680
681 http_status error = HTTP_STATUS_NONE;
682
683 HttpReply *newrep = new HttpReply;
684 const bool parsed = newrep->parse(readBuf, eof, &error);
685
686 if (!parsed && readBuf->contentSize() > 5 && strncmp(readBuf->content(), "HTTP/", 5) != 0 && strncmp(readBuf->content(), "ICY", 3) != 0) {
687 MemBuf *mb;
688 HttpReply *tmprep = new HttpReply;
689 tmprep->setHeaders(HTTP_OK, "Gatewaying", NULL, -1, -1, -1);
690 tmprep->header.putExt("X-Transformed-From", "HTTP/0.9");
691 mb = tmprep->pack();
692 newrep->parse(mb, eof, &error);
693 delete tmprep;
694 } else {
695 if (!parsed && error > 0) { // unrecoverable parsing error
696 debugs(11, 3, "processReplyHeader: Non-HTTP-compliant header: '" << readBuf->content() << "'");
697 flags.headers_parsed = 1;
698 newrep->sline.version = HttpVersion(1,0);
699 newrep->sline.status = error;
700 HttpReply *vrep = setVirginReply(newrep);
701 entry->replaceHttpReply(vrep);
702 ctx_exit(ctx);
703 return;
704 }
705
706 if (!parsed) { // need more data
707 assert(!error);
708 assert(!eof);
709 delete newrep;
710 ctx_exit(ctx);
711 return;
712 }
713
714 debugs(11, 9, "GOT HTTP REPLY HDR:\n---------\n" << readBuf->content() << "\n----------");
715
716 header_bytes_read = headersEnd(readBuf->content(), readBuf->contentSize());
717 readBuf->consume(header_bytes_read);
718 }
719
720 flags.chunked = 0;
721 if (newrep->sline.protocol == PROTO_HTTP && newrep->header.hasListMember(HDR_TRANSFER_ENCODING, "chunked", ',')) {
722 flags.chunked = 1;
723 httpChunkDecoder = new ChunkedCodingParser;
724 }
725
726 if (!peerSupportsConnectionPinning())
727 orig_request->flags.connection_auth_disabled = 1;
728
729 HttpReply *vrep = setVirginReply(newrep);
730 flags.headers_parsed = 1;
731
732 keepaliveAccounting(vrep);
733
734 checkDateSkew(vrep);
735
736 processSurrogateControl (vrep);
737
738 /** \todo IF the reply is a 1.0 reply, AND it has a Connection: Header
739 * Parse the header and remove all referenced headers
740 */
741
742 orig_request->hier.peer_reply_status = newrep->sline.status;
743
744 ctx_exit(ctx);
745
746 }
747
748 /**
749 * returns true if the peer can support connection pinning
750 */
751 bool HttpStateData::peerSupportsConnectionPinning() const
752 {
753 const HttpReply *rep = entry->mem_obj->getReply();
754 const HttpHeader *hdr = &rep->header;
755 bool rc;
756 String header;
757
758 if (!_peer)
759 return true;
760
761 /*If this peer does not support connection pinning (authenticated
762 connections) return false
763 */
764 if (!_peer->connection_auth)
765 return false;
766
767 /*The peer supports connection pinning and the http reply status
768 is not unauthorized, so the related connection can be pinned
769 */
770 if (rep->sline.status != HTTP_UNAUTHORIZED)
771 return true;
772
773 /*The server respond with HTTP_UNAUTHORIZED and the peer configured
774 with "connection-auth=on" we know that the peer supports pinned
775 connections
776 */
777 if (_peer->connection_auth == 1)
778 return true;
779
780 /*At this point peer has configured with "connection-auth=auto"
781 parameter so we need some extra checks to decide if we are going
782 to allow pinned connections or not
783 */
784
785 /*if the peer configured with originserver just allow connection
786 pinning (squid 2.6 behaviour)
787 */
788 if (_peer->options.originserver)
789 return true;
790
791 /*if the connections it is already pinned it is OK*/
792 if (request->flags.pinned)
793 return true;
794
795 /*Allow pinned connections only if the Proxy-support header exists in
796 reply and has in its list the "Session-Based-Authentication"
797 which means that the peer supports connection pinning.
798 */
799 if (!hdr->has(HDR_PROXY_SUPPORT))
800 return false;
801
802 header = hdr->getStrOrList(HDR_PROXY_SUPPORT);
803 /* XXX This ought to be done in a case-insensitive manner */
804 rc = (strstr(header.termedBuf(), "Session-Based-Authentication") != NULL);
805
806 return rc;
807 }
808
809 // Called when we parsed (and possibly adapted) the headers but
810 // had not starting storing (a.k.a., sending) the body yet.
811 void
812 HttpStateData::haveParsedReplyHeaders()
813 {
814 ServerStateData::haveParsedReplyHeaders();
815
816 Ctx ctx = ctx_enter(entry->mem_obj->url);
817 HttpReply *rep = finalReply();
818
819 if (rep->sline.status == HTTP_PARTIAL_CONTENT &&
820 rep->content_range)
821 currentOffset = rep->content_range->spec.offset;
822
823 entry->timestampsSet();
824
825 /* Check if object is cacheable or not based on reply code */
826 debugs(11, 3, "haveParsedReplyHeaders: HTTP CODE: " << rep->sline.status);
827
828 if (neighbors_do_private_keys)
829 httpMaybeRemovePublic(entry, rep->sline.status);
830
831 if (rep->header.has(HDR_VARY)
832 #if X_ACCELERATOR_VARY
833 || rep->header.has(HDR_X_ACCELERATOR_VARY)
834 #endif
835 ) {
836 const char *vary = httpMakeVaryMark(orig_request, rep);
837
838 if (!vary) {
839 entry->makePrivate();
840 if (!fwd->reforwardableStatus(rep->sline.status))
841 EBIT_CLR(entry->flags, ENTRY_FWD_HDR_WAIT);
842 goto no_cache;
843 }
844
845 entry->mem_obj->vary_headers = xstrdup(vary);
846 }
847
848 #if WIP_FWD_LOG
849 fwdStatus(fwd, s);
850
851 #endif
852 /*
853 * If its not a reply that we will re-forward, then
854 * allow the client to get it.
855 */
856 if (!fwd->reforwardableStatus(rep->sline.status))
857 EBIT_CLR(entry->flags, ENTRY_FWD_HDR_WAIT);
858
859 switch (cacheableReply()) {
860
861 case 1:
862 entry->makePublic();
863 break;
864
865 case 0:
866 entry->makePrivate();
867 break;
868
869 case -1:
870
871 #if HTTP_VIOLATIONS
872 if (Config.negativeTtl > 0)
873 entry->cacheNegatively();
874 else
875 #endif
876 entry->makePrivate();
877
878 break;
879
880 default:
881 assert(0);
882
883 break;
884 }
885
886 no_cache:
887
888 if (!ignoreCacheControl && rep->cache_control) {
889 if (EBIT_TEST(rep->cache_control->mask, CC_PROXY_REVALIDATE))
890 EBIT_SET(entry->flags, ENTRY_REVALIDATE);
891 else if (EBIT_TEST(rep->cache_control->mask, CC_MUST_REVALIDATE))
892 EBIT_SET(entry->flags, ENTRY_REVALIDATE);
893 }
894
895 #if HEADERS_LOG
896 headersLog(1, 0, request->method, rep);
897
898 #endif
899
900 ctx_exit(ctx);
901 }
902
903 HttpStateData::ConnectionStatus
904 HttpStateData::statusIfComplete() const
905 {
906 const HttpReply *rep = virginReply();
907 /** \par
908 * If the reply wants to close the connection, it takes precedence */
909
910 if (httpHeaderHasConnDir(&rep->header, "close"))
911 return COMPLETE_NONPERSISTENT_MSG;
912
913 /** \par
914 * If we didn't send a keep-alive request header, then this
915 * can not be a persistent connection.
916 */
917 if (!flags.keepalive)
918 return COMPLETE_NONPERSISTENT_MSG;
919
920 /** \par
921 * If we haven't sent the whole request then this can not be a persistent
922 * connection.
923 */
924 if (!flags.request_sent) {
925 debugs(11, 1, "statusIfComplete: Request not yet fully sent \"" << RequestMethodStr(orig_request->method) << " " << entry->url() << "\"" );
926 return COMPLETE_NONPERSISTENT_MSG;
927 }
928
929 /** \par
930 * What does the reply have to say about keep-alive?
931 */
932 /**
933 \bug XXX BUG?
934 * If the origin server (HTTP/1.0) does not send a keep-alive
935 * header, but keeps the connection open anyway, what happens?
936 * We'll return here and http.c waits for an EOF before changing
937 * store_status to STORE_OK. Combine this with ENTRY_FWD_HDR_WAIT
938 * and an error status code, and we might have to wait until
939 * the server times out the socket.
940 */
941 if (!rep->keep_alive)
942 return COMPLETE_NONPERSISTENT_MSG;
943
944 return COMPLETE_PERSISTENT_MSG;
945 }
946
947 HttpStateData::ConnectionStatus
948 HttpStateData::persistentConnStatus() const
949 {
950 debugs(11, 3, "persistentConnStatus: FD " << fd << " eof=" << eof);
951 const HttpReply *vrep = virginReply();
952 debugs(11, 5, "persistentConnStatus: content_length=" << vrep->content_length);
953
954 /* If we haven't seen the end of reply headers, we are not done */
955 debugs(11, 5, "persistentConnStatus: flags.headers_parsed=" << flags.headers_parsed);
956
957 if (!flags.headers_parsed)
958 return INCOMPLETE_MSG;
959
960 if (eof) // already reached EOF
961 return COMPLETE_NONPERSISTENT_MSG;
962
963 /** \par
964 * In chunked response we do not know the content length but we are absolutely
965 * sure about the end of response, so we are calling the statusIfComplete to
966 * decide if we can be persistant
967 */
968 if (lastChunk && flags.chunked)
969 return statusIfComplete();
970
971 const int64_t clen = vrep->bodySize(request->method);
972
973 debugs(11, 5, "persistentConnStatus: clen=" << clen);
974
975 /* If the body size is unknown we must wait for EOF */
976 if (clen < 0)
977 return INCOMPLETE_MSG;
978
979 /** \par
980 * If the body size is known, we must wait until we've gotten all of it. */
981 if (clen > 0) {
982 // old technique:
983 // if (entry->mem_obj->endOffset() < vrep->content_length + vrep->hdr_sz)
984 const int64_t body_bytes_read = reply_bytes_read - header_bytes_read;
985 debugs(11,5, "persistentConnStatus: body_bytes_read=" <<
986 body_bytes_read << " content_length=" << vrep->content_length);
987
988 if (body_bytes_read < vrep->content_length)
989 return INCOMPLETE_MSG;
990
991 if (body_bytes_truncated > 0) // already read more than needed
992 return COMPLETE_NONPERSISTENT_MSG; // disable pconns
993 }
994
995 /** \par
996 * If there is no message body or we got it all, we can be persistent */
997 return statusIfComplete();
998 }
999
1000 /*
1001 * This is the callback after some data has been read from the network
1002 */
1003 /*
1004 void
1005 HttpStateData::ReadReplyWrapper(int fd, char *buf, size_t len, comm_err_t flag, int xerrno, void *data)
1006 {
1007 HttpStateData *httpState = static_cast<HttpStateData *>(data);
1008 assert (fd == httpState->fd);
1009 // assert(buf == readBuf->content());
1010 PROF_start(HttpStateData_readReply);
1011 httpState->readReply(len, flag, xerrno);
1012 PROF_stop(HttpStateData_readReply);
1013 }
1014 */
1015
1016 /* XXX this function is too long! */
1017 void
1018 HttpStateData::readReply(const CommIoCbParams &io)
1019 {
1020 int bin;
1021 int clen;
1022 int len = io.size;
1023
1024 assert(fd == io.fd);
1025
1026 flags.do_next_read = 0;
1027
1028 debugs(11, 5, "httpReadReply: FD " << fd << ": len " << len << ".");
1029
1030 // Bail out early on COMM_ERR_CLOSING - close handlers will tidy up for us
1031 if (io.flag == COMM_ERR_CLOSING) {
1032 debugs(11, 3, "http socket closing");
1033 return;
1034 }
1035
1036 if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
1037 maybeReadVirginBody();
1038 return;
1039 }
1040
1041 // handle I/O errors
1042 if (io.flag != COMM_OK || len < 0) {
1043 debugs(11, 2, "httpReadReply: FD " << fd << ": read failure: " << xstrerror() << ".");
1044
1045 if (ignoreErrno(io.xerrno)) {
1046 flags.do_next_read = 1;
1047 } else {
1048 ErrorState *err;
1049 err = errorCon(ERR_READ_ERROR, HTTP_BAD_GATEWAY, fwd->request);
1050 err->xerrno = io.xerrno;
1051 fwd->fail(err);
1052 flags.do_next_read = 0;
1053 comm_close(fd);
1054 }
1055
1056 return;
1057 }
1058
1059 // update I/O stats
1060 if (len > 0) {
1061 readBuf->appended(len);
1062 reply_bytes_read += len;
1063 #if DELAY_POOLS
1064
1065 DelayId delayId = entry->mem_obj->mostBytesAllowed();
1066 delayId.bytesIn(len);
1067 #endif
1068
1069 kb_incr(&statCounter.server.all.kbytes_in, len);
1070 kb_incr(&statCounter.server.http.kbytes_in, len);
1071 IOStats.Http.reads++;
1072
1073 for (clen = len - 1, bin = 0; clen; bin++)
1074 clen >>= 1;
1075
1076 IOStats.Http.read_hist[bin]++;
1077
1078 // update peer response time stats (%<pt)
1079 const timeval &sent = orig_request->hier.peer_http_request_sent;
1080 orig_request->hier.peer_response_time =
1081 sent.tv_sec ? tvSubMsec(sent, current_time) : -1;
1082 }
1083
1084 /** \par
1085 * Here the RFC says we should ignore whitespace between replies, but we can't as
1086 * doing so breaks HTTP/0.9 replies beginning with witespace, and in addition
1087 * the response splitting countermeasures is extremely likely to trigger on this,
1088 * not allowing connection reuse in the first place.
1089 */
1090 #if DONT_DO_THIS
1091 if (!flags.headers_parsed && len > 0 && fd_table[fd].uses > 1) {
1092 /* Skip whitespace between replies */
1093
1094 while (len > 0 && xisspace(*buf))
1095 xmemmove(buf, buf + 1, len--);
1096
1097 if (len == 0) {
1098 /* Continue to read... */
1099 /* Timeout NOT increased. This whitespace was from previous reply */
1100 flags.do_next_read = 1;
1101 maybeReadVirginBody();
1102 return;
1103 }
1104 }
1105
1106 #endif
1107
1108 if (len == 0) { // reached EOF?
1109 eof = 1;
1110 flags.do_next_read = 0;
1111 }
1112
1113 if (!flags.headers_parsed) { // have not parsed headers yet?
1114 PROF_start(HttpStateData_processReplyHeader);
1115 processReplyHeader();
1116 PROF_stop(HttpStateData_processReplyHeader);
1117
1118 if (!continueAfterParsingHeader()) // parsing error or need more data
1119 return; // TODO: send errors to ICAP
1120
1121 adaptOrFinalizeReply();
1122 }
1123
1124 // kick more reads if needed and/or process the response body, if any
1125 PROF_start(HttpStateData_processReplyBody);
1126 processReplyBody(); // may call serverComplete()
1127 PROF_stop(HttpStateData_processReplyBody);
1128 }
1129
1130 /**
1131 \retval true if we can continue with processing the body or doing ICAP.
1132 */
1133 bool
1134 HttpStateData::continueAfterParsingHeader()
1135 {
1136 if (!flags.headers_parsed && !eof) {
1137 debugs(11, 9, HERE << "needs more at " << readBuf->contentSize());
1138 flags.do_next_read = 1;
1139 /** \retval false If we have not finished parsing the headers and may get more data.
1140 * Schedules more reads to retrieve the missing data.
1141 */
1142 maybeReadVirginBody(); // schedules all kinds of reads; TODO: rename
1143 return false;
1144 }
1145
1146 /** If we are done with parsing, check for errors */
1147
1148 err_type error = ERR_NONE;
1149
1150 if (flags.headers_parsed) { // parsed headers, possibly with errors
1151 // check for header parsing errors
1152 if (HttpReply *vrep = virginReply()) {
1153 const http_status s = vrep->sline.status;
1154 const HttpVersion &v = vrep->sline.version;
1155 if (s == HTTP_INVALID_HEADER && v != HttpVersion(0,9)) {
1156 debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: Bad header encountered from " << entry->url() << " AKA " << orig_request->GetHost() << orig_request->urlpath.termedBuf() );
1157 error = ERR_INVALID_RESP;
1158 } else if (s == HTTP_HEADER_TOO_LARGE) {
1159 fwd->dontRetry(true);
1160 error = ERR_TOO_BIG;
1161 } else {
1162 return true; // done parsing, got reply, and no error
1163 }
1164 } else {
1165 // parsed headers but got no reply
1166 debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: No reply at all for " << entry->url() << " AKA " << orig_request->GetHost() << orig_request->urlpath.termedBuf() );
1167 error = ERR_INVALID_RESP;
1168 }
1169 } else {
1170 assert(eof);
1171 if (readBuf->hasContent()) {
1172 error = ERR_INVALID_RESP;
1173 debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: Headers did not parse at all for " << entry->url() << " AKA " << orig_request->GetHost() << orig_request->urlpath.termedBuf() );
1174 } else {
1175 error = ERR_ZERO_SIZE_OBJECT;
1176 debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: No object data received for " << entry->url() << " AKA " << orig_request->GetHost() << orig_request->urlpath.termedBuf() );
1177 }
1178 }
1179
1180 assert(error != ERR_NONE);
1181 entry->reset();
1182 fwd->fail(errorCon(error, HTTP_BAD_GATEWAY, fwd->request));
1183 flags.do_next_read = 0;
1184 comm_close(fd);
1185 return false; // quit on error
1186 }
1187
1188 /** truncate what we read if we read too much so that writeReplyBody()
1189 writes no more than what we should have read */
1190 void
1191 HttpStateData::truncateVirginBody()
1192 {
1193 assert(flags.headers_parsed);
1194
1195 HttpReply *vrep = virginReply();
1196 int64_t clen = -1;
1197 if (!vrep->expectingBody(request->method, clen) || clen < 0)
1198 return; // no body or a body of unknown size, including chunked
1199
1200 const int64_t body_bytes_read = reply_bytes_read - header_bytes_read;
1201 if (body_bytes_read - body_bytes_truncated <= clen)
1202 return; // we did not read too much or already took care of the extras
1203
1204 if (const int64_t extras = body_bytes_read - body_bytes_truncated - clen) {
1205 // server sent more that the advertised content length
1206 debugs(11,5, HERE << "body_bytes_read=" << body_bytes_read <<
1207 " clen=" << clen << '/' << vrep->content_length <<
1208 " body_bytes_truncated=" << body_bytes_truncated << '+' << extras);
1209
1210 readBuf->truncate(extras);
1211 body_bytes_truncated += extras;
1212 }
1213 }
1214
1215 /**
1216 * Call this when there is data from the origin server
1217 * which should be sent to either StoreEntry, or to ICAP...
1218 */
1219 void
1220 HttpStateData::writeReplyBody()
1221 {
1222 truncateVirginBody(); // if needed
1223 const char *data = readBuf->content();
1224 int len = readBuf->contentSize();
1225 addVirginReplyBody(data, len);
1226 readBuf->consume(len);
1227 }
1228
1229 bool
1230 HttpStateData::decodeAndWriteReplyBody()
1231 {
1232 const char *data = NULL;
1233 int len;
1234 bool wasThereAnException = false;
1235 assert(flags.chunked);
1236 assert(httpChunkDecoder);
1237 SQUID_ENTER_THROWING_CODE();
1238 MemBuf decodedData;
1239 decodedData.init();
1240 const bool doneParsing = httpChunkDecoder->parse(readBuf,&decodedData);
1241 len = decodedData.contentSize();
1242 data=decodedData.content();
1243 addVirginReplyBody(data, len);
1244 if (doneParsing) {
1245 lastChunk = 1;
1246 flags.do_next_read = 0;
1247 }
1248 SQUID_EXIT_THROWING_CODE(wasThereAnException);
1249 return wasThereAnException;
1250 }
1251
1252 /**
1253 * processReplyBody has two purposes:
1254 * 1 - take the reply body data, if any, and put it into either
1255 * the StoreEntry, or give it over to ICAP.
1256 * 2 - see if we made it to the end of the response (persistent
1257 * connections and such)
1258 */
1259 void
1260 HttpStateData::processReplyBody()
1261 {
1262 AsyncCall::Pointer call;
1263 IpAddress client_addr;
1264 bool ispinned = false;
1265
1266 if (!flags.headers_parsed) {
1267 flags.do_next_read = 1;
1268 maybeReadVirginBody();
1269 return;
1270 }
1271
1272 #if USE_ADAPTATION
1273 debugs(11,5, HERE << "adaptationAccessCheckPending=" << adaptationAccessCheckPending);
1274 if (adaptationAccessCheckPending)
1275 return;
1276
1277 #endif
1278
1279 /*
1280 * At this point the reply headers have been parsed and consumed.
1281 * That means header content has been removed from readBuf and
1282 * it contains only body data.
1283 */
1284 if (flags.chunked) {
1285 if (!decodeAndWriteReplyBody()) {
1286 flags.do_next_read = 0;
1287 serverComplete();
1288 return;
1289 }
1290 } else
1291 writeReplyBody();
1292
1293 if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
1294 /*
1295 * The above writeReplyBody() call could ABORT this entry,
1296 * in that case, the server FD should already be closed.
1297 * there's nothing for us to do.
1298 */
1299 (void) 0;
1300 } else
1301 switch (persistentConnStatus()) {
1302 case INCOMPLETE_MSG:
1303 debugs(11, 5, "processReplyBody: INCOMPLETE_MSG");
1304 /* Wait for more data or EOF condition */
1305 if (flags.keepalive_broken) {
1306 call = NULL;
1307 commSetTimeout(fd, 10, call);
1308 } else {
1309 call = NULL;
1310 commSetTimeout(fd, Config.Timeout.read, call);
1311 }
1312
1313 flags.do_next_read = 1;
1314 break;
1315
1316 case COMPLETE_PERSISTENT_MSG:
1317 debugs(11, 5, "processReplyBody: COMPLETE_PERSISTENT_MSG");
1318 /* yes we have to clear all these! */
1319 call = NULL;
1320 commSetTimeout(fd, -1, call);
1321 flags.do_next_read = 0;
1322
1323 comm_remove_close_handler(fd, closeHandler);
1324 closeHandler = NULL;
1325 fwd->unregister(fd);
1326
1327 if (orig_request->flags.spoof_client_ip)
1328 client_addr = orig_request->client_addr;
1329
1330
1331 if (request->flags.pinned) {
1332 ispinned = true;
1333 } else if (request->flags.connection_auth && request->flags.auth_sent) {
1334 ispinned = true;
1335 }
1336
1337 if (orig_request->pinnedConnection() && ispinned) {
1338 orig_request->pinnedConnection()->pinConnection(fd, orig_request, _peer,
1339 (request->flags.connection_auth != 0));
1340 } else {
1341 fwd->pconnPush(fd, _peer, request, orig_request->GetHost(), client_addr);
1342 }
1343
1344 fd = -1;
1345
1346 serverComplete();
1347 return;
1348
1349 case COMPLETE_NONPERSISTENT_MSG:
1350 debugs(11, 5, "processReplyBody: COMPLETE_NONPERSISTENT_MSG");
1351 serverComplete();
1352 return;
1353 }
1354
1355 maybeReadVirginBody();
1356 }
1357
1358 void
1359 HttpStateData::maybeReadVirginBody()
1360 {
1361 // we may need to grow the buffer if headers do not fit
1362 const int minRead = flags.headers_parsed ? 0 :1024;
1363 const int read_size = replyBodySpace(*readBuf, minRead);
1364
1365 debugs(11,9, HERE << (flags.do_next_read ? "may" : "wont") <<
1366 " read up to " << read_size << " bytes from FD " << fd);
1367
1368 /*
1369 * why <2? Because delayAwareRead() won't actually read if
1370 * you ask it to read 1 byte. The delayed read request
1371 * just gets re-queued until the client side drains, then
1372 * the I/O thread hangs. Better to not register any read
1373 * handler until we get a notification from someone that
1374 * its okay to read again.
1375 */
1376 if (read_size < 2)
1377 return;
1378
1379 if (flags.do_next_read) {
1380 flags.do_next_read = 0;
1381 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
1382 entry->delayAwareRead(fd, readBuf->space(read_size), read_size,
1383 asyncCall(11, 5, "HttpStateData::readReply",
1384 Dialer(this, &HttpStateData::readReply)));
1385 }
1386 }
1387
1388 /*
1389 * This will be called when request write is complete.
1390 */
1391 void
1392 HttpStateData::sendComplete(const CommIoCbParams &io)
1393 {
1394 debugs(11, 5, "httpSendComplete: FD " << fd << ": size " << io.size << ": errflag " << io.flag << ".");
1395 #if URL_CHECKSUM_DEBUG
1396
1397 entry->mem_obj->checkUrlChecksum();
1398 #endif
1399
1400 if (io.size > 0) {
1401 fd_bytes(fd, io.size, FD_WRITE);
1402 kb_incr(&statCounter.server.all.kbytes_out, io.size);
1403 kb_incr(&statCounter.server.http.kbytes_out, io.size);
1404 }
1405
1406 if (io.flag == COMM_ERR_CLOSING)
1407 return;
1408
1409 if (io.flag) {
1410 ErrorState *err;
1411 err = errorCon(ERR_WRITE_ERROR, HTTP_BAD_GATEWAY, fwd->request);
1412 err->xerrno = io.xerrno;
1413 fwd->fail(err);
1414 comm_close(fd);
1415 return;
1416 }
1417
1418 /*
1419 * Set the read timeout here because it hasn't been set yet.
1420 * We only set the read timeout after the request has been
1421 * fully written to the server-side. If we start the timeout
1422 * after connection establishment, then we are likely to hit
1423 * the timeout for POST/PUT requests that have very large
1424 * request bodies.
1425 */
1426 typedef CommCbMemFunT<HttpStateData, CommTimeoutCbParams> TimeoutDialer;
1427 AsyncCall::Pointer timeoutCall = asyncCall(11, 5, "HttpStateData::httpTimeout",
1428 TimeoutDialer(this,&HttpStateData::httpTimeout));
1429
1430 commSetTimeout(fd, Config.Timeout.read, timeoutCall);
1431
1432 flags.request_sent = 1;
1433
1434 orig_request->hier.peer_http_request_sent = current_time;
1435 }
1436
1437 // Close the HTTP server connection. Used by serverComplete().
1438 void
1439 HttpStateData::closeServer()
1440 {
1441 debugs(11,5, HERE << "closing HTTP server FD " << fd << " this " << this);
1442
1443 if (fd >= 0) {
1444 fwd->unregister(fd);
1445 comm_remove_close_handler(fd, closeHandler);
1446 closeHandler = NULL;
1447 comm_close(fd);
1448 fd = -1;
1449 }
1450 }
1451
1452 bool
1453 HttpStateData::doneWithServer() const
1454 {
1455 return fd < 0;
1456 }
1457
1458
1459 /*
1460 * Fixup authentication request headers for special cases
1461 */
1462 static void
1463 httpFixupAuthentication(HttpRequest * request, HttpRequest * orig_request, const HttpHeader * hdr_in, HttpHeader * hdr_out, http_state_flags flags)
1464 {
1465 http_hdr_type header = flags.originpeer ? HDR_AUTHORIZATION : HDR_PROXY_AUTHORIZATION;
1466
1467 /* Nothing to do unless we are forwarding to a peer */
1468 if (!request->flags.proxying)
1469 return;
1470
1471 /* Needs to be explicitly enabled */
1472 if (!orig_request->peer_login)
1473 return;
1474
1475 /* Maybe already dealt with? */
1476 if (hdr_out->has(header))
1477 return;
1478
1479 /* Nothing to do here for PASSTHRU */
1480 if (strcmp(orig_request->peer_login, "PASSTHRU") == 0)
1481 return;
1482
1483 /* PROXYPASS is a special case, single-signon to servers with the proxy password (basic only) */
1484 if (flags.originpeer && strcmp(orig_request->peer_login, "PROXYPASS") == 0 && hdr_in->has(HDR_PROXY_AUTHORIZATION)) {
1485 const char *auth = hdr_in->getStr(HDR_PROXY_AUTHORIZATION);
1486
1487 if (auth && strncasecmp(auth, "basic ", 6) == 0) {
1488 hdr_out->putStr(header, auth);
1489 return;
1490 }
1491 }
1492
1493 /* Special mode to pass the username to the upstream cache */
1494 if (*orig_request->peer_login == '*') {
1495 char loginbuf[256];
1496 const char *username = "-";
1497
1498 if (orig_request->extacl_user.size())
1499 username = orig_request->extacl_user.termedBuf();
1500 else if (orig_request->auth_user_request)
1501 username = orig_request->auth_user_request->username();
1502
1503 snprintf(loginbuf, sizeof(loginbuf), "%s%s", username, orig_request->peer_login + 1);
1504
1505 httpHeaderPutStrf(hdr_out, header, "Basic %s",
1506 base64_encode(loginbuf));
1507 return;
1508 }
1509
1510 /* external_acl provided credentials */
1511 if (orig_request->extacl_user.size() && orig_request->extacl_passwd.size() &&
1512 (strcmp(orig_request->peer_login, "PASS") == 0 ||
1513 strcmp(orig_request->peer_login, "PROXYPASS") == 0)) {
1514 char loginbuf[256];
1515 snprintf(loginbuf, sizeof(loginbuf), SQUIDSTRINGPH ":" SQUIDSTRINGPH,
1516 SQUIDSTRINGPRINT(orig_request->extacl_user),
1517 SQUIDSTRINGPRINT(orig_request->extacl_passwd));
1518 httpHeaderPutStrf(hdr_out, header, "Basic %s",
1519 base64_encode(loginbuf));
1520 return;
1521 }
1522
1523 /* Kerberos login to peer */
1524 #if HAVE_KRB5 && HAVE_GSSAPI
1525 if (strncmp(orig_request->peer_login, "NEGOTIATE",strlen("NEGOTIATE")) == 0) {
1526 char *Token=NULL;
1527 char *PrincipalName=NULL,*p;
1528 if ((p=strchr(orig_request->peer_login,':')) != NULL ) {
1529 PrincipalName=++p;
1530 }
1531 Token = peer_proxy_negotiate_auth(PrincipalName,request->peer_host);
1532 if (Token) {
1533 httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Negotiate %s",Token);
1534 }
1535 return;
1536 }
1537 #endif /* HAVE_KRB5 && HAVE_GSSAPI */
1538
1539 httpHeaderPutStrf(hdr_out, header, "Basic %s",
1540 base64_encode(orig_request->peer_login));
1541 return;
1542 }
1543
1544 /*
1545 * build request headers and append them to a given MemBuf
1546 * used by buildRequestPrefix()
1547 * note: initialised the HttpHeader, the caller is responsible for Clean()-ing
1548 */
1549 void
1550 HttpStateData::httpBuildRequestHeader(HttpRequest * request,
1551 HttpRequest * orig_request,
1552 StoreEntry * entry,
1553 HttpHeader * hdr_out,
1554 http_state_flags flags)
1555 {
1556 /* building buffer for complex strings */
1557 #define BBUF_SZ (MAX_URL+32)
1558 LOCAL_ARRAY(char, bbuf, BBUF_SZ);
1559 LOCAL_ARRAY(char, ntoabuf, MAX_IPSTRLEN);
1560 const HttpHeader *hdr_in = &orig_request->header;
1561 const HttpHeaderEntry *e = NULL;
1562 HttpHeaderPos pos = HttpHeaderInitPos;
1563 assert (hdr_out->owner == hoRequest);
1564
1565 /* append our IMS header */
1566 if (request->lastmod > -1)
1567 hdr_out->putTime(HDR_IF_MODIFIED_SINCE, request->lastmod);
1568
1569 bool we_do_ranges = decideIfWeDoRanges (orig_request);
1570
1571 String strConnection (hdr_in->getList(HDR_CONNECTION));
1572
1573 while ((e = hdr_in->getEntry(&pos)))
1574 copyOneHeaderFromClientsideRequestToUpstreamRequest(e, strConnection, request, orig_request, hdr_out, we_do_ranges, flags);
1575
1576 /* Abstraction break: We should interpret multipart/byterange responses
1577 * into offset-length data, and this works around our inability to do so.
1578 */
1579 if (!we_do_ranges && orig_request->multipartRangeRequest()) {
1580 /* don't cache the result */
1581 orig_request->flags.cachable = 0;
1582 /* pretend it's not a range request */
1583 delete orig_request->range;
1584 orig_request->range = NULL;
1585 orig_request->flags.range = 0;
1586 }
1587
1588 /* append Via */
1589 if (Config.onoff.via) {
1590 String strVia;
1591 strVia = hdr_in->getList(HDR_VIA);
1592 snprintf(bbuf, BBUF_SZ, "%d.%d %s",
1593 orig_request->http_ver.major,
1594 orig_request->http_ver.minor, ThisCache);
1595 strListAdd(&strVia, bbuf, ',');
1596 hdr_out->putStr(HDR_VIA, strVia.termedBuf());
1597 strVia.clean();
1598 }
1599
1600 #if USE_SQUID_ESI
1601 if (orig_request->flags.accelerated) {
1602 /* Append Surrogate-Capabilities */
1603 String strSurrogate (hdr_in->getList(HDR_SURROGATE_CAPABILITY));
1604 snprintf(bbuf, BBUF_SZ, "%s=\"Surrogate/1.0 ESI/1.0\"",
1605 Config.Accel.surrogate_id);
1606 strListAdd(&strSurrogate, bbuf, ',');
1607 hdr_out->putStr(HDR_SURROGATE_CAPABILITY, strSurrogate.termedBuf());
1608 }
1609 #endif
1610
1611 /** \pre Handle X-Forwarded-For */
1612 if (strcmp(opt_forwarded_for, "delete") != 0) {
1613
1614 String strFwd = hdr_in->getList(HDR_X_FORWARDED_FOR);
1615
1616 if (strFwd.size() > 65536/2) {
1617 // There is probably a forwarding loop with Via detection disabled.
1618 // If we do nothing, String will assert on overflow soon.
1619 // TODO: Terminate all transactions with huge XFF?
1620 strFwd = "error";
1621
1622 static int warnedCount = 0;
1623 if (warnedCount++ < 100) {
1624 const char *url = entry ? entry->url() : urlCanonical(orig_request);
1625 debugs(11, 1, "Warning: likely forwarding loop with " << url);
1626 }
1627 }
1628
1629 if (strcmp(opt_forwarded_for, "on") == 0) {
1630 /** If set to ON - append client IP or 'unknown'. */
1631 if ( orig_request->client_addr.IsNoAddr() )
1632 strListAdd(&strFwd, "unknown", ',');
1633 else
1634 strListAdd(&strFwd, orig_request->client_addr.NtoA(ntoabuf, MAX_IPSTRLEN), ',');
1635 } else if (strcmp(opt_forwarded_for, "off") == 0) {
1636 /** If set to OFF - append 'unknown'. */
1637 strListAdd(&strFwd, "unknown", ',');
1638 } else if (strcmp(opt_forwarded_for, "transparent") == 0) {
1639 /** If set to TRANSPARENT - pass through unchanged. */
1640 } else if (strcmp(opt_forwarded_for, "truncate") == 0) {
1641 /** If set to TRUNCATE - drop existing list and replace with client IP or 'unknown'. */
1642 if ( orig_request->client_addr.IsNoAddr() )
1643 strFwd = "unknown";
1644 else
1645 strFwd = orig_request->client_addr.NtoA(ntoabuf, MAX_IPSTRLEN);
1646 }
1647 if (strFwd.size() > 0)
1648 hdr_out->putStr(HDR_X_FORWARDED_FOR, strFwd.termedBuf());
1649 }
1650 /** If set to DELETE - do not copy through. */
1651
1652 /* append Host if not there already */
1653 if (!hdr_out->has(HDR_HOST)) {
1654 if (orig_request->peer_domain) {
1655 hdr_out->putStr(HDR_HOST, orig_request->peer_domain);
1656 } else if (orig_request->port == urlDefaultPort(orig_request->protocol)) {
1657 /* use port# only if not default */
1658 hdr_out->putStr(HDR_HOST, orig_request->GetHost());
1659 } else {
1660 httpHeaderPutStrf(hdr_out, HDR_HOST, "%s:%d",
1661 orig_request->GetHost(),
1662 (int) orig_request->port);
1663 }
1664 }
1665
1666 /* append Authorization if known in URL, not in header and going direct */
1667 if (!hdr_out->has(HDR_AUTHORIZATION)) {
1668 if (!request->flags.proxying && *request->login) {
1669 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1670 base64_encode(request->login));
1671 }
1672 }
1673
1674 /* Fixup (Proxy-)Authorization special cases. Plain relaying dealt with above */
1675 httpFixupAuthentication(request, orig_request, hdr_in, hdr_out, flags);
1676
1677 /* append Cache-Control, add max-age if not there already */
1678 {
1679 HttpHdrCc *cc = hdr_in->getCc();
1680
1681 if (!cc)
1682 cc = httpHdrCcCreate();
1683
1684 #if 0 /* see bug 2330 */
1685 /* Set no-cache if determined needed but not found */
1686 if (orig_request->flags.nocache)
1687 EBIT_SET(cc->mask, CC_NO_CACHE);
1688 #endif
1689
1690 /* Add max-age only without no-cache */
1691 if (!EBIT_TEST(cc->mask, CC_MAX_AGE) && !EBIT_TEST(cc->mask, CC_NO_CACHE)) {
1692 const char *url =
1693 entry ? entry->url() : urlCanonical(orig_request);
1694 httpHdrCcSetMaxAge(cc, getMaxAge(url));
1695
1696 if (request->urlpath.size())
1697 assert(strstr(url, request->urlpath.termedBuf()));
1698 }
1699
1700 /* Enforce sibling relations */
1701 if (flags.only_if_cached)
1702 EBIT_SET(cc->mask, CC_ONLY_IF_CACHED);
1703
1704 hdr_out->putCc(cc);
1705
1706 httpHdrCcDestroy(cc);
1707 }
1708
1709 /* maybe append Connection: keep-alive */
1710 if (flags.keepalive) {
1711 if (flags.proxying) {
1712 hdr_out->putStr(HDR_PROXY_CONNECTION, "keep-alive");
1713 } else {
1714 hdr_out->putStr(HDR_CONNECTION, "keep-alive");
1715 }
1716 }
1717
1718 /* append Front-End-Https */
1719 if (flags.front_end_https) {
1720 if (flags.front_end_https == 1 || request->protocol == PROTO_HTTPS)
1721 hdr_out->putStr(HDR_FRONT_END_HTTPS, "On");
1722 }
1723
1724 /* Now mangle the headers. */
1725 if (Config2.onoff.mangle_request_headers)
1726 httpHdrMangleList(hdr_out, request, ROR_REQUEST);
1727
1728 strConnection.clean();
1729 }
1730
1731 /**
1732 * Decides whether a particular header may be cloned from the received Clients request
1733 * to our outgoing fetch request.
1734 */
1735 void
1736 copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, const String strConnection, HttpRequest * request, const HttpRequest * orig_request, HttpHeader * hdr_out, const int we_do_ranges, const http_state_flags flags)
1737 {
1738 debugs(11, 5, "httpBuildRequestHeader: " << e->name << ": " << e->value );
1739
1740 switch (e->id) {
1741
1742 /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid should not pass on. */
1743
1744 case HDR_PROXY_AUTHORIZATION:
1745 /** \par Proxy-Authorization:
1746 * Only pass on proxy authentication to peers for which
1747 * authentication forwarding is explicitly enabled
1748 */
1749 if (!flags.originpeer && flags.proxying && orig_request->peer_login &&
1750 (strcmp(orig_request->peer_login, "PASS") == 0 ||
1751 strcmp(orig_request->peer_login, "PROXYPASS") == 0 ||
1752 strcmp(orig_request->peer_login, "PASSTHRU") == 0)) {
1753 hdr_out->addEntry(e->clone());
1754 }
1755 break;
1756
1757 /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid does not pass on. */
1758
1759 case HDR_CONNECTION: /** \par Connection: */
1760 case HDR_TE: /** \par TE: */
1761 case HDR_KEEP_ALIVE: /** \par Keep-Alive: */
1762 case HDR_PROXY_AUTHENTICATE: /** \par Proxy-Authenticate: */
1763 case HDR_TRAILERS: /** \par Trailers: */
1764 case HDR_UPGRADE: /** \par Upgrade: */
1765 case HDR_TRANSFER_ENCODING: /** \par Transfer-Encoding: */
1766 break;
1767
1768
1769 /** \par OTHER headers I haven't bothered to track down yet. */
1770
1771 case HDR_AUTHORIZATION:
1772 /** \par WWW-Authorization:
1773 * Pass on WWW authentication */
1774
1775 if (!flags.originpeer) {
1776 hdr_out->addEntry(e->clone());
1777 } else {
1778 /** \note In accelerators, only forward authentication if enabled
1779 * (see also httpFixupAuthentication for special cases)
1780 */
1781 if (orig_request->peer_login &&
1782 (strcmp(orig_request->peer_login, "PASS") == 0 ||
1783 strcmp(orig_request->peer_login, "PASSTHRU") == 0 ||
1784 strcmp(orig_request->peer_login, "PROXYPASS") == 0)) {
1785 hdr_out->addEntry(e->clone());
1786 }
1787 }
1788
1789 break;
1790
1791 case HDR_HOST:
1792 /** \par Host:
1793 * Normally Squid rewrites the Host: header.
1794 * However, there is one case when we don't: If the URL
1795 * went through our redirector and the admin configured
1796 * 'redir_rewrites_host' to be off.
1797 */
1798 if (orig_request->peer_domain)
1799 hdr_out->putStr(HDR_HOST, orig_request->peer_domain);
1800 else if (request->flags.redirected && !Config.onoff.redir_rewrites_host)
1801 hdr_out->addEntry(e->clone());
1802 else {
1803 /* use port# only if not default */
1804
1805 if (orig_request->port == urlDefaultPort(orig_request->protocol)) {
1806 hdr_out->putStr(HDR_HOST, orig_request->GetHost());
1807 } else {
1808 httpHeaderPutStrf(hdr_out, HDR_HOST, "%s:%d",
1809 orig_request->GetHost(),
1810 (int) orig_request->port);
1811 }
1812 }
1813
1814 break;
1815
1816 case HDR_IF_MODIFIED_SINCE:
1817 /** \par If-Modified-Since:
1818 * append unless we added our own;
1819 * \note at most one client's ims header can pass through */
1820
1821 if (!hdr_out->has(HDR_IF_MODIFIED_SINCE))
1822 hdr_out->addEntry(e->clone());
1823
1824 break;
1825
1826 case HDR_MAX_FORWARDS:
1827 /** \par Max-Forwards:
1828 * pass only on TRACE or OPTIONS requests */
1829 if (orig_request->method == METHOD_TRACE || orig_request->method == METHOD_OPTIONS) {
1830 const int64_t hops = e->getInt64();
1831
1832 if (hops > 0)
1833 hdr_out->putInt64(HDR_MAX_FORWARDS, hops - 1);
1834 }
1835
1836 break;
1837
1838 case HDR_VIA:
1839 /** \par Via:
1840 * If Via is disabled then forward any received header as-is.
1841 * Otherwise leave for explicit updated addition later. */
1842
1843 if (!Config.onoff.via)
1844 hdr_out->addEntry(e->clone());
1845
1846 break;
1847
1848 case HDR_RANGE:
1849
1850 case HDR_IF_RANGE:
1851
1852 case HDR_REQUEST_RANGE:
1853 /** \par Range:, If-Range:, Request-Range:
1854 * Only pass if we accept ranges */
1855 if (!we_do_ranges)
1856 hdr_out->addEntry(e->clone());
1857
1858 break;
1859
1860 case HDR_PROXY_CONNECTION:
1861
1862 case HDR_X_FORWARDED_FOR:
1863
1864 case HDR_CACHE_CONTROL:
1865 /** \par Proxy-Connaction:, X-Forwarded-For:, Cache-Control:
1866 * handled specially by Squid, so leave off for now.
1867 * append these after the loop if needed */
1868 break;
1869
1870 case HDR_FRONT_END_HTTPS:
1871 /** \par Front-End-Https:
1872 * Pass thru only if peer is configured with front-end-https */
1873 if (!flags.front_end_https)
1874 hdr_out->addEntry(e->clone());
1875
1876 break;
1877
1878 default:
1879 /** \par default.
1880 * pass on all other header fields
1881 * which are NOT listed by the special Connection: header. */
1882
1883 if (strConnection.size()>0 && strListIsMember(&strConnection, e->name.termedBuf(), ',')) {
1884 debugs(11, 2, "'" << e->name << "' header cropped by Connection: definition");
1885 return;
1886 }
1887
1888 hdr_out->addEntry(e->clone());
1889 }
1890 }
1891
1892 bool
1893 HttpStateData::decideIfWeDoRanges (HttpRequest * orig_request)
1894 {
1895 bool result = true;
1896 /* decide if we want to do Ranges ourselves
1897 * and fetch the whole object now)
1898 * We want to handle Ranges ourselves iff
1899 * - we can actually parse client Range specs
1900 * - the specs are expected to be simple enough (e.g. no out-of-order ranges)
1901 * - reply will be cachable
1902 * (If the reply will be uncachable we have to throw it away after
1903 * serving this request, so it is better to forward ranges to
1904 * the server and fetch only the requested content)
1905 */
1906
1907 if (NULL == orig_request->range || !orig_request->flags.cachable
1908 || orig_request->range->offsetLimitExceeded() || orig_request->flags.connection_auth)
1909 result = false;
1910
1911 debugs(11, 8, "decideIfWeDoRanges: range specs: " <<
1912 orig_request->range << ", cachable: " <<
1913 orig_request->flags.cachable << "; we_do_ranges: " << result);
1914
1915 return result;
1916 }
1917
1918 /* build request prefix and append it to a given MemBuf;
1919 * return the length of the prefix */
1920 mb_size_t
1921 HttpStateData::buildRequestPrefix(HttpRequest * aRequest,
1922 HttpRequest * original_request,
1923 StoreEntry * sentry,
1924 MemBuf * mb,
1925 http_state_flags stateFlags)
1926 {
1927 const int offset = mb->size;
1928 HttpVersion httpver(1,0);
1929 mb->Printf("%s %s HTTP/%d.%d\r\n",
1930 RequestMethodStr(aRequest->method),
1931 aRequest->urlpath.size() ? aRequest->urlpath.termedBuf() : "/",
1932 httpver.major,httpver.minor);
1933 /* build and pack headers */
1934 {
1935 HttpHeader hdr(hoRequest);
1936 Packer p;
1937 httpBuildRequestHeader(aRequest, original_request, sentry, &hdr, stateFlags);
1938
1939 if (aRequest->flags.pinned && aRequest->flags.connection_auth)
1940 aRequest->flags.auth_sent = 1;
1941 else if (hdr.has(HDR_AUTHORIZATION))
1942 aRequest->flags.auth_sent = 1;
1943
1944 packerToMemInit(&p, mb);
1945 hdr.packInto(&p);
1946 hdr.clean();
1947 packerClean(&p);
1948 }
1949 /* append header terminator */
1950 mb->append(crlf, 2);
1951 return mb->size - offset;
1952 }
1953
1954 /* This will be called when connect completes. Write request. */
1955 bool
1956 HttpStateData::sendRequest()
1957 {
1958 MemBuf mb;
1959
1960 debugs(11, 5, "httpSendRequest: FD " << fd << ", request " << request << ", this " << this << ".");
1961 typedef CommCbMemFunT<HttpStateData, CommTimeoutCbParams> TimeoutDialer;
1962 AsyncCall::Pointer timeoutCall = asyncCall(11, 5, "HttpStateData::httpTimeout",
1963 TimeoutDialer(this,&HttpStateData::httpTimeout));
1964 commSetTimeout(fd, Config.Timeout.lifetime, timeoutCall);
1965 flags.do_next_read = 1;
1966 maybeReadVirginBody();
1967
1968 if (orig_request->body_pipe != NULL) {
1969 if (!startRequestBodyFlow()) // register to receive body data
1970 return false;
1971 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
1972 Dialer dialer(this, &HttpStateData::sentRequestBody);
1973 requestSender = asyncCall(11,5, "HttpStateData::sentRequestBody", dialer);
1974 } else {
1975 assert(!requestBodySource);
1976 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
1977 Dialer dialer(this, &HttpStateData::sendComplete);
1978 requestSender = asyncCall(11,5, "HttpStateData::SendComplete", dialer);
1979 }
1980
1981 if (_peer != NULL) {
1982 if (_peer->options.originserver) {
1983 flags.proxying = 0;
1984 flags.originpeer = 1;
1985 } else {
1986 flags.proxying = 1;
1987 flags.originpeer = 0;
1988 }
1989 } else {
1990 flags.proxying = 0;
1991 flags.originpeer = 0;
1992 }
1993
1994 /*
1995 * Is keep-alive okay for all request methods?
1996 */
1997 if (orig_request->flags.must_keepalive)
1998 flags.keepalive = 1;
1999 else if (!Config.onoff.server_pconns)
2000 flags.keepalive = 0;
2001 else if (_peer == NULL)
2002 flags.keepalive = 1;
2003 else if (_peer->stats.n_keepalives_sent < 10)
2004 flags.keepalive = 1;
2005 else if ((double) _peer->stats.n_keepalives_recv /
2006 (double) _peer->stats.n_keepalives_sent > 0.50)
2007 flags.keepalive = 1;
2008
2009 if (_peer) {
2010 if (neighborType(_peer, request) == PEER_SIBLING &&
2011 !_peer->options.allow_miss)
2012 flags.only_if_cached = 1;
2013
2014 flags.front_end_https = _peer->front_end_https;
2015 }
2016
2017 mb.init();
2018 request->peer_host=_peer?_peer->host:NULL;
2019 buildRequestPrefix(request, orig_request, entry, &mb, flags);
2020 debugs(11, 6, "httpSendRequest: FD " << fd << ":\n" << mb.buf);
2021 comm_write_mbuf(fd, &mb, requestSender);
2022
2023 return true;
2024 }
2025
2026 void
2027 httpStart(FwdState *fwd)
2028 {
2029 debugs(11, 3, "httpStart: \"" << RequestMethodStr(fwd->request->method) << " " << fwd->entry->url() << "\"" );
2030 HttpStateData *httpState = new HttpStateData(fwd);
2031
2032 if (!httpState->sendRequest()) {
2033 debugs(11, 3, "httpStart: aborted");
2034 delete httpState;
2035 return;
2036 }
2037
2038 statCounter.server.all.requests++;
2039 statCounter.server.http.requests++;
2040
2041 /*
2042 * We used to set the read timeout here, but not any more.
2043 * Now its set in httpSendComplete() after the full request,
2044 * including request body, has been written to the server.
2045 */
2046 }
2047
2048 void
2049 HttpStateData::doneSendingRequestBody()
2050 {
2051 debugs(11,5, HERE << "doneSendingRequestBody: FD " << fd);
2052
2053 #if HTTP_VIOLATIONS
2054 if (Config.accessList.brokenPosts) {
2055 ACLFilledChecklist ch(Config.accessList.brokenPosts, request, NULL);
2056 if (!ch.fastCheck()) {
2057 debugs(11, 5, "doneSendingRequestBody: didn't match brokenPosts");
2058 CommIoCbParams io(NULL);
2059 io.fd=fd;
2060 io.flag=COMM_OK;
2061 sendComplete(io);
2062 } else {
2063 debugs(11, 2, "doneSendingRequestBody: matched brokenPosts");
2064 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
2065 Dialer dialer(this, &HttpStateData::sendComplete);
2066 AsyncCall::Pointer call= asyncCall(11,5, "HttpStateData::SendComplete", dialer);
2067 comm_write(fd, "\r\n", 2, call);
2068 }
2069 return;
2070 }
2071 debugs(11, 5, "doneSendingRequestBody: No brokenPosts list");
2072 #endif /* HTTP_VIOLATIONS */
2073
2074 CommIoCbParams io(NULL);
2075 io.fd=fd;
2076 io.flag=COMM_OK;
2077 sendComplete(io);
2078 }
2079
2080 // more origin request body data is available
2081 void
2082 HttpStateData::handleMoreRequestBodyAvailable()
2083 {
2084 if (eof || fd < 0) {
2085 // XXX: we should check this condition in other callbacks then!
2086 // TODO: Check whether this can actually happen: We should unsubscribe
2087 // as a body consumer when the above condition(s) are detected.
2088 debugs(11, 1, HERE << "Transaction aborted while reading HTTP body");
2089 return;
2090 }
2091
2092 assert(requestBodySource != NULL);
2093
2094 if (requestBodySource->buf().hasContent()) {
2095 // XXX: why does not this trigger a debug message on every request?
2096
2097 if (flags.headers_parsed && !flags.abuse_detected) {
2098 flags.abuse_detected = 1;
2099 debugs(11, 1, "http handleMoreRequestBodyAvailable: Likely proxy abuse detected '" << orig_request->client_addr << "' -> '" << entry->url() << "'" );
2100
2101 if (virginReply()->sline.status == HTTP_INVALID_HEADER) {
2102 comm_close(fd);
2103 return;
2104 }
2105 }
2106 }
2107
2108 HttpStateData::handleMoreRequestBodyAvailable();
2109 }
2110
2111 // premature end of the request body
2112 void
2113 HttpStateData::handleRequestBodyProducerAborted()
2114 {
2115 ServerStateData::handleRequestBodyProducerAborted();
2116 // XXX: SendComplete(COMM_ERR_CLOSING) does little. Is it enough?
2117 CommIoCbParams io(NULL);
2118 io.fd=fd;
2119 io.flag=COMM_ERR_CLOSING;
2120 sendComplete(io);
2121 }
2122
2123 // called when we wrote request headers(!) or a part of the body
2124 void
2125 HttpStateData::sentRequestBody(const CommIoCbParams &io)
2126 {
2127 if (io.size > 0)
2128 kb_incr(&statCounter.server.http.kbytes_out, io.size);
2129
2130 ServerStateData::sentRequestBody(io);
2131 }
2132
2133 // Quickly abort the transaction
2134 // TODO: destruction should be sufficient as the destructor should cleanup,
2135 // including canceling close handlers
2136 void
2137 HttpStateData::abortTransaction(const char *reason)
2138 {
2139 debugs(11,5, HERE << "aborting transaction for " << reason <<
2140 "; FD " << fd << ", this " << this);
2141
2142 if (fd >= 0) {
2143 comm_close(fd);
2144 return;
2145 }
2146
2147 fwd->handleUnregisteredServerEnd();
2148 deleteThis("HttpStateData::abortTransaction");
2149 }
2150
2151 #if DEAD_CODE
2152 void
2153 httpBuildVersion(HttpVersion * version, unsigned int major, unsigned int minor)
2154 {
2155 version->major = major;
2156 version->minor = minor;
2157 }
2158 #endif
2159
2160 HttpRequest *
2161 HttpStateData::originalRequest()
2162 {
2163 return orig_request;
2164 }