2 * Copyright (C) 1996-2016 The Squid Software Foundation and contributors
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
9 /* DEBUG: section 11 Hypertext Transfer Protocol (HTTP) */
12 * Anonymizing patch by lutz@as-node.jena.thur.de
13 * have a look into http-anon.c to get more informations.
17 #include "acl/FilledChecklist.h"
18 #include "base/AsyncJobCalls.h"
19 #include "base/TextException.h"
21 #include "CachePeer.h"
22 #include "client_side.h"
23 #include "comm/Connection.h"
24 #include "comm/Read.h"
25 #include "comm/Write.h"
27 #include "err_detail_type.h"
28 #include "errorpage.h"
33 #include "http/one/ResponseParser.h"
34 #include "http/one/TeChunkedParser.h"
35 #include "http/Stream.h"
36 #include "HttpControlMsg.h"
37 #include "HttpHdrCc.h"
38 #include "HttpHdrContRange.h"
39 #include "HttpHdrSc.h"
40 #include "HttpHdrScTarget.h"
41 #include "HttpHeaderTools.h"
42 #include "HttpReply.h"
43 #include "HttpRequest.h"
44 #include "HttpStateFlags.h"
45 #include "log/access_log.h"
47 #include "MemObject.h"
48 #include "neighbors.h"
49 #include "peer_proxy_negotiate_auth.h"
50 #include "profiler/Profiler.h"
52 #include "RefreshPattern.h"
54 #include "SquidConfig.h"
55 #include "SquidTime.h"
56 #include "StatCounters.h"
64 #include "auth/UserRequest.h"
67 #include "DelayPools.h"
70 #define SQUID_ENTER_THROWING_CODE() try {
71 #define SQUID_EXIT_THROWING_CODE(status) \
74 catch (const std::exception &e) { \
75 debugs (11, 1, "Exception error:" << e.what()); \
79 CBDATA_CLASS_INIT(HttpStateData
);
81 static const char *const crlf
= "\r\n";
83 static void httpMaybeRemovePublic(StoreEntry
*, Http::StatusCode
);
84 static void copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry
*e
, const String strConnection
, const HttpRequest
* request
,
85 HttpHeader
* hdr_out
, const int we_do_ranges
, const HttpStateFlags
&);
86 //Declared in HttpHeaderTools.cc
87 void httpHdrAdd(HttpHeader
*heads
, HttpRequest
*request
, const AccessLogEntryPointer
&al
, HeaderWithAclList
&headers_add
);
89 HttpStateData::HttpStateData(FwdState
*theFwdState
) :
90 AsyncJob("HttpStateData"),
93 httpChunkDecoder(NULL
),
97 debugs(11,5,HERE
<< "HttpStateData " << this << " created");
98 ignoreCacheControl
= false;
99 surrogateNoStore
= false;
100 serverConnection
= fwd
->serverConnection();
102 // reset peer response time stats for %<pt
103 request
->hier
.peer_http_request_sent
.tv_sec
= 0;
104 request
->hier
.peer_http_request_sent
.tv_usec
= 0;
106 if (fwd
->serverConnection() != NULL
)
107 _peer
= cbdataReference(fwd
->serverConnection()->getPeer()); /* might be NULL */
110 request
->flags
.proxying
= true;
112 * This NEIGHBOR_PROXY_ONLY check probably shouldn't be here.
113 * We might end up getting the object from somewhere else if,
114 * for example, the request to this neighbor fails.
116 if (_peer
->options
.proxy_only
)
117 entry
->releaseRequest();
120 entry
->setNoDelay(_peer
->options
.no_delay
);
125 * register the handler to free HTTP state data when the FD closes
127 typedef CommCbMemFunT
<HttpStateData
, CommCloseCbParams
> Dialer
;
128 closeHandler
= JobCallback(9, 5, Dialer
, this, HttpStateData::httpStateConnClosed
);
129 comm_add_close_handler(serverConnection
->fd
, closeHandler
);
132 HttpStateData::~HttpStateData()
135 * don't forget that ~Client() gets called automatically
138 if (httpChunkDecoder
)
139 delete httpChunkDecoder
;
141 cbdataReferenceDone(_peer
);
143 debugs(11,5, HERE
<< "HttpStateData " << this << " destroyed; " << serverConnection
);
146 const Comm::ConnectionPointer
&
147 HttpStateData::dataConnection() const
149 return serverConnection
;
153 HttpStateData::httpStateConnClosed(const CommCloseCbParams
¶ms
)
155 debugs(11, 5, "httpStateFree: FD " << params
.fd
<< ", httpState=" << params
.data
);
156 doneWithFwd
= "httpStateConnClosed()"; // assume FwdState is monitoring too
157 mustStop("HttpStateData::httpStateConnClosed");
161 HttpStateData::httpTimeout(const CommTimeoutCbParams
&)
163 debugs(11, 4, serverConnection
<< ": '" << entry
->url() << "'");
165 if (entry
->store_status
== STORE_PENDING
) {
166 fwd
->fail(new ErrorState(ERR_READ_TIMEOUT
, Http::scGatewayTimeout
, fwd
->request
));
170 mustStop("HttpStateData::httpTimeout");
173 /// Remove an existing public store entry if the incoming response (to be
174 /// stored in a currently private entry) is going to invalidate it.
176 httpMaybeRemovePublic(StoreEntry
* e
, Http::StatusCode status
)
182 // If the incoming response already goes into a public entry, then there is
183 // nothing to remove. This protects ready-for-collapsing entries as well.
184 if (!EBIT_TEST(e
->flags
, KEY_PRIVATE
))
191 case Http::scNonAuthoritativeInformation
:
193 case Http::scMultipleChoices
:
195 case Http::scMovedPermanently
:
201 case Http::scNotFound
:
206 case Http::scForbidden
:
208 case Http::scMethodNotAllowed
:
215 case Http::scUnauthorized
:
225 * Any 2xx response should eject previously cached entities...
228 if (status
>= 200 && status
< 300)
236 if (!remove
&& !forbidden
)
241 if (e
->mem_obj
->request
)
242 pe
= storeGetPublicByRequest(e
->mem_obj
->request
);
244 pe
= storeGetPublic(e
->mem_obj
->storeId(), e
->mem_obj
->method
);
249 neighborsHtcpClear(e
, NULL
, e
->mem_obj
->request
, e
->mem_obj
->method
, HTCP_CLR_INVALIDATION
);
255 * Also remove any cached HEAD response in case the object has
258 if (e
->mem_obj
->request
)
259 pe
= storeGetPublicByRequestMethod(e
->mem_obj
->request
, Http::METHOD_HEAD
);
261 pe
= storeGetPublic(e
->mem_obj
->storeId(), Http::METHOD_HEAD
);
266 neighborsHtcpClear(e
, NULL
, e
->mem_obj
->request
, HttpRequestMethod(Http::METHOD_HEAD
), HTCP_CLR_INVALIDATION
);
273 HttpStateData::processSurrogateControl(HttpReply
*reply
)
275 if (request
->flags
.accelerated
&& reply
->surrogate_control
) {
276 HttpHdrScTarget
*sctusable
= reply
->surrogate_control
->getMergedTarget(Config
.Accel
.surrogate_id
);
279 if (sctusable
->noStore() ||
280 (Config
.onoff
.surrogate_is_remote
281 && sctusable
->noStoreRemote())) {
282 surrogateNoStore
= true;
283 entry
->makePrivate();
286 /* The HttpHeader logic cannot tell if the header it's parsing is a reply to an
287 * accelerated request or not...
288 * Still, this is an abstraction breach. - RC
290 if (sctusable
->hasMaxAge()) {
291 if (sctusable
->maxAge() < sctusable
->maxStale())
292 reply
->expires
= reply
->date
+ sctusable
->maxAge();
294 reply
->expires
= reply
->date
+ sctusable
->maxStale();
296 /* And update the timestamps */
297 entry
->timestampsSet();
300 /* We ignore cache-control directives as per the Surrogate specification */
301 ignoreCacheControl
= true;
309 HttpStateData::cacheableReply()
311 HttpReply
const *rep
= finalReply();
312 HttpHeader
const *hdr
= &rep
->header
;
314 #if USE_HTTP_VIOLATIONS
316 const RefreshPattern
*R
= NULL
;
318 /* This strange looking define first looks up the refresh pattern
319 * and then checks if the specified flag is set. The main purpose
320 * of this is to simplify the refresh pattern lookup and USE_HTTP_VIOLATIONS
323 #define REFRESH_OVERRIDE(flag) \
324 ((R = (R ? R : refreshLimits(entry->mem_obj->storeId()))) , \
325 (R && R->flags.flag))
327 #define REFRESH_OVERRIDE(flag) 0
330 if (EBIT_TEST(entry
->flags
, RELEASE_REQUEST
)) {
331 debugs(22, 3, "NO because " << *entry
<< " has been released.");
335 // Check for Surrogate/1.0 protocol conditions
336 // NP: reverse-proxy traffic our parent server has instructed us never to cache
337 if (surrogateNoStore
) {
338 debugs(22, 3, HERE
<< "NO because Surrogate-Control:no-store");
342 // RFC 2616: HTTP/1.1 Cache-Control conditions
343 if (!ignoreCacheControl
) {
344 // XXX: check to see if the request headers alone were enough to prevent caching earlier
345 // (ie no-store request header) no need to check those all again here if so.
346 // for now we are not reliably doing that so we waste CPU re-checking request CC
348 // RFC 2616 section 14.9.2 - MUST NOT cache any response with request CC:no-store
349 if (request
&& request
->cache_control
&& request
->cache_control
->noStore() &&
350 !REFRESH_OVERRIDE(ignore_no_store
)) {
351 debugs(22, 3, HERE
<< "NO because client request Cache-Control:no-store");
355 // NP: request CC:no-cache only means cache READ is forbidden. STORE is permitted.
356 if (rep
->cache_control
&& rep
->cache_control
->hasNoCache() && rep
->cache_control
->noCache().size() > 0) {
357 /* TODO: we are allowed to cache when no-cache= has parameters.
358 * Provided we strip away any of the listed headers unless they are revalidated
359 * successfully (ie, must revalidate AND these headers are prohibited on stale replies).
360 * That is a bit tricky for squid right now so we avoid caching entirely.
362 debugs(22, 3, HERE
<< "NO because server reply Cache-Control:no-cache has parameters");
366 // NP: request CC:private is undefined. We ignore.
367 // NP: other request CC flags are limiters on HIT/MISS. We don't care about here.
369 // RFC 2616 section 14.9.2 - MUST NOT cache any response with CC:no-store
370 if (rep
->cache_control
&& rep
->cache_control
->noStore() &&
371 !REFRESH_OVERRIDE(ignore_no_store
)) {
372 debugs(22, 3, HERE
<< "NO because server reply Cache-Control:no-store");
376 // RFC 2616 section 14.9.1 - MUST NOT cache any response with CC:private in a shared cache like Squid.
377 // CC:private overrides CC:public when both are present in a response.
378 // TODO: add a shared/private cache configuration possibility.
379 if (rep
->cache_control
&&
380 rep
->cache_control
->hasPrivate() &&
381 !REFRESH_OVERRIDE(ignore_private
)) {
382 /* TODO: we are allowed to cache when private= has parameters.
383 * Provided we strip away any of the listed headers unless they are revalidated
384 * successfully (ie, must revalidate AND these headers are prohibited on stale replies).
385 * That is a bit tricky for squid right now so we avoid caching entirely.
387 debugs(22, 3, HERE
<< "NO because server reply Cache-Control:private");
392 // RFC 2068, sec 14.9.4 - MUST NOT cache any response with Authentication UNLESS certain CC controls are present
393 // allow HTTP violations to IGNORE those controls (ie re-block caching Auth)
394 if (request
&& (request
->flags
.auth
|| request
->flags
.authSent
)) {
395 if (!rep
->cache_control
) {
396 debugs(22, 3, HERE
<< "NO because Authenticated and server reply missing Cache-Control");
400 if (ignoreCacheControl
) {
401 debugs(22, 3, HERE
<< "NO because Authenticated and ignoring Cache-Control");
405 bool mayStore
= false;
406 // HTTPbis pt6 section 3.2: a response CC:public is present
407 if (rep
->cache_control
->Public()) {
408 debugs(22, 3, HERE
<< "Authenticated but server reply Cache-Control:public");
411 // HTTPbis pt6 section 3.2: a response CC:must-revalidate is present
412 } else if (rep
->cache_control
->mustRevalidate()) {
413 debugs(22, 3, HERE
<< "Authenticated but server reply Cache-Control:must-revalidate");
416 #if USE_HTTP_VIOLATIONS
417 // NP: given the must-revalidate exception we should also be able to exempt no-cache.
418 // HTTPbis WG verdict on this is that it is omitted from the spec due to being 'unexpected' by
419 // some. The caching+revalidate is not exactly unsafe though with Squids interpretation of no-cache
420 // (without parameters) as equivalent to must-revalidate in the reply.
421 } else if (rep
->cache_control
->hasNoCache() && rep
->cache_control
->noCache().size() == 0) {
422 debugs(22, 3, HERE
<< "Authenticated but server reply Cache-Control:no-cache (equivalent to must-revalidate)");
426 // HTTPbis pt6 section 3.2: a response CC:s-maxage is present
427 } else if (rep
->cache_control
->sMaxAge()) {
428 debugs(22, 3, HERE
<< "Authenticated but server reply Cache-Control:s-maxage");
433 debugs(22, 3, HERE
<< "NO because Authenticated transaction");
437 // NP: response CC:no-cache is equivalent to CC:must-revalidate,max-age=0. We MAY cache, and do so.
438 // NP: other request CC flags are limiters on HIT/MISS/REFRESH. We don't care about here.
441 /* HACK: The "multipart/x-mixed-replace" content type is used for
442 * continuous push replies. These are generally dynamic and
443 * probably should not be cachable
445 if ((v
= hdr
->getStr(Http::HdrType::CONTENT_TYPE
)))
446 if (!strncasecmp(v
, "multipart/x-mixed-replace", 25)) {
447 debugs(22, 3, HERE
<< "NO because Content-Type:multipart/x-mixed-replace");
451 switch (rep
->sline
.status()) {
452 /* Responses that are cacheable */
456 case Http::scNonAuthoritativeInformation
:
458 case Http::scMultipleChoices
:
460 case Http::scMovedPermanently
:
461 case Http::scPermanentRedirect
:
465 * Don't cache objects that need to be refreshed on next request,
466 * unless we know how to refresh it.
469 if (!refreshIsCachable(entry
) && !REFRESH_OVERRIDE(store_stale
)) {
470 debugs(22, 3, "NO because refreshIsCachable() returned non-cacheable..");
473 debugs(22, 3, HERE
<< "YES because HTTP status " << rep
->sline
.status());
479 /* Responses that only are cacheable if the server says so */
482 case Http::scTemporaryRedirect
:
483 if (rep
->date
<= 0) {
484 debugs(22, 3, HERE
<< "NO because HTTP status " << rep
->sline
.status() << " and Date missing/invalid");
487 if (rep
->expires
> rep
->date
) {
488 debugs(22, 3, HERE
<< "YES because HTTP status " << rep
->sline
.status() << " and Expires > Date");
491 debugs(22, 3, HERE
<< "NO because HTTP status " << rep
->sline
.status() << " and Expires <= Date");
497 /* Errors can be negatively cached */
499 case Http::scNoContent
:
501 case Http::scUseProxy
:
503 case Http::scBadRequest
:
505 case Http::scForbidden
:
507 case Http::scNotFound
:
509 case Http::scMethodNotAllowed
:
511 case Http::scUriTooLong
:
513 case Http::scInternalServerError
:
515 case Http::scNotImplemented
:
517 case Http::scBadGateway
:
519 case Http::scServiceUnavailable
:
521 case Http::scGatewayTimeout
:
522 case Http::scMisdirectedRequest
:
524 debugs(22, 3, "MAYBE because HTTP status " << rep
->sline
.status());
530 /* Some responses can never be cached */
532 case Http::scPartialContent
: /* Not yet supported */
534 case Http::scSeeOther
:
536 case Http::scNotModified
:
538 case Http::scUnauthorized
:
540 case Http::scProxyAuthenticationRequired
:
542 case Http::scInvalidHeader
: /* Squid header parsing error */
544 case Http::scHeaderTooLarge
:
546 case Http::scPaymentRequired
:
547 case Http::scNotAcceptable
:
548 case Http::scRequestTimeout
:
549 case Http::scConflict
:
550 case Http::scLengthRequired
:
551 case Http::scPreconditionFailed
:
552 case Http::scPayloadTooLarge
:
553 case Http::scUnsupportedMediaType
:
554 case Http::scUnprocessableEntity
:
556 case Http::scFailedDependency
:
557 case Http::scInsufficientStorage
:
558 case Http::scRequestedRangeNotSatisfied
:
559 case Http::scExpectationFailed
:
561 debugs(22, 3, HERE
<< "NO because HTTP status " << rep
->sline
.status());
565 /* RFC 2616 section 6.1.1: an unrecognized response MUST NOT be cached. */
566 debugs (11, 3, HERE
<< "NO because unknown HTTP status code " << rep
->sline
.status());
577 * For Vary, store the relevant request headers as
578 * virtual headers in the reply
579 * Returns false if the variance cannot be stored
582 httpMakeVaryMark(HttpRequest
* request
, HttpReply
const * reply
)
585 const char *pos
= NULL
;
592 vary
= reply
->header
.getList(Http::HdrType::VARY
);
594 while (strListGetItem(&vary
, ',', &item
, &ilen
, &pos
)) {
595 static const SBuf
asterisk("*");
596 SBuf
name(item
, ilen
);
597 if (name
== asterisk
) {
602 strListAdd(&vstr
, name
.c_str(), ',');
603 hdr
= request
->header
.getByName(name
);
604 value
= hdr
.termedBuf();
606 value
= rfc1738_escape_part(value
);
607 vstr
.append("=\"", 2);
609 vstr
.append("\"", 1);
616 #if X_ACCELERATOR_VARY
619 vary
= reply
->header
.getList(Http::HdrType::HDR_X_ACCELERATOR_VARY
);
621 while (strListGetItem(&vary
, ',', &item
, &ilen
, &pos
)) {
622 char *name
= (char *)xmalloc(ilen
+ 1);
623 xstrncpy(name
, item
, ilen
+ 1);
625 strListAdd(&vstr
, name
, ',');
626 hdr
= request
->header
.getByName(name
);
628 value
= hdr
.termedBuf();
631 value
= rfc1738_escape_part(value
);
632 vstr
.append("=\"", 2);
634 vstr
.append("\"", 1);
643 debugs(11, 3, "httpMakeVaryMark: " << vstr
);
644 return vstr
.termedBuf();
648 HttpStateData::keepaliveAccounting(HttpReply
*reply
)
652 ++ _peer
->stats
.n_keepalives_sent
;
654 if (reply
->keep_alive
) {
656 ++ _peer
->stats
.n_keepalives_recv
;
658 if (Config
.onoff
.detect_broken_server_pconns
659 && reply
->bodySize(request
->method
) == -1 && !flags
.chunked
) {
660 debugs(11, DBG_IMPORTANT
, "keepaliveAccounting: Impossible keep-alive header from '" << entry
->url() << "'" );
661 // debugs(11, 2, "GOT HTTP REPLY HDR:\n---------\n" << readBuf->content() << "\n----------" );
662 flags
.keepalive_broken
= true;
668 HttpStateData::checkDateSkew(HttpReply
*reply
)
670 if (reply
->date
> -1 && !_peer
) {
671 int skew
= abs((int)(reply
->date
- squid_curtime
));
674 debugs(11, 3, "" << request
->url
.host() << "'s clock is skewed by " << skew
<< " seconds!");
679 * This creates the error page itself.. its likely
680 * that the forward ported reply header max size patch
681 * generates non http conformant error pages - in which
682 * case the errors where should be 'BAD_GATEWAY' etc
685 HttpStateData::processReplyHeader()
687 /** Creates a blank header. If this routine is made incremental, this will not do */
689 /* NP: all exit points to this function MUST call ctx_exit(ctx) */
690 Ctx ctx
= ctx_enter(entry
->mem_obj
->urlXXX());
692 debugs(11, 3, "processReplyHeader: key '" << entry
->getMD5Text() << "'");
694 assert(!flags
.headers_parsed
);
696 if (!inBuf
.length()) {
701 /* Attempt to parse the first line; this will define where the protocol, status, reason-phrase and header begin */
704 hp
= new Http1::ResponseParser
;
706 bool parsedOk
= hp
->parse(inBuf
);
708 // sync the buffers after parsing.
709 inBuf
= hp
->remaining();
711 if (hp
->needsMoreData()) {
712 if (eof
) { // no more data coming
713 /* Bug 2879: Replies may terminate with \r\n then EOF instead of \r\n\r\n.
714 * We also may receive truncated responses.
715 * Ensure here that we have at minimum two \r\n when EOF is seen.
717 inBuf
.append("\r\n\r\n", 4);
719 parsedOk
= hp
->parse(inBuf
);
720 // sync the buffers after parsing.
721 inBuf
= hp
->remaining();
723 debugs(33, 5, "Incomplete response, waiting for end of response headers");
730 // unrecoverable parsing error
731 // TODO: Use Raw! XXX: inBuf no longer has the [beginning of the] malformed header.
732 debugs(11, 3, "Non-HTTP-compliant header:\n---------\n" << inBuf
<< "\n----------");
733 flags
.headers_parsed
= true;
734 HttpReply
*newrep
= new HttpReply
;
735 newrep
->sline
.set(Http::ProtocolVersion(), hp
->parseStatusCode
);
736 setVirginReply(newrep
);
742 /* We know the whole response is in parser now */
743 debugs(11, 2, "HTTP Server " << serverConnection
);
744 debugs(11, 2, "HTTP Server RESPONSE:\n---------\n" <<
745 hp
->messageProtocol() << " " << hp
->messageStatus() << " " << hp
->reasonPhrase() << "\n" <<
749 // reset payload tracking to begin after message headers
750 payloadSeen
= inBuf
.length();
752 HttpReply
*newrep
= new HttpReply
;
753 // XXX: RFC 7230 indicates we MAY ignore the reason phrase,
754 // and use an empty string on unknown status.
755 // We do that now to avoid performance regression from using SBuf::c_str()
756 newrep
->sline
.set(Http::ProtocolVersion(1,1), hp
->messageStatus() /* , hp->reasonPhrase() */);
757 newrep
->sline
.protocol
= newrep
->sline
.version
.protocol
= hp
->messageProtocol().protocol
;
758 newrep
->sline
.version
.major
= hp
->messageProtocol().major
;
759 newrep
->sline
.version
.minor
= hp
->messageProtocol().minor
;
762 if (!newrep
->parseHeader(*hp
)) {
763 // XXX: when Http::ProtocolVersion is a function, remove this hack. just set with messageProtocol()
764 newrep
->sline
.set(Http::ProtocolVersion(), Http::scInvalidHeader
);
765 newrep
->sline
.version
.protocol
= hp
->messageProtocol().protocol
;
766 newrep
->sline
.version
.major
= hp
->messageProtocol().major
;
767 newrep
->sline
.version
.minor
= hp
->messageProtocol().minor
;
768 debugs(11, 2, "error parsing response headers mime block");
771 // done with Parser, now process using the HttpReply
774 newrep
->sources
|= request
->url
.getScheme() == AnyP::PROTO_HTTPS
? HttpMsg::srcHttps
: HttpMsg::srcHttp
;
776 newrep
->removeStaleWarnings();
778 if (newrep
->sline
.protocol
== AnyP::PROTO_HTTP
&& newrep
->sline
.status() >= 100 && newrep
->sline
.status() < 200) {
784 flags
.chunked
= false;
785 if (newrep
->sline
.protocol
== AnyP::PROTO_HTTP
&& newrep
->header
.chunked()) {
786 flags
.chunked
= true;
787 httpChunkDecoder
= new Http1::TeChunkedParser
;
790 if (!peerSupportsConnectionPinning())
791 request
->flags
.connectionAuthDisabled
= true;
793 HttpReply
*vrep
= setVirginReply(newrep
);
794 flags
.headers_parsed
= true;
796 keepaliveAccounting(vrep
);
800 processSurrogateControl (vrep
);
802 request
->hier
.peer_reply_status
= newrep
->sline
.status();
807 /// ignore or start forwarding the 1xx response (a.k.a., control message)
809 HttpStateData::handle1xx(HttpReply
*reply
)
811 HttpReply::Pointer
msg(reply
); // will destroy reply if unused
813 // one 1xx at a time: we must not be called while waiting for previous 1xx
814 Must(!flags
.handling1xx
);
815 flags
.handling1xx
= true;
817 if (!request
->canHandle1xx() || request
->forcedBodyContinuation
) {
818 debugs(11, 2, "ignoring 1xx because it is " << (request
->forcedBodyContinuation
? "already sent" : "not supported by client"));
823 #if USE_HTTP_VIOLATIONS
824 // check whether the 1xx response forwarding is allowed by squid.conf
825 if (Config
.accessList
.reply
) {
826 ACLFilledChecklist
ch(Config
.accessList
.reply
, originalRequest(), NULL
);
828 HTTPMSGLOCK(ch
.reply
);
829 if (ch
.fastCheck() != ACCESS_ALLOWED
) { // TODO: support slow lookups?
830 debugs(11, 3, HERE
<< "ignoring denied 1xx");
835 #endif // USE_HTTP_VIOLATIONS
837 debugs(11, 2, HERE
<< "forwarding 1xx to client");
839 // the Sink will use this to call us back after writing 1xx to the client
840 typedef NullaryMemFunT
<HttpStateData
> CbDialer
;
841 const AsyncCall::Pointer cb
= JobCallback(11, 3, CbDialer
, this,
842 HttpStateData::proceedAfter1xx
);
843 CallJobHere1(11, 4, request
->clientConnectionManager
, ConnStateData
,
844 ConnStateData::sendControlMsg
, HttpControlMsg(msg
, cb
));
845 // If the call is not fired, then the Sink is gone, and HttpStateData
846 // will terminate due to an aborted store entry or another similar error.
847 // If we get stuck, it is not handle1xx fault if we could get stuck
848 // for similar reasons without a 1xx response.
851 /// restores state and resumes processing after 1xx is ignored or forwarded
853 HttpStateData::proceedAfter1xx()
855 Must(flags
.handling1xx
);
856 debugs(11, 2, "continuing with " << payloadSeen
<< " bytes in buffer after 1xx");
857 CallJobHere(11, 3, this, HttpStateData
, HttpStateData::processReply
);
861 * returns true if the peer can support connection pinning
863 bool HttpStateData::peerSupportsConnectionPinning() const
865 const HttpReply
*rep
= entry
->mem_obj
->getReply();
866 const HttpHeader
*hdr
= &rep
->header
;
873 /*If this peer does not support connection pinning (authenticated
874 connections) return false
876 if (!_peer
->connection_auth
)
879 /*The peer supports connection pinning and the http reply status
880 is not unauthorized, so the related connection can be pinned
882 if (rep
->sline
.status() != Http::scUnauthorized
)
885 /*The server respond with Http::scUnauthorized and the peer configured
886 with "connection-auth=on" we know that the peer supports pinned
889 if (_peer
->connection_auth
== 1)
892 /*At this point peer has configured with "connection-auth=auto"
893 parameter so we need some extra checks to decide if we are going
894 to allow pinned connections or not
897 /*if the peer configured with originserver just allow connection
898 pinning (squid 2.6 behaviour)
900 if (_peer
->options
.originserver
)
903 /*if the connections it is already pinned it is OK*/
904 if (request
->flags
.pinned
)
907 /*Allow pinned connections only if the Proxy-support header exists in
908 reply and has in its list the "Session-Based-Authentication"
909 which means that the peer supports connection pinning.
911 if (!hdr
->has(Http::HdrType::PROXY_SUPPORT
))
914 header
= hdr
->getStrOrList(Http::HdrType::PROXY_SUPPORT
);
915 /* XXX This ought to be done in a case-insensitive manner */
916 rc
= (strstr(header
.termedBuf(), "Session-Based-Authentication") != NULL
);
921 // Called when we parsed (and possibly adapted) the headers but
922 // had not starting storing (a.k.a., sending) the body yet.
924 HttpStateData::haveParsedReplyHeaders()
926 Client::haveParsedReplyHeaders();
928 Ctx ctx
= ctx_enter(entry
->mem_obj
->urlXXX());
929 HttpReply
*rep
= finalReply();
931 entry
->timestampsSet();
933 /* Check if object is cacheable or not based on reply code */
934 debugs(11, 3, "HTTP CODE: " << rep
->sline
.status());
936 if (neighbors_do_private_keys
)
937 httpMaybeRemovePublic(entry
, rep
->sline
.status());
939 bool varyFailure
= false;
940 if (rep
->header
.has(Http::HdrType::VARY
)
941 #if X_ACCELERATOR_VARY
942 || rep
->header
.has(Http::HdrType::HDR_X_ACCELERATOR_VARY
)
945 const char *vary
= httpMakeVaryMark(request
, rep
);
948 entry
->makePrivate();
949 if (!fwd
->reforwardableStatus(rep
->sline
.status()))
950 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
953 entry
->mem_obj
->vary_headers
= xstrdup(vary
);
959 * If its not a reply that we will re-forward, then
960 * allow the client to get it.
962 if (!fwd
->reforwardableStatus(rep
->sline
.status()))
963 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
965 switch (cacheableReply()) {
972 entry
->makePrivate();
977 #if USE_HTTP_VIOLATIONS
978 if (Config
.negativeTtl
> 0)
979 entry
->cacheNegatively();
982 entry
->makePrivate();
991 if (!ignoreCacheControl
) {
992 if (rep
->cache_control
) {
993 // We are required to revalidate on many conditions.
994 // For security reasons we do so even if storage was caused by refresh_pattern ignore-* option
996 // CC:must-revalidate or CC:proxy-revalidate
997 const bool ccMustRevalidate
= (rep
->cache_control
->proxyRevalidate() || rep
->cache_control
->mustRevalidate());
999 // CC:no-cache (only if there are no parameters)
1000 const bool ccNoCacheNoParams
= (rep
->cache_control
->hasNoCache() && rep
->cache_control
->noCache().size()==0);
1003 const bool ccSMaxAge
= rep
->cache_control
->hasSMaxAge();
1005 // CC:private (yes, these can sometimes be stored)
1006 const bool ccPrivate
= rep
->cache_control
->hasPrivate();
1008 if (ccMustRevalidate
|| ccNoCacheNoParams
|| ccSMaxAge
|| ccPrivate
)
1009 EBIT_SET(entry
->flags
, ENTRY_REVALIDATE
);
1011 #if USE_HTTP_VIOLATIONS // response header Pragma::no-cache is undefined in HTTP
1013 // Expensive calculation. So only do it IF the CC: header is not present.
1015 /* HACK: Pragma: no-cache in _replies_ is not documented in HTTP,
1016 * but servers like "Active Imaging Webcast/2.0" sure do use it */
1017 if (rep
->header
.has(Http::HdrType::PRAGMA
) &&
1018 rep
->header
.hasListMember(Http::HdrType::PRAGMA
,"no-cache",','))
1019 EBIT_SET(entry
->flags
, ENTRY_REVALIDATE
);
1025 headersLog(1, 0, request
->method
, rep
);
1032 HttpStateData::ConnectionStatus
1033 HttpStateData::statusIfComplete() const
1035 const HttpReply
*rep
= virginReply();
1037 * If the reply wants to close the connection, it takes precedence */
1039 if (httpHeaderHasConnDir(&rep
->header
, "close"))
1040 return COMPLETE_NONPERSISTENT_MSG
;
1043 * If we didn't send a keep-alive request header, then this
1044 * can not be a persistent connection.
1046 if (!flags
.keepalive
)
1047 return COMPLETE_NONPERSISTENT_MSG
;
1050 * If we haven't sent the whole request then this can not be a persistent
1053 if (!flags
.request_sent
) {
1054 debugs(11, 2, "Request not yet fully sent " << request
->method
<< ' ' << entry
->url());
1055 return COMPLETE_NONPERSISTENT_MSG
;
1059 * What does the reply have to say about keep-alive?
1063 * If the origin server (HTTP/1.0) does not send a keep-alive
1064 * header, but keeps the connection open anyway, what happens?
1065 * We'll return here and http.c waits for an EOF before changing
1066 * store_status to STORE_OK. Combine this with ENTRY_FWD_HDR_WAIT
1067 * and an error status code, and we might have to wait until
1068 * the server times out the socket.
1070 if (!rep
->keep_alive
)
1071 return COMPLETE_NONPERSISTENT_MSG
;
1073 return COMPLETE_PERSISTENT_MSG
;
1076 HttpStateData::ConnectionStatus
1077 HttpStateData::persistentConnStatus() const
1079 debugs(11, 3, HERE
<< serverConnection
<< " eof=" << eof
);
1080 if (eof
) // already reached EOF
1081 return COMPLETE_NONPERSISTENT_MSG
;
1083 /* If server fd is closing (but we have not been notified yet), stop Comm
1084 I/O to avoid assertions. TODO: Change Comm API to handle callers that
1085 want more I/O after async closing (usually initiated by others). */
1086 // XXX: add canReceive or s/canSend/canTalkToServer/
1087 if (!Comm::IsConnOpen(serverConnection
))
1088 return COMPLETE_NONPERSISTENT_MSG
;
1091 * In chunked response we do not know the content length but we are absolutely
1092 * sure about the end of response, so we are calling the statusIfComplete to
1093 * decide if we can be persistant
1095 if (lastChunk
&& flags
.chunked
)
1096 return statusIfComplete();
1098 const HttpReply
*vrep
= virginReply();
1099 debugs(11, 5, "persistentConnStatus: content_length=" << vrep
->content_length
);
1101 const int64_t clen
= vrep
->bodySize(request
->method
);
1103 debugs(11, 5, "persistentConnStatus: clen=" << clen
);
1105 /* If the body size is unknown we must wait for EOF */
1107 return INCOMPLETE_MSG
;
1110 * If the body size is known, we must wait until we've gotten all of it. */
1112 debugs(11,5, "payloadSeen=" << payloadSeen
<< " content_length=" << vrep
->content_length
);
1114 if (payloadSeen
< vrep
->content_length
)
1115 return INCOMPLETE_MSG
;
1117 if (payloadTruncated
> 0) // already read more than needed
1118 return COMPLETE_NONPERSISTENT_MSG
; // disable pconns
1122 * If there is no message body or we got it all, we can be persistent */
1123 return statusIfComplete();
1128 readDelayed(void *context
, CommRead
const &)
1130 HttpStateData
*state
= static_cast<HttpStateData
*>(context
);
1131 state
->flags
.do_next_read
= true;
1132 state
->maybeReadVirginBody();
1137 HttpStateData::readReply(const CommIoCbParams
&io
)
1139 Must(!flags
.do_next_read
); // XXX: should have been set false by mayReadVirginBody()
1140 flags
.do_next_read
= false;
1142 debugs(11, 5, io
.conn
);
1144 // Bail out early on Comm::ERR_CLOSING - close handlers will tidy up for us
1145 if (io
.flag
== Comm::ERR_CLOSING
) {
1146 debugs(11, 3, "http socket closing");
1150 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1151 abortTransaction("store entry aborted while reading reply");
1155 Must(Comm::IsConnOpen(serverConnection
));
1156 Must(io
.conn
->fd
== serverConnection
->fd
);
1159 * Don't reset the timeout value here. The value should be
1160 * counting Config.Timeout.request and applies to the request
1161 * as a whole, not individual read() calls.
1162 * Plus, it breaks our lame *HalfClosed() detection
1165 Must(maybeMakeSpaceAvailable(true));
1166 CommIoCbParams
rd(this); // will be expanded with ReadNow results
1168 rd
.size
= entry
->bytesWanted(Range
<size_t>(0, inBuf
.spaceSize()));
1171 assert(entry
->mem_obj
);
1173 /* read ahead limit */
1174 /* Perhaps these two calls should both live in MemObject */
1175 AsyncCall::Pointer nilCall
;
1176 if (!entry
->mem_obj
->readAheadPolicyCanRead()) {
1177 entry
->mem_obj
->delayRead(DeferredRead(readDelayed
, this, CommRead(io
.conn
, NULL
, 0, nilCall
)));
1181 /* delay id limit */
1182 entry
->mem_obj
->mostBytesAllowed().delayRead(DeferredRead(readDelayed
, this, CommRead(io
.conn
, NULL
, 0, nilCall
)));
1187 switch (Comm::ReadNow(rd
, inBuf
)) {
1188 case Comm::INPROGRESS
:
1189 if (inBuf
.isEmpty())
1190 debugs(33, 2, io
.conn
<< ": no data to process, " << xstrerr(rd
.xerrno
));
1191 flags
.do_next_read
= true;
1192 maybeReadVirginBody();
1197 payloadSeen
+= rd
.size
;
1199 DelayId delayId
= entry
->mem_obj
->mostBytesAllowed();
1200 delayId
.bytesIn(rd
.size
);
1203 statCounter
.server
.all
.kbytes_in
+= rd
.size
;
1204 statCounter
.server
.http
.kbytes_in
+= rd
.size
;
1205 ++ IOStats
.Http
.reads
;
1208 for (int clen
= rd
.size
- 1; clen
; ++bin
)
1211 ++ IOStats
.Http
.read_hist
[bin
];
1213 // update peer response time stats (%<pt)
1214 const timeval
&sent
= request
->hier
.peer_http_request_sent
;
1216 tvSub(request
->hier
.peer_response_time
, sent
, current_time
);
1218 request
->hier
.peer_response_time
.tv_sec
= -1;
1221 /* Continue to process previously read data */
1224 case Comm::ENDFILE
: // close detected by 0-byte read
1226 flags
.do_next_read
= false;
1228 /* Continue to process previously read data */
1231 // case Comm::COMM_ERROR:
1232 default: // no other flags should ever occur
1233 debugs(11, 2, io
.conn
<< ": read failure: " << xstrerr(rd
.xerrno
));
1234 ErrorState
*err
= new ErrorState(ERR_READ_ERROR
, Http::scBadGateway
, fwd
->request
);
1235 err
->xerrno
= rd
.xerrno
;
1237 flags
.do_next_read
= false;
1239 mustStop("HttpStateData::readReply");
1243 /* Process next response from buffer */
1247 /// processes the already read and buffered response data, possibly after
1248 /// waiting for asynchronous 1xx control message processing
1250 HttpStateData::processReply()
1253 if (flags
.handling1xx
) { // we came back after handling a 1xx response
1254 debugs(11, 5, HERE
<< "done with 1xx handling");
1255 flags
.handling1xx
= false;
1256 Must(!flags
.headers_parsed
);
1259 if (!flags
.headers_parsed
) { // have not parsed headers yet?
1260 PROF_start(HttpStateData_processReplyHeader
);
1261 processReplyHeader();
1262 PROF_stop(HttpStateData_processReplyHeader
);
1264 if (!continueAfterParsingHeader()) // parsing error or need more data
1265 return; // TODO: send errors to ICAP
1267 adaptOrFinalizeReply(); // may write to, abort, or "close" the entry
1270 // kick more reads if needed and/or process the response body, if any
1271 PROF_start(HttpStateData_processReplyBody
);
1272 processReplyBody(); // may call serverComplete()
1273 PROF_stop(HttpStateData_processReplyBody
);
1277 \retval true if we can continue with processing the body or doing ICAP.
1280 HttpStateData::continueAfterParsingHeader()
1282 if (flags
.handling1xx
) {
1283 debugs(11, 5, HERE
<< "wait for 1xx handling");
1284 Must(!flags
.headers_parsed
);
1288 if (!flags
.headers_parsed
&& !eof
) {
1289 debugs(11, 9, "needs more at " << inBuf
.length());
1290 flags
.do_next_read
= true;
1291 /** \retval false If we have not finished parsing the headers and may get more data.
1292 * Schedules more reads to retrieve the missing data.
1294 maybeReadVirginBody(); // schedules all kinds of reads; TODO: rename
1298 /** If we are done with parsing, check for errors */
1300 err_type error
= ERR_NONE
;
1302 if (flags
.headers_parsed
) { // parsed headers, possibly with errors
1303 // check for header parsing errors
1304 if (HttpReply
*vrep
= virginReply()) {
1305 const Http::StatusCode s
= vrep
->sline
.status();
1306 const AnyP::ProtocolVersion
&v
= vrep
->sline
.version
;
1307 if (s
== Http::scInvalidHeader
&& v
!= Http::ProtocolVersion(0,9)) {
1308 debugs(11, DBG_IMPORTANT
, "WARNING: HTTP: Invalid Response: Bad header encountered from " << entry
->url() << " AKA " << request
->url
);
1309 error
= ERR_INVALID_RESP
;
1310 } else if (s
== Http::scHeaderTooLarge
) {
1311 fwd
->dontRetry(true);
1312 error
= ERR_TOO_BIG
;
1313 } else if (vrep
->header
.conflictingContentLength()) {
1314 fwd
->dontRetry(true);
1315 error
= ERR_INVALID_RESP
;
1317 return true; // done parsing, got reply, and no error
1320 // parsed headers but got no reply
1321 debugs(11, DBG_IMPORTANT
, "WARNING: HTTP: Invalid Response: No reply at all for " << entry
->url() << " AKA " << request
->url
);
1322 error
= ERR_INVALID_RESP
;
1326 if (inBuf
.length()) {
1327 error
= ERR_INVALID_RESP
;
1328 debugs(11, DBG_IMPORTANT
, "WARNING: HTTP: Invalid Response: Headers did not parse at all for " << entry
->url() << " AKA " << request
->url
);
1330 error
= ERR_ZERO_SIZE_OBJECT
;
1331 debugs(11, (request
->flags
.accelerated
?DBG_IMPORTANT
:2), "WARNING: HTTP: Invalid Response: No object data received for " << entry
->url() << " AKA " << request
->url
);
1335 assert(error
!= ERR_NONE
);
1337 fwd
->fail(new ErrorState(error
, Http::scBadGateway
, fwd
->request
));
1338 flags
.do_next_read
= false;
1340 mustStop("HttpStateData::continueAfterParsingHeader");
1341 return false; // quit on error
1344 /** truncate what we read if we read too much so that writeReplyBody()
1345 writes no more than what we should have read */
1347 HttpStateData::truncateVirginBody()
1349 assert(flags
.headers_parsed
);
1351 HttpReply
*vrep
= virginReply();
1353 if (!vrep
->expectingBody(request
->method
, clen
) || clen
< 0)
1354 return; // no body or a body of unknown size, including chunked
1356 if (payloadSeen
- payloadTruncated
<= clen
)
1357 return; // we did not read too much or already took care of the extras
1359 if (const int64_t extras
= payloadSeen
- payloadTruncated
- clen
) {
1360 // server sent more that the advertised content length
1361 debugs(11, 5, "payloadSeen=" << payloadSeen
<<
1362 " clen=" << clen
<< '/' << vrep
->content_length
<<
1363 " trucated=" << payloadTruncated
<< '+' << extras
);
1365 inBuf
.chop(0, inBuf
.length() - extras
);
1366 payloadTruncated
+= extras
;
1371 * Call this when there is data from the origin server
1372 * which should be sent to either StoreEntry, or to ICAP...
1375 HttpStateData::writeReplyBody()
1377 truncateVirginBody(); // if needed
1378 const char *data
= inBuf
.rawContent();
1379 int len
= inBuf
.length();
1380 addVirginReplyBody(data
, len
);
1385 HttpStateData::decodeAndWriteReplyBody()
1387 const char *data
= NULL
;
1389 bool wasThereAnException
= false;
1390 assert(flags
.chunked
);
1391 assert(httpChunkDecoder
);
1392 SQUID_ENTER_THROWING_CODE();
1395 httpChunkDecoder
->setPayloadBuffer(&decodedData
);
1396 const bool doneParsing
= httpChunkDecoder
->parse(inBuf
);
1397 inBuf
= httpChunkDecoder
->remaining(); // sync buffers after parse
1398 len
= decodedData
.contentSize();
1399 data
=decodedData
.content();
1400 addVirginReplyBody(data
, len
);
1403 flags
.do_next_read
= false;
1405 SQUID_EXIT_THROWING_CODE(wasThereAnException
);
1406 return wasThereAnException
;
1410 * processReplyBody has two purposes:
1411 * 1 - take the reply body data, if any, and put it into either
1412 * the StoreEntry, or give it over to ICAP.
1413 * 2 - see if we made it to the end of the response (persistent
1414 * connections and such)
1417 HttpStateData::processReplyBody()
1419 Ip::Address client_addr
;
1420 bool ispinned
= false;
1422 if (!flags
.headers_parsed
) {
1423 flags
.do_next_read
= true;
1424 maybeReadVirginBody();
1429 debugs(11,5, HERE
<< "adaptationAccessCheckPending=" << adaptationAccessCheckPending
);
1430 if (adaptationAccessCheckPending
)
1436 * At this point the reply headers have been parsed and consumed.
1437 * That means header content has been removed from readBuf and
1438 * it contains only body data.
1440 if (entry
->isAccepting()) {
1441 if (flags
.chunked
) {
1442 if (!decodeAndWriteReplyBody()) {
1443 flags
.do_next_read
= false;
1451 // storing/sending methods like earlier adaptOrFinalizeReply() or
1452 // above writeReplyBody() may release/abort the store entry.
1453 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1454 // TODO: In some cases (e.g., 304), we should keep persistent conn open.
1455 // Detect end-of-reply (and, hence, pool our idle pconn) earlier (ASAP).
1456 abortTransaction("store entry aborted while storing reply");
1459 switch (persistentConnStatus()) {
1460 case INCOMPLETE_MSG
: {
1461 debugs(11, 5, "processReplyBody: INCOMPLETE_MSG from " << serverConnection
);
1462 /* Wait for more data or EOF condition */
1463 AsyncCall::Pointer nil
;
1464 if (flags
.keepalive_broken
) {
1465 commSetConnTimeout(serverConnection
, 10, nil
);
1467 commSetConnTimeout(serverConnection
, Config
.Timeout
.read
, nil
);
1470 flags
.do_next_read
= true;
1474 case COMPLETE_PERSISTENT_MSG
:
1475 debugs(11, 5, "processReplyBody: COMPLETE_PERSISTENT_MSG from " << serverConnection
);
1476 /* yes we have to clear all these! */
1477 commUnsetConnTimeout(serverConnection
);
1478 flags
.do_next_read
= false;
1480 comm_remove_close_handler(serverConnection
->fd
, closeHandler
);
1481 closeHandler
= NULL
;
1482 fwd
->unregister(serverConnection
);
1484 if (request
->flags
.spoofClientIp
)
1485 client_addr
= request
->client_addr
;
1487 if (request
->flags
.pinned
) {
1489 } else if (request
->flags
.connectionAuth
&& request
->flags
.authSent
) {
1493 if (ispinned
&& request
->clientConnectionManager
.valid()) {
1494 request
->clientConnectionManager
->pinConnection(serverConnection
, request
, _peer
,
1495 (request
->flags
.connectionAuth
));
1497 fwd
->pconnPush(serverConnection
, request
->url
.host());
1500 serverConnection
= NULL
;
1504 case COMPLETE_NONPERSISTENT_MSG
:
1505 debugs(11, 5, "processReplyBody: COMPLETE_NONPERSISTENT_MSG from " << serverConnection
);
1510 maybeReadVirginBody();
1514 HttpStateData::mayReadVirginReplyBody() const
1516 // TODO: Be more precise here. For example, if/when reading trailer, we may
1517 // not be doneWithServer() yet, but we should return false. Similarly, we
1518 // could still be writing the request body after receiving the whole reply.
1519 return !doneWithServer();
1523 HttpStateData::maybeReadVirginBody()
1526 if (!Comm::IsConnOpen(serverConnection
) || fd_table
[serverConnection
->fd
].closing())
1529 if (!maybeMakeSpaceAvailable(false))
1532 // XXX: get rid of the do_next_read flag
1533 // check for the proper reasons preventing read(2)
1534 if (!flags
.do_next_read
)
1537 flags
.do_next_read
= false;
1539 // must not already be waiting for read(2) ...
1540 assert(!Comm::MonitorsRead(serverConnection
->fd
));
1542 // wait for read(2) to be possible.
1543 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
1544 AsyncCall::Pointer call
= JobCallback(11, 5, Dialer
, this, HttpStateData::readReply
);
1545 Comm::Read(serverConnection
, call
);
1549 HttpStateData::maybeMakeSpaceAvailable(bool doGrow
)
1551 // how much we are allowed to buffer
1552 const int limitBuffer
= (flags
.headers_parsed
? Config
.readAheadGap
: Config
.maxReplyHeaderSize
);
1554 if (limitBuffer
< 0 || inBuf
.length() >= (SBuf::size_type
)limitBuffer
) {
1555 // when buffer is at or over limit already
1556 debugs(11, 7, "wont read up to " << limitBuffer
<< ". buffer has (" << inBuf
.length() << "/" << inBuf
.spaceSize() << ") from " << serverConnection
);
1557 debugs(11, DBG_DATA
, "buffer has {" << inBuf
<< "}");
1558 // Process next response from buffer
1563 // how much we want to read
1564 const size_t read_size
= calcBufferSpaceToReserve(inBuf
.spaceSize(), (limitBuffer
- inBuf
.length()));
1567 debugs(11, 7, "wont read up to " << read_size
<< " into buffer (" << inBuf
.length() << "/" << inBuf
.spaceSize() << ") from " << serverConnection
);
1571 // just report whether we could grow or not, dont actually do it
1573 return (read_size
>= 2);
1575 // we may need to grow the buffer
1576 inBuf
.reserveSpace(read_size
);
1577 debugs(11, 8, (!flags
.do_next_read
? "wont" : "may") <<
1578 " read up to " << read_size
<< " bytes info buf(" << inBuf
.length() << "/" << inBuf
.spaceSize() <<
1579 ") from " << serverConnection
);
1581 return (inBuf
.spaceSize() >= 2); // only read if there is 1+ bytes of space available
1584 /// called after writing the very last request byte (body, last-chunk, etc)
1586 HttpStateData::wroteLast(const CommIoCbParams
&io
)
1588 debugs(11, 5, HERE
<< serverConnection
<< ": size " << io
.size
<< ": errflag " << io
.flag
<< ".");
1589 #if URL_CHECKSUM_DEBUG
1591 entry
->mem_obj
->checkUrlChecksum();
1595 fd_bytes(io
.fd
, io
.size
, FD_WRITE
);
1596 statCounter
.server
.all
.kbytes_out
+= io
.size
;
1597 statCounter
.server
.http
.kbytes_out
+= io
.size
;
1600 if (io
.flag
== Comm::ERR_CLOSING
)
1604 ErrorState
*err
= new ErrorState(ERR_WRITE_ERROR
, Http::scBadGateway
, fwd
->request
);
1605 err
->xerrno
= io
.xerrno
;
1608 mustStop("HttpStateData::wroteLast");
1615 /// successfully wrote the entire request (including body, last-chunk, etc.)
1617 HttpStateData::sendComplete()
1620 * Set the read timeout here because it hasn't been set yet.
1621 * We only set the read timeout after the request has been
1622 * fully written to the peer. If we start the timeout
1623 * after connection establishment, then we are likely to hit
1624 * the timeout for POST/PUT requests that have very large
1627 typedef CommCbMemFunT
<HttpStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1628 AsyncCall::Pointer timeoutCall
= JobCallback(11, 5,
1629 TimeoutDialer
, this, HttpStateData::httpTimeout
);
1631 commSetConnTimeout(serverConnection
, Config
.Timeout
.read
, timeoutCall
);
1632 flags
.request_sent
= true;
1633 request
->hier
.peer_http_request_sent
= current_time
;
1637 HttpStateData::closeServer()
1639 debugs(11,5, HERE
<< "closing HTTP server " << serverConnection
<< " this " << this);
1641 if (Comm::IsConnOpen(serverConnection
)) {
1642 fwd
->unregister(serverConnection
);
1643 comm_remove_close_handler(serverConnection
->fd
, closeHandler
);
1644 closeHandler
= NULL
;
1645 serverConnection
->close();
1650 HttpStateData::doneWithServer() const
1652 return !Comm::IsConnOpen(serverConnection
);
1656 * Fixup authentication request headers for special cases
1659 httpFixupAuthentication(HttpRequest
* request
, const HttpHeader
* hdr_in
, HttpHeader
* hdr_out
, const HttpStateFlags
&flags
)
1661 Http::HdrType header
= flags
.originpeer
? Http::HdrType::AUTHORIZATION
: Http::HdrType::PROXY_AUTHORIZATION
;
1663 /* Nothing to do unless we are forwarding to a peer */
1664 if (!request
->flags
.proxying
)
1667 /* Needs to be explicitly enabled */
1668 if (!request
->peer_login
)
1671 /* Maybe already dealt with? */
1672 if (hdr_out
->has(header
))
1675 /* Nothing to do here for PASSTHRU */
1676 if (strcmp(request
->peer_login
, "PASSTHRU") == 0)
1679 /* PROXYPASS is a special case, single-signon to servers with the proxy password (basic only) */
1680 if (flags
.originpeer
&& strcmp(request
->peer_login
, "PROXYPASS") == 0 && hdr_in
->has(Http::HdrType::PROXY_AUTHORIZATION
)) {
1681 const char *auth
= hdr_in
->getStr(Http::HdrType::PROXY_AUTHORIZATION
);
1683 if (auth
&& strncasecmp(auth
, "basic ", 6) == 0) {
1684 hdr_out
->putStr(header
, auth
);
1689 uint8_t loginbuf
[base64_encode_len(MAX_LOGIN_SZ
)];
1691 struct base64_encode_ctx ctx
;
1692 base64_encode_init(&ctx
);
1694 /* Special mode to pass the username to the upstream cache */
1695 if (*request
->peer_login
== '*') {
1696 const char *username
= "-";
1698 if (request
->extacl_user
.size())
1699 username
= request
->extacl_user
.termedBuf();
1701 else if (request
->auth_user_request
!= NULL
)
1702 username
= request
->auth_user_request
->username();
1705 blen
= base64_encode_update(&ctx
, loginbuf
, strlen(username
), reinterpret_cast<const uint8_t*>(username
));
1706 blen
+= base64_encode_update(&ctx
, loginbuf
+blen
, strlen(request
->peer_login
+1), reinterpret_cast<const uint8_t*>(request
->peer_login
+1));
1707 blen
+= base64_encode_final(&ctx
, loginbuf
+blen
);
1708 httpHeaderPutStrf(hdr_out
, header
, "Basic %.*s", (int)blen
, loginbuf
);
1712 /* external_acl provided credentials */
1713 if (request
->extacl_user
.size() && request
->extacl_passwd
.size() &&
1714 (strcmp(request
->peer_login
, "PASS") == 0 ||
1715 strcmp(request
->peer_login
, "PROXYPASS") == 0)) {
1717 blen
= base64_encode_update(&ctx
, loginbuf
, request
->extacl_user
.size(), reinterpret_cast<const uint8_t*>(request
->extacl_user
.rawBuf()));
1718 blen
+= base64_encode_update(&ctx
, loginbuf
+blen
, 1, reinterpret_cast<const uint8_t*>(":"));
1719 blen
+= base64_encode_update(&ctx
, loginbuf
+blen
, request
->extacl_passwd
.size(), reinterpret_cast<const uint8_t*>(request
->extacl_passwd
.rawBuf()));
1720 blen
+= base64_encode_final(&ctx
, loginbuf
+blen
);
1721 httpHeaderPutStrf(hdr_out
, header
, "Basic %.*s", (int)blen
, loginbuf
);
1724 // if no external user credentials are available to fake authentication with PASS acts like PASSTHRU
1725 if (strcmp(request
->peer_login
, "PASS") == 0)
1728 /* Kerberos login to peer */
1729 #if HAVE_AUTH_MODULE_NEGOTIATE && HAVE_KRB5 && HAVE_GSSAPI
1730 if (strncmp(request
->peer_login
, "NEGOTIATE",strlen("NEGOTIATE")) == 0) {
1732 char *PrincipalName
=NULL
,*p
;
1733 int negotiate_flags
= 0;
1735 if ((p
=strchr(request
->peer_login
,':')) != NULL
) {
1738 if (request
->flags
.auth_no_keytab
) {
1739 negotiate_flags
|= PEER_PROXY_NEGOTIATE_NOKEYTAB
;
1741 Token
= peer_proxy_negotiate_auth(PrincipalName
, request
->peer_host
, negotiate_flags
);
1743 httpHeaderPutStrf(hdr_out
, header
, "Negotiate %s",Token
);
1747 #endif /* HAVE_KRB5 && HAVE_GSSAPI */
1749 blen
= base64_encode_update(&ctx
, loginbuf
, strlen(request
->peer_login
), reinterpret_cast<const uint8_t*>(request
->peer_login
));
1750 blen
+= base64_encode_final(&ctx
, loginbuf
+blen
);
1751 httpHeaderPutStrf(hdr_out
, header
, "Basic %.*s", (int)blen
, loginbuf
);
1756 * build request headers and append them to a given MemBuf
1757 * used by buildRequestPrefix()
1758 * note: initialised the HttpHeader, the caller is responsible for Clean()-ing
1761 HttpStateData::httpBuildRequestHeader(HttpRequest
* request
,
1763 const AccessLogEntryPointer
&al
,
1764 HttpHeader
* hdr_out
,
1765 const HttpStateFlags
&flags
)
1767 /* building buffer for complex strings */
1768 #define BBUF_SZ (MAX_URL+32)
1769 LOCAL_ARRAY(char, bbuf
, BBUF_SZ
);
1770 LOCAL_ARRAY(char, ntoabuf
, MAX_IPSTRLEN
);
1771 const HttpHeader
*hdr_in
= &request
->header
;
1772 const HttpHeaderEntry
*e
= NULL
;
1773 HttpHeaderPos pos
= HttpHeaderInitPos
;
1774 assert (hdr_out
->owner
== hoRequest
);
1776 /* use our IMS header if the cached entry has Last-Modified time */
1777 if (request
->lastmod
> -1)
1778 hdr_out
->putTime(Http::HdrType::IF_MODIFIED_SINCE
, request
->lastmod
);
1780 // Add our own If-None-Match field if the cached entry has a strong ETag.
1781 // copyOneHeaderFromClientsideRequestToUpstreamRequest() adds client ones.
1782 if (request
->etag
.size() > 0) {
1783 hdr_out
->addEntry(new HttpHeaderEntry(Http::HdrType::IF_NONE_MATCH
, NULL
,
1784 request
->etag
.termedBuf()));
1787 bool we_do_ranges
= decideIfWeDoRanges (request
);
1789 String
strConnection (hdr_in
->getList(Http::HdrType::CONNECTION
));
1791 while ((e
= hdr_in
->getEntry(&pos
)))
1792 copyOneHeaderFromClientsideRequestToUpstreamRequest(e
, strConnection
, request
, hdr_out
, we_do_ranges
, flags
);
1794 /* Abstraction break: We should interpret multipart/byterange responses
1795 * into offset-length data, and this works around our inability to do so.
1797 if (!we_do_ranges
&& request
->multipartRangeRequest()) {
1798 /* don't cache the result */
1799 request
->flags
.cachable
= false;
1800 /* pretend it's not a range request */
1801 request
->ignoreRange("want to request the whole object");
1802 request
->flags
.isRanged
= false;
1806 if (Config
.onoff
.via
) {
1808 strVia
= hdr_in
->getList(Http::HdrType::VIA
);
1809 snprintf(bbuf
, BBUF_SZ
, "%d.%d %s",
1810 request
->http_ver
.major
,
1811 request
->http_ver
.minor
, ThisCache
);
1812 strListAdd(&strVia
, bbuf
, ',');
1813 hdr_out
->putStr(Http::HdrType::VIA
, strVia
.termedBuf());
1817 if (request
->flags
.accelerated
) {
1818 /* Append Surrogate-Capabilities */
1819 String
strSurrogate(hdr_in
->getList(Http::HdrType::SURROGATE_CAPABILITY
));
1821 snprintf(bbuf
, BBUF_SZ
, "%s=\"Surrogate/1.0 ESI/1.0\"", Config
.Accel
.surrogate_id
);
1823 snprintf(bbuf
, BBUF_SZ
, "%s=\"Surrogate/1.0\"", Config
.Accel
.surrogate_id
);
1825 strListAdd(&strSurrogate
, bbuf
, ',');
1826 hdr_out
->putStr(Http::HdrType::SURROGATE_CAPABILITY
, strSurrogate
.termedBuf());
1829 /** \pre Handle X-Forwarded-For */
1830 if (strcmp(opt_forwarded_for
, "delete") != 0) {
1832 String strFwd
= hdr_in
->getList(Http::HdrType::X_FORWARDED_FOR
);
1834 // if we cannot double strFwd size, then it grew past 50% of the limit
1835 if (!strFwd
.canGrowBy(strFwd
.size())) {
1836 // There is probably a forwarding loop with Via detection disabled.
1837 // If we do nothing, String will assert on overflow soon.
1838 // TODO: Terminate all transactions with huge XFF?
1841 static int warnedCount
= 0;
1842 if (warnedCount
++ < 100) {
1843 const SBuf
url(entry
? SBuf(entry
->url()) : request
->effectiveRequestUri());
1844 debugs(11, DBG_IMPORTANT
, "Warning: likely forwarding loop with " << url
);
1848 if (strcmp(opt_forwarded_for
, "on") == 0) {
1849 /** If set to ON - append client IP or 'unknown'. */
1850 if ( request
->client_addr
.isNoAddr() )
1851 strListAdd(&strFwd
, "unknown", ',');
1853 strListAdd(&strFwd
, request
->client_addr
.toStr(ntoabuf
, MAX_IPSTRLEN
), ',');
1854 } else if (strcmp(opt_forwarded_for
, "off") == 0) {
1855 /** If set to OFF - append 'unknown'. */
1856 strListAdd(&strFwd
, "unknown", ',');
1857 } else if (strcmp(opt_forwarded_for
, "transparent") == 0) {
1858 /** If set to TRANSPARENT - pass through unchanged. */
1859 } else if (strcmp(opt_forwarded_for
, "truncate") == 0) {
1860 /** If set to TRUNCATE - drop existing list and replace with client IP or 'unknown'. */
1861 if ( request
->client_addr
.isNoAddr() )
1864 strFwd
= request
->client_addr
.toStr(ntoabuf
, MAX_IPSTRLEN
);
1866 if (strFwd
.size() > 0)
1867 hdr_out
->putStr(Http::HdrType::X_FORWARDED_FOR
, strFwd
.termedBuf());
1869 /** If set to DELETE - do not copy through. */
1871 /* append Host if not there already */
1872 if (!hdr_out
->has(Http::HdrType::HOST
)) {
1873 if (request
->peer_domain
) {
1874 hdr_out
->putStr(Http::HdrType::HOST
, request
->peer_domain
);
1876 SBuf authority
= request
->url
.authority();
1877 hdr_out
->putStr(Http::HdrType::HOST
, authority
.c_str());
1881 /* append Authorization if known in URL, not in header and going direct */
1882 if (!hdr_out
->has(Http::HdrType::AUTHORIZATION
)) {
1883 if (!request
->flags
.proxying
&& !request
->url
.userInfo().isEmpty()) {
1884 static uint8_t result
[base64_encode_len(MAX_URL
*2)]; // should be big enough for a single URI segment
1885 struct base64_encode_ctx ctx
;
1886 base64_encode_init(&ctx
);
1887 size_t blen
= base64_encode_update(&ctx
, result
, request
->url
.userInfo().length(), reinterpret_cast<const uint8_t*>(request
->url
.userInfo().rawContent()));
1888 blen
+= base64_encode_final(&ctx
, result
+blen
);
1889 result
[blen
] = '\0';
1891 httpHeaderPutStrf(hdr_out
, Http::HdrType::AUTHORIZATION
, "Basic %.*s", (int)blen
, result
);
1895 /* Fixup (Proxy-)Authorization special cases. Plain relaying dealt with above */
1896 httpFixupAuthentication(request
, hdr_in
, hdr_out
, flags
);
1898 /* append Cache-Control, add max-age if not there already */
1900 HttpHdrCc
*cc
= hdr_in
->getCc();
1903 cc
= new HttpHdrCc();
1905 #if 0 /* see bug 2330 */
1906 /* Set no-cache if determined needed but not found */
1907 if (request
->flags
.nocache
)
1908 EBIT_SET(cc
->mask
, HttpHdrCcType::CC_NO_CACHE
);
1911 /* Add max-age only without no-cache */
1912 if (!cc
->hasMaxAge() && !cc
->hasNoCache()) {
1913 // XXX: performance regression. c_str() reallocates
1914 SBuf
tmp(request
->effectiveRequestUri());
1915 cc
->maxAge(getMaxAge(entry
? entry
->url() : tmp
.c_str()));
1918 /* Enforce sibling relations */
1919 if (flags
.only_if_cached
)
1920 cc
->onlyIfCached(true);
1927 /* maybe append Connection: keep-alive */
1928 if (flags
.keepalive
) {
1929 hdr_out
->putStr(Http::HdrType::CONNECTION
, "keep-alive");
1932 /* append Front-End-Https */
1933 if (flags
.front_end_https
) {
1934 if (flags
.front_end_https
== 1 || request
->url
.getScheme() == AnyP::PROTO_HTTPS
)
1935 hdr_out
->putStr(Http::HdrType::FRONT_END_HTTPS
, "On");
1938 if (flags
.chunked_request
) {
1939 // Do not just copy the original value so that if the client-side
1940 // starts decode other encodings, this code may remain valid.
1941 hdr_out
->putStr(Http::HdrType::TRANSFER_ENCODING
, "chunked");
1944 /* Now mangle the headers. */
1945 if (Config2
.onoff
.mangle_request_headers
)
1946 httpHdrMangleList(hdr_out
, request
, ROR_REQUEST
);
1948 if (Config
.request_header_add
&& !Config
.request_header_add
->empty())
1949 httpHdrAdd(hdr_out
, request
, al
, *Config
.request_header_add
);
1951 strConnection
.clean();
1955 * Decides whether a particular header may be cloned from the received Clients request
1956 * to our outgoing fetch request.
1959 copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry
*e
, const String strConnection
, const HttpRequest
* request
, HttpHeader
* hdr_out
, const int we_do_ranges
, const HttpStateFlags
&flags
)
1961 debugs(11, 5, "httpBuildRequestHeader: " << e
->name
<< ": " << e
->value
);
1965 /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid should not pass on. */
1967 case Http::HdrType::PROXY_AUTHORIZATION
:
1968 /** \par Proxy-Authorization:
1969 * Only pass on proxy authentication to peers for which
1970 * authentication forwarding is explicitly enabled
1972 if (!flags
.originpeer
&& flags
.proxying
&& request
->peer_login
&&
1973 (strcmp(request
->peer_login
, "PASS") == 0 ||
1974 strcmp(request
->peer_login
, "PROXYPASS") == 0 ||
1975 strcmp(request
->peer_login
, "PASSTHRU") == 0)) {
1976 hdr_out
->addEntry(e
->clone());
1980 /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid does not pass on. */
1982 case Http::HdrType::CONNECTION
: /** \par Connection: */
1983 case Http::HdrType::TE
: /** \par TE: */
1984 case Http::HdrType::KEEP_ALIVE
: /** \par Keep-Alive: */
1985 case Http::HdrType::PROXY_AUTHENTICATE
: /** \par Proxy-Authenticate: */
1986 case Http::HdrType::TRAILER
: /** \par Trailer: */
1987 case Http::HdrType::UPGRADE
: /** \par Upgrade: */
1988 case Http::HdrType::TRANSFER_ENCODING
: /** \par Transfer-Encoding: */
1991 /** \par OTHER headers I haven't bothered to track down yet. */
1993 case Http::HdrType::AUTHORIZATION
:
1994 /** \par WWW-Authorization:
1995 * Pass on WWW authentication */
1997 if (!flags
.originpeer
) {
1998 hdr_out
->addEntry(e
->clone());
2000 /** \note In accelerators, only forward authentication if enabled
2001 * (see also httpFixupAuthentication for special cases)
2003 if (request
->peer_login
&&
2004 (strcmp(request
->peer_login
, "PASS") == 0 ||
2005 strcmp(request
->peer_login
, "PASSTHRU") == 0 ||
2006 strcmp(request
->peer_login
, "PROXYPASS") == 0)) {
2007 hdr_out
->addEntry(e
->clone());
2013 case Http::HdrType::HOST
:
2015 * Normally Squid rewrites the Host: header.
2016 * However, there is one case when we don't: If the URL
2017 * went through our redirector and the admin configured
2018 * 'redir_rewrites_host' to be off.
2020 if (request
->peer_domain
)
2021 hdr_out
->putStr(Http::HdrType::HOST
, request
->peer_domain
);
2022 else if (request
->flags
.redirected
&& !Config
.onoff
.redir_rewrites_host
)
2023 hdr_out
->addEntry(e
->clone());
2025 SBuf authority
= request
->url
.authority();
2026 hdr_out
->putStr(Http::HdrType::HOST
, authority
.c_str());
2031 case Http::HdrType::IF_MODIFIED_SINCE
:
2032 /** \par If-Modified-Since:
2033 * append unless we added our own,
2034 * but only if cache_miss_revalidate is enabled, or
2035 * the request is not cacheable, or
2036 * the request contains authentication credentials.
2037 * \note at most one client's If-Modified-Since header can pass through
2039 // XXX: need to check and cleanup the auth case so cacheable auth requests get cached.
2040 if (hdr_out
->has(Http::HdrType::IF_MODIFIED_SINCE
))
2042 else if (Config
.onoff
.cache_miss_revalidate
|| !request
->flags
.cachable
|| request
->flags
.auth
)
2043 hdr_out
->addEntry(e
->clone());
2046 case Http::HdrType::IF_NONE_MATCH
:
2047 /** \par If-None-Match:
2048 * append if the wildcard '*' special case value is present, or
2049 * cache_miss_revalidate is disabled, or
2050 * the request is not cacheable in this proxy, or
2051 * the request contains authentication credentials.
2052 * \note this header lists a set of responses for the server to elide sending. Squid added values are extending that set.
2054 // XXX: need to check and cleanup the auth case so cacheable auth requests get cached.
2055 if (hdr_out
->hasListMember(Http::HdrType::IF_MATCH
, "*", ',') || Config
.onoff
.cache_miss_revalidate
|| !request
->flags
.cachable
|| request
->flags
.auth
)
2056 hdr_out
->addEntry(e
->clone());
2059 case Http::HdrType::MAX_FORWARDS
:
2060 /** \par Max-Forwards:
2061 * pass only on TRACE or OPTIONS requests */
2062 if (request
->method
== Http::METHOD_TRACE
|| request
->method
== Http::METHOD_OPTIONS
) {
2063 const int64_t hops
= e
->getInt64();
2066 hdr_out
->putInt64(Http::HdrType::MAX_FORWARDS
, hops
- 1);
2071 case Http::HdrType::VIA
:
2073 * If Via is disabled then forward any received header as-is.
2074 * Otherwise leave for explicit updated addition later. */
2076 if (!Config
.onoff
.via
)
2077 hdr_out
->addEntry(e
->clone());
2081 case Http::HdrType::RANGE
:
2083 case Http::HdrType::IF_RANGE
:
2085 case Http::HdrType::REQUEST_RANGE
:
2086 /** \par Range:, If-Range:, Request-Range:
2087 * Only pass if we accept ranges */
2089 hdr_out
->addEntry(e
->clone());
2093 case Http::HdrType::PROXY_CONNECTION
: // SHOULD ignore. But doing so breaks things.
2096 case Http::HdrType::CONTENT_LENGTH
:
2097 // pass through unless we chunk; also, keeping this away from default
2098 // prevents request smuggling via Connection: Content-Length tricks
2099 if (!flags
.chunked_request
)
2100 hdr_out
->addEntry(e
->clone());
2103 case Http::HdrType::X_FORWARDED_FOR
:
2105 case Http::HdrType::CACHE_CONTROL
:
2106 /** \par X-Forwarded-For:, Cache-Control:
2107 * handled specially by Squid, so leave off for now.
2108 * append these after the loop if needed */
2111 case Http::HdrType::FRONT_END_HTTPS
:
2112 /** \par Front-End-Https:
2113 * Pass thru only if peer is configured with front-end-https */
2114 if (!flags
.front_end_https
)
2115 hdr_out
->addEntry(e
->clone());
2121 * pass on all other header fields
2122 * which are NOT listed by the special Connection: header. */
2124 if (strConnection
.size()>0 && strListIsMember(&strConnection
, e
->name
.termedBuf(), ',')) {
2125 debugs(11, 2, "'" << e
->name
<< "' header cropped by Connection: definition");
2129 hdr_out
->addEntry(e
->clone());
2134 HttpStateData::decideIfWeDoRanges (HttpRequest
* request
)
2137 /* decide if we want to do Ranges ourselves
2138 * and fetch the whole object now)
2139 * We want to handle Ranges ourselves iff
2140 * - we can actually parse client Range specs
2141 * - the specs are expected to be simple enough (e.g. no out-of-order ranges)
2142 * - reply will be cachable
2143 * (If the reply will be uncachable we have to throw it away after
2144 * serving this request, so it is better to forward ranges to
2145 * the server and fetch only the requested content)
2148 int64_t roffLimit
= request
->getRangeOffsetLimit();
2150 if (NULL
== request
->range
|| !request
->flags
.cachable
2151 || request
->range
->offsetLimitExceeded(roffLimit
) || request
->flags
.connectionAuth
)
2154 debugs(11, 8, "decideIfWeDoRanges: range specs: " <<
2155 request
->range
<< ", cachable: " <<
2156 request
->flags
.cachable
<< "; we_do_ranges: " << result
);
2161 /* build request prefix and append it to a given MemBuf;
2162 * return the length of the prefix */
2164 HttpStateData::buildRequestPrefix(MemBuf
* mb
)
2166 const int offset
= mb
->size
;
2167 /* Uses a local httpver variable to print the HTTP label
2168 * since the HttpRequest may have an older version label.
2169 * XXX: This could create protocol bugs as the headers sent and
2170 * flow control should all be based on the HttpRequest version
2171 * not the one we are sending. Needs checking.
2173 const AnyP::ProtocolVersion httpver
= Http::ProtocolVersion();
2174 const SBuf
url(_peer
&& !_peer
->options
.originserver
? request
->effectiveRequestUri() : request
->url
.path());
2175 mb
->appendf(SQUIDSBUFPH
" " SQUIDSBUFPH
" %s/%d.%d\r\n",
2176 SQUIDSBUFPRINT(request
->method
.image()),
2177 SQUIDSBUFPRINT(url
),
2178 AnyP::ProtocolType_str
[httpver
.protocol
],
2179 httpver
.major
,httpver
.minor
);
2180 /* build and pack headers */
2182 HttpHeader
hdr(hoRequest
);
2183 httpBuildRequestHeader(request
, entry
, fwd
->al
, &hdr
, flags
);
2185 if (request
->flags
.pinned
&& request
->flags
.connectionAuth
)
2186 request
->flags
.authSent
= true;
2187 else if (hdr
.has(Http::HdrType::AUTHORIZATION
))
2188 request
->flags
.authSent
= true;
2193 /* append header terminator */
2194 mb
->append(crlf
, 2);
2195 return mb
->size
- offset
;
2198 /* This will be called when connect completes. Write request. */
2200 HttpStateData::sendRequest()
2204 debugs(11, 5, HERE
<< serverConnection
<< ", request " << request
<< ", this " << this << ".");
2206 if (!Comm::IsConnOpen(serverConnection
)) {
2207 debugs(11,3, HERE
<< "cannot send request to closing " << serverConnection
);
2208 assert(closeHandler
!= NULL
);
2212 typedef CommCbMemFunT
<HttpStateData
, CommTimeoutCbParams
> TimeoutDialer
;
2213 AsyncCall::Pointer timeoutCall
= JobCallback(11, 5,
2214 TimeoutDialer
, this, HttpStateData::httpTimeout
);
2215 commSetConnTimeout(serverConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
2216 flags
.do_next_read
= true;
2217 maybeReadVirginBody();
2219 if (request
->body_pipe
!= NULL
) {
2220 if (!startRequestBodyFlow()) // register to receive body data
2222 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
2223 requestSender
= JobCallback(11,5,
2224 Dialer
, this, HttpStateData::sentRequestBody
);
2226 Must(!flags
.chunked_request
);
2227 // use chunked encoding if we do not know the length
2228 if (request
->content_length
< 0)
2229 flags
.chunked_request
= true;
2231 assert(!requestBodySource
);
2232 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
2233 requestSender
= JobCallback(11,5,
2234 Dialer
, this, HttpStateData::wroteLast
);
2237 flags
.originpeer
= (_peer
!= NULL
&& _peer
->options
.originserver
);
2238 flags
.proxying
= (_peer
!= NULL
&& !flags
.originpeer
);
2241 * Is keep-alive okay for all request methods?
2243 if (request
->flags
.mustKeepalive
)
2244 flags
.keepalive
= true;
2245 else if (request
->flags
.pinned
)
2246 flags
.keepalive
= request
->persistent();
2247 else if (!Config
.onoff
.server_pconns
)
2248 flags
.keepalive
= false;
2249 else if (_peer
== NULL
)
2250 flags
.keepalive
= true;
2251 else if (_peer
->stats
.n_keepalives_sent
< 10)
2252 flags
.keepalive
= true;
2253 else if ((double) _peer
->stats
.n_keepalives_recv
/
2254 (double) _peer
->stats
.n_keepalives_sent
> 0.50)
2255 flags
.keepalive
= true;
2258 /*The old code here was
2259 if (neighborType(_peer, request->url) == PEER_SIBLING && ...
2260 which is equivalent to:
2261 if (neighborType(_peer, URL()) == PEER_SIBLING && ...
2263 if (((_peer->type == PEER_MULTICAST && p->options.mcast_siblings) ||
2264 _peer->type == PEER_SIBLINGS ) && _peer->options.allow_miss)
2265 flags.only_if_cached = 1;
2267 But I suppose it was a bug
2269 if (neighborType(_peer
, request
->url
) == PEER_SIBLING
&& !_peer
->options
.allow_miss
)
2270 flags
.only_if_cached
= true;
2272 flags
.front_end_https
= _peer
->front_end_https
;
2276 request
->peer_host
=_peer
?_peer
->host
:NULL
;
2277 buildRequestPrefix(&mb
);
2279 debugs(11, 2, "HTTP Server " << serverConnection
);
2280 debugs(11, 2, "HTTP Server REQUEST:\n---------\n" << mb
.buf
<< "\n----------");
2282 Comm::Write(serverConnection
, &mb
, requestSender
);
2287 HttpStateData::getMoreRequestBody(MemBuf
&buf
)
2289 // parent's implementation can handle the no-encoding case
2290 if (!flags
.chunked_request
)
2291 return Client::getMoreRequestBody(buf
);
2295 Must(requestBodySource
!= NULL
);
2296 if (!requestBodySource
->getMoreData(raw
))
2297 return false; // no request body bytes to chunk yet
2299 // optimization: pre-allocate buffer size that should be enough
2300 const mb_size_t rawDataSize
= raw
.contentSize();
2301 // we may need to send: hex-chunk-size CRLF raw-data CRLF last-chunk
2302 buf
.init(16 + 2 + rawDataSize
+ 2 + 5, raw
.max_capacity
);
2304 buf
.appendf("%x\r\n", static_cast<unsigned int>(rawDataSize
));
2305 buf
.append(raw
.content(), rawDataSize
);
2306 buf
.append("\r\n", 2);
2308 Must(rawDataSize
> 0); // we did not accidently created last-chunk above
2310 // Do not send last-chunk unless we successfully received everything
2311 if (receivedWholeRequestBody
) {
2312 Must(!flags
.sentLastChunk
);
2313 flags
.sentLastChunk
= true;
2314 buf
.append("0\r\n\r\n", 5);
2321 httpStart(FwdState
*fwd
)
2323 debugs(11, 3, fwd
->request
->method
<< ' ' << fwd
->entry
->url());
2324 AsyncJob::Start(new HttpStateData(fwd
));
2328 HttpStateData::start()
2330 if (!sendRequest()) {
2331 debugs(11, 3, "httpStart: aborted");
2332 mustStop("HttpStateData::start failed");
2336 ++ statCounter
.server
.all
.requests
;
2337 ++ statCounter
.server
.http
.requests
;
2340 * We used to set the read timeout here, but not any more.
2341 * Now its set in httpSendComplete() after the full request,
2342 * including request body, has been written to the server.
2346 /// if broken posts are enabled for the request, try to fix and return true
2348 HttpStateData::finishingBrokenPost()
2350 #if USE_HTTP_VIOLATIONS
2351 if (!Config
.accessList
.brokenPosts
) {
2352 debugs(11, 5, HERE
<< "No brokenPosts list");
2356 ACLFilledChecklist
ch(Config
.accessList
.brokenPosts
, originalRequest(), NULL
);
2357 if (ch
.fastCheck() != ACCESS_ALLOWED
) {
2358 debugs(11, 5, HERE
<< "didn't match brokenPosts");
2362 if (!Comm::IsConnOpen(serverConnection
)) {
2363 debugs(11, 3, HERE
<< "ignoring broken POST for closed " << serverConnection
);
2364 assert(closeHandler
!= NULL
);
2365 return true; // prevent caller from proceeding as if nothing happened
2368 debugs(11, 3, "finishingBrokenPost: fixing broken POST");
2369 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
2370 requestSender
= JobCallback(11,5,
2371 Dialer
, this, HttpStateData::wroteLast
);
2372 Comm::Write(serverConnection
, "\r\n", 2, requestSender
, NULL
);
2376 #endif /* USE_HTTP_VIOLATIONS */
2379 /// if needed, write last-chunk to end the request body and return true
2381 HttpStateData::finishingChunkedRequest()
2383 if (flags
.sentLastChunk
) {
2384 debugs(11, 5, HERE
<< "already sent last-chunk");
2388 Must(receivedWholeRequestBody
); // or we should not be sending last-chunk
2389 flags
.sentLastChunk
= true;
2391 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
2392 requestSender
= JobCallback(11,5, Dialer
, this, HttpStateData::wroteLast
);
2393 Comm::Write(serverConnection
, "0\r\n\r\n", 5, requestSender
, NULL
);
2398 HttpStateData::doneSendingRequestBody()
2400 Client::doneSendingRequestBody();
2401 debugs(11,5, HERE
<< serverConnection
);
2403 // do we need to write something after the last body byte?
2404 if (flags
.chunked_request
&& finishingChunkedRequest())
2406 if (!flags
.chunked_request
&& finishingBrokenPost())
2412 // more origin request body data is available
2414 HttpStateData::handleMoreRequestBodyAvailable()
2416 if (eof
|| !Comm::IsConnOpen(serverConnection
)) {
2417 // XXX: we should check this condition in other callbacks then!
2418 // TODO: Check whether this can actually happen: We should unsubscribe
2419 // as a body consumer when the above condition(s) are detected.
2420 debugs(11, DBG_IMPORTANT
, HERE
<< "Transaction aborted while reading HTTP body");
2424 assert(requestBodySource
!= NULL
);
2426 if (requestBodySource
->buf().hasContent()) {
2427 // XXX: why does not this trigger a debug message on every request?
2429 if (flags
.headers_parsed
&& !flags
.abuse_detected
) {
2430 flags
.abuse_detected
= true;
2431 debugs(11, DBG_IMPORTANT
, "http handleMoreRequestBodyAvailable: Likely proxy abuse detected '" << request
->client_addr
<< "' -> '" << entry
->url() << "'" );
2433 if (virginReply()->sline
.status() == Http::scInvalidHeader
) {
2435 mustStop("HttpStateData::handleMoreRequestBodyAvailable");
2441 HttpStateData::handleMoreRequestBodyAvailable();
2444 // premature end of the request body
2446 HttpStateData::handleRequestBodyProducerAborted()
2448 Client::handleRequestBodyProducerAborted();
2449 if (entry
->isEmpty()) {
2450 debugs(11, 3, "request body aborted: " << serverConnection
);
2451 // We usually get here when ICAP REQMOD aborts during body processing.
2452 // We might also get here if client-side aborts, but then our response
2453 // should not matter because either client-side will provide its own or
2454 // there will be no response at all (e.g., if the the client has left).
2455 ErrorState
*err
= new ErrorState(ERR_ICAP_FAILURE
, Http::scInternalServerError
, fwd
->request
);
2456 err
->detailError(ERR_DETAIL_SRV_REQMOD_REQ_BODY
);
2460 abortTransaction("request body producer aborted");
2463 // called when we wrote request headers(!) or a part of the body
2465 HttpStateData::sentRequestBody(const CommIoCbParams
&io
)
2468 statCounter
.server
.http
.kbytes_out
+= io
.size
;
2470 Client::sentRequestBody(io
);
2474 HttpStateData::abortAll(const char *reason
)
2476 debugs(11,5, HERE
<< "aborting transaction for " << reason
<<
2477 "; " << serverConnection
<< ", this " << this);