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