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