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