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