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