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