Coverage Report

Created: 2023-05-19 06:16

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