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