xref: /netbsd-src/usr.bin/fstat/fstat.c (revision cac8e449158efc7261bebc8657cbb0125a2cfdde)
1 /*	$NetBSD: fstat.c,v 1.85 2008/07/23 00:57:53 lukem 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.85 2008/07/23 00:57:53 lukem 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/file.h>
62 #include <ufs/ufs/inode.h>
63 #undef _KERNEL
64 #define _KERNEL
65 #include <sys/mount.h>
66 #undef _KERNEL
67 #define NFS
68 #include <nfs/nfsproto.h>
69 #include <nfs/rpcv2.h>
70 #include <nfs/nfs.h>
71 #include <nfs/nfsnode.h>
72 #undef NFS
73 #include <msdosfs/denode.h>
74 #include <msdosfs/bpb.h>
75 #define	_KERNEL
76 #include <msdosfs/msdosfsmount.h>
77 #undef _KERNEL
78 #define	_KERNEL
79 #include <miscfs/genfs/layer.h>
80 #undef _KERNEL
81 
82 #include <net/route.h>
83 #include <netinet/in.h>
84 #include <netinet/in_systm.h>
85 #include <netinet/ip.h>
86 #include <netinet/in_pcb.h>
87 
88 #ifdef INET6
89 #include <netinet/ip6.h>
90 #include <netinet6/ip6_var.h>
91 #include <netinet6/in6_pcb.h>
92 #endif
93 
94 #include <netdb.h>
95 #include <arpa/inet.h>
96 
97 #include <ctype.h>
98 #include <errno.h>
99 #include <kvm.h>
100 #include <limits.h>
101 #include <nlist.h>
102 #include <paths.h>
103 #include <pwd.h>
104 #include <stdio.h>
105 #include <stdlib.h>
106 #include <string.h>
107 #include <unistd.h>
108 #include <err.h>
109 
110 #include "fstat.h"
111 
112 #define	TEXT	-1
113 #define	CDIR	-2
114 #define	RDIR	-3
115 #define	TRACE	-4
116 
117 typedef struct devs {
118 	struct	devs *next;
119 	long	fsid;
120 	ino_t	ino;
121 	const char *name;
122 } DEVS;
123 static DEVS *devs;
124 
125 static int 	fsflg,	/* show files on same filesystem as file(s) argument */
126 	pflg,	/* show files open by a particular pid */
127 	uflg;	/* show files open by a particular (effective) user */
128 static int 	checkfile; /* true if restricting to particular files or filesystems */
129 static int	nflg;	/* (numerical) display f.s. and rdev as dev_t */
130 int	vflg;	/* display errors in locating kernel data objects etc... */
131 
132 static fdfile_t **ofiles; /* buffer of pointers to file structures */
133 static int fstat_maxfiles;
134 #define ALLOC_OFILES(d)	\
135 	if ((d) > fstat_maxfiles) { \
136 		size_t len = (d) * sizeof(fdfile_t *); \
137 		free(ofiles); \
138 		ofiles = malloc(len); \
139 		if (ofiles == NULL) { \
140 			err(1, "malloc(%zu)", len);	\
141 		} \
142 		fstat_maxfiles = (d); \
143 	}
144 
145 kvm_t *kd;
146 
147 static const char *const dtypes[] = {
148 	DTYPE_NAMES
149 };
150 
151 static void	dofiles(struct kinfo_proc2 *);
152 static int	ext2fs_filestat(struct vnode *, struct filestat *);
153 static int	getfname(const char *);
154 static void	getinetproto(int);
155 static char   *getmnton(struct mount *);
156 static const char   *layer_filestat(struct vnode *, struct filestat *);
157 static int	msdosfs_filestat(struct vnode *, struct filestat *);
158 static int	nfs_filestat(struct vnode *, struct filestat *);
159 #ifdef INET6
160 static const char *inet6_addrstr(struct in6_addr *);
161 #endif
162 static void	socktrans(struct socket *, int);
163 static void	misctrans(struct file *);
164 static int	ufs_filestat(struct vnode *, struct filestat *);
165 static void	usage(void) __dead;
166 static const char   *vfilestat(struct vnode *, struct filestat *);
167 static void	vtrans(struct vnode *, int, int);
168 static void	ftrans(fdfile_t *, int);
169 static void	ptrans(struct file *, struct pipe *, int);
170 
171 int
172 main(int argc, char **argv)
173 {
174 	struct passwd *passwd;
175 	struct kinfo_proc2 *p, *plast;
176 	int arg, ch, what;
177 	char *memf, *nlistf;
178 	char buf[_POSIX2_LINE_MAX];
179 	int cnt;
180 	gid_t egid = getegid();
181 
182 	(void)setegid(getgid());
183 	arg = 0;
184 	what = KERN_PROC_ALL;
185 	nlistf = memf = NULL;
186 	while ((ch = getopt(argc, argv, "fnp:u:vN:M:")) != -1)
187 		switch((char)ch) {
188 		case 'f':
189 			fsflg = 1;
190 			break;
191 		case 'M':
192 			memf = optarg;
193 			break;
194 		case 'N':
195 			nlistf = optarg;
196 			break;
197 		case 'n':
198 			nflg = 1;
199 			break;
200 		case 'p':
201 			if (pflg++)
202 				usage();
203 			if (!isdigit((unsigned char)*optarg)) {
204 				warnx("-p requires a process id");
205 				usage();
206 			}
207 			what = KERN_PROC_PID;
208 			arg = atoi(optarg);
209 			break;
210 		case 'u':
211 			if (uflg++)
212 				usage();
213 			if (!(passwd = getpwnam(optarg))) {
214 				errx(1, "%s: unknown uid", optarg);
215 			}
216 			what = KERN_PROC_UID;
217 			arg = passwd->pw_uid;
218 			break;
219 		case 'v':
220 			vflg = 1;
221 			break;
222 		case '?':
223 		default:
224 			usage();
225 		}
226 
227 	if (*(argv += optind)) {
228 		for (; *argv; ++argv) {
229 			if (getfname(*argv))
230 				checkfile = 1;
231 		}
232 		if (!checkfile)	/* file(s) specified, but none accessible */
233 			exit(1);
234 	}
235 
236 	ALLOC_OFILES(256);	/* reserve space for file pointers */
237 
238 	if (fsflg && !checkfile) {
239 		/* -f with no files means use wd */
240 		if (getfname(".") == 0)
241 			exit(1);
242 		checkfile = 1;
243 	}
244 
245 	/*
246 	 * Discard setgid privileges.  If not the running kernel, we toss
247 	 * them away totally so that bad guys can't print interesting stuff
248 	 * from kernel memory, otherwise switch back to kmem for the
249 	 * duration of the kvm_openfiles() call.
250 	 */
251 	if (nlistf != NULL || memf != NULL)
252 		(void)setgid(getgid());
253 	else
254 		(void)setegid(egid);
255 
256 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, buf)) == NULL)
257 		errx(1, "%s", buf);
258 
259 	/* get rid of it now anyway */
260 	if (nlistf == NULL && memf == NULL)
261 		(void)setgid(getgid());
262 
263 	if ((p = kvm_getproc2(kd, what, arg, sizeof *p, &cnt)) == NULL) {
264 		errx(1, "%s", kvm_geterr(kd));
265 	}
266 	if (nflg)
267 		(void)printf("%s",
268 "USER     CMD          PID   FD  DEV     INUM  MODE  SZ|DV R/W");
269 	else
270 		(void)printf("%s",
271 "USER     CMD          PID   FD MOUNT       INUM MODE         SZ|DV R/W");
272 	if (checkfile && fsflg == 0)
273 		(void)printf(" NAME\n");
274 	else
275 		(void)putchar('\n');
276 
277 	for (plast = &p[cnt]; p < plast; ++p) {
278 		if (p->p_stat == SZOMB)
279 			continue;
280 		dofiles(p);
281 	}
282 	return 0;
283 }
284 
285 static const	char *Uname, *Comm;
286 pid_t	Pid;
287 
288 #define PREFIX(i) (void)printf("%-8.8s %-10s %5d", Uname, Comm, Pid); \
289 	switch(i) { \
290 	case TEXT: \
291 		(void)printf(" text"); \
292 		break; \
293 	case CDIR: \
294 		(void)printf("   wd"); \
295 		break; \
296 	case RDIR: \
297 		(void)printf(" root"); \
298 		break; \
299 	case TRACE: \
300 		(void)printf("   tr"); \
301 		break; \
302 	default: \
303 		(void)printf(" %4d", i); \
304 		break; \
305 	}
306 
307 /*
308  * print open files attributed to this process
309  */
310 static void
311 dofiles(struct kinfo_proc2 *p)
312 {
313 	int i;
314 	struct filedesc filed;
315 	struct cwdinfo cwdi;
316 
317 	Uname = user_from_uid(p->p_uid, 0);
318 	Pid = p->p_pid;
319 	Comm = p->p_comm;
320 
321 	if (p->p_fd == 0 || p->p_cwdi == 0)
322 		return;
323 	if (!KVM_READ(p->p_fd, &filed, sizeof (filed))) {
324 		warnx("can't read filedesc at %#llx for pid %d", (unsigned long long)p->p_fd, Pid);
325 		return;
326 	}
327 	if (!KVM_READ(p->p_cwdi, &cwdi, sizeof(cwdi))) {
328 		warnx("can't read cwdinfo at %#llx for pid %d", (unsigned long long)p->p_cwdi, Pid);
329 		return;
330 	}
331 	if (filed.fd_nfiles < 0 || filed.fd_lastfile >= filed.fd_nfiles ||
332 	    filed.fd_freefile > filed.fd_lastfile + 1) {
333 		dprintf("filedesc corrupted at %#llx for pid %d", (unsigned long long)p->p_fd, Pid);
334 		return;
335 	}
336 	/*
337 	 * root directory vnode, if one
338 	 */
339 	if (cwdi.cwdi_rdir)
340 		vtrans(cwdi.cwdi_rdir, RDIR, FREAD);
341 	/*
342 	 * current working directory vnode
343 	 */
344 	vtrans(cwdi.cwdi_cdir, CDIR, FREAD);
345 #if 0
346 	/*
347 	 * Disable for now, since p->p_tracep appears to point to a ktr_desc *
348 	 * ktrace vnode, if one
349 	 */
350 	if (p->p_tracep)
351 		ftrans((struct file *)(intptr_t)p->p_tracep, TRACE);
352 #endif
353 	/*
354 	 * open files
355 	 */
356 #define FPSIZE	(sizeof (fdfile_t *))
357 	ALLOC_OFILES(filed.fd_lastfile+1);
358 	if (!KVM_READ(filed.fd_ofiles, ofiles,
359 	    (filed.fd_lastfile+1) * FPSIZE)) {
360 		dprintf("can't read file structures at %p for pid %d",
361 		    filed.fd_ofiles, Pid);
362 		return;
363 	}
364 	for (i = 0; i <= filed.fd_lastfile; i++) {
365 		if (ofiles[i] == NULL)
366 			continue;
367 		ftrans(ofiles[i], i);
368 	}
369 }
370 
371 static void
372 ftrans(fdfile_t *fp, int i)
373 {
374 	struct file file;
375 	fdfile_t fdfile;
376 
377 	if (!KVM_READ(fp, &fdfile, sizeof(fdfile))) {
378 		dprintf("can't read file %d at %p for pid %d",
379 		    i, fp, Pid);
380 		return;
381 	}
382 	if (fdfile.ff_file == NULL)
383 		return;
384 	if (!KVM_READ(fdfile.ff_file, &file, sizeof(file))) {
385 		dprintf("can't read file %d at %p for pid %d",
386 		    i, fdfile.ff_file, Pid);
387 		return;
388 	}
389 	switch (file.f_type) {
390 	case DTYPE_VNODE:
391 		vtrans((struct vnode *)file.f_data, i, file.f_flag);
392 		break;
393 	case DTYPE_SOCKET:
394 		if (checkfile == 0)
395 			socktrans((struct socket *)file.f_data, i);
396 		break;
397 	case DTYPE_PIPE:
398 		if (checkfile == 0)
399 			ptrans(&file, (struct pipe *)file.f_data, i);
400 		break;
401 	case DTYPE_MISC:
402 	case DTYPE_KQUEUE:
403 	case DTYPE_CRYPTO:
404 	case DTYPE_MQUEUE:
405 		if (checkfile == 0)
406 			misctrans(&file);
407 		break;
408 	default:
409 		dprintf("unknown file type %d for file %d of pid %d",
410 		    file.f_type, i, Pid);
411 		break;
412 	}
413 }
414 
415 static const char *
416 vfilestat(struct vnode *vp, struct filestat *fsp)
417 {
418 	const char *badtype = NULL;
419 
420 	if (vp->v_type == VNON || vp->v_tag == VT_NON)
421 		badtype = "none";
422 	else if (vp->v_type == VBAD)
423 		badtype = "bad";
424 	else
425 		switch (vp->v_tag) {
426 		case VT_UFS:
427 		case VT_LFS:
428 		case VT_MFS:
429 			if (!ufs_filestat(vp, fsp))
430 				badtype = "error";
431 			break;
432 		case VT_MSDOSFS:
433 			if (!msdosfs_filestat(vp, fsp))
434 				badtype = "error";
435 			break;
436 		case VT_NFS:
437 			if (!nfs_filestat(vp, fsp))
438 				badtype = "error";
439 			break;
440 		case VT_EXT2FS:
441 			if (!ext2fs_filestat(vp, fsp))
442 				badtype = "error";
443 			break;
444 		case VT_ISOFS:
445 			if (!isofs_filestat(vp, fsp))
446 				badtype = "error";
447 			break;
448 		case VT_NTFS:
449 			if (!ntfs_filestat(vp, fsp))
450 				badtype = "error";
451 			break;
452 		case VT_PTYFS:
453 			if (!ptyfs_filestat(vp, fsp))
454 				badtype = "error";
455 			break;
456 		case VT_TMPFS:
457 			if (!tmpfs_filestat(vp, fsp))
458 				badtype = "error";
459 			break;
460 		case VT_NULL:
461 		case VT_OVERLAY:
462 		case VT_UMAP:
463 			badtype = layer_filestat(vp, fsp);
464 			break;
465 		default: {
466 			static char unknown[10];
467 			(void)snprintf(unknown, sizeof unknown,
468 			    "?(%x)", vp->v_tag);
469 			badtype = unknown;
470 			break;
471 		}
472 	}
473 	return (badtype);
474 }
475 
476 static void
477 vtrans(struct vnode *vp, int i, int flag)
478 {
479 	struct vnode vn;
480 	struct filestat fst;
481 	char mode[15], rw[3];
482 	const char *badtype, *filename;
483 
484 	filename = NULL;
485 	if (!KVM_READ(vp, &vn, sizeof(struct vnode))) {
486 		dprintf("can't read vnode at %p for pid %d", vp, Pid);
487 		return;
488 	}
489 	badtype = vfilestat(&vn, &fst);
490 	if (checkfile) {
491 		int fsmatch = 0;
492 		DEVS *d;
493 
494 		if (badtype)
495 			return;
496 		for (d = devs; d != NULL; d = d->next)
497 			if (d->fsid == fst.fsid) {
498 				fsmatch = 1;
499 				if (d->ino == fst.fileid) {
500 					filename = d->name;
501 					break;
502 				}
503 			}
504 		if (fsmatch == 0 || (filename == NULL && fsflg == 0))
505 			return;
506 	}
507 	PREFIX(i);
508 	if (badtype) {
509 		(void)printf(" -         -  %10s    -\n", badtype);
510 		return;
511 	}
512 	if (nflg)
513 		(void)printf(" %2d,%-2d", major(fst.fsid), minor(fst.fsid));
514 	else
515 		(void)printf(" %-8s", getmnton(vn.v_mount));
516 	if (nflg)
517 		(void)snprintf(mode, sizeof mode, "%o", fst.mode);
518 	else
519 		strmode(fst.mode, mode);
520 	(void)printf(" %7lu %*s", (unsigned long)fst.fileid, nflg ? 5 : 10, mode);
521 	switch (vn.v_type) {
522 	case VBLK:
523 	case VCHR: {
524 		char *name;
525 
526 		if (nflg || ((name = devname(fst.rdev, vn.v_type == VCHR ?
527 		    S_IFCHR : S_IFBLK)) == NULL))
528 			(void)printf("  %2d,%-2d", major(fst.rdev),
529 			    minor(fst.rdev));
530 		else
531 			(void)printf(" %6s", name);
532 		break;
533 	}
534 	default:
535 		(void)printf(" %6lld", (long long)fst.size);
536 	}
537 	rw[0] = '\0';
538 	if (flag & FREAD)
539 		(void)strlcat(rw, "r", sizeof(rw));
540 	if (flag & FWRITE)
541 		(void)strlcat(rw, "w", sizeof(rw));
542 	(void)printf(" %-2s", rw);
543 	if (filename && !fsflg)
544 		(void)printf("  %s", filename);
545 	(void)putchar('\n');
546 }
547 
548 static int
549 ufs_filestat(struct vnode *vp, struct filestat *fsp)
550 {
551 	struct inode inode;
552 	union dinode {
553 		struct ufs1_dinode dp1;
554 		struct ufs2_dinode dp2;
555 	} dip;
556 
557 	if (!KVM_READ(VTOI(vp), &inode, sizeof (inode))) {
558 		dprintf("can't read inode at %p for pid %d", VTOI(vp), Pid);
559 		return 0;
560 	}
561 
562 	if (!KVM_READ(inode.i_din.ffs1_din, &dip, sizeof(struct ufs1_dinode))) {
563 		dprintf("can't read dinode at %p for pid %d",
564 		    inode.i_din.ffs1_din, Pid);
565 		return 0;
566 	}
567 	if (inode.i_size == dip.dp1.di_size)
568 		fsp->rdev = dip.dp1.di_rdev;
569 	else {
570 		if (!KVM_READ(inode.i_din.ffs1_din, &dip,
571 		    sizeof(struct ufs2_dinode))) {
572 			dprintf("can't read dinode at %p for pid %d",
573 			    inode.i_din.ffs1_din, Pid);
574 			return 0;
575 		}
576 		fsp->rdev = dip.dp2.di_rdev;
577 	}
578 
579 	fsp->fsid = inode.i_dev & 0xffff;
580 	fsp->fileid = (long)inode.i_number;
581 	fsp->mode = (mode_t)inode.i_mode;
582 	fsp->size = inode.i_size;
583 
584 	return 1;
585 }
586 
587 static int
588 ext2fs_filestat(struct vnode *vp, struct filestat *fsp)
589 {
590 	struct inode inode;
591 	u_int16_t mode;
592 	u_int32_t size;
593 
594 	if (!KVM_READ(VTOI(vp), &inode, sizeof (inode))) {
595 		dprintf("can't read inode at %p for pid %d", VTOI(vp), Pid);
596 		return 0;
597 	}
598 	fsp->fsid = inode.i_dev & 0xffff;
599 	fsp->fileid = (long)inode.i_number;
600 
601 	if (!KVM_READ(&inode.i_e2fs_mode, &mode, sizeof mode)) {
602 		dprintf("can't read inode %p's mode at %p for pid %d", VTOI(vp),
603 			&inode.i_e2fs_mode, Pid);
604 		return 0;
605 	}
606 	fsp->mode = mode;
607 
608 	if (!KVM_READ(&inode.i_e2fs_size, &size, sizeof size)) {
609 		dprintf("can't read inode %p's size at %p for pid %d", VTOI(vp),
610 			&inode.i_e2fs_size, Pid);
611 		return 0;
612 	}
613 	fsp->size = size;
614 	fsp->rdev = 0;  /* XXX */
615 	return 1;
616 }
617 
618 static int
619 nfs_filestat(struct vnode *vp, struct filestat *fsp)
620 {
621 	struct nfsnode nfsnode;
622 	struct vattr va;
623 
624 	if (!KVM_READ(VTONFS(vp), &nfsnode, sizeof (nfsnode))) {
625 		dprintf("can't read nfsnode at %p for pid %d", VTONFS(vp),
626 		    Pid);
627 		return 0;
628 	}
629 	if (!KVM_READ(nfsnode.n_vattr, &va, sizeof(va))) {
630 		dprintf("can't read vnode attributes at %p for pid %d",
631 		    nfsnode.n_vattr, Pid);
632 		return 0;
633 	}
634 	fsp->fsid = va.va_fsid;
635 	fsp->fileid = va.va_fileid;
636 	fsp->size = nfsnode.n_size;
637 	fsp->rdev = va.va_rdev;
638 	fsp->mode = (mode_t)va.va_mode | getftype(vp->v_type);
639 
640 	return 1;
641 }
642 
643 static int
644 msdosfs_filestat(struct vnode *vp, struct filestat *fsp)
645 {
646 	struct denode de;
647 	struct msdosfsmount mp;
648 
649 	if (!KVM_READ(VTONFS(vp), &de, sizeof(de))) {
650 		dprintf("can't read denode at %p for pid %d", VTONFS(vp),
651 		    Pid);
652 		return 0;
653 	}
654 	if (!KVM_READ(de.de_pmp, &mp, sizeof(mp))) {
655 		dprintf("can't read mount struct at %p for pid %d", de.de_pmp,
656 		    Pid);
657 		return 0;
658 	}
659 
660 	fsp->fsid = de.de_dev & 0xffff;
661 	fsp->fileid = 0; /* XXX see msdosfs_vptofh() for more info */
662 	fsp->size = de.de_FileSize;
663 	fsp->rdev = 0;	/* msdosfs doesn't support device files */
664 	fsp->mode = (0777 & mp.pm_mask) | getftype(vp->v_type);
665 	return 1;
666 }
667 
668 static const char *
669 layer_filestat(struct vnode *vp, struct filestat *fsp)
670 {
671 	struct layer_node layer_node;
672 	struct mount mount;
673 	struct vnode vn;
674 	const char *badtype;
675 
676 	if (!KVM_READ(VTOLAYER(vp), &layer_node, sizeof(layer_node))) {
677 		dprintf("can't read layer_node at %p for pid %d",
678 		    VTOLAYER(vp), Pid);
679 		return ("error");
680 	}
681 	if (!KVM_READ(vp->v_mount, &mount, sizeof(struct mount))) {
682 		dprintf("can't read mount struct at %p for pid %d",
683 		    vp->v_mount, Pid);
684 		return ("error");
685 	}
686 	vp = layer_node.layer_lowervp;
687 	if (!KVM_READ(vp, &vn, sizeof(struct vnode))) {
688 		dprintf("can't read vnode at %p for pid %d", vp, Pid);
689 		return ("error");
690 	}
691 	if ((badtype = vfilestat(&vn, fsp)) == NULL)
692 		fsp->fsid = mount.mnt_stat.f_fsidx.__fsid_val[0];
693 	return (badtype);
694 }
695 
696 static char *
697 getmnton(struct mount *m)
698 {
699 	static struct mount mount;
700 	static struct mtab {
701 		struct mtab *next;
702 		struct mount *m;
703 		char mntonname[MNAMELEN];
704 	} *mhead = NULL;
705 	struct mtab *mt;
706 
707 	for (mt = mhead; mt != NULL; mt = mt->next)
708 		if (m == mt->m)
709 			return (mt->mntonname);
710 	if (!KVM_READ(m, &mount, sizeof(struct mount))) {
711 		warnx("can't read mount table at %p", m);
712 		return (NULL);
713 	}
714 	if ((mt = malloc(sizeof (struct mtab))) == NULL) {
715 		err(1, "malloc(%u)", (unsigned int)sizeof(struct mtab));
716 	}
717 	mt->m = m;
718 	(void)memmove(&mt->mntonname[0], &mount.mnt_stat.f_mntonname[0],
719 	    MNAMELEN);
720 	mt->next = mhead;
721 	mhead = mt;
722 	return (mt->mntonname);
723 }
724 
725 #ifdef INET6
726 static const char *
727 inet6_addrstr(struct in6_addr *p)
728 {
729 	struct sockaddr_in6 sin6;
730 	static char hbuf[NI_MAXHOST];
731 	const int niflags = NI_NUMERICHOST;
732 
733 	(void)memset(&sin6, 0, sizeof(sin6));
734 	sin6.sin6_family = AF_INET6;
735 	sin6.sin6_len = sizeof(struct sockaddr_in6);
736 	sin6.sin6_addr = *p;
737 	if (IN6_IS_ADDR_LINKLOCAL(p) &&
738 	    *(u_int16_t *)&sin6.sin6_addr.s6_addr[2] != 0) {
739 		sin6.sin6_scope_id =
740 			ntohs(*(u_int16_t *)&sin6.sin6_addr.s6_addr[2]);
741 		sin6.sin6_addr.s6_addr[2] = sin6.sin6_addr.s6_addr[3] = 0;
742 	}
743 
744 	if (getnameinfo((struct sockaddr *)&sin6, sin6.sin6_len,
745 			hbuf, sizeof(hbuf), NULL, 0, niflags))
746 		return "invalid";
747 
748 	return hbuf;
749 }
750 #endif
751 
752 static void
753 socktrans(struct socket *sock, int i)
754 {
755 	static const char *stypename[] = {
756 		"unused",	/* 0 */
757 		"stream", 	/* 1 */
758 		"dgram",	/* 2 */
759 		"raw",		/* 3 */
760 		"rdm",		/* 4 */
761 		"seqpak"	/* 5 */
762 	};
763 #define	STYPEMAX 5
764 	struct socket	so;
765 	struct protosw	proto;
766 	struct domain	dom;
767 	struct inpcb	inpcb;
768 #ifdef INET6
769 	struct in6pcb	in6pcb;
770 #endif
771 	struct unpcb	unpcb;
772 	int len;
773 	char dname[32];
774 #ifdef INET6
775 	char xaddrbuf[NI_MAXHOST + 2];
776 #endif
777 
778 	PREFIX(i);
779 
780 	/* fill in socket */
781 	if (!KVM_READ(sock, &so, sizeof(struct socket))) {
782 		dprintf("can't read sock at %p", sock);
783 		goto bad;
784 	}
785 
786 	/* fill in protosw entry */
787 	if (!KVM_READ(so.so_proto, &proto, sizeof(struct protosw))) {
788 		dprintf("can't read protosw at %p", so.so_proto);
789 		goto bad;
790 	}
791 
792 	/* fill in domain */
793 	if (!KVM_READ(proto.pr_domain, &dom, sizeof(struct domain))) {
794 		dprintf("can't read domain at %p", proto.pr_domain);
795 		goto bad;
796 	}
797 
798 	if ((len = kvm_read(kd, (u_long)dom.dom_name, dname,
799 	    sizeof(dname) - 1)) != sizeof(dname) -1) {
800 		dprintf("can't read domain name at %p", dom.dom_name);
801 		dname[0] = '\0';
802 	}
803 	else
804 		dname[len] = '\0';
805 
806 	if ((u_short)so.so_type > STYPEMAX)
807 		(void)printf("* %s ?%d", dname, so.so_type);
808 	else
809 		(void)printf("* %s %s", dname, stypename[so.so_type]);
810 
811 	/*
812 	 * protocol specific formatting
813 	 *
814 	 * Try to find interesting things to print.  For TCP, the interesting
815 	 * thing is the address of the tcpcb, for UDP and others, just the
816 	 * inpcb (socket pcb).  For UNIX domain, its the address of the socket
817 	 * pcb and the address of the connected pcb (if connected).  Otherwise
818 	 * just print the protocol number and address of the socket itself.
819 	 * The idea is not to duplicate netstat, but to make available enough
820 	 * information for further analysis.
821 	 */
822 	switch(dom.dom_family) {
823 	case AF_INET:
824 		getinetproto(proto.pr_protocol);
825 		if (proto.pr_protocol == IPPROTO_TCP) {
826 			if (so.so_pcb == NULL)
827 				break;
828 			if (kvm_read(kd, (u_long)so.so_pcb, (char *)&inpcb,
829 			    sizeof(struct inpcb)) != sizeof(struct inpcb)) {
830 				dprintf("can't read inpcb at %p", so.so_pcb);
831 				goto bad;
832 			}
833 			(void)printf(" %lx", (long)inpcb.inp_ppcb);
834 			(void)printf(" %s:%d",
835 			    inpcb.inp_laddr.s_addr == INADDR_ANY ? "*" :
836 			    inet_ntoa(inpcb.inp_laddr), ntohs(inpcb.inp_lport));
837 			if (inpcb.inp_fport) {
838 				(void)printf(" <-> %s:%d",
839 				    inpcb.inp_faddr.s_addr == INADDR_ANY ? "*" :
840 				    inet_ntoa(inpcb.inp_faddr),
841 				    ntohs(inpcb.inp_fport));
842 			}
843 		} else if (proto.pr_protocol == IPPROTO_UDP) {
844 			if (so.so_pcb == NULL)
845 				break;
846 			if (kvm_read(kd, (u_long)so.so_pcb, (char *)&inpcb,
847 			    sizeof(struct inpcb)) != sizeof(struct inpcb)) {
848 				dprintf("can't read inpcb at %p", so.so_pcb);
849 				goto bad;
850 			}
851 			(void)printf(" %lx", (long)so.so_pcb);
852 			(void)printf(" %s:%d",
853 			    inpcb.inp_laddr.s_addr == INADDR_ANY ? "*" :
854 			    inet_ntoa(inpcb.inp_laddr), ntohs(inpcb.inp_lport));
855 			if (inpcb.inp_fport)
856 				(void)printf(" <-> %s:%d",
857 				    inpcb.inp_faddr.s_addr == INADDR_ANY ? "*" :
858 				    inet_ntoa(inpcb.inp_faddr),
859 				    ntohs(inpcb.inp_fport));
860 		} else if (so.so_pcb)
861 			(void)printf(" %lx", (long)so.so_pcb);
862 		break;
863 #ifdef INET6
864 	case AF_INET6:
865 		getinetproto(proto.pr_protocol);
866 		if (proto.pr_protocol == IPPROTO_TCP) {
867 			if (so.so_pcb == NULL)
868 				break;
869 			if (kvm_read(kd, (u_long)so.so_pcb, (char *)&in6pcb,
870 			    sizeof(struct in6pcb)) != sizeof(struct in6pcb)) {
871 				dprintf("can't read in6pcb at %p", so.so_pcb);
872 				goto bad;
873 			}
874 			(void)printf(" %lx", (long)in6pcb.in6p_ppcb);
875 			(void)snprintf(xaddrbuf, sizeof(xaddrbuf), "[%s]",
876 			    inet6_addrstr(&in6pcb.in6p_laddr));
877 			(void)printf(" %s:%d",
878 			    IN6_IS_ADDR_UNSPECIFIED(&in6pcb.in6p_laddr) ? "*" :
879 			    xaddrbuf,
880 			    ntohs(in6pcb.in6p_lport));
881 			if (in6pcb.in6p_fport) {
882 				(void)snprintf(xaddrbuf, sizeof(xaddrbuf),
883 				    "[%s]", inet6_addrstr(&in6pcb.in6p_faddr));
884 				(void)printf(" <-> %s:%d",
885 			            IN6_IS_ADDR_UNSPECIFIED(&in6pcb.in6p_faddr) ? "*" :
886 				    xaddrbuf,
887 				    ntohs(in6pcb.in6p_fport));
888 			}
889 		} else if (proto.pr_protocol == IPPROTO_UDP) {
890 			if (so.so_pcb == NULL)
891 				break;
892 			if (kvm_read(kd, (u_long)so.so_pcb, (char *)&in6pcb,
893 			    sizeof(struct in6pcb)) != sizeof(struct in6pcb)) {
894 				dprintf("can't read inpcb at %p", so.so_pcb);
895 				goto bad;
896 			}
897 			(void)printf(" %lx", (long)so.so_pcb);
898 			(void)snprintf(xaddrbuf, sizeof(xaddrbuf), "[%s]",
899 			    inet6_addrstr(&in6pcb.in6p_laddr));
900 			(void)printf(" %s:%d",
901 		            IN6_IS_ADDR_UNSPECIFIED(&in6pcb.in6p_laddr) ? "*" :
902 			    xaddrbuf,
903 			    ntohs(in6pcb.in6p_lport));
904 			if (in6pcb.in6p_fport) {
905 				(void)snprintf(xaddrbuf, sizeof(xaddrbuf), "[%s]",
906 				    inet6_addrstr(&in6pcb.in6p_faddr));
907 				(void)printf(" <-> %s:%d",
908 			            IN6_IS_ADDR_UNSPECIFIED(&in6pcb.in6p_faddr) ? "*" :
909 				    xaddrbuf,
910 				    ntohs(in6pcb.in6p_fport));
911 			}
912 		} else if (so.so_pcb)
913 			(void)printf(" %lx", (long)so.so_pcb);
914 		break;
915 #endif
916 	case AF_LOCAL:
917 		/* print address of pcb and connected pcb */
918 		if (so.so_pcb) {
919 			(void)printf(" %lx", (long)so.so_pcb);
920 			if (kvm_read(kd, (u_long)so.so_pcb, (char *)&unpcb,
921 			    sizeof(struct unpcb)) != sizeof(struct unpcb)){
922 				dprintf("can't read unpcb at %p", so.so_pcb);
923 				goto bad;
924 			}
925 			if (unpcb.unp_conn) {
926 				char shoconn[4], *cp;
927 
928 				cp = shoconn;
929 				if (!(so.so_state & SS_CANTRCVMORE))
930 					*cp++ = '<';
931 				*cp++ = '-';
932 				if (!(so.so_state & SS_CANTSENDMORE))
933 					*cp++ = '>';
934 				*cp = '\0';
935 				(void)printf(" %s %lx", shoconn,
936 				    (long)unpcb.unp_conn);
937 			}
938 		}
939 		break;
940 	default:
941 		/* print protocol number and socket address */
942 		(void)printf(" %d %lx", proto.pr_protocol, (long)sock);
943 	}
944 	(void)printf("\n");
945 	return;
946 bad:
947 	(void)printf("* error\n");
948 }
949 
950 static void
951 ptrans(struct file *fp, struct pipe *cpipe, int i)
952 {
953 	struct pipe cp;
954 
955 	PREFIX(i);
956 
957 	/* fill in pipe */
958 	if (!KVM_READ(cpipe, &cp, sizeof(struct pipe))) {
959 		dprintf("can't read pipe at %p", cpipe);
960 		goto bad;
961 	}
962 
963 	/* pipe descriptor is either read or write, never both */
964 	(void)printf("* pipe %p %s %p %s%s%s", cpipe,
965 		(fp->f_flag & FWRITE) ? "->" : "<-",
966 		cp.pipe_peer,
967 		(fp->f_flag & FWRITE) ? "w" : "r",
968 		(fp->f_flag & FNONBLOCK) ? "n" : "",
969 		(cp.pipe_state & PIPE_ASYNC) ? "a" : "");
970 	(void)printf("\n");
971 	return;
972 bad:
973 	(void)printf("* error\n");
974 }
975 
976 static void
977 misctrans(struct file *file)
978 {
979 
980 	PREFIX(file->f_type);
981 	pmisc(file, dtypes[file->f_type]);
982 }
983 
984 /*
985  * getinetproto --
986  *	print name of protocol number
987  */
988 static void
989 getinetproto(int number)
990 {
991 	const char *cp;
992 
993 	switch (number) {
994 	case IPPROTO_IP:
995 		cp = "ip"; break;
996 	case IPPROTO_ICMP:
997 		cp ="icmp"; break;
998 	case IPPROTO_GGP:
999 		cp ="ggp"; break;
1000 	case IPPROTO_TCP:
1001 		cp ="tcp"; break;
1002 	case IPPROTO_EGP:
1003 		cp ="egp"; break;
1004 	case IPPROTO_PUP:
1005 		cp ="pup"; break;
1006 	case IPPROTO_UDP:
1007 		cp ="udp"; break;
1008 	case IPPROTO_IDP:
1009 		cp ="idp"; break;
1010 	case IPPROTO_RAW:
1011 		cp ="raw"; break;
1012 	case IPPROTO_ICMPV6:
1013 		cp ="icmp6"; break;
1014 	default:
1015 		(void)printf(" %d", number);
1016 		return;
1017 	}
1018 	(void)printf(" %s", cp);
1019 }
1020 
1021 static int
1022 getfname(const char *filename)
1023 {
1024 	struct stat statbuf;
1025 	DEVS *cur;
1026 
1027 	if (stat(filename, &statbuf)) {
1028 		warn("stat(%s)", filename);
1029 		return 0;
1030 	}
1031 	if ((cur = malloc(sizeof(DEVS))) == NULL) {
1032 		err(1, "malloc(%u)", (unsigned int)sizeof(DEVS));
1033 	}
1034 	cur->next = devs;
1035 	devs = cur;
1036 
1037 	cur->ino = statbuf.st_ino;
1038 	cur->fsid = statbuf.st_dev & 0xffff;
1039 	cur->name = filename;
1040 	return 1;
1041 }
1042 
1043 mode_t
1044 getftype(enum vtype v_type)
1045 {
1046 	mode_t ftype;
1047 
1048 	switch (v_type) {
1049 	case VREG:
1050 		ftype = S_IFREG;
1051 		break;
1052 	case VDIR:
1053 		ftype = S_IFDIR;
1054 		break;
1055 	case VBLK:
1056 		ftype = S_IFBLK;
1057 		break;
1058 	case VCHR:
1059 		ftype = S_IFCHR;
1060 		break;
1061 	case VLNK:
1062 		ftype = S_IFLNK;
1063 		break;
1064 	case VSOCK:
1065 		ftype = S_IFSOCK;
1066 		break;
1067 	case VFIFO:
1068 		ftype = S_IFIFO;
1069 		break;
1070 	default:
1071 		ftype = 0;
1072 		break;
1073 	};
1074 
1075 	return ftype;
1076 }
1077 
1078 static void
1079 usage(void)
1080 {
1081 	(void)fprintf(stderr, "Usage: %s [-fnv] [-p pid] [-u user] "
1082 	    "[-N system] [-M core] [file ...]\n", getprogname());
1083 	exit(1);
1084 }
1085