]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - usr.sbin/rtadvd/rtadvd.c
MFC r363988:
[FreeBSD/stable/9.git] / usr.sbin / rtadvd / rtadvd.c
1 /*      $FreeBSD$       */
2 /*      $KAME: rtadvd.c,v 1.82 2003/08/05 12:34:23 itojun Exp $ */
3
4 /*
5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6  * Copyright (C) 2011 Hiroki Sato <hrs@FreeBSD.org>
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the project nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 #include <sys/param.h>
35 #include <sys/ioctl.h>
36 #include <sys/socket.h>
37 #include <sys/uio.h>
38 #include <sys/time.h>
39 #include <sys/queue.h>
40 #include <sys/stat.h>
41 #include <sys/sysctl.h>
42
43 #include <net/if.h>
44 #include <net/if_types.h>
45 #include <net/if_media.h>
46 #include <net/if_dl.h>
47 #include <net/route.h>
48 #include <netinet/in.h>
49 #include <netinet/ip6.h>
50 #include <netinet6/ip6_var.h>
51 #include <netinet/icmp6.h>
52
53 #include <arpa/inet.h>
54
55 #include <net/if_var.h>
56 #include <netinet/in_var.h>
57 #include <netinet6/nd6.h>
58
59 #include <time.h>
60 #include <unistd.h>
61 #include <stdio.h>
62 #include <err.h>
63 #include <errno.h>
64 #include <inttypes.h>
65 #include <libutil.h>
66 #include <netdb.h>
67 #include <signal.h>
68 #include <string.h>
69 #include <stdlib.h>
70 #include <syslog.h>
71 #include <poll.h>
72
73 #include "pathnames.h"
74 #include "rtadvd.h"
75 #include "if.h"
76 #include "rrenum.h"
77 #include "advcap.h"
78 #include "timer_subr.h"
79 #include "timer.h"
80 #include "config.h"
81 #include "control.h"
82 #include "control_server.h"
83
84 #define RTADV_TYPE2BITMASK(type) (0x1 << type)
85
86 struct msghdr rcvmhdr;
87 static char *rcvcmsgbuf;
88 static size_t rcvcmsgbuflen;
89 static char *sndcmsgbuf = NULL;
90 static size_t sndcmsgbuflen;
91 struct msghdr sndmhdr;
92 struct iovec rcviov[2];
93 struct iovec sndiov[2];
94 struct sockaddr_in6 rcvfrom;
95 static const char *pidfilename = _PATH_RTADVDPID;
96 const char *conffile = _PATH_RTADVDCONF;
97 static struct pidfh *pfh;
98 static int dflag, sflag;
99 static int wait_shutdown;
100
101 #define PFD_RAWSOCK     0
102 #define PFD_RTSOCK      1
103 #define PFD_CSOCK       2
104 #define PFD_MAX         3
105
106 struct railist_head_t railist =
107     TAILQ_HEAD_INITIALIZER(railist);
108 struct ifilist_head_t ifilist =
109     TAILQ_HEAD_INITIALIZER(ifilist);
110
111 struct nd_optlist {
112         TAILQ_ENTRY(nd_optlist) nol_next;
113         struct nd_opt_hdr *nol_opt;
114 };
115 union nd_opt {
116         struct nd_opt_hdr *opt_array[9];
117         struct {
118                 struct nd_opt_hdr *zero;
119                 struct nd_opt_hdr *src_lladdr;
120                 struct nd_opt_hdr *tgt_lladdr;
121                 struct nd_opt_prefix_info *pi;
122                 struct nd_opt_rd_hdr *rh;
123                 struct nd_opt_mtu *mtu;
124                 TAILQ_HEAD(, nd_optlist) opt_list;
125         } nd_opt_each;
126 };
127 #define opt_src_lladdr  nd_opt_each.src_lladdr
128 #define opt_tgt_lladdr  nd_opt_each.tgt_lladdr
129 #define opt_pi          nd_opt_each.pi
130 #define opt_rh          nd_opt_each.rh
131 #define opt_mtu         nd_opt_each.mtu
132 #define opt_list        nd_opt_each.opt_list
133
134 #define NDOPT_FLAG_SRCLINKADDR  (1 << 0)
135 #define NDOPT_FLAG_TGTLINKADDR  (1 << 1)
136 #define NDOPT_FLAG_PREFIXINFO   (1 << 2)
137 #define NDOPT_FLAG_RDHDR        (1 << 3)
138 #define NDOPT_FLAG_MTU          (1 << 4)
139 #define NDOPT_FLAG_RDNSS        (1 << 5)
140 #define NDOPT_FLAG_DNSSL        (1 << 6)
141
142 static uint32_t ndopt_flags[] = {
143         [ND_OPT_SOURCE_LINKADDR]        = NDOPT_FLAG_SRCLINKADDR,
144         [ND_OPT_TARGET_LINKADDR]        = NDOPT_FLAG_TGTLINKADDR,
145         [ND_OPT_PREFIX_INFORMATION]     = NDOPT_FLAG_PREFIXINFO,
146         [ND_OPT_REDIRECTED_HEADER]      = NDOPT_FLAG_RDHDR,
147         [ND_OPT_MTU]                    = NDOPT_FLAG_MTU,
148         [ND_OPT_RDNSS]                  = NDOPT_FLAG_RDNSS,
149         [ND_OPT_DNSSL]                  = NDOPT_FLAG_DNSSL,
150 };
151
152 static void     rtadvd_shutdown(void);
153 static void     sock_open(struct sockinfo *);
154 static void     rtsock_open(struct sockinfo *);
155 static void     rtadvd_input(struct sockinfo *);
156 static void     rs_input(int, struct nd_router_solicit *,
157                     struct in6_pktinfo *, struct sockaddr_in6 *);
158 static void     ra_input(int, struct nd_router_advert *,
159                     struct in6_pktinfo *, struct sockaddr_in6 *);
160 static int      prefix_check(struct nd_opt_prefix_info *, struct rainfo *,
161                     struct sockaddr_in6 *);
162 static int      nd6_options(struct nd_opt_hdr *, int,
163                     union nd_opt *, uint32_t);
164 static void     free_ndopts(union nd_opt *);
165 static void     rtmsg_input(struct sockinfo *);
166 static void     set_short_delay(struct ifinfo *);
167 static int      check_accept_rtadv(int);
168
169 static void
170 usage(void)
171 {
172
173         fprintf(stderr, "usage: rtadvd [-dDfRs] "
174             "[-c configfile] [-C ctlsock] [-M ifname] [-p pidfile]\n");
175         exit(1);
176 }
177
178 int
179 main(int argc, char *argv[])
180 {
181         struct pollfd set[PFD_MAX];
182         struct timeval *timeout;
183         int i, ch;
184         int fflag = 0, logopt;
185         int error;
186         pid_t pid, otherpid;
187
188         /* get command line options and arguments */
189         while ((ch = getopt(argc, argv, "c:C:dDfhM:p:Rs")) != -1) {
190                 switch (ch) {
191                 case 'c':
192                         conffile = optarg;
193                         break;
194                 case 'C':
195                         ctrlsock.si_name = optarg;
196                         break;
197                 case 'd':
198                         dflag++;
199                         break;
200                 case 'D':
201                         dflag += 3;
202                         break;
203                 case 'f':
204                         fflag = 1;
205                         break;
206                 case 'M':
207                         mcastif = optarg;
208                         break;
209                 case 'R':
210                         fprintf(stderr, "rtadvd: "
211                                 "the -R option is currently ignored.\n");
212                         /* accept_rr = 1; */
213                         /* run anyway... */
214                         break;
215                 case 's':
216                         sflag = 1;
217                         break;
218                 case 'p':
219                         pidfilename = optarg;
220                         break;
221                 default:
222                         usage();
223                 }
224         }
225         argc -= optind;
226         argv += optind;
227
228         logopt = LOG_NDELAY | LOG_PID;
229         if (fflag)
230                 logopt |= LOG_PERROR;
231         openlog("rtadvd", logopt, LOG_DAEMON);
232
233         /* set log level */
234         if (dflag > 2)
235                 (void)setlogmask(LOG_UPTO(LOG_DEBUG));
236         else if (dflag > 1)
237                 (void)setlogmask(LOG_UPTO(LOG_INFO));
238         else if (dflag > 0)
239                 (void)setlogmask(LOG_UPTO(LOG_NOTICE));
240         else
241                 (void)setlogmask(LOG_UPTO(LOG_ERR));
242
243         /* timer initialization */
244         rtadvd_timer_init();
245
246 #ifndef HAVE_ARC4RANDOM
247         /* random value initialization */
248 #ifdef __FreeBSD__
249         srandomdev();
250 #else
251         srandom((unsigned long)time(NULL));
252 #endif
253 #endif
254         pfh = pidfile_open(pidfilename, 0600, &otherpid);
255         if (pfh == NULL) {
256                 if (errno == EEXIST)
257                         errx(1, "%s already running, pid: %d",
258                             getprogname(), otherpid);
259                 syslog(LOG_ERR,
260                     "failed to open the pid file %s, run anyway.",
261                     pidfilename);
262         }
263         if (!fflag)
264                 daemon(1, 0);
265
266         sock_open(&sock);
267
268         update_ifinfo(&ifilist, UPDATE_IFINFO_ALL);
269         for (i = 0; i < argc; i++)
270                 update_persist_ifinfo(&ifilist, argv[i]);
271
272         csock_open(&ctrlsock, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
273         if (ctrlsock.si_fd == -1) {
274                 syslog(LOG_ERR, "cannot open control socket: %s",
275                     strerror(errno));
276                 exit(1);
277         }
278
279         /* record the current PID */
280         pid = getpid();
281         pidfile_write(pfh);
282
283         set[PFD_RAWSOCK].fd = sock.si_fd;
284         set[PFD_RAWSOCK].events = POLLIN;
285         if (sflag == 0) {
286                 rtsock_open(&rtsock);
287                 set[PFD_RTSOCK].fd = rtsock.si_fd;
288                 set[PFD_RTSOCK].events = POLLIN;
289         } else
290                 set[PFD_RTSOCK].fd = -1;
291         set[PFD_CSOCK].fd = ctrlsock.si_fd;
292         set[PFD_CSOCK].events = POLLIN;
293         signal(SIGTERM, set_do_shutdown);
294         signal(SIGINT, set_do_shutdown);
295         signal(SIGHUP, set_do_reload);
296
297         error = csock_listen(&ctrlsock);
298         if (error) {
299                 syslog(LOG_ERR, "cannot listen control socket: %s",
300                     strerror(errno));
301                 exit(1);
302         }
303
304         /* load configuration file */
305         set_do_reload(0);
306
307         while (1) {
308                 if (is_do_shutdown())
309                         rtadvd_shutdown();
310
311                 if (is_do_reload()) {
312                         loadconfig_ifname(reload_ifname());
313                         if (reload_ifname() == NULL)
314                                 syslog(LOG_INFO,
315                                     "configuration file reloaded.");
316                         else
317                                 syslog(LOG_INFO,
318                                     "configuration file for %s reloaded.",
319                                     reload_ifname());
320                         reset_do_reload();
321                 }
322
323                 /* timeout handler update for active interfaces */
324                 rtadvd_update_timeout_handler();
325
326                 /* timer expiration check and reset the timer */
327                 timeout = rtadvd_check_timer();
328
329                 if (timeout != NULL) {
330                         syslog(LOG_DEBUG,
331                             "<%s> set timer to %ld:%ld. waiting for "
332                             "inputs or timeout", __func__,
333                             (long int)timeout->tv_sec,
334                             (long int)timeout->tv_usec);
335                 } else {
336                         syslog(LOG_DEBUG,
337                             "<%s> there's no timer. waiting for inputs",
338                             __func__);
339                 }
340                 if ((i = poll(set, sizeof(set)/sizeof(set[0]),
341                             timeout ? (timeout->tv_sec * 1000 +
342                                 timeout->tv_usec / 1000) : INFTIM)) < 0) {
343
344                         /* EINTR would occur if a signal was delivered */
345                         if (errno != EINTR)
346                                 syslog(LOG_ERR, "poll() failed: %s",
347                                     strerror(errno));
348                         continue;
349                 }
350                 if (i == 0)     /* timeout */
351                         continue;
352                 if (rtsock.si_fd != -1 && set[PFD_RTSOCK].revents & POLLIN)
353                         rtmsg_input(&rtsock);
354
355                 if (set[PFD_RAWSOCK].revents & POLLIN)
356                         rtadvd_input(&sock);
357
358                 if (set[PFD_CSOCK].revents & POLLIN) {
359                         int fd;
360
361                         fd = csock_accept(&ctrlsock);
362                         if (fd == -1)
363                                 syslog(LOG_ERR,
364                                     "cannot accept() control socket: %s",
365                                     strerror(errno));
366                         else {
367                                 cm_handler_server(fd);
368                                 close(fd);
369                         }
370                 }
371         }
372         exit(0);                /* NOTREACHED */
373 }
374
375 static void
376 rtadvd_shutdown(void)
377 {
378         struct ifinfo *ifi;
379         struct rainfo *rai;
380         struct rdnss *rdn;
381         struct dnssl *dns;
382
383         if (wait_shutdown) {
384                 syslog(LOG_INFO,
385                     "waiting expiration of the all RA timers.");
386
387                 TAILQ_FOREACH(ifi, &ifilist, ifi_next) {
388                         /*
389                          * Ignore !IFF_UP interfaces in waiting for shutdown.
390                          */
391                         if (!(ifi->ifi_flags & IFF_UP) &&
392                             ifi->ifi_ra_timer != NULL) {
393                                 ifi->ifi_state = IFI_STATE_UNCONFIGURED;
394                                 rtadvd_remove_timer(ifi->ifi_ra_timer);
395                                 ifi->ifi_ra_timer = NULL;
396                                 syslog(LOG_DEBUG, "<%s> %s(idx=%d) is down. "
397                                     "Timer removed and marked as UNCONFIGURED.",
398                                      __func__, ifi->ifi_ifname,
399                                     ifi->ifi_ifindex);
400                         }
401                 }
402                 TAILQ_FOREACH(ifi, &ifilist, ifi_next) {
403                         if (ifi->ifi_ra_timer != NULL)
404                                 break;
405                 }
406                 if (ifi == NULL) {
407                         syslog(LOG_NOTICE, "gracefully terminated.");
408                         exit(0);
409                 }
410
411                 sleep(1);
412                 return;
413         }
414
415         syslog(LOG_DEBUG, "<%s> cease to be an advertising router",
416             __func__);
417
418         wait_shutdown = 1;
419
420         TAILQ_FOREACH(rai, &railist, rai_next) {
421                 rai->rai_lifetime = 0;
422                 TAILQ_FOREACH(rdn, &rai->rai_rdnss, rd_next)
423                         rdn->rd_ltime = 0;
424                 TAILQ_FOREACH(dns, &rai->rai_dnssl, dn_next)
425                         dns->dn_ltime = 0;
426         }
427         TAILQ_FOREACH(ifi, &ifilist, ifi_next) {
428                 if (!ifi->ifi_persist)
429                         continue;
430                 if (ifi->ifi_state == IFI_STATE_UNCONFIGURED)
431                         continue;
432                 if (ifi->ifi_ra_timer == NULL)
433                         continue;
434                 if (ifi->ifi_ra_lastsent.tv_sec == 0 &&
435                     ifi->ifi_ra_lastsent.tv_usec == 0 &&
436                     ifi->ifi_ra_timer != NULL) {
437                         /*
438                          * When RA configured but never sent,
439                          * ignore the IF immediately.
440                          */
441                         rtadvd_remove_timer(ifi->ifi_ra_timer);
442                         ifi->ifi_ra_timer = NULL;
443                         ifi->ifi_state = IFI_STATE_UNCONFIGURED;
444                         continue;
445                 }
446
447                 ifi->ifi_state = IFI_STATE_TRANSITIVE;
448
449                 /* Mark as the shut-down state. */
450                 ifi->ifi_rainfo_trans = ifi->ifi_rainfo;
451                 ifi->ifi_rainfo = NULL;
452
453                 ifi->ifi_burstcount = MAX_FINAL_RTR_ADVERTISEMENTS;
454                 ifi->ifi_burstinterval = MIN_DELAY_BETWEEN_RAS;
455
456                 ra_timer_update(ifi, &ifi->ifi_ra_timer->rat_tm);
457                 rtadvd_set_timer(&ifi->ifi_ra_timer->rat_tm,
458                     ifi->ifi_ra_timer);
459         }
460         syslog(LOG_NOTICE, "final RA transmission started.");
461
462         pidfile_remove(pfh);
463         csock_close(&ctrlsock);
464 }
465
466 static void
467 rtmsg_input(struct sockinfo *s)
468 {
469         int n, type, ifindex = 0, plen;
470         size_t len;
471         char msg[2048], *next, *lim;
472         char ifname[IFNAMSIZ];
473         struct if_announcemsghdr *ifan;
474         struct rt_msghdr *rtm;
475         struct prefix *pfx;
476         struct rainfo *rai;
477         struct in6_addr *addr;
478         struct ifinfo *ifi;
479         char addrbuf[INET6_ADDRSTRLEN];
480         int prefixchange = 0;
481
482         if (s == NULL) {
483                 syslog(LOG_ERR, "<%s> internal error", __func__);
484                 exit(1);
485         }
486         n = read(s->si_fd, msg, sizeof(msg));
487         rtm = (struct rt_msghdr *)msg;
488         syslog(LOG_DEBUG, "<%s> received a routing message "
489             "(type = %d, len = %d)", __func__, rtm->rtm_type, n);
490
491         if (n > rtm->rtm_msglen) {
492                 /*
493                  * This usually won't happen for messages received on
494                  * a routing socket.
495                  */
496                 syslog(LOG_DEBUG,
497                     "<%s> received data length is larger than "
498                     "1st routing message len. multiple messages? "
499                     "read %d bytes, but 1st msg len = %d",
500                     __func__, n, rtm->rtm_msglen);
501 #if 0
502                 /* adjust length */
503                 n = rtm->rtm_msglen;
504 #endif
505         }
506
507         lim = msg + n;
508         for (next = msg; next < lim; next += len) {
509                 int oldifflags;
510
511                 next = get_next_msg(next, lim, 0, &len,
512                     RTADV_TYPE2BITMASK(RTM_ADD) |
513                     RTADV_TYPE2BITMASK(RTM_DELETE) |
514                     RTADV_TYPE2BITMASK(RTM_NEWADDR) |
515                     RTADV_TYPE2BITMASK(RTM_DELADDR) |
516                     RTADV_TYPE2BITMASK(RTM_IFINFO) |
517                     RTADV_TYPE2BITMASK(RTM_IFANNOUNCE));
518                 if (len == 0)
519                         break;
520                 type = ((struct rt_msghdr *)next)->rtm_type;
521                 switch (type) {
522                 case RTM_ADD:
523                 case RTM_DELETE:
524                         ifindex = get_rtm_ifindex(next);
525                         break;
526                 case RTM_NEWADDR:
527                 case RTM_DELADDR:
528                         ifindex = (int)((struct ifa_msghdr *)next)->ifam_index;
529                         break;
530                 case RTM_IFINFO:
531                         ifindex = (int)((struct if_msghdr *)next)->ifm_index;
532                         break;
533                 case RTM_IFANNOUNCE:
534                         ifan = (struct if_announcemsghdr *)next;
535                         switch (ifan->ifan_what) {
536                         case IFAN_ARRIVAL:
537                         case IFAN_DEPARTURE:
538                                 break;
539                         default:
540                                 syslog(LOG_DEBUG,
541                                     "<%s:%d> unknown ifan msg (ifan_what=%d)",
542                                    __func__, __LINE__, ifan->ifan_what);
543                                 continue;
544                         }
545
546                         syslog(LOG_DEBUG, "<%s>: if_announcemsg (idx=%d:%d)",
547                                __func__, ifan->ifan_index, ifan->ifan_what);
548                         switch (ifan->ifan_what) {
549                         case IFAN_ARRIVAL:
550                                 syslog(LOG_NOTICE,
551                                     "interface added (idx=%d)",
552                                     ifan->ifan_index);
553                                 update_ifinfo(&ifilist, ifan->ifan_index);
554                                 loadconfig_index(ifan->ifan_index);
555                                 break;
556                         case IFAN_DEPARTURE:
557                                 syslog(LOG_NOTICE,
558                                     "interface removed (idx=%d)",
559                                     ifan->ifan_index);
560                                 rm_ifinfo_index(ifan->ifan_index);
561
562                                 /* Clear ifi_ifindex */
563                                 TAILQ_FOREACH(ifi, &ifilist, ifi_next) {
564                                         if (ifi->ifi_ifindex
565                                             == ifan->ifan_index) {
566                                                 ifi->ifi_ifindex = 0;
567                                                 break;
568                                         }
569                                 }
570                                 update_ifinfo(&ifilist, ifan->ifan_index);
571                                 break;
572                         }
573                         continue;
574                 default:
575                         /* should not reach here */
576                         syslog(LOG_DEBUG,
577                                "<%s:%d> unknown rtmsg %d on %s",
578                                __func__, __LINE__, type,
579                                if_indextoname(ifindex, ifname));
580                         continue;
581                 }
582                 ifi = if_indextoifinfo(ifindex);
583                 if (ifi == NULL) {
584                         syslog(LOG_DEBUG,
585                             "<%s> ifinfo not found for idx=%d.  Why?",
586                             __func__, ifindex);
587                         continue;
588                 }
589                 rai = ifi->ifi_rainfo;
590                 if (rai == NULL) {
591                         syslog(LOG_DEBUG,
592                             "<%s> route changed on "
593                             "non advertising interface(%s)",
594                             __func__, ifi->ifi_ifname);
595                         continue;
596                 }
597
598                 oldifflags = ifi->ifi_flags;
599                 /* init ifflags because it may have changed */
600                 update_ifinfo(&ifilist, ifindex);
601
602                 switch (type) {
603                 case RTM_ADD:
604                         if (sflag)
605                                 break;  /* we aren't interested in prefixes  */
606
607                         addr = get_addr(msg);
608                         plen = get_prefixlen(msg);
609                         /* sanity check for plen */
610                         /* as RFC2373, prefixlen is at least 4 */
611                         if (plen < 4 || plen > 127) {
612                                 syslog(LOG_INFO, "<%s> new interface route's"
613                                     "plen %d is invalid for a prefix",
614                                     __func__, plen);
615                                 break;
616                         }
617                         pfx = find_prefix(rai, addr, plen);
618                         if (pfx) {
619                                 if (pfx->pfx_timer) {
620                                         /*
621                                          * If the prefix has been invalidated,
622                                          * make it available again.
623                                          */
624                                         update_prefix(pfx);
625                                         prefixchange = 1;
626                                 } else
627                                         syslog(LOG_DEBUG,
628                                             "<%s> new prefix(%s/%d) "
629                                             "added on %s, "
630                                             "but it was already in list",
631                                             __func__,
632                                             inet_ntop(AF_INET6, addr,
633                                                 (char *)addrbuf,
634                                                 sizeof(addrbuf)),
635                                             plen, ifi->ifi_ifname);
636                                 break;
637                         }
638                         make_prefix(rai, ifindex, addr, plen);
639                         prefixchange = 1;
640                         break;
641                 case RTM_DELETE:
642                         if (sflag)
643                                 break;
644
645                         addr = get_addr(msg);
646                         plen = get_prefixlen(msg);
647                         /* sanity check for plen */
648                         /* as RFC2373, prefixlen is at least 4 */
649                         if (plen < 4 || plen > 127) {
650                                 syslog(LOG_INFO,
651                                     "<%s> deleted interface route's "
652                                     "plen %d is invalid for a prefix",
653                                     __func__, plen);
654                                 break;
655                         }
656                         pfx = find_prefix(rai, addr, plen);
657                         if (pfx == NULL) {
658                                 syslog(LOG_DEBUG,
659                                     "<%s> prefix(%s/%d) was deleted on %s, "
660                                     "but it was not in list",
661                                     __func__, inet_ntop(AF_INET6, addr,
662                                         (char *)addrbuf, sizeof(addrbuf)),
663                                         plen, ifi->ifi_ifname);
664                                 break;
665                         }
666                         invalidate_prefix(pfx);
667                         prefixchange = 1;
668                         break;
669                 case RTM_NEWADDR:
670                 case RTM_DELADDR:
671                 case RTM_IFINFO:
672                         break;
673                 default:
674                         /* should not reach here */
675                         syslog(LOG_DEBUG,
676                             "<%s:%d> unknown rtmsg %d on %s",
677                             __func__, __LINE__, type,
678                             if_indextoname(ifindex, ifname));
679                         return;
680                 }
681
682                 /* check if an interface flag is changed */
683                 if ((oldifflags & IFF_UP) && /* UP to DOWN */
684                     !(ifi->ifi_flags & IFF_UP)) {
685                         syslog(LOG_NOTICE,
686                             "<interface %s becomes down. stop timer.",
687                             ifi->ifi_ifname);
688                         rtadvd_remove_timer(ifi->ifi_ra_timer);
689                         ifi->ifi_ra_timer = NULL;
690                 } else if (!(oldifflags & IFF_UP) && /* DOWN to UP */
691                     (ifi->ifi_flags & IFF_UP)) {
692                         syslog(LOG_NOTICE,
693                             "interface %s becomes up. restart timer.",
694                             ifi->ifi_ifname);
695
696                         ifi->ifi_state = IFI_STATE_TRANSITIVE;
697                         ifi->ifi_burstcount =
698                             MAX_INITIAL_RTR_ADVERTISEMENTS;
699                         ifi->ifi_burstinterval =
700                             MAX_INITIAL_RTR_ADVERT_INTERVAL;
701
702                         ifi->ifi_ra_timer = rtadvd_add_timer(ra_timeout,
703                             ra_timer_update, ifi, ifi);
704                         ra_timer_update(ifi, &ifi->ifi_ra_timer->rat_tm);
705                         rtadvd_set_timer(&ifi->ifi_ra_timer->rat_tm,
706                             ifi->ifi_ra_timer);
707                 } else if (prefixchange &&
708                     (ifi->ifi_flags & IFF_UP)) {
709                         /*
710                          * An advertised prefix has been added or invalidated.
711                          * Will notice the change in a short delay.
712                          */
713                         set_short_delay(ifi);
714                 }
715         }
716
717         return;
718 }
719
720 void
721 rtadvd_input(struct sockinfo *s)
722 {
723         ssize_t i;
724         int *hlimp = NULL;
725 #ifdef OLDRAWSOCKET
726         struct ip6_hdr *ip;
727 #endif
728         struct icmp6_hdr *icp;
729         int ifindex = 0;
730         struct cmsghdr *cm;
731         struct in6_pktinfo *pi = NULL;
732         char ntopbuf[INET6_ADDRSTRLEN], ifnamebuf[IFNAMSIZ];
733         struct in6_addr dst = in6addr_any;
734         struct ifinfo *ifi;
735
736         syslog(LOG_DEBUG, "<%s> enter", __func__);
737
738         if (s == NULL) {
739                 syslog(LOG_ERR, "<%s> internal error", __func__);
740                 exit(1);
741         }
742         /*
743          * Get message. We reset msg_controllen since the field could
744          * be modified if we had received a message before setting
745          * receive options.
746          */
747         rcvmhdr.msg_controllen = rcvcmsgbuflen;
748         if ((i = recvmsg(s->si_fd, &rcvmhdr, 0)) < 0)
749                 return;
750
751         /* extract optional information via Advanced API */
752         for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(&rcvmhdr);
753              cm;
754              cm = (struct cmsghdr *)CMSG_NXTHDR(&rcvmhdr, cm)) {
755                 if (cm->cmsg_level == IPPROTO_IPV6 &&
756                     cm->cmsg_type == IPV6_PKTINFO &&
757                     cm->cmsg_len == CMSG_LEN(sizeof(struct in6_pktinfo))) {
758                         pi = (struct in6_pktinfo *)(CMSG_DATA(cm));
759                         ifindex = pi->ipi6_ifindex;
760                         dst = pi->ipi6_addr;
761                 }
762                 if (cm->cmsg_level == IPPROTO_IPV6 &&
763                     cm->cmsg_type == IPV6_HOPLIMIT &&
764                     cm->cmsg_len == CMSG_LEN(sizeof(int)))
765                         hlimp = (int *)CMSG_DATA(cm);
766         }
767         if (ifindex == 0) {
768                 syslog(LOG_ERR, "failed to get receiving interface");
769                 return;
770         }
771         if (hlimp == NULL) {
772                 syslog(LOG_ERR, "failed to get receiving hop limit");
773                 return;
774         }
775
776         /*
777          * If we happen to receive data on an interface which is now gone
778          * or down, just discard the data.
779          */
780         ifi = if_indextoifinfo(pi->ipi6_ifindex);
781         if (ifi == NULL || !(ifi->ifi_flags & IFF_UP)) {
782                 syslog(LOG_INFO,
783                     "<%s> received data on a disabled interface (%s)",
784                     __func__,
785                     (ifi == NULL) ? "[gone]" : ifi->ifi_ifname);
786                 return;
787         }
788
789 #ifdef OLDRAWSOCKET
790         if ((size_t)i < sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr)) {
791                 syslog(LOG_ERR,
792                     "packet size(%d) is too short", i);
793                 return;
794         }
795
796         ip = (struct ip6_hdr *)rcvmhdr.msg_iov[0].iov_base;
797         icp = (struct icmp6_hdr *)(ip + 1); /* XXX: ext. hdr? */
798 #else
799         if ((size_t)i < sizeof(struct icmp6_hdr)) {
800                 syslog(LOG_ERR, "packet size(%zd) is too short", i);
801                 return;
802         }
803
804         icp = (struct icmp6_hdr *)rcvmhdr.msg_iov[0].iov_base;
805 #endif
806
807         switch (icp->icmp6_type) {
808         case ND_ROUTER_SOLICIT:
809                 /*
810                  * Message verification - RFC 4861 6.1.1
811                  * XXX: these checks must be done in the kernel as well,
812                  *      but we can't completely rely on them.
813                  */
814                 if (*hlimp != 255) {
815                         syslog(LOG_NOTICE,
816                             "RS with invalid hop limit(%d) "
817                             "received from %s on %s",
818                             *hlimp,
819                             inet_ntop(AF_INET6, &rcvfrom.sin6_addr, ntopbuf,
820                             sizeof(ntopbuf)),
821                             if_indextoname(pi->ipi6_ifindex, ifnamebuf));
822                         return;
823                 }
824                 if (icp->icmp6_code) {
825                         syslog(LOG_NOTICE,
826                             "RS with invalid ICMP6 code(%d) "
827                             "received from %s on %s",
828                             icp->icmp6_code,
829                             inet_ntop(AF_INET6, &rcvfrom.sin6_addr, ntopbuf,
830                             sizeof(ntopbuf)),
831                             if_indextoname(pi->ipi6_ifindex, ifnamebuf));
832                         return;
833                 }
834                 if ((size_t)i < sizeof(struct nd_router_solicit)) {
835                         syslog(LOG_NOTICE,
836                             "RS from %s on %s does not have enough "
837                             "length (len = %zd)",
838                             inet_ntop(AF_INET6, &rcvfrom.sin6_addr, ntopbuf,
839                             sizeof(ntopbuf)),
840                             if_indextoname(pi->ipi6_ifindex, ifnamebuf), i);
841                         return;
842                 }
843                 rs_input(i, (struct nd_router_solicit *)icp, pi, &rcvfrom);
844                 break;
845         case ND_ROUTER_ADVERT:
846                 /*
847                  * Message verification - RFC 4861 6.1.2
848                  * XXX: there's the same dilemma as above...
849                  */
850                 if (!IN6_IS_ADDR_LINKLOCAL(&rcvfrom.sin6_addr)) {
851                         syslog(LOG_NOTICE,
852                             "RA witn non-linklocal source address "
853                             "received from %s on %s",
854                             inet_ntop(AF_INET6, &rcvfrom.sin6_addr,
855                             ntopbuf, sizeof(ntopbuf)),
856                             if_indextoname(pi->ipi6_ifindex, ifnamebuf));
857                         return;
858                 }
859                 if (*hlimp != 255) {
860                         syslog(LOG_NOTICE,
861                             "RA with invalid hop limit(%d) "
862                             "received from %s on %s",
863                             *hlimp,
864                             inet_ntop(AF_INET6, &rcvfrom.sin6_addr, ntopbuf,
865                             sizeof(ntopbuf)),
866                             if_indextoname(pi->ipi6_ifindex, ifnamebuf));
867                         return;
868                 }
869                 if (icp->icmp6_code) {
870                         syslog(LOG_NOTICE,
871                             "RA with invalid ICMP6 code(%d) "
872                             "received from %s on %s",
873                             icp->icmp6_code,
874                             inet_ntop(AF_INET6, &rcvfrom.sin6_addr, ntopbuf,
875                             sizeof(ntopbuf)),
876                             if_indextoname(pi->ipi6_ifindex, ifnamebuf));
877                         return;
878                 }
879                 if ((size_t)i < sizeof(struct nd_router_advert)) {
880                         syslog(LOG_NOTICE,
881                             "RA from %s on %s does not have enough "
882                             "length (len = %zd)",
883                             inet_ntop(AF_INET6, &rcvfrom.sin6_addr, ntopbuf,
884                             sizeof(ntopbuf)),
885                             if_indextoname(pi->ipi6_ifindex, ifnamebuf), i);
886                         return;
887                 }
888                 ra_input(i, (struct nd_router_advert *)icp, pi, &rcvfrom);
889                 break;
890         case ICMP6_ROUTER_RENUMBERING:
891                 if (mcastif == NULL) {
892                         syslog(LOG_ERR, "received a router renumbering "
893                             "message, but not allowed to be accepted");
894                         break;
895                 }
896                 rr_input(i, (struct icmp6_router_renum *)icp, pi, &rcvfrom,
897                     &dst);
898                 break;
899         default:
900                 /*
901                  * Note that this case is POSSIBLE, especially just
902                  * after invocation of the daemon. This is because we
903                  * could receive message after opening the socket and
904                  * before setting ICMP6 type filter(see sock_open()).
905                  */
906                 syslog(LOG_ERR, "invalid icmp type(%d)", icp->icmp6_type);
907                 return;
908         }
909
910         return;
911 }
912
913 static void
914 rs_input(int len, struct nd_router_solicit *rs,
915          struct in6_pktinfo *pi, struct sockaddr_in6 *from)
916 {
917         char ntopbuf[INET6_ADDRSTRLEN];
918         char ifnamebuf[IFNAMSIZ];
919         union nd_opt ndopts;
920         struct rainfo *rai;
921         struct ifinfo *ifi;
922         struct soliciter *sol;
923
924         syslog(LOG_DEBUG,
925             "<%s> RS received from %s on %s",
926             __func__,
927             inet_ntop(AF_INET6, &from->sin6_addr, ntopbuf, sizeof(ntopbuf)),
928             if_indextoname(pi->ipi6_ifindex, ifnamebuf));
929
930         /* ND option check */
931         memset(&ndopts, 0, sizeof(ndopts));
932         TAILQ_INIT(&ndopts.opt_list);
933         if (nd6_options((struct nd_opt_hdr *)(rs + 1),
934                         len - sizeof(struct nd_router_solicit),
935                         &ndopts, NDOPT_FLAG_SRCLINKADDR)) {
936                 syslog(LOG_INFO,
937                     "<%s> ND option check failed for an RS from %s on %s",
938                     __func__,
939                     inet_ntop(AF_INET6, &from->sin6_addr, ntopbuf,
940                         sizeof(ntopbuf)),
941                     if_indextoname(pi->ipi6_ifindex, ifnamebuf));
942                 return;
943         }
944
945         /*
946          * If the IP source address is the unspecified address, there
947          * must be no source link-layer address option in the message.
948          * (RFC 4861 6.1.1)
949          */
950         if (IN6_IS_ADDR_UNSPECIFIED(&from->sin6_addr) &&
951             ndopts.opt_src_lladdr) {
952                 syslog(LOG_INFO,
953                     "<%s> RS from unspecified src on %s has a link-layer"
954                     " address option",
955                     __func__, if_indextoname(pi->ipi6_ifindex, ifnamebuf));
956                 goto done;
957         }
958
959         ifi = if_indextoifinfo(pi->ipi6_ifindex);
960         if (ifi == NULL) {
961                 syslog(LOG_INFO,
962                     "<%s> if (idx=%d) not found.  Why?",
963                     __func__, pi->ipi6_ifindex);
964                 goto done;
965         }
966         rai = ifi->ifi_rainfo;
967         if (rai == NULL) {
968                 syslog(LOG_INFO,
969                        "<%s> RS received on non advertising interface(%s)",
970                        __func__,
971                        if_indextoname(pi->ipi6_ifindex, ifnamebuf));
972                 goto done;
973         }
974
975         rai->rai_ifinfo->ifi_rsinput++;
976
977         /*
978          * Decide whether to send RA according to the rate-limit
979          * consideration.
980          */
981
982         /* record sockaddr waiting for RA, if possible */
983         sol = (struct soliciter *)malloc(sizeof(*sol));
984         if (sol) {
985                 sol->sol_addr = *from;
986                 /* XXX RFC 2553 need clarification on flowinfo */
987                 sol->sol_addr.sin6_flowinfo = 0;
988                 TAILQ_INSERT_TAIL(&rai->rai_soliciter, sol, sol_next);
989         }
990
991         /*
992          * If there is already a waiting RS packet, don't
993          * update the timer.
994          */
995         if (ifi->ifi_rs_waitcount++)
996                 goto done;
997
998         set_short_delay(ifi);
999
1000   done:
1001         free_ndopts(&ndopts);
1002         return;
1003 }
1004
1005 static void
1006 set_short_delay(struct ifinfo *ifi)
1007 {
1008         long delay;     /* must not be greater than 1000000 */
1009         struct timeval interval, now, min_delay, tm_tmp, *rest;
1010
1011         if (ifi->ifi_ra_timer == NULL)
1012                 return;
1013         /*
1014          * Compute a random delay. If the computed value
1015          * corresponds to a time later than the time the next
1016          * multicast RA is scheduled to be sent, ignore the random
1017          * delay and send the advertisement at the
1018          * already-scheduled time. RFC 4861 6.2.6
1019          */
1020 #ifdef HAVE_ARC4RANDOM
1021         delay = arc4random_uniform(MAX_RA_DELAY_TIME);
1022 #else
1023         delay = random() % MAX_RA_DELAY_TIME;
1024 #endif
1025         interval.tv_sec = 0;
1026         interval.tv_usec = delay;
1027         rest = rtadvd_timer_rest(ifi->ifi_ra_timer);
1028         if (TIMEVAL_LT(rest, &interval)) {
1029                 syslog(LOG_DEBUG, "<%s> random delay is larger than "
1030                     "the rest of the current timer", __func__);
1031                 interval = *rest;
1032         }
1033
1034         /*
1035          * If we sent a multicast Router Advertisement within
1036          * the last MIN_DELAY_BETWEEN_RAS seconds, schedule
1037          * the advertisement to be sent at a time corresponding to
1038          * MIN_DELAY_BETWEEN_RAS plus the random value after the
1039          * previous advertisement was sent.
1040          */
1041         gettimeofday(&now, NULL);
1042         TIMEVAL_SUB(&now, &ifi->ifi_ra_lastsent, &tm_tmp);
1043         min_delay.tv_sec = MIN_DELAY_BETWEEN_RAS;
1044         min_delay.tv_usec = 0;
1045         if (TIMEVAL_LT(&tm_tmp, &min_delay)) {
1046                 TIMEVAL_SUB(&min_delay, &tm_tmp, &min_delay);
1047                 TIMEVAL_ADD(&min_delay, &interval, &interval);
1048         }
1049         rtadvd_set_timer(&interval, ifi->ifi_ra_timer);
1050 }
1051
1052 static int
1053 check_accept_rtadv(int idx)
1054 {
1055         struct ifinfo *ifi;
1056
1057         TAILQ_FOREACH(ifi, &ifilist, ifi_next) {
1058                 if (ifi->ifi_ifindex == idx)
1059                         break;
1060         }
1061         if (ifi == NULL) {
1062                 syslog(LOG_DEBUG,
1063                     "<%s> if (idx=%d) not found.  Why?",
1064                     __func__, idx);
1065                 return (0);
1066         }
1067 #if (__FreeBSD_version < 900000)
1068         /*
1069          * RA_RECV: !ip6.forwarding && ip6.accept_rtadv
1070          * RA_SEND: ip6.forwarding
1071          */
1072         return ((getinet6sysctl(IPV6CTL_FORWARDING) == 0) &&
1073             (getinet6sysctl(IPV6CTL_ACCEPT_RTADV) == 1));
1074 #else
1075         /*
1076          * RA_RECV: ND6_IFF_ACCEPT_RTADV
1077          * RA_SEND: ip6.forwarding
1078          */
1079         if (update_ifinfo_nd_flags(ifi) != 0) {
1080                 syslog(LOG_ERR, "cannot get nd6 flags (idx=%d)", idx);
1081                 return (0);
1082         }
1083
1084         return (ifi->ifi_nd_flags & ND6_IFF_ACCEPT_RTADV);
1085 #endif
1086 }
1087
1088 static void
1089 ra_input(int len, struct nd_router_advert *nra,
1090          struct in6_pktinfo *pi, struct sockaddr_in6 *from)
1091 {
1092         struct rainfo *rai;
1093         struct ifinfo *ifi;
1094         char ntopbuf[INET6_ADDRSTRLEN];
1095         char ifnamebuf[IFNAMSIZ];
1096         union nd_opt ndopts;
1097         const char *on_off[] = {"OFF", "ON"};
1098         uint32_t reachabletime, retranstimer, mtu;
1099         int inconsistent = 0;
1100         int error;
1101
1102         syslog(LOG_DEBUG, "<%s> RA received from %s on %s", __func__,
1103             inet_ntop(AF_INET6, &from->sin6_addr, ntopbuf, sizeof(ntopbuf)),
1104             if_indextoname(pi->ipi6_ifindex, ifnamebuf));
1105
1106         /* ND option check */
1107         memset(&ndopts, 0, sizeof(ndopts));
1108         TAILQ_INIT(&ndopts.opt_list);
1109         error = nd6_options((struct nd_opt_hdr *)(nra + 1),
1110             len - sizeof(struct nd_router_advert), &ndopts,
1111             NDOPT_FLAG_SRCLINKADDR | NDOPT_FLAG_PREFIXINFO | NDOPT_FLAG_MTU |
1112             NDOPT_FLAG_RDNSS | NDOPT_FLAG_DNSSL);
1113         if (error) {
1114                 syslog(LOG_INFO,
1115                     "<%s> ND option check failed for an RA from %s on %s",
1116                     __func__,
1117                     inet_ntop(AF_INET6, &from->sin6_addr, ntopbuf,
1118                         sizeof(ntopbuf)), if_indextoname(pi->ipi6_ifindex,
1119                         ifnamebuf));
1120                 return;
1121         }
1122
1123         /*
1124          * RA consistency check according to RFC 4861 6.2.7
1125          */
1126         ifi = if_indextoifinfo(pi->ipi6_ifindex);
1127         if (ifi->ifi_rainfo == NULL) {
1128                 syslog(LOG_INFO,
1129                     "<%s> received RA from %s on non-advertising"
1130                     " interface(%s)",
1131                     __func__,
1132                     inet_ntop(AF_INET6, &from->sin6_addr, ntopbuf,
1133                         sizeof(ntopbuf)), if_indextoname(pi->ipi6_ifindex,
1134                         ifnamebuf));
1135                 goto done;
1136         }
1137         rai = ifi->ifi_rainfo;
1138         ifi->ifi_rainput++;
1139         syslog(LOG_DEBUG, "<%s> ifi->ifi_rainput = %" PRIu64, __func__,
1140             ifi->ifi_rainput);
1141
1142         /* Cur Hop Limit value */
1143         if (nra->nd_ra_curhoplimit && rai->rai_hoplimit &&
1144             nra->nd_ra_curhoplimit != rai->rai_hoplimit) {
1145                 syslog(LOG_NOTICE,
1146                     "CurHopLimit inconsistent on %s:"
1147                     " %d from %s, %d from us",
1148                     ifi->ifi_ifname, nra->nd_ra_curhoplimit,
1149                     inet_ntop(AF_INET6, &from->sin6_addr, ntopbuf,
1150                         sizeof(ntopbuf)), rai->rai_hoplimit);
1151                 inconsistent++;
1152         }
1153         /* M flag */
1154         if ((nra->nd_ra_flags_reserved & ND_RA_FLAG_MANAGED) !=
1155             rai->rai_managedflg) {
1156                 syslog(LOG_NOTICE,
1157                     "M flag inconsistent on %s:"
1158                     " %s from %s, %s from us",
1159                     ifi->ifi_ifname, on_off[!rai->rai_managedflg],
1160                     inet_ntop(AF_INET6, &from->sin6_addr, ntopbuf,
1161                         sizeof(ntopbuf)), on_off[rai->rai_managedflg]);
1162                 inconsistent++;
1163         }
1164         /* O flag */
1165         if ((nra->nd_ra_flags_reserved & ND_RA_FLAG_OTHER) !=
1166             rai->rai_otherflg) {
1167                 syslog(LOG_NOTICE,
1168                     "O flag inconsistent on %s:"
1169                     " %s from %s, %s from us",
1170                     ifi->ifi_ifname, on_off[!rai->rai_otherflg],
1171                     inet_ntop(AF_INET6, &from->sin6_addr, ntopbuf,
1172                         sizeof(ntopbuf)), on_off[rai->rai_otherflg]);
1173                 inconsistent++;
1174         }
1175         /* Reachable Time */
1176         reachabletime = ntohl(nra->nd_ra_reachable);
1177         if (reachabletime && rai->rai_reachabletime &&
1178             reachabletime != rai->rai_reachabletime) {
1179                 syslog(LOG_NOTICE,
1180                     "ReachableTime inconsistent on %s:"
1181                     " %d from %s, %d from us",
1182                     ifi->ifi_ifname, reachabletime,
1183                     inet_ntop(AF_INET6, &from->sin6_addr, ntopbuf,
1184                         sizeof(ntopbuf)), rai->rai_reachabletime);
1185                 inconsistent++;
1186         }
1187         /* Retrans Timer */
1188         retranstimer = ntohl(nra->nd_ra_retransmit);
1189         if (retranstimer && rai->rai_retranstimer &&
1190             retranstimer != rai->rai_retranstimer) {
1191                 syslog(LOG_NOTICE,
1192                     "RetranceTimer inconsistent on %s:"
1193                     " %d from %s, %d from us",
1194                     ifi->ifi_ifname, retranstimer,
1195                     inet_ntop(AF_INET6, &from->sin6_addr, ntopbuf,
1196                         sizeof(ntopbuf)), rai->rai_retranstimer);
1197                 inconsistent++;
1198         }
1199         /* Values in the MTU options */
1200         if (ndopts.opt_mtu) {
1201                 mtu = ntohl(ndopts.opt_mtu->nd_opt_mtu_mtu);
1202                 if (mtu && rai->rai_linkmtu && mtu != rai->rai_linkmtu) {
1203                         syslog(LOG_NOTICE,
1204                             "MTU option value inconsistent on %s:"
1205                             " %d from %s, %d from us",
1206                             ifi->ifi_ifname, mtu,
1207                             inet_ntop(AF_INET6, &from->sin6_addr, ntopbuf,
1208                                 sizeof(ntopbuf)), rai->rai_linkmtu);
1209                         inconsistent++;
1210                 }
1211         }
1212         /* Preferred and Valid Lifetimes for prefixes */
1213         {
1214                 struct nd_optlist *nol;
1215
1216                 if (ndopts.opt_pi)
1217                         if (prefix_check(ndopts.opt_pi, rai, from))
1218                                 inconsistent++;
1219
1220                 TAILQ_FOREACH(nol, &ndopts.opt_list, nol_next)
1221                         if (prefix_check((struct nd_opt_prefix_info *)nol->nol_opt,
1222                                 rai, from))
1223                                 inconsistent++;
1224         }
1225
1226         if (inconsistent)
1227                 ifi->ifi_rainconsistent++;
1228
1229   done:
1230         free_ndopts(&ndopts);
1231         return;
1232 }
1233
1234 static uint32_t
1235 udiff(uint32_t u, uint32_t v)
1236 {
1237         return (u >= v ? u - v : v - u);
1238 }
1239
1240 /* return a non-zero value if the received prefix is inconsitent with ours */
1241 static int
1242 prefix_check(struct nd_opt_prefix_info *pinfo,
1243         struct rainfo *rai, struct sockaddr_in6 *from)
1244 {
1245         struct ifinfo *ifi;
1246         uint32_t preferred_time, valid_time;
1247         struct prefix *pfx;
1248         int inconsistent = 0;
1249         char ntopbuf[INET6_ADDRSTRLEN];
1250         char prefixbuf[INET6_ADDRSTRLEN];
1251         struct timeval now;
1252
1253 #if 0                           /* impossible */
1254         if (pinfo->nd_opt_pi_type != ND_OPT_PREFIX_INFORMATION)
1255                 return (0);
1256 #endif
1257         ifi = rai->rai_ifinfo;
1258         /*
1259          * log if the adveritsed prefix has link-local scope(sanity check?)
1260          */
1261         if (IN6_IS_ADDR_LINKLOCAL(&pinfo->nd_opt_pi_prefix))
1262                 syslog(LOG_INFO,
1263                     "<%s> link-local prefix %s/%d is advertised "
1264                     "from %s on %s",
1265                     __func__,
1266                     inet_ntop(AF_INET6, &pinfo->nd_opt_pi_prefix, prefixbuf,
1267                         sizeof(prefixbuf)),
1268                     pinfo->nd_opt_pi_prefix_len,
1269                     inet_ntop(AF_INET6, &from->sin6_addr, ntopbuf,
1270                         sizeof(ntopbuf)), ifi->ifi_ifname);
1271
1272         if ((pfx = find_prefix(rai, &pinfo->nd_opt_pi_prefix,
1273                 pinfo->nd_opt_pi_prefix_len)) == NULL) {
1274                 syslog(LOG_INFO,
1275                     "<%s> prefix %s/%d from %s on %s is not in our list",
1276                     __func__,
1277                     inet_ntop(AF_INET6, &pinfo->nd_opt_pi_prefix, prefixbuf,
1278                         sizeof(prefixbuf)),
1279                     pinfo->nd_opt_pi_prefix_len,
1280                     inet_ntop(AF_INET6, &from->sin6_addr, ntopbuf,
1281                         sizeof(ntopbuf)), ifi->ifi_ifname);
1282                 return (0);
1283         }
1284
1285         preferred_time = ntohl(pinfo->nd_opt_pi_preferred_time);
1286         if (pfx->pfx_pltimeexpire) {
1287                 /*
1288                  * The lifetime is decremented in real time, so we should
1289                  * compare the expiration time.
1290                  * (RFC 2461 Section 6.2.7.)
1291                  * XXX: can we really expect that all routers on the link
1292                  * have synchronized clocks?
1293                  */
1294                 gettimeofday(&now, NULL);
1295                 preferred_time += now.tv_sec;
1296
1297                 if (!pfx->pfx_timer && rai->rai_clockskew &&
1298                     udiff(preferred_time, pfx->pfx_pltimeexpire) > rai->rai_clockskew) {
1299                         syslog(LOG_INFO,
1300                             "<%s> preferred lifetime for %s/%d"
1301                             " (decr. in real time) inconsistent on %s:"
1302                             " %" PRIu32 " from %s, %" PRIu32 " from us",
1303                             __func__,
1304                             inet_ntop(AF_INET6, &pinfo->nd_opt_pi_prefix, prefixbuf,
1305                                 sizeof(prefixbuf)),
1306                             pinfo->nd_opt_pi_prefix_len,
1307                             ifi->ifi_ifname, preferred_time,
1308                             inet_ntop(AF_INET6, &from->sin6_addr, ntopbuf,
1309                                 sizeof(ntopbuf)), pfx->pfx_pltimeexpire);
1310                         inconsistent++;
1311                 }
1312         } else if (!pfx->pfx_timer && preferred_time != pfx->pfx_preflifetime)
1313                 syslog(LOG_INFO,
1314                     "<%s> preferred lifetime for %s/%d"
1315                     " inconsistent on %s:"
1316                     " %d from %s, %d from us",
1317                     __func__,
1318                     inet_ntop(AF_INET6, &pinfo->nd_opt_pi_prefix, prefixbuf,
1319                         sizeof(prefixbuf)),
1320                     pinfo->nd_opt_pi_prefix_len,
1321                     ifi->ifi_ifname, preferred_time,
1322                     inet_ntop(AF_INET6, &from->sin6_addr, ntopbuf,
1323                         sizeof(ntopbuf)), pfx->pfx_preflifetime);
1324
1325         valid_time = ntohl(pinfo->nd_opt_pi_valid_time);
1326         if (pfx->pfx_vltimeexpire) {
1327                 gettimeofday(&now, NULL);
1328                 valid_time += now.tv_sec;
1329
1330                 if (!pfx->pfx_timer && rai->rai_clockskew &&
1331                     udiff(valid_time, pfx->pfx_vltimeexpire) > rai->rai_clockskew) {
1332                         syslog(LOG_INFO,
1333                             "<%s> valid lifetime for %s/%d"
1334                             " (decr. in real time) inconsistent on %s:"
1335                             " %d from %s, %" PRIu32 " from us",
1336                             __func__,
1337                             inet_ntop(AF_INET6, &pinfo->nd_opt_pi_prefix, prefixbuf,
1338                                 sizeof(prefixbuf)),
1339                             pinfo->nd_opt_pi_prefix_len,
1340                             ifi->ifi_ifname, preferred_time,
1341                             inet_ntop(AF_INET6, &from->sin6_addr, ntopbuf,
1342                                 sizeof(ntopbuf)), pfx->pfx_vltimeexpire);
1343                         inconsistent++;
1344                 }
1345         } else if (!pfx->pfx_timer && valid_time != pfx->pfx_validlifetime) {
1346                 syslog(LOG_INFO,
1347                     "<%s> valid lifetime for %s/%d"
1348                     " inconsistent on %s:"
1349                     " %d from %s, %d from us",
1350                     __func__,
1351                     inet_ntop(AF_INET6, &pinfo->nd_opt_pi_prefix, prefixbuf,
1352                         sizeof(prefixbuf)),
1353                     pinfo->nd_opt_pi_prefix_len,
1354                     ifi->ifi_ifname, valid_time,
1355                     inet_ntop(AF_INET6, &from->sin6_addr, ntopbuf,
1356                         sizeof(ntopbuf)), pfx->pfx_validlifetime);
1357                 inconsistent++;
1358         }
1359
1360         return (inconsistent);
1361 }
1362
1363 struct prefix *
1364 find_prefix(struct rainfo *rai, struct in6_addr *prefix, int plen)
1365 {
1366         struct prefix *pfx;
1367         int bytelen, bitlen;
1368         char bitmask;
1369
1370         TAILQ_FOREACH(pfx, &rai->rai_prefix, pfx_next) {
1371                 if (plen != pfx->pfx_prefixlen)
1372                         continue;
1373
1374                 bytelen = plen / 8;
1375                 bitlen = plen % 8;
1376                 bitmask = 0xff << (8 - bitlen);
1377
1378                 if (memcmp((void *)prefix, (void *)&pfx->pfx_prefix, bytelen))
1379                         continue;
1380
1381                 if (bitlen == 0 ||
1382                     ((prefix->s6_addr[bytelen] & bitmask) ==
1383                      (pfx->pfx_prefix.s6_addr[bytelen] & bitmask))) {
1384                         return (pfx);
1385                 }
1386         }
1387
1388         return (NULL);
1389 }
1390
1391 /* check if p0/plen0 matches p1/plen1; return 1 if matches, otherwise 0. */
1392 int
1393 prefix_match(struct in6_addr *p0, int plen0,
1394         struct in6_addr *p1, int plen1)
1395 {
1396         int bytelen, bitlen;
1397         char bitmask;
1398
1399         if (plen0 < plen1)
1400                 return (0);
1401
1402         bytelen = plen1 / 8;
1403         bitlen = plen1 % 8;
1404         bitmask = 0xff << (8 - bitlen);
1405
1406         if (memcmp((void *)p0, (void *)p1, bytelen))
1407                 return (0);
1408
1409         if (bitlen == 0 ||
1410             ((p0->s6_addr[bytelen] & bitmask) ==
1411              (p1->s6_addr[bytelen] & bitmask))) {
1412                 return (1);
1413         }
1414
1415         return (0);
1416 }
1417
1418 static int
1419 nd6_options(struct nd_opt_hdr *hdr, int limit,
1420         union nd_opt *ndopts, uint32_t optflags)
1421 {
1422         int optlen = 0;
1423
1424         for (; limit > 0; limit -= optlen) {
1425                 if ((size_t)limit < sizeof(struct nd_opt_hdr)) {
1426                         syslog(LOG_INFO, "<%s> short option header", __func__);
1427                         goto bad;
1428                 }
1429
1430                 hdr = (struct nd_opt_hdr *)((caddr_t)hdr + optlen);
1431                 if (hdr->nd_opt_len == 0) {
1432                         syslog(LOG_INFO,
1433                             "<%s> bad ND option length(0) (type = %d)",
1434                             __func__, hdr->nd_opt_type);
1435                         goto bad;
1436                 }
1437                 optlen = hdr->nd_opt_len << 3;
1438                 if (optlen > limit) {
1439                         syslog(LOG_INFO, "<%s> short option", __func__);
1440                         goto bad;
1441                 }
1442
1443                 if (hdr->nd_opt_type > ND_OPT_MTU &&
1444                     hdr->nd_opt_type != ND_OPT_RDNSS &&
1445                     hdr->nd_opt_type != ND_OPT_DNSSL) {
1446                         syslog(LOG_INFO, "<%s> unknown ND option(type %d)",
1447                             __func__, hdr->nd_opt_type);
1448                         continue;
1449                 }
1450
1451                 if ((ndopt_flags[hdr->nd_opt_type] & optflags) == 0) {
1452                         syslog(LOG_INFO, "<%s> unexpected ND option(type %d)",
1453                             __func__, hdr->nd_opt_type);
1454                         continue;
1455                 }
1456
1457                 /*
1458                  * Option length check.  Do it here for all fixed-length
1459                  * options.
1460                  */
1461                 switch (hdr->nd_opt_type) {
1462                 case ND_OPT_MTU:
1463                         if (optlen == sizeof(struct nd_opt_mtu))
1464                                 break;
1465                         goto skip;
1466                 case ND_OPT_RDNSS:
1467                         if (optlen >= 24 &&
1468                             (optlen - sizeof(struct nd_opt_rdnss)) % 16 == 0)
1469                                 break;
1470                         goto skip;
1471                 case ND_OPT_DNSSL:
1472                         if (optlen >= 16 &&
1473                             (optlen - sizeof(struct nd_opt_dnssl)) % 8 == 0)
1474                                 break;
1475                         goto skip;
1476                 case ND_OPT_PREFIX_INFORMATION:
1477                         if (optlen == sizeof(struct nd_opt_prefix_info))
1478                                 break;
1479 skip:
1480                         syslog(LOG_INFO, "<%s> invalid option length",
1481                             __func__);
1482                         continue;
1483                 }
1484
1485                 switch (hdr->nd_opt_type) {
1486                 case ND_OPT_TARGET_LINKADDR:
1487                 case ND_OPT_REDIRECTED_HEADER:
1488                 case ND_OPT_RDNSS:
1489                 case ND_OPT_DNSSL:
1490                         break;  /* we don't care about these options */
1491                 case ND_OPT_SOURCE_LINKADDR:
1492                 case ND_OPT_MTU:
1493                         if (ndopts->opt_array[hdr->nd_opt_type]) {
1494                                 syslog(LOG_INFO,
1495                                     "<%s> duplicated ND option (type = %d)",
1496                                     __func__, hdr->nd_opt_type);
1497                         }
1498                         ndopts->opt_array[hdr->nd_opt_type] = hdr;
1499                         break;
1500                 case ND_OPT_PREFIX_INFORMATION:
1501                 {
1502                         struct nd_optlist *nol;
1503
1504                         if (ndopts->opt_pi == 0) {
1505                                 ndopts->opt_pi =
1506                                     (struct nd_opt_prefix_info *)hdr;
1507                                 continue;
1508                         }
1509                         nol = malloc(sizeof(*nol));
1510                         if (nol == NULL) {
1511                                 syslog(LOG_ERR, "<%s> can't allocate memory",
1512                                     __func__);
1513                                 goto bad;
1514                         }
1515                         nol->nol_opt = hdr;
1516                         TAILQ_INSERT_TAIL(&(ndopts->opt_list), nol, nol_next);
1517
1518                         break;
1519                 }
1520                 default:        /* impossible */
1521                         break;
1522                 }
1523         }
1524
1525         return (0);
1526
1527   bad:
1528         free_ndopts(ndopts);
1529
1530         return (-1);
1531 }
1532
1533 static void
1534 free_ndopts(union nd_opt *ndopts)
1535 {
1536         struct nd_optlist *nol;
1537
1538         while ((nol = TAILQ_FIRST(&ndopts->opt_list)) != NULL) {
1539                 TAILQ_REMOVE(&ndopts->opt_list, nol, nol_next);
1540                 free(nol);
1541         }
1542 }
1543
1544 void
1545 sock_open(struct sockinfo *s)
1546 {
1547         struct icmp6_filter filt;
1548         int on;
1549         /* XXX: should be max MTU attached to the node */
1550         static char answer[1500];
1551
1552         syslog(LOG_DEBUG, "<%s> enter", __func__);
1553
1554         if (s == NULL) {
1555                 syslog(LOG_ERR, "<%s> internal error", __func__);
1556                 exit(1);
1557         }
1558         rcvcmsgbuflen = CMSG_SPACE(sizeof(struct in6_pktinfo)) +
1559             CMSG_SPACE(sizeof(int));
1560         rcvcmsgbuf = (char *)malloc(rcvcmsgbuflen);
1561         if (rcvcmsgbuf == NULL) {
1562                 syslog(LOG_ERR, "<%s> not enough core", __func__);
1563                 exit(1);
1564         }
1565
1566         sndcmsgbuflen = CMSG_SPACE(sizeof(struct in6_pktinfo)) +
1567             CMSG_SPACE(sizeof(int));
1568         sndcmsgbuf = (char *)malloc(sndcmsgbuflen);
1569         if (sndcmsgbuf == NULL) {
1570                 syslog(LOG_ERR, "<%s> not enough core", __func__);
1571                 exit(1);
1572         }
1573
1574         if ((s->si_fd = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6)) < 0) {
1575                 syslog(LOG_ERR, "<%s> socket: %s", __func__, strerror(errno));
1576                 exit(1);
1577         }
1578         /* specify to tell receiving interface */
1579         on = 1;
1580         if (setsockopt(s->si_fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on,
1581             sizeof(on)) < 0) {
1582                 syslog(LOG_ERR, "<%s> IPV6_RECVPKTINFO: %s", __func__,
1583                     strerror(errno));
1584                 exit(1);
1585         }
1586         on = 1;
1587         /* specify to tell value of hoplimit field of received IP6 hdr */
1588         if (setsockopt(s->si_fd, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &on,
1589                 sizeof(on)) < 0) {
1590                 syslog(LOG_ERR, "<%s> IPV6_RECVHOPLIMIT: %s", __func__,
1591                     strerror(errno));
1592                 exit(1);
1593         }
1594         ICMP6_FILTER_SETBLOCKALL(&filt);
1595         ICMP6_FILTER_SETPASS(ND_ROUTER_SOLICIT, &filt);
1596         ICMP6_FILTER_SETPASS(ND_ROUTER_ADVERT, &filt);
1597         if (mcastif != NULL)
1598                 ICMP6_FILTER_SETPASS(ICMP6_ROUTER_RENUMBERING, &filt);
1599
1600         if (setsockopt(s->si_fd, IPPROTO_ICMPV6, ICMP6_FILTER, &filt,
1601             sizeof(filt)) < 0) {
1602                 syslog(LOG_ERR, "<%s> IICMP6_FILTER: %s",
1603                     __func__, strerror(errno));
1604                 exit(1);
1605         }
1606
1607         /* initialize msghdr for receiving packets */
1608         rcviov[0].iov_base = (caddr_t)answer;
1609         rcviov[0].iov_len = sizeof(answer);
1610         rcvmhdr.msg_name = (caddr_t)&rcvfrom;
1611         rcvmhdr.msg_namelen = sizeof(rcvfrom);
1612         rcvmhdr.msg_iov = rcviov;
1613         rcvmhdr.msg_iovlen = 1;
1614         rcvmhdr.msg_control = (caddr_t) rcvcmsgbuf;
1615         rcvmhdr.msg_controllen = rcvcmsgbuflen;
1616
1617         /* initialize msghdr for sending packets */
1618         sndmhdr.msg_namelen = sizeof(struct sockaddr_in6);
1619         sndmhdr.msg_iov = sndiov;
1620         sndmhdr.msg_iovlen = 1;
1621         sndmhdr.msg_control = (caddr_t)sndcmsgbuf;
1622         sndmhdr.msg_controllen = sndcmsgbuflen;
1623
1624         return;
1625 }
1626
1627 /* open a routing socket to watch the routing table */
1628 static void
1629 rtsock_open(struct sockinfo *s)
1630 {
1631         if (s == NULL) {
1632                 syslog(LOG_ERR, "<%s> internal error", __func__);
1633                 exit(1);
1634         }
1635         if ((s->si_fd = socket(PF_ROUTE, SOCK_RAW, 0)) < 0) {
1636                 syslog(LOG_ERR,
1637                     "<%s> socket: %s", __func__, strerror(errno));
1638                 exit(1);
1639         }
1640 }
1641
1642 struct ifinfo *
1643 if_indextoifinfo(int idx)
1644 {
1645         struct ifinfo *ifi;
1646         char *name, name0[IFNAMSIZ];
1647
1648         /* Check if the interface has a valid name or not. */
1649         if (if_indextoname(idx, name0) == NULL)
1650                 return (NULL);
1651
1652         TAILQ_FOREACH(ifi, &ifilist, ifi_next) {
1653                 if (ifi->ifi_ifindex == idx)
1654                         return (ifi);
1655         }
1656
1657         if (ifi != NULL)
1658                 syslog(LOG_DEBUG, "<%s> ifi found (idx=%d)",
1659                     __func__, idx);
1660         else
1661                 syslog(LOG_DEBUG, "<%s> ifi not found (idx=%d)",
1662                     __func__, idx);
1663
1664         return (NULL);          /* search failed */
1665 }
1666
1667 void
1668 ra_output(struct ifinfo *ifi)
1669 {
1670         int i;
1671         struct cmsghdr *cm;
1672         struct in6_pktinfo *pi;
1673         struct soliciter *sol;
1674         struct rainfo *rai;
1675
1676         switch (ifi->ifi_state) {
1677         case IFI_STATE_CONFIGURED:
1678                 rai = ifi->ifi_rainfo;
1679                 break;
1680         case IFI_STATE_TRANSITIVE:
1681                 rai = ifi->ifi_rainfo_trans;
1682                 break;
1683         case IFI_STATE_UNCONFIGURED:
1684                 syslog(LOG_DEBUG, "<%s> %s is unconfigured.  "
1685                     "Skip sending RAs.",
1686                     __func__, ifi->ifi_ifname);
1687                 return;
1688         default:
1689                 rai = NULL;
1690         }
1691         if (rai == NULL) {
1692                 syslog(LOG_DEBUG, "<%s> rainfo is NULL on %s."
1693                     "Skip sending RAs.",
1694                     __func__, ifi->ifi_ifname);
1695                 return;
1696         }
1697         if (!(ifi->ifi_flags & IFF_UP)) {
1698                 syslog(LOG_DEBUG, "<%s> %s is not up.  "
1699                     "Skip sending RAs.",
1700                     __func__, ifi->ifi_ifname);
1701                 return;
1702         }
1703         /*
1704          * Check lifetime, ACCEPT_RTADV flag, and ip6.forwarding.
1705          *
1706          * (lifetime == 0) = output
1707          * (lifetime != 0 && (check_accept_rtadv()) = no output
1708          *
1709          * Basically, hosts MUST NOT send Router Advertisement
1710          * messages at any time (RFC 4861, Section 6.2.3). However, it
1711          * would sometimes be useful to allow hosts to advertise some
1712          * parameters such as prefix information and link MTU. Thus,
1713          * we allow hosts to invoke rtadvd only when router lifetime
1714          * (on every advertising interface) is explicitly set
1715          * zero. (see also the above section)
1716          */
1717         syslog(LOG_DEBUG,
1718             "<%s> check lifetime=%d, ACCEPT_RTADV=%d, ip6.forwarding=%d "
1719             "on %s", __func__,
1720             rai->rai_lifetime,
1721             check_accept_rtadv(ifi->ifi_ifindex),
1722             getinet6sysctl(IPV6CTL_FORWARDING),
1723             ifi->ifi_ifname);
1724
1725         if (rai->rai_lifetime != 0) {
1726                 if (getinet6sysctl(IPV6CTL_FORWARDING) == 0) {
1727                         syslog(LOG_ERR,
1728                             "non-zero lifetime RA "
1729                             "but net.inet6.ip6.forwarding=0.  "
1730                             "Ignored.");
1731                         return;
1732                 }
1733                 if (check_accept_rtadv(ifi->ifi_ifindex)) {
1734                         syslog(LOG_ERR,
1735                             "non-zero lifetime RA "
1736                             "on RA receiving interface %s."
1737                             "  Ignored.", ifi->ifi_ifname);
1738                         return;
1739                 }
1740         }
1741
1742         make_packet(rai);       /* XXX: inefficient */
1743
1744         sndmhdr.msg_name = (caddr_t)&sin6_linklocal_allnodes;
1745         sndmhdr.msg_iov[0].iov_base = (caddr_t)rai->rai_ra_data;
1746         sndmhdr.msg_iov[0].iov_len = rai->rai_ra_datalen;
1747
1748         cm = CMSG_FIRSTHDR(&sndmhdr);
1749         /* specify the outgoing interface */
1750         cm->cmsg_level = IPPROTO_IPV6;
1751         cm->cmsg_type = IPV6_PKTINFO;
1752         cm->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
1753         pi = (struct in6_pktinfo *)CMSG_DATA(cm);
1754         memset(&pi->ipi6_addr, 0, sizeof(pi->ipi6_addr));       /*XXX*/
1755         pi->ipi6_ifindex = ifi->ifi_ifindex;
1756
1757         /* specify the hop limit of the packet */
1758         {
1759                 int hoplimit = 255;
1760
1761                 cm = CMSG_NXTHDR(&sndmhdr, cm);
1762                 cm->cmsg_level = IPPROTO_IPV6;
1763                 cm->cmsg_type = IPV6_HOPLIMIT;
1764                 cm->cmsg_len = CMSG_LEN(sizeof(int));
1765                 memcpy(CMSG_DATA(cm), &hoplimit, sizeof(int));
1766         }
1767
1768         syslog(LOG_DEBUG,
1769             "<%s> send RA on %s, # of RS waitings = %d",
1770             __func__, ifi->ifi_ifname, ifi->ifi_rs_waitcount);
1771
1772         i = sendmsg(sock.si_fd, &sndmhdr, 0);
1773
1774         if (i < 0 || (size_t)i != rai->rai_ra_datalen)  {
1775                 if (i < 0) {
1776                         syslog(LOG_ERR, "<%s> sendmsg on %s: %s",
1777                             __func__, ifi->ifi_ifname,
1778                             strerror(errno));
1779                 }
1780         }
1781
1782         /*
1783          * unicast advertisements
1784          * XXX commented out.  reason: though spec does not forbit it, unicast
1785          * advert does not really help
1786          */
1787         while ((sol = TAILQ_FIRST(&rai->rai_soliciter)) != NULL) {
1788                 TAILQ_REMOVE(&rai->rai_soliciter, sol, sol_next);
1789                 free(sol);
1790         }
1791
1792         /* update timestamp */
1793         gettimeofday(&ifi->ifi_ra_lastsent, NULL);
1794
1795         /* update counter */
1796         ifi->ifi_rs_waitcount = 0;
1797         ifi->ifi_raoutput++;
1798
1799         switch (ifi->ifi_state) {
1800         case IFI_STATE_CONFIGURED:
1801                 if (ifi->ifi_burstcount > 0)
1802                         ifi->ifi_burstcount--;
1803                 break;
1804         case IFI_STATE_TRANSITIVE:
1805                 ifi->ifi_burstcount--;
1806                 if (ifi->ifi_burstcount == 0) {
1807                         if (ifi->ifi_rainfo == ifi->ifi_rainfo_trans) {
1808                                 /* Inital burst finished. */
1809                                 if (ifi->ifi_rainfo_trans != NULL)
1810                                         ifi->ifi_rainfo_trans = NULL;
1811                         }
1812
1813                         /* Remove burst RA information */
1814                         if (ifi->ifi_rainfo_trans != NULL) {
1815                                 rm_rainfo(ifi->ifi_rainfo_trans);
1816                                 ifi->ifi_rainfo_trans = NULL;
1817                         }
1818
1819                         if (ifi->ifi_rainfo != NULL) {
1820                                 /*
1821                                  * TRANSITIVE -> CONFIGURED
1822                                  *
1823                                  * After initial burst or transition from
1824                                  * one configuration to another,
1825                                  * ifi_rainfo always points to the next RA
1826                                  * information.
1827                                  */
1828                                 ifi->ifi_state = IFI_STATE_CONFIGURED;
1829                                 syslog(LOG_DEBUG,
1830                                     "<%s> ifname=%s marked as "
1831                                     "CONFIGURED.", __func__,
1832                                     ifi->ifi_ifname);
1833                         } else {
1834                                 /*
1835                                  * TRANSITIVE -> UNCONFIGURED
1836                                  *
1837                                  * If ifi_rainfo points to NULL, this
1838                                  * interface is shutting down.
1839                                  *
1840                                  */
1841                                 int error;
1842
1843                                 ifi->ifi_state = IFI_STATE_UNCONFIGURED;
1844                                 syslog(LOG_DEBUG,
1845                                     "<%s> ifname=%s marked as "
1846                                     "UNCONFIGURED.", __func__,
1847                                     ifi->ifi_ifname);
1848                                 error = sock_mc_leave(&sock,
1849                                     ifi->ifi_ifindex);
1850                                 if (error)
1851                                         exit(1);
1852                         }
1853                 }
1854                 break;
1855         }
1856 }
1857
1858 /* process RA timer */
1859 struct rtadvd_timer *
1860 ra_timeout(void *arg)
1861 {
1862         struct ifinfo *ifi;
1863
1864         ifi = (struct ifinfo *)arg;
1865         syslog(LOG_DEBUG, "<%s> RA timer on %s is expired",
1866             __func__, ifi->ifi_ifname);
1867
1868         ra_output(ifi);
1869
1870         return (ifi->ifi_ra_timer);
1871 }
1872
1873 /* update RA timer */
1874 void
1875 ra_timer_update(void *arg, struct timeval *tm)
1876 {
1877         uint16_t interval;
1878         struct rainfo *rai;
1879         struct ifinfo *ifi;
1880
1881         ifi = (struct ifinfo *)arg;
1882         rai = ifi->ifi_rainfo;
1883         interval = 0;
1884
1885         switch (ifi->ifi_state) {
1886         case IFI_STATE_UNCONFIGURED:
1887                 return;
1888                 break;
1889         case IFI_STATE_CONFIGURED:
1890                 /*
1891                  * Whenever a multicast advertisement is sent from
1892                  * an interface, the timer is reset to a
1893                  * uniformly-distributed random value between the
1894                  * interface's configured MinRtrAdvInterval and
1895                  * MaxRtrAdvInterval (RFC4861 6.2.4).
1896                  */
1897                 interval = rai->rai_mininterval;
1898 #ifdef HAVE_ARC4RANDOM
1899                 interval += arc4random_uniform(rai->rai_maxinterval -
1900                     rai->rai_mininterval);
1901 #else
1902                 interval += random() % (rai->rai_maxinterval -
1903                     rai->rai_mininterval);
1904 #endif
1905                 break;
1906         case IFI_STATE_TRANSITIVE:
1907                 /*
1908                  * For the first few advertisements (up to
1909                  * MAX_INITIAL_RTR_ADVERTISEMENTS), if the randomly chosen
1910                  * interval is greater than
1911                  * MAX_INITIAL_RTR_ADVERT_INTERVAL, the timer SHOULD be
1912                  * set to MAX_INITIAL_RTR_ADVERT_INTERVAL instead.  (RFC
1913                  * 4861 6.2.4)
1914                  *
1915                  * In such cases, the router SHOULD transmit one or more
1916                  * (but not more than MAX_FINAL_RTR_ADVERTISEMENTS) final
1917                  * multicast Router Advertisements on the interface with a
1918                  * Router Lifetime field of zero.  (RFC 4861 6.2.5)
1919                  */
1920                 interval = ifi->ifi_burstinterval;
1921                 break;
1922         }
1923
1924         tm->tv_sec = interval;
1925         tm->tv_usec = 0;
1926
1927         syslog(LOG_DEBUG,
1928             "<%s> RA timer on %s is set to %ld:%ld",
1929             __func__, ifi->ifi_ifname,
1930             (long int)tm->tv_sec, (long int)tm->tv_usec);
1931
1932         return;
1933 }