]> git.ipfire.org Git - thirdparty/squid.git/blame - src/http.cc
Reorder accel mode options a bit
[thirdparty/squid.git] / src / http.cc
CommitLineData
da2b3a17 1
30a4f2a8 2/*
262a0e14 3 * $Id$
30a4f2a8 4 *
5 * DEBUG: section 11 Hypertext Transfer Protocol (HTTP)
6 * AUTHOR: Harvest Derived
7 *
2b6662ba 8 * SQUID Web Proxy Cache http://www.squid-cache.org/
e25c139f 9 * ----------------------------------------------------------
30a4f2a8 10 *
2b6662ba 11 * Squid is the result of efforts by numerous individuals from
12 * the Internet community; see the CONTRIBUTORS file for full
13 * details. Many organizations have provided support for Squid's
14 * development; see the SPONSORS file for full details. Squid is
15 * Copyrighted (C) 2001 by the Regents of the University of
16 * California; see the COPYRIGHT file for full details. Squid
17 * incorporates software developed and/or copyrighted by other
18 * sources; see the CREDITS file for full details.
30a4f2a8 19 *
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 2 of the License, or
23 * (at your option) any later version.
9e008dda 24 *
30a4f2a8 25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
9e008dda 29 *
30a4f2a8 30 * You should have received a copy of the GNU General Public License
31 * along with this program; if not, write to the Free Software
cbdec147 32 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
e25c139f 33 *
30a4f2a8 34 */
019dd986 35
4a83b852 36/*
37 * Anonymizing patch by lutz@as-node.jena.thur.de
de3bdb4c 38 * have a look into http-anon.c to get more informations.
4a83b852 39 */
40
44a47c6e 41#include "squid.h"
9ca29d23
AJ
42
43#include "acl/FilledChecklist.h"
2f1431ea 44#if USE_AUTH
9ca29d23 45#include "auth/UserRequest.h"
2f1431ea 46#endif
655daa06 47#include "base/AsyncJobCalls.h"
3d93a84d 48#include "base/TextException.h"
25f98340 49#include "base64.h"
8d71285d 50#include "comm/Connection.h"
ec41b64c 51#include "comm/Write.h"
9a0a18de 52#if USE_DELAY_POOLS
9ca29d23
AJ
53#include "DelayPools.h"
54#endif
8b997339 55#include "err_detail_type.h"
aa839030 56#include "errorpage.h"
e6ccf245 57#include "http.h"
655daa06 58#include "HttpControlMsg.h"
528b2c61 59#include "HttpHdrContRange.h"
b19dd748 60#include "HttpHdrSc.h"
61#include "HttpHdrScTarget.h"
9ca29d23
AJ
62#include "HttpReply.h"
63#include "HttpRequest.h"
64#include "MemBuf.h"
65#include "MemObject.h"
66#include "protos.h"
1fa9b1a7 67#include "rfc1738.h"
985c86bc 68#include "SquidTime.h"
9ca29d23 69#include "Store.h"
af0bb8e5 70
9ca29d23 71
af0bb8e5 72#define SQUID_ENTER_THROWING_CODE() try {
73#define SQUID_EXIT_THROWING_CODE(status) \
74 status = true; \
75 } \
0a8bbeeb
AR
76 catch (const std::exception &e) { \
77 debugs (11, 1, "Exception error:" << e.what()); \
af0bb8e5 78 status = false; \
9e008dda 79 }
e6ccf245 80
2afaba07 81CBDATA_CLASS_INIT(HttpStateData);
090089c4 82
6bf8443a 83static const char *const crlf = "\r\n";
4db43fab 84
f9cece6e 85static void httpMaybeRemovePublic(StoreEntry *, http_status);
e24f13cd 86static void copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, const String strConnection, const HttpRequest * request,
9e498bfb 87 HttpHeader * hdr_out, const int we_do_ranges, const http_state_flags);
528b2c61 88
dc56a9b1 89HttpStateData::HttpStateData(FwdState *theFwdState) : AsyncJob("HttpStateData"), ServerStateData(theFwdState),
e1381638
AJ
90 lastChunk(0), header_bytes_read(0), reply_bytes_read(0),
91 body_bytes_truncated(0), httpChunkDecoder(NULL)
2bb867b5 92{
93 debugs(11,5,HERE << "HttpStateData " << this << " created");
a3d50c30 94 ignoreCacheControl = false;
95 surrogateNoStore = false;
8d71285d 96 serverConnection = fwd->serverConnection();
a3d50c30 97 readBuf = new MemBuf;
9cfb5f4d 98 readBuf->init(16*1024, 256*1024);
a3d50c30 99
3ff65596 100 // reset peer response time stats for %<pt
e24f13cd
CT
101 request->hier.peer_http_request_sent.tv_sec = 0;
102 request->hier.peer_http_request_sent.tv_usec = 0;
3ff65596 103
5229395c
AJ
104 if (fwd->serverConnection() != NULL)
105 _peer = cbdataReference(fwd->serverConnection()->getPeer()); /* might be NULL */
a3d50c30 106
107 if (_peer) {
e24f13cd 108 request->flags.proxying = 1;
a3d50c30 109 /*
110 * This NEIGHBOR_PROXY_ONLY check probably shouldn't be here.
111 * We might end up getting the object from somewhere else if,
112 * for example, the request to this neighbor fails.
113 */
114 if (_peer->options.proxy_only)
d88e3c49 115 entry->releaseRequest();
a3d50c30 116
9a0a18de 117#if USE_DELAY_POOLS
a3d50c30 118 entry->setNoDelay(_peer->options.no_delay);
a3d50c30 119#endif
a3d50c30 120 }
121
122 /*
123 * register the handler to free HTTP state data when the FD closes
124 */
dc56a9b1 125 typedef CommCbMemFunT<HttpStateData, CommCloseCbParams> Dialer;
d1c7f781 126 closeHandler = JobCallback(9, 5, Dialer, this, HttpStateData::httpStateConnClosed);
8d71285d 127 comm_add_close_handler(serverConnection->fd, closeHandler);
2bb867b5 128}
b8d8561b 129
2afaba07 130HttpStateData::~HttpStateData()
f5558c95 131{
253caccb 132 /*
3b299123 133 * don't forget that ~ServerStateData() gets called automatically
253caccb 134 */
135
2afaba07 136 if (!readBuf->isNull())
137 readBuf->clean();
62e76326 138
2afaba07 139 delete readBuf;
140
9e008dda
AJ
141 if (httpChunkDecoder)
142 delete httpChunkDecoder;
af0bb8e5 143
5229395c
AJ
144 cbdataReferenceDone(_peer);
145
9cf7de1b 146 debugs(11,5, HERE << "HttpStateData " << this << " destroyed; " << serverConnection);
5f8252d2 147}
148
6b679a01 149const Comm::ConnectionPointer &
e83cc785 150HttpStateData::dataConnection() const
fc68f6b1 151{
6b679a01 152 return serverConnection;
2afaba07 153}
8d71285d 154
dc56a9b1 155/*
2afaba07 156static void
157httpStateFree(int fd, void *data)
158{
159 HttpStateData *httpState = static_cast<HttpStateData *>(data);
bf8fe701 160 debugs(11, 5, "httpStateFree: FD " << fd << ", httpState=" << data);
5f8252d2 161 delete httpState;
dc56a9b1 162}*/
163
9e008dda 164void
dc56a9b1 165HttpStateData::httpStateConnClosed(const CommCloseCbParams &params)
166{
167 debugs(11, 5, "httpStateFree: FD " << params.fd << ", httpState=" << params.data);
168 deleteThis("HttpStateData::httpStateConnClosed");
f5558c95 169}
170
b8d8561b 171int
60745f24 172httpCachable(const HttpRequestMethod& method)
090089c4 173{
090089c4 174 /* GET and HEAD are cachable. Others are not. */
62e76326 175
9e008dda 176 // TODO: replase to HttpRequestMethod::isCachable() ?
6eb42cae 177 if (method != METHOD_GET && method != METHOD_HEAD)
62e76326 178 return 0;
179
090089c4 180 /* else cachable */
181 return 1;
182}
183
dc56a9b1 184void
185HttpStateData::httpTimeout(const CommTimeoutCbParams &params)
090089c4 186{
9cf7de1b 187 debugs(11, 4, HERE << serverConnection << ": '" << entry->url() << "'" );
62e76326 188
12158bdc 189 if (entry->store_status == STORE_PENDING) {
dc56a9b1 190 fwd->fail(errorCon(ERR_READ_TIMEOUT, HTTP_GATEWAY_TIMEOUT, fwd->request));
9b312a19 191 }
62e76326 192
8d71285d 193 serverConnection->close();
090089c4 194}
195
f9cece6e 196static void
197httpMaybeRemovePublic(StoreEntry * e, http_status status)
198{
914b89a2 199 int remove = 0;
7e3ce7b9 200 int forbidden = 0;
f9cece6e 201 StoreEntry *pe;
62e76326 202
d46a87a8 203 if (!EBIT_TEST(e->flags, KEY_PRIVATE))
62e76326 204 return;
205
f9cece6e 206 switch (status) {
62e76326 207
f9cece6e 208 case HTTP_OK:
62e76326 209
f9cece6e 210 case HTTP_NON_AUTHORITATIVE_INFORMATION:
62e76326 211
f9cece6e 212 case HTTP_MULTIPLE_CHOICES:
62e76326 213
f9cece6e 214 case HTTP_MOVED_PERMANENTLY:
62e76326 215
f9cece6e 216 case HTTP_MOVED_TEMPORARILY:
62e76326 217
f9cece6e 218 case HTTP_GONE:
62e76326 219
7e3ce7b9 220 case HTTP_NOT_FOUND:
914b89a2 221 remove = 1;
62e76326 222
223 break;
224
7e3ce7b9 225 case HTTP_FORBIDDEN:
62e76326 226
7e3ce7b9 227 case HTTP_METHOD_NOT_ALLOWED:
62e76326 228 forbidden = 1;
229
230 break;
231
f9cece6e 232#if WORK_IN_PROGRESS
62e76326 233
c8fd0193 234 case HTTP_UNAUTHORIZED:
62e76326 235 forbidden = 1;
236
237 break;
238
f9cece6e 239#endif
62e76326 240
f9cece6e 241 default:
7e3ce7b9 242#if QUESTIONABLE
62e76326 243 /*
244 * Any 2xx response should eject previously cached entities...
245 */
abb929f0 246
62e76326 247 if (status >= 200 && status < 300)
914b89a2 248 remove = 1;
62e76326 249
7e3ce7b9 250#endif
62e76326 251
252 break;
f9cece6e 253 }
62e76326 254
914b89a2 255 if (!remove && !forbidden)
62e76326 256 return;
257
f9cece6e 258 assert(e->mem_obj);
62e76326 259
f66a9ef4 260 if (e->mem_obj->request)
62e76326 261 pe = storeGetPublicByRequest(e->mem_obj->request);
f66a9ef4 262 else
62e76326 263 pe = storeGetPublic(e->mem_obj->url, e->mem_obj->method);
264
f66a9ef4 265 if (pe != NULL) {
62e76326 266 assert(e != pe);
d9129474 267#if USE_HTCP
8dceeee3 268 neighborsHtcpClear(e, NULL, e->mem_obj->request, e->mem_obj->method, HTCP_CLR_INVALIDATION);
d9129474 269#endif
5f33b71d 270 pe->release();
0856d155 271 }
62e76326 272
914b89a2 273 /** \par
7e3ce7b9 274 * Also remove any cached HEAD response in case the object has
275 * changed.
276 */
f66a9ef4 277 if (e->mem_obj->request)
62e76326 278 pe = storeGetPublicByRequestMethod(e->mem_obj->request, METHOD_HEAD);
f66a9ef4 279 else
62e76326 280 pe = storeGetPublic(e->mem_obj->url, METHOD_HEAD);
281
f66a9ef4 282 if (pe != NULL) {
62e76326 283 assert(e != pe);
d9129474 284#if USE_HTCP
8dceeee3 285 neighborsHtcpClear(e, NULL, e->mem_obj->request, HttpRequestMethod(METHOD_HEAD), HTCP_CLR_INVALIDATION);
d9129474 286#endif
5f33b71d 287 pe->release();
7e3ce7b9 288 }
f9cece6e 289}
290
43ae1d95 291void
292HttpStateData::processSurrogateControl(HttpReply *reply)
293{
43ae1d95 294 if (request->flags.accelerated && reply->surrogate_control) {
45cca89d 295 HttpHdrScTarget *sctusable = httpHdrScGetMergedTarget(reply->surrogate_control, Config.Accel.surrogate_id);
43ae1d95 296
297 if (sctusable) {
298 if (EBIT_TEST(sctusable->mask, SC_NO_STORE) ||
299 (Config.onoff.surrogate_is_remote
300 && EBIT_TEST(sctusable->mask, SC_NO_STORE_REMOTE))) {
301 surrogateNoStore = true;
5ed72359 302 entry->makePrivate();
43ae1d95 303 }
304
305 /* The HttpHeader logic cannot tell if the header it's parsing is a reply to an
306 * accelerated request or not...
45cca89d 307 * Still, this is an abstraction breach. - RC
43ae1d95 308 */
309 if (sctusable->max_age != -1) {
310 if (sctusable->max_age < sctusable->max_stale)
311 reply->expires = reply->date + sctusable->max_age;
312 else
313 reply->expires = reply->date + sctusable->max_stale;
314
315 /* And update the timestamps */
3900307b 316 entry->timestampsSet();
43ae1d95 317 }
318
319 /* We ignore cache-control directives as per the Surrogate specification */
320 ignoreCacheControl = true;
321
322 httpHdrScTargetDestroy(sctusable);
323 }
324 }
43ae1d95 325}
326
924f73bc 327int
328HttpStateData::cacheableReply()
c54e9052 329{
585ab260 330 HttpReply const *rep = finalReply();
528b2c61 331 HttpHeader const *hdr = &rep->header;
d8b249ef 332 const int cc_mask = (rep->cache_control) ? rep->cache_control->mask : 0;
c68e9c6b 333 const char *v;
626096be 334#if USE_HTTP_VIOLATIONS
62e76326 335
38f9c547 336 const refresh_t *R = NULL;
b6445726 337
346be6ad 338 /* This strange looking define first looks up the refresh pattern
b6445726 339 * and then checks if the specified flag is set. The main purpose
626096be 340 * of this is to simplify the refresh pattern lookup and USE_HTTP_VIOLATIONS
b6445726 341 * condition
342 */
343#define REFRESH_OVERRIDE(flag) \
5f8252d2 344 ((R = (R ? R : refreshLimits(entry->mem_obj->url))) , \
345 (R && R->flags.flag))
b445957e 346#else
347#define REFRESH_OVERRIDE(flag) 0
38f9c547 348#endif
43ae1d95 349
38f9c547 350 if (surrogateNoStore)
62e76326 351 return 0;
352
8466a4af
AR
353 // RFC 2616: do not cache replies to responses with no-store CC directive
354 if (request && request->cache_control &&
ab745b44
A
355 EBIT_TEST(request->cache_control->mask, CC_NO_STORE) &&
356 !REFRESH_OVERRIDE(ignore_no_store))
8466a4af
AR
357 return 0;
358
924f73bc 359 if (!ignoreCacheControl) {
38f9c547 360 if (EBIT_TEST(cc_mask, CC_PRIVATE)) {
b6445726 361 if (!REFRESH_OVERRIDE(ignore_private))
38f9c547 362 return 0;
363 }
364
365 if (EBIT_TEST(cc_mask, CC_NO_CACHE)) {
b6445726 366 if (!REFRESH_OVERRIDE(ignore_no_cache))
38f9c547 367 return 0;
368 }
369
370 if (EBIT_TEST(cc_mask, CC_NO_STORE)) {
b6445726 371 if (!REFRESH_OVERRIDE(ignore_no_store))
38f9c547 372 return 0;
373 }
43ae1d95 374 }
375
d67acb4e 376 if (request->flags.auth || request->flags.auth_sent) {
62e76326 377 /*
378 * Responses to requests with authorization may be cached
379 * only if a Cache-Control: public reply header is present.
380 * RFC 2068, sec 14.9.4
381 */
382
38f9c547 383 if (!EBIT_TEST(cc_mask, CC_PUBLIC)) {
b6445726 384 if (!REFRESH_OVERRIDE(ignore_auth))
38f9c547 385 return 0;
386 }
a6dfe2d9 387 }
62e76326 388
c68e9c6b 389 /* Pragma: no-cache in _replies_ is not documented in HTTP,
390 * but servers like "Active Imaging Webcast/2.0" sure do use it */
a9925b40 391 if (hdr->has(HDR_PRAGMA)) {
30abd221 392 String s = hdr->getList(HDR_PRAGMA);
62e76326 393 const int no_cache = strListIsMember(&s, "no-cache", ',');
30abd221 394 s.clean();
62e76326 395
38f9c547 396 if (no_cache) {
b6445726 397 if (!REFRESH_OVERRIDE(ignore_no_cache))
38f9c547 398 return 0;
399 }
c68e9c6b 400 }
62e76326 401
c68e9c6b 402 /*
403 * The "multipart/x-mixed-replace" content type is used for
404 * continuous push replies. These are generally dynamic and
405 * probably should not be cachable
406 */
a9925b40 407 if ((v = hdr->getStr(HDR_CONTENT_TYPE)))
62e76326 408 if (!strncasecmp(v, "multipart/x-mixed-replace", 25))
409 return 0;
410
585ab260 411 switch (rep->sline.status) {
62e76326 412 /* Responses that are cacheable */
413
19a04dac 414 case HTTP_OK:
62e76326 415
19a04dac 416 case HTTP_NON_AUTHORITATIVE_INFORMATION:
62e76326 417
19a04dac 418 case HTTP_MULTIPLE_CHOICES:
62e76326 419
19a04dac 420 case HTTP_MOVED_PERMANENTLY:
62e76326 421
19a04dac 422 case HTTP_GONE:
62e76326 423 /*
424 * Don't cache objects that need to be refreshed on next request,
425 * unless we know how to refresh it.
426 */
427
3d8b6ba4 428 if (!refreshIsCachable(entry) && !REFRESH_OVERRIDE(store_stale)) {
bf8fe701 429 debugs(22, 3, "refreshIsCachable() returned non-cacheable..");
62e76326 430 return 0;
ca34dacd 431 } else
62e76326 432 return 1;
433
62e76326 434 /* NOTREACHED */
435 break;
436
437 /* Responses that only are cacheable if the server says so */
438
19a04dac 439 case HTTP_MOVED_TEMPORARILY:
f18c86fd 440 case HTTP_TEMPORARY_REDIRECT:
6a2bf8f4 441 if (rep->expires > rep->date && rep->date > 0)
62e76326 442 return 1;
443 else
444 return 0;
445
446 /* NOTREACHED */
447 break;
448
449 /* Errors can be negatively cached */
450
19a04dac 451 case HTTP_NO_CONTENT:
62e76326 452
19a04dac 453 case HTTP_USE_PROXY:
62e76326 454
19a04dac 455 case HTTP_BAD_REQUEST:
62e76326 456
19a04dac 457 case HTTP_FORBIDDEN:
62e76326 458
19a04dac 459 case HTTP_NOT_FOUND:
62e76326 460
19a04dac 461 case HTTP_METHOD_NOT_ALLOWED:
62e76326 462
19a04dac 463 case HTTP_REQUEST_URI_TOO_LARGE:
62e76326 464
19a04dac 465 case HTTP_INTERNAL_SERVER_ERROR:
62e76326 466
19a04dac 467 case HTTP_NOT_IMPLEMENTED:
62e76326 468
19a04dac 469 case HTTP_BAD_GATEWAY:
62e76326 470
19a04dac 471 case HTTP_SERVICE_UNAVAILABLE:
62e76326 472
19a04dac 473 case HTTP_GATEWAY_TIMEOUT:
62e76326 474 return -1;
475
476 /* NOTREACHED */
477 break;
478
479 /* Some responses can never be cached */
480
0cdcddb9 481 case HTTP_PARTIAL_CONTENT: /* Not yet supported */
62e76326 482
19a04dac 483 case HTTP_SEE_OTHER:
62e76326 484
19a04dac 485 case HTTP_NOT_MODIFIED:
62e76326 486
19a04dac 487 case HTTP_UNAUTHORIZED:
62e76326 488
19a04dac 489 case HTTP_PROXY_AUTHENTICATION_REQUIRED:
62e76326 490
0cdcddb9 491 case HTTP_INVALID_HEADER: /* Squid header parsing error */
4eb368f9 492
493 case HTTP_HEADER_TOO_LARGE:
b004a7fc 494
495 case HTTP_PAYMENT_REQUIRED:
496 case HTTP_NOT_ACCEPTABLE:
497 case HTTP_REQUEST_TIMEOUT:
498 case HTTP_CONFLICT:
499 case HTTP_LENGTH_REQUIRED:
500 case HTTP_PRECONDITION_FAILED:
501 case HTTP_REQUEST_ENTITY_TOO_LARGE:
502 case HTTP_UNSUPPORTED_MEDIA_TYPE:
503 case HTTP_UNPROCESSABLE_ENTITY:
504 case HTTP_LOCKED:
505 case HTTP_FAILED_DEPENDENCY:
506 case HTTP_INSUFFICIENT_STORAGE:
cc7c3c84 507 case HTTP_REQUESTED_RANGE_NOT_SATISFIABLE:
508 case HTTP_EXPECTATION_FAILED:
b004a7fc 509
62e76326 510 return 0;
511
41217979
AJ
512 default:
513 /* RFC 2616 section 6.1.1: an unrecognized response MUST NOT be cached. */
514 debugs (11, 3, HERE << "Unknown HTTP status code " << rep->sline.status << ". Not cacheable.");
62e76326 515
516 return 0;
517
518 /* NOTREACHED */
519 break;
c54e9052 520 }
62e76326 521
79d39a72 522 /* NOTREACHED */
c54e9052 523}
090089c4 524
f66a9ef4 525/*
9e008dda 526 * For Vary, store the relevant request headers as
f66a9ef4 527 * virtual headers in the reply
528 * Returns false if the variance cannot be stored
529 */
530const char *
190154cf 531httpMakeVaryMark(HttpRequest * request, HttpReply const * reply)
f66a9ef4 532{
30abd221 533 String vary, hdr;
f66a9ef4 534 const char *pos = NULL;
535 const char *item;
536 const char *value;
537 int ilen;
30abd221 538 static String vstr;
f66a9ef4 539
30abd221 540 vstr.clean();
a9925b40 541 vary = reply->header.getList(HDR_VARY);
62e76326 542
f66a9ef4 543 while (strListGetItem(&vary, ',', &item, &ilen, &pos)) {
62e76326 544 char *name = (char *)xmalloc(ilen + 1);
545 xstrncpy(name, item, ilen + 1);
546 Tolower(name);
9776e3cc 547
548 if (strcmp(name, "*") == 0) {
549 /* Can not handle "Vary: *" withtout ETag support */
550 safe_free(name);
30abd221 551 vstr.clean();
9776e3cc 552 break;
553 }
554
62e76326 555 strListAdd(&vstr, name, ',');
a9925b40 556 hdr = request->header.getByName(name);
62e76326 557 safe_free(name);
d53b3f6d 558 value = hdr.termedBuf();
62e76326 559
560 if (value) {
561 value = rfc1738_escape_part(value);
562 vstr.append("=\"", 2);
563 vstr.append(value);
564 vstr.append("\"", 1);
565 }
566
30abd221 567 hdr.clean();
f66a9ef4 568 }
62e76326 569
30abd221 570 vary.clean();
f66a9ef4 571#if X_ACCELERATOR_VARY
62e76326 572
aa38be4a 573 pos = NULL;
a9925b40 574 vary = reply->header.getList(HDR_X_ACCELERATOR_VARY);
62e76326 575
f66a9ef4 576 while (strListGetItem(&vary, ',', &item, &ilen, &pos)) {
62e76326 577 char *name = (char *)xmalloc(ilen + 1);
578 xstrncpy(name, item, ilen + 1);
579 Tolower(name);
580 strListAdd(&vstr, name, ',');
a9925b40 581 hdr = request->header.getByName(name);
62e76326 582 safe_free(name);
d53b3f6d 583 value = hdr.termedBuf();
62e76326 584
585 if (value) {
586 value = rfc1738_escape_part(value);
587 vstr.append("=\"", 2);
588 vstr.append(value);
589 vstr.append("\"", 1);
590 }
591
30abd221 592 hdr.clean();
f66a9ef4 593 }
62e76326 594
30abd221 595 vary.clean();
f66a9ef4 596#endif
62e76326 597
d53b3f6d
FC
598 debugs(11, 3, "httpMakeVaryMark: " << vstr);
599 return vstr.termedBuf();
f66a9ef4 600}
601
2afaba07 602void
603HttpStateData::keepaliveAccounting(HttpReply *reply)
604{
605 if (flags.keepalive)
606 if (_peer)
607 _peer->stats.n_keepalives_sent++;
608
609 if (reply->keep_alive) {
610 if (_peer)
611 _peer->stats.n_keepalives_recv++;
612
af6a12ee
AJ
613 if (Config.onoff.detect_broken_server_pconns
614 && reply->bodySize(request->method) == -1 && !flags.chunked) {
bf8fe701 615 debugs(11, 1, "keepaliveAccounting: Impossible keep-alive header from '" << entry->url() << "'" );
616 // debugs(11, 2, "GOT HTTP REPLY HDR:\n---------\n" << readBuf->content() << "\n----------" );
2afaba07 617 flags.keepalive_broken = 1;
618 }
619 }
620}
621
622void
623HttpStateData::checkDateSkew(HttpReply *reply)
624{
625 if (reply->date > -1 && !_peer) {
626 int skew = abs((int)(reply->date - squid_curtime));
627
628 if (skew > 86400)
cc192b50 629 debugs(11, 3, "" << request->GetHost() << "'s clock is skewed by " << skew << " seconds!");
2afaba07 630 }
631}
632
073ba374 633/**
4eb368f9 634 * This creates the error page itself.. its likely
635 * that the forward ported reply header max size patch
636 * generates non http conformant error pages - in which
637 * case the errors where should be 'BAD_GATEWAY' etc
638 */
b8d8561b 639void
2afaba07 640HttpStateData::processReplyHeader()
f5558c95 641{
073ba374 642 /** Creates a blank header. If this routine is made incremental, this will not do */
859f1666
AJ
643
644 /* NP: all exit points to this function MUST call ctx_exit(ctx) */
82384411 645 Ctx ctx = ctx_enter(entry->mem_obj->url);
859f1666 646
bf8fe701 647 debugs(11, 3, "processReplyHeader: key '" << entry->getMD5Text() << "'");
62e76326 648
1a98175f 649 assert(!flags.headers_parsed);
62e76326 650
859f1666
AJ
651 if (!readBuf->hasContent()) {
652 ctx_exit(ctx);
b73a07d6 653 return;
859f1666 654 }
b73a07d6 655
2afaba07 656 http_status error = HTTP_STATUS_NONE;
62e76326 657
585ab260 658 HttpReply *newrep = new HttpReply;
4a56ee8d 659 const bool parsed = newrep->parse(readBuf, eof, &error);
62e76326 660
e77d7ef0 661 if (!parsed && readBuf->contentSize() > 5 && strncmp(readBuf->content(), "HTTP/", 5) != 0 && strncmp(readBuf->content(), "ICY", 3) != 0) {
9e008dda
AJ
662 MemBuf *mb;
663 HttpReply *tmprep = new HttpReply;
11992b6f 664 tmprep->setHeaders(HTTP_OK, "Gatewaying", NULL, -1, -1, -1);
9e008dda
AJ
665 tmprep->header.putExt("X-Transformed-From", "HTTP/0.9");
666 mb = tmprep->pack();
667 newrep->parse(mb, eof, &error);
ddbe383d 668 delete mb;
9e008dda
AJ
669 delete tmprep;
670 } else {
671 if (!parsed && error > 0) { // unrecoverable parsing error
672 debugs(11, 3, "processReplyHeader: Non-HTTP-compliant header: '" << readBuf->content() << "'");
673 flags.headers_parsed = 1;
871c031f 674 newrep->sline.version = HttpVersion(1,1);
9e008dda
AJ
675 newrep->sline.status = error;
676 HttpReply *vrep = setVirginReply(newrep);
677 entry->replaceHttpReply(vrep);
678 ctx_exit(ctx);
679 return;
680 }
681
682 if (!parsed) { // need more data
683 assert(!error);
684 assert(!eof);
685 delete newrep;
686 ctx_exit(ctx);
687 return;
688 }
689
690 debugs(11, 9, "GOT HTTP REPLY HDR:\n---------\n" << readBuf->content() << "\n----------");
691
692 header_bytes_read = headersEnd(readBuf->content(), readBuf->contentSize());
693 readBuf->consume(header_bytes_read);
f5558c95 694 }
62e76326 695
c679653d 696 newrep->removeStaleWarnings();
3d9e71e6 697
0c3d3f65 698 if (newrep->sline.protocol == AnyP::PROTO_HTTP && newrep->sline.status >= 100 && newrep->sline.status < 200) {
655daa06 699 handle1xx(newrep);
3d9e71e6 700 ctx_exit(ctx);
3d9e71e6
AJ
701 return;
702 }
703
af0bb8e5 704 flags.chunked = 0;
0c3d3f65 705 if (newrep->sline.protocol == AnyP::PROTO_HTTP && newrep->header.chunked()) {
9e008dda
AJ
706 flags.chunked = 1;
707 httpChunkDecoder = new ChunkedCodingParser;
af0bb8e5 708 }
709
9e008dda 710 if (!peerSupportsConnectionPinning())
e24f13cd 711 request->flags.connection_auth_disabled = 1;
d67acb4e 712
585ab260 713 HttpReply *vrep = setVirginReply(newrep);
6965ab28 714 flags.headers_parsed = 1;
715
585ab260 716 keepaliveAccounting(vrep);
47ac2ebe 717
585ab260 718 checkDateSkew(vrep);
47ac2ebe 719
585ab260 720 processSurrogateControl (vrep);
528b2c61 721
073ba374 722 /** \todo IF the reply is a 1.0 reply, AND it has a Connection: Header
528b2c61 723 * Parse the header and remove all referenced headers
724 */
725
e24f13cd 726 request->hier.peer_reply_status = newrep->sline.status;
3ff65596 727
2afaba07 728 ctx_exit(ctx);
729}
730
655daa06
AR
731/// ignore or start forwarding the 1xx response (a.k.a., control message)
732void
733HttpStateData::handle1xx(HttpReply *reply)
734{
735 HttpMsgPointerT<HttpReply> msg(reply); // will destroy reply if unused
736
737 // one 1xx at a time: we must not be called while waiting for previous 1xx
738 Must(!flags.handling1xx);
739 flags.handling1xx = true;
740
e24f13cd 741 if (!request->canHandle1xx()) {
655daa06
AR
742 debugs(11, 2, HERE << "ignoring client-unsupported 1xx");
743 proceedAfter1xx();
744 return;
745 }
746
747#if USE_HTTP_VIOLATIONS
748 // check whether the 1xx response forwarding is allowed by squid.conf
749 if (Config.accessList.reply) {
e11513e1 750 ACLFilledChecklist ch(Config.accessList.reply, originalRequest(), NULL);
655daa06
AR
751 ch.reply = HTTPMSGLOCK(reply);
752 if (!ch.fastCheck()) { // TODO: support slow lookups?
753 debugs(11, 3, HERE << "ignoring denied 1xx");
754 proceedAfter1xx();
755 return;
de48b288 756 }
655daa06
AR
757 }
758#endif // USE_HTTP_VIOLATIONS
759
760 debugs(11, 2, HERE << "forwarding 1xx to client");
761
762 // the Sink will use this to call us back after writing 1xx to the client
763 typedef NullaryMemFunT<HttpStateData> CbDialer;
764 const AsyncCall::Pointer cb = JobCallback(11, 3, CbDialer, this,
de48b288 765 HttpStateData::proceedAfter1xx);
e24f13cd 766 CallJobHere1(11, 4, request->clientConnectionManager, ConnStateData,
655daa06
AR
767 ConnStateData::sendControlMsg, HttpControlMsg(msg, cb));
768 // If the call is not fired, then the Sink is gone, and HttpStateData
769 // will terminate due to an aborted store entry or another similar error.
770 // If we get stuck, it is not handle1xx fault if we could get stuck
771 // for similar reasons without a 1xx response.
772}
773
774/// restores state and resumes processing after 1xx is ignored or forwarded
775void
776HttpStateData::proceedAfter1xx()
777{
778 Must(flags.handling1xx);
779
780 debugs(11, 2, HERE << "consuming " << header_bytes_read <<
de48b288 781 " header and " << reply_bytes_read << " body bytes read after 1xx");
655daa06
AR
782 header_bytes_read = 0;
783 reply_bytes_read = 0;
784
785 CallJobHere(11, 3, this, HttpStateData, HttpStateData::processReply);
786}
787
788
d67acb4e
AJ
789/**
790 * returns true if the peer can support connection pinning
791*/
792bool HttpStateData::peerSupportsConnectionPinning() const
793{
794 const HttpReply *rep = entry->mem_obj->getReply();
795 const HttpHeader *hdr = &rep->header;
796 bool rc;
797 String header;
798
799 if (!_peer)
9e008dda
AJ
800 return true;
801
802 /*If this peer does not support connection pinning (authenticated
d67acb4e
AJ
803 connections) return false
804 */
805 if (!_peer->connection_auth)
9e008dda 806 return false;
d67acb4e 807
9e008dda 808 /*The peer supports connection pinning and the http reply status
d67acb4e
AJ
809 is not unauthorized, so the related connection can be pinned
810 */
811 if (rep->sline.status != HTTP_UNAUTHORIZED)
9e008dda
AJ
812 return true;
813
814 /*The server respond with HTTP_UNAUTHORIZED and the peer configured
815 with "connection-auth=on" we know that the peer supports pinned
d67acb4e
AJ
816 connections
817 */
818 if (_peer->connection_auth == 1)
9e008dda 819 return true;
d67acb4e 820
9e008dda
AJ
821 /*At this point peer has configured with "connection-auth=auto"
822 parameter so we need some extra checks to decide if we are going
d67acb4e
AJ
823 to allow pinned connections or not
824 */
825
9e008dda 826 /*if the peer configured with originserver just allow connection
d67acb4e
AJ
827 pinning (squid 2.6 behaviour)
828 */
829 if (_peer->options.originserver)
9e008dda 830 return true;
d67acb4e
AJ
831
832 /*if the connections it is already pinned it is OK*/
833 if (request->flags.pinned)
9e008dda
AJ
834 return true;
835
836 /*Allow pinned connections only if the Proxy-support header exists in
837 reply and has in its list the "Session-Based-Authentication"
d67acb4e
AJ
838 which means that the peer supports connection pinning.
839 */
840 if (!hdr->has(HDR_PROXY_SUPPORT))
9e008dda 841 return false;
d67acb4e
AJ
842
843 header = hdr->getStrOrList(HDR_PROXY_SUPPORT);
844 /* XXX This ought to be done in a case-insensitive manner */
d53b3f6d 845 rc = (strstr(header.termedBuf(), "Session-Based-Authentication") != NULL);
d67acb4e
AJ
846
847 return rc;
848}
849
5f8252d2 850// Called when we parsed (and possibly adapted) the headers but
851// had not starting storing (a.k.a., sending) the body yet.
2afaba07 852void
853HttpStateData::haveParsedReplyHeaders()
854{
c1520b67
AJ
855 ServerStateData::haveParsedReplyHeaders();
856
2afaba07 857 Ctx ctx = ctx_enter(entry->mem_obj->url);
585ab260 858 HttpReply *rep = finalReply();
2afaba07 859
585ab260 860 if (rep->sline.status == HTTP_PARTIAL_CONTENT &&
861 rep->content_range)
862 currentOffset = rep->content_range->spec.offset;
62e76326 863
3900307b 864 entry->timestampsSet();
62e76326 865
9bc73deb 866 /* Check if object is cacheable or not based on reply code */
585ab260 867 debugs(11, 3, "haveParsedReplyHeaders: HTTP CODE: " << rep->sline.status);
62e76326 868
9bc73deb 869 if (neighbors_do_private_keys)
585ab260 870 httpMaybeRemovePublic(entry, rep->sline.status);
e6ccf245 871
585ab260 872 if (rep->header.has(HDR_VARY)
f66a9ef4 873#if X_ACCELERATOR_VARY
585ab260 874 || rep->header.has(HDR_X_ACCELERATOR_VARY)
f66a9ef4 875#endif
4b44c907 876 ) {
e24f13cd 877 const char *vary = httpMakeVaryMark(request, rep);
4b44c907 878
879 if (!vary) {
5ed72359 880 entry->makePrivate();
d7d3253b
AJ
881 if (!fwd->reforwardableStatus(rep->sline.status))
882 EBIT_CLR(entry->flags, ENTRY_FWD_HDR_WAIT);
4b44c907 883 goto no_cache;
62e76326 884 }
885
4b44c907 886 entry->mem_obj->vary_headers = xstrdup(vary);
887 }
888
2afaba07 889 /*
890 * If its not a reply that we will re-forward, then
891 * allow the client to get it.
892 */
585ab260 893 if (!fwd->reforwardableStatus(rep->sline.status))
2afaba07 894 EBIT_CLR(entry->flags, ENTRY_FWD_HDR_WAIT);
895
4b44c907 896 switch (cacheableReply()) {
897
898 case 1:
5ed72359 899 entry->makePublic();
62e76326 900 break;
901
9bc73deb 902 case 0:
5ed72359 903 entry->makePrivate();
62e76326 904 break;
905
9bc73deb 906 case -1:
4b44c907 907
626096be 908#if USE_HTTP_VIOLATIONS
4b44c907 909 if (Config.negativeTtl > 0)
5ed72359 910 entry->cacheNegatively();
4b44c907 911 else
ac9cc053 912#endif
5ed72359 913 entry->makePrivate();
4b44c907 914
62e76326 915 break;
916
9bc73deb 917 default:
62e76326 918 assert(0);
4b44c907 919
62e76326 920 break;
9bc73deb 921 }
62e76326 922
4b44c907 923no_cache:
924
585ab260 925 if (!ignoreCacheControl && rep->cache_control) {
7948b784 926 if (EBIT_TEST(rep->cache_control->mask, CC_PROXY_REVALIDATE) ||
477438e1
A
927 EBIT_TEST(rep->cache_control->mask, CC_MUST_REVALIDATE) ||
928 EBIT_TEST(rep->cache_control->mask, CC_S_MAXAGE))
62e76326 929 EBIT_SET(entry->flags, ENTRY_REVALIDATE);
9bc73deb 930 }
62e76326 931
c3609322 932#if HEADERS_LOG
585ab260 933 headersLog(1, 0, request->method, rep);
fc68f6b1 934
c3609322 935#endif
5f8252d2 936
937 ctx_exit(ctx);
f5558c95 938}
939
528b2c61 940HttpStateData::ConnectionStatus
941HttpStateData::statusIfComplete() const
603a02fd 942{
585ab260 943 const HttpReply *rep = virginReply();
073ba374
AJ
944 /** \par
945 * If the reply wants to close the connection, it takes precedence */
62e76326 946
2afaba07 947 if (httpHeaderHasConnDir(&rep->header, "close"))
62e76326 948 return COMPLETE_NONPERSISTENT_MSG;
949
073ba374
AJ
950 /** \par
951 * If we didn't send a keep-alive request header, then this
978e455f 952 * can not be a persistent connection.
953 */
528b2c61 954 if (!flags.keepalive)
62e76326 955 return COMPLETE_NONPERSISTENT_MSG;
956
073ba374 957 /** \par
72b63f06 958 * If we haven't sent the whole request then this can not be a persistent
959 * connection.
960 */
961 if (!flags.request_sent) {
e24f13cd 962 debugs(11, 2, "statusIfComplete: Request not yet fully sent \"" << RequestMethodStr(request->method) << " " << entry->url() << "\"" );
72b63f06 963 return COMPLETE_NONPERSISTENT_MSG;
964 }
965
073ba374 966 /** \par
9f5a2895 967 * What does the reply have to say about keep-alive?
968 */
073ba374
AJ
969 /**
970 \bug XXX BUG?
b6a2f15e 971 * If the origin server (HTTP/1.0) does not send a keep-alive
972 * header, but keeps the connection open anyway, what happens?
973 * We'll return here and http.c waits for an EOF before changing
974 * store_status to STORE_OK. Combine this with ENTRY_FWD_HDR_WAIT
975 * and an error status code, and we might have to wait until
976 * the server times out the socket.
977 */
2afaba07 978 if (!rep->keep_alive)
528b2c61 979 return COMPLETE_NONPERSISTENT_MSG;
62e76326 980
528b2c61 981 return COMPLETE_PERSISTENT_MSG;
982}
983
984HttpStateData::ConnectionStatus
985HttpStateData::persistentConnStatus() const
986{
9cf7de1b 987 debugs(11, 3, HERE << serverConnection << " eof=" << eof);
839291ac
AJ
988 if (eof) // already reached EOF
989 return COMPLETE_NONPERSISTENT_MSG;
990
505c2f28
AR
991 /* If server fd is closing (but we have not been notified yet), stop Comm
992 I/O to avoid assertions. TODO: Change Comm API to handle callers that
993 want more I/O after async closing (usually initiated by others). */
994 // XXX: add canReceive or s/canSend/canTalkToServer/
e7cea0ed 995 if (!Comm::IsConnOpen(serverConnection))
505c2f28
AR
996 return COMPLETE_NONPERSISTENT_MSG;
997
9035d1d5
AJ
998 /** \par
999 * In chunked response we do not know the content length but we are absolutely
af0bb8e5 1000 * sure about the end of response, so we are calling the statusIfComplete to
9e008dda 1001 * decide if we can be persistant
af0bb8e5 1002 */
839291ac 1003 if (lastChunk && flags.chunked)
9e008dda 1004 return statusIfComplete();
af0bb8e5 1005
718d84bf
AR
1006 const HttpReply *vrep = virginReply();
1007 debugs(11, 5, "persistentConnStatus: content_length=" << vrep->content_length);
1008
47f6e231 1009 const int64_t clen = vrep->bodySize(request->method);
fc68f6b1 1010
bf8fe701 1011 debugs(11, 5, "persistentConnStatus: clen=" << clen);
2afaba07 1012
35282fbf 1013 /* If the body size is unknown we must wait for EOF */
1014 if (clen < 0)
62e76326 1015 return INCOMPLETE_MSG;
1016
9035d1d5
AJ
1017 /** \par
1018 * If the body size is known, we must wait until we've gotten all of it. */
5f8252d2 1019 if (clen > 0) {
1020 // old technique:
585ab260 1021 // if (entry->mem_obj->endOffset() < vrep->content_length + vrep->hdr_sz)
47f6e231 1022 const int64_t body_bytes_read = reply_bytes_read - header_bytes_read;
5f8252d2 1023 debugs(11,5, "persistentConnStatus: body_bytes_read=" <<
585ab260 1024 body_bytes_read << " content_length=" << vrep->content_length);
2afaba07 1025
585ab260 1026 if (body_bytes_read < vrep->content_length)
5f8252d2 1027 return INCOMPLETE_MSG;
821beb5e
AR
1028
1029 if (body_bytes_truncated > 0) // already read more than needed
1030 return COMPLETE_NONPERSISTENT_MSG; // disable pconns
5f8252d2 1031 }
62e76326 1032
9035d1d5
AJ
1033 /** \par
1034 * If there is no message body or we got it all, we can be persistent */
5f8252d2 1035 return statusIfComplete();
603a02fd 1036}
090089c4 1037
2afaba07 1038/*
1039 * This is the callback after some data has been read from the network
1040 */
dc56a9b1 1041/*
e5ee81f0 1042void
d53b3f6d 1043HttpStateData::ReadReplyWrapper(int fd, char *buf, size_t len, comm_err_t flag, int xerrno, void *data)
c4b7a5a9 1044{
1045 HttpStateData *httpState = static_cast<HttpStateData *>(data);
8d71285d 1046 assert (fd == httpState->serverConnection->fd);
d53b3f6d 1047 // assert(buf == readBuf->content());
1d5161bd 1048 PROF_start(HttpStateData_readReply);
e6edd8df 1049 httpState->readReply(len, flag, xerrno);
1d5161bd 1050 PROF_stop(HttpStateData_readReply);
c4b7a5a9 1051}
dc56a9b1 1052*/
073ba374 1053
2afdbf48 1054/* XXX this function is too long! */
c4b7a5a9 1055void
e6edd8df 1056HttpStateData::readReply(const CommIoCbParams &io)
090089c4 1057{
30a4f2a8 1058 int bin;
090089c4 1059 int clen;
dc56a9b1 1060 int len = io.size;
c4b7a5a9 1061
dc56a9b1 1062 flags.do_next_read = 0;
9e008dda 1063
3e4bebf8 1064 debugs(11, 5, HERE << io.conn << ": len " << len << ".");
62e76326 1065
7a7cc03f 1066 // Bail out early on COMM_ERR_CLOSING - close handlers will tidy up for us
dc56a9b1 1067 if (io.flag == COMM_ERR_CLOSING) {
bf8fe701 1068 debugs(11, 3, "http socket closing");
c4b7a5a9 1069 return;
1070 }
1071
e92e4e44 1072 if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
a171b5f0 1073 // TODO: should we call abortTransaction() here?
62e76326 1074 return;
e92e4e44 1075 }
c4b7a5a9 1076
fdf55365 1077 // handle I/O errors
dc56a9b1 1078 if (io.flag != COMM_OK || len < 0) {
3e4bebf8 1079 debugs(11, 2, HERE << io.conn << ": read failure: " << xstrerror() << ".");
fdf55365 1080
dc56a9b1 1081 if (ignoreErrno(io.xerrno)) {
fdf55365 1082 flags.do_next_read = 1;
1083 } else {
1084 ErrorState *err;
1085 err = errorCon(ERR_READ_ERROR, HTTP_BAD_GATEWAY, fwd->request);
dc56a9b1 1086 err->xerrno = io.xerrno;
fdf55365 1087 fwd->fail(err);
1088 flags.do_next_read = 0;
8d71285d 1089 serverConnection->close();
fdf55365 1090 }
1091
1092 return;
1093 }
1094
7a7cc03f 1095 // update I/O stats
fdf55365 1096 if (len > 0) {
2afaba07 1097 readBuf->appended(len);
5f8252d2 1098 reply_bytes_read += len;
9a0a18de 1099#if USE_DELAY_POOLS
2afaba07 1100 DelayId delayId = entry->mem_obj->mostBytesAllowed();
62e76326 1101 delayId.bytesIn(len);
447e176b 1102#endif
62e76326 1103
1104 kb_incr(&statCounter.server.all.kbytes_in, len);
1105 kb_incr(&statCounter.server.http.kbytes_in, len);
62e76326 1106 IOStats.Http.reads++;
1107
1108 for (clen = len - 1, bin = 0; clen; bin++)
1109 clen >>= 1;
1110
1111 IOStats.Http.read_hist[bin]++;
3ff65596
AR
1112
1113 // update peer response time stats (%<pt)
e24f13cd
CT
1114 const timeval &sent = request->hier.peer_http_request_sent;
1115 request->hier.peer_response_time =
3ff65596 1116 sent.tv_sec ? tvSubMsec(sent, current_time) : -1;
30a4f2a8 1117 }
62e76326 1118
073ba374
AJ
1119 /** \par
1120 * Here the RFC says we should ignore whitespace between replies, but we can't as
5fa061b8 1121 * doing so breaks HTTP/0.9 replies beginning with witespace, and in addition
1122 * the response splitting countermeasures is extremely likely to trigger on this,
1123 * not allowing connection reuse in the first place.
1124 */
1125#if DONT_DO_THIS
8d71285d 1126 if (!flags.headers_parsed && len > 0 && fd_table[serverConnection->fd].uses > 1) {
5fa061b8 1127 /* Skip whitespace between replies */
62e76326 1128
d53b3f6d 1129 while (len > 0 && xisspace(*buf))
41d00cd3 1130 memmove(buf, buf + 1, len--);
62e76326 1131
1132 if (len == 0) {
1133 /* Continue to read... */
21b92762 1134 /* Timeout NOT increased. This whitespace was from previous reply */
f61f0107 1135 flags.do_next_read = 1;
5f8252d2 1136 maybeReadVirginBody();
62e76326 1137 return;
1138 }
5ede6c8f 1139 }
62e76326 1140
5fa061b8 1141#endif
1142
ba82c452 1143 if (len == 0) { // reached EOF?
62e76326 1144 eof = 1;
f61f0107 1145 flags.do_next_read = 0;
da6c8415 1146
b73a07d6 1147 /* Bug 2879: Replies may terminate with \r\n then EOF instead of \r\n\r\n
da6c8415 1148 * Ensure here that we have at minimum two \r\n when EOF is seen.
b73a07d6 1149 * TODO: Add eof parameter to headersEnd() and move this hack there.
da6c8415 1150 */
b73a07d6 1151 if (readBuf->contentSize() && !flags.headers_parsed) {
da6c8415
AJ
1152 /*
1153 * Yes Henrik, there is a point to doing this. When we
1154 * called httpProcessReplyHeader() before, we didn't find
1155 * the end of headers, but now we are definately at EOF, so
1156 * we want to process the reply headers.
1157 */
1158 /* Fake an "end-of-headers" to work around such broken servers */
1159 readBuf->append("\r\n", 2);
da6c8415 1160 }
ba82c452 1161 }
62e76326 1162
655daa06
AR
1163 processReply();
1164}
1165
1166/// processes the already read and buffered response data, possibly after
1167/// waiting for asynchronous 1xx control message processing
1168void
de48b288
A
1169HttpStateData::processReply()
1170{
655daa06
AR
1171
1172 if (flags.handling1xx) { // we came back after handling a 1xx response
1173 debugs(11, 5, HERE << "done with 1xx handling");
1174 flags.handling1xx = false;
1175 Must(!flags.headers_parsed);
1176 }
1177
ba82c452 1178 if (!flags.headers_parsed) { // have not parsed headers yet?
1179 PROF_start(HttpStateData_processReplyHeader);
1180 processReplyHeader();
1181 PROF_stop(HttpStateData_processReplyHeader);
1182
1183 if (!continueAfterParsingHeader()) // parsing error or need more data
1184 return; // TODO: send errors to ICAP
1185
585ab260 1186 adaptOrFinalizeReply();
ba82c452 1187 }
1188
1189 // kick more reads if needed and/or process the response body, if any
1190 PROF_start(HttpStateData_processReplyBody);
1191 processReplyBody(); // may call serverComplete()
1192 PROF_stop(HttpStateData_processReplyBody);
1193}
1194
073ba374
AJ
1195/**
1196 \retval true if we can continue with processing the body or doing ICAP.
1197 */
ba82c452 1198bool
1199HttpStateData::continueAfterParsingHeader()
1200{
655daa06
AR
1201 if (flags.handling1xx) {
1202 debugs(11, 5, HERE << "wait for 1xx handling");
1203 Must(!flags.headers_parsed);
1204 return false;
1205 }
1206
073ba374 1207 if (!flags.headers_parsed && !eof) {
ba82c452 1208 debugs(11, 9, HERE << "needs more at " << readBuf->contentSize());
1209 flags.do_next_read = 1;
073ba374
AJ
1210 /** \retval false If we have not finished parsing the headers and may get more data.
1211 * Schedules more reads to retrieve the missing data.
1212 */
ba82c452 1213 maybeReadVirginBody(); // schedules all kinds of reads; TODO: rename
073ba374 1214 return false;
ba82c452 1215 }
1216
073ba374 1217 /** If we are done with parsing, check for errors */
ba82c452 1218
1219 err_type error = ERR_NONE;
1220
1221 if (flags.headers_parsed) { // parsed headers, possibly with errors
1222 // check for header parsing errors
585ab260 1223 if (HttpReply *vrep = virginReply()) {
1224 const http_status s = vrep->sline.status;
1225 const HttpVersion &v = vrep->sline.version;
ba82c452 1226 if (s == HTTP_INVALID_HEADER && v != HttpVersion(0,9)) {
e24f13cd 1227 debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: Bad header encountered from " << entry->url() << " AKA " << request->GetHost() << request->urlpath.termedBuf() );
ba82c452 1228 error = ERR_INVALID_RESP;
e1381638
AJ
1229 } else if (s == HTTP_HEADER_TOO_LARGE) {
1230 fwd->dontRetry(true);
1231 error = ERR_TOO_BIG;
1232 } else {
1233 return true; // done parsing, got reply, and no error
1234 }
ba82c452 1235 } else {
1236 // parsed headers but got no reply
e24f13cd 1237 debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: No reply at all for " << entry->url() << " AKA " << request->GetHost() << request->urlpath.termedBuf() );
ba82c452 1238 error = ERR_INVALID_RESP;
62e76326 1239 }
090089c4 1240 } else {
ba82c452 1241 assert(eof);
9121eba6
AJ
1242 if (readBuf->hasContent()) {
1243 error = ERR_INVALID_RESP;
e24f13cd 1244 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
1245 } else {
1246 error = ERR_ZERO_SIZE_OBJECT;
e24f13cd
CT
1247 debugs(11, (request->flags.accelerated?DBG_IMPORTANT:2), "WARNING: HTTP: Invalid Response: No object data received for " <<
1248 entry->url() << " AKA " << request->GetHost() << request->urlpath.termedBuf() );
9121eba6 1249 }
2afaba07 1250 }
ba82c452 1251
1252 assert(error != ERR_NONE);
1253 entry->reset();
1254 fwd->fail(errorCon(error, HTTP_BAD_GATEWAY, fwd->request));
1255 flags.do_next_read = 0;
8d71285d 1256 serverConnection->close();
ba82c452 1257 return false; // quit on error
2afaba07 1258}
1259
821beb5e
AR
1260/** truncate what we read if we read too much so that writeReplyBody()
1261 writes no more than what we should have read */
1262void
1263HttpStateData::truncateVirginBody()
1264{
1265 assert(flags.headers_parsed);
1266
1267 HttpReply *vrep = virginReply();
1268 int64_t clen = -1;
1269 if (!vrep->expectingBody(request->method, clen) || clen < 0)
1270 return; // no body or a body of unknown size, including chunked
1271
1272 const int64_t body_bytes_read = reply_bytes_read - header_bytes_read;
e1381638 1273 if (body_bytes_read - body_bytes_truncated <= clen)
821beb5e
AR
1274 return; // we did not read too much or already took care of the extras
1275
1276 if (const int64_t extras = body_bytes_read - body_bytes_truncated - clen) {
1277 // server sent more that the advertised content length
e1381638
AJ
1278 debugs(11,5, HERE << "body_bytes_read=" << body_bytes_read <<
1279 " clen=" << clen << '/' << vrep->content_length <<
1280 " body_bytes_truncated=" << body_bytes_truncated << '+' << extras);
821beb5e
AR
1281
1282 readBuf->truncate(extras);
1283 body_bytes_truncated += extras;
1284 }
1285}
1286
073ba374 1287/**
2afaba07 1288 * Call this when there is data from the origin server
1289 * which should be sent to either StoreEntry, or to ICAP...
1290 */
1291void
5f8252d2 1292HttpStateData::writeReplyBody()
2afaba07 1293{
821beb5e 1294 truncateVirginBody(); // if needed
5f8252d2 1295 const char *data = readBuf->content();
1296 int len = readBuf->contentSize();
bc81cb2b 1297 addVirginReplyBody(data, len);
5f8252d2 1298 readBuf->consume(len);
af0bb8e5 1299}
fc68f6b1 1300
af0bb8e5 1301bool
1302HttpStateData::decodeAndWriteReplyBody()
1303{
1304 const char *data = NULL;
1305 int len;
e053c141 1306 bool wasThereAnException = false;
af0bb8e5 1307 assert(flags.chunked);
1308 assert(httpChunkDecoder);
1309 SQUID_ENTER_THROWING_CODE();
1310 MemBuf decodedData;
1311 decodedData.init();
e053c141 1312 const bool doneParsing = httpChunkDecoder->parse(readBuf,&decodedData);
af0bb8e5 1313 len = decodedData.contentSize();
1314 data=decodedData.content();
1315 addVirginReplyBody(data, len);
e053c141 1316 if (doneParsing) {
839291ac
AJ
1317 lastChunk = 1;
1318 flags.do_next_read = 0;
af0bb8e5 1319 }
e053c141
FC
1320 SQUID_EXIT_THROWING_CODE(wasThereAnException);
1321 return wasThereAnException;
e6ccf245 1322}
1323
073ba374 1324/**
2afaba07 1325 * processReplyBody has two purposes:
1326 * 1 - take the reply body data, if any, and put it into either
1327 * the StoreEntry, or give it over to ICAP.
1328 * 2 - see if we made it to the end of the response (persistent
1329 * connections and such)
1330 */
e6ccf245 1331void
2afaba07 1332HttpStateData::processReplyBody()
e6ccf245 1333{
b7ac5457 1334 Ip::Address client_addr;
d67acb4e 1335 bool ispinned = false;
fc68f6b1 1336
1a98175f 1337 if (!flags.headers_parsed) {
f61f0107 1338 flags.do_next_read = 1;
5f8252d2 1339 maybeReadVirginBody();
62e76326 1340 return;
528b2c61 1341 }
62e76326 1342
a83c6ed6 1343#if USE_ADAPTATION
c30ac6ea 1344 debugs(11,5, HERE << "adaptationAccessCheckPending=" << adaptationAccessCheckPending);
a83c6ed6 1345 if (adaptationAccessCheckPending)
2afaba07 1346 return;
fc68f6b1 1347
2afaba07 1348#endif
62e76326 1349
2afaba07 1350 /*
1351 * At this point the reply headers have been parsed and consumed.
1352 * That means header content has been removed from readBuf and
1353 * it contains only body data.
1354 */
9e008dda
AJ
1355 if (flags.chunked) {
1356 if (!decodeAndWriteReplyBody()) {
1357 flags.do_next_read = 0;
1358 serverComplete();
1359 return;
1360 }
1361 } else
1362 writeReplyBody();
528b2c61 1363
e6ccf245 1364 if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
62e76326 1365 /*
073ba374 1366 * The above writeReplyBody() call could ABORT this entry,
62e76326 1367 * in that case, the server FD should already be closed.
1368 * there's nothing for us to do.
1369 */
1370 (void) 0;
1371 } else
1372 switch (persistentConnStatus()) {
dc49061a 1373 case INCOMPLETE_MSG: {
3e4bebf8 1374 debugs(11, 5, "processReplyBody: INCOMPLETE_MSG from " << serverConnection);
21b92762 1375 /* Wait for more data or EOF condition */
8d77a37c 1376 AsyncCall::Pointer nil;
21b92762 1377 if (flags.keepalive_broken) {
8d77a37c 1378 commSetConnTimeout(serverConnection, 10, nil);
21b92762 1379 } else {
8d77a37c 1380 commSetConnTimeout(serverConnection, Config.Timeout.read, nil);
21b92762 1381 }
1382
f61f0107 1383 flags.do_next_read = 1;
dc49061a
A
1384 }
1385 break;
62e76326 1386
1387 case COMPLETE_PERSISTENT_MSG:
3e4bebf8 1388 debugs(11, 5, "processReplyBody: COMPLETE_PERSISTENT_MSG from " << serverConnection);
62e76326 1389 /* yes we have to clear all these! */
8d77a37c 1390 commUnsetConnTimeout(serverConnection);
f61f0107 1391 flags.do_next_read = 0;
62e76326 1392
8d71285d 1393 comm_remove_close_handler(serverConnection->fd, closeHandler);
dc56a9b1 1394 closeHandler = NULL;
8d71285d 1395 fwd->unregister(serverConnection);
fc68f6b1 1396
e24f13cd
CT
1397 if (request->flags.spoof_client_ip)
1398 client_addr = request->client_addr;
fc68f6b1 1399
d67acb4e 1400
9e008dda
AJ
1401 if (request->flags.pinned) {
1402 ispinned = true;
1403 } else if (request->flags.connection_auth && request->flags.auth_sent) {
1404 ispinned = true;
1405 }
1406
e24f13cd
CT
1407 if (request->pinnedConnection() && ispinned) {
1408 request->pinnedConnection()->pinConnection(serverConnection, request, _peer,
9e008dda 1409 (request->flags.connection_auth != 0));
bd0723ad 1410 } else {
e24f13cd 1411 fwd->pconnPush(serverConnection, request->peer_host ? request->peer_host : request->GetHost());
bd0723ad 1412 }
1413
8d71285d 1414 serverConnection = NULL;
5f8252d2 1415 serverComplete();
62e76326 1416 return;
1417
1418 case COMPLETE_NONPERSISTENT_MSG:
3e4bebf8 1419 debugs(11, 5, "processReplyBody: COMPLETE_NONPERSISTENT_MSG from " << serverConnection);
5f8252d2 1420 serverComplete();
62e76326 1421 return;
1422 }
1423
5f8252d2 1424 maybeReadVirginBody();
c4b7a5a9 1425}
1426
1427void
5f8252d2 1428HttpStateData::maybeReadVirginBody()
c4b7a5a9 1429{
52edecde 1430 // we may need to grow the buffer if headers do not fit
1c9605c5 1431 const int minRead = flags.headers_parsed ? 0 :1024;
d5f8d05f 1432 const int read_size = replyBodySpace(*readBuf, minRead);
2afaba07 1433
5f8252d2 1434 debugs(11,9, HERE << (flags.do_next_read ? "may" : "wont") <<
9cf7de1b 1435 " read up to " << read_size << " bytes from " << serverConnection);
2afaba07 1436
1437 /*
1438 * why <2? Because delayAwareRead() won't actually read if
1439 * you ask it to read 1 byte. The delayed read request
1440 * just gets re-queued until the client side drains, then
1441 * the I/O thread hangs. Better to not register any read
1442 * handler until we get a notification from someone that
1443 * its okay to read again.
1444 */
d5f8d05f 1445 if (read_size < 2)
52edecde 1446 return;
2afaba07 1447
f61f0107 1448 if (flags.do_next_read) {
dc56a9b1 1449 flags.do_next_read = 0;
1450 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
3e4bebf8 1451 entry->delayAwareRead(serverConnection, readBuf->space(read_size), read_size,
4cb2536f 1452 JobCallback(11, 5, Dialer, this, HttpStateData::readReply));
528b2c61 1453 }
090089c4 1454}
1455
39cb8c41 1456/// called after writing the very last request byte (body, last-chunk, etc)
d576a6a6 1457void
39cb8c41 1458HttpStateData::wroteLast(const CommIoCbParams &io)
090089c4 1459{
9cf7de1b 1460 debugs(11, 5, HERE << serverConnection << ": size " << io.size << ": errflag " << io.flag << ".");
bc87dc25 1461#if URL_CHECKSUM_DEBUG
62e76326 1462
528b2c61 1463 entry->mem_obj->checkUrlChecksum();
bc87dc25 1464#endif
62e76326 1465
dc56a9b1 1466 if (io.size > 0) {
49ae8b95 1467 fd_bytes(io.fd, io.size, FD_WRITE);
dc56a9b1 1468 kb_incr(&statCounter.server.all.kbytes_out, io.size);
1469 kb_incr(&statCounter.server.http.kbytes_out, io.size);
ee1679df 1470 }
62e76326 1471
dc56a9b1 1472 if (io.flag == COMM_ERR_CLOSING)
62e76326 1473 return;
1474
dc56a9b1 1475 if (io.flag) {
6cae5db1 1476 ErrorState *err;
dc56a9b1 1477 err = errorCon(ERR_WRITE_ERROR, HTTP_BAD_GATEWAY, fwd->request);
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)
1755 cc = httpHdrCcCreate();
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
AJ
1763 /* Add max-age only without no-cache */
1764 if (!EBIT_TEST(cc->mask, CC_MAX_AGE) && !EBIT_TEST(cc->mask, CC_NO_CACHE)) {
43ae1d95 1765 const char *url =
e24f13cd 1766 entry ? entry->url() : urlCanonical(request);
62e76326 1767 httpHdrCcSetMaxAge(cc, getMaxAge(url));
1768
62e76326 1769 }
1770
ce2d6441 1771 /* Enforce sibling relations */
62e76326 1772 if (flags.only_if_cached)
1773 EBIT_SET(cc->mask, CC_ONLY_IF_CACHED);
1774
a9925b40 1775 hdr_out->putCc(cc);
62e76326 1776
1777 httpHdrCcDestroy(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();
2fe7eff9 2013 mb->Printf("%s %s HTTP/%d.%d\r\n",
e24f13cd
CT
2014 RequestMethodStr(request->method),
2015 url && *url ? url : "/",
2fe7eff9 2016 httpver.major,httpver.minor);
99edd1c3 2017 /* build and pack headers */
2018 {
75faaa7a 2019 HttpHeader hdr(hoRequest);
62e76326 2020 Packer p;
e24f13cd 2021 httpBuildRequestHeader(request, entry, &hdr, flags);
9e008dda 2022
e24f13cd
CT
2023 if (request->flags.pinned && request->flags.connection_auth)
2024 request->flags.auth_sent = 1;
d67acb4e 2025 else if (hdr.has(HDR_AUTHORIZATION))
e24f13cd 2026 request->flags.auth_sent = 1;
d67acb4e 2027
62e76326 2028 packerToMemInit(&p, mb);
a9925b40 2029 hdr.packInto(&p);
519e0948 2030 hdr.clean();
62e76326 2031 packerClean(&p);
9d9d144b 2032 }
99edd1c3 2033 /* append header terminator */
2fe7eff9 2034 mb->append(crlf, 2);
99edd1c3 2035 return mb->size - offset;
6bf8443a 2036}
62e76326 2037
090089c4 2038/* This will be called when connect completes. Write request. */
5f8252d2 2039bool
2bb867b5 2040HttpStateData::sendRequest()
090089c4 2041{
99edd1c3 2042 MemBuf mb;
090089c4 2043
9cf7de1b 2044 debugs(11, 5, HERE << serverConnection << ", request " << request << ", this " << this << ".");
a0297974 2045
6b679a01 2046 if (!Comm::IsConnOpen(serverConnection)) {
9cf7de1b 2047 debugs(11,3, HERE << "cannot send request to closing " << serverConnection);
a0297974
AR
2048 assert(closeHandler != NULL);
2049 return false;
2050 }
2051
dc56a9b1 2052 typedef CommCbMemFunT<HttpStateData, CommTimeoutCbParams> TimeoutDialer;
4299f876 2053 AsyncCall::Pointer timeoutCall = JobCallback(11, 5,
4cb2536f 2054 TimeoutDialer, this, HttpStateData::httpTimeout);
8d77a37c 2055 commSetConnTimeout(serverConnection, Config.Timeout.lifetime, timeoutCall);
2bb867b5 2056 flags.do_next_read = 1;
5f8252d2 2057 maybeReadVirginBody();
2058
e24f13cd 2059 if (request->body_pipe != NULL) {
123ec4de 2060 if (!startRequestBodyFlow()) // register to receive body data
5f8252d2 2061 return false;
9e008dda 2062 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
4299f876 2063 requestSender = JobCallback(11,5,
4cb2536f 2064 Dialer, this, HttpStateData::sentRequestBody);
e31a1e67
AR
2065
2066 Must(!flags.chunked_request);
f228d6f6 2067 // use chunked encoding if we do not know the length
e24f13cd 2068 if (request->content_length < 0)
e31a1e67 2069 flags.chunked_request = 1;
5f8252d2 2070 } else {
2071 assert(!requestBodySource);
9e008dda 2072 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
4299f876 2073 requestSender = JobCallback(11,5,
39cb8c41 2074 Dialer, this, HttpStateData::wroteLast);
5f8252d2 2075 }
54220df8 2076
2bb867b5 2077 if (_peer != NULL) {
2078 if (_peer->options.originserver) {
2079 flags.proxying = 0;
2080 flags.originpeer = 1;
62e76326 2081 } else {
2bb867b5 2082 flags.proxying = 1;
2083 flags.originpeer = 0;
62e76326 2084 }
be753325 2085 } else {
2bb867b5 2086 flags.proxying = 0;
2087 flags.originpeer = 0;
be753325 2088 }
62e76326 2089
efb9218c 2090 /*
99edd1c3 2091 * Is keep-alive okay for all request methods?
efb9218c 2092 */
e24f13cd 2093 if (request->flags.must_keepalive)
9e008dda 2094 flags.keepalive = 1;
d67acb4e 2095 else if (!Config.onoff.server_pconns)
2bb867b5 2096 flags.keepalive = 0;
2097 else if (_peer == NULL)
2098 flags.keepalive = 1;
2099 else if (_peer->stats.n_keepalives_sent < 10)
2100 flags.keepalive = 1;
2101 else if ((double) _peer->stats.n_keepalives_recv /
2102 (double) _peer->stats.n_keepalives_sent > 0.50)
2103 flags.keepalive = 1;
2104
2105 if (_peer) {
2ecba5b6 2106 /*The old code here was
e24f13cd
CT
2107 if (neighborType(_peer, request) == PEER_SIBLING && ...
2108 which is equivalent to:
2109 if (neighborType(_peer, NULL) == PEER_SIBLING && ...
2110 or better:
2111 if (((_peer->type == PEER_MULTICAST && p->options.mcast_siblings) ||
2112 _peer->type == PEER_SIBLINGS ) && _peer->options.allow_miss)
2113 flags.only_if_cached = 1;
2114
2115 But I suppose it was a bug
2116 */
2bb867b5 2117 if (neighborType(_peer, request) == PEER_SIBLING &&
2118 !_peer->options.allow_miss)
2119 flags.only_if_cached = 1;
2120
2121 flags.front_end_https = _peer->front_end_https;
a7ad6e4e 2122 }
62e76326 2123
2fe7eff9 2124 mb.init();
9ca29d23 2125 request->peer_host=_peer?_peer->host:NULL;
e24f13cd 2126 buildRequestPrefix(&mb);
9cf7de1b 2127 debugs(11, 6, HERE << serverConnection << ":\n" << mb.buf);
b0388924 2128 Comm::Write(serverConnection, &mb, requestSender);
5f8252d2 2129
2130 return true;
090089c4 2131}
b6a2f15e 2132
39cb8c41
AR
2133bool
2134HttpStateData::getMoreRequestBody(MemBuf &buf)
2135{
2136 // parent's implementation can handle the no-encoding case
e31a1e67 2137 if (!flags.chunked_request)
39cb8c41
AR
2138 return ServerStateData::getMoreRequestBody(buf);
2139
2140 MemBuf raw;
2141
2142 Must(requestBodySource != NULL);
2143 if (!requestBodySource->getMoreData(raw))
2144 return false; // no request body bytes to chunk yet
2145
2146 // optimization: pre-allocate buffer size that should be enough
2147 const mb_size_t rawDataSize = raw.contentSize();
2148 // we may need to send: hex-chunk-size CRLF raw-data CRLF last-chunk
2149 buf.init(16 + 2 + rawDataSize + 2 + 5, raw.max_capacity);
2150
d958d14f 2151 buf.Printf("%x\r\n", static_cast<unsigned int>(rawDataSize));
39cb8c41
AR
2152 buf.append(raw.content(), rawDataSize);
2153 buf.Printf("\r\n");
2154
2155 Must(rawDataSize > 0); // we did not accidently created last-chunk above
2156
2157 // Do not send last-chunk unless we successfully received everything
2158 if (receivedWholeRequestBody) {
2159 Must(!flags.sentLastChunk);
2160 flags.sentLastChunk = true;
de48b288 2161 buf.append("0\r\n\r\n", 5);
39cb8c41
AR
2162 }
2163
2164 return true;
2165}
2166
910169e5 2167void
b6b6f466 2168httpStart(FwdState *fwd)
603a02fd 2169{
60745f24 2170 debugs(11, 3, "httpStart: \"" << RequestMethodStr(fwd->request->method) << " " << fwd->entry->url() << "\"" );
a3d50c30 2171 HttpStateData *httpState = new HttpStateData(fwd);
62e76326 2172
5f8252d2 2173 if (!httpState->sendRequest()) {
bf8fe701 2174 debugs(11, 3, "httpStart: aborted");
5f8252d2 2175 delete httpState;
2176 return;
2177 }
62e76326 2178
5f8252d2 2179 statCounter.server.all.requests++;
83704487 2180 statCounter.server.http.requests++;
62e76326 2181
b6a2f15e 2182 /*
2183 * We used to set the read timeout here, but not any more.
2184 * Now its set in httpSendComplete() after the full request,
2185 * including request body, has been written to the server.
2186 */
090089c4 2187}
2188
39cb8c41
AR
2189/// if broken posts are enabled for the request, try to fix and return true
2190bool
2191HttpStateData::finishingBrokenPost()
2bb867b5 2192{
626096be 2193#if USE_HTTP_VIOLATIONS
39cb8c41
AR
2194 if (!Config.accessList.brokenPosts) {
2195 debugs(11, 5, HERE << "No brokenPosts list");
2196 return false;
2197 }
a0297974 2198
e11513e1 2199 ACLFilledChecklist ch(Config.accessList.brokenPosts, originalRequest(), NULL);
39cb8c41
AR
2200 if (!ch.fastCheck()) {
2201 debugs(11, 5, HERE << "didn't match brokenPosts");
2202 return false;
2203 }
a0297974 2204
9cf7de1b
AJ
2205 if (!Comm::IsConnOpen(serverConnection)) {
2206 debugs(11,2, HERE << "ignoring broken POST for closed " << serverConnection);
39cb8c41
AR
2207 assert(closeHandler != NULL);
2208 return true; // prevent caller from proceeding as if nothing happened
54220df8 2209 }
39cb8c41
AR
2210
2211 debugs(11, 2, "finishingBrokenPost: fixing broken POST");
2212 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
2213 requestSender = JobCallback(11,5,
2214 Dialer, this, HttpStateData::wroteLast);
b0388924 2215 Comm::Write(serverConnection, "\r\n", 2, requestSender, NULL);
39cb8c41
AR
2216 return true;
2217#else
2218 return false;
626096be 2219#endif /* USE_HTTP_VIOLATIONS */
39cb8c41
AR
2220}
2221
2222/// if needed, write last-chunk to end the request body and return true
2223bool
2224HttpStateData::finishingChunkedRequest()
2225{
2226 if (flags.sentLastChunk) {
2227 debugs(11, 5, HERE << "already sent last-chunk");
2228 return false;
2229 }
2230
2231 Must(receivedWholeRequestBody); // or we should not be sending last-chunk
2232 flags.sentLastChunk = true;
2233
2234 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
e0d28505 2235 requestSender = JobCallback(11,5, Dialer, this, HttpStateData::wroteLast);
b0388924 2236 Comm::Write(serverConnection, "0\r\n\r\n", 5, requestSender, NULL);
39cb8c41
AR
2237 return true;
2238}
2239
2240void
2241HttpStateData::doneSendingRequestBody()
2242{
2243 ServerStateData::doneSendingRequestBody();
9cf7de1b 2244 debugs(11,5, HERE << serverConnection);
39cb8c41
AR
2245
2246 // do we need to write something after the last body byte?
e31a1e67 2247 if (flags.chunked_request && finishingChunkedRequest())
39cb8c41 2248 return;
e31a1e67 2249 if (!flags.chunked_request && finishingBrokenPost())
39cb8c41 2250 return;
aa49962c 2251
39cb8c41 2252 sendComplete();
94439e4e 2253}
2254
5f8252d2 2255// more origin request body data is available
2bb867b5 2256void
5f8252d2 2257HttpStateData::handleMoreRequestBodyAvailable()
2bb867b5 2258{
6b679a01 2259 if (eof || !Comm::IsConnOpen(serverConnection)) {
5f8252d2 2260 // XXX: we should check this condition in other callbacks then!
2261 // TODO: Check whether this can actually happen: We should unsubscribe
2262 // as a body consumer when the above condition(s) are detected.
2bb867b5 2263 debugs(11, 1, HERE << "Transaction aborted while reading HTTP body");
2bb867b5 2264 return;
2265 }
62e76326 2266
5f8252d2 2267 assert(requestBodySource != NULL);
fc68f6b1 2268
5f8252d2 2269 if (requestBodySource->buf().hasContent()) {
2270 // XXX: why does not this trigger a debug message on every request?
fc68f6b1 2271
2bb867b5 2272 if (flags.headers_parsed && !flags.abuse_detected) {
2273 flags.abuse_detected = 1;
e24f13cd 2274 debugs(11, 1, "http handleMoreRequestBodyAvailable: Likely proxy abuse detected '" << request->client_addr << "' -> '" << entry->url() << "'" );
21b92762 2275
585ab260 2276 if (virginReply()->sline.status == HTTP_INVALID_HEADER) {
8d71285d 2277 serverConnection->close();
21b92762 2278 return;
2279 }
2280 }
b6a2f15e 2281 }
5f8252d2 2282
2283 HttpStateData::handleMoreRequestBodyAvailable();
376bb137 2284}
2285
5f8252d2 2286// premature end of the request body
2bb867b5 2287void
5f8252d2 2288HttpStateData::handleRequestBodyProducerAborted()
376bb137 2289{
5f8252d2 2290 ServerStateData::handleRequestBodyProducerAborted();
64b66b76 2291 if (entry->isEmpty()) {
25b481e6 2292 debugs(11, 3, "request body aborted: " << serverConnection);
64b66b76 2293 ErrorState *err;
8b997339
AR
2294 // We usually get here when ICAP REQMOD aborts during body processing.
2295 // We might also get here if client-side aborts, but then our response
2296 // should not matter because either client-side will provide its own or
2297 // there will be no response at all (e.g., if the the client has left).
2298 err = errorCon(ERR_ICAP_FAILURE, HTTP_INTERNAL_SERVER_ERROR, fwd->request);
2299 err->xerrno = ERR_DETAIL_SRV_REQMOD_REQ_BODY;
64b66b76
CT
2300 fwd->fail(err);
2301 }
2302
39cb8c41 2303 abortTransaction("request body producer aborted");
2bb867b5 2304}
2305
5f8252d2 2306// called when we wrote request headers(!) or a part of the body
2bb867b5 2307void
dc56a9b1 2308HttpStateData::sentRequestBody(const CommIoCbParams &io)
2bb867b5 2309{
dc56a9b1 2310 if (io.size > 0)
2311 kb_incr(&statCounter.server.http.kbytes_out, io.size);
fc68f6b1 2312
dc56a9b1 2313 ServerStateData::sentRequestBody(io);
5f8252d2 2314}
3b299123 2315
5f8252d2 2316// Quickly abort the transaction
2317// TODO: destruction should be sufficient as the destructor should cleanup,
2318// including canceling close handlers
2319void
2320HttpStateData::abortTransaction(const char *reason)
2321{
2322 debugs(11,5, HERE << "aborting transaction for " << reason <<
9cf7de1b 2323 "; " << serverConnection << ", this " << this);
fc68f6b1 2324
be364179 2325 if (Comm::IsConnOpen(serverConnection)) {
8d71285d 2326 serverConnection->close();
3e8c047e 2327 return;
c23f0c74 2328 }
3e8c047e 2329
2330 fwd->handleUnregisteredServerEnd();
dc56a9b1 2331 deleteThis("HttpStateData::abortTransaction");
54220df8 2332}