2 * DEBUG: section 12 Internet Cache Protocol (ICP)
3 * AUTHOR: Duane Wessels
5 * SQUID Web Proxy Cache http://www.squid-cache.org/
6 * ----------------------------------------------------------
8 * Squid is the result of efforts by numerous individuals from
9 * the Internet community; see the CONTRIBUTORS file for full
10 * details. Many organizations have provided support for Squid's
11 * development; see the SPONSORS file for full details. Squid is
12 * Copyrighted (C) 2001 by the Regents of the University of
13 * California; see the COPYRIGHT file for full details. Squid
14 * incorporates software developed and/or copyrighted by other
15 * sources; see the CREDITS file for full details.
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, write to the Free Software
29 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
34 \defgroup ServerProtocolICPInternal2 ICPv2 Internals
35 \ingroup ServerProtocolICPAPI
42 #include "HttpRequest.h"
43 #include "acl/FilledChecklist.h"
45 #include "AccessLogEntry.h"
47 #include "SquidTime.h"
49 #include "icmp/net_db.h"
50 #include "ip/IpAddress.h"
51 #include "ipc/StartListening.h"
54 /// dials icpIncomingConnectionOpened call
55 class IcpListeningStartedDialer
: public CallDialer
,
56 public Ipc::StartListeningCb
59 typedef void (*Handler
)(int fd
, int errNo
, IpAddress
& addr
);
60 IcpListeningStartedDialer(Handler aHandler
, IpAddress
& anAddr
):
61 handler(aHandler
), addr(anAddr
) {}
63 virtual void print(std::ostream
&os
) const { startPrint(os
) <<
64 ", address=" << addr
<< ')'; }
66 virtual bool canDial(AsyncCall
&) const { return true; }
67 virtual void dial(AsyncCall
&) { (handler
)(fd
, errNo
, addr
); }
74 static void icpIncomingConnectionOpened(int fd
, int errNo
, IpAddress
& addr
);
76 /// \ingroup ServerProtocolICPInternal2
77 static void icpLogIcp(const IpAddress
&, log_type
, int, const char *, int);
79 /// \ingroup ServerProtocolICPInternal2
80 static void icpHandleIcpV2(int, IpAddress
&, char *, int);
82 /// \ingroup ServerProtocolICPInternal2
83 static void icpCount(void *, int, size_t, int);
86 \ingroup ServerProtocolICPInternal2
87 * IcpQueueHead is global so comm_incoming() knows whether or not
88 * to call icpUdpSendQueue.
90 static icpUdpData
*IcpQueueHead
= NULL
;
91 /// \ingroup ServerProtocolICPInternal2
92 static icpUdpData
*IcpQueueTail
= NULL
;
94 /// \ingroup ServerProtocolICPInternal2
95 IpAddress theOutICPAddr
;
98 _icp_common_t::_icp_common_t() : opcode(ICP_INVALID
), version(0), length(0), reqnum(0), flags(0), pad(0), shostid(0)
101 _icp_common_t::_icp_common_t(char *buf
, unsigned int len
)
103 if (len
< sizeof(_icp_common_t
)) {
104 /* mark as invalid */
109 xmemcpy(this, buf
, sizeof(icp_common_t
));
111 * Convert network order sensitive fields
113 length
= ntohs(length
);
114 reqnum
= ntohl(reqnum
);
115 flags
= ntohl(flags
);
120 _icp_common_t::getOpCode() const
122 if (opcode
> (char)ICP_END
)
125 return (icp_opcode
)opcode
;
130 ICPState::ICPState(icp_common_t
&aHeader
, HttpRequest
*aRequest
):
132 request(HTTPMSGLOCK(aRequest
)),
137 ICPState::~ICPState()
140 HTTPMSGUNLOCK(request
);
148 /// \ingroup ServerProtocolICPInternal2
149 class ICP2State
: public ICPState
, public StoreClient
153 ICP2State(icp_common_t
& aHeader
, HttpRequest
*aRequest
):
154 ICPState(aHeader
, aRequest
),rtt(0),src_rtt(0),flags(0) {}
157 void created(StoreEntry
* newEntry
);
164 ICP2State::~ICP2State()
168 ICP2State::created(StoreEntry
*newEntry
)
170 StoreEntry
*entry
= newEntry
->isNull () ? NULL
: newEntry
;
171 debugs(12, 5, "icpHandleIcpV2: OPCODE " << icp_opcode_str
[header
.opcode
]);
172 icp_opcode codeToSend
;
174 if (icpCheckUdpHit(entry
, request
)) {
175 codeToSend
= ICP_HIT
;
178 if (Config
.onoff
.test_reachability
&& rtt
== 0) {
179 if ((rtt
= netdbHostRtt(request
->GetHost())) == 0)
180 netdbPingSite(request
->GetHost());
182 #endif /* USE_ICMP */
184 if (icpGetCommonOpcode() != ICP_ERR
)
185 codeToSend
= icpGetCommonOpcode();
186 else if (Config
.onoff
.test_reachability
&& rtt
== 0)
187 codeToSend
= ICP_MISS_NOFETCH
;
189 codeToSend
= ICP_MISS
;
192 icpCreateAndSend(codeToSend
, flags
, url
, header
.reqnum
, src_rtt
, fd
, from
);
198 /// \ingroup ServerProtocolICPInternal2
200 icpLogIcp(const IpAddress
&caddr
, log_type logcode
, int len
, const char *url
, int delay
)
204 if (LOG_TAG_NONE
== logcode
)
207 if (LOG_ICP_QUERY
== logcode
)
210 clientdbUpdate(caddr
, logcode
, PROTO_ICP
, len
);
212 if (!Config
.onoff
.log_udp
)
215 al
.icp
.opcode
= ICP_QUERY
;
219 al
.cache
.caddr
= caddr
;
221 al
.cache
.replySize
= len
;
223 al
.cache
.code
= logcode
;
225 al
.cache
.msec
= delay
;
227 accessLogLog(&al
, NULL
);
230 /// \ingroup ServerProtocolICPInternal2
232 icpUdpSendQueue(int fd
, void *unused
)
238 while ((q
= IcpQueueHead
) != NULL
) {
239 delay
= tvSubUsec(q
->queue_time
, current_time
);
240 /* increment delay to prevent looping */
241 x
= icpUdpSend(fd
, q
->address
, (icp_common_t
*) q
->msg
, q
->logcode
, ++delay
);
242 IcpQueueHead
= q
->next
;
251 _icp_common_t::createMessage(
259 icp_common_t
*headerp
= NULL
;
260 char *urloffset
= NULL
;
262 buf_len
= sizeof(icp_common_t
) + strlen(url
) + 1;
264 if (opcode
== ICP_QUERY
)
265 buf_len
+= sizeof(u_int32_t
);
267 buf
= (char *) xcalloc(buf_len
, 1);
269 headerp
= (icp_common_t
*) (void *) buf
;
271 headerp
->opcode
= (char) opcode
;
273 headerp
->version
= ICP_VERSION_CURRENT
;
275 headerp
->length
= (u_int16_t
) htons(buf_len
);
277 headerp
->reqnum
= htonl(reqnum
);
279 headerp
->flags
= htonl(flags
);
281 headerp
->pad
= htonl(pad
);
283 theOutICPAddr
.GetInAddr( *((struct in_addr
*)&headerp
->shostid
) );
285 urloffset
= buf
+ sizeof(icp_common_t
);
287 if (opcode
== ICP_QUERY
)
288 urloffset
+= sizeof(u_int32_t
);
290 xmemcpy(urloffset
, url
, strlen(url
));
292 return (icp_common_t
*)buf
;
305 len
= (int) ntohs(msg
->length
);
306 debugs(12, 5, "icpUdpSend: FD " << fd
<< " sending " <<
307 icp_opcode_str
[msg
->opcode
] << ", " << len
<< " bytes to " << to
);
309 x
= comm_udp_sendto(fd
, to
, msg
, len
);
312 /* successfully written */
313 icpLogIcp(to
, logcode
, len
, (char *) (msg
+ 1), delay
);
314 icpCount(msg
, SENT
, (size_t) len
, delay
);
316 } else if (0 == delay
) {
317 /* send failed, but queue it */
318 queue
= (icpUdpData
*) xcalloc(1, sizeof(icpUdpData
));
321 queue
->len
= (int) ntohs(msg
->length
);
322 queue
->queue_time
= current_time
;
323 queue
->logcode
= logcode
;
325 if (IcpQueueHead
== NULL
) {
326 IcpQueueHead
= queue
;
327 IcpQueueTail
= queue
;
328 } else if (IcpQueueTail
== IcpQueueHead
) {
329 IcpQueueTail
= queue
;
330 IcpQueueHead
->next
= queue
;
332 IcpQueueTail
->next
= queue
;
333 IcpQueueTail
= queue
;
336 commSetSelect(fd
, COMM_SELECT_WRITE
, icpUdpSendQueue
, NULL
, 0);
337 statCounter
.icp
.replies_queued
++;
340 statCounter
.icp
.replies_dropped
++;
347 icpCheckUdpHit(StoreEntry
* e
, HttpRequest
* request
)
352 if (!e
->validToSend())
355 if (Config
.onoff
.icp_hit_stale
)
358 if (refreshCheckICP(e
, request
))
365 * This routine selects an ICP opcode for ICP misses.
367 \retval ICP_ERR no opcode selected here
368 \retval ICP_MISS_NOFETCH store is rebuilding, no fetch is possible yet
373 /* if store is rebuilding, return a UDP_MISS_NOFETCH */
375 if ((StoreController::store_dirs_rebuilding
&& opt_reload_hit_only
) ||
376 hit_only_mode_until
> squid_curtime
) {
377 return ICP_MISS_NOFETCH
;
384 icpLogFromICPCode(icp_opcode opcode
)
386 if (opcode
== ICP_ERR
)
387 return LOG_UDP_INVALID
;
389 if (opcode
== ICP_DENIED
)
390 return LOG_UDP_DENIED
;
392 if (opcode
== ICP_HIT
)
395 if (opcode
== ICP_MISS
)
398 if (opcode
== ICP_MISS_NOFETCH
)
399 return LOG_UDP_MISS_NOFETCH
;
401 fatal("expected ICP opcode\n");
403 return LOG_UDP_INVALID
;
407 icpCreateAndSend(icp_opcode opcode
, int flags
, char const *url
, int reqnum
, int pad
, int fd
, const IpAddress
&from
)
409 icp_common_t
*reply
= _icp_common_t::createMessage(opcode
, flags
, url
, reqnum
, pad
);
410 icpUdpSend(fd
, from
, reply
, icpLogFromICPCode(opcode
), 0);
414 icpDenyAccess(IpAddress
&from
, char *url
, int reqnum
, int fd
)
416 debugs(12, 2, "icpDenyAccess: Access Denied for " << from
<< " by " << AclMatchedName
<< ".");
418 if (clientdbCutoffDenied(from
)) {
420 * count this DENIED query in the clientdb, even though
421 * we're not sending an ICP reply...
423 clientdbUpdate(from
, LOG_UDP_DENIED
, PROTO_ICP
, 0);
425 icpCreateAndSend(ICP_DENIED
, 0, url
, reqnum
, 0, fd
, from
);
430 icpAccessAllowed(IpAddress
&from
, HttpRequest
* icp_request
)
432 /* absent an explicit allow, we deny all */
433 if (!Config
.accessList
.icp
)
436 ACLFilledChecklist
checklist(Config
.accessList
.icp
, icp_request
, NULL
);
437 checklist
.src_addr
= from
;
438 checklist
.my_addr
.SetNoAddr();
439 int result
= checklist
.fastCheck();
444 icpGetUrlToSend(char *url
)
446 if (strpbrk(url
, w_space
))
447 return rfc1738_escape(url
);
453 icpGetRequest(char *url
, int reqnum
, int fd
, IpAddress
&from
)
455 if (strpbrk(url
, w_space
)) {
456 url
= rfc1738_escape(url
);
457 icpCreateAndSend(ICP_ERR
, 0, rfc1738_escape(url
), reqnum
, 0, fd
, from
);
463 if ((result
= HttpRequest::CreateFromUrl(url
)) == NULL
)
464 icpCreateAndSend(ICP_ERR
, 0, url
, reqnum
, 0, fd
, from
);
471 doV2Query(int fd
, IpAddress
&from
, char *buf
, icp_common_t header
)
476 /* We have a valid packet */
477 char *url
= buf
+ sizeof(icp_common_t
) + sizeof(u_int32_t
);
478 HttpRequest
*icp_request
= icpGetRequest(url
, header
.reqnum
, fd
, from
);
483 HTTPMSGLOCK(icp_request
);
485 if (!icpAccessAllowed(from
, icp_request
)) {
486 icpDenyAccess(from
, url
, header
.reqnum
, fd
);
487 HTTPMSGUNLOCK(icp_request
);
491 if (header
.flags
& ICP_FLAG_SRC_RTT
) {
492 rtt
= netdbHostRtt(icp_request
->GetHost());
493 int hops
= netdbHostHops(icp_request
->GetHost());
494 src_rtt
= ((hops
& 0xFFFF) << 16) | (rtt
& 0xFFFF);
497 flags
|= ICP_FLAG_SRC_RTT
;
499 #endif /* USE_ICMP */
501 /* The peer is allowed to use this cache */
502 ICP2State
*state
= new ICP2State (header
, icp_request
);
508 state
->url
= xstrdup (url
);
510 state
->flags
= flags
;
514 state
->src_rtt
= src_rtt
;
516 StoreEntry::getPublic (state
, url
, METHOD_GET
);
518 HTTPMSGUNLOCK(icp_request
);
522 _icp_common_t::handleReply(char *buf
, IpAddress
&from
)
524 if (neighbors_do_private_keys
&& reqnum
== 0) {
525 debugs(12, 0, "icpHandleIcpV2: Neighbor " << from
<< " returned reqnum = 0");
526 debugs(12, 0, "icpHandleIcpV2: Disabling use of private keys");
527 neighbors_do_private_keys
= 0;
530 char *url
= buf
+ sizeof(icp_common_t
);
531 debugs(12, 3, "icpHandleIcpV2: " << icp_opcode_str
[opcode
] << " from " << from
<< " for '" << url
<< "'");
533 const cache_key
*key
= icpGetCacheKey(url
, (int) reqnum
);
534 /* call neighborsUdpAck even if ping_status != PING_WAITING */
535 neighborsUdpAck(key
, this, from
);
539 icpHandleIcpV2(int fd
, IpAddress
&from
, char *buf
, int len
)
542 debugs(12, 3, "icpHandleIcpV2: ICP message is too small");
546 icp_common_t
header(buf
, len
);
548 * Length field should match the number of bytes read
551 if (len
!= header
.length
) {
552 debugs(12, 3, "icpHandleIcpV2: ICP message is too small");
556 switch (header
.opcode
) {
559 /* We have a valid packet */
560 doV2Query(fd
, from
, buf
, header
);
571 case ICP_MISS_NOFETCH
:
572 header
.handleReply(buf
, from
);
581 debugs(12, 0, "icpHandleIcpV2: UNKNOWN OPCODE: " << header
.opcode
<< " from " << from
);
589 icpPktDump(icp_common_t
* pkt
)
594 debugs(12, 9, "opcode: " << std::setw(3) << pkt
->opcode
<< " " << icp_opcode_str
[pkt
->opcode
]);
595 debugs(12, 9, "version: "<< std::left
<< std::setw(8) << pkt
->version
);
596 debugs(12, 9, "length: "<< std::left
<< std::setw(8) << ntohs(pkt
->length
));
597 debugs(12, 9, "reqnum: "<< std::left
<< std::setw(8) << ntohl(pkt
->reqnum
));
598 debugs(12, 9, "flags: "<< std::left
<< std::hex
<< std::setw(8) << ntohl(pkt
->flags
));
599 a
= (struct in_addr
)pkt
->shostid
;
600 debugs(12, 9, "shostid: " << a
);
601 debugs(12, 9, "payload: " << (char *) pkt
+ sizeof(icp_common_t
));
607 icpHandleUdp(int sock
, void *data
)
609 int *N
= &incoming_sockets_accepted
;
612 LOCAL_ARRAY(char, buf
, SQUID_UDP_SO_RCVBUF
);
615 int max
= INCOMING_ICP_MAX
;
616 commSetSelect(sock
, COMM_SELECT_READ
, icpHandleUdp
, NULL
, 0);
619 len
= comm_udp_recvfrom(sock
,
621 SQUID_UDP_SO_RCVBUF
- 1,
629 if (ignoreErrno(errno
))
633 /* Some Linux systems seem to set the FD for reading and then
634 * return ECONNREFUSED when sendto() fails and generates an ICMP
635 * port unreachable message. */
636 /* or maybe an EHOSTUNREACH "No route to host" message */
637 if (errno
!= ECONNREFUSED
&& errno
!= EHOSTUNREACH
)
640 debugs(50, 1, "icpHandleUdp: FD " << sock
<< " recvfrom: " << xstrerror());
646 icpCount(buf
, RECV
, (size_t) len
, 0);
648 debugs(12, 4, "icpHandleUdp: FD " << sock
<< ": received " <<
649 (unsigned long int)len
<< " bytes from " << from
);
651 #ifdef ICP_PACKET_DUMP
656 if ((size_t) len
< sizeof(icp_common_t
)) {
657 debugs(12, 4, "icpHandleUdp: Ignoring too-small UDP packet");
661 icp_version
= (int) buf
[1]; /* cheat! */
663 if (icp_version
== ICP_VERSION_2
)
664 icpHandleIcpV2(sock
, from
, buf
, len
);
665 else if (icp_version
== ICP_VERSION_3
)
666 icpHandleIcpV3(sock
, from
, buf
, len
);
668 debugs(12, 1, "WARNING: Unused ICP version " << icp_version
<<
669 " received from " << from
);
674 icpConnectionsOpen(void)
680 struct addrinfo
*xai
= NULL
;
683 if ((port
= Config
.Port
.icp
) <= 0)
686 addr
= Config
.Addrs
.udp_incoming
;
689 AsyncCall::Pointer call
= asyncCall(12, 2,
690 "icpIncomingConnectionOpened",
691 IcpListeningStartedDialer(&icpIncomingConnectionOpened
, addr
));
693 Ipc::StartListening(SOCK_DGRAM
,
697 Ipc::fdnInIcpSocket
, call
);
699 addr
.SetEmpty(); // clear for next use.
700 addr
= Config
.Addrs
.udp_outgoing
;
701 if ( !addr
.IsNoAddr() ) {
704 theOutIcpConnection
= comm_open_listener(SOCK_DGRAM
,
711 if (theOutIcpConnection
< 0)
712 fatal("Cannot open Outgoing ICP Port");
714 commSetSelect(theOutIcpConnection
,
720 debugs(12, 1, "Outgoing ICP messages on port " << addr
.GetPort() << ", FD " << theOutIcpConnection
<< ".");
722 fd_note(theOutIcpConnection
, "Outgoing ICP socket");
725 theOutICPAddr
.SetEmpty();
727 theOutICPAddr
.InitAddrInfo(xai
);
729 x
= getsockname(theOutIcpConnection
, xai
->ai_addr
, &xai
->ai_addrlen
);
732 debugs(50, 1, "theOutIcpConnection FD " << theOutIcpConnection
<< ": getsockname: " << xstrerror());
734 theOutICPAddr
= *xai
;
736 theOutICPAddr
.FreeAddrInfo(xai
);
740 icpIncomingConnectionOpened(int fd
, int errNo
, IpAddress
& addr
)
742 theInIcpConnection
= fd
;
744 if (theInIcpConnection
< 0)
745 fatal("Cannot open ICP Port");
747 commSetSelect(theInIcpConnection
,
753 for (const wordlist
*s
= Config
.mcast_group_list
; s
; s
= s
->next
)
754 ipcache_nbgethostbyname(s
->key
, mcastJoinGroups
, NULL
);
756 debugs(12, 1, "Accepting ICP messages at " << addr
<< ", FD " << theInIcpConnection
<< ".");
758 fd_note(theInIcpConnection
, "Incoming ICP socket");
760 if (Config
.Addrs
.udp_outgoing
.IsNoAddr())
761 theOutIcpConnection
= theInIcpConnection
;
765 * icpConnectionShutdown only closes the 'in' socket if it is
766 * different than the 'out' socket.
769 icpConnectionShutdown(void)
771 if (theInIcpConnection
< 0)
774 if (theInIcpConnection
!= theOutIcpConnection
) {
775 debugs(12, 1, "FD " << theInIcpConnection
<< " Closing ICP connection");
776 comm_close(theInIcpConnection
);
780 * Here we set 'theInIcpConnection' to -1 even though the ICP 'in'
781 * and 'out' sockets might be just one FD. This prevents this
782 * function from executing repeatedly. When we are really ready to
783 * exit or restart, main will comm_close the 'out' descriptor.
785 theInIcpConnection
= -1;
788 * Normally we only write to the outgoing ICP socket, but
789 * we also have a read handler there to catch messages sent
790 * to that specific interface. During shutdown, we must
791 * disable reading on the outgoing socket.
793 assert(theOutIcpConnection
> -1);
795 commSetSelect(theOutIcpConnection
, COMM_SELECT_READ
, NULL
, NULL
, 0);
799 icpConnectionClose(void)
801 icpConnectionShutdown();
803 if (theOutIcpConnection
> -1) {
804 debugs(12, 1, "FD " << theOutIcpConnection
<< " Closing ICP connection");
805 comm_close(theOutIcpConnection
);
806 theOutIcpConnection
= -1;
811 icpCount(void *buf
, int which
, size_t len
, int delay
)
813 icp_common_t
*icp
= (icp_common_t
*) buf
;
815 if (len
< sizeof(*icp
))
819 statCounter
.icp
.pkts_sent
++;
820 kb_incr(&statCounter
.icp
.kbytes_sent
, len
);
822 if (ICP_QUERY
== icp
->opcode
) {
823 statCounter
.icp
.queries_sent
++;
824 kb_incr(&statCounter
.icp
.q_kbytes_sent
, len
);
826 statCounter
.icp
.replies_sent
++;
827 kb_incr(&statCounter
.icp
.r_kbytes_sent
, len
);
828 /* this is the sent-reply service time */
829 statHistCount(&statCounter
.icp
.reply_svc_time
, delay
);
832 if (ICP_HIT
== icp
->opcode
)
833 statCounter
.icp
.hits_sent
++;
834 } else if (RECV
== which
) {
835 statCounter
.icp
.pkts_recv
++;
836 kb_incr(&statCounter
.icp
.kbytes_recv
, len
);
838 if (ICP_QUERY
== icp
->opcode
) {
839 statCounter
.icp
.queries_recv
++;
840 kb_incr(&statCounter
.icp
.q_kbytes_recv
, len
);
842 statCounter
.icp
.replies_recv
++;
843 kb_incr(&statCounter
.icp
.r_kbytes_recv
, len
);
844 /* statCounter.icp.query_svc_time set in clientUpdateCounters */
847 if (ICP_HIT
== icp
->opcode
)
848 statCounter
.icp
.hits_recv
++;
852 #define N_QUERIED_KEYS 8192
853 #define N_QUERIED_KEYS_MASK 8191
854 static cache_key queried_keys
[N_QUERIED_KEYS
][SQUID_MD5_DIGEST_LENGTH
];
857 icpSetCacheKey(const cache_key
* key
)
859 static int reqnum
= 0;
864 storeKeyCopy(queried_keys
[reqnum
& N_QUERIED_KEYS_MASK
], key
);
870 icpGetCacheKey(const char *url
, int reqnum
)
872 if (neighbors_do_private_keys
&& reqnum
)
873 return queried_keys
[reqnum
& N_QUERIED_KEYS_MASK
];
875 return storeKeyPublic(url
, METHOD_GET
);