xref: /netbsd-src/usr.bin/fstat/fstat.c (revision 6d322f2f4598f0d8a138f10ea648ec4fabe41f8b)
1 /*	$NetBSD: fstat.c,v 1.106 2013/12/15 18:56:59 mlelstv Exp $	*/
2 
3 /*-
4  * Copyright (c) 1988, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #ifndef lint
34 __COPYRIGHT("@(#) Copyright (c) 1988, 1993\
35  The Regents of the University of California.  All rights reserved.");
36 #endif /* not lint */
37 
38 #ifndef lint
39 #if 0
40 static char sccsid[] = "@(#)fstat.c	8.3 (Berkeley) 5/2/95";
41 #else
42 __RCSID("$NetBSD: fstat.c,v 1.106 2013/12/15 18:56:59 mlelstv Exp $");
43 #endif
44 #endif /* not lint */
45 
46 #include <sys/types.h>
47 #include <sys/param.h>
48 #include <sys/time.h>
49 #include <sys/proc.h>
50 #include <sys/stat.h>
51 #include <sys/vnode.h>
52 #include <sys/socket.h>
53 #include <sys/socketvar.h>
54 #include <sys/domain.h>
55 #include <sys/protosw.h>
56 #include <sys/unpcb.h>
57 #include <sys/sysctl.h>
58 #include <sys/filedesc.h>
59 #include <sys/pipe.h>
60 #define _KERNEL
61 #include <sys/mount.h>
62 #undef _KERNEL
63 #define	_KERNEL
64 #include <sys/file.h>
65 #include <ufs/ufs/inode.h>
66 #include <ufs/ufs/ufsmount.h>
67 #undef _KERNEL
68 #define NFS
69 #include <nfs/nfsproto.h>
70 #include <nfs/rpcv2.h>
71 #include <nfs/nfs.h>
72 #include <nfs/nfsnode.h>
73 #undef NFS
74 #include <msdosfs/denode.h>
75 #include <msdosfs/bpb.h>
76 #define	_KERNEL
77 #include <msdosfs/msdosfsmount.h>
78 #undef _KERNEL
79 #define	_KERNEL
80 #include <miscfs/genfs/layer.h>
81 #undef _KERNEL
82 
83 #include <net/route.h>
84 #include <netinet/in.h>
85 #include <netinet/in_systm.h>
86 #include <netinet/ip.h>
87 #include <netinet/in_pcb.h>
88 
89 #ifdef INET6
90 #include <netinet/ip6.h>
91 #include <netinet6/in6.h>
92 #include <netinet6/ip6_var.h>
93 #include <netinet6/in6_pcb.h>
94 #endif
95 
96 #include <netatalk/at.h>
97 #include <netatalk/ddp_var.h>
98 
99 #include <netdb.h>
100 #include <arpa/inet.h>
101 
102 #include <ctype.h>
103 #include <errno.h>
104 #include <kvm.h>
105 #include <limits.h>
106 #include <nlist.h>
107 #include <paths.h>
108 #include <pwd.h>
109 #include <stdio.h>
110 #include <stdlib.h>
111 #include <string.h>
112 #include <unistd.h>
113 #include <err.h>
114 #include <util.h>
115 
116 #include "fstat.h"
117 
118 #define	TEXT	-1
119 #define	CDIR	-2
120 #define	RDIR	-3
121 #define	TRACE	-4
122 
123 typedef struct devs {
124 	struct	devs *next;
125 	long	fsid;
126 	ino_t	ino;
127 	const char *name;
128 } DEVS;
129 static DEVS *devs;
130 
131 static int 	fsflg,	/* show files on same filesystem as file(s) argument */
132 	pflg,	/* show files open by a particular pid */
133 	uflg;	/* show files open by a particular (effective) user */
134 static int 	checkfile; /* true if restricting to particular files or filesystems */
135 static int	nflg;	/* (numerical) display f.s. and rdev as dev_t */
136 static int	Aflg;	/* prefix with address of file structure */
137 int	vflg;	/* display errors in locating kernel data objects etc... */
138 
139 static fdfile_t **ofiles; /* buffer of pointers to file structures */
140 static int fstat_maxfiles;
141 #define ALLOC_OFILES(d)	\
142 	if ((d) > fstat_maxfiles) { \
143 		size_t len = (d) * sizeof(fdfile_t *); \
144 		free(ofiles); \
145 		ofiles = malloc(len); \
146 		if (ofiles == NULL) { \
147 			err(1, "malloc(%zu)", len);	\
148 		} \
149 		fstat_maxfiles = (d); \
150 	}
151 
152 kvm_t *kd;
153 
154 static const char *const dtypes[] = {
155 	DTYPE_NAMES
156 };
157 
158 static void	dofiles(struct kinfo_proc2 *);
159 static int	ext2fs_filestat(struct vnode *, struct filestat *);
160 static int	getfname(const char *);
161 static void	getinetproto(int);
162 static void	getatproto(int);
163 static char   *getmnton(struct mount *);
164 static const char   *layer_filestat(struct vnode *, struct filestat *);
165 static int	msdosfs_filestat(struct vnode *, struct filestat *);
166 static int	nfs_filestat(struct vnode *, struct filestat *);
167 static const char *inet_addrstr(char *, size_t, const struct in_addr *,
168     uint16_t);
169 #ifdef INET6
170 static const char *inet6_addrstr(char *, size_t, const struct in6_addr *,
171     uint16_t);
172 #endif
173 static const char *at_addrstr(char *, size_t, const struct sockaddr_at *);
174 static void	socktrans(struct socket *, int);
175 static void	misctrans(struct file *, int);
176 static int	ufs_filestat(struct vnode *, struct filestat *);
177 static void	usage(void) __dead;
178 static const char   *vfilestat(struct vnode *, struct filestat *);
179 static void	vtrans(struct vnode *, int, int, long);
180 static void	ftrans(fdfile_t *, int);
181 static void	ptrans(struct file *, struct pipe *, int);
182 static void	kdriver_init(void);
183 
184 int
185 main(int argc, char **argv)
186 {
187 	struct passwd *passwd;
188 	struct kinfo_proc2 *p, *plast;
189 	int arg, ch, what;
190 	char *memf, *nlistf;
191 	char buf[_POSIX2_LINE_MAX];
192 	int cnt;
193 	gid_t egid = getegid();
194 
195 	(void)setegid(getgid());
196 	arg = 0;
197 	what = KERN_PROC_ALL;
198 	nlistf = memf = NULL;
199 	while ((ch = getopt(argc, argv, "fnAp:u:vN:M:")) != -1)
200 		switch((char)ch) {
201 		case 'f':
202 			fsflg = 1;
203 			break;
204 		case 'M':
205 			memf = optarg;
206 			break;
207 		case 'N':
208 			nlistf = optarg;
209 			break;
210 		case 'n':
211 			nflg = 1;
212 			break;
213 		case 'A':
214 			Aflg = 1;
215 			break;
216 		case 'p':
217 			if (pflg++)
218 				usage();
219 			if (!isdigit((unsigned char)*optarg)) {
220 				warnx("-p requires a process id");
221 				usage();
222 			}
223 			what = KERN_PROC_PID;
224 			arg = atoi(optarg);
225 			break;
226 		case 'u':
227 			if (uflg++)
228 				usage();
229 			if (!(passwd = getpwnam(optarg))) {
230 				errx(1, "%s: unknown uid", optarg);
231 			}
232 			what = KERN_PROC_UID;
233 			arg = passwd->pw_uid;
234 			break;
235 		case 'v':
236 			vflg = 1;
237 			break;
238 		case '?':
239 		default:
240 			usage();
241 		}
242 
243 	kdriver_init();
244 
245 	if (*(argv += optind)) {
246 		for (; *argv; ++argv) {
247 			if (getfname(*argv))
248 				checkfile = 1;
249 		}
250 		if (!checkfile)	/* file(s) specified, but none accessible */
251 			exit(1);
252 	}
253 
254 	ALLOC_OFILES(256);	/* reserve space for file pointers */
255 
256 	if (fsflg && !checkfile) {
257 		/* -f with no files means use wd */
258 		if (getfname(".") == 0)
259 			exit(1);
260 		checkfile = 1;
261 	}
262 
263 	/*
264 	 * Discard setgid privileges.  If not the running kernel, we toss
265 	 * them away totally so that bad guys can't print interesting stuff
266 	 * from kernel memory, otherwise switch back to kmem for the
267 	 * duration of the kvm_openfiles() call.
268 	 */
269 	if (nlistf != NULL || memf != NULL)
270 		(void)setgid(getgid());
271 	else
272 		(void)setegid(egid);
273 
274 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, buf)) == NULL)
275 		errx(1, "%s", buf);
276 
277 	/* get rid of it now anyway */
278 	if (nlistf == NULL && memf == NULL)
279 		(void)setgid(getgid());
280 
281 	if ((p = kvm_getproc2(kd, what, arg, sizeof *p, &cnt)) == NULL) {
282 		errx(1, "%s", kvm_geterr(kd));
283 	}
284 	if (Aflg)
285 		(void)printf("%-*s ", 2*(int)(sizeof(void*)), "ADDR");
286 	if (nflg)
287 		(void)printf("%s",
288 "USER     CMD          PID   FD  DEV     INUM  MODE  SZ|DV R/W");
289 	else
290 		(void)printf("%s",
291 "USER     CMD          PID   FD MOUNT       INUM MODE         SZ|DV R/W");
292 	if (checkfile && fsflg == 0)
293 		(void)printf(" NAME\n");
294 	else
295 		(void)putchar('\n');
296 
297 	for (plast = &p[cnt]; p < plast; ++p) {
298 		if (p->p_stat == SZOMB)
299 			continue;
300 		dofiles(p);
301 	}
302 	return 0;
303 }
304 
305 static const	char *Uname, *Comm;
306 pid_t	Pid;
307 
308 #define PREFIX(i) (void)printf("%-8.8s %-10s %5d", Uname, Comm, Pid); \
309 	switch(i) { \
310 	case TEXT: \
311 		(void)printf(" text"); \
312 		break; \
313 	case CDIR: \
314 		(void)printf("   wd"); \
315 		break; \
316 	case RDIR: \
317 		(void)printf(" root"); \
318 		break; \
319 	case TRACE: \
320 		(void)printf("   tr"); \
321 		break; \
322 	default: \
323 		(void)printf(" %4d", i); \
324 		break; \
325 	}
326 
327 static struct kinfo_drivers *kdriver;
328 static size_t kdriverlen;
329 
330 static int
331 kdriver_comp(const void *a, const void *b)
332 {
333 	const struct kinfo_drivers *ka = a;
334 	const struct kinfo_drivers *kb = b;
335 	int kac = ka->d_cmajor == -1 ? 0 : ka->d_cmajor;
336 	int kbc = kb->d_cmajor == -1 ? 0 : kb->d_cmajor;
337 	int kab = ka->d_bmajor == -1 ? 0 : ka->d_bmajor;
338 	int kbb = kb->d_bmajor == -1 ? 0 : kb->d_bmajor;
339 	int c = kac - kbc;
340 	if (c == 0)
341 		return kab - kbb;
342 	else
343 		return c;
344 }
345 
346 static const char *
347 kdriver_search(int type, dev_t num)
348 {
349 	struct kinfo_drivers k, *kp;
350 	static char buf[64];
351 
352 	if (nflg)
353 		goto out;
354 
355 	if (type == VBLK) {
356 		k.d_bmajor = num;
357 		k.d_cmajor = -1;
358 	} else {
359 		k.d_bmajor = -1;
360 		k.d_cmajor = num;
361 	}
362 	kp = bsearch(&k, kdriver, kdriverlen, sizeof(*kdriver), kdriver_comp);
363 	if (kp)
364 		return kp->d_name;
365 out:
366 	snprintf(buf, sizeof(buf), "%llu", (unsigned long long)num);
367 	return buf;
368 }
369 
370 
371 static void
372 kdriver_init(void)
373 {
374 	size_t sz;
375 	int error;
376 	static const int name[2] = { CTL_KERN, KERN_DRIVERS };
377 
378 	error = sysctl(name, __arraycount(name), NULL, &sz, NULL, 0);
379 	if (error == -1) {
380 		warn("sysctl kern.drivers");
381 		return;
382 	}
383 
384 	if (sz % sizeof(*kdriver)) {
385 		warnx("bad size %zu for kern.drivers", sz);
386 		return;
387 	}
388 
389 	kdriver = malloc(sz);
390 	if (kdriver == NULL) {
391 		warn("malloc");
392 		return;
393 	}
394 
395 	error = sysctl(name, __arraycount(name), kdriver, &sz, NULL, 0);
396 	if (error == -1) {
397 		warn("sysctl kern.drivers");
398 		return;
399 	}
400 
401 	kdriverlen = sz / sizeof(*kdriver);
402 	qsort(kdriver, kdriverlen, sizeof(*kdriver), kdriver_comp);
403 #ifdef DEBUG
404 	for (size_t i = 0; i < kdriverlen; i++)
405 		printf("%d %d %s\n", kdriver[i].d_cmajor, kdriver[i].d_bmajor,
406 		    kdriver[i].d_name);
407 #endif
408 }
409 
410 /*
411  * print open files attributed to this process
412  */
413 static void
414 dofiles(struct kinfo_proc2 *p)
415 {
416 	int i;
417 	struct filedesc filed;
418 	struct cwdinfo cwdi;
419 	struct fdtab dt;
420 
421 	Uname = user_from_uid(p->p_uid, 0);
422 	Pid = p->p_pid;
423 	Comm = p->p_comm;
424 
425 	if (p->p_fd == 0 || p->p_cwdi == 0)
426 		return;
427 	if (!KVM_READ(p->p_fd, &filed, sizeof (filed))) {
428 		warnx("can't read filedesc at %p for pid %d",
429 		    (void *)(uintptr_t)p->p_fd, Pid);
430 		return;
431 	}
432 	if (filed.fd_lastfile == -1)
433 		return;
434 	if (!KVM_READ(p->p_cwdi, &cwdi, sizeof(cwdi))) {
435 		warnx("can't read cwdinfo at %p for pid %d",
436 		    (void *)(uintptr_t)p->p_cwdi, Pid);
437 		return;
438 	}
439 	if (!KVM_READ(filed.fd_dt, &dt, sizeof(dt))) {
440 		warnx("can't read dtab at %p for pid %d", filed.fd_dt, Pid);
441 		return;
442 	}
443 	if ((unsigned)filed.fd_lastfile >= dt.dt_nfiles ||
444 	    filed.fd_freefile > filed.fd_lastfile + 1) {
445 		dprintf("filedesc corrupted at %p for pid %d",
446 		    (void *)(uintptr_t)p->p_fd, Pid);
447 		return;
448 	}
449 	/*
450 	 * root directory vnode, if one
451 	 */
452 	if (cwdi.cwdi_rdir)
453 		vtrans(cwdi.cwdi_rdir, RDIR, FREAD, (long)cwdi.cwdi_rdir);
454 	/*
455 	 * current working directory vnode
456 	 */
457 	vtrans(cwdi.cwdi_cdir, CDIR, FREAD, (long)cwdi.cwdi_cdir);
458 #if 0
459 	/*
460 	 * Disable for now, since p->p_tracep appears to point to a ktr_desc *
461 	 * ktrace vnode, if one
462 	 */
463 	if (p->p_tracep)
464 		ftrans(p->p_tracep, TRACE);
465 #endif
466 	/*
467 	 * open files
468 	 */
469 #define FPSIZE	(sizeof (fdfile_t *))
470 	ALLOC_OFILES(filed.fd_lastfile+1);
471 	if (!KVM_READ(&filed.fd_dt->dt_ff, ofiles,
472 	    (filed.fd_lastfile+1) * FPSIZE)) {
473 		dprintf("can't read file structures at %p for pid %d",
474 		    &filed.fd_dt->dt_ff, Pid);
475 		return;
476 	}
477 	for (i = 0; i <= filed.fd_lastfile; i++) {
478 		if (ofiles[i] == NULL)
479 			continue;
480 		ftrans(ofiles[i], i);
481 	}
482 }
483 
484 static void
485 ftrans(fdfile_t *fp, int i)
486 {
487 	struct file file;
488 	fdfile_t fdfile;
489 
490 	if (!KVM_READ(fp, &fdfile, sizeof(fdfile))) {
491 		dprintf("can't read file %d at %p for pid %d",
492 		    i, fp, Pid);
493 		return;
494 	}
495 	if (fdfile.ff_file == NULL) {
496 		dprintf("null ff_file for %d at %p for pid %d",
497 		    i, fp, Pid);
498 		return;
499 	}
500 	if (!KVM_READ(fdfile.ff_file, &file, sizeof(file))) {
501 		dprintf("can't read file %d at %p for pid %d",
502 		    i, fdfile.ff_file, Pid);
503 		return;
504 	}
505 	if (Aflg && file.f_type != DTYPE_VNODE && checkfile == 0)
506 		(void)printf("%*lx ",
507 			2*(int)(sizeof(void*)), (long)fdfile.ff_file);
508 	switch (file.f_type) {
509 	case DTYPE_VNODE:
510 		vtrans(file.f_data, i, file.f_flag, (long)fdfile.ff_file);
511 		break;
512 	case DTYPE_SOCKET:
513 		if (checkfile == 0)
514 			socktrans(file.f_data, i);
515 		break;
516 	case DTYPE_PIPE:
517 		if (checkfile == 0)
518 			ptrans(&file, file.f_data, i);
519 		break;
520 	case DTYPE_MISC:
521 	case DTYPE_KQUEUE:
522 	case DTYPE_CRYPTO:
523 	case DTYPE_MQUEUE:
524 	case DTYPE_SEM:
525 		if (checkfile == 0)
526 			misctrans(&file, i);
527 		break;
528 	default:
529 		dprintf("unknown file type %d for file %d of pid %d",
530 		    file.f_type, i, Pid);
531 		break;
532 	}
533 }
534 
535 static const char dead[] = "dead";
536 
537 static const char *
538 vfilestat(struct vnode *vp, struct filestat *fsp)
539 {
540 	const char *badtype = NULL;
541 
542 	if (vp->v_type == VNON)
543 		badtype = "none";
544 	else if (vp->v_type == VBAD)
545 		badtype = "bad";
546 	else
547 		switch (vp->v_tag) {
548 		case VT_NON:
549 			badtype = dead;
550 			break;
551 		case VT_UFS:
552 		case VT_LFS:
553 		case VT_MFS:
554 			if (!ufs_filestat(vp, fsp))
555 				badtype = "error";
556 			break;
557 		case VT_MSDOSFS:
558 			if (!msdosfs_filestat(vp, fsp))
559 				badtype = "error";
560 			break;
561 		case VT_NFS:
562 			if (!nfs_filestat(vp, fsp))
563 				badtype = "error";
564 			break;
565 		case VT_EXT2FS:
566 			if (!ext2fs_filestat(vp, fsp))
567 				badtype = "error";
568 			break;
569 		case VT_ISOFS:
570 			if (!isofs_filestat(vp, fsp))
571 				badtype = "error";
572 			break;
573 		case VT_NTFS:
574 			if (!ntfs_filestat(vp, fsp))
575 				badtype = "error";
576 			break;
577 		case VT_PTYFS:
578 			if (!ptyfs_filestat(vp, fsp))
579 				badtype = "error";
580 			break;
581 		case VT_TMPFS:
582 			if (!tmpfs_filestat(vp, fsp))
583 				badtype = "error";
584 			break;
585 		case VT_NULL:
586 		case VT_OVERLAY:
587 		case VT_UMAP:
588 			badtype = layer_filestat(vp, fsp);
589 			break;
590 		default: {
591 			static char unknown[10];
592 			(void)snprintf(unknown, sizeof unknown,
593 			    "?(%x)", vp->v_tag);
594 			badtype = unknown;
595 			break;
596 		}
597 	}
598 	return badtype;
599 }
600 
601 static void
602 vtrans(struct vnode *vp, int i, int flag, long addr)
603 {
604 	struct vnode vn;
605 	struct filestat fst;
606 	char mode[15], rw[3];
607 	const char *badtype, *filename;
608 
609 	filename = NULL;
610 	if (!KVM_READ(vp, &vn, sizeof(struct vnode))) {
611 		dprintf("can't read vnode at %p for pid %d", vp, Pid);
612 		return;
613 	}
614 	badtype = vfilestat(&vn, &fst);
615 	if (checkfile) {
616 		int fsmatch = 0;
617 		DEVS *d;
618 
619 		if (badtype && badtype != dead)
620 			return;
621 		for (d = devs; d != NULL; d = d->next)
622 			if (d->fsid == fst.fsid) {
623 				fsmatch = 1;
624 				if (d->ino == fst.fileid) {
625 					filename = d->name;
626 					break;
627 				}
628 			}
629 		if (fsmatch == 0 || (filename == NULL && fsflg == 0))
630 			return;
631 	}
632 	if (Aflg)
633 		(void)printf("%*lx ", 2*(int)(sizeof(void*)), addr);
634 	PREFIX(i);
635 	if (badtype == dead) {
636 		char buf[1024];
637 		(void)snprintb(buf, sizeof(buf), VNODE_FLAGBITS,
638 		    vn.v_iflag | vn.v_vflag | vn.v_uflag);
639 		(void)printf(" flags %s\n", buf);
640 		return;
641 	} else if (badtype) {
642 		(void)printf(" -         -  %10s    -\n", badtype);
643 		return;
644 	}
645 	if (nflg)
646 		(void)printf(" %2llu,%-2llu",
647 		    (unsigned long long)major(fst.fsid),
648 		    (unsigned long long)minor(fst.fsid));
649 	else
650 		(void)printf(" %-8s", getmnton(vn.v_mount));
651 	if (nflg)
652 		(void)snprintf(mode, sizeof mode, "%o", fst.mode);
653 	else
654 		strmode(fst.mode, mode);
655 	(void)printf(" %7"PRIu64" %*s", fst.fileid, nflg ? 5 : 10, mode);
656 	switch (vn.v_type) {
657 	case VBLK:
658 	case VCHR: {
659 		char *name;
660 
661 		if (nflg || ((name = devname(fst.rdev, vn.v_type == VCHR ?
662 		    S_IFCHR : S_IFBLK)) == NULL))
663 			(void)printf("  %s,%-2llu",
664 			    kdriver_search(vn.v_type, major(fst.rdev)),
665 			    (unsigned long long)minor(fst.rdev));
666 		else
667 			(void)printf(" %6s", name);
668 		break;
669 	}
670 	default:
671 		(void)printf(" %6lld", (long long)fst.size);
672 	}
673 	rw[0] = '\0';
674 	if (flag & FREAD)
675 		(void)strlcat(rw, "r", sizeof(rw));
676 	if (flag & FWRITE)
677 		(void)strlcat(rw, "w", sizeof(rw));
678 	(void)printf(" %-2s", rw);
679 	if (filename && !fsflg)
680 		(void)printf("  %s", filename);
681 	(void)putchar('\n');
682 }
683 
684 static int
685 ufs_filestat(struct vnode *vp, struct filestat *fsp)
686 {
687 	struct inode inode;
688 	struct ufsmount ufsmount;
689 	union dinode {
690 		struct ufs1_dinode dp1;
691 		struct ufs2_dinode dp2;
692 	} dip;
693 
694 	if (!KVM_READ(VTOI(vp), &inode, sizeof (inode))) {
695 		dprintf("can't read inode at %p for pid %d", VTOI(vp), Pid);
696 		return 0;
697 	}
698 
699 	if (!KVM_READ(inode.i_ump, &ufsmount, sizeof (struct ufsmount))) {
700 		dprintf("can't read ufsmount at %p for pid %d", inode.i_ump, Pid);
701 		return 0;
702 	}
703 
704 	switch (ufsmount.um_fstype) {
705 	case UFS1:
706 		if (!KVM_READ(inode.i_din.ffs1_din, &dip,
707 		    sizeof(struct ufs1_dinode))) {
708 			dprintf("can't read dinode at %p for pid %d",
709 				inode.i_din.ffs1_din, Pid);
710 			return 0;
711 		}
712 		fsp->rdev = dip.dp1.di_rdev;
713 		break;
714 	case UFS2:
715 		if (!KVM_READ(inode.i_din.ffs2_din, &dip,
716 		    sizeof(struct ufs2_dinode))) {
717 			dprintf("can't read dinode at %p for pid %d",
718 			    inode.i_din.ffs2_din, Pid);
719 			return 0;
720 		}
721 		fsp->rdev = dip.dp2.di_rdev;
722 		break;
723 	default:
724 		dprintf("unknown ufs type %ld for pid %d",
725 			ufsmount.um_fstype, Pid);
726 		break;
727 	}
728 	fsp->fsid = inode.i_dev & 0xffff;
729 	fsp->fileid = inode.i_number;
730 	fsp->mode = (mode_t)inode.i_mode;
731 	fsp->size = inode.i_size;
732 
733 	return 1;
734 }
735 
736 static int
737 ext2fs_filestat(struct vnode *vp, struct filestat *fsp)
738 {
739 	struct inode inode;
740 	struct ext2fs_dinode dinode;
741 
742 	if (!KVM_READ(VTOI(vp), &inode, sizeof (inode))) {
743 		dprintf("can't read inode at %p for pid %d", VTOI(vp), Pid);
744 		return 0;
745 	}
746 	fsp->fsid = inode.i_dev & 0xffff;
747 	fsp->fileid = inode.i_number;
748 
749 	if (!KVM_READ(inode.i_din.e2fs_din, &dinode, sizeof dinode)) {
750 		dprintf("can't read ext2fs_dinode at %p for pid %d",
751 			inode.i_din.e2fs_din, Pid);
752 		return 0;
753 	}
754 	fsp->mode = dinode.e2di_mode;
755 	fsp->size = dinode.e2di_size;
756 	fsp->rdev = dinode.e2di_rdev;
757 
758 	return 1;
759 }
760 
761 static int
762 nfs_filestat(struct vnode *vp, struct filestat *fsp)
763 {
764 	struct nfsnode nfsnode;
765 	struct vattr va;
766 
767 	if (!KVM_READ(VTONFS(vp), &nfsnode, sizeof (nfsnode))) {
768 		dprintf("can't read nfsnode at %p for pid %d", VTONFS(vp),
769 		    Pid);
770 		return 0;
771 	}
772 	if (!KVM_READ(nfsnode.n_vattr, &va, sizeof(va))) {
773 		dprintf("can't read vnode attributes at %p for pid %d",
774 		    nfsnode.n_vattr, Pid);
775 		return 0;
776 	}
777 	fsp->fsid = va.va_fsid;
778 	fsp->fileid = va.va_fileid;
779 	fsp->size = nfsnode.n_size;
780 	fsp->rdev = va.va_rdev;
781 	fsp->mode = (mode_t)va.va_mode | getftype(vp->v_type);
782 
783 	return 1;
784 }
785 
786 static int
787 msdosfs_filestat(struct vnode *vp, struct filestat *fsp)
788 {
789 	struct denode de;
790 	struct msdosfsmount mp;
791 
792 	if (!KVM_READ(VTONFS(vp), &de, sizeof(de))) {
793 		dprintf("can't read denode at %p for pid %d", VTONFS(vp),
794 		    Pid);
795 		return 0;
796 	}
797 	if (!KVM_READ(de.de_pmp, &mp, sizeof(mp))) {
798 		dprintf("can't read mount struct at %p for pid %d", de.de_pmp,
799 		    Pid);
800 		return 0;
801 	}
802 
803 	fsp->fsid = de.de_dev & 0xffff;
804 	fsp->fileid = 0; /* XXX see msdosfs_vptofh() for more info */
805 	fsp->size = de.de_FileSize;
806 	fsp->rdev = 0;	/* msdosfs doesn't support device files */
807 	fsp->mode = (0777 & mp.pm_mask) | getftype(vp->v_type);
808 	return 1;
809 }
810 
811 static const char *
812 layer_filestat(struct vnode *vp, struct filestat *fsp)
813 {
814 	struct layer_node layer_node;
815 	struct mount mount;
816 	struct vnode vn;
817 	const char *badtype;
818 
819 	if (!KVM_READ(VTOLAYER(vp), &layer_node, sizeof(layer_node))) {
820 		dprintf("can't read layer_node at %p for pid %d",
821 		    VTOLAYER(vp), Pid);
822 		return "error";
823 	}
824 	if (!KVM_READ(vp->v_mount, &mount, sizeof(struct mount))) {
825 		dprintf("can't read mount struct at %p for pid %d",
826 		    vp->v_mount, Pid);
827 		return "error";
828 	}
829 	vp = layer_node.layer_lowervp;
830 	if (!KVM_READ(vp, &vn, sizeof(struct vnode))) {
831 		dprintf("can't read vnode at %p for pid %d", vp, Pid);
832 		return "error";
833 	}
834 	if ((badtype = vfilestat(&vn, fsp)) == NULL)
835 		fsp->fsid = mount.mnt_stat.f_fsidx.__fsid_val[0];
836 	return badtype;
837 }
838 
839 static char *
840 getmnton(struct mount *m)
841 {
842 	static struct mount mount;
843 	static struct mtab {
844 		struct mtab *next;
845 		struct mount *m;
846 		char mntonname[MNAMELEN];
847 	} *mhead = NULL;
848 	struct mtab *mt;
849 
850 	for (mt = mhead; mt != NULL; mt = mt->next)
851 		if (m == mt->m)
852 			return mt->mntonname;
853 	if (!KVM_READ(m, &mount, sizeof(struct mount))) {
854 		warnx("can't read mount table at %p", m);
855 		return NULL;
856 	}
857 	if ((mt = malloc(sizeof (struct mtab))) == NULL) {
858 		err(1, "malloc(%u)", (unsigned int)sizeof(struct mtab));
859 	}
860 	mt->m = m;
861 	(void)memmove(&mt->mntonname[0], &mount.mnt_stat.f_mntonname[0],
862 	    MNAMELEN);
863 	mt->next = mhead;
864 	mhead = mt;
865 	return mt->mntonname;
866 }
867 
868 static const char *
869 inet_addrstr(char *buf, size_t len, const struct in_addr *a, uint16_t p)
870 {
871 	char addr[256], serv[256];
872 	struct sockaddr_in sin;
873 	const int niflags = nflg ? (NI_NUMERICHOST|NI_NUMERICSERV) : 0;
874 
875 	(void)memset(&sin, 0, sizeof(sin));
876 	sin.sin_family = AF_INET;
877 	sin.sin_len = sizeof(sin);
878 	sin.sin_addr = *a;
879 	sin.sin_port = htons(p);
880 
881 	serv[0] = '\0';
882 
883 	if (getnameinfo((struct sockaddr *)&sin, sin.sin_len,
884 	    addr, sizeof(addr), serv, sizeof(serv), niflags)) {
885 		if (inet_ntop(AF_INET, a, addr, sizeof(addr)) == NULL)
886 			strlcpy(addr, "invalid", sizeof(addr));
887 	}
888 
889 	if (serv[0] == '\0')
890 		snprintf(serv, sizeof(serv), "%u", p);
891 
892 	if (a->s_addr == INADDR_ANY) {
893 		if (p == 0)
894 			buf[0] = '\0';
895 		else
896 			snprintf(buf, len, "*:%s", serv);
897 		return buf;
898 	}
899 
900 	snprintf(buf, len, "%s:%s", addr, serv);
901 	return buf;
902 }
903 
904 #ifdef INET6
905 static const char *
906 inet6_addrstr(char *buf, size_t len, const struct in6_addr *a, uint16_t p)
907 {
908 	char addr[256], serv[256];
909 	struct sockaddr_in6 sin6;
910 	const int niflags = nflg ? (NI_NUMERICHOST|NI_NUMERICSERV) : 0;
911 
912 	(void)memset(&sin6, 0, sizeof(sin6));
913 	sin6.sin6_family = AF_INET6;
914 	sin6.sin6_len = sizeof(sin6);
915 	sin6.sin6_addr = *a;
916 	sin6.sin6_port = htons(p);
917 
918 	inet6_getscopeid(&sin6, INET6_IS_ADDR_LINKLOCAL);
919 	serv[0] = '\0';
920 
921 	if (getnameinfo((struct sockaddr *)&sin6, sin6.sin6_len,
922 	    addr, sizeof(addr), serv, sizeof(serv), niflags)) {
923 		if (inet_ntop(AF_INET6, a, addr, sizeof(addr)) == NULL)
924 			strlcpy(addr, "invalid", sizeof(addr));
925 	}
926 
927 	if (serv[0] == '\0')
928 		snprintf(serv, sizeof(serv), "%u", p);
929 
930 	if (IN6_IS_ADDR_UNSPECIFIED(a)) {
931 		if (p == 0)
932 			buf[0] = '\0';
933 		else
934 			snprintf(buf, len, "*:%s", serv);
935 		return buf;
936 	}
937 
938 	if (strchr(addr, ':') == NULL)
939 		snprintf(buf, len, "%s:%s", addr, serv);
940 	else
941 		snprintf(buf, len, "[%s]:%s", addr, serv);
942 
943 	return buf;
944 }
945 #endif
946 
947 static const char *
948 at_addrstr(char *buf, size_t len, const struct sockaddr_at *sat)
949 {
950 	const struct netrange *nr = &sat->sat_range.r_netrange;
951 	const struct at_addr *at = &sat->sat_addr;
952 	char addr[64], phase[64], range[64];
953 
954 	if (sat->sat_port || at->s_net || at->s_node) {
955 		if (at->s_net || at->s_node)
956 			snprintf(addr, sizeof(addr), "%u.%u:%u",
957 			    ntohs(at->s_net), at->s_node, sat->sat_port);
958 		else
959 			snprintf(addr, sizeof(addr), "*:%u", sat->sat_port);
960 	} else
961 		addr[0] = '\0';
962 
963 	if (nr->nr_phase)
964 		snprintf(phase, sizeof(phase), " phase %u", nr->nr_phase);
965 	else
966 		phase[0] = '\0';
967 
968 	if (nr->nr_firstnet || nr->nr_lastnet)
969 		snprintf(range, sizeof(range), " range [%u-%u]",
970 		    ntohs(nr->nr_firstnet), ntohs(nr->nr_lastnet));
971 	else
972 		range[0] = '\0';
973 
974 	snprintf(buf, len, "%s%s%s", addr, phase, range);
975 	return buf;
976 }
977 
978 static void
979 socktrans(struct socket *sock, int i)
980 {
981 	static const char *stypename[] = {
982 		"unused",	/* 0 */
983 		"stream", 	/* 1 */
984 		"dgram",	/* 2 */
985 		"raw",		/* 3 */
986 		"rdm",		/* 4 */
987 		"seqpak"	/* 5 */
988 	};
989 #define	STYPEMAX 5
990 	struct socket	so;
991 	struct protosw	proto;
992 	struct domain	dom;
993 	struct inpcb	inpcb;
994 #ifdef INET6
995 	struct in6pcb	in6pcb;
996 #endif
997 	struct unpcb	unpcb;
998 	struct ddpcb	ddpcb;
999 	int len;
1000 	char dname[32];
1001 	char lbuf[512], fbuf[512];
1002 	PREFIX(i);
1003 
1004 	/* fill in socket */
1005 	if (!KVM_READ(sock, &so, sizeof(struct socket))) {
1006 		dprintf("can't read sock at %p", sock);
1007 		goto bad;
1008 	}
1009 
1010 	/* fill in protosw entry */
1011 	if (!KVM_READ(so.so_proto, &proto, sizeof(struct protosw))) {
1012 		dprintf("can't read protosw at %p", so.so_proto);
1013 		goto bad;
1014 	}
1015 
1016 	/* fill in domain */
1017 	if (!KVM_READ(proto.pr_domain, &dom, sizeof(struct domain))) {
1018 		dprintf("can't read domain at %p", proto.pr_domain);
1019 		goto bad;
1020 	}
1021 
1022 	if ((len = kvm_read(kd, (u_long)dom.dom_name, dname,
1023 	    sizeof(dname) - 1)) != sizeof(dname) -1) {
1024 		dprintf("can't read domain name at %p", dom.dom_name);
1025 		dname[0] = '\0';
1026 	}
1027 	else
1028 		dname[len] = '\0';
1029 
1030 	if ((u_short)so.so_type > STYPEMAX)
1031 		(void)printf("* %s ?%d", dname, so.so_type);
1032 	else
1033 		(void)printf("* %s %s", dname, stypename[so.so_type]);
1034 
1035 	/*
1036 	 * protocol specific formatting
1037 	 *
1038 	 * Try to find interesting things to print.  For TCP, the interesting
1039 	 * thing is the address of the tcpcb, for UDP and others, just the
1040 	 * inpcb (socket pcb).  For UNIX domain, its the address of the socket
1041 	 * pcb and the address of the connected pcb (if connected).  Otherwise
1042 	 * just print the protocol number and address of the socket itself.
1043 	 * The idea is not to duplicate netstat, but to make available enough
1044 	 * information for further analysis.
1045 	 */
1046 	fbuf[0] = '\0';
1047 	lbuf[0] = '\0';
1048 	switch(dom.dom_family) {
1049 	case AF_INET:
1050 		getinetproto(proto.pr_protocol);
1051 		switch (proto.pr_protocol) {
1052 		case IPPROTO_TCP:
1053 		case IPPROTO_UDP:
1054 			if (so.so_pcb == NULL)
1055 				break;
1056 			if (kvm_read(kd, (u_long)so.so_pcb, (char *)&inpcb,
1057 			    sizeof(inpcb)) != sizeof(inpcb)) {
1058 				dprintf("can't read inpcb at %p", so.so_pcb);
1059 				goto bad;
1060 			}
1061 			inet_addrstr(lbuf, sizeof(lbuf), &inpcb.inp_laddr,
1062 			    ntohs(inpcb.inp_lport));
1063 			inet_addrstr(fbuf, sizeof(fbuf), &inpcb.inp_faddr,
1064 			    ntohs(inpcb.inp_fport));
1065 			break;
1066 		default:
1067 			break;
1068 		}
1069 		break;
1070 #ifdef INET6
1071 	case AF_INET6:
1072 		getinetproto(proto.pr_protocol);
1073 		switch (proto.pr_protocol) {
1074 		case IPPROTO_TCP:
1075 		case IPPROTO_UDP:
1076 			if (so.so_pcb == NULL)
1077 				break;
1078 			if (kvm_read(kd, (u_long)so.so_pcb, (char *)&in6pcb,
1079 			    sizeof(in6pcb)) != sizeof(in6pcb)) {
1080 				dprintf("can't read in6pcb at %p", so.so_pcb);
1081 				goto bad;
1082 			}
1083 			inet6_addrstr(lbuf, sizeof(lbuf), &in6pcb.in6p_laddr,
1084 			    ntohs(in6pcb.in6p_lport));
1085 			inet6_addrstr(fbuf, sizeof(fbuf), &in6pcb.in6p_faddr,
1086 			    ntohs(in6pcb.in6p_fport));
1087 			break;
1088 		default:
1089 			break;
1090 		}
1091 		break;
1092 #endif
1093 	case AF_LOCAL:
1094 		/* print address of pcb and connected pcb */
1095 		if (so.so_pcb) {
1096 			char shoconn[4], *cp;
1097 			void *pcb[2];
1098 			size_t p = 0;
1099 
1100 			pcb[0] = so.so_pcb;
1101 
1102 			cp = shoconn;
1103 			if (!(so.so_state & SS_CANTRCVMORE))
1104 				*cp++ = '<';
1105 			*cp++ = '-';
1106 			if (!(so.so_state & SS_CANTSENDMORE))
1107 				*cp++ = '>';
1108 			*cp = '\0';
1109 again:
1110 			if (kvm_read(kd, (u_long)pcb[p], (char *)&unpcb,
1111 			    sizeof(struct unpcb)) != sizeof(struct unpcb)){
1112 				dprintf("can't read unpcb at %p", so.so_pcb);
1113 				goto bad;
1114 			}
1115 
1116 			if (unpcb.unp_addr) {
1117 				struct sockaddr_un *sun =
1118 					malloc(unpcb.unp_addrlen);
1119 				if (sun == NULL)
1120 				    err(1, "malloc(%zu)",
1121 					unpcb.unp_addrlen);
1122 				if (kvm_read(kd, (u_long)unpcb.unp_addr,
1123 				    sun, unpcb.unp_addrlen) !=
1124 				    (ssize_t)unpcb.unp_addrlen) {
1125 					dprintf("can't read sun at %p",
1126 					    unpcb.unp_addr);
1127 					free(sun);
1128 				} else {
1129 					snprintf(fbuf, sizeof(fbuf), " %s %s %s",
1130 					    shoconn, sun->sun_path,
1131 					    p == 0 ? "[creat]" : "[using]");
1132 					free(sun);
1133 					break;
1134 				}
1135 			}
1136 			if (unpcb.unp_conn) {
1137 				if (p == 0) {
1138 					pcb[++p] = unpcb.unp_conn;
1139 					goto again;
1140 				} else
1141 					snprintf(fbuf, sizeof(fbuf),
1142 					    " %p %s %p", pcb[0], shoconn,
1143 					    pcb[1]);
1144 			}
1145 		}
1146 		break;
1147 	case AF_APPLETALK:
1148 		getatproto(proto.pr_protocol);
1149 		if (so.so_pcb) {
1150 			if (kvm_read(kd, (u_long)so.so_pcb, (char *)&ddpcb,
1151 			    sizeof(ddpcb)) != sizeof(ddpcb)){
1152 				dprintf("can't read ddpcb at %p", so.so_pcb);
1153 				goto bad;
1154 			}
1155 			at_addrstr(fbuf, sizeof(fbuf), &ddpcb.ddp_fsat);
1156 			at_addrstr(lbuf, sizeof(lbuf), &ddpcb.ddp_lsat);
1157 		}
1158 		break;
1159 	default:
1160 		/* print protocol number and socket address */
1161 		snprintf(fbuf, sizeof(fbuf), " %d %jx", proto.pr_protocol,
1162 		    (uintmax_t)(uintptr_t)sock);
1163 		break;
1164 	}
1165 	if (fbuf[0] || lbuf[0])
1166 		printf(" %s%s%s", fbuf, (fbuf[0] && lbuf[0]) ? " <-> " : "",
1167 		    lbuf);
1168 	else if (so.so_pcb)
1169 		printf(" %jx", (uintmax_t)(uintptr_t)so.so_pcb);
1170 	(void)printf("\n");
1171 	return;
1172 bad:
1173 	(void)printf("* error\n");
1174 }
1175 
1176 static void
1177 ptrans(struct file *fp, struct pipe *cpipe, int i)
1178 {
1179 	struct pipe cp;
1180 
1181 	PREFIX(i);
1182 
1183 	/* fill in pipe */
1184 	if (!KVM_READ(cpipe, &cp, sizeof(struct pipe))) {
1185 		dprintf("can't read pipe at %p", cpipe);
1186 		goto bad;
1187 	}
1188 
1189 	/* pipe descriptor is either read or write, never both */
1190 	(void)printf("* pipe %p %s %p %s%s%s", cpipe,
1191 		(fp->f_flag & FWRITE) ? "->" : "<-",
1192 		cp.pipe_peer,
1193 		(fp->f_flag & FWRITE) ? "w" : "r",
1194 		(fp->f_flag & FNONBLOCK) ? "n" : "",
1195 		(cp.pipe_state & PIPE_ASYNC) ? "a" : "");
1196 	(void)printf("\n");
1197 	return;
1198 bad:
1199 	(void)printf("* error\n");
1200 }
1201 
1202 static void
1203 misctrans(struct file *file, int i)
1204 {
1205 
1206 	PREFIX(i);
1207 	pmisc(file, dtypes[file->f_type]);
1208 }
1209 
1210 /*
1211  * getinetproto --
1212  *	print name of protocol number
1213  */
1214 static void
1215 getinetproto(int number)
1216 {
1217 	const char *cp;
1218 
1219 	switch (number) {
1220 	case IPPROTO_IP:
1221 		cp = "ip"; break;
1222 	case IPPROTO_ICMP:
1223 		cp ="icmp"; break;
1224 	case IPPROTO_GGP:
1225 		cp ="ggp"; break;
1226 	case IPPROTO_TCP:
1227 		cp ="tcp"; break;
1228 	case IPPROTO_EGP:
1229 		cp ="egp"; break;
1230 	case IPPROTO_PUP:
1231 		cp ="pup"; break;
1232 	case IPPROTO_UDP:
1233 		cp ="udp"; break;
1234 	case IPPROTO_IDP:
1235 		cp ="idp"; break;
1236 	case IPPROTO_RAW:
1237 		cp ="raw"; break;
1238 	case IPPROTO_ICMPV6:
1239 		cp ="icmp6"; break;
1240 	default:
1241 		(void)printf(" %d", number);
1242 		return;
1243 	}
1244 	(void)printf(" %s", cp);
1245 }
1246 
1247 /*
1248  * getatproto --
1249  *	print name of protocol number
1250  */
1251 static void
1252 getatproto(int number)
1253 {
1254 	const char *cp;
1255 
1256 	switch (number) {
1257 	case ATPROTO_DDP:
1258 		cp = "ddp"; break;
1259 	case ATPROTO_AARP:
1260 		cp ="aarp"; break;
1261 	default:
1262 		(void)printf(" %d", number);
1263 		return;
1264 	}
1265 	(void)printf(" %s", cp);
1266 }
1267 
1268 static int
1269 getfname(const char *filename)
1270 {
1271 	struct stat statbuf;
1272 	DEVS *cur;
1273 
1274 	if (stat(filename, &statbuf)) {
1275 		warn("stat(%s)", filename);
1276 		return 0;
1277 	}
1278 	if ((cur = malloc(sizeof(*cur))) == NULL) {
1279 		err(1, "malloc(%zu)", sizeof(*cur));
1280 	}
1281 	cur->next = devs;
1282 	devs = cur;
1283 
1284 	cur->ino = statbuf.st_ino;
1285 	cur->fsid = statbuf.st_dev & 0xffff;
1286 	cur->name = filename;
1287 	return 1;
1288 }
1289 
1290 mode_t
1291 getftype(enum vtype v_type)
1292 {
1293 	mode_t ftype;
1294 
1295 	switch (v_type) {
1296 	case VREG:
1297 		ftype = S_IFREG;
1298 		break;
1299 	case VDIR:
1300 		ftype = S_IFDIR;
1301 		break;
1302 	case VBLK:
1303 		ftype = S_IFBLK;
1304 		break;
1305 	case VCHR:
1306 		ftype = S_IFCHR;
1307 		break;
1308 	case VLNK:
1309 		ftype = S_IFLNK;
1310 		break;
1311 	case VSOCK:
1312 		ftype = S_IFSOCK;
1313 		break;
1314 	case VFIFO:
1315 		ftype = S_IFIFO;
1316 		break;
1317 	default:
1318 		ftype = 0;
1319 		break;
1320 	};
1321 
1322 	return ftype;
1323 }
1324 
1325 static void
1326 usage(void)
1327 {
1328 	(void)fprintf(stderr, "Usage: %s [-Afnv] [-M core] [-N system] "
1329 	    "[-p pid] [-u user] [file ...]\n", getprogname());
1330 	exit(1);
1331 }
1332