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