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