1 /* $NetBSD: ntp_io.c,v 1.1.1.1 2009/12/13 16:56:13 kardel Exp $ */
4 * ntp_io.c - input/output routines for ntpd. The socket-opening code
5 * was shamelessly stolen from ntpd.
14 #ifdef HAVE_SYS_PARAM_H
15 # include <sys/param.h>
17 #ifdef HAVE_SYS_IOCTL_H
18 # include <sys/ioctl.h>
20 #ifdef HAVE_SYS_SOCKIO_H /* UXPV: SIOC* #defines (Frank Vance <fvance@waii.com>) */
21 # include <sys/sockio.h>
27 #include "ntp_machine.h"
31 #include "ntp_lists.h"
32 #include "ntp_refclock.h"
33 #include "ntp_stdlib.h"
34 #include "ntp_request.h"
36 #include "ntp_unixtime.h"
37 #include "ntp_assert.h"
38 #include "ntpd-opts.h"
40 /* Don't include ISC's version of IPv6 variables and structures */
43 #include <isc/interfaceiter.h>
44 #include <isc/netaddr.h>
45 #include <isc/result.h>
46 #include <isc/sockaddr.h>
52 #ifdef HAS_ROUTING_SOCKET
53 # include <net/route.h>
54 # ifdef HAVE_RTNETLINK
55 # include <linux/rtnetlink.h>
61 * setsockopt does not always have the same arg declaration
62 * across all platforms. If it's not defined we make it empty
65 #ifndef SETSOCKOPT_ARG_CAST
66 #define SETSOCKOPT_ARG_CAST
69 extern int listen_to_virtual_ips
;
74 typedef struct nic_rule_tag nic_rule
;
78 nic_rule_action action
;
79 nic_rule_match match_type
;
81 isc_netaddr_t netaddr
;
86 * NIC rule listhead. Entries are added at the head so that the first
87 * match in the list is the last matching rule specified.
89 nic_rule
*nic_rule_list
;
92 #if defined(SO_TIMESTAMP) && defined(SCM_TIMESTAMP)
93 #if defined(CMSG_FIRSTHDR)
94 #define HAVE_TIMESTAMP
95 #define USE_TIMESTAMP_CMSG
96 #ifndef TIMESTAMP_CTLMSGBUF_SIZE
97 #define TIMESTAMP_CTLMSGBUF_SIZE 1536 /* moderate default */
100 /* fill in for old/other timestamp interfaces */
104 #if defined(SYS_WINNT)
105 #include <transmitbuff.h>
106 #include <isc/win32os.h>
108 * Windows C runtime ioctl() can't deal properly with sockets,
109 * map to ioctlsocket for this source file.
111 #define ioctl(fd, opt, val) ioctlsocket((fd), (opt), (u_long *)(val))
112 #endif /* SYS_WINNT */
115 * We do asynchronous input using the SIGIO facility. A number of
116 * recvbuf buffers are preallocated for input. In the signal
117 * handler we poll to see which sockets are ready and read the
118 * packets from them into the recvbuf's along with a time stamp and
119 * an indication of the source host and the interface it was received
120 * through. This allows us to get as accurate receive time stamps
121 * as possible independent of other processing going on.
123 * We watch the number of recvbufs available to the signal handler
124 * and allocate more when this number drops below the low water
125 * mark. If the signal handler should run out of buffers in the
126 * interim it will drop incoming frames, the idea being that it is
127 * better to drop a packet than to be inaccurate.
132 * Other statistics of possible interest
134 volatile u_long packets_dropped
; /* total number of packets dropped on reception */
135 volatile u_long packets_ignored
; /* packets received on wild card interface */
136 volatile u_long packets_received
; /* total number of packets received */
137 u_long packets_sent
; /* total number of packets sent */
138 u_long packets_notsent
; /* total number of packets which couldn't be sent */
140 volatile u_long handler_calls
; /* number of calls to interrupt handler */
141 volatile u_long handler_pkts
; /* number of pkts received by handler */
142 u_long io_timereset
; /* time counters were reset */
147 struct interface
*any_interface
; /* default ipv4 interface */
148 struct interface
*any6_interface
; /* default ipv6 interface */
149 struct interface
*loopback_interface
; /* loopback ipv4 interface */
151 isc_boolean_t broadcast_client_enabled
; /* is broadcast client enabled */
152 int ninterfaces
; /* Total number of interfaces */
154 int disable_dynamic_updates
; /* scan interfaces once only */
158 * Refclock stuff. We keep a chain of structures with data concerning
159 * the guys we are doing I/O for.
161 static struct refclockio
*refio
;
162 #endif /* REFCLOCK */
164 #if defined(HAVE_IPTOS_SUPPORT)
165 /* set IP_TOS to minimize packet delay */
166 # if defined(IPTOS_PREC_INTERNETCONTROL)
167 unsigned int qos
= IPTOS_PREC_INTERNETCONTROL
;
169 unsigned int qos
= IPTOS_LOWDELAY
;
174 * File descriptor masks etc. for call to select
175 * Not needed for I/O Completion Ports
180 * bit alternating value to detect verified interfaces during an update cycle
182 static u_short sys_interphase
= 0;
184 static struct interface
*new_interface (struct interface
*);
185 static void add_interface (struct interface
*);
186 static int update_interfaces(u_short
, interface_receiver_t
, void *);
187 static void remove_interface(struct interface
*);
188 static struct interface
*create_interface(u_short
, struct interface
*);
190 static int move_fd (SOCKET
);
191 static int is_wildcard_addr (sockaddr_u
*);
192 static int is_wildcard_netaddr (const isc_netaddr_t
*);
195 * Multicast functions
197 static isc_boolean_t
addr_ismulticast (sockaddr_u
*);
199 * Not all platforms support multicast
202 static isc_boolean_t
socket_multicast_enable (struct interface
*, int, sockaddr_u
*);
203 static isc_boolean_t
socket_multicast_disable(struct interface
*, sockaddr_u
*);
207 static void interface_dump (struct interface
*);
208 static void sockaddr_dump (sockaddr_u
*psau
);
209 static void print_interface (struct interface
*, char *, char *);
210 #define DPRINT_INTERFACE(level, args) do { if (debug >= (level)) { print_interface args; } } while (0)
212 #define DPRINT_INTERFACE(level, args) do {} while (0)
215 typedef struct vsock vsock_t
;
216 enum desc_type
{ FD_TYPE_SOCKET
, FD_TYPE_FILE
};
226 #if !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET)
228 * async notification processing (e. g. routing sockets)
231 * support for receiving data on fd that is not a refclock or a socket
232 * like e. g. routing sockets
234 struct asyncio_reader
{
235 struct asyncio_reader
*link
; /* the list this is being kept in */
236 SOCKET fd
; /* fd to be read */
237 void *data
; /* possibly local data */
238 void (*receiver
)(struct asyncio_reader
*); /* input handler */
241 struct asyncio_reader
*asyncio_reader_list
;
243 static void delete_asyncio_reader (struct asyncio_reader
*);
244 static struct asyncio_reader
*new_asyncio_reader (void);
245 static void add_asyncio_reader (struct asyncio_reader
*, enum desc_type
);
246 static void remove_asyncio_reader (struct asyncio_reader
*);
248 #endif /* !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET) */
250 static void init_async_notifications (void);
252 static int create_sockets (u_short
);
253 static SOCKET
open_socket (sockaddr_u
*, int, int, struct interface
*);
254 static char * fdbits (int, fd_set
*);
255 static void set_reuseaddr (int);
256 static isc_boolean_t
socket_broadcast_enable (struct interface
*, SOCKET
, sockaddr_u
*);
257 static isc_boolean_t
socket_broadcast_disable (struct interface
*, sockaddr_u
*);
259 typedef struct remaddr remaddr_t
;
264 struct interface
* interface
;
267 remaddr_t
* remoteaddr_list
;
269 struct interface
* inter_list
;
271 static struct interface
*wildipv4
= NULL
;
272 static struct interface
*wildipv6
= NULL
;
274 static void add_fd_to_list (SOCKET
,
276 static struct interface
*find_addr_in_list (sockaddr_u
*);
277 static struct interface
*find_samenet_addr_in_list(sockaddr_u
*);
278 static struct interface
*find_flagged_addr_in_list(sockaddr_u
*, int);
279 static void delete_addr_from_list (sockaddr_u
*);
280 static void delete_interface_from_list(struct interface
*);
281 static void close_and_delete_fd_from_list(SOCKET
);
282 static void add_addr_to_list (sockaddr_u
*,
284 static void create_wildcards (u_short
);
286 static const char * action_text (nic_rule_action
);
288 static nic_rule_action
interface_action(char *, isc_netaddr_t
*,
290 static void convert_isc_if (isc_interface_t
*,
291 struct interface
*, u_short
);
292 static struct interface
*getinterface (sockaddr_u
*, int);
293 static struct interface
*getsamenetinterface (sockaddr_u
*, int);
294 static struct interface
*findlocalinterface (sockaddr_u
*, int, int);
295 static struct interface
*findlocalcastinterface (sockaddr_u
*);
298 * Routines to read the ntp packets
300 #if !defined(HAVE_IO_COMPLETION_PORT)
301 static inline int read_network_packet (SOCKET
, struct interface
*, l_fp
);
302 static inline int read_refclock_packet (SOCKET
, struct refclockio
*, l_fp
);
308 * Windows 2000 systems incorrectly cause UDP sockets using WASRecvFrom
309 * to not work correctly, returning a WSACONNRESET error when a WSASendTo
310 * fails with an "ICMP port unreachable" response and preventing the
311 * socket from using the WSARecvFrom in subsequent operations.
312 * The function below fixes this, but requires that Windows 2000
313 * Service Pack 2 or later be installed on the system. NT 4.0
314 * systems are not affected by this and work correctly.
315 * See Microsoft Knowledge Base Article Q263823 for details of this.
318 connection_reset_fix(
324 BOOL bNewBehavior
= FALSE
;
328 * disable bad behavior using IOCTL: SIO_UDP_CONNRESET
329 * NT 4.0 has no problem
331 if (isc_win32os_majorversion() >= 5) {
332 status
= WSAIoctl(fd
, SIO_UDP_CONNRESET
, &bNewBehavior
,
333 sizeof(bNewBehavior
), NULL
, 0,
335 if (SOCKET_ERROR
== status
)
337 "connection_reset_fix() failed for address %s: %m",
344 * on Unix systems the stdio library typically
345 * makes use of file descriptors in the lower
346 * integer range. stdio usually will make use
347 * of the file descriptors in the range of
349 * in order to keep this range clean, for socket
350 * file descriptors we attempt to move them above
351 * FOPEN_MAX. This is not as easy as it sounds as
352 * FOPEN_MAX changes from implementation to implementation
353 * and may exceed to current file decriptor limits.
354 * We are using following strategy:
355 * - keep a current socket fd boundary initialized with
356 * max(0, min(getdtablesize() - FD_CHUNK, FOPEN_MAX))
357 * - attempt to move the descriptor to the boundary or
359 * - if that fails and boundary > 0 set boundary
360 * to min(0, socket_fd_boundary - FD_CHUNK)
362 * if failure and boundary == 0 return old fd
363 * - on success close old fd return new fd
366 * - fds will be moved above the socket fd boundary
367 * if at all possible.
368 * - the socket boundary will be reduced until
369 * allocation is possible or 0 is reached - at this
370 * point the algrithm will be disabled
377 #if !defined(SYS_WINNT) && defined(F_DUPFD)
382 * number of fds we would like to have for
383 * stdio FILE* available.
384 * we can pick a "low" number as our use of
385 * FILE* is limited to log files and temporarily
386 * to data and config files. Except for log files
387 * we don't keep the other FILE* open beyond the
388 * scope of the function that opened it.
390 #ifndef FD_PREFERRED_SOCKBOUNDARY
391 #define FD_PREFERRED_SOCKBOUNDARY 48
394 #ifndef HAVE_GETDTABLESIZE
396 * if we have no idea about the max fd value set up things
397 * so we will start at FOPEN_MAX
399 #define getdtablesize() (FOPEN_MAX+FD_CHUNK)
403 #define FOPEN_MAX 20 /* assume that for the lack of anything better */
405 static SOCKET socket_boundary
= -1;
408 NTP_REQUIRE((int)fd
>= 0);
411 * check whether boundary has be set up
414 if (socket_boundary
== -1) {
415 socket_boundary
= max(0, min(getdtablesize() - FD_CHUNK
,
416 min(FOPEN_MAX
, FD_PREFERRED_SOCKBOUNDARY
)));
419 "ntp_io: estimated max descriptors: %d, initial socket boundary: %d",
420 getdtablesize(), socket_boundary
);
425 * Leave a space for stdio to work in. potentially moving the
426 * socket_boundary lower until allocation succeeds.
429 if (fd
>= 0 && fd
< socket_boundary
) {
430 /* inside reserved range: attempt to move fd */
431 newfd
= fcntl(fd
, F_DUPFD
, socket_boundary
);
434 /* success: drop the old one - return the new one */
439 /* outside reserved range: no work - return the original one */
442 socket_boundary
= max(0, socket_boundary
- FD_CHUNK
);
445 "ntp_io: selecting new socket boundary: %d",
448 } while (socket_boundary
> 0);
450 NTP_REQUIRE((int)fd
>= 0);
451 #endif /* !defined(SYS_WINNT) && defined(F_DUPFD) */
457 * collect timing information for various processing
458 * paths. currently we only pass then on to the file
459 * for later processing. this could also do histogram
460 * based analysis in other to reduce the load (and skew)
461 * dur to the file output
464 collect_timing(struct recvbuf
*rb
, const char *tag
, int count
, l_fp
*dts
)
468 snprintf(buf
, sizeof(buf
), "%s %d %s %s",
470 ? ((rb
->dstadr
!= NULL
)
471 ? stoa(&rb
->recv_srcadr
)
474 count
, lfptoa(dts
, 9), tag
);
475 record_timing_stats(buf
);
480 * About dynamic interfaces, sockets, reception and more...
482 * the code solves following tasks:
484 * - keep a current list of active interfaces in order
485 * to bind to to the interface address on NTP_PORT so that
486 * all wild and specific bindings for NTP_PORT are taken by ntpd
487 * to avoid other daemons messing with the time or sockets.
488 * - all interfaces keep a list of peers that are referencing
489 * the interface in order to quickly re-assign the peers to
490 * new interface in case an interface is deleted (=> gone from system or
492 * - have a preconfigured socket ready with the right local address
493 * for transmission and reception
494 * - have an address list for all destination addresses used within ntpd
495 * to find the "right" preconfigured socket.
496 * - facilitate updating the internal interface list with respect to
497 * the current kernel state
501 * - mapping of multicast addresses to the interface affected is not always
502 * one to one - especially on hosts with multiple interfaces
503 * the code here currently allocates a separate interface entry for those
504 * multicast addresses
505 * iff it is able to bind to a *new* socket with the multicast address (flags |= MCASTIF)
506 * in case of failure the multicast address is bound to an existing interface.
507 * - on some systems it is perfectly legal to assign the same address to
508 * multiple interfaces. Therefore this code does not keep a list of interfaces
509 * but a list of interfaces that represent a unique address as determined by the kernel
510 * by the procedure in findlocalinterface. Thus it is perfectly legal to see only
511 * one representative of a group of real interfaces if they share the same address.
513 * Frank Kardel 20050910
517 * init_io - initialize I/O data structures and call socket creation routine
523 * Init buffer free list and stat counters
525 init_recvbuff(RECV_INIT
);
528 init_io_completion_port();
529 #endif /* SYS_WINNT */
531 #if defined(HAVE_SIGNALED_IO)
538 * io_open_sockets - call socket creation routine
541 io_open_sockets(void)
543 static int already_opened
;
545 if (already_opened
|| HAVE_OPT( SAVECONFIGQUIT
))
554 create_sockets(NTP_PORT
);
557 init_async_notifications();
559 DPRINTF(3, ("io_open_sockets: maxactivefd %d\n", maxactivefd
));
565 * function to dump the contents of the interface structure
566 * for debugging use only.
569 interface_dump(struct interface
*itf
)
571 printf("Dumping interface: %p\n", itf
);
572 printf("fd = %d\n", itf
->fd
);
573 printf("bfd = %d\n", itf
->bfd
);
574 printf("sin = %s,\n", stoa(&itf
->sin
));
575 sockaddr_dump(&itf
->sin
);
576 printf("bcast = %s,\n", stoa(&itf
->bcast
));
577 sockaddr_dump(&itf
->bcast
);
578 printf("mask = %s,\n", stoa(&itf
->mask
));
579 sockaddr_dump(&itf
->mask
);
580 printf("name = %s\n", itf
->name
);
581 printf("flags = 0x%08x\n", itf
->flags
);
582 printf("last_ttl = %d\n", itf
->last_ttl
);
583 printf("addr_refid = %08x\n", itf
->addr_refid
);
584 printf("num_mcast = %d\n", itf
->num_mcast
);
585 printf("received = %ld\n", itf
->received
);
586 printf("sent = %ld\n", itf
->sent
);
587 printf("notsent = %ld\n", itf
->notsent
);
588 printf("scopeid = %u\n", itf
->scopeid
);
589 printf("peercnt = %u\n", itf
->peercnt
);
590 printf("phase = %u\n", itf
->phase
);
594 * sockaddr_dump - hex dump the start of a sockaddr_u
597 sockaddr_dump(sockaddr_u
*psau
)
599 /* Limit the size of the sockaddr_storage hex dump */
600 const int maxsize
= min(32, sizeof(psau
->sas
));
604 cp
= (u_char
*)&psau
->sas
;
606 for(i
= 0; i
< maxsize
; i
++)
608 printf("%02x", *cp
++);
616 * print_interface - helper to output debug information
619 print_interface(struct interface
*iface
, char *pfx
, char *sfx
)
621 printf("%sinterface #%d: fd=%d, bfd=%d, name=%s, flags=0x%x, scope=%d, sin=%s",
630 if (AF_INET
== iface
->family
) {
631 if (iface
->flags
& INT_BROADCAST
)
632 printf(", bcast=%s", stoa(&iface
->bcast
));
633 printf(", mask=%s", stoa(&iface
->mask
));
636 (iface
->ignore_packets
)
640 if (debug
> 4) /* in-depth debugging only */
641 interface_dump(iface
);
645 #if !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET)
647 * create an asyncio_reader structure
649 static struct asyncio_reader
*
650 new_asyncio_reader(void)
652 struct asyncio_reader
*reader
;
654 reader
= emalloc(sizeof(*reader
));
656 memset(reader
, 0, sizeof(*reader
));
657 reader
->fd
= INVALID_SOCKET
;
665 delete_asyncio_reader(
666 struct asyncio_reader
*reader
673 * add asynchio_reader
677 struct asyncio_reader
* reader
,
680 LINK_SLIST(asyncio_reader_list
, reader
, link
);
681 add_fd_to_list(reader
->fd
, type
);
685 * remove asynchio_reader
688 remove_asyncio_reader(
689 struct asyncio_reader
*reader
692 struct asyncio_reader
*unlinked
;
694 UNLINK_SLIST(unlinked
, asyncio_reader_list
, reader
, link
,
695 struct asyncio_reader
);
697 if (reader
->fd
!= INVALID_SOCKET
)
698 close_and_delete_fd_from_list(reader
->fd
);
700 reader
->fd
= INVALID_SOCKET
;
702 #endif /* !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET) */
705 * Code to tell if we have an IP address
706 * If we have then return the sockaddr structure
707 * and set the return value
708 * see the bind9/getaddresses.c for details
721 NTP_REQUIRE(host
!= NULL
);
722 NTP_REQUIRE(addr
!= NULL
);
725 * Try IPv4, then IPv6. In order to handle the extended format
726 * for IPv6 scoped addresses (address%scope_ID), we'll use a local
727 * working buffer of 128 bytes. The length is an ad-hoc value, but
728 * should be enough for this purpose; the buffer can contain a string
729 * of at least 80 bytes for scope_ID in addition to any IPv6 numeric
730 * addresses (up to 46 bytes), the delimiter character and the
731 * terminating NULL character.
733 if (inet_pton(AF_INET
, host
, &in4
) == 1) {
734 isc_netaddr_fromin(addr
, &in4
);
736 } else if (sizeof(tmpbuf
) > strlen(host
)) {
737 if ('[' == host
[0]) {
738 strncpy(tmpbuf
, &host
[1], sizeof(tmpbuf
));
739 pch
= strchr(tmpbuf
, ']');
743 strncpy(tmpbuf
, host
, sizeof(tmpbuf
));
744 pch
= strchr(tmpbuf
, '%');
748 if (inet_pton(AF_INET6
, tmpbuf
, &in6
) == 1) {
749 isc_netaddr_fromin6(addr
, &in6
);
754 * If we got here it was not an IP address
761 * interface list enumerator - visitor pattern
765 interface_receiver_t receiver
,
769 interface_info_t ifi
;
771 ifi
.action
= IFS_EXISTS
;
773 for (ifi
.interface
= inter_list
;
774 ifi
.interface
!= NULL
;
775 ifi
.interface
= ifi
.interface
->link
)
776 (*receiver
)(data
, &ifi
);
780 * do standard initialization of interface structure
784 struct interface
*iface
787 memset(iface
, 0, sizeof(*iface
));
788 iface
->fd
= INVALID_SOCKET
;
789 iface
->bfd
= INVALID_SOCKET
;
790 iface
->phase
= sys_interphase
;
795 * create new interface structure initialize from
796 * template structure or via standard initialization
799 static struct interface
*
801 struct interface
*interface
804 static u_int sys_ifnum
= 0;
805 struct interface
* iface
;
807 iface
= emalloc(sizeof(*iface
));
809 if (NULL
== interface
)
810 init_interface(iface
);
811 else /* use the template */
812 memcpy(iface
, interface
, sizeof(*iface
));
814 /* count every new instance of an interface in the system */
815 iface
->ifnum
= sys_ifnum
++;
816 iface
->starttime
= current_time
;
823 * return interface storage into free memory pool
827 struct interface
*interface
835 * link interface into list of known interfaces
839 struct interface
*interface
843 * Calculate the address hash
845 interface
->addr_refid
= addr2refid(&interface
->sin
);
847 LINK_SLIST(inter_list
, interface
, link
);
853 * remove interface from known interface list and clean up
854 * associated resources
858 struct interface
*iface
861 struct interface
*unlinked
;
864 UNLINK_SLIST(unlinked
, inter_list
, iface
, link
, struct
867 delete_interface_from_list(iface
);
869 if (iface
->fd
!= INVALID_SOCKET
) {
871 "Deleting interface #%d %s, %s#%d, interface stats: received=%ld, sent=%ld, dropped=%ld, active_time=%ld secs",
875 SRCPORT(&iface
->sin
),
879 current_time
- iface
->starttime
);
881 close_and_delete_fd_from_list(iface
->fd
);
884 if (iface
->bfd
!= INVALID_SOCKET
) {
886 "Deleting broadcast address %s#%d from interface #%d %s",
888 SRCPORT(&iface
->bcast
),
892 close_and_delete_fd_from_list(iface
->bfd
);
896 ntp_monclearinterface(iface
);
898 /* remove restrict interface entry */
899 SET_HOSTMASK(&resmask
, AF(&iface
->sin
));
900 hack_restrict(RESTRICT_REMOVEIF
, &iface
->sin
, &resmask
,
901 RESM_NTPONLY
| RESM_INTERFACE
, RES_IGNORE
);
907 struct interface
* iface
910 msyslog(LOG_INFO
, "%s on %d %s %s UDP %d",
911 (iface
->ignore_packets
)
917 SRCPORT(&iface
->sin
));
928 isc_netaddr_t wnaddr
;
929 nic_rule_action action
;
930 struct interface
* wildif
;
933 * silence "potentially uninitialized" warnings from VC9
934 * failing to follow the logic. Ideally action could remain
935 * uninitialized, and the memset be the first statement under
936 * the first if (v4wild).
938 action
= ACTION_LISTEN
;
939 memset(&wildaddr
, 0, sizeof(wildaddr
));
942 * create pseudo-interface with wildcard IPv4 address
946 /* set wildaddr to the v4 wildcard address 0.0.0.0 */
947 AF(&wildaddr
) = AF_INET
;
948 SET_ADDR4(&wildaddr
, INADDR_ANY
);
949 SET_PORT(&wildaddr
, port
);
951 /* make an libisc-friendly copy */
952 isc_netaddr_fromin(&wnaddr
, &wildaddr
.sa4
.sin_addr
);
954 /* check for interface/nic rules affecting the wildcard */
955 action
= interface_action(NULL
, &wnaddr
, 0);
956 v4wild
= (ACTION_IGNORE
!= action
);
959 wildif
= new_interface(NULL
);
961 strncpy(wildif
->name
, "v4wildcard", sizeof(wildif
->name
));
962 memcpy(&wildif
->sin
, &wildaddr
, sizeof(wildif
->sin
));
963 wildif
->family
= AF_INET
;
964 AF(&wildif
->mask
) = AF_INET
;
965 SET_ONESMASK(&wildif
->mask
);
967 wildif
->flags
= INT_BROADCAST
| INT_UP
| INT_WILDCARD
;
968 wildif
->ignore_packets
= (ACTION_DROP
== action
);
971 * enable multicast reception on the broadcast socket
973 AF(&wildif
->bcast
) = AF_INET
;
974 SET_ADDR4(&wildif
->bcast
, INADDR_ANY
);
975 SET_PORT(&wildif
->bcast
, port
);
977 wildif
->fd
= open_socket(&wildif
->sin
, 0, 1, wildif
);
979 if (wildif
->fd
!= INVALID_SOCKET
) {
981 any_interface
= wildif
;
983 add_addr_to_list(&wildif
->sin
, wildif
);
984 add_interface(wildif
);
985 list_if_listening(wildif
);
988 "unable to bind to wildcard address %s - another process may be running - EXITING",
992 DPRINT_INTERFACE(2, (wildif
, "created ", "\n"));
995 #ifdef INCLUDE_IPV6_SUPPORT
997 * create pseudo-interface with wildcard IPv6 address
1001 /* set wildaddr to the v6 wildcard address :: */
1002 memset(&wildaddr
, 0, sizeof(wildaddr
));
1003 AF(&wildaddr
) = AF_INET6
;
1004 SET_ADDR6N(&wildaddr
, in6addr_any
);
1005 SET_PORT(&wildaddr
, port
);
1006 SET_SCOPE(&wildaddr
, 0);
1008 /* make an libisc-friendly copy */
1009 isc_netaddr_fromin(&wnaddr
, &wildaddr
.sa4
.sin_addr
);
1011 /* check for interface/nic rules affecting the wildcard */
1012 action
= interface_action(NULL
, &wnaddr
, 0);
1013 v6wild
= (ACTION_IGNORE
!= action
);
1016 wildif
= new_interface(NULL
);
1018 strncpy(wildif
->name
, "v6wildcard", sizeof(wildif
->name
));
1019 memcpy(&wildif
->sin
, &wildaddr
, sizeof(wildif
->sin
));
1020 wildif
->family
= AF_INET6
;
1021 AF(&wildif
->mask
) = AF_INET6
;
1022 SET_ONESMASK(&wildif
->mask
);
1024 wildif
->flags
= INT_UP
| INT_WILDCARD
;
1025 wildif
->ignore_packets
= (ACTION_DROP
== action
);
1027 wildif
->fd
= open_socket(&wildif
->sin
, 0, 1, wildif
);
1029 if (wildif
->fd
!= INVALID_SOCKET
) {
1031 any6_interface
= wildif
;
1032 add_addr_to_list(&wildif
->sin
, wildif
);
1033 add_interface(wildif
);
1034 list_if_listening(wildif
);
1037 "unable to bind to wildcard address %s - another process may be running - EXITING",
1038 stoa(&wildif
->sin
));
1041 DPRINT_INTERFACE(2, (wildif
, "created ", "\n"));
1048 * add_nic_rule() -- insert a rule entry at the head of nic_rule_list.
1052 nic_rule_match match_type
,
1053 const char * if_name
, /* interface name or numeric address */
1055 nic_rule_action action
1059 isc_boolean_t is_ip
;
1061 rule
= emalloc(sizeof(*rule
));
1062 memset(rule
, 0, sizeof(*rule
));
1063 rule
->match_type
= match_type
;
1064 rule
->prefixlen
= prefixlen
;
1065 rule
->action
= action
;
1067 if (MATCH_IFNAME
== match_type
) {
1068 NTP_REQUIRE(NULL
!= if_name
);
1069 rule
->if_name
= estrdup(if_name
);
1070 } else if (MATCH_IFADDR
== match_type
) {
1071 NTP_REQUIRE(NULL
!= if_name
);
1072 /* set rule->netaddr */
1073 is_ip
= is_ip_address(if_name
, &rule
->netaddr
);
1076 NTP_REQUIRE(NULL
== if_name
);
1078 LINK_SLIST(nic_rule_list
, rule
, next
);
1085 nic_rule_action action
1093 t
= "ERROR"; /* quiet uninit warning */
1094 DPRINTF(1, ("fatal: unknown nic_rule_action %d\n",
1117 static nic_rule_action
1120 isc_netaddr_t
* if_netaddr
,
1121 isc_uint32_t if_flags
1128 DPRINTF(4, ("interface_action: interface %s ",
1129 (if_name
!= NULL
) ? if_name
: "wildcard"));
1131 iswildcard
= is_wildcard_netaddr(if_netaddr
);
1134 * Always listen on 127.0.0.1 - required by ntp_intres
1136 if (if_flags
& INTERFACE_F_LOOPBACK
) {
1138 if (AF_INET
== if_netaddr
->family
) {
1139 DPRINTF(4, ("IPv4 loopback - listen\n"));
1140 return ACTION_LISTEN
;
1146 * Find any matching NIC rule from --interface / -I or ntp.conf
1147 * interface/nic rules.
1149 for (rule
= nic_rule_list
; rule
!= NULL
; rule
= rule
->next
) {
1151 switch (rule
->match_type
) {
1154 /* loopback and wildcard excluded from "all" */
1155 if (isloopback
|| iswildcard
)
1157 DPRINTF(4, ("nic all %s\n",
1158 action_text(rule
->action
)));
1159 return rule
->action
;
1162 if (AF_INET
== if_netaddr
->family
) {
1163 DPRINTF(4, ("nic ipv4 %s\n",
1164 action_text(rule
->action
)));
1165 return rule
->action
;
1170 if (AF_INET6
== if_netaddr
->family
) {
1171 DPRINTF(4, ("nic ipv6 %s\n",
1172 action_text(rule
->action
)));
1173 return rule
->action
;
1177 case MATCH_WILDCARD
:
1179 DPRINTF(4, ("nic wildcard %s\n",
1180 action_text(rule
->action
)));
1181 return rule
->action
;
1186 if (rule
->prefixlen
!= -1) {
1187 if (isc_netaddr_eqprefix(if_netaddr
,
1188 &rule
->netaddr
, rule
->prefixlen
)) {
1190 DPRINTF(4, ("subnet address match - %s\n",
1191 action_text(rule
->action
)));
1192 return rule
->action
;
1195 if (isc_netaddr_equal(if_netaddr
,
1198 DPRINTF(4, ("address match - %s\n",
1199 action_text(rule
->action
)));
1200 return rule
->action
;
1206 && !strcasecmp(if_name
, rule
->if_name
)) {
1208 DPRINTF(4, ("interface name match - %s\n",
1209 action_text(rule
->action
)));
1210 return rule
->action
;
1217 * Unless explicitly disabled such as with "nic ignore ::1"
1218 * listen on loopback addresses. Since ntpq and ntpdc query
1219 * "localhost" by default, which typically resolves to ::1 and
1220 * 127.0.0.1, it's useful to default to listening on both.
1223 DPRINTF(4, ("default loopback listen\n"));
1224 return ACTION_LISTEN
;
1228 * Treat wildcard addresses specially. If there is no explicit
1229 * "nic ... wildcard" or "nic ... 0.0.0.0" or "nic ... ::" rule
1233 DPRINTF(4, ("default wildcard drop\n"));
1238 * Check for "virtual IP" (colon in the interface name) after
1239 * the rules so that "ntpd --interface eth0:1 -novirtualips"
1240 * does indeed listen on eth0:1's addresses.
1242 if (!listen_to_virtual_ips
&& if_name
!= NULL
1243 && (strchr(if_name
, ':') != NULL
)) {
1245 DPRINTF(4, ("virtual ip - ignore\n"));
1246 return ACTION_IGNORE
;
1250 * If there are no --interface/-I command-line options and no
1251 * interface/nic rules in ntp.conf, the default action is to
1252 * listen. In the presence of rules from either, the default
1253 * is to ignore. This implements ntpd's traditional listen-
1254 * every default with no interface listen configuration, and
1255 * ensures a single -I eth0 or "nic listen eth0" means do not
1256 * listen on any other addresses.
1258 if (NULL
== nic_rule_list
) {
1259 DPRINTF(4, ("default listen\n"));
1260 return ACTION_LISTEN
;
1263 DPRINTF(4, ("implicit ignore\n"));
1264 return ACTION_IGNORE
;
1270 isc_interface_t
*isc_if
,
1271 struct interface
*itf
,
1275 strncpy(itf
->name
, isc_if
->name
, sizeof(itf
->name
));
1276 itf
->name
[sizeof(itf
->name
) - 1] = 0; /* strncpy may not */
1277 itf
->family
= (u_short
)isc_if
->af
;
1278 AF(&itf
->sin
) = itf
->family
;
1279 AF(&itf
->mask
) = itf
->family
;
1280 AF(&itf
->bcast
) = itf
->family
;
1281 SET_PORT(&itf
->sin
, port
);
1282 SET_PORT(&itf
->mask
, port
);
1283 SET_PORT(&itf
->bcast
, port
);
1285 if (IS_IPV4(&itf
->sin
)) {
1286 NSRCADR(&itf
->sin
) = isc_if
->address
.type
.in
.s_addr
;
1287 NSRCADR(&itf
->mask
) = isc_if
->netmask
.type
.in
.s_addr
;
1289 if (isc_if
->flags
& INTERFACE_F_BROADCAST
) {
1290 itf
->flags
|= INT_BROADCAST
;
1291 NSRCADR(&itf
->bcast
) =
1292 isc_if
->broadcast
.type
.in
.s_addr
;
1295 #ifdef INCLUDE_IPV6_SUPPORT
1296 else if (IS_IPV6(&itf
->sin
)) {
1297 SET_ADDR6N(&itf
->sin
, isc_if
->address
.type
.in6
);
1298 SET_ADDR6N(&itf
->mask
, isc_if
->netmask
.type
.in6
);
1300 itf
->scopeid
= isc_netaddr_getzone(&isc_if
->address
);
1301 SET_SCOPE(&itf
->sin
, itf
->scopeid
);
1303 #endif /* INCLUDE_IPV6_SUPPORT */
1306 /* Process the rest of the flags */
1309 ((INTERFACE_F_UP
& isc_if
->flags
)
1311 | ((INTERFACE_F_LOOPBACK
& isc_if
->flags
)
1313 | ((INTERFACE_F_POINTTOPOINT
& isc_if
->flags
)
1315 | ((INTERFACE_F_MULTICAST
& isc_if
->flags
)
1316 ? INT_MULTICAST
: 0)
1324 * some OSes have been observed to keep
1325 * cached routes even when more specific routes
1327 * this can be mitigated by re-binding
1332 struct interface
* interface
1335 #ifdef OS_MISSES_SPECIFIC_ROUTE_UPDATES
1336 if (interface
->fd
!= INVALID_SOCKET
) {
1337 close_and_delete_fd_from_list(interface
->fd
);
1338 interface
->fd
= open_socket(&interface
->sin
,
1341 * reset TTL indication so TTL is is set again
1344 interface
->last_ttl
= 0;
1345 return (interface
->fd
!= INVALID_SOCKET
);
1347 return 0; /* invalid sockets are not refreshable */
1348 #else /* !OS_MISSES_SPECIFIC_ROUTE_UPDATES */
1349 return (interface
->fd
!= INVALID_SOCKET
);
1350 #endif /* !OS_MISSES_SPECIFIC_ROUTE_UPDATES */
1354 * interface_update - externally callable update function
1358 interface_receiver_t receiver
,
1361 int new_interface_found
;
1363 if (disable_dynamic_updates
)
1367 new_interface_found
= update_interfaces(NTP_PORT
, receiver
, data
);
1370 if (!new_interface_found
)
1374 msyslog(LOG_DEBUG
, "new interface(s) found: waking up resolver");
1377 /* wake up the resolver thread */
1378 if (ResolverEventHandle
!= NULL
)
1379 SetEvent(ResolverEventHandle
);
1381 /* write any single byte to the pipe to wake up the resolver process */
1382 write( resolver_pipe_fd
[1], &new_interface_found
, 1 );
1388 * sau_from_netaddr() - convert network address on-wire formats.
1389 * Convert from libisc's isc_netaddr_t to NTP's sockaddr_u
1394 const isc_netaddr_t
*pna
1397 memset(psau
, 0, sizeof(*psau
));
1398 AF(psau
) = (u_short
)pna
->family
;
1399 switch (pna
->family
) {
1402 memcpy(&psau
->sa4
.sin_addr
, &pna
->type
.in
,
1403 sizeof(psau
->sa4
.sin_addr
));
1407 memcpy(&psau
->sa6
.sin6_addr
, &pna
->type
.in6
,
1408 sizeof(psau
->sa6
.sin6_addr
));
1419 if (IS_IPV4(psau
) && !NSRCADR(psau
))
1422 #ifdef INCLUDE_IPV6_SUPPORT
1423 if (IS_IPV6(psau
) && S_ADDR6_EQ(psau
, &in6addr_any
))
1432 is_wildcard_netaddr(
1433 const isc_netaddr_t
*pna
1438 sau_from_netaddr(&sau
, pna
);
1440 return is_wildcard_addr(&sau
);
1444 #ifdef OS_NEEDS_REUSEADDR_FOR_IFADDRBIND
1446 * enable/disable re-use of wildcard address socket
1454 struct interface
*any
;
1455 SOCKET fd
= INVALID_SOCKET
;
1457 any
= ANY_INTERFACE_BYFAM(family
);
1461 if (fd
!= INVALID_SOCKET
) {
1462 if (setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
1463 (char *)&on
, sizeof(on
)))
1465 "set_wildcard_reuse: setsockopt(SO_REUSEADDR, %s) failed: %m",
1468 DPRINTF(4, ("set SO_REUSEADDR to %s on %s\n",
1473 #endif /* OS_NEEDS_REUSEADDR_FOR_IFADDRBIND */
1476 * update_interface strategy
1478 * toggle configuration phase
1481 * forall currently existing interfaces
1482 * if address is known:
1483 * drop socket - rebind again
1485 * if address is NOT known:
1486 * attempt to create a new interface entry
1489 * forall currently known non MCAST and WILDCARD interfaces
1490 * if interface does not match configuration phase (not seen in phase 1):
1491 * remove interface from known interface list
1492 * forall peers associated with this interface
1493 * disconnect peer from this interface
1496 * attempt to re-assign interfaces to peers
1503 interface_receiver_t receiver
,
1507 isc_mem_t
* mctx
= (void *)-1;
1508 interface_info_t ifi
;
1509 isc_interfaceiter_t
* iter
;
1510 isc_result_t result
;
1511 isc_interface_t isc_if
;
1512 int new_interface_found
;
1513 unsigned int family
;
1514 struct interface interface
;
1515 struct interface
* iface
;
1516 struct interface
* next
;
1518 DPRINTF(3, ("update_interfaces(%d)\n", port
));
1521 * phase one - scan interfaces
1522 * - create those that are not found
1523 * - update those that are found
1526 new_interface_found
= 0;
1528 result
= isc_interfaceiter_create(mctx
, &iter
);
1530 if (result
!= ISC_R_SUCCESS
)
1534 * Toggle system interface scan phase to find untouched
1535 * interfaces to be deleted.
1537 sys_interphase
^= 0x1;
1539 for (result
= isc_interfaceiter_first(iter
);
1540 ISC_R_SUCCESS
== result
;
1541 result
= isc_interfaceiter_next(iter
)) {
1543 result
= isc_interfaceiter_current(iter
, &isc_if
);
1545 if (result
!= ISC_R_SUCCESS
)
1548 /* See if we have a valid family to use */
1549 family
= isc_if
.address
.family
;
1550 if (AF_INET
!= family
&& AF_INET6
!= family
)
1552 if (AF_INET
== family
&& !ipv4_works
)
1554 if (AF_INET6
== family
&& !ipv6_works
)
1557 /* create prototype */
1558 init_interface(&interface
);
1560 convert_isc_if(&isc_if
, &interface
, port
);
1563 * Check if and how we are going to use the interface.
1565 switch (interface_action(isc_if
.name
, &isc_if
.address
,
1572 interface
.ignore_packets
= ISC_FALSE
;
1576 interface
.ignore_packets
= ISC_TRUE
;
1580 DPRINT_INTERFACE(4, (&interface
, "examining ", "\n"));
1582 /* interfaces must be UP to be usable */
1583 if (!(interface
.flags
& INT_UP
)) {
1584 DPRINTF(4, ("skipping interface %s (%s) - DOWN\n",
1585 interface
.name
, stoa(&interface
.sin
)));
1590 * skip any interfaces UP and bound to a wildcard
1591 * address - some dhcp clients produce that in the
1594 if (is_wildcard_addr(&interface
.sin
))
1598 * map to local *address* in order to map all duplicate
1599 * interfaces to an interface structure with the
1600 * appropriate socket. Our name space is (ip-address),
1601 * NOT (interface name, ip-address).
1603 iface
= getinterface(&interface
.sin
, INT_WILDCARD
);
1605 if (iface
!= NULL
&& refresh_interface(iface
)) {
1607 * found existing and up to date interface -
1610 if (iface
->phase
!= sys_interphase
) {
1612 * On a new round we reset the name so
1613 * the interface name shows up again if
1614 * this address is no longer shared.
1615 * The same reasoning goes for the
1616 * ignore_packets flag.
1618 strncpy(iface
->name
, interface
.name
,
1619 sizeof(iface
->name
));
1620 iface
->ignore_packets
=
1621 interface
.ignore_packets
;
1623 /* name collision - rename interface */
1624 strncpy(iface
->name
, "*multiple*",
1625 sizeof(iface
->name
));
1627 DPRINT_INTERFACE(4, (iface
, "updating ",
1630 if (iface
->ignore_packets
!=
1631 interface
.ignore_packets
) {
1633 * We have conflicting configurations
1634 * for the interface address. This is
1635 * caused by using -I <interfacename>
1636 * for an interface that shares its
1637 * address with other interfaces. We
1638 * can not disambiguate incoming
1639 * packets delivered to this socket
1640 * without extra syscalls/features.
1641 * These are not (commonly) available.
1642 * Note this is a more unusual
1643 * configuration where several
1644 * interfaces share an address but
1645 * filtering via interface name is
1646 * attempted. We resolve the
1647 * configuration conflict by disabling
1648 * the processing of received packets.
1649 * This leads to no service on the
1650 * interface address where the conflict
1654 "WARNING: conflicting enable configuration for interfaces %s and %s for address %s - unsupported configuration - address DISABLED",
1655 interface
.name
, iface
->name
,
1656 stoa(&interface
.sin
));
1658 iface
->ignore_packets
= ISC_TRUE
;
1661 iface
->phase
= sys_interphase
;
1663 ifi
.action
= IFS_EXISTS
;
1664 ifi
.interface
= iface
;
1665 if (receiver
!= NULL
)
1666 (*receiver
)(data
, &ifi
);
1669 * This is new or refreshing failed - add to
1670 * our interface list. If refreshing failed we
1671 * will delete the interface structure in phase
1672 * 2 as the interface was not marked current.
1673 * We can bind to the address as the refresh
1674 * code already closed the offending socket
1676 iface
= create_interface(port
, &interface
);
1678 if (iface
!= NULL
) {
1679 ifi
.action
= IFS_CREATED
;
1680 ifi
.interface
= iface
;
1681 if (receiver
!= NULL
)
1682 (*receiver
)(data
, &ifi
);
1684 new_interface_found
= 1;
1687 (iface
, "updating ",
1688 " new - created\n"));
1691 (&interface
, "updating ",
1692 " new - creation FAILED"));
1695 "failed to init interface for address %s",
1696 stoa(&interface
.sin
));
1702 isc_interfaceiter_destroy(&iter
);
1705 * phase 2 - delete gone interfaces - reassigning peers to
1710 while (iface
!= NULL
) {
1713 if (!(iface
->flags
& (INT_WILDCARD
| INT_MCASTIF
))) {
1715 * if phase does not match sys_phase this
1716 * interface was not enumerated during the last
1717 * interface scan - so it is gone and will be
1718 * deleted here unless it is solely an MCAST or
1719 * WILDCARD interface.
1721 if (iface
->phase
!= sys_interphase
) {
1723 (iface
, "updating ",
1724 "GONE - deleting\n"));
1725 remove_interface(iface
);
1727 ifi
.action
= IFS_DELETED
;
1728 ifi
.interface
= iface
;
1729 if (receiver
!= NULL
)
1730 (*receiver
)(data
, &ifi
);
1733 * disconnect peers from deleted
1736 while (iface
->peers
!= NULL
)
1737 set_peerdstadr(iface
->peers
, NULL
);
1740 * update globals in case we lose
1741 * a loopback interface
1743 if (iface
== loopback_interface
)
1744 loopback_interface
= NULL
;
1746 delete_interface(iface
);
1753 * phase 3 - re-configure as the world has changed if necessary
1755 refresh_all_peerinterfaces();
1756 return new_interface_found
;
1761 * create_sockets - create a socket for each interface plus a default
1762 * socket for when we don't know where to send
1769 #ifndef HAVE_IO_COMPLETION_PORT
1771 * I/O Completion Ports don't care about the select and FD_SET
1774 FD_ZERO(&activefds
);
1777 DPRINTF(2, ("create_sockets(%d)\n", port
));
1779 create_wildcards(port
);
1781 update_interfaces(port
, NULL
, NULL
);
1784 * Now that we have opened all the sockets, turn off the reuse
1785 * flag for security.
1789 DPRINTF(2, ("create_sockets: Total interfaces = %d\n", ninterfaces
));
1795 * create_interface - create a new interface for a given prototype
1796 * binding the socket.
1798 static struct interface
*
1801 struct interface
* protot
1805 struct interface
*iface
;
1807 DPRINTF(2, ("create_interface(%s#%d)\n", stoa(&protot
->sin
),
1810 /* build an interface */
1811 iface
= new_interface(protot
);
1816 iface
->fd
= open_socket(&iface
->sin
, 0, 0, iface
);
1818 if (iface
->fd
!= INVALID_SOCKET
)
1819 list_if_listening(iface
);
1821 if ((INT_BROADCAST
& iface
->flags
)
1822 && iface
->bfd
!= INVALID_SOCKET
)
1823 msyslog(LOG_INFO
, "Listening on broadcast address %s#%d",
1824 stoa((&iface
->bcast
)), port
);
1826 if (INVALID_SOCKET
== iface
->fd
1827 && INVALID_SOCKET
== iface
->bfd
) {
1828 msyslog(LOG_ERR
, "unable to create socket on %s (%d) for %s#%d",
1831 stoa((&iface
->sin
)),
1833 delete_interface(iface
);
1838 * Blacklist our own addresses, no use talking to ourself
1840 SET_HOSTMASK(&resmask
, AF(&iface
->sin
));
1841 hack_restrict(RESTRICT_FLAGS
, &iface
->sin
, &resmask
,
1842 RESM_NTPONLY
| RESM_INTERFACE
, RES_IGNORE
);
1845 * set globals with the first found
1846 * loopback interface of the appropriate class
1848 if (NULL
== loopback_interface
&& AF_INET
== iface
->family
1849 && (INT_LOOPBACK
& iface
->flags
))
1850 loopback_interface
= iface
;
1853 * put into our interface list
1855 add_addr_to_list(&iface
->sin
, iface
);
1856 add_interface(iface
);
1858 DPRINT_INTERFACE(2, (iface
, "created ", "\n"));
1863 #ifdef SO_EXCLUSIVEADDRUSE
1875 failed
= setsockopt(fd
, SOL_SOCKET
, SO_EXCLUSIVEADDRUSE
,
1876 (char *)&one
, sizeof(one
));
1883 * Prior to Windows XP setting SO_EXCLUSIVEADDRUSE can fail with
1884 * error WSAINVAL depending on service pack level and whether
1885 * the user account is in the Administrators group. Do not
1886 * complain if it fails that way on versions prior to XP (5.1).
1888 err
= GetLastError();
1890 if (isc_win32os_versioncheck(5, 1, 0, 0) < 0 /* < 5.1/XP */
1891 && WSAEINVAL
== err
)
1897 "setsockopt(%d, SO_EXCLUSIVEADDRUSE, on): %m",
1900 #endif /* SO_EXCLUSIVEADDRUSE */
1904 * set_reuseaddr() - set/clear REUSEADDR on all sockets
1905 * NB possible hole - should we be doing this on broadcast
1913 #ifndef SO_EXCLUSIVEADDRUSE
1914 struct interface
*interf
;
1916 for (interf
= inter_list
;
1918 interf
= interf
->link
) {
1920 if (interf
->flags
& INT_WILDCARD
)
1924 * if interf->fd is INVALID_SOCKET, we might have a adapter
1925 * configured but not present
1927 DPRINTF(4, ("setting SO_REUSEADDR on %.16s@%s to %s\n",
1928 interf
->name
, stoa(&interf
->sin
),
1929 flag
? "on" : "off"));
1931 if (interf
->fd
!= INVALID_SOCKET
) {
1932 if (setsockopt(interf
->fd
, SOL_SOCKET
,
1933 SO_REUSEADDR
, (char *)&flag
,
1935 msyslog(LOG_ERR
, "set_reuseaddr: setsockopt(SO_REUSEADDR, %s) failed: %m", flag
? "on" : "off");
1939 #endif /* ! SO_EXCLUSIVEADDRUSE */
1943 * This is just a wrapper around an internal function so we can
1944 * make other changes as necessary later on
1948 struct interface
* iface
,
1952 #ifdef OPEN_BCAST_SOCKET
1953 socket_broadcast_enable(iface
, iface
->fd
, baddr
);
1957 #ifdef OPEN_BCAST_SOCKET
1959 * Enable a broadcast address to a given socket
1960 * The socket is in the inter_list all we need to do is enable
1961 * broadcasting. It is not this function's job to select the socket
1963 static isc_boolean_t
1964 socket_broadcast_enable(
1965 struct interface
* iface
,
1973 if (IS_IPV4(baddr
)) {
1974 /* if this interface can support broadcast, set SO_BROADCAST */
1975 if (setsockopt(fd
, SOL_SOCKET
, SO_BROADCAST
,
1976 (char *)&on
, sizeof(on
)))
1978 "setsockopt(SO_BROADCAST) enable failure on address %s: %m",
1981 DPRINTF(2, ("Broadcast enabled on socket %d for address %s\n",
1984 iface
->flags
|= INT_BCASTOPEN
;
1985 broadcast_client_enabled
= ISC_TRUE
;
1989 #endif /* SO_BROADCAST */
1993 * Remove a broadcast address from a given socket
1994 * The socket is in the inter_list all we need to do is disable
1995 * broadcasting. It is not this function's job to select the socket
1997 static isc_boolean_t
1998 socket_broadcast_disable(
1999 struct interface
* iface
,
2004 int off
= 0; /* This seems to be OK as an int */
2006 if (IS_IPV4(baddr
) && setsockopt(iface
->fd
, SOL_SOCKET
,
2007 SO_BROADCAST
, (char *)&off
, sizeof(off
)))
2009 "setsockopt(SO_BROADCAST) disable failure on address %s: %m",
2012 iface
->flags
&= ~INT_BCASTOPEN
;
2013 broadcast_client_enabled
= ISC_FALSE
;
2017 #endif /* SO_BROADCAST */
2020 #endif /* OPEN_BCAST_SOCKET */
2023 * return the broadcast client flag value
2026 get_broadcastclient_flag(void)
2028 return (broadcast_client_enabled
);
2031 * Check to see if the address is a multicast address
2033 static isc_boolean_t
2038 isc_boolean_t result
;
2040 #ifndef INCLUDE_IPV6_MULTICAST_SUPPORT
2042 * If we don't have IPV6 support any IPV6 addr is not multicast
2048 result
= IS_MCAST(maddr
);
2051 DPRINTF(4, ("address %s is not multicast\n",
2058 * Multicast servers need to set the appropriate Multicast interface
2059 * socket option in order for it to know which interface to use for
2060 * send the multicast packet.
2063 enable_multicast_if(
2064 struct interface
* iface
,
2069 TYPEOF_IP_MULTICAST_LOOP off
= 0;
2071 NTP_REQUIRE(AF(maddr
) == AF(&iface
->sin
));
2073 switch (AF(&iface
->sin
)) {
2076 if (setsockopt(iface
->fd
, IPPROTO_IP
, IP_MULTICAST_IF
,
2077 (void *)&NSRCADR(&iface
->sin
),
2078 sizeof(NSRCADR(&iface
->sin
)))) {
2081 "setsockopt IP_MULTICAST_IF failed: %m on socket %d, addr %s for multicast address %s",
2082 iface
->fd
, stoa(&iface
->sin
),
2086 #ifdef IP_MULTICAST_LOOP
2088 * Don't send back to itself, but allow failure to set
2090 if (setsockopt(iface
->fd
, IPPROTO_IP
,
2092 SETSOCKOPT_ARG_CAST
&off
,
2096 "setsockopt IP_MULTICAST_LOOP failed: %m on socket %d, addr %s for multicast address %s",
2097 iface
->fd
, stoa(&iface
->sin
),
2101 DPRINTF(4, ("Added IPv4 multicast interface on socket %d, addr %s for multicast address %s\n",
2102 iface
->fd
, stoa(&iface
->sin
),
2107 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2108 if (setsockopt(iface
->fd
, IPPROTO_IPV6
,
2110 (char *)&iface
->scopeid
,
2111 sizeof(iface
->scopeid
))) {
2114 "setsockopt IPV6_MULTICAST_IF failed: %m on socket %d, addr %s, scope %d for multicast address %s",
2115 iface
->fd
, stoa(&iface
->sin
),
2116 iface
->scopeid
, stoa(maddr
));
2119 #ifdef IPV6_MULTICAST_LOOP
2121 * Don't send back to itself, but allow failure to set
2123 if (setsockopt(iface
->fd
, IPPROTO_IPV6
,
2124 IPV6_MULTICAST_LOOP
,
2125 (char *) &off
, sizeof(off
))) {
2128 "setsockopt IP_MULTICAST_LOOP failed: %m on socket %d, addr %s for multicast address %s",
2129 iface
->fd
, stoa(&iface
->sin
),
2133 DPRINTF(4, ("Added IPv6 multicast interface on socket %d, addr %s, scope %d for multicast address %s\n",
2134 iface
->fd
, stoa(&iface
->sin
),
2135 iface
->scopeid
, stoa(maddr
)));
2139 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */
2146 * Add a multicast address to a given socket
2147 * The socket is in the inter_list all we need to do is enable
2148 * multicasting. It is not this function's job to select the socket
2151 static isc_boolean_t
2152 socket_multicast_enable(
2153 struct interface
* iface
,
2158 struct ip_mreq mreq
;
2159 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2160 struct ipv6_mreq mreq6
;
2163 if (find_addr_in_list(maddr
) != NULL
) {
2164 DPRINTF(4, ("socket_multicast_enable(%s): already enabled\n",
2169 switch (AF(maddr
)) {
2172 memset(&mreq
, 0, sizeof(mreq
));
2173 mreq
.imr_multiaddr
= SOCK_ADDR4(maddr
);
2174 mreq
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
2175 if (setsockopt(iface
->fd
,
2181 "setsockopt IP_ADD_MEMBERSHIP failed: %m on socket %d, addr %s for %x / %x (%s)",
2182 iface
->fd
, stoa(&iface
->sin
),
2183 mreq
.imr_multiaddr
.s_addr
,
2184 mreq
.imr_interface
.s_addr
,
2188 DPRINTF(4, ("Added IPv4 multicast membership on socket %d, addr %s for %x / %x (%s)\n",
2189 iface
->fd
, stoa(&iface
->sin
),
2190 mreq
.imr_multiaddr
.s_addr
,
2191 mreq
.imr_interface
.s_addr
, stoa(maddr
)));
2195 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2197 * Enable reception of multicast packets.
2198 * If the address is link-local we can get the
2199 * interface index from the scope id. Don't do this
2200 * for other types of multicast addresses. For now let
2201 * the kernel figure it out.
2203 memset(&mreq6
, 0, sizeof(mreq6
));
2204 mreq6
.ipv6mr_multiaddr
= SOCK_ADDR6(maddr
);
2205 mreq6
.ipv6mr_interface
= lscope
;
2207 if (setsockopt(iface
->fd
, IPPROTO_IPV6
,
2208 IPV6_JOIN_GROUP
, (char *)&mreq6
,
2211 "setsockopt IPV6_JOIN_GROUP failed: %m on socket %d, addr %s for interface %d (%s)",
2212 iface
->fd
, stoa(&iface
->sin
),
2213 mreq6
.ipv6mr_interface
, stoa(maddr
));
2216 DPRINTF(4, ("Added IPv6 multicast group on socket %d, addr %s for interface %d(%s)\n",
2217 iface
->fd
, stoa(&iface
->sin
),
2218 mreq6
.ipv6mr_interface
, stoa(maddr
)));
2221 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */
2223 iface
->flags
|= INT_MCASTOPEN
;
2225 add_addr_to_list(maddr
, iface
);
2230 * Remove a multicast address from a given socket
2231 * The socket is in the inter_list all we need to do is disable
2232 * multicasting. It is not this function's job to select the socket
2234 static isc_boolean_t
2235 socket_multicast_disable(
2236 struct interface
* iface
,
2240 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2241 struct ipv6_mreq mreq6
;
2243 struct ip_mreq mreq
;
2245 memset(&mreq
, 0, sizeof(mreq
));
2247 if (find_addr_in_list(maddr
) == NULL
) {
2248 DPRINTF(4, ("socket_multicast_disable(%s): not found\n",
2253 switch (AF(maddr
)) {
2256 mreq
.imr_multiaddr
= SOCK_ADDR4(maddr
);
2257 mreq
.imr_interface
= SOCK_ADDR4(&iface
->sin
);
2258 if (setsockopt(iface
->fd
, IPPROTO_IP
,
2259 IP_DROP_MEMBERSHIP
, (char *)&mreq
,
2263 "setsockopt IP_DROP_MEMBERSHIP failed: %m on socket %d, addr %s for %x / %x (%s)",
2264 iface
->fd
, stoa(&iface
->sin
),
2265 SRCADR(maddr
), SRCADR(&iface
->sin
),
2271 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2273 * Disable reception of multicast packets
2274 * If the address is link-local we can get the
2275 * interface index from the scope id. Don't do this
2276 * for other types of multicast addresses. For now let
2277 * the kernel figure it out.
2279 mreq6
.ipv6mr_multiaddr
= SOCK_ADDR6(maddr
);
2280 mreq6
.ipv6mr_interface
= iface
->scopeid
;
2282 if (setsockopt(iface
->fd
, IPPROTO_IPV6
,
2283 IPV6_LEAVE_GROUP
, (char *)&mreq6
,
2287 "setsockopt IPV6_LEAVE_GROUP failure: %m on socket %d, addr %s for %d (%s)",
2288 iface
->fd
, stoa(&iface
->sin
),
2289 iface
->scopeid
, stoa(maddr
));
2295 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */
2299 if (!iface
->num_mcast
)
2300 iface
->flags
&= ~INT_MCASTOPEN
;
2307 * io_setbclient - open the broadcast client sockets
2312 #ifdef OPEN_BCAST_SOCKET
2313 struct interface
* interf
;
2315 isc_boolean_t jstatus
;
2321 for (interf
= inter_list
;
2323 interf
= interf
->link
) {
2325 if (interf
->flags
& (INT_WILDCARD
| INT_LOOPBACK
))
2328 /* use only allowed addresses */
2329 if (interf
->ignore_packets
)
2333 /* Need a broadcast-capable interface */
2334 if (!(interf
->flags
& INT_BROADCAST
))
2337 /* Only IPv4 addresses are valid for broadcast */
2338 NTP_REQUIRE(IS_IPV4(&interf
->sin
));
2340 /* Do we already have the broadcast address open? */
2341 if (interf
->flags
& INT_BCASTOPEN
) {
2343 * account for already open interfaces to avoid
2344 * misleading warning below
2351 * Try to open the broadcast address
2353 interf
->family
= AF_INET
;
2354 interf
->bfd
= open_socket(&interf
->bcast
, 1, 0, interf
);
2357 * If we succeeded then we use it otherwise enable
2358 * broadcast on the interface address
2360 if (interf
->bfd
!= INVALID_SOCKET
) {
2365 jstatus
= socket_broadcast_enable(interf
, fd
,
2369 /* Enable Broadcast on socket */
2373 "io_setbclient: Opened broadcast client on interface #%d %s",
2374 interf
->ifnum
, interf
->name
);
2375 interf
->addr_refid
= addr2refid(&interf
->sin
);
2380 DPRINTF(1, ("io_setbclient: Opened broadcast clients\n"));
2383 "Unable to listen for broadcasts, no broadcast interfaces available");
2386 "io_setbclient: Broadcast Client disabled by build");
2387 #endif /* OPEN_BCAST_SOCKET */
2391 * io_unsetbclient - close the broadcast client sockets
2394 io_unsetbclient(void)
2396 struct interface
*interf
;
2398 for (interf
= inter_list
;
2400 interf
= interf
->link
)
2402 if (interf
->flags
& INT_WILDCARD
)
2405 if (!(interf
->flags
& INT_BCASTOPEN
))
2408 socket_broadcast_disable(interf
, &interf
->sin
);
2413 * io_multicast_add() - add multicast group address
2421 struct interface
*interface
;
2422 #ifndef MULTICAST_NONEWSOCKET
2423 struct interface
*iface
;
2428 * Check to see if this is a multicast address
2430 if (!addr_ismulticast(addr
))
2433 /* If we already have it we can just return */
2434 if (NULL
!= find_flagged_addr_in_list(addr
, INT_MCASTOPEN
)) {
2436 "Duplicate request found for multicast address %s",
2441 #ifndef MULTICAST_NONEWSOCKET
2442 interface
= new_interface(NULL
);
2445 * Open a new socket for the multicast address
2448 AF(&interface
->sin
) =
2449 AF(&interface
->mask
) = AF(addr
);
2450 SET_PORT(&interface
->sin
, NTP_PORT
);
2451 SET_ONESMASK(&interface
->mask
);
2456 NSRCADR(&interface
->sin
) = NSRCADR(addr
);
2460 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2461 SET_ADDR6N(&interface
->sin
, SOCK_ADDR6(addr
));
2462 lscope
= SCOPE(addr
);
2463 SET_SCOPE(&interface
->sin
, lscope
);
2465 iface
= findlocalcastinterface(addr
);
2467 DPRINTF(4, ("Found interface #%d %s, scope %d for address %s\n",
2468 iface
->ifnum
, iface
->name
, lscope
,
2473 interface
->bfd
= INVALID_SOCKET
;
2474 interface
->fd
= open_socket(&interface
->sin
, INT_MULTICAST
, 0,
2477 if (interface
->fd
!= INVALID_SOCKET
) {
2478 interface
->bfd
= INVALID_SOCKET
;
2479 interface
->ignore_packets
= ISC_FALSE
;
2480 interface
->flags
|= INT_MCASTIF
;
2482 strncpy(interface
->name
, "multicast",
2483 sizeof(interface
->name
));
2484 DPRINT_INTERFACE(2, (interface
, "multicast add ", "\n"));
2486 * socket_multicast_enable() will add this address to
2489 add_interface(interface
);
2490 list_if_listening(interface
);
2492 /* bind failed, re-use wildcard interface */
2493 delete_interface(interface
);
2496 interface
= wildipv4
;
2497 else if (IS_IPV6(addr
))
2498 interface
= wildipv6
;
2502 if (interface
!= NULL
) {
2503 /* HACK ! -- stuff in an address */
2504 /* because we don't bind addr? DH */
2505 interface
->bcast
= *addr
;
2507 "multicast address %s using wildcard interface #%d %s",
2508 stoa(addr
), interface
->ifnum
,
2512 "No multicast socket available to use for address %s",
2519 * For the case where we can't use a separate socket
2521 interface
= findlocalcastinterface(addr
);
2523 * If we don't have a valid socket, just return
2525 if (NULL
== interface
) {
2527 "Can not add multicast address %s: no multicast interface found",
2533 if (socket_multicast_enable(interface
, lscope
, addr
))
2535 "Added Multicast Listener %s on interface #%d %s",
2536 stoa(addr
), interface
->ifnum
, interface
->name
);
2538 msyslog(LOG_ERR
, "Failed to add Multicast Listener %s",
2542 "Can not add multicast address %s: no multicast support",
2550 * io_multicast_del() - delete multicast group address
2558 struct interface
*iface
;
2561 * Check to see if this is a multicast address
2563 if (!addr_ismulticast(addr
)) {
2564 msyslog(LOG_ERR
, "invalid multicast address %s",
2570 * Disable reception of multicast packets
2572 while ((iface
= find_flagged_addr_in_list(addr
, INT_MCASTOPEN
))
2574 socket_multicast_disable(iface
, addr
);
2576 delete_addr_from_list(addr
);
2578 #else /* not MCAST */
2580 "Can not delete multicast address %s: no multicast support",
2582 #endif /* not MCAST */
2587 * init_nonblocking_io() - set up descriptor to be non blocking
2589 static void init_nonblocking_io(
2598 /* in vxWorks we use FIONBIO, but the others are defined for old systems, so
2599 * all hell breaks loose if we leave them defined
2606 #if defined(O_NONBLOCK) /* POSIX */
2607 if (fcntl(fd
, F_SETFL
, O_NONBLOCK
) < 0) {
2609 "fcntl(O_NONBLOCK) fails on fd #%d: %m", fd
);
2612 #elif defined(FNDELAY)
2613 if (fcntl(fd
, F_SETFL
, FNDELAY
) < 0) {
2614 msyslog(LOG_ERR
, "fcntl(FNDELAY) fails on fd #%d: %m",
2618 #elif defined(O_NDELAY) /* generally the same as FNDELAY */
2619 if (fcntl(fd
, F_SETFL
, O_NDELAY
) < 0) {
2620 msyslog(LOG_ERR
, "fcntl(O_NDELAY) fails on fd #%d: %m",
2624 #elif defined(FIONBIO)
2628 if (ioctl(fd
, FIONBIO
, &on
) < 0) {
2630 "ioctl(FIONBIO) fails on fd #%d: %m",
2635 #elif defined(FIOSNBIO)
2636 if (ioctl(fd
, FIOSNBIO
, &on
) < 0) {
2638 "ioctl(FIOSNBIO) fails on fd #%d: %m", fd
);
2642 # include "Bletch: Need non-blocking I/O!"
2647 * open_socket - open a socket, returning the file descriptor
2655 struct interface
* interf
2662 * int is OK for REUSEADR per
2663 * http://www.kohala.com/start/mcast.api.txt
2668 if (IS_IPV6(addr
) && !ipv6_works
)
2669 return INVALID_SOCKET
;
2671 /* create a datagram (UDP) socket */
2672 fd
= socket(AF(addr
), SOCK_DGRAM
, 0);
2673 if (INVALID_SOCKET
== fd
) {
2677 errval
= WSAGetLastError();
2680 "socket(AF_INET%s, SOCK_DGRAM, 0) failed on address %s: %m",
2681 IS_IPV6(addr
) ? "6" : "", stoa(addr
));
2683 if (errval
== EPROTONOSUPPORT
||
2684 errval
== EAFNOSUPPORT
||
2685 errval
== EPFNOSUPPORT
)
2686 return (INVALID_SOCKET
);
2690 "unexpected socket() error %m code %d (not EPROTONOSUPPORT nor EAFNOSUPPORT nor EPFNOSUPPORT) - exiting",
2696 connection_reset_fix(fd
, addr
);
2699 * Fixup the file descriptor for some systems
2700 * See bug #530 for details of the issue.
2705 * set SO_REUSEADDR since we will be binding the same port
2706 * number on each interface according to turn_off_reuse.
2707 * This is undesirable on Windows versions starting with
2708 * Windows XP (numeric version 5.1).
2711 if (isc_win32os_versioncheck(5, 1, 0, 0) < 0) /* before 5.1 */
2713 if (setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
2714 (char *)((turn_off_reuse
)
2720 "setsockopt SO_REUSEADDR %s fails for address %s: %m",
2726 return INVALID_SOCKET
;
2728 #ifdef SO_EXCLUSIVEADDRUSE
2730 * setting SO_EXCLUSIVEADDRUSE on the wildcard we open
2731 * first will cause more specific binds to fail.
2733 if (!(interf
->flags
& INT_WILDCARD
))
2734 set_excladdruse(fd
);
2738 * IPv4 specific options go here
2740 if (IS_IPV4(addr
)) {
2741 #if defined(HAVE_IPTOS_SUPPORT)
2742 if (setsockopt(fd
, IPPROTO_IP
, IP_TOS
, (char *)&qos
,
2745 "setsockopt IP_TOS (%02x) fails on address %s: %m",
2747 #endif /* HAVE_IPTOS_SUPPORT */
2749 socket_broadcast_enable(interf
, fd
, addr
);
2753 * IPv6 specific options go here
2755 if (IS_IPV6(addr
)) {
2756 #if defined(IPV6_V6ONLY)
2757 if (isc_net_probe_ipv6only() == ISC_R_SUCCESS
2758 && setsockopt(fd
, IPPROTO_IPV6
, IPV6_V6ONLY
,
2759 (char*)&on
, sizeof(on
)))
2761 "setsockopt IPV6_V6ONLY on fails on address %s: %m",
2763 #endif /* IPV6_V6ONLY */
2764 #if defined(IPV6_BINDV6ONLY)
2765 if (setsockopt(fd
, IPPROTO_IPV6
, IPV6_BINDV6ONLY
,
2766 (char*)&on
, sizeof(on
)))
2768 "setsockopt IPV6_BINDV6ONLY on fails on address %s: %m",
2770 #endif /* IPV6_BINDV6ONLY */
2773 #ifdef OS_NEEDS_REUSEADDR_FOR_IFADDRBIND
2775 * some OSes don't allow binding to more specific
2776 * addresses if a wildcard address already bound
2777 * to the port and SO_REUSEADDR is not set
2779 if (!is_wildcard_addr(addr
))
2780 set_wildcard_reuse(AF(addr
), 1);
2784 * bind the local address.
2786 errval
= bind(fd
, &addr
->sa
, SOCKLEN(addr
));
2788 #ifdef OS_NEEDS_REUSEADDR_FOR_IFADDRBIND
2789 if (!is_wildcard_addr(addr
))
2790 set_wildcard_reuse(AF(addr
), 0);
2795 * Don't log this under all conditions
2797 if (turn_off_reuse
== 0
2803 snprintf(scopetext
, sizeof(scopetext
),
2804 "%%%d", SCOPE(addr
));
2809 "bind(%d) AF_INET%s %s%s#%d%s flags 0x%x failed: %m",
2810 fd
, IS_IPV6(addr
) ? "6" : "",
2811 stoa(addr
), scopetext
, SRCPORT(addr
),
2812 IS_MCAST(addr
) ? " (multicast)" : "",
2818 return INVALID_SOCKET
;
2821 #ifdef HAVE_TIMESTAMP
2823 if (setsockopt(fd
, SOL_SOCKET
, SO_TIMESTAMP
,
2824 (char*)&on
, sizeof(on
)))
2826 "setsockopt SO_TIMESTAMP on fails on address %s: %m",
2829 DPRINTF(4, ("setsockopt SO_TIMESTAMP enabled on fd %d address %s\n",
2833 DPRINTF(4, ("bind(%d) AF_INET%s, addr %s%%%d#%d, flags 0x%x\n",
2834 fd
, IS_IPV6(addr
) ? "6" : "", stoa(addr
),
2835 SCOPE(addr
), SRCPORT(addr
), interf
->flags
));
2837 init_nonblocking_io(fd
);
2839 #ifdef HAVE_SIGNALED_IO
2840 init_socket_sig(fd
);
2841 #endif /* not HAVE_SIGNALED_IO */
2843 add_fd_to_list(fd
, FD_TYPE_SOCKET
);
2845 #if !defined(SYS_WINNT) && !defined(VMS)
2846 DPRINTF(4, ("flags for fd %d: 0x%x\n", fd
,
2847 fcntl(fd
, F_GETFL
, 0)));
2848 #endif /* SYS_WINNT || VMS */
2850 #if defined (HAVE_IO_COMPLETION_PORT)
2852 * Add the socket to the completion port
2854 if (io_completion_port_add_socket(fd
, interf
)) {
2855 msyslog(LOG_ERR
, "unable to set up io completion port - EXITING");
2862 /* XXX ELIMINATE sendpkt similar in ntpq.c, ntpdc.c, ntp_io.c, ntptrace.c */
2864 * sendpkt - send a packet to the specified destination. Maintain a
2865 * send error cache so that only the first consecutive error for a
2866 * destination is logged.
2871 struct interface
*inter
,
2879 if (NULL
== inter
) {
2881 * unbound peer - drop request and wait for better
2882 * network conditions
2884 DPRINTF(2, ("%ssendpkt(dst=%s, ttl=%d, len=%d): no interface - IGNORED\n",
2885 (ttl
> 0) ? "\tMCAST\t***** " : "",
2886 stoa(dest
), ttl
, len
));
2890 DPRINTF(2, ("%ssendpkt(%d, dst=%s, src=%s, ttl=%d, len=%d)\n",
2891 (ttl
> 0) ? "\tMCAST\t***** " : "",
2892 inter
->fd
, stoa(dest
), stoa(&inter
->sin
),
2897 * for the moment we use the bcast option to set multicast ttl
2899 if (ttl
> 0 && ttl
!= inter
->last_ttl
) {
2901 * set the multicast ttl for outgoing packets
2907 switch (AF(&inter
->sin
)) {
2911 rtc
= setsockopt(inter
->fd
, IPPROTO_IP
,
2913 (void *)&cttl
, sizeof(cttl
));
2916 #ifdef INCLUDE_IPV6_SUPPORT
2919 rtc
= setsockopt(inter
->fd
, IPPROTO_IPV6
,
2920 IPV6_MULTICAST_HOPS
,
2921 (void *)&uttl
, sizeof(uttl
));
2923 #endif /* INCLUDE_IPV6_SUPPORT */
2925 default: /* just NOP if not supported */
2926 DPRINTF(1, ("sendpkt unknown AF %d",
2932 inter
->last_ttl
= ttl
;
2935 "setsockopt IP_MULTICAST_TTL/IPV6_MULTICAST_HOPS fails on address %s: %m",
2941 #if defined(HAVE_IO_COMPLETION_PORT)
2942 cc
= io_completion_port_sendto(inter
, pkt
, len
, dest
);
2943 if (cc
!= ERROR_SUCCESS
) {
2946 cc
= simulate_server(dest
, inter
, pkt
);
2948 cc
= sendto(inter
->fd
, (char *)pkt
, (unsigned int)len
, 0,
2949 (struct sockaddr
*)dest
, SOCKLEN(dest
));
2962 #if !defined(HAVE_IO_COMPLETION_PORT)
2964 * fdbits - generate ascii representation of fd_set (FAU debug support)
2965 * HFDF format - highest fd first.
2973 static char buffer
[256];
2974 char * buf
= buffer
;
2976 count
= min(count
, 255);
2978 while (count
>= 0) {
2979 *buf
++ = FD_ISSET(count
, set
) ? '#' : '-';
2988 * Routine to read the refclock packets for a specific interface
2989 * Return the number of bytes read. That way we know if we should
2990 * read it again or go on to the next one if no bytes returned
2993 read_refclock_packet(SOCKET fd
, struct refclockio
*rp
, l_fp ts
)
2997 register struct recvbuf
*rb
;
2999 rb
= get_free_recv_buffer();
3003 * No buffer space available - just drop the packet
3005 char buf
[RX_BUFF_SIZE
];
3007 buflen
= read(fd
, buf
, sizeof buf
);
3012 i
= (rp
->datalen
== 0
3013 || rp
->datalen
> sizeof(rb
->recv_space
))
3014 ? sizeof(rb
->recv_space
)
3016 buflen
= read(fd
, (char *)&rb
->recv_space
, (unsigned)i
);
3019 if (errno
!= EINTR
&& errno
!= EAGAIN
)
3020 msyslog(LOG_ERR
, "clock read fd %d: %m", fd
);
3026 * Got one. Mark how and when it got here,
3027 * put it on the full list and do bookkeeping.
3029 rb
->recv_length
= buflen
;
3030 rb
->recv_srcclock
= rp
->srcclock
;
3034 rb
->receiver
= rp
->clock_recv
;
3038 * have direct input routine for refclocks
3040 if (rp
->io_input(rb
) == 0) {
3042 * data was consumed - nothing to pass up
3043 * into block input machine
3050 add_full_recv_buffer(rb
);
3058 #ifdef HAVE_TIMESTAMP
3060 * extract timestamps from control message buffer
3064 struct recvbuf
* rb
,
3065 struct msghdr
* msghdr
,
3069 #ifdef USE_TIMESTAMP_CMSG
3070 struct cmsghdr
*cmsghdr
;
3072 cmsghdr
= CMSG_FIRSTHDR(msghdr
);
3073 while (cmsghdr
!= NULL
) {
3074 switch (cmsghdr
->cmsg_type
)
3078 struct timeval
*tvp
;
3082 tvp
= (struct timeval
*)CMSG_DATA(cmsghdr
);
3083 DPRINTF(4, ("fetch_timestamp: system network time stamp: %lld.%06ld\n",
3084 (long long)tvp
->tv_sec
, tvp
->tv_usec
));
3085 nts
.l_i
= tvp
->tv_sec
+ JAN_1970
;
3086 dtemp
= (tvp
->tv_usec
3087 + (ntp_random() * 2. / FRAC
)) / 1e6
;
3088 nts
.l_uf
= (u_int32
)(dtemp
* FRAC
);
3096 "input processing delay",
3098 DPRINTF(4, ("fetch_timestamp: timestamp delta: %s (incl. prec fuzz)\n",
3102 ts
= nts
; /* network time stamp */
3106 DPRINTF(4, ("fetch_timestamp: skipping control message 0x%x\n",
3107 cmsghdr
->cmsg_type
));
3109 cmsghdr
= CMSG_NXTHDR(msghdr
, cmsghdr
);
3118 * Routine to read the network NTP packets for a specific interface
3119 * Return the number of bytes read. That way we know if we should
3120 * read it again or go on to the next one if no bytes returned
3123 read_network_packet(
3125 struct interface
* itf
,
3129 GETSOCKNAME_SOCKLEN_TYPE fromlen
;
3131 register struct recvbuf
*rb
;
3132 #ifdef HAVE_TIMESTAMP
3133 struct msghdr msghdr
;
3135 char control
[TIMESTAMP_CTLMSGBUF_SIZE
];
3139 * Get a buffer and read the frame. If we
3140 * haven't got a buffer, or this is received
3141 * on a disallowed socket, just dump the
3145 rb
= get_free_recv_buffer();
3146 if (NULL
== rb
|| itf
->ignore_packets
) {
3147 char buf
[RX_BUFF_SIZE
];
3153 fromlen
= sizeof(from
);
3154 buflen
= recvfrom(fd
, buf
, sizeof(buf
), 0,
3155 &from
.sa
, &fromlen
);
3156 DPRINTF(4, ("%s on (%lu) fd=%d from %s\n",
3157 (itf
->ignore_packets
)
3160 free_recvbuffs(), fd
, stoa(&from
)));
3161 if (itf
->ignore_packets
)
3168 fromlen
= sizeof(rb
->recv_srcadr
);
3170 #ifndef HAVE_TIMESTAMP
3171 rb
->recv_length
= recvfrom(fd
, (char *)&rb
->recv_space
,
3172 sizeof(rb
->recv_space
), 0,
3173 &rb
->recv_srcadr
.sa
, &fromlen
);
3175 iovec
.iov_base
= &rb
->recv_space
;
3176 iovec
.iov_len
= sizeof(rb
->recv_space
);
3177 msghdr
.msg_name
= &rb
->recv_srcadr
;
3178 msghdr
.msg_namelen
= fromlen
;
3179 msghdr
.msg_iov
= &iovec
;
3180 msghdr
.msg_iovlen
= 1;
3181 msghdr
.msg_control
= (void *)&control
;
3182 msghdr
.msg_controllen
= sizeof(control
);
3183 msghdr
.msg_flags
= 0;
3184 rb
->recv_length
= recvmsg(fd
, &msghdr
, 0);
3187 buflen
= rb
->recv_length
;
3189 if (buflen
== 0 || (buflen
== -1 &&
3190 (EWOULDBLOCK
== errno
3197 } else if (buflen
< 0) {
3198 msyslog(LOG_ERR
, "recvfrom(%s) fd=%d: %m",
3199 stoa(&rb
->recv_srcadr
), fd
);
3200 DPRINTF(5, ("read_network_packet: fd=%d dropped (bad recvfrom)\n",
3206 DPRINTF(3, ("read_network_packet: fd=%d length %d from %s\n",
3207 fd
, buflen
, stoa(&rb
->recv_srcadr
)));
3210 * Got one. Mark how and when it got here,
3211 * put it on the full list and do bookkeeping.
3215 #ifdef HAVE_TIMESTAMP
3216 /* pick up a network time stamp if possible */
3217 ts
= fetch_timestamp(rb
, &msghdr
, ts
);
3220 rb
->receiver
= receive
;
3222 add_full_recv_buffer(rb
);
3231 * input_handler - receive packets asynchronously
3242 struct timeval tvzero
;
3243 l_fp ts
; /* Timestamp at BOselect() gob */
3245 l_fp ts_e
; /* Timestamp at EOselect() gob */
3248 int select_count
= 0;
3249 struct interface
*interface
;
3250 #if defined(HAS_ROUTING_SOCKET)
3251 struct asyncio_reader
*asyncio_reader
;
3257 * If we have something to do, freeze a timestamp.
3258 * See below for the other cases (nothing left to do or error)
3263 * Do a poll to see who has data
3267 tvzero
.tv_sec
= tvzero
.tv_usec
= 0;
3269 n
= select(maxactivefd
+ 1, &fds
, (fd_set
*)0, (fd_set
*)0,
3273 * If there are no packets waiting just return
3278 * extended FAU debugging output
3282 "select(%d, %s, 0L, 0L, &0.0) error: %m",
3284 fdbits(maxactivefd
, &activefds
));
3288 for (j
= 0; j
<= maxactivefd
; j
++)
3289 if ((FD_ISSET(j
, &fds
)
3290 && (read(j
, &b
, 0) == -1)))
3292 "Bad file descriptor %d",
3304 * Check out the reference clocks first, if any
3307 if (refio
!= NULL
) {
3308 register struct refclockio
*rp
;
3310 for (rp
= refio
; rp
!= NULL
; rp
= rp
->next
) {
3313 if (FD_ISSET(fd
, &fds
))
3316 buflen
= read_refclock_packet(
3318 } while (buflen
> 0);
3321 #endif /* REFCLOCK */
3324 * Loop through the interfaces looking for data to read.
3326 for (interface
= inter_list
;
3328 interface
= interface
->link
) {
3330 for (doing
= 0; (doing
< 2); doing
++) {
3334 if (!(interface
->flags
& INT_BCASTOPEN
))
3336 fd
= interface
->bfd
;
3340 if (FD_ISSET(fd
, &fds
))
3343 buflen
= read_network_packet(
3346 } while (buflen
> 0);
3347 /* Check more interfaces */
3351 #ifdef HAS_ROUTING_SOCKET
3353 * scan list of asyncio readers - currently only used for routing sockets
3355 asyncio_reader
= asyncio_reader_list
;
3357 while (asyncio_reader
!= NULL
) {
3358 if (FD_ISSET(asyncio_reader
->fd
, &fds
)) {
3360 (asyncio_reader
->receiver
)(asyncio_reader
);
3362 asyncio_reader
= asyncio_reader
->link
;
3364 #endif /* HAS_ROUTING_SOCKET */
3367 * Done everything from that select.
3371 * If nothing to do, just return.
3372 * If an error occurred, complain and return.
3374 if (select_count
== 0) { /* We really had nothing to do */
3377 msyslog(LOG_DEBUG
, "input_handler: select() returned 0");
3381 /* We've done our work */
3385 * (ts_e - ts) is the amount of time we spent
3386 * processing this gob of file descriptors. Log
3390 collect_timing(NULL
, "input handler", 1, &ts_e
);
3393 "input_handler: Processed a gob of fd's in %s msec",
3402 * findinterface - find local interface corresponding to address
3409 struct interface
*iface
;
3411 iface
= findlocalinterface(addr
, INT_WILDCARD
, 0);
3413 if (NULL
== iface
) {
3414 DPRINTF(4, ("Found no interface for address %s - returning wildcard\n",
3417 iface
= ANY_INTERFACE_CHOOSE(addr
);
3419 DPRINTF(4, ("Found interface #%d %s for address %s\n",
3420 iface
->ifnum
, iface
->name
, stoa(addr
)));
3426 * findlocalinterface - find local interface corresponding to addr,
3427 * which does not have any of flags set. If bast is nonzero, addr is
3428 * a broadcast address.
3430 * This code attempts to find the local sending address for an outgoing
3431 * address by connecting a new socket to destinationaddress:NTP_PORT
3432 * and reading the sockname of the resulting connect.
3433 * the complicated sequence simulates the routing table lookup
3434 * for to first hop without duplicating any of the routing logic into
3435 * ntpd. preferably we would have used an API call - but its not there -
3436 * so this is the best we can do here short of duplicating to entire routing
3437 * logic in ntpd which would be a silly and really unportable thing to do.
3440 static struct interface
*
3447 GETSOCKNAME_SOCKLEN_TYPE sockaddrlen
;
3448 struct interface
* iface
;
3454 DPRINTF(4, ("Finding interface for addr %s in list of addresses\n",
3457 s
= socket(AF(addr
), SOCK_DGRAM
, 0);
3458 if (INVALID_SOCKET
== s
)
3462 * If we are looking for broadcast interface we need to set this
3463 * socket to allow broadcast
3467 setsockopt(s
, SOL_SOCKET
, SO_BROADCAST
,
3468 (char *)&on
, sizeof(on
));
3471 rtn
= connect(s
, &addr
->sa
, SOCKLEN(addr
));
3472 if (SOCKET_ERROR
== rtn
) {
3477 sockaddrlen
= sizeof(saddr
);
3478 rtn
= getsockname(s
, &saddr
.sa
, &sockaddrlen
);
3481 if (SOCKET_ERROR
== rtn
)
3484 DPRINTF(4, ("findlocalinterface: kernel maps %s to %s\n",
3485 stoa(addr
), stoa(&saddr
)));
3487 iface
= getinterface(&saddr
, flags
);
3490 * if we didn't find an exact match on saddr check for an
3491 * interface on the same subnet as saddr. This handles the
3492 * case of the address suggested by the kernel being
3493 * excluded by the user's -I and -L options to ntpd, when
3494 * another address is enabled on the same subnet.
3495 * See http://bugs.ntp.org/1184 for more detail.
3497 if (NULL
== iface
|| iface
->ignore_packets
)
3498 iface
= getsamenetinterface(&saddr
, flags
);
3500 /* Don't use an interface which will ignore replies */
3501 if (iface
!= NULL
&& iface
->ignore_packets
)
3509 * fetch an interface structure the matches the
3510 * address and has the given flags NOT set
3512 static struct interface
*
3518 struct interface
*iface
;
3520 iface
= find_addr_in_list(addr
);
3522 if (iface
!= NULL
&& (iface
->flags
& flags
))
3530 * fetch an interface structure with a local address on the same subnet
3531 * as addr which has the given flags NOT set
3533 static struct interface
*
3534 getsamenetinterface(
3539 struct interface
*iface
;
3541 iface
= find_samenet_addr_in_list(addr
);
3543 if (iface
!= NULL
&& (iface
->flags
& flags
))
3551 * findlocalcastinterface - find local *cast interface for addr
3553 static struct interface
*
3554 findlocalcastinterface(
3558 struct interface
* iface
;
3559 struct interface
* nif
;
3560 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
3561 isc_boolean_t want_linklocal
;
3564 NTP_REQUIRE(addr_ismulticast(addr
));
3567 * see how kernel maps the mcast address
3569 nif
= findlocalinterface(addr
, 0, 0);
3571 if (nif
!= NULL
&& !nif
->ignore_packets
) {
3572 DPRINTF(2, ("findlocalcastinterface: kernel recommends interface #%d %s for %s\n",
3573 nif
->ifnum
, nif
->name
, stoa(addr
)));
3577 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
3578 want_linklocal
= (IN6_IS_ADDR_MC_LINKLOCAL(PSOCK_ADDR6(addr
))
3579 || IN6_IS_ADDR_MC_SITELOCAL(PSOCK_ADDR6(addr
)));
3582 for (iface
= inter_list
;
3584 iface
= iface
->link
)
3586 /* use only allowed addresses */
3587 if (iface
->ignore_packets
)
3590 /* Skip the loopback and wildcard addresses */
3591 if (iface
->flags
& (INT_LOOPBACK
| INT_WILDCARD
))
3594 /* Skip if different family */
3595 if (AF(&iface
->sin
) != AF(addr
))
3598 /* Is it multicast capable? */
3599 if (!(iface
->flags
& INT_MULTICAST
))
3602 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
3603 if (want_linklocal
&& IS_IPV6(&iface
->sin
) &&
3604 IN6_IS_ADDR_LINKLOCAL(PSOCK_ADDR6(&iface
->sin
))) {
3608 /* If we want a linklocal address, skip */
3614 } /* for loop over interfaces */
3617 DPRINTF(3, ("findlocalcastinterface: found interface #%d %s for %s\n",
3618 nif
->ifnum
, nif
->name
, stoa(addr
)));
3620 DPRINTF(3, ("findlocalcastinterface: no interface found for %s\n",
3627 * findbcastinter - find broadcast interface corresponding to address
3634 #if !defined(MPE) && (defined(SIOCGIFCONF) || defined(SYS_WINNT))
3635 struct interface
*iface
;
3638 DPRINTF(4, ("Finding broadcast/multicast interface for addr %s in list of addresses\n",
3641 iface
= findlocalinterface(addr
, INT_LOOPBACK
| INT_WILDCARD
,
3643 if (iface
!= NULL
) {
3644 DPRINTF(4, ("Easily found bcast-/mcast- interface index #%d %s\n",
3645 iface
->ifnum
, iface
->name
));
3650 * plan B - try to find something reasonable in our lists in
3651 * case kernel lookup doesn't help
3653 for (iface
= inter_list
;
3655 iface
= iface
->link
)
3657 if (iface
->flags
& INT_WILDCARD
)
3660 /* Don't bother with ignored interfaces */
3661 if (iface
->ignore_packets
)
3665 * First look if this is the correct family
3667 if(AF(&iface
->sin
) != AF(addr
))
3670 /* Skip the loopback addresses */
3671 if (iface
->flags
& INT_LOOPBACK
)
3675 * If we are looking to match a multicast address and
3676 * this interface is one...
3678 if (addr_ismulticast(addr
)
3679 && (iface
->flags
& INT_MULTICAST
)) {
3680 #ifdef INCLUDE_IPV6_SUPPORT
3682 * ...it is the winner unless we're looking for
3683 * an interface to use for link-local multicast
3684 * and its address is not link-local.
3687 && IN6_IS_ADDR_MC_LINKLOCAL(PSOCK_ADDR6(addr
))
3688 && !IN6_IS_ADDR_LINKLOCAL(PSOCK_ADDR6(&iface
->sin
)))
3695 * We match only those interfaces marked as
3696 * broadcastable and either the explicit broadcast
3697 * address or the network portion of the IP address.
3700 if (IS_IPV4(addr
)) {
3701 if (SOCK_EQ(&iface
->bcast
, addr
))
3704 if ((NSRCADR(&iface
->sin
) & NSRCADR(&iface
->mask
))
3705 == (NSRCADR(addr
) & NSRCADR(&iface
->mask
)))
3708 #ifdef INCLUDE_IPV6_SUPPORT
3709 else if(IS_IPV6(addr
)) {
3710 if (SOCK_EQ(&iface
->bcast
, addr
))
3713 if (SOCK_EQ(netof(&iface
->sin
), netof(addr
)))
3718 #endif /* SIOCGIFCONF */
3719 if (NULL
== iface
) {
3720 DPRINTF(4, ("No bcast interface found for %s\n",
3722 iface
= ANY_INTERFACE_CHOOSE(addr
);
3724 DPRINTF(4, ("Found bcast-/mcast- interface index #%d %s\n",
3725 iface
->ifnum
, iface
->name
));
3731 * io_clr_stats - clear I/O module statistics
3736 packets_dropped
= 0;
3737 packets_ignored
= 0;
3738 packets_received
= 0;
3740 packets_notsent
= 0;
3744 io_timereset
= current_time
;
3750 * io_addclock - add a reference clock to the list and arrange that we
3751 * get SIGIO interrupts from it.
3755 struct refclockio
*rio
3761 * Stuff the I/O structure in the list and mark the descriptor
3762 * in use. There is a harmless (I hope) race condition here.
3766 # ifdef HAVE_SIGNALED_IO
3767 if (init_clock_sig(rio
)) {
3771 # elif defined(HAVE_IO_COMPLETION_PORT)
3772 if (io_completion_port_add_clock_io(rio
)) {
3786 add_fd_to_list(rio
->fd
, FD_TYPE_FILE
);
3793 * io_closeclock - close the clock in the I/O structure given
3797 struct refclockio
*rio
3800 register struct refclockio
*rp
;
3805 * Remove structure from the list
3810 for (rp
= refio
; rp
!= NULL
; rp
= rp
->next
)
3811 if (rp
->next
== rio
) {
3812 rp
->next
= rio
->next
;
3823 * Close the descriptor.
3825 close_and_delete_fd_from_list(rio
->fd
);
3828 #endif /* REFCLOCK */
3831 * On NT a SOCKET is an unsigned int so we cannot possibly keep it in
3832 * an array. So we use one of the ISC_LIST functions to hold the
3833 * socket value and use that when we want to enumerate it.
3835 * This routine is called by the forked intres child process to close
3836 * all open sockets. On Windows there's no need as intres runs in
3837 * the same process as a thread.
3841 kill_asyncio(int startfd
)
3846 * In the child process we do not maintain activefds and
3847 * maxactivefd. Zeroing maxactivefd disables code which
3848 * maintains it in close_and_delete_fd_from_list().
3852 while (fd_list
!= NULL
)
3853 close_and_delete_fd_from_list(fd_list
->fd
);
3857 #endif /* !SYS_WINNT */
3860 * Add and delete functions for the list of open sockets
3868 vsock_t
*lsock
= emalloc(sizeof(*lsock
));
3873 LINK_SLIST(fd_list
, lsock
, link
);
3875 * I/O Completion Ports don't care about the select and FD_SET
3877 #ifndef HAVE_IO_COMPLETION_PORT
3878 if (fd
< 0 || fd
>= FD_SETSIZE
) {
3880 "Too many sockets in use, FD_SETSIZE %d exceeded",
3885 * keep activefds in sync
3887 maxactivefd
= max(fd
, maxactivefd
);
3889 FD_SET(fd
, &activefds
);
3894 close_and_delete_fd_from_list(
3900 UNLINK_EXPR_SLIST(lsock
, fd_list
, fd
==
3901 UNLINK_EXPR_SLIST_CURRENT()->fd
, link
, vsock_t
);
3903 if (lsock
!= NULL
) {
3904 switch (lsock
->type
) {
3905 case FD_TYPE_SOCKET
:
3906 closesocket(lsock
->fd
);
3915 "internal error - illegal descriptor type %d - EXITING",
3922 * I/O Completion Ports don't care about select and fd_set
3924 #ifndef HAVE_IO_COMPLETION_PORT
3926 * remove from activefds
3928 FD_CLR(fd
, &activefds
);
3930 if (fd
== maxactivefd
&& maxactivefd
) {
3932 NTP_INSIST(maxactivefd
- 1 < FD_SETSIZE
);
3933 for (i
= maxactivefd
- 1; i
>= 0; i
--)
3934 if (FD_ISSET(i
, &activefds
)) {
3938 NTP_INSIST(fd
!= maxactivefd
);
3947 struct interface
*interface
3953 if (find_addr_in_list(addr
) == NULL
) {
3955 /* not there yet - add to list */
3956 laddr
= emalloc(sizeof(*laddr
));
3957 memcpy(&laddr
->addr
, addr
, sizeof(laddr
->addr
));
3958 laddr
->interface
= interface
;
3960 LINK_SLIST(remoteaddr_list
, laddr
, link
);
3962 DPRINTF(4, ("Added addr %s to list of addresses\n",
3966 DPRINTF(4, ("WARNING: Attempt to add duplicate addr %s to address list\n",
3973 delete_addr_from_list(
3977 remaddr_t
*unlinked
;
3979 UNLINK_EXPR_SLIST(unlinked
, remoteaddr_list
, SOCK_EQ(addr
,
3980 &(UNLINK_EXPR_SLIST_CURRENT()->addr
)), link
, remaddr_t
);
3982 if (unlinked
!= NULL
) {
3983 DPRINTF(4, ("Deleted addr %s from list of addresses\n",
3991 delete_interface_from_list(
3992 struct interface
*iface
3995 remaddr_t
*unlinked
;
3998 UNLINK_EXPR_SLIST(unlinked
, remoteaddr_list
, iface
==
3999 UNLINK_EXPR_SLIST_CURRENT()->interface
, link
,
4002 if (unlinked
!= NULL
) {
4003 DPRINTF(4, ("Deleted addr %s for interface #%d %s from list of addresses\n",
4004 stoa(&unlinked
->addr
), iface
->ifnum
,
4006 if (addr_ismulticast(&unlinked
->addr
))
4007 /* find a new interface to use */
4008 io_multicast_add(&unlinked
->addr
);
4011 } while (unlinked
!= NULL
);
4015 static struct interface
*
4022 DPRINTF(4, ("Searching for addr %s in list of addresses - ",
4025 for (entry
= remoteaddr_list
;
4027 entry
= entry
->link
)
4028 if (SOCK_EQ(&entry
->addr
, addr
)) {
4029 DPRINTF(4, ("FOUND\n"));
4030 return entry
->interface
;
4033 DPRINTF(4, ("NOT FOUND\n"));
4037 static inline isc_boolean_t
4039 struct sockaddr_in
*addr1
,
4040 struct sockaddr_in
*mask
,
4041 struct sockaddr_in
*addr2
4044 return (addr1
->sin_addr
.s_addr
& mask
->sin_addr
.s_addr
)
4045 == (addr2
->sin_addr
.s_addr
& mask
->sin_addr
.s_addr
);
4048 #ifdef INCLUDE_IPV6_SUPPORT
4049 static inline isc_boolean_t
4051 struct sockaddr_in6
*addr1
,
4052 struct sockaddr_in6
*mask
,
4053 struct sockaddr_in6
*addr2
4059 i
< sizeof(addr1
->sin6_addr
.s6_addr
) /
4060 sizeof(addr1
->sin6_addr
.s6_addr
[0]);
4063 if ((addr1
->sin6_addr
.s6_addr
[i
] &
4064 mask
->sin6_addr
.s6_addr
[i
])
4066 (addr2
->sin6_addr
.s6_addr
[i
] &
4067 mask
->sin6_addr
.s6_addr
[i
]))
4073 #endif /* INCLUDE_IPV6_SUPPORT */
4076 static isc_boolean_t
4085 if (AF(a1
) != AF(a2
))
4087 else if (IS_IPV4(a1
))
4088 sn
= same_network_v4(&a1
->sa4
, &mask
->sa4
, &a2
->sa4
);
4089 #ifdef INCLUDE_IPV6_SUPPORT
4090 else if (IS_IPV6(a1
))
4091 sn
= same_network_v6(&a1
->sa6
, &mask
->sa6
, &a2
->sa6
);
4100 * Find an address in the list on the same network as addr which is not
4103 static struct interface
*
4104 find_samenet_addr_in_list(
4110 DPRINTF(4, ("Searching for addr with same subnet as %s in list of addresses - ",
4113 for (entry
= remoteaddr_list
;
4115 entry
= entry
->link
)
4117 if (!SOCK_EQ(addr
, &entry
->addr
)
4118 && same_network(&entry
->addr
,
4119 &entry
->interface
->mask
,
4121 DPRINTF(4, ("FOUND\n"));
4122 return entry
->interface
;
4125 DPRINTF(4, ("NOT FOUND\n"));
4131 * Find the given address with the all given flags set in the list
4133 static struct interface
*
4134 find_flagged_addr_in_list(
4141 DPRINTF(4, ("Finding addr %s with flags %d in list: ",
4142 stoa(addr
), flags
));
4144 for (entry
= remoteaddr_list
;
4146 entry
= entry
->link
)
4148 if (SOCK_EQ(&entry
->addr
, addr
)
4149 && (entry
->interface
->flags
& flags
) == flags
) {
4151 DPRINTF(4, ("FOUND\n"));
4152 return entry
->interface
;
4155 DPRINTF(4, ("NOT FOUND\n"));
4160 #ifdef HAS_ROUTING_SOCKET
4161 # ifndef UPDATE_GRACE
4162 # define UPDATE_GRACE 2 /* wait UPDATE_GRACE seconds before scanning */
4166 process_routing_msgs(struct asyncio_reader
*reader
)
4170 #ifdef HAVE_RTNETLINK
4171 struct nlmsghdr
*nh
;
4173 struct rt_msghdr
*rtm
;
4177 if (disable_dynamic_updates
) {
4179 * discard ourselves if we are not needed any more
4180 * usually happens when running unprivileged
4182 remove_asyncio_reader(reader
);
4183 delete_asyncio_reader(reader
);
4187 cnt
= read(reader
->fd
, buffer
, sizeof(buffer
));
4191 "i/o error on routing socket %m - disabling");
4192 remove_asyncio_reader(reader
);
4193 delete_asyncio_reader(reader
);
4198 * process routing message
4200 #ifdef HAVE_RTNETLINK
4201 for (nh
= (struct nlmsghdr
*)buffer
;
4203 nh
= NLMSG_NEXT(nh
, cnt
)) {
4204 msg_type
= nh
->nlmsg_type
;
4207 (p
+ sizeof(struct rt_msghdr
)) <= (buffer
+ cnt
);
4208 p
+= rtm
->rtm_msglen
) {
4209 rtm
= (struct rt_msghdr
*)p
;
4210 if (rtm
->rtm_version
!= RTM_VERSION
) {
4212 "version mismatch (got %d - expected %d) on routing socket - disabling",
4213 rtm
->rtm_version
, RTM_VERSION
);
4215 remove_asyncio_reader(reader
);
4216 delete_asyncio_reader(reader
);
4219 msg_type
= rtm
->rtm_type
;
4246 #ifdef RTM_IFANNOUNCE
4247 case RTM_IFANNOUNCE
:
4262 * we are keen on new and deleted addresses and
4263 * if an interface goes up and down or routing
4266 DPRINTF(3, ("routing message op = %d: scheduling interface update\n",
4268 timer_interfacetimeout(current_time
+ UPDATE_GRACE
);
4270 #ifdef HAVE_RTNETLINK
4272 /* end of multipart message */
4277 * the rest doesn't bother us.
4279 DPRINTF(4, ("routing message op = %d: ignored\n",
4287 * set up routing notifications
4290 init_async_notifications()
4292 struct asyncio_reader
*reader
;
4293 #ifdef HAVE_RTNETLINK
4294 int fd
= socket(PF_NETLINK
, SOCK_RAW
, NETLINK_ROUTE
);
4295 struct sockaddr_nl sa
;
4297 int fd
= socket(PF_ROUTE
, SOCK_RAW
, 0);
4301 "unable to open routing socket (%m) - using polled interface update");
4306 #ifdef HAVE_RTNETLINK
4307 memset(&sa
, 0, sizeof(sa
));
4308 sa
.nl_family
= PF_NETLINK
;
4309 sa
.nl_groups
= RTMGRP_LINK
| RTMGRP_IPV4_IFADDR
4310 | RTMGRP_IPV6_IFADDR
| RTMGRP_IPV4_ROUTE
4311 | RTMGRP_IPV4_MROUTE
| RTMGRP_IPV6_ROUTE
4312 | RTMGRP_IPV6_MROUTE
;
4313 if (bind(fd
, (struct sockaddr
*)&sa
, sizeof(sa
)) < 0) {
4315 "bind failed on routing socket (%m) - using polled interface update");
4319 init_nonblocking_io(fd
);
4320 #if defined(HAVE_SIGNALED_IO)
4321 init_socket_sig(fd
);
4322 #endif /* HAVE_SIGNALED_IO */
4324 reader
= new_asyncio_reader();
4327 reader
->receiver
= process_routing_msgs
;
4329 add_asyncio_reader(reader
, FD_TYPE_SOCKET
);
4331 "Listening on routing socket on fd #%d for interface updates",
4335 /* HAS_ROUTING_SOCKET not defined */
4337 init_async_notifications(void)