]> git.ipfire.org Git - thirdparty/squid.git/blame - src/http.cc
Polish HttpStateData::readReply() layout to weed out bugs, step 2:
[thirdparty/squid.git] / src / http.cc
CommitLineData
da2b3a17 1
30a4f2a8 2/*
274d8c70 3 * $Id: http.cc,v 1.529 2007/06/26 00:16:00 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
2afaba07 973 /*
974 * Bail out early on COMM_ERR_CLOSING - close handlers will tidy up for us
975 */
62e76326 976
c4b7a5a9 977 if (flag == COMM_ERR_CLOSING) {
bf8fe701 978 debugs(11, 3, "http socket closing");
c4b7a5a9 979 return;
980 }
981
e92e4e44 982 if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
5f8252d2 983 maybeReadVirginBody();
62e76326 984 return;
e92e4e44 985 }
c4b7a5a9 986
c4b7a5a9 987 /* prepare the read size for the next read (if any) */
62e76326 988
4a7a3d56 989 debugs(11, 5, "httpReadReply: FD " << fd << ": len " << len << ".");
62e76326 990
c4b7a5a9 991 if (flag == COMM_OK && len > 0) {
2afaba07 992 readBuf->appended(len);
5f8252d2 993 reply_bytes_read += len;
447e176b 994#if DELAY_POOLS
2afaba07 995
996 DelayId delayId = entry->mem_obj->mostBytesAllowed();
62e76326 997 delayId.bytesIn(len);
447e176b 998#endif
62e76326 999
1000 kb_incr(&statCounter.server.all.kbytes_in, len);
1001 kb_incr(&statCounter.server.http.kbytes_in, len);
62e76326 1002 IOStats.Http.reads++;
1003
1004 for (clen = len - 1, bin = 0; clen; bin++)
1005 clen >>= 1;
1006
1007 IOStats.Http.read_hist[bin]++;
30a4f2a8 1008 }
62e76326 1009
5fa061b8 1010 /* here the RFC says we should ignore whitespace between replies, but we can't as
1011 * doing so breaks HTTP/0.9 replies beginning with witespace, and in addition
1012 * the response splitting countermeasures is extremely likely to trigger on this,
1013 * not allowing connection reuse in the first place.
1014 */
1015#if DONT_DO_THIS
1a98175f 1016 if (!flags.headers_parsed && flag == COMM_OK && len > 0 && fd_table[fd].uses > 1) {
5fa061b8 1017 /* Skip whitespace between replies */
62e76326 1018
e4755e29 1019 while (len > 0 && xisspace(*buf))
62e76326 1020 xmemmove(buf, buf + 1, len--);
1021
1022 if (len == 0) {
1023 /* Continue to read... */
21b92762 1024 /* Timeout NOT increased. This whitespace was from previous reply */
f61f0107 1025 flags.do_next_read = 1;
5f8252d2 1026 maybeReadVirginBody();
62e76326 1027 return;
1028 }
5ede6c8f 1029 }
62e76326 1030
5fa061b8 1031#endif
1032
c4b7a5a9 1033 if (flag != COMM_OK || len < 0) {
bf8fe701 1034 debugs(50, 2, "httpReadReply: FD " << fd << ": read failure: " << xstrerror() << ".");
62e76326 1035
274d8c70 1036 if (ignoreErrno(xerrno)) {
f61f0107 1037 flags.do_next_read = 1;
6cae5db1 1038 } else {
62e76326 1039 ErrorState *err;
2cc81f1f 1040 err = errorCon(ERR_READ_ERROR, HTTP_BAD_GATEWAY, fwd->request);
274d8c70 1041 err->xerrno = xerrno;
b6b6f466 1042 fwd->fail(err);
f61f0107 1043 flags.do_next_read = 0;
62e76326 1044 comm_close(fd);
62e76326 1045 }
2afaba07 1046 } else if (flag == COMM_OK && len == 0 && !flags.headers_parsed) {
2cc81f1f 1047 fwd->fail(errorCon(ERR_ZERO_SIZE_OBJECT, HTTP_BAD_GATEWAY, fwd->request));
62e76326 1048 eof = 1;
f61f0107 1049 flags.do_next_read = 0;
62e76326 1050 comm_close(fd);
c4b7a5a9 1051 } else if (flag == COMM_OK && len == 0) {
62e76326 1052 /* Connection closed; retrieval done. */
1053 eof = 1;
1054
2cca9b7d 1055 if (!flags.headers_parsed) {
62e76326 1056 /*
3f7d66c7 1057 * When we called processReplyHeader() before, we
1a98175f 1058 * didn't find the end of headers, but now we are
1059 * definately at EOF, so we want to process the reply
1060 * headers.
62e76326 1061 */
fc68f6b1 1062 PROF_start(HttpStateData_processReplyHeader);
2afaba07 1063 processReplyHeader();
fc68f6b1 1064 PROF_stop(HttpStateData_processReplyHeader);
1065 } else if (getReply()->sline.status == HTTP_INVALID_HEADER && HttpVersion(0,9) != getReply()->sline.version) {
2cc81f1f 1066 fwd->fail(errorCon(ERR_INVALID_RESP, HTTP_BAD_GATEWAY, fwd->request));
f61f0107 1067 flags.do_next_read = 0;
47ac2ebe 1068 } else {
4eb368f9 1069 if (entry->mem_obj->getReply()->sline.status == HTTP_HEADER_TOO_LARGE) {
3900307b 1070 entry->reset();
2cc81f1f 1071 fwd->fail( errorCon(ERR_TOO_BIG, HTTP_BAD_GATEWAY, fwd->request));
b6b6f466 1072 fwd->dontRetry(true);
2afaba07 1073 flags.do_next_read = 0;
1074 comm_close(fd);
4eb368f9 1075 } else {
5f8252d2 1076 serverComplete();
4eb368f9 1077 }
62e76326 1078 }
090089c4 1079 } else {
1a98175f 1080 if (!flags.headers_parsed) {
fc68f6b1 1081 PROF_start(HttpStateData_processReplyHeader);
2afaba07 1082 processReplyHeader();
fc68f6b1 1083 PROF_stop(HttpStateData_processReplyHeader);
62e76326 1084
1a98175f 1085 if (flags.headers_parsed) {
42f79b17 1086 bool fail = reply == NULL;
47ac2ebe 1087
42f79b17 1088 if (!fail) {
1089 http_status s = getReply()->sline.status;
1090 HttpVersion httpver = getReply()->sline.version;
1091 fail = s == HTTP_INVALID_HEADER && httpver != HttpVersion(0,9);
1092 }
1093
1094 if (fail) {
3900307b 1095 entry->reset();
2cc81f1f 1096 fwd->fail( errorCon(ERR_INVALID_RESP, HTTP_BAD_GATEWAY, fwd->request));
47ac2ebe 1097 comm_close(fd);
1098 return;
1099 }
1100
2afaba07 1101 }
1102 }
1103
1104 PROF_start(HttpStateData_processReplyBody);
1105 processReplyBody();
1106 PROF_stop(HttpStateData_processReplyBody);
1107 }
1108}
1109
1110/*
1111 * Call this when there is data from the origin server
1112 * which should be sent to either StoreEntry, or to ICAP...
1113 */
1114void
5f8252d2 1115HttpStateData::writeReplyBody()
2afaba07 1116{
5f8252d2 1117 const char *data = readBuf->content();
1118 int len = readBuf->contentSize();
62e76326 1119
5f8252d2 1120#if ICAP_CLIENT
fc68f6b1 1121
5f8252d2 1122 if (virginBodyDestination != NULL) {
1123 const size_t putSize = virginBodyDestination->putMoreData(data, len);
1124 readBuf->consume(putSize);
1125 return;
1126 }
fc68f6b1 1127
5f8252d2 1128 // Even if we are done with sending the virgin body to ICAP, we may still
1129 // be waiting for adapted headers. We need them before writing to store.
1130 if (adaptedHeadSource != NULL) {
1131 debugs(11,5, HERE << "need adapted head from " << adaptedHeadSource);
2afaba07 1132 return;
1133 }
fc68f6b1 1134
225644d7 1135#endif
62e76326 1136
2afaba07 1137 entry->write (StoreIOBuffer(len, currentOffset, (char*)data));
fc68f6b1 1138
5f8252d2 1139 readBuf->consume(len);
fc68f6b1 1140
2afaba07 1141 currentOffset += len;
e6ccf245 1142}
1143
2afaba07 1144/*
1145 * processReplyBody has two purposes:
1146 * 1 - take the reply body data, if any, and put it into either
1147 * the StoreEntry, or give it over to ICAP.
1148 * 2 - see if we made it to the end of the response (persistent
1149 * connections and such)
1150 */
e6ccf245 1151void
2afaba07 1152HttpStateData::processReplyBody()
e6ccf245 1153{
fc68f6b1 1154
1155 struct IN_ADDR *client_addr = NULL;
1156
1a98175f 1157 if (!flags.headers_parsed) {
f61f0107 1158 flags.do_next_read = 1;
5f8252d2 1159 maybeReadVirginBody();
62e76326 1160 return;
528b2c61 1161 }
62e76326 1162
2afaba07 1163#if ICAP_CLIENT
1164 if (icapAccessCheckPending)
1165 return;
fc68f6b1 1166
2afaba07 1167#endif
62e76326 1168
2afaba07 1169 /*
1170 * At this point the reply headers have been parsed and consumed.
1171 * That means header content has been removed from readBuf and
1172 * it contains only body data.
1173 */
5f8252d2 1174 writeReplyBody();
528b2c61 1175
e6ccf245 1176 if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
62e76326 1177 /*
2afaba07 1178 * the above writeReplyBody() call could ABORT this entry,
62e76326 1179 * in that case, the server FD should already be closed.
1180 * there's nothing for us to do.
1181 */
1182 (void) 0;
1183 } else
1184 switch (persistentConnStatus()) {
1185
1186 case INCOMPLETE_MSG:
bf8fe701 1187 debugs(11, 5, "processReplyBody: INCOMPLETE_MSG");
21b92762 1188 /* Wait for more data or EOF condition */
1189
1190 if (flags.keepalive_broken) {
1191 commSetTimeout(fd, 10, NULL, NULL);
1192 } else {
1193 commSetTimeout(fd, Config.Timeout.read, NULL, NULL);
1194 }
1195
f61f0107 1196 flags.do_next_read = 1;
62e76326 1197 break;
1198
1199 case COMPLETE_PERSISTENT_MSG:
bf8fe701 1200 debugs(11, 5, "processReplyBody: COMPLETE_PERSISTENT_MSG");
62e76326 1201 /* yes we have to clear all these! */
62e76326 1202 commSetTimeout(fd, -1, NULL, NULL);
f61f0107 1203 flags.do_next_read = 0;
62e76326 1204
1205 comm_remove_close_handler(fd, httpStateFree, this);
b6b6f466 1206 fwd->unregister(fd);
fc68f6b1 1207#if LINUX_TPROXY
1208
1209 if (orig_request->flags.tproxy)
1210 client_addr = &orig_request->client_addr;
1211
1212#endif
bd0723ad 1213
1214 if (_peer) {
1215 if (_peer->options.originserver)
fc68f6b1 1216 fwd->pconnPush(fd, _peer->name, orig_request->port, orig_request->host, client_addr);
bd0723ad 1217 else
fc68f6b1 1218 fwd->pconnPush(fd, _peer->name, _peer->http_port, NULL, client_addr);
bd0723ad 1219 } else {
fc68f6b1 1220 fwd->pconnPush(fd, request->host, request->port, NULL, client_addr);
bd0723ad 1221 }
1222
62e76326 1223 fd = -1;
2afaba07 1224
5f8252d2 1225 serverComplete();
62e76326 1226 return;
1227
1228 case COMPLETE_NONPERSISTENT_MSG:
bf8fe701 1229 debugs(11, 5, "processReplyBody: COMPLETE_NONPERSISTENT_MSG");
5f8252d2 1230 serverComplete();
62e76326 1231 return;
1232 }
1233
5f8252d2 1234 maybeReadVirginBody();
c4b7a5a9 1235}
1236
1237void
5f8252d2 1238HttpStateData::maybeReadVirginBody()
c4b7a5a9 1239{
2afaba07 1240 int read_sz = readBuf->spaceSize();
2afaba07 1241
5f8252d2 1242#if ICAP_CLIENT
5f8252d2 1243 if (virginBodyDestination != NULL) {
2afaba07 1244 /*
5f8252d2 1245 * BodyPipe buffer has a finite size limit. We
2afaba07 1246 * should not read more data from the network than will fit
254f3930 1247 * into the pipe buffer or we _lose_ what did not fit if
1248 * the response ends sooner that BodyPipe frees up space:
1249 * There is no code to keep pumping data into the pipe once
1250 * response ends and serverComplete() is called.
1251 *
1252 * If the pipe is totally full, don't register the read handler.
1253 * The BodyPipe will call our noteMoreBodySpaceAvailable() method
1254 * when it has free space again.
2afaba07 1255 */
5f8252d2 1256 int icap_space = virginBodyDestination->buf().potentialSpaceSize();
2afaba07 1257
1258 debugs(11,9, "HttpStateData may read up to min(" << icap_space <<
1259 ", " << read_sz << ") bytes");
1260
1261 if (icap_space < read_sz)
1262 read_sz = icap_space;
1263 }
2afaba07 1264#endif
1265
5f8252d2 1266 debugs(11,9, HERE << (flags.do_next_read ? "may" : "wont") <<
fc68f6b1 1267 " read up to " << read_sz << " bytes from FD " << fd);
2afaba07 1268
1269 /*
1270 * why <2? Because delayAwareRead() won't actually read if
1271 * you ask it to read 1 byte. The delayed read request
1272 * just gets re-queued until the client side drains, then
1273 * the I/O thread hangs. Better to not register any read
1274 * handler until we get a notification from someone that
1275 * its okay to read again.
1276 */
1277 if (read_sz < 2)
1278 return;
1279
f61f0107 1280 if (flags.do_next_read) {
1281 flags.do_next_read = 0;
e5ee81f0 1282 entry->delayAwareRead(fd, readBuf->space(), read_sz, ReadReplyWrapper, this);
528b2c61 1283 }
090089c4 1284}
1285
2afaba07 1286/*
1287 * This will be called when request write is complete.
1288 */
d576a6a6 1289void
2b663917 1290HttpStateData::SendComplete(int fd, char *bufnotused, size_t size, comm_err_t errflag, int xerrno, void *data)
090089c4 1291{
e6ccf245 1292 HttpStateData *httpState = static_cast<HttpStateData *>(data);
4a7a3d56 1293 debugs(11, 5, "httpSendComplete: FD " << fd << ": size " << size << ": errflag " << errflag << ".");
bc87dc25 1294#if URL_CHECKSUM_DEBUG
62e76326 1295
528b2c61 1296 entry->mem_obj->checkUrlChecksum();
bc87dc25 1297#endif
62e76326 1298
ee1679df 1299 if (size > 0) {
62e76326 1300 fd_bytes(fd, size, FD_WRITE);
1301 kb_incr(&statCounter.server.all.kbytes_out, size);
1302 kb_incr(&statCounter.server.http.kbytes_out, size);
ee1679df 1303 }
62e76326 1304
ea3a2a69 1305 if (errflag == COMM_ERR_CLOSING)
62e76326 1306 return;
1307
090089c4 1308 if (errflag) {
6cae5db1 1309 ErrorState *err;
2cc81f1f 1310 err = errorCon(ERR_WRITE_ERROR, HTTP_BAD_GATEWAY, httpState->fwd->request);
2b663917 1311 err->xerrno = xerrno;
b6b6f466 1312 httpState->fwd->fail(err);
62e76326 1313 comm_close(fd);
1314 return;
090089c4 1315 }
72b63f06 1316
2afaba07 1317 /*
1318 * Set the read timeout here because it hasn't been set yet.
1319 * We only set the read timeout after the request has been
1320 * fully written to the server-side. If we start the timeout
1321 * after connection establishment, then we are likely to hit
1322 * the timeout for POST/PUT requests that have very large
1323 * request bodies.
1324 */
1325 commSetTimeout(fd, Config.Timeout.read, httpTimeout, httpState);
1326
72b63f06 1327 httpState->flags.request_sent = 1;
090089c4 1328}
1329
5f8252d2 1330// Close the HTTP server connection. Used by serverComplete().
2afaba07 1331void
5f8252d2 1332HttpStateData::closeServer()
2afaba07 1333{
5f8252d2 1334 debugs(11,5, HERE << "closing HTTP server FD " << fd << " this " << this);
fc68f6b1 1335
2afaba07 1336 if (fd >= 0) {
b6b6f466 1337 fwd->unregister(fd);
2afaba07 1338 comm_remove_close_handler(fd, httpStateFree, this);
1339 comm_close(fd);
1340 fd = -1;
1341 }
5f8252d2 1342}
2afaba07 1343
5f8252d2 1344bool
1345HttpStateData::doneWithServer() const
1346{
1347 return fd < 0;
2afaba07 1348}
1349
99edd1c3 1350/*
1351 * build request headers and append them to a given MemBuf
e5ee81f0 1352 * used by buildRequestPrefix()
818c6c9e 1353 * note: initialised the HttpHeader, the caller is responsible for Clean()-ing
99edd1c3 1354 */
e1e72f06 1355void
e5ee81f0 1356HttpStateData::httpBuildRequestHeader(HttpRequest * request,
1357 HttpRequest * orig_request,
1358 StoreEntry * entry,
1359 HttpHeader * hdr_out,
1360 http_state_flags flags)
6bf8443a 1361{
99edd1c3 1362 /* building buffer for complex strings */
5999b776 1363#define BBUF_SZ (MAX_URL+32)
99edd1c3 1364 LOCAL_ARRAY(char, bbuf, BBUF_SZ);
99edd1c3 1365 const HttpHeader *hdr_in = &orig_request->header;
1366 const HttpHeaderEntry *e;
30abd221 1367 String strFwd;
99edd1c3 1368 HttpHeaderPos pos = HttpHeaderInitPos;
75faaa7a 1369 assert (hdr_out->owner == hoRequest);
99edd1c3 1370 /* append our IMS header */
62e76326 1371
fa3e249f 1372 if (request->lastmod > -1)
a9925b40 1373 hdr_out->putTime(HDR_IF_MODIFIED_SINCE, request->lastmod);
99edd1c3 1374
528b2c61 1375 bool we_do_ranges = decideIfWeDoRanges (orig_request);
1376
30abd221 1377 String strConnection (hdr_in->getList(HDR_CONNECTION));
62e76326 1378
a9925b40 1379 while ((e = hdr_in->getEntry(&pos)))
62e76326 1380 copyOneHeaderFromClientsideRequestToUpstreamRequest(e, strConnection, request, orig_request, hdr_out, we_do_ranges, flags);
528b2c61 1381
43ae1d95 1382 /* Abstraction break: We should interpret multipart/byterange responses
528b2c61 1383 * into offset-length data, and this works around our inability to do so.
1384 */
62e76326 1385 if (!we_do_ranges && orig_request->multipartRangeRequest()) {
1386 /* don't cache the result */
1387 orig_request->flags.cachable = 0;
1388 /* pretend it's not a range request */
00d77d6b 1389 delete orig_request->range;
62e76326 1390 orig_request->range = NULL;
1391 orig_request->flags.range = 0;
1392 }
528b2c61 1393
99edd1c3 1394 /* append Via */
736cb6aa 1395 if (Config.onoff.via) {
30abd221 1396 String strVia;
a9925b40 1397 strVia = hdr_in->getList(HDR_VIA);
62e76326 1398 snprintf(bbuf, BBUF_SZ, "%d.%d %s",
1399 orig_request->http_ver.major,
1400 orig_request->http_ver.minor, ThisCache);
1401 strListAdd(&strVia, bbuf, ',');
30abd221 1402 hdr_out->putStr(HDR_VIA, strVia.buf());
1403 strVia.clean();
736cb6aa 1404 }
62e76326 1405
43ae1d95 1406#if ESI
1407 {
1408 /* Append Surrogate-Capabilities */
30abd221 1409 String strSurrogate (hdr_in->getList(HDR_SURROGATE_CAPABILITY));
ec43ae0e 1410 snprintf(bbuf, BBUF_SZ, "%s=\"Surrogate/1.0 ESI/1.0\"",
43ae1d95 1411 Config.Accel.surrogate_id);
1412 strListAdd(&strSurrogate, bbuf, ',');
30abd221 1413 hdr_out->putStr(HDR_SURROGATE_CAPABILITY, strSurrogate.buf());
43ae1d95 1414 }
1415#endif
1416
99edd1c3 1417 /* append X-Forwarded-For */
a9925b40 1418 strFwd = hdr_in->getList(HDR_X_FORWARDED_FOR);
62e76326 1419
6056ae68 1420 if (opt_forwarded_for && orig_request->client_addr.s_addr != no_addr.s_addr)
62e76326 1421 strListAdd(&strFwd, inet_ntoa(orig_request->client_addr), ',');
6056ae68 1422 else
62e76326 1423 strListAdd(&strFwd, "unknown", ',');
1424
30abd221 1425 hdr_out->putStr(HDR_X_FORWARDED_FOR, strFwd.buf());
62e76326 1426
30abd221 1427 strFwd.clean();
6bccf575 1428
99edd1c3 1429 /* append Host if not there already */
a9925b40 1430 if (!hdr_out->has(HDR_HOST)) {
62e76326 1431 if (orig_request->peer_domain) {
a9925b40 1432 hdr_out->putStr(HDR_HOST, orig_request->peer_domain);
62e76326 1433 } else if (orig_request->port == urlDefaultPort(orig_request->protocol)) {
1434 /* use port# only if not default */
a9925b40 1435 hdr_out->putStr(HDR_HOST, orig_request->host);
62e76326 1436 } else {
1437 httpHeaderPutStrf(hdr_out, HDR_HOST, "%s:%d",
1438 orig_request->host, (int) orig_request->port);
1439 }
6bf8443a 1440 }
62e76326 1441
c68e9c6b 1442 /* append Authorization if known in URL, not in header and going direct */
a9925b40 1443 if (!hdr_out->has(HDR_AUTHORIZATION)) {
62e76326 1444 if (!request->flags.proxying && *request->login) {
1445 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1446 base64_encode(request->login));
1447 }
c68e9c6b 1448 }
62e76326 1449
c68e9c6b 1450 /* append Proxy-Authorization if configured for peer, and proxying */
c3b33cb7 1451 if (request->flags.proxying && orig_request->peer_login &&
a9925b40 1452 !hdr_out->has(HDR_PROXY_AUTHORIZATION)) {
62e76326 1453 if (*orig_request->peer_login == '*') {
1454 /* Special mode, to pass the username to the upstream cache */
1455 char loginbuf[256];
1456 const char *username = "-";
1457
1458 if (orig_request->auth_user_request)
1459 username = orig_request->auth_user_request->username();
abb929f0 1460 else if (orig_request->extacl_user.size())
30abd221 1461 username = orig_request->extacl_user.buf();
62e76326 1462
1463 snprintf(loginbuf, sizeof(loginbuf), "%s%s", username, orig_request->peer_login + 1);
1464
1465 httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Basic %s",
1466 base64_encode(loginbuf));
1467 } else if (strcmp(orig_request->peer_login, "PASS") == 0) {
abb929f0 1468 if (orig_request->extacl_user.size() && orig_request->extacl_passwd.size()) {
1469 char loginbuf[256];
30abd221 1470 snprintf(loginbuf, sizeof(loginbuf), "%s:%s", orig_request->extacl_user.buf(), orig_request->extacl_passwd.buf());
abb929f0 1471 httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Basic %s",
1472 base64_encode(loginbuf));
1473 }
62e76326 1474 } else if (strcmp(orig_request->peer_login, "PROXYPASS") == 0) {
1475 /* Nothing to do */
1476 } else {
1477 httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Basic %s",
1478 base64_encode(orig_request->peer_login));
1479 }
c68e9c6b 1480 }
62e76326 1481
be753325 1482 /* append WWW-Authorization if configured for peer */
1483 if (flags.originpeer && orig_request->peer_login &&
a9925b40 1484 !hdr_out->has(HDR_AUTHORIZATION)) {
62e76326 1485 if (strcmp(orig_request->peer_login, "PASS") == 0) {
1486 /* No credentials to forward.. (should have been done above if available) */
1487 } else if (strcmp(orig_request->peer_login, "PROXYPASS") == 0) {
1488 /* Special mode, convert proxy authentication to WWW authentication
abb929f0 1489 * (also applies to authentication provided by external acl)
62e76326 1490 */
a9925b40 1491 const char *auth = hdr_in->getStr(HDR_PROXY_AUTHORIZATION);
62e76326 1492
1493 if (auth && strncasecmp(auth, "basic ", 6) == 0) {
a9925b40 1494 hdr_out->putStr(HDR_AUTHORIZATION, auth);
abb929f0 1495 } else if (orig_request->extacl_user.size() && orig_request->extacl_passwd.size()) {
1496 char loginbuf[256];
30abd221 1497 snprintf(loginbuf, sizeof(loginbuf), "%s:%s", orig_request->extacl_user.buf(), orig_request->extacl_passwd.buf());
abb929f0 1498 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1499 base64_encode(loginbuf));
62e76326 1500 }
1501 } else if (*orig_request->peer_login == '*') {
1502 /* Special mode, to pass the username to the upstream cache */
1503 char loginbuf[256];
1504 const char *username = "-";
1505
1506 if (orig_request->auth_user_request)
f5691f9c 1507 username = orig_request->auth_user_request->username();
abb929f0 1508 else if (orig_request->extacl_user.size())
30abd221 1509 username = orig_request->extacl_user.buf();
62e76326 1510
1511 snprintf(loginbuf, sizeof(loginbuf), "%s%s", username, orig_request->peer_login + 1);
1512
1513 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1514 base64_encode(loginbuf));
1515 } else {
1516 /* Fixed login string */
1517 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1518 base64_encode(orig_request->peer_login));
1519 }
be753325 1520 }
62e76326 1521
abb929f0 1522 /* append Cache-Control, add max-age if not there already */ {
a9925b40 1523 HttpHdrCc *cc = hdr_in->getCc();
62e76326 1524
1525 if (!cc)
1526 cc = httpHdrCcCreate();
1527
1528 if (!EBIT_TEST(cc->mask, CC_MAX_AGE)) {
43ae1d95 1529 const char *url =
3900307b 1530 entry ? entry->url() : urlCanonical(orig_request);
62e76326 1531 httpHdrCcSetMaxAge(cc, getMaxAge(url));
1532
1533 if (request->urlpath.size())
30abd221 1534 assert(strstr(url, request->urlpath.buf()));
62e76326 1535 }
1536
ce2d6441 1537 /* Set no-cache if determined needed but not found */
a9925b40 1538 if (orig_request->flags.nocache && !hdr_in->has(HDR_PRAGMA))
ce2d6441 1539 EBIT_SET(cc->mask, CC_NO_CACHE);
1540
1541 /* Enforce sibling relations */
62e76326 1542 if (flags.only_if_cached)
1543 EBIT_SET(cc->mask, CC_ONLY_IF_CACHED);
1544
a9925b40 1545 hdr_out->putCc(cc);
62e76326 1546
1547 httpHdrCcDestroy(cc);
6bf8443a 1548 }
62e76326 1549
99edd1c3 1550 /* maybe append Connection: keep-alive */
b515fc11 1551 if (flags.keepalive) {
62e76326 1552 if (flags.proxying) {
a9925b40 1553 hdr_out->putStr(HDR_PROXY_CONNECTION, "keep-alive");
62e76326 1554 } else {
a9925b40 1555 hdr_out->putStr(HDR_CONNECTION, "keep-alive");
62e76326 1556 }
603a02fd 1557 }
62e76326 1558
a7ad6e4e 1559 /* append Front-End-Https */
1560 if (flags.front_end_https) {
62e76326 1561 if (flags.front_end_https == 1 || request->protocol == PROTO_HTTPS)
a9925b40 1562 hdr_out->putStr(HDR_FRONT_END_HTTPS, "On");
a7ad6e4e 1563 }
1564
6bccf575 1565 /* Now mangle the headers. */
4f56514c 1566 if (Config2.onoff.mangle_request_headers)
5967c0bf 1567 httpHdrMangleList(hdr_out, request, ROR_REQUEST);
62e76326 1568
30abd221 1569 strConnection.clean();
99edd1c3 1570}
1571
528b2c61 1572void
30abd221 1573copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, String strConnection, HttpRequest * request, HttpRequest * orig_request, HttpHeader * hdr_out, int we_do_ranges, http_state_flags flags)
528b2c61 1574{
30abd221 1575 debugs(11, 5, "httpBuildRequestHeader: " << e->name.buf() << ": " << e->value.buf());
62e76326 1576
528b2c61 1577 if (!httpRequestHdrAllowed(e, &strConnection)) {
30abd221 1578 debugs(11, 2, "'" << e->name.buf() << "' header denied by anonymize_headers configuration");
62e76326 1579 return;
528b2c61 1580 }
62e76326 1581
528b2c61 1582 switch (e->id) {
62e76326 1583
be753325 1584 case HDR_PROXY_AUTHORIZATION:
62e76326 1585 /* Only pass on proxy authentication to peers for which
1586 * authentication forwarding is explicitly enabled
1587 */
1588
1589 if (flags.proxying && orig_request->peer_login &&
abb929f0 1590 (strcmp(orig_request->peer_login, "PASS") == 0 ||
1591 strcmp(orig_request->peer_login, "PROXYPASS") == 0)) {
eede25e7 1592 hdr_out->addEntry(e->clone());
62e76326 1593 }
1594
1595 break;
1596
be753325 1597 case HDR_AUTHORIZATION:
62e76326 1598 /* Pass on WWW authentication */
1599
1600 if (!flags.originpeer) {
eede25e7 1601 hdr_out->addEntry(e->clone());
62e76326 1602 } else {
1603 /* In accelerators, only forward authentication if enabled
1604 * (see also below for proxy->server authentication)
1605 */
1606
abb929f0 1607 if (orig_request->peer_login &&
1608 (strcmp(orig_request->peer_login, "PASS") == 0 ||
1609 strcmp(orig_request->peer_login, "PROXYPASS") == 0)) {
eede25e7 1610 hdr_out->addEntry(e->clone());
62e76326 1611 }
1612 }
1613
1614 break;
1615
be753325 1616 case HDR_HOST:
62e76326 1617 /*
b883b594 1618 * Normally Squid rewrites the Host: header.
1619 * However, there is one case when we don't: If the URL
62e76326 1620 * went through our redirector and the admin configured
1621 * 'redir_rewrites_host' to be off.
1622 */
1623
b883b594 1624 if (request->flags.redirected && !Config.onoff.redir_rewrites_host)
eede25e7 1625 hdr_out->addEntry(e->clone());
b883b594 1626 else {
1627 /* use port# only if not default */
1628
1629 if (orig_request->port == urlDefaultPort(orig_request->protocol)) {
a9925b40 1630 hdr_out->putStr(HDR_HOST, orig_request->host);
b883b594 1631 } else {
1632 httpHeaderPutStrf(hdr_out, HDR_HOST, "%s:%d",
1633 orig_request->host, (int) orig_request->port);
1634 }
1635 }
62e76326 1636
1637 break;
1638
be753325 1639 case HDR_IF_MODIFIED_SINCE:
62e76326 1640 /* append unless we added our own;
1641 * note: at most one client's ims header can pass through */
b883b594 1642
a9925b40 1643 if (!hdr_out->has(HDR_IF_MODIFIED_SINCE))
eede25e7 1644 hdr_out->addEntry(e->clone());
62e76326 1645
1646 break;
1647
be753325 1648 case HDR_MAX_FORWARDS:
62e76326 1649 if (orig_request->method == METHOD_TRACE) {
eede25e7 1650 const int hops = e->getInt();
62e76326 1651
1652 if (hops > 0)
a9925b40 1653 hdr_out->putInt(HDR_MAX_FORWARDS, hops - 1);
62e76326 1654 }
1655
1656 break;
1657
be753325 1658 case HDR_VIA:
62e76326 1659 /* If Via is disabled then forward any received header as-is */
1660
1661 if (!Config.onoff.via)
eede25e7 1662 hdr_out->addEntry(e->clone());
62e76326 1663
1664 break;
1665
be753325 1666 case HDR_RANGE:
62e76326 1667
be753325 1668 case HDR_IF_RANGE:
62e76326 1669
be753325 1670 case HDR_REQUEST_RANGE:
62e76326 1671 if (!we_do_ranges)
eede25e7 1672 hdr_out->addEntry(e->clone());
62e76326 1673
1674 break;
1675
be753325 1676 case HDR_PROXY_CONNECTION:
62e76326 1677
be753325 1678 case HDR_CONNECTION:
62e76326 1679
be753325 1680 case HDR_X_FORWARDED_FOR:
62e76326 1681
be753325 1682 case HDR_CACHE_CONTROL:
62e76326 1683 /* append these after the loop if needed */
1684 break;
1685
be753325 1686 case HDR_FRONT_END_HTTPS:
62e76326 1687 if (!flags.front_end_https)
eede25e7 1688 hdr_out->addEntry(e->clone());
62e76326 1689
1690 break;
1691
be753325 1692 default:
62e76326 1693 /* pass on all other header fields */
eede25e7 1694 hdr_out->addEntry(e->clone());
528b2c61 1695 }
1696}
1697
e5ee81f0 1698bool
1699HttpStateData::decideIfWeDoRanges (HttpRequest * orig_request)
528b2c61 1700{
e5ee81f0 1701 bool result = true;
62e76326 1702 /* decide if we want to do Ranges ourselves
1703 * and fetch the whole object now)
1704 * We want to handle Ranges ourselves iff
1705 * - we can actually parse client Range specs
1706 * - the specs are expected to be simple enough (e.g. no out-of-order ranges)
1707 * - reply will be cachable
1708 * (If the reply will be uncachable we have to throw it away after
1709 * serving this request, so it is better to forward ranges to
1710 * the server and fetch only the requested content)
1711 */
1712
1713 if (NULL == orig_request->range || !orig_request->flags.cachable
1714 || orig_request->range->offsetLimitExceeded())
e5ee81f0 1715 result = false;
62e76326 1716
bf8fe701 1717 debugs(11, 8, "decideIfWeDoRanges: range specs: " <<
1718 orig_request->range << ", cachable: " <<
1719 orig_request->flags.cachable << "; we_do_ranges: " << result);
62e76326 1720
1721 return result;
528b2c61 1722}
1723
62e76326 1724/* build request prefix and append it to a given MemBuf;
99edd1c3 1725 * return the length of the prefix */
9bc73deb 1726mb_size_t
e5ee81f0 1727HttpStateData::buildRequestPrefix(HttpRequest * request,
1728 HttpRequest * orig_request,
1729 StoreEntry * entry,
1730 MemBuf * mb,
1731 http_state_flags flags)
99edd1c3 1732{
1733 const int offset = mb->size;
450e0c10 1734 HttpVersion httpver(1, 0);
2fe7eff9 1735 mb->Printf("%s %s HTTP/%d.%d\r\n",
1736 RequestMethodStr[request->method],
30abd221 1737 request->urlpath.size() ? request->urlpath.buf() : "/",
2fe7eff9 1738 httpver.major,httpver.minor);
99edd1c3 1739 /* build and pack headers */
1740 {
75faaa7a 1741 HttpHeader hdr(hoRequest);
62e76326 1742 Packer p;
1743 httpBuildRequestHeader(request, orig_request, entry, &hdr, flags);
1744 packerToMemInit(&p, mb);
a9925b40 1745 hdr.packInto(&p);
519e0948 1746 hdr.clean();
62e76326 1747 packerClean(&p);
9d9d144b 1748 }
99edd1c3 1749 /* append header terminator */
2fe7eff9 1750 mb->append(crlf, 2);
99edd1c3 1751 return mb->size - offset;
6bf8443a 1752}
62e76326 1753
090089c4 1754/* This will be called when connect completes. Write request. */
5f8252d2 1755bool
2bb867b5 1756HttpStateData::sendRequest()
090089c4 1757{
99edd1c3 1758 MemBuf mb;
090089c4 1759
bf8fe701 1760 debugs(11, 5, "httpSendRequest: FD " << fd << ", request " << request << ", this " << this << ".");
090089c4 1761
2bb867b5 1762 commSetTimeout(fd, Config.Timeout.lifetime, httpTimeout, this);
1763 flags.do_next_read = 1;
5f8252d2 1764 maybeReadVirginBody();
1765
1766 if (orig_request->body_pipe != NULL) {
1767 requestBodySource = orig_request->body_pipe;
fc68f6b1 1768
5f8252d2 1769 if (!requestBodySource->setConsumerIfNotLate(this)) {
1770 debugs(32,3, HERE << "aborting on partially consumed body");
1771 requestBodySource = NULL;
1772 return false;
1773 }
fc68f6b1 1774
5f8252d2 1775 requestSender = HttpStateData::sentRequestBodyWrapper;
1776 debugs(32,3, HERE << "expecting request body on pipe " << requestBodySource);
1777 } else {
1778 assert(!requestBodySource);
1779 requestSender = HttpStateData::SendComplete;
1780 }
54220df8 1781
2bb867b5 1782 if (_peer != NULL) {
1783 if (_peer->options.originserver) {
1784 flags.proxying = 0;
1785 flags.originpeer = 1;
62e76326 1786 } else {
2bb867b5 1787 flags.proxying = 1;
1788 flags.originpeer = 0;
62e76326 1789 }
be753325 1790 } else {
2bb867b5 1791 flags.proxying = 0;
1792 flags.originpeer = 0;
be753325 1793 }
62e76326 1794
efb9218c 1795 /*
99edd1c3 1796 * Is keep-alive okay for all request methods?
efb9218c 1797 */
efd900cb 1798 if (!Config.onoff.server_pconns)
2bb867b5 1799 flags.keepalive = 0;
1800 else if (_peer == NULL)
1801 flags.keepalive = 1;
1802 else if (_peer->stats.n_keepalives_sent < 10)
1803 flags.keepalive = 1;
1804 else if ((double) _peer->stats.n_keepalives_recv /
1805 (double) _peer->stats.n_keepalives_sent > 0.50)
1806 flags.keepalive = 1;
1807
1808 if (_peer) {
1809 if (neighborType(_peer, request) == PEER_SIBLING &&
1810 !_peer->options.allow_miss)
1811 flags.only_if_cached = 1;
1812
1813 flags.front_end_https = _peer->front_end_https;
a7ad6e4e 1814 }
62e76326 1815
2fe7eff9 1816 mb.init();
e5ee81f0 1817 buildRequestPrefix(request, orig_request, entry, &mb, flags);
bf8fe701 1818 debugs(11, 6, "httpSendRequest: FD " << fd << ":\n" << mb.buf);
5f8252d2 1819 comm_write_mbuf(fd, &mb, requestSender, this);
1820
1821 return true;
090089c4 1822}
b6a2f15e 1823
910169e5 1824void
b6b6f466 1825httpStart(FwdState *fwd)
603a02fd 1826{
bf8fe701 1827 debugs(11, 3, "httpStart: \"" << RequestMethodStr[fwd->request->method] << " " << fwd->entry->url() << "\"" );
a3d50c30 1828 HttpStateData *httpState = new HttpStateData(fwd);
62e76326 1829
5f8252d2 1830 if (!httpState->sendRequest()) {
bf8fe701 1831 debugs(11, 3, "httpStart: aborted");
5f8252d2 1832 delete httpState;
1833 return;
1834 }
62e76326 1835
5f8252d2 1836 statCounter.server.all.requests++;
83704487 1837 statCounter.server.http.requests++;
62e76326 1838
b6a2f15e 1839 /*
1840 * We used to set the read timeout here, but not any more.
1841 * Now its set in httpSendComplete() after the full request,
1842 * including request body, has been written to the server.
1843 */
090089c4 1844}
1845
2bb867b5 1846void
5f8252d2 1847HttpStateData::doneSendingRequestBody()
2bb867b5 1848{
4fb35c3c 1849 ACLChecklist ch;
5f8252d2 1850 debugs(11,5, HERE << "doneSendingRequestBody: FD " << fd);
6dd9f4bd 1851 ch.request = HTTPMSGLOCK(request);
506768d9 1852
1853 if (Config.accessList.brokenPosts)
1854 ch.accessList = cbdataReference(Config.accessList.brokenPosts);
62e76326 1855
108d65b2 1856 /* cbdataReferenceDone() happens in either fastCheck() or ~ACLCheckList */
1857
94439e4e 1858 if (!Config.accessList.brokenPosts) {
bf8fe701 1859 debugs(11, 5, "doneSendingRequestBody: No brokenPosts list");
2b663917 1860 HttpStateData::SendComplete(fd, NULL, 0, COMM_OK, 0, this);
b448c119 1861 } else if (!ch.fastCheck()) {
bf8fe701 1862 debugs(11, 5, "doneSendingRequestBody: didn't match brokenPosts");
2b663917 1863 HttpStateData::SendComplete(fd, NULL, 0, COMM_OK, 0, this);
94439e4e 1864 } else {
bf8fe701 1865 debugs(11, 2, "doneSendingRequestBody: matched brokenPosts");
2b663917 1866 comm_write(fd, "\r\n", 2, HttpStateData::SendComplete, this, NULL);
54220df8 1867 }
94439e4e 1868}
1869
5f8252d2 1870// more origin request body data is available
2bb867b5 1871void
5f8252d2 1872HttpStateData::handleMoreRequestBodyAvailable()
2bb867b5 1873{
2bb867b5 1874 if (eof || fd < 0) {
5f8252d2 1875 // XXX: we should check this condition in other callbacks then!
1876 // TODO: Check whether this can actually happen: We should unsubscribe
1877 // as a body consumer when the above condition(s) are detected.
2bb867b5 1878 debugs(11, 1, HERE << "Transaction aborted while reading HTTP body");
2bb867b5 1879 return;
1880 }
62e76326 1881
5f8252d2 1882 assert(requestBodySource != NULL);
fc68f6b1 1883
5f8252d2 1884 if (requestBodySource->buf().hasContent()) {
1885 // XXX: why does not this trigger a debug message on every request?
fc68f6b1 1886
2bb867b5 1887 if (flags.headers_parsed && !flags.abuse_detected) {
1888 flags.abuse_detected = 1;
bf8fe701 1889 debugs(11, 1, "http handleMoreRequestBodyAvailable: Likely proxy abuse detected '" << inet_ntoa(orig_request->client_addr) << "' -> '" << entry->url() << "'" );
21b92762 1890
2bb867b5 1891 if (getReply()->sline.status == HTTP_INVALID_HEADER) {
2bb867b5 1892 comm_close(fd);
21b92762 1893 return;
1894 }
1895 }
b6a2f15e 1896 }
5f8252d2 1897
1898 HttpStateData::handleMoreRequestBodyAvailable();
376bb137 1899}
1900
5f8252d2 1901// premature end of the request body
2bb867b5 1902void
5f8252d2 1903HttpStateData::handleRequestBodyProducerAborted()
376bb137 1904{
5f8252d2 1905 ServerStateData::handleRequestBodyProducerAborted();
1906 // XXX: SendComplete(COMM_ERR_CLOSING) does little. Is it enough?
1907 SendComplete(fd, NULL, 0, COMM_ERR_CLOSING, 0, this);
2bb867b5 1908}
1909
5f8252d2 1910// called when we wrote request headers(!) or a part of the body
2bb867b5 1911void
5f8252d2 1912HttpStateData::sentRequestBody(int fd, size_t size, comm_err_t errflag)
2bb867b5 1913{
5f8252d2 1914 if (size > 0)
62e76326 1915 kb_incr(&statCounter.server.http.kbytes_out, size);
fc68f6b1 1916
5f8252d2 1917 ServerStateData::sentRequestBody(fd, size, errflag);
1918}
3b299123 1919
5f8252d2 1920// Quickly abort the transaction
1921// TODO: destruction should be sufficient as the destructor should cleanup,
1922// including canceling close handlers
1923void
1924HttpStateData::abortTransaction(const char *reason)
1925{
1926 debugs(11,5, HERE << "aborting transaction for " << reason <<
1927 "; FD " << fd << ", this " << this);
fc68f6b1 1928
3e8c047e 1929 if (fd >= 0) {
62e76326 1930 comm_close(fd);
3e8c047e 1931 return;
c23f0c74 1932 }
3e8c047e 1933
1934 fwd->handleUnregisteredServerEnd();
1935 delete this;
54220df8 1936}
ccf44862 1937
1938void
450e0c10 1939httpBuildVersion(HttpVersion * version, unsigned int major, unsigned int minor)
110eb4e5 1940{
1941 version->major = major;
1942 version->minor = minor;
ccf44862 1943}
2afaba07 1944
1945#if ICAP_CLIENT
1946
1947static void
1948icapAclCheckDoneWrapper(ICAPServiceRep::Pointer service, void *data)
1949{
1950 HttpStateData *http = (HttpStateData *)data;
1951 http->icapAclCheckDone(service);
1952}
1953
7c4e4e7f 1954// TODO: why does FtpStateData not need orig_request?
1955HttpRequest *
1956HttpStateData::originalRequest()
2afaba07 1957{
7c4e4e7f 1958 return orig_request;
2afaba07 1959}
1960
2afaba07 1961#endif