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