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