xref: /titanic_50/usr/src/cmd/cmd-inet/usr.bin/netstat/netstat.c (revision 540db9a98e48e044a5fb290242f3ebb8cc3afc36)
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 for a given address
3391  * family (af).  For each, print out the DHCP status using dhcp_do_ipc.
3392  */
3393 static boolean_t
3394 dhcp_walk_interfaces(int af, boolean_t printed_one)
3395 {
3396 	struct lifnum	lifn;
3397 	struct lifconf	lifc;
3398 	int		n_ifs, i, sock_fd;
3399 
3400 	sock_fd = socket(af, SOCK_DGRAM, 0);
3401 	if (sock_fd == -1)
3402 		return (printed_one);
3403 
3404 	/*
3405 	 * SIOCGLIFNUM is just an estimate.  If the ioctl fails, we don't care;
3406 	 * just drive on and use SIOCGLIFCONF with increasing buffer sizes, as
3407 	 * is traditional.
3408 	 */
3409 	(void) memset(&lifn, 0, sizeof (lifn));
3410 	lifn.lifn_family = af;
3411 	lifn.lifn_flags = LIFC_ALLZONES | LIFC_NOXMIT | LIFC_UNDER_IPMP;
3412 	if (ioctl(sock_fd, SIOCGLIFNUM, &lifn) == -1)
3413 		n_ifs = LIFN_GUARD_VALUE;
3414 	else
3415 		n_ifs = lifn.lifn_count + LIFN_GUARD_VALUE;
3416 
3417 	(void) memset(&lifc, 0, sizeof (lifc));
3418 	lifc.lifc_family = af;
3419 	lifc.lifc_flags = lifn.lifn_flags;
3420 	lifc.lifc_len = n_ifs * sizeof (struct lifreq);
3421 	lifc.lifc_buf = malloc(lifc.lifc_len);
3422 	if (lifc.lifc_buf != NULL) {
3423 
3424 		if (ioctl(sock_fd, SIOCGLIFCONF, &lifc) == -1) {
3425 			(void) close(sock_fd);
3426 			free(lifc.lifc_buf);
3427 			return (NULL);
3428 		}
3429 
3430 		n_ifs = lifc.lifc_len / sizeof (struct lifreq);
3431 
3432 		for (i = 0; i < n_ifs; i++) {
3433 			printed_one = dhcp_do_ipc(DHCP_STATUS |
3434 			    (af == AF_INET6 ? DHCP_V6 : 0),
3435 			    lifc.lifc_req[i].lifr_name, printed_one);
3436 		}
3437 	}
3438 	(void) close(sock_fd);
3439 	free(lifc.lifc_buf);
3440 	return (printed_one);
3441 }
3442 
3443 static void
3444 dhcp_report(char *ifname)
3445 {
3446 	boolean_t printed_one;
3447 
3448 	if (!family_selected(AF_INET) && !family_selected(AF_INET6))
3449 		return;
3450 
3451 	printed_one = B_FALSE;
3452 	if (ifname != NULL) {
3453 		if (family_selected(AF_INET)) {
3454 			printed_one = dhcp_do_ipc(DHCP_STATUS, ifname,
3455 			    printed_one);
3456 		}
3457 		if (family_selected(AF_INET6)) {
3458 			printed_one = dhcp_do_ipc(DHCP_STATUS | DHCP_V6,
3459 			    ifname, printed_one);
3460 		}
3461 		if (!printed_one) {
3462 			fail(0, "%s: %s", ifname,
3463 			    dhcp_ipc_strerror(DHCP_IPC_E_UNKIF));
3464 		}
3465 	} else {
3466 		if (family_selected(AF_INET)) {
3467 			printed_one = dhcp_walk_interfaces(AF_INET,
3468 			    printed_one);
3469 		}
3470 		if (family_selected(AF_INET6))
3471 			(void) dhcp_walk_interfaces(AF_INET6, printed_one);
3472 	}
3473 }
3474 
3475 /* --------------------- GROUP_REPORT (netstat -g) ------------------------- */
3476 
3477 static void
3478 group_report(mib_item_t *item)
3479 {
3480 	mib_item_t	*v4grp = NULL, *v4src = NULL;
3481 	mib_item_t	*v6grp = NULL, *v6src = NULL;
3482 	int		jtemp = 0;
3483 	char		ifname[LIFNAMSIZ + 1];
3484 	char		abuf[MAXHOSTNAMELEN + 1];
3485 	ip_member_t	*ipmp;
3486 	ip_grpsrc_t	*ips;
3487 	ipv6_member_t	*ipmp6;
3488 	ipv6_grpsrc_t	*ips6;
3489 	boolean_t	first, first_src;
3490 
3491 	/* 'for' loop 1: */
3492 	for (; item; item = item->next_item) {
3493 		if (Dflag) {
3494 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
3495 			(void) printf("Group = %d, mib_id = %d, "
3496 			    "length = %d, valp = 0x%p\n",
3497 			    item->group, item->mib_id, item->length,
3498 			    item->valp);
3499 		}
3500 		if (item->group == MIB2_IP && family_selected(AF_INET)) {
3501 			switch (item->mib_id) {
3502 			case EXPER_IP_GROUP_MEMBERSHIP:
3503 				v4grp = item;
3504 				if (Dflag)
3505 					(void) printf("item is v4grp info\n");
3506 				break;
3507 			case EXPER_IP_GROUP_SOURCES:
3508 				v4src = item;
3509 				if (Dflag)
3510 					(void) printf("item is v4src info\n");
3511 				break;
3512 			default:
3513 				continue;
3514 			}
3515 			continue;
3516 		}
3517 		if (item->group == MIB2_IP6 && family_selected(AF_INET6)) {
3518 			switch (item->mib_id) {
3519 			case EXPER_IP6_GROUP_MEMBERSHIP:
3520 				v6grp = item;
3521 				if (Dflag)
3522 					(void) printf("item is v6grp info\n");
3523 				break;
3524 			case EXPER_IP6_GROUP_SOURCES:
3525 				v6src = item;
3526 				if (Dflag)
3527 					(void) printf("item is v6src info\n");
3528 				break;
3529 			default:
3530 				continue;
3531 			}
3532 		}
3533 	}
3534 
3535 	if (family_selected(AF_INET) && v4grp != NULL) {
3536 		if (Dflag)
3537 			(void) printf("%u records for ipGroupMember:\n",
3538 			    v4grp->length / sizeof (ip_member_t));
3539 
3540 		first = B_TRUE;
3541 		for (ipmp = (ip_member_t *)v4grp->valp;
3542 		    (char *)ipmp < (char *)v4grp->valp + v4grp->length;
3543 		    /* LINTED: (note 1) */
3544 		    ipmp = (ip_member_t *)((char *)ipmp + ipMemberEntrySize)) {
3545 			if (first) {
3546 				(void) puts(v4compat ?
3547 				    "Group Memberships" :
3548 				    "Group Memberships: IPv4");
3549 				(void) puts("Interface "
3550 				    "Group                RefCnt");
3551 				(void) puts("--------- "
3552 				    "-------------------- ------");
3553 				first = B_FALSE;
3554 			}
3555 
3556 			(void) printf("%-9s %-20s %6u\n",
3557 			    octetstr(&ipmp->ipGroupMemberIfIndex, 'a',
3558 			    ifname, sizeof (ifname)),
3559 			    pr_addr(ipmp->ipGroupMemberAddress,
3560 			    abuf, sizeof (abuf)),
3561 			    ipmp->ipGroupMemberRefCnt);
3562 
3563 
3564 			if (!Vflag || v4src == NULL)
3565 				continue;
3566 
3567 			if (Dflag)
3568 				(void) printf("scanning %u ipGroupSource "
3569 				    "records...\n",
3570 				    v4src->length/sizeof (ip_grpsrc_t));
3571 
3572 			first_src = B_TRUE;
3573 			for (ips = (ip_grpsrc_t *)v4src->valp;
3574 			    (char *)ips < (char *)v4src->valp + v4src->length;
3575 			    /* LINTED: (note 1) */
3576 			    ips = (ip_grpsrc_t *)((char *)ips +
3577 			    ipGroupSourceEntrySize)) {
3578 				/*
3579 				 * We assume that all source addrs for a given
3580 				 * interface/group pair are contiguous, so on
3581 				 * the first non-match after we've found at
3582 				 * least one, we bail.
3583 				 */
3584 				if ((ipmp->ipGroupMemberAddress !=
3585 				    ips->ipGroupSourceGroup) ||
3586 				    (!octetstrmatch(&ipmp->ipGroupMemberIfIndex,
3587 				    &ips->ipGroupSourceIfIndex))) {
3588 					if (first_src)
3589 						continue;
3590 					else
3591 						break;
3592 				}
3593 				if (first_src) {
3594 					(void) printf("\t%s:    %s\n",
3595 					    fmodestr(
3596 					    ipmp->ipGroupMemberFilterMode),
3597 					    pr_addr(ips->ipGroupSourceAddress,
3598 					    abuf, sizeof (abuf)));
3599 					first_src = B_FALSE;
3600 					continue;
3601 				}
3602 
3603 				(void) printf("\t            %s\n",
3604 				    pr_addr(ips->ipGroupSourceAddress, abuf,
3605 				    sizeof (abuf)));
3606 			}
3607 		}
3608 		(void) putchar('\n');
3609 	}
3610 
3611 	if (family_selected(AF_INET6) && v6grp != NULL) {
3612 		if (Dflag)
3613 			(void) printf("%u records for ipv6GroupMember:\n",
3614 			    v6grp->length / sizeof (ipv6_member_t));
3615 
3616 		first = B_TRUE;
3617 		for (ipmp6 = (ipv6_member_t *)v6grp->valp;
3618 		    (char *)ipmp6 < (char *)v6grp->valp + v6grp->length;
3619 		    /* LINTED: (note 1) */
3620 		    ipmp6 = (ipv6_member_t *)((char *)ipmp6 +
3621 		    ipv6MemberEntrySize)) {
3622 			if (first) {
3623 				(void) puts("Group Memberships: "
3624 				    "IPv6");
3625 				(void) puts(" If       "
3626 				    "Group                   RefCnt");
3627 				(void) puts("----- "
3628 				    "--------------------------- ------");
3629 				first = B_FALSE;
3630 			}
3631 
3632 			(void) printf("%-5s %-27s %5u\n",
3633 			    ifindex2str(ipmp6->ipv6GroupMemberIfIndex, ifname),
3634 			    pr_addr6(&ipmp6->ipv6GroupMemberAddress,
3635 			    abuf, sizeof (abuf)),
3636 			    ipmp6->ipv6GroupMemberRefCnt);
3637 
3638 			if (!Vflag || v6src == NULL)
3639 				continue;
3640 
3641 			if (Dflag)
3642 				(void) printf("scanning %u ipv6GroupSource "
3643 				    "records...\n",
3644 				    v6src->length/sizeof (ipv6_grpsrc_t));
3645 
3646 			first_src = B_TRUE;
3647 			for (ips6 = (ipv6_grpsrc_t *)v6src->valp;
3648 			    (char *)ips6 < (char *)v6src->valp + v6src->length;
3649 			    /* LINTED: (note 1) */
3650 			    ips6 = (ipv6_grpsrc_t *)((char *)ips6 +
3651 			    ipv6GroupSourceEntrySize)) {
3652 				/* same assumption as in the v4 case above */
3653 				if ((ipmp6->ipv6GroupMemberIfIndex !=
3654 				    ips6->ipv6GroupSourceIfIndex) ||
3655 				    (!IN6_ARE_ADDR_EQUAL(
3656 				    &ipmp6->ipv6GroupMemberAddress,
3657 				    &ips6->ipv6GroupSourceGroup))) {
3658 					if (first_src)
3659 						continue;
3660 					else
3661 						break;
3662 				}
3663 				if (first_src) {
3664 					(void) printf("\t%s:    %s\n",
3665 					    fmodestr(
3666 					    ipmp6->ipv6GroupMemberFilterMode),
3667 					    pr_addr6(
3668 					    &ips6->ipv6GroupSourceAddress,
3669 					    abuf, sizeof (abuf)));
3670 					first_src = B_FALSE;
3671 					continue;
3672 				}
3673 
3674 				(void) printf("\t            %s\n",
3675 				    pr_addr6(&ips6->ipv6GroupSourceAddress,
3676 				    abuf, sizeof (abuf)));
3677 			}
3678 		}
3679 		(void) putchar('\n');
3680 	}
3681 
3682 	(void) putchar('\n');
3683 	(void) fflush(stdout);
3684 }
3685 
3686 /* --------------------- ARP_REPORT (netstat -p) -------------------------- */
3687 
3688 static void
3689 arp_report(mib_item_t *item)
3690 {
3691 	int		jtemp = 0;
3692 	char		ifname[LIFNAMSIZ + 1];
3693 	char		abuf[MAXHOSTNAMELEN + 1];
3694 	char		maskbuf[STR_EXPAND * OCTET_LENGTH + 1];
3695 	char		flbuf[32];	/* ACE_F_ flags */
3696 	char		xbuf[STR_EXPAND * OCTET_LENGTH + 1];
3697 	mib2_ipNetToMediaEntry_t	*np;
3698 	int		flags;
3699 	boolean_t	first;
3700 
3701 	if (!(family_selected(AF_INET)))
3702 		return;
3703 
3704 	/* 'for' loop 1: */
3705 	for (; item; item = item->next_item) {
3706 		if (Dflag) {
3707 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
3708 			(void) printf("Group = %d, mib_id = %d, "
3709 			    "length = %d, valp = 0x%p\n",
3710 			    item->group, item->mib_id, item->length,
3711 			    item->valp);
3712 		}
3713 		if (!(item->group == MIB2_IP && item->mib_id == MIB2_IP_MEDIA))
3714 			continue; /* 'for' loop 1 */
3715 
3716 		if (Dflag)
3717 			(void) printf("%u records for "
3718 			    "ipNetToMediaEntryTable:\n",
3719 			    item->length/sizeof (mib2_ipNetToMediaEntry_t));
3720 
3721 		first = B_TRUE;
3722 		/* 'for' loop 2: */
3723 		for (np = (mib2_ipNetToMediaEntry_t *)item->valp;
3724 		    (char *)np < (char *)item->valp + item->length;
3725 		    /* LINTED: (note 1) */
3726 		    np = (mib2_ipNetToMediaEntry_t *)((char *)np +
3727 		    ipNetToMediaEntrySize)) {
3728 			if (first) {
3729 				(void) puts(v4compat ?
3730 				    "Net to Media Table" :
3731 				    "Net to Media Table: IPv4");
3732 				(void) puts("Device "
3733 				    "  IP Address               Mask      "
3734 				    "Flags      Phys Addr");
3735 				(void) puts("------ "
3736 				    "-------------------- --------------- "
3737 				    "-------- ---------------");
3738 				first = B_FALSE;
3739 			}
3740 
3741 			flbuf[0] = '\0';
3742 			flags = np->ipNetToMediaInfo.ntm_flags;
3743 			/*
3744 			 * Note that not all flags are possible at the same
3745 			 * time.  Patterns: SPLAy DUo
3746 			 */
3747 			if (flags & ACE_F_PERMANENT)
3748 				(void) strcat(flbuf, "S");
3749 			if (flags & ACE_F_PUBLISH)
3750 				(void) strcat(flbuf, "P");
3751 			if (flags & ACE_F_DYING)
3752 				(void) strcat(flbuf, "D");
3753 			if (!(flags & ACE_F_RESOLVED))
3754 				(void) strcat(flbuf, "U");
3755 			if (flags & ACE_F_MAPPING)
3756 				(void) strcat(flbuf, "M");
3757 			if (flags & ACE_F_MYADDR)
3758 				(void) strcat(flbuf, "L");
3759 			if (flags & ACE_F_UNVERIFIED)
3760 				(void) strcat(flbuf, "d");
3761 			if (flags & ACE_F_AUTHORITY)
3762 				(void) strcat(flbuf, "A");
3763 			if (flags & ACE_F_OLD)
3764 				(void) strcat(flbuf, "o");
3765 			if (flags & ACE_F_DELAYED)
3766 				(void) strcat(flbuf, "y");
3767 			(void) printf("%-6s %-20s %-15s %-8s %s\n",
3768 			    octetstr(&np->ipNetToMediaIfIndex, 'a',
3769 			    ifname, sizeof (ifname)),
3770 			    pr_addr(np->ipNetToMediaNetAddress,
3771 			    abuf, sizeof (abuf)),
3772 			    octetstr(&np->ipNetToMediaInfo.ntm_mask, 'd',
3773 			    maskbuf, sizeof (maskbuf)),
3774 			    flbuf,
3775 			    octetstr(&np->ipNetToMediaPhysAddress, 'h',
3776 			    xbuf, sizeof (xbuf)));
3777 		} /* 'for' loop 2 ends */
3778 	} /* 'for' loop 1 ends */
3779 	(void) fflush(stdout);
3780 }
3781 
3782 /* --------------------- NDP_REPORT (netstat -p) -------------------------- */
3783 
3784 static void
3785 ndp_report(mib_item_t *item)
3786 {
3787 	int		jtemp = 0;
3788 	char		abuf[MAXHOSTNAMELEN + 1];
3789 	char		*state;
3790 	char		*type;
3791 	char		xbuf[STR_EXPAND * OCTET_LENGTH + 1];
3792 	mib2_ipv6NetToMediaEntry_t	*np6;
3793 	char		ifname[LIFNAMSIZ + 1];
3794 	boolean_t	first;
3795 
3796 	if (!(family_selected(AF_INET6)))
3797 		return;
3798 
3799 	/* 'for' loop 1: */
3800 	for (; item; item = item->next_item) {
3801 		if (Dflag) {
3802 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
3803 			(void) printf("Group = %d, mib_id = %d, "
3804 			    "length = %d, valp = 0x%p\n",
3805 			    item->group, item->mib_id, item->length,
3806 			    item->valp);
3807 		}
3808 		if (!(item->group == MIB2_IP6 &&
3809 		    item->mib_id == MIB2_IP6_MEDIA))
3810 			continue; /* 'for' loop 1 */
3811 
3812 		first = B_TRUE;
3813 		/* 'for' loop 2: */
3814 		for (np6 = (mib2_ipv6NetToMediaEntry_t *)item->valp;
3815 		    (char *)np6 < (char *)item->valp + item->length;
3816 		    /* LINTED: (note 1) */
3817 		    np6 = (mib2_ipv6NetToMediaEntry_t *)((char *)np6 +
3818 		    ipv6NetToMediaEntrySize)) {
3819 			if (first) {
3820 				(void) puts("\nNet to Media Table: IPv6");
3821 				(void) puts(" If   Physical Address   "
3822 				    " Type      State      Destination/Mask");
3823 				(void) puts("----- -----------------  "
3824 				    "------- ------------ "
3825 				    "---------------------------");
3826 				first = B_FALSE;
3827 			}
3828 
3829 			switch (np6->ipv6NetToMediaState) {
3830 			case ND_INCOMPLETE:
3831 				state = "INCOMPLETE";
3832 				break;
3833 			case ND_REACHABLE:
3834 				state = "REACHABLE";
3835 				break;
3836 			case ND_STALE:
3837 				state = "STALE";
3838 				break;
3839 			case ND_DELAY:
3840 				state = "DELAY";
3841 				break;
3842 			case ND_PROBE:
3843 				state = "PROBE";
3844 				break;
3845 			case ND_UNREACHABLE:
3846 				state = "UNREACHABLE";
3847 				break;
3848 			default:
3849 				state = "UNKNOWN";
3850 			}
3851 
3852 			switch (np6->ipv6NetToMediaType) {
3853 			case 1:
3854 				type = "other";
3855 				break;
3856 			case 2:
3857 				type = "dynamic";
3858 				break;
3859 			case 3:
3860 				type = "static";
3861 				break;
3862 			case 4:
3863 				type = "local";
3864 				break;
3865 			}
3866 			(void) printf("%-5s %-17s  %-7s %-12s %-27s\n",
3867 			    ifindex2str(np6->ipv6NetToMediaIfIndex, ifname),
3868 			    octetstr(&np6->ipv6NetToMediaPhysAddress, 'h',
3869 			    xbuf, sizeof (xbuf)),
3870 			    type,
3871 			    state,
3872 			    pr_addr6(&np6->ipv6NetToMediaNetAddress,
3873 			    abuf, sizeof (abuf)));
3874 		} /* 'for' loop 2 ends */
3875 	} /* 'for' loop 1 ends */
3876 	(void) putchar('\n');
3877 	(void) fflush(stdout);
3878 }
3879 
3880 /* ------------------------- ire_report (netstat -r) ------------------------ */
3881 
3882 typedef struct sec_attr_list_s {
3883 	struct sec_attr_list_s *sal_next;
3884 	const mib2_ipAttributeEntry_t *sal_attr;
3885 } sec_attr_list_t;
3886 
3887 static boolean_t ire_report_item_v4(const mib2_ipRouteEntry_t *, boolean_t,
3888     const sec_attr_list_t *);
3889 static boolean_t ire_report_item_v6(const mib2_ipv6RouteEntry_t *, boolean_t,
3890     const sec_attr_list_t *);
3891 static const char *pr_secattr(const sec_attr_list_t *);
3892 
3893 static void
3894 ire_report(const mib_item_t *item)
3895 {
3896 	int			jtemp = 0;
3897 	boolean_t		print_hdr_once_v4 = B_TRUE;
3898 	boolean_t		print_hdr_once_v6 = B_TRUE;
3899 	mib2_ipRouteEntry_t	*rp;
3900 	mib2_ipv6RouteEntry_t	*rp6;
3901 	sec_attr_list_t		**v4_attrs, **v4a;
3902 	sec_attr_list_t		**v6_attrs, **v6a;
3903 	sec_attr_list_t		*all_attrs, *aptr;
3904 	const mib_item_t	*iptr;
3905 	int			ipv4_route_count, ipv6_route_count;
3906 	int			route_attrs_count;
3907 
3908 	/*
3909 	 * Preparation pass: the kernel returns separate entries for IP routing
3910 	 * table entries and security attributes.  We loop through the
3911 	 * attributes first and link them into lists.
3912 	 */
3913 	ipv4_route_count = ipv6_route_count = route_attrs_count = 0;
3914 	for (iptr = item; iptr != NULL; iptr = iptr->next_item) {
3915 		if (iptr->group == MIB2_IP6 && iptr->mib_id == MIB2_IP6_ROUTE)
3916 			ipv6_route_count += iptr->length / ipv6RouteEntrySize;
3917 		if (iptr->group == MIB2_IP && iptr->mib_id == MIB2_IP_ROUTE)
3918 			ipv4_route_count += iptr->length / ipRouteEntrySize;
3919 		if ((iptr->group == MIB2_IP || iptr->group == MIB2_IP6) &&
3920 		    iptr->mib_id == EXPER_IP_RTATTR)
3921 			route_attrs_count += iptr->length /
3922 			    ipRouteAttributeSize;
3923 	}
3924 	v4_attrs = v6_attrs = NULL;
3925 	all_attrs = NULL;
3926 	if (family_selected(AF_INET) && ipv4_route_count > 0) {
3927 		v4_attrs = calloc(ipv4_route_count, sizeof (*v4_attrs));
3928 		if (v4_attrs == NULL) {
3929 			perror("ire_report calloc v4_attrs failed");
3930 			return;
3931 		}
3932 	}
3933 	if (family_selected(AF_INET6) && ipv6_route_count > 0) {
3934 		v6_attrs = calloc(ipv6_route_count, sizeof (*v6_attrs));
3935 		if (v6_attrs == NULL) {
3936 			perror("ire_report calloc v6_attrs failed");
3937 			goto ire_report_done;
3938 		}
3939 	}
3940 	if (route_attrs_count > 0) {
3941 		all_attrs = malloc(route_attrs_count * sizeof (*all_attrs));
3942 		if (all_attrs == NULL) {
3943 			perror("ire_report malloc all_attrs failed");
3944 			goto ire_report_done;
3945 		}
3946 	}
3947 	aptr = all_attrs;
3948 	for (iptr = item; iptr != NULL; iptr = iptr->next_item) {
3949 		mib2_ipAttributeEntry_t *iae;
3950 		sec_attr_list_t **alp;
3951 
3952 		if (v4_attrs != NULL && iptr->group == MIB2_IP &&
3953 		    iptr->mib_id == EXPER_IP_RTATTR) {
3954 			alp = v4_attrs;
3955 		} else if (v6_attrs != NULL && iptr->group == MIB2_IP6 &&
3956 		    iptr->mib_id == EXPER_IP_RTATTR) {
3957 			alp = v6_attrs;
3958 		} else {
3959 			continue;
3960 		}
3961 		for (iae = iptr->valp;
3962 		    (char *)iae < (char *)iptr->valp + iptr->length;
3963 		    /* LINTED: (note 1) */
3964 		    iae = (mib2_ipAttributeEntry_t *)((char *)iae +
3965 		    ipRouteAttributeSize)) {
3966 			aptr->sal_next = alp[iae->iae_routeidx];
3967 			aptr->sal_attr = iae;
3968 			alp[iae->iae_routeidx] = aptr++;
3969 		}
3970 	}
3971 
3972 	/* 'for' loop 1: */
3973 	v4a = v4_attrs;
3974 	v6a = v6_attrs;
3975 	for (; item != NULL; item = item->next_item) {
3976 		if (Dflag) {
3977 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
3978 			(void) printf("Group = %d, mib_id = %d, "
3979 			    "length = %d, valp = 0x%p\n",
3980 			    item->group, item->mib_id,
3981 			    item->length, item->valp);
3982 		}
3983 		if (!((item->group == MIB2_IP &&
3984 		    item->mib_id == MIB2_IP_ROUTE) ||
3985 		    (item->group == MIB2_IP6 &&
3986 		    item->mib_id == MIB2_IP6_ROUTE)))
3987 			continue; /* 'for' loop 1 */
3988 
3989 		if (item->group == MIB2_IP && !family_selected(AF_INET))
3990 			continue; /* 'for' loop 1 */
3991 		else if (item->group == MIB2_IP6 && !family_selected(AF_INET6))
3992 			continue; /* 'for' loop 1 */
3993 
3994 		if (Dflag) {
3995 			if (item->group == MIB2_IP) {
3996 				(void) printf("%u records for "
3997 				    "ipRouteEntryTable:\n",
3998 				    item->length/sizeof (mib2_ipRouteEntry_t));
3999 			} else {
4000 				(void) printf("%u records for "
4001 				    "ipv6RouteEntryTable:\n",
4002 				    item->length/
4003 				    sizeof (mib2_ipv6RouteEntry_t));
4004 			}
4005 		}
4006 
4007 		if (item->group == MIB2_IP) {
4008 			for (rp = (mib2_ipRouteEntry_t *)item->valp;
4009 			    (char *)rp < (char *)item->valp + item->length;
4010 			    /* LINTED: (note 1) */
4011 			    rp = (mib2_ipRouteEntry_t *)((char *)rp +
4012 			    ipRouteEntrySize)) {
4013 				aptr = v4a == NULL ? NULL : *v4a++;
4014 				print_hdr_once_v4 = ire_report_item_v4(rp,
4015 				    print_hdr_once_v4, aptr);
4016 			}
4017 		} else {
4018 			for (rp6 = (mib2_ipv6RouteEntry_t *)item->valp;
4019 			    (char *)rp6 < (char *)item->valp + item->length;
4020 			    /* LINTED: (note 1) */
4021 			    rp6 = (mib2_ipv6RouteEntry_t *)((char *)rp6 +
4022 			    ipv6RouteEntrySize)) {
4023 				aptr = v6a == NULL ? NULL : *v6a++;
4024 				print_hdr_once_v6 = ire_report_item_v6(rp6,
4025 				    print_hdr_once_v6, aptr);
4026 			}
4027 		}
4028 	} /* 'for' loop 1 ends */
4029 	(void) fflush(stdout);
4030 ire_report_done:
4031 	if (v4_attrs != NULL)
4032 		free(v4_attrs);
4033 	if (v6_attrs != NULL)
4034 		free(v6_attrs);
4035 	if (all_attrs != NULL)
4036 		free(all_attrs);
4037 }
4038 
4039 /*
4040  * Match a user-supplied device name.  We do this by string because
4041  * the MIB2 interface gives us interface name strings rather than
4042  * ifIndex numbers.  The "none" rule matches only routes with no
4043  * interface.  The "any" rule matches routes with any non-blank
4044  * interface.  A base name ("hme0") matches all aliases as well
4045  * ("hme0:1").
4046  */
4047 static boolean_t
4048 dev_name_match(const DeviceName *devnam, const char *ifname)
4049 {
4050 	int iflen;
4051 
4052 	if (ifname == NULL)
4053 		return (devnam->o_length == 0);		/* "none" */
4054 	if (*ifname == '\0')
4055 		return (devnam->o_length != 0);		/* "any" */
4056 	iflen = strlen(ifname);
4057 	/* The check for ':' here supports interface aliases. */
4058 	if (iflen > devnam->o_length ||
4059 	    (iflen < devnam->o_length && devnam->o_bytes[iflen] != ':'))
4060 		return (B_FALSE);
4061 	return (strncmp(ifname, devnam->o_bytes, iflen) == 0);
4062 }
4063 
4064 /*
4065  * Match a user-supplied IP address list.  The "any" rule matches any
4066  * non-zero address.  The "none" rule matches only the zero address.
4067  * IPv6 addresses supplied by the user are ignored.  If the user
4068  * supplies a subnet mask, then match routes that are at least that
4069  * specific (use the user's mask).  If the user supplies only an
4070  * address, then select any routes that would match (use the route's
4071  * mask).
4072  */
4073 static boolean_t
4074 v4_addr_match(IpAddress addr, IpAddress mask, const filter_t *fp)
4075 {
4076 	char **app;
4077 	char *aptr;
4078 	in_addr_t faddr, fmask;
4079 
4080 	if (fp->u.a.f_address == NULL) {
4081 		if (IN6_IS_ADDR_UNSPECIFIED(&fp->u.a.f_mask))
4082 			return (addr != INADDR_ANY);	/* "any" */
4083 		else
4084 			return (addr == INADDR_ANY);	/* "none" */
4085 	}
4086 	if (!IN6_IS_V4MASK(fp->u.a.f_mask))
4087 		return (B_FALSE);
4088 	IN6_V4MAPPED_TO_IPADDR(&fp->u.a.f_mask, fmask);
4089 	if (fmask != IP_HOST_MASK) {
4090 		if (fmask > mask)
4091 			return (B_FALSE);
4092 		mask = fmask;
4093 	}
4094 	for (app = fp->u.a.f_address->h_addr_list; (aptr = *app) != NULL; app++)
4095 		/* LINTED: (note 1) */
4096 		if (IN6_IS_ADDR_V4MAPPED((in6_addr_t *)aptr)) {
4097 			/* LINTED: (note 1) */
4098 			IN6_V4MAPPED_TO_IPADDR((in6_addr_t *)aptr, faddr);
4099 			if (((faddr ^ addr) & mask) == 0)
4100 				return (B_TRUE);
4101 		}
4102 	return (B_FALSE);
4103 }
4104 
4105 /*
4106  * Run through the filter list for an IPv4 MIB2 route entry.  If all
4107  * filters of a given type fail to match, then the route is filtered
4108  * out (not displayed).  If no filter is given or at least one filter
4109  * of each type matches, then display the route.
4110  */
4111 static boolean_t
4112 ire_filter_match_v4(const mib2_ipRouteEntry_t *rp, uint_t flag_b)
4113 {
4114 	filter_t *fp;
4115 	int idx;
4116 
4117 	/* 'for' loop 1: */
4118 	for (idx = 0; idx < NFILTERKEYS; idx++)
4119 		if ((fp = filters[idx]) != NULL) {
4120 			/* 'for' loop 2: */
4121 			for (; fp != NULL; fp = fp->f_next) {
4122 				switch (idx) {
4123 				case FK_AF:
4124 					if (fp->u.f_family != AF_INET)
4125 						continue; /* 'for' loop 2 */
4126 					break;
4127 				case FK_OUTIF:
4128 					if (!dev_name_match(&rp->ipRouteIfIndex,
4129 					    fp->u.f_ifname))
4130 						continue; /* 'for' loop 2 */
4131 					break;
4132 				case FK_DST:
4133 					if (!v4_addr_match(rp->ipRouteDest,
4134 					    rp->ipRouteMask, fp))
4135 						continue; /* 'for' loop 2 */
4136 					break;
4137 				case FK_FLAGS:
4138 					if ((flag_b & fp->u.f.f_flagset) !=
4139 					    fp->u.f.f_flagset ||
4140 					    (flag_b & fp->u.f.f_flagclear))
4141 						continue; /* 'for' loop 2 */
4142 					break;
4143 				}
4144 				break;
4145 			} /* 'for' loop 2 ends */
4146 			if (fp == NULL)
4147 				return (B_FALSE);
4148 		}
4149 	/* 'for' loop 1 ends */
4150 	return (B_TRUE);
4151 }
4152 
4153 /*
4154  * Given an IPv4 MIB2 route entry, form the list of flags for the
4155  * route.
4156  */
4157 static uint_t
4158 form_v4_route_flags(const mib2_ipRouteEntry_t *rp, char *flags)
4159 {
4160 	uint_t flag_b;
4161 
4162 	flag_b = FLF_U;
4163 	(void) strcpy(flags, "U");
4164 	if (rp->ipRouteInfo.re_ire_type == IRE_DEFAULT ||
4165 	    rp->ipRouteInfo.re_ire_type == IRE_PREFIX ||
4166 	    rp->ipRouteInfo.re_ire_type == IRE_HOST ||
4167 	    rp->ipRouteInfo.re_ire_type == IRE_HOST_REDIRECT) {
4168 		(void) strcat(flags, "G");
4169 		flag_b |= FLF_G;
4170 	}
4171 	if (rp->ipRouteMask == IP_HOST_MASK) {
4172 		(void) strcat(flags, "H");
4173 		flag_b |= FLF_H;
4174 	}
4175 	if (rp->ipRouteInfo.re_ire_type == IRE_HOST_REDIRECT) {
4176 		(void) strcat(flags, "D");
4177 		flag_b |= FLF_D;
4178 	}
4179 	if (rp->ipRouteInfo.re_ire_type == IRE_CACHE) {
4180 		/* Address resolution */
4181 		(void) strcat(flags, "A");
4182 		flag_b |= FLF_A;
4183 	}
4184 	if (rp->ipRouteInfo.re_ire_type == IRE_BROADCAST) {	/* Broadcast */
4185 		(void) strcat(flags, "B");
4186 		flag_b |= FLF_B;
4187 	}
4188 	if (rp->ipRouteInfo.re_ire_type == IRE_LOCAL) {		/* Local */
4189 		(void) strcat(flags, "L");
4190 		flag_b |= FLF_L;
4191 	}
4192 	if (rp->ipRouteInfo.re_flags & RTF_MULTIRT) {
4193 		(void) strcat(flags, "M");			/* Multiroute */
4194 		flag_b |= FLF_M;
4195 	}
4196 	if (rp->ipRouteInfo.re_flags & RTF_SETSRC) {
4197 		(void) strcat(flags, "S");			/* Setsrc */
4198 		flag_b |= FLF_S;
4199 	}
4200 	return (flag_b);
4201 }
4202 
4203 static const char ire_hdr_v4[] =
4204 "\n%s Table: IPv4\n";
4205 static const char ire_hdr_v4_compat[] =
4206 "\n%s Table:\n";
4207 static const char ire_hdr_v4_verbose[] =
4208 "  Destination             Mask           Gateway          Device Mxfrg "
4209 "Rtt   Ref Flg  Out  In/Fwd %s\n"
4210 "-------------------- --------------- -------------------- ------ ----- "
4211 "----- --- --- ----- ------ %s\n";
4212 
4213 static const char ire_hdr_v4_normal[] =
4214 "  Destination           Gateway           Flags  Ref     Use     Interface"
4215 " %s\n-------------------- -------------------- ----- ----- ---------- "
4216 "--------- %s\n";
4217 
4218 static boolean_t
4219 ire_report_item_v4(const mib2_ipRouteEntry_t *rp, boolean_t first,
4220     const sec_attr_list_t *attrs)
4221 {
4222 	char			dstbuf[MAXHOSTNAMELEN + 1];
4223 	char			maskbuf[MAXHOSTNAMELEN + 1];
4224 	char			gwbuf[MAXHOSTNAMELEN + 1];
4225 	char			ifname[LIFNAMSIZ + 1];
4226 	char			flags[10];	/* RTF_ flags */
4227 	uint_t			flag_b;
4228 
4229 	if (!(Aflag || (rp->ipRouteInfo.re_ire_type != IRE_CACHE &&
4230 	    rp->ipRouteInfo.re_ire_type != IRE_BROADCAST &&
4231 	    rp->ipRouteInfo.re_ire_type != IRE_LOCAL))) {
4232 		return (first);
4233 	}
4234 
4235 	flag_b = form_v4_route_flags(rp, flags);
4236 
4237 	if (!ire_filter_match_v4(rp, flag_b))
4238 		return (first);
4239 
4240 	if (first) {
4241 		(void) printf(v4compat ? ire_hdr_v4_compat : ire_hdr_v4,
4242 		    Vflag ? "IRE" : "Routing");
4243 		(void) printf(Vflag ? ire_hdr_v4_verbose : ire_hdr_v4_normal,
4244 		    RSECflag ? "  Gateway security attributes  " : "",
4245 		    RSECflag ? "-------------------------------" : "");
4246 		first = B_FALSE;
4247 	}
4248 
4249 	if (flag_b & FLF_H) {
4250 		(void) pr_addr(rp->ipRouteDest, dstbuf, sizeof (dstbuf));
4251 	} else {
4252 		(void) pr_net(rp->ipRouteDest, rp->ipRouteMask,
4253 		    dstbuf, sizeof (dstbuf));
4254 	}
4255 	if (Vflag) {
4256 		(void) printf("%-20s %-15s %-20s %-6s %5u%c %4u %3u "
4257 		    "%-4s%6u %6u %s\n",
4258 		    dstbuf,
4259 		    pr_mask(rp->ipRouteMask, maskbuf, sizeof (maskbuf)),
4260 		    pr_addrnz(rp->ipRouteNextHop, gwbuf, sizeof (gwbuf)),
4261 		    octetstr(&rp->ipRouteIfIndex, 'a', ifname, sizeof (ifname)),
4262 		    rp->ipRouteInfo.re_max_frag,
4263 		    rp->ipRouteInfo.re_frag_flag ? '*' : ' ',
4264 		    rp->ipRouteInfo.re_rtt,
4265 		    rp->ipRouteInfo.re_ref,
4266 		    flags,
4267 		    rp->ipRouteInfo.re_obpkt,
4268 		    rp->ipRouteInfo.re_ibpkt,
4269 		    pr_secattr(attrs));
4270 	} else {
4271 		(void) printf("%-20s %-20s %-5s  %4u %10u %-9s %s\n",
4272 		    dstbuf,
4273 		    pr_addrnz(rp->ipRouteNextHop, gwbuf, sizeof (gwbuf)),
4274 		    flags,
4275 		    rp->ipRouteInfo.re_ref,
4276 		    rp->ipRouteInfo.re_obpkt + rp->ipRouteInfo.re_ibpkt,
4277 		    octetstr(&rp->ipRouteIfIndex, 'a',
4278 		    ifname, sizeof (ifname)),
4279 		    pr_secattr(attrs));
4280 	}
4281 	return (first);
4282 }
4283 
4284 /*
4285  * Match a user-supplied IP address list against an IPv6 route entry.
4286  * If the user specified "any," then any non-zero address matches.  If
4287  * the user specified "none," then only the zero address matches.  If
4288  * the user specified a subnet mask length, then use that in matching
4289  * routes (select routes that are at least as specific).  If the user
4290  * specified only an address, then use the route's mask (select routes
4291  * that would match that address).  IPv4 addresses are ignored.
4292  */
4293 static boolean_t
4294 v6_addr_match(const Ip6Address *addr, int masklen, const filter_t *fp)
4295 {
4296 	const uint8_t *ucp;
4297 	int fmasklen;
4298 	int i;
4299 	char **app;
4300 	const uint8_t *aptr;
4301 
4302 	if (fp->u.a.f_address == NULL) {
4303 		if (IN6_IS_ADDR_UNSPECIFIED(&fp->u.a.f_mask))	/* any */
4304 			return (!IN6_IS_ADDR_UNSPECIFIED(addr));
4305 		return (IN6_IS_ADDR_UNSPECIFIED(addr));		/* "none" */
4306 	}
4307 	fmasklen = 0;
4308 	/* 'for' loop 1a: */
4309 	for (ucp = fp->u.a.f_mask.s6_addr;
4310 	    ucp < fp->u.a.f_mask.s6_addr + sizeof (fp->u.a.f_mask.s6_addr);
4311 	    ucp++) {
4312 		if (*ucp != 0xff) {
4313 			if (*ucp != 0)
4314 				fmasklen += 9 - ffs(*ucp);
4315 			break; /* 'for' loop 1a */
4316 		}
4317 		fmasklen += 8;
4318 	} /* 'for' loop 1a ends */
4319 	if (fmasklen != IPV6_ABITS) {
4320 		if (fmasklen > masklen)
4321 			return (B_FALSE);
4322 		masklen = fmasklen;
4323 	}
4324 	/* 'for' loop 1b: */
4325 	for (app = fp->u.a.f_address->h_addr_list;
4326 	    (aptr = (uint8_t *)*app) != NULL; app++) {
4327 		/* LINTED: (note 1) */
4328 		if (IN6_IS_ADDR_V4MAPPED((in6_addr_t *)aptr))
4329 			continue; /* 'for' loop 1b */
4330 		ucp = addr->s6_addr;
4331 		for (i = masklen; i >= 8; i -= 8)
4332 			if (*ucp++ != *aptr++)
4333 				break; /* 'for' loop 1b */
4334 		if (i == 0 ||
4335 		    (i < 8 && ((*ucp ^ *aptr) & ~(0xff >> i)) == 0))
4336 			return (B_TRUE);
4337 	} /* 'for' loop 1b ends */
4338 	return (B_FALSE);
4339 }
4340 
4341 /*
4342  * Run through the filter list for an IPv6 MIB2 IRE.  For a given
4343  * type, if there's at least one filter and all filters of that type
4344  * fail to match, then the route doesn't match and isn't displayed.
4345  * If at least one matches, or none are specified, for each of the
4346  * types, then the route is selected and displayed.
4347  */
4348 static boolean_t
4349 ire_filter_match_v6(const mib2_ipv6RouteEntry_t *rp6, uint_t flag_b)
4350 {
4351 	filter_t *fp;
4352 	int idx;
4353 
4354 	/* 'for' loop 1: */
4355 	for (idx = 0; idx < NFILTERKEYS; idx++)
4356 		if ((fp = filters[idx]) != NULL) {
4357 			/* 'for' loop 2: */
4358 			for (; fp != NULL; fp = fp->f_next) {
4359 				switch (idx) {
4360 				case FK_AF:
4361 					if (fp->u.f_family != AF_INET6)
4362 						/* 'for' loop 2 */
4363 						continue;
4364 					break;
4365 				case FK_OUTIF:
4366 					if (!dev_name_match(&rp6->
4367 					    ipv6RouteIfIndex, fp->u.f_ifname))
4368 						/* 'for' loop 2 */
4369 						continue;
4370 					break;
4371 				case FK_DST:
4372 					if (!v6_addr_match(&rp6->ipv6RouteDest,
4373 					    rp6->ipv6RoutePfxLength, fp))
4374 						/* 'for' loop 2 */
4375 						continue;
4376 					break;
4377 				case FK_FLAGS:
4378 					if ((flag_b & fp->u.f.f_flagset) !=
4379 					    fp->u.f.f_flagset ||
4380 					    (flag_b & fp->u.f.f_flagclear))
4381 						/* 'for' loop 2 */
4382 						continue;
4383 					break;
4384 				}
4385 				break;
4386 			} /* 'for' loop 2 ends */
4387 			if (fp == NULL)
4388 				return (B_FALSE);
4389 		}
4390 	/* 'for' loop 1 ends */
4391 	return (B_TRUE);
4392 }
4393 
4394 static const char ire_hdr_v6[] =
4395 "\n%s Table: IPv6\n";
4396 static const char ire_hdr_v6_verbose[] =
4397 "  Destination/Mask            Gateway                    If    PMTU   Rtt  "
4398 "Ref Flags  Out   In/Fwd %s\n"
4399 "--------------------------- --------------------------- ----- ------ ----- "
4400 "--- ----- ------ ------ %s\n";
4401 static const char ire_hdr_v6_normal[] =
4402 "  Destination/Mask            Gateway                   Flags Ref   Use  "
4403 "  If   %s\n"
4404 "--------------------------- --------------------------- ----- --- ------- "
4405 "----- %s\n";
4406 
4407 static boolean_t
4408 ire_report_item_v6(const mib2_ipv6RouteEntry_t *rp6, boolean_t first,
4409     const sec_attr_list_t *attrs)
4410 {
4411 	char			dstbuf[MAXHOSTNAMELEN + 1];
4412 	char			gwbuf[MAXHOSTNAMELEN + 1];
4413 	char			ifname[LIFNAMSIZ + 1];
4414 	char			flags[10];	/* RTF_ flags */
4415 	uint_t			flag_b;
4416 
4417 	if (!(Aflag || (rp6->ipv6RouteInfo.re_ire_type != IRE_CACHE &&
4418 	    rp6->ipv6RouteInfo.re_ire_type != IRE_LOCAL))) {
4419 		return (first);
4420 	}
4421 
4422 	flag_b = FLF_U;
4423 	(void) strcpy(flags, "U");
4424 	if (rp6->ipv6RouteInfo.re_ire_type == IRE_DEFAULT ||
4425 	    rp6->ipv6RouteInfo.re_ire_type == IRE_PREFIX ||
4426 	    rp6->ipv6RouteInfo.re_ire_type == IRE_HOST ||
4427 	    rp6->ipv6RouteInfo.re_ire_type == IRE_HOST_REDIRECT) {
4428 		(void) strcat(flags, "G");
4429 		flag_b |= FLF_G;
4430 	}
4431 
4432 	if (rp6->ipv6RoutePfxLength == IPV6_ABITS) {
4433 		(void) strcat(flags, "H");
4434 		flag_b |= FLF_H;
4435 	}
4436 
4437 	if (rp6->ipv6RouteInfo.re_ire_type == IRE_HOST_REDIRECT) {
4438 		(void) strcat(flags, "D");
4439 		flag_b |= FLF_D;
4440 	}
4441 	if (rp6->ipv6RouteInfo.re_ire_type == IRE_CACHE) {
4442 		/* Address resolution */
4443 		(void) strcat(flags, "A");
4444 		flag_b |= FLF_A;
4445 	}
4446 	if (rp6->ipv6RouteInfo.re_ire_type == IRE_LOCAL) {	/* Local */
4447 		(void) strcat(flags, "L");
4448 		flag_b |= FLF_L;
4449 	}
4450 	if (rp6->ipv6RouteInfo.re_flags & RTF_MULTIRT) {
4451 		(void) strcat(flags, "M");			/* Multiroute */
4452 		flag_b |= FLF_M;
4453 	}
4454 	if (rp6->ipv6RouteInfo.re_flags & RTF_SETSRC) {
4455 		(void) strcat(flags, "S");			/* Setsrc */
4456 		flag_b |= FLF_S;
4457 	}
4458 
4459 	if (!ire_filter_match_v6(rp6, flag_b))
4460 		return (first);
4461 
4462 	if (first) {
4463 		(void) printf(ire_hdr_v6, Vflag ? "IRE" : "Routing");
4464 		(void) printf(Vflag ? ire_hdr_v6_verbose : ire_hdr_v6_normal,
4465 		    RSECflag ? "  Gateway security attributes  " : "",
4466 		    RSECflag ? "-------------------------------" : "");
4467 		first = B_FALSE;
4468 	}
4469 
4470 	if (Vflag) {
4471 		(void) printf("%-27s %-27s %-5s %5u%c %5u %3u "
4472 		    "%-5s %6u %6u %s\n",
4473 		    pr_prefix6(&rp6->ipv6RouteDest,
4474 		    rp6->ipv6RoutePfxLength, dstbuf, sizeof (dstbuf)),
4475 		    IN6_IS_ADDR_UNSPECIFIED(&rp6->ipv6RouteNextHop) ?
4476 		    "    --" :
4477 		    pr_addr6(&rp6->ipv6RouteNextHop, gwbuf, sizeof (gwbuf)),
4478 		    octetstr(&rp6->ipv6RouteIfIndex, 'a',
4479 		    ifname, sizeof (ifname)),
4480 		    rp6->ipv6RouteInfo.re_max_frag,
4481 		    rp6->ipv6RouteInfo.re_frag_flag ? '*' : ' ',
4482 		    rp6->ipv6RouteInfo.re_rtt,
4483 		    rp6->ipv6RouteInfo.re_ref,
4484 		    flags,
4485 		    rp6->ipv6RouteInfo.re_obpkt,
4486 		    rp6->ipv6RouteInfo.re_ibpkt,
4487 		    pr_secattr(attrs));
4488 	} else {
4489 		(void) printf("%-27s %-27s %-5s %3u %7u %-5s %s\n",
4490 		    pr_prefix6(&rp6->ipv6RouteDest,
4491 		    rp6->ipv6RoutePfxLength, dstbuf, sizeof (dstbuf)),
4492 		    IN6_IS_ADDR_UNSPECIFIED(&rp6->ipv6RouteNextHop) ?
4493 		    "    --" :
4494 		    pr_addr6(&rp6->ipv6RouteNextHop, gwbuf, sizeof (gwbuf)),
4495 		    flags,
4496 		    rp6->ipv6RouteInfo.re_ref,
4497 		    rp6->ipv6RouteInfo.re_obpkt + rp6->ipv6RouteInfo.re_ibpkt,
4498 		    octetstr(&rp6->ipv6RouteIfIndex, 'a',
4499 		    ifname, sizeof (ifname)),
4500 		    pr_secattr(attrs));
4501 	}
4502 	return (first);
4503 }
4504 
4505 /*
4506  * Common attribute-gathering routine for all transports.
4507  */
4508 static mib2_transportMLPEntry_t **
4509 gather_attrs(const mib_item_t *item, int group, int mib_id, int esize)
4510 {
4511 	int transport_count = 0;
4512 	const mib_item_t *iptr;
4513 	mib2_transportMLPEntry_t **attrs, *tme;
4514 
4515 	for (iptr = item; iptr != NULL; iptr = iptr->next_item) {
4516 		if (iptr->group == group && iptr->mib_id == mib_id)
4517 			transport_count += iptr->length / esize;
4518 	}
4519 	if (transport_count <= 0)
4520 		return (NULL);
4521 	attrs = calloc(transport_count, sizeof (*attrs));
4522 	if (attrs == NULL) {
4523 		perror("gather_attrs calloc failed");
4524 		return (NULL);
4525 	}
4526 	for (iptr = item; iptr != NULL; iptr = iptr->next_item) {
4527 		if (iptr->group == group && iptr->mib_id == EXPER_XPORT_MLP) {
4528 			for (tme = iptr->valp;
4529 			    (char *)tme < (char *)iptr->valp + iptr->length;
4530 			    /* LINTED: (note 1) */
4531 			    tme = (mib2_transportMLPEntry_t *)((char *)tme +
4532 			    transportMLPSize)) {
4533 				attrs[tme->tme_connidx] = tme;
4534 			}
4535 		}
4536 	}
4537 	return (attrs);
4538 }
4539 
4540 static void
4541 print_transport_label(const mib2_transportMLPEntry_t *attr)
4542 {
4543 	if (!RSECflag || attr == NULL ||
4544 	    !(attr->tme_flags & MIB2_TMEF_IS_LABELED))
4545 		return;
4546 
4547 	if (bisinvalid(&attr->tme_label))
4548 		(void) printf("   INVALID\n");
4549 	else if (!blequal(&attr->tme_label, zone_security_label))
4550 		(void) printf("   %s\n", sl_to_str(&attr->tme_label));
4551 }
4552 
4553 /* ------------------------------ TCP_REPORT------------------------------- */
4554 
4555 static const char tcp_hdr_v4[] =
4556 "\nTCP: IPv4\n";
4557 static const char tcp_hdr_v4_compat[] =
4558 "\nTCP\n";
4559 static const char tcp_hdr_v4_verbose[] =
4560 "Local/Remote Address Swind  Snext     Suna   Rwind  Rnext     Rack   "
4561 " Rto   Mss     State\n"
4562 "-------------------- ----- -------- -------- ----- -------- -------- "
4563 "----- ----- -----------\n";
4564 static const char tcp_hdr_v4_normal[] =
4565 "   Local Address        Remote Address    Swind Send-Q Rwind Recv-Q "
4566 "   State\n"
4567 "-------------------- -------------------- ----- ------ ----- ------ "
4568 "-----------\n";
4569 
4570 static const char tcp_hdr_v6[] =
4571 "\nTCP: IPv6\n";
4572 static const char tcp_hdr_v6_verbose[] =
4573 "Local/Remote Address              Swind  Snext     Suna   Rwind  Rnext   "
4574 "  Rack    Rto   Mss    State      If\n"
4575 "--------------------------------- ----- -------- -------- ----- -------- "
4576 "-------- ----- ----- ----------- -----\n";
4577 static const char tcp_hdr_v6_normal[] =
4578 "   Local Address                     Remote Address                 "
4579 "Swind Send-Q Rwind Recv-Q   State      If\n"
4580 "--------------------------------- --------------------------------- "
4581 "----- ------ ----- ------ ----------- -----\n";
4582 
4583 static boolean_t tcp_report_item_v4(const mib2_tcpConnEntry_t *,
4584     boolean_t first, const mib2_transportMLPEntry_t *);
4585 static boolean_t tcp_report_item_v6(const mib2_tcp6ConnEntry_t *,
4586     boolean_t first, const mib2_transportMLPEntry_t *);
4587 
4588 static void
4589 tcp_report(const mib_item_t *item)
4590 {
4591 	int			jtemp = 0;
4592 	boolean_t		print_hdr_once_v4 = B_TRUE;
4593 	boolean_t		print_hdr_once_v6 = B_TRUE;
4594 	mib2_tcpConnEntry_t	*tp;
4595 	mib2_tcp6ConnEntry_t	*tp6;
4596 	mib2_transportMLPEntry_t **v4_attrs, **v6_attrs;
4597 	mib2_transportMLPEntry_t **v4a, **v6a;
4598 	mib2_transportMLPEntry_t *aptr;
4599 
4600 	if (!protocol_selected(IPPROTO_TCP))
4601 		return;
4602 
4603 	/*
4604 	 * Preparation pass: the kernel returns separate entries for TCP
4605 	 * connection table entries and Multilevel Port attributes.  We loop
4606 	 * through the attributes first and set up an array for each address
4607 	 * family.
4608 	 */
4609 	v4_attrs = family_selected(AF_INET) && RSECflag ?
4610 	    gather_attrs(item, MIB2_TCP, MIB2_TCP_CONN, tcpConnEntrySize) :
4611 	    NULL;
4612 	v6_attrs = family_selected(AF_INET6) && RSECflag ?
4613 	    gather_attrs(item, MIB2_TCP6, MIB2_TCP6_CONN, tcp6ConnEntrySize) :
4614 	    NULL;
4615 
4616 	/* 'for' loop 1: */
4617 	v4a = v4_attrs;
4618 	v6a = v6_attrs;
4619 	for (; item != NULL; item = item->next_item) {
4620 		if (Dflag) {
4621 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
4622 			(void) printf("Group = %d, mib_id = %d, "
4623 			    "length = %d, valp = 0x%p\n",
4624 			    item->group, item->mib_id,
4625 			    item->length, item->valp);
4626 		}
4627 
4628 		if (!((item->group == MIB2_TCP &&
4629 		    item->mib_id == MIB2_TCP_CONN) ||
4630 		    (item->group == MIB2_TCP6 &&
4631 		    item->mib_id == MIB2_TCP6_CONN)))
4632 			continue; /* 'for' loop 1 */
4633 
4634 		if (item->group == MIB2_TCP && !family_selected(AF_INET))
4635 			continue; /* 'for' loop 1 */
4636 		else if (item->group == MIB2_TCP6 && !family_selected(AF_INET6))
4637 			continue; /* 'for' loop 1 */
4638 
4639 		if (item->group == MIB2_TCP) {
4640 			for (tp = (mib2_tcpConnEntry_t *)item->valp;
4641 			    (char *)tp < (char *)item->valp + item->length;
4642 			    /* LINTED: (note 1) */
4643 			    tp = (mib2_tcpConnEntry_t *)((char *)tp +
4644 			    tcpConnEntrySize)) {
4645 				aptr = v4a == NULL ? NULL : *v4a++;
4646 				print_hdr_once_v4 = tcp_report_item_v4(tp,
4647 				    print_hdr_once_v4, aptr);
4648 			}
4649 		} else {
4650 			for (tp6 = (mib2_tcp6ConnEntry_t *)item->valp;
4651 			    (char *)tp6 < (char *)item->valp + item->length;
4652 			    /* LINTED: (note 1) */
4653 			    tp6 = (mib2_tcp6ConnEntry_t *)((char *)tp6 +
4654 			    tcp6ConnEntrySize)) {
4655 				aptr = v6a == NULL ? NULL : *v6a++;
4656 				print_hdr_once_v6 = tcp_report_item_v6(tp6,
4657 				    print_hdr_once_v6, aptr);
4658 			}
4659 		}
4660 	} /* 'for' loop 1 ends */
4661 	(void) fflush(stdout);
4662 
4663 	if (v4_attrs != NULL)
4664 		free(v4_attrs);
4665 	if (v6_attrs != NULL)
4666 		free(v6_attrs);
4667 }
4668 
4669 static boolean_t
4670 tcp_report_item_v4(const mib2_tcpConnEntry_t *tp, boolean_t first,
4671     const mib2_transportMLPEntry_t *attr)
4672 {
4673 	/*
4674 	 * lname and fname below are for the hostname as well as the portname
4675 	 * There is no limit on portname length so we assume MAXHOSTNAMELEN
4676 	 * as the limit
4677 	 */
4678 	char	lname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
4679 	char	fname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
4680 
4681 	if (!(Aflag || tp->tcpConnEntryInfo.ce_state >= TCPS_ESTABLISHED))
4682 		return (first); /* Nothing to print */
4683 
4684 	if (first) {
4685 		(void) printf(v4compat ? tcp_hdr_v4_compat : tcp_hdr_v4);
4686 		(void) printf(Vflag ? tcp_hdr_v4_verbose : tcp_hdr_v4_normal);
4687 	}
4688 
4689 	if (Vflag) {
4690 		(void) printf("%-20s\n%-20s %5u %08x %08x %5u %08x %08x "
4691 		    "%5u %5u %s\n",
4692 		    pr_ap(tp->tcpConnLocalAddress,
4693 		    tp->tcpConnLocalPort, "tcp", lname, sizeof (lname)),
4694 		    pr_ap(tp->tcpConnRemAddress,
4695 		    tp->tcpConnRemPort, "tcp", fname, sizeof (fname)),
4696 		    tp->tcpConnEntryInfo.ce_swnd,
4697 		    tp->tcpConnEntryInfo.ce_snxt,
4698 		    tp->tcpConnEntryInfo.ce_suna,
4699 		    tp->tcpConnEntryInfo.ce_rwnd,
4700 		    tp->tcpConnEntryInfo.ce_rnxt,
4701 		    tp->tcpConnEntryInfo.ce_rack,
4702 		    tp->tcpConnEntryInfo.ce_rto,
4703 		    tp->tcpConnEntryInfo.ce_mss,
4704 		    mitcp_state(tp->tcpConnEntryInfo.ce_state, attr));
4705 	} else {
4706 		int sq = (int)tp->tcpConnEntryInfo.ce_snxt -
4707 		    (int)tp->tcpConnEntryInfo.ce_suna - 1;
4708 		int rq = (int)tp->tcpConnEntryInfo.ce_rnxt -
4709 		    (int)tp->tcpConnEntryInfo.ce_rack;
4710 
4711 		(void) printf("%-20s %-20s %5u %6d %5u %6d %s\n",
4712 		    pr_ap(tp->tcpConnLocalAddress,
4713 		    tp->tcpConnLocalPort, "tcp", lname, sizeof (lname)),
4714 		    pr_ap(tp->tcpConnRemAddress,
4715 		    tp->tcpConnRemPort, "tcp", fname, sizeof (fname)),
4716 		    tp->tcpConnEntryInfo.ce_swnd,
4717 		    (sq >= 0) ? sq : 0,
4718 		    tp->tcpConnEntryInfo.ce_rwnd,
4719 		    (rq >= 0) ? rq : 0,
4720 		    mitcp_state(tp->tcpConnEntryInfo.ce_state, attr));
4721 	}
4722 
4723 	print_transport_label(attr);
4724 
4725 	return (B_FALSE);
4726 }
4727 
4728 static boolean_t
4729 tcp_report_item_v6(const mib2_tcp6ConnEntry_t *tp6, boolean_t first,
4730     const mib2_transportMLPEntry_t *attr)
4731 {
4732 	/*
4733 	 * lname and fname below are for the hostname as well as the portname
4734 	 * There is no limit on portname length so we assume MAXHOSTNAMELEN
4735 	 * as the limit
4736 	 */
4737 	char	lname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
4738 	char	fname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
4739 	char	ifname[LIFNAMSIZ + 1];
4740 	char	*ifnamep;
4741 
4742 	if (!(Aflag || tp6->tcp6ConnEntryInfo.ce_state >= TCPS_ESTABLISHED))
4743 		return (first); /* Nothing to print */
4744 
4745 	if (first) {
4746 		(void) printf(tcp_hdr_v6);
4747 		(void) printf(Vflag ? tcp_hdr_v6_verbose : tcp_hdr_v6_normal);
4748 	}
4749 
4750 	ifnamep = (tp6->tcp6ConnIfIndex != 0) ?
4751 	    if_indextoname(tp6->tcp6ConnIfIndex, ifname) : NULL;
4752 	if (ifnamep == NULL)
4753 		ifnamep = "";
4754 
4755 	if (Vflag) {
4756 		(void) printf("%-33s\n%-33s %5u %08x %08x %5u %08x %08x "
4757 		    "%5u %5u %-11s %s\n",
4758 		    pr_ap6(&tp6->tcp6ConnLocalAddress,
4759 		    tp6->tcp6ConnLocalPort, "tcp", lname, sizeof (lname)),
4760 		    pr_ap6(&tp6->tcp6ConnRemAddress,
4761 		    tp6->tcp6ConnRemPort, "tcp", fname, sizeof (fname)),
4762 		    tp6->tcp6ConnEntryInfo.ce_swnd,
4763 		    tp6->tcp6ConnEntryInfo.ce_snxt,
4764 		    tp6->tcp6ConnEntryInfo.ce_suna,
4765 		    tp6->tcp6ConnEntryInfo.ce_rwnd,
4766 		    tp6->tcp6ConnEntryInfo.ce_rnxt,
4767 		    tp6->tcp6ConnEntryInfo.ce_rack,
4768 		    tp6->tcp6ConnEntryInfo.ce_rto,
4769 		    tp6->tcp6ConnEntryInfo.ce_mss,
4770 		    mitcp_state(tp6->tcp6ConnEntryInfo.ce_state, attr),
4771 		    ifnamep);
4772 	} else {
4773 		int sq = (int)tp6->tcp6ConnEntryInfo.ce_snxt -
4774 		    (int)tp6->tcp6ConnEntryInfo.ce_suna - 1;
4775 		int rq = (int)tp6->tcp6ConnEntryInfo.ce_rnxt -
4776 		    (int)tp6->tcp6ConnEntryInfo.ce_rack;
4777 
4778 		(void) printf("%-33s %-33s %5u %6d %5u %6d %-11s %s\n",
4779 		    pr_ap6(&tp6->tcp6ConnLocalAddress,
4780 		    tp6->tcp6ConnLocalPort, "tcp", lname, sizeof (lname)),
4781 		    pr_ap6(&tp6->tcp6ConnRemAddress,
4782 		    tp6->tcp6ConnRemPort, "tcp", fname, sizeof (fname)),
4783 		    tp6->tcp6ConnEntryInfo.ce_swnd,
4784 		    (sq >= 0) ? sq : 0,
4785 		    tp6->tcp6ConnEntryInfo.ce_rwnd,
4786 		    (rq >= 0) ? rq : 0,
4787 		    mitcp_state(tp6->tcp6ConnEntryInfo.ce_state, attr),
4788 		    ifnamep);
4789 	}
4790 
4791 	print_transport_label(attr);
4792 
4793 	return (B_FALSE);
4794 }
4795 
4796 /* ------------------------------- UDP_REPORT------------------------------- */
4797 
4798 static boolean_t udp_report_item_v4(const mib2_udpEntry_t *ude,
4799     boolean_t first, const mib2_transportMLPEntry_t *attr);
4800 static boolean_t udp_report_item_v6(const mib2_udp6Entry_t *ude6,
4801     boolean_t first, const mib2_transportMLPEntry_t *attr);
4802 
4803 static const char udp_hdr_v4[] =
4804 "   Local Address        Remote Address      State\n"
4805 "-------------------- -------------------- ----------\n";
4806 
4807 static const char udp_hdr_v6[] =
4808 "   Local Address                     Remote Address                 "
4809 "  State      If\n"
4810 "--------------------------------- --------------------------------- "
4811 "---------- -----\n";
4812 
4813 static void
4814 udp_report(const mib_item_t *item)
4815 {
4816 	int			jtemp = 0;
4817 	boolean_t		print_hdr_once_v4 = B_TRUE;
4818 	boolean_t		print_hdr_once_v6 = B_TRUE;
4819 	mib2_udpEntry_t		*ude;
4820 	mib2_udp6Entry_t	*ude6;
4821 	mib2_transportMLPEntry_t **v4_attrs, **v6_attrs;
4822 	mib2_transportMLPEntry_t **v4a, **v6a;
4823 	mib2_transportMLPEntry_t *aptr;
4824 
4825 	if (!protocol_selected(IPPROTO_UDP))
4826 		return;
4827 
4828 	/*
4829 	 * Preparation pass: the kernel returns separate entries for UDP
4830 	 * connection table entries and Multilevel Port attributes.  We loop
4831 	 * through the attributes first and set up an array for each address
4832 	 * family.
4833 	 */
4834 	v4_attrs = family_selected(AF_INET) && RSECflag ?
4835 	    gather_attrs(item, MIB2_UDP, MIB2_UDP_ENTRY, udpEntrySize) : NULL;
4836 	v6_attrs = family_selected(AF_INET6) && RSECflag ?
4837 	    gather_attrs(item, MIB2_UDP6, MIB2_UDP6_ENTRY, udp6EntrySize) :
4838 	    NULL;
4839 
4840 	v4a = v4_attrs;
4841 	v6a = v6_attrs;
4842 	/* 'for' loop 1: */
4843 	for (; item; item = item->next_item) {
4844 		if (Dflag) {
4845 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
4846 			(void) printf("Group = %d, mib_id = %d, "
4847 			    "length = %d, valp = 0x%p\n",
4848 			    item->group, item->mib_id,
4849 			    item->length, item->valp);
4850 		}
4851 		if (!((item->group == MIB2_UDP &&
4852 		    item->mib_id == MIB2_UDP_ENTRY) ||
4853 		    (item->group == MIB2_UDP6 &&
4854 		    item->mib_id == MIB2_UDP6_ENTRY)))
4855 			continue; /* 'for' loop 1 */
4856 
4857 		if (item->group == MIB2_UDP && !family_selected(AF_INET))
4858 			continue; /* 'for' loop 1 */
4859 		else if (item->group == MIB2_UDP6 && !family_selected(AF_INET6))
4860 			continue; /* 'for' loop 1 */
4861 
4862 		/*	xxx.xxx.xxx.xxx,pppp  sss... */
4863 		if (item->group == MIB2_UDP) {
4864 			for (ude = (mib2_udpEntry_t *)item->valp;
4865 			    (char *)ude < (char *)item->valp + item->length;
4866 			    /* LINTED: (note 1) */
4867 			    ude = (mib2_udpEntry_t *)((char *)ude +
4868 			    udpEntrySize)) {
4869 				aptr = v4a == NULL ? NULL : *v4a++;
4870 				print_hdr_once_v4 = udp_report_item_v4(ude,
4871 				    print_hdr_once_v4, aptr);
4872 			}
4873 		} else {
4874 			for (ude6 = (mib2_udp6Entry_t *)item->valp;
4875 			    (char *)ude6 < (char *)item->valp + item->length;
4876 			    /* LINTED: (note 1) */
4877 			    ude6 = (mib2_udp6Entry_t *)((char *)ude6 +
4878 			    udp6EntrySize)) {
4879 				aptr = v6a == NULL ? NULL : *v6a++;
4880 				print_hdr_once_v6 = udp_report_item_v6(ude6,
4881 				    print_hdr_once_v6, aptr);
4882 			}
4883 		}
4884 	} /* 'for' loop 1 ends */
4885 	(void) fflush(stdout);
4886 
4887 	if (v4_attrs != NULL)
4888 		free(v4_attrs);
4889 	if (v6_attrs != NULL)
4890 		free(v6_attrs);
4891 }
4892 
4893 static boolean_t
4894 udp_report_item_v4(const mib2_udpEntry_t *ude, boolean_t first,
4895     const mib2_transportMLPEntry_t *attr)
4896 {
4897 	char	lname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
4898 			/* hostname + portname */
4899 
4900 	if (!(Aflag || ude->udpEntryInfo.ue_state >= MIB2_UDP_connected))
4901 		return (first); /* Nothing to print */
4902 
4903 	if (first) {
4904 		(void) printf(v4compat ? "\nUDP\n" : "\nUDP: IPv4\n");
4905 		(void) printf(udp_hdr_v4);
4906 		first = B_FALSE;
4907 	}
4908 
4909 	(void) printf("%-20s ",
4910 	    pr_ap(ude->udpLocalAddress, ude->udpLocalPort, "udp",
4911 	    lname, sizeof (lname)));
4912 	(void) printf("%-20s %s\n",
4913 	    ude->udpEntryInfo.ue_state == MIB2_UDP_connected ?
4914 	    pr_ap(ude->udpEntryInfo.ue_RemoteAddress,
4915 	    ude->udpEntryInfo.ue_RemotePort, "udp", lname, sizeof (lname)) :
4916 	    "",
4917 	    miudp_state(ude->udpEntryInfo.ue_state, attr));
4918 
4919 	/*
4920 	 * UDP sockets don't have remote attributes, so there's no need to
4921 	 * print them here.
4922 	 */
4923 
4924 	return (first);
4925 }
4926 
4927 static boolean_t
4928 udp_report_item_v6(const mib2_udp6Entry_t *ude6, boolean_t first,
4929     const mib2_transportMLPEntry_t *attr)
4930 {
4931 	char	lname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
4932 			/* hostname + portname */
4933 	char	ifname[LIFNAMSIZ + 1];
4934 	const char *ifnamep;
4935 
4936 	if (!(Aflag || ude6->udp6EntryInfo.ue_state >= MIB2_UDP_connected))
4937 		return (first); /* Nothing to print */
4938 
4939 	if (first) {
4940 		(void) printf("\nUDP: IPv6\n");
4941 		(void) printf(udp_hdr_v6);
4942 		first = B_FALSE;
4943 	}
4944 
4945 	ifnamep = (ude6->udp6IfIndex != 0) ?
4946 	    if_indextoname(ude6->udp6IfIndex, ifname) : NULL;
4947 
4948 	(void) printf("%-33s ",
4949 	    pr_ap6(&ude6->udp6LocalAddress,
4950 	    ude6->udp6LocalPort, "udp", lname, sizeof (lname)));
4951 	(void) printf("%-33s %-10s %s\n",
4952 	    ude6->udp6EntryInfo.ue_state == MIB2_UDP_connected ?
4953 	    pr_ap6(&ude6->udp6EntryInfo.ue_RemoteAddress,
4954 	    ude6->udp6EntryInfo.ue_RemotePort, "udp", lname, sizeof (lname)) :
4955 	    "",
4956 	    miudp_state(ude6->udp6EntryInfo.ue_state, attr),
4957 	    ifnamep == NULL ? "" : ifnamep);
4958 
4959 	/*
4960 	 * UDP sockets don't have remote attributes, so there's no need to
4961 	 * print them here.
4962 	 */
4963 
4964 	return (first);
4965 }
4966 
4967 /* ------------------------------ SCTP_REPORT------------------------------- */
4968 
4969 static const char sctp_hdr[] =
4970 "\nSCTP:";
4971 static const char sctp_hdr_normal[] =
4972 "        Local Address                   Remote Address          "
4973 "Swind  Send-Q Rwind  Recv-Q StrsI/O  State\n"
4974 "------------------------------- ------------------------------- "
4975 "------ ------ ------ ------ ------- -----------";
4976 
4977 static const char *
4978 nssctp_state(int state, const mib2_transportMLPEntry_t *attr)
4979 {
4980 	static char sctpsbuf[50];
4981 	const char *cp;
4982 
4983 	switch (state) {
4984 	case MIB2_SCTP_closed:
4985 		cp = "CLOSED";
4986 		break;
4987 	case MIB2_SCTP_cookieWait:
4988 		cp = "COOKIE_WAIT";
4989 		break;
4990 	case MIB2_SCTP_cookieEchoed:
4991 		cp = "COOKIE_ECHOED";
4992 		break;
4993 	case MIB2_SCTP_established:
4994 		cp = "ESTABLISHED";
4995 		break;
4996 	case MIB2_SCTP_shutdownPending:
4997 		cp = "SHUTDOWN_PENDING";
4998 		break;
4999 	case MIB2_SCTP_shutdownSent:
5000 		cp = "SHUTDOWN_SENT";
5001 		break;
5002 	case MIB2_SCTP_shutdownReceived:
5003 		cp = "SHUTDOWN_RECEIVED";
5004 		break;
5005 	case MIB2_SCTP_shutdownAckSent:
5006 		cp = "SHUTDOWN_ACK_SENT";
5007 		break;
5008 	case MIB2_SCTP_listen:
5009 		cp = "LISTEN";
5010 		break;
5011 	default:
5012 		(void) snprintf(sctpsbuf, sizeof (sctpsbuf),
5013 		    "UNKNOWN STATE(%d)", state);
5014 		cp = sctpsbuf;
5015 		break;
5016 	}
5017 
5018 	if (RSECflag && attr != NULL && attr->tme_flags != 0) {
5019 		if (cp != sctpsbuf) {
5020 			(void) strlcpy(sctpsbuf, cp, sizeof (sctpsbuf));
5021 			cp = sctpsbuf;
5022 		}
5023 		if (attr->tme_flags & MIB2_TMEF_PRIVATE)
5024 			(void) strlcat(sctpsbuf, " P", sizeof (sctpsbuf));
5025 		if (attr->tme_flags & MIB2_TMEF_SHARED)
5026 			(void) strlcat(sctpsbuf, " S", sizeof (sctpsbuf));
5027 	}
5028 
5029 	return (cp);
5030 }
5031 
5032 static const mib2_sctpConnRemoteEntry_t *
5033 sctp_getnext_rem(const mib_item_t **itemp,
5034     const mib2_sctpConnRemoteEntry_t *current, uint32_t associd)
5035 {
5036 	const mib_item_t *item = *itemp;
5037 	const mib2_sctpConnRemoteEntry_t	*sre;
5038 
5039 	for (; item != NULL; item = item->next_item, current = NULL) {
5040 		if (!(item->group == MIB2_SCTP &&
5041 		    item->mib_id == MIB2_SCTP_CONN_REMOTE)) {
5042 			continue;
5043 		}
5044 
5045 		if (current != NULL) {
5046 			/* LINTED: (note 1) */
5047 			sre = (const mib2_sctpConnRemoteEntry_t *)
5048 			    ((const char *)current + sctpRemoteEntrySize);
5049 		} else {
5050 			sre = item->valp;
5051 		}
5052 		for (; (char *)sre < (char *)item->valp + item->length;
5053 		    /* LINTED: (note 1) */
5054 		    sre = (const mib2_sctpConnRemoteEntry_t *)
5055 		    ((const char *)sre + sctpRemoteEntrySize)) {
5056 			if (sre->sctpAssocId != associd) {
5057 				continue;
5058 			}
5059 			*itemp = item;
5060 			return (sre);
5061 		}
5062 	}
5063 	*itemp = NULL;
5064 	return (NULL);
5065 }
5066 
5067 static const mib2_sctpConnLocalEntry_t *
5068 sctp_getnext_local(const mib_item_t **itemp,
5069     const mib2_sctpConnLocalEntry_t *current, uint32_t associd)
5070 {
5071 	const mib_item_t *item = *itemp;
5072 	const mib2_sctpConnLocalEntry_t	*sle;
5073 
5074 	for (; item != NULL; item = item->next_item, current = NULL) {
5075 		if (!(item->group == MIB2_SCTP &&
5076 		    item->mib_id == MIB2_SCTP_CONN_LOCAL)) {
5077 			continue;
5078 		}
5079 
5080 		if (current != NULL) {
5081 			/* LINTED: (note 1) */
5082 			sle = (const mib2_sctpConnLocalEntry_t *)
5083 			    ((const char *)current + sctpLocalEntrySize);
5084 		} else {
5085 			sle = item->valp;
5086 		}
5087 		for (; (char *)sle < (char *)item->valp + item->length;
5088 		    /* LINTED: (note 1) */
5089 		    sle = (const mib2_sctpConnLocalEntry_t *)
5090 		    ((const char *)sle + sctpLocalEntrySize)) {
5091 			if (sle->sctpAssocId != associd) {
5092 				continue;
5093 			}
5094 			*itemp = item;
5095 			return (sle);
5096 		}
5097 	}
5098 	*itemp = NULL;
5099 	return (NULL);
5100 }
5101 
5102 static void
5103 sctp_pr_addr(int type, char *name, int namelen, const in6_addr_t *addr,
5104     int port)
5105 {
5106 	ipaddr_t	v4addr;
5107 	in6_addr_t	v6addr;
5108 
5109 	/*
5110 	 * Address is either a v4 mapped or v6 addr. If
5111 	 * it's a v4 mapped, convert to v4 before
5112 	 * displaying.
5113 	 */
5114 	switch (type) {
5115 	case MIB2_SCTP_ADDR_V4:
5116 		/* v4 */
5117 		v6addr = *addr;
5118 
5119 		IN6_V4MAPPED_TO_IPADDR(&v6addr, v4addr);
5120 		if (port > 0) {
5121 			(void) pr_ap(v4addr, port, "sctp", name, namelen);
5122 		} else {
5123 			(void) pr_addr(v4addr, name, namelen);
5124 		}
5125 		break;
5126 
5127 	case MIB2_SCTP_ADDR_V6:
5128 		/* v6 */
5129 		if (port > 0) {
5130 			(void) pr_ap6(addr, port, "sctp", name, namelen);
5131 		} else {
5132 			(void) pr_addr6(addr, name, namelen);
5133 		}
5134 		break;
5135 
5136 	default:
5137 		(void) snprintf(name, namelen, "<unknown addr type>");
5138 		break;
5139 	}
5140 }
5141 
5142 static void
5143 sctp_conn_report_item(const mib_item_t *head, const mib2_sctpConnEntry_t *sp,
5144     const mib2_transportMLPEntry_t *attr)
5145 {
5146 	char		lname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
5147 	char		fname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
5148 	const mib2_sctpConnRemoteEntry_t	*sre = NULL;
5149 	const mib2_sctpConnLocalEntry_t	*sle = NULL;
5150 	const mib_item_t *local = head;
5151 	const mib_item_t *remote = head;
5152 	uint32_t	id = sp->sctpAssocId;
5153 	boolean_t	printfirst = B_TRUE;
5154 
5155 	sctp_pr_addr(sp->sctpAssocRemPrimAddrType, fname, sizeof (fname),
5156 	    &sp->sctpAssocRemPrimAddr, sp->sctpAssocRemPort);
5157 	sctp_pr_addr(sp->sctpAssocRemPrimAddrType, lname, sizeof (lname),
5158 	    &sp->sctpAssocLocPrimAddr, sp->sctpAssocLocalPort);
5159 
5160 	(void) printf("%-31s %-31s %6u %6d %6u %6d %3d/%-3d %s\n",
5161 	    lname, fname,
5162 	    sp->sctpConnEntryInfo.ce_swnd,
5163 	    sp->sctpConnEntryInfo.ce_sendq,
5164 	    sp->sctpConnEntryInfo.ce_rwnd,
5165 	    sp->sctpConnEntryInfo.ce_recvq,
5166 	    sp->sctpAssocInStreams, sp->sctpAssocOutStreams,
5167 	    nssctp_state(sp->sctpAssocState, attr));
5168 
5169 	print_transport_label(attr);
5170 
5171 	if (!Vflag) {
5172 		return;
5173 	}
5174 
5175 	/* Print remote addresses/local addresses on following lines */
5176 	while ((sre = sctp_getnext_rem(&remote, sre, id)) != NULL) {
5177 		if (!IN6_ARE_ADDR_EQUAL(&sre->sctpAssocRemAddr,
5178 		    &sp->sctpAssocRemPrimAddr)) {
5179 			if (printfirst == B_TRUE) {
5180 				(void) fputs("\t<Remote: ", stdout);
5181 				printfirst = B_FALSE;
5182 			} else {
5183 				(void) fputs(", ", stdout);
5184 			}
5185 			sctp_pr_addr(sre->sctpAssocRemAddrType, fname,
5186 			    sizeof (fname), &sre->sctpAssocRemAddr, -1);
5187 			if (sre->sctpAssocRemAddrActive == MIB2_SCTP_ACTIVE) {
5188 				(void) fputs(fname, stdout);
5189 			} else {
5190 				(void) printf("(%s)", fname);
5191 			}
5192 		}
5193 	}
5194 	if (printfirst == B_FALSE) {
5195 		(void) puts(">");
5196 		printfirst = B_TRUE;
5197 	}
5198 	while ((sle = sctp_getnext_local(&local, sle, id)) != NULL) {
5199 		if (!IN6_ARE_ADDR_EQUAL(&sle->sctpAssocLocalAddr,
5200 		    &sp->sctpAssocLocPrimAddr)) {
5201 			if (printfirst == B_TRUE) {
5202 				(void) fputs("\t<Local: ", stdout);
5203 				printfirst = B_FALSE;
5204 			} else {
5205 				(void) fputs(", ", stdout);
5206 			}
5207 			sctp_pr_addr(sle->sctpAssocLocalAddrType, lname,
5208 			    sizeof (lname), &sle->sctpAssocLocalAddr, -1);
5209 			(void) fputs(lname, stdout);
5210 		}
5211 	}
5212 	if (printfirst == B_FALSE) {
5213 		(void) puts(">");
5214 	}
5215 }
5216 
5217 static void
5218 sctp_report(const mib_item_t *item)
5219 {
5220 	const mib_item_t		*head;
5221 	const mib2_sctpConnEntry_t	*sp;
5222 	boolean_t		first = B_TRUE;
5223 	mib2_transportMLPEntry_t **attrs, **aptr;
5224 	mib2_transportMLPEntry_t *attr;
5225 
5226 	/*
5227 	 * Preparation pass: the kernel returns separate entries for SCTP
5228 	 * connection table entries and Multilevel Port attributes.  We loop
5229 	 * through the attributes first and set up an array for each address
5230 	 * family.
5231 	 */
5232 	attrs = RSECflag ?
5233 	    gather_attrs(item, MIB2_SCTP, MIB2_SCTP_CONN, sctpEntrySize) :
5234 	    NULL;
5235 
5236 	aptr = attrs;
5237 	head = item;
5238 	for (; item != NULL; item = item->next_item) {
5239 
5240 		if (!(item->group == MIB2_SCTP &&
5241 		    item->mib_id == MIB2_SCTP_CONN))
5242 			continue;
5243 
5244 		for (sp = item->valp;
5245 		    (char *)sp < (char *)item->valp + item->length;
5246 		    /* LINTED: (note 1) */
5247 		    sp = (mib2_sctpConnEntry_t *)((char *)sp + sctpEntrySize)) {
5248 			attr = aptr == NULL ? NULL : *aptr++;
5249 			if (Aflag ||
5250 			    sp->sctpAssocState >= MIB2_SCTP_established) {
5251 				if (first == B_TRUE) {
5252 					(void) puts(sctp_hdr);
5253 					(void) puts(sctp_hdr_normal);
5254 					first = B_FALSE;
5255 				}
5256 				sctp_conn_report_item(head, sp, attr);
5257 			}
5258 		}
5259 	}
5260 	if (attrs != NULL)
5261 		free(attrs);
5262 }
5263 
5264 static char *
5265 plural(int n)
5266 {
5267 	return (n != 1 ? "s" : "");
5268 }
5269 
5270 static char *
5271 pluraly(int n)
5272 {
5273 	return (n != 1 ? "ies" : "y");
5274 }
5275 
5276 static char *
5277 plurales(int n)
5278 {
5279 	return (n != 1 ? "es" : "");
5280 }
5281 
5282 static char *
5283 pktscale(n)
5284 	int n;
5285 {
5286 	static char buf[6];
5287 	char t;
5288 
5289 	if (n < 1024) {
5290 		t = ' ';
5291 	} else if (n < 1024 * 1024) {
5292 		t = 'k';
5293 		n /= 1024;
5294 	} else if (n < 1024 * 1024 * 1024) {
5295 		t = 'm';
5296 		n /= 1024 * 1024;
5297 	} else {
5298 		t = 'g';
5299 		n /= 1024 * 1024 * 1024;
5300 	}
5301 
5302 	(void) snprintf(buf, sizeof (buf), "%4u%c", n, t);
5303 	return (buf);
5304 }
5305 
5306 /* --------------------- mrt_report (netstat -m) -------------------------- */
5307 
5308 static void
5309 mrt_report(mib_item_t *item)
5310 {
5311 	int		jtemp = 0;
5312 	struct vifctl	*vip;
5313 	vifi_t		vifi;
5314 	struct mfcctl	*mfccp;
5315 	int		numvifs = 0;
5316 	int		nmfc = 0;
5317 	char		abuf[MAXHOSTNAMELEN + 1];
5318 
5319 	if (!(family_selected(AF_INET)))
5320 		return;
5321 
5322 	/* 'for' loop 1: */
5323 	for (; item; item = item->next_item) {
5324 		if (Dflag) {
5325 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
5326 			(void) printf("Group = %d, mib_id = %d, "
5327 			    "length = %d, valp = 0x%p\n",
5328 			    item->group, item->mib_id, item->length,
5329 			    item->valp);
5330 		}
5331 		if (item->group != EXPER_DVMRP)
5332 			continue; /* 'for' loop 1 */
5333 
5334 		switch (item->mib_id) {
5335 
5336 		case EXPER_DVMRP_VIF:
5337 			if (Dflag)
5338 				(void) printf("%u records for ipVifTable:\n",
5339 				    item->length/sizeof (struct vifctl));
5340 			if (item->length/sizeof (struct vifctl) == 0) {
5341 				(void) puts("\nVirtual Interface Table is "
5342 				    "empty");
5343 				break;
5344 			}
5345 
5346 			(void) puts("\nVirtual Interface Table\n"
5347 			    " Vif Threshold Rate_Limit Local-Address"
5348 			    "   Remote-Address     Pkt_in   Pkt_out");
5349 
5350 			/* 'for' loop 2: */
5351 			for (vip = (struct vifctl *)item->valp;
5352 			    (char *)vip < (char *)item->valp + item->length;
5353 			    /* LINTED: (note 1) */
5354 			    vip = (struct vifctl *)((char *)vip +
5355 			    vifctlSize)) {
5356 				if (vip->vifc_lcl_addr.s_addr == 0)
5357 					continue; /* 'for' loop 2 */
5358 				/* numvifs = vip->vifc_vifi; */
5359 
5360 				numvifs++;
5361 				(void) printf("  %2u       %3u       "
5362 				    "%4u %-15.15s",
5363 				    vip->vifc_vifi,
5364 				    vip->vifc_threshold,
5365 				    vip->vifc_rate_limit,
5366 				    pr_addr(vip->vifc_lcl_addr.s_addr,
5367 				    abuf, sizeof (abuf)));
5368 				(void) printf(" %-15.15s  %8u  %8u\n",
5369 				    (vip->vifc_flags & VIFF_TUNNEL) ?
5370 				    pr_addr(vip->vifc_rmt_addr.s_addr,
5371 				    abuf, sizeof (abuf)) : "",
5372 				    vip->vifc_pkt_in,
5373 				    vip->vifc_pkt_out);
5374 			} /* 'for' loop 2 ends */
5375 
5376 			(void) printf("Numvifs: %d\n", numvifs);
5377 			break;
5378 
5379 		case EXPER_DVMRP_MRT:
5380 			if (Dflag)
5381 				(void) printf("%u records for ipMfcTable:\n",
5382 				    item->length/sizeof (struct vifctl));
5383 			if (item->length/sizeof (struct vifctl) == 0) {
5384 				(void) puts("\nMulticast Forwarding Cache is "
5385 				    "empty");
5386 				break;
5387 			}
5388 
5389 			(void) puts("\nMulticast Forwarding Cache\n"
5390 			    "  Origin-Subnet                 Mcastgroup      "
5391 			    "# Pkts  In-Vif  Out-vifs/Forw-ttl");
5392 
5393 			for (mfccp = (struct mfcctl *)item->valp;
5394 			    (char *)mfccp < (char *)item->valp + item->length;
5395 			    /* LINTED: (note 1) */
5396 			    mfccp = (struct mfcctl *)((char *)mfccp +
5397 			    mfcctlSize)) {
5398 
5399 				nmfc++;
5400 				(void) printf("  %-30.15s",
5401 				    pr_addr(mfccp->mfcc_origin.s_addr,
5402 				    abuf, sizeof (abuf)));
5403 				(void) printf("%-15.15s  %6s  %3u    ",
5404 				    pr_net(mfccp->mfcc_mcastgrp.s_addr,
5405 				    mfccp->mfcc_mcastgrp.s_addr,
5406 				    abuf, sizeof (abuf)),
5407 				    pktscale((int)mfccp->mfcc_pkt_cnt),
5408 				    mfccp->mfcc_parent);
5409 
5410 				for (vifi = 0; vifi < MAXVIFS; ++vifi) {
5411 					if (mfccp->mfcc_ttls[vifi]) {
5412 						(void) printf("      %u (%u)",
5413 						    vifi,
5414 						    mfccp->mfcc_ttls[vifi]);
5415 					}
5416 
5417 				}
5418 				(void) putchar('\n');
5419 			}
5420 			(void) printf("\nTotal no. of entries in cache: %d\n",
5421 			    nmfc);
5422 			break;
5423 		}
5424 	} /* 'for' loop 1 ends */
5425 	(void) putchar('\n');
5426 	(void) fflush(stdout);
5427 }
5428 
5429 /*
5430  * Get the stats for the cache named 'name'.  If prefix != 0, then
5431  * interpret the name as a prefix, and sum up stats for all caches
5432  * named 'name*'.
5433  */
5434 static void
5435 kmem_cache_stats(char *title, char *name, int prefix, int64_t *total_bytes)
5436 {
5437 	int len;
5438 	int alloc;
5439 	int64_t total_alloc = 0;
5440 	int alloc_fail, total_alloc_fail = 0;
5441 	int buf_size = 0;
5442 	int buf_avail;
5443 	int buf_total;
5444 	int buf_max, total_buf_max = 0;
5445 	int buf_inuse, total_buf_inuse = 0;
5446 	kstat_t *ksp;
5447 	char buf[256];
5448 
5449 	len = prefix ? strlen(name) : 256;
5450 
5451 	/* 'for' loop 1: */
5452 	for (ksp = kc->kc_chain; ksp != NULL; ksp = ksp->ks_next) {
5453 
5454 		if (strcmp(ksp->ks_class, "kmem_cache") != 0)
5455 			continue; /* 'for' loop 1 */
5456 
5457 		/*
5458 		 * Hack alert: because of the way streams messages are
5459 		 * allocated, every constructed free dblk has an associated
5460 		 * mblk.  From the allocator's viewpoint those mblks are
5461 		 * allocated (because they haven't been freed), but from
5462 		 * our viewpoint they're actually free (because they're
5463 		 * not currently in use).  To account for this caching
5464 		 * effect we subtract the total constructed free dblks
5465 		 * from the total allocated mblks to derive mblks in use.
5466 		 */
5467 		if (strcmp(name, "streams_mblk") == 0 &&
5468 		    strncmp(ksp->ks_name, "streams_dblk", 12) == 0) {
5469 			(void) safe_kstat_read(kc, ksp, NULL);
5470 			total_buf_inuse -=
5471 			    kstat_named_value(ksp, "buf_constructed");
5472 			continue; /* 'for' loop 1 */
5473 		}
5474 
5475 		if (strncmp(ksp->ks_name, name, len) != 0)
5476 			continue; /* 'for' loop 1 */
5477 
5478 		(void) safe_kstat_read(kc, ksp, NULL);
5479 
5480 		alloc		= kstat_named_value(ksp, "alloc");
5481 		alloc_fail	= kstat_named_value(ksp, "alloc_fail");
5482 		buf_size	= kstat_named_value(ksp, "buf_size");
5483 		buf_avail	= kstat_named_value(ksp, "buf_avail");
5484 		buf_total	= kstat_named_value(ksp, "buf_total");
5485 		buf_max		= kstat_named_value(ksp, "buf_max");
5486 		buf_inuse	= buf_total - buf_avail;
5487 
5488 		if (Vflag && prefix) {
5489 			(void) snprintf(buf, sizeof (buf), "%s%s", title,
5490 			    ksp->ks_name + len);
5491 			(void) printf("    %-18s %6u %9u %11u %11u\n",
5492 			    buf, buf_inuse, buf_max, alloc, alloc_fail);
5493 		}
5494 
5495 		total_alloc		+= alloc;
5496 		total_alloc_fail	+= alloc_fail;
5497 		total_buf_max		+= buf_max;
5498 		total_buf_inuse		+= buf_inuse;
5499 		*total_bytes		+= (int64_t)buf_inuse * buf_size;
5500 	} /* 'for' loop 1 ends */
5501 
5502 	if (buf_size == 0) {
5503 		(void) printf("%-22s [couldn't find statistics for %s]\n",
5504 		    title, name);
5505 		return;
5506 	}
5507 
5508 	if (Vflag && prefix)
5509 		(void) snprintf(buf, sizeof (buf), "%s_total", title);
5510 	else
5511 		(void) snprintf(buf, sizeof (buf), "%s", title);
5512 
5513 	(void) printf("%-22s %6d %9d %11lld %11d\n", buf,
5514 	    total_buf_inuse, total_buf_max, total_alloc, total_alloc_fail);
5515 }
5516 
5517 static void
5518 m_report(void)
5519 {
5520 	int64_t total_bytes = 0;
5521 
5522 	(void) puts("streams allocation:");
5523 	(void) printf("%63s\n", "cumulative  allocation");
5524 	(void) printf("%63s\n",
5525 	    "current   maximum       total    failures");
5526 
5527 	kmem_cache_stats("streams",
5528 	    "stream_head_cache", 0, &total_bytes);
5529 	kmem_cache_stats("queues", "queue_cache", 0, &total_bytes);
5530 	kmem_cache_stats("mblk", "streams_mblk", 0, &total_bytes);
5531 	kmem_cache_stats("dblk", "streams_dblk", 1, &total_bytes);
5532 	kmem_cache_stats("linkblk", "linkinfo_cache", 0, &total_bytes);
5533 	kmem_cache_stats("syncq", "syncq_cache", 0, &total_bytes);
5534 	kmem_cache_stats("qband", "qband_cache", 0, &total_bytes);
5535 
5536 	(void) printf("\n%lld Kbytes allocated for streams data\n",
5537 	    total_bytes / 1024);
5538 
5539 	(void) putchar('\n');
5540 	(void) fflush(stdout);
5541 }
5542 
5543 /* --------------------------------- */
5544 
5545 /*
5546  * Print an IPv4 address. Remove the matching part of the domain name
5547  * from the returned name.
5548  */
5549 static char *
5550 pr_addr(uint_t addr, char *dst, uint_t dstlen)
5551 {
5552 	char			*cp;
5553 	struct hostent		*hp = NULL;
5554 	static char		domain[MAXHOSTNAMELEN + 1];
5555 	static boolean_t	first = B_TRUE;
5556 	int			error_num;
5557 
5558 	if (first) {
5559 		first = B_FALSE;
5560 		if (sysinfo(SI_HOSTNAME, domain, MAXHOSTNAMELEN) != -1 &&
5561 		    (cp = strchr(domain, '.'))) {
5562 			(void) strncpy(domain, cp + 1, sizeof (domain));
5563 		} else
5564 			domain[0] = 0;
5565 	}
5566 	cp = NULL;
5567 	if (!Nflag) {
5568 		hp = getipnodebyaddr((char *)&addr, sizeof (uint_t), AF_INET,
5569 		    &error_num);
5570 		if (hp) {
5571 			if ((cp = strchr(hp->h_name, '.')) != NULL &&
5572 			    strcasecmp(cp + 1, domain) == 0)
5573 				*cp = 0;
5574 			cp = hp->h_name;
5575 		}
5576 	}
5577 	if (cp != NULL) {
5578 		(void) strncpy(dst, cp, dstlen);
5579 		dst[dstlen - 1] = 0;
5580 	} else {
5581 		(void) inet_ntop(AF_INET, (char *)&addr, dst, dstlen);
5582 	}
5583 	if (hp != NULL)
5584 		freehostent(hp);
5585 	return (dst);
5586 }
5587 
5588 /*
5589  * Print a non-zero IPv4 address.  Print "    --" if the address is zero.
5590  */
5591 static char *
5592 pr_addrnz(ipaddr_t addr, char *dst, uint_t dstlen)
5593 {
5594 	if (addr == INADDR_ANY) {
5595 		(void) strlcpy(dst, "    --", dstlen);
5596 		return (dst);
5597 	}
5598 	return (pr_addr(addr, dst, dstlen));
5599 }
5600 
5601 /*
5602  * Print an IPv6 address. Remove the matching part of the domain name
5603  * from the returned name.
5604  */
5605 static char *
5606 pr_addr6(const struct in6_addr *addr, char *dst, uint_t dstlen)
5607 {
5608 	char			*cp;
5609 	struct hostent		*hp = NULL;
5610 	static char		domain[MAXHOSTNAMELEN + 1];
5611 	static boolean_t	first = B_TRUE;
5612 	int			error_num;
5613 
5614 	if (first) {
5615 		first = B_FALSE;
5616 		if (sysinfo(SI_HOSTNAME, domain, MAXHOSTNAMELEN) != -1 &&
5617 		    (cp = strchr(domain, '.'))) {
5618 			(void) strncpy(domain, cp + 1, sizeof (domain));
5619 		} else
5620 			domain[0] = 0;
5621 	}
5622 	cp = NULL;
5623 	if (!Nflag) {
5624 		hp = getipnodebyaddr((char *)addr,
5625 		    sizeof (struct in6_addr), AF_INET6, &error_num);
5626 		if (hp) {
5627 			if ((cp = strchr(hp->h_name, '.')) != NULL &&
5628 			    strcasecmp(cp + 1, domain) == 0)
5629 				*cp = 0;
5630 			cp = hp->h_name;
5631 		}
5632 	}
5633 	if (cp != NULL) {
5634 		(void) strncpy(dst, cp, dstlen);
5635 		dst[dstlen - 1] = 0;
5636 	} else {
5637 		(void) inet_ntop(AF_INET6, (void *)addr, dst, dstlen);
5638 	}
5639 	if (hp != NULL)
5640 		freehostent(hp);
5641 	return (dst);
5642 }
5643 
5644 /* For IPv4 masks */
5645 static char *
5646 pr_mask(uint_t addr, char *dst, uint_t dstlen)
5647 {
5648 	uint8_t	*ip_addr = (uint8_t *)&addr;
5649 
5650 	(void) snprintf(dst, dstlen, "%d.%d.%d.%d",
5651 	    ip_addr[0], ip_addr[1], ip_addr[2], ip_addr[3]);
5652 	return (dst);
5653 }
5654 
5655 /*
5656  * For ipv6 masks format is : dest/mask
5657  * Does not print /128 to save space in printout. H flag carries this notion.
5658  */
5659 static char *
5660 pr_prefix6(const struct in6_addr *addr, uint_t prefixlen, char *dst,
5661     uint_t dstlen)
5662 {
5663 	char *cp;
5664 
5665 	if (IN6_IS_ADDR_UNSPECIFIED(addr) && prefixlen == 0) {
5666 		(void) strncpy(dst, "default", dstlen);
5667 		dst[dstlen - 1] = 0;
5668 		return (dst);
5669 	}
5670 
5671 	(void) pr_addr6(addr, dst, dstlen);
5672 	if (prefixlen != IPV6_ABITS) {
5673 		/* How much room is left? */
5674 		cp = strchr(dst, '\0');
5675 		if (dst + dstlen > cp) {
5676 			dstlen -= (cp - dst);
5677 			(void) snprintf(cp, dstlen, "/%d", prefixlen);
5678 		}
5679 	}
5680 	return (dst);
5681 }
5682 
5683 /* Print IPv4 address and port */
5684 static char *
5685 pr_ap(uint_t addr, uint_t port, char *proto,
5686     char *dst, uint_t dstlen)
5687 {
5688 	char *cp;
5689 
5690 	if (addr == INADDR_ANY) {
5691 		(void) strncpy(dst, "      *", dstlen);
5692 		dst[dstlen - 1] = 0;
5693 	} else {
5694 		(void) pr_addr(addr, dst, dstlen);
5695 	}
5696 	/* How much room is left? */
5697 	cp = strchr(dst, '\0');
5698 	if (dst + dstlen > cp + 1) {
5699 		*cp++ = '.';
5700 		dstlen -= (cp - dst);
5701 		dstlen--;
5702 		(void) portname(port, proto, cp, dstlen);
5703 	}
5704 	return (dst);
5705 }
5706 
5707 /* Print IPv6 address and port */
5708 static char *
5709 pr_ap6(const in6_addr_t *addr, uint_t port, char *proto,
5710     char *dst, uint_t dstlen)
5711 {
5712 	char *cp;
5713 
5714 	if (IN6_IS_ADDR_UNSPECIFIED(addr)) {
5715 		(void) strncpy(dst, "      *", dstlen);
5716 		dst[dstlen - 1] = 0;
5717 	} else {
5718 		(void) pr_addr6(addr, dst, dstlen);
5719 	}
5720 	/* How much room is left? */
5721 	cp = strchr(dst, '\0');
5722 	if (dst + dstlen + 1 > cp) {
5723 		*cp++ = '.';
5724 		dstlen -= (cp - dst);
5725 		dstlen--;
5726 		(void) portname(port, proto, cp, dstlen);
5727 	}
5728 	return (dst);
5729 }
5730 
5731 /*
5732  * Return the name of the network whose address is given. The address is
5733  * assumed to be that of a net or subnet, not a host.
5734  */
5735 static char *
5736 pr_net(uint_t addr, uint_t mask, char *dst, uint_t dstlen)
5737 {
5738 	char		*cp = NULL;
5739 	struct netent	*np = NULL;
5740 	struct hostent	*hp = NULL;
5741 	uint_t		net;
5742 	int		subnetshift;
5743 	int		error_num;
5744 
5745 	if (addr == INADDR_ANY && mask == INADDR_ANY) {
5746 		(void) strncpy(dst, "default", dstlen);
5747 		dst[dstlen - 1] = 0;
5748 		return (dst);
5749 	}
5750 
5751 	if (!Nflag && addr) {
5752 		if (mask == 0) {
5753 			if (IN_CLASSA(addr)) {
5754 				mask = (uint_t)IN_CLASSA_NET;
5755 				subnetshift = 8;
5756 			} else if (IN_CLASSB(addr)) {
5757 				mask = (uint_t)IN_CLASSB_NET;
5758 				subnetshift = 8;
5759 			} else {
5760 				mask = (uint_t)IN_CLASSC_NET;
5761 				subnetshift = 4;
5762 			}
5763 			/*
5764 			 * If there are more bits than the standard mask
5765 			 * would suggest, subnets must be in use. Guess at
5766 			 * the subnet mask, assuming reasonable width subnet
5767 			 * fields.
5768 			 */
5769 			while (addr & ~mask)
5770 				/* compiler doesn't sign extend! */
5771 				mask = (mask | ((int)mask >> subnetshift));
5772 		}
5773 		net = addr & mask;
5774 		while ((mask & 1) == 0)
5775 			mask >>= 1, net >>= 1;
5776 		np = getnetbyaddr(net, AF_INET);
5777 		if (np && np->n_net == net)
5778 			cp = np->n_name;
5779 		else {
5780 			/*
5781 			 * Look for subnets in hosts map.
5782 			 */
5783 			hp = getipnodebyaddr((char *)&addr, sizeof (uint_t),
5784 			    AF_INET, &error_num);
5785 			if (hp)
5786 				cp = hp->h_name;
5787 		}
5788 	}
5789 	if (cp != NULL) {
5790 		(void) strncpy(dst, cp, dstlen);
5791 		dst[dstlen - 1] = 0;
5792 	} else {
5793 		(void) inet_ntop(AF_INET, (char *)&addr, dst, dstlen);
5794 	}
5795 	if (hp != NULL)
5796 		freehostent(hp);
5797 	return (dst);
5798 }
5799 
5800 /*
5801  * Return the name of the network whose address is given.
5802  * The address is assumed to be a host address.
5803  */
5804 static char *
5805 pr_netaddr(uint_t addr, uint_t mask, char *dst, uint_t dstlen)
5806 {
5807 	char		*cp = NULL;
5808 	struct netent	*np = NULL;
5809 	struct hostent	*hp = NULL;
5810 	uint_t		net;
5811 	uint_t		netshifted;
5812 	int		subnetshift;
5813 	struct in_addr in;
5814 	int		error_num;
5815 	uint_t		nbo_addr = addr;	/* network byte order */
5816 
5817 	addr = ntohl(addr);
5818 	mask = ntohl(mask);
5819 	if (addr == INADDR_ANY && mask == INADDR_ANY) {
5820 		(void) strncpy(dst, "default", dstlen);
5821 		dst[dstlen - 1] = 0;
5822 		return (dst);
5823 	}
5824 
5825 	/* Figure out network portion of address (with host portion = 0) */
5826 	if (addr) {
5827 		/* Try figuring out mask if unknown (all 0s). */
5828 		if (mask == 0) {
5829 			if (IN_CLASSA(addr)) {
5830 				mask = (uint_t)IN_CLASSA_NET;
5831 				subnetshift = 8;
5832 			} else if (IN_CLASSB(addr)) {
5833 				mask = (uint_t)IN_CLASSB_NET;
5834 				subnetshift = 8;
5835 			} else {
5836 				mask = (uint_t)IN_CLASSC_NET;
5837 				subnetshift = 4;
5838 			}
5839 			/*
5840 			 * If there are more bits than the standard mask
5841 			 * would suggest, subnets must be in use. Guess at
5842 			 * the subnet mask, assuming reasonable width subnet
5843 			 * fields.
5844 			 */
5845 			while (addr & ~mask)
5846 				/* compiler doesn't sign extend! */
5847 				mask = (mask | ((int)mask >> subnetshift));
5848 		}
5849 		net = netshifted = addr & mask;
5850 		while ((mask & 1) == 0)
5851 			mask >>= 1, netshifted >>= 1;
5852 	}
5853 	else
5854 		net = netshifted = 0;
5855 
5856 	/* Try looking up name unless -n was specified. */
5857 	if (!Nflag) {
5858 		np = getnetbyaddr(netshifted, AF_INET);
5859 		if (np && np->n_net == netshifted)
5860 			cp = np->n_name;
5861 		else {
5862 			/*
5863 			 * Look for subnets in hosts map.
5864 			 */
5865 			hp = getipnodebyaddr((char *)&nbo_addr, sizeof (uint_t),
5866 			    AF_INET, &error_num);
5867 			if (hp)
5868 				cp = hp->h_name;
5869 		}
5870 
5871 		if (cp != NULL) {
5872 			(void) strncpy(dst, cp, dstlen);
5873 			dst[dstlen - 1] = 0;
5874 			if (hp != NULL)
5875 				freehostent(hp);
5876 			return (dst);
5877 		}
5878 		/*
5879 		 * No name found for net: fallthru and return in decimal
5880 		 * dot notation.
5881 		 */
5882 	}
5883 
5884 	in.s_addr = htonl(net);
5885 	(void) inet_ntop(AF_INET, (char *)&in, dst, dstlen);
5886 	if (hp != NULL)
5887 		freehostent(hp);
5888 	return (dst);
5889 }
5890 
5891 /*
5892  * Return the filter mode as a string:
5893  *	1 => "INCLUDE"
5894  *	2 => "EXCLUDE"
5895  *	otherwise "<unknown>"
5896  */
5897 static char *
5898 fmodestr(uint_t fmode)
5899 {
5900 	switch (fmode) {
5901 	case 1:
5902 		return ("INCLUDE");
5903 	case 2:
5904 		return ("EXCLUDE");
5905 	default:
5906 		return ("<unknown>");
5907 	}
5908 }
5909 
5910 #define	MAX_STRING_SIZE	256
5911 
5912 static const char *
5913 pr_secattr(const sec_attr_list_t *attrs)
5914 {
5915 	int i;
5916 	char buf[MAX_STRING_SIZE + 1], *cp;
5917 	static char *sbuf;
5918 	static size_t sbuf_len;
5919 	struct rtsa_s rtsa;
5920 	const sec_attr_list_t *aptr;
5921 
5922 	if (!RSECflag || attrs == NULL)
5923 		return ("");
5924 
5925 	for (aptr = attrs, i = 1; aptr != NULL; aptr = aptr->sal_next)
5926 		i += MAX_STRING_SIZE;
5927 	if (i > sbuf_len) {
5928 		cp = realloc(sbuf, i);
5929 		if (cp == NULL) {
5930 			perror("realloc security attribute buffer");
5931 			return ("");
5932 		}
5933 		sbuf_len = i;
5934 		sbuf = cp;
5935 	}
5936 
5937 	cp = sbuf;
5938 	while (attrs != NULL) {
5939 		const mib2_ipAttributeEntry_t *iae = attrs->sal_attr;
5940 
5941 		/* note: effectively hard-coded in rtsa_keyword */
5942 		rtsa.rtsa_mask = RTSA_CIPSO | RTSA_SLRANGE | RTSA_DOI;
5943 		rtsa.rtsa_slrange = iae->iae_slrange;
5944 		rtsa.rtsa_doi = iae->iae_doi;
5945 
5946 		(void) snprintf(cp, MAX_STRING_SIZE,
5947 		    "<%s>%s ", rtsa_to_str(&rtsa, buf, sizeof (buf)),
5948 		    attrs->sal_next == NULL ? "" : ",");
5949 		cp += strlen(cp);
5950 		attrs = attrs->sal_next;
5951 	}
5952 	*cp = '\0';
5953 
5954 	return (sbuf);
5955 }
5956 
5957 /*
5958  * Pretty print a port number. If the Nflag was
5959  * specified, use numbers instead of names.
5960  */
5961 static char *
5962 portname(uint_t port, char *proto, char *dst, uint_t dstlen)
5963 {
5964 	struct servent *sp = NULL;
5965 
5966 	if (!Nflag && port)
5967 		sp = getservbyport(htons(port), proto);
5968 	if (sp || port == 0)
5969 		(void) snprintf(dst, dstlen, "%.*s", MAXHOSTNAMELEN,
5970 		    sp ? sp->s_name : "*");
5971 	else
5972 		(void) snprintf(dst, dstlen, "%d", port);
5973 	dst[dstlen - 1] = 0;
5974 	return (dst);
5975 }
5976 
5977 /*PRINTFLIKE2*/
5978 void
5979 fail(int do_perror, char *message, ...)
5980 {
5981 	va_list args;
5982 
5983 	va_start(args, message);
5984 	(void) fputs("netstat: ", stderr);
5985 	(void) vfprintf(stderr, message, args);
5986 	va_end(args);
5987 	if (do_perror)
5988 		(void) fprintf(stderr, ": %s", strerror(errno));
5989 	(void) fputc('\n', stderr);
5990 	exit(2);
5991 }
5992 
5993 /*
5994  * Return value of named statistic for given kstat_named kstat;
5995  * return 0LL if named statistic is not in list (use "ll" as a
5996  * type qualifier when printing 64-bit int's with printf() )
5997  */
5998 static uint64_t
5999 kstat_named_value(kstat_t *ksp, char *name)
6000 {
6001 	kstat_named_t *knp;
6002 	uint64_t value;
6003 
6004 	if (ksp == NULL)
6005 		return (0LL);
6006 
6007 	knp = kstat_data_lookup(ksp, name);
6008 	if (knp == NULL)
6009 		return (0LL);
6010 
6011 	switch (knp->data_type) {
6012 	case KSTAT_DATA_INT32:
6013 	case KSTAT_DATA_UINT32:
6014 		value = (uint64_t)(knp->value.ui32);
6015 		break;
6016 	case KSTAT_DATA_INT64:
6017 	case KSTAT_DATA_UINT64:
6018 		value = knp->value.ui64;
6019 		break;
6020 	default:
6021 		value = 0LL;
6022 		break;
6023 	}
6024 
6025 	return (value);
6026 }
6027 
6028 kid_t
6029 safe_kstat_read(kstat_ctl_t *kc, kstat_t *ksp, void *data)
6030 {
6031 	kid_t kstat_chain_id = kstat_read(kc, ksp, data);
6032 
6033 	if (kstat_chain_id == -1)
6034 		fail(1, "kstat_read(%p, '%s') failed", (void *)kc,
6035 		    ksp->ks_name);
6036 	return (kstat_chain_id);
6037 }
6038 
6039 /*
6040  * Parse a list of IRE flag characters into a bit field.
6041  */
6042 static uint_t
6043 flag_bits(const char *arg)
6044 {
6045 	const char *cp;
6046 	uint_t val;
6047 
6048 	if (*arg == '\0')
6049 		fatal(1, "missing flag list\n");
6050 
6051 	val = 0;
6052 	while (*arg != '\0') {
6053 		if ((cp = strchr(flag_list, *arg)) == NULL)
6054 			fatal(1, "%c: illegal flag\n", *arg);
6055 		val |= 1 << (cp - flag_list);
6056 		arg++;
6057 	}
6058 	return (val);
6059 }
6060 
6061 /*
6062  * Handle -f argument.  Validate input format, sort by keyword, and
6063  * save off digested results.
6064  */
6065 static void
6066 process_filter(char *arg)
6067 {
6068 	int idx;
6069 	int klen = 0;
6070 	char *cp, *cp2;
6071 	int val;
6072 	filter_t *newf;
6073 	struct hostent *hp;
6074 	int error_num;
6075 	uint8_t *ucp;
6076 	int maxv;
6077 
6078 	/* Look up the keyword first */
6079 	if (strchr(arg, ':') == NULL) {
6080 		idx = FK_AF;
6081 	} else {
6082 		for (idx = 0; idx < NFILTERKEYS; idx++) {
6083 			klen = strlen(filter_keys[idx]);
6084 			if (strncmp(filter_keys[idx], arg, klen) == 0 &&
6085 			    arg[klen] == ':')
6086 				break;
6087 		}
6088 		if (idx >= NFILTERKEYS)
6089 			fatal(1, "%s: unknown filter keyword\n", arg);
6090 
6091 		/* Advance past keyword and separator. */
6092 		arg += klen + 1;
6093 	}
6094 
6095 	if ((newf = malloc(sizeof (*newf))) == NULL) {
6096 		perror("filter");
6097 		exit(1);
6098 	}
6099 	switch (idx) {
6100 	case FK_AF:
6101 		if (strcmp(arg, "inet") == 0) {
6102 			newf->u.f_family = AF_INET;
6103 		} else if (strcmp(arg, "inet6") == 0) {
6104 			newf->u.f_family = AF_INET6;
6105 		} else if (strcmp(arg, "unix") == 0) {
6106 			newf->u.f_family = AF_UNIX;
6107 		} else {
6108 			newf->u.f_family = strtol(arg, &cp, 0);
6109 			if (arg == cp || *cp != '\0')
6110 				fatal(1, "%s: unknown address family.\n", arg);
6111 		}
6112 		break;
6113 
6114 	case FK_OUTIF:
6115 		if (strcmp(arg, "none") == 0) {
6116 			newf->u.f_ifname = NULL;
6117 			break;
6118 		}
6119 		if (strcmp(arg, "any") == 0) {
6120 			newf->u.f_ifname = "";
6121 			break;
6122 		}
6123 		val = strtol(arg, &cp, 0);
6124 		if (val <= 0 || arg == cp || cp[0] != '\0') {
6125 			if ((val = if_nametoindex(arg)) == 0) {
6126 				perror(arg);
6127 				exit(1);
6128 			}
6129 		}
6130 		newf->u.f_ifname = arg;
6131 		break;
6132 
6133 	case FK_DST:
6134 		V4MASK_TO_V6(IP_HOST_MASK, newf->u.a.f_mask);
6135 		if (strcmp(arg, "any") == 0) {
6136 			/* Special semantics; any address *but* zero */
6137 			newf->u.a.f_address = NULL;
6138 			(void) memset(&newf->u.a.f_mask, 0,
6139 			    sizeof (newf->u.a.f_mask));
6140 			break;
6141 		}
6142 		if (strcmp(arg, "none") == 0) {
6143 			newf->u.a.f_address = NULL;
6144 			break;
6145 		}
6146 		if ((cp = strrchr(arg, '/')) != NULL)
6147 			*cp++ = '\0';
6148 		hp = getipnodebyname(arg, AF_INET6, AI_V4MAPPED|AI_ALL,
6149 		    &error_num);
6150 		if (hp == NULL)
6151 			fatal(1, "%s: invalid or unknown host address\n", arg);
6152 		newf->u.a.f_address = hp;
6153 		if (cp == NULL) {
6154 			V4MASK_TO_V6(IP_HOST_MASK, newf->u.a.f_mask);
6155 		} else {
6156 			val = strtol(cp, &cp2, 0);
6157 			if (cp != cp2 && cp2[0] == '\0') {
6158 				/*
6159 				 * If decode as "/n" works, then translate
6160 				 * into a mask.
6161 				 */
6162 				if (hp->h_addr_list[0] != NULL &&
6163 				    /* LINTED: (note 1) */
6164 				    IN6_IS_ADDR_V4MAPPED((in6_addr_t *)
6165 				    hp->h_addr_list[0])) {
6166 					maxv = IP_ABITS;
6167 				} else {
6168 					maxv = IPV6_ABITS;
6169 				}
6170 				if (val < 0 || val >= maxv)
6171 					fatal(1, "%d: not in range 0 to %d\n",
6172 					    val, maxv - 1);
6173 				if (maxv == IP_ABITS)
6174 					val += IPV6_ABITS - IP_ABITS;
6175 				ucp = newf->u.a.f_mask.s6_addr;
6176 				while (val >= 8)
6177 					*ucp++ = 0xff, val -= 8;
6178 				*ucp++ = (0xff << (8 - val)) & 0xff;
6179 				while (ucp < newf->u.a.f_mask.s6_addr +
6180 				    sizeof (newf->u.a.f_mask.s6_addr))
6181 					*ucp++ = 0;
6182 				/* Otherwise, try as numeric address */
6183 			} else if (inet_pton(AF_INET6,
6184 			    cp, &newf->u.a.f_mask) <= 0) {
6185 				fatal(1, "%s: illegal mask format\n", cp);
6186 			}
6187 		}
6188 		break;
6189 
6190 	case FK_FLAGS:
6191 		if (*arg == '+') {
6192 			newf->u.f.f_flagset = flag_bits(arg + 1);
6193 			newf->u.f.f_flagclear = 0;
6194 		} else if (*arg == '-') {
6195 			newf->u.f.f_flagset = 0;
6196 			newf->u.f.f_flagclear = flag_bits(arg + 1);
6197 		} else {
6198 			newf->u.f.f_flagset = flag_bits(arg);
6199 			newf->u.f.f_flagclear = ~newf->u.f.f_flagset;
6200 		}
6201 		break;
6202 
6203 	default:
6204 		assert(0);
6205 	}
6206 	newf->f_next = filters[idx];
6207 	filters[idx] = newf;
6208 }
6209 
6210 /* Determine if user wants this address family printed. */
6211 static boolean_t
6212 family_selected(int family)
6213 {
6214 	const filter_t *fp;
6215 
6216 	if (v4compat && family == AF_INET6)
6217 		return (B_FALSE);
6218 	if ((fp = filters[FK_AF]) == NULL)
6219 		return (B_TRUE);
6220 	while (fp != NULL) {
6221 		if (fp->u.f_family == family)
6222 			return (B_TRUE);
6223 		fp = fp->f_next;
6224 	}
6225 	return (B_FALSE);
6226 }
6227 
6228 /*
6229  * Convert the interface index to a string using the buffer `ifname', which
6230  * must be at least LIFNAMSIZ bytes.  We first try to map it to name.  If that
6231  * fails (e.g., because we're inside a zone and it does not have access to
6232  * interface for the index in question), just return "if#<num>".
6233  */
6234 static char *
6235 ifindex2str(uint_t ifindex, char *ifname)
6236 {
6237 	if (if_indextoname(ifindex, ifname) == NULL)
6238 		(void) snprintf(ifname, LIFNAMSIZ, "if#%d", ifindex);
6239 
6240 	return (ifname);
6241 }
6242 
6243 /*
6244  * print the usage line
6245  */
6246 static void
6247 usage(char *cmdname)
6248 {
6249 	(void) fprintf(stderr, "usage: %s [-anv] [-f address_family] "
6250 	    "[-T d|u]\n", cmdname);
6251 	(void) fprintf(stderr, "       %s [-n] [-f address_family] "
6252 	    "[-P protocol] [-T d|u] [-g | -p | -s [interval [count]]]\n",
6253 	    cmdname);
6254 	(void) fprintf(stderr, "       %s -m [-v] [-T d|u] "
6255 	    "[interval [count]]\n", cmdname);
6256 	(void) fprintf(stderr, "       %s -i [-I interface] [-an] "
6257 	    "[-f address_family] [-T d|u] [interval [count]]\n", cmdname);
6258 	(void) fprintf(stderr, "       %s -r [-anv] "
6259 	    "[-f address_family|filter] [-T d|u]\n", cmdname);
6260 	(void) fprintf(stderr, "       %s -M [-ns] [-f address_family] "
6261 	    "[-T d|u]\n", cmdname);
6262 	(void) fprintf(stderr, "       %s -D [-I interface] "
6263 	    "[-f address_family] [-T d|u]\n", cmdname);
6264 	exit(EXIT_FAILURE);
6265 }
6266 
6267 /*
6268  * fatal: print error message to stderr and
6269  * call exit(errcode)
6270  */
6271 /*PRINTFLIKE2*/
6272 static void
6273 fatal(int errcode, char *format, ...)
6274 {
6275 	va_list argp;
6276 
6277 	if (format == NULL)
6278 		return;
6279 
6280 	va_start(argp, format);
6281 	(void) vfprintf(stderr, format, argp);
6282 	va_end(argp);
6283 
6284 	exit(errcode);
6285 }
6286