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