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