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