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