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