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