Expand PMF_FN_* macros.
[netbsd-mini2440.git] / dist / ntp / ntpd / ntp_io.c
blob1142e2c2d6356b05757df85233c476ffe21f9482
1 /* $NetBSD: ntp_io.c,v 1.27 2008/12/28 22:56:57 christos 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 "ntp_machine.h"
13 #include "ntpd.h"
14 #include "ntp_io.h"
15 #include "iosignal.h"
16 #include "ntp_refclock.h"
17 #include "ntp_stdlib.h"
18 #include "ntp_request.h"
19 #include "ntp.h"
20 #include "ntp_unixtime.h"
22 /* Don't include ISC's version of IPv6 variables and structures */
23 #define ISC_IPV6_H 1
24 #include <isc/interfaceiter.h>
25 #include <isc/list.h>
26 #include <isc/result.h>
28 #ifdef SIM
29 #include "ntpsim.h"
30 #endif
32 #include <stdio.h>
33 #include <signal.h>
34 #ifdef HAVE_SYS_PARAM_H
35 # include <sys/param.h>
36 #endif /* HAVE_SYS_PARAM_H */
37 #ifdef HAVE_SYS_IOCTL_H
38 # include <sys/ioctl.h>
39 #endif
40 #ifdef HAVE_SYS_SOCKIO_H /* UXPV: SIOC* #defines (Frank Vance <fvance@waii.com>) */
41 # include <sys/sockio.h>
42 #endif
43 #ifdef HAVE_SYS_UIO_H
44 # include <sys/uio.h>
45 #endif
48 * setsockopt does not always have the same arg declaration
49 * across all platforms. If it's not defined we make it empty
52 #ifndef SETSOCKOPT_ARG_CAST
53 #define SETSOCKOPT_ARG_CAST
54 #endif
56 /*
57 * Set up some macros to look for IPv6 and IPv6 multicast
60 #if defined(ISC_PLATFORM_HAVEIPV6) && !defined(DISABLE_IPV6)
62 #define INCLUDE_IPV6_SUPPORT
64 #if defined(INCLUDE_IPV6_SUPPORT) && defined(IPV6_JOIN_GROUP) && defined(IPV6_LEAVE_GROUP)
65 #define INCLUDE_IPV6_MULTICAST_SUPPORT
67 #endif /* IPV6 Multicast Support */
68 #endif /* IPv6 Support */
70 extern int listen_to_virtual_ips;
71 extern const char *specific_interface;
73 #if defined(SO_TIMESTAMP) && defined(SCM_TIMESTAMP)
74 #if defined(CMSG_FIRSTHDR)
75 #define HAVE_TIMESTAMP
76 #define USE_TIMESTAMP_CMSG
77 #ifndef TIMESTAMP_CTLMSGBUF_SIZE
78 #define TIMESTAMP_CTLMSGBUF_SIZE 1536 /* moderate default */
79 #endif
80 #else
81 /* fill in for old/other timestamp interfaces */
82 #endif
83 #endif
85 #if defined(SYS_WINNT)
86 #include <transmitbuff.h>
87 #include <isc/win32os.h>
89 * Define this macro to control the behavior of connection
90 * resets on UDP sockets. See Microsoft KnowledgeBase Article Q263823
91 * for details.
92 * NOTE: This requires that Windows 2000 systems install Service Pack 2
93 * or later.
95 #ifndef SIO_UDP_CONNRESET
96 #define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR,12)
97 #endif
100 * Windows C runtime ioctl() can't deal properly with sockets,
101 * map to ioctlsocket for this source file.
103 #define ioctl(fd, opt, val) ioctlsocket((fd), (opt), (u_long *)(val))
104 #endif /* SYS_WINNT */
107 * We do asynchronous input using the SIGIO facility. A number of
108 * recvbuf buffers are preallocated for input. In the signal
109 * handler we poll to see which sockets are ready and read the
110 * packets from them into the recvbuf's along with a time stamp and
111 * an indication of the source host and the interface it was received
112 * through. This allows us to get as accurate receive time stamps
113 * as possible independent of other processing going on.
115 * We watch the number of recvbufs available to the signal handler
116 * and allocate more when this number drops below the low water
117 * mark. If the signal handler should run out of buffers in the
118 * interim it will drop incoming frames, the idea being that it is
119 * better to drop a packet than to be inaccurate.
124 * Other statistics of possible interest
126 volatile u_long packets_dropped; /* total number of packets dropped on reception */
127 volatile u_long packets_ignored; /* packets received on wild card interface */
128 volatile u_long packets_received; /* total number of packets received */
129 u_long packets_sent; /* total number of packets sent */
130 u_long packets_notsent; /* total number of packets which couldn't be sent */
132 volatile u_long handler_calls; /* number of calls to interrupt handler */
133 volatile u_long handler_pkts; /* number of pkts received by handler */
134 u_long io_timereset; /* time counters were reset */
137 * Interface stuff
139 struct interface *any_interface; /* default ipv4 interface */
140 struct interface *any6_interface; /* default ipv6 interface */
141 struct interface *loopback_interface; /* loopback ipv4 interface */
143 int ninterfaces; /* Total number of interfaces */
145 volatile int disable_dynamic_updates; /* when set to != 0 dynamic updates won't happen */
147 #ifdef REFCLOCK
149 * Refclock stuff. We keep a chain of structures with data concerning
150 * the guys we are doing I/O for.
152 static struct refclockio *refio;
153 #endif /* REFCLOCK */
157 * Define what the possible "soft" errors can be. These are non-fatal returns
158 * of various network related functions, like recv() and so on.
160 * For some reason, BSDI (and perhaps others) will sometimes return <0
161 * from recv() but will have errno==0. This is broken, but we have to
162 * work around it here.
164 #define SOFT_ERROR(e) ((e) == EAGAIN || \
165 (e) == EWOULDBLOCK || \
166 (e) == EINTR || \
167 (e) == 0)
170 * File descriptor masks etc. for call to select
171 * Not needed for I/O Completion Ports
173 fd_set activefds;
174 int maxactivefd;
176 * bit alternating value to detect verified interfaces during an update cycle
178 static u_char sys_interphase = 0;
180 static struct interface *new_interface P((struct interface *));
181 static void add_interface P((struct interface *));
182 static int update_interfaces P((u_short, interface_receiver_t, void *));
183 static void remove_interface P((struct interface *));
184 static struct interface *create_interface P((u_short, struct interface *));
186 static int move_fd P((SOCKET));
189 * Multicast functions
191 static isc_boolean_t addr_ismulticast P((struct sockaddr_storage *));
193 * Not all platforms support multicast
195 #ifdef MCAST
196 static isc_boolean_t socket_multicast_enable P((struct interface *, int, struct sockaddr_storage *));
197 static isc_boolean_t socket_multicast_disable P((struct interface *, struct sockaddr_storage *));
198 #endif
200 #ifdef DEBUG
201 static void print_interface P((struct interface *, char *, char *));
202 #define DPRINT_INTERFACE(_LVL_, _ARGS_) do { if (debug >= (_LVL_)) { print_interface _ARGS_; } } while (0)
203 #else
204 #define DPRINT_INTERFACE(_LVL_, _ARGS_) do {} while (0)
205 #endif
207 typedef struct vsock vsock_t;
208 enum desc_type { FD_TYPE_SOCKET, FD_TYPE_FILE };
210 struct vsock {
211 SOCKET fd;
212 enum desc_type type;
213 ISC_LINK(vsock_t) link;
216 #if !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET)
218 * async notification processing (e. g. routing sockets)
221 * support for receiving data on fd that is not a refclock or a socket
222 * like e. g. routing sockets
224 struct asyncio_reader {
225 SOCKET fd; /* fd to be read */
226 void *data; /* possibly local data */
227 void (*receiver)(struct asyncio_reader *); /* input handler */
228 ISC_LINK(struct asyncio_reader) link; /* the list this is being kept in */
231 ISC_LIST(struct asyncio_reader) asyncio_reader_list;
233 static void delete_asyncio_reader P((struct asyncio_reader *));
234 static struct asyncio_reader *new_asyncio_reader P((void));
235 static void add_asyncio_reader P((struct asyncio_reader *, enum desc_type));
236 static void remove_asyncio_reader P((struct asyncio_reader *));
238 #endif /* !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET) */
240 static void init_async_notifications P((void));
242 static int create_sockets P((u_short));
243 static SOCKET open_socket P((struct sockaddr_storage *, int, int, struct interface *));
244 static char * fdbits P((int, fd_set *));
245 static void set_reuseaddr P((int));
246 static isc_boolean_t socket_broadcast_enable P((struct interface *, SOCKET, struct sockaddr_storage *));
247 static isc_boolean_t socket_broadcast_disable P((struct interface *, struct sockaddr_storage *));
249 ISC_LIST(vsock_t) fd_list;
251 typedef struct remaddr remaddr_t;
253 struct remaddr {
254 struct sockaddr_storage addr;
255 struct interface *interface;
256 ISC_LINK(remaddr_t) link;
259 ISC_LIST(remaddr_t) remoteaddr_list;
261 ISC_LIST(struct interface) inter_list;
263 static struct interface *wildipv4 = NULL;
264 static struct interface *wildipv6 = NULL;
266 static void add_fd_to_list P((SOCKET, enum desc_type));
267 static void close_and_delete_fd_from_list P((SOCKET));
268 static void add_addr_to_list P((struct sockaddr_storage *, struct interface *));
269 static void delete_addr_from_list P((struct sockaddr_storage *));
270 static struct interface *find_addr_in_list P((struct sockaddr_storage *));
271 static struct interface *find_flagged_addr_in_list P((struct sockaddr_storage *, int));
272 static void create_wildcards P((u_short));
273 static isc_boolean_t address_okay P((struct interface *));
274 static void convert_isc_if P((isc_interface_t *, struct interface *, u_short));
275 static void delete_interface_from_list P((struct interface *));
276 static struct interface *getinterface P((struct sockaddr_storage *, int));
277 static struct interface *findlocalinterface P((struct sockaddr_storage *, int));
278 static struct interface *findlocalcastinterface P((struct sockaddr_storage *, int));
281 * Routines to read the ntp packets
283 #if !defined(HAVE_IO_COMPLETION_PORT)
284 static inline int read_network_packet P((SOCKET, struct interface *, l_fp));
285 static inline int read_refclock_packet P((SOCKET, struct refclockio *, l_fp));
286 #endif
288 #ifdef SYS_WINNT
290 * Windows 2000 systems incorrectly cause UDP sockets using WASRecvFrom
291 * to not work correctly, returning a WSACONNRESET error when a WSASendTo
292 * fails with an "ICMP port unreachable" response and preventing the
293 * socket from using the WSARecvFrom in subsequent operations.
294 * The function below fixes this, but requires that Windows 2000
295 * Service Pack 2 or later be installed on the system. NT 4.0
296 * systems are not affected by this and work correctly.
297 * See Microsoft Knowledge Base Article Q263823 for details of this.
299 void
300 connection_reset_fix(
301 SOCKET fd,
302 struct sockaddr_storage *addr
305 DWORD dwBytesReturned = 0;
306 BOOL bNewBehavior = FALSE;
307 DWORD status;
310 * disable bad behavior using IOCTL: SIO_UDP_CONNRESET
311 * NT 4.0 has no problem
313 if (isc_win32os_majorversion() >= 5) {
314 status = WSAIoctl(fd, SIO_UDP_CONNRESET, &bNewBehavior,
315 sizeof(bNewBehavior), NULL, 0,
316 &dwBytesReturned, NULL, NULL);
317 if (SOCKET_ERROR == status)
318 netsyslog(LOG_ERR, "connection_reset_fix() "
319 "failed for address %s: %m",
320 stoa(addr));
323 #endif
326 * on Unix systems the stdio library typically
327 * makes use of file descriptors in the lower
328 * integer range. stdio usually will make use
329 * of the file descriptor in the range of
330 * [0..FOPEN_MAX)
331 * in order to keep this range clean for socket
332 * file descriptors we attempt to move them above
333 * FOPEM_MAX. This is not as easy as it sounds as
334 * FOPEN_MAX changes from implementation to implementation
335 * and may exceed to current file decriptor limits.
336 * We are using following strategy:
337 * - keep a current socket fd boundary initialized with
338 * max(0, min(getdtablesize() - FD_CHUNK, FOPEN_MAX))
339 * - attempt to move the descriptor to the boundary or
340 * above.
341 * - if that fails and boundary > 0 set boundary
342 * to min(0, socket_fd_boundary - FD_CHUNK)
343 * -> retry
344 * if failure and boundary == 0 return old fd
345 * - on success close old fd return new fd
347 * effects:
348 * - fds will be moved above the socket fd boundary
349 * if at all possible.
350 * - the socket boundary will be reduced until
351 * allocation is possible or 0 is reached - at this
352 * point the algrithm will be disabled
354 static int move_fd(SOCKET fd)
356 #if !defined(SYS_WINNT) && defined(F_DUPFD)
357 #ifndef FD_CHUNK
358 #define FD_CHUNK 10
359 #endif
361 * number of fds we would like to have for
362 * stdio FILE* available.
363 * we can pick a "low" number as our use of
364 * FILE* is limited to log files and temporarily
365 * to data and config files. Except for log files
366 * we don't keep the other FILE* open beyond the
367 * scope of the function that opened it.
369 #ifndef FD_PREFERRED_SOCKBOUNDARY
370 #define FD_PREFERRED_SOCKBOUNDARY 48
371 #endif
373 #ifndef HAVE_GETDTABLESIZE
375 * if we have no idea about the max fd value set up things
376 * so we will start at FOPEN_MAX
378 #define getdtablesize() (FOPEN_MAX+FD_CHUNK)
379 #endif
381 #ifndef FOPEN_MAX
382 #define FOPEN_MAX 20 /* assume that for the lack of anything better */
383 #endif
384 static SOCKET socket_boundary = -1;
385 SOCKET newfd;
388 * check whether boundary has be set up
389 * already
391 if (socket_boundary == -1) {
392 socket_boundary = max(0, min(getdtablesize() - FD_CHUNK,
393 min(FOPEN_MAX, FD_PREFERRED_SOCKBOUNDARY)));
394 #ifdef DEBUG
395 msyslog(LOG_DEBUG, "ntp_io: estimated max descriptors: %d, initial socket boundary: %d",
396 getdtablesize(), socket_boundary);
397 #endif
401 * Leave a space for stdio to work in. potentially moving the
402 * socket_boundary lower until allocation succeeds.
404 do {
405 if (fd >= 0 && fd < socket_boundary) {
406 /* inside reserved range: attempt to move fd */
407 newfd = fcntl(fd, F_DUPFD, socket_boundary);
409 if (newfd != -1) {
410 /* success: drop the old one - return the new one */
411 (void)close(fd);
412 return (newfd);
414 } else {
415 /* outside reserved range: no work - return the original one */
416 return (fd);
418 socket_boundary = max(0, socket_boundary - FD_CHUNK);
419 #ifdef DEBUG
420 msyslog(LOG_DEBUG, "ntp_io: selecting new socket boundary: %d",
421 socket_boundary);
422 #endif
423 } while (socket_boundary > 0);
424 #endif /* !defined(SYS_WINNT) && defined(F_DUPFD) */
425 return (fd);
428 #ifdef DEBUG_TIMING
430 * collect timing information for various processing
431 * paths. currently we only pass then on to the file
432 * for later processing. this could also do histogram
433 * based analysis in other to reduce the load (and skew)
434 * dur to the file output
436 void
437 collect_timing(struct recvbuf *rb, const char *tag, int count, l_fp *dts)
439 char buf[2048];
441 snprintf(buf, sizeof(buf), "%s %d %s %s",
442 (rb != NULL) ?
443 ((rb->dstadr) ? stoa(&rb->recv_srcadr) : "-REFCLOCK-") : "-",
444 count, lfptoa(dts, 9), tag);
445 record_timing_stats(buf);
447 #endif
450 * About dynamic interfaces, sockets, reception and more...
452 * the code solves following tasks:
454 * - keep a current list of active interfaces in order
455 * to bind to to the interface address on NTP_PORT so that
456 * all wild and specific bindings for NTP_PORT are taken by ntpd
457 * to avoid other daemons messing with the time or sockets.
458 * - all interfaces keep a list of peers that are referencing
459 * the interface in order to quickly re-assign the peers to
460 * new interface in case an interface is deleted (=> gone from system or
461 * down)
462 * - have a preconfigured socket ready with the right local address
463 * for transmission and reception
464 * - have an address list for all destination addresses used within ntpd
465 * to find the "right" preconfigured socket.
466 * - facilitate updating the internal interface list with respect to
467 * the current kernel state
469 * special issues:
471 * - mapping of multicast addresses to the interface affected is not always
472 * one to one - especially on hosts with multiple interfaces
473 * the code here currently allocates a separate interface entry for those
474 * multicast addresses
475 * iff it is able to bind to a *new* socket with the multicast address (flags |= MCASTIF)
476 * in case of failure the multicast address is bound to an existing interface.
477 * - on some systems it is perfectly legal to assign the same address to
478 * multiple interfaces. Therefore this code does not keep a list of interfaces
479 * but a list of interfaces that represent a unique address as determined by the kernel
480 * by the procedure in findlocalinterface. Thus it is perfectly legal to see only
481 * one representative of a group of real interfaces if they share the same address.
483 * Frank Kardel 20050910
487 * init_io - initialize I/O data structures and call socket creation routine
489 void
490 init_io(void)
492 #ifdef SYS_WINNT
493 init_io_completion_port();
495 if (!Win32InitSockets())
497 netsyslog(LOG_ERR, "No useable winsock.dll: %m");
498 exit(1);
500 init_transmitbuff();
501 #endif /* SYS_WINNT */
504 * Init buffer free list and stat counters
506 init_recvbuff(RECV_INIT);
508 packets_dropped = packets_received = 0;
509 packets_ignored = 0;
510 packets_sent = packets_notsent = 0;
511 handler_calls = handler_pkts = 0;
512 io_timereset = 0;
513 loopback_interface = NULL;
514 any_interface = NULL;
515 any6_interface = NULL;
517 #ifdef REFCLOCK
518 refio = NULL;
519 #endif
521 #if defined(HAVE_SIGNALED_IO)
522 (void) set_signal();
523 #endif
525 ISC_LIST_INIT(fd_list);
527 #if !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET)
528 ISC_LIST_INIT(asyncio_reader_list);
529 #endif
531 ISC_LIST_INIT(remoteaddr_list);
533 ISC_LIST_INIT(inter_list);
536 * Create the sockets
538 BLOCKIO();
539 (void) create_sockets(htons(NTP_PORT));
540 UNBLOCKIO();
542 init_async_notifications();
544 DPRINTF(3, ("init_io: maxactivefd %d\n", maxactivefd));
547 #ifdef DEBUG
549 * function to dump the contents of the interface structure
550 * for debugging use only.
552 void
553 interface_dump(struct interface *itf)
555 u_char* cp;
556 int i;
557 /* Limit the size of the sockaddr_storage hex dump */
558 int maxsize = min(32, sizeof(struct sockaddr_storage));
560 printf("Dumping interface: %p\n", itf);
561 printf("fd = %d\n", itf->fd);
562 printf("bfd = %d\n", itf->bfd);
563 printf("sin = %s,\n", stoa(&(itf->sin)));
564 cp = (u_char*) &(itf->sin);
565 for(i = 0; i < maxsize; i++)
567 printf("%02x", *cp++);
568 if((i+1)%4 == 0)
569 printf(" ");
571 printf("\n");
572 printf("bcast = %s,\n", stoa(&(itf->bcast)));
573 cp = (u_char*) &(itf->bcast);
574 for(i = 0; i < maxsize; i++)
576 printf("%02x", *cp++);
577 if((i+1)%4 == 0)
578 printf(" ");
580 printf("\n");
581 printf("mask = %s,\n", stoa(&(itf->mask)));
582 cp = (u_char*) &(itf->mask);
583 for(i = 0; i < maxsize; i++)
585 printf("%02x", *cp++);
586 if((i+1)%4 == 0)
587 printf(" ");
589 printf("\n");
590 printf("name = %s\n", itf->name);
591 printf("flags = 0x%08x\n", itf->flags);
592 printf("last_ttl = %d\n", itf->last_ttl);
593 printf("addr_refid = %08x\n", itf->addr_refid);
594 printf("num_mcast = %d\n", itf->num_mcast);
595 printf("received = %ld\n", itf->received);
596 printf("sent = %ld\n", itf->sent);
597 printf("notsent = %ld\n", itf->notsent);
598 printf("ifindex = %u\n", itf->ifindex);
599 printf("scopeid = %u\n", itf->scopeid);
600 printf("peercnt = %u\n", itf->peercnt);
601 printf("phase = %u\n", itf->phase);
605 * print_interface - helper to output debug information
607 static void
608 print_interface(struct interface *iface, char *pfx, char *sfx)
610 printf("%sinterface #%d: fd=%d, bfd=%d, name=%s, flags=0x%x, scope=%d, ifindex=%d",
611 pfx,
612 iface->ifnum,
613 iface->fd,
614 iface->bfd,
615 iface->name,
616 iface->flags,
617 iface->scopeid,
618 iface->ifindex);
619 /* Leave these as three printf calls. */
620 printf(", sin=%s",
621 stoa((&iface->sin)));
622 if (iface->flags & INT_BROADCAST)
623 printf(", bcast=%s,",
624 stoa((&iface->bcast)));
625 if (iface->family == AF_INET)
626 printf(", mask=%s",
627 stoa((&iface->mask)));
628 printf(", %s:%s", iface->ignore_packets == ISC_FALSE ? "Enabled" : "Disabled", sfx);
629 if (debug > 4) /* in-depth debugging only */
630 interface_dump(iface);
633 #endif
635 #if !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET)
637 * create an asyncio_reader structure
639 static struct asyncio_reader *
640 new_asyncio_reader()
642 struct asyncio_reader *reader;
644 reader = (struct asyncio_reader *)emalloc(sizeof(struct asyncio_reader));
646 memset((char *)reader, 0, sizeof(*reader));
647 ISC_LINK_INIT(reader, link);
648 reader->fd = INVALID_SOCKET;
649 return reader;
653 * delete a reader
655 static void
656 delete_asyncio_reader(struct asyncio_reader *reader)
658 free(reader);
662 * add asynchio_reader
664 static void
665 add_asyncio_reader(struct asyncio_reader *reader, enum desc_type type)
667 ISC_LIST_APPEND(asyncio_reader_list, reader, link);
668 add_fd_to_list(reader->fd, type);
672 * remove asynchio_reader
674 static void
675 remove_asyncio_reader(struct asyncio_reader *reader)
677 ISC_LIST_UNLINK_TYPE(asyncio_reader_list, reader, link, struct asyncio_reader);
679 if (reader->fd != INVALID_SOCKET)
680 close_and_delete_fd_from_list(reader->fd);
682 reader->fd = INVALID_SOCKET;
684 #endif /* !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET) */
687 * interface list enumerator - visitor pattern
689 void
690 interface_enumerate(interface_receiver_t receiver, void *data)
692 interface_info_t ifi;
693 struct interface *interf;
695 ifi.action = IFS_EXISTS;
697 for (interf = ISC_LIST_HEAD(inter_list);
698 interf != NULL;
699 interf = ISC_LIST_NEXT(interf, link)) {
700 ifi.interface = interf;
701 receiver(data, &ifi);
706 * do standard initialization of interface structure
708 static void
709 init_interface(struct interface *interface)
711 memset((char *)interface, 0, sizeof(struct interface));
712 ISC_LINK_INIT(interface, link);
713 ISC_LIST_INIT(interface->peers);
714 interface->fd = INVALID_SOCKET;
715 interface->bfd = INVALID_SOCKET;
716 interface->num_mcast = 0;
717 interface->received = 0;
718 interface->sent = 0;
719 interface->notsent = 0;
720 interface->peercnt = 0;
721 interface->phase = sys_interphase;
725 * create new interface structure initialize from
726 * template structure or via standard initialization
727 * function
729 static struct interface *
730 new_interface(struct interface *interface)
732 static u_int sys_ifnum = 0;
734 struct interface *iface = (struct interface *)emalloc(sizeof(struct interface));
736 if (interface != NULL)
738 memcpy((char*)iface, (char*)interface, sizeof(*interface));
740 else
742 init_interface(iface);
745 iface->ifnum = sys_ifnum++; /* count every new instance of an interface in the system */
746 iface->starttime = current_time;
748 return iface;
752 * return interface storage into free memory pool
754 static void
755 delete_interface(struct interface *interface)
757 free(interface);
761 * link interface into list of known interfaces
763 static void
764 add_interface(struct interface *interface)
766 static struct interface *listhead = NULL;
769 * For ntpd, the first few interfaces (wildcard, localhost)
770 * will never be removed. This means inter_list.head is
771 * unchanging once initialized. Take advantage of that to
772 * watch for changes and catch corruption earlier. This
773 * helped track down corruption caused by using FD_SET with
774 * a descriptor numerically larger than FD_SETSIZE.
776 if (NULL == listhead)
777 listhead = inter_list.head;
779 if (listhead != inter_list.head) {
780 msyslog(LOG_ERR, "add_interface inter_list.head corrupted: was %p now %p",
781 listhead, inter_list.head);
782 exit(1);
785 * Calculate the address hash
787 interface->addr_refid = addr2refid(&interface->sin);
789 ISC_LIST_APPEND(inter_list, interface, link);
790 ninterfaces++;
794 * remove interface from known interface list and clean up
795 * associated resources
797 static void
798 remove_interface(struct interface *interface)
800 struct sockaddr_storage resmask;
802 ISC_LIST_UNLINK_TYPE(inter_list, interface, link, struct interface);
804 delete_interface_from_list(interface);
806 if (interface->fd != INVALID_SOCKET)
808 msyslog(LOG_INFO, "Deleting interface #%d %s, %s#%d, interface stats: received=%ld, sent=%ld, dropped=%ld, active_time=%ld secs",
809 interface->ifnum,
810 interface->name,
811 stoa((&interface->sin)),
812 NTP_PORT, /* XXX should extract port from sin structure */
813 interface->received,
814 interface->sent,
815 interface->notsent,
816 current_time - interface->starttime);
818 close_and_delete_fd_from_list(interface->fd);
821 if (interface->bfd != INVALID_SOCKET)
823 msyslog(LOG_INFO, "Deleting interface #%d %s, broadcast address %s#%d",
824 interface->ifnum,
825 interface->name,
826 stoa((&interface->bcast)),
827 (u_short) NTP_PORT); /* XXX extract port from sin structure */
828 close_and_delete_fd_from_list(interface->bfd);
831 ninterfaces--;
832 ntp_monclearinterface(interface);
834 /* remove restrict interface entry */
837 * Blacklist bound interface address
839 SET_HOSTMASK(&resmask, interface->sin.ss_family);
840 hack_restrict(RESTRICT_REMOVEIF, &interface->sin, &resmask,
841 RESM_NTPONLY|RESM_INTERFACE, RES_IGNORE);
844 static void
845 list_if_listening(struct interface *interface, u_short port)
847 msyslog(LOG_INFO, "Listening on interface #%d %s, %s#%d %s",
848 interface->ifnum,
849 interface->name,
850 stoa((&interface->sin)),
851 ntohs( (u_short) port),
852 (interface->ignore_packets == ISC_FALSE) ?
853 "Enabled": "Disabled");
856 static void
857 create_wildcards(u_short port) {
858 isc_boolean_t okipv4 = ISC_TRUE;
860 * create pseudo-interface with wildcard IPv4 address
862 #ifdef IPV6_V6ONLY
863 if(isc_net_probeipv4() != ISC_R_SUCCESS)
864 okipv4 = ISC_FALSE;
865 #endif
867 if(okipv4 == ISC_TRUE) {
868 struct interface *interface = new_interface(NULL);
870 interface->family = AF_INET;
871 interface->sin.ss_family = AF_INET;
872 ((struct sockaddr_in*)&interface->sin)->sin_addr.s_addr = htonl(INADDR_ANY);
873 ((struct sockaddr_in*)&interface->sin)->sin_port = port;
874 (void) strncpy(interface->name, "wildcard", sizeof(interface->name));
875 interface->mask.ss_family = AF_INET;
876 ((struct sockaddr_in*)&interface->mask)->sin_addr.s_addr = htonl(~(u_int32)0);
877 interface->flags = INT_BROADCAST | INT_UP | INT_WILDCARD;
878 interface->ignore_packets = ISC_TRUE;
879 #if defined(MCAST)
881 * enable possible multicast reception on the broadcast socket
883 interface->bcast.ss_family = AF_INET;
884 ((struct sockaddr_in*)&interface->bcast)->sin_port = port;
885 ((struct sockaddr_in*)&interface->bcast)->sin_addr.s_addr = htonl(INADDR_ANY);
886 #endif /* MCAST */
887 interface->fd = open_socket(&interface->sin,
888 interface->flags, 1, interface);
890 if (interface->fd != INVALID_SOCKET) {
891 wildipv4 = interface;
892 any_interface = interface;
894 add_addr_to_list(&interface->sin, interface);
895 add_interface(interface);
896 list_if_listening(interface, port);
897 } else {
898 msyslog(LOG_ERR, "unable to bind to wildcard socket address %s - another process may be running - EXITING",
899 stoa((&interface->sin)));
900 exit(1);
904 #ifdef INCLUDE_IPV6_SUPPORT
906 * create pseudo-interface with wildcard IPv6 address
908 if (isc_net_probeipv6() == ISC_R_SUCCESS) {
909 struct interface *interface = new_interface(NULL);
911 interface->family = AF_INET6;
912 interface->sin.ss_family = AF_INET6;
913 ((struct sockaddr_in6*)&interface->sin)->sin6_addr = in6addr_any;
914 ((struct sockaddr_in6*)&interface->sin)->sin6_port = port;
915 # ifdef ISC_PLATFORM_HAVESCOPEID
916 ((struct sockaddr_in6*)&interface->sin)->sin6_scope_id = 0;
917 # endif
918 (void) strncpy(interface->name, "wildcard", sizeof(interface->name));
919 interface->mask.ss_family = AF_INET6;
920 memset(&((struct sockaddr_in6*)&interface->mask)->sin6_addr.s6_addr, 0xff, sizeof(struct in6_addr));
921 interface->flags = INT_UP | INT_WILDCARD;
922 interface->ignore_packets = ISC_TRUE;
924 interface->fd = open_socket(&interface->sin,
925 interface->flags, 1, interface);
927 if (interface->fd != INVALID_SOCKET) {
928 wildipv6 = interface;
929 any6_interface = interface;
930 add_addr_to_list(&interface->sin, interface);
931 add_interface(interface);
932 list_if_listening(interface, port);
933 } else {
934 msyslog(LOG_ERR, "unable to bind to wildcard socket address %s - another process may be running - EXITING",
935 stoa((&interface->sin)));
936 exit(1);
939 #endif
943 static isc_boolean_t
944 address_okay(struct interface *iface) {
946 DPRINTF(4, ("address_okay: listen Virtual: %d, IF name: %s\n",
947 listen_to_virtual_ips, iface->name));
950 * Always allow the loopback
952 if((iface->flags & INT_LOOPBACK) != 0) {
953 DPRINTF(4, ("address_okay: loopback - OK\n"));
954 return (ISC_TRUE);
958 * Check if the interface is specified
960 if (specific_interface != NULL) {
961 if (strcasecmp(iface->name, specific_interface) == 0) {
962 DPRINTF(4, ("address_okay: specific interface name matched - OK\n"));
963 return (ISC_TRUE);
964 } else {
965 DPRINTF(4, ("address_okay: specific interface name NOT matched - FAIL\n"));
966 return (ISC_FALSE);
969 else {
970 if (listen_to_virtual_ips == 0 &&
971 (strchr(iface->name, (int)':') != NULL)) {
972 DPRINTF(4, ("address_okay: virtual ip/alias - FAIL\n"));
973 return (ISC_FALSE);
977 DPRINTF(4, ("address_okay: OK\n"));
978 return (ISC_TRUE);
981 static void
982 convert_isc_if(isc_interface_t *isc_if, struct interface *itf, u_short port)
984 itf->scopeid = 0;
985 itf->family = (short) isc_if->af;
986 strcpy(itf->name, isc_if->name);
988 if(isc_if->af == AF_INET) {
989 itf->sin.ss_family = (u_short) isc_if->af;
990 memcpy(&(((struct sockaddr_in*)&itf->sin)->sin_addr),
991 &(isc_if->address.type.in),
992 sizeof(struct in_addr));
993 ((struct sockaddr_in*)&itf->sin)->sin_port = port;
995 if((isc_if->flags & INTERFACE_F_BROADCAST) != 0) {
996 itf->flags |= INT_BROADCAST;
997 itf->bcast.ss_family = itf->sin.ss_family;
998 memcpy(&(((struct sockaddr_in*)&itf->bcast)->sin_addr),
999 &(isc_if->broadcast.type.in),
1000 sizeof(struct in_addr));
1001 ((struct sockaddr_in*)&itf->bcast)->sin_port = port;
1004 itf->mask.ss_family = itf->sin.ss_family;
1005 memcpy(&(((struct sockaddr_in*)&itf->mask)->sin_addr),
1006 &(isc_if->netmask.type.in),
1007 sizeof(struct in_addr));
1008 ((struct sockaddr_in*)&itf->mask)->sin_port = port;
1010 #ifdef INCLUDE_IPV6_SUPPORT
1011 else if (isc_if->af == AF_INET6) {
1012 itf->sin.ss_family = (u_short) isc_if->af;
1013 memcpy(&(((struct sockaddr_in6 *)&itf->sin)->sin6_addr),
1014 &(isc_if->address.type.in6),
1015 sizeof(((struct sockaddr_in6 *)&itf->sin)->sin6_addr));
1016 ((struct sockaddr_in6 *)&itf->sin)->sin6_port = port;
1018 #ifdef ISC_PLATFORM_HAVESCOPEID
1019 ((struct sockaddr_in6 *)&itf->sin)->sin6_scope_id = isc_netaddr_getzone(&isc_if->address);
1020 itf->scopeid = isc_netaddr_getzone(&isc_if->address);
1021 #endif
1022 itf->mask.ss_family = itf->sin.ss_family;
1023 memcpy(&(((struct sockaddr_in6 *)&itf->mask)->sin6_addr),
1024 &(isc_if->netmask.type.in6),
1025 sizeof(struct in6_addr));
1026 ((struct sockaddr_in6 *)&itf->mask)->sin6_port = port;
1027 /* Copy the interface index */
1028 itf->ifindex = isc_if->ifindex;
1030 #endif /* INCLUDE_IPV6_SUPPORT */
1033 /* Process the rest of the flags */
1035 if((isc_if->flags & INTERFACE_F_UP) != 0)
1036 itf->flags |= INT_UP;
1037 if((isc_if->flags & INTERFACE_F_LOOPBACK) != 0)
1038 itf->flags |= INT_LOOPBACK;
1039 if((isc_if->flags & INTERFACE_F_POINTTOPOINT) != 0)
1040 itf->flags |= INT_PPP;
1041 if((isc_if->flags & INTERFACE_F_MULTICAST) != 0)
1042 itf->flags |= INT_MULTICAST;
1047 * refresh_interface
1049 * some OSes have been observed to keep
1050 * cached routes even when more specific routes
1051 * become available.
1052 * this can be mitigated by re-binding
1053 * the socket.
1055 static int
1056 refresh_interface(struct interface * interface)
1058 #ifdef OS_MISSES_SPECIFIC_ROUTE_UPDATES
1059 if (interface->fd != INVALID_SOCKET)
1061 close_and_delete_fd_from_list(interface->fd);
1062 interface->fd = open_socket(&interface->sin,
1063 interface->flags, 0, interface);
1065 * reset TTL indication so TTL is is set again
1066 * next time around
1068 interface->last_ttl = 0;
1069 return interface->fd != INVALID_SOCKET;
1071 else
1073 return 0; /* invalid sockets are not refreshable */
1075 #else /* !OS_MISSES_SPECIFIC_ROUTE_UPDATES */
1076 return interface->fd != INVALID_SOCKET;
1077 #endif /* !OS_MISSES_SPECIFIC_ROUTE_UPDATES */
1081 * interface_update - externally callable update function
1083 void
1084 interface_update(interface_receiver_t receiver, void *data)
1086 if (!disable_dynamic_updates) {
1087 int new_interface_found;
1089 BLOCKIO();
1090 new_interface_found = update_interfaces(htons(NTP_PORT), receiver, data);
1091 UNBLOCKIO();
1093 if (new_interface_found) {
1094 #ifdef DEBUG
1095 msyslog(LOG_DEBUG, "new interface(s) found: waking up resolver");
1096 #endif
1097 #ifdef SYS_WINNT
1098 /* wake up the resolver thread */
1099 if (ResolverEventHandle != NULL)
1100 SetEvent(ResolverEventHandle);
1101 #else
1102 /* write any single byte to the pipe to wake up the resolver process */
1103 write( resolver_pipe_fd[1], &new_interface_found, 1 );
1104 #endif
1110 * find out if a given interface structure contains
1111 * a wildcard address
1113 static int
1114 is_wildcard_addr(struct sockaddr_storage *sas)
1116 if (sas->ss_family == AF_INET &&
1117 ((struct sockaddr_in*)sas)->sin_addr.s_addr == htonl(INADDR_ANY))
1118 return 1;
1120 #ifdef INCLUDE_IPV6_SUPPORT
1121 if (sas->ss_family == AF_INET6 &&
1122 memcmp(&((struct sockaddr_in6*)sas)->sin6_addr, &in6addr_any,
1123 sizeof(in6addr_any) == 0))
1124 return 1;
1125 #endif
1127 return 0;
1130 #ifdef OS_NEEDS_REUSEADDR_FOR_IFADDRBIND
1132 * enable/disable re-use of wildcard address socket
1134 static void
1135 set_wildcard_reuse(int family, int on)
1137 int onvalue = 1;
1138 int offvalue = 0;
1139 int *onoff;
1140 SOCKET fd = INVALID_SOCKET;
1142 onoff = on ? &onvalue : &offvalue;
1144 switch (family) {
1145 case AF_INET:
1146 if (any_interface) {
1147 fd = any_interface->fd;
1149 break;
1151 #ifdef INCLUDE_IPV6_SUPPORT
1152 case AF_INET6:
1153 if (any6_interface) {
1154 fd = any6_interface->fd;
1156 break;
1157 #endif /* !INCLUDE_IPV6_SUPPORT */
1160 if (fd != INVALID_SOCKET) {
1161 if (setsockopt(fd, SOL_SOCKET,
1162 SO_REUSEADDR, (char *)onoff,
1163 sizeof(*onoff))) {
1164 netsyslog(LOG_ERR, "set_wildcard_reuse: setsockopt(SO_REUSEADDR, %s) failed: %m", *onoff ? "on" : "off");
1166 DPRINTF(4, ("set SO_REUSEADDR to %s on %s\n", *onoff ? "ON" : "OFF",
1167 stoa((family == AF_INET) ?
1168 &any_interface->sin : &any6_interface->sin)));
1171 #endif /* OS_NEEDS_REUSEADDR_FOR_IFADDRBIND */
1174 * update_interface strategy
1176 * toggle configuration phase
1178 * Phase 1:
1179 * forall currently existing interfaces
1180 * if address is known:
1181 * drop socket - rebind again
1183 * if address is NOT known:
1184 * attempt to create a new interface entry
1186 * Phase 2:
1187 * forall currently known non MCAST and WILDCARD interfaces
1188 * if interface does not match configuration phase (not seen in phase 1):
1189 * remove interface from known interface list
1190 * forall peers associated with this interface
1191 * disconnect peer from this interface
1193 * Phase 3:
1194 * attempt to re-assign interfaces to peers
1198 static int
1199 update_interfaces(
1200 u_short port,
1201 interface_receiver_t receiver,
1202 void *data
1205 interface_info_t ifi;
1206 isc_mem_t *mctx = NULL;
1207 isc_interfaceiter_t *iter = NULL;
1208 isc_boolean_t scan_ipv4 = ISC_FALSE;
1209 isc_boolean_t scan_ipv6 = ISC_FALSE;
1210 isc_result_t result;
1211 int new_interface_found = 0;
1213 DPRINTF(3, ("update_interfaces(%d)\n", ntohs( (u_short) port)));
1215 #ifdef INCLUDE_IPV6_SUPPORT
1216 if (isc_net_probeipv6() == ISC_R_SUCCESS)
1217 scan_ipv6 = ISC_TRUE;
1218 #if defined(DEBUG)
1219 else
1220 if (debug)
1221 netsyslog(LOG_ERR, "no IPv6 interfaces found");
1222 #endif
1223 #endif
1224 if (isc_net_probeipv6() == ISC_R_SUCCESS)
1225 scan_ipv6 = ISC_TRUE;
1226 #if defined(ISC_PLATFORM_HAVEIPV6) && defined(DEBUG)
1227 else
1228 if (debug)
1229 netsyslog(LOG_ERR, "no IPv6 interfaces found");
1230 #endif
1232 if (isc_net_probeipv4() == ISC_R_SUCCESS)
1233 scan_ipv4 = ISC_TRUE;
1234 #ifdef DEBUG
1235 else
1236 if(debug)
1237 netsyslog(LOG_ERR, "no IPv4 interfaces found");
1238 #endif
1240 * phase one - scan interfaces
1241 * - create those that are not found
1242 * - update those that are found
1245 result = isc_interfaceiter_create(mctx, &iter);
1247 if (result != ISC_R_SUCCESS)
1248 return 0;
1250 sys_interphase ^= 0x1; /* toggle system phase for finding untouched (to be deleted) interfaces */
1252 for (result = isc_interfaceiter_first(iter);
1253 result == ISC_R_SUCCESS;
1254 result = isc_interfaceiter_next(iter))
1256 isc_interface_t isc_if;
1257 unsigned int family;
1258 struct interface interface;
1259 struct interface *iface;
1261 result = isc_interfaceiter_current(iter, &isc_if);
1263 if (result != ISC_R_SUCCESS)
1264 break;
1266 /* See if we have a valid family to use */
1267 family = isc_if.address.family;
1268 if (family != AF_INET && family != AF_INET6)
1269 continue;
1270 if (scan_ipv4 == ISC_FALSE && family == AF_INET)
1271 continue;
1272 if (scan_ipv6 == ISC_FALSE && family == AF_INET6)
1273 continue;
1276 * create prototype
1278 init_interface(&interface);
1280 convert_isc_if(&isc_if, &interface, port);
1283 * Check to see if we are going to use the interface
1284 * If we don't use it we mark it to drop any packet
1285 * received but we still must create the socket and
1286 * bind to it. This prevents other apps binding to it
1287 * and potentially causing problems with more than one
1288 * process fiddling with the clock
1290 if (address_okay(&interface) == ISC_TRUE) {
1291 interface.ignore_packets = ISC_FALSE;
1293 else {
1294 interface.ignore_packets = ISC_TRUE;
1297 DPRINT_INTERFACE(4, (&interface, "examining ", "\n"));
1299 if (!(interface.flags & INT_UP)) { /* interfaces must be UP to be usable */
1300 DPRINTF(4, ("skipping interface %s (%s) - DOWN\n", interface.name, stoa(&interface.sin)));
1301 continue;
1305 * skip any interfaces UP and bound to a wildcard
1306 * address - some dhcp clients produce that in the
1307 * wild
1309 if (is_wildcard_addr(&interface.sin))
1310 continue;
1313 * map to local *address* in order
1314 * to map all duplicate interfaces to an interface structure
1315 * with the appropriate socket (our name space is
1316 * (ip-address) - NOT (interface name, ip-address))
1318 iface = getinterface(&interface.sin, INT_WILDCARD);
1320 if (iface && refresh_interface(iface))
1323 * found existing and up to date interface - mark present
1326 iface->phase = sys_interphase;
1327 DPRINT_INTERFACE(4, (iface, "updating ", " present\n"));
1328 ifi.action = IFS_EXISTS;
1329 ifi.interface = iface;
1330 if (receiver)
1331 receiver(data, &ifi);
1333 else
1336 * this is new or refreshing failed - add to our interface list
1337 * if refreshing failed we will delete the interface structure in
1338 * phase 2 as the interface was not marked current. We can bind to
1339 * the address as the refresh code already closed the offending socket
1342 iface = create_interface(port, &interface);
1344 if (iface)
1346 ifi.action = IFS_CREATED;
1347 ifi.interface = iface;
1348 if (receiver)
1349 receiver(data, &ifi);
1351 new_interface_found = 1;
1353 DPRINT_INTERFACE(3, (iface, "updating ", " new - created\n"));
1355 else
1357 DPRINT_INTERFACE(3, (&interface, "updating ", " new - creation FAILED"));
1359 msyslog(LOG_INFO, "failed to initialize interface for address %s", stoa(&interface.sin));
1360 continue;
1365 isc_interfaceiter_destroy(&iter);
1368 * phase 2 - delete gone interfaces - reassigning peers to other interfaces
1371 struct interface *interf = ISC_LIST_HEAD(inter_list);
1373 while (interf != NULL)
1375 struct interface *next = ISC_LIST_NEXT(interf, link);
1377 if (!(interf->flags & (INT_WILDCARD|INT_MCASTIF))) {
1379 * if phase does not match sys_phase this interface was not
1380 * enumerated during interface scan - so it is gone and
1381 * will be deleted here unless it is solely an MCAST/WILDCARD interface
1383 if (interf->phase != sys_interphase) {
1384 struct peer *peer;
1385 DPRINT_INTERFACE(3, (interf, "updating ", "GONE - deleting\n"));
1386 remove_interface(interf);
1388 ifi.action = IFS_DELETED;
1389 ifi.interface = interf;
1390 if (receiver)
1391 receiver(data, &ifi);
1393 peer = ISC_LIST_HEAD(interf->peers);
1395 * disconnect peer from deleted interface
1397 while (peer != NULL) {
1398 struct peer *npeer = ISC_LIST_NEXT(peer, ilink);
1401 * this one just lost it's interface
1403 set_peerdstadr(peer, NULL);
1405 peer = npeer;
1409 * update globals in case we lose
1410 * a loopback interface
1412 if (interf == loopback_interface)
1413 loopback_interface = NULL;
1415 delete_interface(interf);
1418 interf = next;
1423 * phase 3 - re-configure as the world has changed if necessary
1425 refresh_all_peerinterfaces();
1426 return new_interface_found;
1431 * create_sockets - create a socket for each interface plus a default
1432 * socket for when we don't know where to send
1434 static int
1435 create_sockets(
1436 u_short port
1439 #ifndef HAVE_IO_COMPLETION_PORT
1441 * I/O Completion Ports don't care about the select and FD_SET
1443 maxactivefd = 0;
1444 FD_ZERO(&activefds);
1445 #endif
1447 DPRINTF(2, ("create_sockets(%d)\n", ntohs( (u_short) port)));
1449 create_wildcards(port);
1451 update_interfaces(port, NULL, NULL);
1454 * Now that we have opened all the sockets, turn off the reuse
1455 * flag for security.
1457 set_reuseaddr(0);
1459 DPRINTF(2, ("create_sockets: Total interfaces = %d\n", ninterfaces));
1461 return ninterfaces;
1465 * create_interface - create a new interface for a given prototype
1466 * binding the socket.
1468 static struct interface *
1469 create_interface(
1470 u_short port,
1471 struct interface *iface
1474 struct sockaddr_storage resmask;
1475 struct interface *interface;
1477 DPRINTF(2, ("create_interface(%s#%d)\n", stoa(&iface->sin), ntohs( (u_short) port)));
1479 /* build an interface */
1480 interface = new_interface(iface);
1483 * create socket
1485 interface->fd = open_socket(&interface->sin,
1486 interface->flags, 0, interface);
1488 if (interface->fd != INVALID_SOCKET)
1489 list_if_listening(interface, port);
1491 if ((interface->flags & INT_BROADCAST) &&
1492 interface->bfd != INVALID_SOCKET)
1493 msyslog(LOG_INFO, "Listening on broadcast address %s#%d",
1494 stoa((&interface->bcast)),
1495 ntohs( (u_short) port));
1497 if (interface->fd == INVALID_SOCKET &&
1498 interface->bfd == INVALID_SOCKET) {
1499 msyslog(LOG_ERR, "unable to create socket on %s (%d) for %s#%d",
1500 interface->name,
1501 interface->ifnum,
1502 stoa((&interface->sin)),
1503 ntohs( (u_short) port));
1504 delete_interface(interface);
1505 return NULL;
1509 * Blacklist bound interface address
1512 SET_HOSTMASK(&resmask, interface->sin.ss_family);
1513 hack_restrict(RESTRICT_FLAGS, &interface->sin, &resmask,
1514 RESM_NTPONLY|RESM_INTERFACE, RES_IGNORE);
1517 * set globals with the first found
1518 * loopback interface of the appropriate class
1520 if ((loopback_interface == NULL) &&
1521 (interface->family == AF_INET) &&
1522 ((interface->flags & INT_LOOPBACK) != 0))
1524 loopback_interface = interface;
1528 * put into our interface list
1530 add_addr_to_list(&interface->sin, interface);
1531 add_interface(interface);
1533 DPRINT_INTERFACE(2, (interface, "created ", "\n"));
1534 return interface;
1538 #ifdef SO_EXCLUSIVEADDRUSE
1539 static void
1540 set_excladdruse(int fd)
1542 int one = 1;
1543 int failed;
1545 failed = setsockopt(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
1546 (char *)&one, sizeof(one));
1548 if (failed)
1549 netsyslog(LOG_ERR,
1550 "setsockopt(%d, SO_EXCLUSIVEADDRUSE, on): %m", fd);
1552 #endif /* SO_EXCLUSIVEADDRUSE */
1556 * set_reuseaddr() - set/clear REUSEADDR on all sockets
1557 * NB possible hole - should we be doing this on broadcast
1558 * fd's also?
1560 static void
1561 set_reuseaddr(int flag) {
1562 struct interface *interf;
1564 #ifndef SO_EXCLUSIVEADDRUSE
1566 for (interf = ISC_LIST_HEAD(inter_list);
1567 interf != NULL;
1568 interf = ISC_LIST_NEXT(interf, link)) {
1570 if (interf->flags & INT_WILDCARD)
1571 continue;
1574 * if interf->fd is INVALID_SOCKET, we might have a adapter
1575 * configured but not present
1577 DPRINTF(4, ("setting SO_REUSEADDR on %.16s@%s to %s\n", interf->name, stoa(&interf->sin), flag ? "on" : "off"));
1579 if (interf->fd != INVALID_SOCKET) {
1580 if (setsockopt(interf->fd, SOL_SOCKET,
1581 SO_REUSEADDR, (char *)&flag,
1582 sizeof(flag))) {
1583 netsyslog(LOG_ERR, "set_reuseaddr: setsockopt(SO_REUSEADDR, %s) failed: %m", flag ? "on" : "off");
1587 #endif /* ! SO_EXCLUSIVEADDRUSE */
1591 * This is just a wrapper around an internal function so we can
1592 * make other changes as necessary later on
1594 void
1595 enable_broadcast(struct interface *iface, struct sockaddr_storage *baddr)
1597 #ifdef SO_BROADCAST
1598 socket_broadcast_enable(iface, iface->fd, baddr);
1599 #endif
1602 #ifdef OPEN_BCAST_SOCKET
1604 * Enable a broadcast address to a given socket
1605 * The socket is in the inter_list all we need to do is enable
1606 * broadcasting. It is not this function's job to select the socket
1608 static isc_boolean_t
1609 socket_broadcast_enable(struct interface *iface, SOCKET fd, struct sockaddr_storage *maddr)
1611 #ifdef SO_BROADCAST
1612 int on = 1;
1614 if (maddr->ss_family == AF_INET)
1616 /* if this interface can support broadcast, set SO_BROADCAST */
1617 if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST,
1618 (char *)&on, sizeof(on)))
1620 netsyslog(LOG_ERR, "setsockopt(SO_BROADCAST) enable failure on address %s: %m",
1621 stoa(maddr));
1623 #ifdef DEBUG
1624 else if (debug > 1) {
1625 printf("Broadcast enabled on socket %d for address %s\n",
1626 fd, stoa(maddr));
1628 #endif
1630 iface->flags |= INT_BCASTOPEN;
1631 return ISC_TRUE;
1632 #else
1633 return ISC_FALSE;
1634 #endif /* SO_BROADCAST */
1638 * Remove a broadcast address from a given socket
1639 * The socket is in the inter_list all we need to do is disable
1640 * broadcasting. It is not this function's job to select the socket
1642 static isc_boolean_t
1643 socket_broadcast_disable(struct interface *iface, struct sockaddr_storage *maddr)
1645 #ifdef SO_BROADCAST
1646 int off = 0; /* This seems to be OK as an int */
1648 if (maddr->ss_family == AF_INET)
1650 if (setsockopt(iface->fd, SOL_SOCKET, SO_BROADCAST,
1651 (char *)&off, sizeof(off)))
1653 netsyslog(LOG_ERR, "setsockopt(SO_BROADCAST) disable failure on address %s: %m",
1654 stoa(maddr));
1657 iface->flags &= ~INT_BCASTOPEN;
1658 return ISC_TRUE;
1659 #else
1660 return ISC_FALSE;
1661 #endif /* SO_BROADCAST */
1664 #endif /* OPEN_BCAST_SOCKET */
1666 * Check to see if the address is a multicast address
1668 static isc_boolean_t
1669 addr_ismulticast(struct sockaddr_storage *maddr)
1671 switch (maddr->ss_family)
1673 case AF_INET :
1674 if (!IN_CLASSD(ntohl(((struct sockaddr_in*)maddr)->sin_addr.s_addr))) {
1675 DPRINTF(4, ("multicast address %s not class D\n", stoa(maddr)));
1676 return (ISC_FALSE);
1678 else
1680 return (ISC_TRUE);
1683 case AF_INET6 :
1684 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
1685 if (!IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6*)maddr)->sin6_addr)) {
1686 DPRINTF(4, ("address %s not IPv6 multicast address\n", stoa(maddr)));
1687 return (ISC_FALSE);
1689 else
1691 return (ISC_TRUE);
1695 * If we don't have IPV6 support any IPV6 address is not multicast
1697 #else
1698 return (ISC_FALSE);
1699 #endif
1701 * Never valid
1703 default:
1704 return (ISC_FALSE);
1709 * Multicast servers need to set the appropriate Multicast interface
1710 * socket option in order for it to know which interface to use for
1711 * send the multicast packet.
1713 void
1714 enable_multicast_if(struct interface *iface, struct sockaddr_storage *maddr)
1716 #ifdef MCAST
1717 /*u_char*/ TYPEOF_IP_MULTICAST_LOOP off = 0;
1719 switch (maddr->ss_family)
1721 case AF_INET:
1722 if (setsockopt(iface->fd, IPPROTO_IP, IP_MULTICAST_IF,
1723 (char *)&(((struct sockaddr_in*)&iface->sin)->sin_addr.s_addr),
1724 sizeof(struct in_addr)) == -1) {
1725 netsyslog(LOG_ERR,
1726 "setsockopt IP_MULTICAST_IF failure: %m on socket %d, addr %s for multicast address %s",
1727 iface->fd, stoa(&iface->sin), stoa(maddr));
1728 return;
1730 #ifdef IP_MULTICAST_LOOP
1732 * Don't send back to itself, but allow it to fail to set it
1734 if (setsockopt(iface->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1735 SETSOCKOPT_ARG_CAST &off, sizeof(off)) == -1) {
1736 netsyslog(LOG_ERR,
1737 "setsockopt IP_MULTICAST_LOOP failure: %m on socket %d, addr %s for multicast address %s",
1738 iface->fd, stoa(&iface->sin), stoa(maddr));
1740 #endif
1741 DPRINTF(4, ("Added IPv4 multicast interface on socket %d, addr %s for multicast address %s\n",
1742 iface->fd, stoa(&iface->sin),
1743 stoa(maddr)));
1744 break;
1746 case AF_INET6:
1747 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
1748 if (setsockopt(iface->fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
1749 (char *) &iface->scopeid, sizeof(iface->scopeid)) == -1) {
1750 netsyslog(LOG_ERR,
1751 "setsockopt IPV6_MULTICAST_IF failure: %m on socket %d, addr %s, scope %d for multicast address %s",
1752 iface->fd, stoa(&iface->sin), iface->scopeid,
1753 stoa(maddr));
1754 return;
1756 #ifdef IPV6_MULTICAST_LOOP
1758 * Don't send back to itself, but allow it to fail to set it
1760 if (setsockopt(iface->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1761 (char *) &off, sizeof(off)) == -1) {
1762 netsyslog(LOG_ERR,
1763 "setsockopt IP_MULTICAST_LOOP failure: %m on socket %d, addr %s for multicast address %s",
1764 iface->fd, stoa(&iface->sin), stoa(maddr));
1766 #endif
1767 DPRINTF(4, ("Added IPv6 multicast interface on socket %d, addr %s, scope %d for multicast address %s\n",
1768 iface->fd, stoa(&iface->sin), iface->scopeid,
1769 stoa(maddr)));
1770 break;
1771 #else
1772 return;
1773 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */
1775 return;
1776 #endif
1780 * Add a multicast address to a given socket
1781 * The socket is in the inter_list all we need to do is enable
1782 * multicasting. It is not this function's job to select the socket
1784 static isc_boolean_t
1785 socket_multicast_enable(struct interface *iface, int lscope, struct sockaddr_storage *maddr)
1787 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
1788 struct ipv6_mreq mreq6;
1789 struct in6_addr iaddr6;
1790 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */
1792 struct ip_mreq mreq;
1794 if (find_addr_in_list(maddr)) {
1795 DPRINTF(4, ("socket_multicast_enable(%s): already enabled\n", stoa(maddr)));
1796 return ISC_TRUE;
1799 switch (maddr->ss_family)
1801 case AF_INET:
1802 memset((char *)&mreq, 0, sizeof(mreq));
1803 mreq.imr_multiaddr = (((struct sockaddr_in*)maddr)->sin_addr);
1804 mreq.imr_interface.s_addr = htonl(INADDR_ANY);
1805 if (setsockopt(iface->fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1806 (char *)&mreq, sizeof(mreq)) == -1) {
1807 netsyslog(LOG_ERR,
1808 "setsockopt IP_ADD_MEMBERSHIP failure: %m on socket %d, addr %s for %x / %x (%s)",
1809 iface->fd, stoa(&iface->sin),
1810 mreq.imr_multiaddr.s_addr,
1811 mreq.imr_interface.s_addr, stoa(maddr));
1812 return ISC_FALSE;
1814 DPRINTF(4, ("Added IPv4 multicast membership on socket %d, addr %s for %x / %x (%s)\n",
1815 iface->fd, stoa(&iface->sin),
1816 mreq.imr_multiaddr.s_addr,
1817 mreq.imr_interface.s_addr, stoa(maddr)));
1818 break;
1820 case AF_INET6:
1821 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
1823 * Enable reception of multicast packets
1824 * If the address is link-local we can get the interface index
1825 * from the scope id. Don't do this for other types of multicast
1826 * addresses. For now let the kernel figure it out.
1828 memset((char *)&mreq6, 0, sizeof(mreq6));
1829 iaddr6 = ((struct sockaddr_in6*)maddr)->sin6_addr;
1830 mreq6.ipv6mr_multiaddr = iaddr6;
1831 mreq6.ipv6mr_interface = lscope;
1833 if (setsockopt(iface->fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
1834 (char *)&mreq6, sizeof(mreq6)) == -1) {
1835 netsyslog(LOG_ERR,
1836 "setsockopt IPV6_JOIN_GROUP failure: %m on socket %d, addr %s for interface %d(%s)",
1837 iface->fd, stoa(&iface->sin),
1838 mreq6.ipv6mr_interface, stoa(maddr));
1839 return ISC_FALSE;
1841 DPRINTF(4, ("Added IPv6 multicast group on socket %d, addr %s for interface %d(%s)\n",
1842 iface->fd, stoa(&iface->sin),
1843 mreq6.ipv6mr_interface, stoa(maddr)));
1844 break;
1845 #else
1846 return ISC_FALSE;
1847 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */
1849 iface->flags |= INT_MCASTOPEN;
1850 iface->num_mcast++;
1851 add_addr_to_list(maddr, iface);
1852 return ISC_TRUE;
1856 * Remove a multicast address from a given socket
1857 * The socket is in the inter_list all we need to do is disable
1858 * multicasting. It is not this function's job to select the socket
1860 static isc_boolean_t
1861 socket_multicast_disable(struct interface *iface, struct sockaddr_storage *maddr)
1863 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
1864 struct ipv6_mreq mreq6;
1865 struct in6_addr iaddr6;
1866 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */
1868 struct ip_mreq mreq;
1869 memset((char *)&mreq, 0, sizeof(mreq));
1871 if (find_addr_in_list(maddr) == NULL) {
1872 DPRINTF(4, ("socket_multicast_disable(%s): not enabled\n", stoa(maddr)));
1873 return ISC_TRUE;
1876 switch (maddr->ss_family)
1878 case AF_INET:
1879 mreq.imr_multiaddr = (((struct sockaddr_in*)&maddr)->sin_addr);
1880 mreq.imr_interface.s_addr = ((struct sockaddr_in*)&iface->sin)->sin_addr.s_addr;
1881 if (setsockopt(iface->fd, IPPROTO_IP, IP_DROP_MEMBERSHIP,
1882 (char *)&mreq, sizeof(mreq)) == -1) {
1883 netsyslog(LOG_ERR,
1884 "setsockopt IP_DROP_MEMBERSHIP failure: %m on socket %d, addr %s for %x / %x (%s)",
1885 iface->fd, stoa(&iface->sin),
1886 mreq.imr_multiaddr.s_addr,
1887 mreq.imr_interface.s_addr, stoa(maddr));
1888 return ISC_FALSE;
1890 break;
1891 case AF_INET6:
1892 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
1894 * Disable reception of multicast packets
1895 * If the address is link-local we can get the interface index
1896 * from the scope id. Don't do this for other types of multicast
1897 * addresses. For now let the kernel figure it out.
1899 iaddr6 = ((struct sockaddr_in6*)&maddr)->sin6_addr;
1900 mreq6.ipv6mr_multiaddr = iaddr6;
1901 mreq6.ipv6mr_interface = iface->scopeid;
1903 if (setsockopt(iface->fd, IPPROTO_IPV6, IPV6_LEAVE_GROUP,
1904 (char *)&mreq6, sizeof(mreq6)) == -1) {
1905 netsyslog(LOG_ERR,
1906 "setsockopt IPV6_LEAVE_GROUP failure: %m on socket %d, addr %s for %d(%s)",
1907 iface->fd, stoa(&iface->sin),
1908 mreq6.ipv6mr_interface, stoa(maddr));
1909 return ISC_FALSE;
1911 break;
1912 #else
1913 return ISC_FALSE;
1914 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */
1917 iface->num_mcast--;
1918 if (iface->num_mcast <= 0) {
1919 iface->num_mcast = 0;
1920 iface->flags &= ~INT_MCASTOPEN;
1922 return ISC_TRUE;
1926 * io_setbclient - open the broadcast client sockets
1928 void
1929 io_setbclient(void)
1931 #ifdef OPEN_BCAST_SOCKET
1932 struct interface *interf;
1933 int nif = 0;
1934 isc_boolean_t jstatus;
1935 SOCKET fd;
1937 set_reuseaddr(1);
1939 for (interf = ISC_LIST_HEAD(inter_list);
1940 interf != NULL;
1941 interf = ISC_LIST_NEXT(interf, link)) {
1942 if (interf->flags & INT_WILDCARD)
1943 continue;
1945 /* use only allowed addresses */
1946 if (interf->ignore_packets == ISC_TRUE)
1947 continue;
1948 /* Only IPv4 addresses are valid for broadcast */
1949 if (interf->sin.ss_family != AF_INET)
1950 continue;
1952 /* Is this a broadcast address? */
1953 if (!(interf->flags & INT_BROADCAST))
1954 continue;
1956 /* Skip the loopback addresses */
1957 if (interf->flags & INT_LOOPBACK)
1958 continue;
1960 /* Do we already have the broadcast address open? */
1961 if (interf->flags & INT_BCASTOPEN) {
1962 /* account for already open interfaces to aviod misleading warning below */
1963 nif++;
1964 continue;
1968 * Try to open the broadcast address
1970 interf->family = AF_INET;
1971 interf->bfd = open_socket(&interf->bcast,
1972 INT_BROADCAST, 0, interf);
1975 * If we succeeded then we use it otherwise
1976 * enable the underlying address
1978 if (interf->bfd == INVALID_SOCKET) {
1979 fd = interf->fd;
1981 else {
1982 fd = interf->bfd;
1985 /* Enable Broadcast on socket */
1986 jstatus = socket_broadcast_enable(interf, fd, &interf->sin);
1987 if (jstatus == ISC_TRUE)
1989 nif++;
1990 netsyslog(LOG_INFO,"io_setbclient: Opened broadcast client on interface #%d %s, socket: %d",
1991 interf->ifnum, interf->name, fd);
1992 interf->addr_refid = addr2refid(&interf->sin);
1995 set_reuseaddr(0);
1996 #ifdef DEBUG
1997 if (debug)
1998 if (nif > 0)
1999 printf("io_setbclient: Opened broadcast clients\n");
2000 #endif
2001 if (nif == 0)
2002 netsyslog(LOG_ERR, "Unable to listen for broadcasts, no broadcast interfaces available");
2003 #else
2004 netsyslog(LOG_ERR, "io_setbclient: Broadcast Client disabled by build");
2005 #endif
2009 * io_unsetbclient - close the broadcast client sockets
2011 void
2012 io_unsetbclient(void)
2014 struct interface *interf;
2015 isc_boolean_t lstatus;
2017 for (interf = ISC_LIST_HEAD(inter_list);
2018 interf != NULL;
2019 interf = ISC_LIST_NEXT(interf, link))
2021 if (interf->flags & INT_WILDCARD)
2022 continue;
2024 if (!(interf->flags & INT_BCASTOPEN))
2025 continue;
2026 lstatus = socket_broadcast_disable(interf, &interf->sin);
2031 * io_multicast_add() - add multicast group address
2033 void
2034 io_multicast_add(
2035 struct sockaddr_storage addr
2038 #ifdef MCAST
2039 struct interface *interface;
2040 #ifndef MULTICAST_NONEWSOCKET
2041 struct interface *iface;
2042 #endif
2043 int lscope = 0;
2046 * Check to see if this is a multicast address
2048 if (addr_ismulticast(&addr) == ISC_FALSE)
2049 return;
2051 /* If we already have it we can just return */
2052 if (find_flagged_addr_in_list(&addr, INT_MCASTOPEN|INT_MCASTIF) != NULL)
2054 netsyslog(LOG_INFO, "Duplicate request found for multicast address %s",
2055 stoa(&addr));
2056 return;
2059 #ifndef MULTICAST_NONEWSOCKET
2060 interface = new_interface(NULL);
2063 * Open a new socket for the multicast address
2065 interface->sin.ss_family = addr.ss_family;
2066 interface->family = addr.ss_family;
2068 switch(addr.ss_family) {
2069 case AF_INET:
2070 memcpy(&(((struct sockaddr_in *)&interface->sin)->sin_addr),
2071 &(((struct sockaddr_in*)&addr)->sin_addr),
2072 sizeof(struct in_addr));
2073 ((struct sockaddr_in*)&interface->sin)->sin_port = htons(NTP_PORT);
2074 memset(&((struct sockaddr_in*)&interface->mask)->sin_addr.s_addr, 0xff, sizeof(struct in_addr));
2075 break;
2076 case AF_INET6:
2077 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2078 memcpy(&(((struct sockaddr_in6 *)&interface->sin)->sin6_addr),
2079 &((struct sockaddr_in6*)&addr)->sin6_addr,
2080 sizeof(struct in6_addr));
2081 ((struct sockaddr_in6*)&interface->sin)->sin6_port = htons(NTP_PORT);
2082 #ifdef ISC_PLATFORM_HAVESCOPEID
2083 ((struct sockaddr_in6*)&interface->sin)->sin6_scope_id = ((struct sockaddr_in6*)&addr)->sin6_scope_id;
2084 #endif
2085 memset(&((struct sockaddr_in6*)&interface->mask)->sin6_addr.s6_addr, 0xff, sizeof(struct in6_addr));
2086 #endif
2087 iface = findlocalcastinterface(&addr, INT_MULTICAST);
2088 if (iface) {
2089 # ifdef ISC_PLATFORM_HAVESCOPEID
2090 lscope = ((struct sockaddr_in6*)&iface->sin)->sin6_scope_id;
2091 # endif
2092 DPRINTF(4, ("Found interface #%d %s, scope: %d for address %s\n", iface->ifnum, iface->name, lscope, stoa(&addr)));
2094 break;
2097 set_reuseaddr(1);
2098 interface->bfd = INVALID_SOCKET;
2099 interface->fd = open_socket(&interface->sin,
2100 INT_MULTICAST, 0, interface);
2102 if (interface->fd != INVALID_SOCKET)
2104 interface->bfd = INVALID_SOCKET;
2105 interface->ignore_packets = ISC_FALSE;
2106 interface->flags |= INT_MCASTIF;
2108 (void) strncpy(interface->name, "multicast",
2109 sizeof(interface->name));
2110 ((struct sockaddr_in*)&interface->mask)->sin_addr.s_addr =
2111 htonl(~(u_int32)0);
2112 DPRINT_INTERFACE(2, (interface, "multicast add ", "\n"));
2113 /* socket_multicast_enable() will add this address to the addresslist */
2114 add_interface(interface);
2115 list_if_listening(interface, htons(NTP_PORT));
2117 else
2119 delete_interface(interface); /* re-use existing interface */
2120 interface = NULL;
2121 if (addr.ss_family == AF_INET)
2122 interface = wildipv4;
2123 else if (addr.ss_family == AF_INET6)
2124 interface = wildipv6;
2126 if (interface != NULL) {
2127 /* HACK ! -- stuff in an address */
2128 interface->bcast = addr;
2129 netsyslog(LOG_ERR,
2130 "...multicast address %s using wildcard interface #%d %s",
2131 stoa(&addr), interface->ifnum, interface->name);
2132 } else {
2133 netsyslog(LOG_ERR,
2134 "No multicast socket available to use for address %s",
2135 stoa(&addr));
2136 return;
2139 #else
2141 * For the case where we can't use a separate socket
2143 interface = findlocalcastinterface(&addr, INT_MULTICAST);
2145 * If we don't have a valid socket, just return
2147 if (!interface)
2149 netsyslog(LOG_ERR,
2150 "Cannot add multicast address %s: Cannot find slot",
2151 stoa(&addr));
2152 return;
2155 #endif
2157 isc_boolean_t jstatus;
2158 jstatus = socket_multicast_enable(interface, lscope, &addr);
2160 if (jstatus == ISC_TRUE)
2161 netsyslog(LOG_INFO, "Added Multicast Listener %s on interface #%d %s\n", stoa(&addr), interface->ifnum, interface->name);
2162 else
2163 netsyslog(LOG_ERR, "Failed to add Multicast Listener %s\n", stoa(&addr));
2165 #else /* MCAST */
2166 netsyslog(LOG_ERR,
2167 "Cannot add multicast address %s: no Multicast support",
2168 stoa(&addr));
2169 #endif /* MCAST */
2170 return;
2174 * io_multicast_del() - delete multicast group address
2176 void
2177 io_multicast_del(
2178 struct sockaddr_storage addr
2181 #ifdef MCAST
2182 struct interface *interface;
2183 isc_boolean_t lstatus;
2186 * Check to see if this is a multicast address
2188 if (addr_ismulticast(&addr) == ISC_FALSE)
2190 netsyslog(LOG_ERR,
2191 "invalid multicast address %s", stoa(&addr));
2192 return;
2195 switch (addr.ss_family)
2197 case AF_INET :
2199 * Disable reception of multicast packets
2201 interface = find_flagged_addr_in_list(&addr, INT_MCASTOPEN);
2202 while ( interface != NULL) {
2203 lstatus = socket_multicast_disable(interface, &addr);
2204 interface = find_flagged_addr_in_list(&addr, INT_MCASTOPEN);
2206 break;
2208 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2209 case AF_INET6 :
2211 * Disable reception of multicast packets
2213 for (interface = ISC_LIST_HEAD(inter_list);
2214 interface != NULL;
2215 interface = ISC_LIST_NEXT(interface, link))
2217 if (interface->flags & INT_WILDCARD)
2218 continue;
2220 /* Be sure it's the correct family */
2221 if (interface->sin.ss_family != AF_INET6)
2222 continue;
2223 if (!(interface->flags & INT_MCASTOPEN))
2224 continue;
2225 if (!(interface->fd < 0))
2226 continue;
2227 if (!SOCKCMP(&addr, &interface->sin))
2228 continue;
2229 lstatus = socket_multicast_disable(interface, &addr);
2231 break;
2232 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */
2234 }/* switch */
2236 delete_addr_from_list(&addr);
2238 #else /* not MCAST */
2239 netsyslog(LOG_ERR, "this function requires multicast kernel");
2240 #endif /* not MCAST */
2244 * init_nonblocking_io() - set up descriptor to be non blocking
2246 static void init_nonblocking_io(SOCKET fd)
2249 * set non-blocking,
2252 #ifdef USE_FIONBIO
2253 /* in vxWorks we use FIONBIO, but the others are defined for old systems, so
2254 * all hell breaks loose if we leave them defined
2256 #undef O_NONBLOCK
2257 #undef FNDELAY
2258 #undef O_NDELAY
2259 #endif
2261 #if defined(O_NONBLOCK) /* POSIX */
2262 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
2264 netsyslog(LOG_ERR, "fcntl(O_NONBLOCK) fails on fd #%d: %m",
2265 fd);
2266 exit(1);
2267 /*NOTREACHED*/
2269 #elif defined(FNDELAY)
2270 if (fcntl(fd, F_SETFL, FNDELAY) < 0)
2272 netsyslog(LOG_ERR, "fcntl(FNDELAY) fails on fd #%d: %m",
2273 fd);
2274 exit(1);
2275 /*NOTREACHED*/
2277 #elif defined(O_NDELAY) /* generally the same as FNDELAY */
2278 if (fcntl(fd, F_SETFL, O_NDELAY) < 0)
2280 netsyslog(LOG_ERR, "fcntl(O_NDELAY) fails on fd #%d: %m",
2281 fd);
2282 exit(1);
2283 /*NOTREACHED*/
2285 #elif defined(FIONBIO)
2287 int on = 1;
2288 if (ioctl(fd,FIONBIO,&on) < 0)
2290 netsyslog(LOG_ERR, "ioctl(FIONBIO) fails on fd #%d: %m",
2291 fd);
2292 exit(1);
2293 /*NOTREACHED*/
2296 #elif defined(FIOSNBIO)
2297 if (ioctl(fd,FIOSNBIO,&on) < 0)
2299 netsyslog(LOG_ERR, "ioctl(FIOSNBIO) fails on fd #%d: %m",
2300 fd);
2301 exit(1);
2302 /*NOTREACHED*/
2304 #else
2305 # include "Bletch: Need non-blocking I/O!"
2306 #endif
2310 * open_socket - open a socket, returning the file descriptor
2313 static SOCKET
2314 open_socket(
2315 struct sockaddr_storage *addr,
2316 int flags,
2317 int turn_off_reuse,
2318 struct interface *interf
2321 int errval;
2322 SOCKET fd;
2324 * int is OK for REUSEADR per
2325 * http://www.kohala.com/start/mcast.api.txt
2327 int on = 1;
2328 int off = 0;
2330 #if defined(IPTOS_LOWDELAY) && defined(IPPROTO_IP) && defined(IP_TOS)
2331 int tos;
2332 #endif /* IPTOS_LOWDELAY && IPPROTO_IP && IP_TOS */
2334 if ((addr->ss_family == AF_INET6) && (isc_net_probeipv6() != ISC_R_SUCCESS))
2335 return (INVALID_SOCKET);
2337 /* create a datagram (UDP) socket */
2338 fd = socket(addr->ss_family, SOCK_DGRAM, 0);
2339 if (INVALID_SOCKET == fd) {
2340 #ifndef SYS_WINNT
2341 errval = errno;
2342 #else
2343 errval = WSAGetLastError();
2344 #endif
2345 netsyslog(LOG_ERR,
2346 "socket(AF_INET%s, SOCK_DGRAM, 0) failed on address %s: %m",
2347 (addr->ss_family == AF_INET6) ? "6" : "",
2348 stoa(addr));
2350 if (errval == EPROTONOSUPPORT ||
2351 errval == EAFNOSUPPORT ||
2352 errval == EPFNOSUPPORT)
2353 return (INVALID_SOCKET);
2354 msyslog(LOG_ERR, "unexpected error code %d (not PROTONOSUPPORT|AFNOSUPPORT|FPNOSUPPORT) - exiting", errval);
2355 exit(1);
2356 /*NOTREACHED*/
2359 #ifdef SYS_WINNT
2360 connection_reset_fix(fd, addr);
2361 #endif
2363 * Fixup the file descriptor for some systems
2364 * See bug #530 for details of the issue.
2366 fd = move_fd(fd);
2369 * set SO_REUSEADDR since we will be binding the same port
2370 * number on each interface according to turn_off_reuse.
2371 * This is undesirable on Windows versions starting with
2372 * Windows XP (numeric version 5.1).
2374 #ifdef SYS_WINNT
2375 if (isc_win32os_versioncheck(5, 1, 0, 0) < 0) /* before 5.1 */
2376 #endif
2377 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
2378 (char *)(turn_off_reuse
2379 ? &off
2380 : &on),
2381 sizeof(on))) {
2383 netsyslog(LOG_ERR, "setsockopt SO_REUSEADDR %s"
2384 " fails for address %s: %m",
2385 turn_off_reuse
2386 ? "off"
2387 : "on",
2388 stoa(addr));
2389 closesocket(fd);
2390 return INVALID_SOCKET;
2392 #ifdef SO_EXCLUSIVEADDRUSE
2394 * setting SO_EXCLUSIVEADDRUSE on the wildcard we open
2395 * first will cause more specific binds to fail.
2397 if (!(interf->flags & INT_WILDCARD))
2398 set_excladdruse(fd);
2399 #endif
2402 * IPv4 specific options go here
2404 if (addr->ss_family == AF_INET) {
2405 #if defined(IPTOS_LOWDELAY) && defined(IPPROTO_IP) && defined(IP_TOS)
2406 /* set IP_TOS to minimize packet delay */
2407 tos = IPTOS_LOWDELAY;
2408 if (setsockopt(fd, IPPROTO_IP, IP_TOS, (char *) &tos, sizeof(tos)) < 0)
2410 netsyslog(LOG_ERR, "setsockopt IPTOS_LOWDELAY on fails on address %s: %m",
2411 stoa(addr));
2413 #endif /* IPTOS_LOWDELAY && IPPROTO_IP && IP_TOS */
2417 * IPv6 specific options go here
2419 if (addr->ss_family == AF_INET6) {
2420 #if defined(IPV6_V6ONLY)
2421 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY,
2422 (char*)&on, sizeof(on)))
2424 netsyslog(LOG_ERR, "setsockopt IPV6_V6ONLY on fails on address %s: %m",
2425 stoa(addr));
2427 #endif /* IPV6_V6ONLY */
2428 #if defined(IPV6_BINDV6ONLY)
2429 if (setsockopt(fd, IPPROTO_IPV6, IPV6_BINDV6ONLY,
2430 (char*)&on, sizeof(on)))
2432 netsyslog(LOG_ERR,
2433 "setsockopt IPV6_BINDV6ONLY on fails on address %s: %m",
2434 stoa(addr));
2436 #endif /* IPV6_BINDV6ONLY */
2439 #ifdef OS_NEEDS_REUSEADDR_FOR_IFADDRBIND
2441 * some OSes don't allow binding to more specific
2442 * addresses if a wildcard address already bound
2443 * to the port and SO_REUSEADDR is not set
2445 if (!is_wildcard_addr(addr)) {
2446 set_wildcard_reuse(addr->ss_family, 1);
2448 #endif
2451 * bind the local address.
2453 errval = bind(fd, (struct sockaddr *)addr, SOCKLEN(addr));
2455 #ifdef OS_NEEDS_REUSEADDR_FOR_IFADDRBIND
2457 * some OSes don't allow binding to more specific
2458 * addresses if a wildcard address already bound
2459 * to the port and REUSE_ADDR is not set
2461 if (!is_wildcard_addr(addr)) {
2462 set_wildcard_reuse(addr->ss_family, 0);
2464 #endif
2466 if (errval < 0) {
2468 * Don't log this under all conditions
2470 if (turn_off_reuse == 0
2471 #ifdef DEBUG
2472 || debug > 1
2473 #endif
2475 if (addr->ss_family == AF_INET)
2476 netsyslog(LOG_ERR,
2477 "bind() fd %d, family AF_INET, port %d, addr %s, in_classd=%d flags=0x%x fails: %m",
2478 fd, (int)ntohs(((struct sockaddr_in*)addr)->sin_port),
2479 stoa(addr),
2480 IN_CLASSD(ntohl(((struct sockaddr_in*)addr)->sin_addr.s_addr)),
2481 flags);
2482 #ifdef INCLUDE_IPV6_SUPPORT
2483 else if (addr->ss_family == AF_INET6)
2484 netsyslog(LOG_ERR,
2485 "bind() fd %d, family AF_INET6, port %d, scope %d, addr %s, mcast=%d flags=0x%x fails: %m",
2486 fd, (int)ntohs(((struct sockaddr_in6*)addr)->sin6_port),
2487 # ifdef ISC_PLATFORM_HAVESCOPEID
2488 ((struct sockaddr_in6*)addr)->sin6_scope_id
2489 # else
2491 # endif
2492 , stoa(addr),
2493 IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6*)addr)->sin6_addr),
2494 flags);
2495 #endif
2498 closesocket(fd);
2500 return INVALID_SOCKET;
2503 #ifdef HAVE_TIMESTAMP
2505 if (setsockopt(fd, SOL_SOCKET, SO_TIMESTAMP,
2506 (char*)&on, sizeof(on)))
2508 netsyslog(LOG_DEBUG,
2509 "setsockopt SO_TIMESTAMP on fails on address %s: %m",
2510 stoa(addr));
2512 #ifdef DEBUG
2513 else
2515 DPRINTF(4, ("setsockopt SO_TIMESTAMP enabled on fd %d address %s\n", fd, stoa(addr)));
2517 #endif
2519 #endif
2520 DPRINTF(4, ("bind() fd %d, family %d, port %d, addr %s, flags=0x%x\n",
2522 addr->ss_family,
2523 (int)ntohs(((struct sockaddr_in*)addr)->sin_port),
2524 stoa(addr),
2525 interf->flags));
2527 init_nonblocking_io(fd);
2529 #ifdef HAVE_SIGNALED_IO
2530 init_socket_sig(fd);
2531 #endif /* not HAVE_SIGNALED_IO */
2533 add_fd_to_list(fd, FD_TYPE_SOCKET);
2535 #if !defined(SYS_WINNT) && !defined(VMS)
2536 DPRINTF(4, ("flags for fd %d: 0x%x\n", fd,
2537 fcntl(fd, F_GETFL, 0)));
2538 #endif /* SYS_WINNT || VMS */
2540 #if defined (HAVE_IO_COMPLETION_PORT)
2542 * Add the socket to the completion port
2544 if (io_completion_port_add_socket(fd, interf))
2546 msyslog(LOG_ERR, "unable to set up io completion port - EXITING");
2547 exit(1);
2549 #endif
2550 return fd;
2553 /* XXX ELIMINATE sendpkt similar in ntpq.c, ntpdc.c, ntp_io.c, ntptrace.c */
2555 * sendpkt - send a packet to the specified destination. Maintain a
2556 * send error cache so that only the first consecutive error for a
2557 * destination is logged.
2559 void
2560 sendpkt(
2561 struct sockaddr_storage *dest,
2562 struct interface *inter,
2563 int ttl,
2564 struct pkt *pkt,
2565 int len
2568 int cc, slot;
2571 * Send error caches. Empty slots have port == 0
2572 * Set ERRORCACHESIZE to 0 to disable
2574 struct cache {
2575 u_short port;
2576 struct in_addr addr;
2579 #ifdef INCLUDE_IPV6_SUPPORT
2580 struct cache6 {
2581 u_short port;
2582 struct in6_addr addr;
2584 #endif /* INCLUDE_IPV6_SUPPORT */
2587 #ifndef ERRORCACHESIZE
2588 #define ERRORCACHESIZE 8
2589 #endif
2590 #if ERRORCACHESIZE > 0
2591 static struct cache badaddrs[ERRORCACHESIZE];
2592 #ifdef INCLUDE_IPV6_SUPPORT
2593 static struct cache6 badaddrs6[ERRORCACHESIZE];
2594 #endif /* INCLUDE_IPV6_SUPPORT */
2595 #else
2596 #define badaddrs ((struct cache *)0) /* Only used in empty loops! */
2597 #ifdef INCLUDE_IPV6_SUPPORT
2598 #define badaddrs6 ((struct cache6 *)0) /* Only used in empty loops! */
2599 #endif /* INCLUDE_IPV6_SUPPORT */
2600 #endif
2601 #ifdef DEBUG
2602 if (debug > 1)
2604 if (inter != NULL)
2606 printf("%ssendpkt(fd=%d dst=%s, src=%s, ttl=%d, len=%d)\n",
2607 (ttl > 0) ? "\tMCAST\t***** " : "",
2608 inter->fd, stoa(dest),
2609 stoa(&inter->sin), ttl, len);
2611 else
2613 printf("%ssendpkt(dst=%s, ttl=%d, len=%d): no interface - IGNORED\n",
2614 (ttl > 0) ? "\tMCAST\t***** " : "",
2615 stoa(dest),
2616 ttl, len);
2619 #endif
2621 if (inter == NULL) /* unbound peer - drop request and wait for better network conditions */
2622 return;
2624 #ifdef MCAST
2627 * for the moment we use the bcast option to set multicast ttl
2629 if (ttl > 0 && ttl != inter->last_ttl) {
2632 * set the multicast ttl for outgoing packets
2634 int rtc;
2636 switch (inter->sin.ss_family) {
2638 case AF_INET :
2640 u_char mttl = (u_char) ttl;
2642 rtc = setsockopt(inter->fd, IPPROTO_IP, IP_MULTICAST_TTL,
2643 (const void *) &mttl, sizeof(mttl));
2644 break;
2647 #ifdef INCLUDE_IPV6_SUPPORT
2648 case AF_INET6 :
2650 u_int ittl = (u_char) ttl;
2652 rtc = setsockopt(inter->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
2653 (const void *) &ittl, sizeof(ittl));
2654 break;
2657 #endif /* INCLUDE_IPV6_SUPPORT */
2658 default: /* just NOP if not supported */
2659 rtc = 0;
2660 break;
2663 if (rtc != 0) {
2664 netsyslog(LOG_ERR, "setsockopt IP_MULTICAST_TTL/IPV6_MULTICAST_HOPS fails on address %s: %m",
2665 stoa(&inter->sin));
2667 else
2668 inter->last_ttl = ttl;
2671 #endif /* MCAST */
2673 for (slot = ERRORCACHESIZE; --slot >= 0; )
2674 if(dest->ss_family == AF_INET) {
2675 if (badaddrs[slot].port == ((struct sockaddr_in*)dest)->sin_port &&
2676 badaddrs[slot].addr.s_addr == ((struct sockaddr_in*)dest)->sin_addr.s_addr)
2677 break;
2679 #ifdef INCLUDE_IPV6_SUPPORT
2680 else if (dest->ss_family == AF_INET6) {
2681 if (badaddrs6[slot].port == ((struct sockaddr_in6*)dest)->sin6_port &&
2682 badaddrs6[slot].addr.s6_addr == ((struct sockaddr_in6*)dest)->sin6_addr.s6_addr)
2683 break;
2685 #endif /* INCLUDE_IPV6_SUPPORT */
2687 #if defined(HAVE_IO_COMPLETION_PORT)
2688 cc = io_completion_port_sendto(inter, pkt, len, dest);
2689 if (cc != ERROR_SUCCESS)
2690 #else
2691 #ifdef SIM
2692 cc = srvr_rply(&ntp_node, dest, inter, pkt);
2693 #else /* SIM */
2694 cc = sendto(inter->fd, (char *)pkt, (unsigned int)len, 0, (struct sockaddr *)dest,
2695 SOCKLEN(dest));
2696 #endif /* SIM */
2697 if (cc == -1)
2698 #endif
2700 inter->notsent++;
2701 packets_notsent++;
2703 #if defined(HAVE_IO_COMPLETION_PORT)
2704 if (cc != WSAEWOULDBLOCK && cc != WSAENOBUFS && slot < 0)
2705 #else
2706 if (errno != EWOULDBLOCK && errno != ENOBUFS && slot < 0)
2707 #endif
2710 * Remember this, if there's an empty slot
2712 switch (dest->ss_family) {
2714 case AF_INET :
2716 for (slot = ERRORCACHESIZE; --slot >= 0; )
2717 if (badaddrs[slot].port == 0)
2719 badaddrs[slot].port = SRCPORT(dest);
2720 badaddrs[slot].addr = ((struct sockaddr_in*)dest)->sin_addr;
2721 break;
2723 break;
2725 #ifdef INCLUDE_IPV6_SUPPORT
2726 case AF_INET6 :
2728 for (slot = ERRORCACHESIZE; --slot >= 0; )
2729 if (badaddrs6[slot].port == 0)
2731 badaddrs6[slot].port = SRCPORT(dest);
2732 badaddrs6[slot].addr = ((struct sockaddr_in6*)dest)->sin6_addr;
2733 break;
2735 break;
2736 #endif /* INCLUDE_IPV6_SUPPORT */
2737 default: /* don't care if not supported */
2738 break;
2741 netsyslog(LOG_ERR, "sendto(%s) (fd=%d): %m",
2742 stoa(dest), inter->fd);
2745 else
2747 inter->sent++;
2748 packets_sent++;
2750 * He's not bad any more
2752 if (slot >= 0)
2754 netsyslog(LOG_INFO, "Connection re-established to %s", stoa(dest));
2755 switch (dest->ss_family) {
2756 case AF_INET :
2757 badaddrs[slot].port = 0;
2758 break;
2759 #ifdef INCLUDE_IPV6_SUPPORT
2760 case AF_INET6 :
2761 badaddrs6[slot].port = 0;
2762 break;
2763 #endif /* INCLUDE_IPV6_SUPPORT */
2764 default: /* don't care if not supported */
2765 break;
2771 #if !defined(HAVE_IO_COMPLETION_PORT)
2773 * fdbits - generate ascii representation of fd_set (FAU debug support)
2774 * HFDF format - highest fd first.
2776 static char *
2777 fdbits(
2778 int count,
2779 fd_set *set
2782 static char buffer[256];
2783 char * buf = buffer;
2785 count = (count < 256) ? count : 255;
2787 while (count >= 0)
2789 *buf++ = FD_ISSET(count, set) ? '#' : '-';
2790 count--;
2792 *buf = '\0';
2794 return buffer;
2798 * Routine to read the refclock packets for a specific interface
2799 * Return the number of bytes read. That way we know if we should
2800 * read it again or go on to the next one if no bytes returned
2802 static inline int
2803 read_refclock_packet(SOCKET fd, struct refclockio *rp, l_fp ts)
2805 int i;
2806 int buflen;
2807 register struct recvbuf *rb;
2809 rb = get_free_recv_buffer();
2811 if (rb == NULL)
2814 * No buffer space available - just drop the packet
2816 char buf[RX_BUFF_SIZE];
2818 buflen = read(fd, buf, sizeof buf);
2819 packets_dropped++;
2820 return (buflen);
2823 i = (rp->datalen == 0
2824 || rp->datalen > sizeof(rb->recv_space))
2825 ? sizeof(rb->recv_space) : rp->datalen;
2826 buflen = read(fd, (char *)&rb->recv_space, (unsigned)i);
2828 if (buflen < 0)
2830 if (errno != EINTR && errno != EAGAIN) {
2831 netsyslog(LOG_ERR, "clock read fd %d: %m", fd);
2833 freerecvbuf(rb);
2834 return (buflen);
2838 * Got one. Mark how and when it got here,
2839 * put it on the full list and do bookkeeping.
2841 rb->recv_length = buflen;
2842 rb->recv_srcclock = rp->srcclock;
2843 rb->dstadr = 0;
2844 rb->fd = fd;
2845 rb->recv_time = ts;
2846 rb->receiver = rp->clock_recv;
2848 if (rp->io_input)
2851 * have direct input routine for refclocks
2853 if (rp->io_input(rb) == 0)
2856 * data was consumed - nothing to pass up
2857 * into block input machine
2859 freerecvbuf(rb);
2860 return (buflen);
2864 add_full_recv_buffer(rb);
2866 rp->recvcount++;
2867 packets_received++;
2868 return (buflen);
2871 #ifdef HAVE_TIMESTAMP
2873 * extract timestamps from control message buffer
2875 static l_fp
2876 fetch_timestamp(struct recvbuf *rb, struct msghdr *msghdr, l_fp ts)
2878 #ifdef USE_TIMESTAMP_CMSG
2879 struct cmsghdr *cmsghdr;
2881 cmsghdr = CMSG_FIRSTHDR(msghdr);
2882 while (cmsghdr != NULL) {
2883 switch (cmsghdr->cmsg_type)
2885 case SCM_TIMESTAMP:
2887 struct timeval *tvp = (struct timeval *)CMSG_DATA(cmsghdr);
2888 double dtemp;
2889 l_fp nts;
2890 DPRINTF(4, ("fetch_timestamp: system network time stamp: %lld.%06ld\n", (long long)tvp->tv_sec, (long)tvp->tv_usec));
2891 nts.l_i = tvp->tv_sec + JAN_1970;
2892 dtemp = tvp->tv_usec / 1e6;
2894 /* fuzz lower bits not covered by precision */
2895 if (sys_precision != 0)
2896 dtemp += (ntp_random() / FRAC - .5) / (1 <<
2897 -sys_precision);
2899 nts.l_uf = (u_int32)(dtemp*FRAC);
2900 #ifdef DEBUG_TIMING
2902 l_fp dts = ts;
2903 L_SUB(&dts, &nts);
2904 collect_timing(rb, "input processing delay", 1, &dts);
2905 DPRINTF(4, ("fetch_timestamp: timestamp delta: %s (incl. prec fuzz)\n", lfptoa(&dts, 9)));
2907 #endif
2908 ts = nts; /* network time stamp */
2909 break;
2911 default:
2912 DPRINTF(4, ("fetch_timestamp: skipping control message 0x%x\n", cmsghdr->cmsg_type));
2913 break;
2915 cmsghdr = CMSG_NXTHDR(msghdr, cmsghdr);
2917 #endif
2918 return ts;
2920 #endif
2923 * Routine to read the network NTP packets for a specific interface
2924 * Return the number of bytes read. That way we know if we should
2925 * read it again or go on to the next one if no bytes returned
2927 static inline int
2928 read_network_packet(SOCKET fd, struct interface *itf, l_fp ts)
2930 GETSOCKNAME_SOCKLEN_TYPE fromlen;
2931 int buflen;
2932 register struct recvbuf *rb;
2933 #ifdef HAVE_TIMESTAMP
2934 struct msghdr msghdr;
2935 struct iovec iovec;
2936 char control[TIMESTAMP_CTLMSGBUF_SIZE]; /* pick up control messages */
2937 #endif
2940 * Get a buffer and read the frame. If we
2941 * haven't got a buffer, or this is received
2942 * on a disallowed socket, just dump the
2943 * packet.
2946 rb = get_free_recv_buffer();
2948 if (rb == NULL || itf->ignore_packets == ISC_TRUE)
2950 char buf[RX_BUFF_SIZE];
2951 struct sockaddr_storage from;
2952 if (rb != NULL)
2953 freerecvbuf(rb);
2955 fromlen = sizeof(from);
2956 buflen = recvfrom(fd, buf, sizeof(buf), 0,
2957 (struct sockaddr*)&from, &fromlen);
2958 DPRINTF(4, ("%s on (%lu) fd=%d from %s\n",
2959 (itf->ignore_packets == ISC_TRUE) ? "ignore" : "drop",
2960 free_recvbuffs(), fd,
2961 stoa(&from)));
2962 if (itf->ignore_packets == ISC_TRUE)
2963 packets_ignored++;
2964 else
2965 packets_dropped++;
2966 return (buflen);
2969 fromlen = sizeof(struct sockaddr_storage);
2971 #ifndef HAVE_TIMESTAMP
2972 rb->recv_length = recvfrom(fd,
2973 (char *)&rb->recv_space,
2974 sizeof(rb->recv_space), 0,
2975 (struct sockaddr *)&rb->recv_srcadr,
2976 &fromlen);
2977 #else
2978 iovec.iov_base = (void *)&rb->recv_space;
2979 iovec.iov_len = sizeof(rb->recv_space);
2980 msghdr.msg_name = (void *)&rb->recv_srcadr;
2981 msghdr.msg_namelen = sizeof(rb->recv_srcadr);
2982 msghdr.msg_iov = &iovec;
2983 msghdr.msg_iovlen = 1;
2984 msghdr.msg_control = (void *)&control;
2985 msghdr.msg_controllen = sizeof(control);
2986 msghdr.msg_flags = 0;
2987 rb->recv_length = recvmsg(fd, &msghdr, 0);
2988 #endif
2990 buflen = rb->recv_length;
2992 if (buflen == 0 || (buflen == -1 &&
2993 (errno==EWOULDBLOCK
2994 #ifdef EAGAIN
2995 || errno==EAGAIN
2996 #endif
2997 ))) {
2998 freerecvbuf(rb);
2999 return (buflen);
3001 else if (buflen < 0)
3003 netsyslog(LOG_ERR, "recvfrom(%s) fd=%d: %m",
3004 stoa(&rb->recv_srcadr), fd);
3005 DPRINTF(5, ("read_network_packet: fd=%d dropped (bad recvfrom)\n", fd));
3006 freerecvbuf(rb);
3007 return (buflen);
3010 #ifdef DEBUG
3011 if (debug > 2) {
3012 if(rb->recv_srcadr.ss_family == AF_INET)
3013 printf("read_network_packet: fd=%d length %d from %08lx %s\n",
3014 fd, buflen,
3015 (u_long)ntohl(((struct sockaddr_in*)&rb->recv_srcadr)->sin_addr.s_addr) &
3016 0x00000000ffffffff,
3017 stoa(&rb->recv_srcadr));
3018 else
3019 printf("read_network_packet: fd=%d length %d from %s\n",
3020 fd, buflen,
3021 stoa(&rb->recv_srcadr));
3023 #endif
3026 * Got one. Mark how and when it got here,
3027 * put it on the full list and do bookkeeping.
3029 rb->dstadr = itf;
3030 rb->fd = fd;
3031 #ifdef HAVE_TIMESTAMP
3032 ts = fetch_timestamp(rb, &msghdr, ts); /* pick up a network time stamp if possible */
3033 #endif
3034 rb->recv_time = ts;
3035 rb->receiver = receive;
3037 add_full_recv_buffer(rb);
3039 itf->received++;
3040 packets_received++;
3041 return (buflen);
3045 * input_handler - receive packets asynchronously
3047 void
3048 input_handler(
3049 l_fp *cts
3053 int buflen;
3054 int n;
3055 int doing;
3056 SOCKET fd;
3057 struct timeval tvzero;
3058 l_fp ts; /* Timestamp at BOselect() gob */
3059 #ifdef DEBUG_TIMING
3060 l_fp ts_e; /* Timestamp at EOselect() gob */
3061 #endif
3062 fd_set fds;
3063 int select_count = 0;
3064 struct interface *interface;
3065 #if defined(HAS_ROUTING_SOCKET)
3066 struct asyncio_reader *asyncio_reader;
3067 #endif
3069 handler_calls++;
3072 * If we have something to do, freeze a timestamp.
3073 * See below for the other cases (nothing (left) to do or error)
3075 ts = *cts;
3078 * Do a poll to see who has data
3081 fds = activefds;
3082 tvzero.tv_sec = tvzero.tv_usec = 0;
3084 n = select(maxactivefd+1, &fds, (fd_set *)0, (fd_set *)0, &tvzero);
3087 * If there are no packets waiting just return
3089 if (n < 0)
3091 int err = errno;
3093 * extended FAU debugging output
3095 if (err != EINTR)
3096 netsyslog(LOG_ERR,
3097 "select(%d, %s, 0L, 0L, &0.0) error: %m",
3098 maxactivefd+1,
3099 fdbits(maxactivefd, &activefds));
3100 if (err == EBADF) {
3101 int j, b;
3102 fds = activefds;
3103 for (j = 0; j <= maxactivefd; j++)
3104 if ((FD_ISSET(j, &fds) && (read(j, &b, 0) == -1)))
3105 netsyslog(LOG_ERR, "Bad file descriptor %d", j);
3107 return;
3109 else if (n == 0)
3110 return;
3112 ++handler_pkts;
3114 #ifdef REFCLOCK
3116 * Check out the reference clocks first, if any
3119 if (refio != NULL)
3121 register struct refclockio *rp;
3123 for (rp = refio; rp != NULL; rp = rp->next)
3125 fd = rp->fd;
3127 if (FD_ISSET(fd, &fds))
3129 do {
3130 ++select_count;
3131 buflen = read_refclock_packet(fd, rp, ts);
3132 } while (buflen > 0);
3134 } /* End if (FD_ISSET(fd, &fds)) */
3135 } /* End for (rp = refio; rp != 0 && n > 0; rp = rp->next) */
3136 } /* End if (refio != 0) */
3138 #endif /* REFCLOCK */
3141 * Loop through the interfaces looking for data to read.
3143 for (interface = ISC_LIST_TAIL(inter_list);
3144 interface != NULL;
3145 interface = ISC_LIST_PREV(interface, link))
3147 for (doing = 0; (doing < 2); doing++)
3149 if (doing == 0)
3151 fd = interface->fd;
3153 else
3155 if (!(interface->flags & INT_BCASTOPEN))
3156 break;
3157 fd = interface->bfd;
3159 if (fd < 0) continue;
3160 if (FD_ISSET(fd, &fds))
3162 do {
3163 ++select_count;
3164 buflen = read_network_packet(fd, interface, ts);
3165 } while (buflen > 0);
3167 /* Check more interfaces */
3171 #ifdef HAS_ROUTING_SOCKET
3173 * scan list of asyncio readers - currently only used for routing sockets
3175 asyncio_reader = ISC_LIST_TAIL(asyncio_reader_list);
3177 while (asyncio_reader != NULL)
3179 struct asyncio_reader *next = ISC_LIST_PREV(asyncio_reader, link);
3180 if (FD_ISSET(asyncio_reader->fd, &fds)) {
3181 ++select_count;
3182 asyncio_reader->receiver(asyncio_reader);
3184 asyncio_reader = next;
3186 #endif /* HAS_ROUTING_SOCKET */
3189 * Done everything from that select.
3193 * If nothing to do, just return.
3194 * If an error occurred, complain and return.
3196 if (select_count == 0) /* We really had nothing to do */
3198 #ifdef DEBUG
3199 if (debug)
3200 netsyslog(LOG_DEBUG, "input_handler: select() returned 0");
3201 #endif
3202 return;
3204 /* We've done our work */
3205 #ifdef DEBUG_TIMING
3206 get_systime(&ts_e);
3208 * (ts_e - ts) is the amount of time we spent
3209 * processing this gob of file descriptors. Log
3210 * it.
3212 L_SUB(&ts_e, &ts);
3213 collect_timing(NULL, "input handler", 1, &ts_e);
3214 if (debug > 3)
3215 netsyslog(LOG_INFO, "input_handler: Processed a gob of fd's in %s msec", lfptoms(&ts_e, 6));
3216 #endif
3217 /* just bail. */
3218 return;
3221 #endif
3224 * findinterface - find local interface corresponding to address
3226 struct interface *
3227 findinterface(
3228 struct sockaddr_storage *addr
3231 struct interface *interface;
3233 interface = findlocalinterface(addr, INT_WILDCARD);
3235 if (interface == NULL)
3237 DPRINTF(4, ("Found no interface for address %s - returning wildcard\n",
3238 stoa(addr)));
3240 return (ANY_INTERFACE_CHOOSE(addr));
3242 else
3244 DPRINTF(4, ("Found interface #%d %s for address %s\n",
3245 interface->ifnum, interface->name, stoa(addr)));
3247 return (interface);
3252 * findlocalinterface - find local interface index corresponding to address
3254 * This code attempts to find the local sending address for an outgoing
3255 * address by connecting a new socket to destinationaddress:NTP_PORT
3256 * and reading the sockname of the resulting connect.
3257 * the complicated sequence simulates the routing table lookup
3258 * for to first hop without duplicating any of the routing logic into
3259 * ntpd. preferably we would have used an API call - but its not there -
3260 * so this is the best we can do here short of duplicating to entire routing
3261 * logic in ntpd which would be a silly and really unportable thing to do.
3264 static struct interface *
3265 findlocalinterface(
3266 struct sockaddr_storage *addr,
3267 int flags
3270 SOCKET s;
3271 int rtn;
3272 struct sockaddr_storage saddr;
3273 GETSOCKNAME_SOCKLEN_TYPE saddrlen = SOCKLEN(addr);
3274 struct interface *iface;
3276 DPRINTF(4, ("Finding interface for addr %s in list of addresses\n",
3277 stoa(addr)));
3279 memset(&saddr, 0, sizeof(saddr));
3280 saddr.ss_family = addr->ss_family;
3281 if(addr->ss_family == AF_INET) {
3282 memcpy(&((struct sockaddr_in*)&saddr)->sin_addr, &((struct sockaddr_in*)addr)->sin_addr, sizeof(struct in_addr));
3283 ((struct sockaddr_in*)&saddr)->sin_port = htons(NTP_PORT);
3285 #ifdef INCLUDE_IPV6_SUPPORT
3286 else if(addr->ss_family == AF_INET6) {
3287 memcpy(&((struct sockaddr_in6*)&saddr)->sin6_addr, &((struct sockaddr_in6*)addr)->sin6_addr, sizeof(struct in6_addr));
3288 ((struct sockaddr_in6*)&saddr)->sin6_port = htons(NTP_PORT);
3289 # ifdef ISC_PLATFORM_HAVESCOPEID
3290 ((struct sockaddr_in6*)&saddr)->sin6_scope_id = ((struct sockaddr_in6*)addr)->sin6_scope_id;
3291 # endif
3293 #endif
3295 s = socket(addr->ss_family, SOCK_DGRAM, 0);
3296 if (s == INVALID_SOCKET)
3297 return NULL;
3299 rtn = connect(s, (struct sockaddr *)&saddr, SOCKLEN(&saddr));
3300 #ifndef SYS_WINNT
3301 if (rtn < 0)
3302 #else
3303 if (rtn == SOCKET_ERROR)
3304 #endif
3306 closesocket(s);
3307 return NULL;
3310 rtn = getsockname(s, (struct sockaddr *)&saddr, &saddrlen);
3311 closesocket(s);
3312 #ifndef SYS_WINNT
3313 if (rtn < 0)
3314 #else
3315 if (rtn == SOCKET_ERROR)
3316 #endif
3317 return NULL;
3319 DPRINTF(4, ("findlocalinterface: kernel maps %s to %s\n", stoa(addr), stoa(&saddr)));
3321 iface = getinterface(&saddr, flags);
3323 /* Don't both with ignore interfaces */
3324 if (iface != NULL && iface->ignore_packets == ISC_TRUE)
3326 return NULL;
3328 else
3330 return iface;
3335 * fetch an interface structure the matches the
3336 * address is has the given flags not set
3338 static struct interface *
3339 getinterface(struct sockaddr_storage *addr, int flags)
3341 struct interface *interface = find_addr_in_list(addr);
3343 if (interface != NULL && interface->flags & flags)
3345 return NULL;
3347 else
3349 return interface;
3354 * findlocalcastinterface - find local *cast interface index corresponding to address
3355 * depending on the flags passed
3357 static struct interface *
3358 findlocalcastinterface(
3359 struct sockaddr_storage *addr, int flags
3362 struct interface *interface;
3363 struct interface *nif = NULL;
3364 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
3365 isc_boolean_t want_linklocal;
3366 #endif
3369 * see how kernel maps the mcast address
3371 nif = findlocalinterface(addr, 0);
3373 if (nif) {
3374 DPRINTF(2, ("findlocalcastinterface: kernel recommends interface #%d %s\n", nif->ifnum, nif->name));
3375 return nif;
3378 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
3379 want_linklocal = ISC_FALSE;
3380 if (addr_ismulticast(addr) && flags == INT_MULTICAST)
3382 if (IN6_IS_ADDR_MC_LINKLOCAL(&((struct sockaddr_in6*)addr)->sin6_addr))
3384 want_linklocal = ISC_TRUE;
3386 else if (IN6_IS_ADDR_MC_SITELOCAL(&((struct sockaddr_in6*)addr)->sin6_addr))
3388 want_linklocal = ISC_TRUE;
3391 #endif
3393 for (interface = ISC_LIST_HEAD(inter_list);
3394 interface != NULL;
3395 interface = ISC_LIST_NEXT(interface, link))
3397 /* use only allowed addresses */
3398 if (interface->ignore_packets == ISC_TRUE)
3399 continue;
3401 /* Skip the loopback and wildcard addresses */
3402 if (interface->flags & (INT_LOOPBACK|INT_WILDCARD))
3403 continue;
3405 /* Skip if different family */
3406 if(interface->sin.ss_family != addr->ss_family)
3407 continue;
3409 /* Is this it one of these based on flags? */
3410 if (!(interface->flags & flags))
3411 continue;
3413 /* for IPv6 multicast check the address for linklocal */
3414 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
3415 if (flags == INT_MULTICAST && interface->sin.ss_family == AF_INET6 &&
3416 (IN6_IS_ADDR_LINKLOCAL(&((struct sockaddr_in6*)&interface->sin)->sin6_addr))
3417 && want_linklocal == ISC_TRUE)
3419 nif = interface;
3420 break;
3422 /* If we want a linklocal address and this isn't it, skip */\
3423 if (want_linklocal == ISC_TRUE)
3424 continue;
3425 #endif
3426 /* Otherwise just look for the flag */
3427 if((interface->flags & flags))
3429 nif = interface;
3430 break;
3433 #ifdef DEBUG
3434 if (debug > 2)
3436 if (nif)
3437 printf("findlocalcastinterface: found interface #%d %s\n", nif->ifnum, nif->name);
3438 else
3439 printf("findlocalcastinterface: no interface found for %s flags 0x%x\n", stoa(addr), flags);
3441 #endif
3442 return (nif);
3446 * findbcastinter - find broadcast interface corresponding to address
3448 struct interface *
3449 findbcastinter(
3450 struct sockaddr_storage *addr
3453 #if !defined(MPE) && (defined(SIOCGIFCONF) || defined(SYS_WINNT))
3454 struct interface *interface;
3457 DPRINTF(4, ("Finding broadcast/multicast interface for addr %s in list of addresses\n",
3458 stoa(addr)));
3460 interface = findlocalinterface(addr, INT_LOOPBACK|INT_WILDCARD);
3462 if (interface != NULL)
3464 DPRINTF(4, ("Found bcast-/mcast- interface index #%d %s\n", interface->ifnum, interface->name));
3465 return interface;
3468 /* plan B - try to find something reasonable in our lists in case kernel lookup doesn't help */
3470 for (interface = ISC_LIST_HEAD(inter_list);
3471 interface != NULL;
3472 interface = ISC_LIST_NEXT(interface, link))
3474 if (interface->flags & INT_WILDCARD)
3475 continue;
3477 /* Don't bother with ignored interfaces */
3478 if (interface->ignore_packets == ISC_TRUE)
3479 continue;
3482 * First look if this is the correct family
3484 if(interface->sin.ss_family != addr->ss_family)
3485 continue;
3487 /* Skip the loopback addresses */
3488 if (interface->flags & INT_LOOPBACK)
3489 continue;
3492 * If we are looking to match a multicast address grab it.
3494 if (addr_ismulticast(addr) == ISC_TRUE && interface->flags & INT_MULTICAST)
3496 #ifdef INCLUDE_IPV6_SUPPORT
3497 if(addr->ss_family == AF_INET6) {
3498 /* Only use link-local address for link-scope mcast */
3499 if(IN6_IS_ADDR_MC_LINKLOCAL(&((struct sockaddr_in6*)addr)->sin6_addr) &&
3500 !IN6_IS_ADDR_LINKLOCAL(&((struct sockaddr_in6*)&interface->sin)->sin6_addr)) {
3501 continue;
3504 #endif
3505 break;
3509 * We match only those interfaces marked as
3510 * broadcastable and either the explicit broadcast
3511 * address or the network portion of the IP address.
3512 * Sloppy.
3514 if(addr->ss_family == AF_INET) {
3515 if (SOCKCMP(&interface->bcast, addr)) {
3516 break;
3518 if ((NSRCADR(&interface->sin) &
3519 NSRCADR(&interface->mask)) == (NSRCADR(addr) &
3520 NSRCADR(&interface->mask)))
3521 break;
3523 #ifdef INCLUDE_IPV6_SUPPORT
3524 else if(addr->ss_family == AF_INET6) {
3525 if (SOCKCMP(&interface->bcast, addr)) {
3526 break;
3528 if (SOCKCMP(netof(&interface->sin), netof(addr))) {
3529 break;
3532 #endif
3534 #endif /* SIOCGIFCONF */
3535 if (interface == NULL) {
3536 DPRINTF(4, ("No bcast interface found for %s\n", stoa(addr)));
3537 return ANY_INTERFACE_CHOOSE(addr);
3538 } else {
3539 DPRINTF(4, ("Found bcast-/mcast- interface index #%d %s\n", interface->ifnum, interface->name));
3540 return interface;
3546 * io_clr_stats - clear I/O module statistics
3548 void
3549 io_clr_stats(void)
3551 packets_dropped = 0;
3552 packets_ignored = 0;
3553 packets_received = 0;
3554 packets_sent = 0;
3555 packets_notsent = 0;
3557 handler_calls = 0;
3558 handler_pkts = 0;
3559 io_timereset = current_time;
3563 #ifdef REFCLOCK
3565 * io_addclock - add a reference clock to the list and arrange that we
3566 * get SIGIO interrupts from it.
3569 io_addclock(
3570 struct refclockio *rio
3573 BLOCKIO();
3575 * Stuff the I/O structure in the list and mark the descriptor
3576 * in use. There is a harmless (I hope) race condition here.
3578 rio->next = refio;
3580 # ifdef HAVE_SIGNALED_IO
3581 if (init_clock_sig(rio))
3583 UNBLOCKIO();
3584 return 0;
3586 # elif defined(HAVE_IO_COMPLETION_PORT)
3587 if (io_completion_port_add_clock_io(rio))
3589 UNBLOCKIO();
3590 return 0;
3592 # endif
3595 * enqueue
3597 refio = rio;
3600 * register fd
3602 add_fd_to_list(rio->fd, FD_TYPE_FILE);
3604 UNBLOCKIO();
3605 return 1;
3609 * io_closeclock - close the clock in the I/O structure given
3611 void
3612 io_closeclock(
3613 struct refclockio *rio
3616 BLOCKIO();
3618 * Remove structure from the list
3620 if (refio == rio)
3622 refio = rio->next;
3624 else
3626 register struct refclockio *rp;
3628 for (rp = refio; rp != NULL; rp = rp->next)
3629 if (rp->next == rio)
3631 rp->next = rio->next;
3632 break;
3635 if (rp == NULL) {
3636 UNBLOCKIO();
3637 return;
3642 * Close the descriptor.
3644 close_and_delete_fd_from_list(rio->fd);
3645 UNBLOCKIO();
3647 #endif /* REFCLOCK */
3650 * On NT a SOCKET is an unsigned int so we cannot possibly keep it in
3651 * an array. So we use one of the ISC_LIST functions to hold the
3652 * socket value and use that when we want to enumerate it.
3654 void
3655 kill_asyncio(int startfd)
3657 vsock_t *lsock;
3658 vsock_t *next;
3660 BLOCKIO();
3662 lsock = ISC_LIST_HEAD(fd_list);
3663 while (lsock != NULL) {
3665 * careful here - list is being dismantled while
3666 * we scan it - setting next here insures that
3667 * we are able to correctly scan the list
3669 next = ISC_LIST_NEXT(lsock, link);
3671 * will remove socket from list
3673 close_and_delete_fd_from_list(lsock->fd);
3674 lsock = next;
3677 UNBLOCKIO();
3681 * Add and delete functions for the list of open sockets
3683 static void
3684 add_fd_to_list(SOCKET fd, enum desc_type type) {
3685 vsock_t *lsock = (vsock_t *)emalloc(sizeof(vsock_t));
3686 lsock->fd = fd;
3687 lsock->type = type;
3689 ISC_LIST_APPEND(fd_list, lsock, link);
3691 * I/O Completion Ports don't care about the select and FD_SET
3693 #ifndef HAVE_IO_COMPLETION_PORT
3694 if (fd < 0 || fd >= FD_SETSIZE) {
3695 msyslog(LOG_ERR, "Too many sockets in use, FD_SETSIZE %d exceeded",
3696 FD_SETSIZE);
3697 exit(1);
3700 * keep activefds in sync
3702 if (fd > maxactivefd)
3703 maxactivefd = fd;
3704 FD_SET( (u_int)fd, &activefds);
3705 #endif
3708 static void
3709 close_and_delete_fd_from_list(SOCKET fd) {
3711 vsock_t *next;
3712 vsock_t *lsock = ISC_LIST_HEAD(fd_list);
3714 while(lsock != NULL) {
3715 next = ISC_LIST_NEXT(lsock, link);
3716 if(lsock->fd == fd) {
3717 ISC_LIST_DEQUEUE_TYPE(fd_list, lsock, link, vsock_t);
3719 switch (lsock->type) {
3720 case FD_TYPE_SOCKET:
3721 #ifdef SYS_WINNT
3722 closesocket(lsock->fd);
3723 break;
3724 #endif
3725 case FD_TYPE_FILE:
3726 (void) close(lsock->fd);
3727 break;
3728 default:
3729 msyslog(LOG_ERR, "internal error - illegal descriptor type %d - EXITING", (int)lsock->type);
3730 exit(1);
3733 free(lsock);
3735 * I/O Completion Ports don't care about select and fd_set
3737 #ifndef HAVE_IO_COMPLETION_PORT
3739 * remove from activefds
3741 FD_CLR( (u_int) fd, &activefds);
3743 if (fd == maxactivefd) {
3744 int i, newmax = 0;
3745 for (i = 0; i < maxactivefd; i++)
3746 if (FD_ISSET(i, &activefds))
3747 newmax = i;
3748 maxactivefd = newmax;
3750 #endif
3751 break;
3753 lsock = next;
3757 static void
3758 add_addr_to_list(struct sockaddr_storage *addr, struct interface *interface){
3759 #ifdef DEBUG
3760 if (find_addr_in_list(addr) == NULL) {
3761 #endif
3762 /* not there yet - add to list */
3763 remaddr_t *laddr = (remaddr_t *)emalloc(sizeof(remaddr_t));
3764 memcpy(&laddr->addr, addr, sizeof(struct sockaddr_storage));
3765 laddr->interface = interface;
3767 ISC_LIST_APPEND(remoteaddr_list, laddr, link);
3769 DPRINTF(4, ("Added addr %s to list of addresses\n",
3770 stoa(addr)));
3771 #ifdef DEBUG
3772 } else {
3773 DPRINTF(4, ("WARNING: Attempt to add duplicate addr %s to address list\n",
3774 stoa(addr)));
3776 #endif
3779 static void
3780 delete_addr_from_list(struct sockaddr_storage *addr) {
3782 remaddr_t *next;
3783 remaddr_t *laddr = ISC_LIST_HEAD(remoteaddr_list);
3785 while(laddr != NULL) {
3786 next = ISC_LIST_NEXT(laddr, link);
3787 if(SOCKCMP(&laddr->addr, addr)) {
3788 ISC_LIST_DEQUEUE_TYPE(remoteaddr_list, laddr, link, remaddr_t);
3789 DPRINTF(4, ("Deleted addr %s from list of addresses\n",
3790 stoa(addr)));
3791 free(laddr);
3792 break;
3794 laddr = next;
3798 static void
3799 delete_interface_from_list(struct interface *iface) {
3800 remaddr_t *next;
3801 remaddr_t *laddr = ISC_LIST_HEAD(remoteaddr_list);
3803 while(laddr != NULL) {
3804 next = ISC_LIST_NEXT(laddr, link);
3805 if (laddr->interface == iface) {
3806 ISC_LIST_DEQUEUE_TYPE(remoteaddr_list, laddr, link, remaddr_t);
3807 DPRINTF(4, ("Deleted addr %s for interface #%d %s from list of addresses\n",
3808 stoa(&laddr->addr), iface->ifnum, iface->name));
3809 free(laddr);
3811 laddr = next;
3815 static struct interface *
3816 find_addr_in_list(struct sockaddr_storage *addr) {
3818 remaddr_t *next;
3819 remaddr_t *laddr = ISC_LIST_HEAD(remoteaddr_list);
3820 DPRINTF(4, ("Searching for addr %s in list of addresses - ",
3821 stoa(addr)));
3823 while(laddr != NULL) {
3824 next = ISC_LIST_NEXT(laddr, link);
3825 if(SOCKCMP(&laddr->addr, addr)) {
3826 DPRINTF(4, ("FOUND\n"));
3827 return laddr->interface;
3829 else
3830 laddr = next;
3832 DPRINTF(4, ("NOT FOUND\n"));
3833 return NULL; /* Not found */
3837 * Find the given address with the associated flag in the list
3839 static struct interface *
3840 find_flagged_addr_in_list(struct sockaddr_storage *addr, int flag) {
3842 remaddr_t *next;
3843 remaddr_t *laddr = ISC_LIST_HEAD(remoteaddr_list);
3844 DPRINTF(4, ("Finding addr %s in list of addresses\n",
3845 stoa(addr)));
3847 while(laddr != NULL) {
3848 next = ISC_LIST_NEXT(laddr, link);
3849 if(SOCKCMP(&laddr->addr, addr) && (laddr->interface->flags & flag)) {
3850 return laddr->interface;
3851 break;
3853 else
3854 laddr = next;
3856 return NULL; /* Not found */
3859 #ifdef HAS_ROUTING_SOCKET
3860 #include <net/route.h>
3862 #ifndef UPDATE_GRACE
3863 #define UPDATE_GRACE 2 /* wait UPDATE_GRACE seconds before scanning */
3864 #endif
3866 static void
3867 process_routing_msgs(struct asyncio_reader *reader)
3869 char buffer[5120];
3870 char *p = buffer;
3872 int cnt;
3874 if (disable_dynamic_updates) {
3876 * discard ourselves if we are not need any more
3877 * usually happens when running unprivileged
3879 remove_asyncio_reader(reader);
3880 delete_asyncio_reader(reader);
3881 return;
3884 cnt = read(reader->fd, buffer, sizeof(buffer));
3886 if (cnt < 0) {
3887 msyslog(LOG_ERR, "i/o error on routing socket %m - disabling");
3888 remove_asyncio_reader(reader);
3889 delete_asyncio_reader(reader);
3890 return;
3894 * process routing message
3896 while ((p + sizeof(struct rt_msghdr)) <= (buffer + cnt))
3898 struct rt_msghdr *rtm;
3900 rtm = (struct rt_msghdr *)p;
3901 if (rtm->rtm_version != RTM_VERSION) {
3902 msyslog(LOG_ERR, "version mismatch on routing socket %m - disabling");
3903 remove_asyncio_reader(reader);
3904 delete_asyncio_reader(reader);
3905 return;
3908 switch (rtm->rtm_type) {
3909 #ifdef RTM_NEWADDR
3910 case RTM_NEWADDR:
3911 #endif
3912 #ifdef RTM_DELADDR
3913 case RTM_DELADDR:
3914 #endif
3915 #ifdef RTM_ADD
3916 case RTM_ADD:
3917 #endif
3918 #ifdef RTM_DELETE
3919 case RTM_DELETE:
3920 #endif
3921 #ifdef RTM_REDIRECT
3922 case RTM_REDIRECT:
3923 #endif
3924 #ifdef RTM_CHANGE
3925 case RTM_CHANGE:
3926 #endif
3927 #ifdef RTM_LOSING
3928 case RTM_LOSING:
3929 #endif
3930 #ifdef RTM_IFINFO
3931 case RTM_IFINFO:
3932 #endif
3933 #ifdef RTM_IFANNOUNCE
3934 case RTM_IFANNOUNCE:
3935 #endif
3937 * we are keen on new and deleted addresses and if an interface goes up and down or routing changes
3939 DPRINTF(3, ("routing message op = %d: scheduling interface update\n", rtm->rtm_type));
3940 timer_interfacetimeout(current_time + UPDATE_GRACE);
3941 break;
3942 default:
3944 * the rest doesn't bother us.
3946 DPRINTF(4, ("routing message op = %d: ignored\n", rtm->rtm_type));
3947 break;
3949 p += rtm->rtm_msglen;
3954 * set up routing notifications
3956 static void
3957 init_async_notifications()
3959 struct asyncio_reader *reader;
3960 int fd = socket(PF_ROUTE, SOCK_RAW, 0);
3962 if (fd >= 0) {
3963 fd = move_fd(fd);
3964 init_nonblocking_io(fd);
3965 #if defined(HAVE_SIGNALED_IO)
3966 init_socket_sig(fd);
3967 #endif /* HAVE_SIGNALED_IO */
3969 reader = new_asyncio_reader();
3971 reader->fd = fd;
3972 reader->receiver = process_routing_msgs;
3974 add_asyncio_reader(reader, FD_TYPE_SOCKET);
3975 msyslog(LOG_INFO, "Listening on routing socket on fd #%d for interface updates", fd);
3976 } else {
3977 msyslog(LOG_ERR, "unable to open routing socket (%m) - using polled interface update");
3980 #else
3981 static void
3982 init_async_notifications()
3985 #endif