sbin/route: Add support for printing RTM_IEEE80211 messages
[dragonfly.git] / sbin / route / route.c
1 /*
2  * Copyright (c) 1983, 1989, 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * @(#) Copyright (c) 1983, 1989, 1991, 1993 The Regents of the University of California.  All rights reserved.
30  * @(#)route.c  8.6 (Berkeley) 4/28/95
31  * $FreeBSD: src/sbin/route/route.c,v 1.40.2.11 2003/02/27 23:10:10 ru Exp $
32  */
33
34 #include <sys/param.h>
35 #include <sys/file.h>
36 #include <sys/socket.h>
37 #include <sys/ioctl.h>
38 #include <sys/sysctl.h>
39 #include <sys/types.h>
40
41 #include <net/if.h>
42 #include <net/route.h>
43 #include <net/if_dl.h>
44 #include <netinet/in.h>
45 #include <netinet/if_ether.h>
46 #include <arpa/inet.h>
47 #include <netdb.h>
48
49 #include <netproto/802_11/ieee80211_dragonfly.h>
50 #include <netproto/mpls/mpls.h>
51
52 #include <ctype.h>
53 #include <err.h>
54 #include <errno.h>
55 #include <inttypes.h>
56 #include <paths.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <sysexits.h>
61 #include <unistd.h>
62 #include <ifaddrs.h>
63
64 #include "extern.h"
65
66 union   sockunion {
67         struct  sockaddr sa;
68         struct  sockaddr_in sin;
69 #ifdef INET6
70         struct  sockaddr_in6 sin6;
71 #endif
72         struct  sockaddr_mpls smpls;
73         struct  sockaddr_dl sdl;
74         struct  sockaddr_inarp sinarp;
75         struct  sockaddr_storage ss; /* added to avoid memory overrun */
76 } so_dst, so_gate, so_mask, so_genmask, so_ifa, so_ifp, so_mpls1,
77         so_mpls2, so_mpls3;
78
79 typedef union sockunion *sup;
80
81 int     nflag, wflag;
82 int     cpuflag = -1;
83
84 static struct keytab {
85         const char      *kt_cp;
86         int     kt_i;
87 } const keywords[] = {
88 #include "keywords.h"
89         {0, 0}
90 };
91
92 static struct sockaddr_in so_gate_tried;
93 static struct rt_metrics rt_metrics;
94 static int      pid, rtm_addrs;
95 static int      s;
96 static int      forcehost, forcenet, af, qflag, tflag;
97 static int      iflag, verbose, aflen = sizeof(struct sockaddr_in);
98 static int      locking, lockrest, debugonly;
99 static int      mplsop, popcount, pushcount, swapcount;
100 static u_long   rtm_inits;
101 static uid_t    uid;
102
103 static void      flushroutes(int, char **);
104 static void      set_metric(char *, int);
105 static void      newroute(int, char **) __dead2;
106 static void      inet_makenetandmask(u_long, struct sockaddr_in *, u_long);
107 static void      interfaces(void);
108 static void      monitor(void) __dead2;
109 static void      sockaddr(const char *, struct sockaddr *);
110 static void      sodump(sup, const char *);
111 static void      bprintf(FILE *, int, u_char *);
112 static void      print_getmsg(struct rt_msghdr *, int);
113 static void      print_rtmsg(struct rt_msghdr *, int);
114 static void      pmsg_common(struct rt_msghdr *);
115 static void      pmsg_addrs(char *, int);
116 static void      mask_addr(void);
117 static int       getaddr(int, const char *, struct hostent **);
118 static int       rtmsg(int, int);
119 static int       prefixlen(const char *);
120 #ifdef INET6
121 static int       inet6_makenetandmask(struct sockaddr_in6 *, const char *);
122 #endif
123
124 #define PRIETHER        "02x:%02x:%02x:%02x:%02x:%02x"
125 #define PRIETHER_ARGS(__enaddr) (__enaddr)[0], (__enaddr)[1], (__enaddr)[2], \
126                                 (__enaddr)[3], (__enaddr)[4], (__enaddr)[5]
127
128 void
129 usage(const char *cp)
130 {
131         if (cp != NULL)
132                 warnx("bad keyword: %s", cp);
133         fprintf(stderr, "usage: route [-dnqtvw] [-c cpu] command [[modifiers] args]\n");
134         exit(EX_USAGE);
135         /* NOTREACHED */
136 }
137
138 int
139 main(int argc, char **argv)
140 {
141         int ch;
142
143         if (argc < 2)
144                 usage(NULL);
145
146         while ((ch = getopt(argc, argv, "c:wnqdtv")) != -1)
147                 switch(ch) {
148                 case 'c':
149                         cpuflag = strtol(optarg, NULL, 0);
150                         break;
151                 case 'w':
152                         wflag = 1;
153                         break;
154                 case 'n':
155                         nflag = 1;
156                         break;
157                 case 'q':
158                         qflag = 1;
159                         break;
160                 case 'v':
161                         verbose = 1;
162                         break;
163                 case 't':
164                         tflag = 1;
165                         break;
166                 case 'd':
167                         debugonly = 1;
168                         break;
169                 case '?':
170                 default:
171                         usage(NULL);
172                 }
173         argc -= optind;
174         argv += optind;
175
176         pid = getpid();
177         uid = geteuid();
178         if (tflag)
179                 s = open(_PATH_DEVNULL, O_WRONLY, 0);
180         else {
181
182                 s = socket(PF_ROUTE, SOCK_RAW, 0);
183 #ifdef SO_RERROR
184                 int on = 1;
185                 if (setsockopt(s, SOL_SOCKET, SO_RERROR, &on, sizeof(on)) == -1)
186                         warn("SO_RERROR");
187 #endif
188         }
189         if (s < 0)
190                 err(EX_OSERR, "socket");
191         if (*argv != NULL)
192                 switch (keyword(*argv)) {
193                 case K_GET:
194                         uid = 0;
195                         /* FALLTHROUGH */
196
197                 case K_CHANGE:
198                 case K_ADD:
199                 case K_DELETE:
200                         newroute(argc, argv);
201                         /* NOTREACHED */
202
203                 case K_SHOW:
204                         show(argc, argv);
205                         return(0);
206
207                 case K_MONITOR:
208                         monitor();
209                         /* NOTREACHED */
210
211                 case K_FLUSH:
212                         flushroutes(argc, argv);
213                         exit(0);
214                         /* NOTREACHED */
215                 }
216         usage(*argv);
217         /* NOTREACHED */
218 }
219
220 /*
221  * Purge all entries in the routing tables not
222  * associated with network interfaces.
223  */
224 static void
225 flushroutes(int argc, char **argv)
226 {
227         size_t needed;
228         int mib[7], rlen, seqno;
229         int miblen;
230         char *buf, *next, *lim;
231         struct rt_msghdr *rtm;
232
233         if (uid != 0) {
234                 errx(EX_NOPERM, "must be root to alter routing table");
235         }
236         shutdown(s, SHUT_RD); /* Don't want to read back our messages */
237         if (argc > 1) {
238                 argv++;
239                 if (argc == 2 && **argv == '-')
240                     switch (keyword(*argv + 1)) {
241                         case K_INET:
242                                 af = AF_INET;
243                                 break;
244 #ifdef INET6
245                         case K_INET6:
246                                 af = AF_INET6;
247                                 break;
248 #endif
249                         case K_LINK:
250                                 af = AF_LINK;
251                                 break;
252                         case K_MPLS:
253                                 af = AF_MPLS;
254                                 break;
255                         default:
256                                 goto bad;
257                 } else
258 bad:                    usage(*argv);
259         }
260         mib[0] = CTL_NET;
261         mib[1] = PF_ROUTE;
262         mib[2] = 0;             /* protocol */
263         mib[3] = 0;             /* wildcard address family */
264         mib[4] = NET_RT_DUMP;
265         mib[5] = 0;             /* no flags */
266         if (cpuflag >= 0) {
267                 mib[6] = cpuflag;
268                 miblen = 7;
269         } else {
270                 miblen = 6;
271         }
272         if (sysctl(mib, miblen, NULL, &needed, NULL, 0) < 0)
273                 err(EX_OSERR, "route-sysctl-estimate");
274         if ((buf = malloc(needed)) == NULL)
275                 errx(EX_OSERR, "malloc failed");
276         if (sysctl(mib, miblen, buf, &needed, NULL, 0) < 0)
277                 err(EX_OSERR, "route-sysctl-get");
278         lim = buf + needed;
279         if (verbose)
280                 printf("Examining routing table from sysctl\n");
281         seqno = 0;              /* ??? */
282         for (next = buf; next < lim; next += rtm->rtm_msglen) {
283                 rtm = (struct rt_msghdr *)next;
284                 if (verbose)
285                         print_rtmsg(rtm, rtm->rtm_msglen);
286                 if ((rtm->rtm_flags & RTF_GATEWAY) == 0)
287                         continue;
288                 if (af != 0) {
289                         struct sockaddr *sa = (struct sockaddr *)(rtm + 1);
290
291                         if (sa->sa_family != af)
292                                 continue;
293                 }
294                 if (debugonly)
295                         continue;
296                 rtm->rtm_type = RTM_DELETE;
297                 rtm->rtm_seq = seqno;
298                 rlen = write(s, next, rtm->rtm_msglen);
299                 if (rlen < (int)rtm->rtm_msglen) {
300                         warn("write to routing socket");
301                         printf("got only %d for rlen\n", rlen);
302                         break;
303                 }
304                 seqno++;
305                 if (qflag)
306                         continue;
307                 if (verbose) {
308                         print_rtmsg(rtm, rlen);
309                 } else {
310                         struct sockaddr *sa = (struct sockaddr *)(rtm + 1);
311                         if (wflag) {
312                             printf("%-20s ", rtm->rtm_flags & RTF_HOST ?
313                                 routename(sa) : netname(sa));
314                         } else {
315                             printf("%-20.20s ", rtm->rtm_flags & RTF_HOST ?
316                                 routename(sa) : netname(sa));
317                         }
318                         sa = (struct sockaddr *)(RT_ROUNDUP(sa->sa_len) +
319                             (char *)sa);
320                         if (wflag) {
321                             printf("%-20s ", routename(sa));
322                         } else {
323                             printf("%-20.20s ", routename(sa));
324                         }
325                         printf("done\n");
326                 }
327         }
328 }
329
330 char *
331 routename(struct sockaddr *sa)
332 {
333         const char *cp;
334         static char line[MAXHOSTNAMELEN + 1];
335         struct hostent *hp;
336         static char domain[MAXHOSTNAMELEN + 1];
337         static int first = 1;
338
339         if (first) {
340                 first = 0;
341                 if (gethostname(domain, MAXHOSTNAMELEN) == 0 &&
342                     (cp = strchr(domain, '.'))) {
343                         domain[MAXHOSTNAMELEN] = '\0';
344                         strcpy(domain, cp + 1);
345                 } else
346                         domain[0] = 0;
347         }
348
349         if (sa->sa_len == 0)
350                 strcpy(line, "default");
351         else switch (sa->sa_family) {
352
353         case AF_INET:
354             {   struct in_addr in;
355                 in = ((struct sockaddr_in *)sa)->sin_addr;
356
357                 cp = NULL;
358                 if (in.s_addr == INADDR_ANY || sa->sa_len < 4)
359                         cp = "default";
360                 if (cp == NULL && !nflag) {
361                         hp = gethostbyaddr(&in, sizeof(struct in_addr),
362                                 AF_INET);
363                         if (hp != NULL) {
364                                 char *cptr;
365                                 cptr = strchr(hp->h_name, '.');
366                                 if (cptr != NULL && !wflag &&
367                                     strcmp(cptr + 1, domain) == 0)
368                                         *cptr = '\0';
369                                 cp = hp->h_name;
370                         }
371                 }
372                 if (cp != NULL) {
373                         strncpy(line, cp, sizeof(line) - 1);
374                         line[sizeof(line) - 1] = '\0';
375                 } else
376                         sprintf(line, "%s", inet_ntoa(in));
377                 break;
378             }
379
380 #ifdef INET6
381         case AF_INET6:
382         {
383                 struct sockaddr_in6 sin6; /* use static var for safety */
384                 int niflags = 0;
385 #ifdef NI_WITHSCOPEID
386                 niflags = NI_WITHSCOPEID;
387 #endif
388
389                 memset(&sin6, 0, sizeof(sin6));
390                 memcpy(&sin6, sa, sa->sa_len);
391                 sin6.sin6_len = sizeof(struct sockaddr_in6);
392                 sin6.sin6_family = AF_INET6;
393 #ifdef __KAME__
394                 if (sa->sa_len == sizeof(struct sockaddr_in6) &&
395                     (IN6_IS_ADDR_LINKLOCAL(&sin6.sin6_addr) ||
396                      IN6_IS_ADDR_MC_LINKLOCAL(&sin6.sin6_addr)) &&
397                     sin6.sin6_scope_id == 0) {
398                         sin6.sin6_scope_id =
399                             ntohs(*(u_int16_t *)&sin6.sin6_addr.s6_addr[2]);
400                         sin6.sin6_addr.s6_addr[2] = 0;
401                         sin6.sin6_addr.s6_addr[3] = 0;
402                 }
403 #endif
404                 if (nflag)
405                         niflags |= NI_NUMERICHOST;
406                 if (getnameinfo((struct sockaddr *)&sin6, sin6.sin6_len,
407                     line, sizeof(line), NULL, 0, niflags) != 0)
408                         strncpy(line, "invalid", sizeof(line));
409
410                 return(line);
411         }
412 #endif
413
414         case AF_LINK:
415                 return(link_ntoa((struct sockaddr_dl *)sa));
416
417         default:
418             {
419                 /*
420                  * Unknown address family; just render the raw
421                  * data in sa->sa_data as hex values.
422                  */
423                 uint8_t *sp = (uint8_t *)sa->sa_data;
424                 uint8_t *splim = (uint8_t *)sa + sa->sa_len;
425                 char *cps = line + sprintf(line, "(%d)", sa->sa_family);
426                 char *cpe = line + sizeof(line);
427
428                 while (sp < splim && cps < cpe)
429                         cps += snprintf(cps, cpe - cps, " %02x", *sp++);
430                 break;
431             }
432         }
433         return(line);
434 }
435
436 /*
437  * Return the name of the network whose address is given.
438  * The address is assumed to be that of a net or subnet, not a host.
439  */
440 char *
441 netname(struct sockaddr *sa)
442 {
443         const char *cp = NULL;
444         static char line[MAXHOSTNAMELEN + 1];
445         struct netent *np = NULL;
446         u_long net, mask;
447         u_long i;
448         int subnetshift;
449
450         switch (sa->sa_family) {
451
452         case AF_INET:
453             {   struct in_addr in;
454                 in = ((struct sockaddr_in *)sa)->sin_addr;
455
456                 i = in.s_addr = ntohl(in.s_addr);
457                 if (in.s_addr == 0)
458                         cp = "default";
459                 else if (!nflag) {
460                         if (IN_CLASSA(i)) {
461                                 mask = IN_CLASSA_NET;
462                                 subnetshift = 8;
463                         } else if (IN_CLASSB(i)) {
464                                 mask = IN_CLASSB_NET;
465                                 subnetshift = 8;
466                         } else {
467                                 mask = IN_CLASSC_NET;
468                                 subnetshift = 4;
469                         }
470                         /*
471                          * If there are more bits than the standard mask
472                          * would suggest, subnets must be in use.
473                          * Guess at the subnet mask, assuming reasonable
474                          * width subnet fields.
475                          */
476                         while (in.s_addr &~ mask)
477                                 mask |= mask >> subnetshift;
478                         net = in.s_addr & mask;
479                         while ((mask & 1) == 0)
480                                 mask >>= 1, net >>= 1;
481                         np = getnetbyaddr(net, AF_INET);
482                         if (np != NULL)
483                                 cp = np->n_name;
484                 }
485 #define C(x)    (unsigned)((x) & 0xff)
486                 if (cp != NULL)
487                         strncpy(line, cp, sizeof(line));
488                 else if ((in.s_addr & 0xffffff) == 0)
489                         sprintf(line, "%u", C(in.s_addr >> 24));
490                 else if ((in.s_addr & 0xffff) == 0)
491                         sprintf(line, "%u.%u", C(in.s_addr >> 24),
492                             C(in.s_addr >> 16));
493                 else if ((in.s_addr & 0xff) == 0)
494                         sprintf(line, "%u.%u.%u", C(in.s_addr >> 24),
495                             C(in.s_addr >> 16), C(in.s_addr >> 8));
496                 else
497                         sprintf(line, "%u.%u.%u.%u", C(in.s_addr >> 24),
498                             C(in.s_addr >> 16), C(in.s_addr >> 8),
499                             C(in.s_addr));
500 #undef C
501                 break;
502             }
503
504 #ifdef INET6
505         case AF_INET6:
506         {
507                 struct sockaddr_in6 sin6; /* use static var for safety */
508                 int niflags = 0;
509 #ifdef NI_WITHSCOPEID
510                 niflags = NI_WITHSCOPEID;
511 #endif
512
513                 memset(&sin6, 0, sizeof(sin6));
514                 memcpy(&sin6, sa, sa->sa_len);
515                 sin6.sin6_len = sizeof(struct sockaddr_in6);
516                 sin6.sin6_family = AF_INET6;
517 #ifdef __KAME__
518                 if (sa->sa_len == sizeof(struct sockaddr_in6) &&
519                     (IN6_IS_ADDR_LINKLOCAL(&sin6.sin6_addr) ||
520                      IN6_IS_ADDR_MC_LINKLOCAL(&sin6.sin6_addr)) &&
521                     sin6.sin6_scope_id == 0) {
522                         sin6.sin6_scope_id =
523                             ntohs(*(u_int16_t *)&sin6.sin6_addr.s6_addr[2]);
524                         sin6.sin6_addr.s6_addr[2] = 0;
525                         sin6.sin6_addr.s6_addr[3] = 0;
526                 }
527 #endif
528                 if (nflag)
529                         niflags |= NI_NUMERICHOST;
530                 if (getnameinfo((struct sockaddr *)&sin6, sin6.sin6_len,
531                     line, sizeof(line), NULL, 0, niflags) != 0)
532                         strncpy(line, "invalid", sizeof(line));
533
534                 return(line);
535         }
536 #endif
537
538         case AF_LINK:
539                 return(link_ntoa((struct sockaddr_dl *)sa));
540
541
542         default:
543             {
544                 /*
545                  * Unknown address family; just render the raw
546                  * data in sa->sa_data as hex values.
547                  */
548                 uint8_t *sp = (uint8_t *)sa->sa_data;
549                 uint8_t *splim = (uint8_t *)sa + sa->sa_len;
550                 char *cps = line + sprintf(line, "af %d:", sa->sa_family);
551                 char *cpe = line + sizeof(line);
552
553                 while (sp < splim && cps < cpe)
554                         cps += snprintf(cps, cpe - cps, " %02x", *sp++);
555                 break;
556             }
557         }
558         return(line);
559 }
560
561 static void
562 set_metric(char *value, int key)
563 {
564         int flag = 0;
565         u_long noval, *valp = &noval;
566
567         switch (key) {
568 #define caseof(x, y, z) case x: valp = &rt_metrics.z; flag = y; break
569         caseof(K_MTU, RTV_MTU, rmx_mtu);
570         caseof(K_HOPCOUNT, RTV_HOPCOUNT, rmx_hopcount);
571         caseof(K_EXPIRE, RTV_EXPIRE, rmx_expire);
572         caseof(K_RECVPIPE, RTV_RPIPE, rmx_recvpipe);
573         caseof(K_SENDPIPE, RTV_SPIPE, rmx_sendpipe);
574         caseof(K_SSTHRESH, RTV_SSTHRESH, rmx_ssthresh);
575         caseof(K_RTT, RTV_RTT, rmx_rtt);
576         caseof(K_RTTVAR, RTV_RTTVAR, rmx_rttvar);
577         caseof(K_MSL, RTV_MSL, rmx_msl);
578         caseof(K_IWMAX, RTV_IWMAXSEGS, rmx_iwmaxsegs);
579         caseof(K_IW, RTV_IWCAPSEGS, rmx_iwcapsegs);
580         }
581         rtm_inits |= flag;
582         if (lockrest || locking)
583                 rt_metrics.rmx_locks |= flag;
584         if (locking)
585                 locking = 0;
586         *valp = atoi(value);
587 }
588
589 static void
590 newroute(int argc, char **argv)
591 {
592         char *cmd;
593         const char *err_str, *dest = "", *gateway = "";
594         int ishost = 0, proxy = 0, ret, attempts, oerrno, flags = RTF_STATIC;
595         int key;
596         struct hostent *hp = NULL;
597
598         if (uid != 0) {
599                 errx(EX_NOPERM, "must be root to alter routing table");
600         }
601         cmd = argv[0];
602         if (*cmd != 'g')
603                 shutdown(s, SHUT_RD); /* Don't want to read back our messages */
604         while (--argc > 0) {
605                 if (**(++argv)== '-') {
606                         switch (key = keyword(1 + *argv)) {
607                         case K_LINK:
608                                 af = AF_LINK;
609                                 aflen = sizeof(struct sockaddr_dl);
610                                 break;
611                         case K_INET:
612                                 af = AF_INET;
613                                 aflen = sizeof(struct sockaddr_in);
614                                 break;
615 #ifdef INET6
616                         case K_INET6:
617                                 af = AF_INET6;
618                                 aflen = sizeof(struct sockaddr_in6);
619                                 break;
620 #endif
621                         case K_SA:
622                                 af = PF_ROUTE;
623                                 aflen = sizeof(union sockunion);
624                                 break;
625                         case K_IFACE:
626                         case K_INTERFACE:
627                                 iflag++;
628                                 break;
629                         case K_NOSTATIC:
630                                 flags &= ~RTF_STATIC;
631                                 break;
632                         case K_LLINFO:
633                                 flags |= RTF_LLINFO;
634                                 break;
635                         case K_LOCK:
636                                 locking = 1;
637                                 break;
638                         case K_LOCKREST:
639                                 lockrest = 1;
640                                 break;
641                         case K_HOST:
642                                 forcehost++;
643                                 break;
644                         case K_REJECT:
645                                 flags |= RTF_REJECT;
646                                 break;
647                         case K_BLACKHOLE:
648                                 flags |= RTF_BLACKHOLE;
649                                 break;
650                         case K_PROTO1:
651                                 flags |= RTF_PROTO1;
652                                 break;
653                         case K_PROTO2:
654                                 flags |= RTF_PROTO2;
655                                 break;
656                         case K_PROXY:
657                                 proxy = 1;
658                                 break;
659                         case K_CLONING:
660                                 flags |= RTF_CLONING;
661                                 break;
662                         case K_XRESOLVE:
663                                 flags |= RTF_XRESOLVE;
664                                 break;
665                         case K_STATIC:
666                                 flags |= RTF_STATIC;
667                                 break;
668                         case K_IFA:
669                                 if (--argc == 0)
670                                         usage(NULL);
671                                 getaddr(RTA_IFA, *++argv, 0);
672                                 break;
673                         case K_IFP:
674                                 if (--argc == 0)
675                                         usage(NULL);
676                                 getaddr(RTA_IFP, *++argv, 0);
677                                 break;
678                         case K_GENMASK:
679                                 if (--argc == 0)
680                                         usage(NULL);
681                                 getaddr(RTA_GENMASK, *++argv, 0);
682                                 break;
683                         case K_GATEWAY:
684                                 if (--argc == 0)
685                                         usage(NULL);
686                                 getaddr(RTA_GATEWAY, *++argv, 0);
687                                 break;
688                         case K_DST:
689                                 if (--argc == 0)
690                                         usage(NULL);
691                                 ishost = getaddr(RTA_DST, *++argv, &hp);
692                                 dest = *argv;
693                                 break;
694                         case K_NETMASK:
695                                 if (--argc == 0)
696                                         usage(NULL);
697                                 getaddr(RTA_NETMASK, *++argv, 0);
698                                 /* FALLTHROUGH */
699                         case K_NET:
700                                 forcenet++;
701                                 break;
702                         case K_PREFIXLEN:
703                                 if (--argc == 0)
704                                         usage(NULL);
705                                 if (prefixlen(*++argv) == -1) {
706                                         forcenet = 0;
707                                         ishost = 1;
708                                 } else {
709                                         forcenet = 1;
710                                         ishost = 0;
711                                 }
712                                 break;
713                         case K_MPLS:
714                                 af = AF_MPLS;
715                                 aflen = sizeof(struct sockaddr_mpls);
716                                 break;
717                         case K_POP:
718                                 flags |= RTF_MPLSOPS;
719                                 af = AF_MPLS;
720                                 mplsop = MPLSLOP_POP;
721                                 switch(++popcount){
722                                         case 1:
723                                                 getaddr(RTA_MPLS1, "", 0);
724                                                 break;
725                                         case 2:
726                                                 getaddr(RTA_MPLS2, "", 0);
727                                                 break;
728                                         case 3:
729                                                 getaddr(RTA_MPLS3, "", 0);
730                                                 break;
731                                 }
732                                 break;
733                         case K_PUSH:
734                         case K_SWAP:
735                                 if (popcount > 0) {
736                                         warnx("Push or swap after pop. Ignoring.");
737                                         break;
738                                 }
739                                 if (key == K_PUSH) {
740                                         mplsop = MPLSLOP_PUSH;
741                                         ++pushcount;
742                                 } else {
743                                         if (pushcount > 0) {
744                                                 warnx("Swap after push. Ignoring.");
745                                                 break;
746                                         }
747                                         if (swapcount > 0) {
748                                                 warnx("Too many swaps. Ignoring.");
749                                                 break;
750                                         }
751                                         mplsop = MPLSLOP_SWAP;
752                                         ++swapcount;
753                                 }
754                                 flags |= RTF_MPLSOPS;
755                                 af = AF_MPLS;
756                                 aflen = sizeof(struct sockaddr_mpls);
757                                 if (--argc == 0)
758                                         usage(NULL);
759                                 switch(pushcount + swapcount){
760                                         case 1:
761                                                 getaddr(RTA_MPLS1, *++argv, 0);
762                                                 break;
763                                         case 2:
764                                                 getaddr(RTA_MPLS2, *++argv, 0);
765                                                 break;
766                                         case 3:
767                                                 getaddr(RTA_MPLS3, *++argv, 0);
768                                                 break;
769                                 }
770                                 break;
771                         case K_MTU:
772                         case K_HOPCOUNT:
773                         case K_EXPIRE:
774                         case K_RECVPIPE:
775                         case K_SENDPIPE:
776                         case K_SSTHRESH:
777                         case K_RTT:
778                         case K_RTTVAR:
779                         case K_MSL:
780                         case K_IWMAX:
781                         case K_IW:
782                                 if (--argc == 0)
783                                         usage(NULL);
784                                 set_metric(*++argv, key);
785                                 break;
786                         default:
787                                 usage(1+*argv);
788                         }
789                 } else {
790                         if ((rtm_addrs & RTA_DST) == 0) {
791                                 dest = *argv;
792                                 ishost = getaddr(RTA_DST, *argv, &hp);
793                         } else if ((rtm_addrs & RTA_GATEWAY) == 0) {
794                                 gateway = *argv;
795                                 getaddr(RTA_GATEWAY, *argv, &hp);
796                         } else {
797                                 getaddr(RTA_NETMASK, *argv, 0);
798                                 forcenet = 1;
799                         }
800                 }
801         }
802         if (forcehost) {
803                 ishost = 1;
804 #ifdef INET6
805                 if (af == AF_INET6) {
806                         rtm_addrs &= ~RTA_NETMASK;
807                         memset((void *)&so_mask, 0, sizeof(so_mask));
808                 }
809 #endif
810         }
811         if (forcenet)
812                 ishost = 0;
813         flags |= RTF_UP;
814         if (ishost)
815                 flags |= RTF_HOST;
816         if (iflag == 0)
817                 flags |= RTF_GATEWAY;
818         if (proxy) {
819                 so_dst.sinarp.sin_other = SIN_PROXY;
820                 flags |= RTF_ANNOUNCE;
821         }
822         for (attempts = 1; ; attempts++) {
823                 errno = 0;
824                 if ((ret = rtmsg(*cmd, flags)) == 0)
825                         break;
826                 if (errno != ENETUNREACH && errno != ESRCH)
827                         break;
828                 if (af == AF_INET && *gateway != '\0' &&
829                     hp != NULL && hp->h_addr_list[1] != NULL) {
830                         so_gate_tried = so_gate.sin;
831                         hp->h_addr_list++;
832                         memmove(&so_gate.sin.sin_addr,
833                                 hp->h_addr_list[0],
834                                 MIN((size_t)hp->h_length,
835                                     sizeof(so_gate.sin.sin_addr)));
836                 } else
837                         break;
838         }
839         if (*cmd == 'g')
840                 exit(0);
841         if (!qflag) {
842                 oerrno = errno;
843                 printf("%s %s %s", cmd, ishost? "host" : "net", dest);
844                 if (*gateway != '\0') {
845                         printf(": gateway %s", gateway);
846                         if (attempts > 1 && ret == 0 && af == AF_INET) {
847                                 printf(" (%s)",
848                                     inet_ntoa(so_gate_tried.sin_addr));
849                         }
850                 }
851                 if (ret == 0) {
852                         printf("\n");
853                 } else {
854                         switch (oerrno) {
855                         case ESRCH:
856                                 err_str = "not in table";
857                                 break;
858                         case EBUSY:
859                                 err_str = "entry in use";
860                                 break;
861                         case ENOBUFS:
862                                 err_str = "routing table overflow";
863                                 break;
864                         case EDQUOT: /* handle recursion avoidance in
865                                         rt_setgate() */
866                                 err_str = "gateway uses the same route";
867                                 break;
868                         default:
869                                 err_str = strerror(oerrno);
870                                 break;
871                         }
872                         printf(": %s\n", err_str);
873                 }
874         }
875         exit(ret != 0);
876 }
877
878 static void
879 inet_makenetandmask(u_long net, struct sockaddr_in *in, u_long bits)
880 {
881         u_long addr, mask = 0;
882         char *cp;
883
884         rtm_addrs |= RTA_NETMASK;
885         /*
886          * XXX: This approach unable to handle 0.0.0.1/32 correctly
887          * as inet_network() converts 0.0.0.1 and 1 equally.
888          */
889         if (net <= 0xff)
890                 addr = net << IN_CLASSA_NSHIFT;
891         else if (net <= 0xffff)
892                 addr = net << IN_CLASSB_NSHIFT;
893         else if (net <= 0xffffff)
894                 addr = net << IN_CLASSC_NSHIFT;
895         else
896                 addr = net;
897
898         if (bits != 0)
899                 mask = 0xffffffff << (32 - bits);
900         else if (net == 0)
901                 mask = 0;
902         else if (IN_CLASSA(addr))
903                 mask = IN_CLASSA_NET;
904         else if (IN_CLASSB(addr))
905                 mask = IN_CLASSB_NET;
906         else if (IN_CLASSC(addr))
907                 mask = IN_CLASSC_NET;
908         else if (IN_MULTICAST(addr))
909                 mask = IN_CLASSD_NET;
910         else
911                 mask = 0xffffffff;
912
913         in->sin_addr.s_addr = htonl(addr);
914         in = &so_mask.sin;
915         in->sin_addr.s_addr = htonl(mask);
916         in->sin_len = 0;
917         in->sin_family = 0;
918         cp = (char *)(&in->sin_addr + 1);
919         while (*--cp == 0 && cp > (char *)in)
920                 ;
921         in->sin_len = 1 + cp - (char *)in;
922 }
923
924 #ifdef INET6
925 /*
926  * XXX the function may need more improvement...
927  */
928 static int
929 inet6_makenetandmask(struct sockaddr_in6 *sin6, const char *plen)
930 {
931         struct in6_addr in6;
932
933         if (plen == NULL) {
934                 if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr) &&
935                     sin6->sin6_scope_id == 0) {
936                         plen = "0";
937                 } else if ((sin6->sin6_addr.s6_addr[0] & 0xe0) == 0x20) {
938                         /* aggregatable global unicast - RFC2374 */
939                         memset(&in6, 0, sizeof(in6));
940                         if (memcmp(&sin6->sin6_addr.s6_addr[8],
941                                    &in6.s6_addr[8], 8) == 0)
942                                 plen = "64";
943                 }
944         }
945
946         if (plen == NULL || strcmp(plen, "128") == 0)
947                 return(1);
948         rtm_addrs |= RTA_NETMASK;
949         prefixlen(plen);
950         return(0);
951 }
952 #endif
953
954 /*
955  * Interpret an argument as a network address of some kind,
956  * returning 1 if a host address, 0 if a network address.
957  */
958 static int
959 getaddr(int which, const char *str, struct hostent **hpp)
960 {
961         sup su;
962         struct hostent *hp;
963         struct netent *np;
964         u_long val;
965         char *q;
966         int afamily;  /* local copy of af so we can change it */
967
968         if (af == 0) {
969                 af = AF_INET;
970                 aflen = sizeof(struct sockaddr_in);
971         }
972         afamily = af;
973         rtm_addrs |= which;
974         switch (which) {
975         case RTA_DST:
976                 su = &so_dst;
977                 break;
978         case RTA_GATEWAY:
979                 su = &so_gate;
980                 if (iflag) {
981                         struct ifaddrs *ifap, *ifa;
982                         struct sockaddr_dl *sdl = NULL;
983
984                         if (getifaddrs(&ifap))
985                                 err(1, "getifaddrs");
986
987                         for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
988                                 if (ifa->ifa_addr->sa_family != AF_LINK)
989                                         continue;
990
991                                 if (strcmp(str, ifa->ifa_name) != 0)
992                                         continue;
993
994                                 sdl = (struct sockaddr_dl *)ifa->ifa_addr;
995                         }
996                         /* If we found it, then use it */
997                         if (sdl != NULL) {
998                                 /*
999                                  * Copy is safe since we have a
1000                                  * sockaddr_storage member in sockunion{}.
1001                                  * Note that we need to copy before calling
1002                                  * freeifaddrs().
1003                                  *
1004                                  * Interface routes are routed only by their
1005                                  * sdl_index or interface name (we provide
1006                                  * both here), not by the ARP address of the
1007                                  * local interface (alen, slen = 0).
1008                                  */
1009                                 memcpy(&su->sdl, sdl, sdl->sdl_len);
1010                                 su->sdl.sdl_alen = 0;
1011                                 su->sdl.sdl_slen = 0;
1012                         }
1013                         freeifaddrs(ifap);
1014                         if (sdl != NULL)
1015                                 return(1);
1016                 }
1017                 break;
1018         case RTA_NETMASK:
1019                 su = &so_mask;
1020                 break;
1021         case RTA_GENMASK:
1022                 su = &so_genmask;
1023                 break;
1024         case RTA_IFP:
1025                 su = &so_ifp;
1026                 afamily = AF_LINK;
1027                 break;
1028         case RTA_IFA:
1029                 su = &so_ifa;
1030                 break;
1031         case RTA_MPLS1:
1032                 su = &so_mpls1;
1033                 break;
1034         case RTA_MPLS2:
1035                 su = &so_mpls2;
1036                 break;
1037         case RTA_MPLS3:
1038                 su = &so_mpls3;
1039                 break;
1040         default:
1041                 usage("internal error");
1042                 /*NOTREACHED*/
1043         }
1044         su->sa.sa_len = aflen;
1045         su->sa.sa_family = afamily; /* cases that don't want it have left
1046                                        already */
1047         if (strcmp(str, "default") == 0) {
1048                 /*
1049                  * Default is net 0.0.0.0/0
1050                  */
1051                 switch (which) {
1052                 case RTA_DST:
1053                         forcenet++;
1054                         /* bzero(su, sizeof(*su)); *//* for readability */
1055                         getaddr(RTA_NETMASK, str, 0);
1056                         break;
1057                 case RTA_NETMASK:
1058                 case RTA_GENMASK:
1059                         /* bzero(su, sizeof(*su)); *//* for readability */
1060                         break;
1061                 }
1062                 return(0);
1063         }
1064         switch (afamily) {
1065 #ifdef INET6
1066         case AF_INET6:
1067         {
1068                 struct addrinfo hints, *res;
1069
1070                 q = NULL;
1071                 if (which == RTA_DST && (q = strchr(str, '/')) != NULL)
1072                         *q = '\0';
1073                 memset(&hints, 0, sizeof(hints));
1074                 hints.ai_family = afamily;      /*AF_INET6*/
1075                 hints.ai_flags = AI_NUMERICHOST;
1076                 hints.ai_socktype = SOCK_DGRAM;         /*dummy*/
1077                 if (getaddrinfo(str, "0", &hints, &res) != 0 ||
1078                     res->ai_family != AF_INET6 ||
1079                     res->ai_addrlen != sizeof(su->sin6)) {
1080                         fprintf(stderr, "%s: bad value\n", str);
1081                         exit(1);
1082                 }
1083                 memcpy(&su->sin6, res->ai_addr, sizeof(su->sin6));
1084 #ifdef __KAME__
1085                 if ((IN6_IS_ADDR_LINKLOCAL(&su->sin6.sin6_addr) ||
1086                      IN6_IS_ADDR_LINKLOCAL(&su->sin6.sin6_addr)) &&
1087                     su->sin6.sin6_scope_id) {
1088                         *(u_int16_t *)&su->sin6.sin6_addr.s6_addr[2] =
1089                                 htons(su->sin6.sin6_scope_id);
1090                         su->sin6.sin6_scope_id = 0;
1091                 }
1092 #endif
1093                 freeaddrinfo(res);
1094                 if (q != NULL)
1095                         *q++ = '/';
1096                 if (which == RTA_DST)
1097                         return(inet6_makenetandmask(&su->sin6, q));
1098                 return(0);
1099         }
1100 #endif /* INET6 */
1101
1102         case AF_LINK:
1103                 link_addr(str, &su->sdl);
1104                 return(1);
1105
1106         case PF_ROUTE:
1107                 su->sa.sa_len = sizeof(*su);
1108                 sockaddr(str, &su->sa);
1109                 return(1);
1110
1111         case AF_MPLS:
1112         {
1113                 mpls_label_t label;
1114
1115                 bzero(su, sizeof(*su));
1116                 su->sa.sa_len = sizeof(*su);
1117                 su->sa.sa_family = AF_MPLS;
1118                 su->smpls.smpls_op = mplsop;
1119                 if (mplsop != MPLSLOP_POP && mplsop != MPLSLOP_POPALL &&
1120                     *str != '\0') {
1121                         if (sscanf(str, "%u", &label) != 1)
1122                                 errx(EX_NOHOST, "bad address: %s", str);
1123                         su->smpls.smpls_label = htonl(label);
1124                 }
1125                 return(1);
1126         }
1127
1128         case AF_INET:
1129         default:
1130                 break;
1131         }
1132
1133         if (hpp == NULL)
1134                 hpp = &hp;
1135         *hpp = NULL;
1136
1137         q = strchr(str,'/');
1138         if (q != NULL && which == RTA_DST) {
1139                 *q = '\0';
1140                 if ((val = inet_network(str)) != INADDR_NONE) {
1141                         inet_makenetandmask(
1142                                 val, &su->sin, strtoul(q+1, 0, 0));
1143                         return(0);
1144                 }
1145                 *q = '/';
1146         }
1147         if ((which != RTA_DST || forcenet == 0) &&
1148             inet_aton(str, &su->sin.sin_addr)) {
1149                 val = su->sin.sin_addr.s_addr;
1150                 if (which != RTA_DST ||
1151                     inet_lnaof(su->sin.sin_addr) != INADDR_ANY)
1152                         return(1);
1153                 else {
1154                         val = ntohl(val);
1155                         goto netdone;
1156                 }
1157         }
1158         if (which == RTA_DST && forcehost == 0 &&
1159             ((val = inet_network(str)) != INADDR_NONE ||
1160             ((np = getnetbyname(str)) != NULL && (val = np->n_net) != 0))) {
1161 netdone:
1162                 inet_makenetandmask(val, &su->sin, 0);
1163                 return(0);
1164         }
1165         hp = gethostbyname(str);
1166         if (hp != NULL) {
1167                 *hpp = hp;
1168                 su->sin.sin_family = hp->h_addrtype;
1169                 memmove((char *)&su->sin.sin_addr, hp->h_addr,
1170                     MIN((size_t)hp->h_length, sizeof(su->sin.sin_addr)));
1171                 return(1);
1172         }
1173         errx(EX_NOHOST, "bad address: %s", str);
1174 }
1175
1176 static int
1177 prefixlen(const char *len_str)
1178 {
1179         int len = atoi(len_str), q, r;
1180         int max;
1181         char *p;
1182
1183         rtm_addrs |= RTA_NETMASK;
1184         switch (af) {
1185 #ifdef INET6
1186         case AF_INET6:
1187                 max = 128;
1188                 p = (char *)&so_mask.sin6.sin6_addr;
1189                 break;
1190 #endif
1191         case AF_INET:
1192                 max = 32;
1193                 p = (char *)&so_mask.sin.sin_addr;
1194                 break;
1195         default:
1196                 fprintf(stderr, "prefixlen not supported in this af\n");
1197                 exit(1);
1198                 /*NOTREACHED*/
1199         }
1200
1201         if (len < 0 || max < len) {
1202                 fprintf(stderr, "%s: bad value\n", len_str);
1203                 exit(1);
1204         }
1205
1206         q = len >> 3;
1207         r = len & 7;
1208         so_mask.sa.sa_family = af;
1209         so_mask.sa.sa_len = aflen;
1210         memset((void *)p, 0, max / 8);
1211         if (q > 0)
1212                 memset((void *)p, 0xff, q);
1213         if (r > 0)
1214                 *((u_char *)p + q) = (0xff00 >> r) & 0xff;
1215         if (len == max)
1216                 return(-1);
1217         else
1218                 return(len);
1219 }
1220
1221 static void
1222 interfaces(void)
1223 {
1224         size_t needed;
1225         int mib[6];
1226         char *buf, *lim, *next;
1227         struct rt_msghdr *rtm;
1228
1229         mib[0] = CTL_NET;
1230         mib[1] = PF_ROUTE;
1231         mib[2] = 0;             /* protocol */
1232         mib[3] = 0;             /* wildcard address family */
1233         mib[4] = NET_RT_IFLIST;
1234         mib[5] = 0;             /* no flags */
1235         if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
1236                 err(EX_OSERR, "route-sysctl-estimate");
1237         if ((buf = malloc(needed)) == NULL)
1238                 errx(EX_OSERR, "malloc failed");
1239         if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0)
1240                 err(EX_OSERR, "actual retrieval of interface table");
1241         lim = buf + needed;
1242         for (next = buf; next < lim; next += rtm->rtm_msglen) {
1243                 rtm = (struct rt_msghdr *)next;
1244                 print_rtmsg(rtm, rtm->rtm_msglen);
1245         }
1246 }
1247
1248 static void
1249 monitor(void)
1250 {
1251         int n, error;
1252         char msg[2048];
1253         time_t now;
1254
1255         verbose = 1;
1256         if (debugonly) {
1257                 interfaces();
1258                 exit(0);
1259         }
1260
1261         for (;;) {
1262                 n = read(s, msg, sizeof(msg));
1263                 error = errno;
1264                 now = time(NULL);
1265                 if (n == -1) {
1266                         printf("\nsocket error %d on %s: %s\n",
1267                             error, ctime(&now), strerror(error));
1268                         continue;
1269                 }
1270                 printf("\ngot message of size %d on %s", n, ctime(&now));
1271                 print_rtmsg((struct rt_msghdr *)msg, n);
1272         }
1273 }
1274
1275 struct {
1276         struct  rt_msghdr m_rtm;
1277         char    m_space[512];
1278 } m_rtmsg;
1279
1280 static int
1281 rtmsg(int cmd, int flags)
1282 {
1283         static int seq;
1284         int rlen;
1285         char *cp = m_rtmsg.m_space;
1286         int l;
1287
1288 #define NEXTADDR(w, u) \
1289         if (rtm_addrs & (w)) {\
1290             l = RT_ROUNDUP(u.sa.sa_len); memmove(cp, &(u), l); cp += l;\
1291             if (verbose) sodump(&(u),"u");\
1292         }
1293
1294         errno = 0;
1295         memset(&m_rtmsg, 0, sizeof(m_rtmsg));
1296         if (cmd == 'a')
1297                 cmd = RTM_ADD;
1298         else if (cmd == 'c')
1299                 cmd = RTM_CHANGE;
1300         else if (cmd == 'g') {
1301                 cmd = RTM_GET;
1302                 if (so_ifp.sa.sa_family == 0) {
1303                         so_ifp.sa.sa_family = AF_LINK;
1304                         so_ifp.sa.sa_len = sizeof(struct sockaddr_dl);
1305                         rtm_addrs |= RTA_IFP;
1306                 }
1307         } else
1308                 cmd = RTM_DELETE;
1309 #define rtm m_rtmsg.m_rtm
1310         rtm.rtm_type = cmd;
1311         rtm.rtm_flags = flags;
1312         rtm.rtm_version = RTM_VERSION;
1313         rtm.rtm_seq = ++seq;
1314         rtm.rtm_addrs = rtm_addrs;
1315         rtm.rtm_rmx = rt_metrics;
1316         rtm.rtm_inits = rtm_inits;
1317
1318         if (rtm_addrs & RTA_NETMASK)
1319                 mask_addr();
1320         NEXTADDR(RTA_DST, so_dst);
1321         NEXTADDR(RTA_GATEWAY, so_gate);
1322         NEXTADDR(RTA_NETMASK, so_mask);
1323         NEXTADDR(RTA_GENMASK, so_genmask);
1324         NEXTADDR(RTA_IFP, so_ifp);
1325         NEXTADDR(RTA_IFA, so_ifa);
1326         NEXTADDR(RTA_MPLS1, so_mpls1);
1327         NEXTADDR(RTA_MPLS2, so_mpls2);
1328         NEXTADDR(RTA_MPLS3, so_mpls3);
1329         rtm.rtm_msglen = l = cp - (char *)&m_rtmsg;
1330         if (verbose)
1331                 print_rtmsg(&rtm, l);
1332         if (debugonly)
1333                 return(0);
1334         if ((rlen = write(s, (char *)&m_rtmsg, l)) < 0) {
1335                 warn("writing to routing socket");
1336                 return(-1);
1337         }
1338         if (cmd == RTM_GET) {
1339                 do {
1340                         l = read(s, (char *)&m_rtmsg, sizeof(m_rtmsg));
1341                 } while (l > 0 && (rtm.rtm_seq != seq || rtm.rtm_pid != pid));
1342                 if (l < 0)
1343                         warn("read from routing socket");
1344                 else
1345                         print_getmsg(&rtm, l);
1346         }
1347 #undef rtm
1348         return(0);
1349 }
1350
1351 static void
1352 mask_addr(void)
1353 {
1354         int olen = so_mask.sa.sa_len;
1355         char *cp1 = olen + (char *)&so_mask, *cp2;
1356
1357         for (so_mask.sa.sa_len = 0; cp1 > (char *)&so_mask; )
1358                 if (*--cp1 != 0) {
1359                         so_mask.sa.sa_len = 1 + cp1 - (char *)&so_mask;
1360                         break;
1361                 }
1362         if ((rtm_addrs & RTA_DST) == 0)
1363                 return;
1364         switch (so_dst.sa.sa_family) {
1365         case AF_INET:
1366 #ifdef INET6
1367         case AF_INET6:
1368 #endif
1369         case 0:
1370                 return;
1371         }
1372         cp1 = so_mask.sa.sa_len + 1 + (char *)&so_dst;
1373         cp2 = so_dst.sa.sa_len + 1 + (char *)&so_dst;
1374         while (cp2 > cp1)
1375                 *--cp2 = 0;
1376         cp2 = so_mask.sa.sa_len + 1 + (char *)&so_mask;
1377         while (cp1 > so_dst.sa.sa_data)
1378                 *--cp1 &= *--cp2;
1379 }
1380
1381 const char *msgtypes[] = {
1382         "",
1383         "RTM_ADD: Add Route",
1384         "RTM_DELETE: Delete Route",
1385         "RTM_CHANGE: Change Metrics or flags",
1386         "RTM_GET: Report Metrics",
1387         "RTM_LOSING: Kernel Suspects Partitioning",
1388         "RTM_REDIRECT: Told to use different route",
1389         "RTM_MISS: Lookup failed on this address",
1390         "RTM_LOCK: fix specified metrics",
1391         "0x9: unused",
1392         "0xa: unused",
1393         "RTM_RESOLVE: Route created by cloning",
1394         "RTM_NEWADDR: address being added to iface",
1395         "RTM_DELADDR: address being removed from iface",
1396         "RTM_IFINFO: iface status change",
1397         "RTM_NEWMADDR: new multicast group membership on iface",
1398         "RTM_DELMADDR: multicast group membership removed from iface",
1399         "RTM_IFANNOUNCE: interface arrival/departure",
1400         "RTM_IEEE80211: IEEE80211 wireless event",
1401         0,
1402 };
1403
1404 char metricnames[] =
1405 "\013iw\012iwmax\011msl\010rttvar\7rtt\6ssthresh\5sendpipe\4recvpipe\3expire"
1406 "\2hopcount\1mtu";
1407 char routeflags[] =
1408 "\1UP\2GATEWAY\3HOST\4REJECT\5DYNAMIC\6MODIFIED\7DONE\010MASK_PRESENT"
1409 "\011CLONING\012XRESOLVE\013LLINFO\014STATIC\015BLACKHOLE\016b016"
1410 "\017PROTO2\020PROTO1\021PRCLONING\022WASCLONED\023PROTO3\024CHAINDELETE"
1411 "\025PINNED\026LOCAL\027BROADCAST\030MULTICAST";
1412 char ifnetflags[] =
1413 "\1UP\2BROADCAST\3DEBUG\4LOOPBACK\5PTP\6b6\7RUNNING\010NOARP"
1414 "\011PPROMISC\012ALLMULTI\013OACTIVE\014SIMPLEX\015LINK0\016LINK1"
1415 "\017LINK2\020MULTICAST";
1416 char addrnames[] =
1417 "\1DST\2GATEWAY\3NETMASK\4GENMASK\5IFP\6IFA\7AUTHOR\010BRD"
1418 "\011MPLS1\012MPLS2\013MPLS3";
1419
1420 static void
1421 print_rtmsg(struct rt_msghdr *rtm, int msglen __unused)
1422 {
1423         struct if_msghdr *ifm;
1424         struct ifa_msghdr *ifam;
1425 #ifdef RTM_NEWMADDR
1426         struct ifma_msghdr *ifmam;
1427 #endif
1428         struct if_announcemsghdr *ifan;
1429         union {
1430                 struct ieee80211_join_event join;
1431                 struct ieee80211_leave_event leave;
1432                 struct ieee80211_replay_event replay;
1433                 struct ieee80211_michael_event michael;
1434         } ev;
1435         size_t evlen = 0;
1436
1437         if (verbose == 0)
1438                 return;
1439         if (rtm->rtm_version != RTM_VERSION) {
1440                 printf("routing message version %d not understood\n",
1441                     rtm->rtm_version);
1442                 return;
1443         }
1444         if (msgtypes[rtm->rtm_type] != NULL)
1445                 printf("%s: ", msgtypes[rtm->rtm_type]);
1446         else
1447                 printf("#%d: ", rtm->rtm_type);
1448         printf("len %d, ", rtm->rtm_msglen);
1449         switch (rtm->rtm_type) {
1450         case RTM_IFINFO:
1451                 ifm = (struct if_msghdr *)rtm;
1452                 printf("if# %d, flags:", ifm->ifm_index);
1453                 bprintf(stdout, ifm->ifm_flags, ifnetflags);
1454                 pmsg_addrs((char *)(ifm + 1), ifm->ifm_addrs);
1455                 break;
1456         case RTM_NEWADDR:
1457         case RTM_DELADDR:
1458                 ifam = (struct ifa_msghdr *)rtm;
1459                 printf("metric %d, flags:", ifam->ifam_metric);
1460                 bprintf(stdout, ifam->ifam_flags, routeflags);
1461                 pmsg_addrs((char *)(ifam + 1), ifam->ifam_addrs);
1462                 break;
1463 #ifdef RTM_NEWMADDR
1464         case RTM_NEWMADDR:
1465         case RTM_DELMADDR:
1466                 ifmam = (struct ifma_msghdr *)rtm;
1467                 pmsg_addrs((char *)(ifmam + 1), ifmam->ifmam_addrs);
1468                 break;
1469 #endif
1470         case RTM_IEEE80211:
1471                 ifan = (struct if_announcemsghdr *)rtm;
1472                 (void)printf("if# %d, what: ", ifan->ifan_index);
1473                 switch (ifan->ifan_what) {
1474                 case RTM_IEEE80211_ASSOC:
1475                         printf("associate");
1476                         break;
1477                 case RTM_IEEE80211_REASSOC:
1478                         printf("re-associate");
1479                         break;
1480                 case RTM_IEEE80211_DISASSOC:
1481                         printf("disassociate");
1482                         break;
1483                 case RTM_IEEE80211_SCAN:
1484                         printf("scan complete");
1485                         break;
1486                 case RTM_IEEE80211_JOIN:
1487                         evlen = sizeof(ev.join);
1488                         printf("join");
1489                         break;
1490                 case RTM_IEEE80211_LEAVE:
1491                         evlen = sizeof(ev.leave);
1492                         printf("leave");
1493                         break;
1494                 case RTM_IEEE80211_MICHAEL:
1495                         evlen = sizeof(ev.michael);
1496                         printf("michael");
1497                         break;
1498                 case RTM_IEEE80211_REPLAY:
1499                         evlen = sizeof(ev.replay);
1500                         printf("replay");
1501                         break;
1502                 default:
1503                         evlen = 0;
1504                         printf("#%d", ifan->ifan_what);
1505                         break;
1506                 }
1507                 if (sizeof(*ifan) + evlen > ifan->ifan_msglen) {
1508                         printf(" (truncated)\n");
1509                         break;
1510                 }
1511                 (void)memcpy(&ev, (ifan + 1), evlen);
1512                 switch (ifan->ifan_what) {
1513                 case RTM_IEEE80211_JOIN:
1514                 case RTM_IEEE80211_LEAVE:
1515                         printf(" mac %" PRIETHER,
1516                             PRIETHER_ARGS(ev.join.iev_addr));
1517                         break;
1518                 case RTM_IEEE80211_REPLAY:
1519                 case RTM_IEEE80211_MICHAEL:
1520                         printf(" src %" PRIETHER " dst %" PRIETHER
1521                                " cipher %" PRIu8 " keyix %" PRIu8,
1522                                PRIETHER_ARGS(ev.replay.iev_src),
1523                                PRIETHER_ARGS(ev.replay.iev_dst),
1524                                ev.replay.iev_cipher,
1525                                ev.replay.iev_keyix);
1526                         if (ifan->ifan_what == RTM_IEEE80211_REPLAY) {
1527                                 printf(" key rsc %#" PRIx64
1528                                        " frame rsc %#" PRIx64,
1529                                        ev.replay.iev_keyrsc, ev.replay.iev_rsc);
1530                         }
1531                         break;
1532                 default:
1533                         break;
1534                 }
1535                 printf("\n");
1536                 break;
1537         case RTM_IFANNOUNCE:
1538                 ifan = (struct if_announcemsghdr *)rtm;
1539                 printf("if# %d, what: ", ifan->ifan_index);
1540                 switch (ifan->ifan_what) {
1541                 case IFAN_ARRIVAL:
1542                         printf("arrival");
1543                         break;
1544                 case IFAN_DEPARTURE:
1545                         printf("departure");
1546                         break;
1547                 default:
1548                         printf("#%d", ifan->ifan_what);
1549                         break;
1550                 }
1551                 printf("\n");
1552                 break;
1553
1554         default:
1555                 printf("pid: %ld, seq %d, errno %d, flags:",
1556                         (long)rtm->rtm_pid, rtm->rtm_seq, rtm->rtm_errno);
1557                 bprintf(stdout, rtm->rtm_flags, routeflags);
1558                 pmsg_common(rtm);
1559         }
1560 }
1561
1562 static void
1563 print_getmsg(struct rt_msghdr *rtm, int msglen)
1564 {
1565         struct sockaddr *dst = NULL, *gate = NULL, *mask = NULL;
1566         struct sockaddr_dl *ifp = NULL;
1567         struct sockaddr *sa;
1568         char *cp;
1569         int i;
1570
1571         printf("   route to: %s\n", routename(&so_dst.sa));
1572         if (rtm->rtm_version != RTM_VERSION) {
1573                 warnx("routing message version %d not understood",
1574                      rtm->rtm_version);
1575                 return;
1576         }
1577         if (rtm->rtm_msglen > msglen) {
1578                 warnx("message length mismatch, in packet %d, returned %d",
1579                       rtm->rtm_msglen, msglen);
1580         }
1581         if (rtm->rtm_errno != 0)  {
1582                 errno = rtm->rtm_errno;
1583                 warn("message indicates error %d", errno);
1584                 return;
1585         }
1586         cp = ((char *)(rtm + 1));
1587         if (rtm->rtm_addrs)
1588                 for (i = 1; i != 0; i <<= 1)
1589                         if (i & rtm->rtm_addrs) {
1590                                 sa = (struct sockaddr *)cp;
1591                                 switch (i) {
1592                                 case RTA_DST:
1593                                         dst = sa;
1594                                         break;
1595                                 case RTA_GATEWAY:
1596                                         gate = sa;
1597                                         break;
1598                                 case RTA_NETMASK:
1599                                         mask = sa;
1600                                         break;
1601                                 case RTA_IFP:
1602                                         if (sa->sa_family == AF_LINK &&
1603                                            ((struct sockaddr_dl *)sa)->sdl_nlen)
1604                                                 ifp = (struct sockaddr_dl *)sa;
1605                                         break;
1606                                 }
1607                                 RT_ADVANCE(cp, sa);
1608                         }
1609         if (dst != NULL && mask != NULL)
1610                 mask->sa_family = dst->sa_family;       /* XXX */
1611         if (dst != NULL)
1612                 printf("destination: %s\n", routename(dst));
1613         if (mask != NULL) {
1614                 int savenflag = nflag;
1615
1616                 nflag = 1;
1617                 printf("       mask: %s\n", routename(mask));
1618                 nflag = savenflag;
1619         }
1620         if (gate != NULL && rtm->rtm_flags & RTF_GATEWAY)
1621                 printf("    gateway: %s\n", routename(gate));
1622         if (ifp != NULL)
1623                 printf("  interface: %.*s\n",
1624                     ifp->sdl_nlen, ifp->sdl_data);
1625         printf("      flags: ");
1626         bprintf(stdout, rtm->rtm_flags, routeflags);
1627
1628 #define lock(f) ((rtm->rtm_rmx.rmx_locks & __CONCAT(RTV_,f)) ? 'L' : ' ')
1629 #define msec(u) (((u) + 500) / 1000)            /* usec to msec */
1630
1631         printf("\n%s\n", "\
1632  recvpipe  sendpipe  ssthresh  rtt,msec    rttvar  hopcount      mtu     expire  msl,msec iwmax iw");
1633         printf("%8ld%c ", rtm->rtm_rmx.rmx_recvpipe, lock(RPIPE));
1634         printf("%8ld%c ", rtm->rtm_rmx.rmx_sendpipe, lock(SPIPE));
1635         printf("%8ld%c ", rtm->rtm_rmx.rmx_ssthresh, lock(SSTHRESH));
1636         printf("%8ld%c ", msec(rtm->rtm_rmx.rmx_rtt), lock(RTT));
1637         printf("%8ld%c ", msec(rtm->rtm_rmx.rmx_rttvar), lock(RTTVAR));
1638         printf("%8ld%c ", rtm->rtm_rmx.rmx_hopcount, lock(HOPCOUNT));
1639         printf("%8ld%c ", rtm->rtm_rmx.rmx_mtu, lock(MTU));
1640         if (rtm->rtm_rmx.rmx_expire != 0) {
1641                 struct timespec sp;
1642                 clock_gettime(CLOCK_MONOTONIC, &sp);
1643                 rtm->rtm_rmx.rmx_expire -= sp.tv_sec;
1644         }
1645         printf("%8ld%c ", rtm->rtm_rmx.rmx_expire, lock(EXPIRE));
1646         printf("%8ld ", rtm->rtm_rmx.rmx_msl);
1647         printf("%5ld ", rtm->rtm_rmx.rmx_iwmaxsegs);
1648         printf("%3ld\n", rtm->rtm_rmx.rmx_iwcapsegs);
1649 #undef lock
1650 #undef msec
1651 #define RTA_IGN (RTA_DST|RTA_GATEWAY|RTA_NETMASK|RTA_IFP|RTA_IFA|RTA_BRD)
1652         if (verbose)
1653                 pmsg_common(rtm);
1654         else if (rtm->rtm_addrs &~ RTA_IGN) {
1655                 printf("sockaddrs: ");
1656                 bprintf(stdout, rtm->rtm_addrs, addrnames);
1657                 putchar('\n');
1658         }
1659 #undef  RTA_IGN
1660 }
1661
1662 static void
1663 pmsg_common(struct rt_msghdr *rtm)
1664 {
1665         printf("\nlocks: ");
1666         bprintf(stdout, rtm->rtm_rmx.rmx_locks, metricnames);
1667         printf(" inits: ");
1668         bprintf(stdout, rtm->rtm_inits, metricnames);
1669         pmsg_addrs(((char *)(rtm + 1)), rtm->rtm_addrs);
1670 }
1671
1672 static void
1673 pmsg_addrs(char *cp, int addrs)
1674 {
1675         struct sockaddr *sa;
1676         int i;
1677
1678         if (addrs == 0) {
1679                 putchar('\n');
1680                 return;
1681         }
1682         printf("\nsockaddrs: ");
1683         bprintf(stdout, addrs, addrnames);
1684         putchar('\n');
1685         for (i = 1; i != 0; i <<= 1)
1686                 if (i & addrs) {
1687                         sa = (struct sockaddr *)cp;
1688                         printf(" %s", routename(sa));
1689                         RT_ADVANCE(cp, sa);
1690                 }
1691         putchar('\n');
1692         fflush(stdout);
1693 }
1694
1695 static void
1696 bprintf(FILE *fp, int b, u_char *str)
1697 {
1698         int i;
1699         int gotsome = 0;
1700
1701         if (b == 0)
1702                 return;
1703         while ((i = *str++) != 0) {
1704                 if (b & (1 << (i-1))) {
1705                         if (!gotsome)
1706                                 i = '<';
1707                         else
1708                                 i = ',';
1709                         putc(i, fp);
1710                         gotsome = 1;
1711                         for (; (i = *str) > 32; str++)
1712                                 putc(i, fp);
1713                 } else
1714                         while (*str > 32)
1715                                 str++;
1716         }
1717         if (gotsome)
1718                 putc('>', fp);
1719 }
1720
1721 int
1722 keyword(const char *cp)
1723 {
1724         const struct keytab *kt = keywords;
1725
1726         while (kt->kt_cp != NULL && strcmp(kt->kt_cp, cp) != 0)
1727                 kt++;
1728         return(kt->kt_i);
1729 }
1730
1731 static void
1732 sodump(sup su, const char *which)
1733 {
1734         switch (su->sa.sa_family) {
1735         case AF_LINK:
1736                 printf("%s: link %s; ",
1737                     which, link_ntoa(&su->sdl));
1738                 break;
1739         case AF_INET:
1740                 printf("%s: inet %s; ",
1741                     which, inet_ntoa(su->sin.sin_addr));
1742                 break;
1743         }
1744         fflush(stdout);
1745 }
1746
1747 /* States*/
1748 #define VIRGIN  0
1749 #define GOTONE  1
1750 #define GOTTWO  2
1751 /* Inputs */
1752 #define DIGIT   (4*0)
1753 #define END     (4*1)
1754 #define DELIM   (4*2)
1755
1756 static void
1757 sockaddr(const char *addr, struct sockaddr *sa)
1758 {
1759         char *cp = (char *)sa;
1760         int size = sa->sa_len;
1761         char *cplim = cp + size;
1762         int byte = 0, state = VIRGIN, new = 0 /* foil gcc */;
1763
1764         memset(cp, 0, size);
1765         cp++;
1766         do {
1767                 if ((*addr >= '0') && (*addr <= '9')) {
1768                         new = *addr - '0';
1769                 } else if ((*addr >= 'a') && (*addr <= 'f')) {
1770                         new = *addr - 'a' + 10;
1771                 } else if ((*addr >= 'A') && (*addr <= 'F')) {
1772                         new = *addr - 'A' + 10;
1773                 } else if (*addr == '\0')
1774                         state |= END;
1775                 else
1776                         state |= DELIM;
1777                 addr++;
1778                 switch (state /* | INPUT */) {
1779                 case GOTTWO | DIGIT:
1780                         *cp++ = byte; /*FALLTHROUGH*/
1781                 case VIRGIN | DIGIT:
1782                         state = GOTONE; byte = new; continue;
1783                 case GOTONE | DIGIT:
1784                         state = GOTTWO; byte = new + (byte << 4); continue;
1785                 default: /* | DELIM */
1786                         state = VIRGIN; *cp++ = byte; byte = 0; continue;
1787                 case GOTONE | END:
1788                 case GOTTWO | END:
1789                         *cp++ = byte; /* FALLTHROUGH */
1790                 case VIRGIN | END:
1791                         break;
1792                 }
1793                 break;
1794         } while (cp < cplim);
1795         sa->sa_len = cp - (char *)sa;
1796 }