1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright (c) 1990  Mentat Inc.
24  * netstat.c 2.2, last change 9/9/91
25  * MROUTING Revision 3.5
26  * Copyright (c) 2017, Joyent, Inc.
27  */
28 
29 /*
30  * simple netstat based on snmp/mib-2 interface to the TCP/IP stack
31  *
32  * NOTES:
33  * 1. A comment "LINTED: (note 1)" appears before certain lines where
34  *    lint would have complained, "pointer cast may result in improper
35  *    alignment". These are lines where lint had suspected potential
36  *    improper alignment of a data structure; in each such situation
37  *    we have relied on the kernel guaranteeing proper alignment.
38  * 2. Some 'for' loops have been commented as "'for' loop 1", etc
39  *    because they have 'continue' or 'break' statements in their
40  *    bodies. 'continue' statements have been used inside some loops
41  *    where avoiding them would have led to deep levels of indentation.
42  *
43  * TODO:
44  *	Add ability to request subsets from kernel (with level = MIB2_IP;
45  *	name = 0 meaning everything for compatibility)
46  */
47 
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <stdarg.h>
51 #include <unistd.h>
52 #include <strings.h>
53 #include <string.h>
54 #include <errno.h>
55 #include <ctype.h>
56 #include <kstat.h>
57 #include <assert.h>
58 #include <locale.h>
59 #include <synch.h>
60 #include <thread.h>
61 
62 #include <sys/types.h>
63 #include <sys/stream.h>
64 #include <stropts.h>
65 #include <sys/strstat.h>
66 #include <sys/tihdr.h>
67 
68 #include <sys/socket.h>
69 #include <sys/sockio.h>
70 #include <netinet/in.h>
71 #include <net/if.h>
72 #include <net/route.h>
73 
74 #include <inet/mib2.h>
75 #include <inet/ip.h>
76 #include <inet/arp.h>
77 #include <inet/tcp.h>
78 #include <netinet/igmp_var.h>
79 #include <netinet/ip_mroute.h>
80 
81 #include <arpa/inet.h>
82 #include <netdb.h>
83 #include <fcntl.h>
84 #include <sys/systeminfo.h>
85 #include <arpa/inet.h>
86 
87 #include <netinet/dhcp.h>
88 #include <dhcpagent_ipc.h>
89 #include <dhcpagent_util.h>
90 #include <compat.h>
91 
92 #include <libtsnet.h>
93 #include <tsol/label.h>
94 
95 #include "statcommon.h"
96 
97 extern void	unixpr(kstat_ctl_t *kc);
98 
99 #define	STR_EXPAND	4
100 
101 #define	V4MASK_TO_V6(v4, v6)	((v6)._S6_un._S6_u32[0] = 0xfffffffful, \
102 				(v6)._S6_un._S6_u32[1] = 0xfffffffful, \
103 				(v6)._S6_un._S6_u32[2] = 0xfffffffful, \
104 				(v6)._S6_un._S6_u32[3] = (v4))
105 
106 #define	IN6_IS_V4MASK(v6)	((v6)._S6_un._S6_u32[0] == 0xfffffffful && \
107 				(v6)._S6_un._S6_u32[1] == 0xfffffffful && \
108 				(v6)._S6_un._S6_u32[2] == 0xfffffffful)
109 
110 /*
111  * This is used as a cushion in the buffer allocation directed by SIOCGLIFNUM.
112  * Because there's no locking between SIOCGLIFNUM and SIOCGLIFCONF, it's
113  * possible for an administrator to plumb new interfaces between those two
114  * calls, resulting in the failure of the latter.  This addition makes that
115  * less likely.
116  */
117 #define	LIFN_GUARD_VALUE	10
118 
119 typedef struct mib_item_s {
120 	struct mib_item_s	*next_item;
121 	int			group;
122 	int			mib_id;
123 	int			length;
124 	void			*valp;
125 } mib_item_t;
126 
127 struct	ifstat {
128 	uint64_t	ipackets;
129 	uint64_t	ierrors;
130 	uint64_t	opackets;
131 	uint64_t	oerrors;
132 	uint64_t	collisions;
133 };
134 
135 struct iflist {
136 	struct iflist	*next_if;
137 	char		ifname[LIFNAMSIZ];
138 	struct ifstat	tot;
139 };
140 
141 static	mib_item_t	*mibget(int sd);
142 static	void		mibfree(mib_item_t *firstitem);
143 static	int		mibopen(void);
144 static void		mib_get_constants(mib_item_t *item);
145 static mib_item_t	*mib_item_dup(mib_item_t *item);
146 static mib_item_t	*mib_item_diff(mib_item_t *item1,
147     mib_item_t *item2);
148 static void		mib_item_destroy(mib_item_t **item);
149 
150 static boolean_t	octetstrmatch(const Octet_t *a, const Octet_t *b);
151 static char		*octetstr(const Octet_t *op, int code,
152 			    char *dst, uint_t dstlen);
153 static char		*pr_addr(uint_t addr,
154 			    char *dst, uint_t dstlen);
155 static char		*pr_addrnz(ipaddr_t addr, char *dst, uint_t dstlen);
156 static char		*pr_addr6(const in6_addr_t *addr,
157 			    char *dst, uint_t dstlen);
158 static char		*pr_mask(uint_t addr,
159 			    char *dst, uint_t dstlen);
160 static char		*pr_prefix6(const struct in6_addr *addr,
161 			    uint_t prefixlen, char *dst, uint_t dstlen);
162 static char		*pr_ap(uint_t addr, uint_t port,
163 			    char *proto, char *dst, uint_t dstlen);
164 static char		*pr_ap6(const in6_addr_t *addr, uint_t port,
165 			    char *proto, char *dst, uint_t dstlen);
166 static char		*pr_net(uint_t addr, uint_t mask,
167 			    char *dst, uint_t dstlen);
168 static char		*pr_netaddr(uint_t addr, uint_t mask,
169 			    char *dst, uint_t dstlen);
170 static char		*fmodestr(uint_t fmode);
171 static char		*portname(uint_t port, char *proto,
172 			    char *dst, uint_t dstlen);
173 
174 static const char	*mitcp_state(int code,
175 			    const mib2_transportMLPEntry_t *attr);
176 static const char	*miudp_state(int code,
177 			    const mib2_transportMLPEntry_t *attr);
178 
179 static void		stat_report(mib_item_t *item);
180 static void		mrt_stat_report(mib_item_t *item);
181 static void		arp_report(mib_item_t *item);
182 static void		ndp_report(mib_item_t *item);
183 static void		mrt_report(mib_item_t *item);
184 static void		if_stat_total(struct ifstat *oldstats,
185 			    struct ifstat *newstats, struct ifstat *sumstats);
186 static void		if_report(mib_item_t *item, char *ifname,
187 			    int Iflag_only, boolean_t once_only);
188 static void		if_report_ip4(mib2_ipAddrEntry_t *ap,
189 			    char ifname[], char logintname[],
190 			    struct ifstat *statptr, boolean_t ksp_not_null);
191 static void		if_report_ip6(mib2_ipv6AddrEntry_t *ap6,
192 			    char ifname[], char logintname[],
193 			    struct ifstat *statptr, boolean_t ksp_not_null);
194 static void		ire_report(const mib_item_t *item);
195 static void		tcp_report(const mib_item_t *item);
196 static void		udp_report(const mib_item_t *item);
197 static void		group_report(mib_item_t *item);
198 static void		dce_report(mib_item_t *item);
199 static void		print_ip_stats(mib2_ip_t *ip);
200 static void		print_icmp_stats(mib2_icmp_t *icmp);
201 static void		print_ip6_stats(mib2_ipv6IfStatsEntry_t *ip6);
202 static void		print_icmp6_stats(mib2_ipv6IfIcmpEntry_t *icmp6);
203 static void		print_sctp_stats(mib2_sctp_t *tcp);
204 static void		print_tcp_stats(mib2_tcp_t *tcp);
205 static void		print_udp_stats(mib2_udp_t *udp);
206 static void		print_rawip_stats(mib2_rawip_t *rawip);
207 static void		print_igmp_stats(struct igmpstat *igps);
208 static void		print_mrt_stats(struct mrtstat *mrts);
209 static void		sctp_report(const mib_item_t *item);
210 static void		sum_ip6_stats(mib2_ipv6IfStatsEntry_t *ip6,
211 			    mib2_ipv6IfStatsEntry_t *sum6);
212 static void		sum_icmp6_stats(mib2_ipv6IfIcmpEntry_t *icmp6,
213 			    mib2_ipv6IfIcmpEntry_t *sum6);
214 static void		m_report(void);
215 static void		dhcp_report(char *);
216 
217 static	uint64_t	kstat_named_value(kstat_t *, char *);
218 static	kid_t		safe_kstat_read(kstat_ctl_t *, kstat_t *, void *);
219 static int		isnum(char *);
220 static char		*plural(int n);
221 static char		*pluraly(int n);
222 static char		*plurales(int n);
223 static void		process_filter(char *arg);
224 static char		*ifindex2str(uint_t, char *);
225 static boolean_t	family_selected(int family);
226 
227 static void		usage(char *);
228 static void 		fatal(int errcode, char *str1, ...);
229 
230 #define	PLURAL(n) plural((int)n)
231 #define	PLURALY(n) pluraly((int)n)
232 #define	PLURALES(n) plurales((int)n)
233 #define	IFLAGMOD(flg, val1, val2)	if (flg == val1) flg = val2
234 #define	MDIFF(diff, elem2, elem1, member)	(diff)->member = \
235 	(elem2)->member - (elem1)->member
236 
237 
238 static	boolean_t	Aflag = B_FALSE;	/* All sockets/ifs/rtng-tbls */
239 static	boolean_t	Dflag = B_FALSE;	/* DCE info */
240 static	boolean_t	Iflag = B_FALSE;	/* IP Traffic Interfaces */
241 static	boolean_t	Mflag = B_FALSE;	/* STREAMS Memory Statistics */
242 static	boolean_t	Nflag = B_FALSE;	/* Numeric Network Addresses */
243 static	boolean_t	Rflag = B_FALSE;	/* Routing Tables */
244 static	boolean_t	RSECflag = B_FALSE;	/* Security attributes */
245 static	boolean_t	Sflag = B_FALSE;	/* Per-protocol Statistics */
246 static	boolean_t	Vflag = B_FALSE;	/* Verbose */
247 static	boolean_t	Pflag = B_FALSE;	/* Net to Media Tables */
248 static	boolean_t	Gflag = B_FALSE;	/* Multicast group membership */
249 static	boolean_t	MMflag = B_FALSE;	/* Multicast routing table */
250 static	boolean_t	DHCPflag = B_FALSE;	/* DHCP statistics */
251 static	boolean_t	Xflag = B_FALSE;	/* Debug Info */
252 
253 static	int	v4compat = 0;	/* Compatible printing format for status */
254 
255 static int	proto = IPPROTO_MAX;	/* all protocols */
256 kstat_ctl_t	*kc = NULL;
257 
258 /*
259  * Name service timeout detection constants.
260  */
261 static mutex_t ns_lock = ERRORCHECKMUTEX;
262 static boolean_t ns_active = B_FALSE;	/* Is a lookup ongoing? */
263 static hrtime_t ns_starttime;		/* Time the lookup started */
264 static int ns_sleeptime = 2;		/* Time in seconds between checks */
265 static int ns_warntime = 2;		/* Time in seconds before warning */
266 
267 /*
268  * Sizes of data structures extracted from the base mib.
269  * This allows the size of the tables entries to grow while preserving
270  * binary compatibility.
271  */
272 static int ipAddrEntrySize;
273 static int ipRouteEntrySize;
274 static int ipNetToMediaEntrySize;
275 static int ipMemberEntrySize;
276 static int ipGroupSourceEntrySize;
277 static int ipRouteAttributeSize;
278 static int vifctlSize;
279 static int mfcctlSize;
280 
281 static int ipv6IfStatsEntrySize;
282 static int ipv6IfIcmpEntrySize;
283 static int ipv6AddrEntrySize;
284 static int ipv6RouteEntrySize;
285 static int ipv6NetToMediaEntrySize;
286 static int ipv6MemberEntrySize;
287 static int ipv6GroupSourceEntrySize;
288 
289 static int ipDestEntrySize;
290 
291 static int transportMLPSize;
292 static int tcpConnEntrySize;
293 static int tcp6ConnEntrySize;
294 static int udpEntrySize;
295 static int udp6EntrySize;
296 static int sctpEntrySize;
297 static int sctpLocalEntrySize;
298 static int sctpRemoteEntrySize;
299 
300 #define	protocol_selected(p)	(proto == IPPROTO_MAX || proto == (p))
301 
302 /* Machinery used for -f (filter) option */
303 enum { FK_AF = 0, FK_OUTIF, FK_DST, FK_FLAGS, NFILTERKEYS };
304 
305 static const char *filter_keys[NFILTERKEYS] = {
306 	"af", "outif", "dst", "flags"
307 };
308 
309 static m_label_t *zone_security_label = NULL;
310 
311 /* Flags on routes */
312 #define	FLF_A		0x00000001
313 #define	FLF_b		0x00000002
314 #define	FLF_D		0x00000004
315 #define	FLF_G		0x00000008
316 #define	FLF_H		0x00000010
317 #define	FLF_L		0x00000020
318 #define	FLF_U		0x00000040
319 #define	FLF_M		0x00000080
320 #define	FLF_S		0x00000100
321 #define	FLF_C		0x00000200	/* IRE_IF_CLONE */
322 #define	FLF_I		0x00000400	/* RTF_INDIRECT */
323 #define	FLF_R		0x00000800	/* RTF_REJECT */
324 #define	FLF_B		0x00001000	/* RTF_BLACKHOLE */
325 #define	FLF_Z		0x00100000	/* RTF_ZONE */
326 
327 static const char flag_list[] = "AbDGHLUMSCIRBZ";
328 
329 typedef struct filter_rule filter_t;
330 
331 struct filter_rule {
332 	filter_t *f_next;
333 	union {
334 		int f_family;
335 		const char *f_ifname;
336 		struct {
337 			struct hostent *f_address;
338 			in6_addr_t f_mask;
339 		} a;
340 		struct {
341 			uint_t f_flagset;
342 			uint_t f_flagclear;
343 		} f;
344 	} u;
345 };
346 
347 /*
348  * The user-specified filters are linked into lists separated by
349  * keyword (type of filter).  Thus, the matching algorithm is:
350  *	For each non-empty filter list
351  *		If no filters in the list match
352  *			then stop here; route doesn't match
353  *	If loop above completes, then route does match and will be
354  *	displayed.
355  */
356 static filter_t *filters[NFILTERKEYS];
357 
358 static uint_t timestamp_fmt = NODATE;
359 
360 #if !defined(TEXT_DOMAIN)		/* Should be defined by cc -D */
361 #define	TEXT_DOMAIN "SYS_TEST"		/* Use this only if it isn't */
362 #endif
363 
364 static void
365 ns_lookup_start(void)
366 {
367 	mutex_enter(&ns_lock);
368 	ns_active = B_TRUE;
369 	ns_starttime = gethrtime();
370 	mutex_exit(&ns_lock);
371 }
372 
373 static void
374 ns_lookup_end(void)
375 {
376 	mutex_enter(&ns_lock);
377 	ns_active = B_FALSE;
378 	mutex_exit(&ns_lock);
379 }
380 
381 /*
382  * When name services are not functioning, this program appears to hang to the
383  * user. To try and give the user a chance of figuring out that this might be
384  * the case, we end up warning them and suggest that they may want to use the -n
385  * flag.
386  */
387 /* ARGSUSED */
388 static void *
389 ns_warning_thr(void *unsued)
390 {
391 	for (;;) {
392 		hrtime_t now;
393 
394 		(void) sleep(ns_sleeptime);
395 		now = gethrtime();
396 		mutex_enter(&ns_lock);
397 		if (ns_active && now - ns_starttime >= ns_warntime * NANOSEC) {
398 			(void) fprintf(stderr, "warning: data "
399 			    "available, but name service lookups are "
400 			    "taking a while. Use the -n option to "
401 			    "disable name service lookups.\n");
402 			mutex_exit(&ns_lock);
403 			return (NULL);
404 		}
405 		mutex_exit(&ns_lock);
406 	}
407 
408 	/* LINTED: E_STMT_NOT_REACHED */
409 	return (NULL);
410 }
411 
412 
413 int
414 main(int argc, char **argv)
415 {
416 	char		*name;
417 	mib_item_t	*item = NULL;
418 	mib_item_t	*previtem = NULL;
419 	int		sd = -1;
420 	char	*ifname = NULL;
421 	int	interval = 0;	/* Single time by default */
422 	int	count = -1;	/* Forever */
423 	int	c;
424 	int	d;
425 	/*
426 	 * Possible values of 'Iflag_only':
427 	 * -1, no feature-flags;
428 	 *  0, IFlag and other feature-flags enabled
429 	 *  1, IFlag is the only feature-flag enabled
430 	 * : trinary variable, modified using IFLAGMOD()
431 	 */
432 	int Iflag_only = -1;
433 	boolean_t once_only = B_FALSE; /* '-i' with count > 1 */
434 	extern char	*optarg;
435 	extern int	optind;
436 	char *default_ip_str = NULL;
437 
438 	name = argv[0];
439 
440 	v4compat = get_compat_flag(&default_ip_str);
441 	if (v4compat == DEFAULT_PROT_BAD_VALUE)
442 		fatal(2, "%s: %s: Bad value for %s in %s\n", name,
443 		    default_ip_str, DEFAULT_IP, INET_DEFAULT_FILE);
444 	free(default_ip_str);
445 
446 	(void) setlocale(LC_ALL, "");
447 	(void) textdomain(TEXT_DOMAIN);
448 
449 	while ((c = getopt(argc, argv, "adimnrspMgvxf:P:I:DRT:")) != -1) {
450 		switch ((char)c) {
451 		case 'a':		/* all connections */
452 			Aflag = B_TRUE;
453 			break;
454 
455 		case 'd':		/* DCE info */
456 			Dflag = B_TRUE;
457 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
458 			break;
459 
460 		case 'i':		/* interface (ill/ipif report) */
461 			Iflag = B_TRUE;
462 			IFLAGMOD(Iflag_only, -1, 1); /* '-i' exists */
463 			break;
464 
465 		case 'm':		/* streams msg report */
466 			Mflag = B_TRUE;
467 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
468 			break;
469 
470 		case 'n':		/* numeric format */
471 			Nflag = B_TRUE;
472 			break;
473 
474 		case 'r':		/* route tables */
475 			Rflag = B_TRUE;
476 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
477 			break;
478 
479 		case 'R':		/* security attributes */
480 			RSECflag = B_TRUE;
481 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
482 			break;
483 
484 		case 's':		/* per-protocol statistics */
485 			Sflag = B_TRUE;
486 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
487 			break;
488 
489 		case 'p':		/* arp/ndp table */
490 			Pflag = B_TRUE;
491 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
492 			break;
493 
494 		case 'M':		/* multicast routing tables */
495 			MMflag = B_TRUE;
496 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
497 			break;
498 
499 		case 'g':		/* multicast group membership */
500 			Gflag = B_TRUE;
501 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
502 			break;
503 
504 		case 'v':		/* verbose output format */
505 			Vflag = B_TRUE;
506 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
507 			break;
508 
509 		case 'x':		/* turn on debugging */
510 			Xflag = B_TRUE;
511 			break;
512 
513 		case 'f':
514 			process_filter(optarg);
515 			break;
516 
517 		case 'P':
518 			if (strcmp(optarg, "ip") == 0) {
519 				proto = IPPROTO_IP;
520 			} else if (strcmp(optarg, "ipv6") == 0 ||
521 			    strcmp(optarg, "ip6") == 0) {
522 				v4compat = 0;	/* Overridden */
523 				proto = IPPROTO_IPV6;
524 			} else if (strcmp(optarg, "icmp") == 0) {
525 				proto = IPPROTO_ICMP;
526 			} else if (strcmp(optarg, "icmpv6") == 0 ||
527 			    strcmp(optarg, "icmp6") == 0) {
528 				v4compat = 0;	/* Overridden */
529 				proto = IPPROTO_ICMPV6;
530 			} else if (strcmp(optarg, "igmp") == 0) {
531 				proto = IPPROTO_IGMP;
532 			} else if (strcmp(optarg, "udp") == 0) {
533 				proto = IPPROTO_UDP;
534 			} else if (strcmp(optarg, "tcp") == 0) {
535 				proto = IPPROTO_TCP;
536 			} else if (strcmp(optarg, "sctp") == 0) {
537 				proto = IPPROTO_SCTP;
538 			} else if (strcmp(optarg, "raw") == 0 ||
539 			    strcmp(optarg, "rawip") == 0) {
540 				proto = IPPROTO_RAW;
541 			} else {
542 				fatal(1, "%s: unknown protocol.\n", optarg);
543 			}
544 			break;
545 
546 		case 'I':
547 			ifname = optarg;
548 			Iflag = B_TRUE;
549 			IFLAGMOD(Iflag_only, -1, 1); /* see macro def'n */
550 			break;
551 
552 		case 'D':
553 			DHCPflag = B_TRUE;
554 			Iflag_only = 0;
555 			break;
556 
557 		case 'T':
558 			if (optarg) {
559 				if (*optarg == 'u')
560 					timestamp_fmt = UDATE;
561 				else if (*optarg == 'd')
562 					timestamp_fmt = DDATE;
563 				else
564 					usage(name);
565 			} else {
566 				usage(name);
567 			}
568 			break;
569 
570 		case '?':
571 		default:
572 			usage(name);
573 		}
574 	}
575 
576 	/*
577 	 * Make sure -R option is set only on a labeled system.
578 	 */
579 	if (RSECflag && !is_system_labeled()) {
580 		(void) fprintf(stderr, "-R set but labeling is not enabled\n");
581 		usage(name);
582 	}
583 
584 	/*
585 	 * Handle other arguments: find interval, count; the
586 	 * flags that accept 'interval' and 'count' are OR'd
587 	 * in the outermost 'if'; more flags may be added as
588 	 * required
589 	 */
590 	if (Iflag || Sflag || Mflag) {
591 		for (d = optind; d < argc; d++) {
592 			if (isnum(argv[d])) {
593 				interval = atoi(argv[d]);
594 				if (d + 1 < argc &&
595 				    isnum(argv[d + 1])) {
596 					count = atoi(argv[d + 1]);
597 					optind++;
598 				}
599 				optind++;
600 				if (interval == 0 || count == 0)
601 					usage(name);
602 				break;
603 			}
604 		}
605 	}
606 	if (optind < argc) {
607 		if (Iflag && isnum(argv[optind])) {
608 			count = atoi(argv[optind]);
609 			if (count == 0)
610 				usage(name);
611 			optind++;
612 		}
613 	}
614 	if (optind < argc) {
615 		(void) fprintf(stderr,
616 		    "%s: extra arguments\n", name);
617 		usage(name);
618 	}
619 	if (interval)
620 		setbuf(stdout, NULL);
621 
622 	/*
623 	 * Start up the thread to check for name services warnings.
624 	 */
625 	if (thr_create(NULL, 0, ns_warning_thr, NULL,
626 	    THR_DETACHED | THR_DAEMON, NULL) != 0) {
627 		fatal(1, "%s: failed to create name services "
628 		    "thread: %s\n", name, strerror(errno));
629 	}
630 
631 	if (DHCPflag) {
632 		dhcp_report(Iflag ? ifname : NULL);
633 		exit(0);
634 	}
635 
636 	/*
637 	 * Get this process's security label if the -R switch is set.
638 	 * We use this label as the current zone's security label.
639 	 */
640 	if (RSECflag) {
641 		zone_security_label = m_label_alloc(MAC_LABEL);
642 		if (zone_security_label == NULL)
643 			fatal(errno, "m_label_alloc() failed");
644 		if (getplabel(zone_security_label) < 0)
645 			fatal(errno, "getplabel() failed");
646 	}
647 
648 	/* Get data structures: priming before iteration */
649 	if (family_selected(AF_INET) || family_selected(AF_INET6)) {
650 		sd = mibopen();
651 		if (sd == -1)
652 			fatal(1, "can't open mib stream\n");
653 		if ((item = mibget(sd)) == NULL) {
654 			(void) close(sd);
655 			fatal(1, "mibget() failed\n");
656 		}
657 		/* Extract constant sizes - need do once only */
658 		mib_get_constants(item);
659 	}
660 	if ((kc = kstat_open()) == NULL) {
661 		mibfree(item);
662 		(void) close(sd);
663 		fail(1, "kstat_open(): can't open /dev/kstat");
664 	}
665 
666 	if (interval <= 0) {
667 		count = 1;
668 		once_only = B_TRUE;
669 	}
670 	/* 'for' loop 1: */
671 	for (;;) {
672 		mib_item_t *curritem = NULL; /* only for -[M]s */
673 
674 		if (timestamp_fmt != NODATE)
675 			print_timestamp(timestamp_fmt);
676 
677 		/* netstat: AF_INET[6] behaviour */
678 		if (family_selected(AF_INET) || family_selected(AF_INET6)) {
679 			if (Sflag) {
680 				curritem = mib_item_diff(previtem, item);
681 				if (curritem == NULL)
682 					fatal(1, "can't process mib data, "
683 					    "out of memory\n");
684 				mib_item_destroy(&previtem);
685 			}
686 
687 			if (!(Dflag || Iflag || Rflag || Sflag || Mflag ||
688 			    MMflag || Pflag || Gflag || DHCPflag)) {
689 				if (protocol_selected(IPPROTO_UDP))
690 					udp_report(item);
691 				if (protocol_selected(IPPROTO_TCP))
692 					tcp_report(item);
693 				if (protocol_selected(IPPROTO_SCTP))
694 					sctp_report(item);
695 			}
696 			if (Iflag)
697 				if_report(item, ifname, Iflag_only, once_only);
698 			if (Mflag)
699 				m_report();
700 			if (Rflag)
701 				ire_report(item);
702 			if (Sflag && MMflag) {
703 				mrt_stat_report(curritem);
704 			} else {
705 				if (Sflag)
706 					stat_report(curritem);
707 				if (MMflag)
708 					mrt_report(item);
709 			}
710 			if (Gflag)
711 				group_report(item);
712 			if (Pflag) {
713 				if (family_selected(AF_INET))
714 					arp_report(item);
715 				if (family_selected(AF_INET6))
716 					ndp_report(item);
717 			}
718 			if (Dflag)
719 				dce_report(item);
720 			mib_item_destroy(&curritem);
721 		}
722 
723 		/* netstat: AF_UNIX behaviour */
724 		if (family_selected(AF_UNIX) &&
725 		    (!(Dflag || Iflag || Rflag || Sflag || Mflag ||
726 		    MMflag || Pflag || Gflag)))
727 			unixpr(kc);
728 		(void) kstat_close(kc);
729 
730 		/* iteration handling code */
731 		if (count > 0 && --count == 0)
732 			break;
733 		(void) sleep(interval);
734 
735 		/* re-populating of data structures */
736 		if (family_selected(AF_INET) || family_selected(AF_INET6)) {
737 			if (Sflag) {
738 				/* previtem is a cut-down list */
739 				previtem = mib_item_dup(item);
740 				if (previtem == NULL)
741 					fatal(1, "can't process mib data, "
742 					    "out of memory\n");
743 			}
744 			mibfree(item);
745 			(void) close(sd);
746 			if ((sd = mibopen()) == -1)
747 				fatal(1, "can't open mib stream anymore\n");
748 			if ((item = mibget(sd)) == NULL) {
749 				(void) close(sd);
750 				fatal(1, "mibget() failed\n");
751 			}
752 		}
753 		if ((kc = kstat_open()) == NULL)
754 			fail(1, "kstat_open(): can't open /dev/kstat");
755 
756 	} /* 'for' loop 1 ends */
757 	mibfree(item);
758 	(void) close(sd);
759 	if (zone_security_label != NULL)
760 		m_label_free(zone_security_label);
761 
762 	return (0);
763 }
764 
765 
766 static int
767 isnum(char *p)
768 {
769 	int	len;
770 	int	i;
771 
772 	len = strlen(p);
773 	for (i = 0; i < len; i++)
774 		if (!isdigit(p[i]))
775 			return (0);
776 	return (1);
777 }
778 
779 
780 /* --------------------------------- MIBGET -------------------------------- */
781 
782 static mib_item_t *
783 mibget(int sd)
784 {
785 	/*
786 	 * buf is an automatic for this function, so the
787 	 * compiler has complete control over its alignment;
788 	 * it is assumed this alignment is satisfactory for
789 	 * it to be casted to certain other struct pointers
790 	 * here, such as struct T_optmgmt_ack * .
791 	 */
792 	uintptr_t		buf[512 / sizeof (uintptr_t)];
793 	int			flags;
794 	int			i, j, getcode;
795 	struct strbuf		ctlbuf, databuf;
796 	struct T_optmgmt_req	*tor = (struct T_optmgmt_req *)buf;
797 	struct T_optmgmt_ack	*toa = (struct T_optmgmt_ack *)buf;
798 	struct T_error_ack	*tea = (struct T_error_ack *)buf;
799 	struct opthdr		*req;
800 	mib_item_t		*first_item = NULL;
801 	mib_item_t		*last_item  = NULL;
802 	mib_item_t		*temp;
803 
804 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
805 	tor->OPT_offset = sizeof (struct T_optmgmt_req);
806 	tor->OPT_length = sizeof (struct opthdr);
807 	tor->MGMT_flags = T_CURRENT;
808 
809 
810 	/*
811 	 * Note: we use the special level value below so that IP will return
812 	 * us information concerning IRE_MARK_TESTHIDDEN routes.
813 	 */
814 	req = (struct opthdr *)&tor[1];
815 	req->level = EXPER_IP_AND_ALL_IRES;
816 	req->name  = 0;
817 	req->len   = 1;
818 
819 	ctlbuf.buf = (char *)buf;
820 	ctlbuf.len = tor->OPT_length + tor->OPT_offset;
821 	flags = 0;
822 	if (putmsg(sd, &ctlbuf, (struct strbuf *)0, flags) == -1) {
823 		perror("mibget: putmsg(ctl) failed");
824 		goto error_exit;
825 	}
826 
827 	/*
828 	 * Each reply consists of a ctl part for one fixed structure
829 	 * or table, as defined in mib2.h.  The format is a T_OPTMGMT_ACK,
830 	 * containing an opthdr structure.  level/name identify the entry,
831 	 * len is the size of the data part of the message.
832 	 */
833 	req = (struct opthdr *)&toa[1];
834 	ctlbuf.maxlen = sizeof (buf);
835 	j = 1;
836 	for (;;) {
837 		flags = 0;
838 		getcode = getmsg(sd, &ctlbuf, (struct strbuf *)0, &flags);
839 		if (getcode == -1) {
840 			perror("mibget getmsg(ctl) failed");
841 			if (Xflag) {
842 				(void) fputs("#   level   name    len\n",
843 				    stderr);
844 				i = 0;
845 				for (last_item = first_item; last_item;
846 				    last_item = last_item->next_item)
847 					(void) printf("%d  %4d   %5d   %d\n",
848 					    ++i,
849 					    last_item->group,
850 					    last_item->mib_id,
851 					    last_item->length);
852 			}
853 			goto error_exit;
854 		}
855 		if (getcode == 0 &&
856 		    ctlbuf.len >= sizeof (struct T_optmgmt_ack) &&
857 		    toa->PRIM_type == T_OPTMGMT_ACK &&
858 		    toa->MGMT_flags == T_SUCCESS &&
859 		    req->len == 0) {
860 			if (Xflag)
861 				(void) printf("mibget getmsg() %d returned "
862 				    "EOD (level %ld, name %ld)\n",
863 				    j, req->level, req->name);
864 			return (first_item);		/* this is EOD msg */
865 		}
866 
867 		if (ctlbuf.len >= sizeof (struct T_error_ack) &&
868 		    tea->PRIM_type == T_ERROR_ACK) {
869 			(void) fprintf(stderr,
870 			    "mibget %d gives T_ERROR_ACK: TLI_error = 0x%lx, "
871 			    "UNIX_error = 0x%lx\n",
872 			    j, tea->TLI_error, tea->UNIX_error);
873 
874 			errno = (tea->TLI_error == TSYSERR) ?
875 			    tea->UNIX_error : EPROTO;
876 			goto error_exit;
877 		}
878 
879 		if (getcode != MOREDATA ||
880 		    ctlbuf.len < sizeof (struct T_optmgmt_ack) ||
881 		    toa->PRIM_type != T_OPTMGMT_ACK ||
882 		    toa->MGMT_flags != T_SUCCESS) {
883 			(void) printf("mibget getmsg(ctl) %d returned %d, "
884 			    "ctlbuf.len = %d, PRIM_type = %ld\n",
885 			    j, getcode, ctlbuf.len, toa->PRIM_type);
886 
887 			if (toa->PRIM_type == T_OPTMGMT_ACK)
888 				(void) printf("T_OPTMGMT_ACK: "
889 				    "MGMT_flags = 0x%lx, req->len = %ld\n",
890 				    toa->MGMT_flags, req->len);
891 			errno = ENOMSG;
892 			goto error_exit;
893 		}
894 
895 		temp = (mib_item_t *)malloc(sizeof (mib_item_t));
896 		if (temp == NULL) {
897 			perror("mibget malloc failed");
898 			goto error_exit;
899 		}
900 		if (last_item != NULL)
901 			last_item->next_item = temp;
902 		else
903 			first_item = temp;
904 		last_item = temp;
905 		last_item->next_item = NULL;
906 		last_item->group = req->level;
907 		last_item->mib_id = req->name;
908 		last_item->length = req->len;
909 		last_item->valp = malloc((int)req->len);
910 		if (last_item->valp == NULL)
911 			goto error_exit;
912 		if (Xflag)
913 			(void) printf("msg %d: group = %4d   mib_id = %5d"
914 			    "length = %d\n",
915 			    j, last_item->group, last_item->mib_id,
916 			    last_item->length);
917 
918 		databuf.maxlen = last_item->length;
919 		databuf.buf    = (char *)last_item->valp;
920 		databuf.len    = 0;
921 		flags = 0;
922 		getcode = getmsg(sd, (struct strbuf *)0, &databuf, &flags);
923 		if (getcode == -1) {
924 			perror("mibget getmsg(data) failed");
925 			goto error_exit;
926 		} else if (getcode != 0) {
927 			(void) printf("mibget getmsg(data) returned %d, "
928 			    "databuf.maxlen = %d, databuf.len = %d\n",
929 			    getcode, databuf.maxlen, databuf.len);
930 			goto error_exit;
931 		}
932 		j++;
933 	}
934 	/* NOTREACHED */
935 
936 error_exit:;
937 	mibfree(first_item);
938 	return (NULL);
939 }
940 
941 /*
942  * mibfree: frees a linked list of type (mib_item_t *)
943  * returned by mibget(); this is NOT THE SAME AS
944  * mib_item_destroy(), so should be used for objects
945  * returned by mibget() only
946  */
947 static void
948 mibfree(mib_item_t *firstitem)
949 {
950 	mib_item_t *lastitem;
951 
952 	while (firstitem != NULL) {
953 		lastitem = firstitem;
954 		firstitem = firstitem->next_item;
955 		if (lastitem->valp != NULL)
956 			free(lastitem->valp);
957 		free(lastitem);
958 	}
959 }
960 
961 static int
962 mibopen(void)
963 {
964 	int	sd;
965 
966 	sd = open("/dev/arp", O_RDWR);
967 	if (sd == -1) {
968 		perror("arp open");
969 		return (-1);
970 	}
971 	if (ioctl(sd, I_PUSH, "tcp") == -1) {
972 		perror("tcp I_PUSH");
973 		(void) close(sd);
974 		return (-1);
975 	}
976 	if (ioctl(sd, I_PUSH, "udp") == -1) {
977 		perror("udp I_PUSH");
978 		(void) close(sd);
979 		return (-1);
980 	}
981 	if (ioctl(sd, I_PUSH, "icmp") == -1) {
982 		perror("icmp I_PUSH");
983 		(void) close(sd);
984 		return (-1);
985 	}
986 	return (sd);
987 }
988 
989 /*
990  * mib_item_dup: returns a clean mib_item_t * linked
991  * list, so that for every element item->mib_id is 0;
992  * to deallocate this linked list, use mib_item_destroy
993  */
994 static mib_item_t *
995 mib_item_dup(mib_item_t *item)
996 {
997 	int	c = 0;
998 	mib_item_t *localp;
999 	mib_item_t *tempp;
1000 
1001 	for (tempp = item; tempp; tempp = tempp->next_item)
1002 		if (tempp->mib_id == 0)
1003 			c++;
1004 	tempp = NULL;
1005 
1006 	localp = (mib_item_t *)malloc(c * sizeof (mib_item_t));
1007 	if (localp == NULL)
1008 		return (NULL);
1009 	c = 0;
1010 	for (; item; item = item->next_item) {
1011 		if (item->mib_id == 0) {
1012 			/* Replicate item in localp */
1013 			(localp[c]).next_item = NULL;
1014 			(localp[c]).group = item->group;
1015 			(localp[c]).mib_id = item->mib_id;
1016 			(localp[c]).length = item->length;
1017 			(localp[c]).valp = (uintptr_t *)malloc(
1018 			    item->length);
1019 			if ((localp[c]).valp == NULL) {
1020 				mib_item_destroy(&localp);
1021 				return (NULL);
1022 			}
1023 			(void *) memcpy((localp[c]).valp,
1024 			    item->valp,
1025 			    item->length);
1026 			tempp = &(localp[c]);
1027 			if (c > 0)
1028 				(localp[c - 1]).next_item = tempp;
1029 			c++;
1030 		}
1031 	}
1032 	return (localp);
1033 }
1034 
1035 /*
1036  * mib_item_diff: takes two (mib_item_t *) linked lists
1037  * item1 and item2 and computes the difference between
1038  * differentiable values in item2 against item1 for every
1039  * given member of item2; returns an mib_item_t * linked
1040  * list of diff's, or a copy of item2 if item1 is NULL;
1041  * will return NULL if system out of memory; works only
1042  * for item->mib_id == 0
1043  */
1044 static mib_item_t *
1045 mib_item_diff(mib_item_t *item1, mib_item_t *item2)
1046 {
1047 	int	nitems	= 0; /* no. of items in item2 */
1048 	mib_item_t *tempp2;  /* walking copy of item2 */
1049 	mib_item_t *tempp1;  /* walking copy of item1 */
1050 	mib_item_t *diffp;
1051 	mib_item_t *diffptr; /* walking copy of diffp */
1052 	mib_item_t *prevp = NULL;
1053 
1054 	if (item1 == NULL) {
1055 		diffp = mib_item_dup(item2);
1056 		return (diffp);
1057 	}
1058 
1059 	for (tempp2 = item2;
1060 	    tempp2;
1061 	    tempp2 = tempp2->next_item) {
1062 		if (tempp2->mib_id == 0)
1063 			switch (tempp2->group) {
1064 			/*
1065 			 * upon adding a case here, the same
1066 			 * must also be added in the next
1067 			 * switch statement, alongwith
1068 			 * appropriate code
1069 			 */
1070 			case MIB2_IP:
1071 			case MIB2_IP6:
1072 			case EXPER_DVMRP:
1073 			case EXPER_IGMP:
1074 			case MIB2_ICMP:
1075 			case MIB2_ICMP6:
1076 			case MIB2_TCP:
1077 			case MIB2_UDP:
1078 			case MIB2_SCTP:
1079 			case EXPER_RAWIP:
1080 				nitems++;
1081 			}
1082 	}
1083 	tempp2 = NULL;
1084 	if (nitems == 0) {
1085 		diffp = mib_item_dup(item2);
1086 		return (diffp);
1087 	}
1088 
1089 	diffp = (mib_item_t *)calloc(nitems, sizeof (mib_item_t));
1090 	if (diffp == NULL)
1091 		return (NULL);
1092 	diffptr = diffp;
1093 	/* 'for' loop 1: */
1094 	for (tempp2 = item2; tempp2 != NULL; tempp2 = tempp2->next_item) {
1095 		if (tempp2->mib_id != 0)
1096 			continue; /* 'for' loop 1 */
1097 		/* 'for' loop 2: */
1098 		for (tempp1 = item1; tempp1 != NULL;
1099 		    tempp1 = tempp1->next_item) {
1100 			if (!(tempp1->mib_id == 0 &&
1101 			    tempp1->group == tempp2->group &&
1102 			    tempp1->mib_id == tempp2->mib_id))
1103 				continue; /* 'for' loop 2 */
1104 			/* found comparable data sets */
1105 			if (prevp != NULL)
1106 				prevp->next_item = diffptr;
1107 			switch (tempp2->group) {
1108 			/*
1109 			 * Indenting note: Because of long variable names
1110 			 * in cases MIB2_IP6 and MIB2_ICMP6, their contents
1111 			 * have been indented by one tab space only
1112 			 */
1113 			case MIB2_IP: {
1114 				mib2_ip_t *i2 = (mib2_ip_t *)tempp2->valp;
1115 				mib2_ip_t *i1 = (mib2_ip_t *)tempp1->valp;
1116 				mib2_ip_t *d;
1117 
1118 				diffptr->group = tempp2->group;
1119 				diffptr->mib_id = tempp2->mib_id;
1120 				diffptr->length = tempp2->length;
1121 				d = (mib2_ip_t *)calloc(tempp2->length, 1);
1122 				if (d == NULL)
1123 					goto mibdiff_out_of_memory;
1124 				diffptr->valp = d;
1125 				d->ipForwarding = i2->ipForwarding;
1126 				d->ipDefaultTTL = i2->ipDefaultTTL;
1127 				MDIFF(d, i2, i1, ipInReceives);
1128 				MDIFF(d, i2, i1, ipInHdrErrors);
1129 				MDIFF(d, i2, i1, ipInAddrErrors);
1130 				MDIFF(d, i2, i1, ipInCksumErrs);
1131 				MDIFF(d, i2, i1, ipForwDatagrams);
1132 				MDIFF(d, i2, i1, ipForwProhibits);
1133 				MDIFF(d, i2, i1, ipInUnknownProtos);
1134 				MDIFF(d, i2, i1, ipInDiscards);
1135 				MDIFF(d, i2, i1, ipInDelivers);
1136 				MDIFF(d, i2, i1, ipOutRequests);
1137 				MDIFF(d, i2, i1, ipOutDiscards);
1138 				MDIFF(d, i2, i1, ipOutNoRoutes);
1139 				MDIFF(d, i2, i1, ipReasmTimeout);
1140 				MDIFF(d, i2, i1, ipReasmReqds);
1141 				MDIFF(d, i2, i1, ipReasmOKs);
1142 				MDIFF(d, i2, i1, ipReasmFails);
1143 				MDIFF(d, i2, i1, ipReasmDuplicates);
1144 				MDIFF(d, i2, i1, ipReasmPartDups);
1145 				MDIFF(d, i2, i1, ipFragOKs);
1146 				MDIFF(d, i2, i1, ipFragFails);
1147 				MDIFF(d, i2, i1, ipFragCreates);
1148 				MDIFF(d, i2, i1, ipRoutingDiscards);
1149 				MDIFF(d, i2, i1, tcpInErrs);
1150 				MDIFF(d, i2, i1, udpNoPorts);
1151 				MDIFF(d, i2, i1, udpInCksumErrs);
1152 				MDIFF(d, i2, i1, udpInOverflows);
1153 				MDIFF(d, i2, i1, rawipInOverflows);
1154 				MDIFF(d, i2, i1, ipsecInSucceeded);
1155 				MDIFF(d, i2, i1, ipsecInFailed);
1156 				MDIFF(d, i2, i1, ipInIPv6);
1157 				MDIFF(d, i2, i1, ipOutIPv6);
1158 				MDIFF(d, i2, i1, ipOutSwitchIPv6);
1159 				prevp = diffptr++;
1160 				break;
1161 			}
1162 			case MIB2_IP6: {
1163 			mib2_ipv6IfStatsEntry_t *i2;
1164 			mib2_ipv6IfStatsEntry_t *i1;
1165 			mib2_ipv6IfStatsEntry_t *d;
1166 
1167 			i2 = (mib2_ipv6IfStatsEntry_t *)tempp2->valp;
1168 			i1 = (mib2_ipv6IfStatsEntry_t *)tempp1->valp;
1169 			diffptr->group = tempp2->group;
1170 			diffptr->mib_id = tempp2->mib_id;
1171 			diffptr->length = tempp2->length;
1172 			d = (mib2_ipv6IfStatsEntry_t *)calloc(
1173 			    tempp2->length, 1);
1174 			if (d == NULL)
1175 				goto mibdiff_out_of_memory;
1176 			diffptr->valp = d;
1177 			d->ipv6Forwarding = i2->ipv6Forwarding;
1178 			d->ipv6DefaultHopLimit =
1179 			    i2->ipv6DefaultHopLimit;
1180 
1181 			MDIFF(d, i2, i1, ipv6InReceives);
1182 			MDIFF(d, i2, i1, ipv6InHdrErrors);
1183 			MDIFF(d, i2, i1, ipv6InTooBigErrors);
1184 			MDIFF(d, i2, i1, ipv6InNoRoutes);
1185 			MDIFF(d, i2, i1, ipv6InAddrErrors);
1186 			MDIFF(d, i2, i1, ipv6InUnknownProtos);
1187 			MDIFF(d, i2, i1, ipv6InTruncatedPkts);
1188 			MDIFF(d, i2, i1, ipv6InDiscards);
1189 			MDIFF(d, i2, i1, ipv6InDelivers);
1190 			MDIFF(d, i2, i1, ipv6OutForwDatagrams);
1191 			MDIFF(d, i2, i1, ipv6OutRequests);
1192 			MDIFF(d, i2, i1, ipv6OutDiscards);
1193 			MDIFF(d, i2, i1, ipv6OutNoRoutes);
1194 			MDIFF(d, i2, i1, ipv6OutFragOKs);
1195 			MDIFF(d, i2, i1, ipv6OutFragFails);
1196 			MDIFF(d, i2, i1, ipv6OutFragCreates);
1197 			MDIFF(d, i2, i1, ipv6ReasmReqds);
1198 			MDIFF(d, i2, i1, ipv6ReasmOKs);
1199 			MDIFF(d, i2, i1, ipv6ReasmFails);
1200 			MDIFF(d, i2, i1, ipv6InMcastPkts);
1201 			MDIFF(d, i2, i1, ipv6OutMcastPkts);
1202 			MDIFF(d, i2, i1, ipv6ReasmDuplicates);
1203 			MDIFF(d, i2, i1, ipv6ReasmPartDups);
1204 			MDIFF(d, i2, i1, ipv6ForwProhibits);
1205 			MDIFF(d, i2, i1, udpInCksumErrs);
1206 			MDIFF(d, i2, i1, udpInOverflows);
1207 			MDIFF(d, i2, i1, rawipInOverflows);
1208 			MDIFF(d, i2, i1, ipv6InIPv4);
1209 			MDIFF(d, i2, i1, ipv6OutIPv4);
1210 			MDIFF(d, i2, i1, ipv6OutSwitchIPv4);
1211 			prevp = diffptr++;
1212 			break;
1213 			}
1214 			case EXPER_DVMRP: {
1215 				struct mrtstat *m2;
1216 				struct mrtstat *m1;
1217 				struct mrtstat *d;
1218 
1219 				m2 = (struct mrtstat *)tempp2->valp;
1220 				m1 = (struct mrtstat *)tempp1->valp;
1221 				diffptr->group = tempp2->group;
1222 				diffptr->mib_id = tempp2->mib_id;
1223 				diffptr->length = tempp2->length;
1224 				d = (struct mrtstat *)calloc(tempp2->length, 1);
1225 				if (d == NULL)
1226 					goto mibdiff_out_of_memory;
1227 				diffptr->valp = d;
1228 				MDIFF(d, m2, m1, mrts_mfc_hits);
1229 				MDIFF(d, m2, m1, mrts_mfc_misses);
1230 				MDIFF(d, m2, m1, mrts_fwd_in);
1231 				MDIFF(d, m2, m1, mrts_fwd_out);
1232 				d->mrts_upcalls = m2->mrts_upcalls;
1233 				MDIFF(d, m2, m1, mrts_fwd_drop);
1234 				MDIFF(d, m2, m1, mrts_bad_tunnel);
1235 				MDIFF(d, m2, m1, mrts_cant_tunnel);
1236 				MDIFF(d, m2, m1, mrts_wrong_if);
1237 				MDIFF(d, m2, m1, mrts_upq_ovflw);
1238 				MDIFF(d, m2, m1, mrts_cache_cleanups);
1239 				MDIFF(d, m2, m1, mrts_drop_sel);
1240 				MDIFF(d, m2, m1, mrts_q_overflow);
1241 				MDIFF(d, m2, m1, mrts_pkt2large);
1242 				MDIFF(d, m2, m1, mrts_pim_badversion);
1243 				MDIFF(d, m2, m1, mrts_pim_rcv_badcsum);
1244 				MDIFF(d, m2, m1, mrts_pim_badregisters);
1245 				MDIFF(d, m2, m1, mrts_pim_regforwards);
1246 				MDIFF(d, m2, m1, mrts_pim_regsend_drops);
1247 				MDIFF(d, m2, m1, mrts_pim_malformed);
1248 				MDIFF(d, m2, m1, mrts_pim_nomemory);
1249 				prevp = diffptr++;
1250 				break;
1251 			}
1252 			case EXPER_IGMP: {
1253 				struct igmpstat *i2;
1254 				struct igmpstat *i1;
1255 				struct igmpstat *d;
1256 
1257 				i2 = (struct igmpstat *)tempp2->valp;
1258 				i1 = (struct igmpstat *)tempp1->valp;
1259 				diffptr->group = tempp2->group;
1260 				diffptr->mib_id = tempp2->mib_id;
1261 				diffptr->length = tempp2->length;
1262 				d = (struct igmpstat *)calloc(
1263 				    tempp2->length, 1);
1264 				if (d == NULL)
1265 					goto mibdiff_out_of_memory;
1266 				diffptr->valp = d;
1267 				MDIFF(d, i2, i1, igps_rcv_total);
1268 				MDIFF(d, i2, i1, igps_rcv_tooshort);
1269 				MDIFF(d, i2, i1, igps_rcv_badsum);
1270 				MDIFF(d, i2, i1, igps_rcv_queries);
1271 				MDIFF(d, i2, i1, igps_rcv_badqueries);
1272 				MDIFF(d, i2, i1, igps_rcv_reports);
1273 				MDIFF(d, i2, i1, igps_rcv_badreports);
1274 				MDIFF(d, i2, i1, igps_rcv_ourreports);
1275 				MDIFF(d, i2, i1, igps_snd_reports);
1276 				prevp = diffptr++;
1277 				break;
1278 			}
1279 			case MIB2_ICMP: {
1280 				mib2_icmp_t *i2;
1281 				mib2_icmp_t *i1;
1282 				mib2_icmp_t *d;
1283 
1284 				i2 = (mib2_icmp_t *)tempp2->valp;
1285 				i1 = (mib2_icmp_t *)tempp1->valp;
1286 				diffptr->group = tempp2->group;
1287 				diffptr->mib_id = tempp2->mib_id;
1288 				diffptr->length = tempp2->length;
1289 				d = (mib2_icmp_t *)calloc(tempp2->length, 1);
1290 				if (d == NULL)
1291 					goto mibdiff_out_of_memory;
1292 				diffptr->valp = d;
1293 				MDIFF(d, i2, i1, icmpInMsgs);
1294 				MDIFF(d, i2, i1, icmpInErrors);
1295 				MDIFF(d, i2, i1, icmpInCksumErrs);
1296 				MDIFF(d, i2, i1, icmpInUnknowns);
1297 				MDIFF(d, i2, i1, icmpInDestUnreachs);
1298 				MDIFF(d, i2, i1, icmpInTimeExcds);
1299 				MDIFF(d, i2, i1, icmpInParmProbs);
1300 				MDIFF(d, i2, i1, icmpInSrcQuenchs);
1301 				MDIFF(d, i2, i1, icmpInRedirects);
1302 				MDIFF(d, i2, i1, icmpInBadRedirects);
1303 				MDIFF(d, i2, i1, icmpInEchos);
1304 				MDIFF(d, i2, i1, icmpInEchoReps);
1305 				MDIFF(d, i2, i1, icmpInTimestamps);
1306 				MDIFF(d, i2, i1, icmpInAddrMasks);
1307 				MDIFF(d, i2, i1, icmpInAddrMaskReps);
1308 				MDIFF(d, i2, i1, icmpInFragNeeded);
1309 				MDIFF(d, i2, i1, icmpOutMsgs);
1310 				MDIFF(d, i2, i1, icmpOutDrops);
1311 				MDIFF(d, i2, i1, icmpOutErrors);
1312 				MDIFF(d, i2, i1, icmpOutDestUnreachs);
1313 				MDIFF(d, i2, i1, icmpOutTimeExcds);
1314 				MDIFF(d, i2, i1, icmpOutParmProbs);
1315 				MDIFF(d, i2, i1, icmpOutSrcQuenchs);
1316 				MDIFF(d, i2, i1, icmpOutRedirects);
1317 				MDIFF(d, i2, i1, icmpOutEchos);
1318 				MDIFF(d, i2, i1, icmpOutEchoReps);
1319 				MDIFF(d, i2, i1, icmpOutTimestamps);
1320 				MDIFF(d, i2, i1, icmpOutTimestampReps);
1321 				MDIFF(d, i2, i1, icmpOutAddrMasks);
1322 				MDIFF(d, i2, i1, icmpOutAddrMaskReps);
1323 				MDIFF(d, i2, i1, icmpOutFragNeeded);
1324 				MDIFF(d, i2, i1, icmpInOverflows);
1325 				prevp = diffptr++;
1326 				break;
1327 			}
1328 			case MIB2_ICMP6: {
1329 	mib2_ipv6IfIcmpEntry_t *i2;
1330 	mib2_ipv6IfIcmpEntry_t *i1;
1331 	mib2_ipv6IfIcmpEntry_t *d;
1332 
1333 	i2 = (mib2_ipv6IfIcmpEntry_t *)tempp2->valp;
1334 	i1 = (mib2_ipv6IfIcmpEntry_t *)tempp1->valp;
1335 	diffptr->group = tempp2->group;
1336 	diffptr->mib_id = tempp2->mib_id;
1337 	diffptr->length = tempp2->length;
1338 	d = (mib2_ipv6IfIcmpEntry_t *)calloc(tempp2->length, 1);
1339 	if (d == NULL)
1340 		goto mibdiff_out_of_memory;
1341 	diffptr->valp = d;
1342 	MDIFF(d, i2, i1, ipv6IfIcmpInMsgs);
1343 	MDIFF(d, i2, i1, ipv6IfIcmpInErrors);
1344 	MDIFF(d, i2, i1, ipv6IfIcmpInDestUnreachs);
1345 	MDIFF(d, i2, i1, ipv6IfIcmpInAdminProhibs);
1346 	MDIFF(d, i2, i1, ipv6IfIcmpInTimeExcds);
1347 	MDIFF(d, i2, i1, ipv6IfIcmpInParmProblems);
1348 	MDIFF(d, i2, i1, ipv6IfIcmpInPktTooBigs);
1349 	MDIFF(d, i2, i1, ipv6IfIcmpInEchos);
1350 	MDIFF(d, i2, i1, ipv6IfIcmpInEchoReplies);
1351 	MDIFF(d, i2, i1, ipv6IfIcmpInRouterSolicits);
1352 	MDIFF(d, i2, i1, ipv6IfIcmpInRouterAdvertisements);
1353 	MDIFF(d, i2, i1, ipv6IfIcmpInNeighborSolicits);
1354 	MDIFF(d, i2, i1, ipv6IfIcmpInNeighborAdvertisements);
1355 	MDIFF(d, i2, i1, ipv6IfIcmpInRedirects);
1356 	MDIFF(d, i2, i1, ipv6IfIcmpInBadRedirects);
1357 	MDIFF(d, i2, i1, ipv6IfIcmpInGroupMembQueries);
1358 	MDIFF(d, i2, i1, ipv6IfIcmpInGroupMembResponses);
1359 	MDIFF(d, i2, i1, ipv6IfIcmpInGroupMembReductions);
1360 	MDIFF(d, i2, i1, ipv6IfIcmpInOverflows);
1361 	MDIFF(d, i2, i1, ipv6IfIcmpOutMsgs);
1362 	MDIFF(d, i2, i1, ipv6IfIcmpOutErrors);
1363 	MDIFF(d, i2, i1, ipv6IfIcmpOutDestUnreachs);
1364 	MDIFF(d, i2, i1, ipv6IfIcmpOutAdminProhibs);
1365 	MDIFF(d, i2, i1, ipv6IfIcmpOutTimeExcds);
1366 	MDIFF(d, i2, i1, ipv6IfIcmpOutParmProblems);
1367 	MDIFF(d, i2, i1, ipv6IfIcmpOutPktTooBigs);
1368 	MDIFF(d, i2, i1, ipv6IfIcmpOutEchos);
1369 	MDIFF(d, i2, i1, ipv6IfIcmpOutEchoReplies);
1370 	MDIFF(d, i2, i1, ipv6IfIcmpOutRouterSolicits);
1371 	MDIFF(d, i2, i1, ipv6IfIcmpOutRouterAdvertisements);
1372 	MDIFF(d, i2, i1, ipv6IfIcmpOutNeighborSolicits);
1373 	MDIFF(d, i2, i1, ipv6IfIcmpOutNeighborAdvertisements);
1374 	MDIFF(d, i2, i1, ipv6IfIcmpOutRedirects);
1375 	MDIFF(d, i2, i1, ipv6IfIcmpOutGroupMembQueries);
1376 	MDIFF(d, i2, i1, ipv6IfIcmpOutGroupMembResponses);
1377 	MDIFF(d, i2, i1, ipv6IfIcmpOutGroupMembReductions);
1378 	prevp = diffptr++;
1379 	break;
1380 			}
1381 			case MIB2_TCP: {
1382 				mib2_tcp_t *t2;
1383 				mib2_tcp_t *t1;
1384 				mib2_tcp_t *d;
1385 
1386 				t2 = (mib2_tcp_t *)tempp2->valp;
1387 				t1 = (mib2_tcp_t *)tempp1->valp;
1388 				diffptr->group = tempp2->group;
1389 				diffptr->mib_id = tempp2->mib_id;
1390 				diffptr->length = tempp2->length;
1391 				d = (mib2_tcp_t *)calloc(tempp2->length, 1);
1392 				if (d == NULL)
1393 					goto mibdiff_out_of_memory;
1394 				diffptr->valp = d;
1395 				d->tcpRtoMin = t2->tcpRtoMin;
1396 				d->tcpRtoMax = t2->tcpRtoMax;
1397 				d->tcpMaxConn = t2->tcpMaxConn;
1398 				MDIFF(d, t2, t1, tcpActiveOpens);
1399 				MDIFF(d, t2, t1, tcpPassiveOpens);
1400 				MDIFF(d, t2, t1, tcpAttemptFails);
1401 				MDIFF(d, t2, t1, tcpEstabResets);
1402 				d->tcpCurrEstab = t2->tcpCurrEstab;
1403 				MDIFF(d, t2, t1, tcpHCOutSegs);
1404 				MDIFF(d, t2, t1, tcpOutDataSegs);
1405 				MDIFF(d, t2, t1, tcpOutDataBytes);
1406 				MDIFF(d, t2, t1, tcpRetransSegs);
1407 				MDIFF(d, t2, t1, tcpRetransBytes);
1408 				MDIFF(d, t2, t1, tcpOutAck);
1409 				MDIFF(d, t2, t1, tcpOutAckDelayed);
1410 				MDIFF(d, t2, t1, tcpOutUrg);
1411 				MDIFF(d, t2, t1, tcpOutWinUpdate);
1412 				MDIFF(d, t2, t1, tcpOutWinProbe);
1413 				MDIFF(d, t2, t1, tcpOutControl);
1414 				MDIFF(d, t2, t1, tcpOutRsts);
1415 				MDIFF(d, t2, t1, tcpOutFastRetrans);
1416 				MDIFF(d, t2, t1, tcpHCInSegs);
1417 				MDIFF(d, t2, t1, tcpInAckSegs);
1418 				MDIFF(d, t2, t1, tcpInAckBytes);
1419 				MDIFF(d, t2, t1, tcpInDupAck);
1420 				MDIFF(d, t2, t1, tcpInAckUnsent);
1421 				MDIFF(d, t2, t1, tcpInDataInorderSegs);
1422 				MDIFF(d, t2, t1, tcpInDataInorderBytes);
1423 				MDIFF(d, t2, t1, tcpInDataUnorderSegs);
1424 				MDIFF(d, t2, t1, tcpInDataUnorderBytes);
1425 				MDIFF(d, t2, t1, tcpInDataDupSegs);
1426 				MDIFF(d, t2, t1, tcpInDataDupBytes);
1427 				MDIFF(d, t2, t1, tcpInDataPartDupSegs);
1428 				MDIFF(d, t2, t1, tcpInDataPartDupBytes);
1429 				MDIFF(d, t2, t1, tcpInDataPastWinSegs);
1430 				MDIFF(d, t2, t1, tcpInDataPastWinBytes);
1431 				MDIFF(d, t2, t1, tcpInWinProbe);
1432 				MDIFF(d, t2, t1, tcpInWinUpdate);
1433 				MDIFF(d, t2, t1, tcpInClosed);
1434 				MDIFF(d, t2, t1, tcpRttNoUpdate);
1435 				MDIFF(d, t2, t1, tcpRttUpdate);
1436 				MDIFF(d, t2, t1, tcpTimRetrans);
1437 				MDIFF(d, t2, t1, tcpTimRetransDrop);
1438 				MDIFF(d, t2, t1, tcpTimKeepalive);
1439 				MDIFF(d, t2, t1, tcpTimKeepaliveProbe);
1440 				MDIFF(d, t2, t1, tcpTimKeepaliveDrop);
1441 				MDIFF(d, t2, t1, tcpListenDrop);
1442 				MDIFF(d, t2, t1, tcpListenDropQ0);
1443 				MDIFF(d, t2, t1, tcpHalfOpenDrop);
1444 				MDIFF(d, t2, t1, tcpOutSackRetransSegs);
1445 				prevp = diffptr++;
1446 				break;
1447 			}
1448 			case MIB2_UDP: {
1449 				mib2_udp_t *u2;
1450 				mib2_udp_t *u1;
1451 				mib2_udp_t *d;
1452 
1453 				u2 = (mib2_udp_t *)tempp2->valp;
1454 				u1 = (mib2_udp_t *)tempp1->valp;
1455 				diffptr->group = tempp2->group;
1456 				diffptr->mib_id = tempp2->mib_id;
1457 				diffptr->length = tempp2->length;
1458 				d = (mib2_udp_t *)calloc(tempp2->length, 1);
1459 				if (d == NULL)
1460 					goto mibdiff_out_of_memory;
1461 				diffptr->valp = d;
1462 				MDIFF(d, u2, u1, udpHCInDatagrams);
1463 				MDIFF(d, u2, u1, udpInErrors);
1464 				MDIFF(d, u2, u1, udpHCOutDatagrams);
1465 				MDIFF(d, u2, u1, udpOutErrors);
1466 				prevp = diffptr++;
1467 				break;
1468 			}
1469 			case MIB2_SCTP: {
1470 				mib2_sctp_t *s2;
1471 				mib2_sctp_t *s1;
1472 				mib2_sctp_t *d;
1473 
1474 				s2 = (mib2_sctp_t *)tempp2->valp;
1475 				s1 = (mib2_sctp_t *)tempp1->valp;
1476 				diffptr->group = tempp2->group;
1477 				diffptr->mib_id = tempp2->mib_id;
1478 				diffptr->length = tempp2->length;
1479 				d = (mib2_sctp_t *)calloc(tempp2->length, 1);
1480 				if (d == NULL)
1481 					goto mibdiff_out_of_memory;
1482 				diffptr->valp = d;
1483 				d->sctpRtoAlgorithm = s2->sctpRtoAlgorithm;
1484 				d->sctpRtoMin = s2->sctpRtoMin;
1485 				d->sctpRtoMax = s2->sctpRtoMax;
1486 				d->sctpRtoInitial = s2->sctpRtoInitial;
1487 				d->sctpMaxAssocs = s2->sctpMaxAssocs;
1488 				d->sctpValCookieLife = s2->sctpValCookieLife;
1489 				d->sctpMaxInitRetr = s2->sctpMaxInitRetr;
1490 				d->sctpCurrEstab = s2->sctpCurrEstab;
1491 				MDIFF(d, s2, s1, sctpActiveEstab);
1492 				MDIFF(d, s2, s1, sctpPassiveEstab);
1493 				MDIFF(d, s2, s1, sctpAborted);
1494 				MDIFF(d, s2, s1, sctpShutdowns);
1495 				MDIFF(d, s2, s1, sctpOutOfBlue);
1496 				MDIFF(d, s2, s1, sctpChecksumError);
1497 				MDIFF(d, s2, s1, sctpOutCtrlChunks);
1498 				MDIFF(d, s2, s1, sctpOutOrderChunks);
1499 				MDIFF(d, s2, s1, sctpOutUnorderChunks);
1500 				MDIFF(d, s2, s1, sctpRetransChunks);
1501 				MDIFF(d, s2, s1, sctpOutAck);
1502 				MDIFF(d, s2, s1, sctpOutAckDelayed);
1503 				MDIFF(d, s2, s1, sctpOutWinUpdate);
1504 				MDIFF(d, s2, s1, sctpOutFastRetrans);
1505 				MDIFF(d, s2, s1, sctpOutWinProbe);
1506 				MDIFF(d, s2, s1, sctpInCtrlChunks);
1507 				MDIFF(d, s2, s1, sctpInOrderChunks);
1508 				MDIFF(d, s2, s1, sctpInUnorderChunks);
1509 				MDIFF(d, s2, s1, sctpInAck);
1510 				MDIFF(d, s2, s1, sctpInDupAck);
1511 				MDIFF(d, s2, s1, sctpInAckUnsent);
1512 				MDIFF(d, s2, s1, sctpFragUsrMsgs);
1513 				MDIFF(d, s2, s1, sctpReasmUsrMsgs);
1514 				MDIFF(d, s2, s1, sctpOutSCTPPkts);
1515 				MDIFF(d, s2, s1, sctpInSCTPPkts);
1516 				MDIFF(d, s2, s1, sctpInInvalidCookie);
1517 				MDIFF(d, s2, s1, sctpTimRetrans);
1518 				MDIFF(d, s2, s1, sctpTimRetransDrop);
1519 				MDIFF(d, s2, s1, sctpTimHeartBeatProbe);
1520 				MDIFF(d, s2, s1, sctpTimHeartBeatDrop);
1521 				MDIFF(d, s2, s1, sctpListenDrop);
1522 				MDIFF(d, s2, s1, sctpInClosed);
1523 				prevp = diffptr++;
1524 				break;
1525 			}
1526 			case EXPER_RAWIP: {
1527 				mib2_rawip_t *r2;
1528 				mib2_rawip_t *r1;
1529 				mib2_rawip_t *d;
1530 
1531 				r2 = (mib2_rawip_t *)tempp2->valp;
1532 				r1 = (mib2_rawip_t *)tempp1->valp;
1533 				diffptr->group = tempp2->group;
1534 				diffptr->mib_id = tempp2->mib_id;
1535 				diffptr->length = tempp2->length;
1536 				d = (mib2_rawip_t *)calloc(tempp2->length, 1);
1537 				if (d == NULL)
1538 					goto mibdiff_out_of_memory;
1539 				diffptr->valp = d;
1540 				MDIFF(d, r2, r1, rawipInDatagrams);
1541 				MDIFF(d, r2, r1, rawipInErrors);
1542 				MDIFF(d, r2, r1, rawipInCksumErrs);
1543 				MDIFF(d, r2, r1, rawipOutDatagrams);
1544 				MDIFF(d, r2, r1, rawipOutErrors);
1545 				prevp = diffptr++;
1546 				break;
1547 			}
1548 			/*
1549 			 * there are more "group" types but they aren't
1550 			 * required for the -s and -Ms options
1551 			 */
1552 			}
1553 		} /* 'for' loop 2 ends */
1554 		tempp1 = NULL;
1555 	} /* 'for' loop 1 ends */
1556 	tempp2 = NULL;
1557 	diffptr--;
1558 	diffptr->next_item = NULL;
1559 	return (diffp);
1560 
1561 mibdiff_out_of_memory:;
1562 	mib_item_destroy(&diffp);
1563 	return (NULL);
1564 }
1565 
1566 /*
1567  * mib_item_destroy: cleans up a mib_item_t *
1568  * that was created by calling mib_item_dup or
1569  * mib_item_diff
1570  */
1571 static void
1572 mib_item_destroy(mib_item_t **itemp)
1573 {
1574 	int	nitems = 0;
1575 	int	c = 0;
1576 	mib_item_t *tempp;
1577 
1578 	if (itemp == NULL || *itemp == NULL)
1579 		return;
1580 
1581 	for (tempp = *itemp; tempp != NULL; tempp = tempp->next_item)
1582 		if (tempp->mib_id == 0)
1583 			nitems++;
1584 		else
1585 			return;	/* cannot destroy! */
1586 
1587 	if (nitems == 0)
1588 		return;		/* cannot destroy! */
1589 
1590 	for (c = nitems - 1; c >= 0; c--) {
1591 		if ((itemp[0][c]).valp != NULL)
1592 			free((itemp[0][c]).valp);
1593 	}
1594 	free(*itemp);
1595 
1596 	*itemp = NULL;
1597 }
1598 
1599 /* Compare two Octet_ts.  Return B_TRUE if they match, B_FALSE if not. */
1600 static boolean_t
1601 octetstrmatch(const Octet_t *a, const Octet_t *b)
1602 {
1603 	if (a == NULL || b == NULL)
1604 		return (B_FALSE);
1605 
1606 	if (a->o_length != b->o_length)
1607 		return (B_FALSE);
1608 
1609 	return (memcmp(a->o_bytes, b->o_bytes, a->o_length) == 0);
1610 }
1611 
1612 /* If octetstr() changes make an appropriate change to STR_EXPAND */
1613 static char *
1614 octetstr(const Octet_t *op, int code, char *dst, uint_t dstlen)
1615 {
1616 	int	i;
1617 	char	*cp;
1618 
1619 	cp = dst;
1620 	if (op) {
1621 		for (i = 0; i < op->o_length; i++) {
1622 			switch (code) {
1623 			case 'd':
1624 				if (cp - dst + 4 > dstlen) {
1625 					*cp = '\0';
1626 					return (dst);
1627 				}
1628 				(void) snprintf(cp, 5, "%d.",
1629 				    0xff & op->o_bytes[i]);
1630 				cp = strchr(cp, '\0');
1631 				break;
1632 			case 'a':
1633 				if (cp - dst + 1 > dstlen) {
1634 					*cp = '\0';
1635 					return (dst);
1636 				}
1637 				*cp++ = op->o_bytes[i];
1638 				break;
1639 			case 'h':
1640 			default:
1641 				if (cp - dst + 3 > dstlen) {
1642 					*cp = '\0';
1643 					return (dst);
1644 				}
1645 				(void) snprintf(cp, 4, "%02x:",
1646 				    0xff & op->o_bytes[i]);
1647 				cp += 3;
1648 				break;
1649 			}
1650 		}
1651 	}
1652 	if (code != 'a' && cp != dst)
1653 		cp--;
1654 	*cp = '\0';
1655 	return (dst);
1656 }
1657 
1658 static const char *
1659 mitcp_state(int state, const mib2_transportMLPEntry_t *attr)
1660 {
1661 	static char tcpsbuf[50];
1662 	const char *cp;
1663 
1664 	switch (state) {
1665 	case TCPS_CLOSED:
1666 		cp = "CLOSED";
1667 		break;
1668 	case TCPS_IDLE:
1669 		cp = "IDLE";
1670 		break;
1671 	case TCPS_BOUND:
1672 		cp = "BOUND";
1673 		break;
1674 	case TCPS_LISTEN:
1675 		cp = "LISTEN";
1676 		break;
1677 	case TCPS_SYN_SENT:
1678 		cp = "SYN_SENT";
1679 		break;
1680 	case TCPS_SYN_RCVD:
1681 		cp = "SYN_RCVD";
1682 		break;
1683 	case TCPS_ESTABLISHED:
1684 		cp = "ESTABLISHED";
1685 		break;
1686 	case TCPS_CLOSE_WAIT:
1687 		cp = "CLOSE_WAIT";
1688 		break;
1689 	case TCPS_FIN_WAIT_1:
1690 		cp = "FIN_WAIT_1";
1691 		break;
1692 	case TCPS_CLOSING:
1693 		cp = "CLOSING";
1694 		break;
1695 	case TCPS_LAST_ACK:
1696 		cp = "LAST_ACK";
1697 		break;
1698 	case TCPS_FIN_WAIT_2:
1699 		cp = "FIN_WAIT_2";
1700 		break;
1701 	case TCPS_TIME_WAIT:
1702 		cp = "TIME_WAIT";
1703 		break;
1704 	default:
1705 		(void) snprintf(tcpsbuf, sizeof (tcpsbuf),
1706 		    "UnknownState(%d)", state);
1707 		cp = tcpsbuf;
1708 		break;
1709 	}
1710 
1711 	if (RSECflag && attr != NULL && attr->tme_flags != 0) {
1712 		if (cp != tcpsbuf) {
1713 			(void) strlcpy(tcpsbuf, cp, sizeof (tcpsbuf));
1714 			cp = tcpsbuf;
1715 		}
1716 		if (attr->tme_flags & MIB2_TMEF_PRIVATE)
1717 			(void) strlcat(tcpsbuf, " P", sizeof (tcpsbuf));
1718 		if (attr->tme_flags & MIB2_TMEF_SHARED)
1719 			(void) strlcat(tcpsbuf, " S", sizeof (tcpsbuf));
1720 	}
1721 
1722 	return (cp);
1723 }
1724 
1725 static const char *
1726 miudp_state(int state, const mib2_transportMLPEntry_t *attr)
1727 {
1728 	static char udpsbuf[50];
1729 	const char *cp;
1730 
1731 	switch (state) {
1732 	case MIB2_UDP_unbound:
1733 		cp = "Unbound";
1734 		break;
1735 	case MIB2_UDP_idle:
1736 		cp = "Idle";
1737 		break;
1738 	case MIB2_UDP_connected:
1739 		cp = "Connected";
1740 		break;
1741 	default:
1742 		(void) snprintf(udpsbuf, sizeof (udpsbuf),
1743 		    "Unknown State(%d)", state);
1744 		cp = udpsbuf;
1745 		break;
1746 	}
1747 
1748 	if (RSECflag && attr != NULL && attr->tme_flags != 0) {
1749 		if (cp != udpsbuf) {
1750 			(void) strlcpy(udpsbuf, cp, sizeof (udpsbuf));
1751 			cp = udpsbuf;
1752 		}
1753 		if (attr->tme_flags & MIB2_TMEF_PRIVATE)
1754 			(void) strlcat(udpsbuf, " P", sizeof (udpsbuf));
1755 		if (attr->tme_flags & MIB2_TMEF_SHARED)
1756 			(void) strlcat(udpsbuf, " S", sizeof (udpsbuf));
1757 	}
1758 
1759 	return (cp);
1760 }
1761 
1762 static int odd;
1763 
1764 static void
1765 prval_init(void)
1766 {
1767 	odd = 0;
1768 }
1769 
1770 static void
1771 prval(char *str, Counter val)
1772 {
1773 	(void) printf("\t%-20s=%6u", str, val);
1774 	if (odd++ & 1)
1775 		(void) putchar('\n');
1776 }
1777 
1778 static void
1779 prval64(char *str, Counter64 val)
1780 {
1781 	(void) printf("\t%-20s=%6llu", str, val);
1782 	if (odd++ & 1)
1783 		(void) putchar('\n');
1784 }
1785 
1786 static void
1787 pr_int_val(char *str, int val)
1788 {
1789 	(void) printf("\t%-20s=%6d", str, val);
1790 	if (odd++ & 1)
1791 		(void) putchar('\n');
1792 }
1793 
1794 static void
1795 pr_sctp_rtoalgo(char *str, int val)
1796 {
1797 	(void) printf("\t%-20s=", str);
1798 	switch (val) {
1799 		case MIB2_SCTP_RTOALGO_OTHER:
1800 			(void) printf("%6.6s", "other");
1801 			break;
1802 
1803 		case MIB2_SCTP_RTOALGO_VANJ:
1804 			(void) printf("%6.6s", "vanj");
1805 			break;
1806 
1807 		default:
1808 			(void) printf("%6d", val);
1809 			break;
1810 	}
1811 	if (odd++ & 1)
1812 		(void) putchar('\n');
1813 }
1814 
1815 static void
1816 prval_end(void)
1817 {
1818 	if (odd++ & 1)
1819 		(void) putchar('\n');
1820 }
1821 
1822 /* Extract constant sizes */
1823 static void
1824 mib_get_constants(mib_item_t *item)
1825 {
1826 	/* 'for' loop 1: */
1827 	for (; item; item = item->next_item) {
1828 		if (item->mib_id != 0)
1829 			continue; /* 'for' loop 1 */
1830 
1831 		switch (item->group) {
1832 		case MIB2_IP: {
1833 			mib2_ip_t	*ip = (mib2_ip_t *)item->valp;
1834 
1835 			ipAddrEntrySize = ip->ipAddrEntrySize;
1836 			ipRouteEntrySize = ip->ipRouteEntrySize;
1837 			ipNetToMediaEntrySize = ip->ipNetToMediaEntrySize;
1838 			ipMemberEntrySize = ip->ipMemberEntrySize;
1839 			ipGroupSourceEntrySize = ip->ipGroupSourceEntrySize;
1840 			ipRouteAttributeSize = ip->ipRouteAttributeSize;
1841 			transportMLPSize = ip->transportMLPSize;
1842 			ipDestEntrySize = ip->ipDestEntrySize;
1843 			assert(IS_P2ALIGNED(ipAddrEntrySize,
1844 			    sizeof (mib2_ipAddrEntry_t *)));
1845 			assert(IS_P2ALIGNED(ipRouteEntrySize,
1846 			    sizeof (mib2_ipRouteEntry_t *)));
1847 			assert(IS_P2ALIGNED(ipNetToMediaEntrySize,
1848 			    sizeof (mib2_ipNetToMediaEntry_t *)));
1849 			assert(IS_P2ALIGNED(ipMemberEntrySize,
1850 			    sizeof (ip_member_t *)));
1851 			assert(IS_P2ALIGNED(ipGroupSourceEntrySize,
1852 			    sizeof (ip_grpsrc_t *)));
1853 			assert(IS_P2ALIGNED(ipRouteAttributeSize,
1854 			    sizeof (mib2_ipAttributeEntry_t *)));
1855 			assert(IS_P2ALIGNED(transportMLPSize,
1856 			    sizeof (mib2_transportMLPEntry_t *)));
1857 			break;
1858 		}
1859 		case EXPER_DVMRP: {
1860 			struct mrtstat	*mrts = (struct mrtstat *)item->valp;
1861 
1862 			vifctlSize = mrts->mrts_vifctlSize;
1863 			mfcctlSize = mrts->mrts_mfcctlSize;
1864 			assert(IS_P2ALIGNED(vifctlSize,
1865 			    sizeof (struct vifclt *)));
1866 			assert(IS_P2ALIGNED(mfcctlSize,
1867 			    sizeof (struct mfcctl *)));
1868 			break;
1869 		}
1870 		case MIB2_IP6: {
1871 			mib2_ipv6IfStatsEntry_t *ip6;
1872 			/* Just use the first entry */
1873 
1874 			ip6 = (mib2_ipv6IfStatsEntry_t *)item->valp;
1875 			ipv6IfStatsEntrySize = ip6->ipv6IfStatsEntrySize;
1876 			ipv6AddrEntrySize = ip6->ipv6AddrEntrySize;
1877 			ipv6RouteEntrySize = ip6->ipv6RouteEntrySize;
1878 			ipv6NetToMediaEntrySize = ip6->ipv6NetToMediaEntrySize;
1879 			ipv6MemberEntrySize = ip6->ipv6MemberEntrySize;
1880 			ipv6GroupSourceEntrySize =
1881 			    ip6->ipv6GroupSourceEntrySize;
1882 			assert(IS_P2ALIGNED(ipv6IfStatsEntrySize,
1883 			    sizeof (mib2_ipv6IfStatsEntry_t *)));
1884 			assert(IS_P2ALIGNED(ipv6AddrEntrySize,
1885 			    sizeof (mib2_ipv6AddrEntry_t *)));
1886 			assert(IS_P2ALIGNED(ipv6RouteEntrySize,
1887 			    sizeof (mib2_ipv6RouteEntry_t *)));
1888 			assert(IS_P2ALIGNED(ipv6NetToMediaEntrySize,
1889 			    sizeof (mib2_ipv6NetToMediaEntry_t *)));
1890 			assert(IS_P2ALIGNED(ipv6MemberEntrySize,
1891 			    sizeof (ipv6_member_t *)));
1892 			assert(IS_P2ALIGNED(ipv6GroupSourceEntrySize,
1893 			    sizeof (ipv6_grpsrc_t *)));
1894 			break;
1895 		}
1896 		case MIB2_ICMP6: {
1897 			mib2_ipv6IfIcmpEntry_t *icmp6;
1898 			/* Just use the first entry */
1899 
1900 			icmp6 = (mib2_ipv6IfIcmpEntry_t *)item->valp;
1901 			ipv6IfIcmpEntrySize = icmp6->ipv6IfIcmpEntrySize;
1902 			assert(IS_P2ALIGNED(ipv6IfIcmpEntrySize,
1903 			    sizeof (mib2_ipv6IfIcmpEntry_t *)));
1904 			break;
1905 		}
1906 		case MIB2_TCP: {
1907 			mib2_tcp_t	*tcp = (mib2_tcp_t *)item->valp;
1908 
1909 			tcpConnEntrySize = tcp->tcpConnTableSize;
1910 			tcp6ConnEntrySize = tcp->tcp6ConnTableSize;
1911 			assert(IS_P2ALIGNED(tcpConnEntrySize,
1912 			    sizeof (mib2_tcpConnEntry_t *)));
1913 			assert(IS_P2ALIGNED(tcp6ConnEntrySize,
1914 			    sizeof (mib2_tcp6ConnEntry_t *)));
1915 			break;
1916 		}
1917 		case MIB2_UDP: {
1918 			mib2_udp_t	*udp = (mib2_udp_t *)item->valp;
1919 
1920 			udpEntrySize = udp->udpEntrySize;
1921 			udp6EntrySize = udp->udp6EntrySize;
1922 			assert(IS_P2ALIGNED(udpEntrySize,
1923 			    sizeof (mib2_udpEntry_t *)));
1924 			assert(IS_P2ALIGNED(udp6EntrySize,
1925 			    sizeof (mib2_udp6Entry_t *)));
1926 			break;
1927 		}
1928 		case MIB2_SCTP: {
1929 			mib2_sctp_t	*sctp = (mib2_sctp_t *)item->valp;
1930 
1931 			sctpEntrySize = sctp->sctpEntrySize;
1932 			sctpLocalEntrySize = sctp->sctpLocalEntrySize;
1933 			sctpRemoteEntrySize = sctp->sctpRemoteEntrySize;
1934 			break;
1935 		}
1936 		}
1937 	} /* 'for' loop 1 ends */
1938 
1939 	if (Xflag) {
1940 		(void) puts("mib_get_constants:");
1941 		(void) printf("\tipv6IfStatsEntrySize %d\n",
1942 		    ipv6IfStatsEntrySize);
1943 		(void) printf("\tipAddrEntrySize %d\n", ipAddrEntrySize);
1944 		(void) printf("\tipRouteEntrySize %d\n", ipRouteEntrySize);
1945 		(void) printf("\tipNetToMediaEntrySize %d\n",
1946 		    ipNetToMediaEntrySize);
1947 		(void) printf("\tipMemberEntrySize %d\n", ipMemberEntrySize);
1948 		(void) printf("\tipRouteAttributeSize %d\n",
1949 		    ipRouteAttributeSize);
1950 		(void) printf("\tvifctlSize %d\n", vifctlSize);
1951 		(void) printf("\tmfcctlSize %d\n", mfcctlSize);
1952 
1953 		(void) printf("\tipv6AddrEntrySize %d\n", ipv6AddrEntrySize);
1954 		(void) printf("\tipv6RouteEntrySize %d\n", ipv6RouteEntrySize);
1955 		(void) printf("\tipv6NetToMediaEntrySize %d\n",
1956 		    ipv6NetToMediaEntrySize);
1957 		(void) printf("\tipv6MemberEntrySize %d\n",
1958 		    ipv6MemberEntrySize);
1959 		(void) printf("\tipv6IfIcmpEntrySize %d\n",
1960 		    ipv6IfIcmpEntrySize);
1961 		(void) printf("\tipDestEntrySize %d\n", ipDestEntrySize);
1962 		(void) printf("\ttransportMLPSize %d\n", transportMLPSize);
1963 		(void) printf("\ttcpConnEntrySize %d\n", tcpConnEntrySize);
1964 		(void) printf("\ttcp6ConnEntrySize %d\n", tcp6ConnEntrySize);
1965 		(void) printf("\tudpEntrySize %d\n", udpEntrySize);
1966 		(void) printf("\tudp6EntrySize %d\n", udp6EntrySize);
1967 		(void) printf("\tsctpEntrySize %d\n", sctpEntrySize);
1968 		(void) printf("\tsctpLocalEntrySize %d\n", sctpLocalEntrySize);
1969 		(void) printf("\tsctpRemoteEntrySize %d\n",
1970 		    sctpRemoteEntrySize);
1971 	}
1972 }
1973 
1974 
1975 /* ----------------------------- STAT_REPORT ------------------------------- */
1976 
1977 static void
1978 stat_report(mib_item_t *item)
1979 {
1980 	int	jtemp = 0;
1981 	char	ifname[LIFNAMSIZ + 1];
1982 
1983 	/* 'for' loop 1: */
1984 	for (; item; item = item->next_item) {
1985 		if (Xflag) {
1986 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
1987 			(void) printf("Group = %d, mib_id = %d, "
1988 			    "length = %d, valp = 0x%p\n",
1989 			    item->group, item->mib_id,
1990 			    item->length, item->valp);
1991 		}
1992 		if (item->mib_id != 0)
1993 			continue; /* 'for' loop 1 */
1994 
1995 		switch (item->group) {
1996 		case MIB2_IP: {
1997 			mib2_ip_t	*ip = (mib2_ip_t *)item->valp;
1998 
1999 			if (protocol_selected(IPPROTO_IP) &&
2000 			    family_selected(AF_INET)) {
2001 				(void) fputs(v4compat ? "\nIP" : "\nIPv4",
2002 				    stdout);
2003 				print_ip_stats(ip);
2004 			}
2005 			break;
2006 		}
2007 		case MIB2_ICMP: {
2008 			mib2_icmp_t	*icmp =
2009 			    (mib2_icmp_t *)item->valp;
2010 
2011 			if (protocol_selected(IPPROTO_ICMP) &&
2012 			    family_selected(AF_INET)) {
2013 				(void) fputs(v4compat ? "\nICMP" : "\nICMPv4",
2014 				    stdout);
2015 				print_icmp_stats(icmp);
2016 			}
2017 			break;
2018 		}
2019 		case MIB2_IP6: {
2020 			mib2_ipv6IfStatsEntry_t *ip6;
2021 			mib2_ipv6IfStatsEntry_t sum6;
2022 
2023 			if (!(protocol_selected(IPPROTO_IPV6)) ||
2024 			    !(family_selected(AF_INET6)))
2025 				break;
2026 			bzero(&sum6, sizeof (sum6));
2027 			/* 'for' loop 2a: */
2028 			for (ip6 = (mib2_ipv6IfStatsEntry_t *)item->valp;
2029 			    (char *)ip6 < (char *)item->valp + item->length;
2030 			    /* LINTED: (note 1) */
2031 			    ip6 = (mib2_ipv6IfStatsEntry_t *)((char *)ip6 +
2032 			    ipv6IfStatsEntrySize)) {
2033 				if (ip6->ipv6IfIndex == 0) {
2034 					/*
2035 					 * The "unknown interface" ip6
2036 					 * mib. Just add to the sum.
2037 					 */
2038 					sum_ip6_stats(ip6, &sum6);
2039 					continue; /* 'for' loop 2a */
2040 				}
2041 				if (Aflag) {
2042 					(void) printf("\nIPv6 for %s\n",
2043 					    ifindex2str(ip6->ipv6IfIndex,
2044 					    ifname));
2045 					print_ip6_stats(ip6);
2046 				}
2047 				sum_ip6_stats(ip6, &sum6);
2048 			} /* 'for' loop 2a ends */
2049 			(void) fputs("\nIPv6", stdout);
2050 			print_ip6_stats(&sum6);
2051 			break;
2052 		}
2053 		case MIB2_ICMP6: {
2054 			mib2_ipv6IfIcmpEntry_t *icmp6;
2055 			mib2_ipv6IfIcmpEntry_t sum6;
2056 
2057 			if (!(protocol_selected(IPPROTO_ICMPV6)) ||
2058 			    !(family_selected(AF_INET6)))
2059 				break;
2060 			bzero(&sum6, sizeof (sum6));
2061 			/* 'for' loop 2b: */
2062 			for (icmp6 = (mib2_ipv6IfIcmpEntry_t *)item->valp;
2063 			    (char *)icmp6 < (char *)item->valp + item->length;
2064 			    icmp6 = (void *)((char *)icmp6 +
2065 			    ipv6IfIcmpEntrySize)) {
2066 				if (icmp6->ipv6IfIcmpIfIndex == 0) {
2067 					/*
2068 					 * The "unknown interface" icmp6
2069 					 * mib. Just add to the sum.
2070 					 */
2071 					sum_icmp6_stats(icmp6, &sum6);
2072 					continue; /* 'for' loop 2b: */
2073 				}
2074 				if (Aflag) {
2075 					(void) printf("\nICMPv6 for %s\n",
2076 					    ifindex2str(
2077 					    icmp6->ipv6IfIcmpIfIndex, ifname));
2078 					print_icmp6_stats(icmp6);
2079 				}
2080 				sum_icmp6_stats(icmp6, &sum6);
2081 			} /* 'for' loop 2b ends */
2082 			(void) fputs("\nICMPv6", stdout);
2083 			print_icmp6_stats(&sum6);
2084 			break;
2085 		}
2086 		case MIB2_TCP: {
2087 			mib2_tcp_t	*tcp = (mib2_tcp_t *)item->valp;
2088 
2089 			if (protocol_selected(IPPROTO_TCP) &&
2090 			    (family_selected(AF_INET) ||
2091 			    family_selected(AF_INET6))) {
2092 				(void) fputs("\nTCP", stdout);
2093 				print_tcp_stats(tcp);
2094 			}
2095 			break;
2096 		}
2097 		case MIB2_UDP: {
2098 			mib2_udp_t	*udp = (mib2_udp_t *)item->valp;
2099 
2100 			if (protocol_selected(IPPROTO_UDP) &&
2101 			    (family_selected(AF_INET) ||
2102 			    family_selected(AF_INET6))) {
2103 				(void) fputs("\nUDP", stdout);
2104 				print_udp_stats(udp);
2105 			}
2106 			break;
2107 		}
2108 		case MIB2_SCTP: {
2109 			mib2_sctp_t	*sctp = (mib2_sctp_t *)item->valp;
2110 
2111 			if (protocol_selected(IPPROTO_SCTP) &&
2112 			    (family_selected(AF_INET) ||
2113 			    family_selected(AF_INET6))) {
2114 				(void) fputs("\nSCTP", stdout);
2115 				print_sctp_stats(sctp);
2116 			}
2117 			break;
2118 		}
2119 		case EXPER_RAWIP: {
2120 			mib2_rawip_t	*rawip =
2121 			    (mib2_rawip_t *)item->valp;
2122 
2123 			if (protocol_selected(IPPROTO_RAW) &&
2124 			    (family_selected(AF_INET) ||
2125 			    family_selected(AF_INET6))) {
2126 				(void) fputs("\nRAWIP", stdout);
2127 				print_rawip_stats(rawip);
2128 			}
2129 			break;
2130 		}
2131 		case EXPER_IGMP: {
2132 			struct igmpstat	*igps =
2133 			    (struct igmpstat *)item->valp;
2134 
2135 			if (protocol_selected(IPPROTO_IGMP) &&
2136 			    (family_selected(AF_INET))) {
2137 				(void) fputs("\nIGMP:\n", stdout);
2138 				print_igmp_stats(igps);
2139 			}
2140 			break;
2141 		}
2142 		}
2143 	} /* 'for' loop 1 ends */
2144 	(void) putchar('\n');
2145 	(void) fflush(stdout);
2146 }
2147 
2148 static void
2149 print_ip_stats(mib2_ip_t *ip)
2150 {
2151 	prval_init();
2152 	pr_int_val("ipForwarding",	ip->ipForwarding);
2153 	pr_int_val("ipDefaultTTL",	ip->ipDefaultTTL);
2154 	prval("ipInReceives",		ip->ipInReceives);
2155 	prval("ipInHdrErrors",		ip->ipInHdrErrors);
2156 	prval("ipInAddrErrors",		ip->ipInAddrErrors);
2157 	prval("ipInCksumErrs",		ip->ipInCksumErrs);
2158 	prval("ipForwDatagrams",	ip->ipForwDatagrams);
2159 	prval("ipForwProhibits",	ip->ipForwProhibits);
2160 	prval("ipInUnknownProtos",	ip->ipInUnknownProtos);
2161 	prval("ipInDiscards",		ip->ipInDiscards);
2162 	prval("ipInDelivers",		ip->ipInDelivers);
2163 	prval("ipOutRequests",		ip->ipOutRequests);
2164 	prval("ipOutDiscards",		ip->ipOutDiscards);
2165 	prval("ipOutNoRoutes",		ip->ipOutNoRoutes);
2166 	pr_int_val("ipReasmTimeout",	ip->ipReasmTimeout);
2167 	prval("ipReasmReqds",		ip->ipReasmReqds);
2168 	prval("ipReasmOKs",		ip->ipReasmOKs);
2169 	prval("ipReasmFails",		ip->ipReasmFails);
2170 	prval("ipReasmDuplicates",	ip->ipReasmDuplicates);
2171 	prval("ipReasmPartDups",	ip->ipReasmPartDups);
2172 	prval("ipFragOKs",		ip->ipFragOKs);
2173 	prval("ipFragFails",		ip->ipFragFails);
2174 	prval("ipFragCreates",		ip->ipFragCreates);
2175 	prval("ipRoutingDiscards",	ip->ipRoutingDiscards);
2176 
2177 	prval("tcpInErrs",		ip->tcpInErrs);
2178 	prval("udpNoPorts",		ip->udpNoPorts);
2179 	prval("udpInCksumErrs",		ip->udpInCksumErrs);
2180 	prval("udpInOverflows",		ip->udpInOverflows);
2181 	prval("rawipInOverflows",	ip->rawipInOverflows);
2182 	prval("ipsecInSucceeded",	ip->ipsecInSucceeded);
2183 	prval("ipsecInFailed",		ip->ipsecInFailed);
2184 	prval("ipInIPv6",		ip->ipInIPv6);
2185 	prval("ipOutIPv6",		ip->ipOutIPv6);
2186 	prval("ipOutSwitchIPv6",	ip->ipOutSwitchIPv6);
2187 	prval_end();
2188 }
2189 
2190 static void
2191 print_icmp_stats(mib2_icmp_t *icmp)
2192 {
2193 	prval_init();
2194 	prval("icmpInMsgs",		icmp->icmpInMsgs);
2195 	prval("icmpInErrors",		icmp->icmpInErrors);
2196 	prval("icmpInCksumErrs",	icmp->icmpInCksumErrs);
2197 	prval("icmpInUnknowns",		icmp->icmpInUnknowns);
2198 	prval("icmpInDestUnreachs",	icmp->icmpInDestUnreachs);
2199 	prval("icmpInTimeExcds",	icmp->icmpInTimeExcds);
2200 	prval("icmpInParmProbs",	icmp->icmpInParmProbs);
2201 	prval("icmpInSrcQuenchs",	icmp->icmpInSrcQuenchs);
2202 	prval("icmpInRedirects",	icmp->icmpInRedirects);
2203 	prval("icmpInBadRedirects",	icmp->icmpInBadRedirects);
2204 	prval("icmpInEchos",		icmp->icmpInEchos);
2205 	prval("icmpInEchoReps",		icmp->icmpInEchoReps);
2206 	prval("icmpInTimestamps",	icmp->icmpInTimestamps);
2207 	prval("icmpInTimestampReps",	icmp->icmpInTimestampReps);
2208 	prval("icmpInAddrMasks",	icmp->icmpInAddrMasks);
2209 	prval("icmpInAddrMaskReps",	icmp->icmpInAddrMaskReps);
2210 	prval("icmpInFragNeeded",	icmp->icmpInFragNeeded);
2211 	prval("icmpOutMsgs",		icmp->icmpOutMsgs);
2212 	prval("icmpOutDrops",		icmp->icmpOutDrops);
2213 	prval("icmpOutErrors",		icmp->icmpOutErrors);
2214 	prval("icmpOutDestUnreachs",	icmp->icmpOutDestUnreachs);
2215 	prval("icmpOutTimeExcds",	icmp->icmpOutTimeExcds);
2216 	prval("icmpOutParmProbs",	icmp->icmpOutParmProbs);
2217 	prval("icmpOutSrcQuenchs",	icmp->icmpOutSrcQuenchs);
2218 	prval("icmpOutRedirects",	icmp->icmpOutRedirects);
2219 	prval("icmpOutEchos",		icmp->icmpOutEchos);
2220 	prval("icmpOutEchoReps",	icmp->icmpOutEchoReps);
2221 	prval("icmpOutTimestamps",	icmp->icmpOutTimestamps);
2222 	prval("icmpOutTimestampReps",	icmp->icmpOutTimestampReps);
2223 	prval("icmpOutAddrMasks",	icmp->icmpOutAddrMasks);
2224 	prval("icmpOutAddrMaskReps",	icmp->icmpOutAddrMaskReps);
2225 	prval("icmpOutFragNeeded",	icmp->icmpOutFragNeeded);
2226 	prval("icmpInOverflows",	icmp->icmpInOverflows);
2227 	prval_end();
2228 }
2229 
2230 static void
2231 print_ip6_stats(mib2_ipv6IfStatsEntry_t *ip6)
2232 {
2233 	prval_init();
2234 	prval("ipv6Forwarding",		ip6->ipv6Forwarding);
2235 	prval("ipv6DefaultHopLimit",	ip6->ipv6DefaultHopLimit);
2236 
2237 	prval("ipv6InReceives",		ip6->ipv6InReceives);
2238 	prval("ipv6InHdrErrors",	ip6->ipv6InHdrErrors);
2239 	prval("ipv6InTooBigErrors",	ip6->ipv6InTooBigErrors);
2240 	prval("ipv6InNoRoutes",		ip6->ipv6InNoRoutes);
2241 	prval("ipv6InAddrErrors",	ip6->ipv6InAddrErrors);
2242 	prval("ipv6InUnknownProtos",	ip6->ipv6InUnknownProtos);
2243 	prval("ipv6InTruncatedPkts",	ip6->ipv6InTruncatedPkts);
2244 	prval("ipv6InDiscards",		ip6->ipv6InDiscards);
2245 	prval("ipv6InDelivers",		ip6->ipv6InDelivers);
2246 	prval("ipv6OutForwDatagrams",	ip6->ipv6OutForwDatagrams);
2247 	prval("ipv6OutRequests",	ip6->ipv6OutRequests);
2248 	prval("ipv6OutDiscards",	ip6->ipv6OutDiscards);
2249 	prval("ipv6OutNoRoutes",	ip6->ipv6OutNoRoutes);
2250 	prval("ipv6OutFragOKs",		ip6->ipv6OutFragOKs);
2251 	prval("ipv6OutFragFails",	ip6->ipv6OutFragFails);
2252 	prval("ipv6OutFragCreates",	ip6->ipv6OutFragCreates);
2253 	prval("ipv6ReasmReqds",		ip6->ipv6ReasmReqds);
2254 	prval("ipv6ReasmOKs",		ip6->ipv6ReasmOKs);
2255 	prval("ipv6ReasmFails",		ip6->ipv6ReasmFails);
2256 	prval("ipv6InMcastPkts",	ip6->ipv6InMcastPkts);
2257 	prval("ipv6OutMcastPkts",	ip6->ipv6OutMcastPkts);
2258 	prval("ipv6ReasmDuplicates",	ip6->ipv6ReasmDuplicates);
2259 	prval("ipv6ReasmPartDups",	ip6->ipv6ReasmPartDups);
2260 	prval("ipv6ForwProhibits",	ip6->ipv6ForwProhibits);
2261 	prval("udpInCksumErrs",		ip6->udpInCksumErrs);
2262 	prval("udpInOverflows",		ip6->udpInOverflows);
2263 	prval("rawipInOverflows",	ip6->rawipInOverflows);
2264 	prval("ipv6InIPv4",		ip6->ipv6InIPv4);
2265 	prval("ipv6OutIPv4",		ip6->ipv6OutIPv4);
2266 	prval("ipv6OutSwitchIPv4",	ip6->ipv6OutSwitchIPv4);
2267 	prval_end();
2268 }
2269 
2270 static void
2271 print_icmp6_stats(mib2_ipv6IfIcmpEntry_t *icmp6)
2272 {
2273 	prval_init();
2274 	prval("icmp6InMsgs",		icmp6->ipv6IfIcmpInMsgs);
2275 	prval("icmp6InErrors",		icmp6->ipv6IfIcmpInErrors);
2276 	prval("icmp6InDestUnreachs",	icmp6->ipv6IfIcmpInDestUnreachs);
2277 	prval("icmp6InAdminProhibs",	icmp6->ipv6IfIcmpInAdminProhibs);
2278 	prval("icmp6InTimeExcds",	icmp6->ipv6IfIcmpInTimeExcds);
2279 	prval("icmp6InParmProblems",	icmp6->ipv6IfIcmpInParmProblems);
2280 	prval("icmp6InPktTooBigs",	icmp6->ipv6IfIcmpInPktTooBigs);
2281 	prval("icmp6InEchos",		icmp6->ipv6IfIcmpInEchos);
2282 	prval("icmp6InEchoReplies",	icmp6->ipv6IfIcmpInEchoReplies);
2283 	prval("icmp6InRouterSols",	icmp6->ipv6IfIcmpInRouterSolicits);
2284 	prval("icmp6InRouterAds",
2285 	    icmp6->ipv6IfIcmpInRouterAdvertisements);
2286 	prval("icmp6InNeighborSols",	icmp6->ipv6IfIcmpInNeighborSolicits);
2287 	prval("icmp6InNeighborAds",
2288 	    icmp6->ipv6IfIcmpInNeighborAdvertisements);
2289 	prval("icmp6InRedirects",	icmp6->ipv6IfIcmpInRedirects);
2290 	prval("icmp6InBadRedirects",	icmp6->ipv6IfIcmpInBadRedirects);
2291 	prval("icmp6InGroupQueries",	icmp6->ipv6IfIcmpInGroupMembQueries);
2292 	prval("icmp6InGroupResps",	icmp6->ipv6IfIcmpInGroupMembResponses);
2293 	prval("icmp6InGroupReds",	icmp6->ipv6IfIcmpInGroupMembReductions);
2294 	prval("icmp6InOverflows",	icmp6->ipv6IfIcmpInOverflows);
2295 	prval_end();
2296 	prval_init();
2297 	prval("icmp6OutMsgs",		icmp6->ipv6IfIcmpOutMsgs);
2298 	prval("icmp6OutErrors",		icmp6->ipv6IfIcmpOutErrors);
2299 	prval("icmp6OutDestUnreachs",	icmp6->ipv6IfIcmpOutDestUnreachs);
2300 	prval("icmp6OutAdminProhibs",	icmp6->ipv6IfIcmpOutAdminProhibs);
2301 	prval("icmp6OutTimeExcds",	icmp6->ipv6IfIcmpOutTimeExcds);
2302 	prval("icmp6OutParmProblems",	icmp6->ipv6IfIcmpOutParmProblems);
2303 	prval("icmp6OutPktTooBigs",	icmp6->ipv6IfIcmpOutPktTooBigs);
2304 	prval("icmp6OutEchos",		icmp6->ipv6IfIcmpOutEchos);
2305 	prval("icmp6OutEchoReplies",	icmp6->ipv6IfIcmpOutEchoReplies);
2306 	prval("icmp6OutRouterSols",	icmp6->ipv6IfIcmpOutRouterSolicits);
2307 	prval("icmp6OutRouterAds",
2308 	    icmp6->ipv6IfIcmpOutRouterAdvertisements);
2309 	prval("icmp6OutNeighborSols",	icmp6->ipv6IfIcmpOutNeighborSolicits);
2310 	prval("icmp6OutNeighborAds",
2311 	    icmp6->ipv6IfIcmpOutNeighborAdvertisements);
2312 	prval("icmp6OutRedirects",	icmp6->ipv6IfIcmpOutRedirects);
2313 	prval("icmp6OutGroupQueries",	icmp6->ipv6IfIcmpOutGroupMembQueries);
2314 	prval("icmp6OutGroupResps",
2315 	    icmp6->ipv6IfIcmpOutGroupMembResponses);
2316 	prval("icmp6OutGroupReds",
2317 	    icmp6->ipv6IfIcmpOutGroupMembReductions);
2318 	prval_end();
2319 }
2320 
2321 static void
2322 print_sctp_stats(mib2_sctp_t *sctp)
2323 {
2324 	prval_init();
2325 	pr_sctp_rtoalgo("sctpRtoAlgorithm", sctp->sctpRtoAlgorithm);
2326 	prval("sctpRtoMin",		sctp->sctpRtoMin);
2327 	prval("sctpRtoMax",		sctp->sctpRtoMax);
2328 	prval("sctpRtoInitial",		sctp->sctpRtoInitial);
2329 	pr_int_val("sctpMaxAssocs",	sctp->sctpMaxAssocs);
2330 	prval("sctpValCookieLife",	sctp->sctpValCookieLife);
2331 	prval("sctpMaxInitRetr",	sctp->sctpMaxInitRetr);
2332 	prval("sctpCurrEstab",		sctp->sctpCurrEstab);
2333 	prval("sctpActiveEstab",	sctp->sctpActiveEstab);
2334 	prval("sctpPassiveEstab",	sctp->sctpPassiveEstab);
2335 	prval("sctpAborted",		sctp->sctpAborted);
2336 	prval("sctpShutdowns",		sctp->sctpShutdowns);
2337 	prval("sctpOutOfBlue",		sctp->sctpOutOfBlue);
2338 	prval("sctpChecksumError",	sctp->sctpChecksumError);
2339 	prval64("sctpOutCtrlChunks",	sctp->sctpOutCtrlChunks);
2340 	prval64("sctpOutOrderChunks",	sctp->sctpOutOrderChunks);
2341 	prval64("sctpOutUnorderChunks",	sctp->sctpOutUnorderChunks);
2342 	prval64("sctpRetransChunks",	sctp->sctpRetransChunks);
2343 	prval("sctpOutAck",		sctp->sctpOutAck);
2344 	prval("sctpOutAckDelayed",	sctp->sctpOutAckDelayed);
2345 	prval("sctpOutWinUpdate",	sctp->sctpOutWinUpdate);
2346 	prval("sctpOutFastRetrans",	sctp->sctpOutFastRetrans);
2347 	prval("sctpOutWinProbe",	sctp->sctpOutWinProbe);
2348 	prval64("sctpInCtrlChunks",	sctp->sctpInCtrlChunks);
2349 	prval64("sctpInOrderChunks",	sctp->sctpInOrderChunks);
2350 	prval64("sctpInUnorderChunks",	sctp->sctpInUnorderChunks);
2351 	prval("sctpInAck",		sctp->sctpInAck);
2352 	prval("sctpInDupAck",		sctp->sctpInDupAck);
2353 	prval("sctpInAckUnsent",	sctp->sctpInAckUnsent);
2354 	prval64("sctpFragUsrMsgs",	sctp->sctpFragUsrMsgs);
2355 	prval64("sctpReasmUsrMsgs",	sctp->sctpReasmUsrMsgs);
2356 	prval64("sctpOutSCTPPkts",	sctp->sctpOutSCTPPkts);
2357 	prval64("sctpInSCTPPkts",	sctp->sctpInSCTPPkts);
2358 	prval("sctpInInvalidCookie",	sctp->sctpInInvalidCookie);
2359 	prval("sctpTimRetrans",		sctp->sctpTimRetrans);
2360 	prval("sctpTimRetransDrop",	sctp->sctpTimRetransDrop);
2361 	prval("sctpTimHearBeatProbe",	sctp->sctpTimHeartBeatProbe);
2362 	prval("sctpTimHearBeatDrop",	sctp->sctpTimHeartBeatDrop);
2363 	prval("sctpListenDrop",		sctp->sctpListenDrop);
2364 	prval("sctpInClosed",		sctp->sctpInClosed);
2365 	prval_end();
2366 }
2367 
2368 static void
2369 print_tcp_stats(mib2_tcp_t *tcp)
2370 {
2371 	prval_init();
2372 	pr_int_val("tcpRtoAlgorithm",	tcp->tcpRtoAlgorithm);
2373 	pr_int_val("tcpRtoMin",		tcp->tcpRtoMin);
2374 	pr_int_val("tcpRtoMax",		tcp->tcpRtoMax);
2375 	pr_int_val("tcpMaxConn",	tcp->tcpMaxConn);
2376 	prval("tcpActiveOpens",		tcp->tcpActiveOpens);
2377 	prval("tcpPassiveOpens",	tcp->tcpPassiveOpens);
2378 	prval("tcpAttemptFails",	tcp->tcpAttemptFails);
2379 	prval("tcpEstabResets",		tcp->tcpEstabResets);
2380 	prval("tcpCurrEstab",		tcp->tcpCurrEstab);
2381 	prval64("tcpOutSegs",		tcp->tcpHCOutSegs);
2382 	prval("tcpOutDataSegs",		tcp->tcpOutDataSegs);
2383 	prval("tcpOutDataBytes",	tcp->tcpOutDataBytes);
2384 	prval("tcpRetransSegs",		tcp->tcpRetransSegs);
2385 	prval("tcpRetransBytes",	tcp->tcpRetransBytes);
2386 	prval("tcpOutAck",		tcp->tcpOutAck);
2387 	prval("tcpOutAckDelayed",	tcp->tcpOutAckDelayed);
2388 	prval("tcpOutUrg",		tcp->tcpOutUrg);
2389 	prval("tcpOutWinUpdate",	tcp->tcpOutWinUpdate);
2390 	prval("tcpOutWinProbe",		tcp->tcpOutWinProbe);
2391 	prval("tcpOutControl",		tcp->tcpOutControl);
2392 	prval("tcpOutRsts",		tcp->tcpOutRsts);
2393 	prval("tcpOutFastRetrans",	tcp->tcpOutFastRetrans);
2394 	prval64("tcpInSegs",		tcp->tcpHCInSegs);
2395 	prval_end();
2396 	prval("tcpInAckSegs",		tcp->tcpInAckSegs);
2397 	prval("tcpInAckBytes",		tcp->tcpInAckBytes);
2398 	prval("tcpInDupAck",		tcp->tcpInDupAck);
2399 	prval("tcpInAckUnsent",		tcp->tcpInAckUnsent);
2400 	prval("tcpInInorderSegs",	tcp->tcpInDataInorderSegs);
2401 	prval("tcpInInorderBytes",	tcp->tcpInDataInorderBytes);
2402 	prval("tcpInUnorderSegs",	tcp->tcpInDataUnorderSegs);
2403 	prval("tcpInUnorderBytes",	tcp->tcpInDataUnorderBytes);
2404 	prval("tcpInDupSegs",		tcp->tcpInDataDupSegs);
2405 	prval("tcpInDupBytes",		tcp->tcpInDataDupBytes);
2406 	prval("tcpInPartDupSegs",	tcp->tcpInDataPartDupSegs);
2407 	prval("tcpInPartDupBytes",	tcp->tcpInDataPartDupBytes);
2408 	prval("tcpInPastWinSegs",	tcp->tcpInDataPastWinSegs);
2409 	prval("tcpInPastWinBytes",	tcp->tcpInDataPastWinBytes);
2410 	prval("tcpInWinProbe",		tcp->tcpInWinProbe);
2411 	prval("tcpInWinUpdate",		tcp->tcpInWinUpdate);
2412 	prval("tcpInClosed",		tcp->tcpInClosed);
2413 	prval("tcpRttNoUpdate",		tcp->tcpRttNoUpdate);
2414 	prval("tcpRttUpdate",		tcp->tcpRttUpdate);
2415 	prval("tcpTimRetrans",		tcp->tcpTimRetrans);
2416 	prval("tcpTimRetransDrop",	tcp->tcpTimRetransDrop);
2417 	prval("tcpTimKeepalive",	tcp->tcpTimKeepalive);
2418 	prval("tcpTimKeepaliveProbe",	tcp->tcpTimKeepaliveProbe);
2419 	prval("tcpTimKeepaliveDrop",	tcp->tcpTimKeepaliveDrop);
2420 	prval("tcpListenDrop",		tcp->tcpListenDrop);
2421 	prval("tcpListenDropQ0",	tcp->tcpListenDropQ0);
2422 	prval("tcpHalfOpenDrop",	tcp->tcpHalfOpenDrop);
2423 	prval("tcpOutSackRetrans",	tcp->tcpOutSackRetransSegs);
2424 	prval_end();
2425 
2426 }
2427 
2428 static void
2429 print_udp_stats(mib2_udp_t *udp)
2430 {
2431 	prval_init();
2432 	prval64("udpInDatagrams",	udp->udpHCInDatagrams);
2433 	prval("udpInErrors",		udp->udpInErrors);
2434 	prval64("udpOutDatagrams",	udp->udpHCOutDatagrams);
2435 	prval("udpOutErrors",		udp->udpOutErrors);
2436 	prval_end();
2437 }
2438 
2439 static void
2440 print_rawip_stats(mib2_rawip_t *rawip)
2441 {
2442 	prval_init();
2443 	prval("rawipInDatagrams",	rawip->rawipInDatagrams);
2444 	prval("rawipInErrors",		rawip->rawipInErrors);
2445 	prval("rawipInCksumErrs",	rawip->rawipInCksumErrs);
2446 	prval("rawipOutDatagrams",	rawip->rawipOutDatagrams);
2447 	prval("rawipOutErrors",		rawip->rawipOutErrors);
2448 	prval_end();
2449 }
2450 
2451 void
2452 print_igmp_stats(struct igmpstat *igps)
2453 {
2454 	(void) printf(" %10u message%s received\n",
2455 	    igps->igps_rcv_total, PLURAL(igps->igps_rcv_total));
2456 	(void) printf(" %10u message%s received with too few bytes\n",
2457 	    igps->igps_rcv_tooshort, PLURAL(igps->igps_rcv_tooshort));
2458 	(void) printf(" %10u message%s received with bad checksum\n",
2459 	    igps->igps_rcv_badsum, PLURAL(igps->igps_rcv_badsum));
2460 	(void) printf(" %10u membership quer%s received\n",
2461 	    igps->igps_rcv_queries, PLURALY(igps->igps_rcv_queries));
2462 	(void) printf(" %10u membership quer%s received with invalid "
2463 	    "field(s)\n",
2464 	    igps->igps_rcv_badqueries, PLURALY(igps->igps_rcv_badqueries));
2465 	(void) printf(" %10u membership report%s received\n",
2466 	    igps->igps_rcv_reports, PLURAL(igps->igps_rcv_reports));
2467 	(void) printf(" %10u membership report%s received with invalid "
2468 	    "field(s)\n",
2469 	    igps->igps_rcv_badreports, PLURAL(igps->igps_rcv_badreports));
2470 	(void) printf(" %10u membership report%s received for groups to "
2471 	    "which we belong\n",
2472 	    igps->igps_rcv_ourreports, PLURAL(igps->igps_rcv_ourreports));
2473 	(void) printf(" %10u membership report%s sent\n",
2474 	    igps->igps_snd_reports, PLURAL(igps->igps_snd_reports));
2475 }
2476 
2477 static void
2478 print_mrt_stats(struct mrtstat *mrts)
2479 {
2480 	(void) puts("DVMRP multicast routing:");
2481 	(void) printf(" %10u hit%s - kernel forwarding cache hits\n",
2482 	    mrts->mrts_mfc_hits, PLURAL(mrts->mrts_mfc_hits));
2483 	(void) printf(" %10u miss%s - kernel forwarding cache misses\n",
2484 	    mrts->mrts_mfc_misses, PLURALES(mrts->mrts_mfc_misses));
2485 	(void) printf(" %10u packet%s potentially forwarded\n",
2486 	    mrts->mrts_fwd_in, PLURAL(mrts->mrts_fwd_in));
2487 	(void) printf(" %10u packet%s actually sent out\n",
2488 	    mrts->mrts_fwd_out, PLURAL(mrts->mrts_fwd_out));
2489 	(void) printf(" %10u upcall%s - upcalls made to mrouted\n",
2490 	    mrts->mrts_upcalls, PLURAL(mrts->mrts_upcalls));
2491 	(void) printf(" %10u packet%s not sent out due to lack of resources\n",
2492 	    mrts->mrts_fwd_drop, PLURAL(mrts->mrts_fwd_drop));
2493 	(void) printf(" %10u datagram%s with malformed tunnel options\n",
2494 	    mrts->mrts_bad_tunnel, PLURAL(mrts->mrts_bad_tunnel));
2495 	(void) printf(" %10u datagram%s with no room for tunnel options\n",
2496 	    mrts->mrts_cant_tunnel, PLURAL(mrts->mrts_cant_tunnel));
2497 	(void) printf(" %10u datagram%s arrived on wrong interface\n",
2498 	    mrts->mrts_wrong_if, PLURAL(mrts->mrts_wrong_if));
2499 	(void) printf(" %10u datagram%s dropped due to upcall Q overflow\n",
2500 	    mrts->mrts_upq_ovflw, PLURAL(mrts->mrts_upq_ovflw));
2501 	(void) printf(" %10u datagram%s cleaned up by the cache\n",
2502 	    mrts->mrts_cache_cleanups, PLURAL(mrts->mrts_cache_cleanups));
2503 	(void) printf(" %10u datagram%s dropped selectively by ratelimiter\n",
2504 	    mrts->mrts_drop_sel, PLURAL(mrts->mrts_drop_sel));
2505 	(void) printf(" %10u datagram%s dropped - bucket Q overflow\n",
2506 	    mrts->mrts_q_overflow, PLURAL(mrts->mrts_q_overflow));
2507 	(void) printf(" %10u datagram%s dropped - larger than bkt size\n",
2508 	    mrts->mrts_pkt2large, PLURAL(mrts->mrts_pkt2large));
2509 	(void) printf("\nPIM multicast routing:\n");
2510 	(void) printf(" %10u datagram%s dropped - bad version number\n",
2511 	    mrts->mrts_pim_badversion, PLURAL(mrts->mrts_pim_badversion));
2512 	(void) printf(" %10u datagram%s dropped - bad checksum\n",
2513 	    mrts->mrts_pim_rcv_badcsum, PLURAL(mrts->mrts_pim_rcv_badcsum));
2514 	(void) printf(" %10u datagram%s dropped - bad register packets\n",
2515 	    mrts->mrts_pim_badregisters, PLURAL(mrts->mrts_pim_badregisters));
2516 	(void) printf(
2517 	    " %10u datagram%s potentially forwarded - register packets\n",
2518 	    mrts->mrts_pim_regforwards, PLURAL(mrts->mrts_pim_regforwards));
2519 	(void) printf(" %10u datagram%s dropped - register send drops\n",
2520 	    mrts->mrts_pim_regsend_drops, PLURAL(mrts->mrts_pim_regsend_drops));
2521 	(void) printf(" %10u datagram%s dropped - packet malformed\n",
2522 	    mrts->mrts_pim_malformed, PLURAL(mrts->mrts_pim_malformed));
2523 	(void) printf(" %10u datagram%s dropped - no memory to forward\n",
2524 	    mrts->mrts_pim_nomemory, PLURAL(mrts->mrts_pim_nomemory));
2525 }
2526 
2527 static void
2528 sum_ip6_stats(mib2_ipv6IfStatsEntry_t *ip6, mib2_ipv6IfStatsEntry_t *sum6)
2529 {
2530 	/* First few are not additive */
2531 	sum6->ipv6Forwarding = ip6->ipv6Forwarding;
2532 	sum6->ipv6DefaultHopLimit = ip6->ipv6DefaultHopLimit;
2533 
2534 	sum6->ipv6InReceives += ip6->ipv6InReceives;
2535 	sum6->ipv6InHdrErrors += ip6->ipv6InHdrErrors;
2536 	sum6->ipv6InTooBigErrors += ip6->ipv6InTooBigErrors;
2537 	sum6->ipv6InNoRoutes += ip6->ipv6InNoRoutes;
2538 	sum6->ipv6InAddrErrors += ip6->ipv6InAddrErrors;
2539 	sum6->ipv6InUnknownProtos += ip6->ipv6InUnknownProtos;
2540 	sum6->ipv6InTruncatedPkts += ip6->ipv6InTruncatedPkts;
2541 	sum6->ipv6InDiscards += ip6->ipv6InDiscards;
2542 	sum6->ipv6InDelivers += ip6->ipv6InDelivers;
2543 	sum6->ipv6OutForwDatagrams += ip6->ipv6OutForwDatagrams;
2544 	sum6->ipv6OutRequests += ip6->ipv6OutRequests;
2545 	sum6->ipv6OutDiscards += ip6->ipv6OutDiscards;
2546 	sum6->ipv6OutFragOKs += ip6->ipv6OutFragOKs;
2547 	sum6->ipv6OutFragFails += ip6->ipv6OutFragFails;
2548 	sum6->ipv6OutFragCreates += ip6->ipv6OutFragCreates;
2549 	sum6->ipv6ReasmReqds += ip6->ipv6ReasmReqds;
2550 	sum6->ipv6ReasmOKs += ip6->ipv6ReasmOKs;
2551 	sum6->ipv6ReasmFails += ip6->ipv6ReasmFails;
2552 	sum6->ipv6InMcastPkts += ip6->ipv6InMcastPkts;
2553 	sum6->ipv6OutMcastPkts += ip6->ipv6OutMcastPkts;
2554 	sum6->ipv6OutNoRoutes += ip6->ipv6OutNoRoutes;
2555 	sum6->ipv6ReasmDuplicates += ip6->ipv6ReasmDuplicates;
2556 	sum6->ipv6ReasmPartDups += ip6->ipv6ReasmPartDups;
2557 	sum6->ipv6ForwProhibits += ip6->ipv6ForwProhibits;
2558 	sum6->udpInCksumErrs += ip6->udpInCksumErrs;
2559 	sum6->udpInOverflows += ip6->udpInOverflows;
2560 	sum6->rawipInOverflows += ip6->rawipInOverflows;
2561 }
2562 
2563 static void
2564 sum_icmp6_stats(mib2_ipv6IfIcmpEntry_t *icmp6, mib2_ipv6IfIcmpEntry_t *sum6)
2565 {
2566 	sum6->ipv6IfIcmpInMsgs += icmp6->ipv6IfIcmpInMsgs;
2567 	sum6->ipv6IfIcmpInErrors += icmp6->ipv6IfIcmpInErrors;
2568 	sum6->ipv6IfIcmpInDestUnreachs += icmp6->ipv6IfIcmpInDestUnreachs;
2569 	sum6->ipv6IfIcmpInAdminProhibs += icmp6->ipv6IfIcmpInAdminProhibs;
2570 	sum6->ipv6IfIcmpInTimeExcds += icmp6->ipv6IfIcmpInTimeExcds;
2571 	sum6->ipv6IfIcmpInParmProblems += icmp6->ipv6IfIcmpInParmProblems;
2572 	sum6->ipv6IfIcmpInPktTooBigs += icmp6->ipv6IfIcmpInPktTooBigs;
2573 	sum6->ipv6IfIcmpInEchos += icmp6->ipv6IfIcmpInEchos;
2574 	sum6->ipv6IfIcmpInEchoReplies += icmp6->ipv6IfIcmpInEchoReplies;
2575 	sum6->ipv6IfIcmpInRouterSolicits += icmp6->ipv6IfIcmpInRouterSolicits;
2576 	sum6->ipv6IfIcmpInRouterAdvertisements +=
2577 	    icmp6->ipv6IfIcmpInRouterAdvertisements;
2578 	sum6->ipv6IfIcmpInNeighborSolicits +=
2579 	    icmp6->ipv6IfIcmpInNeighborSolicits;
2580 	sum6->ipv6IfIcmpInNeighborAdvertisements +=
2581 	    icmp6->ipv6IfIcmpInNeighborAdvertisements;
2582 	sum6->ipv6IfIcmpInRedirects += icmp6->ipv6IfIcmpInRedirects;
2583 	sum6->ipv6IfIcmpInGroupMembQueries +=
2584 	    icmp6->ipv6IfIcmpInGroupMembQueries;
2585 	sum6->ipv6IfIcmpInGroupMembResponses +=
2586 	    icmp6->ipv6IfIcmpInGroupMembResponses;
2587 	sum6->ipv6IfIcmpInGroupMembReductions +=
2588 	    icmp6->ipv6IfIcmpInGroupMembReductions;
2589 	sum6->ipv6IfIcmpOutMsgs += icmp6->ipv6IfIcmpOutMsgs;
2590 	sum6->ipv6IfIcmpOutErrors += icmp6->ipv6IfIcmpOutErrors;
2591 	sum6->ipv6IfIcmpOutDestUnreachs += icmp6->ipv6IfIcmpOutDestUnreachs;
2592 	sum6->ipv6IfIcmpOutAdminProhibs += icmp6->ipv6IfIcmpOutAdminProhibs;
2593 	sum6->ipv6IfIcmpOutTimeExcds += icmp6->ipv6IfIcmpOutTimeExcds;
2594 	sum6->ipv6IfIcmpOutParmProblems += icmp6->ipv6IfIcmpOutParmProblems;
2595 	sum6->ipv6IfIcmpOutPktTooBigs += icmp6->ipv6IfIcmpOutPktTooBigs;
2596 	sum6->ipv6IfIcmpOutEchos += icmp6->ipv6IfIcmpOutEchos;
2597 	sum6->ipv6IfIcmpOutEchoReplies += icmp6->ipv6IfIcmpOutEchoReplies;
2598 	sum6->ipv6IfIcmpOutRouterSolicits +=
2599 	    icmp6->ipv6IfIcmpOutRouterSolicits;
2600 	sum6->ipv6IfIcmpOutRouterAdvertisements +=
2601 	    icmp6->ipv6IfIcmpOutRouterAdvertisements;
2602 	sum6->ipv6IfIcmpOutNeighborSolicits +=
2603 	    icmp6->ipv6IfIcmpOutNeighborSolicits;
2604 	sum6->ipv6IfIcmpOutNeighborAdvertisements +=
2605 	    icmp6->ipv6IfIcmpOutNeighborAdvertisements;
2606 	sum6->ipv6IfIcmpOutRedirects += icmp6->ipv6IfIcmpOutRedirects;
2607 	sum6->ipv6IfIcmpOutGroupMembQueries +=
2608 	    icmp6->ipv6IfIcmpOutGroupMembQueries;
2609 	sum6->ipv6IfIcmpOutGroupMembResponses +=
2610 	    icmp6->ipv6IfIcmpOutGroupMembResponses;
2611 	sum6->ipv6IfIcmpOutGroupMembReductions +=
2612 	    icmp6->ipv6IfIcmpOutGroupMembReductions;
2613 	sum6->ipv6IfIcmpInOverflows += icmp6->ipv6IfIcmpInOverflows;
2614 }
2615 
2616 /* ----------------------------- MRT_STAT_REPORT --------------------------- */
2617 
2618 static void
2619 mrt_stat_report(mib_item_t *curritem)
2620 {
2621 	int	jtemp = 0;
2622 	mib_item_t *tempitem;
2623 
2624 	if (!(family_selected(AF_INET)))
2625 		return;
2626 
2627 	(void) putchar('\n');
2628 	/* 'for' loop 1: */
2629 	for (tempitem = curritem;
2630 	    tempitem;
2631 	    tempitem = tempitem->next_item) {
2632 		if (Xflag) {
2633 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
2634 			(void) printf("Group = %d, mib_id = %d, "
2635 			    "length = %d, valp = 0x%p\n",
2636 			    tempitem->group, tempitem->mib_id,
2637 			    tempitem->length, tempitem->valp);
2638 		}
2639 
2640 		if (tempitem->mib_id == 0) {
2641 			switch (tempitem->group) {
2642 			case EXPER_DVMRP: {
2643 				struct mrtstat	*mrts;
2644 				mrts = (struct mrtstat *)tempitem->valp;
2645 
2646 				if (!(family_selected(AF_INET)))
2647 					continue; /* 'for' loop 1 */
2648 
2649 				print_mrt_stats(mrts);
2650 				break;
2651 			}
2652 			}
2653 		}
2654 	} /* 'for' loop 1 ends */
2655 	(void) putchar('\n');
2656 	(void) fflush(stdout);
2657 }
2658 
2659 /*
2660  * if_stat_total() - Computes totals for interface statistics
2661  *                   and returns result by updating sumstats.
2662  */
2663 static void
2664 if_stat_total(struct ifstat *oldstats, struct ifstat *newstats,
2665     struct ifstat *sumstats)
2666 {
2667 	sumstats->ipackets += newstats->ipackets - oldstats->ipackets;
2668 	sumstats->opackets += newstats->opackets - oldstats->opackets;
2669 	sumstats->ierrors += newstats->ierrors - oldstats->ierrors;
2670 	sumstats->oerrors += newstats->oerrors - oldstats->oerrors;
2671 	sumstats->collisions += newstats->collisions - oldstats->collisions;
2672 }
2673 
2674 /* --------------------- IF_REPORT (netstat -i)  -------------------------- */
2675 
2676 static struct	ifstat	zerostat = {
2677 	0LL, 0LL, 0LL, 0LL, 0LL
2678 };
2679 
2680 static void
2681 if_report(mib_item_t *item, char *matchname,
2682     int Iflag_only, boolean_t once_only)
2683 {
2684 	static boolean_t	reentry = B_FALSE;
2685 	boolean_t		alreadydone = B_FALSE;
2686 	int			jtemp = 0;
2687 	uint32_t		ifindex_v4 = 0;
2688 	uint32_t		ifindex_v6 = 0;
2689 	boolean_t		first_header = B_TRUE;
2690 
2691 	/* 'for' loop 1: */
2692 	for (; item; item = item->next_item) {
2693 		if (Xflag) {
2694 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
2695 			(void) printf("Group = %d, mib_id = %d, "
2696 			    "length = %d, valp = 0x%p\n",
2697 			    item->group, item->mib_id, item->length,
2698 			    item->valp);
2699 		}
2700 
2701 		switch (item->group) {
2702 		case MIB2_IP:
2703 		if (item->mib_id != MIB2_IP_ADDR ||
2704 		    !family_selected(AF_INET))
2705 			continue; /* 'for' loop 1 */
2706 		{
2707 			static struct ifstat	old = {0L, 0L, 0L, 0L, 0L};
2708 			static struct ifstat	new = {0L, 0L, 0L, 0L, 0L};
2709 			struct ifstat		sum;
2710 			struct iflist		*newlist = NULL;
2711 			static struct iflist	*oldlist = NULL;
2712 			kstat_t	 *ksp;
2713 
2714 			if (once_only) {
2715 				char    ifname[LIFNAMSIZ + 1];
2716 				char    logintname[LIFNAMSIZ + 1];
2717 				mib2_ipAddrEntry_t *ap;
2718 				struct ifstat	stat = {0L, 0L, 0L, 0L, 0L};
2719 				boolean_t	first = B_TRUE;
2720 				uint32_t	new_ifindex;
2721 
2722 				if (Xflag)
2723 					(void) printf("if_report: %d items\n",
2724 					    (item->length)
2725 					    / sizeof (mib2_ipAddrEntry_t));
2726 
2727 				/* 'for' loop 2a: */
2728 				for (ap = (mib2_ipAddrEntry_t *)item->valp;
2729 				    (char *)ap < (char *)item->valp
2730 				    + item->length;
2731 				    ap++) {
2732 					(void) octetstr(&ap->ipAdEntIfIndex,
2733 					    'a', logintname,
2734 					    sizeof (logintname));
2735 					(void) strcpy(ifname, logintname);
2736 					(void) strtok(ifname, ":");
2737 					if (matchname != NULL &&
2738 					    strcmp(matchname, ifname) != 0 &&
2739 					    strcmp(matchname, logintname) != 0)
2740 						continue; /* 'for' loop 2a */
2741 					new_ifindex =
2742 					    if_nametoindex(logintname);
2743 					/*
2744 					 * First lookup the "link" kstats in
2745 					 * case the link is renamed. Then
2746 					 * fallback to the legacy kstats for
2747 					 * those non-GLDv3 links.
2748 					 */
2749 					if (new_ifindex != ifindex_v4 &&
2750 					    (((ksp = kstat_lookup(kc, "link", 0,
2751 					    ifname)) != NULL) ||
2752 					    ((ksp = kstat_lookup(kc, NULL, -1,
2753 					    ifname)) != NULL))) {
2754 						(void) safe_kstat_read(kc, ksp,
2755 						    NULL);
2756 						stat.ipackets =
2757 						    kstat_named_value(ksp,
2758 						    "ipackets");
2759 						stat.ierrors =
2760 						    kstat_named_value(ksp,
2761 						    "ierrors");
2762 						stat.opackets =
2763 						    kstat_named_value(ksp,
2764 						    "opackets");
2765 						stat.oerrors =
2766 						    kstat_named_value(ksp,
2767 						    "oerrors");
2768 						stat.collisions =
2769 						    kstat_named_value(ksp,
2770 						    "collisions");
2771 						if (first) {
2772 							if (!first_header)
2773 							(void) putchar('\n');
2774 							first_header = B_FALSE;
2775 						(void) printf(
2776 						    "%-5.5s %-5.5s%-13.13s "
2777 						    "%-14.14s %-6.6s %-5.5s "
2778 						    "%-6.6s %-5.5s %-6.6s "
2779 						    "%-6.6s\n",
2780 						    "Name", "Mtu", "Net/Dest",
2781 						    "Address", "Ipkts",
2782 						    "Ierrs", "Opkts", "Oerrs",
2783 						    "Collis", "Queue");
2784 
2785 						first = B_FALSE;
2786 						}
2787 						if_report_ip4(ap, ifname,
2788 						    logintname, &stat, B_TRUE);
2789 						ifindex_v4 = new_ifindex;
2790 					} else {
2791 						if_report_ip4(ap, ifname,
2792 						    logintname, &stat, B_FALSE);
2793 					}
2794 				} /* 'for' loop 2a ends */
2795 			} else if (!alreadydone) {
2796 				char    ifname[LIFNAMSIZ + 1];
2797 				char    buf[LIFNAMSIZ + 1];
2798 				mib2_ipAddrEntry_t *ap;
2799 				struct ifstat   t;
2800 				struct iflist	*tlp = NULL;
2801 				struct iflist	**nextnew = &newlist;
2802 				struct iflist	*walkold;
2803 				struct iflist	*cleanlist;
2804 				boolean_t	found_if = B_FALSE;
2805 
2806 				alreadydone = B_TRUE; /* ignore other case */
2807 
2808 				/*
2809 				 * Check if there is anything to do.
2810 				 */
2811 				if (item->length <
2812 				    sizeof (mib2_ipAddrEntry_t)) {
2813 					fail(0, "No compatible interfaces");
2814 				}
2815 
2816 				/*
2817 				 * 'for' loop 2b: find the "right" entry:
2818 				 * If an interface name to match has been
2819 				 * supplied then try and find it, otherwise
2820 				 * match the first non-loopback interface found.
2821 				 * Use lo0 if all else fails.
2822 				 */
2823 				for (ap = (mib2_ipAddrEntry_t *)item->valp;
2824 				    (char *)ap < (char *)item->valp
2825 				    + item->length;
2826 				    ap++) {
2827 					(void) octetstr(&ap->ipAdEntIfIndex,
2828 					    'a', ifname, sizeof (ifname));
2829 					(void) strtok(ifname, ":");
2830 
2831 					if (matchname) {
2832 						if (strcmp(matchname,
2833 						    ifname) == 0) {
2834 							/* 'for' loop 2b */
2835 							found_if = B_TRUE;
2836 							break;
2837 						}
2838 					} else if (strcmp(ifname, "lo0") != 0)
2839 						break; /* 'for' loop 2b */
2840 				} /* 'for' loop 2b ends */
2841 
2842 				if (matchname == NULL) {
2843 					matchname = ifname;
2844 				} else {
2845 					if (!found_if)
2846 						fail(0, "-I: %s no such "
2847 						    "interface.", matchname);
2848 				}
2849 
2850 				if (Iflag_only == 0 || !reentry) {
2851 					(void) printf("    input   %-6.6s    "
2852 					    "output	",
2853 					    matchname);
2854 					(void) printf("   input  (Total)    "
2855 					"output\n");
2856 					(void) printf("%-7.7s %-5.5s %-7.7s "
2857 					    "%-5.5s %-6.6s ",
2858 					    "packets", "errs", "packets",
2859 					    "errs", "colls");
2860 					(void) printf("%-7.7s %-5.5s %-7.7s "
2861 					    "%-5.5s %-6.6s\n",
2862 					    "packets", "errs", "packets",
2863 					    "errs", "colls");
2864 				}
2865 
2866 				sum = zerostat;
2867 
2868 				/* 'for' loop 2c: */
2869 				for (ap = (mib2_ipAddrEntry_t *)item->valp;
2870 				    (char *)ap < (char *)item->valp
2871 				    + item->length;
2872 				    ap++) {
2873 					(void) octetstr(&ap->ipAdEntIfIndex,
2874 					    'a', buf, sizeof (buf));
2875 					(void) strtok(buf, ":");
2876 
2877 					/*
2878 					 * We have reduced the IP interface
2879 					 * name, which could have been a
2880 					 * logical, down to a name suitable
2881 					 * for use with kstats.
2882 					 * We treat this name as unique and
2883 					 * only collate statistics for it once
2884 					 * per pass. This is to avoid falsely
2885 					 * amplifying these statistics by the
2886 					 * the number of logical instances.
2887 					 */
2888 					if ((tlp != NULL) &&
2889 					    ((strcmp(buf, tlp->ifname) == 0))) {
2890 						continue;
2891 					}
2892 
2893 					/*
2894 					 * First lookup the "link" kstats in
2895 					 * case the link is renamed. Then
2896 					 * fallback to the legacy kstats for
2897 					 * those non-GLDv3 links.
2898 					 */
2899 					if (((ksp = kstat_lookup(kc, "link",
2900 					    0, buf)) != NULL ||
2901 					    (ksp = kstat_lookup(kc, NULL, -1,
2902 					    buf)) != NULL) && (ksp->ks_type ==
2903 					    KSTAT_TYPE_NAMED)) {
2904 						(void) safe_kstat_read(kc, ksp,
2905 						    NULL);
2906 					}
2907 
2908 					t.ipackets = kstat_named_value(ksp,
2909 					    "ipackets");
2910 					t.ierrors = kstat_named_value(ksp,
2911 					    "ierrors");
2912 					t.opackets = kstat_named_value(ksp,
2913 					    "opackets");
2914 					t.oerrors = kstat_named_value(ksp,
2915 					    "oerrors");
2916 					t.collisions = kstat_named_value(ksp,
2917 					    "collisions");
2918 
2919 					if (strcmp(buf, matchname) == 0)
2920 						new = t;
2921 
2922 					/* Build the interface list */
2923 
2924 					tlp = malloc(sizeof (struct iflist));
2925 					(void) strlcpy(tlp->ifname, buf,
2926 					    sizeof (tlp->ifname));
2927 					tlp->tot = t;
2928 					*nextnew = tlp;
2929 					nextnew = &tlp->next_if;
2930 
2931 					/*
2932 					 * First time through.
2933 					 * Just add up the interface stats.
2934 					 */
2935 
2936 					if (oldlist == NULL) {
2937 						if_stat_total(&zerostat,
2938 						    &t, &sum);
2939 						continue;
2940 					}
2941 
2942 					/*
2943 					 * Walk old list for the interface.
2944 					 *
2945 					 * If found, add difference to total.
2946 					 *
2947 					 * If not, an interface has been plumbed
2948 					 * up.  In this case, we will simply
2949 					 * ignore the new interface until the
2950 					 * next interval; as there's no easy way
2951 					 * to acquire statistics between time
2952 					 * of the plumb and the next interval
2953 					 * boundary.  This results in inaccurate
2954 					 * total values for current interval.
2955 					 *
2956 					 * Note the case when an interface is
2957 					 * unplumbed; as similar problems exist.
2958 					 * The unplumbed interface is not in the
2959 					 * current list, and there's no easy way
2960 					 * to account for the statistics between
2961 					 * the previous interval and time of the
2962 					 * unplumb.  Therefore, we (in a sense)
2963 					 * ignore the removed interface by only
2964 					 * involving "current" interfaces when
2965 					 * computing the total statistics.
2966 					 * Unfortunately, this also results in
2967 					 * inaccurate values for interval total.
2968 					 */
2969 
2970 					for (walkold = oldlist;
2971 					    walkold != NULL;
2972 					    walkold = walkold->next_if) {
2973 						if (strcmp(walkold->ifname,
2974 						    buf) == 0) {
2975 							if_stat_total(
2976 							    &walkold->tot,
2977 							    &t, &sum);
2978 							break;
2979 						}
2980 					}
2981 
2982 				} /* 'for' loop 2c ends */
2983 
2984 				*nextnew = NULL;
2985 
2986 				(void) printf("%-7llu %-5llu %-7llu "
2987 				    "%-5llu %-6llu ",
2988 				    new.ipackets - old.ipackets,
2989 				    new.ierrors - old.ierrors,
2990 				    new.opackets - old.opackets,
2991 				    new.oerrors - old.oerrors,
2992 				    new.collisions - old.collisions);
2993 
2994 				(void) printf("%-7llu %-5llu %-7llu "
2995 				    "%-5llu %-6llu\n", sum.ipackets,
2996 				    sum.ierrors, sum.opackets,
2997 				    sum.oerrors, sum.collisions);
2998 
2999 				/*
3000 				 * Tidy things up once finished.
3001 				 */
3002 
3003 				old = new;
3004 				cleanlist = oldlist;
3005 				oldlist = newlist;
3006 				while (cleanlist != NULL) {
3007 					tlp = cleanlist->next_if;
3008 					free(cleanlist);
3009 					cleanlist = tlp;
3010 				}
3011 			}
3012 			break;
3013 		}
3014 		case MIB2_IP6:
3015 		if (item->mib_id != MIB2_IP6_ADDR ||
3016 		    !family_selected(AF_INET6))
3017 			continue; /* 'for' loop 1 */
3018 		{
3019 			static struct ifstat	old6 = {0L, 0L, 0L, 0L, 0L};
3020 			static struct ifstat	new6 = {0L, 0L, 0L, 0L, 0L};
3021 			struct ifstat		sum6;
3022 			struct iflist		*newlist6 = NULL;
3023 			static struct iflist	*oldlist6 = NULL;
3024 			kstat_t	 *ksp;
3025 
3026 			if (once_only) {
3027 				char    ifname[LIFNAMSIZ + 1];
3028 				char    logintname[LIFNAMSIZ + 1];
3029 				mib2_ipv6AddrEntry_t *ap6;
3030 				struct ifstat	stat = {0L, 0L, 0L, 0L, 0L};
3031 				boolean_t	first = B_TRUE;
3032 				uint32_t	new_ifindex;
3033 
3034 				if (Xflag)
3035 					(void) printf("if_report: %d items\n",
3036 					    (item->length)
3037 					    / sizeof (mib2_ipv6AddrEntry_t));
3038 				/* 'for' loop 2d: */
3039 				for (ap6 = (mib2_ipv6AddrEntry_t *)item->valp;
3040 				    (char *)ap6 < (char *)item->valp
3041 				    + item->length;
3042 				    ap6++) {
3043 					(void) octetstr(&ap6->ipv6AddrIfIndex,
3044 					    'a', logintname,
3045 					    sizeof (logintname));
3046 					(void) strcpy(ifname, logintname);
3047 					(void) strtok(ifname, ":");
3048 					if (matchname != NULL &&
3049 					    strcmp(matchname, ifname) != 0 &&
3050 					    strcmp(matchname, logintname) != 0)
3051 						continue; /* 'for' loop 2d */
3052 					new_ifindex =
3053 					    if_nametoindex(logintname);
3054 
3055 					/*
3056 					 * First lookup the "link" kstats in
3057 					 * case the link is renamed. Then
3058 					 * fallback to the legacy kstats for
3059 					 * those non-GLDv3 links.
3060 					 */
3061 					if (new_ifindex != ifindex_v6 &&
3062 					    ((ksp = kstat_lookup(kc, "link", 0,
3063 					    ifname)) != NULL ||
3064 					    (ksp = kstat_lookup(kc, NULL, -1,
3065 					    ifname)) != NULL)) {
3066 						(void) safe_kstat_read(kc, ksp,
3067 						    NULL);
3068 						stat.ipackets =
3069 						    kstat_named_value(ksp,
3070 						    "ipackets");
3071 						stat.ierrors =
3072 						    kstat_named_value(ksp,
3073 						    "ierrors");
3074 						stat.opackets =
3075 						    kstat_named_value(ksp,
3076 						    "opackets");
3077 						stat.oerrors =
3078 						    kstat_named_value(ksp,
3079 						    "oerrors");
3080 						stat.collisions =
3081 						    kstat_named_value(ksp,
3082 						    "collisions");
3083 						if (first) {
3084 							if (!first_header)
3085 							(void) putchar('\n');
3086 							first_header = B_FALSE;
3087 							(void) printf(
3088 							    "%-5.5s %-5.5s%"
3089 							    "-27.27s %-27.27s "
3090 							    "%-6.6s %-5.5s "
3091 							    "%-6.6s %-5.5s "
3092 							    "%-6.6s\n",
3093 							    "Name", "Mtu",
3094 							    "Net/Dest",
3095 							    "Address", "Ipkts",
3096 							    "Ierrs", "Opkts",
3097 							    "Oerrs", "Collis");
3098 							first = B_FALSE;
3099 						}
3100 						if_report_ip6(ap6, ifname,
3101 						    logintname, &stat, B_TRUE);
3102 						ifindex_v6 = new_ifindex;
3103 					} else {
3104 						if_report_ip6(ap6, ifname,
3105 						    logintname, &stat, B_FALSE);
3106 					}
3107 				} /* 'for' loop 2d ends */
3108 			} else if (!alreadydone) {
3109 				char    ifname[LIFNAMSIZ + 1];
3110 				char    buf[IFNAMSIZ + 1];
3111 				mib2_ipv6AddrEntry_t *ap6;
3112 				struct ifstat   t;
3113 				struct iflist	*tlp = NULL;
3114 				struct iflist	**nextnew = &newlist6;
3115 				struct iflist	*walkold;
3116 				struct iflist	*cleanlist;
3117 				boolean_t	found_if = B_FALSE;
3118 
3119 				alreadydone = B_TRUE; /* ignore other case */
3120 
3121 				/*
3122 				 * Check if there is anything to do.
3123 				 */
3124 				if (item->length <
3125 				    sizeof (mib2_ipv6AddrEntry_t)) {
3126 					fail(0, "No compatible interfaces");
3127 				}
3128 
3129 				/*
3130 				 * 'for' loop 2e: find the "right" entry:
3131 				 * If an interface name to match has been
3132 				 * supplied then try and find it, otherwise
3133 				 * match the first non-loopback interface found.
3134 				 * Use lo0 if all else fails.
3135 				 */
3136 				for (ap6 = (mib2_ipv6AddrEntry_t *)item->valp;
3137 				    (char *)ap6 < (char *)item->valp
3138 				    + item->length;
3139 				    ap6++) {
3140 					(void) octetstr(&ap6->ipv6AddrIfIndex,
3141 					    'a', ifname, sizeof (ifname));
3142 					(void) strtok(ifname, ":");
3143 
3144 					if (matchname) {
3145 						if (strcmp(matchname,
3146 						    ifname) == 0) {
3147 							/* 'for' loop 2e */
3148 							found_if = B_TRUE;
3149 							break;
3150 						}
3151 					} else if (strcmp(ifname, "lo0") != 0)
3152 						break; /* 'for' loop 2e */
3153 				} /* 'for' loop 2e ends */
3154 
3155 				if (matchname == NULL) {
3156 					matchname = ifname;
3157 				} else {
3158 					if (!found_if)
3159 						fail(0, "-I: %s no such "
3160 						    "interface.", matchname);
3161 				}
3162 
3163 				if (Iflag_only == 0 || !reentry) {
3164 					(void) printf(
3165 					    "    input   %-6.6s"
3166 					    "    output	",
3167 					    matchname);
3168 					(void) printf("   input  (Total)"
3169 					    "    output\n");
3170 					(void) printf("%-7.7s %-5.5s %-7.7s "
3171 					    "%-5.5s %-6.6s ",
3172 					    "packets", "errs", "packets",
3173 					    "errs", "colls");
3174 					(void) printf("%-7.7s %-5.5s %-7.7s "
3175 					    "%-5.5s %-6.6s\n",
3176 					    "packets", "errs", "packets",
3177 					    "errs", "colls");
3178 				}
3179 
3180 				sum6 = zerostat;
3181 
3182 				/* 'for' loop 2f: */
3183 				for (ap6 = (mib2_ipv6AddrEntry_t *)item->valp;
3184 				    (char *)ap6 < (char *)item->valp
3185 				    + item->length;
3186 				    ap6++) {
3187 					(void) octetstr(&ap6->ipv6AddrIfIndex,
3188 					    'a', buf, sizeof (buf));
3189 					(void) strtok(buf, ":");
3190 
3191 					/*
3192 					 * We have reduced the IP interface
3193 					 * name, which could have been a
3194 					 * logical, down to a name suitable
3195 					 * for use with kstats.
3196 					 * We treat this name as unique and
3197 					 * only collate statistics for it once
3198 					 * per pass. This is to avoid falsely
3199 					 * amplifying these statistics by the
3200 					 * the number of logical instances.
3201 					 */
3202 
3203 					if ((tlp != NULL) &&
3204 					    ((strcmp(buf, tlp->ifname) == 0))) {
3205 						continue;
3206 					}
3207 
3208 					/*
3209 					 * First lookup the "link" kstats in
3210 					 * case the link is renamed. Then
3211 					 * fallback to the legacy kstats for
3212 					 * those non-GLDv3 links.
3213 					 */
3214 					if (((ksp = kstat_lookup(kc, "link",
3215 					    0, buf)) != NULL ||
3216 					    (ksp = kstat_lookup(kc, NULL, -1,
3217 					    buf)) != NULL) && (ksp->ks_type ==
3218 					    KSTAT_TYPE_NAMED)) {
3219 						(void) safe_kstat_read(kc,
3220 						    ksp, NULL);
3221 					}
3222 
3223 					t.ipackets = kstat_named_value(ksp,
3224 					    "ipackets");
3225 					t.ierrors = kstat_named_value(ksp,
3226 					    "ierrors");
3227 					t.opackets = kstat_named_value(ksp,
3228 					    "opackets");
3229 					t.oerrors = kstat_named_value(ksp,
3230 					    "oerrors");
3231 					t.collisions = kstat_named_value(ksp,
3232 					    "collisions");
3233 
3234 					if (strcmp(buf, matchname) == 0)
3235 						new6 = t;
3236 
3237 					/* Build the interface list */
3238 
3239 					tlp = malloc(sizeof (struct iflist));
3240 					(void) strlcpy(tlp->ifname, buf,
3241 					    sizeof (tlp->ifname));
3242 					tlp->tot = t;
3243 					*nextnew = tlp;
3244 					nextnew = &tlp->next_if;
3245 
3246 					/*
3247 					 * First time through.
3248 					 * Just add up the interface stats.
3249 					 */
3250 
3251 					if (oldlist6 == NULL) {
3252 						if_stat_total(&zerostat,
3253 						    &t, &sum6);
3254 						continue;
3255 					}
3256 
3257 					/*
3258 					 * Walk old list for the interface.
3259 					 *
3260 					 * If found, add difference to total.
3261 					 *
3262 					 * If not, an interface has been plumbed
3263 					 * up.  In this case, we will simply
3264 					 * ignore the new interface until the
3265 					 * next interval; as there's no easy way
3266 					 * to acquire statistics between time
3267 					 * of the plumb and the next interval
3268 					 * boundary.  This results in inaccurate
3269 					 * total values for current interval.
3270 					 *
3271 					 * Note the case when an interface is
3272 					 * unplumbed; as similar problems exist.
3273 					 * The unplumbed interface is not in the
3274 					 * current list, and there's no easy way
3275 					 * to account for the statistics between
3276 					 * the previous interval and time of the
3277 					 * unplumb.  Therefore, we (in a sense)
3278 					 * ignore the removed interface by only
3279 					 * involving "current" interfaces when
3280 					 * computing the total statistics.
3281 					 * Unfortunately, this also results in
3282 					 * inaccurate values for interval total.
3283 					 */
3284 
3285 					for (walkold = oldlist6;
3286 					    walkold != NULL;
3287 					    walkold = walkold->next_if) {
3288 						if (strcmp(walkold->ifname,
3289 						    buf) == 0) {
3290 							if_stat_total(
3291 							    &walkold->tot,
3292 							    &t, &sum6);
3293 							break;
3294 						}
3295 					}
3296 
3297 				} /* 'for' loop 2f ends */
3298 
3299 				*nextnew = NULL;
3300 
3301 				(void) printf("%-7llu %-5llu %-7llu "
3302 				    "%-5llu %-6llu ",
3303 				    new6.ipackets - old6.ipackets,
3304 				    new6.ierrors - old6.ierrors,
3305 				    new6.opackets - old6.opackets,
3306 				    new6.oerrors - old6.oerrors,
3307 				    new6.collisions - old6.collisions);
3308 
3309 				(void) printf("%-7llu %-5llu %-7llu "
3310 				    "%-5llu %-6llu\n", sum6.ipackets,
3311 				    sum6.ierrors, sum6.opackets,
3312 				    sum6.oerrors, sum6.collisions);
3313 
3314 				/*
3315 				 * Tidy things up once finished.
3316 				 */
3317 
3318 				old6 = new6;
3319 				cleanlist = oldlist6;
3320 				oldlist6 = newlist6;
3321 				while (cleanlist != NULL) {
3322 					tlp = cleanlist->next_if;
3323 					free(cleanlist);
3324 					cleanlist = tlp;
3325 				}
3326 			}
3327 			break;
3328 		}
3329 		}
3330 		(void) fflush(stdout);
3331 	} /* 'for' loop 1 ends */
3332 	if ((Iflag_only == 0) && (!once_only))
3333 		(void) putchar('\n');
3334 	reentry = B_TRUE;
3335 }
3336 
3337 static void
3338 if_report_ip4(mib2_ipAddrEntry_t *ap,
3339     char ifname[], char logintname[], struct ifstat *statptr,
3340     boolean_t ksp_not_null)
3341 {
3342 
3343 	char abuf[MAXHOSTNAMELEN + 1];
3344 	char dstbuf[MAXHOSTNAMELEN + 1];
3345 
3346 	if (ksp_not_null) {
3347 		(void) printf("%-5s %-4u ",
3348 		    ifname, ap->ipAdEntInfo.ae_mtu);
3349 		if (ap->ipAdEntInfo.ae_flags & IFF_POINTOPOINT)
3350 			(void) pr_addr(ap->ipAdEntInfo.ae_pp_dst_addr,
3351 			    abuf, sizeof (abuf));
3352 		else
3353 			(void) pr_netaddr(ap->ipAdEntAddr,
3354 			    ap->ipAdEntNetMask, abuf, sizeof (abuf));
3355 		(void) printf("%-13s %-14s %-6llu %-5llu %-6llu %-5llu "
3356 		    "%-6llu %-6llu\n",
3357 		    abuf, pr_addr(ap->ipAdEntAddr, dstbuf, sizeof (dstbuf)),
3358 		    statptr->ipackets, statptr->ierrors,
3359 		    statptr->opackets, statptr->oerrors,
3360 		    statptr->collisions, 0LL);
3361 	}
3362 	/*
3363 	 * Print logical interface info if Aflag set (including logical unit 0)
3364 	 */
3365 	if (Aflag) {
3366 		*statptr = zerostat;
3367 		statptr->ipackets = ap->ipAdEntInfo.ae_ibcnt;
3368 		statptr->opackets = ap->ipAdEntInfo.ae_obcnt;
3369 
3370 		(void) printf("%-5s %-4u ", logintname, ap->ipAdEntInfo.ae_mtu);
3371 		if (ap->ipAdEntInfo.ae_flags & IFF_POINTOPOINT)
3372 			(void) pr_addr(ap->ipAdEntInfo.ae_pp_dst_addr, abuf,
3373 			    sizeof (abuf));
3374 		else
3375 			(void) pr_netaddr(ap->ipAdEntAddr, ap->ipAdEntNetMask,
3376 			    abuf, sizeof (abuf));
3377 
3378 		(void) printf("%-13s %-14s %-6llu %-5s %-6s "
3379 		    "%-5s %-6s %-6llu\n", abuf,
3380 		    pr_addr(ap->ipAdEntAddr, dstbuf, sizeof (dstbuf)),
3381 		    statptr->ipackets, "N/A", "N/A", "N/A", "N/A",
3382 		    0LL);
3383 	}
3384 }
3385 
3386 static void
3387 if_report_ip6(mib2_ipv6AddrEntry_t *ap6,
3388     char ifname[], char logintname[], struct ifstat *statptr,
3389     boolean_t ksp_not_null)
3390 {
3391 
3392 	char abuf[MAXHOSTNAMELEN + 1];
3393 	char dstbuf[MAXHOSTNAMELEN + 1];
3394 
3395 	if (ksp_not_null) {
3396 		(void) printf("%-5s %-4u ", ifname, ap6->ipv6AddrInfo.ae_mtu);
3397 		if (ap6->ipv6AddrInfo.ae_flags &
3398 		    IFF_POINTOPOINT) {
3399 			(void) pr_addr6(&ap6->ipv6AddrInfo.ae_pp_dst_addr,
3400 			    abuf, sizeof (abuf));
3401 		} else {
3402 			(void) pr_prefix6(&ap6->ipv6AddrAddress,
3403 			    ap6->ipv6AddrPfxLength, abuf,
3404 			    sizeof (abuf));
3405 		}
3406 		(void) printf("%-27s %-27s %-6llu %-5llu "
3407 		    "%-6llu %-5llu %-6llu\n",
3408 		    abuf, pr_addr6(&ap6->ipv6AddrAddress, dstbuf,
3409 		    sizeof (dstbuf)),
3410 		    statptr->ipackets, statptr->ierrors, statptr->opackets,
3411 		    statptr->oerrors, statptr->collisions);
3412 	}
3413 	/*
3414 	 * Print logical interface info if Aflag set (including logical unit 0)
3415 	 */
3416 	if (Aflag) {
3417 		*statptr = zerostat;
3418 		statptr->ipackets = ap6->ipv6AddrInfo.ae_ibcnt;
3419 		statptr->opackets = ap6->ipv6AddrInfo.ae_obcnt;
3420 
3421 		(void) printf("%-5s %-4u ", logintname,
3422 		    ap6->ipv6AddrInfo.ae_mtu);
3423 		if (ap6->ipv6AddrInfo.ae_flags & IFF_POINTOPOINT)
3424 			(void) pr_addr6(&ap6->ipv6AddrInfo.ae_pp_dst_addr,
3425 			    abuf, sizeof (abuf));
3426 		else
3427 			(void) pr_prefix6(&ap6->ipv6AddrAddress,
3428 			    ap6->ipv6AddrPfxLength, abuf, sizeof (abuf));
3429 		(void) printf("%-27s %-27s %-6llu %-5s %-6s %-5s %-6s\n",
3430 		    abuf, pr_addr6(&ap6->ipv6AddrAddress, dstbuf,
3431 		    sizeof (dstbuf)),
3432 		    statptr->ipackets, "N/A", "N/A", "N/A", "N/A");
3433 	}
3434 }
3435 
3436 /* --------------------- DHCP_REPORT  (netstat -D) ------------------------- */
3437 
3438 static boolean_t
3439 dhcp_do_ipc(dhcp_ipc_type_t type, const char *ifname, boolean_t printed_one)
3440 {
3441 	dhcp_ipc_request_t	*request;
3442 	dhcp_ipc_reply_t	*reply;
3443 	int			error;
3444 
3445 	request = dhcp_ipc_alloc_request(type, ifname, NULL, 0, DHCP_TYPE_NONE);
3446 	if (request == NULL)
3447 		fail(0, "dhcp_do_ipc: out of memory");
3448 
3449 	error = dhcp_ipc_make_request(request, &reply, DHCP_IPC_WAIT_DEFAULT);
3450 	if (error != 0) {
3451 		free(request);
3452 		fail(0, "dhcp_do_ipc: %s", dhcp_ipc_strerror(error));
3453 	}
3454 
3455 	free(request);
3456 	error = reply->return_code;
3457 	if (error == DHCP_IPC_E_UNKIF) {
3458 		free(reply);
3459 		return (printed_one);
3460 	}
3461 	if (error != 0) {
3462 		free(reply);
3463 		fail(0, "dhcp_do_ipc: %s", dhcp_ipc_strerror(error));
3464 	}
3465 
3466 	if (timestamp_fmt != NODATE)
3467 		print_timestamp(timestamp_fmt);
3468 
3469 	if (!printed_one)
3470 		(void) printf("%s", dhcp_status_hdr_string());
3471 
3472 	(void) printf("%s", dhcp_status_reply_to_string(reply));
3473 	free(reply);
3474 	return (B_TRUE);
3475 }
3476 
3477 /*
3478  * dhcp_walk_interfaces: walk the list of interfaces for a given address
3479  * family (af).  For each, print out the DHCP status using dhcp_do_ipc.
3480  */
3481 static boolean_t
3482 dhcp_walk_interfaces(int af, boolean_t printed_one)
3483 {
3484 	struct lifnum	lifn;
3485 	struct lifconf	lifc;
3486 	int		n_ifs, i, sock_fd;
3487 
3488 	sock_fd = socket(af, SOCK_DGRAM, 0);
3489 	if (sock_fd == -1)
3490 		return (printed_one);
3491 
3492 	/*
3493 	 * SIOCGLIFNUM is just an estimate.  If the ioctl fails, we don't care;
3494 	 * just drive on and use SIOCGLIFCONF with increasing buffer sizes, as
3495 	 * is traditional.
3496 	 */
3497 	(void) memset(&lifn, 0, sizeof (lifn));
3498 	lifn.lifn_family = af;
3499 	lifn.lifn_flags = LIFC_ALLZONES | LIFC_NOXMIT | LIFC_UNDER_IPMP;
3500 	if (ioctl(sock_fd, SIOCGLIFNUM, &lifn) == -1)
3501 		n_ifs = LIFN_GUARD_VALUE;
3502 	else
3503 		n_ifs = lifn.lifn_count + LIFN_GUARD_VALUE;
3504 
3505 	(void) memset(&lifc, 0, sizeof (lifc));
3506 	lifc.lifc_family = af;
3507 	lifc.lifc_flags = lifn.lifn_flags;
3508 	lifc.lifc_len = n_ifs * sizeof (struct lifreq);
3509 	lifc.lifc_buf = malloc(lifc.lifc_len);
3510 	if (lifc.lifc_buf != NULL) {
3511 
3512 		if (ioctl(sock_fd, SIOCGLIFCONF, &lifc) == -1) {
3513 			(void) close(sock_fd);
3514 			free(lifc.lifc_buf);
3515 			return (NULL);
3516 		}
3517 
3518 		n_ifs = lifc.lifc_len / sizeof (struct lifreq);
3519 
3520 		for (i = 0; i < n_ifs; i++) {
3521 			printed_one = dhcp_do_ipc(DHCP_STATUS |
3522 			    (af == AF_INET6 ? DHCP_V6 : 0),
3523 			    lifc.lifc_req[i].lifr_name, printed_one);
3524 		}
3525 	}
3526 	(void) close(sock_fd);
3527 	free(lifc.lifc_buf);
3528 	return (printed_one);
3529 }
3530 
3531 static void
3532 dhcp_report(char *ifname)
3533 {
3534 	boolean_t printed_one;
3535 
3536 	if (!family_selected(AF_INET) && !family_selected(AF_INET6))
3537 		return;
3538 
3539 	printed_one = B_FALSE;
3540 	if (ifname != NULL) {
3541 		if (family_selected(AF_INET)) {
3542 			printed_one = dhcp_do_ipc(DHCP_STATUS, ifname,
3543 			    printed_one);
3544 		}
3545 		if (family_selected(AF_INET6)) {
3546 			printed_one = dhcp_do_ipc(DHCP_STATUS | DHCP_V6,
3547 			    ifname, printed_one);
3548 		}
3549 		if (!printed_one) {
3550 			fail(0, "%s: %s", ifname,
3551 			    dhcp_ipc_strerror(DHCP_IPC_E_UNKIF));
3552 		}
3553 	} else {
3554 		if (family_selected(AF_INET)) {
3555 			printed_one = dhcp_walk_interfaces(AF_INET,
3556 			    printed_one);
3557 		}
3558 		if (family_selected(AF_INET6))
3559 			(void) dhcp_walk_interfaces(AF_INET6, printed_one);
3560 	}
3561 }
3562 
3563 /* --------------------- GROUP_REPORT (netstat -g) ------------------------- */
3564 
3565 static void
3566 group_report(mib_item_t *item)
3567 {
3568 	mib_item_t	*v4grp = NULL, *v4src = NULL;
3569 	mib_item_t	*v6grp = NULL, *v6src = NULL;
3570 	int		jtemp = 0;
3571 	char		ifname[LIFNAMSIZ + 1];
3572 	char		abuf[MAXHOSTNAMELEN + 1];
3573 	ip_member_t	*ipmp;
3574 	ip_grpsrc_t	*ips;
3575 	ipv6_member_t	*ipmp6;
3576 	ipv6_grpsrc_t	*ips6;
3577 	boolean_t	first, first_src;
3578 
3579 	/* 'for' loop 1: */
3580 	for (; item; item = item->next_item) {
3581 		if (Xflag) {
3582 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
3583 			(void) printf("Group = %d, mib_id = %d, "
3584 			    "length = %d, valp = 0x%p\n",
3585 			    item->group, item->mib_id, item->length,
3586 			    item->valp);
3587 		}
3588 		if (item->group == MIB2_IP && family_selected(AF_INET)) {
3589 			switch (item->mib_id) {
3590 			case EXPER_IP_GROUP_MEMBERSHIP:
3591 				v4grp = item;
3592 				if (Xflag)
3593 					(void) printf("item is v4grp info\n");
3594 				break;
3595 			case EXPER_IP_GROUP_SOURCES:
3596 				v4src = item;
3597 				if (Xflag)
3598 					(void) printf("item is v4src info\n");
3599 				break;
3600 			default:
3601 				continue;
3602 			}
3603 			continue;
3604 		}
3605 		if (item->group == MIB2_IP6 && family_selected(AF_INET6)) {
3606 			switch (item->mib_id) {
3607 			case EXPER_IP6_GROUP_MEMBERSHIP:
3608 				v6grp = item;
3609 				if (Xflag)
3610 					(void) printf("item is v6grp info\n");
3611 				break;
3612 			case EXPER_IP6_GROUP_SOURCES:
3613 				v6src = item;
3614 				if (Xflag)
3615 					(void) printf("item is v6src info\n");
3616 				break;
3617 			default:
3618 				continue;
3619 			}
3620 		}
3621 	}
3622 
3623 	if (family_selected(AF_INET) && v4grp != NULL) {
3624 		if (Xflag)
3625 			(void) printf("%u records for ipGroupMember:\n",
3626 			    v4grp->length / sizeof (ip_member_t));
3627 
3628 		first = B_TRUE;
3629 		for (ipmp = (ip_member_t *)v4grp->valp;
3630 		    (char *)ipmp < (char *)v4grp->valp + v4grp->length;
3631 		    /* LINTED: (note 1) */
3632 		    ipmp = (ip_member_t *)((char *)ipmp + ipMemberEntrySize)) {
3633 			if (first) {
3634 				(void) puts(v4compat ?
3635 				    "Group Memberships" :
3636 				    "Group Memberships: IPv4");
3637 				(void) puts("Interface "
3638 				    "Group                RefCnt");
3639 				(void) puts("--------- "
3640 				    "-------------------- ------");
3641 				first = B_FALSE;
3642 			}
3643 
3644 			(void) printf("%-9s %-20s %6u\n",
3645 			    octetstr(&ipmp->ipGroupMemberIfIndex, 'a',
3646 			    ifname, sizeof (ifname)),
3647 			    pr_addr(ipmp->ipGroupMemberAddress,
3648 			    abuf, sizeof (abuf)),
3649 			    ipmp->ipGroupMemberRefCnt);
3650 
3651 
3652 			if (!Vflag || v4src == NULL)
3653 				continue;
3654 
3655 			if (Xflag)
3656 				(void) printf("scanning %u ipGroupSource "
3657 				    "records...\n",
3658 				    v4src->length/sizeof (ip_grpsrc_t));
3659 
3660 			first_src = B_TRUE;
3661 			for (ips = (ip_grpsrc_t *)v4src->valp;
3662 			    (char *)ips < (char *)v4src->valp + v4src->length;
3663 			    /* LINTED: (note 1) */
3664 			    ips = (ip_grpsrc_t *)((char *)ips +
3665 			    ipGroupSourceEntrySize)) {
3666 				/*
3667 				 * We assume that all source addrs for a given
3668 				 * interface/group pair are contiguous, so on
3669 				 * the first non-match after we've found at
3670 				 * least one, we bail.
3671 				 */
3672 				if ((ipmp->ipGroupMemberAddress !=
3673 				    ips->ipGroupSourceGroup) ||
3674 				    (!octetstrmatch(&ipmp->ipGroupMemberIfIndex,
3675 				    &ips->ipGroupSourceIfIndex))) {
3676 					if (first_src)
3677 						continue;
3678 					else
3679 						break;
3680 				}
3681 				if (first_src) {
3682 					(void) printf("\t%s:    %s\n",
3683 					    fmodestr(
3684 					    ipmp->ipGroupMemberFilterMode),
3685 					    pr_addr(ips->ipGroupSourceAddress,
3686 					    abuf, sizeof (abuf)));
3687 					first_src = B_FALSE;
3688 					continue;
3689 				}
3690 
3691 				(void) printf("\t            %s\n",
3692 				    pr_addr(ips->ipGroupSourceAddress, abuf,
3693 				    sizeof (abuf)));
3694 			}
3695 		}
3696 		(void) putchar('\n');
3697 	}
3698 
3699 	if (family_selected(AF_INET6) && v6grp != NULL) {
3700 		if (Xflag)
3701 			(void) printf("%u records for ipv6GroupMember:\n",
3702 			    v6grp->length / sizeof (ipv6_member_t));
3703 
3704 		first = B_TRUE;
3705 		for (ipmp6 = (ipv6_member_t *)v6grp->valp;
3706 		    (char *)ipmp6 < (char *)v6grp->valp + v6grp->length;
3707 		    /* LINTED: (note 1) */
3708 		    ipmp6 = (ipv6_member_t *)((char *)ipmp6 +
3709 		    ipv6MemberEntrySize)) {
3710 			if (first) {
3711 				(void) puts("Group Memberships: "
3712 				    "IPv6");
3713 				(void) puts(" If       "
3714 				    "Group                   RefCnt");
3715 				(void) puts("----- "
3716 				    "--------------------------- ------");
3717 				first = B_FALSE;
3718 			}
3719 
3720 			(void) printf("%-5s %-27s %5u\n",
3721 			    ifindex2str(ipmp6->ipv6GroupMemberIfIndex, ifname),
3722 			    pr_addr6(&ipmp6->ipv6GroupMemberAddress,
3723 			    abuf, sizeof (abuf)),
3724 			    ipmp6->ipv6GroupMemberRefCnt);
3725 
3726 			if (!Vflag || v6src == NULL)
3727 				continue;
3728 
3729 			if (Xflag)
3730 				(void) printf("scanning %u ipv6GroupSource "
3731 				    "records...\n",
3732 				    v6src->length/sizeof (ipv6_grpsrc_t));
3733 
3734 			first_src = B_TRUE;
3735 			for (ips6 = (ipv6_grpsrc_t *)v6src->valp;
3736 			    (char *)ips6 < (char *)v6src->valp + v6src->length;
3737 			    /* LINTED: (note 1) */
3738 			    ips6 = (ipv6_grpsrc_t *)((char *)ips6 +
3739 			    ipv6GroupSourceEntrySize)) {
3740 				/* same assumption as in the v4 case above */
3741 				if ((ipmp6->ipv6GroupMemberIfIndex !=
3742 				    ips6->ipv6GroupSourceIfIndex) ||
3743 				    (!IN6_ARE_ADDR_EQUAL(
3744 				    &ipmp6->ipv6GroupMemberAddress,
3745 				    &ips6->ipv6GroupSourceGroup))) {
3746 					if (first_src)
3747 						continue;
3748 					else
3749 						break;
3750 				}
3751 				if (first_src) {
3752 					(void) printf("\t%s:    %s\n",
3753 					    fmodestr(
3754 					    ipmp6->ipv6GroupMemberFilterMode),
3755 					    pr_addr6(
3756 					    &ips6->ipv6GroupSourceAddress,
3757 					    abuf, sizeof (abuf)));
3758 					first_src = B_FALSE;
3759 					continue;
3760 				}
3761 
3762 				(void) printf("\t            %s\n",
3763 				    pr_addr6(&ips6->ipv6GroupSourceAddress,
3764 				    abuf, sizeof (abuf)));
3765 			}
3766 		}
3767 		(void) putchar('\n');
3768 	}
3769 
3770 	(void) putchar('\n');
3771 	(void) fflush(stdout);
3772 }
3773 
3774 /* --------------------- DCE_REPORT (netstat -d) ------------------------- */
3775 
3776 #define	FLBUFSIZE	8
3777 
3778 /* Assumes flbuf is at least 5 characters; callers use FLBUFSIZE */
3779 static char *
3780 dceflags2str(uint32_t flags, char *flbuf)
3781 {
3782 	char *str = flbuf;
3783 
3784 	if (flags & DCEF_DEFAULT)
3785 		*str++ = 'D';
3786 	if (flags & DCEF_PMTU)
3787 		*str++ = 'P';
3788 	if (flags & DCEF_UINFO)
3789 		*str++ = 'U';
3790 	if (flags & DCEF_TOO_SMALL_PMTU)
3791 		*str++ = 'S';
3792 	*str++ = '\0';
3793 	return (flbuf);
3794 }
3795 
3796 static void
3797 dce_report(mib_item_t *item)
3798 {
3799 	mib_item_t	*v4dce = NULL;
3800 	mib_item_t	*v6dce = NULL;
3801 	int		jtemp = 0;
3802 	char		ifname[LIFNAMSIZ + 1];
3803 	char		abuf[MAXHOSTNAMELEN + 1];
3804 	char		flbuf[FLBUFSIZE];
3805 	boolean_t	first;
3806 	dest_cache_entry_t *dce;
3807 
3808 	/* 'for' loop 1: */
3809 	for (; item; item = item->next_item) {
3810 		if (Xflag) {
3811 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
3812 			(void) printf("Group = %d, mib_id = %d, "
3813 			    "length = %d, valp = 0x%p\n",
3814 			    item->group, item->mib_id, item->length,
3815 			    item->valp);
3816 		}
3817 		if (item->group == MIB2_IP && family_selected(AF_INET) &&
3818 		    item->mib_id == EXPER_IP_DCE) {
3819 			v4dce = item;
3820 			if (Xflag)
3821 				(void) printf("item is v4dce info\n");
3822 		}
3823 		if (item->group == MIB2_IP6 && family_selected(AF_INET6) &&
3824 		    item->mib_id == EXPER_IP_DCE) {
3825 			v6dce = item;
3826 			if (Xflag)
3827 				(void) printf("item is v6dce info\n");
3828 		}
3829 	}
3830 
3831 	if (family_selected(AF_INET) && v4dce != NULL) {
3832 		if (Xflag)
3833 			(void) printf("%u records for DestCacheEntry:\n",
3834 			    v4dce->length / ipDestEntrySize);
3835 
3836 		first = B_TRUE;
3837 		for (dce = (dest_cache_entry_t *)v4dce->valp;
3838 		    (char *)dce < (char *)v4dce->valp + v4dce->length;
3839 		    /* LINTED: (note 1) */
3840 		    dce = (dest_cache_entry_t *)((char *)dce +
3841 		    ipDestEntrySize)) {
3842 			if (first) {
3843 				(void) putchar('\n');
3844 				(void) puts("Destination Cache Entries: IPv4");
3845 				(void) puts(
3846 				    "Address               PMTU   Age  Flags");
3847 				(void) puts(
3848 				    "-------------------- ------ ----- -----");
3849 				first = B_FALSE;
3850 			}
3851 
3852 			(void) printf("%-20s %6u %5u %-5s\n",
3853 			    pr_addr(dce->DestIpv4Address, abuf, sizeof (abuf)),
3854 			    dce->DestPmtu, dce->DestAge,
3855 			    dceflags2str(dce->DestFlags, flbuf));
3856 		}
3857 	}
3858 
3859 	if (family_selected(AF_INET6) && v6dce != NULL) {
3860 		if (Xflag)
3861 			(void) printf("%u records for DestCacheEntry:\n",
3862 			    v6dce->length / ipDestEntrySize);
3863 
3864 		first = B_TRUE;
3865 		for (dce = (dest_cache_entry_t *)v6dce->valp;
3866 		    (char *)dce < (char *)v6dce->valp + v6dce->length;
3867 		    /* LINTED: (note 1) */
3868 		    dce = (dest_cache_entry_t *)((char *)dce +
3869 		    ipDestEntrySize)) {
3870 			if (first) {
3871 				(void) putchar('\n');
3872 				(void) puts("Destination Cache Entries: IPv6");
3873 				(void) puts(
3874 				    "Address                      PMTU  "
3875 				    " Age Flags If ");
3876 				(void) puts(
3877 				    "--------------------------- ------ "
3878 				    "----- ----- ---");
3879 				first = B_FALSE;
3880 			}
3881 
3882 			(void) printf("%-27s %6u %5u %-5s %s\n",
3883 			    pr_addr6(&dce->DestIpv6Address, abuf,
3884 			    sizeof (abuf)),
3885 			    dce->DestPmtu, dce->DestAge,
3886 			    dceflags2str(dce->DestFlags, flbuf),
3887 			    dce->DestIfindex == 0 ? "" :
3888 			    ifindex2str(dce->DestIfindex, ifname));
3889 		}
3890 	}
3891 	(void) fflush(stdout);
3892 }
3893 
3894 /* --------------------- ARP_REPORT (netstat -p) -------------------------- */
3895 
3896 static void
3897 arp_report(mib_item_t *item)
3898 {
3899 	int		jtemp = 0;
3900 	char		ifname[LIFNAMSIZ + 1];
3901 	char		abuf[MAXHOSTNAMELEN + 1];
3902 	char		maskbuf[STR_EXPAND * OCTET_LENGTH + 1];
3903 	char		flbuf[32];	/* ACE_F_ flags */
3904 	char		xbuf[STR_EXPAND * OCTET_LENGTH + 1];
3905 	mib2_ipNetToMediaEntry_t	*np;
3906 	int		flags;
3907 	boolean_t	first;
3908 
3909 	if (!(family_selected(AF_INET)))
3910 		return;
3911 
3912 	/* 'for' loop 1: */
3913 	for (; item; item = item->next_item) {
3914 		if (Xflag) {
3915 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
3916 			(void) printf("Group = %d, mib_id = %d, "
3917 			    "length = %d, valp = 0x%p\n",
3918 			    item->group, item->mib_id, item->length,
3919 			    item->valp);
3920 		}
3921 		if (!(item->group == MIB2_IP && item->mib_id == MIB2_IP_MEDIA))
3922 			continue; /* 'for' loop 1 */
3923 
3924 		if (Xflag)
3925 			(void) printf("%u records for "
3926 			    "ipNetToMediaEntryTable:\n",
3927 			    item->length/sizeof (mib2_ipNetToMediaEntry_t));
3928 
3929 		first = B_TRUE;
3930 		/* 'for' loop 2: */
3931 		for (np = (mib2_ipNetToMediaEntry_t *)item->valp;
3932 		    (char *)np < (char *)item->valp + item->length;
3933 		    /* LINTED: (note 1) */
3934 		    np = (mib2_ipNetToMediaEntry_t *)((char *)np +
3935 		    ipNetToMediaEntrySize)) {
3936 			if (first) {
3937 				(void) puts(v4compat ?
3938 				    "Net to Media Table" :
3939 				    "Net to Media Table: IPv4");
3940 				(void) puts("Device "
3941 				    "  IP Address               Mask      "
3942 				    "Flags      Phys Addr");
3943 				(void) puts("------ "
3944 				    "-------------------- --------------- "
3945 				    "-------- ---------------");
3946 				first = B_FALSE;
3947 			}
3948 
3949 			flbuf[0] = '\0';
3950 			flags = np->ipNetToMediaInfo.ntm_flags;
3951 			/*
3952 			 * Note that not all flags are possible at the same
3953 			 * time.  Patterns: SPLAy DUo
3954 			 */
3955 			if (flags & ACE_F_PERMANENT)
3956 				(void) strcat(flbuf, "S");
3957 			if (flags & ACE_F_PUBLISH)
3958 				(void) strcat(flbuf, "P");
3959 			if (flags & ACE_F_DYING)
3960 				(void) strcat(flbuf, "D");
3961 			if (!(flags & ACE_F_RESOLVED))
3962 				(void) strcat(flbuf, "U");
3963 			if (flags & ACE_F_MAPPING)
3964 				(void) strcat(flbuf, "M");
3965 			if (flags & ACE_F_MYADDR)
3966 				(void) strcat(flbuf, "L");
3967 			if (flags & ACE_F_UNVERIFIED)
3968 				(void) strcat(flbuf, "d");
3969 			if (flags & ACE_F_AUTHORITY)
3970 				(void) strcat(flbuf, "A");
3971 			if (flags & ACE_F_OLD)
3972 				(void) strcat(flbuf, "o");
3973 			if (flags & ACE_F_DELAYED)
3974 				(void) strcat(flbuf, "y");
3975 			(void) printf("%-6s %-20s %-15s %-8s %s\n",
3976 			    octetstr(&np->ipNetToMediaIfIndex, 'a',
3977 			    ifname, sizeof (ifname)),
3978 			    pr_addr(np->ipNetToMediaNetAddress,
3979 			    abuf, sizeof (abuf)),
3980 			    octetstr(&np->ipNetToMediaInfo.ntm_mask, 'd',
3981 			    maskbuf, sizeof (maskbuf)),
3982 			    flbuf,
3983 			    octetstr(&np->ipNetToMediaPhysAddress, 'h',
3984 			    xbuf, sizeof (xbuf)));
3985 		} /* 'for' loop 2 ends */
3986 	} /* 'for' loop 1 ends */
3987 	(void) fflush(stdout);
3988 }
3989 
3990 /* --------------------- NDP_REPORT (netstat -p) -------------------------- */
3991 
3992 static void
3993 ndp_report(mib_item_t *item)
3994 {
3995 	int		jtemp = 0;
3996 	char		abuf[MAXHOSTNAMELEN + 1];
3997 	char		*state;
3998 	char		*type;
3999 	char		xbuf[STR_EXPAND * OCTET_LENGTH + 1];
4000 	mib2_ipv6NetToMediaEntry_t	*np6;
4001 	char		ifname[LIFNAMSIZ + 1];
4002 	boolean_t	first;
4003 
4004 	if (!(family_selected(AF_INET6)))
4005 		return;
4006 
4007 	/* 'for' loop 1: */
4008 	for (; item; item = item->next_item) {
4009 		if (Xflag) {
4010 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
4011 			(void) printf("Group = %d, mib_id = %d, "
4012 			    "length = %d, valp = 0x%p\n",
4013 			    item->group, item->mib_id, item->length,
4014 			    item->valp);
4015 		}
4016 		if (!(item->group == MIB2_IP6 &&
4017 		    item->mib_id == MIB2_IP6_MEDIA))
4018 			continue; /* 'for' loop 1 */
4019 
4020 		first = B_TRUE;
4021 		/* 'for' loop 2: */
4022 		for (np6 = (mib2_ipv6NetToMediaEntry_t *)item->valp;
4023 		    (char *)np6 < (char *)item->valp + item->length;
4024 		    /* LINTED: (note 1) */
4025 		    np6 = (mib2_ipv6NetToMediaEntry_t *)((char *)np6 +
4026 		    ipv6NetToMediaEntrySize)) {
4027 			if (first) {
4028 				(void) puts("\nNet to Media Table: IPv6");
4029 				(void) puts(" If   Physical Address   "
4030 				    " Type      State      Destination/Mask");
4031 				(void) puts("----- -----------------  "
4032 				    "------- ------------ "
4033 				    "---------------------------");
4034 				first = B_FALSE;
4035 			}
4036 
4037 			switch (np6->ipv6NetToMediaState) {
4038 			case ND_INCOMPLETE:
4039 				state = "INCOMPLETE";
4040 				break;
4041 			case ND_REACHABLE:
4042 				state = "REACHABLE";
4043 				break;
4044 			case ND_STALE:
4045 				state = "STALE";
4046 				break;
4047 			case ND_DELAY:
4048 				state = "DELAY";
4049 				break;
4050 			case ND_PROBE:
4051 				state = "PROBE";
4052 				break;
4053 			case ND_UNREACHABLE:
4054 				state = "UNREACHABLE";
4055 				break;
4056 			default:
4057 				state = "UNKNOWN";
4058 			}
4059 
4060 			switch (np6->ipv6NetToMediaType) {
4061 			case 1:
4062 				type = "other";
4063 				break;
4064 			case 2:
4065 				type = "dynamic";
4066 				break;
4067 			case 3:
4068 				type = "static";
4069 				break;
4070 			case 4:
4071 				type = "local";
4072 				break;
4073 			}
4074 			(void) printf("%-5s %-17s  %-7s %-12s %-27s\n",
4075 			    ifindex2str(np6->ipv6NetToMediaIfIndex, ifname),
4076 			    octetstr(&np6->ipv6NetToMediaPhysAddress, 'h',
4077 			    xbuf, sizeof (xbuf)),
4078 			    type,
4079 			    state,
4080 			    pr_addr6(&np6->ipv6NetToMediaNetAddress,
4081 			    abuf, sizeof (abuf)));
4082 		} /* 'for' loop 2 ends */
4083 	} /* 'for' loop 1 ends */
4084 	(void) putchar('\n');
4085 	(void) fflush(stdout);
4086 }
4087 
4088 /* ------------------------- ire_report (netstat -r) ------------------------ */
4089 
4090 typedef struct sec_attr_list_s {
4091 	struct sec_attr_list_s *sal_next;
4092 	const mib2_ipAttributeEntry_t *sal_attr;
4093 } sec_attr_list_t;
4094 
4095 static boolean_t ire_report_item_v4(const mib2_ipRouteEntry_t *, boolean_t,
4096     const sec_attr_list_t *);
4097 static boolean_t ire_report_item_v6(const mib2_ipv6RouteEntry_t *, boolean_t,
4098     const sec_attr_list_t *);
4099 static const char *pr_secattr(const sec_attr_list_t *);
4100 
4101 static void
4102 ire_report(const mib_item_t *item)
4103 {
4104 	int			jtemp = 0;
4105 	boolean_t		print_hdr_once_v4 = B_TRUE;
4106 	boolean_t		print_hdr_once_v6 = B_TRUE;
4107 	mib2_ipRouteEntry_t	*rp;
4108 	mib2_ipv6RouteEntry_t	*rp6;
4109 	sec_attr_list_t		**v4_attrs, **v4a;
4110 	sec_attr_list_t		**v6_attrs, **v6a;
4111 	sec_attr_list_t		*all_attrs, *aptr;
4112 	const mib_item_t	*iptr;
4113 	int			ipv4_route_count, ipv6_route_count;
4114 	int			route_attrs_count;
4115 
4116 	/*
4117 	 * Preparation pass: the kernel returns separate entries for IP routing
4118 	 * table entries and security attributes.  We loop through the
4119 	 * attributes first and link them into lists.
4120 	 */
4121 	ipv4_route_count = ipv6_route_count = route_attrs_count = 0;
4122 	for (iptr = item; iptr != NULL; iptr = iptr->next_item) {
4123 		if (iptr->group == MIB2_IP6 && iptr->mib_id == MIB2_IP6_ROUTE)
4124 			ipv6_route_count += iptr->length / ipv6RouteEntrySize;
4125 		if (iptr->group == MIB2_IP && iptr->mib_id == MIB2_IP_ROUTE)
4126 			ipv4_route_count += iptr->length / ipRouteEntrySize;
4127 		if ((iptr->group == MIB2_IP || iptr->group == MIB2_IP6) &&
4128 		    iptr->mib_id == EXPER_IP_RTATTR)
4129 			route_attrs_count += iptr->length /
4130 			    ipRouteAttributeSize;
4131 	}
4132 	v4_attrs = v6_attrs = NULL;
4133 	all_attrs = NULL;
4134 	if (family_selected(AF_INET) && ipv4_route_count > 0) {
4135 		v4_attrs = calloc(ipv4_route_count, sizeof (*v4_attrs));
4136 		if (v4_attrs == NULL) {
4137 			perror("ire_report calloc v4_attrs failed");
4138 			return;
4139 		}
4140 	}
4141 	if (family_selected(AF_INET6) && ipv6_route_count > 0) {
4142 		v6_attrs = calloc(ipv6_route_count, sizeof (*v6_attrs));
4143 		if (v6_attrs == NULL) {
4144 			perror("ire_report calloc v6_attrs failed");
4145 			goto ire_report_done;
4146 		}
4147 	}
4148 	if (route_attrs_count > 0) {
4149 		all_attrs = malloc(route_attrs_count * sizeof (*all_attrs));
4150 		if (all_attrs == NULL) {
4151 			perror("ire_report malloc all_attrs failed");
4152 			goto ire_report_done;
4153 		}
4154 	}
4155 	aptr = all_attrs;
4156 	for (iptr = item; iptr != NULL; iptr = iptr->next_item) {
4157 		mib2_ipAttributeEntry_t *iae;
4158 		sec_attr_list_t **alp;
4159 
4160 		if (v4_attrs != NULL && iptr->group == MIB2_IP &&
4161 		    iptr->mib_id == EXPER_IP_RTATTR) {
4162 			alp = v4_attrs;
4163 		} else if (v6_attrs != NULL && iptr->group == MIB2_IP6 &&
4164 		    iptr->mib_id == EXPER_IP_RTATTR) {
4165 			alp = v6_attrs;
4166 		} else {
4167 			continue;
4168 		}
4169 		for (iae = iptr->valp;
4170 		    (char *)iae < (char *)iptr->valp + iptr->length;
4171 		    /* LINTED: (note 1) */
4172 		    iae = (mib2_ipAttributeEntry_t *)((char *)iae +
4173 		    ipRouteAttributeSize)) {
4174 			aptr->sal_next = alp[iae->iae_routeidx];
4175 			aptr->sal_attr = iae;
4176 			alp[iae->iae_routeidx] = aptr++;
4177 		}
4178 	}
4179 
4180 	/* 'for' loop 1: */
4181 	v4a = v4_attrs;
4182 	v6a = v6_attrs;
4183 	for (; item != NULL; item = item->next_item) {
4184 		if (Xflag) {
4185 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
4186 			(void) printf("Group = %d, mib_id = %d, "
4187 			    "length = %d, valp = 0x%p\n",
4188 			    item->group, item->mib_id,
4189 			    item->length, item->valp);
4190 		}
4191 		if (!((item->group == MIB2_IP &&
4192 		    item->mib_id == MIB2_IP_ROUTE) ||
4193 		    (item->group == MIB2_IP6 &&
4194 		    item->mib_id == MIB2_IP6_ROUTE)))
4195 			continue; /* 'for' loop 1 */
4196 
4197 		if (item->group == MIB2_IP && !family_selected(AF_INET))
4198 			continue; /* 'for' loop 1 */
4199 		else if (item->group == MIB2_IP6 && !family_selected(AF_INET6))
4200 			continue; /* 'for' loop 1 */
4201 
4202 		if (Xflag) {
4203 			if (item->group == MIB2_IP) {
4204 				(void) printf("%u records for "
4205 				    "ipRouteEntryTable:\n",
4206 				    item->length/sizeof (mib2_ipRouteEntry_t));
4207 			} else {
4208 				(void) printf("%u records for "
4209 				    "ipv6RouteEntryTable:\n",
4210 				    item->length/
4211 				    sizeof (mib2_ipv6RouteEntry_t));
4212 			}
4213 		}
4214 
4215 		if (item->group == MIB2_IP) {
4216 			for (rp = (mib2_ipRouteEntry_t *)item->valp;
4217 			    (char *)rp < (char *)item->valp + item->length;
4218 			    /* LINTED: (note 1) */
4219 			    rp = (mib2_ipRouteEntry_t *)((char *)rp +
4220 			    ipRouteEntrySize)) {
4221 				aptr = v4a == NULL ? NULL : *v4a++;
4222 				print_hdr_once_v4 = ire_report_item_v4(rp,
4223 				    print_hdr_once_v4, aptr);
4224 			}
4225 		} else {
4226 			for (rp6 = (mib2_ipv6RouteEntry_t *)item->valp;
4227 			    (char *)rp6 < (char *)item->valp + item->length;
4228 			    /* LINTED: (note 1) */
4229 			    rp6 = (mib2_ipv6RouteEntry_t *)((char *)rp6 +
4230 			    ipv6RouteEntrySize)) {
4231 				aptr = v6a == NULL ? NULL : *v6a++;
4232 				print_hdr_once_v6 = ire_report_item_v6(rp6,
4233 				    print_hdr_once_v6, aptr);
4234 			}
4235 		}
4236 	} /* 'for' loop 1 ends */
4237 	(void) fflush(stdout);
4238 ire_report_done:
4239 	if (v4_attrs != NULL)
4240 		free(v4_attrs);
4241 	if (v6_attrs != NULL)
4242 		free(v6_attrs);
4243 	if (all_attrs != NULL)
4244 		free(all_attrs);
4245 }
4246 
4247 /*
4248  * Match a user-supplied device name.  We do this by string because
4249  * the MIB2 interface gives us interface name strings rather than
4250  * ifIndex numbers.  The "none" rule matches only routes with no
4251  * interface.  The "any" rule matches routes with any non-blank
4252  * interface.  A base name ("hme0") matches all aliases as well
4253  * ("hme0:1").
4254  */
4255 static boolean_t
4256 dev_name_match(const DeviceName *devnam, const char *ifname)
4257 {
4258 	int iflen;
4259 
4260 	if (ifname == NULL)
4261 		return (devnam->o_length == 0);		/* "none" */
4262 	if (*ifname == '\0')
4263 		return (devnam->o_length != 0);		/* "any" */
4264 	iflen = strlen(ifname);
4265 	/* The check for ':' here supports interface aliases. */
4266 	if (iflen > devnam->o_length ||
4267 	    (iflen < devnam->o_length && devnam->o_bytes[iflen] != ':'))
4268 		return (B_FALSE);
4269 	return (strncmp(ifname, devnam->o_bytes, iflen) == 0);
4270 }
4271 
4272 /*
4273  * Match a user-supplied IP address list.  The "any" rule matches any
4274  * non-zero address.  The "none" rule matches only the zero address.
4275  * IPv6 addresses supplied by the user are ignored.  If the user
4276  * supplies a subnet mask, then match routes that are at least that
4277  * specific (use the user's mask).  If the user supplies only an
4278  * address, then select any routes that would match (use the route's
4279  * mask).
4280  */
4281 static boolean_t
4282 v4_addr_match(IpAddress addr, IpAddress mask, const filter_t *fp)
4283 {
4284 	char **app;
4285 	char *aptr;
4286 	in_addr_t faddr, fmask;
4287 
4288 	if (fp->u.a.f_address == NULL) {
4289 		if (IN6_IS_ADDR_UNSPECIFIED(&fp->u.a.f_mask))
4290 			return (addr != INADDR_ANY);	/* "any" */
4291 		else
4292 			return (addr == INADDR_ANY);	/* "none" */
4293 	}
4294 	if (!IN6_IS_V4MASK(fp->u.a.f_mask))
4295 		return (B_FALSE);
4296 	IN6_V4MAPPED_TO_IPADDR(&fp->u.a.f_mask, fmask);
4297 	if (fmask != IP_HOST_MASK) {
4298 		if (fmask > mask)
4299 			return (B_FALSE);
4300 		mask = fmask;
4301 	}
4302 	for (app = fp->u.a.f_address->h_addr_list; (aptr = *app) != NULL; app++)
4303 		/* LINTED: (note 1) */
4304 		if (IN6_IS_ADDR_V4MAPPED((in6_addr_t *)aptr)) {
4305 			/* LINTED: (note 1) */
4306 			IN6_V4MAPPED_TO_IPADDR((in6_addr_t *)aptr, faddr);
4307 			if (((faddr ^ addr) & mask) == 0)
4308 				return (B_TRUE);
4309 		}
4310 	return (B_FALSE);
4311 }
4312 
4313 /*
4314  * Run through the filter list for an IPv4 MIB2 route entry.  If all
4315  * filters of a given type fail to match, then the route is filtered
4316  * out (not displayed).  If no filter is given or at least one filter
4317  * of each type matches, then display the route.
4318  */
4319 static boolean_t
4320 ire_filter_match_v4(const mib2_ipRouteEntry_t *rp, uint_t flag_b)
4321 {
4322 	filter_t *fp;
4323 	int idx;
4324 
4325 	/* 'for' loop 1: */
4326 	for (idx = 0; idx < NFILTERKEYS; idx++)
4327 		if ((fp = filters[idx]) != NULL) {
4328 			/* 'for' loop 2: */
4329 			for (; fp != NULL; fp = fp->f_next) {
4330 				switch (idx) {
4331 				case FK_AF:
4332 					if (fp->u.f_family != AF_INET)
4333 						continue; /* 'for' loop 2 */
4334 					break;
4335 				case FK_OUTIF:
4336 					if (!dev_name_match(&rp->ipRouteIfIndex,
4337 					    fp->u.f_ifname))
4338 						continue; /* 'for' loop 2 */
4339 					break;
4340 				case FK_DST:
4341 					if (!v4_addr_match(rp->ipRouteDest,
4342 					    rp->ipRouteMask, fp))
4343 						continue; /* 'for' loop 2 */
4344 					break;
4345 				case FK_FLAGS:
4346 					if ((flag_b & fp->u.f.f_flagset) !=
4347 					    fp->u.f.f_flagset ||
4348 					    (flag_b & fp->u.f.f_flagclear))
4349 						continue; /* 'for' loop 2 */
4350 					break;
4351 				}
4352 				break;
4353 			} /* 'for' loop 2 ends */
4354 			if (fp == NULL)
4355 				return (B_FALSE);
4356 		}
4357 	/* 'for' loop 1 ends */
4358 	return (B_TRUE);
4359 }
4360 
4361 /*
4362  * Given an IPv4 MIB2 route entry, form the list of flags for the
4363  * route.
4364  */
4365 static uint_t
4366 form_v4_route_flags(const mib2_ipRouteEntry_t *rp, char *flags)
4367 {
4368 	uint_t flag_b;
4369 
4370 	flag_b = FLF_U;
4371 	(void) strcpy(flags, "U");
4372 	/* RTF_INDIRECT wins over RTF_GATEWAY - don't display both */
4373 	if (rp->ipRouteInfo.re_flags & RTF_INDIRECT) {
4374 		(void) strcat(flags, "I");
4375 		flag_b |= FLF_I;
4376 	} else if (rp->ipRouteInfo.re_ire_type & IRE_OFFLINK) {
4377 		(void) strcat(flags, "G");
4378 		flag_b |= FLF_G;
4379 	}
4380 	/* IRE_IF_CLONE wins over RTF_HOST - don't display both */
4381 	if (rp->ipRouteInfo.re_ire_type & IRE_IF_CLONE) {
4382 		(void) strcat(flags, "C");
4383 		flag_b |= FLF_C;
4384 	} else if (rp->ipRouteMask == IP_HOST_MASK) {
4385 		(void) strcat(flags, "H");
4386 		flag_b |= FLF_H;
4387 	}
4388 	if (rp->ipRouteInfo.re_flags & RTF_DYNAMIC) {
4389 		(void) strcat(flags, "D");
4390 		flag_b |= FLF_D;
4391 	}
4392 	if (rp->ipRouteInfo.re_ire_type == IRE_BROADCAST) {	/* Broadcast */
4393 		(void) strcat(flags, "b");
4394 		flag_b |= FLF_b;
4395 	}
4396 	if (rp->ipRouteInfo.re_ire_type == IRE_LOCAL) {		/* Local */
4397 		(void) strcat(flags, "L");
4398 		flag_b |= FLF_L;
4399 	}
4400 	if (rp->ipRouteInfo.re_flags & RTF_MULTIRT) {
4401 		(void) strcat(flags, "M");			/* Multiroute */
4402 		flag_b |= FLF_M;
4403 	}
4404 	if (rp->ipRouteInfo.re_flags & RTF_SETSRC) {
4405 		(void) strcat(flags, "S");			/* Setsrc */
4406 		flag_b |= FLF_S;
4407 	}
4408 	if (rp->ipRouteInfo.re_flags & RTF_REJECT) {
4409 		(void) strcat(flags, "R");
4410 		flag_b |= FLF_R;
4411 	}
4412 	if (rp->ipRouteInfo.re_flags & RTF_BLACKHOLE) {
4413 		(void) strcat(flags, "B");
4414 		flag_b |= FLF_B;
4415 	}
4416 	if (rp->ipRouteInfo.re_flags & RTF_ZONE) {
4417 		(void) strcat(flags, "Z");
4418 		flag_b |= FLF_Z;
4419 	}
4420 	return (flag_b);
4421 }
4422 
4423 static const char ire_hdr_v4[] =
4424 "\n%s Table: IPv4\n";
4425 static const char ire_hdr_v4_compat[] =
4426 "\n%s Table:\n";
4427 static const char ire_hdr_v4_verbose[] =
4428 "  Destination             Mask           Gateway          Device "
4429 " MTU  Ref Flg  Out  In/Fwd %s\n"
4430 "-------------------- --------------- -------------------- ------ "
4431 "----- --- --- ----- ------ %s\n";
4432 
4433 static const char ire_hdr_v4_normal[] =
4434 "  Destination           Gateway           Flags  Ref     Use     Interface"
4435 " %s\n-------------------- -------------------- ----- ----- ---------- "
4436 "--------- %s\n";
4437 
4438 static boolean_t
4439 ire_report_item_v4(const mib2_ipRouteEntry_t *rp, boolean_t first,
4440     const sec_attr_list_t *attrs)
4441 {
4442 	char			dstbuf[MAXHOSTNAMELEN + 1];
4443 	char			maskbuf[MAXHOSTNAMELEN + 1];
4444 	char			gwbuf[MAXHOSTNAMELEN + 1];
4445 	char			ifname[LIFNAMSIZ + 1];
4446 	char			flags[10];	/* RTF_ flags */
4447 	uint_t			flag_b;
4448 
4449 	if (!(Aflag || (rp->ipRouteInfo.re_ire_type != IRE_IF_CLONE &&
4450 	    rp->ipRouteInfo.re_ire_type != IRE_BROADCAST &&
4451 	    rp->ipRouteInfo.re_ire_type != IRE_MULTICAST &&
4452 	    rp->ipRouteInfo.re_ire_type != IRE_NOROUTE &&
4453 	    rp->ipRouteInfo.re_ire_type != IRE_LOCAL))) {
4454 		return (first);
4455 	}
4456 
4457 	flag_b = form_v4_route_flags(rp, flags);
4458 
4459 	if (!ire_filter_match_v4(rp, flag_b))
4460 		return (first);
4461 
4462 	if (first) {
4463 		(void) printf(v4compat ? ire_hdr_v4_compat : ire_hdr_v4,
4464 		    Vflag ? "IRE" : "Routing");
4465 		(void) printf(Vflag ? ire_hdr_v4_verbose : ire_hdr_v4_normal,
4466 		    RSECflag ? "  Gateway security attributes  " : "",
4467 		    RSECflag ? "-------------------------------" : "");
4468 		first = B_FALSE;
4469 	}
4470 
4471 	if (flag_b & FLF_H) {
4472 		(void) pr_addr(rp->ipRouteDest, dstbuf, sizeof (dstbuf));
4473 	} else {
4474 		(void) pr_net(rp->ipRouteDest, rp->ipRouteMask,
4475 		    dstbuf, sizeof (dstbuf));
4476 	}
4477 	if (Vflag) {
4478 		(void) printf("%-20s %-15s %-20s %-6s %5u %3u "
4479 		    "%-4s%6u %6u %s\n",
4480 		    dstbuf,
4481 		    pr_mask(rp->ipRouteMask, maskbuf, sizeof (maskbuf)),
4482 		    pr_addrnz(rp->ipRouteNextHop, gwbuf, sizeof (gwbuf)),
4483 		    octetstr(&rp->ipRouteIfIndex, 'a', ifname, sizeof (ifname)),
4484 		    rp->ipRouteInfo.re_max_frag,
4485 		    rp->ipRouteInfo.re_ref,
4486 		    flags,
4487 		    rp->ipRouteInfo.re_obpkt,
4488 		    rp->ipRouteInfo.re_ibpkt,
4489 		    pr_secattr(attrs));
4490 	} else {
4491 		(void) printf("%-20s %-20s %-5s  %4u %10u %-9s %s\n",
4492 		    dstbuf,
4493 		    pr_addrnz(rp->ipRouteNextHop, gwbuf, sizeof (gwbuf)),
4494 		    flags,
4495 		    rp->ipRouteInfo.re_ref,
4496 		    rp->ipRouteInfo.re_obpkt + rp->ipRouteInfo.re_ibpkt,
4497 		    octetstr(&rp->ipRouteIfIndex, 'a',
4498 		    ifname, sizeof (ifname)),
4499 		    pr_secattr(attrs));
4500 	}
4501 	return (first);
4502 }
4503 
4504 /*
4505  * Match a user-supplied IP address list against an IPv6 route entry.
4506  * If the user specified "any," then any non-zero address matches.  If
4507  * the user specified "none," then only the zero address matches.  If
4508  * the user specified a subnet mask length, then use that in matching
4509  * routes (select routes that are at least as specific).  If the user
4510  * specified only an address, then use the route's mask (select routes
4511  * that would match that address).  IPv4 addresses are ignored.
4512  */
4513 static boolean_t
4514 v6_addr_match(const Ip6Address *addr, int masklen, const filter_t *fp)
4515 {
4516 	const uint8_t *ucp;
4517 	int fmasklen;
4518 	int i;
4519 	char **app;
4520 	const uint8_t *aptr;
4521 
4522 	if (fp->u.a.f_address == NULL) {
4523 		if (IN6_IS_ADDR_UNSPECIFIED(&fp->u.a.f_mask))	/* any */
4524 			return (!IN6_IS_ADDR_UNSPECIFIED(addr));
4525 		return (IN6_IS_ADDR_UNSPECIFIED(addr));		/* "none" */
4526 	}
4527 	fmasklen = 0;
4528 	/* 'for' loop 1a: */
4529 	for (ucp = fp->u.a.f_mask.s6_addr;
4530 	    ucp < fp->u.a.f_mask.s6_addr + sizeof (fp->u.a.f_mask.s6_addr);
4531 	    ucp++) {
4532 		if (*ucp != 0xff) {
4533 			if (*ucp != 0)
4534 				fmasklen += 9 - ffs(*ucp);
4535 			break; /* 'for' loop 1a */
4536 		}
4537 		fmasklen += 8;
4538 	} /* 'for' loop 1a ends */
4539 	if (fmasklen != IPV6_ABITS) {
4540 		if (fmasklen > masklen)
4541 			return (B_FALSE);
4542 		masklen = fmasklen;
4543 	}
4544 	/* 'for' loop 1b: */
4545 	for (app = fp->u.a.f_address->h_addr_list;
4546 	    (aptr = (uint8_t *)*app) != NULL; app++) {
4547 		/* LINTED: (note 1) */
4548 		if (IN6_IS_ADDR_V4MAPPED((in6_addr_t *)aptr))
4549 			continue; /* 'for' loop 1b */
4550 		ucp = addr->s6_addr;
4551 		for (i = masklen; i >= 8; i -= 8)
4552 			if (*ucp++ != *aptr++)
4553 				break; /* 'for' loop 1b */
4554 		if (i == 0 ||
4555 		    (i < 8 && ((*ucp ^ *aptr) & ~(0xff >> i)) == 0))
4556 			return (B_TRUE);
4557 	} /* 'for' loop 1b ends */
4558 	return (B_FALSE);
4559 }
4560 
4561 /*
4562  * Run through the filter list for an IPv6 MIB2 IRE.  For a given
4563  * type, if there's at least one filter and all filters of that type
4564  * fail to match, then the route doesn't match and isn't displayed.
4565  * If at least one matches, or none are specified, for each of the
4566  * types, then the route is selected and displayed.
4567  */
4568 static boolean_t
4569 ire_filter_match_v6(const mib2_ipv6RouteEntry_t *rp6, uint_t flag_b)
4570 {
4571 	filter_t *fp;
4572 	int idx;
4573 
4574 	/* 'for' loop 1: */
4575 	for (idx = 0; idx < NFILTERKEYS; idx++)
4576 		if ((fp = filters[idx]) != NULL) {
4577 			/* 'for' loop 2: */
4578 			for (; fp != NULL; fp = fp->f_next) {
4579 				switch (idx) {
4580 				case FK_AF:
4581 					if (fp->u.f_family != AF_INET6)
4582 						/* 'for' loop 2 */
4583 						continue;
4584 					break;
4585 				case FK_OUTIF:
4586 					if (!dev_name_match(&rp6->
4587 					    ipv6RouteIfIndex, fp->u.f_ifname))
4588 						/* 'for' loop 2 */
4589 						continue;
4590 					break;
4591 				case FK_DST:
4592 					if (!v6_addr_match(&rp6->ipv6RouteDest,
4593 					    rp6->ipv6RoutePfxLength, fp))
4594 						/* 'for' loop 2 */
4595 						continue;
4596 					break;
4597 				case FK_FLAGS:
4598 					if ((flag_b & fp->u.f.f_flagset) !=
4599 					    fp->u.f.f_flagset ||
4600 					    (flag_b & fp->u.f.f_flagclear))
4601 						/* 'for' loop 2 */
4602 						continue;
4603 					break;
4604 				}
4605 				break;
4606 			} /* 'for' loop 2 ends */
4607 			if (fp == NULL)
4608 				return (B_FALSE);
4609 		}
4610 	/* 'for' loop 1 ends */
4611 	return (B_TRUE);
4612 }
4613 
4614 /*
4615  * Given an IPv6 MIB2 route entry, form the list of flags for the
4616  * route.
4617  */
4618 static uint_t
4619 form_v6_route_flags(const mib2_ipv6RouteEntry_t *rp6, char *flags)
4620 {
4621 	uint_t flag_b;
4622 
4623 	flag_b = FLF_U;
4624 	(void) strcpy(flags, "U");
4625 	/* RTF_INDIRECT wins over RTF_GATEWAY - don't display both */
4626 	if (rp6->ipv6RouteInfo.re_flags & RTF_INDIRECT) {
4627 		(void) strcat(flags, "I");
4628 		flag_b |= FLF_I;
4629 	} else if (rp6->ipv6RouteInfo.re_ire_type & IRE_OFFLINK) {
4630 		(void) strcat(flags, "G");
4631 		flag_b |= FLF_G;
4632 	}
4633 
4634 	/* IRE_IF_CLONE wins over RTF_HOST - don't display both */
4635 	if (rp6->ipv6RouteInfo.re_ire_type & IRE_IF_CLONE) {
4636 		(void) strcat(flags, "C");
4637 		flag_b |= FLF_C;
4638 	} else if (rp6->ipv6RoutePfxLength == IPV6_ABITS) {
4639 		(void) strcat(flags, "H");
4640 		flag_b |= FLF_H;
4641 	}
4642 
4643 	if (rp6->ipv6RouteInfo.re_flags & RTF_DYNAMIC) {
4644 		(void) strcat(flags, "D");
4645 		flag_b |= FLF_D;
4646 	}
4647 	if (rp6->ipv6RouteInfo.re_ire_type == IRE_LOCAL) {	/* Local */
4648 		(void) strcat(flags, "L");
4649 		flag_b |= FLF_L;
4650 	}
4651 	if (rp6->ipv6RouteInfo.re_flags & RTF_MULTIRT) {
4652 		(void) strcat(flags, "M");			/* Multiroute */
4653 		flag_b |= FLF_M;
4654 	}
4655 	if (rp6->ipv6RouteInfo.re_flags & RTF_SETSRC) {
4656 		(void) strcat(flags, "S");			/* Setsrc */
4657 		flag_b |= FLF_S;
4658 	}
4659 	if (rp6->ipv6RouteInfo.re_flags & RTF_REJECT) {
4660 		(void) strcat(flags, "R");
4661 		flag_b |= FLF_R;
4662 	}
4663 	if (rp6->ipv6RouteInfo.re_flags & RTF_BLACKHOLE) {
4664 		(void) strcat(flags, "B");
4665 		flag_b |= FLF_B;
4666 	}
4667 	if (rp6->ipv6RouteInfo.re_flags & RTF_ZONE) {
4668 		(void) strcat(flags, "Z");
4669 		flag_b |= FLF_Z;
4670 	}
4671 	return (flag_b);
4672 }
4673 
4674 static const char ire_hdr_v6[] =
4675 "\n%s Table: IPv6\n";
4676 static const char ire_hdr_v6_verbose[] =
4677 "  Destination/Mask            Gateway                    If    MTU  "
4678 "Ref Flags  Out   In/Fwd %s\n"
4679 "--------------------------- --------------------------- ----- ----- "
4680 "--- ----- ------ ------ %s\n";
4681 static const char ire_hdr_v6_normal[] =
4682 "  Destination/Mask            Gateway                   Flags Ref   Use  "
4683 "  If   %s\n"
4684 "--------------------------- --------------------------- ----- --- ------- "
4685 "----- %s\n";
4686 
4687 static boolean_t
4688 ire_report_item_v6(const mib2_ipv6RouteEntry_t *rp6, boolean_t first,
4689     const sec_attr_list_t *attrs)
4690 {
4691 	char			dstbuf[MAXHOSTNAMELEN + 1];
4692 	char			gwbuf[MAXHOSTNAMELEN + 1];
4693 	char			ifname[LIFNAMSIZ + 1];
4694 	char			flags[10];	/* RTF_ flags */
4695 	uint_t			flag_b;
4696 
4697 	if (!(Aflag || (rp6->ipv6RouteInfo.re_ire_type != IRE_IF_CLONE &&
4698 	    rp6->ipv6RouteInfo.re_ire_type != IRE_MULTICAST &&
4699 	    rp6->ipv6RouteInfo.re_ire_type != IRE_NOROUTE &&
4700 	    rp6->ipv6RouteInfo.re_ire_type != IRE_LOCAL))) {
4701 		return (first);
4702 	}
4703 
4704 	flag_b = form_v6_route_flags(rp6, flags);
4705 
4706 	if (!ire_filter_match_v6(rp6, flag_b))
4707 		return (first);
4708 
4709 	if (first) {
4710 		(void) printf(ire_hdr_v6, Vflag ? "IRE" : "Routing");
4711 		(void) printf(Vflag ? ire_hdr_v6_verbose : ire_hdr_v6_normal,
4712 		    RSECflag ? "  Gateway security attributes  " : "",
4713 		    RSECflag ? "-------------------------------" : "");
4714 		first = B_FALSE;
4715 	}
4716 
4717 	if (Vflag) {
4718 		(void) printf("%-27s %-27s %-5s %5u %3u "
4719 		    "%-5s %6u %6u %s\n",
4720 		    pr_prefix6(&rp6->ipv6RouteDest,
4721 		    rp6->ipv6RoutePfxLength, dstbuf, sizeof (dstbuf)),
4722 		    IN6_IS_ADDR_UNSPECIFIED(&rp6->ipv6RouteNextHop) ?
4723 		    "    --" :
4724 		    pr_addr6(&rp6->ipv6RouteNextHop, gwbuf, sizeof (gwbuf)),
4725 		    octetstr(&rp6->ipv6RouteIfIndex, 'a',
4726 		    ifname, sizeof (ifname)),
4727 		    rp6->ipv6RouteInfo.re_max_frag,
4728 		    rp6->ipv6RouteInfo.re_ref,
4729 		    flags,
4730 		    rp6->ipv6RouteInfo.re_obpkt,
4731 		    rp6->ipv6RouteInfo.re_ibpkt,
4732 		    pr_secattr(attrs));
4733 	} else {
4734 		(void) printf("%-27s %-27s %-5s %3u %7u %-5s %s\n",
4735 		    pr_prefix6(&rp6->ipv6RouteDest,
4736 		    rp6->ipv6RoutePfxLength, dstbuf, sizeof (dstbuf)),
4737 		    IN6_IS_ADDR_UNSPECIFIED(&rp6->ipv6RouteNextHop) ?
4738 		    "    --" :
4739 		    pr_addr6(&rp6->ipv6RouteNextHop, gwbuf, sizeof (gwbuf)),
4740 		    flags,
4741 		    rp6->ipv6RouteInfo.re_ref,
4742 		    rp6->ipv6RouteInfo.re_obpkt + rp6->ipv6RouteInfo.re_ibpkt,
4743 		    octetstr(&rp6->ipv6RouteIfIndex, 'a',
4744 		    ifname, sizeof (ifname)),
4745 		    pr_secattr(attrs));
4746 	}
4747 	return (first);
4748 }
4749 
4750 /*
4751  * Common attribute-gathering routine for all transports.
4752  */
4753 static mib2_transportMLPEntry_t **
4754 gather_attrs(const mib_item_t *item, int group, int mib_id, int esize)
4755 {
4756 	int transport_count = 0;
4757 	const mib_item_t *iptr;
4758 	mib2_transportMLPEntry_t **attrs, *tme;
4759 
4760 	for (iptr = item; iptr != NULL; iptr = iptr->next_item) {
4761 		if (iptr->group == group && iptr->mib_id == mib_id)
4762 			transport_count += iptr->length / esize;
4763 	}
4764 	if (transport_count <= 0)
4765 		return (NULL);
4766 	attrs = calloc(transport_count, sizeof (*attrs));
4767 	if (attrs == NULL) {
4768 		perror("gather_attrs calloc failed");
4769 		return (NULL);
4770 	}
4771 	for (iptr = item; iptr != NULL; iptr = iptr->next_item) {
4772 		if (iptr->group == group && iptr->mib_id == EXPER_XPORT_MLP) {
4773 			for (tme = iptr->valp;
4774 			    (char *)tme < (char *)iptr->valp + iptr->length;
4775 			    /* LINTED: (note 1) */
4776 			    tme = (mib2_transportMLPEntry_t *)((char *)tme +
4777 			    transportMLPSize)) {
4778 				attrs[tme->tme_connidx] = tme;
4779 			}
4780 		}
4781 	}
4782 	return (attrs);
4783 }
4784 
4785 static void
4786 print_transport_label(const mib2_transportMLPEntry_t *attr)
4787 {
4788 	if (!RSECflag || attr == NULL ||
4789 	    !(attr->tme_flags & MIB2_TMEF_IS_LABELED))
4790 		return;
4791 
4792 	if (bisinvalid(&attr->tme_label)) {
4793 		(void) printf("   INVALID\n");
4794 	} else if (!blequal(&attr->tme_label, zone_security_label)) {
4795 		char *sl_str;
4796 
4797 		sl_str = sl_to_str(&attr->tme_label);
4798 		(void) printf("   %s\n", sl_str);
4799 		free(sl_str);
4800 	}
4801 }
4802 
4803 /* ------------------------------ TCP_REPORT------------------------------- */
4804 
4805 static const char tcp_hdr_v4[] =
4806 "\nTCP: IPv4\n";
4807 static const char tcp_hdr_v4_compat[] =
4808 "\nTCP\n";
4809 static const char tcp_hdr_v4_verbose[] =
4810 "Local/Remote Address Swind  Snext     Suna   Rwind  Rnext     Rack   "
4811 " Rto   Mss     State\n"
4812 "-------------------- ----- -------- -------- ----- -------- -------- "
4813 "----- ----- -----------\n";
4814 static const char tcp_hdr_v4_normal[] =
4815 "   Local Address        Remote Address    Swind Send-Q Rwind Recv-Q "
4816 "   State\n"
4817 "-------------------- -------------------- ----- ------ ----- ------ "
4818 "-----------\n";
4819 
4820 static const char tcp_hdr_v6[] =
4821 "\nTCP: IPv6\n";
4822 static const char tcp_hdr_v6_verbose[] =
4823 "Local/Remote Address              Swind  Snext     Suna   Rwind  Rnext   "
4824 "  Rack    Rto   Mss    State      If\n"
4825 "--------------------------------- ----- -------- -------- ----- -------- "
4826 "-------- ----- ----- ----------- -----\n";
4827 static const char tcp_hdr_v6_normal[] =
4828 "   Local Address                     Remote Address                 "
4829 "Swind Send-Q Rwind Recv-Q   State      If\n"
4830 "--------------------------------- --------------------------------- "
4831 "----- ------ ----- ------ ----------- -----\n";
4832 
4833 static boolean_t tcp_report_item_v4(const mib2_tcpConnEntry_t *,
4834     boolean_t first, const mib2_transportMLPEntry_t *);
4835 static boolean_t tcp_report_item_v6(const mib2_tcp6ConnEntry_t *,
4836     boolean_t first, const mib2_transportMLPEntry_t *);
4837 
4838 static void
4839 tcp_report(const mib_item_t *item)
4840 {
4841 	int			jtemp = 0;
4842 	boolean_t		print_hdr_once_v4 = B_TRUE;
4843 	boolean_t		print_hdr_once_v6 = B_TRUE;
4844 	mib2_tcpConnEntry_t	*tp;
4845 	mib2_tcp6ConnEntry_t	*tp6;
4846 	mib2_transportMLPEntry_t **v4_attrs, **v6_attrs;
4847 	mib2_transportMLPEntry_t **v4a, **v6a;
4848 	mib2_transportMLPEntry_t *aptr;
4849 
4850 	if (!protocol_selected(IPPROTO_TCP))
4851 		return;
4852 
4853 	/*
4854 	 * Preparation pass: the kernel returns separate entries for TCP
4855 	 * connection table entries and Multilevel Port attributes.  We loop
4856 	 * through the attributes first and set up an array for each address
4857 	 * family.
4858 	 */
4859 	v4_attrs = family_selected(AF_INET) && RSECflag ?
4860 	    gather_attrs(item, MIB2_TCP, MIB2_TCP_CONN, tcpConnEntrySize) :
4861 	    NULL;
4862 	v6_attrs = family_selected(AF_INET6) && RSECflag ?
4863 	    gather_attrs(item, MIB2_TCP6, MIB2_TCP6_CONN, tcp6ConnEntrySize) :
4864 	    NULL;
4865 
4866 	/* 'for' loop 1: */
4867 	v4a = v4_attrs;
4868 	v6a = v6_attrs;
4869 	for (; item != NULL; item = item->next_item) {
4870 		if (Xflag) {
4871 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
4872 			(void) printf("Group = %d, mib_id = %d, "
4873 			    "length = %d, valp = 0x%p\n",
4874 			    item->group, item->mib_id,
4875 			    item->length, item->valp);
4876 		}
4877 
4878 		if (!((item->group == MIB2_TCP &&
4879 		    item->mib_id == MIB2_TCP_CONN) ||
4880 		    (item->group == MIB2_TCP6 &&
4881 		    item->mib_id == MIB2_TCP6_CONN)))
4882 			continue; /* 'for' loop 1 */
4883 
4884 		if (item->group == MIB2_TCP && !family_selected(AF_INET))
4885 			continue; /* 'for' loop 1 */
4886 		else if (item->group == MIB2_TCP6 && !family_selected(AF_INET6))
4887 			continue; /* 'for' loop 1 */
4888 
4889 		if (item->group == MIB2_TCP) {
4890 			for (tp = (mib2_tcpConnEntry_t *)item->valp;
4891 			    (char *)tp < (char *)item->valp + item->length;
4892 			    /* LINTED: (note 1) */
4893 			    tp = (mib2_tcpConnEntry_t *)((char *)tp +
4894 			    tcpConnEntrySize)) {
4895 				aptr = v4a == NULL ? NULL : *v4a++;
4896 				print_hdr_once_v4 = tcp_report_item_v4(tp,
4897 				    print_hdr_once_v4, aptr);
4898 			}
4899 		} else {
4900 			for (tp6 = (mib2_tcp6ConnEntry_t *)item->valp;
4901 			    (char *)tp6 < (char *)item->valp + item->length;
4902 			    /* LINTED: (note 1) */
4903 			    tp6 = (mib2_tcp6ConnEntry_t *)((char *)tp6 +
4904 			    tcp6ConnEntrySize)) {
4905 				aptr = v6a == NULL ? NULL : *v6a++;
4906 				print_hdr_once_v6 = tcp_report_item_v6(tp6,
4907 				    print_hdr_once_v6, aptr);
4908 			}
4909 		}
4910 	} /* 'for' loop 1 ends */
4911 	(void) fflush(stdout);
4912 
4913 	if (v4_attrs != NULL)
4914 		free(v4_attrs);
4915 	if (v6_attrs != NULL)
4916 		free(v6_attrs);
4917 }
4918 
4919 static boolean_t
4920 tcp_report_item_v4(const mib2_tcpConnEntry_t *tp, boolean_t first,
4921     const mib2_transportMLPEntry_t *attr)
4922 {
4923 	/*
4924 	 * lname and fname below are for the hostname as well as the portname
4925 	 * There is no limit on portname length so we assume MAXHOSTNAMELEN
4926 	 * as the limit
4927 	 */
4928 	char	lname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
4929 	char	fname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
4930 
4931 	if (!(Aflag || tp->tcpConnEntryInfo.ce_state >= TCPS_ESTABLISHED))
4932 		return (first); /* Nothing to print */
4933 
4934 	if (first) {
4935 		(void) printf(v4compat ? tcp_hdr_v4_compat : tcp_hdr_v4);
4936 		(void) printf(Vflag ? tcp_hdr_v4_verbose : tcp_hdr_v4_normal);
4937 	}
4938 
4939 	if (Vflag) {
4940 		(void) printf("%-20s\n%-20s %5u %08x %08x %5u %08x %08x "
4941 		    "%5u %5u %s\n",
4942 		    pr_ap(tp->tcpConnLocalAddress,
4943 		    tp->tcpConnLocalPort, "tcp", lname, sizeof (lname)),
4944 		    pr_ap(tp->tcpConnRemAddress,
4945 		    tp->tcpConnRemPort, "tcp", fname, sizeof (fname)),
4946 		    tp->tcpConnEntryInfo.ce_swnd,
4947 		    tp->tcpConnEntryInfo.ce_snxt,
4948 		    tp->tcpConnEntryInfo.ce_suna,
4949 		    tp->tcpConnEntryInfo.ce_rwnd,
4950 		    tp->tcpConnEntryInfo.ce_rnxt,
4951 		    tp->tcpConnEntryInfo.ce_rack,
4952 		    tp->tcpConnEntryInfo.ce_rto,
4953 		    tp->tcpConnEntryInfo.ce_mss,
4954 		    mitcp_state(tp->tcpConnEntryInfo.ce_state, attr));
4955 	} else {
4956 		int sq = (int)tp->tcpConnEntryInfo.ce_snxt -
4957 		    (int)tp->tcpConnEntryInfo.ce_suna - 1;
4958 		int rq = (int)tp->tcpConnEntryInfo.ce_rnxt -
4959 		    (int)tp->tcpConnEntryInfo.ce_rack;
4960 
4961 		(void) printf("%-20s %-20s %5u %6d %5u %6d %s\n",
4962 		    pr_ap(tp->tcpConnLocalAddress,
4963 		    tp->tcpConnLocalPort, "tcp", lname, sizeof (lname)),
4964 		    pr_ap(tp->tcpConnRemAddress,
4965 		    tp->tcpConnRemPort, "tcp", fname, sizeof (fname)),
4966 		    tp->tcpConnEntryInfo.ce_swnd,
4967 		    (sq >= 0) ? sq : 0,
4968 		    tp->tcpConnEntryInfo.ce_rwnd,
4969 		    (rq >= 0) ? rq : 0,
4970 		    mitcp_state(tp->tcpConnEntryInfo.ce_state, attr));
4971 	}
4972 
4973 	print_transport_label(attr);
4974 
4975 	return (B_FALSE);
4976 }
4977 
4978 static boolean_t
4979 tcp_report_item_v6(const mib2_tcp6ConnEntry_t *tp6, boolean_t first,
4980     const mib2_transportMLPEntry_t *attr)
4981 {
4982 	/*
4983 	 * lname and fname below are for the hostname as well as the portname
4984 	 * There is no limit on portname length so we assume MAXHOSTNAMELEN
4985 	 * as the limit
4986 	 */
4987 	char	lname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
4988 	char	fname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
4989 	char	ifname[LIFNAMSIZ + 1];
4990 	char	*ifnamep;
4991 
4992 	if (!(Aflag || tp6->tcp6ConnEntryInfo.ce_state >= TCPS_ESTABLISHED))
4993 		return (first); /* Nothing to print */
4994 
4995 	if (first) {
4996 		(void) printf(tcp_hdr_v6);
4997 		(void) printf(Vflag ? tcp_hdr_v6_verbose : tcp_hdr_v6_normal);
4998 	}
4999 
5000 	ifnamep = (tp6->tcp6ConnIfIndex != 0) ?
5001 	    if_indextoname(tp6->tcp6ConnIfIndex, ifname) : NULL;
5002 	if (ifnamep == NULL)
5003 		ifnamep = "";
5004 
5005 	if (Vflag) {
5006 		(void) printf("%-33s\n%-33s %5u %08x %08x %5u %08x %08x "
5007 		    "%5u %5u %-11s %s\n",
5008 		    pr_ap6(&tp6->tcp6ConnLocalAddress,
5009 		    tp6->tcp6ConnLocalPort, "tcp", lname, sizeof (lname)),
5010 		    pr_ap6(&tp6->tcp6ConnRemAddress,
5011 		    tp6->tcp6ConnRemPort, "tcp", fname, sizeof (fname)),
5012 		    tp6->tcp6ConnEntryInfo.ce_swnd,
5013 		    tp6->tcp6ConnEntryInfo.ce_snxt,
5014 		    tp6->tcp6ConnEntryInfo.ce_suna,
5015 		    tp6->tcp6ConnEntryInfo.ce_rwnd,
5016 		    tp6->tcp6ConnEntryInfo.ce_rnxt,
5017 		    tp6->tcp6ConnEntryInfo.ce_rack,
5018 		    tp6->tcp6ConnEntryInfo.ce_rto,
5019 		    tp6->tcp6ConnEntryInfo.ce_mss,
5020 		    mitcp_state(tp6->tcp6ConnEntryInfo.ce_state, attr),
5021 		    ifnamep);
5022 	} else {
5023 		int sq = (int)tp6->tcp6ConnEntryInfo.ce_snxt -
5024 		    (int)tp6->tcp6ConnEntryInfo.ce_suna - 1;
5025 		int rq = (int)tp6->tcp6ConnEntryInfo.ce_rnxt -
5026 		    (int)tp6->tcp6ConnEntryInfo.ce_rack;
5027 
5028 		(void) printf("%-33s %-33s %5u %6d %5u %6d %-11s %s\n",
5029 		    pr_ap6(&tp6->tcp6ConnLocalAddress,
5030 		    tp6->tcp6ConnLocalPort, "tcp", lname, sizeof (lname)),
5031 		    pr_ap6(&tp6->tcp6ConnRemAddress,
5032 		    tp6->tcp6ConnRemPort, "tcp", fname, sizeof (fname)),
5033 		    tp6->tcp6ConnEntryInfo.ce_swnd,
5034 		    (sq >= 0) ? sq : 0,
5035 		    tp6->tcp6ConnEntryInfo.ce_rwnd,
5036 		    (rq >= 0) ? rq : 0,
5037 		    mitcp_state(tp6->tcp6ConnEntryInfo.ce_state, attr),
5038 		    ifnamep);
5039 	}
5040 
5041 	print_transport_label(attr);
5042 
5043 	return (B_FALSE);
5044 }
5045 
5046 /* ------------------------------- UDP_REPORT------------------------------- */
5047 
5048 static boolean_t udp_report_item_v4(const mib2_udpEntry_t *ude,
5049     boolean_t first, const mib2_transportMLPEntry_t *attr);
5050 static boolean_t udp_report_item_v6(const mib2_udp6Entry_t *ude6,
5051     boolean_t first, const mib2_transportMLPEntry_t *attr);
5052 
5053 static const char udp_hdr_v4[] =
5054 "   Local Address        Remote Address      State\n"
5055 "-------------------- -------------------- ----------\n";
5056 
5057 static const char udp_hdr_v6[] =
5058 "   Local Address                     Remote Address                 "
5059 "  State      If\n"
5060 "--------------------------------- --------------------------------- "
5061 "---------- -----\n";
5062 
5063 static void
5064 udp_report(const mib_item_t *item)
5065 {
5066 	int			jtemp = 0;
5067 	boolean_t		print_hdr_once_v4 = B_TRUE;
5068 	boolean_t		print_hdr_once_v6 = B_TRUE;
5069 	mib2_udpEntry_t		*ude;
5070 	mib2_udp6Entry_t	*ude6;
5071 	mib2_transportMLPEntry_t **v4_attrs, **v6_attrs;
5072 	mib2_transportMLPEntry_t **v4a, **v6a;
5073 	mib2_transportMLPEntry_t *aptr;
5074 
5075 	if (!protocol_selected(IPPROTO_UDP))
5076 		return;
5077 
5078 	/*
5079 	 * Preparation pass: the kernel returns separate entries for UDP
5080 	 * connection table entries and Multilevel Port attributes.  We loop
5081 	 * through the attributes first and set up an array for each address
5082 	 * family.
5083 	 */
5084 	v4_attrs = family_selected(AF_INET) && RSECflag ?
5085 	    gather_attrs(item, MIB2_UDP, MIB2_UDP_ENTRY, udpEntrySize) : NULL;
5086 	v6_attrs = family_selected(AF_INET6) && RSECflag ?
5087 	    gather_attrs(item, MIB2_UDP6, MIB2_UDP6_ENTRY, udp6EntrySize) :
5088 	    NULL;
5089 
5090 	v4a = v4_attrs;
5091 	v6a = v6_attrs;
5092 	/* 'for' loop 1: */
5093 	for (; item; item = item->next_item) {
5094 		if (Xflag) {
5095 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
5096 			(void) printf("Group = %d, mib_id = %d, "
5097 			    "length = %d, valp = 0x%p\n",
5098 			    item->group, item->mib_id,
5099 			    item->length, item->valp);
5100 		}
5101 		if (!((item->group == MIB2_UDP &&
5102 		    item->mib_id == MIB2_UDP_ENTRY) ||
5103 		    (item->group == MIB2_UDP6 &&
5104 		    item->mib_id == MIB2_UDP6_ENTRY)))
5105 			continue; /* 'for' loop 1 */
5106 
5107 		if (item->group == MIB2_UDP && !family_selected(AF_INET))
5108 			continue; /* 'for' loop 1 */
5109 		else if (item->group == MIB2_UDP6 && !family_selected(AF_INET6))
5110 			continue; /* 'for' loop 1 */
5111 
5112 		/*	xxx.xxx.xxx.xxx,pppp  sss... */
5113 		if (item->group == MIB2_UDP) {
5114 			for (ude = (mib2_udpEntry_t *)item->valp;
5115 			    (char *)ude < (char *)item->valp + item->length;
5116 			    /* LINTED: (note 1) */
5117 			    ude = (mib2_udpEntry_t *)((char *)ude +
5118 			    udpEntrySize)) {
5119 				aptr = v4a == NULL ? NULL : *v4a++;
5120 				print_hdr_once_v4 = udp_report_item_v4(ude,
5121 				    print_hdr_once_v4, aptr);
5122 			}
5123 		} else {
5124 			for (ude6 = (mib2_udp6Entry_t *)item->valp;
5125 			    (char *)ude6 < (char *)item->valp + item->length;
5126 			    /* LINTED: (note 1) */
5127 			    ude6 = (mib2_udp6Entry_t *)((char *)ude6 +
5128 			    udp6EntrySize)) {
5129 				aptr = v6a == NULL ? NULL : *v6a++;
5130 				print_hdr_once_v6 = udp_report_item_v6(ude6,
5131 				    print_hdr_once_v6, aptr);
5132 			}
5133 		}
5134 	} /* 'for' loop 1 ends */
5135 	(void) fflush(stdout);
5136 
5137 	if (v4_attrs != NULL)
5138 		free(v4_attrs);
5139 	if (v6_attrs != NULL)
5140 		free(v6_attrs);
5141 }
5142 
5143 static boolean_t
5144 udp_report_item_v4(const mib2_udpEntry_t *ude, boolean_t first,
5145     const mib2_transportMLPEntry_t *attr)
5146 {
5147 	char	lname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
5148 			/* hostname + portname */
5149 
5150 	if (!(Aflag || ude->udpEntryInfo.ue_state >= MIB2_UDP_connected))
5151 		return (first); /* Nothing to print */
5152 
5153 	if (first) {
5154 		(void) printf(v4compat ? "\nUDP\n" : "\nUDP: IPv4\n");
5155 		(void) printf(udp_hdr_v4);
5156 		first = B_FALSE;
5157 	}
5158 
5159 	(void) printf("%-20s ",
5160 	    pr_ap(ude->udpLocalAddress, ude->udpLocalPort, "udp",
5161 	    lname, sizeof (lname)));
5162 	(void) printf("%-20s %s\n",
5163 	    ude->udpEntryInfo.ue_state == MIB2_UDP_connected ?
5164 	    pr_ap(ude->udpEntryInfo.ue_RemoteAddress,
5165 	    ude->udpEntryInfo.ue_RemotePort, "udp", lname, sizeof (lname)) :
5166 	    "",
5167 	    miudp_state(ude->udpEntryInfo.ue_state, attr));
5168 
5169 	print_transport_label(attr);
5170 
5171 	return (first);
5172 }
5173 
5174 static boolean_t
5175 udp_report_item_v6(const mib2_udp6Entry_t *ude6, boolean_t first,
5176     const mib2_transportMLPEntry_t *attr)
5177 {
5178 	char	lname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
5179 			/* hostname + portname */
5180 	char	ifname[LIFNAMSIZ + 1];
5181 	const char *ifnamep;
5182 
5183 	if (!(Aflag || ude6->udp6EntryInfo.ue_state >= MIB2_UDP_connected))
5184 		return (first); /* Nothing to print */
5185 
5186 	if (first) {
5187 		(void) printf("\nUDP: IPv6\n");
5188 		(void) printf(udp_hdr_v6);
5189 		first = B_FALSE;
5190 	}
5191 
5192 	ifnamep = (ude6->udp6IfIndex != 0) ?
5193 	    if_indextoname(ude6->udp6IfIndex, ifname) : NULL;
5194 
5195 	(void) printf("%-33s ",
5196 	    pr_ap6(&ude6->udp6LocalAddress,
5197 	    ude6->udp6LocalPort, "udp", lname, sizeof (lname)));
5198 	(void) printf("%-33s %-10s %s\n",
5199 	    ude6->udp6EntryInfo.ue_state == MIB2_UDP_connected ?
5200 	    pr_ap6(&ude6->udp6EntryInfo.ue_RemoteAddress,
5201 	    ude6->udp6EntryInfo.ue_RemotePort, "udp", lname, sizeof (lname)) :
5202 	    "",
5203 	    miudp_state(ude6->udp6EntryInfo.ue_state, attr),
5204 	    ifnamep == NULL ? "" : ifnamep);
5205 
5206 	print_transport_label(attr);
5207 
5208 	return (first);
5209 }
5210 
5211 /* ------------------------------ SCTP_REPORT------------------------------- */
5212 
5213 static const char sctp_hdr[] =
5214 "\nSCTP:";
5215 static const char sctp_hdr_normal[] =
5216 "        Local Address                   Remote Address          "
5217 "Swind  Send-Q Rwind  Recv-Q StrsI/O  State\n"
5218 "------------------------------- ------------------------------- "
5219 "------ ------ ------ ------ ------- -----------";
5220 
5221 static const char *
5222 nssctp_state(int state, const mib2_transportMLPEntry_t *attr)
5223 {
5224 	static char sctpsbuf[50];
5225 	const char *cp;
5226 
5227 	switch (state) {
5228 	case MIB2_SCTP_closed:
5229 		cp = "CLOSED";
5230 		break;
5231 	case MIB2_SCTP_cookieWait:
5232 		cp = "COOKIE_WAIT";
5233 		break;
5234 	case MIB2_SCTP_cookieEchoed:
5235 		cp = "COOKIE_ECHOED";
5236 		break;
5237 	case MIB2_SCTP_established:
5238 		cp = "ESTABLISHED";
5239 		break;
5240 	case MIB2_SCTP_shutdownPending:
5241 		cp = "SHUTDOWN_PENDING";
5242 		break;
5243 	case MIB2_SCTP_shutdownSent:
5244 		cp = "SHUTDOWN_SENT";
5245 		break;
5246 	case MIB2_SCTP_shutdownReceived:
5247 		cp = "SHUTDOWN_RECEIVED";
5248 		break;
5249 	case MIB2_SCTP_shutdownAckSent:
5250 		cp = "SHUTDOWN_ACK_SENT";
5251 		break;
5252 	case MIB2_SCTP_listen:
5253 		cp = "LISTEN";
5254 		break;
5255 	default:
5256 		(void) snprintf(sctpsbuf, sizeof (sctpsbuf),
5257 		    "UNKNOWN STATE(%d)", state);
5258 		cp = sctpsbuf;
5259 		break;
5260 	}
5261 
5262 	if (RSECflag && attr != NULL && attr->tme_flags != 0) {
5263 		if (cp != sctpsbuf) {
5264 			(void) strlcpy(sctpsbuf, cp, sizeof (sctpsbuf));
5265 			cp = sctpsbuf;
5266 		}
5267 		if (attr->tme_flags & MIB2_TMEF_PRIVATE)
5268 			(void) strlcat(sctpsbuf, " P", sizeof (sctpsbuf));
5269 		if (attr->tme_flags & MIB2_TMEF_SHARED)
5270 			(void) strlcat(sctpsbuf, " S", sizeof (sctpsbuf));
5271 	}
5272 
5273 	return (cp);
5274 }
5275 
5276 static const mib2_sctpConnRemoteEntry_t *
5277 sctp_getnext_rem(const mib_item_t **itemp,
5278     const mib2_sctpConnRemoteEntry_t *current, uint32_t associd)
5279 {
5280 	const mib_item_t *item = *itemp;
5281 	const mib2_sctpConnRemoteEntry_t	*sre;
5282 
5283 	for (; item != NULL; item = item->next_item, current = NULL) {
5284 		if (!(item->group == MIB2_SCTP &&
5285 		    item->mib_id == MIB2_SCTP_CONN_REMOTE)) {
5286 			continue;
5287 		}
5288 
5289 		if (current != NULL) {
5290 			/* LINTED: (note 1) */
5291 			sre = (const mib2_sctpConnRemoteEntry_t *)
5292 			    ((const char *)current + sctpRemoteEntrySize);
5293 		} else {
5294 			sre = item->valp;
5295 		}
5296 		for (; (char *)sre < (char *)item->valp + item->length;
5297 		    /* LINTED: (note 1) */
5298 		    sre = (const mib2_sctpConnRemoteEntry_t *)
5299 		    ((const char *)sre + sctpRemoteEntrySize)) {
5300 			if (sre->sctpAssocId != associd) {
5301 				continue;
5302 			}
5303 			*itemp = item;
5304 			return (sre);
5305 		}
5306 	}
5307 	*itemp = NULL;
5308 	return (NULL);
5309 }
5310 
5311 static const mib2_sctpConnLocalEntry_t *
5312 sctp_getnext_local(const mib_item_t **itemp,
5313     const mib2_sctpConnLocalEntry_t *current, uint32_t associd)
5314 {
5315 	const mib_item_t *item = *itemp;
5316 	const mib2_sctpConnLocalEntry_t	*sle;
5317 
5318 	for (; item != NULL; item = item->next_item, current = NULL) {
5319 		if (!(item->group == MIB2_SCTP &&
5320 		    item->mib_id == MIB2_SCTP_CONN_LOCAL)) {
5321 			continue;
5322 		}
5323 
5324 		if (current != NULL) {
5325 			/* LINTED: (note 1) */
5326 			sle = (const mib2_sctpConnLocalEntry_t *)
5327 			    ((const char *)current + sctpLocalEntrySize);
5328 		} else {
5329 			sle = item->valp;
5330 		}
5331 		for (; (char *)sle < (char *)item->valp + item->length;
5332 		    /* LINTED: (note 1) */
5333 		    sle = (const mib2_sctpConnLocalEntry_t *)
5334 		    ((const char *)sle + sctpLocalEntrySize)) {
5335 			if (sle->sctpAssocId != associd) {
5336 				continue;
5337 			}
5338 			*itemp = item;
5339 			return (sle);
5340 		}
5341 	}
5342 	*itemp = NULL;
5343 	return (NULL);
5344 }
5345 
5346 static void
5347 sctp_pr_addr(int type, char *name, int namelen, const in6_addr_t *addr,
5348     int port)
5349 {
5350 	ipaddr_t	v4addr;
5351 	in6_addr_t	v6addr;
5352 
5353 	/*
5354 	 * Address is either a v4 mapped or v6 addr. If
5355 	 * it's a v4 mapped, convert to v4 before
5356 	 * displaying.
5357 	 */
5358 	switch (type) {
5359 	case MIB2_SCTP_ADDR_V4:
5360 		/* v4 */
5361 		v6addr = *addr;
5362 
5363 		IN6_V4MAPPED_TO_IPADDR(&v6addr, v4addr);
5364 		if (port > 0) {
5365 			(void) pr_ap(v4addr, port, "sctp", name, namelen);
5366 		} else {
5367 			(void) pr_addr(v4addr, name, namelen);
5368 		}
5369 		break;
5370 
5371 	case MIB2_SCTP_ADDR_V6:
5372 		/* v6 */
5373 		if (port > 0) {
5374 			(void) pr_ap6(addr, port, "sctp", name, namelen);
5375 		} else {
5376 			(void) pr_addr6(addr, name, namelen);
5377 		}
5378 		break;
5379 
5380 	default:
5381 		(void) snprintf(name, namelen, "<unknown addr type>");
5382 		break;
5383 	}
5384 }
5385 
5386 static void
5387 sctp_conn_report_item(const mib_item_t *head, const mib2_sctpConnEntry_t *sp,
5388     const mib2_transportMLPEntry_t *attr)
5389 {
5390 	char		lname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
5391 	char		fname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
5392 	const mib2_sctpConnRemoteEntry_t	*sre = NULL;
5393 	const mib2_sctpConnLocalEntry_t	*sle = NULL;
5394 	const mib_item_t *local = head;
5395 	const mib_item_t *remote = head;
5396 	uint32_t	id = sp->sctpAssocId;
5397 	boolean_t	printfirst = B_TRUE;
5398 
5399 	sctp_pr_addr(sp->sctpAssocRemPrimAddrType, fname, sizeof (fname),
5400 	    &sp->sctpAssocRemPrimAddr, sp->sctpAssocRemPort);
5401 	sctp_pr_addr(sp->sctpAssocRemPrimAddrType, lname, sizeof (lname),
5402 	    &sp->sctpAssocLocPrimAddr, sp->sctpAssocLocalPort);
5403 
5404 	(void) printf("%-31s %-31s %6u %6d %6u %6d %3d/%-3d %s\n",
5405 	    lname, fname,
5406 	    sp->sctpConnEntryInfo.ce_swnd,
5407 	    sp->sctpConnEntryInfo.ce_sendq,
5408 	    sp->sctpConnEntryInfo.ce_rwnd,
5409 	    sp->sctpConnEntryInfo.ce_recvq,
5410 	    sp->sctpAssocInStreams, sp->sctpAssocOutStreams,
5411 	    nssctp_state(sp->sctpAssocState, attr));
5412 
5413 	print_transport_label(attr);
5414 
5415 	if (!Vflag) {
5416 		return;
5417 	}
5418 
5419 	/* Print remote addresses/local addresses on following lines */
5420 	while ((sre = sctp_getnext_rem(&remote, sre, id)) != NULL) {
5421 		if (!IN6_ARE_ADDR_EQUAL(&sre->sctpAssocRemAddr,
5422 		    &sp->sctpAssocRemPrimAddr)) {
5423 			if (printfirst == B_TRUE) {
5424 				(void) fputs("\t<Remote: ", stdout);
5425 				printfirst = B_FALSE;
5426 			} else {
5427 				(void) fputs(", ", stdout);
5428 			}
5429 			sctp_pr_addr(sre->sctpAssocRemAddrType, fname,
5430 			    sizeof (fname), &sre->sctpAssocRemAddr, -1);
5431 			if (sre->sctpAssocRemAddrActive == MIB2_SCTP_ACTIVE) {
5432 				(void) fputs(fname, stdout);
5433 			} else {
5434 				(void) printf("(%s)", fname);
5435 			}
5436 		}
5437 	}
5438 	if (printfirst == B_FALSE) {
5439 		(void) puts(">");
5440 		printfirst = B_TRUE;
5441 	}
5442 	while ((sle = sctp_getnext_local(&local, sle, id)) != NULL) {
5443 		if (!IN6_ARE_ADDR_EQUAL(&sle->sctpAssocLocalAddr,
5444 		    &sp->sctpAssocLocPrimAddr)) {
5445 			if (printfirst == B_TRUE) {
5446 				(void) fputs("\t<Local: ", stdout);
5447 				printfirst = B_FALSE;
5448 			} else {
5449 				(void) fputs(", ", stdout);
5450 			}
5451 			sctp_pr_addr(sle->sctpAssocLocalAddrType, lname,
5452 			    sizeof (lname), &sle->sctpAssocLocalAddr, -1);
5453 			(void) fputs(lname, stdout);
5454 		}
5455 	}
5456 	if (printfirst == B_FALSE) {
5457 		(void) puts(">");
5458 	}
5459 }
5460 
5461 static void
5462 sctp_report(const mib_item_t *item)
5463 {
5464 	const mib_item_t		*head;
5465 	const mib2_sctpConnEntry_t	*sp;
5466 	boolean_t		first = B_TRUE;
5467 	mib2_transportMLPEntry_t **attrs, **aptr;
5468 	mib2_transportMLPEntry_t *attr;
5469 
5470 	/*
5471 	 * Preparation pass: the kernel returns separate entries for SCTP
5472 	 * connection table entries and Multilevel Port attributes.  We loop
5473 	 * through the attributes first and set up an array for each address
5474 	 * family.
5475 	 */
5476 	attrs = RSECflag ?
5477 	    gather_attrs(item, MIB2_SCTP, MIB2_SCTP_CONN, sctpEntrySize) :
5478 	    NULL;
5479 
5480 	aptr = attrs;
5481 	head = item;
5482 	for (; item != NULL; item = item->next_item) {
5483 
5484 		if (!(item->group == MIB2_SCTP &&
5485 		    item->mib_id == MIB2_SCTP_CONN))
5486 			continue;
5487 
5488 		for (sp = item->valp;
5489 		    (char *)sp < (char *)item->valp + item->length;
5490 		    /* LINTED: (note 1) */
5491 		    sp = (mib2_sctpConnEntry_t *)((char *)sp + sctpEntrySize)) {
5492 			attr = aptr == NULL ? NULL : *aptr++;
5493 			if (Aflag ||
5494 			    sp->sctpAssocState >= MIB2_SCTP_established) {
5495 				if (first == B_TRUE) {
5496 					(void) puts(sctp_hdr);
5497 					(void) puts(sctp_hdr_normal);
5498 					first = B_FALSE;
5499 				}
5500 				sctp_conn_report_item(head, sp, attr);
5501 			}
5502 		}
5503 	}
5504 	if (attrs != NULL)
5505 		free(attrs);
5506 }
5507 
5508 static char *
5509 plural(int n)
5510 {
5511 	return (n != 1 ? "s" : "");
5512 }
5513 
5514 static char *
5515 pluraly(int n)
5516 {
5517 	return (n != 1 ? "ies" : "y");
5518 }
5519 
5520 static char *
5521 plurales(int n)
5522 {
5523 	return (n != 1 ? "es" : "");
5524 }
5525 
5526 static char *
5527 pktscale(int n)
5528 {
5529 	static char buf[6];
5530 	char t;
5531 
5532 	if (n < 1024) {
5533 		t = ' ';
5534 	} else if (n < 1024 * 1024) {
5535 		t = 'k';
5536 		n /= 1024;
5537 	} else if (n < 1024 * 1024 * 1024) {
5538 		t = 'm';
5539 		n /= 1024 * 1024;
5540 	} else {
5541 		t = 'g';
5542 		n /= 1024 * 1024 * 1024;
5543 	}
5544 
5545 	(void) snprintf(buf, sizeof (buf), "%4u%c", n, t);
5546 	return (buf);
5547 }
5548 
5549 /* --------------------- mrt_report (netstat -m) -------------------------- */
5550 
5551 static void
5552 mrt_report(mib_item_t *item)
5553 {
5554 	int		jtemp = 0;
5555 	struct vifctl	*vip;
5556 	vifi_t		vifi;
5557 	struct mfcctl	*mfccp;
5558 	int		numvifs = 0;
5559 	int		nmfc = 0;
5560 	char		abuf[MAXHOSTNAMELEN + 1];
5561 
5562 	if (!(family_selected(AF_INET)))
5563 		return;
5564 
5565 	/* 'for' loop 1: */
5566 	for (; item; item = item->next_item) {
5567 		if (Xflag) {
5568 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
5569 			(void) printf("Group = %d, mib_id = %d, "
5570 			    "length = %d, valp = 0x%p\n",
5571 			    item->group, item->mib_id, item->length,
5572 			    item->valp);
5573 		}
5574 		if (item->group != EXPER_DVMRP)
5575 			continue; /* 'for' loop 1 */
5576 
5577 		switch (item->mib_id) {
5578 
5579 		case EXPER_DVMRP_VIF:
5580 			if (Xflag)
5581 				(void) printf("%u records for ipVifTable:\n",
5582 				    item->length/sizeof (struct vifctl));
5583 			if (item->length/sizeof (struct vifctl) == 0) {
5584 				(void) puts("\nVirtual Interface Table is "
5585 				    "empty");
5586 				break;
5587 			}
5588 
5589 			(void) puts("\nVirtual Interface Table\n"
5590 			    " Vif Threshold Rate_Limit Local-Address"
5591 			    "   Remote-Address     Pkt_in   Pkt_out");
5592 
5593 			/* 'for' loop 2: */
5594 			for (vip = (struct vifctl *)item->valp;
5595 			    (char *)vip < (char *)item->valp + item->length;
5596 			    /* LINTED: (note 1) */
5597 			    vip = (struct vifctl *)((char *)vip +
5598 			    vifctlSize)) {
5599 				if (vip->vifc_lcl_addr.s_addr == 0)
5600 					continue; /* 'for' loop 2 */
5601 				/* numvifs = vip->vifc_vifi; */
5602 
5603 				numvifs++;
5604 				(void) printf("  %2u       %3u       "
5605 				    "%4u %-15.15s",
5606 				    vip->vifc_vifi,
5607 				    vip->vifc_threshold,
5608 				    vip->vifc_rate_limit,
5609 				    pr_addr(vip->vifc_lcl_addr.s_addr,
5610 				    abuf, sizeof (abuf)));
5611 				(void) printf(" %-15.15s  %8u  %8u\n",
5612 				    (vip->vifc_flags & VIFF_TUNNEL) ?
5613 				    pr_addr(vip->vifc_rmt_addr.s_addr,
5614 				    abuf, sizeof (abuf)) : "",
5615 				    vip->vifc_pkt_in,
5616 				    vip->vifc_pkt_out);
5617 			} /* 'for' loop 2 ends */
5618 
5619 			(void) printf("Numvifs: %d\n", numvifs);
5620 			break;
5621 
5622 		case EXPER_DVMRP_MRT:
5623 			if (Xflag)
5624 				(void) printf("%u records for ipMfcTable:\n",
5625 				    item->length/sizeof (struct vifctl));
5626 			if (item->length/sizeof (struct vifctl) == 0) {
5627 				(void) puts("\nMulticast Forwarding Cache is "
5628 				    "empty");
5629 				break;
5630 			}
5631 
5632 			(void) puts("\nMulticast Forwarding Cache\n"
5633 			    "  Origin-Subnet                 Mcastgroup      "
5634 			    "# Pkts  In-Vif  Out-vifs/Forw-ttl");
5635 
5636 			for (mfccp = (struct mfcctl *)item->valp;
5637 			    (char *)mfccp < (char *)item->valp + item->length;
5638 			    /* LINTED: (note 1) */
5639 			    mfccp = (struct mfcctl *)((char *)mfccp +
5640 			    mfcctlSize)) {
5641 
5642 				nmfc++;
5643 				(void) printf("  %-30.15s",
5644 				    pr_addr(mfccp->mfcc_origin.s_addr,
5645 				    abuf, sizeof (abuf)));
5646 				(void) printf("%-15.15s  %6s  %3u    ",
5647 				    pr_net(mfccp->mfcc_mcastgrp.s_addr,
5648 				    mfccp->mfcc_mcastgrp.s_addr,
5649 				    abuf, sizeof (abuf)),
5650 				    pktscale((int)mfccp->mfcc_pkt_cnt),
5651 				    mfccp->mfcc_parent);
5652 
5653 				for (vifi = 0; vifi < MAXVIFS; ++vifi) {
5654 					if (mfccp->mfcc_ttls[vifi]) {
5655 						(void) printf("      %u (%u)",
5656 						    vifi,
5657 						    mfccp->mfcc_ttls[vifi]);
5658 					}
5659 
5660 				}
5661 				(void) putchar('\n');
5662 			}
5663 			(void) printf("\nTotal no. of entries in cache: %d\n",
5664 			    nmfc);
5665 			break;
5666 		}
5667 	} /* 'for' loop 1 ends */
5668 	(void) putchar('\n');
5669 	(void) fflush(stdout);
5670 }
5671 
5672 /*
5673  * Get the stats for the cache named 'name'.  If prefix != 0, then
5674  * interpret the name as a prefix, and sum up stats for all caches
5675  * named 'name*'.
5676  */
5677 static void
5678 kmem_cache_stats(char *title, char *name, int prefix, int64_t *total_bytes)
5679 {
5680 	int len;
5681 	int alloc;
5682 	int64_t total_alloc = 0;
5683 	int alloc_fail, total_alloc_fail = 0;
5684 	int buf_size = 0;
5685 	int buf_avail;
5686 	int buf_total;
5687 	int buf_max, total_buf_max = 0;
5688 	int buf_inuse, total_buf_inuse = 0;
5689 	kstat_t *ksp;
5690 	char buf[256];
5691 
5692 	len = prefix ? strlen(name) : 256;
5693 
5694 	/* 'for' loop 1: */
5695 	for (ksp = kc->kc_chain; ksp != NULL; ksp = ksp->ks_next) {
5696 
5697 		if (strcmp(ksp->ks_class, "kmem_cache") != 0)
5698 			continue; /* 'for' loop 1 */
5699 
5700 		/*
5701 		 * Hack alert: because of the way streams messages are
5702 		 * allocated, every constructed free dblk has an associated
5703 		 * mblk.  From the allocator's viewpoint those mblks are
5704 		 * allocated (because they haven't been freed), but from
5705 		 * our viewpoint they're actually free (because they're
5706 		 * not currently in use).  To account for this caching
5707 		 * effect we subtract the total constructed free dblks
5708 		 * from the total allocated mblks to derive mblks in use.
5709 		 */
5710 		if (strcmp(name, "streams_mblk") == 0 &&
5711 		    strncmp(ksp->ks_name, "streams_dblk", 12) == 0) {
5712 			(void) safe_kstat_read(kc, ksp, NULL);
5713 			total_buf_inuse -=
5714 			    kstat_named_value(ksp, "buf_constructed");
5715 			continue; /* 'for' loop 1 */
5716 		}
5717 
5718 		if (strncmp(ksp->ks_name, name, len) != 0)
5719 			continue; /* 'for' loop 1 */
5720 
5721 		(void) safe_kstat_read(kc, ksp, NULL);
5722 
5723 		alloc		= kstat_named_value(ksp, "alloc");
5724 		alloc_fail	= kstat_named_value(ksp, "alloc_fail");
5725 		buf_size	= kstat_named_value(ksp, "buf_size");
5726 		buf_avail	= kstat_named_value(ksp, "buf_avail");
5727 		buf_total	= kstat_named_value(ksp, "buf_total");
5728 		buf_max		= kstat_named_value(ksp, "buf_max");
5729 		buf_inuse	= buf_total - buf_avail;
5730 
5731 		if (Vflag && prefix) {
5732 			(void) snprintf(buf, sizeof (buf), "%s%s", title,
5733 			    ksp->ks_name + len);
5734 			(void) printf("    %-18s %6u %9u %11u %11u\n",
5735 			    buf, buf_inuse, buf_max, alloc, alloc_fail);
5736 		}
5737 
5738 		total_alloc		+= alloc;
5739 		total_alloc_fail	+= alloc_fail;
5740 		total_buf_max		+= buf_max;
5741 		total_buf_inuse		+= buf_inuse;
5742 		*total_bytes		+= (int64_t)buf_inuse * buf_size;
5743 	} /* 'for' loop 1 ends */
5744 
5745 	if (buf_size == 0) {
5746 		(void) printf("%-22s [couldn't find statistics for %s]\n",
5747 		    title, name);
5748 		return;
5749 	}
5750 
5751 	if (Vflag && prefix)
5752 		(void) snprintf(buf, sizeof (buf), "%s_total", title);
5753 	else
5754 		(void) snprintf(buf, sizeof (buf), "%s", title);
5755 
5756 	(void) printf("%-22s %6d %9d %11lld %11d\n", buf,
5757 	    total_buf_inuse, total_buf_max, total_alloc, total_alloc_fail);
5758 }
5759 
5760 static void
5761 m_report(void)
5762 {
5763 	int64_t total_bytes = 0;
5764 
5765 	(void) puts("streams allocation:");
5766 	(void) printf("%63s\n", "cumulative  allocation");
5767 	(void) printf("%63s\n",
5768 	    "current   maximum       total    failures");
5769 
5770 	kmem_cache_stats("streams",
5771 	    "stream_head_cache", 0, &total_bytes);
5772 	kmem_cache_stats("queues", "queue_cache", 0, &total_bytes);
5773 	kmem_cache_stats("mblk", "streams_mblk", 0, &total_bytes);
5774 	kmem_cache_stats("dblk", "streams_dblk", 1, &total_bytes);
5775 	kmem_cache_stats("linkblk", "linkinfo_cache", 0, &total_bytes);
5776 	kmem_cache_stats("syncq", "syncq_cache", 0, &total_bytes);
5777 	kmem_cache_stats("qband", "qband_cache", 0, &total_bytes);
5778 
5779 	(void) printf("\n%lld Kbytes allocated for streams data\n",
5780 	    total_bytes / 1024);
5781 
5782 	(void) putchar('\n');
5783 	(void) fflush(stdout);
5784 }
5785 
5786 /* --------------------------------- */
5787 
5788 /*
5789  * Print an IPv4 address. Remove the matching part of the domain name
5790  * from the returned name.
5791  */
5792 static char *
5793 pr_addr(uint_t addr, char *dst, uint_t dstlen)
5794 {
5795 	char			*cp;
5796 	struct hostent		*hp = NULL;
5797 	static char		domain[MAXHOSTNAMELEN + 1];
5798 	static boolean_t	first = B_TRUE;
5799 	int			error_num;
5800 
5801 	if (first) {
5802 		first = B_FALSE;
5803 		if (sysinfo(SI_HOSTNAME, domain, MAXHOSTNAMELEN) != -1 &&
5804 		    (cp = strchr(domain, '.'))) {
5805 			(void) strncpy(domain, cp + 1, sizeof (domain));
5806 		} else
5807 			domain[0] = 0;
5808 	}
5809 	cp = NULL;
5810 	if (!Nflag) {
5811 		ns_lookup_start();
5812 		hp = getipnodebyaddr((char *)&addr, sizeof (uint_t), AF_INET,
5813 		    &error_num);
5814 		ns_lookup_end();
5815 		if (hp) {
5816 			if ((cp = strchr(hp->h_name, '.')) != NULL &&
5817 			    strcasecmp(cp + 1, domain) == 0)
5818 				*cp = 0;
5819 			cp = hp->h_name;
5820 		}
5821 	}
5822 	if (cp != NULL) {
5823 		(void) strncpy(dst, cp, dstlen);
5824 		dst[dstlen - 1] = 0;
5825 	} else {
5826 		(void) inet_ntop(AF_INET, (char *)&addr, dst, dstlen);
5827 	}
5828 	if (hp != NULL)
5829 		freehostent(hp);
5830 	return (dst);
5831 }
5832 
5833 /*
5834  * Print a non-zero IPv4 address.  Print "    --" if the address is zero.
5835  */
5836 static char *
5837 pr_addrnz(ipaddr_t addr, char *dst, uint_t dstlen)
5838 {
5839 	if (addr == INADDR_ANY) {
5840 		(void) strlcpy(dst, "    --", dstlen);
5841 		return (dst);
5842 	}
5843 	return (pr_addr(addr, dst, dstlen));
5844 }
5845 
5846 /*
5847  * Print an IPv6 address. Remove the matching part of the domain name
5848  * from the returned name.
5849  */
5850 static char *
5851 pr_addr6(const struct in6_addr *addr, char *dst, uint_t dstlen)
5852 {
5853 	char			*cp;
5854 	struct hostent		*hp = NULL;
5855 	static char		domain[MAXHOSTNAMELEN + 1];
5856 	static boolean_t	first = B_TRUE;
5857 	int			error_num;
5858 
5859 	if (first) {
5860 		first = B_FALSE;
5861 		if (sysinfo(SI_HOSTNAME, domain, MAXHOSTNAMELEN) != -1 &&
5862 		    (cp = strchr(domain, '.'))) {
5863 			(void) strncpy(domain, cp + 1, sizeof (domain));
5864 		} else
5865 			domain[0] = 0;
5866 	}
5867 	cp = NULL;
5868 	if (!Nflag) {
5869 		ns_lookup_start();
5870 		hp = getipnodebyaddr((char *)addr,
5871 		    sizeof (struct in6_addr), AF_INET6, &error_num);
5872 		ns_lookup_end();
5873 		if (hp) {
5874 			if ((cp = strchr(hp->h_name, '.')) != NULL &&
5875 			    strcasecmp(cp + 1, domain) == 0)
5876 				*cp = 0;
5877 			cp = hp->h_name;
5878 		}
5879 	}
5880 	if (cp != NULL) {
5881 		(void) strncpy(dst, cp, dstlen);
5882 		dst[dstlen - 1] = 0;
5883 	} else {
5884 		(void) inet_ntop(AF_INET6, (void *)addr, dst, dstlen);
5885 	}
5886 	if (hp != NULL)
5887 		freehostent(hp);
5888 	return (dst);
5889 }
5890 
5891 /* For IPv4 masks */
5892 static char *
5893 pr_mask(uint_t addr, char *dst, uint_t dstlen)
5894 {
5895 	uint8_t	*ip_addr = (uint8_t *)&addr;
5896 
5897 	(void) snprintf(dst, dstlen, "%d.%d.%d.%d",
5898 	    ip_addr[0], ip_addr[1], ip_addr[2], ip_addr[3]);
5899 	return (dst);
5900 }
5901 
5902 /*
5903  * For ipv6 masks format is : dest/mask
5904  * Does not print /128 to save space in printout. H flag carries this notion.
5905  */
5906 static char *
5907 pr_prefix6(const struct in6_addr *addr, uint_t prefixlen, char *dst,
5908     uint_t dstlen)
5909 {
5910 	char *cp;
5911 
5912 	if (IN6_IS_ADDR_UNSPECIFIED(addr) && prefixlen == 0) {
5913 		(void) strncpy(dst, "default", dstlen);
5914 		dst[dstlen - 1] = 0;
5915 		return (dst);
5916 	}
5917 
5918 	(void) pr_addr6(addr, dst, dstlen);
5919 	if (prefixlen != IPV6_ABITS) {
5920 		/* How much room is left? */
5921 		cp = strchr(dst, '\0');
5922 		if (dst + dstlen > cp) {
5923 			dstlen -= (cp - dst);
5924 			(void) snprintf(cp, dstlen, "/%d", prefixlen);
5925 		}
5926 	}
5927 	return (dst);
5928 }
5929 
5930 /* Print IPv4 address and port */
5931 static char *
5932 pr_ap(uint_t addr, uint_t port, char *proto,
5933     char *dst, uint_t dstlen)
5934 {
5935 	char *cp;
5936 
5937 	if (addr == INADDR_ANY) {
5938 		(void) strncpy(dst, "      *", dstlen);
5939 		dst[dstlen - 1] = 0;
5940 	} else {
5941 		(void) pr_addr(addr, dst, dstlen);
5942 	}
5943 	/* How much room is left? */
5944 	cp = strchr(dst, '\0');
5945 	if (dst + dstlen > cp + 1) {
5946 		*cp++ = '.';
5947 		dstlen -= (cp - dst);
5948 		dstlen--;
5949 		(void) portname(port, proto, cp, dstlen);
5950 	}
5951 	return (dst);
5952 }
5953 
5954 /* Print IPv6 address and port */
5955 static char *
5956 pr_ap6(const in6_addr_t *addr, uint_t port, char *proto,
5957     char *dst, uint_t dstlen)
5958 {
5959 	char *cp;
5960 
5961 	if (IN6_IS_ADDR_UNSPECIFIED(addr)) {
5962 		(void) strncpy(dst, "      *", dstlen);
5963 		dst[dstlen - 1] = 0;
5964 	} else {
5965 		(void) pr_addr6(addr, dst, dstlen);
5966 	}
5967 	/* How much room is left? */
5968 	cp = strchr(dst, '\0');
5969 	if (dst + dstlen + 1 > cp) {
5970 		*cp++ = '.';
5971 		dstlen -= (cp - dst);
5972 		dstlen--;
5973 		(void) portname(port, proto, cp, dstlen);
5974 	}
5975 	return (dst);
5976 }
5977 
5978 /*
5979  * Return the name of the network whose address is given. The address is
5980  * assumed to be that of a net or subnet, not a host.
5981  */
5982 static char *
5983 pr_net(uint_t addr, uint_t mask, char *dst, uint_t dstlen)
5984 {
5985 	char		*cp = NULL;
5986 	struct netent	*np = NULL;
5987 	struct hostent	*hp = NULL;
5988 	uint_t		net;
5989 	int		subnetshift;
5990 	int		error_num;
5991 
5992 	if (addr == INADDR_ANY && mask == INADDR_ANY) {
5993 		(void) strncpy(dst, "default", dstlen);
5994 		dst[dstlen - 1] = 0;
5995 		return (dst);
5996 	}
5997 
5998 	if (!Nflag && addr) {
5999 		if (mask == 0) {
6000 			if (IN_CLASSA(addr)) {
6001 				mask = (uint_t)IN_CLASSA_NET;
6002 				subnetshift = 8;
6003 			} else if (IN_CLASSB(addr)) {
6004 				mask = (uint_t)IN_CLASSB_NET;
6005 				subnetshift = 8;
6006 			} else {
6007 				mask = (uint_t)IN_CLASSC_NET;
6008 				subnetshift = 4;
6009 			}
6010 			/*
6011 			 * If there are more bits than the standard mask
6012 			 * would suggest, subnets must be in use. Guess at
6013 			 * the subnet mask, assuming reasonable width subnet
6014 			 * fields.
6015 			 */
6016 			while (addr & ~mask)
6017 				/* compiler doesn't sign extend! */
6018 				mask = (mask | ((int)mask >> subnetshift));
6019 		}
6020 		net = addr & mask;
6021 		while ((mask & 1) == 0)
6022 			mask >>= 1, net >>= 1;
6023 		ns_lookup_start();
6024 		np = getnetbyaddr(net, AF_INET);
6025 		ns_lookup_end();
6026 		if (np && np->n_net == net)
6027 			cp = np->n_name;
6028 		else {
6029 			/*
6030 			 * Look for subnets in hosts map.
6031 			 */
6032 			ns_lookup_start();
6033 			hp = getipnodebyaddr((char *)&addr, sizeof (uint_t),
6034 			    AF_INET, &error_num);
6035 			ns_lookup_end();
6036 			if (hp)
6037 				cp = hp->h_name;
6038 		}
6039 	}
6040 	if (cp != NULL) {
6041 		(void) strncpy(dst, cp, dstlen);
6042 		dst[dstlen - 1] = 0;
6043 	} else {
6044 		(void) inet_ntop(AF_INET, (char *)&addr, dst, dstlen);
6045 	}
6046 	if (hp != NULL)
6047 		freehostent(hp);
6048 	return (dst);
6049 }
6050 
6051 /*
6052  * Return the name of the network whose address is given.
6053  * The address is assumed to be a host address.
6054  */
6055 static char *
6056 pr_netaddr(uint_t addr, uint_t mask, char *dst, uint_t dstlen)
6057 {
6058 	char		*cp = NULL;
6059 	struct netent	*np = NULL;
6060 	struct hostent	*hp = NULL;
6061 	uint_t		net;
6062 	uint_t		netshifted;
6063 	int		subnetshift;
6064 	struct in_addr in;
6065 	int		error_num;
6066 	uint_t		nbo_addr = addr;	/* network byte order */
6067 
6068 	addr = ntohl(addr);
6069 	mask = ntohl(mask);
6070 	if (addr == INADDR_ANY && mask == INADDR_ANY) {
6071 		(void) strncpy(dst, "default", dstlen);
6072 		dst[dstlen - 1] = 0;
6073 		return (dst);
6074 	}
6075 
6076 	/* Figure out network portion of address (with host portion = 0) */
6077 	if (addr) {
6078 		/* Try figuring out mask if unknown (all 0s). */
6079 		if (mask == 0) {
6080 			if (IN_CLASSA(addr)) {
6081 				mask = (uint_t)IN_CLASSA_NET;
6082 				subnetshift = 8;
6083 			} else if (IN_CLASSB(addr)) {
6084 				mask = (uint_t)IN_CLASSB_NET;
6085 				subnetshift = 8;
6086 			} else {
6087 				mask = (uint_t)IN_CLASSC_NET;
6088 				subnetshift = 4;
6089 			}
6090 			/*
6091 			 * If there are more bits than the standard mask
6092 			 * would suggest, subnets must be in use. Guess at
6093 			 * the subnet mask, assuming reasonable width subnet
6094 			 * fields.
6095 			 */
6096 			while (addr & ~mask)
6097 				/* compiler doesn't sign extend! */
6098 				mask = (mask | ((int)mask >> subnetshift));
6099 		}
6100 		net = netshifted = addr & mask;
6101 		while ((mask & 1) == 0)
6102 			mask >>= 1, netshifted >>= 1;
6103 	}
6104 	else
6105 		net = netshifted = 0;
6106 
6107 	/* Try looking up name unless -n was specified. */
6108 	if (!Nflag) {
6109 		ns_lookup_start();
6110 		np = getnetbyaddr(netshifted, AF_INET);
6111 		ns_lookup_end();
6112 		if (np && np->n_net == netshifted)
6113 			cp = np->n_name;
6114 		else {
6115 			/*
6116 			 * Look for subnets in hosts map.
6117 			 */
6118 			ns_lookup_start();
6119 			hp = getipnodebyaddr((char *)&nbo_addr, sizeof (uint_t),
6120 			    AF_INET, &error_num);
6121 			ns_lookup_end();
6122 			if (hp)
6123 				cp = hp->h_name;
6124 		}
6125 
6126 		if (cp != NULL) {
6127 			(void) strncpy(dst, cp, dstlen);
6128 			dst[dstlen - 1] = 0;
6129 			if (hp != NULL)
6130 				freehostent(hp);
6131 			return (dst);
6132 		}
6133 		/*
6134 		 * No name found for net: fallthru and return in decimal
6135 		 * dot notation.
6136 		 */
6137 	}
6138 
6139 	in.s_addr = htonl(net);
6140 	(void) inet_ntop(AF_INET, (char *)&in, dst, dstlen);
6141 	if (hp != NULL)
6142 		freehostent(hp);
6143 	return (dst);
6144 }
6145 
6146 /*
6147  * Return the filter mode as a string:
6148  *	1 => "INCLUDE"
6149  *	2 => "EXCLUDE"
6150  *	otherwise "<unknown>"
6151  */
6152 static char *
6153 fmodestr(uint_t fmode)
6154 {
6155 	switch (fmode) {
6156 	case 1:
6157 		return ("INCLUDE");
6158 	case 2:
6159 		return ("EXCLUDE");
6160 	default:
6161 		return ("<unknown>");
6162 	}
6163 }
6164 
6165 #define	MAX_STRING_SIZE	256
6166 
6167 static const char *
6168 pr_secattr(const sec_attr_list_t *attrs)
6169 {
6170 	int i;
6171 	char buf[MAX_STRING_SIZE + 1], *cp;
6172 	static char *sbuf;
6173 	static size_t sbuf_len;
6174 	struct rtsa_s rtsa;
6175 	const sec_attr_list_t *aptr;
6176 
6177 	if (!RSECflag || attrs == NULL)
6178 		return ("");
6179 
6180 	for (aptr = attrs, i = 1; aptr != NULL; aptr = aptr->sal_next)
6181 		i += MAX_STRING_SIZE;
6182 	if (i > sbuf_len) {
6183 		cp = realloc(sbuf, i);
6184 		if (cp == NULL) {
6185 			perror("realloc security attribute buffer");
6186 			return ("");
6187 		}
6188 		sbuf_len = i;
6189 		sbuf = cp;
6190 	}
6191 
6192 	cp = sbuf;
6193 	while (attrs != NULL) {
6194 		const mib2_ipAttributeEntry_t *iae = attrs->sal_attr;
6195 
6196 		/* note: effectively hard-coded in rtsa_keyword */
6197 		rtsa.rtsa_mask = RTSA_CIPSO | RTSA_SLRANGE | RTSA_DOI;
6198 		rtsa.rtsa_slrange = iae->iae_slrange;
6199 		rtsa.rtsa_doi = iae->iae_doi;
6200 
6201 		(void) snprintf(cp, MAX_STRING_SIZE,
6202 		    "<%s>%s ", rtsa_to_str(&rtsa, buf, sizeof (buf)),
6203 		    attrs->sal_next == NULL ? "" : ",");
6204 		cp += strlen(cp);
6205 		attrs = attrs->sal_next;
6206 	}
6207 	*cp = '\0';
6208 
6209 	return (sbuf);
6210 }
6211 
6212 /*
6213  * Pretty print a port number. If the Nflag was
6214  * specified, use numbers instead of names.
6215  */
6216 static char *
6217 portname(uint_t port, char *proto, char *dst, uint_t dstlen)
6218 {
6219 	struct servent *sp = NULL;
6220 
6221 	if (!Nflag && port) {
6222 		ns_lookup_start();
6223 		sp = getservbyport(htons(port), proto);
6224 		ns_lookup_end();
6225 	}
6226 	if (sp || port == 0)
6227 		(void) snprintf(dst, dstlen, "%.*s", MAXHOSTNAMELEN,
6228 		    sp ? sp->s_name : "*");
6229 	else
6230 		(void) snprintf(dst, dstlen, "%d", port);
6231 	dst[dstlen - 1] = 0;
6232 	return (dst);
6233 }
6234 
6235 /*PRINTFLIKE2*/
6236 void
6237 fail(int do_perror, char *message, ...)
6238 {
6239 	va_list args;
6240 
6241 	va_start(args, message);
6242 	(void) fputs("netstat: ", stderr);
6243 	(void) vfprintf(stderr, message, args);
6244 	va_end(args);
6245 	if (do_perror)
6246 		(void) fprintf(stderr, ": %s", strerror(errno));
6247 	(void) fputc('\n', stderr);
6248 	exit(2);
6249 }
6250 
6251 /*
6252  * Return value of named statistic for given kstat_named kstat;
6253  * return 0LL if named statistic is not in list (use "ll" as a
6254  * type qualifier when printing 64-bit int's with printf() )
6255  */
6256 static uint64_t
6257 kstat_named_value(kstat_t *ksp, char *name)
6258 {
6259 	kstat_named_t *knp;
6260 	uint64_t value;
6261 
6262 	if (ksp == NULL)
6263 		return (0LL);
6264 
6265 	knp = kstat_data_lookup(ksp, name);
6266 	if (knp == NULL)
6267 		return (0LL);
6268 
6269 	switch (knp->data_type) {
6270 	case KSTAT_DATA_INT32:
6271 	case KSTAT_DATA_UINT32:
6272 		value = (uint64_t)(knp->value.ui32);
6273 		break;
6274 	case KSTAT_DATA_INT64:
6275 	case KSTAT_DATA_UINT64:
6276 		value = knp->value.ui64;
6277 		break;
6278 	default:
6279 		value = 0LL;
6280 		break;
6281 	}
6282 
6283 	return (value);
6284 }
6285 
6286 kid_t
6287 safe_kstat_read(kstat_ctl_t *kc, kstat_t *ksp, void *data)
6288 {
6289 	kid_t kstat_chain_id = kstat_read(kc, ksp, data);
6290 
6291 	if (kstat_chain_id == -1)
6292 		fail(1, "kstat_read(%p, '%s') failed", (void *)kc,
6293 		    ksp->ks_name);
6294 	return (kstat_chain_id);
6295 }
6296 
6297 /*
6298  * Parse a list of IRE flag characters into a bit field.
6299  */
6300 static uint_t
6301 flag_bits(const char *arg)
6302 {
6303 	const char *cp;
6304 	uint_t val;
6305 
6306 	if (*arg == '\0')
6307 		fatal(1, "missing flag list\n");
6308 
6309 	val = 0;
6310 	while (*arg != '\0') {
6311 		if ((cp = strchr(flag_list, *arg)) == NULL)
6312 			fatal(1, "%c: illegal flag\n", *arg);
6313 		val |= 1 << (cp - flag_list);
6314 		arg++;
6315 	}
6316 	return (val);
6317 }
6318 
6319 /*
6320  * Handle -f argument.  Validate input format, sort by keyword, and
6321  * save off digested results.
6322  */
6323 static void
6324 process_filter(char *arg)
6325 {
6326 	int idx;
6327 	int klen = 0;
6328 	char *cp, *cp2;
6329 	int val;
6330 	filter_t *newf;
6331 	struct hostent *hp;
6332 	int error_num;
6333 	uint8_t *ucp;
6334 	int maxv;
6335 
6336 	/* Look up the keyword first */
6337 	if (strchr(arg, ':') == NULL) {
6338 		idx = FK_AF;
6339 	} else {
6340 		for (idx = 0; idx < NFILTERKEYS; idx++) {
6341 			klen = strlen(filter_keys[idx]);
6342 			if (strncmp(filter_keys[idx], arg, klen) == 0 &&
6343 			    arg[klen] == ':')
6344 				break;
6345 		}
6346 		if (idx >= NFILTERKEYS)
6347 			fatal(1, "%s: unknown filter keyword\n", arg);
6348 
6349 		/* Advance past keyword and separator. */
6350 		arg += klen + 1;
6351 	}
6352 
6353 	if ((newf = malloc(sizeof (*newf))) == NULL) {
6354 		perror("filter");
6355 		exit(1);
6356 	}
6357 	switch (idx) {
6358 	case FK_AF:
6359 		if (strcmp(arg, "inet") == 0) {
6360 			newf->u.f_family = AF_INET;
6361 		} else if (strcmp(arg, "inet6") == 0) {
6362 			newf->u.f_family = AF_INET6;
6363 		} else if (strcmp(arg, "unix") == 0) {
6364 			newf->u.f_family = AF_UNIX;
6365 		} else {
6366 			newf->u.f_family = strtol(arg, &cp, 0);
6367 			if (arg == cp || *cp != '\0')
6368 				fatal(1, "%s: unknown address family.\n", arg);
6369 		}
6370 		break;
6371 
6372 	case FK_OUTIF:
6373 		if (strcmp(arg, "none") == 0) {
6374 			newf->u.f_ifname = NULL;
6375 			break;
6376 		}
6377 		if (strcmp(arg, "any") == 0) {
6378 			newf->u.f_ifname = "";
6379 			break;
6380 		}
6381 		val = strtol(arg, &cp, 0);
6382 		if (val <= 0 || arg == cp || cp[0] != '\0') {
6383 			if ((val = if_nametoindex(arg)) == 0) {
6384 				perror(arg);
6385 				exit(1);
6386 			}
6387 		}
6388 		newf->u.f_ifname = arg;
6389 		break;
6390 
6391 	case FK_DST:
6392 		V4MASK_TO_V6(IP_HOST_MASK, newf->u.a.f_mask);
6393 		if (strcmp(arg, "any") == 0) {
6394 			/* Special semantics; any address *but* zero */
6395 			newf->u.a.f_address = NULL;
6396 			(void) memset(&newf->u.a.f_mask, 0,
6397 			    sizeof (newf->u.a.f_mask));
6398 			break;
6399 		}
6400 		if (strcmp(arg, "none") == 0) {
6401 			newf->u.a.f_address = NULL;
6402 			break;
6403 		}
6404 		if ((cp = strrchr(arg, '/')) != NULL)
6405 			*cp++ = '\0';
6406 		hp = getipnodebyname(arg, AF_INET6, AI_V4MAPPED|AI_ALL,
6407 		    &error_num);
6408 		if (hp == NULL)
6409 			fatal(1, "%s: invalid or unknown host address\n", arg);
6410 		newf->u.a.f_address = hp;
6411 		if (cp == NULL) {
6412 			V4MASK_TO_V6(IP_HOST_MASK, newf->u.a.f_mask);
6413 		} else {
6414 			val = strtol(cp, &cp2, 0);
6415 			if (cp != cp2 && cp2[0] == '\0') {
6416 				/*
6417 				 * If decode as "/n" works, then translate
6418 				 * into a mask.
6419 				 */
6420 				if (hp->h_addr_list[0] != NULL &&
6421 				    /* LINTED: (note 1) */
6422 				    IN6_IS_ADDR_V4MAPPED((in6_addr_t *)
6423 				    hp->h_addr_list[0])) {
6424 					maxv = IP_ABITS;
6425 				} else {
6426 					maxv = IPV6_ABITS;
6427 				}
6428 				if (val < 0 || val >= maxv)
6429 					fatal(1, "%d: not in range 0 to %d\n",
6430 					    val, maxv - 1);
6431 				if (maxv == IP_ABITS)
6432 					val += IPV6_ABITS - IP_ABITS;
6433 				ucp = newf->u.a.f_mask.s6_addr;
6434 				while (val >= 8)
6435 					*ucp++ = 0xff, val -= 8;
6436 				*ucp++ = (0xff << (8 - val)) & 0xff;
6437 				while (ucp < newf->u.a.f_mask.s6_addr +
6438 				    sizeof (newf->u.a.f_mask.s6_addr))
6439 					*ucp++ = 0;
6440 				/* Otherwise, try as numeric address */
6441 			} else if (inet_pton(AF_INET6,
6442 			    cp, &newf->u.a.f_mask) <= 0) {
6443 				fatal(1, "%s: illegal mask format\n", cp);
6444 			}
6445 		}
6446 		break;
6447 
6448 	case FK_FLAGS:
6449 		if (*arg == '+') {
6450 			newf->u.f.f_flagset = flag_bits(arg + 1);
6451 			newf->u.f.f_flagclear = 0;
6452 		} else if (*arg == '-') {
6453 			newf->u.f.f_flagset = 0;
6454 			newf->u.f.f_flagclear = flag_bits(arg + 1);
6455 		} else {
6456 			newf->u.f.f_flagset = flag_bits(arg);
6457 			newf->u.f.f_flagclear = ~newf->u.f.f_flagset;
6458 		}
6459 		break;
6460 
6461 	default:
6462 		assert(0);
6463 	}
6464 	newf->f_next = filters[idx];
6465 	filters[idx] = newf;
6466 }
6467 
6468 /* Determine if user wants this address family printed. */
6469 static boolean_t
6470 family_selected(int family)
6471 {
6472 	const filter_t *fp;
6473 
6474 	if (v4compat && family == AF_INET6)
6475 		return (B_FALSE);
6476 	if ((fp = filters[FK_AF]) == NULL)
6477 		return (B_TRUE);
6478 	while (fp != NULL) {
6479 		if (fp->u.f_family == family)
6480 			return (B_TRUE);
6481 		fp = fp->f_next;
6482 	}
6483 	return (B_FALSE);
6484 }
6485 
6486 /*
6487  * Convert the interface index to a string using the buffer `ifname', which
6488  * must be at least LIFNAMSIZ bytes.  We first try to map it to name.  If that
6489  * fails (e.g., because we're inside a zone and it does not have access to
6490  * interface for the index in question), just return "if#<num>".
6491  */
6492 static char *
6493 ifindex2str(uint_t ifindex, char *ifname)
6494 {
6495 	if (if_indextoname(ifindex, ifname) == NULL)
6496 		(void) snprintf(ifname, LIFNAMSIZ, "if#%d", ifindex);
6497 
6498 	return (ifname);
6499 }
6500 
6501 /*
6502  * print the usage line
6503  */
6504 static void
6505 usage(char *cmdname)
6506 {
6507 	(void) fprintf(stderr, "usage: %s [-anv] [-f address_family] "
6508 	    "[-T d|u]\n", cmdname);
6509 	(void) fprintf(stderr, "       %s [-n] [-f address_family] "
6510 	    "[-P protocol] [-T d|u] [-g | -p | -s [interval [count]]]\n",
6511 	    cmdname);
6512 	(void) fprintf(stderr, "       %s -m [-v] [-T d|u] "
6513 	    "[interval [count]]\n", cmdname);
6514 	(void) fprintf(stderr, "       %s -i [-I interface] [-an] "
6515 	    "[-f address_family] [-T d|u] [interval [count]]\n", cmdname);
6516 	(void) fprintf(stderr, "       %s -r [-anv] "
6517 	    "[-f address_family|filter] [-T d|u]\n", cmdname);
6518 	(void) fprintf(stderr, "       %s -M [-ns] [-f address_family] "
6519 	    "[-T d|u]\n", cmdname);
6520 	(void) fprintf(stderr, "       %s -D [-I interface] "
6521 	    "[-f address_family] [-T d|u]\n", cmdname);
6522 	exit(EXIT_FAILURE);
6523 }
6524 
6525 /*
6526  * fatal: print error message to stderr and
6527  * call exit(errcode)
6528  */
6529 /*PRINTFLIKE2*/
6530 static void
6531 fatal(int errcode, char *format, ...)
6532 {
6533 	va_list argp;
6534 
6535 	if (format == NULL)
6536 		return;
6537 
6538 	va_start(argp, format);
6539 	(void) vfprintf(stderr, format, argp);
6540 	va_end(argp);
6541 
6542 	exit(errcode);
6543 }
6544