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