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