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