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