5 * DEBUG: section 11 Hypertext Transfer Protocol (HTTP)
6 * AUTHOR: Harvest Derived
8 * SQUID Web Proxy Cache http://www.squid-cache.org/
9 * ----------------------------------------------------------
11 * Squid is the result of efforts by numerous individuals from
12 * the Internet community; see the CONTRIBUTORS file for full
13 * details. Many organizations have provided support for Squid's
14 * development; see the SPONSORS file for full details. Squid is
15 * Copyrighted (C) 2001 by the Regents of the University of
16 * California; see the COPYRIGHT file for full details. Squid
17 * incorporates software developed and/or copyrighted by other
18 * sources; see the CREDITS file for full details.
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 2 of the License, or
23 * (at your option) any later version.
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
30 * You should have received a copy of the GNU General Public License
31 * along with this program; if not, write to the Free Software
32 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
37 * Anonymizing patch by lutz@as-node.jena.thur.de
38 * have a look into http-anon.c to get more informations.
42 #include "errorpage.h"
45 #include "auth/UserRequest.h"
47 #include "HttpReply.h"
48 #include "HttpRequest.h"
49 #include "MemObject.h"
50 #include "HttpHdrContRange.h"
51 #include "HttpHdrSc.h"
52 #include "HttpHdrScTarget.h"
53 #include "acl/FilledChecklist.h"
56 #include "DelayPools.h"
58 #include "SquidTime.h"
59 #include "TextException.h"
61 #define SQUID_ENTER_THROWING_CODE() try {
62 #define SQUID_EXIT_THROWING_CODE(status) \
65 catch (const std::exception &e) { \
66 debugs (11, 1, "Exception error:" << e.what()); \
70 CBDATA_CLASS_INIT(HttpStateData
);
72 static const char *const crlf
= "\r\n";
74 static void httpMaybeRemovePublic(StoreEntry
*, http_status
);
75 static void copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry
*e
, const String strConnection
, HttpRequest
* request
, const HttpRequest
* orig_request
,
76 HttpHeader
* hdr_out
, const int we_do_ranges
, const http_state_flags
);
78 HttpStateData::HttpStateData(FwdState
*theFwdState
) : AsyncJob("HttpStateData"), ServerStateData(theFwdState
),
79 lastChunk(0), header_bytes_read(0), reply_bytes_read(0),
80 body_bytes_truncated(0), httpChunkDecoder(NULL
)
82 debugs(11,5,HERE
<< "HttpStateData " << this << " created");
83 ignoreCacheControl
= false;
84 surrogateNoStore
= false;
88 orig_request
= HTTPMSGLOCK(fwd
->request
);
91 _peer
= fwd
->servers
->_peer
; /* might be NULL */
96 if (_peer
->options
.originserver
)
97 url
= orig_request
->urlpath
.termedBuf();
101 HttpRequest
* proxy_req
= new HttpRequest(orig_request
->method
,
102 orig_request
->protocol
, url
);
104 proxy_req
->SetHost(_peer
->host
);
106 proxy_req
->port
= _peer
->http_port
;
108 proxy_req
->flags
= orig_request
->flags
;
110 proxy_req
->lastmod
= orig_request
->lastmod
;
112 proxy_req
->flags
.proxying
= 1;
114 HTTPMSGUNLOCK(request
);
116 request
= HTTPMSGLOCK(proxy_req
);
119 * This NEIGHBOR_PROXY_ONLY check probably shouldn't be here.
120 * We might end up getting the object from somewhere else if,
121 * for example, the request to this neighbor fails.
123 if (_peer
->options
.proxy_only
)
124 entry
->releaseRequest();
128 entry
->setNoDelay(_peer
->options
.no_delay
);
134 * register the handler to free HTTP state data when the FD closes
136 typedef CommCbMemFunT
<HttpStateData
, CommCloseCbParams
> Dialer
;
137 closeHandler
= asyncCall(9, 5, "httpStateData::httpStateConnClosed",
138 Dialer(this,&HttpStateData::httpStateConnClosed
));
139 comm_add_close_handler(fd
, closeHandler
);
142 HttpStateData::~HttpStateData()
145 * don't forget that ~ServerStateData() gets called automatically
148 if (!readBuf
->isNull())
153 if (httpChunkDecoder
)
154 delete httpChunkDecoder
;
156 HTTPMSGUNLOCK(orig_request
);
158 debugs(11,5, HERE
<< "HttpStateData " << this << " destroyed; FD " << fd
);
162 HttpStateData::dataDescriptor() const
168 httpStateFree(int fd, void *data)
170 HttpStateData *httpState = static_cast<HttpStateData *>(data);
171 debugs(11, 5, "httpStateFree: FD " << fd << ", httpState=" << data);
176 HttpStateData::httpStateConnClosed(const CommCloseCbParams
¶ms
)
178 debugs(11, 5, "httpStateFree: FD " << params
.fd
<< ", httpState=" << params
.data
);
179 deleteThis("HttpStateData::httpStateConnClosed");
183 httpCachable(const HttpRequestMethod
& method
)
185 /* GET and HEAD are cachable. Others are not. */
187 // TODO: replase to HttpRequestMethod::isCachable() ?
188 if (method
!= METHOD_GET
&& method
!= METHOD_HEAD
)
196 HttpStateData::httpTimeout(const CommTimeoutCbParams
¶ms
)
198 debugs(11, 4, "httpTimeout: FD " << fd
<< ": '" << entry
->url() << "'" );
200 if (entry
->store_status
== STORE_PENDING
) {
201 fwd
->fail(errorCon(ERR_READ_TIMEOUT
, HTTP_GATEWAY_TIMEOUT
, fwd
->request
));
208 httpMaybeRemovePublic(StoreEntry
* e
, http_status status
)
214 if (!EBIT_TEST(e
->flags
, KEY_PRIVATE
))
221 case HTTP_NON_AUTHORITATIVE_INFORMATION
:
223 case HTTP_MULTIPLE_CHOICES
:
225 case HTTP_MOVED_PERMANENTLY
:
227 case HTTP_MOVED_TEMPORARILY
:
238 case HTTP_METHOD_NOT_ALLOWED
:
245 case HTTP_UNAUTHORIZED
:
255 * Any 2xx response should eject previously cached entities...
258 if (status
>= 200 && status
< 300)
266 if (!remove
&& !forbidden
)
271 if (e
->mem_obj
->request
)
272 pe
= storeGetPublicByRequest(e
->mem_obj
->request
);
274 pe
= storeGetPublic(e
->mem_obj
->url
, e
->mem_obj
->method
);
279 neighborsHtcpClear(e
, NULL
, e
->mem_obj
->request
, e
->mem_obj
->method
, HTCP_CLR_INVALIDATION
);
285 * Also remove any cached HEAD response in case the object has
288 if (e
->mem_obj
->request
)
289 pe
= storeGetPublicByRequestMethod(e
->mem_obj
->request
, METHOD_HEAD
);
291 pe
= storeGetPublic(e
->mem_obj
->url
, METHOD_HEAD
);
296 neighborsHtcpClear(e
, NULL
, e
->mem_obj
->request
, HttpRequestMethod(METHOD_HEAD
), HTCP_CLR_INVALIDATION
);
303 HttpStateData::processSurrogateControl(HttpReply
*reply
)
307 if (request
->flags
.accelerated
&& reply
->surrogate_control
) {
308 HttpHdrScTarget
*sctusable
=
309 httpHdrScGetMergedTarget(reply
->surrogate_control
,
310 Config
.Accel
.surrogate_id
);
313 if (EBIT_TEST(sctusable
->mask
, SC_NO_STORE
) ||
314 (Config
.onoff
.surrogate_is_remote
315 && EBIT_TEST(sctusable
->mask
, SC_NO_STORE_REMOTE
))) {
316 surrogateNoStore
= true;
317 entry
->makePrivate();
320 /* The HttpHeader logic cannot tell if the header it's parsing is a reply to an
321 * accelerated request or not...
322 * Still, this is an abtraction breach. - RC
324 if (sctusable
->max_age
!= -1) {
325 if (sctusable
->max_age
< sctusable
->max_stale
)
326 reply
->expires
= reply
->date
+ sctusable
->max_age
;
328 reply
->expires
= reply
->date
+ sctusable
->max_stale
;
330 /* And update the timestamps */
331 entry
->timestampsSet();
334 /* We ignore cache-control directives as per the Surrogate specification */
335 ignoreCacheControl
= true;
337 httpHdrScTargetDestroy(sctusable
);
345 HttpStateData::cacheableReply()
347 HttpReply
const *rep
= finalReply();
348 HttpHeader
const *hdr
= &rep
->header
;
349 const int cc_mask
= (rep
->cache_control
) ? rep
->cache_control
->mask
: 0;
353 const refresh_t
*R
= NULL
;
355 /* This strange looking define first looks up the refresh pattern
356 * and then checks if the specified flag is set. The main purpose
357 * of this is to simplify the refresh pattern lookup and HTTP_VIOLATIONS
360 #define REFRESH_OVERRIDE(flag) \
361 ((R = (R ? R : refreshLimits(entry->mem_obj->url))) , \
362 (R && R->flags.flag))
364 #define REFRESH_OVERRIDE(flag) 0
367 if (surrogateNoStore
)
370 if (!ignoreCacheControl
) {
371 if (EBIT_TEST(cc_mask
, CC_PRIVATE
)) {
372 if (!REFRESH_OVERRIDE(ignore_private
))
376 if (EBIT_TEST(cc_mask
, CC_NO_CACHE
)) {
377 if (!REFRESH_OVERRIDE(ignore_no_cache
))
381 if (EBIT_TEST(cc_mask
, CC_NO_STORE
)) {
382 if (!REFRESH_OVERRIDE(ignore_no_store
))
387 if (request
->flags
.auth
|| request
->flags
.auth_sent
) {
389 * Responses to requests with authorization may be cached
390 * only if a Cache-Control: public reply header is present.
391 * RFC 2068, sec 14.9.4
394 if (!EBIT_TEST(cc_mask
, CC_PUBLIC
)) {
395 if (!REFRESH_OVERRIDE(ignore_auth
))
400 /* Pragma: no-cache in _replies_ is not documented in HTTP,
401 * but servers like "Active Imaging Webcast/2.0" sure do use it */
402 if (hdr
->has(HDR_PRAGMA
)) {
403 String s
= hdr
->getList(HDR_PRAGMA
);
404 const int no_cache
= strListIsMember(&s
, "no-cache", ',');
408 if (!REFRESH_OVERRIDE(ignore_no_cache
))
414 * The "multipart/x-mixed-replace" content type is used for
415 * continuous push replies. These are generally dynamic and
416 * probably should not be cachable
418 if ((v
= hdr
->getStr(HDR_CONTENT_TYPE
)))
419 if (!strncasecmp(v
, "multipart/x-mixed-replace", 25))
422 switch (rep
->sline
.status
) {
423 /* Responses that are cacheable */
427 case HTTP_NON_AUTHORITATIVE_INFORMATION
:
429 case HTTP_MULTIPLE_CHOICES
:
431 case HTTP_MOVED_PERMANENTLY
:
435 * Don't cache objects that need to be refreshed on next request,
436 * unless we know how to refresh it.
439 if (!refreshIsCachable(entry
)) {
440 debugs(22, 3, "refreshIsCachable() returned non-cacheable..");
444 /* don't cache objects from peers w/o LMT, Date, or Expires */
445 /* check that is it enough to check headers @?@ */
448 else if (rep
->last_modified
> -1)
453 /* @?@ (here and 302): invalid expires header compiles to squid_curtime */
454 else if (rep
->expires
> -1)
462 /* Responses that only are cacheable if the server says so */
464 case HTTP_MOVED_TEMPORARILY
:
465 case HTTP_TEMPORARY_REDIRECT
:
466 if (rep
->expires
> rep
->date
&& rep
->date
> 0)
474 /* Errors can be negatively cached */
476 case HTTP_NO_CONTENT
:
480 case HTTP_BAD_REQUEST
:
486 case HTTP_METHOD_NOT_ALLOWED
:
488 case HTTP_REQUEST_URI_TOO_LARGE
:
490 case HTTP_INTERNAL_SERVER_ERROR
:
492 case HTTP_NOT_IMPLEMENTED
:
494 case HTTP_BAD_GATEWAY
:
496 case HTTP_SERVICE_UNAVAILABLE
:
498 case HTTP_GATEWAY_TIMEOUT
:
504 /* Some responses can never be cached */
506 case HTTP_PARTIAL_CONTENT
: /* Not yet supported */
510 case HTTP_NOT_MODIFIED
:
512 case HTTP_UNAUTHORIZED
:
514 case HTTP_PROXY_AUTHENTICATION_REQUIRED
:
516 case HTTP_INVALID_HEADER
: /* Squid header parsing error */
518 case HTTP_HEADER_TOO_LARGE
:
520 case HTTP_PAYMENT_REQUIRED
:
521 case HTTP_NOT_ACCEPTABLE
:
522 case HTTP_REQUEST_TIMEOUT
:
524 case HTTP_LENGTH_REQUIRED
:
525 case HTTP_PRECONDITION_FAILED
:
526 case HTTP_REQUEST_ENTITY_TOO_LARGE
:
527 case HTTP_UNSUPPORTED_MEDIA_TYPE
:
528 case HTTP_UNPROCESSABLE_ENTITY
:
530 case HTTP_FAILED_DEPENDENCY
:
531 case HTTP_INSUFFICIENT_STORAGE
:
532 case HTTP_REQUESTED_RANGE_NOT_SATISFIABLE
:
533 case HTTP_EXPECTATION_FAILED
:
537 default: /* Unknown status code */
538 debugs (11, 0, HERE
<< "HttpStateData::cacheableReply: unexpected http status code " << rep
->sline
.status
);
550 * For Vary, store the relevant request headers as
551 * virtual headers in the reply
552 * Returns false if the variance cannot be stored
555 httpMakeVaryMark(HttpRequest
* request
, HttpReply
const * reply
)
558 const char *pos
= NULL
;
565 vary
= reply
->header
.getList(HDR_VARY
);
567 while (strListGetItem(&vary
, ',', &item
, &ilen
, &pos
)) {
568 char *name
= (char *)xmalloc(ilen
+ 1);
569 xstrncpy(name
, item
, ilen
+ 1);
572 if (strcmp(name
, "*") == 0) {
573 /* Can not handle "Vary: *" withtout ETag support */
579 strListAdd(&vstr
, name
, ',');
580 hdr
= request
->header
.getByName(name
);
582 value
= hdr
.termedBuf();
585 value
= rfc1738_escape_part(value
);
586 vstr
.append("=\"", 2);
588 vstr
.append("\"", 1);
595 #if X_ACCELERATOR_VARY
598 vary
= reply
->header
.getList(HDR_X_ACCELERATOR_VARY
);
600 while (strListGetItem(&vary
, ',', &item
, &ilen
, &pos
)) {
601 char *name
= (char *)xmalloc(ilen
+ 1);
602 xstrncpy(name
, item
, ilen
+ 1);
604 strListAdd(&vstr
, name
, ',');
605 hdr
= request
->header
.getByName(name
);
607 value
= hdr
.termedBuf();
610 value
= rfc1738_escape_part(value
);
611 vstr
.append("=\"", 2);
613 vstr
.append("\"", 1);
622 debugs(11, 3, "httpMakeVaryMark: " << vstr
);
623 return vstr
.termedBuf();
627 HttpStateData::keepaliveAccounting(HttpReply
*reply
)
631 _peer
->stats
.n_keepalives_sent
++;
633 if (reply
->keep_alive
) {
635 _peer
->stats
.n_keepalives_recv
++;
637 if (Config
.onoff
.detect_broken_server_pconns
638 && reply
->bodySize(request
->method
) == -1 && !flags
.chunked
) {
639 debugs(11, 1, "keepaliveAccounting: Impossible keep-alive header from '" << entry
->url() << "'" );
640 // debugs(11, 2, "GOT HTTP REPLY HDR:\n---------\n" << readBuf->content() << "\n----------" );
641 flags
.keepalive_broken
= 1;
647 HttpStateData::checkDateSkew(HttpReply
*reply
)
649 if (reply
->date
> -1 && !_peer
) {
650 int skew
= abs((int)(reply
->date
- squid_curtime
));
653 debugs(11, 3, "" << request
->GetHost() << "'s clock is skewed by " << skew
<< " seconds!");
658 * This creates the error page itself.. its likely
659 * that the forward ported reply header max size patch
660 * generates non http conformant error pages - in which
661 * case the errors where should be 'BAD_GATEWAY' etc
664 HttpStateData::processReplyHeader()
666 /** Creates a blank header. If this routine is made incremental, this will not do */
667 Ctx ctx
= ctx_enter(entry
->mem_obj
->url
);
668 debugs(11, 3, "processReplyHeader: key '" << entry
->getMD5Text() << "'");
670 assert(!flags
.headers_parsed
);
672 http_status error
= HTTP_STATUS_NONE
;
674 HttpReply
*newrep
= new HttpReply
;
675 const bool parsed
= newrep
->parse(readBuf
, eof
, &error
);
677 if (!parsed
&& readBuf
->contentSize() > 5 && strncmp(readBuf
->content(), "HTTP/", 5) != 0) {
679 HttpReply
*tmprep
= new HttpReply
;
680 tmprep
->sline
.version
= HttpVersion(1, 0);
681 tmprep
->sline
.status
= HTTP_OK
;
682 tmprep
->header
.putTime(HDR_DATE
, squid_curtime
);
683 tmprep
->header
.putExt("X-Transformed-From", "HTTP/0.9");
685 newrep
->parse(mb
, eof
, &error
);
688 if (!parsed
&& error
> 0) { // unrecoverable parsing error
689 debugs(11, 3, "processReplyHeader: Non-HTTP-compliant header: '" << readBuf
->content() << "'");
690 flags
.headers_parsed
= 1;
691 newrep
->sline
.version
= HttpVersion(1, 0);
692 newrep
->sline
.status
= error
;
693 HttpReply
*vrep
= setVirginReply(newrep
);
694 entry
->replaceHttpReply(vrep
);
699 if (!parsed
) { // need more data
707 debugs(11, 9, "GOT HTTP REPLY HDR:\n---------\n" << readBuf
->content() << "\n----------");
709 header_bytes_read
= headersEnd(readBuf
->content(), readBuf
->contentSize());
710 readBuf
->consume(header_bytes_read
);
714 if (newrep
->header
.hasListMember(HDR_TRANSFER_ENCODING
, "chunked", ',')) {
716 httpChunkDecoder
= new ChunkedCodingParser
;
719 if (!peerSupportsConnectionPinning())
720 orig_request
->flags
.connection_auth_disabled
= 1;
722 HttpReply
*vrep
= setVirginReply(newrep
);
723 flags
.headers_parsed
= 1;
725 keepaliveAccounting(vrep
);
729 processSurrogateControl (vrep
);
731 /** \todo IF the reply is a 1.0 reply, AND it has a Connection: Header
732 * Parse the header and remove all referenced headers
740 * returns true if the peer can support connection pinning
742 bool HttpStateData::peerSupportsConnectionPinning() const
744 const HttpReply
*rep
= entry
->mem_obj
->getReply();
745 const HttpHeader
*hdr
= &rep
->header
;
752 /*If this peer does not support connection pinning (authenticated
753 connections) return false
755 if (!_peer
->connection_auth
)
758 /*The peer supports connection pinning and the http reply status
759 is not unauthorized, so the related connection can be pinned
761 if (rep
->sline
.status
!= HTTP_UNAUTHORIZED
)
764 /*The server respond with HTTP_UNAUTHORIZED and the peer configured
765 with "connection-auth=on" we know that the peer supports pinned
768 if (_peer
->connection_auth
== 1)
771 /*At this point peer has configured with "connection-auth=auto"
772 parameter so we need some extra checks to decide if we are going
773 to allow pinned connections or not
776 /*if the peer configured with originserver just allow connection
777 pinning (squid 2.6 behaviour)
779 if (_peer
->options
.originserver
)
782 /*if the connections it is already pinned it is OK*/
783 if (request
->flags
.pinned
)
786 /*Allow pinned connections only if the Proxy-support header exists in
787 reply and has in its list the "Session-Based-Authentication"
788 which means that the peer supports connection pinning.
790 if (!hdr
->has(HDR_PROXY_SUPPORT
))
793 header
= hdr
->getStrOrList(HDR_PROXY_SUPPORT
);
794 /* XXX This ought to be done in a case-insensitive manner */
795 rc
= (strstr(header
.termedBuf(), "Session-Based-Authentication") != NULL
);
800 // Called when we parsed (and possibly adapted) the headers but
801 // had not starting storing (a.k.a., sending) the body yet.
803 HttpStateData::haveParsedReplyHeaders()
805 ServerStateData::haveParsedReplyHeaders();
807 Ctx ctx
= ctx_enter(entry
->mem_obj
->url
);
808 HttpReply
*rep
= finalReply();
810 if (rep
->sline
.status
== HTTP_PARTIAL_CONTENT
&&
812 currentOffset
= rep
->content_range
->spec
.offset
;
814 entry
->timestampsSet();
816 /* Check if object is cacheable or not based on reply code */
817 debugs(11, 3, "haveParsedReplyHeaders: HTTP CODE: " << rep
->sline
.status
);
819 if (neighbors_do_private_keys
)
820 httpMaybeRemovePublic(entry
, rep
->sline
.status
);
822 if (rep
->header
.has(HDR_VARY
)
823 #if X_ACCELERATOR_VARY
824 || rep
->header
.has(HDR_X_ACCELERATOR_VARY
)
827 const char *vary
= httpMakeVaryMark(orig_request
, rep
);
830 entry
->makePrivate();
835 entry
->mem_obj
->vary_headers
= xstrdup(vary
);
843 * If its not a reply that we will re-forward, then
844 * allow the client to get it.
846 if (!fwd
->reforwardableStatus(rep
->sline
.status
))
847 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
849 switch (cacheableReply()) {
856 entry
->makePrivate();
862 if (Config
.negativeTtl
> 0)
863 entry
->cacheNegatively();
866 entry
->makePrivate();
878 if (!ignoreCacheControl
&& rep
->cache_control
) {
879 if (EBIT_TEST(rep
->cache_control
->mask
, CC_PROXY_REVALIDATE
))
880 EBIT_SET(entry
->flags
, ENTRY_REVALIDATE
);
881 else if (EBIT_TEST(rep
->cache_control
->mask
, CC_MUST_REVALIDATE
))
882 EBIT_SET(entry
->flags
, ENTRY_REVALIDATE
);
886 headersLog(1, 0, request
->method
, rep
);
893 HttpStateData::ConnectionStatus
894 HttpStateData::statusIfComplete() const
896 const HttpReply
*rep
= virginReply();
898 * If the reply wants to close the connection, it takes precedence */
900 if (httpHeaderHasConnDir(&rep
->header
, "close"))
901 return COMPLETE_NONPERSISTENT_MSG
;
904 * If we didn't send a keep-alive request header, then this
905 * can not be a persistent connection.
907 if (!flags
.keepalive
)
908 return COMPLETE_NONPERSISTENT_MSG
;
911 * If we haven't sent the whole request then this can not be a persistent
914 if (!flags
.request_sent
) {
915 debugs(11, 1, "statusIfComplete: Request not yet fully sent \"" << RequestMethodStr(orig_request
->method
) << " " << entry
->url() << "\"" );
916 return COMPLETE_NONPERSISTENT_MSG
;
920 * What does the reply have to say about keep-alive?
924 * If the origin server (HTTP/1.0) does not send a keep-alive
925 * header, but keeps the connection open anyway, what happens?
926 * We'll return here and http.c waits for an EOF before changing
927 * store_status to STORE_OK. Combine this with ENTRY_FWD_HDR_WAIT
928 * and an error status code, and we might have to wait until
929 * the server times out the socket.
931 if (!rep
->keep_alive
)
932 return COMPLETE_NONPERSISTENT_MSG
;
934 return COMPLETE_PERSISTENT_MSG
;
937 HttpStateData::ConnectionStatus
938 HttpStateData::persistentConnStatus() const
940 debugs(11, 3, "persistentConnStatus: FD " << fd
<< " eof=" << eof
);
941 const HttpReply
*vrep
= virginReply();
942 debugs(11, 5, "persistentConnStatus: content_length=" << vrep
->content_length
);
944 /* If we haven't seen the end of reply headers, we are not done */
945 debugs(11, 5, "persistentConnStatus: flags.headers_parsed=" << flags
.headers_parsed
);
947 if (!flags
.headers_parsed
)
948 return INCOMPLETE_MSG
;
950 if (eof
) // already reached EOF
951 return COMPLETE_NONPERSISTENT_MSG
;
954 * In chunked response we do not know the content length but we are absolutely
955 * sure about the end of response, so we are calling the statusIfComplete to
956 * decide if we can be persistant
958 if (lastChunk
&& flags
.chunked
)
959 return statusIfComplete();
961 const int64_t clen
= vrep
->bodySize(request
->method
);
963 debugs(11, 5, "persistentConnStatus: clen=" << clen
);
965 /* If the body size is unknown we must wait for EOF */
967 return INCOMPLETE_MSG
;
970 * If the body size is known, we must wait until we've gotten all of it. */
973 // if (entry->mem_obj->endOffset() < vrep->content_length + vrep->hdr_sz)
974 const int64_t body_bytes_read
= reply_bytes_read
- header_bytes_read
;
975 debugs(11,5, "persistentConnStatus: body_bytes_read=" <<
976 body_bytes_read
<< " content_length=" << vrep
->content_length
);
978 if (body_bytes_read
< vrep
->content_length
)
979 return INCOMPLETE_MSG
;
981 if (body_bytes_truncated
> 0) // already read more than needed
982 return COMPLETE_NONPERSISTENT_MSG
; // disable pconns
986 * If there is no message body or we got it all, we can be persistent */
987 return statusIfComplete();
991 * This is the callback after some data has been read from the network
995 HttpStateData::ReadReplyWrapper(int fd, char *buf, size_t len, comm_err_t flag, int xerrno, void *data)
997 HttpStateData *httpState = static_cast<HttpStateData *>(data);
998 assert (fd == httpState->fd);
999 // assert(buf == readBuf->content());
1000 PROF_start(HttpStateData_readReply);
1001 httpState->readReply(len, flag, xerrno);
1002 PROF_stop(HttpStateData_readReply);
1006 /* XXX this function is too long! */
1008 HttpStateData::readReply(const CommIoCbParams
&io
)
1014 assert(fd
== io
.fd
);
1016 flags
.do_next_read
= 0;
1018 debugs(11, 5, "httpReadReply: FD " << fd
<< ": len " << len
<< ".");
1020 // Bail out early on COMM_ERR_CLOSING - close handlers will tidy up for us
1021 if (io
.flag
== COMM_ERR_CLOSING
) {
1022 debugs(11, 3, "http socket closing");
1026 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1027 maybeReadVirginBody();
1031 // handle I/O errors
1032 if (io
.flag
!= COMM_OK
|| len
< 0) {
1033 debugs(11, 2, "httpReadReply: FD " << fd
<< ": read failure: " << xstrerror() << ".");
1035 if (ignoreErrno(io
.xerrno
)) {
1036 flags
.do_next_read
= 1;
1039 err
= errorCon(ERR_READ_ERROR
, HTTP_BAD_GATEWAY
, fwd
->request
);
1040 err
->xerrno
= io
.xerrno
;
1042 flags
.do_next_read
= 0;
1051 readBuf
->appended(len
);
1052 reply_bytes_read
+= len
;
1055 DelayId delayId
= entry
->mem_obj
->mostBytesAllowed();
1056 delayId
.bytesIn(len
);
1059 kb_incr(&statCounter
.server
.all
.kbytes_in
, len
);
1060 kb_incr(&statCounter
.server
.http
.kbytes_in
, len
);
1061 IOStats
.Http
.reads
++;
1063 for (clen
= len
- 1, bin
= 0; clen
; bin
++)
1066 IOStats
.Http
.read_hist
[bin
]++;
1070 * Here the RFC says we should ignore whitespace between replies, but we can't as
1071 * doing so breaks HTTP/0.9 replies beginning with witespace, and in addition
1072 * the response splitting countermeasures is extremely likely to trigger on this,
1073 * not allowing connection reuse in the first place.
1076 if (!flags
.headers_parsed
&& len
> 0 && fd_table
[fd
].uses
> 1) {
1077 /* Skip whitespace between replies */
1079 while (len
> 0 && xisspace(*buf
))
1080 xmemmove(buf
, buf
+ 1, len
--);
1083 /* Continue to read... */
1084 /* Timeout NOT increased. This whitespace was from previous reply */
1085 flags
.do_next_read
= 1;
1086 maybeReadVirginBody();
1093 if (len
== 0) { // reached EOF?
1095 flags
.do_next_read
= 0;
1098 if (!flags
.headers_parsed
) { // have not parsed headers yet?
1099 PROF_start(HttpStateData_processReplyHeader
);
1100 processReplyHeader();
1101 PROF_stop(HttpStateData_processReplyHeader
);
1103 if (!continueAfterParsingHeader()) // parsing error or need more data
1104 return; // TODO: send errors to ICAP
1106 adaptOrFinalizeReply();
1109 // kick more reads if needed and/or process the response body, if any
1110 PROF_start(HttpStateData_processReplyBody
);
1111 processReplyBody(); // may call serverComplete()
1112 PROF_stop(HttpStateData_processReplyBody
);
1116 \retval true if we can continue with processing the body or doing ICAP.
1119 HttpStateData::continueAfterParsingHeader()
1121 if (!flags
.headers_parsed
&& !eof
) {
1122 debugs(11, 9, HERE
<< "needs more at " << readBuf
->contentSize());
1123 flags
.do_next_read
= 1;
1124 /** \retval false If we have not finished parsing the headers and may get more data.
1125 * Schedules more reads to retrieve the missing data.
1127 maybeReadVirginBody(); // schedules all kinds of reads; TODO: rename
1131 /** If we are done with parsing, check for errors */
1133 err_type error
= ERR_NONE
;
1135 if (flags
.headers_parsed
) { // parsed headers, possibly with errors
1136 // check for header parsing errors
1137 if (HttpReply
*vrep
= virginReply()) {
1138 const http_status s
= vrep
->sline
.status
;
1139 const HttpVersion
&v
= vrep
->sline
.version
;
1140 if (s
== HTTP_INVALID_HEADER
&& v
!= HttpVersion(0,9)) {
1141 error
= ERR_INVALID_RESP
;
1143 if (s
== HTTP_HEADER_TOO_LARGE
) {
1144 fwd
->dontRetry(true);
1145 error
= ERR_TOO_BIG
;
1147 return true; // done parsing, got reply, and no error
1150 // parsed headers but got no reply
1151 error
= ERR_INVALID_RESP
;
1155 error
= readBuf
->hasContent() ?
1156 ERR_INVALID_RESP
: ERR_ZERO_SIZE_OBJECT
;
1159 assert(error
!= ERR_NONE
);
1161 fwd
->fail(errorCon(error
, HTTP_BAD_GATEWAY
, fwd
->request
));
1162 flags
.do_next_read
= 0;
1164 return false; // quit on error
1167 /** truncate what we read if we read too much so that writeReplyBody()
1168 writes no more than what we should have read */
1170 HttpStateData::truncateVirginBody()
1172 assert(flags
.headers_parsed
);
1174 HttpReply
*vrep
= virginReply();
1176 if (!vrep
->expectingBody(request
->method
, clen
) || clen
< 0)
1177 return; // no body or a body of unknown size, including chunked
1179 const int64_t body_bytes_read
= reply_bytes_read
- header_bytes_read
;
1180 if (body_bytes_read
- body_bytes_truncated
<= clen
)
1181 return; // we did not read too much or already took care of the extras
1183 if (const int64_t extras
= body_bytes_read
- body_bytes_truncated
- clen
) {
1184 // server sent more that the advertised content length
1185 debugs(11,5, HERE
<< "body_bytes_read=" << body_bytes_read
<<
1186 " clen=" << clen
<< '/' << vrep
->content_length
<<
1187 " body_bytes_truncated=" << body_bytes_truncated
<< '+' << extras
);
1189 readBuf
->truncate(extras
);
1190 body_bytes_truncated
+= extras
;
1195 * Call this when there is data from the origin server
1196 * which should be sent to either StoreEntry, or to ICAP...
1199 HttpStateData::writeReplyBody()
1201 truncateVirginBody(); // if needed
1202 const char *data
= readBuf
->content();
1203 int len
= readBuf
->contentSize();
1204 addVirginReplyBody(data
, len
);
1205 readBuf
->consume(len
);
1209 HttpStateData::decodeAndWriteReplyBody()
1211 const char *data
= NULL
;
1213 bool status
= false;
1214 assert(flags
.chunked
);
1215 assert(httpChunkDecoder
);
1216 SQUID_ENTER_THROWING_CODE();
1219 const bool done
= httpChunkDecoder
->parse(readBuf
,&decodedData
);
1220 len
= decodedData
.contentSize();
1221 data
=decodedData
.content();
1222 addVirginReplyBody(data
, len
);
1225 flags
.do_next_read
= 0;
1227 SQUID_EXIT_THROWING_CODE(status
);
1232 * processReplyBody has two purposes:
1233 * 1 - take the reply body data, if any, and put it into either
1234 * the StoreEntry, or give it over to ICAP.
1235 * 2 - see if we made it to the end of the response (persistent
1236 * connections and such)
1239 HttpStateData::processReplyBody()
1241 AsyncCall::Pointer call
;
1242 IpAddress client_addr
;
1243 bool ispinned
= false;
1245 if (!flags
.headers_parsed
) {
1246 flags
.do_next_read
= 1;
1247 maybeReadVirginBody();
1252 if (adaptationAccessCheckPending
)
1258 * At this point the reply headers have been parsed and consumed.
1259 * That means header content has been removed from readBuf and
1260 * it contains only body data.
1262 if (flags
.chunked
) {
1263 if (!decodeAndWriteReplyBody()) {
1264 flags
.do_next_read
= 0;
1271 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1273 * The above writeReplyBody() call could ABORT this entry,
1274 * in that case, the server FD should already be closed.
1275 * there's nothing for us to do.
1279 switch (persistentConnStatus()) {
1280 case INCOMPLETE_MSG
:
1281 debugs(11, 5, "processReplyBody: INCOMPLETE_MSG");
1282 /* Wait for more data or EOF condition */
1283 if (flags
.keepalive_broken
) {
1285 commSetTimeout(fd
, 10, call
);
1288 commSetTimeout(fd
, Config
.Timeout
.read
, call
);
1291 flags
.do_next_read
= 1;
1294 case COMPLETE_PERSISTENT_MSG
:
1295 debugs(11, 5, "processReplyBody: COMPLETE_PERSISTENT_MSG");
1296 /* yes we have to clear all these! */
1298 commSetTimeout(fd
, -1, call
);
1299 flags
.do_next_read
= 0;
1301 comm_remove_close_handler(fd
, closeHandler
);
1302 closeHandler
= NULL
;
1303 fwd
->unregister(fd
);
1305 if (orig_request
->flags
.spoof_client_ip
)
1306 client_addr
= orig_request
->client_addr
;
1309 if (request
->flags
.pinned
) {
1311 } else if (request
->flags
.connection_auth
&& request
->flags
.auth_sent
) {
1315 if (orig_request
->pinnedConnection() && ispinned
) {
1316 orig_request
->pinnedConnection()->pinConnection(fd
, orig_request
, _peer
,
1317 (request
->flags
.connection_auth
!= 0));
1319 fwd
->pconnPush(fd
, _peer
, request
, orig_request
->GetHost(), client_addr
);
1327 case COMPLETE_NONPERSISTENT_MSG
:
1328 debugs(11, 5, "processReplyBody: COMPLETE_NONPERSISTENT_MSG");
1333 maybeReadVirginBody();
1337 HttpStateData::maybeReadVirginBody()
1339 int read_sz
= replyBodySpace(readBuf
->spaceSize());
1341 debugs(11,9, HERE
<< (flags
.do_next_read
? "may" : "wont") <<
1342 " read up to " << read_sz
<< " bytes from FD " << fd
);
1345 * why <2? Because delayAwareRead() won't actually read if
1346 * you ask it to read 1 byte. The delayed read request
1347 * just gets re-queued until the client side drains, then
1348 * the I/O thread hangs. Better to not register any read
1349 * handler until we get a notification from someone that
1350 * its okay to read again.
1353 if (flags
.headers_parsed
)
1359 if (flags
.do_next_read
) {
1360 flags
.do_next_read
= 0;
1361 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
1362 entry
->delayAwareRead(fd
, readBuf
->space(read_sz
), read_sz
,
1363 asyncCall(11, 5, "HttpStateData::readReply",
1364 Dialer(this, &HttpStateData::readReply
)));
1369 * This will be called when request write is complete.
1372 HttpStateData::sendComplete(const CommIoCbParams
&io
)
1374 debugs(11, 5, "httpSendComplete: FD " << fd
<< ": size " << io
.size
<< ": errflag " << io
.flag
<< ".");
1375 #if URL_CHECKSUM_DEBUG
1377 entry
->mem_obj
->checkUrlChecksum();
1381 fd_bytes(fd
, io
.size
, FD_WRITE
);
1382 kb_incr(&statCounter
.server
.all
.kbytes_out
, io
.size
);
1383 kb_incr(&statCounter
.server
.http
.kbytes_out
, io
.size
);
1386 if (io
.flag
== COMM_ERR_CLOSING
)
1391 err
= errorCon(ERR_WRITE_ERROR
, HTTP_BAD_GATEWAY
, fwd
->request
);
1392 err
->xerrno
= io
.xerrno
;
1399 * Set the read timeout here because it hasn't been set yet.
1400 * We only set the read timeout after the request has been
1401 * fully written to the server-side. If we start the timeout
1402 * after connection establishment, then we are likely to hit
1403 * the timeout for POST/PUT requests that have very large
1406 typedef CommCbMemFunT
<HttpStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1407 AsyncCall::Pointer timeoutCall
= asyncCall(11, 5, "HttpStateData::httpTimeout",
1408 TimeoutDialer(this,&HttpStateData::httpTimeout
));
1410 commSetTimeout(fd
, Config
.Timeout
.read
, timeoutCall
);
1412 flags
.request_sent
= 1;
1415 // Close the HTTP server connection. Used by serverComplete().
1417 HttpStateData::closeServer()
1419 debugs(11,5, HERE
<< "closing HTTP server FD " << fd
<< " this " << this);
1422 fwd
->unregister(fd
);
1423 comm_remove_close_handler(fd
, closeHandler
);
1424 closeHandler
= NULL
;
1431 HttpStateData::doneWithServer() const
1437 * build request headers and append them to a given MemBuf
1438 * used by buildRequestPrefix()
1439 * note: initialised the HttpHeader, the caller is responsible for Clean()-ing
1442 HttpStateData::httpBuildRequestHeader(HttpRequest
* request
,
1443 HttpRequest
* orig_request
,
1445 HttpHeader
* hdr_out
,
1446 http_state_flags flags
)
1448 /* building buffer for complex strings */
1449 #define BBUF_SZ (MAX_URL+32)
1450 LOCAL_ARRAY(char, bbuf
, BBUF_SZ
);
1451 LOCAL_ARRAY(char, ntoabuf
, MAX_IPSTRLEN
);
1452 const HttpHeader
*hdr_in
= &orig_request
->header
;
1453 const HttpHeaderEntry
*e
= NULL
;
1455 HttpHeaderPos pos
= HttpHeaderInitPos
;
1456 assert (hdr_out
->owner
== hoRequest
);
1458 /* append our IMS header */
1459 if (request
->lastmod
> -1)
1460 hdr_out
->putTime(HDR_IF_MODIFIED_SINCE
, request
->lastmod
);
1462 bool we_do_ranges
= decideIfWeDoRanges (orig_request
);
1464 String
strConnection (hdr_in
->getList(HDR_CONNECTION
));
1466 while ((e
= hdr_in
->getEntry(&pos
)))
1467 copyOneHeaderFromClientsideRequestToUpstreamRequest(e
, strConnection
, request
, orig_request
, hdr_out
, we_do_ranges
, flags
);
1469 /* Abstraction break: We should interpret multipart/byterange responses
1470 * into offset-length data, and this works around our inability to do so.
1472 if (!we_do_ranges
&& orig_request
->multipartRangeRequest()) {
1473 /* don't cache the result */
1474 orig_request
->flags
.cachable
= 0;
1475 /* pretend it's not a range request */
1476 delete orig_request
->range
;
1477 orig_request
->range
= NULL
;
1478 orig_request
->flags
.range
= 0;
1482 if (Config
.onoff
.via
) {
1484 strVia
= hdr_in
->getList(HDR_VIA
);
1485 snprintf(bbuf
, BBUF_SZ
, "%d.%d %s",
1486 orig_request
->http_ver
.major
,
1487 orig_request
->http_ver
.minor
, ThisCache
);
1488 strListAdd(&strVia
, bbuf
, ',');
1489 hdr_out
->putStr(HDR_VIA
, strVia
.termedBuf());
1495 /* Append Surrogate-Capabilities */
1496 String
strSurrogate (hdr_in
->getList(HDR_SURROGATE_CAPABILITY
));
1497 snprintf(bbuf
, BBUF_SZ
, "%s=\"Surrogate/1.0 ESI/1.0\"",
1498 Config
.Accel
.surrogate_id
);
1499 strListAdd(&strSurrogate
, bbuf
, ',');
1500 hdr_out
->putStr(HDR_SURROGATE_CAPABILITY
, strSurrogate
.termedBuf());
1504 strFwd
= hdr_in
->getList(HDR_X_FORWARDED_FOR
);
1506 /** \pre Handle X-Forwarded-For */
1507 if (strcmp(opt_forwarded_for
, "delete") != 0) {
1508 if (strcmp(opt_forwarded_for
, "on") == 0) {
1509 /** If set to ON - append client IP or 'unknown'. */
1510 strFwd
= hdr_in
->getList(HDR_X_FORWARDED_FOR
);
1511 if ( orig_request
->client_addr
.IsNoAddr() )
1512 strListAdd(&strFwd
, "unknown", ',');
1514 strListAdd(&strFwd
, orig_request
->client_addr
.NtoA(ntoabuf
, MAX_IPSTRLEN
), ',');
1515 } else if (strcmp(opt_forwarded_for
, "off") == 0) {
1516 /** If set to OFF - append 'unknown'. */
1517 strFwd
= hdr_in
->getList(HDR_X_FORWARDED_FOR
);
1518 strListAdd(&strFwd
, "unknown", ',');
1519 } else if (strcmp(opt_forwarded_for
, "transparent") == 0) {
1520 /** If set to TRANSPARENT - pass through unchanged. */
1521 strFwd
= hdr_in
->getList(HDR_X_FORWARDED_FOR
);
1522 } else if (strcmp(opt_forwarded_for
, "truncate") == 0) {
1523 /** If set to TRUNCATE - drop existing list and replace with client IP or 'unknown'. */
1524 if ( orig_request
->client_addr
.IsNoAddr() )
1527 strFwd
= orig_request
->client_addr
.NtoA(ntoabuf
, MAX_IPSTRLEN
);
1529 if (strFwd
.size() > 0)
1530 hdr_out
->putStr(HDR_X_FORWARDED_FOR
, strFwd
.termedBuf());
1532 /** If set to DELETE - do not copy through. */
1535 /* append Host if not there already */
1536 if (!hdr_out
->has(HDR_HOST
)) {
1537 if (orig_request
->peer_domain
) {
1538 hdr_out
->putStr(HDR_HOST
, orig_request
->peer_domain
);
1539 } else if (orig_request
->port
== urlDefaultPort(orig_request
->protocol
)) {
1540 /* use port# only if not default */
1541 hdr_out
->putStr(HDR_HOST
, orig_request
->GetHost());
1543 httpHeaderPutStrf(hdr_out
, HDR_HOST
, "%s:%d",
1544 orig_request
->GetHost(),
1545 (int) orig_request
->port
);
1549 /* append Authorization if known in URL, not in header and going direct */
1550 if (!hdr_out
->has(HDR_AUTHORIZATION
)) {
1551 if (!request
->flags
.proxying
&& *request
->login
) {
1552 httpHeaderPutStrf(hdr_out
, HDR_AUTHORIZATION
, "Basic %s",
1553 base64_encode(request
->login
));
1557 /* append Proxy-Authorization if configured for peer, and proxying */
1558 if (request
->flags
.proxying
&& orig_request
->peer_login
&&
1559 !hdr_out
->has(HDR_PROXY_AUTHORIZATION
)) {
1560 if (*orig_request
->peer_login
== '*') {
1561 /* Special mode, to pass the username to the upstream cache */
1563 const char *username
= "-";
1565 if (orig_request
->extacl_user
.size())
1566 username
= orig_request
->extacl_user
.termedBuf();
1567 else if (orig_request
->auth_user_request
)
1568 username
= orig_request
->auth_user_request
->username();
1570 snprintf(loginbuf
, sizeof(loginbuf
), "%s%s", username
, orig_request
->peer_login
+ 1);
1572 httpHeaderPutStrf(hdr_out
, HDR_PROXY_AUTHORIZATION
, "Basic %s",
1573 base64_encode(loginbuf
));
1574 } else if (strcmp(orig_request
->peer_login
, "PASS") == 0) {
1575 if (orig_request
->extacl_user
.size() && orig_request
->extacl_passwd
.size()) {
1577 snprintf(loginbuf
, sizeof(loginbuf
), SQUIDSTRINGPH
":" SQUIDSTRINGPH
,
1578 SQUIDSTRINGPRINT(orig_request
->extacl_user
),
1579 SQUIDSTRINGPRINT(orig_request
->extacl_passwd
));
1580 httpHeaderPutStrf(hdr_out
, HDR_PROXY_AUTHORIZATION
, "Basic %s",
1581 base64_encode(loginbuf
));
1583 } else if (strcmp(orig_request
->peer_login
, "PROXYPASS") == 0) {
1586 httpHeaderPutStrf(hdr_out
, HDR_PROXY_AUTHORIZATION
, "Basic %s",
1587 base64_encode(orig_request
->peer_login
));
1591 /* append WWW-Authorization if configured for peer */
1592 if (flags
.originpeer
&& orig_request
->peer_login
&&
1593 !hdr_out
->has(HDR_AUTHORIZATION
)) {
1594 if (strcmp(orig_request
->peer_login
, "PASS") == 0) {
1595 /* No credentials to forward.. (should have been done above if available) */
1596 } else if (strcmp(orig_request
->peer_login
, "PROXYPASS") == 0) {
1597 /* Special mode, convert proxy authentication to WWW authentication
1598 * (also applies to authentication provided by external acl)
1600 const char *auth
= hdr_in
->getStr(HDR_PROXY_AUTHORIZATION
);
1602 if (auth
&& strncasecmp(auth
, "basic ", 6) == 0) {
1603 hdr_out
->putStr(HDR_AUTHORIZATION
, auth
);
1604 } else if (orig_request
->extacl_user
.size() && orig_request
->extacl_passwd
.size()) {
1606 snprintf(loginbuf
, sizeof(loginbuf
), SQUIDSTRINGPH
":" SQUIDSTRINGPH
,
1607 SQUIDSTRINGPRINT(orig_request
->extacl_user
),
1608 SQUIDSTRINGPRINT(orig_request
->extacl_passwd
));
1609 httpHeaderPutStrf(hdr_out
, HDR_AUTHORIZATION
, "Basic %s",
1610 base64_encode(loginbuf
));
1612 } else if (*orig_request
->peer_login
== '*') {
1613 /* Special mode, to pass the username to the upstream cache */
1615 const char *username
= "-";
1617 if (orig_request
->auth_user_request
)
1618 username
= orig_request
->auth_user_request
->username();
1619 else if (orig_request
->extacl_user
.size())
1620 username
= orig_request
->extacl_user
.termedBuf();
1622 snprintf(loginbuf
, sizeof(loginbuf
), "%s%s", username
, orig_request
->peer_login
+ 1);
1624 httpHeaderPutStrf(hdr_out
, HDR_AUTHORIZATION
, "Basic %s",
1625 base64_encode(loginbuf
));
1627 /* Fixed login string */
1628 httpHeaderPutStrf(hdr_out
, HDR_AUTHORIZATION
, "Basic %s",
1629 base64_encode(orig_request
->peer_login
));
1633 /* append Cache-Control, add max-age if not there already */ {
1634 HttpHdrCc
*cc
= hdr_in
->getCc();
1637 cc
= httpHdrCcCreate();
1639 #if 0 /* see bug 2330 */
1640 /* Set no-cache if determined needed but not found */
1641 if (orig_request
->flags
.nocache
)
1642 EBIT_SET(cc
->mask
, CC_NO_CACHE
);
1645 /* Add max-age only without no-cache */
1646 if (!EBIT_TEST(cc
->mask
, CC_MAX_AGE
) && !EBIT_TEST(cc
->mask
, CC_NO_CACHE
)) {
1648 entry
? entry
->url() : urlCanonical(orig_request
);
1649 httpHdrCcSetMaxAge(cc
, getMaxAge(url
));
1651 if (request
->urlpath
.size())
1652 assert(strstr(url
, request
->urlpath
.termedBuf()));
1655 /* Enforce sibling relations */
1656 if (flags
.only_if_cached
)
1657 EBIT_SET(cc
->mask
, CC_ONLY_IF_CACHED
);
1661 httpHdrCcDestroy(cc
);
1664 /* maybe append Connection: keep-alive */
1665 if (flags
.keepalive
) {
1666 if (flags
.proxying
) {
1667 hdr_out
->putStr(HDR_PROXY_CONNECTION
, "keep-alive");
1669 hdr_out
->putStr(HDR_CONNECTION
, "keep-alive");
1673 /* append Front-End-Https */
1674 if (flags
.front_end_https
) {
1675 if (flags
.front_end_https
== 1 || request
->protocol
== PROTO_HTTPS
)
1676 hdr_out
->putStr(HDR_FRONT_END_HTTPS
, "On");
1679 /* Now mangle the headers. */
1680 if (Config2
.onoff
.mangle_request_headers
)
1681 httpHdrMangleList(hdr_out
, request
, ROR_REQUEST
);
1683 strConnection
.clean();
1687 * Decides whether a particular header may be cloned from the received Clients request
1688 * to our outgoing fetch request.
1691 copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry
*e
, const String strConnection
, HttpRequest
* request
, const HttpRequest
* orig_request
, HttpHeader
* hdr_out
, const int we_do_ranges
, const http_state_flags flags
)
1693 debugs(11, 5, "httpBuildRequestHeader: " << e
->name
<< ": " << e
->value
);
1697 /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid should not pass on. */
1699 case HDR_PROXY_AUTHORIZATION
:
1700 /** \par Proxy-Authorization:
1701 * Only pass on proxy authentication to peers for which
1702 * authentication forwarding is explicitly enabled
1705 if (flags
.proxying
&& orig_request
->peer_login
&&
1706 (strcmp(orig_request
->peer_login
, "PASS") == 0 ||
1707 strcmp(orig_request
->peer_login
, "PROXYPASS") == 0)) {
1708 hdr_out
->addEntry(e
->clone());
1713 /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid does not pass on. */
1715 case HDR_CONNECTION
: /** \par Connection: */
1716 case HDR_TE
: /** \par TE: */
1717 case HDR_KEEP_ALIVE
: /** \par Keep-Alive: */
1718 case HDR_PROXY_AUTHENTICATE
: /** \par Proxy-Authenticate: */
1719 case HDR_TRAILERS
: /** \par Trailers: */
1720 case HDR_UPGRADE
: /** \par Upgrade: */
1721 case HDR_TRANSFER_ENCODING
: /** \par Transfer-Encoding: */
1725 /** \par OTHER headers I haven't bothered to track down yet. */
1727 case HDR_AUTHORIZATION
:
1728 /** \par WWW-Authorization:
1729 * Pass on WWW authentication */
1731 if (!flags
.originpeer
) {
1732 hdr_out
->addEntry(e
->clone());
1734 /** \note In accelerators, only forward authentication if enabled
1735 * by login=PASS or login=PROXYPASS
1736 * (see also below for proxy->server authentication)
1738 if (orig_request
->peer_login
&&
1739 (strcmp(orig_request
->peer_login
, "PASS") == 0 ||
1740 strcmp(orig_request
->peer_login
, "PROXYPASS") == 0)) {
1741 hdr_out
->addEntry(e
->clone());
1749 * Normally Squid rewrites the Host: header.
1750 * However, there is one case when we don't: If the URL
1751 * went through our redirector and the admin configured
1752 * 'redir_rewrites_host' to be off.
1754 if (orig_request
->peer_domain
)
1755 hdr_out
->putStr(HDR_HOST
, orig_request
->peer_domain
);
1756 else if (request
->flags
.redirected
&& !Config
.onoff
.redir_rewrites_host
)
1757 hdr_out
->addEntry(e
->clone());
1759 /* use port# only if not default */
1761 if (orig_request
->port
== urlDefaultPort(orig_request
->protocol
)) {
1762 hdr_out
->putStr(HDR_HOST
, orig_request
->GetHost());
1764 httpHeaderPutStrf(hdr_out
, HDR_HOST
, "%s:%d",
1765 orig_request
->GetHost(),
1766 (int) orig_request
->port
);
1772 case HDR_IF_MODIFIED_SINCE
:
1773 /** \par If-Modified-Since:
1774 * append unless we added our own;
1775 * \note at most one client's ims header can pass through */
1777 if (!hdr_out
->has(HDR_IF_MODIFIED_SINCE
))
1778 hdr_out
->addEntry(e
->clone());
1782 case HDR_MAX_FORWARDS
:
1783 /** \par Max-Forwards:
1784 * pass only on TRACE or OPTIONS requests */
1785 if (orig_request
->method
== METHOD_TRACE
|| orig_request
->method
== METHOD_OPTIONS
) {
1786 const int64_t hops
= e
->getInt64();
1789 hdr_out
->putInt64(HDR_MAX_FORWARDS
, hops
- 1);
1796 * If Via is disabled then forward any received header as-is.
1797 * Otherwise leave for explicit updated addition later. */
1799 if (!Config
.onoff
.via
)
1800 hdr_out
->addEntry(e
->clone());
1808 case HDR_REQUEST_RANGE
:
1809 /** \par Range:, If-Range:, Request-Range:
1810 * Only pass if we accept ranges */
1812 hdr_out
->addEntry(e
->clone());
1816 case HDR_PROXY_CONNECTION
:
1818 case HDR_X_FORWARDED_FOR
:
1820 case HDR_CACHE_CONTROL
:
1821 /** \par Proxy-Connaction:, X-Forwarded-For:, Cache-Control:
1822 * handled specially by Squid, so leave off for now.
1823 * append these after the loop if needed */
1826 case HDR_FRONT_END_HTTPS
:
1827 /** \par Front-End-Https:
1828 * Pass thru only if peer is configured with front-end-https */
1829 if (!flags
.front_end_https
)
1830 hdr_out
->addEntry(e
->clone());
1836 * pass on all other header fields
1837 * which are NOT listed by the special Connection: header. */
1839 if (strConnection
.size()>0 && strListIsMember(&strConnection
, e
->name
.termedBuf(), ',')) {
1840 debugs(11, 2, "'" << e
->name
<< "' header cropped by Connection: definition");
1844 hdr_out
->addEntry(e
->clone());
1849 HttpStateData::decideIfWeDoRanges (HttpRequest
* orig_request
)
1852 /* decide if we want to do Ranges ourselves
1853 * and fetch the whole object now)
1854 * We want to handle Ranges ourselves iff
1855 * - we can actually parse client Range specs
1856 * - the specs are expected to be simple enough (e.g. no out-of-order ranges)
1857 * - reply will be cachable
1858 * (If the reply will be uncachable we have to throw it away after
1859 * serving this request, so it is better to forward ranges to
1860 * the server and fetch only the requested content)
1863 if (NULL
== orig_request
->range
|| !orig_request
->flags
.cachable
1864 || orig_request
->range
->offsetLimitExceeded() || orig_request
->flags
.connection_auth
)
1867 debugs(11, 8, "decideIfWeDoRanges: range specs: " <<
1868 orig_request
->range
<< ", cachable: " <<
1869 orig_request
->flags
.cachable
<< "; we_do_ranges: " << result
);
1874 /* build request prefix and append it to a given MemBuf;
1875 * return the length of the prefix */
1877 HttpStateData::buildRequestPrefix(HttpRequest
* request
,
1878 HttpRequest
* orig_request
,
1881 http_state_flags flags
)
1883 const int offset
= mb
->size
;
1884 HttpVersion
httpver(1, 0);
1885 mb
->Printf("%s %s HTTP/%d.%d\r\n",
1886 RequestMethodStr(request
->method
),
1887 request
->urlpath
.size() ? request
->urlpath
.termedBuf() : "/",
1888 httpver
.major
,httpver
.minor
);
1889 /* build and pack headers */
1891 HttpHeader
hdr(hoRequest
);
1893 httpBuildRequestHeader(request
, orig_request
, entry
, &hdr
, flags
);
1895 if (request
->flags
.pinned
&& request
->flags
.connection_auth
)
1896 request
->flags
.auth_sent
= 1;
1897 else if (hdr
.has(HDR_AUTHORIZATION
))
1898 request
->flags
.auth_sent
= 1;
1900 packerToMemInit(&p
, mb
);
1905 /* append header terminator */
1906 mb
->append(crlf
, 2);
1907 return mb
->size
- offset
;
1910 /* This will be called when connect completes. Write request. */
1912 HttpStateData::sendRequest()
1916 debugs(11, 5, "httpSendRequest: FD " << fd
<< ", request " << request
<< ", this " << this << ".");
1917 typedef CommCbMemFunT
<HttpStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1918 AsyncCall::Pointer timeoutCall
= asyncCall(11, 5, "HttpStateData::httpTimeout",
1919 TimeoutDialer(this,&HttpStateData::httpTimeout
));
1920 commSetTimeout(fd
, Config
.Timeout
.lifetime
, timeoutCall
);
1921 flags
.do_next_read
= 1;
1922 maybeReadVirginBody();
1924 if (orig_request
->body_pipe
!= NULL
) {
1925 if (!startRequestBodyFlow()) // register to receive body data
1927 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
1928 Dialer
dialer(this, &HttpStateData::sentRequestBody
);
1929 requestSender
= asyncCall(11,5, "HttpStateData::sentRequestBody", dialer
);
1931 assert(!requestBodySource
);
1932 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
1933 Dialer
dialer(this, &HttpStateData::sendComplete
);
1934 requestSender
= asyncCall(11,5, "HttpStateData::SendComplete", dialer
);
1937 if (_peer
!= NULL
) {
1938 if (_peer
->options
.originserver
) {
1940 flags
.originpeer
= 1;
1943 flags
.originpeer
= 0;
1947 flags
.originpeer
= 0;
1951 * Is keep-alive okay for all request methods?
1953 if (orig_request
->flags
.must_keepalive
)
1954 flags
.keepalive
= 1;
1955 else if (!Config
.onoff
.server_pconns
)
1956 flags
.keepalive
= 0;
1957 else if (_peer
== NULL
)
1958 flags
.keepalive
= 1;
1959 else if (_peer
->stats
.n_keepalives_sent
< 10)
1960 flags
.keepalive
= 1;
1961 else if ((double) _peer
->stats
.n_keepalives_recv
/
1962 (double) _peer
->stats
.n_keepalives_sent
> 0.50)
1963 flags
.keepalive
= 1;
1966 if (neighborType(_peer
, request
) == PEER_SIBLING
&&
1967 !_peer
->options
.allow_miss
)
1968 flags
.only_if_cached
= 1;
1970 flags
.front_end_https
= _peer
->front_end_https
;
1974 buildRequestPrefix(request
, orig_request
, entry
, &mb
, flags
);
1975 debugs(11, 6, "httpSendRequest: FD " << fd
<< ":\n" << mb
.buf
);
1976 comm_write_mbuf(fd
, &mb
, requestSender
);
1982 httpStart(FwdState
*fwd
)
1984 debugs(11, 3, "httpStart: \"" << RequestMethodStr(fwd
->request
->method
) << " " << fwd
->entry
->url() << "\"" );
1985 HttpStateData
*httpState
= new HttpStateData(fwd
);
1987 if (!httpState
->sendRequest()) {
1988 debugs(11, 3, "httpStart: aborted");
1993 statCounter
.server
.all
.requests
++;
1994 statCounter
.server
.http
.requests
++;
1997 * We used to set the read timeout here, but not any more.
1998 * Now its set in httpSendComplete() after the full request,
1999 * including request body, has been written to the server.
2004 HttpStateData::doneSendingRequestBody()
2006 debugs(11,5, HERE
<< "doneSendingRequestBody: FD " << fd
);
2009 if (Config
.accessList
.brokenPosts
) {
2010 ACLFilledChecklist
ch(Config
.accessList
.brokenPosts
, request
, NULL
);
2011 if (!ch
.fastCheck()) {
2012 debugs(11, 5, "doneSendingRequestBody: didn't match brokenPosts");
2013 CommIoCbParams
io(NULL
);
2018 debugs(11, 2, "doneSendingRequestBody: matched brokenPosts");
2019 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
2020 Dialer
dialer(this, &HttpStateData::sendComplete
);
2021 AsyncCall::Pointer call
= asyncCall(11,5, "HttpStateData::SendComplete", dialer
);
2022 comm_write(fd
, "\r\n", 2, call
);
2026 debugs(11, 5, "doneSendingRequestBody: No brokenPosts list");
2027 #endif /* HTTP_VIOLATIONS */
2029 CommIoCbParams
io(NULL
);
2035 // more origin request body data is available
2037 HttpStateData::handleMoreRequestBodyAvailable()
2039 if (eof
|| fd
< 0) {
2040 // XXX: we should check this condition in other callbacks then!
2041 // TODO: Check whether this can actually happen: We should unsubscribe
2042 // as a body consumer when the above condition(s) are detected.
2043 debugs(11, 1, HERE
<< "Transaction aborted while reading HTTP body");
2047 assert(requestBodySource
!= NULL
);
2049 if (requestBodySource
->buf().hasContent()) {
2050 // XXX: why does not this trigger a debug message on every request?
2052 if (flags
.headers_parsed
&& !flags
.abuse_detected
) {
2053 flags
.abuse_detected
= 1;
2054 debugs(11, 1, "http handleMoreRequestBodyAvailable: Likely proxy abuse detected '" << orig_request
->client_addr
<< "' -> '" << entry
->url() << "'" );
2056 if (virginReply()->sline
.status
== HTTP_INVALID_HEADER
) {
2063 HttpStateData::handleMoreRequestBodyAvailable();
2066 // premature end of the request body
2068 HttpStateData::handleRequestBodyProducerAborted()
2070 ServerStateData::handleRequestBodyProducerAborted();
2071 // XXX: SendComplete(COMM_ERR_CLOSING) does little. Is it enough?
2072 CommIoCbParams
io(NULL
);
2074 io
.flag
=COMM_ERR_CLOSING
;
2078 // called when we wrote request headers(!) or a part of the body
2080 HttpStateData::sentRequestBody(const CommIoCbParams
&io
)
2083 kb_incr(&statCounter
.server
.http
.kbytes_out
, io
.size
);
2085 ServerStateData::sentRequestBody(io
);
2088 // Quickly abort the transaction
2089 // TODO: destruction should be sufficient as the destructor should cleanup,
2090 // including canceling close handlers
2092 HttpStateData::abortTransaction(const char *reason
)
2094 debugs(11,5, HERE
<< "aborting transaction for " << reason
<<
2095 "; FD " << fd
<< ", this " << this);
2102 fwd
->handleUnregisteredServerEnd();
2103 deleteThis("HttpStateData::abortTransaction");
2108 httpBuildVersion(HttpVersion
* version
, unsigned int major
, unsigned int minor
)
2110 version
->major
= major
;
2111 version
->minor
= minor
;
2116 HttpStateData::originalRequest()
2118 return orig_request
;