]> git.ipfire.org Git - thirdparty/squid.git/blob - src/http.cc
Fix build issue in X-Accelerator-Vary
[thirdparty/squid.git] / src / http.cc
1 /*
2 * Copyright (C) 1996-2016 The Squid Software Foundation and contributors
3 *
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
7 */
8
9 /* DEBUG: section 11 Hypertext Transfer Protocol (HTTP) */
10
11 /*
12 * Anonymizing patch by lutz@as-node.jena.thur.de
13 * have a look into http-anon.c to get more informations.
14 */
15
16 #include "squid.h"
17 #include "acl/FilledChecklist.h"
18 #include "base/AsyncJobCalls.h"
19 #include "base/TextException.h"
20 #include "base64.h"
21 #include "CachePeer.h"
22 #include "client_side.h"
23 #include "comm/Connection.h"
24 #include "comm/Read.h"
25 #include "comm/Write.h"
26 #include "CommRead.h"
27 #include "err_detail_type.h"
28 #include "errorpage.h"
29 #include "fd.h"
30 #include "fde.h"
31 #include "globals.h"
32 #include "http.h"
33 #include "http/one/ResponseParser.h"
34 #include "http/one/TeChunkedParser.h"
35 #include "http/Stream.h"
36 #include "HttpControlMsg.h"
37 #include "HttpHdrCc.h"
38 #include "HttpHdrContRange.h"
39 #include "HttpHdrSc.h"
40 #include "HttpHdrScTarget.h"
41 #include "HttpHeaderTools.h"
42 #include "HttpReply.h"
43 #include "HttpRequest.h"
44 #include "HttpStateFlags.h"
45 #include "log/access_log.h"
46 #include "MemBuf.h"
47 #include "MemObject.h"
48 #include "neighbors.h"
49 #include "peer_proxy_negotiate_auth.h"
50 #include "profiler/Profiler.h"
51 #include "refresh.h"
52 #include "RefreshPattern.h"
53 #include "rfc1738.h"
54 #include "SquidConfig.h"
55 #include "SquidTime.h"
56 #include "StatCounters.h"
57 #include "Store.h"
58 #include "StrList.h"
59 #include "tools.h"
60 #include "URL.h"
61 #include "util.h"
62
63 #if USE_AUTH
64 #include "auth/UserRequest.h"
65 #endif
66 #if USE_DELAY_POOLS
67 #include "DelayPools.h"
68 #endif
69
70 #define SQUID_ENTER_THROWING_CODE() try {
71 #define SQUID_EXIT_THROWING_CODE(status) \
72 status = true; \
73 } \
74 catch (const std::exception &e) { \
75 debugs (11, 1, "Exception error:" << e.what()); \
76 status = false; \
77 }
78
79 CBDATA_CLASS_INIT(HttpStateData);
80
81 static const char *const crlf = "\r\n";
82
83 static void httpMaybeRemovePublic(StoreEntry *, Http::StatusCode);
84 static void copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, const String strConnection, const HttpRequest * request,
85 HttpHeader * hdr_out, const int we_do_ranges, const HttpStateFlags &);
86 //Declared in HttpHeaderTools.cc
87 void httpHdrAdd(HttpHeader *heads, HttpRequest *request, const AccessLogEntryPointer &al, HeaderWithAclList &headers_add);
88
89 HttpStateData::HttpStateData(FwdState *theFwdState) :
90 AsyncJob("HttpStateData"),
91 Client(theFwdState),
92 lastChunk(0),
93 httpChunkDecoder(NULL),
94 payloadSeen(0),
95 payloadTruncated(0)
96 {
97 debugs(11,5,HERE << "HttpStateData " << this << " created");
98 ignoreCacheControl = false;
99 surrogateNoStore = false;
100 serverConnection = fwd->serverConnection();
101
102 // reset peer response time stats for %<pt
103 request->hier.peer_http_request_sent.tv_sec = 0;
104 request->hier.peer_http_request_sent.tv_usec = 0;
105
106 if (fwd->serverConnection() != NULL)
107 _peer = cbdataReference(fwd->serverConnection()->getPeer()); /* might be NULL */
108
109 if (_peer) {
110 request->flags.proxying = true;
111 /*
112 * This NEIGHBOR_PROXY_ONLY check probably shouldn't be here.
113 * We might end up getting the object from somewhere else if,
114 * for example, the request to this neighbor fails.
115 */
116 if (_peer->options.proxy_only)
117 entry->releaseRequest();
118
119 #if USE_DELAY_POOLS
120 entry->setNoDelay(_peer->options.no_delay);
121 #endif
122 }
123
124 /*
125 * register the handler to free HTTP state data when the FD closes
126 */
127 typedef CommCbMemFunT<HttpStateData, CommCloseCbParams> Dialer;
128 closeHandler = JobCallback(9, 5, Dialer, this, HttpStateData::httpStateConnClosed);
129 comm_add_close_handler(serverConnection->fd, closeHandler);
130 }
131
132 HttpStateData::~HttpStateData()
133 {
134 /*
135 * don't forget that ~Client() gets called automatically
136 */
137
138 if (httpChunkDecoder)
139 delete httpChunkDecoder;
140
141 cbdataReferenceDone(_peer);
142
143 debugs(11,5, HERE << "HttpStateData " << this << " destroyed; " << serverConnection);
144 }
145
146 const Comm::ConnectionPointer &
147 HttpStateData::dataConnection() const
148 {
149 return serverConnection;
150 }
151
152 void
153 HttpStateData::httpStateConnClosed(const CommCloseCbParams &params)
154 {
155 debugs(11, 5, "httpStateFree: FD " << params.fd << ", httpState=" << params.data);
156 doneWithFwd = "httpStateConnClosed()"; // assume FwdState is monitoring too
157 mustStop("HttpStateData::httpStateConnClosed");
158 }
159
160 void
161 HttpStateData::httpTimeout(const CommTimeoutCbParams &)
162 {
163 debugs(11, 4, serverConnection << ": '" << entry->url() << "'");
164
165 if (entry->store_status == STORE_PENDING) {
166 fwd->fail(new ErrorState(ERR_READ_TIMEOUT, Http::scGatewayTimeout, fwd->request));
167 }
168
169 closeServer();
170 mustStop("HttpStateData::httpTimeout");
171 }
172
173 /// Remove an existing public store entry if the incoming response (to be
174 /// stored in a currently private entry) is going to invalidate it.
175 static void
176 httpMaybeRemovePublic(StoreEntry * e, Http::StatusCode status)
177 {
178 int remove = 0;
179 int forbidden = 0;
180 StoreEntry *pe;
181
182 // If the incoming response already goes into a public entry, then there is
183 // nothing to remove. This protects ready-for-collapsing entries as well.
184 if (!EBIT_TEST(e->flags, KEY_PRIVATE))
185 return;
186
187 switch (status) {
188
189 case Http::scOkay:
190
191 case Http::scNonAuthoritativeInformation:
192
193 case Http::scMultipleChoices:
194
195 case Http::scMovedPermanently:
196
197 case Http::scFound:
198
199 case Http::scGone:
200
201 case Http::scNotFound:
202 remove = 1;
203
204 break;
205
206 case Http::scForbidden:
207
208 case Http::scMethodNotAllowed:
209 forbidden = 1;
210
211 break;
212
213 #if WORK_IN_PROGRESS
214
215 case Http::scUnauthorized:
216 forbidden = 1;
217
218 break;
219
220 #endif
221
222 default:
223 #if QUESTIONABLE
224 /*
225 * Any 2xx response should eject previously cached entities...
226 */
227
228 if (status >= 200 && status < 300)
229 remove = 1;
230
231 #endif
232
233 break;
234 }
235
236 if (!remove && !forbidden)
237 return;
238
239 assert(e->mem_obj);
240
241 if (e->mem_obj->request)
242 pe = storeGetPublicByRequest(e->mem_obj->request);
243 else
244 pe = storeGetPublic(e->mem_obj->storeId(), e->mem_obj->method);
245
246 if (pe != NULL) {
247 assert(e != pe);
248 #if USE_HTCP
249 neighborsHtcpClear(e, NULL, e->mem_obj->request, e->mem_obj->method, HTCP_CLR_INVALIDATION);
250 #endif
251 pe->release();
252 }
253
254 /** \par
255 * Also remove any cached HEAD response in case the object has
256 * changed.
257 */
258 if (e->mem_obj->request)
259 pe = storeGetPublicByRequestMethod(e->mem_obj->request, Http::METHOD_HEAD);
260 else
261 pe = storeGetPublic(e->mem_obj->storeId(), Http::METHOD_HEAD);
262
263 if (pe != NULL) {
264 assert(e != pe);
265 #if USE_HTCP
266 neighborsHtcpClear(e, NULL, e->mem_obj->request, HttpRequestMethod(Http::METHOD_HEAD), HTCP_CLR_INVALIDATION);
267 #endif
268 pe->release();
269 }
270 }
271
272 void
273 HttpStateData::processSurrogateControl(HttpReply *reply)
274 {
275 if (request->flags.accelerated && reply->surrogate_control) {
276 HttpHdrScTarget *sctusable = reply->surrogate_control->getMergedTarget(Config.Accel.surrogate_id);
277
278 if (sctusable) {
279 if (sctusable->noStore() ||
280 (Config.onoff.surrogate_is_remote
281 && sctusable->noStoreRemote())) {
282 surrogateNoStore = true;
283 entry->makePrivate();
284 }
285
286 /* The HttpHeader logic cannot tell if the header it's parsing is a reply to an
287 * accelerated request or not...
288 * Still, this is an abstraction breach. - RC
289 */
290 if (sctusable->hasMaxAge()) {
291 if (sctusable->maxAge() < sctusable->maxStale())
292 reply->expires = reply->date + sctusable->maxAge();
293 else
294 reply->expires = reply->date + sctusable->maxStale();
295
296 /* And update the timestamps */
297 entry->timestampsSet();
298 }
299
300 /* We ignore cache-control directives as per the Surrogate specification */
301 ignoreCacheControl = true;
302
303 delete sctusable;
304 }
305 }
306 }
307
308 int
309 HttpStateData::cacheableReply()
310 {
311 HttpReply const *rep = finalReply();
312 HttpHeader const *hdr = &rep->header;
313 const char *v;
314 #if USE_HTTP_VIOLATIONS
315
316 const RefreshPattern *R = NULL;
317
318 /* This strange looking define first looks up the refresh pattern
319 * and then checks if the specified flag is set. The main purpose
320 * of this is to simplify the refresh pattern lookup and USE_HTTP_VIOLATIONS
321 * condition
322 */
323 #define REFRESH_OVERRIDE(flag) \
324 ((R = (R ? R : refreshLimits(entry->mem_obj->storeId()))) , \
325 (R && R->flags.flag))
326 #else
327 #define REFRESH_OVERRIDE(flag) 0
328 #endif
329
330 if (EBIT_TEST(entry->flags, RELEASE_REQUEST)) {
331 debugs(22, 3, "NO because " << *entry << " has been released.");
332 return 0;
333 }
334
335 // Check for Surrogate/1.0 protocol conditions
336 // NP: reverse-proxy traffic our parent server has instructed us never to cache
337 if (surrogateNoStore) {
338 debugs(22, 3, HERE << "NO because Surrogate-Control:no-store");
339 return 0;
340 }
341
342 // RFC 2616: HTTP/1.1 Cache-Control conditions
343 if (!ignoreCacheControl) {
344 // XXX: check to see if the request headers alone were enough to prevent caching earlier
345 // (ie no-store request header) no need to check those all again here if so.
346 // for now we are not reliably doing that so we waste CPU re-checking request CC
347
348 // RFC 2616 section 14.9.2 - MUST NOT cache any response with request CC:no-store
349 if (request && request->cache_control && request->cache_control->noStore() &&
350 !REFRESH_OVERRIDE(ignore_no_store)) {
351 debugs(22, 3, HERE << "NO because client request Cache-Control:no-store");
352 return 0;
353 }
354
355 // NP: request CC:no-cache only means cache READ is forbidden. STORE is permitted.
356 if (rep->cache_control && rep->cache_control->hasNoCache() && rep->cache_control->noCache().size() > 0) {
357 /* TODO: we are allowed to cache when no-cache= has parameters.
358 * Provided we strip away any of the listed headers unless they are revalidated
359 * successfully (ie, must revalidate AND these headers are prohibited on stale replies).
360 * That is a bit tricky for squid right now so we avoid caching entirely.
361 */
362 debugs(22, 3, HERE << "NO because server reply Cache-Control:no-cache has parameters");
363 return 0;
364 }
365
366 // NP: request CC:private is undefined. We ignore.
367 // NP: other request CC flags are limiters on HIT/MISS. We don't care about here.
368
369 // RFC 2616 section 14.9.2 - MUST NOT cache any response with CC:no-store
370 if (rep->cache_control && rep->cache_control->noStore() &&
371 !REFRESH_OVERRIDE(ignore_no_store)) {
372 debugs(22, 3, HERE << "NO because server reply Cache-Control:no-store");
373 return 0;
374 }
375
376 // RFC 2616 section 14.9.1 - MUST NOT cache any response with CC:private in a shared cache like Squid.
377 // CC:private overrides CC:public when both are present in a response.
378 // TODO: add a shared/private cache configuration possibility.
379 if (rep->cache_control &&
380 rep->cache_control->hasPrivate() &&
381 !REFRESH_OVERRIDE(ignore_private)) {
382 /* TODO: we are allowed to cache when private= has parameters.
383 * Provided we strip away any of the listed headers unless they are revalidated
384 * successfully (ie, must revalidate AND these headers are prohibited on stale replies).
385 * That is a bit tricky for squid right now so we avoid caching entirely.
386 */
387 debugs(22, 3, HERE << "NO because server reply Cache-Control:private");
388 return 0;
389 }
390 }
391
392 // RFC 2068, sec 14.9.4 - MUST NOT cache any response with Authentication UNLESS certain CC controls are present
393 // allow HTTP violations to IGNORE those controls (ie re-block caching Auth)
394 if (request && (request->flags.auth || request->flags.authSent)) {
395 if (!rep->cache_control) {
396 debugs(22, 3, HERE << "NO because Authenticated and server reply missing Cache-Control");
397 return 0;
398 }
399
400 if (ignoreCacheControl) {
401 debugs(22, 3, HERE << "NO because Authenticated and ignoring Cache-Control");
402 return 0;
403 }
404
405 bool mayStore = false;
406 // HTTPbis pt6 section 3.2: a response CC:public is present
407 if (rep->cache_control->Public()) {
408 debugs(22, 3, HERE << "Authenticated but server reply Cache-Control:public");
409 mayStore = true;
410
411 // HTTPbis pt6 section 3.2: a response CC:must-revalidate is present
412 } else if (rep->cache_control->mustRevalidate()) {
413 debugs(22, 3, HERE << "Authenticated but server reply Cache-Control:must-revalidate");
414 mayStore = true;
415
416 #if USE_HTTP_VIOLATIONS
417 // NP: given the must-revalidate exception we should also be able to exempt no-cache.
418 // HTTPbis WG verdict on this is that it is omitted from the spec due to being 'unexpected' by
419 // some. The caching+revalidate is not exactly unsafe though with Squids interpretation of no-cache
420 // (without parameters) as equivalent to must-revalidate in the reply.
421 } else if (rep->cache_control->hasNoCache() && rep->cache_control->noCache().size() == 0) {
422 debugs(22, 3, HERE << "Authenticated but server reply Cache-Control:no-cache (equivalent to must-revalidate)");
423 mayStore = true;
424 #endif
425
426 // HTTPbis pt6 section 3.2: a response CC:s-maxage is present
427 } else if (rep->cache_control->sMaxAge()) {
428 debugs(22, 3, HERE << "Authenticated but server reply Cache-Control:s-maxage");
429 mayStore = true;
430 }
431
432 if (!mayStore) {
433 debugs(22, 3, HERE << "NO because Authenticated transaction");
434 return 0;
435 }
436
437 // NP: response CC:no-cache is equivalent to CC:must-revalidate,max-age=0. We MAY cache, and do so.
438 // NP: other request CC flags are limiters on HIT/MISS/REFRESH. We don't care about here.
439 }
440
441 /* HACK: The "multipart/x-mixed-replace" content type is used for
442 * continuous push replies. These are generally dynamic and
443 * probably should not be cachable
444 */
445 if ((v = hdr->getStr(Http::HdrType::CONTENT_TYPE)))
446 if (!strncasecmp(v, "multipart/x-mixed-replace", 25)) {
447 debugs(22, 3, HERE << "NO because Content-Type:multipart/x-mixed-replace");
448 return 0;
449 }
450
451 switch (rep->sline.status()) {
452 /* Responses that are cacheable */
453
454 case Http::scOkay:
455
456 case Http::scNonAuthoritativeInformation:
457
458 case Http::scMultipleChoices:
459
460 case Http::scMovedPermanently:
461 case Http::scPermanentRedirect:
462
463 case Http::scGone:
464 /*
465 * Don't cache objects that need to be refreshed on next request,
466 * unless we know how to refresh it.
467 */
468
469 if (!refreshIsCachable(entry) && !REFRESH_OVERRIDE(store_stale)) {
470 debugs(22, 3, "NO because refreshIsCachable() returned non-cacheable..");
471 return 0;
472 } else {
473 debugs(22, 3, HERE << "YES because HTTP status " << rep->sline.status());
474 return 1;
475 }
476 /* NOTREACHED */
477 break;
478
479 /* Responses that only are cacheable if the server says so */
480
481 case Http::scFound:
482 case Http::scTemporaryRedirect:
483 if (rep->date <= 0) {
484 debugs(22, 3, HERE << "NO because HTTP status " << rep->sline.status() << " and Date missing/invalid");
485 return 0;
486 }
487 if (rep->expires > rep->date) {
488 debugs(22, 3, HERE << "YES because HTTP status " << rep->sline.status() << " and Expires > Date");
489 return 1;
490 } else {
491 debugs(22, 3, HERE << "NO because HTTP status " << rep->sline.status() << " and Expires <= Date");
492 return 0;
493 }
494 /* NOTREACHED */
495 break;
496
497 /* Errors can be negatively cached */
498
499 case Http::scNoContent:
500
501 case Http::scUseProxy:
502
503 case Http::scBadRequest:
504
505 case Http::scForbidden:
506
507 case Http::scNotFound:
508
509 case Http::scMethodNotAllowed:
510
511 case Http::scUriTooLong:
512
513 case Http::scInternalServerError:
514
515 case Http::scNotImplemented:
516
517 case Http::scBadGateway:
518
519 case Http::scServiceUnavailable:
520
521 case Http::scGatewayTimeout:
522 case Http::scMisdirectedRequest:
523
524 debugs(22, 3, "MAYBE because HTTP status " << rep->sline.status());
525 return -1;
526
527 /* NOTREACHED */
528 break;
529
530 /* Some responses can never be cached */
531
532 case Http::scPartialContent: /* Not yet supported */
533
534 case Http::scSeeOther:
535
536 case Http::scNotModified:
537
538 case Http::scUnauthorized:
539
540 case Http::scProxyAuthenticationRequired:
541
542 case Http::scInvalidHeader: /* Squid header parsing error */
543
544 case Http::scHeaderTooLarge:
545
546 case Http::scPaymentRequired:
547 case Http::scNotAcceptable:
548 case Http::scRequestTimeout:
549 case Http::scConflict:
550 case Http::scLengthRequired:
551 case Http::scPreconditionFailed:
552 case Http::scPayloadTooLarge:
553 case Http::scUnsupportedMediaType:
554 case Http::scUnprocessableEntity:
555 case Http::scLocked:
556 case Http::scFailedDependency:
557 case Http::scInsufficientStorage:
558 case Http::scRequestedRangeNotSatisfied:
559 case Http::scExpectationFailed:
560
561 debugs(22, 3, HERE << "NO because HTTP status " << rep->sline.status());
562 return 0;
563
564 default:
565 /* RFC 2616 section 6.1.1: an unrecognized response MUST NOT be cached. */
566 debugs (11, 3, HERE << "NO because unknown HTTP status code " << rep->sline.status());
567 return 0;
568
569 /* NOTREACHED */
570 break;
571 }
572
573 /* NOTREACHED */
574 }
575
576 /*
577 * For Vary, store the relevant request headers as
578 * virtual headers in the reply
579 * Returns an empty SBuf if the variance cannot be stored
580 */
581 SBuf
582 httpMakeVaryMark(HttpRequest * request, HttpReply const * reply)
583 {
584 String vary, hdr;
585 const char *pos = NULL;
586 const char *item;
587 const char *value;
588 int ilen;
589 SBuf vstr;
590 static const SBuf asterisk("*");
591
592 vary = reply->header.getList(Http::HdrType::VARY);
593
594 while (strListGetItem(&vary, ',', &item, &ilen, &pos)) {
595 SBuf name(item, ilen);
596 if (name == asterisk) {
597 vstr.clear();
598 break;
599 }
600 name.toLower();
601 if (!vstr.isEmpty())
602 vstr.append(", ", 2);
603 vstr.append(name);
604 hdr = request->header.getByName(name);
605 value = hdr.termedBuf();
606 if (value) {
607 value = rfc1738_escape_part(value);
608 vstr.append("=\"", 2);
609 vstr.append(value);
610 vstr.append("\"", 1);
611 }
612
613 hdr.clean();
614 }
615
616 vary.clean();
617 #if X_ACCELERATOR_VARY
618
619 pos = NULL;
620 vary = reply->header.getList(Http::HdrType::HDR_X_ACCELERATOR_VARY);
621
622 while (strListGetItem(&vary, ',', &item, &ilen, &pos)) {
623 SBuf name(item, ilen);
624 if (name == asterisk) {
625 vstr.clear();
626 break;
627 }
628 name.toLower();
629 if (!vstr.isEmpty())
630 vstr.append(", ", 2);
631 vstr.append(name);
632 hdr = request->header.getByName(name);
633 value = hdr.termedBuf();
634
635 if (value) {
636 value = rfc1738_escape_part(value);
637 vstr.append("=\"", 2);
638 vstr.append(value);
639 vstr.append("\"", 1);
640 }
641
642 hdr.clean();
643 }
644
645 vary.clean();
646 #endif
647
648 debugs(11, 3, vstr);
649 return vstr;
650 }
651
652 void
653 HttpStateData::keepaliveAccounting(HttpReply *reply)
654 {
655 if (flags.keepalive)
656 if (_peer)
657 ++ _peer->stats.n_keepalives_sent;
658
659 if (reply->keep_alive) {
660 if (_peer)
661 ++ _peer->stats.n_keepalives_recv;
662
663 if (Config.onoff.detect_broken_server_pconns
664 && reply->bodySize(request->method) == -1 && !flags.chunked) {
665 debugs(11, DBG_IMPORTANT, "keepaliveAccounting: Impossible keep-alive header from '" << entry->url() << "'" );
666 // debugs(11, 2, "GOT HTTP REPLY HDR:\n---------\n" << readBuf->content() << "\n----------" );
667 flags.keepalive_broken = true;
668 }
669 }
670 }
671
672 void
673 HttpStateData::checkDateSkew(HttpReply *reply)
674 {
675 if (reply->date > -1 && !_peer) {
676 int skew = abs((int)(reply->date - squid_curtime));
677
678 if (skew > 86400)
679 debugs(11, 3, "" << request->url.host() << "'s clock is skewed by " << skew << " seconds!");
680 }
681 }
682
683 /**
684 * This creates the error page itself.. its likely
685 * that the forward ported reply header max size patch
686 * generates non http conformant error pages - in which
687 * case the errors where should be 'BAD_GATEWAY' etc
688 */
689 void
690 HttpStateData::processReplyHeader()
691 {
692 /** Creates a blank header. If this routine is made incremental, this will not do */
693
694 /* NP: all exit points to this function MUST call ctx_exit(ctx) */
695 Ctx ctx = ctx_enter(entry->mem_obj->urlXXX());
696
697 debugs(11, 3, "processReplyHeader: key '" << entry->getMD5Text() << "'");
698
699 assert(!flags.headers_parsed);
700
701 if (!inBuf.length()) {
702 ctx_exit(ctx);
703 return;
704 }
705
706 /* Attempt to parse the first line; this will define where the protocol, status, reason-phrase and header begin */
707 {
708 if (hp == NULL)
709 hp = new Http1::ResponseParser;
710
711 bool parsedOk = hp->parse(inBuf);
712
713 // sync the buffers after parsing.
714 inBuf = hp->remaining();
715
716 if (hp->needsMoreData()) {
717 if (eof) { // no more data coming
718 /* Bug 2879: Replies may terminate with \r\n then EOF instead of \r\n\r\n.
719 * We also may receive truncated responses.
720 * Ensure here that we have at minimum two \r\n when EOF is seen.
721 */
722 inBuf.append("\r\n\r\n", 4);
723 // retry the parse
724 parsedOk = hp->parse(inBuf);
725 // sync the buffers after parsing.
726 inBuf = hp->remaining();
727 } else {
728 debugs(33, 5, "Incomplete response, waiting for end of response headers");
729 ctx_exit(ctx);
730 return;
731 }
732 }
733
734 if (!parsedOk) {
735 // unrecoverable parsing error
736 // TODO: Use Raw! XXX: inBuf no longer has the [beginning of the] malformed header.
737 debugs(11, 3, "Non-HTTP-compliant header:\n---------\n" << inBuf << "\n----------");
738 flags.headers_parsed = true;
739 HttpReply *newrep = new HttpReply;
740 newrep->sline.set(Http::ProtocolVersion(), hp->parseStatusCode);
741 setVirginReply(newrep);
742 ctx_exit(ctx);
743 return;
744 }
745 }
746
747 /* We know the whole response is in parser now */
748 debugs(11, 2, "HTTP Server " << serverConnection);
749 debugs(11, 2, "HTTP Server RESPONSE:\n---------\n" <<
750 hp->messageProtocol() << " " << hp->messageStatus() << " " << hp->reasonPhrase() << "\n" <<
751 hp->mimeHeader() <<
752 "----------");
753
754 // reset payload tracking to begin after message headers
755 payloadSeen = inBuf.length();
756
757 HttpReply *newrep = new HttpReply;
758 // XXX: RFC 7230 indicates we MAY ignore the reason phrase,
759 // and use an empty string on unknown status.
760 // We do that now to avoid performance regression from using SBuf::c_str()
761 newrep->sline.set(Http::ProtocolVersion(1,1), hp->messageStatus() /* , hp->reasonPhrase() */);
762 newrep->sline.protocol = newrep->sline.version.protocol = hp->messageProtocol().protocol;
763 newrep->sline.version.major = hp->messageProtocol().major;
764 newrep->sline.version.minor = hp->messageProtocol().minor;
765
766 // parse headers
767 if (!newrep->parseHeader(*hp)) {
768 // XXX: when Http::ProtocolVersion is a function, remove this hack. just set with messageProtocol()
769 newrep->sline.set(Http::ProtocolVersion(), Http::scInvalidHeader);
770 newrep->sline.version.protocol = hp->messageProtocol().protocol;
771 newrep->sline.version.major = hp->messageProtocol().major;
772 newrep->sline.version.minor = hp->messageProtocol().minor;
773 debugs(11, 2, "error parsing response headers mime block");
774 }
775
776 // done with Parser, now process using the HttpReply
777 hp = NULL;
778
779 newrep->sources |= request->url.getScheme() == AnyP::PROTO_HTTPS ? HttpMsg::srcHttps : HttpMsg::srcHttp;
780
781 newrep->removeStaleWarnings();
782
783 if (newrep->sline.protocol == AnyP::PROTO_HTTP && newrep->sline.status() >= 100 && newrep->sline.status() < 200) {
784 handle1xx(newrep);
785 ctx_exit(ctx);
786 return;
787 }
788
789 flags.chunked = false;
790 if (newrep->sline.protocol == AnyP::PROTO_HTTP && newrep->header.chunked()) {
791 flags.chunked = true;
792 httpChunkDecoder = new Http1::TeChunkedParser;
793 }
794
795 if (!peerSupportsConnectionPinning())
796 request->flags.connectionAuthDisabled = true;
797
798 HttpReply *vrep = setVirginReply(newrep);
799 flags.headers_parsed = true;
800
801 keepaliveAccounting(vrep);
802
803 checkDateSkew(vrep);
804
805 processSurrogateControl (vrep);
806
807 request->hier.peer_reply_status = newrep->sline.status();
808
809 ctx_exit(ctx);
810 }
811
812 /// ignore or start forwarding the 1xx response (a.k.a., control message)
813 void
814 HttpStateData::handle1xx(HttpReply *reply)
815 {
816 HttpReply::Pointer msg(reply); // will destroy reply if unused
817
818 // one 1xx at a time: we must not be called while waiting for previous 1xx
819 Must(!flags.handling1xx);
820 flags.handling1xx = true;
821
822 if (!request->canHandle1xx() || request->forcedBodyContinuation) {
823 debugs(11, 2, "ignoring 1xx because it is " << (request->forcedBodyContinuation ? "already sent" : "not supported by client"));
824 proceedAfter1xx();
825 return;
826 }
827
828 #if USE_HTTP_VIOLATIONS
829 // check whether the 1xx response forwarding is allowed by squid.conf
830 if (Config.accessList.reply) {
831 ACLFilledChecklist ch(Config.accessList.reply, originalRequest(), NULL);
832 ch.reply = reply;
833 HTTPMSGLOCK(ch.reply);
834 if (ch.fastCheck() != ACCESS_ALLOWED) { // TODO: support slow lookups?
835 debugs(11, 3, HERE << "ignoring denied 1xx");
836 proceedAfter1xx();
837 return;
838 }
839 }
840 #endif // USE_HTTP_VIOLATIONS
841
842 debugs(11, 2, HERE << "forwarding 1xx to client");
843
844 // the Sink will use this to call us back after writing 1xx to the client
845 typedef NullaryMemFunT<HttpStateData> CbDialer;
846 const AsyncCall::Pointer cb = JobCallback(11, 3, CbDialer, this,
847 HttpStateData::proceedAfter1xx);
848 CallJobHere1(11, 4, request->clientConnectionManager, ConnStateData,
849 ConnStateData::sendControlMsg, HttpControlMsg(msg, cb));
850 // If the call is not fired, then the Sink is gone, and HttpStateData
851 // will terminate due to an aborted store entry or another similar error.
852 // If we get stuck, it is not handle1xx fault if we could get stuck
853 // for similar reasons without a 1xx response.
854 }
855
856 /// restores state and resumes processing after 1xx is ignored or forwarded
857 void
858 HttpStateData::proceedAfter1xx()
859 {
860 Must(flags.handling1xx);
861 debugs(11, 2, "continuing with " << payloadSeen << " bytes in buffer after 1xx");
862 CallJobHere(11, 3, this, HttpStateData, HttpStateData::processReply);
863 }
864
865 /**
866 * returns true if the peer can support connection pinning
867 */
868 bool HttpStateData::peerSupportsConnectionPinning() const
869 {
870 const HttpReply *rep = entry->mem_obj->getReply();
871 const HttpHeader *hdr = &rep->header;
872 bool rc;
873 String header;
874
875 if (!_peer)
876 return true;
877
878 /*If this peer does not support connection pinning (authenticated
879 connections) return false
880 */
881 if (!_peer->connection_auth)
882 return false;
883
884 /*The peer supports connection pinning and the http reply status
885 is not unauthorized, so the related connection can be pinned
886 */
887 if (rep->sline.status() != Http::scUnauthorized)
888 return true;
889
890 /*The server respond with Http::scUnauthorized and the peer configured
891 with "connection-auth=on" we know that the peer supports pinned
892 connections
893 */
894 if (_peer->connection_auth == 1)
895 return true;
896
897 /*At this point peer has configured with "connection-auth=auto"
898 parameter so we need some extra checks to decide if we are going
899 to allow pinned connections or not
900 */
901
902 /*if the peer configured with originserver just allow connection
903 pinning (squid 2.6 behaviour)
904 */
905 if (_peer->options.originserver)
906 return true;
907
908 /*if the connections it is already pinned it is OK*/
909 if (request->flags.pinned)
910 return true;
911
912 /*Allow pinned connections only if the Proxy-support header exists in
913 reply and has in its list the "Session-Based-Authentication"
914 which means that the peer supports connection pinning.
915 */
916 if (!hdr->has(Http::HdrType::PROXY_SUPPORT))
917 return false;
918
919 header = hdr->getStrOrList(Http::HdrType::PROXY_SUPPORT);
920 /* XXX This ought to be done in a case-insensitive manner */
921 rc = (strstr(header.termedBuf(), "Session-Based-Authentication") != NULL);
922
923 return rc;
924 }
925
926 // Called when we parsed (and possibly adapted) the headers but
927 // had not starting storing (a.k.a., sending) the body yet.
928 void
929 HttpStateData::haveParsedReplyHeaders()
930 {
931 Client::haveParsedReplyHeaders();
932
933 Ctx ctx = ctx_enter(entry->mem_obj->urlXXX());
934 HttpReply *rep = finalReply();
935
936 entry->timestampsSet();
937
938 /* Check if object is cacheable or not based on reply code */
939 debugs(11, 3, "HTTP CODE: " << rep->sline.status());
940
941 if (neighbors_do_private_keys)
942 httpMaybeRemovePublic(entry, rep->sline.status());
943
944 bool varyFailure = false;
945 if (rep->header.has(Http::HdrType::VARY)
946 #if X_ACCELERATOR_VARY
947 || rep->header.has(Http::HdrType::HDR_X_ACCELERATOR_VARY)
948 #endif
949 ) {
950 const SBuf vary(httpMakeVaryMark(request, rep));
951
952 if (vary.isEmpty()) {
953 entry->makePrivate();
954 if (!fwd->reforwardableStatus(rep->sline.status()))
955 EBIT_CLR(entry->flags, ENTRY_FWD_HDR_WAIT);
956 varyFailure = true;
957 } else {
958 entry->mem_obj->vary_headers = vary;
959 }
960 }
961
962 if (!varyFailure) {
963 /*
964 * If its not a reply that we will re-forward, then
965 * allow the client to get it.
966 */
967 if (!fwd->reforwardableStatus(rep->sline.status()))
968 EBIT_CLR(entry->flags, ENTRY_FWD_HDR_WAIT);
969
970 switch (cacheableReply()) {
971
972 case 1:
973 entry->makePublic();
974 break;
975
976 case 0:
977 entry->makePrivate();
978 break;
979
980 case -1:
981
982 #if USE_HTTP_VIOLATIONS
983 if (Config.negativeTtl > 0)
984 entry->cacheNegatively();
985 else
986 #endif
987 entry->makePrivate();
988 break;
989
990 default:
991 assert(0);
992 break;
993 }
994 }
995
996 if (!ignoreCacheControl) {
997 if (rep->cache_control) {
998 // We are required to revalidate on many conditions.
999 // For security reasons we do so even if storage was caused by refresh_pattern ignore-* option
1000
1001 // CC:must-revalidate or CC:proxy-revalidate
1002 const bool ccMustRevalidate = (rep->cache_control->proxyRevalidate() || rep->cache_control->mustRevalidate());
1003
1004 // CC:no-cache (only if there are no parameters)
1005 const bool ccNoCacheNoParams = (rep->cache_control->hasNoCache() && rep->cache_control->noCache().size()==0);
1006
1007 // CC:s-maxage=N
1008 const bool ccSMaxAge = rep->cache_control->hasSMaxAge();
1009
1010 // CC:private (yes, these can sometimes be stored)
1011 const bool ccPrivate = rep->cache_control->hasPrivate();
1012
1013 if (ccMustRevalidate || ccNoCacheNoParams || ccSMaxAge || ccPrivate)
1014 EBIT_SET(entry->flags, ENTRY_REVALIDATE);
1015 }
1016 #if USE_HTTP_VIOLATIONS // response header Pragma::no-cache is undefined in HTTP
1017 else {
1018 // Expensive calculation. So only do it IF the CC: header is not present.
1019
1020 /* HACK: Pragma: no-cache in _replies_ is not documented in HTTP,
1021 * but servers like "Active Imaging Webcast/2.0" sure do use it */
1022 if (rep->header.has(Http::HdrType::PRAGMA) &&
1023 rep->header.hasListMember(Http::HdrType::PRAGMA,"no-cache",','))
1024 EBIT_SET(entry->flags, ENTRY_REVALIDATE);
1025 }
1026 #endif
1027 }
1028
1029 #if HEADERS_LOG
1030 headersLog(1, 0, request->method, rep);
1031
1032 #endif
1033
1034 ctx_exit(ctx);
1035 }
1036
1037 HttpStateData::ConnectionStatus
1038 HttpStateData::statusIfComplete() const
1039 {
1040 const HttpReply *rep = virginReply();
1041 /** \par
1042 * If the reply wants to close the connection, it takes precedence */
1043
1044 if (httpHeaderHasConnDir(&rep->header, "close"))
1045 return COMPLETE_NONPERSISTENT_MSG;
1046
1047 /** \par
1048 * If we didn't send a keep-alive request header, then this
1049 * can not be a persistent connection.
1050 */
1051 if (!flags.keepalive)
1052 return COMPLETE_NONPERSISTENT_MSG;
1053
1054 /** \par
1055 * If we haven't sent the whole request then this can not be a persistent
1056 * connection.
1057 */
1058 if (!flags.request_sent) {
1059 debugs(11, 2, "Request not yet fully sent " << request->method << ' ' << entry->url());
1060 return COMPLETE_NONPERSISTENT_MSG;
1061 }
1062
1063 /** \par
1064 * What does the reply have to say about keep-alive?
1065 */
1066 /**
1067 \bug XXX BUG?
1068 * If the origin server (HTTP/1.0) does not send a keep-alive
1069 * header, but keeps the connection open anyway, what happens?
1070 * We'll return here and http.c waits for an EOF before changing
1071 * store_status to STORE_OK. Combine this with ENTRY_FWD_HDR_WAIT
1072 * and an error status code, and we might have to wait until
1073 * the server times out the socket.
1074 */
1075 if (!rep->keep_alive)
1076 return COMPLETE_NONPERSISTENT_MSG;
1077
1078 return COMPLETE_PERSISTENT_MSG;
1079 }
1080
1081 HttpStateData::ConnectionStatus
1082 HttpStateData::persistentConnStatus() const
1083 {
1084 debugs(11, 3, HERE << serverConnection << " eof=" << eof);
1085 if (eof) // already reached EOF
1086 return COMPLETE_NONPERSISTENT_MSG;
1087
1088 /* If server fd is closing (but we have not been notified yet), stop Comm
1089 I/O to avoid assertions. TODO: Change Comm API to handle callers that
1090 want more I/O after async closing (usually initiated by others). */
1091 // XXX: add canReceive or s/canSend/canTalkToServer/
1092 if (!Comm::IsConnOpen(serverConnection))
1093 return COMPLETE_NONPERSISTENT_MSG;
1094
1095 /** \par
1096 * In chunked response we do not know the content length but we are absolutely
1097 * sure about the end of response, so we are calling the statusIfComplete to
1098 * decide if we can be persistant
1099 */
1100 if (lastChunk && flags.chunked)
1101 return statusIfComplete();
1102
1103 const HttpReply *vrep = virginReply();
1104 debugs(11, 5, "persistentConnStatus: content_length=" << vrep->content_length);
1105
1106 const int64_t clen = vrep->bodySize(request->method);
1107
1108 debugs(11, 5, "persistentConnStatus: clen=" << clen);
1109
1110 /* If the body size is unknown we must wait for EOF */
1111 if (clen < 0)
1112 return INCOMPLETE_MSG;
1113
1114 /** \par
1115 * If the body size is known, we must wait until we've gotten all of it. */
1116 if (clen > 0) {
1117 debugs(11,5, "payloadSeen=" << payloadSeen << " content_length=" << vrep->content_length);
1118
1119 if (payloadSeen < vrep->content_length)
1120 return INCOMPLETE_MSG;
1121
1122 if (payloadTruncated > 0) // already read more than needed
1123 return COMPLETE_NONPERSISTENT_MSG; // disable pconns
1124 }
1125
1126 /** \par
1127 * If there is no message body or we got it all, we can be persistent */
1128 return statusIfComplete();
1129 }
1130
1131 #if USE_DELAY_POOLS
1132 static void
1133 readDelayed(void *context, CommRead const &)
1134 {
1135 HttpStateData *state = static_cast<HttpStateData*>(context);
1136 state->flags.do_next_read = true;
1137 state->maybeReadVirginBody();
1138 }
1139 #endif
1140
1141 void
1142 HttpStateData::readReply(const CommIoCbParams &io)
1143 {
1144 Must(!flags.do_next_read); // XXX: should have been set false by mayReadVirginBody()
1145 flags.do_next_read = false;
1146
1147 debugs(11, 5, io.conn);
1148
1149 // Bail out early on Comm::ERR_CLOSING - close handlers will tidy up for us
1150 if (io.flag == Comm::ERR_CLOSING) {
1151 debugs(11, 3, "http socket closing");
1152 return;
1153 }
1154
1155 if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
1156 abortTransaction("store entry aborted while reading reply");
1157 return;
1158 }
1159
1160 Must(Comm::IsConnOpen(serverConnection));
1161 Must(io.conn->fd == serverConnection->fd);
1162
1163 /*
1164 * Don't reset the timeout value here. The value should be
1165 * counting Config.Timeout.request and applies to the request
1166 * as a whole, not individual read() calls.
1167 * Plus, it breaks our lame *HalfClosed() detection
1168 */
1169
1170 Must(maybeMakeSpaceAvailable(true));
1171 CommIoCbParams rd(this); // will be expanded with ReadNow results
1172 rd.conn = io.conn;
1173 rd.size = entry->bytesWanted(Range<size_t>(0, inBuf.spaceSize()));
1174 #if USE_DELAY_POOLS
1175 if (rd.size < 1) {
1176 assert(entry->mem_obj);
1177
1178 /* read ahead limit */
1179 /* Perhaps these two calls should both live in MemObject */
1180 AsyncCall::Pointer nilCall;
1181 if (!entry->mem_obj->readAheadPolicyCanRead()) {
1182 entry->mem_obj->delayRead(DeferredRead(readDelayed, this, CommRead(io.conn, NULL, 0, nilCall)));
1183 return;
1184 }
1185
1186 /* delay id limit */
1187 entry->mem_obj->mostBytesAllowed().delayRead(DeferredRead(readDelayed, this, CommRead(io.conn, NULL, 0, nilCall)));
1188 return;
1189 }
1190 #endif
1191
1192 switch (Comm::ReadNow(rd, inBuf)) {
1193 case Comm::INPROGRESS:
1194 if (inBuf.isEmpty())
1195 debugs(33, 2, io.conn << ": no data to process, " << xstrerr(rd.xerrno));
1196 flags.do_next_read = true;
1197 maybeReadVirginBody();
1198 return;
1199
1200 case Comm::OK:
1201 {
1202 payloadSeen += rd.size;
1203 #if USE_DELAY_POOLS
1204 DelayId delayId = entry->mem_obj->mostBytesAllowed();
1205 delayId.bytesIn(rd.size);
1206 #endif
1207
1208 statCounter.server.all.kbytes_in += rd.size;
1209 statCounter.server.http.kbytes_in += rd.size;
1210 ++ IOStats.Http.reads;
1211
1212 int bin = 0;
1213 for (int clen = rd.size - 1; clen; ++bin)
1214 clen >>= 1;
1215
1216 ++ IOStats.Http.read_hist[bin];
1217
1218 // update peer response time stats (%<pt)
1219 const timeval &sent = request->hier.peer_http_request_sent;
1220 if (sent.tv_sec)
1221 tvSub(request->hier.peer_response_time, sent, current_time);
1222 else
1223 request->hier.peer_response_time.tv_sec = -1;
1224 }
1225
1226 /* Continue to process previously read data */
1227 break;
1228
1229 case Comm::ENDFILE: // close detected by 0-byte read
1230 eof = 1;
1231 flags.do_next_read = false;
1232
1233 /* Continue to process previously read data */
1234 break;
1235
1236 // case Comm::COMM_ERROR:
1237 default: // no other flags should ever occur
1238 debugs(11, 2, io.conn << ": read failure: " << xstrerr(rd.xerrno));
1239 ErrorState *err = new ErrorState(ERR_READ_ERROR, Http::scBadGateway, fwd->request);
1240 err->xerrno = rd.xerrno;
1241 fwd->fail(err);
1242 flags.do_next_read = false;
1243 closeServer();
1244 mustStop("HttpStateData::readReply");
1245 return;
1246 }
1247
1248 /* Process next response from buffer */
1249 processReply();
1250 }
1251
1252 /// processes the already read and buffered response data, possibly after
1253 /// waiting for asynchronous 1xx control message processing
1254 void
1255 HttpStateData::processReply()
1256 {
1257
1258 if (flags.handling1xx) { // we came back after handling a 1xx response
1259 debugs(11, 5, HERE << "done with 1xx handling");
1260 flags.handling1xx = false;
1261 Must(!flags.headers_parsed);
1262 }
1263
1264 if (!flags.headers_parsed) { // have not parsed headers yet?
1265 PROF_start(HttpStateData_processReplyHeader);
1266 processReplyHeader();
1267 PROF_stop(HttpStateData_processReplyHeader);
1268
1269 if (!continueAfterParsingHeader()) // parsing error or need more data
1270 return; // TODO: send errors to ICAP
1271
1272 adaptOrFinalizeReply(); // may write to, abort, or "close" the entry
1273 }
1274
1275 // kick more reads if needed and/or process the response body, if any
1276 PROF_start(HttpStateData_processReplyBody);
1277 processReplyBody(); // may call serverComplete()
1278 PROF_stop(HttpStateData_processReplyBody);
1279 }
1280
1281 /**
1282 \retval true if we can continue with processing the body or doing ICAP.
1283 */
1284 bool
1285 HttpStateData::continueAfterParsingHeader()
1286 {
1287 if (flags.handling1xx) {
1288 debugs(11, 5, HERE << "wait for 1xx handling");
1289 Must(!flags.headers_parsed);
1290 return false;
1291 }
1292
1293 if (!flags.headers_parsed && !eof) {
1294 debugs(11, 9, "needs more at " << inBuf.length());
1295 flags.do_next_read = true;
1296 /** \retval false If we have not finished parsing the headers and may get more data.
1297 * Schedules more reads to retrieve the missing data.
1298 */
1299 maybeReadVirginBody(); // schedules all kinds of reads; TODO: rename
1300 return false;
1301 }
1302
1303 /** If we are done with parsing, check for errors */
1304
1305 err_type error = ERR_NONE;
1306
1307 if (flags.headers_parsed) { // parsed headers, possibly with errors
1308 // check for header parsing errors
1309 if (HttpReply *vrep = virginReply()) {
1310 const Http::StatusCode s = vrep->sline.status();
1311 const AnyP::ProtocolVersion &v = vrep->sline.version;
1312 if (s == Http::scInvalidHeader && v != Http::ProtocolVersion(0,9)) {
1313 debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: Bad header encountered from " << entry->url() << " AKA " << request->url);
1314 error = ERR_INVALID_RESP;
1315 } else if (s == Http::scHeaderTooLarge) {
1316 fwd->dontRetry(true);
1317 error = ERR_TOO_BIG;
1318 } else if (vrep->header.conflictingContentLength()) {
1319 fwd->dontRetry(true);
1320 error = ERR_INVALID_RESP;
1321 } else {
1322 return true; // done parsing, got reply, and no error
1323 }
1324 } else {
1325 // parsed headers but got no reply
1326 debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: No reply at all for " << entry->url() << " AKA " << request->url);
1327 error = ERR_INVALID_RESP;
1328 }
1329 } else {
1330 assert(eof);
1331 if (inBuf.length()) {
1332 error = ERR_INVALID_RESP;
1333 debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: Headers did not parse at all for " << entry->url() << " AKA " << request->url);
1334 } else {
1335 error = ERR_ZERO_SIZE_OBJECT;
1336 debugs(11, (request->flags.accelerated?DBG_IMPORTANT:2), "WARNING: HTTP: Invalid Response: No object data received for " << entry->url() << " AKA " << request->url);
1337 }
1338 }
1339
1340 assert(error != ERR_NONE);
1341 entry->reset();
1342 fwd->fail(new ErrorState(error, Http::scBadGateway, fwd->request));
1343 flags.do_next_read = false;
1344 closeServer();
1345 mustStop("HttpStateData::continueAfterParsingHeader");
1346 return false; // quit on error
1347 }
1348
1349 /** truncate what we read if we read too much so that writeReplyBody()
1350 writes no more than what we should have read */
1351 void
1352 HttpStateData::truncateVirginBody()
1353 {
1354 assert(flags.headers_parsed);
1355
1356 HttpReply *vrep = virginReply();
1357 int64_t clen = -1;
1358 if (!vrep->expectingBody(request->method, clen) || clen < 0)
1359 return; // no body or a body of unknown size, including chunked
1360
1361 if (payloadSeen - payloadTruncated <= clen)
1362 return; // we did not read too much or already took care of the extras
1363
1364 if (const int64_t extras = payloadSeen - payloadTruncated - clen) {
1365 // server sent more that the advertised content length
1366 debugs(11, 5, "payloadSeen=" << payloadSeen <<
1367 " clen=" << clen << '/' << vrep->content_length <<
1368 " trucated=" << payloadTruncated << '+' << extras);
1369
1370 inBuf.chop(0, inBuf.length() - extras);
1371 payloadTruncated += extras;
1372 }
1373 }
1374
1375 /**
1376 * Call this when there is data from the origin server
1377 * which should be sent to either StoreEntry, or to ICAP...
1378 */
1379 void
1380 HttpStateData::writeReplyBody()
1381 {
1382 truncateVirginBody(); // if needed
1383 const char *data = inBuf.rawContent();
1384 int len = inBuf.length();
1385 addVirginReplyBody(data, len);
1386 inBuf.consume(len);
1387 }
1388
1389 bool
1390 HttpStateData::decodeAndWriteReplyBody()
1391 {
1392 const char *data = NULL;
1393 int len;
1394 bool wasThereAnException = false;
1395 assert(flags.chunked);
1396 assert(httpChunkDecoder);
1397 SQUID_ENTER_THROWING_CODE();
1398 MemBuf decodedData;
1399 decodedData.init();
1400 httpChunkDecoder->setPayloadBuffer(&decodedData);
1401 const bool doneParsing = httpChunkDecoder->parse(inBuf);
1402 inBuf = httpChunkDecoder->remaining(); // sync buffers after parse
1403 len = decodedData.contentSize();
1404 data=decodedData.content();
1405 addVirginReplyBody(data, len);
1406 if (doneParsing) {
1407 lastChunk = 1;
1408 flags.do_next_read = false;
1409 }
1410 SQUID_EXIT_THROWING_CODE(wasThereAnException);
1411 return wasThereAnException;
1412 }
1413
1414 /**
1415 * processReplyBody has two purposes:
1416 * 1 - take the reply body data, if any, and put it into either
1417 * the StoreEntry, or give it over to ICAP.
1418 * 2 - see if we made it to the end of the response (persistent
1419 * connections and such)
1420 */
1421 void
1422 HttpStateData::processReplyBody()
1423 {
1424 Ip::Address client_addr;
1425 bool ispinned = false;
1426
1427 if (!flags.headers_parsed) {
1428 flags.do_next_read = true;
1429 maybeReadVirginBody();
1430 return;
1431 }
1432
1433 #if USE_ADAPTATION
1434 debugs(11,5, HERE << "adaptationAccessCheckPending=" << adaptationAccessCheckPending);
1435 if (adaptationAccessCheckPending)
1436 return;
1437
1438 #endif
1439
1440 /*
1441 * At this point the reply headers have been parsed and consumed.
1442 * That means header content has been removed from readBuf and
1443 * it contains only body data.
1444 */
1445 if (entry->isAccepting()) {
1446 if (flags.chunked) {
1447 if (!decodeAndWriteReplyBody()) {
1448 flags.do_next_read = false;
1449 serverComplete();
1450 return;
1451 }
1452 } else
1453 writeReplyBody();
1454 }
1455
1456 // storing/sending methods like earlier adaptOrFinalizeReply() or
1457 // above writeReplyBody() may release/abort the store entry.
1458 if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
1459 // TODO: In some cases (e.g., 304), we should keep persistent conn open.
1460 // Detect end-of-reply (and, hence, pool our idle pconn) earlier (ASAP).
1461 abortTransaction("store entry aborted while storing reply");
1462 return;
1463 } else
1464 switch (persistentConnStatus()) {
1465 case INCOMPLETE_MSG: {
1466 debugs(11, 5, "processReplyBody: INCOMPLETE_MSG from " << serverConnection);
1467 /* Wait for more data or EOF condition */
1468 AsyncCall::Pointer nil;
1469 if (flags.keepalive_broken) {
1470 commSetConnTimeout(serverConnection, 10, nil);
1471 } else {
1472 commSetConnTimeout(serverConnection, Config.Timeout.read, nil);
1473 }
1474
1475 flags.do_next_read = true;
1476 }
1477 break;
1478
1479 case COMPLETE_PERSISTENT_MSG:
1480 debugs(11, 5, "processReplyBody: COMPLETE_PERSISTENT_MSG from " << serverConnection);
1481 /* yes we have to clear all these! */
1482 commUnsetConnTimeout(serverConnection);
1483 flags.do_next_read = false;
1484
1485 comm_remove_close_handler(serverConnection->fd, closeHandler);
1486 closeHandler = NULL;
1487 fwd->unregister(serverConnection);
1488
1489 if (request->flags.spoofClientIp)
1490 client_addr = request->client_addr;
1491
1492 if (request->flags.pinned) {
1493 ispinned = true;
1494 } else if (request->flags.connectionAuth && request->flags.authSent) {
1495 ispinned = true;
1496 }
1497
1498 if (ispinned && request->clientConnectionManager.valid()) {
1499 request->clientConnectionManager->pinConnection(serverConnection, request, _peer,
1500 (request->flags.connectionAuth));
1501 } else {
1502 fwd->pconnPush(serverConnection, request->url.host());
1503 }
1504
1505 serverConnection = NULL;
1506 serverComplete();
1507 return;
1508
1509 case COMPLETE_NONPERSISTENT_MSG:
1510 debugs(11, 5, "processReplyBody: COMPLETE_NONPERSISTENT_MSG from " << serverConnection);
1511 serverComplete();
1512 return;
1513 }
1514
1515 maybeReadVirginBody();
1516 }
1517
1518 bool
1519 HttpStateData::mayReadVirginReplyBody() const
1520 {
1521 // TODO: Be more precise here. For example, if/when reading trailer, we may
1522 // not be doneWithServer() yet, but we should return false. Similarly, we
1523 // could still be writing the request body after receiving the whole reply.
1524 return !doneWithServer();
1525 }
1526
1527 void
1528 HttpStateData::maybeReadVirginBody()
1529 {
1530 // too late to read
1531 if (!Comm::IsConnOpen(serverConnection) || fd_table[serverConnection->fd].closing())
1532 return;
1533
1534 if (!maybeMakeSpaceAvailable(false))
1535 return;
1536
1537 // XXX: get rid of the do_next_read flag
1538 // check for the proper reasons preventing read(2)
1539 if (!flags.do_next_read)
1540 return;
1541
1542 flags.do_next_read = false;
1543
1544 // must not already be waiting for read(2) ...
1545 assert(!Comm::MonitorsRead(serverConnection->fd));
1546
1547 // wait for read(2) to be possible.
1548 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
1549 AsyncCall::Pointer call = JobCallback(11, 5, Dialer, this, HttpStateData::readReply);
1550 Comm::Read(serverConnection, call);
1551 }
1552
1553 bool
1554 HttpStateData::maybeMakeSpaceAvailable(bool doGrow)
1555 {
1556 // how much we are allowed to buffer
1557 const int limitBuffer = (flags.headers_parsed ? Config.readAheadGap : Config.maxReplyHeaderSize);
1558
1559 if (limitBuffer < 0 || inBuf.length() >= (SBuf::size_type)limitBuffer) {
1560 // when buffer is at or over limit already
1561 debugs(11, 7, "wont read up to " << limitBuffer << ". buffer has (" << inBuf.length() << "/" << inBuf.spaceSize() << ") from " << serverConnection);
1562 debugs(11, DBG_DATA, "buffer has {" << inBuf << "}");
1563 // Process next response from buffer
1564 processReply();
1565 return false;
1566 }
1567
1568 // how much we want to read
1569 const size_t read_size = calcBufferSpaceToReserve(inBuf.spaceSize(), (limitBuffer - inBuf.length()));
1570
1571 if (!read_size) {
1572 debugs(11, 7, "wont read up to " << read_size << " into buffer (" << inBuf.length() << "/" << inBuf.spaceSize() << ") from " << serverConnection);
1573 return false;
1574 }
1575
1576 // just report whether we could grow or not, dont actually do it
1577 if (doGrow)
1578 return (read_size >= 2);
1579
1580 // we may need to grow the buffer
1581 inBuf.reserveSpace(read_size);
1582 debugs(11, 8, (!flags.do_next_read ? "wont" : "may") <<
1583 " read up to " << read_size << " bytes info buf(" << inBuf.length() << "/" << inBuf.spaceSize() <<
1584 ") from " << serverConnection);
1585
1586 return (inBuf.spaceSize() >= 2); // only read if there is 1+ bytes of space available
1587 }
1588
1589 /// called after writing the very last request byte (body, last-chunk, etc)
1590 void
1591 HttpStateData::wroteLast(const CommIoCbParams &io)
1592 {
1593 debugs(11, 5, HERE << serverConnection << ": size " << io.size << ": errflag " << io.flag << ".");
1594 #if URL_CHECKSUM_DEBUG
1595
1596 entry->mem_obj->checkUrlChecksum();
1597 #endif
1598
1599 if (io.size > 0) {
1600 fd_bytes(io.fd, io.size, FD_WRITE);
1601 statCounter.server.all.kbytes_out += io.size;
1602 statCounter.server.http.kbytes_out += io.size;
1603 }
1604
1605 if (io.flag == Comm::ERR_CLOSING)
1606 return;
1607
1608 if (io.flag) {
1609 ErrorState *err = new ErrorState(ERR_WRITE_ERROR, Http::scBadGateway, fwd->request);
1610 err->xerrno = io.xerrno;
1611 fwd->fail(err);
1612 closeServer();
1613 mustStop("HttpStateData::wroteLast");
1614 return;
1615 }
1616
1617 sendComplete();
1618 }
1619
1620 /// successfully wrote the entire request (including body, last-chunk, etc.)
1621 void
1622 HttpStateData::sendComplete()
1623 {
1624 /*
1625 * Set the read timeout here because it hasn't been set yet.
1626 * We only set the read timeout after the request has been
1627 * fully written to the peer. If we start the timeout
1628 * after connection establishment, then we are likely to hit
1629 * the timeout for POST/PUT requests that have very large
1630 * request bodies.
1631 */
1632 typedef CommCbMemFunT<HttpStateData, CommTimeoutCbParams> TimeoutDialer;
1633 AsyncCall::Pointer timeoutCall = JobCallback(11, 5,
1634 TimeoutDialer, this, HttpStateData::httpTimeout);
1635
1636 commSetConnTimeout(serverConnection, Config.Timeout.read, timeoutCall);
1637 flags.request_sent = true;
1638 request->hier.peer_http_request_sent = current_time;
1639 }
1640
1641 void
1642 HttpStateData::closeServer()
1643 {
1644 debugs(11,5, HERE << "closing HTTP server " << serverConnection << " this " << this);
1645
1646 if (Comm::IsConnOpen(serverConnection)) {
1647 fwd->unregister(serverConnection);
1648 comm_remove_close_handler(serverConnection->fd, closeHandler);
1649 closeHandler = NULL;
1650 serverConnection->close();
1651 }
1652 }
1653
1654 bool
1655 HttpStateData::doneWithServer() const
1656 {
1657 return !Comm::IsConnOpen(serverConnection);
1658 }
1659
1660 /*
1661 * Fixup authentication request headers for special cases
1662 */
1663 static void
1664 httpFixupAuthentication(HttpRequest * request, const HttpHeader * hdr_in, HttpHeader * hdr_out, const HttpStateFlags &flags)
1665 {
1666 Http::HdrType header = flags.originpeer ? Http::HdrType::AUTHORIZATION : Http::HdrType::PROXY_AUTHORIZATION;
1667
1668 /* Nothing to do unless we are forwarding to a peer */
1669 if (!request->flags.proxying)
1670 return;
1671
1672 /* Needs to be explicitly enabled */
1673 if (!request->peer_login)
1674 return;
1675
1676 /* Maybe already dealt with? */
1677 if (hdr_out->has(header))
1678 return;
1679
1680 /* Nothing to do here for PASSTHRU */
1681 if (strcmp(request->peer_login, "PASSTHRU") == 0)
1682 return;
1683
1684 /* PROXYPASS is a special case, single-signon to servers with the proxy password (basic only) */
1685 if (flags.originpeer && strcmp(request->peer_login, "PROXYPASS") == 0 && hdr_in->has(Http::HdrType::PROXY_AUTHORIZATION)) {
1686 const char *auth = hdr_in->getStr(Http::HdrType::PROXY_AUTHORIZATION);
1687
1688 if (auth && strncasecmp(auth, "basic ", 6) == 0) {
1689 hdr_out->putStr(header, auth);
1690 return;
1691 }
1692 }
1693
1694 uint8_t loginbuf[base64_encode_len(MAX_LOGIN_SZ)];
1695 size_t blen;
1696 struct base64_encode_ctx ctx;
1697 base64_encode_init(&ctx);
1698
1699 /* Special mode to pass the username to the upstream cache */
1700 if (*request->peer_login == '*') {
1701 const char *username = "-";
1702
1703 if (request->extacl_user.size())
1704 username = request->extacl_user.termedBuf();
1705 #if USE_AUTH
1706 else if (request->auth_user_request != NULL)
1707 username = request->auth_user_request->username();
1708 #endif
1709
1710 blen = base64_encode_update(&ctx, loginbuf, strlen(username), reinterpret_cast<const uint8_t*>(username));
1711 blen += base64_encode_update(&ctx, loginbuf+blen, strlen(request->peer_login +1), reinterpret_cast<const uint8_t*>(request->peer_login +1));
1712 blen += base64_encode_final(&ctx, loginbuf+blen);
1713 httpHeaderPutStrf(hdr_out, header, "Basic %.*s", (int)blen, loginbuf);
1714 return;
1715 }
1716
1717 /* external_acl provided credentials */
1718 if (request->extacl_user.size() && request->extacl_passwd.size() &&
1719 (strcmp(request->peer_login, "PASS") == 0 ||
1720 strcmp(request->peer_login, "PROXYPASS") == 0)) {
1721
1722 blen = base64_encode_update(&ctx, loginbuf, request->extacl_user.size(), reinterpret_cast<const uint8_t*>(request->extacl_user.rawBuf()));
1723 blen += base64_encode_update(&ctx, loginbuf+blen, 1, reinterpret_cast<const uint8_t*>(":"));
1724 blen += base64_encode_update(&ctx, loginbuf+blen, request->extacl_passwd.size(), reinterpret_cast<const uint8_t*>(request->extacl_passwd.rawBuf()));
1725 blen += base64_encode_final(&ctx, loginbuf+blen);
1726 httpHeaderPutStrf(hdr_out, header, "Basic %.*s", (int)blen, loginbuf);
1727 return;
1728 }
1729 // if no external user credentials are available to fake authentication with PASS acts like PASSTHRU
1730 if (strcmp(request->peer_login, "PASS") == 0)
1731 return;
1732
1733 /* Kerberos login to peer */
1734 #if HAVE_AUTH_MODULE_NEGOTIATE && HAVE_KRB5 && HAVE_GSSAPI
1735 if (strncmp(request->peer_login, "NEGOTIATE",strlen("NEGOTIATE")) == 0) {
1736 char *Token=NULL;
1737 char *PrincipalName=NULL,*p;
1738 int negotiate_flags = 0;
1739
1740 if ((p=strchr(request->peer_login,':')) != NULL ) {
1741 PrincipalName=++p;
1742 }
1743 if (request->flags.auth_no_keytab) {
1744 negotiate_flags |= PEER_PROXY_NEGOTIATE_NOKEYTAB;
1745 }
1746 Token = peer_proxy_negotiate_auth(PrincipalName, request->peer_host, negotiate_flags);
1747 if (Token) {
1748 httpHeaderPutStrf(hdr_out, header, "Negotiate %s",Token);
1749 }
1750 return;
1751 }
1752 #endif /* HAVE_KRB5 && HAVE_GSSAPI */
1753
1754 blen = base64_encode_update(&ctx, loginbuf, strlen(request->peer_login), reinterpret_cast<const uint8_t*>(request->peer_login));
1755 blen += base64_encode_final(&ctx, loginbuf+blen);
1756 httpHeaderPutStrf(hdr_out, header, "Basic %.*s", (int)blen, loginbuf);
1757 return;
1758 }
1759
1760 /*
1761 * build request headers and append them to a given MemBuf
1762 * used by buildRequestPrefix()
1763 * note: initialised the HttpHeader, the caller is responsible for Clean()-ing
1764 */
1765 void
1766 HttpStateData::httpBuildRequestHeader(HttpRequest * request,
1767 StoreEntry * entry,
1768 const AccessLogEntryPointer &al,
1769 HttpHeader * hdr_out,
1770 const HttpStateFlags &flags)
1771 {
1772 /* building buffer for complex strings */
1773 #define BBUF_SZ (MAX_URL+32)
1774 LOCAL_ARRAY(char, bbuf, BBUF_SZ);
1775 LOCAL_ARRAY(char, ntoabuf, MAX_IPSTRLEN);
1776 const HttpHeader *hdr_in = &request->header;
1777 const HttpHeaderEntry *e = NULL;
1778 HttpHeaderPos pos = HttpHeaderInitPos;
1779 assert (hdr_out->owner == hoRequest);
1780
1781 /* use our IMS header if the cached entry has Last-Modified time */
1782 if (request->lastmod > -1)
1783 hdr_out->putTime(Http::HdrType::IF_MODIFIED_SINCE, request->lastmod);
1784
1785 // Add our own If-None-Match field if the cached entry has a strong ETag.
1786 // copyOneHeaderFromClientsideRequestToUpstreamRequest() adds client ones.
1787 if (request->etag.size() > 0) {
1788 hdr_out->addEntry(new HttpHeaderEntry(Http::HdrType::IF_NONE_MATCH, NULL,
1789 request->etag.termedBuf()));
1790 }
1791
1792 bool we_do_ranges = decideIfWeDoRanges (request);
1793
1794 String strConnection (hdr_in->getList(Http::HdrType::CONNECTION));
1795
1796 while ((e = hdr_in->getEntry(&pos)))
1797 copyOneHeaderFromClientsideRequestToUpstreamRequest(e, strConnection, request, hdr_out, we_do_ranges, flags);
1798
1799 /* Abstraction break: We should interpret multipart/byterange responses
1800 * into offset-length data, and this works around our inability to do so.
1801 */
1802 if (!we_do_ranges && request->multipartRangeRequest()) {
1803 /* don't cache the result */
1804 request->flags.cachable = false;
1805 /* pretend it's not a range request */
1806 request->ignoreRange("want to request the whole object");
1807 request->flags.isRanged = false;
1808 }
1809
1810 /* append Via */
1811 if (Config.onoff.via) {
1812 String strVia;
1813 strVia = hdr_in->getList(Http::HdrType::VIA);
1814 snprintf(bbuf, BBUF_SZ, "%d.%d %s",
1815 request->http_ver.major,
1816 request->http_ver.minor, ThisCache);
1817 strListAdd(&strVia, bbuf, ',');
1818 hdr_out->putStr(Http::HdrType::VIA, strVia.termedBuf());
1819 strVia.clean();
1820 }
1821
1822 if (request->flags.accelerated) {
1823 /* Append Surrogate-Capabilities */
1824 String strSurrogate(hdr_in->getList(Http::HdrType::SURROGATE_CAPABILITY));
1825 #if USE_SQUID_ESI
1826 snprintf(bbuf, BBUF_SZ, "%s=\"Surrogate/1.0 ESI/1.0\"", Config.Accel.surrogate_id);
1827 #else
1828 snprintf(bbuf, BBUF_SZ, "%s=\"Surrogate/1.0\"", Config.Accel.surrogate_id);
1829 #endif
1830 strListAdd(&strSurrogate, bbuf, ',');
1831 hdr_out->putStr(Http::HdrType::SURROGATE_CAPABILITY, strSurrogate.termedBuf());
1832 }
1833
1834 /** \pre Handle X-Forwarded-For */
1835 if (strcmp(opt_forwarded_for, "delete") != 0) {
1836
1837 String strFwd = hdr_in->getList(Http::HdrType::X_FORWARDED_FOR);
1838
1839 // if we cannot double strFwd size, then it grew past 50% of the limit
1840 if (!strFwd.canGrowBy(strFwd.size())) {
1841 // There is probably a forwarding loop with Via detection disabled.
1842 // If we do nothing, String will assert on overflow soon.
1843 // TODO: Terminate all transactions with huge XFF?
1844 strFwd = "error";
1845
1846 static int warnedCount = 0;
1847 if (warnedCount++ < 100) {
1848 const SBuf url(entry ? SBuf(entry->url()) : request->effectiveRequestUri());
1849 debugs(11, DBG_IMPORTANT, "Warning: likely forwarding loop with " << url);
1850 }
1851 }
1852
1853 if (strcmp(opt_forwarded_for, "on") == 0) {
1854 /** If set to ON - append client IP or 'unknown'. */
1855 if ( request->client_addr.isNoAddr() )
1856 strListAdd(&strFwd, "unknown", ',');
1857 else
1858 strListAdd(&strFwd, request->client_addr.toStr(ntoabuf, MAX_IPSTRLEN), ',');
1859 } else if (strcmp(opt_forwarded_for, "off") == 0) {
1860 /** If set to OFF - append 'unknown'. */
1861 strListAdd(&strFwd, "unknown", ',');
1862 } else if (strcmp(opt_forwarded_for, "transparent") == 0) {
1863 /** If set to TRANSPARENT - pass through unchanged. */
1864 } else if (strcmp(opt_forwarded_for, "truncate") == 0) {
1865 /** If set to TRUNCATE - drop existing list and replace with client IP or 'unknown'. */
1866 if ( request->client_addr.isNoAddr() )
1867 strFwd = "unknown";
1868 else
1869 strFwd = request->client_addr.toStr(ntoabuf, MAX_IPSTRLEN);
1870 }
1871 if (strFwd.size() > 0)
1872 hdr_out->putStr(Http::HdrType::X_FORWARDED_FOR, strFwd.termedBuf());
1873 }
1874 /** If set to DELETE - do not copy through. */
1875
1876 /* append Host if not there already */
1877 if (!hdr_out->has(Http::HdrType::HOST)) {
1878 if (request->peer_domain) {
1879 hdr_out->putStr(Http::HdrType::HOST, request->peer_domain);
1880 } else {
1881 SBuf authority = request->url.authority();
1882 hdr_out->putStr(Http::HdrType::HOST, authority.c_str());
1883 }
1884 }
1885
1886 /* append Authorization if known in URL, not in header and going direct */
1887 if (!hdr_out->has(Http::HdrType::AUTHORIZATION)) {
1888 if (!request->flags.proxying && !request->url.userInfo().isEmpty()) {
1889 static uint8_t result[base64_encode_len(MAX_URL*2)]; // should be big enough for a single URI segment
1890 struct base64_encode_ctx ctx;
1891 base64_encode_init(&ctx);
1892 size_t blen = base64_encode_update(&ctx, result, request->url.userInfo().length(), reinterpret_cast<const uint8_t*>(request->url.userInfo().rawContent()));
1893 blen += base64_encode_final(&ctx, result+blen);
1894 result[blen] = '\0';
1895 if (blen)
1896 httpHeaderPutStrf(hdr_out, Http::HdrType::AUTHORIZATION, "Basic %.*s", (int)blen, result);
1897 }
1898 }
1899
1900 /* Fixup (Proxy-)Authorization special cases. Plain relaying dealt with above */
1901 httpFixupAuthentication(request, hdr_in, hdr_out, flags);
1902
1903 /* append Cache-Control, add max-age if not there already */
1904 {
1905 HttpHdrCc *cc = hdr_in->getCc();
1906
1907 if (!cc)
1908 cc = new HttpHdrCc();
1909
1910 #if 0 /* see bug 2330 */
1911 /* Set no-cache if determined needed but not found */
1912 if (request->flags.nocache)
1913 EBIT_SET(cc->mask, HttpHdrCcType::CC_NO_CACHE);
1914 #endif
1915
1916 /* Add max-age only without no-cache */
1917 if (!cc->hasMaxAge() && !cc->hasNoCache()) {
1918 // XXX: performance regression. c_str() reallocates
1919 SBuf tmp(request->effectiveRequestUri());
1920 cc->maxAge(getMaxAge(entry ? entry->url() : tmp.c_str()));
1921 }
1922
1923 /* Enforce sibling relations */
1924 if (flags.only_if_cached)
1925 cc->onlyIfCached(true);
1926
1927 hdr_out->putCc(cc);
1928
1929 delete cc;
1930 }
1931
1932 /* maybe append Connection: keep-alive */
1933 if (flags.keepalive) {
1934 hdr_out->putStr(Http::HdrType::CONNECTION, "keep-alive");
1935 }
1936
1937 /* append Front-End-Https */
1938 if (flags.front_end_https) {
1939 if (flags.front_end_https == 1 || request->url.getScheme() == AnyP::PROTO_HTTPS)
1940 hdr_out->putStr(Http::HdrType::FRONT_END_HTTPS, "On");
1941 }
1942
1943 if (flags.chunked_request) {
1944 // Do not just copy the original value so that if the client-side
1945 // starts decode other encodings, this code may remain valid.
1946 hdr_out->putStr(Http::HdrType::TRANSFER_ENCODING, "chunked");
1947 }
1948
1949 /* Now mangle the headers. */
1950 if (Config2.onoff.mangle_request_headers)
1951 httpHdrMangleList(hdr_out, request, ROR_REQUEST);
1952
1953 if (Config.request_header_add && !Config.request_header_add->empty())
1954 httpHdrAdd(hdr_out, request, al, *Config.request_header_add);
1955
1956 strConnection.clean();
1957 }
1958
1959 /**
1960 * Decides whether a particular header may be cloned from the received Clients request
1961 * to our outgoing fetch request.
1962 */
1963 void
1964 copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, const String strConnection, const HttpRequest * request, HttpHeader * hdr_out, const int we_do_ranges, const HttpStateFlags &flags)
1965 {
1966 debugs(11, 5, "httpBuildRequestHeader: " << e->name << ": " << e->value );
1967
1968 switch (e->id) {
1969
1970 /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid should not pass on. */
1971
1972 case Http::HdrType::PROXY_AUTHORIZATION:
1973 /** \par Proxy-Authorization:
1974 * Only pass on proxy authentication to peers for which
1975 * authentication forwarding is explicitly enabled
1976 */
1977 if (!flags.originpeer && flags.proxying && request->peer_login &&
1978 (strcmp(request->peer_login, "PASS") == 0 ||
1979 strcmp(request->peer_login, "PROXYPASS") == 0 ||
1980 strcmp(request->peer_login, "PASSTHRU") == 0)) {
1981 hdr_out->addEntry(e->clone());
1982 }
1983 break;
1984
1985 /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid does not pass on. */
1986
1987 case Http::HdrType::CONNECTION: /** \par Connection: */
1988 case Http::HdrType::TE: /** \par TE: */
1989 case Http::HdrType::KEEP_ALIVE: /** \par Keep-Alive: */
1990 case Http::HdrType::PROXY_AUTHENTICATE: /** \par Proxy-Authenticate: */
1991 case Http::HdrType::TRAILER: /** \par Trailer: */
1992 case Http::HdrType::UPGRADE: /** \par Upgrade: */
1993 case Http::HdrType::TRANSFER_ENCODING: /** \par Transfer-Encoding: */
1994 break;
1995
1996 /** \par OTHER headers I haven't bothered to track down yet. */
1997
1998 case Http::HdrType::AUTHORIZATION:
1999 /** \par WWW-Authorization:
2000 * Pass on WWW authentication */
2001
2002 if (!flags.originpeer) {
2003 hdr_out->addEntry(e->clone());
2004 } else {
2005 /** \note In accelerators, only forward authentication if enabled
2006 * (see also httpFixupAuthentication for special cases)
2007 */
2008 if (request->peer_login &&
2009 (strcmp(request->peer_login, "PASS") == 0 ||
2010 strcmp(request->peer_login, "PASSTHRU") == 0 ||
2011 strcmp(request->peer_login, "PROXYPASS") == 0)) {
2012 hdr_out->addEntry(e->clone());
2013 }
2014 }
2015
2016 break;
2017
2018 case Http::HdrType::HOST:
2019 /** \par Host:
2020 * Normally Squid rewrites the Host: header.
2021 * However, there is one case when we don't: If the URL
2022 * went through our redirector and the admin configured
2023 * 'redir_rewrites_host' to be off.
2024 */
2025 if (request->peer_domain)
2026 hdr_out->putStr(Http::HdrType::HOST, request->peer_domain);
2027 else if (request->flags.redirected && !Config.onoff.redir_rewrites_host)
2028 hdr_out->addEntry(e->clone());
2029 else {
2030 SBuf authority = request->url.authority();
2031 hdr_out->putStr(Http::HdrType::HOST, authority.c_str());
2032 }
2033
2034 break;
2035
2036 case Http::HdrType::IF_MODIFIED_SINCE:
2037 /** \par If-Modified-Since:
2038 * append unless we added our own,
2039 * but only if cache_miss_revalidate is enabled, or
2040 * the request is not cacheable, or
2041 * the request contains authentication credentials.
2042 * \note at most one client's If-Modified-Since header can pass through
2043 */
2044 // XXX: need to check and cleanup the auth case so cacheable auth requests get cached.
2045 if (hdr_out->has(Http::HdrType::IF_MODIFIED_SINCE))
2046 break;
2047 else if (Config.onoff.cache_miss_revalidate || !request->flags.cachable || request->flags.auth)
2048 hdr_out->addEntry(e->clone());
2049 break;
2050
2051 case Http::HdrType::IF_NONE_MATCH:
2052 /** \par If-None-Match:
2053 * append if the wildcard '*' special case value is present, or
2054 * cache_miss_revalidate is disabled, or
2055 * the request is not cacheable in this proxy, or
2056 * the request contains authentication credentials.
2057 * \note this header lists a set of responses for the server to elide sending. Squid added values are extending that set.
2058 */
2059 // XXX: need to check and cleanup the auth case so cacheable auth requests get cached.
2060 if (hdr_out->hasListMember(Http::HdrType::IF_MATCH, "*", ',') || Config.onoff.cache_miss_revalidate || !request->flags.cachable || request->flags.auth)
2061 hdr_out->addEntry(e->clone());
2062 break;
2063
2064 case Http::HdrType::MAX_FORWARDS:
2065 /** \par Max-Forwards:
2066 * pass only on TRACE or OPTIONS requests */
2067 if (request->method == Http::METHOD_TRACE || request->method == Http::METHOD_OPTIONS) {
2068 const int64_t hops = e->getInt64();
2069
2070 if (hops > 0)
2071 hdr_out->putInt64(Http::HdrType::MAX_FORWARDS, hops - 1);
2072 }
2073
2074 break;
2075
2076 case Http::HdrType::VIA:
2077 /** \par Via:
2078 * If Via is disabled then forward any received header as-is.
2079 * Otherwise leave for explicit updated addition later. */
2080
2081 if (!Config.onoff.via)
2082 hdr_out->addEntry(e->clone());
2083
2084 break;
2085
2086 case Http::HdrType::RANGE:
2087
2088 case Http::HdrType::IF_RANGE:
2089
2090 case Http::HdrType::REQUEST_RANGE:
2091 /** \par Range:, If-Range:, Request-Range:
2092 * Only pass if we accept ranges */
2093 if (!we_do_ranges)
2094 hdr_out->addEntry(e->clone());
2095
2096 break;
2097
2098 case Http::HdrType::PROXY_CONNECTION: // SHOULD ignore. But doing so breaks things.
2099 break;
2100
2101 case Http::HdrType::CONTENT_LENGTH:
2102 // pass through unless we chunk; also, keeping this away from default
2103 // prevents request smuggling via Connection: Content-Length tricks
2104 if (!flags.chunked_request)
2105 hdr_out->addEntry(e->clone());
2106 break;
2107
2108 case Http::HdrType::X_FORWARDED_FOR:
2109
2110 case Http::HdrType::CACHE_CONTROL:
2111 /** \par X-Forwarded-For:, Cache-Control:
2112 * handled specially by Squid, so leave off for now.
2113 * append these after the loop if needed */
2114 break;
2115
2116 case Http::HdrType::FRONT_END_HTTPS:
2117 /** \par Front-End-Https:
2118 * Pass thru only if peer is configured with front-end-https */
2119 if (!flags.front_end_https)
2120 hdr_out->addEntry(e->clone());
2121
2122 break;
2123
2124 default:
2125 /** \par default.
2126 * pass on all other header fields
2127 * which are NOT listed by the special Connection: header. */
2128
2129 if (strConnection.size()>0 && strListIsMember(&strConnection, e->name.termedBuf(), ',')) {
2130 debugs(11, 2, "'" << e->name << "' header cropped by Connection: definition");
2131 return;
2132 }
2133
2134 hdr_out->addEntry(e->clone());
2135 }
2136 }
2137
2138 bool
2139 HttpStateData::decideIfWeDoRanges (HttpRequest * request)
2140 {
2141 bool result = true;
2142 /* decide if we want to do Ranges ourselves
2143 * and fetch the whole object now)
2144 * We want to handle Ranges ourselves iff
2145 * - we can actually parse client Range specs
2146 * - the specs are expected to be simple enough (e.g. no out-of-order ranges)
2147 * - reply will be cachable
2148 * (If the reply will be uncachable we have to throw it away after
2149 * serving this request, so it is better to forward ranges to
2150 * the server and fetch only the requested content)
2151 */
2152
2153 int64_t roffLimit = request->getRangeOffsetLimit();
2154
2155 if (NULL == request->range || !request->flags.cachable
2156 || request->range->offsetLimitExceeded(roffLimit) || request->flags.connectionAuth)
2157 result = false;
2158
2159 debugs(11, 8, "decideIfWeDoRanges: range specs: " <<
2160 request->range << ", cachable: " <<
2161 request->flags.cachable << "; we_do_ranges: " << result);
2162
2163 return result;
2164 }
2165
2166 /* build request prefix and append it to a given MemBuf;
2167 * return the length of the prefix */
2168 mb_size_t
2169 HttpStateData::buildRequestPrefix(MemBuf * mb)
2170 {
2171 const int offset = mb->size;
2172 /* Uses a local httpver variable to print the HTTP label
2173 * since the HttpRequest may have an older version label.
2174 * XXX: This could create protocol bugs as the headers sent and
2175 * flow control should all be based on the HttpRequest version
2176 * not the one we are sending. Needs checking.
2177 */
2178 const AnyP::ProtocolVersion httpver = Http::ProtocolVersion();
2179 const SBuf url(_peer && !_peer->options.originserver ? request->effectiveRequestUri() : request->url.path());
2180 mb->appendf(SQUIDSBUFPH " " SQUIDSBUFPH " %s/%d.%d\r\n",
2181 SQUIDSBUFPRINT(request->method.image()),
2182 SQUIDSBUFPRINT(url),
2183 AnyP::ProtocolType_str[httpver.protocol],
2184 httpver.major,httpver.minor);
2185 /* build and pack headers */
2186 {
2187 HttpHeader hdr(hoRequest);
2188 httpBuildRequestHeader(request, entry, fwd->al, &hdr, flags);
2189
2190 if (request->flags.pinned && request->flags.connectionAuth)
2191 request->flags.authSent = true;
2192 else if (hdr.has(Http::HdrType::AUTHORIZATION))
2193 request->flags.authSent = true;
2194
2195 hdr.packInto(mb);
2196 hdr.clean();
2197 }
2198 /* append header terminator */
2199 mb->append(crlf, 2);
2200 return mb->size - offset;
2201 }
2202
2203 /* This will be called when connect completes. Write request. */
2204 bool
2205 HttpStateData::sendRequest()
2206 {
2207 MemBuf mb;
2208
2209 debugs(11, 5, HERE << serverConnection << ", request " << request << ", this " << this << ".");
2210
2211 if (!Comm::IsConnOpen(serverConnection)) {
2212 debugs(11,3, HERE << "cannot send request to closing " << serverConnection);
2213 assert(closeHandler != NULL);
2214 return false;
2215 }
2216
2217 typedef CommCbMemFunT<HttpStateData, CommTimeoutCbParams> TimeoutDialer;
2218 AsyncCall::Pointer timeoutCall = JobCallback(11, 5,
2219 TimeoutDialer, this, HttpStateData::httpTimeout);
2220 commSetConnTimeout(serverConnection, Config.Timeout.lifetime, timeoutCall);
2221 flags.do_next_read = true;
2222 maybeReadVirginBody();
2223
2224 if (request->body_pipe != NULL) {
2225 if (!startRequestBodyFlow()) // register to receive body data
2226 return false;
2227 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
2228 requestSender = JobCallback(11,5,
2229 Dialer, this, HttpStateData::sentRequestBody);
2230
2231 Must(!flags.chunked_request);
2232 // use chunked encoding if we do not know the length
2233 if (request->content_length < 0)
2234 flags.chunked_request = true;
2235 } else {
2236 assert(!requestBodySource);
2237 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
2238 requestSender = JobCallback(11,5,
2239 Dialer, this, HttpStateData::wroteLast);
2240 }
2241
2242 flags.originpeer = (_peer != NULL && _peer->options.originserver);
2243 flags.proxying = (_peer != NULL && !flags.originpeer);
2244
2245 /*
2246 * Is keep-alive okay for all request methods?
2247 */
2248 if (request->flags.mustKeepalive)
2249 flags.keepalive = true;
2250 else if (request->flags.pinned)
2251 flags.keepalive = request->persistent();
2252 else if (!Config.onoff.server_pconns)
2253 flags.keepalive = false;
2254 else if (_peer == NULL)
2255 flags.keepalive = true;
2256 else if (_peer->stats.n_keepalives_sent < 10)
2257 flags.keepalive = true;
2258 else if ((double) _peer->stats.n_keepalives_recv /
2259 (double) _peer->stats.n_keepalives_sent > 0.50)
2260 flags.keepalive = true;
2261
2262 if (_peer) {
2263 /*The old code here was
2264 if (neighborType(_peer, request->url) == PEER_SIBLING && ...
2265 which is equivalent to:
2266 if (neighborType(_peer, URL()) == PEER_SIBLING && ...
2267 or better:
2268 if (((_peer->type == PEER_MULTICAST && p->options.mcast_siblings) ||
2269 _peer->type == PEER_SIBLINGS ) && _peer->options.allow_miss)
2270 flags.only_if_cached = 1;
2271
2272 But I suppose it was a bug
2273 */
2274 if (neighborType(_peer, request->url) == PEER_SIBLING && !_peer->options.allow_miss)
2275 flags.only_if_cached = true;
2276
2277 flags.front_end_https = _peer->front_end_https;
2278 }
2279
2280 mb.init();
2281 request->peer_host=_peer?_peer->host:NULL;
2282 buildRequestPrefix(&mb);
2283
2284 debugs(11, 2, "HTTP Server " << serverConnection);
2285 debugs(11, 2, "HTTP Server REQUEST:\n---------\n" << mb.buf << "\n----------");
2286
2287 Comm::Write(serverConnection, &mb, requestSender);
2288 return true;
2289 }
2290
2291 bool
2292 HttpStateData::getMoreRequestBody(MemBuf &buf)
2293 {
2294 // parent's implementation can handle the no-encoding case
2295 if (!flags.chunked_request)
2296 return Client::getMoreRequestBody(buf);
2297
2298 MemBuf raw;
2299
2300 Must(requestBodySource != NULL);
2301 if (!requestBodySource->getMoreData(raw))
2302 return false; // no request body bytes to chunk yet
2303
2304 // optimization: pre-allocate buffer size that should be enough
2305 const mb_size_t rawDataSize = raw.contentSize();
2306 // we may need to send: hex-chunk-size CRLF raw-data CRLF last-chunk
2307 buf.init(16 + 2 + rawDataSize + 2 + 5, raw.max_capacity);
2308
2309 buf.appendf("%x\r\n", static_cast<unsigned int>(rawDataSize));
2310 buf.append(raw.content(), rawDataSize);
2311 buf.append("\r\n", 2);
2312
2313 Must(rawDataSize > 0); // we did not accidently created last-chunk above
2314
2315 // Do not send last-chunk unless we successfully received everything
2316 if (receivedWholeRequestBody) {
2317 Must(!flags.sentLastChunk);
2318 flags.sentLastChunk = true;
2319 buf.append("0\r\n\r\n", 5);
2320 }
2321
2322 return true;
2323 }
2324
2325 void
2326 httpStart(FwdState *fwd)
2327 {
2328 debugs(11, 3, fwd->request->method << ' ' << fwd->entry->url());
2329 AsyncJob::Start(new HttpStateData(fwd));
2330 }
2331
2332 void
2333 HttpStateData::start()
2334 {
2335 if (!sendRequest()) {
2336 debugs(11, 3, "httpStart: aborted");
2337 mustStop("HttpStateData::start failed");
2338 return;
2339 }
2340
2341 ++ statCounter.server.all.requests;
2342 ++ statCounter.server.http.requests;
2343
2344 /*
2345 * We used to set the read timeout here, but not any more.
2346 * Now its set in httpSendComplete() after the full request,
2347 * including request body, has been written to the server.
2348 */
2349 }
2350
2351 /// if broken posts are enabled for the request, try to fix and return true
2352 bool
2353 HttpStateData::finishingBrokenPost()
2354 {
2355 #if USE_HTTP_VIOLATIONS
2356 if (!Config.accessList.brokenPosts) {
2357 debugs(11, 5, HERE << "No brokenPosts list");
2358 return false;
2359 }
2360
2361 ACLFilledChecklist ch(Config.accessList.brokenPosts, originalRequest(), NULL);
2362 if (ch.fastCheck() != ACCESS_ALLOWED) {
2363 debugs(11, 5, HERE << "didn't match brokenPosts");
2364 return false;
2365 }
2366
2367 if (!Comm::IsConnOpen(serverConnection)) {
2368 debugs(11, 3, HERE << "ignoring broken POST for closed " << serverConnection);
2369 assert(closeHandler != NULL);
2370 return true; // prevent caller from proceeding as if nothing happened
2371 }
2372
2373 debugs(11, 3, "finishingBrokenPost: fixing broken POST");
2374 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
2375 requestSender = JobCallback(11,5,
2376 Dialer, this, HttpStateData::wroteLast);
2377 Comm::Write(serverConnection, "\r\n", 2, requestSender, NULL);
2378 return true;
2379 #else
2380 return false;
2381 #endif /* USE_HTTP_VIOLATIONS */
2382 }
2383
2384 /// if needed, write last-chunk to end the request body and return true
2385 bool
2386 HttpStateData::finishingChunkedRequest()
2387 {
2388 if (flags.sentLastChunk) {
2389 debugs(11, 5, HERE << "already sent last-chunk");
2390 return false;
2391 }
2392
2393 Must(receivedWholeRequestBody); // or we should not be sending last-chunk
2394 flags.sentLastChunk = true;
2395
2396 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
2397 requestSender = JobCallback(11,5, Dialer, this, HttpStateData::wroteLast);
2398 Comm::Write(serverConnection, "0\r\n\r\n", 5, requestSender, NULL);
2399 return true;
2400 }
2401
2402 void
2403 HttpStateData::doneSendingRequestBody()
2404 {
2405 Client::doneSendingRequestBody();
2406 debugs(11,5, HERE << serverConnection);
2407
2408 // do we need to write something after the last body byte?
2409 if (flags.chunked_request && finishingChunkedRequest())
2410 return;
2411 if (!flags.chunked_request && finishingBrokenPost())
2412 return;
2413
2414 sendComplete();
2415 }
2416
2417 // more origin request body data is available
2418 void
2419 HttpStateData::handleMoreRequestBodyAvailable()
2420 {
2421 if (eof || !Comm::IsConnOpen(serverConnection)) {
2422 // XXX: we should check this condition in other callbacks then!
2423 // TODO: Check whether this can actually happen: We should unsubscribe
2424 // as a body consumer when the above condition(s) are detected.
2425 debugs(11, DBG_IMPORTANT, HERE << "Transaction aborted while reading HTTP body");
2426 return;
2427 }
2428
2429 assert(requestBodySource != NULL);
2430
2431 if (requestBodySource->buf().hasContent()) {
2432 // XXX: why does not this trigger a debug message on every request?
2433
2434 if (flags.headers_parsed && !flags.abuse_detected) {
2435 flags.abuse_detected = true;
2436 debugs(11, DBG_IMPORTANT, "http handleMoreRequestBodyAvailable: Likely proxy abuse detected '" << request->client_addr << "' -> '" << entry->url() << "'" );
2437
2438 if (virginReply()->sline.status() == Http::scInvalidHeader) {
2439 closeServer();
2440 mustStop("HttpStateData::handleMoreRequestBodyAvailable");
2441 return;
2442 }
2443 }
2444 }
2445
2446 HttpStateData::handleMoreRequestBodyAvailable();
2447 }
2448
2449 // premature end of the request body
2450 void
2451 HttpStateData::handleRequestBodyProducerAborted()
2452 {
2453 Client::handleRequestBodyProducerAborted();
2454 if (entry->isEmpty()) {
2455 debugs(11, 3, "request body aborted: " << serverConnection);
2456 // We usually get here when ICAP REQMOD aborts during body processing.
2457 // We might also get here if client-side aborts, but then our response
2458 // should not matter because either client-side will provide its own or
2459 // there will be no response at all (e.g., if the the client has left).
2460 ErrorState *err = new ErrorState(ERR_ICAP_FAILURE, Http::scInternalServerError, fwd->request);
2461 err->detailError(ERR_DETAIL_SRV_REQMOD_REQ_BODY);
2462 fwd->fail(err);
2463 }
2464
2465 abortTransaction("request body producer aborted");
2466 }
2467
2468 // called when we wrote request headers(!) or a part of the body
2469 void
2470 HttpStateData::sentRequestBody(const CommIoCbParams &io)
2471 {
2472 if (io.size > 0)
2473 statCounter.server.http.kbytes_out += io.size;
2474
2475 Client::sentRequestBody(io);
2476 }
2477
2478 void
2479 HttpStateData::abortAll(const char *reason)
2480 {
2481 debugs(11,5, HERE << "aborting transaction for " << reason <<
2482 "; " << serverConnection << ", this " << this);
2483 mustStop(reason);
2484 }
2485