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