2 * ntp_io.c - input/output routines for ntpd. The socket-opening code
3 * was shamelessly stolen from ntpd.
10 #include "ntp_machine.h"
14 #include "ntp_refclock.h"
15 #include "ntp_stdlib.h"
16 #include "ntp_request.h"
18 #include "ntp_unixtime.h"
20 /* Don't include ISC's version of IPv6 variables and structures */
22 #include <isc/interfaceiter.h>
24 #include <isc/result.h>
32 #ifdef HAVE_SYS_PARAM_H
33 # include <sys/param.h>
34 #endif /* HAVE_SYS_PARAM_H */
35 #ifdef HAVE_SYS_IOCTL_H
36 # include <sys/ioctl.h>
38 #ifdef HAVE_SYS_SOCKIO_H /* UXPV: SIOC* #defines (Frank Vance <fvance@waii.com>) */
39 # include <sys/sockio.h>
46 * setsockopt does not always have the same arg declaration
47 * across all platforms. If it's not defined we make it empty
50 #ifndef SETSOCKOPT_ARG_CAST
51 #define SETSOCKOPT_ARG_CAST
55 * Set up some macros to look for IPv6 and IPv6 multicast
58 #if defined(ISC_PLATFORM_HAVEIPV6) && !defined(DISABLE_IPV6)
60 #define INCLUDE_IPV6_SUPPORT
62 #if defined(INCLUDE_IPV6_SUPPORT) && defined(IPV6_JOIN_GROUP) && defined(IPV6_LEAVE_GROUP)
63 #define INCLUDE_IPV6_MULTICAST_SUPPORT
65 #endif /* IPV6 Multicast Support */
66 #endif /* IPv6 Support */
68 extern int listen_to_virtual_ips;
69 extern const char *specific_interface;
71 #if defined(SO_TIMESTAMP) && defined(SCM_TIMESTAMP)
72 #if defined(CMSG_FIRSTHDR)
73 #define HAVE_TIMESTAMP
74 #define USE_TIMESTAMP_CMSG
75 #ifndef TIMESTAMP_CTLMSGBUF_SIZE
76 #define TIMESTAMP_CTLMSGBUF_SIZE 1536 /* moderate default */
79 /* fill in for old/other timestamp interfaces */
83 #if defined(SYS_WINNT)
84 #include <transmitbuff.h>
85 #include <isc/win32os.h>
87 * Define this macro to control the behavior of connection
88 * resets on UDP sockets. See Microsoft KnowledgeBase Article Q263823
90 * NOTE: This requires that Windows 2000 systems install Service Pack 2
93 #ifndef SIO_UDP_CONNRESET
94 #define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR,12)
100 * We do asynchronous input using the SIGIO facility. A number of
101 * recvbuf buffers are preallocated for input. In the signal
102 * handler we poll to see which sockets are ready and read the
103 * packets from them into the recvbuf's along with a time stamp and
104 * an indication of the source host and the interface it was received
105 * through. This allows us to get as accurate receive time stamps
106 * as possible independent of other processing going on.
108 * We watch the number of recvbufs available to the signal handler
109 * and allocate more when this number drops below the low water
110 * mark. If the signal handler should run out of buffers in the
111 * interim it will drop incoming frames, the idea being that it is
112 * better to drop a packet than to be inaccurate.
117 * Other statistics of possible interest
119 volatile u_long packets_dropped; /* total number of packets dropped on reception */
120 volatile u_long packets_ignored; /* packets received on wild card interface */
121 volatile u_long packets_received; /* total number of packets received */
122 u_long packets_sent; /* total number of packets sent */
123 u_long packets_notsent; /* total number of packets which couldn't be sent */
125 volatile u_long handler_calls; /* number of calls to interrupt handler */
126 volatile u_long handler_pkts; /* number of pkts received by handler */
127 u_long io_timereset; /* time counters were reset */
132 struct interface *any_interface; /* default ipv4 interface */
133 struct interface *any6_interface; /* default ipv6 interface */
134 struct interface *loopback_interface; /* loopback ipv4 interface */
136 int ninterfaces; /* Total number of interfaces */
138 volatile int disable_dynamic_updates; /* when set to != 0 dynamic updates won't happen */
142 * Refclock stuff. We keep a chain of structures with data concerning
143 * the guys we are doing I/O for.
145 static struct refclockio *refio;
146 #endif /* REFCLOCK */
150 * Define what the possible "soft" errors can be. These are non-fatal returns
151 * of various network related functions, like recv() and so on.
153 * For some reason, BSDI (and perhaps others) will sometimes return <0
154 * from recv() but will have errno==0. This is broken, but we have to
155 * work around it here.
157 #define SOFT_ERROR(e) ((e) == EAGAIN || \
158 (e) == EWOULDBLOCK || \
163 * File descriptor masks etc. for call to select
164 * Not needed for I/O Completion Ports
169 * bit alternating value to detect verified interfaces during an update cycle
171 static u_char sys_interphase = 0;
173 static struct interface *new_interface P((struct interface *));
174 static void add_interface P((struct interface *));
175 static int update_interfaces P((u_short, interface_receiver_t, void *));
176 static void remove_interface P((struct interface *));
177 static struct interface *create_interface P((u_short, struct interface *));
179 static int move_fd P((SOCKET));
182 * Multicast functions
184 static isc_boolean_t addr_ismulticast P((struct sockaddr_storage *));
186 * Not all platforms support multicast
189 static isc_boolean_t socket_multicast_enable P((struct interface *, int, struct sockaddr_storage *));
190 static isc_boolean_t socket_multicast_disable P((struct interface *, struct sockaddr_storage *));
194 static void print_interface P((struct interface *, char *, char *));
195 #define DPRINT_INTERFACE(_LVL_, _ARGS_) do { if (debug >= (_LVL_)) { print_interface _ARGS_; } } while (0)
197 #define DPRINT_INTERFACE(_LVL_, _ARGS_)
200 typedef struct vsock vsock_t;
201 enum desc_type { FD_TYPE_SOCKET, FD_TYPE_FILE };
206 ISC_LINK(vsock_t) link;
209 #if !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET)
211 * async notification processing (e. g. routing sockets)
214 * support for receiving data on fd that is not a refclock or a socket
215 * like e. g. routing sockets
217 struct asyncio_reader {
218 SOCKET fd; /* fd to be read */
219 void *data; /* possibly local data */
220 void (*receiver)(struct asyncio_reader *); /* input handler */
221 ISC_LINK(struct asyncio_reader) link; /* the list this is being kept in */
224 ISC_LIST(struct asyncio_reader) asyncio_reader_list;
226 static void delete_asyncio_reader P((struct asyncio_reader *));
227 static struct asyncio_reader *new_asyncio_reader P((void));
228 static void add_asyncio_reader P((struct asyncio_reader *, enum desc_type));
229 static void remove_asyncio_reader P((struct asyncio_reader *));
231 #endif /* !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET) */
233 static void init_async_notifications P((void));
235 static int create_sockets P((u_short));
236 static SOCKET open_socket P((struct sockaddr_storage *, int, int, struct interface *));
237 static char * fdbits P((int, fd_set *));
238 static void set_reuseaddr P((int));
239 static isc_boolean_t socket_broadcast_enable P((struct interface *, SOCKET, struct sockaddr_storage *));
240 static isc_boolean_t socket_broadcast_disable P((struct interface *, struct sockaddr_storage *));
242 ISC_LIST(vsock_t) fd_list;
244 typedef struct remaddr remaddr_t;
247 struct sockaddr_storage addr;
248 struct interface *interface;
249 ISC_LINK(remaddr_t) link;
252 ISC_LIST(remaddr_t) remoteaddr_list;
254 ISC_LIST(struct interface) inter_list;
256 static struct interface *wildipv4 = NULL;
257 static struct interface *wildipv6 = NULL;
259 static void add_fd_to_list P((SOCKET, enum desc_type));
260 static void close_and_delete_fd_from_list P((SOCKET));
261 static void add_addr_to_list P((struct sockaddr_storage *, struct interface *));
262 static void delete_addr_from_list P((struct sockaddr_storage *));
263 static struct interface *find_addr_in_list P((struct sockaddr_storage *));
264 static struct interface *find_flagged_addr_in_list P((struct sockaddr_storage *, int));
265 static void create_wildcards P((u_short));
266 static isc_boolean_t address_okay P((struct interface *));
267 static void convert_isc_if P((isc_interface_t *, struct interface *, u_short));
268 static void delete_interface_from_list P((struct interface *));
269 static struct interface *getinterface P((struct sockaddr_storage *, int));
270 static struct interface *findlocalinterface P((struct sockaddr_storage *, int));
271 static struct interface *findlocalcastinterface P((struct sockaddr_storage *, int));
274 * Routines to read the ntp packets
276 #if !defined(HAVE_IO_COMPLETION_PORT)
277 static inline int read_network_packet P((SOCKET, struct interface *, l_fp));
278 static inline int read_refclock_packet P((SOCKET, struct refclockio *, l_fp));
283 * Windows 2000 systems incorrectly cause UDP sockets using WASRecvFrom
284 * to not work correctly, returning a WSACONNRESET error when a WSASendTo
285 * fails with an "ICMP port unreachable" response and preventing the
286 * socket from using the WSARecvFrom in subsequent operations.
287 * The function below fixes this, but requires that Windows 2000
288 * Service Pack 2 or later be installed on the system. NT 4.0
289 * systems are not affected by this and work correctly.
290 * See Microsoft Knowledge Base Article Q263823 for details of this.
293 connection_reset_fix(SOCKET fd) {
294 DWORD dwBytesReturned = 0;
295 BOOL bNewBehavior = FALSE;
298 if(isc_win32os_majorversion() < 5)
299 return (ISC_R_SUCCESS); /* NT 4.0 has no problem */
301 /* disable bad behavior using IOCTL: SIO_UDP_CONNRESET */
302 status = WSAIoctl(fd, SIO_UDP_CONNRESET, &bNewBehavior,
303 sizeof(bNewBehavior), NULL, 0,
304 &dwBytesReturned, NULL, NULL);
305 if (status != SOCKET_ERROR)
306 return (ISC_R_SUCCESS);
308 return (ISC_R_UNEXPECTED);
313 * on Unix systems the stdio library typically
314 * makes use of file descriptors in the lower
315 * integer range. stdio usually will make use
316 * of the file descriptor in the range of
318 * in order to keep this range clean for socket
319 * file descriptors we attempt to move them above
320 * FOPEM_MAX. This is not as easy as it sounds as
321 * FOPEN_MAX changes from implementation to implementation
322 * and may exceed to current file decriptor limits.
323 * We are using following strategy:
324 * - keep a current socket fd boundary initialized with
325 * max(0, min(getdtablesize() - FD_CHUNK, FOPEN_MAX))
326 * - attempt to move the descriptor to the boundary or
328 * - if that fails and boundary > 0 set boundary
329 * to min(0, socket_fd_boundary - FD_CHUNK)
331 * if failure and boundary == 0 return old fd
332 * - on success close old fd return new fd
335 * - fds will be moved above the socket fd boundary
336 * if at all possible.
337 * - the socket boundary will be reduced until
338 * allocation is possible or 0 is reached - at this
339 * point the algrithm will be disabled
341 static int move_fd(SOCKET fd)
343 #if !defined(SYS_WINNT) && defined(F_DUPFD)
348 * number of fds we would like to have for
349 * stdio FILE* available.
350 * we can pick a "low" number as our use of
351 * FILE* is limited to log files and temporarily
352 * to data and config files. Except for log files
353 * we don't keep the other FILE* open beyond the
354 * scope of the function that opened it.
356 #ifndef FD_PREFERRED_SOCKBOUNDARY
357 #define FD_PREFERRED_SOCKBOUNDARY 48
360 #ifndef HAVE_GETDTABLESIZE
362 * if we have no idea about the max fd value set up things
363 * so we will start at FOPEN_MAX
365 #define getdtablesize() (FOPEN_MAX+FD_CHUNK)
369 #define FOPEN_MAX 20 /* assume that for the lack of anything better */
371 static SOCKET socket_boundary = -1;
375 * check whether boundary has be set up
378 if (socket_boundary == -1) {
379 socket_boundary = max(0, min(getdtablesize() - FD_CHUNK,
380 min(FOPEN_MAX, FD_PREFERRED_SOCKBOUNDARY)));
382 msyslog(LOG_DEBUG, "ntp_io: estimated max descriptors: %d, initial socket boundary: %d",
383 getdtablesize(), socket_boundary);
388 * Leave a space for stdio to work in. potentially moving the
389 * socket_boundary lower until allocation succeeds.
392 if (fd >= 0 && fd < socket_boundary) {
393 /* inside reserved range: attempt to move fd */
394 newfd = fcntl(fd, F_DUPFD, socket_boundary);
397 /* success: drop the old one - return the new one */
402 /* outside reserved range: no work - return the original one */
405 socket_boundary = max(0, socket_boundary - FD_CHUNK);
407 msyslog(LOG_DEBUG, "ntp_io: selecting new socket boundary: %d",
410 } while (socket_boundary > 0);
411 #endif /* !defined(SYS_WINNT) && defined(F_DUPFD) */
417 * collect timing information for various processing
418 * paths. currently we only pass then on to the file
419 * for later processing. this could also do histogram
420 * based analysis in other to reduce the load (and skew)
421 * dur to the file output
424 collect_timing(struct recvbuf *rb, const char *tag, int count, l_fp *dts)
428 snprintf(buf, sizeof(buf), "%s %d %s %s",
430 ((rb->dstadr) ? stoa(&rb->recv_srcadr) : "-REFCLOCK-") : "-",
431 count, lfptoa(dts, 9), tag);
432 record_timing_stats(buf);
437 * About dynamic interfaces, sockets, reception and more...
439 * the code solves following tasks:
441 * - keep a current list of active interfaces in order
442 * to bind to to the interface address on NTP_PORT so that
443 * all wild and specific bindings for NTP_PORT are taken by ntpd
444 * to avoid other daemons messing with the time or sockets.
445 * - all interfaces keep a list of peers that are referencing
446 * the interface in order to quickly re-assign the peers to
447 * new interface in case an interface is deleted (=> gone from system or
449 * - have a preconfigured socket ready with the right local address
450 * for transmission and reception
451 * - have an address list for all destination addresses used within ntpd
452 * to find the "right" preconfigured socket.
453 * - facilitate updating the internal interface list with respect to
454 * the current kernel state
458 * - mapping of multicast addresses to the interface affected is not always
459 * one to one - especially on hosts with multiple interfaces
460 * the code here currently allocates a separate interface entry for those
461 * multicast addresses
462 * iff it is able to bind to a *new* socket with the multicast address (flags |= MCASTIF)
463 * in case of failure the multicast address is bound to an existing interface.
464 * - on some systems it is perfectly legal to assign the same address to
465 * multiple interfaces. Therefore this code does not keep a list of interfaces
466 * but a list of interfaces that represent a unique address as determined by the kernel
467 * by the procedure in findlocalinterface. Thus it is perfectly legal to see only
468 * one representative of a group of real interfaces if they share the same address.
470 * Frank Kardel 20050910
474 * init_io - initialize I/O data structures and call socket creation routine
480 if (!Win32InitSockets())
482 netsyslog(LOG_ERR, "No useable winsock.dll: %m");
486 #endif /* SYS_WINNT */
489 * Init buffer free list and stat counters
491 init_recvbuff(RECV_INIT);
493 packets_dropped = packets_received = 0;
495 packets_sent = packets_notsent = 0;
496 handler_calls = handler_pkts = 0;
498 loopback_interface = NULL;
499 any_interface = NULL;
500 any6_interface = NULL;
506 #if defined(HAVE_SIGNALED_IO)
510 ISC_LIST_INIT(fd_list);
512 #if !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET)
513 ISC_LIST_INIT(asyncio_reader_list);
516 ISC_LIST_INIT(remoteaddr_list);
518 ISC_LIST_INIT(inter_list);
524 (void) create_sockets(htons(NTP_PORT));
527 init_async_notifications();
529 DPRINTF(3, ("init_io: maxactivefd %d\n", maxactivefd));
534 * function to dump the contents of the interface structure
535 * for debugging use only.
538 interface_dump(struct interface *itf)
542 /* Limit the size of the sockaddr_storage hex dump */
543 int maxsize = min(32, sizeof(struct sockaddr_storage));
545 printf("Dumping interface: %p\n", itf);
546 printf("fd = %d\n", itf->fd);
547 printf("bfd = %d\n", itf->bfd);
548 printf("sin = %s,\n", stoa(&(itf->sin)));
549 cp = (u_char*) &(itf->sin);
550 for(i = 0; i < maxsize; i++)
552 printf("%02x", *cp++);
557 printf("bcast = %s,\n", stoa(&(itf->bcast)));
558 cp = (u_char*) &(itf->bcast);
559 for(i = 0; i < maxsize; i++)
561 printf("%02x", *cp++);
566 printf("mask = %s,\n", stoa(&(itf->mask)));
567 cp = (u_char*) &(itf->mask);
568 for(i = 0; i < maxsize; i++)
570 printf("%02x", *cp++);
575 printf("name = %s\n", itf->name);
576 printf("flags = 0x%08x\n", itf->flags);
577 printf("last_ttl = %d\n", itf->last_ttl);
578 printf("addr_refid = %08x\n", itf->addr_refid);
579 printf("num_mcast = %d\n", itf->num_mcast);
580 printf("received = %ld\n", itf->received);
581 printf("sent = %ld\n", itf->sent);
582 printf("notsent = %ld\n", itf->notsent);
583 printf("ifindex = %u\n", itf->ifindex);
584 printf("scopeid = %u\n", itf->scopeid);
585 printf("peercnt = %u\n", itf->peercnt);
586 printf("phase = %u\n", itf->phase);
590 * print_interface - helper to output debug information
593 print_interface(struct interface *iface, char *pfx, char *sfx)
595 printf("%sinterface #%d: fd=%d, bfd=%d, name=%s, flags=0x%x, scope=%d, ifindex=%d",
604 /* Leave these as three printf calls. */
606 stoa((&iface->sin)));
607 if (iface->flags & INT_BROADCAST)
608 printf(", bcast=%s,",
609 stoa((&iface->bcast)));
610 if (iface->family == AF_INET)
612 stoa((&iface->mask)));
613 printf(", %s:%s", iface->ignore_packets == ISC_FALSE ? "Enabled" : "Disabled", sfx);
614 if (debug > 4) /* in-depth debugging only */
615 interface_dump(iface);
620 #if !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET)
622 * create an asyncio_reader structure
624 static struct asyncio_reader *
627 struct asyncio_reader *reader;
629 reader = (struct asyncio_reader *)emalloc(sizeof(struct asyncio_reader));
631 memset((char *)reader, 0, sizeof(*reader));
632 ISC_LINK_INIT(reader, link);
633 reader->fd = INVALID_SOCKET;
641 delete_asyncio_reader(struct asyncio_reader *reader)
647 * add asynchio_reader
650 add_asyncio_reader(struct asyncio_reader *reader, enum desc_type type)
652 ISC_LIST_APPEND(asyncio_reader_list, reader, link);
653 add_fd_to_list(reader->fd, type);
657 * remove asynchio_reader
660 remove_asyncio_reader(struct asyncio_reader *reader)
662 ISC_LIST_UNLINK_TYPE(asyncio_reader_list, reader, link, struct asyncio_reader);
664 if (reader->fd != INVALID_SOCKET)
665 close_and_delete_fd_from_list(reader->fd);
667 reader->fd = INVALID_SOCKET;
669 #endif /* !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET) */
672 * interface list enumerator - visitor pattern
675 interface_enumerate(interface_receiver_t receiver, void *data)
677 interface_info_t ifi;
678 struct interface *interf;
680 ifi.action = IFS_EXISTS;
682 for (interf = ISC_LIST_HEAD(inter_list);
684 interf = ISC_LIST_NEXT(interf, link)) {
685 ifi.interface = interf;
686 receiver(data, &ifi);
691 * do standard initialization of interface structure
694 init_interface(struct interface *interface)
696 memset((char *)interface, 0, sizeof(struct interface));
697 ISC_LINK_INIT(interface, link);
698 ISC_LIST_INIT(interface->peers);
699 interface->fd = INVALID_SOCKET;
700 interface->bfd = INVALID_SOCKET;
701 interface->num_mcast = 0;
702 interface->received = 0;
704 interface->notsent = 0;
705 interface->peercnt = 0;
706 interface->phase = sys_interphase;
710 * create new interface structure initialize from
711 * template structure or via standard initialization
714 static struct interface *
715 new_interface(struct interface *interface)
717 static u_int sys_ifnum = 0;
719 struct interface *iface = (struct interface *)emalloc(sizeof(struct interface));
721 if (interface != NULL)
723 memcpy((char*)iface, (char*)interface, sizeof(*interface));
727 init_interface(iface);
730 iface->ifnum = sys_ifnum++; /* count every new instance of an interface in the system */
731 iface->starttime = current_time;
737 * return interface storage into free memory pool
740 delete_interface(struct interface *interface)
746 * link interface into list of known interfaces
749 add_interface(struct interface *interface)
752 * Calculate the address hash
754 interface->addr_refid = addr2refid(&interface->sin);
756 ISC_LIST_APPEND(inter_list, interface, link);
761 * remove interface from known interface list and clean up
762 * associated resources
765 remove_interface(struct interface *interface)
767 struct sockaddr_storage resmask;
769 ISC_LIST_UNLINK_TYPE(inter_list, interface, link, struct interface);
771 delete_interface_from_list(interface);
773 if (interface->fd != INVALID_SOCKET)
775 msyslog(LOG_INFO, "Deleting interface #%d %s, %s#%d, interface stats: received=%ld, sent=%ld, dropped=%ld, active_time=%ld secs",
778 stoa((&interface->sin)),
779 NTP_PORT, /* XXX should extract port from sin structure */
783 current_time - interface->starttime);
785 close_and_delete_fd_from_list(interface->fd);
788 if (interface->bfd != INVALID_SOCKET)
790 msyslog(LOG_INFO, "Deleting interface #%d %s, broadcast address %s#%d",
793 stoa((&interface->bcast)),
794 (u_short) NTP_PORT); /* XXX extract port from sin structure */
795 close_and_delete_fd_from_list(interface->bfd);
799 ntp_monclearinterface(interface);
801 /* remove restrict interface entry */
804 * Blacklist bound interface address
806 SET_HOSTMASK(&resmask, interface->sin.ss_family);
807 hack_restrict(RESTRICT_REMOVEIF, &interface->sin, &resmask,
808 RESM_NTPONLY|RESM_INTERFACE, RES_IGNORE);
812 list_if_listening(struct interface *interface, u_short port)
814 msyslog(LOG_INFO, "Listening on interface #%d %s, %s#%d %s",
817 stoa((&interface->sin)),
818 ntohs( (u_short) port),
819 (interface->ignore_packets == ISC_FALSE) ?
820 "Enabled": "Disabled");
824 create_wildcards(u_short port) {
825 isc_boolean_t okipv4 = ISC_TRUE;
827 * create pseudo-interface with wildcard IPv4 address
830 if(isc_net_probeipv4() != ISC_R_SUCCESS)
834 if(okipv4 == ISC_TRUE) {
835 struct interface *interface = new_interface(NULL);
837 interface->family = AF_INET;
838 interface->sin.ss_family = AF_INET;
839 ((struct sockaddr_in*)&interface->sin)->sin_addr.s_addr = htonl(INADDR_ANY);
840 ((struct sockaddr_in*)&interface->sin)->sin_port = port;
841 (void) strncpy(interface->name, "wildcard", sizeof(interface->name));
842 interface->mask.ss_family = AF_INET;
843 ((struct sockaddr_in*)&interface->mask)->sin_addr.s_addr = htonl(~(u_int32)0);
844 interface->flags = INT_BROADCAST | INT_UP | INT_WILDCARD;
845 interface->ignore_packets = ISC_TRUE;
848 * enable possible multicast reception on the broadcast socket
850 interface->bcast.ss_family = AF_INET;
851 ((struct sockaddr_in*)&interface->bcast)->sin_port = port;
852 ((struct sockaddr_in*)&interface->bcast)->sin_addr.s_addr = htonl(INADDR_ANY);
854 interface->fd = open_socket(&interface->sin,
855 interface->flags, 1, interface);
857 if (interface->fd != INVALID_SOCKET) {
858 wildipv4 = interface;
859 any_interface = interface;
861 add_addr_to_list(&interface->sin, interface);
862 add_interface(interface);
863 list_if_listening(interface, port);
865 msyslog(LOG_ERR, "unable to bind to wildcard socket address %s - another process may be running - EXITING",
866 stoa((&interface->sin)));
871 #ifdef INCLUDE_IPV6_SUPPORT
873 * create pseudo-interface with wildcard IPv6 address
875 if (isc_net_probeipv6() == ISC_R_SUCCESS) {
876 struct interface *interface = new_interface(NULL);
878 interface->family = AF_INET6;
879 interface->sin.ss_family = AF_INET6;
880 ((struct sockaddr_in6*)&interface->sin)->sin6_addr = in6addr_any;
881 ((struct sockaddr_in6*)&interface->sin)->sin6_port = port;
882 # ifdef ISC_PLATFORM_HAVESCOPEID
883 ((struct sockaddr_in6*)&interface->sin)->sin6_scope_id = 0;
885 (void) strncpy(interface->name, "wildcard", sizeof(interface->name));
886 interface->mask.ss_family = AF_INET6;
887 memset(&((struct sockaddr_in6*)&interface->mask)->sin6_addr.s6_addr, 0xff, sizeof(struct in6_addr));
888 interface->flags = INT_UP | INT_WILDCARD;
889 interface->ignore_packets = ISC_TRUE;
891 interface->fd = open_socket(&interface->sin,
892 interface->flags, 1, interface);
894 if (interface->fd != INVALID_SOCKET) {
895 wildipv6 = interface;
896 any6_interface = interface;
897 add_addr_to_list(&interface->sin, interface);
898 add_interface(interface);
899 list_if_listening(interface, port);
901 msyslog(LOG_ERR, "unable to bind to wildcard socket address %s - another process may be running - EXITING",
902 stoa((&interface->sin)));
911 address_okay(struct interface *iface) {
913 DPRINTF(4, ("address_okay: listen Virtual: %d, IF name: %s\n",
914 listen_to_virtual_ips, iface->name));
917 * Always allow the loopback
919 if((iface->flags & INT_LOOPBACK) != 0) {
920 DPRINTF(4, ("address_okay: loopback - OK\n"));
925 * Check if the interface is specified
927 if (specific_interface != NULL) {
928 if (strcasecmp(iface->name, specific_interface) == 0) {
929 DPRINTF(4, ("address_okay: specific interface name matched - OK\n"));
932 DPRINTF(4, ("address_okay: specific interface name NOT matched - FAIL\n"));
937 if (listen_to_virtual_ips == 0 &&
938 (strchr(iface->name, (int)':') != NULL)) {
939 DPRINTF(4, ("address_okay: virtual ip/alias - FAIL\n"));
944 DPRINTF(4, ("address_okay: OK\n"));
949 convert_isc_if(isc_interface_t *isc_if, struct interface *itf, u_short port)
952 itf->family = (short) isc_if->af;
953 strcpy(itf->name, isc_if->name);
955 if(isc_if->af == AF_INET) {
956 itf->sin.ss_family = (u_short) isc_if->af;
957 memcpy(&(((struct sockaddr_in*)&itf->sin)->sin_addr),
958 &(isc_if->address.type.in),
959 sizeof(struct in_addr));
960 ((struct sockaddr_in*)&itf->sin)->sin_port = port;
962 if((isc_if->flags & INTERFACE_F_BROADCAST) != 0) {
963 itf->flags |= INT_BROADCAST;
964 itf->bcast.ss_family = itf->sin.ss_family;
965 memcpy(&(((struct sockaddr_in*)&itf->bcast)->sin_addr),
966 &(isc_if->broadcast.type.in),
967 sizeof(struct in_addr));
968 ((struct sockaddr_in*)&itf->bcast)->sin_port = port;
971 itf->mask.ss_family = itf->sin.ss_family;
972 memcpy(&(((struct sockaddr_in*)&itf->mask)->sin_addr),
973 &(isc_if->netmask.type.in),
974 sizeof(struct in_addr));
975 ((struct sockaddr_in*)&itf->mask)->sin_port = port;
977 #ifdef INCLUDE_IPV6_SUPPORT
978 else if (isc_if->af == AF_INET6) {
979 itf->sin.ss_family = (u_short) isc_if->af;
980 memcpy(&(((struct sockaddr_in6 *)&itf->sin)->sin6_addr),
981 &(isc_if->address.type.in6),
982 sizeof(((struct sockaddr_in6 *)&itf->sin)->sin6_addr));
983 ((struct sockaddr_in6 *)&itf->sin)->sin6_port = port;
985 #ifdef ISC_PLATFORM_HAVESCOPEID
986 ((struct sockaddr_in6 *)&itf->sin)->sin6_scope_id = isc_netaddr_getzone(&isc_if->address);
987 itf->scopeid = isc_netaddr_getzone(&isc_if->address);
989 itf->mask.ss_family = itf->sin.ss_family;
990 memcpy(&(((struct sockaddr_in6 *)&itf->mask)->sin6_addr),
991 &(isc_if->netmask.type.in6),
992 sizeof(struct in6_addr));
993 ((struct sockaddr_in6 *)&itf->mask)->sin6_port = port;
994 /* Copy the interface index */
995 itf->ifindex = isc_if->ifindex;
997 #endif /* INCLUDE_IPV6_SUPPORT */
1000 /* Process the rest of the flags */
1002 if((isc_if->flags & INTERFACE_F_UP) != 0)
1003 itf->flags |= INT_UP;
1004 if((isc_if->flags & INTERFACE_F_LOOPBACK) != 0)
1005 itf->flags |= INT_LOOPBACK;
1006 if((isc_if->flags & INTERFACE_F_POINTTOPOINT) != 0)
1007 itf->flags |= INT_PPP;
1008 if((isc_if->flags & INTERFACE_F_MULTICAST) != 0)
1009 itf->flags |= INT_MULTICAST;
1016 * some OSes have been observed to keep
1017 * cached routes even when more specific routes
1019 * this can be mitigated by re-binding
1023 refresh_interface(struct interface * interface)
1025 #ifdef OS_MISSES_SPECIFIC_ROUTE_UPDATES
1026 if (interface->fd != INVALID_SOCKET)
1028 close_and_delete_fd_from_list(interface->fd);
1029 interface->fd = open_socket(&interface->sin,
1030 interface->flags, 0, interface);
1032 * reset TTL indication so TTL is is set again
1035 interface->last_ttl = 0;
1036 return interface->fd != INVALID_SOCKET;
1040 return 0; /* invalid sockets are not refreshable */
1042 #else /* !OS_MISSES_SPECIFIC_ROUTE_UPDATES */
1043 return interface->fd != INVALID_SOCKET;
1044 #endif /* !OS_MISSES_SPECIFIC_ROUTE_UPDATES */
1048 * interface_update - externally callable update function
1051 interface_update(interface_receiver_t receiver, void *data)
1053 if (!disable_dynamic_updates) {
1054 int new_interface_found;
1057 new_interface_found = update_interfaces(htons(NTP_PORT), receiver, data);
1060 if (new_interface_found) {
1062 msyslog(LOG_DEBUG, "new interface(s) found: waking up resolver");
1065 /* wake up the resolver thread */
1066 if (ResolverEventHandle != NULL)
1067 SetEvent(ResolverEventHandle);
1069 /* write any single byte to the pipe to wake up the resolver process */
1070 write( resolver_pipe_fd[1], &new_interface_found, 1 );
1077 * find out if a given interface structure contains
1078 * a wildcard address
1081 is_wildcard_addr(struct sockaddr_storage *sas)
1083 if (sas->ss_family == AF_INET &&
1084 ((struct sockaddr_in*)sas)->sin_addr.s_addr == htonl(INADDR_ANY))
1087 #ifdef INCLUDE_IPV6_SUPPORT
1088 if (sas->ss_family == AF_INET6 &&
1089 memcmp(&((struct sockaddr_in6*)sas)->sin6_addr, &in6addr_any,
1090 sizeof(in6addr_any) == 0))
1097 #ifdef OS_NEEDS_REUSEADDR_FOR_IFADDRBIND
1099 * enable/disable re-use of wildcard address socket
1102 set_wildcard_reuse(int family, int on)
1107 SOCKET fd = INVALID_SOCKET;
1109 onoff = on ? &onvalue : &offvalue;
1113 if (any_interface) {
1114 fd = any_interface->fd;
1118 #ifdef INCLUDE_IPV6_SUPPORT
1120 if (any6_interface) {
1121 fd = any6_interface->fd;
1124 #endif /* !INCLUDE_IPV6_SUPPORT */
1127 if (fd != INVALID_SOCKET) {
1128 if (setsockopt(fd, SOL_SOCKET,
1129 SO_REUSEADDR, (char *)onoff,
1131 netsyslog(LOG_ERR, "set_wildcard_reuse: setsockopt(SO_REUSEADDR, %s) failed: %m", *onoff ? "on" : "off");
1133 DPRINTF(4, ("set SO_REUSEADDR to %s on %s\n", *onoff ? "ON" : "OFF",
1134 stoa((family == AF_INET) ?
1135 &any_interface->sin : &any6_interface->sin)));
1138 #endif /* OS_NEEDS_REUSEADDR_FOR_IFADDRBIND */
1141 * update_interface strategy
1143 * toggle configuration phase
1146 * forall currently existing interfaces
1147 * if address is known:
1148 * drop socket - rebind again
1150 * if address is NOT known:
1151 * attempt to create a new interface entry
1154 * forall currently known non MCAST and WILDCARD interfaces
1155 * if interface does not match configuration phase (not seen in phase 1):
1156 * remove interface from known interface list
1157 * forall peers associated with this interface
1158 * disconnect peer from this interface
1161 * attempt to re-assign interfaces to peers
1168 interface_receiver_t receiver,
1172 interface_info_t ifi;
1173 isc_mem_t *mctx = NULL;
1174 isc_interfaceiter_t *iter = NULL;
1175 isc_boolean_t scan_ipv4 = ISC_FALSE;
1176 isc_boolean_t scan_ipv6 = ISC_FALSE;
1177 isc_result_t result;
1178 int new_interface_found = 0;
1180 DPRINTF(3, ("update_interfaces(%d)\n", ntohs( (u_short) port)));
1182 #ifdef INCLUDE_IPV6_SUPPORT
1183 if (isc_net_probeipv6() == ISC_R_SUCCESS)
1184 scan_ipv6 = ISC_TRUE;
1188 netsyslog(LOG_ERR, "no IPv6 interfaces found");
1191 if (isc_net_probeipv6() == ISC_R_SUCCESS)
1192 scan_ipv6 = ISC_TRUE;
1193 #if defined(ISC_PLATFORM_HAVEIPV6) && defined(DEBUG)
1196 netsyslog(LOG_ERR, "no IPv6 interfaces found");
1199 if (isc_net_probeipv4() == ISC_R_SUCCESS)
1200 scan_ipv4 = ISC_TRUE;
1204 netsyslog(LOG_ERR, "no IPv4 interfaces found");
1207 * phase one - scan interfaces
1208 * - create those that are not found
1209 * - update those that are found
1212 result = isc_interfaceiter_create(mctx, &iter);
1214 if (result != ISC_R_SUCCESS)
1217 sys_interphase ^= 0x1; /* toggle system phase for finding untouched (to be deleted) interfaces */
1219 for (result = isc_interfaceiter_first(iter);
1220 result == ISC_R_SUCCESS;
1221 result = isc_interfaceiter_next(iter))
1223 isc_interface_t isc_if;
1224 unsigned int family;
1225 struct interface interface;
1226 struct interface *iface;
1228 result = isc_interfaceiter_current(iter, &isc_if);
1230 if (result != ISC_R_SUCCESS)
1233 /* See if we have a valid family to use */
1234 family = isc_if.address.family;
1235 if (family != AF_INET && family != AF_INET6)
1237 if (scan_ipv4 == ISC_FALSE && family == AF_INET)
1239 if (scan_ipv6 == ISC_FALSE && family == AF_INET6)
1245 init_interface(&interface);
1247 convert_isc_if(&isc_if, &interface, port);
1250 * Check to see if we are going to use the interface
1251 * If we don't use it we mark it to drop any packet
1252 * received but we still must create the socket and
1253 * bind to it. This prevents other apps binding to it
1254 * and potentially causing problems with more than one
1255 * process fiddling with the clock
1257 if (address_okay(&interface) == ISC_TRUE) {
1258 interface.ignore_packets = ISC_FALSE;
1261 interface.ignore_packets = ISC_TRUE;
1264 DPRINT_INTERFACE(4, (&interface, "examining ", "\n"));
1266 if (!(interface.flags & INT_UP)) { /* interfaces must be UP to be usable */
1267 DPRINTF(4, ("skipping interface %s (%s) - DOWN\n", interface.name, stoa(&interface.sin)));
1272 * skip any interfaces UP and bound to a wildcard
1273 * address - some dhcp clients produce that in the
1276 if (is_wildcard_addr(&interface.sin))
1280 * map to local *address* in order
1281 * to map all duplicate interfaces to an interface structure
1282 * with the appropriate socket (our name space is
1283 * (ip-address) - NOT (interface name, ip-address))
1285 iface = getinterface(&interface.sin, INT_WILDCARD);
1287 if (iface && refresh_interface(iface))
1290 * found existing and up to date interface - mark present
1293 iface->phase = sys_interphase;
1294 DPRINT_INTERFACE(4, (iface, "updating ", " present\n"));
1295 ifi.action = IFS_EXISTS;
1296 ifi.interface = iface;
1298 receiver(data, &ifi);
1303 * this is new or refreshing failed - add to our interface list
1304 * if refreshing failed we will delete the interface structure in
1305 * phase 2 as the interface was not marked current. We can bind to
1306 * the address as the refresh code already closed the offending socket
1309 iface = create_interface(port, &interface);
1313 ifi.action = IFS_CREATED;
1314 ifi.interface = iface;
1316 receiver(data, &ifi);
1318 new_interface_found = 1;
1320 DPRINT_INTERFACE(3, (iface, "updating ", " new - created\n"));
1324 DPRINT_INTERFACE(3, (&interface, "updating ", " new - creation FAILED"));
1326 msyslog(LOG_INFO, "failed to initialize interface for address %s", stoa(&interface.sin));
1332 isc_interfaceiter_destroy(&iter);
1335 * phase 2 - delete gone interfaces - reassigning peers to other interfaces
1338 struct interface *interf = ISC_LIST_HEAD(inter_list);
1340 while (interf != NULL)
1342 struct interface *next = ISC_LIST_NEXT(interf, link);
1344 if (!(interf->flags & (INT_WILDCARD|INT_MCASTIF))) {
1346 * if phase does not match sys_phase this interface was not
1347 * enumerated during interface scan - so it is gone and
1348 * will be deleted here unless it is solely an MCAST/WILDCARD interface
1350 if (interf->phase != sys_interphase) {
1352 DPRINT_INTERFACE(3, (interf, "updating ", "GONE - deleting\n"));
1353 remove_interface(interf);
1355 ifi.action = IFS_DELETED;
1356 ifi.interface = interf;
1358 receiver(data, &ifi);
1360 peer = ISC_LIST_HEAD(interf->peers);
1362 * disconnect peer from deleted interface
1364 while (peer != NULL) {
1365 struct peer *npeer = ISC_LIST_NEXT(peer, ilink);
1368 * this one just lost it's interface
1370 set_peerdstadr(peer, NULL);
1376 * update globals in case we lose
1377 * a loopback interface
1379 if (interf == loopback_interface)
1380 loopback_interface = NULL;
1382 delete_interface(interf);
1390 * phase 3 - re-configure as the world has changed if necessary
1392 refresh_all_peerinterfaces();
1393 return new_interface_found;
1398 * create_sockets - create a socket for each interface plus a default
1399 * socket for when we don't know where to send
1406 #ifndef HAVE_IO_COMPLETION_PORT
1408 * I/O Completion Ports don't care about the select and FD_SET
1411 FD_ZERO(&activefds);
1414 DPRINTF(2, ("create_sockets(%d)\n", ntohs( (u_short) port)));
1416 create_wildcards(port);
1418 update_interfaces(port, NULL, NULL);
1421 * Now that we have opened all the sockets, turn off the reuse
1422 * flag for security.
1426 DPRINTF(2, ("create_sockets: Total interfaces = %d\n", ninterfaces));
1432 * create_interface - create a new interface for a given prototype
1433 * binding the socket.
1435 static struct interface *
1438 struct interface *iface
1441 struct sockaddr_storage resmask;
1442 struct interface *interface;
1444 DPRINTF(2, ("create_interface(%s#%d)\n", stoa(&iface->sin), ntohs( (u_short) port)));
1446 /* build an interface */
1447 interface = new_interface(iface);
1452 interface->fd = open_socket(&interface->sin,
1453 interface->flags, 0, interface);
1455 if (interface->fd != INVALID_SOCKET)
1456 list_if_listening(interface, port);
1458 if ((interface->flags & INT_BROADCAST) &&
1459 interface->bfd != INVALID_SOCKET)
1460 msyslog(LOG_INFO, "Listening on broadcast address %s#%d",
1461 stoa((&interface->bcast)),
1462 ntohs( (u_short) port));
1464 if (interface->fd == INVALID_SOCKET &&
1465 interface->bfd == INVALID_SOCKET) {
1466 msyslog(LOG_ERR, "unable to create socket on %s (%d) for %s#%d",
1469 stoa((&interface->sin)),
1470 ntohs( (u_short) port));
1471 delete_interface(interface);
1476 * Blacklist bound interface address
1479 SET_HOSTMASK(&resmask, interface->sin.ss_family);
1480 hack_restrict(RESTRICT_FLAGS, &interface->sin, &resmask,
1481 RESM_NTPONLY|RESM_INTERFACE, RES_IGNORE);
1484 * set globals with the first found
1485 * loopback interface of the appropriate class
1487 if ((loopback_interface == NULL) &&
1488 (interface->family == AF_INET) &&
1489 ((interface->flags & INT_LOOPBACK) != 0))
1491 loopback_interface = interface;
1495 * put into our interface list
1497 add_addr_to_list(&interface->sin, interface);
1498 add_interface(interface);
1500 DPRINT_INTERFACE(2, (interface, "created ", "\n"));
1505 * set_reuseaddr() - set/clear REUSEADDR on all sockets
1506 * NB possible hole - should we be doing this on broadcast
1510 set_reuseaddr(int flag) {
1511 struct interface *interf;
1513 for (interf = ISC_LIST_HEAD(inter_list);
1515 interf = ISC_LIST_NEXT(interf, link)) {
1516 if (interf->flags & INT_WILDCARD)
1520 * if interf->fd is INVALID_SOCKET, we might have a adapter
1521 * configured but not present
1523 DPRINTF(4, ("setting SO_REUSEADDR on %.16s@%s to %s\n", interf->name, stoa(&interf->sin), flag ? "on" : "off"));
1525 if (interf->fd != INVALID_SOCKET) {
1526 if (setsockopt(interf->fd, SOL_SOCKET,
1527 SO_REUSEADDR, (char *)&flag,
1529 netsyslog(LOG_ERR, "set_reuseaddr: setsockopt(SO_REUSEADDR, %s) failed: %m", flag ? "on" : "off");
1536 * This is just a wrapper around an internal function so we can
1537 * make other changes as necessary later on
1540 enable_broadcast(struct interface *iface, struct sockaddr_storage *baddr)
1543 socket_broadcast_enable(iface, iface->fd, baddr);
1547 #ifdef OPEN_BCAST_SOCKET
1549 * Enable a broadcast address to a given socket
1550 * The socket is in the inter_list all we need to do is enable
1551 * broadcasting. It is not this function's job to select the socket
1553 static isc_boolean_t
1554 socket_broadcast_enable(struct interface *iface, SOCKET fd, struct sockaddr_storage *maddr)
1559 if (maddr->ss_family == AF_INET)
1561 /* if this interface can support broadcast, set SO_BROADCAST */
1562 if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST,
1563 (char *)&on, sizeof(on)))
1565 netsyslog(LOG_ERR, "setsockopt(SO_BROADCAST) enable failure on address %s: %m",
1569 else if (debug > 1) {
1570 printf("Broadcast enabled on socket %d for address %s\n",
1575 iface->flags |= INT_BCASTOPEN;
1579 #endif /* SO_BROADCAST */
1583 * Remove a broadcast address from a given socket
1584 * The socket is in the inter_list all we need to do is disable
1585 * broadcasting. It is not this function's job to select the socket
1587 static isc_boolean_t
1588 socket_broadcast_disable(struct interface *iface, struct sockaddr_storage *maddr)
1591 int off = 0; /* This seems to be OK as an int */
1593 if (maddr->ss_family == AF_INET)
1595 if (setsockopt(iface->fd, SOL_SOCKET, SO_BROADCAST,
1596 (char *)&off, sizeof(off)))
1598 netsyslog(LOG_ERR, "setsockopt(SO_BROADCAST) disable failure on address %s: %m",
1602 iface->flags &= ~INT_BCASTOPEN;
1606 #endif /* SO_BROADCAST */
1609 #endif /* OPEN_BCAST_SOCKET */
1611 * Check to see if the address is a multicast address
1613 static isc_boolean_t
1614 addr_ismulticast(struct sockaddr_storage *maddr)
1616 switch (maddr->ss_family)
1619 if (!IN_CLASSD(ntohl(((struct sockaddr_in*)maddr)->sin_addr.s_addr))) {
1620 DPRINTF(4, ("multicast address %s not class D\n", stoa(maddr)));
1629 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
1630 if (!IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6*)maddr)->sin6_addr)) {
1631 DPRINTF(4, ("address %s not IPv6 multicast address\n", stoa(maddr)));
1640 * If we don't have IPV6 support any IPV6 address is not multicast
1654 * Multicast servers need to set the appropriate Multicast interface
1655 * socket option in order for it to know which interface to use for
1656 * send the multicast packet.
1659 enable_multicast_if(struct interface *iface, struct sockaddr_storage *maddr)
1662 /*u_char*/ TYPEOF_IP_MULTICAST_LOOP off = 0;
1664 switch (maddr->ss_family)
1667 if (setsockopt(iface->fd, IPPROTO_IP, IP_MULTICAST_IF,
1668 (char *)&(((struct sockaddr_in*)&iface->sin)->sin_addr.s_addr),
1669 sizeof(struct in_addr)) == -1) {
1671 "setsockopt IP_MULTICAST_IF failure: %m on socket %d, addr %s for multicast address %s",
1672 iface->fd, stoa(&iface->sin), stoa(maddr));
1675 #ifdef IP_MULTICAST_LOOP
1677 * Don't send back to itself, but allow it to fail to set it
1679 if (setsockopt(iface->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1680 SETSOCKOPT_ARG_CAST &off, sizeof(off)) == -1) {
1682 "setsockopt IP_MULTICAST_LOOP failure: %m on socket %d, addr %s for multicast address %s",
1683 iface->fd, stoa(&iface->sin), stoa(maddr));
1686 DPRINTF(4, ("Added IPv4 multicast interface on socket %d, addr %s for multicast address %s\n",
1687 iface->fd, stoa(&iface->sin),
1692 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
1693 if (setsockopt(iface->fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
1694 &iface->scopeid, sizeof(iface->scopeid)) == -1) {
1696 "setsockopt IPV6_MULTICAST_IF failure: %m on socket %d, addr %s, scope %d for multicast address %s",
1697 iface->fd, stoa(&iface->sin), iface->scopeid,
1701 #ifdef IPV6_MULTICAST_LOOP
1703 * Don't send back to itself, but allow it to fail to set it
1705 if (setsockopt(iface->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1706 &off, sizeof(off)) == -1) {
1708 "setsockopt IP_MULTICAST_LOOP failure: %m on socket %d, addr %s for multicast address %s",
1709 iface->fd, stoa(&iface->sin), stoa(maddr));
1712 DPRINTF(4, ("Added IPv6 multicast interface on socket %d, addr %s, scope %d for multicast address %s\n",
1713 iface->fd, stoa(&iface->sin), iface->scopeid,
1718 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */
1725 * Add a multicast address to a given socket
1726 * The socket is in the inter_list all we need to do is enable
1727 * multicasting. It is not this function's job to select the socket
1729 static isc_boolean_t
1730 socket_multicast_enable(struct interface *iface, int lscope, struct sockaddr_storage *maddr)
1732 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
1733 struct ipv6_mreq mreq6;
1734 struct in6_addr iaddr6;
1735 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */
1737 struct ip_mreq mreq;
1739 if (find_addr_in_list(maddr)) {
1740 DPRINTF(4, ("socket_multicast_enable(%s): already enabled\n", stoa(maddr)));
1744 switch (maddr->ss_family)
1747 memset((char *)&mreq, 0, sizeof(mreq));
1748 mreq.imr_multiaddr = (((struct sockaddr_in*)maddr)->sin_addr);
1749 mreq.imr_interface.s_addr = htonl(INADDR_ANY);
1750 if (setsockopt(iface->fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1751 (char *)&mreq, sizeof(mreq)) == -1) {
1753 "setsockopt IP_ADD_MEMBERSHIP failure: %m on socket %d, addr %s for %x / %x (%s)",
1754 iface->fd, stoa(&iface->sin),
1755 mreq.imr_multiaddr.s_addr,
1756 mreq.imr_interface.s_addr, stoa(maddr));
1759 DPRINTF(4, ("Added IPv4 multicast membership on socket %d, addr %s for %x / %x (%s)\n",
1760 iface->fd, stoa(&iface->sin),
1761 mreq.imr_multiaddr.s_addr,
1762 mreq.imr_interface.s_addr, stoa(maddr)));
1766 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
1768 * Enable reception of multicast packets
1769 * If the address is link-local we can get the interface index
1770 * from the scope id. Don't do this for other types of multicast
1771 * addresses. For now let the kernel figure it out.
1773 memset((char *)&mreq6, 0, sizeof(mreq6));
1774 iaddr6 = ((struct sockaddr_in6*)maddr)->sin6_addr;
1775 mreq6.ipv6mr_multiaddr = iaddr6;
1776 mreq6.ipv6mr_interface = lscope;
1778 if (setsockopt(iface->fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
1779 (char *)&mreq6, sizeof(mreq6)) == -1) {
1781 "setsockopt IPV6_JOIN_GROUP failure: %m on socket %d, addr %s for interface %d(%s)",
1782 iface->fd, stoa(&iface->sin),
1783 mreq6.ipv6mr_interface, stoa(maddr));
1786 DPRINTF(4, ("Added IPv6 multicast group on socket %d, addr %s for interface %d(%s)\n",
1787 iface->fd, stoa(&iface->sin),
1788 mreq6.ipv6mr_interface, stoa(maddr)));
1792 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */
1794 iface->flags |= INT_MCASTOPEN;
1796 add_addr_to_list(maddr, iface);
1801 * Remove a multicast address from a given socket
1802 * The socket is in the inter_list all we need to do is disable
1803 * multicasting. It is not this function's job to select the socket
1805 static isc_boolean_t
1806 socket_multicast_disable(struct interface *iface, struct sockaddr_storage *maddr)
1808 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
1809 struct ipv6_mreq mreq6;
1810 struct in6_addr iaddr6;
1811 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */
1813 struct ip_mreq mreq;
1814 memset((char *)&mreq, 0, sizeof(mreq));
1816 if (find_addr_in_list(maddr) == NULL) {
1817 DPRINTF(4, ("socket_multicast_disable(%s): not enabled\n", stoa(maddr)));
1821 switch (maddr->ss_family)
1824 mreq.imr_multiaddr = (((struct sockaddr_in*)&maddr)->sin_addr);
1825 mreq.imr_interface.s_addr = ((struct sockaddr_in*)&iface->sin)->sin_addr.s_addr;
1826 if (setsockopt(iface->fd, IPPROTO_IP, IP_DROP_MEMBERSHIP,
1827 (char *)&mreq, sizeof(mreq)) == -1) {
1829 "setsockopt IP_DROP_MEMBERSHIP failure: %m on socket %d, addr %s for %x / %x (%s)",
1830 iface->fd, stoa(&iface->sin),
1831 mreq.imr_multiaddr.s_addr,
1832 mreq.imr_interface.s_addr, stoa(maddr));
1837 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
1839 * Disable reception of multicast packets
1840 * If the address is link-local we can get the interface index
1841 * from the scope id. Don't do this for other types of multicast
1842 * addresses. For now let the kernel figure it out.
1844 iaddr6 = ((struct sockaddr_in6*)&maddr)->sin6_addr;
1845 mreq6.ipv6mr_multiaddr = iaddr6;
1846 mreq6.ipv6mr_interface = iface->scopeid;
1848 if (setsockopt(iface->fd, IPPROTO_IPV6, IPV6_LEAVE_GROUP,
1849 (char *)&mreq6, sizeof(mreq6)) == -1) {
1851 "setsockopt IPV6_LEAVE_GROUP failure: %m on socket %d, addr %s for %d(%s)",
1852 iface->fd, stoa(&iface->sin),
1853 mreq6.ipv6mr_interface, stoa(maddr));
1859 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */
1863 if (iface->num_mcast <= 0) {
1864 iface->num_mcast = 0;
1865 iface->flags &= ~INT_MCASTOPEN;
1871 * io_setbclient - open the broadcast client sockets
1876 #ifdef OPEN_BCAST_SOCKET
1877 struct interface *interf;
1879 isc_boolean_t jstatus;
1884 for (interf = ISC_LIST_HEAD(inter_list);
1886 interf = ISC_LIST_NEXT(interf, link)) {
1887 if (interf->flags & INT_WILDCARD)
1890 /* use only allowed addresses */
1891 if (interf->ignore_packets == ISC_TRUE)
1893 /* Only IPv4 addresses are valid for broadcast */
1894 if (interf->sin.ss_family != AF_INET)
1897 /* Is this a broadcast address? */
1898 if (!(interf->flags & INT_BROADCAST))
1901 /* Skip the loopback addresses */
1902 if (interf->flags & INT_LOOPBACK)
1905 /* Do we already have the broadcast address open? */
1906 if (interf->flags & INT_BCASTOPEN) {
1907 /* account for already open interfaces to aviod misleading warning below */
1913 * Try to open the broadcast address
1915 interf->family = AF_INET;
1916 interf->bfd = open_socket(&interf->bcast,
1917 INT_BROADCAST, 0, interf);
1920 * If we succeeded then we use it otherwise
1921 * enable the underlying address
1923 if (interf->bfd == INVALID_SOCKET) {
1930 /* Enable Broadcast on socket */
1931 jstatus = socket_broadcast_enable(interf, fd, &interf->sin);
1932 if (jstatus == ISC_TRUE)
1935 netsyslog(LOG_INFO,"io_setbclient: Opened broadcast client on interface #%d %s, socket: %d",
1936 interf->ifnum, interf->name, fd);
1937 interf->addr_refid = addr2refid(&interf->sin);
1944 printf("io_setbclient: Opened broadcast clients\n");
1947 netsyslog(LOG_ERR, "Unable to listen for broadcasts, no broadcast interfaces available");
1949 netsyslog(LOG_ERR, "io_setbclient: Broadcast Client disabled by build");
1954 * io_unsetbclient - close the broadcast client sockets
1957 io_unsetbclient(void)
1959 struct interface *interf;
1960 isc_boolean_t lstatus;
1962 for (interf = ISC_LIST_HEAD(inter_list);
1964 interf = ISC_LIST_NEXT(interf, link))
1966 if (interf->flags & INT_WILDCARD)
1969 if (!(interf->flags & INT_BCASTOPEN))
1971 lstatus = socket_broadcast_disable(interf, &interf->sin);
1976 * io_multicast_add() - add multicast group address
1980 struct sockaddr_storage addr
1984 struct interface *interface, *iface;
1988 * Check to see if this is a multicast address
1990 if (addr_ismulticast(&addr) == ISC_FALSE)
1993 /* If we already have it we can just return */
1994 if (find_flagged_addr_in_list(&addr, INT_MCASTOPEN|INT_MCASTIF) != NULL)
1996 netsyslog(LOG_INFO, "Duplicate request found for multicast address %s",
2001 #ifndef MULTICAST_NONEWSOCKET
2002 interface = new_interface(NULL);
2005 * Open a new socket for the multicast address
2007 interface->sin.ss_family = addr.ss_family;
2008 interface->family = addr.ss_family;
2010 switch(addr.ss_family) {
2012 memcpy(&(((struct sockaddr_in *)&interface->sin)->sin_addr),
2013 &(((struct sockaddr_in*)&addr)->sin_addr),
2014 sizeof(struct in_addr));
2015 ((struct sockaddr_in*)&interface->sin)->sin_port = htons(NTP_PORT);
2016 memset(&((struct sockaddr_in*)&interface->mask)->sin_addr.s_addr, 0xff, sizeof(struct in_addr));
2019 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2020 memcpy(&(((struct sockaddr_in6 *)&interface->sin)->sin6_addr),
2021 &((struct sockaddr_in6*)&addr)->sin6_addr,
2022 sizeof(struct in6_addr));
2023 ((struct sockaddr_in6*)&interface->sin)->sin6_port = htons(NTP_PORT);
2024 #ifdef ISC_PLATFORM_HAVESCOPEID
2025 ((struct sockaddr_in6*)&interface->sin)->sin6_scope_id = ((struct sockaddr_in6*)&addr)->sin6_scope_id;
2027 memset(&((struct sockaddr_in6*)&interface->mask)->sin6_addr.s6_addr, 0xff, sizeof(struct in6_addr));
2029 iface = findlocalcastinterface(&addr, INT_MULTICAST);
2031 # ifdef ISC_PLATFORM_HAVESCOPEID
2032 lscope = ((struct sockaddr_in6*)&iface->sin)->sin6_scope_id;
2034 DPRINTF(4, ("Found interface #%d %s, scope: %d for address %s\n", iface->ifnum, iface->name, lscope, stoa(&addr)));
2040 interface->bfd = INVALID_SOCKET;
2041 interface->fd = open_socket(&interface->sin,
2042 INT_MULTICAST, 0, interface);
2044 if (interface->fd != INVALID_SOCKET)
2046 interface->bfd = INVALID_SOCKET;
2047 interface->ignore_packets = ISC_FALSE;
2048 interface->flags |= INT_MCASTIF;
2050 (void) strncpy(interface->name, "multicast",
2051 sizeof(interface->name));
2052 ((struct sockaddr_in*)&interface->mask)->sin_addr.s_addr =
2054 DPRINT_INTERFACE(2, (interface, "multicast add ", "\n"));
2055 /* socket_multicast_enable() will add this address to the addresslist */
2056 add_interface(interface);
2057 list_if_listening(interface, htons(NTP_PORT));
2061 delete_interface(interface); /* re-use existing interface */
2063 if (addr.ss_family == AF_INET)
2064 interface = wildipv4;
2065 else if (addr.ss_family == AF_INET6)
2066 interface = wildipv6;
2068 if (interface != NULL) {
2069 /* HACK ! -- stuff in an address */
2070 interface->bcast = addr;
2072 "...multicast address %s using wildcard interface #%d %s",
2073 stoa(&addr), interface->ifnum, interface->name);
2076 "No multicast socket available to use for address %s",
2083 * For the case where we can't use a separate socket
2085 interface = findlocalcastinterface(&addr, INT_MULTICAST);
2087 * If we don't have a valid socket, just return
2092 "Cannot add multicast address %s: Cannot find slot",
2099 isc_boolean_t jstatus;
2100 jstatus = socket_multicast_enable(interface, lscope, &addr);
2102 if (jstatus == ISC_TRUE)
2103 netsyslog(LOG_INFO, "Added Multicast Listener %s on interface #%d %s\n", stoa(&addr), interface->ifnum, interface->name);
2105 netsyslog(LOG_ERR, "Failed to add Multicast Listener %s\n", stoa(&addr));
2109 "Cannot add multicast address %s: no Multicast support",
2116 * io_multicast_del() - delete multicast group address
2120 struct sockaddr_storage addr
2124 struct interface *interface;
2125 isc_boolean_t lstatus;
2128 * Check to see if this is a multicast address
2130 if (addr_ismulticast(&addr) == ISC_FALSE)
2133 "invalid multicast address %s", stoa(&addr));
2137 switch (addr.ss_family)
2141 * Disable reception of multicast packets
2143 interface = find_flagged_addr_in_list(&addr, INT_MCASTOPEN);
2144 while ( interface != NULL) {
2145 lstatus = socket_multicast_disable(interface, &addr);
2146 interface = find_flagged_addr_in_list(&addr, INT_MCASTOPEN);
2150 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
2153 * Disable reception of multicast packets
2155 for (interface = ISC_LIST_HEAD(inter_list);
2157 interface = ISC_LIST_NEXT(interface, link))
2159 if (interface->flags & INT_WILDCARD)
2162 /* Be sure it's the correct family */
2163 if (interface->sin.ss_family != AF_INET6)
2165 if (!(interface->flags & INT_MCASTOPEN))
2167 if (!(interface->fd < 0))
2169 if (!SOCKCMP(&addr, &interface->sin))
2171 lstatus = socket_multicast_disable(interface, &addr);
2174 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */
2178 delete_addr_from_list(&addr);
2180 #else /* not MCAST */
2181 netsyslog(LOG_ERR, "this function requires multicast kernel");
2182 #endif /* not MCAST */
2186 * init_nonblocking_io() - set up descriptor to be non blocking
2188 static void init_nonblocking_io(SOCKET fd)
2195 /* in vxWorks we use FIONBIO, but the others are defined for old systems, so
2196 * all hell breaks loose if we leave them defined
2203 #if defined(O_NONBLOCK) /* POSIX */
2204 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
2206 netsyslog(LOG_ERR, "fcntl(O_NONBLOCK) fails on fd #%d: %m",
2211 #elif defined(FNDELAY)
2212 if (fcntl(fd, F_SETFL, FNDELAY) < 0)
2214 netsyslog(LOG_ERR, "fcntl(FNDELAY) fails on fd #%d: %m",
2219 #elif defined(O_NDELAY) /* generally the same as FNDELAY */
2220 if (fcntl(fd, F_SETFL, O_NDELAY) < 0)
2222 netsyslog(LOG_ERR, "fcntl(O_NDELAY) fails on fd #%d: %m",
2227 #elif defined(FIONBIO)
2230 # if defined(SYS_WINNT)
2232 if (ioctlsocket(fd,FIONBIO,(u_long *) &on) == SOCKET_ERROR)
2234 if (ioctl(fd,FIONBIO,&on) < 0)
2237 netsyslog(LOG_ERR, "ioctl(FIONBIO) fails on fd #%d: %m",
2243 #elif defined(FIOSNBIO)
2244 if (ioctl(fd,FIOSNBIO,&on) < 0)
2246 netsyslog(LOG_ERR, "ioctl(FIOSNBIO) fails on fd #%d: %m",
2252 # include "Bletch: Need non-blocking I/O!"
2257 * open_socket - open a socket, returning the file descriptor
2262 struct sockaddr_storage *addr,
2265 struct interface *interf
2270 int on = 1, off = 0; /* int is OK for REUSEADR per */
2271 /* http://www.kohala.com/start/mcast.api.txt */
2272 #if defined(IPTOS_LOWDELAY) && defined(IPPROTO_IP) && defined(IP_TOS)
2274 #endif /* IPTOS_LOWDELAY && IPPROTO_IP && IP_TOS */
2276 if ((addr->ss_family == AF_INET6) && (isc_net_probeipv6() != ISC_R_SUCCESS))
2277 return (INVALID_SOCKET);
2279 /* create a datagram (UDP) socket */
2281 if ( (fd = socket(addr->ss_family, SOCK_DGRAM, 0)) < 0) {
2284 if ( (fd = socket(addr->ss_family, SOCK_DGRAM, 0)) == INVALID_SOCKET) {
2285 errval = WSAGetLastError();
2287 if(addr->ss_family == AF_INET)
2288 netsyslog(LOG_ERR, "socket(AF_INET, SOCK_DGRAM, 0) failed on address %s: %m",
2290 else if(addr->ss_family == AF_INET6)
2291 netsyslog(LOG_ERR, "socket(AF_INET6, SOCK_DGRAM, 0) failed on address %s: %m",
2294 if (errval == EPROTONOSUPPORT || errval == EAFNOSUPPORT ||
2295 errval == EPFNOSUPPORT)
2297 if (errval == WSAEPROTONOSUPPORT || errval == WSAEAFNOSUPPORT ||
2298 errval == WSAEPFNOSUPPORT)
2300 return (INVALID_SOCKET);
2301 msyslog(LOG_ERR, "unexpected error code %d (not PROTONOSUPPORT|AFNOSUPPORT|FPNOSUPPORT) - exiting", errval);
2306 if (connection_reset_fix(fd) != ISC_R_SUCCESS) {
2307 netsyslog(LOG_ERR, "connection_reset_fix(fd) failed on address %s: %m",
2310 #endif /* SYS_WINNT */
2313 * Fixup the file descriptor for some systems
2314 * See bug #530 for details of the issue.
2319 * set SO_REUSEADDR since we will be binding the same port
2320 * number on each interface according to flag
2322 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
2323 turn_off_reuse ? (char *)&off : (char *)&on, sizeof(on)))
2325 netsyslog(LOG_ERR, "setsockopt SO_REUSEADDR %s on fails on address %s: %m",
2326 turn_off_reuse ? "off" : "on", stoa(addr));
2330 return INVALID_SOCKET;
2334 * IPv4 specific options go here
2336 if (addr->ss_family == AF_INET) {
2337 #if defined(IPTOS_LOWDELAY) && defined(IPPROTO_IP) && defined(IP_TOS)
2338 /* set IP_TOS to minimize packet delay */
2339 tos = IPTOS_LOWDELAY;
2340 if (setsockopt(fd, IPPROTO_IP, IP_TOS, (char *) &tos, sizeof(tos)) < 0)
2342 netsyslog(LOG_ERR, "setsockopt IPTOS_LOWDELAY on fails on address %s: %m",
2345 #endif /* IPTOS_LOWDELAY && IPPROTO_IP && IP_TOS */
2349 * IPv6 specific options go here
2351 if (addr->ss_family == AF_INET6) {
2352 #if defined(IPV6_V6ONLY)
2353 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY,
2354 (char*)&on, sizeof(on)))
2356 netsyslog(LOG_ERR, "setsockopt IPV6_V6ONLY on fails on address %s: %m",
2359 #endif /* IPV6_V6ONLY */
2360 #if defined(IPV6_BINDV6ONLY)
2361 if (setsockopt(fd, IPPROTO_IPV6, IPV6_BINDV6ONLY,
2362 (char*)&on, sizeof(on)))
2365 "setsockopt IPV6_BINDV6ONLY on fails on address %s: %m",
2368 #endif /* IPV6_BINDV6ONLY */
2371 #ifdef OS_NEEDS_REUSEADDR_FOR_IFADDRBIND
2373 * some OSes don't allow binding to more specific
2374 * addresses if a wildcard address already bound
2375 * to the port and SO_REUSEADDR is not set
2377 if (!is_wildcard_addr(addr)) {
2378 set_wildcard_reuse(addr->ss_family, 1);
2383 * bind the local address.
2385 errval = bind(fd, (struct sockaddr *)addr, SOCKLEN(addr));
2387 #ifdef OS_NEEDS_REUSEADDR_FOR_IFADDRBIND
2389 * some OSes don't allow binding to more specific
2390 * addresses if a wildcard address already bound
2391 * to the port and REUSE_ADDR is not set
2393 if (!is_wildcard_addr(addr)) {
2394 set_wildcard_reuse(addr->ss_family, 0);
2400 * Don't log this under all conditions
2402 if (turn_off_reuse == 0
2407 if (addr->ss_family == AF_INET)
2409 "bind() fd %d, family %d, port %d, addr %s, in_classd=%d flags=0x%x fails: %m",
2410 fd, addr->ss_family, (int)ntohs(((struct sockaddr_in*)addr)->sin_port),
2412 IN_CLASSD(ntohl(((struct sockaddr_in*)addr)->sin_addr.s_addr)), flags);
2413 #ifdef INCLUDE_IPV6_SUPPORT
2414 else if (addr->ss_family == AF_INET6)
2416 "bind() fd %d, family %d, port %d, scope %d, addr %s, in6_is_addr_multicast=%d flags=0x%x fails: %m",
2417 fd, addr->ss_family, (int)ntohs(((struct sockaddr_in6*)addr)->sin6_port),
2418 # ifdef ISC_PLATFORM_HAVESCOPEID
2419 ((struct sockaddr_in6*)addr)->sin6_scope_id
2424 IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6*)addr)->sin6_addr), flags);
2430 return INVALID_SOCKET;
2433 #ifdef HAVE_TIMESTAMP
2435 if (setsockopt(fd, SOL_SOCKET, SO_TIMESTAMP,
2436 (char*)&on, sizeof(on)))
2438 netsyslog(LOG_DEBUG,
2439 "setsockopt SO_TIMESTAMP on fails on address %s: %m",
2445 DPRINTF(4, ("setsockopt SO_TIMESTAMP enabled on fd %d address %s\n", fd, stoa(addr)));
2450 DPRINTF(4, ("bind() fd %d, family %d, port %d, addr %s, flags=0x%x\n",
2453 (int)ntohs(((struct sockaddr_in*)addr)->sin_port),
2457 init_nonblocking_io(fd);
2459 #ifdef HAVE_SIGNALED_IO
2460 init_socket_sig(fd);
2461 #endif /* not HAVE_SIGNALED_IO */
2463 add_fd_to_list(fd, FD_TYPE_SOCKET);
2465 #if !defined(SYS_WINNT) && !defined(VMS)
2466 DPRINTF(4, ("flags for fd %d: 0x%x\n", fd,
2467 fcntl(fd, F_GETFL, 0)));
2468 #endif /* SYS_WINNT || VMS */
2470 #if defined (HAVE_IO_COMPLETION_PORT)
2472 * Add the socket to the completion port
2474 if (io_completion_port_add_socket(fd, interf))
2476 msyslog(LOG_ERR, "unable to set up io completion port - EXITING");
2483 /* XXX ELIMINATE sendpkt similar in ntpq.c, ntpdc.c, ntp_io.c, ntptrace.c */
2485 * sendpkt - send a packet to the specified destination. Maintain a
2486 * send error cache so that only the first consecutive error for a
2487 * destination is logged.
2491 struct sockaddr_storage *dest,
2492 struct interface *inter,
2501 #endif /* SYS_WINNT */
2504 * Send error caches. Empty slots have port == 0
2505 * Set ERRORCACHESIZE to 0 to disable
2509 struct in_addr addr;
2512 #ifdef INCLUDE_IPV6_SUPPORT
2515 struct in6_addr addr;
2517 #endif /* INCLUDE_IPV6_SUPPORT */
2520 #ifndef ERRORCACHESIZE
2521 #define ERRORCACHESIZE 8
2523 #if ERRORCACHESIZE > 0
2524 static struct cache badaddrs[ERRORCACHESIZE];
2525 #ifdef INCLUDE_IPV6_SUPPORT
2526 static struct cache6 badaddrs6[ERRORCACHESIZE];
2527 #endif /* INCLUDE_IPV6_SUPPORT */
2529 #define badaddrs ((struct cache *)0) /* Only used in empty loops! */
2530 #ifdef INCLUDE_IPV6_SUPPORT
2531 #define badaddrs6 ((struct cache6 *)0) /* Only used in empty loops! */
2532 #endif /* INCLUDE_IPV6_SUPPORT */
2539 printf("%ssendpkt(fd=%d dst=%s, src=%s, ttl=%d, len=%d)\n",
2540 (ttl > 0) ? "\tMCAST\t***** " : "",
2541 inter->fd, stoa(dest),
2542 stoa(&inter->sin), ttl, len);
2546 printf("%ssendpkt(dst=%s, ttl=%d, len=%d): no interface - IGNORED\n",
2547 (ttl > 0) ? "\tMCAST\t***** " : "",
2554 if (inter == NULL) /* unbound peer - drop request and wait for better network conditions */
2560 * for the moment we use the bcast option to set multicast ttl
2562 if (ttl > 0 && ttl != inter->last_ttl) {
2565 * set the multicast ttl for outgoing packets
2569 switch (inter->sin.ss_family) {
2573 u_char mttl = (u_char) ttl;
2575 rtc = setsockopt(inter->fd, IPPROTO_IP, IP_MULTICAST_TTL,
2576 (const void *) &mttl, sizeof(mttl));
2580 #ifdef INCLUDE_IPV6_SUPPORT
2583 u_int ittl = (u_char) ttl;
2585 rtc = setsockopt(inter->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
2586 (const void *) &ittl, sizeof(ittl));
2590 #endif /* INCLUDE_IPV6_SUPPORT */
2591 default: /* just NOP if not supported */
2597 netsyslog(LOG_ERR, "setsockopt IP_MULTICAST_TTL/IPV6_MULTICAST_HOPS fails on address %s: %m",
2601 inter->last_ttl = ttl;
2606 for (slot = ERRORCACHESIZE; --slot >= 0; )
2607 if(dest->ss_family == AF_INET) {
2608 if (badaddrs[slot].port == ((struct sockaddr_in*)dest)->sin_port &&
2609 badaddrs[slot].addr.s_addr == ((struct sockaddr_in*)dest)->sin_addr.s_addr)
2612 #ifdef INCLUDE_IPV6_SUPPORT
2613 else if (dest->ss_family == AF_INET6) {
2614 if (badaddrs6[slot].port == ((struct sockaddr_in6*)dest)->sin6_port &&
2615 badaddrs6[slot].addr.s6_addr == ((struct sockaddr_in6*)dest)->sin6_addr.s6_addr)
2618 #endif /* INCLUDE_IPV6_SUPPORT */
2620 #if defined(HAVE_IO_COMPLETION_PORT)
2621 err = io_completion_port_sendto(inter, pkt, len, dest);
2622 if (err != ERROR_SUCCESS)
2625 cc = srvr_rply(&ntp_node, dest, inter, pkt);
2627 cc = sendto(inter->fd, (char *)pkt, (unsigned int)len, 0, (struct sockaddr *)dest,
2635 #if defined(HAVE_IO_COMPLETION_PORT)
2636 err = WSAGetLastError();
2637 if (err != WSAEWOULDBLOCK && err != WSAENOBUFS && slot < 0)
2639 if (errno != EWOULDBLOCK && errno != ENOBUFS && slot < 0)
2643 * Remember this, if there's an empty slot
2645 switch (dest->ss_family) {
2649 for (slot = ERRORCACHESIZE; --slot >= 0; )
2650 if (badaddrs[slot].port == 0)
2652 badaddrs[slot].port = SRCPORT(dest);
2653 badaddrs[slot].addr = ((struct sockaddr_in*)dest)->sin_addr;
2658 #ifdef INCLUDE_IPV6_SUPPORT
2661 for (slot = ERRORCACHESIZE; --slot >= 0; )
2662 if (badaddrs6[slot].port == 0)
2664 badaddrs6[slot].port = SRCPORT(dest);
2665 badaddrs6[slot].addr = ((struct sockaddr_in6*)dest)->sin6_addr;
2669 #endif /* INCLUDE_IPV6_SUPPORT */
2670 default: /* don't care if not supported */
2674 netsyslog(LOG_ERR, "sendto(%s) (fd=%d): %m",
2675 stoa(dest), inter->fd);
2683 * He's not bad any more
2687 netsyslog(LOG_INFO, "Connection re-established to %s", stoa(dest));
2688 switch (dest->ss_family) {
2690 badaddrs[slot].port = 0;
2692 #ifdef INCLUDE_IPV6_SUPPORT
2694 badaddrs6[slot].port = 0;
2696 #endif /* INCLUDE_IPV6_SUPPORT */
2697 default: /* don't care if not supported */
2704 #if !defined(HAVE_IO_COMPLETION_PORT)
2706 * fdbits - generate ascii representation of fd_set (FAU debug support)
2707 * HFDF format - highest fd first.
2715 static char buffer[256];
2716 char * buf = buffer;
2718 count = (count < 256) ? count : 255;
2722 *buf++ = FD_ISSET(count, set) ? '#' : '-';
2731 * Routine to read the refclock packets for a specific interface
2732 * Return the number of bytes read. That way we know if we should
2733 * read it again or go on to the next one if no bytes returned
2736 read_refclock_packet(SOCKET fd, struct refclockio *rp, l_fp ts)
2740 register struct recvbuf *rb;
2742 rb = get_free_recv_buffer();
2747 * No buffer space available - just drop the packet
2749 char buf[RX_BUFF_SIZE];
2751 buflen = read(fd, buf, sizeof buf);
2756 i = (rp->datalen == 0
2757 || rp->datalen > sizeof(rb->recv_space))
2758 ? sizeof(rb->recv_space) : rp->datalen;
2759 buflen = read(fd, (char *)&rb->recv_space, (unsigned)i);
2763 if (errno != EINTR && errno != EAGAIN) {
2764 netsyslog(LOG_ERR, "clock read fd %d: %m", fd);
2771 * Got one. Mark how and when it got here,
2772 * put it on the full list and do bookkeeping.
2774 rb->recv_length = buflen;
2775 rb->recv_srcclock = rp->srcclock;
2779 rb->receiver = rp->clock_recv;
2784 * have direct input routine for refclocks
2786 if (rp->io_input(rb) == 0)
2789 * data was consumed - nothing to pass up
2790 * into block input machine
2797 add_full_recv_buffer(rb);
2804 #ifdef HAVE_TIMESTAMP
2806 * extract timestamps from control message buffer
2809 fetch_timestamp(struct recvbuf *rb, struct msghdr *msghdr, l_fp ts)
2811 #ifdef USE_TIMESTAMP_CMSG
2812 struct cmsghdr *cmsghdr;
2814 cmsghdr = CMSG_FIRSTHDR(msghdr);
2815 while (cmsghdr != NULL) {
2816 switch (cmsghdr->cmsg_type)
2820 struct timeval *tvp = (struct timeval *)CMSG_DATA(cmsghdr);
2823 DPRINTF(4, ("fetch_timestamp: system network time stamp: %ld.%06ld\n", tvp->tv_sec, tvp->tv_usec));
2824 nts.l_i = tvp->tv_sec + JAN_1970;
2825 dtemp = tvp->tv_usec / 1e6;
2827 /* fuzz lower bits not covered by precision */
2828 if (sys_precision != 0)
2829 dtemp += (ntp_random() / FRAC - .5) / (1 <<
2832 nts.l_uf = (u_int32)(dtemp*FRAC);
2837 collect_timing(rb, "input processing delay", 1, &dts);
2838 DPRINTF(4, ("fetch_timestamp: timestamp delta: %s (incl. prec fuzz)\n", lfptoa(&dts, 9)));
2841 ts = nts; /* network time stamp */
2845 DPRINTF(4, ("fetch_timestamp: skipping control message 0x%x\n", cmsghdr->cmsg_type));
2848 cmsghdr = CMSG_NXTHDR(msghdr, cmsghdr);
2856 * Routine to read the network NTP packets for a specific interface
2857 * Return the number of bytes read. That way we know if we should
2858 * read it again or go on to the next one if no bytes returned
2861 read_network_packet(SOCKET fd, struct interface *itf, l_fp ts)
2863 GETSOCKNAME_SOCKLEN_TYPE fromlen;
2865 register struct recvbuf *rb;
2866 #ifdef HAVE_TIMESTAMP
2867 struct msghdr msghdr;
2869 char control[TIMESTAMP_CTLMSGBUF_SIZE]; /* pick up control messages */
2873 * Get a buffer and read the frame. If we
2874 * haven't got a buffer, or this is received
2875 * on a disallowed socket, just dump the
2879 rb = get_free_recv_buffer();
2881 if (rb == NULL || itf->ignore_packets == ISC_TRUE)
2883 char buf[RX_BUFF_SIZE];
2884 struct sockaddr_storage from;
2888 fromlen = sizeof(from);
2889 buflen = recvfrom(fd, buf, sizeof(buf), 0,
2890 (struct sockaddr*)&from, &fromlen);
2891 DPRINTF(4, ("%s on (%lu) fd=%d from %s\n",
2892 (itf->ignore_packets == ISC_TRUE) ? "ignore" : "drop",
2893 free_recvbuffs(), fd,
2895 if (itf->ignore_packets == ISC_TRUE)
2902 fromlen = sizeof(struct sockaddr_storage);
2904 #ifndef HAVE_TIMESTAMP
2905 rb->recv_length = recvfrom(fd,
2906 (char *)&rb->recv_space,
2907 sizeof(rb->recv_space), 0,
2908 (struct sockaddr *)&rb->recv_srcadr,
2911 iovec.iov_base = (void *)&rb->recv_space;
2912 iovec.iov_len = sizeof(rb->recv_space);
2913 msghdr.msg_name = (void *)&rb->recv_srcadr;
2914 msghdr.msg_namelen = sizeof(rb->recv_srcadr);
2915 msghdr.msg_iov = &iovec;
2916 msghdr.msg_iovlen = 1;
2917 msghdr.msg_control = (void *)&control;
2918 msghdr.msg_controllen = sizeof(control);
2919 msghdr.msg_flags = 0;
2920 rb->recv_length = recvmsg(fd, &msghdr, 0);
2923 buflen = rb->recv_length;
2925 if (buflen == 0 || (buflen == -1 &&
2934 else if (buflen < 0)
2936 netsyslog(LOG_ERR, "recvfrom(%s) fd=%d: %m",
2937 stoa(&rb->recv_srcadr), fd);
2938 DPRINTF(5, ("read_network_packet: fd=%d dropped (bad recvfrom)\n", fd));
2945 if(rb->recv_srcadr.ss_family == AF_INET)
2946 printf("read_network_packet: fd=%d length %d from %08lx %s\n",
2948 (u_long)ntohl(((struct sockaddr_in*)&rb->recv_srcadr)->sin_addr.s_addr) &
2950 stoa(&rb->recv_srcadr));
2952 printf("read_network_packet: fd=%d length %d from %s\n",
2954 stoa(&rb->recv_srcadr));
2959 * Got one. Mark how and when it got here,
2960 * put it on the full list and do bookkeeping.
2964 #ifdef HAVE_TIMESTAMP
2965 ts = fetch_timestamp(rb, &msghdr, ts); /* pick up a network time stamp if possible */
2968 rb->receiver = receive;
2970 add_full_recv_buffer(rb);
2978 * input_handler - receive packets asynchronously
2990 struct timeval tvzero;
2991 l_fp ts; /* Timestamp at BOselect() gob */
2993 l_fp ts_e; /* Timestamp at EOselect() gob */
2996 int select_count = 0;
2997 struct interface *interface;
2998 #if defined(HAS_ROUTING_SOCKET)
2999 struct asyncio_reader *asyncio_reader;
3005 * If we have something to do, freeze a timestamp.
3006 * See below for the other cases (nothing (left) to do or error)
3011 * Do a poll to see who has data
3015 tvzero.tv_sec = tvzero.tv_usec = 0;
3017 n = select(maxactivefd+1, &fds, (fd_set *)0, (fd_set *)0, &tvzero);
3020 * If there are no packets waiting just return
3026 * extended FAU debugging output
3030 "select(%d, %s, 0L, 0L, &0.0) error: %m",
3032 fdbits(maxactivefd, &activefds));
3036 for (j = 0; j <= maxactivefd; j++)
3037 if ((FD_ISSET(j, &fds) && (read(j, &b, 0) == -1)))
3038 netsyslog(LOG_ERR, "Bad file descriptor %d", j);
3049 * Check out the reference clocks first, if any
3054 register struct refclockio *rp;
3056 for (rp = refio; rp != NULL; rp = rp->next)
3060 if (FD_ISSET(fd, &fds))
3064 buflen = read_refclock_packet(fd, rp, ts);
3065 } while (buflen > 0);
3067 } /* End if (FD_ISSET(fd, &fds)) */
3068 } /* End for (rp = refio; rp != 0 && n > 0; rp = rp->next) */
3069 } /* End if (refio != 0) */
3071 #endif /* REFCLOCK */
3074 * Loop through the interfaces looking for data to read.
3076 for (interface = ISC_LIST_TAIL(inter_list);
3078 interface = ISC_LIST_PREV(interface, link))
3080 for (doing = 0; (doing < 2); doing++)
3088 if (!(interface->flags & INT_BCASTOPEN))
3090 fd = interface->bfd;
3092 if (fd < 0) continue;
3093 if (FD_ISSET(fd, &fds))
3097 buflen = read_network_packet(fd, interface, ts);
3098 } while (buflen > 0);
3100 /* Check more interfaces */
3104 #ifdef HAS_ROUTING_SOCKET
3106 * scan list of asyncio readers - currently only used for routing sockets
3108 asyncio_reader = ISC_LIST_TAIL(asyncio_reader_list);
3110 while (asyncio_reader != NULL)
3112 struct asyncio_reader *next = ISC_LIST_PREV(asyncio_reader, link);
3113 if (FD_ISSET(asyncio_reader->fd, &fds)) {
3115 asyncio_reader->receiver(asyncio_reader);
3117 asyncio_reader = next;
3119 #endif /* HAS_ROUTING_SOCKET */
3122 * Done everything from that select.
3126 * If nothing to do, just return.
3127 * If an error occurred, complain and return.
3129 if (select_count == 0) /* We really had nothing to do */
3133 netsyslog(LOG_DEBUG, "input_handler: select() returned 0");
3137 /* We've done our work */
3141 * (ts_e - ts) is the amount of time we spent
3142 * processing this gob of file descriptors. Log
3146 collect_timing(NULL, "input handler", 1, &ts_e);
3148 netsyslog(LOG_INFO, "input_handler: Processed a gob of fd's in %s msec", lfptoms(&ts_e, 6));
3157 * findinterface - find local interface corresponding to address
3161 struct sockaddr_storage *addr
3164 struct interface *interface;
3166 interface = findlocalinterface(addr, INT_WILDCARD);
3168 if (interface == NULL)
3170 DPRINTF(4, ("Found no interface for address %s - returning wildcard\n",
3173 return (ANY_INTERFACE_CHOOSE(addr));
3177 DPRINTF(4, ("Found interface #%d %s for address %s\n",
3178 interface->ifnum, interface->name, stoa(addr)));
3185 * findlocalinterface - find local interface index corresponding to address
3187 * This code attempts to find the local sending address for an outgoing
3188 * address by connecting a new socket to destinationaddress:NTP_PORT
3189 * and reading the sockname of the resulting connect.
3190 * the complicated sequence simulates the routing table lookup
3191 * for to first hop without duplicating any of the routing logic into
3192 * ntpd. preferably we would have used an API call - but its not there -
3193 * so this is the best we can do here short of duplicating to entire routing
3194 * logic in ntpd which would be a silly and really unportable thing to do.
3197 static struct interface *
3199 struct sockaddr_storage *addr,
3205 struct sockaddr_storage saddr;
3206 GETSOCKNAME_SOCKLEN_TYPE saddrlen = SOCKLEN(addr);
3207 struct interface *iface;
3209 DPRINTF(4, ("Finding interface for addr %s in list of addresses\n",
3212 memset(&saddr, 0, sizeof(saddr));
3213 saddr.ss_family = addr->ss_family;
3214 if(addr->ss_family == AF_INET) {
3215 memcpy(&((struct sockaddr_in*)&saddr)->sin_addr, &((struct sockaddr_in*)addr)->sin_addr, sizeof(struct in_addr));
3216 ((struct sockaddr_in*)&saddr)->sin_port = htons(NTP_PORT);
3218 #ifdef INCLUDE_IPV6_SUPPORT
3219 else if(addr->ss_family == AF_INET6) {
3220 memcpy(&((struct sockaddr_in6*)&saddr)->sin6_addr, &((struct sockaddr_in6*)addr)->sin6_addr, sizeof(struct in6_addr));
3221 ((struct sockaddr_in6*)&saddr)->sin6_port = htons(NTP_PORT);
3222 # ifdef ISC_PLATFORM_HAVESCOPEID
3223 ((struct sockaddr_in6*)&saddr)->sin6_scope_id = ((struct sockaddr_in6*)addr)->sin6_scope_id;
3228 s = socket(addr->ss_family, SOCK_DGRAM, 0);
3229 if (s == INVALID_SOCKET)
3232 rtn = connect(s, (struct sockaddr *)&saddr, SOCKLEN(&saddr));
3236 if (rtn == SOCKET_ERROR)
3243 rtn = getsockname(s, (struct sockaddr *)&saddr, &saddrlen);
3248 if (rtn == SOCKET_ERROR)
3252 DPRINTF(4, ("findlocalinterface: kernel maps %s to %s\n", stoa(addr), stoa(&saddr)));
3254 iface = getinterface(&saddr, flags);
3256 /* Don't both with ignore interfaces */
3257 if (iface != NULL && iface->ignore_packets == ISC_TRUE)
3268 * fetch an interface structure the matches the
3269 * address is has the given flags not set
3271 static struct interface *
3272 getinterface(struct sockaddr_storage *addr, int flags)
3274 struct interface *interface = find_addr_in_list(addr);
3276 if (interface != NULL && interface->flags & flags)
3287 * findlocalcastinterface - find local *cast interface index corresponding to address
3288 * depending on the flags passed
3290 static struct interface *
3291 findlocalcastinterface(
3292 struct sockaddr_storage *addr, int flags
3295 struct interface *interface;
3296 struct interface *nif = NULL;
3297 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
3298 isc_boolean_t want_linklocal;
3302 * see how kernel maps the mcast address
3304 nif = findlocalinterface(addr, 0);
3307 DPRINTF(2, ("findlocalcastinterface: kernel recommends interface #%d %s\n", nif->ifnum, nif->name));
3311 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
3312 want_linklocal = ISC_FALSE;
3313 if (addr_ismulticast(addr) && flags == INT_MULTICAST)
3315 if (IN6_IS_ADDR_MC_LINKLOCAL(&((struct sockaddr_in6*)addr)->sin6_addr))
3317 want_linklocal = ISC_TRUE;
3319 else if (IN6_IS_ADDR_MC_SITELOCAL(&((struct sockaddr_in6*)addr)->sin6_addr))
3321 want_linklocal = ISC_TRUE;
3326 for (interface = ISC_LIST_HEAD(inter_list);
3328 interface = ISC_LIST_NEXT(interface, link))
3330 /* use only allowed addresses */
3331 if (interface->ignore_packets == ISC_TRUE)
3334 /* Skip the loopback and wildcard addresses */
3335 if (interface->flags & (INT_LOOPBACK|INT_WILDCARD))
3338 /* Skip if different family */
3339 if(interface->sin.ss_family != addr->ss_family)
3342 /* Is this it one of these based on flags? */
3343 if (!(interface->flags & flags))
3346 /* for IPv6 multicast check the address for linklocal */
3347 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
3348 if (flags == INT_MULTICAST && interface->sin.ss_family == AF_INET6 &&
3349 (IN6_IS_ADDR_LINKLOCAL(&((struct sockaddr_in6*)&interface->sin)->sin6_addr))
3350 && want_linklocal == ISC_TRUE)
3355 /* If we want a linklocal address and this isn't it, skip */\
3356 if (want_linklocal == ISC_TRUE)
3359 /* Otherwise just look for the flag */
3360 if((interface->flags & flags))
3370 printf("findlocalcastinterface: found interface #%d %s\n", nif->ifnum, nif->name);
3372 printf("findlocalcastinterface: no interface found for %s flags 0x%x\n", stoa(addr), flags);
3379 * findbcastinter - find broadcast interface corresponding to address
3383 struct sockaddr_storage *addr
3386 #if !defined(MPE) && (defined(SIOCGIFCONF) || defined(SYS_WINNT))
3387 struct interface *interface;
3390 DPRINTF(4, ("Finding broadcast/multicast interface for addr %s in list of addresses\n",
3393 interface = findlocalinterface(addr, INT_LOOPBACK|INT_WILDCARD);
3395 if (interface != NULL)
3397 DPRINTF(4, ("Found bcast-/mcast- interface index #%d %s\n", interface->ifnum, interface->name));
3401 /* plan B - try to find something reasonable in our lists in case kernel lookup doesn't help */
3403 for (interface = ISC_LIST_HEAD(inter_list);
3405 interface = ISC_LIST_NEXT(interface, link))
3407 if (interface->flags & INT_WILDCARD)
3410 /* Don't bother with ignored interfaces */
3411 if (interface->ignore_packets == ISC_TRUE)
3415 * First look if this is the correct family
3417 if(interface->sin.ss_family != addr->ss_family)
3420 /* Skip the loopback addresses */
3421 if (interface->flags & INT_LOOPBACK)
3425 * If we are looking to match a multicast address grab it.
3427 if (addr_ismulticast(addr) == ISC_TRUE && interface->flags & INT_MULTICAST)
3429 #ifdef INCLUDE_IPV6_SUPPORT
3430 if(addr->ss_family == AF_INET6) {
3431 /* Only use link-local address for link-scope mcast */
3432 if(IN6_IS_ADDR_MC_LINKLOCAL(&((struct sockaddr_in6*)addr)->sin6_addr) &&
3433 !IN6_IS_ADDR_LINKLOCAL(&((struct sockaddr_in6*)&interface->sin)->sin6_addr)) {
3442 * We match only those interfaces marked as
3443 * broadcastable and either the explicit broadcast
3444 * address or the network portion of the IP address.
3447 if(addr->ss_family == AF_INET) {
3448 if (SOCKCMP(&interface->bcast, addr)) {
3451 if ((NSRCADR(&interface->sin) &
3452 NSRCADR(&interface->mask)) == (NSRCADR(addr) &
3453 NSRCADR(&interface->mask)))
3456 #ifdef INCLUDE_IPV6_SUPPORT
3457 else if(addr->ss_family == AF_INET6) {
3458 if (SOCKCMP(&interface->bcast, addr)) {
3461 if (SOCKCMP(netof(&interface->sin), netof(addr))) {
3467 #endif /* SIOCGIFCONF */
3468 if (interface == NULL) {
3469 DPRINTF(4, ("No bcast interface found for %s\n", stoa(addr)));
3470 return ANY_INTERFACE_CHOOSE(addr);
3472 DPRINTF(4, ("Found bcast-/mcast- interface index #%d %s\n", interface->ifnum, interface->name));
3479 * io_clr_stats - clear I/O module statistics
3484 packets_dropped = 0;
3485 packets_ignored = 0;
3486 packets_received = 0;
3488 packets_notsent = 0;
3492 io_timereset = current_time;
3498 * io_addclock - add a reference clock to the list and arrange that we
3499 * get SIGIO interrupts from it.
3503 struct refclockio *rio
3508 * Stuff the I/O structure in the list and mark the descriptor
3509 * in use. There is a harmless (I hope) race condition here.
3513 # ifdef HAVE_SIGNALED_IO
3514 if (init_clock_sig(rio))
3519 # elif defined(HAVE_IO_COMPLETION_PORT)
3520 if (io_completion_port_add_clock_io(rio))
3535 add_fd_to_list(rio->fd, FD_TYPE_FILE);
3542 * io_closeclock - close the clock in the I/O structure given
3546 struct refclockio *rio
3551 * Remove structure from the list
3559 register struct refclockio *rp;
3561 for (rp = refio; rp != NULL; rp = rp->next)
3562 if (rp->next == rio)
3564 rp->next = rio->next;
3575 * Close the descriptor.
3577 close_and_delete_fd_from_list(rio->fd);
3580 #endif /* REFCLOCK */
3583 * On NT a SOCKET is an unsigned int so we cannot possibly keep it in
3584 * an array. So we use one of the ISC_LIST functions to hold the
3585 * socket value and use that when we want to enumerate it.
3588 kill_asyncio(int startfd)
3595 lsock = ISC_LIST_HEAD(fd_list);
3596 while (lsock != NULL) {
3598 * careful here - list is being dismantled while
3599 * we scan it - setting next here insures that
3600 * we are able to correctly scan the list
3602 next = ISC_LIST_NEXT(lsock, link);
3604 * will remove socket from list
3606 close_and_delete_fd_from_list(lsock->fd);
3614 * Add and delete functions for the list of open sockets
3617 add_fd_to_list(SOCKET fd, enum desc_type type) {
3618 vsock_t *lsock = (vsock_t *)emalloc(sizeof(vsock_t));
3622 ISC_LIST_APPEND(fd_list, lsock, link);
3624 * I/O Completion Ports don't care about the select and FD_SET
3626 #ifndef HAVE_IO_COMPLETION_PORT
3628 * keep activefds in sync
3630 if (fd > maxactivefd)
3632 FD_SET( (u_int)fd, &activefds);
3637 close_and_delete_fd_from_list(SOCKET fd) {
3640 vsock_t *lsock = ISC_LIST_HEAD(fd_list);
3642 while(lsock != NULL) {
3643 next = ISC_LIST_NEXT(lsock, link);
3644 if(lsock->fd == fd) {
3645 ISC_LIST_DEQUEUE_TYPE(fd_list, lsock, link, vsock_t);
3647 switch (lsock->type) {
3648 case FD_TYPE_SOCKET:
3650 closesocket(lsock->fd);
3654 (void) close(lsock->fd);
3657 msyslog(LOG_ERR, "internal error - illegal descriptor type %d - EXITING", (int)lsock->type);
3663 * I/O Completion Ports don't care about select and fd_set
3665 #ifndef HAVE_IO_COMPLETION_PORT
3667 * remove from activefds
3669 FD_CLR( (u_int) fd, &activefds);
3671 if (fd == maxactivefd) {
3673 for (i = 0; i < maxactivefd; i++)
3674 if (FD_ISSET(i, &activefds))
3676 maxactivefd = newmax;
3686 add_addr_to_list(struct sockaddr_storage *addr, struct interface *interface){
3688 if (find_addr_in_list(addr) == NULL) {
3690 /* not there yet - add to list */
3691 remaddr_t *laddr = (remaddr_t *)emalloc(sizeof(remaddr_t));
3692 memcpy(&laddr->addr, addr, sizeof(struct sockaddr_storage));
3693 laddr->interface = interface;
3695 ISC_LIST_APPEND(remoteaddr_list, laddr, link);
3697 DPRINTF(4, ("Added addr %s to list of addresses\n",
3701 DPRINTF(4, ("WARNING: Attempt to add duplicate addr %s to address list\n",
3708 delete_addr_from_list(struct sockaddr_storage *addr) {
3711 remaddr_t *laddr = ISC_LIST_HEAD(remoteaddr_list);
3713 while(laddr != NULL) {
3714 next = ISC_LIST_NEXT(laddr, link);
3715 if(SOCKCMP(&laddr->addr, addr)) {
3716 ISC_LIST_DEQUEUE_TYPE(remoteaddr_list, laddr, link, remaddr_t);
3717 DPRINTF(4, ("Deleted addr %s from list of addresses\n",
3727 delete_interface_from_list(struct interface *iface) {
3729 remaddr_t *laddr = ISC_LIST_HEAD(remoteaddr_list);
3731 while(laddr != NULL) {
3732 next = ISC_LIST_NEXT(laddr, link);
3733 if (laddr->interface == iface) {
3734 ISC_LIST_DEQUEUE_TYPE(remoteaddr_list, laddr, link, remaddr_t);
3735 DPRINTF(4, ("Deleted addr %s for interface #%d %s from list of addresses\n",
3736 stoa(&laddr->addr), iface->ifnum, iface->name));
3743 static struct interface *
3744 find_addr_in_list(struct sockaddr_storage *addr) {
3747 remaddr_t *laddr = ISC_LIST_HEAD(remoteaddr_list);
3748 DPRINTF(4, ("Searching for addr %s in list of addresses - ",
3751 while(laddr != NULL) {
3752 next = ISC_LIST_NEXT(laddr, link);
3753 if(SOCKCMP(&laddr->addr, addr)) {
3754 DPRINTF(4, ("FOUND\n"));
3755 return laddr->interface;
3760 DPRINTF(4, ("NOT FOUND\n"));
3761 return NULL; /* Not found */
3765 * Find the given address with the associated flag in the list
3767 static struct interface *
3768 find_flagged_addr_in_list(struct sockaddr_storage *addr, int flag) {
3771 remaddr_t *laddr = ISC_LIST_HEAD(remoteaddr_list);
3772 DPRINTF(4, ("Finding addr %s in list of addresses\n",
3775 while(laddr != NULL) {
3776 next = ISC_LIST_NEXT(laddr, link);
3777 if(SOCKCMP(&laddr->addr, addr) && (laddr->interface->flags & flag)) {
3778 return laddr->interface;
3784 return NULL; /* Not found */
3787 #ifdef HAS_ROUTING_SOCKET
3788 #include <net/route.h>
3790 #ifndef UPDATE_GRACE
3791 #define UPDATE_GRACE 2 /* wait UPDATE_GRACE seconds before scanning */
3795 process_routing_msgs(struct asyncio_reader *reader)
3802 if (disable_dynamic_updates) {
3804 * discard ourselves if we are not need any more
3805 * usually happens when running unprivileged
3807 remove_asyncio_reader(reader);
3808 delete_asyncio_reader(reader);
3812 cnt = read(reader->fd, buffer, sizeof(buffer));
3815 msyslog(LOG_ERR, "i/o error on routing socket %m - disabling");
3816 remove_asyncio_reader(reader);
3817 delete_asyncio_reader(reader);
3822 * process routing message
3824 while ((p + sizeof(struct rt_msghdr)) <= (buffer + cnt))
3826 struct rt_msghdr *rtm;
3828 rtm = (struct rt_msghdr *)p;
3829 if (rtm->rtm_version != RTM_VERSION) {
3830 msyslog(LOG_ERR, "version mismatch on routing socket %m - disabling");
3831 remove_asyncio_reader(reader);
3832 delete_asyncio_reader(reader);
3836 switch (rtm->rtm_type) {
3861 #ifdef RTM_IFANNOUNCE
3862 case RTM_IFANNOUNCE:
3865 * we are keen on new and deleted addresses and if an interface goes up and down or routing changes
3867 DPRINTF(3, ("routing message op = %d: scheduling interface update\n", rtm->rtm_type));
3868 timer_interfacetimeout(current_time + UPDATE_GRACE);
3872 * the rest doesn't bother us.
3874 DPRINTF(4, ("routing message op = %d: ignored\n", rtm->rtm_type));
3877 p += rtm->rtm_msglen;
3882 * set up routing notifications
3885 init_async_notifications()
3887 struct asyncio_reader *reader;
3888 int fd = socket(PF_ROUTE, SOCK_RAW, 0);
3892 init_nonblocking_io(fd);
3893 #if defined(HAVE_SIGNALED_IO)
3894 init_socket_sig(fd);
3895 #endif /* HAVE_SIGNALED_IO */
3897 reader = new_asyncio_reader();
3900 reader->receiver = process_routing_msgs;
3902 add_asyncio_reader(reader, FD_TYPE_SOCKET);
3903 msyslog(LOG_INFO, "Listening on routing socket on fd #%d for interface updates", fd);
3905 msyslog(LOG_ERR, "unable to open routing socket (%m) - using polled interface update");
3910 init_async_notifications()