2 * ntp_io.c - input/output routines for ntpd. The socket-opening code
3 * was shamelessly stolen from ntpd.
14 # if !defined(FNM_CASEFOLD) && defined(FNM_IGNORECASE)
15 # define FNM_CASEFOLD FNM_IGNORECASE
18 #ifdef HAVE_SYS_PARAM_H
19 # include <sys/param.h>
21 #ifdef HAVE_SYS_IOCTL_H
22 # include <sys/ioctl.h>
24 #ifdef HAVE_SYS_SOCKIO_H /* UXPV: SIOC* #defines (Frank Vance <fvance@waii.com>) */
25 # include <sys/sockio.h>
31 #include "ntp_machine.h"
35 #include "ntp_lists.h"
36 #include "ntp_refclock.h"
37 #include "ntp_stdlib.h"
38 #include "ntp_worker.h"
39 #include "ntp_request.h"
40 #include "ntp_assert.h"
41 #include "timevalops.h"
42 #include "timespecops.h"
43 #include "ntpd-opts.h"
45 /* Don't include ISC's version of IPv6 variables and structures */
48 #include <isc/interfaceiter.h>
49 #include <isc/netaddr.h>
50 #include <isc/result.h>
51 #include <isc/sockaddr.h>
57 #ifdef HAS_ROUTING_SOCKET
58 # include <net/route.h>
59 # ifdef HAVE_RTNETLINK
60 # include <linux/rtnetlink.h>
66 * setsockopt does not always have the same arg declaration
67 * across all platforms. If it's not defined we make it empty
70 #ifndef SETSOCKOPT_ARG_CAST
71 #define SETSOCKOPT_ARG_CAST
74 extern int listen_to_virtual_ips;
79 typedef struct nic_rule_tag nic_rule;
83 nic_rule_action action;
84 nic_rule_match match_type;
91 * NIC rule listhead. Entries are added at the head so that the first
92 * match in the list is the last matching rule specified.
94 nic_rule *nic_rule_list;
97 #if defined(SO_BINTIME) && defined(SCM_BINTIME) && defined(CMSG_FIRSTHDR)
98 # define HAVE_PACKET_TIMESTAMP
100 # ifdef BINTIME_CTLMSGBUF_SIZE
101 # define CMSG_BUFSIZE BINTIME_CTLMSGBUF_SIZE
103 # define CMSG_BUFSIZE 1536 /* moderate default */
105 #elif defined(SO_TIMESTAMPNS) && defined(SCM_TIMESTAMPNS) && defined(CMSG_FIRSTHDR)
106 # define HAVE_PACKET_TIMESTAMP
107 # define HAVE_TIMESTAMPNS
108 # ifdef TIMESTAMPNS_CTLMSGBUF_SIZE
109 # define CMSG_BUFSIZE TIMESTAMPNS_CTLMSGBUF_SIZE
111 # define CMSG_BUFSIZE 1536 /* moderate default */
113 #elif defined(SO_TIMESTAMP) && defined(SCM_TIMESTAMP) && defined(CMSG_FIRSTHDR)
114 # define HAVE_PACKET_TIMESTAMP
115 # define HAVE_TIMESTAMP
116 # ifdef TIMESTAMP_CTLMSGBUF_SIZE
117 # define CMSG_BUFSIZE TIMESTAMP_CTLMSGBUF_SIZE
119 # define CMSG_BUFSIZE 1536 /* moderate default */
122 /* fill in for old/other timestamp interfaces */
125 #if defined(SYS_WINNT)
126 #include "win32_io.h"
127 #include <isc/win32os.h>
131 * We do asynchronous input using the SIGIO facility. A number of
132 * recvbuf buffers are preallocated for input. In the signal
133 * handler we poll to see which sockets are ready and read the
134 * packets from them into the recvbuf's along with a time stamp and
135 * an indication of the source host and the interface it was received
136 * through. This allows us to get as accurate receive time stamps
137 * as possible independent of other processing going on.
139 * We watch the number of recvbufs available to the signal handler
140 * and allocate more when this number drops below the low water
141 * mark. If the signal handler should run out of buffers in the
142 * interim it will drop incoming frames, the idea being that it is
143 * better to drop a packet than to be inaccurate.
148 * Other statistics of possible interest
150 volatile u_long packets_dropped; /* total number of packets dropped on reception */
151 volatile u_long packets_ignored; /* packets received on wild card interface */
152 volatile u_long packets_received; /* total number of packets received */
153 u_long packets_sent; /* total number of packets sent */
154 u_long packets_notsent; /* total number of packets which couldn't be sent */
156 volatile u_long handler_calls; /* number of calls to interrupt handler */
157 volatile u_long handler_pkts; /* number of pkts received by handler */
158 u_long io_timereset; /* time counters were reset */
163 endpt * any_interface; /* wildcard ipv4 interface */
164 endpt * any6_interface; /* wildcard ipv6 interface */
165 endpt * loopback_interface; /* loopback ipv4 interface */
167 isc_boolean_t broadcast_client_enabled; /* is broadcast client enabled */
168 u_int sys_ifnum; /* next .ifnum to assign */
169 int ninterfaces; /* Total number of interfaces */
171 int disable_dynamic_updates; /* scan interfaces once only */
175 * Refclock stuff. We keep a chain of structures with data concerning
176 * the guys we are doing I/O for.
178 static struct refclockio *refio;
179 #endif /* REFCLOCK */
182 * File descriptor masks etc. for call to select
183 * Not needed for I/O Completion Ports or anything outside this file
185 static fd_set activefds;
186 static int maxactivefd;
189 * bit alternating value to detect verified interfaces during an update cycle
191 static u_short sys_interphase = 0;
193 static endpt * new_interface(endpt *);
194 static void add_interface(endpt *);
195 static int update_interfaces(u_short, interface_receiver_t,
197 static void remove_interface(endpt *);
198 static endpt * create_interface(u_short, endpt *);
200 static int is_wildcard_addr (const sockaddr_u *);
203 * Multicast functions
205 static isc_boolean_t addr_ismulticast (sockaddr_u *);
206 static isc_boolean_t is_not_bindable (sockaddr_u *,
210 * Not all platforms support multicast
213 static isc_boolean_t socket_multicast_enable (endpt *, sockaddr_u *);
214 static isc_boolean_t socket_multicast_disable(endpt *, sockaddr_u *);
218 static void interface_dump (const endpt *);
219 static void sockaddr_dump (const sockaddr_u *);
220 static void print_interface (const endpt *, const char *, const char *);
221 #define DPRINT_INTERFACE(level, args) do { if (debug >= (level)) { print_interface args; } } while (0)
223 #define DPRINT_INTERFACE(level, args) do {} while (0)
226 typedef struct vsock vsock_t;
227 enum desc_type { FD_TYPE_SOCKET, FD_TYPE_FILE };
237 #if !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET)
239 * async notification processing (e. g. routing sockets)
242 * support for receiving data on fd that is not a refclock or a socket
243 * like e. g. routing sockets
245 struct asyncio_reader {
246 struct asyncio_reader *link; /* the list this is being kept in */
247 SOCKET fd; /* fd to be read */
248 void *data; /* possibly local data */
249 void (*receiver)(struct asyncio_reader *); /* input handler */
252 struct asyncio_reader *asyncio_reader_list;
254 static void delete_asyncio_reader (struct asyncio_reader *);
255 static struct asyncio_reader *new_asyncio_reader (void);
256 static void add_asyncio_reader (struct asyncio_reader *, enum desc_type);
257 static void remove_asyncio_reader (struct asyncio_reader *);
259 #endif /* !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET) */
261 static void init_async_notifications (void);
263 static int addr_eqprefix (const sockaddr_u *, const sockaddr_u *,
265 static int addr_samesubnet (const sockaddr_u *, const sockaddr_u *,
266 const sockaddr_u *, const sockaddr_u *);
267 static int create_sockets (u_short);
268 static SOCKET open_socket (sockaddr_u *, int, int, endpt *);
269 static char * fdbits (int, fd_set *);
270 static void set_reuseaddr (int);
271 static isc_boolean_t socket_broadcast_enable (struct interface *, SOCKET, sockaddr_u *);
272 #ifdef OS_MISSES_SPECIFIC_ROUTE_UPDATES
273 static isc_boolean_t socket_broadcast_disable (struct interface *, sockaddr_u *);
276 typedef struct remaddr remaddr_t;
284 remaddr_t * remoteaddr_list;
285 endpt * ep_list; /* complete endpt list */
286 endpt * mc4_list; /* IPv4 mcast-capable unicast endpts */
287 endpt * mc6_list; /* IPv6 mcast-capable unicast endpts */
289 static endpt * wildipv4;
290 static endpt * wildipv6;
293 int accept_wildcard_if_for_winnt;
295 const int accept_wildcard_if_for_winnt = FALSE;
298 static void add_fd_to_list (SOCKET, enum desc_type);
299 static endpt * find_addr_in_list (sockaddr_u *);
300 static endpt * find_flagged_addr_in_list(sockaddr_u *, u_int32);
301 static void delete_addr_from_list (sockaddr_u *);
302 static void delete_interface_from_list(endpt *);
303 static void close_and_delete_fd_from_list(SOCKET);
304 static void add_addr_to_list (sockaddr_u *, endpt *);
305 static void create_wildcards (u_short);
306 static endpt * findlocalinterface (sockaddr_u *, int, int);
307 static endpt * findclosestinterface (sockaddr_u *, int);
309 static const char * action_text (nic_rule_action);
311 static nic_rule_action interface_action(char *, sockaddr_u *, u_int32);
312 static void convert_isc_if (isc_interface_t *,
314 static void calc_addr_distance(sockaddr_u *,
317 static int cmp_addr_distance(const sockaddr_u *,
321 * Routines to read the ntp packets
323 #if !defined(HAVE_IO_COMPLETION_PORT)
324 static inline int read_network_packet (SOCKET, struct interface *, l_fp);
325 static void ntpd_addremove_io_fd (int, int, int);
326 static input_handler_t input_handler;
328 static inline int read_refclock_packet (SOCKET, struct refclockio *, l_fp);
334 #ifndef HAVE_IO_COMPLETION_PORT
343 if (fd < 0 || fd >= FD_SETSIZE) {
345 "Too many sockets in use, FD_SETSIZE %d exceeded by fd %d",
351 FD_SET(fd, &activefds);
352 maxactivefd = max(fd, maxactivefd);
354 FD_CLR(fd, &activefds);
355 if (maxactivefd && fd == maxactivefd) {
356 for (i = maxactivefd - 1; i >= 0; i--)
357 if (FD_ISSET(i, &activefds)) {
361 NTP_INSIST(fd != maxactivefd);
365 #endif /* !HAVE_IO_COMPLETION_PORT */
370 * collect timing information for various processing
371 * paths. currently we only pass them on to the file
372 * for later processing. this could also do histogram
373 * based analysis in other to reduce the load (and skew)
374 * dur to the file output
377 collect_timing(struct recvbuf *rb, const char *tag, int count, l_fp *dts)
381 snprintf(buf, sizeof(buf), "%s %d %s %s",
383 ? ((rb->dstadr != NULL)
384 ? stoa(&rb->recv_srcadr)
387 count, lfptoa(dts, 9), tag);
388 record_timing_stats(buf);
393 * About dynamic interfaces, sockets, reception and more...
395 * the code solves following tasks:
397 * - keep a current list of active interfaces in order
398 * to bind to to the interface address on NTP_PORT so that
399 * all wild and specific bindings for NTP_PORT are taken by ntpd
400 * to avoid other daemons messing with the time or sockets.
401 * - all interfaces keep a list of peers that are referencing
402 * the interface in order to quickly re-assign the peers to
403 * new interface in case an interface is deleted (=> gone from system or
405 * - have a preconfigured socket ready with the right local address
406 * for transmission and reception
407 * - have an address list for all destination addresses used within ntpd
408 * to find the "right" preconfigured socket.
409 * - facilitate updating the internal interface list with respect to
410 * the current kernel state
414 * - mapping of multicast addresses to the interface affected is not always
415 * one to one - especially on hosts with multiple interfaces
416 * the code here currently allocates a separate interface entry for those
417 * multicast addresses
418 * iff it is able to bind to a *new* socket with the multicast address (flags |= MCASTIF)
419 * in case of failure the multicast address is bound to an existing interface.
420 * - on some systems it is perfectly legal to assign the same address to
421 * multiple interfaces. Therefore this code does not keep a list of interfaces
422 * but a list of interfaces that represent a unique address as determined by the kernel
423 * by the procedure in findlocalinterface. Thus it is perfectly legal to see only
424 * one representative of a group of real interfaces if they share the same address.
426 * Frank Kardel 20050910
430 * init_io - initialize I/O module.
435 /* Init buffer free list and stat counters */
436 init_recvbuff(RECV_INIT);
437 /* update interface every 5 minutes as default */
438 interface_interval = 300;
441 addremove_io_fd = &ntpd_addremove_io_fd;
445 init_io_completion_port();
448 #if defined(HAVE_SIGNALED_IO)
449 (void) set_signal(input_handler);
455 ntpd_addremove_io_fd(
463 #ifdef HAVE_SIGNALED_IO
465 #endif /* not HAVE_SIGNALED_IO */
467 maintain_activefds(fd, remove_it);
472 * io_open_sockets - call socket creation routine
475 io_open_sockets(void)
477 static int already_opened;
479 if (already_opened || HAVE_OPT( SAVECONFIGQUIT ))
488 create_sockets(NTP_PORT);
491 init_async_notifications();
493 DPRINTF(3, ("io_open_sockets: maxactivefd %d\n", maxactivefd));
499 * function to dump the contents of the interface structure
500 * for debugging use only.
503 interface_dump(const endpt *itf)
505 printf("Dumping interface: %p\n", itf);
506 printf("fd = %d\n", itf->fd);
507 printf("bfd = %d\n", itf->bfd);
508 printf("sin = %s,\n", stoa(&itf->sin));
509 sockaddr_dump(&itf->sin);
510 printf("bcast = %s,\n", stoa(&itf->bcast));
511 sockaddr_dump(&itf->bcast);
512 printf("mask = %s,\n", stoa(&itf->mask));
513 sockaddr_dump(&itf->mask);
514 printf("name = %s\n", itf->name);
515 printf("flags = 0x%08x\n", itf->flags);
516 printf("last_ttl = %d\n", itf->last_ttl);
517 printf("addr_refid = %08x\n", itf->addr_refid);
518 printf("num_mcast = %d\n", itf->num_mcast);
519 printf("received = %ld\n", itf->received);
520 printf("sent = %ld\n", itf->sent);
521 printf("notsent = %ld\n", itf->notsent);
522 printf("ifindex = %u\n", itf->ifindex);
523 printf("peercnt = %u\n", itf->peercnt);
524 printf("phase = %u\n", itf->phase);
528 * sockaddr_dump - hex dump the start of a sockaddr_u
531 sockaddr_dump(const sockaddr_u *psau)
533 /* Limit the size of the sockaddr_in6 hex dump */
534 const int maxsize = min(32, sizeof(psau->sa6));
538 /* XXX: Should we limit maxsize based on psau->saX.sin_family? */
539 cp = (const void *)&psau->sa6;
541 for(i = 0; i < maxsize; i++) {
542 printf("%02x", *cp++);
550 * print_interface - helper to output debug information
553 print_interface(const endpt *iface, const char *pfx, const char *sfx)
555 printf("%sinterface #%d: fd=%d, bfd=%d, name=%s, flags=0x%x, ifindex=%u, sin=%s",
564 if (AF_INET == iface->family) {
565 if (iface->flags & INT_BROADCAST)
566 printf(", bcast=%s", stoa(&iface->bcast));
567 printf(", mask=%s", stoa(&iface->mask));
570 (iface->ignore_packets)
574 if (debug > 4) /* in-depth debugging only */
575 interface_dump(iface);
579 #if !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET)
581 * create an asyncio_reader structure
583 static struct asyncio_reader *
584 new_asyncio_reader(void)
586 struct asyncio_reader *reader;
588 reader = emalloc_zero(sizeof(*reader));
589 reader->fd = INVALID_SOCKET;
598 delete_asyncio_reader(
599 struct asyncio_reader *reader
606 * add asynchio_reader
610 struct asyncio_reader * reader,
613 LINK_SLIST(asyncio_reader_list, reader, link);
614 add_fd_to_list(reader->fd, type);
618 * remove asynchio_reader
621 remove_asyncio_reader(
622 struct asyncio_reader *reader
625 struct asyncio_reader *unlinked;
627 UNLINK_SLIST(unlinked, asyncio_reader_list, reader, link,
628 struct asyncio_reader);
630 if (reader->fd != INVALID_SOCKET)
631 close_and_delete_fd_from_list(reader->fd);
633 reader->fd = INVALID_SOCKET;
635 #endif /* !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET) */
638 /* compare two sockaddr prefixes */
641 const sockaddr_u * a,
642 const sockaddr_u * b,
648 isc_sockaddr_t isc_sa;
651 memcpy(&isc_sa.type, a, min(sizeof(isc_sa.type), sizeof(*a)));
652 isc_netaddr_fromsockaddr(&isc_a, &isc_sa);
655 memcpy(&isc_sa.type, b, min(sizeof(isc_sa.type), sizeof(*b)));
656 isc_netaddr_fromsockaddr(&isc_b, &isc_sa);
658 return (int)isc_netaddr_eqprefix(&isc_a, &isc_b,
665 const sockaddr_u * a,
666 const sockaddr_u * a_mask,
667 const sockaddr_u * b,
668 const sockaddr_u * b_mask
672 const u_int32 * pa_limit;
677 NTP_REQUIRE(AF(a) == AF(a_mask));
678 NTP_REQUIRE(AF(b) == AF(b_mask));
680 * With address and mask families verified to match, comparing
681 * the masks also validates the address's families match.
683 if (!SOCK_EQ(a_mask, b_mask))
687 loops = sizeof(NSRCADR6(a)) / sizeof(*pa);
688 pa = (const void *)&NSRCADR6(a);
689 pb = (const void *)&NSRCADR6(b);
690 pm = (const void *)&NSRCADR6(a_mask);
692 loops = sizeof(NSRCADR(a)) / sizeof(*pa);
693 pa = (const void *)&NSRCADR(a);
694 pb = (const void *)&NSRCADR(b);
695 pm = (const void *)&NSRCADR(a_mask);
697 for (pa_limit = pa + loops; pa < pa_limit; pa++, pb++, pm++)
698 if ((*pa & *pm) != (*pb & *pm))
706 * Code to tell if we have an IP address
707 * If we have then return the sockaddr structure
708 * and set the return value
709 * see the bind9/getaddresses.c for details
719 struct addrinfo hints;
720 struct addrinfo *result;
721 struct sockaddr_in6 *resaddr6;
725 NTP_REQUIRE(host != NULL);
726 NTP_REQUIRE(addr != NULL);
731 * Try IPv4, then IPv6. In order to handle the extended format
732 * for IPv6 scoped addresses (address%scope_ID), we'll use a local
733 * working buffer of 128 bytes. The length is an ad-hoc value, but
734 * should be enough for this purpose; the buffer can contain a string
735 * of at least 80 bytes for scope_ID in addition to any IPv6 numeric
736 * addresses (up to 46 bytes), the delimiter character and the
737 * terminating NULL character.
739 if (AF_UNSPEC == af || AF_INET == af)
740 if (inet_pton(AF_INET, host, &in4) == 1) {
742 SET_ADDR4N(addr, in4.s_addr);
747 if (AF_UNSPEC == af || AF_INET6 == af)
748 if (sizeof(tmpbuf) > strlen(host)) {
749 if ('[' == host[0]) {
750 strlcpy(tmpbuf, &host[1], sizeof(tmpbuf));
751 pch = strchr(tmpbuf, ']');
755 strlcpy(tmpbuf, host, sizeof(tmpbuf));
758 hints.ai_family = AF_INET6;
759 hints.ai_flags |= AI_NUMERICHOST;
760 if (getaddrinfo(tmpbuf, NULL, &hints, &result) == 0) {
762 resaddr6 = (struct sockaddr_in6 *)result->ai_addr;
763 SET_ADDR6N(addr, resaddr6->sin6_addr);
764 SET_SCOPE(addr, resaddr6->sin6_scope_id);
766 freeaddrinfo(result);
771 * If we got here it was not an IP address
778 * interface list enumerator - visitor pattern
782 interface_receiver_t receiver,
786 interface_info_t ifi;
788 ifi.action = IFS_EXISTS;
789 for (ifi.ep = ep_list; ifi.ep != NULL; ifi.ep = ifi.ep->elink)
790 (*receiver)(data, &ifi);
794 * do standard initialization of interface structure
802 ep->fd = INVALID_SOCKET;
803 ep->bfd = INVALID_SOCKET;
804 ep->phase = sys_interphase;
809 * create new interface structure initialize from
810 * template structure or via standard initialization
813 static struct interface *
815 struct interface *interface
818 struct interface * iface;
820 iface = emalloc(sizeof(*iface));
822 if (NULL == interface)
823 init_interface(iface);
824 else /* use the template */
825 memcpy(iface, interface, sizeof(*iface));
827 /* count every new instance of an interface in the system */
828 iface->ifnum = sys_ifnum++;
829 iface->starttime = current_time;
836 * return interface storage into free memory pool
848 * link interface into list of known interfaces
855 endpt ** pmclisthead;
863 int ep_univ_iid; /* iface ID from MAC address */
864 int scan_univ_iid; /* see RFC 4291 */
865 int ep_privacy; /* random local iface ID */
866 int scan_privacy; /* see RFC 4941 */
869 /* Calculate the refid */
870 ep->addr_refid = addr2refid(&ep->sin);
871 /* link at tail so ntpdc -c ifstats index increases each row */
872 LINK_TAIL_SLIST(ep_list, ep, elink, endpt);
875 /* the rest is for enabled multicast-capable addresses only */
876 if (ep->ignore_packets || !(INT_MULTICAST & ep->flags) ||
877 INT_LOOPBACK & ep->flags)
879 # ifndef INCLUDE_IPV6_MULTICAST_SUPPORT
880 if (AF_INET6 == ep->family)
883 pmclisthead = (AF_INET == ep->family)
887 if (AF_INET6 == ep->family) {
889 IN6_IS_ADDR_LINKLOCAL(PSOCK_ADDR6(&ep->sin)) ||
890 IN6_IS_ADDR_SITELOCAL(PSOCK_ADDR6(&ep->sin));
891 ep_univ_iid = IS_IID_UNIV(&ep->sin);
892 ep_privacy = !!(INT_PRIVACY & ep->flags);
898 DPRINTF(4, ("add_interface mcast-capable %s%s%s%s\n",
900 (ep_local) ? " link/scope-local" : "",
901 (ep_univ_iid) ? " univ-IID" : "",
902 (ep_privacy) ? " privacy" : ""));
904 * If we have multiple local addresses on the same network
905 * interface, and some are link- or site-local, do not multicast
906 * out from the link-/site-local addresses by default, to avoid
907 * duplicate manycastclient associations between v6 peers using
908 * link-local and global addresses. link-local can still be
909 * chosen using "nic ignore myv6globalprefix::/64".
910 * Similarly, if we have multiple global addresses from the same
911 * prefix on the same network interface, multicast from one,
912 * preferring EUI-64, then static, then least RFC 4941 privacy
915 for (scan = *pmclisthead; scan != NULL; scan = scan_next) {
916 scan_next = scan->mclink;
917 if (ep->family != scan->family)
919 if (strcmp(ep->name, scan->name))
921 same_subnet = addr_samesubnet(&ep->sin, &ep->mask,
922 &scan->sin, &scan->mask);
923 if (AF_INET6 == ep->family) {
926 IN6_IS_ADDR_LINKLOCAL(PSOCK_ADDR6(addr)) ||
927 IN6_IS_ADDR_SITELOCAL(PSOCK_ADDR6(addr));
928 scan_univ_iid = IS_IID_UNIV(addr);
929 scan_privacy = !!(INT_PRIVACY & scan->flags);
932 scan_univ_iid = FALSE;
933 scan_privacy = FALSE;
935 DPRINTF(4, ("add_interface mcast-capable scan %s%s%s%s\n",
937 (scan_local) ? " link/scope-local" : "",
938 (scan_univ_iid) ? " univ-IID" : "",
939 (scan_privacy) ? " privacy" : ""));
940 if ((ep_local && !scan_local) || (same_subnet &&
941 ((ep_privacy && !scan_privacy) ||
942 (!ep_univ_iid && scan_univ_iid)))) {
943 DPRINTF(4, ("did not add %s to %s of IPv6 multicast-capable list which already has %s\n",
951 if ((scan_local && !ep_local) || (same_subnet &&
952 ((scan_privacy && !ep_privacy) ||
953 (!scan_univ_iid && ep_univ_iid)))) {
954 UNLINK_SLIST(unlinked, *pmclisthead,
955 scan, mclink, endpt);
956 DPRINTF(4, ("%s %s from IPv6 multicast-capable list to add %s\n",
960 stoa(&scan->sin), stoa(&ep->sin)));
964 * Add link/site local at the tail of the multicast-
965 * capable unicast interfaces list, so that ntpd will
966 * send from global addresses before link-/site-local
970 LINK_TAIL_SLIST(*pmclisthead, ep, mclink, endpt);
972 LINK_SLIST(*pmclisthead, ep, mclink);
973 DPRINTF(4, ("added %s to %s of IPv%s multicast-capable unicast local address list\n",
978 (AF_INET == ep->family)
982 if (INVALID_SOCKET == ep->fd)
986 * select the local address from which to send to multicast.
988 switch (AF(&ep->sin)) {
991 rc = setsockopt(ep->fd, IPPROTO_IP,
993 (void *)&NSRCADR(&ep->sin),
994 sizeof(NSRCADR(&ep->sin)));
997 "setsockopt IP_MULTICAST_IF %s fails: %m",
1001 # ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
1003 rc = setsockopt(ep->fd, IPPROTO_IPV6,
1005 (void *)&ep->ifindex,
1006 sizeof(ep->ifindex));
1007 /* do not complain if bound addr scope is ifindex */
1008 if (rc && ep->ifindex != SCOPE(&ep->sin))
1010 "setsockopt IPV6_MULTICAST_IF %u for %s fails: %m",
1011 ep->ifindex, stoa(&ep->sin));
1020 * remove interface from known interface list and clean up
1021 * associated resources
1029 endpt ** pmclisthead;
1032 UNLINK_SLIST(unlinked, ep_list, ep, elink, endpt);
1033 if (!ep->ignore_packets && INT_MULTICAST & ep->flags) {
1034 pmclisthead = (AF_INET == ep->family)
1037 UNLINK_SLIST(unlinked, *pmclisthead, ep, mclink, endpt);
1038 DPRINTF(4, ("%s %s IPv%s multicast-capable unicast local address list\n",
1043 (AF_INET == ep->family)
1047 delete_interface_from_list(ep);
1049 if (ep->fd != INVALID_SOCKET) {
1051 "Deleting interface #%d %s, %s#%d, interface stats: received=%ld, sent=%ld, dropped=%ld, active_time=%ld secs",
1059 current_time - ep->starttime);
1060 close_and_delete_fd_from_list(ep->fd);
1061 ep->fd = INVALID_SOCKET;
1064 if (ep->bfd != INVALID_SOCKET) {
1066 "stop listening for broadcasts to %s on interface #%d %s",
1067 stoa(&ep->bcast), ep->ifnum, ep->name);
1068 close_and_delete_fd_from_list(ep->bfd);
1069 ep->bfd = INVALID_SOCKET;
1070 ep->flags &= ~INT_BCASTOPEN;
1074 mon_clearinterface(ep);
1076 /* remove restrict interface entry */
1077 SET_HOSTMASK(&resmask, AF(&ep->sin));
1078 hack_restrict(RESTRICT_REMOVEIF, &ep->sin, &resmask,
1079 RESM_NTPONLY | RESM_INTERFACE, RES_IGNORE, 0);
1088 msyslog(LOG_INFO, "%s on %d %s %s",
1089 (ep->ignore_packets)
1091 : "Listen normally",
1104 #ifdef INCLUDE_IPV6_SUPPORT
1107 sockaddr_u wildaddr;
1108 nic_rule_action action;
1109 struct interface * wildif;
1112 * silence "potentially uninitialized" warnings from VC9
1113 * failing to follow the logic. Ideally action could remain
1114 * uninitialized, and the memset be the first statement under
1115 * the first if (v4wild).
1117 action = ACTION_LISTEN;
1120 #ifdef INCLUDE_IPV6_SUPPORT
1122 * create pseudo-interface with wildcard IPv6 address
1124 v6wild = ipv6_works;
1126 /* set wildaddr to the v6 wildcard address :: */
1128 AF(&wildaddr) = AF_INET6;
1129 SET_ADDR6N(&wildaddr, in6addr_any);
1130 SET_PORT(&wildaddr, port);
1131 SET_SCOPE(&wildaddr, 0);
1133 /* check for interface/nic rules affecting the wildcard */
1134 action = interface_action(NULL, &wildaddr, 0);
1135 v6wild = (ACTION_IGNORE != action);
1138 wildif = new_interface(NULL);
1140 strlcpy(wildif->name, "v6wildcard", sizeof(wildif->name));
1141 memcpy(&wildif->sin, &wildaddr, sizeof(wildif->sin));
1142 wildif->family = AF_INET6;
1143 AF(&wildif->mask) = AF_INET6;
1144 SET_ONESMASK(&wildif->mask);
1146 wildif->flags = INT_UP | INT_WILDCARD;
1147 wildif->ignore_packets = (ACTION_DROP == action);
1149 wildif->fd = open_socket(&wildif->sin, 0, 1, wildif);
1151 if (wildif->fd != INVALID_SOCKET) {
1153 any6_interface = wildif;
1154 add_addr_to_list(&wildif->sin, wildif);
1155 add_interface(wildif);
1156 log_listen_address(wildif);
1159 "unable to bind to wildcard address %s - another process may be running - EXITING",
1160 stoa(&wildif->sin));
1163 DPRINT_INTERFACE(2, (wildif, "created ", "\n"));
1168 * create pseudo-interface with wildcard IPv4 address
1170 v4wild = ipv4_works;
1172 /* set wildaddr to the v4 wildcard address 0.0.0.0 */
1173 AF(&wildaddr) = AF_INET;
1174 SET_ADDR4N(&wildaddr, INADDR_ANY);
1175 SET_PORT(&wildaddr, port);
1177 /* check for interface/nic rules affecting the wildcard */
1178 action = interface_action(NULL, &wildaddr, 0);
1179 v4wild = (ACTION_IGNORE != action);
1182 wildif = new_interface(NULL);
1184 strlcpy(wildif->name, "v4wildcard", sizeof(wildif->name));
1185 memcpy(&wildif->sin, &wildaddr, sizeof(wildif->sin));
1186 wildif->family = AF_INET;
1187 AF(&wildif->mask) = AF_INET;
1188 SET_ONESMASK(&wildif->mask);
1190 wildif->flags = INT_BROADCAST | INT_UP | INT_WILDCARD;
1191 wildif->ignore_packets = (ACTION_DROP == action);
1194 * enable multicast reception on the broadcast socket
1196 AF(&wildif->bcast) = AF_INET;
1197 SET_ADDR4N(&wildif->bcast, INADDR_ANY);
1198 SET_PORT(&wildif->bcast, port);
1200 wildif->fd = open_socket(&wildif->sin, 0, 1, wildif);
1202 if (wildif->fd != INVALID_SOCKET) {
1204 any_interface = wildif;
1206 add_addr_to_list(&wildif->sin, wildif);
1207 add_interface(wildif);
1208 log_listen_address(wildif);
1211 "unable to bind to wildcard address %s - another process may be running - EXITING",
1212 stoa(&wildif->sin));
1215 DPRINT_INTERFACE(2, (wildif, "created ", "\n"));
1221 * add_nic_rule() -- insert a rule entry at the head of nic_rule_list.
1225 nic_rule_match match_type,
1226 const char * if_name, /* interface name or numeric address */
1228 nic_rule_action action
1232 isc_boolean_t is_ip;
1234 rule = emalloc_zero(sizeof(*rule));
1235 rule->match_type = match_type;
1236 rule->prefixlen = prefixlen;
1237 rule->action = action;
1239 if (MATCH_IFNAME == match_type) {
1240 NTP_REQUIRE(NULL != if_name);
1241 rule->if_name = estrdup(if_name);
1242 } else if (MATCH_IFADDR == match_type) {
1243 NTP_REQUIRE(NULL != if_name);
1244 /* set rule->addr */
1245 is_ip = is_ip_address(if_name, AF_UNSPEC, &rule->addr);
1248 NTP_REQUIRE(NULL == if_name);
1250 LINK_SLIST(nic_rule_list, rule, next);
1257 nic_rule_action action
1265 t = "ERROR"; /* quiet uninit warning */
1266 DPRINTF(1, ("fatal: unknown nic_rule_action %d\n",
1289 static nic_rule_action
1292 sockaddr_u * if_addr,
1300 DPRINTF(4, ("interface_action: interface %s ",
1301 (if_name != NULL) ? if_name : "wildcard"));
1303 iswildcard = is_wildcard_addr(if_addr);
1304 isloopback = !!(INT_LOOPBACK & if_flags);
1307 * Find any matching NIC rule from --interface / -I or ntp.conf
1308 * interface/nic rules.
1310 for (rule = nic_rule_list; rule != NULL; rule = rule->next) {
1312 switch (rule->match_type) {
1315 /* loopback and wildcard excluded from "all" */
1316 if (isloopback || iswildcard)
1318 DPRINTF(4, ("nic all %s\n",
1319 action_text(rule->action)));
1320 return rule->action;
1323 if (IS_IPV4(if_addr)) {
1324 DPRINTF(4, ("nic ipv4 %s\n",
1325 action_text(rule->action)));
1326 return rule->action;
1331 if (IS_IPV6(if_addr)) {
1332 DPRINTF(4, ("nic ipv6 %s\n",
1333 action_text(rule->action)));
1334 return rule->action;
1338 case MATCH_WILDCARD:
1340 DPRINTF(4, ("nic wildcard %s\n",
1341 action_text(rule->action)));
1342 return rule->action;
1347 if (rule->prefixlen != -1) {
1348 if (addr_eqprefix(if_addr, &rule->addr,
1351 DPRINTF(4, ("subnet address match - %s\n",
1352 action_text(rule->action)));
1353 return rule->action;
1356 if (SOCK_EQ(if_addr, &rule->addr)) {
1358 DPRINTF(4, ("address match - %s\n",
1359 action_text(rule->action)));
1360 return rule->action;
1366 #if defined(HAVE_FNMATCH) && defined(FNM_CASEFOLD)
1367 && !fnmatch(rule->if_name, if_name, FNM_CASEFOLD)
1369 && !strcasecmp(if_name, rule->if_name)
1373 DPRINTF(4, ("interface name match - %s\n",
1374 action_text(rule->action)));
1375 return rule->action;
1382 * Unless explicitly disabled such as with "nic ignore ::1"
1383 * listen on loopback addresses. Since ntpq and ntpdc query
1384 * "localhost" by default, which typically resolves to ::1 and
1385 * 127.0.0.1, it's useful to default to listening on both.
1388 DPRINTF(4, ("default loopback listen\n"));
1389 return ACTION_LISTEN;
1393 * Treat wildcard addresses specially. If there is no explicit
1394 * "nic ... wildcard" or "nic ... 0.0.0.0" or "nic ... ::" rule
1398 DPRINTF(4, ("default wildcard drop\n"));
1403 * Check for "virtual IP" (colon in the interface name) after
1404 * the rules so that "ntpd --interface eth0:1 -novirtualips"
1405 * does indeed listen on eth0:1's addresses.
1407 if (!listen_to_virtual_ips && if_name != NULL
1408 && (strchr(if_name, ':') != NULL)) {
1410 DPRINTF(4, ("virtual ip - ignore\n"));
1411 return ACTION_IGNORE;
1415 * If there are no --interface/-I command-line options and no
1416 * interface/nic rules in ntp.conf, the default action is to
1417 * listen. In the presence of rules from either, the default
1418 * is to ignore. This implements ntpd's traditional listen-
1419 * every default with no interface listen configuration, and
1420 * ensures a single -I eth0 or "nic listen eth0" means do not
1421 * listen on any other addresses.
1423 if (NULL == nic_rule_list) {
1424 DPRINTF(4, ("default listen\n"));
1425 return ACTION_LISTEN;
1428 DPRINTF(4, ("implicit ignore\n"));
1429 return ACTION_IGNORE;
1435 isc_interface_t *isc_if,
1440 const u_char v6loop[16] = {0, 0, 0, 0, 0, 0, 0, 0,
1441 0, 0, 0, 0, 0, 0, 0, 1};
1443 strlcpy(itf->name, isc_if->name, sizeof(itf->name));
1444 itf->ifindex = isc_if->ifindex;
1445 itf->family = (u_short)isc_if->af;
1446 AF(&itf->sin) = itf->family;
1447 AF(&itf->mask) = itf->family;
1448 AF(&itf->bcast) = itf->family;
1449 SET_PORT(&itf->sin, port);
1450 SET_PORT(&itf->mask, port);
1451 SET_PORT(&itf->bcast, port);
1453 if (IS_IPV4(&itf->sin)) {
1454 NSRCADR(&itf->sin) = isc_if->address.type.in.s_addr;
1455 NSRCADR(&itf->mask) = isc_if->netmask.type.in.s_addr;
1457 if (isc_if->flags & INTERFACE_F_BROADCAST) {
1458 itf->flags |= INT_BROADCAST;
1459 NSRCADR(&itf->bcast) =
1460 isc_if->broadcast.type.in.s_addr;
1463 #ifdef INCLUDE_IPV6_SUPPORT
1464 else if (IS_IPV6(&itf->sin)) {
1465 SET_ADDR6N(&itf->sin, isc_if->address.type.in6);
1466 SET_ADDR6N(&itf->mask, isc_if->netmask.type.in6);
1468 SET_SCOPE(&itf->sin, isc_if->address.zone);
1470 #endif /* INCLUDE_IPV6_SUPPORT */
1473 /* Process the rest of the flags */
1476 ((INTERFACE_F_UP & isc_if->flags)
1478 | ((INTERFACE_F_LOOPBACK & isc_if->flags)
1480 | ((INTERFACE_F_POINTTOPOINT & isc_if->flags)
1482 | ((INTERFACE_F_MULTICAST & isc_if->flags)
1483 ? INT_MULTICAST : 0)
1484 | ((INTERFACE_F_PRIVACY & isc_if->flags)
1489 * Clear the loopback flag if the address is not localhost.
1490 * http://bugs.ntp.org/1683
1492 if (INT_LOOPBACK & itf->flags) {
1493 if (AF_INET == itf->family) {
1494 if (127 != (SRCADR(&itf->sin) >> 24))
1495 itf->flags &= ~INT_LOOPBACK;
1497 if (memcmp(v6loop, NSRCADR6(&itf->sin),
1498 sizeof(NSRCADR6(&itf->sin))))
1499 itf->flags &= ~INT_LOOPBACK;
1508 * some OSes have been observed to keep
1509 * cached routes even when more specific routes
1511 * this can be mitigated by re-binding
1516 struct interface * interface
1519 #ifdef OS_MISSES_SPECIFIC_ROUTE_UPDATES
1520 if (interface->fd != INVALID_SOCKET) {
1521 int bcast = (interface->flags & INT_BCASTXMIT) != 0;
1522 /* as we forcibly close() the socket remove the
1523 broadcast permission indication */
1525 socket_broadcast_disable(interface, &interface->sin);
1527 close_and_delete_fd_from_list(interface->fd);
1529 /* create new socket picking up a new first hop binding
1530 at connect() time */
1531 interface->fd = open_socket(&interface->sin,
1532 bcast, 0, interface);
1534 * reset TTL indication so TTL is is set again
1537 interface->last_ttl = 0;
1538 return (interface->fd != INVALID_SOCKET);
1540 return 0; /* invalid sockets are not refreshable */
1541 #else /* !OS_MISSES_SPECIFIC_ROUTE_UPDATES */
1542 return (interface->fd != INVALID_SOCKET);
1543 #endif /* !OS_MISSES_SPECIFIC_ROUTE_UPDATES */
1547 * interface_update - externally callable update function
1551 interface_receiver_t receiver,
1554 int new_interface_found;
1556 if (disable_dynamic_updates)
1560 new_interface_found = update_interfaces(NTP_PORT, receiver, data);
1563 if (!new_interface_found)
1567 msyslog(LOG_DEBUG, "new interface(s) found: waking up resolver");
1569 interrupt_worker_sleep();
1574 * sau_from_netaddr() - convert network address on-wire formats.
1575 * Convert from libisc's isc_netaddr_t to NTP's sockaddr_u
1580 const isc_netaddr_t *pna
1584 AF(psau) = (u_short)pna->family;
1585 switch (pna->family) {
1588 memcpy(&psau->sa4.sin_addr, &pna->type.in,
1589 sizeof(psau->sa4.sin_addr));
1593 memcpy(&psau->sa6.sin6_addr, &pna->type.in6,
1594 sizeof(psau->sa6.sin6_addr));
1602 const sockaddr_u *psau
1605 if (IS_IPV4(psau) && !NSRCADR(psau))
1608 #ifdef INCLUDE_IPV6_SUPPORT
1609 if (IS_IPV6(psau) && S_ADDR6_EQ(psau, &in6addr_any))
1617 #ifdef OS_NEEDS_REUSEADDR_FOR_IFADDRBIND
1619 * enable/disable re-use of wildcard address socket
1627 struct interface *any;
1628 SOCKET fd = INVALID_SOCKET;
1630 any = ANY_INTERFACE_BYFAM(family);
1634 if (fd != INVALID_SOCKET) {
1635 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1636 (char *)&on, sizeof(on)))
1638 "set_wildcard_reuse: setsockopt(SO_REUSEADDR, %s) failed: %m",
1641 DPRINTF(4, ("set SO_REUSEADDR to %s on %s\n",
1646 #endif /* OS_NEEDS_REUSEADDR_FOR_IFADDRBIND */
1649 static isc_boolean_t
1656 #if defined(INCLUDE_IPV6_SUPPORT) && defined(SIOCGIFAFLAG_IN6) && \
1657 (defined(IN6_IFF_ANYCAST) || defined(IN6_IFF_NOTREADY))
1658 struct in6_ifreq ifr6;
1660 u_int32 exclude = 0;
1662 if (psau->sa.sa_family != AF_INET6)
1664 if ((fd = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1667 memcpy(&ifr6.ifr_addr, &psau->sa6, sizeof(ifr6.ifr_addr));
1668 strlcpy(ifr6.ifr_name, name, sizeof(ifr6.ifr_name));
1669 if (ioctl(fd, SIOCGIFAFLAG_IN6, &ifr6) < 0) {
1674 flags6 = ifr6.ifr_ifru.ifru_flags6;
1675 #if defined(IN6_IFF_ANYCAST)
1676 exclude |= IN6_IFF_ANYCAST;
1677 #endif /* !IN6_IFF_ANYCAST */
1678 #if defined(IN6_IFF_NOTREADY)
1679 exclude |= IN6_IFF_NOTREADY;
1680 #endif /* !IN6_IFF_NOTREADY */
1681 if ((flags6 & exclude) != 0)
1683 #endif /* INCLUDE_IPV6_SUPPORT && SIOCGIFAFLAG_IN6 && (IN6_IFF_ANYCAST && IN6_IFF_NOTREADY) */
1687 static isc_boolean_t
1693 #ifdef IN6_IFF_ANYCAST
1694 return check_flags6(psau, name, IN6_IFF_ANYCAST);
1700 static isc_boolean_t
1709 #ifdef IN6_IFF_DEPARTED
1710 flags6 |= IN6_IFF_DEPARTED;
1712 #ifdef IN6_IFF_DETACHED
1713 flags6 |= IN6_IFF_DETACHED;
1715 #ifdef IN6_IFF_TENTATIVE
1716 flags6 |= IN6_IFF_TENTATIVE;
1718 return check_flags6(psau, name, flags6) ? ISC_FALSE : ISC_TRUE;
1722 * update_interface strategy
1724 * toggle configuration phase
1727 * forall currently existing interfaces
1728 * if address is known:
1729 * drop socket - rebind again
1731 * if address is NOT known:
1732 * attempt to create a new interface entry
1735 * forall currently known non MCAST and WILDCARD interfaces
1736 * if interface does not match configuration phase (not seen in phase 1):
1737 * remove interface from known interface list
1738 * forall peers associated with this interface
1739 * disconnect peer from this interface
1742 * attempt to re-assign interfaces to peers
1749 interface_receiver_t receiver,
1753 isc_mem_t * mctx = (void *)-1;
1754 interface_info_t ifi;
1755 isc_interfaceiter_t * iter;
1756 isc_result_t result;
1757 isc_interface_t isc_if;
1758 int new_interface_found;
1759 unsigned int family;
1764 DPRINTF(3, ("update_interfaces(%d)\n", port));
1767 * phase one - scan interfaces
1768 * - create those that are not found
1769 * - update those that are found
1772 new_interface_found = FALSE;
1774 result = isc_interfaceiter_create(mctx, &iter);
1776 if (result != ISC_R_SUCCESS)
1780 * Toggle system interface scan phase to find untouched
1781 * interfaces to be deleted.
1783 sys_interphase ^= 0x1;
1785 for (result = isc_interfaceiter_first(iter);
1786 ISC_R_SUCCESS == result;
1787 result = isc_interfaceiter_next(iter)) {
1789 result = isc_interfaceiter_current(iter, &isc_if);
1791 if (result != ISC_R_SUCCESS)
1794 /* See if we have a valid family to use */
1795 family = isc_if.address.family;
1796 if (AF_INET != family && AF_INET6 != family)
1798 if (AF_INET == family && !ipv4_works)
1800 if (AF_INET6 == family && !ipv6_works)
1803 /* create prototype */
1804 init_interface(&enumep);
1806 convert_isc_if(&isc_if, &enumep, port);
1808 DPRINT_INTERFACE(4, (&enumep, "examining ", "\n"));
1811 * Check if and how we are going to use the interface.
1813 switch (interface_action(enumep.name, &enumep.sin,
1817 DPRINTF(4, ("ignoring interface %s (%s) - by nic rules\n",
1818 enumep.name, stoa(&enumep.sin)));
1822 DPRINTF(4, ("listen interface %s (%s) - by nic rules\n",
1823 enumep.name, stoa(&enumep.sin)));
1824 enumep.ignore_packets = ISC_FALSE;
1828 DPRINTF(4, ("drop on interface %s (%s) - by nic rules\n",
1829 enumep.name, stoa(&enumep.sin)));
1830 enumep.ignore_packets = ISC_TRUE;
1834 /* interfaces must be UP to be usable */
1835 if (!(enumep.flags & INT_UP)) {
1836 DPRINTF(4, ("skipping interface %s (%s) - DOWN\n",
1837 enumep.name, stoa(&enumep.sin)));
1842 * skip any interfaces UP and bound to a wildcard
1843 * address - some dhcp clients produce that in the
1846 if (is_wildcard_addr(&enumep.sin))
1849 if (is_not_bindable(&enumep.sin, isc_if.name))
1853 * skip any address that is an invalid state to be used
1855 if (!is_valid(&enumep.sin, isc_if.name))
1859 * map to local *address* in order to map all duplicate
1860 * interfaces to an endpt structure with the appropriate
1861 * socket. Our name space is (ip-address), NOT
1862 * (interface name, ip-address).
1864 ep = getinterface(&enumep.sin, INT_WILDCARD);
1866 if (ep != NULL && refresh_interface(ep)) {
1868 * found existing and up to date interface -
1871 if (ep->phase != sys_interphase) {
1873 * On a new round we reset the name so
1874 * the interface name shows up again if
1875 * this address is no longer shared.
1876 * We reset ignore_packets from the
1877 * new prototype to respect any runtime
1878 * changes to the nic rules.
1880 strlcpy(ep->name, enumep.name,
1882 ep->ignore_packets =
1883 enumep.ignore_packets;
1885 /* name collision - rename interface */
1886 strlcpy(ep->name, "*multiple*",
1890 DPRINT_INTERFACE(4, (ep, "updating ",
1893 if (ep->ignore_packets !=
1894 enumep.ignore_packets) {
1896 * We have conflicting configurations
1897 * for the interface address. This is
1898 * caused by using -I <interfacename>
1899 * for an interface that shares its
1900 * address with other interfaces. We
1901 * can not disambiguate incoming
1902 * packets delivered to this socket
1903 * without extra syscalls/features.
1904 * These are not (commonly) available.
1905 * Note this is a more unusual
1906 * configuration where several
1907 * interfaces share an address but
1908 * filtering via interface name is
1909 * attempted. We resolve the
1910 * configuration conflict by disabling
1911 * the processing of received packets.
1912 * This leads to no service on the
1913 * interface address where the conflict
1917 "WARNING: conflicting enable configuration for interfaces %s and %s for address %s - unsupported configuration - address DISABLED",
1918 enumep.name, ep->name,
1921 ep->ignore_packets = ISC_TRUE;
1924 ep->phase = sys_interphase;
1926 ifi.action = IFS_EXISTS;
1928 if (receiver != NULL)
1929 (*receiver)(data, &ifi);
1932 * This is new or refreshing failed - add to
1933 * our interface list. If refreshing failed we
1934 * will delete the interface structure in phase
1935 * 2 as the interface was not marked current.
1936 * We can bind to the address as the refresh
1937 * code already closed the offending socket
1939 ep = create_interface(port, &enumep);
1942 ifi.action = IFS_CREATED;
1944 if (receiver != NULL)
1945 (*receiver)(data, &ifi);
1947 new_interface_found = TRUE;
1950 " new - created\n"));
1953 (&enumep, "updating ",
1954 " new - creation FAILED"));
1957 "failed to init interface for address %s",
1964 isc_interfaceiter_destroy(&iter);
1967 * phase 2 - delete gone interfaces - reassigning peers to
1970 for (ep = ep_list; ep != NULL; ep = next_ep) {
1971 next_ep = ep->elink;
1974 * if phase does not match sys_phase this interface was
1975 * not enumerated during the last interface scan - so it
1976 * is gone and will be deleted here unless it did not
1977 * originate from interface enumeration (INT_WILDCARD,
1980 if (((INT_WILDCARD | INT_MCASTIF) & ep->flags) ||
1981 ep->phase == sys_interphase)
1984 DPRINT_INTERFACE(3, (ep, "updating ",
1985 "GONE - deleting\n"));
1986 remove_interface(ep);
1988 ifi.action = IFS_DELETED;
1990 if (receiver != NULL)
1991 (*receiver)(data, &ifi);
1993 /* disconnect peers from deleted endpt. */
1994 while (ep->peers != NULL)
1995 set_peerdstadr(ep->peers, NULL);
1998 * update globals in case we lose
1999 * a loopback interface
2001 if (ep == loopback_interface)
2002 loopback_interface = NULL;
2004 delete_interface(ep);
2008 * phase 3 - re-configure as the world has possibly changed
2010 * never ever make this conditional again - it is needed to track
2011 * routing updates. see bug #2506
2013 refresh_all_peerinterfaces();
2015 if (broadcast_client_enabled)
2021 return new_interface_found;
2026 * create_sockets - create a socket for each interface plus a default
2027 * socket for when we don't know where to send
2034 #ifndef HAVE_IO_COMPLETION_PORT
2036 * I/O Completion Ports don't care about the select and FD_SET
2039 FD_ZERO(&activefds);
2042 DPRINTF(2, ("create_sockets(%d)\n", port));
2044 create_wildcards(port);
2046 update_interfaces(port, NULL, NULL);
2049 * Now that we have opened all the sockets, turn off the reuse
2050 * flag for security.
2054 DPRINTF(2, ("create_sockets: Total interfaces = %d\n", ninterfaces));
2060 * create_interface - create a new interface for a given prototype
2061 * binding the socket.
2063 static struct interface *
2066 struct interface * protot
2071 #if defined(MCAST) && defined(MULTICAST_NONEWSOCKET)
2073 remaddr_t * next_entry;
2075 DPRINTF(2, ("create_interface(%s#%d)\n", stoa(&protot->sin),
2078 /* build an interface */
2079 iface = new_interface(protot);
2084 iface->fd = open_socket(&iface->sin, 0, 0, iface);
2086 if (iface->fd != INVALID_SOCKET)
2087 log_listen_address(iface);
2089 if ((INT_BROADCAST & iface->flags)
2090 && iface->bfd != INVALID_SOCKET)
2091 msyslog(LOG_INFO, "Listening on broadcast address %s#%d",
2092 stoa((&iface->bcast)), port);
2094 if (INVALID_SOCKET == iface->fd
2095 && INVALID_SOCKET == iface->bfd) {
2096 msyslog(LOG_ERR, "unable to create socket on %s (%d) for %s#%d",
2099 stoa((&iface->sin)),
2101 delete_interface(iface);
2106 * Blacklist our own addresses, no use talking to ourself
2108 SET_HOSTMASK(&resmask, AF(&iface->sin));
2109 hack_restrict(RESTRICT_FLAGS, &iface->sin, &resmask,
2110 RESM_NTPONLY | RESM_INTERFACE, RES_IGNORE, 0);
2113 * set globals with the first found
2114 * loopback interface of the appropriate class
2116 if (NULL == loopback_interface && AF_INET == iface->family
2117 && (INT_LOOPBACK & iface->flags))
2118 loopback_interface = iface;
2121 * put into our interface list
2123 add_addr_to_list(&iface->sin, iface);
2124 add_interface(iface);
2126 #if defined(MCAST) && defined(MULTICAST_NONEWSOCKET)
2128 * Join any previously-configured compatible multicast groups.
2130 if (INT_MULTICAST & iface->flags &&
2131 !((INT_LOOPBACK | INT_WILDCARD) & iface->flags) &&
2132 !iface->ignore_packets) {
2133 for (entry = remoteaddr_list;
2135 entry = next_entry) {
2136 next_entry = entry->link;
2137 if (AF(&iface->sin) != AF(&entry->addr) ||
2138 !IS_MCAST(&entry->addr))
2140 if (socket_multicast_enable(iface,
2143 "Joined %s socket to multicast group %s",
2145 stoa(&entry->addr));
2148 "Failed to join %s socket to multicast group %s",
2150 stoa(&entry->addr));
2153 #endif /* MCAST && MCAST_NONEWSOCKET */
2155 DPRINT_INTERFACE(2, (iface, "created ", "\n"));
2160 #ifdef SO_EXCLUSIVEADDRUSE
2172 failed = setsockopt(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
2173 (char *)&one, sizeof(one));
2180 * Prior to Windows XP setting SO_EXCLUSIVEADDRUSE can fail with
2181 * error WSAINVAL depending on service pack level and whether
2182 * the user account is in the Administrators group. Do not
2183 * complain if it fails that way on versions prior to XP (5.1).
2185 err = GetLastError();
2187 if (isc_win32os_versioncheck(5, 1, 0, 0) < 0 /* < 5.1/XP */
2188 && WSAEINVAL == err)
2194 "setsockopt(%d, SO_EXCLUSIVEADDRUSE, on): %m",
2197 #endif /* SO_EXCLUSIVEADDRUSE */
2201 * set_reuseaddr() - set/clear REUSEADDR on all sockets
2202 * NB possible hole - should we be doing this on broadcast
2210 #ifndef SO_EXCLUSIVEADDRUSE
2213 for (ep = ep_list; ep != NULL; ep = ep->elink) {
2214 if (ep->flags & INT_WILDCARD)
2218 * if ep->fd is INVALID_SOCKET, we might have a adapter
2219 * configured but not present
2221 DPRINTF(4, ("setting SO_REUSEADDR on %.16s@%s to %s\n",
2222 ep->name, stoa(&ep->sin),
2223 flag ? "on" : "off"));
2225 if (ep->fd != INVALID_SOCKET) {
2226 if (setsockopt(ep->fd, SOL_SOCKET, SO_REUSEADDR,
2227 (char *)&flag, sizeof(flag))) {
2228 msyslog(LOG_ERR, "set_reuseaddr: setsockopt(%s, SO_REUSEADDR, %s) failed: %m",
2229 stoa(&ep->sin), flag ? "on" : "off");
2233 #endif /* ! SO_EXCLUSIVEADDRUSE */
2237 * This is just a wrapper around an internal function so we can
2238 * make other changes as necessary later on
2242 struct interface * iface,
2246 #ifdef OPEN_BCAST_SOCKET
2247 socket_broadcast_enable(iface, iface->fd, baddr);
2251 #ifdef OPEN_BCAST_SOCKET
2253 * Enable a broadcast address to a given socket
2254 * The socket is in the ep_list all we need to do is enable
2255 * broadcasting. It is not this function's job to select the socket
2257 static isc_boolean_t
2258 socket_broadcast_enable(
2259 struct interface * iface,
2267 if (IS_IPV4(baddr)) {
2268 /* if this interface can support broadcast, set SO_BROADCAST */
2269 if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST,
2270 (char *)&on, sizeof(on)))
2272 "setsockopt(SO_BROADCAST) enable failure on address %s: %m",
2275 DPRINTF(2, ("Broadcast enabled on socket %d for address %s\n",
2278 iface->flags |= INT_BCASTXMIT;
2282 #endif /* SO_BROADCAST */
2285 #ifdef OS_MISSES_SPECIFIC_ROUTE_UPDATES
2287 * Remove a broadcast address from a given socket
2288 * The socket is in the ep_list all we need to do is disable
2289 * broadcasting. It is not this function's job to select the socket
2291 static isc_boolean_t
2292 socket_broadcast_disable(
2293 struct interface * iface,
2298 int off = 0; /* This seems to be OK as an int */
2300 if (IS_IPV4(baddr) && setsockopt(iface->fd, SOL_SOCKET,
2301 SO_BROADCAST, (char *)&off, sizeof(off)))
2303 "setsockopt(SO_BROADCAST) disable failure on address %s: %m",
2306 iface->flags &= ~INT_BCASTXMIT;
2310 #endif /* SO_BROADCAST */
2312 #endif /* OS_MISSES_SPECIFIC_ROUTE_UPDATES */
2314 #endif /* OPEN_BCAST_SOCKET */
2317 * return the broadcast client flag value
2320 get_broadcastclient_flag(void)
2322 return (broadcast_client_enabled);
2325 * Check to see if the address is a multicast address
2327 static isc_boolean_t
2332 isc_boolean_t result;
2334 #ifndef INCLUDE_IPV6_MULTICAST_SUPPORT
2336 * If we don't have IPV6 support any IPV6 addr is not multicast
2342 result = IS_MCAST(maddr);
2345 DPRINTF(4, ("address %s is not multicast\n",
2352 * Multicast servers need to set the appropriate Multicast interface
2353 * socket option in order for it to know which interface to use for
2354 * send the multicast packet.
2357 enable_multicast_if(
2358 struct interface * iface,
2363 #ifdef IP_MULTICAST_LOOP
2364 TYPEOF_IP_MULTICAST_LOOP off = 0;
2366 #if defined(INCLUDE_IPV6_MULTICAST_SUPPORT) && defined(IPV6_MULTICAST_LOOP)
2370 NTP_REQUIRE(AF(maddr) == AF(&iface->sin));
2372 switch (AF(&iface->sin)) {
2375 #ifdef IP_MULTICAST_LOOP
2377 * Don't send back to itself, but allow failure to set
2379 if (setsockopt(iface->fd, IPPROTO_IP,
2381 SETSOCKOPT_ARG_CAST &off,
2385 "setsockopt IP_MULTICAST_LOOP failed: %m on socket %d, addr %s for multicast address %s",
2386 iface->fd, stoa(&iface->sin),
2393 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2394 #ifdef IPV6_MULTICAST_LOOP
2396 * Don't send back to itself, but allow failure to set
2398 if (setsockopt(iface->fd, IPPROTO_IPV6,
2399 IPV6_MULTICAST_LOOP,
2400 (char *) &off6, sizeof(off6))) {
2403 "setsockopt IPV6_MULTICAST_LOOP failed: %m on socket %d, addr %s for multicast address %s",
2404 iface->fd, stoa(&iface->sin),
2411 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */
2418 * Add a multicast address to a given socket
2419 * The socket is in the ep_list all we need to do is enable
2420 * multicasting. It is not this function's job to select the socket
2423 static isc_boolean_t
2424 socket_multicast_enable(
2429 struct ip_mreq mreq;
2430 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2431 struct ipv6_mreq mreq6;
2433 switch (AF(maddr)) {
2437 mreq.imr_multiaddr = SOCK_ADDR4(maddr);
2438 mreq.imr_interface.s_addr = htonl(INADDR_ANY);
2439 if (setsockopt(iface->fd,
2445 "setsockopt IP_ADD_MEMBERSHIP failed: %m on socket %d, addr %s for %x / %x (%s)",
2446 iface->fd, stoa(&iface->sin),
2447 mreq.imr_multiaddr.s_addr,
2448 mreq.imr_interface.s_addr,
2452 DPRINTF(4, ("Added IPv4 multicast membership on socket %d, addr %s for %x / %x (%s)\n",
2453 iface->fd, stoa(&iface->sin),
2454 mreq.imr_multiaddr.s_addr,
2455 mreq.imr_interface.s_addr, stoa(maddr)));
2459 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2461 * Enable reception of multicast packets.
2462 * If the address is link-local we can get the
2463 * interface index from the scope id. Don't do this
2464 * for other types of multicast addresses. For now let
2465 * the kernel figure it out.
2468 mreq6.ipv6mr_multiaddr = SOCK_ADDR6(maddr);
2469 mreq6.ipv6mr_interface = iface->ifindex;
2471 if (setsockopt(iface->fd, IPPROTO_IPV6,
2472 IPV6_JOIN_GROUP, (char *)&mreq6,
2475 "setsockopt IPV6_JOIN_GROUP failed: %m on socket %d, addr %s for interface %u (%s)",
2476 iface->fd, stoa(&iface->sin),
2477 mreq6.ipv6mr_interface, stoa(maddr));
2480 DPRINTF(4, ("Added IPv6 multicast group on socket %d, addr %s for interface %u (%s)\n",
2481 iface->fd, stoa(&iface->sin),
2482 mreq6.ipv6mr_interface, stoa(maddr)));
2485 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */
2487 iface->flags |= INT_MCASTOPEN;
2496 * Remove a multicast address from a given socket
2497 * The socket is in the ep_list all we need to do is disable
2498 * multicasting. It is not this function's job to select the socket
2501 static isc_boolean_t
2502 socket_multicast_disable(
2503 struct interface * iface,
2507 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2508 struct ipv6_mreq mreq6;
2510 struct ip_mreq mreq;
2514 if (find_addr_in_list(maddr) == NULL) {
2515 DPRINTF(4, ("socket_multicast_disable(%s): not found\n",
2520 switch (AF(maddr)) {
2523 mreq.imr_multiaddr = SOCK_ADDR4(maddr);
2524 mreq.imr_interface = SOCK_ADDR4(&iface->sin);
2525 if (setsockopt(iface->fd, IPPROTO_IP,
2526 IP_DROP_MEMBERSHIP, (char *)&mreq,
2530 "setsockopt IP_DROP_MEMBERSHIP failed: %m on socket %d, addr %s for %x / %x (%s)",
2531 iface->fd, stoa(&iface->sin),
2532 SRCADR(maddr), SRCADR(&iface->sin),
2538 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2540 * Disable reception of multicast packets
2541 * If the address is link-local we can get the
2542 * interface index from the scope id. Don't do this
2543 * for other types of multicast addresses. For now let
2544 * the kernel figure it out.
2546 mreq6.ipv6mr_multiaddr = SOCK_ADDR6(maddr);
2547 mreq6.ipv6mr_interface = iface->ifindex;
2549 if (setsockopt(iface->fd, IPPROTO_IPV6,
2550 IPV6_LEAVE_GROUP, (char *)&mreq6,
2554 "setsockopt IPV6_LEAVE_GROUP failure: %m on socket %d, addr %s for %d (%s)",
2555 iface->fd, stoa(&iface->sin),
2556 iface->ifindex, stoa(maddr));
2562 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */
2566 if (!iface->num_mcast)
2567 iface->flags &= ~INT_MCASTOPEN;
2574 * io_setbclient - open the broadcast client sockets
2579 #ifdef OPEN_BCAST_SOCKET
2580 struct interface * interf;
2586 for (interf = ep_list;
2588 interf = interf->elink) {
2590 if (interf->flags & (INT_WILDCARD | INT_LOOPBACK))
2593 /* use only allowed addresses */
2594 if (interf->ignore_packets)
2597 /* Need a broadcast-capable interface */
2598 if (!(interf->flags & INT_BROADCAST))
2601 /* Only IPv4 addresses are valid for broadcast */
2602 NTP_REQUIRE(IS_IPV4(&interf->sin));
2604 /* Do we already have the broadcast address open? */
2605 if (interf->flags & INT_BCASTOPEN) {
2607 * account for already open interfaces to avoid
2608 * misleading warning below
2615 * Try to open the broadcast address
2617 interf->family = AF_INET;
2618 interf->bfd = open_socket(&interf->bcast, 1, 0, interf);
2621 * If we succeeded then we use it otherwise enable
2622 * broadcast on the interface address
2624 if (interf->bfd != INVALID_SOCKET) {
2626 interf->flags |= INT_BCASTOPEN;
2628 "Listen for broadcasts to %s on interface #%d %s",
2629 stoa(&interf->bcast), interf->ifnum, interf->name);
2631 /* silently ignore EADDRINUSE as we probably opened
2632 the socket already for an address in the same network */
2633 if (errno != EADDRINUSE)
2635 "failed to listen for broadcasts to %s on interface #%d %s",
2636 stoa(&interf->bcast), interf->ifnum, interf->name);
2641 broadcast_client_enabled = ISC_TRUE;
2642 DPRINTF(1, ("io_setbclient: listening to %d broadcast addresses\n", nif));
2645 broadcast_client_enabled = ISC_FALSE;
2647 "Unable to listen for broadcasts, no broadcast interfaces available");
2651 "io_setbclient: Broadcast Client disabled by build");
2652 #endif /* OPEN_BCAST_SOCKET */
2656 * io_unsetbclient - close the broadcast client sockets
2659 io_unsetbclient(void)
2663 for (ep = ep_list; ep != NULL; ep = ep->elink) {
2664 if (INT_WILDCARD & ep->flags)
2666 if (!(INT_BCASTOPEN & ep->flags))
2669 if (ep->bfd != INVALID_SOCKET) {
2670 /* destroy broadcast listening socket */
2672 "stop listening for broadcasts to %s on interface #%d %s",
2673 stoa(&ep->bcast), ep->ifnum, ep->name);
2674 close_and_delete_fd_from_list(ep->bfd);
2675 ep->bfd = INVALID_SOCKET;
2676 ep->flags &= ~INT_BCASTOPEN;
2679 broadcast_client_enabled = ISC_FALSE;
2683 * io_multicast_add() - add multicast group address
2695 * Check to see if this is a multicast address
2697 if (!addr_ismulticast(addr))
2700 /* If we already have it we can just return */
2701 if (NULL != find_flagged_addr_in_list(addr, INT_MCASTOPEN)) {
2703 "Duplicate request found for multicast address %s",
2708 #ifndef MULTICAST_NONEWSOCKET
2709 ep = new_interface(NULL);
2712 * Open a new socket for the multicast address
2715 SET_PORT(&ep->sin, NTP_PORT);
2716 ep->family = AF(&ep->sin);
2717 AF(&ep->mask) = ep->family;
2718 SET_ONESMASK(&ep->mask);
2721 ep->bfd = INVALID_SOCKET;
2722 ep->fd = open_socket(&ep->sin, 0, 0, ep);
2723 if (ep->fd != INVALID_SOCKET) {
2724 ep->ignore_packets = ISC_FALSE;
2725 ep->flags |= INT_MCASTIF;
2727 strlcpy(ep->name, "multicast", sizeof(ep->name));
2728 DPRINT_INTERFACE(2, (ep, "multicast add ", "\n"));
2730 log_listen_address(ep);
2732 /* bind failed, re-use wildcard interface */
2733 delete_interface(ep);
2737 else if (IS_IPV6(addr))
2743 /* HACK ! -- stuff in an address */
2744 /* because we don't bind addr? DH */
2747 "multicast address %s using wildcard interface #%d %s",
2748 stoa(addr), ep->ifnum, ep->name);
2751 "No multicast socket available to use for address %s",
2756 { /* in place of the { following for in #else clause */
2758 #else /* MULTICAST_NONEWSOCKET follows */
2760 * For the case where we can't use a separate socket (Windows)
2761 * join each applicable endpoint socket to the group address.
2767 for (ep = ep_list; ep != NULL; ep = ep->elink) {
2768 if (ep->ignore_packets || AF(&ep->sin) != AF(addr) ||
2769 !(INT_MULTICAST & ep->flags) ||
2770 (INT_LOOPBACK | INT_WILDCARD) & ep->flags)
2773 #endif /* MULTICAST_NONEWSOCKET */
2774 if (socket_multicast_enable(ep, addr))
2776 "Joined %s socket to multicast group %s",
2781 "Failed to join %s socket to multicast group %s",
2786 add_addr_to_list(addr, one_ep);
2787 #else /* !MCAST follows*/
2789 "Can not add multicast address %s: no multicast support",
2797 * io_multicast_del() - delete multicast group address
2808 * Check to see if this is a multicast address
2810 if (!addr_ismulticast(addr)) {
2811 msyslog(LOG_ERR, "invalid multicast address %s",
2817 * Disable reception of multicast packets
2819 while ((iface = find_flagged_addr_in_list(addr, INT_MCASTOPEN))
2821 socket_multicast_disable(iface, addr);
2823 delete_addr_from_list(addr);
2825 #else /* not MCAST */
2827 "Can not delete multicast address %s: no multicast support",
2829 #endif /* not MCAST */
2834 * open_socket - open a socket, returning the file descriptor
2848 * int is OK for REUSEADR per
2849 * http://www.kohala.com/start/mcast.api.txt
2854 #ifndef IPTOS_DSCP_EF
2855 #define IPTOS_DSCP_EF 0xb8
2857 int qos = IPTOS_DSCP_EF; /* QoS RFC3246 */
2859 if (IS_IPV6(addr) && !ipv6_works)
2860 return INVALID_SOCKET;
2862 /* create a datagram (UDP) socket */
2863 fd = socket(AF(addr), SOCK_DGRAM, 0);
2864 if (INVALID_SOCKET == fd) {
2865 errval = socket_errno();
2867 "socket(AF_INET%s, SOCK_DGRAM, 0) failed on address %s: %m",
2868 IS_IPV6(addr) ? "6" : "", stoa(addr));
2870 if (errval == EPROTONOSUPPORT ||
2871 errval == EAFNOSUPPORT ||
2872 errval == EPFNOSUPPORT)
2873 return (INVALID_SOCKET);
2877 "unexpected socket() error %m code %d (not EPROTONOSUPPORT nor EAFNOSUPPORT nor EPFNOSUPPORT) - exiting",
2883 connection_reset_fix(fd, addr);
2886 * Fixup the file descriptor for some systems
2887 * See bug #530 for details of the issue.
2892 * set SO_REUSEADDR since we will be binding the same port
2893 * number on each interface according to turn_off_reuse.
2894 * This is undesirable on Windows versions starting with
2895 * Windows XP (numeric version 5.1).
2898 if (isc_win32os_versioncheck(5, 1, 0, 0) < 0) /* before 5.1 */
2900 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
2901 (char *)((turn_off_reuse)
2907 "setsockopt SO_REUSEADDR %s fails for address %s: %m",
2913 return INVALID_SOCKET;
2915 #ifdef SO_EXCLUSIVEADDRUSE
2917 * setting SO_EXCLUSIVEADDRUSE on the wildcard we open
2918 * first will cause more specific binds to fail.
2920 if (!(interf->flags & INT_WILDCARD))
2921 set_excladdruse(fd);
2925 * IPv4 specific options go here
2927 if (IS_IPV4(addr)) {
2928 #if defined(IPPROTO_IP) && defined(IP_TOS)
2929 if (setsockopt(fd, IPPROTO_IP, IP_TOS, (char*)&qos,
2932 "setsockopt IP_TOS (%02x) fails on address %s: %m",
2934 #endif /* IPPROTO_IP && IP_TOS */
2936 socket_broadcast_enable(interf, fd, addr);
2940 * IPv6 specific options go here
2942 if (IS_IPV6(addr)) {
2943 #if defined(IPPROTO_IPV6) && defined(IPV6_TCLASS)
2944 if (setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS, (char*)&qos,
2947 "setsockopt IPV6_TCLASS (%02x) fails on address %s: %m",
2949 #endif /* IPPROTO_IPV6 && IPV6_TCLASS */
2951 if (isc_net_probe_ipv6only() == ISC_R_SUCCESS
2952 && setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY,
2953 (char*)&on, sizeof(on)))
2955 "setsockopt IPV6_V6ONLY on fails on address %s: %m",
2958 #ifdef IPV6_BINDV6ONLY
2959 if (setsockopt(fd, IPPROTO_IPV6, IPV6_BINDV6ONLY,
2960 (char*)&on, sizeof(on)))
2962 "setsockopt IPV6_BINDV6ONLY on fails on address %s: %m",
2967 #ifdef OS_NEEDS_REUSEADDR_FOR_IFADDRBIND
2969 * some OSes don't allow binding to more specific
2970 * addresses if a wildcard address already bound
2971 * to the port and SO_REUSEADDR is not set
2973 if (!is_wildcard_addr(addr))
2974 set_wildcard_reuse(AF(addr), 1);
2978 * bind the local address.
2980 errval = bind(fd, &addr->sa, SOCKLEN(addr));
2982 #ifdef OS_NEEDS_REUSEADDR_FOR_IFADDRBIND
2983 if (!is_wildcard_addr(addr))
2984 set_wildcard_reuse(AF(addr), 0);
2989 * Don't log this under all conditions
2991 if (turn_off_reuse == 0
2997 "bind(%d) AF_INET%s %s#%d%s flags 0x%x failed: %m",
2998 fd, IS_IPV6(addr) ? "6" : "",
2999 stoa(addr), SRCPORT(addr),
3000 IS_MCAST(addr) ? " (multicast)" : "",
3006 return INVALID_SOCKET;
3009 #ifdef HAVE_TIMESTAMP
3011 if (setsockopt(fd, SOL_SOCKET, SO_TIMESTAMP,
3012 (char*)&on, sizeof(on)))
3014 "setsockopt SO_TIMESTAMP on fails on address %s: %m",
3017 DPRINTF(4, ("setsockopt SO_TIMESTAMP enabled on fd %d address %s\n",
3021 #ifdef HAVE_TIMESTAMPNS
3023 if (setsockopt(fd, SOL_SOCKET, SO_TIMESTAMPNS,
3024 (char*)&on, sizeof(on)))
3026 "setsockopt SO_TIMESTAMPNS on fails on address %s: %m",
3029 DPRINTF(4, ("setsockopt SO_TIMESTAMPNS enabled on fd %d address %s\n",
3035 if (setsockopt(fd, SOL_SOCKET, SO_BINTIME,
3036 (char*)&on, sizeof(on)))
3038 "setsockopt SO_BINTIME on fails on address %s: %m",
3041 DPRINTF(4, ("setsockopt SO_BINTIME enabled on fd %d address %s\n",
3046 DPRINTF(4, ("bind(%d) AF_INET%s, addr %s%%%d#%d, flags 0x%x\n",
3047 fd, IS_IPV6(addr) ? "6" : "", stoa(addr),
3048 SCOPE(addr), SRCPORT(addr), interf->flags));
3050 make_socket_nonblocking(fd);
3052 #ifdef HAVE_SIGNALED_IO
3053 init_socket_sig(fd);
3054 #endif /* not HAVE_SIGNALED_IO */
3056 add_fd_to_list(fd, FD_TYPE_SOCKET);
3058 #if !defined(SYS_WINNT) && !defined(VMS)
3059 DPRINTF(4, ("flags for fd %d: 0x%x\n", fd,
3060 fcntl(fd, F_GETFL, 0)));
3061 #endif /* SYS_WINNT || VMS */
3063 #if defined (HAVE_IO_COMPLETION_PORT)
3065 * Add the socket to the completion port
3067 if (io_completion_port_add_socket(fd, interf)) {
3068 msyslog(LOG_ERR, "unable to set up io completion port - EXITING");
3077 #define sendto(fd, buf, len, flags, dest, destsz) \
3078 io_completion_port_sendto(fd, buf, len, (sockaddr_u *)(dest))
3081 /* XXX ELIMINATE sendpkt similar in ntpq.c, ntpdc.c, ntp_io.c, ntptrace.c */
3083 * sendpkt - send a packet to the specified destination. Maintain a
3084 * send error cache so that only the first consecutive error for a
3085 * destination is logged.
3090 struct interface * ep,
3102 ismcast = IS_MCAST(dest);
3106 src = (IS_IPV4(dest))
3112 * unbound peer - drop request and wait for better
3113 * network conditions
3115 DPRINTF(2, ("%ssendpkt(dst=%s, ttl=%d, len=%d): no interface - IGNORED\n",
3116 ismcast ? "\tMCAST\t***** " : "",
3117 stoa(dest), ttl, len));
3122 DPRINTF(2, ("%ssendpkt(%d, dst=%s, src=%s, ttl=%d, len=%d)\n",
3123 ismcast ? "\tMCAST\t***** " : "", src->fd,
3124 stoa(dest), stoa(&src->sin), ttl, len));
3127 * for the moment we use the bcast option to set multicast ttl
3129 if (ismcast && ttl > 0 && ttl != src->last_ttl) {
3131 * set the multicast ttl for outgoing packets
3133 switch (AF(&src->sin)) {
3137 rc = setsockopt(src->fd, IPPROTO_IP,
3143 # ifdef INCLUDE_IPV6_SUPPORT
3145 rc = setsockopt(src->fd, IPPROTO_IPV6,
3146 IPV6_MULTICAST_HOPS,
3150 # endif /* INCLUDE_IPV6_SUPPORT */
3157 src->last_ttl = ttl;
3160 "setsockopt IP_MULTICAST_TTL/IPV6_MULTICAST_HOPS fails on address %s: %m",
3166 cc = simulate_server(dest, src, pkt);
3168 cc = sendto(src->fd, (char *)pkt, (u_int)len, 0,
3169 &dest->sa, SOCKLEN(dest));
3180 } while (ismcast && src != NULL);
3184 #if !defined(HAVE_IO_COMPLETION_PORT)
3186 * fdbits - generate ascii representation of fd_set (FAU debug support)
3187 * HFDF format - highest fd first.
3195 static char buffer[256];
3196 char * buf = buffer;
3198 count = min(count, 255);
3200 while (count >= 0) {
3201 *buf++ = FD_ISSET(count, set) ? '#' : '-';
3212 * Routine to read the refclock packets for a specific interface
3213 * Return the number of bytes read. That way we know if we should
3214 * read it again or go on to the next one if no bytes returned
3217 read_refclock_packet(
3219 struct refclockio * rp,
3227 struct recvbuf * rb;
3229 rb = get_free_recv_buffer();
3233 * No buffer space available - just drop the packet
3235 char buf[RX_BUFF_SIZE];
3237 buflen = read(fd, buf, sizeof buf);
3242 i = (rp->datalen == 0
3243 || rp->datalen > (int)sizeof(rb->recv_space))
3244 ? (int)sizeof(rb->recv_space)
3247 buflen = read(fd, (char *)&rb->recv_space, (u_int)i);
3248 } while (buflen < 0 && EINTR == errno);
3251 saved_errno = errno;
3253 errno = saved_errno;
3258 * Got one. Mark how and when it got here,
3259 * put it on the full list and do bookkeeping.
3261 rb->recv_length = buflen;
3262 rb->recv_peer = rp->srcclock;
3266 rb->receiver = rp->clock_recv;
3268 consumed = indicate_refclock_packet(rp, rb);
3276 #endif /* REFCLOCK */
3279 #ifdef HAVE_PACKET_TIMESTAMP
3281 * extract timestamps from control message buffer
3285 struct recvbuf * rb,
3286 struct msghdr * msghdr,
3290 struct cmsghdr * cmsghdr;
3292 struct bintime * btp;
3294 #ifdef HAVE_TIMESTAMPNS
3295 struct timespec * tsp;
3297 #ifdef HAVE_TIMESTAMP
3298 struct timeval * tvp;
3300 unsigned long ticks;
3308 cmsghdr = CMSG_FIRSTHDR(msghdr);
3309 while (cmsghdr != NULL) {
3310 switch (cmsghdr->cmsg_type)
3314 #endif /* HAVE_BINTIME */
3315 #ifdef HAVE_TIMESTAMPNS
3316 case SCM_TIMESTAMPNS:
3317 #endif /* HAVE_TIMESTAMPNS */
3318 #ifdef HAVE_TIMESTAMP
3320 #endif /* HAVE_TIMESTAMP */
3321 #if defined(HAVE_BINTIME) || defined (HAVE_TIMESTAMPNS) || defined(HAVE_TIMESTAMP)
3322 switch (cmsghdr->cmsg_type)
3326 btp = (struct bintime *)CMSG_DATA(cmsghdr);
3328 * bintime documentation is at http://phk.freebsd.dk/pubs/timecounter.pdf
3330 nts.l_i = btp->sec + JAN_1970;
3331 nts.l_uf = (u_int32)(btp->frac >> 32);
3332 if (sys_tick > measured_tick &&
3334 ticks = (unsigned long)(nts.l_uf / (unsigned long)(sys_tick * FRAC));
3335 nts.l_uf = (unsigned long)(ticks * (unsigned long)(sys_tick * FRAC));
3337 DPRINTF(4, ("fetch_timestamp: system bintime network time stamp: %ld.%09lu\n",
3338 btp->sec, (unsigned long)((nts.l_uf / FRAC) * 1e9)));
3340 #endif /* HAVE_BINTIME */
3341 #ifdef HAVE_TIMESTAMPNS
3342 case SCM_TIMESTAMPNS:
3343 tsp = (struct timespec *)CMSG_DATA(cmsghdr);
3344 if (sys_tick > measured_tick &&
3346 ticks = (unsigned long)((tsp->tv_nsec * 1e-9) /
3348 tsp->tv_nsec = (long)(ticks * 1e9 *
3351 DPRINTF(4, ("fetch_timestamp: system nsec network time stamp: %ld.%09ld\n",
3352 tsp->tv_sec, tsp->tv_nsec));
3353 nts = tspec_stamp_to_lfp(*tsp);
3355 #endif /* HAVE_TIMESTAMPNS */
3356 #ifdef HAVE_TIMESTAMP
3358 tvp = (struct timeval *)CMSG_DATA(cmsghdr);
3359 if (sys_tick > measured_tick &&
3361 ticks = (unsigned long)((tvp->tv_usec * 1e-6) /
3363 tvp->tv_usec = (long)(ticks * 1e6 *
3366 DPRINTF(4, ("fetch_timestamp: system usec network time stamp: %jd.%06ld\n",
3367 (intmax_t)tvp->tv_sec, (long)tvp->tv_usec));
3368 nts = tval_stamp_to_lfp(*tvp);
3370 #endif /* HAVE_TIMESTAMP */
3372 fuzz = ntp_random() * 2. / FRAC * sys_fuzz;
3373 DTOLFP(fuzz, &lfpfuzz);
3374 L_ADD(&nts, &lfpfuzz);
3378 collect_timing(rb, "input processing delay", 1,
3380 DPRINTF(4, ("fetch_timestamp: timestamp delta: %s (incl. fuzz)\n",
3382 #endif /* DEBUG_TIMING */
3383 ts = nts; /* network time stamp */
3385 #endif /* HAVE_BINTIME || HAVE_TIMESTAMPNS || HAVE_TIMESTAMP */
3388 DPRINTF(4, ("fetch_timestamp: skipping control message 0x%x\n",
3389 cmsghdr->cmsg_type));
3391 cmsghdr = CMSG_NXTHDR(msghdr, cmsghdr);
3395 #endif /* HAVE_PACKET_TIMESTAMP */
3399 * Routine to read the network NTP packets for a specific interface
3400 * Return the number of bytes read. That way we know if we should
3401 * read it again or go on to the next one if no bytes returned
3404 read_network_packet(
3406 struct interface * itf,
3410 GETSOCKNAME_SOCKLEN_TYPE fromlen;
3412 register struct recvbuf *rb;
3413 #ifdef HAVE_PACKET_TIMESTAMP
3414 struct msghdr msghdr;
3416 char control[CMSG_BUFSIZE];
3420 * Get a buffer and read the frame. If we
3421 * haven't got a buffer, or this is received
3422 * on a disallowed socket, just dump the
3426 rb = get_free_recv_buffer();
3427 if (NULL == rb || itf->ignore_packets) {
3428 char buf[RX_BUFF_SIZE];
3434 fromlen = sizeof(from);
3435 buflen = recvfrom(fd, buf, sizeof(buf), 0,
3436 &from.sa, &fromlen);
3437 DPRINTF(4, ("%s on (%lu) fd=%d from %s\n",
3438 (itf->ignore_packets)
3441 free_recvbuffs(), fd, stoa(&from)));
3442 if (itf->ignore_packets)
3449 fromlen = sizeof(rb->recv_srcadr);
3451 #ifndef HAVE_PACKET_TIMESTAMP
3452 rb->recv_length = recvfrom(fd, (char *)&rb->recv_space,
3453 sizeof(rb->recv_space), 0,
3454 &rb->recv_srcadr.sa, &fromlen);
3456 iovec.iov_base = &rb->recv_space;
3457 iovec.iov_len = sizeof(rb->recv_space);
3458 msghdr.msg_name = &rb->recv_srcadr;
3459 msghdr.msg_namelen = fromlen;
3460 msghdr.msg_iov = &iovec;
3461 msghdr.msg_iovlen = 1;
3462 msghdr.msg_control = (void *)&control;
3463 msghdr.msg_controllen = sizeof(control);
3464 msghdr.msg_flags = 0;
3465 rb->recv_length = recvmsg(fd, &msghdr, 0);
3468 buflen = rb->recv_length;
3470 if (buflen == 0 || (buflen == -1 &&
3471 (EWOULDBLOCK == errno
3478 } else if (buflen < 0) {
3479 msyslog(LOG_ERR, "recvfrom(%s) fd=%d: %m",
3480 stoa(&rb->recv_srcadr), fd);
3481 DPRINTF(5, ("read_network_packet: fd=%d dropped (bad recvfrom)\n",
3487 DPRINTF(3, ("read_network_packet: fd=%d length %d from %s\n",
3488 fd, buflen, stoa(&rb->recv_srcadr)));
3491 ** Bug 2672: Some OSes (MacOSX and Linux) don't block spoofed ::1
3494 if (AF_INET6 == itf->family) {
3495 DPRINTF(2, ("Got an IPv6 packet, from <%s> (%d) to <%s> (%d)\n",
3496 stoa(&rb->recv_srcadr),
3497 IN6_IS_ADDR_LOOPBACK(PSOCK_ADDR6(&rb->recv_srcadr)),
3499 !IN6_IS_ADDR_LOOPBACK(PSOCK_ADDR6(&itf->sin))
3502 if ( IN6_IS_ADDR_LOOPBACK(PSOCK_ADDR6(&rb->recv_srcadr))
3503 && !IN6_IS_ADDR_LOOPBACK(PSOCK_ADDR6(&itf->sin))
3506 DPRINTF(2, ("DROPPING that packet\n"));
3510 DPRINTF(2, ("processing that packet\n"));
3514 * Got one. Mark how and when it got here,
3515 * put it on the full list and do bookkeeping.
3519 #ifdef HAVE_PACKET_TIMESTAMP
3520 /* pick up a network time stamp if possible */
3521 ts = fetch_timestamp(rb, &msghdr, ts);
3524 rb->receiver = receive;
3526 add_full_recv_buffer(rb);
3534 * attempt to handle io (select()/signaled IO)
3539 # ifndef HAVE_SIGNALED_IO
3544 * Use select() on all on all input fd's for unlimited
3545 * time. select() will terminate on SIGALARM or on the
3546 * reception of input. Using select() means we can't do
3547 * robust signal handling and we get a potential race
3548 * between checking for alarms and doing the select().
3549 * Mostly harmless, I think.
3552 * On VMS, I suspect that select() can't be interrupted
3553 * by a "signal" either, so I take the easy way out and
3554 * have select() time out after one second.
3555 * System clock updates really aren't time-critical,
3556 * and - lacking a hardware reference clock - I have
3557 * yet to learn about anything else that is.
3560 # if !defined(VMS) && !defined(SYS_VXWORKS)
3561 nfound = select(maxactivefd + 1, &rdfdes, NULL,
3563 # else /* VMS, VxWorks */
3564 /* make select() wake up after one second */
3570 nfound = select(maxactivefd + 1,
3571 &rdfdes, NULL, NULL,
3574 # endif /* VMS, VxWorks */
3581 } else if (nfound == -1 && errno != EINTR) {
3582 msyslog(LOG_ERR, "select() error: %m");
3585 else if (debug > 4) {
3586 msyslog(LOG_DEBUG, "select(): nfound=%d, error: %m", nfound);
3588 DPRINTF(1, ("select() returned %d: %m\n", nfound));
3591 # else /* HAVE_SIGNALED_IO */
3593 # endif /* HAVE_SIGNALED_IO */
3597 * input_handler - receive packets asynchronously
3610 struct timeval tvzero;
3611 l_fp ts; /* Timestamp at BOselect() gob */
3613 l_fp ts_e; /* Timestamp at EOselect() gob */
3616 size_t select_count;
3619 struct refclockio *rp;
3623 #ifdef HAS_ROUTING_SOCKET
3624 struct asyncio_reader * asyncio_reader;
3625 struct asyncio_reader * next_asyncio_reader;
3632 * If we have something to do, freeze a timestamp.
3633 * See below for the other cases (nothing left to do or error)
3638 * Do a poll to see who has data
3642 tvzero.tv_sec = tvzero.tv_usec = 0;
3644 n = select(maxactivefd + 1, &fds, (fd_set *)0, (fd_set *)0,
3648 * If there are no packets waiting just return
3654 * extended FAU debugging output
3658 "select(%d, %s, 0L, 0L, &0.0) error: %m",
3660 fdbits(maxactivefd, &activefds));
3663 for (j = 0, prior = 0; j <= maxactivefd; j++) {
3664 if (FD_ISSET(j, &activefds)) {
3665 if (-1 != read(j, &b, 0)) {
3670 "Removing bad file descriptor %d from select set",
3672 FD_CLR(j, &activefds);
3673 if (j == maxactivefd)
3674 maxactivefd = prior;
3686 * Check out the reference clocks first, if any
3689 if (refio != NULL) {
3690 for (rp = refio; rp != NULL; rp = rp->next) {
3693 if (!FD_ISSET(fd, &fds))
3696 buflen = read_refclock_packet(fd, rp, ts);
3698 * The first read must succeed after select()
3699 * indicates readability, or we've reached
3700 * a permanent EOF. http://bugs.ntp.org/1732
3701 * reported ntpd munching CPU after a USB GPS
3702 * was unplugged because select was indicating
3703 * EOF but ntpd didn't remove the descriptor
3704 * from the activefds set.
3706 if (buflen < 0 && EAGAIN != errno) {
3707 saved_errno = errno;
3708 clk = refnumtoa(&rp->srcclock->srcadr);
3709 errno = saved_errno;
3710 msyslog(LOG_ERR, "%s read: %m", clk);
3711 maintain_activefds(fd, TRUE);
3712 } else if (0 == buflen) {
3713 clk = refnumtoa(&rp->srcclock->srcadr);
3714 msyslog(LOG_ERR, "%s read EOF", clk);
3715 maintain_activefds(fd, TRUE);
3717 /* drain any remaining refclock input */
3719 buflen = read_refclock_packet(fd, rp, ts);
3720 } while (buflen > 0);
3724 #endif /* REFCLOCK */
3727 * Loop through the interfaces looking for data to read.
3729 for (ep = ep_list; ep != NULL; ep = ep->elink) {
3730 for (doing = 0; doing < 2; doing++) {
3734 if (!(ep->flags & INT_BCASTOPEN))
3740 if (FD_ISSET(fd, &fds))
3743 buflen = read_network_packet(
3745 } while (buflen > 0);
3746 /* Check more interfaces */
3750 #ifdef HAS_ROUTING_SOCKET
3752 * scan list of asyncio readers - currently only used for routing sockets
3754 asyncio_reader = asyncio_reader_list;
3756 while (asyncio_reader != NULL) {
3757 /* callback may unlink and free asyncio_reader */
3758 next_asyncio_reader = asyncio_reader->link;
3759 if (FD_ISSET(asyncio_reader->fd, &fds)) {
3761 (*asyncio_reader->receiver)(asyncio_reader);
3763 asyncio_reader = next_asyncio_reader;
3765 #endif /* HAS_ROUTING_SOCKET */
3768 * Check for a response from a blocking child
3770 for (idx = 0; idx < blocking_children_alloc; idx++) {
3771 c = blocking_children[idx];
3772 if (NULL == c || -1 == c->resp_read_pipe)
3774 if (FD_ISSET(c->resp_read_pipe, &fds)) {
3776 process_blocking_resp(c);
3781 * Done everything from that select.
3782 * If nothing to do, just return.
3783 * If an error occurred, complain and return.
3785 if (select_count == 0) { /* We really had nothing to do */
3788 msyslog(LOG_DEBUG, "input_handler: select() returned 0");
3792 /* We've done our work */
3796 * (ts_e - ts) is the amount of time we spent
3797 * processing this gob of file descriptors. Log
3801 collect_timing(NULL, "input handler", 1, &ts_e);
3804 "input_handler: Processed a gob of fd's in %s msec",
3806 #endif /* DEBUG_TIMING */
3811 #endif /* !HAVE_IO_COMPLETION_PORT */
3815 * find an interface suitable for the src address
3818 select_peerinterface(
3820 sockaddr_u * srcadr,
3828 wild = ANY_INTERFACE_CHOOSE(srcadr);
3831 * Initialize the peer structure and dance the interface jig.
3832 * Reference clocks step the loopback waltz, the others
3833 * squaredance around the interface list looking for a buddy. If
3834 * the dance peters out, there is always the wildcard interface.
3835 * This might happen in some systems and would preclude proper
3836 * operation with public key cryptography.
3838 if (ISREFCLOCKADR(srcadr)) {
3839 ep = loopback_interface;
3840 } else if (peer->cast_flags &
3841 (MDF_BCLNT | MDF_ACAST | MDF_MCAST | MDF_BCAST)) {
3842 ep = findbcastinter(srcadr);
3844 DPRINTF(4, ("Found *-cast interface %s for address %s\n",
3845 stoa(&ep->sin), stoa(srcadr)));
3847 DPRINTF(4, ("No *-cast local address found for address %s\n",
3855 * If it is a multicast address, findbcastinter() may not find
3856 * it. For unicast, we get to find the interface when dstadr is
3857 * given to us as the wildcard (ANY_INTERFACE_CHOOSE). Either
3858 * way, try a little harder.
3861 ep = findinterface(srcadr);
3863 * we do not bind to the wildcard interfaces for output
3864 * as our (network) source address would be undefined and
3865 * crypto will not work without knowing the own transmit address
3867 if (ep != NULL && INT_WILDCARD & ep->flags)
3868 if (!accept_wildcard_if_for_winnt)
3870 #else /* SIM follows */
3871 ep = loopback_interface;
3879 * findinterface - find local interface corresponding to address
3888 iface = findlocalinterface(addr, INT_WILDCARD, 0);
3890 if (NULL == iface) {
3891 DPRINTF(4, ("Found no interface for address %s - returning wildcard\n",
3894 iface = ANY_INTERFACE_CHOOSE(addr);
3896 DPRINTF(4, ("Found interface #%d %s for address %s\n",
3897 iface->ifnum, iface->name, stoa(addr)));
3903 * findlocalinterface - find local interface corresponding to addr,
3904 * which does not have any of flags set. If bast is nonzero, addr is
3905 * a broadcast address.
3907 * This code attempts to find the local sending address for an outgoing
3908 * address by connecting a new socket to destinationaddress:NTP_PORT
3909 * and reading the sockname of the resulting connect.
3910 * the complicated sequence simulates the routing table lookup
3911 * for to first hop without duplicating any of the routing logic into
3912 * ntpd. preferably we would have used an API call - but its not there -
3913 * so this is the best we can do here short of duplicating to entire routing
3914 * logic in ntpd which would be a silly and really unportable thing to do.
3924 GETSOCKNAME_SOCKLEN_TYPE sockaddrlen;
3931 DPRINTF(4, ("Finding interface for addr %s in list of addresses\n",
3934 s = socket(AF(addr), SOCK_DGRAM, 0);
3935 if (INVALID_SOCKET == s)
3939 * If we are looking for broadcast interface we need to set this
3940 * socket to allow broadcast
3944 if (SOCKET_ERROR == setsockopt(s, SOL_SOCKET,
3953 rtn = connect(s, &addr->sa, SOCKLEN(addr));
3954 if (SOCKET_ERROR == rtn) {
3959 sockaddrlen = sizeof(saddr);
3960 rtn = getsockname(s, &saddr.sa, &sockaddrlen);
3962 if (SOCKET_ERROR == rtn)
3965 DPRINTF(4, ("findlocalinterface: kernel maps %s to %s\n",
3966 stoa(addr), stoa(&saddr)));
3968 iface = getinterface(&saddr, flags);
3971 * if we didn't find an exact match on saddr, find the closest
3972 * available local address. This handles the case of the
3973 * address suggested by the kernel being excluded by nic rules
3974 * or the user's -I and -L options to ntpd.
3975 * See http://bugs.ntp.org/1184 and http://bugs.ntp.org/1683
3976 * for more background.
3978 if (NULL == iface || iface->ignore_packets)
3979 iface = findclosestinterface(&saddr,
3980 flags | INT_LOOPBACK);
3982 /* Don't use an interface which will ignore replies */
3983 if (iface != NULL && iface->ignore_packets)
3991 * findclosestinterface
3993 * If there are -I/--interface or -L/novirtualips command-line options,
3994 * or "nic" or "interface" rules in ntp.conf, findlocalinterface() may
3995 * find the kernel's preferred local address for a given peer address is
3996 * administratively unavailable to ntpd, and punt to this routine's more
3999 * Find the numerically closest local address to the one connect()
4000 * suggested. This matches an address on the same subnet first, as
4001 * needed by Bug 1184, and provides a consistent choice if there are
4002 * multiple feasible local addresses, regardless of the order ntpd
4006 findclosestinterface(
4013 sockaddr_u addr_dist;
4014 sockaddr_u min_dist;
4016 ZERO_SOCK(&min_dist);
4019 for (ep = ep_list; ep != NULL; ep = ep->elink) {
4020 if (ep->ignore_packets ||
4021 AF(addr) != ep->family ||
4025 calc_addr_distance(&addr_dist, addr, &ep->sin);
4026 if (NULL == winner ||
4027 -1 == cmp_addr_distance(&addr_dist, &min_dist)) {
4028 min_dist = addr_dist;
4033 DPRINTF(4, ("findclosestinterface(%s) failed\n",
4036 DPRINTF(4, ("findclosestinterface(%s) -> %s\n",
4037 stoa(addr), stoa(&winner->sin)));
4044 * calc_addr_distance - calculate the distance between two addresses,
4045 * the absolute value of the difference between
4046 * the addresses numerically, stored as an address.
4051 const sockaddr_u * a1,
4052 const sockaddr_u * a2
4062 NTP_REQUIRE(AF(a1) == AF(a2));
4067 /* v4 can be done a bit simpler */
4071 v4dist = (a1val > a2val)
4074 SET_ADDR4(dist, v4dist);
4079 found_greater = FALSE;
4080 a1_greater = FALSE; /* suppress pot. uninit. warning */
4081 for (i = 0; i < (int)sizeof(NSRCADR6(a1)); i++) {
4082 if (!found_greater &&
4083 NSRCADR6(a1)[i] != NSRCADR6(a2)[i]) {
4084 found_greater = TRUE;
4085 a1_greater = (NSRCADR6(a1)[i] > NSRCADR6(a2)[i]);
4087 if (!found_greater) {
4088 NSRCADR6(dist)[i] = 0;
4091 NSRCADR6(dist)[i] = NSRCADR6(a1)[i] -
4094 NSRCADR6(dist)[i] = NSRCADR6(a2)[i] -
4102 * cmp_addr_distance - compare two address distances, returning -1, 0,
4103 * 1 to indicate their relationship.
4107 const sockaddr_u * d1,
4108 const sockaddr_u * d2
4113 NTP_REQUIRE(AF(d1) == AF(d2));
4116 if (SRCADR(d1) < SRCADR(d2))
4118 else if (SRCADR(d1) == SRCADR(d2))
4124 for (i = 0; i < (int)sizeof(NSRCADR6(d1)); i++) {
4125 if (NSRCADR6(d1)[i] < NSRCADR6(d2)[i])
4127 else if (NSRCADR6(d1)[i] > NSRCADR6(d2)[i])
4137 * fetch an interface structure the matches the
4138 * address and has the given flags NOT set
4148 iface = find_addr_in_list(addr);
4150 if (iface != NULL && (iface->flags & flags))
4158 * findbcastinter - find broadcast interface corresponding to address
4168 #if !defined(MPE) && (defined(SIOCGIFCONF) || defined(SYS_WINNT))
4169 DPRINTF(4, ("Finding broadcast/multicast interface for addr %s in list of addresses\n",
4172 iface = findlocalinterface(addr, INT_LOOPBACK | INT_WILDCARD,
4174 if (iface != NULL) {
4175 DPRINTF(4, ("Easily found bcast-/mcast- interface index #%d %s\n",
4176 iface->ifnum, iface->name));
4181 * plan B - try to find something reasonable in our lists in
4182 * case kernel lookup doesn't help
4184 for (iface = ep_list; iface != NULL; iface = iface->elink) {
4185 if (iface->flags & INT_WILDCARD)
4188 /* Don't bother with ignored interfaces */
4189 if (iface->ignore_packets)
4193 * First look if this is the correct family
4195 if(AF(&iface->sin) != AF(addr))
4198 /* Skip the loopback addresses */
4199 if (iface->flags & INT_LOOPBACK)
4203 * If we are looking to match a multicast address and
4204 * this interface is one...
4206 if (addr_ismulticast(addr)
4207 && (iface->flags & INT_MULTICAST)) {
4208 #ifdef INCLUDE_IPV6_SUPPORT
4210 * ...it is the winner unless we're looking for
4211 * an interface to use for link-local multicast
4212 * and its address is not link-local.
4215 && IN6_IS_ADDR_MC_LINKLOCAL(PSOCK_ADDR6(addr))
4216 && !IN6_IS_ADDR_LINKLOCAL(PSOCK_ADDR6(&iface->sin)))
4223 * We match only those interfaces marked as
4224 * broadcastable and either the explicit broadcast
4225 * address or the network portion of the IP address.
4228 if (IS_IPV4(addr)) {
4229 if (SOCK_EQ(&iface->bcast, addr))
4232 if ((NSRCADR(&iface->sin) & NSRCADR(&iface->mask))
4233 == (NSRCADR(addr) & NSRCADR(&iface->mask)))
4236 #ifdef INCLUDE_IPV6_SUPPORT
4237 else if (IS_IPV6(addr)) {
4238 if (SOCK_EQ(&iface->bcast, addr))
4241 if (SOCK_EQ(netof(&iface->sin), netof(addr)))
4246 #endif /* SIOCGIFCONF */
4247 if (NULL == iface) {
4248 DPRINTF(4, ("No bcast interface found for %s\n",
4250 iface = ANY_INTERFACE_CHOOSE(addr);
4252 DPRINTF(4, ("Found bcast-/mcast- interface index #%d %s\n",
4253 iface->ifnum, iface->name));
4261 * io_clr_stats - clear I/O module statistics
4266 packets_dropped = 0;
4267 packets_ignored = 0;
4268 packets_received = 0;
4270 packets_notsent = 0;
4274 io_timereset = current_time;
4280 * io_addclock - add a reference clock to the list and arrange that we
4281 * get SIGIO interrupts from it.
4285 struct refclockio *rio
4291 * Stuff the I/O structure in the list and mark the descriptor
4292 * in use. There is a harmless (I hope) race condition here.
4296 # ifdef HAVE_SIGNALED_IO
4297 if (init_clock_sig(rio)) {
4301 # elif defined(HAVE_IO_COMPLETION_PORT)
4302 if (io_completion_port_add_clock_io(rio)) {
4311 LINK_SLIST(refio, rio, next);
4316 add_fd_to_list(rio->fd, FD_TYPE_FILE);
4324 * io_closeclock - close the clock in the I/O structure given
4328 struct refclockio *rio
4331 struct refclockio *unlinked;
4336 * Remove structure from the list
4338 rio->active = FALSE;
4339 UNLINK_SLIST(unlinked, refio, rio, next, struct refclockio);
4340 if (NULL != unlinked) {
4341 purge_recv_buffers_for_fd(rio->fd);
4343 * Close the descriptor.
4345 close_and_delete_fd_from_list(rio->fd);
4351 #endif /* REFCLOCK */
4355 * On NT a SOCKET is an unsigned int so we cannot possibly keep it in
4356 * an array. So we use one of the ISC_LIST functions to hold the
4357 * socket value and use that when we want to enumerate it.
4359 * This routine is called by the forked intres child process to close
4360 * all open sockets. On Windows there's no need as intres runs in
4361 * the same process as a thread.
4372 * In the child process we do not maintain activefds and
4373 * maxactivefd. Zeroing maxactivefd disables code which
4374 * maintains it in close_and_delete_fd_from_list().
4378 while (fd_list != NULL)
4379 close_and_delete_fd_from_list(fd_list->fd);
4383 #endif /* !SYS_WINNT */
4387 * Add and delete functions for the list of open sockets
4395 vsock_t *lsock = emalloc(sizeof(*lsock));
4400 LINK_SLIST(fd_list, lsock, link);
4401 maintain_activefds(fd, 0);
4406 close_and_delete_fd_from_list(
4412 UNLINK_EXPR_SLIST(lsock, fd_list, fd ==
4413 UNLINK_EXPR_SLIST_CURRENT()->fd, link, vsock_t);
4418 switch (lsock->type) {
4420 case FD_TYPE_SOCKET:
4421 closesocket(lsock->fd);
4425 closeserial(lsock->fd);
4430 "internal error - illegal descriptor type %d - EXITING",
4437 * remove from activefds
4439 maintain_activefds(fd, 1);
4452 if (find_addr_in_list(addr) == NULL) {
4454 /* not there yet - add to list */
4455 laddr = emalloc(sizeof(*laddr));
4456 laddr->addr = *addr;
4459 LINK_SLIST(remoteaddr_list, laddr, link);
4461 DPRINTF(4, ("Added addr %s to list of addresses\n",
4465 DPRINTF(4, ("WARNING: Attempt to add duplicate addr %s to address list\n",
4472 delete_addr_from_list(
4476 remaddr_t *unlinked;
4478 UNLINK_EXPR_SLIST(unlinked, remoteaddr_list, SOCK_EQ(addr,
4479 &(UNLINK_EXPR_SLIST_CURRENT()->addr)), link, remaddr_t);
4481 if (unlinked != NULL) {
4482 DPRINTF(4, ("Deleted addr %s from list of addresses\n",
4490 delete_interface_from_list(
4494 remaddr_t *unlinked;
4497 UNLINK_EXPR_SLIST(unlinked, remoteaddr_list, iface ==
4498 UNLINK_EXPR_SLIST_CURRENT()->ep, link,
4501 if (unlinked == NULL)
4503 DPRINTF(4, ("Deleted addr %s for interface #%d %s from list of addresses\n",
4504 stoa(&unlinked->addr), iface->ifnum,
4511 static struct interface *
4518 DPRINTF(4, ("Searching for addr %s in list of addresses - ",
4521 for (entry = remoteaddr_list;
4523 entry = entry->link)
4524 if (SOCK_EQ(&entry->addr, addr)) {
4525 DPRINTF(4, ("FOUND\n"));
4529 DPRINTF(4, ("NOT FOUND\n"));
4535 * Find the given address with the all given flags set in the list
4538 find_flagged_addr_in_list(
4545 DPRINTF(4, ("Finding addr %s with flags %d in list: ",
4546 stoa(addr), flags));
4548 for (entry = remoteaddr_list;
4550 entry = entry->link)
4552 if (SOCK_EQ(&entry->addr, addr)
4553 && (entry->ep->flags & flags) == flags) {
4555 DPRINTF(4, ("FOUND\n"));
4559 DPRINTF(4, ("NOT FOUND\n"));
4575 #ifdef HAS_ROUTING_SOCKET
4576 # ifndef UPDATE_GRACE
4577 # define UPDATE_GRACE 2 /* wait UPDATE_GRACE seconds before scanning */
4581 process_routing_msgs(struct asyncio_reader *reader)
4585 #ifdef HAVE_RTNETLINK
4586 struct nlmsghdr *nh;
4588 struct rt_msghdr rtm;
4592 if (disable_dynamic_updates) {
4594 * discard ourselves if we are not needed any more
4595 * usually happens when running unprivileged
4597 remove_asyncio_reader(reader);
4598 delete_asyncio_reader(reader);
4602 cnt = read(reader->fd, buffer, sizeof(buffer));
4606 "i/o error on routing socket %m - disabling");
4607 remove_asyncio_reader(reader);
4608 delete_asyncio_reader(reader);
4613 * process routing message
4615 #ifdef HAVE_RTNETLINK
4616 for (nh = (struct nlmsghdr *)buffer;
4618 nh = NLMSG_NEXT(nh, cnt)) {
4619 msg_type = nh->nlmsg_type;
4622 (p + sizeof(struct rt_msghdr)) <= (buffer + cnt);
4623 p += rtm.rtm_msglen) {
4624 memcpy(&rtm, p, sizeof(rtm));
4625 if (rtm.rtm_version != RTM_VERSION) {
4627 "version mismatch (got %d - expected %d) on routing socket - disabling",
4628 rtm.rtm_version, RTM_VERSION);
4630 remove_asyncio_reader(reader);
4631 delete_asyncio_reader(reader);
4634 msg_type = rtm.rtm_type;
4661 #ifdef RTM_IFANNOUNCE
4662 case RTM_IFANNOUNCE:
4677 * we are keen on new and deleted addresses and
4678 * if an interface goes up and down or routing
4681 DPRINTF(3, ("routing message op = %d: scheduling interface update\n",
4683 timer_interfacetimeout(current_time + UPDATE_GRACE);
4685 #ifdef HAVE_RTNETLINK
4687 /* end of multipart message */
4692 * the rest doesn't bother us.
4694 DPRINTF(4, ("routing message op = %d: ignored\n",
4702 * set up routing notifications
4705 init_async_notifications()
4707 struct asyncio_reader *reader;
4708 #ifdef HAVE_RTNETLINK
4709 int fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
4710 struct sockaddr_nl sa;
4712 int fd = socket(PF_ROUTE, SOCK_RAW, 0);
4716 "unable to open routing socket (%m) - using polled interface update");
4721 #ifdef HAVE_RTNETLINK
4723 sa.nl_family = PF_NETLINK;
4724 sa.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR
4725 | RTMGRP_IPV6_IFADDR | RTMGRP_IPV4_ROUTE
4726 | RTMGRP_IPV4_MROUTE | RTMGRP_IPV6_ROUTE
4727 | RTMGRP_IPV6_MROUTE;
4728 if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
4730 "bind failed on routing socket (%m) - using polled interface update");
4734 make_socket_nonblocking(fd);
4735 #if defined(HAVE_SIGNALED_IO)
4736 init_socket_sig(fd);
4737 #endif /* HAVE_SIGNALED_IO */
4739 reader = new_asyncio_reader();
4742 reader->receiver = process_routing_msgs;
4744 add_asyncio_reader(reader, FD_TYPE_SOCKET);
4746 "Listening on routing socket on fd #%d for interface updates",
4750 /* HAS_ROUTING_SOCKET not defined */
4752 init_async_notifications(void)