]> git.ipfire.org Git - thirdparty/squid.git/blame - src/http.cc
Adding a comment that tests/testUfs will fail when 'heap' is the only
[thirdparty/squid.git] / src / http.cc
CommitLineData
da2b3a17 1
30a4f2a8 2/*
b004a7fc 3 * $Id: http.cc,v 1.516 2007/04/24 23:13:25 wessels Exp $
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.
24 *
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.
29 *
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"
aa839030 42#include "errorpage.h"
0eb49b6d 43#include "MemBuf.h"
e6ccf245 44#include "http.h"
f5691f9c 45#include "AuthUserRequest.h"
e6ccf245 46#include "Store.h"
528b2c61 47#include "HttpReply.h"
48#include "HttpRequest.h"
49#include "MemObject.h"
50#include "HttpHdrContRange.h"
b19dd748 51#include "HttpHdrSc.h"
52#include "HttpHdrScTarget.h"
4fb35c3c 53#include "ACLChecklist.h"
21b92762 54#include "fde.h"
b67e2c8c 55#if DELAY_POOLS
56#include "DelayPools.h"
57#endif
2afaba07 58#if ICAP_CLIENT
2afaba07 59#include "ICAP/ICAPConfig.h"
ab7ac359 60extern ICAPConfig TheICAPConfig;
2afaba07 61#endif
985c86bc 62#include "SquidTime.h"
e6ccf245 63
2afaba07 64CBDATA_CLASS_INIT(HttpStateData);
090089c4 65
6bf8443a 66static const char *const crlf = "\r\n";
4db43fab 67
9e4ad609 68static PF httpStateFree;
69static PF httpTimeout;
f9cece6e 70static void httpMaybeRemovePublic(StoreEntry *, http_status);
190154cf 71static void copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, String strConnection, HttpRequest * request, HttpRequest * orig_request,
62e76326 72 HttpHeader * hdr_out, int we_do_ranges, http_state_flags);
2afaba07 73#if ICAP_CLIENT
74static void icapAclCheckDoneWrapper(ICAPServiceRep::Pointer service, void *data);
75#endif
528b2c61 76
5f8252d2 77HttpStateData::HttpStateData(FwdState *theFwdState) : ServerStateData(theFwdState),
fc68f6b1 78 header_bytes_read(0), reply_bytes_read(0)
2bb867b5 79{
80 debugs(11,5,HERE << "HttpStateData " << this << " created");
a3d50c30 81 ignoreCacheControl = false;
82 surrogateNoStore = false;
a3d50c30 83 fd = fwd->server_fd;
84 readBuf = new MemBuf;
85 readBuf->init(4096, SQUID_TCP_SO_RCVBUF);
6dd9f4bd 86 orig_request = HTTPMSGLOCK(fwd->request);
a3d50c30 87
88 if (fwd->servers)
89 _peer = fwd->servers->_peer; /* might be NULL */
90
91 if (_peer) {
92 const char *url;
93
94 if (_peer->options.originserver)
95 url = orig_request->urlpath.buf();
96 else
3900307b 97 url = entry->url();
a3d50c30 98
5cafad19 99 HttpRequest * proxy_req = new HttpRequest(orig_request->method,
100 orig_request->protocol, url);
a3d50c30 101
102 xstrncpy(proxy_req->host, _peer->host, SQUIDHOSTNAMELEN);
103
104 proxy_req->port = _peer->http_port;
105
106 proxy_req->flags = orig_request->flags;
107
108 proxy_req->lastmod = orig_request->lastmod;
109
110 proxy_req->flags.proxying = 1;
111
6dd9f4bd 112 HTTPMSGUNLOCK(request);
253caccb 113
6dd9f4bd 114 request = HTTPMSGLOCK(proxy_req);
a3d50c30 115
116 /*
117 * This NEIGHBOR_PROXY_ONLY check probably shouldn't be here.
118 * We might end up getting the object from somewhere else if,
119 * for example, the request to this neighbor fails.
120 */
121 if (_peer->options.proxy_only)
d88e3c49 122 entry->releaseRequest();
a3d50c30 123
124#if DELAY_POOLS
125
126 entry->setNoDelay(_peer->options.no_delay);
127
128#endif
129
a3d50c30 130 }
131
132 /*
133 * register the handler to free HTTP state data when the FD closes
134 */
135 comm_add_close_handler(fd, httpStateFree, this);
2bb867b5 136}
b8d8561b 137
2afaba07 138HttpStateData::~HttpStateData()
f5558c95 139{
253caccb 140 /*
3b299123 141 * don't forget that ~ServerStateData() gets called automatically
253caccb 142 */
143
2afaba07 144 if (!readBuf->isNull())
145 readBuf->clean();
62e76326 146
2afaba07 147 delete readBuf;
148
6dd9f4bd 149 HTTPMSGUNLOCK(orig_request);
2afaba07 150
5f8252d2 151 debugs(11,5, HERE << "HttpStateData " << this << " destroyed; FD " << fd);
152}
153
154int
fc68f6b1 155HttpStateData::dataDescriptor() const
156{
5f8252d2 157 return fd;
2afaba07 158}
159
160static void
161httpStateFree(int fd, void *data)
162{
163 HttpStateData *httpState = static_cast<HttpStateData *>(data);
164 debug(11,5)("httpStateFree: FD %d, httpState=%p\n", fd, data);
5f8252d2 165 delete httpState;
f5558c95 166}
167
b8d8561b 168int
75e88d56 169httpCachable(method_t method)
090089c4 170{
090089c4 171 /* GET and HEAD are cachable. Others are not. */
62e76326 172
6eb42cae 173 if (method != METHOD_GET && method != METHOD_HEAD)
62e76326 174 return 0;
175
090089c4 176 /* else cachable */
177 return 1;
178}
179
b8d8561b 180static void
5c5783a2 181httpTimeout(int fd, void *data)
090089c4 182{
e6ccf245 183 HttpStateData *httpState = static_cast<HttpStateData *>(data);
593c9a75 184 StoreEntry *entry = httpState->entry;
3900307b 185 debug(11, 4) ("httpTimeout: FD %d: '%s'\n", fd, entry->url());
62e76326 186
12158bdc 187 if (entry->store_status == STORE_PENDING) {
2cc81f1f 188 httpState->fwd->fail(errorCon(ERR_READ_TIMEOUT, HTTP_GATEWAY_TIMEOUT, httpState->fwd->request));
9b312a19 189 }
62e76326 190
0d4d4170 191 comm_close(fd);
090089c4 192}
193
f9cece6e 194static void
195httpMaybeRemovePublic(StoreEntry * e, http_status status)
196{
62e76326 197
198 int remove
199 = 0;
200
7e3ce7b9 201 int forbidden = 0;
62e76326 202
f9cece6e 203 StoreEntry *pe;
62e76326 204
d46a87a8 205 if (!EBIT_TEST(e->flags, KEY_PRIVATE))
62e76326 206 return;
207
f9cece6e 208 switch (status) {
62e76326 209
f9cece6e 210 case HTTP_OK:
62e76326 211
f9cece6e 212 case HTTP_NON_AUTHORITATIVE_INFORMATION:
62e76326 213
f9cece6e 214 case HTTP_MULTIPLE_CHOICES:
62e76326 215
f9cece6e 216 case HTTP_MOVED_PERMANENTLY:
62e76326 217
f9cece6e 218 case HTTP_MOVED_TEMPORARILY:
62e76326 219
f9cece6e 220 case HTTP_GONE:
62e76326 221
7e3ce7b9 222 case HTTP_NOT_FOUND:
62e76326 223
224 remove
225 = 1;
226
227 break;
228
7e3ce7b9 229 case HTTP_FORBIDDEN:
62e76326 230
7e3ce7b9 231 case HTTP_METHOD_NOT_ALLOWED:
62e76326 232 forbidden = 1;
233
234 break;
235
f9cece6e 236#if WORK_IN_PROGRESS
62e76326 237
c8fd0193 238 case HTTP_UNAUTHORIZED:
62e76326 239 forbidden = 1;
240
241 break;
242
f9cece6e 243#endif
62e76326 244
f9cece6e 245 default:
7e3ce7b9 246#if QUESTIONABLE
62e76326 247 /*
248 * Any 2xx response should eject previously cached entities...
249 */
abb929f0 250
62e76326 251 if (status >= 200 && status < 300)
252 remove
253 = 1;
254
7e3ce7b9 255#endif
62e76326 256
257 break;
f9cece6e 258 }
62e76326 259
260 if (!remove
261 && !forbidden)
262 return;
263
f9cece6e 264 assert(e->mem_obj);
62e76326 265
f66a9ef4 266 if (e->mem_obj->request)
62e76326 267 pe = storeGetPublicByRequest(e->mem_obj->request);
f66a9ef4 268 else
62e76326 269 pe = storeGetPublic(e->mem_obj->url, e->mem_obj->method);
270
f66a9ef4 271 if (pe != NULL) {
62e76326 272 assert(e != pe);
5f33b71d 273 pe->release();
0856d155 274 }
62e76326 275
7e3ce7b9 276 /*
277 * Also remove any cached HEAD response in case the object has
278 * changed.
279 */
f66a9ef4 280 if (e->mem_obj->request)
62e76326 281 pe = storeGetPublicByRequestMethod(e->mem_obj->request, METHOD_HEAD);
f66a9ef4 282 else
62e76326 283 pe = storeGetPublic(e->mem_obj->url, METHOD_HEAD);
284
f66a9ef4 285 if (pe != NULL) {
62e76326 286 assert(e != pe);
5f33b71d 287 pe->release();
7e3ce7b9 288 }
62e76326 289
7e3ce7b9 290 if (forbidden)
62e76326 291 return;
292
7e3ce7b9 293 switch (e->mem_obj->method) {
62e76326 294
7e3ce7b9 295 case METHOD_PUT:
62e76326 296
7e3ce7b9 297 case METHOD_DELETE:
62e76326 298
7e3ce7b9 299 case METHOD_PROPPATCH:
62e76326 300
7e3ce7b9 301 case METHOD_MKCOL:
62e76326 302
7e3ce7b9 303 case METHOD_MOVE:
62e76326 304
42b51993 305 case METHOD_BMOVE:
62e76326 306
42b51993 307 case METHOD_BDELETE:
62e76326 308 /*
309 * Remove any cached GET object if it is beleived that the
310 * object may have changed as a result of other methods
311 */
312
313 if (e->mem_obj->request)
314 pe = storeGetPublicByRequestMethod(e->mem_obj->request, METHOD_GET);
315 else
316 pe = storeGetPublic(e->mem_obj->url, METHOD_GET);
317
318 if (pe != NULL) {
319 assert(e != pe);
5f33b71d 320 pe->release();
62e76326 321 }
322
323 break;
324
c8be6d7b 325 default:
62e76326 326 /* Keep GCC happy. The methods above are all mutating HTTP methods
327 */
328 break;
0856d155 329 }
f9cece6e 330}
331
43ae1d95 332void
333HttpStateData::processSurrogateControl(HttpReply *reply)
334{
335#if ESI
336
337 if (request->flags.accelerated && reply->surrogate_control) {
338 HttpHdrScTarget *sctusable =
339 httpHdrScGetMergedTarget(reply->surrogate_control,
340 Config.Accel.surrogate_id);
341
342 if (sctusable) {
343 if (EBIT_TEST(sctusable->mask, SC_NO_STORE) ||
344 (Config.onoff.surrogate_is_remote
345 && EBIT_TEST(sctusable->mask, SC_NO_STORE_REMOTE))) {
346 surrogateNoStore = true;
5ed72359 347 entry->makePrivate();
43ae1d95 348 }
349
350 /* The HttpHeader logic cannot tell if the header it's parsing is a reply to an
351 * accelerated request or not...
352 * Still, this is an abtraction breach. - RC
353 */
354 if (sctusable->max_age != -1) {
355 if (sctusable->max_age < sctusable->max_stale)
356 reply->expires = reply->date + sctusable->max_age;
357 else
358 reply->expires = reply->date + sctusable->max_stale;
359
360 /* And update the timestamps */
3900307b 361 entry->timestampsSet();
43ae1d95 362 }
363
364 /* We ignore cache-control directives as per the Surrogate specification */
365 ignoreCacheControl = true;
366
367 httpHdrScTargetDestroy(sctusable);
368 }
369 }
370
371#endif
372}
373
924f73bc 374int
375HttpStateData::cacheableReply()
c54e9052 376{
2afaba07 377 HttpReply const *rep = getReply();
528b2c61 378 HttpHeader const *hdr = &rep->header;
d8b249ef 379 const int cc_mask = (rep->cache_control) ? rep->cache_control->mask : 0;
c68e9c6b 380 const char *v;
38f9c547 381#if HTTP_VIOLATIONS
62e76326 382
38f9c547 383 const refresh_t *R = NULL;
b6445726 384
346be6ad 385 /* This strange looking define first looks up the refresh pattern
b6445726 386 * and then checks if the specified flag is set. The main purpose
387 * of this is to simplify the refresh pattern lookup and HTTP_VIOLATIONS
388 * condition
389 */
390#define REFRESH_OVERRIDE(flag) \
5f8252d2 391 ((R = (R ? R : refreshLimits(entry->mem_obj->url))) , \
392 (R && R->flags.flag))
b445957e 393#else
394#define REFRESH_OVERRIDE(flag) 0
38f9c547 395#endif
43ae1d95 396
38f9c547 397 if (surrogateNoStore)
62e76326 398 return 0;
399
924f73bc 400 if (!ignoreCacheControl) {
38f9c547 401 if (EBIT_TEST(cc_mask, CC_PRIVATE)) {
b6445726 402 if (!REFRESH_OVERRIDE(ignore_private))
38f9c547 403 return 0;
404 }
405
406 if (EBIT_TEST(cc_mask, CC_NO_CACHE)) {
b6445726 407 if (!REFRESH_OVERRIDE(ignore_no_cache))
38f9c547 408 return 0;
409 }
410
411 if (EBIT_TEST(cc_mask, CC_NO_STORE)) {
b6445726 412 if (!REFRESH_OVERRIDE(ignore_no_store))
38f9c547 413 return 0;
414 }
43ae1d95 415 }
416
924f73bc 417 if (request->flags.auth) {
62e76326 418 /*
419 * Responses to requests with authorization may be cached
420 * only if a Cache-Control: public reply header is present.
421 * RFC 2068, sec 14.9.4
422 */
423
38f9c547 424 if (!EBIT_TEST(cc_mask, CC_PUBLIC)) {
b6445726 425 if (!REFRESH_OVERRIDE(ignore_auth))
38f9c547 426 return 0;
427 }
a6dfe2d9 428 }
62e76326 429
c68e9c6b 430 /* Pragma: no-cache in _replies_ is not documented in HTTP,
431 * but servers like "Active Imaging Webcast/2.0" sure do use it */
a9925b40 432 if (hdr->has(HDR_PRAGMA)) {
433 String s = hdr->getList(HDR_PRAGMA);
62e76326 434 const int no_cache = strListIsMember(&s, "no-cache", ',');
435 s.clean();
436
38f9c547 437 if (no_cache) {
b6445726 438 if (!REFRESH_OVERRIDE(ignore_no_cache))
38f9c547 439 return 0;
440 }
c68e9c6b 441 }
62e76326 442
c68e9c6b 443 /*
444 * The "multipart/x-mixed-replace" content type is used for
445 * continuous push replies. These are generally dynamic and
446 * probably should not be cachable
447 */
a9925b40 448 if ((v = hdr->getStr(HDR_CONTENT_TYPE)))
62e76326 449 if (!strncasecmp(v, "multipart/x-mixed-replace", 25))
450 return 0;
451
2afaba07 452 switch (getReply()->sline.status) {
62e76326 453 /* Responses that are cacheable */
454
19a04dac 455 case HTTP_OK:
62e76326 456
19a04dac 457 case HTTP_NON_AUTHORITATIVE_INFORMATION:
62e76326 458
19a04dac 459 case HTTP_MULTIPLE_CHOICES:
62e76326 460
19a04dac 461 case HTTP_MOVED_PERMANENTLY:
62e76326 462
19a04dac 463 case HTTP_GONE:
62e76326 464 /*
465 * Don't cache objects that need to be refreshed on next request,
466 * unless we know how to refresh it.
467 */
468
1b5358c3 469 if (!refreshIsCachable(entry)) {
fc68f6b1 470 debug(22, 3) ("refreshIsCachable() returned non-cacheable..\n");
62e76326 471 return 0;
fc68f6b1 472 }
62e76326 473
474 /* don't cache objects from peers w/o LMT, Date, or Expires */
475 /* check that is it enough to check headers @?@ */
476 if (rep->date > -1)
477 return 1;
478 else if (rep->last_modified > -1)
479 return 1;
924f73bc 480 else if (!_peer)
62e76326 481 return 1;
482
483 /* @?@ (here and 302): invalid expires header compiles to squid_curtime */
484 else if (rep->expires > -1)
485 return 1;
486 else
487 return 0;
488
489 /* NOTREACHED */
490 break;
491
492 /* Responses that only are cacheable if the server says so */
493
19a04dac 494 case HTTP_MOVED_TEMPORARILY:
6a2bf8f4 495 if (rep->expires > rep->date && rep->date > 0)
62e76326 496 return 1;
497 else
498 return 0;
499
500 /* NOTREACHED */
501 break;
502
503 /* Errors can be negatively cached */
504
19a04dac 505 case HTTP_NO_CONTENT:
62e76326 506
19a04dac 507 case HTTP_USE_PROXY:
62e76326 508
19a04dac 509 case HTTP_BAD_REQUEST:
62e76326 510
19a04dac 511 case HTTP_FORBIDDEN:
62e76326 512
19a04dac 513 case HTTP_NOT_FOUND:
62e76326 514
19a04dac 515 case HTTP_METHOD_NOT_ALLOWED:
62e76326 516
19a04dac 517 case HTTP_REQUEST_URI_TOO_LARGE:
62e76326 518
19a04dac 519 case HTTP_INTERNAL_SERVER_ERROR:
62e76326 520
19a04dac 521 case HTTP_NOT_IMPLEMENTED:
62e76326 522
19a04dac 523 case HTTP_BAD_GATEWAY:
62e76326 524
19a04dac 525 case HTTP_SERVICE_UNAVAILABLE:
62e76326 526
19a04dac 527 case HTTP_GATEWAY_TIMEOUT:
62e76326 528 return -1;
529
530 /* NOTREACHED */
531 break;
532
533 /* Some responses can never be cached */
534
0cdcddb9 535 case HTTP_PARTIAL_CONTENT: /* Not yet supported */
62e76326 536
19a04dac 537 case HTTP_SEE_OTHER:
62e76326 538
19a04dac 539 case HTTP_NOT_MODIFIED:
62e76326 540
19a04dac 541 case HTTP_UNAUTHORIZED:
62e76326 542
19a04dac 543 case HTTP_PROXY_AUTHENTICATION_REQUIRED:
62e76326 544
0cdcddb9 545 case HTTP_INVALID_HEADER: /* Squid header parsing error */
4eb368f9 546
547 case HTTP_HEADER_TOO_LARGE:
b004a7fc 548
549 case HTTP_PAYMENT_REQUIRED:
550 case HTTP_NOT_ACCEPTABLE:
551 case HTTP_REQUEST_TIMEOUT:
552 case HTTP_CONFLICT:
553 case HTTP_LENGTH_REQUIRED:
554 case HTTP_PRECONDITION_FAILED:
555 case HTTP_REQUEST_ENTITY_TOO_LARGE:
556 case HTTP_UNSUPPORTED_MEDIA_TYPE:
557 case HTTP_UNPROCESSABLE_ENTITY:
558 case HTTP_LOCKED:
559 case HTTP_FAILED_DEPENDENCY:
560 case HTTP_INSUFFICIENT_STORAGE:
561
62e76326 562 return 0;
563
c54e9052 564 default: /* Unknown status code */
b004a7fc 565 debugs (11, 0, HERE << "HttpStateData::cacheableReply: unexpected http status code " << getReply()->sline.status);
62e76326 566
567 return 0;
568
569 /* NOTREACHED */
570 break;
c54e9052 571 }
62e76326 572
79d39a72 573 /* NOTREACHED */
c54e9052 574}
090089c4 575
f66a9ef4 576/*
577 * For Vary, store the relevant request headers as
578 * virtual headers in the reply
579 * Returns false if the variance cannot be stored
580 */
581const char *
190154cf 582httpMakeVaryMark(HttpRequest * request, HttpReply const * reply)
f66a9ef4 583{
f66a9ef4 584 String vary, hdr;
585 const char *pos = NULL;
586 const char *item;
587 const char *value;
588 int ilen;
528b2c61 589 static String vstr;
f66a9ef4 590
528b2c61 591 vstr.clean();
a9925b40 592 vary = reply->header.getList(HDR_VARY);
62e76326 593
f66a9ef4 594 while (strListGetItem(&vary, ',', &item, &ilen, &pos)) {
62e76326 595 char *name = (char *)xmalloc(ilen + 1);
596 xstrncpy(name, item, ilen + 1);
597 Tolower(name);
9776e3cc 598
599 if (strcmp(name, "*") == 0) {
600 /* Can not handle "Vary: *" withtout ETag support */
601 safe_free(name);
602 vstr.clean();
603 break;
604 }
605
62e76326 606 strListAdd(&vstr, name, ',');
a9925b40 607 hdr = request->header.getByName(name);
62e76326 608 safe_free(name);
609 value = hdr.buf();
610
611 if (value) {
612 value = rfc1738_escape_part(value);
613 vstr.append("=\"", 2);
614 vstr.append(value);
615 vstr.append("\"", 1);
616 }
617
618 hdr.clean();
f66a9ef4 619 }
62e76326 620
528b2c61 621 vary.clean();
f66a9ef4 622#if X_ACCELERATOR_VARY
62e76326 623
aa38be4a 624 pos = NULL;
a9925b40 625 vary = reply->header.getList(HDR_X_ACCELERATOR_VARY);
62e76326 626
f66a9ef4 627 while (strListGetItem(&vary, ',', &item, &ilen, &pos)) {
62e76326 628 char *name = (char *)xmalloc(ilen + 1);
629 xstrncpy(name, item, ilen + 1);
630 Tolower(name);
631 strListAdd(&vstr, name, ',');
a9925b40 632 hdr = request->header.getByName(name);
62e76326 633 safe_free(name);
634 value = hdr.buf();
635
636 if (value) {
637 value = rfc1738_escape_part(value);
638 vstr.append("=\"", 2);
639 vstr.append(value);
640 vstr.append("\"", 1);
641 }
642
643 hdr.clean();
f66a9ef4 644 }
62e76326 645
528b2c61 646 vary.clean();
f66a9ef4 647#endif
62e76326 648
528b2c61 649 debug(11, 3) ("httpMakeVaryMark: %s\n", vstr.buf());
650 return vstr.buf();
f66a9ef4 651}
652
4eb368f9 653void
654HttpStateData::failReply(HttpReply *reply, http_status const & status)
655{
656 reply->sline.version = HttpVersion(1, 0);
657 reply->sline.status = status;
db237875 658 entry->replaceHttpReply(reply);
4eb368f9 659
660 if (eof == 1) {
5f8252d2 661 serverComplete();
4eb368f9 662 }
663}
664
2afaba07 665void
666HttpStateData::keepaliveAccounting(HttpReply *reply)
667{
668 if (flags.keepalive)
669 if (_peer)
670 _peer->stats.n_keepalives_sent++;
671
672 if (reply->keep_alive) {
673 if (_peer)
674 _peer->stats.n_keepalives_recv++;
675
676 if (Config.onoff.detect_broken_server_pconns && reply->bodySize(request->method) == -1) {
3900307b 677 debug(11, 1) ("keepaliveAccounting: Impossible keep-alive header from '%s'\n", entry->url());
2afaba07 678 // debug(11, 2) ("GOT HTTP REPLY HDR:\n---------\n%s\n----------\n", readBuf->content());
679 flags.keepalive_broken = 1;
680 }
681 }
682}
683
684void
685HttpStateData::checkDateSkew(HttpReply *reply)
686{
687 if (reply->date > -1 && !_peer) {
688 int skew = abs((int)(reply->date - squid_curtime));
689
690 if (skew > 86400)
691 debug(11, 3) ("%s's clock is skewed by %d seconds!\n",
692 request->host, skew);
693 }
694}
695
696/*
4eb368f9 697 * This creates the error page itself.. its likely
698 * that the forward ported reply header max size patch
699 * generates non http conformant error pages - in which
700 * case the errors where should be 'BAD_GATEWAY' etc
701 */
b8d8561b 702void
2afaba07 703HttpStateData::processReplyHeader()
f5558c95 704{
528b2c61 705 /* Creates a blank header. If this routine is made incremental, this will
706 * not do
707 */
4a56ee8d 708 HttpReply *newrep = new HttpReply;
82384411 709 Ctx ctx = ctx_enter(entry->mem_obj->url);
2afaba07 710 debug(11, 3) ("processReplyHeader: key '%s'\n", entry->getMD5Text());
62e76326 711
1a98175f 712 assert(!flags.headers_parsed);
62e76326 713
2afaba07 714 http_status error = HTTP_STATUS_NONE;
62e76326 715
4a56ee8d 716 const bool parsed = newrep->parse(readBuf, eof, &error);
62e76326 717
2afaba07 718 if (!parsed && error > 0) { // unrecoverable parsing error
719 debugs(11, 3, "processReplyHeader: Non-HTTP-compliant header: '" << readBuf->content() << "'");
1a98175f 720 flags.headers_parsed = 1;
2afaba07 721 // negated result yields http_status
4a56ee8d 722 failReply (newrep, error);
82384411 723 ctx_exit(ctx);
4eb368f9 724 return;
725 }
62e76326 726
2afaba07 727 if (!parsed) { // need more data
728 assert(!error);
729 assert(!eof);
4a56ee8d 730 delete newrep;
82384411 731 ctx_exit(ctx);
62e76326 732 return;
f5558c95 733 }
62e76326 734
6dd9f4bd 735 reply = HTTPMSGLOCK(newrep);
4a56ee8d 736
9bc73deb 737 debug(11, 9) ("GOT HTTP REPLY HDR:\n---------\n%s\n----------\n",
2afaba07 738 readBuf->content());
4eb368f9 739
5f8252d2 740 header_bytes_read = headersEnd(readBuf->content(), readBuf->contentSize());
741 readBuf->consume(header_bytes_read);
4a56ee8d 742
6965ab28 743 flags.headers_parsed = 1;
744
2afaba07 745 keepaliveAccounting(reply);
47ac2ebe 746
2afaba07 747 checkDateSkew(reply);
47ac2ebe 748
43ae1d95 749 processSurrogateControl (reply);
528b2c61 750
751 /* TODO: IF the reply is a 1.0 reply, AND it has a Connection: Header
752 * Parse the header and remove all referenced headers
753 */
754
2afaba07 755#if ICAP_CLIENT
756
ab7ac359 757 if (TheICAPConfig.onoff) {
2afaba07 758 ICAPAccessCheck *icap_access_check =
759 new ICAPAccessCheck(ICAP::methodRespmod, ICAP::pointPreCache, request, reply, icapAclCheckDoneWrapper, this);
760
761 icapAccessCheckPending = true;
762 icap_access_check->check(); // will eventually delete self
763 ctx_exit(ctx);
764 return;
765 }
ab7ac359 766
2afaba07 767#endif
768
db237875 769 entry->replaceHttpReply(reply);
2afaba07 770
2afaba07 771 haveParsedReplyHeaders();
772
773 if (eof == 1) {
5f8252d2 774 serverComplete();
2afaba07 775 }
776
777 ctx_exit(ctx);
778}
779
5f8252d2 780// Called when we parsed (and possibly adapted) the headers but
781// had not starting storing (a.k.a., sending) the body yet.
2afaba07 782void
783HttpStateData::haveParsedReplyHeaders()
784{
785 Ctx ctx = ctx_enter(entry->mem_obj->url);
786
787 if (getReply()->sline.status == HTTP_PARTIAL_CONTENT &&
788 getReply()->content_range)
789 currentOffset = getReply()->content_range->spec.offset;
62e76326 790
3900307b 791 entry->timestampsSet();
62e76326 792
9bc73deb 793 /* Check if object is cacheable or not based on reply code */
2afaba07 794 debug(11, 3) ("haveParsedReplyHeaders: HTTP CODE: %d\n", getReply()->sline.status);
62e76326 795
9bc73deb 796 if (neighbors_do_private_keys)
2afaba07 797 httpMaybeRemovePublic(entry, getReply()->sline.status);
e6ccf245 798
a9925b40 799 if (getReply()->header.has(HDR_VARY)
f66a9ef4 800#if X_ACCELERATOR_VARY
a9925b40 801 || getReply()->header.has(HDR_X_ACCELERATOR_VARY)
f66a9ef4 802#endif
4b44c907 803 ) {
2afaba07 804 const char *vary = httpMakeVaryMark(orig_request, getReply());
4b44c907 805
806 if (!vary) {
5ed72359 807 entry->makePrivate();
4b44c907 808 goto no_cache;
809
62e76326 810 }
811
4b44c907 812 entry->mem_obj->vary_headers = xstrdup(vary);
813 }
814
2afaba07 815#if WIP_FWD_LOG
816 fwdStatus(fwd, s);
817
818#endif
819 /*
820 * If its not a reply that we will re-forward, then
821 * allow the client to get it.
822 */
b6b6f466 823 if (!fwd->reforwardableStatus(getReply()->sline.status))
2afaba07 824 EBIT_CLR(entry->flags, ENTRY_FWD_HDR_WAIT);
825
4b44c907 826 switch (cacheableReply()) {
827
828 case 1:
5ed72359 829 entry->makePublic();
62e76326 830 break;
831
9bc73deb 832 case 0:
5ed72359 833 entry->makePrivate();
62e76326 834 break;
835
9bc73deb 836 case -1:
4b44c907 837
838 if (Config.negativeTtl > 0)
5ed72359 839 entry->cacheNegatively();
4b44c907 840 else
5ed72359 841 entry->makePrivate();
4b44c907 842
62e76326 843 break;
844
9bc73deb 845 default:
62e76326 846 assert(0);
4b44c907 847
62e76326 848 break;
9bc73deb 849 }
62e76326 850
4b44c907 851no_cache:
852
2afaba07 853 if (!ignoreCacheControl && getReply()->cache_control) {
854 if (EBIT_TEST(getReply()->cache_control->mask, CC_PROXY_REVALIDATE))
62e76326 855 EBIT_SET(entry->flags, ENTRY_REVALIDATE);
2afaba07 856 else if (EBIT_TEST(getReply()->cache_control->mask, CC_MUST_REVALIDATE))
62e76326 857 EBIT_SET(entry->flags, ENTRY_REVALIDATE);
9bc73deb 858 }
62e76326 859
c3609322 860#if HEADERS_LOG
2afaba07 861 headersLog(1, 0, request->method, getReply());
fc68f6b1 862
c3609322 863#endif
5f8252d2 864
865 ctx_exit(ctx);
f5558c95 866}
867
528b2c61 868HttpStateData::ConnectionStatus
869HttpStateData::statusIfComplete() const
603a02fd 870{
2afaba07 871 HttpReply const *rep = getReply();
528b2c61 872 /* If the reply wants to close the connection, it takes precedence */
62e76326 873
2afaba07 874 if (httpHeaderHasConnDir(&rep->header, "close"))
62e76326 875 return COMPLETE_NONPERSISTENT_MSG;
876
528b2c61 877 /* If we didn't send a keep-alive request header, then this
978e455f 878 * can not be a persistent connection.
879 */
528b2c61 880 if (!flags.keepalive)
62e76326 881 return COMPLETE_NONPERSISTENT_MSG;
882
72b63f06 883 /*
884 * If we haven't sent the whole request then this can not be a persistent
885 * connection.
886 */
887 if (!flags.request_sent) {
2afdbf48 888 debug(11, 1) ("statusIfComplete: Request not yet fully sent \"%s %s\"\n",
72b63f06 889 RequestMethodStr[orig_request->method],
3900307b 890 entry->url());
72b63f06 891 return COMPLETE_NONPERSISTENT_MSG;
892 }
893
9f5a2895 894 /*
895 * What does the reply have to say about keep-alive?
896 */
b6a2f15e 897 /*
898 * XXX BUG?
899 * If the origin server (HTTP/1.0) does not send a keep-alive
900 * header, but keeps the connection open anyway, what happens?
901 * We'll return here and http.c waits for an EOF before changing
902 * store_status to STORE_OK. Combine this with ENTRY_FWD_HDR_WAIT
903 * and an error status code, and we might have to wait until
904 * the server times out the socket.
905 */
2afaba07 906 if (!rep->keep_alive)
528b2c61 907 return COMPLETE_NONPERSISTENT_MSG;
62e76326 908
528b2c61 909 return COMPLETE_PERSISTENT_MSG;
910}
911
912HttpStateData::ConnectionStatus
913HttpStateData::persistentConnStatus() const
914{
2afaba07 915 debug(11, 3) ("persistentConnStatus: FD %d\n", fd);
2afaba07 916 debug(11, 5) ("persistentConnStatus: content_length=%d\n",
62e76326 917 reply->content_length);
62e76326 918
5f8252d2 919 /* If we haven't seen the end of reply headers, we are not done */
2afaba07 920 debug(11,5)("persistentConnStatus: flags.headers_parsed=%d\n", flags.headers_parsed);
fc68f6b1 921
1a98175f 922 if (!flags.headers_parsed)
62e76326 923 return INCOMPLETE_MSG;
924
5f8252d2 925 const int clen = reply->bodySize(request->method);
fc68f6b1 926
2afaba07 927 debug(11,5)("persistentConnStatus: clen=%d\n", clen);
928
35282fbf 929 /* If the body size is unknown we must wait for EOF */
930 if (clen < 0)
62e76326 931 return INCOMPLETE_MSG;
932
5f8252d2 933 /* If the body size is known, we must wait until we've gotten all of it. */
934 if (clen > 0) {
935 // old technique:
936 // if (entry->mem_obj->endOffset() < reply->content_length + reply->hdr_sz)
937 const int body_bytes_read = reply_bytes_read - header_bytes_read;
938 debugs(11,5, "persistentConnStatus: body_bytes_read=" <<
fc68f6b1 939 body_bytes_read << " content_length=" << reply->content_length);
2afaba07 940
5f8252d2 941 if (body_bytes_read < reply->content_length)
942 return INCOMPLETE_MSG;
943 }
62e76326 944
5f8252d2 945 /* If there is no message body or we got it all, we can be persistent */
946 return statusIfComplete();
603a02fd 947}
090089c4 948
2afaba07 949/*
950 * This is the callback after some data has been read from the network
951 */
e5ee81f0 952void
953HttpStateData::ReadReplyWrapper(int fd, char *buf, size_t len, comm_err_t flag, int xerrno, void *data)
c4b7a5a9 954{
955 HttpStateData *httpState = static_cast<HttpStateData *>(data);
7194987f 956 assert (fd == httpState->fd);
2afaba07 957 // assert(buf == readBuf->content());
1d5161bd 958 PROF_start(HttpStateData_readReply);
2afaba07 959 httpState->readReply (len, flag, xerrno);
1d5161bd 960 PROF_stop(HttpStateData_readReply);
c4b7a5a9 961}
962
2afdbf48 963/* XXX this function is too long! */
c4b7a5a9 964void
2afaba07 965HttpStateData::readReply (size_t len, comm_err_t flag, int xerrno)
090089c4 966{
30a4f2a8 967 int bin;
090089c4 968 int clen;
f61f0107 969 flags.do_next_read = 0;
c4b7a5a9 970
2afaba07 971 /*
972 * Bail out early on COMM_ERR_CLOSING - close handlers will tidy up for us
973 */
62e76326 974
c4b7a5a9 975 if (flag == COMM_ERR_CLOSING) {
d09176e1 976 debug (11,3)("http socket closing\n");
c4b7a5a9 977 return;
978 }
979
e92e4e44 980 if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
5f8252d2 981 maybeReadVirginBody();
62e76326 982 return;
e92e4e44 983 }
c4b7a5a9 984
1513873c 985 errno = 0;
c4b7a5a9 986 /* prepare the read size for the next read (if any) */
62e76326 987
c4b7a5a9 988 debug(11, 5) ("httpReadReply: FD %d: len %d.\n", fd, (int)len);
62e76326 989
c4b7a5a9 990 if (flag == COMM_OK && len > 0) {
2afaba07 991 readBuf->appended(len);
5f8252d2 992 reply_bytes_read += len;
447e176b 993#if DELAY_POOLS
2afaba07 994
995 DelayId delayId = entry->mem_obj->mostBytesAllowed();
62e76326 996 delayId.bytesIn(len);
447e176b 997#endif
62e76326 998
999 kb_incr(&statCounter.server.all.kbytes_in, len);
1000 kb_incr(&statCounter.server.http.kbytes_in, len);
62e76326 1001 IOStats.Http.reads++;
1002
1003 for (clen = len - 1, bin = 0; clen; bin++)
1004 clen >>= 1;
1005
1006 IOStats.Http.read_hist[bin]++;
30a4f2a8 1007 }
62e76326 1008
5fa061b8 1009 /* here the RFC says we should ignore whitespace between replies, but we can't as
1010 * doing so breaks HTTP/0.9 replies beginning with witespace, and in addition
1011 * the response splitting countermeasures is extremely likely to trigger on this,
1012 * not allowing connection reuse in the first place.
1013 */
1014#if DONT_DO_THIS
1a98175f 1015 if (!flags.headers_parsed && flag == COMM_OK && len > 0 && fd_table[fd].uses > 1) {
5fa061b8 1016 /* Skip whitespace between replies */
62e76326 1017
e4755e29 1018 while (len > 0 && xisspace(*buf))
62e76326 1019 xmemmove(buf, buf + 1, len--);
1020
1021 if (len == 0) {
1022 /* Continue to read... */
21b92762 1023 /* Timeout NOT increased. This whitespace was from previous reply */
f61f0107 1024 flags.do_next_read = 1;
5f8252d2 1025 maybeReadVirginBody();
62e76326 1026 return;
1027 }
5ede6c8f 1028 }
62e76326 1029
5fa061b8 1030#endif
1031
c4b7a5a9 1032 if (flag != COMM_OK || len < 0) {
62e76326 1033 debug(50, 2) ("httpReadReply: FD %d: read failure: %s.\n",
1034 fd, xstrerror());
1035
1036 if (ignoreErrno(errno)) {
f61f0107 1037 flags.do_next_read = 1;
6cae5db1 1038 } else {
62e76326 1039 ErrorState *err;
2cc81f1f 1040 err = errorCon(ERR_READ_ERROR, HTTP_BAD_GATEWAY, fwd->request);
62e76326 1041 err->xerrno = errno;
b6b6f466 1042 fwd->fail(err);
f61f0107 1043 flags.do_next_read = 0;
62e76326 1044 comm_close(fd);
62e76326 1045 }
2afaba07 1046 } else if (flag == COMM_OK && len == 0 && !flags.headers_parsed) {
2cc81f1f 1047 fwd->fail(errorCon(ERR_ZERO_SIZE_OBJECT, HTTP_BAD_GATEWAY, fwd->request));
62e76326 1048 eof = 1;
f61f0107 1049 flags.do_next_read = 0;
62e76326 1050 comm_close(fd);
c4b7a5a9 1051 } else if (flag == COMM_OK && len == 0) {
62e76326 1052 /* Connection closed; retrieval done. */
1053 eof = 1;
1054
2cca9b7d 1055 if (!flags.headers_parsed) {
62e76326 1056 /*
3f7d66c7 1057 * When we called processReplyHeader() before, we
1a98175f 1058 * didn't find the end of headers, but now we are
1059 * definately at EOF, so we want to process the reply
1060 * headers.
62e76326 1061 */
fc68f6b1 1062 PROF_start(HttpStateData_processReplyHeader);
2afaba07 1063 processReplyHeader();
fc68f6b1 1064 PROF_stop(HttpStateData_processReplyHeader);
1065 } else if (getReply()->sline.status == HTTP_INVALID_HEADER && HttpVersion(0,9) != getReply()->sline.version) {
2cc81f1f 1066 fwd->fail(errorCon(ERR_INVALID_RESP, HTTP_BAD_GATEWAY, fwd->request));
f61f0107 1067 flags.do_next_read = 0;
47ac2ebe 1068 } else {
4eb368f9 1069 if (entry->mem_obj->getReply()->sline.status == HTTP_HEADER_TOO_LARGE) {
3900307b 1070 entry->reset();
2cc81f1f 1071 fwd->fail( errorCon(ERR_TOO_BIG, HTTP_BAD_GATEWAY, fwd->request));
b6b6f466 1072 fwd->dontRetry(true);
2afaba07 1073 flags.do_next_read = 0;
1074 comm_close(fd);
4eb368f9 1075 } else {
5f8252d2 1076 serverComplete();
4eb368f9 1077 }
62e76326 1078 }
090089c4 1079 } else {
1a98175f 1080 if (!flags.headers_parsed) {
fc68f6b1 1081 PROF_start(HttpStateData_processReplyHeader);
2afaba07 1082 processReplyHeader();
fc68f6b1 1083 PROF_stop(HttpStateData_processReplyHeader);
62e76326 1084
1a98175f 1085 if (flags.headers_parsed) {
42f79b17 1086 bool fail = reply == NULL;
47ac2ebe 1087
42f79b17 1088 if (!fail) {
1089 http_status s = getReply()->sline.status;
1090 HttpVersion httpver = getReply()->sline.version;
1091 fail = s == HTTP_INVALID_HEADER && httpver != HttpVersion(0,9);
1092 }
1093
1094 if (fail) {
3900307b 1095 entry->reset();
2cc81f1f 1096 fwd->fail( errorCon(ERR_INVALID_RESP, HTTP_BAD_GATEWAY, fwd->request));
47ac2ebe 1097 comm_close(fd);
1098 return;
1099 }
1100
2afaba07 1101 }
1102 }
1103
1104 PROF_start(HttpStateData_processReplyBody);
1105 processReplyBody();
1106 PROF_stop(HttpStateData_processReplyBody);
1107 }
1108}
1109
1110/*
1111 * Call this when there is data from the origin server
1112 * which should be sent to either StoreEntry, or to ICAP...
1113 */
1114void
5f8252d2 1115HttpStateData::writeReplyBody()
2afaba07 1116{
5f8252d2 1117 const char *data = readBuf->content();
1118 int len = readBuf->contentSize();
62e76326 1119
5f8252d2 1120#if ICAP_CLIENT
fc68f6b1 1121
5f8252d2 1122 if (virginBodyDestination != NULL) {
1123 const size_t putSize = virginBodyDestination->putMoreData(data, len);
1124 readBuf->consume(putSize);
1125 return;
1126 }
fc68f6b1 1127
5f8252d2 1128 // Even if we are done with sending the virgin body to ICAP, we may still
1129 // be waiting for adapted headers. We need them before writing to store.
1130 if (adaptedHeadSource != NULL) {
1131 debugs(11,5, HERE << "need adapted head from " << adaptedHeadSource);
2afaba07 1132 return;
1133 }
fc68f6b1 1134
225644d7 1135#endif
62e76326 1136
2afaba07 1137 entry->write (StoreIOBuffer(len, currentOffset, (char*)data));
fc68f6b1 1138
5f8252d2 1139 readBuf->consume(len);
fc68f6b1 1140
2afaba07 1141 currentOffset += len;
e6ccf245 1142}
1143
2afaba07 1144/*
1145 * processReplyBody has two purposes:
1146 * 1 - take the reply body data, if any, and put it into either
1147 * the StoreEntry, or give it over to ICAP.
1148 * 2 - see if we made it to the end of the response (persistent
1149 * connections and such)
1150 */
e6ccf245 1151void
2afaba07 1152HttpStateData::processReplyBody()
e6ccf245 1153{
fc68f6b1 1154
1155 struct IN_ADDR *client_addr = NULL;
1156
1a98175f 1157 if (!flags.headers_parsed) {
f61f0107 1158 flags.do_next_read = 1;
5f8252d2 1159 maybeReadVirginBody();
62e76326 1160 return;
528b2c61 1161 }
62e76326 1162
2afaba07 1163#if ICAP_CLIENT
1164 if (icapAccessCheckPending)
1165 return;
fc68f6b1 1166
2afaba07 1167#endif
62e76326 1168
2afaba07 1169 /*
1170 * At this point the reply headers have been parsed and consumed.
1171 * That means header content has been removed from readBuf and
1172 * it contains only body data.
1173 */
5f8252d2 1174 writeReplyBody();
528b2c61 1175
e6ccf245 1176 if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
62e76326 1177 /*
2afaba07 1178 * the above writeReplyBody() call could ABORT this entry,
62e76326 1179 * in that case, the server FD should already be closed.
1180 * there's nothing for us to do.
1181 */
1182 (void) 0;
1183 } else
1184 switch (persistentConnStatus()) {
1185
1186 case INCOMPLETE_MSG:
2afaba07 1187 debug(11,5)("processReplyBody: INCOMPLETE_MSG\n");
21b92762 1188 /* Wait for more data or EOF condition */
1189
1190 if (flags.keepalive_broken) {
1191 commSetTimeout(fd, 10, NULL, NULL);
1192 } else {
1193 commSetTimeout(fd, Config.Timeout.read, NULL, NULL);
1194 }
1195
f61f0107 1196 flags.do_next_read = 1;
62e76326 1197 break;
1198
1199 case COMPLETE_PERSISTENT_MSG:
2afaba07 1200 debug(11,5)("processReplyBody: COMPLETE_PERSISTENT_MSG\n");
62e76326 1201 /* yes we have to clear all these! */
62e76326 1202 commSetTimeout(fd, -1, NULL, NULL);
f61f0107 1203 flags.do_next_read = 0;
62e76326 1204
1205 comm_remove_close_handler(fd, httpStateFree, this);
b6b6f466 1206 fwd->unregister(fd);
fc68f6b1 1207#if LINUX_TPROXY
1208
1209 if (orig_request->flags.tproxy)
1210 client_addr = &orig_request->client_addr;
1211
1212#endif
bd0723ad 1213
1214 if (_peer) {
1215 if (_peer->options.originserver)
fc68f6b1 1216 fwd->pconnPush(fd, _peer->name, orig_request->port, orig_request->host, client_addr);
bd0723ad 1217 else
fc68f6b1 1218 fwd->pconnPush(fd, _peer->name, _peer->http_port, NULL, client_addr);
bd0723ad 1219 } else {
fc68f6b1 1220 fwd->pconnPush(fd, request->host, request->port, NULL, client_addr);
bd0723ad 1221 }
1222
62e76326 1223 fd = -1;
2afaba07 1224
5f8252d2 1225 serverComplete();
62e76326 1226 return;
1227
1228 case COMPLETE_NONPERSISTENT_MSG:
2afaba07 1229 debug(11,5)("processReplyBody: COMPLETE_NONPERSISTENT_MSG\n");
5f8252d2 1230 serverComplete();
62e76326 1231 return;
1232 }
1233
5f8252d2 1234 maybeReadVirginBody();
c4b7a5a9 1235}
1236
1237void
5f8252d2 1238HttpStateData::maybeReadVirginBody()
c4b7a5a9 1239{
2afaba07 1240 int read_sz = readBuf->spaceSize();
2afaba07 1241
5f8252d2 1242#if ICAP_CLIENT
1243#if RE_ENABLE_THIS_IF_NEEDED_OR_DELETE
1244 // This code is not broken, but is probably not needed because we
1245 // probably can read more than will fit into the BodyPipe buffer.
fc68f6b1 1246
5f8252d2 1247 if (virginBodyDestination != NULL) {
2afaba07 1248 /*
5f8252d2 1249 * BodyPipe buffer has a finite size limit. We
2afaba07 1250 * should not read more data from the network than will fit
1251 * into the pipe buffer. If totally full, don't register
1252 * the read handler at all. The ICAP side will call our
1253 * icapSpaceAvailable() method when it has free space again.
1254 */
5f8252d2 1255 int icap_space = virginBodyDestination->buf().potentialSpaceSize();
2afaba07 1256
1257 debugs(11,9, "HttpStateData may read up to min(" << icap_space <<
1258 ", " << read_sz << ") bytes");
1259
1260 if (icap_space < read_sz)
1261 read_sz = icap_space;
1262 }
fc68f6b1 1263
5f8252d2 1264#endif
2afaba07 1265#endif
1266
5f8252d2 1267 debugs(11,9, HERE << (flags.do_next_read ? "may" : "wont") <<
fc68f6b1 1268 " read up to " << read_sz << " bytes from FD " << fd);
2afaba07 1269
1270 /*
1271 * why <2? Because delayAwareRead() won't actually read if
1272 * you ask it to read 1 byte. The delayed read request
1273 * just gets re-queued until the client side drains, then
1274 * the I/O thread hangs. Better to not register any read
1275 * handler until we get a notification from someone that
1276 * its okay to read again.
1277 */
1278 if (read_sz < 2)
1279 return;
1280
f61f0107 1281 if (flags.do_next_read) {
1282 flags.do_next_read = 0;
e5ee81f0 1283 entry->delayAwareRead(fd, readBuf->space(), read_sz, ReadReplyWrapper, this);
528b2c61 1284 }
090089c4 1285}
1286
2afaba07 1287/*
1288 * This will be called when request write is complete.
1289 */
d576a6a6 1290void
2b663917 1291HttpStateData::SendComplete(int fd, char *bufnotused, size_t size, comm_err_t errflag, int xerrno, void *data)
090089c4 1292{
e6ccf245 1293 HttpStateData *httpState = static_cast<HttpStateData *>(data);
a3d5953d 1294 debug(11, 5) ("httpSendComplete: FD %d: size %d: errflag %d.\n",
62e76326 1295 fd, (int) size, errflag);
bc87dc25 1296#if URL_CHECKSUM_DEBUG
62e76326 1297
528b2c61 1298 entry->mem_obj->checkUrlChecksum();
bc87dc25 1299#endif
62e76326 1300
ee1679df 1301 if (size > 0) {
62e76326 1302 fd_bytes(fd, size, FD_WRITE);
1303 kb_incr(&statCounter.server.all.kbytes_out, size);
1304 kb_incr(&statCounter.server.http.kbytes_out, size);
ee1679df 1305 }
62e76326 1306
ea3a2a69 1307 if (errflag == COMM_ERR_CLOSING)
62e76326 1308 return;
1309
090089c4 1310 if (errflag) {
6cae5db1 1311 ErrorState *err;
2cc81f1f 1312 err = errorCon(ERR_WRITE_ERROR, HTTP_BAD_GATEWAY, httpState->fwd->request);
2b663917 1313 err->xerrno = xerrno;
b6b6f466 1314 httpState->fwd->fail(err);
62e76326 1315 comm_close(fd);
1316 return;
090089c4 1317 }
72b63f06 1318
2afaba07 1319 /*
1320 * Set the read timeout here because it hasn't been set yet.
1321 * We only set the read timeout after the request has been
1322 * fully written to the server-side. If we start the timeout
1323 * after connection establishment, then we are likely to hit
1324 * the timeout for POST/PUT requests that have very large
1325 * request bodies.
1326 */
1327 commSetTimeout(fd, Config.Timeout.read, httpTimeout, httpState);
1328
72b63f06 1329 httpState->flags.request_sent = 1;
090089c4 1330}
1331
5f8252d2 1332// Close the HTTP server connection. Used by serverComplete().
2afaba07 1333void
5f8252d2 1334HttpStateData::closeServer()
2afaba07 1335{
5f8252d2 1336 debugs(11,5, HERE << "closing HTTP server FD " << fd << " this " << this);
fc68f6b1 1337
2afaba07 1338 if (fd >= 0) {
b6b6f466 1339 fwd->unregister(fd);
2afaba07 1340 comm_remove_close_handler(fd, httpStateFree, this);
1341 comm_close(fd);
1342 fd = -1;
1343 }
5f8252d2 1344}
2afaba07 1345
5f8252d2 1346bool
1347HttpStateData::doneWithServer() const
1348{
1349 return fd < 0;
2afaba07 1350}
1351
99edd1c3 1352/*
1353 * build request headers and append them to a given MemBuf
e5ee81f0 1354 * used by buildRequestPrefix()
818c6c9e 1355 * note: initialised the HttpHeader, the caller is responsible for Clean()-ing
99edd1c3 1356 */
e1e72f06 1357void
e5ee81f0 1358HttpStateData::httpBuildRequestHeader(HttpRequest * request,
1359 HttpRequest * orig_request,
1360 StoreEntry * entry,
1361 HttpHeader * hdr_out,
1362 http_state_flags flags)
6bf8443a 1363{
99edd1c3 1364 /* building buffer for complex strings */
5999b776 1365#define BBUF_SZ (MAX_URL+32)
99edd1c3 1366 LOCAL_ARRAY(char, bbuf, BBUF_SZ);
99edd1c3 1367 const HttpHeader *hdr_in = &orig_request->header;
1368 const HttpHeaderEntry *e;
6bccf575 1369 String strFwd;
99edd1c3 1370 HttpHeaderPos pos = HttpHeaderInitPos;
75faaa7a 1371 assert (hdr_out->owner == hoRequest);
99edd1c3 1372 /* append our IMS header */
62e76326 1373
fa3e249f 1374 if (request->lastmod > -1)
a9925b40 1375 hdr_out->putTime(HDR_IF_MODIFIED_SINCE, request->lastmod);
99edd1c3 1376
528b2c61 1377 bool we_do_ranges = decideIfWeDoRanges (orig_request);
1378
a9925b40 1379 String strConnection (hdr_in->getList(HDR_CONNECTION));
62e76326 1380
a9925b40 1381 while ((e = hdr_in->getEntry(&pos)))
62e76326 1382 copyOneHeaderFromClientsideRequestToUpstreamRequest(e, strConnection, request, orig_request, hdr_out, we_do_ranges, flags);
528b2c61 1383
43ae1d95 1384 /* Abstraction break: We should interpret multipart/byterange responses
528b2c61 1385 * into offset-length data, and this works around our inability to do so.
1386 */
62e76326 1387 if (!we_do_ranges && orig_request->multipartRangeRequest()) {
1388 /* don't cache the result */
1389 orig_request->flags.cachable = 0;
1390 /* pretend it's not a range request */
00d77d6b 1391 delete orig_request->range;
62e76326 1392 orig_request->range = NULL;
1393 orig_request->flags.range = 0;
1394 }
528b2c61 1395
99edd1c3 1396 /* append Via */
736cb6aa 1397 if (Config.onoff.via) {
43ae1d95 1398 String strVia;
a9925b40 1399 strVia = hdr_in->getList(HDR_VIA);
62e76326 1400 snprintf(bbuf, BBUF_SZ, "%d.%d %s",
1401 orig_request->http_ver.major,
1402 orig_request->http_ver.minor, ThisCache);
1403 strListAdd(&strVia, bbuf, ',');
a9925b40 1404 hdr_out->putStr(HDR_VIA, strVia.buf());
62e76326 1405 strVia.clean();
736cb6aa 1406 }
62e76326 1407
43ae1d95 1408#if ESI
1409 {
1410 /* Append Surrogate-Capabilities */
a9925b40 1411 String strSurrogate (hdr_in->getList(HDR_SURROGATE_CAPABILITY));
ec43ae0e 1412 snprintf(bbuf, BBUF_SZ, "%s=\"Surrogate/1.0 ESI/1.0\"",
43ae1d95 1413 Config.Accel.surrogate_id);
1414 strListAdd(&strSurrogate, bbuf, ',');
a9925b40 1415 hdr_out->putStr(HDR_SURROGATE_CAPABILITY, strSurrogate.buf());
43ae1d95 1416 }
1417#endif
1418
99edd1c3 1419 /* append X-Forwarded-For */
a9925b40 1420 strFwd = hdr_in->getList(HDR_X_FORWARDED_FOR);
62e76326 1421
6056ae68 1422 if (opt_forwarded_for && orig_request->client_addr.s_addr != no_addr.s_addr)
62e76326 1423 strListAdd(&strFwd, inet_ntoa(orig_request->client_addr), ',');
6056ae68 1424 else
62e76326 1425 strListAdd(&strFwd, "unknown", ',');
1426
a9925b40 1427 hdr_out->putStr(HDR_X_FORWARDED_FOR, strFwd.buf());
62e76326 1428
528b2c61 1429 strFwd.clean();
6bccf575 1430
99edd1c3 1431 /* append Host if not there already */
a9925b40 1432 if (!hdr_out->has(HDR_HOST)) {
62e76326 1433 if (orig_request->peer_domain) {
a9925b40 1434 hdr_out->putStr(HDR_HOST, orig_request->peer_domain);
62e76326 1435 } else if (orig_request->port == urlDefaultPort(orig_request->protocol)) {
1436 /* use port# only if not default */
a9925b40 1437 hdr_out->putStr(HDR_HOST, orig_request->host);
62e76326 1438 } else {
1439 httpHeaderPutStrf(hdr_out, HDR_HOST, "%s:%d",
1440 orig_request->host, (int) orig_request->port);
1441 }
6bf8443a 1442 }
62e76326 1443
c68e9c6b 1444 /* append Authorization if known in URL, not in header and going direct */
a9925b40 1445 if (!hdr_out->has(HDR_AUTHORIZATION)) {
62e76326 1446 if (!request->flags.proxying && *request->login) {
1447 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1448 base64_encode(request->login));
1449 }
c68e9c6b 1450 }
62e76326 1451
c68e9c6b 1452 /* append Proxy-Authorization if configured for peer, and proxying */
c3b33cb7 1453 if (request->flags.proxying && orig_request->peer_login &&
a9925b40 1454 !hdr_out->has(HDR_PROXY_AUTHORIZATION)) {
62e76326 1455 if (*orig_request->peer_login == '*') {
1456 /* Special mode, to pass the username to the upstream cache */
1457 char loginbuf[256];
1458 const char *username = "-";
1459
1460 if (orig_request->auth_user_request)
1461 username = orig_request->auth_user_request->username();
abb929f0 1462 else if (orig_request->extacl_user.size())
1463 username = orig_request->extacl_user.buf();
62e76326 1464
1465 snprintf(loginbuf, sizeof(loginbuf), "%s%s", username, orig_request->peer_login + 1);
1466
1467 httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Basic %s",
1468 base64_encode(loginbuf));
1469 } else if (strcmp(orig_request->peer_login, "PASS") == 0) {
abb929f0 1470 if (orig_request->extacl_user.size() && orig_request->extacl_passwd.size()) {
1471 char loginbuf[256];
1472 snprintf(loginbuf, sizeof(loginbuf), "%s:%s", orig_request->extacl_user.buf(), orig_request->extacl_passwd.buf());
1473 httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Basic %s",
1474 base64_encode(loginbuf));
1475 }
62e76326 1476 } else if (strcmp(orig_request->peer_login, "PROXYPASS") == 0) {
1477 /* Nothing to do */
1478 } else {
1479 httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Basic %s",
1480 base64_encode(orig_request->peer_login));
1481 }
c68e9c6b 1482 }
62e76326 1483
be753325 1484 /* append WWW-Authorization if configured for peer */
1485 if (flags.originpeer && orig_request->peer_login &&
a9925b40 1486 !hdr_out->has(HDR_AUTHORIZATION)) {
62e76326 1487 if (strcmp(orig_request->peer_login, "PASS") == 0) {
1488 /* No credentials to forward.. (should have been done above if available) */
1489 } else if (strcmp(orig_request->peer_login, "PROXYPASS") == 0) {
1490 /* Special mode, convert proxy authentication to WWW authentication
abb929f0 1491 * (also applies to authentication provided by external acl)
62e76326 1492 */
a9925b40 1493 const char *auth = hdr_in->getStr(HDR_PROXY_AUTHORIZATION);
62e76326 1494
1495 if (auth && strncasecmp(auth, "basic ", 6) == 0) {
a9925b40 1496 hdr_out->putStr(HDR_AUTHORIZATION, auth);
abb929f0 1497 } else if (orig_request->extacl_user.size() && orig_request->extacl_passwd.size()) {
1498 char loginbuf[256];
1499 snprintf(loginbuf, sizeof(loginbuf), "%s:%s", orig_request->extacl_user.buf(), orig_request->extacl_passwd.buf());
1500 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1501 base64_encode(loginbuf));
62e76326 1502 }
1503 } else if (*orig_request->peer_login == '*') {
1504 /* Special mode, to pass the username to the upstream cache */
1505 char loginbuf[256];
1506 const char *username = "-";
1507
1508 if (orig_request->auth_user_request)
f5691f9c 1509 username = orig_request->auth_user_request->username();
abb929f0 1510 else if (orig_request->extacl_user.size())
1511 username = orig_request->extacl_user.buf();
62e76326 1512
1513 snprintf(loginbuf, sizeof(loginbuf), "%s%s", username, orig_request->peer_login + 1);
1514
1515 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1516 base64_encode(loginbuf));
1517 } else {
1518 /* Fixed login string */
1519 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1520 base64_encode(orig_request->peer_login));
1521 }
be753325 1522 }
62e76326 1523
abb929f0 1524 /* append Cache-Control, add max-age if not there already */ {
a9925b40 1525 HttpHdrCc *cc = hdr_in->getCc();
62e76326 1526
1527 if (!cc)
1528 cc = httpHdrCcCreate();
1529
1530 if (!EBIT_TEST(cc->mask, CC_MAX_AGE)) {
43ae1d95 1531 const char *url =
3900307b 1532 entry ? entry->url() : urlCanonical(orig_request);
62e76326 1533 httpHdrCcSetMaxAge(cc, getMaxAge(url));
1534
1535 if (request->urlpath.size())
1536 assert(strstr(url, request->urlpath.buf()));
1537 }
1538
ce2d6441 1539 /* Set no-cache if determined needed but not found */
a9925b40 1540 if (orig_request->flags.nocache && !hdr_in->has(HDR_PRAGMA))
ce2d6441 1541 EBIT_SET(cc->mask, CC_NO_CACHE);
1542
1543 /* Enforce sibling relations */
62e76326 1544 if (flags.only_if_cached)
1545 EBIT_SET(cc->mask, CC_ONLY_IF_CACHED);
1546
a9925b40 1547 hdr_out->putCc(cc);
62e76326 1548
1549 httpHdrCcDestroy(cc);
6bf8443a 1550 }
62e76326 1551
99edd1c3 1552 /* maybe append Connection: keep-alive */
b515fc11 1553 if (flags.keepalive) {
62e76326 1554 if (flags.proxying) {
a9925b40 1555 hdr_out->putStr(HDR_PROXY_CONNECTION, "keep-alive");
62e76326 1556 } else {
a9925b40 1557 hdr_out->putStr(HDR_CONNECTION, "keep-alive");
62e76326 1558 }
603a02fd 1559 }
62e76326 1560
a7ad6e4e 1561 /* append Front-End-Https */
1562 if (flags.front_end_https) {
62e76326 1563 if (flags.front_end_https == 1 || request->protocol == PROTO_HTTPS)
a9925b40 1564 hdr_out->putStr(HDR_FRONT_END_HTTPS, "On");
a7ad6e4e 1565 }
1566
6bccf575 1567 /* Now mangle the headers. */
4f56514c 1568 if (Config2.onoff.mangle_request_headers)
5967c0bf 1569 httpHdrMangleList(hdr_out, request, ROR_REQUEST);
62e76326 1570
528b2c61 1571 strConnection.clean();
99edd1c3 1572}
1573
528b2c61 1574void
190154cf 1575copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, String strConnection, HttpRequest * request, HttpRequest * orig_request, HttpHeader * hdr_out, int we_do_ranges, http_state_flags flags)
528b2c61 1576{
1577 debug(11, 5) ("httpBuildRequestHeader: %s: %s\n",
62e76326 1578 e->name.buf(), e->value.buf());
1579
528b2c61 1580 if (!httpRequestHdrAllowed(e, &strConnection)) {
62e76326 1581 debug(11, 2) ("'%s' header denied by anonymize_headers configuration\n",+ e->name.buf());
1582 return;
528b2c61 1583 }
62e76326 1584
528b2c61 1585 switch (e->id) {
62e76326 1586
be753325 1587 case HDR_PROXY_AUTHORIZATION:
62e76326 1588 /* Only pass on proxy authentication to peers for which
1589 * authentication forwarding is explicitly enabled
1590 */
1591
1592 if (flags.proxying && orig_request->peer_login &&
abb929f0 1593 (strcmp(orig_request->peer_login, "PASS") == 0 ||
1594 strcmp(orig_request->peer_login, "PROXYPASS") == 0)) {
eede25e7 1595 hdr_out->addEntry(e->clone());
62e76326 1596 }
1597
1598 break;
1599
be753325 1600 case HDR_AUTHORIZATION:
62e76326 1601 /* Pass on WWW authentication */
1602
1603 if (!flags.originpeer) {
eede25e7 1604 hdr_out->addEntry(e->clone());
62e76326 1605 } else {
1606 /* In accelerators, only forward authentication if enabled
1607 * (see also below for proxy->server authentication)
1608 */
1609
abb929f0 1610 if (orig_request->peer_login &&
1611 (strcmp(orig_request->peer_login, "PASS") == 0 ||
1612 strcmp(orig_request->peer_login, "PROXYPASS") == 0)) {
eede25e7 1613 hdr_out->addEntry(e->clone());
62e76326 1614 }
1615 }
1616
1617 break;
1618
be753325 1619 case HDR_HOST:
62e76326 1620 /*
b883b594 1621 * Normally Squid rewrites the Host: header.
1622 * However, there is one case when we don't: If the URL
62e76326 1623 * went through our redirector and the admin configured
1624 * 'redir_rewrites_host' to be off.
1625 */
1626
b883b594 1627 if (request->flags.redirected && !Config.onoff.redir_rewrites_host)
eede25e7 1628 hdr_out->addEntry(e->clone());
b883b594 1629 else {
1630 /* use port# only if not default */
1631
1632 if (orig_request->port == urlDefaultPort(orig_request->protocol)) {
a9925b40 1633 hdr_out->putStr(HDR_HOST, orig_request->host);
b883b594 1634 } else {
1635 httpHeaderPutStrf(hdr_out, HDR_HOST, "%s:%d",
1636 orig_request->host, (int) orig_request->port);
1637 }
1638 }
62e76326 1639
1640 break;
1641
be753325 1642 case HDR_IF_MODIFIED_SINCE:
62e76326 1643 /* append unless we added our own;
1644 * note: at most one client's ims header can pass through */
b883b594 1645
a9925b40 1646 if (!hdr_out->has(HDR_IF_MODIFIED_SINCE))
eede25e7 1647 hdr_out->addEntry(e->clone());
62e76326 1648
1649 break;
1650
be753325 1651 case HDR_MAX_FORWARDS:
62e76326 1652 if (orig_request->method == METHOD_TRACE) {
eede25e7 1653 const int hops = e->getInt();
62e76326 1654
1655 if (hops > 0)
a9925b40 1656 hdr_out->putInt(HDR_MAX_FORWARDS, hops - 1);
62e76326 1657 }
1658
1659 break;
1660
be753325 1661 case HDR_VIA:
62e76326 1662 /* If Via is disabled then forward any received header as-is */
1663
1664 if (!Config.onoff.via)
eede25e7 1665 hdr_out->addEntry(e->clone());
62e76326 1666
1667 break;
1668
be753325 1669 case HDR_RANGE:
62e76326 1670
be753325 1671 case HDR_IF_RANGE:
62e76326 1672
be753325 1673 case HDR_REQUEST_RANGE:
62e76326 1674 if (!we_do_ranges)
eede25e7 1675 hdr_out->addEntry(e->clone());
62e76326 1676
1677 break;
1678
be753325 1679 case HDR_PROXY_CONNECTION:
62e76326 1680
be753325 1681 case HDR_CONNECTION:
62e76326 1682
be753325 1683 case HDR_X_FORWARDED_FOR:
62e76326 1684
be753325 1685 case HDR_CACHE_CONTROL:
62e76326 1686 /* append these after the loop if needed */
1687 break;
1688
be753325 1689 case HDR_FRONT_END_HTTPS:
62e76326 1690 if (!flags.front_end_https)
eede25e7 1691 hdr_out->addEntry(e->clone());
62e76326 1692
1693 break;
1694
be753325 1695 default:
62e76326 1696 /* pass on all other header fields */
eede25e7 1697 hdr_out->addEntry(e->clone());
528b2c61 1698 }
1699}
1700
e5ee81f0 1701bool
1702HttpStateData::decideIfWeDoRanges (HttpRequest * orig_request)
528b2c61 1703{
e5ee81f0 1704 bool result = true;
62e76326 1705 /* decide if we want to do Ranges ourselves
1706 * and fetch the whole object now)
1707 * We want to handle Ranges ourselves iff
1708 * - we can actually parse client Range specs
1709 * - the specs are expected to be simple enough (e.g. no out-of-order ranges)
1710 * - reply will be cachable
1711 * (If the reply will be uncachable we have to throw it away after
1712 * serving this request, so it is better to forward ranges to
1713 * the server and fetch only the requested content)
1714 */
1715
1716 if (NULL == orig_request->range || !orig_request->flags.cachable
1717 || orig_request->range->offsetLimitExceeded())
e5ee81f0 1718 result = false;
62e76326 1719
1720 debug(11, 8) ("decideIfWeDoRanges: range specs: %p, cachable: %d; we_do_ranges: %d\n",
1721 orig_request->range, orig_request->flags.cachable, result);
1722
1723 return result;
528b2c61 1724}
1725
62e76326 1726/* build request prefix and append it to a given MemBuf;
99edd1c3 1727 * return the length of the prefix */
9bc73deb 1728mb_size_t
e5ee81f0 1729HttpStateData::buildRequestPrefix(HttpRequest * request,
1730 HttpRequest * orig_request,
1731 StoreEntry * entry,
1732 MemBuf * mb,
1733 http_state_flags flags)
99edd1c3 1734{
1735 const int offset = mb->size;
450e0c10 1736 HttpVersion httpver(1, 0);
2fe7eff9 1737 mb->Printf("%s %s HTTP/%d.%d\r\n",
1738 RequestMethodStr[request->method],
1739 request->urlpath.size() ? request->urlpath.buf() : "/",
1740 httpver.major,httpver.minor);
99edd1c3 1741 /* build and pack headers */
1742 {
75faaa7a 1743 HttpHeader hdr(hoRequest);
62e76326 1744 Packer p;
1745 httpBuildRequestHeader(request, orig_request, entry, &hdr, flags);
1746 packerToMemInit(&p, mb);
a9925b40 1747 hdr.packInto(&p);
519e0948 1748 hdr.clean();
62e76326 1749 packerClean(&p);
9d9d144b 1750 }
99edd1c3 1751 /* append header terminator */
2fe7eff9 1752 mb->append(crlf, 2);
99edd1c3 1753 return mb->size - offset;
6bf8443a 1754}
62e76326 1755
090089c4 1756/* This will be called when connect completes. Write request. */
5f8252d2 1757bool
2bb867b5 1758HttpStateData::sendRequest()
090089c4 1759{
99edd1c3 1760 MemBuf mb;
090089c4 1761
5f8252d2 1762 debug(11, 5) ("httpSendRequest: FD %d, request %p, this %p.\n", fd, request, this);
090089c4 1763
2bb867b5 1764 commSetTimeout(fd, Config.Timeout.lifetime, httpTimeout, this);
1765 flags.do_next_read = 1;
5f8252d2 1766 maybeReadVirginBody();
1767
1768 if (orig_request->body_pipe != NULL) {
1769 requestBodySource = orig_request->body_pipe;
fc68f6b1 1770
5f8252d2 1771 if (!requestBodySource->setConsumerIfNotLate(this)) {
1772 debugs(32,3, HERE << "aborting on partially consumed body");
1773 requestBodySource = NULL;
1774 return false;
1775 }
fc68f6b1 1776
5f8252d2 1777 requestSender = HttpStateData::sentRequestBodyWrapper;
1778 debugs(32,3, HERE << "expecting request body on pipe " << requestBodySource);
1779 } else {
1780 assert(!requestBodySource);
1781 requestSender = HttpStateData::SendComplete;
1782 }
54220df8 1783
2bb867b5 1784 if (_peer != NULL) {
1785 if (_peer->options.originserver) {
1786 flags.proxying = 0;
1787 flags.originpeer = 1;
62e76326 1788 } else {
2bb867b5 1789 flags.proxying = 1;
1790 flags.originpeer = 0;
62e76326 1791 }
be753325 1792 } else {
2bb867b5 1793 flags.proxying = 0;
1794 flags.originpeer = 0;
be753325 1795 }
62e76326 1796
efb9218c 1797 /*
99edd1c3 1798 * Is keep-alive okay for all request methods?
efb9218c 1799 */
efd900cb 1800 if (!Config.onoff.server_pconns)
2bb867b5 1801 flags.keepalive = 0;
1802 else if (_peer == NULL)
1803 flags.keepalive = 1;
1804 else if (_peer->stats.n_keepalives_sent < 10)
1805 flags.keepalive = 1;
1806 else if ((double) _peer->stats.n_keepalives_recv /
1807 (double) _peer->stats.n_keepalives_sent > 0.50)
1808 flags.keepalive = 1;
1809
1810 if (_peer) {
1811 if (neighborType(_peer, request) == PEER_SIBLING &&
1812 !_peer->options.allow_miss)
1813 flags.only_if_cached = 1;
1814
1815 flags.front_end_https = _peer->front_end_https;
a7ad6e4e 1816 }
62e76326 1817
2fe7eff9 1818 mb.init();
e5ee81f0 1819 buildRequestPrefix(request, orig_request, entry, &mb, flags);
21b92762 1820 debug(11, 6) ("httpSendRequest: FD %d:\n%s\n", fd, mb.buf);
5f8252d2 1821 comm_write_mbuf(fd, &mb, requestSender, this);
1822
1823 return true;
090089c4 1824}
b6a2f15e 1825
910169e5 1826void
b6b6f466 1827httpStart(FwdState *fwd)
603a02fd 1828{
910169e5 1829 debug(11, 3) ("httpStart: \"%s %s\"\n",
a3d50c30 1830 RequestMethodStr[fwd->request->method],
3900307b 1831 fwd->entry->url());
a3d50c30 1832 HttpStateData *httpState = new HttpStateData(fwd);
62e76326 1833
5f8252d2 1834 if (!httpState->sendRequest()) {
1835 debug(11, 3) ("httpStart: aborted");
1836 delete httpState;
1837 return;
1838 }
62e76326 1839
5f8252d2 1840 statCounter.server.all.requests++;
83704487 1841 statCounter.server.http.requests++;
62e76326 1842
b6a2f15e 1843 /*
1844 * We used to set the read timeout here, but not any more.
1845 * Now its set in httpSendComplete() after the full request,
1846 * including request body, has been written to the server.
1847 */
090089c4 1848}
1849
2bb867b5 1850void
5f8252d2 1851HttpStateData::doneSendingRequestBody()
2bb867b5 1852{
4fb35c3c 1853 ACLChecklist ch;
5f8252d2 1854 debugs(11,5, HERE << "doneSendingRequestBody: FD " << fd);
6dd9f4bd 1855 ch.request = HTTPMSGLOCK(request);
506768d9 1856
1857 if (Config.accessList.brokenPosts)
1858 ch.accessList = cbdataReference(Config.accessList.brokenPosts);
62e76326 1859
108d65b2 1860 /* cbdataReferenceDone() happens in either fastCheck() or ~ACLCheckList */
1861
94439e4e 1862 if (!Config.accessList.brokenPosts) {
5f8252d2 1863 debug(11, 5) ("doneSendingRequestBody: No brokenPosts list\n");
2b663917 1864 HttpStateData::SendComplete(fd, NULL, 0, COMM_OK, 0, this);
b448c119 1865 } else if (!ch.fastCheck()) {
5f8252d2 1866 debug(11, 5) ("doneSendingRequestBody: didn't match brokenPosts\n");
2b663917 1867 HttpStateData::SendComplete(fd, NULL, 0, COMM_OK, 0, this);
94439e4e 1868 } else {
5f8252d2 1869 debug(11, 2) ("doneSendingRequestBody: matched brokenPosts\n");
2b663917 1870 comm_write(fd, "\r\n", 2, HttpStateData::SendComplete, this, NULL);
54220df8 1871 }
94439e4e 1872}
1873
5f8252d2 1874// more origin request body data is available
2bb867b5 1875void
5f8252d2 1876HttpStateData::handleMoreRequestBodyAvailable()
2bb867b5 1877{
2bb867b5 1878 if (eof || fd < 0) {
5f8252d2 1879 // XXX: we should check this condition in other callbacks then!
1880 // TODO: Check whether this can actually happen: We should unsubscribe
1881 // as a body consumer when the above condition(s) are detected.
2bb867b5 1882 debugs(11, 1, HERE << "Transaction aborted while reading HTTP body");
2bb867b5 1883 return;
1884 }
62e76326 1885
5f8252d2 1886 assert(requestBodySource != NULL);
fc68f6b1 1887
5f8252d2 1888 if (requestBodySource->buf().hasContent()) {
1889 // XXX: why does not this trigger a debug message on every request?
fc68f6b1 1890
2bb867b5 1891 if (flags.headers_parsed && !flags.abuse_detected) {
1892 flags.abuse_detected = 1;
5f8252d2 1893 debug(11, 1) ("http handleMoreRequestBodyAvailable: Likely proxy abuse detected '%s' -> '%s'\n",
2bb867b5 1894 inet_ntoa(orig_request->client_addr),
3900307b 1895 entry->url());
21b92762 1896
2bb867b5 1897 if (getReply()->sline.status == HTTP_INVALID_HEADER) {
2bb867b5 1898 comm_close(fd);
21b92762 1899 return;
1900 }
1901 }
b6a2f15e 1902 }
5f8252d2 1903
1904 HttpStateData::handleMoreRequestBodyAvailable();
376bb137 1905}
1906
5f8252d2 1907// premature end of the request body
2bb867b5 1908void
5f8252d2 1909HttpStateData::handleRequestBodyProducerAborted()
376bb137 1910{
5f8252d2 1911 ServerStateData::handleRequestBodyProducerAborted();
1912 // XXX: SendComplete(COMM_ERR_CLOSING) does little. Is it enough?
1913 SendComplete(fd, NULL, 0, COMM_ERR_CLOSING, 0, this);
2bb867b5 1914}
1915
5f8252d2 1916// called when we wrote request headers(!) or a part of the body
2bb867b5 1917void
5f8252d2 1918HttpStateData::sentRequestBody(int fd, size_t size, comm_err_t errflag)
2bb867b5 1919{
5f8252d2 1920 if (size > 0)
62e76326 1921 kb_incr(&statCounter.server.http.kbytes_out, size);
fc68f6b1 1922
5f8252d2 1923 ServerStateData::sentRequestBody(fd, size, errflag);
1924}
3b299123 1925
5f8252d2 1926// Quickly abort the transaction
1927// TODO: destruction should be sufficient as the destructor should cleanup,
1928// including canceling close handlers
1929void
1930HttpStateData::abortTransaction(const char *reason)
1931{
1932 debugs(11,5, HERE << "aborting transaction for " << reason <<
1933 "; FD " << fd << ", this " << this);
fc68f6b1 1934
5f8252d2 1935 if (fd >= 0)
62e76326 1936 comm_close(fd);
5f8252d2 1937 else
1938 delete this;
54220df8 1939}
ccf44862 1940
1941void
450e0c10 1942httpBuildVersion(HttpVersion * version, unsigned int major, unsigned int minor)
110eb4e5 1943{
1944 version->major = major;
1945 version->minor = minor;
ccf44862 1946}
2afaba07 1947
1948#if ICAP_CLIENT
1949
1950static void
1951icapAclCheckDoneWrapper(ICAPServiceRep::Pointer service, void *data)
1952{
1953 HttpStateData *http = (HttpStateData *)data;
1954 http->icapAclCheckDone(service);
1955}
1956
1957void
1958HttpStateData::icapAclCheckDone(ICAPServiceRep::Pointer service)
1959{
1960 icapAccessCheckPending = false;
1961
5f8252d2 1962 const bool startedIcap = startIcap(service, orig_request);
c99de607 1963
1964 if (!startedIcap && (!service || service->bypass)) {
1965 // handle ICAP start failure when no service was selected
1966 // or where the selected service was optional
db237875 1967 entry->replaceHttpReply(reply);
2afaba07 1968
2afaba07 1969 haveParsedReplyHeaders();
1970 processReplyBody();
1971
1972 if (eof == 1)
5f8252d2 1973 serverComplete();
2afaba07 1974
1975 return;
1976 }
1977
c99de607 1978 if (!startedIcap) {
1979 // handle start failure for an essential ICAP service
2cc81f1f 1980 ErrorState *err = errorCon(ERR_ICAP_FAILURE, HTTP_INTERNAL_SERVER_ERROR, orig_request);
2afaba07 1981 err->xerrno = errno;
2afaba07 1982 errorAppendEntry(entry, err);
1983 comm_close(fd);
1984 return;
1985 }
1986
2afaba07 1987 processReplyBody();
1988}
1989
2afaba07 1990#endif