Patrick Welche <prlw1@cam.ac.uk>
[netbsd-mini2440.git] / external / bsd / ntp / dist / ntpd / ntp_io.c
blob63986a76a9f83c692b3dd331a05d4d8fdbd0b146
1 /* $NetBSD: ntp_io.c,v 1.1.1.1 2009/12/13 16:56:13 kardel Exp $ */
3 /*
4 * ntp_io.c - input/output routines for ntpd. The socket-opening code
5 * was shamelessly stolen from ntpd.
6 */
8 #ifdef HAVE_CONFIG_H
9 # include <config.h>
10 #endif
12 #include <stdio.h>
13 #include <signal.h>
14 #ifdef HAVE_SYS_PARAM_H
15 # include <sys/param.h>
16 #endif
17 #ifdef HAVE_SYS_IOCTL_H
18 # include <sys/ioctl.h>
19 #endif
20 #ifdef HAVE_SYS_SOCKIO_H /* UXPV: SIOC* #defines (Frank Vance <fvance@waii.com>) */
21 # include <sys/sockio.h>
22 #endif
23 #ifdef HAVE_SYS_UIO_H
24 # include <sys/uio.h>
25 #endif
27 #include "ntp_machine.h"
28 #include "ntpd.h"
29 #include "ntp_io.h"
30 #include "iosignal.h"
31 #include "ntp_lists.h"
32 #include "ntp_refclock.h"
33 #include "ntp_stdlib.h"
34 #include "ntp_request.h"
35 #include "ntp.h"
36 #include "ntp_unixtime.h"
37 #include "ntp_assert.h"
38 #include "ntpd-opts.h"
40 /* Don't include ISC's version of IPv6 variables and structures */
41 #define ISC_IPV6_H 1
42 #include <isc/mem.h>
43 #include <isc/interfaceiter.h>
44 #include <isc/netaddr.h>
45 #include <isc/result.h>
46 #include <isc/sockaddr.h>
48 #ifdef SIM
49 #include "ntpsim.h"
50 #endif
52 #ifdef HAS_ROUTING_SOCKET
53 # include <net/route.h>
54 # ifdef HAVE_RTNETLINK
55 # include <linux/rtnetlink.h>
56 # endif
57 #endif
61 * setsockopt does not always have the same arg declaration
62 * across all platforms. If it's not defined we make it empty
65 #ifndef SETSOCKOPT_ARG_CAST
66 #define SETSOCKOPT_ARG_CAST
67 #endif
69 extern int listen_to_virtual_ips;
72 * NIC rule entry
74 typedef struct nic_rule_tag nic_rule;
76 struct nic_rule_tag {
77 nic_rule * next;
78 nic_rule_action action;
79 nic_rule_match match_type;
80 char * if_name;
81 isc_netaddr_t netaddr;
82 int prefixlen;
86 * NIC rule listhead. Entries are added at the head so that the first
87 * match in the list is the last matching rule specified.
89 nic_rule *nic_rule_list;
92 #if defined(SO_TIMESTAMP) && defined(SCM_TIMESTAMP)
93 #if defined(CMSG_FIRSTHDR)
94 #define HAVE_TIMESTAMP
95 #define USE_TIMESTAMP_CMSG
96 #ifndef TIMESTAMP_CTLMSGBUF_SIZE
97 #define TIMESTAMP_CTLMSGBUF_SIZE 1536 /* moderate default */
98 #endif
99 #else
100 /* fill in for old/other timestamp interfaces */
101 #endif
102 #endif
104 #if defined(SYS_WINNT)
105 #include <transmitbuff.h>
106 #include <isc/win32os.h>
108 * Windows C runtime ioctl() can't deal properly with sockets,
109 * map to ioctlsocket for this source file.
111 #define ioctl(fd, opt, val) ioctlsocket((fd), (opt), (u_long *)(val))
112 #endif /* SYS_WINNT */
115 * We do asynchronous input using the SIGIO facility. A number of
116 * recvbuf buffers are preallocated for input. In the signal
117 * handler we poll to see which sockets are ready and read the
118 * packets from them into the recvbuf's along with a time stamp and
119 * an indication of the source host and the interface it was received
120 * through. This allows us to get as accurate receive time stamps
121 * as possible independent of other processing going on.
123 * We watch the number of recvbufs available to the signal handler
124 * and allocate more when this number drops below the low water
125 * mark. If the signal handler should run out of buffers in the
126 * interim it will drop incoming frames, the idea being that it is
127 * better to drop a packet than to be inaccurate.
132 * Other statistics of possible interest
134 volatile u_long packets_dropped; /* total number of packets dropped on reception */
135 volatile u_long packets_ignored; /* packets received on wild card interface */
136 volatile u_long packets_received; /* total number of packets received */
137 u_long packets_sent; /* total number of packets sent */
138 u_long packets_notsent; /* total number of packets which couldn't be sent */
140 volatile u_long handler_calls; /* number of calls to interrupt handler */
141 volatile u_long handler_pkts; /* number of pkts received by handler */
142 u_long io_timereset; /* time counters were reset */
145 * Interface stuff
147 struct interface *any_interface; /* default ipv4 interface */
148 struct interface *any6_interface; /* default ipv6 interface */
149 struct interface *loopback_interface; /* loopback ipv4 interface */
151 isc_boolean_t broadcast_client_enabled; /* is broadcast client enabled */
152 int ninterfaces; /* Total number of interfaces */
154 int disable_dynamic_updates; /* scan interfaces once only */
156 #ifdef REFCLOCK
158 * Refclock stuff. We keep a chain of structures with data concerning
159 * the guys we are doing I/O for.
161 static struct refclockio *refio;
162 #endif /* REFCLOCK */
164 #if defined(HAVE_IPTOS_SUPPORT)
165 /* set IP_TOS to minimize packet delay */
166 # if defined(IPTOS_PREC_INTERNETCONTROL)
167 unsigned int qos = IPTOS_PREC_INTERNETCONTROL;
168 # else
169 unsigned int qos = IPTOS_LOWDELAY;
170 # endif
171 #endif
174 * File descriptor masks etc. for call to select
175 * Not needed for I/O Completion Ports
177 fd_set activefds;
178 int maxactivefd;
180 * bit alternating value to detect verified interfaces during an update cycle
182 static u_short sys_interphase = 0;
184 static struct interface *new_interface (struct interface *);
185 static void add_interface (struct interface *);
186 static int update_interfaces(u_short, interface_receiver_t, void *);
187 static void remove_interface(struct interface *);
188 static struct interface *create_interface(u_short, struct interface *);
190 static int move_fd (SOCKET);
191 static int is_wildcard_addr (sockaddr_u *);
192 static int is_wildcard_netaddr (const isc_netaddr_t *);
195 * Multicast functions
197 static isc_boolean_t addr_ismulticast (sockaddr_u *);
199 * Not all platforms support multicast
201 #ifdef MCAST
202 static isc_boolean_t socket_multicast_enable (struct interface *, int, sockaddr_u *);
203 static isc_boolean_t socket_multicast_disable(struct interface *, sockaddr_u *);
204 #endif
206 #ifdef DEBUG
207 static void interface_dump (struct interface *);
208 static void sockaddr_dump (sockaddr_u *psau);
209 static void print_interface (struct interface *, char *, char *);
210 #define DPRINT_INTERFACE(level, args) do { if (debug >= (level)) { print_interface args; } } while (0)
211 #else
212 #define DPRINT_INTERFACE(level, args) do {} while (0)
213 #endif
215 typedef struct vsock vsock_t;
216 enum desc_type { FD_TYPE_SOCKET, FD_TYPE_FILE };
218 struct vsock {
219 vsock_t * link;
220 SOCKET fd;
221 enum desc_type type;
224 vsock_t *fd_list;
226 #if !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET)
228 * async notification processing (e. g. routing sockets)
231 * support for receiving data on fd that is not a refclock or a socket
232 * like e. g. routing sockets
234 struct asyncio_reader {
235 struct asyncio_reader *link; /* the list this is being kept in */
236 SOCKET fd; /* fd to be read */
237 void *data; /* possibly local data */
238 void (*receiver)(struct asyncio_reader *); /* input handler */
241 struct asyncio_reader *asyncio_reader_list;
243 static void delete_asyncio_reader (struct asyncio_reader *);
244 static struct asyncio_reader *new_asyncio_reader (void);
245 static void add_asyncio_reader (struct asyncio_reader *, enum desc_type);
246 static void remove_asyncio_reader (struct asyncio_reader *);
248 #endif /* !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET) */
250 static void init_async_notifications (void);
252 static int create_sockets (u_short);
253 static SOCKET open_socket (sockaddr_u *, int, int, struct interface *);
254 static char * fdbits (int, fd_set *);
255 static void set_reuseaddr (int);
256 static isc_boolean_t socket_broadcast_enable (struct interface *, SOCKET, sockaddr_u *);
257 static isc_boolean_t socket_broadcast_disable (struct interface *, sockaddr_u *);
259 typedef struct remaddr remaddr_t;
261 struct remaddr {
262 remaddr_t * link;
263 sockaddr_u addr;
264 struct interface * interface;
267 remaddr_t * remoteaddr_list;
269 struct interface * inter_list;
271 static struct interface *wildipv4 = NULL;
272 static struct interface *wildipv6 = NULL;
274 static void add_fd_to_list (SOCKET,
275 enum desc_type);
276 static struct interface *find_addr_in_list (sockaddr_u *);
277 static struct interface *find_samenet_addr_in_list(sockaddr_u *);
278 static struct interface *find_flagged_addr_in_list(sockaddr_u *, int);
279 static void delete_addr_from_list (sockaddr_u *);
280 static void delete_interface_from_list(struct interface *);
281 static void close_and_delete_fd_from_list(SOCKET);
282 static void add_addr_to_list (sockaddr_u *,
283 struct interface *);
284 static void create_wildcards (u_short);
285 #ifdef DEBUG
286 static const char * action_text (nic_rule_action);
287 #endif
288 static nic_rule_action interface_action(char *, isc_netaddr_t *,
289 isc_uint32_t);
290 static void convert_isc_if (isc_interface_t *,
291 struct interface *, u_short);
292 static struct interface *getinterface (sockaddr_u *, int);
293 static struct interface *getsamenetinterface (sockaddr_u *, int);
294 static struct interface *findlocalinterface (sockaddr_u *, int, int);
295 static struct interface *findlocalcastinterface (sockaddr_u *);
298 * Routines to read the ntp packets
300 #if !defined(HAVE_IO_COMPLETION_PORT)
301 static inline int read_network_packet (SOCKET, struct interface *, l_fp);
302 static inline int read_refclock_packet (SOCKET, struct refclockio *, l_fp);
303 #endif
306 #ifdef SYS_WINNT
308 * Windows 2000 systems incorrectly cause UDP sockets using WASRecvFrom
309 * to not work correctly, returning a WSACONNRESET error when a WSASendTo
310 * fails with an "ICMP port unreachable" response and preventing the
311 * socket from using the WSARecvFrom in subsequent operations.
312 * The function below fixes this, but requires that Windows 2000
313 * Service Pack 2 or later be installed on the system. NT 4.0
314 * systems are not affected by this and work correctly.
315 * See Microsoft Knowledge Base Article Q263823 for details of this.
317 void
318 connection_reset_fix(
319 SOCKET fd,
320 sockaddr_u * addr
323 DWORD dw;
324 BOOL bNewBehavior = FALSE;
325 DWORD status;
328 * disable bad behavior using IOCTL: SIO_UDP_CONNRESET
329 * NT 4.0 has no problem
331 if (isc_win32os_majorversion() >= 5) {
332 status = WSAIoctl(fd, SIO_UDP_CONNRESET, &bNewBehavior,
333 sizeof(bNewBehavior), NULL, 0,
334 &dw, NULL, NULL);
335 if (SOCKET_ERROR == status)
336 msyslog(LOG_ERR,
337 "connection_reset_fix() failed for address %s: %m",
338 stoa(addr));
341 #endif
344 * on Unix systems the stdio library typically
345 * makes use of file descriptors in the lower
346 * integer range. stdio usually will make use
347 * of the file descriptors in the range of
348 * [0..FOPEN_MAX)
349 * in order to keep this range clean, for socket
350 * file descriptors we attempt to move them above
351 * FOPEN_MAX. This is not as easy as it sounds as
352 * FOPEN_MAX changes from implementation to implementation
353 * and may exceed to current file decriptor limits.
354 * We are using following strategy:
355 * - keep a current socket fd boundary initialized with
356 * max(0, min(getdtablesize() - FD_CHUNK, FOPEN_MAX))
357 * - attempt to move the descriptor to the boundary or
358 * above.
359 * - if that fails and boundary > 0 set boundary
360 * to min(0, socket_fd_boundary - FD_CHUNK)
361 * -> retry
362 * if failure and boundary == 0 return old fd
363 * - on success close old fd return new fd
365 * effects:
366 * - fds will be moved above the socket fd boundary
367 * if at all possible.
368 * - the socket boundary will be reduced until
369 * allocation is possible or 0 is reached - at this
370 * point the algrithm will be disabled
372 static int
373 move_fd(
374 SOCKET fd
377 #if !defined(SYS_WINNT) && defined(F_DUPFD)
378 #ifndef FD_CHUNK
379 #define FD_CHUNK 10
380 #endif
382 * number of fds we would like to have for
383 * stdio FILE* available.
384 * we can pick a "low" number as our use of
385 * FILE* is limited to log files and temporarily
386 * to data and config files. Except for log files
387 * we don't keep the other FILE* open beyond the
388 * scope of the function that opened it.
390 #ifndef FD_PREFERRED_SOCKBOUNDARY
391 #define FD_PREFERRED_SOCKBOUNDARY 48
392 #endif
394 #ifndef HAVE_GETDTABLESIZE
396 * if we have no idea about the max fd value set up things
397 * so we will start at FOPEN_MAX
399 #define getdtablesize() (FOPEN_MAX+FD_CHUNK)
400 #endif
402 #ifndef FOPEN_MAX
403 #define FOPEN_MAX 20 /* assume that for the lack of anything better */
404 #endif
405 static SOCKET socket_boundary = -1;
406 SOCKET newfd;
408 NTP_REQUIRE((int)fd >= 0);
411 * check whether boundary has be set up
412 * already
414 if (socket_boundary == -1) {
415 socket_boundary = max(0, min(getdtablesize() - FD_CHUNK,
416 min(FOPEN_MAX, FD_PREFERRED_SOCKBOUNDARY)));
417 #ifdef DEBUG
418 msyslog(LOG_DEBUG,
419 "ntp_io: estimated max descriptors: %d, initial socket boundary: %d",
420 getdtablesize(), socket_boundary);
421 #endif
425 * Leave a space for stdio to work in. potentially moving the
426 * socket_boundary lower until allocation succeeds.
428 do {
429 if (fd >= 0 && fd < socket_boundary) {
430 /* inside reserved range: attempt to move fd */
431 newfd = fcntl(fd, F_DUPFD, socket_boundary);
433 if (newfd != -1) {
434 /* success: drop the old one - return the new one */
435 close(fd);
436 return newfd;
438 } else {
439 /* outside reserved range: no work - return the original one */
440 return fd;
442 socket_boundary = max(0, socket_boundary - FD_CHUNK);
443 #ifdef DEBUG
444 msyslog(LOG_DEBUG,
445 "ntp_io: selecting new socket boundary: %d",
446 socket_boundary);
447 #endif
448 } while (socket_boundary > 0);
449 #else
450 NTP_REQUIRE((int)fd >= 0);
451 #endif /* !defined(SYS_WINNT) && defined(F_DUPFD) */
452 return fd;
455 #ifdef DEBUG_TIMING
457 * collect timing information for various processing
458 * paths. currently we only pass then on to the file
459 * for later processing. this could also do histogram
460 * based analysis in other to reduce the load (and skew)
461 * dur to the file output
463 void
464 collect_timing(struct recvbuf *rb, const char *tag, int count, l_fp *dts)
466 char buf[256];
468 snprintf(buf, sizeof(buf), "%s %d %s %s",
469 (rb != NULL)
470 ? ((rb->dstadr != NULL)
471 ? stoa(&rb->recv_srcadr)
472 : "-REFCLOCK-")
473 : "-",
474 count, lfptoa(dts, 9), tag);
475 record_timing_stats(buf);
477 #endif
480 * About dynamic interfaces, sockets, reception and more...
482 * the code solves following tasks:
484 * - keep a current list of active interfaces in order
485 * to bind to to the interface address on NTP_PORT so that
486 * all wild and specific bindings for NTP_PORT are taken by ntpd
487 * to avoid other daemons messing with the time or sockets.
488 * - all interfaces keep a list of peers that are referencing
489 * the interface in order to quickly re-assign the peers to
490 * new interface in case an interface is deleted (=> gone from system or
491 * down)
492 * - have a preconfigured socket ready with the right local address
493 * for transmission and reception
494 * - have an address list for all destination addresses used within ntpd
495 * to find the "right" preconfigured socket.
496 * - facilitate updating the internal interface list with respect to
497 * the current kernel state
499 * special issues:
501 * - mapping of multicast addresses to the interface affected is not always
502 * one to one - especially on hosts with multiple interfaces
503 * the code here currently allocates a separate interface entry for those
504 * multicast addresses
505 * iff it is able to bind to a *new* socket with the multicast address (flags |= MCASTIF)
506 * in case of failure the multicast address is bound to an existing interface.
507 * - on some systems it is perfectly legal to assign the same address to
508 * multiple interfaces. Therefore this code does not keep a list of interfaces
509 * but a list of interfaces that represent a unique address as determined by the kernel
510 * by the procedure in findlocalinterface. Thus it is perfectly legal to see only
511 * one representative of a group of real interfaces if they share the same address.
513 * Frank Kardel 20050910
517 * init_io - initialize I/O data structures and call socket creation routine
519 void
520 init_io(void)
523 * Init buffer free list and stat counters
525 init_recvbuff(RECV_INIT);
527 #ifdef SYS_WINNT
528 init_io_completion_port();
529 #endif /* SYS_WINNT */
531 #if defined(HAVE_SIGNALED_IO)
532 (void) set_signal();
533 #endif
538 * io_open_sockets - call socket creation routine
540 void
541 io_open_sockets(void)
543 static int already_opened;
545 if (already_opened || HAVE_OPT( SAVECONFIGQUIT ))
546 return;
548 already_opened = 1;
551 * Create the sockets
553 BLOCKIO();
554 create_sockets(NTP_PORT);
555 UNBLOCKIO();
557 init_async_notifications();
559 DPRINTF(3, ("io_open_sockets: maxactivefd %d\n", maxactivefd));
563 #ifdef DEBUG
565 * function to dump the contents of the interface structure
566 * for debugging use only.
568 void
569 interface_dump(struct interface *itf)
571 printf("Dumping interface: %p\n", itf);
572 printf("fd = %d\n", itf->fd);
573 printf("bfd = %d\n", itf->bfd);
574 printf("sin = %s,\n", stoa(&itf->sin));
575 sockaddr_dump(&itf->sin);
576 printf("bcast = %s,\n", stoa(&itf->bcast));
577 sockaddr_dump(&itf->bcast);
578 printf("mask = %s,\n", stoa(&itf->mask));
579 sockaddr_dump(&itf->mask);
580 printf("name = %s\n", itf->name);
581 printf("flags = 0x%08x\n", itf->flags);
582 printf("last_ttl = %d\n", itf->last_ttl);
583 printf("addr_refid = %08x\n", itf->addr_refid);
584 printf("num_mcast = %d\n", itf->num_mcast);
585 printf("received = %ld\n", itf->received);
586 printf("sent = %ld\n", itf->sent);
587 printf("notsent = %ld\n", itf->notsent);
588 printf("scopeid = %u\n", itf->scopeid);
589 printf("peercnt = %u\n", itf->peercnt);
590 printf("phase = %u\n", itf->phase);
594 * sockaddr_dump - hex dump the start of a sockaddr_u
596 static void
597 sockaddr_dump(sockaddr_u *psau)
599 /* Limit the size of the sockaddr_storage hex dump */
600 const int maxsize = min(32, sizeof(psau->sas));
601 u_char * cp;
602 int i;
604 cp = (u_char *)&psau->sas;
606 for(i = 0; i < maxsize; i++)
608 printf("%02x", *cp++);
609 if (!((i + 1) % 4))
610 printf(" ");
612 printf("\n");
616 * print_interface - helper to output debug information
618 static void
619 print_interface(struct interface *iface, char *pfx, char *sfx)
621 printf("%sinterface #%d: fd=%d, bfd=%d, name=%s, flags=0x%x, scope=%d, sin=%s",
622 pfx,
623 iface->ifnum,
624 iface->fd,
625 iface->bfd,
626 iface->name,
627 iface->flags,
628 iface->scopeid,
629 stoa(&iface->sin));
630 if (AF_INET == iface->family) {
631 if (iface->flags & INT_BROADCAST)
632 printf(", bcast=%s", stoa(&iface->bcast));
633 printf(", mask=%s", stoa(&iface->mask));
635 printf(", %s:%s",
636 (iface->ignore_packets)
637 ? "Disabled"
638 : "Enabled",
639 sfx);
640 if (debug > 4) /* in-depth debugging only */
641 interface_dump(iface);
643 #endif
645 #if !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET)
647 * create an asyncio_reader structure
649 static struct asyncio_reader *
650 new_asyncio_reader(void)
652 struct asyncio_reader *reader;
654 reader = emalloc(sizeof(*reader));
656 memset(reader, 0, sizeof(*reader));
657 reader->fd = INVALID_SOCKET;
658 return reader;
662 * delete a reader
664 static void
665 delete_asyncio_reader(
666 struct asyncio_reader *reader
669 free(reader);
673 * add asynchio_reader
675 static void
676 add_asyncio_reader(
677 struct asyncio_reader * reader,
678 enum desc_type type)
680 LINK_SLIST(asyncio_reader_list, reader, link);
681 add_fd_to_list(reader->fd, type);
685 * remove asynchio_reader
687 static void
688 remove_asyncio_reader(
689 struct asyncio_reader *reader
692 struct asyncio_reader *unlinked;
694 UNLINK_SLIST(unlinked, asyncio_reader_list, reader, link,
695 struct asyncio_reader);
697 if (reader->fd != INVALID_SOCKET)
698 close_and_delete_fd_from_list(reader->fd);
700 reader->fd = INVALID_SOCKET;
702 #endif /* !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET) */
705 * Code to tell if we have an IP address
706 * If we have then return the sockaddr structure
707 * and set the return value
708 * see the bind9/getaddresses.c for details
710 isc_boolean_t
711 is_ip_address(
712 const char * host,
713 isc_netaddr_t * addr
716 struct in_addr in4;
717 struct in6_addr in6;
718 char tmpbuf[128];
719 char *pch;
721 NTP_REQUIRE(host != NULL);
722 NTP_REQUIRE(addr != NULL);
725 * Try IPv4, then IPv6. In order to handle the extended format
726 * for IPv6 scoped addresses (address%scope_ID), we'll use a local
727 * working buffer of 128 bytes. The length is an ad-hoc value, but
728 * should be enough for this purpose; the buffer can contain a string
729 * of at least 80 bytes for scope_ID in addition to any IPv6 numeric
730 * addresses (up to 46 bytes), the delimiter character and the
731 * terminating NULL character.
733 if (inet_pton(AF_INET, host, &in4) == 1) {
734 isc_netaddr_fromin(addr, &in4);
735 return (ISC_TRUE);
736 } else if (sizeof(tmpbuf) > strlen(host)) {
737 if ('[' == host[0]) {
738 strncpy(tmpbuf, &host[1], sizeof(tmpbuf));
739 pch = strchr(tmpbuf, ']');
740 if (pch != NULL)
741 *pch = '\0';
742 } else
743 strncpy(tmpbuf, host, sizeof(tmpbuf));
744 pch = strchr(tmpbuf, '%');
745 if (pch != NULL)
746 *pch = '\0';
748 if (inet_pton(AF_INET6, tmpbuf, &in6) == 1) {
749 isc_netaddr_fromin6(addr, &in6);
750 return (ISC_TRUE);
754 * If we got here it was not an IP address
756 return (ISC_FALSE);
761 * interface list enumerator - visitor pattern
763 void
764 interface_enumerate(
765 interface_receiver_t receiver,
766 void * data
769 interface_info_t ifi;
771 ifi.action = IFS_EXISTS;
773 for (ifi.interface = inter_list;
774 ifi.interface != NULL;
775 ifi.interface = ifi.interface->link)
776 (*receiver)(data, &ifi);
780 * do standard initialization of interface structure
782 static void
783 init_interface(
784 struct interface *iface
787 memset(iface, 0, sizeof(*iface));
788 iface->fd = INVALID_SOCKET;
789 iface->bfd = INVALID_SOCKET;
790 iface->phase = sys_interphase;
795 * create new interface structure initialize from
796 * template structure or via standard initialization
797 * function
799 static struct interface *
800 new_interface(
801 struct interface *interface
804 static u_int sys_ifnum = 0;
805 struct interface * iface;
807 iface = emalloc(sizeof(*iface));
809 if (NULL == interface)
810 init_interface(iface);
811 else /* use the template */
812 memcpy(iface, interface, sizeof(*iface));
814 /* count every new instance of an interface in the system */
815 iface->ifnum = sys_ifnum++;
816 iface->starttime = current_time;
818 return iface;
823 * return interface storage into free memory pool
825 static inline void
826 delete_interface(
827 struct interface *interface
830 free(interface);
835 * link interface into list of known interfaces
837 static void
838 add_interface(
839 struct interface *interface
843 * Calculate the address hash
845 interface->addr_refid = addr2refid(&interface->sin);
847 LINK_SLIST(inter_list, interface, link);
848 ninterfaces++;
853 * remove interface from known interface list and clean up
854 * associated resources
856 static void
857 remove_interface(
858 struct interface *iface
861 struct interface *unlinked;
862 sockaddr_u resmask;
864 UNLINK_SLIST(unlinked, inter_list, iface, link, struct
865 interface);
867 delete_interface_from_list(iface);
869 if (iface->fd != INVALID_SOCKET) {
870 msyslog(LOG_INFO,
871 "Deleting interface #%d %s, %s#%d, interface stats: received=%ld, sent=%ld, dropped=%ld, active_time=%ld secs",
872 iface->ifnum,
873 iface->name,
874 stoa(&iface->sin),
875 SRCPORT(&iface->sin),
876 iface->received,
877 iface->sent,
878 iface->notsent,
879 current_time - iface->starttime);
881 close_and_delete_fd_from_list(iface->fd);
884 if (iface->bfd != INVALID_SOCKET) {
885 msyslog(LOG_INFO,
886 "Deleting broadcast address %s#%d from interface #%d %s",
887 stoa(&iface->bcast),
888 SRCPORT(&iface->bcast),
889 iface->ifnum,
890 iface->name);
892 close_and_delete_fd_from_list(iface->bfd);
895 ninterfaces--;
896 ntp_monclearinterface(iface);
898 /* remove restrict interface entry */
899 SET_HOSTMASK(&resmask, AF(&iface->sin));
900 hack_restrict(RESTRICT_REMOVEIF, &iface->sin, &resmask,
901 RESM_NTPONLY | RESM_INTERFACE, RES_IGNORE);
905 static void
906 list_if_listening(
907 struct interface * iface
910 msyslog(LOG_INFO, "%s on %d %s %s UDP %d",
911 (iface->ignore_packets)
912 ? "Listen and drop"
913 : "Listen normally",
914 iface->ifnum,
915 iface->name,
916 stoa(&iface->sin),
917 SRCPORT(&iface->sin));
921 static void
922 create_wildcards(
923 u_short port
926 int v4wild, v6wild;
927 sockaddr_u wildaddr;
928 isc_netaddr_t wnaddr;
929 nic_rule_action action;
930 struct interface * wildif;
933 * silence "potentially uninitialized" warnings from VC9
934 * failing to follow the logic. Ideally action could remain
935 * uninitialized, and the memset be the first statement under
936 * the first if (v4wild).
938 action = ACTION_LISTEN;
939 memset(&wildaddr, 0, sizeof(wildaddr));
942 * create pseudo-interface with wildcard IPv4 address
944 v4wild = ipv4_works;
945 if (v4wild) {
946 /* set wildaddr to the v4 wildcard address 0.0.0.0 */
947 AF(&wildaddr) = AF_INET;
948 SET_ADDR4(&wildaddr, INADDR_ANY);
949 SET_PORT(&wildaddr, port);
951 /* make an libisc-friendly copy */
952 isc_netaddr_fromin(&wnaddr, &wildaddr.sa4.sin_addr);
954 /* check for interface/nic rules affecting the wildcard */
955 action = interface_action(NULL, &wnaddr, 0);
956 v4wild = (ACTION_IGNORE != action);
958 if (v4wild) {
959 wildif = new_interface(NULL);
961 strncpy(wildif->name, "v4wildcard", sizeof(wildif->name));
962 memcpy(&wildif->sin, &wildaddr, sizeof(wildif->sin));
963 wildif->family = AF_INET;
964 AF(&wildif->mask) = AF_INET;
965 SET_ONESMASK(&wildif->mask);
967 wildif->flags = INT_BROADCAST | INT_UP | INT_WILDCARD;
968 wildif->ignore_packets = (ACTION_DROP == action);
969 #if defined(MCAST)
971 * enable multicast reception on the broadcast socket
973 AF(&wildif->bcast) = AF_INET;
974 SET_ADDR4(&wildif->bcast, INADDR_ANY);
975 SET_PORT(&wildif->bcast, port);
976 #endif /* MCAST */
977 wildif->fd = open_socket(&wildif->sin, 0, 1, wildif);
979 if (wildif->fd != INVALID_SOCKET) {
980 wildipv4 = wildif;
981 any_interface = wildif;
983 add_addr_to_list(&wildif->sin, wildif);
984 add_interface(wildif);
985 list_if_listening(wildif);
986 } else {
987 msyslog(LOG_ERR,
988 "unable to bind to wildcard address %s - another process may be running - EXITING",
989 stoa(&wildif->sin));
990 exit(1);
992 DPRINT_INTERFACE(2, (wildif, "created ", "\n"));
995 #ifdef INCLUDE_IPV6_SUPPORT
997 * create pseudo-interface with wildcard IPv6 address
999 v6wild = ipv6_works;
1000 if (v6wild) {
1001 /* set wildaddr to the v6 wildcard address :: */
1002 memset(&wildaddr, 0, sizeof(wildaddr));
1003 AF(&wildaddr) = AF_INET6;
1004 SET_ADDR6N(&wildaddr, in6addr_any);
1005 SET_PORT(&wildaddr, port);
1006 SET_SCOPE(&wildaddr, 0);
1008 /* make an libisc-friendly copy */
1009 isc_netaddr_fromin(&wnaddr, &wildaddr.sa4.sin_addr);
1011 /* check for interface/nic rules affecting the wildcard */
1012 action = interface_action(NULL, &wnaddr, 0);
1013 v6wild = (ACTION_IGNORE != action);
1015 if (v6wild) {
1016 wildif = new_interface(NULL);
1018 strncpy(wildif->name, "v6wildcard", sizeof(wildif->name));
1019 memcpy(&wildif->sin, &wildaddr, sizeof(wildif->sin));
1020 wildif->family = AF_INET6;
1021 AF(&wildif->mask) = AF_INET6;
1022 SET_ONESMASK(&wildif->mask);
1024 wildif->flags = INT_UP | INT_WILDCARD;
1025 wildif->ignore_packets = (ACTION_DROP == action);
1027 wildif->fd = open_socket(&wildif->sin, 0, 1, wildif);
1029 if (wildif->fd != INVALID_SOCKET) {
1030 wildipv6 = wildif;
1031 any6_interface = wildif;
1032 add_addr_to_list(&wildif->sin, wildif);
1033 add_interface(wildif);
1034 list_if_listening(wildif);
1035 } else {
1036 msyslog(LOG_ERR,
1037 "unable to bind to wildcard address %s - another process may be running - EXITING",
1038 stoa(&wildif->sin));
1039 exit(1);
1041 DPRINT_INTERFACE(2, (wildif, "created ", "\n"));
1043 #endif
1048 * add_nic_rule() -- insert a rule entry at the head of nic_rule_list.
1050 void
1051 add_nic_rule(
1052 nic_rule_match match_type,
1053 const char * if_name, /* interface name or numeric address */
1054 int prefixlen,
1055 nic_rule_action action
1058 nic_rule * rule;
1059 isc_boolean_t is_ip;
1061 rule = emalloc(sizeof(*rule));
1062 memset(rule, 0, sizeof(*rule));
1063 rule->match_type = match_type;
1064 rule->prefixlen = prefixlen;
1065 rule->action = action;
1067 if (MATCH_IFNAME == match_type) {
1068 NTP_REQUIRE(NULL != if_name);
1069 rule->if_name = estrdup(if_name);
1070 } else if (MATCH_IFADDR == match_type) {
1071 NTP_REQUIRE(NULL != if_name);
1072 /* set rule->netaddr */
1073 is_ip = is_ip_address(if_name, &rule->netaddr);
1074 NTP_REQUIRE(is_ip);
1075 } else
1076 NTP_REQUIRE(NULL == if_name);
1078 LINK_SLIST(nic_rule_list, rule, next);
1082 #ifdef DEBUG
1083 static const char *
1084 action_text(
1085 nic_rule_action action
1088 const char *t;
1090 switch (action) {
1092 default:
1093 t = "ERROR"; /* quiet uninit warning */
1094 DPRINTF(1, ("fatal: unknown nic_rule_action %d\n",
1095 action));
1096 NTP_ENSURE(0);
1097 break;
1099 case ACTION_LISTEN:
1100 t = "listen";
1101 break;
1103 case ACTION_IGNORE:
1104 t = "ignore";
1105 break;
1107 case ACTION_DROP:
1108 t = "drop";
1109 break;
1112 return t;
1114 #endif /* DEBUG */
1117 static nic_rule_action
1118 interface_action(
1119 char * if_name,
1120 isc_netaddr_t * if_netaddr,
1121 isc_uint32_t if_flags
1124 nic_rule *rule;
1125 int isloopback;
1126 int iswildcard;
1128 DPRINTF(4, ("interface_action: interface %s ",
1129 (if_name != NULL) ? if_name : "wildcard"));
1131 iswildcard = is_wildcard_netaddr(if_netaddr);
1134 * Always listen on 127.0.0.1 - required by ntp_intres
1136 if (if_flags & INTERFACE_F_LOOPBACK) {
1137 isloopback = 1;
1138 if (AF_INET == if_netaddr->family) {
1139 DPRINTF(4, ("IPv4 loopback - listen\n"));
1140 return ACTION_LISTEN;
1142 } else
1143 isloopback = 0;
1146 * Find any matching NIC rule from --interface / -I or ntp.conf
1147 * interface/nic rules.
1149 for (rule = nic_rule_list; rule != NULL; rule = rule->next) {
1151 switch (rule->match_type) {
1153 case MATCH_ALL:
1154 /* loopback and wildcard excluded from "all" */
1155 if (isloopback || iswildcard)
1156 break;
1157 DPRINTF(4, ("nic all %s\n",
1158 action_text(rule->action)));
1159 return rule->action;
1161 case MATCH_IPV4:
1162 if (AF_INET == if_netaddr->family) {
1163 DPRINTF(4, ("nic ipv4 %s\n",
1164 action_text(rule->action)));
1165 return rule->action;
1167 break;
1169 case MATCH_IPV6:
1170 if (AF_INET6 == if_netaddr->family) {
1171 DPRINTF(4, ("nic ipv6 %s\n",
1172 action_text(rule->action)));
1173 return rule->action;
1175 break;
1177 case MATCH_WILDCARD:
1178 if (iswildcard) {
1179 DPRINTF(4, ("nic wildcard %s\n",
1180 action_text(rule->action)));
1181 return rule->action;
1183 break;
1185 case MATCH_IFADDR:
1186 if (rule->prefixlen != -1) {
1187 if (isc_netaddr_eqprefix(if_netaddr,
1188 &rule->netaddr, rule->prefixlen)) {
1190 DPRINTF(4, ("subnet address match - %s\n",
1191 action_text(rule->action)));
1192 return rule->action;
1194 } else
1195 if (isc_netaddr_equal(if_netaddr,
1196 &rule->netaddr)) {
1198 DPRINTF(4, ("address match - %s\n",
1199 action_text(rule->action)));
1200 return rule->action;
1202 break;
1204 case MATCH_IFNAME:
1205 if (if_name != NULL
1206 && !strcasecmp(if_name, rule->if_name)) {
1208 DPRINTF(4, ("interface name match - %s\n",
1209 action_text(rule->action)));
1210 return rule->action;
1212 break;
1217 * Unless explicitly disabled such as with "nic ignore ::1"
1218 * listen on loopback addresses. Since ntpq and ntpdc query
1219 * "localhost" by default, which typically resolves to ::1 and
1220 * 127.0.0.1, it's useful to default to listening on both.
1222 if (isloopback) {
1223 DPRINTF(4, ("default loopback listen\n"));
1224 return ACTION_LISTEN;
1228 * Treat wildcard addresses specially. If there is no explicit
1229 * "nic ... wildcard" or "nic ... 0.0.0.0" or "nic ... ::" rule
1230 * default to drop.
1232 if (iswildcard) {
1233 DPRINTF(4, ("default wildcard drop\n"));
1234 return ACTION_DROP;
1238 * Check for "virtual IP" (colon in the interface name) after
1239 * the rules so that "ntpd --interface eth0:1 -novirtualips"
1240 * does indeed listen on eth0:1's addresses.
1242 if (!listen_to_virtual_ips && if_name != NULL
1243 && (strchr(if_name, ':') != NULL)) {
1245 DPRINTF(4, ("virtual ip - ignore\n"));
1246 return ACTION_IGNORE;
1250 * If there are no --interface/-I command-line options and no
1251 * interface/nic rules in ntp.conf, the default action is to
1252 * listen. In the presence of rules from either, the default
1253 * is to ignore. This implements ntpd's traditional listen-
1254 * every default with no interface listen configuration, and
1255 * ensures a single -I eth0 or "nic listen eth0" means do not
1256 * listen on any other addresses.
1258 if (NULL == nic_rule_list) {
1259 DPRINTF(4, ("default listen\n"));
1260 return ACTION_LISTEN;
1263 DPRINTF(4, ("implicit ignore\n"));
1264 return ACTION_IGNORE;
1268 static void
1269 convert_isc_if(
1270 isc_interface_t *isc_if,
1271 struct interface *itf,
1272 u_short port
1275 strncpy(itf->name, isc_if->name, sizeof(itf->name));
1276 itf->name[sizeof(itf->name) - 1] = 0; /* strncpy may not */
1277 itf->family = (u_short)isc_if->af;
1278 AF(&itf->sin) = itf->family;
1279 AF(&itf->mask) = itf->family;
1280 AF(&itf->bcast) = itf->family;
1281 SET_PORT(&itf->sin, port);
1282 SET_PORT(&itf->mask, port);
1283 SET_PORT(&itf->bcast, port);
1285 if (IS_IPV4(&itf->sin)) {
1286 NSRCADR(&itf->sin) = isc_if->address.type.in.s_addr;
1287 NSRCADR(&itf->mask) = isc_if->netmask.type.in.s_addr;
1289 if (isc_if->flags & INTERFACE_F_BROADCAST) {
1290 itf->flags |= INT_BROADCAST;
1291 NSRCADR(&itf->bcast) =
1292 isc_if->broadcast.type.in.s_addr;
1295 #ifdef INCLUDE_IPV6_SUPPORT
1296 else if (IS_IPV6(&itf->sin)) {
1297 SET_ADDR6N(&itf->sin, isc_if->address.type.in6);
1298 SET_ADDR6N(&itf->mask, isc_if->netmask.type.in6);
1300 itf->scopeid = isc_netaddr_getzone(&isc_if->address);
1301 SET_SCOPE(&itf->sin, itf->scopeid);
1303 #endif /* INCLUDE_IPV6_SUPPORT */
1306 /* Process the rest of the flags */
1308 itf->flags |=
1309 ((INTERFACE_F_UP & isc_if->flags)
1310 ? INT_UP : 0)
1311 | ((INTERFACE_F_LOOPBACK & isc_if->flags)
1312 ? INT_LOOPBACK : 0)
1313 | ((INTERFACE_F_POINTTOPOINT & isc_if->flags)
1314 ? INT_PPP : 0)
1315 | ((INTERFACE_F_MULTICAST & isc_if->flags)
1316 ? INT_MULTICAST : 0)
1322 * refresh_interface
1324 * some OSes have been observed to keep
1325 * cached routes even when more specific routes
1326 * become available.
1327 * this can be mitigated by re-binding
1328 * the socket.
1330 static int
1331 refresh_interface(
1332 struct interface * interface
1335 #ifdef OS_MISSES_SPECIFIC_ROUTE_UPDATES
1336 if (interface->fd != INVALID_SOCKET) {
1337 close_and_delete_fd_from_list(interface->fd);
1338 interface->fd = open_socket(&interface->sin,
1339 0, 0, interface);
1341 * reset TTL indication so TTL is is set again
1342 * next time around
1344 interface->last_ttl = 0;
1345 return (interface->fd != INVALID_SOCKET);
1346 } else
1347 return 0; /* invalid sockets are not refreshable */
1348 #else /* !OS_MISSES_SPECIFIC_ROUTE_UPDATES */
1349 return (interface->fd != INVALID_SOCKET);
1350 #endif /* !OS_MISSES_SPECIFIC_ROUTE_UPDATES */
1354 * interface_update - externally callable update function
1356 void
1357 interface_update(
1358 interface_receiver_t receiver,
1359 void * data)
1361 int new_interface_found;
1363 if (disable_dynamic_updates)
1364 return;
1366 BLOCKIO();
1367 new_interface_found = update_interfaces(NTP_PORT, receiver, data);
1368 UNBLOCKIO();
1370 if (!new_interface_found)
1371 return;
1373 #ifdef DEBUG
1374 msyslog(LOG_DEBUG, "new interface(s) found: waking up resolver");
1375 #endif
1376 #ifdef SYS_WINNT
1377 /* wake up the resolver thread */
1378 if (ResolverEventHandle != NULL)
1379 SetEvent(ResolverEventHandle);
1380 #else
1381 /* write any single byte to the pipe to wake up the resolver process */
1382 write( resolver_pipe_fd[1], &new_interface_found, 1 );
1383 #endif
1388 * sau_from_netaddr() - convert network address on-wire formats.
1389 * Convert from libisc's isc_netaddr_t to NTP's sockaddr_u
1391 void
1392 sau_from_netaddr(
1393 sockaddr_u *psau,
1394 const isc_netaddr_t *pna
1397 memset(psau, 0, sizeof(*psau));
1398 AF(psau) = (u_short)pna->family;
1399 switch (pna->family) {
1401 case AF_INET:
1402 memcpy(&psau->sa4.sin_addr, &pna->type.in,
1403 sizeof(psau->sa4.sin_addr));
1404 break;
1406 case AF_INET6:
1407 memcpy(&psau->sa6.sin6_addr, &pna->type.in6,
1408 sizeof(psau->sa6.sin6_addr));
1409 break;
1414 static int
1415 is_wildcard_addr(
1416 sockaddr_u *psau
1419 if (IS_IPV4(psau) && !NSRCADR(psau))
1420 return 1;
1422 #ifdef INCLUDE_IPV6_SUPPORT
1423 if (IS_IPV6(psau) && S_ADDR6_EQ(psau, &in6addr_any))
1424 return 1;
1425 #endif
1427 return 0;
1431 static int
1432 is_wildcard_netaddr(
1433 const isc_netaddr_t *pna
1436 sockaddr_u sau;
1438 sau_from_netaddr(&sau, pna);
1440 return is_wildcard_addr(&sau);
1444 #ifdef OS_NEEDS_REUSEADDR_FOR_IFADDRBIND
1446 * enable/disable re-use of wildcard address socket
1448 static void
1449 set_wildcard_reuse(
1450 u_short family,
1451 int on
1454 struct interface *any;
1455 SOCKET fd = INVALID_SOCKET;
1457 any = ANY_INTERFACE_BYFAM(family);
1458 if (any != NULL)
1459 fd = any->fd;
1461 if (fd != INVALID_SOCKET) {
1462 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1463 (char *)&on, sizeof(on)))
1464 msyslog(LOG_ERR,
1465 "set_wildcard_reuse: setsockopt(SO_REUSEADDR, %s) failed: %m",
1466 on ? "on" : "off");
1468 DPRINTF(4, ("set SO_REUSEADDR to %s on %s\n",
1469 on ? "on" : "off",
1470 stoa(&any->sin)));
1473 #endif /* OS_NEEDS_REUSEADDR_FOR_IFADDRBIND */
1476 * update_interface strategy
1478 * toggle configuration phase
1480 * Phase 1:
1481 * forall currently existing interfaces
1482 * if address is known:
1483 * drop socket - rebind again
1485 * if address is NOT known:
1486 * attempt to create a new interface entry
1488 * Phase 2:
1489 * forall currently known non MCAST and WILDCARD interfaces
1490 * if interface does not match configuration phase (not seen in phase 1):
1491 * remove interface from known interface list
1492 * forall peers associated with this interface
1493 * disconnect peer from this interface
1495 * Phase 3:
1496 * attempt to re-assign interfaces to peers
1500 static int
1501 update_interfaces(
1502 u_short port,
1503 interface_receiver_t receiver,
1504 void * data
1507 isc_mem_t * mctx = (void *)-1;
1508 interface_info_t ifi;
1509 isc_interfaceiter_t * iter;
1510 isc_result_t result;
1511 isc_interface_t isc_if;
1512 int new_interface_found;
1513 unsigned int family;
1514 struct interface interface;
1515 struct interface * iface;
1516 struct interface * next;
1518 DPRINTF(3, ("update_interfaces(%d)\n", port));
1521 * phase one - scan interfaces
1522 * - create those that are not found
1523 * - update those that are found
1526 new_interface_found = 0;
1527 iter = NULL;
1528 result = isc_interfaceiter_create(mctx, &iter);
1530 if (result != ISC_R_SUCCESS)
1531 return 0;
1534 * Toggle system interface scan phase to find untouched
1535 * interfaces to be deleted.
1537 sys_interphase ^= 0x1;
1539 for (result = isc_interfaceiter_first(iter);
1540 ISC_R_SUCCESS == result;
1541 result = isc_interfaceiter_next(iter)) {
1543 result = isc_interfaceiter_current(iter, &isc_if);
1545 if (result != ISC_R_SUCCESS)
1546 break;
1548 /* See if we have a valid family to use */
1549 family = isc_if.address.family;
1550 if (AF_INET != family && AF_INET6 != family)
1551 continue;
1552 if (AF_INET == family && !ipv4_works)
1553 continue;
1554 if (AF_INET6 == family && !ipv6_works)
1555 continue;
1557 /* create prototype */
1558 init_interface(&interface);
1560 convert_isc_if(&isc_if, &interface, port);
1563 * Check if and how we are going to use the interface.
1565 switch (interface_action(isc_if.name, &isc_if.address,
1566 isc_if.flags)) {
1568 case ACTION_IGNORE:
1569 continue;
1571 case ACTION_LISTEN:
1572 interface.ignore_packets = ISC_FALSE;
1573 break;
1575 case ACTION_DROP:
1576 interface.ignore_packets = ISC_TRUE;
1577 break;
1580 DPRINT_INTERFACE(4, (&interface, "examining ", "\n"));
1582 /* interfaces must be UP to be usable */
1583 if (!(interface.flags & INT_UP)) {
1584 DPRINTF(4, ("skipping interface %s (%s) - DOWN\n",
1585 interface.name, stoa(&interface.sin)));
1586 continue;
1590 * skip any interfaces UP and bound to a wildcard
1591 * address - some dhcp clients produce that in the
1592 * wild
1594 if (is_wildcard_addr(&interface.sin))
1595 continue;
1598 * map to local *address* in order to map all duplicate
1599 * interfaces to an interface structure with the
1600 * appropriate socket. Our name space is (ip-address),
1601 * NOT (interface name, ip-address).
1603 iface = getinterface(&interface.sin, INT_WILDCARD);
1605 if (iface != NULL && refresh_interface(iface)) {
1607 * found existing and up to date interface -
1608 * mark present.
1610 if (iface->phase != sys_interphase) {
1612 * On a new round we reset the name so
1613 * the interface name shows up again if
1614 * this address is no longer shared.
1615 * The same reasoning goes for the
1616 * ignore_packets flag.
1618 strncpy(iface->name, interface.name,
1619 sizeof(iface->name));
1620 iface->ignore_packets =
1621 interface.ignore_packets;
1622 } else
1623 /* name collision - rename interface */
1624 strncpy(iface->name, "*multiple*",
1625 sizeof(iface->name));
1627 DPRINT_INTERFACE(4, (iface, "updating ",
1628 " present\n"));
1630 if (iface->ignore_packets !=
1631 interface.ignore_packets) {
1633 * We have conflicting configurations
1634 * for the interface address. This is
1635 * caused by using -I <interfacename>
1636 * for an interface that shares its
1637 * address with other interfaces. We
1638 * can not disambiguate incoming
1639 * packets delivered to this socket
1640 * without extra syscalls/features.
1641 * These are not (commonly) available.
1642 * Note this is a more unusual
1643 * configuration where several
1644 * interfaces share an address but
1645 * filtering via interface name is
1646 * attempted. We resolve the
1647 * configuration conflict by disabling
1648 * the processing of received packets.
1649 * This leads to no service on the
1650 * interface address where the conflict
1651 * occurs.
1653 msyslog(LOG_ERR,
1654 "WARNING: conflicting enable configuration for interfaces %s and %s for address %s - unsupported configuration - address DISABLED",
1655 interface.name, iface->name,
1656 stoa(&interface.sin));
1658 iface->ignore_packets = ISC_TRUE;
1661 iface->phase = sys_interphase;
1663 ifi.action = IFS_EXISTS;
1664 ifi.interface = iface;
1665 if (receiver != NULL)
1666 (*receiver)(data, &ifi);
1667 } else {
1669 * This is new or refreshing failed - add to
1670 * our interface list. If refreshing failed we
1671 * will delete the interface structure in phase
1672 * 2 as the interface was not marked current.
1673 * We can bind to the address as the refresh
1674 * code already closed the offending socket
1676 iface = create_interface(port, &interface);
1678 if (iface != NULL) {
1679 ifi.action = IFS_CREATED;
1680 ifi.interface = iface;
1681 if (receiver != NULL)
1682 (*receiver)(data, &ifi);
1684 new_interface_found = 1;
1686 DPRINT_INTERFACE(3,
1687 (iface, "updating ",
1688 " new - created\n"));
1689 } else {
1690 DPRINT_INTERFACE(3,
1691 (&interface, "updating ",
1692 " new - creation FAILED"));
1694 msyslog(LOG_INFO,
1695 "failed to init interface for address %s",
1696 stoa(&interface.sin));
1697 continue;
1702 isc_interfaceiter_destroy(&iter);
1705 * phase 2 - delete gone interfaces - reassigning peers to
1706 * other interfaces
1708 iface = inter_list;
1710 while (iface != NULL) {
1711 next = iface->link;
1713 if (!(iface->flags & (INT_WILDCARD | INT_MCASTIF))) {
1715 * if phase does not match sys_phase this
1716 * interface was not enumerated during the last
1717 * interface scan - so it is gone and will be
1718 * deleted here unless it is solely an MCAST or
1719 * WILDCARD interface.
1721 if (iface->phase != sys_interphase) {
1722 DPRINT_INTERFACE(3,
1723 (iface, "updating ",
1724 "GONE - deleting\n"));
1725 remove_interface(iface);
1727 ifi.action = IFS_DELETED;
1728 ifi.interface = iface;
1729 if (receiver != NULL)
1730 (*receiver)(data, &ifi);
1733 * disconnect peers from deleted
1734 * interface
1736 while (iface->peers != NULL)
1737 set_peerdstadr(iface->peers, NULL);
1740 * update globals in case we lose
1741 * a loopback interface
1743 if (iface == loopback_interface)
1744 loopback_interface = NULL;
1746 delete_interface(iface);
1749 iface = next;
1753 * phase 3 - re-configure as the world has changed if necessary
1755 refresh_all_peerinterfaces();
1756 return new_interface_found;
1761 * create_sockets - create a socket for each interface plus a default
1762 * socket for when we don't know where to send
1764 static int
1765 create_sockets(
1766 u_short port
1769 #ifndef HAVE_IO_COMPLETION_PORT
1771 * I/O Completion Ports don't care about the select and FD_SET
1773 maxactivefd = 0;
1774 FD_ZERO(&activefds);
1775 #endif
1777 DPRINTF(2, ("create_sockets(%d)\n", port));
1779 create_wildcards(port);
1781 update_interfaces(port, NULL, NULL);
1784 * Now that we have opened all the sockets, turn off the reuse
1785 * flag for security.
1787 set_reuseaddr(0);
1789 DPRINTF(2, ("create_sockets: Total interfaces = %d\n", ninterfaces));
1791 return ninterfaces;
1795 * create_interface - create a new interface for a given prototype
1796 * binding the socket.
1798 static struct interface *
1799 create_interface(
1800 u_short port,
1801 struct interface * protot
1804 sockaddr_u resmask;
1805 struct interface *iface;
1807 DPRINTF(2, ("create_interface(%s#%d)\n", stoa(&protot->sin),
1808 port));
1810 /* build an interface */
1811 iface = new_interface(protot);
1814 * create socket
1816 iface->fd = open_socket(&iface->sin, 0, 0, iface);
1818 if (iface->fd != INVALID_SOCKET)
1819 list_if_listening(iface);
1821 if ((INT_BROADCAST & iface->flags)
1822 && iface->bfd != INVALID_SOCKET)
1823 msyslog(LOG_INFO, "Listening on broadcast address %s#%d",
1824 stoa((&iface->bcast)), port);
1826 if (INVALID_SOCKET == iface->fd
1827 && INVALID_SOCKET == iface->bfd) {
1828 msyslog(LOG_ERR, "unable to create socket on %s (%d) for %s#%d",
1829 iface->name,
1830 iface->ifnum,
1831 stoa((&iface->sin)),
1832 port);
1833 delete_interface(iface);
1834 return NULL;
1838 * Blacklist our own addresses, no use talking to ourself
1840 SET_HOSTMASK(&resmask, AF(&iface->sin));
1841 hack_restrict(RESTRICT_FLAGS, &iface->sin, &resmask,
1842 RESM_NTPONLY | RESM_INTERFACE, RES_IGNORE);
1845 * set globals with the first found
1846 * loopback interface of the appropriate class
1848 if (NULL == loopback_interface && AF_INET == iface->family
1849 && (INT_LOOPBACK & iface->flags))
1850 loopback_interface = iface;
1853 * put into our interface list
1855 add_addr_to_list(&iface->sin, iface);
1856 add_interface(iface);
1858 DPRINT_INTERFACE(2, (iface, "created ", "\n"));
1859 return iface;
1863 #ifdef SO_EXCLUSIVEADDRUSE
1864 static void
1865 set_excladdruse(
1866 SOCKET fd
1869 int one = 1;
1870 int failed;
1871 #ifdef SYS_WINNT
1872 DWORD err;
1873 #endif
1875 failed = setsockopt(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
1876 (char *)&one, sizeof(one));
1878 if (!failed)
1879 return;
1881 #ifdef SYS_WINNT
1883 * Prior to Windows XP setting SO_EXCLUSIVEADDRUSE can fail with
1884 * error WSAINVAL depending on service pack level and whether
1885 * the user account is in the Administrators group. Do not
1886 * complain if it fails that way on versions prior to XP (5.1).
1888 err = GetLastError();
1890 if (isc_win32os_versioncheck(5, 1, 0, 0) < 0 /* < 5.1/XP */
1891 && WSAEINVAL == err)
1892 return;
1894 SetLastError(err);
1895 #endif
1896 msyslog(LOG_ERR,
1897 "setsockopt(%d, SO_EXCLUSIVEADDRUSE, on): %m",
1898 (int)fd);
1900 #endif /* SO_EXCLUSIVEADDRUSE */
1904 * set_reuseaddr() - set/clear REUSEADDR on all sockets
1905 * NB possible hole - should we be doing this on broadcast
1906 * fd's also?
1908 static void
1909 set_reuseaddr(
1910 int flag
1913 #ifndef SO_EXCLUSIVEADDRUSE
1914 struct interface *interf;
1916 for (interf = inter_list;
1917 interf != NULL;
1918 interf = interf->link) {
1920 if (interf->flags & INT_WILDCARD)
1921 continue;
1924 * if interf->fd is INVALID_SOCKET, we might have a adapter
1925 * configured but not present
1927 DPRINTF(4, ("setting SO_REUSEADDR on %.16s@%s to %s\n",
1928 interf->name, stoa(&interf->sin),
1929 flag ? "on" : "off"));
1931 if (interf->fd != INVALID_SOCKET) {
1932 if (setsockopt(interf->fd, SOL_SOCKET,
1933 SO_REUSEADDR, (char *)&flag,
1934 sizeof(flag))) {
1935 msyslog(LOG_ERR, "set_reuseaddr: setsockopt(SO_REUSEADDR, %s) failed: %m", flag ? "on" : "off");
1939 #endif /* ! SO_EXCLUSIVEADDRUSE */
1943 * This is just a wrapper around an internal function so we can
1944 * make other changes as necessary later on
1946 void
1947 enable_broadcast(
1948 struct interface * iface,
1949 sockaddr_u * baddr
1952 #ifdef OPEN_BCAST_SOCKET
1953 socket_broadcast_enable(iface, iface->fd, baddr);
1954 #endif
1957 #ifdef OPEN_BCAST_SOCKET
1959 * Enable a broadcast address to a given socket
1960 * The socket is in the inter_list all we need to do is enable
1961 * broadcasting. It is not this function's job to select the socket
1963 static isc_boolean_t
1964 socket_broadcast_enable(
1965 struct interface * iface,
1966 SOCKET fd,
1967 sockaddr_u * baddr
1970 #ifdef SO_BROADCAST
1971 int on = 1;
1973 if (IS_IPV4(baddr)) {
1974 /* if this interface can support broadcast, set SO_BROADCAST */
1975 if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST,
1976 (char *)&on, sizeof(on)))
1977 msyslog(LOG_ERR,
1978 "setsockopt(SO_BROADCAST) enable failure on address %s: %m",
1979 stoa(baddr));
1980 else
1981 DPRINTF(2, ("Broadcast enabled on socket %d for address %s\n",
1982 fd, stoa(baddr)));
1984 iface->flags |= INT_BCASTOPEN;
1985 broadcast_client_enabled = ISC_TRUE;
1986 return ISC_TRUE;
1987 #else
1988 return ISC_FALSE;
1989 #endif /* SO_BROADCAST */
1993 * Remove a broadcast address from a given socket
1994 * The socket is in the inter_list all we need to do is disable
1995 * broadcasting. It is not this function's job to select the socket
1997 static isc_boolean_t
1998 socket_broadcast_disable(
1999 struct interface * iface,
2000 sockaddr_u * baddr
2003 #ifdef SO_BROADCAST
2004 int off = 0; /* This seems to be OK as an int */
2006 if (IS_IPV4(baddr) && setsockopt(iface->fd, SOL_SOCKET,
2007 SO_BROADCAST, (char *)&off, sizeof(off)))
2008 msyslog(LOG_ERR,
2009 "setsockopt(SO_BROADCAST) disable failure on address %s: %m",
2010 stoa(baddr));
2012 iface->flags &= ~INT_BCASTOPEN;
2013 broadcast_client_enabled = ISC_FALSE;
2014 return ISC_TRUE;
2015 #else
2016 return ISC_FALSE;
2017 #endif /* SO_BROADCAST */
2020 #endif /* OPEN_BCAST_SOCKET */
2023 * return the broadcast client flag value
2025 isc_boolean_t
2026 get_broadcastclient_flag(void)
2028 return (broadcast_client_enabled);
2031 * Check to see if the address is a multicast address
2033 static isc_boolean_t
2034 addr_ismulticast(
2035 sockaddr_u *maddr
2038 isc_boolean_t result;
2040 #ifndef INCLUDE_IPV6_MULTICAST_SUPPORT
2042 * If we don't have IPV6 support any IPV6 addr is not multicast
2044 if (IS_IPV6(maddr))
2045 result = ISC_FALSE;
2046 else
2047 #endif
2048 result = IS_MCAST(maddr);
2050 if (!result)
2051 DPRINTF(4, ("address %s is not multicast\n",
2052 stoa(maddr)));
2054 return result;
2058 * Multicast servers need to set the appropriate Multicast interface
2059 * socket option in order for it to know which interface to use for
2060 * send the multicast packet.
2062 void
2063 enable_multicast_if(
2064 struct interface * iface,
2065 sockaddr_u * maddr
2068 #ifdef MCAST
2069 TYPEOF_IP_MULTICAST_LOOP off = 0;
2071 NTP_REQUIRE(AF(maddr) == AF(&iface->sin));
2073 switch (AF(&iface->sin)) {
2075 case AF_INET:
2076 if (setsockopt(iface->fd, IPPROTO_IP, IP_MULTICAST_IF,
2077 (void *)&NSRCADR(&iface->sin),
2078 sizeof(NSRCADR(&iface->sin)))) {
2080 msyslog(LOG_ERR,
2081 "setsockopt IP_MULTICAST_IF failed: %m on socket %d, addr %s for multicast address %s",
2082 iface->fd, stoa(&iface->sin),
2083 stoa(maddr));
2084 return;
2086 #ifdef IP_MULTICAST_LOOP
2088 * Don't send back to itself, but allow failure to set
2090 if (setsockopt(iface->fd, IPPROTO_IP,
2091 IP_MULTICAST_LOOP,
2092 SETSOCKOPT_ARG_CAST &off,
2093 sizeof(off))) {
2095 msyslog(LOG_ERR,
2096 "setsockopt IP_MULTICAST_LOOP failed: %m on socket %d, addr %s for multicast address %s",
2097 iface->fd, stoa(&iface->sin),
2098 stoa(maddr));
2100 #endif
2101 DPRINTF(4, ("Added IPv4 multicast interface on socket %d, addr %s for multicast address %s\n",
2102 iface->fd, stoa(&iface->sin),
2103 stoa(maddr)));
2104 break;
2106 case AF_INET6:
2107 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2108 if (setsockopt(iface->fd, IPPROTO_IPV6,
2109 IPV6_MULTICAST_IF,
2110 (char *)&iface->scopeid,
2111 sizeof(iface->scopeid))) {
2113 msyslog(LOG_ERR,
2114 "setsockopt IPV6_MULTICAST_IF failed: %m on socket %d, addr %s, scope %d for multicast address %s",
2115 iface->fd, stoa(&iface->sin),
2116 iface->scopeid, stoa(maddr));
2117 return;
2119 #ifdef IPV6_MULTICAST_LOOP
2121 * Don't send back to itself, but allow failure to set
2123 if (setsockopt(iface->fd, IPPROTO_IPV6,
2124 IPV6_MULTICAST_LOOP,
2125 (char *) &off, sizeof(off))) {
2127 msyslog(LOG_ERR,
2128 "setsockopt IP_MULTICAST_LOOP failed: %m on socket %d, addr %s for multicast address %s",
2129 iface->fd, stoa(&iface->sin),
2130 stoa(maddr));
2132 #endif
2133 DPRINTF(4, ("Added IPv6 multicast interface on socket %d, addr %s, scope %d for multicast address %s\n",
2134 iface->fd, stoa(&iface->sin),
2135 iface->scopeid, stoa(maddr)));
2136 break;
2137 #else
2138 return;
2139 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */
2141 return;
2142 #endif
2146 * Add a multicast address to a given socket
2147 * The socket is in the inter_list all we need to do is enable
2148 * multicasting. It is not this function's job to select the socket
2150 #ifdef MCAST
2151 static isc_boolean_t
2152 socket_multicast_enable(
2153 struct interface * iface,
2154 int lscope,
2155 sockaddr_u * maddr
2158 struct ip_mreq mreq;
2159 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2160 struct ipv6_mreq mreq6;
2161 #endif
2163 if (find_addr_in_list(maddr) != NULL) {
2164 DPRINTF(4, ("socket_multicast_enable(%s): already enabled\n",
2165 stoa(maddr)));
2166 return ISC_TRUE;
2169 switch (AF(maddr)) {
2171 case AF_INET:
2172 memset(&mreq, 0, sizeof(mreq));
2173 mreq.imr_multiaddr = SOCK_ADDR4(maddr);
2174 mreq.imr_interface.s_addr = htonl(INADDR_ANY);
2175 if (setsockopt(iface->fd,
2176 IPPROTO_IP,
2177 IP_ADD_MEMBERSHIP,
2178 (char *)&mreq,
2179 sizeof(mreq))) {
2180 msyslog(LOG_ERR,
2181 "setsockopt IP_ADD_MEMBERSHIP failed: %m on socket %d, addr %s for %x / %x (%s)",
2182 iface->fd, stoa(&iface->sin),
2183 mreq.imr_multiaddr.s_addr,
2184 mreq.imr_interface.s_addr,
2185 stoa(maddr));
2186 return ISC_FALSE;
2188 DPRINTF(4, ("Added IPv4 multicast membership on socket %d, addr %s for %x / %x (%s)\n",
2189 iface->fd, stoa(&iface->sin),
2190 mreq.imr_multiaddr.s_addr,
2191 mreq.imr_interface.s_addr, stoa(maddr)));
2192 break;
2194 case AF_INET6:
2195 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2197 * Enable reception of multicast packets.
2198 * If the address is link-local we can get the
2199 * interface index from the scope id. Don't do this
2200 * for other types of multicast addresses. For now let
2201 * the kernel figure it out.
2203 memset(&mreq6, 0, sizeof(mreq6));
2204 mreq6.ipv6mr_multiaddr = SOCK_ADDR6(maddr);
2205 mreq6.ipv6mr_interface = lscope;
2207 if (setsockopt(iface->fd, IPPROTO_IPV6,
2208 IPV6_JOIN_GROUP, (char *)&mreq6,
2209 sizeof(mreq6))) {
2210 msyslog(LOG_ERR,
2211 "setsockopt IPV6_JOIN_GROUP failed: %m on socket %d, addr %s for interface %d (%s)",
2212 iface->fd, stoa(&iface->sin),
2213 mreq6.ipv6mr_interface, stoa(maddr));
2214 return ISC_FALSE;
2216 DPRINTF(4, ("Added IPv6 multicast group on socket %d, addr %s for interface %d(%s)\n",
2217 iface->fd, stoa(&iface->sin),
2218 mreq6.ipv6mr_interface, stoa(maddr)));
2219 #else
2220 return ISC_FALSE;
2221 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */
2223 iface->flags |= INT_MCASTOPEN;
2224 iface->num_mcast++;
2225 add_addr_to_list(maddr, iface);
2226 return ISC_TRUE;
2230 * Remove a multicast address from a given socket
2231 * The socket is in the inter_list all we need to do is disable
2232 * multicasting. It is not this function's job to select the socket
2234 static isc_boolean_t
2235 socket_multicast_disable(
2236 struct interface * iface,
2237 sockaddr_u * maddr
2240 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2241 struct ipv6_mreq mreq6;
2242 #endif
2243 struct ip_mreq mreq;
2245 memset(&mreq, 0, sizeof(mreq));
2247 if (find_addr_in_list(maddr) == NULL) {
2248 DPRINTF(4, ("socket_multicast_disable(%s): not found\n",
2249 stoa(maddr)));
2250 return ISC_TRUE;
2253 switch (AF(maddr)) {
2255 case AF_INET:
2256 mreq.imr_multiaddr = SOCK_ADDR4(maddr);
2257 mreq.imr_interface = SOCK_ADDR4(&iface->sin);
2258 if (setsockopt(iface->fd, IPPROTO_IP,
2259 IP_DROP_MEMBERSHIP, (char *)&mreq,
2260 sizeof(mreq))) {
2262 msyslog(LOG_ERR,
2263 "setsockopt IP_DROP_MEMBERSHIP failed: %m on socket %d, addr %s for %x / %x (%s)",
2264 iface->fd, stoa(&iface->sin),
2265 SRCADR(maddr), SRCADR(&iface->sin),
2266 stoa(maddr));
2267 return ISC_FALSE;
2269 break;
2270 case AF_INET6:
2271 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2273 * Disable reception of multicast packets
2274 * If the address is link-local we can get the
2275 * interface index from the scope id. Don't do this
2276 * for other types of multicast addresses. For now let
2277 * the kernel figure it out.
2279 mreq6.ipv6mr_multiaddr = SOCK_ADDR6(maddr);
2280 mreq6.ipv6mr_interface = iface->scopeid;
2282 if (setsockopt(iface->fd, IPPROTO_IPV6,
2283 IPV6_LEAVE_GROUP, (char *)&mreq6,
2284 sizeof(mreq6))) {
2286 msyslog(LOG_ERR,
2287 "setsockopt IPV6_LEAVE_GROUP failure: %m on socket %d, addr %s for %d (%s)",
2288 iface->fd, stoa(&iface->sin),
2289 iface->scopeid, stoa(maddr));
2290 return ISC_FALSE;
2292 break;
2293 #else
2294 return ISC_FALSE;
2295 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */
2298 iface->num_mcast--;
2299 if (!iface->num_mcast)
2300 iface->flags &= ~INT_MCASTOPEN;
2302 return ISC_TRUE;
2304 #endif /* MCAST */
2307 * io_setbclient - open the broadcast client sockets
2309 void
2310 io_setbclient(void)
2312 #ifdef OPEN_BCAST_SOCKET
2313 struct interface * interf;
2314 int nif;
2315 isc_boolean_t jstatus;
2316 SOCKET fd;
2318 nif = 0;
2319 set_reuseaddr(1);
2321 for (interf = inter_list;
2322 interf != NULL;
2323 interf = interf->link) {
2325 if (interf->flags & (INT_WILDCARD | INT_LOOPBACK))
2326 continue;
2328 /* use only allowed addresses */
2329 if (interf->ignore_packets)
2330 continue;
2333 /* Need a broadcast-capable interface */
2334 if (!(interf->flags & INT_BROADCAST))
2335 continue;
2337 /* Only IPv4 addresses are valid for broadcast */
2338 NTP_REQUIRE(IS_IPV4(&interf->sin));
2340 /* Do we already have the broadcast address open? */
2341 if (interf->flags & INT_BCASTOPEN) {
2343 * account for already open interfaces to avoid
2344 * misleading warning below
2346 nif++;
2347 continue;
2351 * Try to open the broadcast address
2353 interf->family = AF_INET;
2354 interf->bfd = open_socket(&interf->bcast, 1, 0, interf);
2357 * If we succeeded then we use it otherwise enable
2358 * broadcast on the interface address
2360 if (interf->bfd != INVALID_SOCKET) {
2361 fd = interf->bfd;
2362 jstatus = ISC_TRUE;
2363 } else {
2364 fd = interf->fd;
2365 jstatus = socket_broadcast_enable(interf, fd,
2366 &interf->sin);
2369 /* Enable Broadcast on socket */
2370 if (jstatus) {
2371 nif++;
2372 msyslog(LOG_INFO,
2373 "io_setbclient: Opened broadcast client on interface #%d %s",
2374 interf->ifnum, interf->name);
2375 interf->addr_refid = addr2refid(&interf->sin);
2378 set_reuseaddr(0);
2379 if (nif > 0)
2380 DPRINTF(1, ("io_setbclient: Opened broadcast clients\n"));
2381 else if (!nif)
2382 msyslog(LOG_ERR,
2383 "Unable to listen for broadcasts, no broadcast interfaces available");
2384 #else
2385 msyslog(LOG_ERR,
2386 "io_setbclient: Broadcast Client disabled by build");
2387 #endif /* OPEN_BCAST_SOCKET */
2391 * io_unsetbclient - close the broadcast client sockets
2393 void
2394 io_unsetbclient(void)
2396 struct interface *interf;
2398 for (interf = inter_list;
2399 NULL != interf;
2400 interf = interf->link)
2402 if (interf->flags & INT_WILDCARD)
2403 continue;
2405 if (!(interf->flags & INT_BCASTOPEN))
2406 continue;
2408 socket_broadcast_disable(interf, &interf->sin);
2413 * io_multicast_add() - add multicast group address
2415 void
2416 io_multicast_add(
2417 sockaddr_u *addr
2420 #ifdef MCAST
2421 struct interface *interface;
2422 #ifndef MULTICAST_NONEWSOCKET
2423 struct interface *iface;
2424 #endif
2425 int lscope = 0;
2428 * Check to see if this is a multicast address
2430 if (!addr_ismulticast(addr))
2431 return;
2433 /* If we already have it we can just return */
2434 if (NULL != find_flagged_addr_in_list(addr, INT_MCASTOPEN)) {
2435 msyslog(LOG_INFO,
2436 "Duplicate request found for multicast address %s",
2437 stoa(addr));
2438 return;
2441 #ifndef MULTICAST_NONEWSOCKET
2442 interface = new_interface(NULL);
2445 * Open a new socket for the multicast address
2447 interface->family =
2448 AF(&interface->sin) =
2449 AF(&interface->mask) = AF(addr);
2450 SET_PORT(&interface->sin, NTP_PORT);
2451 SET_ONESMASK(&interface->mask);
2453 switch(AF(addr)) {
2455 case AF_INET:
2456 NSRCADR(&interface->sin) = NSRCADR(addr);
2457 break;
2459 case AF_INET6:
2460 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2461 SET_ADDR6N(&interface->sin, SOCK_ADDR6(addr));
2462 lscope = SCOPE(addr);
2463 SET_SCOPE(&interface->sin, lscope);
2464 #endif
2465 iface = findlocalcastinterface(addr);
2466 if (iface != NULL)
2467 DPRINTF(4, ("Found interface #%d %s, scope %d for address %s\n",
2468 iface->ifnum, iface->name, lscope,
2469 stoa(addr)));
2472 set_reuseaddr(1);
2473 interface->bfd = INVALID_SOCKET;
2474 interface->fd = open_socket(&interface->sin, INT_MULTICAST, 0,
2475 interface);
2477 if (interface->fd != INVALID_SOCKET) {
2478 interface->bfd = INVALID_SOCKET;
2479 interface->ignore_packets = ISC_FALSE;
2480 interface->flags |= INT_MCASTIF;
2482 strncpy(interface->name, "multicast",
2483 sizeof(interface->name));
2484 DPRINT_INTERFACE(2, (interface, "multicast add ", "\n"));
2486 * socket_multicast_enable() will add this address to
2487 * the addresslist
2489 add_interface(interface);
2490 list_if_listening(interface);
2491 } else {
2492 /* bind failed, re-use wildcard interface */
2493 delete_interface(interface);
2495 if (IS_IPV4(addr))
2496 interface = wildipv4;
2497 else if (IS_IPV6(addr))
2498 interface = wildipv6;
2499 else
2500 interface = NULL;
2502 if (interface != NULL) {
2503 /* HACK ! -- stuff in an address */
2504 /* because we don't bind addr? DH */
2505 interface->bcast = *addr;
2506 msyslog(LOG_ERR,
2507 "multicast address %s using wildcard interface #%d %s",
2508 stoa(addr), interface->ifnum,
2509 interface->name);
2510 } else {
2511 msyslog(LOG_ERR,
2512 "No multicast socket available to use for address %s",
2513 stoa(addr));
2514 return;
2517 #else
2519 * For the case where we can't use a separate socket
2521 interface = findlocalcastinterface(addr);
2523 * If we don't have a valid socket, just return
2525 if (NULL == interface) {
2526 msyslog(LOG_ERR,
2527 "Can not add multicast address %s: no multicast interface found",
2528 stoa(addr));
2529 return;
2532 #endif
2533 if (socket_multicast_enable(interface, lscope, addr))
2534 msyslog(LOG_INFO,
2535 "Added Multicast Listener %s on interface #%d %s",
2536 stoa(addr), interface->ifnum, interface->name);
2537 else
2538 msyslog(LOG_ERR, "Failed to add Multicast Listener %s",
2539 stoa(addr));
2540 #else /* MCAST */
2541 msyslog(LOG_ERR,
2542 "Can not add multicast address %s: no multicast support",
2543 stoa(addr));
2544 #endif /* MCAST */
2545 return;
2550 * io_multicast_del() - delete multicast group address
2552 void
2553 io_multicast_del(
2554 sockaddr_u * addr
2557 #ifdef MCAST
2558 struct interface *iface;
2561 * Check to see if this is a multicast address
2563 if (!addr_ismulticast(addr)) {
2564 msyslog(LOG_ERR, "invalid multicast address %s",
2565 stoa(addr));
2566 return;
2570 * Disable reception of multicast packets
2572 while ((iface = find_flagged_addr_in_list(addr, INT_MCASTOPEN))
2573 != NULL)
2574 socket_multicast_disable(iface, addr);
2576 delete_addr_from_list(addr);
2578 #else /* not MCAST */
2579 msyslog(LOG_ERR,
2580 "Can not delete multicast address %s: no multicast support",
2581 stoa(addr));
2582 #endif /* not MCAST */
2587 * init_nonblocking_io() - set up descriptor to be non blocking
2589 static void init_nonblocking_io(
2590 SOCKET fd
2594 * set non-blocking,
2597 #ifdef USE_FIONBIO
2598 /* in vxWorks we use FIONBIO, but the others are defined for old systems, so
2599 * all hell breaks loose if we leave them defined
2601 #undef O_NONBLOCK
2602 #undef FNDELAY
2603 #undef O_NDELAY
2604 #endif
2606 #if defined(O_NONBLOCK) /* POSIX */
2607 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) {
2608 msyslog(LOG_ERR,
2609 "fcntl(O_NONBLOCK) fails on fd #%d: %m", fd);
2610 exit(1);
2612 #elif defined(FNDELAY)
2613 if (fcntl(fd, F_SETFL, FNDELAY) < 0) {
2614 msyslog(LOG_ERR, "fcntl(FNDELAY) fails on fd #%d: %m",
2615 fd);
2616 exit(1);
2618 #elif defined(O_NDELAY) /* generally the same as FNDELAY */
2619 if (fcntl(fd, F_SETFL, O_NDELAY) < 0) {
2620 msyslog(LOG_ERR, "fcntl(O_NDELAY) fails on fd #%d: %m",
2621 fd);
2622 exit(1);
2624 #elif defined(FIONBIO)
2626 int on = 1;
2628 if (ioctl(fd, FIONBIO, &on) < 0) {
2629 msyslog(LOG_ERR,
2630 "ioctl(FIONBIO) fails on fd #%d: %m",
2631 fd);
2632 exit(1);
2635 #elif defined(FIOSNBIO)
2636 if (ioctl(fd, FIOSNBIO, &on) < 0) {
2637 msyslog(LOG_ERR,
2638 "ioctl(FIOSNBIO) fails on fd #%d: %m", fd);
2639 exit(1);
2641 #else
2642 # include "Bletch: Need non-blocking I/O!"
2643 #endif
2647 * open_socket - open a socket, returning the file descriptor
2650 static SOCKET
2651 open_socket(
2652 sockaddr_u * addr,
2653 int bcast,
2654 int turn_off_reuse,
2655 struct interface * interf
2658 SOCKET fd;
2659 int errval;
2660 char scopetext[16];
2662 * int is OK for REUSEADR per
2663 * http://www.kohala.com/start/mcast.api.txt
2665 int on = 1;
2666 int off = 0;
2668 if (IS_IPV6(addr) && !ipv6_works)
2669 return INVALID_SOCKET;
2671 /* create a datagram (UDP) socket */
2672 fd = socket(AF(addr), SOCK_DGRAM, 0);
2673 if (INVALID_SOCKET == fd) {
2674 #ifndef SYS_WINNT
2675 errval = errno;
2676 #else
2677 errval = WSAGetLastError();
2678 #endif
2679 msyslog(LOG_ERR,
2680 "socket(AF_INET%s, SOCK_DGRAM, 0) failed on address %s: %m",
2681 IS_IPV6(addr) ? "6" : "", stoa(addr));
2683 if (errval == EPROTONOSUPPORT ||
2684 errval == EAFNOSUPPORT ||
2685 errval == EPFNOSUPPORT)
2686 return (INVALID_SOCKET);
2688 errno = errval;
2689 msyslog(LOG_ERR,
2690 "unexpected socket() error %m code %d (not EPROTONOSUPPORT nor EAFNOSUPPORT nor EPFNOSUPPORT) - exiting",
2691 errno);
2692 exit(1);
2695 #ifdef SYS_WINNT
2696 connection_reset_fix(fd, addr);
2697 #endif
2699 * Fixup the file descriptor for some systems
2700 * See bug #530 for details of the issue.
2702 fd = move_fd(fd);
2705 * set SO_REUSEADDR since we will be binding the same port
2706 * number on each interface according to turn_off_reuse.
2707 * This is undesirable on Windows versions starting with
2708 * Windows XP (numeric version 5.1).
2710 #ifdef SYS_WINNT
2711 if (isc_win32os_versioncheck(5, 1, 0, 0) < 0) /* before 5.1 */
2712 #endif
2713 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
2714 (char *)((turn_off_reuse)
2715 ? &off
2716 : &on),
2717 sizeof(on))) {
2719 msyslog(LOG_ERR,
2720 "setsockopt SO_REUSEADDR %s fails for address %s: %m",
2721 (turn_off_reuse)
2722 ? "off"
2723 : "on",
2724 stoa(addr));
2725 closesocket(fd);
2726 return INVALID_SOCKET;
2728 #ifdef SO_EXCLUSIVEADDRUSE
2730 * setting SO_EXCLUSIVEADDRUSE on the wildcard we open
2731 * first will cause more specific binds to fail.
2733 if (!(interf->flags & INT_WILDCARD))
2734 set_excladdruse(fd);
2735 #endif
2738 * IPv4 specific options go here
2740 if (IS_IPV4(addr)) {
2741 #if defined(HAVE_IPTOS_SUPPORT)
2742 if (setsockopt(fd, IPPROTO_IP, IP_TOS, (char *)&qos,
2743 sizeof(qos)))
2744 msyslog(LOG_ERR,
2745 "setsockopt IP_TOS (%02x) fails on address %s: %m",
2746 qos, stoa(addr));
2747 #endif /* HAVE_IPTOS_SUPPORT */
2748 if (bcast)
2749 socket_broadcast_enable(interf, fd, addr);
2753 * IPv6 specific options go here
2755 if (IS_IPV6(addr)) {
2756 #if defined(IPV6_V6ONLY)
2757 if (isc_net_probe_ipv6only() == ISC_R_SUCCESS
2758 && setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY,
2759 (char*)&on, sizeof(on)))
2760 msyslog(LOG_ERR,
2761 "setsockopt IPV6_V6ONLY on fails on address %s: %m",
2762 stoa(addr));
2763 #endif /* IPV6_V6ONLY */
2764 #if defined(IPV6_BINDV6ONLY)
2765 if (setsockopt(fd, IPPROTO_IPV6, IPV6_BINDV6ONLY,
2766 (char*)&on, sizeof(on)))
2767 msyslog(LOG_ERR,
2768 "setsockopt IPV6_BINDV6ONLY on fails on address %s: %m",
2769 stoa(addr));
2770 #endif /* IPV6_BINDV6ONLY */
2773 #ifdef OS_NEEDS_REUSEADDR_FOR_IFADDRBIND
2775 * some OSes don't allow binding to more specific
2776 * addresses if a wildcard address already bound
2777 * to the port and SO_REUSEADDR is not set
2779 if (!is_wildcard_addr(addr))
2780 set_wildcard_reuse(AF(addr), 1);
2781 #endif
2784 * bind the local address.
2786 errval = bind(fd, &addr->sa, SOCKLEN(addr));
2788 #ifdef OS_NEEDS_REUSEADDR_FOR_IFADDRBIND
2789 if (!is_wildcard_addr(addr))
2790 set_wildcard_reuse(AF(addr), 0);
2791 #endif
2793 if (errval < 0) {
2795 * Don't log this under all conditions
2797 if (turn_off_reuse == 0
2798 #ifdef DEBUG
2799 || debug > 1
2800 #endif
2802 if (SCOPE(addr))
2803 snprintf(scopetext, sizeof(scopetext),
2804 "%%%d", SCOPE(addr));
2805 else
2806 scopetext[0] = 0;
2808 msyslog(LOG_ERR,
2809 "bind(%d) AF_INET%s %s%s#%d%s flags 0x%x failed: %m",
2810 fd, IS_IPV6(addr) ? "6" : "",
2811 stoa(addr), scopetext, SRCPORT(addr),
2812 IS_MCAST(addr) ? " (multicast)" : "",
2813 interf->flags);
2816 closesocket(fd);
2818 return INVALID_SOCKET;
2821 #ifdef HAVE_TIMESTAMP
2823 if (setsockopt(fd, SOL_SOCKET, SO_TIMESTAMP,
2824 (char*)&on, sizeof(on)))
2825 msyslog(LOG_DEBUG,
2826 "setsockopt SO_TIMESTAMP on fails on address %s: %m",
2827 stoa(addr));
2828 else
2829 DPRINTF(4, ("setsockopt SO_TIMESTAMP enabled on fd %d address %s\n",
2830 fd, stoa(addr)));
2832 #endif
2833 DPRINTF(4, ("bind(%d) AF_INET%s, addr %s%%%d#%d, flags 0x%x\n",
2834 fd, IS_IPV6(addr) ? "6" : "", stoa(addr),
2835 SCOPE(addr), SRCPORT(addr), interf->flags));
2837 init_nonblocking_io(fd);
2839 #ifdef HAVE_SIGNALED_IO
2840 init_socket_sig(fd);
2841 #endif /* not HAVE_SIGNALED_IO */
2843 add_fd_to_list(fd, FD_TYPE_SOCKET);
2845 #if !defined(SYS_WINNT) && !defined(VMS)
2846 DPRINTF(4, ("flags for fd %d: 0x%x\n", fd,
2847 fcntl(fd, F_GETFL, 0)));
2848 #endif /* SYS_WINNT || VMS */
2850 #if defined (HAVE_IO_COMPLETION_PORT)
2852 * Add the socket to the completion port
2854 if (io_completion_port_add_socket(fd, interf)) {
2855 msyslog(LOG_ERR, "unable to set up io completion port - EXITING");
2856 exit(1);
2858 #endif
2859 return fd;
2862 /* XXX ELIMINATE sendpkt similar in ntpq.c, ntpdc.c, ntp_io.c, ntptrace.c */
2864 * sendpkt - send a packet to the specified destination. Maintain a
2865 * send error cache so that only the first consecutive error for a
2866 * destination is logged.
2868 void
2869 sendpkt(
2870 sockaddr_u *dest,
2871 struct interface *inter,
2872 int ttl,
2873 struct pkt *pkt,
2874 int len
2877 int cc;
2879 if (NULL == inter) {
2881 * unbound peer - drop request and wait for better
2882 * network conditions
2884 DPRINTF(2, ("%ssendpkt(dst=%s, ttl=%d, len=%d): no interface - IGNORED\n",
2885 (ttl > 0) ? "\tMCAST\t***** " : "",
2886 stoa(dest), ttl, len));
2887 return;
2890 DPRINTF(2, ("%ssendpkt(%d, dst=%s, src=%s, ttl=%d, len=%d)\n",
2891 (ttl > 0) ? "\tMCAST\t***** " : "",
2892 inter->fd, stoa(dest), stoa(&inter->sin),
2893 ttl, len));
2895 #ifdef MCAST
2897 * for the moment we use the bcast option to set multicast ttl
2899 if (ttl > 0 && ttl != inter->last_ttl) {
2901 * set the multicast ttl for outgoing packets
2903 int rtc;
2904 u_char cttl;
2905 u_int uttl;
2907 switch (AF(&inter->sin)) {
2909 case AF_INET :
2910 cttl = (u_char)ttl;
2911 rtc = setsockopt(inter->fd, IPPROTO_IP,
2912 IP_MULTICAST_TTL,
2913 (void *)&cttl, sizeof(cttl));
2914 break;
2916 #ifdef INCLUDE_IPV6_SUPPORT
2917 case AF_INET6 :
2918 uttl = (u_int)ttl;
2919 rtc = setsockopt(inter->fd, IPPROTO_IPV6,
2920 IPV6_MULTICAST_HOPS,
2921 (void *)&uttl, sizeof(uttl));
2922 break;
2923 #endif /* INCLUDE_IPV6_SUPPORT */
2925 default: /* just NOP if not supported */
2926 DPRINTF(1, ("sendpkt unknown AF %d",
2927 AF(&inter->sin)));
2928 rtc = 0;
2931 if (!rtc)
2932 inter->last_ttl = ttl;
2933 else
2934 msyslog(LOG_ERR,
2935 "setsockopt IP_MULTICAST_TTL/IPV6_MULTICAST_HOPS fails on address %s: %m",
2936 stoa(&inter->sin));
2939 #endif /* MCAST */
2941 #if defined(HAVE_IO_COMPLETION_PORT)
2942 cc = io_completion_port_sendto(inter, pkt, len, dest);
2943 if (cc != ERROR_SUCCESS) {
2944 #else
2945 #ifdef SIM
2946 cc = simulate_server(dest, inter, pkt);
2947 #else /* SIM */
2948 cc = sendto(inter->fd, (char *)pkt, (unsigned int)len, 0,
2949 (struct sockaddr *)dest, SOCKLEN(dest));
2950 #endif /* SIM */
2951 if (cc == -1) {
2952 #endif
2953 inter->notsent++;
2954 packets_notsent++;
2955 } else {
2956 inter->sent++;
2957 packets_sent++;
2962 #if !defined(HAVE_IO_COMPLETION_PORT)
2964 * fdbits - generate ascii representation of fd_set (FAU debug support)
2965 * HFDF format - highest fd first.
2967 static char *
2968 fdbits(
2969 int count,
2970 fd_set *set
2973 static char buffer[256];
2974 char * buf = buffer;
2976 count = min(count, 255);
2978 while (count >= 0) {
2979 *buf++ = FD_ISSET(count, set) ? '#' : '-';
2980 count--;
2982 *buf = '\0';
2984 return buffer;
2988 * Routine to read the refclock packets for a specific interface
2989 * Return the number of bytes read. That way we know if we should
2990 * read it again or go on to the next one if no bytes returned
2992 static inline int
2993 read_refclock_packet(SOCKET fd, struct refclockio *rp, l_fp ts)
2995 int i;
2996 int buflen;
2997 register struct recvbuf *rb;
2999 rb = get_free_recv_buffer();
3001 if (NULL == rb) {
3003 * No buffer space available - just drop the packet
3005 char buf[RX_BUFF_SIZE];
3007 buflen = read(fd, buf, sizeof buf);
3008 packets_dropped++;
3009 return (buflen);
3012 i = (rp->datalen == 0
3013 || rp->datalen > sizeof(rb->recv_space))
3014 ? sizeof(rb->recv_space)
3015 : rp->datalen;
3016 buflen = read(fd, (char *)&rb->recv_space, (unsigned)i);
3018 if (buflen < 0) {
3019 if (errno != EINTR && errno != EAGAIN)
3020 msyslog(LOG_ERR, "clock read fd %d: %m", fd);
3021 freerecvbuf(rb);
3022 return (buflen);
3026 * Got one. Mark how and when it got here,
3027 * put it on the full list and do bookkeeping.
3029 rb->recv_length = buflen;
3030 rb->recv_srcclock = rp->srcclock;
3031 rb->dstadr = 0;
3032 rb->fd = fd;
3033 rb->recv_time = ts;
3034 rb->receiver = rp->clock_recv;
3036 if (rp->io_input) {
3038 * have direct input routine for refclocks
3040 if (rp->io_input(rb) == 0) {
3042 * data was consumed - nothing to pass up
3043 * into block input machine
3045 freerecvbuf(rb);
3046 return (buflen);
3050 add_full_recv_buffer(rb);
3052 rp->recvcount++;
3053 packets_received++;
3054 return (buflen);
3058 #ifdef HAVE_TIMESTAMP
3060 * extract timestamps from control message buffer
3062 static l_fp
3063 fetch_timestamp(
3064 struct recvbuf * rb,
3065 struct msghdr * msghdr,
3066 l_fp ts
3069 #ifdef USE_TIMESTAMP_CMSG
3070 struct cmsghdr *cmsghdr;
3072 cmsghdr = CMSG_FIRSTHDR(msghdr);
3073 while (cmsghdr != NULL) {
3074 switch (cmsghdr->cmsg_type)
3076 case SCM_TIMESTAMP:
3078 struct timeval *tvp;
3079 double dtemp;
3080 l_fp nts;
3082 tvp = (struct timeval *)CMSG_DATA(cmsghdr);
3083 DPRINTF(4, ("fetch_timestamp: system network time stamp: %lld.%06ld\n",
3084 (long long)tvp->tv_sec, tvp->tv_usec));
3085 nts.l_i = tvp->tv_sec + JAN_1970;
3086 dtemp = (tvp->tv_usec
3087 + (ntp_random() * 2. / FRAC)) / 1e6;
3088 nts.l_uf = (u_int32)(dtemp * FRAC);
3089 #ifdef DEBUG_TIMING
3091 l_fp dts;
3093 dts = ts;
3094 L_SUB(&dts, &nts);
3095 collect_timing(rb,
3096 "input processing delay",
3097 1, &dts);
3098 DPRINTF(4, ("fetch_timestamp: timestamp delta: %s (incl. prec fuzz)\n",
3099 lfptoa(&dts, 9)));
3101 #endif
3102 ts = nts; /* network time stamp */
3103 break;
3105 default:
3106 DPRINTF(4, ("fetch_timestamp: skipping control message 0x%x\n",
3107 cmsghdr->cmsg_type));
3109 cmsghdr = CMSG_NXTHDR(msghdr, cmsghdr);
3111 #endif
3112 return ts;
3114 #endif
3118 * Routine to read the network NTP packets for a specific interface
3119 * Return the number of bytes read. That way we know if we should
3120 * read it again or go on to the next one if no bytes returned
3122 static inline int
3123 read_network_packet(
3124 SOCKET fd,
3125 struct interface * itf,
3126 l_fp ts
3129 GETSOCKNAME_SOCKLEN_TYPE fromlen;
3130 int buflen;
3131 register struct recvbuf *rb;
3132 #ifdef HAVE_TIMESTAMP
3133 struct msghdr msghdr;
3134 struct iovec iovec;
3135 char control[TIMESTAMP_CTLMSGBUF_SIZE];
3136 #endif
3139 * Get a buffer and read the frame. If we
3140 * haven't got a buffer, or this is received
3141 * on a disallowed socket, just dump the
3142 * packet.
3145 rb = get_free_recv_buffer();
3146 if (NULL == rb || itf->ignore_packets) {
3147 char buf[RX_BUFF_SIZE];
3148 sockaddr_u from;
3150 if (rb != NULL)
3151 freerecvbuf(rb);
3153 fromlen = sizeof(from);
3154 buflen = recvfrom(fd, buf, sizeof(buf), 0,
3155 &from.sa, &fromlen);
3156 DPRINTF(4, ("%s on (%lu) fd=%d from %s\n",
3157 (itf->ignore_packets)
3158 ? "ignore"
3159 : "drop",
3160 free_recvbuffs(), fd, stoa(&from)));
3161 if (itf->ignore_packets)
3162 packets_ignored++;
3163 else
3164 packets_dropped++;
3165 return (buflen);
3168 fromlen = sizeof(rb->recv_srcadr);
3170 #ifndef HAVE_TIMESTAMP
3171 rb->recv_length = recvfrom(fd, (char *)&rb->recv_space,
3172 sizeof(rb->recv_space), 0,
3173 &rb->recv_srcadr.sa, &fromlen);
3174 #else
3175 iovec.iov_base = &rb->recv_space;
3176 iovec.iov_len = sizeof(rb->recv_space);
3177 msghdr.msg_name = &rb->recv_srcadr;
3178 msghdr.msg_namelen = fromlen;
3179 msghdr.msg_iov = &iovec;
3180 msghdr.msg_iovlen = 1;
3181 msghdr.msg_control = (void *)&control;
3182 msghdr.msg_controllen = sizeof(control);
3183 msghdr.msg_flags = 0;
3184 rb->recv_length = recvmsg(fd, &msghdr, 0);
3185 #endif
3187 buflen = rb->recv_length;
3189 if (buflen == 0 || (buflen == -1 &&
3190 (EWOULDBLOCK == errno
3191 #ifdef EAGAIN
3192 || EAGAIN == errno
3193 #endif
3194 ))) {
3195 freerecvbuf(rb);
3196 return (buflen);
3197 } else if (buflen < 0) {
3198 msyslog(LOG_ERR, "recvfrom(%s) fd=%d: %m",
3199 stoa(&rb->recv_srcadr), fd);
3200 DPRINTF(5, ("read_network_packet: fd=%d dropped (bad recvfrom)\n",
3201 fd));
3202 freerecvbuf(rb);
3203 return (buflen);
3206 DPRINTF(3, ("read_network_packet: fd=%d length %d from %s\n",
3207 fd, buflen, stoa(&rb->recv_srcadr)));
3210 * Got one. Mark how and when it got here,
3211 * put it on the full list and do bookkeeping.
3213 rb->dstadr = itf;
3214 rb->fd = fd;
3215 #ifdef HAVE_TIMESTAMP
3216 /* pick up a network time stamp if possible */
3217 ts = fetch_timestamp(rb, &msghdr, ts);
3218 #endif
3219 rb->recv_time = ts;
3220 rb->receiver = receive;
3222 add_full_recv_buffer(rb);
3224 itf->received++;
3225 packets_received++;
3226 return (buflen);
3231 * input_handler - receive packets asynchronously
3233 void
3234 input_handler(
3235 l_fp *cts
3238 int buflen;
3239 int n;
3240 int doing;
3241 SOCKET fd;
3242 struct timeval tvzero;
3243 l_fp ts; /* Timestamp at BOselect() gob */
3244 #ifdef DEBUG_TIMING
3245 l_fp ts_e; /* Timestamp at EOselect() gob */
3246 #endif
3247 fd_set fds;
3248 int select_count = 0;
3249 struct interface *interface;
3250 #if defined(HAS_ROUTING_SOCKET)
3251 struct asyncio_reader *asyncio_reader;
3252 #endif
3254 handler_calls++;
3257 * If we have something to do, freeze a timestamp.
3258 * See below for the other cases (nothing left to do or error)
3260 ts = *cts;
3263 * Do a poll to see who has data
3266 fds = activefds;
3267 tvzero.tv_sec = tvzero.tv_usec = 0;
3269 n = select(maxactivefd + 1, &fds, (fd_set *)0, (fd_set *)0,
3270 &tvzero);
3273 * If there are no packets waiting just return
3275 if (n < 0) {
3276 int err = errno;
3278 * extended FAU debugging output
3280 if (err != EINTR)
3281 msyslog(LOG_ERR,
3282 "select(%d, %s, 0L, 0L, &0.0) error: %m",
3283 maxactivefd + 1,
3284 fdbits(maxactivefd, &activefds));
3285 if (err == EBADF) {
3286 int j, b;
3287 fds = activefds;
3288 for (j = 0; j <= maxactivefd; j++)
3289 if ((FD_ISSET(j, &fds)
3290 && (read(j, &b, 0) == -1)))
3291 msyslog(LOG_ERR,
3292 "Bad file descriptor %d",
3295 return;
3297 else if (n == 0)
3298 return;
3300 ++handler_pkts;
3302 #ifdef REFCLOCK
3304 * Check out the reference clocks first, if any
3307 if (refio != NULL) {
3308 register struct refclockio *rp;
3310 for (rp = refio; rp != NULL; rp = rp->next) {
3311 fd = rp->fd;
3313 if (FD_ISSET(fd, &fds))
3314 do {
3315 ++select_count;
3316 buflen = read_refclock_packet(
3317 fd, rp, ts);
3318 } while (buflen > 0);
3321 #endif /* REFCLOCK */
3324 * Loop through the interfaces looking for data to read.
3326 for (interface = inter_list;
3327 interface != NULL;
3328 interface = interface->link) {
3330 for (doing = 0; (doing < 2); doing++) {
3331 if (!doing)
3332 fd = interface->fd;
3333 else {
3334 if (!(interface->flags & INT_BCASTOPEN))
3335 break;
3336 fd = interface->bfd;
3338 if (fd < 0)
3339 continue;
3340 if (FD_ISSET(fd, &fds))
3341 do {
3342 ++select_count;
3343 buflen = read_network_packet(
3344 fd, interface,
3345 ts);
3346 } while (buflen > 0);
3347 /* Check more interfaces */
3351 #ifdef HAS_ROUTING_SOCKET
3353 * scan list of asyncio readers - currently only used for routing sockets
3355 asyncio_reader = asyncio_reader_list;
3357 while (asyncio_reader != NULL) {
3358 if (FD_ISSET(asyncio_reader->fd, &fds)) {
3359 ++select_count;
3360 (asyncio_reader->receiver)(asyncio_reader);
3362 asyncio_reader = asyncio_reader->link;
3364 #endif /* HAS_ROUTING_SOCKET */
3367 * Done everything from that select.
3371 * If nothing to do, just return.
3372 * If an error occurred, complain and return.
3374 if (select_count == 0) { /* We really had nothing to do */
3375 #ifdef DEBUG
3376 if (debug)
3377 msyslog(LOG_DEBUG, "input_handler: select() returned 0");
3378 #endif
3379 return;
3381 /* We've done our work */
3382 #ifdef DEBUG_TIMING
3383 get_systime(&ts_e);
3385 * (ts_e - ts) is the amount of time we spent
3386 * processing this gob of file descriptors. Log
3387 * it.
3389 L_SUB(&ts_e, &ts);
3390 collect_timing(NULL, "input handler", 1, &ts_e);
3391 if (debug > 3)
3392 msyslog(LOG_DEBUG,
3393 "input_handler: Processed a gob of fd's in %s msec",
3394 lfptoms(&ts_e, 6));
3395 #endif
3396 /* just bail. */
3397 return;
3399 #endif
3402 * findinterface - find local interface corresponding to address
3404 struct interface *
3405 findinterface(
3406 sockaddr_u *addr
3409 struct interface *iface;
3411 iface = findlocalinterface(addr, INT_WILDCARD, 0);
3413 if (NULL == iface) {
3414 DPRINTF(4, ("Found no interface for address %s - returning wildcard\n",
3415 stoa(addr)));
3417 iface = ANY_INTERFACE_CHOOSE(addr);
3418 } else
3419 DPRINTF(4, ("Found interface #%d %s for address %s\n",
3420 iface->ifnum, iface->name, stoa(addr)));
3422 return iface;
3426 * findlocalinterface - find local interface corresponding to addr,
3427 * which does not have any of flags set. If bast is nonzero, addr is
3428 * a broadcast address.
3430 * This code attempts to find the local sending address for an outgoing
3431 * address by connecting a new socket to destinationaddress:NTP_PORT
3432 * and reading the sockname of the resulting connect.
3433 * the complicated sequence simulates the routing table lookup
3434 * for to first hop without duplicating any of the routing logic into
3435 * ntpd. preferably we would have used an API call - but its not there -
3436 * so this is the best we can do here short of duplicating to entire routing
3437 * logic in ntpd which would be a silly and really unportable thing to do.
3440 static struct interface *
3441 findlocalinterface(
3442 sockaddr_u * addr,
3443 int flags,
3444 int bcast
3447 GETSOCKNAME_SOCKLEN_TYPE sockaddrlen;
3448 struct interface * iface;
3449 sockaddr_u saddr;
3450 SOCKET s;
3451 int rtn;
3452 int on;
3454 DPRINTF(4, ("Finding interface for addr %s in list of addresses\n",
3455 stoa(addr)));
3457 s = socket(AF(addr), SOCK_DGRAM, 0);
3458 if (INVALID_SOCKET == s)
3459 return NULL;
3462 * If we are looking for broadcast interface we need to set this
3463 * socket to allow broadcast
3465 if (bcast) {
3466 on = 1;
3467 setsockopt(s, SOL_SOCKET, SO_BROADCAST,
3468 (char *)&on, sizeof(on));
3471 rtn = connect(s, &addr->sa, SOCKLEN(addr));
3472 if (SOCKET_ERROR == rtn) {
3473 closesocket(s);
3474 return NULL;
3477 sockaddrlen = sizeof(saddr);
3478 rtn = getsockname(s, &saddr.sa, &sockaddrlen);
3479 closesocket(s);
3481 if (SOCKET_ERROR == rtn)
3482 return NULL;
3484 DPRINTF(4, ("findlocalinterface: kernel maps %s to %s\n",
3485 stoa(addr), stoa(&saddr)));
3487 iface = getinterface(&saddr, flags);
3490 * if we didn't find an exact match on saddr check for an
3491 * interface on the same subnet as saddr. This handles the
3492 * case of the address suggested by the kernel being
3493 * excluded by the user's -I and -L options to ntpd, when
3494 * another address is enabled on the same subnet.
3495 * See http://bugs.ntp.org/1184 for more detail.
3497 if (NULL == iface || iface->ignore_packets)
3498 iface = getsamenetinterface(&saddr, flags);
3500 /* Don't use an interface which will ignore replies */
3501 if (iface != NULL && iface->ignore_packets)
3502 iface = NULL;
3504 return iface;
3509 * fetch an interface structure the matches the
3510 * address and has the given flags NOT set
3512 static struct interface *
3513 getinterface(
3514 sockaddr_u * addr,
3515 int flags
3518 struct interface *iface;
3520 iface = find_addr_in_list(addr);
3522 if (iface != NULL && (iface->flags & flags))
3523 iface = NULL;
3525 return iface;
3530 * fetch an interface structure with a local address on the same subnet
3531 * as addr which has the given flags NOT set
3533 static struct interface *
3534 getsamenetinterface(
3535 sockaddr_u * addr,
3536 int flags
3539 struct interface *iface;
3541 iface = find_samenet_addr_in_list(addr);
3543 if (iface != NULL && (iface->flags & flags))
3544 iface = NULL;
3546 return iface;
3551 * findlocalcastinterface - find local *cast interface for addr
3553 static struct interface *
3554 findlocalcastinterface(
3555 sockaddr_u * addr
3558 struct interface * iface;
3559 struct interface * nif;
3560 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
3561 isc_boolean_t want_linklocal;
3562 #endif
3564 NTP_REQUIRE(addr_ismulticast(addr));
3567 * see how kernel maps the mcast address
3569 nif = findlocalinterface(addr, 0, 0);
3571 if (nif != NULL && !nif->ignore_packets) {
3572 DPRINTF(2, ("findlocalcastinterface: kernel recommends interface #%d %s for %s\n",
3573 nif->ifnum, nif->name, stoa(addr)));
3574 return nif;
3577 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
3578 want_linklocal = (IN6_IS_ADDR_MC_LINKLOCAL(PSOCK_ADDR6(addr))
3579 || IN6_IS_ADDR_MC_SITELOCAL(PSOCK_ADDR6(addr)));
3580 #endif
3582 for (iface = inter_list;
3583 iface != NULL;
3584 iface = iface->link)
3586 /* use only allowed addresses */
3587 if (iface->ignore_packets)
3588 continue;
3590 /* Skip the loopback and wildcard addresses */
3591 if (iface->flags & (INT_LOOPBACK | INT_WILDCARD))
3592 continue;
3594 /* Skip if different family */
3595 if (AF(&iface->sin) != AF(addr))
3596 continue;
3598 /* Is it multicast capable? */
3599 if (!(iface->flags & INT_MULTICAST))
3600 continue;
3602 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
3603 if (want_linklocal && IS_IPV6(&iface->sin) &&
3604 IN6_IS_ADDR_LINKLOCAL(PSOCK_ADDR6(&iface->sin))) {
3605 nif = iface;
3606 break;
3608 /* If we want a linklocal address, skip */
3609 if (want_linklocal)
3610 continue;
3611 #endif
3612 nif = iface;
3613 break;
3614 } /* for loop over interfaces */
3616 if (nif != NULL)
3617 DPRINTF(3, ("findlocalcastinterface: found interface #%d %s for %s\n",
3618 nif->ifnum, nif->name, stoa(addr)));
3619 else
3620 DPRINTF(3, ("findlocalcastinterface: no interface found for %s\n",
3621 stoa(addr)));
3622 return nif;
3627 * findbcastinter - find broadcast interface corresponding to address
3629 struct interface *
3630 findbcastinter(
3631 sockaddr_u *addr
3634 #if !defined(MPE) && (defined(SIOCGIFCONF) || defined(SYS_WINNT))
3635 struct interface *iface;
3638 DPRINTF(4, ("Finding broadcast/multicast interface for addr %s in list of addresses\n",
3639 stoa(addr)));
3641 iface = findlocalinterface(addr, INT_LOOPBACK | INT_WILDCARD,
3642 1);
3643 if (iface != NULL) {
3644 DPRINTF(4, ("Easily found bcast-/mcast- interface index #%d %s\n",
3645 iface->ifnum, iface->name));
3646 return iface;
3650 * plan B - try to find something reasonable in our lists in
3651 * case kernel lookup doesn't help
3653 for (iface = inter_list;
3654 iface != NULL;
3655 iface = iface->link)
3657 if (iface->flags & INT_WILDCARD)
3658 continue;
3660 /* Don't bother with ignored interfaces */
3661 if (iface->ignore_packets)
3662 continue;
3665 * First look if this is the correct family
3667 if(AF(&iface->sin) != AF(addr))
3668 continue;
3670 /* Skip the loopback addresses */
3671 if (iface->flags & INT_LOOPBACK)
3672 continue;
3675 * If we are looking to match a multicast address and
3676 * this interface is one...
3678 if (addr_ismulticast(addr)
3679 && (iface->flags & INT_MULTICAST)) {
3680 #ifdef INCLUDE_IPV6_SUPPORT
3682 * ...it is the winner unless we're looking for
3683 * an interface to use for link-local multicast
3684 * and its address is not link-local.
3686 if (IS_IPV6(addr)
3687 && IN6_IS_ADDR_MC_LINKLOCAL(PSOCK_ADDR6(addr))
3688 && !IN6_IS_ADDR_LINKLOCAL(PSOCK_ADDR6(&iface->sin)))
3689 continue;
3690 #endif
3691 break;
3695 * We match only those interfaces marked as
3696 * broadcastable and either the explicit broadcast
3697 * address or the network portion of the IP address.
3698 * Sloppy.
3700 if (IS_IPV4(addr)) {
3701 if (SOCK_EQ(&iface->bcast, addr))
3702 break;
3704 if ((NSRCADR(&iface->sin) & NSRCADR(&iface->mask))
3705 == (NSRCADR(addr) & NSRCADR(&iface->mask)))
3706 break;
3708 #ifdef INCLUDE_IPV6_SUPPORT
3709 else if(IS_IPV6(addr)) {
3710 if (SOCK_EQ(&iface->bcast, addr))
3711 break;
3713 if (SOCK_EQ(netof(&iface->sin), netof(addr)))
3714 break;
3716 #endif
3718 #endif /* SIOCGIFCONF */
3719 if (NULL == iface) {
3720 DPRINTF(4, ("No bcast interface found for %s\n",
3721 stoa(addr)));
3722 iface = ANY_INTERFACE_CHOOSE(addr);
3723 } else
3724 DPRINTF(4, ("Found bcast-/mcast- interface index #%d %s\n",
3725 iface->ifnum, iface->name));
3726 return iface;
3731 * io_clr_stats - clear I/O module statistics
3733 void
3734 io_clr_stats(void)
3736 packets_dropped = 0;
3737 packets_ignored = 0;
3738 packets_received = 0;
3739 packets_sent = 0;
3740 packets_notsent = 0;
3742 handler_calls = 0;
3743 handler_pkts = 0;
3744 io_timereset = current_time;
3748 #ifdef REFCLOCK
3750 * io_addclock - add a reference clock to the list and arrange that we
3751 * get SIGIO interrupts from it.
3754 io_addclock(
3755 struct refclockio *rio
3758 BLOCKIO();
3761 * Stuff the I/O structure in the list and mark the descriptor
3762 * in use. There is a harmless (I hope) race condition here.
3764 rio->next = refio;
3766 # ifdef HAVE_SIGNALED_IO
3767 if (init_clock_sig(rio)) {
3768 UNBLOCKIO();
3769 return 0;
3771 # elif defined(HAVE_IO_COMPLETION_PORT)
3772 if (io_completion_port_add_clock_io(rio)) {
3773 UNBLOCKIO();
3774 return 0;
3776 # endif
3779 * enqueue
3781 refio = rio;
3784 * register fd
3786 add_fd_to_list(rio->fd, FD_TYPE_FILE);
3788 UNBLOCKIO();
3789 return 1;
3793 * io_closeclock - close the clock in the I/O structure given
3795 void
3796 io_closeclock(
3797 struct refclockio *rio
3800 register struct refclockio *rp;
3802 BLOCKIO();
3805 * Remove structure from the list
3807 if (refio == rio)
3808 refio = rio->next;
3809 else {
3810 for (rp = refio; rp != NULL; rp = rp->next)
3811 if (rp->next == rio) {
3812 rp->next = rio->next;
3813 break;
3816 if (NULL == rp) {
3817 UNBLOCKIO();
3818 return;
3823 * Close the descriptor.
3825 close_and_delete_fd_from_list(rio->fd);
3826 UNBLOCKIO();
3828 #endif /* REFCLOCK */
3831 * On NT a SOCKET is an unsigned int so we cannot possibly keep it in
3832 * an array. So we use one of the ISC_LIST functions to hold the
3833 * socket value and use that when we want to enumerate it.
3835 * This routine is called by the forked intres child process to close
3836 * all open sockets. On Windows there's no need as intres runs in
3837 * the same process as a thread.
3839 #ifndef SYS_WINNT
3840 void
3841 kill_asyncio(int startfd)
3843 BLOCKIO();
3846 * In the child process we do not maintain activefds and
3847 * maxactivefd. Zeroing maxactivefd disables code which
3848 * maintains it in close_and_delete_fd_from_list().
3850 maxactivefd = 0;
3852 while (fd_list != NULL)
3853 close_and_delete_fd_from_list(fd_list->fd);
3855 UNBLOCKIO();
3857 #endif /* !SYS_WINNT */
3860 * Add and delete functions for the list of open sockets
3862 static void
3863 add_fd_to_list(
3864 SOCKET fd,
3865 enum desc_type type
3868 vsock_t *lsock = emalloc(sizeof(*lsock));
3870 lsock->fd = fd;
3871 lsock->type = type;
3873 LINK_SLIST(fd_list, lsock, link);
3875 * I/O Completion Ports don't care about the select and FD_SET
3877 #ifndef HAVE_IO_COMPLETION_PORT
3878 if (fd < 0 || fd >= FD_SETSIZE) {
3879 msyslog(LOG_ERR,
3880 "Too many sockets in use, FD_SETSIZE %d exceeded",
3881 FD_SETSIZE);
3882 exit(1);
3885 * keep activefds in sync
3887 maxactivefd = max(fd, maxactivefd);
3889 FD_SET(fd, &activefds);
3890 #endif
3893 static void
3894 close_and_delete_fd_from_list(
3895 SOCKET fd
3898 vsock_t *lsock;
3900 UNLINK_EXPR_SLIST(lsock, fd_list, fd ==
3901 UNLINK_EXPR_SLIST_CURRENT()->fd, link, vsock_t);
3903 if (lsock != NULL) {
3904 switch (lsock->type) {
3905 case FD_TYPE_SOCKET:
3906 closesocket(lsock->fd);
3907 break;
3909 case FD_TYPE_FILE:
3910 close(lsock->fd);
3911 break;
3913 default:
3914 msyslog(LOG_ERR,
3915 "internal error - illegal descriptor type %d - EXITING",
3916 (int)lsock->type);
3917 exit(1);
3920 free(lsock);
3922 * I/O Completion Ports don't care about select and fd_set
3924 #ifndef HAVE_IO_COMPLETION_PORT
3926 * remove from activefds
3928 FD_CLR(fd, &activefds);
3930 if (fd == maxactivefd && maxactivefd) {
3931 int i;
3932 NTP_INSIST(maxactivefd - 1 < FD_SETSIZE);
3933 for (i = maxactivefd - 1; i >= 0; i--)
3934 if (FD_ISSET(i, &activefds)) {
3935 maxactivefd = i;
3936 break;
3938 NTP_INSIST(fd != maxactivefd);
3940 #endif
3944 static void
3945 add_addr_to_list(
3946 sockaddr_u *addr,
3947 struct interface *interface
3950 remaddr_t *laddr;
3952 #ifdef DEBUG
3953 if (find_addr_in_list(addr) == NULL) {
3954 #endif
3955 /* not there yet - add to list */
3956 laddr = emalloc(sizeof(*laddr));
3957 memcpy(&laddr->addr, addr, sizeof(laddr->addr));
3958 laddr->interface = interface;
3960 LINK_SLIST(remoteaddr_list, laddr, link);
3962 DPRINTF(4, ("Added addr %s to list of addresses\n",
3963 stoa(addr)));
3964 #ifdef DEBUG
3965 } else
3966 DPRINTF(4, ("WARNING: Attempt to add duplicate addr %s to address list\n",
3967 stoa(addr)));
3968 #endif
3972 static void
3973 delete_addr_from_list(
3974 sockaddr_u *addr
3977 remaddr_t *unlinked;
3979 UNLINK_EXPR_SLIST(unlinked, remoteaddr_list, SOCK_EQ(addr,
3980 &(UNLINK_EXPR_SLIST_CURRENT()->addr)), link, remaddr_t);
3982 if (unlinked != NULL) {
3983 DPRINTF(4, ("Deleted addr %s from list of addresses\n",
3984 stoa(addr)));
3985 free(unlinked);
3990 static void
3991 delete_interface_from_list(
3992 struct interface *iface
3995 remaddr_t *unlinked;
3997 do {
3998 UNLINK_EXPR_SLIST(unlinked, remoteaddr_list, iface ==
3999 UNLINK_EXPR_SLIST_CURRENT()->interface, link,
4000 remaddr_t);
4002 if (unlinked != NULL) {
4003 DPRINTF(4, ("Deleted addr %s for interface #%d %s from list of addresses\n",
4004 stoa(&unlinked->addr), iface->ifnum,
4005 iface->name));
4006 if (addr_ismulticast(&unlinked->addr))
4007 /* find a new interface to use */
4008 io_multicast_add(&unlinked->addr);
4009 free(unlinked);
4011 } while (unlinked != NULL);
4015 static struct interface *
4016 find_addr_in_list(
4017 sockaddr_u *addr
4020 remaddr_t *entry;
4022 DPRINTF(4, ("Searching for addr %s in list of addresses - ",
4023 stoa(addr)));
4025 for (entry = remoteaddr_list;
4026 entry != NULL;
4027 entry = entry->link)
4028 if (SOCK_EQ(&entry->addr, addr)) {
4029 DPRINTF(4, ("FOUND\n"));
4030 return entry->interface;
4033 DPRINTF(4, ("NOT FOUND\n"));
4034 return NULL;
4037 static inline isc_boolean_t
4038 same_network_v4(
4039 struct sockaddr_in *addr1,
4040 struct sockaddr_in *mask,
4041 struct sockaddr_in *addr2
4044 return (addr1->sin_addr.s_addr & mask->sin_addr.s_addr)
4045 == (addr2->sin_addr.s_addr & mask->sin_addr.s_addr);
4048 #ifdef INCLUDE_IPV6_SUPPORT
4049 static inline isc_boolean_t
4050 same_network_v6(
4051 struct sockaddr_in6 *addr1,
4052 struct sockaddr_in6 *mask,
4053 struct sockaddr_in6 *addr2
4056 int i;
4058 for (i = 0;
4059 i < sizeof(addr1->sin6_addr.s6_addr) /
4060 sizeof(addr1->sin6_addr.s6_addr[0]);
4061 i++)
4063 if ((addr1->sin6_addr.s6_addr[i] &
4064 mask->sin6_addr.s6_addr[i])
4066 (addr2->sin6_addr.s6_addr[i] &
4067 mask->sin6_addr.s6_addr[i]))
4069 return ISC_FALSE;
4071 return ISC_TRUE;
4073 #endif /* INCLUDE_IPV6_SUPPORT */
4076 static isc_boolean_t
4077 same_network(
4078 sockaddr_u *a1,
4079 sockaddr_u *mask,
4080 sockaddr_u *a2
4083 isc_boolean_t sn;
4085 if (AF(a1) != AF(a2))
4086 sn = ISC_FALSE;
4087 else if (IS_IPV4(a1))
4088 sn = same_network_v4(&a1->sa4, &mask->sa4, &a2->sa4);
4089 #ifdef INCLUDE_IPV6_SUPPORT
4090 else if (IS_IPV6(a1))
4091 sn = same_network_v6(&a1->sa6, &mask->sa6, &a2->sa6);
4092 #endif
4093 else
4094 sn = ISC_FALSE;
4096 return sn;
4100 * Find an address in the list on the same network as addr which is not
4101 * addr.
4103 static struct interface *
4104 find_samenet_addr_in_list(
4105 sockaddr_u *addr
4108 remaddr_t *entry;
4110 DPRINTF(4, ("Searching for addr with same subnet as %s in list of addresses - ",
4111 stoa(addr)));
4113 for (entry = remoteaddr_list;
4114 entry != NULL;
4115 entry = entry->link)
4117 if (!SOCK_EQ(addr, &entry->addr)
4118 && same_network(&entry->addr,
4119 &entry->interface->mask,
4120 addr)) {
4121 DPRINTF(4, ("FOUND\n"));
4122 return entry->interface;
4125 DPRINTF(4, ("NOT FOUND\n"));
4126 return NULL;
4131 * Find the given address with the all given flags set in the list
4133 static struct interface *
4134 find_flagged_addr_in_list(
4135 sockaddr_u * addr,
4136 int flags
4139 remaddr_t *entry;
4141 DPRINTF(4, ("Finding addr %s with flags %d in list: ",
4142 stoa(addr), flags));
4144 for (entry = remoteaddr_list;
4145 entry != NULL;
4146 entry = entry->link)
4148 if (SOCK_EQ(&entry->addr, addr)
4149 && (entry->interface->flags & flags) == flags) {
4151 DPRINTF(4, ("FOUND\n"));
4152 return entry->interface;
4155 DPRINTF(4, ("NOT FOUND\n"));
4156 return NULL;
4160 #ifdef HAS_ROUTING_SOCKET
4161 # ifndef UPDATE_GRACE
4162 # define UPDATE_GRACE 2 /* wait UPDATE_GRACE seconds before scanning */
4163 # endif
4165 static void
4166 process_routing_msgs(struct asyncio_reader *reader)
4168 char buffer[5120];
4169 int cnt, msg_type;
4170 #ifdef HAVE_RTNETLINK
4171 struct nlmsghdr *nh;
4172 #else
4173 struct rt_msghdr *rtm;
4174 char *p;
4175 #endif
4177 if (disable_dynamic_updates) {
4179 * discard ourselves if we are not needed any more
4180 * usually happens when running unprivileged
4182 remove_asyncio_reader(reader);
4183 delete_asyncio_reader(reader);
4184 return;
4187 cnt = read(reader->fd, buffer, sizeof(buffer));
4189 if (cnt < 0) {
4190 msyslog(LOG_ERR,
4191 "i/o error on routing socket %m - disabling");
4192 remove_asyncio_reader(reader);
4193 delete_asyncio_reader(reader);
4194 return;
4198 * process routing message
4200 #ifdef HAVE_RTNETLINK
4201 for (nh = (struct nlmsghdr *)buffer;
4202 NLMSG_OK(nh, cnt);
4203 nh = NLMSG_NEXT(nh, cnt)) {
4204 msg_type = nh->nlmsg_type;
4205 #else
4206 for (p = buffer;
4207 (p + sizeof(struct rt_msghdr)) <= (buffer + cnt);
4208 p += rtm->rtm_msglen) {
4209 rtm = (struct rt_msghdr *)p;
4210 if (rtm->rtm_version != RTM_VERSION) {
4211 msyslog(LOG_ERR,
4212 "version mismatch (got %d - expected %d) on routing socket - disabling",
4213 rtm->rtm_version, RTM_VERSION);
4215 remove_asyncio_reader(reader);
4216 delete_asyncio_reader(reader);
4217 return;
4219 msg_type = rtm->rtm_type;
4220 #endif
4221 switch (msg_type) {
4222 #ifdef RTM_NEWADDR
4223 case RTM_NEWADDR:
4224 #endif
4225 #ifdef RTM_DELADDR
4226 case RTM_DELADDR:
4227 #endif
4228 #ifdef RTM_ADD
4229 case RTM_ADD:
4230 #endif
4231 #ifdef RTM_DELETE
4232 case RTM_DELETE:
4233 #endif
4234 #ifdef RTM_REDIRECT
4235 case RTM_REDIRECT:
4236 #endif
4237 #ifdef RTM_CHANGE
4238 case RTM_CHANGE:
4239 #endif
4240 #ifdef RTM_LOSING
4241 case RTM_LOSING:
4242 #endif
4243 #ifdef RTM_IFINFO
4244 case RTM_IFINFO:
4245 #endif
4246 #ifdef RTM_IFANNOUNCE
4247 case RTM_IFANNOUNCE:
4248 #endif
4249 #ifdef RTM_NEWLINK
4250 case RTM_NEWLINK:
4251 #endif
4252 #ifdef RTM_DELLINK
4253 case RTM_DELLINK:
4254 #endif
4255 #ifdef RTM_NEWROUTE
4256 case RTM_NEWROUTE:
4257 #endif
4258 #ifdef RTM_DELROUTE
4259 case RTM_DELROUTE:
4260 #endif
4262 * we are keen on new and deleted addresses and
4263 * if an interface goes up and down or routing
4264 * changes
4266 DPRINTF(3, ("routing message op = %d: scheduling interface update\n",
4267 msg_type));
4268 timer_interfacetimeout(current_time + UPDATE_GRACE);
4269 break;
4270 #ifdef HAVE_RTNETLINK
4271 case NLMSG_DONE:
4272 /* end of multipart message */
4273 return;
4274 #endif
4275 default:
4277 * the rest doesn't bother us.
4279 DPRINTF(4, ("routing message op = %d: ignored\n",
4280 msg_type));
4281 break;
4287 * set up routing notifications
4289 static void
4290 init_async_notifications()
4292 struct asyncio_reader *reader;
4293 #ifdef HAVE_RTNETLINK
4294 int fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
4295 struct sockaddr_nl sa;
4296 #else
4297 int fd = socket(PF_ROUTE, SOCK_RAW, 0);
4298 #endif
4299 if (fd < 0) {
4300 msyslog(LOG_ERR,
4301 "unable to open routing socket (%m) - using polled interface update");
4302 return;
4305 fd = move_fd(fd);
4306 #ifdef HAVE_RTNETLINK
4307 memset(&sa, 0, sizeof(sa));
4308 sa.nl_family = PF_NETLINK;
4309 sa.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR
4310 | RTMGRP_IPV6_IFADDR | RTMGRP_IPV4_ROUTE
4311 | RTMGRP_IPV4_MROUTE | RTMGRP_IPV6_ROUTE
4312 | RTMGRP_IPV6_MROUTE;
4313 if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
4314 msyslog(LOG_ERR,
4315 "bind failed on routing socket (%m) - using polled interface update");
4316 return;
4318 #endif
4319 init_nonblocking_io(fd);
4320 #if defined(HAVE_SIGNALED_IO)
4321 init_socket_sig(fd);
4322 #endif /* HAVE_SIGNALED_IO */
4324 reader = new_asyncio_reader();
4326 reader->fd = fd;
4327 reader->receiver = process_routing_msgs;
4329 add_asyncio_reader(reader, FD_TYPE_SOCKET);
4330 msyslog(LOG_INFO,
4331 "Listening on routing socket on fd #%d for interface updates",
4332 fd);
4334 #else
4335 /* HAS_ROUTING_SOCKET not defined */
4336 static void
4337 init_async_notifications(void)
4340 #endif