]> git.ipfire.org Git - thirdparty/squid.git/blame - src/http.cc
Documentation updates
[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.
9e008dda 24 *
30a4f2a8 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.
9e008dda 29 *
30a4f2a8 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; \
9e008dda 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,
9e008dda 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",
9e008dda 137 Dialer(this,&HttpStateData::httpStateConnClosed));
dc56a9b1 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
9e008dda
AJ
152 if (httpChunkDecoder)
153 delete httpChunkDecoder;
af0bb8e5 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
9e008dda 174void
dc56a9b1 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
9e008dda 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
d67acb4e 386 if (request->flags.auth || request->flags.auth_sent) {
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/*
9e008dda 549 * For Vary, store the relevant request headers as
f66a9ef4 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
9e008dda
AJ
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;
685 } else {
686 if (!parsed && error > 0) { // unrecoverable parsing error
687 debugs(11, 3, "processReplyHeader: Non-HTTP-compliant header: '" << readBuf->content() << "'");
688 flags.headers_parsed = 1;
689 newrep->sline.version = HttpVersion(1, 0);
690 newrep->sline.status = error;
691 HttpReply *vrep = setVirginReply(newrep);
692 entry->replaceHttpReply(vrep);
693 ctx_exit(ctx);
694 return;
695 }
696
697 if (!parsed) { // need more data
698 assert(!error);
699 assert(!eof);
700 delete newrep;
701 ctx_exit(ctx);
702 return;
703 }
704
705 debugs(11, 9, "GOT HTTP REPLY HDR:\n---------\n" << readBuf->content() << "\n----------");
706
707 header_bytes_read = headersEnd(readBuf->content(), readBuf->contentSize());
708 readBuf->consume(header_bytes_read);
f5558c95 709 }
62e76326 710
af0bb8e5 711 flags.chunked = 0;
712 if (newrep->header.hasListMember(HDR_TRANSFER_ENCODING, "chunked", ',')) {
9e008dda
AJ
713 flags.chunked = 1;
714 httpChunkDecoder = new ChunkedCodingParser;
af0bb8e5 715 }
716
9e008dda
AJ
717 if (!peerSupportsConnectionPinning())
718 orig_request->flags.connection_auth_disabled = 1;
d67acb4e 719
585ab260 720 HttpReply *vrep = setVirginReply(newrep);
6965ab28 721 flags.headers_parsed = 1;
722
585ab260 723 keepaliveAccounting(vrep);
47ac2ebe 724
585ab260 725 checkDateSkew(vrep);
47ac2ebe 726
585ab260 727 processSurrogateControl (vrep);
528b2c61 728
073ba374 729 /** \todo IF the reply is a 1.0 reply, AND it has a Connection: Header
528b2c61 730 * Parse the header and remove all referenced headers
731 */
732
2afaba07 733 ctx_exit(ctx);
7dc79973 734
2afaba07 735}
736
d67acb4e
AJ
737/**
738 * returns true if the peer can support connection pinning
739*/
740bool HttpStateData::peerSupportsConnectionPinning() const
741{
742 const HttpReply *rep = entry->mem_obj->getReply();
743 const HttpHeader *hdr = &rep->header;
744 bool rc;
745 String header;
746
747 if (!_peer)
9e008dda
AJ
748 return true;
749
750 /*If this peer does not support connection pinning (authenticated
d67acb4e
AJ
751 connections) return false
752 */
753 if (!_peer->connection_auth)
9e008dda 754 return false;
d67acb4e 755
9e008dda 756 /*The peer supports connection pinning and the http reply status
d67acb4e
AJ
757 is not unauthorized, so the related connection can be pinned
758 */
759 if (rep->sline.status != HTTP_UNAUTHORIZED)
9e008dda
AJ
760 return true;
761
762 /*The server respond with HTTP_UNAUTHORIZED and the peer configured
763 with "connection-auth=on" we know that the peer supports pinned
d67acb4e
AJ
764 connections
765 */
766 if (_peer->connection_auth == 1)
9e008dda 767 return true;
d67acb4e 768
9e008dda
AJ
769 /*At this point peer has configured with "connection-auth=auto"
770 parameter so we need some extra checks to decide if we are going
d67acb4e
AJ
771 to allow pinned connections or not
772 */
773
9e008dda 774 /*if the peer configured with originserver just allow connection
d67acb4e
AJ
775 pinning (squid 2.6 behaviour)
776 */
777 if (_peer->options.originserver)
9e008dda 778 return true;
d67acb4e
AJ
779
780 /*if the connections it is already pinned it is OK*/
781 if (request->flags.pinned)
9e008dda
AJ
782 return true;
783
784 /*Allow pinned connections only if the Proxy-support header exists in
785 reply and has in its list the "Session-Based-Authentication"
d67acb4e
AJ
786 which means that the peer supports connection pinning.
787 */
788 if (!hdr->has(HDR_PROXY_SUPPORT))
9e008dda 789 return false;
d67acb4e
AJ
790
791 header = hdr->getStrOrList(HDR_PROXY_SUPPORT);
792 /* XXX This ought to be done in a case-insensitive manner */
793 rc = (strstr(header.buf(), "Session-Based-Authentication") != NULL);
794
795 return rc;
796}
797
5f8252d2 798// Called when we parsed (and possibly adapted) the headers but
799// had not starting storing (a.k.a., sending) the body yet.
2afaba07 800void
801HttpStateData::haveParsedReplyHeaders()
802{
c1520b67
AJ
803 ServerStateData::haveParsedReplyHeaders();
804
2afaba07 805 Ctx ctx = ctx_enter(entry->mem_obj->url);
585ab260 806 HttpReply *rep = finalReply();
2afaba07 807
585ab260 808 if (rep->sline.status == HTTP_PARTIAL_CONTENT &&
809 rep->content_range)
810 currentOffset = rep->content_range->spec.offset;
62e76326 811
3900307b 812 entry->timestampsSet();
62e76326 813
9bc73deb 814 /* Check if object is cacheable or not based on reply code */
585ab260 815 debugs(11, 3, "haveParsedReplyHeaders: HTTP CODE: " << rep->sline.status);
62e76326 816
9bc73deb 817 if (neighbors_do_private_keys)
585ab260 818 httpMaybeRemovePublic(entry, rep->sline.status);
e6ccf245 819
585ab260 820 if (rep->header.has(HDR_VARY)
f66a9ef4 821#if X_ACCELERATOR_VARY
585ab260 822 || rep->header.has(HDR_X_ACCELERATOR_VARY)
f66a9ef4 823#endif
4b44c907 824 ) {
585ab260 825 const char *vary = httpMakeVaryMark(orig_request, rep);
4b44c907 826
827 if (!vary) {
5ed72359 828 entry->makePrivate();
4b44c907 829 goto no_cache;
830
62e76326 831 }
832
4b44c907 833 entry->mem_obj->vary_headers = xstrdup(vary);
834 }
835
2afaba07 836#if WIP_FWD_LOG
837 fwdStatus(fwd, s);
838
839#endif
840 /*
841 * If its not a reply that we will re-forward, then
842 * allow the client to get it.
843 */
585ab260 844 if (!fwd->reforwardableStatus(rep->sline.status))
2afaba07 845 EBIT_CLR(entry->flags, ENTRY_FWD_HDR_WAIT);
846
4b44c907 847 switch (cacheableReply()) {
848
849 case 1:
5ed72359 850 entry->makePublic();
62e76326 851 break;
852
9bc73deb 853 case 0:
5ed72359 854 entry->makePrivate();
62e76326 855 break;
856
9bc73deb 857 case -1:
4b44c907 858
ac9cc053 859#if HTTP_VIOLATIONS
4b44c907 860 if (Config.negativeTtl > 0)
5ed72359 861 entry->cacheNegatively();
4b44c907 862 else
ac9cc053 863#endif
5ed72359 864 entry->makePrivate();
4b44c907 865
62e76326 866 break;
867
9bc73deb 868 default:
62e76326 869 assert(0);
4b44c907 870
62e76326 871 break;
9bc73deb 872 }
62e76326 873
4b44c907 874no_cache:
875
585ab260 876 if (!ignoreCacheControl && rep->cache_control) {
877 if (EBIT_TEST(rep->cache_control->mask, CC_PROXY_REVALIDATE))
62e76326 878 EBIT_SET(entry->flags, ENTRY_REVALIDATE);
585ab260 879 else if (EBIT_TEST(rep->cache_control->mask, CC_MUST_REVALIDATE))
62e76326 880 EBIT_SET(entry->flags, ENTRY_REVALIDATE);
9bc73deb 881 }
62e76326 882
c3609322 883#if HEADERS_LOG
585ab260 884 headersLog(1, 0, request->method, rep);
fc68f6b1 885
c3609322 886#endif
5f8252d2 887
888 ctx_exit(ctx);
f5558c95 889}
890
528b2c61 891HttpStateData::ConnectionStatus
892HttpStateData::statusIfComplete() const
603a02fd 893{
585ab260 894 const HttpReply *rep = virginReply();
073ba374
AJ
895 /** \par
896 * If the reply wants to close the connection, it takes precedence */
62e76326 897
2afaba07 898 if (httpHeaderHasConnDir(&rep->header, "close"))
62e76326 899 return COMPLETE_NONPERSISTENT_MSG;
900
073ba374
AJ
901 /** \par
902 * If we didn't send a keep-alive request header, then this
978e455f 903 * can not be a persistent connection.
904 */
528b2c61 905 if (!flags.keepalive)
62e76326 906 return COMPLETE_NONPERSISTENT_MSG;
907
073ba374 908 /** \par
72b63f06 909 * If we haven't sent the whole request then this can not be a persistent
910 * connection.
911 */
912 if (!flags.request_sent) {
60745f24 913 debugs(11, 1, "statusIfComplete: Request not yet fully sent \"" << RequestMethodStr(orig_request->method) << " " << entry->url() << "\"" );
72b63f06 914 return COMPLETE_NONPERSISTENT_MSG;
915 }
916
073ba374 917 /** \par
9f5a2895 918 * What does the reply have to say about keep-alive?
919 */
073ba374
AJ
920 /**
921 \bug XXX BUG?
b6a2f15e 922 * If the origin server (HTTP/1.0) does not send a keep-alive
923 * header, but keeps the connection open anyway, what happens?
924 * We'll return here and http.c waits for an EOF before changing
925 * store_status to STORE_OK. Combine this with ENTRY_FWD_HDR_WAIT
926 * and an error status code, and we might have to wait until
927 * the server times out the socket.
928 */
2afaba07 929 if (!rep->keep_alive)
528b2c61 930 return COMPLETE_NONPERSISTENT_MSG;
62e76326 931
528b2c61 932 return COMPLETE_PERSISTENT_MSG;
933}
934
935HttpStateData::ConnectionStatus
936HttpStateData::persistentConnStatus() const
937{
ba82c452 938 debugs(11, 3, "persistentConnStatus: FD " << fd << " eof=" << eof);
585ab260 939 const HttpReply *vrep = virginReply();
940 debugs(11, 5, "persistentConnStatus: content_length=" << vrep->content_length);
62e76326 941
5f8252d2 942 /* If we haven't seen the end of reply headers, we are not done */
bf8fe701 943 debugs(11, 5, "persistentConnStatus: flags.headers_parsed=" << flags.headers_parsed);
fc68f6b1 944
1a98175f 945 if (!flags.headers_parsed)
62e76326 946 return INCOMPLETE_MSG;
947
839291ac
AJ
948 if (eof) // already reached EOF
949 return COMPLETE_NONPERSISTENT_MSG;
950
9035d1d5
AJ
951 /** \par
952 * In chunked response we do not know the content length but we are absolutely
af0bb8e5 953 * sure about the end of response, so we are calling the statusIfComplete to
9e008dda 954 * decide if we can be persistant
af0bb8e5 955 */
839291ac 956 if (lastChunk && flags.chunked)
9e008dda 957 return statusIfComplete();
af0bb8e5 958
47f6e231 959 const int64_t clen = vrep->bodySize(request->method);
fc68f6b1 960
bf8fe701 961 debugs(11, 5, "persistentConnStatus: clen=" << clen);
2afaba07 962
35282fbf 963 /* If the body size is unknown we must wait for EOF */
964 if (clen < 0)
62e76326 965 return INCOMPLETE_MSG;
966
9035d1d5
AJ
967 /** \par
968 * If the body size is known, we must wait until we've gotten all of it. */
5f8252d2 969 if (clen > 0) {
970 // old technique:
585ab260 971 // if (entry->mem_obj->endOffset() < vrep->content_length + vrep->hdr_sz)
47f6e231 972 const int64_t body_bytes_read = reply_bytes_read - header_bytes_read;
5f8252d2 973 debugs(11,5, "persistentConnStatus: body_bytes_read=" <<
585ab260 974 body_bytes_read << " content_length=" << vrep->content_length);
2afaba07 975
585ab260 976 if (body_bytes_read < vrep->content_length)
5f8252d2 977 return INCOMPLETE_MSG;
978 }
62e76326 979
9035d1d5
AJ
980 /** \par
981 * If there is no message body or we got it all, we can be persistent */
5f8252d2 982 return statusIfComplete();
603a02fd 983}
090089c4 984
2afaba07 985/*
986 * This is the callback after some data has been read from the network
987 */
dc56a9b1 988/*
e5ee81f0 989void
990HttpStateData::ReadReplyWrapper(int fd, char *buf, size_t len, comm_err_t flag, int xerrno, void *data)
c4b7a5a9 991{
992 HttpStateData *httpState = static_cast<HttpStateData *>(data);
7194987f 993 assert (fd == httpState->fd);
2afaba07 994 // assert(buf == readBuf->content());
1d5161bd 995 PROF_start(HttpStateData_readReply);
2afaba07 996 httpState->readReply (len, flag, xerrno);
1d5161bd 997 PROF_stop(HttpStateData_readReply);
c4b7a5a9 998}
dc56a9b1 999*/
073ba374 1000
2afdbf48 1001/* XXX this function is too long! */
c4b7a5a9 1002void
dc56a9b1 1003HttpStateData::readReply (const CommIoCbParams &io)
090089c4 1004{
30a4f2a8 1005 int bin;
090089c4 1006 int clen;
dc56a9b1 1007 int len = io.size;
c4b7a5a9 1008
dc56a9b1 1009 assert(fd == io.fd);
1010
1011 flags.do_next_read = 0;
9e008dda 1012
7a7cc03f 1013 debugs(11, 5, "httpReadReply: FD " << fd << ": len " << len << ".");
62e76326 1014
7a7cc03f 1015 // Bail out early on COMM_ERR_CLOSING - close handlers will tidy up for us
dc56a9b1 1016 if (io.flag == COMM_ERR_CLOSING) {
bf8fe701 1017 debugs(11, 3, "http socket closing");
c4b7a5a9 1018 return;
1019 }
1020
e92e4e44 1021 if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
5f8252d2 1022 maybeReadVirginBody();
62e76326 1023 return;
e92e4e44 1024 }
c4b7a5a9 1025
fdf55365 1026 // handle I/O errors
dc56a9b1 1027 if (io.flag != COMM_OK || len < 0) {
7a7cc03f 1028 debugs(11, 2, "httpReadReply: FD " << fd << ": read failure: " << xstrerror() << ".");
fdf55365 1029
dc56a9b1 1030 if (ignoreErrno(io.xerrno)) {
fdf55365 1031 flags.do_next_read = 1;
1032 } else {
1033 ErrorState *err;
1034 err = errorCon(ERR_READ_ERROR, HTTP_BAD_GATEWAY, fwd->request);
dc56a9b1 1035 err->xerrno = io.xerrno;
fdf55365 1036 fwd->fail(err);
1037 flags.do_next_read = 0;
1038 comm_close(fd);
1039 }
1040
1041 return;
1042 }
1043
7a7cc03f 1044 // update I/O stats
fdf55365 1045 if (len > 0) {
2afaba07 1046 readBuf->appended(len);
5f8252d2 1047 reply_bytes_read += len;
447e176b 1048#if DELAY_POOLS
2afaba07 1049
1050 DelayId delayId = entry->mem_obj->mostBytesAllowed();
62e76326 1051 delayId.bytesIn(len);
447e176b 1052#endif
62e76326 1053
1054 kb_incr(&statCounter.server.all.kbytes_in, len);
1055 kb_incr(&statCounter.server.http.kbytes_in, len);
62e76326 1056 IOStats.Http.reads++;
1057
1058 for (clen = len - 1, bin = 0; clen; bin++)
1059 clen >>= 1;
1060
1061 IOStats.Http.read_hist[bin]++;
30a4f2a8 1062 }
62e76326 1063
073ba374
AJ
1064 /** \par
1065 * Here the RFC says we should ignore whitespace between replies, but we can't as
5fa061b8 1066 * doing so breaks HTTP/0.9 replies beginning with witespace, and in addition
1067 * the response splitting countermeasures is extremely likely to trigger on this,
1068 * not allowing connection reuse in the first place.
1069 */
1070#if DONT_DO_THIS
fdf55365 1071 if (!flags.headers_parsed && len > 0 && fd_table[fd].uses > 1) {
5fa061b8 1072 /* Skip whitespace between replies */
62e76326 1073
e4755e29 1074 while (len > 0 && xisspace(*buf))
62e76326 1075 xmemmove(buf, buf + 1, len--);
1076
1077 if (len == 0) {
1078 /* Continue to read... */
21b92762 1079 /* Timeout NOT increased. This whitespace was from previous reply */
f61f0107 1080 flags.do_next_read = 1;
5f8252d2 1081 maybeReadVirginBody();
62e76326 1082 return;
1083 }
5ede6c8f 1084 }
62e76326 1085
5fa061b8 1086#endif
1087
ba82c452 1088 if (len == 0) { // reached EOF?
62e76326 1089 eof = 1;
f61f0107 1090 flags.do_next_read = 0;
ba82c452 1091 }
62e76326 1092
ba82c452 1093 if (!flags.headers_parsed) { // have not parsed headers yet?
1094 PROF_start(HttpStateData_processReplyHeader);
1095 processReplyHeader();
1096 PROF_stop(HttpStateData_processReplyHeader);
1097
1098 if (!continueAfterParsingHeader()) // parsing error or need more data
1099 return; // TODO: send errors to ICAP
1100
585ab260 1101 adaptOrFinalizeReply();
ba82c452 1102 }
1103
1104 // kick more reads if needed and/or process the response body, if any
1105 PROF_start(HttpStateData_processReplyBody);
1106 processReplyBody(); // may call serverComplete()
1107 PROF_stop(HttpStateData_processReplyBody);
1108}
1109
073ba374
AJ
1110/**
1111 \retval true if we can continue with processing the body or doing ICAP.
1112 */
ba82c452 1113bool
1114HttpStateData::continueAfterParsingHeader()
1115{
073ba374 1116 if (!flags.headers_parsed && !eof) {
ba82c452 1117 debugs(11, 9, HERE << "needs more at " << readBuf->contentSize());
1118 flags.do_next_read = 1;
073ba374
AJ
1119 /** \retval false If we have not finished parsing the headers and may get more data.
1120 * Schedules more reads to retrieve the missing data.
1121 */
ba82c452 1122 maybeReadVirginBody(); // schedules all kinds of reads; TODO: rename
073ba374 1123 return false;
ba82c452 1124 }
1125
073ba374 1126 /** If we are done with parsing, check for errors */
ba82c452 1127
1128 err_type error = ERR_NONE;
1129
1130 if (flags.headers_parsed) { // parsed headers, possibly with errors
1131 // check for header parsing errors
585ab260 1132 if (HttpReply *vrep = virginReply()) {
1133 const http_status s = vrep->sline.status;
1134 const HttpVersion &v = vrep->sline.version;
ba82c452 1135 if (s == HTTP_INVALID_HEADER && v != HttpVersion(0,9)) {
1136 error = ERR_INVALID_RESP;
1137 } else
9e008dda
AJ
1138 if (s == HTTP_HEADER_TOO_LARGE) {
1139 fwd->dontRetry(true);
1140 error = ERR_TOO_BIG;
1141 } else {
1142 return true; // done parsing, got reply, and no error
1143 }
ba82c452 1144 } else {
1145 // parsed headers but got no reply
1146 error = ERR_INVALID_RESP;
62e76326 1147 }
090089c4 1148 } else {
ba82c452 1149 assert(eof);
1150 error = readBuf->hasContent() ?
9e008dda 1151 ERR_INVALID_RESP : ERR_ZERO_SIZE_OBJECT;
2afaba07 1152 }
ba82c452 1153
1154 assert(error != ERR_NONE);
1155 entry->reset();
1156 fwd->fail(errorCon(error, HTTP_BAD_GATEWAY, fwd->request));
1157 flags.do_next_read = 0;
1158 comm_close(fd);
1159 return false; // quit on error
2afaba07 1160}
1161
073ba374 1162/**
2afaba07 1163 * Call this when there is data from the origin server
1164 * which should be sent to either StoreEntry, or to ICAP...
1165 */
1166void
5f8252d2 1167HttpStateData::writeReplyBody()
2afaba07 1168{
5f8252d2 1169 const char *data = readBuf->content();
1170 int len = readBuf->contentSize();
bc81cb2b 1171 addVirginReplyBody(data, len);
5f8252d2 1172 readBuf->consume(len);
af0bb8e5 1173}
fc68f6b1 1174
af0bb8e5 1175bool
1176HttpStateData::decodeAndWriteReplyBody()
1177{
1178 const char *data = NULL;
1179 int len;
1180 bool status = false;
1181 assert(flags.chunked);
1182 assert(httpChunkDecoder);
1183 SQUID_ENTER_THROWING_CODE();
1184 MemBuf decodedData;
1185 decodedData.init();
1186 const bool done = httpChunkDecoder->parse(readBuf,&decodedData);
1187 len = decodedData.contentSize();
1188 data=decodedData.content();
1189 addVirginReplyBody(data, len);
1190 if (done) {
839291ac
AJ
1191 lastChunk = 1;
1192 flags.do_next_read = 0;
af0bb8e5 1193 }
1194 SQUID_EXIT_THROWING_CODE(status);
1195 return status;
e6ccf245 1196}
1197
073ba374 1198/**
2afaba07 1199 * processReplyBody has two purposes:
1200 * 1 - take the reply body data, if any, and put it into either
1201 * the StoreEntry, or give it over to ICAP.
1202 * 2 - see if we made it to the end of the response (persistent
1203 * connections and such)
1204 */
e6ccf245 1205void
2afaba07 1206HttpStateData::processReplyBody()
e6ccf245 1207{
dc56a9b1 1208 AsyncCall::Pointer call;
cc192b50 1209 IPAddress client_addr;
d67acb4e 1210 bool ispinned = false;
fc68f6b1 1211
1a98175f 1212 if (!flags.headers_parsed) {
f61f0107 1213 flags.do_next_read = 1;
5f8252d2 1214 maybeReadVirginBody();
62e76326 1215 return;
528b2c61 1216 }
62e76326 1217
a83c6ed6
AR
1218#if USE_ADAPTATION
1219 if (adaptationAccessCheckPending)
2afaba07 1220 return;
fc68f6b1 1221
2afaba07 1222#endif
62e76326 1223
2afaba07 1224 /*
1225 * At this point the reply headers have been parsed and consumed.
1226 * That means header content has been removed from readBuf and
1227 * it contains only body data.
1228 */
9e008dda
AJ
1229 if (flags.chunked) {
1230 if (!decodeAndWriteReplyBody()) {
1231 flags.do_next_read = 0;
1232 serverComplete();
1233 return;
1234 }
1235 } else
1236 writeReplyBody();
528b2c61 1237
e6ccf245 1238 if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
62e76326 1239 /*
073ba374 1240 * The above writeReplyBody() call could ABORT this entry,
62e76326 1241 * in that case, the server FD should already be closed.
1242 * there's nothing for us to do.
1243 */
1244 (void) 0;
1245 } else
1246 switch (persistentConnStatus()) {
62e76326 1247 case INCOMPLETE_MSG:
bf8fe701 1248 debugs(11, 5, "processReplyBody: INCOMPLETE_MSG");
21b92762 1249 /* Wait for more data or EOF condition */
21b92762 1250 if (flags.keepalive_broken) {
9e008dda 1251 call = NULL;
dc56a9b1 1252 commSetTimeout(fd, 10, call);
21b92762 1253 } else {
9e008dda 1254 call = NULL;
dc56a9b1 1255 commSetTimeout(fd, Config.Timeout.read, call);
21b92762 1256 }
1257
f61f0107 1258 flags.do_next_read = 1;
62e76326 1259 break;
1260
1261 case COMPLETE_PERSISTENT_MSG:
bf8fe701 1262 debugs(11, 5, "processReplyBody: COMPLETE_PERSISTENT_MSG");
62e76326 1263 /* yes we have to clear all these! */
9e008dda 1264 call = NULL;
dc56a9b1 1265 commSetTimeout(fd, -1, call);
f61f0107 1266 flags.do_next_read = 0;
62e76326 1267
9e008dda 1268 comm_remove_close_handler(fd, closeHandler);
dc56a9b1 1269 closeHandler = NULL;
b6b6f466 1270 fwd->unregister(fd);
fc68f6b1 1271
f165d2fb 1272 if (orig_request->flags.spoof_client_ip)
cc192b50 1273 client_addr = orig_request->client_addr;
fc68f6b1 1274
d67acb4e 1275
9e008dda
AJ
1276 if (request->flags.pinned) {
1277 ispinned = true;
1278 } else if (request->flags.connection_auth && request->flags.auth_sent) {
1279 ispinned = true;
1280 }
1281
1282 if (orig_request->pinnedConnection() && ispinned) {
1283 orig_request->pinnedConnection()->pinConnection(fd, orig_request, _peer,
1284 (request->flags.connection_auth != 0));
1285 } else if (_peer) {
bd0723ad 1286 if (_peer->options.originserver)
cc192b50 1287 fwd->pconnPush(fd, _peer->name, orig_request->port, orig_request->GetHost(), client_addr);
bd0723ad 1288 else
fc68f6b1 1289 fwd->pconnPush(fd, _peer->name, _peer->http_port, NULL, client_addr);
bd0723ad 1290 } else {
cc192b50 1291 fwd->pconnPush(fd, request->GetHost(), request->port, NULL, client_addr);
bd0723ad 1292 }
1293
62e76326 1294 fd = -1;
2afaba07 1295
5f8252d2 1296 serverComplete();
62e76326 1297 return;
1298
1299 case COMPLETE_NONPERSISTENT_MSG:
bf8fe701 1300 debugs(11, 5, "processReplyBody: COMPLETE_NONPERSISTENT_MSG");
5f8252d2 1301 serverComplete();
62e76326 1302 return;
1303 }
1304
5f8252d2 1305 maybeReadVirginBody();
c4b7a5a9 1306}
1307
1308void
5f8252d2 1309HttpStateData::maybeReadVirginBody()
c4b7a5a9 1310{
7dc79973 1311 int read_sz = replyBodySpace(readBuf->spaceSize());
2afaba07 1312
5f8252d2 1313 debugs(11,9, HERE << (flags.do_next_read ? "may" : "wont") <<
fc68f6b1 1314 " read up to " << read_sz << " bytes from FD " << fd);
2afaba07 1315
1316 /*
1317 * why <2? Because delayAwareRead() won't actually read if
1318 * you ask it to read 1 byte. The delayed read request
1319 * just gets re-queued until the client side drains, then
1320 * the I/O thread hangs. Better to not register any read
1321 * handler until we get a notification from someone that
1322 * its okay to read again.
1323 */
53dbd8cb 1324 if (read_sz < 2) {
9e008dda
AJ
1325 if (flags.headers_parsed)
1326 return;
1327 else
1328 read_sz = 1024;
53dbd8cb 1329 }
2afaba07 1330
f61f0107 1331 if (flags.do_next_read) {
dc56a9b1 1332 flags.do_next_read = 0;
1333 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
1334 entry->delayAwareRead(fd, readBuf->space(read_sz), read_sz,
9e008dda
AJ
1335 asyncCall(11, 5, "HttpStateData::readReply",
1336 Dialer(this, &HttpStateData::readReply)));
528b2c61 1337 }
090089c4 1338}
1339
2afaba07 1340/*
1341 * This will be called when request write is complete.
1342 */
d576a6a6 1343void
dc56a9b1 1344HttpStateData::sendComplete(const CommIoCbParams &io)
090089c4 1345{
dc56a9b1 1346 debugs(11, 5, "httpSendComplete: FD " << fd << ": size " << io.size << ": errflag " << io.flag << ".");
bc87dc25 1347#if URL_CHECKSUM_DEBUG
62e76326 1348
528b2c61 1349 entry->mem_obj->checkUrlChecksum();
bc87dc25 1350#endif
62e76326 1351
dc56a9b1 1352 if (io.size > 0) {
1353 fd_bytes(fd, io.size, FD_WRITE);
1354 kb_incr(&statCounter.server.all.kbytes_out, io.size);
1355 kb_incr(&statCounter.server.http.kbytes_out, io.size);
ee1679df 1356 }
62e76326 1357
dc56a9b1 1358 if (io.flag == COMM_ERR_CLOSING)
62e76326 1359 return;
1360
dc56a9b1 1361 if (io.flag) {
6cae5db1 1362 ErrorState *err;
dc56a9b1 1363 err = errorCon(ERR_WRITE_ERROR, HTTP_BAD_GATEWAY, fwd->request);
1364 err->xerrno = io.xerrno;
1365 fwd->fail(err);
62e76326 1366 comm_close(fd);
1367 return;
090089c4 1368 }
72b63f06 1369
2afaba07 1370 /*
1371 * Set the read timeout here because it hasn't been set yet.
1372 * We only set the read timeout after the request has been
1373 * fully written to the server-side. If we start the timeout
1374 * after connection establishment, then we are likely to hit
1375 * the timeout for POST/PUT requests that have very large
1376 * request bodies.
1377 */
dc56a9b1 1378 typedef CommCbMemFunT<HttpStateData, CommTimeoutCbParams> TimeoutDialer;
1379 AsyncCall::Pointer timeoutCall = asyncCall(11, 5, "HttpStateData::httpTimeout",
9e008dda 1380 TimeoutDialer(this,&HttpStateData::httpTimeout));
2afaba07 1381
dc56a9b1 1382 commSetTimeout(fd, Config.Timeout.read, timeoutCall);
1383
1384 flags.request_sent = 1;
090089c4 1385}
1386
5f8252d2 1387// Close the HTTP server connection. Used by serverComplete().
2afaba07 1388void
5f8252d2 1389HttpStateData::closeServer()
2afaba07 1390{
5f8252d2 1391 debugs(11,5, HERE << "closing HTTP server FD " << fd << " this " << this);
fc68f6b1 1392
2afaba07 1393 if (fd >= 0) {
b6b6f466 1394 fwd->unregister(fd);
9e008dda 1395 comm_remove_close_handler(fd, closeHandler);
dc56a9b1 1396 closeHandler = NULL;
2afaba07 1397 comm_close(fd);
1398 fd = -1;
1399 }
5f8252d2 1400}
2afaba07 1401
5f8252d2 1402bool
1403HttpStateData::doneWithServer() const
1404{
1405 return fd < 0;
2afaba07 1406}
1407
99edd1c3 1408/*
9e008dda 1409 * build request headers and append them to a given MemBuf
e5ee81f0 1410 * used by buildRequestPrefix()
818c6c9e 1411 * note: initialised the HttpHeader, the caller is responsible for Clean()-ing
99edd1c3 1412 */
e1e72f06 1413void
e5ee81f0 1414HttpStateData::httpBuildRequestHeader(HttpRequest * request,
1415 HttpRequest * orig_request,
1416 StoreEntry * entry,
1417 HttpHeader * hdr_out,
1418 http_state_flags flags)
6bf8443a 1419{
99edd1c3 1420 /* building buffer for complex strings */
5999b776 1421#define BBUF_SZ (MAX_URL+32)
99edd1c3 1422 LOCAL_ARRAY(char, bbuf, BBUF_SZ);
67c06f0d 1423 LOCAL_ARRAY(char, ntoabuf, MAX_IPSTRLEN);
99edd1c3 1424 const HttpHeader *hdr_in = &orig_request->header;
67c06f0d 1425 const HttpHeaderEntry *e = NULL;
30abd221 1426 String strFwd;
99edd1c3 1427 HttpHeaderPos pos = HttpHeaderInitPos;
75faaa7a 1428 assert (hdr_out->owner == hoRequest);
99edd1c3 1429 /* append our IMS header */
62e76326 1430
fa3e249f 1431 if (request->lastmod > -1)
a9925b40 1432 hdr_out->putTime(HDR_IF_MODIFIED_SINCE, request->lastmod);
99edd1c3 1433
528b2c61 1434 bool we_do_ranges = decideIfWeDoRanges (orig_request);
1435
30abd221 1436 String strConnection (hdr_in->getList(HDR_CONNECTION));
62e76326 1437
a9925b40 1438 while ((e = hdr_in->getEntry(&pos)))
62e76326 1439 copyOneHeaderFromClientsideRequestToUpstreamRequest(e, strConnection, request, orig_request, hdr_out, we_do_ranges, flags);
528b2c61 1440
43ae1d95 1441 /* Abstraction break: We should interpret multipart/byterange responses
528b2c61 1442 * into offset-length data, and this works around our inability to do so.
1443 */
62e76326 1444 if (!we_do_ranges && orig_request->multipartRangeRequest()) {
1445 /* don't cache the result */
1446 orig_request->flags.cachable = 0;
1447 /* pretend it's not a range request */
00d77d6b 1448 delete orig_request->range;
62e76326 1449 orig_request->range = NULL;
1450 orig_request->flags.range = 0;
1451 }
528b2c61 1452
99edd1c3 1453 /* append Via */
736cb6aa 1454 if (Config.onoff.via) {
30abd221 1455 String strVia;
a9925b40 1456 strVia = hdr_in->getList(HDR_VIA);
62e76326 1457 snprintf(bbuf, BBUF_SZ, "%d.%d %s",
1458 orig_request->http_ver.major,
1459 orig_request->http_ver.minor, ThisCache);
1460 strListAdd(&strVia, bbuf, ',');
30abd221 1461 hdr_out->putStr(HDR_VIA, strVia.buf());
1462 strVia.clean();
736cb6aa 1463 }
62e76326 1464
f41735ea 1465#if USE_SQUID_ESI
43ae1d95 1466 {
1467 /* Append Surrogate-Capabilities */
30abd221 1468 String strSurrogate (hdr_in->getList(HDR_SURROGATE_CAPABILITY));
ec43ae0e 1469 snprintf(bbuf, BBUF_SZ, "%s=\"Surrogate/1.0 ESI/1.0\"",
43ae1d95 1470 Config.Accel.surrogate_id);
1471 strListAdd(&strSurrogate, bbuf, ',');
30abd221 1472 hdr_out->putStr(HDR_SURROGATE_CAPABILITY, strSurrogate.buf());
43ae1d95 1473 }
1474#endif
1475
a9925b40 1476 strFwd = hdr_in->getList(HDR_X_FORWARDED_FOR);
62e76326 1477
67c06f0d 1478 /** \pre Handle X-Forwarded-For */
9e008dda
AJ
1479 if (strcmp(opt_forwarded_for, "delete") != 0) {
1480 if (strcmp(opt_forwarded_for, "on") == 0) {
67c06f0d
AJ
1481 /** If set to ON - append client IP or 'unknown'. */
1482 strFwd = hdr_in->getList(HDR_X_FORWARDED_FOR);
9e008dda 1483 if ( orig_request->client_addr.IsNoAddr() )
67c06f0d
AJ
1484 strListAdd(&strFwd, "unknown", ',');
1485 else
1486 strListAdd(&strFwd, orig_request->client_addr.NtoA(ntoabuf, MAX_IPSTRLEN), ',');
9e008dda 1487 } else if (strcmp(opt_forwarded_for, "off") == 0) {
67c06f0d
AJ
1488 /** If set to OFF - append 'unknown'. */
1489 strFwd = hdr_in->getList(HDR_X_FORWARDED_FOR);
1490 strListAdd(&strFwd, "unknown", ',');
9e008dda 1491 } else if (strcmp(opt_forwarded_for, "transparent") == 0) {
67c06f0d
AJ
1492 /** If set to TRANSPARENT - pass through unchanged. */
1493 strFwd = hdr_in->getList(HDR_X_FORWARDED_FOR);
9e008dda 1494 } else if (strcmp(opt_forwarded_for, "truncate") == 0) {
67c06f0d 1495 /** If set to TRUNCATE - drop existing list and replace with client IP or 'unknown'. */
9e008dda 1496 if ( orig_request->client_addr.IsNoAddr() )
67c06f0d
AJ
1497 strFwd = "unknown";
1498 else
1499 strFwd = orig_request->client_addr.NtoA(ntoabuf, MAX_IPSTRLEN);
1500 }
9e008dda 1501 if (strFwd.size() > 0)
67c06f0d 1502 hdr_out->putStr(HDR_X_FORWARDED_FOR, strFwd.buf());
cc192b50 1503 }
67c06f0d 1504 /** If set to DELETE - do not copy through. */
30abd221 1505 strFwd.clean();
6bccf575 1506
99edd1c3 1507 /* append Host if not there already */
a9925b40 1508 if (!hdr_out->has(HDR_HOST)) {
62e76326 1509 if (orig_request->peer_domain) {
a9925b40 1510 hdr_out->putStr(HDR_HOST, orig_request->peer_domain);
62e76326 1511 } else if (orig_request->port == urlDefaultPort(orig_request->protocol)) {
1512 /* use port# only if not default */
cc192b50 1513 hdr_out->putStr(HDR_HOST, orig_request->GetHost());
62e76326 1514 } else {
1515 httpHeaderPutStrf(hdr_out, HDR_HOST, "%s:%d",
cc192b50 1516 orig_request->GetHost(),
1517 (int) orig_request->port);
62e76326 1518 }
6bf8443a 1519 }
62e76326 1520
c68e9c6b 1521 /* append Authorization if known in URL, not in header and going direct */
a9925b40 1522 if (!hdr_out->has(HDR_AUTHORIZATION)) {
62e76326 1523 if (!request->flags.proxying && *request->login) {
1524 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1525 base64_encode(request->login));
1526 }
c68e9c6b 1527 }
62e76326 1528
c68e9c6b 1529 /* append Proxy-Authorization if configured for peer, and proxying */
c3b33cb7 1530 if (request->flags.proxying && orig_request->peer_login &&
a9925b40 1531 !hdr_out->has(HDR_PROXY_AUTHORIZATION)) {
62e76326 1532 if (*orig_request->peer_login == '*') {
1533 /* Special mode, to pass the username to the upstream cache */
1534 char loginbuf[256];
1535 const char *username = "-";
1536
a8bc2b9c 1537 if (orig_request->extacl_user.size())
30abd221 1538 username = orig_request->extacl_user.buf();
a8bc2b9c 1539 else if (orig_request->auth_user_request)
1540 username = orig_request->auth_user_request->username();
62e76326 1541
1542 snprintf(loginbuf, sizeof(loginbuf), "%s%s", username, orig_request->peer_login + 1);
1543
1544 httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Basic %s",
1545 base64_encode(loginbuf));
1546 } else if (strcmp(orig_request->peer_login, "PASS") == 0) {
abb929f0 1547 if (orig_request->extacl_user.size() && orig_request->extacl_passwd.size()) {
1548 char loginbuf[256];
30abd221 1549 snprintf(loginbuf, sizeof(loginbuf), "%s:%s", orig_request->extacl_user.buf(), orig_request->extacl_passwd.buf());
abb929f0 1550 httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Basic %s",
1551 base64_encode(loginbuf));
1552 }
62e76326 1553 } else if (strcmp(orig_request->peer_login, "PROXYPASS") == 0) {
1554 /* Nothing to do */
1555 } else {
1556 httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Basic %s",
1557 base64_encode(orig_request->peer_login));
1558 }
c68e9c6b 1559 }
62e76326 1560
be753325 1561 /* append WWW-Authorization if configured for peer */
1562 if (flags.originpeer && orig_request->peer_login &&
a9925b40 1563 !hdr_out->has(HDR_AUTHORIZATION)) {
62e76326 1564 if (strcmp(orig_request->peer_login, "PASS") == 0) {
1565 /* No credentials to forward.. (should have been done above if available) */
1566 } else if (strcmp(orig_request->peer_login, "PROXYPASS") == 0) {
1567 /* Special mode, convert proxy authentication to WWW authentication
abb929f0 1568 * (also applies to authentication provided by external acl)
62e76326 1569 */
a9925b40 1570 const char *auth = hdr_in->getStr(HDR_PROXY_AUTHORIZATION);
62e76326 1571
1572 if (auth && strncasecmp(auth, "basic ", 6) == 0) {
a9925b40 1573 hdr_out->putStr(HDR_AUTHORIZATION, auth);
abb929f0 1574 } else if (orig_request->extacl_user.size() && orig_request->extacl_passwd.size()) {
1575 char loginbuf[256];
30abd221 1576 snprintf(loginbuf, sizeof(loginbuf), "%s:%s", orig_request->extacl_user.buf(), orig_request->extacl_passwd.buf());
abb929f0 1577 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1578 base64_encode(loginbuf));
62e76326 1579 }
1580 } else if (*orig_request->peer_login == '*') {
1581 /* Special mode, to pass the username to the upstream cache */
1582 char loginbuf[256];
1583 const char *username = "-";
1584
1585 if (orig_request->auth_user_request)
f5691f9c 1586 username = orig_request->auth_user_request->username();
abb929f0 1587 else if (orig_request->extacl_user.size())
30abd221 1588 username = orig_request->extacl_user.buf();
62e76326 1589
1590 snprintf(loginbuf, sizeof(loginbuf), "%s%s", username, orig_request->peer_login + 1);
1591
1592 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1593 base64_encode(loginbuf));
1594 } else {
1595 /* Fixed login string */
1596 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1597 base64_encode(orig_request->peer_login));
1598 }
be753325 1599 }
62e76326 1600
abb929f0 1601 /* append Cache-Control, add max-age if not there already */ {
a9925b40 1602 HttpHdrCc *cc = hdr_in->getCc();
62e76326 1603
1604 if (!cc)
1605 cc = httpHdrCcCreate();
1606
1607 if (!EBIT_TEST(cc->mask, CC_MAX_AGE)) {
43ae1d95 1608 const char *url =
3900307b 1609 entry ? entry->url() : urlCanonical(orig_request);
62e76326 1610 httpHdrCcSetMaxAge(cc, getMaxAge(url));
1611
1612 if (request->urlpath.size())
30abd221 1613 assert(strstr(url, request->urlpath.buf()));
62e76326 1614 }
1615
ce2d6441 1616 /* Set no-cache if determined needed but not found */
a9925b40 1617 if (orig_request->flags.nocache && !hdr_in->has(HDR_PRAGMA))
ce2d6441 1618 EBIT_SET(cc->mask, CC_NO_CACHE);
1619
1620 /* Enforce sibling relations */
62e76326 1621 if (flags.only_if_cached)
1622 EBIT_SET(cc->mask, CC_ONLY_IF_CACHED);
1623
a9925b40 1624 hdr_out->putCc(cc);
62e76326 1625
1626 httpHdrCcDestroy(cc);
6bf8443a 1627 }
62e76326 1628
99edd1c3 1629 /* maybe append Connection: keep-alive */
b515fc11 1630 if (flags.keepalive) {
62e76326 1631 if (flags.proxying) {
a9925b40 1632 hdr_out->putStr(HDR_PROXY_CONNECTION, "keep-alive");
62e76326 1633 } else {
a9925b40 1634 hdr_out->putStr(HDR_CONNECTION, "keep-alive");
62e76326 1635 }
603a02fd 1636 }
62e76326 1637
a7ad6e4e 1638 /* append Front-End-Https */
1639 if (flags.front_end_https) {
62e76326 1640 if (flags.front_end_https == 1 || request->protocol == PROTO_HTTPS)
a9925b40 1641 hdr_out->putStr(HDR_FRONT_END_HTTPS, "On");
a7ad6e4e 1642 }
1643
6bccf575 1644 /* Now mangle the headers. */
4f56514c 1645 if (Config2.onoff.mangle_request_headers)
5967c0bf 1646 httpHdrMangleList(hdr_out, request, ROR_REQUEST);
62e76326 1647
30abd221 1648 strConnection.clean();
99edd1c3 1649}
1650
528b2c61 1651void
30abd221 1652copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, String strConnection, HttpRequest * request, HttpRequest * orig_request, HttpHeader * hdr_out, int we_do_ranges, http_state_flags flags)
528b2c61 1653{
30abd221 1654 debugs(11, 5, "httpBuildRequestHeader: " << e->name.buf() << ": " << e->value.buf());
62e76326 1655
528b2c61 1656 if (!httpRequestHdrAllowed(e, &strConnection)) {
30abd221 1657 debugs(11, 2, "'" << e->name.buf() << "' header denied by anonymize_headers configuration");
62e76326 1658 return;
528b2c61 1659 }
62e76326 1660
528b2c61 1661 switch (e->id) {
62e76326 1662
be753325 1663 case HDR_PROXY_AUTHORIZATION:
62e76326 1664 /* Only pass on proxy authentication to peers for which
1665 * authentication forwarding is explicitly enabled
1666 */
1667
1668 if (flags.proxying && orig_request->peer_login &&
abb929f0 1669 (strcmp(orig_request->peer_login, "PASS") == 0 ||
1670 strcmp(orig_request->peer_login, "PROXYPASS") == 0)) {
eede25e7 1671 hdr_out->addEntry(e->clone());
62e76326 1672 }
1673
1674 break;
1675
be753325 1676 case HDR_AUTHORIZATION:
62e76326 1677 /* Pass on WWW authentication */
1678
1679 if (!flags.originpeer) {
eede25e7 1680 hdr_out->addEntry(e->clone());
62e76326 1681 } else {
1682 /* In accelerators, only forward authentication if enabled
1683 * (see also below for proxy->server authentication)
1684 */
1685
abb929f0 1686 if (orig_request->peer_login &&
1687 (strcmp(orig_request->peer_login, "PASS") == 0 ||
1688 strcmp(orig_request->peer_login, "PROXYPASS") == 0)) {
eede25e7 1689 hdr_out->addEntry(e->clone());
62e76326 1690 }
1691 }
1692
1693 break;
1694
be753325 1695 case HDR_HOST:
62e76326 1696 /*
b883b594 1697 * Normally Squid rewrites the Host: header.
1698 * However, there is one case when we don't: If the URL
62e76326 1699 * went through our redirector and the admin configured
1700 * 'redir_rewrites_host' to be off.
1701 */
9e008dda 1702 if (orig_request->peer_domain)
488b27c5
HN
1703 hdr_out->putStr(HDR_HOST, orig_request->peer_domain);
1704 else if (request->flags.redirected && !Config.onoff.redir_rewrites_host)
eede25e7 1705 hdr_out->addEntry(e->clone());
b883b594 1706 else {
1707 /* use port# only if not default */
1708
1709 if (orig_request->port == urlDefaultPort(orig_request->protocol)) {
cc192b50 1710 hdr_out->putStr(HDR_HOST, orig_request->GetHost());
b883b594 1711 } else {
1712 httpHeaderPutStrf(hdr_out, HDR_HOST, "%s:%d",
cc192b50 1713 orig_request->GetHost(),
1714 (int) orig_request->port);
b883b594 1715 }
1716 }
62e76326 1717
1718 break;
1719
be753325 1720 case HDR_IF_MODIFIED_SINCE:
62e76326 1721 /* append unless we added our own;
1722 * note: at most one client's ims header can pass through */
b883b594 1723
a9925b40 1724 if (!hdr_out->has(HDR_IF_MODIFIED_SINCE))
eede25e7 1725 hdr_out->addEntry(e->clone());
62e76326 1726
1727 break;
1728
be753325 1729 case HDR_MAX_FORWARDS:
62e76326 1730 if (orig_request->method == METHOD_TRACE) {
eede25e7 1731 const int hops = e->getInt();
62e76326 1732
1733 if (hops > 0)
a9925b40 1734 hdr_out->putInt(HDR_MAX_FORWARDS, hops - 1);
62e76326 1735 }
1736
1737 break;
1738
be753325 1739 case HDR_VIA:
62e76326 1740 /* If Via is disabled then forward any received header as-is */
1741
1742 if (!Config.onoff.via)
eede25e7 1743 hdr_out->addEntry(e->clone());
62e76326 1744
1745 break;
1746
be753325 1747 case HDR_RANGE:
62e76326 1748
be753325 1749 case HDR_IF_RANGE:
62e76326 1750
be753325 1751 case HDR_REQUEST_RANGE:
62e76326 1752 if (!we_do_ranges)
eede25e7 1753 hdr_out->addEntry(e->clone());
62e76326 1754
1755 break;
1756
be753325 1757 case HDR_PROXY_CONNECTION:
62e76326 1758
be753325 1759 case HDR_CONNECTION:
62e76326 1760
be753325 1761 case HDR_X_FORWARDED_FOR:
62e76326 1762
be753325 1763 case HDR_CACHE_CONTROL:
62e76326 1764 /* append these after the loop if needed */
1765 break;
1766
be753325 1767 case HDR_FRONT_END_HTTPS:
62e76326 1768 if (!flags.front_end_https)
eede25e7 1769 hdr_out->addEntry(e->clone());
62e76326 1770
1771 break;
1772
be753325 1773 default:
62e76326 1774 /* pass on all other header fields */
eede25e7 1775 hdr_out->addEntry(e->clone());
528b2c61 1776 }
1777}
1778
e5ee81f0 1779bool
1780HttpStateData::decideIfWeDoRanges (HttpRequest * orig_request)
528b2c61 1781{
e5ee81f0 1782 bool result = true;
62e76326 1783 /* decide if we want to do Ranges ourselves
1784 * and fetch the whole object now)
1785 * We want to handle Ranges ourselves iff
1786 * - we can actually parse client Range specs
1787 * - the specs are expected to be simple enough (e.g. no out-of-order ranges)
1788 * - reply will be cachable
1789 * (If the reply will be uncachable we have to throw it away after
1790 * serving this request, so it is better to forward ranges to
1791 * the server and fetch only the requested content)
1792 */
1793
1794 if (NULL == orig_request->range || !orig_request->flags.cachable
d67acb4e 1795 || orig_request->range->offsetLimitExceeded() || orig_request->flags.connection_auth)
e5ee81f0 1796 result = false;
62e76326 1797
9e008dda
AJ
1798 debugs(11, 8, "decideIfWeDoRanges: range specs: " <<
1799 orig_request->range << ", cachable: " <<
1800 orig_request->flags.cachable << "; we_do_ranges: " << result);
62e76326 1801
1802 return result;
528b2c61 1803}
1804
62e76326 1805/* build request prefix and append it to a given MemBuf;
99edd1c3 1806 * return the length of the prefix */
9bc73deb 1807mb_size_t
e5ee81f0 1808HttpStateData::buildRequestPrefix(HttpRequest * request,
1809 HttpRequest * orig_request,
1810 StoreEntry * entry,
1811 MemBuf * mb,
1812 http_state_flags flags)
99edd1c3 1813{
1814 const int offset = mb->size;
450e0c10 1815 HttpVersion httpver(1, 0);
2fe7eff9 1816 mb->Printf("%s %s HTTP/%d.%d\r\n",
60745f24 1817 RequestMethodStr(request->method),
30abd221 1818 request->urlpath.size() ? request->urlpath.buf() : "/",
2fe7eff9 1819 httpver.major,httpver.minor);
99edd1c3 1820 /* build and pack headers */
1821 {
75faaa7a 1822 HttpHeader hdr(hoRequest);
62e76326 1823 Packer p;
1824 httpBuildRequestHeader(request, orig_request, entry, &hdr, flags);
9e008dda
AJ
1825
1826 if (request->flags.pinned && request->flags.connection_auth)
d67acb4e
AJ
1827 request->flags.auth_sent = 1;
1828 else if (hdr.has(HDR_AUTHORIZATION))
1829 request->flags.auth_sent = 1;
1830
62e76326 1831 packerToMemInit(&p, mb);
a9925b40 1832 hdr.packInto(&p);
519e0948 1833 hdr.clean();
62e76326 1834 packerClean(&p);
9d9d144b 1835 }
99edd1c3 1836 /* append header terminator */
2fe7eff9 1837 mb->append(crlf, 2);
99edd1c3 1838 return mb->size - offset;
6bf8443a 1839}
62e76326 1840
090089c4 1841/* This will be called when connect completes. Write request. */
5f8252d2 1842bool
2bb867b5 1843HttpStateData::sendRequest()
090089c4 1844{
99edd1c3 1845 MemBuf mb;
090089c4 1846
bf8fe701 1847 debugs(11, 5, "httpSendRequest: FD " << fd << ", request " << request << ", this " << this << ".");
dc56a9b1 1848 typedef CommCbMemFunT<HttpStateData, CommTimeoutCbParams> TimeoutDialer;
1849 AsyncCall::Pointer timeoutCall = asyncCall(11, 5, "HttpStateData::httpTimeout",
9e008dda 1850 TimeoutDialer(this,&HttpStateData::httpTimeout));
dc56a9b1 1851 commSetTimeout(fd, Config.Timeout.lifetime, timeoutCall);
2bb867b5 1852 flags.do_next_read = 1;
5f8252d2 1853 maybeReadVirginBody();
1854
1855 if (orig_request->body_pipe != NULL) {
123ec4de 1856 if (!startRequestBodyFlow()) // register to receive body data
5f8252d2 1857 return false;
9e008dda 1858 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
dc56a9b1 1859 Dialer dialer(this, &HttpStateData::sentRequestBody);
9e008dda 1860 requestSender = asyncCall(11,5, "HttpStateData::sentRequestBody", dialer);
5f8252d2 1861 } else {
1862 assert(!requestBodySource);
9e008dda 1863 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
dc56a9b1 1864 Dialer dialer(this, &HttpStateData::sendComplete);
9e008dda 1865 requestSender = asyncCall(11,5, "HttpStateData::SendComplete", dialer);
5f8252d2 1866 }
54220df8 1867
2bb867b5 1868 if (_peer != NULL) {
1869 if (_peer->options.originserver) {
1870 flags.proxying = 0;
1871 flags.originpeer = 1;
62e76326 1872 } else {
2bb867b5 1873 flags.proxying = 1;
1874 flags.originpeer = 0;
62e76326 1875 }
be753325 1876 } else {
2bb867b5 1877 flags.proxying = 0;
1878 flags.originpeer = 0;
be753325 1879 }
62e76326 1880
efb9218c 1881 /*
99edd1c3 1882 * Is keep-alive okay for all request methods?
efb9218c 1883 */
d67acb4e 1884 if (orig_request->flags.must_keepalive)
9e008dda 1885 flags.keepalive = 1;
d67acb4e 1886 else if (!Config.onoff.server_pconns)
2bb867b5 1887 flags.keepalive = 0;
1888 else if (_peer == NULL)
1889 flags.keepalive = 1;
1890 else if (_peer->stats.n_keepalives_sent < 10)
1891 flags.keepalive = 1;
1892 else if ((double) _peer->stats.n_keepalives_recv /
1893 (double) _peer->stats.n_keepalives_sent > 0.50)
1894 flags.keepalive = 1;
1895
1896 if (_peer) {
1897 if (neighborType(_peer, request) == PEER_SIBLING &&
1898 !_peer->options.allow_miss)
1899 flags.only_if_cached = 1;
1900
1901 flags.front_end_https = _peer->front_end_https;
a7ad6e4e 1902 }
62e76326 1903
2fe7eff9 1904 mb.init();
e5ee81f0 1905 buildRequestPrefix(request, orig_request, entry, &mb, flags);
bf8fe701 1906 debugs(11, 6, "httpSendRequest: FD " << fd << ":\n" << mb.buf);
dc56a9b1 1907 comm_write_mbuf(fd, &mb, requestSender);
5f8252d2 1908
1909 return true;
090089c4 1910}
b6a2f15e 1911
910169e5 1912void
b6b6f466 1913httpStart(FwdState *fwd)
603a02fd 1914{
60745f24 1915 debugs(11, 3, "httpStart: \"" << RequestMethodStr(fwd->request->method) << " " << fwd->entry->url() << "\"" );
a3d50c30 1916 HttpStateData *httpState = new HttpStateData(fwd);
62e76326 1917
5f8252d2 1918 if (!httpState->sendRequest()) {
bf8fe701 1919 debugs(11, 3, "httpStart: aborted");
5f8252d2 1920 delete httpState;
1921 return;
1922 }
62e76326 1923
5f8252d2 1924 statCounter.server.all.requests++;
83704487 1925 statCounter.server.http.requests++;
62e76326 1926
b6a2f15e 1927 /*
1928 * We used to set the read timeout here, but not any more.
1929 * Now its set in httpSendComplete() after the full request,
1930 * including request body, has been written to the server.
1931 */
090089c4 1932}
1933
2bb867b5 1934void
5f8252d2 1935HttpStateData::doneSendingRequestBody()
2bb867b5 1936{
4fb35c3c 1937 ACLChecklist ch;
5f8252d2 1938 debugs(11,5, HERE << "doneSendingRequestBody: FD " << fd);
6dd9f4bd 1939 ch.request = HTTPMSGLOCK(request);
506768d9 1940
1941 if (Config.accessList.brokenPosts)
1942 ch.accessList = cbdataReference(Config.accessList.brokenPosts);
62e76326 1943
108d65b2 1944 /* cbdataReferenceDone() happens in either fastCheck() or ~ACLCheckList */
1945
94439e4e 1946 if (!Config.accessList.brokenPosts) {
bf8fe701 1947 debugs(11, 5, "doneSendingRequestBody: No brokenPosts list");
9e008dda
AJ
1948 CommIoCbParams io(NULL);
1949 io.fd=fd;
1950 io.flag=COMM_OK;
1951 sendComplete(io);
b448c119 1952 } else if (!ch.fastCheck()) {
bf8fe701 1953 debugs(11, 5, "doneSendingRequestBody: didn't match brokenPosts");
9e008dda
AJ
1954 CommIoCbParams io(NULL);
1955 io.fd=fd;
1956 io.flag=COMM_OK;
1957 sendComplete(io);
94439e4e 1958 } else {
bf8fe701 1959 debugs(11, 2, "doneSendingRequestBody: matched brokenPosts");
9e008dda 1960 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
dc56a9b1 1961 Dialer dialer(this, &HttpStateData::sendComplete);
9e008dda 1962 AsyncCall::Pointer call= asyncCall(11,5, "HttpStateData::SendComplete", dialer);
dc56a9b1 1963 comm_write(fd, "\r\n", 2, call);
54220df8 1964 }
94439e4e 1965}
1966
5f8252d2 1967// more origin request body data is available
2bb867b5 1968void
5f8252d2 1969HttpStateData::handleMoreRequestBodyAvailable()
2bb867b5 1970{
2bb867b5 1971 if (eof || fd < 0) {
5f8252d2 1972 // XXX: we should check this condition in other callbacks then!
1973 // TODO: Check whether this can actually happen: We should unsubscribe
1974 // as a body consumer when the above condition(s) are detected.
2bb867b5 1975 debugs(11, 1, HERE << "Transaction aborted while reading HTTP body");
2bb867b5 1976 return;
1977 }
62e76326 1978
5f8252d2 1979 assert(requestBodySource != NULL);
fc68f6b1 1980
5f8252d2 1981 if (requestBodySource->buf().hasContent()) {
1982 // XXX: why does not this trigger a debug message on every request?
fc68f6b1 1983
2bb867b5 1984 if (flags.headers_parsed && !flags.abuse_detected) {
1985 flags.abuse_detected = 1;
cc192b50 1986 debugs(11, 1, "http handleMoreRequestBodyAvailable: Likely proxy abuse detected '" << orig_request->client_addr << "' -> '" << entry->url() << "'" );
21b92762 1987
585ab260 1988 if (virginReply()->sline.status == HTTP_INVALID_HEADER) {
2bb867b5 1989 comm_close(fd);
21b92762 1990 return;
1991 }
1992 }
b6a2f15e 1993 }
5f8252d2 1994
1995 HttpStateData::handleMoreRequestBodyAvailable();
376bb137 1996}
1997
5f8252d2 1998// premature end of the request body
2bb867b5 1999void
5f8252d2 2000HttpStateData::handleRequestBodyProducerAborted()
376bb137 2001{
5f8252d2 2002 ServerStateData::handleRequestBodyProducerAborted();
2003 // XXX: SendComplete(COMM_ERR_CLOSING) does little. Is it enough?
dc56a9b1 2004 CommIoCbParams io(NULL);
2005 io.fd=fd;
2006 io.flag=COMM_ERR_CLOSING;
2007 sendComplete(io);
2bb867b5 2008}
2009
5f8252d2 2010// called when we wrote request headers(!) or a part of the body
2bb867b5 2011void
dc56a9b1 2012HttpStateData::sentRequestBody(const CommIoCbParams &io)
2bb867b5 2013{
dc56a9b1 2014 if (io.size > 0)
2015 kb_incr(&statCounter.server.http.kbytes_out, io.size);
fc68f6b1 2016
dc56a9b1 2017 ServerStateData::sentRequestBody(io);
5f8252d2 2018}
3b299123 2019
5f8252d2 2020// Quickly abort the transaction
2021// TODO: destruction should be sufficient as the destructor should cleanup,
2022// including canceling close handlers
2023void
2024HttpStateData::abortTransaction(const char *reason)
2025{
2026 debugs(11,5, HERE << "aborting transaction for " << reason <<
2027 "; FD " << fd << ", this " << this);
fc68f6b1 2028
3e8c047e 2029 if (fd >= 0) {
62e76326 2030 comm_close(fd);
3e8c047e 2031 return;
c23f0c74 2032 }
3e8c047e 2033
2034 fwd->handleUnregisteredServerEnd();
dc56a9b1 2035 deleteThis("HttpStateData::abortTransaction");
54220df8 2036}
ccf44862 2037
073ba374 2038#if DEAD_CODE
ccf44862 2039void
450e0c10 2040httpBuildVersion(HttpVersion * version, unsigned int major, unsigned int minor)
110eb4e5 2041{
2042 version->major = major;
2043 version->minor = minor;
ccf44862 2044}
073ba374 2045#endif
2afaba07 2046
7c4e4e7f 2047HttpRequest *
2048HttpStateData::originalRequest()
2afaba07 2049{
7c4e4e7f 2050 return orig_request;
2afaba07 2051}