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;
77 #define IPTOS_DSCP_EF 0xb8
79 int qos = IPTOS_DSCP_EF; /* QoS RFC3246 */
82 /* TODO burnicki: This should be moved to ntp_timer.c, but if we do so
83 * we get a linker error. Since we're running out of time before the leap
84 * second occurs, we let it here where it just works.
92 typedef struct nic_rule_tag nic_rule;
96 nic_rule_action action;
97 nic_rule_match match_type;
104 * NIC rule listhead. Entries are added at the head so that the first
105 * match in the list is the last matching rule specified.
107 nic_rule *nic_rule_list;
110 #if defined(SO_BINTIME) && defined(SCM_BINTIME) && defined(CMSG_FIRSTHDR)
111 # define HAVE_PACKET_TIMESTAMP
112 # define HAVE_BINTIME
113 # ifdef BINTIME_CTLMSGBUF_SIZE
114 # define CMSG_BUFSIZE BINTIME_CTLMSGBUF_SIZE
116 # define CMSG_BUFSIZE 1536 /* moderate default */
118 #elif defined(SO_TIMESTAMPNS) && defined(SCM_TIMESTAMPNS) && defined(CMSG_FIRSTHDR)
119 # define HAVE_PACKET_TIMESTAMP
120 # define HAVE_TIMESTAMPNS
121 # ifdef TIMESTAMPNS_CTLMSGBUF_SIZE
122 # define CMSG_BUFSIZE TIMESTAMPNS_CTLMSGBUF_SIZE
124 # define CMSG_BUFSIZE 1536 /* moderate default */
126 #elif defined(SO_TIMESTAMP) && defined(SCM_TIMESTAMP) && defined(CMSG_FIRSTHDR)
127 # define HAVE_PACKET_TIMESTAMP
128 # define HAVE_TIMESTAMP
129 # ifdef TIMESTAMP_CTLMSGBUF_SIZE
130 # define CMSG_BUFSIZE TIMESTAMP_CTLMSGBUF_SIZE
132 # define CMSG_BUFSIZE 1536 /* moderate default */
135 /* fill in for old/other timestamp interfaces */
138 #if defined(SYS_WINNT)
139 #include "win32_io.h"
140 #include <isc/win32os.h>
144 * We do asynchronous input using the SIGIO facility. A number of
145 * recvbuf buffers are preallocated for input. In the signal
146 * handler we poll to see which sockets are ready and read the
147 * packets from them into the recvbuf's along with a time stamp and
148 * an indication of the source host and the interface it was received
149 * through. This allows us to get as accurate receive time stamps
150 * as possible independent of other processing going on.
152 * We watch the number of recvbufs available to the signal handler
153 * and allocate more when this number drops below the low water
154 * mark. If the signal handler should run out of buffers in the
155 * interim it will drop incoming frames, the idea being that it is
156 * better to drop a packet than to be inaccurate.
161 * Other statistics of possible interest
163 volatile u_long packets_dropped; /* total number of packets dropped on reception */
164 volatile u_long packets_ignored; /* packets received on wild card interface */
165 volatile u_long packets_received; /* total number of packets received */
166 u_long packets_sent; /* total number of packets sent */
167 u_long packets_notsent; /* total number of packets which couldn't be sent */
169 volatile u_long handler_calls; /* number of calls to interrupt handler */
170 volatile u_long handler_pkts; /* number of pkts received by handler */
171 u_long io_timereset; /* time counters were reset */
176 endpt * any_interface; /* wildcard ipv4 interface */
177 endpt * any6_interface; /* wildcard ipv6 interface */
178 endpt * loopback_interface; /* loopback ipv4 interface */
180 isc_boolean_t broadcast_client_enabled; /* is broadcast client enabled */
181 u_int sys_ifnum; /* next .ifnum to assign */
182 int ninterfaces; /* Total number of interfaces */
184 int disable_dynamic_updates; /* scan interfaces once only */
188 * Refclock stuff. We keep a chain of structures with data concerning
189 * the guys we are doing I/O for.
191 static struct refclockio *refio;
192 #endif /* REFCLOCK */
195 * File descriptor masks etc. for call to select
196 * Not needed for I/O Completion Ports or anything outside this file
198 static fd_set activefds;
199 static int maxactivefd;
202 * bit alternating value to detect verified interfaces during an update cycle
204 static u_short sys_interphase = 0;
206 static endpt * new_interface(endpt *);
207 static void add_interface(endpt *);
208 static int update_interfaces(u_short, interface_receiver_t,
210 static void remove_interface(endpt *);
211 static endpt * create_interface(u_short, endpt *);
213 static int is_wildcard_addr (const sockaddr_u *);
216 * Multicast functions
218 static isc_boolean_t addr_ismulticast (sockaddr_u *);
219 static isc_boolean_t is_not_bindable (sockaddr_u *,
223 * Not all platforms support multicast
226 static isc_boolean_t socket_multicast_enable (endpt *, sockaddr_u *);
227 static isc_boolean_t socket_multicast_disable(endpt *, sockaddr_u *);
231 static void interface_dump (const endpt *);
232 static void sockaddr_dump (const sockaddr_u *);
233 static void print_interface (const endpt *, const char *, const char *);
234 #define DPRINT_INTERFACE(level, args) do { if (debug >= (level)) { print_interface args; } } while (0)
236 #define DPRINT_INTERFACE(level, args) do {} while (0)
239 typedef struct vsock vsock_t;
240 enum desc_type { FD_TYPE_SOCKET, FD_TYPE_FILE };
250 #if !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET)
252 * async notification processing (e. g. routing sockets)
255 * support for receiving data on fd that is not a refclock or a socket
256 * like e. g. routing sockets
258 struct asyncio_reader {
259 struct asyncio_reader *link; /* the list this is being kept in */
260 SOCKET fd; /* fd to be read */
261 void *data; /* possibly local data */
262 void (*receiver)(struct asyncio_reader *); /* input handler */
265 struct asyncio_reader *asyncio_reader_list;
267 static void delete_asyncio_reader (struct asyncio_reader *);
268 static struct asyncio_reader *new_asyncio_reader (void);
269 static void add_asyncio_reader (struct asyncio_reader *, enum desc_type);
270 static void remove_asyncio_reader (struct asyncio_reader *);
272 #endif /* !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET) */
274 static void init_async_notifications (void);
276 static int addr_eqprefix (const sockaddr_u *, const sockaddr_u *,
278 static int addr_samesubnet (const sockaddr_u *, const sockaddr_u *,
279 const sockaddr_u *, const sockaddr_u *);
280 static int create_sockets (u_short);
281 static SOCKET open_socket (sockaddr_u *, int, int, endpt *);
282 static char * fdbits (int, fd_set *);
283 static void set_reuseaddr (int);
284 static isc_boolean_t socket_broadcast_enable (struct interface *, SOCKET, sockaddr_u *);
285 #ifdef OS_MISSES_SPECIFIC_ROUTE_UPDATES
286 static isc_boolean_t socket_broadcast_disable (struct interface *, sockaddr_u *);
289 typedef struct remaddr remaddr_t;
297 remaddr_t * remoteaddr_list;
298 endpt * ep_list; /* complete endpt list */
299 endpt * mc4_list; /* IPv4 mcast-capable unicast endpts */
300 endpt * mc6_list; /* IPv6 mcast-capable unicast endpts */
302 static endpt * wildipv4;
303 static endpt * wildipv6;
306 int accept_wildcard_if_for_winnt;
308 const int accept_wildcard_if_for_winnt = FALSE;
311 static void add_fd_to_list (SOCKET, enum desc_type);
312 static endpt * find_addr_in_list (sockaddr_u *);
313 static endpt * find_flagged_addr_in_list(sockaddr_u *, u_int32);
314 static void delete_addr_from_list (sockaddr_u *);
315 static void delete_interface_from_list(endpt *);
316 static void close_and_delete_fd_from_list(SOCKET);
317 static void add_addr_to_list (sockaddr_u *, endpt *);
318 static void create_wildcards (u_short);
319 static endpt * findlocalinterface (sockaddr_u *, int, int);
320 static endpt * findclosestinterface (sockaddr_u *, int);
322 static const char * action_text (nic_rule_action);
324 static nic_rule_action interface_action(char *, sockaddr_u *, u_int32);
325 static void convert_isc_if (isc_interface_t *,
327 static void calc_addr_distance(sockaddr_u *,
330 static int cmp_addr_distance(const sockaddr_u *,
334 * Routines to read the ntp packets
336 #if !defined(HAVE_IO_COMPLETION_PORT)
337 static inline int read_network_packet (SOCKET, struct interface *, l_fp);
338 static void ntpd_addremove_io_fd (int, int, int);
339 static input_handler_t input_handler;
341 static inline int read_refclock_packet (SOCKET, struct refclockio *, l_fp);
347 #ifndef HAVE_IO_COMPLETION_PORT
356 if (fd < 0 || fd >= FD_SETSIZE) {
358 "Too many sockets in use, FD_SETSIZE %d exceeded by fd %d",
364 FD_SET(fd, &activefds);
365 maxactivefd = max(fd, maxactivefd);
367 FD_CLR(fd, &activefds);
368 if (maxactivefd && fd == maxactivefd) {
369 for (i = maxactivefd - 1; i >= 0; i--)
370 if (FD_ISSET(i, &activefds)) {
374 NTP_INSIST(fd != maxactivefd);
378 #endif /* !HAVE_IO_COMPLETION_PORT */
383 * collect timing information for various processing
384 * paths. currently we only pass them on to the file
385 * for later processing. this could also do histogram
386 * based analysis in other to reduce the load (and skew)
387 * dur to the file output
390 collect_timing(struct recvbuf *rb, const char *tag, int count, l_fp *dts)
394 snprintf(buf, sizeof(buf), "%s %d %s %s",
396 ? ((rb->dstadr != NULL)
397 ? stoa(&rb->recv_srcadr)
400 count, lfptoa(dts, 9), tag);
401 record_timing_stats(buf);
406 * About dynamic interfaces, sockets, reception and more...
408 * the code solves following tasks:
410 * - keep a current list of active interfaces in order
411 * to bind to to the interface address on NTP_PORT so that
412 * all wild and specific bindings for NTP_PORT are taken by ntpd
413 * to avoid other daemons messing with the time or sockets.
414 * - all interfaces keep a list of peers that are referencing
415 * the interface in order to quickly re-assign the peers to
416 * new interface in case an interface is deleted (=> gone from system or
418 * - have a preconfigured socket ready with the right local address
419 * for transmission and reception
420 * - have an address list for all destination addresses used within ntpd
421 * to find the "right" preconfigured socket.
422 * - facilitate updating the internal interface list with respect to
423 * the current kernel state
427 * - mapping of multicast addresses to the interface affected is not always
428 * one to one - especially on hosts with multiple interfaces
429 * the code here currently allocates a separate interface entry for those
430 * multicast addresses
431 * iff it is able to bind to a *new* socket with the multicast address (flags |= MCASTIF)
432 * in case of failure the multicast address is bound to an existing interface.
433 * - on some systems it is perfectly legal to assign the same address to
434 * multiple interfaces. Therefore this code does not keep a list of interfaces
435 * but a list of interfaces that represent a unique address as determined by the kernel
436 * by the procedure in findlocalinterface. Thus it is perfectly legal to see only
437 * one representative of a group of real interfaces if they share the same address.
439 * Frank Kardel 20050910
443 * init_io - initialize I/O module.
448 /* Init buffer free list and stat counters */
449 init_recvbuff(RECV_INIT);
450 /* update interface every 5 minutes as default */
451 interface_interval = 300;
454 addremove_io_fd = &ntpd_addremove_io_fd;
458 init_io_completion_port();
461 #if defined(HAVE_SIGNALED_IO)
462 (void) set_signal(input_handler);
468 ntpd_addremove_io_fd(
476 #ifdef HAVE_SIGNALED_IO
478 #endif /* not HAVE_SIGNALED_IO */
480 maintain_activefds(fd, remove_it);
485 * io_open_sockets - call socket creation routine
488 io_open_sockets(void)
490 static int already_opened;
492 if (already_opened || HAVE_OPT( SAVECONFIGQUIT ))
501 create_sockets(NTP_PORT);
504 init_async_notifications();
506 DPRINTF(3, ("io_open_sockets: maxactivefd %d\n", maxactivefd));
512 * function to dump the contents of the interface structure
513 * for debugging use only.
516 interface_dump(const endpt *itf)
518 printf("Dumping interface: %p\n", itf);
519 printf("fd = %d\n", itf->fd);
520 printf("bfd = %d\n", itf->bfd);
521 printf("sin = %s,\n", stoa(&itf->sin));
522 sockaddr_dump(&itf->sin);
523 printf("bcast = %s,\n", stoa(&itf->bcast));
524 sockaddr_dump(&itf->bcast);
525 printf("mask = %s,\n", stoa(&itf->mask));
526 sockaddr_dump(&itf->mask);
527 printf("name = %s\n", itf->name);
528 printf("flags = 0x%08x\n", itf->flags);
529 printf("last_ttl = %d\n", itf->last_ttl);
530 printf("addr_refid = %08x\n", itf->addr_refid);
531 printf("num_mcast = %d\n", itf->num_mcast);
532 printf("received = %ld\n", itf->received);
533 printf("sent = %ld\n", itf->sent);
534 printf("notsent = %ld\n", itf->notsent);
535 printf("ifindex = %u\n", itf->ifindex);
536 printf("peercnt = %u\n", itf->peercnt);
537 printf("phase = %u\n", itf->phase);
541 * sockaddr_dump - hex dump the start of a sockaddr_u
544 sockaddr_dump(const sockaddr_u *psau)
546 /* Limit the size of the sockaddr_in6 hex dump */
547 const int maxsize = min(32, sizeof(psau->sa6));
551 /* XXX: Should we limit maxsize based on psau->saX.sin_family? */
552 cp = (const void *)&psau->sa6;
554 for(i = 0; i < maxsize; i++) {
555 printf("%02x", *cp++);
563 * print_interface - helper to output debug information
566 print_interface(const endpt *iface, const char *pfx, const char *sfx)
568 printf("%sinterface #%d: fd=%d, bfd=%d, name=%s, flags=0x%x, ifindex=%u, sin=%s",
577 if (AF_INET == iface->family) {
578 if (iface->flags & INT_BROADCAST)
579 printf(", bcast=%s", stoa(&iface->bcast));
580 printf(", mask=%s", stoa(&iface->mask));
583 (iface->ignore_packets)
587 if (debug > 4) /* in-depth debugging only */
588 interface_dump(iface);
592 #if !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET)
594 * create an asyncio_reader structure
596 static struct asyncio_reader *
597 new_asyncio_reader(void)
599 struct asyncio_reader *reader;
601 reader = emalloc_zero(sizeof(*reader));
602 reader->fd = INVALID_SOCKET;
611 delete_asyncio_reader(
612 struct asyncio_reader *reader
619 * add asynchio_reader
623 struct asyncio_reader * reader,
626 LINK_SLIST(asyncio_reader_list, reader, link);
627 add_fd_to_list(reader->fd, type);
631 * remove asynchio_reader
634 remove_asyncio_reader(
635 struct asyncio_reader *reader
638 struct asyncio_reader *unlinked;
640 UNLINK_SLIST(unlinked, asyncio_reader_list, reader, link,
641 struct asyncio_reader);
643 if (reader->fd != INVALID_SOCKET)
644 close_and_delete_fd_from_list(reader->fd);
646 reader->fd = INVALID_SOCKET;
648 #endif /* !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET) */
651 /* compare two sockaddr prefixes */
654 const sockaddr_u * a,
655 const sockaddr_u * b,
661 isc_sockaddr_t isc_sa;
664 memcpy(&isc_sa.type, a, min(sizeof(isc_sa.type), sizeof(*a)));
665 isc_netaddr_fromsockaddr(&isc_a, &isc_sa);
668 memcpy(&isc_sa.type, b, min(sizeof(isc_sa.type), sizeof(*b)));
669 isc_netaddr_fromsockaddr(&isc_b, &isc_sa);
671 return (int)isc_netaddr_eqprefix(&isc_a, &isc_b,
678 const sockaddr_u * a,
679 const sockaddr_u * a_mask,
680 const sockaddr_u * b,
681 const sockaddr_u * b_mask
685 const u_int32 * pa_limit;
690 NTP_REQUIRE(AF(a) == AF(a_mask));
691 NTP_REQUIRE(AF(b) == AF(b_mask));
693 * With address and mask families verified to match, comparing
694 * the masks also validates the address's families match.
696 if (!SOCK_EQ(a_mask, b_mask))
700 loops = sizeof(NSRCADR6(a)) / sizeof(*pa);
701 pa = (const void *)&NSRCADR6(a);
702 pb = (const void *)&NSRCADR6(b);
703 pm = (const void *)&NSRCADR6(a_mask);
705 loops = sizeof(NSRCADR(a)) / sizeof(*pa);
706 pa = (const void *)&NSRCADR(a);
707 pb = (const void *)&NSRCADR(b);
708 pm = (const void *)&NSRCADR(a_mask);
710 for (pa_limit = pa + loops; pa < pa_limit; pa++, pb++, pm++)
711 if ((*pa & *pm) != (*pb & *pm))
719 * Code to tell if we have an IP address
720 * If we have then return the sockaddr structure
721 * and set the return value
722 * see the bind9/getaddresses.c for details
732 struct addrinfo hints;
733 struct addrinfo *result;
734 struct sockaddr_in6 *resaddr6;
738 NTP_REQUIRE(host != NULL);
739 NTP_REQUIRE(addr != NULL);
744 * Try IPv4, then IPv6. In order to handle the extended format
745 * for IPv6 scoped addresses (address%scope_ID), we'll use a local
746 * working buffer of 128 bytes. The length is an ad-hoc value, but
747 * should be enough for this purpose; the buffer can contain a string
748 * of at least 80 bytes for scope_ID in addition to any IPv6 numeric
749 * addresses (up to 46 bytes), the delimiter character and the
750 * terminating NULL character.
752 if (AF_UNSPEC == af || AF_INET == af)
753 if (inet_pton(AF_INET, host, &in4) == 1) {
755 SET_ADDR4N(addr, in4.s_addr);
760 if (AF_UNSPEC == af || AF_INET6 == af)
761 if (sizeof(tmpbuf) > strlen(host)) {
762 if ('[' == host[0]) {
763 strlcpy(tmpbuf, &host[1], sizeof(tmpbuf));
764 pch = strchr(tmpbuf, ']');
768 strlcpy(tmpbuf, host, sizeof(tmpbuf));
771 hints.ai_family = AF_INET6;
772 hints.ai_flags |= AI_NUMERICHOST;
773 if (getaddrinfo(tmpbuf, NULL, &hints, &result) == 0) {
775 resaddr6 = (struct sockaddr_in6 *)result->ai_addr;
776 SET_ADDR6N(addr, resaddr6->sin6_addr);
777 SET_SCOPE(addr, resaddr6->sin6_scope_id);
779 freeaddrinfo(result);
784 * If we got here it was not an IP address
791 * interface list enumerator - visitor pattern
795 interface_receiver_t receiver,
799 interface_info_t ifi;
801 ifi.action = IFS_EXISTS;
802 for (ifi.ep = ep_list; ifi.ep != NULL; ifi.ep = ifi.ep->elink)
803 (*receiver)(data, &ifi);
807 * do standard initialization of interface structure
815 ep->fd = INVALID_SOCKET;
816 ep->bfd = INVALID_SOCKET;
817 ep->phase = sys_interphase;
822 * create new interface structure initialize from
823 * template structure or via standard initialization
826 static struct interface *
828 struct interface *interface
831 struct interface * iface;
833 iface = emalloc(sizeof(*iface));
835 if (NULL == interface)
836 init_interface(iface);
837 else /* use the template */
838 memcpy(iface, interface, sizeof(*iface));
840 /* count every new instance of an interface in the system */
841 iface->ifnum = sys_ifnum++;
842 iface->starttime = current_time;
849 * return interface storage into free memory pool
861 * link interface into list of known interfaces
868 endpt ** pmclisthead;
876 int ep_univ_iid; /* iface ID from MAC address */
877 int scan_univ_iid; /* see RFC 4291 */
878 int ep_privacy; /* random local iface ID */
879 int scan_privacy; /* see RFC 4941 */
882 /* Calculate the refid */
883 ep->addr_refid = addr2refid(&ep->sin);
884 /* link at tail so ntpdc -c ifstats index increases each row */
885 LINK_TAIL_SLIST(ep_list, ep, elink, endpt);
888 /* the rest is for enabled multicast-capable addresses only */
889 if (ep->ignore_packets || !(INT_MULTICAST & ep->flags) ||
890 INT_LOOPBACK & ep->flags)
892 # ifndef INCLUDE_IPV6_MULTICAST_SUPPORT
893 if (AF_INET6 == ep->family)
896 pmclisthead = (AF_INET == ep->family)
900 if (AF_INET6 == ep->family) {
902 IN6_IS_ADDR_LINKLOCAL(PSOCK_ADDR6(&ep->sin)) ||
903 IN6_IS_ADDR_SITELOCAL(PSOCK_ADDR6(&ep->sin));
904 ep_univ_iid = IS_IID_UNIV(&ep->sin);
905 ep_privacy = !!(INT_PRIVACY & ep->flags);
911 DPRINTF(4, ("add_interface mcast-capable %s%s%s%s\n",
913 (ep_local) ? " link/scope-local" : "",
914 (ep_univ_iid) ? " univ-IID" : "",
915 (ep_privacy) ? " privacy" : ""));
917 * If we have multiple local addresses on the same network
918 * interface, and some are link- or site-local, do not multicast
919 * out from the link-/site-local addresses by default, to avoid
920 * duplicate manycastclient associations between v6 peers using
921 * link-local and global addresses. link-local can still be
922 * chosen using "nic ignore myv6globalprefix::/64".
923 * Similarly, if we have multiple global addresses from the same
924 * prefix on the same network interface, multicast from one,
925 * preferring EUI-64, then static, then least RFC 4941 privacy
928 for (scan = *pmclisthead; scan != NULL; scan = scan_next) {
929 scan_next = scan->mclink;
930 if (ep->family != scan->family)
932 if (strcmp(ep->name, scan->name))
934 same_subnet = addr_samesubnet(&ep->sin, &ep->mask,
935 &scan->sin, &scan->mask);
936 if (AF_INET6 == ep->family) {
939 IN6_IS_ADDR_LINKLOCAL(PSOCK_ADDR6(addr)) ||
940 IN6_IS_ADDR_SITELOCAL(PSOCK_ADDR6(addr));
941 scan_univ_iid = IS_IID_UNIV(addr);
942 scan_privacy = !!(INT_PRIVACY & scan->flags);
945 scan_univ_iid = FALSE;
946 scan_privacy = FALSE;
948 DPRINTF(4, ("add_interface mcast-capable scan %s%s%s%s\n",
950 (scan_local) ? " link/scope-local" : "",
951 (scan_univ_iid) ? " univ-IID" : "",
952 (scan_privacy) ? " privacy" : ""));
953 if ((ep_local && !scan_local) || (same_subnet &&
954 ((ep_privacy && !scan_privacy) ||
955 (!ep_univ_iid && scan_univ_iid)))) {
956 DPRINTF(4, ("did not add %s to %s of IPv6 multicast-capable list which already has %s\n",
964 if ((scan_local && !ep_local) || (same_subnet &&
965 ((scan_privacy && !ep_privacy) ||
966 (!scan_univ_iid && ep_univ_iid)))) {
967 UNLINK_SLIST(unlinked, *pmclisthead,
968 scan, mclink, endpt);
969 DPRINTF(4, ("%s %s from IPv6 multicast-capable list to add %s\n",
973 stoa(&scan->sin), stoa(&ep->sin)));
977 * Add link/site local at the tail of the multicast-
978 * capable unicast interfaces list, so that ntpd will
979 * send from global addresses before link-/site-local
983 LINK_TAIL_SLIST(*pmclisthead, ep, mclink, endpt);
985 LINK_SLIST(*pmclisthead, ep, mclink);
986 DPRINTF(4, ("added %s to %s of IPv%s multicast-capable unicast local address list\n",
991 (AF_INET == ep->family)
995 if (INVALID_SOCKET == ep->fd)
999 * select the local address from which to send to multicast.
1001 switch (AF(&ep->sin)) {
1004 rc = setsockopt(ep->fd, IPPROTO_IP,
1006 (void *)&NSRCADR(&ep->sin),
1007 sizeof(NSRCADR(&ep->sin)));
1010 "setsockopt IP_MULTICAST_IF %s fails: %m",
1014 # ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
1016 rc = setsockopt(ep->fd, IPPROTO_IPV6,
1018 (void *)&ep->ifindex,
1019 sizeof(ep->ifindex));
1020 /* do not complain if bound addr scope is ifindex */
1021 if (rc && ep->ifindex != SCOPE(&ep->sin))
1023 "setsockopt IPV6_MULTICAST_IF %u for %s fails: %m",
1024 ep->ifindex, stoa(&ep->sin));
1033 * remove interface from known interface list and clean up
1034 * associated resources
1042 endpt ** pmclisthead;
1045 UNLINK_SLIST(unlinked, ep_list, ep, elink, endpt);
1046 if (!ep->ignore_packets && INT_MULTICAST & ep->flags) {
1047 pmclisthead = (AF_INET == ep->family)
1050 UNLINK_SLIST(unlinked, *pmclisthead, ep, mclink, endpt);
1051 DPRINTF(4, ("%s %s IPv%s multicast-capable unicast local address list\n",
1056 (AF_INET == ep->family)
1060 delete_interface_from_list(ep);
1062 if (ep->fd != INVALID_SOCKET) {
1064 "Deleting interface #%d %s, %s#%d, interface stats: received=%ld, sent=%ld, dropped=%ld, active_time=%ld secs",
1072 current_time - ep->starttime);
1073 close_and_delete_fd_from_list(ep->fd);
1074 ep->fd = INVALID_SOCKET;
1077 if (ep->bfd != INVALID_SOCKET) {
1079 "stop listening for broadcasts to %s on interface #%d %s",
1080 stoa(&ep->bcast), ep->ifnum, ep->name);
1081 close_and_delete_fd_from_list(ep->bfd);
1082 ep->bfd = INVALID_SOCKET;
1083 ep->flags &= ~INT_BCASTOPEN;
1087 mon_clearinterface(ep);
1089 /* remove restrict interface entry */
1090 SET_HOSTMASK(&resmask, AF(&ep->sin));
1091 hack_restrict(RESTRICT_REMOVEIF, &ep->sin, &resmask,
1092 RESM_NTPONLY | RESM_INTERFACE, RES_IGNORE, 0);
1101 msyslog(LOG_INFO, "%s on %d %s %s",
1102 (ep->ignore_packets)
1104 : "Listen normally",
1117 #ifdef INCLUDE_IPV6_SUPPORT
1120 sockaddr_u wildaddr;
1121 nic_rule_action action;
1122 struct interface * wildif;
1125 * silence "potentially uninitialized" warnings from VC9
1126 * failing to follow the logic. Ideally action could remain
1127 * uninitialized, and the memset be the first statement under
1128 * the first if (v4wild).
1130 action = ACTION_LISTEN;
1133 #ifdef INCLUDE_IPV6_SUPPORT
1135 * create pseudo-interface with wildcard IPv6 address
1137 v6wild = ipv6_works;
1139 /* set wildaddr to the v6 wildcard address :: */
1141 AF(&wildaddr) = AF_INET6;
1142 SET_ADDR6N(&wildaddr, in6addr_any);
1143 SET_PORT(&wildaddr, port);
1144 SET_SCOPE(&wildaddr, 0);
1146 /* check for interface/nic rules affecting the wildcard */
1147 action = interface_action(NULL, &wildaddr, 0);
1148 v6wild = (ACTION_IGNORE != action);
1151 wildif = new_interface(NULL);
1153 strlcpy(wildif->name, "v6wildcard", sizeof(wildif->name));
1154 memcpy(&wildif->sin, &wildaddr, sizeof(wildif->sin));
1155 wildif->family = AF_INET6;
1156 AF(&wildif->mask) = AF_INET6;
1157 SET_ONESMASK(&wildif->mask);
1159 wildif->flags = INT_UP | INT_WILDCARD;
1160 wildif->ignore_packets = (ACTION_DROP == action);
1162 wildif->fd = open_socket(&wildif->sin, 0, 1, wildif);
1164 if (wildif->fd != INVALID_SOCKET) {
1166 any6_interface = wildif;
1167 add_addr_to_list(&wildif->sin, wildif);
1168 add_interface(wildif);
1169 log_listen_address(wildif);
1172 "unable to bind to wildcard address %s - another process may be running - EXITING",
1173 stoa(&wildif->sin));
1176 DPRINT_INTERFACE(2, (wildif, "created ", "\n"));
1181 * create pseudo-interface with wildcard IPv4 address
1183 v4wild = ipv4_works;
1185 /* set wildaddr to the v4 wildcard address 0.0.0.0 */
1186 AF(&wildaddr) = AF_INET;
1187 SET_ADDR4N(&wildaddr, INADDR_ANY);
1188 SET_PORT(&wildaddr, port);
1190 /* check for interface/nic rules affecting the wildcard */
1191 action = interface_action(NULL, &wildaddr, 0);
1192 v4wild = (ACTION_IGNORE != action);
1195 wildif = new_interface(NULL);
1197 strlcpy(wildif->name, "v4wildcard", sizeof(wildif->name));
1198 memcpy(&wildif->sin, &wildaddr, sizeof(wildif->sin));
1199 wildif->family = AF_INET;
1200 AF(&wildif->mask) = AF_INET;
1201 SET_ONESMASK(&wildif->mask);
1203 wildif->flags = INT_BROADCAST | INT_UP | INT_WILDCARD;
1204 wildif->ignore_packets = (ACTION_DROP == action);
1207 * enable multicast reception on the broadcast socket
1209 AF(&wildif->bcast) = AF_INET;
1210 SET_ADDR4N(&wildif->bcast, INADDR_ANY);
1211 SET_PORT(&wildif->bcast, port);
1213 wildif->fd = open_socket(&wildif->sin, 0, 1, wildif);
1215 if (wildif->fd != INVALID_SOCKET) {
1217 any_interface = wildif;
1219 add_addr_to_list(&wildif->sin, wildif);
1220 add_interface(wildif);
1221 log_listen_address(wildif);
1224 "unable to bind to wildcard address %s - another process may be running - EXITING",
1225 stoa(&wildif->sin));
1228 DPRINT_INTERFACE(2, (wildif, "created ", "\n"));
1234 * add_nic_rule() -- insert a rule entry at the head of nic_rule_list.
1238 nic_rule_match match_type,
1239 const char * if_name, /* interface name or numeric address */
1241 nic_rule_action action
1245 isc_boolean_t is_ip;
1247 rule = emalloc_zero(sizeof(*rule));
1248 rule->match_type = match_type;
1249 rule->prefixlen = prefixlen;
1250 rule->action = action;
1252 if (MATCH_IFNAME == match_type) {
1253 NTP_REQUIRE(NULL != if_name);
1254 rule->if_name = estrdup(if_name);
1255 } else if (MATCH_IFADDR == match_type) {
1256 NTP_REQUIRE(NULL != if_name);
1257 /* set rule->addr */
1258 is_ip = is_ip_address(if_name, AF_UNSPEC, &rule->addr);
1261 NTP_REQUIRE(NULL == if_name);
1263 LINK_SLIST(nic_rule_list, rule, next);
1270 nic_rule_action action
1278 t = "ERROR"; /* quiet uninit warning */
1279 DPRINTF(1, ("fatal: unknown nic_rule_action %d\n",
1302 static nic_rule_action
1305 sockaddr_u * if_addr,
1313 DPRINTF(4, ("interface_action: interface %s ",
1314 (if_name != NULL) ? if_name : "wildcard"));
1316 iswildcard = is_wildcard_addr(if_addr);
1317 isloopback = !!(INT_LOOPBACK & if_flags);
1320 * Find any matching NIC rule from --interface / -I or ntp.conf
1321 * interface/nic rules.
1323 for (rule = nic_rule_list; rule != NULL; rule = rule->next) {
1325 switch (rule->match_type) {
1328 /* loopback and wildcard excluded from "all" */
1329 if (isloopback || iswildcard)
1331 DPRINTF(4, ("nic all %s\n",
1332 action_text(rule->action)));
1333 return rule->action;
1336 if (IS_IPV4(if_addr)) {
1337 DPRINTF(4, ("nic ipv4 %s\n",
1338 action_text(rule->action)));
1339 return rule->action;
1344 if (IS_IPV6(if_addr)) {
1345 DPRINTF(4, ("nic ipv6 %s\n",
1346 action_text(rule->action)));
1347 return rule->action;
1351 case MATCH_WILDCARD:
1353 DPRINTF(4, ("nic wildcard %s\n",
1354 action_text(rule->action)));
1355 return rule->action;
1360 if (rule->prefixlen != -1) {
1361 if (addr_eqprefix(if_addr, &rule->addr,
1364 DPRINTF(4, ("subnet address match - %s\n",
1365 action_text(rule->action)));
1366 return rule->action;
1369 if (SOCK_EQ(if_addr, &rule->addr)) {
1371 DPRINTF(4, ("address match - %s\n",
1372 action_text(rule->action)));
1373 return rule->action;
1379 #if defined(HAVE_FNMATCH) && defined(FNM_CASEFOLD)
1380 && !fnmatch(rule->if_name, if_name, FNM_CASEFOLD)
1382 && !strcasecmp(if_name, rule->if_name)
1386 DPRINTF(4, ("interface name match - %s\n",
1387 action_text(rule->action)));
1388 return rule->action;
1395 * Unless explicitly disabled such as with "nic ignore ::1"
1396 * listen on loopback addresses. Since ntpq and ntpdc query
1397 * "localhost" by default, which typically resolves to ::1 and
1398 * 127.0.0.1, it's useful to default to listening on both.
1401 DPRINTF(4, ("default loopback listen\n"));
1402 return ACTION_LISTEN;
1406 * Treat wildcard addresses specially. If there is no explicit
1407 * "nic ... wildcard" or "nic ... 0.0.0.0" or "nic ... ::" rule
1411 DPRINTF(4, ("default wildcard drop\n"));
1416 * Check for "virtual IP" (colon in the interface name) after
1417 * the rules so that "ntpd --interface eth0:1 -novirtualips"
1418 * does indeed listen on eth0:1's addresses.
1420 if (!listen_to_virtual_ips && if_name != NULL
1421 && (strchr(if_name, ':') != NULL)) {
1423 DPRINTF(4, ("virtual ip - ignore\n"));
1424 return ACTION_IGNORE;
1428 * If there are no --interface/-I command-line options and no
1429 * interface/nic rules in ntp.conf, the default action is to
1430 * listen. In the presence of rules from either, the default
1431 * is to ignore. This implements ntpd's traditional listen-
1432 * every default with no interface listen configuration, and
1433 * ensures a single -I eth0 or "nic listen eth0" means do not
1434 * listen on any other addresses.
1436 if (NULL == nic_rule_list) {
1437 DPRINTF(4, ("default listen\n"));
1438 return ACTION_LISTEN;
1441 DPRINTF(4, ("implicit ignore\n"));
1442 return ACTION_IGNORE;
1448 isc_interface_t *isc_if,
1453 const u_char v6loop[16] = {0, 0, 0, 0, 0, 0, 0, 0,
1454 0, 0, 0, 0, 0, 0, 0, 1};
1456 strlcpy(itf->name, isc_if->name, sizeof(itf->name));
1457 itf->ifindex = isc_if->ifindex;
1458 itf->family = (u_short)isc_if->af;
1459 AF(&itf->sin) = itf->family;
1460 AF(&itf->mask) = itf->family;
1461 AF(&itf->bcast) = itf->family;
1462 SET_PORT(&itf->sin, port);
1463 SET_PORT(&itf->mask, port);
1464 SET_PORT(&itf->bcast, port);
1466 if (IS_IPV4(&itf->sin)) {
1467 NSRCADR(&itf->sin) = isc_if->address.type.in.s_addr;
1468 NSRCADR(&itf->mask) = isc_if->netmask.type.in.s_addr;
1470 if (isc_if->flags & INTERFACE_F_BROADCAST) {
1471 itf->flags |= INT_BROADCAST;
1472 NSRCADR(&itf->bcast) =
1473 isc_if->broadcast.type.in.s_addr;
1476 #ifdef INCLUDE_IPV6_SUPPORT
1477 else if (IS_IPV6(&itf->sin)) {
1478 SET_ADDR6N(&itf->sin, isc_if->address.type.in6);
1479 SET_ADDR6N(&itf->mask, isc_if->netmask.type.in6);
1481 SET_SCOPE(&itf->sin, isc_if->address.zone);
1483 #endif /* INCLUDE_IPV6_SUPPORT */
1486 /* Process the rest of the flags */
1489 ((INTERFACE_F_UP & isc_if->flags)
1491 | ((INTERFACE_F_LOOPBACK & isc_if->flags)
1493 | ((INTERFACE_F_POINTTOPOINT & isc_if->flags)
1495 | ((INTERFACE_F_MULTICAST & isc_if->flags)
1496 ? INT_MULTICAST : 0)
1497 | ((INTERFACE_F_PRIVACY & isc_if->flags)
1502 * Clear the loopback flag if the address is not localhost.
1503 * http://bugs.ntp.org/1683
1505 if (INT_LOOPBACK & itf->flags) {
1506 if (AF_INET == itf->family) {
1507 if (127 != (SRCADR(&itf->sin) >> 24))
1508 itf->flags &= ~INT_LOOPBACK;
1510 if (memcmp(v6loop, NSRCADR6(&itf->sin),
1511 sizeof(NSRCADR6(&itf->sin))))
1512 itf->flags &= ~INT_LOOPBACK;
1521 * some OSes have been observed to keep
1522 * cached routes even when more specific routes
1524 * this can be mitigated by re-binding
1529 struct interface * interface
1532 #ifdef OS_MISSES_SPECIFIC_ROUTE_UPDATES
1533 if (interface->fd != INVALID_SOCKET) {
1534 int bcast = (interface->flags & INT_BCASTXMIT) != 0;
1535 /* as we forcibly close() the socket remove the
1536 broadcast permission indication */
1538 socket_broadcast_disable(interface, &interface->sin);
1540 close_and_delete_fd_from_list(interface->fd);
1542 /* create new socket picking up a new first hop binding
1543 at connect() time */
1544 interface->fd = open_socket(&interface->sin,
1545 bcast, 0, interface);
1547 * reset TTL indication so TTL is is set again
1550 interface->last_ttl = 0;
1551 return (interface->fd != INVALID_SOCKET);
1553 return 0; /* invalid sockets are not refreshable */
1554 #else /* !OS_MISSES_SPECIFIC_ROUTE_UPDATES */
1555 return (interface->fd != INVALID_SOCKET);
1556 #endif /* !OS_MISSES_SPECIFIC_ROUTE_UPDATES */
1560 * interface_update - externally callable update function
1564 interface_receiver_t receiver,
1567 int new_interface_found;
1569 if (disable_dynamic_updates)
1573 new_interface_found = update_interfaces(NTP_PORT, receiver, data);
1576 if (!new_interface_found)
1580 msyslog(LOG_DEBUG, "new interface(s) found: waking up resolver");
1582 interrupt_worker_sleep();
1587 * sau_from_netaddr() - convert network address on-wire formats.
1588 * Convert from libisc's isc_netaddr_t to NTP's sockaddr_u
1593 const isc_netaddr_t *pna
1597 AF(psau) = (u_short)pna->family;
1598 switch (pna->family) {
1601 memcpy(&psau->sa4.sin_addr, &pna->type.in,
1602 sizeof(psau->sa4.sin_addr));
1606 memcpy(&psau->sa6.sin6_addr, &pna->type.in6,
1607 sizeof(psau->sa6.sin6_addr));
1615 const sockaddr_u *psau
1618 if (IS_IPV4(psau) && !NSRCADR(psau))
1621 #ifdef INCLUDE_IPV6_SUPPORT
1622 if (IS_IPV6(psau) && S_ADDR6_EQ(psau, &in6addr_any))
1630 #ifdef OS_NEEDS_REUSEADDR_FOR_IFADDRBIND
1632 * enable/disable re-use of wildcard address socket
1640 struct interface *any;
1641 SOCKET fd = INVALID_SOCKET;
1643 any = ANY_INTERFACE_BYFAM(family);
1647 if (fd != INVALID_SOCKET) {
1648 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1649 (char *)&on, sizeof(on)))
1651 "set_wildcard_reuse: setsockopt(SO_REUSEADDR, %s) failed: %m",
1654 DPRINTF(4, ("set SO_REUSEADDR to %s on %s\n",
1659 #endif /* OS_NEEDS_REUSEADDR_FOR_IFADDRBIND */
1662 static isc_boolean_t
1669 #if defined(INCLUDE_IPV6_SUPPORT) && defined(SIOCGIFAFLAG_IN6) && \
1670 (defined(IN6_IFF_ANYCAST) || defined(IN6_IFF_NOTREADY))
1671 struct in6_ifreq ifr6;
1673 u_int32 exclude = 0;
1675 if (psau->sa.sa_family != AF_INET6)
1677 if ((fd = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1680 memcpy(&ifr6.ifr_addr, &psau->sa6, sizeof(ifr6.ifr_addr));
1681 strlcpy(ifr6.ifr_name, name, sizeof(ifr6.ifr_name));
1682 if (ioctl(fd, SIOCGIFAFLAG_IN6, &ifr6) < 0) {
1687 flags6 = ifr6.ifr_ifru.ifru_flags6;
1688 #if defined(IN6_IFF_ANYCAST)
1689 exclude |= IN6_IFF_ANYCAST;
1690 #endif /* !IN6_IFF_ANYCAST */
1691 #if defined(IN6_IFF_NOTREADY)
1692 exclude |= IN6_IFF_NOTREADY;
1693 #endif /* !IN6_IFF_NOTREADY */
1694 if ((flags6 & exclude) != 0)
1696 #endif /* INCLUDE_IPV6_SUPPORT && SIOCGIFAFLAG_IN6 && (IN6_IFF_ANYCAST && IN6_IFF_NOTREADY) */
1700 static isc_boolean_t
1706 #ifdef IN6_IFF_ANYCAST
1707 return check_flags6(psau, name, IN6_IFF_ANYCAST);
1713 static isc_boolean_t
1722 #ifdef IN6_IFF_DEPARTED
1723 flags6 |= IN6_IFF_DEPARTED;
1725 #ifdef IN6_IFF_DETACHED
1726 flags6 |= IN6_IFF_DETACHED;
1728 #ifdef IN6_IFF_TENTATIVE
1729 flags6 |= IN6_IFF_TENTATIVE;
1731 return check_flags6(psau, name, flags6) ? ISC_FALSE : ISC_TRUE;
1735 * update_interface strategy
1737 * toggle configuration phase
1740 * forall currently existing interfaces
1741 * if address is known:
1742 * drop socket - rebind again
1744 * if address is NOT known:
1745 * attempt to create a new interface entry
1748 * forall currently known non MCAST and WILDCARD interfaces
1749 * if interface does not match configuration phase (not seen in phase 1):
1750 * remove interface from known interface list
1751 * forall peers associated with this interface
1752 * disconnect peer from this interface
1755 * attempt to re-assign interfaces to peers
1762 interface_receiver_t receiver,
1766 isc_mem_t * mctx = (void *)-1;
1767 interface_info_t ifi;
1768 isc_interfaceiter_t * iter;
1769 isc_result_t result;
1770 isc_interface_t isc_if;
1771 int new_interface_found;
1772 unsigned int family;
1777 DPRINTF(3, ("update_interfaces(%d)\n", port));
1780 * phase one - scan interfaces
1781 * - create those that are not found
1782 * - update those that are found
1785 new_interface_found = FALSE;
1787 result = isc_interfaceiter_create(mctx, &iter);
1789 if (result != ISC_R_SUCCESS)
1793 * Toggle system interface scan phase to find untouched
1794 * interfaces to be deleted.
1796 sys_interphase ^= 0x1;
1798 for (result = isc_interfaceiter_first(iter);
1799 ISC_R_SUCCESS == result;
1800 result = isc_interfaceiter_next(iter)) {
1802 result = isc_interfaceiter_current(iter, &isc_if);
1804 if (result != ISC_R_SUCCESS)
1807 /* See if we have a valid family to use */
1808 family = isc_if.address.family;
1809 if (AF_INET != family && AF_INET6 != family)
1811 if (AF_INET == family && !ipv4_works)
1813 if (AF_INET6 == family && !ipv6_works)
1816 /* create prototype */
1817 init_interface(&enumep);
1819 convert_isc_if(&isc_if, &enumep, port);
1821 DPRINT_INTERFACE(4, (&enumep, "examining ", "\n"));
1824 * Check if and how we are going to use the interface.
1826 switch (interface_action(enumep.name, &enumep.sin,
1830 DPRINTF(4, ("ignoring interface %s (%s) - by nic rules\n",
1831 enumep.name, stoa(&enumep.sin)));
1835 DPRINTF(4, ("listen interface %s (%s) - by nic rules\n",
1836 enumep.name, stoa(&enumep.sin)));
1837 enumep.ignore_packets = ISC_FALSE;
1841 DPRINTF(4, ("drop on interface %s (%s) - by nic rules\n",
1842 enumep.name, stoa(&enumep.sin)));
1843 enumep.ignore_packets = ISC_TRUE;
1847 /* interfaces must be UP to be usable */
1848 if (!(enumep.flags & INT_UP)) {
1849 DPRINTF(4, ("skipping interface %s (%s) - DOWN\n",
1850 enumep.name, stoa(&enumep.sin)));
1855 * skip any interfaces UP and bound to a wildcard
1856 * address - some dhcp clients produce that in the
1859 if (is_wildcard_addr(&enumep.sin))
1862 if (is_not_bindable(&enumep.sin, isc_if.name))
1866 * skip any address that is an invalid state to be used
1868 if (!is_valid(&enumep.sin, isc_if.name))
1872 * map to local *address* in order to map all duplicate
1873 * interfaces to an endpt structure with the appropriate
1874 * socket. Our name space is (ip-address), NOT
1875 * (interface name, ip-address).
1877 ep = getinterface(&enumep.sin, INT_WILDCARD);
1879 if (ep != NULL && refresh_interface(ep)) {
1881 * found existing and up to date interface -
1884 if (ep->phase != sys_interphase) {
1886 * On a new round we reset the name so
1887 * the interface name shows up again if
1888 * this address is no longer shared.
1889 * We reset ignore_packets from the
1890 * new prototype to respect any runtime
1891 * changes to the nic rules.
1893 strlcpy(ep->name, enumep.name,
1895 ep->ignore_packets =
1896 enumep.ignore_packets;
1898 /* name collision - rename interface */
1899 strlcpy(ep->name, "*multiple*",
1903 DPRINT_INTERFACE(4, (ep, "updating ",
1906 if (ep->ignore_packets !=
1907 enumep.ignore_packets) {
1909 * We have conflicting configurations
1910 * for the interface address. This is
1911 * caused by using -I <interfacename>
1912 * for an interface that shares its
1913 * address with other interfaces. We
1914 * can not disambiguate incoming
1915 * packets delivered to this socket
1916 * without extra syscalls/features.
1917 * These are not (commonly) available.
1918 * Note this is a more unusual
1919 * configuration where several
1920 * interfaces share an address but
1921 * filtering via interface name is
1922 * attempted. We resolve the
1923 * configuration conflict by disabling
1924 * the processing of received packets.
1925 * This leads to no service on the
1926 * interface address where the conflict
1930 "WARNING: conflicting enable configuration for interfaces %s and %s for address %s - unsupported configuration - address DISABLED",
1931 enumep.name, ep->name,
1934 ep->ignore_packets = ISC_TRUE;
1937 ep->phase = sys_interphase;
1939 ifi.action = IFS_EXISTS;
1941 if (receiver != NULL)
1942 (*receiver)(data, &ifi);
1945 * This is new or refreshing failed - add to
1946 * our interface list. If refreshing failed we
1947 * will delete the interface structure in phase
1948 * 2 as the interface was not marked current.
1949 * We can bind to the address as the refresh
1950 * code already closed the offending socket
1952 ep = create_interface(port, &enumep);
1955 ifi.action = IFS_CREATED;
1957 if (receiver != NULL)
1958 (*receiver)(data, &ifi);
1960 new_interface_found = TRUE;
1963 " new - created\n"));
1966 (&enumep, "updating ",
1967 " new - creation FAILED"));
1970 "failed to init interface for address %s",
1977 isc_interfaceiter_destroy(&iter);
1980 * phase 2 - delete gone interfaces - reassigning peers to
1983 for (ep = ep_list; ep != NULL; ep = next_ep) {
1984 next_ep = ep->elink;
1987 * if phase does not match sys_phase this interface was
1988 * not enumerated during the last interface scan - so it
1989 * is gone and will be deleted here unless it did not
1990 * originate from interface enumeration (INT_WILDCARD,
1993 if (((INT_WILDCARD | INT_MCASTIF) & ep->flags) ||
1994 ep->phase == sys_interphase)
1997 DPRINT_INTERFACE(3, (ep, "updating ",
1998 "GONE - deleting\n"));
1999 remove_interface(ep);
2001 ifi.action = IFS_DELETED;
2003 if (receiver != NULL)
2004 (*receiver)(data, &ifi);
2006 /* disconnect peers from deleted endpt. */
2007 while (ep->peers != NULL)
2008 set_peerdstadr(ep->peers, NULL);
2011 * update globals in case we lose
2012 * a loopback interface
2014 if (ep == loopback_interface)
2015 loopback_interface = NULL;
2017 delete_interface(ep);
2021 * phase 3 - re-configure as the world has possibly changed
2023 * never ever make this conditional again - it is needed to track
2024 * routing updates. see bug #2506
2026 refresh_all_peerinterfaces();
2028 if (broadcast_client_enabled)
2035 * Check multicast interfaces and try to join multicast groups if
2038 for (ep = ep_list; ep != NULL; ep = ep->elink) {
2041 if (!(INT_MCASTIF & ep->flags) || (INT_MCASTOPEN & ep->flags))
2044 /* Find remote address that was linked to this interface */
2045 for (entry = remoteaddr_list;
2047 entry = entry->link) {
2048 if (entry->ep == ep) {
2049 if (socket_multicast_enable(ep, &entry->addr)) {
2051 "Joined %s socket to multicast group %s",
2053 stoa(&entry->addr));
2060 return new_interface_found;
2065 * create_sockets - create a socket for each interface plus a default
2066 * socket for when we don't know where to send
2073 #ifndef HAVE_IO_COMPLETION_PORT
2075 * I/O Completion Ports don't care about the select and FD_SET
2078 FD_ZERO(&activefds);
2081 DPRINTF(2, ("create_sockets(%d)\n", port));
2083 create_wildcards(port);
2085 update_interfaces(port, NULL, NULL);
2088 * Now that we have opened all the sockets, turn off the reuse
2089 * flag for security.
2093 DPRINTF(2, ("create_sockets: Total interfaces = %d\n", ninterfaces));
2099 * create_interface - create a new interface for a given prototype
2100 * binding the socket.
2102 static struct interface *
2105 struct interface * protot
2110 #if defined(MCAST) && defined(MULTICAST_NONEWSOCKET)
2112 remaddr_t * next_entry;
2114 DPRINTF(2, ("create_interface(%s#%d)\n", stoa(&protot->sin),
2117 /* build an interface */
2118 iface = new_interface(protot);
2123 iface->fd = open_socket(&iface->sin, 0, 0, iface);
2125 if (iface->fd != INVALID_SOCKET)
2126 log_listen_address(iface);
2128 if ((INT_BROADCAST & iface->flags)
2129 && iface->bfd != INVALID_SOCKET)
2130 msyslog(LOG_INFO, "Listening on broadcast address %s#%d",
2131 stoa((&iface->bcast)), port);
2133 if (INVALID_SOCKET == iface->fd
2134 && INVALID_SOCKET == iface->bfd) {
2135 msyslog(LOG_ERR, "unable to create socket on %s (%d) for %s#%d",
2138 stoa((&iface->sin)),
2140 delete_interface(iface);
2145 * Blacklist our own addresses, no use talking to ourself
2147 SET_HOSTMASK(&resmask, AF(&iface->sin));
2148 hack_restrict(RESTRICT_FLAGS, &iface->sin, &resmask,
2149 RESM_NTPONLY | RESM_INTERFACE, RES_IGNORE, 0);
2152 * set globals with the first found
2153 * loopback interface of the appropriate class
2155 if (NULL == loopback_interface && AF_INET == iface->family
2156 && (INT_LOOPBACK & iface->flags))
2157 loopback_interface = iface;
2160 * put into our interface list
2162 add_addr_to_list(&iface->sin, iface);
2163 add_interface(iface);
2165 #if defined(MCAST) && defined(MULTICAST_NONEWSOCKET)
2167 * Join any previously-configured compatible multicast groups.
2169 if (INT_MULTICAST & iface->flags &&
2170 !((INT_LOOPBACK | INT_WILDCARD) & iface->flags) &&
2171 !iface->ignore_packets) {
2172 for (entry = remoteaddr_list;
2174 entry = next_entry) {
2175 next_entry = entry->link;
2176 if (AF(&iface->sin) != AF(&entry->addr) ||
2177 !IS_MCAST(&entry->addr))
2179 if (socket_multicast_enable(iface,
2182 "Joined %s socket to multicast group %s",
2184 stoa(&entry->addr));
2187 "Failed to join %s socket to multicast group %s",
2189 stoa(&entry->addr));
2192 #endif /* MCAST && MCAST_NONEWSOCKET */
2194 DPRINT_INTERFACE(2, (iface, "created ", "\n"));
2199 #ifdef SO_EXCLUSIVEADDRUSE
2211 failed = setsockopt(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
2212 (char *)&one, sizeof(one));
2219 * Prior to Windows XP setting SO_EXCLUSIVEADDRUSE can fail with
2220 * error WSAINVAL depending on service pack level and whether
2221 * the user account is in the Administrators group. Do not
2222 * complain if it fails that way on versions prior to XP (5.1).
2224 err = GetLastError();
2226 if (isc_win32os_versioncheck(5, 1, 0, 0) < 0 /* < 5.1/XP */
2227 && WSAEINVAL == err)
2233 "setsockopt(%d, SO_EXCLUSIVEADDRUSE, on): %m",
2236 #endif /* SO_EXCLUSIVEADDRUSE */
2240 * set_reuseaddr() - set/clear REUSEADDR on all sockets
2241 * NB possible hole - should we be doing this on broadcast
2249 #ifndef SO_EXCLUSIVEADDRUSE
2252 for (ep = ep_list; ep != NULL; ep = ep->elink) {
2253 if (ep->flags & INT_WILDCARD)
2257 * if ep->fd is INVALID_SOCKET, we might have a adapter
2258 * configured but not present
2260 DPRINTF(4, ("setting SO_REUSEADDR on %.16s@%s to %s\n",
2261 ep->name, stoa(&ep->sin),
2262 flag ? "on" : "off"));
2264 if (ep->fd != INVALID_SOCKET) {
2265 if (setsockopt(ep->fd, SOL_SOCKET, SO_REUSEADDR,
2266 (char *)&flag, sizeof(flag))) {
2267 msyslog(LOG_ERR, "set_reuseaddr: setsockopt(%s, SO_REUSEADDR, %s) failed: %m",
2268 stoa(&ep->sin), flag ? "on" : "off");
2272 #endif /* ! SO_EXCLUSIVEADDRUSE */
2276 * This is just a wrapper around an internal function so we can
2277 * make other changes as necessary later on
2281 struct interface * iface,
2285 #ifdef OPEN_BCAST_SOCKET
2286 socket_broadcast_enable(iface, iface->fd, baddr);
2290 #ifdef OPEN_BCAST_SOCKET
2292 * Enable a broadcast address to a given socket
2293 * The socket is in the ep_list all we need to do is enable
2294 * broadcasting. It is not this function's job to select the socket
2296 static isc_boolean_t
2297 socket_broadcast_enable(
2298 struct interface * iface,
2306 if (IS_IPV4(baddr)) {
2307 /* if this interface can support broadcast, set SO_BROADCAST */
2308 if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST,
2309 (char *)&on, sizeof(on)))
2311 "setsockopt(SO_BROADCAST) enable failure on address %s: %m",
2314 DPRINTF(2, ("Broadcast enabled on socket %d for address %s\n",
2317 iface->flags |= INT_BCASTXMIT;
2321 #endif /* SO_BROADCAST */
2324 #ifdef OS_MISSES_SPECIFIC_ROUTE_UPDATES
2326 * Remove a broadcast address from a given socket
2327 * The socket is in the ep_list all we need to do is disable
2328 * broadcasting. It is not this function's job to select the socket
2330 static isc_boolean_t
2331 socket_broadcast_disable(
2332 struct interface * iface,
2337 int off = 0; /* This seems to be OK as an int */
2339 if (IS_IPV4(baddr) && setsockopt(iface->fd, SOL_SOCKET,
2340 SO_BROADCAST, (char *)&off, sizeof(off)))
2342 "setsockopt(SO_BROADCAST) disable failure on address %s: %m",
2345 iface->flags &= ~INT_BCASTXMIT;
2349 #endif /* SO_BROADCAST */
2351 #endif /* OS_MISSES_SPECIFIC_ROUTE_UPDATES */
2353 #endif /* OPEN_BCAST_SOCKET */
2356 * return the broadcast client flag value
2359 get_broadcastclient_flag(void)
2361 return (broadcast_client_enabled);
2364 * Check to see if the address is a multicast address
2366 static isc_boolean_t
2371 isc_boolean_t result;
2373 #ifndef INCLUDE_IPV6_MULTICAST_SUPPORT
2375 * If we don't have IPV6 support any IPV6 addr is not multicast
2381 result = IS_MCAST(maddr);
2384 DPRINTF(4, ("address %s is not multicast\n",
2391 * Multicast servers need to set the appropriate Multicast interface
2392 * socket option in order for it to know which interface to use for
2393 * send the multicast packet.
2396 enable_multicast_if(
2397 struct interface * iface,
2402 #ifdef IP_MULTICAST_LOOP
2403 TYPEOF_IP_MULTICAST_LOOP off = 0;
2405 #if defined(INCLUDE_IPV6_MULTICAST_SUPPORT) && defined(IPV6_MULTICAST_LOOP)
2409 NTP_REQUIRE(AF(maddr) == AF(&iface->sin));
2411 switch (AF(&iface->sin)) {
2414 #ifdef IP_MULTICAST_LOOP
2416 * Don't send back to itself, but allow failure to set
2418 if (setsockopt(iface->fd, IPPROTO_IP,
2420 SETSOCKOPT_ARG_CAST &off,
2424 "setsockopt IP_MULTICAST_LOOP failed: %m on socket %d, addr %s for multicast address %s",
2425 iface->fd, stoa(&iface->sin),
2432 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2433 #ifdef IPV6_MULTICAST_LOOP
2435 * Don't send back to itself, but allow failure to set
2437 if (setsockopt(iface->fd, IPPROTO_IPV6,
2438 IPV6_MULTICAST_LOOP,
2439 (char *) &off6, sizeof(off6))) {
2442 "setsockopt IPV6_MULTICAST_LOOP failed: %m on socket %d, addr %s for multicast address %s",
2443 iface->fd, stoa(&iface->sin),
2450 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */
2457 * Add a multicast address to a given socket
2458 * The socket is in the ep_list all we need to do is enable
2459 * multicasting. It is not this function's job to select the socket
2462 static isc_boolean_t
2463 socket_multicast_enable(
2468 struct ip_mreq mreq;
2469 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2470 struct ipv6_mreq mreq6;
2472 switch (AF(maddr)) {
2476 mreq.imr_multiaddr = SOCK_ADDR4(maddr);
2477 mreq.imr_interface.s_addr = htonl(INADDR_ANY);
2478 if (setsockopt(iface->fd,
2484 "setsockopt IP_ADD_MEMBERSHIP failed: %m on socket %d, addr %s for %x / %x (%s)",
2485 iface->fd, stoa(&iface->sin),
2486 mreq.imr_multiaddr.s_addr,
2487 mreq.imr_interface.s_addr,
2491 DPRINTF(4, ("Added IPv4 multicast membership on socket %d, addr %s for %x / %x (%s)\n",
2492 iface->fd, stoa(&iface->sin),
2493 mreq.imr_multiaddr.s_addr,
2494 mreq.imr_interface.s_addr, stoa(maddr)));
2498 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2500 * Enable reception of multicast packets.
2501 * If the address is link-local we can get the
2502 * interface index from the scope id. Don't do this
2503 * for other types of multicast addresses. For now let
2504 * the kernel figure it out.
2507 mreq6.ipv6mr_multiaddr = SOCK_ADDR6(maddr);
2508 mreq6.ipv6mr_interface = iface->ifindex;
2510 if (setsockopt(iface->fd, IPPROTO_IPV6,
2511 IPV6_JOIN_GROUP, (char *)&mreq6,
2514 "setsockopt IPV6_JOIN_GROUP failed: %m on socket %d, addr %s for interface %u (%s)",
2515 iface->fd, stoa(&iface->sin),
2516 mreq6.ipv6mr_interface, stoa(maddr)));
2519 DPRINTF(4, ("Added IPv6 multicast group on socket %d, addr %s for interface %u (%s)\n",
2520 iface->fd, stoa(&iface->sin),
2521 mreq6.ipv6mr_interface, stoa(maddr)));
2524 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */
2526 iface->flags |= INT_MCASTOPEN;
2535 * Remove a multicast address from a given socket
2536 * The socket is in the ep_list all we need to do is disable
2537 * multicasting. It is not this function's job to select the socket
2540 static isc_boolean_t
2541 socket_multicast_disable(
2542 struct interface * iface,
2546 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2547 struct ipv6_mreq mreq6;
2549 struct ip_mreq mreq;
2553 if (find_addr_in_list(maddr) == NULL) {
2554 DPRINTF(4, ("socket_multicast_disable(%s): not found\n",
2559 switch (AF(maddr)) {
2562 mreq.imr_multiaddr = SOCK_ADDR4(maddr);
2563 mreq.imr_interface = SOCK_ADDR4(&iface->sin);
2564 if (setsockopt(iface->fd, IPPROTO_IP,
2565 IP_DROP_MEMBERSHIP, (char *)&mreq,
2569 "setsockopt IP_DROP_MEMBERSHIP failed: %m on socket %d, addr %s for %x / %x (%s)",
2570 iface->fd, stoa(&iface->sin),
2571 SRCADR(maddr), SRCADR(&iface->sin),
2577 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2579 * Disable reception of multicast packets
2580 * If the address is link-local we can get the
2581 * interface index from the scope id. Don't do this
2582 * for other types of multicast addresses. For now let
2583 * the kernel figure it out.
2585 mreq6.ipv6mr_multiaddr = SOCK_ADDR6(maddr);
2586 mreq6.ipv6mr_interface = iface->ifindex;
2588 if (setsockopt(iface->fd, IPPROTO_IPV6,
2589 IPV6_LEAVE_GROUP, (char *)&mreq6,
2593 "setsockopt IPV6_LEAVE_GROUP failure: %m on socket %d, addr %s for %d (%s)",
2594 iface->fd, stoa(&iface->sin),
2595 iface->ifindex, stoa(maddr));
2601 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */
2605 if (!iface->num_mcast)
2606 iface->flags &= ~INT_MCASTOPEN;
2613 * io_setbclient - open the broadcast client sockets
2618 #ifdef OPEN_BCAST_SOCKET
2619 struct interface * interf;
2625 for (interf = ep_list;
2627 interf = interf->elink) {
2629 if (interf->flags & (INT_WILDCARD | INT_LOOPBACK))
2632 /* use only allowed addresses */
2633 if (interf->ignore_packets)
2636 /* Need a broadcast-capable interface */
2637 if (!(interf->flags & INT_BROADCAST))
2640 /* Only IPv4 addresses are valid for broadcast */
2641 NTP_REQUIRE(IS_IPV4(&interf->sin));
2643 /* Do we already have the broadcast address open? */
2644 if (interf->flags & INT_BCASTOPEN) {
2646 * account for already open interfaces to avoid
2647 * misleading warning below
2654 * Try to open the broadcast address
2656 interf->family = AF_INET;
2657 interf->bfd = open_socket(&interf->bcast, 1, 0, interf);
2660 * If we succeeded then we use it otherwise enable
2661 * broadcast on the interface address
2663 if (interf->bfd != INVALID_SOCKET) {
2665 interf->flags |= INT_BCASTOPEN;
2667 "Listen for broadcasts to %s on interface #%d %s",
2668 stoa(&interf->bcast), interf->ifnum, interf->name);
2670 /* silently ignore EADDRINUSE as we probably opened
2671 the socket already for an address in the same network */
2672 if (errno != EADDRINUSE)
2674 "failed to listen for broadcasts to %s on interface #%d %s",
2675 stoa(&interf->bcast), interf->ifnum, interf->name);
2680 broadcast_client_enabled = ISC_TRUE;
2681 DPRINTF(1, ("io_setbclient: listening to %d broadcast addresses\n", nif));
2684 broadcast_client_enabled = ISC_FALSE;
2686 "Unable to listen for broadcasts, no broadcast interfaces available");
2690 "io_setbclient: Broadcast Client disabled by build");
2691 #endif /* OPEN_BCAST_SOCKET */
2695 * io_unsetbclient - close the broadcast client sockets
2698 io_unsetbclient(void)
2702 for (ep = ep_list; ep != NULL; ep = ep->elink) {
2703 if (INT_WILDCARD & ep->flags)
2705 if (!(INT_BCASTOPEN & ep->flags))
2708 if (ep->bfd != INVALID_SOCKET) {
2709 /* destroy broadcast listening socket */
2711 "stop listening for broadcasts to %s on interface #%d %s",
2712 stoa(&ep->bcast), ep->ifnum, ep->name);
2713 close_and_delete_fd_from_list(ep->bfd);
2714 ep->bfd = INVALID_SOCKET;
2715 ep->flags &= ~INT_BCASTOPEN;
2718 broadcast_client_enabled = ISC_FALSE;
2722 * io_multicast_add() - add multicast group address
2734 * Check to see if this is a multicast address
2736 if (!addr_ismulticast(addr))
2739 /* If we already have it we can just return */
2740 if (NULL != find_flagged_addr_in_list(addr, INT_MCASTOPEN)) {
2742 "Duplicate request found for multicast address %s",
2747 #ifndef MULTICAST_NONEWSOCKET
2748 ep = new_interface(NULL);
2751 * Open a new socket for the multicast address
2754 SET_PORT(&ep->sin, NTP_PORT);
2755 ep->family = AF(&ep->sin);
2756 AF(&ep->mask) = ep->family;
2757 SET_ONESMASK(&ep->mask);
2760 ep->bfd = INVALID_SOCKET;
2761 ep->fd = open_socket(&ep->sin, 0, 0, ep);
2762 if (ep->fd != INVALID_SOCKET) {
2763 ep->ignore_packets = ISC_FALSE;
2764 ep->flags |= INT_MCASTIF;
2766 strlcpy(ep->name, "multicast", sizeof(ep->name));
2767 DPRINT_INTERFACE(2, (ep, "multicast add ", "\n"));
2769 log_listen_address(ep);
2771 /* bind failed, re-use wildcard interface */
2772 delete_interface(ep);
2776 else if (IS_IPV6(addr))
2782 /* HACK ! -- stuff in an address */
2783 /* because we don't bind addr? DH */
2786 "multicast address %s using wildcard interface #%d %s",
2787 stoa(addr), ep->ifnum, ep->name);
2790 "No multicast socket available to use for address %s",
2795 { /* in place of the { following for in #else clause */
2797 #else /* MULTICAST_NONEWSOCKET follows */
2799 * For the case where we can't use a separate socket (Windows)
2800 * join each applicable endpoint socket to the group address.
2806 for (ep = ep_list; ep != NULL; ep = ep->elink) {
2807 if (ep->ignore_packets || AF(&ep->sin) != AF(addr) ||
2808 !(INT_MULTICAST & ep->flags) ||
2809 (INT_LOOPBACK | INT_WILDCARD) & ep->flags)
2812 #endif /* MULTICAST_NONEWSOCKET */
2813 if (socket_multicast_enable(ep, addr))
2815 "Joined %s socket to multicast group %s",
2820 add_addr_to_list(addr, one_ep);
2821 #else /* !MCAST follows*/
2823 "Can not add multicast address %s: no multicast support",
2831 * io_multicast_del() - delete multicast group address
2842 * Check to see if this is a multicast address
2844 if (!addr_ismulticast(addr)) {
2845 msyslog(LOG_ERR, "invalid multicast address %s",
2851 * Disable reception of multicast packets
2853 while ((iface = find_flagged_addr_in_list(addr, INT_MCASTOPEN))
2855 socket_multicast_disable(iface, addr);
2857 delete_addr_from_list(addr);
2859 #else /* not MCAST */
2861 "Can not delete multicast address %s: no multicast support",
2863 #endif /* not MCAST */
2868 * open_socket - open a socket, returning the file descriptor
2882 * int is OK for REUSEADR per
2883 * http://www.kohala.com/start/mcast.api.txt
2888 if (IS_IPV6(addr) && !ipv6_works)
2889 return INVALID_SOCKET;
2891 /* create a datagram (UDP) socket */
2892 fd = socket(AF(addr), SOCK_DGRAM, 0);
2893 if (INVALID_SOCKET == fd) {
2894 errval = socket_errno();
2896 "socket(AF_INET%s, SOCK_DGRAM, 0) failed on address %s: %m",
2897 IS_IPV6(addr) ? "6" : "", stoa(addr));
2899 if (errval == EPROTONOSUPPORT ||
2900 errval == EAFNOSUPPORT ||
2901 errval == EPFNOSUPPORT)
2902 return (INVALID_SOCKET);
2906 "unexpected socket() error %m code %d (not EPROTONOSUPPORT nor EAFNOSUPPORT nor EPFNOSUPPORT) - exiting",
2912 connection_reset_fix(fd, addr);
2915 * Fixup the file descriptor for some systems
2916 * See bug #530 for details of the issue.
2921 * set SO_REUSEADDR since we will be binding the same port
2922 * number on each interface according to turn_off_reuse.
2923 * This is undesirable on Windows versions starting with
2924 * Windows XP (numeric version 5.1).
2927 if (isc_win32os_versioncheck(5, 1, 0, 0) < 0) /* before 5.1 */
2929 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
2930 (char *)((turn_off_reuse)
2936 "setsockopt SO_REUSEADDR %s fails for address %s: %m",
2942 return INVALID_SOCKET;
2944 #ifdef SO_EXCLUSIVEADDRUSE
2946 * setting SO_EXCLUSIVEADDRUSE on the wildcard we open
2947 * first will cause more specific binds to fail.
2949 if (!(interf->flags & INT_WILDCARD))
2950 set_excladdruse(fd);
2954 * IPv4 specific options go here
2956 if (IS_IPV4(addr)) {
2957 #if defined(IPPROTO_IP) && defined(IP_TOS)
2958 if (setsockopt(fd, IPPROTO_IP, IP_TOS, (char*)&qos,
2961 "setsockopt IP_TOS (%02x) fails on address %s: %m",
2963 #endif /* IPPROTO_IP && IP_TOS */
2965 socket_broadcast_enable(interf, fd, addr);
2969 * IPv6 specific options go here
2971 if (IS_IPV6(addr)) {
2972 #if defined(IPPROTO_IPV6) && defined(IPV6_TCLASS)
2973 if (setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS, (char*)&qos,
2976 "setsockopt IPV6_TCLASS (%02x) fails on address %s: %m",
2978 #endif /* IPPROTO_IPV6 && IPV6_TCLASS */
2980 if (isc_net_probe_ipv6only() == ISC_R_SUCCESS
2981 && setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY,
2982 (char*)&on, sizeof(on)))
2984 "setsockopt IPV6_V6ONLY on fails on address %s: %m",
2987 #ifdef IPV6_BINDV6ONLY
2988 if (setsockopt(fd, IPPROTO_IPV6, IPV6_BINDV6ONLY,
2989 (char*)&on, sizeof(on)))
2991 "setsockopt IPV6_BINDV6ONLY on fails on address %s: %m",
2996 #ifdef OS_NEEDS_REUSEADDR_FOR_IFADDRBIND
2998 * some OSes don't allow binding to more specific
2999 * addresses if a wildcard address already bound
3000 * to the port and SO_REUSEADDR is not set
3002 if (!is_wildcard_addr(addr))
3003 set_wildcard_reuse(AF(addr), 1);
3007 * bind the local address.
3009 errval = bind(fd, &addr->sa, SOCKLEN(addr));
3011 #ifdef OS_NEEDS_REUSEADDR_FOR_IFADDRBIND
3012 if (!is_wildcard_addr(addr))
3013 set_wildcard_reuse(AF(addr), 0);
3018 * Don't log this under all conditions
3020 if (turn_off_reuse == 0
3026 "bind(%d) AF_INET%s %s#%d%s flags 0x%x failed: %m",
3027 fd, IS_IPV6(addr) ? "6" : "",
3028 stoa(addr), SRCPORT(addr),
3029 IS_MCAST(addr) ? " (multicast)" : "",
3035 return INVALID_SOCKET;
3038 #ifdef HAVE_TIMESTAMP
3040 if (setsockopt(fd, SOL_SOCKET, SO_TIMESTAMP,
3041 (char*)&on, sizeof(on)))
3043 "setsockopt SO_TIMESTAMP on fails on address %s: %m",
3046 DPRINTF(4, ("setsockopt SO_TIMESTAMP enabled on fd %d address %s\n",
3050 #ifdef HAVE_TIMESTAMPNS
3052 if (setsockopt(fd, SOL_SOCKET, SO_TIMESTAMPNS,
3053 (char*)&on, sizeof(on)))
3055 "setsockopt SO_TIMESTAMPNS on fails on address %s: %m",
3058 DPRINTF(4, ("setsockopt SO_TIMESTAMPNS enabled on fd %d address %s\n",
3064 if (setsockopt(fd, SOL_SOCKET, SO_BINTIME,
3065 (char*)&on, sizeof(on)))
3067 "setsockopt SO_BINTIME on fails on address %s: %m",
3070 DPRINTF(4, ("setsockopt SO_BINTIME enabled on fd %d address %s\n",
3075 DPRINTF(4, ("bind(%d) AF_INET%s, addr %s%%%d#%d, flags 0x%x\n",
3076 fd, IS_IPV6(addr) ? "6" : "", stoa(addr),
3077 SCOPE(addr), SRCPORT(addr), interf->flags));
3079 make_socket_nonblocking(fd);
3081 #ifdef HAVE_SIGNALED_IO
3082 init_socket_sig(fd);
3083 #endif /* not HAVE_SIGNALED_IO */
3085 add_fd_to_list(fd, FD_TYPE_SOCKET);
3087 #if !defined(SYS_WINNT) && !defined(VMS)
3088 DPRINTF(4, ("flags for fd %d: 0x%x\n", fd,
3089 fcntl(fd, F_GETFL, 0)));
3090 #endif /* SYS_WINNT || VMS */
3092 #if defined (HAVE_IO_COMPLETION_PORT)
3094 * Add the socket to the completion port
3096 if (io_completion_port_add_socket(fd, interf)) {
3097 msyslog(LOG_ERR, "unable to set up io completion port - EXITING");
3106 #define sendto(fd, buf, len, flags, dest, destsz) \
3107 io_completion_port_sendto(fd, buf, len, (sockaddr_u *)(dest))
3110 /* XXX ELIMINATE sendpkt similar in ntpq.c, ntpdc.c, ntp_io.c, ntptrace.c */
3112 * sendpkt - send a packet to the specified destination. Maintain a
3113 * send error cache so that only the first consecutive error for a
3114 * destination is logged.
3119 struct interface * ep,
3131 ismcast = IS_MCAST(dest);
3135 src = (IS_IPV4(dest))
3141 * unbound peer - drop request and wait for better
3142 * network conditions
3144 DPRINTF(2, ("%ssendpkt(dst=%s, ttl=%d, len=%d): no interface - IGNORED\n",
3145 ismcast ? "\tMCAST\t***** " : "",
3146 stoa(dest), ttl, len));
3151 DPRINTF(2, ("%ssendpkt(%d, dst=%s, src=%s, ttl=%d, len=%d)\n",
3152 ismcast ? "\tMCAST\t***** " : "", src->fd,
3153 stoa(dest), stoa(&src->sin), ttl, len));
3156 * for the moment we use the bcast option to set multicast ttl
3158 if (ismcast && ttl > 0 && ttl != src->last_ttl) {
3160 * set the multicast ttl for outgoing packets
3162 switch (AF(&src->sin)) {
3166 rc = setsockopt(src->fd, IPPROTO_IP,
3172 # ifdef INCLUDE_IPV6_SUPPORT
3174 rc = setsockopt(src->fd, IPPROTO_IPV6,
3175 IPV6_MULTICAST_HOPS,
3179 # endif /* INCLUDE_IPV6_SUPPORT */
3186 src->last_ttl = ttl;
3189 "setsockopt IP_MULTICAST_TTL/IPV6_MULTICAST_HOPS fails on address %s: %m",
3195 cc = simulate_server(dest, src, pkt);
3197 cc = sendto(src->fd, (char *)pkt, (u_int)len, 0,
3198 &dest->sa, SOCKLEN(dest));
3209 } while (ismcast && src != NULL);
3213 #if !defined(HAVE_IO_COMPLETION_PORT)
3215 * fdbits - generate ascii representation of fd_set (FAU debug support)
3216 * HFDF format - highest fd first.
3224 static char buffer[256];
3225 char * buf = buffer;
3227 count = min(count, 255);
3229 while (count >= 0) {
3230 *buf++ = FD_ISSET(count, set) ? '#' : '-';
3241 * Routine to read the refclock packets for a specific interface
3242 * Return the number of bytes read. That way we know if we should
3243 * read it again or go on to the next one if no bytes returned
3246 read_refclock_packet(
3248 struct refclockio * rp,
3256 struct recvbuf * rb;
3258 rb = get_free_recv_buffer();
3262 * No buffer space available - just drop the packet
3264 char buf[RX_BUFF_SIZE];
3266 buflen = read(fd, buf, sizeof buf);
3271 i = (rp->datalen == 0
3272 || rp->datalen > (int)sizeof(rb->recv_space))
3273 ? (int)sizeof(rb->recv_space)
3276 buflen = read(fd, (char *)&rb->recv_space, (u_int)i);
3277 } while (buflen < 0 && EINTR == errno);
3280 saved_errno = errno;
3282 errno = saved_errno;
3287 * Got one. Mark how and when it got here,
3288 * put it on the full list and do bookkeeping.
3290 rb->recv_length = buflen;
3291 rb->recv_peer = rp->srcclock;
3295 rb->receiver = rp->clock_recv;
3297 consumed = indicate_refclock_packet(rp, rb);
3305 #endif /* REFCLOCK */
3308 #ifdef HAVE_PACKET_TIMESTAMP
3310 * extract timestamps from control message buffer
3314 struct recvbuf * rb,
3315 struct msghdr * msghdr,
3319 struct cmsghdr * cmsghdr;
3321 struct bintime * btp;
3323 #ifdef HAVE_TIMESTAMPNS
3324 struct timespec * tsp;
3326 #ifdef HAVE_TIMESTAMP
3327 struct timeval * tvp;
3329 unsigned long ticks;
3337 cmsghdr = CMSG_FIRSTHDR(msghdr);
3338 while (cmsghdr != NULL) {
3339 switch (cmsghdr->cmsg_type)
3343 #endif /* HAVE_BINTIME */
3344 #ifdef HAVE_TIMESTAMPNS
3345 case SCM_TIMESTAMPNS:
3346 #endif /* HAVE_TIMESTAMPNS */
3347 #ifdef HAVE_TIMESTAMP
3349 #endif /* HAVE_TIMESTAMP */
3350 #if defined(HAVE_BINTIME) || defined (HAVE_TIMESTAMPNS) || defined(HAVE_TIMESTAMP)
3351 switch (cmsghdr->cmsg_type)
3355 btp = (struct bintime *)CMSG_DATA(cmsghdr);
3357 * bintime documentation is at http://phk.freebsd.dk/pubs/timecounter.pdf
3359 nts.l_i = btp->sec + JAN_1970;
3360 nts.l_uf = (u_int32)(btp->frac >> 32);
3361 if (sys_tick > measured_tick &&
3363 ticks = (unsigned long)(nts.l_uf / (unsigned long)(sys_tick * FRAC));
3364 nts.l_uf = (unsigned long)(ticks * (unsigned long)(sys_tick * FRAC));
3366 DPRINTF(4, ("fetch_timestamp: system bintime network time stamp: %ld.%09lu\n",
3367 btp->sec, (unsigned long)((nts.l_uf / FRAC) * 1e9)));
3369 #endif /* HAVE_BINTIME */
3370 #ifdef HAVE_TIMESTAMPNS
3371 case SCM_TIMESTAMPNS:
3372 tsp = (struct timespec *)CMSG_DATA(cmsghdr);
3373 if (sys_tick > measured_tick &&
3375 ticks = (unsigned long)((tsp->tv_nsec * 1e-9) /
3377 tsp->tv_nsec = (long)(ticks * 1e9 *
3380 DPRINTF(4, ("fetch_timestamp: system nsec network time stamp: %ld.%09ld\n",
3381 tsp->tv_sec, tsp->tv_nsec));
3382 nts = tspec_stamp_to_lfp(*tsp);
3384 #endif /* HAVE_TIMESTAMPNS */
3385 #ifdef HAVE_TIMESTAMP
3387 tvp = (struct timeval *)CMSG_DATA(cmsghdr);
3388 if (sys_tick > measured_tick &&
3390 ticks = (unsigned long)((tvp->tv_usec * 1e-6) /
3392 tvp->tv_usec = (long)(ticks * 1e6 *
3395 DPRINTF(4, ("fetch_timestamp: system usec network time stamp: %jd.%06ld\n",
3396 (intmax_t)tvp->tv_sec, (long)tvp->tv_usec));
3397 nts = tval_stamp_to_lfp(*tvp);
3399 #endif /* HAVE_TIMESTAMP */
3401 fuzz = ntp_random() * 2. / FRAC * sys_fuzz;
3402 DTOLFP(fuzz, &lfpfuzz);
3403 L_ADD(&nts, &lfpfuzz);
3407 collect_timing(rb, "input processing delay", 1,
3409 DPRINTF(4, ("fetch_timestamp: timestamp delta: %s (incl. fuzz)\n",
3411 #endif /* DEBUG_TIMING */
3412 ts = nts; /* network time stamp */
3414 #endif /* HAVE_BINTIME || HAVE_TIMESTAMPNS || HAVE_TIMESTAMP */
3417 DPRINTF(4, ("fetch_timestamp: skipping control message 0x%x\n",
3418 cmsghdr->cmsg_type));
3420 cmsghdr = CMSG_NXTHDR(msghdr, cmsghdr);
3424 #endif /* HAVE_PACKET_TIMESTAMP */
3428 * Routine to read the network NTP packets for a specific interface
3429 * Return the number of bytes read. That way we know if we should
3430 * read it again or go on to the next one if no bytes returned
3433 read_network_packet(
3435 struct interface * itf,
3439 GETSOCKNAME_SOCKLEN_TYPE fromlen;
3441 register struct recvbuf *rb;
3442 #ifdef HAVE_PACKET_TIMESTAMP
3443 struct msghdr msghdr;
3445 char control[CMSG_BUFSIZE];
3449 * Get a buffer and read the frame. If we
3450 * haven't got a buffer, or this is received
3451 * on a disallowed socket, just dump the
3455 rb = get_free_recv_buffer();
3456 if (NULL == rb || itf->ignore_packets) {
3457 char buf[RX_BUFF_SIZE];
3463 fromlen = sizeof(from);
3464 buflen = recvfrom(fd, buf, sizeof(buf), 0,
3465 &from.sa, &fromlen);
3466 DPRINTF(4, ("%s on (%lu) fd=%d from %s\n",
3467 (itf->ignore_packets)
3470 free_recvbuffs(), fd, stoa(&from)));
3471 if (itf->ignore_packets)
3478 fromlen = sizeof(rb->recv_srcadr);
3480 #ifndef HAVE_PACKET_TIMESTAMP
3481 rb->recv_length = recvfrom(fd, (char *)&rb->recv_space,
3482 sizeof(rb->recv_space), 0,
3483 &rb->recv_srcadr.sa, &fromlen);
3485 iovec.iov_base = &rb->recv_space;
3486 iovec.iov_len = sizeof(rb->recv_space);
3487 msghdr.msg_name = &rb->recv_srcadr;
3488 msghdr.msg_namelen = fromlen;
3489 msghdr.msg_iov = &iovec;
3490 msghdr.msg_iovlen = 1;
3491 msghdr.msg_control = (void *)&control;
3492 msghdr.msg_controllen = sizeof(control);
3493 msghdr.msg_flags = 0;
3494 rb->recv_length = recvmsg(fd, &msghdr, 0);
3497 buflen = rb->recv_length;
3499 if (buflen == 0 || (buflen == -1 &&
3500 (EWOULDBLOCK == errno
3507 } else if (buflen < 0) {
3508 msyslog(LOG_ERR, "recvfrom(%s) fd=%d: %m",
3509 stoa(&rb->recv_srcadr), fd);
3510 DPRINTF(5, ("read_network_packet: fd=%d dropped (bad recvfrom)\n",
3516 DPRINTF(3, ("read_network_packet: fd=%d length %d from %s\n",
3517 fd, buflen, stoa(&rb->recv_srcadr)));
3520 ** Bug 2672: Some OSes (MacOSX and Linux) don't block spoofed ::1
3523 if (AF_INET6 == itf->family) {
3524 DPRINTF(2, ("Got an IPv6 packet, from <%s> (%d) to <%s> (%d)\n",
3525 stoa(&rb->recv_srcadr),
3526 IN6_IS_ADDR_LOOPBACK(PSOCK_ADDR6(&rb->recv_srcadr)),
3528 !IN6_IS_ADDR_LOOPBACK(PSOCK_ADDR6(&itf->sin))
3531 if ( IN6_IS_ADDR_LOOPBACK(PSOCK_ADDR6(&rb->recv_srcadr))
3532 && !IN6_IS_ADDR_LOOPBACK(PSOCK_ADDR6(&itf->sin))
3535 DPRINTF(2, ("DROPPING that packet\n"));
3539 DPRINTF(2, ("processing that packet\n"));
3543 * Got one. Mark how and when it got here,
3544 * put it on the full list and do bookkeeping.
3548 #ifdef HAVE_PACKET_TIMESTAMP
3549 /* pick up a network time stamp if possible */
3550 ts = fetch_timestamp(rb, &msghdr, ts);
3553 rb->receiver = receive;
3555 add_full_recv_buffer(rb);
3563 * attempt to handle io (select()/signaled IO)
3568 # ifndef HAVE_SIGNALED_IO
3573 * Use select() on all on all input fd's for unlimited
3574 * time. select() will terminate on SIGALARM or on the
3575 * reception of input. Using select() means we can't do
3576 * robust signal handling and we get a potential race
3577 * between checking for alarms and doing the select().
3578 * Mostly harmless, I think.
3581 * On VMS, I suspect that select() can't be interrupted
3582 * by a "signal" either, so I take the easy way out and
3583 * have select() time out after one second.
3584 * System clock updates really aren't time-critical,
3585 * and - lacking a hardware reference clock - I have
3586 * yet to learn about anything else that is.
3589 # if !defined(VMS) && !defined(SYS_VXWORKS)
3590 nfound = select(maxactivefd + 1, &rdfdes, NULL,
3592 # else /* VMS, VxWorks */
3593 /* make select() wake up after one second */
3599 nfound = select(maxactivefd + 1,
3600 &rdfdes, NULL, NULL,
3603 # endif /* VMS, VxWorks */
3610 } else if (nfound == -1 && errno != EINTR) {
3611 msyslog(LOG_ERR, "select() error: %m");
3614 else if (debug > 4) {
3615 msyslog(LOG_DEBUG, "select(): nfound=%d, error: %m", nfound);
3617 DPRINTF(3, ("select() returned %d: %m\n", nfound));
3620 # else /* HAVE_SIGNALED_IO */
3622 # endif /* HAVE_SIGNALED_IO */
3626 * input_handler - receive packets asynchronously
3639 struct timeval tvzero;
3640 l_fp ts; /* Timestamp at BOselect() gob */
3642 l_fp ts_e; /* Timestamp at EOselect() gob */
3645 size_t select_count;
3648 struct refclockio *rp;
3652 #ifdef HAS_ROUTING_SOCKET
3653 struct asyncio_reader * asyncio_reader;
3654 struct asyncio_reader * next_asyncio_reader;
3661 * If we have something to do, freeze a timestamp.
3662 * See below for the other cases (nothing left to do or error)
3667 * Do a poll to see who has data
3671 tvzero.tv_sec = tvzero.tv_usec = 0;
3673 n = select(maxactivefd + 1, &fds, (fd_set *)0, (fd_set *)0,
3677 * If there are no packets waiting just return
3683 * extended FAU debugging output
3687 "select(%d, %s, 0L, 0L, &0.0) error: %m",
3689 fdbits(maxactivefd, &activefds));
3692 for (j = 0, prior = 0; j <= maxactivefd; j++) {
3693 if (FD_ISSET(j, &activefds)) {
3694 if (-1 != read(j, &b, 0)) {
3699 "Removing bad file descriptor %d from select set",
3701 FD_CLR(j, &activefds);
3702 if (j == maxactivefd)
3703 maxactivefd = prior;
3715 * Check out the reference clocks first, if any
3718 if (refio != NULL) {
3719 for (rp = refio; rp != NULL; rp = rp->next) {
3722 if (!FD_ISSET(fd, &fds))
3725 buflen = read_refclock_packet(fd, rp, ts);
3727 * The first read must succeed after select()
3728 * indicates readability, or we've reached
3729 * a permanent EOF. http://bugs.ntp.org/1732
3730 * reported ntpd munching CPU after a USB GPS
3731 * was unplugged because select was indicating
3732 * EOF but ntpd didn't remove the descriptor
3733 * from the activefds set.
3735 if (buflen < 0 && EAGAIN != errno) {
3736 saved_errno = errno;
3737 clk = refnumtoa(&rp->srcclock->srcadr);
3738 errno = saved_errno;
3739 msyslog(LOG_ERR, "%s read: %m", clk);
3740 maintain_activefds(fd, TRUE);
3741 } else if (0 == buflen) {
3742 clk = refnumtoa(&rp->srcclock->srcadr);
3743 msyslog(LOG_ERR, "%s read EOF", clk);
3744 maintain_activefds(fd, TRUE);
3746 /* drain any remaining refclock input */
3748 buflen = read_refclock_packet(fd, rp, ts);
3749 } while (buflen > 0);
3753 #endif /* REFCLOCK */
3756 * Loop through the interfaces looking for data to read.
3758 for (ep = ep_list; ep != NULL; ep = ep->elink) {
3759 for (doing = 0; doing < 2; doing++) {
3763 if (!(ep->flags & INT_BCASTOPEN))
3769 if (FD_ISSET(fd, &fds))
3772 buflen = read_network_packet(
3774 } while (buflen > 0);
3775 /* Check more interfaces */
3779 #ifdef HAS_ROUTING_SOCKET
3781 * scan list of asyncio readers - currently only used for routing sockets
3783 asyncio_reader = asyncio_reader_list;
3785 while (asyncio_reader != NULL) {
3786 /* callback may unlink and free asyncio_reader */
3787 next_asyncio_reader = asyncio_reader->link;
3788 if (FD_ISSET(asyncio_reader->fd, &fds)) {
3790 (*asyncio_reader->receiver)(asyncio_reader);
3792 asyncio_reader = next_asyncio_reader;
3794 #endif /* HAS_ROUTING_SOCKET */
3797 * Check for a response from a blocking child
3799 for (idx = 0; idx < blocking_children_alloc; idx++) {
3800 c = blocking_children[idx];
3801 if (NULL == c || -1 == c->resp_read_pipe)
3803 if (FD_ISSET(c->resp_read_pipe, &fds)) {
3805 process_blocking_resp(c);
3810 * Done everything from that select.
3811 * If nothing to do, just return.
3812 * If an error occurred, complain and return.
3814 if (select_count == 0) { /* We really had nothing to do */
3817 msyslog(LOG_DEBUG, "input_handler: select() returned 0");
3821 /* We've done our work */
3825 * (ts_e - ts) is the amount of time we spent
3826 * processing this gob of file descriptors. Log
3830 collect_timing(NULL, "input handler", 1, &ts_e);
3833 "input_handler: Processed a gob of fd's in %s msec",
3835 #endif /* DEBUG_TIMING */
3840 #endif /* !HAVE_IO_COMPLETION_PORT */
3844 * find an interface suitable for the src address
3847 select_peerinterface(
3849 sockaddr_u * srcadr,
3857 wild = ANY_INTERFACE_CHOOSE(srcadr);
3860 * Initialize the peer structure and dance the interface jig.
3861 * Reference clocks step the loopback waltz, the others
3862 * squaredance around the interface list looking for a buddy. If
3863 * the dance peters out, there is always the wildcard interface.
3864 * This might happen in some systems and would preclude proper
3865 * operation with public key cryptography.
3867 if (ISREFCLOCKADR(srcadr)) {
3868 ep = loopback_interface;
3869 } else if (peer->cast_flags &
3870 (MDF_BCLNT | MDF_ACAST | MDF_MCAST | MDF_BCAST)) {
3871 ep = findbcastinter(srcadr);
3873 DPRINTF(4, ("Found *-cast interface %s for address %s\n",
3874 stoa(&ep->sin), stoa(srcadr)));
3876 DPRINTF(4, ("No *-cast local address found for address %s\n",
3884 * If it is a multicast address, findbcastinter() may not find
3885 * it. For unicast, we get to find the interface when dstadr is
3886 * given to us as the wildcard (ANY_INTERFACE_CHOOSE). Either
3887 * way, try a little harder.
3890 ep = findinterface(srcadr);
3892 * we do not bind to the wildcard interfaces for output
3893 * as our (network) source address would be undefined and
3894 * crypto will not work without knowing the own transmit address
3896 if (ep != NULL && INT_WILDCARD & ep->flags)
3897 if (!accept_wildcard_if_for_winnt)
3899 #else /* SIM follows */
3900 ep = loopback_interface;
3908 * findinterface - find local interface corresponding to address
3917 iface = findlocalinterface(addr, INT_WILDCARD, 0);
3919 if (NULL == iface) {
3920 DPRINTF(4, ("Found no interface for address %s - returning wildcard\n",
3923 iface = ANY_INTERFACE_CHOOSE(addr);
3925 DPRINTF(4, ("Found interface #%d %s for address %s\n",
3926 iface->ifnum, iface->name, stoa(addr)));
3932 * findlocalinterface - find local interface corresponding to addr,
3933 * which does not have any of flags set. If bast is nonzero, addr is
3934 * a broadcast address.
3936 * This code attempts to find the local sending address for an outgoing
3937 * address by connecting a new socket to destinationaddress:NTP_PORT
3938 * and reading the sockname of the resulting connect.
3939 * the complicated sequence simulates the routing table lookup
3940 * for to first hop without duplicating any of the routing logic into
3941 * ntpd. preferably we would have used an API call - but its not there -
3942 * so this is the best we can do here short of duplicating to entire routing
3943 * logic in ntpd which would be a silly and really unportable thing to do.
3953 GETSOCKNAME_SOCKLEN_TYPE sockaddrlen;
3960 DPRINTF(4, ("Finding interface for addr %s in list of addresses\n",
3963 s = socket(AF(addr), SOCK_DGRAM, 0);
3964 if (INVALID_SOCKET == s)
3968 * If we are looking for broadcast interface we need to set this
3969 * socket to allow broadcast
3973 if (SOCKET_ERROR == setsockopt(s, SOL_SOCKET,
3982 rtn = connect(s, &addr->sa, SOCKLEN(addr));
3983 if (SOCKET_ERROR == rtn) {
3988 sockaddrlen = sizeof(saddr);
3989 rtn = getsockname(s, &saddr.sa, &sockaddrlen);
3991 if (SOCKET_ERROR == rtn)
3994 DPRINTF(4, ("findlocalinterface: kernel maps %s to %s\n",
3995 stoa(addr), stoa(&saddr)));
3997 iface = getinterface(&saddr, flags);
4000 * if we didn't find an exact match on saddr, find the closest
4001 * available local address. This handles the case of the
4002 * address suggested by the kernel being excluded by nic rules
4003 * or the user's -I and -L options to ntpd.
4004 * See http://bugs.ntp.org/1184 and http://bugs.ntp.org/1683
4005 * for more background.
4007 if (NULL == iface || iface->ignore_packets)
4008 iface = findclosestinterface(&saddr,
4009 flags | INT_LOOPBACK);
4011 /* Don't use an interface which will ignore replies */
4012 if (iface != NULL && iface->ignore_packets)
4020 * findclosestinterface
4022 * If there are -I/--interface or -L/novirtualips command-line options,
4023 * or "nic" or "interface" rules in ntp.conf, findlocalinterface() may
4024 * find the kernel's preferred local address for a given peer address is
4025 * administratively unavailable to ntpd, and punt to this routine's more
4028 * Find the numerically closest local address to the one connect()
4029 * suggested. This matches an address on the same subnet first, as
4030 * needed by Bug 1184, and provides a consistent choice if there are
4031 * multiple feasible local addresses, regardless of the order ntpd
4035 findclosestinterface(
4042 sockaddr_u addr_dist;
4043 sockaddr_u min_dist;
4045 ZERO_SOCK(&min_dist);
4048 for (ep = ep_list; ep != NULL; ep = ep->elink) {
4049 if (ep->ignore_packets ||
4050 AF(addr) != ep->family ||
4054 calc_addr_distance(&addr_dist, addr, &ep->sin);
4055 if (NULL == winner ||
4056 -1 == cmp_addr_distance(&addr_dist, &min_dist)) {
4057 min_dist = addr_dist;
4062 DPRINTF(4, ("findclosestinterface(%s) failed\n",
4065 DPRINTF(4, ("findclosestinterface(%s) -> %s\n",
4066 stoa(addr), stoa(&winner->sin)));
4073 * calc_addr_distance - calculate the distance between two addresses,
4074 * the absolute value of the difference between
4075 * the addresses numerically, stored as an address.
4080 const sockaddr_u * a1,
4081 const sockaddr_u * a2
4091 NTP_REQUIRE(AF(a1) == AF(a2));
4096 /* v4 can be done a bit simpler */
4100 v4dist = (a1val > a2val)
4103 SET_ADDR4(dist, v4dist);
4108 found_greater = FALSE;
4109 a1_greater = FALSE; /* suppress pot. uninit. warning */
4110 for (i = 0; i < (int)sizeof(NSRCADR6(a1)); i++) {
4111 if (!found_greater &&
4112 NSRCADR6(a1)[i] != NSRCADR6(a2)[i]) {
4113 found_greater = TRUE;
4114 a1_greater = (NSRCADR6(a1)[i] > NSRCADR6(a2)[i]);
4116 if (!found_greater) {
4117 NSRCADR6(dist)[i] = 0;
4120 NSRCADR6(dist)[i] = NSRCADR6(a1)[i] -
4123 NSRCADR6(dist)[i] = NSRCADR6(a2)[i] -
4131 * cmp_addr_distance - compare two address distances, returning -1, 0,
4132 * 1 to indicate their relationship.
4136 const sockaddr_u * d1,
4137 const sockaddr_u * d2
4142 NTP_REQUIRE(AF(d1) == AF(d2));
4145 if (SRCADR(d1) < SRCADR(d2))
4147 else if (SRCADR(d1) == SRCADR(d2))
4153 for (i = 0; i < (int)sizeof(NSRCADR6(d1)); i++) {
4154 if (NSRCADR6(d1)[i] < NSRCADR6(d2)[i])
4156 else if (NSRCADR6(d1)[i] > NSRCADR6(d2)[i])
4166 * fetch an interface structure the matches the
4167 * address and has the given flags NOT set
4177 iface = find_addr_in_list(addr);
4179 if (iface != NULL && (iface->flags & flags))
4187 * findbcastinter - find broadcast interface corresponding to address
4197 #if !defined(MPE) && (defined(SIOCGIFCONF) || defined(SYS_WINNT))
4198 DPRINTF(4, ("Finding broadcast/multicast interface for addr %s in list of addresses\n",
4201 iface = findlocalinterface(addr, INT_LOOPBACK | INT_WILDCARD,
4203 if (iface != NULL) {
4204 DPRINTF(4, ("Easily found bcast-/mcast- interface index #%d %s\n",
4205 iface->ifnum, iface->name));
4210 * plan B - try to find something reasonable in our lists in
4211 * case kernel lookup doesn't help
4213 for (iface = ep_list; iface != NULL; iface = iface->elink) {
4214 if (iface->flags & INT_WILDCARD)
4217 /* Don't bother with ignored interfaces */
4218 if (iface->ignore_packets)
4222 * First look if this is the correct family
4224 if(AF(&iface->sin) != AF(addr))
4227 /* Skip the loopback addresses */
4228 if (iface->flags & INT_LOOPBACK)
4232 * If we are looking to match a multicast address and
4233 * this interface is one...
4235 if (addr_ismulticast(addr)
4236 && (iface->flags & INT_MULTICAST)) {
4237 #ifdef INCLUDE_IPV6_SUPPORT
4239 * ...it is the winner unless we're looking for
4240 * an interface to use for link-local multicast
4241 * and its address is not link-local.
4244 && IN6_IS_ADDR_MC_LINKLOCAL(PSOCK_ADDR6(addr))
4245 && !IN6_IS_ADDR_LINKLOCAL(PSOCK_ADDR6(&iface->sin)))
4252 * We match only those interfaces marked as
4253 * broadcastable and either the explicit broadcast
4254 * address or the network portion of the IP address.
4257 if (IS_IPV4(addr)) {
4258 if (SOCK_EQ(&iface->bcast, addr))
4261 if ((NSRCADR(&iface->sin) & NSRCADR(&iface->mask))
4262 == (NSRCADR(addr) & NSRCADR(&iface->mask)))
4265 #ifdef INCLUDE_IPV6_SUPPORT
4266 else if (IS_IPV6(addr)) {
4267 if (SOCK_EQ(&iface->bcast, addr))
4270 if (SOCK_EQ(netof(&iface->sin), netof(addr)))
4275 #endif /* SIOCGIFCONF */
4276 if (NULL == iface) {
4277 DPRINTF(4, ("No bcast interface found for %s\n",
4279 iface = ANY_INTERFACE_CHOOSE(addr);
4281 DPRINTF(4, ("Found bcast-/mcast- interface index #%d %s\n",
4282 iface->ifnum, iface->name));
4290 * io_clr_stats - clear I/O module statistics
4295 packets_dropped = 0;
4296 packets_ignored = 0;
4297 packets_received = 0;
4299 packets_notsent = 0;
4303 io_timereset = current_time;
4309 * io_addclock - add a reference clock to the list and arrange that we
4310 * get SIGIO interrupts from it.
4314 struct refclockio *rio
4320 * Stuff the I/O structure in the list and mark the descriptor
4321 * in use. There is a harmless (I hope) race condition here.
4325 # ifdef HAVE_SIGNALED_IO
4326 if (init_clock_sig(rio)) {
4330 # elif defined(HAVE_IO_COMPLETION_PORT)
4331 if (io_completion_port_add_clock_io(rio)) {
4340 LINK_SLIST(refio, rio, next);
4345 add_fd_to_list(rio->fd, FD_TYPE_FILE);
4353 * io_closeclock - close the clock in the I/O structure given
4357 struct refclockio *rio
4360 struct refclockio *unlinked;
4365 * Remove structure from the list
4367 rio->active = FALSE;
4368 UNLINK_SLIST(unlinked, refio, rio, next, struct refclockio);
4369 if (NULL != unlinked) {
4370 purge_recv_buffers_for_fd(rio->fd);
4372 * Close the descriptor.
4374 close_and_delete_fd_from_list(rio->fd);
4380 #endif /* REFCLOCK */
4384 * On NT a SOCKET is an unsigned int so we cannot possibly keep it in
4385 * an array. So we use one of the ISC_LIST functions to hold the
4386 * socket value and use that when we want to enumerate it.
4388 * This routine is called by the forked intres child process to close
4389 * all open sockets. On Windows there's no need as intres runs in
4390 * the same process as a thread.
4401 * In the child process we do not maintain activefds and
4402 * maxactivefd. Zeroing maxactivefd disables code which
4403 * maintains it in close_and_delete_fd_from_list().
4407 while (fd_list != NULL)
4408 close_and_delete_fd_from_list(fd_list->fd);
4412 #endif /* !SYS_WINNT */
4416 * Add and delete functions for the list of open sockets
4424 vsock_t *lsock = emalloc(sizeof(*lsock));
4429 LINK_SLIST(fd_list, lsock, link);
4430 maintain_activefds(fd, 0);
4435 close_and_delete_fd_from_list(
4441 UNLINK_EXPR_SLIST(lsock, fd_list, fd ==
4442 UNLINK_EXPR_SLIST_CURRENT()->fd, link, vsock_t);
4447 switch (lsock->type) {
4449 case FD_TYPE_SOCKET:
4450 closesocket(lsock->fd);
4454 closeserial(lsock->fd);
4459 "internal error - illegal descriptor type %d - EXITING",
4466 * remove from activefds
4468 maintain_activefds(fd, 1);
4481 if (find_addr_in_list(addr) == NULL) {
4483 /* not there yet - add to list */
4484 laddr = emalloc(sizeof(*laddr));
4485 laddr->addr = *addr;
4488 LINK_SLIST(remoteaddr_list, laddr, link);
4490 DPRINTF(4, ("Added addr %s to list of addresses\n",
4494 DPRINTF(4, ("WARNING: Attempt to add duplicate addr %s to address list\n",
4501 delete_addr_from_list(
4505 remaddr_t *unlinked;
4507 UNLINK_EXPR_SLIST(unlinked, remoteaddr_list, SOCK_EQ(addr,
4508 &(UNLINK_EXPR_SLIST_CURRENT()->addr)), link, remaddr_t);
4510 if (unlinked != NULL) {
4511 DPRINTF(4, ("Deleted addr %s from list of addresses\n",
4519 delete_interface_from_list(
4523 remaddr_t *unlinked;
4526 UNLINK_EXPR_SLIST(unlinked, remoteaddr_list, iface ==
4527 UNLINK_EXPR_SLIST_CURRENT()->ep, link,
4530 if (unlinked == NULL)
4532 DPRINTF(4, ("Deleted addr %s for interface #%d %s from list of addresses\n",
4533 stoa(&unlinked->addr), iface->ifnum,
4540 static struct interface *
4547 DPRINTF(4, ("Searching for addr %s in list of addresses - ",
4550 for (entry = remoteaddr_list;
4552 entry = entry->link)
4553 if (SOCK_EQ(&entry->addr, addr)) {
4554 DPRINTF(4, ("FOUND\n"));
4558 DPRINTF(4, ("NOT FOUND\n"));
4564 * Find the given address with the all given flags set in the list
4567 find_flagged_addr_in_list(
4574 DPRINTF(4, ("Finding addr %s with flags %d in list: ",
4575 stoa(addr), flags));
4577 for (entry = remoteaddr_list;
4579 entry = entry->link)
4581 if (SOCK_EQ(&entry->addr, addr)
4582 && (entry->ep->flags & flags) == flags) {
4584 DPRINTF(4, ("FOUND\n"));
4588 DPRINTF(4, ("NOT FOUND\n"));
4604 #ifdef HAS_ROUTING_SOCKET
4605 # ifndef UPDATE_GRACE
4606 # define UPDATE_GRACE 2 /* wait UPDATE_GRACE seconds before scanning */
4610 process_routing_msgs(struct asyncio_reader *reader)
4614 #ifdef HAVE_RTNETLINK
4615 struct nlmsghdr *nh;
4617 struct rt_msghdr rtm;
4621 if (disable_dynamic_updates) {
4623 * discard ourselves if we are not needed any more
4624 * usually happens when running unprivileged
4626 remove_asyncio_reader(reader);
4627 delete_asyncio_reader(reader);
4631 cnt = read(reader->fd, buffer, sizeof(buffer));
4635 "i/o error on routing socket %m - disabling");
4636 remove_asyncio_reader(reader);
4637 delete_asyncio_reader(reader);
4642 * process routing message
4644 #ifdef HAVE_RTNETLINK
4645 for (nh = (struct nlmsghdr *)buffer;
4647 nh = NLMSG_NEXT(nh, cnt)) {
4648 msg_type = nh->nlmsg_type;
4651 (p + sizeof(struct rt_msghdr)) <= (buffer + cnt);
4652 p += rtm.rtm_msglen) {
4653 memcpy(&rtm, p, sizeof(rtm));
4654 if (rtm.rtm_version != RTM_VERSION) {
4656 "version mismatch (got %d - expected %d) on routing socket - disabling",
4657 rtm.rtm_version, RTM_VERSION);
4659 remove_asyncio_reader(reader);
4660 delete_asyncio_reader(reader);
4663 msg_type = rtm.rtm_type;
4690 #ifdef RTM_IFANNOUNCE
4691 case RTM_IFANNOUNCE:
4706 * we are keen on new and deleted addresses and
4707 * if an interface goes up and down or routing
4710 DPRINTF(3, ("routing message op = %d: scheduling interface update\n",
4712 timer_interfacetimeout(current_time + UPDATE_GRACE);
4714 #ifdef HAVE_RTNETLINK
4716 /* end of multipart message */
4721 * the rest doesn't bother us.
4723 DPRINTF(4, ("routing message op = %d: ignored\n",
4731 * set up routing notifications
4734 init_async_notifications()
4736 struct asyncio_reader *reader;
4737 #ifdef HAVE_RTNETLINK
4738 int fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
4739 struct sockaddr_nl sa;
4741 int fd = socket(PF_ROUTE, SOCK_RAW, 0);
4745 "unable to open routing socket (%m) - using polled interface update");
4750 #ifdef HAVE_RTNETLINK
4752 sa.nl_family = PF_NETLINK;
4753 sa.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR
4754 | RTMGRP_IPV6_IFADDR | RTMGRP_IPV4_ROUTE
4755 | RTMGRP_IPV4_MROUTE | RTMGRP_IPV6_ROUTE
4756 | RTMGRP_IPV6_MROUTE;
4757 if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
4759 "bind failed on routing socket (%m) - using polled interface update");
4763 make_socket_nonblocking(fd);
4764 #if defined(HAVE_SIGNALED_IO)
4765 init_socket_sig(fd);
4766 #endif /* HAVE_SIGNALED_IO */
4768 reader = new_asyncio_reader();
4771 reader->receiver = process_routing_msgs;
4773 add_asyncio_reader(reader, FD_TYPE_SOCKET);
4775 "Listening on routing socket on fd #%d for interface updates",
4779 /* HAS_ROUTING_SOCKET not defined */
4781 init_async_notifications(void)