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