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