Coverage Report

Created: 2026-02-26 06:20

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