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