2 * Copyright (C) 1996-2017 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 "log/access_log.h"
46 #include "MemObject.h"
47 #include "neighbors.h"
48 #include "peer_proxy_negotiate_auth.h"
49 #include "profiler/Profiler.h"
51 #include "RefreshPattern.h"
53 #include "SquidConfig.h"
54 #include "SquidTime.h"
55 #include "StatCounters.h"
63 #include "auth/UserRequest.h"
66 #include "DelayPools.h"
69 #define SQUID_ENTER_THROWING_CODE() try {
70 #define SQUID_EXIT_THROWING_CODE(status) \
73 catch (const std::exception &e) { \
74 debugs (11, 1, "Exception error:" << e.what()); \
78 CBDATA_CLASS_INIT(HttpStateData
);
80 static const char *const crlf
= "\r\n";
82 static void httpMaybeRemovePublic(StoreEntry
*, Http::StatusCode
);
83 static void copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry
*e
, const String strConnection
, const HttpRequest
* request
,
84 HttpHeader
* hdr_out
, const int we_do_ranges
, const Http::StateFlags
&);
86 HttpStateData::HttpStateData(FwdState
*theFwdState
) :
87 AsyncJob("HttpStateData"),
90 httpChunkDecoder(NULL
),
95 debugs(11,5,HERE
<< "HttpStateData " << this << " created");
96 ignoreCacheControl
= false;
97 surrogateNoStore
= false;
98 serverConnection
= fwd
->serverConnection();
100 if (fwd
->serverConnection() != NULL
)
101 _peer
= cbdataReference(fwd
->serverConnection()->getPeer()); /* might be NULL */
104 request
->flags
.proxying
= true;
106 * This NEIGHBOR_PROXY_ONLY check probably shouldn't be here.
107 * We might end up getting the object from somewhere else if,
108 * for example, the request to this neighbor fails.
110 if (_peer
->options
.proxy_only
)
111 entry
->releaseRequest();
114 entry
->setNoDelay(_peer
->options
.no_delay
);
119 * register the handler to free HTTP state data when the FD closes
121 typedef CommCbMemFunT
<HttpStateData
, CommCloseCbParams
> Dialer
;
122 closeHandler
= JobCallback(9, 5, Dialer
, this, HttpStateData::httpStateConnClosed
);
123 comm_add_close_handler(serverConnection
->fd
, closeHandler
);
126 HttpStateData::~HttpStateData()
129 * don't forget that ~Client() gets called automatically
132 if (httpChunkDecoder
)
133 delete httpChunkDecoder
;
135 cbdataReferenceDone(_peer
);
137 debugs(11,5, HERE
<< "HttpStateData " << this << " destroyed; " << serverConnection
);
140 const Comm::ConnectionPointer
&
141 HttpStateData::dataConnection() const
143 return serverConnection
;
147 HttpStateData::httpStateConnClosed(const CommCloseCbParams
¶ms
)
149 debugs(11, 5, "httpStateFree: FD " << params
.fd
<< ", httpState=" << params
.data
);
150 doneWithFwd
= "httpStateConnClosed()"; // assume FwdState is monitoring too
151 mustStop("HttpStateData::httpStateConnClosed");
155 HttpStateData::httpTimeout(const CommTimeoutCbParams
&)
157 debugs(11, 4, serverConnection
<< ": '" << entry
->url() << "'");
159 if (entry
->store_status
== STORE_PENDING
) {
160 fwd
->fail(new ErrorState(ERR_READ_TIMEOUT
, Http::scGatewayTimeout
, fwd
->request
));
164 mustStop("HttpStateData::httpTimeout");
168 findPreviouslyCachedEntry(StoreEntry
*newEntry
) {
169 assert(newEntry
->mem_obj
);
170 return newEntry
->mem_obj
->request
?
171 storeGetPublicByRequest(newEntry
->mem_obj
->request
.getRaw()) :
172 storeGetPublic(newEntry
->mem_obj
->storeId(), newEntry
->mem_obj
->method
);
175 /// Remove an existing public store entry if the incoming response (to be
176 /// stored in a currently private entry) is going to invalidate it.
178 httpMaybeRemovePublic(StoreEntry
* e
, Http::StatusCode status
)
183 // If the incoming response already goes into a public entry, then there is
184 // nothing to remove. This protects ready-for-collapsing entries as well.
185 if (!EBIT_TEST(e
->flags
, KEY_PRIVATE
))
188 // If the new/incoming response cannot be stored, then it does not
189 // compete with the old stored response for the public key, and the
190 // old stored response should be left as is.
191 if (e
->mem_obj
->request
&& !e
->mem_obj
->request
->flags
.cachable
)
198 case Http::scNonAuthoritativeInformation
:
200 case Http::scMultipleChoices
:
202 case Http::scMovedPermanently
:
206 case Http::scSeeOther
:
210 case Http::scNotFound
:
215 case Http::scForbidden
:
217 case Http::scMethodNotAllowed
:
224 case Http::scUnauthorized
:
234 * Any 2xx response should eject previously cached entities...
237 if (status
>= 200 && status
< 300)
245 if (!remove
&& !forbidden
)
248 StoreEntry
*pe
= findPreviouslyCachedEntry(e
);
253 neighborsHtcpClear(e
, nullptr, e
->mem_obj
->request
.getRaw(), e
->mem_obj
->method
, HTCP_CLR_INVALIDATION
);
259 * Also remove any cached HEAD response in case the object has
262 if (e
->mem_obj
->request
)
263 pe
= storeGetPublicByRequestMethod(e
->mem_obj
->request
.getRaw(), Http::METHOD_HEAD
);
265 pe
= storeGetPublic(e
->mem_obj
->storeId(), Http::METHOD_HEAD
);
270 neighborsHtcpClear(e
, nullptr, e
->mem_obj
->request
.getRaw(), HttpRequestMethod(Http::METHOD_HEAD
), HTCP_CLR_INVALIDATION
);
277 HttpStateData::processSurrogateControl(HttpReply
*reply
)
279 if (request
->flags
.accelerated
&& reply
->surrogate_control
) {
280 HttpHdrScTarget
*sctusable
= reply
->surrogate_control
->getMergedTarget(Config
.Accel
.surrogate_id
);
283 if (sctusable
->hasNoStore() ||
284 (Config
.onoff
.surrogate_is_remote
285 && sctusable
->noStoreRemote())) {
286 surrogateNoStore
= true;
287 // Be conservative for now and make it non-shareable because
288 // there is no enough information here to make the decision.
289 entry
->makePrivate(false);
292 /* The HttpHeader logic cannot tell if the header it's parsing is a reply to an
293 * accelerated request or not...
294 * Still, this is an abstraction breach. - RC
296 if (sctusable
->hasMaxAge()) {
297 if (sctusable
->maxAge() < sctusable
->maxStale())
298 reply
->expires
= reply
->date
+ sctusable
->maxAge();
300 reply
->expires
= reply
->date
+ sctusable
->maxStale();
302 /* And update the timestamps */
303 entry
->timestampsSet();
306 /* We ignore cache-control directives as per the Surrogate specification */
307 ignoreCacheControl
= true;
314 HttpStateData::ReuseDecision::Answers
315 HttpStateData::reusableReply(HttpStateData::ReuseDecision
&decision
)
317 HttpReply
const *rep
= finalReply();
318 HttpHeader
const *hdr
= &rep
->header
;
320 #if USE_HTTP_VIOLATIONS
322 const RefreshPattern
*R
= NULL
;
324 /* This strange looking define first looks up the refresh pattern
325 * and then checks if the specified flag is set. The main purpose
326 * of this is to simplify the refresh pattern lookup and USE_HTTP_VIOLATIONS
329 #define REFRESH_OVERRIDE(flag) \
330 ((R = (R ? R : refreshLimits(entry->mem_obj->storeId()))) , \
331 (R && R->flags.flag))
333 #define REFRESH_OVERRIDE(flag) 0
336 if (EBIT_TEST(entry
->flags
, RELEASE_REQUEST
))
337 return decision
.make(ReuseDecision::reuseNot
, "the entry has been released");
339 // RFC 7234 section 4: a cache MUST use the most recent response
340 // (as determined by the Date header field)
341 // TODO: whether such responses could be shareable?
343 return decision
.make(ReuseDecision::reuseNot
, "the response has an older date header");
345 // Check for Surrogate/1.0 protocol conditions
346 // NP: reverse-proxy traffic our parent server has instructed us never to cache
347 if (surrogateNoStore
)
348 return decision
.make(ReuseDecision::reuseNot
, "Surrogate-Control:no-store");
350 // RFC 2616: HTTP/1.1 Cache-Control conditions
351 if (!ignoreCacheControl
) {
352 // XXX: check to see if the request headers alone were enough to prevent caching earlier
353 // (ie no-store request header) no need to check those all again here if so.
354 // for now we are not reliably doing that so we waste CPU re-checking request CC
356 // RFC 2616 section 14.9.2 - MUST NOT cache any response with request CC:no-store
357 if (request
&& request
->cache_control
&& request
->cache_control
->hasNoStore() &&
358 !REFRESH_OVERRIDE(ignore_no_store
))
359 return decision
.make(ReuseDecision::reuseNot
,
360 "client request Cache-Control:no-store");
362 // NP: request CC:no-cache only means cache READ is forbidden. STORE is permitted.
363 if (rep
->cache_control
&& rep
->cache_control
->hasNoCacheWithParameters()) {
364 /* TODO: we are allowed to cache when no-cache= has parameters.
365 * Provided we strip away any of the listed headers unless they are revalidated
366 * successfully (ie, must revalidate AND these headers are prohibited on stale replies).
367 * That is a bit tricky for squid right now so we avoid caching entirely.
369 return decision
.make(ReuseDecision::reuseNot
,
370 "server reply Cache-Control:no-cache has parameters");
373 // NP: request CC:private is undefined. We ignore.
374 // NP: other request CC flags are limiters on HIT/MISS. We don't care about here.
376 // RFC 2616 section 14.9.2 - MUST NOT cache any response with CC:no-store
377 if (rep
->cache_control
&& rep
->cache_control
->hasNoStore() &&
378 !REFRESH_OVERRIDE(ignore_no_store
))
379 return decision
.make(ReuseDecision::reuseNot
,
380 "server reply Cache-Control:no-store");
382 // RFC 2616 section 14.9.1 - MUST NOT cache any response with CC:private in a shared cache like Squid.
383 // CC:private overrides CC:public when both are present in a response.
384 // TODO: add a shared/private cache configuration possibility.
385 if (rep
->cache_control
&&
386 rep
->cache_control
->hasPrivate() &&
387 !REFRESH_OVERRIDE(ignore_private
)) {
388 /* TODO: we are allowed to cache when private= has parameters.
389 * Provided we strip away any of the listed headers unless they are revalidated
390 * successfully (ie, must revalidate AND these headers are prohibited on stale replies).
391 * That is a bit tricky for squid right now so we avoid caching entirely.
393 return decision
.make(ReuseDecision::reuseNot
,
394 "server reply Cache-Control:private");
398 // RFC 2068, sec 14.9.4 - MUST NOT cache any response with Authentication UNLESS certain CC controls are present
399 // allow HTTP violations to IGNORE those controls (ie re-block caching Auth)
400 if (request
&& (request
->flags
.auth
|| request
->flags
.authSent
)) {
401 if (!rep
->cache_control
)
402 return decision
.make(ReuseDecision::reuseNot
,
403 "authenticated and server reply missing Cache-Control");
405 if (ignoreCacheControl
)
406 return decision
.make(ReuseDecision::reuseNot
,
407 "authenticated and ignoring Cache-Control");
409 bool mayStore
= false;
410 // HTTPbis pt6 section 3.2: a response CC:public is present
411 if (rep
->cache_control
->hasPublic()) {
412 debugs(22, 3, HERE
<< "Authenticated but server reply Cache-Control:public");
415 // HTTPbis pt6 section 3.2: a response CC:must-revalidate is present
416 } else if (rep
->cache_control
->hasMustRevalidate()) {
417 debugs(22, 3, HERE
<< "Authenticated but server reply Cache-Control:must-revalidate");
420 #if USE_HTTP_VIOLATIONS
421 // NP: given the must-revalidate exception we should also be able to exempt no-cache.
422 // HTTPbis WG verdict on this is that it is omitted from the spec due to being 'unexpected' by
423 // some. The caching+revalidate is not exactly unsafe though with Squids interpretation of no-cache
424 // (without parameters) as equivalent to must-revalidate in the reply.
425 } else if (rep
->cache_control
->hasNoCacheWithoutParameters()) {
426 debugs(22, 3, HERE
<< "Authenticated but server reply Cache-Control:no-cache (equivalent to must-revalidate)");
430 // HTTPbis pt6 section 3.2: a response CC:s-maxage is present
431 } else if (rep
->cache_control
->hasSMaxAge()) {
432 debugs(22, 3, HERE
<< "Authenticated but server reply Cache-Control:s-maxage");
437 return decision
.make(ReuseDecision::reuseNot
, "authenticated transaction");
439 // NP: response CC:no-cache is equivalent to CC:must-revalidate,max-age=0. We MAY cache, and do so.
440 // NP: other request CC flags are limiters on HIT/MISS/REFRESH. We don't care about here.
443 /* HACK: The "multipart/x-mixed-replace" content type is used for
444 * continuous push replies. These are generally dynamic and
445 * probably should not be cachable
447 if ((v
= hdr
->getStr(Http::HdrType::CONTENT_TYPE
)))
448 if (!strncasecmp(v
, "multipart/x-mixed-replace", 25))
449 return decision
.make(ReuseDecision::reuseNot
, "Content-Type:multipart/x-mixed-replace");
451 // TODO: if possible, provide more specific message for each status code
452 static const char *shareableError
= "shareable error status code";
453 static const char *nonShareableError
= "non-shareable error status code";
454 ReuseDecision::Answers statusAnswer
= ReuseDecision::reuseNot
;
455 const char *statusReason
= nonShareableError
;
457 switch (rep
->sline
.status()) {
459 /* There are several situations when a non-cacheable response may be
460 * still shareable (e.g., among collapsed clients). We assume that these
461 * are 3xx and 5xx responses, indicating server problems and some of
462 * 4xx responses, common for all clients with a given cache key (e.g.,
463 * 404 Not Found or 414 URI Too Long). On the other hand, we should not
464 * share non-cacheable client-specific errors, such as 400 Bad Request
465 * or 406 Not Acceptable.
468 /* Responses that are cacheable */
472 case Http::scNonAuthoritativeInformation
:
474 case Http::scMultipleChoices
:
476 case Http::scMovedPermanently
:
477 case Http::scPermanentRedirect
:
481 * Don't cache objects that need to be refreshed on next request,
482 * unless we know how to refresh it.
485 if (refreshIsCachable(entry
) || REFRESH_OVERRIDE(store_stale
))
486 decision
.make(ReuseDecision::cachePositively
, "refresh check returned cacheable");
488 decision
.make(ReuseDecision::doNotCacheButShare
, "refresh check returned non-cacheable");
491 /* Responses that only are cacheable if the server says so */
494 case Http::scTemporaryRedirect
:
496 decision
.make(ReuseDecision::doNotCacheButShare
, "Date is missing/invalid");
497 else if (rep
->expires
> rep
->date
)
498 decision
.make(ReuseDecision::cachePositively
, "Expires > Date");
500 decision
.make(ReuseDecision::doNotCacheButShare
, "Expires <= Date");
503 /* These responses can be negatively cached. Most can also be shared. */
504 case Http::scNoContent
:
505 case Http::scUseProxy
:
506 case Http::scForbidden
:
507 case Http::scNotFound
:
508 case Http::scMethodNotAllowed
:
509 case Http::scUriTooLong
:
510 case Http::scInternalServerError
:
511 case Http::scNotImplemented
:
512 case Http::scBadGateway
:
513 case Http::scServiceUnavailable
:
514 case Http::scGatewayTimeout
:
515 case Http::scMisdirectedRequest
:
516 statusAnswer
= ReuseDecision::doNotCacheButShare
;
517 statusReason
= shareableError
;
518 // fall through to the actual decision making below
520 case Http::scBadRequest
: // no sharing; perhaps the server did not like something specific to this request
521 #if USE_HTTP_VIOLATIONS
522 if (Config
.negativeTtl
> 0)
523 decision
.make(ReuseDecision::cacheNegatively
, "Config.negativeTtl > 0");
526 decision
.make(statusAnswer
, statusReason
);
529 /* these responses can never be cached, some
530 of them can be shared though */
531 case Http::scSeeOther
:
532 case Http::scNotModified
:
533 case Http::scUnauthorized
:
534 case Http::scProxyAuthenticationRequired
:
535 case Http::scPaymentRequired
:
536 case Http::scInsufficientStorage
:
537 // TODO: use more specific reason for non-error status codes
538 decision
.make(ReuseDecision::doNotCacheButShare
, shareableError
);
541 case Http::scPartialContent
: /* Not yet supported. TODO: make shareable for suitable ranges */
542 case Http::scNotAcceptable
:
543 case Http::scRequestTimeout
: // TODO: is this shareable?
544 case Http::scConflict
: // TODO: is this shareable?
545 case Http::scLengthRequired
:
546 case Http::scPreconditionFailed
:
547 case Http::scPayloadTooLarge
:
548 case Http::scUnsupportedMediaType
:
549 case Http::scUnprocessableEntity
:
550 case Http::scLocked
: // TODO: is this shareable?
551 case Http::scFailedDependency
:
552 case Http::scRequestedRangeNotSatisfied
:
553 case Http::scExpectationFailed
:
554 case Http::scInvalidHeader
: /* Squid header parsing error */
555 case Http::scHeaderTooLarge
:
556 decision
.make(ReuseDecision::reuseNot
, nonShareableError
);
560 /* RFC 2616 section 6.1.1: an unrecognized response MUST NOT be cached. */
561 decision
.make(ReuseDecision::reuseNot
, "unknown status code");
565 return decision
.answer
;
568 /// assemble a variant key (vary-mark) from the given Vary header and HTTP request
570 assembleVaryKey(String
&vary
, SBuf
&vstr
, const HttpRequest
&request
)
572 static const SBuf
asterisk("*");
573 const char *pos
= nullptr;
574 const char *item
= nullptr;
577 while (strListGetItem(&vary
, ',', &item
, &ilen
, &pos
)) {
578 SBuf
name(item
, ilen
);
579 if (name
== asterisk
) {
585 vstr
.append(", ", 2);
587 String
hdr(request
.header
.getByName(name
));
588 const char *value
= hdr
.termedBuf();
590 value
= rfc1738_escape_part(value
);
591 vstr
.append("=\"", 2);
593 vstr
.append("\"", 1);
601 * For Vary, store the relevant request headers as
602 * virtual headers in the reply
603 * Returns an empty SBuf if the variance cannot be stored
606 httpMakeVaryMark(HttpRequest
* request
, HttpReply
const * reply
)
611 vary
= reply
->header
.getList(Http::HdrType::VARY
);
612 assembleVaryKey(vary
, vstr
, *request
);
614 #if X_ACCELERATOR_VARY
616 vary
= reply
->header
.getList(Http::HdrType::HDR_X_ACCELERATOR_VARY
);
617 assembleVaryKey(vary
, vstr
, *request
);
625 HttpStateData::keepaliveAccounting(HttpReply
*reply
)
629 ++ _peer
->stats
.n_keepalives_sent
;
631 if (reply
->keep_alive
) {
633 ++ _peer
->stats
.n_keepalives_recv
;
635 if (Config
.onoff
.detect_broken_server_pconns
636 && reply
->bodySize(request
->method
) == -1 && !flags
.chunked
) {
637 debugs(11, DBG_IMPORTANT
, "keepaliveAccounting: Impossible keep-alive header from '" << entry
->url() << "'" );
638 // debugs(11, 2, "GOT HTTP REPLY HDR:\n---------\n" << readBuf->content() << "\n----------" );
639 flags
.keepalive_broken
= true;
645 HttpStateData::checkDateSkew(HttpReply
*reply
)
647 if (reply
->date
> -1 && !_peer
) {
648 int skew
= abs((int)(reply
->date
- squid_curtime
));
651 debugs(11, 3, "" << request
->url
.host() << "'s clock is skewed by " << skew
<< " seconds!");
656 * This creates the error page itself.. its likely
657 * that the forward ported reply header max size patch
658 * generates non http conformant error pages - in which
659 * case the errors where should be 'BAD_GATEWAY' etc
662 HttpStateData::processReplyHeader()
664 /** Creates a blank header. If this routine is made incremental, this will not do */
666 /* NP: all exit points to this function MUST call ctx_exit(ctx) */
667 Ctx ctx
= ctx_enter(entry
->mem_obj
->urlXXX());
669 debugs(11, 3, "processReplyHeader: key '" << entry
->getMD5Text() << "'");
671 assert(!flags
.headers_parsed
);
673 if (!inBuf
.length()) {
678 /* Attempt to parse the first line; this will define where the protocol, status, reason-phrase and header begin */
681 hp
= new Http1::ResponseParser
;
683 bool parsedOk
= hp
->parse(inBuf
);
685 // sync the buffers after parsing.
686 inBuf
= hp
->remaining();
688 if (hp
->needsMoreData()) {
689 if (eof
) { // no more data coming
690 /* Bug 2879: Replies may terminate with \r\n then EOF instead of \r\n\r\n.
691 * We also may receive truncated responses.
692 * Ensure here that we have at minimum two \r\n when EOF is seen.
694 inBuf
.append("\r\n\r\n", 4);
696 parsedOk
= hp
->parse(inBuf
);
697 // sync the buffers after parsing.
698 inBuf
= hp
->remaining();
700 debugs(33, 5, "Incomplete response, waiting for end of response headers");
707 // unrecoverable parsing error
708 // TODO: Use Raw! XXX: inBuf no longer has the [beginning of the] malformed header.
709 debugs(11, 3, "Non-HTTP-compliant header:\n---------\n" << inBuf
<< "\n----------");
710 flags
.headers_parsed
= true;
711 HttpReply
*newrep
= new HttpReply
;
712 newrep
->sline
.set(Http::ProtocolVersion(), hp
->parseStatusCode
);
713 setVirginReply(newrep
);
719 /* We know the whole response is in parser now */
720 debugs(11, 2, "HTTP Server " << serverConnection
);
721 debugs(11, 2, "HTTP Server RESPONSE:\n---------\n" <<
722 hp
->messageProtocol() << " " << hp
->messageStatus() << " " << hp
->reasonPhrase() << "\n" <<
726 // reset payload tracking to begin after message headers
727 payloadSeen
= inBuf
.length();
729 HttpReply
*newrep
= new HttpReply
;
730 // XXX: RFC 7230 indicates we MAY ignore the reason phrase,
731 // and use an empty string on unknown status.
732 // We do that now to avoid performance regression from using SBuf::c_str()
733 newrep
->sline
.set(Http::ProtocolVersion(1,1), hp
->messageStatus() /* , hp->reasonPhrase() */);
734 newrep
->sline
.protocol
= newrep
->sline
.version
.protocol
= hp
->messageProtocol().protocol
;
735 newrep
->sline
.version
.major
= hp
->messageProtocol().major
;
736 newrep
->sline
.version
.minor
= hp
->messageProtocol().minor
;
739 if (!newrep
->parseHeader(*hp
)) {
740 // XXX: when Http::ProtocolVersion is a function, remove this hack. just set with messageProtocol()
741 newrep
->sline
.set(Http::ProtocolVersion(), Http::scInvalidHeader
);
742 newrep
->sline
.version
.protocol
= hp
->messageProtocol().protocol
;
743 newrep
->sline
.version
.major
= hp
->messageProtocol().major
;
744 newrep
->sline
.version
.minor
= hp
->messageProtocol().minor
;
745 debugs(11, 2, "error parsing response headers mime block");
748 // done with Parser, now process using the HttpReply
751 newrep
->sources
|= request
->url
.getScheme() == AnyP::PROTO_HTTPS
? Http::Message::srcHttps
: Http::Message::srcHttp
;
753 newrep
->removeStaleWarnings();
755 if (newrep
->sline
.protocol
== AnyP::PROTO_HTTP
&& newrep
->sline
.status() >= 100 && newrep
->sline
.status() < 200) {
761 flags
.chunked
= false;
762 if (newrep
->sline
.protocol
== AnyP::PROTO_HTTP
&& newrep
->header
.chunked()) {
763 flags
.chunked
= true;
764 httpChunkDecoder
= new Http1::TeChunkedParser
;
767 if (!peerSupportsConnectionPinning())
768 request
->flags
.connectionAuthDisabled
= true;
770 HttpReply
*vrep
= setVirginReply(newrep
);
771 flags
.headers_parsed
= true;
773 keepaliveAccounting(vrep
);
777 processSurrogateControl (vrep
);
779 request
->hier
.peer_reply_status
= newrep
->sline
.status();
784 /// ignore or start forwarding the 1xx response (a.k.a., control message)
786 HttpStateData::handle1xx(HttpReply
*reply
)
788 HttpReply::Pointer
msg(reply
); // will destroy reply if unused
790 // one 1xx at a time: we must not be called while waiting for previous 1xx
791 Must(!flags
.handling1xx
);
792 flags
.handling1xx
= true;
794 if (!request
->canHandle1xx() || request
->forcedBodyContinuation
) {
795 debugs(11, 2, "ignoring 1xx because it is " << (request
->forcedBodyContinuation
? "already sent" : "not supported by client"));
800 #if USE_HTTP_VIOLATIONS
801 // check whether the 1xx response forwarding is allowed by squid.conf
802 if (Config
.accessList
.reply
) {
803 ACLFilledChecklist
ch(Config
.accessList
.reply
, originalRequest().getRaw());
805 HTTPMSGLOCK(ch
.reply
);
806 if (!ch
.fastCheck().allowed()) { // TODO: support slow lookups?
807 debugs(11, 3, HERE
<< "ignoring denied 1xx");
812 #endif // USE_HTTP_VIOLATIONS
814 debugs(11, 2, HERE
<< "forwarding 1xx to client");
816 // the Sink will use this to call us back after writing 1xx to the client
817 typedef NullaryMemFunT
<HttpStateData
> CbDialer
;
818 const AsyncCall::Pointer cb
= JobCallback(11, 3, CbDialer
, this,
819 HttpStateData::proceedAfter1xx
);
820 CallJobHere1(11, 4, request
->clientConnectionManager
, ConnStateData
,
821 ConnStateData::sendControlMsg
, HttpControlMsg(msg
, cb
));
822 // If the call is not fired, then the Sink is gone, and HttpStateData
823 // will terminate due to an aborted store entry or another similar error.
824 // If we get stuck, it is not handle1xx fault if we could get stuck
825 // for similar reasons without a 1xx response.
828 /// restores state and resumes processing after 1xx is ignored or forwarded
830 HttpStateData::proceedAfter1xx()
832 Must(flags
.handling1xx
);
833 debugs(11, 2, "continuing with " << payloadSeen
<< " bytes in buffer after 1xx");
834 CallJobHere(11, 3, this, HttpStateData
, HttpStateData::processReply
);
838 * returns true if the peer can support connection pinning
841 HttpStateData::peerSupportsConnectionPinning() const
846 /*If this peer does not support connection pinning (authenticated
847 connections) return false
849 if (!_peer
->connection_auth
)
852 const HttpReplyPointer
rep(entry
->mem_obj
->getReply());
854 /*The peer supports connection pinning and the http reply status
855 is not unauthorized, so the related connection can be pinned
857 if (rep
->sline
.status() != Http::scUnauthorized
)
860 /*The server respond with Http::scUnauthorized and the peer configured
861 with "connection-auth=on" we know that the peer supports pinned
864 if (_peer
->connection_auth
== 1)
867 /*At this point peer has configured with "connection-auth=auto"
868 parameter so we need some extra checks to decide if we are going
869 to allow pinned connections or not
872 /*if the peer configured with originserver just allow connection
873 pinning (squid 2.6 behaviour)
875 if (_peer
->options
.originserver
)
878 /*if the connections it is already pinned it is OK*/
879 if (request
->flags
.pinned
)
882 /*Allow pinned connections only if the Proxy-support header exists in
883 reply and has in its list the "Session-Based-Authentication"
884 which means that the peer supports connection pinning.
886 if (rep
->header
.hasListMember(Http::HdrType::PROXY_SUPPORT
, "Session-Based-Authentication", ','))
892 // Called when we parsed (and possibly adapted) the headers but
893 // had not starting storing (a.k.a., sending) the body yet.
895 HttpStateData::haveParsedReplyHeaders()
897 Client::haveParsedReplyHeaders();
899 Ctx ctx
= ctx_enter(entry
->mem_obj
->urlXXX());
900 HttpReply
*rep
= finalReply();
901 const Http::StatusCode statusCode
= rep
->sline
.status();
903 entry
->timestampsSet();
905 /* Check if object is cacheable or not based on reply code */
906 debugs(11, 3, "HTTP CODE: " << statusCode
);
908 if (const StoreEntry
*oldEntry
= findPreviouslyCachedEntry(entry
))
909 sawDateGoBack
= rep
->olderThan(oldEntry
->getReply());
911 if (neighbors_do_private_keys
&& !sawDateGoBack
)
912 httpMaybeRemovePublic(entry
, rep
->sline
.status());
914 bool varyFailure
= false;
915 if (rep
->header
.has(Http::HdrType::VARY
)
916 #if X_ACCELERATOR_VARY
917 || rep
->header
.has(Http::HdrType::HDR_X_ACCELERATOR_VARY
)
920 const SBuf
vary(httpMakeVaryMark(request
.getRaw(), rep
));
922 if (vary
.isEmpty()) {
923 // TODO: check whether such responses are shareable.
924 // Do not share for now.
925 entry
->makePrivate(false);
926 if (!fwd
->reforwardableStatus(rep
->sline
.status()))
927 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
930 entry
->mem_obj
->vary_headers
= vary
;
932 // RFC 7231 section 7.1.4
933 // Vary:* can be cached, but has mandatory revalidation
934 static const SBuf
asterisk("*");
935 if (vary
== asterisk
)
936 EBIT_SET(entry
->flags
, ENTRY_REVALIDATE_ALWAYS
);
942 * If its not a reply that we will re-forward, then
943 * allow the client to get it.
945 if (!fwd
->reforwardableStatus(rep
->sline
.status()))
946 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
948 ReuseDecision
decision(entry
, statusCode
);
950 switch (reusableReply(decision
)) {
952 case ReuseDecision::reuseNot
:
953 entry
->makePrivate(false);
956 case ReuseDecision::cachePositively
:
960 case ReuseDecision::cacheNegatively
:
961 entry
->cacheNegatively();
964 case ReuseDecision::doNotCacheButShare
:
965 entry
->makePrivate(true);
972 debugs(11, 3, "decided: " << decision
);
975 if (!ignoreCacheControl
) {
976 if (rep
->cache_control
) {
977 // We are required to revalidate on many conditions.
978 // For security reasons we do so even if storage was caused by refresh_pattern ignore-* option
980 // CC:must-revalidate or CC:proxy-revalidate
981 const bool ccMustRevalidate
= (rep
->cache_control
->hasProxyRevalidate() || rep
->cache_control
->hasMustRevalidate());
983 // CC:no-cache (only if there are no parameters)
984 const bool ccNoCacheNoParams
= rep
->cache_control
->hasNoCacheWithoutParameters();
987 const bool ccSMaxAge
= rep
->cache_control
->hasSMaxAge();
989 // CC:private (yes, these can sometimes be stored)
990 const bool ccPrivate
= rep
->cache_control
->hasPrivate();
992 if (ccNoCacheNoParams
|| ccPrivate
)
993 EBIT_SET(entry
->flags
, ENTRY_REVALIDATE_ALWAYS
);
994 else if (ccMustRevalidate
|| ccSMaxAge
)
995 EBIT_SET(entry
->flags
, ENTRY_REVALIDATE_STALE
);
997 #if USE_HTTP_VIOLATIONS // response header Pragma::no-cache is undefined in HTTP
999 // Expensive calculation. So only do it IF the CC: header is not present.
1001 /* HACK: Pragma: no-cache in _replies_ is not documented in HTTP,
1002 * but servers like "Active Imaging Webcast/2.0" sure do use it */
1003 if (rep
->header
.has(Http::HdrType::PRAGMA
) &&
1004 rep
->header
.hasListMember(Http::HdrType::PRAGMA
,"no-cache",','))
1005 EBIT_SET(entry
->flags
, ENTRY_REVALIDATE_ALWAYS
);
1011 headersLog(1, 0, request
->method
, rep
);
1018 HttpStateData::ConnectionStatus
1019 HttpStateData::statusIfComplete() const
1021 const HttpReply
*rep
= virginReply();
1023 * If the reply wants to close the connection, it takes precedence */
1025 static SBuf
close("close", 5);
1026 if (httpHeaderHasConnDir(&rep
->header
, close
))
1027 return COMPLETE_NONPERSISTENT_MSG
;
1030 * If we didn't send a keep-alive request header, then this
1031 * can not be a persistent connection.
1033 if (!flags
.keepalive
)
1034 return COMPLETE_NONPERSISTENT_MSG
;
1037 * If we haven't sent the whole request then this can not be a persistent
1040 if (!flags
.request_sent
) {
1041 debugs(11, 2, "Request not yet fully sent " << request
->method
<< ' ' << entry
->url());
1042 return COMPLETE_NONPERSISTENT_MSG
;
1046 * What does the reply have to say about keep-alive?
1050 * If the origin server (HTTP/1.0) does not send a keep-alive
1051 * header, but keeps the connection open anyway, what happens?
1052 * We'll return here and http.c waits for an EOF before changing
1053 * store_status to STORE_OK. Combine this with ENTRY_FWD_HDR_WAIT
1054 * and an error status code, and we might have to wait until
1055 * the server times out the socket.
1057 if (!rep
->keep_alive
)
1058 return COMPLETE_NONPERSISTENT_MSG
;
1060 return COMPLETE_PERSISTENT_MSG
;
1063 HttpStateData::ConnectionStatus
1064 HttpStateData::persistentConnStatus() const
1066 debugs(11, 3, HERE
<< serverConnection
<< " eof=" << eof
);
1067 if (eof
) // already reached EOF
1068 return COMPLETE_NONPERSISTENT_MSG
;
1070 /* If server fd is closing (but we have not been notified yet), stop Comm
1071 I/O to avoid assertions. TODO: Change Comm API to handle callers that
1072 want more I/O after async closing (usually initiated by others). */
1073 // XXX: add canReceive or s/canSend/canTalkToServer/
1074 if (!Comm::IsConnOpen(serverConnection
))
1075 return COMPLETE_NONPERSISTENT_MSG
;
1078 * In chunked response we do not know the content length but we are absolutely
1079 * sure about the end of response, so we are calling the statusIfComplete to
1080 * decide if we can be persistant
1082 if (lastChunk
&& flags
.chunked
)
1083 return statusIfComplete();
1085 const HttpReply
*vrep
= virginReply();
1086 debugs(11, 5, "persistentConnStatus: content_length=" << vrep
->content_length
);
1088 const int64_t clen
= vrep
->bodySize(request
->method
);
1090 debugs(11, 5, "persistentConnStatus: clen=" << clen
);
1092 /* If the body size is unknown we must wait for EOF */
1094 return INCOMPLETE_MSG
;
1097 * If the body size is known, we must wait until we've gotten all of it. */
1099 debugs(11,5, "payloadSeen=" << payloadSeen
<< " content_length=" << vrep
->content_length
);
1101 if (payloadSeen
< vrep
->content_length
)
1102 return INCOMPLETE_MSG
;
1104 if (payloadTruncated
> 0) // already read more than needed
1105 return COMPLETE_NONPERSISTENT_MSG
; // disable pconns
1109 * If there is no message body or we got it all, we can be persistent */
1110 return statusIfComplete();
1114 readDelayed(void *context
, CommRead
const &)
1116 HttpStateData
*state
= static_cast<HttpStateData
*>(context
);
1117 state
->flags
.do_next_read
= true;
1118 state
->maybeReadVirginBody();
1122 HttpStateData::readReply(const CommIoCbParams
&io
)
1124 Must(!flags
.do_next_read
); // XXX: should have been set false by mayReadVirginBody()
1125 flags
.do_next_read
= false;
1127 debugs(11, 5, io
.conn
);
1129 // Bail out early on Comm::ERR_CLOSING - close handlers will tidy up for us
1130 if (io
.flag
== Comm::ERR_CLOSING
) {
1131 debugs(11, 3, "http socket closing");
1135 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1136 abortTransaction("store entry aborted while reading reply");
1140 Must(Comm::IsConnOpen(serverConnection
));
1141 Must(io
.conn
->fd
== serverConnection
->fd
);
1144 * Don't reset the timeout value here. The value should be
1145 * counting Config.Timeout.request and applies to the request
1146 * as a whole, not individual read() calls.
1147 * Plus, it breaks our lame *HalfClosed() detection
1150 Must(maybeMakeSpaceAvailable(true));
1151 CommIoCbParams
rd(this); // will be expanded with ReadNow results
1153 rd
.size
= entry
->bytesWanted(Range
<size_t>(0, inBuf
.spaceSize()));
1156 assert(entry
->mem_obj
);
1157 AsyncCall::Pointer nilCall
;
1158 entry
->mem_obj
->delayRead(DeferredRead(readDelayed
, this, CommRead(io
.conn
, NULL
, 0, nilCall
)));
1162 switch (Comm::ReadNow(rd
, inBuf
)) {
1163 case Comm::INPROGRESS
:
1164 if (inBuf
.isEmpty())
1165 debugs(33, 2, io
.conn
<< ": no data to process, " << xstrerr(rd
.xerrno
));
1166 flags
.do_next_read
= true;
1167 maybeReadVirginBody();
1172 payloadSeen
+= rd
.size
;
1174 DelayId delayId
= entry
->mem_obj
->mostBytesAllowed();
1175 delayId
.bytesIn(rd
.size
);
1178 statCounter
.server
.all
.kbytes_in
+= rd
.size
;
1179 statCounter
.server
.http
.kbytes_in
+= rd
.size
;
1180 ++ IOStats
.Http
.reads
;
1183 for (int clen
= rd
.size
- 1; clen
; ++bin
)
1186 ++ IOStats
.Http
.read_hist
[bin
];
1188 request
->hier
.notePeerRead();
1191 /* Continue to process previously read data */
1194 case Comm::ENDFILE
: // close detected by 0-byte read
1196 flags
.do_next_read
= false;
1198 /* Continue to process previously read data */
1201 // case Comm::COMM_ERROR:
1202 default: // no other flags should ever occur
1203 debugs(11, 2, io
.conn
<< ": read failure: " << xstrerr(rd
.xerrno
));
1204 ErrorState
*err
= new ErrorState(ERR_READ_ERROR
, Http::scBadGateway
, fwd
->request
);
1205 err
->xerrno
= rd
.xerrno
;
1207 flags
.do_next_read
= false;
1209 mustStop("HttpStateData::readReply");
1213 /* Process next response from buffer */
1217 /// processes the already read and buffered response data, possibly after
1218 /// waiting for asynchronous 1xx control message processing
1220 HttpStateData::processReply()
1223 if (flags
.handling1xx
) { // we came back after handling a 1xx response
1224 debugs(11, 5, HERE
<< "done with 1xx handling");
1225 flags
.handling1xx
= false;
1226 Must(!flags
.headers_parsed
);
1229 if (!flags
.headers_parsed
) { // have not parsed headers yet?
1230 PROF_start(HttpStateData_processReplyHeader
);
1231 processReplyHeader();
1232 PROF_stop(HttpStateData_processReplyHeader
);
1234 if (!continueAfterParsingHeader()) // parsing error or need more data
1235 return; // TODO: send errors to ICAP
1237 adaptOrFinalizeReply(); // may write to, abort, or "close" the entry
1240 // kick more reads if needed and/or process the response body, if any
1241 PROF_start(HttpStateData_processReplyBody
);
1242 processReplyBody(); // may call serverComplete()
1243 PROF_stop(HttpStateData_processReplyBody
);
1247 \retval true if we can continue with processing the body or doing ICAP.
1250 HttpStateData::continueAfterParsingHeader()
1252 if (flags
.handling1xx
) {
1253 debugs(11, 5, HERE
<< "wait for 1xx handling");
1254 Must(!flags
.headers_parsed
);
1258 if (!flags
.headers_parsed
&& !eof
) {
1259 debugs(11, 9, "needs more at " << inBuf
.length());
1260 flags
.do_next_read
= true;
1261 /** \retval false If we have not finished parsing the headers and may get more data.
1262 * Schedules more reads to retrieve the missing data.
1264 maybeReadVirginBody(); // schedules all kinds of reads; TODO: rename
1268 /** If we are done with parsing, check for errors */
1270 err_type error
= ERR_NONE
;
1272 if (flags
.headers_parsed
) { // parsed headers, possibly with errors
1273 // check for header parsing errors
1274 if (HttpReply
*vrep
= virginReply()) {
1275 const Http::StatusCode s
= vrep
->sline
.status();
1276 const AnyP::ProtocolVersion
&v
= vrep
->sline
.version
;
1277 if (s
== Http::scInvalidHeader
&& v
!= Http::ProtocolVersion(0,9)) {
1278 debugs(11, DBG_IMPORTANT
, "WARNING: HTTP: Invalid Response: Bad header encountered from " << entry
->url() << " AKA " << request
->url
);
1279 error
= ERR_INVALID_RESP
;
1280 } else if (s
== Http::scHeaderTooLarge
) {
1281 fwd
->dontRetry(true);
1282 error
= ERR_TOO_BIG
;
1283 } else if (vrep
->header
.conflictingContentLength()) {
1284 fwd
->dontRetry(true);
1285 error
= ERR_INVALID_RESP
;
1287 return true; // done parsing, got reply, and no error
1290 // parsed headers but got no reply
1291 debugs(11, DBG_IMPORTANT
, "WARNING: HTTP: Invalid Response: No reply at all for " << entry
->url() << " AKA " << request
->url
);
1292 error
= ERR_INVALID_RESP
;
1296 if (inBuf
.length()) {
1297 error
= ERR_INVALID_RESP
;
1298 debugs(11, DBG_IMPORTANT
, "WARNING: HTTP: Invalid Response: Headers did not parse at all for " << entry
->url() << " AKA " << request
->url
);
1300 error
= ERR_ZERO_SIZE_OBJECT
;
1301 debugs(11, (request
->flags
.accelerated
?DBG_IMPORTANT
:2), "WARNING: HTTP: Invalid Response: No object data received for " << entry
->url() << " AKA " << request
->url
);
1305 assert(error
!= ERR_NONE
);
1307 fwd
->fail(new ErrorState(error
, Http::scBadGateway
, fwd
->request
));
1308 flags
.do_next_read
= false;
1310 mustStop("HttpStateData::continueAfterParsingHeader");
1311 return false; // quit on error
1314 /** truncate what we read if we read too much so that writeReplyBody()
1315 writes no more than what we should have read */
1317 HttpStateData::truncateVirginBody()
1319 assert(flags
.headers_parsed
);
1321 HttpReply
*vrep
= virginReply();
1323 if (!vrep
->expectingBody(request
->method
, clen
) || clen
< 0)
1324 return; // no body or a body of unknown size, including chunked
1326 if (payloadSeen
- payloadTruncated
<= clen
)
1327 return; // we did not read too much or already took care of the extras
1329 if (const int64_t extras
= payloadSeen
- payloadTruncated
- clen
) {
1330 // server sent more that the advertised content length
1331 debugs(11, 5, "payloadSeen=" << payloadSeen
<<
1332 " clen=" << clen
<< '/' << vrep
->content_length
<<
1333 " trucated=" << payloadTruncated
<< '+' << extras
);
1335 inBuf
.chop(0, inBuf
.length() - extras
);
1336 payloadTruncated
+= extras
;
1341 * Call this when there is data from the origin server
1342 * which should be sent to either StoreEntry, or to ICAP...
1345 HttpStateData::writeReplyBody()
1347 truncateVirginBody(); // if needed
1348 const char *data
= inBuf
.rawContent();
1349 int len
= inBuf
.length();
1350 addVirginReplyBody(data
, len
);
1355 HttpStateData::decodeAndWriteReplyBody()
1357 const char *data
= NULL
;
1359 bool wasThereAnException
= false;
1360 assert(flags
.chunked
);
1361 assert(httpChunkDecoder
);
1362 SQUID_ENTER_THROWING_CODE();
1365 httpChunkDecoder
->setPayloadBuffer(&decodedData
);
1366 const bool doneParsing
= httpChunkDecoder
->parse(inBuf
);
1367 inBuf
= httpChunkDecoder
->remaining(); // sync buffers after parse
1368 len
= decodedData
.contentSize();
1369 data
=decodedData
.content();
1370 addVirginReplyBody(data
, len
);
1373 flags
.do_next_read
= false;
1375 SQUID_EXIT_THROWING_CODE(wasThereAnException
);
1376 return wasThereAnException
;
1380 * processReplyBody has two purposes:
1381 * 1 - take the reply body data, if any, and put it into either
1382 * the StoreEntry, or give it over to ICAP.
1383 * 2 - see if we made it to the end of the response (persistent
1384 * connections and such)
1387 HttpStateData::processReplyBody()
1389 if (!flags
.headers_parsed
) {
1390 flags
.do_next_read
= true;
1391 maybeReadVirginBody();
1396 debugs(11,5, HERE
<< "adaptationAccessCheckPending=" << adaptationAccessCheckPending
);
1397 if (adaptationAccessCheckPending
)
1403 * At this point the reply headers have been parsed and consumed.
1404 * That means header content has been removed from readBuf and
1405 * it contains only body data.
1407 if (entry
->isAccepting()) {
1408 if (flags
.chunked
) {
1409 if (!decodeAndWriteReplyBody()) {
1410 flags
.do_next_read
= false;
1418 // storing/sending methods like earlier adaptOrFinalizeReply() or
1419 // above writeReplyBody() may release/abort the store entry.
1420 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1421 // TODO: In some cases (e.g., 304), we should keep persistent conn open.
1422 // Detect end-of-reply (and, hence, pool our idle pconn) earlier (ASAP).
1423 abortTransaction("store entry aborted while storing reply");
1426 switch (persistentConnStatus()) {
1427 case INCOMPLETE_MSG
: {
1428 debugs(11, 5, "processReplyBody: INCOMPLETE_MSG from " << serverConnection
);
1429 /* Wait for more data or EOF condition */
1430 AsyncCall::Pointer nil
;
1431 if (flags
.keepalive_broken
) {
1432 commSetConnTimeout(serverConnection
, 10, nil
);
1434 commSetConnTimeout(serverConnection
, Config
.Timeout
.read
, nil
);
1437 flags
.do_next_read
= true;
1441 case COMPLETE_PERSISTENT_MSG
: {
1442 debugs(11, 5, "processReplyBody: COMPLETE_PERSISTENT_MSG from " << serverConnection
);
1444 // TODO: Remove serverConnectionSaved but preserve exception safety.
1446 commUnsetConnTimeout(serverConnection
);
1447 flags
.do_next_read
= false;
1449 comm_remove_close_handler(serverConnection
->fd
, closeHandler
);
1450 closeHandler
= NULL
;
1452 Ip::Address client_addr
; // XXX: Remove as unused. Why was it added?
1453 if (request
->flags
.spoofClientIp
)
1454 client_addr
= request
->client_addr
;
1456 auto serverConnectionSaved
= serverConnection
;
1457 fwd
->unregister(serverConnection
);
1458 serverConnection
= nullptr;
1460 bool ispinned
= false; // TODO: Rename to isOrShouldBePinned
1461 if (request
->flags
.pinned
) {
1463 } else if (request
->flags
.connectionAuth
&& request
->flags
.authSent
) {
1468 if (request
->clientConnectionManager
.valid()) {
1469 CallJobHere1(11, 4, request
->clientConnectionManager
,
1471 notePinnedConnectionBecameIdle
,
1472 ConnStateData::PinnedIdleContext(serverConnectionSaved
, request
));
1474 // must not pool/share ispinned connections, even orphaned ones
1475 serverConnectionSaved
->close();
1478 fwd
->pconnPush(serverConnectionSaved
, request
->url
.host());
1485 case COMPLETE_NONPERSISTENT_MSG
:
1486 debugs(11, 5, "processReplyBody: COMPLETE_NONPERSISTENT_MSG from " << serverConnection
);
1491 maybeReadVirginBody();
1495 HttpStateData::mayReadVirginReplyBody() const
1497 // TODO: Be more precise here. For example, if/when reading trailer, we may
1498 // not be doneWithServer() yet, but we should return false. Similarly, we
1499 // could still be writing the request body after receiving the whole reply.
1500 return !doneWithServer();
1504 HttpStateData::maybeReadVirginBody()
1507 if (!Comm::IsConnOpen(serverConnection
) || fd_table
[serverConnection
->fd
].closing())
1510 if (!maybeMakeSpaceAvailable(false))
1513 // XXX: get rid of the do_next_read flag
1514 // check for the proper reasons preventing read(2)
1515 if (!flags
.do_next_read
)
1518 flags
.do_next_read
= false;
1520 // must not already be waiting for read(2) ...
1521 assert(!Comm::MonitorsRead(serverConnection
->fd
));
1523 // wait for read(2) to be possible.
1524 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
1525 AsyncCall::Pointer call
= JobCallback(11, 5, Dialer
, this, HttpStateData::readReply
);
1526 Comm::Read(serverConnection
, call
);
1530 HttpStateData::maybeMakeSpaceAvailable(bool doGrow
)
1532 // how much we are allowed to buffer
1533 const int limitBuffer
= (flags
.headers_parsed
? Config
.readAheadGap
: Config
.maxReplyHeaderSize
);
1535 if (limitBuffer
< 0 || inBuf
.length() >= (SBuf::size_type
)limitBuffer
) {
1536 // when buffer is at or over limit already
1537 debugs(11, 7, "wont read up to " << limitBuffer
<< ". buffer has (" << inBuf
.length() << "/" << inBuf
.spaceSize() << ") from " << serverConnection
);
1538 debugs(11, DBG_DATA
, "buffer has {" << inBuf
<< "}");
1539 // Process next response from buffer
1544 // how much we want to read
1545 const size_t read_size
= calcBufferSpaceToReserve(inBuf
.spaceSize(), (limitBuffer
- inBuf
.length()));
1548 debugs(11, 7, "wont read up to " << read_size
<< " into buffer (" << inBuf
.length() << "/" << inBuf
.spaceSize() << ") from " << serverConnection
);
1552 // just report whether we could grow or not, dont actually do it
1554 return (read_size
>= 2);
1556 // we may need to grow the buffer
1557 inBuf
.reserveSpace(read_size
);
1558 debugs(11, 8, (!flags
.do_next_read
? "wont" : "may") <<
1559 " read up to " << read_size
<< " bytes info buf(" << inBuf
.length() << "/" << inBuf
.spaceSize() <<
1560 ") from " << serverConnection
);
1562 return (inBuf
.spaceSize() >= 2); // only read if there is 1+ bytes of space available
1565 /// called after writing the very last request byte (body, last-chunk, etc)
1567 HttpStateData::wroteLast(const CommIoCbParams
&io
)
1569 debugs(11, 5, HERE
<< serverConnection
<< ": size " << io
.size
<< ": errflag " << io
.flag
<< ".");
1570 #if URL_CHECKSUM_DEBUG
1572 entry
->mem_obj
->checkUrlChecksum();
1575 // XXX: Keep in sync with Client::sentRequestBody().
1576 // TODO: Extract common parts.
1579 fd_bytes(io
.fd
, io
.size
, FD_WRITE
);
1580 statCounter
.server
.all
.kbytes_out
+= io
.size
;
1581 statCounter
.server
.http
.kbytes_out
+= io
.size
;
1584 if (io
.flag
== Comm::ERR_CLOSING
)
1587 // both successful and failed writes affect response times
1588 request
->hier
.notePeerWrite();
1591 ErrorState
*err
= new ErrorState(ERR_WRITE_ERROR
, Http::scBadGateway
, fwd
->request
);
1592 err
->xerrno
= io
.xerrno
;
1595 mustStop("HttpStateData::wroteLast");
1602 /// successfully wrote the entire request (including body, last-chunk, etc.)
1604 HttpStateData::sendComplete()
1607 * Set the read timeout here because it hasn't been set yet.
1608 * We only set the read timeout after the request has been
1609 * fully written to the peer. If we start the timeout
1610 * after connection establishment, then we are likely to hit
1611 * the timeout for POST/PUT requests that have very large
1614 typedef CommCbMemFunT
<HttpStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1615 AsyncCall::Pointer timeoutCall
= JobCallback(11, 5,
1616 TimeoutDialer
, this, HttpStateData::httpTimeout
);
1618 commSetConnTimeout(serverConnection
, Config
.Timeout
.read
, timeoutCall
);
1619 flags
.request_sent
= true;
1623 HttpStateData::closeServer()
1625 debugs(11,5, HERE
<< "closing HTTP server " << serverConnection
<< " this " << this);
1627 if (Comm::IsConnOpen(serverConnection
)) {
1628 fwd
->unregister(serverConnection
);
1629 comm_remove_close_handler(serverConnection
->fd
, closeHandler
);
1630 closeHandler
= NULL
;
1631 serverConnection
->close();
1636 HttpStateData::doneWithServer() const
1638 return !Comm::IsConnOpen(serverConnection
);
1642 * Fixup authentication request headers for special cases
1645 httpFixupAuthentication(HttpRequest
* request
, const HttpHeader
* hdr_in
, HttpHeader
* hdr_out
, const Http::StateFlags
&flags
)
1647 Http::HdrType header
= flags
.originpeer
? Http::HdrType::AUTHORIZATION
: Http::HdrType::PROXY_AUTHORIZATION
;
1649 /* Nothing to do unless we are forwarding to a peer */
1650 if (!request
->flags
.proxying
)
1653 /* Needs to be explicitly enabled */
1654 if (!request
->peer_login
)
1657 /* Maybe already dealt with? */
1658 if (hdr_out
->has(header
))
1661 /* Nothing to do here for PASSTHRU */
1662 if (strcmp(request
->peer_login
, "PASSTHRU") == 0)
1665 /* PROXYPASS is a special case, single-signon to servers with the proxy password (basic only) */
1666 if (flags
.originpeer
&& strcmp(request
->peer_login
, "PROXYPASS") == 0 && hdr_in
->has(Http::HdrType::PROXY_AUTHORIZATION
)) {
1667 const char *auth
= hdr_in
->getStr(Http::HdrType::PROXY_AUTHORIZATION
);
1669 if (auth
&& strncasecmp(auth
, "basic ", 6) == 0) {
1670 hdr_out
->putStr(header
, auth
);
1675 char loginbuf
[base64_encode_len(MAX_LOGIN_SZ
)];
1677 struct base64_encode_ctx ctx
;
1678 base64_encode_init(&ctx
);
1680 /* Special mode to pass the username to the upstream cache */
1681 if (*request
->peer_login
== '*') {
1682 const char *username
= "-";
1684 if (request
->extacl_user
.size())
1685 username
= request
->extacl_user
.termedBuf();
1687 else if (request
->auth_user_request
!= NULL
)
1688 username
= request
->auth_user_request
->username();
1691 blen
= base64_encode_update(&ctx
, loginbuf
, strlen(username
), reinterpret_cast<const uint8_t*>(username
));
1692 blen
+= base64_encode_update(&ctx
, loginbuf
+blen
, strlen(request
->peer_login
+1), reinterpret_cast<const uint8_t*>(request
->peer_login
+1));
1693 blen
+= base64_encode_final(&ctx
, loginbuf
+blen
);
1694 httpHeaderPutStrf(hdr_out
, header
, "Basic %.*s", (int)blen
, loginbuf
);
1698 /* external_acl provided credentials */
1699 if (request
->extacl_user
.size() && request
->extacl_passwd
.size() &&
1700 (strcmp(request
->peer_login
, "PASS") == 0 ||
1701 strcmp(request
->peer_login
, "PROXYPASS") == 0)) {
1703 blen
= base64_encode_update(&ctx
, loginbuf
, request
->extacl_user
.size(), reinterpret_cast<const uint8_t*>(request
->extacl_user
.rawBuf()));
1704 blen
+= base64_encode_update(&ctx
, loginbuf
+blen
, 1, reinterpret_cast<const uint8_t*>(":"));
1705 blen
+= base64_encode_update(&ctx
, loginbuf
+blen
, request
->extacl_passwd
.size(), reinterpret_cast<const uint8_t*>(request
->extacl_passwd
.rawBuf()));
1706 blen
+= base64_encode_final(&ctx
, loginbuf
+blen
);
1707 httpHeaderPutStrf(hdr_out
, header
, "Basic %.*s", (int)blen
, loginbuf
);
1710 // if no external user credentials are available to fake authentication with PASS acts like PASSTHRU
1711 if (strcmp(request
->peer_login
, "PASS") == 0)
1714 /* Kerberos login to peer */
1715 #if HAVE_AUTH_MODULE_NEGOTIATE && HAVE_KRB5 && HAVE_GSSAPI
1716 if (strncmp(request
->peer_login
, "NEGOTIATE",strlen("NEGOTIATE")) == 0) {
1718 char *PrincipalName
=NULL
,*p
;
1719 int negotiate_flags
= 0;
1721 if ((p
=strchr(request
->peer_login
,':')) != NULL
) {
1724 if (request
->flags
.auth_no_keytab
) {
1725 negotiate_flags
|= PEER_PROXY_NEGOTIATE_NOKEYTAB
;
1727 Token
= peer_proxy_negotiate_auth(PrincipalName
, request
->peer_host
, negotiate_flags
);
1729 httpHeaderPutStrf(hdr_out
, header
, "Negotiate %s",Token
);
1733 #endif /* HAVE_KRB5 && HAVE_GSSAPI */
1735 blen
= base64_encode_update(&ctx
, loginbuf
, strlen(request
->peer_login
), reinterpret_cast<const uint8_t*>(request
->peer_login
));
1736 blen
+= base64_encode_final(&ctx
, loginbuf
+blen
);
1737 httpHeaderPutStrf(hdr_out
, header
, "Basic %.*s", (int)blen
, loginbuf
);
1742 * build request headers and append them to a given MemBuf
1743 * used by buildRequestPrefix()
1744 * note: initialised the HttpHeader, the caller is responsible for Clean()-ing
1747 HttpStateData::httpBuildRequestHeader(HttpRequest
* request
,
1749 const AccessLogEntryPointer
&al
,
1750 HttpHeader
* hdr_out
,
1751 const Http::StateFlags
&flags
)
1753 /* building buffer for complex strings */
1754 #define BBUF_SZ (MAX_URL+32)
1755 LOCAL_ARRAY(char, bbuf
, BBUF_SZ
);
1756 LOCAL_ARRAY(char, ntoabuf
, MAX_IPSTRLEN
);
1757 const HttpHeader
*hdr_in
= &request
->header
;
1758 const HttpHeaderEntry
*e
= NULL
;
1759 HttpHeaderPos pos
= HttpHeaderInitPos
;
1760 assert (hdr_out
->owner
== hoRequest
);
1762 /* use our IMS header if the cached entry has Last-Modified time */
1763 if (request
->lastmod
> -1)
1764 hdr_out
->putTime(Http::HdrType::IF_MODIFIED_SINCE
, request
->lastmod
);
1766 // Add our own If-None-Match field if the cached entry has a strong ETag.
1767 // copyOneHeaderFromClientsideRequestToUpstreamRequest() adds client ones.
1768 if (request
->etag
.size() > 0) {
1769 hdr_out
->addEntry(new HttpHeaderEntry(Http::HdrType::IF_NONE_MATCH
, SBuf(),
1770 request
->etag
.termedBuf()));
1773 bool we_do_ranges
= decideIfWeDoRanges (request
);
1775 String
strConnection (hdr_in
->getList(Http::HdrType::CONNECTION
));
1777 while ((e
= hdr_in
->getEntry(&pos
)))
1778 copyOneHeaderFromClientsideRequestToUpstreamRequest(e
, strConnection
, request
, hdr_out
, we_do_ranges
, flags
);
1780 /* Abstraction break: We should interpret multipart/byterange responses
1781 * into offset-length data, and this works around our inability to do so.
1783 if (!we_do_ranges
&& request
->multipartRangeRequest()) {
1784 /* don't cache the result */
1785 request
->flags
.cachable
= false;
1786 /* pretend it's not a range request */
1787 request
->ignoreRange("want to request the whole object");
1788 request
->flags
.isRanged
= false;
1791 hdr_out
->addVia(request
->http_ver
, hdr_in
);
1793 if (request
->flags
.accelerated
) {
1794 /* Append Surrogate-Capabilities */
1795 String
strSurrogate(hdr_in
->getList(Http::HdrType::SURROGATE_CAPABILITY
));
1797 snprintf(bbuf
, BBUF_SZ
, "%s=\"Surrogate/1.0 ESI/1.0\"", Config
.Accel
.surrogate_id
);
1799 snprintf(bbuf
, BBUF_SZ
, "%s=\"Surrogate/1.0\"", Config
.Accel
.surrogate_id
);
1801 strListAdd(&strSurrogate
, bbuf
, ',');
1802 hdr_out
->putStr(Http::HdrType::SURROGATE_CAPABILITY
, strSurrogate
.termedBuf());
1805 /** \pre Handle X-Forwarded-For */
1806 if (strcmp(opt_forwarded_for
, "delete") != 0) {
1808 String strFwd
= hdr_in
->getList(Http::HdrType::X_FORWARDED_FOR
);
1810 // if we cannot double strFwd size, then it grew past 50% of the limit
1811 if (!strFwd
.canGrowBy(strFwd
.size())) {
1812 // There is probably a forwarding loop with Via detection disabled.
1813 // If we do nothing, String will assert on overflow soon.
1814 // TODO: Terminate all transactions with huge XFF?
1817 static int warnedCount
= 0;
1818 if (warnedCount
++ < 100) {
1819 const SBuf
url(entry
? SBuf(entry
->url()) : request
->effectiveRequestUri());
1820 debugs(11, DBG_IMPORTANT
, "Warning: likely forwarding loop with " << url
);
1824 if (strcmp(opt_forwarded_for
, "on") == 0) {
1825 /** If set to ON - append client IP or 'unknown'. */
1826 if ( request
->client_addr
.isNoAddr() )
1827 strListAdd(&strFwd
, "unknown", ',');
1829 strListAdd(&strFwd
, request
->client_addr
.toStr(ntoabuf
, MAX_IPSTRLEN
), ',');
1830 } else if (strcmp(opt_forwarded_for
, "off") == 0) {
1831 /** If set to OFF - append 'unknown'. */
1832 strListAdd(&strFwd
, "unknown", ',');
1833 } else if (strcmp(opt_forwarded_for
, "transparent") == 0) {
1834 /** If set to TRANSPARENT - pass through unchanged. */
1835 } else if (strcmp(opt_forwarded_for
, "truncate") == 0) {
1836 /** If set to TRUNCATE - drop existing list and replace with client IP or 'unknown'. */
1837 if ( request
->client_addr
.isNoAddr() )
1840 strFwd
= request
->client_addr
.toStr(ntoabuf
, MAX_IPSTRLEN
);
1842 if (strFwd
.size() > 0)
1843 hdr_out
->putStr(Http::HdrType::X_FORWARDED_FOR
, strFwd
.termedBuf());
1845 /** If set to DELETE - do not copy through. */
1847 /* append Host if not there already */
1848 if (!hdr_out
->has(Http::HdrType::HOST
)) {
1849 if (request
->peer_domain
) {
1850 hdr_out
->putStr(Http::HdrType::HOST
, request
->peer_domain
);
1852 SBuf authority
= request
->url
.authority();
1853 hdr_out
->putStr(Http::HdrType::HOST
, authority
.c_str());
1857 /* append Authorization if known in URL, not in header and going direct */
1858 if (!hdr_out
->has(Http::HdrType::AUTHORIZATION
)) {
1859 if (!request
->flags
.proxying
&& !request
->url
.userInfo().isEmpty()) {
1860 static char result
[base64_encode_len(MAX_URL
*2)]; // should be big enough for a single URI segment
1861 struct base64_encode_ctx ctx
;
1862 base64_encode_init(&ctx
);
1863 size_t blen
= base64_encode_update(&ctx
, result
, request
->url
.userInfo().length(), reinterpret_cast<const uint8_t*>(request
->url
.userInfo().rawContent()));
1864 blen
+= base64_encode_final(&ctx
, result
+blen
);
1865 result
[blen
] = '\0';
1867 httpHeaderPutStrf(hdr_out
, Http::HdrType::AUTHORIZATION
, "Basic %.*s", (int)blen
, result
);
1871 /* Fixup (Proxy-)Authorization special cases. Plain relaying dealt with above */
1872 httpFixupAuthentication(request
, hdr_in
, hdr_out
, flags
);
1874 /* append Cache-Control, add max-age if not there already */
1876 HttpHdrCc
*cc
= hdr_in
->getCc();
1879 cc
= new HttpHdrCc();
1881 #if 0 /* see bug 2330 */
1882 /* Set no-cache if determined needed but not found */
1883 if (request
->flags
.nocache
)
1884 EBIT_SET(cc
->mask
, HttpHdrCcType::CC_NO_CACHE
);
1887 /* Add max-age only without no-cache */
1888 if (!cc
->hasMaxAge() && !cc
->hasNoCache()) {
1889 // XXX: performance regression. c_str() reallocates
1890 SBuf
tmp(request
->effectiveRequestUri());
1891 cc
->maxAge(getMaxAge(entry
? entry
->url() : tmp
.c_str()));
1894 /* Enforce sibling relations */
1895 if (flags
.only_if_cached
)
1896 cc
->onlyIfCached(true);
1903 /* maybe append Connection: keep-alive */
1904 if (flags
.keepalive
) {
1905 hdr_out
->putStr(Http::HdrType::CONNECTION
, "keep-alive");
1908 /* append Front-End-Https */
1909 if (flags
.front_end_https
) {
1910 if (flags
.front_end_https
== 1 || request
->url
.getScheme() == AnyP::PROTO_HTTPS
)
1911 hdr_out
->putStr(Http::HdrType::FRONT_END_HTTPS
, "On");
1914 if (flags
.chunked_request
) {
1915 // Do not just copy the original value so that if the client-side
1916 // starts decode other encodings, this code may remain valid.
1917 hdr_out
->putStr(Http::HdrType::TRANSFER_ENCODING
, "chunked");
1920 /* Now mangle the headers. */
1921 httpHdrMangleList(hdr_out
, request
, al
, ROR_REQUEST
);
1923 strConnection
.clean();
1927 * Decides whether a particular header may be cloned from the received Clients request
1928 * to our outgoing fetch request.
1931 copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry
*e
, const String strConnection
, const HttpRequest
* request
, HttpHeader
* hdr_out
, const int we_do_ranges
, const Http::StateFlags
&flags
)
1933 debugs(11, 5, "httpBuildRequestHeader: " << e
->name
<< ": " << e
->value
);
1937 /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid should not pass on. */
1939 case Http::HdrType::PROXY_AUTHORIZATION
:
1940 /** \par Proxy-Authorization:
1941 * Only pass on proxy authentication to peers for which
1942 * authentication forwarding is explicitly enabled
1944 if (!flags
.originpeer
&& flags
.proxying
&& request
->peer_login
&&
1945 (strcmp(request
->peer_login
, "PASS") == 0 ||
1946 strcmp(request
->peer_login
, "PROXYPASS") == 0 ||
1947 strcmp(request
->peer_login
, "PASSTHRU") == 0)) {
1948 hdr_out
->addEntry(e
->clone());
1952 /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid does not pass on. */
1954 case Http::HdrType::CONNECTION
: /** \par Connection: */
1955 case Http::HdrType::TE
: /** \par TE: */
1956 case Http::HdrType::KEEP_ALIVE
: /** \par Keep-Alive: */
1957 case Http::HdrType::PROXY_AUTHENTICATE
: /** \par Proxy-Authenticate: */
1958 case Http::HdrType::TRAILER
: /** \par Trailer: */
1959 case Http::HdrType::UPGRADE
: /** \par Upgrade: */
1960 case Http::HdrType::TRANSFER_ENCODING
: /** \par Transfer-Encoding: */
1963 /** \par OTHER headers I haven't bothered to track down yet. */
1965 case Http::HdrType::AUTHORIZATION
:
1966 /** \par WWW-Authorization:
1967 * Pass on WWW authentication */
1969 if (!flags
.originpeer
) {
1970 hdr_out
->addEntry(e
->clone());
1972 /** \note In accelerators, only forward authentication if enabled
1973 * (see also httpFixupAuthentication for special cases)
1975 if (request
->peer_login
&&
1976 (strcmp(request
->peer_login
, "PASS") == 0 ||
1977 strcmp(request
->peer_login
, "PASSTHRU") == 0 ||
1978 strcmp(request
->peer_login
, "PROXYPASS") == 0)) {
1979 hdr_out
->addEntry(e
->clone());
1985 case Http::HdrType::HOST
:
1987 * Normally Squid rewrites the Host: header.
1988 * However, there is one case when we don't: If the URL
1989 * went through our redirector and the admin configured
1990 * 'redir_rewrites_host' to be off.
1992 if (request
->peer_domain
)
1993 hdr_out
->putStr(Http::HdrType::HOST
, request
->peer_domain
);
1994 else if (request
->flags
.redirected
&& !Config
.onoff
.redir_rewrites_host
)
1995 hdr_out
->addEntry(e
->clone());
1997 SBuf authority
= request
->url
.authority();
1998 hdr_out
->putStr(Http::HdrType::HOST
, authority
.c_str());
2003 case Http::HdrType::IF_MODIFIED_SINCE
:
2004 /** \par If-Modified-Since:
2005 * append unless we added our own,
2006 * but only if cache_miss_revalidate is enabled, or
2007 * the request is not cacheable, or
2008 * the request contains authentication credentials.
2009 * \note at most one client's If-Modified-Since header can pass through
2011 // XXX: need to check and cleanup the auth case so cacheable auth requests get cached.
2012 if (hdr_out
->has(Http::HdrType::IF_MODIFIED_SINCE
))
2014 else if (Config
.onoff
.cache_miss_revalidate
|| !request
->flags
.cachable
|| request
->flags
.auth
)
2015 hdr_out
->addEntry(e
->clone());
2018 case Http::HdrType::IF_NONE_MATCH
:
2019 /** \par If-None-Match:
2020 * append if the wildcard '*' special case value is present, or
2021 * cache_miss_revalidate is disabled, or
2022 * the request is not cacheable in this proxy, or
2023 * the request contains authentication credentials.
2024 * \note this header lists a set of responses for the server to elide sending. Squid added values are extending that set.
2026 // XXX: need to check and cleanup the auth case so cacheable auth requests get cached.
2027 if (hdr_out
->hasListMember(Http::HdrType::IF_MATCH
, "*", ',') || Config
.onoff
.cache_miss_revalidate
|| !request
->flags
.cachable
|| request
->flags
.auth
)
2028 hdr_out
->addEntry(e
->clone());
2031 case Http::HdrType::MAX_FORWARDS
:
2032 /** \par Max-Forwards:
2033 * pass only on TRACE or OPTIONS requests */
2034 if (request
->method
== Http::METHOD_TRACE
|| request
->method
== Http::METHOD_OPTIONS
) {
2035 const int64_t hops
= e
->getInt64();
2038 hdr_out
->putInt64(Http::HdrType::MAX_FORWARDS
, hops
- 1);
2043 case Http::HdrType::VIA
:
2045 * If Via is disabled then forward any received header as-is.
2046 * Otherwise leave for explicit updated addition later. */
2048 if (!Config
.onoff
.via
)
2049 hdr_out
->addEntry(e
->clone());
2053 case Http::HdrType::RANGE
:
2055 case Http::HdrType::IF_RANGE
:
2057 case Http::HdrType::REQUEST_RANGE
:
2058 /** \par Range:, If-Range:, Request-Range:
2059 * Only pass if we accept ranges */
2061 hdr_out
->addEntry(e
->clone());
2065 case Http::HdrType::PROXY_CONNECTION
: // SHOULD ignore. But doing so breaks things.
2068 case Http::HdrType::CONTENT_LENGTH
:
2069 // pass through unless we chunk; also, keeping this away from default
2070 // prevents request smuggling via Connection: Content-Length tricks
2071 if (!flags
.chunked_request
)
2072 hdr_out
->addEntry(e
->clone());
2075 case Http::HdrType::X_FORWARDED_FOR
:
2077 case Http::HdrType::CACHE_CONTROL
:
2078 /** \par X-Forwarded-For:, Cache-Control:
2079 * handled specially by Squid, so leave off for now.
2080 * append these after the loop if needed */
2083 case Http::HdrType::FRONT_END_HTTPS
:
2084 /** \par Front-End-Https:
2085 * Pass thru only if peer is configured with front-end-https */
2086 if (!flags
.front_end_https
)
2087 hdr_out
->addEntry(e
->clone());
2093 * pass on all other header fields
2094 * which are NOT listed by the special Connection: header. */
2095 if (strConnection
.size()>0 && strListIsMember(&strConnection
, e
->name
, ',')) {
2096 debugs(11, 2, "'" << e
->name
<< "' header cropped by Connection: definition");
2100 hdr_out
->addEntry(e
->clone());
2105 HttpStateData::decideIfWeDoRanges (HttpRequest
* request
)
2108 /* decide if we want to do Ranges ourselves
2109 * and fetch the whole object now)
2110 * We want to handle Ranges ourselves iff
2111 * - we can actually parse client Range specs
2112 * - the specs are expected to be simple enough (e.g. no out-of-order ranges)
2113 * - reply will be cachable
2114 * (If the reply will be uncachable we have to throw it away after
2115 * serving this request, so it is better to forward ranges to
2116 * the server and fetch only the requested content)
2119 int64_t roffLimit
= request
->getRangeOffsetLimit();
2121 if (NULL
== request
->range
|| !request
->flags
.cachable
2122 || request
->range
->offsetLimitExceeded(roffLimit
) || request
->flags
.connectionAuth
)
2125 debugs(11, 8, "decideIfWeDoRanges: range specs: " <<
2126 request
->range
<< ", cachable: " <<
2127 request
->flags
.cachable
<< "; we_do_ranges: " << result
);
2132 /* build request prefix and append it to a given MemBuf;
2133 * return the length of the prefix */
2135 HttpStateData::buildRequestPrefix(MemBuf
* mb
)
2137 const int offset
= mb
->size
;
2138 /* Uses a local httpver variable to print the HTTP label
2139 * since the HttpRequest may have an older version label.
2140 * XXX: This could create protocol bugs as the headers sent and
2141 * flow control should all be based on the HttpRequest version
2142 * not the one we are sending. Needs checking.
2144 const AnyP::ProtocolVersion httpver
= Http::ProtocolVersion();
2145 const SBuf
url(_peer
&& !_peer
->options
.originserver
? request
->effectiveRequestUri() : request
->url
.path());
2146 mb
->appendf(SQUIDSBUFPH
" " SQUIDSBUFPH
" %s/%d.%d\r\n",
2147 SQUIDSBUFPRINT(request
->method
.image()),
2148 SQUIDSBUFPRINT(url
),
2149 AnyP::ProtocolType_str
[httpver
.protocol
],
2150 httpver
.major
,httpver
.minor
);
2151 /* build and pack headers */
2153 HttpHeader
hdr(hoRequest
);
2154 httpBuildRequestHeader(request
.getRaw(), entry
, fwd
->al
, &hdr
, flags
);
2156 if (request
->flags
.pinned
&& request
->flags
.connectionAuth
)
2157 request
->flags
.authSent
= true;
2158 else if (hdr
.has(Http::HdrType::AUTHORIZATION
))
2159 request
->flags
.authSent
= true;
2164 /* append header terminator */
2165 mb
->append(crlf
, 2);
2166 return mb
->size
- offset
;
2169 /* This will be called when connect completes. Write request. */
2171 HttpStateData::sendRequest()
2175 debugs(11, 5, HERE
<< serverConnection
<< ", request " << request
<< ", this " << this << ".");
2177 if (!Comm::IsConnOpen(serverConnection
)) {
2178 debugs(11,3, HERE
<< "cannot send request to closing " << serverConnection
);
2179 assert(closeHandler
!= NULL
);
2183 typedef CommCbMemFunT
<HttpStateData
, CommTimeoutCbParams
> TimeoutDialer
;
2184 AsyncCall::Pointer timeoutCall
= JobCallback(11, 5,
2185 TimeoutDialer
, this, HttpStateData::httpTimeout
);
2186 commSetConnTimeout(serverConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
2187 flags
.do_next_read
= true;
2188 maybeReadVirginBody();
2190 if (request
->body_pipe
!= NULL
) {
2191 if (!startRequestBodyFlow()) // register to receive body data
2193 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
2194 requestSender
= JobCallback(11,5,
2195 Dialer
, this, HttpStateData::sentRequestBody
);
2197 Must(!flags
.chunked_request
);
2198 // use chunked encoding if we do not know the length
2199 if (request
->content_length
< 0)
2200 flags
.chunked_request
= true;
2202 assert(!requestBodySource
);
2203 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
2204 requestSender
= JobCallback(11,5,
2205 Dialer
, this, HttpStateData::wroteLast
);
2208 flags
.originpeer
= (_peer
!= NULL
&& _peer
->options
.originserver
);
2209 flags
.proxying
= (_peer
!= NULL
&& !flags
.originpeer
);
2212 * Is keep-alive okay for all request methods?
2214 if (request
->flags
.mustKeepalive
)
2215 flags
.keepalive
= true;
2216 else if (request
->flags
.pinned
)
2217 flags
.keepalive
= request
->persistent();
2218 else if (!Config
.onoff
.server_pconns
)
2219 flags
.keepalive
= false;
2220 else if (_peer
== NULL
)
2221 flags
.keepalive
= true;
2222 else if (_peer
->stats
.n_keepalives_sent
< 10)
2223 flags
.keepalive
= true;
2224 else if ((double) _peer
->stats
.n_keepalives_recv
/
2225 (double) _peer
->stats
.n_keepalives_sent
> 0.50)
2226 flags
.keepalive
= true;
2229 /*The old code here was
2230 if (neighborType(_peer, request->url) == PEER_SIBLING && ...
2231 which is equivalent to:
2232 if (neighborType(_peer, URL()) == PEER_SIBLING && ...
2234 if (((_peer->type == PEER_MULTICAST && p->options.mcast_siblings) ||
2235 _peer->type == PEER_SIBLINGS ) && _peer->options.allow_miss)
2236 flags.only_if_cached = 1;
2238 But I suppose it was a bug
2240 if (neighborType(_peer
, request
->url
) == PEER_SIBLING
&& !_peer
->options
.allow_miss
)
2241 flags
.only_if_cached
= true;
2243 flags
.front_end_https
= _peer
->front_end_https
;
2247 request
->peer_host
=_peer
?_peer
->host
:NULL
;
2248 buildRequestPrefix(&mb
);
2250 debugs(11, 2, "HTTP Server " << serverConnection
);
2251 debugs(11, 2, "HTTP Server REQUEST:\n---------\n" << mb
.buf
<< "\n----------");
2253 Comm::Write(serverConnection
, &mb
, requestSender
);
2258 HttpStateData::getMoreRequestBody(MemBuf
&buf
)
2260 // parent's implementation can handle the no-encoding case
2261 if (!flags
.chunked_request
)
2262 return Client::getMoreRequestBody(buf
);
2266 Must(requestBodySource
!= NULL
);
2267 if (!requestBodySource
->getMoreData(raw
))
2268 return false; // no request body bytes to chunk yet
2270 // optimization: pre-allocate buffer size that should be enough
2271 const mb_size_t rawDataSize
= raw
.contentSize();
2272 // we may need to send: hex-chunk-size CRLF raw-data CRLF last-chunk
2273 buf
.init(16 + 2 + rawDataSize
+ 2 + 5, raw
.max_capacity
);
2275 buf
.appendf("%x\r\n", static_cast<unsigned int>(rawDataSize
));
2276 buf
.append(raw
.content(), rawDataSize
);
2277 buf
.append("\r\n", 2);
2279 Must(rawDataSize
> 0); // we did not accidently created last-chunk above
2281 // Do not send last-chunk unless we successfully received everything
2282 if (receivedWholeRequestBody
) {
2283 Must(!flags
.sentLastChunk
);
2284 flags
.sentLastChunk
= true;
2285 buf
.append("0\r\n\r\n", 5);
2292 httpStart(FwdState
*fwd
)
2294 debugs(11, 3, fwd
->request
->method
<< ' ' << fwd
->entry
->url());
2295 AsyncJob::Start(new HttpStateData(fwd
));
2299 HttpStateData::start()
2301 if (!sendRequest()) {
2302 debugs(11, 3, "httpStart: aborted");
2303 mustStop("HttpStateData::start failed");
2307 ++ statCounter
.server
.all
.requests
;
2308 ++ statCounter
.server
.http
.requests
;
2311 * We used to set the read timeout here, but not any more.
2312 * Now its set in httpSendComplete() after the full request,
2313 * including request body, has been written to the server.
2317 /// if broken posts are enabled for the request, try to fix and return true
2319 HttpStateData::finishingBrokenPost()
2321 #if USE_HTTP_VIOLATIONS
2322 if (!Config
.accessList
.brokenPosts
) {
2323 debugs(11, 5, HERE
<< "No brokenPosts list");
2327 ACLFilledChecklist
ch(Config
.accessList
.brokenPosts
, originalRequest().getRaw());
2328 if (!ch
.fastCheck().allowed()) {
2329 debugs(11, 5, HERE
<< "didn't match brokenPosts");
2333 if (!Comm::IsConnOpen(serverConnection
)) {
2334 debugs(11, 3, HERE
<< "ignoring broken POST for closed " << serverConnection
);
2335 assert(closeHandler
!= NULL
);
2336 return true; // prevent caller from proceeding as if nothing happened
2339 debugs(11, 3, "finishingBrokenPost: fixing broken POST");
2340 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
2341 requestSender
= JobCallback(11,5,
2342 Dialer
, this, HttpStateData::wroteLast
);
2343 Comm::Write(serverConnection
, "\r\n", 2, requestSender
, NULL
);
2347 #endif /* USE_HTTP_VIOLATIONS */
2350 /// if needed, write last-chunk to end the request body and return true
2352 HttpStateData::finishingChunkedRequest()
2354 if (flags
.sentLastChunk
) {
2355 debugs(11, 5, HERE
<< "already sent last-chunk");
2359 Must(receivedWholeRequestBody
); // or we should not be sending last-chunk
2360 flags
.sentLastChunk
= true;
2362 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
2363 requestSender
= JobCallback(11,5, Dialer
, this, HttpStateData::wroteLast
);
2364 Comm::Write(serverConnection
, "0\r\n\r\n", 5, requestSender
, NULL
);
2369 HttpStateData::doneSendingRequestBody()
2371 Client::doneSendingRequestBody();
2372 debugs(11,5, HERE
<< serverConnection
);
2374 // do we need to write something after the last body byte?
2375 if (flags
.chunked_request
&& finishingChunkedRequest())
2377 if (!flags
.chunked_request
&& finishingBrokenPost())
2383 // more origin request body data is available
2385 HttpStateData::handleMoreRequestBodyAvailable()
2387 if (eof
|| !Comm::IsConnOpen(serverConnection
)) {
2388 // XXX: we should check this condition in other callbacks then!
2389 // TODO: Check whether this can actually happen: We should unsubscribe
2390 // as a body consumer when the above condition(s) are detected.
2391 debugs(11, DBG_IMPORTANT
, HERE
<< "Transaction aborted while reading HTTP body");
2395 assert(requestBodySource
!= NULL
);
2397 if (requestBodySource
->buf().hasContent()) {
2398 // XXX: why does not this trigger a debug message on every request?
2400 if (flags
.headers_parsed
&& !flags
.abuse_detected
) {
2401 flags
.abuse_detected
= true;
2402 debugs(11, DBG_IMPORTANT
, "http handleMoreRequestBodyAvailable: Likely proxy abuse detected '" << request
->client_addr
<< "' -> '" << entry
->url() << "'" );
2404 if (virginReply()->sline
.status() == Http::scInvalidHeader
) {
2406 mustStop("HttpStateData::handleMoreRequestBodyAvailable");
2412 HttpStateData::handleMoreRequestBodyAvailable();
2415 // premature end of the request body
2417 HttpStateData::handleRequestBodyProducerAborted()
2419 Client::handleRequestBodyProducerAborted();
2420 if (entry
->isEmpty()) {
2421 debugs(11, 3, "request body aborted: " << serverConnection
);
2422 // We usually get here when ICAP REQMOD aborts during body processing.
2423 // We might also get here if client-side aborts, but then our response
2424 // should not matter because either client-side will provide its own or
2425 // there will be no response at all (e.g., if the the client has left).
2426 ErrorState
*err
= new ErrorState(ERR_ICAP_FAILURE
, Http::scInternalServerError
, fwd
->request
);
2427 err
->detailError(ERR_DETAIL_SRV_REQMOD_REQ_BODY
);
2431 abortTransaction("request body producer aborted");
2434 // called when we wrote request headers(!) or a part of the body
2436 HttpStateData::sentRequestBody(const CommIoCbParams
&io
)
2439 statCounter
.server
.http
.kbytes_out
+= io
.size
;
2441 Client::sentRequestBody(io
);
2445 HttpStateData::abortAll(const char *reason
)
2447 debugs(11,5, HERE
<< "aborting transaction for " << reason
<<
2448 "; " << serverConnection
<< ", this " << this);
2452 HttpStateData::ReuseDecision::ReuseDecision(const StoreEntry
*e
, const Http::StatusCode code
)
2453 : answer(HttpStateData::ReuseDecision::reuseNot
), reason(nullptr), entry(e
), statusCode(code
) {}
2455 HttpStateData::ReuseDecision::Answers
2456 HttpStateData::ReuseDecision::make(const HttpStateData::ReuseDecision::Answers ans
, const char *why
)
2463 std::ostream
&operator <<(std::ostream
&os
, const HttpStateData::ReuseDecision
&d
)
2465 static const char *ReuseMessages
[] = {
2466 "do not cache and do not share", // reuseNot
2467 "cache positively and share", // cachePositively
2468 "cache negatively and share", // cacheNegatively
2469 "do not cache but share" // doNotCacheButShare
2472 assert(d
.answer
>= HttpStateData::ReuseDecision::reuseNot
&&
2473 d
.answer
<= HttpStateData::ReuseDecision::doNotCacheButShare
);
2474 return os
<< ReuseMessages
[d
.answer
] << " because " << d
.reason
<<
2475 "; HTTP status " << d
.statusCode
<< " " << *(d
.entry
);