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