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