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