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