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