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
);
90 // reset peer response time stats for %<pt
91 orig_request
->hier
.peer_http_request_sent
.tv_sec
= 0;
92 orig_request
->hier
.peer_http_request_sent
.tv_usec
= 0;
95 _peer
= fwd
->servers
->_peer
; /* might be NULL */
100 if (_peer
->options
.originserver
)
101 url
= orig_request
->urlpath
.termedBuf();
105 HttpRequest
* proxy_req
= new HttpRequest(orig_request
->method
,
106 orig_request
->protocol
, url
);
108 proxy_req
->SetHost(_peer
->host
);
110 proxy_req
->port
= _peer
->http_port
;
112 proxy_req
->flags
= orig_request
->flags
;
114 proxy_req
->lastmod
= orig_request
->lastmod
;
116 proxy_req
->flags
.proxying
= 1;
118 HTTPMSGUNLOCK(request
);
120 request
= HTTPMSGLOCK(proxy_req
);
123 * This NEIGHBOR_PROXY_ONLY check probably shouldn't be here.
124 * We might end up getting the object from somewhere else if,
125 * for example, the request to this neighbor fails.
127 if (_peer
->options
.proxy_only
)
128 entry
->releaseRequest();
132 entry
->setNoDelay(_peer
->options
.no_delay
);
138 * register the handler to free HTTP state data when the FD closes
140 typedef CommCbMemFunT
<HttpStateData
, CommCloseCbParams
> Dialer
;
141 closeHandler
= asyncCall(9, 5, "httpStateData::httpStateConnClosed",
142 Dialer(this,&HttpStateData::httpStateConnClosed
));
143 comm_add_close_handler(fd
, closeHandler
);
146 HttpStateData::~HttpStateData()
149 * don't forget that ~ServerStateData() gets called automatically
152 if (!readBuf
->isNull())
157 if (httpChunkDecoder
)
158 delete httpChunkDecoder
;
160 HTTPMSGUNLOCK(orig_request
);
162 debugs(11,5, HERE
<< "HttpStateData " << this << " destroyed; FD " << fd
);
166 HttpStateData::dataDescriptor() const
172 httpStateFree(int fd, void *data)
174 HttpStateData *httpState = static_cast<HttpStateData *>(data);
175 debugs(11, 5, "httpStateFree: FD " << fd << ", httpState=" << data);
180 HttpStateData::httpStateConnClosed(const CommCloseCbParams
¶ms
)
182 debugs(11, 5, "httpStateFree: FD " << params
.fd
<< ", httpState=" << params
.data
);
183 deleteThis("HttpStateData::httpStateConnClosed");
187 httpCachable(const HttpRequestMethod
& method
)
189 /* GET and HEAD are cachable. Others are not. */
191 // TODO: replase to HttpRequestMethod::isCachable() ?
192 if (method
!= METHOD_GET
&& method
!= METHOD_HEAD
)
200 HttpStateData::httpTimeout(const CommTimeoutCbParams
¶ms
)
202 debugs(11, 4, "httpTimeout: FD " << fd
<< ": '" << entry
->url() << "'" );
204 if (entry
->store_status
== STORE_PENDING
) {
205 fwd
->fail(errorCon(ERR_READ_TIMEOUT
, HTTP_GATEWAY_TIMEOUT
, fwd
->request
));
212 httpMaybeRemovePublic(StoreEntry
* e
, http_status status
)
218 if (!EBIT_TEST(e
->flags
, KEY_PRIVATE
))
225 case HTTP_NON_AUTHORITATIVE_INFORMATION
:
227 case HTTP_MULTIPLE_CHOICES
:
229 case HTTP_MOVED_PERMANENTLY
:
231 case HTTP_MOVED_TEMPORARILY
:
242 case HTTP_METHOD_NOT_ALLOWED
:
249 case HTTP_UNAUTHORIZED
:
259 * Any 2xx response should eject previously cached entities...
262 if (status
>= 200 && status
< 300)
270 if (!remove
&& !forbidden
)
275 if (e
->mem_obj
->request
)
276 pe
= storeGetPublicByRequest(e
->mem_obj
->request
);
278 pe
= storeGetPublic(e
->mem_obj
->url
, e
->mem_obj
->method
);
283 neighborsHtcpClear(e
, NULL
, e
->mem_obj
->request
, e
->mem_obj
->method
, HTCP_CLR_INVALIDATION
);
289 * Also remove any cached HEAD response in case the object has
292 if (e
->mem_obj
->request
)
293 pe
= storeGetPublicByRequestMethod(e
->mem_obj
->request
, METHOD_HEAD
);
295 pe
= storeGetPublic(e
->mem_obj
->url
, METHOD_HEAD
);
300 neighborsHtcpClear(e
, NULL
, e
->mem_obj
->request
, HttpRequestMethod(METHOD_HEAD
), HTCP_CLR_INVALIDATION
);
307 HttpStateData::processSurrogateControl(HttpReply
*reply
)
311 if (request
->flags
.accelerated
&& reply
->surrogate_control
) {
312 HttpHdrScTarget
*sctusable
=
313 httpHdrScGetMergedTarget(reply
->surrogate_control
,
314 Config
.Accel
.surrogate_id
);
317 if (EBIT_TEST(sctusable
->mask
, SC_NO_STORE
) ||
318 (Config
.onoff
.surrogate_is_remote
319 && EBIT_TEST(sctusable
->mask
, SC_NO_STORE_REMOTE
))) {
320 surrogateNoStore
= true;
321 entry
->makePrivate();
324 /* The HttpHeader logic cannot tell if the header it's parsing is a reply to an
325 * accelerated request or not...
326 * Still, this is an abtraction breach. - RC
328 if (sctusable
->max_age
!= -1) {
329 if (sctusable
->max_age
< sctusable
->max_stale
)
330 reply
->expires
= reply
->date
+ sctusable
->max_age
;
332 reply
->expires
= reply
->date
+ sctusable
->max_stale
;
334 /* And update the timestamps */
335 entry
->timestampsSet();
338 /* We ignore cache-control directives as per the Surrogate specification */
339 ignoreCacheControl
= true;
341 httpHdrScTargetDestroy(sctusable
);
349 HttpStateData::cacheableReply()
351 HttpReply
const *rep
= finalReply();
352 HttpHeader
const *hdr
= &rep
->header
;
353 const int cc_mask
= (rep
->cache_control
) ? rep
->cache_control
->mask
: 0;
357 const refresh_t
*R
= NULL
;
359 /* This strange looking define first looks up the refresh pattern
360 * and then checks if the specified flag is set. The main purpose
361 * of this is to simplify the refresh pattern lookup and HTTP_VIOLATIONS
364 #define REFRESH_OVERRIDE(flag) \
365 ((R = (R ? R : refreshLimits(entry->mem_obj->url))) , \
366 (R && R->flags.flag))
368 #define REFRESH_OVERRIDE(flag) 0
371 if (surrogateNoStore
)
374 if (!ignoreCacheControl
) {
375 if (EBIT_TEST(cc_mask
, CC_PRIVATE
)) {
376 if (!REFRESH_OVERRIDE(ignore_private
))
380 if (EBIT_TEST(cc_mask
, CC_NO_CACHE
)) {
381 if (!REFRESH_OVERRIDE(ignore_no_cache
))
385 if (EBIT_TEST(cc_mask
, CC_NO_STORE
)) {
386 if (!REFRESH_OVERRIDE(ignore_no_store
))
391 if (request
->flags
.auth
|| request
->flags
.auth_sent
) {
393 * Responses to requests with authorization may be cached
394 * only if a Cache-Control: public reply header is present.
395 * RFC 2068, sec 14.9.4
398 if (!EBIT_TEST(cc_mask
, CC_PUBLIC
)) {
399 if (!REFRESH_OVERRIDE(ignore_auth
))
404 /* Pragma: no-cache in _replies_ is not documented in HTTP,
405 * but servers like "Active Imaging Webcast/2.0" sure do use it */
406 if (hdr
->has(HDR_PRAGMA
)) {
407 String s
= hdr
->getList(HDR_PRAGMA
);
408 const int no_cache
= strListIsMember(&s
, "no-cache", ',');
412 if (!REFRESH_OVERRIDE(ignore_no_cache
))
418 * The "multipart/x-mixed-replace" content type is used for
419 * continuous push replies. These are generally dynamic and
420 * probably should not be cachable
422 if ((v
= hdr
->getStr(HDR_CONTENT_TYPE
)))
423 if (!strncasecmp(v
, "multipart/x-mixed-replace", 25))
426 switch (rep
->sline
.status
) {
427 /* Responses that are cacheable */
431 case HTTP_NON_AUTHORITATIVE_INFORMATION
:
433 case HTTP_MULTIPLE_CHOICES
:
435 case HTTP_MOVED_PERMANENTLY
:
439 * Don't cache objects that need to be refreshed on next request,
440 * unless we know how to refresh it.
443 if (!refreshIsCachable(entry
)) {
444 debugs(22, 3, "refreshIsCachable() returned non-cacheable..");
448 /* don't cache objects from peers w/o LMT, Date, or Expires */
449 /* check that is it enough to check headers @?@ */
452 else if (rep
->last_modified
> -1)
457 /* @?@ (here and 302): invalid expires header compiles to squid_curtime */
458 else if (rep
->expires
> -1)
466 /* Responses that only are cacheable if the server says so */
468 case HTTP_MOVED_TEMPORARILY
:
469 case HTTP_TEMPORARY_REDIRECT
:
470 if (rep
->expires
> rep
->date
&& rep
->date
> 0)
478 /* Errors can be negatively cached */
480 case HTTP_NO_CONTENT
:
484 case HTTP_BAD_REQUEST
:
490 case HTTP_METHOD_NOT_ALLOWED
:
492 case HTTP_REQUEST_URI_TOO_LARGE
:
494 case HTTP_INTERNAL_SERVER_ERROR
:
496 case HTTP_NOT_IMPLEMENTED
:
498 case HTTP_BAD_GATEWAY
:
500 case HTTP_SERVICE_UNAVAILABLE
:
502 case HTTP_GATEWAY_TIMEOUT
:
508 /* Some responses can never be cached */
510 case HTTP_PARTIAL_CONTENT
: /* Not yet supported */
514 case HTTP_NOT_MODIFIED
:
516 case HTTP_UNAUTHORIZED
:
518 case HTTP_PROXY_AUTHENTICATION_REQUIRED
:
520 case HTTP_INVALID_HEADER
: /* Squid header parsing error */
522 case HTTP_HEADER_TOO_LARGE
:
524 case HTTP_PAYMENT_REQUIRED
:
525 case HTTP_NOT_ACCEPTABLE
:
526 case HTTP_REQUEST_TIMEOUT
:
528 case HTTP_LENGTH_REQUIRED
:
529 case HTTP_PRECONDITION_FAILED
:
530 case HTTP_REQUEST_ENTITY_TOO_LARGE
:
531 case HTTP_UNSUPPORTED_MEDIA_TYPE
:
532 case HTTP_UNPROCESSABLE_ENTITY
:
534 case HTTP_FAILED_DEPENDENCY
:
535 case HTTP_INSUFFICIENT_STORAGE
:
536 case HTTP_REQUESTED_RANGE_NOT_SATISFIABLE
:
537 case HTTP_EXPECTATION_FAILED
:
541 default: /* Unknown status code */
542 debugs (11, 0, HERE
<< "HttpStateData::cacheableReply: unexpected http status code " << rep
->sline
.status
);
554 * For Vary, store the relevant request headers as
555 * virtual headers in the reply
556 * Returns false if the variance cannot be stored
559 httpMakeVaryMark(HttpRequest
* request
, HttpReply
const * reply
)
562 const char *pos
= NULL
;
569 vary
= reply
->header
.getList(HDR_VARY
);
571 while (strListGetItem(&vary
, ',', &item
, &ilen
, &pos
)) {
572 char *name
= (char *)xmalloc(ilen
+ 1);
573 xstrncpy(name
, item
, ilen
+ 1);
576 if (strcmp(name
, "*") == 0) {
577 /* Can not handle "Vary: *" withtout ETag support */
583 strListAdd(&vstr
, name
, ',');
584 hdr
= request
->header
.getByName(name
);
586 value
= hdr
.termedBuf();
589 value
= rfc1738_escape_part(value
);
590 vstr
.append("=\"", 2);
592 vstr
.append("\"", 1);
599 #if X_ACCELERATOR_VARY
602 vary
= reply
->header
.getList(HDR_X_ACCELERATOR_VARY
);
604 while (strListGetItem(&vary
, ',', &item
, &ilen
, &pos
)) {
605 char *name
= (char *)xmalloc(ilen
+ 1);
606 xstrncpy(name
, item
, ilen
+ 1);
608 strListAdd(&vstr
, name
, ',');
609 hdr
= request
->header
.getByName(name
);
611 value
= hdr
.termedBuf();
614 value
= rfc1738_escape_part(value
);
615 vstr
.append("=\"", 2);
617 vstr
.append("\"", 1);
626 debugs(11, 3, "httpMakeVaryMark: " << vstr
);
627 return vstr
.termedBuf();
631 HttpStateData::keepaliveAccounting(HttpReply
*reply
)
635 _peer
->stats
.n_keepalives_sent
++;
637 if (reply
->keep_alive
) {
639 _peer
->stats
.n_keepalives_recv
++;
641 if (Config
.onoff
.detect_broken_server_pconns
642 && reply
->bodySize(request
->method
) == -1 && !flags
.chunked
) {
643 debugs(11, 1, "keepaliveAccounting: Impossible keep-alive header from '" << entry
->url() << "'" );
644 // debugs(11, 2, "GOT HTTP REPLY HDR:\n---------\n" << readBuf->content() << "\n----------" );
645 flags
.keepalive_broken
= 1;
651 HttpStateData::checkDateSkew(HttpReply
*reply
)
653 if (reply
->date
> -1 && !_peer
) {
654 int skew
= abs((int)(reply
->date
- squid_curtime
));
657 debugs(11, 3, "" << request
->GetHost() << "'s clock is skewed by " << skew
<< " seconds!");
662 * This creates the error page itself.. its likely
663 * that the forward ported reply header max size patch
664 * generates non http conformant error pages - in which
665 * case the errors where should be 'BAD_GATEWAY' etc
668 HttpStateData::processReplyHeader()
670 /** Creates a blank header. If this routine is made incremental, this will not do */
671 Ctx ctx
= ctx_enter(entry
->mem_obj
->url
);
672 debugs(11, 3, "processReplyHeader: key '" << entry
->getMD5Text() << "'");
674 assert(!flags
.headers_parsed
);
676 http_status error
= HTTP_STATUS_NONE
;
678 HttpReply
*newrep
= new HttpReply
;
679 const bool parsed
= newrep
->parse(readBuf
, eof
, &error
);
681 if (!parsed
&& readBuf
->contentSize() > 5 && strncmp(readBuf
->content(), "HTTP/", 5) != 0) {
683 HttpReply
*tmprep
= new HttpReply
;
684 tmprep
->sline
.version
= HttpVersion(1, 0);
685 tmprep
->sline
.status
= HTTP_OK
;
686 tmprep
->header
.putTime(HDR_DATE
, squid_curtime
);
687 tmprep
->header
.putExt("X-Transformed-From", "HTTP/0.9");
689 newrep
->parse(mb
, eof
, &error
);
692 if (!parsed
&& error
> 0) { // unrecoverable parsing error
693 debugs(11, 3, "processReplyHeader: Non-HTTP-compliant header: '" << readBuf
->content() << "'");
694 flags
.headers_parsed
= 1;
695 newrep
->sline
.version
= HttpVersion(1, 0);
696 newrep
->sline
.status
= error
;
697 HttpReply
*vrep
= setVirginReply(newrep
);
698 entry
->replaceHttpReply(vrep
);
703 if (!parsed
) { // need more data
711 debugs(11, 9, "GOT HTTP REPLY HDR:\n---------\n" << readBuf
->content() << "\n----------");
713 header_bytes_read
= headersEnd(readBuf
->content(), readBuf
->contentSize());
714 readBuf
->consume(header_bytes_read
);
718 if (newrep
->header
.hasListMember(HDR_TRANSFER_ENCODING
, "chunked", ',')) {
720 httpChunkDecoder
= new ChunkedCodingParser
;
723 if (!peerSupportsConnectionPinning())
724 orig_request
->flags
.connection_auth_disabled
= 1;
726 HttpReply
*vrep
= setVirginReply(newrep
);
727 flags
.headers_parsed
= 1;
729 keepaliveAccounting(vrep
);
733 processSurrogateControl (vrep
);
735 /** \todo IF the reply is a 1.0 reply, AND it has a Connection: Header
736 * Parse the header and remove all referenced headers
739 orig_request
->hier
.peer_reply_status
= newrep
->sline
.status
;
746 * returns true if the peer can support connection pinning
748 bool HttpStateData::peerSupportsConnectionPinning() const
750 const HttpReply
*rep
= entry
->mem_obj
->getReply();
751 const HttpHeader
*hdr
= &rep
->header
;
758 /*If this peer does not support connection pinning (authenticated
759 connections) return false
761 if (!_peer
->connection_auth
)
764 /*The peer supports connection pinning and the http reply status
765 is not unauthorized, so the related connection can be pinned
767 if (rep
->sline
.status
!= HTTP_UNAUTHORIZED
)
770 /*The server respond with HTTP_UNAUTHORIZED and the peer configured
771 with "connection-auth=on" we know that the peer supports pinned
774 if (_peer
->connection_auth
== 1)
777 /*At this point peer has configured with "connection-auth=auto"
778 parameter so we need some extra checks to decide if we are going
779 to allow pinned connections or not
782 /*if the peer configured with originserver just allow connection
783 pinning (squid 2.6 behaviour)
785 if (_peer
->options
.originserver
)
788 /*if the connections it is already pinned it is OK*/
789 if (request
->flags
.pinned
)
792 /*Allow pinned connections only if the Proxy-support header exists in
793 reply and has in its list the "Session-Based-Authentication"
794 which means that the peer supports connection pinning.
796 if (!hdr
->has(HDR_PROXY_SUPPORT
))
799 header
= hdr
->getStrOrList(HDR_PROXY_SUPPORT
);
800 /* XXX This ought to be done in a case-insensitive manner */
801 rc
= (strstr(header
.termedBuf(), "Session-Based-Authentication") != NULL
);
806 // Called when we parsed (and possibly adapted) the headers but
807 // had not starting storing (a.k.a., sending) the body yet.
809 HttpStateData::haveParsedReplyHeaders()
811 ServerStateData::haveParsedReplyHeaders();
813 Ctx ctx
= ctx_enter(entry
->mem_obj
->url
);
814 HttpReply
*rep
= finalReply();
816 if (rep
->sline
.status
== HTTP_PARTIAL_CONTENT
&&
818 currentOffset
= rep
->content_range
->spec
.offset
;
820 entry
->timestampsSet();
822 /* Check if object is cacheable or not based on reply code */
823 debugs(11, 3, "haveParsedReplyHeaders: HTTP CODE: " << rep
->sline
.status
);
825 if (neighbors_do_private_keys
)
826 httpMaybeRemovePublic(entry
, rep
->sline
.status
);
828 if (rep
->header
.has(HDR_VARY
)
829 #if X_ACCELERATOR_VARY
830 || rep
->header
.has(HDR_X_ACCELERATOR_VARY
)
833 const char *vary
= httpMakeVaryMark(orig_request
, rep
);
836 entry
->makePrivate();
841 entry
->mem_obj
->vary_headers
= xstrdup(vary
);
849 * If its not a reply that we will re-forward, then
850 * allow the client to get it.
852 if (!fwd
->reforwardableStatus(rep
->sline
.status
))
853 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
855 switch (cacheableReply()) {
862 entry
->makePrivate();
868 if (Config
.negativeTtl
> 0)
869 entry
->cacheNegatively();
872 entry
->makePrivate();
884 if (!ignoreCacheControl
&& rep
->cache_control
) {
885 if (EBIT_TEST(rep
->cache_control
->mask
, CC_PROXY_REVALIDATE
))
886 EBIT_SET(entry
->flags
, ENTRY_REVALIDATE
);
887 else if (EBIT_TEST(rep
->cache_control
->mask
, CC_MUST_REVALIDATE
))
888 EBIT_SET(entry
->flags
, ENTRY_REVALIDATE
);
892 headersLog(1, 0, request
->method
, rep
);
899 HttpStateData::ConnectionStatus
900 HttpStateData::statusIfComplete() const
902 const HttpReply
*rep
= virginReply();
904 * If the reply wants to close the connection, it takes precedence */
906 if (httpHeaderHasConnDir(&rep
->header
, "close"))
907 return COMPLETE_NONPERSISTENT_MSG
;
910 * If we didn't send a keep-alive request header, then this
911 * can not be a persistent connection.
913 if (!flags
.keepalive
)
914 return COMPLETE_NONPERSISTENT_MSG
;
917 * If we haven't sent the whole request then this can not be a persistent
920 if (!flags
.request_sent
) {
921 debugs(11, 1, "statusIfComplete: Request not yet fully sent \"" << RequestMethodStr(orig_request
->method
) << " " << entry
->url() << "\"" );
922 return COMPLETE_NONPERSISTENT_MSG
;
926 * What does the reply have to say about keep-alive?
930 * If the origin server (HTTP/1.0) does not send a keep-alive
931 * header, but keeps the connection open anyway, what happens?
932 * We'll return here and http.c waits for an EOF before changing
933 * store_status to STORE_OK. Combine this with ENTRY_FWD_HDR_WAIT
934 * and an error status code, and we might have to wait until
935 * the server times out the socket.
937 if (!rep
->keep_alive
)
938 return COMPLETE_NONPERSISTENT_MSG
;
940 return COMPLETE_PERSISTENT_MSG
;
943 HttpStateData::ConnectionStatus
944 HttpStateData::persistentConnStatus() const
946 debugs(11, 3, "persistentConnStatus: FD " << fd
<< " eof=" << eof
);
947 const HttpReply
*vrep
= virginReply();
948 debugs(11, 5, "persistentConnStatus: content_length=" << vrep
->content_length
);
950 /* If we haven't seen the end of reply headers, we are not done */
951 debugs(11, 5, "persistentConnStatus: flags.headers_parsed=" << flags
.headers_parsed
);
953 if (!flags
.headers_parsed
)
954 return INCOMPLETE_MSG
;
956 if (eof
) // already reached EOF
957 return COMPLETE_NONPERSISTENT_MSG
;
960 * In chunked response we do not know the content length but we are absolutely
961 * sure about the end of response, so we are calling the statusIfComplete to
962 * decide if we can be persistant
964 if (lastChunk
&& flags
.chunked
)
965 return statusIfComplete();
967 const int64_t clen
= vrep
->bodySize(request
->method
);
969 debugs(11, 5, "persistentConnStatus: clen=" << clen
);
971 /* If the body size is unknown we must wait for EOF */
973 return INCOMPLETE_MSG
;
976 * If the body size is known, we must wait until we've gotten all of it. */
979 // if (entry->mem_obj->endOffset() < vrep->content_length + vrep->hdr_sz)
980 const int64_t body_bytes_read
= reply_bytes_read
- header_bytes_read
;
981 debugs(11,5, "persistentConnStatus: body_bytes_read=" <<
982 body_bytes_read
<< " content_length=" << vrep
->content_length
);
984 if (body_bytes_read
< vrep
->content_length
)
985 return INCOMPLETE_MSG
;
987 if (body_bytes_truncated
> 0) // already read more than needed
988 return COMPLETE_NONPERSISTENT_MSG
; // disable pconns
992 * If there is no message body or we got it all, we can be persistent */
993 return statusIfComplete();
997 * This is the callback after some data has been read from the network
1001 HttpStateData::ReadReplyWrapper(int fd, char *buf, size_t len, comm_err_t flag, int xerrno, void *data)
1003 HttpStateData *httpState = static_cast<HttpStateData *>(data);
1004 assert (fd == httpState->fd);
1005 // assert(buf == readBuf->content());
1006 PROF_start(HttpStateData_readReply);
1007 httpState->readReply(len, flag, xerrno);
1008 PROF_stop(HttpStateData_readReply);
1012 /* XXX this function is too long! */
1014 HttpStateData::readReply(const CommIoCbParams
&io
)
1020 assert(fd
== io
.fd
);
1022 flags
.do_next_read
= 0;
1024 debugs(11, 5, "httpReadReply: FD " << fd
<< ": len " << len
<< ".");
1026 // Bail out early on COMM_ERR_CLOSING - close handlers will tidy up for us
1027 if (io
.flag
== COMM_ERR_CLOSING
) {
1028 debugs(11, 3, "http socket closing");
1032 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1033 maybeReadVirginBody();
1037 // handle I/O errors
1038 if (io
.flag
!= COMM_OK
|| len
< 0) {
1039 debugs(11, 2, "httpReadReply: FD " << fd
<< ": read failure: " << xstrerror() << ".");
1041 if (ignoreErrno(io
.xerrno
)) {
1042 flags
.do_next_read
= 1;
1045 err
= errorCon(ERR_READ_ERROR
, HTTP_BAD_GATEWAY
, fwd
->request
);
1046 err
->xerrno
= io
.xerrno
;
1048 flags
.do_next_read
= 0;
1057 readBuf
->appended(len
);
1058 reply_bytes_read
+= len
;
1061 DelayId delayId
= entry
->mem_obj
->mostBytesAllowed();
1062 delayId
.bytesIn(len
);
1065 kb_incr(&statCounter
.server
.all
.kbytes_in
, len
);
1066 kb_incr(&statCounter
.server
.http
.kbytes_in
, len
);
1067 IOStats
.Http
.reads
++;
1069 for (clen
= len
- 1, bin
= 0; clen
; bin
++)
1072 IOStats
.Http
.read_hist
[bin
]++;
1074 // update peer response time stats (%<pt)
1075 const timeval
&sent
= orig_request
->hier
.peer_http_request_sent
;
1076 orig_request
->hier
.peer_response_time
=
1077 sent
.tv_sec
? tvSubMsec(sent
, current_time
) : -1;
1081 * Here the RFC says we should ignore whitespace between replies, but we can't as
1082 * doing so breaks HTTP/0.9 replies beginning with witespace, and in addition
1083 * the response splitting countermeasures is extremely likely to trigger on this,
1084 * not allowing connection reuse in the first place.
1087 if (!flags
.headers_parsed
&& len
> 0 && fd_table
[fd
].uses
> 1) {
1088 /* Skip whitespace between replies */
1090 while (len
> 0 && xisspace(*buf
))
1091 xmemmove(buf
, buf
+ 1, len
--);
1094 /* Continue to read... */
1095 /* Timeout NOT increased. This whitespace was from previous reply */
1096 flags
.do_next_read
= 1;
1097 maybeReadVirginBody();
1104 if (len
== 0) { // reached EOF?
1106 flags
.do_next_read
= 0;
1109 if (!flags
.headers_parsed
) { // have not parsed headers yet?
1110 PROF_start(HttpStateData_processReplyHeader
);
1111 processReplyHeader();
1112 PROF_stop(HttpStateData_processReplyHeader
);
1114 if (!continueAfterParsingHeader()) // parsing error or need more data
1115 return; // TODO: send errors to ICAP
1117 adaptOrFinalizeReply();
1120 // kick more reads if needed and/or process the response body, if any
1121 PROF_start(HttpStateData_processReplyBody
);
1122 processReplyBody(); // may call serverComplete()
1123 PROF_stop(HttpStateData_processReplyBody
);
1127 \retval true if we can continue with processing the body or doing ICAP.
1130 HttpStateData::continueAfterParsingHeader()
1132 if (!flags
.headers_parsed
&& !eof
) {
1133 debugs(11, 9, HERE
<< "needs more at " << readBuf
->contentSize());
1134 flags
.do_next_read
= 1;
1135 /** \retval false If we have not finished parsing the headers and may get more data.
1136 * Schedules more reads to retrieve the missing data.
1138 maybeReadVirginBody(); // schedules all kinds of reads; TODO: rename
1142 /** If we are done with parsing, check for errors */
1144 err_type error
= ERR_NONE
;
1146 if (flags
.headers_parsed
) { // parsed headers, possibly with errors
1147 // check for header parsing errors
1148 if (HttpReply
*vrep
= virginReply()) {
1149 const http_status s
= vrep
->sline
.status
;
1150 const HttpVersion
&v
= vrep
->sline
.version
;
1151 if (s
== HTTP_INVALID_HEADER
&& v
!= HttpVersion(0,9)) {
1152 error
= ERR_INVALID_RESP
;
1154 if (s
== HTTP_HEADER_TOO_LARGE
) {
1155 fwd
->dontRetry(true);
1156 error
= ERR_TOO_BIG
;
1158 return true; // done parsing, got reply, and no error
1161 // parsed headers but got no reply
1162 error
= ERR_INVALID_RESP
;
1166 error
= readBuf
->hasContent() ?
1167 ERR_INVALID_RESP
: ERR_ZERO_SIZE_OBJECT
;
1170 assert(error
!= ERR_NONE
);
1172 fwd
->fail(errorCon(error
, HTTP_BAD_GATEWAY
, fwd
->request
));
1173 flags
.do_next_read
= 0;
1175 return false; // quit on error
1178 /** truncate what we read if we read too much so that writeReplyBody()
1179 writes no more than what we should have read */
1181 HttpStateData::truncateVirginBody()
1183 assert(flags
.headers_parsed
);
1185 HttpReply
*vrep
= virginReply();
1187 if (!vrep
->expectingBody(request
->method
, clen
) || clen
< 0)
1188 return; // no body or a body of unknown size, including chunked
1190 const int64_t body_bytes_read
= reply_bytes_read
- header_bytes_read
;
1191 if (body_bytes_read
- body_bytes_truncated
<= clen
)
1192 return; // we did not read too much or already took care of the extras
1194 if (const int64_t extras
= body_bytes_read
- body_bytes_truncated
- clen
) {
1195 // server sent more that the advertised content length
1196 debugs(11,5, HERE
<< "body_bytes_read=" << body_bytes_read
<<
1197 " clen=" << clen
<< '/' << vrep
->content_length
<<
1198 " body_bytes_truncated=" << body_bytes_truncated
<< '+' << extras
);
1200 readBuf
->truncate(extras
);
1201 body_bytes_truncated
+= extras
;
1206 * Call this when there is data from the origin server
1207 * which should be sent to either StoreEntry, or to ICAP...
1210 HttpStateData::writeReplyBody()
1212 truncateVirginBody(); // if needed
1213 const char *data
= readBuf
->content();
1214 int len
= readBuf
->contentSize();
1215 addVirginReplyBody(data
, len
);
1216 readBuf
->consume(len
);
1220 HttpStateData::decodeAndWriteReplyBody()
1222 const char *data
= NULL
;
1224 bool status
= false;
1225 assert(flags
.chunked
);
1226 assert(httpChunkDecoder
);
1227 SQUID_ENTER_THROWING_CODE();
1230 const bool done
= httpChunkDecoder
->parse(readBuf
,&decodedData
);
1231 len
= decodedData
.contentSize();
1232 data
=decodedData
.content();
1233 addVirginReplyBody(data
, len
);
1236 flags
.do_next_read
= 0;
1238 SQUID_EXIT_THROWING_CODE(status
);
1243 * processReplyBody has two purposes:
1244 * 1 - take the reply body data, if any, and put it into either
1245 * the StoreEntry, or give it over to ICAP.
1246 * 2 - see if we made it to the end of the response (persistent
1247 * connections and such)
1250 HttpStateData::processReplyBody()
1252 AsyncCall::Pointer call
;
1253 IpAddress client_addr
;
1254 bool ispinned
= false;
1256 if (!flags
.headers_parsed
) {
1257 flags
.do_next_read
= 1;
1258 maybeReadVirginBody();
1263 debugs(11,5, HERE
<< "adaptationAccessCheckPending=" << adaptationAccessCheckPending
);
1264 if (adaptationAccessCheckPending
)
1270 * At this point the reply headers have been parsed and consumed.
1271 * That means header content has been removed from readBuf and
1272 * it contains only body data.
1274 if (flags
.chunked
) {
1275 if (!decodeAndWriteReplyBody()) {
1276 flags
.do_next_read
= 0;
1283 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1285 * The above writeReplyBody() call could ABORT this entry,
1286 * in that case, the server FD should already be closed.
1287 * there's nothing for us to do.
1291 switch (persistentConnStatus()) {
1292 case INCOMPLETE_MSG
:
1293 debugs(11, 5, "processReplyBody: INCOMPLETE_MSG");
1294 /* Wait for more data or EOF condition */
1295 if (flags
.keepalive_broken
) {
1297 commSetTimeout(fd
, 10, call
);
1300 commSetTimeout(fd
, Config
.Timeout
.read
, call
);
1303 flags
.do_next_read
= 1;
1306 case COMPLETE_PERSISTENT_MSG
:
1307 debugs(11, 5, "processReplyBody: COMPLETE_PERSISTENT_MSG");
1308 /* yes we have to clear all these! */
1310 commSetTimeout(fd
, -1, call
);
1311 flags
.do_next_read
= 0;
1313 comm_remove_close_handler(fd
, closeHandler
);
1314 closeHandler
= NULL
;
1315 fwd
->unregister(fd
);
1317 if (orig_request
->flags
.spoof_client_ip
)
1318 client_addr
= orig_request
->client_addr
;
1321 if (request
->flags
.pinned
) {
1323 } else if (request
->flags
.connection_auth
&& request
->flags
.auth_sent
) {
1327 if (orig_request
->pinnedConnection() && ispinned
) {
1328 orig_request
->pinnedConnection()->pinConnection(fd
, orig_request
, _peer
,
1329 (request
->flags
.connection_auth
!= 0));
1331 fwd
->pconnPush(fd
, _peer
, request
, orig_request
->GetHost(), client_addr
);
1339 case COMPLETE_NONPERSISTENT_MSG
:
1340 debugs(11, 5, "processReplyBody: COMPLETE_NONPERSISTENT_MSG");
1345 maybeReadVirginBody();
1349 HttpStateData::maybeReadVirginBody()
1351 int read_sz
= replyBodySpace(readBuf
->spaceSize());
1353 debugs(11,9, HERE
<< (flags
.do_next_read
? "may" : "wont") <<
1354 " read up to " << read_sz
<< " bytes from FD " << fd
);
1357 * why <2? Because delayAwareRead() won't actually read if
1358 * you ask it to read 1 byte. The delayed read request
1359 * just gets re-queued until the client side drains, then
1360 * the I/O thread hangs. Better to not register any read
1361 * handler until we get a notification from someone that
1362 * its okay to read again.
1365 if (flags
.headers_parsed
)
1371 if (flags
.do_next_read
) {
1372 flags
.do_next_read
= 0;
1373 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
1374 entry
->delayAwareRead(fd
, readBuf
->space(read_sz
), read_sz
,
1375 asyncCall(11, 5, "HttpStateData::readReply",
1376 Dialer(this, &HttpStateData::readReply
)));
1381 * This will be called when request write is complete.
1384 HttpStateData::sendComplete(const CommIoCbParams
&io
)
1386 debugs(11, 5, "httpSendComplete: FD " << fd
<< ": size " << io
.size
<< ": errflag " << io
.flag
<< ".");
1387 #if URL_CHECKSUM_DEBUG
1389 entry
->mem_obj
->checkUrlChecksum();
1393 fd_bytes(fd
, io
.size
, FD_WRITE
);
1394 kb_incr(&statCounter
.server
.all
.kbytes_out
, io
.size
);
1395 kb_incr(&statCounter
.server
.http
.kbytes_out
, io
.size
);
1398 if (io
.flag
== COMM_ERR_CLOSING
)
1403 err
= errorCon(ERR_WRITE_ERROR
, HTTP_BAD_GATEWAY
, fwd
->request
);
1404 err
->xerrno
= io
.xerrno
;
1411 * Set the read timeout here because it hasn't been set yet.
1412 * We only set the read timeout after the request has been
1413 * fully written to the server-side. If we start the timeout
1414 * after connection establishment, then we are likely to hit
1415 * the timeout for POST/PUT requests that have very large
1418 typedef CommCbMemFunT
<HttpStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1419 AsyncCall::Pointer timeoutCall
= asyncCall(11, 5, "HttpStateData::httpTimeout",
1420 TimeoutDialer(this,&HttpStateData::httpTimeout
));
1422 commSetTimeout(fd
, Config
.Timeout
.read
, timeoutCall
);
1424 flags
.request_sent
= 1;
1426 orig_request
->hier
.peer_http_request_sent
= current_time
;
1429 // Close the HTTP server connection. Used by serverComplete().
1431 HttpStateData::closeServer()
1433 debugs(11,5, HERE
<< "closing HTTP server FD " << fd
<< " this " << this);
1436 fwd
->unregister(fd
);
1437 comm_remove_close_handler(fd
, closeHandler
);
1438 closeHandler
= NULL
;
1445 HttpStateData::doneWithServer() const
1451 * build request headers and append them to a given MemBuf
1452 * used by buildRequestPrefix()
1453 * note: initialised the HttpHeader, the caller is responsible for Clean()-ing
1456 HttpStateData::httpBuildRequestHeader(HttpRequest
* request
,
1457 HttpRequest
* orig_request
,
1459 HttpHeader
* hdr_out
,
1460 http_state_flags flags
)
1462 /* building buffer for complex strings */
1463 #define BBUF_SZ (MAX_URL+32)
1464 LOCAL_ARRAY(char, bbuf
, BBUF_SZ
);
1465 LOCAL_ARRAY(char, ntoabuf
, MAX_IPSTRLEN
);
1466 const HttpHeader
*hdr_in
= &orig_request
->header
;
1467 const HttpHeaderEntry
*e
= NULL
;
1468 HttpHeaderPos pos
= HttpHeaderInitPos
;
1469 assert (hdr_out
->owner
== hoRequest
);
1471 /* append our IMS header */
1472 if (request
->lastmod
> -1)
1473 hdr_out
->putTime(HDR_IF_MODIFIED_SINCE
, request
->lastmod
);
1475 bool we_do_ranges
= decideIfWeDoRanges (orig_request
);
1477 String
strConnection (hdr_in
->getList(HDR_CONNECTION
));
1479 while ((e
= hdr_in
->getEntry(&pos
)))
1480 copyOneHeaderFromClientsideRequestToUpstreamRequest(e
, strConnection
, request
, orig_request
, hdr_out
, we_do_ranges
, flags
);
1482 /* Abstraction break: We should interpret multipart/byterange responses
1483 * into offset-length data, and this works around our inability to do so.
1485 if (!we_do_ranges
&& orig_request
->multipartRangeRequest()) {
1486 /* don't cache the result */
1487 orig_request
->flags
.cachable
= 0;
1488 /* pretend it's not a range request */
1489 delete orig_request
->range
;
1490 orig_request
->range
= NULL
;
1491 orig_request
->flags
.range
= 0;
1495 if (Config
.onoff
.via
) {
1497 strVia
= hdr_in
->getList(HDR_VIA
);
1498 snprintf(bbuf
, BBUF_SZ
, "%d.%d %s",
1499 orig_request
->http_ver
.major
,
1500 orig_request
->http_ver
.minor
, ThisCache
);
1501 strListAdd(&strVia
, bbuf
, ',');
1502 hdr_out
->putStr(HDR_VIA
, strVia
.termedBuf());
1508 /* Append Surrogate-Capabilities */
1509 String
strSurrogate (hdr_in
->getList(HDR_SURROGATE_CAPABILITY
));
1510 snprintf(bbuf
, BBUF_SZ
, "%s=\"Surrogate/1.0 ESI/1.0\"",
1511 Config
.Accel
.surrogate_id
);
1512 strListAdd(&strSurrogate
, bbuf
, ',');
1513 hdr_out
->putStr(HDR_SURROGATE_CAPABILITY
, strSurrogate
.termedBuf());
1517 /** \pre Handle X-Forwarded-For */
1518 if (strcmp(opt_forwarded_for
, "delete") != 0) {
1520 String strFwd
= hdr_in
->getList(HDR_X_FORWARDED_FOR
);
1522 if (strFwd
.size() > 65536/2) {
1523 // There is probably a forwarding loop with Via detection disabled.
1524 // If we do nothing, String will assert on overflow soon.
1525 // TODO: Terminate all transactions with huge XFF?
1528 static int warnedCount
= 0;
1529 if (warnedCount
++ < 100) {
1530 const char *url
= entry
? entry
->url() : urlCanonical(orig_request
);
1531 debugs(11, 1, "Warning: likely forwarding loop with " << url
);
1535 if (strcmp(opt_forwarded_for
, "on") == 0) {
1536 /** If set to ON - append client IP or 'unknown'. */
1537 if ( orig_request
->client_addr
.IsNoAddr() )
1538 strListAdd(&strFwd
, "unknown", ',');
1540 strListAdd(&strFwd
, orig_request
->client_addr
.NtoA(ntoabuf
, MAX_IPSTRLEN
), ',');
1541 } else if (strcmp(opt_forwarded_for
, "off") == 0) {
1542 /** If set to OFF - append 'unknown'. */
1543 strListAdd(&strFwd
, "unknown", ',');
1544 } else if (strcmp(opt_forwarded_for
, "transparent") == 0) {
1545 /** If set to TRANSPARENT - pass through unchanged. */
1546 } else if (strcmp(opt_forwarded_for
, "truncate") == 0) {
1547 /** If set to TRUNCATE - drop existing list and replace with client IP or 'unknown'. */
1548 if ( orig_request
->client_addr
.IsNoAddr() )
1551 strFwd
= orig_request
->client_addr
.NtoA(ntoabuf
, MAX_IPSTRLEN
);
1553 if (strFwd
.size() > 0)
1554 hdr_out
->putStr(HDR_X_FORWARDED_FOR
, strFwd
.termedBuf());
1556 /** If set to DELETE - do not copy through. */
1558 /* append Host if not there already */
1559 if (!hdr_out
->has(HDR_HOST
)) {
1560 if (orig_request
->peer_domain
) {
1561 hdr_out
->putStr(HDR_HOST
, orig_request
->peer_domain
);
1562 } else if (orig_request
->port
== urlDefaultPort(orig_request
->protocol
)) {
1563 /* use port# only if not default */
1564 hdr_out
->putStr(HDR_HOST
, orig_request
->GetHost());
1566 httpHeaderPutStrf(hdr_out
, HDR_HOST
, "%s:%d",
1567 orig_request
->GetHost(),
1568 (int) orig_request
->port
);
1572 /* append Authorization if known in URL, not in header and going direct */
1573 if (!hdr_out
->has(HDR_AUTHORIZATION
)) {
1574 if (!request
->flags
.proxying
&& *request
->login
) {
1575 httpHeaderPutStrf(hdr_out
, HDR_AUTHORIZATION
, "Basic %s",
1576 base64_encode(request
->login
));
1580 /* append Proxy-Authorization if configured for peer, and proxying */
1581 if (request
->flags
.proxying
&& orig_request
->peer_login
&&
1582 !hdr_out
->has(HDR_PROXY_AUTHORIZATION
)) {
1583 if (*orig_request
->peer_login
== '*') {
1584 /* Special mode, to pass the username to the upstream cache */
1586 const char *username
= "-";
1588 if (orig_request
->extacl_user
.size())
1589 username
= orig_request
->extacl_user
.termedBuf();
1590 else if (orig_request
->auth_user_request
)
1591 username
= orig_request
->auth_user_request
->username();
1593 snprintf(loginbuf
, sizeof(loginbuf
), "%s%s", username
, orig_request
->peer_login
+ 1);
1595 httpHeaderPutStrf(hdr_out
, HDR_PROXY_AUTHORIZATION
, "Basic %s",
1596 base64_encode(loginbuf
));
1597 } else if (strcmp(orig_request
->peer_login
, "PASS") == 0) {
1598 if (orig_request
->extacl_user
.size() && orig_request
->extacl_passwd
.size()) {
1600 snprintf(loginbuf
, sizeof(loginbuf
), SQUIDSTRINGPH
":" SQUIDSTRINGPH
,
1601 SQUIDSTRINGPRINT(orig_request
->extacl_user
),
1602 SQUIDSTRINGPRINT(orig_request
->extacl_passwd
));
1603 httpHeaderPutStrf(hdr_out
, HDR_PROXY_AUTHORIZATION
, "Basic %s",
1604 base64_encode(loginbuf
));
1606 } else if (strcmp(orig_request
->peer_login
, "PROXYPASS") == 0) {
1609 httpHeaderPutStrf(hdr_out
, HDR_PROXY_AUTHORIZATION
, "Basic %s",
1610 base64_encode(orig_request
->peer_login
));
1614 /* append WWW-Authorization if configured for peer */
1615 if (flags
.originpeer
&& orig_request
->peer_login
&&
1616 !hdr_out
->has(HDR_AUTHORIZATION
)) {
1617 if (strcmp(orig_request
->peer_login
, "PASS") == 0) {
1618 /* No credentials to forward.. (should have been done above if available) */
1619 } else if (strcmp(orig_request
->peer_login
, "PROXYPASS") == 0) {
1620 /* Special mode, convert proxy authentication to WWW authentication
1621 * (also applies to authentication provided by external acl)
1623 const char *auth
= hdr_in
->getStr(HDR_PROXY_AUTHORIZATION
);
1625 if (auth
&& strncasecmp(auth
, "basic ", 6) == 0) {
1626 hdr_out
->putStr(HDR_AUTHORIZATION
, auth
);
1627 } else if (orig_request
->extacl_user
.size() && orig_request
->extacl_passwd
.size()) {
1629 snprintf(loginbuf
, sizeof(loginbuf
), SQUIDSTRINGPH
":" SQUIDSTRINGPH
,
1630 SQUIDSTRINGPRINT(orig_request
->extacl_user
),
1631 SQUIDSTRINGPRINT(orig_request
->extacl_passwd
));
1632 httpHeaderPutStrf(hdr_out
, HDR_AUTHORIZATION
, "Basic %s",
1633 base64_encode(loginbuf
));
1635 } else if (*orig_request
->peer_login
== '*') {
1636 /* Special mode, to pass the username to the upstream cache */
1638 const char *username
= "-";
1640 if (orig_request
->auth_user_request
)
1641 username
= orig_request
->auth_user_request
->username();
1642 else if (orig_request
->extacl_user
.size())
1643 username
= orig_request
->extacl_user
.termedBuf();
1645 snprintf(loginbuf
, sizeof(loginbuf
), "%s%s", username
, orig_request
->peer_login
+ 1);
1647 httpHeaderPutStrf(hdr_out
, HDR_AUTHORIZATION
, "Basic %s",
1648 base64_encode(loginbuf
));
1650 /* Fixed login string */
1651 httpHeaderPutStrf(hdr_out
, HDR_AUTHORIZATION
, "Basic %s",
1652 base64_encode(orig_request
->peer_login
));
1656 /* append Cache-Control, add max-age if not there already */ {
1657 HttpHdrCc
*cc
= hdr_in
->getCc();
1660 cc
= httpHdrCcCreate();
1662 #if 0 /* see bug 2330 */
1663 /* Set no-cache if determined needed but not found */
1664 if (orig_request
->flags
.nocache
)
1665 EBIT_SET(cc
->mask
, CC_NO_CACHE
);
1668 /* Add max-age only without no-cache */
1669 if (!EBIT_TEST(cc
->mask
, CC_MAX_AGE
) && !EBIT_TEST(cc
->mask
, CC_NO_CACHE
)) {
1671 entry
? entry
->url() : urlCanonical(orig_request
);
1672 httpHdrCcSetMaxAge(cc
, getMaxAge(url
));
1674 if (request
->urlpath
.size())
1675 assert(strstr(url
, request
->urlpath
.termedBuf()));
1678 /* Enforce sibling relations */
1679 if (flags
.only_if_cached
)
1680 EBIT_SET(cc
->mask
, CC_ONLY_IF_CACHED
);
1684 httpHdrCcDestroy(cc
);
1687 /* maybe append Connection: keep-alive */
1688 if (flags
.keepalive
) {
1689 if (flags
.proxying
) {
1690 hdr_out
->putStr(HDR_PROXY_CONNECTION
, "keep-alive");
1692 hdr_out
->putStr(HDR_CONNECTION
, "keep-alive");
1696 /* append Front-End-Https */
1697 if (flags
.front_end_https
) {
1698 if (flags
.front_end_https
== 1 || request
->protocol
== PROTO_HTTPS
)
1699 hdr_out
->putStr(HDR_FRONT_END_HTTPS
, "On");
1702 /* Now mangle the headers. */
1703 if (Config2
.onoff
.mangle_request_headers
)
1704 httpHdrMangleList(hdr_out
, request
, ROR_REQUEST
);
1706 strConnection
.clean();
1710 * Decides whether a particular header may be cloned from the received Clients request
1711 * to our outgoing fetch request.
1714 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
)
1716 debugs(11, 5, "httpBuildRequestHeader: " << e
->name
<< ": " << e
->value
);
1720 /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid should not pass on. */
1722 case HDR_PROXY_AUTHORIZATION
:
1723 /** \par Proxy-Authorization:
1724 * Only pass on proxy authentication to peers for which
1725 * authentication forwarding is explicitly enabled
1728 if (flags
.proxying
&& orig_request
->peer_login
&&
1729 (strcmp(orig_request
->peer_login
, "PASS") == 0 ||
1730 strcmp(orig_request
->peer_login
, "PROXYPASS") == 0)) {
1731 hdr_out
->addEntry(e
->clone());
1736 /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid does not pass on. */
1738 case HDR_CONNECTION
: /** \par Connection: */
1739 case HDR_TE
: /** \par TE: */
1740 case HDR_KEEP_ALIVE
: /** \par Keep-Alive: */
1741 case HDR_PROXY_AUTHENTICATE
: /** \par Proxy-Authenticate: */
1742 case HDR_TRAILERS
: /** \par Trailers: */
1743 case HDR_UPGRADE
: /** \par Upgrade: */
1744 case HDR_TRANSFER_ENCODING
: /** \par Transfer-Encoding: */
1748 /** \par OTHER headers I haven't bothered to track down yet. */
1750 case HDR_AUTHORIZATION
:
1751 /** \par WWW-Authorization:
1752 * Pass on WWW authentication */
1754 if (!flags
.originpeer
) {
1755 hdr_out
->addEntry(e
->clone());
1757 /** \note In accelerators, only forward authentication if enabled
1758 * by login=PASS or login=PROXYPASS
1759 * (see also below for proxy->server authentication)
1761 if (orig_request
->peer_login
&&
1762 (strcmp(orig_request
->peer_login
, "PASS") == 0 ||
1763 strcmp(orig_request
->peer_login
, "PROXYPASS") == 0)) {
1764 hdr_out
->addEntry(e
->clone());
1772 * Normally Squid rewrites the Host: header.
1773 * However, there is one case when we don't: If the URL
1774 * went through our redirector and the admin configured
1775 * 'redir_rewrites_host' to be off.
1777 if (orig_request
->peer_domain
)
1778 hdr_out
->putStr(HDR_HOST
, orig_request
->peer_domain
);
1779 else if (request
->flags
.redirected
&& !Config
.onoff
.redir_rewrites_host
)
1780 hdr_out
->addEntry(e
->clone());
1782 /* use port# only if not default */
1784 if (orig_request
->port
== urlDefaultPort(orig_request
->protocol
)) {
1785 hdr_out
->putStr(HDR_HOST
, orig_request
->GetHost());
1787 httpHeaderPutStrf(hdr_out
, HDR_HOST
, "%s:%d",
1788 orig_request
->GetHost(),
1789 (int) orig_request
->port
);
1795 case HDR_IF_MODIFIED_SINCE
:
1796 /** \par If-Modified-Since:
1797 * append unless we added our own;
1798 * \note at most one client's ims header can pass through */
1800 if (!hdr_out
->has(HDR_IF_MODIFIED_SINCE
))
1801 hdr_out
->addEntry(e
->clone());
1805 case HDR_MAX_FORWARDS
:
1806 /** \par Max-Forwards:
1807 * pass only on TRACE or OPTIONS requests */
1808 if (orig_request
->method
== METHOD_TRACE
|| orig_request
->method
== METHOD_OPTIONS
) {
1809 const int64_t hops
= e
->getInt64();
1812 hdr_out
->putInt64(HDR_MAX_FORWARDS
, hops
- 1);
1819 * If Via is disabled then forward any received header as-is.
1820 * Otherwise leave for explicit updated addition later. */
1822 if (!Config
.onoff
.via
)
1823 hdr_out
->addEntry(e
->clone());
1831 case HDR_REQUEST_RANGE
:
1832 /** \par Range:, If-Range:, Request-Range:
1833 * Only pass if we accept ranges */
1835 hdr_out
->addEntry(e
->clone());
1839 case HDR_PROXY_CONNECTION
:
1841 case HDR_X_FORWARDED_FOR
:
1843 case HDR_CACHE_CONTROL
:
1844 /** \par Proxy-Connaction:, X-Forwarded-For:, Cache-Control:
1845 * handled specially by Squid, so leave off for now.
1846 * append these after the loop if needed */
1849 case HDR_FRONT_END_HTTPS
:
1850 /** \par Front-End-Https:
1851 * Pass thru only if peer is configured with front-end-https */
1852 if (!flags
.front_end_https
)
1853 hdr_out
->addEntry(e
->clone());
1859 * pass on all other header fields
1860 * which are NOT listed by the special Connection: header. */
1862 if (strConnection
.size()>0 && strListIsMember(&strConnection
, e
->name
.termedBuf(), ',')) {
1863 debugs(11, 2, "'" << e
->name
<< "' header cropped by Connection: definition");
1867 hdr_out
->addEntry(e
->clone());
1872 HttpStateData::decideIfWeDoRanges (HttpRequest
* orig_request
)
1875 /* decide if we want to do Ranges ourselves
1876 * and fetch the whole object now)
1877 * We want to handle Ranges ourselves iff
1878 * - we can actually parse client Range specs
1879 * - the specs are expected to be simple enough (e.g. no out-of-order ranges)
1880 * - reply will be cachable
1881 * (If the reply will be uncachable we have to throw it away after
1882 * serving this request, so it is better to forward ranges to
1883 * the server and fetch only the requested content)
1886 if (NULL
== orig_request
->range
|| !orig_request
->flags
.cachable
1887 || orig_request
->range
->offsetLimitExceeded() || orig_request
->flags
.connection_auth
)
1890 debugs(11, 8, "decideIfWeDoRanges: range specs: " <<
1891 orig_request
->range
<< ", cachable: " <<
1892 orig_request
->flags
.cachable
<< "; we_do_ranges: " << result
);
1897 /* build request prefix and append it to a given MemBuf;
1898 * return the length of the prefix */
1900 HttpStateData::buildRequestPrefix(HttpRequest
* request
,
1901 HttpRequest
* orig_request
,
1904 http_state_flags flags
)
1906 const int offset
= mb
->size
;
1907 HttpVersion
httpver(1, 0);
1908 mb
->Printf("%s %s HTTP/%d.%d\r\n",
1909 RequestMethodStr(request
->method
),
1910 request
->urlpath
.size() ? request
->urlpath
.termedBuf() : "/",
1911 httpver
.major
,httpver
.minor
);
1912 /* build and pack headers */
1914 HttpHeader
hdr(hoRequest
);
1916 httpBuildRequestHeader(request
, orig_request
, entry
, &hdr
, flags
);
1918 if (request
->flags
.pinned
&& request
->flags
.connection_auth
)
1919 request
->flags
.auth_sent
= 1;
1920 else if (hdr
.has(HDR_AUTHORIZATION
))
1921 request
->flags
.auth_sent
= 1;
1923 packerToMemInit(&p
, mb
);
1928 /* append header terminator */
1929 mb
->append(crlf
, 2);
1930 return mb
->size
- offset
;
1933 /* This will be called when connect completes. Write request. */
1935 HttpStateData::sendRequest()
1939 debugs(11, 5, "httpSendRequest: FD " << fd
<< ", request " << request
<< ", this " << this << ".");
1940 typedef CommCbMemFunT
<HttpStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1941 AsyncCall::Pointer timeoutCall
= asyncCall(11, 5, "HttpStateData::httpTimeout",
1942 TimeoutDialer(this,&HttpStateData::httpTimeout
));
1943 commSetTimeout(fd
, Config
.Timeout
.lifetime
, timeoutCall
);
1944 flags
.do_next_read
= 1;
1945 maybeReadVirginBody();
1947 if (orig_request
->body_pipe
!= NULL
) {
1948 if (!startRequestBodyFlow()) // register to receive body data
1950 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
1951 Dialer
dialer(this, &HttpStateData::sentRequestBody
);
1952 requestSender
= asyncCall(11,5, "HttpStateData::sentRequestBody", dialer
);
1954 assert(!requestBodySource
);
1955 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
1956 Dialer
dialer(this, &HttpStateData::sendComplete
);
1957 requestSender
= asyncCall(11,5, "HttpStateData::SendComplete", dialer
);
1960 if (_peer
!= NULL
) {
1961 if (_peer
->options
.originserver
) {
1963 flags
.originpeer
= 1;
1966 flags
.originpeer
= 0;
1970 flags
.originpeer
= 0;
1974 * Is keep-alive okay for all request methods?
1976 if (orig_request
->flags
.must_keepalive
)
1977 flags
.keepalive
= 1;
1978 else if (!Config
.onoff
.server_pconns
)
1979 flags
.keepalive
= 0;
1980 else if (_peer
== NULL
)
1981 flags
.keepalive
= 1;
1982 else if (_peer
->stats
.n_keepalives_sent
< 10)
1983 flags
.keepalive
= 1;
1984 else if ((double) _peer
->stats
.n_keepalives_recv
/
1985 (double) _peer
->stats
.n_keepalives_sent
> 0.50)
1986 flags
.keepalive
= 1;
1989 if (neighborType(_peer
, request
) == PEER_SIBLING
&&
1990 !_peer
->options
.allow_miss
)
1991 flags
.only_if_cached
= 1;
1993 flags
.front_end_https
= _peer
->front_end_https
;
1997 buildRequestPrefix(request
, orig_request
, entry
, &mb
, flags
);
1998 debugs(11, 6, "httpSendRequest: FD " << fd
<< ":\n" << mb
.buf
);
1999 comm_write_mbuf(fd
, &mb
, requestSender
);
2005 httpStart(FwdState
*fwd
)
2007 debugs(11, 3, "httpStart: \"" << RequestMethodStr(fwd
->request
->method
) << " " << fwd
->entry
->url() << "\"" );
2008 HttpStateData
*httpState
= new HttpStateData(fwd
);
2010 if (!httpState
->sendRequest()) {
2011 debugs(11, 3, "httpStart: aborted");
2016 statCounter
.server
.all
.requests
++;
2017 statCounter
.server
.http
.requests
++;
2020 * We used to set the read timeout here, but not any more.
2021 * Now its set in httpSendComplete() after the full request,
2022 * including request body, has been written to the server.
2027 HttpStateData::doneSendingRequestBody()
2029 debugs(11,5, HERE
<< "doneSendingRequestBody: FD " << fd
);
2032 if (Config
.accessList
.brokenPosts
) {
2033 ACLFilledChecklist
ch(Config
.accessList
.brokenPosts
, request
, NULL
);
2034 if (!ch
.fastCheck()) {
2035 debugs(11, 5, "doneSendingRequestBody: didn't match brokenPosts");
2036 CommIoCbParams
io(NULL
);
2041 debugs(11, 2, "doneSendingRequestBody: matched brokenPosts");
2042 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
2043 Dialer
dialer(this, &HttpStateData::sendComplete
);
2044 AsyncCall::Pointer call
= asyncCall(11,5, "HttpStateData::SendComplete", dialer
);
2045 comm_write(fd
, "\r\n", 2, call
);
2049 debugs(11, 5, "doneSendingRequestBody: No brokenPosts list");
2050 #endif /* HTTP_VIOLATIONS */
2052 CommIoCbParams
io(NULL
);
2058 // more origin request body data is available
2060 HttpStateData::handleMoreRequestBodyAvailable()
2062 if (eof
|| fd
< 0) {
2063 // XXX: we should check this condition in other callbacks then!
2064 // TODO: Check whether this can actually happen: We should unsubscribe
2065 // as a body consumer when the above condition(s) are detected.
2066 debugs(11, 1, HERE
<< "Transaction aborted while reading HTTP body");
2070 assert(requestBodySource
!= NULL
);
2072 if (requestBodySource
->buf().hasContent()) {
2073 // XXX: why does not this trigger a debug message on every request?
2075 if (flags
.headers_parsed
&& !flags
.abuse_detected
) {
2076 flags
.abuse_detected
= 1;
2077 debugs(11, 1, "http handleMoreRequestBodyAvailable: Likely proxy abuse detected '" << orig_request
->client_addr
<< "' -> '" << entry
->url() << "'" );
2079 if (virginReply()->sline
.status
== HTTP_INVALID_HEADER
) {
2086 HttpStateData::handleMoreRequestBodyAvailable();
2089 // premature end of the request body
2091 HttpStateData::handleRequestBodyProducerAborted()
2093 ServerStateData::handleRequestBodyProducerAborted();
2094 // XXX: SendComplete(COMM_ERR_CLOSING) does little. Is it enough?
2095 CommIoCbParams
io(NULL
);
2097 io
.flag
=COMM_ERR_CLOSING
;
2101 // called when we wrote request headers(!) or a part of the body
2103 HttpStateData::sentRequestBody(const CommIoCbParams
&io
)
2106 kb_incr(&statCounter
.server
.http
.kbytes_out
, io
.size
);
2108 ServerStateData::sentRequestBody(io
);
2111 // Quickly abort the transaction
2112 // TODO: destruction should be sufficient as the destructor should cleanup,
2113 // including canceling close handlers
2115 HttpStateData::abortTransaction(const char *reason
)
2117 debugs(11,5, HERE
<< "aborting transaction for " << reason
<<
2118 "; FD " << fd
<< ", this " << this);
2125 fwd
->handleUnregisteredServerEnd();
2126 deleteThis("HttpStateData::abortTransaction");
2131 httpBuildVersion(HttpVersion
* version
, unsigned int major
, unsigned int minor
)
2133 version
->major
= major
;
2134 version
->minor
= minor
;
2139 HttpStateData::originalRequest()
2141 return orig_request
;