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