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