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