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