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