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