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