/contrib/ntp/ntpd/ntp_io.c

https://bitbucket.org/freebsd/freebsd-head/ · C · 4029 lines · 2744 code · 465 blank · 820 comment · 573 complexity · f6b7746f9e2b27cfdbf19b0d937c3239 MD5 · raw file

Large files are truncated click here to view the full file

  1. /*
  2. * ntp_io.c - input/output routines for ntpd. The socket-opening code
  3. * was shamelessly stolen from ntpd.
  4. */
  5. #ifdef HAVE_CONFIG_H
  6. # include <config.h>
  7. #endif
  8. #include "ntp_machine.h"
  9. #include "ntpd.h"
  10. #include "ntp_io.h"
  11. #include "iosignal.h"
  12. #include "ntp_refclock.h"
  13. #include "ntp_stdlib.h"
  14. #include "ntp_request.h"
  15. #include "ntp.h"
  16. #include "ntp_unixtime.h"
  17. /* Don't include ISC's version of IPv6 variables and structures */
  18. #define ISC_IPV6_H 1
  19. #include <isc/interfaceiter.h>
  20. #include <isc/list.h>
  21. #include <isc/result.h>
  22. #ifdef SIM
  23. #include "ntpsim.h"
  24. #endif
  25. #include <stdio.h>
  26. #include <signal.h>
  27. #ifdef HAVE_SYS_PARAM_H
  28. # include <sys/param.h>
  29. #endif /* HAVE_SYS_PARAM_H */
  30. #ifdef HAVE_SYS_IOCTL_H
  31. # include <sys/ioctl.h>
  32. #endif
  33. #ifdef HAVE_SYS_SOCKIO_H /* UXPV: SIOC* #defines (Frank Vance <fvance@waii.com>) */
  34. # include <sys/sockio.h>
  35. #endif
  36. #ifdef HAVE_SYS_UIO_H
  37. # include <sys/uio.h>
  38. #endif
  39. /*
  40. * setsockopt does not always have the same arg declaration
  41. * across all platforms. If it's not defined we make it empty
  42. */
  43. #ifndef SETSOCKOPT_ARG_CAST
  44. #define SETSOCKOPT_ARG_CAST
  45. #endif
  46. /*
  47. * Set up some macros to look for IPv6 and IPv6 multicast
  48. */
  49. #if defined(ISC_PLATFORM_HAVEIPV6) && !defined(DISABLE_IPV6)
  50. #define INCLUDE_IPV6_SUPPORT
  51. #if defined(INCLUDE_IPV6_SUPPORT) && defined(IPV6_JOIN_GROUP) && defined(IPV6_LEAVE_GROUP)
  52. #define INCLUDE_IPV6_MULTICAST_SUPPORT
  53. #endif /* IPV6 Multicast Support */
  54. #endif /* IPv6 Support */
  55. #ifdef INCLUDE_IPV6_SUPPORT
  56. #include <netinet/in.h>
  57. #include <net/if_var.h>
  58. #include <netinet/in_var.h>
  59. #endif /* !INCLUDE_IPV6_SUPPORT */
  60. extern int listen_to_virtual_ips;
  61. extern const char *specific_interface;
  62. #if defined(SO_TIMESTAMP) && defined(SCM_TIMESTAMP)
  63. #if defined(CMSG_FIRSTHDR)
  64. #define HAVE_TIMESTAMP
  65. #define USE_TIMESTAMP_CMSG
  66. #ifndef TIMESTAMP_CTLMSGBUF_SIZE
  67. #define TIMESTAMP_CTLMSGBUF_SIZE 1536 /* moderate default */
  68. #endif
  69. #else
  70. /* fill in for old/other timestamp interfaces */
  71. #endif
  72. #endif
  73. #if defined(SYS_WINNT)
  74. #include <transmitbuff.h>
  75. #include <isc/win32os.h>
  76. /*
  77. * Define this macro to control the behavior of connection
  78. * resets on UDP sockets. See Microsoft KnowledgeBase Article Q263823
  79. * for details.
  80. * NOTE: This requires that Windows 2000 systems install Service Pack 2
  81. * or later.
  82. */
  83. #ifndef SIO_UDP_CONNRESET
  84. #define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR,12)
  85. #endif
  86. /*
  87. * Windows C runtime ioctl() can't deal properly with sockets,
  88. * map to ioctlsocket for this source file.
  89. */
  90. #define ioctl(fd, opt, val) ioctlsocket((fd), (opt), (u_long *)(val))
  91. #endif /* SYS_WINNT */
  92. /*
  93. * We do asynchronous input using the SIGIO facility. A number of
  94. * recvbuf buffers are preallocated for input. In the signal
  95. * handler we poll to see which sockets are ready and read the
  96. * packets from them into the recvbuf's along with a time stamp and
  97. * an indication of the source host and the interface it was received
  98. * through. This allows us to get as accurate receive time stamps
  99. * as possible independent of other processing going on.
  100. *
  101. * We watch the number of recvbufs available to the signal handler
  102. * and allocate more when this number drops below the low water
  103. * mark. If the signal handler should run out of buffers in the
  104. * interim it will drop incoming frames, the idea being that it is
  105. * better to drop a packet than to be inaccurate.
  106. */
  107. /*
  108. * Other statistics of possible interest
  109. */
  110. volatile u_long packets_dropped; /* total number of packets dropped on reception */
  111. volatile u_long packets_ignored; /* packets received on wild card interface */
  112. volatile u_long packets_received; /* total number of packets received */
  113. u_long packets_sent; /* total number of packets sent */
  114. u_long packets_notsent; /* total number of packets which couldn't be sent */
  115. volatile u_long handler_calls; /* number of calls to interrupt handler */
  116. volatile u_long handler_pkts; /* number of pkts received by handler */
  117. u_long io_timereset; /* time counters were reset */
  118. /*
  119. * Interface stuff
  120. */
  121. struct interface *any_interface; /* default ipv4 interface */
  122. struct interface *any6_interface; /* default ipv6 interface */
  123. struct interface *loopback_interface; /* loopback ipv4 interface */
  124. int ninterfaces; /* Total number of interfaces */
  125. volatile int disable_dynamic_updates; /* when set to != 0 dynamic updates won't happen */
  126. #ifdef REFCLOCK
  127. /*
  128. * Refclock stuff. We keep a chain of structures with data concerning
  129. * the guys we are doing I/O for.
  130. */
  131. static struct refclockio *refio;
  132. #endif /* REFCLOCK */
  133. /*
  134. * Define what the possible "soft" errors can be. These are non-fatal returns
  135. * of various network related functions, like recv() and so on.
  136. *
  137. * For some reason, BSDI (and perhaps others) will sometimes return <0
  138. * from recv() but will have errno==0. This is broken, but we have to
  139. * work around it here.
  140. */
  141. #define SOFT_ERROR(e) ((e) == EAGAIN || \
  142. (e) == EWOULDBLOCK || \
  143. (e) == EINTR || \
  144. (e) == 0)
  145. /*
  146. * File descriptor masks etc. for call to select
  147. * Not needed for I/O Completion Ports
  148. */
  149. fd_set activefds;
  150. int maxactivefd;
  151. /*
  152. * bit alternating value to detect verified interfaces during an update cycle
  153. */
  154. static u_char sys_interphase = 0;
  155. static struct interface *new_interface P((struct interface *));
  156. static void add_interface P((struct interface *));
  157. static int update_interfaces P((u_short, interface_receiver_t, void *));
  158. static void remove_interface P((struct interface *));
  159. static struct interface *create_interface P((u_short, struct interface *));
  160. static int move_fd P((SOCKET));
  161. /*
  162. * Multicast functions
  163. */
  164. static isc_boolean_t addr_ismulticast P((struct sockaddr_storage *));
  165. /*
  166. * Not all platforms support multicast
  167. */
  168. #ifdef MCAST
  169. static isc_boolean_t socket_multicast_enable P((struct interface *, int, struct sockaddr_storage *));
  170. static isc_boolean_t socket_multicast_disable P((struct interface *, struct sockaddr_storage *));
  171. #endif
  172. #ifdef DEBUG
  173. static void print_interface P((struct interface *, char *, char *));
  174. #define DPRINT_INTERFACE(_LVL_, _ARGS_) do { if (debug >= (_LVL_)) { print_interface _ARGS_; } } while (0)
  175. #else
  176. #define DPRINT_INTERFACE(_LVL_, _ARGS_) do {} while (0)
  177. #endif
  178. typedef struct vsock vsock_t;
  179. enum desc_type { FD_TYPE_SOCKET, FD_TYPE_FILE };
  180. struct vsock {
  181. SOCKET fd;
  182. enum desc_type type;
  183. ISC_LINK(vsock_t) link;
  184. };
  185. #if !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET)
  186. /*
  187. * async notification processing (e. g. routing sockets)
  188. */
  189. /*
  190. * support for receiving data on fd that is not a refclock or a socket
  191. * like e. g. routing sockets
  192. */
  193. struct asyncio_reader {
  194. SOCKET fd; /* fd to be read */
  195. void *data; /* possibly local data */
  196. void (*receiver)(struct asyncio_reader *); /* input handler */
  197. ISC_LINK(struct asyncio_reader) link; /* the list this is being kept in */
  198. };
  199. ISC_LIST(struct asyncio_reader) asyncio_reader_list;
  200. static void delete_asyncio_reader P((struct asyncio_reader *));
  201. static struct asyncio_reader *new_asyncio_reader P((void));
  202. static void add_asyncio_reader P((struct asyncio_reader *, enum desc_type));
  203. static void remove_asyncio_reader P((struct asyncio_reader *));
  204. #endif /* !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET) */
  205. static void init_async_notifications P((void));
  206. static int create_sockets P((u_short));
  207. static SOCKET open_socket P((struct sockaddr_storage *, int, int, struct interface *));
  208. static char * fdbits P((int, fd_set *));
  209. static void set_reuseaddr P((int));
  210. static isc_boolean_t socket_broadcast_enable P((struct interface *, SOCKET, struct sockaddr_storage *));
  211. static isc_boolean_t socket_broadcast_disable P((struct interface *, struct sockaddr_storage *));
  212. ISC_LIST(vsock_t) fd_list;
  213. typedef struct remaddr remaddr_t;
  214. struct remaddr {
  215. struct sockaddr_storage addr;
  216. struct interface *interface;
  217. ISC_LINK(remaddr_t) link;
  218. };
  219. ISC_LIST(remaddr_t) remoteaddr_list;
  220. ISC_LIST(struct interface) inter_list;
  221. static struct interface *wildipv4 = NULL;
  222. static struct interface *wildipv6 = NULL;
  223. static void add_fd_to_list P((SOCKET, enum desc_type));
  224. static void close_and_delete_fd_from_list P((SOCKET));
  225. static void add_addr_to_list P((struct sockaddr_storage *, struct interface *));
  226. static void delete_addr_from_list P((struct sockaddr_storage *));
  227. static struct interface *find_addr_in_list P((struct sockaddr_storage *));
  228. static struct interface *find_flagged_addr_in_list P((struct sockaddr_storage *, int));
  229. static void create_wildcards P((u_short));
  230. static isc_boolean_t address_okay P((struct interface *));
  231. static void convert_isc_if P((isc_interface_t *, struct interface *, u_short));
  232. static void delete_interface_from_list P((struct interface *));
  233. static struct interface *getinterface P((struct sockaddr_storage *, int));
  234. static struct interface *findlocalinterface P((struct sockaddr_storage *, int));
  235. static struct interface *findlocalcastinterface P((struct sockaddr_storage *, int));
  236. /*
  237. * Routines to read the ntp packets
  238. */
  239. #if !defined(HAVE_IO_COMPLETION_PORT)
  240. static inline int read_network_packet P((SOCKET, struct interface *, l_fp));
  241. static inline int read_refclock_packet P((SOCKET, struct refclockio *, l_fp));
  242. #endif
  243. #ifdef SYS_WINNT
  244. /*
  245. * Windows 2000 systems incorrectly cause UDP sockets using WASRecvFrom
  246. * to not work correctly, returning a WSACONNRESET error when a WSASendTo
  247. * fails with an "ICMP port unreachable" response and preventing the
  248. * socket from using the WSARecvFrom in subsequent operations.
  249. * The function below fixes this, but requires that Windows 2000
  250. * Service Pack 2 or later be installed on the system. NT 4.0
  251. * systems are not affected by this and work correctly.
  252. * See Microsoft Knowledge Base Article Q263823 for details of this.
  253. */
  254. void
  255. connection_reset_fix(
  256. SOCKET fd,
  257. struct sockaddr_storage *addr
  258. )
  259. {
  260. DWORD dwBytesReturned = 0;
  261. BOOL bNewBehavior = FALSE;
  262. DWORD status;
  263. /*
  264. * disable bad behavior using IOCTL: SIO_UDP_CONNRESET
  265. * NT 4.0 has no problem
  266. */
  267. if (isc_win32os_majorversion() >= 5) {
  268. status = WSAIoctl(fd, SIO_UDP_CONNRESET, &bNewBehavior,
  269. sizeof(bNewBehavior), NULL, 0,
  270. &dwBytesReturned, NULL, NULL);
  271. if (SOCKET_ERROR == status)
  272. netsyslog(LOG_ERR, "connection_reset_fix() "
  273. "failed for address %s: %m",
  274. stoa(addr));
  275. }
  276. }
  277. #endif
  278. /*
  279. * on Unix systems the stdio library typically
  280. * makes use of file descriptors in the lower
  281. * integer range. stdio usually will make use
  282. * of the file descriptor in the range of
  283. * [0..FOPEN_MAX)
  284. * in order to keep this range clean for socket
  285. * file descriptors we attempt to move them above
  286. * FOPEM_MAX. This is not as easy as it sounds as
  287. * FOPEN_MAX changes from implementation to implementation
  288. * and may exceed to current file decriptor limits.
  289. * We are using following strategy:
  290. * - keep a current socket fd boundary initialized with
  291. * max(0, min(getdtablesize() - FD_CHUNK, FOPEN_MAX))
  292. * - attempt to move the descriptor to the boundary or
  293. * above.
  294. * - if that fails and boundary > 0 set boundary
  295. * to min(0, socket_fd_boundary - FD_CHUNK)
  296. * -> retry
  297. * if failure and boundary == 0 return old fd
  298. * - on success close old fd return new fd
  299. *
  300. * effects:
  301. * - fds will be moved above the socket fd boundary
  302. * if at all possible.
  303. * - the socket boundary will be reduced until
  304. * allocation is possible or 0 is reached - at this
  305. * point the algrithm will be disabled
  306. */
  307. static int move_fd(SOCKET fd)
  308. {
  309. #if !defined(SYS_WINNT) && defined(F_DUPFD)
  310. #ifndef FD_CHUNK
  311. #define FD_CHUNK 10
  312. #endif
  313. /*
  314. * number of fds we would like to have for
  315. * stdio FILE* available.
  316. * we can pick a "low" number as our use of
  317. * FILE* is limited to log files and temporarily
  318. * to data and config files. Except for log files
  319. * we don't keep the other FILE* open beyond the
  320. * scope of the function that opened it.
  321. */
  322. #ifndef FD_PREFERRED_SOCKBOUNDARY
  323. #define FD_PREFERRED_SOCKBOUNDARY 48
  324. #endif
  325. #ifndef HAVE_GETDTABLESIZE
  326. /*
  327. * if we have no idea about the max fd value set up things
  328. * so we will start at FOPEN_MAX
  329. */
  330. #define getdtablesize() (FOPEN_MAX+FD_CHUNK)
  331. #endif
  332. #ifndef FOPEN_MAX
  333. #define FOPEN_MAX 20 /* assume that for the lack of anything better */
  334. #endif
  335. static SOCKET socket_boundary = -1;
  336. SOCKET newfd;
  337. /*
  338. * check whether boundary has be set up
  339. * already
  340. */
  341. if (socket_boundary == -1) {
  342. socket_boundary = max(0, min(getdtablesize() - FD_CHUNK,
  343. min(FOPEN_MAX, FD_PREFERRED_SOCKBOUNDARY)));
  344. #ifdef DEBUG
  345. msyslog(LOG_DEBUG, "ntp_io: estimated max descriptors: %d, initial socket boundary: %d",
  346. getdtablesize(), socket_boundary);
  347. #endif
  348. }
  349. /*
  350. * Leave a space for stdio to work in. potentially moving the
  351. * socket_boundary lower until allocation succeeds.
  352. */
  353. do {
  354. if (fd >= 0 && fd < socket_boundary) {
  355. /* inside reserved range: attempt to move fd */
  356. newfd = fcntl(fd, F_DUPFD, socket_boundary);
  357. if (newfd != -1) {
  358. /* success: drop the old one - return the new one */
  359. (void)close(fd);
  360. return (newfd);
  361. }
  362. } else {
  363. /* outside reserved range: no work - return the original one */
  364. return (fd);
  365. }
  366. socket_boundary = max(0, socket_boundary - FD_CHUNK);
  367. #ifdef DEBUG
  368. msyslog(LOG_DEBUG, "ntp_io: selecting new socket boundary: %d",
  369. socket_boundary);
  370. #endif
  371. } while (socket_boundary > 0);
  372. #endif /* !defined(SYS_WINNT) && defined(F_DUPFD) */
  373. return (fd);
  374. }
  375. #ifdef DEBUG_TIMING
  376. /*
  377. * collect timing information for various processing
  378. * paths. currently we only pass then on to the file
  379. * for later processing. this could also do histogram
  380. * based analysis in other to reduce the load (and skew)
  381. * dur to the file output
  382. */
  383. void
  384. collect_timing(struct recvbuf *rb, const char *tag, int count, l_fp *dts)
  385. {
  386. char buf[2048];
  387. snprintf(buf, sizeof(buf), "%s %d %s %s",
  388. (rb != NULL) ?
  389. ((rb->dstadr) ? stoa(&rb->recv_srcadr) : "-REFCLOCK-") : "-",
  390. count, lfptoa(dts, 9), tag);
  391. record_timing_stats(buf);
  392. }
  393. #endif
  394. /*
  395. * About dynamic interfaces, sockets, reception and more...
  396. *
  397. * the code solves following tasks:
  398. *
  399. * - keep a current list of active interfaces in order
  400. * to bind to to the interface address on NTP_PORT so that
  401. * all wild and specific bindings for NTP_PORT are taken by ntpd
  402. * to avoid other daemons messing with the time or sockets.
  403. * - all interfaces keep a list of peers that are referencing
  404. * the interface in order to quickly re-assign the peers to
  405. * new interface in case an interface is deleted (=> gone from system or
  406. * down)
  407. * - have a preconfigured socket ready with the right local address
  408. * for transmission and reception
  409. * - have an address list for all destination addresses used within ntpd
  410. * to find the "right" preconfigured socket.
  411. * - facilitate updating the internal interface list with respect to
  412. * the current kernel state
  413. *
  414. * special issues:
  415. *
  416. * - mapping of multicast addresses to the interface affected is not always
  417. * one to one - especially on hosts with multiple interfaces
  418. * the code here currently allocates a separate interface entry for those
  419. * multicast addresses
  420. * iff it is able to bind to a *new* socket with the multicast address (flags |= MCASTIF)
  421. * in case of failure the multicast address is bound to an existing interface.
  422. * - on some systems it is perfectly legal to assign the same address to
  423. * multiple interfaces. Therefore this code does not keep a list of interfaces
  424. * but a list of interfaces that represent a unique address as determined by the kernel
  425. * by the procedure in findlocalinterface. Thus it is perfectly legal to see only
  426. * one representative of a group of real interfaces if they share the same address.
  427. *
  428. * Frank Kardel 20050910
  429. */
  430. /*
  431. * init_io - initialize I/O data structures and call socket creation routine
  432. */
  433. void
  434. init_io(void)
  435. {
  436. #ifdef SYS_WINNT
  437. init_io_completion_port();
  438. if (!Win32InitSockets())
  439. {
  440. netsyslog(LOG_ERR, "No useable winsock.dll: %m");
  441. exit(1);
  442. }
  443. init_transmitbuff();
  444. #endif /* SYS_WINNT */
  445. /*
  446. * Init buffer free list and stat counters
  447. */
  448. init_recvbuff(RECV_INIT);
  449. packets_dropped = packets_received = 0;
  450. packets_ignored = 0;
  451. packets_sent = packets_notsent = 0;
  452. handler_calls = handler_pkts = 0;
  453. io_timereset = 0;
  454. loopback_interface = NULL;
  455. any_interface = NULL;
  456. any6_interface = NULL;
  457. #ifdef REFCLOCK
  458. refio = NULL;
  459. #endif
  460. #if defined(HAVE_SIGNALED_IO)
  461. (void) set_signal();
  462. #endif
  463. ISC_LIST_INIT(fd_list);
  464. #if !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET)
  465. ISC_LIST_INIT(asyncio_reader_list);
  466. #endif
  467. ISC_LIST_INIT(remoteaddr_list);
  468. ISC_LIST_INIT(inter_list);
  469. /*
  470. * Create the sockets
  471. */
  472. BLOCKIO();
  473. (void) create_sockets(htons(NTP_PORT));
  474. UNBLOCKIO();
  475. init_async_notifications();
  476. DPRINTF(3, ("init_io: maxactivefd %d\n", maxactivefd));
  477. }
  478. #ifdef DEBUG
  479. /*
  480. * function to dump the contents of the interface structure
  481. * for debugging use only.
  482. */
  483. void
  484. interface_dump(struct interface *itf)
  485. {
  486. u_char* cp;
  487. int i;
  488. /* Limit the size of the sockaddr_storage hex dump */
  489. int maxsize = min(32, sizeof(struct sockaddr_storage));
  490. printf("Dumping interface: %p\n", itf);
  491. printf("fd = %d\n", itf->fd);
  492. printf("bfd = %d\n", itf->bfd);
  493. printf("sin = %s,\n", stoa(&(itf->sin)));
  494. cp = (u_char*) &(itf->sin);
  495. for(i = 0; i < maxsize; i++)
  496. {
  497. printf("%02x", *cp++);
  498. if((i+1)%4 == 0)
  499. printf(" ");
  500. }
  501. printf("\n");
  502. printf("bcast = %s,\n", stoa(&(itf->bcast)));
  503. cp = (u_char*) &(itf->bcast);
  504. for(i = 0; i < maxsize; i++)
  505. {
  506. printf("%02x", *cp++);
  507. if((i+1)%4 == 0)
  508. printf(" ");
  509. }
  510. printf("\n");
  511. printf("mask = %s,\n", stoa(&(itf->mask)));
  512. cp = (u_char*) &(itf->mask);
  513. for(i = 0; i < maxsize; i++)
  514. {
  515. printf("%02x", *cp++);
  516. if((i+1)%4 == 0)
  517. printf(" ");
  518. }
  519. printf("\n");
  520. printf("name = %s\n", itf->name);
  521. printf("flags = 0x%08x\n", itf->flags);
  522. printf("last_ttl = %d\n", itf->last_ttl);
  523. printf("addr_refid = %08x\n", itf->addr_refid);
  524. printf("num_mcast = %d\n", itf->num_mcast);
  525. printf("received = %ld\n", itf->received);
  526. printf("sent = %ld\n", itf->sent);
  527. printf("notsent = %ld\n", itf->notsent);
  528. printf("ifindex = %u\n", itf->ifindex);
  529. printf("scopeid = %u\n", itf->scopeid);
  530. printf("peercnt = %u\n", itf->peercnt);
  531. printf("phase = %u\n", itf->phase);
  532. }
  533. /*
  534. * print_interface - helper to output debug information
  535. */
  536. static void
  537. print_interface(struct interface *iface, char *pfx, char *sfx)
  538. {
  539. printf("%sinterface #%d: fd=%d, bfd=%d, name=%s, flags=0x%x, scope=%d, ifindex=%d",
  540. pfx,
  541. iface->ifnum,
  542. iface->fd,
  543. iface->bfd,
  544. iface->name,
  545. iface->flags,
  546. iface->scopeid,
  547. iface->ifindex);
  548. /* Leave these as three printf calls. */
  549. printf(", sin=%s",
  550. stoa((&iface->sin)));
  551. if (iface->flags & INT_BROADCAST)
  552. printf(", bcast=%s,",
  553. stoa((&iface->bcast)));
  554. if (iface->family == AF_INET)
  555. printf(", mask=%s",
  556. stoa((&iface->mask)));
  557. printf(", %s:%s", iface->ignore_packets == ISC_FALSE ? "Enabled" : "Disabled", sfx);
  558. if (debug > 4) /* in-depth debugging only */
  559. interface_dump(iface);
  560. }
  561. #endif
  562. #if !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET)
  563. /*
  564. * create an asyncio_reader structure
  565. */
  566. static struct asyncio_reader *
  567. new_asyncio_reader()
  568. {
  569. struct asyncio_reader *reader;
  570. reader = (struct asyncio_reader *)emalloc(sizeof(struct asyncio_reader));
  571. memset((char *)reader, 0, sizeof(*reader));
  572. ISC_LINK_INIT(reader, link);
  573. reader->fd = INVALID_SOCKET;
  574. return reader;
  575. }
  576. /*
  577. * delete a reader
  578. */
  579. static void
  580. delete_asyncio_reader(struct asyncio_reader *reader)
  581. {
  582. free(reader);
  583. }
  584. /*
  585. * add asynchio_reader
  586. */
  587. static void
  588. add_asyncio_reader(struct asyncio_reader *reader, enum desc_type type)
  589. {
  590. ISC_LIST_APPEND(asyncio_reader_list, reader, link);
  591. add_fd_to_list(reader->fd, type);
  592. }
  593. /*
  594. * remove asynchio_reader
  595. */
  596. static void
  597. remove_asyncio_reader(struct asyncio_reader *reader)
  598. {
  599. ISC_LIST_UNLINK_TYPE(asyncio_reader_list, reader, link, struct asyncio_reader);
  600. if (reader->fd != INVALID_SOCKET)
  601. close_and_delete_fd_from_list(reader->fd);
  602. reader->fd = INVALID_SOCKET;
  603. }
  604. #endif /* !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET) */
  605. /*
  606. * interface list enumerator - visitor pattern
  607. */
  608. void
  609. interface_enumerate(interface_receiver_t receiver, void *data)
  610. {
  611. interface_info_t ifi;
  612. struct interface *interf;
  613. ifi.action = IFS_EXISTS;
  614. for (interf = ISC_LIST_HEAD(inter_list);
  615. interf != NULL;
  616. interf = ISC_LIST_NEXT(interf, link)) {
  617. ifi.interface = interf;
  618. receiver(data, &ifi);
  619. }
  620. }
  621. /*
  622. * do standard initialization of interface structure
  623. */
  624. static void
  625. init_interface(struct interface *interface)
  626. {
  627. memset((char *)interface, 0, sizeof(struct interface));
  628. ISC_LINK_INIT(interface, link);
  629. ISC_LIST_INIT(interface->peers);
  630. interface->fd = INVALID_SOCKET;
  631. interface->bfd = INVALID_SOCKET;
  632. interface->num_mcast = 0;
  633. interface->received = 0;
  634. interface->sent = 0;
  635. interface->notsent = 0;
  636. interface->peercnt = 0;
  637. interface->phase = sys_interphase;
  638. }
  639. /*
  640. * create new interface structure initialize from
  641. * template structure or via standard initialization
  642. * function
  643. */
  644. static struct interface *
  645. new_interface(struct interface *interface)
  646. {
  647. static u_int sys_ifnum = 0;
  648. struct interface *iface = (struct interface *)emalloc(sizeof(struct interface));
  649. if (interface != NULL)
  650. {
  651. memcpy((char*)iface, (char*)interface, sizeof(*interface));
  652. }
  653. else
  654. {
  655. init_interface(iface);
  656. }
  657. iface->ifnum = sys_ifnum++; /* count every new instance of an interface in the system */
  658. iface->starttime = current_time;
  659. return iface;
  660. }
  661. /*
  662. * return interface storage into free memory pool
  663. */
  664. static void
  665. delete_interface(struct interface *interface)
  666. {
  667. free(interface);
  668. }
  669. /*
  670. * link interface into list of known interfaces
  671. */
  672. static void
  673. add_interface(struct interface *interface)
  674. {
  675. static struct interface *listhead = NULL;
  676. /*
  677. * For ntpd, the first few interfaces (wildcard, localhost)
  678. * will never be removed. This means inter_list.head is
  679. * unchanging once initialized. Take advantage of that to
  680. * watch for changes and catch corruption earlier. This
  681. * helped track down corruption caused by using FD_SET with
  682. * a descriptor numerically larger than FD_SETSIZE.
  683. */
  684. if (NULL == listhead)
  685. listhead = inter_list.head;
  686. if (listhead != inter_list.head) {
  687. msyslog(LOG_ERR, "add_interface inter_list.head corrupted: was %p now %p",
  688. listhead, inter_list.head);
  689. exit(1);
  690. }
  691. /*
  692. * Calculate the address hash
  693. */
  694. interface->addr_refid = addr2refid(&interface->sin);
  695. ISC_LIST_APPEND(inter_list, interface, link);
  696. ninterfaces++;
  697. }
  698. /*
  699. * remove interface from known interface list and clean up
  700. * associated resources
  701. */
  702. static void
  703. remove_interface(struct interface *interface)
  704. {
  705. struct sockaddr_storage resmask;
  706. ISC_LIST_UNLINK_TYPE(inter_list, interface, link, struct interface);
  707. delete_interface_from_list(interface);
  708. if (interface->fd != INVALID_SOCKET)
  709. {
  710. msyslog(LOG_INFO, "Deleting interface #%d %s, %s#%d, interface stats: received=%ld, sent=%ld, dropped=%ld, active_time=%ld secs",
  711. interface->ifnum,
  712. interface->name,
  713. stoa((&interface->sin)),
  714. NTP_PORT, /* XXX should extract port from sin structure */
  715. interface->received,
  716. interface->sent,
  717. interface->notsent,
  718. current_time - interface->starttime);
  719. close_and_delete_fd_from_list(interface->fd);
  720. }
  721. if (interface->bfd != INVALID_SOCKET)
  722. {
  723. msyslog(LOG_INFO, "Deleting interface #%d %s, broadcast address %s#%d",
  724. interface->ifnum,
  725. interface->name,
  726. stoa((&interface->bcast)),
  727. (u_short) NTP_PORT); /* XXX extract port from sin structure */
  728. close_and_delete_fd_from_list(interface->bfd);
  729. }
  730. ninterfaces--;
  731. ntp_monclearinterface(interface);
  732. /* remove restrict interface entry */
  733. /*
  734. * Blacklist bound interface address
  735. */
  736. SET_HOSTMASK(&resmask, interface->sin.ss_family);
  737. hack_restrict(RESTRICT_REMOVEIF, &interface->sin, &resmask,
  738. RESM_NTPONLY|RESM_INTERFACE, RES_IGNORE);
  739. }
  740. static void
  741. list_if_listening(struct interface *interface, u_short port)
  742. {
  743. msyslog(LOG_INFO, "Listening on interface #%d %s, %s#%d %s",
  744. interface->ifnum,
  745. interface->name,
  746. stoa((&interface->sin)),
  747. ntohs( (u_short) port),
  748. (interface->ignore_packets == ISC_FALSE) ?
  749. "Enabled": "Disabled");
  750. }
  751. static void
  752. create_wildcards(u_short port) {
  753. isc_boolean_t okipv4 = ISC_TRUE;
  754. /*
  755. * create pseudo-interface with wildcard IPv4 address
  756. */
  757. #ifdef IPV6_V6ONLY
  758. if(isc_net_probeipv4() != ISC_R_SUCCESS)
  759. okipv4 = ISC_FALSE;
  760. #endif
  761. if(okipv4 == ISC_TRUE) {
  762. struct interface *interface = new_interface(NULL);
  763. interface->family = AF_INET;
  764. interface->sin.ss_family = AF_INET;
  765. ((struct sockaddr_in*)&interface->sin)->sin_addr.s_addr = htonl(INADDR_ANY);
  766. ((struct sockaddr_in*)&interface->sin)->sin_port = port;
  767. (void) strncpy(interface->name, "wildcard", sizeof(interface->name));
  768. interface->mask.ss_family = AF_INET;
  769. ((struct sockaddr_in*)&interface->mask)->sin_addr.s_addr = htonl(~(u_int32)0);
  770. interface->flags = INT_BROADCAST | INT_UP | INT_WILDCARD;
  771. interface->ignore_packets = ISC_TRUE;
  772. #if defined(MCAST)
  773. /*
  774. * enable possible multicast reception on the broadcast socket
  775. */
  776. interface->bcast.ss_family = AF_INET;
  777. ((struct sockaddr_in*)&interface->bcast)->sin_port = port;
  778. ((struct sockaddr_in*)&interface->bcast)->sin_addr.s_addr = htonl(INADDR_ANY);
  779. #endif /* MCAST */
  780. interface->fd = open_socket(&interface->sin,
  781. interface->flags, 1, interface);
  782. if (interface->fd != INVALID_SOCKET) {
  783. wildipv4 = interface;
  784. any_interface = interface;
  785. add_addr_to_list(&interface->sin, interface);
  786. add_interface(interface);
  787. list_if_listening(interface, port);
  788. } else {
  789. msyslog(LOG_ERR, "unable to bind to wildcard socket address %s - another process may be running - EXITING",
  790. stoa((&interface->sin)));
  791. exit(1);
  792. }
  793. }
  794. #ifdef INCLUDE_IPV6_SUPPORT
  795. /*
  796. * create pseudo-interface with wildcard IPv6 address
  797. */
  798. if (isc_net_probeipv6() == ISC_R_SUCCESS) {
  799. struct interface *interface = new_interface(NULL);
  800. interface->family = AF_INET6;
  801. interface->sin.ss_family = AF_INET6;
  802. ((struct sockaddr_in6*)&interface->sin)->sin6_addr = in6addr_any;
  803. ((struct sockaddr_in6*)&interface->sin)->sin6_port = port;
  804. # ifdef ISC_PLATFORM_HAVESCOPEID
  805. ((struct sockaddr_in6*)&interface->sin)->sin6_scope_id = 0;
  806. # endif
  807. (void) strncpy(interface->name, "wildcard", sizeof(interface->name));
  808. interface->mask.ss_family = AF_INET6;
  809. memset(&((struct sockaddr_in6*)&interface->mask)->sin6_addr.s6_addr, 0xff, sizeof(struct in6_addr));
  810. interface->flags = INT_UP | INT_WILDCARD;
  811. interface->ignore_packets = ISC_TRUE;
  812. interface->fd = open_socket(&interface->sin,
  813. interface->flags, 1, interface);
  814. if (interface->fd != INVALID_SOCKET) {
  815. wildipv6 = interface;
  816. any6_interface = interface;
  817. add_addr_to_list(&interface->sin, interface);
  818. add_interface(interface);
  819. list_if_listening(interface, port);
  820. } else {
  821. msyslog(LOG_ERR, "unable to bind to wildcard socket address %s - another process may be running - EXITING",
  822. stoa((&interface->sin)));
  823. exit(1);
  824. }
  825. }
  826. #endif
  827. }
  828. static isc_boolean_t
  829. address_okay(struct interface *iface) {
  830. DPRINTF(4, ("address_okay: listen Virtual: %d, IF name: %s\n",
  831. listen_to_virtual_ips, iface->name));
  832. /*
  833. * Always allow the loopback
  834. */
  835. if((iface->flags & INT_LOOPBACK) != 0) {
  836. DPRINTF(4, ("address_okay: loopback - OK\n"));
  837. return (ISC_TRUE);
  838. }
  839. /*
  840. * Check if the interface is specified
  841. */
  842. if (specific_interface != NULL) {
  843. if (strcasecmp(iface->name, specific_interface) == 0) {
  844. DPRINTF(4, ("address_okay: specific interface name matched - OK\n"));
  845. return (ISC_TRUE);
  846. } else {
  847. DPRINTF(4, ("address_okay: specific interface name NOT matched - FAIL\n"));
  848. return (ISC_FALSE);
  849. }
  850. }
  851. else {
  852. if (listen_to_virtual_ips == 0 &&
  853. (strchr(iface->name, (int)':') != NULL)) {
  854. DPRINTF(4, ("address_okay: virtual ip/alias - FAIL\n"));
  855. return (ISC_FALSE);
  856. }
  857. }
  858. DPRINTF(4, ("address_okay: OK\n"));
  859. return (ISC_TRUE);
  860. }
  861. static void
  862. convert_isc_if(isc_interface_t *isc_if, struct interface *itf, u_short port)
  863. {
  864. itf->scopeid = 0;
  865. itf->family = (short) isc_if->af;
  866. strcpy(itf->name, isc_if->name);
  867. if(isc_if->af == AF_INET) {
  868. itf->sin.ss_family = (u_short) isc_if->af;
  869. memcpy(&(((struct sockaddr_in*)&itf->sin)->sin_addr),
  870. &(isc_if->address.type.in),
  871. sizeof(struct in_addr));
  872. ((struct sockaddr_in*)&itf->sin)->sin_port = port;
  873. if((isc_if->flags & INTERFACE_F_BROADCAST) != 0) {
  874. itf->flags |= INT_BROADCAST;
  875. itf->bcast.ss_family = itf->sin.ss_family;
  876. memcpy(&(((struct sockaddr_in*)&itf->bcast)->sin_addr),
  877. &(isc_if->broadcast.type.in),
  878. sizeof(struct in_addr));
  879. ((struct sockaddr_in*)&itf->bcast)->sin_port = port;
  880. }
  881. itf->mask.ss_family = itf->sin.ss_family;
  882. memcpy(&(((struct sockaddr_in*)&itf->mask)->sin_addr),
  883. &(isc_if->netmask.type.in),
  884. sizeof(struct in_addr));
  885. ((struct sockaddr_in*)&itf->mask)->sin_port = port;
  886. }
  887. #ifdef INCLUDE_IPV6_SUPPORT
  888. else if (isc_if->af == AF_INET6) {
  889. itf->sin.ss_family = (u_short) isc_if->af;
  890. memcpy(&(((struct sockaddr_in6 *)&itf->sin)->sin6_addr),
  891. &(isc_if->address.type.in6),
  892. sizeof(((struct sockaddr_in6 *)&itf->sin)->sin6_addr));
  893. ((struct sockaddr_in6 *)&itf->sin)->sin6_port = port;
  894. #ifdef ISC_PLATFORM_HAVESCOPEID
  895. ((struct sockaddr_in6 *)&itf->sin)->sin6_scope_id = isc_netaddr_getzone(&isc_if->address);
  896. itf->scopeid = isc_netaddr_getzone(&isc_if->address);
  897. #endif
  898. itf->mask.ss_family = itf->sin.ss_family;
  899. memcpy(&(((struct sockaddr_in6 *)&itf->mask)->sin6_addr),
  900. &(isc_if->netmask.type.in6),
  901. sizeof(struct in6_addr));
  902. ((struct sockaddr_in6 *)&itf->mask)->sin6_port = port;
  903. /* Copy the interface index */
  904. itf->ifindex = isc_if->ifindex;
  905. }
  906. #endif /* INCLUDE_IPV6_SUPPORT */
  907. /* Process the rest of the flags */
  908. if((isc_if->flags & INTERFACE_F_UP) != 0)
  909. itf->flags |= INT_UP;
  910. if((isc_if->flags & INTERFACE_F_LOOPBACK) != 0)
  911. itf->flags |= INT_LOOPBACK;
  912. if((isc_if->flags & INTERFACE_F_POINTTOPOINT) != 0)
  913. itf->flags |= INT_PPP;
  914. if((isc_if->flags & INTERFACE_F_MULTICAST) != 0)
  915. itf->flags |= INT_MULTICAST;
  916. }
  917. /*
  918. * refresh_interface
  919. *
  920. * some OSes have been observed to keep
  921. * cached routes even when more specific routes
  922. * become available.
  923. * this can be mitigated by re-binding
  924. * the socket.
  925. */
  926. static int
  927. refresh_interface(struct interface * interface)
  928. {
  929. #ifdef OS_MISSES_SPECIFIC_ROUTE_UPDATES
  930. if (interface->fd != INVALID_SOCKET)
  931. {
  932. close_and_delete_fd_from_list(interface->fd);
  933. interface->fd = open_socket(&interface->sin,
  934. interface->flags, 0, interface);
  935. /*
  936. * reset TTL indication so TTL is is set again
  937. * next time around
  938. */
  939. interface->last_ttl = 0;
  940. return interface->fd != INVALID_SOCKET;
  941. }
  942. else
  943. {
  944. return 0; /* invalid sockets are not refreshable */
  945. }
  946. #else /* !OS_MISSES_SPECIFIC_ROUTE_UPDATES */
  947. return interface->fd != INVALID_SOCKET;
  948. #endif /* !OS_MISSES_SPECIFIC_ROUTE_UPDATES */
  949. }
  950. /*
  951. * interface_update - externally callable update function
  952. */
  953. void
  954. interface_update(interface_receiver_t receiver, void *data)
  955. {
  956. if (!disable_dynamic_updates) {
  957. int new_interface_found;
  958. BLOCKIO();
  959. new_interface_found = update_interfaces(htons(NTP_PORT), receiver, data);
  960. UNBLOCKIO();
  961. if (new_interface_found) {
  962. #ifdef DEBUG
  963. msyslog(LOG_DEBUG, "new interface(s) found: waking up resolver");
  964. #endif
  965. #ifdef SYS_WINNT
  966. /* wake up the resolver thread */
  967. if (ResolverEventHandle != NULL)
  968. SetEvent(ResolverEventHandle);
  969. #else
  970. /* write any single byte to the pipe to wake up the resolver process */
  971. write( resolver_pipe_fd[1], &new_interface_found, 1 );
  972. #endif
  973. }
  974. }
  975. }
  976. /*
  977. * find out if a given interface structure contains
  978. * a wildcard address
  979. */
  980. static int
  981. is_wildcard_addr(struct sockaddr_storage *sas)
  982. {
  983. if (sas->ss_family == AF_INET &&
  984. ((struct sockaddr_in*)sas)->sin_addr.s_addr == htonl(INADDR_ANY))
  985. return 1;
  986. #ifdef INCLUDE_IPV6_SUPPORT
  987. if (sas->ss_family == AF_INET6 &&
  988. memcmp(&((struct sockaddr_in6*)sas)->sin6_addr, &in6addr_any,
  989. sizeof(in6addr_any) == 0))
  990. return 1;
  991. #endif
  992. return 0;
  993. }
  994. #ifdef OS_NEEDS_REUSEADDR_FOR_IFADDRBIND
  995. /*
  996. * enable/disable re-use of wildcard address socket
  997. */
  998. static void
  999. set_wildcard_reuse(int family, int on)
  1000. {
  1001. int onvalue = 1;
  1002. int offvalue = 0;
  1003. int *onoff;
  1004. SOCKET fd = INVALID_SOCKET;
  1005. onoff = on ? &onvalue : &offvalue;
  1006. switch (family) {
  1007. case AF_INET:
  1008. if (any_interface) {
  1009. fd = any_interface->fd;
  1010. }
  1011. break;
  1012. #ifdef INCLUDE_IPV6_SUPPORT
  1013. case AF_INET6:
  1014. if (any6_interface) {
  1015. fd = any6_interface->fd;
  1016. }
  1017. break;
  1018. #endif /* !INCLUDE_IPV6_SUPPORT */
  1019. }
  1020. if (fd != INVALID_SOCKET) {
  1021. if (setsockopt(fd, SOL_SOCKET,
  1022. SO_REUSEADDR, (char *)onoff,
  1023. sizeof(*onoff))) {
  1024. netsyslog(LOG_ERR, "set_wildcard_reuse: setsockopt(SO_REUSEADDR, %s) failed: %m", *onoff ? "on" : "off");
  1025. }
  1026. DPRINTF(4, ("set SO_REUSEADDR to %s on %s\n", *onoff ? "ON" : "OFF",
  1027. stoa((family == AF_INET) ?
  1028. &any_interface->sin : &any6_interface->sin)));
  1029. }
  1030. }
  1031. #endif /* OS_NEEDS_REUSEADDR_FOR_IFADDRBIND */
  1032. #ifdef INCLUDE_IPV6_SUPPORT
  1033. static isc_boolean_t
  1034. is_anycast(struct sockaddr *sa, char *name)
  1035. {
  1036. #if defined(SIOCGIFAFLAG_IN6) && defined(IN6_IFF_ANYCAST)
  1037. struct in6_ifreq ifr6;
  1038. int fd;
  1039. u_int32_t flags6;
  1040. if (sa->sa_family != AF_INET6)
  1041. return ISC_FALSE;
  1042. if ((fd = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
  1043. return ISC_FALSE;
  1044. memset(&ifr6, 0, sizeof(ifr6));
  1045. memcpy(&ifr6.ifr_addr, (struct sockaddr_in6 *)sa,
  1046. sizeof(struct sockaddr_in6));
  1047. strlcpy(ifr6.ifr_name, name, IF_NAMESIZE);
  1048. if (ioctl(fd, SIOCGIFAFLAG_IN6, &ifr6) < 0) {
  1049. close(fd);
  1050. return ISC_FALSE;
  1051. }
  1052. close(fd);
  1053. flags6 = ifr6.ifr_ifru.ifru_flags6;
  1054. if ((flags6 & IN6_IFF_ANYCAST) != 0)
  1055. return ISC_TRUE;
  1056. #endif /* !SIOCGIFAFLAG_IN6 || !IN6_IFF_ANYCAST */
  1057. return ISC_FALSE;
  1058. }
  1059. #endif /* !INCLUDE_IPV6_SUPPORT */
  1060. /*
  1061. * update_interface strategy
  1062. *
  1063. * toggle configuration phase
  1064. *
  1065. * Phase 1:
  1066. * forall currently existing interfaces
  1067. * if address is known:
  1068. * drop socket - rebind again
  1069. *
  1070. * if address is NOT known:
  1071. * attempt to create a new interface entry
  1072. *
  1073. * Phase 2:
  1074. * forall currently known non MCAST and WILDCARD interfaces
  1075. * if interface does not match configuration phase (not seen in phase 1):
  1076. * remove interface from known interface list
  1077. * forall peers associated with this interface
  1078. * disconnect peer from this interface
  1079. *
  1080. * Phase 3:
  1081. * attempt to re-assign interfaces to peers
  1082. *
  1083. */
  1084. static int
  1085. update_interfaces(
  1086. u_short port,
  1087. interface_receiver_t receiver,
  1088. void *data
  1089. )
  1090. {
  1091. interface_info_t ifi;
  1092. isc_mem_t *mctx = NULL;
  1093. isc_interfaceiter_t *iter = NULL;
  1094. isc_boolean_t scan_ipv4 = ISC_FALSE;
  1095. isc_boolean_t scan_ipv6 = ISC_FALSE;
  1096. isc_result_t result;
  1097. int new_interface_found = 0;
  1098. DPRINTF(3, ("update_interfaces(%d)\n", ntohs( (u_short) port)));
  1099. #ifdef INCLUDE_IPV6_SUPPORT
  1100. if (isc_net_probeipv6() == ISC_R_SUCCESS)
  1101. scan_ipv6 = ISC_TRUE;
  1102. #if defined(DEBUG)
  1103. else
  1104. if (debug)
  1105. netsyslog(LOG_ERR, "no IPv6 interfaces found");
  1106. #endif
  1107. #endif
  1108. if (isc_net_probeipv6() == ISC_R_SUCCESS)
  1109. scan_ipv6 = ISC_TRUE;
  1110. #if defined(ISC_PLATFORM_HAVEIPV6) && defined(DEBUG)
  1111. else
  1112. if (debug)
  1113. netsyslog(LOG_ERR, "no IPv6 interfaces found");
  1114. #endif
  1115. if (isc_net_probeipv4() == ISC_R_SUCCESS)
  1116. scan_ipv4 = ISC_TRUE;
  1117. #ifdef DEBUG
  1118. else
  1119. if(debug)
  1120. netsyslog(LOG_ERR, "no IPv4 interfaces found");
  1121. #endif
  1122. /*
  1123. * phase one - scan interfaces
  1124. * - create those that are not found
  1125. * - update those that are found
  1126. */
  1127. result = isc_interfaceiter_create(mctx, &iter);
  1128. if (result != ISC_R_SUCCESS)
  1129. return 0;
  1130. sys_interphase ^= 0x1; /* toggle system phase for finding untouched (to be deleted) interfaces */
  1131. for (result = isc_interfaceiter_first(iter);
  1132. result == ISC_R_SUCCESS;
  1133. result = isc_interfaceiter_next(iter))
  1134. {
  1135. isc_interface_t isc_if;
  1136. unsigned int family;
  1137. struct interface interface;
  1138. struct interface *iface;
  1139. result = isc_interfaceiter_current(iter, &isc_if);
  1140. if (result != ISC_R_SUCCESS)
  1141. break;
  1142. /* See if we have a valid family to use */
  1143. family = isc_if.address.family;
  1144. if (family != AF_INET && family != AF_INET6)
  1145. continue;
  1146. if (scan_ipv4 == ISC_FALSE && family == AF_INET)
  1147. continue;
  1148. if (scan_ipv6 == ISC_FALSE && family == AF_INET6)
  1149. continue;
  1150. /*
  1151. * create prototype
  1152. */
  1153. init_interface(&interface);
  1154. convert_isc_if(&isc_if, &interface, port);
  1155. /*
  1156. * Check to see if we are going to use the interface
  1157. * If we don't use it we mark it to drop any packet
  1158. * received but we still must create the socket and
  1159. * bind to it. This prevents other apps binding to it
  1160. * and potentially causing problems with more than one
  1161. * process fiddling with the clock
  1162. */
  1163. if (address_okay(&interface) == ISC_TRUE) {
  1164. interface.ignore_packets = ISC_FALSE;
  1165. }
  1166. else {
  1167. interface.ignore_packets = ISC_TRUE;
  1168. }
  1169. DPRINT_INTERFACE(4, (&interface, "examining ", "\n"));
  1170. if (!(interface.flags & INT_UP)) { /* interfaces must be UP to be usable */
  1171. DPRINTF(4, ("skipping interface %s (%s) - DOWN\n", interface.name, stoa(&interface.sin)));
  1172. continue;
  1173. }
  1174. /*
  1175. * skip any interfaces UP and bound to a wildcard
  1176. * address - some dhcp clients produce that in the
  1177. * wild
  1178. */
  1179. if (is_wildcard_addr(&interface.sin))
  1180. continue;
  1181. #ifdef INCLUDE_IPV6_SUPPORT
  1182. if (is_anycast((struct sockaddr *)&interface.sin, isc_if.name))
  1183. continue;
  1184. #endif /* !INCLUDE_IPV6_SUPPORT */
  1185. /*
  1186. * map to local *address* in order
  1187. * to map all duplicate interfaces to an interface structure
  1188. * with the appropriate socket (our name space is
  1189. * (ip-address) - NOT (interface name, ip-address))
  1190. */
  1191. iface = getinterface(&interface.sin, INT_WILDCARD);
  1192. if (iface && refresh_interface(iface))
  1193. {
  1194. /*
  1195. * found existing and up to date interface - mark present
  1196. */
  1197. iface->phase = sys_interphase;
  1198. DPRINT_INTERFACE(4, (iface, "updating ", " present\n"));
  1199. ifi.action = IFS_EXISTS;
  1200. ifi.interface = iface;
  1201. if (receiver)
  1202. receiver(data, &ifi);
  1203. }
  1204. else
  1205. {
  1206. /*
  1207. * this is new or refreshing failed - add to our interface list
  1208. * if refreshing failed we will delete the interface structure in
  1209. * phase 2 as the interface was not marked current. We can bind to
  1210. * the address as the refresh code already closed the offending socket
  1211. */
  1212. iface = create_interface(port, &interface);
  1213. if (iface)
  1214. {
  1215. ifi.action = IFS_CREATED;
  1216. ifi.interface = iface;
  1217. if (receiver)
  1218. receiver(data, &ifi);
  1219. new_interface_found = 1;
  1220. DPRINT_INTERFACE(3, (iface, "updating ", " new - created\n"));
  1221. }
  1222. else
  1223. {
  1224. DPRINT_INTERFACE(3, (&interface, "updating ", " new - creation FAILED"));
  1225. msyslog(LOG_INFO, "failed to initialize interface for address %s", stoa(&interface.sin));
  1226. continue;
  1227. }
  1228. }
  1229. }
  1230. isc_interfaceiter_destroy(&iter);
  1231. /*
  1232. * phase 2 - delete gone interfaces - reassigning peers to other interfaces
  1233. */
  1234. {
  1235. struct interface *interf = ISC_LIST_HEAD(inter_list);
  1236. while (interf != NULL)
  1237. {
  1238. struct interface *next = ISC_LIST_NEXT(interf, link);
  1239. if (!(interf->flags & (INT_WILDCARD|INT_MCASTIF))) {
  1240. /*
  1241. * if phase does not match sys_phase this interface was not
  1242. * enumerated during interface scan - so it is gone and
  1243. * will be deleted here unless it is solely an MCAST/WILDCARD interface
  1244. */
  1245. if (interf->phase != sys_interphase) {
  1246. struct peer *peer;
  1247. DPRINT_INTERFACE(3, (interf, "updating ", "GONE - deleting\n"));
  1248. remove_interface(interf);
  1249. ifi.action = IFS_DELETED;
  1250. ifi.interface = interf;
  1251. if (receiver)
  1252. receiver(data, &ifi);
  1253. peer = ISC_LIST_HEAD(interf->peers);
  1254. /*
  1255. * disconnect peer from deleted interface
  1256. */
  1257. while (peer != NULL) {
  1258. struct peer *npeer = ISC_LIST_NEXT(peer, ilink);
  1259. /*
  1260. * this one just lost it's interface
  1261. */
  1262. set_peerdstadr(peer, NULL);
  1263. peer = npeer;
  1264. }
  1265. /*
  1266. * update globals in case we lose
  1267. * a loopback interface
  1268. */
  1269. if (interf == loopback_interface)
  1270. loopback_interface = NULL;
  1271. delete_interface(interf);
  1272. }
  1273. }
  1274. interf = next;
  1275. }
  1276. }
  1277. /*
  1278. * phase 3 - re-configure as the world has changed if necessary
  1279. */
  1280. refresh_all_peerinterfaces();
  1281. return new_interface_found;
  1282. }
  1283. /*
  1284. * create_sockets - create a socket for each interface plus a default
  1285. * socket for when we don't know where to send
  1286. */
  1287. static int
  1288. create_sockets(
  1289. u_short port
  1290. )
  1291. {
  1292. #ifndef HAVE_IO_COMPLETION_PORT
  1293. /*
  1294. * I/O Completion Ports don't care about the select and FD_SET
  1295. */
  1296. maxactivefd = 0;
  1297. FD_ZERO(&activefds);
  1298. #endif
  1299. DPRINTF(2, ("create_sockets(%d)\n", ntohs( (u_short) port)));
  1300. create_wildcards(port);
  1301. update_interfaces(port, NULL, NULL);
  1302. /*
  1303. * Now that we have opened all the sockets, turn off the reuse
  1304. * flag for security.
  1305. */
  1306. set_reuseaddr(0);
  1307. DPRINTF(2, ("create_sockets: Total interfaces = %d\n", ninterfaces));
  1308. return ninterfaces;
  1309. }
  1310. /*
  1311. * create_interface - create a new interface for a given prototype
  1312. * binding the socket.
  1313. */
  1314. static struct interface *
  1315. create_interface(
  1316. u_short port,
  1317. struct interface *iface
  1318. )
  1319. {
  1320. struct sockaddr_storage resmask;
  1321. struct interface *interface;
  1322. DPRINTF(2, ("create_interface(%s#%d)\n", stoa(&iface->sin), ntohs( (u_short) port)));
  1323. /* build an interface */
  1324. interface = new_interface(iface);
  1325. /*
  1326. * create socket
  1327. */
  1328. interface->fd = open_socket(&interface->sin,
  1329. interface->flags, 0, interface);
  1330. if (interface->fd != INVALID_SOCKET)
  1331. list_if_listening(interface, port);
  1332. if ((interface->flags & INT_BROADCAST) &&
  1333. interface->bfd != INVALID_SOCKET)
  1334. msyslog(LOG_INFO, "Listening on broadcast address %s#%d",
  1335. stoa((&interface->bcast)),
  1336. ntohs( (u_short) port));
  1337. if (interface->fd == INVALID_SOCKET &&
  1338. interface->bfd == INVALID_SOCKET) {
  1339. msyslog(LOG_ERR, "unable to create socket on %s (%d) for %s#%d",
  1340. interface->name,
  1341. interface->ifnum,
  1342. stoa((&interface->sin)),
  1343. ntohs( (u_short) port));
  1344. delete_interface(interface);
  1345. return NULL;
  1346. }
  1347. /*
  1348. * Blacklist bound interface address
  1349. */
  1350. SET_HOSTMASK(&resmask, interface->sin.ss_family);
  1351. hack_restrict(RESTRICT_FLAGS, &interface->sin, &resmask,
  1352. RESM_NTPONLY|RESM_INTERFACE, RES_IGNORE);
  1353. /*
  1354. * set globals with the first found
  1355. * loopback interface of the appropriate class
  1356. */
  1357. if ((loopback_interface == NULL) &&
  1358. (interface->family == AF_INET) &&
  1359. ((interface->flags & INT_LOOPBACK) != 0))
  1360. {
  1361. loopback_interface = interface;
  1362. }
  1363. /*
  1364. * put into our interface list
  1365. */
  1366. add_addr_to_list(&interface->sin, interface);
  1367. add_interface(interface);
  1368. DPRINT_INTERFACE(2, (interface, "created ", "\n"));
  1369. return interface;
  1370. }
  1371. #ifdef SO_EXCLUSIVEADDRUSE
  1372. static void
  1373. set_excladdruse(int fd)
  1374. {
  1375. int one = 1;
  1376. int failed;
  1377. failed = setsockopt(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
  1378. (char *)&one, sizeof(one));
  1379. if (failed)
  1380. netsyslog(LOG_ERR,
  1381. "setsockopt(%d, SO_EXCLUSIVEADDRUSE, on): %m", fd);
  1382. }
  1383. #endif /* SO_EXCLUSIVEADDRUSE */
  1384. /*
  1385. * set_reuseaddr() - set/clear REUSEADDR on all sockets
  1386. * NB possible hole - should we be doing this on broadcast
  1387. * fd's also?
  1388. */
  1389. static void
  1390. set_reuseaddr(int flag) {
  1391. struct interface *interf;
  1392. #ifndef SO_EXCLUSIVEADDRUSE
  1393. for (interf = ISC_LIST_HEAD(inter_list);
  1394. interf != NULL;
  1395. interf = ISC_LIST_NEXT(interf, link)) {
  1396. if (interf->flags & INT_WILDCARD)
  1397. continue;
  1398. /*
  1399. * if interf->fd is INVALID_SOCKET, we might have a adapter
  1400. * configured but not present
  1401. */
  1402. DPRINTF(4, ("setting SO_REUSEADDR on %.16s@%s to %s\n", interf->name, stoa(&interf->sin), flag ? "on" : "off"));
  1403. if (interf->fd != INVALID_SOCKET) {
  1404. if (setsockopt(interf->fd, SOL_SOCKET,
  1405. SO_REUSEADDR, (char *)&flag,
  1406. sizeof(flag))) {
  1407. netsyslog(LOG_ERR, "set_reuseaddr: setsockopt(SO_REUSEADDR, %s) failed: %m", flag ? "on" : "off");
  1408. }
  1409. }
  1410. }
  1411. #endif /* ! SO_EXCLUSIVEADDRUSE */
  1412. }
  1413. /*
  1414. * This is just a wrapper around an internal function so we can
  1415. * make other changes as necessary later on
  1416. */
  1417. void
  1418. enable_broadcast(struct interface *iface, struct sockaddr_storage *baddr)
  1419. {
  1420. #ifdef SO_BROADCAST
  1421. socket_broadcast_enable(iface, iface->fd, baddr);
  1422. #endif
  1423. }
  1424. #ifdef OPEN_BCAST_SOCKET
  1425. /*
  1426. * Enable a broadcast address to a given socket
  1427. * The socket is in the inter_list all we need to do is enable
  1428. * broadcasting. It is not this function's job to select the socket
  1429. */
  1430. static isc_boolean_t
  1431. socket_broadcast_enable(struct interface *iface, SOCKET fd, struct sockaddr_storage *maddr)
  1432. {
  1433. #ifdef SO_BROADCAST
  1434. int on = 1;
  1435. if (maddr->ss_family == AF_INET)
  1436. {
  1437. /* if this interface can support broadcast, set SO_BROADCAST */
  1438. if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST,
  1439. (char *)&on, sizeof(on)))
  1440. {
  1441. netsyslog(LOG_ERR, "setsockopt(SO_BROADCAST) enable failure on address %s: %m",
  1442. stoa(maddr));
  1443. }
  1444. #ifdef DEBUG
  1445. else if (debug > 1) {
  1446. printf("Broadcast enabled on socket %d for address %s\n",
  1447. fd, stoa(maddr));
  1448. }
  1449. #endif
  1450. }
  1451. iface->flags |= INT_BCASTOPEN;
  1452. return ISC_TRUE;
  1453. #else
  1454. return ISC_FALSE;
  1455. #endif /* SO_BROADCAST */
  1456. }
  1457. /*
  1458. * Remove a broadcast address from a given socket
  1459. * The socket is in the inter_list all we need to do is disable
  1460. * broadcasting. It is not this function's job to select the socket
  1461. */
  1462. static isc_boolean_t
  1463. socket_broadcast_disable(struct interface *iface, struct sockaddr_storage *maddr)
  1464. {
  1465. #ifdef SO_BROADCAST
  1466. int off = 0; /* This seems to be OK as an int */
  1467. if (maddr->ss_family == AF_INET)
  1468. {
  1469. if (setsockopt(iface->fd, SOL_SOCKET, SO_BROADCAST,
  1470. (char *)&off, sizeof(off)))
  1471. {
  1472. netsyslog(LOG_ERR, "setsockopt(SO_BROADCAST) disable failure on address %s: %m",
  1473. stoa(maddr));
  1474. }
  1475. }
  1476. iface->flags &= ~INT_BCASTOPEN;
  1477. return ISC_TRUE;
  1478. #else
  1479. return ISC_FALSE;
  1480. #endif /* SO_BROADCAST */
  1481. }
  1482. #endif /* OPEN_BCAST_SOCKET */
  1483. /*
  1484. * Check to see if the address is a multicast address
  1485. */
  1486. static isc_boolean_t
  1487. addr_ismulticast(struct sockaddr_storage *maddr)
  1488. {
  1489. switch (maddr->ss_family)
  1490. {
  1491. case AF_INET :
  1492. if (!IN_CLASSD(ntohl(((struct sockaddr_in*)maddr)->sin_addr.s_addr))) {
  1493. DPRINTF(4, ("multicast address %s not class D\n", stoa(maddr)));
  1494. return (ISC_FALSE);
  1495. }
  1496. else
  1497. {
  1498. return (ISC_TRUE);
  1499. }
  1500. case AF_INET6 :
  1501. #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
  1502. if (!IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6*)maddr)->sin6_addr)) {
  1503. DPRINTF(4, ("address %s not IPv6 multicast address\n", stoa(maddr)));
  1504. return (ISC_FALSE);
  1505. }
  1506. else
  1507. {
  1508. return (ISC_TRUE);
  1509. }
  1510. /*
  1511. * If we don't have IPV6 support any IPV6 address is not multicast
  1512. */
  1513. #else
  1514. return (ISC_FALSE);
  1515. #endif
  1516. /*
  1517. * Never valid
  1518. */
  1519. default:
  1520. return (ISC_FALSE);
  1521. }
  1522. }
  1523. /*
  1524. * Multicast servers need to set the appropriate Multicast interface
  1525. * socket option in order for it to know which interface to use for
  1526. * send the multicast packet.
  1527. */
  1528. void
  1529. enable_multicast_if(struct interface *iface, struct sockaddr_storage *maddr)
  1530. {
  1531. #ifdef MCAST
  1532. #ifdef IP_MULTICAST_LOOP
  1533. /*u_char*/ TYPEOF_IP_MULTICAST_LOOP off = 0;
  1534. #endif
  1535. #ifdef IPV6_MULTICAST_LOOP
  1536. u_int off6 = 0; /* RFC 3493, 5.2. defines type unsigned int */
  1537. #endif
  1538. switch (maddr->ss_family)
  1539. {
  1540. case AF_INET:
  1541. if (setsockopt(iface->fd, IPPROTO_IP, IP_MULTICAST_IF,
  1542. (char *)&(((struct sockaddr_in*)&iface->sin)->sin_addr.s_addr),
  1543. sizeof(struct in_addr)) == -1) {
  1544. netsyslog(LOG_ERR,
  1545. "setsockopt IP_MULTICAST_IF failure: %m on socket %d, addr %s for multicast address %s",
  1546. iface->fd, stoa(&iface->sin), stoa(maddr));
  1547. return;
  1548. }
  1549. #ifdef IP_MULTICAST_LOOP
  1550. /*
  1551. * Don't send back to itself, but allow it to fail to set it
  1552. */
  1553. if (setsockopt(iface->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
  1554. SETSOCKOPT_ARG_CAST &off, sizeof(off)) == -1) {
  1555. netsyslog(LOG_ERR,
  1556. "setsockopt IP_MULTICAST_LOOP failure: %m on socket %d, addr %s for multicast address %s",
  1557. iface->fd, stoa(&iface->sin), stoa(maddr));
  1558. }
  1559. #endif
  1560. DPRINTF(4, ("Added IPv4 multicast interface on socket %d, addr %s for multicast address %s\n",
  1561. iface->fd, stoa(&iface->sin),
  1562. stoa(maddr)));
  1563. break;
  1564. case AF_INET6:
  1565. #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
  1566. if (setsockopt(iface->fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
  1567. (char *) &iface->scopeid, sizeof(iface->scopeid)) == -1) {
  1568. netsyslog(LOG_ERR,
  1569. "setsockopt IPV6_MULTICAST_IF failure: %m on socket %d, addr %s, scope %d for multicast address %s",
  1570. iface->fd, stoa(&iface->sin), iface->scopeid,
  1571. stoa(maddr));
  1572. return;
  1573. }
  1574. #ifdef IPV6_MULTICAST_LOOP
  1575. /*
  1576. * Don't send back to itself, but allow it to fail to set it
  1577. */
  1578. if (setsockopt(iface->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
  1579. (char *) &off6, sizeof(off6)) == -1) {
  1580. netsyslog(LOG_ERR,
  1581. "setsockopt IPV6_MULTICAST_LOOP failure: %m on socket %d, addr %s for multicast address %s",
  1582. iface->fd, stoa(&iface->sin), stoa(maddr));
  1583. }
  1584. #endif
  1585. DPRINTF(4, ("Added IPv6 multicast interface on socket %d, addr %s, scope %d for multicast address %s\n",
  1586. iface->fd, stoa(&iface->sin), iface->scopeid,
  1587. stoa(maddr)));
  1588. break;
  1589. #else
  1590. return;
  1591. #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */
  1592. }
  1593. return;
  1594. #endif
  1595. }
  1596. /*
  1597. * Add a multicast address to a given socket
  1598. * The socket is in the inter_list all we need to do is enable
  1599. * multicasting. It is not this function's job to select the socket
  1600. */
  1601. static isc_boolean_t
  1602. socket_multicast_enable(struct interface *iface, int lscope, struct sockaddr_storage *maddr)
  1603. {
  1604. #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT
  1605. struct ipv6_mreq mreq6;
  1606. struct in6_addr iaddr6;
  1607. #endi