]> git.ipfire.org Git - thirdparty/squid.git/blob - src/http.cc
Author: Alex Rousskov <rousskov@measurement-factory.com>
[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 // we may need to grow the buffer if headers do not fit
1354 const int minRead = flags.headers_parsed ? 0 : 1024;
1355 const int read_sz = replyBodySpace(*readBuf, minRead);
1356
1357 debugs(11,9, HERE << (flags.do_next_read ? "may" : "wont") <<
1358 " read up to " << read_sz << " bytes from FD " << fd);
1359
1360 /*
1361 * why <2? Because delayAwareRead() won't actually read if
1362 * you ask it to read 1 byte. The delayed read request
1363 * just gets re-queued until the client side drains, then
1364 * the I/O thread hangs. Better to not register any read
1365 * handler until we get a notification from someone that
1366 * its okay to read again.
1367 */
1368 if (read_sz < 2)
1369 return;
1370
1371 if (flags.do_next_read) {
1372 flags.do_next_read = 0;
1373 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
1374 entry->delayAwareRead(fd, readBuf->space(read_sz), read_sz,
1375 asyncCall(11, 5, "HttpStateData::readReply",
1376 Dialer(this, &HttpStateData::readReply)));
1377 }
1378 }
1379
1380 /*
1381 * This will be called when request write is complete.
1382 */
1383 void
1384 HttpStateData::sendComplete(const CommIoCbParams &io)
1385 {
1386 debugs(11, 5, "httpSendComplete: FD " << fd << ": size " << io.size << ": errflag " << io.flag << ".");
1387 #if URL_CHECKSUM_DEBUG
1388
1389 entry->mem_obj->checkUrlChecksum();
1390 #endif
1391
1392 if (io.size > 0) {
1393 fd_bytes(fd, io.size, FD_WRITE);
1394 kb_incr(&statCounter.server.all.kbytes_out, io.size);
1395 kb_incr(&statCounter.server.http.kbytes_out, io.size);
1396 }
1397
1398 if (io.flag == COMM_ERR_CLOSING)
1399 return;
1400
1401 if (io.flag) {
1402 ErrorState *err;
1403 err = errorCon(ERR_WRITE_ERROR, HTTP_BAD_GATEWAY, fwd->request);
1404 err->xerrno = io.xerrno;
1405 fwd->fail(err);
1406 comm_close(fd);
1407 return;
1408 }
1409
1410 /*
1411 * Set the read timeout here because it hasn't been set yet.
1412 * We only set the read timeout after the request has been
1413 * fully written to the server-side. If we start the timeout
1414 * after connection establishment, then we are likely to hit
1415 * the timeout for POST/PUT requests that have very large
1416 * request bodies.
1417 */
1418 typedef CommCbMemFunT<HttpStateData, CommTimeoutCbParams> TimeoutDialer;
1419 AsyncCall::Pointer timeoutCall = asyncCall(11, 5, "HttpStateData::httpTimeout",
1420 TimeoutDialer(this,&HttpStateData::httpTimeout));
1421
1422 commSetTimeout(fd, Config.Timeout.read, timeoutCall);
1423
1424 flags.request_sent = 1;
1425
1426 orig_request->hier.peer_http_request_sent = current_time;
1427 }
1428
1429 // Close the HTTP server connection. Used by serverComplete().
1430 void
1431 HttpStateData::closeServer()
1432 {
1433 debugs(11,5, HERE << "closing HTTP server FD " << fd << " this " << this);
1434
1435 if (fd >= 0) {
1436 fwd->unregister(fd);
1437 comm_remove_close_handler(fd, closeHandler);
1438 closeHandler = NULL;
1439 comm_close(fd);
1440 fd = -1;
1441 }
1442 }
1443
1444 bool
1445 HttpStateData::doneWithServer() const
1446 {
1447 return fd < 0;
1448 }
1449
1450
1451 /*
1452 * Fixup authentication request headers for special cases
1453 */
1454 static void
1455 httpFixupAuthentication(HttpRequest * request, HttpRequest * orig_request, const HttpHeader * hdr_in, HttpHeader * hdr_out, http_state_flags flags)
1456 {
1457 http_hdr_type header = flags.originpeer ? HDR_AUTHORIZATION : HDR_PROXY_AUTHORIZATION;
1458
1459 /* Nothing to do unless we are forwarding to a peer */
1460 if (!request->flags.proxying)
1461 return;
1462
1463 /* Needs to be explicitly enabled */
1464 if (!orig_request->peer_login)
1465 return;
1466
1467 /* Maybe already dealt with? */
1468 if (hdr_out->has(header))
1469 return;
1470
1471 /* Nothing to do here for PASSTHRU */
1472 if (strcmp(orig_request->peer_login, "PASSTHRU") == 0)
1473 return;
1474
1475 /* PROXYPASS is a special case, single-signon to servers with the proxy password (basic only) */
1476 if (flags.originpeer && strcmp(orig_request->peer_login, "PROXYPASS") == 0 && hdr_in->has(HDR_PROXY_AUTHORIZATION)) {
1477 const char *auth = hdr_in->getStr(HDR_PROXY_AUTHORIZATION);
1478
1479 if (auth && strncasecmp(auth, "basic ", 6) == 0) {
1480 hdr_out->putStr(header, auth);
1481 return;
1482 }
1483 }
1484
1485 /* Special mode to pass the username to the upstream cache */
1486 if (*orig_request->peer_login == '*') {
1487 char loginbuf[256];
1488 const char *username = "-";
1489
1490 if (orig_request->extacl_user.size())
1491 username = orig_request->extacl_user.termedBuf();
1492 else if (orig_request->auth_user_request)
1493 username = orig_request->auth_user_request->username();
1494
1495 snprintf(loginbuf, sizeof(loginbuf), "%s%s", username, orig_request->peer_login + 1);
1496
1497 httpHeaderPutStrf(hdr_out, header, "Basic %s",
1498 base64_encode(loginbuf));
1499 return;
1500 }
1501
1502 /* external_acl provided credentials */
1503 if (orig_request->extacl_user.size() && orig_request->extacl_passwd.size() &&
1504 (strcmp(orig_request->peer_login, "PASS") == 0 ||
1505 strcmp(orig_request->peer_login, "PROXYPASS") == 0)) {
1506 char loginbuf[256];
1507 snprintf(loginbuf, sizeof(loginbuf), SQUIDSTRINGPH ":" SQUIDSTRINGPH,
1508 SQUIDSTRINGPRINT(orig_request->extacl_user),
1509 SQUIDSTRINGPRINT(orig_request->extacl_passwd));
1510 httpHeaderPutStrf(hdr_out, header, "Basic %s",
1511 base64_encode(loginbuf));
1512 return;
1513 }
1514
1515 /* Kerberos login to peer */
1516 #if HAVE_KRB5 && HAVE_GSSAPI
1517 if (strncmp(orig_request->peer_login, "NEGOTIATE",strlen("NEGOTIATE")) == 0) {
1518 char *Token=NULL;
1519 char *PrincipalName=NULL,*p;
1520 if ((p=strchr(orig_request->peer_login,':')) != NULL ) {
1521 PrincipalName=++p;
1522 }
1523 Token = peer_proxy_negotiate_auth(PrincipalName,request->peer_host);
1524 if (Token) {
1525 httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Negotiate %s",Token);
1526 }
1527 return;
1528 }
1529 #endif /* HAVE_KRB5 && HAVE_GSSAPI */
1530
1531 httpHeaderPutStrf(hdr_out, header, "Basic %s",
1532 base64_encode(orig_request->peer_login));
1533 return;
1534 }
1535
1536 /*
1537 * build request headers and append them to a given MemBuf
1538 * used by buildRequestPrefix()
1539 * note: initialised the HttpHeader, the caller is responsible for Clean()-ing
1540 */
1541 void
1542 HttpStateData::httpBuildRequestHeader(HttpRequest * request,
1543 HttpRequest * orig_request,
1544 StoreEntry * entry,
1545 HttpHeader * hdr_out,
1546 http_state_flags flags)
1547 {
1548 /* building buffer for complex strings */
1549 #define BBUF_SZ (MAX_URL+32)
1550 LOCAL_ARRAY(char, bbuf, BBUF_SZ);
1551 LOCAL_ARRAY(char, ntoabuf, MAX_IPSTRLEN);
1552 const HttpHeader *hdr_in = &orig_request->header;
1553 const HttpHeaderEntry *e = NULL;
1554 HttpHeaderPos pos = HttpHeaderInitPos;
1555 assert (hdr_out->owner == hoRequest);
1556
1557 /* append our IMS header */
1558 if (request->lastmod > -1)
1559 hdr_out->putTime(HDR_IF_MODIFIED_SINCE, request->lastmod);
1560
1561 bool we_do_ranges = decideIfWeDoRanges (orig_request);
1562
1563 String strConnection (hdr_in->getList(HDR_CONNECTION));
1564
1565 while ((e = hdr_in->getEntry(&pos)))
1566 copyOneHeaderFromClientsideRequestToUpstreamRequest(e, strConnection, request, orig_request, hdr_out, we_do_ranges, flags);
1567
1568 /* Abstraction break: We should interpret multipart/byterange responses
1569 * into offset-length data, and this works around our inability to do so.
1570 */
1571 if (!we_do_ranges && orig_request->multipartRangeRequest()) {
1572 /* don't cache the result */
1573 orig_request->flags.cachable = 0;
1574 /* pretend it's not a range request */
1575 delete orig_request->range;
1576 orig_request->range = NULL;
1577 orig_request->flags.range = 0;
1578 }
1579
1580 /* append Via */
1581 if (Config.onoff.via) {
1582 String strVia;
1583 strVia = hdr_in->getList(HDR_VIA);
1584 snprintf(bbuf, BBUF_SZ, "%d.%d %s",
1585 orig_request->http_ver.major,
1586 orig_request->http_ver.minor, ThisCache);
1587 strListAdd(&strVia, bbuf, ',');
1588 hdr_out->putStr(HDR_VIA, strVia.termedBuf());
1589 strVia.clean();
1590 }
1591
1592 #if USE_SQUID_ESI
1593 if (orig_request->flags.accelerated) {
1594 /* Append Surrogate-Capabilities */
1595 String strSurrogate (hdr_in->getList(HDR_SURROGATE_CAPABILITY));
1596 snprintf(bbuf, BBUF_SZ, "%s=\"Surrogate/1.0 ESI/1.0\"",
1597 Config.Accel.surrogate_id);
1598 strListAdd(&strSurrogate, bbuf, ',');
1599 hdr_out->putStr(HDR_SURROGATE_CAPABILITY, strSurrogate.termedBuf());
1600 }
1601 #endif
1602
1603 /** \pre Handle X-Forwarded-For */
1604 if (strcmp(opt_forwarded_for, "delete") != 0) {
1605
1606 String strFwd = hdr_in->getList(HDR_X_FORWARDED_FOR);
1607
1608 if (strFwd.size() > 65536/2) {
1609 // There is probably a forwarding loop with Via detection disabled.
1610 // If we do nothing, String will assert on overflow soon.
1611 // TODO: Terminate all transactions with huge XFF?
1612 strFwd = "error";
1613
1614 static int warnedCount = 0;
1615 if (warnedCount++ < 100) {
1616 const char *url = entry ? entry->url() : urlCanonical(orig_request);
1617 debugs(11, 1, "Warning: likely forwarding loop with " << url);
1618 }
1619 }
1620
1621 if (strcmp(opt_forwarded_for, "on") == 0) {
1622 /** If set to ON - append client IP or 'unknown'. */
1623 if ( orig_request->client_addr.IsNoAddr() )
1624 strListAdd(&strFwd, "unknown", ',');
1625 else
1626 strListAdd(&strFwd, orig_request->client_addr.NtoA(ntoabuf, MAX_IPSTRLEN), ',');
1627 } else if (strcmp(opt_forwarded_for, "off") == 0) {
1628 /** If set to OFF - append 'unknown'. */
1629 strListAdd(&strFwd, "unknown", ',');
1630 } else if (strcmp(opt_forwarded_for, "transparent") == 0) {
1631 /** If set to TRANSPARENT - pass through unchanged. */
1632 } else if (strcmp(opt_forwarded_for, "truncate") == 0) {
1633 /** If set to TRUNCATE - drop existing list and replace with client IP or 'unknown'. */
1634 if ( orig_request->client_addr.IsNoAddr() )
1635 strFwd = "unknown";
1636 else
1637 strFwd = orig_request->client_addr.NtoA(ntoabuf, MAX_IPSTRLEN);
1638 }
1639 if (strFwd.size() > 0)
1640 hdr_out->putStr(HDR_X_FORWARDED_FOR, strFwd.termedBuf());
1641 }
1642 /** If set to DELETE - do not copy through. */
1643
1644 /* append Host if not there already */
1645 if (!hdr_out->has(HDR_HOST)) {
1646 if (orig_request->peer_domain) {
1647 hdr_out->putStr(HDR_HOST, orig_request->peer_domain);
1648 } else if (orig_request->port == urlDefaultPort(orig_request->protocol)) {
1649 /* use port# only if not default */
1650 hdr_out->putStr(HDR_HOST, orig_request->GetHost());
1651 } else {
1652 httpHeaderPutStrf(hdr_out, HDR_HOST, "%s:%d",
1653 orig_request->GetHost(),
1654 (int) orig_request->port);
1655 }
1656 }
1657
1658 /* append Authorization if known in URL, not in header and going direct */
1659 if (!hdr_out->has(HDR_AUTHORIZATION)) {
1660 if (!request->flags.proxying && *request->login) {
1661 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1662 base64_encode(request->login));
1663 }
1664 }
1665
1666 /* Fixup (Proxy-)Authorization special cases. Plain relaying dealt with above */
1667 httpFixupAuthentication(request, orig_request, hdr_in, hdr_out, flags);
1668
1669 /* append Cache-Control, add max-age if not there already */
1670 {
1671 HttpHdrCc *cc = hdr_in->getCc();
1672
1673 if (!cc)
1674 cc = httpHdrCcCreate();
1675
1676 #if 0 /* see bug 2330 */
1677 /* Set no-cache if determined needed but not found */
1678 if (orig_request->flags.nocache)
1679 EBIT_SET(cc->mask, CC_NO_CACHE);
1680 #endif
1681
1682 /* Add max-age only without no-cache */
1683 if (!EBIT_TEST(cc->mask, CC_MAX_AGE) && !EBIT_TEST(cc->mask, CC_NO_CACHE)) {
1684 const char *url =
1685 entry ? entry->url() : urlCanonical(orig_request);
1686 httpHdrCcSetMaxAge(cc, getMaxAge(url));
1687
1688 if (request->urlpath.size())
1689 assert(strstr(url, request->urlpath.termedBuf()));
1690 }
1691
1692 /* Enforce sibling relations */
1693 if (flags.only_if_cached)
1694 EBIT_SET(cc->mask, CC_ONLY_IF_CACHED);
1695
1696 hdr_out->putCc(cc);
1697
1698 httpHdrCcDestroy(cc);
1699 }
1700
1701 /* maybe append Connection: keep-alive */
1702 if (flags.keepalive) {
1703 if (flags.proxying) {
1704 hdr_out->putStr(HDR_PROXY_CONNECTION, "keep-alive");
1705 } else {
1706 hdr_out->putStr(HDR_CONNECTION, "keep-alive");
1707 }
1708 }
1709
1710 /* append Front-End-Https */
1711 if (flags.front_end_https) {
1712 if (flags.front_end_https == 1 || request->protocol == PROTO_HTTPS)
1713 hdr_out->putStr(HDR_FRONT_END_HTTPS, "On");
1714 }
1715
1716 /* Now mangle the headers. */
1717 if (Config2.onoff.mangle_request_headers)
1718 httpHdrMangleList(hdr_out, request, ROR_REQUEST);
1719
1720 strConnection.clean();
1721 }
1722
1723 /**
1724 * Decides whether a particular header may be cloned from the received Clients request
1725 * to our outgoing fetch request.
1726 */
1727 void
1728 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)
1729 {
1730 debugs(11, 5, "httpBuildRequestHeader: " << e->name << ": " << e->value );
1731
1732 switch (e->id) {
1733
1734 /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid should not pass on. */
1735
1736 case HDR_PROXY_AUTHORIZATION:
1737 /** \par Proxy-Authorization:
1738 * Only pass on proxy authentication to peers for which
1739 * authentication forwarding is explicitly enabled
1740 */
1741 if (!flags.originpeer && flags.proxying && orig_request->peer_login &&
1742 (strcmp(orig_request->peer_login, "PASS") == 0 ||
1743 strcmp(orig_request->peer_login, "PROXYPASS") == 0 ||
1744 strcmp(orig_request->peer_login, "PASSTHRU") == 0)) {
1745 hdr_out->addEntry(e->clone());
1746 }
1747 break;
1748
1749 /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid does not pass on. */
1750
1751 case HDR_CONNECTION: /** \par Connection: */
1752 case HDR_TE: /** \par TE: */
1753 case HDR_KEEP_ALIVE: /** \par Keep-Alive: */
1754 case HDR_PROXY_AUTHENTICATE: /** \par Proxy-Authenticate: */
1755 case HDR_TRAILERS: /** \par Trailers: */
1756 case HDR_UPGRADE: /** \par Upgrade: */
1757 case HDR_TRANSFER_ENCODING: /** \par Transfer-Encoding: */
1758 break;
1759
1760
1761 /** \par OTHER headers I haven't bothered to track down yet. */
1762
1763 case HDR_AUTHORIZATION:
1764 /** \par WWW-Authorization:
1765 * Pass on WWW authentication */
1766
1767 if (!flags.originpeer) {
1768 hdr_out->addEntry(e->clone());
1769 } else {
1770 /** \note In accelerators, only forward authentication if enabled
1771 * (see also httpFixupAuthentication for special cases)
1772 */
1773 if (orig_request->peer_login &&
1774 (strcmp(orig_request->peer_login, "PASS") == 0 ||
1775 strcmp(orig_request->peer_login, "PASSTHRU") == 0 ||
1776 strcmp(orig_request->peer_login, "PROXYPASS") == 0)) {
1777 hdr_out->addEntry(e->clone());
1778 }
1779 }
1780
1781 break;
1782
1783 case HDR_HOST:
1784 /** \par Host:
1785 * Normally Squid rewrites the Host: header.
1786 * However, there is one case when we don't: If the URL
1787 * went through our redirector and the admin configured
1788 * 'redir_rewrites_host' to be off.
1789 */
1790 if (orig_request->peer_domain)
1791 hdr_out->putStr(HDR_HOST, orig_request->peer_domain);
1792 else if (request->flags.redirected && !Config.onoff.redir_rewrites_host)
1793 hdr_out->addEntry(e->clone());
1794 else {
1795 /* use port# only if not default */
1796
1797 if (orig_request->port == urlDefaultPort(orig_request->protocol)) {
1798 hdr_out->putStr(HDR_HOST, orig_request->GetHost());
1799 } else {
1800 httpHeaderPutStrf(hdr_out, HDR_HOST, "%s:%d",
1801 orig_request->GetHost(),
1802 (int) orig_request->port);
1803 }
1804 }
1805
1806 break;
1807
1808 case HDR_IF_MODIFIED_SINCE:
1809 /** \par If-Modified-Since:
1810 * append unless we added our own;
1811 * \note at most one client's ims header can pass through */
1812
1813 if (!hdr_out->has(HDR_IF_MODIFIED_SINCE))
1814 hdr_out->addEntry(e->clone());
1815
1816 break;
1817
1818 case HDR_MAX_FORWARDS:
1819 /** \par Max-Forwards:
1820 * pass only on TRACE or OPTIONS requests */
1821 if (orig_request->method == METHOD_TRACE || orig_request->method == METHOD_OPTIONS) {
1822 const int64_t hops = e->getInt64();
1823
1824 if (hops > 0)
1825 hdr_out->putInt64(HDR_MAX_FORWARDS, hops - 1);
1826 }
1827
1828 break;
1829
1830 case HDR_VIA:
1831 /** \par Via:
1832 * If Via is disabled then forward any received header as-is.
1833 * Otherwise leave for explicit updated addition later. */
1834
1835 if (!Config.onoff.via)
1836 hdr_out->addEntry(e->clone());
1837
1838 break;
1839
1840 case HDR_RANGE:
1841
1842 case HDR_IF_RANGE:
1843
1844 case HDR_REQUEST_RANGE:
1845 /** \par Range:, If-Range:, Request-Range:
1846 * Only pass if we accept ranges */
1847 if (!we_do_ranges)
1848 hdr_out->addEntry(e->clone());
1849
1850 break;
1851
1852 case HDR_PROXY_CONNECTION:
1853
1854 case HDR_X_FORWARDED_FOR:
1855
1856 case HDR_CACHE_CONTROL:
1857 /** \par Proxy-Connaction:, X-Forwarded-For:, Cache-Control:
1858 * handled specially by Squid, so leave off for now.
1859 * append these after the loop if needed */
1860 break;
1861
1862 case HDR_FRONT_END_HTTPS:
1863 /** \par Front-End-Https:
1864 * Pass thru only if peer is configured with front-end-https */
1865 if (!flags.front_end_https)
1866 hdr_out->addEntry(e->clone());
1867
1868 break;
1869
1870 default:
1871 /** \par default.
1872 * pass on all other header fields
1873 * which are NOT listed by the special Connection: header. */
1874
1875 if (strConnection.size()>0 && strListIsMember(&strConnection, e->name.termedBuf(), ',')) {
1876 debugs(11, 2, "'" << e->name << "' header cropped by Connection: definition");
1877 return;
1878 }
1879
1880 hdr_out->addEntry(e->clone());
1881 }
1882 }
1883
1884 bool
1885 HttpStateData::decideIfWeDoRanges (HttpRequest * orig_request)
1886 {
1887 bool result = true;
1888 /* decide if we want to do Ranges ourselves
1889 * and fetch the whole object now)
1890 * We want to handle Ranges ourselves iff
1891 * - we can actually parse client Range specs
1892 * - the specs are expected to be simple enough (e.g. no out-of-order ranges)
1893 * - reply will be cachable
1894 * (If the reply will be uncachable we have to throw it away after
1895 * serving this request, so it is better to forward ranges to
1896 * the server and fetch only the requested content)
1897 */
1898
1899 if (NULL == orig_request->range || !orig_request->flags.cachable
1900 || orig_request->range->offsetLimitExceeded() || orig_request->flags.connection_auth)
1901 result = false;
1902
1903 debugs(11, 8, "decideIfWeDoRanges: range specs: " <<
1904 orig_request->range << ", cachable: " <<
1905 orig_request->flags.cachable << "; we_do_ranges: " << result);
1906
1907 return result;
1908 }
1909
1910 /* build request prefix and append it to a given MemBuf;
1911 * return the length of the prefix */
1912 mb_size_t
1913 HttpStateData::buildRequestPrefix(HttpRequest * request,
1914 HttpRequest * orig_request,
1915 StoreEntry * entry,
1916 MemBuf * mb,
1917 http_state_flags flags)
1918 {
1919 const int offset = mb->size;
1920 HttpVersion httpver(1, 0);
1921 mb->Printf("%s %s HTTP/%d.%d\r\n",
1922 RequestMethodStr(request->method),
1923 request->urlpath.size() ? request->urlpath.termedBuf() : "/",
1924 httpver.major,httpver.minor);
1925 /* build and pack headers */
1926 {
1927 HttpHeader hdr(hoRequest);
1928 Packer p;
1929 httpBuildRequestHeader(request, orig_request, entry, &hdr, flags);
1930
1931 if (request->flags.pinned && request->flags.connection_auth)
1932 request->flags.auth_sent = 1;
1933 else if (hdr.has(HDR_AUTHORIZATION))
1934 request->flags.auth_sent = 1;
1935
1936 packerToMemInit(&p, mb);
1937 hdr.packInto(&p);
1938 hdr.clean();
1939 packerClean(&p);
1940 }
1941 /* append header terminator */
1942 mb->append(crlf, 2);
1943 return mb->size - offset;
1944 }
1945
1946 /* This will be called when connect completes. Write request. */
1947 bool
1948 HttpStateData::sendRequest()
1949 {
1950 MemBuf mb;
1951
1952 debugs(11, 5, "httpSendRequest: FD " << fd << ", request " << request << ", this " << this << ".");
1953 typedef CommCbMemFunT<HttpStateData, CommTimeoutCbParams> TimeoutDialer;
1954 AsyncCall::Pointer timeoutCall = asyncCall(11, 5, "HttpStateData::httpTimeout",
1955 TimeoutDialer(this,&HttpStateData::httpTimeout));
1956 commSetTimeout(fd, Config.Timeout.lifetime, timeoutCall);
1957 flags.do_next_read = 1;
1958 maybeReadVirginBody();
1959
1960 if (orig_request->body_pipe != NULL) {
1961 if (!startRequestBodyFlow()) // register to receive body data
1962 return false;
1963 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
1964 Dialer dialer(this, &HttpStateData::sentRequestBody);
1965 requestSender = asyncCall(11,5, "HttpStateData::sentRequestBody", dialer);
1966 } else {
1967 assert(!requestBodySource);
1968 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
1969 Dialer dialer(this, &HttpStateData::sendComplete);
1970 requestSender = asyncCall(11,5, "HttpStateData::SendComplete", dialer);
1971 }
1972
1973 if (_peer != NULL) {
1974 if (_peer->options.originserver) {
1975 flags.proxying = 0;
1976 flags.originpeer = 1;
1977 } else {
1978 flags.proxying = 1;
1979 flags.originpeer = 0;
1980 }
1981 } else {
1982 flags.proxying = 0;
1983 flags.originpeer = 0;
1984 }
1985
1986 /*
1987 * Is keep-alive okay for all request methods?
1988 */
1989 if (orig_request->flags.must_keepalive)
1990 flags.keepalive = 1;
1991 else if (!Config.onoff.server_pconns)
1992 flags.keepalive = 0;
1993 else if (_peer == NULL)
1994 flags.keepalive = 1;
1995 else if (_peer->stats.n_keepalives_sent < 10)
1996 flags.keepalive = 1;
1997 else if ((double) _peer->stats.n_keepalives_recv /
1998 (double) _peer->stats.n_keepalives_sent > 0.50)
1999 flags.keepalive = 1;
2000
2001 if (_peer) {
2002 if (neighborType(_peer, request) == PEER_SIBLING &&
2003 !_peer->options.allow_miss)
2004 flags.only_if_cached = 1;
2005
2006 flags.front_end_https = _peer->front_end_https;
2007 }
2008
2009 mb.init();
2010 request->peer_host=_peer?_peer->host:NULL;
2011 buildRequestPrefix(request, orig_request, entry, &mb, flags);
2012 debugs(11, 6, "httpSendRequest: FD " << fd << ":\n" << mb.buf);
2013 comm_write_mbuf(fd, &mb, requestSender);
2014
2015 return true;
2016 }
2017
2018 void
2019 httpStart(FwdState *fwd)
2020 {
2021 debugs(11, 3, "httpStart: \"" << RequestMethodStr(fwd->request->method) << " " << fwd->entry->url() << "\"" );
2022 HttpStateData *httpState = new HttpStateData(fwd);
2023
2024 if (!httpState->sendRequest()) {
2025 debugs(11, 3, "httpStart: aborted");
2026 delete httpState;
2027 return;
2028 }
2029
2030 statCounter.server.all.requests++;
2031 statCounter.server.http.requests++;
2032
2033 /*
2034 * We used to set the read timeout here, but not any more.
2035 * Now its set in httpSendComplete() after the full request,
2036 * including request body, has been written to the server.
2037 */
2038 }
2039
2040 void
2041 HttpStateData::doneSendingRequestBody()
2042 {
2043 debugs(11,5, HERE << "doneSendingRequestBody: FD " << fd);
2044
2045 #if HTTP_VIOLATIONS
2046 if (Config.accessList.brokenPosts) {
2047 ACLFilledChecklist ch(Config.accessList.brokenPosts, request, NULL);
2048 if (!ch.fastCheck()) {
2049 debugs(11, 5, "doneSendingRequestBody: didn't match brokenPosts");
2050 CommIoCbParams io(NULL);
2051 io.fd=fd;
2052 io.flag=COMM_OK;
2053 sendComplete(io);
2054 } else {
2055 debugs(11, 2, "doneSendingRequestBody: matched brokenPosts");
2056 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
2057 Dialer dialer(this, &HttpStateData::sendComplete);
2058 AsyncCall::Pointer call= asyncCall(11,5, "HttpStateData::SendComplete", dialer);
2059 comm_write(fd, "\r\n", 2, call);
2060 }
2061 return;
2062 }
2063 debugs(11, 5, "doneSendingRequestBody: No brokenPosts list");
2064 #endif /* HTTP_VIOLATIONS */
2065
2066 CommIoCbParams io(NULL);
2067 io.fd=fd;
2068 io.flag=COMM_OK;
2069 sendComplete(io);
2070 }
2071
2072 // more origin request body data is available
2073 void
2074 HttpStateData::handleMoreRequestBodyAvailable()
2075 {
2076 if (eof || fd < 0) {
2077 // XXX: we should check this condition in other callbacks then!
2078 // TODO: Check whether this can actually happen: We should unsubscribe
2079 // as a body consumer when the above condition(s) are detected.
2080 debugs(11, 1, HERE << "Transaction aborted while reading HTTP body");
2081 return;
2082 }
2083
2084 assert(requestBodySource != NULL);
2085
2086 if (requestBodySource->buf().hasContent()) {
2087 // XXX: why does not this trigger a debug message on every request?
2088
2089 if (flags.headers_parsed && !flags.abuse_detected) {
2090 flags.abuse_detected = 1;
2091 debugs(11, 1, "http handleMoreRequestBodyAvailable: Likely proxy abuse detected '" << orig_request->client_addr << "' -> '" << entry->url() << "'" );
2092
2093 if (virginReply()->sline.status == HTTP_INVALID_HEADER) {
2094 comm_close(fd);
2095 return;
2096 }
2097 }
2098 }
2099
2100 HttpStateData::handleMoreRequestBodyAvailable();
2101 }
2102
2103 // premature end of the request body
2104 void
2105 HttpStateData::handleRequestBodyProducerAborted()
2106 {
2107 ServerStateData::handleRequestBodyProducerAborted();
2108 // XXX: SendComplete(COMM_ERR_CLOSING) does little. Is it enough?
2109 CommIoCbParams io(NULL);
2110 io.fd=fd;
2111 io.flag=COMM_ERR_CLOSING;
2112 sendComplete(io);
2113 }
2114
2115 // called when we wrote request headers(!) or a part of the body
2116 void
2117 HttpStateData::sentRequestBody(const CommIoCbParams &io)
2118 {
2119 if (io.size > 0)
2120 kb_incr(&statCounter.server.http.kbytes_out, io.size);
2121
2122 ServerStateData::sentRequestBody(io);
2123 }
2124
2125 // Quickly abort the transaction
2126 // TODO: destruction should be sufficient as the destructor should cleanup,
2127 // including canceling close handlers
2128 void
2129 HttpStateData::abortTransaction(const char *reason)
2130 {
2131 debugs(11,5, HERE << "aborting transaction for " << reason <<
2132 "; FD " << fd << ", this " << this);
2133
2134 if (fd >= 0) {
2135 comm_close(fd);
2136 return;
2137 }
2138
2139 fwd->handleUnregisteredServerEnd();
2140 deleteThis("HttpStateData::abortTransaction");
2141 }
2142
2143 #if DEAD_CODE
2144 void
2145 httpBuildVersion(HttpVersion * version, unsigned int major, unsigned int minor)
2146 {
2147 version->major = major;
2148 version->minor = minor;
2149 }
2150 #endif
2151
2152 HttpRequest *
2153 HttpStateData::originalRequest()
2154 {
2155 return orig_request;
2156 }