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