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