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