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