]> CyberLeo.Net >> Repos - FreeBSD/releng/9.2.git/blob - usr.sbin/route6d/route6d.c
- Copy stable/9 to releng/9.2 as part of the 9.2-RELEASE cycle.
[FreeBSD/releng/9.2.git] / usr.sbin / route6d / route6d.c
1 /*      $FreeBSD$       */
2 /*      $KAME: route6d.c,v 1.104 2003/10/31 00:30:20 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 #ifndef lint
34 static const char _rcsid[] = "$KAME: route6d.c,v 1.104 2003/10/31 00:30:20 itojun Exp $";
35 #endif
36
37 #include <stdio.h>
38
39 #include <time.h>
40 #include <unistd.h>
41 #include <fnmatch.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <signal.h>
45 #ifdef __STDC__
46 #include <stdarg.h>
47 #else
48 #include <varargs.h>
49 #endif
50 #include <syslog.h>
51 #include <stddef.h>
52 #include <errno.h>
53 #include <err.h>
54 #ifdef HAVE_POLL_H
55 #include <poll.h>
56 #endif
57
58 #include <sys/types.h>
59 #include <sys/param.h>
60 #include <sys/file.h>
61 #include <sys/socket.h>
62 #include <sys/ioctl.h>
63 #include <sys/sysctl.h>
64 #include <sys/uio.h>
65 #include <net/if.h>
66 #include <net/if_var.h>
67 #define _KERNEL 1
68 #include <net/route.h>
69 #undef _KERNEL
70 #include <netinet/in.h>
71 #include <netinet/in_var.h>
72 #include <netinet/ip6.h>
73 #include <netinet/udp.h>
74 #include <netdb.h>
75 #include <ifaddrs.h>
76
77 #include <arpa/inet.h>
78
79 #include "route6d.h"
80
81 #define MAXFILTER       40
82 #define RT_DUMP_MAXRETRY        15
83
84 #ifdef  DEBUG
85 #define INIT_INTERVAL6  6
86 #else
87 #define INIT_INTERVAL6  10      /* Wait to submit an initial riprequest */
88 #endif
89
90 /* alignment constraint for routing socket */
91 #define ROUNDUP(a) \
92         ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
93 #define ADVANCE(x, n) (x += ROUNDUP((n)->sa_len))
94
95 /*
96  * Following two macros are highly depending on KAME Release
97  */
98 #define IN6_LINKLOCAL_IFINDEX(addr) \
99         ((addr).s6_addr[2] << 8 | (addr).s6_addr[3])
100
101 #define SET_IN6_LINKLOCAL_IFINDEX(addr, index) \
102         do { \
103                 (addr).s6_addr[2] = ((index) >> 8) & 0xff; \
104                 (addr).s6_addr[3] = (index) & 0xff; \
105         } while (0)
106
107 struct ifc {                    /* Configuration of an interface */
108         TAILQ_ENTRY(ifc) ifc_next;
109
110         char    ifc_name[IFNAMSIZ];             /* if name */
111         int     ifc_index;                      /* if index */
112         int     ifc_mtu;                        /* if mtu */
113         int     ifc_metric;                     /* if metric */
114         u_int   ifc_flags;                      /* flags */
115         short   ifc_cflags;                     /* IFC_XXX */
116         struct  in6_addr ifc_mylladdr;          /* my link-local address */
117         struct  sockaddr_in6 ifc_ripsin;        /* rip multicast address */
118         TAILQ_HEAD(, ifac) ifc_ifac_head;       /* list of AF_INET6 addrs */
119         TAILQ_HEAD(, iff) ifc_iff_head;         /* list of filters */
120         int     ifc_joined;                     /* joined to ff02::9 */
121 };
122 TAILQ_HEAD(, ifc) ifc_head = TAILQ_HEAD_INITIALIZER(ifc_head);
123
124 struct ifac {                   /* Adddress associated to an interface */ 
125         TAILQ_ENTRY(ifac) ifac_next;
126
127         struct  ifc *ifac_ifc;          /* back pointer */
128         struct  in6_addr ifac_addr;     /* address */
129         struct  in6_addr ifac_raddr;    /* remote address, valid in p2p */
130         int     ifac_scope_id;          /* scope id */
131         int     ifac_plen;              /* prefix length */
132 };
133
134 struct iff {                    /* Filters for an interface */
135         TAILQ_ENTRY(iff) iff_next;
136
137         int     iff_type;
138         struct  in6_addr iff_addr;
139         int     iff_plen;
140 };
141
142 struct  ifc **index2ifc;
143 unsigned int    nindex2ifc;
144 struct  ifc *loopifcp = NULL;   /* pointing to loopback */
145 #ifdef HAVE_POLL_H
146 struct  pollfd set[2];
147 #else
148 fd_set  *sockvecp;      /* vector to select() for receiving */
149 fd_set  *recvecp;
150 int     fdmasks;
151 int     maxfd;          /* maximum fd for select() */
152 #endif
153 int     rtsock;         /* the routing socket */
154 int     ripsock;        /* socket to send/receive RIP datagram */
155
156 struct  rip6 *ripbuf;   /* packet buffer for sending */
157
158 /*
159  * Maintain the routes in a linked list.  When the number of the routes
160  * grows, somebody would like to introduce a hash based or a radix tree
161  * based structure.  I believe the number of routes handled by RIP is
162  * limited and I don't have to manage a complex data structure, however.
163  *
164  * One of the major drawbacks of the linear linked list is the difficulty
165  * of representing the relationship between a couple of routes.  This may
166  * be a significant problem when we have to support route aggregation with
167  * suppressing the specifics covered by the aggregate.
168  */
169
170 struct riprt {
171         TAILQ_ENTRY(riprt) rrt_next;    /* next destination */
172
173         struct  riprt *rrt_same;        /* same destination - future use */
174         struct  netinfo6 rrt_info;      /* network info */
175         struct  in6_addr rrt_gw;        /* gateway */
176         u_long  rrt_flags;              /* kernel routing table flags */
177         u_long  rrt_rflags;             /* route6d routing table flags */
178         time_t  rrt_t;                  /* when the route validated */
179         int     rrt_index;              /* ifindex from which this route got */
180 };
181 TAILQ_HEAD(, riprt) riprt_head = TAILQ_HEAD_INITIALIZER(riprt_head);
182
183 int     dflag = 0;      /* debug flag */
184 int     qflag = 0;      /* quiet flag */
185 int     nflag = 0;      /* don't update kernel routing table */
186 int     aflag = 0;      /* age out even the statically defined routes */
187 int     hflag = 0;      /* don't split horizon */
188 int     lflag = 0;      /* exchange site local routes */
189 int     Pflag = 0;      /* don't age out routes with RTF_PROTO[123] */
190 int     Qflag = RTF_PROTO2;     /* set RTF_PROTO[123] flag to routes by RIPng */
191 int     sflag = 0;      /* announce static routes w/ split horizon */
192 int     Sflag = 0;      /* announce static routes to every interface */
193 unsigned long routetag = 0;     /* route tag attached on originating case */
194
195 char    *filter[MAXFILTER];
196 int     filtertype[MAXFILTER];
197 int     nfilter = 0;
198
199 pid_t   pid;
200
201 struct  sockaddr_storage ripsin;
202
203 int     interval = 1;
204 time_t  nextalarm = 0;
205 time_t  sup_trig_update = 0;
206
207 FILE    *rtlog = NULL;
208
209 int logopened = 0;
210
211 static  int     seq = 0;
212
213 volatile sig_atomic_t seenalrm;
214 volatile sig_atomic_t seenquit;
215 volatile sig_atomic_t seenusr1;
216
217 #define RRTF_AGGREGATE          0x08000000
218 #define RRTF_NOADVERTISE        0x10000000
219 #define RRTF_NH_NOT_LLADDR      0x20000000
220 #define RRTF_SENDANYWAY         0x40000000
221 #define RRTF_CHANGED            0x80000000
222
223 int main(int, char **);
224 void sighandler(int);
225 void ripalarm(void);
226 void riprecv(void);
227 void ripsend(struct ifc *, struct sockaddr_in6 *, int);
228 int out_filter(struct riprt *, struct ifc *);
229 void init(void);
230 void sockopt(struct ifc *);
231 void ifconfig(void);
232 int ifconfig1(const char *, const struct sockaddr *, struct ifc *, int);
233 void rtrecv(void);
234 int rt_del(const struct sockaddr_in6 *, const struct sockaddr_in6 *,
235         const struct sockaddr_in6 *);
236 int rt_deladdr(struct ifc *, const struct sockaddr_in6 *,
237         const struct sockaddr_in6 *);
238 void filterconfig(void);
239 int getifmtu(int);
240 const char *rttypes(struct rt_msghdr *);
241 const char *rtflags(struct rt_msghdr *);
242 const char *ifflags(int);
243 int ifrt(struct ifc *, int);
244 void ifrt_p2p(struct ifc *, int);
245 void applymask(struct in6_addr *, struct in6_addr *);
246 void applyplen(struct in6_addr *, int);
247 void ifrtdump(int);
248 void ifdump(int);
249 void ifdump0(FILE *, const struct ifc *);
250 void ifremove(int);
251 void rtdump(int);
252 void rt_entry(struct rt_msghdr *, int);
253 void rtdexit(void);
254 void riprequest(struct ifc *, struct netinfo6 *, int,
255         struct sockaddr_in6 *);
256 void ripflush(struct ifc *, struct sockaddr_in6 *, int, struct netinfo6 *np);
257 void sendrequest(struct ifc *);
258 int sin6mask2len(const struct sockaddr_in6 *);
259 int mask2len(const struct in6_addr *, int);
260 int sendpacket(struct sockaddr_in6 *, int);
261 int addroute(struct riprt *, const struct in6_addr *, struct ifc *);
262 int delroute(struct netinfo6 *, struct in6_addr *);
263 struct in6_addr *getroute(struct netinfo6 *, struct in6_addr *);
264 void krtread(int);
265 int tobeadv(struct riprt *, struct ifc *);
266 char *allocopy(char *);
267 char *hms(void);
268 const char *inet6_n2p(const struct in6_addr *);
269 struct ifac *ifa_match(const struct ifc *, const struct in6_addr *, int);
270 struct in6_addr *plen2mask(int);
271 struct riprt *rtsearch(struct netinfo6 *);
272 int ripinterval(int);
273 time_t ripsuptrig(void);
274 void fatal(const char *, ...)
275         __attribute__((__format__(__printf__, 1, 2)));
276 void trace(int, const char *, ...)
277         __attribute__((__format__(__printf__, 2, 3)));
278 void tracet(int, const char *, ...)
279         __attribute__((__format__(__printf__, 2, 3)));
280 unsigned int if_maxindex(void);
281 struct ifc *ifc_find(char *);
282 struct iff *iff_find(struct ifc *, int);
283 void setindex2ifc(int, struct ifc *);
284
285 #define MALLOC(type)    ((type *)malloc(sizeof(type)))
286
287 #define IFIL_TYPE_ANY   0x0
288 #define IFIL_TYPE_A     'A'
289 #define IFIL_TYPE_N     'N'
290 #define IFIL_TYPE_T     'T'
291 #define IFIL_TYPE_O     'O'
292 #define IFIL_TYPE_L     'L'
293
294 int
295 main(int argc, char *argv[])
296 {
297         int     ch;
298         int     error = 0;
299         unsigned long proto;
300         struct  ifc *ifcp;
301         sigset_t mask, omask;
302         const char *pidfile = ROUTE6D_PID;
303         FILE *pidfh;
304         char *progname;
305         char *ep;
306
307         progname = strrchr(*argv, '/');
308         if (progname)
309                 progname++;
310         else
311                 progname = *argv;
312
313         pid = getpid();
314         while ((ch = getopt(argc, argv, "A:N:O:R:T:L:t:adDhlnp:P:Q:qsS")) != -1) {
315                 switch (ch) {
316                 case 'A':
317                 case 'N':
318                 case 'O':
319                 case 'T':
320                 case 'L':
321                         if (nfilter >= MAXFILTER) {
322                                 fatal("Exceeds MAXFILTER");
323                                 /*NOTREACHED*/
324                         }
325                         filtertype[nfilter] = ch;
326                         filter[nfilter++] = allocopy(optarg);
327                         break;
328                 case 't':
329                         ep = NULL;
330                         routetag = strtoul(optarg, &ep, 0);
331                         if (!ep || *ep != '\0' || (routetag & ~0xffff) != 0) {
332                                 fatal("invalid route tag");
333                                 /*NOTREACHED*/
334                         }
335                         break;
336                 case 'p':
337                         pidfile = optarg;
338                         break;
339                 case 'P':
340                         ep = NULL;
341                         proto = strtoul(optarg, &ep, 0);
342                         if (!ep || *ep != '\0' || 3 < proto) {
343                                 fatal("invalid P flag");
344                                 /*NOTREACHED*/
345                         }
346                         if (proto == 0)
347                                 Pflag = 0;
348                         if (proto == 1)
349                                 Pflag |= RTF_PROTO1;
350                         if (proto == 2)
351                                 Pflag |= RTF_PROTO2;
352                         if (proto == 3)
353                                 Pflag |= RTF_PROTO3;
354                         break;
355                 case 'Q':
356                         ep = NULL;
357                         proto = strtoul(optarg, &ep, 0);
358                         if (!ep || *ep != '\0' || 3 < proto) {
359                                 fatal("invalid Q flag");
360                                 /*NOTREACHED*/
361                         }
362                         if (proto == 0)
363                                 Qflag = 0;
364                         if (proto == 1)
365                                 Qflag |= RTF_PROTO1;
366                         if (proto == 2)
367                                 Qflag |= RTF_PROTO2;
368                         if (proto == 3)
369                                 Qflag |= RTF_PROTO3;
370                         break;
371                 case 'R':
372                         if ((rtlog = fopen(optarg, "w")) == NULL) {
373                                 fatal("Can not write to routelog");
374                                 /*NOTREACHED*/
375                         }
376                         break;
377 #define FLAG(c, flag, n)        case c: do { flag = n; break; } while(0)
378                 FLAG('a', aflag, 1); break;
379                 FLAG('d', dflag, 1); break;
380                 FLAG('D', dflag, 2); break;
381                 FLAG('h', hflag, 1); break;
382                 FLAG('l', lflag, 1); break;
383                 FLAG('n', nflag, 1); break;
384                 FLAG('q', qflag, 1); break;
385                 FLAG('s', sflag, 1); break;
386                 FLAG('S', Sflag, 1); break;
387 #undef  FLAG
388                 default:
389                         fatal("Invalid option specified, terminating");
390                         /*NOTREACHED*/
391                 }
392         }
393         argc -= optind;
394         argv += optind;
395         if (argc > 0) {
396                 fatal("bogus extra arguments");
397                 /*NOTREACHED*/
398         }
399
400         if (geteuid()) {
401                 nflag = 1;
402                 fprintf(stderr, "No kernel update is allowed\n");
403         }
404
405         if (dflag == 0) {
406                 if (daemon(0, 0) < 0) {
407                         fatal("daemon");
408                         /*NOTREACHED*/
409                 }
410         }
411
412         openlog(progname, LOG_NDELAY|LOG_PID, LOG_DAEMON);
413         logopened++;
414
415         if ((ripbuf = (struct rip6 *)malloc(RIP6_MAXMTU)) == NULL)
416                 fatal("malloc");
417         memset(ripbuf, 0, RIP6_MAXMTU);
418         ripbuf->rip6_cmd = RIP6_RESPONSE;
419         ripbuf->rip6_vers = RIP6_VERSION;
420         ripbuf->rip6_res1[0] = 0;
421         ripbuf->rip6_res1[1] = 0;
422
423         init();
424         ifconfig();
425         TAILQ_FOREACH(ifcp, &ifc_head, ifc_next) {
426                 if (ifcp->ifc_index < 0) {
427                         fprintf(stderr, "No ifindex found at %s "
428                             "(no link-local address?)\n", ifcp->ifc_name);
429                         error++;
430                 }
431         }
432         if (error)
433                 exit(1);
434         if (loopifcp == NULL) {
435                 fatal("No loopback found");
436                 /*NOTREACHED*/
437         }
438         TAILQ_FOREACH(ifcp, &ifc_head, ifc_next) {
439                 ifrt(ifcp, 0);
440         }
441         filterconfig();
442         krtread(0);
443         if (dflag)
444                 ifrtdump(0);
445
446         pid = getpid();
447         if ((pidfh = fopen(pidfile, "w")) != NULL) {
448                 fprintf(pidfh, "%d\n", pid);
449                 fclose(pidfh);
450         }
451
452         if ((ripbuf = (struct rip6 *)malloc(RIP6_MAXMTU)) == NULL) {
453                 fatal("malloc");
454                 /*NOTREACHED*/
455         }
456         memset(ripbuf, 0, RIP6_MAXMTU);
457         ripbuf->rip6_cmd = RIP6_RESPONSE;
458         ripbuf->rip6_vers = RIP6_VERSION;
459         ripbuf->rip6_res1[0] = 0;
460         ripbuf->rip6_res1[1] = 0;
461
462         if (signal(SIGALRM, sighandler) == SIG_ERR ||
463             signal(SIGQUIT, sighandler) == SIG_ERR ||
464             signal(SIGTERM, sighandler) == SIG_ERR ||
465             signal(SIGUSR1, sighandler) == SIG_ERR ||
466             signal(SIGHUP, sighandler) == SIG_ERR ||
467             signal(SIGINT, sighandler) == SIG_ERR) {
468                 fatal("signal");
469                 /*NOTREACHED*/
470         }
471         /*
472          * To avoid rip packet congestion (not on a cable but in this
473          * process), wait for a moment to send the first RIP6_RESPONSE
474          * packets.
475          */
476         alarm(ripinterval(INIT_INTERVAL6));
477
478         TAILQ_FOREACH(ifcp, &ifc_head, ifc_next) {
479                 if (iff_find(ifcp, IFIL_TYPE_N) != NULL)
480                         continue;
481                 if (ifcp->ifc_index > 0 && (ifcp->ifc_flags & IFF_UP))
482                         sendrequest(ifcp);
483         }
484
485         syslog(LOG_INFO, "**** Started ****");
486         sigemptyset(&mask);
487         sigaddset(&mask, SIGALRM);
488         while (1) {
489                 if (seenalrm) {
490                         ripalarm();
491                         seenalrm = 0;
492                         continue;
493                 }
494                 if (seenquit) {
495                         rtdexit();
496                         seenquit = 0;
497                         continue;
498                 }
499                 if (seenusr1) {
500                         ifrtdump(SIGUSR1);
501                         seenusr1 = 0;
502                         continue;
503                 }
504
505 #ifdef HAVE_POLL_H
506                 switch (poll(set, 2, INFTIM))
507 #else
508                 memcpy(recvecp, sockvecp, fdmasks);
509                 switch (select(maxfd + 1, recvecp, 0, 0, 0))
510 #endif
511                 {
512                 case -1:
513                         if (errno != EINTR) {
514                                 fatal("select");
515                                 /*NOTREACHED*/
516                         }
517                         continue;
518                 case 0:
519                         continue;
520                 default:
521 #ifdef HAVE_POLL_H
522                         if (set[0].revents & POLLIN)
523 #else
524                         if (FD_ISSET(ripsock, recvecp))
525 #endif
526                         {
527                                 sigprocmask(SIG_BLOCK, &mask, &omask);
528                                 riprecv();
529                                 sigprocmask(SIG_SETMASK, &omask, NULL);
530                         }
531 #ifdef HAVE_POLL_H
532                         if (set[1].revents & POLLIN)
533 #else
534                         if (FD_ISSET(rtsock, recvecp))
535 #endif
536                         {
537                                 sigprocmask(SIG_BLOCK, &mask, &omask);
538                                 rtrecv();
539                                 sigprocmask(SIG_SETMASK, &omask, NULL);
540                         }
541                 }
542         }
543 }
544
545 void
546 sighandler(int signo)
547 {
548
549         switch (signo) {
550         case SIGALRM:
551                 seenalrm++;
552                 break;
553         case SIGQUIT:
554         case SIGTERM:
555                 seenquit++;
556                 break;
557         case SIGUSR1:
558         case SIGHUP:
559         case SIGINT:
560                 seenusr1++;
561                 break;
562         }
563 }
564
565 /*
566  * gracefully exits after resetting sockopts.
567  */
568 /* ARGSUSED */
569 void
570 rtdexit(void)
571 {
572         struct  riprt *rrt;
573
574         alarm(0);
575         TAILQ_FOREACH(rrt, &riprt_head, rrt_next) {
576                 if (rrt->rrt_rflags & RRTF_AGGREGATE) {
577                         delroute(&rrt->rrt_info, &rrt->rrt_gw);
578                 }
579         }
580         close(ripsock);
581         close(rtsock);
582         syslog(LOG_INFO, "**** Terminated ****");
583         closelog();
584         exit(1);
585 }
586
587 /*
588  * Called periodically:
589  *      1. age out the learned route. remove it if necessary.
590  *      2. submit RIP6_RESPONSE packets.
591  * Invoked in every SUPPLY_INTERVAL6 (30) seconds.  I believe we don't have
592  * to invoke this function in every 1 or 5 or 10 seconds only to age the
593  * routes more precisely.
594  */
595 /* ARGSUSED */
596 void
597 ripalarm(void)
598 {
599         struct  ifc *ifcp;
600         struct  riprt *rrt, *rrt_tmp;
601         time_t  t_lifetime, t_holddown;
602
603         /* age the RIP routes */
604         t_lifetime = time(NULL) - RIP_LIFETIME;
605         t_holddown = t_lifetime - RIP_HOLDDOWN;
606         TAILQ_FOREACH_SAFE(rrt, &riprt_head, rrt_next, rrt_tmp) {
607                 if (rrt->rrt_t == 0)
608                         continue;
609                 else if (rrt->rrt_t < t_holddown) {
610                         TAILQ_REMOVE(&riprt_head, rrt, rrt_next);
611                         delroute(&rrt->rrt_info, &rrt->rrt_gw);
612                         free(rrt);
613                 } else if (rrt->rrt_t < t_lifetime)
614                         rrt->rrt_info.rip6_metric = HOPCNT_INFINITY6;
615         }
616         /* Supply updates */
617         TAILQ_FOREACH(ifcp, &ifc_head, ifc_next) {
618                 if (ifcp->ifc_index > 0 && (ifcp->ifc_flags & IFF_UP))
619                         ripsend(ifcp, &ifcp->ifc_ripsin, 0);
620         }
621         alarm(ripinterval(SUPPLY_INTERVAL6));
622 }
623
624 void
625 init(void)
626 {
627         int     error;
628         const int int0 = 0, int1 = 1, int255 = 255;
629         struct  addrinfo hints, *res;
630         char    port[NI_MAXSERV];
631
632         TAILQ_INIT(&ifc_head);
633         nindex2ifc = 0; /*initial guess*/
634         index2ifc = NULL;
635         snprintf(port, sizeof(port), "%u", RIP6_PORT);
636
637         memset(&hints, 0, sizeof(hints));
638         hints.ai_family = PF_INET6;
639         hints.ai_socktype = SOCK_DGRAM;
640         hints.ai_protocol = IPPROTO_UDP;
641         hints.ai_flags = AI_PASSIVE;
642         error = getaddrinfo(NULL, port, &hints, &res);
643         if (error) {
644                 fatal("%s", gai_strerror(error));
645                 /*NOTREACHED*/
646         }
647         if (res->ai_next) {
648                 fatal(":: resolved to multiple address");
649                 /*NOTREACHED*/
650         }
651
652         ripsock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
653         if (ripsock < 0) {
654                 fatal("rip socket");
655                 /*NOTREACHED*/
656         }
657 #ifdef IPV6_V6ONLY
658         if (setsockopt(ripsock, IPPROTO_IPV6, IPV6_V6ONLY,
659             &int1, sizeof(int1)) < 0) {
660                 fatal("rip IPV6_V6ONLY");
661                 /*NOTREACHED*/
662         }
663 #endif
664         if (bind(ripsock, res->ai_addr, res->ai_addrlen) < 0) {
665                 fatal("rip bind");
666                 /*NOTREACHED*/
667         }
668         if (setsockopt(ripsock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
669             &int255, sizeof(int255)) < 0) {
670                 fatal("rip IPV6_MULTICAST_HOPS");
671                 /*NOTREACHED*/
672         }
673         if (setsockopt(ripsock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
674             &int0, sizeof(int0)) < 0) {
675                 fatal("rip IPV6_MULTICAST_LOOP");
676                 /*NOTREACHED*/
677         }
678
679 #ifdef IPV6_RECVPKTINFO
680         if (setsockopt(ripsock, IPPROTO_IPV6, IPV6_RECVPKTINFO,
681             &int1, sizeof(int1)) < 0) {
682                 fatal("rip IPV6_RECVPKTINFO");
683                 /*NOTREACHED*/
684         }
685 #else  /* old adv. API */
686         if (setsockopt(ripsock, IPPROTO_IPV6, IPV6_PKTINFO,
687             &int1, sizeof(int1)) < 0) {
688                 fatal("rip IPV6_PKTINFO");
689                 /*NOTREACHED*/
690         }
691 #endif 
692
693 #ifdef IPV6_RECVPKTINFO
694         if (setsockopt(ripsock, IPPROTO_IPV6, IPV6_RECVHOPLIMIT,
695             &int1, sizeof(int1)) < 0) {
696                 fatal("rip IPV6_RECVHOPLIMIT");
697                 /*NOTREACHED*/
698         }
699 #else  /* old adv. API */
700         if (setsockopt(ripsock, IPPROTO_IPV6, IPV6_HOPLIMIT,
701             &int1, sizeof(int1)) < 0) {
702                 fatal("rip IPV6_HOPLIMIT");
703                 /*NOTREACHED*/
704         }
705 #endif
706
707         memset(&hints, 0, sizeof(hints));
708         hints.ai_family = PF_INET6;
709         hints.ai_socktype = SOCK_DGRAM;
710         hints.ai_protocol = IPPROTO_UDP;
711         error = getaddrinfo(RIP6_DEST, port, &hints, &res);
712         if (error) {
713                 fatal("%s", gai_strerror(error));
714                 /*NOTREACHED*/
715         }
716         if (res->ai_next) {
717                 fatal("%s resolved to multiple address", RIP6_DEST);
718                 /*NOTREACHED*/
719         }
720         memcpy(&ripsin, res->ai_addr, res->ai_addrlen);
721
722 #ifdef HAVE_POLL_H
723         set[0].fd = ripsock;
724         set[0].events = POLLIN;
725 #else
726         maxfd = ripsock;
727 #endif
728
729         if (nflag == 0) {
730                 if ((rtsock = socket(PF_ROUTE, SOCK_RAW, 0)) < 0) {
731                         fatal("route socket");
732                         /*NOTREACHED*/
733                 }
734 #ifdef HAVE_POLL_H
735                 set[1].fd = rtsock;
736                 set[1].events = POLLIN;
737 #else
738                 if (rtsock > maxfd)
739                         maxfd = rtsock;
740 #endif
741         } else {
742 #ifdef HAVE_POLL_H
743                 set[1].fd = -1;
744 #else
745                 rtsock = -1;    /*just for safety */
746 #endif
747         }
748
749 #ifndef HAVE_POLL_H
750         fdmasks = howmany(maxfd + 1, NFDBITS) * sizeof(fd_mask);
751         if ((sockvecp = malloc(fdmasks)) == NULL) {
752                 fatal("malloc");
753                 /*NOTREACHED*/
754         }
755         if ((recvecp = malloc(fdmasks)) == NULL) {
756                 fatal("malloc");
757                 /*NOTREACHED*/
758         }
759         memset(sockvecp, 0, fdmasks);
760         FD_SET(ripsock, sockvecp);
761         if (rtsock >= 0)
762                 FD_SET(rtsock, sockvecp);
763 #endif
764 }
765
766 #define RIPSIZE(n) \
767         (sizeof(struct rip6) + ((n)-1) * sizeof(struct netinfo6))
768
769 /*
770  * ripflush flushes the rip datagram stored in the rip buffer
771  */
772 void
773 ripflush(struct ifc *ifcp, struct sockaddr_in6 *sin6, int nrt, struct netinfo6 *np)
774 {
775         int i;
776         int error;
777
778         if (ifcp)
779                 tracet(1, "Send(%s): info(%d) to %s.%d\n",
780                         ifcp->ifc_name, nrt,
781                         inet6_n2p(&sin6->sin6_addr), ntohs(sin6->sin6_port));
782         else
783                 tracet(1, "Send: info(%d) to %s.%d\n",
784                         nrt, inet6_n2p(&sin6->sin6_addr), ntohs(sin6->sin6_port));
785         if (dflag >= 2) {
786                 np = ripbuf->rip6_nets;
787                 for (i = 0; i < nrt; i++, np++) {
788                         if (np->rip6_metric == NEXTHOP_METRIC) {
789                                 if (IN6_IS_ADDR_UNSPECIFIED(&np->rip6_dest))
790                                         trace(2, "    NextHop reset");
791                                 else {
792                                         trace(2, "    NextHop %s",
793                                                 inet6_n2p(&np->rip6_dest));
794                                 }
795                         } else {
796                                 trace(2, "    %s/%d[%d]",
797                                         inet6_n2p(&np->rip6_dest),
798                                         np->rip6_plen, np->rip6_metric);
799                         }
800                         if (np->rip6_tag) {
801                                 trace(2, "  tag=0x%04x",
802                                         ntohs(np->rip6_tag) & 0xffff);
803                         }
804                         trace(2, "\n");
805                 }
806         }
807         error = sendpacket(sin6, RIPSIZE(nrt));
808         if (error == EAFNOSUPPORT) {
809                 /* Protocol not supported */
810                 tracet(1, "Could not send info to %s (%s): "
811                         "set IFF_UP to 0\n",
812                         ifcp->ifc_name, inet6_n2p(&ifcp->ifc_ripsin.sin6_addr));
813                 ifcp->ifc_flags &= ~IFF_UP;     /* As if down for AF_INET6 */
814         }
815 }
816
817 /*
818  * Generate RIP6_RESPONSE packets and send them.
819  */
820 void
821 ripsend(struct  ifc *ifcp, struct sockaddr_in6 *sin6, int flag)
822 {
823         struct  riprt *rrt;
824         struct  in6_addr *nh;   /* next hop */
825         struct netinfo6 *np;
826         int     maxrte;
827         int nrt;
828
829         if (qflag)
830                 return;
831
832         if (ifcp == NULL) {
833                 /*
834                  * Request from non-link local address is not
835                  * a regular route6d update.
836                  */
837                 maxrte = (IFMINMTU - sizeof(struct ip6_hdr) - 
838                                 sizeof(struct udphdr) - 
839                                 sizeof(struct rip6) + sizeof(struct netinfo6)) /
840                                 sizeof(struct netinfo6);
841                 nh = NULL;
842                 nrt = 0;
843                 np = ripbuf->rip6_nets;
844                 TAILQ_FOREACH(rrt, &riprt_head, rrt_next) {
845                         if (rrt->rrt_rflags & RRTF_NOADVERTISE)
846                                 continue;
847                         /* Put the route to the buffer */
848                         *np = rrt->rrt_info;
849                         np++; nrt++;
850                         if (nrt == maxrte) {
851                                 ripflush(NULL, sin6, nrt, np);
852                                 nh = NULL;
853                                 nrt = 0;
854                                 np = ripbuf->rip6_nets;
855                         }
856                 }
857                 if (nrt)        /* Send last packet */
858                         ripflush(NULL, sin6, nrt, np);
859                 return;
860         }
861
862         if ((flag & RRTF_SENDANYWAY) == 0 &&
863             (qflag || (ifcp->ifc_flags & IFF_LOOPBACK)))
864                 return;
865
866         /* -N: no use */
867         if (iff_find(ifcp, IFIL_TYPE_N) != NULL)
868                 return;
869
870         /* -T: generate default route only */
871         if (iff_find(ifcp, IFIL_TYPE_T) != NULL) {
872                 struct netinfo6 rrt_info;
873                 memset(&rrt_info, 0, sizeof(struct netinfo6));
874                 rrt_info.rip6_dest = in6addr_any;
875                 rrt_info.rip6_plen = 0;
876                 rrt_info.rip6_metric = 1;
877                 rrt_info.rip6_metric += ifcp->ifc_metric;
878                 rrt_info.rip6_tag = htons(routetag & 0xffff);
879                 np = ripbuf->rip6_nets;
880                 *np = rrt_info;
881                 nrt = 1;
882                 ripflush(ifcp, sin6, nrt, np);
883                 return;
884         }
885
886         maxrte = (ifcp->ifc_mtu - sizeof(struct ip6_hdr) - 
887                         sizeof(struct udphdr) - 
888                         sizeof(struct rip6) + sizeof(struct netinfo6)) /
889                         sizeof(struct netinfo6);
890
891         nrt = 0; np = ripbuf->rip6_nets; nh = NULL;
892         TAILQ_FOREACH(rrt, &riprt_head, rrt_next) {
893                 if (rrt->rrt_rflags & RRTF_NOADVERTISE)
894                         continue;
895
896                 /* Need to check filter here */
897                 if (out_filter(rrt, ifcp) == 0)
898                         continue;
899
900                 /* Check split horizon and other conditions */
901                 if (tobeadv(rrt, ifcp) == 0)
902                         continue;
903
904                 /* Only considers the routes with flag if specified */
905                 if ((flag & RRTF_CHANGED) &&
906                     (rrt->rrt_rflags & RRTF_CHANGED) == 0)
907                         continue;
908
909                 /* Check nexthop */
910                 if (rrt->rrt_index == ifcp->ifc_index &&
911                     !IN6_IS_ADDR_UNSPECIFIED(&rrt->rrt_gw) &&
912                     (rrt->rrt_rflags & RRTF_NH_NOT_LLADDR) == 0) {
913                         if (nh == NULL || !IN6_ARE_ADDR_EQUAL(nh, &rrt->rrt_gw)) {
914                                 if (nrt == maxrte - 2) {
915                                         ripflush(ifcp, sin6, nrt, np);
916                                         nh = NULL;
917                                         nrt = 0;
918                                         np = ripbuf->rip6_nets;
919                                 }
920
921                                 np->rip6_dest = rrt->rrt_gw;
922                                 if (IN6_IS_ADDR_LINKLOCAL(&np->rip6_dest))
923                                         SET_IN6_LINKLOCAL_IFINDEX(np->rip6_dest, 0);
924                                 np->rip6_plen = 0;
925                                 np->rip6_tag = 0;
926                                 np->rip6_metric = NEXTHOP_METRIC;
927                                 nh = &rrt->rrt_gw;
928                                 np++; nrt++;
929                         }
930                 } else if (nh && (rrt->rrt_index != ifcp->ifc_index ||
931                                   !IN6_ARE_ADDR_EQUAL(nh, &rrt->rrt_gw) ||
932                                   rrt->rrt_rflags & RRTF_NH_NOT_LLADDR)) {
933                         /* Reset nexthop */
934                         if (nrt == maxrte - 2) {
935                                 ripflush(ifcp, sin6, nrt, np);
936                                 nh = NULL;
937                                 nrt = 0;
938                                 np = ripbuf->rip6_nets;
939                         }
940                         memset(np, 0, sizeof(struct netinfo6));
941                         np->rip6_metric = NEXTHOP_METRIC;
942                         nh = NULL;
943                         np++; nrt++;
944                 }
945
946                 /* Put the route to the buffer */
947                 *np = rrt->rrt_info;
948                 np++; nrt++;
949                 if (nrt == maxrte) {
950                         ripflush(ifcp, sin6, nrt, np);
951                         nh = NULL;
952                         nrt = 0;
953                         np = ripbuf->rip6_nets;
954                 }
955         }
956         if (nrt)        /* Send last packet */
957                 ripflush(ifcp, sin6, nrt, np);
958 }
959
960 /*
961  * outbound filter logic, per-route/interface.
962  */
963 int
964 out_filter(struct riprt *rrt, struct ifc *ifcp)
965 {
966         struct iff *iffp;
967         struct in6_addr ia;
968         int ok;
969
970         /*
971          * -A: filter out less specific routes, if we have aggregated
972          * route configured.
973          */ 
974         TAILQ_FOREACH(iffp, &ifcp->ifc_iff_head, iff_next) {
975                 if (iffp->iff_type != 'A')
976                         continue;
977                 if (rrt->rrt_info.rip6_plen <= iffp->iff_plen)
978                         continue;
979                 ia = rrt->rrt_info.rip6_dest; 
980                 applyplen(&ia, iffp->iff_plen);
981                 if (IN6_ARE_ADDR_EQUAL(&ia, &iffp->iff_addr))
982                         return 0;
983         }
984
985         /*
986          * if it is an aggregated route, advertise it only to the
987          * interfaces specified on -A.
988          */
989         if ((rrt->rrt_rflags & RRTF_AGGREGATE) != 0) {
990                 ok = 0;
991                 TAILQ_FOREACH(iffp, &ifcp->ifc_iff_head, iff_next) {
992                         if (iffp->iff_type != 'A')
993                                 continue;
994                         if (rrt->rrt_info.rip6_plen == iffp->iff_plen &&
995                             IN6_ARE_ADDR_EQUAL(&rrt->rrt_info.rip6_dest,
996                             &iffp->iff_addr)) {
997                                 ok = 1;
998                                 break;
999                         }
1000                 }
1001                 if (!ok)
1002                         return 0;
1003         }
1004
1005         /*
1006          * -O: advertise only if prefix matches the configured prefix.
1007          */
1008         if (iff_find(ifcp, IFIL_TYPE_O) != NULL) {
1009                 ok = 0;
1010                 TAILQ_FOREACH(iffp, &ifcp->ifc_iff_head, iff_next) {
1011                         if (iffp->iff_type != 'O')
1012                                 continue;
1013                         if (rrt->rrt_info.rip6_plen < iffp->iff_plen)
1014                                 continue;
1015                         ia = rrt->rrt_info.rip6_dest; 
1016                         applyplen(&ia, iffp->iff_plen);
1017                         if (IN6_ARE_ADDR_EQUAL(&ia, &iffp->iff_addr)) {
1018                                 ok = 1;
1019                                 break;
1020                         }
1021                 }
1022                 if (!ok)
1023                         return 0;
1024         }
1025
1026         /* the prefix should be advertised */
1027         return 1;
1028 }
1029
1030 /*
1031  * Determine if the route is to be advertised on the specified interface.
1032  * It checks options specified in the arguments and the split horizon rule.
1033  */
1034 int
1035 tobeadv(struct riprt *rrt, struct ifc *ifcp)
1036 {
1037
1038         /* Special care for static routes */
1039         if (rrt->rrt_flags & RTF_STATIC) {
1040                 /* XXX don't advertise reject/blackhole routes */
1041                 if (rrt->rrt_flags & (RTF_REJECT | RTF_BLACKHOLE))
1042                         return 0;
1043
1044                 if (Sflag)      /* Yes, advertise it anyway */
1045                         return 1;
1046                 if (sflag && rrt->rrt_index != ifcp->ifc_index)
1047                         return 1;
1048                 return 0;
1049         }
1050         /* Regular split horizon */
1051         if (hflag == 0 && rrt->rrt_index == ifcp->ifc_index)
1052                 return 0;
1053         return 1;
1054 }
1055
1056 /*
1057  * Send a rip packet actually.
1058  */
1059 int
1060 sendpacket(struct sockaddr_in6 *sin6, int len)
1061 {
1062         struct msghdr m;
1063         struct cmsghdr *cm;
1064         struct iovec iov[2];
1065         u_char cmsgbuf[256];
1066         struct in6_pktinfo *pi;
1067         int idx;
1068         struct sockaddr_in6 sincopy;
1069
1070         /* do not overwrite the given sin */
1071         sincopy = *sin6;
1072         sin6 = &sincopy;
1073
1074         if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr) ||
1075             IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) {
1076                 /* XXX: do not mix the interface index and link index */
1077                 idx = IN6_LINKLOCAL_IFINDEX(sin6->sin6_addr);
1078                 SET_IN6_LINKLOCAL_IFINDEX(sin6->sin6_addr, 0);
1079                 sin6->sin6_scope_id = idx;
1080         } else
1081                 idx = 0;
1082
1083         m.msg_name = (caddr_t)sin6;
1084         m.msg_namelen = sizeof(*sin6);
1085         iov[0].iov_base = (caddr_t)ripbuf;
1086         iov[0].iov_len = len;
1087         m.msg_iov = iov;
1088         m.msg_iovlen = 1;
1089         if (!idx) {
1090                 m.msg_control = NULL;
1091                 m.msg_controllen = 0;
1092         } else {
1093                 memset(cmsgbuf, 0, sizeof(cmsgbuf));
1094                 cm = (struct cmsghdr *)cmsgbuf;
1095                 m.msg_control = (caddr_t)cm;
1096                 m.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
1097
1098                 cm->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
1099                 cm->cmsg_level = IPPROTO_IPV6;
1100                 cm->cmsg_type = IPV6_PKTINFO;
1101                 pi = (struct in6_pktinfo *)CMSG_DATA(cm);
1102                 memset(&pi->ipi6_addr, 0, sizeof(pi->ipi6_addr)); /*::*/
1103                 pi->ipi6_ifindex = idx;
1104         }
1105
1106         if (sendmsg(ripsock, &m, 0 /*MSG_DONTROUTE*/) < 0) {
1107                 trace(1, "sendmsg: %s\n", strerror(errno));
1108                 return errno;
1109         }
1110
1111         return 0;
1112 }
1113
1114 /*
1115  * Receive and process RIP packets.  Update the routes/kernel forwarding
1116  * table if necessary.
1117  */
1118 void
1119 riprecv(void)
1120 {
1121         struct  ifc *ifcp, *ic;
1122         struct  sockaddr_in6 fsock;
1123         struct  in6_addr nh;    /* next hop */
1124         struct  rip6 *rp;
1125         struct  netinfo6 *np, *nq;
1126         struct  riprt *rrt;
1127         ssize_t len, nn;
1128         unsigned int need_trigger, idx;
1129         char    buf[4 * RIP6_MAXMTU];
1130         time_t  t;
1131         struct msghdr m;
1132         struct cmsghdr *cm;
1133         struct iovec iov[2];
1134         u_char cmsgbuf[256];
1135         struct in6_pktinfo *pi = NULL;
1136         int *hlimp = NULL;
1137         struct iff *iffp;
1138         struct in6_addr ia;
1139         int ok;
1140         time_t t_half_lifetime;
1141
1142         need_trigger = 0;
1143
1144         m.msg_name = (caddr_t)&fsock;
1145         m.msg_namelen = sizeof(fsock);
1146         iov[0].iov_base = (caddr_t)buf;
1147         iov[0].iov_len = sizeof(buf);
1148         m.msg_iov = iov;
1149         m.msg_iovlen = 1;
1150         cm = (struct cmsghdr *)cmsgbuf;
1151         m.msg_control = (caddr_t)cm;
1152         m.msg_controllen = sizeof(cmsgbuf);
1153         if ((len = recvmsg(ripsock, &m, 0)) < 0) {
1154                 fatal("recvmsg");
1155                 /*NOTREACHED*/
1156         }
1157         idx = 0;
1158         for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(&m);
1159              cm;
1160              cm = (struct cmsghdr *)CMSG_NXTHDR(&m, cm)) {
1161                 if (cm->cmsg_level != IPPROTO_IPV6)
1162                     continue;
1163                 switch (cm->cmsg_type) {
1164                 case IPV6_PKTINFO:
1165                         if (cm->cmsg_len != CMSG_LEN(sizeof(*pi))) {
1166                                 trace(1,
1167                                     "invalid cmsg length for IPV6_PKTINFO\n");
1168                                 return;
1169                         }
1170                         pi = (struct in6_pktinfo *)(CMSG_DATA(cm));
1171                         idx = pi->ipi6_ifindex;
1172                         break;
1173                 case IPV6_HOPLIMIT:
1174                         if (cm->cmsg_len != CMSG_LEN(sizeof(int))) {
1175                                 trace(1,
1176                                     "invalid cmsg length for IPV6_HOPLIMIT\n");
1177                                 return;
1178                         }
1179                         hlimp = (int *)CMSG_DATA(cm);
1180                         break;
1181                 }
1182         }
1183         if (idx && IN6_IS_ADDR_LINKLOCAL(&fsock.sin6_addr))
1184                 SET_IN6_LINKLOCAL_IFINDEX(fsock.sin6_addr, idx);
1185
1186         if ((size_t)len < sizeof(struct rip6)) {
1187                 trace(1, "Packet too short\n");
1188                 return;
1189         }
1190
1191         if (pi == NULL || hlimp == NULL) {
1192                 /*
1193                  * This can happen when the kernel failed to allocate memory
1194                  * for the ancillary data.  Although we might be able to handle
1195                  * some cases without this info, those are minor and not so
1196                  * important, so it's better to discard the packet for safer
1197                  * operation.
1198                  */
1199                 trace(1, "IPv6 packet information cannot be retrieved\n");
1200                 return;
1201         }
1202
1203         nh = fsock.sin6_addr;
1204         nn = (len - sizeof(struct rip6) + sizeof(struct netinfo6)) /
1205                 sizeof(struct netinfo6);
1206         rp = (struct rip6 *)buf;
1207         np = rp->rip6_nets;
1208
1209         if (rp->rip6_vers != RIP6_VERSION) {
1210                 trace(1, "Incorrect RIP version %d\n", rp->rip6_vers);
1211                 return;
1212         }
1213         if (rp->rip6_cmd == RIP6_REQUEST) {
1214                 if (idx && idx < nindex2ifc) {
1215                         ifcp = index2ifc[idx];
1216                         riprequest(ifcp, np, nn, &fsock);
1217                 } else {
1218                         riprequest(NULL, np, nn, &fsock);
1219                 }
1220                 return; 
1221         } 
1222
1223         if (!IN6_IS_ADDR_LINKLOCAL(&fsock.sin6_addr)) {
1224                 trace(1, "Response from non-ll addr: %s\n",
1225                     inet6_n2p(&fsock.sin6_addr));
1226                 return;         /* Ignore packets from non-link-local addr */
1227         }
1228         if (ntohs(fsock.sin6_port) != RIP6_PORT) {
1229                 trace(1, "Response from non-rip port from %s\n",
1230                     inet6_n2p(&fsock.sin6_addr));
1231                 return;
1232         }
1233         if (IN6_IS_ADDR_MULTICAST(&pi->ipi6_addr) && *hlimp != 255) {
1234                 trace(1,
1235                     "Response packet with a smaller hop limit (%d) from %s\n",
1236                     *hlimp, inet6_n2p(&fsock.sin6_addr));
1237                 return;
1238         }
1239         /*
1240          * Further validation: since this program does not send off-link
1241          * requests, an incoming response must always come from an on-link
1242          * node.  Although this is normally ensured by the source address
1243          * check above, it may not 100% be safe because there are router
1244          * implementations that (invalidly) allow a packet with a link-local
1245          * source address to be forwarded to a different link.
1246          * So we also check whether the destination address is a link-local
1247          * address or the hop limit is 255.  Note that RFC2080 does not require
1248          * the specific hop limit for a unicast response, so we cannot assume 
1249          * the limitation.
1250          */
1251         if (!IN6_IS_ADDR_LINKLOCAL(&pi->ipi6_addr) && *hlimp != 255) {
1252                 trace(1,
1253                     "Response packet possibly from an off-link node: "
1254                     "from %s to %s hlim=%d\n",
1255                     inet6_n2p(&fsock.sin6_addr),
1256                     inet6_n2p(&pi->ipi6_addr), *hlimp);
1257                 return;
1258         }
1259
1260         idx = IN6_LINKLOCAL_IFINDEX(fsock.sin6_addr);
1261         ifcp = (idx < nindex2ifc) ? index2ifc[idx] : NULL;
1262         if (!ifcp) {
1263                 trace(1, "Packets to unknown interface index %d\n", idx);
1264                 return;         /* Ignore it */
1265         }
1266         if (IN6_ARE_ADDR_EQUAL(&ifcp->ifc_mylladdr, &fsock.sin6_addr))
1267                 return;         /* The packet is from me; ignore */
1268         if (rp->rip6_cmd != RIP6_RESPONSE) {
1269                 trace(1, "Invalid command %d\n", rp->rip6_cmd);
1270                 return; 
1271         }
1272
1273         /* -N: no use */
1274         if (iff_find(ifcp, IFIL_TYPE_N) != NULL)
1275                 return;
1276
1277         tracet(1, "Recv(%s): from %s.%d info(%zd)\n",
1278             ifcp->ifc_name, inet6_n2p(&nh), ntohs(fsock.sin6_port), nn);
1279
1280         t = time(NULL);
1281         t_half_lifetime = t - (RIP_LIFETIME/2);
1282         for (; nn; nn--, np++) {
1283                 if (np->rip6_metric == NEXTHOP_METRIC) {
1284                         /* modify neighbor address */
1285                         if (IN6_IS_ADDR_LINKLOCAL(&np->rip6_dest)) {
1286                                 nh = np->rip6_dest;
1287                                 SET_IN6_LINKLOCAL_IFINDEX(nh, idx);
1288                                 trace(1, "\tNexthop: %s\n", inet6_n2p(&nh));
1289                         } else if (IN6_IS_ADDR_UNSPECIFIED(&np->rip6_dest)) {
1290                                 nh = fsock.sin6_addr;
1291                                 trace(1, "\tNexthop: %s\n", inet6_n2p(&nh));
1292                         } else {
1293                                 nh = fsock.sin6_addr;
1294                                 trace(1, "\tInvalid Nexthop: %s\n",
1295                                     inet6_n2p(&np->rip6_dest));
1296                         }
1297                         continue;
1298                 }
1299                 if (IN6_IS_ADDR_MULTICAST(&np->rip6_dest)) {
1300                         trace(1, "\tMulticast netinfo6: %s/%d [%d]\n",
1301                                 inet6_n2p(&np->rip6_dest),
1302                                 np->rip6_plen, np->rip6_metric);
1303                         continue;
1304                 }
1305                 if (IN6_IS_ADDR_LOOPBACK(&np->rip6_dest)) {
1306                         trace(1, "\tLoopback netinfo6: %s/%d [%d]\n",
1307                                 inet6_n2p(&np->rip6_dest),
1308                                 np->rip6_plen, np->rip6_metric);
1309                         continue;
1310                 }
1311                 if (IN6_IS_ADDR_LINKLOCAL(&np->rip6_dest)) {
1312                         trace(1, "\tLink Local netinfo6: %s/%d [%d]\n",
1313                                 inet6_n2p(&np->rip6_dest),
1314                                 np->rip6_plen, np->rip6_metric);
1315                         continue;
1316                 }
1317                 /* may need to pass sitelocal prefix in some case, however*/
1318                 if (IN6_IS_ADDR_SITELOCAL(&np->rip6_dest) && !lflag) {
1319                         trace(1, "\tSite Local netinfo6: %s/%d [%d]\n",
1320                                 inet6_n2p(&np->rip6_dest),
1321                                 np->rip6_plen, np->rip6_metric);
1322                         continue;
1323                 }
1324                 trace(2, "\tnetinfo6: %s/%d [%d]",
1325                         inet6_n2p(&np->rip6_dest),
1326                         np->rip6_plen, np->rip6_metric);
1327                 if (np->rip6_tag)
1328                         trace(2, "  tag=0x%04x", ntohs(np->rip6_tag) & 0xffff);
1329                 if (dflag >= 2) {
1330                         ia = np->rip6_dest;
1331                         applyplen(&ia, np->rip6_plen);
1332                         if (!IN6_ARE_ADDR_EQUAL(&ia, &np->rip6_dest))
1333                                 trace(2, " [junk outside prefix]");
1334                 }
1335
1336                 /*
1337                  * -L: listen only if the prefix matches the configuration
1338                  */
1339                 ok = 1; /* if there's no L filter, it is ok */
1340                 TAILQ_FOREACH(iffp, &ifcp->ifc_iff_head, iff_next) {
1341                         if (iffp->iff_type != IFIL_TYPE_L)
1342                                 continue;
1343                         ok = 0;
1344                         if (np->rip6_plen < iffp->iff_plen)
1345                                 continue;
1346                         /* special rule: ::/0 means default, not "in /0" */
1347                         if (iffp->iff_plen == 0 && np->rip6_plen > 0)
1348                                 continue;
1349                         ia = np->rip6_dest; 
1350                         applyplen(&ia, iffp->iff_plen);
1351                         if (IN6_ARE_ADDR_EQUAL(&ia, &iffp->iff_addr)) {
1352                                 ok = 1;
1353                                 break;
1354                         }
1355                 }
1356                 if (!ok) {
1357                         trace(2, "  (filtered)\n");
1358                         continue;
1359                 }
1360
1361                 trace(2, "\n");
1362                 np->rip6_metric++;
1363                 np->rip6_metric += ifcp->ifc_metric;
1364                 if (np->rip6_metric > HOPCNT_INFINITY6)
1365                         np->rip6_metric = HOPCNT_INFINITY6;
1366
1367                 applyplen(&np->rip6_dest, np->rip6_plen);
1368                 if ((rrt = rtsearch(np)) != NULL) {
1369                         if (rrt->rrt_t == 0)
1370                                 continue;       /* Intf route has priority */
1371                         nq = &rrt->rrt_info;
1372                         if (nq->rip6_metric > np->rip6_metric) {
1373                                 if (rrt->rrt_index == ifcp->ifc_index &&
1374                                     IN6_ARE_ADDR_EQUAL(&nh, &rrt->rrt_gw)) {
1375                                         /* Small metric from the same gateway */
1376                                         nq->rip6_metric = np->rip6_metric;
1377                                 } else {
1378                                         /* Better route found */
1379                                         rrt->rrt_index = ifcp->ifc_index;
1380                                         /* Update routing table */
1381                                         delroute(nq, &rrt->rrt_gw);
1382                                         rrt->rrt_gw = nh;
1383                                         *nq = *np;
1384                                         addroute(rrt, &nh, ifcp);
1385                                 }
1386                                 rrt->rrt_rflags |= RRTF_CHANGED;
1387                                 rrt->rrt_t = t;
1388                                 need_trigger = 1;
1389                         } else if (nq->rip6_metric < np->rip6_metric &&
1390                                    rrt->rrt_index == ifcp->ifc_index &&
1391                                    IN6_ARE_ADDR_EQUAL(&nh, &rrt->rrt_gw)) {
1392                                 /* Got worse route from same gw */
1393                                 nq->rip6_metric = np->rip6_metric;
1394                                 rrt->rrt_t = t;
1395                                 rrt->rrt_rflags |= RRTF_CHANGED;
1396                                 need_trigger = 1;
1397                         } else if (nq->rip6_metric == np->rip6_metric &&
1398                                    np->rip6_metric < HOPCNT_INFINITY6) {
1399                                 if (rrt->rrt_index == ifcp->ifc_index &&
1400                                    IN6_ARE_ADDR_EQUAL(&nh, &rrt->rrt_gw)) { 
1401                                         /* same metric, same route from same gw */
1402                                         rrt->rrt_t = t;
1403                                 } else if (rrt->rrt_t < t_half_lifetime) {
1404                                         /* Better route found */
1405                                         rrt->rrt_index = ifcp->ifc_index;
1406                                         /* Update routing table */
1407                                         delroute(nq, &rrt->rrt_gw);
1408                                         rrt->rrt_gw = nh;
1409                                         *nq = *np;
1410                                         addroute(rrt, &nh, ifcp);
1411                                         rrt->rrt_rflags |= RRTF_CHANGED;
1412                                         rrt->rrt_t = t;
1413                                 }
1414                         }
1415                         /* 
1416                          * if nq->rip6_metric == HOPCNT_INFINITY6 then
1417                          * do not update age value.  Do nothing.
1418                          */
1419                 } else if (np->rip6_metric < HOPCNT_INFINITY6) {
1420                         /* Got a new valid route */
1421                         if ((rrt = MALLOC(struct riprt)) == NULL) {
1422                                 fatal("malloc: struct riprt");
1423                                 /*NOTREACHED*/
1424                         }
1425                         memset(rrt, 0, sizeof(*rrt));
1426                         nq = &rrt->rrt_info;
1427
1428                         rrt->rrt_same = NULL;
1429                         rrt->rrt_index = ifcp->ifc_index;
1430                         rrt->rrt_flags = RTF_UP|RTF_GATEWAY;
1431                         rrt->rrt_gw = nh;
1432                         *nq = *np;
1433                         applyplen(&nq->rip6_dest, nq->rip6_plen);
1434                         if (nq->rip6_plen == sizeof(struct in6_addr) * 8)
1435                                 rrt->rrt_flags |= RTF_HOST;
1436
1437                         /* Update routing table */
1438                         addroute(rrt, &nh, ifcp);
1439                         rrt->rrt_rflags |= RRTF_CHANGED;
1440                         need_trigger = 1;
1441                         rrt->rrt_t = t;
1442
1443                         /* Put the route to the list */
1444                         TAILQ_INSERT_HEAD(&riprt_head, rrt, rrt_next);
1445                 }
1446         }
1447         /* XXX need to care the interval between triggered updates */
1448         if (need_trigger) {
1449                 if (nextalarm > time(NULL) + RIP_TRIG_INT6_MAX) {
1450                         TAILQ_FOREACH(ic, &ifc_head, ifc_next) {
1451                                 if (ifcp->ifc_index == ic->ifc_index)
1452                                         continue;
1453                                 if (ic->ifc_flags & IFF_UP)
1454                                         ripsend(ic, &ic->ifc_ripsin,
1455                                                 RRTF_CHANGED);
1456                         }
1457                 }
1458                 /* Reset the flag */
1459                 TAILQ_FOREACH(rrt, &riprt_head, rrt_next) {
1460                         rrt->rrt_rflags &= ~RRTF_CHANGED;
1461                 }
1462         }
1463 }
1464
1465 /*
1466  * Send all routes request packet to the specified interface.
1467  */
1468 void
1469 sendrequest(struct ifc *ifcp)
1470 {
1471         struct netinfo6 *np;
1472         int error;
1473
1474         if (ifcp->ifc_flags & IFF_LOOPBACK)
1475                 return;
1476         ripbuf->rip6_cmd = RIP6_REQUEST;
1477         np = ripbuf->rip6_nets;
1478         memset(np, 0, sizeof(struct netinfo6));
1479         np->rip6_metric = HOPCNT_INFINITY6;
1480         tracet(1, "Send rtdump Request to %s (%s)\n",
1481                 ifcp->ifc_name, inet6_n2p(&ifcp->ifc_ripsin.sin6_addr));
1482         error = sendpacket(&ifcp->ifc_ripsin, RIPSIZE(1));
1483         if (error == EAFNOSUPPORT) {
1484                 /* Protocol not supported */
1485                 tracet(1, "Could not send rtdump Request to %s (%s): "
1486                         "set IFF_UP to 0\n",
1487                         ifcp->ifc_name, inet6_n2p(&ifcp->ifc_ripsin.sin6_addr));
1488                 ifcp->ifc_flags &= ~IFF_UP;     /* As if down for AF_INET6 */
1489         }
1490         ripbuf->rip6_cmd = RIP6_RESPONSE;
1491 }
1492
1493 /*
1494  * Process a RIP6_REQUEST packet.
1495  */
1496 void
1497 riprequest(struct ifc *ifcp,
1498         struct netinfo6 *np,
1499         int nn,
1500         struct sockaddr_in6 *sin6)
1501 {
1502         int i;
1503         struct riprt *rrt;
1504
1505         if (!(nn == 1 && IN6_IS_ADDR_UNSPECIFIED(&np->rip6_dest) &&
1506               np->rip6_plen == 0 && np->rip6_metric == HOPCNT_INFINITY6)) {
1507                 /* Specific response, don't split-horizon */
1508                 trace(1, "\tRIP Request\n");
1509                 for (i = 0; i < nn; i++, np++) {
1510                         rrt = rtsearch(np);
1511                         if (rrt)
1512                                 np->rip6_metric = rrt->rrt_info.rip6_metric;
1513                         else
1514                                 np->rip6_metric = HOPCNT_INFINITY6;
1515                 }
1516                 (void)sendpacket(sin6, RIPSIZE(nn));
1517                 return;
1518         }
1519         /* Whole routing table dump */
1520         trace(1, "\tRIP Request -- whole routing table\n");
1521         ripsend(ifcp, sin6, RRTF_SENDANYWAY);
1522 }
1523
1524 /*
1525  * Get information of each interface.
1526  */
1527 void
1528 ifconfig(void)
1529 {
1530         struct ifaddrs *ifap, *ifa;
1531         struct ifc *ifcp;
1532         struct ipv6_mreq mreq;
1533         int s;
1534
1535         if ((s = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
1536                 fatal("socket");
1537                 /*NOTREACHED*/
1538         }
1539
1540         if (getifaddrs(&ifap) != 0) {
1541                 fatal("getifaddrs");
1542                 /*NOTREACHED*/
1543         }
1544
1545         for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
1546                 if (ifa->ifa_addr->sa_family != AF_INET6)
1547                         continue;
1548                 ifcp = ifc_find(ifa->ifa_name);
1549                 /* we are interested in multicast-capable interfaces */
1550                 if ((ifa->ifa_flags & IFF_MULTICAST) == 0)
1551                         continue;
1552                 if (!ifcp) {
1553                         /* new interface */
1554                         if ((ifcp = MALLOC(struct ifc)) == NULL) {
1555                                 fatal("malloc: struct ifc");
1556                                 /*NOTREACHED*/
1557                         }
1558                         memset(ifcp, 0, sizeof(*ifcp));
1559
1560                         ifcp->ifc_index = -1;
1561                         strlcpy(ifcp->ifc_name, ifa->ifa_name,
1562                             sizeof(ifcp->ifc_name));
1563                         TAILQ_INIT(&ifcp->ifc_ifac_head);
1564                         TAILQ_INIT(&ifcp->ifc_iff_head);
1565                         ifcp->ifc_flags = ifa->ifa_flags;
1566                         TAILQ_INSERT_HEAD(&ifc_head, ifcp, ifc_next);
1567                         trace(1, "newif %s <%s>\n", ifcp->ifc_name,
1568                                 ifflags(ifcp->ifc_flags));
1569                         if (!strcmp(ifcp->ifc_name, LOOPBACK_IF))
1570                                 loopifcp = ifcp;
1571                 } else {
1572                         /* update flag, this may be up again */
1573                         if (ifcp->ifc_flags != ifa->ifa_flags) {
1574                                 trace(1, "%s: <%s> -> ", ifcp->ifc_name,
1575                                         ifflags(ifcp->ifc_flags));
1576                                 trace(1, "<%s>\n", ifflags(ifa->ifa_flags));
1577                                 ifcp->ifc_cflags |= IFC_CHANGED;
1578                         }
1579                         ifcp->ifc_flags = ifa->ifa_flags;
1580                 }
1581                 if (ifconfig1(ifa->ifa_name, ifa->ifa_addr, ifcp, s) < 0) {
1582                         /* maybe temporary failure */
1583                         continue;
1584                 }
1585                 if ((ifcp->ifc_flags & (IFF_LOOPBACK | IFF_UP)) == IFF_UP
1586                  && 0 < ifcp->ifc_index && !ifcp->ifc_joined) {
1587                         mreq.ipv6mr_multiaddr = ifcp->ifc_ripsin.sin6_addr;
1588                         mreq.ipv6mr_interface = ifcp->ifc_index;
1589                         if (setsockopt(ripsock, IPPROTO_IPV6, IPV6_JOIN_GROUP,
1590                             &mreq, sizeof(mreq)) < 0) {
1591                                 fatal("IPV6_JOIN_GROUP");
1592                                 /*NOTREACHED*/
1593                         }
1594                         trace(1, "join %s %s\n", ifcp->ifc_name, RIP6_DEST);
1595                         ifcp->ifc_joined++;
1596                 }
1597         }
1598         close(s);
1599         freeifaddrs(ifap);
1600 }
1601
1602 int
1603 ifconfig1(const char *name,
1604         const struct sockaddr *sa,
1605         struct ifc *ifcp,
1606         int s)
1607 {
1608         struct  in6_ifreq ifr;
1609         const struct sockaddr_in6 *sin6;
1610         struct  ifac *ifac;
1611         int     plen;
1612         char    buf[BUFSIZ];
1613
1614         sin6 = (const struct sockaddr_in6 *)sa;
1615         if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr) && !lflag)
1616                 return (-1);
1617         ifr.ifr_addr = *sin6;
1618         strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
1619         if (ioctl(s, SIOCGIFNETMASK_IN6, (char *)&ifr) < 0) {
1620                 syslog(LOG_INFO, "ioctl: SIOCGIFNETMASK_IN6");
1621                 return (-1);
1622         }
1623         plen = sin6mask2len(&ifr.ifr_addr);
1624         if ((ifac = ifa_match(ifcp, &sin6->sin6_addr, plen)) != NULL) {
1625                 /* same interface found */
1626                 /* need check if something changed */
1627                 /* XXX not yet implemented */
1628                 return (-1);
1629         }
1630         /*
1631          * New address is found
1632          */
1633         if ((ifac = MALLOC(struct ifac)) == NULL) {
1634                 fatal("malloc: struct ifac");
1635                 /*NOTREACHED*/
1636         }
1637         memset(ifac, 0, sizeof(*ifac));
1638
1639         ifac->ifac_ifc = ifcp;
1640         ifac->ifac_addr = sin6->sin6_addr;
1641         ifac->ifac_plen = plen;
1642         ifac->ifac_scope_id = sin6->sin6_scope_id;
1643         if (ifcp->ifc_flags & IFF_POINTOPOINT) {
1644                 ifr.ifr_addr = *sin6;
1645                 if (ioctl(s, SIOCGIFDSTADDR_IN6, (char *)&ifr) < 0) {
1646                         fatal("ioctl: SIOCGIFDSTADDR_IN6");
1647                         /*NOTREACHED*/
1648                 }
1649                 ifac->ifac_raddr = ifr.ifr_dstaddr.sin6_addr;
1650                 inet_ntop(AF_INET6, (void *)&ifac->ifac_raddr, buf,
1651                     sizeof(buf));
1652                 trace(1, "found address %s/%d -- %s\n",
1653                         inet6_n2p(&ifac->ifac_addr), ifac->ifac_plen, buf);
1654         } else {
1655                 trace(1, "found address %s/%d\n",
1656                         inet6_n2p(&ifac->ifac_addr), ifac->ifac_plen);
1657         }
1658         if (ifcp->ifc_index < 0 && IN6_IS_ADDR_LINKLOCAL(&ifac->ifac_addr)) {
1659                 ifcp->ifc_mylladdr = ifac->ifac_addr;
1660                 ifcp->ifc_index = IN6_LINKLOCAL_IFINDEX(ifac->ifac_addr);
1661                 memcpy(&ifcp->ifc_ripsin, &ripsin, ripsin.ss_len);
1662                 SET_IN6_LINKLOCAL_IFINDEX(ifcp->ifc_ripsin.sin6_addr,
1663                         ifcp->ifc_index);
1664                 setindex2ifc(ifcp->ifc_index, ifcp);
1665                 ifcp->ifc_mtu = getifmtu(ifcp->ifc_index);
1666                 if (ifcp->ifc_mtu > RIP6_MAXMTU)
1667                         ifcp->ifc_mtu = RIP6_MAXMTU;
1668                 if (ioctl(s, SIOCGIFMETRIC, (char *)&ifr) < 0) {
1669                         fatal("ioctl: SIOCGIFMETRIC");
1670                         /*NOTREACHED*/
1671                 }
1672                 ifcp->ifc_metric = ifr.ifr_metric;
1673                 trace(1, "\tindex: %d, mtu: %d, metric: %d\n",
1674                         ifcp->ifc_index, ifcp->ifc_mtu, ifcp->ifc_metric);
1675         } else
1676                 ifcp->ifc_cflags |= IFC_CHANGED;
1677
1678         TAILQ_INSERT_HEAD(&ifcp->ifc_ifac_head, ifac, ifac_next);
1679
1680         return 0;
1681 }
1682
1683 void
1684 ifremove(int ifindex)
1685 {
1686         struct ifc *ifcp;
1687         struct riprt *rrt;
1688
1689         TAILQ_FOREACH(ifcp, &ifc_head, ifc_next) {
1690                 if (ifcp->ifc_index == ifindex)
1691                         break;
1692         }
1693         if (ifcp == NULL)
1694                 return; 
1695
1696         tracet(1, "ifremove: %s is departed.\n", ifcp->ifc_name);
1697         TAILQ_REMOVE(&ifc_head, ifcp, ifc_next);
1698
1699         TAILQ_FOREACH(rrt, &riprt_head, rrt_next) {
1700                 if (rrt->rrt_index == ifcp->ifc_index &&
1701                     rrt->rrt_rflags & RRTF_AGGREGATE)
1702                         delroute(&rrt->rrt_info, &rrt->rrt_gw);
1703         }
1704         free(ifcp);
1705 }
1706
1707 /*
1708  * Receive and process routing messages.
1709  * Update interface information as necesssary.
1710  */
1711 void
1712 rtrecv(void)
1713 {
1714         char buf[BUFSIZ];
1715         char *p, *q = NULL;
1716         struct rt_msghdr *rtm;
1717         struct ifa_msghdr *ifam;
1718         struct if_msghdr *ifm;
1719         struct if_announcemsghdr *ifan;
1720         int len;
1721         struct ifc *ifcp, *ic;
1722         int iface = 0, rtable = 0;
1723         struct sockaddr_in6 *rta[RTAX_MAX];
1724         struct sockaddr_in6 mask;
1725         int i, addrs = 0;
1726         struct riprt *rrt;
1727
1728         if ((len = read(rtsock, buf, sizeof(buf))) < 0) {
1729                 perror("read from rtsock");
1730                 exit(1);
1731         }
1732         if (len == 0)
1733                 return;
1734 #if 0
1735         if (len < sizeof(*rtm)) {
1736                 trace(1, "short read from rtsock: %d (should be > %lu)\n",
1737                         len, (u_long)sizeof(*rtm));
1738                 return;
1739         }
1740 #endif
1741         if (dflag >= 2) {
1742                 fprintf(stderr, "rtmsg:\n");
1743                 for (i = 0; i < len; i++) {
1744                         fprintf(stderr, "%02x ", buf[i] & 0xff);
1745                         if (i % 16 == 15) fprintf(stderr, "\n");
1746                 }
1747                 fprintf(stderr, "\n");
1748         }
1749
1750         for (p = buf; p - buf < len; p += ((struct rt_msghdr *)p)->rtm_msglen) {
1751                 if (((struct rt_msghdr *)p)->rtm_version != RTM_VERSION)
1752                         continue;
1753
1754                 /* safety against bogus message */
1755                 if (((struct rt_msghdr *)p)->rtm_msglen <= 0) {
1756                         trace(1, "bogus rtmsg: length=%d\n",
1757                                 ((struct rt_msghdr *)p)->rtm_msglen);
1758                         break;
1759                 }
1760                 rtm = NULL;
1761                 ifam = NULL;
1762                 ifm = NULL;
1763                 switch (((struct rt_msghdr *)p)->rtm_type) {
1764                 case RTM_NEWADDR:
1765                 case RTM_DELADDR:
1766                         ifam = (struct ifa_msghdr *)p;
1767                         addrs = ifam->ifam_addrs;
1768                         q = (char *)(ifam + 1);
1769                         break;
1770                 case RTM_IFINFO:
1771                         ifm = (struct if_msghdr *)p;
1772                         addrs = ifm->ifm_addrs;
1773                         q = (char *)(ifm + 1);
1774                         break;
1775                 case RTM_IFANNOUNCE:
1776                         ifan = (struct if_announcemsghdr *)p;
1777                         switch (ifan->ifan_what) {
1778                         case IFAN_ARRIVAL:
1779                                 iface++;
1780                                 break;
1781                         case IFAN_DEPARTURE:
1782                                 ifremove(ifan->ifan_index);
1783                                 iface++;
1784                                 break;
1785                         }
1786                         break;
1787                 default:
1788                         rtm = (struct rt_msghdr *)p;
1789                         addrs = rtm->rtm_addrs;
1790                         q = (char *)(rtm + 1);
1791                         if (rtm->rtm_version != RTM_VERSION) {
1792                                 trace(1, "unexpected rtmsg version %d "
1793                                         "(should be %d)\n",
1794                                         rtm->rtm_version, RTM_VERSION);
1795                                 continue;
1796                         }
1797                         if (rtm->rtm_pid == pid) {
1798 #if 0
1799                                 trace(1, "rtmsg looped back to me, ignored\n");
1800 #endif
1801                                 continue;
1802                         }
1803                         break;
1804                 }
1805                 memset(&rta, 0, sizeof(rta));
1806                 for (i = 0; i < RTAX_MAX; i++) {
1807                         if (addrs & (1 << i)) {
1808                                 rta[i] = (struct sockaddr_in6 *)q;
1809                                 q += ROUNDUP(rta[i]->sin6_len);
1810                         }
1811                 }
1812
1813                 trace(1, "rtsock: %s (addrs=%x)\n",
1814                         rttypes((struct rt_msghdr *)p), addrs);
1815                 if (dflag >= 2) {
1816                         for (i = 0;
1817                              i < ((struct rt_msghdr *)p)->rtm_msglen;
1818                              i++) {
1819                                 fprintf(stderr, "%02x ", p[i] & 0xff);
1820                                 if (i % 16 == 15) fprintf(stderr, "\n");
1821                         }
1822                         fprintf(stderr, "\n");
1823                 }
1824
1825                 /*
1826                  * Easy ones first.
1827                  *
1828                  * We may be able to optimize by using ifm->ifm_index or
1829                  * ifam->ifam_index.  For simplicity we don't do that here.
1830                  */
1831                 switch (((struct rt_msghdr *)p)->rtm_type) {
1832                 case RTM_NEWADDR:
1833                 case RTM_IFINFO:
1834                         iface++;
1835                         continue;
1836                 case RTM_ADD:
1837                         rtable++;
1838                         continue;
1839                 case RTM_LOSING:
1840                 case RTM_MISS:
1841                 case RTM_GET:
1842                 case RTM_LOCK:
1843                         /* nothing to be done here */
1844                         trace(1, "\tnothing to be done, ignored\n");
1845                         continue;
1846                 }
1847
1848 #if 0
1849                 if (rta[RTAX_DST] == NULL) {
1850                         trace(1, "\tno destination, ignored\n");
1851                         continue;       
1852                 }
1853                 if (rta[RTAX_DST]->sin6_family != AF_INET6) {
1854                         trace(1, "\taf mismatch, ignored\n");
1855                         continue;
1856                 }
1857                 if (IN6_IS_ADDR_LINKLOCAL(&rta[RTAX_DST]->sin6_addr)) {
1858                         trace(1, "\tlinklocal destination, ignored\n");
1859                         continue;
1860                 }
1861                 if (IN6_ARE_ADDR_EQUAL(&rta[RTAX_DST]->sin6_addr, &in6addr_loopback)) {
1862                         trace(1, "\tloopback destination, ignored\n");
1863                         continue;               /* Loopback */
1864                 }
1865                 if (IN6_IS_ADDR_MULTICAST(&rta[RTAX_DST]->sin6_addr)) {
1866                         trace(1, "\tmulticast destination, ignored\n");
1867                         continue;
1868                 }
1869 #endif
1870
1871                 /* hard ones */
1872                 switch (((struct rt_msghdr *)p)->rtm_type) {
1873                 case RTM_NEWADDR:
1874                 case RTM_IFINFO:
1875                 case RTM_ADD:
1876                 case RTM_LOSING:
1877                 case RTM_MISS:
1878                 case RTM_GET:
1879                 case RTM_LOCK:
1880                         /* should already be handled */
1881                         fatal("rtrecv: never reach here");
1882                         /*NOTREACHED*/
1883                 case RTM_DELETE:
1884                         if (!rta[RTAX_DST] || !rta[RTAX_GATEWAY]) {
1885                                 trace(1, "\tsome of dst/gw/netamsk are "
1886                                     "unavailable, ignored\n");
1887                                 break;
1888                         }
1889                         if ((rtm->rtm_flags & RTF_HOST) != 0) {
1890                                 mask.sin6_len = sizeof(mask);
1891                                 memset(&mask.sin6_addr, 0xff,
1892                                     sizeof(mask.sin6_addr));
1893                                 rta[RTAX_NETMASK] = &mask;
1894                         } else if (!rta[RTAX_NETMASK]) {
1895                                 trace(1, "\tsome of dst/gw/netamsk are "
1896                                     "unavailable, ignored\n");
1897                                 break;
1898                         }
1899                         if (rt_del(rta[RTAX_DST], rta[RTAX_GATEWAY],
1900                             rta[RTAX_NETMASK]) == 0) {
1901                                 rtable++;       /*just to be sure*/
1902                         }
1903                         break;
1904                 case RTM_CHANGE:
1905                 case RTM_REDIRECT:
1906                         trace(1, "\tnot supported yet, ignored\n");
1907                         break;
1908                 case RTM_DELADDR:
1909                         if (!rta[RTAX_NETMASK] || !rta[RTAX_IFA]) {
1910                                 trace(1, "\tno netmask or ifa given, ignored\n");
1911                                 break;
1912                         }
1913                         if (ifam->ifam_index < nindex2ifc)
1914                                 ifcp = index2ifc[ifam->ifam_index];
1915                         else
1916                                 ifcp = NULL;
1917                         if (!ifcp) {
1918                                 trace(1, "\tinvalid ifam_index %d, ignored\n",
1919                                         ifam->ifam_index);
1920                                 break;
1921                         }
1922                         if (!rt_deladdr(ifcp, rta[RTAX_IFA], rta[RTAX_NETMASK]))
1923                                 iface++;
1924                         break;
1925                 case RTM_OLDADD:
1926                 case RTM_OLDDEL:
1927                         trace(1, "\tnot supported yet, ignored\n");
1928                         break;
1929                 }
1930
1931         }
1932
1933         if (iface) {
1934                 trace(1, "rtsock: reconfigure interfaces, refresh interface routes\n");
1935                 ifconfig();
1936                 TAILQ_FOREACH(ifcp, &ifc_head, ifc_next) {
1937                         if (ifcp->ifc_cflags & IFC_CHANGED) {
1938                                 if (ifrt(ifcp, 1)) {
1939                                         TAILQ_FOREACH(ic, &ifc_head, ifc_next) {
1940                                                 if (ifcp->ifc_index == ic->ifc_index)
1941                                                         continue;
1942                                                 if (ic->ifc_flags & IFF_UP)
1943                                                         ripsend(ic, &ic->ifc_ripsin,
1944                                                         RRTF_CHANGED);
1945                                         }
1946                                         /* Reset the flag */
1947                                         TAILQ_FOREACH(rrt, &riprt_head, rrt_next) {
1948                                                 rrt->rrt_rflags &= ~RRTF_CHANGED;
1949                                         }
1950                                 }
1951                                 ifcp->ifc_cflags &= ~IFC_CHANGED;
1952                         }
1953                 }
1954         }
1955         if (rtable) {
1956                 trace(1, "rtsock: read routing table again\n");
1957                 krtread(1);
1958         }
1959 }
1960
1961 /*
1962  * remove specified route from the internal routing table.
1963  */
1964 int
1965 rt_del(const struct sockaddr_in6 *sdst,
1966         const struct sockaddr_in6 *sgw,
1967         const struct sockaddr_in6 *smask)
1968 {
1969         const struct in6_addr *dst = NULL;
1970         const struct in6_addr *gw = NULL;
1971         int prefix;
1972         struct netinfo6 ni6;
1973         struct riprt *rrt = NULL;
1974         time_t t_lifetime;
1975
1976         if (sdst->sin6_family != AF_INET6) {
1977                 trace(1, "\tother AF, ignored\n");
1978                 return -1;
1979         }
1980         if (IN6_IS_ADDR_LINKLOCAL(&sdst->sin6_addr)
1981          || IN6_ARE_ADDR_EQUAL(&sdst->sin6_addr, &in6addr_loopback)
1982          || IN6_IS_ADDR_MULTICAST(&sdst->sin6_addr)) {
1983                 trace(1, "\taddress %s not interesting, ignored\n",
1984                         inet6_n2p(&sdst->sin6_addr));
1985                 return -1;
1986         }
1987         dst = &sdst->sin6_addr;
1988         if (sgw->sin6_family == AF_INET6) {
1989                 /* easy case */
1990                 gw = &sgw->sin6_addr;
1991                 prefix = sin6mask2len(smask);
1992         } else if (sgw->sin6_family == AF_LINK) {
1993                 /*
1994                  * Interface route... a hard case.  We need to get the prefix
1995                  * length from the kernel, but we now are parsing rtmsg.
1996                  * We'll purge matching routes from my list, then get the
1997                  * fresh list.
1998                  */
1999                 struct riprt *longest;
2000                 trace(1, "\t%s is an interface route, guessing prefixlen\n",
2001                         inet6_n2p(dst));
2002                 longest = NULL;
2003                 TAILQ_FOREACH(rrt, &riprt_head, rrt_next) {
2004                         if (IN6_ARE_ADDR_EQUAL(&rrt->rrt_info.rip6_dest,
2005                                         &sdst->sin6_addr)
2006                          && IN6_IS_ADDR_LOOPBACK(&rrt->rrt_gw)) {
2007                                 if (!longest
2008                                  || longest->rrt_info.rip6_plen <
2009                                                  rrt->rrt_info.rip6_plen) {
2010                                         longest = rrt;
2011                                 }
2012                         }
2013                 }
2014                 rrt = longest;
2015                 if (!rrt) {
2016                         trace(1, "\tno matching interface route found\n");
2017                         return -1;
2018                 }
2019                 gw = &in6addr_loopback;
2020                 prefix = rrt->rrt_info.rip6_plen;
2021         } else {
2022                 trace(1, "\tunsupported af: (gw=%d)\n", sgw->sin6_family);
2023                 return -1;
2024         }
2025
2026         trace(1, "\tdeleting %s/%d ", inet6_n2p(dst), prefix);
2027         trace(1, "gw %s\n", inet6_n2p(gw));
2028         t_lifetime = time(NULL) - RIP_LIFETIME;
2029         /* age route for interface address */
2030         memset(&ni6, 0, sizeof(ni6));
2031         ni6.rip6_dest = *dst;
2032         ni6.rip6_plen = prefix;
2033         applyplen(&ni6.rip6_dest, ni6.rip6_plen);       /*to be sure*/
2034         trace(1, "\tfind route %s/%d\n", inet6_n2p(&ni6.rip6_dest),
2035                 ni6.rip6_plen);
2036         if (!rrt && (rrt = rtsearch(&ni6)) == NULL) {
2037                 trace(1, "\tno route found\n");
2038                 return -1;
2039         }
2040 #if 0
2041         if ((rrt->rrt_flags & RTF_STATIC) == 0) {
2042                 trace(1, "\tyou can delete static routes only\n");
2043         } else
2044 #endif
2045         if (!IN6_ARE_ADDR_EQUAL(&rrt->rrt_gw, gw)) {
2046                 trace(1, "\tgw mismatch: %s <-> ",
2047                         inet6_n2p(&rrt->rrt_gw));
2048                 trace(1, "%s\n", inet6_n2p(gw));
2049         } else {
2050                 trace(1, "\troute found, age it\n");
2051                 if (rrt->rrt_t == 0 || rrt->rrt_t > t_lifetime) {
2052                         rrt->rrt_t = t_lifetime;
2053                         rrt->rrt_info.rip6_metric = HOPCNT_INFINITY6;
2054                 }
2055         }
2056         return 0;
2057 }
2058
2059 /*
2060  * remove specified address from internal interface/routing table.
2061  */
2062 int
2063 rt_deladdr(struct ifc *ifcp,
2064         const struct sockaddr_in6 *sifa,
2065         const struct sockaddr_in6 *smask)
2066 {
2067         const struct in6_addr *addr = NULL;
2068         int prefix;
2069         struct ifac *ifac = NULL;
2070         struct netinfo6 ni6;
2071         struct riprt *rrt = NULL;
2072         time_t t_lifetime;
2073         int updated = 0;
2074
2075         if (sifa->sin6_family != AF_INET6) {
2076                 trace(1, "\tother AF, ignored\n");
2077                 return -1;
2078         }
2079         addr = &sifa->sin6_addr;
2080         prefix = sin6mask2len(smask);
2081
2082         trace(1, "\tdeleting %s/%d from %s\n",
2083                 inet6_n2p(addr), prefix, ifcp->ifc_name);
2084         ifac = ifa_match(ifcp, addr, prefix);
2085         if (!ifac) {
2086                 trace(1, "\tno matching ifa found for %s/%d on %s\n",
2087                         inet6_n2p(addr), prefix, ifcp->ifc_name);
2088                 return -1;
2089         }
2090         if (ifac->ifac_ifc != ifcp) {
2091                 trace(1, "\taddress table corrupt: back pointer does not match "
2092                         "(%s != %s)\n",
2093                         ifcp->ifc_name, ifac->ifac_ifc->ifc_name);
2094                 return -1;
2095         }
2096         TAILQ_REMOVE(&ifcp->ifc_ifac_head, ifac, ifac_next);
2097         t_lifetime = time(NULL) - RIP_LIFETIME;
2098         /* age route for interface address */
2099         memset(&ni6, 0, sizeof(ni6));
2100         ni6.rip6_dest = ifac->ifac_addr;
2101         ni6.rip6_plen = ifac->ifac_plen;
2102         applyplen(&ni6.rip6_dest, ni6.rip6_plen);
2103         trace(1, "\tfind interface route %s/%d on %d\n",
2104                 inet6_n2p(&ni6.rip6_dest), ni6.rip6_plen, ifcp->ifc_index);
2105         if ((rrt = rtsearch(&ni6)) != NULL) {
2106                 struct in6_addr none;
2107                 memset(&none, 0, sizeof(none));
2108                 if (rrt->rrt_index == ifcp->ifc_index &&
2109                     (IN6_ARE_ADDR_EQUAL(&rrt->rrt_gw, &none) ||
2110                      IN6_IS_ADDR_LOOPBACK(&rrt->rrt_gw))) {
2111                         trace(1, "\troute found, age it\n");
2112                         if (rrt->rrt_t == 0 || rrt->rrt_t > t_lifetime) {
2113                                 rrt->rrt_t = t_lifetime;
2114                                 rrt->rrt_info.rip6_metric = HOPCNT_INFINITY6;
2115                         }
2116                         updated++;
2117                 } else {
2118                         trace(1, "\tnon-interface route found: %s/%d on %d\n",
2119                                 inet6_n2p(&rrt->rrt_info.rip6_dest),
2120                                 rrt->rrt_info.rip6_plen,
2121                                 rrt->rrt_index);
2122                 }
2123         } else
2124                 trace(1, "\tno interface route found\n");
2125         /* age route for p2p destination */
2126         if (ifcp->ifc_flags & IFF_POINTOPOINT) {
2127                 memset(&ni6, 0, sizeof(ni6));
2128                 ni6.rip6_dest = ifac->ifac_raddr;
2129                 ni6.rip6_plen = 128;
2130                 applyplen(&ni6.rip6_dest, ni6.rip6_plen);       /*to be sure*/
2131                 trace(1, "\tfind p2p route %s/%d on %d\n",
2132                         inet6_n2p(&ni6.rip6_dest), ni6.rip6_plen,
2133                         ifcp->ifc_index);
2134                 if ((rrt = rtsearch(&ni6)) != NULL) {
2135                         if (rrt->rrt_index == ifcp->ifc_index &&
2136                             IN6_ARE_ADDR_EQUAL(&rrt->rrt_gw,
2137                             &ifac->ifac_addr)) {
2138                                 trace(1, "\troute found, age it\n");
2139                                 if (rrt->rrt_t == 0 || rrt->rrt_t > t_lifetime) {
2140                                         rrt->rrt_t = t_lifetime;
2141                                         rrt->rrt_info.rip6_metric =
2142                                             HOPCNT_INFINITY6;
2143                                         updated++;
2144                                 }
2145                         } else {
2146                                 trace(1, "\tnon-p2p route found: %s/%d on %d\n",
2147                                         inet6_n2p(&rrt->rrt_info.rip6_dest),
2148                                         rrt->rrt_info.rip6_plen,
2149                                         rrt->rrt_index);
2150                         }
2151                 } else
2152                         trace(1, "\tno p2p route found\n");
2153         }
2154         free(ifac);
2155
2156         return ((updated) ? 0 : -1);
2157 }
2158
2159 /*
2160  * Get each interface address and put those interface routes to the route
2161  * list.
2162  */
2163 int
2164 ifrt(struct ifc *ifcp, int again)
2165 {
2166         struct ifac *ifac;
2167         struct riprt *rrt = NULL, *search_rrt, *loop_rrt;
2168         struct netinfo6 *np;
2169         time_t t_lifetime;
2170         int need_trigger = 0;
2171
2172 #if 0
2173         if (ifcp->ifc_flags & IFF_LOOPBACK)
2174                 return 0;                       /* ignore loopback */
2175 #endif
2176
2177         if (ifcp->ifc_flags & IFF_POINTOPOINT) {
2178                 ifrt_p2p(ifcp, again);
2179                 return 0;
2180         }
2181
2182         TAILQ_FOREACH(ifac, &ifcp->ifc_ifac_head, ifac_next) {
2183                 if (IN6_IS_ADDR_LINKLOCAL(&ifac->ifac_addr)) {
2184 #if 0
2185                         trace(1, "route: %s on %s: "
2186                             "skip linklocal interface address\n",
2187                             inet6_n2p(&ifac->ifac_addr), ifcp->ifc_name);
2188 #endif
2189                         continue;
2190                 }
2191                 if (IN6_IS_ADDR_UNSPECIFIED(&ifac->ifac_addr)) {
2192 #if 0
2193                         trace(1, "route: %s: skip unspec interface address\n",
2194                             ifcp->ifc_name);
2195 #endif
2196                         continue;
2197                 }
2198                 if (IN6_IS_ADDR_LOOPBACK(&ifac->ifac_addr)) {
2199 #if 0
2200                         trace(1, "route: %s: skip loopback address\n",
2201                             ifcp->ifc_name);
2202 #endif
2203                         continue;
2204                 }
2205                 if (ifcp->ifc_flags & IFF_UP) {
2206                         if ((rrt = MALLOC(struct riprt)) == NULL)
2207                                 fatal("malloc: struct riprt");
2208                         memset(rrt, 0, sizeof(*rrt));
2209                         rrt->rrt_same = NULL;
2210                         rrt->rrt_index = ifcp->ifc_index;
2211                         rrt->rrt_t = 0; /* don't age */
2212                         rrt->rrt_info.rip6_dest = ifac->ifac_addr;
2213                         rrt->rrt_info.rip6_tag = htons(routetag & 0xffff);
2214                         rrt->rrt_info.rip6_metric = 1 + ifcp->ifc_metric;
2215                         rrt->rrt_info.rip6_plen = ifac->ifac_plen;
2216                         rrt->rrt_flags = RTF_HOST;
2217                         rrt->rrt_rflags |= RRTF_CHANGED;
2218                         applyplen(&rrt->rrt_info.rip6_dest, ifac->ifac_plen);
2219                         memset(&rrt->rrt_gw, 0, sizeof(struct in6_addr));
2220                         rrt->rrt_gw = ifac->ifac_addr;
2221                         np = &rrt->rrt_info;
2222                         search_rrt = rtsearch(np);
2223                         if (search_rrt != NULL) {
2224                                 if (search_rrt->rrt_info.rip6_metric <=
2225                                     rrt->rrt_info.rip6_metric) {
2226                                         /* Already have better route */
2227                                         if (!again) {
2228                                                 trace(1, "route: %s/%d: "
2229                                                     "already registered (%s)\n",
2230                                                     inet6_n2p(&np->rip6_dest), np->rip6_plen,
2231                                                     ifcp->ifc_name);
2232                                         }
2233                                         goto next;
2234                                 }
2235
2236                                 TAILQ_REMOVE(&riprt_head, rrt, rrt_next);
2237                                 delroute(&rrt->rrt_info, &rrt->rrt_gw);
2238                         }
2239                         /* Attach the route to the list */
2240                         trace(1, "route: %s/%d: register route (%s)\n",
2241                             inet6_n2p(&np->rip6_dest), np->rip6_plen,
2242                             ifcp->ifc_name);
2243                         TAILQ_INSERT_HEAD(&riprt_head, rrt, rrt_next);
2244                         addroute(rrt, &rrt->rrt_gw, ifcp);
2245                         rrt = NULL;
2246                         sendrequest(ifcp);
2247                         ripsend(ifcp, &ifcp->ifc_ripsin, 0);
2248                         need_trigger = 1;
2249                 } else {
2250                         TAILQ_FOREACH(loop_rrt, &riprt_head, rrt_next) {
2251                                 if (loop_rrt->rrt_index == ifcp->ifc_index) {
2252                                         t_lifetime = time(NULL) - RIP_LIFETIME;
2253                                         if (loop_rrt->rrt_t == 0 || loop_rrt->rrt_t > t_lifetime) {
2254                                                 loop_rrt->rrt_t = t_lifetime;
2255                                                 loop_rrt->rrt_info.rip6_metric = HOPCNT_INFINITY6;
2256                                                 loop_rrt->rrt_rflags |= RRTF_CHANGED;
2257                                                 need_trigger = 1;
2258                                         }
2259                                 }
2260                         }
2261                 }
2262         next:
2263                 if (rrt)
2264                         free(rrt);
2265         }
2266         return need_trigger;
2267 }
2268
2269 /*
2270  * there are couple of p2p interface routing models.  "behavior" lets
2271  * you pick one.  it looks that gated behavior fits best with BSDs,
2272  * since BSD kernels do not look at prefix length on p2p interfaces.
2273  */
2274 void
2275 ifrt_p2p(struct ifc *ifcp, int again)
2276 {
2277         struct ifac *ifac;
2278         struct riprt *rrt, *orrt;
2279         struct netinfo6 *np;
2280         struct in6_addr addr, dest;
2281         int advert, ignore, i;
2282 #define P2PADVERT_NETWORK       1
2283 #define P2PADVERT_ADDR          2
2284 #define P2PADVERT_DEST          4
2285 #define P2PADVERT_MAX           4
2286         const enum { CISCO, GATED, ROUTE6D } behavior = GATED;
2287         const char *category = "";
2288         const char *noadv;
2289
2290         TAILQ_FOREACH(ifac, &ifcp->ifc_ifac_head, ifac_next) {
2291                 addr = ifac->ifac_addr;
2292                 dest = ifac->ifac_raddr;
2293                 applyplen(&addr, ifac->ifac_plen);
2294                 applyplen(&dest, ifac->ifac_plen);
2295                 advert = ignore = 0;
2296                 switch (behavior) {
2297                 case CISCO:
2298                         /*
2299                          * honor addr/plen, just like normal shared medium
2300                          * interface.  this may cause trouble if you reuse
2301                          * addr/plen on other interfaces.
2302                          *
2303                          * advertise addr/plen.
2304                          */
2305                         advert |= P2PADVERT_NETWORK;
2306                         break;
2307                 case GATED:
2308                         /*
2309                          * prefixlen on p2p interface is meaningless.
2310                          * advertise addr/128 and dest/128.
2311                          *
2312                          * do not install network route to route6d routing
2313                          * table (if we do, it would prevent route installation
2314                          * for other p2p interface that shares addr/plen).
2315                          *
2316                          * XXX what should we do if dest is ::?  it will not
2317                          * get announced anyways (see following filter),
2318                          * but we need to think.
2319                          */
2320                         advert |= P2PADVERT_ADDR;
2321                         advert |= P2PADVERT_DEST;
2322                         ignore |= P2PADVERT_NETWORK;
2323                         break;
2324                 case ROUTE6D:
2325                         /*
2326                          * just for testing.  actually the code is redundant
2327                          * given the current p2p interface address assignment
2328                          * rule for kame kernel.
2329                          *
2330                          * intent:
2331                          *      A/n -> announce A/n
2332                          *      A B/n, A and B share prefix -> A/n (= B/n)
2333                          *      A B/n, do not share prefix -> A/128 and B/128
2334                          * actually, A/64 and A B/128 are the only cases
2335                          * permitted by the kernel:
2336                          *      A/64 -> A/64
2337                          *      A B/128 -> A/128 and B/128
2338                          */
2339                         if (!IN6_IS_ADDR_UNSPECIFIED(&ifac->ifac_raddr)) {
2340                                 if (IN6_ARE_ADDR_EQUAL(&addr, &dest))
2341                                         advert |= P2PADVERT_NETWORK;
2342                                 else {
2343                                         advert |= P2PADVERT_ADDR;
2344                                         advert |= P2PADVERT_DEST;
2345                                         ignore |= P2PADVERT_NETWORK;
2346                                 }
2347                         } else
2348                                 advert |= P2PADVERT_NETWORK;
2349                         break;
2350                 }
2351
2352                 for (i = 1; i <= P2PADVERT_MAX; i *= 2) {
2353                         if ((ignore & i) != 0)
2354                                 continue;
2355                         if ((rrt = MALLOC(struct riprt)) == NULL) {
2356                                 fatal("malloc: struct riprt");
2357                                 /*NOTREACHED*/
2358                         }
2359                         memset(rrt, 0, sizeof(*rrt));
2360                         rrt->rrt_same = NULL;
2361                         rrt->rrt_index = ifcp->ifc_index;
2362                         rrt->rrt_t = 0; /* don't age */
2363                         switch (i) {
2364                         case P2PADVERT_NETWORK:
2365                                 rrt->rrt_info.rip6_dest = ifac->ifac_addr;
2366                                 rrt->rrt_info.rip6_plen = ifac->ifac_plen;
2367                                 applyplen(&rrt->rrt_info.rip6_dest,
2368                                     ifac->ifac_plen);
2369                                 category = "network";
2370                                 break;
2371                         case P2PADVERT_ADDR:
2372                                 rrt->rrt_info.rip6_dest = ifac->ifac_addr;
2373                                 rrt->rrt_info.rip6_plen = 128;
2374                                 rrt->rrt_gw = in6addr_loopback;
2375                                 category = "addr";
2376                                 break;
2377                         case P2PADVERT_DEST:
2378                                 rrt->rrt_info.rip6_dest = ifac->ifac_raddr;
2379                                 rrt->rrt_info.rip6_plen = 128;
2380                                 rrt->rrt_gw = ifac->ifac_addr;
2381                                 category = "dest";
2382                                 break;
2383                         }
2384                         if (IN6_IS_ADDR_UNSPECIFIED(&rrt->rrt_info.rip6_dest) ||
2385                             IN6_IS_ADDR_LINKLOCAL(&rrt->rrt_info.rip6_dest)) {
2386 #if 0
2387                                 trace(1, "route: %s: skip unspec/linklocal "
2388                                     "(%s on %s)\n", category, ifcp->ifc_name);
2389 #endif
2390                                 free(rrt);
2391                                 continue;
2392                         }
2393                         if ((advert & i) == 0) {
2394                                 rrt->rrt_rflags |= RRTF_NOADVERTISE;
2395                                 noadv = ", NO-ADV";
2396                         } else
2397                                 noadv = "";
2398                         rrt->rrt_info.rip6_tag = htons(routetag & 0xffff);
2399                         rrt->rrt_info.rip6_metric = 1 + ifcp->ifc_metric;
2400                         np = &rrt->rrt_info;
2401                         orrt = rtsearch(np);
2402                         if (!orrt) {
2403                                 /* Attach the route to the list */
2404                                 trace(1, "route: %s/%d: register route "
2405                                     "(%s on %s%s)\n",
2406                                     inet6_n2p(&np->rip6_dest), np->rip6_plen,
2407                                     category, ifcp->ifc_name, noadv);
2408                                 TAILQ_INSERT_HEAD(&riprt_head, rrt, rrt_next);
2409                         } else if (rrt->rrt_index != orrt->rrt_index ||
2410                             rrt->rrt_info.rip6_metric != orrt->rrt_info.rip6_metric) {
2411                                 /* replace route */
2412                                 TAILQ_INSERT_BEFORE(orrt, rrt, rrt_next);
2413                                 TAILQ_REMOVE(&riprt_head, orrt, rrt_next);
2414                                 free(orrt);
2415
2416                                 trace(1, "route: %s/%d: update (%s on %s%s)\n",
2417                                     inet6_n2p(&np->rip6_dest), np->rip6_plen,
2418                                     category, ifcp->ifc_name, noadv);
2419                         } else {
2420                                 /* Already found */
2421                                 if (!again) {
2422                                         trace(1, "route: %s/%d: "
2423                                             "already registered (%s on %s%s)\n",
2424                                             inet6_n2p(&np->rip6_dest),
2425                                             np->rip6_plen, category,
2426                                             ifcp->ifc_name, noadv);
2427                                 }
2428                                 free(rrt);
2429                         }
2430                 }
2431         }
2432 #undef P2PADVERT_NETWORK
2433 #undef P2PADVERT_ADDR
2434 #undef P2PADVERT_DEST
2435 #undef P2PADVERT_MAX
2436 }
2437
2438 int
2439 getifmtu(int ifindex)
2440 {
2441         int     mib[6];
2442         char    *buf;
2443         size_t  msize;
2444         struct  if_msghdr *ifm;
2445         int     mtu;
2446
2447         mib[0] = CTL_NET;
2448         mib[1] = PF_ROUTE;
2449         mib[2] = 0;
2450         mib[3] = AF_INET6;
2451         mib[4] = NET_RT_IFLIST;
2452         mib[5] = ifindex;
2453         if (sysctl(mib, 6, NULL, &msize, NULL, 0) < 0) {
2454                 fatal("sysctl estimate NET_RT_IFLIST");
2455                 /*NOTREACHED*/
2456         }
2457         if ((buf = malloc(msize)) == NULL) {
2458                 fatal("malloc");
2459                 /*NOTREACHED*/
2460         }
2461         if (sysctl(mib, 6, buf, &msize, NULL, 0) < 0) {
2462                 fatal("sysctl NET_RT_IFLIST");
2463                 /*NOTREACHED*/
2464         }
2465         ifm = (struct if_msghdr *)buf;
2466         mtu = ifm->ifm_data.ifi_mtu;
2467         if (ifindex != ifm->ifm_index) {
2468                 fatal("ifindex does not match with ifm_index");
2469                 /*NOTREACHED*/
2470         }
2471         free(buf);
2472         return mtu;
2473 }
2474
2475 const char *
2476 rttypes(struct rt_msghdr *rtm)
2477 {
2478 #define RTTYPE(s, f) \
2479 do { \
2480         if (rtm->rtm_type == (f)) \
2481                 return (s); \
2482 } while (0)
2483         RTTYPE("ADD", RTM_ADD);
2484         RTTYPE("DELETE", RTM_DELETE);
2485         RTTYPE("CHANGE", RTM_CHANGE);
2486         RTTYPE("GET", RTM_GET);
2487         RTTYPE("LOSING", RTM_LOSING);
2488         RTTYPE("REDIRECT", RTM_REDIRECT);
2489         RTTYPE("MISS", RTM_MISS);
2490         RTTYPE("LOCK", RTM_LOCK);
2491         RTTYPE("OLDADD", RTM_OLDADD);
2492         RTTYPE("OLDDEL", RTM_OLDDEL);
2493         RTTYPE("NEWADDR", RTM_NEWADDR);
2494         RTTYPE("DELADDR", RTM_DELADDR);
2495         RTTYPE("IFINFO", RTM_IFINFO);
2496 #ifdef RTM_OLDADD
2497         RTTYPE("OLDADD", RTM_OLDADD);
2498 #endif
2499 #ifdef RTM_OLDDEL
2500         RTTYPE("OLDDEL", RTM_OLDDEL);
2501 #endif
2502 #ifdef RTM_OIFINFO
2503         RTTYPE("OIFINFO", RTM_OIFINFO);
2504 #endif
2505 #ifdef RTM_IFANNOUNCE
2506         RTTYPE("IFANNOUNCE", RTM_IFANNOUNCE);
2507 #endif
2508 #ifdef RTM_NEWMADDR
2509         RTTYPE("NEWMADDR", RTM_NEWMADDR);
2510 #endif
2511 #ifdef RTM_DELMADDR
2512         RTTYPE("DELMADDR", RTM_DELMADDR);
2513 #endif
2514 #undef RTTYPE
2515         return NULL;
2516 }
2517
2518 const char *
2519 rtflags(struct rt_msghdr *rtm)
2520 {
2521         static char buf[BUFSIZ];
2522
2523         /*
2524          * letter conflict should be okay.  painful when *BSD diverges...
2525          */
2526         strlcpy(buf, "", sizeof(buf));
2527 #define RTFLAG(s, f) \
2528 do { \
2529         if (rtm->rtm_flags & (f)) \
2530                 strlcat(buf, (s), sizeof(buf)); \
2531 } while (0)
2532         RTFLAG("U", RTF_UP);
2533         RTFLAG("G", RTF_GATEWAY);
2534         RTFLAG("H", RTF_HOST);
2535         RTFLAG("R", RTF_REJECT);
2536         RTFLAG("D", RTF_DYNAMIC);
2537         RTFLAG("M", RTF_MODIFIED);
2538         RTFLAG("d", RTF_DONE);
2539 #ifdef  RTF_MASK
2540         RTFLAG("m", RTF_MASK);
2541 #endif
2542 #ifdef RTF_CLONING
2543         RTFLAG("C", RTF_CLONING);
2544 #endif
2545 #ifdef RTF_CLONED
2546         RTFLAG("c", RTF_CLONED);
2547 #endif
2548 #ifdef RTF_PRCLONING
2549         RTFLAG("c", RTF_PRCLONING);
2550 #endif
2551 #ifdef RTF_WASCLONED
2552         RTFLAG("W", RTF_WASCLONED);
2553 #endif
2554         RTFLAG("X", RTF_XRESOLVE);
2555 #ifdef RTF_LLINFO
2556         RTFLAG("L", RTF_LLINFO);
2557 #endif
2558         RTFLAG("S", RTF_STATIC);
2559         RTFLAG("B", RTF_BLACKHOLE);
2560 #ifdef RTF_PROTO3
2561         RTFLAG("3", RTF_PROTO3);
2562 #endif
2563         RTFLAG("2", RTF_PROTO2);
2564         RTFLAG("1", RTF_PROTO1);
2565 #ifdef RTF_BROADCAST
2566         RTFLAG("b", RTF_BROADCAST);
2567 #endif
2568 #ifdef RTF_DEFAULT
2569         RTFLAG("d", RTF_DEFAULT);
2570 #endif
2571 #ifdef RTF_ISAROUTER
2572         RTFLAG("r", RTF_ISAROUTER);
2573 #endif
2574 #ifdef RTF_TUNNEL
2575         RTFLAG("T", RTF_TUNNEL);
2576 #endif
2577 #ifdef RTF_AUTH
2578         RTFLAG("A", RTF_AUTH);
2579 #endif
2580 #ifdef RTF_CRYPT
2581         RTFLAG("E", RTF_CRYPT);
2582 #endif
2583 #undef RTFLAG
2584         return buf;
2585 }
2586
2587 const char *
2588 ifflags(int flags)
2589 {
2590         static char buf[BUFSIZ];
2591
2592         strlcpy(buf, "", sizeof(buf));
2593 #define IFFLAG(s, f) \
2594 do { \
2595         if (flags & (f)) { \
2596                 if (buf[0]) \
2597                         strlcat(buf, ",", sizeof(buf)); \
2598                 strlcat(buf, (s), sizeof(buf)); \
2599         } \
2600 } while (0)
2601         IFFLAG("UP", IFF_UP);
2602         IFFLAG("BROADCAST", IFF_BROADCAST);
2603         IFFLAG("DEBUG", IFF_DEBUG);
2604         IFFLAG("LOOPBACK", IFF_LOOPBACK);
2605         IFFLAG("POINTOPOINT", IFF_POINTOPOINT);
2606 #ifdef IFF_NOTRAILERS
2607         IFFLAG("NOTRAILERS", IFF_NOTRAILERS);
2608 #endif
2609 #ifdef IFF_SMART
2610         IFFLAG("SMART", IFF_SMART);
2611 #endif
2612         IFFLAG("RUNNING", IFF_RUNNING);
2613         IFFLAG("NOARP", IFF_NOARP);
2614         IFFLAG("PROMISC", IFF_PROMISC);
2615         IFFLAG("ALLMULTI", IFF_ALLMULTI);
2616         IFFLAG("OACTIVE", IFF_OACTIVE);
2617         IFFLAG("SIMPLEX", IFF_SIMPLEX);
2618         IFFLAG("LINK0", IFF_LINK0);
2619         IFFLAG("LINK1", IFF_LINK1);
2620         IFFLAG("LINK2", IFF_LINK2);
2621         IFFLAG("MULTICAST", IFF_MULTICAST);
2622 #undef IFFLAG
2623         return buf;
2624 }
2625
2626 void
2627 krtread(int again)
2628 {
2629         int mib[6];
2630         size_t msize;
2631         char *buf, *p, *lim;
2632         struct rt_msghdr *rtm;
2633         int retry;
2634         const char *errmsg;
2635
2636         retry = 0;
2637         buf = NULL;
2638         mib[0] = CTL_NET;
2639         mib[1] = PF_ROUTE;
2640         mib[2] = 0;
2641         mib[3] = AF_INET6;      /* Address family */
2642         mib[4] = NET_RT_DUMP;   /* Dump the kernel routing table */
2643         mib[5] = 0;             /* No flags */
2644         do {
2645                 if (retry)
2646                         sleep(1);
2647                 retry++;
2648                 errmsg = NULL;
2649                 if (buf)
2650                         free(buf);
2651                 if (sysctl(mib, 6, NULL, &msize, NULL, 0) < 0) {
2652                         errmsg = "sysctl estimate";
2653                         continue;
2654                 }
2655                 if ((buf = malloc(msize)) == NULL) {
2656                         errmsg = "malloc";
2657                         continue;
2658                 }
2659                 if (sysctl(mib, 6, buf, &msize, NULL, 0) < 0) {
2660                         errmsg = "sysctl NET_RT_DUMP";
2661                         continue;
2662                 }
2663         } while (retry < RT_DUMP_MAXRETRY && errmsg != NULL);
2664         if (errmsg) {
2665                 fatal("%s (with %d retries, msize=%lu)", errmsg, retry,
2666                     (u_long)msize);
2667                 /*NOTREACHED*/
2668         } else if (1 < retry)
2669                 syslog(LOG_INFO, "NET_RT_DUMP %d retires", retry);
2670
2671         lim = buf + msize;
2672         for (p = buf; p < lim; p += rtm->rtm_msglen) {
2673                 rtm = (struct rt_msghdr *)p;
2674                 rt_entry(rtm, again);
2675         }
2676         free(buf);
2677 }
2678
2679 void
2680 rt_entry(struct rt_msghdr *rtm, int again)
2681 {
2682         struct  sockaddr_in6 *sin6_dst, *sin6_gw, *sin6_mask;
2683         struct  sockaddr_in6 *sin6_genmask, *sin6_ifp;
2684         char    *rtmp, *ifname = NULL;
2685         struct  riprt *rrt, *orrt;
2686         struct  netinfo6 *np;
2687         int ifindex;
2688
2689         sin6_dst = sin6_gw = sin6_mask = sin6_genmask = sin6_ifp = 0;
2690         if ((rtm->rtm_flags & RTF_UP) == 0 || rtm->rtm_flags &
2691                 (RTF_XRESOLVE|RTF_BLACKHOLE)) {
2692                 return;         /* not interested in the link route */
2693         }
2694         /* do not look at cloned routes */
2695 #ifdef RTF_WASCLONED
2696         if (rtm->rtm_flags & RTF_WASCLONED)
2697                 return;
2698 #endif
2699 #ifdef RTF_CLONED
2700         if (rtm->rtm_flags & RTF_CLONED)
2701                 return;
2702 #endif
2703         /* XXX: Ignore connected routes. */
2704         if (!(rtm->rtm_flags & (RTF_GATEWAY|RTF_HOST|RTF_STATIC)))
2705                 return;
2706         /*
2707          * do not look at dynamic routes.
2708          * netbsd/openbsd cloned routes have UGHD.
2709          */
2710         if (rtm->rtm_flags & RTF_DYNAMIC)
2711                 return;
2712         rtmp = (char *)(rtm + 1);
2713         /* Destination */
2714         if ((rtm->rtm_addrs & RTA_DST) == 0)
2715                 return;         /* ignore routes without destination address */
2716         sin6_dst = (struct sockaddr_in6 *)rtmp;
2717         rtmp += ROUNDUP(sin6_dst->sin6_len);
2718         if (rtm->rtm_addrs & RTA_GATEWAY) {
2719                 sin6_gw = (struct sockaddr_in6 *)rtmp;
2720                 rtmp += ROUNDUP(sin6_gw->sin6_len);
2721         }
2722         if (rtm->rtm_addrs & RTA_NETMASK) {
2723                 sin6_mask = (struct sockaddr_in6 *)rtmp;
2724                 rtmp += ROUNDUP(sin6_mask->sin6_len);
2725         }
2726         if (rtm->rtm_addrs & RTA_GENMASK) {
2727                 sin6_genmask = (struct sockaddr_in6 *)rtmp;
2728                 rtmp += ROUNDUP(sin6_genmask->sin6_len);
2729         }
2730         if (rtm->rtm_addrs & RTA_IFP) {
2731                 sin6_ifp = (struct sockaddr_in6 *)rtmp;
2732                 rtmp += ROUNDUP(sin6_ifp->sin6_len);
2733         }
2734
2735         /* Destination */
2736         if (sin6_dst->sin6_family != AF_INET6)
2737                 return;
2738         if (IN6_IS_ADDR_LINKLOCAL(&sin6_dst->sin6_addr))
2739                 return;         /* Link-local */
2740         if (IN6_ARE_ADDR_EQUAL(&sin6_dst->sin6_addr, &in6addr_loopback))
2741                 return;         /* Loopback */
2742         if (IN6_IS_ADDR_MULTICAST(&sin6_dst->sin6_addr))
2743                 return;
2744
2745         if ((rrt = MALLOC(struct riprt)) == NULL) {
2746                 fatal("malloc: struct riprt");
2747                 /*NOTREACHED*/
2748         }
2749         memset(rrt, 0, sizeof(*rrt));
2750         np = &rrt->rrt_info;
2751         rrt->rrt_same = NULL;
2752         rrt->rrt_t = time(NULL);
2753         if (aflag == 0 && (rtm->rtm_flags & RTF_STATIC))
2754                 rrt->rrt_t = 0; /* Don't age static routes */
2755         if (rtm->rtm_flags & Pflag)
2756                 rrt->rrt_t = 0; /* Don't age PROTO[123] routes */
2757         if ((rtm->rtm_flags & (RTF_HOST|RTF_GATEWAY)) == RTF_HOST)
2758                 rrt->rrt_t = 0; /* Don't age non-gateway host routes */
2759         np->rip6_tag = 0;
2760         np->rip6_metric = rtm->rtm_rmx.rmx_hopcount;
2761         if (np->rip6_metric < 1)
2762                 np->rip6_metric = 1;
2763         rrt->rrt_flags = rtm->rtm_flags;
2764         np->rip6_dest = sin6_dst->sin6_addr;
2765
2766         /* Mask or plen */
2767         if (rtm->rtm_flags & RTF_HOST)
2768                 np->rip6_plen = 128;    /* Host route */
2769         else if (sin6_mask)
2770                 np->rip6_plen = sin6mask2len(sin6_mask);
2771         else
2772                 np->rip6_plen = 0;
2773
2774         orrt = rtsearch(np);
2775         if (orrt && orrt->rrt_info.rip6_metric != HOPCNT_INFINITY6) {
2776                 /* Already found */
2777                 if (!again) {
2778                         trace(1, "route: %s/%d flags %s: already registered\n",
2779                                 inet6_n2p(&np->rip6_dest), np->rip6_plen,
2780                                 rtflags(rtm));
2781                 }
2782                 free(rrt);
2783                 return;
2784         }
2785         /* Gateway */
2786         if (!sin6_gw)
2787                 memset(&rrt->rrt_gw, 0, sizeof(struct in6_addr));
2788         else {
2789                 if (sin6_gw->sin6_family == AF_INET6)
2790                         rrt->rrt_gw = sin6_gw->sin6_addr;
2791                 else if (sin6_gw->sin6_family == AF_LINK) {
2792                         /* XXX in case ppp link? */
2793                         rrt->rrt_gw = in6addr_loopback;
2794                 } else
2795                         memset(&rrt->rrt_gw, 0, sizeof(struct in6_addr));
2796         }
2797         trace(1, "route: %s/%d flags %s",
2798                 inet6_n2p(&np->rip6_dest), np->rip6_plen, rtflags(rtm));
2799         trace(1, " gw %s", inet6_n2p(&rrt->rrt_gw));
2800
2801         /* Interface */
2802         ifindex = rtm->rtm_index;
2803         if ((unsigned int)ifindex < nindex2ifc && index2ifc[ifindex])
2804                 ifname = index2ifc[ifindex]->ifc_name;
2805         else {
2806                 trace(1, " not configured\n");
2807                 free(rrt);
2808                 return;
2809         }
2810         trace(1, " if %s sock %d", ifname, ifindex);
2811         rrt->rrt_index = ifindex;
2812
2813         trace(1, "\n");
2814
2815         /* Check gateway */
2816         if (!IN6_IS_ADDR_LINKLOCAL(&rrt->rrt_gw) &&
2817             !IN6_IS_ADDR_LOOPBACK(&rrt->rrt_gw) &&
2818             (rrt->rrt_flags & RTF_LOCAL) == 0) {
2819                 trace(0, "***** Gateway %s is not a link-local address.\n",
2820                         inet6_n2p(&rrt->rrt_gw));
2821                 trace(0, "*****     dest(%s) if(%s) -- Not optimized.\n",
2822                         inet6_n2p(&rrt->rrt_info.rip6_dest), ifname);
2823                 rrt->rrt_rflags |= RRTF_NH_NOT_LLADDR;
2824         }
2825
2826         /* Put it to the route list */
2827         if (orrt && orrt->rrt_info.rip6_metric == HOPCNT_INFINITY6) {
2828                 /* replace route list */
2829                 TAILQ_INSERT_BEFORE(orrt, rrt, rrt_next);
2830                 TAILQ_REMOVE(&riprt_head, orrt, rrt_next);
2831
2832                 trace(1, "route: %s/%d flags %s: replace new route\n",
2833                     inet6_n2p(&np->rip6_dest), np->rip6_plen,
2834                     rtflags(rtm));
2835                 free(orrt);
2836         } else
2837                 TAILQ_INSERT_HEAD(&riprt_head, rrt, rrt_next);
2838 }
2839
2840 int
2841 addroute(struct riprt *rrt,
2842         const struct in6_addr *gw,
2843         struct ifc *ifcp)
2844 {
2845         struct  netinfo6 *np;
2846         u_char  buf[BUFSIZ], buf1[BUFSIZ], buf2[BUFSIZ];
2847         struct  rt_msghdr       *rtm;
2848         struct  sockaddr_in6    *sin6;
2849         int     len;
2850
2851         np = &rrt->rrt_info;
2852         inet_ntop(AF_INET6, (const void *)gw, (char *)buf1, sizeof(buf1));
2853         inet_ntop(AF_INET6, (void *)&ifcp->ifc_mylladdr, (char *)buf2, sizeof(buf2));
2854         tracet(1, "ADD: %s/%d gw %s [%d] ifa %s\n",
2855                 inet6_n2p(&np->rip6_dest), np->rip6_plen, buf1,
2856                 np->rip6_metric - 1, buf2);
2857         if (rtlog)
2858                 fprintf(rtlog, "%s: ADD: %s/%d gw %s [%d] ifa %s\n", hms(),
2859                         inet6_n2p(&np->rip6_dest), np->rip6_plen, buf1,
2860                         np->rip6_metric - 1, buf2);
2861         if (nflag)
2862                 return 0;
2863
2864         memset(buf, 0, sizeof(buf));
2865         rtm = (struct rt_msghdr *)buf;
2866         rtm->rtm_type = RTM_ADD;
2867         rtm->rtm_version = RTM_VERSION;
2868         rtm->rtm_seq = ++seq;
2869         rtm->rtm_pid = pid;
2870         rtm->rtm_flags = rrt->rrt_flags;
2871         rtm->rtm_flags |= Qflag;
2872         rtm->rtm_addrs = RTA_DST | RTA_GATEWAY | RTA_NETMASK;
2873         rtm->rtm_rmx.rmx_hopcount = np->rip6_metric - 1;
2874         rtm->rtm_inits = RTV_HOPCOUNT;
2875         sin6 = (struct sockaddr_in6 *)&buf[sizeof(struct rt_msghdr)];
2876         /* Destination */
2877         sin6->sin6_len = sizeof(struct sockaddr_in6);
2878         sin6->sin6_family = AF_INET6;
2879         sin6->sin6_addr = np->rip6_dest;
2880         sin6 = (struct sockaddr_in6 *)((char *)sin6 + ROUNDUP(sin6->sin6_len));
2881         /* Gateway */
2882         sin6->sin6_len = sizeof(struct sockaddr_in6);
2883         sin6->sin6_family = AF_INET6;
2884         sin6->sin6_addr = *gw;
2885         sin6 = (struct sockaddr_in6 *)((char *)sin6 + ROUNDUP(sin6->sin6_len));
2886         /* Netmask */
2887         sin6->sin6_len = sizeof(struct sockaddr_in6);
2888         sin6->sin6_family = AF_INET6;
2889         sin6->sin6_addr = *(plen2mask(np->rip6_plen));
2890         sin6 = (struct sockaddr_in6 *)((char *)sin6 + ROUNDUP(sin6->sin6_len));
2891
2892         len = (char *)sin6 - (char *)buf;
2893         rtm->rtm_msglen = len;
2894         if (write(rtsock, buf, len) > 0)
2895                 return 0;
2896
2897         if (errno == EEXIST) {
2898                 trace(0, "ADD: Route already exists %s/%d gw %s\n",
2899                     inet6_n2p(&np->rip6_dest), np->rip6_plen, buf1);
2900                 if (rtlog)
2901                         fprintf(rtlog, "ADD: Route already exists %s/%d gw %s\n",
2902                             inet6_n2p(&np->rip6_dest), np->rip6_plen, buf1);
2903         } else {
2904                 trace(0, "Can not write to rtsock (addroute): %s\n",
2905                     strerror(errno));
2906                 if (rtlog)
2907                         fprintf(rtlog, "\tCan not write to rtsock: %s\n",
2908                             strerror(errno));
2909         }
2910         return -1;
2911 }
2912
2913 int
2914 delroute(struct netinfo6 *np, struct in6_addr *gw)
2915 {
2916         u_char  buf[BUFSIZ], buf2[BUFSIZ];
2917         struct  rt_msghdr       *rtm;
2918         struct  sockaddr_in6    *sin6;
2919         int     len;
2920
2921         inet_ntop(AF_INET6, (void *)gw, (char *)buf2, sizeof(buf2));
2922         tracet(1, "DEL: %s/%d gw %s\n", inet6_n2p(&np->rip6_dest),
2923                 np->rip6_plen, buf2);
2924         if (rtlog)
2925                 fprintf(rtlog, "%s: DEL: %s/%d gw %s\n",
2926                         hms(), inet6_n2p(&np->rip6_dest), np->rip6_plen, buf2);
2927         if (nflag)
2928                 return 0;
2929
2930         memset(buf, 0, sizeof(buf));
2931         rtm = (struct rt_msghdr *)buf;
2932         rtm->rtm_type = RTM_DELETE;
2933         rtm->rtm_version = RTM_VERSION;
2934         rtm->rtm_seq = ++seq;
2935         rtm->rtm_pid = pid;
2936         rtm->rtm_flags = RTF_UP | RTF_GATEWAY;
2937         rtm->rtm_flags |= Qflag;
2938         if (np->rip6_plen == sizeof(struct in6_addr) * 8)
2939                 rtm->rtm_flags |= RTF_HOST;
2940         rtm->rtm_addrs = RTA_DST | RTA_GATEWAY | RTA_NETMASK;
2941         sin6 = (struct sockaddr_in6 *)&buf[sizeof(struct rt_msghdr)];
2942         /* Destination */
2943         sin6->sin6_len = sizeof(struct sockaddr_in6);
2944         sin6->sin6_family = AF_INET6;
2945         sin6->sin6_addr = np->rip6_dest;
2946         sin6 = (struct sockaddr_in6 *)((char *)sin6 + ROUNDUP(sin6->sin6_len));
2947         /* Gateway */
2948         sin6->sin6_len = sizeof(struct sockaddr_in6);
2949         sin6->sin6_family = AF_INET6;
2950         sin6->sin6_addr = *gw;
2951         sin6 = (struct sockaddr_in6 *)((char *)sin6 + ROUNDUP(sin6->sin6_len));
2952         /* Netmask */
2953         sin6->sin6_len = sizeof(struct sockaddr_in6);
2954         sin6->sin6_family = AF_INET6;
2955         sin6->sin6_addr = *(plen2mask(np->rip6_plen));
2956         sin6 = (struct sockaddr_in6 *)((char *)sin6 + ROUNDUP(sin6->sin6_len));
2957
2958         len = (char *)sin6 - (char *)buf;
2959         rtm->rtm_msglen = len;
2960         if (write(rtsock, buf, len) >= 0)
2961                 return 0;
2962
2963         if (errno == ESRCH) {
2964                 trace(0, "RTDEL: Route does not exist: %s/%d gw %s\n",
2965                     inet6_n2p(&np->rip6_dest), np->rip6_plen, buf2);
2966                 if (rtlog)
2967                         fprintf(rtlog, "RTDEL: Route does not exist: %s/%d gw %s\n",
2968                             inet6_n2p(&np->rip6_dest), np->rip6_plen, buf2);
2969         } else {
2970                 trace(0, "Can not write to rtsock (delroute): %s\n",
2971                     strerror(errno));
2972                 if (rtlog)
2973                         fprintf(rtlog, "\tCan not write to rtsock: %s\n",
2974                             strerror(errno));
2975         }
2976         return -1;
2977 }
2978
2979 struct in6_addr *
2980 getroute(struct netinfo6 *np, struct in6_addr *gw)
2981 {
2982         u_char buf[BUFSIZ];
2983         int myseq;
2984         int len;
2985         struct rt_msghdr *rtm;
2986         struct sockaddr_in6 *sin6;
2987
2988         rtm = (struct rt_msghdr *)buf;
2989         len = sizeof(struct rt_msghdr) + sizeof(struct sockaddr_in6);
2990         memset(rtm, 0, len);
2991         rtm->rtm_type = RTM_GET;
2992         rtm->rtm_version = RTM_VERSION;
2993         myseq = ++seq;
2994         rtm->rtm_seq = myseq;
2995         rtm->rtm_addrs = RTA_DST;
2996         rtm->rtm_msglen = len;
2997         sin6 = (struct sockaddr_in6 *)&buf[sizeof(struct rt_msghdr)];
2998         sin6->sin6_len = sizeof(struct sockaddr_in6);
2999         sin6->sin6_family = AF_INET6;
3000         sin6->sin6_addr = np->rip6_dest;
3001         if (write(rtsock, buf, len) < 0) {
3002                 if (errno == ESRCH)     /* No such route found */
3003                         return NULL;
3004                 perror("write to rtsock");
3005                 exit(1);
3006         }
3007         do {
3008                 if ((len = read(rtsock, buf, sizeof(buf))) < 0) {
3009                         perror("read from rtsock");
3010                         exit(1);
3011                 }
3012                 rtm = (struct rt_msghdr *)buf;
3013         } while (rtm->rtm_seq != myseq || rtm->rtm_pid != pid);
3014         sin6 = (struct sockaddr_in6 *)&buf[sizeof(struct rt_msghdr)];
3015         if (rtm->rtm_addrs & RTA_DST) {
3016                 sin6 = (struct sockaddr_in6 *)
3017                         ((char *)sin6 + ROUNDUP(sin6->sin6_len));
3018         }
3019         if (rtm->rtm_addrs & RTA_GATEWAY) {
3020                 *gw = sin6->sin6_addr;
3021                 return gw;
3022         }
3023         return NULL;
3024 }
3025
3026 const char *
3027 inet6_n2p(const struct in6_addr *p)
3028 {
3029         static char buf[BUFSIZ];
3030
3031         return inet_ntop(AF_INET6, (const void *)p, buf, sizeof(buf));
3032 }
3033
3034 void
3035 ifrtdump(int sig)
3036 {
3037
3038         ifdump(sig);
3039         rtdump(sig);
3040 }
3041
3042 void
3043 ifdump(int sig)
3044 {
3045         struct ifc *ifcp;
3046         FILE *dump;
3047         int nifc = 0;
3048
3049         if (sig == 0)
3050                 dump = stderr;
3051         else
3052                 if ((dump = fopen(ROUTE6D_DUMP, "a")) == NULL)
3053                         dump = stderr;
3054
3055         fprintf(dump, "%s: Interface Table Dump\n", hms());
3056         TAILQ_FOREACH(ifcp, &ifc_head, ifc_next)
3057                 nifc++;
3058         fprintf(dump, "  Number of interfaces: %d\n", nifc);
3059
3060         fprintf(dump, "  advertising interfaces:\n");
3061         TAILQ_FOREACH(ifcp, &ifc_head, ifc_next) {
3062                 if ((ifcp->ifc_flags & IFF_UP) == 0)
3063                         continue;
3064                 if (iff_find(ifcp, IFIL_TYPE_N) != NULL)
3065                         continue;
3066                 ifdump0(dump, ifcp);
3067         }
3068         fprintf(dump, "\n");
3069         fprintf(dump, "  non-advertising interfaces:\n");
3070         TAILQ_FOREACH(ifcp, &ifc_head, ifc_next) {
3071                 if ((ifcp->ifc_flags & IFF_UP) &&
3072                     (iff_find(ifcp, IFIL_TYPE_N) == NULL))
3073                         continue;
3074                 ifdump0(dump, ifcp);
3075         }
3076         fprintf(dump, "\n");
3077         if (dump != stderr)
3078                 fclose(dump);
3079 }
3080
3081 void
3082 ifdump0(FILE *dump, const struct ifc *ifcp)
3083 {
3084         struct ifac *ifac;
3085         struct iff *iffp;
3086         char buf[BUFSIZ];
3087         const char *ft;
3088         int addr;
3089
3090         fprintf(dump, "    %s: index(%d) flags(%s) addr(%s) mtu(%d) metric(%d)\n",
3091                 ifcp->ifc_name, ifcp->ifc_index, ifflags(ifcp->ifc_flags),
3092                 inet6_n2p(&ifcp->ifc_mylladdr),
3093                 ifcp->ifc_mtu, ifcp->ifc_metric);
3094         TAILQ_FOREACH(ifac, &ifcp->ifc_ifac_head, ifac_next) {
3095                 if (ifcp->ifc_flags & IFF_POINTOPOINT) {
3096                         inet_ntop(AF_INET6, (void *)&ifac->ifac_raddr,
3097                                 buf, sizeof(buf));
3098                         fprintf(dump, "\t%s/%d -- %s\n",
3099                                 inet6_n2p(&ifac->ifac_addr),
3100                                 ifac->ifac_plen, buf);
3101                 } else {
3102                         fprintf(dump, "\t%s/%d\n",
3103                                 inet6_n2p(&ifac->ifac_addr),
3104                                 ifac->ifac_plen);
3105                 }
3106         }
3107
3108         fprintf(dump, "\tFilter:\n");
3109         TAILQ_FOREACH(iffp, &ifcp->ifc_iff_head, iff_next) {
3110                 addr = 0;
3111                 switch (iffp->iff_type) {
3112                 case IFIL_TYPE_A:
3113                         ft = "Aggregate"; addr++; break;
3114                 case IFIL_TYPE_N:
3115                         ft = "No-use"; break;
3116                 case IFIL_TYPE_O:
3117                         ft = "Advertise-only"; addr++; break;
3118                 case IFIL_TYPE_T:
3119                         ft = "Default-only"; break;
3120                 case IFIL_TYPE_L:
3121                         ft = "Listen-only"; addr++; break;
3122                 default:
3123                         snprintf(buf, sizeof(buf), "Unknown-%c", iffp->iff_type);
3124                         ft = buf;
3125                         addr++;
3126                         break;
3127                 }
3128                 fprintf(dump, "\t\t%s", ft);
3129                 if (addr)
3130                         fprintf(dump, "(%s/%d)", inet6_n2p(&iffp->iff_addr),
3131                                 iffp->iff_plen);
3132                 fprintf(dump, "\n");
3133         }
3134         fprintf(dump, "\n");
3135 }
3136
3137 void
3138 rtdump(int sig)
3139 {
3140         struct  riprt *rrt;
3141         char    buf[BUFSIZ];
3142         FILE    *dump;
3143         time_t  t, age;
3144
3145         if (sig == 0)
3146                 dump = stderr;
3147         else
3148                 if ((dump = fopen(ROUTE6D_DUMP, "a")) == NULL)
3149                         dump = stderr;
3150
3151         t = time(NULL);
3152         fprintf(dump, "\n%s: Routing Table Dump\n", hms());
3153         TAILQ_FOREACH(rrt, &riprt_head, rrt_next) {
3154                 if (rrt->rrt_t == 0)
3155                         age = 0;
3156                 else
3157                         age = t - rrt->rrt_t;
3158                 inet_ntop(AF_INET6, (void *)&rrt->rrt_info.rip6_dest,
3159                         buf, sizeof(buf));
3160                 fprintf(dump, "    %s/%d if(%d:%s) gw(%s) [%d] age(%ld)",
3161                         buf, rrt->rrt_info.rip6_plen, rrt->rrt_index,
3162                         index2ifc[rrt->rrt_index]->ifc_name,
3163                         inet6_n2p(&rrt->rrt_gw),
3164                         rrt->rrt_info.rip6_metric, (long)age);
3165                 if (rrt->rrt_info.rip6_tag) {
3166                         fprintf(dump, " tag(0x%04x)",
3167                                 ntohs(rrt->rrt_info.rip6_tag) & 0xffff);
3168                 }
3169                 if (rrt->rrt_rflags & RRTF_NH_NOT_LLADDR)
3170                         fprintf(dump, " NOT-LL");
3171                 if (rrt->rrt_rflags & RRTF_NOADVERTISE)
3172                         fprintf(dump, " NO-ADV");
3173                 fprintf(dump, "\n");
3174         }
3175         fprintf(dump, "\n");
3176         if (dump != stderr)
3177                 fclose(dump);
3178 }
3179
3180 /*
3181  * Parse the -A (and -O) options and put corresponding filter object to the
3182  * specified interface structures.  Each of the -A/O option has the following
3183  * syntax:      -A 5f09:c400::/32,ef0,ef1  (aggregate)
3184  *              -O 5f09:c400::/32,ef0,ef1  (only when match)
3185  */
3186 void
3187 filterconfig(void)
3188 {
3189         int i;
3190         char *p, *ap, *iflp, *ifname, *ep;
3191         struct iff iff, *iffp;
3192         struct ifc *ifcp;
3193         struct riprt *rrt;
3194 #if 0
3195         struct in6_addr gw;
3196 #endif
3197         u_long plen;
3198
3199         for (i = 0; i < nfilter; i++) {
3200                 ap = filter[i];
3201                 iflp = NULL;
3202                 iffp = &iff;
3203                 memset(iffp, 0, sizeof(*iffp));
3204                 if (filtertype[i] == 'N' || filtertype[i] == 'T') {
3205                         iflp = ap;
3206                         goto ifonly;
3207                 }
3208                 if ((p = strchr(ap, ',')) != NULL) {
3209                         *p++ = '\0';
3210                         iflp = p;
3211                 }
3212                 if ((p = strchr(ap, '/')) == NULL) {
3213                         fatal("no prefixlen specified for '%s'", ap);
3214                         /*NOTREACHED*/
3215                 }
3216                 *p++ = '\0';
3217                 if (inet_pton(AF_INET6, ap, &iffp->iff_addr) != 1) {
3218                         fatal("invalid prefix specified for '%s'", ap);
3219                         /*NOTREACHED*/
3220                 }
3221                 errno = 0;
3222                 ep = NULL;
3223                 plen = strtoul(p, &ep, 10);
3224                 if (errno || !*p || *ep || plen > sizeof(iffp->iff_addr) * 8) {
3225                         fatal("invalid prefix length specified for '%s'", ap);
3226                         /*NOTREACHED*/
3227                 }
3228                 iffp->iff_plen = plen;
3229                 applyplen(&iffp->iff_addr, iffp->iff_plen);
3230 ifonly:
3231                 iffp->iff_type = filtertype[i];
3232                 if (iflp == NULL || *iflp == '\0') {
3233                         fatal("no interface specified for '%s'", ap);
3234                         /*NOTREACHED*/
3235                 }
3236                 /* parse the interface listing portion */
3237                 while (iflp) {
3238                         ifname = iflp;
3239                         if ((iflp = strchr(iflp, ',')) != NULL)
3240                                 *iflp++ = '\0';
3241
3242                         TAILQ_FOREACH(ifcp, &ifc_head, ifc_next) {
3243                                 if (fnmatch(ifname, ifcp->ifc_name, 0) != 0)
3244                                         continue;
3245
3246                                 iffp = malloc(sizeof(*iffp));
3247                                 if (iffp == NULL) {
3248                                         fatal("malloc of iff");
3249                                         /*NOTREACHED*/
3250                                 }
3251                                 memcpy(iffp, &iff, sizeof(*iffp));
3252 #if 0
3253                                 syslog(LOG_INFO, "Add filter: type %d, ifname %s.", iffp->iff_type, ifname);
3254 #endif
3255                                 TAILQ_INSERT_HEAD(&ifcp->ifc_iff_head, iffp, iff_next);
3256                         }
3257                 }
3258
3259                 /*
3260                  * -A: aggregate configuration.
3261                  */
3262                 if (filtertype[i] != IFIL_TYPE_A)
3263                         continue;
3264                 /* put the aggregate to the kernel routing table */
3265                 rrt = (struct riprt *)malloc(sizeof(struct riprt));
3266                 if (rrt == NULL) {
3267                         fatal("malloc: rrt");
3268                         /*NOTREACHED*/
3269                 }
3270                 memset(rrt, 0, sizeof(struct riprt));
3271                 rrt->rrt_info.rip6_dest = iff.iff_addr;
3272                 rrt->rrt_info.rip6_plen = iff.iff_plen;
3273                 rrt->rrt_info.rip6_metric = 1;
3274                 rrt->rrt_info.rip6_tag = htons(routetag & 0xffff);
3275                 rrt->rrt_gw = in6addr_loopback;
3276                 rrt->rrt_flags = RTF_UP | RTF_REJECT;
3277                 rrt->rrt_rflags = RRTF_AGGREGATE;
3278                 rrt->rrt_t = 0;
3279                 rrt->rrt_index = loopifcp->ifc_index;
3280 #if 0
3281                 if (getroute(&rrt->rrt_info, &gw)) {
3282 #if 0
3283                         /*
3284                          * When the address has already been registered in the
3285                          * kernel routing table, it should be removed 
3286                          */
3287                         delroute(&rrt->rrt_info, &gw);
3288 #else
3289                         /* it is safer behavior */
3290                         errno = EINVAL;
3291                         fatal("%s/%u already in routing table, "
3292                             "cannot aggregate",
3293                             inet6_n2p(&rrt->rrt_info.rip6_dest),
3294                             rrt->rrt_info.rip6_plen);
3295                         /*NOTREACHED*/
3296 #endif
3297                 }
3298 #endif
3299                 /* Put the route to the list */
3300                 TAILQ_INSERT_HEAD(&riprt_head, rrt, rrt_next);
3301                 trace(1, "Aggregate: %s/%d for %s\n",
3302                         inet6_n2p(&iff.iff_addr), iff.iff_plen,
3303                         loopifcp->ifc_name);
3304                 /* Add this route to the kernel */
3305                 if (nflag)      /* do not modify kernel routing table */
3306                         continue;
3307                 addroute(rrt, &in6addr_loopback, loopifcp);
3308         }
3309 }
3310
3311 /***************** utility functions *****************/
3312
3313 /*
3314  * Returns a pointer to ifac whose address and prefix length matches
3315  * with the address and prefix length specified in the arguments.
3316  */
3317 struct ifac *
3318 ifa_match(const struct ifc *ifcp,
3319         const struct in6_addr *ia,
3320         int plen)
3321 {
3322         struct ifac *ifac;
3323
3324         TAILQ_FOREACH(ifac, &ifcp->ifc_ifac_head, ifac_next) {
3325                 if (IN6_ARE_ADDR_EQUAL(&ifac->ifac_addr, ia) &&
3326                     ifac->ifac_plen == plen)
3327                         break;
3328         }
3329
3330         return (ifac);
3331 }
3332
3333 /*
3334  * Return a pointer to riprt structure whose address and prefix length
3335  * matches with the address and prefix length found in the argument.
3336  * Note: This is not a rtalloc().  Therefore exact match is necessary.
3337  */
3338 struct riprt *
3339 rtsearch(struct netinfo6 *np)
3340 {
3341         struct  riprt   *rrt;
3342
3343         TAILQ_FOREACH(rrt, &riprt_head, rrt_next) {
3344                 if (rrt->rrt_info.rip6_plen == np->rip6_plen &&
3345                     IN6_ARE_ADDR_EQUAL(&rrt->rrt_info.rip6_dest,
3346                                        &np->rip6_dest))
3347                         break;
3348         }
3349
3350         return (rrt);
3351 }
3352
3353 int
3354 sin6mask2len(const struct sockaddr_in6 *sin6)
3355 {
3356
3357         return mask2len(&sin6->sin6_addr,
3358             sin6->sin6_len - offsetof(struct sockaddr_in6, sin6_addr));
3359 }
3360
3361 int
3362 mask2len(const struct in6_addr *addr, int lenlim)
3363 {
3364         int i = 0, j;
3365         const u_char *p = (const u_char *)addr;
3366         
3367         for (j = 0; j < lenlim; j++, p++) {
3368                 if (*p != 0xff)
3369                         break;
3370                 i += 8;
3371         }
3372         if (j < lenlim) {
3373                 switch (*p) {
3374 #define MASKLEN(m, l)   case m: do { i += l; break; } while (0)
3375                 MASKLEN(0xfe, 7); break;
3376                 MASKLEN(0xfc, 6); break;
3377                 MASKLEN(0xf8, 5); break;
3378                 MASKLEN(0xf0, 4); break;
3379                 MASKLEN(0xe0, 3); break;
3380                 MASKLEN(0xc0, 2); break;
3381                 MASKLEN(0x80, 1); break;
3382 #undef  MASKLEN
3383                 }
3384         }
3385         return i;
3386 }
3387
3388 void
3389 applymask(struct in6_addr *addr, struct in6_addr *mask)
3390 {
3391         int     i;
3392         u_long  *p, *q;
3393
3394         p = (u_long *)addr; q = (u_long *)mask;
3395         for (i = 0; i < 4; i++)
3396                 *p++ &= *q++;
3397 }
3398
3399 static const u_char plent[8] = {
3400         0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe
3401 };
3402
3403 void
3404 applyplen(struct in6_addr *ia, int plen)
3405 {
3406         u_char  *p;
3407         int     i;
3408
3409         p = ia->s6_addr;
3410         for (i = 0; i < 16; i++) {
3411                 if (plen <= 0)
3412                         *p = 0;
3413                 else if (plen < 8)
3414                         *p &= plent[plen];
3415                 p++, plen -= 8;
3416         }
3417 }
3418
3419 static const int pl2m[9] = {
3420         0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff
3421 };
3422
3423 struct in6_addr *
3424 plen2mask(int n)
3425 {
3426         static struct in6_addr ia;
3427         u_char  *p;
3428         int     i;
3429
3430         memset(&ia, 0, sizeof(struct in6_addr));
3431         p = (u_char *)&ia;
3432         for (i = 0; i < 16; i++, p++, n -= 8) {
3433                 if (n >= 8) {
3434                         *p = 0xff;
3435                         continue;
3436                 }
3437                 *p = pl2m[n];
3438                 break;
3439         }
3440         return &ia;
3441 }
3442
3443 char *
3444 allocopy(char *p)
3445 {
3446         int len = strlen(p) + 1;
3447         char *q = (char *)malloc(len);
3448
3449         if (!q) {
3450                 fatal("malloc");
3451                 /*NOTREACHED*/
3452         }
3453
3454         strlcpy(q, p, len);
3455         return q;
3456 }
3457
3458 char *
3459 hms(void)
3460 {
3461         static char buf[BUFSIZ];
3462         time_t t;
3463         struct  tm *tm;
3464
3465         t = time(NULL);
3466         if ((tm = localtime(&t)) == 0) {
3467                 fatal("localtime");
3468                 /*NOTREACHED*/
3469         }
3470         snprintf(buf, sizeof(buf), "%02d:%02d:%02d", tm->tm_hour, tm->tm_min,
3471             tm->tm_sec);
3472         return buf;
3473 }
3474
3475 #define RIPRANDDEV      1.0     /* 30 +- 15, max - min = 30 */
3476
3477 int
3478 ripinterval(int timer)
3479 {
3480         double r = rand();
3481
3482         interval = (int)(timer + timer * RIPRANDDEV * (r / RAND_MAX - 0.5));
3483         nextalarm = time(NULL) + interval;
3484         return interval;
3485 }
3486
3487 time_t
3488 ripsuptrig(void)
3489 {
3490         time_t t;
3491
3492         double r = rand();
3493         t  = (int)(RIP_TRIG_INT6_MIN + 
3494                 (RIP_TRIG_INT6_MAX - RIP_TRIG_INT6_MIN) * (r / RAND_MAX));
3495         sup_trig_update = time(NULL) + t;
3496         return t;
3497 }
3498
3499 void
3500 #ifdef __STDC__
3501 fatal(const char *fmt, ...)
3502 #else
3503 fatal(fmt, va_alist)
3504         char    *fmt;
3505         va_dcl
3506 #endif
3507 {
3508         va_list ap;
3509         char buf[1024];
3510
3511 #ifdef __STDC__
3512         va_start(ap, fmt);
3513 #else
3514         va_start(ap);
3515 #endif
3516         vsnprintf(buf, sizeof(buf), fmt, ap);
3517         va_end(ap);
3518         perror(buf);
3519         if (errno)
3520                 syslog(LOG_ERR, "%s: %s", buf, strerror(errno));
3521         else
3522                 syslog(LOG_ERR, "%s", buf);
3523         rtdexit();
3524 }
3525
3526 void
3527 #ifdef __STDC__
3528 tracet(int level, const char *fmt, ...)
3529 #else
3530 tracet(level, fmt, va_alist)
3531         int level;
3532         char *fmt;
3533         va_dcl
3534 #endif
3535 {
3536         va_list ap;
3537
3538         if (level <= dflag) {
3539 #ifdef __STDC__
3540                 va_start(ap, fmt);
3541 #else
3542                 va_start(ap);
3543 #endif
3544                 fprintf(stderr, "%s: ", hms());
3545                 vfprintf(stderr, fmt, ap);
3546                 va_end(ap);
3547         }
3548         if (dflag) {
3549 #ifdef __STDC__
3550                 va_start(ap, fmt);
3551 #else
3552                 va_start(ap);
3553 #endif
3554                 if (level > 0)
3555                         vsyslog(LOG_DEBUG, fmt, ap);
3556                 else
3557                         vsyslog(LOG_WARNING, fmt, ap);
3558                 va_end(ap);
3559         }
3560 }
3561
3562 void
3563 #ifdef __STDC__
3564 trace(int level, const char *fmt, ...)
3565 #else
3566 trace(level, fmt, va_alist)
3567         int level;
3568         char *fmt;
3569         va_dcl
3570 #endif
3571 {
3572         va_list ap;
3573
3574         if (level <= dflag) {
3575 #ifdef __STDC__
3576                 va_start(ap, fmt);
3577 #else
3578                 va_start(ap);
3579 #endif
3580                 vfprintf(stderr, fmt, ap);
3581                 va_end(ap);
3582         }
3583         if (dflag) {
3584 #ifdef __STDC__
3585                 va_start(ap, fmt);
3586 #else
3587                 va_start(ap);
3588 #endif
3589                 if (level > 0)
3590                         vsyslog(LOG_DEBUG, fmt, ap);
3591                 else
3592                         vsyslog(LOG_WARNING, fmt, ap);
3593                 va_end(ap);
3594         }
3595 }
3596
3597 unsigned int
3598 if_maxindex(void)
3599 {
3600         struct if_nameindex *p, *p0;
3601         unsigned int max = 0;
3602
3603         p0 = if_nameindex();
3604         for (p = p0; p && p->if_index && p->if_name; p++) {
3605                 if (max < p->if_index)
3606                         max = p->if_index;
3607         }
3608         if_freenameindex(p0);
3609         return max;
3610 }
3611
3612 struct ifc *
3613 ifc_find(char *name)
3614 {
3615         struct ifc *ifcp;
3616
3617         TAILQ_FOREACH(ifcp, &ifc_head, ifc_next) {
3618                 if (strcmp(name, ifcp->ifc_name) == 0)
3619                         break;
3620         }
3621         return (ifcp);
3622 }
3623
3624 struct iff *
3625 iff_find(struct ifc *ifcp, int type)
3626 {
3627         struct iff *iffp;
3628
3629         TAILQ_FOREACH(iffp, &ifcp->ifc_iff_head, iff_next) {
3630                 if (type == IFIL_TYPE_ANY ||
3631                     type == iffp->iff_type)
3632                         break;
3633         }
3634
3635         return (iffp);
3636 }
3637
3638 void
3639 setindex2ifc(int idx, struct ifc *ifcp)
3640 {
3641         int n, nsize;
3642         struct ifc **p;
3643
3644         if (!index2ifc) {
3645                 nindex2ifc = 5; /*initial guess*/
3646                 index2ifc = (struct ifc **)
3647                         malloc(sizeof(*index2ifc) * nindex2ifc);
3648                 if (index2ifc == NULL) {
3649                         fatal("malloc");
3650                         /*NOTREACHED*/
3651                 }
3652                 memset(index2ifc, 0, sizeof(*index2ifc) * nindex2ifc);
3653         }
3654         n = nindex2ifc;
3655         for (nsize = nindex2ifc; nsize <= idx; nsize *= 2)
3656                 ;
3657         if (n != nsize) {
3658                 p = (struct ifc **)realloc(index2ifc,
3659                     sizeof(*index2ifc) * nsize);
3660                 if (p == NULL) {
3661                         fatal("realloc");
3662                         /*NOTREACHED*/
3663                 }
3664                 memset(p + n, 0, sizeof(*index2ifc) * (nindex2ifc - n));
3665                 index2ifc = p;
3666                 nindex2ifc = nsize;
3667         }
3668         index2ifc[idx] = ifcp;
3669 }