1 /* $NetBSD: ntp_io.c,v 1.5 2011/01/09 14:49:40 kardel Exp $ */ 2 3 /* 4 * ntp_io.c - input/output routines for ntpd. The socket-opening code 5 * was shamelessly stolen from ntpd. 6 */ 7 8 #ifdef HAVE_CONFIG_H 9 # include <config.h> 10 #endif 11 12 #include <stdio.h> 13 #include <signal.h> 14 #ifdef HAVE_SYS_PARAM_H 15 # include <sys/param.h> 16 #endif 17 #ifdef HAVE_SYS_IOCTL_H 18 # include <sys/ioctl.h> 19 #endif 20 #ifdef HAVE_SYS_SOCKIO_H /* UXPV: SIOC* #defines (Frank Vance <fvance@waii.com>) */ 21 # include <sys/sockio.h> 22 #endif 23 #ifdef HAVE_SYS_UIO_H 24 # include <sys/uio.h> 25 #endif 26 27 #include "ntp_machine.h" 28 #include "ntpd.h" 29 #include "ntp_io.h" 30 #include "iosignal.h" 31 #include "ntp_lists.h" 32 #include "ntp_refclock.h" 33 #include "ntp_stdlib.h" 34 #include "ntp_request.h" 35 #include "ntp.h" 36 #include "ntp_unixtime.h" 37 #include "ntp_assert.h" 38 #include "ntpd-opts.h" 39 40 /* Don't include ISC's version of IPv6 variables and structures */ 41 #define ISC_IPV6_H 1 42 #include <isc/mem.h> 43 #include <isc/interfaceiter.h> 44 #include <isc/netaddr.h> 45 #include <isc/result.h> 46 #include <isc/sockaddr.h> 47 48 #ifdef SIM 49 #include "ntpsim.h" 50 #endif 51 52 #ifdef HAS_ROUTING_SOCKET 53 # include <net/route.h> 54 # ifdef HAVE_RTNETLINK 55 # include <linux/rtnetlink.h> 56 # endif 57 #endif 58 59 60 /* 61 * setsockopt does not always have the same arg declaration 62 * across all platforms. If it's not defined we make it empty 63 */ 64 65 #ifndef SETSOCKOPT_ARG_CAST 66 #define SETSOCKOPT_ARG_CAST 67 #endif 68 69 extern int listen_to_virtual_ips; 70 71 /* 72 * NIC rule entry 73 */ 74 typedef struct nic_rule_tag nic_rule; 75 76 struct nic_rule_tag { 77 nic_rule * next; 78 nic_rule_action action; 79 nic_rule_match match_type; 80 char * if_name; 81 isc_netaddr_t netaddr; 82 int prefixlen; 83 }; 84 85 /* 86 * NIC rule listhead. Entries are added at the head so that the first 87 * match in the list is the last matching rule specified. 88 */ 89 nic_rule *nic_rule_list; 90 91 92 #if defined(SO_TIMESTAMP) && defined(SCM_TIMESTAMP) 93 #if defined(CMSG_FIRSTHDR) 94 #define HAVE_TIMESTAMP 95 #define USE_TIMESTAMP_CMSG 96 #ifndef TIMESTAMP_CTLMSGBUF_SIZE 97 #define TIMESTAMP_CTLMSGBUF_SIZE 1536 /* moderate default */ 98 #endif 99 #else 100 /* fill in for old/other timestamp interfaces */ 101 #endif 102 #endif 103 104 #if defined(SYS_WINNT) 105 #include <transmitbuff.h> 106 #include <isc/win32os.h> 107 /* 108 * Windows C runtime ioctl() can't deal properly with sockets, 109 * map to ioctlsocket for this source file. 110 */ 111 #define ioctl(fd, opt, val) ioctlsocket((fd), (opt), (u_long *)(val)) 112 #endif /* SYS_WINNT */ 113 114 /* 115 * We do asynchronous input using the SIGIO facility. A number of 116 * recvbuf buffers are preallocated for input. In the signal 117 * handler we poll to see which sockets are ready and read the 118 * packets from them into the recvbuf's along with a time stamp and 119 * an indication of the source host and the interface it was received 120 * through. This allows us to get as accurate receive time stamps 121 * as possible independent of other processing going on. 122 * 123 * We watch the number of recvbufs available to the signal handler 124 * and allocate more when this number drops below the low water 125 * mark. If the signal handler should run out of buffers in the 126 * interim it will drop incoming frames, the idea being that it is 127 * better to drop a packet than to be inaccurate. 128 */ 129 130 131 /* 132 * Other statistics of possible interest 133 */ 134 volatile u_long packets_dropped; /* total number of packets dropped on reception */ 135 volatile u_long packets_ignored; /* packets received on wild card interface */ 136 volatile u_long packets_received; /* total number of packets received */ 137 u_long packets_sent; /* total number of packets sent */ 138 u_long packets_notsent; /* total number of packets which couldn't be sent */ 139 140 volatile u_long handler_calls; /* number of calls to interrupt handler */ 141 volatile u_long handler_pkts; /* number of pkts received by handler */ 142 u_long io_timereset; /* time counters were reset */ 143 144 /* 145 * Interface stuff 146 */ 147 struct interface *any_interface; /* default ipv4 interface */ 148 struct interface *any6_interface; /* default ipv6 interface */ 149 struct interface *loopback_interface; /* loopback ipv4 interface */ 150 151 isc_boolean_t broadcast_client_enabled; /* is broadcast client enabled */ 152 int ninterfaces; /* Total number of interfaces */ 153 154 int disable_dynamic_updates; /* scan interfaces once only */ 155 156 #ifdef REFCLOCK 157 /* 158 * Refclock stuff. We keep a chain of structures with data concerning 159 * the guys we are doing I/O for. 160 */ 161 static struct refclockio *refio; 162 #endif /* REFCLOCK */ 163 164 #if defined(HAVE_IPTOS_SUPPORT) 165 /* set IP_TOS to minimize packet delay */ 166 # if defined(IPTOS_PREC_INTERNETCONTROL) 167 unsigned int qos = IPTOS_PREC_INTERNETCONTROL; 168 # else 169 unsigned int qos = IPTOS_LOWDELAY; 170 # endif 171 #endif 172 173 /* 174 * File descriptor masks etc. for call to select 175 * Not needed for I/O Completion Ports 176 */ 177 fd_set activefds; 178 int maxactivefd; 179 /* 180 * bit alternating value to detect verified interfaces during an update cycle 181 */ 182 static u_short sys_interphase = 0; 183 184 static struct interface *new_interface (struct interface *); 185 static void add_interface (struct interface *); 186 static int update_interfaces(u_short, interface_receiver_t, void *); 187 static void remove_interface(struct interface *); 188 static struct interface *create_interface(u_short, struct interface *); 189 190 static int move_fd (SOCKET); 191 static int is_wildcard_addr (sockaddr_u *); 192 static int is_wildcard_netaddr (const isc_netaddr_t *); 193 194 /* 195 * Multicast functions 196 */ 197 static isc_boolean_t addr_ismulticast (sockaddr_u *); 198 /* 199 * Not all platforms support multicast 200 */ 201 #ifdef MCAST 202 static isc_boolean_t socket_multicast_enable (struct interface *, int, sockaddr_u *); 203 static isc_boolean_t socket_multicast_disable(struct interface *, sockaddr_u *); 204 #endif 205 206 #ifdef DEBUG 207 static void interface_dump (struct interface *); 208 static void sockaddr_dump (sockaddr_u *psau); 209 static void print_interface (struct interface *, const char *, const char *); 210 #define DPRINT_INTERFACE(level, args) do { if (debug >= (level)) { print_interface args; } } while (0) 211 #else 212 #define DPRINT_INTERFACE(level, args) do {} while (0) 213 #endif 214 215 typedef struct vsock vsock_t; 216 enum desc_type { FD_TYPE_SOCKET, FD_TYPE_FILE }; 217 218 struct vsock { 219 vsock_t * link; 220 SOCKET fd; 221 enum desc_type type; 222 }; 223 224 vsock_t *fd_list; 225 226 #if !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET) 227 /* 228 * async notification processing (e. g. routing sockets) 229 */ 230 /* 231 * support for receiving data on fd that is not a refclock or a socket 232 * like e. g. routing sockets 233 */ 234 struct asyncio_reader { 235 struct asyncio_reader *link; /* the list this is being kept in */ 236 SOCKET fd; /* fd to be read */ 237 void *data; /* possibly local data */ 238 void (*receiver)(struct asyncio_reader *); /* input handler */ 239 }; 240 241 struct asyncio_reader *asyncio_reader_list; 242 243 static void delete_asyncio_reader (struct asyncio_reader *); 244 static struct asyncio_reader *new_asyncio_reader (void); 245 static void add_asyncio_reader (struct asyncio_reader *, enum desc_type); 246 static void remove_asyncio_reader (struct asyncio_reader *); 247 248 #endif /* !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET) */ 249 250 static void init_async_notifications (void); 251 252 static int create_sockets (u_short); 253 static SOCKET open_socket (sockaddr_u *, int, int, struct interface *); 254 static char * fdbits (int, fd_set *); 255 static void set_reuseaddr (int); 256 static isc_boolean_t socket_broadcast_enable (struct interface *, SOCKET, sockaddr_u *); 257 static isc_boolean_t socket_broadcast_disable (struct interface *, sockaddr_u *); 258 259 typedef struct remaddr remaddr_t; 260 261 struct remaddr { 262 remaddr_t * link; 263 sockaddr_u addr; 264 struct interface * interface; 265 }; 266 267 remaddr_t * remoteaddr_list; 268 269 struct interface * inter_list; 270 271 static struct interface *wildipv4 = NULL; 272 static struct interface *wildipv6 = NULL; 273 274 static void add_fd_to_list (SOCKET, 275 enum desc_type); 276 static struct interface *find_addr_in_list (sockaddr_u *); 277 static struct interface *find_samenet_addr_in_list(sockaddr_u *); 278 static struct interface *find_flagged_addr_in_list(sockaddr_u *, int); 279 static void delete_addr_from_list (sockaddr_u *); 280 static void delete_interface_from_list(struct interface *); 281 static void close_and_delete_fd_from_list(SOCKET); 282 static void add_addr_to_list (sockaddr_u *, 283 struct interface *); 284 static void create_wildcards (u_short); 285 #ifdef DEBUG 286 static const char * action_text (nic_rule_action); 287 #endif 288 static nic_rule_action interface_action(char *, isc_netaddr_t *, 289 isc_uint32_t); 290 static void convert_isc_if (isc_interface_t *, 291 struct interface *, u_short); 292 static struct interface *getinterface (sockaddr_u *, int); 293 static struct interface *getsamenetinterface (sockaddr_u *, int); 294 static struct interface *findlocalinterface (sockaddr_u *, int, int); 295 static struct interface *findlocalcastinterface (sockaddr_u *); 296 297 /* 298 * Routines to read the ntp packets 299 */ 300 #if !defined(HAVE_IO_COMPLETION_PORT) 301 static inline int read_network_packet (SOCKET, struct interface *, l_fp); 302 static inline int read_refclock_packet (SOCKET, struct refclockio *, l_fp); 303 #endif 304 305 306 #ifdef SYS_WINNT 307 /* 308 * Windows 2000 systems incorrectly cause UDP sockets using WASRecvFrom 309 * to not work correctly, returning a WSACONNRESET error when a WSASendTo 310 * fails with an "ICMP port unreachable" response and preventing the 311 * socket from using the WSARecvFrom in subsequent operations. 312 * The function below fixes this, but requires that Windows 2000 313 * Service Pack 2 or later be installed on the system. NT 4.0 314 * systems are not affected by this and work correctly. 315 * See Microsoft Knowledge Base Article Q263823 for details of this. 316 */ 317 void 318 connection_reset_fix( 319 SOCKET fd, 320 sockaddr_u * addr 321 ) 322 { 323 DWORD dw; 324 BOOL bNewBehavior = FALSE; 325 DWORD status; 326 327 /* 328 * disable bad behavior using IOCTL: SIO_UDP_CONNRESET 329 * NT 4.0 has no problem 330 */ 331 if (isc_win32os_majorversion() >= 5) { 332 status = WSAIoctl(fd, SIO_UDP_CONNRESET, &bNewBehavior, 333 sizeof(bNewBehavior), NULL, 0, 334 &dw, NULL, NULL); 335 if (SOCKET_ERROR == status) 336 msyslog(LOG_ERR, 337 "connection_reset_fix() failed for address %s: %m", 338 stoa(addr)); 339 } 340 } 341 #endif 342 343 /* 344 * on Unix systems the stdio library typically 345 * makes use of file descriptors in the lower 346 * integer range. stdio usually will make use 347 * of the file descriptors in the range of 348 * [0..FOPEN_MAX) 349 * in order to keep this range clean, for socket 350 * file descriptors we attempt to move them above 351 * FOPEN_MAX. This is not as easy as it sounds as 352 * FOPEN_MAX changes from implementation to implementation 353 * and may exceed to current file decriptor limits. 354 * We are using following strategy: 355 * - keep a current socket fd boundary initialized with 356 * max(0, min(getdtablesize() - FD_CHUNK, FOPEN_MAX)) 357 * - attempt to move the descriptor to the boundary or 358 * above. 359 * - if that fails and boundary > 0 set boundary 360 * to min(0, socket_fd_boundary - FD_CHUNK) 361 * -> retry 362 * if failure and boundary == 0 return old fd 363 * - on success close old fd return new fd 364 * 365 * effects: 366 * - fds will be moved above the socket fd boundary 367 * if at all possible. 368 * - the socket boundary will be reduced until 369 * allocation is possible or 0 is reached - at this 370 * point the algrithm will be disabled 371 */ 372 static int 373 move_fd( 374 SOCKET fd 375 ) 376 { 377 #if !defined(SYS_WINNT) && defined(F_DUPFD) 378 #ifndef FD_CHUNK 379 #define FD_CHUNK 10 380 #endif 381 /* 382 * number of fds we would like to have for 383 * stdio FILE* available. 384 * we can pick a "low" number as our use of 385 * FILE* is limited to log files and temporarily 386 * to data and config files. Except for log files 387 * we don't keep the other FILE* open beyond the 388 * scope of the function that opened it. 389 */ 390 #ifndef FD_PREFERRED_SOCKBOUNDARY 391 #define FD_PREFERRED_SOCKBOUNDARY 48 392 #endif 393 394 #ifndef HAVE_GETDTABLESIZE 395 /* 396 * if we have no idea about the max fd value set up things 397 * so we will start at FOPEN_MAX 398 */ 399 #define getdtablesize() (FOPEN_MAX+FD_CHUNK) 400 #endif 401 402 #ifndef FOPEN_MAX 403 #define FOPEN_MAX 20 /* assume that for the lack of anything better */ 404 #endif 405 static SOCKET socket_boundary = -1; 406 SOCKET newfd; 407 408 NTP_REQUIRE((int)fd >= 0); 409 410 /* 411 * check whether boundary has be set up 412 * already 413 */ 414 if (socket_boundary == -1) { 415 socket_boundary = max(0, min(getdtablesize() - FD_CHUNK, 416 min(FOPEN_MAX, FD_PREFERRED_SOCKBOUNDARY))); 417 #ifdef DEBUG 418 msyslog(LOG_DEBUG, 419 "ntp_io: estimated max descriptors: %d, initial socket boundary: %d", 420 getdtablesize(), socket_boundary); 421 #endif 422 } 423 424 /* 425 * Leave a space for stdio to work in. potentially moving the 426 * socket_boundary lower until allocation succeeds. 427 */ 428 do { 429 if (fd >= 0 && fd < socket_boundary) { 430 /* inside reserved range: attempt to move fd */ 431 newfd = fcntl(fd, F_DUPFD, socket_boundary); 432 433 if (newfd != -1) { 434 /* success: drop the old one - return the new one */ 435 close(fd); 436 return newfd; 437 } 438 } else { 439 /* outside reserved range: no work - return the original one */ 440 return fd; 441 } 442 socket_boundary = max(0, socket_boundary - FD_CHUNK); 443 #ifdef DEBUG 444 msyslog(LOG_DEBUG, 445 "ntp_io: selecting new socket boundary: %d", 446 socket_boundary); 447 #endif 448 } while (socket_boundary > 0); 449 #else 450 NTP_REQUIRE((int)fd >= 0); 451 #endif /* !defined(SYS_WINNT) && defined(F_DUPFD) */ 452 return fd; 453 } 454 455 #ifdef DEBUG_TIMING 456 /* 457 * collect timing information for various processing 458 * paths. currently we only pass then on to the file 459 * for later processing. this could also do histogram 460 * based analysis in other to reduce the load (and skew) 461 * dur to the file output 462 */ 463 void 464 collect_timing(struct recvbuf *rb, const char *tag, int count, l_fp *dts) 465 { 466 char buf[256]; 467 468 snprintf(buf, sizeof(buf), "%s %d %s %s", 469 (rb != NULL) 470 ? ((rb->dstadr != NULL) 471 ? stoa(&rb->recv_srcadr) 472 : "-REFCLOCK-") 473 : "-", 474 count, lfptoa(dts, 9), tag); 475 record_timing_stats(buf); 476 } 477 #endif 478 479 /* 480 * About dynamic interfaces, sockets, reception and more... 481 * 482 * the code solves following tasks: 483 * 484 * - keep a current list of active interfaces in order 485 * to bind to to the interface address on NTP_PORT so that 486 * all wild and specific bindings for NTP_PORT are taken by ntpd 487 * to avoid other daemons messing with the time or sockets. 488 * - all interfaces keep a list of peers that are referencing 489 * the interface in order to quickly re-assign the peers to 490 * new interface in case an interface is deleted (=> gone from system or 491 * down) 492 * - have a preconfigured socket ready with the right local address 493 * for transmission and reception 494 * - have an address list for all destination addresses used within ntpd 495 * to find the "right" preconfigured socket. 496 * - facilitate updating the internal interface list with respect to 497 * the current kernel state 498 * 499 * special issues: 500 * 501 * - mapping of multicast addresses to the interface affected is not always 502 * one to one - especially on hosts with multiple interfaces 503 * the code here currently allocates a separate interface entry for those 504 * multicast addresses 505 * iff it is able to bind to a *new* socket with the multicast address (flags |= MCASTIF) 506 * in case of failure the multicast address is bound to an existing interface. 507 * - on some systems it is perfectly legal to assign the same address to 508 * multiple interfaces. Therefore this code does not keep a list of interfaces 509 * but a list of interfaces that represent a unique address as determined by the kernel 510 * by the procedure in findlocalinterface. Thus it is perfectly legal to see only 511 * one representative of a group of real interfaces if they share the same address. 512 * 513 * Frank Kardel 20050910 514 */ 515 516 /* 517 * init_io - initialize I/O data structures and call socket creation routine 518 */ 519 void 520 init_io(void) 521 { 522 /* 523 * Init buffer free list and stat counters 524 */ 525 init_recvbuff(RECV_INIT); 526 527 #ifdef SYS_WINNT 528 init_io_completion_port(); 529 #endif /* SYS_WINNT */ 530 531 #if defined(HAVE_SIGNALED_IO) 532 (void) set_signal(); 533 #endif 534 } 535 536 537 /* 538 * io_open_sockets - call socket creation routine 539 */ 540 void 541 io_open_sockets(void) 542 { 543 static int already_opened; 544 545 if (already_opened || HAVE_OPT( SAVECONFIGQUIT )) 546 return; 547 548 already_opened = 1; 549 550 /* 551 * Create the sockets 552 */ 553 BLOCKIO(); 554 create_sockets(NTP_PORT); 555 UNBLOCKIO(); 556 557 init_async_notifications(); 558 559 DPRINTF(3, ("io_open_sockets: maxactivefd %d\n", maxactivefd)); 560 } 561 562 563 #ifdef DEBUG 564 /* 565 * function to dump the contents of the interface structure 566 * for debugging use only. 567 */ 568 void 569 interface_dump(struct interface *itf) 570 { 571 printf("Dumping interface: %p\n", itf); 572 printf("fd = %d\n", itf->fd); 573 printf("bfd = %d\n", itf->bfd); 574 printf("sin = %s,\n", stoa(&itf->sin)); 575 sockaddr_dump(&itf->sin); 576 printf("bcast = %s,\n", stoa(&itf->bcast)); 577 sockaddr_dump(&itf->bcast); 578 printf("mask = %s,\n", stoa(&itf->mask)); 579 sockaddr_dump(&itf->mask); 580 printf("name = %s\n", itf->name); 581 printf("flags = 0x%08x\n", itf->flags); 582 printf("last_ttl = %d\n", itf->last_ttl); 583 printf("addr_refid = %08x\n", itf->addr_refid); 584 printf("num_mcast = %d\n", itf->num_mcast); 585 printf("received = %ld\n", itf->received); 586 printf("sent = %ld\n", itf->sent); 587 printf("notsent = %ld\n", itf->notsent); 588 printf("scopeid = %u\n", itf->scopeid); 589 printf("peercnt = %u\n", itf->peercnt); 590 printf("phase = %u\n", itf->phase); 591 } 592 593 /* 594 * sockaddr_dump - hex dump the start of a sockaddr_u 595 */ 596 static void 597 sockaddr_dump(sockaddr_u *psau) 598 { 599 /* Limit the size of the sockaddr_storage hex dump */ 600 const int maxsize = min(32, sizeof(psau->sas)); 601 u_char * cp; 602 int i; 603 604 cp = (u_char *)&psau->sas; 605 606 for(i = 0; i < maxsize; i++) 607 { 608 printf("%02x", *cp++); 609 if (!((i + 1) % 4)) 610 printf(" "); 611 } 612 printf("\n"); 613 } 614 615 /* 616 * print_interface - helper to output debug information 617 */ 618 static void 619 print_interface(struct interface *iface, const char *pfx, const char *sfx) 620 { 621 printf("%sinterface #%d: fd=%d, bfd=%d, name=%s, flags=0x%x, scope=%d, sin=%s", 622 pfx, 623 iface->ifnum, 624 iface->fd, 625 iface->bfd, 626 iface->name, 627 iface->flags, 628 iface->scopeid, 629 stoa(&iface->sin)); 630 if (AF_INET == iface->family) { 631 if (iface->flags & INT_BROADCAST) 632 printf(", bcast=%s", stoa(&iface->bcast)); 633 printf(", mask=%s", stoa(&iface->mask)); 634 } 635 printf(", %s:%s", 636 (iface->ignore_packets) 637 ? "Disabled" 638 : "Enabled", 639 sfx); 640 if (debug > 4) /* in-depth debugging only */ 641 interface_dump(iface); 642 } 643 #endif 644 645 #if !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET) 646 /* 647 * create an asyncio_reader structure 648 */ 649 static struct asyncio_reader * 650 new_asyncio_reader(void) 651 { 652 struct asyncio_reader *reader; 653 654 reader = emalloc(sizeof(*reader)); 655 656 memset(reader, 0, sizeof(*reader)); 657 reader->fd = INVALID_SOCKET; 658 return reader; 659 } 660 661 /* 662 * delete a reader 663 */ 664 static void 665 delete_asyncio_reader( 666 struct asyncio_reader *reader 667 ) 668 { 669 free(reader); 670 } 671 672 /* 673 * add asynchio_reader 674 */ 675 static void 676 add_asyncio_reader( 677 struct asyncio_reader * reader, 678 enum desc_type type) 679 { 680 LINK_SLIST(asyncio_reader_list, reader, link); 681 add_fd_to_list(reader->fd, type); 682 } 683 684 /* 685 * remove asynchio_reader 686 */ 687 static void 688 remove_asyncio_reader( 689 struct asyncio_reader *reader 690 ) 691 { 692 struct asyncio_reader *unlinked; 693 694 UNLINK_SLIST(unlinked, asyncio_reader_list, reader, link, 695 struct asyncio_reader); 696 697 if (reader->fd != INVALID_SOCKET) 698 close_and_delete_fd_from_list(reader->fd); 699 700 reader->fd = INVALID_SOCKET; 701 } 702 #endif /* !defined(HAVE_IO_COMPLETION_PORT) && defined(HAS_ROUTING_SOCKET) */ 703 704 /* 705 * Code to tell if we have an IP address 706 * If we have then return the sockaddr structure 707 * and set the return value 708 * see the bind9/getaddresses.c for details 709 */ 710 isc_boolean_t 711 is_ip_address( 712 const char * host, 713 isc_netaddr_t * addr 714 ) 715 { 716 struct in_addr in4; 717 struct in6_addr in6; 718 char tmpbuf[128]; 719 char *pch; 720 721 NTP_REQUIRE(host != NULL); 722 NTP_REQUIRE(addr != NULL); 723 724 /* 725 * Try IPv4, then IPv6. In order to handle the extended format 726 * for IPv6 scoped addresses (address%scope_ID), we'll use a local 727 * working buffer of 128 bytes. The length is an ad-hoc value, but 728 * should be enough for this purpose; the buffer can contain a string 729 * of at least 80 bytes for scope_ID in addition to any IPv6 numeric 730 * addresses (up to 46 bytes), the delimiter character and the 731 * terminating NULL character. 732 */ 733 if (inet_pton(AF_INET, host, &in4) == 1) { 734 isc_netaddr_fromin(addr, &in4); 735 return (ISC_TRUE); 736 } else if (sizeof(tmpbuf) > strlen(host)) { 737 if ('[' == host[0]) { 738 strncpy(tmpbuf, &host[1], sizeof(tmpbuf)); 739 pch = strchr(tmpbuf, ']'); 740 if (pch != NULL) 741 *pch = '\0'; 742 } else 743 strncpy(tmpbuf, host, sizeof(tmpbuf)); 744 pch = strchr(tmpbuf, '%'); 745 if (pch != NULL) 746 *pch = '\0'; 747 748 if (inet_pton(AF_INET6, tmpbuf, &in6) == 1) { 749 isc_netaddr_fromin6(addr, &in6); 750 return (ISC_TRUE); 751 } 752 } 753 /* 754 * If we got here it was not an IP address 755 */ 756 return (ISC_FALSE); 757 } 758 759 760 /* 761 * interface list enumerator - visitor pattern 762 */ 763 void 764 interface_enumerate( 765 interface_receiver_t receiver, 766 void * data 767 ) 768 { 769 interface_info_t ifi; 770 771 ifi.action = IFS_EXISTS; 772 773 for (ifi.interface = inter_list; 774 ifi.interface != NULL; 775 ifi.interface = ifi.interface->link) 776 (*receiver)(data, &ifi); 777 } 778 779 /* 780 * do standard initialization of interface structure 781 */ 782 static void 783 init_interface( 784 struct interface *iface 785 ) 786 { 787 memset(iface, 0, sizeof(*iface)); 788 iface->fd = INVALID_SOCKET; 789 iface->bfd = INVALID_SOCKET; 790 iface->phase = sys_interphase; 791 } 792 793 794 /* 795 * create new interface structure initialize from 796 * template structure or via standard initialization 797 * function 798 */ 799 static struct interface * 800 new_interface( 801 struct interface *interface 802 ) 803 { 804 static u_int sys_ifnum = 0; 805 struct interface * iface; 806 807 iface = emalloc(sizeof(*iface)); 808 809 if (NULL == interface) 810 init_interface(iface); 811 else /* use the template */ 812 memcpy(iface, interface, sizeof(*iface)); 813 814 /* count every new instance of an interface in the system */ 815 iface->ifnum = sys_ifnum++; 816 iface->starttime = current_time; 817 818 return iface; 819 } 820 821 822 /* 823 * return interface storage into free memory pool 824 */ 825 static inline void 826 delete_interface( 827 struct interface *interface 828 ) 829 { 830 free(interface); 831 } 832 833 834 /* 835 * link interface into list of known interfaces 836 */ 837 static void 838 add_interface( 839 struct interface *interface 840 ) 841 { 842 /* 843 * Calculate the address hash 844 */ 845 interface->addr_refid = addr2refid(&interface->sin); 846 847 LINK_SLIST(inter_list, interface, link); 848 ninterfaces++; 849 } 850 851 852 /* 853 * remove interface from known interface list and clean up 854 * associated resources 855 */ 856 static void 857 remove_interface( 858 struct interface *iface 859 ) 860 { 861 struct interface *unlinked; 862 sockaddr_u resmask; 863 864 UNLINK_SLIST(unlinked, inter_list, iface, link, struct 865 interface); 866 867 delete_interface_from_list(iface); 868 869 if (iface->fd != INVALID_SOCKET) { 870 msyslog(LOG_INFO, 871 "Deleting interface #%d %s, %s#%d, interface stats: received=%ld, sent=%ld, dropped=%ld, active_time=%ld secs", 872 iface->ifnum, 873 iface->name, 874 stoa(&iface->sin), 875 SRCPORT(&iface->sin), 876 iface->received, 877 iface->sent, 878 iface->notsent, 879 current_time - iface->starttime); 880 881 close_and_delete_fd_from_list(iface->fd); 882 } 883 884 if (iface->bfd != INVALID_SOCKET) { 885 msyslog(LOG_INFO, 886 "Deleting broadcast address %s#%d from interface #%d %s", 887 stoa(&iface->bcast), 888 SRCPORT(&iface->bcast), 889 iface->ifnum, 890 iface->name); 891 892 close_and_delete_fd_from_list(iface->bfd); 893 } 894 895 ninterfaces--; 896 ntp_monclearinterface(iface); 897 898 /* remove restrict interface entry */ 899 SET_HOSTMASK(&resmask, AF(&iface->sin)); 900 hack_restrict(RESTRICT_REMOVEIF, &iface->sin, &resmask, 901 RESM_NTPONLY | RESM_INTERFACE, RES_IGNORE); 902 } 903 904 905 static void 906 list_if_listening( 907 struct interface * iface 908 ) 909 { 910 msyslog(LOG_INFO, "%s on %d %s %s UDP %d", 911 (iface->ignore_packets) 912 ? "Listen and drop" 913 : "Listen normally", 914 iface->ifnum, 915 iface->name, 916 stoa(&iface->sin), 917 SRCPORT(&iface->sin)); 918 } 919 920 921 static void 922 create_wildcards( 923 u_short port 924 ) 925 { 926 int v4wild; 927 #ifdef INCLUDE_IPV6_SUPPORT 928 int v6wild; 929 #endif 930 sockaddr_u wildaddr; 931 isc_netaddr_t wnaddr; 932 nic_rule_action action; 933 struct interface * wildif; 934 935 /* 936 * silence "potentially uninitialized" warnings from VC9 937 * failing to follow the logic. Ideally action could remain 938 * uninitialized, and the memset be the first statement under 939 * the first if (v4wild). 940 */ 941 action = ACTION_LISTEN; 942 memset(&wildaddr, 0, sizeof(wildaddr)); 943 944 /* 945 * create pseudo-interface with wildcard IPv4 address 946 */ 947 v4wild = ipv4_works; 948 if (v4wild) { 949 /* set wildaddr to the v4 wildcard address 0.0.0.0 */ 950 AF(&wildaddr) = AF_INET; 951 SET_ADDR4(&wildaddr, INADDR_ANY); 952 SET_PORT(&wildaddr, port); 953 954 /* make an libisc-friendly copy */ 955 isc_netaddr_fromin(&wnaddr, &wildaddr.sa4.sin_addr); 956 957 /* check for interface/nic rules affecting the wildcard */ 958 action = interface_action(NULL, &wnaddr, 0); 959 v4wild = (ACTION_IGNORE != action); 960 } 961 if (v4wild) { 962 wildif = new_interface(NULL); 963 964 strncpy(wildif->name, "v4wildcard", sizeof(wildif->name)); 965 memcpy(&wildif->sin, &wildaddr, sizeof(wildif->sin)); 966 wildif->family = AF_INET; 967 AF(&wildif->mask) = AF_INET; 968 SET_ONESMASK(&wildif->mask); 969 970 wildif->flags = INT_BROADCAST | INT_UP | INT_WILDCARD; 971 wildif->ignore_packets = (ACTION_DROP == action); 972 #if defined(MCAST) 973 /* 974 * enable multicast reception on the broadcast socket 975 */ 976 AF(&wildif->bcast) = AF_INET; 977 SET_ADDR4(&wildif->bcast, INADDR_ANY); 978 SET_PORT(&wildif->bcast, port); 979 #endif /* MCAST */ 980 wildif->fd = open_socket(&wildif->sin, 0, 1, wildif); 981 982 if (wildif->fd != INVALID_SOCKET) { 983 wildipv4 = wildif; 984 any_interface = wildif; 985 986 add_addr_to_list(&wildif->sin, wildif); 987 add_interface(wildif); 988 list_if_listening(wildif); 989 } else { 990 msyslog(LOG_ERR, 991 "unable to bind to wildcard address %s - another process may be running - EXITING", 992 stoa(&wildif->sin)); 993 exit(1); 994 } 995 DPRINT_INTERFACE(2, (wildif, "created ", "\n")); 996 } 997 998 #ifdef INCLUDE_IPV6_SUPPORT 999 /* 1000 * create pseudo-interface with wildcard IPv6 address 1001 */ 1002 v6wild = ipv6_works; 1003 if (v6wild) { 1004 /* set wildaddr to the v6 wildcard address :: */ 1005 memset(&wildaddr, 0, sizeof(wildaddr)); 1006 AF(&wildaddr) = AF_INET6; 1007 SET_ADDR6N(&wildaddr, in6addr_any); 1008 SET_PORT(&wildaddr, port); 1009 SET_SCOPE(&wildaddr, 0); 1010 1011 /* make an libisc-friendly copy */ 1012 isc_netaddr_fromin(&wnaddr, &wildaddr.sa4.sin_addr); 1013 1014 /* check for interface/nic rules affecting the wildcard */ 1015 action = interface_action(NULL, &wnaddr, 0); 1016 v6wild = (ACTION_IGNORE != action); 1017 } 1018 if (v6wild) { 1019 wildif = new_interface(NULL); 1020 1021 strncpy(wildif->name, "v6wildcard", sizeof(wildif->name)); 1022 memcpy(&wildif->sin, &wildaddr, sizeof(wildif->sin)); 1023 wildif->family = AF_INET6; 1024 AF(&wildif->mask) = AF_INET6; 1025 SET_ONESMASK(&wildif->mask); 1026 1027 wildif->flags = INT_UP | INT_WILDCARD; 1028 wildif->ignore_packets = (ACTION_DROP == action); 1029 1030 wildif->fd = open_socket(&wildif->sin, 0, 1, wildif); 1031 1032 if (wildif->fd != INVALID_SOCKET) { 1033 wildipv6 = wildif; 1034 any6_interface = wildif; 1035 add_addr_to_list(&wildif->sin, wildif); 1036 add_interface(wildif); 1037 list_if_listening(wildif); 1038 } else { 1039 msyslog(LOG_ERR, 1040 "unable to bind to wildcard address %s - another process may be running - EXITING", 1041 stoa(&wildif->sin)); 1042 exit(1); 1043 } 1044 DPRINT_INTERFACE(2, (wildif, "created ", "\n")); 1045 } 1046 #endif 1047 } 1048 1049 1050 /* 1051 * add_nic_rule() -- insert a rule entry at the head of nic_rule_list. 1052 */ 1053 void 1054 add_nic_rule( 1055 nic_rule_match match_type, 1056 const char * if_name, /* interface name or numeric address */ 1057 int prefixlen, 1058 nic_rule_action action 1059 ) 1060 { 1061 nic_rule * rule; 1062 isc_boolean_t is_ip; 1063 1064 rule = emalloc(sizeof(*rule)); 1065 memset(rule, 0, sizeof(*rule)); 1066 rule->match_type = match_type; 1067 rule->prefixlen = prefixlen; 1068 rule->action = action; 1069 1070 if (MATCH_IFNAME == match_type) { 1071 NTP_REQUIRE(NULL != if_name); 1072 rule->if_name = estrdup(if_name); 1073 } else if (MATCH_IFADDR == match_type) { 1074 NTP_REQUIRE(NULL != if_name); 1075 /* set rule->netaddr */ 1076 is_ip = is_ip_address(if_name, &rule->netaddr); 1077 NTP_REQUIRE(is_ip); 1078 } else 1079 NTP_REQUIRE(NULL == if_name); 1080 1081 LINK_SLIST(nic_rule_list, rule, next); 1082 } 1083 1084 1085 #ifdef DEBUG 1086 static const char * 1087 action_text( 1088 nic_rule_action action 1089 ) 1090 { 1091 const char *t; 1092 1093 switch (action) { 1094 1095 default: 1096 t = "ERROR"; /* quiet uninit warning */ 1097 DPRINTF(1, ("fatal: unknown nic_rule_action %d\n", 1098 action)); 1099 NTP_ENSURE(0); 1100 break; 1101 1102 case ACTION_LISTEN: 1103 t = "listen"; 1104 break; 1105 1106 case ACTION_IGNORE: 1107 t = "ignore"; 1108 break; 1109 1110 case ACTION_DROP: 1111 t = "drop"; 1112 break; 1113 } 1114 1115 return t; 1116 } 1117 #endif /* DEBUG */ 1118 1119 1120 static nic_rule_action 1121 interface_action( 1122 char * if_name, 1123 isc_netaddr_t * if_netaddr, 1124 isc_uint32_t if_flags 1125 ) 1126 { 1127 nic_rule *rule; 1128 int isloopback; 1129 int iswildcard; 1130 1131 DPRINTF(4, ("interface_action: interface %s ", 1132 (if_name != NULL) ? if_name : "wildcard")); 1133 1134 iswildcard = is_wildcard_netaddr(if_netaddr); 1135 1136 /* 1137 * Always listen on 127.0.0.1 - required by ntp_intres 1138 */ 1139 if (if_flags & INTERFACE_F_LOOPBACK) { 1140 isloopback = 1; 1141 if (AF_INET == if_netaddr->family) { 1142 DPRINTF(4, ("IPv4 loopback - listen\n")); 1143 return ACTION_LISTEN; 1144 } 1145 } else 1146 isloopback = 0; 1147 1148 /* 1149 * Find any matching NIC rule from --interface / -I or ntp.conf 1150 * interface/nic rules. 1151 */ 1152 for (rule = nic_rule_list; rule != NULL; rule = rule->next) { 1153 1154 switch (rule->match_type) { 1155 1156 case MATCH_ALL: 1157 /* loopback and wildcard excluded from "all" */ 1158 if (isloopback || iswildcard) 1159 break; 1160 DPRINTF(4, ("nic all %s\n", 1161 action_text(rule->action))); 1162 return rule->action; 1163 1164 case MATCH_IPV4: 1165 if (AF_INET == if_netaddr->family) { 1166 DPRINTF(4, ("nic ipv4 %s\n", 1167 action_text(rule->action))); 1168 return rule->action; 1169 } 1170 break; 1171 1172 case MATCH_IPV6: 1173 if (AF_INET6 == if_netaddr->family) { 1174 DPRINTF(4, ("nic ipv6 %s\n", 1175 action_text(rule->action))); 1176 return rule->action; 1177 } 1178 break; 1179 1180 case MATCH_WILDCARD: 1181 if (iswildcard) { 1182 DPRINTF(4, ("nic wildcard %s\n", 1183 action_text(rule->action))); 1184 return rule->action; 1185 } 1186 break; 1187 1188 case MATCH_IFADDR: 1189 if (rule->prefixlen != -1) { 1190 if (isc_netaddr_eqprefix(if_netaddr, 1191 &rule->netaddr, rule->prefixlen)) { 1192 1193 DPRINTF(4, ("subnet address match - %s\n", 1194 action_text(rule->action))); 1195 return rule->action; 1196 } 1197 } else 1198 if (isc_netaddr_equal(if_netaddr, 1199 &rule->netaddr)) { 1200 1201 DPRINTF(4, ("address match - %s\n", 1202 action_text(rule->action))); 1203 return rule->action; 1204 } 1205 break; 1206 1207 case MATCH_IFNAME: 1208 if (if_name != NULL 1209 && !strcasecmp(if_name, rule->if_name)) { 1210 1211 DPRINTF(4, ("interface name match - %s\n", 1212 action_text(rule->action))); 1213 return rule->action; 1214 } 1215 break; 1216 } 1217 } 1218 1219 /* 1220 * Unless explicitly disabled such as with "nic ignore ::1" 1221 * listen on loopback addresses. Since ntpq and ntpdc query 1222 * "localhost" by default, which typically resolves to ::1 and 1223 * 127.0.0.1, it's useful to default to listening on both. 1224 */ 1225 if (isloopback) { 1226 DPRINTF(4, ("default loopback listen\n")); 1227 return ACTION_LISTEN; 1228 } 1229 1230 /* 1231 * Treat wildcard addresses specially. If there is no explicit 1232 * "nic ... wildcard" or "nic ... 0.0.0.0" or "nic ... ::" rule 1233 * default to drop. 1234 */ 1235 if (iswildcard) { 1236 DPRINTF(4, ("default wildcard drop\n")); 1237 return ACTION_DROP; 1238 } 1239 1240 /* 1241 * Check for "virtual IP" (colon in the interface name) after 1242 * the rules so that "ntpd --interface eth0:1 -novirtualips" 1243 * does indeed listen on eth0:1's addresses. 1244 */ 1245 if (!listen_to_virtual_ips && if_name != NULL 1246 && (strchr(if_name, ':') != NULL)) { 1247 1248 DPRINTF(4, ("virtual ip - ignore\n")); 1249 return ACTION_IGNORE; 1250 } 1251 1252 /* 1253 * If there are no --interface/-I command-line options and no 1254 * interface/nic rules in ntp.conf, the default action is to 1255 * listen. In the presence of rules from either, the default 1256 * is to ignore. This implements ntpd's traditional listen- 1257 * every default with no interface listen configuration, and 1258 * ensures a single -I eth0 or "nic listen eth0" means do not 1259 * listen on any other addresses. 1260 */ 1261 if (NULL == nic_rule_list) { 1262 DPRINTF(4, ("default listen\n")); 1263 return ACTION_LISTEN; 1264 } 1265 1266 DPRINTF(4, ("implicit ignore\n")); 1267 return ACTION_IGNORE; 1268 } 1269 1270 1271 static void 1272 convert_isc_if( 1273 isc_interface_t *isc_if, 1274 struct interface *itf, 1275 u_short port 1276 ) 1277 { 1278 strncpy(itf->name, isc_if->name, sizeof(itf->name)); 1279 itf->name[sizeof(itf->name) - 1] = 0; /* strncpy may not */ 1280 itf->family = (u_short)isc_if->af; 1281 AF(&itf->sin) = itf->family; 1282 AF(&itf->mask) = itf->family; 1283 AF(&itf->bcast) = itf->family; 1284 SET_PORT(&itf->sin, port); 1285 SET_PORT(&itf->mask, port); 1286 SET_PORT(&itf->bcast, port); 1287 1288 if (IS_IPV4(&itf->sin)) { 1289 NSRCADR(&itf->sin) = isc_if->address.type.in.s_addr; 1290 NSRCADR(&itf->mask) = isc_if->netmask.type.in.s_addr; 1291 1292 if (isc_if->flags & INTERFACE_F_BROADCAST) { 1293 itf->flags |= INT_BROADCAST; 1294 NSRCADR(&itf->bcast) = 1295 isc_if->broadcast.type.in.s_addr; 1296 } 1297 } 1298 #ifdef INCLUDE_IPV6_SUPPORT 1299 else if (IS_IPV6(&itf->sin)) { 1300 SET_ADDR6N(&itf->sin, isc_if->address.type.in6); 1301 SET_ADDR6N(&itf->mask, isc_if->netmask.type.in6); 1302 1303 itf->scopeid = isc_netaddr_getzone(&isc_if->address); 1304 SET_SCOPE(&itf->sin, itf->scopeid); 1305 } 1306 #endif /* INCLUDE_IPV6_SUPPORT */ 1307 1308 1309 /* Process the rest of the flags */ 1310 1311 itf->flags |= 1312 ((INTERFACE_F_UP & isc_if->flags) 1313 ? INT_UP : 0) 1314 | ((INTERFACE_F_LOOPBACK & isc_if->flags) 1315 ? INT_LOOPBACK : 0) 1316 | ((INTERFACE_F_POINTTOPOINT & isc_if->flags) 1317 ? INT_PPP : 0) 1318 | ((INTERFACE_F_MULTICAST & isc_if->flags) 1319 ? INT_MULTICAST : 0) 1320 ; 1321 } 1322 1323 1324 /* 1325 * refresh_interface 1326 * 1327 * some OSes have been observed to keep 1328 * cached routes even when more specific routes 1329 * become available. 1330 * this can be mitigated by re-binding 1331 * the socket. 1332 */ 1333 static int 1334 refresh_interface( 1335 struct interface * interface 1336 ) 1337 { 1338 #ifdef OS_MISSES_SPECIFIC_ROUTE_UPDATES 1339 if (interface->fd != INVALID_SOCKET) { 1340 close_and_delete_fd_from_list(interface->fd); 1341 interface->fd = open_socket(&interface->sin, 1342 0, 0, interface); 1343 /* 1344 * reset TTL indication so TTL is is set again 1345 * next time around 1346 */ 1347 interface->last_ttl = 0; 1348 return (interface->fd != INVALID_SOCKET); 1349 } else 1350 return 0; /* invalid sockets are not refreshable */ 1351 #else /* !OS_MISSES_SPECIFIC_ROUTE_UPDATES */ 1352 return (interface->fd != INVALID_SOCKET); 1353 #endif /* !OS_MISSES_SPECIFIC_ROUTE_UPDATES */ 1354 } 1355 1356 /* 1357 * interface_update - externally callable update function 1358 */ 1359 void 1360 interface_update( 1361 interface_receiver_t receiver, 1362 void * data) 1363 { 1364 int new_interface_found; 1365 1366 if (disable_dynamic_updates) 1367 return; 1368 1369 BLOCKIO(); 1370 new_interface_found = update_interfaces(NTP_PORT, receiver, data); 1371 UNBLOCKIO(); 1372 1373 if (!new_interface_found) 1374 return; 1375 1376 #ifdef DEBUG 1377 msyslog(LOG_DEBUG, "new interface(s) found: waking up resolver"); 1378 #endif 1379 #ifdef SYS_WINNT 1380 /* wake up the resolver thread */ 1381 if (ResolverEventHandle != NULL) 1382 SetEvent(ResolverEventHandle); 1383 #else 1384 /* write any single byte to the pipe to wake up the resolver process */ 1385 write( resolver_pipe_fd[1], &new_interface_found, 1 ); 1386 #endif 1387 } 1388 1389 1390 /* 1391 * sau_from_netaddr() - convert network address on-wire formats. 1392 * Convert from libisc's isc_netaddr_t to NTP's sockaddr_u 1393 */ 1394 void 1395 sau_from_netaddr( 1396 sockaddr_u *psau, 1397 const isc_netaddr_t *pna 1398 ) 1399 { 1400 memset(psau, 0, sizeof(*psau)); 1401 AF(psau) = (u_short)pna->family; 1402 switch (pna->family) { 1403 1404 case AF_INET: 1405 memcpy(&psau->sa4.sin_addr, &pna->type.in, 1406 sizeof(psau->sa4.sin_addr)); 1407 break; 1408 1409 case AF_INET6: 1410 memcpy(&psau->sa6.sin6_addr, &pna->type.in6, 1411 sizeof(psau->sa6.sin6_addr)); 1412 break; 1413 } 1414 } 1415 1416 1417 static int 1418 is_wildcard_addr( 1419 sockaddr_u *psau 1420 ) 1421 { 1422 if (IS_IPV4(psau) && !NSRCADR(psau)) 1423 return 1; 1424 1425 #ifdef INCLUDE_IPV6_SUPPORT 1426 if (IS_IPV6(psau) && S_ADDR6_EQ(psau, &in6addr_any)) 1427 return 1; 1428 #endif 1429 1430 return 0; 1431 } 1432 1433 1434 static int 1435 is_wildcard_netaddr( 1436 const isc_netaddr_t *pna 1437 ) 1438 { 1439 sockaddr_u sau; 1440 1441 sau_from_netaddr(&sau, pna); 1442 1443 return is_wildcard_addr(&sau); 1444 } 1445 1446 1447 #ifdef OS_NEEDS_REUSEADDR_FOR_IFADDRBIND 1448 /* 1449 * enable/disable re-use of wildcard address socket 1450 */ 1451 static void 1452 set_wildcard_reuse( 1453 u_short family, 1454 int on 1455 ) 1456 { 1457 struct interface *any; 1458 SOCKET fd = INVALID_SOCKET; 1459 1460 any = ANY_INTERFACE_BYFAM(family); 1461 if (any != NULL) 1462 fd = any->fd; 1463 1464 if (fd != INVALID_SOCKET) { 1465 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, 1466 (char *)&on, sizeof(on))) 1467 msyslog(LOG_ERR, 1468 "set_wildcard_reuse: setsockopt(SO_REUSEADDR, %s) failed: %m", 1469 on ? "on" : "off"); 1470 1471 DPRINTF(4, ("set SO_REUSEADDR to %s on %s\n", 1472 on ? "on" : "off", 1473 stoa(&any->sin))); 1474 } 1475 } 1476 #endif /* OS_NEEDS_REUSEADDR_FOR_IFADDRBIND */ 1477 1478 /* 1479 * update_interface strategy 1480 * 1481 * toggle configuration phase 1482 * 1483 * Phase 1: 1484 * forall currently existing interfaces 1485 * if address is known: 1486 * drop socket - rebind again 1487 * 1488 * if address is NOT known: 1489 * attempt to create a new interface entry 1490 * 1491 * Phase 2: 1492 * forall currently known non MCAST and WILDCARD interfaces 1493 * if interface does not match configuration phase (not seen in phase 1): 1494 * remove interface from known interface list 1495 * forall peers associated with this interface 1496 * disconnect peer from this interface 1497 * 1498 * Phase 3: 1499 * attempt to re-assign interfaces to peers 1500 * 1501 */ 1502 1503 static int 1504 update_interfaces( 1505 u_short port, 1506 interface_receiver_t receiver, 1507 void * data 1508 ) 1509 { 1510 isc_mem_t * mctx = (void *)-1; 1511 interface_info_t ifi; 1512 isc_interfaceiter_t * iter; 1513 isc_result_t result; 1514 isc_interface_t isc_if; 1515 int new_interface_found; 1516 unsigned int family; 1517 struct interface interface; 1518 struct interface * iface; 1519 struct interface * next; 1520 1521 DPRINTF(3, ("update_interfaces(%d)\n", port)); 1522 1523 /* 1524 * phase one - scan interfaces 1525 * - create those that are not found 1526 * - update those that are found 1527 */ 1528 1529 new_interface_found = 0; 1530 iter = NULL; 1531 result = isc_interfaceiter_create(mctx, &iter); 1532 1533 if (result != ISC_R_SUCCESS) 1534 return 0; 1535 1536 /* 1537 * Toggle system interface scan phase to find untouched 1538 * interfaces to be deleted. 1539 */ 1540 sys_interphase ^= 0x1; 1541 1542 for (result = isc_interfaceiter_first(iter); 1543 ISC_R_SUCCESS == result; 1544 result = isc_interfaceiter_next(iter)) { 1545 1546 result = isc_interfaceiter_current(iter, &isc_if); 1547 1548 if (result != ISC_R_SUCCESS) 1549 break; 1550 1551 /* See if we have a valid family to use */ 1552 family = isc_if.address.family; 1553 if (AF_INET != family && AF_INET6 != family) 1554 continue; 1555 if (AF_INET == family && !ipv4_works) 1556 continue; 1557 if (AF_INET6 == family && !ipv6_works) 1558 continue; 1559 1560 /* create prototype */ 1561 init_interface(&interface); 1562 1563 convert_isc_if(&isc_if, &interface, port); 1564 1565 /* 1566 * Check if and how we are going to use the interface. 1567 */ 1568 switch (interface_action(isc_if.name, &isc_if.address, 1569 isc_if.flags)) { 1570 1571 case ACTION_IGNORE: 1572 continue; 1573 1574 case ACTION_LISTEN: 1575 interface.ignore_packets = ISC_FALSE; 1576 break; 1577 1578 case ACTION_DROP: 1579 interface.ignore_packets = ISC_TRUE; 1580 break; 1581 } 1582 1583 DPRINT_INTERFACE(4, (&interface, "examining ", "\n")); 1584 1585 /* interfaces must be UP to be usable */ 1586 if (!(interface.flags & INT_UP)) { 1587 DPRINTF(4, ("skipping interface %s (%s) - DOWN\n", 1588 interface.name, stoa(&interface.sin))); 1589 continue; 1590 } 1591 1592 /* 1593 * skip any interfaces UP and bound to a wildcard 1594 * address - some dhcp clients produce that in the 1595 * wild 1596 */ 1597 if (is_wildcard_addr(&interface.sin)) 1598 continue; 1599 1600 /* 1601 * map to local *address* in order to map all duplicate 1602 * interfaces to an interface structure with the 1603 * appropriate socket. Our name space is (ip-address), 1604 * NOT (interface name, ip-address). 1605 */ 1606 iface = getinterface(&interface.sin, INT_WILDCARD); 1607 1608 if (iface != NULL && refresh_interface(iface)) { 1609 /* 1610 * found existing and up to date interface - 1611 * mark present. 1612 */ 1613 if (iface->phase != sys_interphase) { 1614 /* 1615 * On a new round we reset the name so 1616 * the interface name shows up again if 1617 * this address is no longer shared. 1618 * The same reasoning goes for the 1619 * ignore_packets flag. 1620 */ 1621 strncpy(iface->name, interface.name, 1622 sizeof(iface->name)); 1623 iface->ignore_packets = 1624 interface.ignore_packets; 1625 } else 1626 /* name collision - rename interface */ 1627 strncpy(iface->name, "*multiple*", 1628 sizeof(iface->name)); 1629 1630 DPRINT_INTERFACE(4, (iface, "updating ", 1631 " present\n")); 1632 1633 if (iface->ignore_packets != 1634 interface.ignore_packets) { 1635 /* 1636 * We have conflicting configurations 1637 * for the interface address. This is 1638 * caused by using -I <interfacename> 1639 * for an interface that shares its 1640 * address with other interfaces. We 1641 * can not disambiguate incoming 1642 * packets delivered to this socket 1643 * without extra syscalls/features. 1644 * These are not (commonly) available. 1645 * Note this is a more unusual 1646 * configuration where several 1647 * interfaces share an address but 1648 * filtering via interface name is 1649 * attempted. We resolve the 1650 * configuration conflict by disabling 1651 * the processing of received packets. 1652 * This leads to no service on the 1653 * interface address where the conflict 1654 * occurs. 1655 */ 1656 msyslog(LOG_ERR, 1657 "WARNING: conflicting enable configuration for interfaces %s and %s for address %s - unsupported configuration - address DISABLED", 1658 interface.name, iface->name, 1659 stoa(&interface.sin)); 1660 1661 iface->ignore_packets = ISC_TRUE; 1662 } 1663 1664 iface->phase = sys_interphase; 1665 1666 ifi.action = IFS_EXISTS; 1667 ifi.interface = iface; 1668 if (receiver != NULL) 1669 (*receiver)(data, &ifi); 1670 } else { 1671 /* 1672 * This is new or refreshing failed - add to 1673 * our interface list. If refreshing failed we 1674 * will delete the interface structure in phase 1675 * 2 as the interface was not marked current. 1676 * We can bind to the address as the refresh 1677 * code already closed the offending socket 1678 */ 1679 iface = create_interface(port, &interface); 1680 1681 if (iface != NULL) { 1682 ifi.action = IFS_CREATED; 1683 ifi.interface = iface; 1684 if (receiver != NULL) 1685 (*receiver)(data, &ifi); 1686 1687 new_interface_found = 1; 1688 1689 DPRINT_INTERFACE(3, 1690 (iface, "updating ", 1691 " new - created\n")); 1692 } else { 1693 DPRINT_INTERFACE(3, 1694 (&interface, "updating ", 1695 " new - creation FAILED")); 1696 1697 msyslog(LOG_INFO, 1698 "failed to init interface for address %s", 1699 stoa(&interface.sin)); 1700 continue; 1701 } 1702 } 1703 } 1704 1705 isc_interfaceiter_destroy(&iter); 1706 1707 /* 1708 * phase 2 - delete gone interfaces - reassigning peers to 1709 * other interfaces 1710 */ 1711 iface = inter_list; 1712 1713 while (iface != NULL) { 1714 next = iface->link; 1715 1716 if (!(iface->flags & (INT_WILDCARD | INT_MCASTIF))) { 1717 /* 1718 * if phase does not match sys_phase this 1719 * interface was not enumerated during the last 1720 * interface scan - so it is gone and will be 1721 * deleted here unless it is solely an MCAST or 1722 * WILDCARD interface. 1723 */ 1724 if (iface->phase != sys_interphase) { 1725 DPRINT_INTERFACE(3, 1726 (iface, "updating ", 1727 "GONE - deleting\n")); 1728 remove_interface(iface); 1729 1730 ifi.action = IFS_DELETED; 1731 ifi.interface = iface; 1732 if (receiver != NULL) 1733 (*receiver)(data, &ifi); 1734 1735 /* 1736 * disconnect peers from deleted 1737 * interface 1738 */ 1739 while (iface->peers != NULL) 1740 set_peerdstadr(iface->peers, NULL); 1741 1742 /* 1743 * update globals in case we lose 1744 * a loopback interface 1745 */ 1746 if (iface == loopback_interface) 1747 loopback_interface = NULL; 1748 1749 delete_interface(iface); 1750 } 1751 } 1752 iface = next; 1753 } 1754 1755 /* 1756 * phase 3 - re-configure as the world has changed if necessary 1757 */ 1758 refresh_all_peerinterfaces(); 1759 return new_interface_found; 1760 } 1761 1762 1763 /* 1764 * create_sockets - create a socket for each interface plus a default 1765 * socket for when we don't know where to send 1766 */ 1767 static int 1768 create_sockets( 1769 u_short port 1770 ) 1771 { 1772 #ifndef HAVE_IO_COMPLETION_PORT 1773 /* 1774 * I/O Completion Ports don't care about the select and FD_SET 1775 */ 1776 maxactivefd = 0; 1777 FD_ZERO(&activefds); 1778 #endif 1779 1780 DPRINTF(2, ("create_sockets(%d)\n", port)); 1781 1782 create_wildcards(port); 1783 1784 update_interfaces(port, NULL, NULL); 1785 1786 /* 1787 * Now that we have opened all the sockets, turn off the reuse 1788 * flag for security. 1789 */ 1790 set_reuseaddr(0); 1791 1792 DPRINTF(2, ("create_sockets: Total interfaces = %d\n", ninterfaces)); 1793 1794 return ninterfaces; 1795 } 1796 1797 /* 1798 * create_interface - create a new interface for a given prototype 1799 * binding the socket. 1800 */ 1801 static struct interface * 1802 create_interface( 1803 u_short port, 1804 struct interface * protot 1805 ) 1806 { 1807 sockaddr_u resmask; 1808 struct interface *iface; 1809 1810 DPRINTF(2, ("create_interface(%s#%d)\n", stoa(&protot->sin), 1811 port)); 1812 1813 /* build an interface */ 1814 iface = new_interface(protot); 1815 1816 /* 1817 * create socket 1818 */ 1819 iface->fd = open_socket(&iface->sin, 0, 0, iface); 1820 1821 if (iface->fd != INVALID_SOCKET) 1822 list_if_listening(iface); 1823 1824 if ((INT_BROADCAST & iface->flags) 1825 && iface->bfd != INVALID_SOCKET) 1826 msyslog(LOG_INFO, "Listening on broadcast address %s#%d", 1827 stoa((&iface->bcast)), port); 1828 1829 if (INVALID_SOCKET == iface->fd 1830 && INVALID_SOCKET == iface->bfd) { 1831 msyslog(LOG_ERR, "unable to create socket on %s (%d) for %s#%d", 1832 iface->name, 1833 iface->ifnum, 1834 stoa((&iface->sin)), 1835 port); 1836 delete_interface(iface); 1837 return NULL; 1838 } 1839 1840 /* 1841 * Blacklist our own addresses, no use talking to ourself 1842 */ 1843 SET_HOSTMASK(&resmask, AF(&iface->sin)); 1844 hack_restrict(RESTRICT_FLAGS, &iface->sin, &resmask, 1845 RESM_NTPONLY | RESM_INTERFACE, RES_IGNORE); 1846 1847 /* 1848 * set globals with the first found 1849 * loopback interface of the appropriate class 1850 */ 1851 if (NULL == loopback_interface && AF_INET == iface->family 1852 && (INT_LOOPBACK & iface->flags)) 1853 loopback_interface = iface; 1854 1855 /* 1856 * put into our interface list 1857 */ 1858 add_addr_to_list(&iface->sin, iface); 1859 add_interface(iface); 1860 1861 DPRINT_INTERFACE(2, (iface, "created ", "\n")); 1862 return iface; 1863 } 1864 1865 1866 #ifdef SO_EXCLUSIVEADDRUSE 1867 static void 1868 set_excladdruse( 1869 SOCKET fd 1870 ) 1871 { 1872 int one = 1; 1873 int failed; 1874 #ifdef SYS_WINNT 1875 DWORD err; 1876 #endif 1877 1878 failed = setsockopt(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, 1879 (char *)&one, sizeof(one)); 1880 1881 if (!failed) 1882 return; 1883 1884 #ifdef SYS_WINNT 1885 /* 1886 * Prior to Windows XP setting SO_EXCLUSIVEADDRUSE can fail with 1887 * error WSAINVAL depending on service pack level and whether 1888 * the user account is in the Administrators group. Do not 1889 * complain if it fails that way on versions prior to XP (5.1). 1890 */ 1891 err = GetLastError(); 1892 1893 if (isc_win32os_versioncheck(5, 1, 0, 0) < 0 /* < 5.1/XP */ 1894 && WSAEINVAL == err) 1895 return; 1896 1897 SetLastError(err); 1898 #endif 1899 msyslog(LOG_ERR, 1900 "setsockopt(%d, SO_EXCLUSIVEADDRUSE, on): %m", 1901 (int)fd); 1902 } 1903 #endif /* SO_EXCLUSIVEADDRUSE */ 1904 1905 1906 /* 1907 * set_reuseaddr() - set/clear REUSEADDR on all sockets 1908 * NB possible hole - should we be doing this on broadcast 1909 * fd's also? 1910 */ 1911 static void 1912 set_reuseaddr( 1913 int flag 1914 ) 1915 { 1916 #ifndef SO_EXCLUSIVEADDRUSE 1917 struct interface *interf; 1918 1919 for (interf = inter_list; 1920 interf != NULL; 1921 interf = interf->link) { 1922 1923 if (interf->flags & INT_WILDCARD) 1924 continue; 1925 1926 /* 1927 * if interf->fd is INVALID_SOCKET, we might have a adapter 1928 * configured but not present 1929 */ 1930 DPRINTF(4, ("setting SO_REUSEADDR on %.16s@%s to %s\n", 1931 interf->name, stoa(&interf->sin), 1932 flag ? "on" : "off")); 1933 1934 if (interf->fd != INVALID_SOCKET) { 1935 if (setsockopt(interf->fd, SOL_SOCKET, 1936 SO_REUSEADDR, (char *)&flag, 1937 sizeof(flag))) { 1938 msyslog(LOG_ERR, "set_reuseaddr: setsockopt(SO_REUSEADDR, %s) failed: %m", flag ? "on" : "off"); 1939 } 1940 } 1941 } 1942 #endif /* ! SO_EXCLUSIVEADDRUSE */ 1943 } 1944 1945 /* 1946 * This is just a wrapper around an internal function so we can 1947 * make other changes as necessary later on 1948 */ 1949 void 1950 enable_broadcast( 1951 struct interface * iface, 1952 sockaddr_u * baddr 1953 ) 1954 { 1955 #ifdef OPEN_BCAST_SOCKET 1956 socket_broadcast_enable(iface, iface->fd, baddr); 1957 #endif 1958 } 1959 1960 #ifdef OPEN_BCAST_SOCKET 1961 /* 1962 * Enable a broadcast address to a given socket 1963 * The socket is in the inter_list all we need to do is enable 1964 * broadcasting. It is not this function's job to select the socket 1965 */ 1966 static isc_boolean_t 1967 socket_broadcast_enable( 1968 struct interface * iface, 1969 SOCKET fd, 1970 sockaddr_u * baddr 1971 ) 1972 { 1973 #ifdef SO_BROADCAST 1974 int on = 1; 1975 1976 if (IS_IPV4(baddr)) { 1977 /* if this interface can support broadcast, set SO_BROADCAST */ 1978 if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, 1979 (char *)&on, sizeof(on))) 1980 msyslog(LOG_ERR, 1981 "setsockopt(SO_BROADCAST) enable failure on address %s: %m", 1982 stoa(baddr)); 1983 else 1984 DPRINTF(2, ("Broadcast enabled on socket %d for address %s\n", 1985 fd, stoa(baddr))); 1986 } 1987 iface->flags |= INT_BCASTOPEN; 1988 broadcast_client_enabled = ISC_TRUE; 1989 return ISC_TRUE; 1990 #else 1991 return ISC_FALSE; 1992 #endif /* SO_BROADCAST */ 1993 } 1994 1995 /* 1996 * Remove a broadcast address from a given socket 1997 * The socket is in the inter_list all we need to do is disable 1998 * broadcasting. It is not this function's job to select the socket 1999 */ 2000 static isc_boolean_t 2001 socket_broadcast_disable( 2002 struct interface * iface, 2003 sockaddr_u * baddr 2004 ) 2005 { 2006 #ifdef SO_BROADCAST 2007 int off = 0; /* This seems to be OK as an int */ 2008 2009 if (IS_IPV4(baddr) && setsockopt(iface->fd, SOL_SOCKET, 2010 SO_BROADCAST, (char *)&off, sizeof(off))) 2011 msyslog(LOG_ERR, 2012 "setsockopt(SO_BROADCAST) disable failure on address %s: %m", 2013 stoa(baddr)); 2014 2015 iface->flags &= ~INT_BCASTOPEN; 2016 broadcast_client_enabled = ISC_FALSE; 2017 return ISC_TRUE; 2018 #else 2019 return ISC_FALSE; 2020 #endif /* SO_BROADCAST */ 2021 } 2022 2023 #endif /* OPEN_BCAST_SOCKET */ 2024 2025 /* 2026 * return the broadcast client flag value 2027 */ 2028 isc_boolean_t 2029 get_broadcastclient_flag(void) 2030 { 2031 return (broadcast_client_enabled); 2032 } 2033 /* 2034 * Check to see if the address is a multicast address 2035 */ 2036 static isc_boolean_t 2037 addr_ismulticast( 2038 sockaddr_u *maddr 2039 ) 2040 { 2041 isc_boolean_t result; 2042 2043 #ifndef INCLUDE_IPV6_MULTICAST_SUPPORT 2044 /* 2045 * If we don't have IPV6 support any IPV6 addr is not multicast 2046 */ 2047 if (IS_IPV6(maddr)) 2048 result = ISC_FALSE; 2049 else 2050 #endif 2051 result = IS_MCAST(maddr); 2052 2053 if (!result) 2054 DPRINTF(4, ("address %s is not multicast\n", 2055 stoa(maddr))); 2056 2057 return result; 2058 } 2059 2060 /* 2061 * Multicast servers need to set the appropriate Multicast interface 2062 * socket option in order for it to know which interface to use for 2063 * send the multicast packet. 2064 */ 2065 void 2066 enable_multicast_if( 2067 struct interface * iface, 2068 sockaddr_u * maddr 2069 ) 2070 { 2071 #ifdef MCAST 2072 TYPEOF_IP_MULTICAST_LOOP off = 0; 2073 2074 NTP_REQUIRE(AF(maddr) == AF(&iface->sin)); 2075 2076 switch (AF(&iface->sin)) { 2077 2078 case AF_INET: 2079 if (setsockopt(iface->fd, IPPROTO_IP, IP_MULTICAST_IF, 2080 (void *)&NSRCADR(&iface->sin), 2081 sizeof(NSRCADR(&iface->sin)))) { 2082 2083 msyslog(LOG_ERR, 2084 "setsockopt IP_MULTICAST_IF failed: %m on socket %d, addr %s for multicast address %s", 2085 iface->fd, stoa(&iface->sin), 2086 stoa(maddr)); 2087 return; 2088 } 2089 #ifdef IP_MULTICAST_LOOP 2090 /* 2091 * Don't send back to itself, but allow failure to set 2092 */ 2093 if (setsockopt(iface->fd, IPPROTO_IP, 2094 IP_MULTICAST_LOOP, 2095 SETSOCKOPT_ARG_CAST &off, 2096 sizeof(off))) { 2097 2098 msyslog(LOG_ERR, 2099 "setsockopt IP_MULTICAST_LOOP failed: %m on socket %d, addr %s for multicast address %s", 2100 iface->fd, stoa(&iface->sin), 2101 stoa(maddr)); 2102 } 2103 #endif 2104 DPRINTF(4, ("Added IPv4 multicast interface on socket %d, addr %s for multicast address %s\n", 2105 iface->fd, stoa(&iface->sin), 2106 stoa(maddr))); 2107 break; 2108 2109 case AF_INET6: 2110 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT 2111 if (setsockopt(iface->fd, IPPROTO_IPV6, 2112 IPV6_MULTICAST_IF, 2113 (char *)&iface->scopeid, 2114 sizeof(iface->scopeid))) { 2115 2116 msyslog(LOG_ERR, 2117 "setsockopt IPV6_MULTICAST_IF failed: %m on socket %d, addr %s, scope %d for multicast address %s", 2118 iface->fd, stoa(&iface->sin), 2119 iface->scopeid, stoa(maddr)); 2120 return; 2121 } 2122 #ifdef IPV6_MULTICAST_LOOP 2123 /* 2124 * Don't send back to itself, but allow failure to set 2125 */ 2126 if (setsockopt(iface->fd, IPPROTO_IPV6, 2127 IPV6_MULTICAST_LOOP, 2128 (char *) &off, sizeof(off))) { 2129 2130 msyslog(LOG_ERR, 2131 "setsockopt IP_MULTICAST_LOOP failed: %m on socket %d, addr %s for multicast address %s", 2132 iface->fd, stoa(&iface->sin), 2133 stoa(maddr)); 2134 } 2135 #endif 2136 DPRINTF(4, ("Added IPv6 multicast interface on socket %d, addr %s, scope %d for multicast address %s\n", 2137 iface->fd, stoa(&iface->sin), 2138 iface->scopeid, stoa(maddr))); 2139 break; 2140 #else 2141 return; 2142 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */ 2143 } 2144 return; 2145 #endif 2146 } 2147 2148 /* 2149 * Add a multicast address to a given socket 2150 * The socket is in the inter_list all we need to do is enable 2151 * multicasting. It is not this function's job to select the socket 2152 */ 2153 #ifdef MCAST 2154 static isc_boolean_t 2155 socket_multicast_enable( 2156 struct interface * iface, 2157 int lscope, 2158 sockaddr_u * maddr 2159 ) 2160 { 2161 struct ip_mreq mreq; 2162 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT 2163 struct ipv6_mreq mreq6; 2164 #endif 2165 2166 if (find_addr_in_list(maddr) != NULL) { 2167 DPRINTF(4, ("socket_multicast_enable(%s): already enabled\n", 2168 stoa(maddr))); 2169 return ISC_TRUE; 2170 } 2171 2172 switch (AF(maddr)) { 2173 2174 case AF_INET: 2175 memset(&mreq, 0, sizeof(mreq)); 2176 mreq.imr_multiaddr = SOCK_ADDR4(maddr); 2177 mreq.imr_interface.s_addr = htonl(INADDR_ANY); 2178 if (setsockopt(iface->fd, 2179 IPPROTO_IP, 2180 IP_ADD_MEMBERSHIP, 2181 (char *)&mreq, 2182 sizeof(mreq))) { 2183 msyslog(LOG_ERR, 2184 "setsockopt IP_ADD_MEMBERSHIP failed: %m on socket %d, addr %s for %x / %x (%s)", 2185 iface->fd, stoa(&iface->sin), 2186 mreq.imr_multiaddr.s_addr, 2187 mreq.imr_interface.s_addr, 2188 stoa(maddr)); 2189 return ISC_FALSE; 2190 } 2191 DPRINTF(4, ("Added IPv4 multicast membership on socket %d, addr %s for %x / %x (%s)\n", 2192 iface->fd, stoa(&iface->sin), 2193 mreq.imr_multiaddr.s_addr, 2194 mreq.imr_interface.s_addr, stoa(maddr))); 2195 break; 2196 2197 case AF_INET6: 2198 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT 2199 /* 2200 * Enable reception of multicast packets. 2201 * If the address is link-local we can get the 2202 * interface index from the scope id. Don't do this 2203 * for other types of multicast addresses. For now let 2204 * the kernel figure it out. 2205 */ 2206 memset(&mreq6, 0, sizeof(mreq6)); 2207 mreq6.ipv6mr_multiaddr = SOCK_ADDR6(maddr); 2208 mreq6.ipv6mr_interface = lscope; 2209 2210 if (setsockopt(iface->fd, IPPROTO_IPV6, 2211 IPV6_JOIN_GROUP, (char *)&mreq6, 2212 sizeof(mreq6))) { 2213 msyslog(LOG_ERR, 2214 "setsockopt IPV6_JOIN_GROUP failed: %m on socket %d, addr %s for interface %d (%s)", 2215 iface->fd, stoa(&iface->sin), 2216 mreq6.ipv6mr_interface, stoa(maddr)); 2217 return ISC_FALSE; 2218 } 2219 DPRINTF(4, ("Added IPv6 multicast group on socket %d, addr %s for interface %d(%s)\n", 2220 iface->fd, stoa(&iface->sin), 2221 mreq6.ipv6mr_interface, stoa(maddr))); 2222 #else 2223 return ISC_FALSE; 2224 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */ 2225 } 2226 iface->flags |= INT_MCASTOPEN; 2227 iface->num_mcast++; 2228 add_addr_to_list(maddr, iface); 2229 return ISC_TRUE; 2230 } 2231 2232 /* 2233 * Remove a multicast address from a given socket 2234 * The socket is in the inter_list all we need to do is disable 2235 * multicasting. It is not this function's job to select the socket 2236 */ 2237 static isc_boolean_t 2238 socket_multicast_disable( 2239 struct interface * iface, 2240 sockaddr_u * maddr 2241 ) 2242 { 2243 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT 2244 struct ipv6_mreq mreq6; 2245 #endif 2246 struct ip_mreq mreq; 2247 2248 memset(&mreq, 0, sizeof(mreq)); 2249 2250 if (find_addr_in_list(maddr) == NULL) { 2251 DPRINTF(4, ("socket_multicast_disable(%s): not found\n", 2252 stoa(maddr))); 2253 return ISC_TRUE; 2254 } 2255 2256 switch (AF(maddr)) { 2257 2258 case AF_INET: 2259 mreq.imr_multiaddr = SOCK_ADDR4(maddr); 2260 mreq.imr_interface = SOCK_ADDR4(&iface->sin); 2261 if (setsockopt(iface->fd, IPPROTO_IP, 2262 IP_DROP_MEMBERSHIP, (char *)&mreq, 2263 sizeof(mreq))) { 2264 2265 msyslog(LOG_ERR, 2266 "setsockopt IP_DROP_MEMBERSHIP failed: %m on socket %d, addr %s for %x / %x (%s)", 2267 iface->fd, stoa(&iface->sin), 2268 SRCADR(maddr), SRCADR(&iface->sin), 2269 stoa(maddr)); 2270 return ISC_FALSE; 2271 } 2272 break; 2273 case AF_INET6: 2274 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT 2275 /* 2276 * Disable reception of multicast packets 2277 * If the address is link-local we can get the 2278 * interface index from the scope id. Don't do this 2279 * for other types of multicast addresses. For now let 2280 * the kernel figure it out. 2281 */ 2282 mreq6.ipv6mr_multiaddr = SOCK_ADDR6(maddr); 2283 mreq6.ipv6mr_interface = iface->scopeid; 2284 2285 if (setsockopt(iface->fd, IPPROTO_IPV6, 2286 IPV6_LEAVE_GROUP, (char *)&mreq6, 2287 sizeof(mreq6))) { 2288 2289 msyslog(LOG_ERR, 2290 "setsockopt IPV6_LEAVE_GROUP failure: %m on socket %d, addr %s for %d (%s)", 2291 iface->fd, stoa(&iface->sin), 2292 iface->scopeid, stoa(maddr)); 2293 return ISC_FALSE; 2294 } 2295 break; 2296 #else 2297 return ISC_FALSE; 2298 #endif /* INCLUDE_IPV6_MULTICAST_SUPPORT */ 2299 } 2300 2301 iface->num_mcast--; 2302 if (!iface->num_mcast) 2303 iface->flags &= ~INT_MCASTOPEN; 2304 2305 return ISC_TRUE; 2306 } 2307 #endif /* MCAST */ 2308 2309 /* 2310 * io_setbclient - open the broadcast client sockets 2311 */ 2312 void 2313 io_setbclient(void) 2314 { 2315 #ifdef OPEN_BCAST_SOCKET 2316 struct interface * interf; 2317 int nif; 2318 isc_boolean_t jstatus; 2319 SOCKET fd; 2320 2321 nif = 0; 2322 set_reuseaddr(1); 2323 2324 for (interf = inter_list; 2325 interf != NULL; 2326 interf = interf->link) { 2327 2328 if (interf->flags & (INT_WILDCARD | INT_LOOPBACK)) 2329 continue; 2330 2331 /* use only allowed addresses */ 2332 if (interf->ignore_packets) 2333 continue; 2334 2335 2336 /* Need a broadcast-capable interface */ 2337 if (!(interf->flags & INT_BROADCAST)) 2338 continue; 2339 2340 /* Only IPv4 addresses are valid for broadcast */ 2341 NTP_REQUIRE(IS_IPV4(&interf->sin)); 2342 2343 /* Do we already have the broadcast address open? */ 2344 if (interf->flags & INT_BCASTOPEN) { 2345 /* 2346 * account for already open interfaces to avoid 2347 * misleading warning below 2348 */ 2349 nif++; 2350 continue; 2351 } 2352 2353 /* 2354 * Try to open the broadcast address 2355 */ 2356 interf->family = AF_INET; 2357 interf->bfd = open_socket(&interf->bcast, 1, 0, interf); 2358 2359 /* 2360 * If we succeeded then we use it otherwise enable 2361 * broadcast on the interface address 2362 */ 2363 if (interf->bfd != INVALID_SOCKET) { 2364 fd = interf->bfd; 2365 jstatus = ISC_TRUE; 2366 } else { 2367 fd = interf->fd; 2368 jstatus = socket_broadcast_enable(interf, fd, 2369 &interf->sin); 2370 } 2371 2372 /* Enable Broadcast on socket */ 2373 if (jstatus) { 2374 nif++; 2375 msyslog(LOG_INFO, 2376 "io_setbclient: Opened broadcast client on interface #%d %s", 2377 interf->ifnum, interf->name); 2378 interf->addr_refid = addr2refid(&interf->sin); 2379 } 2380 } 2381 set_reuseaddr(0); 2382 if (nif > 0) 2383 DPRINTF(1, ("io_setbclient: Opened broadcast clients\n")); 2384 else if (!nif) 2385 msyslog(LOG_ERR, 2386 "Unable to listen for broadcasts, no broadcast interfaces available"); 2387 #else 2388 msyslog(LOG_ERR, 2389 "io_setbclient: Broadcast Client disabled by build"); 2390 #endif /* OPEN_BCAST_SOCKET */ 2391 } 2392 2393 /* 2394 * io_unsetbclient - close the broadcast client sockets 2395 */ 2396 void 2397 io_unsetbclient(void) 2398 { 2399 struct interface *interf; 2400 2401 for (interf = inter_list; 2402 NULL != interf; 2403 interf = interf->link) 2404 { 2405 if (interf->flags & INT_WILDCARD) 2406 continue; 2407 2408 if (!(interf->flags & INT_BCASTOPEN)) 2409 continue; 2410 2411 socket_broadcast_disable(interf, &interf->sin); 2412 } 2413 } 2414 2415 /* 2416 * io_multicast_add() - add multicast group address 2417 */ 2418 void 2419 io_multicast_add( 2420 sockaddr_u *addr 2421 ) 2422 { 2423 #ifdef MCAST 2424 struct interface *interface; 2425 #ifndef MULTICAST_NONEWSOCKET 2426 struct interface *iface; 2427 #endif 2428 int lscope = 0; 2429 2430 /* 2431 * Check to see if this is a multicast address 2432 */ 2433 if (!addr_ismulticast(addr)) 2434 return; 2435 2436 /* If we already have it we can just return */ 2437 if (NULL != find_flagged_addr_in_list(addr, INT_MCASTOPEN)) { 2438 msyslog(LOG_INFO, 2439 "Duplicate request found for multicast address %s", 2440 stoa(addr)); 2441 return; 2442 } 2443 2444 #ifndef MULTICAST_NONEWSOCKET 2445 interface = new_interface(NULL); 2446 2447 /* 2448 * Open a new socket for the multicast address 2449 */ 2450 interface->family = 2451 AF(&interface->sin) = 2452 AF(&interface->mask) = AF(addr); 2453 SET_PORT(&interface->sin, NTP_PORT); 2454 SET_ONESMASK(&interface->mask); 2455 2456 switch(AF(addr)) { 2457 2458 case AF_INET: 2459 NSRCADR(&interface->sin) = NSRCADR(addr); 2460 break; 2461 2462 case AF_INET6: 2463 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT 2464 SET_ADDR6N(&interface->sin, SOCK_ADDR6(addr)); 2465 lscope = SCOPE(addr); 2466 SET_SCOPE(&interface->sin, lscope); 2467 #endif 2468 iface = findlocalcastinterface(addr); 2469 if (iface != NULL) 2470 DPRINTF(4, ("Found interface #%d %s, scope %d for address %s\n", 2471 iface->ifnum, iface->name, lscope, 2472 stoa(addr))); 2473 } 2474 2475 set_reuseaddr(1); 2476 interface->bfd = INVALID_SOCKET; 2477 interface->fd = open_socket(&interface->sin, INT_MULTICAST, 0, 2478 interface); 2479 2480 if (interface->fd != INVALID_SOCKET) { 2481 interface->bfd = INVALID_SOCKET; 2482 interface->ignore_packets = ISC_FALSE; 2483 interface->flags |= INT_MCASTIF; 2484 2485 strncpy(interface->name, "multicast", 2486 sizeof(interface->name)); 2487 DPRINT_INTERFACE(2, (interface, "multicast add ", "\n")); 2488 /* 2489 * socket_multicast_enable() will add this address to 2490 * the addresslist 2491 */ 2492 add_interface(interface); 2493 list_if_listening(interface); 2494 } else { 2495 /* bind failed, re-use wildcard interface */ 2496 delete_interface(interface); 2497 2498 if (IS_IPV4(addr)) 2499 interface = wildipv4; 2500 else if (IS_IPV6(addr)) 2501 interface = wildipv6; 2502 else 2503 interface = NULL; 2504 2505 if (interface != NULL) { 2506 /* HACK ! -- stuff in an address */ 2507 /* because we don't bind addr? DH */ 2508 interface->bcast = *addr; 2509 msyslog(LOG_ERR, 2510 "multicast address %s using wildcard interface #%d %s", 2511 stoa(addr), interface->ifnum, 2512 interface->name); 2513 } else { 2514 msyslog(LOG_ERR, 2515 "No multicast socket available to use for address %s", 2516 stoa(addr)); 2517 return; 2518 } 2519 } 2520 #else 2521 /* 2522 * For the case where we can't use a separate socket 2523 */ 2524 interface = findlocalcastinterface(addr); 2525 /* 2526 * If we don't have a valid socket, just return 2527 */ 2528 if (NULL == interface) { 2529 msyslog(LOG_ERR, 2530 "Can not add multicast address %s: no multicast interface found", 2531 stoa(addr)); 2532 return; 2533 } 2534 2535 #endif 2536 if (socket_multicast_enable(interface, lscope, addr)) 2537 msyslog(LOG_INFO, 2538 "Added Multicast Listener %s on interface #%d %s", 2539 stoa(addr), interface->ifnum, interface->name); 2540 else 2541 msyslog(LOG_ERR, "Failed to add Multicast Listener %s", 2542 stoa(addr)); 2543 #else /* MCAST */ 2544 msyslog(LOG_ERR, 2545 "Can not add multicast address %s: no multicast support", 2546 stoa(addr)); 2547 #endif /* MCAST */ 2548 return; 2549 } 2550 2551 2552 /* 2553 * io_multicast_del() - delete multicast group address 2554 */ 2555 void 2556 io_multicast_del( 2557 sockaddr_u * addr 2558 ) 2559 { 2560 #ifdef MCAST 2561 struct interface *iface; 2562 2563 /* 2564 * Check to see if this is a multicast address 2565 */ 2566 if (!addr_ismulticast(addr)) { 2567 msyslog(LOG_ERR, "invalid multicast address %s", 2568 stoa(addr)); 2569 return; 2570 } 2571 2572 /* 2573 * Disable reception of multicast packets 2574 */ 2575 while ((iface = find_flagged_addr_in_list(addr, INT_MCASTOPEN)) 2576 != NULL) 2577 socket_multicast_disable(iface, addr); 2578 2579 delete_addr_from_list(addr); 2580 2581 #else /* not MCAST */ 2582 msyslog(LOG_ERR, 2583 "Can not delete multicast address %s: no multicast support", 2584 stoa(addr)); 2585 #endif /* not MCAST */ 2586 } 2587 2588 2589 /* 2590 * init_nonblocking_io() - set up descriptor to be non blocking 2591 */ 2592 static void init_nonblocking_io( 2593 SOCKET fd 2594 ) 2595 { 2596 /* 2597 * set non-blocking, 2598 */ 2599 2600 #ifdef USE_FIONBIO 2601 /* in vxWorks we use FIONBIO, but the others are defined for old systems, so 2602 * all hell breaks loose if we leave them defined 2603 */ 2604 #undef O_NONBLOCK 2605 #undef FNDELAY 2606 #undef O_NDELAY 2607 #endif 2608 2609 #if defined(O_NONBLOCK) /* POSIX */ 2610 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) { 2611 msyslog(LOG_ERR, 2612 "fcntl(O_NONBLOCK) fails on fd #%d: %m", fd); 2613 exit(1); 2614 } 2615 #elif defined(FNDELAY) 2616 if (fcntl(fd, F_SETFL, FNDELAY) < 0) { 2617 msyslog(LOG_ERR, "fcntl(FNDELAY) fails on fd #%d: %m", 2618 fd); 2619 exit(1); 2620 } 2621 #elif defined(O_NDELAY) /* generally the same as FNDELAY */ 2622 if (fcntl(fd, F_SETFL, O_NDELAY) < 0) { 2623 msyslog(LOG_ERR, "fcntl(O_NDELAY) fails on fd #%d: %m", 2624 fd); 2625 exit(1); 2626 } 2627 #elif defined(FIONBIO) 2628 { 2629 int on = 1; 2630 2631 if (ioctl(fd, FIONBIO, &on) < 0) { 2632 msyslog(LOG_ERR, 2633 "ioctl(FIONBIO) fails on fd #%d: %m", 2634 fd); 2635 exit(1); 2636 } 2637 } 2638 #elif defined(FIOSNBIO) 2639 if (ioctl(fd, FIOSNBIO, &on) < 0) { 2640 msyslog(LOG_ERR, 2641 "ioctl(FIOSNBIO) fails on fd #%d: %m", fd); 2642 exit(1); 2643 } 2644 #else 2645 # include "Bletch: Need non-blocking I/O!" 2646 #endif 2647 } 2648 2649 /* 2650 * open_socket - open a socket, returning the file descriptor 2651 */ 2652 2653 static SOCKET 2654 open_socket( 2655 sockaddr_u * addr, 2656 int bcast, 2657 int turn_off_reuse, 2658 struct interface * interf 2659 ) 2660 { 2661 SOCKET fd; 2662 int errval; 2663 char scopetext[16]; 2664 /* 2665 * int is OK for REUSEADR per 2666 * http://www.kohala.com/start/mcast.api.txt 2667 */ 2668 int on = 1; 2669 int off = 0; 2670 2671 if (IS_IPV6(addr) && !ipv6_works) 2672 return INVALID_SOCKET; 2673 2674 /* create a datagram (UDP) socket */ 2675 fd = socket(AF(addr), SOCK_DGRAM, 0); 2676 if (INVALID_SOCKET == fd) { 2677 #ifndef SYS_WINNT 2678 errval = errno; 2679 #else 2680 errval = WSAGetLastError(); 2681 #endif 2682 msyslog(LOG_ERR, 2683 "socket(AF_INET%s, SOCK_DGRAM, 0) failed on address %s: %m", 2684 IS_IPV6(addr) ? "6" : "", stoa(addr)); 2685 2686 if (errval == EPROTONOSUPPORT || 2687 errval == EAFNOSUPPORT || 2688 errval == EPFNOSUPPORT) 2689 return (INVALID_SOCKET); 2690 2691 errno = errval; 2692 msyslog(LOG_ERR, 2693 "unexpected socket() error %m code %d (not EPROTONOSUPPORT nor EAFNOSUPPORT nor EPFNOSUPPORT) - exiting", 2694 errno); 2695 exit(1); 2696 } 2697 2698 #ifdef SYS_WINNT 2699 connection_reset_fix(fd, addr); 2700 #endif 2701 /* 2702 * Fixup the file descriptor for some systems 2703 * See bug #530 for details of the issue. 2704 */ 2705 fd = move_fd(fd); 2706 2707 /* 2708 * set SO_REUSEADDR since we will be binding the same port 2709 * number on each interface according to turn_off_reuse. 2710 * This is undesirable on Windows versions starting with 2711 * Windows XP (numeric version 5.1). 2712 */ 2713 #ifdef SYS_WINNT 2714 if (isc_win32os_versioncheck(5, 1, 0, 0) < 0) /* before 5.1 */ 2715 #endif 2716 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, 2717 (char *)((turn_off_reuse) 2718 ? &off 2719 : &on), 2720 sizeof(on))) { 2721 2722 msyslog(LOG_ERR, 2723 "setsockopt SO_REUSEADDR %s fails for address %s: %m", 2724 (turn_off_reuse) 2725 ? "off" 2726 : "on", 2727 stoa(addr)); 2728 closesocket(fd); 2729 return INVALID_SOCKET; 2730 } 2731 #ifdef SO_EXCLUSIVEADDRUSE 2732 /* 2733 * setting SO_EXCLUSIVEADDRUSE on the wildcard we open 2734 * first will cause more specific binds to fail. 2735 */ 2736 if (!(interf->flags & INT_WILDCARD)) 2737 set_excladdruse(fd); 2738 #endif 2739 2740 /* 2741 * IPv4 specific options go here 2742 */ 2743 if (IS_IPV4(addr)) { 2744 #if defined(HAVE_IPTOS_SUPPORT) 2745 if (setsockopt(fd, IPPROTO_IP, IP_TOS, (char *)&qos, 2746 sizeof(qos))) 2747 msyslog(LOG_ERR, 2748 "setsockopt IP_TOS (%02x) fails on address %s: %m", 2749 qos, stoa(addr)); 2750 #endif /* HAVE_IPTOS_SUPPORT */ 2751 if (bcast) 2752 socket_broadcast_enable(interf, fd, addr); 2753 } 2754 2755 /* 2756 * IPv6 specific options go here 2757 */ 2758 if (IS_IPV6(addr)) { 2759 #if defined(IPV6_V6ONLY) 2760 if (isc_net_probe_ipv6only() == ISC_R_SUCCESS 2761 && setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, 2762 (char*)&on, sizeof(on))) 2763 msyslog(LOG_ERR, 2764 "setsockopt IPV6_V6ONLY on fails on address %s: %m", 2765 stoa(addr)); 2766 #endif /* IPV6_V6ONLY */ 2767 #if defined(IPV6_BINDV6ONLY) 2768 if (setsockopt(fd, IPPROTO_IPV6, IPV6_BINDV6ONLY, 2769 (char*)&on, sizeof(on))) 2770 msyslog(LOG_ERR, 2771 "setsockopt IPV6_BINDV6ONLY on fails on address %s: %m", 2772 stoa(addr)); 2773 #endif /* IPV6_BINDV6ONLY */ 2774 } 2775 2776 #ifdef OS_NEEDS_REUSEADDR_FOR_IFADDRBIND 2777 /* 2778 * some OSes don't allow binding to more specific 2779 * addresses if a wildcard address already bound 2780 * to the port and SO_REUSEADDR is not set 2781 */ 2782 if (!is_wildcard_addr(addr)) 2783 set_wildcard_reuse(AF(addr), 1); 2784 #endif 2785 2786 /* 2787 * bind the local address. 2788 */ 2789 errval = bind(fd, &addr->sa, SOCKLEN(addr)); 2790 2791 #ifdef OS_NEEDS_REUSEADDR_FOR_IFADDRBIND 2792 if (!is_wildcard_addr(addr)) 2793 set_wildcard_reuse(AF(addr), 0); 2794 #endif 2795 2796 if (errval < 0) { 2797 /* 2798 * Don't log this under all conditions 2799 */ 2800 if (turn_off_reuse == 0 2801 #ifdef DEBUG 2802 || debug > 1 2803 #endif 2804 ) { 2805 if (SCOPE(addr)) 2806 snprintf(scopetext, sizeof(scopetext), 2807 "%%%d", SCOPE(addr)); 2808 else 2809 scopetext[0] = 0; 2810 2811 msyslog(LOG_ERR, 2812 "bind(%d) AF_INET%s %s%s#%d%s flags 0x%x failed: %m", 2813 fd, IS_IPV6(addr) ? "6" : "", 2814 stoa(addr), scopetext, SRCPORT(addr), 2815 IS_MCAST(addr) ? " (multicast)" : "", 2816 interf->flags); 2817 } 2818 2819 closesocket(fd); 2820 2821 return INVALID_SOCKET; 2822 } 2823 2824 #ifdef HAVE_TIMESTAMP 2825 { 2826 if (setsockopt(fd, SOL_SOCKET, SO_TIMESTAMP, 2827 (char*)&on, sizeof(on))) 2828 msyslog(LOG_DEBUG, 2829 "setsockopt SO_TIMESTAMP on fails on address %s: %m", 2830 stoa(addr)); 2831 else 2832 DPRINTF(4, ("setsockopt SO_TIMESTAMP enabled on fd %d address %s\n", 2833 fd, stoa(addr))); 2834 } 2835 #endif 2836 DPRINTF(4, ("bind(%d) AF_INET%s, addr %s%%%d#%d, flags 0x%x\n", 2837 fd, IS_IPV6(addr) ? "6" : "", stoa(addr), 2838 SCOPE(addr), SRCPORT(addr), interf->flags)); 2839 2840 init_nonblocking_io(fd); 2841 2842 #ifdef HAVE_SIGNALED_IO 2843 init_socket_sig(fd); 2844 #endif /* not HAVE_SIGNALED_IO */ 2845 2846 add_fd_to_list(fd, FD_TYPE_SOCKET); 2847 2848 #if !defined(SYS_WINNT) && !defined(VMS) 2849 DPRINTF(4, ("flags for fd %d: 0x%x\n", fd, 2850 fcntl(fd, F_GETFL, 0))); 2851 #endif /* SYS_WINNT || VMS */ 2852 2853 #if defined (HAVE_IO_COMPLETION_PORT) 2854 /* 2855 * Add the socket to the completion port 2856 */ 2857 if (io_completion_port_add_socket(fd, interf)) { 2858 msyslog(LOG_ERR, "unable to set up io completion port - EXITING"); 2859 exit(1); 2860 } 2861 #endif 2862 return fd; 2863 } 2864 2865 /* XXX ELIMINATE sendpkt similar in ntpq.c, ntpdc.c, ntp_io.c, ntptrace.c */ 2866 /* 2867 * sendpkt - send a packet to the specified destination. Maintain a 2868 * send error cache so that only the first consecutive error for a 2869 * destination is logged. 2870 */ 2871 void 2872 sendpkt( 2873 sockaddr_u *dest, 2874 struct interface *inter, 2875 int ttl, 2876 struct pkt *pkt, 2877 int len 2878 ) 2879 { 2880 int cc; 2881 2882 if (NULL == inter) { 2883 /* 2884 * unbound peer - drop request and wait for better 2885 * network conditions 2886 */ 2887 DPRINTF(2, ("%ssendpkt(dst=%s, ttl=%d, len=%d): no interface - IGNORED\n", 2888 (ttl > 0) ? "\tMCAST\t***** " : "", 2889 stoa(dest), ttl, len)); 2890 return; 2891 } 2892 2893 DPRINTF(2, ("%ssendpkt(%d, dst=%s, src=%s, ttl=%d, len=%d)\n", 2894 (ttl > 0) ? "\tMCAST\t***** " : "", 2895 inter->fd, stoa(dest), stoa(&inter->sin), 2896 ttl, len)); 2897 2898 #ifdef MCAST 2899 /* 2900 * for the moment we use the bcast option to set multicast ttl 2901 */ 2902 if (ttl > 0 && ttl != inter->last_ttl) { 2903 /* 2904 * set the multicast ttl for outgoing packets 2905 */ 2906 int rtc; 2907 u_char cttl; 2908 #ifdef INCLUDE_IPV6_SUPPORT 2909 u_int uttl; 2910 #endif 2911 2912 switch (AF(&inter->sin)) { 2913 2914 case AF_INET : 2915 cttl = (u_char)ttl; 2916 rtc = setsockopt(inter->fd, IPPROTO_IP, 2917 IP_MULTICAST_TTL, 2918 (void *)&cttl, sizeof(cttl)); 2919 break; 2920 2921 #ifdef INCLUDE_IPV6_SUPPORT 2922 case AF_INET6 : 2923 uttl = (u_int)ttl; 2924 rtc = setsockopt(inter->fd, IPPROTO_IPV6, 2925 IPV6_MULTICAST_HOPS, 2926 (void *)&uttl, sizeof(uttl)); 2927 break; 2928 #endif /* INCLUDE_IPV6_SUPPORT */ 2929 2930 default: /* just NOP if not supported */ 2931 DPRINTF(1, ("sendpkt unknown AF %d", 2932 AF(&inter->sin))); 2933 rtc = 0; 2934 } 2935 2936 if (!rtc) 2937 inter->last_ttl = ttl; 2938 else 2939 msyslog(LOG_ERR, 2940 "setsockopt IP_MULTICAST_TTL/IPV6_MULTICAST_HOPS fails on address %s: %m", 2941 stoa(&inter->sin)); 2942 } 2943 2944 #endif /* MCAST */ 2945 2946 #if defined(HAVE_IO_COMPLETION_PORT) 2947 cc = io_completion_port_sendto(inter, pkt, len, dest); 2948 if (cc != ERROR_SUCCESS) { 2949 #else 2950 #ifdef SIM 2951 cc = simulate_server(dest, inter, pkt); 2952 #else /* SIM */ 2953 cc = sendto(inter->fd, (char *)pkt, (unsigned int)len, 0, 2954 (struct sockaddr *)dest, SOCKLEN(dest)); 2955 #endif /* SIM */ 2956 if (cc == -1) { 2957 #endif 2958 inter->notsent++; 2959 packets_notsent++; 2960 } else { 2961 inter->sent++; 2962 packets_sent++; 2963 } 2964 } 2965 2966 2967 #if !defined(HAVE_IO_COMPLETION_PORT) 2968 /* 2969 * fdbits - generate ascii representation of fd_set (FAU debug support) 2970 * HFDF format - highest fd first. 2971 */ 2972 static char * 2973 fdbits( 2974 int count, 2975 fd_set *set 2976 ) 2977 { 2978 static char buffer[256]; 2979 char * buf = buffer; 2980 2981 count = min(count, 255); 2982 2983 while (count >= 0) { 2984 *buf++ = FD_ISSET(count, set) ? '#' : '-'; 2985 count--; 2986 } 2987 *buf = '\0'; 2988 2989 return buffer; 2990 } 2991 2992 /* 2993 * Routine to read the refclock packets for a specific interface 2994 * Return the number of bytes read. That way we know if we should 2995 * read it again or go on to the next one if no bytes returned 2996 */ 2997 static inline int 2998 read_refclock_packet(SOCKET fd, struct refclockio *rp, l_fp ts) 2999 { 3000 int i; 3001 int buflen; 3002 register struct recvbuf *rb; 3003 3004 rb = get_free_recv_buffer(); 3005 3006 if (NULL == rb) { 3007 /* 3008 * No buffer space available - just drop the packet 3009 */ 3010 char buf[RX_BUFF_SIZE]; 3011 3012 buflen = read(fd, buf, sizeof buf); 3013 packets_dropped++; 3014 return (buflen); 3015 } 3016 3017 i = (rp->datalen == 0 3018 || rp->datalen > (int)sizeof(rb->recv_space)) 3019 ? (int)sizeof(rb->recv_space) 3020 : rp->datalen; 3021 buflen = read(fd, (char *)&rb->recv_space, (unsigned)i); 3022 3023 if (buflen < 0) { 3024 if (errno != EINTR && errno != EAGAIN) 3025 msyslog(LOG_ERR, "clock read fd %d: %m", fd); 3026 freerecvbuf(rb); 3027 return (buflen); 3028 } 3029 3030 /* 3031 * Got one. Mark how and when it got here, 3032 * put it on the full list and do bookkeeping. 3033 */ 3034 rb->recv_length = buflen; 3035 rb->recv_srcclock = rp->srcclock; 3036 rb->dstadr = 0; 3037 rb->fd = fd; 3038 rb->recv_time = ts; 3039 rb->receiver = rp->clock_recv; 3040 3041 if (rp->io_input) { 3042 /* 3043 * have direct input routine for refclocks 3044 */ 3045 if (rp->io_input(rb) == 0) { 3046 /* 3047 * data was consumed - nothing to pass up 3048 * into block input machine 3049 */ 3050 freerecvbuf(rb); 3051 return (buflen); 3052 } 3053 } 3054 3055 add_full_recv_buffer(rb); 3056 3057 rp->recvcount++; 3058 packets_received++; 3059 return (buflen); 3060 } 3061 3062 3063 #ifdef HAVE_TIMESTAMP 3064 /* 3065 * extract timestamps from control message buffer 3066 */ 3067 static l_fp 3068 fetch_timestamp( 3069 struct recvbuf * rb, 3070 struct msghdr * msghdr, 3071 l_fp ts 3072 ) 3073 { 3074 #ifdef USE_TIMESTAMP_CMSG 3075 struct cmsghdr *cmsghdr; 3076 3077 cmsghdr = CMSG_FIRSTHDR(msghdr); 3078 while (cmsghdr != NULL) { 3079 switch (cmsghdr->cmsg_type) 3080 { 3081 case SCM_TIMESTAMP: 3082 { 3083 struct timeval *tvp; 3084 double dtemp; 3085 l_fp nts; 3086 3087 tvp = (struct timeval *)CMSG_DATA(cmsghdr); 3088 DPRINTF(4, ("fetch_timestamp: system network time stamp: %lld.%06ld\n", 3089 (long long)tvp->tv_sec, (long)tvp->tv_usec)); 3090 nts.l_i = tvp->tv_sec + JAN_1970; 3091 dtemp = (tvp->tv_usec 3092 + (ntp_random() * 2. / FRAC)) / 1e6; 3093 nts.l_uf = (u_int32)(dtemp * FRAC); 3094 #ifdef DEBUG_TIMING 3095 { 3096 l_fp dts; 3097 3098 dts = ts; 3099 L_SUB(&dts, &nts); 3100 collect_timing(rb, 3101 "input processing delay", 3102 1, &dts); 3103 DPRINTF(4, ("fetch_timestamp: timestamp delta: %s (incl. prec fuzz)\n", 3104 lfptoa(&dts, 9))); 3105 } 3106 #endif 3107 ts = nts; /* network time stamp */ 3108 break; 3109 } 3110 default: 3111 DPRINTF(4, ("fetch_timestamp: skipping control message 0x%x\n", 3112 cmsghdr->cmsg_type)); 3113 } 3114 cmsghdr = CMSG_NXTHDR(msghdr, cmsghdr); 3115 } 3116 #endif 3117 return ts; 3118 } 3119 #endif 3120 3121 3122 /* 3123 * Routine to read the network NTP packets for a specific interface 3124 * Return the number of bytes read. That way we know if we should 3125 * read it again or go on to the next one if no bytes returned 3126 */ 3127 static inline int 3128 read_network_packet( 3129 SOCKET fd, 3130 struct interface * itf, 3131 l_fp ts 3132 ) 3133 { 3134 GETSOCKNAME_SOCKLEN_TYPE fromlen; 3135 int buflen; 3136 register struct recvbuf *rb; 3137 #ifdef HAVE_TIMESTAMP 3138 struct msghdr msghdr; 3139 struct iovec iovec; 3140 char control[TIMESTAMP_CTLMSGBUF_SIZE]; 3141 #endif 3142 3143 /* 3144 * Get a buffer and read the frame. If we 3145 * haven't got a buffer, or this is received 3146 * on a disallowed socket, just dump the 3147 * packet. 3148 */ 3149 3150 rb = get_free_recv_buffer(); 3151 if (NULL == rb || itf->ignore_packets) { 3152 char buf[RX_BUFF_SIZE]; 3153 sockaddr_u from; 3154 3155 if (rb != NULL) 3156 freerecvbuf(rb); 3157 3158 fromlen = sizeof(from); 3159 buflen = recvfrom(fd, buf, sizeof(buf), 0, 3160 &from.sa, &fromlen); 3161 DPRINTF(4, ("%s on (%lu) fd=%d from %s\n", 3162 (itf->ignore_packets) 3163 ? "ignore" 3164 : "drop", 3165 free_recvbuffs(), fd, stoa(&from))); 3166 if (itf->ignore_packets) 3167 packets_ignored++; 3168 else 3169 packets_dropped++; 3170 return (buflen); 3171 } 3172 3173 fromlen = sizeof(rb->recv_srcadr); 3174 3175 #ifndef HAVE_TIMESTAMP 3176 rb->recv_length = recvfrom(fd, (char *)&rb->recv_space, 3177 sizeof(rb->recv_space), 0, 3178 &rb->recv_srcadr.sa, &fromlen); 3179 #else 3180 iovec.iov_base = &rb->recv_space; 3181 iovec.iov_len = sizeof(rb->recv_space); 3182 msghdr.msg_name = &rb->recv_srcadr; 3183 msghdr.msg_namelen = fromlen; 3184 msghdr.msg_iov = &iovec; 3185 msghdr.msg_iovlen = 1; 3186 msghdr.msg_control = (void *)&control; 3187 msghdr.msg_controllen = sizeof(control); 3188 msghdr.msg_flags = 0; 3189 rb->recv_length = recvmsg(fd, &msghdr, 0); 3190 #endif 3191 3192 buflen = rb->recv_length; 3193 3194 if (buflen == 0 || (buflen == -1 && 3195 (EWOULDBLOCK == errno 3196 #ifdef EAGAIN 3197 || EAGAIN == errno 3198 #endif 3199 ))) { 3200 freerecvbuf(rb); 3201 return (buflen); 3202 } else if (buflen < 0) { 3203 msyslog(LOG_ERR, "recvfrom(%s) fd=%d: %m", 3204 stoa(&rb->recv_srcadr), fd); 3205 DPRINTF(5, ("read_network_packet: fd=%d dropped (bad recvfrom)\n", 3206 fd)); 3207 freerecvbuf(rb); 3208 return (buflen); 3209 } 3210 3211 DPRINTF(3, ("read_network_packet: fd=%d length %d from %s\n", 3212 fd, buflen, stoa(&rb->recv_srcadr))); 3213 3214 /* 3215 * Got one. Mark how and when it got here, 3216 * put it on the full list and do bookkeeping. 3217 */ 3218 rb->dstadr = itf; 3219 rb->fd = fd; 3220 #ifdef HAVE_TIMESTAMP 3221 /* pick up a network time stamp if possible */ 3222 ts = fetch_timestamp(rb, &msghdr, ts); 3223 #endif 3224 rb->recv_time = ts; 3225 rb->receiver = receive; 3226 3227 add_full_recv_buffer(rb); 3228 3229 itf->received++; 3230 packets_received++; 3231 return (buflen); 3232 } 3233 3234 3235 /* 3236 * input_handler - receive packets asynchronously 3237 */ 3238 void 3239 input_handler( 3240 l_fp *cts 3241 ) 3242 { 3243 int buflen; 3244 int n; 3245 int doing; 3246 SOCKET fd; 3247 struct timeval tvzero; 3248 l_fp ts; /* Timestamp at BOselect() gob */ 3249 #ifdef DEBUG_TIMING 3250 l_fp ts_e; /* Timestamp at EOselect() gob */ 3251 #endif 3252 fd_set fds; 3253 int select_count = 0; 3254 struct interface *interface; 3255 #if defined(HAS_ROUTING_SOCKET) 3256 struct asyncio_reader *asyncio_reader; 3257 #endif 3258 3259 handler_calls++; 3260 3261 /* 3262 * If we have something to do, freeze a timestamp. 3263 * See below for the other cases (nothing left to do or error) 3264 */ 3265 ts = *cts; 3266 3267 /* 3268 * Do a poll to see who has data 3269 */ 3270 3271 fds = activefds; 3272 tvzero.tv_sec = tvzero.tv_usec = 0; 3273 3274 n = select(maxactivefd + 1, &fds, (fd_set *)0, (fd_set *)0, 3275 &tvzero); 3276 3277 /* 3278 * If there are no packets waiting just return 3279 */ 3280 if (n < 0) { 3281 int err = errno; 3282 /* 3283 * extended FAU debugging output 3284 */ 3285 if (err != EINTR) 3286 msyslog(LOG_ERR, 3287 "select(%d, %s, 0L, 0L, &0.0) error: %m", 3288 maxactivefd + 1, 3289 fdbits(maxactivefd, &activefds)); 3290 if (err == EBADF) { 3291 int j, b; 3292 fds = activefds; 3293 for (j = 0; j <= maxactivefd; j++) 3294 if ((FD_ISSET(j, &fds) 3295 && (read(j, &b, 0) == -1))) 3296 msyslog(LOG_ERR, 3297 "Bad file descriptor %d", 3298 j); 3299 } 3300 return; 3301 } 3302 else if (n == 0) 3303 return; 3304 3305 ++handler_pkts; 3306 3307 #ifdef REFCLOCK 3308 /* 3309 * Check out the reference clocks first, if any 3310 */ 3311 3312 if (refio != NULL) { 3313 register struct refclockio *rp; 3314 3315 for (rp = refio; rp != NULL; rp = rp->next) { 3316 fd = rp->fd; 3317 3318 if (FD_ISSET(fd, &fds)) 3319 do { 3320 ++select_count; 3321 buflen = read_refclock_packet( 3322 fd, rp, ts); 3323 } while (buflen > 0); 3324 } 3325 } 3326 #endif /* REFCLOCK */ 3327 3328 /* 3329 * Loop through the interfaces looking for data to read. 3330 */ 3331 for (interface = inter_list; 3332 interface != NULL; 3333 interface = interface->link) { 3334 3335 for (doing = 0; (doing < 2); doing++) { 3336 if (!doing) 3337 fd = interface->fd; 3338 else { 3339 if (!(interface->flags & INT_BCASTOPEN)) 3340 break; 3341 fd = interface->bfd; 3342 } 3343 if (fd < 0) 3344 continue; 3345 if (FD_ISSET(fd, &fds)) 3346 do { 3347 ++select_count; 3348 buflen = read_network_packet( 3349 fd, interface, 3350 ts); 3351 } while (buflen > 0); 3352 /* Check more interfaces */ 3353 } 3354 } 3355 3356 #ifdef HAS_ROUTING_SOCKET 3357 /* 3358 * scan list of asyncio readers - currently only used for routing sockets 3359 */ 3360 asyncio_reader = asyncio_reader_list; 3361 3362 while (asyncio_reader != NULL) { 3363 struct asyncio_reader *next = asyncio_reader->link; 3364 3365 if (FD_ISSET(asyncio_reader->fd, &fds)) { 3366 ++select_count; 3367 (asyncio_reader->receiver)(asyncio_reader); 3368 } 3369 3370 asyncio_reader = next; 3371 } 3372 #endif /* HAS_ROUTING_SOCKET */ 3373 3374 /* 3375 * Done everything from that select. 3376 */ 3377 3378 /* 3379 * If nothing to do, just return. 3380 * If an error occurred, complain and return. 3381 */ 3382 if (select_count == 0) { /* We really had nothing to do */ 3383 #ifdef DEBUG 3384 if (debug) 3385 msyslog(LOG_DEBUG, "input_handler: select() returned 0"); 3386 #endif 3387 return; 3388 } 3389 /* We've done our work */ 3390 #ifdef DEBUG_TIMING 3391 get_systime(&ts_e); 3392 /* 3393 * (ts_e - ts) is the amount of time we spent 3394 * processing this gob of file descriptors. Log 3395 * it. 3396 */ 3397 L_SUB(&ts_e, &ts); 3398 collect_timing(NULL, "input handler", 1, &ts_e); 3399 if (debug > 3) 3400 msyslog(LOG_DEBUG, 3401 "input_handler: Processed a gob of fd's in %s msec", 3402 lfptoms(&ts_e, 6)); 3403 #endif 3404 /* just bail. */ 3405 return; 3406 } 3407 #endif 3408 3409 /* 3410 * findinterface - find local interface corresponding to address 3411 */ 3412 struct interface * 3413 findinterface( 3414 sockaddr_u *addr 3415 ) 3416 { 3417 struct interface *iface; 3418 3419 iface = findlocalinterface(addr, INT_WILDCARD, 0); 3420 3421 if (NULL == iface) { 3422 DPRINTF(4, ("Found no interface for address %s - returning wildcard\n", 3423 stoa(addr))); 3424 3425 iface = ANY_INTERFACE_CHOOSE(addr); 3426 } else 3427 DPRINTF(4, ("Found interface #%d %s for address %s\n", 3428 iface->ifnum, iface->name, stoa(addr))); 3429 3430 return iface; 3431 } 3432 3433 /* 3434 * findlocalinterface - find local interface corresponding to addr, 3435 * which does not have any of flags set. If bast is nonzero, addr is 3436 * a broadcast address. 3437 * 3438 * This code attempts to find the local sending address for an outgoing 3439 * address by connecting a new socket to destinationaddress:NTP_PORT 3440 * and reading the sockname of the resulting connect. 3441 * the complicated sequence simulates the routing table lookup 3442 * for to first hop without duplicating any of the routing logic into 3443 * ntpd. preferably we would have used an API call - but its not there - 3444 * so this is the best we can do here short of duplicating to entire routing 3445 * logic in ntpd which would be a silly and really unportable thing to do. 3446 * 3447 */ 3448 static struct interface * 3449 findlocalinterface( 3450 sockaddr_u * addr, 3451 int flags, 3452 int bcast 3453 ) 3454 { 3455 GETSOCKNAME_SOCKLEN_TYPE sockaddrlen; 3456 struct interface * iface; 3457 sockaddr_u saddr; 3458 SOCKET s; 3459 int rtn; 3460 int on; 3461 3462 DPRINTF(4, ("Finding interface for addr %s in list of addresses\n", 3463 stoa(addr))); 3464 3465 s = socket(AF(addr), SOCK_DGRAM, 0); 3466 if (INVALID_SOCKET == s) 3467 return NULL; 3468 3469 /* 3470 * If we are looking for broadcast interface we need to set this 3471 * socket to allow broadcast 3472 */ 3473 if (bcast) { 3474 on = 1; 3475 setsockopt(s, SOL_SOCKET, SO_BROADCAST, 3476 (char *)&on, sizeof(on)); 3477 } 3478 3479 rtn = connect(s, &addr->sa, SOCKLEN(addr)); 3480 if (SOCKET_ERROR == rtn) { 3481 closesocket(s); 3482 return NULL; 3483 } 3484 3485 sockaddrlen = sizeof(saddr); 3486 rtn = getsockname(s, &saddr.sa, &sockaddrlen); 3487 closesocket(s); 3488 3489 if (SOCKET_ERROR == rtn) 3490 return NULL; 3491 3492 DPRINTF(4, ("findlocalinterface: kernel maps %s to %s\n", 3493 stoa(addr), stoa(&saddr))); 3494 3495 iface = getinterface(&saddr, flags); 3496 3497 /* 3498 * if we didn't find an exact match on saddr check for an 3499 * interface on the same subnet as saddr. This handles the 3500 * case of the address suggested by the kernel being 3501 * excluded by the user's -I and -L options to ntpd, when 3502 * another address is enabled on the same subnet. 3503 * See http://bugs.ntp.org/1184 for more detail. 3504 */ 3505 if (NULL == iface || iface->ignore_packets) 3506 iface = getsamenetinterface(&saddr, flags); 3507 3508 /* Don't use an interface which will ignore replies */ 3509 if (iface != NULL && iface->ignore_packets) 3510 iface = NULL; 3511 3512 return iface; 3513 } 3514 3515 3516 /* 3517 * fetch an interface structure the matches the 3518 * address and has the given flags NOT set 3519 */ 3520 static struct interface * 3521 getinterface( 3522 sockaddr_u * addr, 3523 int flags 3524 ) 3525 { 3526 struct interface *iface; 3527 3528 iface = find_addr_in_list(addr); 3529 3530 if (iface != NULL && (iface->flags & flags)) 3531 iface = NULL; 3532 3533 return iface; 3534 } 3535 3536 3537 /* 3538 * fetch an interface structure with a local address on the same subnet 3539 * as addr which has the given flags NOT set 3540 */ 3541 static struct interface * 3542 getsamenetinterface( 3543 sockaddr_u * addr, 3544 int flags 3545 ) 3546 { 3547 struct interface *iface; 3548 3549 iface = find_samenet_addr_in_list(addr); 3550 3551 if (iface != NULL && (iface->flags & flags)) 3552 iface = NULL; 3553 3554 return iface; 3555 } 3556 3557 3558 /* 3559 * findlocalcastinterface - find local *cast interface for addr 3560 */ 3561 static struct interface * 3562 findlocalcastinterface( 3563 sockaddr_u * addr 3564 ) 3565 { 3566 struct interface * iface; 3567 struct interface * nif; 3568 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT 3569 isc_boolean_t want_linklocal; 3570 #endif 3571 3572 NTP_REQUIRE(addr_ismulticast(addr)); 3573 3574 /* 3575 * see how kernel maps the mcast address 3576 */ 3577 nif = findlocalinterface(addr, 0, 0); 3578 3579 if (nif != NULL && !nif->ignore_packets) { 3580 DPRINTF(2, ("findlocalcastinterface: kernel recommends interface #%d %s for %s\n", 3581 nif->ifnum, nif->name, stoa(addr))); 3582 return nif; 3583 } 3584 3585 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT 3586 want_linklocal = (IN6_IS_ADDR_MC_LINKLOCAL(PSOCK_ADDR6(addr)) 3587 || IN6_IS_ADDR_MC_SITELOCAL(PSOCK_ADDR6(addr))); 3588 #endif 3589 3590 for (iface = inter_list; 3591 iface != NULL; 3592 iface = iface->link) 3593 { 3594 /* use only allowed addresses */ 3595 if (iface->ignore_packets) 3596 continue; 3597 3598 /* Skip the loopback and wildcard addresses */ 3599 if (iface->flags & (INT_LOOPBACK | INT_WILDCARD)) 3600 continue; 3601 3602 /* Skip if different family */ 3603 if (AF(&iface->sin) != AF(addr)) 3604 continue; 3605 3606 /* Is it multicast capable? */ 3607 if (!(iface->flags & INT_MULTICAST)) 3608 continue; 3609 3610 #ifdef INCLUDE_IPV6_MULTICAST_SUPPORT 3611 if (want_linklocal && IS_IPV6(&iface->sin) && 3612 IN6_IS_ADDR_LINKLOCAL(PSOCK_ADDR6(&iface->sin))) { 3613 nif = iface; 3614 break; 3615 } 3616 /* If we want a linklocal address, skip */ 3617 if (want_linklocal) 3618 continue; 3619 #endif 3620 nif = iface; 3621 break; 3622 } /* for loop over interfaces */ 3623 3624 if (nif != NULL) 3625 DPRINTF(3, ("findlocalcastinterface: found interface #%d %s for %s\n", 3626 nif->ifnum, nif->name, stoa(addr))); 3627 else 3628 DPRINTF(3, ("findlocalcastinterface: no interface found for %s\n", 3629 stoa(addr))); 3630 return nif; 3631 } 3632 3633 3634 /* 3635 * findbcastinter - find broadcast interface corresponding to address 3636 */ 3637 struct interface * 3638 findbcastinter( 3639 sockaddr_u *addr 3640 ) 3641 { 3642 #if !defined(MPE) && (defined(SIOCGIFCONF) || defined(SYS_WINNT)) 3643 struct interface *iface; 3644 3645 3646 DPRINTF(4, ("Finding broadcast/multicast interface for addr %s in list of addresses\n", 3647 stoa(addr))); 3648 3649 iface = findlocalinterface(addr, INT_LOOPBACK | INT_WILDCARD, 3650 1); 3651 if (iface != NULL) { 3652 DPRINTF(4, ("Easily found bcast-/mcast- interface index #%d %s\n", 3653 iface->ifnum, iface->name)); 3654 return iface; 3655 } 3656 3657 /* 3658 * plan B - try to find something reasonable in our lists in 3659 * case kernel lookup doesn't help 3660 */ 3661 for (iface = inter_list; 3662 iface != NULL; 3663 iface = iface->link) 3664 { 3665 if (iface->flags & INT_WILDCARD) 3666 continue; 3667 3668 /* Don't bother with ignored interfaces */ 3669 if (iface->ignore_packets) 3670 continue; 3671 3672 /* 3673 * First look if this is the correct family 3674 */ 3675 if(AF(&iface->sin) != AF(addr)) 3676 continue; 3677 3678 /* Skip the loopback addresses */ 3679 if (iface->flags & INT_LOOPBACK) 3680 continue; 3681 3682 /* 3683 * If we are looking to match a multicast address and 3684 * this interface is one... 3685 */ 3686 if (addr_ismulticast(addr) 3687 && (iface->flags & INT_MULTICAST)) { 3688 #ifdef INCLUDE_IPV6_SUPPORT 3689 /* 3690 * ...it is the winner unless we're looking for 3691 * an interface to use for link-local multicast 3692 * and its address is not link-local. 3693 */ 3694 if (IS_IPV6(addr) 3695 && IN6_IS_ADDR_MC_LINKLOCAL(PSOCK_ADDR6(addr)) 3696 && !IN6_IS_ADDR_LINKLOCAL(PSOCK_ADDR6(&iface->sin))) 3697 continue; 3698 #endif 3699 break; 3700 } 3701 3702 /* 3703 * We match only those interfaces marked as 3704 * broadcastable and either the explicit broadcast 3705 * address or the network portion of the IP address. 3706 * Sloppy. 3707 */ 3708 if (IS_IPV4(addr)) { 3709 if (SOCK_EQ(&iface->bcast, addr)) 3710 break; 3711 3712 if ((NSRCADR(&iface->sin) & NSRCADR(&iface->mask)) 3713 == (NSRCADR(addr) & NSRCADR(&iface->mask))) 3714 break; 3715 } 3716 #ifdef INCLUDE_IPV6_SUPPORT 3717 else if(IS_IPV6(addr)) { 3718 if (SOCK_EQ(&iface->bcast, addr)) 3719 break; 3720 3721 if (SOCK_EQ(netof(&iface->sin), netof(addr))) 3722 break; 3723 } 3724 #endif 3725 } 3726 #endif /* SIOCGIFCONF */ 3727 if (NULL == iface) { 3728 DPRINTF(4, ("No bcast interface found for %s\n", 3729 stoa(addr))); 3730 iface = ANY_INTERFACE_CHOOSE(addr); 3731 } else 3732 DPRINTF(4, ("Found bcast-/mcast- interface index #%d %s\n", 3733 iface->ifnum, iface->name)); 3734 return iface; 3735 } 3736 3737 3738 /* 3739 * io_clr_stats - clear I/O module statistics 3740 */ 3741 void 3742 io_clr_stats(void) 3743 { 3744 packets_dropped = 0; 3745 packets_ignored = 0; 3746 packets_received = 0; 3747 packets_sent = 0; 3748 packets_notsent = 0; 3749 3750 handler_calls = 0; 3751 handler_pkts = 0; 3752 io_timereset = current_time; 3753 } 3754 3755 3756 #ifdef REFCLOCK 3757 /* 3758 * io_addclock - add a reference clock to the list and arrange that we 3759 * get SIGIO interrupts from it. 3760 */ 3761 int 3762 io_addclock( 3763 struct refclockio *rio 3764 ) 3765 { 3766 BLOCKIO(); 3767 3768 /* 3769 * Stuff the I/O structure in the list and mark the descriptor 3770 * in use. There is a harmless (I hope) race condition here. 3771 */ 3772 rio->next = refio; 3773 3774 # ifdef HAVE_SIGNALED_IO 3775 if (init_clock_sig(rio)) { 3776 UNBLOCKIO(); 3777 return 0; 3778 } 3779 # elif defined(HAVE_IO_COMPLETION_PORT) 3780 if (io_completion_port_add_clock_io(rio)) { 3781 UNBLOCKIO(); 3782 return 0; 3783 } 3784 # endif 3785 3786 /* 3787 * enqueue 3788 */ 3789 refio = rio; 3790 3791 /* 3792 * register fd 3793 */ 3794 add_fd_to_list(rio->fd, FD_TYPE_FILE); 3795 3796 UNBLOCKIO(); 3797 return 1; 3798 } 3799 3800 /* 3801 * io_closeclock - close the clock in the I/O structure given 3802 */ 3803 void 3804 io_closeclock( 3805 struct refclockio *rio 3806 ) 3807 { 3808 register struct refclockio *rp; 3809 3810 BLOCKIO(); 3811 3812 /* 3813 * Remove structure from the list 3814 */ 3815 if (refio == rio) 3816 refio = rio->next; 3817 else { 3818 for (rp = refio; rp != NULL; rp = rp->next) 3819 if (rp->next == rio) { 3820 rp->next = rio->next; 3821 break; 3822 } 3823 3824 if (NULL == rp) { 3825 UNBLOCKIO(); 3826 return; 3827 } 3828 } 3829 3830 /* 3831 * Close the descriptor. 3832 */ 3833 close_and_delete_fd_from_list(rio->fd); 3834 UNBLOCKIO(); 3835 } 3836 #endif /* REFCLOCK */ 3837 3838 /* 3839 * On NT a SOCKET is an unsigned int so we cannot possibly keep it in 3840 * an array. So we use one of the ISC_LIST functions to hold the 3841 * socket value and use that when we want to enumerate it. 3842 * 3843 * This routine is called by the forked intres child process to close 3844 * all open sockets. On Windows there's no need as intres runs in 3845 * the same process as a thread. 3846 */ 3847 #ifndef SYS_WINNT 3848 void 3849 kill_asyncio(int startfd) 3850 { 3851 BLOCKIO(); 3852 3853 /* 3854 * In the child process we do not maintain activefds and 3855 * maxactivefd. Zeroing maxactivefd disables code which 3856 * maintains it in close_and_delete_fd_from_list(). 3857 */ 3858 maxactivefd = 0; 3859 3860 while (fd_list != NULL) 3861 close_and_delete_fd_from_list(fd_list->fd); 3862 3863 UNBLOCKIO(); 3864 } 3865 #endif /* !SYS_WINNT */ 3866 3867 /* 3868 * Add and delete functions for the list of open sockets 3869 */ 3870 static void 3871 add_fd_to_list( 3872 SOCKET fd, 3873 enum desc_type type 3874 ) 3875 { 3876 vsock_t *lsock = emalloc(sizeof(*lsock)); 3877 3878 lsock->fd = fd; 3879 lsock->type = type; 3880 3881 LINK_SLIST(fd_list, lsock, link); 3882 /* 3883 * I/O Completion Ports don't care about the select and FD_SET 3884 */ 3885 #ifndef HAVE_IO_COMPLETION_PORT 3886 if (fd < 0 || fd >= FD_SETSIZE) { 3887 msyslog(LOG_ERR, 3888 "Too many sockets in use, FD_SETSIZE %d exceeded", 3889 FD_SETSIZE); 3890 exit(1); 3891 } 3892 /* 3893 * keep activefds in sync 3894 */ 3895 maxactivefd = max(fd, maxactivefd); 3896 3897 FD_SET(fd, &activefds); 3898 #endif 3899 } 3900 3901 static void 3902 close_and_delete_fd_from_list( 3903 SOCKET fd 3904 ) 3905 { 3906 vsock_t *lsock; 3907 3908 UNLINK_EXPR_SLIST(lsock, fd_list, fd == 3909 UNLINK_EXPR_SLIST_CURRENT()->fd, link, vsock_t); 3910 3911 if (lsock != NULL) { 3912 switch (lsock->type) { 3913 case FD_TYPE_SOCKET: 3914 closesocket(lsock->fd); 3915 break; 3916 3917 case FD_TYPE_FILE: 3918 close(lsock->fd); 3919 break; 3920 3921 default: 3922 msyslog(LOG_ERR, 3923 "internal error - illegal descriptor type %d - EXITING", 3924 (int)lsock->type); 3925 exit(1); 3926 } 3927 3928 free(lsock); 3929 /* 3930 * I/O Completion Ports don't care about select and fd_set 3931 */ 3932 #ifndef HAVE_IO_COMPLETION_PORT 3933 /* 3934 * remove from activefds 3935 */ 3936 FD_CLR(fd, &activefds); 3937 3938 if (fd == maxactivefd && maxactivefd) { 3939 int i; 3940 NTP_INSIST(maxactivefd - 1 < FD_SETSIZE); 3941 for (i = maxactivefd - 1; i >= 0; i--) 3942 if (FD_ISSET(i, &activefds)) { 3943 maxactivefd = i; 3944 break; 3945 } 3946 NTP_INSIST(fd != maxactivefd); 3947 } 3948 #endif 3949 } 3950 } 3951 3952 static void 3953 add_addr_to_list( 3954 sockaddr_u *addr, 3955 struct interface *interface 3956 ) 3957 { 3958 remaddr_t *laddr; 3959 3960 #ifdef DEBUG 3961 if (find_addr_in_list(addr) == NULL) { 3962 #endif 3963 /* not there yet - add to list */ 3964 laddr = emalloc(sizeof(*laddr)); 3965 memcpy(&laddr->addr, addr, sizeof(laddr->addr)); 3966 laddr->interface = interface; 3967 3968 LINK_SLIST(remoteaddr_list, laddr, link); 3969 3970 DPRINTF(4, ("Added addr %s to list of addresses\n", 3971 stoa(addr))); 3972 #ifdef DEBUG 3973 } else 3974 DPRINTF(4, ("WARNING: Attempt to add duplicate addr %s to address list\n", 3975 stoa(addr))); 3976 #endif 3977 } 3978 3979 3980 static void 3981 delete_addr_from_list( 3982 sockaddr_u *addr 3983 ) 3984 { 3985 remaddr_t *unlinked; 3986 3987 UNLINK_EXPR_SLIST(unlinked, remoteaddr_list, SOCK_EQ(addr, 3988 &(UNLINK_EXPR_SLIST_CURRENT()->addr)), link, remaddr_t); 3989 3990 if (unlinked != NULL) { 3991 DPRINTF(4, ("Deleted addr %s from list of addresses\n", 3992 stoa(addr))); 3993 free(unlinked); 3994 } 3995 } 3996 3997 3998 static void 3999 delete_interface_from_list( 4000 struct interface *iface 4001 ) 4002 { 4003 remaddr_t *unlinked; 4004 4005 do { 4006 UNLINK_EXPR_SLIST(unlinked, remoteaddr_list, iface == 4007 UNLINK_EXPR_SLIST_CURRENT()->interface, link, 4008 remaddr_t); 4009 4010 if (unlinked != NULL) { 4011 DPRINTF(4, ("Deleted addr %s for interface #%d %s from list of addresses\n", 4012 stoa(&unlinked->addr), iface->ifnum, 4013 iface->name)); 4014 if (addr_ismulticast(&unlinked->addr)) 4015 /* find a new interface to use */ 4016 io_multicast_add(&unlinked->addr); 4017 free(unlinked); 4018 } 4019 } while (unlinked != NULL); 4020 } 4021 4022 4023 static struct interface * 4024 find_addr_in_list( 4025 sockaddr_u *addr 4026 ) 4027 { 4028 remaddr_t *entry; 4029 4030 DPRINTF(4, ("Searching for addr %s in list of addresses - ", 4031 stoa(addr))); 4032 4033 for (entry = remoteaddr_list; 4034 entry != NULL; 4035 entry = entry->link) 4036 if (SOCK_EQ(&entry->addr, addr)) { 4037 DPRINTF(4, ("FOUND\n")); 4038 return entry->interface; 4039 } 4040 4041 DPRINTF(4, ("NOT FOUND\n")); 4042 return NULL; 4043 } 4044 4045 static inline isc_boolean_t 4046 same_network_v4( 4047 struct sockaddr_in *addr1, 4048 struct sockaddr_in *mask, 4049 struct sockaddr_in *addr2 4050 ) 4051 { 4052 return (addr1->sin_addr.s_addr & mask->sin_addr.s_addr) 4053 == (addr2->sin_addr.s_addr & mask->sin_addr.s_addr); 4054 } 4055 4056 #ifdef INCLUDE_IPV6_SUPPORT 4057 static inline isc_boolean_t 4058 same_network_v6( 4059 struct sockaddr_in6 *addr1, 4060 struct sockaddr_in6 *mask, 4061 struct sockaddr_in6 *addr2 4062 ) 4063 { 4064 size_t i; 4065 4066 for (i = 0; 4067 i < sizeof(addr1->sin6_addr.s6_addr) / 4068 sizeof(addr1->sin6_addr.s6_addr[0]); 4069 i++) 4070 4071 if ((addr1->sin6_addr.s6_addr[i] & 4072 mask->sin6_addr.s6_addr[i]) 4073 != 4074 (addr2->sin6_addr.s6_addr[i] & 4075 mask->sin6_addr.s6_addr[i])) 4076 4077 return ISC_FALSE; 4078 4079 return ISC_TRUE; 4080 } 4081 #endif /* INCLUDE_IPV6_SUPPORT */ 4082 4083 4084 static isc_boolean_t 4085 same_network( 4086 sockaddr_u *a1, 4087 sockaddr_u *mask, 4088 sockaddr_u *a2 4089 ) 4090 { 4091 isc_boolean_t sn; 4092 4093 if (AF(a1) != AF(a2)) 4094 sn = ISC_FALSE; 4095 else if (IS_IPV4(a1)) 4096 sn = same_network_v4(&a1->sa4, &mask->sa4, &a2->sa4); 4097 #ifdef INCLUDE_IPV6_SUPPORT 4098 else if (IS_IPV6(a1)) 4099 sn = same_network_v6(&a1->sa6, &mask->sa6, &a2->sa6); 4100 #endif 4101 else 4102 sn = ISC_FALSE; 4103 4104 return sn; 4105 } 4106 4107 /* 4108 * Find an address in the list on the same network as addr which is not 4109 * addr. 4110 */ 4111 static struct interface * 4112 find_samenet_addr_in_list( 4113 sockaddr_u *addr 4114 ) 4115 { 4116 remaddr_t *entry; 4117 4118 DPRINTF(4, ("Searching for addr with same subnet as %s in list of addresses - ", 4119 stoa(addr))); 4120 4121 for (entry = remoteaddr_list; 4122 entry != NULL; 4123 entry = entry->link) 4124 4125 if (!SOCK_EQ(addr, &entry->addr) 4126 && same_network(&entry->addr, 4127 &entry->interface->mask, 4128 addr)) { 4129 DPRINTF(4, ("FOUND\n")); 4130 return entry->interface; 4131 } 4132 4133 DPRINTF(4, ("NOT FOUND\n")); 4134 return NULL; 4135 } 4136 4137 4138 /* 4139 * Find the given address with the all given flags set in the list 4140 */ 4141 static struct interface * 4142 find_flagged_addr_in_list( 4143 sockaddr_u * addr, 4144 int flags 4145 ) 4146 { 4147 remaddr_t *entry; 4148 4149 DPRINTF(4, ("Finding addr %s with flags %d in list: ", 4150 stoa(addr), flags)); 4151 4152 for (entry = remoteaddr_list; 4153 entry != NULL; 4154 entry = entry->link) 4155 4156 if (SOCK_EQ(&entry->addr, addr) 4157 && (entry->interface->flags & flags) == flags) { 4158 4159 DPRINTF(4, ("FOUND\n")); 4160 return entry->interface; 4161 } 4162 4163 DPRINTF(4, ("NOT FOUND\n")); 4164 return NULL; 4165 } 4166 4167 4168 #ifdef HAS_ROUTING_SOCKET 4169 # ifndef UPDATE_GRACE 4170 # define UPDATE_GRACE 2 /* wait UPDATE_GRACE seconds before scanning */ 4171 # endif 4172 4173 static void 4174 process_routing_msgs(struct asyncio_reader *reader) 4175 { 4176 char buffer[5120]; 4177 int cnt, msg_type; 4178 #ifdef HAVE_RTNETLINK 4179 struct nlmsghdr *nh; 4180 #else 4181 struct rt_msghdr *rtm; 4182 char *p; 4183 #endif 4184 4185 if (disable_dynamic_updates) { 4186 /* 4187 * discard ourselves if we are not needed any more 4188 * usually happens when running unprivileged 4189 */ 4190 remove_asyncio_reader(reader); 4191 delete_asyncio_reader(reader); 4192 return; 4193 } 4194 4195 cnt = read(reader->fd, buffer, sizeof(buffer)); 4196 4197 if (cnt < 0) { 4198 msyslog(LOG_ERR, 4199 "i/o error on routing socket %m - disabling"); 4200 remove_asyncio_reader(reader); 4201 delete_asyncio_reader(reader); 4202 return; 4203 } 4204 4205 /* 4206 * process routing message 4207 */ 4208 #ifdef HAVE_RTNETLINK 4209 for (nh = (struct nlmsghdr *)buffer; 4210 NLMSG_OK(nh, cnt); 4211 nh = NLMSG_NEXT(nh, cnt)) { 4212 msg_type = nh->nlmsg_type; 4213 #else 4214 for (p = buffer; 4215 (p + sizeof(struct rt_msghdr)) <= (buffer + cnt); 4216 p += rtm->rtm_msglen) { 4217 rtm = (struct rt_msghdr *)p; 4218 if (rtm->rtm_version != RTM_VERSION) { 4219 msyslog(LOG_ERR, 4220 "version mismatch (got %d - expected %d) on routing socket - disabling", 4221 rtm->rtm_version, RTM_VERSION); 4222 4223 remove_asyncio_reader(reader); 4224 delete_asyncio_reader(reader); 4225 return; 4226 } 4227 msg_type = rtm->rtm_type; 4228 #endif 4229 switch (msg_type) { 4230 #ifdef RTM_NEWADDR 4231 case RTM_NEWADDR: 4232 #endif 4233 #ifdef RTM_DELADDR 4234 case RTM_DELADDR: 4235 #endif 4236 #ifdef RTM_ADD 4237 case RTM_ADD: 4238 #endif 4239 #ifdef RTM_DELETE 4240 case RTM_DELETE: 4241 #endif 4242 #ifdef RTM_REDIRECT 4243 case RTM_REDIRECT: 4244 #endif 4245 #ifdef RTM_CHANGE 4246 case RTM_CHANGE: 4247 #endif 4248 #ifdef RTM_LOSING 4249 case RTM_LOSING: 4250 #endif 4251 #ifdef RTM_IFINFO 4252 case RTM_IFINFO: 4253 #endif 4254 #ifdef RTM_IFANNOUNCE 4255 case RTM_IFANNOUNCE: 4256 #endif 4257 #ifdef RTM_NEWLINK 4258 case RTM_NEWLINK: 4259 #endif 4260 #ifdef RTM_DELLINK 4261 case RTM_DELLINK: 4262 #endif 4263 #ifdef RTM_NEWROUTE 4264 case RTM_NEWROUTE: 4265 #endif 4266 #ifdef RTM_DELROUTE 4267 case RTM_DELROUTE: 4268 #endif 4269 /* 4270 * we are keen on new and deleted addresses and 4271 * if an interface goes up and down or routing 4272 * changes 4273 */ 4274 DPRINTF(3, ("routing message op = %d: scheduling interface update\n", 4275 msg_type)); 4276 timer_interfacetimeout(current_time + UPDATE_GRACE); 4277 break; 4278 #ifdef HAVE_RTNETLINK 4279 case NLMSG_DONE: 4280 /* end of multipart message */ 4281 return; 4282 #endif 4283 default: 4284 /* 4285 * the rest doesn't bother us. 4286 */ 4287 DPRINTF(4, ("routing message op = %d: ignored\n", 4288 msg_type)); 4289 break; 4290 } 4291 } 4292 } 4293 4294 /* 4295 * set up routing notifications 4296 */ 4297 static void 4298 init_async_notifications() 4299 { 4300 struct asyncio_reader *reader; 4301 #ifdef HAVE_RTNETLINK 4302 int fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE); 4303 struct sockaddr_nl sa; 4304 #else 4305 int fd = socket(PF_ROUTE, SOCK_RAW, 0); 4306 #endif 4307 if (fd < 0) { 4308 msyslog(LOG_ERR, 4309 "unable to open routing socket (%m) - using polled interface update"); 4310 return; 4311 } 4312 4313 fd = move_fd(fd); 4314 #ifdef HAVE_RTNETLINK 4315 memset(&sa, 0, sizeof(sa)); 4316 sa.nl_family = PF_NETLINK; 4317 sa.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR 4318 | RTMGRP_IPV6_IFADDR | RTMGRP_IPV4_ROUTE 4319 | RTMGRP_IPV4_MROUTE | RTMGRP_IPV6_ROUTE 4320 | RTMGRP_IPV6_MROUTE; 4321 if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) { 4322 msyslog(LOG_ERR, 4323 "bind failed on routing socket (%m) - using polled interface update"); 4324 return; 4325 } 4326 #endif 4327 init_nonblocking_io(fd); 4328 #if defined(HAVE_SIGNALED_IO) 4329 init_socket_sig(fd); 4330 #endif /* HAVE_SIGNALED_IO */ 4331 4332 reader = new_asyncio_reader(); 4333 4334 reader->fd = fd; 4335 reader->receiver = process_routing_msgs; 4336 4337 add_asyncio_reader(reader, FD_TYPE_SOCKET); 4338 msyslog(LOG_INFO, 4339 "Listening on routing socket on fd #%d for interface updates", 4340 fd); 4341 } 4342 #else 4343 /* HAS_ROUTING_SOCKET not defined */ 4344 static void 4345 init_async_notifications(void) 4346 { 4347 } 4348 #endif 4349