]> git.ipfire.org Git - thirdparty/squid.git/blame - src/http.cc
Fix for --enable-cpu-profiling mode. Do not change PROF_start() arg.
[thirdparty/squid.git] / src / http.cc
CommitLineData
da2b3a17 1
30a4f2a8 2/*
d88e3c49 3 * $Id: http.cc,v 1.514 2007/04/20 23:53:41 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
97 url = storeUrl(entry);
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;
9fb13bb6 185 debug(11, 4) ("httpTimeout: FD %d: '%s'\n", fd, storeUrl(entry));
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 */
361 storeTimestampsSet(entry);
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:
62e76326 548 return 0;
549
c54e9052 550 default: /* Unknown status code */
924f73bc 551 debug (11,0)("HttpStateData::cacheableReply: unknown http status code in reply\n");
62e76326 552
553 return 0;
554
555 /* NOTREACHED */
556 break;
c54e9052 557 }
62e76326 558
79d39a72 559 /* NOTREACHED */
c54e9052 560}
090089c4 561
f66a9ef4 562/*
563 * For Vary, store the relevant request headers as
564 * virtual headers in the reply
565 * Returns false if the variance cannot be stored
566 */
567const char *
190154cf 568httpMakeVaryMark(HttpRequest * request, HttpReply const * reply)
f66a9ef4 569{
f66a9ef4 570 String vary, hdr;
571 const char *pos = NULL;
572 const char *item;
573 const char *value;
574 int ilen;
528b2c61 575 static String vstr;
f66a9ef4 576
528b2c61 577 vstr.clean();
a9925b40 578 vary = reply->header.getList(HDR_VARY);
62e76326 579
f66a9ef4 580 while (strListGetItem(&vary, ',', &item, &ilen, &pos)) {
62e76326 581 char *name = (char *)xmalloc(ilen + 1);
582 xstrncpy(name, item, ilen + 1);
583 Tolower(name);
9776e3cc 584
585 if (strcmp(name, "*") == 0) {
586 /* Can not handle "Vary: *" withtout ETag support */
587 safe_free(name);
588 vstr.clean();
589 break;
590 }
591
62e76326 592 strListAdd(&vstr, name, ',');
a9925b40 593 hdr = request->header.getByName(name);
62e76326 594 safe_free(name);
595 value = hdr.buf();
596
597 if (value) {
598 value = rfc1738_escape_part(value);
599 vstr.append("=\"", 2);
600 vstr.append(value);
601 vstr.append("\"", 1);
602 }
603
604 hdr.clean();
f66a9ef4 605 }
62e76326 606
528b2c61 607 vary.clean();
f66a9ef4 608#if X_ACCELERATOR_VARY
62e76326 609
aa38be4a 610 pos = NULL;
a9925b40 611 vary = reply->header.getList(HDR_X_ACCELERATOR_VARY);
62e76326 612
f66a9ef4 613 while (strListGetItem(&vary, ',', &item, &ilen, &pos)) {
62e76326 614 char *name = (char *)xmalloc(ilen + 1);
615 xstrncpy(name, item, ilen + 1);
616 Tolower(name);
617 strListAdd(&vstr, name, ',');
a9925b40 618 hdr = request->header.getByName(name);
62e76326 619 safe_free(name);
620 value = hdr.buf();
621
622 if (value) {
623 value = rfc1738_escape_part(value);
624 vstr.append("=\"", 2);
625 vstr.append(value);
626 vstr.append("\"", 1);
627 }
628
629 hdr.clean();
f66a9ef4 630 }
62e76326 631
528b2c61 632 vary.clean();
f66a9ef4 633#endif
62e76326 634
528b2c61 635 debug(11, 3) ("httpMakeVaryMark: %s\n", vstr.buf());
636 return vstr.buf();
f66a9ef4 637}
638
4eb368f9 639void
640HttpStateData::failReply(HttpReply *reply, http_status const & status)
641{
642 reply->sline.version = HttpVersion(1, 0);
643 reply->sline.status = status;
db237875 644 entry->replaceHttpReply(reply);
4eb368f9 645
646 if (eof == 1) {
5f8252d2 647 serverComplete();
4eb368f9 648 }
649}
650
2afaba07 651void
652HttpStateData::keepaliveAccounting(HttpReply *reply)
653{
654 if (flags.keepalive)
655 if (_peer)
656 _peer->stats.n_keepalives_sent++;
657
658 if (reply->keep_alive) {
659 if (_peer)
660 _peer->stats.n_keepalives_recv++;
661
662 if (Config.onoff.detect_broken_server_pconns && reply->bodySize(request->method) == -1) {
663 debug(11, 1) ("keepaliveAccounting: Impossible keep-alive header from '%s'\n", storeUrl(entry));
664 // debug(11, 2) ("GOT HTTP REPLY HDR:\n---------\n%s\n----------\n", readBuf->content());
665 flags.keepalive_broken = 1;
666 }
667 }
668}
669
670void
671HttpStateData::checkDateSkew(HttpReply *reply)
672{
673 if (reply->date > -1 && !_peer) {
674 int skew = abs((int)(reply->date - squid_curtime));
675
676 if (skew > 86400)
677 debug(11, 3) ("%s's clock is skewed by %d seconds!\n",
678 request->host, skew);
679 }
680}
681
682/*
4eb368f9 683 * This creates the error page itself.. its likely
684 * that the forward ported reply header max size patch
685 * generates non http conformant error pages - in which
686 * case the errors where should be 'BAD_GATEWAY' etc
687 */
b8d8561b 688void
2afaba07 689HttpStateData::processReplyHeader()
f5558c95 690{
528b2c61 691 /* Creates a blank header. If this routine is made incremental, this will
692 * not do
693 */
4a56ee8d 694 HttpReply *newrep = new HttpReply;
82384411 695 Ctx ctx = ctx_enter(entry->mem_obj->url);
2afaba07 696 debug(11, 3) ("processReplyHeader: key '%s'\n", entry->getMD5Text());
62e76326 697
1a98175f 698 assert(!flags.headers_parsed);
62e76326 699
2afaba07 700 http_status error = HTTP_STATUS_NONE;
62e76326 701
4a56ee8d 702 const bool parsed = newrep->parse(readBuf, eof, &error);
62e76326 703
2afaba07 704 if (!parsed && error > 0) { // unrecoverable parsing error
705 debugs(11, 3, "processReplyHeader: Non-HTTP-compliant header: '" << readBuf->content() << "'");
1a98175f 706 flags.headers_parsed = 1;
2afaba07 707 // negated result yields http_status
4a56ee8d 708 failReply (newrep, error);
82384411 709 ctx_exit(ctx);
4eb368f9 710 return;
711 }
62e76326 712
2afaba07 713 if (!parsed) { // need more data
714 assert(!error);
715 assert(!eof);
4a56ee8d 716 delete newrep;
82384411 717 ctx_exit(ctx);
62e76326 718 return;
f5558c95 719 }
62e76326 720
6dd9f4bd 721 reply = HTTPMSGLOCK(newrep);
4a56ee8d 722
9bc73deb 723 debug(11, 9) ("GOT HTTP REPLY HDR:\n---------\n%s\n----------\n",
2afaba07 724 readBuf->content());
4eb368f9 725
5f8252d2 726 header_bytes_read = headersEnd(readBuf->content(), readBuf->contentSize());
727 readBuf->consume(header_bytes_read);
4a56ee8d 728
6965ab28 729 flags.headers_parsed = 1;
730
2afaba07 731 keepaliveAccounting(reply);
47ac2ebe 732
2afaba07 733 checkDateSkew(reply);
47ac2ebe 734
43ae1d95 735 processSurrogateControl (reply);
528b2c61 736
737 /* TODO: IF the reply is a 1.0 reply, AND it has a Connection: Header
738 * Parse the header and remove all referenced headers
739 */
740
2afaba07 741#if ICAP_CLIENT
742
ab7ac359 743 if (TheICAPConfig.onoff) {
2afaba07 744 ICAPAccessCheck *icap_access_check =
745 new ICAPAccessCheck(ICAP::methodRespmod, ICAP::pointPreCache, request, reply, icapAclCheckDoneWrapper, this);
746
747 icapAccessCheckPending = true;
748 icap_access_check->check(); // will eventually delete self
749 ctx_exit(ctx);
750 return;
751 }
ab7ac359 752
2afaba07 753#endif
754
db237875 755 entry->replaceHttpReply(reply);
2afaba07 756
2afaba07 757 haveParsedReplyHeaders();
758
759 if (eof == 1) {
5f8252d2 760 serverComplete();
2afaba07 761 }
762
763 ctx_exit(ctx);
764}
765
5f8252d2 766// Called when we parsed (and possibly adapted) the headers but
767// had not starting storing (a.k.a., sending) the body yet.
2afaba07 768void
769HttpStateData::haveParsedReplyHeaders()
770{
771 Ctx ctx = ctx_enter(entry->mem_obj->url);
772
773 if (getReply()->sline.status == HTTP_PARTIAL_CONTENT &&
774 getReply()->content_range)
775 currentOffset = getReply()->content_range->spec.offset;
62e76326 776
9bc73deb 777 storeTimestampsSet(entry);
62e76326 778
9bc73deb 779 /* Check if object is cacheable or not based on reply code */
2afaba07 780 debug(11, 3) ("haveParsedReplyHeaders: HTTP CODE: %d\n", getReply()->sline.status);
62e76326 781
9bc73deb 782 if (neighbors_do_private_keys)
2afaba07 783 httpMaybeRemovePublic(entry, getReply()->sline.status);
e6ccf245 784
a9925b40 785 if (getReply()->header.has(HDR_VARY)
f66a9ef4 786#if X_ACCELERATOR_VARY
a9925b40 787 || getReply()->header.has(HDR_X_ACCELERATOR_VARY)
f66a9ef4 788#endif
4b44c907 789 ) {
2afaba07 790 const char *vary = httpMakeVaryMark(orig_request, getReply());
4b44c907 791
792 if (!vary) {
5ed72359 793 entry->makePrivate();
4b44c907 794 goto no_cache;
795
62e76326 796 }
797
4b44c907 798 entry->mem_obj->vary_headers = xstrdup(vary);
799 }
800
2afaba07 801#if WIP_FWD_LOG
802 fwdStatus(fwd, s);
803
804#endif
805 /*
806 * If its not a reply that we will re-forward, then
807 * allow the client to get it.
808 */
b6b6f466 809 if (!fwd->reforwardableStatus(getReply()->sline.status))
2afaba07 810 EBIT_CLR(entry->flags, ENTRY_FWD_HDR_WAIT);
811
4b44c907 812 switch (cacheableReply()) {
813
814 case 1:
5ed72359 815 entry->makePublic();
62e76326 816 break;
817
9bc73deb 818 case 0:
5ed72359 819 entry->makePrivate();
62e76326 820 break;
821
9bc73deb 822 case -1:
4b44c907 823
824 if (Config.negativeTtl > 0)
5ed72359 825 entry->cacheNegatively();
4b44c907 826 else
5ed72359 827 entry->makePrivate();
4b44c907 828
62e76326 829 break;
830
9bc73deb 831 default:
62e76326 832 assert(0);
4b44c907 833
62e76326 834 break;
9bc73deb 835 }
62e76326 836
4b44c907 837no_cache:
838
2afaba07 839 if (!ignoreCacheControl && getReply()->cache_control) {
840 if (EBIT_TEST(getReply()->cache_control->mask, CC_PROXY_REVALIDATE))
62e76326 841 EBIT_SET(entry->flags, ENTRY_REVALIDATE);
2afaba07 842 else if (EBIT_TEST(getReply()->cache_control->mask, CC_MUST_REVALIDATE))
62e76326 843 EBIT_SET(entry->flags, ENTRY_REVALIDATE);
9bc73deb 844 }
62e76326 845
c3609322 846#if HEADERS_LOG
2afaba07 847 headersLog(1, 0, request->method, getReply());
fc68f6b1 848
c3609322 849#endif
5f8252d2 850
851 ctx_exit(ctx);
f5558c95 852}
853
528b2c61 854HttpStateData::ConnectionStatus
855HttpStateData::statusIfComplete() const
603a02fd 856{
2afaba07 857 HttpReply const *rep = getReply();
528b2c61 858 /* If the reply wants to close the connection, it takes precedence */
62e76326 859
2afaba07 860 if (httpHeaderHasConnDir(&rep->header, "close"))
62e76326 861 return COMPLETE_NONPERSISTENT_MSG;
862
528b2c61 863 /* If we didn't send a keep-alive request header, then this
978e455f 864 * can not be a persistent connection.
865 */
528b2c61 866 if (!flags.keepalive)
62e76326 867 return COMPLETE_NONPERSISTENT_MSG;
868
72b63f06 869 /*
870 * If we haven't sent the whole request then this can not be a persistent
871 * connection.
872 */
873 if (!flags.request_sent) {
2afdbf48 874 debug(11, 1) ("statusIfComplete: Request not yet fully sent \"%s %s\"\n",
72b63f06 875 RequestMethodStr[orig_request->method],
876 storeUrl(entry));
877 return COMPLETE_NONPERSISTENT_MSG;
878 }
879
9f5a2895 880 /*
881 * What does the reply have to say about keep-alive?
882 */
b6a2f15e 883 /*
884 * XXX BUG?
885 * If the origin server (HTTP/1.0) does not send a keep-alive
886 * header, but keeps the connection open anyway, what happens?
887 * We'll return here and http.c waits for an EOF before changing
888 * store_status to STORE_OK. Combine this with ENTRY_FWD_HDR_WAIT
889 * and an error status code, and we might have to wait until
890 * the server times out the socket.
891 */
2afaba07 892 if (!rep->keep_alive)
528b2c61 893 return COMPLETE_NONPERSISTENT_MSG;
62e76326 894
528b2c61 895 return COMPLETE_PERSISTENT_MSG;
896}
897
898HttpStateData::ConnectionStatus
899HttpStateData::persistentConnStatus() const
900{
2afaba07 901 debug(11, 3) ("persistentConnStatus: FD %d\n", fd);
2afaba07 902 debug(11, 5) ("persistentConnStatus: content_length=%d\n",
62e76326 903 reply->content_length);
62e76326 904
5f8252d2 905 /* If we haven't seen the end of reply headers, we are not done */
2afaba07 906 debug(11,5)("persistentConnStatus: flags.headers_parsed=%d\n", flags.headers_parsed);
fc68f6b1 907
1a98175f 908 if (!flags.headers_parsed)
62e76326 909 return INCOMPLETE_MSG;
910
5f8252d2 911 const int clen = reply->bodySize(request->method);
fc68f6b1 912
2afaba07 913 debug(11,5)("persistentConnStatus: clen=%d\n", clen);
914
35282fbf 915 /* If the body size is unknown we must wait for EOF */
916 if (clen < 0)
62e76326 917 return INCOMPLETE_MSG;
918
5f8252d2 919 /* If the body size is known, we must wait until we've gotten all of it. */
920 if (clen > 0) {
921 // old technique:
922 // if (entry->mem_obj->endOffset() < reply->content_length + reply->hdr_sz)
923 const int body_bytes_read = reply_bytes_read - header_bytes_read;
924 debugs(11,5, "persistentConnStatus: body_bytes_read=" <<
fc68f6b1 925 body_bytes_read << " content_length=" << reply->content_length);
2afaba07 926
5f8252d2 927 if (body_bytes_read < reply->content_length)
928 return INCOMPLETE_MSG;
929 }
62e76326 930
5f8252d2 931 /* If there is no message body or we got it all, we can be persistent */
932 return statusIfComplete();
603a02fd 933}
090089c4 934
2afaba07 935/*
936 * This is the callback after some data has been read from the network
937 */
e5ee81f0 938void
939HttpStateData::ReadReplyWrapper(int fd, char *buf, size_t len, comm_err_t flag, int xerrno, void *data)
c4b7a5a9 940{
941 HttpStateData *httpState = static_cast<HttpStateData *>(data);
7194987f 942 assert (fd == httpState->fd);
2afaba07 943 // assert(buf == readBuf->content());
1d5161bd 944 PROF_start(HttpStateData_readReply);
2afaba07 945 httpState->readReply (len, flag, xerrno);
1d5161bd 946 PROF_stop(HttpStateData_readReply);
c4b7a5a9 947}
948
2afdbf48 949/* XXX this function is too long! */
c4b7a5a9 950void
2afaba07 951HttpStateData::readReply (size_t len, comm_err_t flag, int xerrno)
090089c4 952{
30a4f2a8 953 int bin;
090089c4 954 int clen;
f61f0107 955 flags.do_next_read = 0;
c4b7a5a9 956
2afaba07 957 /*
958 * Bail out early on COMM_ERR_CLOSING - close handlers will tidy up for us
959 */
62e76326 960
c4b7a5a9 961 if (flag == COMM_ERR_CLOSING) {
d09176e1 962 debug (11,3)("http socket closing\n");
c4b7a5a9 963 return;
964 }
965
e92e4e44 966 if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
5f8252d2 967 maybeReadVirginBody();
62e76326 968 return;
e92e4e44 969 }
c4b7a5a9 970
1513873c 971 errno = 0;
c4b7a5a9 972 /* prepare the read size for the next read (if any) */
62e76326 973
c4b7a5a9 974 debug(11, 5) ("httpReadReply: FD %d: len %d.\n", fd, (int)len);
62e76326 975
c4b7a5a9 976 if (flag == COMM_OK && len > 0) {
2afaba07 977 readBuf->appended(len);
5f8252d2 978 reply_bytes_read += len;
447e176b 979#if DELAY_POOLS
2afaba07 980
981 DelayId delayId = entry->mem_obj->mostBytesAllowed();
62e76326 982 delayId.bytesIn(len);
447e176b 983#endif
62e76326 984
985 kb_incr(&statCounter.server.all.kbytes_in, len);
986 kb_incr(&statCounter.server.http.kbytes_in, len);
62e76326 987 IOStats.Http.reads++;
988
989 for (clen = len - 1, bin = 0; clen; bin++)
990 clen >>= 1;
991
992 IOStats.Http.read_hist[bin]++;
30a4f2a8 993 }
62e76326 994
5fa061b8 995 /* here the RFC says we should ignore whitespace between replies, but we can't as
996 * doing so breaks HTTP/0.9 replies beginning with witespace, and in addition
997 * the response splitting countermeasures is extremely likely to trigger on this,
998 * not allowing connection reuse in the first place.
999 */
1000#if DONT_DO_THIS
1a98175f 1001 if (!flags.headers_parsed && flag == COMM_OK && len > 0 && fd_table[fd].uses > 1) {
5fa061b8 1002 /* Skip whitespace between replies */
62e76326 1003
e4755e29 1004 while (len > 0 && xisspace(*buf))
62e76326 1005 xmemmove(buf, buf + 1, len--);
1006
1007 if (len == 0) {
1008 /* Continue to read... */
21b92762 1009 /* Timeout NOT increased. This whitespace was from previous reply */
f61f0107 1010 flags.do_next_read = 1;
5f8252d2 1011 maybeReadVirginBody();
62e76326 1012 return;
1013 }
5ede6c8f 1014 }
62e76326 1015
5fa061b8 1016#endif
1017
c4b7a5a9 1018 if (flag != COMM_OK || len < 0) {
62e76326 1019 debug(50, 2) ("httpReadReply: FD %d: read failure: %s.\n",
1020 fd, xstrerror());
1021
1022 if (ignoreErrno(errno)) {
f61f0107 1023 flags.do_next_read = 1;
6cae5db1 1024 } else {
62e76326 1025 ErrorState *err;
2cc81f1f 1026 err = errorCon(ERR_READ_ERROR, HTTP_BAD_GATEWAY, fwd->request);
62e76326 1027 err->xerrno = errno;
b6b6f466 1028 fwd->fail(err);
f61f0107 1029 flags.do_next_read = 0;
62e76326 1030 comm_close(fd);
62e76326 1031 }
2afaba07 1032 } else if (flag == COMM_OK && len == 0 && !flags.headers_parsed) {
2cc81f1f 1033 fwd->fail(errorCon(ERR_ZERO_SIZE_OBJECT, HTTP_BAD_GATEWAY, fwd->request));
62e76326 1034 eof = 1;
f61f0107 1035 flags.do_next_read = 0;
62e76326 1036 comm_close(fd);
c4b7a5a9 1037 } else if (flag == COMM_OK && len == 0) {
62e76326 1038 /* Connection closed; retrieval done. */
1039 eof = 1;
1040
2cca9b7d 1041 if (!flags.headers_parsed) {
62e76326 1042 /*
3f7d66c7 1043 * When we called processReplyHeader() before, we
1a98175f 1044 * didn't find the end of headers, but now we are
1045 * definately at EOF, so we want to process the reply
1046 * headers.
62e76326 1047 */
fc68f6b1 1048 PROF_start(HttpStateData_processReplyHeader);
2afaba07 1049 processReplyHeader();
fc68f6b1 1050 PROF_stop(HttpStateData_processReplyHeader);
1051 } else if (getReply()->sline.status == HTTP_INVALID_HEADER && HttpVersion(0,9) != getReply()->sline.version) {
2cc81f1f 1052 fwd->fail(errorCon(ERR_INVALID_RESP, HTTP_BAD_GATEWAY, fwd->request));
f61f0107 1053 flags.do_next_read = 0;
47ac2ebe 1054 } else {
4eb368f9 1055 if (entry->mem_obj->getReply()->sline.status == HTTP_HEADER_TOO_LARGE) {
4eb368f9 1056 storeEntryReset(entry);
2cc81f1f 1057 fwd->fail( errorCon(ERR_TOO_BIG, HTTP_BAD_GATEWAY, fwd->request));
b6b6f466 1058 fwd->dontRetry(true);
2afaba07 1059 flags.do_next_read = 0;
1060 comm_close(fd);
4eb368f9 1061 } else {
5f8252d2 1062 serverComplete();
4eb368f9 1063 }
62e76326 1064 }
090089c4 1065 } else {
1a98175f 1066 if (!flags.headers_parsed) {
fc68f6b1 1067 PROF_start(HttpStateData_processReplyHeader);
2afaba07 1068 processReplyHeader();
fc68f6b1 1069 PROF_stop(HttpStateData_processReplyHeader);
62e76326 1070
1a98175f 1071 if (flags.headers_parsed) {
42f79b17 1072 bool fail = reply == NULL;
47ac2ebe 1073
42f79b17 1074 if (!fail) {
1075 http_status s = getReply()->sline.status;
1076 HttpVersion httpver = getReply()->sline.version;
1077 fail = s == HTTP_INVALID_HEADER && httpver != HttpVersion(0,9);
1078 }
1079
1080 if (fail) {
47ac2ebe 1081 storeEntryReset(entry);
2cc81f1f 1082 fwd->fail( errorCon(ERR_INVALID_RESP, HTTP_BAD_GATEWAY, fwd->request));
47ac2ebe 1083 comm_close(fd);
1084 return;
1085 }
1086
2afaba07 1087 }
1088 }
1089
1090 PROF_start(HttpStateData_processReplyBody);
1091 processReplyBody();
1092 PROF_stop(HttpStateData_processReplyBody);
1093 }
1094}
1095
1096/*
1097 * Call this when there is data from the origin server
1098 * which should be sent to either StoreEntry, or to ICAP...
1099 */
1100void
5f8252d2 1101HttpStateData::writeReplyBody()
2afaba07 1102{
5f8252d2 1103 const char *data = readBuf->content();
1104 int len = readBuf->contentSize();
62e76326 1105
5f8252d2 1106#if ICAP_CLIENT
fc68f6b1 1107
5f8252d2 1108 if (virginBodyDestination != NULL) {
1109 const size_t putSize = virginBodyDestination->putMoreData(data, len);
1110 readBuf->consume(putSize);
1111 return;
1112 }
fc68f6b1 1113
5f8252d2 1114 // Even if we are done with sending the virgin body to ICAP, we may still
1115 // be waiting for adapted headers. We need them before writing to store.
1116 if (adaptedHeadSource != NULL) {
1117 debugs(11,5, HERE << "need adapted head from " << adaptedHeadSource);
2afaba07 1118 return;
1119 }
fc68f6b1 1120
225644d7 1121#endif
62e76326 1122
2afaba07 1123 entry->write (StoreIOBuffer(len, currentOffset, (char*)data));
fc68f6b1 1124
5f8252d2 1125 readBuf->consume(len);
fc68f6b1 1126
2afaba07 1127 currentOffset += len;
e6ccf245 1128}
1129
2afaba07 1130/*
1131 * processReplyBody has two purposes:
1132 * 1 - take the reply body data, if any, and put it into either
1133 * the StoreEntry, or give it over to ICAP.
1134 * 2 - see if we made it to the end of the response (persistent
1135 * connections and such)
1136 */
e6ccf245 1137void
2afaba07 1138HttpStateData::processReplyBody()
e6ccf245 1139{
fc68f6b1 1140
1141 struct IN_ADDR *client_addr = NULL;
1142
1a98175f 1143 if (!flags.headers_parsed) {
f61f0107 1144 flags.do_next_read = 1;
5f8252d2 1145 maybeReadVirginBody();
62e76326 1146 return;
528b2c61 1147 }
62e76326 1148
2afaba07 1149#if ICAP_CLIENT
1150 if (icapAccessCheckPending)
1151 return;
fc68f6b1 1152
2afaba07 1153#endif
62e76326 1154
2afaba07 1155 /*
1156 * At this point the reply headers have been parsed and consumed.
1157 * That means header content has been removed from readBuf and
1158 * it contains only body data.
1159 */
5f8252d2 1160 writeReplyBody();
528b2c61 1161
e6ccf245 1162 if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
62e76326 1163 /*
2afaba07 1164 * the above writeReplyBody() call could ABORT this entry,
62e76326 1165 * in that case, the server FD should already be closed.
1166 * there's nothing for us to do.
1167 */
1168 (void) 0;
1169 } else
1170 switch (persistentConnStatus()) {
1171
1172 case INCOMPLETE_MSG:
2afaba07 1173 debug(11,5)("processReplyBody: INCOMPLETE_MSG\n");
21b92762 1174 /* Wait for more data or EOF condition */
1175
1176 if (flags.keepalive_broken) {
1177 commSetTimeout(fd, 10, NULL, NULL);
1178 } else {
1179 commSetTimeout(fd, Config.Timeout.read, NULL, NULL);
1180 }
1181
f61f0107 1182 flags.do_next_read = 1;
62e76326 1183 break;
1184
1185 case COMPLETE_PERSISTENT_MSG:
2afaba07 1186 debug(11,5)("processReplyBody: COMPLETE_PERSISTENT_MSG\n");
62e76326 1187 /* yes we have to clear all these! */
62e76326 1188 commSetTimeout(fd, -1, NULL, NULL);
f61f0107 1189 flags.do_next_read = 0;
62e76326 1190
1191 comm_remove_close_handler(fd, httpStateFree, this);
b6b6f466 1192 fwd->unregister(fd);
fc68f6b1 1193#if LINUX_TPROXY
1194
1195 if (orig_request->flags.tproxy)
1196 client_addr = &orig_request->client_addr;
1197
1198#endif
bd0723ad 1199
1200 if (_peer) {
1201 if (_peer->options.originserver)
fc68f6b1 1202 fwd->pconnPush(fd, _peer->name, orig_request->port, orig_request->host, client_addr);
bd0723ad 1203 else
fc68f6b1 1204 fwd->pconnPush(fd, _peer->name, _peer->http_port, NULL, client_addr);
bd0723ad 1205 } else {
fc68f6b1 1206 fwd->pconnPush(fd, request->host, request->port, NULL, client_addr);
bd0723ad 1207 }
1208
62e76326 1209 fd = -1;
2afaba07 1210
5f8252d2 1211 serverComplete();
62e76326 1212 return;
1213
1214 case COMPLETE_NONPERSISTENT_MSG:
2afaba07 1215 debug(11,5)("processReplyBody: COMPLETE_NONPERSISTENT_MSG\n");
5f8252d2 1216 serverComplete();
62e76326 1217 return;
1218 }
1219
5f8252d2 1220 maybeReadVirginBody();
c4b7a5a9 1221}
1222
1223void
5f8252d2 1224HttpStateData::maybeReadVirginBody()
c4b7a5a9 1225{
2afaba07 1226 int read_sz = readBuf->spaceSize();
2afaba07 1227
5f8252d2 1228#if ICAP_CLIENT
1229#if RE_ENABLE_THIS_IF_NEEDED_OR_DELETE
1230 // This code is not broken, but is probably not needed because we
1231 // probably can read more than will fit into the BodyPipe buffer.
fc68f6b1 1232
5f8252d2 1233 if (virginBodyDestination != NULL) {
2afaba07 1234 /*
5f8252d2 1235 * BodyPipe buffer has a finite size limit. We
2afaba07 1236 * should not read more data from the network than will fit
1237 * into the pipe buffer. If totally full, don't register
1238 * the read handler at all. The ICAP side will call our
1239 * icapSpaceAvailable() method when it has free space again.
1240 */
5f8252d2 1241 int icap_space = virginBodyDestination->buf().potentialSpaceSize();
2afaba07 1242
1243 debugs(11,9, "HttpStateData may read up to min(" << icap_space <<
1244 ", " << read_sz << ") bytes");
1245
1246 if (icap_space < read_sz)
1247 read_sz = icap_space;
1248 }
fc68f6b1 1249
5f8252d2 1250#endif
2afaba07 1251#endif
1252
5f8252d2 1253 debugs(11,9, HERE << (flags.do_next_read ? "may" : "wont") <<
fc68f6b1 1254 " read up to " << read_sz << " bytes from FD " << fd);
2afaba07 1255
1256 /*
1257 * why <2? Because delayAwareRead() won't actually read if
1258 * you ask it to read 1 byte. The delayed read request
1259 * just gets re-queued until the client side drains, then
1260 * the I/O thread hangs. Better to not register any read
1261 * handler until we get a notification from someone that
1262 * its okay to read again.
1263 */
1264 if (read_sz < 2)
1265 return;
1266
f61f0107 1267 if (flags.do_next_read) {
1268 flags.do_next_read = 0;
e5ee81f0 1269 entry->delayAwareRead(fd, readBuf->space(), read_sz, ReadReplyWrapper, this);
528b2c61 1270 }
090089c4 1271}
1272
2afaba07 1273/*
1274 * This will be called when request write is complete.
1275 */
d576a6a6 1276void
2b663917 1277HttpStateData::SendComplete(int fd, char *bufnotused, size_t size, comm_err_t errflag, int xerrno, void *data)
090089c4 1278{
e6ccf245 1279 HttpStateData *httpState = static_cast<HttpStateData *>(data);
a3d5953d 1280 debug(11, 5) ("httpSendComplete: FD %d: size %d: errflag %d.\n",
62e76326 1281 fd, (int) size, errflag);
bc87dc25 1282#if URL_CHECKSUM_DEBUG
62e76326 1283
528b2c61 1284 entry->mem_obj->checkUrlChecksum();
bc87dc25 1285#endif
62e76326 1286
ee1679df 1287 if (size > 0) {
62e76326 1288 fd_bytes(fd, size, FD_WRITE);
1289 kb_incr(&statCounter.server.all.kbytes_out, size);
1290 kb_incr(&statCounter.server.http.kbytes_out, size);
ee1679df 1291 }
62e76326 1292
ea3a2a69 1293 if (errflag == COMM_ERR_CLOSING)
62e76326 1294 return;
1295
090089c4 1296 if (errflag) {
6cae5db1 1297 ErrorState *err;
2cc81f1f 1298 err = errorCon(ERR_WRITE_ERROR, HTTP_BAD_GATEWAY, httpState->fwd->request);
2b663917 1299 err->xerrno = xerrno;
b6b6f466 1300 httpState->fwd->fail(err);
62e76326 1301 comm_close(fd);
1302 return;
090089c4 1303 }
72b63f06 1304
2afaba07 1305 /*
1306 * Set the read timeout here because it hasn't been set yet.
1307 * We only set the read timeout after the request has been
1308 * fully written to the server-side. If we start the timeout
1309 * after connection establishment, then we are likely to hit
1310 * the timeout for POST/PUT requests that have very large
1311 * request bodies.
1312 */
1313 commSetTimeout(fd, Config.Timeout.read, httpTimeout, httpState);
1314
72b63f06 1315 httpState->flags.request_sent = 1;
090089c4 1316}
1317
5f8252d2 1318// Close the HTTP server connection. Used by serverComplete().
2afaba07 1319void
5f8252d2 1320HttpStateData::closeServer()
2afaba07 1321{
5f8252d2 1322 debugs(11,5, HERE << "closing HTTP server FD " << fd << " this " << this);
fc68f6b1 1323
2afaba07 1324 if (fd >= 0) {
b6b6f466 1325 fwd->unregister(fd);
2afaba07 1326 comm_remove_close_handler(fd, httpStateFree, this);
1327 comm_close(fd);
1328 fd = -1;
1329 }
5f8252d2 1330}
2afaba07 1331
5f8252d2 1332bool
1333HttpStateData::doneWithServer() const
1334{
1335 return fd < 0;
2afaba07 1336}
1337
99edd1c3 1338/*
1339 * build request headers and append them to a given MemBuf
e5ee81f0 1340 * used by buildRequestPrefix()
818c6c9e 1341 * note: initialised the HttpHeader, the caller is responsible for Clean()-ing
99edd1c3 1342 */
e1e72f06 1343void
e5ee81f0 1344HttpStateData::httpBuildRequestHeader(HttpRequest * request,
1345 HttpRequest * orig_request,
1346 StoreEntry * entry,
1347 HttpHeader * hdr_out,
1348 http_state_flags flags)
6bf8443a 1349{
99edd1c3 1350 /* building buffer for complex strings */
5999b776 1351#define BBUF_SZ (MAX_URL+32)
99edd1c3 1352 LOCAL_ARRAY(char, bbuf, BBUF_SZ);
99edd1c3 1353 const HttpHeader *hdr_in = &orig_request->header;
1354 const HttpHeaderEntry *e;
6bccf575 1355 String strFwd;
99edd1c3 1356 HttpHeaderPos pos = HttpHeaderInitPos;
75faaa7a 1357 assert (hdr_out->owner == hoRequest);
99edd1c3 1358 /* append our IMS header */
62e76326 1359
fa3e249f 1360 if (request->lastmod > -1)
a9925b40 1361 hdr_out->putTime(HDR_IF_MODIFIED_SINCE, request->lastmod);
99edd1c3 1362
528b2c61 1363 bool we_do_ranges = decideIfWeDoRanges (orig_request);
1364
a9925b40 1365 String strConnection (hdr_in->getList(HDR_CONNECTION));
62e76326 1366
a9925b40 1367 while ((e = hdr_in->getEntry(&pos)))
62e76326 1368 copyOneHeaderFromClientsideRequestToUpstreamRequest(e, strConnection, request, orig_request, hdr_out, we_do_ranges, flags);
528b2c61 1369
43ae1d95 1370 /* Abstraction break: We should interpret multipart/byterange responses
528b2c61 1371 * into offset-length data, and this works around our inability to do so.
1372 */
62e76326 1373 if (!we_do_ranges && orig_request->multipartRangeRequest()) {
1374 /* don't cache the result */
1375 orig_request->flags.cachable = 0;
1376 /* pretend it's not a range request */
00d77d6b 1377 delete orig_request->range;
62e76326 1378 orig_request->range = NULL;
1379 orig_request->flags.range = 0;
1380 }
528b2c61 1381
99edd1c3 1382 /* append Via */
736cb6aa 1383 if (Config.onoff.via) {
43ae1d95 1384 String strVia;
a9925b40 1385 strVia = hdr_in->getList(HDR_VIA);
62e76326 1386 snprintf(bbuf, BBUF_SZ, "%d.%d %s",
1387 orig_request->http_ver.major,
1388 orig_request->http_ver.minor, ThisCache);
1389 strListAdd(&strVia, bbuf, ',');
a9925b40 1390 hdr_out->putStr(HDR_VIA, strVia.buf());
62e76326 1391 strVia.clean();
736cb6aa 1392 }
62e76326 1393
43ae1d95 1394#if ESI
1395 {
1396 /* Append Surrogate-Capabilities */
a9925b40 1397 String strSurrogate (hdr_in->getList(HDR_SURROGATE_CAPABILITY));
ec43ae0e 1398 snprintf(bbuf, BBUF_SZ, "%s=\"Surrogate/1.0 ESI/1.0\"",
43ae1d95 1399 Config.Accel.surrogate_id);
1400 strListAdd(&strSurrogate, bbuf, ',');
a9925b40 1401 hdr_out->putStr(HDR_SURROGATE_CAPABILITY, strSurrogate.buf());
43ae1d95 1402 }
1403#endif
1404
99edd1c3 1405 /* append X-Forwarded-For */
a9925b40 1406 strFwd = hdr_in->getList(HDR_X_FORWARDED_FOR);
62e76326 1407
6056ae68 1408 if (opt_forwarded_for && orig_request->client_addr.s_addr != no_addr.s_addr)
62e76326 1409 strListAdd(&strFwd, inet_ntoa(orig_request->client_addr), ',');
6056ae68 1410 else
62e76326 1411 strListAdd(&strFwd, "unknown", ',');
1412
a9925b40 1413 hdr_out->putStr(HDR_X_FORWARDED_FOR, strFwd.buf());
62e76326 1414
528b2c61 1415 strFwd.clean();
6bccf575 1416
99edd1c3 1417 /* append Host if not there already */
a9925b40 1418 if (!hdr_out->has(HDR_HOST)) {
62e76326 1419 if (orig_request->peer_domain) {
a9925b40 1420 hdr_out->putStr(HDR_HOST, orig_request->peer_domain);
62e76326 1421 } else if (orig_request->port == urlDefaultPort(orig_request->protocol)) {
1422 /* use port# only if not default */
a9925b40 1423 hdr_out->putStr(HDR_HOST, orig_request->host);
62e76326 1424 } else {
1425 httpHeaderPutStrf(hdr_out, HDR_HOST, "%s:%d",
1426 orig_request->host, (int) orig_request->port);
1427 }
6bf8443a 1428 }
62e76326 1429
c68e9c6b 1430 /* append Authorization if known in URL, not in header and going direct */
a9925b40 1431 if (!hdr_out->has(HDR_AUTHORIZATION)) {
62e76326 1432 if (!request->flags.proxying && *request->login) {
1433 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1434 base64_encode(request->login));
1435 }
c68e9c6b 1436 }
62e76326 1437
c68e9c6b 1438 /* append Proxy-Authorization if configured for peer, and proxying */
c3b33cb7 1439 if (request->flags.proxying && orig_request->peer_login &&
a9925b40 1440 !hdr_out->has(HDR_PROXY_AUTHORIZATION)) {
62e76326 1441 if (*orig_request->peer_login == '*') {
1442 /* Special mode, to pass the username to the upstream cache */
1443 char loginbuf[256];
1444 const char *username = "-";
1445
1446 if (orig_request->auth_user_request)
1447 username = orig_request->auth_user_request->username();
abb929f0 1448 else if (orig_request->extacl_user.size())
1449 username = orig_request->extacl_user.buf();
62e76326 1450
1451 snprintf(loginbuf, sizeof(loginbuf), "%s%s", username, orig_request->peer_login + 1);
1452
1453 httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Basic %s",
1454 base64_encode(loginbuf));
1455 } else if (strcmp(orig_request->peer_login, "PASS") == 0) {
abb929f0 1456 if (orig_request->extacl_user.size() && orig_request->extacl_passwd.size()) {
1457 char loginbuf[256];
1458 snprintf(loginbuf, sizeof(loginbuf), "%s:%s", orig_request->extacl_user.buf(), orig_request->extacl_passwd.buf());
1459 httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Basic %s",
1460 base64_encode(loginbuf));
1461 }
62e76326 1462 } else if (strcmp(orig_request->peer_login, "PROXYPASS") == 0) {
1463 /* Nothing to do */
1464 } else {
1465 httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Basic %s",
1466 base64_encode(orig_request->peer_login));
1467 }
c68e9c6b 1468 }
62e76326 1469
be753325 1470 /* append WWW-Authorization if configured for peer */
1471 if (flags.originpeer && orig_request->peer_login &&
a9925b40 1472 !hdr_out->has(HDR_AUTHORIZATION)) {
62e76326 1473 if (strcmp(orig_request->peer_login, "PASS") == 0) {
1474 /* No credentials to forward.. (should have been done above if available) */
1475 } else if (strcmp(orig_request->peer_login, "PROXYPASS") == 0) {
1476 /* Special mode, convert proxy authentication to WWW authentication
abb929f0 1477 * (also applies to authentication provided by external acl)
62e76326 1478 */
a9925b40 1479 const char *auth = hdr_in->getStr(HDR_PROXY_AUTHORIZATION);
62e76326 1480
1481 if (auth && strncasecmp(auth, "basic ", 6) == 0) {
a9925b40 1482 hdr_out->putStr(HDR_AUTHORIZATION, auth);
abb929f0 1483 } else if (orig_request->extacl_user.size() && orig_request->extacl_passwd.size()) {
1484 char loginbuf[256];
1485 snprintf(loginbuf, sizeof(loginbuf), "%s:%s", orig_request->extacl_user.buf(), orig_request->extacl_passwd.buf());
1486 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1487 base64_encode(loginbuf));
62e76326 1488 }
1489 } else if (*orig_request->peer_login == '*') {
1490 /* Special mode, to pass the username to the upstream cache */
1491 char loginbuf[256];
1492 const char *username = "-";
1493
1494 if (orig_request->auth_user_request)
f5691f9c 1495 username = orig_request->auth_user_request->username();
abb929f0 1496 else if (orig_request->extacl_user.size())
1497 username = orig_request->extacl_user.buf();
62e76326 1498
1499 snprintf(loginbuf, sizeof(loginbuf), "%s%s", username, orig_request->peer_login + 1);
1500
1501 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1502 base64_encode(loginbuf));
1503 } else {
1504 /* Fixed login string */
1505 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1506 base64_encode(orig_request->peer_login));
1507 }
be753325 1508 }
62e76326 1509
abb929f0 1510 /* append Cache-Control, add max-age if not there already */ {
a9925b40 1511 HttpHdrCc *cc = hdr_in->getCc();
62e76326 1512
1513 if (!cc)
1514 cc = httpHdrCcCreate();
1515
1516 if (!EBIT_TEST(cc->mask, CC_MAX_AGE)) {
43ae1d95 1517 const char *url =
1518 entry ? storeUrl(entry) : urlCanonical(orig_request);
62e76326 1519 httpHdrCcSetMaxAge(cc, getMaxAge(url));
1520
1521 if (request->urlpath.size())
1522 assert(strstr(url, request->urlpath.buf()));
1523 }
1524
ce2d6441 1525 /* Set no-cache if determined needed but not found */
a9925b40 1526 if (orig_request->flags.nocache && !hdr_in->has(HDR_PRAGMA))
ce2d6441 1527 EBIT_SET(cc->mask, CC_NO_CACHE);
1528
1529 /* Enforce sibling relations */
62e76326 1530 if (flags.only_if_cached)
1531 EBIT_SET(cc->mask, CC_ONLY_IF_CACHED);
1532
a9925b40 1533 hdr_out->putCc(cc);
62e76326 1534
1535 httpHdrCcDestroy(cc);
6bf8443a 1536 }
62e76326 1537
99edd1c3 1538 /* maybe append Connection: keep-alive */
b515fc11 1539 if (flags.keepalive) {
62e76326 1540 if (flags.proxying) {
a9925b40 1541 hdr_out->putStr(HDR_PROXY_CONNECTION, "keep-alive");
62e76326 1542 } else {
a9925b40 1543 hdr_out->putStr(HDR_CONNECTION, "keep-alive");
62e76326 1544 }
603a02fd 1545 }
62e76326 1546
a7ad6e4e 1547 /* append Front-End-Https */
1548 if (flags.front_end_https) {
62e76326 1549 if (flags.front_end_https == 1 || request->protocol == PROTO_HTTPS)
a9925b40 1550 hdr_out->putStr(HDR_FRONT_END_HTTPS, "On");
a7ad6e4e 1551 }
1552
6bccf575 1553 /* Now mangle the headers. */
4f56514c 1554 if (Config2.onoff.mangle_request_headers)
5967c0bf 1555 httpHdrMangleList(hdr_out, request, ROR_REQUEST);
62e76326 1556
528b2c61 1557 strConnection.clean();
99edd1c3 1558}
1559
528b2c61 1560void
190154cf 1561copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, String strConnection, HttpRequest * request, HttpRequest * orig_request, HttpHeader * hdr_out, int we_do_ranges, http_state_flags flags)
528b2c61 1562{
1563 debug(11, 5) ("httpBuildRequestHeader: %s: %s\n",
62e76326 1564 e->name.buf(), e->value.buf());
1565
528b2c61 1566 if (!httpRequestHdrAllowed(e, &strConnection)) {
62e76326 1567 debug(11, 2) ("'%s' header denied by anonymize_headers configuration\n",+ e->name.buf());
1568 return;
528b2c61 1569 }
62e76326 1570
528b2c61 1571 switch (e->id) {
62e76326 1572
be753325 1573 case HDR_PROXY_AUTHORIZATION:
62e76326 1574 /* Only pass on proxy authentication to peers for which
1575 * authentication forwarding is explicitly enabled
1576 */
1577
1578 if (flags.proxying && orig_request->peer_login &&
abb929f0 1579 (strcmp(orig_request->peer_login, "PASS") == 0 ||
1580 strcmp(orig_request->peer_login, "PROXYPASS") == 0)) {
eede25e7 1581 hdr_out->addEntry(e->clone());
62e76326 1582 }
1583
1584 break;
1585
be753325 1586 case HDR_AUTHORIZATION:
62e76326 1587 /* Pass on WWW authentication */
1588
1589 if (!flags.originpeer) {
eede25e7 1590 hdr_out->addEntry(e->clone());
62e76326 1591 } else {
1592 /* In accelerators, only forward authentication if enabled
1593 * (see also below for proxy->server authentication)
1594 */
1595
abb929f0 1596 if (orig_request->peer_login &&
1597 (strcmp(orig_request->peer_login, "PASS") == 0 ||
1598 strcmp(orig_request->peer_login, "PROXYPASS") == 0)) {
eede25e7 1599 hdr_out->addEntry(e->clone());
62e76326 1600 }
1601 }
1602
1603 break;
1604
be753325 1605 case HDR_HOST:
62e76326 1606 /*
b883b594 1607 * Normally Squid rewrites the Host: header.
1608 * However, there is one case when we don't: If the URL
62e76326 1609 * went through our redirector and the admin configured
1610 * 'redir_rewrites_host' to be off.
1611 */
1612
b883b594 1613 if (request->flags.redirected && !Config.onoff.redir_rewrites_host)
eede25e7 1614 hdr_out->addEntry(e->clone());
b883b594 1615 else {
1616 /* use port# only if not default */
1617
1618 if (orig_request->port == urlDefaultPort(orig_request->protocol)) {
a9925b40 1619 hdr_out->putStr(HDR_HOST, orig_request->host);
b883b594 1620 } else {
1621 httpHeaderPutStrf(hdr_out, HDR_HOST, "%s:%d",
1622 orig_request->host, (int) orig_request->port);
1623 }
1624 }
62e76326 1625
1626 break;
1627
be753325 1628 case HDR_IF_MODIFIED_SINCE:
62e76326 1629 /* append unless we added our own;
1630 * note: at most one client's ims header can pass through */
b883b594 1631
a9925b40 1632 if (!hdr_out->has(HDR_IF_MODIFIED_SINCE))
eede25e7 1633 hdr_out->addEntry(e->clone());
62e76326 1634
1635 break;
1636
be753325 1637 case HDR_MAX_FORWARDS:
62e76326 1638 if (orig_request->method == METHOD_TRACE) {
eede25e7 1639 const int hops = e->getInt();
62e76326 1640
1641 if (hops > 0)
a9925b40 1642 hdr_out->putInt(HDR_MAX_FORWARDS, hops - 1);
62e76326 1643 }
1644
1645 break;
1646
be753325 1647 case HDR_VIA:
62e76326 1648 /* If Via is disabled then forward any received header as-is */
1649
1650 if (!Config.onoff.via)
eede25e7 1651 hdr_out->addEntry(e->clone());
62e76326 1652
1653 break;
1654
be753325 1655 case HDR_RANGE:
62e76326 1656
be753325 1657 case HDR_IF_RANGE:
62e76326 1658
be753325 1659 case HDR_REQUEST_RANGE:
62e76326 1660 if (!we_do_ranges)
eede25e7 1661 hdr_out->addEntry(e->clone());
62e76326 1662
1663 break;
1664
be753325 1665 case HDR_PROXY_CONNECTION:
62e76326 1666
be753325 1667 case HDR_CONNECTION:
62e76326 1668
be753325 1669 case HDR_X_FORWARDED_FOR:
62e76326 1670
be753325 1671 case HDR_CACHE_CONTROL:
62e76326 1672 /* append these after the loop if needed */
1673 break;
1674
be753325 1675 case HDR_FRONT_END_HTTPS:
62e76326 1676 if (!flags.front_end_https)
eede25e7 1677 hdr_out->addEntry(e->clone());
62e76326 1678
1679 break;
1680
be753325 1681 default:
62e76326 1682 /* pass on all other header fields */
eede25e7 1683 hdr_out->addEntry(e->clone());
528b2c61 1684 }
1685}
1686
e5ee81f0 1687bool
1688HttpStateData::decideIfWeDoRanges (HttpRequest * orig_request)
528b2c61 1689{
e5ee81f0 1690 bool result = true;
62e76326 1691 /* decide if we want to do Ranges ourselves
1692 * and fetch the whole object now)
1693 * We want to handle Ranges ourselves iff
1694 * - we can actually parse client Range specs
1695 * - the specs are expected to be simple enough (e.g. no out-of-order ranges)
1696 * - reply will be cachable
1697 * (If the reply will be uncachable we have to throw it away after
1698 * serving this request, so it is better to forward ranges to
1699 * the server and fetch only the requested content)
1700 */
1701
1702 if (NULL == orig_request->range || !orig_request->flags.cachable
1703 || orig_request->range->offsetLimitExceeded())
e5ee81f0 1704 result = false;
62e76326 1705
1706 debug(11, 8) ("decideIfWeDoRanges: range specs: %p, cachable: %d; we_do_ranges: %d\n",
1707 orig_request->range, orig_request->flags.cachable, result);
1708
1709 return result;
528b2c61 1710}
1711
62e76326 1712/* build request prefix and append it to a given MemBuf;
99edd1c3 1713 * return the length of the prefix */
9bc73deb 1714mb_size_t
e5ee81f0 1715HttpStateData::buildRequestPrefix(HttpRequest * request,
1716 HttpRequest * orig_request,
1717 StoreEntry * entry,
1718 MemBuf * mb,
1719 http_state_flags flags)
99edd1c3 1720{
1721 const int offset = mb->size;
450e0c10 1722 HttpVersion httpver(1, 0);
2fe7eff9 1723 mb->Printf("%s %s HTTP/%d.%d\r\n",
1724 RequestMethodStr[request->method],
1725 request->urlpath.size() ? request->urlpath.buf() : "/",
1726 httpver.major,httpver.minor);
99edd1c3 1727 /* build and pack headers */
1728 {
75faaa7a 1729 HttpHeader hdr(hoRequest);
62e76326 1730 Packer p;
1731 httpBuildRequestHeader(request, orig_request, entry, &hdr, flags);
1732 packerToMemInit(&p, mb);
a9925b40 1733 hdr.packInto(&p);
519e0948 1734 hdr.clean();
62e76326 1735 packerClean(&p);
9d9d144b 1736 }
99edd1c3 1737 /* append header terminator */
2fe7eff9 1738 mb->append(crlf, 2);
99edd1c3 1739 return mb->size - offset;
6bf8443a 1740}
62e76326 1741
090089c4 1742/* This will be called when connect completes. Write request. */
5f8252d2 1743bool
2bb867b5 1744HttpStateData::sendRequest()
090089c4 1745{
99edd1c3 1746 MemBuf mb;
090089c4 1747
5f8252d2 1748 debug(11, 5) ("httpSendRequest: FD %d, request %p, this %p.\n", fd, request, this);
090089c4 1749
2bb867b5 1750 commSetTimeout(fd, Config.Timeout.lifetime, httpTimeout, this);
1751 flags.do_next_read = 1;
5f8252d2 1752 maybeReadVirginBody();
1753
1754 if (orig_request->body_pipe != NULL) {
1755 requestBodySource = orig_request->body_pipe;
fc68f6b1 1756
5f8252d2 1757 if (!requestBodySource->setConsumerIfNotLate(this)) {
1758 debugs(32,3, HERE << "aborting on partially consumed body");
1759 requestBodySource = NULL;
1760 return false;
1761 }
fc68f6b1 1762
5f8252d2 1763 requestSender = HttpStateData::sentRequestBodyWrapper;
1764 debugs(32,3, HERE << "expecting request body on pipe " << requestBodySource);
1765 } else {
1766 assert(!requestBodySource);
1767 requestSender = HttpStateData::SendComplete;
1768 }
54220df8 1769
2bb867b5 1770 if (_peer != NULL) {
1771 if (_peer->options.originserver) {
1772 flags.proxying = 0;
1773 flags.originpeer = 1;
62e76326 1774 } else {
2bb867b5 1775 flags.proxying = 1;
1776 flags.originpeer = 0;
62e76326 1777 }
be753325 1778 } else {
2bb867b5 1779 flags.proxying = 0;
1780 flags.originpeer = 0;
be753325 1781 }
62e76326 1782
efb9218c 1783 /*
99edd1c3 1784 * Is keep-alive okay for all request methods?
efb9218c 1785 */
efd900cb 1786 if (!Config.onoff.server_pconns)
2bb867b5 1787 flags.keepalive = 0;
1788 else if (_peer == NULL)
1789 flags.keepalive = 1;
1790 else if (_peer->stats.n_keepalives_sent < 10)
1791 flags.keepalive = 1;
1792 else if ((double) _peer->stats.n_keepalives_recv /
1793 (double) _peer->stats.n_keepalives_sent > 0.50)
1794 flags.keepalive = 1;
1795
1796 if (_peer) {
1797 if (neighborType(_peer, request) == PEER_SIBLING &&
1798 !_peer->options.allow_miss)
1799 flags.only_if_cached = 1;
1800
1801 flags.front_end_https = _peer->front_end_https;
a7ad6e4e 1802 }
62e76326 1803
2fe7eff9 1804 mb.init();
e5ee81f0 1805 buildRequestPrefix(request, orig_request, entry, &mb, flags);
21b92762 1806 debug(11, 6) ("httpSendRequest: FD %d:\n%s\n", fd, mb.buf);
5f8252d2 1807 comm_write_mbuf(fd, &mb, requestSender, this);
1808
1809 return true;
090089c4 1810}
b6a2f15e 1811
910169e5 1812void
b6b6f466 1813httpStart(FwdState *fwd)
603a02fd 1814{
910169e5 1815 debug(11, 3) ("httpStart: \"%s %s\"\n",
a3d50c30 1816 RequestMethodStr[fwd->request->method],
62e76326 1817 storeUrl(fwd->entry));
a3d50c30 1818 HttpStateData *httpState = new HttpStateData(fwd);
62e76326 1819
5f8252d2 1820 if (!httpState->sendRequest()) {
1821 debug(11, 3) ("httpStart: aborted");
1822 delete httpState;
1823 return;
1824 }
62e76326 1825
5f8252d2 1826 statCounter.server.all.requests++;
83704487 1827 statCounter.server.http.requests++;
62e76326 1828
b6a2f15e 1829 /*
1830 * We used to set the read timeout here, but not any more.
1831 * Now its set in httpSendComplete() after the full request,
1832 * including request body, has been written to the server.
1833 */
090089c4 1834}
1835
2bb867b5 1836void
5f8252d2 1837HttpStateData::doneSendingRequestBody()
2bb867b5 1838{
4fb35c3c 1839 ACLChecklist ch;
5f8252d2 1840 debugs(11,5, HERE << "doneSendingRequestBody: FD " << fd);
6dd9f4bd 1841 ch.request = HTTPMSGLOCK(request);
506768d9 1842
1843 if (Config.accessList.brokenPosts)
1844 ch.accessList = cbdataReference(Config.accessList.brokenPosts);
62e76326 1845
108d65b2 1846 /* cbdataReferenceDone() happens in either fastCheck() or ~ACLCheckList */
1847
94439e4e 1848 if (!Config.accessList.brokenPosts) {
5f8252d2 1849 debug(11, 5) ("doneSendingRequestBody: No brokenPosts list\n");
2b663917 1850 HttpStateData::SendComplete(fd, NULL, 0, COMM_OK, 0, this);
b448c119 1851 } else if (!ch.fastCheck()) {
5f8252d2 1852 debug(11, 5) ("doneSendingRequestBody: didn't match brokenPosts\n");
2b663917 1853 HttpStateData::SendComplete(fd, NULL, 0, COMM_OK, 0, this);
94439e4e 1854 } else {
5f8252d2 1855 debug(11, 2) ("doneSendingRequestBody: matched brokenPosts\n");
2b663917 1856 comm_write(fd, "\r\n", 2, HttpStateData::SendComplete, this, NULL);
54220df8 1857 }
94439e4e 1858}
1859
5f8252d2 1860// more origin request body data is available
2bb867b5 1861void
5f8252d2 1862HttpStateData::handleMoreRequestBodyAvailable()
2bb867b5 1863{
2bb867b5 1864 if (eof || fd < 0) {
5f8252d2 1865 // XXX: we should check this condition in other callbacks then!
1866 // TODO: Check whether this can actually happen: We should unsubscribe
1867 // as a body consumer when the above condition(s) are detected.
2bb867b5 1868 debugs(11, 1, HERE << "Transaction aborted while reading HTTP body");
2bb867b5 1869 return;
1870 }
62e76326 1871
5f8252d2 1872 assert(requestBodySource != NULL);
fc68f6b1 1873
5f8252d2 1874 if (requestBodySource->buf().hasContent()) {
1875 // XXX: why does not this trigger a debug message on every request?
fc68f6b1 1876
2bb867b5 1877 if (flags.headers_parsed && !flags.abuse_detected) {
1878 flags.abuse_detected = 1;
5f8252d2 1879 debug(11, 1) ("http handleMoreRequestBodyAvailable: Likely proxy abuse detected '%s' -> '%s'\n",
2bb867b5 1880 inet_ntoa(orig_request->client_addr),
1881 storeUrl(entry));
21b92762 1882
2bb867b5 1883 if (getReply()->sline.status == HTTP_INVALID_HEADER) {
2bb867b5 1884 comm_close(fd);
21b92762 1885 return;
1886 }
1887 }
b6a2f15e 1888 }
5f8252d2 1889
1890 HttpStateData::handleMoreRequestBodyAvailable();
376bb137 1891}
1892
5f8252d2 1893// premature end of the request body
2bb867b5 1894void
5f8252d2 1895HttpStateData::handleRequestBodyProducerAborted()
376bb137 1896{
5f8252d2 1897 ServerStateData::handleRequestBodyProducerAborted();
1898 // XXX: SendComplete(COMM_ERR_CLOSING) does little. Is it enough?
1899 SendComplete(fd, NULL, 0, COMM_ERR_CLOSING, 0, this);
2bb867b5 1900}
1901
5f8252d2 1902// called when we wrote request headers(!) or a part of the body
2bb867b5 1903void
5f8252d2 1904HttpStateData::sentRequestBody(int fd, size_t size, comm_err_t errflag)
2bb867b5 1905{
5f8252d2 1906 if (size > 0)
62e76326 1907 kb_incr(&statCounter.server.http.kbytes_out, size);
fc68f6b1 1908
5f8252d2 1909 ServerStateData::sentRequestBody(fd, size, errflag);
1910}
3b299123 1911
5f8252d2 1912// Quickly abort the transaction
1913// TODO: destruction should be sufficient as the destructor should cleanup,
1914// including canceling close handlers
1915void
1916HttpStateData::abortTransaction(const char *reason)
1917{
1918 debugs(11,5, HERE << "aborting transaction for " << reason <<
1919 "; FD " << fd << ", this " << this);
fc68f6b1 1920
5f8252d2 1921 if (fd >= 0)
62e76326 1922 comm_close(fd);
5f8252d2 1923 else
1924 delete this;
54220df8 1925}
ccf44862 1926
1927void
450e0c10 1928httpBuildVersion(HttpVersion * version, unsigned int major, unsigned int minor)
110eb4e5 1929{
1930 version->major = major;
1931 version->minor = minor;
ccf44862 1932}
2afaba07 1933
1934#if ICAP_CLIENT
1935
1936static void
1937icapAclCheckDoneWrapper(ICAPServiceRep::Pointer service, void *data)
1938{
1939 HttpStateData *http = (HttpStateData *)data;
1940 http->icapAclCheckDone(service);
1941}
1942
1943void
1944HttpStateData::icapAclCheckDone(ICAPServiceRep::Pointer service)
1945{
1946 icapAccessCheckPending = false;
1947
5f8252d2 1948 const bool startedIcap = startIcap(service, orig_request);
c99de607 1949
1950 if (!startedIcap && (!service || service->bypass)) {
1951 // handle ICAP start failure when no service was selected
1952 // or where the selected service was optional
db237875 1953 entry->replaceHttpReply(reply);
2afaba07 1954
2afaba07 1955 haveParsedReplyHeaders();
1956 processReplyBody();
1957
1958 if (eof == 1)
5f8252d2 1959 serverComplete();
2afaba07 1960
1961 return;
1962 }
1963
c99de607 1964 if (!startedIcap) {
1965 // handle start failure for an essential ICAP service
2cc81f1f 1966 ErrorState *err = errorCon(ERR_ICAP_FAILURE, HTTP_INTERNAL_SERVER_ERROR, orig_request);
2afaba07 1967 err->xerrno = errno;
2afaba07 1968 errorAppendEntry(entry, err);
1969 comm_close(fd);
1970 return;
1971 }
1972
2afaba07 1973 processReplyBody();
1974}
1975
2afaba07 1976#endif