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/StreamContext.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 mustStop("HttpStateData::httpStateConnClosed");
160 HttpStateData::httpTimeout(const CommTimeoutCbParams
&)
162 debugs(11, 4, serverConnection
<< ": '" << entry
->url() << "'");
164 if (entry
->store_status
== STORE_PENDING
) {
165 fwd
->fail(new ErrorState(ERR_READ_TIMEOUT
, Http::scGatewayTimeout
, fwd
->request
));
168 serverConnection
->close();
171 /// Remove an existing public store entry if the incoming response (to be
172 /// stored in a currently private entry) is going to invalidate it.
174 httpMaybeRemovePublic(StoreEntry
* e
, Http::StatusCode status
)
180 // If the incoming response already goes into a public entry, then there is
181 // nothing to remove. This protects ready-for-collapsing entries as well.
182 if (!EBIT_TEST(e
->flags
, KEY_PRIVATE
))
189 case Http::scNonAuthoritativeInformation
:
191 case Http::scMultipleChoices
:
193 case Http::scMovedPermanently
:
199 case Http::scNotFound
:
204 case Http::scForbidden
:
206 case Http::scMethodNotAllowed
:
213 case Http::scUnauthorized
:
223 * Any 2xx response should eject previously cached entities...
226 if (status
>= 200 && status
< 300)
234 if (!remove
&& !forbidden
)
239 if (e
->mem_obj
->request
)
240 pe
= storeGetPublicByRequest(e
->mem_obj
->request
);
242 pe
= storeGetPublic(e
->mem_obj
->storeId(), e
->mem_obj
->method
);
247 neighborsHtcpClear(e
, NULL
, e
->mem_obj
->request
, e
->mem_obj
->method
, HTCP_CLR_INVALIDATION
);
253 * Also remove any cached HEAD response in case the object has
256 if (e
->mem_obj
->request
)
257 pe
= storeGetPublicByRequestMethod(e
->mem_obj
->request
, Http::METHOD_HEAD
);
259 pe
= storeGetPublic(e
->mem_obj
->storeId(), Http::METHOD_HEAD
);
264 neighborsHtcpClear(e
, NULL
, e
->mem_obj
->request
, HttpRequestMethod(Http::METHOD_HEAD
), HTCP_CLR_INVALIDATION
);
271 HttpStateData::processSurrogateControl(HttpReply
*reply
)
273 if (request
->flags
.accelerated
&& reply
->surrogate_control
) {
274 HttpHdrScTarget
*sctusable
= reply
->surrogate_control
->getMergedTarget(Config
.Accel
.surrogate_id
);
277 if (sctusable
->noStore() ||
278 (Config
.onoff
.surrogate_is_remote
279 && sctusable
->noStoreRemote())) {
280 surrogateNoStore
= true;
281 entry
->makePrivate();
284 /* The HttpHeader logic cannot tell if the header it's parsing is a reply to an
285 * accelerated request or not...
286 * Still, this is an abstraction breach. - RC
288 if (sctusable
->hasMaxAge()) {
289 if (sctusable
->maxAge() < sctusable
->maxStale())
290 reply
->expires
= reply
->date
+ sctusable
->maxAge();
292 reply
->expires
= reply
->date
+ sctusable
->maxStale();
294 /* And update the timestamps */
295 entry
->timestampsSet();
298 /* We ignore cache-control directives as per the Surrogate specification */
299 ignoreCacheControl
= true;
307 HttpStateData::cacheableReply()
309 HttpReply
const *rep
= finalReply();
310 HttpHeader
const *hdr
= &rep
->header
;
312 #if USE_HTTP_VIOLATIONS
314 const RefreshPattern
*R
= NULL
;
316 /* This strange looking define first looks up the refresh pattern
317 * and then checks if the specified flag is set. The main purpose
318 * of this is to simplify the refresh pattern lookup and USE_HTTP_VIOLATIONS
321 #define REFRESH_OVERRIDE(flag) \
322 ((R = (R ? R : refreshLimits(entry->mem_obj->storeId()))) , \
323 (R && R->flags.flag))
325 #define REFRESH_OVERRIDE(flag) 0
328 if (EBIT_TEST(entry
->flags
, RELEASE_REQUEST
)) {
329 debugs(22, 3, "NO because " << *entry
<< " has been released.");
333 // Check for Surrogate/1.0 protocol conditions
334 // NP: reverse-proxy traffic our parent server has instructed us never to cache
335 if (surrogateNoStore
) {
336 debugs(22, 3, HERE
<< "NO because Surrogate-Control:no-store");
340 // RFC 2616: HTTP/1.1 Cache-Control conditions
341 if (!ignoreCacheControl
) {
342 // XXX: check to see if the request headers alone were enough to prevent caching earlier
343 // (ie no-store request header) no need to check those all again here if so.
344 // for now we are not reliably doing that so we waste CPU re-checking request CC
346 // RFC 2616 section 14.9.2 - MUST NOT cache any response with request CC:no-store
347 if (request
&& request
->cache_control
&& request
->cache_control
->noStore() &&
348 !REFRESH_OVERRIDE(ignore_no_store
)) {
349 debugs(22, 3, HERE
<< "NO because client request Cache-Control:no-store");
353 // NP: request CC:no-cache only means cache READ is forbidden. STORE is permitted.
354 if (rep
->cache_control
&& rep
->cache_control
->hasNoCache() && rep
->cache_control
->noCache().size() > 0) {
355 /* TODO: we are allowed to cache when no-cache= has parameters.
356 * Provided we strip away any of the listed headers unless they are revalidated
357 * successfully (ie, must revalidate AND these headers are prohibited on stale replies).
358 * That is a bit tricky for squid right now so we avoid caching entirely.
360 debugs(22, 3, HERE
<< "NO because server reply Cache-Control:no-cache has parameters");
364 // NP: request CC:private is undefined. We ignore.
365 // NP: other request CC flags are limiters on HIT/MISS. We don't care about here.
367 // RFC 2616 section 14.9.2 - MUST NOT cache any response with CC:no-store
368 if (rep
->cache_control
&& rep
->cache_control
->noStore() &&
369 !REFRESH_OVERRIDE(ignore_no_store
)) {
370 debugs(22, 3, HERE
<< "NO because server reply Cache-Control:no-store");
374 // RFC 2616 section 14.9.1 - MUST NOT cache any response with CC:private in a shared cache like Squid.
375 // CC:private overrides CC:public when both are present in a response.
376 // TODO: add a shared/private cache configuration possibility.
377 if (rep
->cache_control
&&
378 rep
->cache_control
->hasPrivate() &&
379 !REFRESH_OVERRIDE(ignore_private
)) {
380 /* TODO: we are allowed to cache when private= has parameters.
381 * Provided we strip away any of the listed headers unless they are revalidated
382 * successfully (ie, must revalidate AND these headers are prohibited on stale replies).
383 * That is a bit tricky for squid right now so we avoid caching entirely.
385 debugs(22, 3, HERE
<< "NO because server reply Cache-Control:private");
390 // RFC 2068, sec 14.9.4 - MUST NOT cache any response with Authentication UNLESS certain CC controls are present
391 // allow HTTP violations to IGNORE those controls (ie re-block caching Auth)
392 if (request
&& (request
->flags
.auth
|| request
->flags
.authSent
)) {
393 if (!rep
->cache_control
) {
394 debugs(22, 3, HERE
<< "NO because Authenticated and server reply missing Cache-Control");
398 if (ignoreCacheControl
) {
399 debugs(22, 3, HERE
<< "NO because Authenticated and ignoring Cache-Control");
403 bool mayStore
= false;
404 // HTTPbis pt6 section 3.2: a response CC:public is present
405 if (rep
->cache_control
->Public()) {
406 debugs(22, 3, HERE
<< "Authenticated but server reply Cache-Control:public");
409 // HTTPbis pt6 section 3.2: a response CC:must-revalidate is present
410 } else if (rep
->cache_control
->mustRevalidate()) {
411 debugs(22, 3, HERE
<< "Authenticated but server reply Cache-Control:must-revalidate");
414 #if USE_HTTP_VIOLATIONS
415 // NP: given the must-revalidate exception we should also be able to exempt no-cache.
416 // HTTPbis WG verdict on this is that it is omitted from the spec due to being 'unexpected' by
417 // some. The caching+revalidate is not exactly unsafe though with Squids interpretation of no-cache
418 // (without parameters) as equivalent to must-revalidate in the reply.
419 } else if (rep
->cache_control
->hasNoCache() && rep
->cache_control
->noCache().size() == 0) {
420 debugs(22, 3, HERE
<< "Authenticated but server reply Cache-Control:no-cache (equivalent to must-revalidate)");
424 // HTTPbis pt6 section 3.2: a response CC:s-maxage is present
425 } else if (rep
->cache_control
->sMaxAge()) {
426 debugs(22, 3, HERE
<< "Authenticated but server reply Cache-Control:s-maxage");
431 debugs(22, 3, HERE
<< "NO because Authenticated transaction");
435 // NP: response CC:no-cache is equivalent to CC:must-revalidate,max-age=0. We MAY cache, and do so.
436 // NP: other request CC flags are limiters on HIT/MISS/REFRESH. We don't care about here.
439 /* HACK: The "multipart/x-mixed-replace" content type is used for
440 * continuous push replies. These are generally dynamic and
441 * probably should not be cachable
443 if ((v
= hdr
->getStr(Http::HdrType::CONTENT_TYPE
)))
444 if (!strncasecmp(v
, "multipart/x-mixed-replace", 25)) {
445 debugs(22, 3, HERE
<< "NO because Content-Type:multipart/x-mixed-replace");
449 switch (rep
->sline
.status()) {
450 /* Responses that are cacheable */
454 case Http::scNonAuthoritativeInformation
:
456 case Http::scMultipleChoices
:
458 case Http::scMovedPermanently
:
459 case Http::scPermanentRedirect
:
463 * Don't cache objects that need to be refreshed on next request,
464 * unless we know how to refresh it.
467 if (!refreshIsCachable(entry
) && !REFRESH_OVERRIDE(store_stale
)) {
468 debugs(22, 3, "NO because refreshIsCachable() returned non-cacheable..");
471 debugs(22, 3, HERE
<< "YES because HTTP status " << rep
->sline
.status());
477 /* Responses that only are cacheable if the server says so */
480 case Http::scTemporaryRedirect
:
481 if (rep
->date
<= 0) {
482 debugs(22, 3, HERE
<< "NO because HTTP status " << rep
->sline
.status() << " and Date missing/invalid");
485 if (rep
->expires
> rep
->date
) {
486 debugs(22, 3, HERE
<< "YES because HTTP status " << rep
->sline
.status() << " and Expires > Date");
489 debugs(22, 3, HERE
<< "NO because HTTP status " << rep
->sline
.status() << " and Expires <= Date");
495 /* Errors can be negatively cached */
497 case Http::scNoContent
:
499 case Http::scUseProxy
:
501 case Http::scBadRequest
:
503 case Http::scForbidden
:
505 case Http::scNotFound
:
507 case Http::scMethodNotAllowed
:
509 case Http::scUriTooLong
:
511 case Http::scInternalServerError
:
513 case Http::scNotImplemented
:
515 case Http::scBadGateway
:
517 case Http::scServiceUnavailable
:
519 case Http::scGatewayTimeout
:
520 case Http::scMisdirectedRequest
:
522 debugs(22, 3, "MAYBE because HTTP status " << rep
->sline
.status());
528 /* Some responses can never be cached */
530 case Http::scPartialContent
: /* Not yet supported */
532 case Http::scSeeOther
:
534 case Http::scNotModified
:
536 case Http::scUnauthorized
:
538 case Http::scProxyAuthenticationRequired
:
540 case Http::scInvalidHeader
: /* Squid header parsing error */
542 case Http::scHeaderTooLarge
:
544 case Http::scPaymentRequired
:
545 case Http::scNotAcceptable
:
546 case Http::scRequestTimeout
:
547 case Http::scConflict
:
548 case Http::scLengthRequired
:
549 case Http::scPreconditionFailed
:
550 case Http::scPayloadTooLarge
:
551 case Http::scUnsupportedMediaType
:
552 case Http::scUnprocessableEntity
:
554 case Http::scFailedDependency
:
555 case Http::scInsufficientStorage
:
556 case Http::scRequestedRangeNotSatisfied
:
557 case Http::scExpectationFailed
:
559 debugs(22, 3, HERE
<< "NO because HTTP status " << rep
->sline
.status());
563 /* RFC 2616 section 6.1.1: an unrecognized response MUST NOT be cached. */
564 debugs (11, 3, HERE
<< "NO because unknown HTTP status code " << rep
->sline
.status());
575 * For Vary, store the relevant request headers as
576 * virtual headers in the reply
577 * Returns false if the variance cannot be stored
580 httpMakeVaryMark(HttpRequest
* request
, HttpReply
const * reply
)
583 const char *pos
= NULL
;
590 vary
= reply
->header
.getList(Http::HdrType::VARY
);
592 while (strListGetItem(&vary
, ',', &item
, &ilen
, &pos
)) {
593 static const SBuf
asterisk("*");
594 SBuf
name(item
, ilen
);
595 if (name
== asterisk
) {
600 strListAdd(&vstr
, name
.c_str(), ',');
601 hdr
= request
->header
.getByName(name
);
602 value
= hdr
.termedBuf();
604 value
= rfc1738_escape_part(value
);
605 vstr
.append("=\"", 2);
607 vstr
.append("\"", 1);
614 #if X_ACCELERATOR_VARY
617 vary
= reply
->header
.getList(Http::HdrType::HDR_X_ACCELERATOR_VARY
);
619 while (strListGetItem(&vary
, ',', &item
, &ilen
, &pos
)) {
620 char *name
= (char *)xmalloc(ilen
+ 1);
621 xstrncpy(name
, item
, ilen
+ 1);
623 strListAdd(&vstr
, name
, ',');
624 hdr
= request
->header
.getByName(name
);
626 value
= hdr
.termedBuf();
629 value
= rfc1738_escape_part(value
);
630 vstr
.append("=\"", 2);
632 vstr
.append("\"", 1);
641 debugs(11, 3, "httpMakeVaryMark: " << vstr
);
642 return vstr
.termedBuf();
646 HttpStateData::keepaliveAccounting(HttpReply
*reply
)
650 ++ _peer
->stats
.n_keepalives_sent
;
652 if (reply
->keep_alive
) {
654 ++ _peer
->stats
.n_keepalives_recv
;
656 if (Config
.onoff
.detect_broken_server_pconns
657 && reply
->bodySize(request
->method
) == -1 && !flags
.chunked
) {
658 debugs(11, DBG_IMPORTANT
, "keepaliveAccounting: Impossible keep-alive header from '" << entry
->url() << "'" );
659 // debugs(11, 2, "GOT HTTP REPLY HDR:\n---------\n" << readBuf->content() << "\n----------" );
660 flags
.keepalive_broken
= true;
666 HttpStateData::checkDateSkew(HttpReply
*reply
)
668 if (reply
->date
> -1 && !_peer
) {
669 int skew
= abs((int)(reply
->date
- squid_curtime
));
672 debugs(11, 3, "" << request
->url
.host() << "'s clock is skewed by " << skew
<< " seconds!");
677 * This creates the error page itself.. its likely
678 * that the forward ported reply header max size patch
679 * generates non http conformant error pages - in which
680 * case the errors where should be 'BAD_GATEWAY' etc
683 HttpStateData::processReplyHeader()
685 /** Creates a blank header. If this routine is made incremental, this will not do */
687 /* NP: all exit points to this function MUST call ctx_exit(ctx) */
688 Ctx ctx
= ctx_enter(entry
->mem_obj
->urlXXX());
690 debugs(11, 3, "processReplyHeader: key '" << entry
->getMD5Text() << "'");
692 assert(!flags
.headers_parsed
);
694 if (!inBuf
.length()) {
699 /* Attempt to parse the first line; this will define where the protocol, status, reason-phrase and header begin */
702 hp
= new Http1::ResponseParser
;
704 bool parsedOk
= hp
->parse(inBuf
);
706 // sync the buffers after parsing.
707 inBuf
= hp
->remaining();
709 if (hp
->needsMoreData()) {
710 if (eof
) { // no more data coming
711 /* Bug 2879: Replies may terminate with \r\n then EOF instead of \r\n\r\n.
712 * We also may receive truncated responses.
713 * Ensure here that we have at minimum two \r\n when EOF is seen.
715 inBuf
.append("\r\n\r\n", 4);
717 parsedOk
= hp
->parse(inBuf
);
718 // sync the buffers after parsing.
719 inBuf
= hp
->remaining();
721 debugs(33, 5, "Incomplete response, waiting for end of response headers");
728 // unrecoverable parsing error
729 debugs(11, 3, "Non-HTTP-compliant header:\n---------\n" << inBuf
<< "\n----------");
730 flags
.headers_parsed
= true;
731 HttpReply
*newrep
= new HttpReply
;
732 newrep
->sline
.set(Http::ProtocolVersion(), hp
->messageStatus());
733 HttpReply
*vrep
= setVirginReply(newrep
);
734 entry
->replaceHttpReply(vrep
);
735 // XXX: close the server connection ?
741 /* We know the whole response is in parser now */
742 debugs(11, 2, "HTTP Server " << serverConnection
);
743 debugs(11, 2, "HTTP Server RESPONSE:\n---------\n" <<
744 hp
->messageProtocol() << " " << hp
->messageStatus() << " " << hp
->reasonPhrase() << "\n" <<
748 // reset payload tracking to begin after message headers
749 payloadSeen
= inBuf
.length();
751 HttpReply
*newrep
= new HttpReply
;
752 // XXX: RFC 7230 indicates we MAY ignore the reason phrase,
753 // and use an empty string on unknown status.
754 // We do that now to avoid performance regression from using SBuf::c_str()
755 newrep
->sline
.set(Http::ProtocolVersion(1,1), hp
->messageStatus() /* , hp->reasonPhrase() */);
756 newrep
->sline
.protocol
= newrep
->sline
.version
.protocol
= hp
->messageProtocol().protocol
;
757 newrep
->sline
.version
.major
= hp
->messageProtocol().major
;
758 newrep
->sline
.version
.minor
= hp
->messageProtocol().minor
;
761 if (!newrep
->parseHeader(*hp
)) {
762 // XXX: when Http::ProtocolVersion is a function, remove this hack. just set with messageProtocol()
763 newrep
->sline
.set(Http::ProtocolVersion(), Http::scInvalidHeader
);
764 newrep
->sline
.version
.protocol
= hp
->messageProtocol().protocol
;
765 newrep
->sline
.version
.major
= hp
->messageProtocol().major
;
766 newrep
->sline
.version
.minor
= hp
->messageProtocol().minor
;
767 debugs(11, 2, "error parsing response headers mime block");
770 // done with Parser, now process using the HttpReply
773 newrep
->removeStaleWarnings();
775 if (newrep
->sline
.protocol
== AnyP::PROTO_HTTP
&& newrep
->sline
.status() >= 100 && newrep
->sline
.status() < 200) {
781 flags
.chunked
= false;
782 if (newrep
->sline
.protocol
== AnyP::PROTO_HTTP
&& newrep
->header
.chunked()) {
783 flags
.chunked
= true;
784 httpChunkDecoder
= new Http1::TeChunkedParser
;
787 if (!peerSupportsConnectionPinning())
788 request
->flags
.connectionAuthDisabled
= true;
790 HttpReply
*vrep
= setVirginReply(newrep
);
791 flags
.headers_parsed
= true;
793 keepaliveAccounting(vrep
);
797 processSurrogateControl (vrep
);
799 request
->hier
.peer_reply_status
= newrep
->sline
.status();
804 /// ignore or start forwarding the 1xx response (a.k.a., control message)
806 HttpStateData::handle1xx(HttpReply
*reply
)
808 HttpReply::Pointer
msg(reply
); // will destroy reply if unused
810 // one 1xx at a time: we must not be called while waiting for previous 1xx
811 Must(!flags
.handling1xx
);
812 flags
.handling1xx
= true;
814 if (!request
->canHandle1xx() || request
->forcedBodyContinuation
) {
815 debugs(11, 2, "ignoring 1xx because it is " << (request
->forcedBodyContinuation
? "already sent" : "not supported by client"));
820 #if USE_HTTP_VIOLATIONS
821 // check whether the 1xx response forwarding is allowed by squid.conf
822 if (Config
.accessList
.reply
) {
823 ACLFilledChecklist
ch(Config
.accessList
.reply
, originalRequest(), NULL
);
825 HTTPMSGLOCK(ch
.reply
);
826 if (ch
.fastCheck() != ACCESS_ALLOWED
) { // TODO: support slow lookups?
827 debugs(11, 3, HERE
<< "ignoring denied 1xx");
832 #endif // USE_HTTP_VIOLATIONS
834 debugs(11, 2, HERE
<< "forwarding 1xx to client");
836 // the Sink will use this to call us back after writing 1xx to the client
837 typedef NullaryMemFunT
<HttpStateData
> CbDialer
;
838 const AsyncCall::Pointer cb
= JobCallback(11, 3, CbDialer
, this,
839 HttpStateData::proceedAfter1xx
);
840 CallJobHere1(11, 4, request
->clientConnectionManager
, ConnStateData
,
841 ConnStateData::sendControlMsg
, HttpControlMsg(msg
, cb
));
842 // If the call is not fired, then the Sink is gone, and HttpStateData
843 // will terminate due to an aborted store entry or another similar error.
844 // If we get stuck, it is not handle1xx fault if we could get stuck
845 // for similar reasons without a 1xx response.
848 /// restores state and resumes processing after 1xx is ignored or forwarded
850 HttpStateData::proceedAfter1xx()
852 Must(flags
.handling1xx
);
853 debugs(11, 2, "continuing with " << payloadSeen
<< " bytes in buffer after 1xx");
854 CallJobHere(11, 3, this, HttpStateData
, HttpStateData::processReply
);
858 * returns true if the peer can support connection pinning
860 bool HttpStateData::peerSupportsConnectionPinning() const
862 const HttpReply
*rep
= entry
->mem_obj
->getReply();
863 const HttpHeader
*hdr
= &rep
->header
;
870 /*If this peer does not support connection pinning (authenticated
871 connections) return false
873 if (!_peer
->connection_auth
)
876 /*The peer supports connection pinning and the http reply status
877 is not unauthorized, so the related connection can be pinned
879 if (rep
->sline
.status() != Http::scUnauthorized
)
882 /*The server respond with Http::scUnauthorized and the peer configured
883 with "connection-auth=on" we know that the peer supports pinned
886 if (_peer
->connection_auth
== 1)
889 /*At this point peer has configured with "connection-auth=auto"
890 parameter so we need some extra checks to decide if we are going
891 to allow pinned connections or not
894 /*if the peer configured with originserver just allow connection
895 pinning (squid 2.6 behaviour)
897 if (_peer
->options
.originserver
)
900 /*if the connections it is already pinned it is OK*/
901 if (request
->flags
.pinned
)
904 /*Allow pinned connections only if the Proxy-support header exists in
905 reply and has in its list the "Session-Based-Authentication"
906 which means that the peer supports connection pinning.
908 if (!hdr
->has(Http::HdrType::PROXY_SUPPORT
))
911 header
= hdr
->getStrOrList(Http::HdrType::PROXY_SUPPORT
);
912 /* XXX This ought to be done in a case-insensitive manner */
913 rc
= (strstr(header
.termedBuf(), "Session-Based-Authentication") != NULL
);
918 // Called when we parsed (and possibly adapted) the headers but
919 // had not starting storing (a.k.a., sending) the body yet.
921 HttpStateData::haveParsedReplyHeaders()
923 Client::haveParsedReplyHeaders();
925 Ctx ctx
= ctx_enter(entry
->mem_obj
->urlXXX());
926 HttpReply
*rep
= finalReply();
928 entry
->timestampsSet();
930 /* Check if object is cacheable or not based on reply code */
931 debugs(11, 3, "HTTP CODE: " << rep
->sline
.status());
933 if (neighbors_do_private_keys
)
934 httpMaybeRemovePublic(entry
, rep
->sline
.status());
936 bool varyFailure
= false;
937 if (rep
->header
.has(Http::HdrType::VARY
)
938 #if X_ACCELERATOR_VARY
939 || rep
->header
.has(Http::HdrType::HDR_X_ACCELERATOR_VARY
)
942 const char *vary
= httpMakeVaryMark(request
, rep
);
945 entry
->makePrivate();
946 if (!fwd
->reforwardableStatus(rep
->sline
.status()))
947 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
950 entry
->mem_obj
->vary_headers
= xstrdup(vary
);
956 * If its not a reply that we will re-forward, then
957 * allow the client to get it.
959 if (!fwd
->reforwardableStatus(rep
->sline
.status()))
960 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
962 switch (cacheableReply()) {
969 entry
->makePrivate();
974 #if USE_HTTP_VIOLATIONS
975 if (Config
.negativeTtl
> 0)
976 entry
->cacheNegatively();
979 entry
->makePrivate();
988 if (!ignoreCacheControl
) {
989 if (rep
->cache_control
) {
990 // We are required to revalidate on many conditions.
991 // For security reasons we do so even if storage was caused by refresh_pattern ignore-* option
993 // CC:must-revalidate or CC:proxy-revalidate
994 const bool ccMustRevalidate
= (rep
->cache_control
->proxyRevalidate() || rep
->cache_control
->mustRevalidate());
996 // CC:no-cache (only if there are no parameters)
997 const bool ccNoCacheNoParams
= (rep
->cache_control
->hasNoCache() && rep
->cache_control
->noCache().size()==0);
1000 const bool ccSMaxAge
= rep
->cache_control
->hasSMaxAge();
1002 // CC:private (yes, these can sometimes be stored)
1003 const bool ccPrivate
= rep
->cache_control
->hasPrivate();
1005 if (ccMustRevalidate
|| ccNoCacheNoParams
|| ccSMaxAge
|| ccPrivate
)
1006 EBIT_SET(entry
->flags
, ENTRY_REVALIDATE
);
1008 #if USE_HTTP_VIOLATIONS // response header Pragma::no-cache is undefined in HTTP
1010 // Expensive calculation. So only do it IF the CC: header is not present.
1012 /* HACK: Pragma: no-cache in _replies_ is not documented in HTTP,
1013 * but servers like "Active Imaging Webcast/2.0" sure do use it */
1014 if (rep
->header
.has(Http::HdrType::PRAGMA
) &&
1015 rep
->header
.hasListMember(Http::HdrType::PRAGMA
,"no-cache",','))
1016 EBIT_SET(entry
->flags
, ENTRY_REVALIDATE
);
1022 headersLog(1, 0, request
->method
, rep
);
1029 HttpStateData::ConnectionStatus
1030 HttpStateData::statusIfComplete() const
1032 const HttpReply
*rep
= virginReply();
1034 * If the reply wants to close the connection, it takes precedence */
1036 if (httpHeaderHasConnDir(&rep
->header
, "close"))
1037 return COMPLETE_NONPERSISTENT_MSG
;
1040 * If we didn't send a keep-alive request header, then this
1041 * can not be a persistent connection.
1043 if (!flags
.keepalive
)
1044 return COMPLETE_NONPERSISTENT_MSG
;
1047 * If we haven't sent the whole request then this can not be a persistent
1050 if (!flags
.request_sent
) {
1051 debugs(11, 2, "Request not yet fully sent " << request
->method
<< ' ' << entry
->url());
1052 return COMPLETE_NONPERSISTENT_MSG
;
1056 * What does the reply have to say about keep-alive?
1060 * If the origin server (HTTP/1.0) does not send a keep-alive
1061 * header, but keeps the connection open anyway, what happens?
1062 * We'll return here and http.c waits for an EOF before changing
1063 * store_status to STORE_OK. Combine this with ENTRY_FWD_HDR_WAIT
1064 * and an error status code, and we might have to wait until
1065 * the server times out the socket.
1067 if (!rep
->keep_alive
)
1068 return COMPLETE_NONPERSISTENT_MSG
;
1070 return COMPLETE_PERSISTENT_MSG
;
1073 HttpStateData::ConnectionStatus
1074 HttpStateData::persistentConnStatus() const
1076 debugs(11, 3, HERE
<< serverConnection
<< " eof=" << eof
);
1077 if (eof
) // already reached EOF
1078 return COMPLETE_NONPERSISTENT_MSG
;
1080 /* If server fd is closing (but we have not been notified yet), stop Comm
1081 I/O to avoid assertions. TODO: Change Comm API to handle callers that
1082 want more I/O after async closing (usually initiated by others). */
1083 // XXX: add canReceive or s/canSend/canTalkToServer/
1084 if (!Comm::IsConnOpen(serverConnection
))
1085 return COMPLETE_NONPERSISTENT_MSG
;
1088 * In chunked response we do not know the content length but we are absolutely
1089 * sure about the end of response, so we are calling the statusIfComplete to
1090 * decide if we can be persistant
1092 if (lastChunk
&& flags
.chunked
)
1093 return statusIfComplete();
1095 const HttpReply
*vrep
= virginReply();
1096 debugs(11, 5, "persistentConnStatus: content_length=" << vrep
->content_length
);
1098 const int64_t clen
= vrep
->bodySize(request
->method
);
1100 debugs(11, 5, "persistentConnStatus: clen=" << clen
);
1102 /* If the body size is unknown we must wait for EOF */
1104 return INCOMPLETE_MSG
;
1107 * If the body size is known, we must wait until we've gotten all of it. */
1109 debugs(11,5, "payloadSeen=" << payloadSeen
<< " content_length=" << vrep
->content_length
);
1111 if (payloadSeen
< vrep
->content_length
)
1112 return INCOMPLETE_MSG
;
1114 if (payloadTruncated
> 0) // already read more than needed
1115 return COMPLETE_NONPERSISTENT_MSG
; // disable pconns
1119 * If there is no message body or we got it all, we can be persistent */
1120 return statusIfComplete();
1125 readDelayed(void *context
, CommRead
const &)
1127 HttpStateData
*state
= static_cast<HttpStateData
*>(context
);
1128 state
->flags
.do_next_read
= true;
1129 state
->maybeReadVirginBody();
1134 HttpStateData::readReply(const CommIoCbParams
&io
)
1136 Must(!flags
.do_next_read
); // XXX: should have been set false by mayReadVirginBody()
1137 flags
.do_next_read
= false;
1139 debugs(11, 5, io
.conn
);
1141 // Bail out early on Comm::ERR_CLOSING - close handlers will tidy up for us
1142 if (io
.flag
== Comm::ERR_CLOSING
) {
1143 debugs(11, 3, "http socket closing");
1147 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1148 abortTransaction("store entry aborted while reading reply");
1152 Must(Comm::IsConnOpen(serverConnection
));
1153 Must(io
.conn
->fd
== serverConnection
->fd
);
1156 * Don't reset the timeout value here. The value should be
1157 * counting Config.Timeout.request and applies to the request
1158 * as a whole, not individual read() calls.
1159 * Plus, it breaks our lame *HalfClosed() detection
1162 Must(maybeMakeSpaceAvailable(true));
1163 CommIoCbParams
rd(this); // will be expanded with ReadNow results
1165 rd
.size
= entry
->bytesWanted(Range
<size_t>(0, inBuf
.spaceSize()));
1168 assert(entry
->mem_obj
);
1170 /* read ahead limit */
1171 /* Perhaps these two calls should both live in MemObject */
1172 AsyncCall::Pointer nilCall
;
1173 if (!entry
->mem_obj
->readAheadPolicyCanRead()) {
1174 entry
->mem_obj
->delayRead(DeferredRead(readDelayed
, this, CommRead(io
.conn
, NULL
, 0, nilCall
)));
1178 /* delay id limit */
1179 entry
->mem_obj
->mostBytesAllowed().delayRead(DeferredRead(readDelayed
, this, CommRead(io
.conn
, NULL
, 0, nilCall
)));
1184 switch (Comm::ReadNow(rd
, inBuf
)) {
1185 case Comm::INPROGRESS
:
1186 if (inBuf
.isEmpty())
1187 debugs(33, 2, io
.conn
<< ": no data to process, " << xstrerr(rd
.xerrno
));
1188 flags
.do_next_read
= true;
1189 maybeReadVirginBody();
1194 payloadSeen
+= rd
.size
;
1196 DelayId delayId
= entry
->mem_obj
->mostBytesAllowed();
1197 delayId
.bytesIn(rd
.size
);
1200 statCounter
.server
.all
.kbytes_in
+= rd
.size
;
1201 statCounter
.server
.http
.kbytes_in
+= rd
.size
;
1202 ++ IOStats
.Http
.reads
;
1205 for (int clen
= rd
.size
- 1; clen
; ++bin
)
1208 ++ IOStats
.Http
.read_hist
[bin
];
1210 // update peer response time stats (%<pt)
1211 const timeval
&sent
= request
->hier
.peer_http_request_sent
;
1213 tvSub(request
->hier
.peer_response_time
, sent
, current_time
);
1215 request
->hier
.peer_response_time
.tv_sec
= -1;
1218 /* Continue to process previously read data */
1221 case Comm::ENDFILE
: // close detected by 0-byte read
1223 flags
.do_next_read
= false;
1225 /* Continue to process previously read data */
1228 // case Comm::COMM_ERROR:
1229 default: // no other flags should ever occur
1230 debugs(11, 2, io
.conn
<< ": read failure: " << xstrerr(rd
.xerrno
));
1231 ErrorState
*err
= new ErrorState(ERR_READ_ERROR
, Http::scBadGateway
, fwd
->request
);
1232 err
->xerrno
= rd
.xerrno
;
1234 flags
.do_next_read
= false;
1240 /* Process next response from buffer */
1244 /// processes the already read and buffered response data, possibly after
1245 /// waiting for asynchronous 1xx control message processing
1247 HttpStateData::processReply()
1250 if (flags
.handling1xx
) { // we came back after handling a 1xx response
1251 debugs(11, 5, HERE
<< "done with 1xx handling");
1252 flags
.handling1xx
= false;
1253 Must(!flags
.headers_parsed
);
1256 if (!flags
.headers_parsed
) { // have not parsed headers yet?
1257 PROF_start(HttpStateData_processReplyHeader
);
1258 processReplyHeader();
1259 PROF_stop(HttpStateData_processReplyHeader
);
1261 if (!continueAfterParsingHeader()) // parsing error or need more data
1262 return; // TODO: send errors to ICAP
1264 adaptOrFinalizeReply(); // may write to, abort, or "close" the entry
1267 // kick more reads if needed and/or process the response body, if any
1268 PROF_start(HttpStateData_processReplyBody
);
1269 processReplyBody(); // may call serverComplete()
1270 PROF_stop(HttpStateData_processReplyBody
);
1274 \retval true if we can continue with processing the body or doing ICAP.
1277 HttpStateData::continueAfterParsingHeader()
1279 if (flags
.handling1xx
) {
1280 debugs(11, 5, HERE
<< "wait for 1xx handling");
1281 Must(!flags
.headers_parsed
);
1285 if (!flags
.headers_parsed
&& !eof
) {
1286 debugs(11, 9, "needs more at " << inBuf
.length());
1287 flags
.do_next_read
= true;
1288 /** \retval false If we have not finished parsing the headers and may get more data.
1289 * Schedules more reads to retrieve the missing data.
1291 maybeReadVirginBody(); // schedules all kinds of reads; TODO: rename
1295 /** If we are done with parsing, check for errors */
1297 err_type error
= ERR_NONE
;
1299 if (flags
.headers_parsed
) { // parsed headers, possibly with errors
1300 // check for header parsing errors
1301 if (HttpReply
*vrep
= virginReply()) {
1302 const Http::StatusCode s
= vrep
->sline
.status();
1303 const AnyP::ProtocolVersion
&v
= vrep
->sline
.version
;
1304 if (s
== Http::scInvalidHeader
&& v
!= Http::ProtocolVersion(0,9)) {
1305 debugs(11, DBG_IMPORTANT
, "WARNING: HTTP: Invalid Response: Bad header encountered from " << entry
->url() << " AKA " << request
->url
);
1306 error
= ERR_INVALID_RESP
;
1307 } else if (s
== Http::scHeaderTooLarge
) {
1308 fwd
->dontRetry(true);
1309 error
= ERR_TOO_BIG
;
1310 } else if (vrep
->header
.conflictingContentLength()) {
1311 fwd
->dontRetry(true);
1312 error
= ERR_INVALID_RESP
;
1314 return true; // done parsing, got reply, and no error
1317 // parsed headers but got no reply
1318 debugs(11, DBG_IMPORTANT
, "WARNING: HTTP: Invalid Response: No reply at all for " << entry
->url() << " AKA " << request
->url
);
1319 error
= ERR_INVALID_RESP
;
1323 if (inBuf
.length()) {
1324 error
= ERR_INVALID_RESP
;
1325 debugs(11, DBG_IMPORTANT
, "WARNING: HTTP: Invalid Response: Headers did not parse at all for " << entry
->url() << " AKA " << request
->url
);
1327 error
= ERR_ZERO_SIZE_OBJECT
;
1328 debugs(11, (request
->flags
.accelerated
?DBG_IMPORTANT
:2), "WARNING: HTTP: Invalid Response: No object data received for " << entry
->url() << " AKA " << request
->url
);
1332 assert(error
!= ERR_NONE
);
1334 fwd
->fail(new ErrorState(error
, Http::scBadGateway
, fwd
->request
));
1335 flags
.do_next_read
= false;
1336 serverConnection
->close();
1337 return false; // quit on error
1340 /** truncate what we read if we read too much so that writeReplyBody()
1341 writes no more than what we should have read */
1343 HttpStateData::truncateVirginBody()
1345 assert(flags
.headers_parsed
);
1347 HttpReply
*vrep
= virginReply();
1349 if (!vrep
->expectingBody(request
->method
, clen
) || clen
< 0)
1350 return; // no body or a body of unknown size, including chunked
1352 if (payloadSeen
- payloadTruncated
<= clen
)
1353 return; // we did not read too much or already took care of the extras
1355 if (const int64_t extras
= payloadSeen
- payloadTruncated
- clen
) {
1356 // server sent more that the advertised content length
1357 debugs(11, 5, "payloadSeen=" << payloadSeen
<<
1358 " clen=" << clen
<< '/' << vrep
->content_length
<<
1359 " trucated=" << payloadTruncated
<< '+' << extras
);
1361 inBuf
.chop(0, inBuf
.length() - extras
);
1362 payloadTruncated
+= extras
;
1367 * Call this when there is data from the origin server
1368 * which should be sent to either StoreEntry, or to ICAP...
1371 HttpStateData::writeReplyBody()
1373 truncateVirginBody(); // if needed
1374 const char *data
= inBuf
.rawContent();
1375 int len
= inBuf
.length();
1376 addVirginReplyBody(data
, len
);
1381 HttpStateData::decodeAndWriteReplyBody()
1383 const char *data
= NULL
;
1385 bool wasThereAnException
= false;
1386 assert(flags
.chunked
);
1387 assert(httpChunkDecoder
);
1388 SQUID_ENTER_THROWING_CODE();
1391 httpChunkDecoder
->setPayloadBuffer(&decodedData
);
1392 const bool doneParsing
= httpChunkDecoder
->parse(inBuf
);
1393 inBuf
= httpChunkDecoder
->remaining(); // sync buffers after parse
1394 len
= decodedData
.contentSize();
1395 data
=decodedData
.content();
1396 addVirginReplyBody(data
, len
);
1399 flags
.do_next_read
= false;
1401 SQUID_EXIT_THROWING_CODE(wasThereAnException
);
1402 return wasThereAnException
;
1406 * processReplyBody has two purposes:
1407 * 1 - take the reply body data, if any, and put it into either
1408 * the StoreEntry, or give it over to ICAP.
1409 * 2 - see if we made it to the end of the response (persistent
1410 * connections and such)
1413 HttpStateData::processReplyBody()
1415 Ip::Address client_addr
;
1416 bool ispinned
= false;
1418 if (!flags
.headers_parsed
) {
1419 flags
.do_next_read
= true;
1420 maybeReadVirginBody();
1425 debugs(11,5, HERE
<< "adaptationAccessCheckPending=" << adaptationAccessCheckPending
);
1426 if (adaptationAccessCheckPending
)
1432 * At this point the reply headers have been parsed and consumed.
1433 * That means header content has been removed from readBuf and
1434 * it contains only body data.
1436 if (entry
->isAccepting()) {
1437 if (flags
.chunked
) {
1438 if (!decodeAndWriteReplyBody()) {
1439 flags
.do_next_read
= false;
1447 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1448 // The above writeReplyBody() call may have aborted the store entry.
1449 abortTransaction("store entry aborted while storing reply");
1452 switch (persistentConnStatus()) {
1453 case INCOMPLETE_MSG
: {
1454 debugs(11, 5, "processReplyBody: INCOMPLETE_MSG from " << serverConnection
);
1455 /* Wait for more data or EOF condition */
1456 AsyncCall::Pointer nil
;
1457 if (flags
.keepalive_broken
) {
1458 commSetConnTimeout(serverConnection
, 10, nil
);
1460 commSetConnTimeout(serverConnection
, Config
.Timeout
.read
, nil
);
1463 flags
.do_next_read
= true;
1467 case COMPLETE_PERSISTENT_MSG
:
1468 debugs(11, 5, "processReplyBody: COMPLETE_PERSISTENT_MSG from " << serverConnection
);
1469 /* yes we have to clear all these! */
1470 commUnsetConnTimeout(serverConnection
);
1471 flags
.do_next_read
= false;
1473 comm_remove_close_handler(serverConnection
->fd
, closeHandler
);
1474 closeHandler
= NULL
;
1475 fwd
->unregister(serverConnection
);
1477 if (request
->flags
.spoofClientIp
)
1478 client_addr
= request
->client_addr
;
1480 if (request
->flags
.pinned
) {
1482 } else if (request
->flags
.connectionAuth
&& request
->flags
.authSent
) {
1486 if (ispinned
&& request
->clientConnectionManager
.valid()) {
1487 request
->clientConnectionManager
->pinConnection(serverConnection
, request
, _peer
,
1488 (request
->flags
.connectionAuth
));
1490 fwd
->pconnPush(serverConnection
, request
->url
.host());
1493 serverConnection
= NULL
;
1497 case COMPLETE_NONPERSISTENT_MSG
:
1498 debugs(11, 5, "processReplyBody: COMPLETE_NONPERSISTENT_MSG from " << serverConnection
);
1503 maybeReadVirginBody();
1507 HttpStateData::mayReadVirginReplyBody() const
1509 // TODO: Be more precise here. For example, if/when reading trailer, we may
1510 // not be doneWithServer() yet, but we should return false. Similarly, we
1511 // could still be writing the request body after receiving the whole reply.
1512 return !doneWithServer();
1516 HttpStateData::maybeReadVirginBody()
1519 if (!Comm::IsConnOpen(serverConnection
) || fd_table
[serverConnection
->fd
].closing())
1522 if (!maybeMakeSpaceAvailable(false))
1525 // XXX: get rid of the do_next_read flag
1526 // check for the proper reasons preventing read(2)
1527 if (!flags
.do_next_read
)
1530 flags
.do_next_read
= false;
1532 // must not already be waiting for read(2) ...
1533 assert(!Comm::MonitorsRead(serverConnection
->fd
));
1535 // wait for read(2) to be possible.
1536 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
1537 AsyncCall::Pointer call
= JobCallback(11, 5, Dialer
, this, HttpStateData::readReply
);
1538 Comm::Read(serverConnection
, call
);
1542 HttpStateData::maybeMakeSpaceAvailable(bool doGrow
)
1544 // how much we are allowed to buffer
1545 const int limitBuffer
= (flags
.headers_parsed
? Config
.readAheadGap
: Config
.maxReplyHeaderSize
);
1547 if (limitBuffer
< 0 || inBuf
.length() >= (SBuf::size_type
)limitBuffer
) {
1548 // when buffer is at or over limit already
1549 debugs(11, 7, "wont read up to " << limitBuffer
<< ". buffer has (" << inBuf
.length() << "/" << inBuf
.spaceSize() << ") from " << serverConnection
);
1550 debugs(11, DBG_DATA
, "buffer has {" << inBuf
<< "}");
1551 // Process next response from buffer
1556 // how much we want to read
1557 const size_t read_size
= calcBufferSpaceToReserve(inBuf
.spaceSize(), (limitBuffer
- inBuf
.length()));
1560 debugs(11, 7, "wont read up to " << read_size
<< " into buffer (" << inBuf
.length() << "/" << inBuf
.spaceSize() << ") from " << serverConnection
);
1564 // just report whether we could grow or not, dont actually do it
1566 return (read_size
>= 2);
1568 // we may need to grow the buffer
1569 inBuf
.reserveSpace(read_size
);
1570 debugs(11, 8, (!flags
.do_next_read
? "wont" : "may") <<
1571 " read up to " << read_size
<< " bytes info buf(" << inBuf
.length() << "/" << inBuf
.spaceSize() <<
1572 ") from " << serverConnection
);
1574 return (inBuf
.spaceSize() >= 2); // only read if there is 1+ bytes of space available
1577 /// called after writing the very last request byte (body, last-chunk, etc)
1579 HttpStateData::wroteLast(const CommIoCbParams
&io
)
1581 debugs(11, 5, HERE
<< serverConnection
<< ": size " << io
.size
<< ": errflag " << io
.flag
<< ".");
1582 #if URL_CHECKSUM_DEBUG
1584 entry
->mem_obj
->checkUrlChecksum();
1588 fd_bytes(io
.fd
, io
.size
, FD_WRITE
);
1589 statCounter
.server
.all
.kbytes_out
+= io
.size
;
1590 statCounter
.server
.http
.kbytes_out
+= io
.size
;
1593 if (io
.flag
== Comm::ERR_CLOSING
)
1597 ErrorState
*err
= new ErrorState(ERR_WRITE_ERROR
, Http::scBadGateway
, fwd
->request
);
1598 err
->xerrno
= io
.xerrno
;
1600 serverConnection
->close();
1607 /// successfully wrote the entire request (including body, last-chunk, etc.)
1609 HttpStateData::sendComplete()
1612 * Set the read timeout here because it hasn't been set yet.
1613 * We only set the read timeout after the request has been
1614 * fully written to the peer. If we start the timeout
1615 * after connection establishment, then we are likely to hit
1616 * the timeout for POST/PUT requests that have very large
1619 typedef CommCbMemFunT
<HttpStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1620 AsyncCall::Pointer timeoutCall
= JobCallback(11, 5,
1621 TimeoutDialer
, this, HttpStateData::httpTimeout
);
1623 commSetConnTimeout(serverConnection
, Config
.Timeout
.read
, timeoutCall
);
1624 flags
.request_sent
= true;
1625 request
->hier
.peer_http_request_sent
= current_time
;
1628 // Close the HTTP server connection. Used by serverComplete().
1630 HttpStateData::closeServer()
1632 debugs(11,5, HERE
<< "closing HTTP server " << serverConnection
<< " this " << this);
1634 if (Comm::IsConnOpen(serverConnection
)) {
1635 fwd
->unregister(serverConnection
);
1636 comm_remove_close_handler(serverConnection
->fd
, closeHandler
);
1637 closeHandler
= NULL
;
1638 serverConnection
->close();
1643 HttpStateData::doneWithServer() const
1645 return !Comm::IsConnOpen(serverConnection
);
1649 * Fixup authentication request headers for special cases
1652 httpFixupAuthentication(HttpRequest
* request
, const HttpHeader
* hdr_in
, HttpHeader
* hdr_out
, const HttpStateFlags
&flags
)
1654 Http::HdrType header
= flags
.originpeer
? Http::HdrType::AUTHORIZATION
: Http::HdrType::PROXY_AUTHORIZATION
;
1656 /* Nothing to do unless we are forwarding to a peer */
1657 if (!request
->flags
.proxying
)
1660 /* Needs to be explicitly enabled */
1661 if (!request
->peer_login
)
1664 /* Maybe already dealt with? */
1665 if (hdr_out
->has(header
))
1668 /* Nothing to do here for PASSTHRU */
1669 if (strcmp(request
->peer_login
, "PASSTHRU") == 0)
1672 /* PROXYPASS is a special case, single-signon to servers with the proxy password (basic only) */
1673 if (flags
.originpeer
&& strcmp(request
->peer_login
, "PROXYPASS") == 0 && hdr_in
->has(Http::HdrType::PROXY_AUTHORIZATION
)) {
1674 const char *auth
= hdr_in
->getStr(Http::HdrType::PROXY_AUTHORIZATION
);
1676 if (auth
&& strncasecmp(auth
, "basic ", 6) == 0) {
1677 hdr_out
->putStr(header
, auth
);
1682 uint8_t loginbuf
[base64_encode_len(MAX_LOGIN_SZ
)];
1684 struct base64_encode_ctx ctx
;
1685 base64_encode_init(&ctx
);
1687 /* Special mode to pass the username to the upstream cache */
1688 if (*request
->peer_login
== '*') {
1689 const char *username
= "-";
1691 if (request
->extacl_user
.size())
1692 username
= request
->extacl_user
.termedBuf();
1694 else if (request
->auth_user_request
!= NULL
)
1695 username
= request
->auth_user_request
->username();
1698 blen
= base64_encode_update(&ctx
, loginbuf
, strlen(username
), reinterpret_cast<const uint8_t*>(username
));
1699 blen
+= base64_encode_update(&ctx
, loginbuf
+blen
, strlen(request
->peer_login
+1), reinterpret_cast<const uint8_t*>(request
->peer_login
+1));
1700 blen
+= base64_encode_final(&ctx
, loginbuf
+blen
);
1701 httpHeaderPutStrf(hdr_out
, header
, "Basic %.*s", (int)blen
, loginbuf
);
1705 /* external_acl provided credentials */
1706 if (request
->extacl_user
.size() && request
->extacl_passwd
.size() &&
1707 (strcmp(request
->peer_login
, "PASS") == 0 ||
1708 strcmp(request
->peer_login
, "PROXYPASS") == 0)) {
1710 blen
= base64_encode_update(&ctx
, loginbuf
, request
->extacl_user
.size(), reinterpret_cast<const uint8_t*>(request
->extacl_user
.rawBuf()));
1711 blen
+= base64_encode_update(&ctx
, loginbuf
+blen
, 1, reinterpret_cast<const uint8_t*>(":"));
1712 blen
+= base64_encode_update(&ctx
, loginbuf
+blen
, request
->extacl_passwd
.size(), reinterpret_cast<const uint8_t*>(request
->extacl_passwd
.rawBuf()));
1713 blen
+= base64_encode_final(&ctx
, loginbuf
+blen
);
1714 httpHeaderPutStrf(hdr_out
, header
, "Basic %.*s", (int)blen
, loginbuf
);
1717 // if no external user credentials are available to fake authentication with PASS acts like PASSTHRU
1718 if (strcmp(request
->peer_login
, "PASS") == 0)
1721 /* Kerberos login to peer */
1722 #if HAVE_AUTH_MODULE_NEGOTIATE && HAVE_KRB5 && HAVE_GSSAPI
1723 if (strncmp(request
->peer_login
, "NEGOTIATE",strlen("NEGOTIATE")) == 0) {
1725 char *PrincipalName
=NULL
,*p
;
1726 int negotiate_flags
= 0;
1728 if ((p
=strchr(request
->peer_login
,':')) != NULL
) {
1731 if (request
->flags
.auth_no_keytab
) {
1732 negotiate_flags
|= PEER_PROXY_NEGOTIATE_NOKEYTAB
;
1734 Token
= peer_proxy_negotiate_auth(PrincipalName
, request
->peer_host
, negotiate_flags
);
1736 httpHeaderPutStrf(hdr_out
, header
, "Negotiate %s",Token
);
1740 #endif /* HAVE_KRB5 && HAVE_GSSAPI */
1742 blen
= base64_encode_update(&ctx
, loginbuf
, strlen(request
->peer_login
), reinterpret_cast<const uint8_t*>(request
->peer_login
));
1743 blen
+= base64_encode_final(&ctx
, loginbuf
+blen
);
1744 httpHeaderPutStrf(hdr_out
, header
, "Basic %.*s", (int)blen
, loginbuf
);
1749 * build request headers and append them to a given MemBuf
1750 * used by buildRequestPrefix()
1751 * note: initialised the HttpHeader, the caller is responsible for Clean()-ing
1754 HttpStateData::httpBuildRequestHeader(HttpRequest
* request
,
1756 const AccessLogEntryPointer
&al
,
1757 HttpHeader
* hdr_out
,
1758 const HttpStateFlags
&flags
)
1760 /* building buffer for complex strings */
1761 #define BBUF_SZ (MAX_URL+32)
1762 LOCAL_ARRAY(char, bbuf
, BBUF_SZ
);
1763 LOCAL_ARRAY(char, ntoabuf
, MAX_IPSTRLEN
);
1764 const HttpHeader
*hdr_in
= &request
->header
;
1765 const HttpHeaderEntry
*e
= NULL
;
1766 HttpHeaderPos pos
= HttpHeaderInitPos
;
1767 assert (hdr_out
->owner
== hoRequest
);
1769 /* use our IMS header if the cached entry has Last-Modified time */
1770 if (request
->lastmod
> -1)
1771 hdr_out
->putTime(Http::HdrType::IF_MODIFIED_SINCE
, request
->lastmod
);
1773 // Add our own If-None-Match field if the cached entry has a strong ETag.
1774 // copyOneHeaderFromClientsideRequestToUpstreamRequest() adds client ones.
1775 if (request
->etag
.size() > 0) {
1776 hdr_out
->addEntry(new HttpHeaderEntry(Http::HdrType::IF_NONE_MATCH
, NULL
,
1777 request
->etag
.termedBuf()));
1780 bool we_do_ranges
= decideIfWeDoRanges (request
);
1782 String
strConnection (hdr_in
->getList(Http::HdrType::CONNECTION
));
1784 while ((e
= hdr_in
->getEntry(&pos
)))
1785 copyOneHeaderFromClientsideRequestToUpstreamRequest(e
, strConnection
, request
, hdr_out
, we_do_ranges
, flags
);
1787 /* Abstraction break: We should interpret multipart/byterange responses
1788 * into offset-length data, and this works around our inability to do so.
1790 if (!we_do_ranges
&& request
->multipartRangeRequest()) {
1791 /* don't cache the result */
1792 request
->flags
.cachable
= false;
1793 /* pretend it's not a range request */
1794 request
->ignoreRange("want to request the whole object");
1795 request
->flags
.isRanged
= false;
1799 if (Config
.onoff
.via
) {
1801 strVia
= hdr_in
->getList(Http::HdrType::VIA
);
1802 snprintf(bbuf
, BBUF_SZ
, "%d.%d %s",
1803 request
->http_ver
.major
,
1804 request
->http_ver
.minor
, ThisCache
);
1805 strListAdd(&strVia
, bbuf
, ',');
1806 hdr_out
->putStr(Http::HdrType::VIA
, strVia
.termedBuf());
1810 if (request
->flags
.accelerated
) {
1811 /* Append Surrogate-Capabilities */
1812 String
strSurrogate(hdr_in
->getList(Http::HdrType::SURROGATE_CAPABILITY
));
1814 snprintf(bbuf
, BBUF_SZ
, "%s=\"Surrogate/1.0 ESI/1.0\"", Config
.Accel
.surrogate_id
);
1816 snprintf(bbuf
, BBUF_SZ
, "%s=\"Surrogate/1.0\"", Config
.Accel
.surrogate_id
);
1818 strListAdd(&strSurrogate
, bbuf
, ',');
1819 hdr_out
->putStr(Http::HdrType::SURROGATE_CAPABILITY
, strSurrogate
.termedBuf());
1822 /** \pre Handle X-Forwarded-For */
1823 if (strcmp(opt_forwarded_for
, "delete") != 0) {
1825 String strFwd
= hdr_in
->getList(Http::HdrType::X_FORWARDED_FOR
);
1827 if (strFwd
.size() > 65536/2) {
1828 // There is probably a forwarding loop with Via detection disabled.
1829 // If we do nothing, String will assert on overflow soon.
1830 // TODO: Terminate all transactions with huge XFF?
1833 static int warnedCount
= 0;
1834 if (warnedCount
++ < 100) {
1835 const SBuf
url(entry
? SBuf(entry
->url()) : request
->effectiveRequestUri());
1836 debugs(11, DBG_IMPORTANT
, "Warning: likely forwarding loop with " << url
);
1840 if (strcmp(opt_forwarded_for
, "on") == 0) {
1841 /** If set to ON - append client IP or 'unknown'. */
1842 if ( request
->client_addr
.isNoAddr() )
1843 strListAdd(&strFwd
, "unknown", ',');
1845 strListAdd(&strFwd
, request
->client_addr
.toStr(ntoabuf
, MAX_IPSTRLEN
), ',');
1846 } else if (strcmp(opt_forwarded_for
, "off") == 0) {
1847 /** If set to OFF - append 'unknown'. */
1848 strListAdd(&strFwd
, "unknown", ',');
1849 } else if (strcmp(opt_forwarded_for
, "transparent") == 0) {
1850 /** If set to TRANSPARENT - pass through unchanged. */
1851 } else if (strcmp(opt_forwarded_for
, "truncate") == 0) {
1852 /** If set to TRUNCATE - drop existing list and replace with client IP or 'unknown'. */
1853 if ( request
->client_addr
.isNoAddr() )
1856 strFwd
= request
->client_addr
.toStr(ntoabuf
, MAX_IPSTRLEN
);
1858 if (strFwd
.size() > 0)
1859 hdr_out
->putStr(Http::HdrType::X_FORWARDED_FOR
, strFwd
.termedBuf());
1861 /** If set to DELETE - do not copy through. */
1863 /* append Host if not there already */
1864 if (!hdr_out
->has(Http::HdrType::HOST
)) {
1865 if (request
->peer_domain
) {
1866 hdr_out
->putStr(Http::HdrType::HOST
, request
->peer_domain
);
1868 SBuf authority
= request
->url
.authority();
1869 hdr_out
->putStr(Http::HdrType::HOST
, authority
.c_str());
1873 /* append Authorization if known in URL, not in header and going direct */
1874 if (!hdr_out
->has(Http::HdrType::AUTHORIZATION
)) {
1875 if (!request
->flags
.proxying
&& !request
->url
.userInfo().isEmpty()) {
1876 static uint8_t result
[base64_encode_len(MAX_URL
*2)]; // should be big enough for a single URI segment
1877 struct base64_encode_ctx ctx
;
1878 base64_encode_init(&ctx
);
1879 size_t blen
= base64_encode_update(&ctx
, result
, request
->url
.userInfo().length(), reinterpret_cast<const uint8_t*>(request
->url
.userInfo().rawContent()));
1880 blen
+= base64_encode_final(&ctx
, result
+blen
);
1881 result
[blen
] = '\0';
1883 httpHeaderPutStrf(hdr_out
, Http::HdrType::AUTHORIZATION
, "Basic %.*s", (int)blen
, result
);
1887 /* Fixup (Proxy-)Authorization special cases. Plain relaying dealt with above */
1888 httpFixupAuthentication(request
, hdr_in
, hdr_out
, flags
);
1890 /* append Cache-Control, add max-age if not there already */
1892 HttpHdrCc
*cc
= hdr_in
->getCc();
1895 cc
= new HttpHdrCc();
1897 #if 0 /* see bug 2330 */
1898 /* Set no-cache if determined needed but not found */
1899 if (request
->flags
.nocache
)
1900 EBIT_SET(cc
->mask
, HttpHdrCcType::CC_NO_CACHE
);
1903 /* Add max-age only without no-cache */
1904 if (!cc
->hasMaxAge() && !cc
->hasNoCache()) {
1905 // XXX: performance regression. c_str() reallocates
1906 SBuf
tmp(request
->effectiveRequestUri());
1907 cc
->maxAge(getMaxAge(entry
? entry
->url() : tmp
.c_str()));
1910 /* Enforce sibling relations */
1911 if (flags
.only_if_cached
)
1912 cc
->onlyIfCached(true);
1919 /* maybe append Connection: keep-alive */
1920 if (flags
.keepalive
) {
1921 hdr_out
->putStr(Http::HdrType::CONNECTION
, "keep-alive");
1924 /* append Front-End-Https */
1925 if (flags
.front_end_https
) {
1926 if (flags
.front_end_https
== 1 || request
->url
.getScheme() == AnyP::PROTO_HTTPS
)
1927 hdr_out
->putStr(Http::HdrType::FRONT_END_HTTPS
, "On");
1930 if (flags
.chunked_request
) {
1931 // Do not just copy the original value so that if the client-side
1932 // starts decode other encodings, this code may remain valid.
1933 hdr_out
->putStr(Http::HdrType::TRANSFER_ENCODING
, "chunked");
1936 /* Now mangle the headers. */
1937 if (Config2
.onoff
.mangle_request_headers
)
1938 httpHdrMangleList(hdr_out
, request
, ROR_REQUEST
);
1940 if (Config
.request_header_add
&& !Config
.request_header_add
->empty())
1941 httpHdrAdd(hdr_out
, request
, al
, *Config
.request_header_add
);
1943 strConnection
.clean();
1947 * Decides whether a particular header may be cloned from the received Clients request
1948 * to our outgoing fetch request.
1951 copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry
*e
, const String strConnection
, const HttpRequest
* request
, HttpHeader
* hdr_out
, const int we_do_ranges
, const HttpStateFlags
&flags
)
1953 debugs(11, 5, "httpBuildRequestHeader: " << e
->name
<< ": " << e
->value
);
1957 /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid should not pass on. */
1959 case Http::HdrType::PROXY_AUTHORIZATION
:
1960 /** \par Proxy-Authorization:
1961 * Only pass on proxy authentication to peers for which
1962 * authentication forwarding is explicitly enabled
1964 if (!flags
.originpeer
&& flags
.proxying
&& request
->peer_login
&&
1965 (strcmp(request
->peer_login
, "PASS") == 0 ||
1966 strcmp(request
->peer_login
, "PROXYPASS") == 0 ||
1967 strcmp(request
->peer_login
, "PASSTHRU") == 0)) {
1968 hdr_out
->addEntry(e
->clone());
1972 /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid does not pass on. */
1974 case Http::HdrType::CONNECTION
: /** \par Connection: */
1975 case Http::HdrType::TE
: /** \par TE: */
1976 case Http::HdrType::KEEP_ALIVE
: /** \par Keep-Alive: */
1977 case Http::HdrType::PROXY_AUTHENTICATE
: /** \par Proxy-Authenticate: */
1978 case Http::HdrType::TRAILER
: /** \par Trailer: */
1979 case Http::HdrType::UPGRADE
: /** \par Upgrade: */
1980 case Http::HdrType::TRANSFER_ENCODING
: /** \par Transfer-Encoding: */
1983 /** \par OTHER headers I haven't bothered to track down yet. */
1985 case Http::HdrType::AUTHORIZATION
:
1986 /** \par WWW-Authorization:
1987 * Pass on WWW authentication */
1989 if (!flags
.originpeer
) {
1990 hdr_out
->addEntry(e
->clone());
1992 /** \note In accelerators, only forward authentication if enabled
1993 * (see also httpFixupAuthentication for special cases)
1995 if (request
->peer_login
&&
1996 (strcmp(request
->peer_login
, "PASS") == 0 ||
1997 strcmp(request
->peer_login
, "PASSTHRU") == 0 ||
1998 strcmp(request
->peer_login
, "PROXYPASS") == 0)) {
1999 hdr_out
->addEntry(e
->clone());
2005 case Http::HdrType::HOST
:
2007 * Normally Squid rewrites the Host: header.
2008 * However, there is one case when we don't: If the URL
2009 * went through our redirector and the admin configured
2010 * 'redir_rewrites_host' to be off.
2012 if (request
->peer_domain
)
2013 hdr_out
->putStr(Http::HdrType::HOST
, request
->peer_domain
);
2014 else if (request
->flags
.redirected
&& !Config
.onoff
.redir_rewrites_host
)
2015 hdr_out
->addEntry(e
->clone());
2017 SBuf authority
= request
->url
.authority();
2018 hdr_out
->putStr(Http::HdrType::HOST
, authority
.c_str());
2023 case Http::HdrType::IF_MODIFIED_SINCE
:
2024 /** \par If-Modified-Since:
2025 * append unless we added our own,
2026 * but only if cache_miss_revalidate is enabled, or
2027 * the request is not cacheable, or
2028 * the request contains authentication credentials.
2029 * \note at most one client's If-Modified-Since header can pass through
2031 // XXX: need to check and cleanup the auth case so cacheable auth requests get cached.
2032 if (hdr_out
->has(Http::HdrType::IF_MODIFIED_SINCE
))
2034 else if (Config
.onoff
.cache_miss_revalidate
|| !request
->flags
.cachable
|| request
->flags
.auth
)
2035 hdr_out
->addEntry(e
->clone());
2038 case Http::HdrType::IF_NONE_MATCH
:
2039 /** \par If-None-Match:
2040 * append if the wildcard '*' special case value is present, or
2041 * cache_miss_revalidate is disabled, or
2042 * the request is not cacheable in this proxy, or
2043 * the request contains authentication credentials.
2044 * \note this header lists a set of responses for the server to elide sending. Squid added values are extending that set.
2046 // XXX: need to check and cleanup the auth case so cacheable auth requests get cached.
2047 if (hdr_out
->hasListMember(Http::HdrType::IF_MATCH
, "*", ',') || Config
.onoff
.cache_miss_revalidate
|| !request
->flags
.cachable
|| request
->flags
.auth
)
2048 hdr_out
->addEntry(e
->clone());
2051 case Http::HdrType::MAX_FORWARDS
:
2052 /** \par Max-Forwards:
2053 * pass only on TRACE or OPTIONS requests */
2054 if (request
->method
== Http::METHOD_TRACE
|| request
->method
== Http::METHOD_OPTIONS
) {
2055 const int64_t hops
= e
->getInt64();
2058 hdr_out
->putInt64(Http::HdrType::MAX_FORWARDS
, hops
- 1);
2063 case Http::HdrType::VIA
:
2065 * If Via is disabled then forward any received header as-is.
2066 * Otherwise leave for explicit updated addition later. */
2068 if (!Config
.onoff
.via
)
2069 hdr_out
->addEntry(e
->clone());
2073 case Http::HdrType::RANGE
:
2075 case Http::HdrType::IF_RANGE
:
2077 case Http::HdrType::REQUEST_RANGE
:
2078 /** \par Range:, If-Range:, Request-Range:
2079 * Only pass if we accept ranges */
2081 hdr_out
->addEntry(e
->clone());
2085 case Http::HdrType::PROXY_CONNECTION
: // SHOULD ignore. But doing so breaks things.
2088 case Http::HdrType::CONTENT_LENGTH
:
2089 // pass through unless we chunk; also, keeping this away from default
2090 // prevents request smuggling via Connection: Content-Length tricks
2091 if (!flags
.chunked_request
)
2092 hdr_out
->addEntry(e
->clone());
2095 case Http::HdrType::X_FORWARDED_FOR
:
2097 case Http::HdrType::CACHE_CONTROL
:
2098 /** \par X-Forwarded-For:, Cache-Control:
2099 * handled specially by Squid, so leave off for now.
2100 * append these after the loop if needed */
2103 case Http::HdrType::FRONT_END_HTTPS
:
2104 /** \par Front-End-Https:
2105 * Pass thru only if peer is configured with front-end-https */
2106 if (!flags
.front_end_https
)
2107 hdr_out
->addEntry(e
->clone());
2113 * pass on all other header fields
2114 * which are NOT listed by the special Connection: header. */
2116 if (strConnection
.size()>0 && strListIsMember(&strConnection
, e
->name
.termedBuf(), ',')) {
2117 debugs(11, 2, "'" << e
->name
<< "' header cropped by Connection: definition");
2121 hdr_out
->addEntry(e
->clone());
2126 HttpStateData::decideIfWeDoRanges (HttpRequest
* request
)
2129 /* decide if we want to do Ranges ourselves
2130 * and fetch the whole object now)
2131 * We want to handle Ranges ourselves iff
2132 * - we can actually parse client Range specs
2133 * - the specs are expected to be simple enough (e.g. no out-of-order ranges)
2134 * - reply will be cachable
2135 * (If the reply will be uncachable we have to throw it away after
2136 * serving this request, so it is better to forward ranges to
2137 * the server and fetch only the requested content)
2140 int64_t roffLimit
= request
->getRangeOffsetLimit();
2142 if (NULL
== request
->range
|| !request
->flags
.cachable
2143 || request
->range
->offsetLimitExceeded(roffLimit
) || request
->flags
.connectionAuth
)
2146 debugs(11, 8, "decideIfWeDoRanges: range specs: " <<
2147 request
->range
<< ", cachable: " <<
2148 request
->flags
.cachable
<< "; we_do_ranges: " << result
);
2153 /* build request prefix and append it to a given MemBuf;
2154 * return the length of the prefix */
2156 HttpStateData::buildRequestPrefix(MemBuf
* mb
)
2158 const int offset
= mb
->size
;
2159 /* Uses a local httpver variable to print the HTTP label
2160 * since the HttpRequest may have an older version label.
2161 * XXX: This could create protocol bugs as the headers sent and
2162 * flow control should all be based on the HttpRequest version
2163 * not the one we are sending. Needs checking.
2165 const AnyP::ProtocolVersion httpver
= Http::ProtocolVersion();
2166 const SBuf
url(_peer
&& !_peer
->options
.originserver
? request
->effectiveRequestUri() : request
->url
.path());
2167 mb
->appendf(SQUIDSBUFPH
" " SQUIDSBUFPH
" %s/%d.%d\r\n",
2168 SQUIDSBUFPRINT(request
->method
.image()),
2169 SQUIDSBUFPRINT(url
),
2170 AnyP::ProtocolType_str
[httpver
.protocol
],
2171 httpver
.major
,httpver
.minor
);
2172 /* build and pack headers */
2174 HttpHeader
hdr(hoRequest
);
2175 httpBuildRequestHeader(request
, entry
, fwd
->al
, &hdr
, flags
);
2177 if (request
->flags
.pinned
&& request
->flags
.connectionAuth
)
2178 request
->flags
.authSent
= true;
2179 else if (hdr
.has(Http::HdrType::AUTHORIZATION
))
2180 request
->flags
.authSent
= true;
2185 /* append header terminator */
2186 mb
->append(crlf
, 2);
2187 return mb
->size
- offset
;
2190 /* This will be called when connect completes. Write request. */
2192 HttpStateData::sendRequest()
2196 debugs(11, 5, HERE
<< serverConnection
<< ", request " << request
<< ", this " << this << ".");
2198 if (!Comm::IsConnOpen(serverConnection
)) {
2199 debugs(11,3, HERE
<< "cannot send request to closing " << serverConnection
);
2200 assert(closeHandler
!= NULL
);
2204 typedef CommCbMemFunT
<HttpStateData
, CommTimeoutCbParams
> TimeoutDialer
;
2205 AsyncCall::Pointer timeoutCall
= JobCallback(11, 5,
2206 TimeoutDialer
, this, HttpStateData::httpTimeout
);
2207 commSetConnTimeout(serverConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
2208 flags
.do_next_read
= true;
2209 maybeReadVirginBody();
2211 if (request
->body_pipe
!= NULL
) {
2212 if (!startRequestBodyFlow()) // register to receive body data
2214 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
2215 requestSender
= JobCallback(11,5,
2216 Dialer
, this, HttpStateData::sentRequestBody
);
2218 Must(!flags
.chunked_request
);
2219 // use chunked encoding if we do not know the length
2220 if (request
->content_length
< 0)
2221 flags
.chunked_request
= true;
2223 assert(!requestBodySource
);
2224 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
2225 requestSender
= JobCallback(11,5,
2226 Dialer
, this, HttpStateData::wroteLast
);
2229 flags
.originpeer
= (_peer
!= NULL
&& _peer
->options
.originserver
);
2230 flags
.proxying
= (_peer
!= NULL
&& !flags
.originpeer
);
2233 * Is keep-alive okay for all request methods?
2235 if (request
->flags
.mustKeepalive
)
2236 flags
.keepalive
= true;
2237 else if (request
->flags
.pinned
)
2238 flags
.keepalive
= request
->persistent();
2239 else if (!Config
.onoff
.server_pconns
)
2240 flags
.keepalive
= false;
2241 else if (_peer
== NULL
)
2242 flags
.keepalive
= true;
2243 else if (_peer
->stats
.n_keepalives_sent
< 10)
2244 flags
.keepalive
= true;
2245 else if ((double) _peer
->stats
.n_keepalives_recv
/
2246 (double) _peer
->stats
.n_keepalives_sent
> 0.50)
2247 flags
.keepalive
= true;
2250 /*The old code here was
2251 if (neighborType(_peer, request->url) == PEER_SIBLING && ...
2252 which is equivalent to:
2253 if (neighborType(_peer, URL()) == PEER_SIBLING && ...
2255 if (((_peer->type == PEER_MULTICAST && p->options.mcast_siblings) ||
2256 _peer->type == PEER_SIBLINGS ) && _peer->options.allow_miss)
2257 flags.only_if_cached = 1;
2259 But I suppose it was a bug
2261 if (neighborType(_peer
, request
->url
) == PEER_SIBLING
&& !_peer
->options
.allow_miss
)
2262 flags
.only_if_cached
= true;
2264 flags
.front_end_https
= _peer
->front_end_https
;
2268 request
->peer_host
=_peer
?_peer
->host
:NULL
;
2269 buildRequestPrefix(&mb
);
2271 debugs(11, 2, "HTTP Server " << serverConnection
);
2272 debugs(11, 2, "HTTP Server REQUEST:\n---------\n" << mb
.buf
<< "\n----------");
2274 Comm::Write(serverConnection
, &mb
, requestSender
);
2279 HttpStateData::getMoreRequestBody(MemBuf
&buf
)
2281 // parent's implementation can handle the no-encoding case
2282 if (!flags
.chunked_request
)
2283 return Client::getMoreRequestBody(buf
);
2287 Must(requestBodySource
!= NULL
);
2288 if (!requestBodySource
->getMoreData(raw
))
2289 return false; // no request body bytes to chunk yet
2291 // optimization: pre-allocate buffer size that should be enough
2292 const mb_size_t rawDataSize
= raw
.contentSize();
2293 // we may need to send: hex-chunk-size CRLF raw-data CRLF last-chunk
2294 buf
.init(16 + 2 + rawDataSize
+ 2 + 5, raw
.max_capacity
);
2296 buf
.appendf("%x\r\n", static_cast<unsigned int>(rawDataSize
));
2297 buf
.append(raw
.content(), rawDataSize
);
2298 buf
.append("\r\n", 2);
2300 Must(rawDataSize
> 0); // we did not accidently created last-chunk above
2302 // Do not send last-chunk unless we successfully received everything
2303 if (receivedWholeRequestBody
) {
2304 Must(!flags
.sentLastChunk
);
2305 flags
.sentLastChunk
= true;
2306 buf
.append("0\r\n\r\n", 5);
2313 httpStart(FwdState
*fwd
)
2315 debugs(11, 3, fwd
->request
->method
<< ' ' << fwd
->entry
->url());
2316 AsyncJob::Start(new HttpStateData(fwd
));
2320 HttpStateData::start()
2322 if (!sendRequest()) {
2323 debugs(11, 3, "httpStart: aborted");
2324 mustStop("HttpStateData::start failed");
2328 ++ statCounter
.server
.all
.requests
;
2329 ++ statCounter
.server
.http
.requests
;
2332 * We used to set the read timeout here, but not any more.
2333 * Now its set in httpSendComplete() after the full request,
2334 * including request body, has been written to the server.
2338 /// if broken posts are enabled for the request, try to fix and return true
2340 HttpStateData::finishingBrokenPost()
2342 #if USE_HTTP_VIOLATIONS
2343 if (!Config
.accessList
.brokenPosts
) {
2344 debugs(11, 5, HERE
<< "No brokenPosts list");
2348 ACLFilledChecklist
ch(Config
.accessList
.brokenPosts
, originalRequest(), NULL
);
2349 if (ch
.fastCheck() != ACCESS_ALLOWED
) {
2350 debugs(11, 5, HERE
<< "didn't match brokenPosts");
2354 if (!Comm::IsConnOpen(serverConnection
)) {
2355 debugs(11, 3, HERE
<< "ignoring broken POST for closed " << serverConnection
);
2356 assert(closeHandler
!= NULL
);
2357 return true; // prevent caller from proceeding as if nothing happened
2360 debugs(11, 3, "finishingBrokenPost: fixing broken POST");
2361 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
2362 requestSender
= JobCallback(11,5,
2363 Dialer
, this, HttpStateData::wroteLast
);
2364 Comm::Write(serverConnection
, "\r\n", 2, requestSender
, NULL
);
2368 #endif /* USE_HTTP_VIOLATIONS */
2371 /// if needed, write last-chunk to end the request body and return true
2373 HttpStateData::finishingChunkedRequest()
2375 if (flags
.sentLastChunk
) {
2376 debugs(11, 5, HERE
<< "already sent last-chunk");
2380 Must(receivedWholeRequestBody
); // or we should not be sending last-chunk
2381 flags
.sentLastChunk
= true;
2383 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
2384 requestSender
= JobCallback(11,5, Dialer
, this, HttpStateData::wroteLast
);
2385 Comm::Write(serverConnection
, "0\r\n\r\n", 5, requestSender
, NULL
);
2390 HttpStateData::doneSendingRequestBody()
2392 Client::doneSendingRequestBody();
2393 debugs(11,5, HERE
<< serverConnection
);
2395 // do we need to write something after the last body byte?
2396 if (flags
.chunked_request
&& finishingChunkedRequest())
2398 if (!flags
.chunked_request
&& finishingBrokenPost())
2404 // more origin request body data is available
2406 HttpStateData::handleMoreRequestBodyAvailable()
2408 if (eof
|| !Comm::IsConnOpen(serverConnection
)) {
2409 // XXX: we should check this condition in other callbacks then!
2410 // TODO: Check whether this can actually happen: We should unsubscribe
2411 // as a body consumer when the above condition(s) are detected.
2412 debugs(11, DBG_IMPORTANT
, HERE
<< "Transaction aborted while reading HTTP body");
2416 assert(requestBodySource
!= NULL
);
2418 if (requestBodySource
->buf().hasContent()) {
2419 // XXX: why does not this trigger a debug message on every request?
2421 if (flags
.headers_parsed
&& !flags
.abuse_detected
) {
2422 flags
.abuse_detected
= true;
2423 debugs(11, DBG_IMPORTANT
, "http handleMoreRequestBodyAvailable: Likely proxy abuse detected '" << request
->client_addr
<< "' -> '" << entry
->url() << "'" );
2425 if (virginReply()->sline
.status() == Http::scInvalidHeader
) {
2426 serverConnection
->close();
2432 HttpStateData::handleMoreRequestBodyAvailable();
2435 // premature end of the request body
2437 HttpStateData::handleRequestBodyProducerAborted()
2439 Client::handleRequestBodyProducerAborted();
2440 if (entry
->isEmpty()) {
2441 debugs(11, 3, "request body aborted: " << serverConnection
);
2442 // We usually get here when ICAP REQMOD aborts during body processing.
2443 // We might also get here if client-side aborts, but then our response
2444 // should not matter because either client-side will provide its own or
2445 // there will be no response at all (e.g., if the the client has left).
2446 ErrorState
*err
= new ErrorState(ERR_ICAP_FAILURE
, Http::scInternalServerError
, fwd
->request
);
2447 err
->detailError(ERR_DETAIL_SRV_REQMOD_REQ_BODY
);
2451 abortTransaction("request body producer aborted");
2454 // called when we wrote request headers(!) or a part of the body
2456 HttpStateData::sentRequestBody(const CommIoCbParams
&io
)
2459 statCounter
.server
.http
.kbytes_out
+= io
.size
;
2461 Client::sentRequestBody(io
);
2464 // Quickly abort the transaction
2465 // TODO: destruction should be sufficient as the destructor should cleanup,
2466 // including canceling close handlers
2468 HttpStateData::abortTransaction(const char *reason
)
2470 debugs(11,5, HERE
<< "aborting transaction for " << reason
<<
2471 "; " << serverConnection
<< ", this " << this);
2473 if (Comm::IsConnOpen(serverConnection
)) {
2474 serverConnection
->close();
2478 fwd
->handleUnregisteredServerEnd();
2479 mustStop("HttpStateData::abortTransaction");