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