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