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.
43 #include "acl/FilledChecklist.h"
44 #include "auth/UserRequest.h"
46 #include "DelayPools.h"
48 #include "errorpage.h"
51 #include "HttpHdrContRange.h"
52 #include "HttpHdrSc.h"
53 #include "HttpHdrScTarget.h"
54 #include "HttpReply.h"
55 #include "HttpRequest.h"
57 #include "MemObject.h"
59 #include "SquidTime.h"
61 #include "TextException.h"
64 #define SQUID_ENTER_THROWING_CODE() try {
65 #define SQUID_EXIT_THROWING_CODE(status) \
68 catch (const std::exception &e) { \
69 debugs (11, 1, "Exception error:" << e.what()); \
73 CBDATA_CLASS_INIT(HttpStateData
);
75 static const char *const crlf
= "\r\n";
77 static void httpMaybeRemovePublic(StoreEntry
*, http_status
);
78 static void copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry
*e
, const String strConnection
, HttpRequest
* request
, const HttpRequest
* orig_request
,
79 HttpHeader
* hdr_out
, const int we_do_ranges
, const http_state_flags
);
81 HttpStateData::HttpStateData(FwdState
*theFwdState
) : AsyncJob("HttpStateData"), ServerStateData(theFwdState
),
82 lastChunk(0), header_bytes_read(0), reply_bytes_read(0),
83 body_bytes_truncated(0), httpChunkDecoder(NULL
)
85 debugs(11,5,HERE
<< "HttpStateData " << this << " created");
86 ignoreCacheControl
= false;
87 surrogateNoStore
= false;
91 orig_request
= HTTPMSGLOCK(fwd
->request
);
93 // reset peer response time stats for %<pt
94 orig_request
->hier
.peer_http_request_sent
.tv_sec
= 0;
95 orig_request
->hier
.peer_http_request_sent
.tv_usec
= 0;
98 _peer
= fwd
->servers
->_peer
; /* might be NULL */
103 if (_peer
->options
.originserver
)
104 url
= orig_request
->urlpath
.termedBuf();
108 HttpRequest
* proxy_req
= new HttpRequest(orig_request
->method
,
109 orig_request
->protocol
, url
);
111 proxy_req
->SetHost(_peer
->host
);
113 proxy_req
->port
= _peer
->http_port
;
115 proxy_req
->flags
= orig_request
->flags
;
117 proxy_req
->lastmod
= orig_request
->lastmod
;
119 proxy_req
->flags
.proxying
= 1;
121 HTTPMSGUNLOCK(request
);
123 request
= HTTPMSGLOCK(proxy_req
);
126 * This NEIGHBOR_PROXY_ONLY check probably shouldn't be here.
127 * We might end up getting the object from somewhere else if,
128 * for example, the request to this neighbor fails.
130 if (_peer
->options
.proxy_only
)
131 entry
->releaseRequest();
135 entry
->setNoDelay(_peer
->options
.no_delay
);
141 * register the handler to free HTTP state data when the FD closes
143 typedef CommCbMemFunT
<HttpStateData
, CommCloseCbParams
> Dialer
;
144 closeHandler
= asyncCall(9, 5, "httpStateData::httpStateConnClosed",
145 Dialer(this,&HttpStateData::httpStateConnClosed
));
146 comm_add_close_handler(fd
, closeHandler
);
149 HttpStateData::~HttpStateData()
152 * don't forget that ~ServerStateData() gets called automatically
155 if (!readBuf
->isNull())
160 if (httpChunkDecoder
)
161 delete httpChunkDecoder
;
163 HTTPMSGUNLOCK(orig_request
);
165 debugs(11,5, HERE
<< "HttpStateData " << this << " destroyed; FD " << fd
);
169 HttpStateData::dataDescriptor() const
175 httpStateFree(int fd, void *data)
177 HttpStateData *httpState = static_cast<HttpStateData *>(data);
178 debugs(11, 5, "httpStateFree: FD " << fd << ", httpState=" << data);
183 HttpStateData::httpStateConnClosed(const CommCloseCbParams
¶ms
)
185 debugs(11, 5, "httpStateFree: FD " << params
.fd
<< ", httpState=" << params
.data
);
186 deleteThis("HttpStateData::httpStateConnClosed");
190 httpCachable(const HttpRequestMethod
& method
)
192 /* GET and HEAD are cachable. Others are not. */
194 // TODO: replase to HttpRequestMethod::isCachable() ?
195 if (method
!= METHOD_GET
&& method
!= METHOD_HEAD
)
203 HttpStateData::httpTimeout(const CommTimeoutCbParams
¶ms
)
205 debugs(11, 4, "httpTimeout: FD " << fd
<< ": '" << entry
->url() << "'" );
207 if (entry
->store_status
== STORE_PENDING
) {
208 fwd
->fail(errorCon(ERR_READ_TIMEOUT
, HTTP_GATEWAY_TIMEOUT
, fwd
->request
));
215 httpMaybeRemovePublic(StoreEntry
* e
, http_status status
)
221 if (!EBIT_TEST(e
->flags
, KEY_PRIVATE
))
228 case HTTP_NON_AUTHORITATIVE_INFORMATION
:
230 case HTTP_MULTIPLE_CHOICES
:
232 case HTTP_MOVED_PERMANENTLY
:
234 case HTTP_MOVED_TEMPORARILY
:
245 case HTTP_METHOD_NOT_ALLOWED
:
252 case HTTP_UNAUTHORIZED
:
262 * Any 2xx response should eject previously cached entities...
265 if (status
>= 200 && status
< 300)
273 if (!remove
&& !forbidden
)
278 if (e
->mem_obj
->request
)
279 pe
= storeGetPublicByRequest(e
->mem_obj
->request
);
281 pe
= storeGetPublic(e
->mem_obj
->url
, e
->mem_obj
->method
);
286 neighborsHtcpClear(e
, NULL
, e
->mem_obj
->request
, e
->mem_obj
->method
, HTCP_CLR_INVALIDATION
);
292 * Also remove any cached HEAD response in case the object has
295 if (e
->mem_obj
->request
)
296 pe
= storeGetPublicByRequestMethod(e
->mem_obj
->request
, METHOD_HEAD
);
298 pe
= storeGetPublic(e
->mem_obj
->url
, METHOD_HEAD
);
303 neighborsHtcpClear(e
, NULL
, e
->mem_obj
->request
, HttpRequestMethod(METHOD_HEAD
), HTCP_CLR_INVALIDATION
);
310 HttpStateData::processSurrogateControl(HttpReply
*reply
)
314 if (request
->flags
.accelerated
&& reply
->surrogate_control
) {
315 HttpHdrScTarget
*sctusable
=
316 httpHdrScGetMergedTarget(reply
->surrogate_control
,
317 Config
.Accel
.surrogate_id
);
320 if (EBIT_TEST(sctusable
->mask
, SC_NO_STORE
) ||
321 (Config
.onoff
.surrogate_is_remote
322 && EBIT_TEST(sctusable
->mask
, SC_NO_STORE_REMOTE
))) {
323 surrogateNoStore
= true;
324 entry
->makePrivate();
327 /* The HttpHeader logic cannot tell if the header it's parsing is a reply to an
328 * accelerated request or not...
329 * Still, this is an abtraction breach. - RC
331 if (sctusable
->max_age
!= -1) {
332 if (sctusable
->max_age
< sctusable
->max_stale
)
333 reply
->expires
= reply
->date
+ sctusable
->max_age
;
335 reply
->expires
= reply
->date
+ sctusable
->max_stale
;
337 /* And update the timestamps */
338 entry
->timestampsSet();
341 /* We ignore cache-control directives as per the Surrogate specification */
342 ignoreCacheControl
= true;
344 httpHdrScTargetDestroy(sctusable
);
352 HttpStateData::cacheableReply()
354 HttpReply
const *rep
= finalReply();
355 HttpHeader
const *hdr
= &rep
->header
;
356 const int cc_mask
= (rep
->cache_control
) ? rep
->cache_control
->mask
: 0;
360 const refresh_t
*R
= NULL
;
362 /* This strange looking define first looks up the refresh pattern
363 * and then checks if the specified flag is set. The main purpose
364 * of this is to simplify the refresh pattern lookup and HTTP_VIOLATIONS
367 #define REFRESH_OVERRIDE(flag) \
368 ((R = (R ? R : refreshLimits(entry->mem_obj->url))) , \
369 (R && R->flags.flag))
371 #define REFRESH_OVERRIDE(flag) 0
374 if (surrogateNoStore
)
377 if (!ignoreCacheControl
) {
378 if (EBIT_TEST(cc_mask
, CC_PRIVATE
)) {
379 if (!REFRESH_OVERRIDE(ignore_private
))
383 if (EBIT_TEST(cc_mask
, CC_NO_CACHE
)) {
384 if (!REFRESH_OVERRIDE(ignore_no_cache
))
388 if (EBIT_TEST(cc_mask
, CC_NO_STORE
)) {
389 if (!REFRESH_OVERRIDE(ignore_no_store
))
394 if (request
->flags
.auth
|| request
->flags
.auth_sent
) {
396 * Responses to requests with authorization may be cached
397 * only if a Cache-Control: public reply header is present.
398 * RFC 2068, sec 14.9.4
401 if (!EBIT_TEST(cc_mask
, CC_PUBLIC
)) {
402 if (!REFRESH_OVERRIDE(ignore_auth
))
407 /* Pragma: no-cache in _replies_ is not documented in HTTP,
408 * but servers like "Active Imaging Webcast/2.0" sure do use it */
409 if (hdr
->has(HDR_PRAGMA
)) {
410 String s
= hdr
->getList(HDR_PRAGMA
);
411 const int no_cache
= strListIsMember(&s
, "no-cache", ',');
415 if (!REFRESH_OVERRIDE(ignore_no_cache
))
421 * The "multipart/x-mixed-replace" content type is used for
422 * continuous push replies. These are generally dynamic and
423 * probably should not be cachable
425 if ((v
= hdr
->getStr(HDR_CONTENT_TYPE
)))
426 if (!strncasecmp(v
, "multipart/x-mixed-replace", 25))
429 switch (rep
->sline
.status
) {
430 /* Responses that are cacheable */
434 case HTTP_NON_AUTHORITATIVE_INFORMATION
:
436 case HTTP_MULTIPLE_CHOICES
:
438 case HTTP_MOVED_PERMANENTLY
:
442 * Don't cache objects that need to be refreshed on next request,
443 * unless we know how to refresh it.
446 if (!refreshIsCachable(entry
)) {
447 debugs(22, 3, "refreshIsCachable() returned non-cacheable..");
451 /* don't cache objects from peers w/o LMT, Date, or Expires */
452 /* check that is it enough to check headers @?@ */
455 else if (rep
->last_modified
> -1)
460 /* @?@ (here and 302): invalid expires header compiles to squid_curtime */
461 else if (rep
->expires
> -1)
469 /* Responses that only are cacheable if the server says so */
471 case HTTP_MOVED_TEMPORARILY
:
472 case HTTP_TEMPORARY_REDIRECT
:
473 if (rep
->expires
> rep
->date
&& rep
->date
> 0)
481 /* Errors can be negatively cached */
483 case HTTP_NO_CONTENT
:
487 case HTTP_BAD_REQUEST
:
493 case HTTP_METHOD_NOT_ALLOWED
:
495 case HTTP_REQUEST_URI_TOO_LARGE
:
497 case HTTP_INTERNAL_SERVER_ERROR
:
499 case HTTP_NOT_IMPLEMENTED
:
501 case HTTP_BAD_GATEWAY
:
503 case HTTP_SERVICE_UNAVAILABLE
:
505 case HTTP_GATEWAY_TIMEOUT
:
511 /* Some responses can never be cached */
513 case HTTP_PARTIAL_CONTENT
: /* Not yet supported */
517 case HTTP_NOT_MODIFIED
:
519 case HTTP_UNAUTHORIZED
:
521 case HTTP_PROXY_AUTHENTICATION_REQUIRED
:
523 case HTTP_INVALID_HEADER
: /* Squid header parsing error */
525 case HTTP_HEADER_TOO_LARGE
:
527 case HTTP_PAYMENT_REQUIRED
:
528 case HTTP_NOT_ACCEPTABLE
:
529 case HTTP_REQUEST_TIMEOUT
:
531 case HTTP_LENGTH_REQUIRED
:
532 case HTTP_PRECONDITION_FAILED
:
533 case HTTP_REQUEST_ENTITY_TOO_LARGE
:
534 case HTTP_UNSUPPORTED_MEDIA_TYPE
:
535 case HTTP_UNPROCESSABLE_ENTITY
:
537 case HTTP_FAILED_DEPENDENCY
:
538 case HTTP_INSUFFICIENT_STORAGE
:
539 case HTTP_REQUESTED_RANGE_NOT_SATISFIABLE
:
540 case HTTP_EXPECTATION_FAILED
:
544 default: /* Unknown status code */
545 debugs (11, 0, HERE
<< "HttpStateData::cacheableReply: unexpected http status code " << rep
->sline
.status
);
557 * For Vary, store the relevant request headers as
558 * virtual headers in the reply
559 * Returns false if the variance cannot be stored
562 httpMakeVaryMark(HttpRequest
* request
, HttpReply
const * reply
)
565 const char *pos
= NULL
;
572 vary
= reply
->header
.getList(HDR_VARY
);
574 while (strListGetItem(&vary
, ',', &item
, &ilen
, &pos
)) {
575 char *name
= (char *)xmalloc(ilen
+ 1);
576 xstrncpy(name
, item
, ilen
+ 1);
579 if (strcmp(name
, "*") == 0) {
580 /* Can not handle "Vary: *" withtout ETag support */
586 strListAdd(&vstr
, name
, ',');
587 hdr
= request
->header
.getByName(name
);
589 value
= hdr
.termedBuf();
592 value
= rfc1738_escape_part(value
);
593 vstr
.append("=\"", 2);
595 vstr
.append("\"", 1);
602 #if X_ACCELERATOR_VARY
605 vary
= reply
->header
.getList(HDR_X_ACCELERATOR_VARY
);
607 while (strListGetItem(&vary
, ',', &item
, &ilen
, &pos
)) {
608 char *name
= (char *)xmalloc(ilen
+ 1);
609 xstrncpy(name
, item
, ilen
+ 1);
611 strListAdd(&vstr
, name
, ',');
612 hdr
= request
->header
.getByName(name
);
614 value
= hdr
.termedBuf();
617 value
= rfc1738_escape_part(value
);
618 vstr
.append("=\"", 2);
620 vstr
.append("\"", 1);
629 debugs(11, 3, "httpMakeVaryMark: " << vstr
);
630 return vstr
.termedBuf();
634 HttpStateData::keepaliveAccounting(HttpReply
*reply
)
638 _peer
->stats
.n_keepalives_sent
++;
640 if (reply
->keep_alive
) {
642 _peer
->stats
.n_keepalives_recv
++;
644 if (Config
.onoff
.detect_broken_server_pconns
645 && reply
->bodySize(request
->method
) == -1 && !flags
.chunked
) {
646 debugs(11, 1, "keepaliveAccounting: Impossible keep-alive header from '" << entry
->url() << "'" );
647 // debugs(11, 2, "GOT HTTP REPLY HDR:\n---------\n" << readBuf->content() << "\n----------" );
648 flags
.keepalive_broken
= 1;
654 HttpStateData::checkDateSkew(HttpReply
*reply
)
656 if (reply
->date
> -1 && !_peer
) {
657 int skew
= abs((int)(reply
->date
- squid_curtime
));
660 debugs(11, 3, "" << request
->GetHost() << "'s clock is skewed by " << skew
<< " seconds!");
665 * This creates the error page itself.. its likely
666 * that the forward ported reply header max size patch
667 * generates non http conformant error pages - in which
668 * case the errors where should be 'BAD_GATEWAY' etc
671 HttpStateData::processReplyHeader()
673 /** Creates a blank header. If this routine is made incremental, this will not do */
674 Ctx ctx
= ctx_enter(entry
->mem_obj
->url
);
675 debugs(11, 3, "processReplyHeader: key '" << entry
->getMD5Text() << "'");
677 assert(!flags
.headers_parsed
);
679 http_status error
= HTTP_STATUS_NONE
;
681 HttpReply
*newrep
= new HttpReply
;
682 const bool parsed
= newrep
->parse(readBuf
, eof
, &error
);
684 if (!parsed
&& readBuf
->contentSize() > 5 && strncmp(readBuf
->content(), "HTTP/", 5) != 0) {
686 HttpReply
*tmprep
= new HttpReply
;
687 tmprep
->sline
.version
= HttpVersion(1, 0);
688 tmprep
->sline
.status
= HTTP_OK
;
689 tmprep
->header
.putTime(HDR_DATE
, squid_curtime
);
690 tmprep
->header
.putExt("X-Transformed-From", "HTTP/0.9");
692 newrep
->parse(mb
, eof
, &error
);
695 if (!parsed
&& error
> 0) { // unrecoverable parsing error
696 debugs(11, 3, "processReplyHeader: Non-HTTP-compliant header: '" << readBuf
->content() << "'");
697 flags
.headers_parsed
= 1;
698 newrep
->sline
.version
= HttpVersion(1, 0);
699 newrep
->sline
.status
= error
;
700 HttpReply
*vrep
= setVirginReply(newrep
);
701 entry
->replaceHttpReply(vrep
);
706 if (!parsed
) { // need more data
714 debugs(11, 9, "GOT HTTP REPLY HDR:\n---------\n" << readBuf
->content() << "\n----------");
716 header_bytes_read
= headersEnd(readBuf
->content(), readBuf
->contentSize());
717 readBuf
->consume(header_bytes_read
);
721 if (newrep
->header
.hasListMember(HDR_TRANSFER_ENCODING
, "chunked", ',')) {
723 httpChunkDecoder
= new ChunkedCodingParser
;
726 if (!peerSupportsConnectionPinning())
727 orig_request
->flags
.connection_auth_disabled
= 1;
729 HttpReply
*vrep
= setVirginReply(newrep
);
730 flags
.headers_parsed
= 1;
732 keepaliveAccounting(vrep
);
736 processSurrogateControl (vrep
);
738 /** \todo IF the reply is a 1.0 reply, AND it has a Connection: Header
739 * Parse the header and remove all referenced headers
742 orig_request
->hier
.peer_reply_status
= newrep
->sline
.status
;
749 * returns true if the peer can support connection pinning
751 bool HttpStateData::peerSupportsConnectionPinning() const
753 const HttpReply
*rep
= entry
->mem_obj
->getReply();
754 const HttpHeader
*hdr
= &rep
->header
;
761 /*If this peer does not support connection pinning (authenticated
762 connections) return false
764 if (!_peer
->connection_auth
)
767 /*The peer supports connection pinning and the http reply status
768 is not unauthorized, so the related connection can be pinned
770 if (rep
->sline
.status
!= HTTP_UNAUTHORIZED
)
773 /*The server respond with HTTP_UNAUTHORIZED and the peer configured
774 with "connection-auth=on" we know that the peer supports pinned
777 if (_peer
->connection_auth
== 1)
780 /*At this point peer has configured with "connection-auth=auto"
781 parameter so we need some extra checks to decide if we are going
782 to allow pinned connections or not
785 /*if the peer configured with originserver just allow connection
786 pinning (squid 2.6 behaviour)
788 if (_peer
->options
.originserver
)
791 /*if the connections it is already pinned it is OK*/
792 if (request
->flags
.pinned
)
795 /*Allow pinned connections only if the Proxy-support header exists in
796 reply and has in its list the "Session-Based-Authentication"
797 which means that the peer supports connection pinning.
799 if (!hdr
->has(HDR_PROXY_SUPPORT
))
802 header
= hdr
->getStrOrList(HDR_PROXY_SUPPORT
);
803 /* XXX This ought to be done in a case-insensitive manner */
804 rc
= (strstr(header
.termedBuf(), "Session-Based-Authentication") != NULL
);
809 // Called when we parsed (and possibly adapted) the headers but
810 // had not starting storing (a.k.a., sending) the body yet.
812 HttpStateData::haveParsedReplyHeaders()
814 ServerStateData::haveParsedReplyHeaders();
816 Ctx ctx
= ctx_enter(entry
->mem_obj
->url
);
817 HttpReply
*rep
= finalReply();
819 if (rep
->sline
.status
== HTTP_PARTIAL_CONTENT
&&
821 currentOffset
= rep
->content_range
->spec
.offset
;
823 entry
->timestampsSet();
825 /* Check if object is cacheable or not based on reply code */
826 debugs(11, 3, "haveParsedReplyHeaders: HTTP CODE: " << rep
->sline
.status
);
828 if (neighbors_do_private_keys
)
829 httpMaybeRemovePublic(entry
, rep
->sline
.status
);
831 if (rep
->header
.has(HDR_VARY
)
832 #if X_ACCELERATOR_VARY
833 || rep
->header
.has(HDR_X_ACCELERATOR_VARY
)
836 const char *vary
= httpMakeVaryMark(orig_request
, rep
);
839 entry
->makePrivate();
844 entry
->mem_obj
->vary_headers
= xstrdup(vary
);
852 * If its not a reply that we will re-forward, then
853 * allow the client to get it.
855 if (!fwd
->reforwardableStatus(rep
->sline
.status
))
856 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
858 switch (cacheableReply()) {
865 entry
->makePrivate();
871 if (Config
.negativeTtl
> 0)
872 entry
->cacheNegatively();
875 entry
->makePrivate();
887 if (!ignoreCacheControl
&& rep
->cache_control
) {
888 if (EBIT_TEST(rep
->cache_control
->mask
, CC_PROXY_REVALIDATE
))
889 EBIT_SET(entry
->flags
, ENTRY_REVALIDATE
);
890 else if (EBIT_TEST(rep
->cache_control
->mask
, CC_MUST_REVALIDATE
))
891 EBIT_SET(entry
->flags
, ENTRY_REVALIDATE
);
895 headersLog(1, 0, request
->method
, rep
);
902 HttpStateData::ConnectionStatus
903 HttpStateData::statusIfComplete() const
905 const HttpReply
*rep
= virginReply();
907 * If the reply wants to close the connection, it takes precedence */
909 if (httpHeaderHasConnDir(&rep
->header
, "close"))
910 return COMPLETE_NONPERSISTENT_MSG
;
913 * If we didn't send a keep-alive request header, then this
914 * can not be a persistent connection.
916 if (!flags
.keepalive
)
917 return COMPLETE_NONPERSISTENT_MSG
;
920 * If we haven't sent the whole request then this can not be a persistent
923 if (!flags
.request_sent
) {
924 debugs(11, 1, "statusIfComplete: Request not yet fully sent \"" << RequestMethodStr(orig_request
->method
) << " " << entry
->url() << "\"" );
925 return COMPLETE_NONPERSISTENT_MSG
;
929 * What does the reply have to say about keep-alive?
933 * If the origin server (HTTP/1.0) does not send a keep-alive
934 * header, but keeps the connection open anyway, what happens?
935 * We'll return here and http.c waits for an EOF before changing
936 * store_status to STORE_OK. Combine this with ENTRY_FWD_HDR_WAIT
937 * and an error status code, and we might have to wait until
938 * the server times out the socket.
940 if (!rep
->keep_alive
)
941 return COMPLETE_NONPERSISTENT_MSG
;
943 return COMPLETE_PERSISTENT_MSG
;
946 HttpStateData::ConnectionStatus
947 HttpStateData::persistentConnStatus() const
949 debugs(11, 3, "persistentConnStatus: FD " << fd
<< " eof=" << eof
);
950 const HttpReply
*vrep
= virginReply();
951 debugs(11, 5, "persistentConnStatus: content_length=" << vrep
->content_length
);
953 /* If we haven't seen the end of reply headers, we are not done */
954 debugs(11, 5, "persistentConnStatus: flags.headers_parsed=" << flags
.headers_parsed
);
956 if (!flags
.headers_parsed
)
957 return INCOMPLETE_MSG
;
959 if (eof
) // already reached EOF
960 return COMPLETE_NONPERSISTENT_MSG
;
963 * In chunked response we do not know the content length but we are absolutely
964 * sure about the end of response, so we are calling the statusIfComplete to
965 * decide if we can be persistant
967 if (lastChunk
&& flags
.chunked
)
968 return statusIfComplete();
970 const int64_t clen
= vrep
->bodySize(request
->method
);
972 debugs(11, 5, "persistentConnStatus: clen=" << clen
);
974 /* If the body size is unknown we must wait for EOF */
976 return INCOMPLETE_MSG
;
979 * If the body size is known, we must wait until we've gotten all of it. */
982 // if (entry->mem_obj->endOffset() < vrep->content_length + vrep->hdr_sz)
983 const int64_t body_bytes_read
= reply_bytes_read
- header_bytes_read
;
984 debugs(11,5, "persistentConnStatus: body_bytes_read=" <<
985 body_bytes_read
<< " content_length=" << vrep
->content_length
);
987 if (body_bytes_read
< vrep
->content_length
)
988 return INCOMPLETE_MSG
;
990 if (body_bytes_truncated
> 0) // already read more than needed
991 return COMPLETE_NONPERSISTENT_MSG
; // disable pconns
995 * If there is no message body or we got it all, we can be persistent */
996 return statusIfComplete();
1000 * This is the callback after some data has been read from the network
1004 HttpStateData::ReadReplyWrapper(int fd, char *buf, size_t len, comm_err_t flag, int xerrno, void *data)
1006 HttpStateData *httpState = static_cast<HttpStateData *>(data);
1007 assert (fd == httpState->fd);
1008 // assert(buf == readBuf->content());
1009 PROF_start(HttpStateData_readReply);
1010 httpState->readReply(len, flag, xerrno);
1011 PROF_stop(HttpStateData_readReply);
1015 /* XXX this function is too long! */
1017 HttpStateData::readReply(const CommIoCbParams
&io
)
1023 assert(fd
== io
.fd
);
1025 flags
.do_next_read
= 0;
1027 debugs(11, 5, "httpReadReply: FD " << fd
<< ": len " << len
<< ".");
1029 // Bail out early on COMM_ERR_CLOSING - close handlers will tidy up for us
1030 if (io
.flag
== COMM_ERR_CLOSING
) {
1031 debugs(11, 3, "http socket closing");
1035 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1036 maybeReadVirginBody();
1040 // handle I/O errors
1041 if (io
.flag
!= COMM_OK
|| len
< 0) {
1042 debugs(11, 2, "httpReadReply: FD " << fd
<< ": read failure: " << xstrerror() << ".");
1044 if (ignoreErrno(io
.xerrno
)) {
1045 flags
.do_next_read
= 1;
1048 err
= errorCon(ERR_READ_ERROR
, HTTP_BAD_GATEWAY
, fwd
->request
);
1049 err
->xerrno
= io
.xerrno
;
1051 flags
.do_next_read
= 0;
1060 readBuf
->appended(len
);
1061 reply_bytes_read
+= len
;
1064 DelayId delayId
= entry
->mem_obj
->mostBytesAllowed();
1065 delayId
.bytesIn(len
);
1068 kb_incr(&statCounter
.server
.all
.kbytes_in
, len
);
1069 kb_incr(&statCounter
.server
.http
.kbytes_in
, len
);
1070 IOStats
.Http
.reads
++;
1072 for (clen
= len
- 1, bin
= 0; clen
; bin
++)
1075 IOStats
.Http
.read_hist
[bin
]++;
1077 // update peer response time stats (%<pt)
1078 const timeval
&sent
= orig_request
->hier
.peer_http_request_sent
;
1079 orig_request
->hier
.peer_response_time
=
1080 sent
.tv_sec
? tvSubMsec(sent
, current_time
) : -1;
1084 * Here the RFC says we should ignore whitespace between replies, but we can't as
1085 * doing so breaks HTTP/0.9 replies beginning with witespace, and in addition
1086 * the response splitting countermeasures is extremely likely to trigger on this,
1087 * not allowing connection reuse in the first place.
1090 if (!flags
.headers_parsed
&& len
> 0 && fd_table
[fd
].uses
> 1) {
1091 /* Skip whitespace between replies */
1093 while (len
> 0 && xisspace(*buf
))
1094 xmemmove(buf
, buf
+ 1, len
--);
1097 /* Continue to read... */
1098 /* Timeout NOT increased. This whitespace was from previous reply */
1099 flags
.do_next_read
= 1;
1100 maybeReadVirginBody();
1107 if (len
== 0) { // reached EOF?
1109 flags
.do_next_read
= 0;
1112 if (!flags
.headers_parsed
) { // have not parsed headers yet?
1113 PROF_start(HttpStateData_processReplyHeader
);
1114 processReplyHeader();
1115 PROF_stop(HttpStateData_processReplyHeader
);
1117 if (!continueAfterParsingHeader()) // parsing error or need more data
1118 return; // TODO: send errors to ICAP
1120 adaptOrFinalizeReply();
1123 // kick more reads if needed and/or process the response body, if any
1124 PROF_start(HttpStateData_processReplyBody
);
1125 processReplyBody(); // may call serverComplete()
1126 PROF_stop(HttpStateData_processReplyBody
);
1130 \retval true if we can continue with processing the body or doing ICAP.
1133 HttpStateData::continueAfterParsingHeader()
1135 if (!flags
.headers_parsed
&& !eof
) {
1136 debugs(11, 9, HERE
<< "needs more at " << readBuf
->contentSize());
1137 flags
.do_next_read
= 1;
1138 /** \retval false If we have not finished parsing the headers and may get more data.
1139 * Schedules more reads to retrieve the missing data.
1141 maybeReadVirginBody(); // schedules all kinds of reads; TODO: rename
1145 /** If we are done with parsing, check for errors */
1147 err_type error
= ERR_NONE
;
1149 if (flags
.headers_parsed
) { // parsed headers, possibly with errors
1150 // check for header parsing errors
1151 if (HttpReply
*vrep
= virginReply()) {
1152 const http_status s
= vrep
->sline
.status
;
1153 const HttpVersion
&v
= vrep
->sline
.version
;
1154 if (s
== HTTP_INVALID_HEADER
&& v
!= HttpVersion(0,9)) {
1155 error
= ERR_INVALID_RESP
;
1156 } else if (s
== HTTP_HEADER_TOO_LARGE
) {
1157 fwd
->dontRetry(true);
1158 error
= ERR_TOO_BIG
;
1160 return true; // done parsing, got reply, and no error
1163 // parsed headers but got no reply
1164 error
= ERR_INVALID_RESP
;
1168 error
= readBuf
->hasContent() ?
1169 ERR_INVALID_RESP
: ERR_ZERO_SIZE_OBJECT
;
1172 assert(error
!= ERR_NONE
);
1174 fwd
->fail(errorCon(error
, HTTP_BAD_GATEWAY
, fwd
->request
));
1175 flags
.do_next_read
= 0;
1177 return false; // quit on error
1180 /** truncate what we read if we read too much so that writeReplyBody()
1181 writes no more than what we should have read */
1183 HttpStateData::truncateVirginBody()
1185 assert(flags
.headers_parsed
);
1187 HttpReply
*vrep
= virginReply();
1189 if (!vrep
->expectingBody(request
->method
, clen
) || clen
< 0)
1190 return; // no body or a body of unknown size, including chunked
1192 const int64_t body_bytes_read
= reply_bytes_read
- header_bytes_read
;
1193 if (body_bytes_read
- body_bytes_truncated
<= clen
)
1194 return; // we did not read too much or already took care of the extras
1196 if (const int64_t extras
= body_bytes_read
- body_bytes_truncated
- clen
) {
1197 // server sent more that the advertised content length
1198 debugs(11,5, HERE
<< "body_bytes_read=" << body_bytes_read
<<
1199 " clen=" << clen
<< '/' << vrep
->content_length
<<
1200 " body_bytes_truncated=" << body_bytes_truncated
<< '+' << extras
);
1202 readBuf
->truncate(extras
);
1203 body_bytes_truncated
+= extras
;
1208 * Call this when there is data from the origin server
1209 * which should be sent to either StoreEntry, or to ICAP...
1212 HttpStateData::writeReplyBody()
1214 truncateVirginBody(); // if needed
1215 const char *data
= readBuf
->content();
1216 int len
= readBuf
->contentSize();
1217 addVirginReplyBody(data
, len
);
1218 readBuf
->consume(len
);
1222 HttpStateData::decodeAndWriteReplyBody()
1224 const char *data
= NULL
;
1226 bool status
= false;
1227 assert(flags
.chunked
);
1228 assert(httpChunkDecoder
);
1229 SQUID_ENTER_THROWING_CODE();
1232 const bool done
= httpChunkDecoder
->parse(readBuf
,&decodedData
);
1233 len
= decodedData
.contentSize();
1234 data
=decodedData
.content();
1235 addVirginReplyBody(data
, len
);
1238 flags
.do_next_read
= 0;
1240 SQUID_EXIT_THROWING_CODE(status
);
1245 * processReplyBody has two purposes:
1246 * 1 - take the reply body data, if any, and put it into either
1247 * the StoreEntry, or give it over to ICAP.
1248 * 2 - see if we made it to the end of the response (persistent
1249 * connections and such)
1252 HttpStateData::processReplyBody()
1254 AsyncCall::Pointer call
;
1255 IpAddress client_addr
;
1256 bool ispinned
= false;
1258 if (!flags
.headers_parsed
) {
1259 flags
.do_next_read
= 1;
1260 maybeReadVirginBody();
1265 debugs(11,5, HERE
<< "adaptationAccessCheckPending=" << adaptationAccessCheckPending
);
1266 if (adaptationAccessCheckPending
)
1272 * At this point the reply headers have been parsed and consumed.
1273 * That means header content has been removed from readBuf and
1274 * it contains only body data.
1276 if (flags
.chunked
) {
1277 if (!decodeAndWriteReplyBody()) {
1278 flags
.do_next_read
= 0;
1285 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1287 * The above writeReplyBody() call could ABORT this entry,
1288 * in that case, the server FD should already be closed.
1289 * there's nothing for us to do.
1293 switch (persistentConnStatus()) {
1294 case INCOMPLETE_MSG
:
1295 debugs(11, 5, "processReplyBody: INCOMPLETE_MSG");
1296 /* Wait for more data or EOF condition */
1297 if (flags
.keepalive_broken
) {
1299 commSetTimeout(fd
, 10, call
);
1302 commSetTimeout(fd
, Config
.Timeout
.read
, call
);
1305 flags
.do_next_read
= 1;
1308 case COMPLETE_PERSISTENT_MSG
:
1309 debugs(11, 5, "processReplyBody: COMPLETE_PERSISTENT_MSG");
1310 /* yes we have to clear all these! */
1312 commSetTimeout(fd
, -1, call
);
1313 flags
.do_next_read
= 0;
1315 comm_remove_close_handler(fd
, closeHandler
);
1316 closeHandler
= NULL
;
1317 fwd
->unregister(fd
);
1319 if (orig_request
->flags
.spoof_client_ip
)
1320 client_addr
= orig_request
->client_addr
;
1323 if (request
->flags
.pinned
) {
1325 } else if (request
->flags
.connection_auth
&& request
->flags
.auth_sent
) {
1329 if (orig_request
->pinnedConnection() && ispinned
) {
1330 orig_request
->pinnedConnection()->pinConnection(fd
, orig_request
, _peer
,
1331 (request
->flags
.connection_auth
!= 0));
1333 fwd
->pconnPush(fd
, _peer
, request
, orig_request
->GetHost(), client_addr
);
1341 case COMPLETE_NONPERSISTENT_MSG
:
1342 debugs(11, 5, "processReplyBody: COMPLETE_NONPERSISTENT_MSG");
1347 maybeReadVirginBody();
1351 HttpStateData::maybeReadVirginBody()
1353 // we may need to grow the buffer if headers do not fit
1354 const int minRead
= flags
.headers_parsed
? 0 : 1024;
1355 const int read_sz
= replyBodySpace(*readBuf
, minRead
);
1357 debugs(11,9, HERE
<< (flags
.do_next_read
? "may" : "wont") <<
1358 " read up to " << read_sz
<< " bytes from FD " << fd
);
1361 * why <2? Because delayAwareRead() won't actually read if
1362 * you ask it to read 1 byte. The delayed read request
1363 * just gets re-queued until the client side drains, then
1364 * the I/O thread hangs. Better to not register any read
1365 * handler until we get a notification from someone that
1366 * its okay to read again.
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
1452 * Fixup authentication request headers for special cases
1455 httpFixupAuthentication(HttpRequest
* request
, HttpRequest
* orig_request
, const HttpHeader
* hdr_in
, HttpHeader
* hdr_out
, http_state_flags flags
)
1457 http_hdr_type header
= flags
.originpeer
? HDR_AUTHORIZATION
: HDR_PROXY_AUTHORIZATION
;
1459 /* Nothing to do unless we are forwarding to a peer */
1460 if (!request
->flags
.proxying
)
1463 /* Needs to be explicitly enabled */
1464 if (!orig_request
->peer_login
)
1467 /* Maybe already dealt with? */
1468 if (hdr_out
->has(header
))
1471 /* Nothing to do here for PASSTHRU */
1472 if (strcmp(orig_request
->peer_login
, "PASSTHRU") == 0)
1475 /* PROXYPASS is a special case, single-signon to servers with the proxy password (basic only) */
1476 if (flags
.originpeer
&& strcmp(orig_request
->peer_login
, "PROXYPASS") == 0 && hdr_in
->has(HDR_PROXY_AUTHORIZATION
)) {
1477 const char *auth
= hdr_in
->getStr(HDR_PROXY_AUTHORIZATION
);
1479 if (auth
&& strncasecmp(auth
, "basic ", 6) == 0) {
1480 hdr_out
->putStr(header
, auth
);
1485 /* Special mode to pass the username to the upstream cache */
1486 if (*orig_request
->peer_login
== '*') {
1488 const char *username
= "-";
1490 if (orig_request
->extacl_user
.size())
1491 username
= orig_request
->extacl_user
.termedBuf();
1492 else if (orig_request
->auth_user_request
)
1493 username
= orig_request
->auth_user_request
->username();
1495 snprintf(loginbuf
, sizeof(loginbuf
), "%s%s", username
, orig_request
->peer_login
+ 1);
1497 httpHeaderPutStrf(hdr_out
, header
, "Basic %s",
1498 base64_encode(loginbuf
));
1502 /* external_acl provided credentials */
1503 if (orig_request
->extacl_user
.size() && orig_request
->extacl_passwd
.size() &&
1504 (strcmp(orig_request
->peer_login
, "PASS") == 0 ||
1505 strcmp(orig_request
->peer_login
, "PROXYPASS") == 0)) {
1507 snprintf(loginbuf
, sizeof(loginbuf
), SQUIDSTRINGPH
":" SQUIDSTRINGPH
,
1508 SQUIDSTRINGPRINT(orig_request
->extacl_user
),
1509 SQUIDSTRINGPRINT(orig_request
->extacl_passwd
));
1510 httpHeaderPutStrf(hdr_out
, header
, "Basic %s",
1511 base64_encode(loginbuf
));
1515 /* Kerberos login to peer */
1516 #if HAVE_KRB5 && HAVE_GSSAPI
1517 if (strncmp(orig_request
->peer_login
, "NEGOTIATE",strlen("NEGOTIATE")) == 0) {
1519 char *PrincipalName
=NULL
,*p
;
1520 if ((p
=strchr(orig_request
->peer_login
,':')) != NULL
) {
1523 Token
= peer_proxy_negotiate_auth(PrincipalName
,request
->peer_host
);
1525 httpHeaderPutStrf(hdr_out
, HDR_PROXY_AUTHORIZATION
, "Negotiate %s",Token
);
1529 #endif /* HAVE_KRB5 && HAVE_GSSAPI */
1531 httpHeaderPutStrf(hdr_out
, header
, "Basic %s",
1532 base64_encode(orig_request
->peer_login
));
1537 * build request headers and append them to a given MemBuf
1538 * used by buildRequestPrefix()
1539 * note: initialised the HttpHeader, the caller is responsible for Clean()-ing
1542 HttpStateData::httpBuildRequestHeader(HttpRequest
* request
,
1543 HttpRequest
* orig_request
,
1545 HttpHeader
* hdr_out
,
1546 http_state_flags flags
)
1548 /* building buffer for complex strings */
1549 #define BBUF_SZ (MAX_URL+32)
1550 LOCAL_ARRAY(char, bbuf
, BBUF_SZ
);
1551 LOCAL_ARRAY(char, ntoabuf
, MAX_IPSTRLEN
);
1552 const HttpHeader
*hdr_in
= &orig_request
->header
;
1553 const HttpHeaderEntry
*e
= NULL
;
1554 HttpHeaderPos pos
= HttpHeaderInitPos
;
1555 assert (hdr_out
->owner
== hoRequest
);
1557 /* append our IMS header */
1558 if (request
->lastmod
> -1)
1559 hdr_out
->putTime(HDR_IF_MODIFIED_SINCE
, request
->lastmod
);
1561 bool we_do_ranges
= decideIfWeDoRanges (orig_request
);
1563 String
strConnection (hdr_in
->getList(HDR_CONNECTION
));
1565 while ((e
= hdr_in
->getEntry(&pos
)))
1566 copyOneHeaderFromClientsideRequestToUpstreamRequest(e
, strConnection
, request
, orig_request
, hdr_out
, we_do_ranges
, flags
);
1568 /* Abstraction break: We should interpret multipart/byterange responses
1569 * into offset-length data, and this works around our inability to do so.
1571 if (!we_do_ranges
&& orig_request
->multipartRangeRequest()) {
1572 /* don't cache the result */
1573 orig_request
->flags
.cachable
= 0;
1574 /* pretend it's not a range request */
1575 delete orig_request
->range
;
1576 orig_request
->range
= NULL
;
1577 orig_request
->flags
.range
= 0;
1581 if (Config
.onoff
.via
) {
1583 strVia
= hdr_in
->getList(HDR_VIA
);
1584 snprintf(bbuf
, BBUF_SZ
, "%d.%d %s",
1585 orig_request
->http_ver
.major
,
1586 orig_request
->http_ver
.minor
, ThisCache
);
1587 strListAdd(&strVia
, bbuf
, ',');
1588 hdr_out
->putStr(HDR_VIA
, strVia
.termedBuf());
1593 if (orig_request
->flags
.accelerated
) {
1594 /* Append Surrogate-Capabilities */
1595 String
strSurrogate (hdr_in
->getList(HDR_SURROGATE_CAPABILITY
));
1596 snprintf(bbuf
, BBUF_SZ
, "%s=\"Surrogate/1.0 ESI/1.0\"",
1597 Config
.Accel
.surrogate_id
);
1598 strListAdd(&strSurrogate
, bbuf
, ',');
1599 hdr_out
->putStr(HDR_SURROGATE_CAPABILITY
, strSurrogate
.termedBuf());
1603 /** \pre Handle X-Forwarded-For */
1604 if (strcmp(opt_forwarded_for
, "delete") != 0) {
1606 String strFwd
= hdr_in
->getList(HDR_X_FORWARDED_FOR
);
1608 if (strFwd
.size() > 65536/2) {
1609 // There is probably a forwarding loop with Via detection disabled.
1610 // If we do nothing, String will assert on overflow soon.
1611 // TODO: Terminate all transactions with huge XFF?
1614 static int warnedCount
= 0;
1615 if (warnedCount
++ < 100) {
1616 const char *url
= entry
? entry
->url() : urlCanonical(orig_request
);
1617 debugs(11, 1, "Warning: likely forwarding loop with " << url
);
1621 if (strcmp(opt_forwarded_for
, "on") == 0) {
1622 /** If set to ON - append client IP or 'unknown'. */
1623 if ( orig_request
->client_addr
.IsNoAddr() )
1624 strListAdd(&strFwd
, "unknown", ',');
1626 strListAdd(&strFwd
, orig_request
->client_addr
.NtoA(ntoabuf
, MAX_IPSTRLEN
), ',');
1627 } else if (strcmp(opt_forwarded_for
, "off") == 0) {
1628 /** If set to OFF - append 'unknown'. */
1629 strListAdd(&strFwd
, "unknown", ',');
1630 } else if (strcmp(opt_forwarded_for
, "transparent") == 0) {
1631 /** If set to TRANSPARENT - pass through unchanged. */
1632 } else if (strcmp(opt_forwarded_for
, "truncate") == 0) {
1633 /** If set to TRUNCATE - drop existing list and replace with client IP or 'unknown'. */
1634 if ( orig_request
->client_addr
.IsNoAddr() )
1637 strFwd
= orig_request
->client_addr
.NtoA(ntoabuf
, MAX_IPSTRLEN
);
1639 if (strFwd
.size() > 0)
1640 hdr_out
->putStr(HDR_X_FORWARDED_FOR
, strFwd
.termedBuf());
1642 /** If set to DELETE - do not copy through. */
1644 /* append Host if not there already */
1645 if (!hdr_out
->has(HDR_HOST
)) {
1646 if (orig_request
->peer_domain
) {
1647 hdr_out
->putStr(HDR_HOST
, orig_request
->peer_domain
);
1648 } else if (orig_request
->port
== urlDefaultPort(orig_request
->protocol
)) {
1649 /* use port# only if not default */
1650 hdr_out
->putStr(HDR_HOST
, orig_request
->GetHost());
1652 httpHeaderPutStrf(hdr_out
, HDR_HOST
, "%s:%d",
1653 orig_request
->GetHost(),
1654 (int) orig_request
->port
);
1658 /* append Authorization if known in URL, not in header and going direct */
1659 if (!hdr_out
->has(HDR_AUTHORIZATION
)) {
1660 if (!request
->flags
.proxying
&& *request
->login
) {
1661 httpHeaderPutStrf(hdr_out
, HDR_AUTHORIZATION
, "Basic %s",
1662 base64_encode(request
->login
));
1666 /* Fixup (Proxy-)Authorization special cases. Plain relaying dealt with above */
1667 httpFixupAuthentication(request
, orig_request
, hdr_in
, hdr_out
, flags
);
1669 /* append Cache-Control, add max-age if not there already */
1671 HttpHdrCc
*cc
= hdr_in
->getCc();
1674 cc
= httpHdrCcCreate();
1676 #if 0 /* see bug 2330 */
1677 /* Set no-cache if determined needed but not found */
1678 if (orig_request
->flags
.nocache
)
1679 EBIT_SET(cc
->mask
, CC_NO_CACHE
);
1682 /* Add max-age only without no-cache */
1683 if (!EBIT_TEST(cc
->mask
, CC_MAX_AGE
) && !EBIT_TEST(cc
->mask
, CC_NO_CACHE
)) {
1685 entry
? entry
->url() : urlCanonical(orig_request
);
1686 httpHdrCcSetMaxAge(cc
, getMaxAge(url
));
1688 if (request
->urlpath
.size())
1689 assert(strstr(url
, request
->urlpath
.termedBuf()));
1692 /* Enforce sibling relations */
1693 if (flags
.only_if_cached
)
1694 EBIT_SET(cc
->mask
, CC_ONLY_IF_CACHED
);
1698 httpHdrCcDestroy(cc
);
1701 /* maybe append Connection: keep-alive */
1702 if (flags
.keepalive
) {
1703 if (flags
.proxying
) {
1704 hdr_out
->putStr(HDR_PROXY_CONNECTION
, "keep-alive");
1706 hdr_out
->putStr(HDR_CONNECTION
, "keep-alive");
1710 /* append Front-End-Https */
1711 if (flags
.front_end_https
) {
1712 if (flags
.front_end_https
== 1 || request
->protocol
== PROTO_HTTPS
)
1713 hdr_out
->putStr(HDR_FRONT_END_HTTPS
, "On");
1716 /* Now mangle the headers. */
1717 if (Config2
.onoff
.mangle_request_headers
)
1718 httpHdrMangleList(hdr_out
, request
, ROR_REQUEST
);
1720 strConnection
.clean();
1724 * Decides whether a particular header may be cloned from the received Clients request
1725 * to our outgoing fetch request.
1728 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
)
1730 debugs(11, 5, "httpBuildRequestHeader: " << e
->name
<< ": " << e
->value
);
1734 /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid should not pass on. */
1736 case HDR_PROXY_AUTHORIZATION
:
1737 /** \par Proxy-Authorization:
1738 * Only pass on proxy authentication to peers for which
1739 * authentication forwarding is explicitly enabled
1741 if (!flags
.originpeer
&& flags
.proxying
&& orig_request
->peer_login
&&
1742 (strcmp(orig_request
->peer_login
, "PASS") == 0 ||
1743 strcmp(orig_request
->peer_login
, "PROXYPASS") == 0 ||
1744 strcmp(orig_request
->peer_login
, "PASSTHRU") == 0)) {
1745 hdr_out
->addEntry(e
->clone());
1749 /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid does not pass on. */
1751 case HDR_CONNECTION
: /** \par Connection: */
1752 case HDR_TE
: /** \par TE: */
1753 case HDR_KEEP_ALIVE
: /** \par Keep-Alive: */
1754 case HDR_PROXY_AUTHENTICATE
: /** \par Proxy-Authenticate: */
1755 case HDR_TRAILERS
: /** \par Trailers: */
1756 case HDR_UPGRADE
: /** \par Upgrade: */
1757 case HDR_TRANSFER_ENCODING
: /** \par Transfer-Encoding: */
1761 /** \par OTHER headers I haven't bothered to track down yet. */
1763 case HDR_AUTHORIZATION
:
1764 /** \par WWW-Authorization:
1765 * Pass on WWW authentication */
1767 if (!flags
.originpeer
) {
1768 hdr_out
->addEntry(e
->clone());
1770 /** \note In accelerators, only forward authentication if enabled
1771 * (see also httpFixupAuthentication for special cases)
1773 if (orig_request
->peer_login
&&
1774 (strcmp(orig_request
->peer_login
, "PASS") == 0 ||
1775 strcmp(orig_request
->peer_login
, "PASSTHRU") == 0 ||
1776 strcmp(orig_request
->peer_login
, "PROXYPASS") == 0)) {
1777 hdr_out
->addEntry(e
->clone());
1785 * Normally Squid rewrites the Host: header.
1786 * However, there is one case when we don't: If the URL
1787 * went through our redirector and the admin configured
1788 * 'redir_rewrites_host' to be off.
1790 if (orig_request
->peer_domain
)
1791 hdr_out
->putStr(HDR_HOST
, orig_request
->peer_domain
);
1792 else if (request
->flags
.redirected
&& !Config
.onoff
.redir_rewrites_host
)
1793 hdr_out
->addEntry(e
->clone());
1795 /* use port# only if not default */
1797 if (orig_request
->port
== urlDefaultPort(orig_request
->protocol
)) {
1798 hdr_out
->putStr(HDR_HOST
, orig_request
->GetHost());
1800 httpHeaderPutStrf(hdr_out
, HDR_HOST
, "%s:%d",
1801 orig_request
->GetHost(),
1802 (int) orig_request
->port
);
1808 case HDR_IF_MODIFIED_SINCE
:
1809 /** \par If-Modified-Since:
1810 * append unless we added our own;
1811 * \note at most one client's ims header can pass through */
1813 if (!hdr_out
->has(HDR_IF_MODIFIED_SINCE
))
1814 hdr_out
->addEntry(e
->clone());
1818 case HDR_MAX_FORWARDS
:
1819 /** \par Max-Forwards:
1820 * pass only on TRACE or OPTIONS requests */
1821 if (orig_request
->method
== METHOD_TRACE
|| orig_request
->method
== METHOD_OPTIONS
) {
1822 const int64_t hops
= e
->getInt64();
1825 hdr_out
->putInt64(HDR_MAX_FORWARDS
, hops
- 1);
1832 * If Via is disabled then forward any received header as-is.
1833 * Otherwise leave for explicit updated addition later. */
1835 if (!Config
.onoff
.via
)
1836 hdr_out
->addEntry(e
->clone());
1844 case HDR_REQUEST_RANGE
:
1845 /** \par Range:, If-Range:, Request-Range:
1846 * Only pass if we accept ranges */
1848 hdr_out
->addEntry(e
->clone());
1852 case HDR_PROXY_CONNECTION
:
1854 case HDR_X_FORWARDED_FOR
:
1856 case HDR_CACHE_CONTROL
:
1857 /** \par Proxy-Connaction:, X-Forwarded-For:, Cache-Control:
1858 * handled specially by Squid, so leave off for now.
1859 * append these after the loop if needed */
1862 case HDR_FRONT_END_HTTPS
:
1863 /** \par Front-End-Https:
1864 * Pass thru only if peer is configured with front-end-https */
1865 if (!flags
.front_end_https
)
1866 hdr_out
->addEntry(e
->clone());
1872 * pass on all other header fields
1873 * which are NOT listed by the special Connection: header. */
1875 if (strConnection
.size()>0 && strListIsMember(&strConnection
, e
->name
.termedBuf(), ',')) {
1876 debugs(11, 2, "'" << e
->name
<< "' header cropped by Connection: definition");
1880 hdr_out
->addEntry(e
->clone());
1885 HttpStateData::decideIfWeDoRanges (HttpRequest
* orig_request
)
1888 /* decide if we want to do Ranges ourselves
1889 * and fetch the whole object now)
1890 * We want to handle Ranges ourselves iff
1891 * - we can actually parse client Range specs
1892 * - the specs are expected to be simple enough (e.g. no out-of-order ranges)
1893 * - reply will be cachable
1894 * (If the reply will be uncachable we have to throw it away after
1895 * serving this request, so it is better to forward ranges to
1896 * the server and fetch only the requested content)
1899 if (NULL
== orig_request
->range
|| !orig_request
->flags
.cachable
1900 || orig_request
->range
->offsetLimitExceeded() || orig_request
->flags
.connection_auth
)
1903 debugs(11, 8, "decideIfWeDoRanges: range specs: " <<
1904 orig_request
->range
<< ", cachable: " <<
1905 orig_request
->flags
.cachable
<< "; we_do_ranges: " << result
);
1910 /* build request prefix and append it to a given MemBuf;
1911 * return the length of the prefix */
1913 HttpStateData::buildRequestPrefix(HttpRequest
* request
,
1914 HttpRequest
* orig_request
,
1917 http_state_flags flags
)
1919 const int offset
= mb
->size
;
1920 HttpVersion
httpver(1, 0);
1921 mb
->Printf("%s %s HTTP/%d.%d\r\n",
1922 RequestMethodStr(request
->method
),
1923 request
->urlpath
.size() ? request
->urlpath
.termedBuf() : "/",
1924 httpver
.major
,httpver
.minor
);
1925 /* build and pack headers */
1927 HttpHeader
hdr(hoRequest
);
1929 httpBuildRequestHeader(request
, orig_request
, entry
, &hdr
, flags
);
1931 if (request
->flags
.pinned
&& request
->flags
.connection_auth
)
1932 request
->flags
.auth_sent
= 1;
1933 else if (hdr
.has(HDR_AUTHORIZATION
))
1934 request
->flags
.auth_sent
= 1;
1936 packerToMemInit(&p
, mb
);
1941 /* append header terminator */
1942 mb
->append(crlf
, 2);
1943 return mb
->size
- offset
;
1946 /* This will be called when connect completes. Write request. */
1948 HttpStateData::sendRequest()
1952 debugs(11, 5, "httpSendRequest: FD " << fd
<< ", request " << request
<< ", this " << this << ".");
1953 typedef CommCbMemFunT
<HttpStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1954 AsyncCall::Pointer timeoutCall
= asyncCall(11, 5, "HttpStateData::httpTimeout",
1955 TimeoutDialer(this,&HttpStateData::httpTimeout
));
1956 commSetTimeout(fd
, Config
.Timeout
.lifetime
, timeoutCall
);
1957 flags
.do_next_read
= 1;
1958 maybeReadVirginBody();
1960 if (orig_request
->body_pipe
!= NULL
) {
1961 if (!startRequestBodyFlow()) // register to receive body data
1963 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
1964 Dialer
dialer(this, &HttpStateData::sentRequestBody
);
1965 requestSender
= asyncCall(11,5, "HttpStateData::sentRequestBody", dialer
);
1967 assert(!requestBodySource
);
1968 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
1969 Dialer
dialer(this, &HttpStateData::sendComplete
);
1970 requestSender
= asyncCall(11,5, "HttpStateData::SendComplete", dialer
);
1973 if (_peer
!= NULL
) {
1974 if (_peer
->options
.originserver
) {
1976 flags
.originpeer
= 1;
1979 flags
.originpeer
= 0;
1983 flags
.originpeer
= 0;
1987 * Is keep-alive okay for all request methods?
1989 if (orig_request
->flags
.must_keepalive
)
1990 flags
.keepalive
= 1;
1991 else if (!Config
.onoff
.server_pconns
)
1992 flags
.keepalive
= 0;
1993 else if (_peer
== NULL
)
1994 flags
.keepalive
= 1;
1995 else if (_peer
->stats
.n_keepalives_sent
< 10)
1996 flags
.keepalive
= 1;
1997 else if ((double) _peer
->stats
.n_keepalives_recv
/
1998 (double) _peer
->stats
.n_keepalives_sent
> 0.50)
1999 flags
.keepalive
= 1;
2002 if (neighborType(_peer
, request
) == PEER_SIBLING
&&
2003 !_peer
->options
.allow_miss
)
2004 flags
.only_if_cached
= 1;
2006 flags
.front_end_https
= _peer
->front_end_https
;
2010 request
->peer_host
=_peer
?_peer
->host
:NULL
;
2011 buildRequestPrefix(request
, orig_request
, entry
, &mb
, flags
);
2012 debugs(11, 6, "httpSendRequest: FD " << fd
<< ":\n" << mb
.buf
);
2013 comm_write_mbuf(fd
, &mb
, requestSender
);
2019 httpStart(FwdState
*fwd
)
2021 debugs(11, 3, "httpStart: \"" << RequestMethodStr(fwd
->request
->method
) << " " << fwd
->entry
->url() << "\"" );
2022 HttpStateData
*httpState
= new HttpStateData(fwd
);
2024 if (!httpState
->sendRequest()) {
2025 debugs(11, 3, "httpStart: aborted");
2030 statCounter
.server
.all
.requests
++;
2031 statCounter
.server
.http
.requests
++;
2034 * We used to set the read timeout here, but not any more.
2035 * Now its set in httpSendComplete() after the full request,
2036 * including request body, has been written to the server.
2041 HttpStateData::doneSendingRequestBody()
2043 debugs(11,5, HERE
<< "doneSendingRequestBody: FD " << fd
);
2046 if (Config
.accessList
.brokenPosts
) {
2047 ACLFilledChecklist
ch(Config
.accessList
.brokenPosts
, request
, NULL
);
2048 if (!ch
.fastCheck()) {
2049 debugs(11, 5, "doneSendingRequestBody: didn't match brokenPosts");
2050 CommIoCbParams
io(NULL
);
2055 debugs(11, 2, "doneSendingRequestBody: matched brokenPosts");
2056 typedef CommCbMemFunT
<HttpStateData
, CommIoCbParams
> Dialer
;
2057 Dialer
dialer(this, &HttpStateData::sendComplete
);
2058 AsyncCall::Pointer call
= asyncCall(11,5, "HttpStateData::SendComplete", dialer
);
2059 comm_write(fd
, "\r\n", 2, call
);
2063 debugs(11, 5, "doneSendingRequestBody: No brokenPosts list");
2064 #endif /* HTTP_VIOLATIONS */
2066 CommIoCbParams
io(NULL
);
2072 // more origin request body data is available
2074 HttpStateData::handleMoreRequestBodyAvailable()
2076 if (eof
|| fd
< 0) {
2077 // XXX: we should check this condition in other callbacks then!
2078 // TODO: Check whether this can actually happen: We should unsubscribe
2079 // as a body consumer when the above condition(s) are detected.
2080 debugs(11, 1, HERE
<< "Transaction aborted while reading HTTP body");
2084 assert(requestBodySource
!= NULL
);
2086 if (requestBodySource
->buf().hasContent()) {
2087 // XXX: why does not this trigger a debug message on every request?
2089 if (flags
.headers_parsed
&& !flags
.abuse_detected
) {
2090 flags
.abuse_detected
= 1;
2091 debugs(11, 1, "http handleMoreRequestBodyAvailable: Likely proxy abuse detected '" << orig_request
->client_addr
<< "' -> '" << entry
->url() << "'" );
2093 if (virginReply()->sline
.status
== HTTP_INVALID_HEADER
) {
2100 HttpStateData::handleMoreRequestBodyAvailable();
2103 // premature end of the request body
2105 HttpStateData::handleRequestBodyProducerAborted()
2107 ServerStateData::handleRequestBodyProducerAborted();
2108 // XXX: SendComplete(COMM_ERR_CLOSING) does little. Is it enough?
2109 CommIoCbParams
io(NULL
);
2111 io
.flag
=COMM_ERR_CLOSING
;
2115 // called when we wrote request headers(!) or a part of the body
2117 HttpStateData::sentRequestBody(const CommIoCbParams
&io
)
2120 kb_incr(&statCounter
.server
.http
.kbytes_out
, io
.size
);
2122 ServerStateData::sentRequestBody(io
);
2125 // Quickly abort the transaction
2126 // TODO: destruction should be sufficient as the destructor should cleanup,
2127 // including canceling close handlers
2129 HttpStateData::abortTransaction(const char *reason
)
2131 debugs(11,5, HERE
<< "aborting transaction for " << reason
<<
2132 "; FD " << fd
<< ", this " << this);
2139 fwd
->handleUnregisteredServerEnd();
2140 deleteThis("HttpStateData::abortTransaction");
2145 httpBuildVersion(HttpVersion
* version
, unsigned int major
, unsigned int minor
)
2147 version
->major
= major
;
2148 version
->minor
= minor
;
2153 HttpStateData::originalRequest()
2155 return orig_request
;