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