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