xref: /netbsd-src/usr.bin/fstat/fstat.c (revision d0b9170efe70b3a8ede38a60ede546792c926885)
1 /*	$NetBSD: fstat.c,v 1.69 2004/11/16 05:59:32 itojun 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.69 2004/11/16 05:59:32 itojun 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 	const int niflags = NI_NUMERICHOST;
731 
732 	memset(&sin6, 0, sizeof(sin6));
733 	sin6.sin6_family = AF_INET6;
734 	sin6.sin6_len = sizeof(struct sockaddr_in6);
735 	sin6.sin6_addr = *p;
736 	if (IN6_IS_ADDR_LINKLOCAL(p) &&
737 	    *(u_int16_t *)&sin6.sin6_addr.s6_addr[2] != 0) {
738 		sin6.sin6_scope_id =
739 			ntohs(*(u_int16_t *)&sin6.sin6_addr.s6_addr[2]);
740 		sin6.sin6_addr.s6_addr[2] = sin6.sin6_addr.s6_addr[3] = 0;
741 	}
742 
743 	if (getnameinfo((struct sockaddr *)&sin6, sin6.sin6_len,
744 			hbuf, sizeof(hbuf), NULL, 0, niflags))
745 		return "invalid";
746 
747 	return hbuf;
748 }
749 #endif
750 
751 void
752 socktrans(sock, i)
753 	struct socket *sock;
754 	int i;
755 {
756 	static char *stypename[] = {
757 		"unused",	/* 0 */
758 		"stream", 	/* 1 */
759 		"dgram",	/* 2 */
760 		"raw",		/* 3 */
761 		"rdm",		/* 4 */
762 		"seqpak"	/* 5 */
763 	};
764 #define	STYPEMAX 5
765 	struct socket	so;
766 	struct protosw	proto;
767 	struct domain	dom;
768 	struct inpcb	inpcb;
769 #ifdef INET6
770 	struct in6pcb	in6pcb;
771 #endif
772 	struct unpcb	unpcb;
773 	int len;
774 	char dname[32];
775 #ifdef INET6
776 	char xaddrbuf[NI_MAXHOST + 2];
777 #endif
778 
779 	PREFIX(i);
780 
781 	/* fill in socket */
782 	if (!KVM_READ(sock, &so, sizeof(struct socket))) {
783 		dprintf("can't read sock at %p", sock);
784 		goto bad;
785 	}
786 
787 	/* fill in protosw entry */
788 	if (!KVM_READ(so.so_proto, &proto, sizeof(struct protosw))) {
789 		dprintf("can't read protosw at %p", so.so_proto);
790 		goto bad;
791 	}
792 
793 	/* fill in domain */
794 	if (!KVM_READ(proto.pr_domain, &dom, sizeof(struct domain))) {
795 		dprintf("can't read domain at %p", proto.pr_domain);
796 		goto bad;
797 	}
798 
799 	if ((len = kvm_read(kd, (u_long)dom.dom_name, dname,
800 	    sizeof(dname) - 1)) != sizeof(dname) -1) {
801 		dprintf("can't read domain name at %p", dom.dom_name);
802 		dname[0] = '\0';
803 	}
804 	else
805 		dname[len] = '\0';
806 
807 	if ((u_short)so.so_type > STYPEMAX)
808 		printf("* %s ?%d", dname, so.so_type);
809 	else
810 		printf("* %s %s", dname, stypename[so.so_type]);
811 
812 	/*
813 	 * protocol specific formatting
814 	 *
815 	 * Try to find interesting things to print.  For TCP, the interesting
816 	 * thing is the address of the tcpcb, for UDP and others, just the
817 	 * inpcb (socket pcb).  For UNIX domain, its the address of the socket
818 	 * pcb and the address of the connected pcb (if connected).  Otherwise
819 	 * just print the protocol number and address of the socket itself.
820 	 * The idea is not to duplicate netstat, but to make available enough
821 	 * information for further analysis.
822 	 */
823 	switch(dom.dom_family) {
824 	case AF_INET:
825 		getinetproto(proto.pr_protocol);
826 		if (proto.pr_protocol == IPPROTO_TCP) {
827 			if (so.so_pcb == NULL)
828 				break;
829 			if (kvm_read(kd, (u_long)so.so_pcb, (char *)&inpcb,
830 			    sizeof(struct inpcb)) != sizeof(struct inpcb)) {
831 				dprintf("can't read inpcb at %p", so.so_pcb);
832 				goto bad;
833 			}
834 			printf(" %lx", (long)inpcb.inp_ppcb);
835 			printf(" %s:%d",
836 			    inpcb.inp_laddr.s_addr == INADDR_ANY ? "*" :
837 			    inet_ntoa(inpcb.inp_laddr), ntohs(inpcb.inp_lport));
838 			if (inpcb.inp_fport) {
839 				printf(" <-> %s:%d",
840 				    inpcb.inp_faddr.s_addr == INADDR_ANY ? "*" :
841 				    inet_ntoa(inpcb.inp_faddr),
842 				    ntohs(inpcb.inp_fport));
843 			}
844 		} else if (proto.pr_protocol == IPPROTO_UDP) {
845 			if (so.so_pcb == NULL)
846 				break;
847 			if (kvm_read(kd, (u_long)so.so_pcb, (char *)&inpcb,
848 			    sizeof(struct inpcb)) != sizeof(struct inpcb)) {
849 				dprintf("can't read inpcb at %p", so.so_pcb);
850 				goto bad;
851 			}
852 			printf(" %lx", (long)so.so_pcb);
853 			printf(" %s:%d",
854 			    inpcb.inp_laddr.s_addr == INADDR_ANY ? "*" :
855 			    inet_ntoa(inpcb.inp_laddr), ntohs(inpcb.inp_lport));
856 			if (inpcb.inp_fport)
857 				printf(" <-> %s:%d",
858 				    inpcb.inp_faddr.s_addr == INADDR_ANY ? "*" :
859 				    inet_ntoa(inpcb.inp_faddr),
860 				    ntohs(inpcb.inp_fport));
861 		} else if (so.so_pcb)
862 			printf(" %lx", (long)so.so_pcb);
863 		break;
864 #ifdef INET6
865 	case AF_INET6:
866 		getinetproto(proto.pr_protocol);
867 		if (proto.pr_protocol == IPPROTO_TCP) {
868 			if (so.so_pcb == NULL)
869 				break;
870 			if (kvm_read(kd, (u_long)so.so_pcb, (char *)&in6pcb,
871 			    sizeof(struct in6pcb)) != sizeof(struct in6pcb)) {
872 				dprintf("can't read in6pcb at %p", so.so_pcb);
873 				goto bad;
874 			}
875 			printf(" %lx", (long)in6pcb.in6p_ppcb);
876 			snprintf(xaddrbuf, sizeof(xaddrbuf), "[%s]",
877 			    inet6_addrstr(&in6pcb.in6p_laddr));
878 			printf(" %s:%d",
879 			    IN6_IS_ADDR_UNSPECIFIED(&in6pcb.in6p_laddr) ? "*" :
880 			    xaddrbuf,
881 			    ntohs(in6pcb.in6p_lport));
882 			if (in6pcb.in6p_fport) {
883 				snprintf(xaddrbuf, sizeof(xaddrbuf), "[%s]",
884 				    inet6_addrstr(&in6pcb.in6p_faddr));
885 				printf(" <-> %s:%d",
886 			            IN6_IS_ADDR_UNSPECIFIED(&in6pcb.in6p_faddr) ? "*" :
887 				    xaddrbuf,
888 				    ntohs(in6pcb.in6p_fport));
889 			}
890 		} else if (proto.pr_protocol == IPPROTO_UDP) {
891 			if (so.so_pcb == NULL)
892 				break;
893 			if (kvm_read(kd, (u_long)so.so_pcb, (char *)&in6pcb,
894 			    sizeof(struct in6pcb)) != sizeof(struct in6pcb)) {
895 				dprintf("can't read inpcb at %p", so.so_pcb);
896 				goto bad;
897 			}
898 			printf(" %lx", (long)so.so_pcb);
899 			snprintf(xaddrbuf, sizeof(xaddrbuf), "[%s]",
900 			    inet6_addrstr(&in6pcb.in6p_laddr));
901 			printf(" %s:%d",
902 		            IN6_IS_ADDR_UNSPECIFIED(&in6pcb.in6p_laddr) ? "*" :
903 			    xaddrbuf,
904 			    ntohs(in6pcb.in6p_lport));
905 			if (in6pcb.in6p_fport) {
906 				snprintf(xaddrbuf, sizeof(xaddrbuf), "[%s]",
907 				    inet6_addrstr(&in6pcb.in6p_faddr));
908 				printf(" <-> %s:%d",
909 			            IN6_IS_ADDR_UNSPECIFIED(&in6pcb.in6p_faddr) ? "*" :
910 				    xaddrbuf,
911 				    ntohs(in6pcb.in6p_fport));
912 			}
913 		} else if (so.so_pcb)
914 			printf(" %lx", (long)so.so_pcb);
915 		break;
916 #endif
917 	case AF_LOCAL:
918 		/* print address of pcb and connected pcb */
919 		if (so.so_pcb) {
920 			printf(" %lx", (long)so.so_pcb);
921 			if (kvm_read(kd, (u_long)so.so_pcb, (char *)&unpcb,
922 			    sizeof(struct unpcb)) != sizeof(struct unpcb)){
923 				dprintf("can't read unpcb at %p", so.so_pcb);
924 				goto bad;
925 			}
926 			if (unpcb.unp_conn) {
927 				char shoconn[4], *cp;
928 
929 				cp = shoconn;
930 				if (!(so.so_state & SS_CANTRCVMORE))
931 					*cp++ = '<';
932 				*cp++ = '-';
933 				if (!(so.so_state & SS_CANTSENDMORE))
934 					*cp++ = '>';
935 				*cp = '\0';
936 				printf(" %s %lx", shoconn,
937 				    (long)unpcb.unp_conn);
938 			}
939 		}
940 		break;
941 	default:
942 		/* print protocol number and socket address */
943 		printf(" %d %lx", proto.pr_protocol, (long)sock);
944 	}
945 	printf("\n");
946 	return;
947 bad:
948 	printf("* error\n");
949 }
950 
951 void
952 ptrans(fp, cpipe, i)
953 	struct file *fp;
954 	struct pipe *cpipe;
955 	int i;
956 {
957 	struct pipe cp;
958 
959 	PREFIX(i);
960 
961 	/* fill in pipe */
962 	if (!KVM_READ(cpipe, &cp, sizeof(struct pipe))) {
963 		dprintf("can't read pipe at %p", cpipe);
964 		goto bad;
965 	}
966 
967 	/* pipe descriptor is either read or write, never both */
968 	printf("* pipe %p %s %p %s%s%s", cpipe,
969 		(fp->f_flag & FWRITE) ? "->" : "<-",
970 		cp.pipe_peer,
971 		(fp->f_flag & FWRITE) ? "w" : "r",
972 		(fp->f_flag & FNONBLOCK) ? "n" : "",
973 		(cp.pipe_state & PIPE_ASYNC) ? "a" : "");
974 	printf("\n");
975 	return;
976 bad:
977 	printf("* error\n");
978 }
979 
980 void
981 kqueuetrans(kq, i)
982 	void *kq;
983 	int i;
984 {
985 
986 	PREFIX(i);
987 	printf("* kqueue %lx", (long)kq);
988 	printf("\n");
989 }
990 
991 /*
992  * getinetproto --
993  *	print name of protocol number
994  */
995 void
996 getinetproto(number)
997 	int number;
998 {
999 	char *cp;
1000 
1001 	switch (number) {
1002 	case IPPROTO_IP:
1003 		cp = "ip"; break;
1004 	case IPPROTO_ICMP:
1005 		cp ="icmp"; break;
1006 	case IPPROTO_GGP:
1007 		cp ="ggp"; break;
1008 	case IPPROTO_TCP:
1009 		cp ="tcp"; break;
1010 	case IPPROTO_EGP:
1011 		cp ="egp"; break;
1012 	case IPPROTO_PUP:
1013 		cp ="pup"; break;
1014 	case IPPROTO_UDP:
1015 		cp ="udp"; break;
1016 	case IPPROTO_IDP:
1017 		cp ="idp"; break;
1018 	case IPPROTO_RAW:
1019 		cp ="raw"; break;
1020 	case IPPROTO_ICMPV6:
1021 		cp ="icmp6"; break;
1022 	default:
1023 		printf(" %d", number);
1024 		return;
1025 	}
1026 	printf(" %s", cp);
1027 }
1028 
1029 int
1030 getfname(filename)
1031 	char *filename;
1032 {
1033 	struct stat statbuf;
1034 	DEVS *cur;
1035 
1036 	if (stat(filename, &statbuf)) {
1037 		warn("stat(%s)", filename);
1038 		return(0);
1039 	}
1040 	if ((cur = malloc(sizeof(DEVS))) == NULL) {
1041 		err(1, "malloc(%u)", (unsigned int)sizeof(DEVS));
1042 	}
1043 	cur->next = devs;
1044 	devs = cur;
1045 
1046 	cur->ino = statbuf.st_ino;
1047 	cur->fsid = statbuf.st_dev & 0xffff;
1048 	cur->name = filename;
1049 	return(1);
1050 }
1051 
1052 mode_t
1053 getftype(v_type)
1054 	enum vtype v_type;
1055 {
1056 	mode_t ftype;
1057 
1058 	switch (v_type) {
1059 	case VREG:
1060 		ftype = S_IFREG;
1061 		break;
1062 	case VDIR:
1063 		ftype = S_IFDIR;
1064 		break;
1065 	case VBLK:
1066 		ftype = S_IFBLK;
1067 		break;
1068 	case VCHR:
1069 		ftype = S_IFCHR;
1070 		break;
1071 	case VLNK:
1072 		ftype = S_IFLNK;
1073 		break;
1074 	case VSOCK:
1075 		ftype = S_IFSOCK;
1076 		break;
1077 	case VFIFO:
1078 		ftype = S_IFIFO;
1079 		break;
1080 	default:
1081 		ftype = 0;
1082 		break;
1083 	};
1084 
1085 	return ftype;
1086 }
1087 
1088 void
1089 usage()
1090 {
1091 	errx(1,
1092  "usage: fstat [-fnv] [-p pid] [-u user] [-N system] [-M core] [file ...]\n");
1093 }
1094