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