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