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