]> git.ipfire.org Git - thirdparty/squid.git/blame - src/http.cc
Author: Finn Thain <fthain@telegraphics.com.au>
[thirdparty/squid.git] / src / http.cc
CommitLineData
da2b3a17 1
30a4f2a8 2/*
dc56a9b1 3 * $Id: http.cc,v 1.547 2008/02/12 23:55:26 rousskov Exp $
30a4f2a8 4 *
5 * DEBUG: section 11 Hypertext Transfer Protocol (HTTP)
6 * AUTHOR: Harvest Derived
7 *
2b6662ba 8 * SQUID Web Proxy Cache http://www.squid-cache.org/
e25c139f 9 * ----------------------------------------------------------
30a4f2a8 10 *
2b6662ba 11 * Squid is the result of efforts by numerous individuals from
12 * the Internet community; see the CONTRIBUTORS file for full
13 * details. Many organizations have provided support for Squid's
14 * development; see the SPONSORS file for full details. Squid is
15 * Copyrighted (C) 2001 by the Regents of the University of
16 * California; see the COPYRIGHT file for full details. Squid
17 * incorporates software developed and/or copyrighted by other
18 * sources; see the CREDITS file for full details.
30a4f2a8 19 *
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 2 of the License, or
23 * (at your option) any later version.
24 *
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
29 *
30 * You should have received a copy of the GNU General Public License
31 * along with this program; if not, write to the Free Software
cbdec147 32 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
e25c139f 33 *
30a4f2a8 34 */
019dd986 35
4a83b852 36/*
37 * Anonymizing patch by lutz@as-node.jena.thur.de
de3bdb4c 38 * have a look into http-anon.c to get more informations.
4a83b852 39 */
40
44a47c6e 41#include "squid.h"
aa839030 42#include "errorpage.h"
0eb49b6d 43#include "MemBuf.h"
e6ccf245 44#include "http.h"
f5691f9c 45#include "AuthUserRequest.h"
e6ccf245 46#include "Store.h"
528b2c61 47#include "HttpReply.h"
48#include "HttpRequest.h"
49#include "MemObject.h"
50#include "HttpHdrContRange.h"
b19dd748 51#include "HttpHdrSc.h"
52#include "HttpHdrScTarget.h"
4fb35c3c 53#include "ACLChecklist.h"
21b92762 54#include "fde.h"
b67e2c8c 55#if DELAY_POOLS
56#include "DelayPools.h"
57#endif
985c86bc 58#include "SquidTime.h"
af0bb8e5 59#include "TextException.h"
60
61#define SQUID_ENTER_THROWING_CODE() try {
62#define SQUID_EXIT_THROWING_CODE(status) \
63 status = true; \
64 } \
65 catch (const TextException &e) { \
66 debugs (11, 1, "Exception error:" << e.message); \
67 status = false; \
68 }
e6ccf245 69
2afaba07 70CBDATA_CLASS_INIT(HttpStateData);
090089c4 71
6bf8443a 72static const char *const crlf = "\r\n";
4db43fab 73
f9cece6e 74static void httpMaybeRemovePublic(StoreEntry *, http_status);
30abd221 75static void copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, String strConnection, HttpRequest * request, HttpRequest * orig_request,
62e76326 76 HttpHeader * hdr_out, int we_do_ranges, http_state_flags);
528b2c61 77
dc56a9b1 78HttpStateData::HttpStateData(FwdState *theFwdState) : AsyncJob("HttpStateData"), ServerStateData(theFwdState),
79 header_bytes_read(0), reply_bytes_read(0), httpChunkDecoder(NULL)
2bb867b5 80{
81 debugs(11,5,HERE << "HttpStateData " << this << " created");
a3d50c30 82 ignoreCacheControl = false;
83 surrogateNoStore = false;
a3d50c30 84 fd = fwd->server_fd;
85 readBuf = new MemBuf;
86 readBuf->init(4096, SQUID_TCP_SO_RCVBUF);
6dd9f4bd 87 orig_request = HTTPMSGLOCK(fwd->request);
a3d50c30 88
89 if (fwd->servers)
90 _peer = fwd->servers->_peer; /* might be NULL */
91
92 if (_peer) {
93 const char *url;
94
95 if (_peer->options.originserver)
30abd221 96 url = orig_request->urlpath.buf();
a3d50c30 97 else
3900307b 98 url = entry->url();
a3d50c30 99
5cafad19 100 HttpRequest * proxy_req = new HttpRequest(orig_request->method,
101 orig_request->protocol, url);
a3d50c30 102
cc192b50 103 proxy_req->SetHost(_peer->host);
a3d50c30 104
105 proxy_req->port = _peer->http_port;
106
107 proxy_req->flags = orig_request->flags;
108
109 proxy_req->lastmod = orig_request->lastmod;
110
111 proxy_req->flags.proxying = 1;
112
6dd9f4bd 113 HTTPMSGUNLOCK(request);
253caccb 114
6dd9f4bd 115 request = HTTPMSGLOCK(proxy_req);
a3d50c30 116
117 /*
118 * This NEIGHBOR_PROXY_ONLY check probably shouldn't be here.
119 * We might end up getting the object from somewhere else if,
120 * for example, the request to this neighbor fails.
121 */
122 if (_peer->options.proxy_only)
d88e3c49 123 entry->releaseRequest();
a3d50c30 124
125#if DELAY_POOLS
126
127 entry->setNoDelay(_peer->options.no_delay);
128
129#endif
a3d50c30 130 }
131
132 /*
133 * register the handler to free HTTP state data when the FD closes
134 */
dc56a9b1 135 typedef CommCbMemFunT<HttpStateData, CommCloseCbParams> Dialer;
136 closeHandler = asyncCall(9, 5, "httpStateData::httpStateConnClosed",
137 Dialer(this,&HttpStateData::httpStateConnClosed));
138 comm_add_close_handler(fd, closeHandler);
2bb867b5 139}
b8d8561b 140
2afaba07 141HttpStateData::~HttpStateData()
f5558c95 142{
253caccb 143 /*
3b299123 144 * don't forget that ~ServerStateData() gets called automatically
253caccb 145 */
146
2afaba07 147 if (!readBuf->isNull())
148 readBuf->clean();
62e76326 149
2afaba07 150 delete readBuf;
151
af0bb8e5 152 if(httpChunkDecoder)
153 delete httpChunkDecoder;
154
6dd9f4bd 155 HTTPMSGUNLOCK(orig_request);
2afaba07 156
5f8252d2 157 debugs(11,5, HERE << "HttpStateData " << this << " destroyed; FD " << fd);
158}
159
160int
fc68f6b1 161HttpStateData::dataDescriptor() const
162{
5f8252d2 163 return fd;
2afaba07 164}
dc56a9b1 165/*
2afaba07 166static void
167httpStateFree(int fd, void *data)
168{
169 HttpStateData *httpState = static_cast<HttpStateData *>(data);
bf8fe701 170 debugs(11, 5, "httpStateFree: FD " << fd << ", httpState=" << data);
5f8252d2 171 delete httpState;
dc56a9b1 172}*/
173
174void
175HttpStateData::httpStateConnClosed(const CommCloseCbParams &params)
176{
177 debugs(11, 5, "httpStateFree: FD " << params.fd << ", httpState=" << params.data);
178 deleteThis("HttpStateData::httpStateConnClosed");
f5558c95 179}
180
b8d8561b 181int
60745f24 182httpCachable(const HttpRequestMethod& method)
090089c4 183{
090089c4 184 /* GET and HEAD are cachable. Others are not. */
62e76326 185
60745f24 186 // TODO: replase to HttpRequestMethod::isCachable() ?
6eb42cae 187 if (method != METHOD_GET && method != METHOD_HEAD)
62e76326 188 return 0;
189
090089c4 190 /* else cachable */
191 return 1;
192}
193
dc56a9b1 194void
195HttpStateData::httpTimeout(const CommTimeoutCbParams &params)
090089c4 196{
bf8fe701 197 debugs(11, 4, "httpTimeout: FD " << fd << ": '" << entry->url() << "'" );
62e76326 198
12158bdc 199 if (entry->store_status == STORE_PENDING) {
dc56a9b1 200 fwd->fail(errorCon(ERR_READ_TIMEOUT, HTTP_GATEWAY_TIMEOUT, fwd->request));
9b312a19 201 }
62e76326 202
0d4d4170 203 comm_close(fd);
090089c4 204}
205
f9cece6e 206static void
207httpMaybeRemovePublic(StoreEntry * e, http_status status)
208{
914b89a2 209 int remove = 0;
7e3ce7b9 210 int forbidden = 0;
f9cece6e 211 StoreEntry *pe;
62e76326 212
d46a87a8 213 if (!EBIT_TEST(e->flags, KEY_PRIVATE))
62e76326 214 return;
215
f9cece6e 216 switch (status) {
62e76326 217
f9cece6e 218 case HTTP_OK:
62e76326 219
f9cece6e 220 case HTTP_NON_AUTHORITATIVE_INFORMATION:
62e76326 221
f9cece6e 222 case HTTP_MULTIPLE_CHOICES:
62e76326 223
f9cece6e 224 case HTTP_MOVED_PERMANENTLY:
62e76326 225
f9cece6e 226 case HTTP_MOVED_TEMPORARILY:
62e76326 227
f9cece6e 228 case HTTP_GONE:
62e76326 229
7e3ce7b9 230 case HTTP_NOT_FOUND:
914b89a2 231 remove = 1;
62e76326 232
233 break;
234
7e3ce7b9 235 case HTTP_FORBIDDEN:
62e76326 236
7e3ce7b9 237 case HTTP_METHOD_NOT_ALLOWED:
62e76326 238 forbidden = 1;
239
240 break;
241
f9cece6e 242#if WORK_IN_PROGRESS
62e76326 243
c8fd0193 244 case HTTP_UNAUTHORIZED:
62e76326 245 forbidden = 1;
246
247 break;
248
f9cece6e 249#endif
62e76326 250
f9cece6e 251 default:
7e3ce7b9 252#if QUESTIONABLE
62e76326 253 /*
254 * Any 2xx response should eject previously cached entities...
255 */
abb929f0 256
62e76326 257 if (status >= 200 && status < 300)
914b89a2 258 remove = 1;
62e76326 259
7e3ce7b9 260#endif
62e76326 261
262 break;
f9cece6e 263 }
62e76326 264
914b89a2 265 if (!remove && !forbidden)
62e76326 266 return;
267
f9cece6e 268 assert(e->mem_obj);
62e76326 269
f66a9ef4 270 if (e->mem_obj->request)
62e76326 271 pe = storeGetPublicByRequest(e->mem_obj->request);
f66a9ef4 272 else
62e76326 273 pe = storeGetPublic(e->mem_obj->url, e->mem_obj->method);
274
f66a9ef4 275 if (pe != NULL) {
62e76326 276 assert(e != pe);
5f33b71d 277 pe->release();
0856d155 278 }
62e76326 279
914b89a2 280 /** \par
7e3ce7b9 281 * Also remove any cached HEAD response in case the object has
282 * changed.
283 */
f66a9ef4 284 if (e->mem_obj->request)
62e76326 285 pe = storeGetPublicByRequestMethod(e->mem_obj->request, METHOD_HEAD);
f66a9ef4 286 else
62e76326 287 pe = storeGetPublic(e->mem_obj->url, METHOD_HEAD);
288
f66a9ef4 289 if (pe != NULL) {
62e76326 290 assert(e != pe);
5f33b71d 291 pe->release();
7e3ce7b9 292 }
62e76326 293
7e3ce7b9 294 if (forbidden)
62e76326 295 return;
296
914b89a2 297 /// \todo AYJ: given the coment below + new behaviour of accepting METHOD_UNKNOWN, should we invert this test
298 /// removing the object unless the method is nown to be safely kept?
299 switch (e->mem_obj->method.id()) {
62e76326 300
7e3ce7b9 301 case METHOD_PUT:
62e76326 302
7e3ce7b9 303 case METHOD_DELETE:
62e76326 304
7e3ce7b9 305 case METHOD_PROPPATCH:
62e76326 306
7e3ce7b9 307 case METHOD_MKCOL:
62e76326 308
7e3ce7b9 309 case METHOD_MOVE:
62e76326 310
42b51993 311 case METHOD_BMOVE:
62e76326 312
42b51993 313 case METHOD_BDELETE:
914b89a2 314 /** \par
315 * Remove any cached GET object if it is believed that the
62e76326 316 * object may have changed as a result of other methods
317 */
318
319 if (e->mem_obj->request)
320 pe = storeGetPublicByRequestMethod(e->mem_obj->request, METHOD_GET);
321 else
322 pe = storeGetPublic(e->mem_obj->url, METHOD_GET);
323
324 if (pe != NULL) {
325 assert(e != pe);
5f33b71d 326 pe->release();
62e76326 327 }
328
329 break;
330
c8be6d7b 331 default:
62e76326 332 /* Keep GCC happy. The methods above are all mutating HTTP methods
333 */
334 break;
0856d155 335 }
f9cece6e 336}
337
43ae1d95 338void
339HttpStateData::processSurrogateControl(HttpReply *reply)
340{
f41735ea 341#if USE_SQUID_ESI
43ae1d95 342
343 if (request->flags.accelerated && reply->surrogate_control) {
344 HttpHdrScTarget *sctusable =
345 httpHdrScGetMergedTarget(reply->surrogate_control,
346 Config.Accel.surrogate_id);
347
348 if (sctusable) {
349 if (EBIT_TEST(sctusable->mask, SC_NO_STORE) ||
350 (Config.onoff.surrogate_is_remote
351 && EBIT_TEST(sctusable->mask, SC_NO_STORE_REMOTE))) {
352 surrogateNoStore = true;
5ed72359 353 entry->makePrivate();
43ae1d95 354 }
355
356 /* The HttpHeader logic cannot tell if the header it's parsing is a reply to an
357 * accelerated request or not...
358 * Still, this is an abtraction breach. - RC
359 */
360 if (sctusable->max_age != -1) {
361 if (sctusable->max_age < sctusable->max_stale)
362 reply->expires = reply->date + sctusable->max_age;
363 else
364 reply->expires = reply->date + sctusable->max_stale;
365
366 /* And update the timestamps */
3900307b 367 entry->timestampsSet();
43ae1d95 368 }
369
370 /* We ignore cache-control directives as per the Surrogate specification */
371 ignoreCacheControl = true;
372
373 httpHdrScTargetDestroy(sctusable);
374 }
375 }
376
377#endif
378}
379
924f73bc 380int
381HttpStateData::cacheableReply()
c54e9052 382{
585ab260 383 HttpReply const *rep = finalReply();
528b2c61 384 HttpHeader const *hdr = &rep->header;
d8b249ef 385 const int cc_mask = (rep->cache_control) ? rep->cache_control->mask : 0;
c68e9c6b 386 const char *v;
38f9c547 387#if HTTP_VIOLATIONS
62e76326 388
38f9c547 389 const refresh_t *R = NULL;
b6445726 390
346be6ad 391 /* This strange looking define first looks up the refresh pattern
b6445726 392 * and then checks if the specified flag is set. The main purpose
393 * of this is to simplify the refresh pattern lookup and HTTP_VIOLATIONS
394 * condition
395 */
396#define REFRESH_OVERRIDE(flag) \
5f8252d2 397 ((R = (R ? R : refreshLimits(entry->mem_obj->url))) , \
398 (R && R->flags.flag))
b445957e 399#else
400#define REFRESH_OVERRIDE(flag) 0
38f9c547 401#endif
43ae1d95 402
38f9c547 403 if (surrogateNoStore)
62e76326 404 return 0;
405
924f73bc 406 if (!ignoreCacheControl) {
38f9c547 407 if (EBIT_TEST(cc_mask, CC_PRIVATE)) {
b6445726 408 if (!REFRESH_OVERRIDE(ignore_private))
38f9c547 409 return 0;
410 }
411
412 if (EBIT_TEST(cc_mask, CC_NO_CACHE)) {
b6445726 413 if (!REFRESH_OVERRIDE(ignore_no_cache))
38f9c547 414 return 0;
415 }
416
417 if (EBIT_TEST(cc_mask, CC_NO_STORE)) {
b6445726 418 if (!REFRESH_OVERRIDE(ignore_no_store))
38f9c547 419 return 0;
420 }
43ae1d95 421 }
422
924f73bc 423 if (request->flags.auth) {
62e76326 424 /*
425 * Responses to requests with authorization may be cached
426 * only if a Cache-Control: public reply header is present.
427 * RFC 2068, sec 14.9.4
428 */
429
38f9c547 430 if (!EBIT_TEST(cc_mask, CC_PUBLIC)) {
b6445726 431 if (!REFRESH_OVERRIDE(ignore_auth))
38f9c547 432 return 0;
433 }
a6dfe2d9 434 }
62e76326 435
c68e9c6b 436 /* Pragma: no-cache in _replies_ is not documented in HTTP,
437 * but servers like "Active Imaging Webcast/2.0" sure do use it */
a9925b40 438 if (hdr->has(HDR_PRAGMA)) {
30abd221 439 String s = hdr->getList(HDR_PRAGMA);
62e76326 440 const int no_cache = strListIsMember(&s, "no-cache", ',');
30abd221 441 s.clean();
62e76326 442
38f9c547 443 if (no_cache) {
b6445726 444 if (!REFRESH_OVERRIDE(ignore_no_cache))
38f9c547 445 return 0;
446 }
c68e9c6b 447 }
62e76326 448
c68e9c6b 449 /*
450 * The "multipart/x-mixed-replace" content type is used for
451 * continuous push replies. These are generally dynamic and
452 * probably should not be cachable
453 */
a9925b40 454 if ((v = hdr->getStr(HDR_CONTENT_TYPE)))
62e76326 455 if (!strncasecmp(v, "multipart/x-mixed-replace", 25))
456 return 0;
457
585ab260 458 switch (rep->sline.status) {
62e76326 459 /* Responses that are cacheable */
460
19a04dac 461 case HTTP_OK:
62e76326 462
19a04dac 463 case HTTP_NON_AUTHORITATIVE_INFORMATION:
62e76326 464
19a04dac 465 case HTTP_MULTIPLE_CHOICES:
62e76326 466
19a04dac 467 case HTTP_MOVED_PERMANENTLY:
62e76326 468
19a04dac 469 case HTTP_GONE:
62e76326 470 /*
471 * Don't cache objects that need to be refreshed on next request,
472 * unless we know how to refresh it.
473 */
474
1b5358c3 475 if (!refreshIsCachable(entry)) {
bf8fe701 476 debugs(22, 3, "refreshIsCachable() returned non-cacheable..");
62e76326 477 return 0;
fc68f6b1 478 }
62e76326 479
480 /* don't cache objects from peers w/o LMT, Date, or Expires */
481 /* check that is it enough to check headers @?@ */
482 if (rep->date > -1)
483 return 1;
484 else if (rep->last_modified > -1)
485 return 1;
924f73bc 486 else if (!_peer)
62e76326 487 return 1;
488
489 /* @?@ (here and 302): invalid expires header compiles to squid_curtime */
490 else if (rep->expires > -1)
491 return 1;
492 else
493 return 0;
494
495 /* NOTREACHED */
496 break;
497
498 /* Responses that only are cacheable if the server says so */
499
19a04dac 500 case HTTP_MOVED_TEMPORARILY:
f18c86fd 501 case HTTP_TEMPORARY_REDIRECT:
6a2bf8f4 502 if (rep->expires > rep->date && rep->date > 0)
62e76326 503 return 1;
504 else
505 return 0;
506
507 /* NOTREACHED */
508 break;
509
510 /* Errors can be negatively cached */
511
19a04dac 512 case HTTP_NO_CONTENT:
62e76326 513
19a04dac 514 case HTTP_USE_PROXY:
62e76326 515
19a04dac 516 case HTTP_BAD_REQUEST:
62e76326 517
19a04dac 518 case HTTP_FORBIDDEN:
62e76326 519
19a04dac 520 case HTTP_NOT_FOUND:
62e76326 521
19a04dac 522 case HTTP_METHOD_NOT_ALLOWED:
62e76326 523
19a04dac 524 case HTTP_REQUEST_URI_TOO_LARGE:
62e76326 525
19a04dac 526 case HTTP_INTERNAL_SERVER_ERROR:
62e76326 527
19a04dac 528 case HTTP_NOT_IMPLEMENTED:
62e76326 529
19a04dac 530 case HTTP_BAD_GATEWAY:
62e76326 531
19a04dac 532 case HTTP_SERVICE_UNAVAILABLE:
62e76326 533
19a04dac 534 case HTTP_GATEWAY_TIMEOUT:
62e76326 535 return -1;
536
537 /* NOTREACHED */
538 break;
539
540 /* Some responses can never be cached */
541
0cdcddb9 542 case HTTP_PARTIAL_CONTENT: /* Not yet supported */
62e76326 543
19a04dac 544 case HTTP_SEE_OTHER:
62e76326 545
19a04dac 546 case HTTP_NOT_MODIFIED:
62e76326 547
19a04dac 548 case HTTP_UNAUTHORIZED:
62e76326 549
19a04dac 550 case HTTP_PROXY_AUTHENTICATION_REQUIRED:
62e76326 551
0cdcddb9 552 case HTTP_INVALID_HEADER: /* Squid header parsing error */
4eb368f9 553
554 case HTTP_HEADER_TOO_LARGE:
b004a7fc 555
556 case HTTP_PAYMENT_REQUIRED:
557 case HTTP_NOT_ACCEPTABLE:
558 case HTTP_REQUEST_TIMEOUT:
559 case HTTP_CONFLICT:
560 case HTTP_LENGTH_REQUIRED:
561 case HTTP_PRECONDITION_FAILED:
562 case HTTP_REQUEST_ENTITY_TOO_LARGE:
563 case HTTP_UNSUPPORTED_MEDIA_TYPE:
564 case HTTP_UNPROCESSABLE_ENTITY:
565 case HTTP_LOCKED:
566 case HTTP_FAILED_DEPENDENCY:
567 case HTTP_INSUFFICIENT_STORAGE:
cc7c3c84 568 case HTTP_REQUESTED_RANGE_NOT_SATISFIABLE:
569 case HTTP_EXPECTATION_FAILED:
b004a7fc 570
62e76326 571 return 0;
572
c54e9052 573 default: /* Unknown status code */
585ab260 574 debugs (11, 0, HERE << "HttpStateData::cacheableReply: unexpected http status code " << rep->sline.status);
62e76326 575
576 return 0;
577
578 /* NOTREACHED */
579 break;
c54e9052 580 }
62e76326 581
79d39a72 582 /* NOTREACHED */
c54e9052 583}
090089c4 584
f66a9ef4 585/*
586 * For Vary, store the relevant request headers as
587 * virtual headers in the reply
588 * Returns false if the variance cannot be stored
589 */
590const char *
190154cf 591httpMakeVaryMark(HttpRequest * request, HttpReply const * reply)
f66a9ef4 592{
30abd221 593 String vary, hdr;
f66a9ef4 594 const char *pos = NULL;
595 const char *item;
596 const char *value;
597 int ilen;
30abd221 598 static String vstr;
f66a9ef4 599
30abd221 600 vstr.clean();
a9925b40 601 vary = reply->header.getList(HDR_VARY);
62e76326 602
f66a9ef4 603 while (strListGetItem(&vary, ',', &item, &ilen, &pos)) {
62e76326 604 char *name = (char *)xmalloc(ilen + 1);
605 xstrncpy(name, item, ilen + 1);
606 Tolower(name);
9776e3cc 607
608 if (strcmp(name, "*") == 0) {
609 /* Can not handle "Vary: *" withtout ETag support */
610 safe_free(name);
30abd221 611 vstr.clean();
9776e3cc 612 break;
613 }
614
62e76326 615 strListAdd(&vstr, name, ',');
a9925b40 616 hdr = request->header.getByName(name);
62e76326 617 safe_free(name);
30abd221 618 value = hdr.buf();
62e76326 619
620 if (value) {
621 value = rfc1738_escape_part(value);
622 vstr.append("=\"", 2);
623 vstr.append(value);
624 vstr.append("\"", 1);
625 }
626
30abd221 627 hdr.clean();
f66a9ef4 628 }
62e76326 629
30abd221 630 vary.clean();
f66a9ef4 631#if X_ACCELERATOR_VARY
62e76326 632
aa38be4a 633 pos = NULL;
a9925b40 634 vary = reply->header.getList(HDR_X_ACCELERATOR_VARY);
62e76326 635
f66a9ef4 636 while (strListGetItem(&vary, ',', &item, &ilen, &pos)) {
62e76326 637 char *name = (char *)xmalloc(ilen + 1);
638 xstrncpy(name, item, ilen + 1);
639 Tolower(name);
640 strListAdd(&vstr, name, ',');
a9925b40 641 hdr = request->header.getByName(name);
62e76326 642 safe_free(name);
30abd221 643 value = hdr.buf();
62e76326 644
645 if (value) {
646 value = rfc1738_escape_part(value);
647 vstr.append("=\"", 2);
648 vstr.append(value);
649 vstr.append("\"", 1);
650 }
651
30abd221 652 hdr.clean();
f66a9ef4 653 }
62e76326 654
30abd221 655 vary.clean();
f66a9ef4 656#endif
62e76326 657
30abd221 658 debugs(11, 3, "httpMakeVaryMark: " << vstr.buf());
659 return vstr.buf();
f66a9ef4 660}
661
2afaba07 662void
663HttpStateData::keepaliveAccounting(HttpReply *reply)
664{
665 if (flags.keepalive)
666 if (_peer)
667 _peer->stats.n_keepalives_sent++;
668
669 if (reply->keep_alive) {
670 if (_peer)
671 _peer->stats.n_keepalives_recv++;
672
673 if (Config.onoff.detect_broken_server_pconns && reply->bodySize(request->method) == -1) {
bf8fe701 674 debugs(11, 1, "keepaliveAccounting: Impossible keep-alive header from '" << entry->url() << "'" );
675 // debugs(11, 2, "GOT HTTP REPLY HDR:\n---------\n" << readBuf->content() << "\n----------" );
2afaba07 676 flags.keepalive_broken = 1;
677 }
678 }
679}
680
681void
682HttpStateData::checkDateSkew(HttpReply *reply)
683{
684 if (reply->date > -1 && !_peer) {
685 int skew = abs((int)(reply->date - squid_curtime));
686
687 if (skew > 86400)
cc192b50 688 debugs(11, 3, "" << request->GetHost() << "'s clock is skewed by " << skew << " seconds!");
2afaba07 689 }
690}
691
692/*
4eb368f9 693 * This creates the error page itself.. its likely
694 * that the forward ported reply header max size patch
695 * generates non http conformant error pages - in which
696 * case the errors where should be 'BAD_GATEWAY' etc
697 */
b8d8561b 698void
2afaba07 699HttpStateData::processReplyHeader()
f5558c95 700{
528b2c61 701 /* Creates a blank header. If this routine is made incremental, this will
702 * not do
703 */
82384411 704 Ctx ctx = ctx_enter(entry->mem_obj->url);
bf8fe701 705 debugs(11, 3, "processReplyHeader: key '" << entry->getMD5Text() << "'");
62e76326 706
1a98175f 707 assert(!flags.headers_parsed);
62e76326 708
2afaba07 709 http_status error = HTTP_STATUS_NONE;
62e76326 710
585ab260 711 HttpReply *newrep = new HttpReply;
4a56ee8d 712 const bool parsed = newrep->parse(readBuf, eof, &error);
62e76326 713
793c0ba9 714 if(!parsed && readBuf->contentSize() > 5 && strncmp(readBuf->content(), "HTTP/", 5) != 0){
715 MemBuf *mb;
716 HttpReply *tmprep = new HttpReply;
717 tmprep->sline.version = HttpVersion(1, 0);
718 tmprep->sline.status = HTTP_OK;
719 tmprep->header.putTime(HDR_DATE, squid_curtime);
720 tmprep->header.putExt("X-Transformed-From", "HTTP/0.9");
721 mb = tmprep->pack();
722 newrep->parse(mb, eof, &error);
723 delete tmprep;
4eb368f9 724 }
793c0ba9 725 else{
726 if (!parsed && error > 0) { // unrecoverable parsing error
727 debugs(11, 3, "processReplyHeader: Non-HTTP-compliant header: '" << readBuf->content() << "'");
728 flags.headers_parsed = 1;
ba82c452 729 newrep->sline.version = HttpVersion(1, 0);
730 newrep->sline.status = error;
585ab260 731 HttpReply *vrep = setVirginReply(newrep);
732 entry->replaceHttpReply(vrep);
793c0ba9 733 ctx_exit(ctx);
734 return;
735 }
736
737 if (!parsed) { // need more data
738 assert(!error);
739 assert(!eof);
740 delete newrep;
741 ctx_exit(ctx);
742 return;
743 }
744
745 debugs(11, 9, "GOT HTTP REPLY HDR:\n---------\n" << readBuf->content() << "\n----------");
746
747 header_bytes_read = headersEnd(readBuf->content(), readBuf->contentSize());
748 readBuf->consume(header_bytes_read);
f5558c95 749 }
62e76326 750
af0bb8e5 751 flags.chunked = 0;
752 if (newrep->header.hasListMember(HDR_TRANSFER_ENCODING, "chunked", ',')) {
753 flags.chunked = 1;
754 httpChunkDecoder = new ChunkedCodingParser;
755 }
756
585ab260 757 HttpReply *vrep = setVirginReply(newrep);
6965ab28 758 flags.headers_parsed = 1;
759
585ab260 760 keepaliveAccounting(vrep);
47ac2ebe 761
585ab260 762 checkDateSkew(vrep);
47ac2ebe 763
585ab260 764 processSurrogateControl (vrep);
528b2c61 765
766 /* TODO: IF the reply is a 1.0 reply, AND it has a Connection: Header
767 * Parse the header and remove all referenced headers
768 */
769
2afaba07 770 ctx_exit(ctx);
7dc79973 771
2afaba07 772}
773
5f8252d2 774// Called when we parsed (and possibly adapted) the headers but
775// had not starting storing (a.k.a., sending) the body yet.
2afaba07 776void
777HttpStateData::haveParsedReplyHeaders()
778{
779 Ctx ctx = ctx_enter(entry->mem_obj->url);
585ab260 780 HttpReply *rep = finalReply();
2afaba07 781
585ab260 782 if (rep->sline.status == HTTP_PARTIAL_CONTENT &&
783 rep->content_range)
784 currentOffset = rep->content_range->spec.offset;
62e76326 785
3900307b 786 entry->timestampsSet();
62e76326 787
9bc73deb 788 /* Check if object is cacheable or not based on reply code */
585ab260 789 debugs(11, 3, "haveParsedReplyHeaders: HTTP CODE: " << rep->sline.status);
62e76326 790
9bc73deb 791 if (neighbors_do_private_keys)
585ab260 792 httpMaybeRemovePublic(entry, rep->sline.status);
e6ccf245 793
585ab260 794 if (rep->header.has(HDR_VARY)
f66a9ef4 795#if X_ACCELERATOR_VARY
585ab260 796 || rep->header.has(HDR_X_ACCELERATOR_VARY)
f66a9ef4 797#endif
4b44c907 798 ) {
585ab260 799 const char *vary = httpMakeVaryMark(orig_request, rep);
4b44c907 800
801 if (!vary) {
5ed72359 802 entry->makePrivate();
4b44c907 803 goto no_cache;
804
62e76326 805 }
806
4b44c907 807 entry->mem_obj->vary_headers = xstrdup(vary);
808 }
809
2afaba07 810#if WIP_FWD_LOG
811 fwdStatus(fwd, s);
812
813#endif
814 /*
815 * If its not a reply that we will re-forward, then
816 * allow the client to get it.
817 */
585ab260 818 if (!fwd->reforwardableStatus(rep->sline.status))
2afaba07 819 EBIT_CLR(entry->flags, ENTRY_FWD_HDR_WAIT);
820
4b44c907 821 switch (cacheableReply()) {
822
823 case 1:
5ed72359 824 entry->makePublic();
62e76326 825 break;
826
9bc73deb 827 case 0:
5ed72359 828 entry->makePrivate();
62e76326 829 break;
830
9bc73deb 831 case -1:
4b44c907 832
833 if (Config.negativeTtl > 0)
5ed72359 834 entry->cacheNegatively();
4b44c907 835 else
5ed72359 836 entry->makePrivate();
4b44c907 837
62e76326 838 break;
839
9bc73deb 840 default:
62e76326 841 assert(0);
4b44c907 842
62e76326 843 break;
9bc73deb 844 }
62e76326 845
4b44c907 846no_cache:
847
585ab260 848 if (!ignoreCacheControl && rep->cache_control) {
849 if (EBIT_TEST(rep->cache_control->mask, CC_PROXY_REVALIDATE))
62e76326 850 EBIT_SET(entry->flags, ENTRY_REVALIDATE);
585ab260 851 else if (EBIT_TEST(rep->cache_control->mask, CC_MUST_REVALIDATE))
62e76326 852 EBIT_SET(entry->flags, ENTRY_REVALIDATE);
9bc73deb 853 }
62e76326 854
c3609322 855#if HEADERS_LOG
585ab260 856 headersLog(1, 0, request->method, rep);
fc68f6b1 857
c3609322 858#endif
5f8252d2 859
860 ctx_exit(ctx);
f5558c95 861}
862
528b2c61 863HttpStateData::ConnectionStatus
864HttpStateData::statusIfComplete() const
603a02fd 865{
585ab260 866 const HttpReply *rep = virginReply();
528b2c61 867 /* If the reply wants to close the connection, it takes precedence */
62e76326 868
2afaba07 869 if (httpHeaderHasConnDir(&rep->header, "close"))
62e76326 870 return COMPLETE_NONPERSISTENT_MSG;
871
528b2c61 872 /* If we didn't send a keep-alive request header, then this
978e455f 873 * can not be a persistent connection.
874 */
528b2c61 875 if (!flags.keepalive)
62e76326 876 return COMPLETE_NONPERSISTENT_MSG;
877
72b63f06 878 /*
879 * If we haven't sent the whole request then this can not be a persistent
880 * connection.
881 */
882 if (!flags.request_sent) {
60745f24 883 debugs(11, 1, "statusIfComplete: Request not yet fully sent \"" << RequestMethodStr(orig_request->method) << " " << entry->url() << "\"" );
72b63f06 884 return COMPLETE_NONPERSISTENT_MSG;
885 }
886
9f5a2895 887 /*
888 * What does the reply have to say about keep-alive?
889 */
b6a2f15e 890 /*
891 * XXX BUG?
892 * If the origin server (HTTP/1.0) does not send a keep-alive
893 * header, but keeps the connection open anyway, what happens?
894 * We'll return here and http.c waits for an EOF before changing
895 * store_status to STORE_OK. Combine this with ENTRY_FWD_HDR_WAIT
896 * and an error status code, and we might have to wait until
897 * the server times out the socket.
898 */
2afaba07 899 if (!rep->keep_alive)
528b2c61 900 return COMPLETE_NONPERSISTENT_MSG;
62e76326 901
528b2c61 902 return COMPLETE_PERSISTENT_MSG;
903}
904
905HttpStateData::ConnectionStatus
906HttpStateData::persistentConnStatus() const
907{
ba82c452 908 debugs(11, 3, "persistentConnStatus: FD " << fd << " eof=" << eof);
585ab260 909 const HttpReply *vrep = virginReply();
910 debugs(11, 5, "persistentConnStatus: content_length=" << vrep->content_length);
62e76326 911
5f8252d2 912 /* If we haven't seen the end of reply headers, we are not done */
bf8fe701 913 debugs(11, 5, "persistentConnStatus: flags.headers_parsed=" << flags.headers_parsed);
fc68f6b1 914
1a98175f 915 if (!flags.headers_parsed)
62e76326 916 return INCOMPLETE_MSG;
917
af0bb8e5 918 /* In chunked responce we do not know the content length but we are absolutelly
919 * sure about the end of response, so we are calling the statusIfComplete to
920 * decide if we can be persistant
921 */
922 if (eof && flags.chunked)
923 return statusIfComplete();
924
ba82c452 925 if (eof) // already reached EOF
926 return COMPLETE_NONPERSISTENT_MSG;
927
47f6e231 928 const int64_t clen = vrep->bodySize(request->method);
fc68f6b1 929
bf8fe701 930 debugs(11, 5, "persistentConnStatus: clen=" << clen);
2afaba07 931
35282fbf 932 /* If the body size is unknown we must wait for EOF */
933 if (clen < 0)
62e76326 934 return INCOMPLETE_MSG;
935
5f8252d2 936 /* If the body size is known, we must wait until we've gotten all of it. */
937 if (clen > 0) {
938 // old technique:
585ab260 939 // if (entry->mem_obj->endOffset() < vrep->content_length + vrep->hdr_sz)
47f6e231 940 const int64_t body_bytes_read = reply_bytes_read - header_bytes_read;
5f8252d2 941 debugs(11,5, "persistentConnStatus: body_bytes_read=" <<
585ab260 942 body_bytes_read << " content_length=" << vrep->content_length);
2afaba07 943
585ab260 944 if (body_bytes_read < vrep->content_length)
5f8252d2 945 return INCOMPLETE_MSG;
946 }
62e76326 947
5f8252d2 948 /* If there is no message body or we got it all, we can be persistent */
949 return statusIfComplete();
603a02fd 950}
090089c4 951
2afaba07 952/*
953 * This is the callback after some data has been read from the network
954 */
dc56a9b1 955/*
e5ee81f0 956void
957HttpStateData::ReadReplyWrapper(int fd, char *buf, size_t len, comm_err_t flag, int xerrno, void *data)
c4b7a5a9 958{
959 HttpStateData *httpState = static_cast<HttpStateData *>(data);
7194987f 960 assert (fd == httpState->fd);
2afaba07 961 // assert(buf == readBuf->content());
1d5161bd 962 PROF_start(HttpStateData_readReply);
2afaba07 963 httpState->readReply (len, flag, xerrno);
1d5161bd 964 PROF_stop(HttpStateData_readReply);
c4b7a5a9 965}
dc56a9b1 966*/
2afdbf48 967/* XXX this function is too long! */
c4b7a5a9 968void
dc56a9b1 969HttpStateData::readReply (const CommIoCbParams &io)
090089c4 970{
30a4f2a8 971 int bin;
090089c4 972 int clen;
dc56a9b1 973 int len = io.size;
c4b7a5a9 974
dc56a9b1 975 assert(fd == io.fd);
976
977 flags.do_next_read = 0;
978
7a7cc03f 979 debugs(11, 5, "httpReadReply: FD " << fd << ": len " << len << ".");
62e76326 980
7a7cc03f 981 // Bail out early on COMM_ERR_CLOSING - close handlers will tidy up for us
dc56a9b1 982 if (io.flag == COMM_ERR_CLOSING) {
bf8fe701 983 debugs(11, 3, "http socket closing");
c4b7a5a9 984 return;
985 }
986
e92e4e44 987 if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
5f8252d2 988 maybeReadVirginBody();
62e76326 989 return;
e92e4e44 990 }
c4b7a5a9 991
fdf55365 992 // handle I/O errors
dc56a9b1 993 if (io.flag != COMM_OK || len < 0) {
7a7cc03f 994 debugs(11, 2, "httpReadReply: FD " << fd << ": read failure: " << xstrerror() << ".");
fdf55365 995
dc56a9b1 996 if (ignoreErrno(io.xerrno)) {
fdf55365 997 flags.do_next_read = 1;
998 } else {
999 ErrorState *err;
1000 err = errorCon(ERR_READ_ERROR, HTTP_BAD_GATEWAY, fwd->request);
dc56a9b1 1001 err->xerrno = io.xerrno;
fdf55365 1002 fwd->fail(err);
1003 flags.do_next_read = 0;
1004 comm_close(fd);
1005 }
1006
1007 return;
1008 }
1009
7a7cc03f 1010 // update I/O stats
fdf55365 1011 if (len > 0) {
2afaba07 1012 readBuf->appended(len);
5f8252d2 1013 reply_bytes_read += len;
447e176b 1014#if DELAY_POOLS
2afaba07 1015
1016 DelayId delayId = entry->mem_obj->mostBytesAllowed();
62e76326 1017 delayId.bytesIn(len);
447e176b 1018#endif
62e76326 1019
1020 kb_incr(&statCounter.server.all.kbytes_in, len);
1021 kb_incr(&statCounter.server.http.kbytes_in, len);
62e76326 1022 IOStats.Http.reads++;
1023
1024 for (clen = len - 1, bin = 0; clen; bin++)
1025 clen >>= 1;
1026
1027 IOStats.Http.read_hist[bin]++;
30a4f2a8 1028 }
62e76326 1029
5fa061b8 1030 /* here the RFC says we should ignore whitespace between replies, but we can't as
1031 * doing so breaks HTTP/0.9 replies beginning with witespace, and in addition
1032 * the response splitting countermeasures is extremely likely to trigger on this,
1033 * not allowing connection reuse in the first place.
1034 */
1035#if DONT_DO_THIS
fdf55365 1036 if (!flags.headers_parsed && len > 0 && fd_table[fd].uses > 1) {
5fa061b8 1037 /* Skip whitespace between replies */
62e76326 1038
e4755e29 1039 while (len > 0 && xisspace(*buf))
62e76326 1040 xmemmove(buf, buf + 1, len--);
1041
1042 if (len == 0) {
1043 /* Continue to read... */
21b92762 1044 /* Timeout NOT increased. This whitespace was from previous reply */
f61f0107 1045 flags.do_next_read = 1;
5f8252d2 1046 maybeReadVirginBody();
62e76326 1047 return;
1048 }
5ede6c8f 1049 }
62e76326 1050
5fa061b8 1051#endif
1052
ba82c452 1053 if (len == 0) { // reached EOF?
62e76326 1054 eof = 1;
f61f0107 1055 flags.do_next_read = 0;
ba82c452 1056 }
62e76326 1057
ba82c452 1058 if (!flags.headers_parsed) { // have not parsed headers yet?
1059 PROF_start(HttpStateData_processReplyHeader);
1060 processReplyHeader();
1061 PROF_stop(HttpStateData_processReplyHeader);
1062
1063 if (!continueAfterParsingHeader()) // parsing error or need more data
1064 return; // TODO: send errors to ICAP
1065
585ab260 1066 adaptOrFinalizeReply();
ba82c452 1067 }
1068
1069 // kick more reads if needed and/or process the response body, if any
1070 PROF_start(HttpStateData_processReplyBody);
1071 processReplyBody(); // may call serverComplete()
1072 PROF_stop(HttpStateData_processReplyBody);
1073}
1074
1075// Checks whether we can continue with processing the body or doing ICAP.
1076// Returns false if we cannot (e.g., due to lack of headers or errors).
1077bool
1078HttpStateData::continueAfterParsingHeader()
1079{
1080 if (!flags.headers_parsed && !eof) { // need more and may get more
1081 debugs(11, 9, HERE << "needs more at " << readBuf->contentSize());
1082 flags.do_next_read = 1;
1083 maybeReadVirginBody(); // schedules all kinds of reads; TODO: rename
1084 return false; // wait for more data
1085 }
1086
1087 /* we are done with parsing, now check for errors */
1088
1089 err_type error = ERR_NONE;
1090
1091 if (flags.headers_parsed) { // parsed headers, possibly with errors
1092 // check for header parsing errors
585ab260 1093 if (HttpReply *vrep = virginReply()) {
1094 const http_status s = vrep->sline.status;
1095 const HttpVersion &v = vrep->sline.version;
ba82c452 1096 if (s == HTTP_INVALID_HEADER && v != HttpVersion(0,9)) {
1097 error = ERR_INVALID_RESP;
1098 } else
1099 if (s == HTTP_HEADER_TOO_LARGE) {
b6b6f466 1100 fwd->dontRetry(true);
ba82c452 1101 error = ERR_TOO_BIG;
4eb368f9 1102 } else {
ba82c452 1103 return true; // done parsing, got reply, and no error
4eb368f9 1104 }
ba82c452 1105 } else {
1106 // parsed headers but got no reply
1107 error = ERR_INVALID_RESP;
62e76326 1108 }
090089c4 1109 } else {
ba82c452 1110 assert(eof);
1111 error = readBuf->hasContent() ?
1112 ERR_INVALID_RESP : ERR_ZERO_SIZE_OBJECT;
2afaba07 1113 }
ba82c452 1114
1115 assert(error != ERR_NONE);
1116 entry->reset();
1117 fwd->fail(errorCon(error, HTTP_BAD_GATEWAY, fwd->request));
1118 flags.do_next_read = 0;
1119 comm_close(fd);
1120 return false; // quit on error
2afaba07 1121}
1122
1123/*
1124 * Call this when there is data from the origin server
1125 * which should be sent to either StoreEntry, or to ICAP...
1126 */
1127void
5f8252d2 1128HttpStateData::writeReplyBody()
2afaba07 1129{
5f8252d2 1130 const char *data = readBuf->content();
1131 int len = readBuf->contentSize();
bc81cb2b 1132 addVirginReplyBody(data, len);
5f8252d2 1133 readBuf->consume(len);
af0bb8e5 1134}
fc68f6b1 1135
af0bb8e5 1136bool
1137HttpStateData::decodeAndWriteReplyBody()
1138{
1139 const char *data = NULL;
1140 int len;
1141 bool status = false;
1142 assert(flags.chunked);
1143 assert(httpChunkDecoder);
1144 SQUID_ENTER_THROWING_CODE();
1145 MemBuf decodedData;
1146 decodedData.init();
1147 const bool done = httpChunkDecoder->parse(readBuf,&decodedData);
1148 len = decodedData.contentSize();
1149 data=decodedData.content();
1150 addVirginReplyBody(data, len);
1151 if (done) {
1152 eof = 1;
1153 flags.do_next_read = 0;
1154 }
1155 SQUID_EXIT_THROWING_CODE(status);
1156 return status;
e6ccf245 1157}
1158
2afaba07 1159/*
1160 * processReplyBody has two purposes:
1161 * 1 - take the reply body data, if any, and put it into either
1162 * the StoreEntry, or give it over to ICAP.
1163 * 2 - see if we made it to the end of the response (persistent
1164 * connections and such)
1165 */
e6ccf245 1166void
2afaba07 1167HttpStateData::processReplyBody()
e6ccf245 1168{
dc56a9b1 1169 AsyncCall::Pointer call;
cc192b50 1170 IPAddress client_addr;
fc68f6b1 1171
1a98175f 1172 if (!flags.headers_parsed) {
f61f0107 1173 flags.do_next_read = 1;
5f8252d2 1174 maybeReadVirginBody();
62e76326 1175 return;
528b2c61 1176 }
62e76326 1177
a83c6ed6
AR
1178#if USE_ADAPTATION
1179 if (adaptationAccessCheckPending)
2afaba07 1180 return;
fc68f6b1 1181
2afaba07 1182#endif
62e76326 1183
2afaba07 1184 /*
1185 * At this point the reply headers have been parsed and consumed.
1186 * That means header content has been removed from readBuf and
1187 * it contains only body data.
1188 */
af0bb8e5 1189 if(flags.chunked){
1190 if(!decodeAndWriteReplyBody()){
1191 flags.do_next_read = 0;
1192 serverComplete();
1193 return;
1194 }
1195 }
1196 else
1197 writeReplyBody();
528b2c61 1198
e6ccf245 1199 if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
62e76326 1200 /*
2afaba07 1201 * the above writeReplyBody() call could ABORT this entry,
62e76326 1202 * in that case, the server FD should already be closed.
1203 * there's nothing for us to do.
1204 */
1205 (void) 0;
1206 } else
1207 switch (persistentConnStatus()) {
62e76326 1208 case INCOMPLETE_MSG:
bf8fe701 1209 debugs(11, 5, "processReplyBody: INCOMPLETE_MSG");
21b92762 1210 /* Wait for more data or EOF condition */
21b92762 1211 if (flags.keepalive_broken) {
dc56a9b1 1212 call = NULL;
1213 commSetTimeout(fd, 10, call);
21b92762 1214 } else {
dc56a9b1 1215 call = NULL;
1216 commSetTimeout(fd, Config.Timeout.read, call);
21b92762 1217 }
1218
f61f0107 1219 flags.do_next_read = 1;
62e76326 1220 break;
1221
1222 case COMPLETE_PERSISTENT_MSG:
bf8fe701 1223 debugs(11, 5, "processReplyBody: COMPLETE_PERSISTENT_MSG");
62e76326 1224 /* yes we have to clear all these! */
dc56a9b1 1225 call = NULL;
1226 commSetTimeout(fd, -1, call);
f61f0107 1227 flags.do_next_read = 0;
62e76326 1228
dc56a9b1 1229 comm_remove_close_handler(fd, closeHandler);
1230 closeHandler = NULL;
b6b6f466 1231 fwd->unregister(fd);
f1e0717c 1232
f165d2fb 1233 if (orig_request->flags.spoof_client_ip)
cc192b50 1234 client_addr = orig_request->client_addr;
fc68f6b1 1235
bd0723ad 1236 if (_peer) {
1237 if (_peer->options.originserver)
cc192b50 1238 fwd->pconnPush(fd, _peer->name, orig_request->port, orig_request->GetHost(), client_addr);
bd0723ad 1239 else
fc68f6b1 1240 fwd->pconnPush(fd, _peer->name, _peer->http_port, NULL, client_addr);
bd0723ad 1241 } else {
cc192b50 1242 fwd->pconnPush(fd, request->GetHost(), request->port, NULL, client_addr);
bd0723ad 1243 }
1244
62e76326 1245 fd = -1;
2afaba07 1246
5f8252d2 1247 serverComplete();
62e76326 1248 return;
1249
1250 case COMPLETE_NONPERSISTENT_MSG:
bf8fe701 1251 debugs(11, 5, "processReplyBody: COMPLETE_NONPERSISTENT_MSG");
5f8252d2 1252 serverComplete();
62e76326 1253 return;
1254 }
1255
5f8252d2 1256 maybeReadVirginBody();
c4b7a5a9 1257}
1258
1259void
5f8252d2 1260HttpStateData::maybeReadVirginBody()
c4b7a5a9 1261{
7dc79973 1262 int read_sz = replyBodySpace(readBuf->spaceSize());
2afaba07 1263
5f8252d2 1264 debugs(11,9, HERE << (flags.do_next_read ? "may" : "wont") <<
fc68f6b1 1265 " read up to " << read_sz << " bytes from FD " << fd);
2afaba07 1266
1267 /*
1268 * why <2? Because delayAwareRead() won't actually read if
1269 * you ask it to read 1 byte. The delayed read request
1270 * just gets re-queued until the client side drains, then
1271 * the I/O thread hangs. Better to not register any read
1272 * handler until we get a notification from someone that
1273 * its okay to read again.
1274 */
53dbd8cb 1275 if (read_sz < 2) {
1276 if (flags.headers_parsed)
1277 return;
1278 else
1279 read_sz = 1024;
1280 }
2afaba07 1281
f61f0107 1282 if (flags.do_next_read) {
dc56a9b1 1283 flags.do_next_read = 0;
1284 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
1285 entry->delayAwareRead(fd, readBuf->space(read_sz), read_sz,
1286 asyncCall(11, 5, "HttpStateData::readReply",
1287 Dialer(this, &HttpStateData::readReply)));
528b2c61 1288 }
090089c4 1289}
1290
2afaba07 1291/*
1292 * This will be called when request write is complete.
1293 */
d576a6a6 1294void
dc56a9b1 1295HttpStateData::sendComplete(const CommIoCbParams &io)
090089c4 1296{
dc56a9b1 1297 debugs(11, 5, "httpSendComplete: FD " << fd << ": size " << io.size << ": errflag " << io.flag << ".");
bc87dc25 1298#if URL_CHECKSUM_DEBUG
62e76326 1299
528b2c61 1300 entry->mem_obj->checkUrlChecksum();
bc87dc25 1301#endif
62e76326 1302
dc56a9b1 1303 if (io.size > 0) {
1304 fd_bytes(fd, io.size, FD_WRITE);
1305 kb_incr(&statCounter.server.all.kbytes_out, io.size);
1306 kb_incr(&statCounter.server.http.kbytes_out, io.size);
ee1679df 1307 }
62e76326 1308
dc56a9b1 1309 if (io.flag == COMM_ERR_CLOSING)
62e76326 1310 return;
1311
dc56a9b1 1312 if (io.flag) {
6cae5db1 1313 ErrorState *err;
dc56a9b1 1314 err = errorCon(ERR_WRITE_ERROR, HTTP_BAD_GATEWAY, fwd->request);
1315 err->xerrno = io.xerrno;
1316 fwd->fail(err);
62e76326 1317 comm_close(fd);
1318 return;
090089c4 1319 }
72b63f06 1320
2afaba07 1321 /*
1322 * Set the read timeout here because it hasn't been set yet.
1323 * We only set the read timeout after the request has been
1324 * fully written to the server-side. If we start the timeout
1325 * after connection establishment, then we are likely to hit
1326 * the timeout for POST/PUT requests that have very large
1327 * request bodies.
1328 */
dc56a9b1 1329 typedef CommCbMemFunT<HttpStateData, CommTimeoutCbParams> TimeoutDialer;
1330 AsyncCall::Pointer timeoutCall = asyncCall(11, 5, "HttpStateData::httpTimeout",
1331 TimeoutDialer(this,&HttpStateData::httpTimeout));
2afaba07 1332
dc56a9b1 1333 commSetTimeout(fd, Config.Timeout.read, timeoutCall);
1334
1335 flags.request_sent = 1;
090089c4 1336}
1337
5f8252d2 1338// Close the HTTP server connection. Used by serverComplete().
2afaba07 1339void
5f8252d2 1340HttpStateData::closeServer()
2afaba07 1341{
5f8252d2 1342 debugs(11,5, HERE << "closing HTTP server FD " << fd << " this " << this);
fc68f6b1 1343
2afaba07 1344 if (fd >= 0) {
b6b6f466 1345 fwd->unregister(fd);
dc56a9b1 1346 comm_remove_close_handler(fd, closeHandler);
1347 closeHandler = NULL;
2afaba07 1348 comm_close(fd);
1349 fd = -1;
1350 }
5f8252d2 1351}
2afaba07 1352
5f8252d2 1353bool
1354HttpStateData::doneWithServer() const
1355{
1356 return fd < 0;
2afaba07 1357}
1358
99edd1c3 1359/*
1360 * build request headers and append them to a given MemBuf
e5ee81f0 1361 * used by buildRequestPrefix()
818c6c9e 1362 * note: initialised the HttpHeader, the caller is responsible for Clean()-ing
99edd1c3 1363 */
e1e72f06 1364void
e5ee81f0 1365HttpStateData::httpBuildRequestHeader(HttpRequest * request,
1366 HttpRequest * orig_request,
1367 StoreEntry * entry,
1368 HttpHeader * hdr_out,
1369 http_state_flags flags)
6bf8443a 1370{
99edd1c3 1371 /* building buffer for complex strings */
5999b776 1372#define BBUF_SZ (MAX_URL+32)
99edd1c3 1373 LOCAL_ARRAY(char, bbuf, BBUF_SZ);
99edd1c3 1374 const HttpHeader *hdr_in = &orig_request->header;
1375 const HttpHeaderEntry *e;
30abd221 1376 String strFwd;
99edd1c3 1377 HttpHeaderPos pos = HttpHeaderInitPos;
75faaa7a 1378 assert (hdr_out->owner == hoRequest);
99edd1c3 1379 /* append our IMS header */
62e76326 1380
fa3e249f 1381 if (request->lastmod > -1)
a9925b40 1382 hdr_out->putTime(HDR_IF_MODIFIED_SINCE, request->lastmod);
99edd1c3 1383
528b2c61 1384 bool we_do_ranges = decideIfWeDoRanges (orig_request);
1385
30abd221 1386 String strConnection (hdr_in->getList(HDR_CONNECTION));
62e76326 1387
a9925b40 1388 while ((e = hdr_in->getEntry(&pos)))
62e76326 1389 copyOneHeaderFromClientsideRequestToUpstreamRequest(e, strConnection, request, orig_request, hdr_out, we_do_ranges, flags);
528b2c61 1390
43ae1d95 1391 /* Abstraction break: We should interpret multipart/byterange responses
528b2c61 1392 * into offset-length data, and this works around our inability to do so.
1393 */
62e76326 1394 if (!we_do_ranges && orig_request->multipartRangeRequest()) {
1395 /* don't cache the result */
1396 orig_request->flags.cachable = 0;
1397 /* pretend it's not a range request */
00d77d6b 1398 delete orig_request->range;
62e76326 1399 orig_request->range = NULL;
1400 orig_request->flags.range = 0;
1401 }
528b2c61 1402
99edd1c3 1403 /* append Via */
736cb6aa 1404 if (Config.onoff.via) {
30abd221 1405 String strVia;
a9925b40 1406 strVia = hdr_in->getList(HDR_VIA);
62e76326 1407 snprintf(bbuf, BBUF_SZ, "%d.%d %s",
1408 orig_request->http_ver.major,
1409 orig_request->http_ver.minor, ThisCache);
1410 strListAdd(&strVia, bbuf, ',');
30abd221 1411 hdr_out->putStr(HDR_VIA, strVia.buf());
1412 strVia.clean();
736cb6aa 1413 }
62e76326 1414
f41735ea 1415#if USE_SQUID_ESI
43ae1d95 1416 {
1417 /* Append Surrogate-Capabilities */
30abd221 1418 String strSurrogate (hdr_in->getList(HDR_SURROGATE_CAPABILITY));
ec43ae0e 1419 snprintf(bbuf, BBUF_SZ, "%s=\"Surrogate/1.0 ESI/1.0\"",
43ae1d95 1420 Config.Accel.surrogate_id);
1421 strListAdd(&strSurrogate, bbuf, ',');
30abd221 1422 hdr_out->putStr(HDR_SURROGATE_CAPABILITY, strSurrogate.buf());
43ae1d95 1423 }
1424#endif
1425
99edd1c3 1426 /* append X-Forwarded-For */
a9925b40 1427 strFwd = hdr_in->getList(HDR_X_FORWARDED_FOR);
62e76326 1428
cc192b50 1429 if (opt_forwarded_for && !orig_request->client_addr.IsNoAddr()) {
1430 orig_request->client_addr.NtoA(bbuf,MAX_IPSTRLEN);
1431 strListAdd(&strFwd, bbuf, ',');
1432 }
6056ae68 1433 else
62e76326 1434 strListAdd(&strFwd, "unknown", ',');
1435
30abd221 1436 hdr_out->putStr(HDR_X_FORWARDED_FOR, strFwd.buf());
62e76326 1437
30abd221 1438 strFwd.clean();
6bccf575 1439
99edd1c3 1440 /* append Host if not there already */
a9925b40 1441 if (!hdr_out->has(HDR_HOST)) {
62e76326 1442 if (orig_request->peer_domain) {
a9925b40 1443 hdr_out->putStr(HDR_HOST, orig_request->peer_domain);
62e76326 1444 } else if (orig_request->port == urlDefaultPort(orig_request->protocol)) {
1445 /* use port# only if not default */
cc192b50 1446 hdr_out->putStr(HDR_HOST, orig_request->GetHost());
62e76326 1447 } else {
1448 httpHeaderPutStrf(hdr_out, HDR_HOST, "%s:%d",
cc192b50 1449 orig_request->GetHost(),
1450 (int) orig_request->port);
62e76326 1451 }
6bf8443a 1452 }
62e76326 1453
c68e9c6b 1454 /* append Authorization if known in URL, not in header and going direct */
a9925b40 1455 if (!hdr_out->has(HDR_AUTHORIZATION)) {
62e76326 1456 if (!request->flags.proxying && *request->login) {
1457 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1458 base64_encode(request->login));
1459 }
c68e9c6b 1460 }
62e76326 1461
c68e9c6b 1462 /* append Proxy-Authorization if configured for peer, and proxying */
c3b33cb7 1463 if (request->flags.proxying && orig_request->peer_login &&
a9925b40 1464 !hdr_out->has(HDR_PROXY_AUTHORIZATION)) {
62e76326 1465 if (*orig_request->peer_login == '*') {
1466 /* Special mode, to pass the username to the upstream cache */
1467 char loginbuf[256];
1468 const char *username = "-";
1469
a8bc2b9c 1470 if (orig_request->extacl_user.size())
30abd221 1471 username = orig_request->extacl_user.buf();
a8bc2b9c 1472 else if (orig_request->auth_user_request)
1473 username = orig_request->auth_user_request->username();
62e76326 1474
1475 snprintf(loginbuf, sizeof(loginbuf), "%s%s", username, orig_request->peer_login + 1);
1476
1477 httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Basic %s",
1478 base64_encode(loginbuf));
1479 } else if (strcmp(orig_request->peer_login, "PASS") == 0) {
abb929f0 1480 if (orig_request->extacl_user.size() && orig_request->extacl_passwd.size()) {
1481 char loginbuf[256];
30abd221 1482 snprintf(loginbuf, sizeof(loginbuf), "%s:%s", orig_request->extacl_user.buf(), orig_request->extacl_passwd.buf());
abb929f0 1483 httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Basic %s",
1484 base64_encode(loginbuf));
1485 }
62e76326 1486 } else if (strcmp(orig_request->peer_login, "PROXYPASS") == 0) {
1487 /* Nothing to do */
1488 } else {
1489 httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Basic %s",
1490 base64_encode(orig_request->peer_login));
1491 }
c68e9c6b 1492 }
62e76326 1493
be753325 1494 /* append WWW-Authorization if configured for peer */
1495 if (flags.originpeer && orig_request->peer_login &&
a9925b40 1496 !hdr_out->has(HDR_AUTHORIZATION)) {
62e76326 1497 if (strcmp(orig_request->peer_login, "PASS") == 0) {
1498 /* No credentials to forward.. (should have been done above if available) */
1499 } else if (strcmp(orig_request->peer_login, "PROXYPASS") == 0) {
1500 /* Special mode, convert proxy authentication to WWW authentication
abb929f0 1501 * (also applies to authentication provided by external acl)
62e76326 1502 */
a9925b40 1503 const char *auth = hdr_in->getStr(HDR_PROXY_AUTHORIZATION);
62e76326 1504
1505 if (auth && strncasecmp(auth, "basic ", 6) == 0) {
a9925b40 1506 hdr_out->putStr(HDR_AUTHORIZATION, auth);
abb929f0 1507 } else if (orig_request->extacl_user.size() && orig_request->extacl_passwd.size()) {
1508 char loginbuf[256];
30abd221 1509 snprintf(loginbuf, sizeof(loginbuf), "%s:%s", orig_request->extacl_user.buf(), orig_request->extacl_passwd.buf());
abb929f0 1510 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1511 base64_encode(loginbuf));
62e76326 1512 }
1513 } else if (*orig_request->peer_login == '*') {
1514 /* Special mode, to pass the username to the upstream cache */
1515 char loginbuf[256];
1516 const char *username = "-";
1517
1518 if (orig_request->auth_user_request)
f5691f9c 1519 username = orig_request->auth_user_request->username();
abb929f0 1520 else if (orig_request->extacl_user.size())
30abd221 1521 username = orig_request->extacl_user.buf();
62e76326 1522
1523 snprintf(loginbuf, sizeof(loginbuf), "%s%s", username, orig_request->peer_login + 1);
1524
1525 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1526 base64_encode(loginbuf));
1527 } else {
1528 /* Fixed login string */
1529 httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
1530 base64_encode(orig_request->peer_login));
1531 }
be753325 1532 }
62e76326 1533
abb929f0 1534 /* append Cache-Control, add max-age if not there already */ {
a9925b40 1535 HttpHdrCc *cc = hdr_in->getCc();
62e76326 1536
1537 if (!cc)
1538 cc = httpHdrCcCreate();
1539
1540 if (!EBIT_TEST(cc->mask, CC_MAX_AGE)) {
43ae1d95 1541 const char *url =
3900307b 1542 entry ? entry->url() : urlCanonical(orig_request);
62e76326 1543 httpHdrCcSetMaxAge(cc, getMaxAge(url));
1544
1545 if (request->urlpath.size())
30abd221 1546 assert(strstr(url, request->urlpath.buf()));
62e76326 1547 }
1548
ce2d6441 1549 /* Set no-cache if determined needed but not found */
a9925b40 1550 if (orig_request->flags.nocache && !hdr_in->has(HDR_PRAGMA))
ce2d6441 1551 EBIT_SET(cc->mask, CC_NO_CACHE);
1552
1553 /* Enforce sibling relations */
62e76326 1554 if (flags.only_if_cached)
1555 EBIT_SET(cc->mask, CC_ONLY_IF_CACHED);
1556
a9925b40 1557 hdr_out->putCc(cc);
62e76326 1558
1559 httpHdrCcDestroy(cc);
6bf8443a 1560 }
62e76326 1561
99edd1c3 1562 /* maybe append Connection: keep-alive */
b515fc11 1563 if (flags.keepalive) {
62e76326 1564 if (flags.proxying) {
a9925b40 1565 hdr_out->putStr(HDR_PROXY_CONNECTION, "keep-alive");
62e76326 1566 } else {
a9925b40 1567 hdr_out->putStr(HDR_CONNECTION, "keep-alive");
62e76326 1568 }
603a02fd 1569 }
62e76326 1570
a7ad6e4e 1571 /* append Front-End-Https */
1572 if (flags.front_end_https) {
62e76326 1573 if (flags.front_end_https == 1 || request->protocol == PROTO_HTTPS)
a9925b40 1574 hdr_out->putStr(HDR_FRONT_END_HTTPS, "On");
a7ad6e4e 1575 }
1576
6bccf575 1577 /* Now mangle the headers. */
4f56514c 1578 if (Config2.onoff.mangle_request_headers)
5967c0bf 1579 httpHdrMangleList(hdr_out, request, ROR_REQUEST);
62e76326 1580
30abd221 1581 strConnection.clean();
99edd1c3 1582}
1583
528b2c61 1584void
30abd221 1585copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, String strConnection, HttpRequest * request, HttpRequest * orig_request, HttpHeader * hdr_out, int we_do_ranges, http_state_flags flags)
528b2c61 1586{
30abd221 1587 debugs(11, 5, "httpBuildRequestHeader: " << e->name.buf() << ": " << e->value.buf());
62e76326 1588
528b2c61 1589 if (!httpRequestHdrAllowed(e, &strConnection)) {
30abd221 1590 debugs(11, 2, "'" << e->name.buf() << "' header denied by anonymize_headers configuration");
62e76326 1591 return;
528b2c61 1592 }
62e76326 1593
528b2c61 1594 switch (e->id) {
62e76326 1595
be753325 1596 case HDR_PROXY_AUTHORIZATION:
62e76326 1597 /* Only pass on proxy authentication to peers for which
1598 * authentication forwarding is explicitly enabled
1599 */
1600
1601 if (flags.proxying && orig_request->peer_login &&
abb929f0 1602 (strcmp(orig_request->peer_login, "PASS") == 0 ||
1603 strcmp(orig_request->peer_login, "PROXYPASS") == 0)) {
eede25e7 1604 hdr_out->addEntry(e->clone());
62e76326 1605 }
1606
1607 break;
1608
be753325 1609 case HDR_AUTHORIZATION:
62e76326 1610 /* Pass on WWW authentication */
1611
1612 if (!flags.originpeer) {
eede25e7 1613 hdr_out->addEntry(e->clone());
62e76326 1614 } else {
1615 /* In accelerators, only forward authentication if enabled
1616 * (see also below for proxy->server authentication)
1617 */
1618
abb929f0 1619 if (orig_request->peer_login &&
1620 (strcmp(orig_request->peer_login, "PASS") == 0 ||
1621 strcmp(orig_request->peer_login, "PROXYPASS") == 0)) {
eede25e7 1622 hdr_out->addEntry(e->clone());
62e76326 1623 }
1624 }
1625
1626 break;
1627
be753325 1628 case HDR_HOST:
62e76326 1629 /*
b883b594 1630 * Normally Squid rewrites the Host: header.
1631 * However, there is one case when we don't: If the URL
62e76326 1632 * went through our redirector and the admin configured
1633 * 'redir_rewrites_host' to be off.
1634 */
1635
b883b594 1636 if (request->flags.redirected && !Config.onoff.redir_rewrites_host)
eede25e7 1637 hdr_out->addEntry(e->clone());
b883b594 1638 else {
1639 /* use port# only if not default */
1640
1641 if (orig_request->port == urlDefaultPort(orig_request->protocol)) {
cc192b50 1642 hdr_out->putStr(HDR_HOST, orig_request->GetHost());
b883b594 1643 } else {
1644 httpHeaderPutStrf(hdr_out, HDR_HOST, "%s:%d",
cc192b50 1645 orig_request->GetHost(),
1646 (int) orig_request->port);
b883b594 1647 }
1648 }
62e76326 1649
1650 break;
1651
be753325 1652 case HDR_IF_MODIFIED_SINCE:
62e76326 1653 /* append unless we added our own;
1654 * note: at most one client's ims header can pass through */
b883b594 1655
a9925b40 1656 if (!hdr_out->has(HDR_IF_MODIFIED_SINCE))
eede25e7 1657 hdr_out->addEntry(e->clone());
62e76326 1658
1659 break;
1660
be753325 1661 case HDR_MAX_FORWARDS:
62e76326 1662 if (orig_request->method == METHOD_TRACE) {
eede25e7 1663 const int hops = e->getInt();
62e76326 1664
1665 if (hops > 0)
a9925b40 1666 hdr_out->putInt(HDR_MAX_FORWARDS, hops - 1);
62e76326 1667 }
1668
1669 break;
1670
be753325 1671 case HDR_VIA:
62e76326 1672 /* If Via is disabled then forward any received header as-is */
1673
1674 if (!Config.onoff.via)
eede25e7 1675 hdr_out->addEntry(e->clone());
62e76326 1676
1677 break;
1678
be753325 1679 case HDR_RANGE:
62e76326 1680
be753325 1681 case HDR_IF_RANGE:
62e76326 1682
be753325 1683 case HDR_REQUEST_RANGE:
62e76326 1684 if (!we_do_ranges)
eede25e7 1685 hdr_out->addEntry(e->clone());
62e76326 1686
1687 break;
1688
be753325 1689 case HDR_PROXY_CONNECTION:
62e76326 1690
be753325 1691 case HDR_CONNECTION:
62e76326 1692
be753325 1693 case HDR_X_FORWARDED_FOR:
62e76326 1694
be753325 1695 case HDR_CACHE_CONTROL:
62e76326 1696 /* append these after the loop if needed */
1697 break;
1698
be753325 1699 case HDR_FRONT_END_HTTPS:
62e76326 1700 if (!flags.front_end_https)
eede25e7 1701 hdr_out->addEntry(e->clone());
62e76326 1702
1703 break;
1704
be753325 1705 default:
62e76326 1706 /* pass on all other header fields */
eede25e7 1707 hdr_out->addEntry(e->clone());
528b2c61 1708 }
1709}
1710
e5ee81f0 1711bool
1712HttpStateData::decideIfWeDoRanges (HttpRequest * orig_request)
528b2c61 1713{
e5ee81f0 1714 bool result = true;
62e76326 1715 /* decide if we want to do Ranges ourselves
1716 * and fetch the whole object now)
1717 * We want to handle Ranges ourselves iff
1718 * - we can actually parse client Range specs
1719 * - the specs are expected to be simple enough (e.g. no out-of-order ranges)
1720 * - reply will be cachable
1721 * (If the reply will be uncachable we have to throw it away after
1722 * serving this request, so it is better to forward ranges to
1723 * the server and fetch only the requested content)
1724 */
1725
1726 if (NULL == orig_request->range || !orig_request->flags.cachable
1727 || orig_request->range->offsetLimitExceeded())
e5ee81f0 1728 result = false;
62e76326 1729
bf8fe701 1730 debugs(11, 8, "decideIfWeDoRanges: range specs: " <<
1731 orig_request->range << ", cachable: " <<
1732 orig_request->flags.cachable << "; we_do_ranges: " << result);
62e76326 1733
1734 return result;
528b2c61 1735}
1736
62e76326 1737/* build request prefix and append it to a given MemBuf;
99edd1c3 1738 * return the length of the prefix */
9bc73deb 1739mb_size_t
e5ee81f0 1740HttpStateData::buildRequestPrefix(HttpRequest * request,
1741 HttpRequest * orig_request,
1742 StoreEntry * entry,
1743 MemBuf * mb,
1744 http_state_flags flags)
99edd1c3 1745{
1746 const int offset = mb->size;
450e0c10 1747 HttpVersion httpver(1, 0);
2fe7eff9 1748 mb->Printf("%s %s HTTP/%d.%d\r\n",
60745f24 1749 RequestMethodStr(request->method),
30abd221 1750 request->urlpath.size() ? request->urlpath.buf() : "/",
2fe7eff9 1751 httpver.major,httpver.minor);
99edd1c3 1752 /* build and pack headers */
1753 {
75faaa7a 1754 HttpHeader hdr(hoRequest);
62e76326 1755 Packer p;
1756 httpBuildRequestHeader(request, orig_request, entry, &hdr, flags);
1757 packerToMemInit(&p, mb);
a9925b40 1758 hdr.packInto(&p);
519e0948 1759 hdr.clean();
62e76326 1760 packerClean(&p);
9d9d144b 1761 }
99edd1c3 1762 /* append header terminator */
2fe7eff9 1763 mb->append(crlf, 2);
99edd1c3 1764 return mb->size - offset;
6bf8443a 1765}
62e76326 1766
090089c4 1767/* This will be called when connect completes. Write request. */
5f8252d2 1768bool
2bb867b5 1769HttpStateData::sendRequest()
090089c4 1770{
99edd1c3 1771 MemBuf mb;
090089c4 1772
bf8fe701 1773 debugs(11, 5, "httpSendRequest: FD " << fd << ", request " << request << ", this " << this << ".");
dc56a9b1 1774 typedef CommCbMemFunT<HttpStateData, CommTimeoutCbParams> TimeoutDialer;
1775 AsyncCall::Pointer timeoutCall = asyncCall(11, 5, "HttpStateData::httpTimeout",
1776 TimeoutDialer(this,&HttpStateData::httpTimeout));
1777 commSetTimeout(fd, Config.Timeout.lifetime, timeoutCall);
2bb867b5 1778 flags.do_next_read = 1;
5f8252d2 1779 maybeReadVirginBody();
1780
1781 if (orig_request->body_pipe != NULL) {
123ec4de 1782 if (!startRequestBodyFlow()) // register to receive body data
5f8252d2 1783 return false;
dc56a9b1 1784 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
1785 Dialer dialer(this, &HttpStateData::sentRequestBody);
1786 requestSender = asyncCall(11,5, "HttpStateData::sentRequestBody", dialer);
5f8252d2 1787 } else {
1788 assert(!requestBodySource);
dc56a9b1 1789 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
1790 Dialer dialer(this, &HttpStateData::sendComplete);
1791 requestSender = asyncCall(11,5, "HttpStateData::SendComplete", dialer);
5f8252d2 1792 }
54220df8 1793
2bb867b5 1794 if (_peer != NULL) {
1795 if (_peer->options.originserver) {
1796 flags.proxying = 0;
1797 flags.originpeer = 1;
62e76326 1798 } else {
2bb867b5 1799 flags.proxying = 1;
1800 flags.originpeer = 0;
62e76326 1801 }
be753325 1802 } else {
2bb867b5 1803 flags.proxying = 0;
1804 flags.originpeer = 0;
be753325 1805 }
62e76326 1806
efb9218c 1807 /*
99edd1c3 1808 * Is keep-alive okay for all request methods?
efb9218c 1809 */
efd900cb 1810 if (!Config.onoff.server_pconns)
2bb867b5 1811 flags.keepalive = 0;
1812 else if (_peer == NULL)
1813 flags.keepalive = 1;
1814 else if (_peer->stats.n_keepalives_sent < 10)
1815 flags.keepalive = 1;
1816 else if ((double) _peer->stats.n_keepalives_recv /
1817 (double) _peer->stats.n_keepalives_sent > 0.50)
1818 flags.keepalive = 1;
1819
1820 if (_peer) {
1821 if (neighborType(_peer, request) == PEER_SIBLING &&
1822 !_peer->options.allow_miss)
1823 flags.only_if_cached = 1;
1824
1825 flags.front_end_https = _peer->front_end_https;
a7ad6e4e 1826 }
62e76326 1827
2fe7eff9 1828 mb.init();
e5ee81f0 1829 buildRequestPrefix(request, orig_request, entry, &mb, flags);
bf8fe701 1830 debugs(11, 6, "httpSendRequest: FD " << fd << ":\n" << mb.buf);
dc56a9b1 1831 comm_write_mbuf(fd, &mb, requestSender);
5f8252d2 1832
1833 return true;
090089c4 1834}
b6a2f15e 1835
910169e5 1836void
b6b6f466 1837httpStart(FwdState *fwd)
603a02fd 1838{
60745f24 1839 debugs(11, 3, "httpStart: \"" << RequestMethodStr(fwd->request->method) << " " << fwd->entry->url() << "\"" );
a3d50c30 1840 HttpStateData *httpState = new HttpStateData(fwd);
62e76326 1841
5f8252d2 1842 if (!httpState->sendRequest()) {
bf8fe701 1843 debugs(11, 3, "httpStart: aborted");
5f8252d2 1844 delete httpState;
1845 return;
1846 }
62e76326 1847
5f8252d2 1848 statCounter.server.all.requests++;
83704487 1849 statCounter.server.http.requests++;
62e76326 1850
b6a2f15e 1851 /*
1852 * We used to set the read timeout here, but not any more.
1853 * Now its set in httpSendComplete() after the full request,
1854 * including request body, has been written to the server.
1855 */
090089c4 1856}
1857
2bb867b5 1858void
5f8252d2 1859HttpStateData::doneSendingRequestBody()
2bb867b5 1860{
4fb35c3c 1861 ACLChecklist ch;
5f8252d2 1862 debugs(11,5, HERE << "doneSendingRequestBody: FD " << fd);
6dd9f4bd 1863 ch.request = HTTPMSGLOCK(request);
506768d9 1864
1865 if (Config.accessList.brokenPosts)
1866 ch.accessList = cbdataReference(Config.accessList.brokenPosts);
62e76326 1867
108d65b2 1868 /* cbdataReferenceDone() happens in either fastCheck() or ~ACLCheckList */
1869
94439e4e 1870 if (!Config.accessList.brokenPosts) {
bf8fe701 1871 debugs(11, 5, "doneSendingRequestBody: No brokenPosts list");
dc56a9b1 1872 CommIoCbParams io(NULL);
1873 io.fd=fd;
1874 io.flag=COMM_OK;
1875 sendComplete(io);
b448c119 1876 } else if (!ch.fastCheck()) {
bf8fe701 1877 debugs(11, 5, "doneSendingRequestBody: didn't match brokenPosts");
dc56a9b1 1878 CommIoCbParams io(NULL);
1879 io.fd=fd;
1880 io.flag=COMM_OK;
1881 sendComplete(io);
94439e4e 1882 } else {
bf8fe701 1883 debugs(11, 2, "doneSendingRequestBody: matched brokenPosts");
dc56a9b1 1884 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
1885 Dialer dialer(this, &HttpStateData::sendComplete);
1886 AsyncCall::Pointer call= asyncCall(11,5, "HttpStateData::SendComplete", dialer);
1887 comm_write(fd, "\r\n", 2, call);
54220df8 1888 }
94439e4e 1889}
1890
5f8252d2 1891// more origin request body data is available
2bb867b5 1892void
5f8252d2 1893HttpStateData::handleMoreRequestBodyAvailable()
2bb867b5 1894{
2bb867b5 1895 if (eof || fd < 0) {
5f8252d2 1896 // XXX: we should check this condition in other callbacks then!
1897 // TODO: Check whether this can actually happen: We should unsubscribe
1898 // as a body consumer when the above condition(s) are detected.
2bb867b5 1899 debugs(11, 1, HERE << "Transaction aborted while reading HTTP body");
2bb867b5 1900 return;
1901 }
62e76326 1902
5f8252d2 1903 assert(requestBodySource != NULL);
fc68f6b1 1904
5f8252d2 1905 if (requestBodySource->buf().hasContent()) {
1906 // XXX: why does not this trigger a debug message on every request?
fc68f6b1 1907
2bb867b5 1908 if (flags.headers_parsed && !flags.abuse_detected) {
1909 flags.abuse_detected = 1;
cc192b50 1910 debugs(11, 1, "http handleMoreRequestBodyAvailable: Likely proxy abuse detected '" << orig_request->client_addr << "' -> '" << entry->url() << "'" );
21b92762 1911
585ab260 1912 if (virginReply()->sline.status == HTTP_INVALID_HEADER) {
2bb867b5 1913 comm_close(fd);
21b92762 1914 return;
1915 }
1916 }
b6a2f15e 1917 }
5f8252d2 1918
1919 HttpStateData::handleMoreRequestBodyAvailable();
376bb137 1920}
1921
5f8252d2 1922// premature end of the request body
2bb867b5 1923void
5f8252d2 1924HttpStateData::handleRequestBodyProducerAborted()
376bb137 1925{
5f8252d2 1926 ServerStateData::handleRequestBodyProducerAborted();
1927 // XXX: SendComplete(COMM_ERR_CLOSING) does little. Is it enough?
dc56a9b1 1928 CommIoCbParams io(NULL);
1929 io.fd=fd;
1930 io.flag=COMM_ERR_CLOSING;
1931 sendComplete(io);
2bb867b5 1932}
1933
5f8252d2 1934// called when we wrote request headers(!) or a part of the body
2bb867b5 1935void
dc56a9b1 1936HttpStateData::sentRequestBody(const CommIoCbParams &io)
2bb867b5 1937{
dc56a9b1 1938 if (io.size > 0)
1939 kb_incr(&statCounter.server.http.kbytes_out, io.size);
fc68f6b1 1940
dc56a9b1 1941 ServerStateData::sentRequestBody(io);
5f8252d2 1942}
3b299123 1943
5f8252d2 1944// Quickly abort the transaction
1945// TODO: destruction should be sufficient as the destructor should cleanup,
1946// including canceling close handlers
1947void
1948HttpStateData::abortTransaction(const char *reason)
1949{
1950 debugs(11,5, HERE << "aborting transaction for " << reason <<
1951 "; FD " << fd << ", this " << this);
fc68f6b1 1952
3e8c047e 1953 if (fd >= 0) {
62e76326 1954 comm_close(fd);
3e8c047e 1955 return;
c23f0c74 1956 }
3e8c047e 1957
1958 fwd->handleUnregisteredServerEnd();
dc56a9b1 1959 deleteThis("HttpStateData::abortTransaction");
54220df8 1960}
ccf44862 1961
1962void
450e0c10 1963httpBuildVersion(HttpVersion * version, unsigned int major, unsigned int minor)
110eb4e5 1964{
1965 version->major = major;
1966 version->minor = minor;
ccf44862 1967}
2afaba07 1968
7c4e4e7f 1969HttpRequest *
1970HttpStateData::originalRequest()
2afaba07 1971{
7c4e4e7f 1972 return orig_request;
2afaba07 1973}