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