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