]> git.ipfire.org Git - thirdparty/squid.git/blame - src/http.cc
Docs: Fix Squid-5 reference in v5 release notes (#530)
[thirdparty/squid.git] / src / http.cc
CommitLineData
30a4f2a8 1/*
f6e9a3ee 2 * Copyright (C) 1996-2019 The Squid Software Foundation and contributors
30a4f2a8 3 *
bbc27441
AJ
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.
30a4f2a8 7 */
019dd986 8
bbc27441
AJ
9/* DEBUG: section 11 Hypertext Transfer Protocol (HTTP) */
10
4a83b852 11/*
12 * Anonymizing patch by lutz@as-node.jena.thur.de
de3bdb4c 13 * have a look into http-anon.c to get more informations.
4a83b852 14 */
15
582c2af2 16#include "squid.h"
9ca29d23 17#include "acl/FilledChecklist.h"
655daa06 18#include "base/AsyncJobCalls.h"
3d93a84d 19#include "base/TextException.h"
602d9612 20#include "base64.h"
a011edee 21#include "CachePeer.h"
582c2af2 22#include "client_side.h"
8d71285d 23#include "comm/Connection.h"
395a814a 24#include "comm/Read.h"
ec41b64c 25#include "comm/Write.h"
d4a083cc 26#include "CommRead.h"
8b997339 27#include "err_detail_type.h"
aa839030 28#include "errorpage.h"
fc54b8d2 29#include "fd.h"
85bef0a7 30#include "fde.h"
67679543 31#include "globals.h"
582c2af2 32#include "http.h"
f542211b 33#include "http/one/ResponseParser.h"
db1720f8 34#include "http/one/TeChunkedParser.h"
d3dddfb5 35#include "http/Stream.h"
602d9612 36#include "HttpControlMsg.h"
7ebe76de 37#include "HttpHdrCc.h"
582c2af2 38#include "HttpHdrContRange.h"
b19dd748 39#include "HttpHdrSc.h"
40#include "HttpHdrScTarget.h"
fc54b8d2 41#include "HttpHeaderTools.h"
9ca29d23
AJ
42#include "HttpReply.h"
43#include "HttpRequest.h"
fc54b8d2 44#include "log/access_log.h"
9ca29d23
AJ
45#include "MemBuf.h"
46#include "MemObject.h"
fc54b8d2 47#include "neighbors.h"
55622953 48#include "pconn.h"
6ff204fc 49#include "peer_proxy_negotiate_auth.h"
582c2af2 50#include "profiler/Profiler.h"
fc54b8d2 51#include "refresh.h"
8d9a8184 52#include "RefreshPattern.h"
1fa9b1a7 53#include "rfc1738.h"
4d5904f7 54#include "SquidConfig.h"
985c86bc 55#include "SquidTime.h"
e4f1fdae 56#include "StatCounters.h"
9ca29d23 57#include "Store.h"
28204b3b 58#include "StrList.h"
fc54b8d2 59#include "tools.h"
ed6e9fb9 60#include "util.h"
af0bb8e5 61
582c2af2
FC
62#if USE_AUTH
63#include "auth/UserRequest.h"
64#endif
65#if USE_DELAY_POOLS
66#include "DelayPools.h"
67#endif
9ca29d23 68
af0bb8e5 69#define SQUID_ENTER_THROWING_CODE() try {
70#define SQUID_EXIT_THROWING_CODE(status) \
f53969cc 71 status = true; \
af0bb8e5 72 } \
0a8bbeeb 73 catch (const std::exception &e) { \
f53969cc
SM
74 debugs (11, 1, "Exception error:" << e.what()); \
75 status = false; \
9e008dda 76 }
e6ccf245 77
2afaba07 78CBDATA_CLASS_INIT(HttpStateData);
090089c4 79
6bf8443a 80static const char *const crlf = "\r\n";
4db43fab 81
955394ce 82static void httpMaybeRemovePublic(StoreEntry *, Http::StatusCode);
e24f13cd 83static void copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, const String strConnection, const HttpRequest * request,
bad9c5e4 84 HttpHeader * hdr_out, const int we_do_ranges, const Http::StateFlags &);
528b2c61 85
8e100780 86HttpStateData::HttpStateData(FwdState *theFwdState) :
1810a0cb
SM
87 AsyncJob("HttpStateData"),
88 Client(theFwdState),
89 lastChunk(0),
90 httpChunkDecoder(NULL),
91 payloadSeen(0),
eace013e
EB
92 payloadTruncated(0),
93 sawDateGoBack(false)
2bb867b5 94{
95 debugs(11,5,HERE << "HttpStateData " << this << " created");
a3d50c30 96 ignoreCacheControl = false;
97 surrogateNoStore = false;
8d71285d 98 serverConnection = fwd->serverConnection();
a3d50c30 99
5229395c
AJ
100 if (fwd->serverConnection() != NULL)
101 _peer = cbdataReference(fwd->serverConnection()->getPeer()); /* might be NULL */
a3d50c30 102
f5e17947
CT
103 flags.peering = _peer;
104 flags.tunneling = (_peer && request->flags.sslBumped);
105 flags.toOrigin = (!_peer || _peer->options.originserver || request->flags.sslBumped);
106
a3d50c30 107 if (_peer) {
a3d50c30 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 */
f5e17947 113 if (!flags.tunneling && _peer->options.proxy_only)
4310f8b0 114 entry->releaseRequest(true);
a3d50c30 115
9a0a18de 116#if USE_DELAY_POOLS
a3d50c30 117 entry->setNoDelay(_peer->options.no_delay);
a3d50c30 118#endif
a3d50c30 119 }
120
121 /*
122 * register the handler to free HTTP state data when the FD closes
123 */
dc56a9b1 124 typedef CommCbMemFunT<HttpStateData, CommCloseCbParams> Dialer;
d1c7f781 125 closeHandler = JobCallback(9, 5, Dialer, this, HttpStateData::httpStateConnClosed);
8d71285d 126 comm_add_close_handler(serverConnection->fd, closeHandler);
2bb867b5 127}
b8d8561b 128
2afaba07 129HttpStateData::~HttpStateData()
f5558c95 130{
253caccb 131 /*
fccd4a86 132 * don't forget that ~Client() gets called automatically
253caccb 133 */
134
9e008dda
AJ
135 if (httpChunkDecoder)
136 delete httpChunkDecoder;
af0bb8e5 137
5229395c
AJ
138 cbdataReferenceDone(_peer);
139
9cf7de1b 140 debugs(11,5, HERE << "HttpStateData " << this << " destroyed; " << serverConnection);
5f8252d2 141}
142
6b679a01 143const Comm::ConnectionPointer &
e83cc785 144HttpStateData::dataConnection() const
fc68f6b1 145{
6b679a01 146 return serverConnection;
2afaba07 147}
8d71285d 148
9e008dda 149void
dc56a9b1 150HttpStateData::httpStateConnClosed(const CommCloseCbParams &params)
151{
152 debugs(11, 5, "httpStateFree: FD " << params.fd << ", httpState=" << params.data);
70df76e3 153 doneWithFwd = "httpStateConnClosed()"; // assume FwdState is monitoring too
79628299 154 mustStop("HttpStateData::httpStateConnClosed");
f5558c95 155}
156
dc56a9b1 157void
ced8def3 158HttpStateData::httpTimeout(const CommTimeoutCbParams &)
090089c4 159{
ced8def3 160 debugs(11, 4, serverConnection << ": '" << entry->url() << "'");
62e76326 161
12158bdc 162 if (entry->store_status == STORE_PENDING) {
7e6eabbc 163 fwd->fail(new ErrorState(ERR_READ_TIMEOUT, Http::scGatewayTimeout, fwd->request, fwd->al));
9b312a19 164 }
62e76326 165
398bc066
CT
166 closeServer();
167 mustStop("HttpStateData::httpTimeout");
090089c4 168}
169
eace013e
EB
170static StoreEntry *
171findPreviouslyCachedEntry(StoreEntry *newEntry) {
172 assert(newEntry->mem_obj);
173 return newEntry->mem_obj->request ?
c43405e7 174 storeGetPublicByRequest(newEntry->mem_obj->request.getRaw()) :
eace013e
EB
175 storeGetPublic(newEntry->mem_obj->storeId(), newEntry->mem_obj->method);
176}
177
09f0985d
AR
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.
f9cece6e 180static void
955394ce 181httpMaybeRemovePublic(StoreEntry * e, Http::StatusCode status)
f9cece6e 182{
914b89a2 183 int remove = 0;
7e3ce7b9 184 int forbidden = 0;
62e76326 185
09f0985d
AR
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.
d46a87a8 188 if (!EBIT_TEST(e->flags, KEY_PRIVATE))
62e76326 189 return;
3140dc6a
GD
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;
62e76326 196
f9cece6e 197 switch (status) {
62e76326 198
955394ce 199 case Http::scOkay:
62e76326 200
955394ce 201 case Http::scNonAuthoritativeInformation:
62e76326 202
955394ce 203 case Http::scMultipleChoices:
62e76326 204
955394ce 205 case Http::scMovedPermanently:
62e76326 206
f11c8e2f 207 case Http::scFound:
62e76326 208
5613c60d
GD
209 case Http::scSeeOther:
210
955394ce 211 case Http::scGone:
62e76326 212
955394ce 213 case Http::scNotFound:
914b89a2 214 remove = 1;
62e76326 215
216 break;
217
955394ce 218 case Http::scForbidden:
62e76326 219
955394ce 220 case Http::scMethodNotAllowed:
62e76326 221 forbidden = 1;
222
223 break;
224
f9cece6e 225#if WORK_IN_PROGRESS
62e76326 226
955394ce 227 case Http::scUnauthorized:
62e76326 228 forbidden = 1;
229
230 break;
231
f9cece6e 232#endif
62e76326 233
f9cece6e 234 default:
7e3ce7b9 235#if QUESTIONABLE
62e76326 236 /*
237 * Any 2xx response should eject previously cached entities...
238 */
abb929f0 239
62e76326 240 if (status >= 200 && status < 300)
914b89a2 241 remove = 1;
62e76326 242
7e3ce7b9 243#endif
62e76326 244
245 break;
f9cece6e 246 }
62e76326 247
914b89a2 248 if (!remove && !forbidden)
62e76326 249 return;
250
eace013e 251 StoreEntry *pe = findPreviouslyCachedEntry(e);
62e76326 252
f66a9ef4 253 if (pe != NULL) {
62e76326 254 assert(e != pe);
d9129474 255#if USE_HTCP
c43405e7 256 neighborsHtcpClear(e, nullptr, e->mem_obj->request.getRaw(), e->mem_obj->method, HTCP_CLR_INVALIDATION);
d9129474 257#endif
4310f8b0 258 pe->release(true);
0856d155 259 }
62e76326 260
914b89a2 261 /** \par
7e3ce7b9 262 * Also remove any cached HEAD response in case the object has
263 * changed.
264 */
f66a9ef4 265 if (e->mem_obj->request)
c43405e7 266 pe = storeGetPublicByRequestMethod(e->mem_obj->request.getRaw(), Http::METHOD_HEAD);
f66a9ef4 267 else
c877c0bc 268 pe = storeGetPublic(e->mem_obj->storeId(), Http::METHOD_HEAD);
62e76326 269
f66a9ef4 270 if (pe != NULL) {
62e76326 271 assert(e != pe);
d9129474 272#if USE_HTCP
c43405e7 273 neighborsHtcpClear(e, nullptr, e->mem_obj->request.getRaw(), HttpRequestMethod(Http::METHOD_HEAD), HTCP_CLR_INVALIDATION);
d9129474 274#endif
4310f8b0 275 pe->release(true);
7e3ce7b9 276 }
f9cece6e 277}
278
43ae1d95 279void
280HttpStateData::processSurrogateControl(HttpReply *reply)
281{
45e5102d 282 if (request->flags.accelerated && reply->surrogate_control) {
45a58345 283 HttpHdrScTarget *sctusable = reply->surrogate_control->getMergedTarget(Config.Accel.surrogate_id);
43ae1d95 284
285 if (sctusable) {
810d879f 286 if (sctusable->hasNoStore() ||
43ae1d95 287 (Config.onoff.surrogate_is_remote
45a58345 288 && sctusable->noStoreRemote())) {
43ae1d95 289 surrogateNoStore = true;
39fe14b2
EB
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);
43ae1d95 293 }
294
295 /* The HttpHeader logic cannot tell if the header it's parsing is a reply to an
296 * accelerated request or not...
45cca89d 297 * Still, this is an abstraction breach. - RC
43ae1d95 298 */
45a58345
FC
299 if (sctusable->hasMaxAge()) {
300 if (sctusable->maxAge() < sctusable->maxStale())
301 reply->expires = reply->date + sctusable->maxAge();
43ae1d95 302 else
45a58345 303 reply->expires = reply->date + sctusable->maxStale();
43ae1d95 304
305 /* And update the timestamps */
3900307b 306 entry->timestampsSet();
43ae1d95 307 }
308
309 /* We ignore cache-control directives as per the Surrogate specification */
310 ignoreCacheControl = true;
311
45a58345 312 delete sctusable;
43ae1d95 313 }
314 }
43ae1d95 315}
316
39fe14b2
EB
317HttpStateData::ReuseDecision::Answers
318HttpStateData::reusableReply(HttpStateData::ReuseDecision &decision)
c54e9052 319{
585ab260 320 HttpReply const *rep = finalReply();
528b2c61 321 HttpHeader const *hdr = &rep->header;
c68e9c6b 322 const char *v;
626096be 323#if USE_HTTP_VIOLATIONS
62e76326 324
8d9a8184 325 const RefreshPattern *R = NULL;
b6445726 326
346be6ad 327 /* This strange looking define first looks up the refresh pattern
b6445726 328 * and then checks if the specified flag is set. The main purpose
626096be 329 * of this is to simplify the refresh pattern lookup and USE_HTTP_VIOLATIONS
b6445726 330 * condition
331 */
332#define REFRESH_OVERRIDE(flag) \
c877c0bc 333 ((R = (R ? R : refreshLimits(entry->mem_obj->storeId()))) , \
5f8252d2 334 (R && R->flags.flag))
b445957e 335#else
336#define REFRESH_OVERRIDE(flag) 0
38f9c547 337#endif
43ae1d95 338
39fe14b2 339 if (EBIT_TEST(entry->flags, RELEASE_REQUEST))
4310f8b0 340 return decision.make(ReuseDecision::doNotCacheButShare, "the entry has been released");
6919be24 341
eace013e
EB
342 // RFC 7234 section 4: a cache MUST use the most recent response
343 // (as determined by the Date header field)
39fe14b2
EB
344 // TODO: whether such responses could be shareable?
345 if (sawDateGoBack)
346 return decision.make(ReuseDecision::reuseNot, "the response has an older date header");
eace013e 347
2b59002c
AJ
348 // Check for Surrogate/1.0 protocol conditions
349 // NP: reverse-proxy traffic our parent server has instructed us never to cache
39fe14b2
EB
350 if (surrogateNoStore)
351 return decision.make(ReuseDecision::reuseNot, "Surrogate-Control:no-store");
62e76326 352
2b59002c
AJ
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
8466a4af 358
2b59002c 359 // RFC 2616 section 14.9.2 - MUST NOT cache any response with request CC:no-store
810d879f 360 if (request && request->cache_control && request->cache_control->hasNoStore() &&
39fe14b2
EB
361 !REFRESH_OVERRIDE(ignore_no_store))
362 return decision.make(ReuseDecision::reuseNot,
363 "client request Cache-Control:no-store");
38f9c547 364
2b59002c 365 // NP: request CC:no-cache only means cache READ is forbidden. STORE is permitted.
810d879f 366 if (rep->cache_control && rep->cache_control->hasNoCacheWithParameters()) {
1259f9cf
AJ
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 */
39fe14b2
EB
372 return decision.make(ReuseDecision::reuseNot,
373 "server reply Cache-Control:no-cache has parameters");
1259f9cf
AJ
374 }
375
2b59002c
AJ
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
810d879f 380 if (rep->cache_control && rep->cache_control->hasNoStore() &&
39fe14b2
EB
381 !REFRESH_OVERRIDE(ignore_no_store))
382 return decision.make(ReuseDecision::reuseNot,
383 "server reply Cache-Control:no-store");
38f9c547 384
2b59002c 385 // RFC 2616 section 14.9.1 - MUST NOT cache any response with CC:private in a shared cache like Squid.
1259f9cf 386 // CC:private overrides CC:public when both are present in a response.
2b59002c
AJ
387 // TODO: add a shared/private cache configuration possibility.
388 if (rep->cache_control &&
1259f9cf 389 rep->cache_control->hasPrivate() &&
2b59002c 390 !REFRESH_OVERRIDE(ignore_private)) {
1259f9cf
AJ
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 */
39fe14b2
EB
396 return decision.make(ReuseDecision::reuseNot,
397 "server reply Cache-Control:private");
38f9c547 398 }
2b59002c 399 }
1259f9cf 400
2b59002c
AJ
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)
d94cbaa8 403 if (request && (request->flags.auth || request->flags.authSent)) {
39fe14b2
EB
404 if (!rep->cache_control)
405 return decision.make(ReuseDecision::reuseNot,
406 "authenticated and server reply missing Cache-Control");
62e76326 407
39fe14b2
EB
408 if (ignoreCacheControl)
409 return decision.make(ReuseDecision::reuseNot,
410 "authenticated and ignoring Cache-Control");
62e76326 411
2b59002c 412 bool mayStore = false;
8f9343d0 413 // HTTPbis pt6 section 3.2: a response CC:public is present
810d879f 414 if (rep->cache_control->hasPublic()) {
2b59002c
AJ
415 debugs(22, 3, HERE << "Authenticated but server reply Cache-Control:public");
416 mayStore = true;
417
8f9343d0 418 // HTTPbis pt6 section 3.2: a response CC:must-revalidate is present
810d879f 419 } else if (rep->cache_control->hasMustRevalidate()) {
d94cbaa8 420 debugs(22, 3, HERE << "Authenticated but server reply Cache-Control:must-revalidate");
2b59002c
AJ
421 mayStore = true;
422
8f9343d0 423#if USE_HTTP_VIOLATIONS
2b59002c 424 // NP: given the must-revalidate exception we should also be able to exempt no-cache.
8f9343d0
AJ
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
1259f9cf 427 // (without parameters) as equivalent to must-revalidate in the reply.
810d879f 428 } else if (rep->cache_control->hasNoCacheWithoutParameters()) {
8f9343d0 429 debugs(22, 3, HERE << "Authenticated but server reply Cache-Control:no-cache (equivalent to must-revalidate)");
2b59002c
AJ
430 mayStore = true;
431#endif
432
8f9343d0 433 // HTTPbis pt6 section 3.2: a response CC:s-maxage is present
810d879f 434 } else if (rep->cache_control->hasSMaxAge()) {
908ac81e 435 debugs(22, 3, HERE << "Authenticated but server reply Cache-Control:s-maxage");
2b59002c
AJ
436 mayStore = true;
437 }
62e76326 438
39fe14b2
EB
439 if (!mayStore)
440 return decision.make(ReuseDecision::reuseNot, "authenticated transaction");
2b59002c
AJ
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.
c68e9c6b 444 }
62e76326 445
2b59002c 446 /* HACK: The "multipart/x-mixed-replace" content type is used for
c68e9c6b 447 * continuous push replies. These are generally dynamic and
448 * probably should not be cachable
449 */
789217a2 450 if ((v = hdr->getStr(Http::HdrType::CONTENT_TYPE)))
39fe14b2
EB
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;
62e76326 459
9b769c67 460 switch (rep->sline.status()) {
39fe14b2
EB
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
f53969cc 471 /* Responses that are cacheable */
62e76326 472
955394ce 473 case Http::scOkay:
62e76326 474
955394ce 475 case Http::scNonAuthoritativeInformation:
62e76326 476
955394ce 477 case Http::scMultipleChoices:
62e76326 478
955394ce
AJ
479 case Http::scMovedPermanently:
480 case Http::scPermanentRedirect:
62e76326 481
955394ce 482 case Http::scGone:
62e76326 483 /*
484 * Don't cache objects that need to be refreshed on next request,
485 * unless we know how to refresh it.
486 */
487
39fe14b2
EB
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");
62e76326 492 break;
493
f53969cc 494 /* Responses that only are cacheable if the server says so */
62e76326 495
f11c8e2f 496 case Http::scFound:
955394ce 497 case Http::scTemporaryRedirect:
39fe14b2
EB
498 if (rep->date <= 0)
499 decision.make(ReuseDecision::doNotCacheButShare, "Date is missing/invalid");
3655aa12 500 else if (rep->expires > rep->date)
39fe14b2
EB
501 decision.make(ReuseDecision::cachePositively, "Expires > Date");
502 else
503 decision.make(ReuseDecision::doNotCacheButShare, "Expires <= Date");
62e76326 504 break;
505
c3d5e452 506 /* These responses can be negatively cached. Most can also be shared. */
955394ce 507 case Http::scNoContent:
955394ce 508 case Http::scUseProxy:
955394ce 509 case Http::scForbidden:
955394ce 510 case Http::scNotFound:
955394ce 511 case Http::scMethodNotAllowed:
f11c8e2f 512 case Http::scUriTooLong:
955394ce 513 case Http::scInternalServerError:
955394ce 514 case Http::scNotImplemented:
955394ce 515 case Http::scBadGateway:
955394ce 516 case Http::scServiceUnavailable:
f11c8e2f 517 case Http::scGatewayTimeout:
fe3f8977 518 case Http::scMisdirectedRequest:
39fe14b2
EB
519 statusAnswer = ReuseDecision::doNotCacheButShare;
520 statusReason = shareableError;
0d175eb8 521 // fall through to the actual decision making below
62e76326 522
c3d5e452 523 case Http::scBadRequest: // no sharing; perhaps the server did not like something specific to this request
39fe14b2
EB
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);
62e76326 530 break;
531
39fe14b2
EB
532 /* these responses can never be cached, some
533 of them can be shared though */
955394ce 534 case Http::scSeeOther:
955394ce 535 case Http::scNotModified:
955394ce 536 case Http::scUnauthorized:
955394ce 537 case Http::scProxyAuthenticationRequired:
955394ce 538 case Http::scPaymentRequired:
39fe14b2
EB
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 */
955394ce 545 case Http::scNotAcceptable:
39fe14b2
EB
546 case Http::scRequestTimeout: // TODO: is this shareable?
547 case Http::scConflict: // TODO: is this shareable?
955394ce
AJ
548 case Http::scLengthRequired:
549 case Http::scPreconditionFailed:
f11c8e2f 550 case Http::scPayloadTooLarge:
955394ce
AJ
551 case Http::scUnsupportedMediaType:
552 case Http::scUnprocessableEntity:
39fe14b2 553 case Http::scLocked: // TODO: is this shareable?
955394ce 554 case Http::scFailedDependency:
955394ce
AJ
555 case Http::scRequestedRangeNotSatisfied:
556 case Http::scExpectationFailed:
39fe14b2
EB
557 case Http::scInvalidHeader: /* Squid header parsing error */
558 case Http::scHeaderTooLarge:
559 decision.make(ReuseDecision::reuseNot, nonShareableError);
560 break;
62e76326 561
41217979
AJ
562 default:
563 /* RFC 2616 section 6.1.1: an unrecognized response MUST NOT be cached. */
39fe14b2 564 decision.make(ReuseDecision::reuseNot, "unknown status code");
62e76326 565 break;
c54e9052 566 }
62e76326 567
39fe14b2 568 return decision.answer;
c54e9052 569}
090089c4 570
f5df2040
AJ
571/// assemble a variant key (vary-mark) from the given Vary header and HTTP request
572static void
573assembleVaryKey(String &vary, SBuf &vstr, const HttpRequest &request)
f66a9ef4 574{
90ab8f20 575 static const SBuf asterisk("*");
f5df2040
AJ
576 const char *pos = nullptr;
577 const char *item = nullptr;
578 int ilen = 0;
62e76326 579
f66a9ef4 580 while (strListGetItem(&vary, ',', &item, &ilen, &pos)) {
81ab22b6
FC
581 SBuf name(item, ilen);
582 if (name == asterisk) {
ee2e0b31 583 vstr = asterisk;
9776e3cc 584 break;
585 }
81ab22b6 586 name.toLower();
90ab8f20
AJ
587 if (!vstr.isEmpty())
588 vstr.append(", ", 2);
589 vstr.append(name);
f5df2040
AJ
590 String hdr(request.header.getByName(name));
591 const char *value = hdr.termedBuf();
62e76326 592 if (value) {
593 value = rfc1738_escape_part(value);
594 vstr.append("=\"", 2);
595 vstr.append(value);
596 vstr.append("\"", 1);
597 }
598
30abd221 599 hdr.clean();
f66a9ef4 600 }
f5df2040 601}
62e76326 602
f5df2040
AJ
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 */
608SBuf
609httpMakeVaryMark(HttpRequest * request, HttpReply const * reply)
610{
611 SBuf vstr;
612 String vary;
62e76326 613
f5df2040
AJ
614 vary = reply->header.getList(Http::HdrType::VARY);
615 assembleVaryKey(vary, vstr, *request);
62e76326 616
f5df2040 617#if X_ACCELERATOR_VARY
30abd221 618 vary.clean();
f5df2040
AJ
619 vary = reply->header.getList(Http::HdrType::HDR_X_ACCELERATOR_VARY);
620 assembleVaryKey(vary, vstr, *request);
f66a9ef4 621#endif
62e76326 622
90ab8f20
AJ
623 debugs(11, 3, vstr);
624 return vstr;
f66a9ef4 625}
626
2afaba07 627void
628HttpStateData::keepaliveAccounting(HttpReply *reply)
629{
630 if (flags.keepalive)
f5e17947 631 if (flags.peering && !flags.tunneling)
95dc7ff4 632 ++ _peer->stats.n_keepalives_sent;
2afaba07 633
634 if (reply->keep_alive) {
f5e17947 635 if (flags.peering && !flags.tunneling)
95dc7ff4 636 ++ _peer->stats.n_keepalives_recv;
2afaba07 637
af6a12ee
AJ
638 if (Config.onoff.detect_broken_server_pconns
639 && reply->bodySize(request->method) == -1 && !flags.chunked) {
e0236918 640 debugs(11, DBG_IMPORTANT, "keepaliveAccounting: Impossible keep-alive header from '" << entry->url() << "'" );
bf8fe701 641 // debugs(11, 2, "GOT HTTP REPLY HDR:\n---------\n" << readBuf->content() << "\n----------" );
46f4b111 642 flags.keepalive_broken = true;
2afaba07 643 }
644 }
645}
646
647void
648HttpStateData::checkDateSkew(HttpReply *reply)
649{
f5e17947 650 if (reply->date > -1 && flags.toOrigin) {
2afaba07 651 int skew = abs((int)(reply->date - squid_curtime));
652
653 if (skew > 86400)
5c51bffb 654 debugs(11, 3, "" << request->url.host() << "'s clock is skewed by " << skew << " seconds!");
2afaba07 655 }
656}
657
073ba374 658/**
4eb368f9 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 */
b8d8561b 664void
2afaba07 665HttpStateData::processReplyHeader()
f5558c95 666{
073ba374 667 /** Creates a blank header. If this routine is made incremental, this will not do */
859f1666
AJ
668
669 /* NP: all exit points to this function MUST call ctx_exit(ctx) */
c877c0bc 670 Ctx ctx = ctx_enter(entry->mem_obj->urlXXX());
859f1666 671
bf8fe701 672 debugs(11, 3, "processReplyHeader: key '" << entry->getMD5Text() << "'");
62e76326 673
1a98175f 674 assert(!flags.headers_parsed);
62e76326 675
395a814a 676 if (!inBuf.length()) {
859f1666 677 ctx_exit(ctx);
b73a07d6 678 return;
859f1666 679 }
b73a07d6 680
f542211b
AJ
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 }
62e76326 708
f542211b
AJ
709 if (!parsedOk) {
710 // unrecoverable parsing error
3d67f7e6 711 // TODO: Use Raw! XXX: inBuf no longer has the [beginning of the] malformed header.
f542211b 712 debugs(11, 3, "Non-HTTP-compliant header:\n---------\n" << inBuf << "\n----------");
18b4c80d 713 flags.headers_parsed = true;
f542211b 714 HttpReply *newrep = new HttpReply;
3d67f7e6
AR
715 newrep->sline.set(Http::ProtocolVersion(), hp->parseStatusCode);
716 setVirginReply(newrep);
9e008dda
AJ
717 ctx_exit(ctx);
718 return;
719 }
f542211b 720 }
9e008dda 721
f542211b
AJ
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() <<
8e100780 727 "----------");
9e008dda 728
8e100780
AJ
729 // reset payload tracking to begin after message headers
730 payloadSeen = inBuf.length();
9e008dda 731
f542211b 732 HttpReply *newrep = new HttpReply;
62f9b110
AJ
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() */);
f542211b
AJ
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
af2980f3 742 if (!newrep->parseHeader(*hp)) {
f542211b
AJ
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");
f5558c95 749 }
62e76326 750
f542211b
AJ
751 // done with Parser, now process using the HttpReply
752 hp = NULL;
753
63df1d28 754 newrep->sources |= request->url.getScheme() == AnyP::PROTO_HTTPS ? Http::Message::srcHttps : Http::Message::srcHttp;
88df846b 755
c679653d 756 newrep->removeStaleWarnings();
3d9e71e6 757
4f1c93a7 758 if (newrep->sline.protocol == AnyP::PROTO_HTTP && Http::Is1xx(newrep->sline.status())) {
655daa06 759 handle1xx(newrep);
3d9e71e6 760 ctx_exit(ctx);
3d9e71e6
AJ
761 return;
762 }
763
46f4b111 764 flags.chunked = false;
0c3d3f65 765 if (newrep->sline.protocol == AnyP::PROTO_HTTP && newrep->header.chunked()) {
46f4b111 766 flags.chunked = true;
db1720f8 767 httpChunkDecoder = new Http1::TeChunkedParser;
af0bb8e5 768 }
769
9e008dda 770 if (!peerSupportsConnectionPinning())
e857372a 771 request->flags.connectionAuthDisabled = true;
d67acb4e 772
585ab260 773 HttpReply *vrep = setVirginReply(newrep);
46f4b111 774 flags.headers_parsed = true;
6965ab28 775
585ab260 776 keepaliveAccounting(vrep);
47ac2ebe 777
585ab260 778 checkDateSkew(vrep);
47ac2ebe 779
585ab260 780 processSurrogateControl (vrep);
528b2c61 781
9b769c67 782 request->hier.peer_reply_status = newrep->sline.status();
3ff65596 783
2afaba07 784 ctx_exit(ctx);
785}
786
655daa06
AR
787/// ignore or start forwarding the 1xx response (a.k.a., control message)
788void
789HttpStateData::handle1xx(HttpReply *reply)
790{
49f57088
EB
791 if (fwd->al)
792 fwd->al->reply = reply;
793
b248c2a3 794 HttpReply::Pointer msg(reply); // will destroy reply if unused
655daa06
AR
795
796 // one 1xx at a time: we must not be called while waiting for previous 1xx
797 Must(!flags.handling1xx);
798 flags.handling1xx = true;
799
ec69bdb2
CT
800 if (!request->canHandle1xx() || request->forcedBodyContinuation) {
801 debugs(11, 2, "ignoring 1xx because it is " << (request->forcedBodyContinuation ? "already sent" : "not supported by client"));
655daa06
AR
802 proceedAfter1xx();
803 return;
804 }
805
806#if USE_HTTP_VIOLATIONS
807 // check whether the 1xx response forwarding is allowed by squid.conf
808 if (Config.accessList.reply) {
d603e3c2 809 ACLFilledChecklist ch(Config.accessList.reply, originalRequest().getRaw());
cb365059 810 ch.al = fwd->al;
b248c2a3 811 ch.reply = reply;
cb365059 812 ch.syncAle(originalRequest().getRaw(), nullptr);
b248c2a3 813 HTTPMSGLOCK(ch.reply);
06bf5384 814 if (!ch.fastCheck().allowed()) { // TODO: support slow lookups?
655daa06
AR
815 debugs(11, 3, HERE << "ignoring denied 1xx");
816 proceedAfter1xx();
817 return;
de48b288 818 }
655daa06
AR
819 }
820#endif // USE_HTTP_VIOLATIONS
821
822 debugs(11, 2, HERE << "forwarding 1xx to client");
823
824 // the Sink will use this to call us back after writing 1xx to the client
825 typedef NullaryMemFunT<HttpStateData> CbDialer;
826 const AsyncCall::Pointer cb = JobCallback(11, 3, CbDialer, this,
de48b288 827 HttpStateData::proceedAfter1xx);
e24f13cd 828 CallJobHere1(11, 4, request->clientConnectionManager, ConnStateData,
655daa06
AR
829 ConnStateData::sendControlMsg, HttpControlMsg(msg, cb));
830 // If the call is not fired, then the Sink is gone, and HttpStateData
831 // will terminate due to an aborted store entry or another similar error.
832 // If we get stuck, it is not handle1xx fault if we could get stuck
833 // for similar reasons without a 1xx response.
834}
835
836/// restores state and resumes processing after 1xx is ignored or forwarded
837void
838HttpStateData::proceedAfter1xx()
839{
840 Must(flags.handling1xx);
8e100780 841 debugs(11, 2, "continuing with " << payloadSeen << " bytes in buffer after 1xx");
655daa06
AR
842 CallJobHere(11, 3, this, HttpStateData, HttpStateData::processReply);
843}
844
d67acb4e
AJ
845/**
846 * returns true if the peer can support connection pinning
847*/
f891baff
AJ
848bool
849HttpStateData::peerSupportsConnectionPinning() const
d67acb4e 850{
d67acb4e 851 if (!_peer)
9e008dda
AJ
852 return true;
853
f5e17947
CT
854 // we are talking "through" rather than "to" our _peer
855 if (flags.tunneling)
856 return true;
857
9e008dda 858 /*If this peer does not support connection pinning (authenticated
d67acb4e
AJ
859 connections) return false
860 */
861 if (!_peer->connection_auth)
9e008dda 862 return false;
d67acb4e 863
66d51f4f 864 const auto &rep = entry->mem().freshestReply();
f891baff 865
9e008dda 866 /*The peer supports connection pinning and the http reply status
d67acb4e
AJ
867 is not unauthorized, so the related connection can be pinned
868 */
66d51f4f 869 if (rep.sline.status() != Http::scUnauthorized)
9e008dda
AJ
870 return true;
871
955394ce 872 /*The server respond with Http::scUnauthorized and the peer configured
9e008dda 873 with "connection-auth=on" we know that the peer supports pinned
d67acb4e
AJ
874 connections
875 */
876 if (_peer->connection_auth == 1)
9e008dda 877 return true;
d67acb4e 878
9e008dda
AJ
879 /*At this point peer has configured with "connection-auth=auto"
880 parameter so we need some extra checks to decide if we are going
d67acb4e
AJ
881 to allow pinned connections or not
882 */
883
9e008dda 884 /*if the peer configured with originserver just allow connection
d67acb4e
AJ
885 pinning (squid 2.6 behaviour)
886 */
887 if (_peer->options.originserver)
9e008dda 888 return true;
d67acb4e
AJ
889
890 /*if the connections it is already pinned it is OK*/
45e5102d 891 if (request->flags.pinned)
9e008dda
AJ
892 return true;
893
894 /*Allow pinned connections only if the Proxy-support header exists in
895 reply and has in its list the "Session-Based-Authentication"
d67acb4e
AJ
896 which means that the peer supports connection pinning.
897 */
66d51f4f 898 if (rep.header.hasListMember(Http::HdrType::PROXY_SUPPORT, "Session-Based-Authentication", ','))
f891baff 899 return true;
d67acb4e 900
f891baff 901 return false;
d67acb4e
AJ
902}
903
5f8252d2 904// Called when we parsed (and possibly adapted) the headers but
905// had not starting storing (a.k.a., sending) the body yet.
2afaba07 906void
907HttpStateData::haveParsedReplyHeaders()
908{
fccd4a86 909 Client::haveParsedReplyHeaders();
c1520b67 910
c877c0bc 911 Ctx ctx = ctx_enter(entry->mem_obj->urlXXX());
585ab260 912 HttpReply *rep = finalReply();
39fe14b2 913 const Http::StatusCode statusCode = rep->sline.status();
2afaba07 914
3900307b 915 entry->timestampsSet();
62e76326 916
9bc73deb 917 /* Check if object is cacheable or not based on reply code */
39fe14b2 918 debugs(11, 3, "HTTP CODE: " << statusCode);
62e76326 919
4310f8b0
EB
920 if (StoreEntry *oldEntry = findPreviouslyCachedEntry(entry)) {
921 oldEntry->lock("HttpStateData::haveParsedReplyHeaders");
66d51f4f 922 sawDateGoBack = rep->olderThan(oldEntry->hasFreshestReply());
4310f8b0
EB
923 oldEntry->unlock("HttpStateData::haveParsedReplyHeaders");
924 }
eace013e
EB
925
926 if (neighbors_do_private_keys && !sawDateGoBack)
9b769c67 927 httpMaybeRemovePublic(entry, rep->sline.status());
e6ccf245 928
7c476309 929 bool varyFailure = false;
789217a2 930 if (rep->header.has(Http::HdrType::VARY)
f66a9ef4 931#if X_ACCELERATOR_VARY
789217a2 932 || rep->header.has(Http::HdrType::HDR_X_ACCELERATOR_VARY)
f66a9ef4 933#endif
4b44c907 934 ) {
d603e3c2 935 const SBuf vary(httpMakeVaryMark(request.getRaw(), rep));
4b44c907 936
90ab8f20 937 if (vary.isEmpty()) {
39fe14b2
EB
938 // TODO: check whether such responses are shareable.
939 // Do not share for now.
940 entry->makePrivate(false);
70eb3fde
EB
941 if (fwd->reforwardableStatus(rep->sline.status()))
942 EBIT_SET(entry->flags, ENTRY_FWD_HDR_WAIT);
7c476309
AJ
943 varyFailure = true;
944 } else {
90ab8f20 945 entry->mem_obj->vary_headers = vary;
ee2e0b31
AJ
946
947 // RFC 7231 section 7.1.4
948 // Vary:* can be cached, but has mandatory revalidation
949 static const SBuf asterisk("*");
950 if (vary == asterisk)
951 EBIT_SET(entry->flags, ENTRY_REVALIDATE_ALWAYS);
62e76326 952 }
4b44c907 953 }
954
7c476309
AJ
955 if (!varyFailure) {
956 /*
957 * If its not a reply that we will re-forward, then
958 * allow the client to get it.
959 */
70eb3fde
EB
960 if (fwd->reforwardableStatus(rep->sline.status()))
961 EBIT_SET(entry->flags, ENTRY_FWD_HDR_WAIT);
2afaba07 962
39fe14b2 963 ReuseDecision decision(entry, statusCode);
4b44c907 964
39fe14b2
EB
965 switch (reusableReply(decision)) {
966
967 case ReuseDecision::reuseNot:
968 entry->makePrivate(false);
7c476309 969 break;
62e76326 970
39fe14b2 971 case ReuseDecision::cachePositively:
4310f8b0
EB
972 if (!entry->makePublic()) {
973 decision.make(ReuseDecision::doNotCacheButShare, "public key creation error");
974 entry->makePrivate(true);
975 }
7c476309 976 break;
62e76326 977
39fe14b2 978 case ReuseDecision::cacheNegatively:
4310f8b0
EB
979 if (!entry->cacheNegatively()) {
980 decision.make(ReuseDecision::doNotCacheButShare, "public key creation error");
981 entry->makePrivate(true);
982 }
39fe14b2 983 break;
4b44c907 984
39fe14b2
EB
985 case ReuseDecision::doNotCacheButShare:
986 entry->makePrivate(true);
7c476309 987 break;
4b44c907 988
7c476309
AJ
989 default:
990 assert(0);
991 break;
992 }
39fe14b2 993 debugs(11, 3, "decided: " << decision);
9bc73deb 994 }
62e76326 995
2b59002c
AJ
996 if (!ignoreCacheControl) {
997 if (rep->cache_control) {
1259f9cf
AJ
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
810d879f 1002 const bool ccMustRevalidate = (rep->cache_control->hasProxyRevalidate() || rep->cache_control->hasMustRevalidate());
1259f9cf
AJ
1003
1004 // CC:no-cache (only if there are no parameters)
810d879f 1005 const bool ccNoCacheNoParams = rep->cache_control->hasNoCacheWithoutParameters();
1259f9cf
AJ
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
fa83b766
EB
1013 if (ccNoCacheNoParams || ccPrivate)
1014 EBIT_SET(entry->flags, ENTRY_REVALIDATE_ALWAYS);
1015 else if (ccMustRevalidate || ccSMaxAge)
1016 EBIT_SET(entry->flags, ENTRY_REVALIDATE_STALE);
2b59002c
AJ
1017 }
1018#if USE_HTTP_VIOLATIONS // response header Pragma::no-cache is undefined in HTTP
1019 else {
1020 // Expensive calculation. So only do it IF the CC: header is not present.
1021
1022 /* HACK: Pragma: no-cache in _replies_ is not documented in HTTP,
1023 * but servers like "Active Imaging Webcast/2.0" sure do use it */
789217a2
FC
1024 if (rep->header.has(Http::HdrType::PRAGMA) &&
1025 rep->header.hasListMember(Http::HdrType::PRAGMA,"no-cache",','))
fa83b766 1026 EBIT_SET(entry->flags, ENTRY_REVALIDATE_ALWAYS);
2b59002c
AJ
1027 }
1028#endif
9bc73deb 1029 }
62e76326 1030
c3609322 1031#if HEADERS_LOG
585ab260 1032 headersLog(1, 0, request->method, rep);
fc68f6b1 1033
c3609322 1034#endif
5f8252d2 1035
1036 ctx_exit(ctx);
f5558c95 1037}
1038
528b2c61 1039HttpStateData::ConnectionStatus
1040HttpStateData::statusIfComplete() const
603a02fd 1041{
585ab260 1042 const HttpReply *rep = virginReply();
073ba374
AJ
1043 /** \par
1044 * If the reply wants to close the connection, it takes precedence */
62e76326 1045
d5f18517
AJ
1046 static SBuf close("close", 5);
1047 if (httpHeaderHasConnDir(&rep->header, close))
62e76326 1048 return COMPLETE_NONPERSISTENT_MSG;
1049
073ba374
AJ
1050 /** \par
1051 * If we didn't send a keep-alive request header, then this
978e455f 1052 * can not be a persistent connection.
1053 */
528b2c61 1054 if (!flags.keepalive)
62e76326 1055 return COMPLETE_NONPERSISTENT_MSG;
1056
073ba374 1057 /** \par
72b63f06 1058 * If we haven't sent the whole request then this can not be a persistent
1059 * connection.
1060 */
1061 if (!flags.request_sent) {
7f06a3d8 1062 debugs(11, 2, "Request not yet fully sent " << request->method << ' ' << entry->url());
72b63f06 1063 return COMPLETE_NONPERSISTENT_MSG;
1064 }
1065
073ba374 1066 /** \par
9f5a2895 1067 * What does the reply have to say about keep-alive?
1068 */
073ba374
AJ
1069 /**
1070 \bug XXX BUG?
b6a2f15e 1071 * If the origin server (HTTP/1.0) does not send a keep-alive
1072 * header, but keeps the connection open anyway, what happens?
1073 * We'll return here and http.c waits for an EOF before changing
1074 * store_status to STORE_OK. Combine this with ENTRY_FWD_HDR_WAIT
1075 * and an error status code, and we might have to wait until
1076 * the server times out the socket.
1077 */
2afaba07 1078 if (!rep->keep_alive)
528b2c61 1079 return COMPLETE_NONPERSISTENT_MSG;
62e76326 1080
528b2c61 1081 return COMPLETE_PERSISTENT_MSG;
1082}
1083
1084HttpStateData::ConnectionStatus
1085HttpStateData::persistentConnStatus() const
1086{
9cf7de1b 1087 debugs(11, 3, HERE << serverConnection << " eof=" << eof);
839291ac
AJ
1088 if (eof) // already reached EOF
1089 return COMPLETE_NONPERSISTENT_MSG;
1090
505c2f28
AR
1091 /* If server fd is closing (but we have not been notified yet), stop Comm
1092 I/O to avoid assertions. TODO: Change Comm API to handle callers that
1093 want more I/O after async closing (usually initiated by others). */
1094 // XXX: add canReceive or s/canSend/canTalkToServer/
e7cea0ed 1095 if (!Comm::IsConnOpen(serverConnection))
505c2f28
AR
1096 return COMPLETE_NONPERSISTENT_MSG;
1097
9035d1d5
AJ
1098 /** \par
1099 * In chunked response we do not know the content length but we are absolutely
af0bb8e5 1100 * sure about the end of response, so we are calling the statusIfComplete to
9e008dda 1101 * decide if we can be persistant
af0bb8e5 1102 */
839291ac 1103 if (lastChunk && flags.chunked)
9e008dda 1104 return statusIfComplete();
af0bb8e5 1105
718d84bf
AR
1106 const HttpReply *vrep = virginReply();
1107 debugs(11, 5, "persistentConnStatus: content_length=" << vrep->content_length);
1108
47f6e231 1109 const int64_t clen = vrep->bodySize(request->method);
fc68f6b1 1110
bf8fe701 1111 debugs(11, 5, "persistentConnStatus: clen=" << clen);
2afaba07 1112
35282fbf 1113 /* If the body size is unknown we must wait for EOF */
1114 if (clen < 0)
62e76326 1115 return INCOMPLETE_MSG;
1116
9035d1d5
AJ
1117 /** \par
1118 * If the body size is known, we must wait until we've gotten all of it. */
5f8252d2 1119 if (clen > 0) {
8e100780 1120 debugs(11,5, "payloadSeen=" << payloadSeen << " content_length=" << vrep->content_length);
2afaba07 1121
8e100780 1122 if (payloadSeen < vrep->content_length)
5f8252d2 1123 return INCOMPLETE_MSG;
821beb5e 1124
8e100780 1125 if (payloadTruncated > 0) // already read more than needed
821beb5e 1126 return COMPLETE_NONPERSISTENT_MSG; // disable pconns
5f8252d2 1127 }
62e76326 1128
9035d1d5
AJ
1129 /** \par
1130 * If there is no message body or we got it all, we can be persistent */
5f8252d2 1131 return statusIfComplete();
603a02fd 1132}
090089c4 1133
d4a083cc
AJ
1134static void
1135readDelayed(void *context, CommRead const &)
1136{
1137 HttpStateData *state = static_cast<HttpStateData*>(context);
57912702 1138 state->flags.do_next_read = true;
d4a083cc
AJ
1139 state->maybeReadVirginBody();
1140}
d4a083cc 1141
c4b7a5a9 1142void
e6edd8df 1143HttpStateData::readReply(const CommIoCbParams &io)
090089c4 1144{
5867ac79 1145 Must(!flags.do_next_read); // XXX: should have been set false by mayReadVirginBody()
46f4b111 1146 flags.do_next_read = false;
9e008dda 1147
395a814a 1148 debugs(11, 5, io.conn);
62e76326 1149
c8407295
AJ
1150 // Bail out early on Comm::ERR_CLOSING - close handlers will tidy up for us
1151 if (io.flag == Comm::ERR_CLOSING) {
bf8fe701 1152 debugs(11, 3, "http socket closing");
c4b7a5a9 1153 return;
1154 }
1155
e92e4e44 1156 if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
6dd9a2e4 1157 abortTransaction("store entry aborted while reading reply");
62e76326 1158 return;
e92e4e44 1159 }
c4b7a5a9 1160
5867ac79
AJ
1161 Must(Comm::IsConnOpen(serverConnection));
1162 Must(io.conn->fd == serverConnection->fd);
fdf55365 1163
395a814a
AJ
1164 /*
1165 * Don't reset the timeout value here. The value should be
1166 * counting Config.Timeout.request and applies to the request
1167 * as a whole, not individual read() calls.
1168 * Plus, it breaks our lame *HalfClosed() detection
1169 */
1170
1ad68518 1171 Must(maybeMakeSpaceAvailable(true));
395a814a
AJ
1172 CommIoCbParams rd(this); // will be expanded with ReadNow results
1173 rd.conn = io.conn;
1174 rd.size = entry->bytesWanted(Range<size_t>(0, inBuf.spaceSize()));
395a814a 1175
f1ba1fba
EB
1176 if (rd.size <= 0) {
1177 assert(entry->mem_obj);
d4a083cc 1178 AsyncCall::Pointer nilCall;
f1ba1fba 1179 entry->mem_obj->delayRead(DeferredRead(readDelayed, this, CommRead(io.conn, NULL, 0, nilCall)));
fdf55365 1180 return;
1181 }
1182
395a814a
AJ
1183 switch (Comm::ReadNow(rd, inBuf)) {
1184 case Comm::INPROGRESS:
1185 if (inBuf.isEmpty())
1186 debugs(33, 2, io.conn << ": no data to process, " << xstrerr(rd.xerrno));
da958e50 1187 flags.do_next_read = true;
395a814a
AJ
1188 maybeReadVirginBody();
1189 return;
1190
1191 case Comm::OK:
1192 {
8e100780 1193 payloadSeen += rd.size;
9a0a18de 1194#if USE_DELAY_POOLS
2afaba07 1195 DelayId delayId = entry->mem_obj->mostBytesAllowed();
395a814a 1196 delayId.bytesIn(rd.size);
447e176b 1197#endif
62e76326 1198
a0864754
AJ
1199 statCounter.server.all.kbytes_in += rd.size;
1200 statCounter.server.http.kbytes_in += rd.size;
95dc7ff4 1201 ++ IOStats.Http.reads;
62e76326 1202
395a814a
AJ
1203 int bin = 0;
1204 for (int clen = rd.size - 1; clen; ++bin)
62e76326 1205 clen >>= 1;
1206
95dc7ff4 1207 ++ IOStats.Http.read_hist[bin];
3ff65596 1208
d8165775 1209 request->hier.notePeerRead();
30a4f2a8 1210 }
62e76326 1211
395a814a 1212 /* Continue to process previously read data */
1810a0cb 1213 break;
5fa061b8 1214
395a814a 1215 case Comm::ENDFILE: // close detected by 0-byte read
62e76326 1216 eof = 1;
46f4b111 1217 flags.do_next_read = false;
da6c8415 1218
395a814a
AJ
1219 /* Continue to process previously read data */
1220 break;
1221
1810a0cb 1222 // case Comm::COMM_ERROR:
395a814a
AJ
1223 default: // no other flags should ever occur
1224 debugs(11, 2, io.conn << ": read failure: " << xstrerr(rd.xerrno));
7e6eabbc 1225 const auto err = new ErrorState(ERR_READ_ERROR, Http::scBadGateway, fwd->request, fwd->al);
da958e50
CT
1226 err->xerrno = rd.xerrno;
1227 fwd->fail(err);
1228 flags.do_next_read = false;
398bc066
CT
1229 closeServer();
1230 mustStop("HttpStateData::readReply");
395a814a 1231 return;
ba82c452 1232 }
62e76326 1233
395a814a 1234 /* Process next response from buffer */
655daa06
AR
1235 processReply();
1236}
1237
1238/// processes the already read and buffered response data, possibly after
1239/// waiting for asynchronous 1xx control message processing
1240void
de48b288
A
1241HttpStateData::processReply()
1242{
655daa06
AR
1243
1244 if (flags.handling1xx) { // we came back after handling a 1xx response
1245 debugs(11, 5, HERE << "done with 1xx handling");
1246 flags.handling1xx = false;
1247 Must(!flags.headers_parsed);
1248 }
1249
ba82c452 1250 if (!flags.headers_parsed) { // have not parsed headers yet?
1251 PROF_start(HttpStateData_processReplyHeader);
1252 processReplyHeader();
1253 PROF_stop(HttpStateData_processReplyHeader);
1254
1255 if (!continueAfterParsingHeader()) // parsing error or need more data
1256 return; // TODO: send errors to ICAP
1257
ab593f19 1258 adaptOrFinalizeReply(); // may write to, abort, or "close" the entry
ba82c452 1259 }
1260
1261 // kick more reads if needed and/or process the response body, if any
1262 PROF_start(HttpStateData_processReplyBody);
1263 processReplyBody(); // may call serverComplete()
1264 PROF_stop(HttpStateData_processReplyBody);
1265}
1266
073ba374
AJ
1267/**
1268 \retval true if we can continue with processing the body or doing ICAP.
1269 */
ba82c452 1270bool
1271HttpStateData::continueAfterParsingHeader()
1272{
655daa06
AR
1273 if (flags.handling1xx) {
1274 debugs(11, 5, HERE << "wait for 1xx handling");
1275 Must(!flags.headers_parsed);
1276 return false;
1277 }
1278
073ba374 1279 if (!flags.headers_parsed && !eof) {
395a814a 1280 debugs(11, 9, "needs more at " << inBuf.length());
46f4b111 1281 flags.do_next_read = true;
073ba374
AJ
1282 /** \retval false If we have not finished parsing the headers and may get more data.
1283 * Schedules more reads to retrieve the missing data.
1284 */
ba82c452 1285 maybeReadVirginBody(); // schedules all kinds of reads; TODO: rename
073ba374 1286 return false;
ba82c452 1287 }
1288
073ba374 1289 /** If we are done with parsing, check for errors */
ba82c452 1290
1291 err_type error = ERR_NONE;
1292
1293 if (flags.headers_parsed) { // parsed headers, possibly with errors
1294 // check for header parsing errors
585ab260 1295 if (HttpReply *vrep = virginReply()) {
9b769c67 1296 const Http::StatusCode s = vrep->sline.status();
2592bc70 1297 const AnyP::ProtocolVersion &v = vrep->sline.version;
526ed14e 1298 if (s == Http::scInvalidHeader && v != Http::ProtocolVersion(0,9)) {
51b5dcf5 1299 debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: Bad header encountered from " << entry->url() << " AKA " << request->url);
ba82c452 1300 error = ERR_INVALID_RESP;
955394ce 1301 } else if (s == Http::scHeaderTooLarge) {
e1381638
AJ
1302 fwd->dontRetry(true);
1303 error = ERR_TOO_BIG;
3e42b356
AR
1304 } else if (vrep->header.conflictingContentLength()) {
1305 fwd->dontRetry(true);
1306 error = ERR_INVALID_RESP;
e1381638
AJ
1307 } else {
1308 return true; // done parsing, got reply, and no error
1309 }
ba82c452 1310 } else {
1311 // parsed headers but got no reply
51b5dcf5 1312 debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: No reply at all for " << entry->url() << " AKA " << request->url);
ba82c452 1313 error = ERR_INVALID_RESP;
62e76326 1314 }
090089c4 1315 } else {
ba82c452 1316 assert(eof);
395a814a 1317 if (inBuf.length()) {
9121eba6 1318 error = ERR_INVALID_RESP;
51b5dcf5 1319 debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: Headers did not parse at all for " << entry->url() << " AKA " << request->url);
9121eba6
AJ
1320 } else {
1321 error = ERR_ZERO_SIZE_OBJECT;
51b5dcf5 1322 debugs(11, (request->flags.accelerated?DBG_IMPORTANT:2), "WARNING: HTTP: Invalid Response: No object data received for " << entry->url() << " AKA " << request->url);
9121eba6 1323 }
2afaba07 1324 }
ba82c452 1325
1326 assert(error != ERR_NONE);
1327 entry->reset();
7e6eabbc 1328 fwd->fail(new ErrorState(error, Http::scBadGateway, fwd->request, fwd->al));
46f4b111 1329 flags.do_next_read = false;
398bc066
CT
1330 closeServer();
1331 mustStop("HttpStateData::continueAfterParsingHeader");
ba82c452 1332 return false; // quit on error
2afaba07 1333}
1334
821beb5e
AR
1335/** truncate what we read if we read too much so that writeReplyBody()
1336 writes no more than what we should have read */
1337void
1338HttpStateData::truncateVirginBody()
1339{
1340 assert(flags.headers_parsed);
1341
1342 HttpReply *vrep = virginReply();
1343 int64_t clen = -1;
1344 if (!vrep->expectingBody(request->method, clen) || clen < 0)
1345 return; // no body or a body of unknown size, including chunked
1346
8e100780 1347 if (payloadSeen - payloadTruncated <= clen)
821beb5e
AR
1348 return; // we did not read too much or already took care of the extras
1349
8e100780 1350 if (const int64_t extras = payloadSeen - payloadTruncated - clen) {
821beb5e 1351 // server sent more that the advertised content length
8e100780 1352 debugs(11, 5, "payloadSeen=" << payloadSeen <<
e1381638 1353 " clen=" << clen << '/' << vrep->content_length <<
8e100780 1354 " trucated=" << payloadTruncated << '+' << extras);
821beb5e 1355
395a814a 1356 inBuf.chop(0, inBuf.length() - extras);
8e100780 1357 payloadTruncated += extras;
821beb5e
AR
1358 }
1359}
1360
073ba374 1361/**
2afaba07 1362 * Call this when there is data from the origin server
1363 * which should be sent to either StoreEntry, or to ICAP...
1364 */
1365void
5f8252d2 1366HttpStateData::writeReplyBody()
2afaba07 1367{
821beb5e 1368 truncateVirginBody(); // if needed
395a814a
AJ
1369 const char *data = inBuf.rawContent();
1370 int len = inBuf.length();
bc81cb2b 1371 addVirginReplyBody(data, len);
395a814a 1372 inBuf.consume(len);
af0bb8e5 1373}
fc68f6b1 1374
af0bb8e5 1375bool
1376HttpStateData::decodeAndWriteReplyBody()
1377{
1378 const char *data = NULL;
1379 int len;
e053c141 1380 bool wasThereAnException = false;
af0bb8e5 1381 assert(flags.chunked);
1382 assert(httpChunkDecoder);
1383 SQUID_ENTER_THROWING_CODE();
1384 MemBuf decodedData;
1385 decodedData.init();
be29ee33
AJ
1386 httpChunkDecoder->setPayloadBuffer(&decodedData);
1387 const bool doneParsing = httpChunkDecoder->parse(inBuf);
1388 inBuf = httpChunkDecoder->remaining(); // sync buffers after parse
af0bb8e5 1389 len = decodedData.contentSize();
1390 data=decodedData.content();
1391 addVirginReplyBody(data, len);
e053c141 1392 if (doneParsing) {
839291ac 1393 lastChunk = 1;
46f4b111 1394 flags.do_next_read = false;
af0bb8e5 1395 }
e053c141
FC
1396 SQUID_EXIT_THROWING_CODE(wasThereAnException);
1397 return wasThereAnException;
e6ccf245 1398}
1399
073ba374 1400/**
2afaba07 1401 * processReplyBody has two purposes:
1402 * 1 - take the reply body data, if any, and put it into either
1403 * the StoreEntry, or give it over to ICAP.
1404 * 2 - see if we made it to the end of the response (persistent
1405 * connections and such)
1406 */
e6ccf245 1407void
2afaba07 1408HttpStateData::processReplyBody()
e6ccf245 1409{
1a98175f 1410 if (!flags.headers_parsed) {
46f4b111 1411 flags.do_next_read = true;
5f8252d2 1412 maybeReadVirginBody();
62e76326 1413 return;
528b2c61 1414 }
62e76326 1415
a83c6ed6 1416#if USE_ADAPTATION
c30ac6ea 1417 debugs(11,5, HERE << "adaptationAccessCheckPending=" << adaptationAccessCheckPending);
a83c6ed6 1418 if (adaptationAccessCheckPending)
2afaba07 1419 return;
fc68f6b1 1420
2afaba07 1421#endif
62e76326 1422
2afaba07 1423 /*
1424 * At this point the reply headers have been parsed and consumed.
1425 * That means header content has been removed from readBuf and
1426 * it contains only body data.
1427 */
ef85ab2f
DK
1428 if (entry->isAccepting()) {
1429 if (flags.chunked) {
1430 if (!decodeAndWriteReplyBody()) {
46f4b111 1431 flags.do_next_read = false;
ef85ab2f
DK
1432 serverComplete();
1433 return;
1434 }
1435 } else
1436 writeReplyBody();
1437 }
528b2c61 1438
abf396ec
AR
1439 // storing/sending methods like earlier adaptOrFinalizeReply() or
1440 // above writeReplyBody() may release/abort the store entry.
e6ccf245 1441 if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
abf396ec
AR
1442 // TODO: In some cases (e.g., 304), we should keep persistent conn open.
1443 // Detect end-of-reply (and, hence, pool our idle pconn) earlier (ASAP).
6dd9a2e4
AJ
1444 abortTransaction("store entry aborted while storing reply");
1445 return;
62e76326 1446 } else
1447 switch (persistentConnStatus()) {
dc49061a 1448 case INCOMPLETE_MSG: {
3e4bebf8 1449 debugs(11, 5, "processReplyBody: INCOMPLETE_MSG from " << serverConnection);
21b92762 1450 /* Wait for more data or EOF condition */
8d77a37c 1451 AsyncCall::Pointer nil;
21b92762 1452 if (flags.keepalive_broken) {
8d77a37c 1453 commSetConnTimeout(serverConnection, 10, nil);
21b92762 1454 } else {
8d77a37c 1455 commSetConnTimeout(serverConnection, Config.Timeout.read, nil);
21b92762 1456 }
1457
46f4b111 1458 flags.do_next_read = true;
dc49061a
A
1459 }
1460 break;
62e76326 1461
801cfc26 1462 case COMPLETE_PERSISTENT_MSG: {
3e4bebf8 1463 debugs(11, 5, "processReplyBody: COMPLETE_PERSISTENT_MSG from " << serverConnection);
801cfc26
CT
1464
1465 // TODO: Remove serverConnectionSaved but preserve exception safety.
1466
8d77a37c 1467 commUnsetConnTimeout(serverConnection);
46f4b111 1468 flags.do_next_read = false;
62e76326 1469
8d71285d 1470 comm_remove_close_handler(serverConnection->fd, closeHandler);
dc56a9b1 1471 closeHandler = NULL;
fc68f6b1 1472
801cfc26 1473 Ip::Address client_addr; // XXX: Remove as unused. Why was it added?
450fe1cb 1474 if (request->flags.spoofClientIp)
e24f13cd 1475 client_addr = request->client_addr;
fc68f6b1 1476
801cfc26
CT
1477 auto serverConnectionSaved = serverConnection;
1478 fwd->unregister(serverConnection);
1479 serverConnection = nullptr;
1480
1481 bool ispinned = false; // TODO: Rename to isOrShouldBePinned
45e5102d 1482 if (request->flags.pinned) {
9e008dda 1483 ispinned = true;
450fe1cb 1484 } else if (request->flags.connectionAuth && request->flags.authSent) {
9e008dda
AJ
1485 ispinned = true;
1486 }
1487
801cfc26
CT
1488 if (ispinned) {
1489 if (request->clientConnectionManager.valid()) {
1490 CallJobHere1(11, 4, request->clientConnectionManager,
1491 ConnStateData,
1492 notePinnedConnectionBecameIdle,
1493 ConnStateData::PinnedIdleContext(serverConnectionSaved, request));
1494 } else {
1495 // must not pool/share ispinned connections, even orphaned ones
1496 serverConnectionSaved->close();
1497 }
bd0723ad 1498 } else {
55622953 1499 fwdPconnPool->push(serverConnectionSaved, request->url.host());
bd0723ad 1500 }
1501
5f8252d2 1502 serverComplete();
62e76326 1503 return;
801cfc26 1504 }
62e76326 1505
1506 case COMPLETE_NONPERSISTENT_MSG:
3e4bebf8 1507 debugs(11, 5, "processReplyBody: COMPLETE_NONPERSISTENT_MSG from " << serverConnection);
6c36866e
D
1508 if (flags.chunked && !lastChunk)
1509 entry->lengthWentBad("missing last-chunk");
1510
5f8252d2 1511 serverComplete();
62e76326 1512 return;
1513 }
1514
5f8252d2 1515 maybeReadVirginBody();
c4b7a5a9 1516}
1517
aea65fec
AR
1518bool
1519HttpStateData::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
c4b7a5a9 1527void
5f8252d2 1528HttpStateData::maybeReadVirginBody()
c4b7a5a9 1529{
85bef0a7
AR
1530 // too late to read
1531 if (!Comm::IsConnOpen(serverConnection) || fd_table[serverConnection->fd].closing())
1532 return;
1533
1ad68518
AJ
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
1553bool
1554HttpStateData::maybeMakeSpaceAvailable(bool doGrow)
1555{
57912702
AJ
1556 // how much we are allowed to buffer
1557 const int limitBuffer = (flags.headers_parsed ? Config.readAheadGap : Config.maxReplyHeaderSize);
2afaba07 1558
57912702
AJ
1559 if (limitBuffer < 0 || inBuf.length() >= (SBuf::size_type)limitBuffer) {
1560 // when buffer is at or over limit already
61beade2 1561 debugs(11, 7, "will not read up to " << limitBuffer << ". buffer has (" << inBuf.length() << "/" << inBuf.spaceSize() << ") from " << serverConnection);
57912702
AJ
1562 debugs(11, DBG_DATA, "buffer has {" << inBuf << "}");
1563 // Process next response from buffer
1564 processReply();
1ad68518 1565 return false;
57912702
AJ
1566 }
1567
1568 // how much we want to read
5867ac79 1569 const size_t read_size = calcBufferSpaceToReserve(inBuf.spaceSize(), (limitBuffer - inBuf.length()));
57912702 1570
5867ac79 1571 if (!read_size) {
61beade2 1572 debugs(11, 7, "will not read up to " << read_size << " into buffer (" << inBuf.length() << "/" << inBuf.spaceSize() << ") from " << serverConnection);
1ad68518 1573 return false;
57912702
AJ
1574 }
1575
61beade2 1576 // just report whether we could grow or not, do not actually do it
1ad68518
AJ
1577 if (doGrow)
1578 return (read_size >= 2);
1579
57912702
AJ
1580 // we may need to grow the buffer
1581 inBuf.reserveSpace(read_size);
61beade2 1582 debugs(11, 8, (!flags.do_next_read ? "will not" : "may") <<
57912702
AJ
1583 " read up to " << read_size << " bytes info buf(" << inBuf.length() << "/" << inBuf.spaceSize() <<
1584 ") from " << serverConnection);
2afaba07 1585
1ad68518 1586 return (inBuf.spaceSize() >= 2); // only read if there is 1+ bytes of space available
090089c4 1587}
1588
39cb8c41 1589/// called after writing the very last request byte (body, last-chunk, etc)
d576a6a6 1590void
39cb8c41 1591HttpStateData::wroteLast(const CommIoCbParams &io)
090089c4 1592{
9cf7de1b 1593 debugs(11, 5, HERE << serverConnection << ": size " << io.size << ": errflag " << io.flag << ".");
bc87dc25 1594#if URL_CHECKSUM_DEBUG
62e76326 1595
528b2c61 1596 entry->mem_obj->checkUrlChecksum();
bc87dc25 1597#endif
62e76326 1598
d8165775
AR
1599 // XXX: Keep in sync with Client::sentRequestBody().
1600 // TODO: Extract common parts.
1601
dc56a9b1 1602 if (io.size > 0) {
49ae8b95 1603 fd_bytes(io.fd, io.size, FD_WRITE);
a0864754
AJ
1604 statCounter.server.all.kbytes_out += io.size;
1605 statCounter.server.http.kbytes_out += io.size;
ee1679df 1606 }
62e76326 1607
c8407295 1608 if (io.flag == Comm::ERR_CLOSING)
62e76326 1609 return;
1610
d8165775
AR
1611 // both successful and failed writes affect response times
1612 request->hier.notePeerWrite();
1613
dc56a9b1 1614 if (io.flag) {
7e6eabbc 1615 const auto err = new ErrorState(ERR_WRITE_ERROR, Http::scBadGateway, fwd->request, fwd->al);
dc56a9b1 1616 err->xerrno = io.xerrno;
1617 fwd->fail(err);
398bc066
CT
1618 closeServer();
1619 mustStop("HttpStateData::wroteLast");
62e76326 1620 return;
090089c4 1621 }
72b63f06 1622
39cb8c41
AR
1623 sendComplete();
1624}
1625
1626/// successfully wrote the entire request (including body, last-chunk, etc.)
1627void
1628HttpStateData::sendComplete()
1629{
2afaba07 1630 /*
1631 * Set the read timeout here because it hasn't been set yet.
1632 * We only set the read timeout after the request has been
d5430dc8 1633 * fully written to the peer. If we start the timeout
2afaba07 1634 * after connection establishment, then we are likely to hit
1635 * the timeout for POST/PUT requests that have very large
1636 * request bodies.
1637 */
dc56a9b1 1638 typedef CommCbMemFunT<HttpStateData, CommTimeoutCbParams> TimeoutDialer;
4299f876 1639 AsyncCall::Pointer timeoutCall = JobCallback(11, 5,
4cb2536f 1640 TimeoutDialer, this, HttpStateData::httpTimeout);
2afaba07 1641
8d77a37c 1642 commSetConnTimeout(serverConnection, Config.Timeout.read, timeoutCall);
46f4b111 1643 flags.request_sent = true;
090089c4 1644}
1645
2afaba07 1646void
5f8252d2 1647HttpStateData::closeServer()
2afaba07 1648{
9cf7de1b 1649 debugs(11,5, HERE << "closing HTTP server " << serverConnection << " this " << this);
fc68f6b1 1650
9cf7de1b 1651 if (Comm::IsConnOpen(serverConnection)) {
8d71285d
AJ
1652 fwd->unregister(serverConnection);
1653 comm_remove_close_handler(serverConnection->fd, closeHandler);
dc56a9b1 1654 closeHandler = NULL;
8d71285d 1655 serverConnection->close();
2afaba07 1656 }
5f8252d2 1657}
2afaba07 1658
5f8252d2 1659bool
1660HttpStateData::doneWithServer() const
1661{
9cf7de1b 1662 return !Comm::IsConnOpen(serverConnection);
2afaba07 1663}
1664
ee0b94f4
HN
1665/*
1666 * Fixup authentication request headers for special cases
1667 */
1668static void
bad9c5e4 1669httpFixupAuthentication(HttpRequest * request, const HttpHeader * hdr_in, HttpHeader * hdr_out, const Http::StateFlags &flags)
ee0b94f4 1670{
ee0b94f4 1671 /* Nothing to do unless we are forwarding to a peer */
f5e17947
CT
1672 if (!flags.peering)
1673 return;
1674
1675 // This request is going "through" rather than "to" our _peer.
1676 if (flags.tunneling)
f54f527e 1677 return;
ee0b94f4
HN
1678
1679 /* Needs to be explicitly enabled */
e24f13cd 1680 if (!request->peer_login)
f54f527e 1681 return;
ee0b94f4 1682
f5e17947 1683 const auto header = flags.toOrigin ? Http::HdrType::AUTHORIZATION : Http::HdrType::PROXY_AUTHORIZATION;
ee0b94f4
HN
1684 /* Maybe already dealt with? */
1685 if (hdr_out->has(header))
f54f527e 1686 return;
ee0b94f4
HN
1687
1688 /* Nothing to do here for PASSTHRU */
e24f13cd 1689 if (strcmp(request->peer_login, "PASSTHRU") == 0)
f54f527e 1690 return;
ee0b94f4 1691
f5e17947
CT
1692 // Dangerous and undocumented PROXYPASS is a single-signon to servers with
1693 // the proxy password. Only Basic Authentication can work this way. This
1694 // statement forwards a "basic" Proxy-Authorization value from our client
1695 // to an originserver peer. Other PROXYPASS cases are handled lower.
1696 if (flags.toOrigin &&
63ed43c5 1697 strcmp(request->peer_login, "PROXYPASS") == 0 &&
1698 hdr_in->has(Http::HdrType::PROXY_AUTHORIZATION)) {
f5e17947 1699
789217a2 1700 const char *auth = hdr_in->getStr(Http::HdrType::PROXY_AUTHORIZATION);
ee0b94f4 1701
f54f527e
AJ
1702 if (auth && strncasecmp(auth, "basic ", 6) == 0) {
1703 hdr_out->putStr(header, auth);
1704 return;
1705 }
ee0b94f4
HN
1706 }
1707
1d11e9b3 1708 char loginbuf[base64_encode_len(MAX_LOGIN_SZ)];
aadbbd7d
AJ
1709 size_t blen;
1710 struct base64_encode_ctx ctx;
1711 base64_encode_init(&ctx);
1712
ee0b94f4 1713 /* Special mode to pass the username to the upstream cache */
e24f13cd 1714 if (*request->peer_login == '*') {
f54f527e 1715 const char *username = "-";
ee0b94f4 1716
e24f13cd
CT
1717 if (request->extacl_user.size())
1718 username = request->extacl_user.termedBuf();
2f1431ea 1719#if USE_AUTH
e24f13cd
CT
1720 else if (request->auth_user_request != NULL)
1721 username = request->auth_user_request->username();
2f1431ea 1722#endif
ee0b94f4 1723
aadbbd7d
AJ
1724 blen = base64_encode_update(&ctx, loginbuf, strlen(username), reinterpret_cast<const uint8_t*>(username));
1725 blen += base64_encode_update(&ctx, loginbuf+blen, strlen(request->peer_login +1), reinterpret_cast<const uint8_t*>(request->peer_login +1));
1726 blen += base64_encode_final(&ctx, loginbuf+blen);
bb64d879 1727 httpHeaderPutStrf(hdr_out, header, "Basic %.*s", (int)blen, loginbuf);
f54f527e 1728 return;
ee0b94f4
HN
1729 }
1730
1731 /* external_acl provided credentials */
e24f13cd
CT
1732 if (request->extacl_user.size() && request->extacl_passwd.size() &&
1733 (strcmp(request->peer_login, "PASS") == 0 ||
1734 strcmp(request->peer_login, "PROXYPASS") == 0)) {
aadbbd7d
AJ
1735
1736 blen = base64_encode_update(&ctx, loginbuf, request->extacl_user.size(), reinterpret_cast<const uint8_t*>(request->extacl_user.rawBuf()));
1737 blen += base64_encode_update(&ctx, loginbuf+blen, 1, reinterpret_cast<const uint8_t*>(":"));
1738 blen += base64_encode_update(&ctx, loginbuf+blen, request->extacl_passwd.size(), reinterpret_cast<const uint8_t*>(request->extacl_passwd.rawBuf()));
1739 blen += base64_encode_final(&ctx, loginbuf+blen);
bb64d879 1740 httpHeaderPutStrf(hdr_out, header, "Basic %.*s", (int)blen, loginbuf);
f54f527e 1741 return;
ee0b94f4 1742 }
8fdaa8af
AJ
1743 // if no external user credentials are available to fake authentication with PASS acts like PASSTHRU
1744 if (strcmp(request->peer_login, "PASS") == 0)
28204b3b 1745 return;
ee0b94f4 1746
9ca29d23 1747 /* Kerberos login to peer */
2f1431ea 1748#if HAVE_AUTH_MODULE_NEGOTIATE && HAVE_KRB5 && HAVE_GSSAPI
e24f13cd 1749 if (strncmp(request->peer_login, "NEGOTIATE",strlen("NEGOTIATE")) == 0) {
9ca29d23
AJ
1750 char *Token=NULL;
1751 char *PrincipalName=NULL,*p;
9825b398
AJ
1752 int negotiate_flags = 0;
1753
e24f13cd 1754 if ((p=strchr(request->peer_login,':')) != NULL ) {
9ca29d23
AJ
1755 PrincipalName=++p;
1756 }
9825b398
AJ
1757 if (request->flags.auth_no_keytab) {
1758 negotiate_flags |= PEER_PROXY_NEGOTIATE_NOKEYTAB;
1759 }
1760 Token = peer_proxy_negotiate_auth(PrincipalName, request->peer_host, negotiate_flags);
9ca29d23 1761 if (Token) {
63f03f79 1762 httpHeaderPutStrf(hdr_out, header, "Negotiate %s",Token);
9ca29d23
AJ
1763 }
1764 return;
1765 }
1766#endif /* HAVE_KRB5 && HAVE_GSSAPI */
1767
aadbbd7d
AJ
1768 blen = base64_encode_update(&ctx, loginbuf, strlen(request->peer_login), reinterpret_cast<const uint8_t*>(request->peer_login));
1769 blen += base64_encode_final(&ctx, loginbuf+blen);
bb64d879 1770 httpHeaderPutStrf(hdr_out, header, "Basic %.*s", (int)blen, loginbuf);
ee0b94f4
HN
1771 return;
1772}
1773
99edd1c3 1774/*
9e008dda 1775 * build request headers and append them to a given MemBuf
e5ee81f0 1776 * used by buildRequestPrefix()
818c6c9e 1777 * note: initialised the HttpHeader, the caller is responsible for Clean()-ing
99edd1c3 1778 */
e1e72f06 1779void
e5ee81f0 1780HttpStateData::httpBuildRequestHeader(HttpRequest * request,
e5ee81f0 1781 StoreEntry * entry,
4bf68cfa 1782 const AccessLogEntryPointer &al,
e5ee81f0 1783 HttpHeader * hdr_out,
bad9c5e4 1784 const Http::StateFlags &flags)
6bf8443a 1785{
99edd1c3 1786 /* building buffer for complex strings */
5999b776 1787#define BBUF_SZ (MAX_URL+32)
99edd1c3 1788 LOCAL_ARRAY(char, bbuf, BBUF_SZ);
67c06f0d 1789 LOCAL_ARRAY(char, ntoabuf, MAX_IPSTRLEN);
e24f13cd 1790 const HttpHeader *hdr_in = &request->header;
67c06f0d 1791 const HttpHeaderEntry *e = NULL;
99edd1c3 1792 HttpHeaderPos pos = HttpHeaderInitPos;
75faaa7a 1793 assert (hdr_out->owner == hoRequest);
62e76326 1794
46017fdd 1795 /* use our IMS header if the cached entry has Last-Modified time */
fa3e249f 1796 if (request->lastmod > -1)
789217a2 1797 hdr_out->putTime(Http::HdrType::IF_MODIFIED_SINCE, request->lastmod);
99edd1c3 1798
46017fdd
CT
1799 // Add our own If-None-Match field if the cached entry has a strong ETag.
1800 // copyOneHeaderFromClientsideRequestToUpstreamRequest() adds client ones.
b38b26cb 1801 if (request->etag.size() > 0) {
d5f18517 1802 hdr_out->addEntry(new HttpHeaderEntry(Http::HdrType::IF_NONE_MATCH, SBuf(),
7f754be8 1803 request->etag.termedBuf()));
46017fdd
CT
1804 }
1805
e24f13cd 1806 bool we_do_ranges = decideIfWeDoRanges (request);
528b2c61 1807
789217a2 1808 String strConnection (hdr_in->getList(Http::HdrType::CONNECTION));
62e76326 1809
a9925b40 1810 while ((e = hdr_in->getEntry(&pos)))
e24f13cd 1811 copyOneHeaderFromClientsideRequestToUpstreamRequest(e, strConnection, request, hdr_out, we_do_ranges, flags);
528b2c61 1812
43ae1d95 1813 /* Abstraction break: We should interpret multipart/byterange responses
528b2c61 1814 * into offset-length data, and this works around our inability to do so.
1815 */
e24f13cd 1816 if (!we_do_ranges && request->multipartRangeRequest()) {
62e76326 1817 /* don't cache the result */
e857372a 1818 request->flags.cachable = false;
62e76326 1819 /* pretend it's not a range request */
f0baf149 1820 request->ignoreRange("want to request the whole object");
e857372a 1821 request->flags.isRanged = false;
62e76326 1822 }
528b2c61 1823
90be6ff5 1824 hdr_out->addVia(request->http_ver, hdr_in);
62e76326 1825
45e5102d 1826 if (request->flags.accelerated) {
43ae1d95 1827 /* Append Surrogate-Capabilities */
789217a2 1828 String strSurrogate(hdr_in->getList(Http::HdrType::SURROGATE_CAPABILITY));
45cca89d
AJ
1829#if USE_SQUID_ESI
1830 snprintf(bbuf, BBUF_SZ, "%s=\"Surrogate/1.0 ESI/1.0\"", Config.Accel.surrogate_id);
1831#else
1832 snprintf(bbuf, BBUF_SZ, "%s=\"Surrogate/1.0\"", Config.Accel.surrogate_id);
1833#endif
43ae1d95 1834 strListAdd(&strSurrogate, bbuf, ',');
789217a2 1835 hdr_out->putStr(Http::HdrType::SURROGATE_CAPABILITY, strSurrogate.termedBuf());
43ae1d95 1836 }
43ae1d95 1837
67c06f0d 1838 /** \pre Handle X-Forwarded-For */
9e008dda 1839 if (strcmp(opt_forwarded_for, "delete") != 0) {
c4f30223 1840
789217a2 1841 String strFwd = hdr_in->getList(Http::HdrType::X_FORWARDED_FOR);
c4f30223 1842
70df76e3
AR
1843 // if we cannot double strFwd size, then it grew past 50% of the limit
1844 if (!strFwd.canGrowBy(strFwd.size())) {
c4f30223
AR
1845 // There is probably a forwarding loop with Via detection disabled.
1846 // If we do nothing, String will assert on overflow soon.
1847 // TODO: Terminate all transactions with huge XFF?
1848 strFwd = "error";
1849
1850 static int warnedCount = 0;
1851 if (warnedCount++ < 100) {
851feda6 1852 const SBuf url(entry ? SBuf(entry->url()) : request->effectiveRequestUri());
e0236918 1853 debugs(11, DBG_IMPORTANT, "Warning: likely forwarding loop with " << url);
c4f30223
AR
1854 }
1855 }
1856
9e008dda 1857 if (strcmp(opt_forwarded_for, "on") == 0) {
67c06f0d 1858 /** If set to ON - append client IP or 'unknown'. */
4dd643d5 1859 if ( request->client_addr.isNoAddr() )
67c06f0d
AJ
1860 strListAdd(&strFwd, "unknown", ',');
1861 else
4dd643d5 1862 strListAdd(&strFwd, request->client_addr.toStr(ntoabuf, MAX_IPSTRLEN), ',');
9e008dda 1863 } else if (strcmp(opt_forwarded_for, "off") == 0) {
67c06f0d 1864 /** If set to OFF - append 'unknown'. */
67c06f0d 1865 strListAdd(&strFwd, "unknown", ',');
9e008dda 1866 } else if (strcmp(opt_forwarded_for, "transparent") == 0) {
67c06f0d 1867 /** If set to TRANSPARENT - pass through unchanged. */
9e008dda 1868 } else if (strcmp(opt_forwarded_for, "truncate") == 0) {
67c06f0d 1869 /** If set to TRUNCATE - drop existing list and replace with client IP or 'unknown'. */
4dd643d5 1870 if ( request->client_addr.isNoAddr() )
67c06f0d
AJ
1871 strFwd = "unknown";
1872 else
4dd643d5 1873 strFwd = request->client_addr.toStr(ntoabuf, MAX_IPSTRLEN);
67c06f0d 1874 }
9e008dda 1875 if (strFwd.size() > 0)
789217a2 1876 hdr_out->putStr(Http::HdrType::X_FORWARDED_FOR, strFwd.termedBuf());
cc192b50 1877 }
67c06f0d 1878 /** If set to DELETE - do not copy through. */
6bccf575 1879
99edd1c3 1880 /* append Host if not there already */
789217a2 1881 if (!hdr_out->has(Http::HdrType::HOST)) {
e24f13cd 1882 if (request->peer_domain) {
789217a2 1883 hdr_out->putStr(Http::HdrType::HOST, request->peer_domain);
62e76326 1884 } else {
5c51bffb 1885 SBuf authority = request->url.authority();
789217a2 1886 hdr_out->putStr(Http::HdrType::HOST, authority.c_str());
62e76326 1887 }
6bf8443a 1888 }
62e76326 1889
c68e9c6b 1890 /* append Authorization if known in URL, not in header and going direct */
789217a2 1891 if (!hdr_out->has(Http::HdrType::AUTHORIZATION)) {
f5e17947 1892 if (flags.toOrigin && !request->url.userInfo().isEmpty()) {
1d11e9b3 1893 static char result[base64_encode_len(MAX_URL*2)]; // should be big enough for a single URI segment
aadbbd7d
AJ
1894 struct base64_encode_ctx ctx;
1895 base64_encode_init(&ctx);
1896 size_t blen = base64_encode_update(&ctx, result, request->url.userInfo().length(), reinterpret_cast<const uint8_t*>(request->url.userInfo().rawContent()));
1897 blen += base64_encode_final(&ctx, result+blen);
1898 result[blen] = '\0';
1899 if (blen)
789217a2 1900 httpHeaderPutStrf(hdr_out, Http::HdrType::AUTHORIZATION, "Basic %.*s", (int)blen, result);
62e76326 1901 }
c68e9c6b 1902 }
62e76326 1903
ee0b94f4 1904 /* Fixup (Proxy-)Authorization special cases. Plain relaying dealt with above */
e24f13cd 1905 httpFixupAuthentication(request, hdr_in, hdr_out, flags);
62e76326 1906
ee0b94f4
HN
1907 /* append Cache-Control, add max-age if not there already */
1908 {
a9925b40 1909 HttpHdrCc *cc = hdr_in->getCc();
62e76326 1910
1911 if (!cc)
a4a03b37 1912 cc = new HttpHdrCc();
62e76326 1913
7dc5c309
AJ
1914#if 0 /* see bug 2330 */
1915 /* Set no-cache if determined needed but not found */
e24f13cd 1916 if (request->flags.nocache)
1da82544 1917 EBIT_SET(cc->mask, HttpHdrCcType::CC_NO_CACHE);
7dc5c309
AJ
1918#endif
1919
af6a12ee 1920 /* Add max-age only without no-cache */
1259f9cf 1921 if (!cc->hasMaxAge() && !cc->hasNoCache()) {
851feda6
AJ
1922 // XXX: performance regression. c_str() reallocates
1923 SBuf tmp(request->effectiveRequestUri());
1924 cc->maxAge(getMaxAge(entry ? entry->url() : tmp.c_str()));
62e76326 1925 }
1926
ce2d6441 1927 /* Enforce sibling relations */
62e76326 1928 if (flags.only_if_cached)
4ce6e3b5 1929 cc->onlyIfCached(true);
62e76326 1930
a9925b40 1931 hdr_out->putCc(cc);
62e76326 1932
3d7782c1 1933 delete cc;
6bf8443a 1934 }
62e76326 1935
2aaabae3
EB
1936 // Always send Connection because HTTP/1.0 servers need explicit "keep-alive"
1937 // while HTTP/1.1 servers need explicit "close", and we do not always know
1938 // the server expectations.
1939 hdr_out->putStr(Http::HdrType::CONNECTION, flags.keepalive ? "keep-alive" : "close");
62e76326 1940
a7ad6e4e 1941 /* append Front-End-Https */
1942 if (flags.front_end_https) {
4e3f4dc7 1943 if (flags.front_end_https == 1 || request->url.getScheme() == AnyP::PROTO_HTTPS)
789217a2 1944 hdr_out->putStr(Http::HdrType::FRONT_END_HTTPS, "On");
a7ad6e4e 1945 }
1946
e31a1e67
AR
1947 if (flags.chunked_request) {
1948 // Do not just copy the original value so that if the client-side
1949 // starts decode other encodings, this code may remain valid.
789217a2 1950 hdr_out->putStr(Http::HdrType::TRANSFER_ENCODING, "chunked");
39cb8c41
AR
1951 }
1952
6bccf575 1953 /* Now mangle the headers. */
cde8f31b 1954 httpHdrMangleList(hdr_out, request, al, ROR_REQUEST);
f4698e0b 1955
30abd221 1956 strConnection.clean();
99edd1c3 1957}
1958
9e498bfb
AJ
1959/**
1960 * Decides whether a particular header may be cloned from the received Clients request
1961 * to our outgoing fetch request.
1962 */
528b2c61 1963void
bad9c5e4 1964copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, const String strConnection, const HttpRequest * request, HttpHeader * hdr_out, const int we_do_ranges, const Http::StateFlags &flags)
528b2c61 1965{
e8466ea9 1966 debugs(11, 5, "httpBuildRequestHeader: " << e->name << ": " << e->value );
62e76326 1967
528b2c61 1968 switch (e->id) {
62e76326 1969
f53969cc 1970 /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid should not pass on. */
9e498bfb 1971
789217a2 1972 case Http::HdrType::PROXY_AUTHORIZATION:
9e498bfb
AJ
1973 /** \par Proxy-Authorization:
1974 * Only pass on proxy authentication to peers for which
62e76326 1975 * authentication forwarding is explicitly enabled
1976 */
f5e17947 1977 if (!flags.toOrigin && request->peer_login &&
e24f13cd
CT
1978 (strcmp(request->peer_login, "PASS") == 0 ||
1979 strcmp(request->peer_login, "PROXYPASS") == 0 ||
1980 strcmp(request->peer_login, "PASSTHRU") == 0)) {
eede25e7 1981 hdr_out->addEntry(e->clone());
62e76326 1982 }
62e76326 1983 break;
1984
f53969cc 1985 /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid does not pass on. */
9e498bfb 1986
789217a2
FC
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: */
9e498bfb
AJ
1994 break;
1995
f53969cc 1996 /** \par OTHER headers I haven't bothered to track down yet. */
9e498bfb 1997
789217a2 1998 case Http::HdrType::AUTHORIZATION:
9e498bfb
AJ
1999 /** \par WWW-Authorization:
2000 * Pass on WWW authentication */
62e76326 2001
f5e17947 2002 if (!flags.toOriginPeer()) {
eede25e7 2003 hdr_out->addEntry(e->clone());
62e76326 2004 } else {
f5e17947
CT
2005 /** \note Assume that talking to a cache_peer originserver makes
2006 * us a reverse proxy and only forward authentication if enabled
ee0b94f4 2007 * (see also httpFixupAuthentication for special cases)
62e76326 2008 */
e24f13cd
CT
2009 if (request->peer_login &&
2010 (strcmp(request->peer_login, "PASS") == 0 ||
2011 strcmp(request->peer_login, "PASSTHRU") == 0 ||
2012 strcmp(request->peer_login, "PROXYPASS") == 0)) {
eede25e7 2013 hdr_out->addEntry(e->clone());
62e76326 2014 }
2015 }
2016
2017 break;
2018
789217a2 2019 case Http::HdrType::HOST:
9e498bfb 2020 /** \par Host:
b883b594 2021 * Normally Squid rewrites the Host: header.
2022 * However, there is one case when we don't: If the URL
62e76326 2023 * went through our redirector and the admin configured
2024 * 'redir_rewrites_host' to be off.
2025 */
e24f13cd 2026 if (request->peer_domain)
789217a2 2027 hdr_out->putStr(Http::HdrType::HOST, request->peer_domain);
45e5102d 2028 else if (request->flags.redirected && !Config.onoff.redir_rewrites_host)
eede25e7 2029 hdr_out->addEntry(e->clone());
b883b594 2030 else {
5c51bffb 2031 SBuf authority = request->url.authority();
789217a2 2032 hdr_out->putStr(Http::HdrType::HOST, authority.c_str());
b883b594 2033 }
62e76326 2034
2035 break;
2036
789217a2 2037 case Http::HdrType::IF_MODIFIED_SINCE:
9e498bfb 2038 /** \par If-Modified-Since:
96598f93
AJ
2039 * append unless we added our own,
2040 * but only if cache_miss_revalidate is enabled, or
2041 * the request is not cacheable, or
2042 * the request contains authentication credentials.
2043 * \note at most one client's If-Modified-Since header can pass through
2044 */
2045 // XXX: need to check and cleanup the auth case so cacheable auth requests get cached.
789217a2 2046 if (hdr_out->has(Http::HdrType::IF_MODIFIED_SINCE))
96598f93
AJ
2047 break;
2048 else if (Config.onoff.cache_miss_revalidate || !request->flags.cachable || request->flags.auth)
eede25e7 2049 hdr_out->addEntry(e->clone());
96598f93 2050 break;
62e76326 2051
789217a2 2052 case Http::HdrType::IF_NONE_MATCH:
96598f93
AJ
2053 /** \par If-None-Match:
2054 * append if the wildcard '*' special case value is present, or
2055 * cache_miss_revalidate is disabled, or
2056 * the request is not cacheable in this proxy, or
2057 * the request contains authentication credentials.
2058 * \note this header lists a set of responses for the server to elide sending. Squid added values are extending that set.
2059 */
2060 // XXX: need to check and cleanup the auth case so cacheable auth requests get cached.
789217a2 2061 if (hdr_out->hasListMember(Http::HdrType::IF_MATCH, "*", ',') || Config.onoff.cache_miss_revalidate || !request->flags.cachable || request->flags.auth)
eede25e7 2062 hdr_out->addEntry(e->clone());
62e76326 2063 break;
2064
789217a2 2065 case Http::HdrType::MAX_FORWARDS:
9e498bfb 2066 /** \par Max-Forwards:
fc90edc3 2067 * pass only on TRACE or OPTIONS requests */
c2a7cefd 2068 if (request->method == Http::METHOD_TRACE || request->method == Http::METHOD_OPTIONS) {
fc90edc3 2069 const int64_t hops = e->getInt64();
62e76326 2070
2071 if (hops > 0)
789217a2 2072 hdr_out->putInt64(Http::HdrType::MAX_FORWARDS, hops - 1);
62e76326 2073 }
2074
2075 break;
2076
789217a2 2077 case Http::HdrType::VIA:
9e498bfb
AJ
2078 /** \par Via:
2079 * If Via is disabled then forward any received header as-is.
2080 * Otherwise leave for explicit updated addition later. */
62e76326 2081
2082 if (!Config.onoff.via)
eede25e7 2083 hdr_out->addEntry(e->clone());
62e76326 2084
2085 break;
2086
789217a2 2087 case Http::HdrType::RANGE:
62e76326 2088
789217a2 2089 case Http::HdrType::IF_RANGE:
62e76326 2090
789217a2 2091 case Http::HdrType::REQUEST_RANGE:
9e498bfb
AJ
2092 /** \par Range:, If-Range:, Request-Range:
2093 * Only pass if we accept ranges */
62e76326 2094 if (!we_do_ranges)
eede25e7 2095 hdr_out->addEntry(e->clone());
62e76326 2096
2097 break;
2098
789217a2 2099 case Http::HdrType::PROXY_CONNECTION: // SHOULD ignore. But doing so breaks things.
95e78500 2100 break;
62e76326 2101
789217a2 2102 case Http::HdrType::CONTENT_LENGTH:
f228d6f6
AR
2103 // pass through unless we chunk; also, keeping this away from default
2104 // prevents request smuggling via Connection: Content-Length tricks
2105 if (!flags.chunked_request)
2106 hdr_out->addEntry(e->clone());
2107 break;
2108
789217a2 2109 case Http::HdrType::X_FORWARDED_FOR:
62e76326 2110
789217a2 2111 case Http::HdrType::CACHE_CONTROL:
95e78500 2112 /** \par X-Forwarded-For:, Cache-Control:
9e498bfb
AJ
2113 * handled specially by Squid, so leave off for now.
2114 * append these after the loop if needed */
62e76326 2115 break;
2116
789217a2 2117 case Http::HdrType::FRONT_END_HTTPS:
9e498bfb
AJ
2118 /** \par Front-End-Https:
2119 * Pass thru only if peer is configured with front-end-https */
62e76326 2120 if (!flags.front_end_https)
eede25e7 2121 hdr_out->addEntry(e->clone());
62e76326 2122
2123 break;
2124
be753325 2125 default:
9e498bfb
AJ
2126 /** \par default.
2127 * pass on all other header fields
2128 * which are NOT listed by the special Connection: header. */
d5f18517 2129 if (strConnection.size()>0 && strListIsMember(&strConnection, e->name, ',')) {
e1ea7456 2130 debugs(11, 2, "'" << e->name << "' header cropped by Connection: definition");
9e498bfb
AJ
2131 return;
2132 }
2133
eede25e7 2134 hdr_out->addEntry(e->clone());
528b2c61 2135 }
2136}
2137
e5ee81f0 2138bool
e24f13cd 2139HttpStateData::decideIfWeDoRanges (HttpRequest * request)
528b2c61 2140{
e5ee81f0 2141 bool result = true;
62e76326 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
e24f13cd 2153 int64_t roffLimit = request->getRangeOffsetLimit();
11e3fa1c 2154
45e5102d 2155 if (NULL == request->range || !request->flags.cachable
450fe1cb 2156 || request->range->offsetLimitExceeded(roffLimit) || request->flags.connectionAuth)
e5ee81f0 2157 result = false;
62e76326 2158
9e008dda 2159 debugs(11, 8, "decideIfWeDoRanges: range specs: " <<
e24f13cd 2160 request->range << ", cachable: " <<
45e5102d 2161 request->flags.cachable << "; we_do_ranges: " << result);
62e76326 2162
2163 return result;
528b2c61 2164}
2165
62e76326 2166/* build request prefix and append it to a given MemBuf;
99edd1c3 2167 * return the length of the prefix */
9bc73deb 2168mb_size_t
e24f13cd 2169HttpStateData::buildRequestPrefix(MemBuf * mb)
99edd1c3 2170{
2171 const int offset = mb->size;
2592bc70 2172 /* Uses a local httpver variable to print the HTTP label
526ed14e
AJ
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 */
2592bc70 2178 const AnyP::ProtocolVersion httpver = Http::ProtocolVersion();
f5e17947 2179 const SBuf url(flags.toOrigin ? request->url.path() : request->effectiveRequestUri());
51b5dcf5 2180 mb->appendf(SQUIDSBUFPH " " SQUIDSBUFPH " %s/%d.%d\r\n",
4391cd15 2181 SQUIDSBUFPRINT(request->method.image()),
51b5dcf5 2182 SQUIDSBUFPRINT(url),
4391cd15
AJ
2183 AnyP::ProtocolType_str[httpver.protocol],
2184 httpver.major,httpver.minor);
99edd1c3 2185 /* build and pack headers */
2186 {
75faaa7a 2187 HttpHeader hdr(hoRequest);
d603e3c2 2188 httpBuildRequestHeader(request.getRaw(), entry, fwd->al, &hdr, flags);
9e008dda 2189
450fe1cb 2190 if (request->flags.pinned && request->flags.connectionAuth)
e857372a 2191 request->flags.authSent = true;
789217a2 2192 else if (hdr.has(Http::HdrType::AUTHORIZATION))
e857372a 2193 request->flags.authSent = true;
d67acb4e 2194
10201568 2195 hdr.packInto(mb);
519e0948 2196 hdr.clean();
9d9d144b 2197 }
99edd1c3 2198 /* append header terminator */
2fe7eff9 2199 mb->append(crlf, 2);
99edd1c3 2200 return mb->size - offset;
6bf8443a 2201}
62e76326 2202
090089c4 2203/* This will be called when connect completes. Write request. */
5f8252d2 2204bool
2bb867b5 2205HttpStateData::sendRequest()
090089c4 2206{
99edd1c3 2207 MemBuf mb;
090089c4 2208
9cf7de1b 2209 debugs(11, 5, HERE << serverConnection << ", request " << request << ", this " << this << ".");
a0297974 2210
6b679a01 2211 if (!Comm::IsConnOpen(serverConnection)) {
9cf7de1b 2212 debugs(11,3, HERE << "cannot send request to closing " << serverConnection);
a0297974
AR
2213 assert(closeHandler != NULL);
2214 return false;
2215 }
2216
dc56a9b1 2217 typedef CommCbMemFunT<HttpStateData, CommTimeoutCbParams> TimeoutDialer;
4299f876 2218 AsyncCall::Pointer timeoutCall = JobCallback(11, 5,
4cb2536f 2219 TimeoutDialer, this, HttpStateData::httpTimeout);
8d77a37c 2220 commSetConnTimeout(serverConnection, Config.Timeout.lifetime, timeoutCall);
46f4b111 2221 flags.do_next_read = true;
5f8252d2 2222 maybeReadVirginBody();
2223
e24f13cd 2224 if (request->body_pipe != NULL) {
123ec4de 2225 if (!startRequestBodyFlow()) // register to receive body data
5f8252d2 2226 return false;
9e008dda 2227 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
4299f876 2228 requestSender = JobCallback(11,5,
4cb2536f 2229 Dialer, this, HttpStateData::sentRequestBody);
e31a1e67
AR
2230
2231 Must(!flags.chunked_request);
f228d6f6 2232 // use chunked encoding if we do not know the length
e24f13cd 2233 if (request->content_length < 0)
46f4b111 2234 flags.chunked_request = true;
5f8252d2 2235 } else {
2236 assert(!requestBodySource);
9e008dda 2237 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
4299f876 2238 requestSender = JobCallback(11,5,
39cb8c41 2239 Dialer, this, HttpStateData::wroteLast);
5f8252d2 2240 }
54220df8 2241
efb9218c 2242 /*
99edd1c3 2243 * Is keep-alive okay for all request methods?
efb9218c 2244 */
450fe1cb 2245 if (request->flags.mustKeepalive)
46f4b111 2246 flags.keepalive = true;
693cb033
CT
2247 else if (request->flags.pinned)
2248 flags.keepalive = request->persistent();
d67acb4e 2249 else if (!Config.onoff.server_pconns)
46f4b111 2250 flags.keepalive = false;
f5e17947
CT
2251 else if (flags.tunneling)
2252 // tunneled non pinned bumped requests must not keepalive
2253 flags.keepalive = !request->flags.sslBumped;
2bb867b5 2254 else if (_peer == NULL)
46f4b111 2255 flags.keepalive = true;
2bb867b5 2256 else if (_peer->stats.n_keepalives_sent < 10)
46f4b111 2257 flags.keepalive = true;
2bb867b5 2258 else if ((double) _peer->stats.n_keepalives_recv /
2259 (double) _peer->stats.n_keepalives_sent > 0.50)
46f4b111 2260 flags.keepalive = true;
2bb867b5 2261
f5e17947 2262 if (_peer && !flags.tunneling) {
2ecba5b6 2263 /*The old code here was
5c51bffb 2264 if (neighborType(_peer, request->url) == PEER_SIBLING && ...
e24f13cd 2265 which is equivalent to:
5c51bffb 2266 if (neighborType(_peer, URL()) == PEER_SIBLING && ...
e24f13cd
CT
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 */
5c51bffb 2274 if (neighborType(_peer, request->url) == PEER_SIBLING && !_peer->options.allow_miss)
46f4b111 2275 flags.only_if_cached = true;
2bb867b5 2276
2277 flags.front_end_https = _peer->front_end_https;
a7ad6e4e 2278 }
62e76326 2279
2fe7eff9 2280 mb.init();
9ca29d23 2281 request->peer_host=_peer?_peer->host:NULL;
e24f13cd 2282 buildRequestPrefix(&mb);
5f8252d2 2283
1ce34ddd
AJ
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);
5f8252d2 2288 return true;
090089c4 2289}
b6a2f15e 2290
39cb8c41
AR
2291bool
2292HttpStateData::getMoreRequestBody(MemBuf &buf)
2293{
2294 // parent's implementation can handle the no-encoding case
e31a1e67 2295 if (!flags.chunked_request)
fccd4a86 2296 return Client::getMoreRequestBody(buf);
39cb8c41
AR
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
4391cd15 2309 buf.appendf("%x\r\n", static_cast<unsigned int>(rawDataSize));
39cb8c41 2310 buf.append(raw.content(), rawDataSize);
4391cd15 2311 buf.append("\r\n", 2);
39cb8c41
AR
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;
de48b288 2319 buf.append("0\r\n\r\n", 5);
39cb8c41
AR
2320 }
2321
2322 return true;
2323}
2324
910169e5 2325void
b6b6f466 2326httpStart(FwdState *fwd)
603a02fd 2327{
7f06a3d8 2328 debugs(11, 3, fwd->request->method << ' ' << fwd->entry->url());
79628299
CT
2329 AsyncJob::Start(new HttpStateData(fwd));
2330}
62e76326 2331
79628299
CT
2332void
2333HttpStateData::start()
2334{
2335 if (!sendRequest()) {
bf8fe701 2336 debugs(11, 3, "httpStart: aborted");
79628299 2337 mustStop("HttpStateData::start failed");
5f8252d2 2338 return;
2339 }
62e76326 2340
95dc7ff4
FC
2341 ++ statCounter.server.all.requests;
2342 ++ statCounter.server.http.requests;
62e76326 2343
b6a2f15e 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 */
090089c4 2349}
2350
39cb8c41
AR
2351/// if broken posts are enabled for the request, try to fix and return true
2352bool
2353HttpStateData::finishingBrokenPost()
2bb867b5 2354{
626096be 2355#if USE_HTTP_VIOLATIONS
39cb8c41
AR
2356 if (!Config.accessList.brokenPosts) {
2357 debugs(11, 5, HERE << "No brokenPosts list");
2358 return false;
2359 }
a0297974 2360
d603e3c2 2361 ACLFilledChecklist ch(Config.accessList.brokenPosts, originalRequest().getRaw());
cb365059
EB
2362 ch.al = fwd->al;
2363 ch.syncAle(originalRequest().getRaw(), nullptr);
06bf5384 2364 if (!ch.fastCheck().allowed()) {
39cb8c41
AR
2365 debugs(11, 5, HERE << "didn't match brokenPosts");
2366 return false;
2367 }
a0297974 2368
9cf7de1b 2369 if (!Comm::IsConnOpen(serverConnection)) {
30c48b1a 2370 debugs(11, 3, HERE << "ignoring broken POST for closed " << serverConnection);
39cb8c41
AR
2371 assert(closeHandler != NULL);
2372 return true; // prevent caller from proceeding as if nothing happened
54220df8 2373 }
39cb8c41 2374
30c48b1a 2375 debugs(11, 3, "finishingBrokenPost: fixing broken POST");
39cb8c41
AR
2376 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
2377 requestSender = JobCallback(11,5,
2378 Dialer, this, HttpStateData::wroteLast);
b0388924 2379 Comm::Write(serverConnection, "\r\n", 2, requestSender, NULL);
39cb8c41
AR
2380 return true;
2381#else
2382 return false;
626096be 2383#endif /* USE_HTTP_VIOLATIONS */
39cb8c41
AR
2384}
2385
2386/// if needed, write last-chunk to end the request body and return true
2387bool
2388HttpStateData::finishingChunkedRequest()
2389{
2390 if (flags.sentLastChunk) {
2391 debugs(11, 5, HERE << "already sent last-chunk");
2392 return false;
2393 }
2394
2395 Must(receivedWholeRequestBody); // or we should not be sending last-chunk
2396 flags.sentLastChunk = true;
2397
2398 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
e0d28505 2399 requestSender = JobCallback(11,5, Dialer, this, HttpStateData::wroteLast);
b0388924 2400 Comm::Write(serverConnection, "0\r\n\r\n", 5, requestSender, NULL);
39cb8c41
AR
2401 return true;
2402}
2403
2404void
2405HttpStateData::doneSendingRequestBody()
2406{
fccd4a86 2407 Client::doneSendingRequestBody();
9cf7de1b 2408 debugs(11,5, HERE << serverConnection);
39cb8c41
AR
2409
2410 // do we need to write something after the last body byte?
e31a1e67 2411 if (flags.chunked_request && finishingChunkedRequest())
39cb8c41 2412 return;
e31a1e67 2413 if (!flags.chunked_request && finishingBrokenPost())
39cb8c41 2414 return;
aa49962c 2415
39cb8c41 2416 sendComplete();
94439e4e 2417}
2418
5f8252d2 2419// more origin request body data is available
2bb867b5 2420void
5f8252d2 2421HttpStateData::handleMoreRequestBodyAvailable()
2bb867b5 2422{
6b679a01 2423 if (eof || !Comm::IsConnOpen(serverConnection)) {
5f8252d2 2424 // XXX: we should check this condition in other callbacks then!
2425 // TODO: Check whether this can actually happen: We should unsubscribe
2426 // as a body consumer when the above condition(s) are detected.
e0236918 2427 debugs(11, DBG_IMPORTANT, HERE << "Transaction aborted while reading HTTP body");
2bb867b5 2428 return;
2429 }
62e76326 2430
5f8252d2 2431 assert(requestBodySource != NULL);
fc68f6b1 2432
5f8252d2 2433 if (requestBodySource->buf().hasContent()) {
2434 // XXX: why does not this trigger a debug message on every request?
fc68f6b1 2435
2bb867b5 2436 if (flags.headers_parsed && !flags.abuse_detected) {
46f4b111 2437 flags.abuse_detected = true;
e0236918 2438 debugs(11, DBG_IMPORTANT, "http handleMoreRequestBodyAvailable: Likely proxy abuse detected '" << request->client_addr << "' -> '" << entry->url() << "'" );
21b92762 2439
9b769c67 2440 if (virginReply()->sline.status() == Http::scInvalidHeader) {
398bc066
CT
2441 closeServer();
2442 mustStop("HttpStateData::handleMoreRequestBodyAvailable");
21b92762 2443 return;
2444 }
2445 }
b6a2f15e 2446 }
5f8252d2 2447
2448 HttpStateData::handleMoreRequestBodyAvailable();
376bb137 2449}
2450
5f8252d2 2451// premature end of the request body
2bb867b5 2452void
5f8252d2 2453HttpStateData::handleRequestBodyProducerAborted()
376bb137 2454{
fccd4a86 2455 Client::handleRequestBodyProducerAborted();
64b66b76 2456 if (entry->isEmpty()) {
25b481e6 2457 debugs(11, 3, "request body aborted: " << serverConnection);
8b997339
AR
2458 // We usually get here when ICAP REQMOD aborts during body processing.
2459 // We might also get here if client-side aborts, but then our response
2460 // should not matter because either client-side will provide its own or
2461 // there will be no response at all (e.g., if the the client has left).
7e6eabbc 2462 const auto err = new ErrorState(ERR_ICAP_FAILURE, Http::scInternalServerError, fwd->request, fwd->al);
129fe2a1 2463 err->detailError(ERR_DETAIL_SRV_REQMOD_REQ_BODY);
64b66b76
CT
2464 fwd->fail(err);
2465 }
2466
39cb8c41 2467 abortTransaction("request body producer aborted");
2bb867b5 2468}
2469
5f8252d2 2470// called when we wrote request headers(!) or a part of the body
2bb867b5 2471void
dc56a9b1 2472HttpStateData::sentRequestBody(const CommIoCbParams &io)
2bb867b5 2473{
dc56a9b1 2474 if (io.size > 0)
a0864754 2475 statCounter.server.http.kbytes_out += io.size;
fc68f6b1 2476
fccd4a86 2477 Client::sentRequestBody(io);
5f8252d2 2478}
3b299123 2479
5f8252d2 2480void
92cfc72f 2481HttpStateData::abortAll(const char *reason)
5f8252d2 2482{
2483 debugs(11,5, HERE << "aborting transaction for " << reason <<
9cf7de1b 2484 "; " << serverConnection << ", this " << this);
70df76e3 2485 mustStop(reason);
54220df8 2486}
f53969cc 2487
39fe14b2
EB
2488HttpStateData::ReuseDecision::ReuseDecision(const StoreEntry *e, const Http::StatusCode code)
2489 : answer(HttpStateData::ReuseDecision::reuseNot), reason(nullptr), entry(e), statusCode(code) {}
2490
2491HttpStateData::ReuseDecision::Answers
2492HttpStateData::ReuseDecision::make(const HttpStateData::ReuseDecision::Answers ans, const char *why)
2493{
2494 answer = ans;
2495 reason = why;
2496 return answer;
2497}
2498
2499std::ostream &operator <<(std::ostream &os, const HttpStateData::ReuseDecision &d)
2500{
2501 static const char *ReuseMessages[] = {
2502 "do not cache and do not share", // reuseNot
2503 "cache positively and share", // cachePositively
2504 "cache negatively and share", // cacheNegatively
2505 "do not cache but share" // doNotCacheButShare
2506 };
2507
2508 assert(d.answer >= HttpStateData::ReuseDecision::reuseNot &&
4a71b1fc 2509 d.answer <= HttpStateData::ReuseDecision::doNotCacheButShare);
39fe14b2 2510 return os << ReuseMessages[d.answer] << " because " << d.reason <<
4a71b1fc 2511 "; HTTP status " << d.statusCode << " " << *(d.entry);
39fe14b2
EB
2512}
2513