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