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