]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/rtadvd/rtadvd.c
This commit was generated by cvs2svn to compensate for changes in r98005,
[FreeBSD/FreeBSD.git] / usr.sbin / rtadvd / rtadvd.c
1 /*      $FreeBSD$       */
2 /*      $KAME: rtadvd.c,v 1.50 2001/02/04 06:15:15 itojun Exp $ */
3
4 /*
5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6  * All rights reserved.
7  * 
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the project nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  * 
20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32
33 #include <sys/param.h>
34 #include <sys/socket.h>
35 #include <sys/uio.h>
36 #include <sys/time.h>
37 #include <sys/queue.h>
38
39 #include <net/if.h>
40 #include <net/route.h>
41 #include <net/if_dl.h>
42 #include <netinet/in.h>
43 #include <netinet/ip6.h>
44 #include <netinet6/ip6_var.h>
45 #include <netinet/icmp6.h>
46
47 #include <arpa/inet.h>
48
49 #include <time.h>
50 #include <unistd.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <err.h>
54 #include <errno.h>
55 #include <string.h>
56 #include <stdlib.h>
57 #include <syslog.h>
58 #include "rtadvd.h"
59 #include "rrenum.h"
60 #include "advcap.h"
61 #include "timer.h"
62 #include "if.h"
63 #include "config.h"
64 #include "dump.h"
65
66 struct msghdr rcvmhdr;
67 static u_char *rcvcmsgbuf;
68 static size_t rcvcmsgbuflen;
69 static u_char *sndcmsgbuf = NULL;
70 static size_t sndcmsgbuflen;
71 static int do_dump;
72 static int do_die;
73 struct msghdr sndmhdr;
74 struct iovec rcviov[2];
75 struct iovec sndiov[2];
76 struct sockaddr_in6 from;
77 struct sockaddr_in6 sin6_allnodes = {sizeof(sin6_allnodes), AF_INET6};
78 struct in6_addr in6a_site_allrouters;
79 static char *dumpfilename = "/var/run/rtadvd.dump"; /* XXX: should be configurable */
80 static char *pidfilename = "/var/run/rtadvd.pid"; /* should be configurable */
81 static char *mcastif;
82 int sock;
83 int rtsock = -1;
84 #ifdef MIP6
85 int mobileip6 = 0;
86 #endif
87 int accept_rr = 0;
88 int dflag = 0, sflag = 0;
89
90 u_char *conffile = NULL;
91
92 struct rainfo *ralist = NULL;
93 struct nd_optlist {
94         struct nd_optlist *next;
95         struct nd_opt_hdr *opt;
96 };
97 union nd_opts {
98         struct nd_opt_hdr *nd_opt_array[7];
99         struct {
100                 struct nd_opt_hdr *zero;
101                 struct nd_opt_hdr *src_lladdr;
102                 struct nd_opt_hdr *tgt_lladdr;
103                 struct nd_opt_prefix_info *pi;
104                 struct nd_opt_rd_hdr *rh;
105                 struct nd_opt_mtu *mtu;
106                 struct nd_optlist *list;
107         } nd_opt_each;
108 };
109 #define nd_opts_src_lladdr      nd_opt_each.src_lladdr
110 #define nd_opts_tgt_lladdr      nd_opt_each.tgt_lladdr
111 #define nd_opts_pi              nd_opt_each.pi
112 #define nd_opts_rh              nd_opt_each.rh
113 #define nd_opts_mtu             nd_opt_each.mtu
114 #define nd_opts_list            nd_opt_each.list
115
116 #define NDOPT_FLAG_SRCLINKADDR 0x1
117 #define NDOPT_FLAG_TGTLINKADDR 0x2
118 #define NDOPT_FLAG_PREFIXINFO 0x4
119 #define NDOPT_FLAG_RDHDR 0x8
120 #define NDOPT_FLAG_MTU 0x10
121
122 u_int32_t ndopt_flags[] = {
123         0, NDOPT_FLAG_SRCLINKADDR, NDOPT_FLAG_TGTLINKADDR,
124         NDOPT_FLAG_PREFIXINFO, NDOPT_FLAG_RDHDR, NDOPT_FLAG_MTU
125 };
126
127 int main __P((int, char *[]));
128 static void set_die __P((int));
129 static void die __P((void));
130 static void sock_open __P((void));
131 static void rtsock_open __P((void));
132 static void rtadvd_input __P((void));
133 static void rs_input __P((int, struct nd_router_solicit *,
134                           struct in6_pktinfo *, struct sockaddr_in6 *));
135 static void ra_input __P((int, struct nd_router_advert *,
136                           struct in6_pktinfo *, struct sockaddr_in6 *));
137 static int prefix_check __P((struct nd_opt_prefix_info *, struct rainfo *,
138                              struct sockaddr_in6 *));
139 static int nd6_options __P((struct nd_opt_hdr *, int,
140                             union nd_opts *, u_int32_t));
141 static void free_ndopts __P((union nd_opts *));
142 static void ra_output __P((struct rainfo *));
143 static void rtmsg_input __P((void));
144 static void rtadvd_set_dump_file __P((void));
145
146 int
147 main(argc, argv)
148         int argc;
149         char *argv[];
150 {
151         fd_set fdset;
152         int maxfd = 0;
153         struct timeval *timeout;
154         int i, ch;
155         int fflag = 0;
156         FILE *pidfp;
157         pid_t pid;
158
159         openlog("rtadvd", LOG_NDELAY|LOG_PID, LOG_DAEMON);
160
161         /* get command line options and arguments */
162 #ifdef MIP6
163 #define OPTIONS "c:dDfM:mRs"
164 #else
165 #define OPTIONS "c:dDfM:Rs"
166 #endif
167         while ((ch = getopt(argc, argv, OPTIONS)) != -1) {
168 #undef OPTIONS
169                 switch (ch) {
170                 case 'c':
171                         conffile = optarg;
172                         break;
173                 case 'd':
174                         dflag = 1;
175                         break;
176                 case 'D':
177                         dflag = 2;
178                         break;
179                 case 'f':
180                         fflag = 1;
181                         break;
182                 case 'M':
183                         mcastif = optarg;
184                         break;
185 #ifdef MIP6
186                 case 'm':
187                         mobileip6 = 1;
188                         break;
189 #endif
190                 case 'R':
191                         fprintf(stderr, "rtadvd: "
192                                 "the -R option is currently ignored.\n");
193                         /* accept_rr = 1; */
194                         /* run anyway... */
195                         break;
196                 case 's':
197                         sflag = 1;
198                         break;
199                 }
200         }
201         argc -= optind;
202         argv += optind;
203         if (argc == 0) {
204                 fprintf(stderr,
205 #ifdef MIP6
206                         "usage: rtadvd [-dDfMmRs] [-c conffile] "
207 #else
208                         "usage: rtadvd [-dDfMRs] [-c conffile] "
209 #endif
210                         "interfaces...\n");
211                 exit(1);
212         }
213
214         /* set log level */
215         if (dflag == 0)
216                 (void)setlogmask(LOG_UPTO(LOG_ERR));
217         if (dflag == 1)
218                 (void)setlogmask(LOG_UPTO(LOG_INFO));
219
220         /* timer initialization */
221         rtadvd_timer_init();
222
223         /* random value initialization */
224         srandom((u_long)time(NULL));
225
226         /* get iflist block from kernel */
227         init_iflist();
228
229         while (argc--)
230                 getconfig(*argv++);
231
232         if (inet_pton(AF_INET6, ALLNODES, &sin6_allnodes.sin6_addr) != 1) {
233                 fprintf(stderr, "fatal: inet_pton failed\n");
234                 exit(1);
235         }
236         sock_open();
237
238         if (!fflag)
239                 daemon(1, 0);
240
241         /* record the current PID */
242         pid = getpid();
243         if ((pidfp = fopen(pidfilename, "w")) == NULL) {
244                 syslog(LOG_ERR,
245                     "<%s> failed to open a log file(%s), run anyway.",
246                     __FUNCTION__, pidfilename);
247         } else {
248                 fprintf(pidfp, "%d\n", pid);
249                 fclose(pidfp);
250         }
251
252         FD_ZERO(&fdset);
253         FD_SET(sock, &fdset);
254         maxfd = sock;
255         if (sflag == 0) {
256                 rtsock_open();
257                 FD_SET(rtsock, &fdset);
258                 if (rtsock > sock)
259                         maxfd = rtsock;
260         } else
261                 rtsock = -1;
262
263         signal(SIGTERM, (void *)set_die);
264         signal(SIGUSR1, (void *)rtadvd_set_dump_file);
265
266         while (1) {
267                 struct fd_set select_fd = fdset; /* reinitialize */
268
269                 if (do_dump) {  /* SIGUSR1 */
270                         do_dump = 0;
271                         rtadvd_dump_file(dumpfilename);
272                 }
273
274                 if (do_die) {
275                         die();
276                         /*NOTREACHED*/
277                 }
278
279                 /* timer expiration check and reset the timer */
280                 timeout = rtadvd_check_timer();
281
282                 if (timeout != NULL) {
283                         syslog(LOG_DEBUG,
284                             "<%s> set timer to %ld:%ld. waiting for "
285                             "inputs or timeout", __FUNCTION__,
286                             (long int)timeout->tv_sec,
287                             (long int)timeout->tv_usec);
288                 } else {
289                         syslog(LOG_DEBUG,
290                             "<%s> there's no timer. waiting for inputs",
291                             __FUNCTION__);
292                 }
293
294                 if ((i = select(maxfd + 1, &select_fd,
295                                 NULL, NULL, timeout)) < 0) {
296                         /* EINTR would occur upon SIGUSR1 for status dump */
297                         if (errno != EINTR)
298                                 syslog(LOG_ERR, "<%s> select: %s",
299                                     __FUNCTION__, strerror(errno));
300                         continue;
301                 }
302                 if (i == 0)     /* timeout */
303                         continue;
304                 if (rtsock != -1 && FD_ISSET(rtsock, &select_fd))
305                         rtmsg_input();
306                 if (FD_ISSET(sock, &select_fd))
307                         rtadvd_input();
308         }
309         exit(0);                /* NOTREACHED */
310 }
311
312 static void
313 rtadvd_set_dump_file()
314 {
315         do_dump = 1;
316 }
317
318 static void
319 set_die(sig)
320         int sig;
321 {
322         do_die = 1;
323 }
324
325 static void
326 die()
327 {
328         struct rainfo *ra;
329         int i;
330         const int retrans = MAX_FINAL_RTR_ADVERTISEMENTS;
331
332         if (dflag > 1) {
333                 syslog(LOG_DEBUG, "<%s> cease to be an advertising router\n",
334                     __FUNCTION__);
335         }
336
337         for (ra = ralist; ra; ra = ra->next) {
338                 ra->lifetime = 0;
339                 make_packet(ra);
340         }
341         for (i = 0; i < retrans; i++) {
342                 for (ra = ralist; ra; ra = ra->next)
343                         ra_output(ra);
344                 sleep(MIN_DELAY_BETWEEN_RAS);
345         }
346         exit(0);
347         /*NOTREACHED*/
348 }
349
350 static void
351 rtmsg_input()
352 {
353         int n, type, ifindex = 0, plen;
354         size_t len;
355         char msg[2048], *next, *lim;
356         u_char ifname[IF_NAMESIZE];
357         struct prefix *prefix;
358         struct rainfo *rai;
359         struct in6_addr *addr;
360         char addrbuf[INET6_ADDRSTRLEN];
361
362         n = read(rtsock, msg, sizeof(msg));
363         if (dflag > 1) {
364                 syslog(LOG_DEBUG, "<%s> received a routing message "
365                     "(type = %d, len = %d)", __FUNCTION__, rtmsg_type(msg), n);
366         }
367         if (n > rtmsg_len(msg)) {
368                 /*
369                  * This usually won't happen for messages received on 
370                  * a routing socket.
371                  */
372                 if (dflag > 1)
373                         syslog(LOG_DEBUG,
374                             "<%s> received data length is larger than "
375                             "1st routing message len. multiple messages? "
376                             "read %d bytes, but 1st msg len = %d",
377                             __FUNCTION__, n, rtmsg_len(msg));
378 #if 0
379                 /* adjust length */
380                 n = rtmsg_len(msg);
381 #endif
382         }
383
384         lim = msg + n;
385         for (next = msg; next < lim; next += len) {
386                 int oldifflags;
387
388                 next = get_next_msg(next, lim, 0, &len,
389                                     RTADV_TYPE2BITMASK(RTM_ADD) |
390                                     RTADV_TYPE2BITMASK(RTM_DELETE) |
391                                     RTADV_TYPE2BITMASK(RTM_NEWADDR) |
392                                     RTADV_TYPE2BITMASK(RTM_DELADDR) |
393                                     RTADV_TYPE2BITMASK(RTM_IFINFO));
394                 if (len == 0)
395                         break;
396                 type = rtmsg_type(next);
397                 switch (type) {
398                 case RTM_ADD:
399                 case RTM_DELETE:
400                         ifindex = get_rtm_ifindex(next);
401                         break;
402                 case RTM_NEWADDR:
403                 case RTM_DELADDR:
404                         ifindex = get_ifam_ifindex(next);
405                         break;
406                 case RTM_IFINFO:
407                         ifindex = get_ifm_ifindex(next);
408                         break;
409                 default:
410                         /* should not reach here */
411                         if (dflag > 1) {
412                                 syslog(LOG_DEBUG,
413                                        "<%s:%d> unknown rtmsg %d on %s",
414                                        __FUNCTION__, __LINE__, type,
415                                        if_indextoname(ifindex, ifname));
416                         }
417                         continue;
418                 }
419
420                 if ((rai = if_indextorainfo(ifindex)) == NULL) {
421                         if (dflag > 1) {
422                                 syslog(LOG_DEBUG,
423                                        "<%s> route changed on "
424                                        "non advertising interface(%s)",
425                                        __FUNCTION__,
426                                        if_indextoname(ifindex, ifname));
427                         }
428                         continue;
429                 }
430                 oldifflags = iflist[ifindex]->ifm_flags;
431
432                 switch (type) {
433                 case RTM_ADD:
434                         /* init ifflags because it may have changed */
435                         iflist[ifindex]->ifm_flags =
436                             if_getflags(ifindex, iflist[ifindex]->ifm_flags);
437
438                         if (sflag)
439                                 break;  /* we aren't interested in prefixes  */
440
441                         addr = get_addr(msg);
442                         plen = get_prefixlen(msg);
443                         /* sanity check for plen */
444                         /* as RFC2373, prefixlen is at least 4 */
445                         if (plen < 4 || plen > 127) {
446                                 syslog(LOG_INFO, "<%s> new interface route's"
447                                     "plen %d is invalid for a prefix",
448                                     __FUNCTION__, plen);
449                                 break;
450                         }
451                         prefix = find_prefix(rai, addr, plen);
452                         if (prefix) {
453                                 if (dflag > 1) {
454                                         syslog(LOG_DEBUG,
455                                             "<%s> new prefix(%s/%d) "
456                                             "added on %s, "
457                                             "but it was already in list",
458                                             __FUNCTION__,
459                                             inet_ntop(AF_INET6, addr,
460                                             (char *)addrbuf, INET6_ADDRSTRLEN),
461                                             plen, rai->ifname);
462                                 }
463                                 break;
464                         }
465                         make_prefix(rai, ifindex, addr, plen);
466                         break;
467                 case RTM_DELETE:
468                         /* init ifflags because it may have changed */
469                         iflist[ifindex]->ifm_flags =
470                             if_getflags(ifindex, iflist[ifindex]->ifm_flags);
471
472                         if (sflag)
473                                 break;
474
475                         addr = get_addr(msg);
476                         plen = get_prefixlen(msg);
477                         /* sanity check for plen */
478                         /* as RFC2373, prefixlen is at least 4 */
479                         if (plen < 4 || plen > 127) {
480                                 syslog(LOG_INFO,
481                                     "<%s> deleted interface route's "
482                                     "plen %d is invalid for a prefix",
483                                     __FUNCTION__, plen);
484                                 break;
485                         }
486                         prefix = find_prefix(rai, addr, plen);
487                         if (prefix == NULL) {
488                                 if (dflag > 1) {
489                                         syslog(LOG_DEBUG,
490                                             "<%s> prefix(%s/%d) was "
491                                             "deleted on %s, "
492                                             "but it was not in list",
493                                             __FUNCTION__,
494                                             inet_ntop(AF_INET6, addr,
495                                             (char *)addrbuf, INET6_ADDRSTRLEN),
496                                             plen, rai->ifname);
497                                 }
498                                 break;
499                         }
500                         delete_prefix(rai, prefix);
501                         break;
502                 case RTM_NEWADDR:
503                 case RTM_DELADDR:
504                         /* init ifflags because it may have changed */
505                         iflist[ifindex]->ifm_flags =
506                             if_getflags(ifindex, iflist[ifindex]->ifm_flags);
507                         break;
508                 case RTM_IFINFO:
509                         iflist[ifindex]->ifm_flags = get_ifm_flags(next);
510                         break;
511                 default:
512                         /* should not reach here */
513                         if (dflag > 1) {
514                                 syslog(LOG_DEBUG,
515                                     "<%s:%d> unknown rtmsg %d on %s",
516                                     __FUNCTION__, __LINE__, type,
517                                     if_indextoname(ifindex, ifname));
518                         }
519                         return;
520                 }
521
522                 /* check if an interface flag is changed */
523                 if ((oldifflags & IFF_UP) != 0 &&       /* UP to DOWN */
524                     (iflist[ifindex]->ifm_flags & IFF_UP) == 0) {
525                         syslog(LOG_INFO,
526                             "<%s> interface %s becomes down. stop timer.",
527                             __FUNCTION__, rai->ifname);
528                         rtadvd_remove_timer(&rai->timer);
529                 } else if ((oldifflags & IFF_UP) == 0 &&        /* DOWN to UP */
530                          (iflist[ifindex]->ifm_flags & IFF_UP) != 0) {
531                         syslog(LOG_INFO,
532                             "<%s> interface %s becomes up. restart timer.",
533                             __FUNCTION__, rai->ifname);
534
535                         rai->initcounter = 0; /* reset the counter */
536                         rai->waiting = 0; /* XXX */
537                         rai->timer = rtadvd_add_timer(ra_timeout,
538                             ra_timer_update, rai, rai);
539                         ra_timer_update((void *)rai, &rai->timer->tm);
540                         rtadvd_set_timer(&rai->timer->tm, rai->timer);
541                 }
542         }
543
544         return;
545 }
546
547 void
548 rtadvd_input()
549 {
550         int i;
551         int *hlimp = NULL;
552 #ifdef OLDRAWSOCKET
553         struct ip6_hdr *ip;
554 #endif 
555         struct icmp6_hdr *icp;
556         int ifindex = 0;
557         struct cmsghdr *cm;
558         struct in6_pktinfo *pi = NULL;
559         u_char ntopbuf[INET6_ADDRSTRLEN], ifnamebuf[IFNAMSIZ];
560         struct in6_addr dst = in6addr_any;
561
562         /*
563          * Get message. We reset msg_controllen since the field could
564          * be modified if we had received a message before setting
565          * receive options.
566          */
567         rcvmhdr.msg_controllen = rcvcmsgbuflen;
568         if ((i = recvmsg(sock, &rcvmhdr, 0)) < 0)
569                 return;
570
571         /* extract optional information via Advanced API */
572         for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(&rcvmhdr);
573              cm;
574              cm = (struct cmsghdr *)CMSG_NXTHDR(&rcvmhdr, cm)) {
575                 if (cm->cmsg_level == IPPROTO_IPV6 &&
576                     cm->cmsg_type == IPV6_PKTINFO &&
577                     cm->cmsg_len == CMSG_LEN(sizeof(struct in6_pktinfo))) {
578                         pi = (struct in6_pktinfo *)(CMSG_DATA(cm));
579                         ifindex = pi->ipi6_ifindex;
580                         dst = pi->ipi6_addr;
581                 }
582                 if (cm->cmsg_level == IPPROTO_IPV6 &&
583                     cm->cmsg_type == IPV6_HOPLIMIT &&
584                     cm->cmsg_len == CMSG_LEN(sizeof(int)))
585                         hlimp = (int *)CMSG_DATA(cm);
586         }
587         if (ifindex == 0) {
588                 syslog(LOG_ERR,
589                        "<%s> failed to get receiving interface",
590                        __FUNCTION__);
591                 return;
592         }
593         if (hlimp == NULL) {
594                 syslog(LOG_ERR,
595                        "<%s> failed to get receiving hop limit",
596                        __FUNCTION__);
597                 return;
598         }
599
600         /*
601          * If we happen to receive data on an interface which is now down,
602          * just discard the data.
603          */
604         if ((iflist[pi->ipi6_ifindex]->ifm_flags & IFF_UP) == 0) {
605                 syslog(LOG_INFO,
606                        "<%s> received data on a disabled interface (%s)",
607                        __FUNCTION__,
608                        if_indextoname(pi->ipi6_ifindex, ifnamebuf));
609                 return;
610         }
611
612 #ifdef OLDRAWSOCKET
613         if (i < sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr)) {
614                 syslog(LOG_ERR,
615                        "<%s> packet size(%d) is too short",
616                        __FUNCTION__, i);
617                 return;
618         }
619
620         ip = (struct ip6_hdr *)rcvmhdr.msg_iov[0].iov_base;
621         icp = (struct icmp6_hdr *)(ip + 1); /* XXX: ext. hdr? */
622 #else
623         if (i < sizeof(struct icmp6_hdr)) {
624                 syslog(LOG_ERR,
625                        "<%s> packet size(%d) is too short",
626                        __FUNCTION__, i);
627                 return;
628         }
629
630         icp = (struct icmp6_hdr *)rcvmhdr.msg_iov[0].iov_base;
631 #endif
632
633         switch (icp->icmp6_type) {
634         case ND_ROUTER_SOLICIT:
635                 /*
636                  * Message verification - RFC-2461 6.1.1
637                  * XXX: these checks must be done in the kernel as well,
638                  *      but we can't completely rely on them.
639                  */
640                 if (*hlimp != 255) {
641                         syslog(LOG_NOTICE,
642                             "<%s> RS with invalid hop limit(%d) "
643                             "received from %s on %s",
644                             __FUNCTION__, *hlimp,
645                             inet_ntop(AF_INET6, &from.sin6_addr, ntopbuf,
646                             INET6_ADDRSTRLEN),
647                             if_indextoname(pi->ipi6_ifindex, ifnamebuf));
648                         return;
649                 }
650                 if (icp->icmp6_code) {
651                         syslog(LOG_NOTICE,
652                             "<%s> RS with invalid ICMP6 code(%d) "
653                             "received from %s on %s",
654                             __FUNCTION__, icp->icmp6_code,
655                             inet_ntop(AF_INET6, &from.sin6_addr, ntopbuf,
656                             INET6_ADDRSTRLEN),
657                             if_indextoname(pi->ipi6_ifindex, ifnamebuf));
658                         return;
659                 }
660                 if (i < sizeof(struct nd_router_solicit)) {
661                         syslog(LOG_NOTICE,
662                             "<%s> RS from %s on %s does not have enough "
663                             "length (len = %d)",
664                             __FUNCTION__,
665                             inet_ntop(AF_INET6, &from.sin6_addr, ntopbuf,
666                             INET6_ADDRSTRLEN),
667                             if_indextoname(pi->ipi6_ifindex, ifnamebuf), i);
668                         return;
669                 }
670                 rs_input(i, (struct nd_router_solicit *)icp, pi, &from);
671                 break;
672         case ND_ROUTER_ADVERT:
673                 /*
674                  * Message verification - RFC-2461 6.1.2
675                  * XXX: there's a same dilemma as above... 
676                  */
677                 if (*hlimp != 255) {
678                         syslog(LOG_NOTICE,
679                             "<%s> RA with invalid hop limit(%d) "
680                             "received from %s on %s",
681                             __FUNCTION__, *hlimp,
682                             inet_ntop(AF_INET6, &from.sin6_addr, ntopbuf,
683                             INET6_ADDRSTRLEN),
684                             if_indextoname(pi->ipi6_ifindex, ifnamebuf));
685                         return;
686                 }
687                 if (icp->icmp6_code) {
688                         syslog(LOG_NOTICE,
689                             "<%s> RA with invalid ICMP6 code(%d) "
690                             "received from %s on %s",
691                             __FUNCTION__, icp->icmp6_code,
692                             inet_ntop(AF_INET6, &from.sin6_addr, ntopbuf,
693                             INET6_ADDRSTRLEN),
694                             if_indextoname(pi->ipi6_ifindex, ifnamebuf));
695                         return;
696                 }
697                 if (i < sizeof(struct nd_router_advert)) {
698                         syslog(LOG_NOTICE,
699                             "<%s> RA from %s on %s does not have enough "
700                             "length (len = %d)",
701                             __FUNCTION__,
702                             inet_ntop(AF_INET6, &from.sin6_addr, ntopbuf,
703                             INET6_ADDRSTRLEN),
704                             if_indextoname(pi->ipi6_ifindex, ifnamebuf), i);
705                         return;
706                 }
707                 ra_input(i, (struct nd_router_advert *)icp, pi, &from);
708                 break;
709         case ICMP6_ROUTER_RENUMBERING:
710                 if (accept_rr == 0) {
711                         syslog(LOG_ERR, "<%s> received a router renumbering "
712                             "message, but not allowed to be accepted",
713                             __FUNCTION__);
714                         break;
715                 }
716                 rr_input(i, (struct icmp6_router_renum *)icp, pi, &from,
717                          &dst);
718                 break;
719         default:
720                 /*
721                  * Note that this case is POSSIBLE, especially just
722                  * after invocation of the daemon. This is because we
723                  * could receive message after opening the socket and
724                  * before setting ICMP6 type filter(see sock_open()).
725                  */
726                 syslog(LOG_ERR, "<%s> invalid icmp type(%d)",
727                     __FUNCTION__, icp->icmp6_type);
728                 return;
729         }
730
731         return;
732 }
733
734 static void
735 rs_input(int len, struct nd_router_solicit *rs,
736          struct in6_pktinfo *pi, struct sockaddr_in6 *from)
737 {
738         u_char ntopbuf[INET6_ADDRSTRLEN], ifnamebuf[IFNAMSIZ];
739         union nd_opts ndopts;
740         struct rainfo *ra;
741
742         syslog(LOG_DEBUG,
743                "<%s> RS received from %s on %s",
744                __FUNCTION__,
745                inet_ntop(AF_INET6, &from->sin6_addr,
746                          ntopbuf, INET6_ADDRSTRLEN),
747                if_indextoname(pi->ipi6_ifindex, ifnamebuf));
748
749         /* ND option check */
750         memset(&ndopts, 0, sizeof(ndopts));
751         if (nd6_options((struct nd_opt_hdr *)(rs + 1),
752                         len - sizeof(struct nd_router_solicit),
753                          &ndopts, NDOPT_FLAG_SRCLINKADDR)) {
754                 syslog(LOG_DEBUG,
755                        "<%s> ND option check failed for an RS from %s on %s",
756                        __FUNCTION__,
757                        inet_ntop(AF_INET6, &from->sin6_addr,
758                                  ntopbuf, INET6_ADDRSTRLEN),
759                        if_indextoname(pi->ipi6_ifindex, ifnamebuf));
760                 return;
761         }
762
763         /*
764          * If the IP source address is the unspecified address, there
765          * must be no source link-layer address option in the message.
766          * (RFC-2461 6.1.1)
767          */
768         if (IN6_IS_ADDR_UNSPECIFIED(&from->sin6_addr) &&
769             ndopts.nd_opts_src_lladdr) {
770                 syslog(LOG_ERR,
771                        "<%s> RS from unspecified src on %s has a link-layer"
772                        " address option",
773                        __FUNCTION__,
774                        if_indextoname(pi->ipi6_ifindex, ifnamebuf));
775                 goto done;
776         }
777
778         ra = ralist;
779         while (ra != NULL) {
780                 if (pi->ipi6_ifindex == ra->ifindex)
781                         break;
782                 ra = ra->next;
783         }
784         if (ra == NULL) {
785                 syslog(LOG_INFO,
786                        "<%s> RS received on non advertising interface(%s)",
787                        __FUNCTION__,
788                        if_indextoname(pi->ipi6_ifindex, ifnamebuf));
789                 goto done;
790         }
791
792         ra->rsinput++;          /* increment statistics */
793
794         /*
795          * Decide whether to send RA according to the rate-limit
796          * consideration.
797          */
798         {
799                 long delay;     /* must not be greater than 1000000 */
800                 struct timeval interval, now, min_delay, tm_tmp, *rest;
801                 struct soliciter *sol;
802
803                 /*
804                  * record sockaddr waiting for RA, if possible
805                  */
806                 sol = (struct soliciter *)malloc(sizeof(*sol));
807                 if (sol) {
808                         sol->addr = *from;
809                         /*XXX RFC2553 need clarification on flowinfo */
810                         sol->addr.sin6_flowinfo = 0;    
811                         sol->next = ra->soliciter;
812                         ra->soliciter = sol->next;
813                 }
814
815                 /*
816                  * If there is already a waiting RS packet, don't
817                  * update the timer.
818                  */
819                 if (ra->waiting++)
820                         goto done;
821
822                 /*
823                  * Compute a random delay. If the computed value
824                  * corresponds to a time later than the time the next
825                  * multicast RA is scheduled to be sent, ignore the random
826                  * delay and send the advertisement at the
827                  * already-scheduled time. RFC-2461 6.2.6
828                  */
829                 delay = random() % MAX_RA_DELAY_TIME;
830                 interval.tv_sec = 0;
831                 interval.tv_usec = delay;
832                 rest = rtadvd_timer_rest(ra->timer);
833                 if (TIMEVAL_LT(*rest, interval)) {
834                         syslog(LOG_DEBUG,
835                                "<%s> random delay is larger than "
836                                "the rest of normal timer",
837                                __FUNCTION__);
838                         interval = *rest;
839                 }
840
841                 /*
842                  * If we sent a multicast Router Advertisement within
843                  * the last MIN_DELAY_BETWEEN_RAS seconds, schedule
844                  * the advertisement to be sent at a time corresponding to
845                  * MIN_DELAY_BETWEEN_RAS plus the random value after the
846                  * previous advertisement was sent.
847                  */
848                 gettimeofday(&now, NULL);
849                 TIMEVAL_SUB(&now, &ra->lastsent, &tm_tmp);
850                 min_delay.tv_sec = MIN_DELAY_BETWEEN_RAS;
851                 min_delay.tv_usec = 0;
852                 if (TIMEVAL_LT(tm_tmp, min_delay)) {
853                         TIMEVAL_SUB(&min_delay, &tm_tmp, &min_delay);
854                         TIMEVAL_ADD(&min_delay, &interval, &interval);
855                 }
856                 rtadvd_set_timer(&interval, ra->timer);
857                 goto done;
858         }
859
860   done:
861         free_ndopts(&ndopts);
862         return;
863 }
864
865 static void
866 ra_input(int len, struct nd_router_advert *ra,
867          struct in6_pktinfo *pi, struct sockaddr_in6 *from)
868 {
869         struct rainfo *rai;
870         u_char ntopbuf[INET6_ADDRSTRLEN], ifnamebuf[IFNAMSIZ];
871         union nd_opts ndopts;
872         char *on_off[] = {"OFF", "ON"};
873         u_int32_t reachabletime, retranstimer, mtu;
874         int inconsistent = 0;
875
876         syslog(LOG_DEBUG,
877                "<%s> RA received from %s on %s",
878                __FUNCTION__,
879                inet_ntop(AF_INET6, &from->sin6_addr,
880                          ntopbuf, INET6_ADDRSTRLEN),
881                if_indextoname(pi->ipi6_ifindex, ifnamebuf));
882         
883         /* ND option check */
884         memset(&ndopts, 0, sizeof(ndopts));
885         if (nd6_options((struct nd_opt_hdr *)(ra + 1),
886                         len - sizeof(struct nd_router_advert),
887                         &ndopts, NDOPT_FLAG_SRCLINKADDR |
888                         NDOPT_FLAG_PREFIXINFO | NDOPT_FLAG_MTU)) {
889                 syslog(LOG_ERR,
890                        "<%s> ND option check failed for an RA from %s on %s",
891                        __FUNCTION__,
892                        inet_ntop(AF_INET6, &from->sin6_addr,
893                                  ntopbuf, INET6_ADDRSTRLEN),
894                        if_indextoname(pi->ipi6_ifindex, ifnamebuf));
895                 return;
896         }
897
898         /*
899          * RA consistency check according to RFC-2461 6.2.7
900          */
901         if ((rai = if_indextorainfo(pi->ipi6_ifindex)) == 0) {
902                 syslog(LOG_INFO,
903                        "<%s> received RA from %s on non-advertising"
904                        " interface(%s)",
905                        __FUNCTION__,
906                        inet_ntop(AF_INET6, &from->sin6_addr,
907                                  ntopbuf, INET6_ADDRSTRLEN),
908                        if_indextoname(pi->ipi6_ifindex, ifnamebuf));
909                 goto done;
910         }
911         rai->rainput++;         /* increment statistics */
912         
913         /* Cur Hop Limit value */
914         if (ra->nd_ra_curhoplimit && rai->hoplimit &&
915             ra->nd_ra_curhoplimit != rai->hoplimit) {
916                 syslog(LOG_INFO,
917                        "<%s> CurHopLimit inconsistent on %s:"
918                        " %d from %s, %d from us",
919                        __FUNCTION__,
920                        rai->ifname,
921                        ra->nd_ra_curhoplimit,
922                        inet_ntop(AF_INET6, &from->sin6_addr,
923                                  ntopbuf, INET6_ADDRSTRLEN),
924                        rai->hoplimit);
925                 inconsistent++;
926         }
927         /* M flag */
928         if ((ra->nd_ra_flags_reserved & ND_RA_FLAG_MANAGED) !=
929             rai->managedflg) {
930                 syslog(LOG_INFO,
931                        "<%s> M flag inconsistent on %s:"
932                        " %s from %s, %s from us",
933                        __FUNCTION__,
934                        rai->ifname,
935                        on_off[!rai->managedflg],
936                        inet_ntop(AF_INET6, &from->sin6_addr,
937                                  ntopbuf, INET6_ADDRSTRLEN),
938                        on_off[rai->managedflg]);
939                 inconsistent++;
940         }
941         /* O flag */
942         if ((ra->nd_ra_flags_reserved & ND_RA_FLAG_OTHER) !=
943             rai->otherflg) {
944                 syslog(LOG_INFO,
945                        "<%s> O flag inconsistent on %s:"
946                        " %s from %s, %s from us",
947                        __FUNCTION__,
948                        rai->ifname,
949                        on_off[!rai->otherflg],
950                        inet_ntop(AF_INET6, &from->sin6_addr,
951                                  ntopbuf, INET6_ADDRSTRLEN),
952                        on_off[rai->otherflg]);
953                 inconsistent++;
954         }
955         /* Reachable Time */
956         reachabletime = ntohl(ra->nd_ra_reachable);
957         if (reachabletime && rai->reachabletime &&
958             reachabletime != rai->reachabletime) {
959                 syslog(LOG_INFO,
960                        "<%s> ReachableTime inconsistent on %s:"
961                        " %d from %s, %d from us",
962                        __FUNCTION__,
963                        rai->ifname,
964                        reachabletime,
965                        inet_ntop(AF_INET6, &from->sin6_addr,
966                                  ntopbuf, INET6_ADDRSTRLEN),
967                        rai->reachabletime);
968                 inconsistent++;
969         }
970         /* Retrans Timer */
971         retranstimer = ntohl(ra->nd_ra_retransmit);
972         if (retranstimer && rai->retranstimer &&
973             retranstimer != rai->retranstimer) {
974                 syslog(LOG_INFO,
975                        "<%s> RetranceTimer inconsistent on %s:"
976                        " %d from %s, %d from us",
977                        __FUNCTION__,
978                        rai->ifname,
979                        retranstimer,
980                        inet_ntop(AF_INET6, &from->sin6_addr,
981                                  ntopbuf, INET6_ADDRSTRLEN),
982                        rai->retranstimer);
983                 inconsistent++;
984         }
985         /* Values in the MTU options */
986         if (ndopts.nd_opts_mtu) {
987                 mtu = ntohl(ndopts.nd_opts_mtu->nd_opt_mtu_mtu);
988                 if (mtu && rai->linkmtu && mtu != rai->linkmtu) {
989                         syslog(LOG_INFO,
990                                "<%s> MTU option value inconsistent on %s:"
991                                " %d from %s, %d from us",
992                                __FUNCTION__,
993                                rai->ifname, mtu,
994                                inet_ntop(AF_INET6, &from->sin6_addr,
995                                          ntopbuf, INET6_ADDRSTRLEN),
996                                rai->linkmtu);
997                         inconsistent++;
998                 }
999         }
1000         /* Preferred and Valid Lifetimes for prefixes */
1001         {
1002                 struct nd_optlist *optp = ndopts.nd_opts_list;
1003
1004                 if (ndopts.nd_opts_pi) {
1005                         if (prefix_check(ndopts.nd_opts_pi, rai, from))
1006                                 inconsistent++;
1007                 }
1008                 while (optp) {
1009                         if (prefix_check((struct nd_opt_prefix_info *)optp->opt,
1010                                          rai, from))
1011                                 inconsistent++;
1012                         optp = optp->next;
1013                 }
1014         }
1015
1016         if (inconsistent)
1017                 rai->rainconsistent++;
1018         
1019   done:
1020         free_ndopts(&ndopts);
1021         return;
1022 }
1023
1024 /* return a non-zero value if the received prefix is inconsitent with ours */
1025 static int
1026 prefix_check(struct nd_opt_prefix_info *pinfo,
1027              struct rainfo *rai, struct sockaddr_in6 *from)
1028 {
1029         u_int32_t preferred_time, valid_time;
1030         struct prefix *pp;
1031         int inconsistent = 0;
1032         u_char ntopbuf[INET6_ADDRSTRLEN], prefixbuf[INET6_ADDRSTRLEN];
1033         struct timeval now;
1034
1035 #if 0                           /* impossible */
1036         if (pinfo->nd_opt_pi_type != ND_OPT_PREFIX_INFORMATION)
1037                 return(0);
1038 #endif
1039
1040         /*
1041          * log if the adveritsed prefix has link-local scope(sanity check?)
1042          */
1043         if (IN6_IS_ADDR_LINKLOCAL(&pinfo->nd_opt_pi_prefix)) {
1044                 syslog(LOG_INFO,
1045                        "<%s> link-local prefix %s/%d is advertised "
1046                        "from %s on %s",
1047                        __FUNCTION__,
1048                        inet_ntop(AF_INET6, &pinfo->nd_opt_pi_prefix,
1049                                  prefixbuf, INET6_ADDRSTRLEN),
1050                        pinfo->nd_opt_pi_prefix_len,
1051                        inet_ntop(AF_INET6, &from->sin6_addr,
1052                                  ntopbuf, INET6_ADDRSTRLEN),
1053                        rai->ifname);
1054         }
1055
1056         if ((pp = find_prefix(rai, &pinfo->nd_opt_pi_prefix,
1057                               pinfo->nd_opt_pi_prefix_len)) == NULL) {
1058                 syslog(LOG_INFO,
1059                        "<%s> prefix %s/%d from %s on %s is not in our list",
1060                        __FUNCTION__,
1061                        inet_ntop(AF_INET6, &pinfo->nd_opt_pi_prefix,
1062                                  prefixbuf, INET6_ADDRSTRLEN),
1063                        pinfo->nd_opt_pi_prefix_len,
1064                        inet_ntop(AF_INET6, &from->sin6_addr,
1065                                  ntopbuf, INET6_ADDRSTRLEN),
1066                        rai->ifname);
1067                 return(0);
1068         }
1069
1070         preferred_time = ntohl(pinfo->nd_opt_pi_preferred_time);
1071         if (pp->pltimeexpire) {
1072                 /*
1073                  * The lifetime is decremented in real time, so we should
1074                  * compare the expiration time.
1075                  * (RFC 2461 Section 6.2.7.)
1076                  * XXX: can we really expect that all routers on the link
1077                  * have synchronized clocks?
1078                  */
1079                 gettimeofday(&now, NULL);
1080                 preferred_time += now.tv_sec;
1081
1082                 if (rai->clockskew &&
1083                     abs(preferred_time - pp->pltimeexpire) > rai->clockskew) {
1084                         syslog(LOG_INFO,
1085                                "<%s> prefeerred lifetime for %s/%d"
1086                                " (decr. in real time) inconsistent on %s:"
1087                                " %d from %s, %ld from us",
1088                                __FUNCTION__,
1089                                inet_ntop(AF_INET6, &pinfo->nd_opt_pi_prefix,
1090                                          prefixbuf, INET6_ADDRSTRLEN),
1091                                pinfo->nd_opt_pi_prefix_len,
1092                                rai->ifname, preferred_time,
1093                                inet_ntop(AF_INET6, &from->sin6_addr,
1094                                          ntopbuf, INET6_ADDRSTRLEN),
1095                                pp->pltimeexpire);
1096                         inconsistent++;
1097                 }
1098         } else if (preferred_time != pp->preflifetime) {
1099                 syslog(LOG_INFO,
1100                        "<%s> prefeerred lifetime for %s/%d"
1101                        " inconsistent on %s:"
1102                        " %d from %s, %d from us",
1103                        __FUNCTION__,
1104                        inet_ntop(AF_INET6, &pinfo->nd_opt_pi_prefix,
1105                                  prefixbuf, INET6_ADDRSTRLEN),
1106                        pinfo->nd_opt_pi_prefix_len,
1107                        rai->ifname, preferred_time,
1108                        inet_ntop(AF_INET6, &from->sin6_addr,
1109                                  ntopbuf, INET6_ADDRSTRLEN),
1110                        pp->preflifetime);
1111         }
1112
1113         valid_time = ntohl(pinfo->nd_opt_pi_valid_time);
1114         if (pp->vltimeexpire) {
1115                 gettimeofday(&now, NULL);
1116                 valid_time += now.tv_sec;
1117
1118                 if (rai->clockskew &&
1119                     abs(valid_time - pp->vltimeexpire) > rai->clockskew) {
1120                         syslog(LOG_INFO,
1121                                "<%s> valid lifetime for %s/%d"
1122                                " (decr. in real time) inconsistent on %s:"
1123                                " %d from %s, %ld from us",
1124                                __FUNCTION__,
1125                                inet_ntop(AF_INET6, &pinfo->nd_opt_pi_prefix,
1126                                          prefixbuf, INET6_ADDRSTRLEN),
1127                                pinfo->nd_opt_pi_prefix_len,
1128                                rai->ifname, preferred_time,
1129                                inet_ntop(AF_INET6, &from->sin6_addr,
1130                                          ntopbuf, INET6_ADDRSTRLEN),
1131                                pp->vltimeexpire);
1132                         inconsistent++;
1133                 }
1134         } else if (valid_time != pp->validlifetime) {
1135                 syslog(LOG_INFO,
1136                        "<%s> valid lifetime for %s/%d"
1137                        " inconsistent on %s:"
1138                        " %d from %s, %d from us",
1139                        __FUNCTION__,
1140                        inet_ntop(AF_INET6, &pinfo->nd_opt_pi_prefix,
1141                                  prefixbuf, INET6_ADDRSTRLEN),
1142                        pinfo->nd_opt_pi_prefix_len,
1143                        rai->ifname, valid_time,
1144                        inet_ntop(AF_INET6, &from->sin6_addr,
1145                                  ntopbuf, INET6_ADDRSTRLEN),
1146                        pp->validlifetime);
1147                 inconsistent++;
1148         }
1149
1150         return(inconsistent);
1151 }
1152
1153 struct prefix *
1154 find_prefix(struct rainfo *rai, struct in6_addr *prefix, int plen)
1155 {
1156         struct prefix *pp;
1157         int bytelen, bitlen;
1158
1159         for (pp = rai->prefix.next; pp != &rai->prefix; pp = pp->next) {
1160                 if (plen != pp->prefixlen)
1161                         continue;
1162                 bytelen = plen / 8;
1163                 bitlen = plen % 8;
1164                 if (memcmp((void *)prefix, (void *)&pp->prefix, bytelen))
1165                         continue;
1166                 if (prefix->s6_addr[bytelen] >> (8 - bitlen) ==
1167                     pp->prefix.s6_addr[bytelen] >> (8 - bitlen))
1168                         return(pp);
1169         }
1170
1171         return(NULL);
1172 }
1173
1174 /* check if p0/plen0 matches p1/plen1; return 1 if matches, otherwise 0. */
1175 int
1176 prefix_match(struct in6_addr *p0, int plen0,
1177              struct in6_addr *p1, int plen1)
1178 {
1179         int bytelen, bitlen;
1180
1181         if (plen0 < plen1)
1182                 return(0);
1183         bytelen = plen1 / 8;
1184         bitlen = plen1 % 8;
1185         if (memcmp((void *)p0, (void *)p1, bytelen))
1186                 return(0);
1187         if (p0->s6_addr[bytelen] >> (8 - bitlen) ==
1188             p1->s6_addr[bytelen] >> (8 - bitlen))
1189                 return(1);
1190
1191         return(0);
1192 }
1193
1194 static int
1195 nd6_options(struct nd_opt_hdr *hdr, int limit,
1196             union nd_opts *ndopts, u_int32_t optflags)
1197 {
1198         int optlen = 0;
1199
1200         for (; limit > 0; limit -= optlen) {
1201                 hdr = (struct nd_opt_hdr *)((caddr_t)hdr + optlen);
1202                 optlen = hdr->nd_opt_len << 3;
1203                 if (hdr->nd_opt_len == 0) {
1204                         syslog(LOG_ERR,
1205                             "<%s> bad ND option length(0) (type = %d)",
1206                             __FUNCTION__, hdr->nd_opt_type);
1207                         goto bad;
1208                 }
1209
1210                 if (hdr->nd_opt_type > ND_OPT_MTU) {
1211                         syslog(LOG_INFO,
1212                             "<%s> unknown ND option(type %d)",
1213                             __FUNCTION__, hdr->nd_opt_type);
1214                         continue;
1215                 }
1216
1217                 if ((ndopt_flags[hdr->nd_opt_type] & optflags) == 0) {
1218                         syslog(LOG_INFO,
1219                             "<%s> unexpected ND option(type %d)",
1220                                __FUNCTION__, hdr->nd_opt_type);
1221                         continue;
1222                 }
1223
1224                 switch (hdr->nd_opt_type) {
1225                 case ND_OPT_SOURCE_LINKADDR:
1226                 case ND_OPT_TARGET_LINKADDR:
1227                 case ND_OPT_REDIRECTED_HEADER:
1228                 case ND_OPT_MTU:
1229                         if (ndopts->nd_opt_array[hdr->nd_opt_type]) {
1230                                 syslog(LOG_INFO,
1231                                     "<%s> duplicated ND option (type = %d)",
1232                                     __FUNCTION__, hdr->nd_opt_type);
1233                         }
1234                         ndopts->nd_opt_array[hdr->nd_opt_type] = hdr;
1235                         break;
1236                 case ND_OPT_PREFIX_INFORMATION:
1237                 {
1238                         struct nd_optlist *pfxlist;
1239
1240                         if (ndopts->nd_opts_pi == 0) {
1241                                 ndopts->nd_opts_pi =
1242                                     (struct nd_opt_prefix_info *)hdr;
1243                                 continue;
1244                         }
1245                         if ((pfxlist = malloc(sizeof(*pfxlist))) == NULL) {
1246                                 syslog(LOG_ERR, "<%s> can't allocate memory",
1247                                     __FUNCTION__);
1248                                 goto bad;
1249                         }
1250                         pfxlist->next = ndopts->nd_opts_list;
1251                         pfxlist->opt = hdr;
1252                         ndopts->nd_opts_list = pfxlist;
1253
1254                         break;
1255                 }
1256                 default:        /* impossible */
1257                         break;
1258                 }
1259         }
1260
1261         return(0);
1262
1263   bad:
1264         free_ndopts(ndopts);
1265
1266         return(-1);
1267 }
1268
1269 static void
1270 free_ndopts(union nd_opts *ndopts)
1271 {
1272         struct nd_optlist *opt = ndopts->nd_opts_list, *next;
1273
1274         while (opt) {
1275                 next = opt->next;
1276                 free(opt);
1277                 opt = next;
1278         }
1279 }
1280
1281 void
1282 sock_open()
1283 {
1284         struct icmp6_filter filt;
1285         struct ipv6_mreq mreq;
1286         struct rainfo *ra = ralist;
1287         int on;
1288         /* XXX: should be max MTU attached to the node */
1289         static u_char answer[1500];
1290
1291         rcvcmsgbuflen = CMSG_SPACE(sizeof(struct in6_pktinfo)) +
1292                                 CMSG_SPACE(sizeof(int));
1293         rcvcmsgbuf = (u_char *)malloc(rcvcmsgbuflen);
1294         if (rcvcmsgbuf == NULL) {
1295                 syslog(LOG_ERR, "<%s> not enough core", __FUNCTION__);
1296                 exit(1);
1297         }
1298
1299         sndcmsgbuflen = CMSG_SPACE(sizeof(struct in6_pktinfo)) + 
1300                                 CMSG_SPACE(sizeof(int));
1301         sndcmsgbuf = (u_char *)malloc(sndcmsgbuflen);
1302         if (sndcmsgbuf == NULL) {
1303                 syslog(LOG_ERR, "<%s> not enough core", __FUNCTION__);
1304                 exit(1);
1305         }
1306
1307         if ((sock = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6)) < 0) {
1308                 syslog(LOG_ERR, "<%s> socket: %s", __FUNCTION__,
1309                        strerror(errno));
1310                 exit(1);
1311         }
1312
1313         /* specify to tell receiving interface */
1314         on = 1;
1315 #ifdef IPV6_RECVPKTINFO
1316         if (setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on,
1317                        sizeof(on)) < 0) {
1318                 syslog(LOG_ERR, "<%s> IPV6_RECVPKTINFO: %s",
1319                        __FUNCTION__, strerror(errno));
1320                 exit(1);
1321         }
1322 #else  /* old adv. API */
1323         if (setsockopt(sock, IPPROTO_IPV6, IPV6_PKTINFO, &on,
1324                        sizeof(on)) < 0) {
1325                 syslog(LOG_ERR, "<%s> IPV6_PKTINFO: %s",
1326                        __FUNCTION__, strerror(errno));
1327                 exit(1);
1328         }
1329 #endif 
1330
1331         on = 1;
1332         /* specify to tell value of hoplimit field of received IP6 hdr */
1333 #ifdef IPV6_RECVHOPLIMIT
1334         if (setsockopt(sock, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &on,
1335                        sizeof(on)) < 0) {
1336                 syslog(LOG_ERR, "<%s> IPV6_RECVHOPLIMIT: %s",
1337                        __FUNCTION__, strerror(errno));
1338                 exit(1);
1339         }
1340 #else  /* old adv. API */
1341         if (setsockopt(sock, IPPROTO_IPV6, IPV6_HOPLIMIT, &on,
1342                        sizeof(on)) < 0) {
1343                 syslog(LOG_ERR, "<%s> IPV6_HOPLIMIT: %s",
1344                        __FUNCTION__, strerror(errno));
1345                 exit(1);
1346         }
1347 #endif
1348
1349         ICMP6_FILTER_SETBLOCKALL(&filt);
1350         ICMP6_FILTER_SETPASS(ND_ROUTER_SOLICIT, &filt);
1351         ICMP6_FILTER_SETPASS(ND_ROUTER_ADVERT, &filt);
1352         if (accept_rr)
1353                 ICMP6_FILTER_SETPASS(ICMP6_ROUTER_RENUMBERING, &filt);
1354         if (setsockopt(sock, IPPROTO_ICMPV6, ICMP6_FILTER, &filt,
1355                        sizeof(filt)) < 0) {
1356                 syslog(LOG_ERR, "<%s> IICMP6_FILTER: %s",
1357                        __FUNCTION__, strerror(errno));
1358                 exit(1);
1359         }
1360
1361         /*
1362          * join all routers multicast address on each advertising interface.
1363          */
1364         if (inet_pton(AF_INET6, ALLROUTERS_LINK,
1365                       &mreq.ipv6mr_multiaddr.s6_addr)
1366             != 1) {
1367                 syslog(LOG_ERR, "<%s> inet_pton failed(library bug?)",
1368                        __FUNCTION__);
1369                 exit(1);
1370         }
1371         while (ra) {
1372                 mreq.ipv6mr_interface = ra->ifindex;
1373                 if (setsockopt(sock, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq,
1374                                sizeof(mreq)) < 0) {
1375                         syslog(LOG_ERR, "<%s> IPV6_JOIN_GROUP(link) on %s: %s",
1376                                __FUNCTION__, ra->ifname, strerror(errno));
1377                         exit(1);
1378                 }
1379                 ra = ra->next;
1380         }
1381
1382         /*
1383          * When attending router renumbering, join all-routers site-local
1384          * multicast group. 
1385          */
1386         if (accept_rr) {
1387                 if (inet_pton(AF_INET6, ALLROUTERS_SITE,
1388                               &in6a_site_allrouters) != 1) {
1389                         syslog(LOG_ERR, "<%s> inet_pton failed(library bug?)",
1390                                __FUNCTION__);
1391                         exit(1);
1392                 }
1393                 mreq.ipv6mr_multiaddr = in6a_site_allrouters;
1394                 if (mcastif) {
1395                         if ((mreq.ipv6mr_interface = if_nametoindex(mcastif))
1396                             == 0) {
1397                                 syslog(LOG_ERR,
1398                                        "<%s> invalid interface: %s",
1399                                        __FUNCTION__, mcastif);
1400                                 exit(1);
1401                         }
1402                 } else
1403                         mreq.ipv6mr_interface = ralist->ifindex;
1404                 if (setsockopt(sock, IPPROTO_IPV6, IPV6_JOIN_GROUP,
1405                                &mreq, sizeof(mreq)) < 0) {
1406                         syslog(LOG_ERR,
1407                                "<%s> IPV6_JOIN_GROUP(site) on %s: %s",
1408                                __FUNCTION__,
1409                                mcastif ? mcastif : ralist->ifname,
1410                                strerror(errno));
1411                         exit(1);
1412                 }
1413         }
1414         
1415         /* initialize msghdr for receiving packets */
1416         rcviov[0].iov_base = (caddr_t)answer;
1417         rcviov[0].iov_len = sizeof(answer);
1418         rcvmhdr.msg_name = (caddr_t)&from;
1419         rcvmhdr.msg_namelen = sizeof(from);
1420         rcvmhdr.msg_iov = rcviov;
1421         rcvmhdr.msg_iovlen = 1;
1422         rcvmhdr.msg_control = (caddr_t) rcvcmsgbuf;
1423         rcvmhdr.msg_controllen = rcvcmsgbuflen;
1424
1425         /* initialize msghdr for sending packets */
1426         sndmhdr.msg_namelen = sizeof(struct sockaddr_in6);
1427         sndmhdr.msg_iov = sndiov;
1428         sndmhdr.msg_iovlen = 1;
1429         sndmhdr.msg_control = (caddr_t)sndcmsgbuf;
1430         sndmhdr.msg_controllen = sndcmsgbuflen;
1431         
1432         return;
1433 }
1434
1435 /* open a routing socket to watch the routing table */
1436 static void
1437 rtsock_open()
1438 {
1439         if ((rtsock = socket(PF_ROUTE, SOCK_RAW, 0)) < 0) {
1440                 syslog(LOG_ERR,
1441                        "<%s> socket: %s", __FUNCTION__, strerror(errno));
1442                 exit(1);
1443         }
1444 }
1445
1446 struct rainfo *
1447 if_indextorainfo(int index)
1448 {
1449         struct rainfo *rai = ralist;
1450
1451         for (rai = ralist; rai; rai = rai->next) {
1452                 if (rai->ifindex == index)
1453                         return(rai);
1454         }
1455
1456         return(NULL);           /* search failed */
1457 }
1458
1459 static void
1460 ra_output(rainfo)
1461 struct rainfo *rainfo;
1462 {
1463         int i;
1464         struct cmsghdr *cm;
1465         struct in6_pktinfo *pi;
1466         struct soliciter *sol, *nextsol;
1467
1468         if ((iflist[rainfo->ifindex]->ifm_flags & IFF_UP) == 0) {
1469                 syslog(LOG_DEBUG, "<%s> %s is not up, skip sending RA",
1470                        __FUNCTION__, rainfo->ifname);
1471                 return;
1472         }
1473
1474         make_packet(rainfo);    /* XXX: inefficient */
1475
1476         sndmhdr.msg_name = (caddr_t)&sin6_allnodes;
1477         sndmhdr.msg_iov[0].iov_base = (caddr_t)rainfo->ra_data;
1478         sndmhdr.msg_iov[0].iov_len = rainfo->ra_datalen;
1479
1480         cm = CMSG_FIRSTHDR(&sndmhdr);
1481         /* specify the outgoing interface */
1482         cm->cmsg_level = IPPROTO_IPV6;
1483         cm->cmsg_type = IPV6_PKTINFO;
1484         cm->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
1485         pi = (struct in6_pktinfo *)CMSG_DATA(cm);
1486         memset(&pi->ipi6_addr, 0, sizeof(pi->ipi6_addr));       /*XXX*/
1487         pi->ipi6_ifindex = rainfo->ifindex;
1488
1489         /* specify the hop limit of the packet */
1490         {
1491                 int hoplimit = 255;
1492
1493                 cm = CMSG_NXTHDR(&sndmhdr, cm);
1494                 cm->cmsg_level = IPPROTO_IPV6;
1495                 cm->cmsg_type = IPV6_HOPLIMIT;
1496                 cm->cmsg_len = CMSG_LEN(sizeof(int));
1497                 memcpy(CMSG_DATA(cm), &hoplimit, sizeof(int));
1498         }
1499
1500         syslog(LOG_DEBUG,
1501                "<%s> send RA on %s, # of waitings = %d",
1502                __FUNCTION__, rainfo->ifname, rainfo->waiting); 
1503
1504         i = sendmsg(sock, &sndmhdr, 0);
1505
1506         if (i < 0 || i != rainfo->ra_datalen)  {
1507                 if (i < 0) {
1508                         syslog(LOG_ERR, "<%s> sendmsg on %s: %s",
1509                                __FUNCTION__, rainfo->ifname,
1510                                strerror(errno));
1511                 }
1512         }
1513
1514         /*
1515          * unicast advertisements
1516          * XXX commented out.  reason: though spec does not forbit it, unicast
1517          * advert does not really help
1518          */
1519         for (sol = rainfo->soliciter; sol; sol = nextsol) {
1520                 nextsol = sol->next;
1521
1522 #if 0
1523                 sndmhdr.msg_name = (caddr_t)&sol->addr;
1524                 i = sendmsg(sock, &sndmhdr, 0);
1525                 if (i < 0 || i != rainfo->ra_datalen)  {
1526                         if (i < 0) {
1527                                 syslog(LOG_ERR,
1528                                     "<%s> unicast sendmsg on %s: %s",
1529                                     __FUNCTION__, rainfo->ifname,
1530                                     strerror(errno));
1531                         }
1532                 }
1533 #endif
1534
1535                 sol->next = NULL;
1536                 free(sol);
1537         }
1538         rainfo->soliciter = NULL;
1539
1540         /* update counter */
1541         if (rainfo->initcounter < MAX_INITIAL_RTR_ADVERTISEMENTS)
1542                 rainfo->initcounter++;
1543         rainfo->raoutput++;
1544
1545         /* update timestamp */
1546         gettimeofday(&rainfo->lastsent, NULL);
1547
1548         /* reset waiting conter */
1549         rainfo->waiting = 0;
1550 }
1551
1552 /* process RA timer */
1553 void
1554 ra_timeout(void *data)
1555 {
1556         struct rainfo *rai = (struct rainfo *)data;
1557
1558 #ifdef notyet
1559         /* if necessary, reconstruct the packet. */
1560 #endif
1561
1562         syslog(LOG_DEBUG,
1563                "<%s> RA timer on %s is expired",
1564                __FUNCTION__, rai->ifname);
1565
1566         ra_output(rai);
1567 }
1568
1569 /* update RA timer */
1570 void
1571 ra_timer_update(void *data, struct timeval *tm)
1572 {
1573         struct rainfo *rai = (struct rainfo *)data;
1574         long interval;
1575
1576         /*
1577          * Whenever a multicast advertisement is sent from an interface,
1578          * the timer is reset to a uniformly-distributed random value
1579          * between the interface's configured MinRtrAdvInterval and
1580          * MaxRtrAdvInterval (RFC2461 6.2.4).
1581          */
1582         interval = rai->mininterval; 
1583         interval += random() % (rai->maxinterval - rai->mininterval);
1584
1585         /*
1586          * For the first few advertisements (up to
1587          * MAX_INITIAL_RTR_ADVERTISEMENTS), if the randomly chosen interval
1588          * is greater than MAX_INITIAL_RTR_ADVERT_INTERVAL, the timer
1589          * SHOULD be set to MAX_INITIAL_RTR_ADVERT_INTERVAL instead.
1590          * (RFC-2461 6.2.4)
1591          */
1592         if (rai->initcounter < MAX_INITIAL_RTR_ADVERTISEMENTS &&
1593             interval > MAX_INITIAL_RTR_ADVERT_INTERVAL)
1594                 interval = MAX_INITIAL_RTR_ADVERT_INTERVAL;
1595
1596         tm->tv_sec = interval;
1597         tm->tv_usec = 0;
1598
1599         syslog(LOG_DEBUG,
1600                "<%s> RA timer on %s is set to %ld:%ld",
1601                __FUNCTION__, rai->ifname,
1602                (long int)tm->tv_sec, (long int)tm->tv_usec);
1603
1604         return;
1605 }