2 * DEBUG: section 11 Hypertext Transfer Protocol (HTTP)
3 * AUTHOR: Harvest Derived
5 * SQUID Web Proxy Cache http://www.squid-cache.org/
6 * ----------------------------------------------------------
8 * Squid is the result of efforts by numerous individuals from
9 * the Internet community; see the CONTRIBUTORS file for full
10 * details. Many organizations have provided support for Squid's
11 * development; see the SPONSORS file for full details. Squid is
12 * Copyrighted (C) 2001 by the Regents of the University of
13 * California; see the COPYRIGHT file for full details. Squid
14 * incorporates software developed and/or copyrighted by other
15 * sources; see the CREDITS file for full details.
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, write to the Free Software
29 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
33 * Anonymizing patch by lutz@as-node.jena.thur.de
34 * have a look into http-anon.c to get more informations.
38 #include "acl/FilledChecklist.h"
40 #include "base/AsyncJobCalls.h"
41 #include "base/TextException.h"
42 #include "CachePeer.h"
43 #include "ChunkedCodingParser.h"
44 #include "client_side.h"
45 #include "comm/Connection.h"
46 #include "comm/Write.h"
47 #include "err_detail_type.h"
48 #include "errorpage.h"
52 #include "HttpControlMsg.h"
54 #include "HttpHdrCc.h"
55 #include "HttpHdrContRange.h"
56 #include "HttpHdrSc.h"
57 #include "HttpHdrScTarget.h"
58 #include "HttpHeaderTools.h"
59 #include "HttpReply.h"
60 #include "HttpRequest.h"
61 #include "HttpStateFlags.h"
62 #include "log/access_log.h"
64 #include "MemObject.h"
65 #include "mime_header.h"
66 #include "neighbors.h"
67 #include "peer_proxy_negotiate_auth.h"
68 #include "profiler/Profiler.h"
70 #include "RefreshPattern.h"
72 #include "SquidConfig.h"
73 #include "SquidTime.h"
74 #include "StatCounters.h"
81 #include "auth/UserRequest.h"
84 #include "DelayPools.h"
87 #define SQUID_ENTER_THROWING_CODE() try {
88 #define SQUID_EXIT_THROWING_CODE(status) \
91 catch (const std::exception &e) { \
92 debugs (11, 1, "Exception error:" << e.what()); \
96 CBDATA_CLASS_INIT(HttpStateData
);
98 static const char *const crlf
= "\r\n";
100 static void httpMaybeRemovePublic(StoreEntry
*, http_status
);
101 static void copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry
*e
, const String strConnection
, const HttpRequest
* request
,
102 HttpHeader
* hdr_out
, const int we_do_ranges
, const HttpStateFlags
&);
103 //Declared in HttpHeaderTools.cc
104 void httpHdrAdd(HttpHeader
*heads
, HttpRequest
*request
, const AccessLogEntryPointer
&al
, HeaderWithAclList
&headers_add
);
106 HttpStateData::HttpStateData(FwdState
*theFwdState
) : AsyncJob("HttpStateData"), ServerStateData(theFwdState
),
107 lastChunk(0), header_bytes_read(0), reply_bytes_read(0),
108 body_bytes_truncated(0), httpChunkDecoder(NULL
)
110 debugs(11,5,HERE
<< "HttpStateData " << this << " created");
111 ignoreCacheControl
= false;
112 surrogateNoStore
= false;
113 serverConnection
= fwd
->serverConnection();
114 readBuf
= new MemBuf
;
115 readBuf
->init(16*1024, 256*1024);
117 // reset peer response time stats for %<pt
118 request
->hier
.peer_http_request_sent
.tv_sec
= 0;
119 request
->hier
.peer_http_request_sent
.tv_usec
= 0;
121 if (fwd
->serverConnection() != NULL
)
122 _peer
= cbdataReference(fwd
->serverConnection()->getPeer()); /* might be NULL */
125 request
->flags
.proxying
= 1;
127 * This NEIGHBOR_PROXY_ONLY check probably shouldn't be here.
128 * We might end up getting the object from somewhere else if,
129 * for example, the request to this neighbor fails.
131 if (_peer
->options
.proxy_only
)
132 entry
->releaseRequest();
135 entry
->setNoDelay(_peer
->options
.no_delay
);
140 * register the handler to free HTTP state data when the FD closes
142 typedef CommCbMemFunT
<HttpStateData
, CommCloseCbParams
> Dialer
;
143 closeHandler
= JobCallback(9, 5, Dialer
, this, HttpStateData::httpStateConnClosed
);
144 comm_add_close_handler(serverConnection
->fd
, closeHandler
);
147 HttpStateData::~HttpStateData()
150 * don't forget that ~ServerStateData() gets called automatically
153 if (!readBuf
->isNull())
158 if (httpChunkDecoder
)
159 delete httpChunkDecoder
;
161 cbdataReferenceDone(_peer
);
163 debugs(11,5, HERE
<< "HttpStateData " << this << " destroyed; " << serverConnection
);
166 const Comm::ConnectionPointer
&
167 HttpStateData::dataConnection() const
169 return serverConnection
;
173 HttpStateData::httpStateConnClosed(const CommCloseCbParams
¶ms
)
175 debugs(11, 5, "httpStateFree: FD " << params
.fd
<< ", httpState=" << params
.data
);
176 mustStop("HttpStateData::httpStateConnClosed");
180 httpCachable(const HttpRequestMethod
& method
)
182 /* GET and HEAD are cachable. Others are not. */
184 // TODO: replase to HttpRequestMethod::isCachable() ?
185 if (method
!= METHOD_GET
&& method
!= METHOD_HEAD
)
193 HttpStateData::httpTimeout(const CommTimeoutCbParams
¶ms
)
195 debugs(11, 4, HERE
<< serverConnection
<< ": '" << entry
->url() << "'" );
197 if (entry
->store_status
== STORE_PENDING
) {
198 fwd
->fail(new ErrorState(ERR_READ_TIMEOUT
, HTTP_GATEWAY_TIMEOUT
, fwd
->request
));
201 serverConnection
->close();
205 httpMaybeRemovePublic(StoreEntry
* e
, http_status status
)
211 if (!EBIT_TEST(e
->flags
, KEY_PRIVATE
))
218 case HTTP_NON_AUTHORITATIVE_INFORMATION
:
220 case HTTP_MULTIPLE_CHOICES
:
222 case HTTP_MOVED_PERMANENTLY
:
224 case HTTP_MOVED_TEMPORARILY
:
235 case HTTP_METHOD_NOT_ALLOWED
:
242 case HTTP_UNAUTHORIZED
:
252 * Any 2xx response should eject previously cached entities...
255 if (status
>= 200 && status
< 300)
263 if (!remove
&& !forbidden
)
268 if (e
->mem_obj
->request
)
269 pe
= storeGetPublicByRequest(e
->mem_obj
->request
);
271 pe
= storeGetPublic(e
->mem_obj
->url
, e
->mem_obj
->method
);
276 neighborsHtcpClear(e
, NULL
, e
->mem_obj
->request
, e
->mem_obj
->method
, HTCP_CLR_INVALIDATION
);
282 * Also remove any cached HEAD response in case the object has
285 if (e
->mem_obj
->request
)
286 pe
= storeGetPublicByRequestMethod(e
->mem_obj
->request
, METHOD_HEAD
);
288 pe
= storeGetPublic(e
->mem_obj
->url
, METHOD_HEAD
);
293 neighborsHtcpClear(e
, NULL
, e
->mem_obj
->request
, HttpRequestMethod(METHOD_HEAD
), HTCP_CLR_INVALIDATION
);
300 HttpStateData::processSurrogateControl(HttpReply
*reply
)
302 if (request
->flags
.accelerated
&& reply
->surrogate_control
) {
303 HttpHdrScTarget
*sctusable
= reply
->surrogate_control
->getMergedTarget(Config
.Accel
.surrogate_id
);
306 if (sctusable
->noStore() ||
307 (Config
.onoff
.surrogate_is_remote
308 && sctusable
->noStoreRemote())) {
309 surrogateNoStore
= true;
310 entry
->makePrivate();
313 /* The HttpHeader logic cannot tell if the header it's parsing is a reply to an
314 * accelerated request or not...
315 * Still, this is an abstraction breach. - RC
317 if (sctusable
->hasMaxAge()) {
318 if (sctusable
->maxAge() < sctusable
->maxStale())
319 reply
->expires
= reply
->date
+ sctusable
->maxAge();
321 reply
->expires
= reply
->date
+ sctusable
->maxStale();
323 /* And update the timestamps */
324 entry
->timestampsSet();
327 /* We ignore cache-control directives as per the Surrogate specification */
328 ignoreCacheControl
= true;
336 HttpStateData::cacheableReply()
338 HttpReply
const *rep
= finalReply();
339 HttpHeader
const *hdr
= &rep
->header
;
341 #if USE_HTTP_VIOLATIONS
343 const RefreshPattern
*R
= NULL
;
345 /* This strange looking define first looks up the refresh pattern
346 * and then checks if the specified flag is set. The main purpose
347 * of this is to simplify the refresh pattern lookup and USE_HTTP_VIOLATIONS
350 #define REFRESH_OVERRIDE(flag) \
351 ((R = (R ? R : refreshLimits(entry->mem_obj->url))) , \
352 (R && R->flags.flag))
354 #define REFRESH_OVERRIDE(flag) 0
357 if (surrogateNoStore
)
360 // RFC 2616: do not cache replies to responses with no-store CC directive
361 if (request
&& request
->cache_control
&&
362 request
->cache_control
->noStore() &&
363 !REFRESH_OVERRIDE(ignore_no_store
))
366 if (!ignoreCacheControl
&& request
->cache_control
!= NULL
) {
367 const HttpHdrCc
* cc
=request
->cache_control
;
369 if (!REFRESH_OVERRIDE(ignore_private
))
374 if (!REFRESH_OVERRIDE(ignore_no_cache
))
379 if (!REFRESH_OVERRIDE(ignore_no_store
))
384 if (request
->flags
.auth
|| request
->flags
.authSent
) {
386 * Responses to requests with authorization may be cached
387 * only if a Cache-Control: public reply header is present.
388 * RFC 2068, sec 14.9.4
391 if (!request
->cache_control
|| !request
->cache_control
->Public()) {
392 if (!REFRESH_OVERRIDE(ignore_auth
))
397 /* Pragma: no-cache in _replies_ is not documented in HTTP,
398 * but servers like "Active Imaging Webcast/2.0" sure do use it */
399 if (hdr
->has(HDR_PRAGMA
)) {
400 String s
= hdr
->getList(HDR_PRAGMA
);
401 const int no_cache
= strListIsMember(&s
, "no-cache", ',');
405 if (!REFRESH_OVERRIDE(ignore_no_cache
))
411 * The "multipart/x-mixed-replace" content type is used for
412 * continuous push replies. These are generally dynamic and
413 * probably should not be cachable
415 if ((v
= hdr
->getStr(HDR_CONTENT_TYPE
)))
416 if (!strncasecmp(v
, "multipart/x-mixed-replace", 25))
419 switch (rep
->sline
.status
) {
420 /* Responses that are cacheable */
424 case HTTP_NON_AUTHORITATIVE_INFORMATION
:
426 case HTTP_MULTIPLE_CHOICES
:
428 case HTTP_MOVED_PERMANENTLY
:
429 case HTTP_PERMANENT_REDIRECT
:
433 * Don't cache objects that need to be refreshed on next request,
434 * unless we know how to refresh it.
437 if (!refreshIsCachable(entry
) && !REFRESH_OVERRIDE(store_stale
)) {
438 debugs(22, 3, "refreshIsCachable() returned non-cacheable..");
446 /* Responses that only are cacheable if the server says so */
448 case HTTP_MOVED_TEMPORARILY
:
449 case HTTP_TEMPORARY_REDIRECT
:
450 if (rep
->expires
> rep
->date
&& rep
->date
> 0)
458 /* Errors can be negatively cached */
460 case HTTP_NO_CONTENT
:
464 case HTTP_BAD_REQUEST
:
470 case HTTP_METHOD_NOT_ALLOWED
:
472 case HTTP_REQUEST_URI_TOO_LARGE
:
474 case HTTP_INTERNAL_SERVER_ERROR
:
476 case HTTP_NOT_IMPLEMENTED
:
478 case HTTP_BAD_GATEWAY
:
480 case HTTP_SERVICE_UNAVAILABLE
:
482 case HTTP_GATEWAY_TIMEOUT
:
488 /* Some responses can never be cached */
490 case HTTP_PARTIAL_CONTENT
: /* Not yet supported */
494 case HTTP_NOT_MODIFIED
:
496 case HTTP_UNAUTHORIZED
:
498 case HTTP_PROXY_AUTHENTICATION_REQUIRED
:
500 case HTTP_INVALID_HEADER
: /* Squid header parsing error */
502 case HTTP_HEADER_TOO_LARGE
:
504 case HTTP_PAYMENT_REQUIRED
:
505 case HTTP_NOT_ACCEPTABLE
:
506 case HTTP_REQUEST_TIMEOUT
:
508 case HTTP_LENGTH_REQUIRED
:
509 case HTTP_PRECONDITION_FAILED
:
510 case HTTP_REQUEST_ENTITY_TOO_LARGE
:
511 case HTTP_UNSUPPORTED_MEDIA_TYPE
:
512 case HTTP_UNPROCESSABLE_ENTITY
:
514 case HTTP_FAILED_DEPENDENCY
:
515 case HTTP_INSUFFICIENT_STORAGE
:
516 case HTTP_REQUESTED_RANGE_NOT_SATISFIABLE
:
517 case HTTP_EXPECTATION_FAILED
:
522 /* RFC 2616 section 6.1.1: an unrecognized response MUST NOT be cached. */
523 debugs (11, 3, HERE
<< "Unknown HTTP status code " << rep
->sline
.status
<< ". Not cacheable.");
535 * For Vary, store the relevant request headers as
536 * virtual headers in the reply
537 * Returns false if the variance cannot be stored
540 httpMakeVaryMark(HttpRequest
* request
, HttpReply
const * reply
)
543 const char *pos
= NULL
;
550 vary
= reply
->header
.getList(HDR_VARY
);
552 while (strListGetItem(&vary
, ',', &item
, &ilen
, &pos
)) {
553 char *name
= (char *)xmalloc(ilen
+ 1);
554 xstrncpy(name
, item
, ilen
+ 1);
557 if (strcmp(name
, "*") == 0) {
558 /* Can not handle "Vary: *" withtout ETag support */
564 strListAdd(&vstr
, name
, ',');
565 hdr
= request
->header
.getByName(name
);
567 value
= hdr
.termedBuf();
570 value
= rfc1738_escape_part(value
);
571 vstr
.append("=\"", 2);
573 vstr
.append("\"", 1);
580 #if X_ACCELERATOR_VARY
583 vary
= reply
->header
.getList(HDR_X_ACCELERATOR_VARY
);
585 while (strListGetItem(&vary
, ',', &item
, &ilen
, &pos
)) {
586 char *name
= (char *)xmalloc(ilen
+ 1);
587 xstrncpy(name
, item
, ilen
+ 1);
589 strListAdd(&vstr
, name
, ',');
590 hdr
= request
->header
.getByName(name
);
592 value
= hdr
.termedBuf();
595 value
= rfc1738_escape_part(value
);
596 vstr
.append("=\"", 2);
598 vstr
.append("\"", 1);
607 debugs(11, 3, "httpMakeVaryMark: " << vstr
);
608 return vstr
.termedBuf();
612 HttpStateData::keepaliveAccounting(HttpReply
*reply
)
616 ++ _peer
->stats
.n_keepalives_sent
;
618 if (reply
->keep_alive
) {
620 ++ _peer
->stats
.n_keepalives_recv
;
622 if (Config
.onoff
.detect_broken_server_pconns
623 && reply
->bodySize(request
->method
) == -1 && !flags
.chunked
) {
624 debugs(11, DBG_IMPORTANT
, "keepaliveAccounting: Impossible keep-alive header from '" << entry
->url() << "'" );
625 // debugs(11, 2, "GOT HTTP REPLY HDR:\n---------\n" << readBuf->content() << "\n----------" );
626 flags
.keepalive_broken
= true;
632 HttpStateData::checkDateSkew(HttpReply
*reply
)
634 if (reply
->date
> -1 && !_peer
) {
635 int skew
= abs((int)(reply
->date
- squid_curtime
));
638 debugs(11, 3, "" << request
->GetHost() << "'s clock is skewed by " << skew
<< " seconds!");
643 * This creates the error page itself.. its likely
644 * that the forward ported reply header max size patch
645 * generates non http conformant error pages - in which
646 * case the errors where should be 'BAD_GATEWAY' etc
649 HttpStateData::processReplyHeader()
651 /** Creates a blank header. If this routine is made incremental, this will not do */
653 /* NP: all exit points to this function MUST call ctx_exit(ctx) */
654 Ctx ctx
= ctx_enter(entry
->mem_obj
->url
);
656 debugs(11, 3, "processReplyHeader: key '" << entry
->getMD5Text() << "'");
658 assert(!flags
.headers_parsed
);
660 if (!readBuf
->hasContent()) {
665 http_status error
= HTTP_STATUS_NONE
;
667 HttpReply
*newrep
= new HttpReply
;
668 const bool parsed
= newrep
->parse(readBuf
, eof
, &error
);
670 if (!parsed
&& readBuf
->contentSize() > 5 && strncmp(readBuf
->content(), "HTTP/", 5) != 0 && strncmp(readBuf
->content(), "ICY", 3) != 0) {
672 HttpReply
*tmprep
= new HttpReply
;
673 tmprep
->setHeaders(HTTP_OK
, "Gatewaying", NULL
, -1, -1, -1);
674 tmprep
->header
.putExt("X-Transformed-From", "HTTP/0.9");
676 newrep
->parse(mb
, eof
, &error
);
680 if (!parsed
&& error
> 0) { // unrecoverable parsing error
681 debugs(11, 3, "processReplyHeader: Non-HTTP-compliant header: '" << readBuf
->content() << "'");
682 flags
.headers_parsed
= true;
683 newrep
->sline
.version
= HttpVersion(1,1);
684 newrep
->sline
.status
= error
;
685 HttpReply
*vrep
= setVirginReply(newrep
);
686 entry
->replaceHttpReply(vrep
);
691 if (!parsed
) { // need more data
699 debugs(11, 2, "HTTP Server " << serverConnection
);
700 debugs(11, 2, "HTTP Server REPLY:\n---------\n" << readBuf
->content() << "\n----------");
702 header_bytes_read
= headersEnd(readBuf
->content(), readBuf
->contentSize());
703 readBuf
->consume(header_bytes_read
);
706 newrep
->removeStaleWarnings();
708 if (newrep
->sline
.protocol
== AnyP::PROTO_HTTP
&& newrep
->sline
.status
>= 100 && newrep
->sline
.status
< 200) {
714 flags
.chunked
= false;
715 if (newrep
->sline
.protocol
== AnyP::PROTO_HTTP
&& newrep
->header
.chunked()) {
716 flags
.chunked
= true;
717 httpChunkDecoder
= new ChunkedCodingParser
;
720 if (!peerSupportsConnectionPinning())
721 request
->flags
.connectionAuthDisabled
= 1;
723 HttpReply
*vrep
= setVirginReply(newrep
);
724 flags
.headers_parsed
= true;
726 keepaliveAccounting(vrep
);
730 processSurrogateControl (vrep
);
732 request
->hier
.peer_reply_status
= newrep
->sline
.status
;
737 /// ignore or start forwarding the 1xx response (a.k.a., control message)
739 HttpStateData::handle1xx(HttpReply
*reply
)
741 HttpMsgPointerT
<HttpReply
> msg(reply
); // will destroy reply if unused
743 // one 1xx at a time: we must not be called while waiting for previous 1xx
744 Must(!flags
.handling1xx
);
745 flags
.handling1xx
= true;
747 if (!request
->canHandle1xx()) {
748 debugs(11, 2, HERE
<< "ignoring client-unsupported 1xx");
753 #if USE_HTTP_VIOLATIONS
754 // check whether the 1xx response forwarding is allowed by squid.conf
755 if (Config
.accessList
.reply
) {
756 ACLFilledChecklist
ch(Config
.accessList
.reply
, originalRequest(), NULL
);
757 ch
.reply
= HTTPMSGLOCK(reply
);
758 if (ch
.fastCheck() != ACCESS_ALLOWED
) { // TODO: support slow lookups?
759 debugs(11, 3, HERE
<< "ignoring denied 1xx");
764 #endif // USE_HTTP_VIOLATIONS
766 debugs(11, 2, HERE
<< "forwarding 1xx to client");
768 // the Sink will use this to call us back after writing 1xx to the client
769 typedef NullaryMemFunT
<HttpStateData
> CbDialer
;
770 const AsyncCall::Pointer cb
= JobCallback(11, 3, CbDialer
, this,
771 HttpStateData::proceedAfter1xx
);
772 CallJobHere1(11, 4, request
->clientConnectionManager
, ConnStateData
,
773 ConnStateData::sendControlMsg
, HttpControlMsg(msg
, cb
));
774 // If the call is not fired, then the Sink is gone, and HttpStateData
775 // will terminate due to an aborted store entry or another similar error.
776 // If we get stuck, it is not handle1xx fault if we could get stuck
777 // for similar reasons without a 1xx response.
780 /// restores state and resumes processing after 1xx is ignored or forwarded
782 HttpStateData::proceedAfter1xx()
784 Must(flags
.handling1xx
);
786 debugs(11, 2, HERE
<< "consuming " << header_bytes_read
<<
787 " header and " << reply_bytes_read
<< " body bytes read after 1xx");
788 header_bytes_read
= 0;
789 reply_bytes_read
= 0;
791 CallJobHere(11, 3, this, HttpStateData
, HttpStateData::processReply
);
795 * returns true if the peer can support connection pinning
797 bool HttpStateData::peerSupportsConnectionPinning() const
799 const HttpReply
*rep
= entry
->mem_obj
->getReply();
800 const HttpHeader
*hdr
= &rep
->header
;
807 /*If this peer does not support connection pinning (authenticated
808 connections) return false
810 if (!_peer
->connection_auth
)
813 /*The peer supports connection pinning and the http reply status
814 is not unauthorized, so the related connection can be pinned
816 if (rep
->sline
.status
!= HTTP_UNAUTHORIZED
)
819 /*The server respond with HTTP_UNAUTHORIZED and the peer configured
820 with "connection-auth=on" we know that the peer supports pinned
823 if (_peer
->connection_auth
== 1)
826 /*At this point peer has configured with "connection-auth=auto"
827 parameter so we need some extra checks to decide if we are going
828 to allow pinned connections or not
831 /*if the peer configured with originserver just allow connection
832 pinning (squid 2.6 behaviour)
834 if (_peer
->options
.originserver
)
837 /*if the connections it is already pinned it is OK*/
838 if (request
->flags
.pinned
)
841 /*Allow pinned connections only if the Proxy-support header exists in
842 reply and has in its list the "Session-Based-Authentication"
843 which means that the peer supports connection pinning.
845 if (!hdr
->has(HDR_PROXY_SUPPORT
))
848 header
= hdr
->getStrOrList(HDR_PROXY_SUPPORT
);
849 /* XXX This ought to be done in a case-insensitive manner */
850 rc
= (strstr(header
.termedBuf(), "Session-Based-Authentication") != NULL
);
855 // Called when we parsed (and possibly adapted) the headers but
856 // had not starting storing (a.k.a., sending) the body yet.
858 HttpStateData::haveParsedReplyHeaders()
860 ServerStateData::haveParsedReplyHeaders();
862 Ctx ctx
= ctx_enter(entry
->mem_obj
->url
);
863 HttpReply
*rep
= finalReply();
865 if (rep
->sline
.status
== HTTP_PARTIAL_CONTENT
&&
867 currentOffset
= rep
->content_range
->spec
.offset
;
869 entry
->timestampsSet();
871 /* Check if object is cacheable or not based on reply code */
872 debugs(11, 3, "haveParsedReplyHeaders: HTTP CODE: " << rep
->sline
.status
);
874 if (neighbors_do_private_keys
)
875 httpMaybeRemovePublic(entry
, rep
->sline
.status
);
877 if (rep
->header
.has(HDR_VARY
)
878 #if X_ACCELERATOR_VARY
879 || rep
->header
.has(HDR_X_ACCELERATOR_VARY
)
882 const char *vary
= httpMakeVaryMark(request
, rep
);
885 entry
->makePrivate();
886 if (!fwd
->reforwardableStatus(rep
->sline
.status
))
887 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
891 entry
->mem_obj
->vary_headers
= xstrdup(vary
);
895 * If its not a reply that we will re-forward, then
896 * allow the client to get it.
898 if (!fwd
->reforwardableStatus(rep
->sline
.status
))
899 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
901 switch (cacheableReply()) {
908 entry
->makePrivate();
913 #if USE_HTTP_VIOLATIONS
914 if (Config
.negativeTtl
> 0)
915 entry
->cacheNegatively();
918 entry
->makePrivate();
930 if (!ignoreCacheControl
&& rep
->cache_control
) {
931 if (rep
->cache_control
->proxyRevalidate() ||
932 rep
->cache_control
->mustRevalidate() ||
933 rep
->cache_control
->hasSMaxAge()
935 EBIT_SET(entry
->flags
, ENTRY_REVALIDATE
);
939 headersLog(1, 0, request
->method
, rep
);
946 HttpStateData::ConnectionStatus
947 HttpStateData::statusIfComplete() const
949 const HttpReply
*rep
= virginReply();
951 * If the reply wants to close the connection, it takes precedence */
953 if (httpHeaderHasConnDir(&rep
->header
, "close"))
954 return COMPLETE_NONPERSISTENT_MSG
;
957 * If we didn't send a keep-alive request header, then this
958 * can not be a persistent connection.
960 if (!flags
.keepalive
)
961 return COMPLETE_NONPERSISTENT_MSG
;
964 * If we haven't sent the whole request then this can not be a persistent
967 if (!flags
.request_sent
) {
968 debugs(11, 2, "statusIfComplete: Request not yet fully sent \"" << RequestMethodStr(request
->method
) << " " << entry
->url() << "\"" );
969 return COMPLETE_NONPERSISTENT_MSG
;
973 * What does the reply have to say about keep-alive?
977 * If the origin server (HTTP/1.0) does not send a keep-alive
978 * header, but keeps the connection open anyway, what happens?
979 * We'll return here and http.c waits for an EOF before changing
980 * store_status to STORE_OK. Combine this with ENTRY_FWD_HDR_WAIT
981 * and an error status code, and we might have to wait until
982 * the server times out the socket.
984 if (!rep
->keep_alive
)
985 return COMPLETE_NONPERSISTENT_MSG
;
987 return COMPLETE_PERSISTENT_MSG
;
990 HttpStateData::ConnectionStatus
991 HttpStateData::persistentConnStatus() const
993 debugs(11, 3, HERE
<< serverConnection
<< " eof=" << eof
);
994 if (eof
) // already reached EOF
995 return COMPLETE_NONPERSISTENT_MSG
;
997 /* If server fd is closing (but we have not been notified yet), stop Comm
998 I/O to avoid assertions. TODO: Change Comm API to handle callers that
999 want more I/O after async closing (usually initiated by others). */
1000 // XXX: add canReceive or s/canSend/canTalkToServer/
1001 if (!Comm::IsConnOpen(serverConnection
))
1002 return COMPLETE_NONPERSISTENT_MSG
;
1005 * In chunked response we do not know the content length but we are absolutely
1006 * sure about the end of response, so we are calling the statusIfComplete to
1007 * decide if we can be persistant
1009 if (lastChunk
&& flags
.chunked
)
1010 return statusIfComplete();
1012 const HttpReply
*vrep
= virginReply();
1013 debugs(11, 5, "persistentConnStatus: content_length=" << vrep
->content_length
);
1015 const int64_t clen
= vrep
->bodySize(request
->method
);
1017 debugs(11, 5, "persistentConnStatus: clen=" << clen
);
1019 /* If the body size is unknown we must wait for EOF */
1021 return INCOMPLETE_MSG
;
1024 * If the body size is known, we must wait until we've gotten all of it. */
1027 // if (entry->mem_obj->endOffset() < vrep->content_length + vrep->hdr_sz)
1028 const int64_t body_bytes_read
= reply_bytes_read
- header_bytes_read
;
1029 debugs(11,5, "persistentConnStatus: body_bytes_read=" <<
1030 body_bytes_read
<< " content_length=" << vrep
->content_length
);
1032 if (body_bytes_read
< vrep
->content_length
)
1033 return INCOMPLETE_MSG
;
1035 if (body_bytes_truncated
> 0) // already read more than needed
1036 return COMPLETE_NONPERSISTENT_MSG
; // disable pconns
1040 * If there is no message body or we got it all, we can be persistent */
1041 return statusIfComplete();
1045 * This is the callback after some data has been read from the network
1049 HttpStateData::ReadReplyWrapper(int fd, char *buf, size_t len, comm_err_t flag, int xerrno, void *data)
1051 HttpStateData *httpState = static_cast<HttpStateData *>(data);
1052 assert (fd == httpState->serverConnection->fd);
1053 // assert(buf == readBuf->content());
1054 PROF_start(HttpStateData_readReply);
1055 httpState->readReply(len, flag, xerrno);
1056 PROF_stop(HttpStateData_readReply);
1060 /* XXX this function is too long! */
1062 HttpStateData::readReply(const CommIoCbParams
&io
)
1068 flags
.do_next_read
= false;
1070 debugs(11, 5, HERE
<< io
.conn
<< ": len " << len
<< ".");
1072 // Bail out early on COMM_ERR_CLOSING - close handlers will tidy up for us
1073 if (io
.flag
== COMM_ERR_CLOSING
) {
1074 debugs(11, 3, "http socket closing");
1078 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1079 abortTransaction("store entry aborted while reading reply");
1083 // handle I/O errors
1084 if (io
.flag
!= COMM_OK
|| len
< 0) {
1085 debugs(11, 2, HERE
<< io
.conn
<< ": read failure: " << xstrerror() << ".");
1087 if (ignoreErrno(io
.xerrno
)) {
1088 flags
.do_next_read
= true;
1090 ErrorState
*err
= new ErrorState(ERR_READ_ERROR
, HTTP_BAD_GATEWAY
, fwd
->request
);
1091 err
->xerrno
= io
.xerrno
;
1093 flags
.do_next_read
= false;
1094 serverConnection
->close();
1102 readBuf
->appended(len
);
1103 reply_bytes_read
+= len
;
1105 DelayId delayId
= entry
->mem_obj
->mostBytesAllowed();
1106 delayId
.bytesIn(len
);
1109 kb_incr(&(statCounter
.server
.all
.kbytes_in
), len
);
1110 kb_incr(&(statCounter
.server
.http
.kbytes_in
), len
);
1111 ++ IOStats
.Http
.reads
;
1113 for (clen
= len
- 1, bin
= 0; clen
; ++bin
)
1116 ++ IOStats
.Http
.read_hist
[bin
];
1118 // update peer response time stats (%<pt)
1119 const timeval
&sent
= request
->hier
.peer_http_request_sent
;
1120 request
->hier
.peer_response_time
=
1121 sent
.tv_sec
? tvSubMsec(sent
, current_time
) : -1;
1125 * Here the RFC says we should ignore whitespace between replies, but we can't as
1126 * doing so breaks HTTP/0.9 replies beginning with witespace, and in addition
1127 * the response splitting countermeasures is extremely likely to trigger on this,
1128 * not allowing connection reuse in the first place.
1130 * 2012-02-10: which RFC? not 2068 or 2616,
1131 * tolerance there is all about whitespace between requests and header tokens.
1134 if (len
== 0) { // reached EOF?
1136 flags
.do_next_read
= false;
1138 /* Bug 2879: Replies may terminate with \r\n then EOF instead of \r\n\r\n
1139 * Ensure here that we have at minimum two \r\n when EOF is seen.
1140 * TODO: Add eof parameter to headersEnd() and move this hack there.
1142 if (readBuf
->contentSize() && !flags
.headers_parsed
) {
1144 * Yes Henrik, there is a point to doing this. When we
1145 * called httpProcessReplyHeader() before, we didn't find
1146 * the end of headers, but now we are definately at EOF, so
1147 * we want to process the reply headers.
1149 /* Fake an "end-of-headers" to work around such broken servers */
1150 readBuf
->append("\r\n", 2);
1157 /// processes the already read and buffered response data, possibly after
1158 /// waiting for asynchronous 1xx control message processing
1160 HttpStateData::processReply()
1163 if (flags
.handling1xx
) { // we came back after handling a 1xx response
1164 debugs(11, 5, HERE
<< "done with 1xx handling");
1165 flags
.handling1xx
= false;
1166 Must(!flags
.headers_parsed
);
1169 if (!flags
.headers_parsed
) { // have not parsed headers yet?
1170 PROF_start(HttpStateData_processReplyHeader
);
1171 processReplyHeader();
1172 PROF_stop(HttpStateData_processReplyHeader
);
1174 if (!continueAfterParsingHeader()) // parsing error or need more data
1175 return; // TODO: send errors to ICAP
1177 adaptOrFinalizeReply(); // may write to, abort, or "close" the entry
1180 // kick more reads if needed and/or process the response body, if any
1181 PROF_start(HttpStateData_processReplyBody
);
1182 processReplyBody(); // may call serverComplete()
1183 PROF_stop(HttpStateData_processReplyBody
);
1187 \retval true if we can continue with processing the body or doing ICAP.
1190 HttpStateData::continueAfterParsingHeader()
1192 if (flags
.handling1xx
) {
1193 debugs(11, 5, HERE
<< "wait for 1xx handling");
1194 Must(!flags
.headers_parsed
);
1198 if (!flags
.headers_parsed
&& !eof
) {
1199 debugs(11, 9, HERE
<< "needs more at " << readBuf
->contentSize());
1200 flags
.do_next_read
= true;
1201 /** \retval false If we have not finished parsing the headers and may get more data.
1202 * Schedules more reads to retrieve the missing data.
1204 maybeReadVirginBody(); // schedules all kinds of reads; TODO: rename
1208 /** If we are done with parsing, check for errors */
1210 err_type error
= ERR_NONE
;
1212 if (flags
.headers_parsed
) { // parsed headers, possibly with errors
1213 // check for header parsing errors
1214 if (HttpReply
*vrep
= virginReply()) {
1215 const http_status s
= vrep
->sline
.status
;
1216 const HttpVersion
&v
= vrep
->sline
.version
;
1217 if (s
== HTTP_INVALID_HEADER
&& v
!= HttpVersion(0,9)) {
1218 debugs(11, DBG_IMPORTANT
, "WARNING: HTTP: Invalid Response: Bad header encountered from " << entry
->url() << " AKA " << request
->GetHost() << request
->urlpath
.termedBuf() );
1219 error
= ERR_INVALID_RESP
;
1220 } else if (s
== HTTP_HEADER_TOO_LARGE
) {
1221 fwd
->dontRetry(true);
1222 error
= ERR_TOO_BIG
;
1224 return true; // done parsing, got reply, and no error
1227 // parsed headers but got no reply
1228 debugs(11, DBG_IMPORTANT
, "WARNING: HTTP: Invalid Response: No reply at all for " << entry
->url() << " AKA " << request
->GetHost() << request
->urlpath
.termedBuf() );
1229 error
= ERR_INVALID_RESP
;
1233 if (readBuf
->hasContent()) {
1234 error
= ERR_INVALID_RESP
;
1235 debugs(11, DBG_IMPORTANT
, "WARNING: HTTP: Invalid Response: Headers did not parse at all for " << entry
->url() << " AKA " << request
->GetHost() << request
->urlpath
.termedBuf() );
1237 error
= ERR_ZERO_SIZE_OBJECT
;
1238 debugs(11, (request
->flags
.accelerated
?DBG_IMPORTANT
:2), "WARNING: HTTP: Invalid Response: No object data received for " <<
1239 entry
->url() << " AKA " << request
->GetHost() << request
->urlpath
.termedBuf() );
1243 assert(error
!= ERR_NONE
);
1245 fwd
->fail(new ErrorState(error
, HTTP_BAD_GATEWAY
, fwd
->request
));
1246 flags
.do_next_read
= false;
1247 serverConnection
->close();
1248 return false; // quit on error
1251 /** truncate what we read if we read too much so that writeReplyBody()
1252 writes no more than what we should have read */
1254 HttpStateData::truncateVirginBody()
1256 assert(flags
.headers_parsed
);
1258 HttpReply
*vrep
= virginReply();
1260 if (!vrep
->expectingBody(request
->method
, clen
) || clen
< 0)
1261 return; // no body or a body of unknown size, including chunked
1263 const int64_t body_bytes_read
= reply_bytes_read
- header_bytes_read
;
1264 if (body_bytes_read
- body_bytes_truncated
<= clen
)
1265 return; // we did not read too much or already took care of the extras
1267 if (const int64_t extras
= body_bytes_read
- body_bytes_truncated
- clen
) {
1268 // server sent more that the advertised content length
1269 debugs(11,5, HERE
<< "body_bytes_read=" << body_bytes_read
<<
1270 " clen=" << clen
<< '/' << vrep
->content_length
<<
1271 " body_bytes_truncated=" << body_bytes_truncated
<< '+' << extras
);
1273 readBuf
->truncate(extras
);
1274 body_bytes_truncated
+= extras
;
1279 * Call this when there is data from the origin server
1280 * which should be sent to either StoreEntry, or to ICAP...
1283 HttpStateData::writeReplyBody()
1285 truncateVirginBody(); // if needed
1286 const char *data
= readBuf
->content();
1287 int len
= readBuf
->contentSize();
1288 addVirginReplyBody(data
, len
);
1289 readBuf
->consume(len
);
1293 HttpStateData::decodeAndWriteReplyBody()
1295 const char *data
= NULL
;
1297 bool wasThereAnException
= false;
1298 assert(flags
.chunked
);
1299 assert(httpChunkDecoder
);
1300 SQUID_ENTER_THROWING_CODE();
1303 const bool doneParsing
= httpChunkDecoder
->parse(readBuf
,&decodedData
);
1304 len
= decodedData
.contentSize();
1305 data
=decodedData
.content();
1306 addVirginReplyBody(data
, len
);
1309 flags
.do_next_read
= false;
1311 SQUID_EXIT_THROWING_CODE(wasThereAnException
);
1312 return wasThereAnException
;
1316 * processReplyBody has two purposes:
1317 * 1 - take the reply body data, if any, and put it into either
1318 * the StoreEntry, or give it over to ICAP.
1319 * 2 - see if we made it to the end of the response (persistent
1320 * connections and such)
1323 HttpStateData::processReplyBody()
1325 Ip::Address client_addr
;
1326 bool ispinned
= false;
1328 if (!flags
.headers_parsed
) {
1329 flags
.do_next_read
= true;
1330 maybeReadVirginBody();
1335 debugs(11,5, HERE
<< "adaptationAccessCheckPending=" << adaptationAccessCheckPending
);
1336 if (adaptationAccessCheckPending
)
1342 * At this point the reply headers have been parsed and consumed.
1343 * That means header content has been removed from readBuf and
1344 * it contains only body data.
1346 if (entry
->isAccepting()) {
1347 if (flags
.chunked
) {
1348 if (!decodeAndWriteReplyBody()) {
1349 flags
.do_next_read
= false;
1357 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1358 // The above writeReplyBody() call may have aborted the store entry.
1359 abortTransaction("store entry aborted while storing reply");
1362 switch (persistentConnStatus()) {
1363 case INCOMPLETE_MSG
: {
1364 debugs(11, 5, "processReplyBody: INCOMPLETE_MSG from " << serverConnection
);
1365 /* Wait for more data or EOF condition */
1366 AsyncCall::Pointer nil
;
1367 if (flags
.keepalive_broken
) {
1368 commSetConnTimeout(serverConnection
, 10, nil
);
1370 commSetConnTimeout(serverConnection
, Config
.Timeout
.read
, nil
);
1373 flags
.do_next_read
= true;
1377 case COMPLETE_PERSISTENT_MSG
:
1378 debugs(11, 5, "processReplyBody: COMPLETE_PERSISTENT_MSG from " << serverConnection
);
1379 /* yes we have to clear all these! */
1380 commUnsetConnTimeout(serverConnection
);
1381 flags
.do_next_read
= false;
1383 comm_remove_close_handler(serverConnection
->fd
, closeHandler
);
1384 closeHandler
= NULL
;
1385 fwd
->unregister(serverConnection
);
1387 if (request
->flags
.spoofClientIp
)
1388 client_addr
= request
->client_addr
;
1390 if (request
->flags
.pinned
) {
1392 } else if (request
->flags
.connectionAuth
&& request
->flags
.authSent
) {
1396 if (ispinned
&& request
->clientConnectionManager
.valid()) {
1397 request
->clientConnectionManager
->pinConnection(serverConnection
, request
, _peer
,
1398 (request
->flags
.connectionAuth
!= 0));
1400 fwd
->pconnPush(serverConnection
, request
->peer_host
? request
->peer_host
: request
->GetHost());
1403 serverConnection
= NULL
;
1407 case COMPLETE_NONPERSISTENT_MSG
:
1408 debugs(11, 5, "processReplyBody: COMPLETE_NONPERSISTENT_MSG from " << serverConnection
);
1413 maybeReadVirginBody();
1417 HttpStateData::maybeReadVirginBody()
1420 if (!Comm::IsConnOpen(serverConnection
) || fd_table
[serverConnection
->fd
].closing())
1423 // we may need to grow the buffer if headers do not fit
1424 const int minRead
= flags
.headers_parsed
? 0 :1024;
1425 const int read_size
= replyBodySpace(*readBuf
, minRead
);
1427 debugs(11,9, HERE
<< (flags
.do_next_read
? "may" : "wont") <<
1428 " read up to " << read_size
<< " bytes from " << serverConnection
);
1431 * why <2? Because delayAwareRead() won't actually read if
1432 * you ask it to read 1 byte. The delayed read request
1433 * just gets re-queued until the client side drains, then
1434 * the I/O thread hangs. Better to not register any read
1435 * handler until we get a notification from someone that
1436 * its okay to read again.
1441 if (flags
.do_next_read
) {
1442 flags
.do_next_read
= false;
1443 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
1444 entry
->delayAwareRead(serverConnection
, readBuf
->space(read_size
), read_size
,
1445 JobCallback(11, 5, Dialer
, this, HttpStateData::readReply
));
1449 /// called after writing the very last request byte (body, last-chunk, etc)
1451 HttpStateData::wroteLast(const CommIoCbParams
&io
)
1453 debugs(11, 5, HERE
<< serverConnection
<< ": size " << io
.size
<< ": errflag " << io
.flag
<< ".");
1454 #if URL_CHECKSUM_DEBUG
1456 entry
->mem_obj
->checkUrlChecksum();
1460 fd_bytes(io
.fd
, io
.size
, FD_WRITE
);
1461 kb_incr(&(statCounter
.server
.all
.kbytes_out
), io
.size
);
1462 kb_incr(&(statCounter
.server
.http
.kbytes_out
), io
.size
);
1465 if (io
.flag
== COMM_ERR_CLOSING
)
1469 ErrorState
*err
= new ErrorState(ERR_WRITE_ERROR
, HTTP_BAD_GATEWAY
, fwd
->request
);
1470 err
->xerrno
= io
.xerrno
;
1472 serverConnection
->close();
1479 /// successfully wrote the entire request (including body, last-chunk, etc.)
1481 HttpStateData::sendComplete()
1484 * Set the read timeout here because it hasn't been set yet.
1485 * We only set the read timeout after the request has been
1486 * fully written to the server-side. If we start the timeout
1487 * after connection establishment, then we are likely to hit
1488 * the timeout for POST/PUT requests that have very large
1491 typedef CommCbMemFunT
<HttpStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1492 AsyncCall::Pointer timeoutCall
= JobCallback(11, 5,
1493 TimeoutDialer
, this, HttpStateData::httpTimeout
);
1495 commSetConnTimeout(serverConnection
, Config
.Timeout
.read
, timeoutCall
);
1496 flags
.request_sent
= true;
1497 request
->hier
.peer_http_request_sent
= current_time
;
1500 // Close the HTTP server connection. Used by serverComplete().
1502 HttpStateData::closeServer()
1504 debugs(11,5, HERE
<< "closing HTTP server " << serverConnection
<< " this " << this);
1506 if (Comm::IsConnOpen(serverConnection
)) {
1507 fwd
->unregister(serverConnection
);
1508 comm_remove_close_handler(serverConnection
->fd
, closeHandler
);
1509 closeHandler
= NULL
;
1510 serverConnection
->close();
1515 HttpStateData::doneWithServer() const
1517 return !Comm::IsConnOpen(serverConnection
);
1521 * Fixup authentication request headers for special cases
1524 httpFixupAuthentication(HttpRequest
* request
, const HttpHeader
* hdr_in
, HttpHeader
* hdr_out
, const HttpStateFlags
&flags
)
1526 http_hdr_type header
= flags
.originpeer
? HDR_AUTHORIZATION
: HDR_PROXY_AUTHORIZATION
;
1528 /* Nothing to do unless we are forwarding to a peer */
1529 if (!request
->flags
.proxying
)
1532 /* Needs to be explicitly enabled */
1533 if (!request
->peer_login
)
1536 /* Maybe already dealt with? */
1537 if (hdr_out
->has(header
))
1540 /* Nothing to do here for PASSTHRU */
1541 if (strcmp(request
->peer_login
, "PASSTHRU") == 0)
1544 /* PROXYPASS is a special case, single-signon to servers with the proxy password (basic only) */
1545 if (flags
.originpeer
&& strcmp(request
->peer_login
, "PROXYPASS") == 0 && hdr_in
->has(HDR_PROXY_AUTHORIZATION
)) {
1546 const char *auth
= hdr_in
->getStr(HDR_PROXY_AUTHORIZATION
);
1548 if (auth
&& strncasecmp(auth
, "basic ", 6) == 0) {
1549 hdr_out
->putStr(header
, auth
);
1554 /* Special mode to pass the username to the upstream cache */
1555 if (*request
->peer_login
== '*') {
1557 const char *username
= "-";
1559 if (request
->extacl_user
.size())
1560 username
= request
->extacl_user
.termedBuf();
1562 else if (request
->auth_user_request
!= NULL
)
1563 username
= request
->auth_user_request
->username();
1566 snprintf(loginbuf
, sizeof(loginbuf
), "%s%s", username
, request
->peer_login
+ 1);
1568 httpHeaderPutStrf(hdr_out
, header
, "Basic %s",
1569 old_base64_encode(loginbuf
));
1573 /* external_acl provided credentials */
1574 if (request
->extacl_user
.size() && request
->extacl_passwd
.size() &&
1575 (strcmp(request
->peer_login
, "PASS") == 0 ||
1576 strcmp(request
->peer_login
, "PROXYPASS") == 0)) {
1578 snprintf(loginbuf
, sizeof(loginbuf
), SQUIDSTRINGPH
":" SQUIDSTRINGPH
,
1579 SQUIDSTRINGPRINT(request
->extacl_user
),
1580 SQUIDSTRINGPRINT(request
->extacl_passwd
));
1581 httpHeaderPutStrf(hdr_out
, header
, "Basic %s",
1582 old_base64_encode(loginbuf
));
1585 // if no external user credentials are available to fake authentication with PASS acts like PASSTHRU
1586 if (strcmp(request
->peer_login
, "PASS") == 0)
1589 /* Kerberos login to peer */
1590 #if HAVE_AUTH_MODULE_NEGOTIATE && HAVE_KRB5 && HAVE_GSSAPI
1591 if (strncmp(request
->peer_login
, "NEGOTIATE",strlen("NEGOTIATE")) == 0) {
1593 char *PrincipalName
=NULL
,*p
;
1594 if ((p
=strchr(request
->peer_login
,':')) != NULL
) {
1597 Token
= peer_proxy_negotiate_auth(PrincipalName
, request
->peer_host
);
1599 httpHeaderPutStrf(hdr_out
, header
, "Negotiate %s",Token
);
1603 #endif /* HAVE_KRB5 && HAVE_GSSAPI */
1605 httpHeaderPutStrf(hdr_out
, header
, "Basic %s",
1606 old_base64_encode(request
->peer_login
));
1611 * build request headers and append them to a given MemBuf
1612 * used by buildRequestPrefix()
1613 * note: initialised the HttpHeader, the caller is responsible for Clean()-ing
1616 HttpStateData::httpBuildRequestHeader(HttpRequest
* request
,
1618 const AccessLogEntryPointer
&al
,
1619 HttpHeader
* hdr_out
,
1620 const HttpStateFlags
&flags
)
1622 /* building buffer for complex strings */
1623 #define BBUF_SZ (MAX_URL+32)
1624 LOCAL_ARRAY(char, bbuf
, BBUF_SZ
);
1625 LOCAL_ARRAY(char, ntoabuf
, MAX_IPSTRLEN
);
1626 const HttpHeader
*hdr_in
= &request
->header
;
1627 const HttpHeaderEntry
*e
= NULL
;
1628 HttpHeaderPos pos
= HttpHeaderInitPos
;
1629 assert (hdr_out
->owner
== hoRequest
);
1631 /* append our IMS header */
1632 if (request
->lastmod
> -1)
1633 hdr_out
->putTime(HDR_IF_MODIFIED_SINCE
, request
->lastmod
);
1635 bool we_do_ranges
= decideIfWeDoRanges (request
);
1637 String
strConnection (hdr_in
->getList(HDR_CONNECTION
));
1639 while ((e
= hdr_in
->getEntry(&pos
)))
1640 copyOneHeaderFromClientsideRequestToUpstreamRequest(e
, strConnection
, request
, hdr_out
, we_do_ranges
, flags
);
1642 /* Abstraction break: We should interpret multipart/byterange responses
1643 * into offset-length data, and this works around our inability to do so.
1645 if (!we_do_ranges
&& request
->multipartRangeRequest()) {
1646 /* don't cache the result */
1647 request
->flags
.cachable
= 0;
1648 /* pretend it's not a range request */
1649 delete request
->range
;
1650 request
->range
= NULL
;
1651 request
->flags
.isRanged
=false;
1655 if (Config
.onoff
.via
) {
1657 strVia
= hdr_in
->getList(HDR_VIA
);
1658 snprintf(bbuf
, BBUF_SZ
, "%d.%d %s",
1659 request
->http_ver
.major
,
1660 request
->http_ver
.minor
, ThisCache
);
1661 strListAdd(&strVia
, bbuf
, ',');
1662 hdr_out
->putStr(HDR_VIA
, strVia
.termedBuf());
1666 if (request
->flags
.accelerated
) {
1667 /* Append Surrogate-Capabilities */
1668 String
strSurrogate(hdr_in
->getList(HDR_SURROGATE_CAPABILITY
));
1670 snprintf(bbuf
, BBUF_SZ
, "%s=\"Surrogate/1.0 ESI/1.0\"", Config
.Accel
.surrogate_id
);
1672 snprintf(bbuf
, BBUF_SZ
, "%s=\"Surrogate/1.0\"", Config
.Accel
.surrogate_id
);
1674 strListAdd(&strSurrogate
, bbuf
, ',');
1675 hdr_out
->putStr(HDR_SURROGATE_CAPABILITY
, strSurrogate
.termedBuf());
1678 /** \pre Handle X-Forwarded-For */
1679 if (strcmp(opt_forwarded_for
, "delete") != 0) {
1681 String strFwd
= hdr_in
->getList(HDR_X_FORWARDED_FOR
);
1683 if (strFwd
.size() > 65536/2) {
1684 // There is probably a forwarding loop with Via detection disabled.
1685 // If we do nothing, String will assert on overflow soon.
1686 // TODO: Terminate all transactions with huge XFF?
1689 static int warnedCount
= 0;
1690 if (warnedCount
++ < 100) {
1691 const char *url
= entry
? entry
->url() : urlCanonical(request
);
1692 debugs(11, DBG_IMPORTANT
, "Warning: likely forwarding loop with " << url
);
1696 if (strcmp(opt_forwarded_for
, "on") == 0) {
1697 /** If set to ON - append client IP or 'unknown'. */
1698 if ( request
->client_addr
.IsNoAddr() )
1699 strListAdd(&strFwd
, "unknown", ',');
1701 strListAdd(&strFwd
, request
->client_addr
.NtoA(ntoabuf
, MAX_IPSTRLEN
), ',');
1702 } else if (strcmp(opt_forwarded_for
, "off") == 0) {
1703 /** If set to OFF - append 'unknown'. */
1704 strListAdd(&strFwd
, "unknown", ',');
1705 } else if (strcmp(opt_forwarded_for
, "transparent") == 0) {
1706 /** If set to TRANSPARENT - pass through unchanged. */
1707 } else if (strcmp(opt_forwarded_for
, "truncate") == 0) {
1708 /** If set to TRUNCATE - drop existing list and replace with client IP or 'unknown'. */
1709 if ( request
->client_addr
.IsNoAddr() )
1712 strFwd
= request
->client_addr
.NtoA(ntoabuf
, MAX_IPSTRLEN
);
1714 if (strFwd
.size() > 0)
1715 hdr_out
->putStr(HDR_X_FORWARDED_FOR
, strFwd
.termedBuf());
1717 /** If set to DELETE - do not copy through. */
1719 /* append Host if not there already */
1720 if (!hdr_out
->has(HDR_HOST
)) {
1721 if (request
->peer_domain
) {
1722 hdr_out
->putStr(HDR_HOST
, request
->peer_domain
);
1723 } else if (request
->port
== urlDefaultPort(request
->protocol
)) {
1724 /* use port# only if not default */
1725 hdr_out
->putStr(HDR_HOST
, request
->GetHost());
1727 httpHeaderPutStrf(hdr_out
, HDR_HOST
, "%s:%d",
1729 (int) request
->port
);
1733 /* append Authorization if known in URL, not in header and going direct */
1734 if (!hdr_out
->has(HDR_AUTHORIZATION
)) {
1735 if (!request
->flags
.proxying
&& request
->login
&& *request
->login
) {
1736 httpHeaderPutStrf(hdr_out
, HDR_AUTHORIZATION
, "Basic %s",
1737 old_base64_encode(request
->login
));
1741 /* Fixup (Proxy-)Authorization special cases. Plain relaying dealt with above */
1742 httpFixupAuthentication(request
, hdr_in
, hdr_out
, flags
);
1744 /* append Cache-Control, add max-age if not there already */
1746 HttpHdrCc
*cc
= hdr_in
->getCc();
1749 cc
= new HttpHdrCc();
1751 #if 0 /* see bug 2330 */
1752 /* Set no-cache if determined needed but not found */
1753 if (request
->flags
.nocache
)
1754 EBIT_SET(cc
->mask
, CC_NO_CACHE
);
1757 /* Add max-age only without no-cache */
1758 if (!cc
->hasMaxAge() && !cc
->noCache()) {
1760 entry
? entry
->url() : urlCanonical(request
);
1761 cc
->maxAge(getMaxAge(url
));
1765 /* Enforce sibling relations */
1766 if (flags
.only_if_cached
)
1767 cc
->onlyIfCached(true);
1774 /* maybe append Connection: keep-alive */
1775 if (flags
.keepalive
) {
1776 hdr_out
->putStr(HDR_CONNECTION
, "keep-alive");
1779 /* append Front-End-Https */
1780 if (flags
.front_end_https
) {
1781 if (flags
.front_end_https
== 1 || request
->protocol
== AnyP::PROTO_HTTPS
)
1782 hdr_out
->putStr(HDR_FRONT_END_HTTPS
, "On");
1785 if (flags
.chunked_request
) {
1786 // Do not just copy the original value so that if the client-side
1787 // starts decode other encodings, this code may remain valid.
1788 hdr_out
->putStr(HDR_TRANSFER_ENCODING
, "chunked");
1791 /* Now mangle the headers. */
1792 if (Config2
.onoff
.mangle_request_headers
)
1793 httpHdrMangleList(hdr_out
, request
, ROR_REQUEST
);
1795 if (Config
.request_header_add
&& !Config
.request_header_add
->empty())
1796 httpHdrAdd(hdr_out
, request
, al
, *Config
.request_header_add
);
1798 strConnection
.clean();
1802 * Decides whether a particular header may be cloned from the received Clients request
1803 * to our outgoing fetch request.
1806 copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry
*e
, const String strConnection
, const HttpRequest
* request
, HttpHeader
* hdr_out
, const int we_do_ranges
, const HttpStateFlags
&flags
)
1808 debugs(11, 5, "httpBuildRequestHeader: " << e
->name
<< ": " << e
->value
);
1812 /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid should not pass on. */
1814 case HDR_PROXY_AUTHORIZATION
:
1815 /** \par Proxy-Authorization:
1816 * Only pass on proxy authentication to peers for which
1817 * authentication forwarding is explicitly enabled
1819 if (!flags
.originpeer
&& flags
.proxying
&& request
->peer_login
&&
1820 (strcmp(request
->peer_login
, "PASS") == 0 ||
1821 strcmp(request
->peer_login
, "PROXYPASS") == 0 ||
1822 strcmp(request
->peer_login
, "PASSTHRU") == 0)) {
1823 hdr_out
->addEntry(e
->clone());
1827 /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid does not pass on. */
1829 case HDR_CONNECTION
: /** \par Connection: */
1830 case HDR_TE
: /** \par TE: */
1831 case HDR_KEEP_ALIVE
: /** \par Keep-Alive: */
1832 case HDR_PROXY_AUTHENTICATE
: /** \par Proxy-Authenticate: */
1833 case HDR_TRAILER
: /** \par Trailer: */
1834 case HDR_UPGRADE
: /** \par Upgrade: */
1835 case HDR_TRANSFER_ENCODING
: /** \par Transfer-Encoding: */
1838 /** \par OTHER headers I haven't bothered to track down yet. */
1840 case HDR_AUTHORIZATION
:
1841 /** \par WWW-Authorization:
1842 * Pass on WWW authentication */
1844 if (!flags
.originpeer
) {
1845 hdr_out
->addEntry(e
->clone());
1847 /** \note In accelerators, only forward authentication if enabled
1848 * (see also httpFixupAuthentication for special cases)
1850 if (request
->peer_login
&&
1851 (strcmp(request
->peer_login
, "PASS") == 0 ||
1852 strcmp(request
->peer_login
, "PASSTHRU") == 0 ||
1853 strcmp(request
->peer_login
, "PROXYPASS") == 0)) {
1854 hdr_out
->addEntry(e
->clone());
1862 * Normally Squid rewrites the Host: header.
1863 * However, there is one case when we don't: If the URL
1864 * went through our redirector and the admin configured
1865 * 'redir_rewrites_host' to be off.
1867 if (request
->peer_domain
)
1868 hdr_out
->putStr(HDR_HOST
, request
->peer_domain
);
1869 else if (request
->flags
.redirected
&& !Config
.onoff
.redir_rewrites_host
)
1870 hdr_out
->addEntry(e
->clone());
1872 /* use port# only if not default */
1874 if (request
->port
== urlDefaultPort(request
->protocol
)) {
1875 hdr_out
->putStr(HDR_HOST
, request
->GetHost());
1877 httpHeaderPutStrf(hdr_out
, HDR_HOST
, "%s:%d",
1879 (int) request
->port
);
1885 case HDR_IF_MODIFIED_SINCE
:
1886 /** \par If-Modified-Since:
1887 * append unless we added our own;
1888 * \note at most one client's ims header can pass through */
1890 if (!hdr_out
->has(HDR_IF_MODIFIED_SINCE
))
1891 hdr_out
->addEntry(e
->clone());
1895 case HDR_MAX_FORWARDS
:
1896 /** \par Max-Forwards:
1897 * pass only on TRACE or OPTIONS requests */
1898 if (request
->method
== METHOD_TRACE
|| request
->method
== METHOD_OPTIONS
) {
1899 const int64_t hops
= e
->getInt64();
1902 hdr_out
->putInt64(HDR_MAX_FORWARDS
, hops
- 1);
1909 * If Via is disabled then forward any received header as-is.
1910 * Otherwise leave for explicit updated addition later. */
1912 if (!Config
.onoff
.via
)
1913 hdr_out
->addEntry(e
->clone());
1921 case HDR_REQUEST_RANGE
:
1922 /** \par Range:, If-Range:, Request-Range:
1923 * Only pass if we accept ranges */
1925 hdr_out
->addEntry(e
->clone());
1929 case HDR_PROXY_CONNECTION
: // SHOULD ignore. But doing so breaks things.
1932 case HDR_CONTENT_LENGTH
:
1933 // pass through unless we chunk; also, keeping this away from default
1934 // prevents request smuggling via Connection: Content-Length tricks
1935 if (!flags
.chunked_request
)
1936 hdr_out
->addEntry(e
->clone());
1939 case HDR_X_FORWARDED_FOR
:
1941 case HDR_CACHE_CONTROL
:
1942 /** \par X-Forwarded-For:, Cache-Control:
1943 * handled specially by Squid, so leave off for now.
1944 * append these after the loop if needed */
1947 case HDR_FRONT_END_HTTPS
:
1948 /** \par Front-End-Https:
1949 * Pass thru only if peer is configured with front-end-https */
1950 if (!flags
.front_end_https
)
1951 hdr_out
->addEntry(e
->clone());
1957 * pass on all other header fields
1958 * which are NOT listed by the special Connection: header. */
1960 if (strConnection
.size()>0 && strListIsMember(&strConnection
, e
->name
.termedBuf(), ',')) {
1961 debugs(11, 2, "'" << e
->name
<< "' header cropped by Connection: definition");
1965 hdr_out
->addEntry(e
->clone());
1970 HttpStateData::decideIfWeDoRanges (HttpRequest
* request
)
1973 /* decide if we want to do Ranges ourselves
1974 * and fetch the whole object now)
1975 * We want to handle Ranges ourselves iff
1976 * - we can actually parse client Range specs
1977 * - the specs are expected to be simple enough (e.g. no out-of-order ranges)
1978 * - reply will be cachable
1979 * (If the reply will be uncachable we have to throw it away after
1980 * serving this request, so it is better to forward ranges to
1981 * the server and fetch only the requested content)
1984 int64_t roffLimit
= request
->getRangeOffsetLimit();
1986 if (NULL
== request
->range
|| !request
->flags
.cachable
1987 || request
->range
->offsetLimitExceeded(roffLimit
) || request
->flags
.connectionAuth
)
1990 debugs(11, 8, "decideIfWeDoRanges: range specs: " <<
1991 request
->range
<< ", cachable: " <<
1992 request
->flags
.cachable
<< "; we_do_ranges: " << result
);
1997 /* build request prefix and append it to a given MemBuf;
1998 * return the length of the prefix */
2000 HttpStateData::buildRequestPrefix(MemBuf
* mb
)
2002 const int offset
= mb
->size
;
2003 HttpVersion
httpver(1,1);
2005 if (_peer
&& !_peer
->options
.originserver
)
2008 url
= request
->urlpath
.termedBuf();
2009 mb
->Printf("%s %s %s/%d.%d\r\n",
2010 RequestMethodStr(request
->method
),
2011 url
&& *url
? url
: "/",
2012 AnyP::ProtocolType_str
[httpver
.protocol
],
2013 httpver
.major
,httpver
.minor
);
2014 /* build and pack headers */
2016 HttpHeader
hdr(hoRequest
);
2018 httpBuildRequestHeader(request
, entry
, fwd
->al
, &hdr
, flags
);
2020 if (request
->flags
.pinned
&& request
->flags
.connectionAuth
)
2021 request
->flags
.authSent
= 1;
2022 else if (hdr
.has(HDR_AUTHORIZATION
))
2023 request
->flags
.authSent
= 1;
2025 packerToMemInit(&p
, mb
);
2030 /* append header terminator */
2031 mb
->append(crlf
, 2);
2032 return mb
->size
- offset
;
2035 /* This will be called when connect completes. Write request. */
2037 HttpStateData::sendRequest()
2041 debugs(11, 5, HERE
<< serverConnection
<< ", request " << request
<< ", this " << this << ".");
2043 if (!Comm::IsConnOpen(serverConnection
)) {
2044 debugs(11,3, HERE
<< "cannot send request to closing " << serverConnection
);
2045 assert(closeHandler
!= NULL
);
2049 typedef CommCbMemFunT
<HttpStateData
, CommTimeoutCbParams
> TimeoutDialer
;
2050 AsyncCall::Pointer timeoutCall
= JobCallback(11, 5,
2051 TimeoutDialer
, this, HttpStateData::httpTimeout
);
2052 commSetConnTimeout(serverConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
2053 flags
.do_next_read
= true;
2054 maybeReadVirginBody();
2056 if (request
->body_pipe
!= NULL
) {
2057 if (!startRequestBodyFlow()) // register to receive body data
2059 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
2060 requestSender
= JobCallback(11,5,
2061 Dialer
, this, HttpStateData::sentRequestBody
);
2063 Must(!flags
.chunked_request
);
2064 // use chunked encoding if we do not know the length
2065 if (request
->content_length
< 0)
2066 flags
.chunked_request
= true;
2068 assert(!requestBodySource
);
2069 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
2070 requestSender
= JobCallback(11,5,
2071 Dialer
, this, HttpStateData::wroteLast
);
2074 if (_peer
!= NULL
) {
2075 if (_peer
->options
.originserver
) {
2076 flags
.proxying
= false;
2077 flags
.originpeer
= true;
2079 flags
.proxying
= false;
2080 flags
.originpeer
= false;
2083 flags
.proxying
= false;
2084 flags
.originpeer
= false;
2088 * Is keep-alive okay for all request methods?
2090 if (request
->flags
.mustKeepalive
)
2091 flags
.keepalive
= true;
2092 else if (!Config
.onoff
.server_pconns
)
2093 flags
.keepalive
= false;
2094 else if (_peer
== NULL
)
2095 flags
.keepalive
= true;
2096 else if (_peer
->stats
.n_keepalives_sent
< 10)
2097 flags
.keepalive
= true;
2098 else if ((double) _peer
->stats
.n_keepalives_recv
/
2099 (double) _peer
->stats
.n_keepalives_sent
> 0.50)
2100 flags
.keepalive
= true;
2103 /*The old code here was
2104 if (neighborType(_peer, request) == PEER_SIBLING && ...
2105 which is equivalent to:
2106 if (neighborType(_peer, NULL) == PEER_SIBLING && ...
2108 if (((_peer->type == PEER_MULTICAST && p->options.mcast_siblings) ||
2109 _peer->type == PEER_SIBLINGS ) && _peer->options.allow_miss)
2110 flags.only_if_cached = 1;
2112 But I suppose it was a bug
2114 if (neighborType(_peer
, request
) == PEER_SIBLING
&&
2115 !_peer
->options
.allow_miss
)
2116 flags
.only_if_cached
= true;
2118 flags
.front_end_https
= _peer
->front_end_https
;
2122 request
->peer_host
=_peer
?_peer
->host
:NULL
;
2123 buildRequestPrefix(&mb
);
2125 debugs(11, 2, "HTTP Server " << serverConnection
);
2126 debugs(11, 2, "HTTP Server REQUEST:\n---------\n" << mb
.buf
<< "\n----------");
2128 Comm::Write(serverConnection
, &mb
, requestSender
);
2133 HttpStateData::getMoreRequestBody(MemBuf
&buf
)
2135 // parent's implementation can handle the no-encoding case
2136 if (!flags
.chunked_request
)
2137 return ServerStateData::getMoreRequestBody(buf
);
2141 Must(requestBodySource
!= NULL
);
2142 if (!requestBodySource
->getMoreData(raw
))
2143 return false; // no request body bytes to chunk yet
2145 // optimization: pre-allocate buffer size that should be enough
2146 const mb_size_t rawDataSize
= raw
.contentSize();
2147 // we may need to send: hex-chunk-size CRLF raw-data CRLF last-chunk
2148 buf
.init(16 + 2 + rawDataSize
+ 2 + 5, raw
.max_capacity
);
2150 buf
.Printf("%x\r\n", static_cast<unsigned int>(rawDataSize
));
2151 buf
.append(raw
.content(), rawDataSize
);
2154 Must(rawDataSize
> 0); // we did not accidently created last-chunk above
2156 // Do not send last-chunk unless we successfully received everything
2157 if (receivedWholeRequestBody
) {
2158 Must(!flags
.sentLastChunk
);
2159 flags
.sentLastChunk
= true;
2160 buf
.append("0\r\n\r\n", 5);
2167 httpStart(FwdState
*fwd
)
2169 debugs(11, 3, "httpStart: \"" << RequestMethodStr(fwd
->request
->method
) << " " << fwd
->entry
->url() << "\"" );
2170 AsyncJob::Start(new HttpStateData(fwd
));
2174 HttpStateData::start()
2176 if (!sendRequest()) {
2177 debugs(11, 3, "httpStart: aborted");
2178 mustStop("HttpStateData::start failed");
2182 ++ statCounter
.server
.all
.requests
;
2183 ++ statCounter
.server
.http
.requests
;
2186 * We used to set the read timeout here, but not any more.
2187 * Now its set in httpSendComplete() after the full request,
2188 * including request body, has been written to the server.
2192 /// if broken posts are enabled for the request, try to fix and return true
2194 HttpStateData::finishingBrokenPost()
2196 #if USE_HTTP_VIOLATIONS
2197 if (!Config
.accessList
.brokenPosts
) {
2198 debugs(11, 5, HERE
<< "No brokenPosts list");
2202 ACLFilledChecklist
ch(Config
.accessList
.brokenPosts
, originalRequest(), NULL
);
2203 if (ch
.fastCheck() != ACCESS_ALLOWED
) {
2204 debugs(11, 5, HERE
<< "didn't match brokenPosts");
2208 if (!Comm::IsConnOpen(serverConnection
)) {
2209 debugs(11, 3, HERE
<< "ignoring broken POST for closed " << serverConnection
);
2210 assert(closeHandler
!= NULL
);
2211 return true; // prevent caller from proceeding as if nothing happened
2214 debugs(11, 3, "finishingBrokenPost: fixing broken POST");
2215 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
2216 requestSender
= JobCallback(11,5,
2217 Dialer
, this, HttpStateData::wroteLast
);
2218 Comm::Write(serverConnection
, "\r\n", 2, requestSender
, NULL
);
2222 #endif /* USE_HTTP_VIOLATIONS */
2225 /// if needed, write last-chunk to end the request body and return true
2227 HttpStateData::finishingChunkedRequest()
2229 if (flags
.sentLastChunk
) {
2230 debugs(11, 5, HERE
<< "already sent last-chunk");
2234 Must(receivedWholeRequestBody
); // or we should not be sending last-chunk
2235 flags
.sentLastChunk
= true;
2237 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
2238 requestSender
= JobCallback(11,5, Dialer
, this, HttpStateData::wroteLast
);
2239 Comm::Write(serverConnection
, "0\r\n\r\n", 5, requestSender
, NULL
);
2244 HttpStateData::doneSendingRequestBody()
2246 ServerStateData::doneSendingRequestBody();
2247 debugs(11,5, HERE
<< serverConnection
);
2249 // do we need to write something after the last body byte?
2250 if (flags
.chunked_request
&& finishingChunkedRequest())
2252 if (!flags
.chunked_request
&& finishingBrokenPost())
2258 // more origin request body data is available
2260 HttpStateData::handleMoreRequestBodyAvailable()
2262 if (eof
|| !Comm::IsConnOpen(serverConnection
)) {
2263 // XXX: we should check this condition in other callbacks then!
2264 // TODO: Check whether this can actually happen: We should unsubscribe
2265 // as a body consumer when the above condition(s) are detected.
2266 debugs(11, DBG_IMPORTANT
, HERE
<< "Transaction aborted while reading HTTP body");
2270 assert(requestBodySource
!= NULL
);
2272 if (requestBodySource
->buf().hasContent()) {
2273 // XXX: why does not this trigger a debug message on every request?
2275 if (flags
.headers_parsed
&& !flags
.abuse_detected
) {
2276 flags
.abuse_detected
= true;
2277 debugs(11, DBG_IMPORTANT
, "http handleMoreRequestBodyAvailable: Likely proxy abuse detected '" << request
->client_addr
<< "' -> '" << entry
->url() << "'" );
2279 if (virginReply()->sline
.status
== HTTP_INVALID_HEADER
) {
2280 serverConnection
->close();
2286 HttpStateData::handleMoreRequestBodyAvailable();
2289 // premature end of the request body
2291 HttpStateData::handleRequestBodyProducerAborted()
2293 ServerStateData::handleRequestBodyProducerAborted();
2294 if (entry
->isEmpty()) {
2295 debugs(11, 3, "request body aborted: " << serverConnection
);
2296 // We usually get here when ICAP REQMOD aborts during body processing.
2297 // We might also get here if client-side aborts, but then our response
2298 // should not matter because either client-side will provide its own or
2299 // there will be no response at all (e.g., if the the client has left).
2300 ErrorState
*err
= new ErrorState(ERR_ICAP_FAILURE
, HTTP_INTERNAL_SERVER_ERROR
, fwd
->request
);
2301 err
->detailError(ERR_DETAIL_SRV_REQMOD_REQ_BODY
);
2305 abortTransaction("request body producer aborted");
2308 // called when we wrote request headers(!) or a part of the body
2310 HttpStateData::sentRequestBody(const CommIoCbParams
&io
)
2313 kb_incr(&statCounter
.server
.http
.kbytes_out
, io
.size
);
2315 ServerStateData::sentRequestBody(io
);
2318 // Quickly abort the transaction
2319 // TODO: destruction should be sufficient as the destructor should cleanup,
2320 // including canceling close handlers
2322 HttpStateData::abortTransaction(const char *reason
)
2324 debugs(11,5, HERE
<< "aborting transaction for " << reason
<<
2325 "; " << serverConnection
<< ", this " << this);
2327 if (Comm::IsConnOpen(serverConnection
)) {
2328 serverConnection
->close();
2332 fwd
->handleUnregisteredServerEnd();
2333 mustStop("HttpStateData::abortTransaction");