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