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