xref: /titanic_41/usr/src/cmd/cmd-inet/usr.sbin/route.c (revision 31e37bb439502e3f7c4c0a9a77d655ea5d56887a)
1 /*
2  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
3  * Use is subject to license terms.
4  */
5 
6 /* Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
7 /* All Rights Reserved	*/
8 
9 /* Copyright (c) 1990  Mentat Inc. */
10 
11 /*
12  *
13  * Copyright (c) 1983, 1989, 1991, 1993
14  *	The Regents of the University of California.  All rights reserved.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  * 3. All advertising materials mentioning features or use of this software
25  *    must display the following acknowledgement:
26  *	This product includes software developed by the University of
27  *	California, Berkeley and its contributors.
28  * 4. Neither the name of the University nor the names of its contributors
29  *    may be used to endorse or promote products derived from this software
30  *    without specific prior written permission.
31  *
32  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
33  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
34  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
36  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
37  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
38  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
39  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
40  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
41  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
42  * SUCH DAMAGE.
43  *
44  *	@(#)route.c	8.6 (Berkeley) 4/28/95
45  *	@(#)linkaddr.c	8.1 (Berkeley) 6/4/93
46  */
47 
48 #pragma ident	"%Z%%M%	%I%	%E% SMI"
49 
50 #include <sys/param.h>
51 #include <sys/file.h>
52 #include <sys/socket.h>
53 #include <sys/ioctl.h>
54 #include <sys/stat.h>
55 #include <sys/stream.h>
56 #include <sys/sysmacros.h>
57 #include <sys/tihdr.h>
58 #include <sys/types.h>
59 #include <sys/ccompile.h>
60 
61 #include <net/if.h>
62 #include <net/route.h>
63 #include <net/if_dl.h>
64 #include <netinet/in.h>
65 #include <arpa/inet.h>
66 #include <netdb.h>
67 #include <inet/mib2.h>
68 #include <inet/ip.h>
69 
70 #include <limits.h>
71 #include <locale.h>
72 
73 #include <errno.h>
74 #include <unistd.h>
75 #include <stdio.h>
76 #include <stdlib.h>
77 #include <stddef.h>
78 #include <string.h>
79 #include <stropts.h>
80 #include <fcntl.h>
81 #include <stdarg.h>
82 #include <assert.h>
83 #include <strings.h>
84 
85 #include <libtsnet.h>
86 #include <tsol/label.h>
87 
88 static struct keytab {
89 	char	*kt_cp;
90 	int	kt_i;
91 } keywords[] = {
92 #define	K_ADD		1
93 	{"add",		K_ADD},
94 #define	K_BLACKHOLE	2
95 	{"blackhole",	K_BLACKHOLE},
96 #define	K_CHANGE	3
97 	{"change",	K_CHANGE},
98 #define	K_CLONING	4
99 	{"cloning",	K_CLONING},
100 #define	K_DELETE	5
101 	{"delete",	K_DELETE},
102 #define	K_DST		6
103 	{"dst",		K_DST},
104 #define	K_EXPIRE	7
105 	{"expire",	K_EXPIRE},
106 #define	K_FLUSH		8
107 	{"flush",	K_FLUSH},
108 #define	K_GATEWAY	9
109 	{"gateway",	K_GATEWAY},
110 #define	K_GET		11
111 	{"get",		K_GET},
112 #define	K_HOPCOUNT	12
113 	{"hopcount",	K_HOPCOUNT},
114 #define	K_HOST		13
115 	{"host",	K_HOST},
116 #define	K_IFA		14
117 	{"ifa",		K_IFA},
118 #define	K_IFACE		15
119 	{"iface",	K_IFACE},
120 #define	K_IFP		16
121 	{"ifp",		K_IFP},
122 #define	K_INET		17
123 	{"inet",	K_INET},
124 #define	K_INET6		18
125 	{"inet6",	K_INET6},
126 #define	K_INTERFACE	19
127 	{"interface",	K_INTERFACE},
128 #define	K_LINK		20
129 	{"link",	K_LINK},
130 #define	K_LOCK		21
131 	{"lock",	K_LOCK},
132 #define	K_LOCKREST	22
133 	{"lockrest",	K_LOCKREST},
134 #define	K_MASK		23
135 	{"mask",	K_MASK},
136 #define	K_MONITOR	24
137 	{"monitor",	K_MONITOR},
138 #define	K_MTU		25
139 	{"mtu",		K_MTU},
140 #define	K_NET		26
141 	{"net",		K_NET},
142 #define	K_NETMASK	27
143 	{"netmask",	K_NETMASK},
144 #define	K_NOSTATIC	28
145 	{"nostatic",	K_NOSTATIC},
146 #define	K_PRIVATE	29
147 	{"private",	K_PRIVATE},
148 #define	K_PROTO1	30
149 	{"proto1",	K_PROTO1},
150 #define	K_PROTO2	31
151 	{"proto2",	K_PROTO2},
152 #define	K_RECVPIPE	32
153 	{"recvpipe",	K_RECVPIPE},
154 #define	K_REJECT	33
155 	{"reject",	K_REJECT},
156 #define	K_RTT		34
157 	{"rtt",		K_RTT},
158 #define	K_RTTVAR	35
159 	{"rttvar",	K_RTTVAR},
160 #define	K_SA		36
161 	{"sa",		K_SA},
162 #define	K_SENDPIPE	37
163 	{"sendpipe",	K_SENDPIPE},
164 #define	K_SSTHRESH	38
165 	{"ssthresh",	K_SSTHRESH},
166 #define	K_STATIC	39
167 	{"static",	K_STATIC},
168 #define	K_XRESOLVE	40
169 	{"xresolve",	K_XRESOLVE},
170 #define	K_MULTIRT	41
171 	{"multirt",	K_MULTIRT},
172 #define	K_SETSRC	42
173 	{"setsrc",	K_SETSRC},
174 #define	K_SHOW		43
175 	{"show",	K_SHOW},
176 #define	K_SECATTR	43
177 	{"secattr",	K_SECATTR},
178 	{0, 0}
179 };
180 
181 /*
182  * Size of buffers used to hold command lines from the saved route file as
183  * well as error strings.
184  */
185 #define	BUF_SIZE 2048
186 
187 typedef union sockunion {
188 	struct	sockaddr sa;
189 	struct	sockaddr_in sin;
190 	struct	sockaddr_dl sdl;
191 	struct	sockaddr_in6 sin6;
192 } su_t;
193 
194 /*
195  * This structure represents the digested information from parsing arguments
196  * to route add, change, delete, and get.
197  *
198  */
199 typedef struct rtcmd_irep {
200 	int ri_cmd;
201 	int ri_flags;
202 	int ri_af;
203 	ulong_t	ri_inits;
204 	struct rt_metrics ri_metrics;
205 	int ri_addrs;
206 	su_t ri_dst;
207 	char *ri_dest_str;
208 	su_t ri_src;
209 	su_t ri_gate;
210 	struct hostent *ri_gate_hp;
211 	char *ri_gate_str;
212 	su_t ri_mask;
213 	su_t ri_ifa;
214 	su_t ri_ifp;
215 	char *ri_ifp_str;
216 	int ri_rtsa_cnt;	/* number of gateway security attributes */
217 	struct rtsa_s ri_rtsa;	/* enough space for one attribute */
218 } rtcmd_irep_t;
219 
220 typedef struct	mib_item_s {
221 	struct mib_item_s *next_item;
222 	long group;
223 	long mib_id;
224 	long length;
225 	intmax_t *valp;
226 } mib_item_t;
227 
228 typedef enum {
229 	ADDR_TYPE_ANY,
230 	ADDR_TYPE_HOST,
231 	ADDR_TYPE_NET
232 } addr_type_t;
233 
234 typedef enum {
235 	SEARCH_MODE_NULL,
236 	SEARCH_MODE_PRINT,
237 	SEARCH_MODE_DEL
238 } search_mode_t;
239 
240 static boolean_t	args_to_rtcmd(rtcmd_irep_t *rcip, char **argv,
241     char *cmd_string);
242 static void		bprintf(FILE *fp, int b, char *s);
243 static boolean_t	compare_rtcmd(rtcmd_irep_t *srch_rt,
244     rtcmd_irep_t *file_rt);
245 static void		delRouteEntry(mib2_ipRouteEntry_t *rp,
246     mib2_ipv6RouteEntry_t *rp6, int seqno);
247 static void		del_rtcmd_irep(rtcmd_irep_t *rcip);
248 static void		flushroutes(int argc, char *argv[]);
249 static boolean_t	getaddr(rtcmd_irep_t *rcip, int which, char *s,
250     addr_type_t atype);
251 static boolean_t	in6_getaddr(char *s, struct sockaddr_in6 *sin6,
252     int *plenp, struct hostent **hpp);
253 static boolean_t	in_getaddr(char *s, struct sockaddr_in *sin,
254     int *plenp, int which, struct hostent **hpp, addr_type_t atype,
255     rtcmd_irep_t *rcip);
256 static int		in_getprefixlen(char *addr, int max_plen);
257 static boolean_t	in_prefixlentomask(int prefixlen, int maxlen,
258     uchar_t *mask);
259 static void		inet_makenetandmask(rtcmd_irep_t *rcip, in_addr_t net,
260     struct sockaddr_in *sin);
261 static in_addr_t	inet_makesubnetmask(in_addr_t addr, in_addr_t mask);
262 static int		keyword(const char *cp);
263 static void		link_addr(const char *addr, struct sockaddr_dl *sdl);
264 static char		*link_ntoa(const struct sockaddr_dl *sdl);
265 static mib_item_t	*mibget(int sd);
266 static char		*netname(struct sockaddr *sa);
267 static int		newroute(char **argv);
268 static rtcmd_irep_t	*new_rtcmd_irep(void);
269 static void		pmsg_addrs(const char *cp, size_t len, uint_t addrs);
270 static void		pmsg_common(const struct rt_msghdr *rtm, size_t len);
271 static void		print_getmsg(rtcmd_irep_t *req_rt,
272     struct rt_msghdr *rtm, int msglen);
273 static void		print_rtcmd_short(FILE *to, rtcmd_irep_t *rcip,
274     boolean_t gw_good, boolean_t to_saved);
275 static void		print_rtmsg(struct rt_msghdr *rtm, int msglen);
276 static void		quit(char *s, int err) __NORETURN;
277 static char		*routename(const struct sockaddr *sa);
278 static void		rtmonitor(int argc, char *argv[]);
279 static int		rtmsg(rtcmd_irep_t *rcip);
280 static int		salen(const struct sockaddr *sa);
281 static void		save_route(int argc, char **argv, int do_flush);
282 static void		save_string(char **dst, char *src);
283 static int		search_rtfile(FILE *fp, FILE *temp_fp, rtcmd_irep_t *rt,
284     search_mode_t mode);
285 static void		set_metric(rtcmd_irep_t *rcip, char *value, int key,
286     boolean_t lock);
287 static int		show_saved_routes(int argc);
288 static void		sockaddr(char *addr, struct sockaddr *sa);
289 static void		sodump(su_t *su, char *which);
290 static void		syntax_arg_missing(char *keyword);
291 static void		syntax_bad_keyword(char *keyword);
292 static void		syntax_error(char *err, ...);
293 static void		usage(char *cp);
294 static void		write_to_rtfile(FILE *fp, int argc, char **argv);
295 static void		pmsg_secattr(const char *, size_t, const char *);
296 
297 static pid_t		pid;
298 static int		s;
299 static boolean_t	nflag;
300 static int		af = AF_INET;
301 static boolean_t	qflag, tflag;
302 static boolean_t	verbose;
303 static boolean_t	debugonly;
304 static boolean_t	fflag;
305 static boolean_t	update_table;
306 static boolean_t	perm_flag;
307 static boolean_t	early_v6_keyword;
308 static char		perm_file_sfx[] = "/etc/inet/static_routes";
309 static char		*perm_file;
310 static char		temp_file_sfx[] = "/etc/inet/static_routes.tmp";
311 static char		*temp_file;
312 static struct in6_addr	in6_host_mask = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
313     0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
314 /*
315  * WARNING:
316  * This next variable indicates whether certain functions exit when an error
317  * is detected in the user input.  Currently, exit_on_error is only set false
318  * in search_rtfile(), when argument are being parsed.  Only those functions
319  * used by search_rtfile() to parse its arguments are designed to work in
320  * both modes.  Take particular care in setting this false to ensure that any
321  * functions you call that might act on this flag properly return errors when
322  * exit_on_error is false.
323  */
324 static int		exit_on_error = B_TRUE;
325 
326 static struct {
327 	struct	rt_msghdr m_rtm;
328 	char	m_space[BUF_SIZE];
329 } m_rtmsg;
330 
331 /*
332  * Sizes of data structures extracted from the base mib.
333  * This allows the size of the tables entries to grow while preserving
334  * binary compatibility.
335  */
336 static int ipRouteEntrySize;
337 static int ipv6RouteEntrySize;
338 
339 #define	ROUNDUP_LONG(a) \
340 	((a) > 0 ? (1 + (((a) - 1) | (sizeof (long) - 1))) : sizeof (long))
341 #define	ADVANCE(x, n) ((x) += ROUNDUP_LONG(salen(n)))
342 #define	C(x)	((x) & 0xff)
343 
344 /*
345  * return values from in_getprefixlen()
346  */
347 #define	BAD_ADDR	-1	/* prefix is invalid */
348 #define	NO_PREFIX	-2	/* no prefix was found */
349 
350 void
351 usage(char *cp)
352 {
353 	if (cp != NULL) {
354 		(void) fprintf(stderr, gettext("route: botched keyword: %s\n"),
355 		    cp);
356 	}
357 	(void) fprintf(stderr, gettext("usage: route [ -fnpqv ] "
358 	    "[ -R <root-dir> ] cmd [[ -<qualifers> ] args ]\n"));
359 	exit(1);
360 	/* NOTREACHED */
361 }
362 
363 /*PRINTFLIKE1*/
364 void
365 syntax_error(char *err, ...)
366 {
367 	va_list args;
368 
369 	if (exit_on_error) {
370 		va_start(args, err);
371 		(void) vfprintf(stderr, err, args);
372 		va_end(args);
373 		exit(1);
374 	}
375 	/* NOTREACHED */
376 }
377 
378 void
379 syntax_bad_keyword(char *keyword)
380 {
381 	syntax_error(gettext("route: botched keyword: %s\n"), keyword);
382 }
383 
384 void
385 syntax_arg_missing(char *keyword)
386 {
387 	syntax_error(gettext("route: argument required following keyword %s\n"),
388 	    keyword);
389 }
390 
391 void
392 quit(char *s, int sverrno)
393 {
394 	(void) fprintf(stderr, "route: ");
395 	if (s != NULL)
396 		(void) fprintf(stderr, "%s: ", s);
397 	(void) fprintf(stderr, "%s\n", strerror(sverrno));
398 	exit(sverrno);
399 	/* NOTREACHED */
400 }
401 
402 int
403 main(int argc, char **argv)
404 {
405 	extern int optind;
406 	extern char *optarg;
407 	int ch;
408 	int rval;
409 	size_t size;
410 	const char *root_dir = NULL;
411 
412 	(void) setlocale(LC_ALL, "");
413 
414 #if !defined(TEXT_DOMAIN)
415 #define	TEXT_DOMAIN "SYS_TEST"
416 #endif
417 	(void) textdomain(TEXT_DOMAIN);
418 
419 	if (argc < 2)
420 		usage(NULL);
421 
422 	while ((ch = getopt(argc, argv, "R:nqdtvfp")) != EOF) {
423 		switch (ch) {
424 		case 'n':
425 			nflag = B_TRUE;
426 			break;
427 		case 'q':
428 			qflag = B_TRUE;
429 			break;
430 		case 'v':
431 			verbose = B_TRUE;
432 			break;
433 		case 't':
434 			tflag = B_TRUE;
435 			break;
436 		case 'd':
437 			debugonly = B_TRUE;
438 			break;
439 		case 'f':
440 			fflag = B_TRUE;
441 			break;
442 		case 'p':
443 			perm_flag = B_TRUE;
444 			break;
445 		case 'R':
446 			root_dir = optarg;
447 			break;
448 		case '?':
449 		default:
450 			usage(NULL);
451 			/* NOTREACHED */
452 		}
453 	}
454 	argc -= optind;
455 	argv += optind;
456 
457 	pid = getpid();
458 	if (tflag)
459 		s = open("/dev/null", O_WRONLY);
460 	else
461 		s = socket(PF_ROUTE, SOCK_RAW, 0);
462 	if (s < 0)
463 		quit("socket", errno);
464 
465 	/*
466 	 * Handle the -p and -R flags.  The -R flag only applies
467 	 * when the -p flag is set.
468 	 */
469 	if (root_dir == NULL) {
470 		perm_file = perm_file_sfx;
471 		temp_file = temp_file_sfx;
472 	} else {
473 		size = strlen(root_dir) + sizeof (perm_file_sfx);
474 		perm_file = malloc(size);
475 		if (perm_file == NULL)
476 			quit("malloc", errno);
477 		(void) snprintf(perm_file, size, "%s%s", root_dir,
478 		    perm_file_sfx);
479 		size = strlen(root_dir) + sizeof (temp_file_sfx);
480 		temp_file = malloc(size);
481 		if (temp_file == NULL)
482 			quit("malloc", errno);
483 		(void) snprintf(temp_file, size, "%s%s", root_dir,
484 		    temp_file_sfx);
485 	}
486 	/*
487 	 * Whether or not to act on the routing table.  The only time the
488 	 * routing table is not modified is when both -p and -R are present.
489 	 */
490 	update_table = (!perm_flag || root_dir == NULL);
491 	if (tflag)
492 		perm_flag = 0;
493 
494 	if (fflag) {
495 		/*
496 		 * Accept an address family keyword after the -f.  Since the
497 		 * default address family is AF_INET, reassign af only for the
498 		 * other valid address families.
499 		 */
500 		if (*argv != NULL) {
501 			switch (keyword(*argv)) {
502 			case K_INET6:
503 				af = AF_INET6;
504 				early_v6_keyword = B_TRUE;
505 				/* fallthrough */
506 			case K_INET:
507 				/* Skip over the address family parameter. */
508 				argc--;
509 				argv++;
510 				break;
511 			}
512 		}
513 		flushroutes(0, NULL);
514 	}
515 
516 	if (*argv != NULL) {
517 		switch (keyword(*argv)) {
518 		case K_GET:
519 		case K_CHANGE:
520 		case K_ADD:
521 		case K_DELETE:
522 			rval = 0;
523 			if (update_table) {
524 				rval = newroute(argv);
525 			}
526 			if (perm_flag && (rval == 0 || rval == EEXIST ||
527 			    rval == ESRCH)) {
528 				save_route(argc, argv, B_FALSE);
529 				return (0);
530 			}
531 			return (rval);
532 		case K_SHOW:
533 			if (perm_flag) {
534 				return (show_saved_routes(argc));
535 			} else {
536 				syntax_error(gettext(
537 				    "route: show command requires -p\n"));
538 			}
539 			/* NOTREACHED */
540 		case K_MONITOR:
541 			rtmonitor(argc, argv);
542 			/* NOTREACHED */
543 
544 		case K_FLUSH:
545 			flushroutes(argc, argv);
546 			return (0);
547 		}
548 	}
549 	if (!fflag)
550 		usage(*argv);
551 	return (0);
552 }
553 
554 /*
555  * Purge all entries in the routing tables not
556  * associated with network interfaces.
557  */
558 void
559 flushroutes(int argc, char *argv[])
560 {
561 	int seqno;
562 	int sd;	/* mib stream */
563 	mib_item_t	*item;
564 	mib2_ipRouteEntry_t *rp;
565 	mib2_ipv6RouteEntry_t *rp6;
566 	int oerrno;
567 	int off = 0;
568 	int on = 1;
569 
570 	if (argc > 1) {
571 		argv++;
572 		if (argc == 2 && **argv == '-') {
573 			/*
574 			 * The address family (preceded by a dash) may be used
575 			 * to flush the routes of that particular family.
576 			 */
577 			switch (keyword(*argv + 1)) {
578 			case K_INET:
579 				af = AF_INET;
580 				break;
581 			case K_LINK:
582 				af = AF_LINK;
583 				break;
584 			case K_INET6:
585 				af = AF_INET6;
586 				break;
587 			default:
588 				usage(*argv);
589 				/* NOTREACHED */
590 			}
591 		} else {
592 			usage(*argv);
593 		}
594 	}
595 	if (perm_flag) {
596 		/* This flushes the persistent route file */
597 		save_route(0, NULL, B_TRUE);
598 	}
599 	if (!update_table) {
600 		return;
601 	}
602 
603 	if (setsockopt(s, SOL_SOCKET, SO_USELOOPBACK, (char *)&off,
604 	    sizeof (off)) < 0)
605 		quit("setsockopt", errno);
606 
607 	sd = open("/dev/ip", O_RDWR);
608 	oerrno = errno;
609 	if (sd < 0) {
610 		switch (errno) {
611 		case EACCES:
612 			(void) fprintf(stderr,
613 			    gettext("route: flush: insufficient privileges\n"));
614 			exit(oerrno);
615 			/* NOTREACHED */
616 		default:
617 			quit(gettext("can't open mib stream"), oerrno);
618 			/* NOTREACHED */
619 		}
620 	}
621 	if ((item = mibget(sd)) == NULL)
622 		quit("mibget", errno);
623 	if (verbose) {
624 		(void) printf("Examining routing table from "
625 		    "T_SVR4_OPTMGMT_REQ\n");
626 	}
627 	seqno = 0;		/* ??? */
628 	switch (af) {
629 	case AF_INET:
630 		/* Extract ipRouteEntrySize */
631 		for (; item != NULL; item = item->next_item) {
632 			if (item->mib_id != 0)
633 				continue;
634 			if (item->group == MIB2_IP) {
635 				ipRouteEntrySize =
636 				    ((mib2_ip_t *)item->valp)->ipRouteEntrySize;
637 				assert(IS_P2ALIGNED(ipRouteEntrySize,
638 				    sizeof (mib2_ipRouteEntry_t *)));
639 				break;
640 			}
641 		}
642 		if (ipRouteEntrySize == 0) {
643 			(void) fprintf(stderr,
644 			    gettext("ipRouteEntrySize can't be determined.\n"));
645 			exit(1);
646 		}
647 		for (; item != NULL; item = item->next_item) {
648 			/*
649 			 * skip all the other trash that comes up the mib stream
650 			 */
651 			if (item->group != MIB2_IP ||
652 			    item->mib_id != MIB2_IP_ROUTE)
653 				continue;
654 			for (rp = (mib2_ipRouteEntry_t *)item->valp;
655 			    (char *)rp < (char *)item->valp + item->length;
656 			    /* LINTED */
657 			    rp = (mib2_ipRouteEntry_t *)
658 				((char *)rp + ipRouteEntrySize)) {
659 				delRouteEntry(rp, NULL, seqno);
660 				seqno++;
661 			}
662 			break;
663 		}
664 		break;
665 	case AF_INET6:
666 		/* Extract ipv6RouteEntrySize */
667 		for (; item != NULL; item = item->next_item) {
668 			if (item->mib_id != 0)
669 				continue;
670 			if (item->group == MIB2_IP6) {
671 				ipv6RouteEntrySize =
672 				    ((mib2_ipv6IfStatsEntry_t *)item->valp)->
673 					ipv6RouteEntrySize;
674 				assert(IS_P2ALIGNED(ipv6RouteEntrySize,
675 				    sizeof (mib2_ipv6RouteEntry_t *)));
676 				break;
677 			}
678 		}
679 		if (ipv6RouteEntrySize == 0) {
680 			(void) fprintf(stderr, gettext(
681 			    "ipv6RouteEntrySize cannot be determined.\n"));
682 			exit(1);
683 		}
684 		for (; item != NULL; item = item->next_item) {
685 			/*
686 			 * skip all the other trash that comes up the mib stream
687 			 */
688 			if (item->group != MIB2_IP6 ||
689 			    item->mib_id != MIB2_IP6_ROUTE)
690 				continue;
691 			for (rp6 = (mib2_ipv6RouteEntry_t *)item->valp;
692 			    (char *)rp6 < (char *)item->valp + item->length;
693 			    /* LINTED */
694 			    rp6 = (mib2_ipv6RouteEntry_t *)
695 				((char *)rp6 + ipv6RouteEntrySize)) {
696 				delRouteEntry(NULL, rp6, seqno);
697 				seqno++;
698 			}
699 			break;
700 		}
701 		break;
702 	}
703 
704 	if (setsockopt(s, SOL_SOCKET, SO_USELOOPBACK, (char *)&on,
705 	    sizeof (on)) < 0)
706 		quit("setsockopt", errno);
707 }
708 
709 /*
710  * Given the contents of a mib_item_t of id type MIB2_IP_ROUTE or
711  * MIB2_IP6_ROUTE, construct and send an RTM_DELETE routing socket message in
712  * order to facilitate the flushing of RTF_GATEWAY routes.
713  */
714 static void
715 delRouteEntry(mib2_ipRouteEntry_t *rp, mib2_ipv6RouteEntry_t *rp6, int seqno)
716 {
717 	char *cp;
718 	int ire_type;
719 	int rlen;
720 	struct rt_msghdr *rtm;
721 	struct sockaddr_in sin;
722 	struct sockaddr_in6 sin6;
723 	int slen;
724 
725 	if (rp != NULL)
726 		ire_type = rp->ipRouteInfo.re_ire_type;
727 	else
728 		ire_type = rp6->ipv6RouteInfo.re_ire_type;
729 	if (ire_type != IRE_DEFAULT &&
730 	    ire_type != IRE_PREFIX &&
731 	    ire_type != IRE_HOST &&
732 	    ire_type != IRE_HOST_REDIRECT)
733 		return;
734 
735 	rtm = &m_rtmsg.m_rtm;
736 	(void) memset(rtm, 0, sizeof (m_rtmsg));
737 	rtm->rtm_type = RTM_DELETE;
738 	rtm->rtm_seq = seqno;
739 	rtm->rtm_flags |= RTF_GATEWAY;
740 	rtm->rtm_version = RTM_VERSION;
741 	rtm->rtm_addrs = RTA_DST | RTA_GATEWAY | RTA_NETMASK;
742 	cp = m_rtmsg.m_space;
743 	if (rp != NULL) {
744 		slen = sizeof (struct sockaddr_in);
745 		if (rp->ipRouteMask == IP_HOST_MASK)
746 			rtm->rtm_flags |= RTF_HOST;
747 		(void) memset(&sin, 0, slen);
748 		sin.sin_family = AF_INET;
749 		sin.sin_addr.s_addr = rp->ipRouteDest;
750 		(void) memmove(cp, &sin, slen);
751 		cp += slen;
752 		sin.sin_addr.s_addr = rp->ipRouteNextHop;
753 		(void) memmove(cp, &sin, slen);
754 		cp += slen;
755 		sin.sin_addr.s_addr = rp->ipRouteMask;
756 		(void) memmove(cp, &sin, slen);
757 		cp += slen;
758 	} else {
759 		slen = sizeof (struct sockaddr_in6);
760 		if (rp6->ipv6RoutePfxLength == IPV6_ABITS)
761 			rtm->rtm_flags |= RTF_HOST;
762 		(void) memset(&sin6, 0, slen);
763 		sin6.sin6_family = AF_INET6;
764 		sin6.sin6_addr = rp6->ipv6RouteDest;
765 		(void) memmove(cp, &sin6, slen);
766 		cp += slen;
767 		sin6.sin6_addr = rp6->ipv6RouteNextHop;
768 		(void) memmove(cp, &sin6, slen);
769 		cp += slen;
770 		(void) memset(&sin6.sin6_addr, 0, sizeof (sin6.sin6_addr));
771 		(void) in_prefixlentomask(rp6->ipv6RoutePfxLength, IPV6_ABITS,
772 		    (uchar_t *)&sin6.sin6_addr.s6_addr);
773 		(void) memmove(cp, &sin6, slen);
774 		cp += slen;
775 	}
776 	rtm->rtm_msglen = cp - (char *)&m_rtmsg;
777 	if (debugonly) {
778 		/*
779 		 * In debugonly mode, the routing socket message to delete the
780 		 * current entry is not actually sent.  However if verbose is
781 		 * also set, the routing socket message that would have been
782 		 * is printed.
783 		 */
784 		if (verbose)
785 			print_rtmsg(rtm, rtm->rtm_msglen);
786 		return;
787 	}
788 
789 	rlen = write(s, (char *)&m_rtmsg, rtm->rtm_msglen);
790 	if (rlen < (int)rtm->rtm_msglen) {
791 		if (rlen < 0) {
792 			(void) fprintf(stderr,
793 			    gettext("route: write to routing socket: %s\n"),
794 			    strerror(errno));
795 		} else {
796 			(void) fprintf(stderr, gettext("route: write to "
797 			    "routing socket got only %d for rlen\n"), rlen);
798 		}
799 		return;
800 	}
801 	if (qflag) {
802 		/*
803 		 * In quiet mode, nothing is printed at all (unless the write()
804 		 * itself failed.
805 		 */
806 		return;
807 	}
808 	if (verbose) {
809 		print_rtmsg(rtm, rlen);
810 	} else {
811 		struct sockaddr *sa = (struct sockaddr *)(rtm + 1);
812 
813 		(void) printf("%-20.20s ",
814 		    rtm->rtm_flags & RTF_HOST ? routename(sa) :
815 			netname(sa));
816 		/* LINTED */
817 		sa = (struct sockaddr *)(salen(sa) + (char *)sa);
818 		(void) printf("%-20.20s ", routename(sa));
819 		(void) printf("done\n");
820 	}
821 }
822 
823 /*
824  * Return the name of the host whose address is given.
825  */
826 char *
827 routename(const struct sockaddr *sa)
828 {
829 	char *cp;
830 	static char line[MAXHOSTNAMELEN + 1];
831 	struct hostent *hp = NULL;
832 	static char domain[MAXHOSTNAMELEN + 1];
833 	static boolean_t first = B_TRUE;
834 	struct in_addr in;
835 	struct in6_addr in6;
836 	int error_num;
837 	ushort_t *s;
838 	ushort_t *slim;
839 
840 	if (first) {
841 		first = B_FALSE;
842 		if (gethostname(domain, MAXHOSTNAMELEN) == 0 &&
843 		    (cp = strchr(domain, '.')))
844 			(void) strcpy(domain, cp + 1);
845 		else
846 			domain[0] = 0;
847 	}
848 
849 	if (salen(sa) == 0) {
850 		(void) strcpy(line, "default");
851 		return (line);
852 	}
853 	switch (sa->sa_family) {
854 
855 	case AF_INET:
856 		/* LINTED */
857 		in = ((struct sockaddr_in *)sa)->sin_addr;
858 
859 		cp = NULL;
860 		if (in.s_addr == INADDR_ANY)
861 			cp = "default";
862 		if (cp == NULL && !nflag) {
863 			hp = gethostbyaddr((char *)&in, sizeof (struct in_addr),
864 				AF_INET);
865 			if (hp != NULL) {
866 				if (((cp = strchr(hp->h_name, '.')) != NULL) &&
867 				    (strcmp(cp + 1, domain) == 0))
868 					*cp = 0;
869 				cp = hp->h_name;
870 			}
871 		}
872 		if (cp != NULL) {
873 			(void) strncpy(line, cp, MAXHOSTNAMELEN);
874 			line[MAXHOSTNAMELEN] = '\0';
875 		} else {
876 			in.s_addr = ntohl(in.s_addr);
877 			(void) sprintf(line, "%u.%u.%u.%u", C(in.s_addr >> 24),
878 			    C(in.s_addr >> 16), C(in.s_addr >> 8),
879 			    C(in.s_addr));
880 		}
881 		break;
882 
883 	case AF_LINK:
884 		return (link_ntoa((struct sockaddr_dl *)sa));
885 
886 	case AF_INET6:
887 		/* LINTED */
888 		in6 = ((struct sockaddr_in6 *)sa)->sin6_addr;
889 
890 		cp = NULL;
891 		if (IN6_IS_ADDR_UNSPECIFIED(&in6))
892 			cp = "default";
893 		if (cp == NULL && !nflag) {
894 			hp = getipnodebyaddr((char *)&in6,
895 				sizeof (struct in6_addr), AF_INET6, &error_num);
896 			if (hp != NULL) {
897 				if (((cp = strchr(hp->h_name, '.')) != NULL) &&
898 				    (strcmp(cp + 1, domain) == 0))
899 					*cp = 0;
900 				cp = hp->h_name;
901 			}
902 		}
903 		if (cp != NULL) {
904 			(void) strncpy(line, cp, MAXHOSTNAMELEN);
905 			line[MAXHOSTNAMELEN] = '\0';
906 		} else {
907 			(void) inet_ntop(AF_INET6, (void *)&in6, line,
908 			    INET6_ADDRSTRLEN);
909 		}
910 		if (hp != NULL)
911 			freehostent(hp);
912 
913 		break;
914 
915 	default:
916 		s = (ushort_t *)sa;
917 
918 		slim = s + ((salen(sa) + 1) >> 1);
919 		cp = line + sprintf(line, "(%d)", sa->sa_family);
920 
921 		while (++s < slim) /* start with sa->sa_data */
922 			cp += sprintf(cp, " %x", *s);
923 		break;
924 	}
925 	return (line);
926 }
927 
928 /*
929  * Return the name of the network whose address is given.
930  * The address is assumed to be that of a net or subnet, not a host.
931  */
932 static char *
933 netname(struct sockaddr *sa)
934 {
935 	char *cp = NULL;
936 	static char line[MAXHOSTNAMELEN + 1];
937 	struct netent *np;
938 	in_addr_t net, mask;
939 	int subnetshift;
940 	struct in_addr in;
941 	ushort_t *s;
942 	ushort_t *slim;
943 
944 	switch (sa->sa_family) {
945 
946 	case AF_INET:
947 		/* LINTED */
948 		in = ((struct sockaddr_in *)sa)->sin_addr;
949 
950 		in.s_addr = ntohl(in.s_addr);
951 		if (in.s_addr == INADDR_ANY) {
952 			cp = "default";
953 		} else if (!nflag) {
954 			if (IN_CLASSA(in.s_addr)) {
955 				mask = IN_CLASSA_NET;
956 				subnetshift = 8;
957 			} else if (IN_CLASSB(in.s_addr)) {
958 				mask = IN_CLASSB_NET;
959 				subnetshift = 8;
960 			} else {
961 				mask = IN_CLASSC_NET;
962 				subnetshift = 4;
963 			}
964 			/*
965 			 * If there are more bits than the standard mask
966 			 * would suggest, subnets must be in use.
967 			 * Guess at the subnet mask, assuming reasonable
968 			 * width subnet fields.
969 			 */
970 			while (in.s_addr &~ mask)
971 				mask = (long)mask >> subnetshift;
972 			net = in.s_addr & mask;
973 			while ((mask & 1) == 0)
974 				mask >>= 1, net >>= 1;
975 			np = getnetbyaddr(net, AF_INET);
976 			if (np != NULL)
977 				cp = np->n_name;
978 		}
979 		if (cp != NULL) {
980 			(void) strncpy(line, cp, MAXHOSTNAMELEN);
981 			line[MAXHOSTNAMELEN] = '\0';
982 		} else if ((in.s_addr & 0xffffff) == 0) {
983 			(void) sprintf(line, "%u", C(in.s_addr >> 24));
984 		} else if ((in.s_addr & 0xffff) == 0) {
985 			(void) sprintf(line, "%u.%u", C(in.s_addr >> 24),
986 			    C(in.s_addr >> 16));
987 		} else if ((in.s_addr & 0xff) == 0) {
988 			(void) sprintf(line, "%u.%u.%u", C(in.s_addr >> 24),
989 			    C(in.s_addr >> 16), C(in.s_addr >> 8));
990 		} else {
991 			(void) sprintf(line, "%u.%u.%u.%u", C(in.s_addr >> 24),
992 			    C(in.s_addr >> 16), C(in.s_addr >> 8),
993 			    C(in.s_addr));
994 		}
995 		break;
996 
997 	case AF_LINK:
998 		return (link_ntoa((struct sockaddr_dl *)sa));
999 
1000 	case AF_INET6:
1001 		return (routename(sa));
1002 
1003 	default:
1004 		/* LINTED */
1005 		s = (ushort_t *)sa->sa_data;
1006 
1007 		slim = s + ((salen(sa) + 1) >> 1);
1008 		cp = line + sprintf(line, "af %d:", sa->sa_family);
1009 
1010 		while (s < slim)
1011 			cp += sprintf(cp, " %x", *s++);
1012 		break;
1013 	}
1014 	return (line);
1015 }
1016 
1017 /*
1018  * Initialize a new structure.  Keep in mind that ri_dst_str, ri_gate_str and
1019  * ri_ifp_str will be freed by det_rtcmd_irep, so they should either be NULL
1020  * or point to dynamically allocated memory.
1021  */
1022 rtcmd_irep_t *
1023 new_rtcmd_irep(void)
1024 {
1025 	rtcmd_irep_t *rcip;
1026 
1027 	rcip = calloc(1, sizeof (rtcmd_irep_t));
1028 	if (rcip == NULL) {
1029 		quit("calloc", errno);
1030 	}
1031 	rcip->ri_af = af;
1032 	rcip->ri_flags = RTF_STATIC;
1033 	return (rcip);
1034 }
1035 
1036 void
1037 del_rtcmd_irep(rtcmd_irep_t *rcip)
1038 {
1039 	free(rcip->ri_dest_str);
1040 	free(rcip->ri_gate_str);
1041 	free(rcip->ri_ifp_str);
1042 	if (rcip->ri_gate_hp != NULL) {
1043 		freehostent(rcip->ri_gate_hp);
1044 	}
1045 	free(rcip);
1046 }
1047 
1048 void
1049 save_string(char **dst, char *src)
1050 {
1051 	free(*dst);
1052 	*dst = strdup(src);
1053 	if (*dst == NULL) {
1054 		quit("malloc", errno);
1055 	}
1056 }
1057 
1058 /*
1059  * Print the short form summary of a route command.
1060  * Eg. "add net default: gateway 10.0.0.1"
1061  * The final newline is not added, allowing the caller to append additional
1062  * information.
1063  */
1064 void
1065 print_rtcmd_short(FILE *to, rtcmd_irep_t *rcip, boolean_t gw_good,
1066     boolean_t to_saved)
1067 {
1068 	char *cmd;
1069 	char obuf[INET6_ADDRSTRLEN];
1070 
1071 	switch (rcip->ri_cmd) {
1072 	case RTM_ADD:
1073 		cmd = "add";
1074 		break;
1075 	case RTM_CHANGE:
1076 		cmd = "change";
1077 		break;
1078 	case RTM_DELETE:
1079 		cmd = "delete";
1080 		break;
1081 	case RTM_GET:
1082 		cmd = "get";
1083 		break;
1084 	default:
1085 		assert(0);
1086 	}
1087 
1088 	(void) fprintf(to, "%s%s %s %s", cmd,
1089 	    (to_saved) ? " persistent" : "",
1090 	    (rcip->ri_flags & RTF_HOST) ? "host" : "net",
1091 	    (rcip->ri_dest_str == NULL) ? "NULL" : rcip->ri_dest_str);
1092 
1093 	if (rcip->ri_gate_str != NULL) {
1094 		switch (rcip->ri_af) {
1095 		case AF_INET:
1096 			if (nflag) {
1097 				(void) fprintf(to, ": gateway %s",
1098 				    inet_ntoa(rcip->ri_gate.sin.sin_addr));
1099 			} else if (gw_good &&
1100 			    rcip->ri_gate_hp != NULL &&
1101 			    rcip->ri_gate_hp->h_addr_list[1] != NULL) {
1102 				/*
1103 				 * Print the actual address used in the case
1104 				 * where there was more than one address
1105 				 * available for the name, and one was used
1106 				 * successfully.
1107 				 */
1108 				(void) fprintf(to, ": gateway %s (%s)",
1109 				    rcip->ri_gate_str,
1110 				    inet_ntoa(rcip->ri_gate.sin.sin_addr));
1111 			} else {
1112 				(void) fprintf(to, ": gateway %s",
1113 				    rcip->ri_gate_str);
1114 			}
1115 			break;
1116 		case AF_INET6:
1117 			if (inet_ntop(AF_INET6,
1118 				&rcip->ri_gate.sin6.sin6_addr, obuf,
1119 				INET6_ADDRSTRLEN) != NULL) {
1120 				if (nflag) {
1121 					(void) fprintf(to, ": gateway %s",
1122 					    obuf);
1123 					break;
1124 				}
1125 				if (gw_good &&
1126 				    rcip->ri_gate_hp->h_addr_list[1] != NULL) {
1127 					(void) fprintf(to, ": gateway %s (%s)",
1128 					    rcip->ri_gate_str, obuf);
1129 					break;
1130 				}
1131 			}
1132 			/* FALLTHROUGH */
1133 		default:
1134 			(void) fprintf(to, ": gateway %s",
1135 			    rcip->ri_gate_str);
1136 			break;
1137 		}
1138 	}
1139 }
1140 
1141 void
1142 set_metric(rtcmd_irep_t *rcip, char *value, int key, boolean_t lock)
1143 {
1144 	int flag = 0;
1145 	uint_t noval, *valp = &noval;
1146 
1147 	switch (key) {
1148 #define	caseof(x, y, z)	\
1149 	case (x): valp = &(rcip->ri_metrics.z); flag = (y); break
1150 
1151 	caseof(K_MTU, RTV_MTU, rmx_mtu);
1152 	caseof(K_HOPCOUNT, RTV_HOPCOUNT, rmx_hopcount);
1153 	caseof(K_EXPIRE, RTV_EXPIRE, rmx_expire);
1154 	caseof(K_RECVPIPE, RTV_RPIPE, rmx_recvpipe);
1155 	caseof(K_SENDPIPE, RTV_SPIPE, rmx_sendpipe);
1156 	caseof(K_SSTHRESH, RTV_SSTHRESH, rmx_ssthresh);
1157 	caseof(K_RTT, RTV_RTT, rmx_rtt);
1158 	caseof(K_RTTVAR, RTV_RTTVAR, rmx_rttvar);
1159 #undef	caseof
1160 	}
1161 	rcip->ri_inits |= flag;
1162 	if (lock)
1163 		rcip->ri_metrics.rmx_locks |= flag;
1164 	*valp = atoi(value);
1165 }
1166 
1167 /*
1168  * Parse the options give in argv[], filling in rcip with the results.
1169  * If cmd_string is non-null, argc and argv are ignored, and cmd_string is
1170  * tokenized to produce the command line.  Cmd_string is tokenized using
1171  * strtok, which will overwrite whitespace in the string with nulls.
1172  *
1173  * Returns B_TRUE on success and B_FALSE on failure.
1174  */
1175 boolean_t
1176 args_to_rtcmd(rtcmd_irep_t *rcip, char **argv, char *cmd_string)
1177 {
1178 	const char *ws = "\f\n\r\t\v ";
1179 	char *tok = cmd_string;
1180 	char *keyword_str;
1181 	addr_type_t atype = ADDR_TYPE_ANY;
1182 	boolean_t iflag = B_FALSE;
1183 	boolean_t locknext = B_FALSE;
1184 	boolean_t lockrest = B_FALSE;
1185 	boolean_t dash_keyword;
1186 	int key;
1187 	char *err;
1188 
1189 	if (cmd_string == NULL) {
1190 		tok = argv[0];
1191 	} else {
1192 		tok = strtok(cmd_string, ws);
1193 	}
1194 
1195 	/*
1196 	 * The command keywords are already fully checked by main() or
1197 	 * search_rtfile().
1198 	 */
1199 	switch (*tok) {
1200 	case 'a':
1201 		rcip->ri_cmd = RTM_ADD;
1202 		break;
1203 	case 'c':
1204 		rcip->ri_cmd = RTM_CHANGE;
1205 		break;
1206 	case 'd':
1207 		rcip->ri_cmd = RTM_DELETE;
1208 		break;
1209 	case 'g':
1210 		rcip->ri_cmd = RTM_GET;
1211 		break;
1212 	default:
1213 		/* NOTREACHED */
1214 		quit(gettext("Internal Error"), EINVAL);
1215 		/* NOTREACHED */
1216 	}
1217 
1218 #define	NEXTTOKEN \
1219 	((tok = (cmd_string == NULL ? *++argv : strtok(NULL, ws))) != NULL)
1220 
1221 	while (NEXTTOKEN) {
1222 		keyword_str = tok;
1223 		if (*tok == '-') {
1224 			dash_keyword = B_TRUE;
1225 			key = keyword(tok + 1);
1226 		} else {
1227 			dash_keyword = B_FALSE;
1228 			key = keyword(tok);
1229 			if (key != K_HOST && key != K_NET) {
1230 				/* All others must be preceded by '-' */
1231 				key = 0;
1232 			}
1233 		}
1234 		switch (key) {
1235 		case K_HOST:
1236 			if (atype == ADDR_TYPE_NET) {
1237 				syntax_error(gettext("route: -host and -net "
1238 				    "are mutually exclusive\n"));
1239 				return (B_FALSE);
1240 			}
1241 			atype = ADDR_TYPE_HOST;
1242 			break;
1243 		case K_NET:
1244 			if (atype == ADDR_TYPE_HOST) {
1245 				syntax_error(gettext("route: -host and -net "
1246 				    "are mutually exclusive\n"));
1247 				return (B_FALSE);
1248 			}
1249 			atype = ADDR_TYPE_NET;
1250 			break;
1251 		case K_LINK:
1252 			rcip->ri_af = AF_LINK;
1253 			break;
1254 		case K_INET:
1255 			rcip->ri_af = AF_INET;
1256 			break;
1257 		case K_SA:
1258 			rcip->ri_af = PF_ROUTE;
1259 			break;
1260 		case K_INET6:
1261 			rcip->ri_af = AF_INET6;
1262 			break;
1263 		case K_IFACE:
1264 		case K_INTERFACE:
1265 			iflag = B_TRUE;
1266 			/* fallthrough */
1267 		case K_NOSTATIC:
1268 			rcip->ri_flags &= ~RTF_STATIC;
1269 			break;
1270 		case K_LOCK:
1271 			locknext = B_TRUE;
1272 			break;
1273 		case K_LOCKREST:
1274 			lockrest = B_TRUE;
1275 			break;
1276 		case K_REJECT:
1277 			rcip->ri_flags |= RTF_REJECT;
1278 			break;
1279 		case K_BLACKHOLE:
1280 			rcip->ri_flags |= RTF_BLACKHOLE;
1281 			break;
1282 		case K_PROTO1:
1283 			rcip->ri_flags |= RTF_PROTO1;
1284 			break;
1285 		case K_PROTO2:
1286 			rcip->ri_flags |= RTF_PROTO2;
1287 			break;
1288 		case K_CLONING:
1289 			rcip->ri_flags |= RTF_CLONING;
1290 			break;
1291 		case K_XRESOLVE:
1292 			rcip->ri_flags |= RTF_XRESOLVE;
1293 			break;
1294 		case K_STATIC:
1295 			rcip->ri_flags |= RTF_STATIC;
1296 			break;
1297 		case K_IFA:
1298 			if (!NEXTTOKEN) {
1299 				syntax_arg_missing(keyword_str);
1300 				return (B_FALSE);
1301 			}
1302 			if (!getaddr(rcip, RTA_IFA, tok, atype)) {
1303 				return (B_FALSE);
1304 			}
1305 			break;
1306 		case K_IFP:
1307 			if (!NEXTTOKEN) {
1308 				syntax_arg_missing(keyword_str);
1309 				return (B_FALSE);
1310 			}
1311 			if (!getaddr(rcip, RTA_IFP, tok, atype)) {
1312 				return (B_FALSE);
1313 			}
1314 			break;
1315 		case K_GATEWAY:
1316 			if (!NEXTTOKEN) {
1317 				syntax_arg_missing(keyword_str);
1318 				return (B_FALSE);
1319 			}
1320 			if (!getaddr(rcip, RTA_GATEWAY, tok, atype)) {
1321 				return (B_FALSE);
1322 			}
1323 			break;
1324 		case K_DST:
1325 			if (!NEXTTOKEN) {
1326 				syntax_arg_missing(keyword_str);
1327 				return (B_FALSE);
1328 			}
1329 			if (!getaddr(rcip, RTA_DST, tok, atype)) {
1330 				return (B_FALSE);
1331 			}
1332 			break;
1333 		case K_NETMASK:
1334 			if (!NEXTTOKEN) {
1335 				syntax_arg_missing(keyword_str);
1336 				return (B_FALSE);
1337 			}
1338 			if (!getaddr(rcip, RTA_NETMASK, tok, atype)) {
1339 				return (B_FALSE);
1340 			}
1341 			atype = ADDR_TYPE_NET;
1342 			break;
1343 		case K_MTU:
1344 		case K_HOPCOUNT:
1345 		case K_EXPIRE:
1346 		case K_RECVPIPE:
1347 		case K_SENDPIPE:
1348 		case K_SSTHRESH:
1349 		case K_RTT:
1350 		case K_RTTVAR:
1351 			if (!NEXTTOKEN) {
1352 				syntax_arg_missing(keyword_str);
1353 				return (B_FALSE);
1354 			}
1355 			set_metric(rcip, tok, key, locknext || lockrest);
1356 			locknext = B_FALSE;
1357 			break;
1358 		case K_PRIVATE:
1359 			rcip->ri_flags |= RTF_PRIVATE;
1360 			break;
1361 		case K_MULTIRT:
1362 			rcip->ri_flags |= RTF_MULTIRT;
1363 			break;
1364 		case K_SETSRC:
1365 			if (!NEXTTOKEN) {
1366 				syntax_arg_missing(keyword_str);
1367 				return (B_FALSE);
1368 			}
1369 			if (!getaddr(rcip, RTA_SRC, tok, atype)) {
1370 				return (B_FALSE);
1371 			}
1372 			rcip->ri_flags |= RTF_SETSRC;
1373 			break;
1374 		case K_SECATTR:
1375 			if (!NEXTTOKEN) {
1376 				syntax_arg_missing(keyword_str);
1377 				return (B_FALSE);
1378 			}
1379 			if ((rcip->ri_cmd == RTM_ADD ||
1380 			    rcip->ri_cmd == RTM_CHANGE) &&
1381 			    rcip->ri_rtsa_cnt++ < 1 && is_system_labeled()) {
1382 				int err;
1383 
1384 				if (!rtsa_keyword(tok, &rcip->ri_rtsa, &err,
1385 				    NULL)) {
1386 					(void) fprintf(stderr, gettext("route: "
1387 					    "bad security attribute: %s\n"),
1388 					    tsol_strerror(err, errno));
1389 					return (B_FALSE);
1390 				}
1391 			}
1392 			if (rcip->ri_rtsa_cnt > 1) {
1393 				(void) fprintf(stderr,
1394 				    gettext("route: can't specify more "
1395 				    "than one security attribute\n"));
1396 				return (B_FALSE);
1397 			}
1398 			break;
1399 		default:
1400 			if (dash_keyword) {
1401 				syntax_bad_keyword(tok + 1);
1402 				return (B_FALSE);
1403 			}
1404 			if ((rcip->ri_addrs & RTA_DST) == 0) {
1405 				if (!getaddr(rcip, RTA_DST, tok, atype)) {
1406 					return (B_FALSE);
1407 				}
1408 			} else if ((rcip->ri_addrs & RTA_GATEWAY) == 0) {
1409 				/*
1410 				 * For the gateway parameter, retrieve the
1411 				 * pointer to the struct hostent so that all
1412 				 * possible addresses can be tried until one
1413 				 * is successful.
1414 				 */
1415 				if (!getaddr(rcip, RTA_GATEWAY, tok, atype)) {
1416 					return (B_FALSE);
1417 				}
1418 			} else {
1419 				ulong_t metric;
1420 				/*
1421 				 * Assume that a regular number is a metric.
1422 				 * Needed for compatibility with old route
1423 				 * command syntax.
1424 				 */
1425 				errno = 0;
1426 				metric = strtoul(tok, &err, 10);
1427 				if (errno == 0 && *err == '\0' &&
1428 				    metric < 0x80000000ul) {
1429 					iflag = (metric == 0);
1430 					if (verbose) {
1431 						(void) printf("old usage of "
1432 						    "trailing number, assuming "
1433 						    "route %s\n", iflag ?
1434 						    "to if" : "via gateway");
1435 					}
1436 					continue;
1437 				}
1438 				if (!getaddr(rcip, RTA_NETMASK, tok, atype)) {
1439 					return (B_FALSE);
1440 				}
1441 			}
1442 		}
1443 	}
1444 #undef NEXTTOKEN
1445 
1446 	if ((rcip->ri_addrs & RTA_DST) == 0) {
1447 		syntax_error(gettext("route: destination required\n"));
1448 		return (B_FALSE);
1449 	} else if ((rcip->ri_cmd == RTM_ADD || rcip->ri_cmd == RTM_DELETE) &&
1450 	    (rcip->ri_addrs & RTA_GATEWAY) == 0) {
1451 		syntax_error(gettext(
1452 		    "route: gateway required for add or delete command\n"));
1453 		return (B_FALSE);
1454 	}
1455 
1456 	if (!iflag) {
1457 		rcip->ri_flags |= RTF_GATEWAY;
1458 	}
1459 
1460 	if (atype != ADDR_TYPE_NET) {
1461 		if (rcip->ri_addrs & RTA_NETMASK) {
1462 			/*
1463 			 * We know the netmask, so we can set the host flag
1464 			 * based on whether the netmask is the host netmask.
1465 			 */
1466 			if (rcip->ri_af == AF_INET &&
1467 			    rcip->ri_mask.sin.sin_addr.s_addr ==
1468 			    IP_HOST_MASK) {
1469 				rcip->ri_flags |= RTF_HOST;
1470 			}
1471 			if (rcip->ri_af == AF_INET6 &&
1472 			    memcmp(&rcip->ri_mask.sin6.sin6_addr,
1473 				&in6_host_mask,
1474 				sizeof (struct in6_addr)) == 0) {
1475 				rcip->ri_flags |= RTF_HOST;
1476 			}
1477 		} else {
1478 			/*
1479 			 * If no prefix mask has been saved at this point, it
1480 			 * only makes sense to treat the destination address
1481 			 * as a host address.
1482 			 */
1483 			rcip->ri_flags |= RTF_HOST;
1484 		}
1485 	}
1486 	return (B_TRUE);
1487 }
1488 
1489 /*
1490  * This command always seeks to the end of the file prior to writing.
1491  */
1492 void
1493 write_to_rtfile(FILE *fp, int argc, char **argv)
1494 {
1495 	char file_line[BUF_SIZE];
1496 	int len;
1497 	int i;
1498 
1499 	len = 0;
1500 	if (early_v6_keyword) {
1501 		/*
1502 		 * This flag is set when "inet6" was seen as an
1503 		 * argument to the -f flag.  Normally, when writing
1504 		 * routes to the persistent route file, everything on
1505 		 * the command line after "add" is saved verbatim.
1506 		 * In this case, the arguments after "add" may not be
1507 		 * sufficient, as the ipv6 keyword came before "add",
1508 		 * yet must be present in the persistent route file.
1509 		 */
1510 		len += snprintf(file_line, BUF_SIZE, "-inet6 ");
1511 	}
1512 	for (i = 0; argc > 0 && len < BUF_SIZE; i++, argc--) {
1513 		len += snprintf(&file_line[len], BUF_SIZE - len, "%s ",
1514 		    argv[i]);
1515 	}
1516 	if (len >= BUF_SIZE)
1517 		quit(gettext("Internal Error"), EINVAL);
1518 	file_line[len - 1] = '\n';
1519 	if (fseek(fp, 0, SEEK_END) != 0 ||
1520 	    fputs(file_line, fp) == EOF) {
1521 		quit(gettext("failed to write to route file"),
1522 		    errno);
1523 	}
1524 }
1525 
1526 boolean_t
1527 compare_rtcmd(rtcmd_irep_t *srch_rt, rtcmd_irep_t *file_rt)
1528 {
1529 	if (strcmp(srch_rt->ri_dest_str, file_rt->ri_dest_str) != 0 ||
1530 	    memcmp(&srch_rt->ri_mask, &file_rt->ri_mask, sizeof (su_t)) != 0) {
1531 		return (B_FALSE);
1532 	}
1533 	return (srch_rt->ri_gate_str == NULL ||
1534 	    strcmp(srch_rt->ri_gate_str, file_rt->ri_gate_str) == 0);
1535 }
1536 
1537 /*
1538  * Search the route file for routes matching the supplied route.  There are 3
1539  * modes of operation:
1540  *    SEARCH_MODE_RET - no side effects.
1541  *    SEARCH_MODE_PRINT - prints each matching line.
1542  *    SEARCH_MODE_DEL - copies all valid, non-matching lines to tmp_fp.
1543  *
1544  * In all cases, the number of matches is returned.  If rt is NULL, all routes
1545  * matching the global af value are considered matching.
1546  */
1547 int
1548 search_rtfile(FILE *fp, FILE *temp_fp, rtcmd_irep_t *rt, search_mode_t mode)
1549 {
1550 	char *tmp_buf;
1551 	int match_cnt;
1552 	boolean_t match;
1553 	char file_line[BUF_SIZE + 4] = "add ";
1554 	rtcmd_irep_t *thisrt;
1555 
1556 	match_cnt = 0;
1557 
1558 	/*
1559 	 * Leave space at the beginning of file_line for "add ".
1560 	 */
1561 	while (fgets(file_line + 4, BUF_SIZE, fp) != NULL) {
1562 
1563 		if (file_line[4] == '#' || file_line[4] == '\n') {
1564 			/* Handle comments and blank lines */
1565 			if (mode == SEARCH_MODE_DEL &&
1566 			    fputs(file_line + 4, temp_fp) == EOF) {
1567 				quit(gettext(
1568 				    "route: failed to write to temp file"),
1569 				    errno);
1570 			}
1571 			continue;
1572 		}
1573 		thisrt = new_rtcmd_irep();
1574 		/*
1575 		 * thisrt->ri_af defaults to whatever address family happens
1576 		 * to be set in the global af, but routes in the persistent
1577 		 * route file must be treated as AF_INET by default.
1578 		 */
1579 		thisrt->ri_af = AF_INET;
1580 
1581 		exit_on_error = B_FALSE;
1582 		tmp_buf = strdup(file_line);
1583 		/* args_to_rtcmd() will mangle the string passed. */
1584 		if (!args_to_rtcmd(thisrt, NULL, tmp_buf)) {
1585 			/* There was an error in args_to_rtcmd() or helpers */
1586 			del_rtcmd_irep(thisrt);
1587 			free(tmp_buf);
1588 			continue;
1589 		}
1590 		exit_on_error = B_TRUE;
1591 		free(tmp_buf);
1592 
1593 		if (thisrt->ri_gate_str == NULL) {
1594 			del_rtcmd_irep(thisrt);
1595 			continue;
1596 		}
1597 		match = (rt == NULL) ? (thisrt->ri_af == af) :
1598 		    compare_rtcmd(rt, thisrt);
1599 
1600 		if (match) match_cnt++;
1601 		if (match && mode == SEARCH_MODE_PRINT) {
1602 			(void) printf("persistent: route %s", file_line);
1603 		}
1604 		if (match && mode == SEARCH_MODE_DEL) {
1605 			thisrt->ri_cmd = RTM_DELETE;
1606 			print_rtcmd_short(stdout, thisrt, B_FALSE, B_TRUE);
1607 			(void) printf("\n");
1608 		}
1609 		del_rtcmd_irep(thisrt);
1610 
1611 		if (!match && mode == SEARCH_MODE_DEL &&
1612 		    fputs(file_line + 4, temp_fp) == EOF) {
1613 			quit(gettext("failed to write to temp file"),
1614 			    errno);
1615 		}
1616 	}
1617 	return (match_cnt);
1618 }
1619 
1620 /*
1621  * Perform the route operation given in argv on the persistent route file.
1622  * If do_flush is set, the persistent route file is flushed of all routes
1623  * matching the global family, and the arguments are ignored.
1624  */
1625 void
1626 save_route(int argc, char **argv, int do_flush)
1627 {
1628 	rtcmd_irep_t *rt;
1629 	int perm_fd;
1630 	FILE *perm_fp;
1631 	FILE *temp_fp;
1632 	mode_t fmode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
1633 	struct flock lock;
1634 	struct stat st;
1635 	const char commentstr[] =
1636 	    "# File generated by route(1M) - do not edit.\n";
1637 
1638 	perm_fd = open(perm_file, O_RDWR | O_CREAT, fmode);
1639 	if (perm_fd == -1 || fstat(perm_fd, &st) == -1)
1640 		quit("failed to open route file", errno);
1641 
1642 	lock.l_type = F_WRLCK;
1643 	lock.l_whence = SEEK_SET;
1644 	lock.l_start = 0;
1645 	lock.l_len = 0;
1646 	if (fcntl(perm_fd, F_SETLK, &lock) != 0) {
1647 		quit(gettext("failed to lock route file"), errno);
1648 		/* NOTREACHED */
1649 	}
1650 	if (st.st_size == 0 &&
1651 	    write(perm_fd, commentstr, sizeof (commentstr) - 1) !=
1652 	    sizeof (commentstr) - 1)
1653 		quit(gettext("failed to open route file"), errno);
1654 
1655 	if ((perm_fp = fdopen(perm_fd, "r+")) == NULL) {
1656 		quit(gettext("failed to open route file"), errno);
1657 		/* NOTREACHED */
1658 	}
1659 
1660 	if (!do_flush) {
1661 		rt = new_rtcmd_irep();
1662 		(void) args_to_rtcmd(rt, argv, NULL);
1663 	}
1664 	if (do_flush || rt->ri_cmd == RTM_DELETE) {
1665 		if ((temp_fp = fopen(temp_file, "w")) == NULL) {
1666 			quit(gettext("failed to open temp file"), errno);
1667 			/* NOTREACHED */
1668 		}
1669 	}
1670 	if (do_flush) {
1671 		(void) search_rtfile(perm_fp, temp_fp, NULL, SEARCH_MODE_DEL);
1672 		if (fclose(temp_fp) != 0 || rename(temp_file, perm_file) != 0) {
1673 			quit(gettext("failed to update route file"), errno);
1674 			/* NOTREACHED */
1675 		}
1676 		(void) fclose(perm_fp);
1677 		return;
1678 	}
1679 
1680 	switch (rt->ri_cmd) {
1681 	case RTM_ADD:
1682 		if (search_rtfile(perm_fp, NULL, rt, SEARCH_MODE_NULL) > 0) {
1683 			/* Route is already in the file */
1684 			print_rtcmd_short(stderr, rt, B_FALSE, B_TRUE);
1685 			(void) fprintf(stderr, ": entry exists\n");
1686 			exit(1);
1687 		}
1688 		write_to_rtfile(perm_fp, argc - 1, argv + 1);
1689 		print_rtcmd_short(stdout, rt, B_FALSE, B_TRUE);
1690 		(void) printf("\n");
1691 		break;
1692 
1693 	case RTM_CHANGE:
1694 		syntax_error(
1695 		    gettext("route: change command not supported with -p\n"));
1696 		/* NOTREACHED */
1697 
1698 	case RTM_DELETE:
1699 		if (search_rtfile(perm_fp, temp_fp, rt, SEARCH_MODE_DEL) <= 0) {
1700 			/* Route not found */
1701 			print_rtcmd_short(stderr, rt, B_FALSE, B_TRUE);
1702 			(void) fprintf(stderr, gettext(": not in file\n"));
1703 			exit(1);
1704 		}
1705 		if (fclose(temp_fp) != 0 || rename(temp_file, perm_file) != 0) {
1706 			quit(gettext("failed to update route file"), errno);
1707 			/* NOTREACHED */
1708 		}
1709 		break;
1710 
1711 	case RTM_GET:
1712 		if (search_rtfile(perm_fp, temp_fp, rt, SEARCH_MODE_PRINT) <=
1713 		    0) {
1714 			print_rtcmd_short(stdout, rt, B_FALSE, B_TRUE);
1715 			(void) printf(gettext(": not in file\n"));
1716 		}
1717 		break;
1718 
1719 	default:
1720 		quit(gettext("Internal Error"), EINVAL);
1721 		/* NOTREACHED */
1722 	}
1723 
1724 	/*
1725 	 * Closing the file unlocks it.
1726 	 */
1727 	(void) fclose(perm_fp);
1728 }
1729 
1730 int
1731 show_saved_routes(int argc)
1732 {
1733 	int perm_fd;
1734 	FILE *perm_fp;
1735 	struct flock lock;
1736 	int count = 0;
1737 
1738 	if (argc != 1) {
1739 		syntax_error(gettext("route: invalid arguments for show\n"));
1740 	}
1741 
1742 	perm_fd = open(perm_file, O_RDONLY, 0);
1743 
1744 	if (perm_fd == -1) {
1745 		if (errno == ENOENT) {
1746 			(void) printf("No persistent routes are defined\n");
1747 			return (0);
1748 		} else {
1749 			quit(gettext("failed to open route file"), errno);
1750 		}
1751 	}
1752 	lock.l_type = F_RDLCK;
1753 	lock.l_whence = SEEK_SET;
1754 	lock.l_start = 0;
1755 	lock.l_len = 0;
1756 	if (fcntl(perm_fd, F_SETLK, &lock) != 0) {
1757 		quit(gettext("failed to lock route file"),
1758 		    errno);
1759 		/* NOTREACHED */
1760 	}
1761 	if ((perm_fp = fdopen(perm_fd, "r")) == NULL) {
1762 		quit(gettext("failed to open route file"), errno);
1763 		/* NOTREACHED */
1764 	}
1765 	count += search_rtfile(perm_fp, NULL, NULL, SEARCH_MODE_PRINT);
1766 	(void) fseek(perm_fp, 0, SEEK_SET);
1767 	af = AF_INET6;
1768 	count += search_rtfile(perm_fp, NULL, NULL, SEARCH_MODE_PRINT);
1769 
1770 	if (count == 0)
1771 		(void) printf("No persistent routes are defined\n");
1772 
1773 	(void) fclose(perm_fp);
1774 	return (0);
1775 }
1776 
1777 int
1778 newroute(char **argv)
1779 {
1780 	rtcmd_irep_t *newrt;
1781 	int ret, attempts, oerrno;
1782 	char *err;
1783 	char obuf[INET6_ADDRSTRLEN];
1784 #define	hp (newrt->ri_gate_hp)
1785 
1786 	newrt = new_rtcmd_irep();
1787 	(void) args_to_rtcmd(newrt, argv, NULL);
1788 
1789 	if (newrt->ri_cmd != RTM_GET && !tflag) {
1790 		/* Don't want to read back our messages */
1791 		(void) shutdown(s, 0);
1792 	}
1793 	if (newrt->ri_addrs & RTA_IFP) {
1794 		newrt->ri_ifp.sdl.sdl_index = if_nametoindex(newrt->ri_ifp_str);
1795 		if (newrt->ri_ifp.sdl.sdl_index == 0) {
1796 			if (errno != ENXIO) {
1797 				quit("if_nametoindex", errno);
1798 			} else {
1799 				(void) fprintf(stderr,
1800 				    gettext("route: %s: no such interface\n"),
1801 				    newrt->ri_ifp_str);
1802 				exit(1);
1803 			}
1804 		}
1805 		newrt->ri_ifp.sdl.sdl_family = AF_LINK;
1806 	}
1807 	for (attempts = 1; ; attempts++) {
1808 		errno = 0;
1809 		if ((ret = rtmsg(newrt)) == 0)
1810 			break;
1811 		if (errno != ENETUNREACH && errno != ESRCH)
1812 			break;
1813 		if ((newrt->ri_addrs & RTA_GATEWAY) && hp != NULL &&
1814 		    hp->h_addr_list[attempts] != NULL) {
1815 			switch (af) {
1816 			case AF_INET:
1817 				(void) memmove(&newrt->ri_gate.sin.sin_addr,
1818 				    hp->h_addr_list[attempts], hp->h_length);
1819 				continue;
1820 			case AF_INET6:
1821 				(void) memmove(&newrt->ri_gate.sin6.sin6_addr,
1822 				    hp->h_addr_list[attempts], hp->h_length);
1823 				continue;
1824 			}
1825 		}
1826 		break;
1827 	}
1828 	oerrno = errno;
1829 
1830 	if (newrt->ri_cmd != RTM_GET) {
1831 		print_rtcmd_short(stdout, newrt, (ret == 0), B_FALSE);
1832 		if (ret == 0)
1833 			(void) printf("\n");
1834 	} else if (ret != 0) {
1835 		/*
1836 		 * Note: there is nothing additional to print for get
1837 		 * if ret == 0.
1838 		 */
1839 		if (nflag) {
1840 			switch (newrt->ri_af) {
1841 			case AF_INET:
1842 				(void) printf(" %s",
1843 				    inet_ntoa(newrt->ri_dst.sin.sin_addr));
1844 				break;
1845 			case AF_INET6:
1846 				if (inet_ntop(AF_INET6,
1847 					(void *)&newrt->ri_dst.sin6.sin6_addr,
1848 					obuf, INET6_ADDRSTRLEN) != NULL) {
1849 					(void) printf(" %s", obuf);
1850 					break;
1851 				}
1852 				/* FALLTHROUGH */
1853 			default:
1854 				(void) printf("%s", newrt->ri_dest_str);
1855 				break;
1856 			}
1857 		} else {
1858 			(void) printf("%s", newrt->ri_dest_str);
1859 		}
1860 	}
1861 
1862 	if (ret != 0) {
1863 		switch (oerrno) {
1864 		case ESRCH:
1865 			err = "not in table";
1866 			break;
1867 		case EBUSY:
1868 			err = "entry in use";
1869 			break;
1870 		case ENOBUFS:
1871 			err = "routing table overflow";
1872 			break;
1873 		case EEXIST:
1874 			err = "entry exists";
1875 			break;
1876 		case EPERM:
1877 			err = "insufficient privileges";
1878 			break;
1879 		default:
1880 			err = strerror(oerrno);
1881 			break;
1882 		}
1883 		(void) printf(": %s\n", err);
1884 	}
1885 
1886 	del_rtcmd_irep(newrt);
1887 
1888 	return (oerrno);
1889 #undef hp
1890 }
1891 
1892 
1893 /*
1894  * Convert a network number to the corresponding IP address.
1895  * If the RTA_NETMASK hasn't been specified yet set it based
1896  * on the class of address.
1897  */
1898 static void
1899 inet_makenetandmask(rtcmd_irep_t *rcip, in_addr_t net, struct sockaddr_in *sin)
1900 {
1901 	in_addr_t addr, mask;
1902 
1903 	if (net == 0) {
1904 		mask = addr = 0;
1905 	} else if (net < 128) {
1906 		addr = net << IN_CLASSA_NSHIFT;
1907 		mask = IN_CLASSA_NET;
1908 	} else if (net < 65536) {
1909 		addr = net << IN_CLASSB_NSHIFT;
1910 		mask = IN_CLASSB_NET;
1911 	} else if (net < 16777216L) {
1912 		addr = net << IN_CLASSC_NSHIFT;
1913 		mask = IN_CLASSC_NET;
1914 	} else {
1915 		addr = net;
1916 		if ((addr & IN_CLASSA_HOST) == 0)
1917 			mask =  IN_CLASSA_NET;
1918 		else if ((addr & IN_CLASSB_HOST) == 0)
1919 			mask =  IN_CLASSB_NET;
1920 		else if ((addr & IN_CLASSC_HOST) == 0)
1921 			mask =  IN_CLASSC_NET;
1922 		else {
1923 			if (IN_CLASSA(addr))
1924 				mask =  IN_CLASSA_NET;
1925 			else if (IN_CLASSB(addr))
1926 				mask =  IN_CLASSB_NET;
1927 			else if (IN_CLASSC(addr))
1928 				mask =  IN_CLASSC_NET;
1929 			else
1930 				mask = IP_HOST_MASK;
1931 			mask = inet_makesubnetmask(addr, mask);
1932 		}
1933 	}
1934 	sin->sin_addr.s_addr = htonl(addr);
1935 
1936 	if (!(rcip->ri_addrs & RTA_NETMASK)) {
1937 		rcip->ri_addrs |= RTA_NETMASK;
1938 		sin = &rcip->ri_mask.sin;
1939 		sin->sin_addr.s_addr = htonl(mask);
1940 		sin->sin_family = AF_INET;
1941 	}
1942 }
1943 
1944 static in_addr_t
1945 inet_makesubnetmask(in_addr_t addr, in_addr_t mask)
1946 {
1947 	int n;
1948 	struct ifconf ifc;
1949 	struct ifreq ifreq;
1950 	struct ifreq *ifr;
1951 	struct sockaddr_in *sin;
1952 	char *buf;
1953 	int numifs;
1954 	size_t bufsize;
1955 	int iosoc;
1956 	in_addr_t if_addr, if_mask;
1957 	in_addr_t if_subnetmask = 0;
1958 	short if_flags;
1959 
1960 	if (mask == 0)
1961 		return (0);
1962 	if ((iosoc = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
1963 		quit("socket", errno);
1964 	if (ioctl(iosoc, SIOCGIFNUM, (char *)&numifs) < 0)
1965 		quit("ioctl", errno);
1966 	bufsize = numifs * sizeof (struct ifreq);
1967 	buf = malloc(bufsize);
1968 	if (buf == NULL)
1969 		quit("malloc", errno);
1970 	(void) memset(&ifc, 0, sizeof (ifc));
1971 	ifc.ifc_len = bufsize;
1972 	ifc.ifc_buf = buf;
1973 	if (ioctl(iosoc, SIOCGIFCONF, (char *)&ifc) < 0)
1974 		quit("ioctl (get interface configuration)", errno);
1975 	/* Let's check to see if this is maybe a local subnet route. */
1976 	ifr = ifc.ifc_req;
1977 	for (n = ifc.ifc_len / sizeof (struct ifreq); n > 0; n--, ifr++) {
1978 		ifreq = *ifr;
1979 		/* LINTED */
1980 		sin = (struct sockaddr_in *)&ifr->ifr_addr;
1981 		if_addr = ntohl(sin->sin_addr.s_addr);
1982 
1983 		if (ioctl(iosoc, SIOCGIFFLAGS, (char *)&ifreq) < 0)
1984 			quit("ioctl (get interface flags)", errno);
1985 		if ((ifreq.ifr_flags & IFF_UP) == 0)
1986 			continue;
1987 		if_flags = ifreq.ifr_flags;
1988 
1989 		if (ioctl(iosoc, SIOCGIFNETMASK, (char *)&ifreq) < 0)
1990 			quit("ioctl (get netmask)", errno);
1991 		/* LINTED */
1992 		sin = (struct sockaddr_in *)&ifreq.ifr_addr;
1993 		if_mask = ntohl(sin->sin_addr.s_addr);
1994 		if ((if_addr & mask) == (addr & mask)) {
1995 			/*
1996 			 * Don't trust pt-pt interfaces if there are
1997 			 * other interfaces.
1998 			 */
1999 			if (if_flags & IFF_POINTOPOINT) {
2000 				if_subnetmask = if_mask;
2001 				continue;
2002 			}
2003 			/*
2004 			 * Fine.  Just assume the same net mask as the
2005 			 * directly attached subnet interface is using.
2006 			 */
2007 			return (if_mask);
2008 		}
2009 	}
2010 	if (if_subnetmask != 0)
2011 		return (if_subnetmask);
2012 	return (mask);
2013 }
2014 
2015 /*
2016  * Interpret an argument as a network address of some kind.
2017  *
2018  * If the address family is one looked up in getaddr() using one of the
2019  * getipnodebyX() functions (currently only AF_INET6), then callers should
2020  * freehostent() the returned "struct hostent" pointer if one was passed in.
2021  *
2022  * If exit_on_error is true, this function will cause route to exit on error by
2023  * calling syntax_error().  Otherwise, it returns B_TRUE on success or B_FALSE
2024  * on failure.
2025  */
2026 static boolean_t
2027 getaddr(rtcmd_irep_t *rcip, int which, char *s, addr_type_t atype)
2028 {
2029 	su_t *su;
2030 	struct hostent **hpp;
2031 	struct hostent *hp;
2032 	int masklen;
2033 
2034 	if (which == RTA_GATEWAY) {
2035 		hpp = &(rcip->ri_gate_hp);
2036 	} else {
2037 		hpp = &hp;
2038 	}
2039 	*hpp = NULL;
2040 
2041 	rcip->ri_addrs |= which;
2042 	switch (which) {
2043 	case RTA_DST:
2044 		save_string(&rcip->ri_dest_str, s);
2045 		su = &rcip->ri_dst;
2046 		su->sa.sa_family = rcip->ri_af;
2047 		break;
2048 	case RTA_GATEWAY:
2049 		save_string(&rcip->ri_gate_str, s);
2050 		su = &rcip->ri_gate;
2051 		su->sa.sa_family = rcip->ri_af;
2052 		break;
2053 	case RTA_NETMASK:
2054 		su = &rcip->ri_mask;
2055 		su->sa.sa_family = rcip->ri_af;
2056 		break;
2057 	case RTA_IFP:
2058 		save_string(&rcip->ri_ifp_str, s);
2059 		return (B_TRUE);
2060 		/*
2061 		 * RTA_SRC has overloaded meaning. It can represent the
2062 		 * src address of incoming or outgoing packets.
2063 		 */
2064 	case RTA_IFA:
2065 		su = &rcip->ri_ifa;
2066 		su->sa.sa_family = rcip->ri_af;
2067 		break;
2068 	case RTA_SRC:
2069 		su = &rcip->ri_src;
2070 		su->sa.sa_family = rcip->ri_af;
2071 		break;
2072 	default:
2073 		/* NOTREACHED */
2074 		quit(gettext("Internal Error"), EINVAL);
2075 		/* NOTREACHED */
2076 	}
2077 	if (strcmp(s, "default") == 0) {
2078 		if (which == RTA_DST) {
2079 			return (getaddr(rcip, RTA_NETMASK, s, ADDR_TYPE_NET));
2080 		}
2081 		if (which == RTA_SRC) {
2082 			return (B_TRUE);
2083 		}
2084 		return (B_TRUE);
2085 	}
2086 	switch (rcip->ri_af) {
2087 	case AF_LINK:
2088 		link_addr(s, &su->sdl);
2089 		return (B_TRUE);
2090 	case PF_ROUTE:
2091 		sockaddr(s, &su->sa);
2092 		return (B_TRUE);
2093 	case AF_INET6:
2094 		switch (which) {
2095 		case RTA_DST:
2096 			if (!in6_getaddr(s, &su->sin6, &masklen, hpp)) {
2097 				return (B_FALSE);
2098 			}
2099 			if (masklen != NO_PREFIX) {
2100 				(void) memset(&rcip->ri_mask.sin6.sin6_addr, 0,
2101 				    sizeof (rcip->ri_mask.sin6.sin6_addr));
2102 				if (!in_prefixlentomask(masklen, IPV6_ABITS,
2103 				    (uchar_t *)&rcip->ri_mask.sin6.sin6_addr)) {
2104 					syntax_error(gettext(
2105 					    "route: bad prefix length: %d\n"),
2106 					    masklen);
2107 					return (B_FALSE);
2108 				}
2109 				rcip->ri_mask.sin6.sin6_family = rcip->ri_af;
2110 				rcip->ri_addrs |= RTA_NETMASK;
2111 			}
2112 			return (B_TRUE);
2113 		case RTA_GATEWAY:
2114 		case RTA_IFA:
2115 		case RTA_SRC:
2116 			return (in6_getaddr(s, &su->sin6, NULL, hpp));
2117 		case RTA_NETMASK:
2118 			syntax_error(
2119 			    gettext("route: -netmask not supported for IPv6: "
2120 			    "use <prefix>/<prefix-length> instead\n"));
2121 			return (B_FALSE);
2122 		default:
2123 			quit(gettext("Internal Error"), EINVAL);
2124 			/* NOTREACHED */
2125 		}
2126 	case AF_INET:
2127 		switch (which) {
2128 		case RTA_DST:
2129 			if (!in_getaddr(s, &su->sin, &masklen, which, hpp,
2130 			    atype, rcip)) {
2131 				return (B_FALSE);
2132 			}
2133 			if (masklen != NO_PREFIX) {
2134 				(void) memset(&rcip->ri_mask.sin.sin_addr, 0,
2135 				    sizeof (rcip->ri_mask.sin.sin_addr));
2136 				if (!in_prefixlentomask(masklen, IP_ABITS,
2137 				    (uchar_t *)&rcip->ri_mask.sin.sin_addr)) {
2138 					syntax_error(gettext(
2139 					    "route: bad prefix length: %d\n"),
2140 					    masklen);
2141 					return (B_FALSE);
2142 				}
2143 				rcip->ri_mask.sin.sin_family = rcip->ri_af;
2144 				rcip->ri_addrs |= RTA_NETMASK;
2145 			}
2146 			return (B_TRUE);
2147 		case RTA_GATEWAY:
2148 		case RTA_IFA:
2149 		case RTA_NETMASK:
2150 		case RTA_SRC:
2151 			return (in_getaddr(s, &su->sin, NULL, which, hpp, atype,
2152 			    rcip));
2153 		default:
2154 			quit(gettext("Internal Error"), EINVAL);
2155 			/* NOTREACHED */
2156 		}
2157 	default:
2158 		quit(gettext("Internal Error"), EINVAL);
2159 		/* NOTREACHED */
2160 	}
2161 	return (B_TRUE);
2162 }
2163 
2164 /*
2165  * Interpret an argument as an IPv4 network address of some kind,
2166  * returning B_TRUE on success or B_FALSE on failure.
2167  * This function will cause an exit() on failure if exit_on_failure is set.
2168  *
2169  * Note that this tries host interpretation before network interpretation,
2170  * except when -net has been given and the destination address is being parsed.
2171  *
2172  * If the plenp argument is non-NULL, allow <addr>/<n> syntax and
2173  * pass out <n> in *plenp.
2174  * If <n> doesn't parse return BAD_ADDR as *plenp.
2175  * If no /<n> is present return NO_PREFIX as *plenp.
2176  */
2177 static boolean_t
2178 in_getaddr(char *s, struct sockaddr_in *sin, int *plenp, int which,
2179     struct hostent **hpp, addr_type_t atype, rtcmd_irep_t *rcip)
2180 {
2181 	struct hostent *hp;
2182 	struct netent *np;
2183 	in_addr_t val;
2184 	char str[BUFSIZ];
2185 
2186 	(void) strlcpy(str, s, sizeof (str));
2187 
2188 	/*
2189 	 * If plenp is non-NULL, /<n> syntax for netmask is allowed.
2190 	 */
2191 	if (plenp != NULL) {
2192 		char *cp;
2193 
2194 		*plenp = in_getprefixlen(str, IP_ABITS);
2195 		if (*plenp == BAD_ADDR)
2196 			return (B_FALSE);
2197 		cp = strchr(str, '/');
2198 		if (cp != NULL)
2199 			*cp = '\0';
2200 	} else if (strchr(str, '/') != NULL) {
2201 		syntax_error(gettext("route: %s: unexpected '/'\n"), str);
2202 		return (B_FALSE);
2203 	}
2204 
2205 	(void) memset(sin, 0, sizeof (*sin));
2206 	sin->sin_family = AF_INET;
2207 
2208 	/*
2209 	 * Handle 255.255.255.255 as a special case first.
2210 	 */
2211 	if (strcmp(str, "255.255.255.255") == 0) {
2212 		sin->sin_addr.s_addr = INADDR_BROADCAST;
2213 		return (B_TRUE);
2214 	}
2215 
2216 	val = inet_addr(str);
2217 	if (val != (in_addr_t)-1) {
2218 		/* Numeric address */
2219 		sin->sin_addr.s_addr = val;
2220 		if (which == RTA_DST) {
2221 			if (atype == ADDR_TYPE_NET ||
2222 			    (atype == ADDR_TYPE_ANY &&
2223 			    inet_lnaof(sin->sin_addr) == INADDR_ANY)) {
2224 				/* This looks like a network address. */
2225 				inet_makenetandmask(rcip, ntohl(val),
2226 					    sin);
2227 			}
2228 		}
2229 		return (B_TRUE);
2230 	}
2231 	/* Host or net name */
2232 	if (which != RTA_DST || atype != ADDR_TYPE_NET) {
2233 		/* A host name is allowed. */
2234 		if ((hp = gethostbyname(str)) != NULL) {
2235 			*hpp = hp;
2236 			(void) memmove(&sin->sin_addr, hp->h_addr,
2237 			    hp->h_length);
2238 			return (B_TRUE);
2239 		}
2240 	}
2241 	if (atype != ADDR_TYPE_HOST) {
2242 		/* A network name is allowed */
2243 		if ((np = getnetbyname(str)) != NULL &&
2244 		    (val = np->n_net) != 0) {
2245 			if (which == RTA_DST) {
2246 				inet_makenetandmask(rcip, val, sin);
2247 			}
2248 			return (B_TRUE);
2249 		}
2250 	}
2251 	syntax_error(gettext("%s: bad value\n"), s);
2252 	return (B_FALSE);
2253 }
2254 
2255 /*
2256  * Interpret an argument as an IPv6 network address of some kind,
2257  * returning B_TRUE on success or B_FALSE on failure.
2258  * This function will cause an exit() on failure if exit_on_failure is set.
2259  *
2260  * If the last argument is non-NULL allow a <addr>/<n> syntax and
2261  * pass out <n> in *plenp.
2262  * If <n> doesn't parse return BAD_ADDR as *plenp.
2263  * If no /<n> is present return NO_PREFIX as *plenp.
2264  */
2265 static boolean_t
2266 in6_getaddr(char *s, struct sockaddr_in6 *sin6, int *plenp,
2267     struct hostent **hpp)
2268 {
2269 	struct hostent *hp;
2270 	char str[BUFSIZ];
2271 	int error_num;
2272 
2273 	(void) strlcpy(str, s, sizeof (str));
2274 
2275 	/*
2276 	 * If plenp is non-NULL, /<n> syntax for netmask is allowed.
2277 	 */
2278 	if (plenp != NULL) {
2279 		char *cp;
2280 
2281 		*plenp = in_getprefixlen(str, IPV6_ABITS);
2282 		if (*plenp == BAD_ADDR)
2283 			return (B_FALSE);
2284 		cp = strchr(str, '/');
2285 		if (cp != NULL)
2286 			*cp = '\0';
2287 	} else if (strchr(str, '/') != NULL) {
2288 		syntax_error(gettext("route: %s: unexpected '/'\n"), str);
2289 		return (B_FALSE);
2290 	}
2291 
2292 	(void) memset(sin6, 0, sizeof (struct sockaddr_in6));
2293 	sin6->sin6_family = AF_INET6;
2294 
2295 	hp = getipnodebyname(str, AF_INET6, 0, &error_num);
2296 	if (hp != NULL) {
2297 		*hpp = hp;
2298 		(void) memmove(&sin6->sin6_addr, hp->h_addr, hp->h_length);
2299 		return (B_TRUE);
2300 	}
2301 	if (error_num == TRY_AGAIN) {
2302 		/*
2303 		 * This isn't a problem if we aren't going to use the address
2304 		 * right away.
2305 		 */
2306 		if (!exit_on_error) {
2307 			return (B_TRUE);
2308 		}
2309 		syntax_error(gettext("route: %s: bad address (try "
2310 		    "again later)\n"), s);
2311 		return (B_FALSE);
2312 	}
2313 	syntax_error(gettext("route: %s: bad address\n"), s);
2314 	return (B_FALSE);
2315 }
2316 
2317 /*
2318  * Parse <addr>/<n> syntax and return the integer n.
2319  * If <addr> is missing or <n> is not a valid integer, this function calls
2320  * syntax_error() and returns BAD_ADDR.
2321  * if n is not between 0 and max_plen inclusive, this functions calls
2322  * syntax_error() and returns BAD_ADDR.
2323  * If /<n> is not present, this function returns NO_PREFIX.
2324  * The string addr is not modified.
2325  */
2326 int
2327 in_getprefixlen(char *addr, int max_plen)
2328 {
2329 	int prefixlen;
2330 	char *str, *end;
2331 
2332 	str = strchr(addr, '/');
2333 	if (str == addr) {
2334 		syntax_error(gettext("route: %s: unexpected '/'\n"), addr);
2335 		return (BAD_ADDR);
2336 	}
2337 	if (str == NULL)
2338 		return (NO_PREFIX);
2339 	str++;
2340 
2341 	errno = 0;
2342 	prefixlen = strtoul(str, &end, 10);
2343 	if (errno != 0 || str == end) {
2344 		syntax_error(gettext("route: bad prefix length %s\n"), str);
2345 		return (BAD_ADDR);
2346 	}
2347 	if (prefixlen > max_plen) {
2348 		syntax_error(gettext("route: prefix length %s out of range\n"),
2349 		    str);
2350 		return (BAD_ADDR);
2351 	}
2352 	return (prefixlen);
2353 }
2354 
2355 /*
2356  * Convert a prefix length to a mask.
2357  * Returns B_TRUE if ok. B_FALSE otherwise.
2358  * Assumes the mask array is zeroed by the caller.
2359  */
2360 boolean_t
2361 in_prefixlentomask(int prefixlen, int maxlen, uchar_t *mask)
2362 {
2363 	if (prefixlen < 0 || prefixlen > maxlen)
2364 		return (B_FALSE);
2365 
2366 	while (prefixlen > 0) {
2367 		if (prefixlen >= 8) {
2368 			*mask++ = 0xFF;
2369 			prefixlen -= 8;
2370 			continue;
2371 		}
2372 		*mask |= 1 << (8 - prefixlen);
2373 		prefixlen--;
2374 	}
2375 	return (B_TRUE);
2376 }
2377 
2378 void
2379 rtmonitor(int argc, char *argv[])
2380 {
2381 	int n;
2382 	intmax_t msg[2048 / sizeof (intmax_t)];
2383 
2384 	if (tflag)
2385 		exit(0);
2386 	verbose = B_TRUE;
2387 	if (argc > 1) {
2388 		argv++;
2389 		if (argc == 2 && **argv == '-') {
2390 			switch (keyword(*argv + 1)) {
2391 			case K_INET:
2392 				af = AF_INET;
2393 				break;
2394 			case K_LINK:
2395 				af = AF_LINK;
2396 				break;
2397 			case K_INET6:
2398 				af = AF_INET6;
2399 				break;
2400 			default:
2401 				usage(*argv);
2402 				/* NOTREACHED */
2403 			}
2404 		} else {
2405 			usage(*argv);
2406 		}
2407 		(void) close(s);
2408 		s = socket(PF_ROUTE, SOCK_RAW, af);
2409 		if (s < 0)
2410 			quit("socket", errno);
2411 	}
2412 	for (;;) {
2413 		n = read(s, msg, sizeof (msg));
2414 		if (n <= 0)
2415 			quit("read", errno);
2416 		(void) printf("got message of size %d\n", n);
2417 		print_rtmsg((struct rt_msghdr *)msg, n);
2418 	}
2419 }
2420 
2421 int
2422 rtmsg(rtcmd_irep_t *newrt)
2423 {
2424 	static int seq;
2425 	int rlen;
2426 	char *cp = m_rtmsg.m_space;
2427 	int l;
2428 
2429 	errno = 0;
2430 	(void) memset(&m_rtmsg, 0, sizeof (m_rtmsg));
2431 
2432 	if (newrt->ri_cmd == RTM_GET) {
2433 		newrt->ri_ifp.sa.sa_family = AF_LINK;
2434 		newrt->ri_addrs |= RTA_IFP;
2435 	}
2436 
2437 #define	rtm m_rtmsg.m_rtm
2438 	rtm.rtm_type = newrt->ri_cmd;
2439 	rtm.rtm_flags = newrt->ri_flags;
2440 	rtm.rtm_version = RTM_VERSION;
2441 	rtm.rtm_seq = ++seq;
2442 	rtm.rtm_addrs = newrt->ri_addrs;
2443 	rtm.rtm_rmx = newrt->ri_metrics;
2444 	rtm.rtm_inits = newrt->ri_inits;
2445 
2446 #define	NEXTADDR(w, u) \
2447 	if (newrt->ri_addrs & (w)) { \
2448 		l = ROUNDUP_LONG(salen(&u.sa)); \
2449 		(void) memmove(cp, &(u), l); \
2450 		cp += l; \
2451 		if (verbose) \
2452 			sodump(&(u), #u); \
2453 	}
2454 	NEXTADDR(RTA_DST, newrt->ri_dst);
2455 	NEXTADDR(RTA_GATEWAY, newrt->ri_gate);
2456 	NEXTADDR(RTA_NETMASK, newrt->ri_mask);
2457 	NEXTADDR(RTA_IFP, newrt->ri_ifp);
2458 	NEXTADDR(RTA_IFA, newrt->ri_ifa);
2459 	/*
2460 	 * RTA_SRC has overloaded meaning. It can represent the
2461 	 * src address of incoming or outgoing packets.
2462 	 */
2463 	NEXTADDR(RTA_SRC, newrt->ri_src);
2464 #undef	NEXTADDR
2465 
2466 	if (newrt->ri_rtsa_cnt > 0) {
2467 		/* LINTED: aligned */
2468 		rtm_ext_t *rtm_ext = (rtm_ext_t *)cp;
2469 		tsol_rtsecattr_t *rtsecattr;
2470 
2471 		rtm_ext->rtmex_type = RTMEX_GATEWAY_SECATTR;
2472 		rtm_ext->rtmex_len = TSOL_RTSECATTR_SIZE(1);
2473 
2474 		rtsecattr = (tsol_rtsecattr_t *)(rtm_ext + 1);
2475 		rtsecattr->rtsa_cnt = 1;
2476 
2477 		bcopy(&newrt->ri_rtsa, rtsecattr->rtsa_attr,
2478 		    sizeof (newrt->ri_rtsa));
2479 		cp = (char *)(rtsecattr->rtsa_attr + 1);
2480 	}
2481 
2482 	rtm.rtm_msglen = l = cp - (char *)&m_rtmsg;
2483 
2484 	if (verbose)
2485 		print_rtmsg(&rtm, l);
2486 	if (debugonly)
2487 		return (0);
2488 	if ((rlen = write(s, (char *)&m_rtmsg, l)) < 0) {
2489 		switch (errno) {
2490 		case ESRCH:
2491 		case EBUSY:
2492 		case ENOBUFS:
2493 		case EEXIST:
2494 		case ENETUNREACH:
2495 		case EHOSTUNREACH:
2496 		case EPERM:
2497 			break;
2498 		default:
2499 			perror(gettext("writing to routing socket"));
2500 			break;
2501 		}
2502 		return (-1);
2503 	} else if (rlen < (int)rtm.rtm_msglen) {
2504 		(void) fprintf(stderr,
2505 		    gettext("route: write to routing socket got only %d for "
2506 		    "len\n"), rlen);
2507 		return (-1);
2508 	}
2509 	if (newrt->ri_cmd == RTM_GET) {
2510 		do {
2511 			l = read(s, (char *)&m_rtmsg, sizeof (m_rtmsg));
2512 		} while (l > 0 && (rtm.rtm_seq != seq || rtm.rtm_pid != pid));
2513 		if (l < 0) {
2514 			(void) fprintf(stderr,
2515 			    gettext("route: read from routing socket: %s\n"),
2516 			    strerror(errno));
2517 		} else {
2518 			print_getmsg(newrt, &rtm, l);
2519 		}
2520 	}
2521 #undef rtm
2522 	return (0);
2523 }
2524 
2525 static char *msgtypes[] = {
2526 	"",
2527 	"RTM_ADD: Add Route",
2528 	"RTM_DELETE: Delete Route",
2529 	"RTM_CHANGE: Change Metrics or flags",
2530 	"RTM_GET: Report Metrics",
2531 	"RTM_LOSING: Kernel Suspects Partitioning",
2532 	"RTM_REDIRECT: Told to use different route",
2533 	"RTM_MISS: Lookup failed on this address",
2534 	"RTM_LOCK: fix specified metrics",
2535 	"RTM_OLDADD: caused by SIOCADDRT",
2536 	"RTM_OLDDEL: caused by SIOCDELRT",
2537 	"RTM_RESOLVE: Route created by cloning",
2538 	"RTM_NEWADDR: address being added to iface",
2539 	"RTM_DELADDR: address being removed from iface",
2540 	"RTM_IFINFO: iface status change",
2541 	0,
2542 };
2543 
2544 #define	NMSGTYPES (sizeof (msgtypes) / sizeof (msgtypes[0]))
2545 
2546 static char metricnames[] =
2547 "\011pksent\010rttvar\7rtt\6ssthresh\5sendpipe\4recvpipe\3expire\2hopcount"
2548 	"\1mtu";
2549 static char routeflags[] =
2550 "\1UP\2GATEWAY\3HOST\4REJECT\5DYNAMIC\6MODIFIED\7DONE\010MASK_PRESENT"
2551 	"\011CLONING\012XRESOLVE\013LLINFO\014STATIC\015BLACKHOLE"
2552 	"\016PRIVATE\017PROTO2\020PROTO1\021MULTIRT\022SETSRC";
2553 static char ifnetflags[] =
2554 "\1UP\2BROADCAST\3DEBUG\4LOOPBACK\5PTP\6NOTRAILERS\7RUNNING\010NOARP"
2555 	"\011PPROMISC\012ALLMULTI\013INTELLIGENT\014MULTICAST"
2556 	"\015MULTI_BCAST\016UNNUMBERED\017DHCP\020PRIVATE"
2557 	"\021NOXMIT\022NOLOCAL\023DEPRECATED\024ADDRCONF"
2558 	"\025ROUTER\026NONUD\027ANYCAST\030NORTEXCH\031IPv4\032IPv6"
2559 	"\033MIP\034NOFAILOVER\035FAILED\036STANDBY\037INACTIVE\040OFFLINE"
2560 	"\041XRESOLV\042COS\043PREFERRED\044TEMPORARY";
2561 static char addrnames[] =
2562 "\1DST\2GATEWAY\3NETMASK\4GENMASK\5IFP\6IFA\7AUTHOR\010BRD\011SRC";
2563 
2564 void
2565 print_rtmsg(struct rt_msghdr *rtm, int msglen)
2566 {
2567 	struct if_msghdr *ifm;
2568 	struct ifa_msghdr *ifam;
2569 
2570 	if (!verbose)
2571 		return;
2572 	if (rtm->rtm_version != RTM_VERSION) {
2573 		(void) printf("routing message version %d not understood\n",
2574 		    rtm->rtm_version);
2575 		return;
2576 	}
2577 	if (rtm->rtm_msglen != msglen) {
2578 		(void) printf("message length mismatch, in packet %d, "
2579 		    "returned %d\n",
2580 		    rtm->rtm_msglen, msglen);
2581 		if (msglen > rtm->rtm_msglen)
2582 			msglen = rtm->rtm_msglen;
2583 	}
2584 	/*
2585 	 * Since rtm->rtm_type is unsigned, we'll just check the case of zero
2586 	 * and the upper-bound of (NMSGTYPES - 1).
2587 	 */
2588 	if (rtm->rtm_type == 0 || rtm->rtm_type >= (NMSGTYPES - 1)) {
2589 		(void) printf("routing message type %d not understood\n",
2590 		    rtm->rtm_type);
2591 		return;
2592 	}
2593 	(void) printf("%s: len %d, ", msgtypes[rtm->rtm_type], msglen);
2594 	switch (rtm->rtm_type) {
2595 	case RTM_IFINFO:
2596 		ifm = (struct if_msghdr *)rtm;
2597 		(void) printf("if# %d, flags:", ifm->ifm_index);
2598 		bprintf(stdout, ifm->ifm_flags, ifnetflags);
2599 		pmsg_addrs((const char *)(ifm + 1), msglen - sizeof (*ifm),
2600 		    ifm->ifm_addrs);
2601 		break;
2602 	case RTM_NEWADDR:
2603 	case RTM_DELADDR:
2604 		ifam = (struct ifa_msghdr *)rtm;
2605 		(void) printf("metric %d, flags:", ifam->ifam_metric);
2606 		bprintf(stdout, ifam->ifam_flags, routeflags);
2607 		pmsg_addrs((const char *)(ifam + 1), msglen - sizeof (*ifam),
2608 		    ifam->ifam_addrs);
2609 		break;
2610 	default:
2611 		(void) printf("pid: %ld, seq %d, errno %d, flags:",
2612 			rtm->rtm_pid, rtm->rtm_seq, rtm->rtm_errno);
2613 		bprintf(stdout, rtm->rtm_flags, routeflags);
2614 		pmsg_common(rtm, msglen);
2615 		break;
2616 	}
2617 }
2618 
2619 void
2620 print_getmsg(rtcmd_irep_t *req_rt, struct rt_msghdr *rtm, int msglen)
2621 {
2622 	struct sockaddr *dst = NULL, *gate = NULL, *mask = NULL, *src = NULL;
2623 	struct sockaddr_dl *ifp = NULL;
2624 	struct sockaddr *sa;
2625 	char *cp;
2626 	int i;
2627 
2628 	(void) printf("   route to: %s\n", routename(&req_rt->ri_dst.sa));
2629 	if (rtm->rtm_version != RTM_VERSION) {
2630 		(void) fprintf(stderr,
2631 		    gettext("routing message version %d not understood\n"),
2632 		    rtm->rtm_version);
2633 		return;
2634 	}
2635 	if (rtm->rtm_msglen > (ushort_t)msglen) {
2636 		(void) fprintf(stderr,
2637 		    gettext("message length mismatch, in packet %d, "
2638 			"returned %d\n"), rtm->rtm_msglen, msglen);
2639 	}
2640 	if (rtm->rtm_errno)  {
2641 		(void) fprintf(stderr, "RTM_GET: %s (errno %d)\n",
2642 		    strerror(rtm->rtm_errno), rtm->rtm_errno);
2643 		return;
2644 	}
2645 	cp = ((char *)(rtm + 1));
2646 	if (rtm->rtm_addrs != 0) {
2647 		for (i = 1; i != 0; i <<= 1) {
2648 			if (i & rtm->rtm_addrs) {
2649 				/* LINTED */
2650 				sa = (struct sockaddr *)cp;
2651 				switch (i) {
2652 				case RTA_DST:
2653 					dst = sa;
2654 					break;
2655 				case RTA_GATEWAY:
2656 					gate = sa;
2657 					break;
2658 				case RTA_NETMASK:
2659 					mask = sa;
2660 					break;
2661 				case RTA_IFP:
2662 					if (sa->sa_family == AF_LINK &&
2663 					    ((struct sockaddr_dl *)sa)->
2664 						sdl_nlen != 0)
2665 						ifp = (struct sockaddr_dl *)sa;
2666 					break;
2667 				case RTA_SRC:
2668 					src = sa;
2669 					break;
2670 				}
2671 				ADVANCE(cp, sa);
2672 			}
2673 		}
2674 	}
2675 	if (dst != NULL && mask != NULL)
2676 		mask->sa_family = dst->sa_family;	/* XXX */
2677 	if (dst != NULL)
2678 		(void) printf("destination: %s\n", routename(dst));
2679 	if (mask != NULL) {
2680 		boolean_t savenflag = nflag;
2681 
2682 		nflag = B_TRUE;
2683 		(void) printf("       mask: %s\n", routename(mask));
2684 		nflag = savenflag;
2685 	}
2686 	if (gate != NULL && rtm->rtm_flags & RTF_GATEWAY)
2687 		(void) printf("    gateway: %s\n", routename(gate));
2688 	if (src != NULL && rtm->rtm_flags & RTF_SETSRC)
2689 		(void) printf("     setsrc: %s\n", routename(src));
2690 	if (ifp != NULL) {
2691 		if (verbose) {
2692 			int i;
2693 
2694 			(void) printf("  interface: %.*s index %d address ",
2695 			    ifp->sdl_nlen, ifp->sdl_data, ifp->sdl_index);
2696 			for (i = ifp->sdl_nlen;
2697 			    i < ifp->sdl_nlen + ifp->sdl_alen;
2698 			    i++) {
2699 				(void) printf("%02x ",
2700 				    ifp->sdl_data[i] & 0xFF);
2701 			}
2702 			(void) printf("\n");
2703 		} else {
2704 			(void) printf("  interface: %.*s\n",
2705 			    ifp->sdl_nlen, ifp->sdl_data);
2706 		}
2707 	}
2708 	(void) printf("      flags: ");
2709 	bprintf(stdout, rtm->rtm_flags, routeflags);
2710 
2711 #define	lock(f)	((rtm->rtm_rmx.rmx_locks & RTV_ ## f) ? 'L' : ' ')
2712 #define	msec(u)	(((u) + 500) / 1000)		/* usec to msec */
2713 
2714 	(void) printf("\n%s\n", " recvpipe  sendpipe  ssthresh    rtt,ms "
2715 	    "rttvar,ms  hopcount      mtu     expire");
2716 	(void) printf("%8d%c ", rtm->rtm_rmx.rmx_recvpipe, lock(RPIPE));
2717 	(void) printf("%8d%c ", rtm->rtm_rmx.rmx_sendpipe, lock(SPIPE));
2718 	(void) printf("%8d%c ", rtm->rtm_rmx.rmx_ssthresh, lock(SSTHRESH));
2719 	(void) printf("%8d%c ", msec(rtm->rtm_rmx.rmx_rtt), lock(RTT));
2720 	(void) printf("%8d%c ", msec(rtm->rtm_rmx.rmx_rttvar), lock(RTTVAR));
2721 	(void) printf("%8d%c ", rtm->rtm_rmx.rmx_hopcount, lock(HOPCOUNT));
2722 	(void) printf("%8d%c ", rtm->rtm_rmx.rmx_mtu, lock(MTU));
2723 	if (rtm->rtm_rmx.rmx_expire)
2724 		rtm->rtm_rmx.rmx_expire -= time(0);
2725 	(void) printf("%8d%c", rtm->rtm_rmx.rmx_expire, lock(EXPIRE));
2726 #undef lock
2727 #undef msec
2728 #define	RTA_IGN	\
2729 	(RTA_DST|RTA_GATEWAY|RTA_NETMASK|RTA_IFP|RTA_IFA|RTA_BRD|RTA_SRC)
2730 	if (verbose) {
2731 		pmsg_common(rtm, msglen);
2732 	} else {
2733 		const char *sptr, *endptr;
2734 		const struct sockaddr *sa;
2735 		uint_t addrs;
2736 
2737 		/* Not verbose; just print out the exceptional cases */
2738 		if (rtm->rtm_addrs &~ RTA_IGN) {
2739 			(void) printf("\nsockaddrs: ");
2740 			bprintf(stdout, rtm->rtm_addrs, addrnames);
2741 		}
2742 		sptr = (const char *)(rtm + 1);
2743 		endptr = (const char *)rtm + msglen;
2744 		addrs = rtm->rtm_addrs;
2745 		while (addrs != 0 && sptr + sizeof (*sa) <= endptr) {
2746 			addrs &= addrs - 1;
2747 			/* LINTED */
2748 			sa = (const struct sockaddr *)sptr;
2749 			ADVANCE(sptr, sa);
2750 		}
2751 		if (addrs == 0)
2752 			pmsg_secattr(sptr, endptr - sptr, "    secattr: ");
2753 		(void) putchar('\n');
2754 	}
2755 #undef	RTA_IGN
2756 }
2757 
2758 static void
2759 pmsg_common(const struct rt_msghdr *rtm, size_t msglen)
2760 {
2761 	(void) printf("\nlocks: ");
2762 	bprintf(stdout, (int)rtm->rtm_rmx.rmx_locks, metricnames);
2763 	(void) printf(" inits: ");
2764 	bprintf(stdout, (int)rtm->rtm_inits, metricnames);
2765 	pmsg_addrs((const char *)(rtm + 1), msglen - sizeof (*rtm),
2766 	    rtm->rtm_addrs);
2767 }
2768 
2769 static void
2770 pmsg_addrs(const char *cp, size_t msglen, uint_t addrs)
2771 {
2772 	const struct sockaddr *sa;
2773 	const char *maxptr;
2774 	int i;
2775 
2776 	if (addrs != 0) {
2777 		(void) printf("\nsockaddrs: ");
2778 		bprintf(stdout, addrs, addrnames);
2779 		(void) putchar('\n');
2780 		maxptr = cp + msglen;
2781 		for (i = 1; i != 0 && cp + sizeof (*sa) <= maxptr; i <<= 1) {
2782 			if (i & addrs) {
2783 				/* LINTED */
2784 				sa = (const struct sockaddr *)cp;
2785 				(void) printf(" %s", routename(sa));
2786 				ADVANCE(cp, sa);
2787 			}
2788 		}
2789 		if (i != 0)
2790 			msglen = 0;
2791 		else
2792 			msglen = maxptr - cp;
2793 	}
2794 	pmsg_secattr(cp, msglen, "secattr: ");
2795 	(void) putchar('\n');
2796 	(void) fflush(stdout);
2797 }
2798 
2799 void
2800 bprintf(FILE *fp, int b, char *s)
2801 {
2802 	int i;
2803 	boolean_t gotsome = B_FALSE;
2804 
2805 	if (b == 0)
2806 		return;
2807 	while ((i = *s++) != 0) {
2808 		if (b & (1 << (i - 1))) {
2809 			if (!gotsome)
2810 				i = '<';
2811 			else
2812 				i = ',';
2813 			(void) putc(i, fp);
2814 			gotsome = B_TRUE;
2815 			for (; (i = *s) > ' '; s++)
2816 				(void) putc(i, fp);
2817 		} else {
2818 			while (*s > ' ')
2819 				s++;
2820 		}
2821 	}
2822 	if (gotsome)
2823 		(void) putc('>', fp);
2824 }
2825 
2826 int
2827 keyword(const char *cp)
2828 {
2829 	struct keytab *kt = keywords;
2830 
2831 	while (kt->kt_cp && strcmp(kt->kt_cp, cp))
2832 		kt++;
2833 	return (kt->kt_i);
2834 }
2835 
2836 void
2837 sodump(su_t *su, char *which)
2838 {
2839 	static char obuf[INET6_ADDRSTRLEN];
2840 
2841 	switch (su->sa.sa_family) {
2842 	case AF_LINK:
2843 		(void) printf("%s: link %s; ",
2844 		    which, link_ntoa(&su->sdl));
2845 		break;
2846 	case AF_INET:
2847 		(void) printf("%s: inet %s; ",
2848 		    which, inet_ntoa(su->sin.sin_addr));
2849 		break;
2850 	case AF_INET6:
2851 		if (inet_ntop(AF_INET6, (void *)&su->sin6.sin6_addr, obuf,
2852 		    INET6_ADDRSTRLEN) != NULL) {
2853 			(void) printf("%s: inet6 %s; ", which, obuf);
2854 			break;
2855 		}
2856 		/* FALLTHROUGH */
2857 	default:
2858 		quit(gettext("Internal Error"), EINVAL);
2859 		/* NOTREACHED */
2860 	}
2861 	(void) fflush(stdout);
2862 }
2863 
2864 /* States */
2865 #define	VIRGIN	0
2866 #define	GOTONE	1
2867 #define	GOTTWO	2
2868 #define	RESET	3
2869 /* Inputs */
2870 #define	DIGIT	(4*0)
2871 #define	END	(4*1)
2872 #define	DELIM	(4*2)
2873 #define	LETTER	(4*3)
2874 
2875 void
2876 sockaddr(char *addr, struct sockaddr *sa)
2877 {
2878 	char *cp = (char *)sa;
2879 	int size = salen(sa);
2880 	char *cplim = cp + size;
2881 	int byte = 0, state = VIRGIN, new;
2882 
2883 	(void) memset(cp, 0, size);
2884 	cp++;
2885 	do {
2886 		if ((*addr >= '0') && (*addr <= '9')) {
2887 			new = *addr - '0';
2888 		} else if ((*addr >= 'a') && (*addr <= 'f')) {
2889 			new = *addr - 'a' + 10;
2890 		} else if ((*addr >= 'A') && (*addr <= 'F')) {
2891 			new = *addr - 'A' + 10;
2892 		} else if (*addr == 0) {
2893 			state |= END;
2894 		} else {
2895 			state |= DELIM;
2896 		}
2897 		addr++;
2898 		switch (state /* | INPUT */) {
2899 		case GOTTWO | DIGIT:
2900 			*cp++ = byte;
2901 			/* FALLTHROUGH */
2902 		case VIRGIN | DIGIT:
2903 			state = GOTONE; byte = new; continue;
2904 		case GOTONE | DIGIT:
2905 			state = GOTTWO; byte = new + (byte << 4); continue;
2906 		default: /* | DELIM */
2907 			state = VIRGIN; *cp++ = byte; byte = 0; continue;
2908 		case GOTONE | END:
2909 		case GOTTWO | END:
2910 			*cp++ = byte;
2911 			/* FALLTHROUGH */
2912 		case VIRGIN | END:
2913 			break;
2914 		}
2915 		break;
2916 	} while (cp < cplim);
2917 }
2918 
2919 int
2920 salen(const struct sockaddr *sa)
2921 {
2922 	switch (sa->sa_family) {
2923 	case AF_INET:
2924 		return (sizeof (struct sockaddr_in));
2925 	case AF_LINK:
2926 		return (sizeof (struct sockaddr_dl));
2927 	case AF_INET6:
2928 		return (sizeof (struct sockaddr_in6));
2929 	default:
2930 		return (sizeof (struct sockaddr));
2931 	}
2932 }
2933 
2934 void
2935 link_addr(const char *addr, struct sockaddr_dl *sdl)
2936 {
2937 	char *cp = sdl->sdl_data;
2938 	char *cplim = sizeof (struct sockaddr_dl) + (char *)sdl;
2939 	int byte = 0, state = VIRGIN, new;
2940 
2941 	(void) memset(sdl, 0, sizeof (struct sockaddr_dl));
2942 	sdl->sdl_family = AF_LINK;
2943 	do {
2944 		state &= ~LETTER;
2945 		if ((*addr >= '0') && (*addr <= '9')) {
2946 			new = *addr - '0';
2947 		} else if ((*addr >= 'a') && (*addr <= 'f')) {
2948 			new = *addr - 'a' + 10;
2949 		} else if ((*addr >= 'A') && (*addr <= 'F')) {
2950 			new = *addr - 'A' + 10;
2951 		} else if (*addr == 0) {
2952 			state |= END;
2953 		} else if (state == VIRGIN &&
2954 		    (((*addr >= 'A') && (*addr <= 'Z')) ||
2955 		    ((*addr >= 'a') && (*addr <= 'z')))) {
2956 			state |= LETTER;
2957 		} else {
2958 			state |= DELIM;
2959 		}
2960 		addr++;
2961 		switch (state /* | INPUT */) {
2962 		case VIRGIN | DIGIT:
2963 		case VIRGIN | LETTER:
2964 			*cp++ = addr[-1];
2965 			continue;
2966 		case VIRGIN | DELIM:
2967 			state = RESET;
2968 			sdl->sdl_nlen = cp - sdl->sdl_data;
2969 			continue;
2970 		case GOTTWO | DIGIT:
2971 			*cp++ = byte;
2972 			/* FALLTHROUGH */
2973 		case RESET | DIGIT:
2974 			state = GOTONE;
2975 			byte = new;
2976 			continue;
2977 		case GOTONE | DIGIT:
2978 			state = GOTTWO;
2979 			byte = new + (byte << 4);
2980 			continue;
2981 		default: /* | DELIM */
2982 			state = RESET;
2983 			*cp++ = byte;
2984 			byte = 0;
2985 			continue;
2986 		case GOTONE | END:
2987 		case GOTTWO | END:
2988 			*cp++ = byte;
2989 			/* FALLTHROUGH */
2990 		case RESET | END:
2991 			break;
2992 		}
2993 		break;
2994 	} while (cp < cplim);
2995 	sdl->sdl_alen = cp - LLADDR(sdl);
2996 }
2997 
2998 static char hexlist[] = "0123456789abcdef";
2999 
3000 char *
3001 link_ntoa(const struct sockaddr_dl *sdl)
3002 {
3003 	static char obuf[64];
3004 	char *out = obuf;
3005 	int i;
3006 	uchar_t *in = (uchar_t *)LLADDR(sdl);
3007 	uchar_t *inlim = in + sdl->sdl_alen;
3008 	boolean_t firsttime = B_TRUE;
3009 
3010 	if (sdl->sdl_nlen) {
3011 		(void) memcpy(obuf, sdl->sdl_data, sdl->sdl_nlen);
3012 		out += sdl->sdl_nlen;
3013 		if (sdl->sdl_alen)
3014 			*out++ = ':';
3015 	}
3016 	while (in < inlim) {
3017 		if (firsttime)
3018 			firsttime = B_FALSE;
3019 		else
3020 			*out++ = '.';
3021 		i = *in++;
3022 		if (i > 0xf) {
3023 			out[1] = hexlist[i & 0xf];
3024 			i >>= 4;
3025 			out[0] = hexlist[i];
3026 			out += 2;
3027 		} else {
3028 			*out++ = hexlist[i];
3029 		}
3030 	}
3031 	*out = 0;
3032 	return (obuf);
3033 }
3034 
3035 static mib_item_t *
3036 mibget(int sd)
3037 {
3038 	intmax_t		buf[512 / sizeof (intmax_t)];
3039 	int			flags;
3040 	int			i, j, getcode;
3041 	struct strbuf		ctlbuf, databuf;
3042 	struct T_optmgmt_req	*tor = (struct T_optmgmt_req *)buf;
3043 	struct T_optmgmt_ack	*toa = (struct T_optmgmt_ack *)buf;
3044 	struct T_error_ack	*tea = (struct T_error_ack *)buf;
3045 	struct opthdr		*req;
3046 	mib_item_t		*first_item = NULL;
3047 	mib_item_t		*last_item  = NULL;
3048 	mib_item_t		*temp;
3049 
3050 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
3051 	tor->OPT_offset = sizeof (struct T_optmgmt_req);
3052 	tor->OPT_length = sizeof (struct opthdr);
3053 	tor->MGMT_flags = T_CURRENT;
3054 	req = (struct opthdr *)&tor[1];
3055 	req->level = MIB2_IP;		/* any MIB2_xxx value ok here */
3056 	req->name  = 0;
3057 	req->len   = 0;
3058 
3059 	ctlbuf.buf = (char *)buf;
3060 	ctlbuf.len = tor->OPT_length + tor->OPT_offset;
3061 	flags = 0;
3062 	if (putmsg(sd, &ctlbuf, NULL, flags) < 0) {
3063 		perror("mibget: putmsg (ctl)");
3064 		return (NULL);
3065 	}
3066 	/*
3067 	 * each reply consists of a ctl part for one fixed structure
3068 	 * or table, as defined in mib2.h.  The format is a T_OPTMGMT_ACK,
3069 	 * containing an opthdr structure.  level/name identify the entry,
3070 	 * len is the size of the data part of the message.
3071 	 */
3072 	req = (struct opthdr *)&toa[1];
3073 	ctlbuf.maxlen = sizeof (buf);
3074 	for (j = 1; ; j++) {
3075 		flags = 0;
3076 		getcode = getmsg(sd, &ctlbuf, NULL, &flags);
3077 		if (getcode < 0) {
3078 			perror("mibget: getmsg (ctl)");
3079 			if (verbose) {
3080 				(void) fprintf(stderr,
3081 				    "#   level   name    len\n");
3082 				i = 0;
3083 				for (last_item = first_item; last_item != NULL;
3084 				    last_item = last_item->next_item) {
3085 					(void) printf("%d  %4ld   %5ld   %ld\n",
3086 					    ++i, last_item->group,
3087 					    last_item->mib_id,
3088 					    last_item->length);
3089 				}
3090 			}
3091 			break;
3092 		}
3093 		if (getcode == 0 &&
3094 		    ctlbuf.len >= sizeof (struct T_optmgmt_ack) &&
3095 		    toa->PRIM_type == T_OPTMGMT_ACK &&
3096 		    toa->MGMT_flags == T_SUCCESS &&
3097 		    req->len == 0) {
3098 			if (verbose) {
3099 				(void) printf("mibget getmsg() %d returned EOD "
3100 				    "(level %lu, name %lu)\n", j, req->level,
3101 				    req->name);
3102 			}
3103 			return (first_item);		/* this is EOD msg */
3104 		}
3105 
3106 		if (ctlbuf.len >= sizeof (struct T_error_ack) &&
3107 		    tea->PRIM_type == T_ERROR_ACK) {
3108 			(void) fprintf(stderr, gettext("mibget %d gives "
3109 			    "T_ERROR_ACK: TLI_error = 0x%lx, UNIX_error = "
3110 			    "0x%lx\n"), j, tea->TLI_error, tea->UNIX_error);
3111 			errno = (tea->TLI_error == TSYSERR)
3112 				? tea->UNIX_error : EPROTO;
3113 			break;
3114 		}
3115 
3116 		if (getcode != MOREDATA ||
3117 		    ctlbuf.len < sizeof (struct T_optmgmt_ack) ||
3118 		    toa->PRIM_type != T_OPTMGMT_ACK ||
3119 		    toa->MGMT_flags != T_SUCCESS) {
3120 			(void) printf("mibget getmsg(ctl) %d returned %d, "
3121 			    "ctlbuf.len = %d, PRIM_type = %ld\n",
3122 			    j, getcode, ctlbuf.len, toa->PRIM_type);
3123 			if (toa->PRIM_type == T_OPTMGMT_ACK) {
3124 				(void) printf("T_OPTMGMT_ACK: "
3125 				    "MGMT_flags = 0x%lx, req->len = %ld\n",
3126 				    toa->MGMT_flags, req->len);
3127 			}
3128 			errno = ENOMSG;
3129 			break;
3130 		}
3131 
3132 		temp = malloc(sizeof (mib_item_t));
3133 		if (temp == NULL) {
3134 			perror("mibget: malloc");
3135 			break;
3136 		}
3137 		if (last_item != NULL)
3138 			last_item->next_item = temp;
3139 		else
3140 			first_item = temp;
3141 		last_item = temp;
3142 		last_item->next_item = NULL;
3143 		last_item->group = req->level;
3144 		last_item->mib_id = req->name;
3145 		last_item->length = req->len;
3146 		last_item->valp = malloc(req->len);
3147 		if (verbose) {
3148 			(void) printf("msg %d:  group = %4ld   mib_id = %5ld   "
3149 			    "length = %ld\n",
3150 			    j, last_item->group, last_item->mib_id,
3151 			    last_item->length);
3152 		}
3153 
3154 		databuf.maxlen = last_item->length;
3155 		databuf.buf    = (char *)last_item->valp;
3156 		databuf.len    = 0;
3157 		flags = 0;
3158 		getcode = getmsg(sd, NULL, &databuf, &flags);
3159 		if (getcode < 0) {
3160 			perror("mibget: getmsg (data)");
3161 			break;
3162 		} else if (getcode != 0) {
3163 			(void) printf("mibget getmsg(data) returned %d, "
3164 			    "databuf.maxlen = %d, databuf.len = %d\n",
3165 			    getcode, databuf.maxlen, databuf.len);
3166 			break;
3167 		}
3168 	}
3169 
3170 	/*
3171 	 * On error, free all the allocated mib_item_t objects.
3172 	 */
3173 	while (first_item != NULL) {
3174 		last_item = first_item;
3175 		first_item = first_item->next_item;
3176 		free(last_item);
3177 	}
3178 	return (NULL);
3179 }
3180 
3181 /*
3182  * print label security attributes for gateways.
3183  */
3184 static void
3185 pmsg_secattr(const char *sptr, size_t msglen, const char *labelstr)
3186 {
3187 	rtm_ext_t rtm_ext;
3188 	tsol_rtsecattr_t sp;
3189 	struct rtsa_s *rtsa = &sp.rtsa_attr[0];
3190 	const char *endptr;
3191 	char buf[256];
3192 	int i;
3193 
3194 	if (!is_system_labeled())
3195 		return;
3196 
3197 	endptr = sptr + msglen;
3198 
3199 	for (;;) {
3200 		if (sptr + sizeof (rtm_ext_t) + sizeof (sp) > endptr)
3201 			return;
3202 
3203 		bcopy(sptr, &rtm_ext, sizeof (rtm_ext));
3204 		sptr += sizeof (rtm_ext);
3205 		if (rtm_ext.rtmex_type == RTMEX_GATEWAY_SECATTR)
3206 			break;
3207 		sptr += rtm_ext.rtmex_len;
3208 	}
3209 
3210 	/* bail if this entry is corrupt or overruns buffer length */
3211 	if (rtm_ext.rtmex_len < sizeof (sp) ||
3212 	    sptr + rtm_ext.rtmex_len > endptr)
3213 		return;
3214 
3215 	/* run up just to the end of this extension */
3216 	endptr = sptr + rtm_ext.rtmex_len;
3217 
3218 	bcopy(sptr, &sp, sizeof (sp));
3219 	sptr += sizeof (sp);
3220 
3221 	if (sptr + (sp.rtsa_cnt - 1) * sizeof (*rtsa) != endptr)
3222 		return;
3223 
3224 	for (i = 0; i < sp.rtsa_cnt; i++) {
3225 		if (i > 0) {
3226 			/* first element is part of sp initalized above */
3227 			bcopy(sptr, rtsa, sizeof (*rtsa));
3228 			sptr += sizeof (*rtsa);
3229 		}
3230 		(void) printf("\n%s%s", labelstr, rtsa_to_str(rtsa, buf,
3231 		    sizeof (buf)));
3232 	}
3233 }
3234