xref: /netbsd-src/usr.bin/fstat/fstat.c (revision 89c5a767f8fc7a4633b2d409966e2becbb98ff92)
1 /*	$NetBSD: fstat.c,v 1.41 2000/02/04 11:02:00 jdolecek 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. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/cdefs.h>
37 #ifndef lint
38 __COPYRIGHT("@(#) Copyright (c) 1988, 1993\n\
39 	The Regents of the University of California.  All rights reserved.\n");
40 #endif /* not lint */
41 
42 #ifndef lint
43 #if 0
44 static char sccsid[] = "@(#)fstat.c	8.3 (Berkeley) 5/2/95";
45 #else
46 __RCSID("$NetBSD: fstat.c,v 1.41 2000/02/04 11:02:00 jdolecek Exp $");
47 #endif
48 #endif /* not lint */
49 
50 #include <sys/param.h>
51 #include <sys/time.h>
52 #include <sys/proc.h>
53 #include <sys/user.h>
54 #include <sys/stat.h>
55 #include <sys/vnode.h>
56 #include <sys/socket.h>
57 #include <sys/socketvar.h>
58 #include <sys/domain.h>
59 #include <sys/protosw.h>
60 #include <sys/unpcb.h>
61 #include <sys/sysctl.h>
62 #include <sys/filedesc.h>
63 #define	_KERNEL
64 #define _LKM
65 #include <sys/file.h>
66 #include <ufs/ufs/quota.h>
67 #include <ufs/ufs/inode.h>
68 #undef _LKM
69 #undef _KERNEL
70 #define _KERNEL
71 #include <sys/mount.h>
72 #undef _KERNEL
73 #define NFS
74 #include <nfs/nfsproto.h>
75 #include <nfs/rpcv2.h>
76 #include <nfs/nfs.h>
77 #include <nfs/nfsnode.h>
78 #undef NFS
79 #include <msdosfs/denode.h>
80 #include <msdosfs/bpb.h>
81 #define	_KERNEL
82 #include <msdosfs/msdosfsmount.h>
83 #undef _KERNEL
84 
85 #include <net/route.h>
86 #include <netinet/in.h>
87 #include <netinet/in_systm.h>
88 #include <netinet/ip.h>
89 #include <netinet/in_pcb.h>
90 
91 #ifdef INET6
92 #include <netinet/ip6.h>
93 #include <netinet6/ip6_var.h>
94 #include <netinet6/in6_pcb.h>
95 #endif
96 
97 #include <netdb.h>
98 #include <arpa/inet.h>
99 
100 #include <ctype.h>
101 #include <errno.h>
102 #include <kvm.h>
103 #include <limits.h>
104 #include <nlist.h>
105 #include <paths.h>
106 #include <pwd.h>
107 #include <stdio.h>
108 #include <stdlib.h>
109 #include <string.h>
110 #include <unistd.h>
111 #include <err.h>
112 
113 #include "fstat.h"
114 
115 #define	TEXT	-1
116 #define	CDIR	-2
117 #define	RDIR	-3
118 #define	TRACE	-4
119 
120 typedef struct devs {
121 	struct	devs *next;
122 	long	fsid;
123 	ino_t	ino;
124 	char	*name;
125 } DEVS;
126 DEVS *devs;
127 
128 int 	fsflg,	/* show files on same filesystem as file(s) argument */
129 	pflg,	/* show files open by a particular pid */
130 	uflg;	/* show files open by a particular (effective) user */
131 int 	checkfile; /* true if restricting to particular files or filesystems */
132 int	nflg;	/* (numerical) display f.s. and rdev as dev_t */
133 int	vflg;	/* display errors in locating kernel data objects etc... */
134 
135 struct file **ofiles;	/* buffer of pointers to file structures */
136 int maxfiles;
137 #define ALLOC_OFILES(d)	\
138 	if ((d) > maxfiles) { \
139 		free(ofiles); \
140 		ofiles = malloc((d) * sizeof(struct file *)); \
141 		if (ofiles == NULL) { \
142 			err(1, "malloc(%u)", (d) *	\
143 					(unsigned int)sizeof(struct file *)); \
144 		} \
145 		maxfiles = (d); \
146 	}
147 
148 kvm_t *kd;
149 
150 void	dofiles __P((struct kinfo_proc *));
151 int	ext2fs_filestat __P((struct vnode *, struct filestat *));
152 int	getfname __P((char *));
153 void	getinetproto __P((int));
154 char   *getmnton __P((struct mount *));
155 int	main __P((int, char **));
156 int	msdosfs_filestat __P((struct vnode *, struct filestat *));
157 int	nfs_filestat __P((struct vnode *, struct filestat *));
158 #ifdef INET6
159 static const char *inet6_addrstr __P((struct in6_addr *));
160 #endif
161 void	socktrans __P((struct socket *, int));
162 int	ufs_filestat __P((struct vnode *, struct filestat *));
163 void	usage __P((void));
164 void	vtrans __P((struct vnode *, int, int));
165 
166 int
167 main(argc, argv)
168 	int argc;
169 	char **argv;
170 {
171 	struct passwd *passwd;
172 	struct kinfo_proc *p, *plast;
173 	int arg, ch, what;
174 	char *memf, *nlistf;
175 	char buf[_POSIX2_LINE_MAX];
176 	int cnt;
177 	gid_t egid = getegid();
178 
179 	(void)setegid(getgid());
180 	arg = 0;
181 	what = KERN_PROC_ALL;
182 	nlistf = memf = NULL;
183 	while ((ch = getopt(argc, argv, "fnp:u:vN:M:")) != -1)
184 		switch((char)ch) {
185 		case 'f':
186 			fsflg = 1;
187 			break;
188 		case 'M':
189 			memf = optarg;
190 			break;
191 		case 'N':
192 			nlistf = optarg;
193 			break;
194 		case 'n':
195 			nflg = 1;
196 			break;
197 		case 'p':
198 			if (pflg++)
199 				usage();
200 			if (!isdigit(*optarg)) {
201 				warnx("-p requires a process id");
202 				usage();
203 			}
204 			what = KERN_PROC_PID;
205 			arg = atoi(optarg);
206 			break;
207 		case 'u':
208 			if (uflg++)
209 				usage();
210 			if (!(passwd = getpwnam(optarg))) {
211 				errx(1, "%s: unknown uid", optarg);
212 			}
213 			what = KERN_PROC_UID;
214 			arg = passwd->pw_uid;
215 			break;
216 		case 'v':
217 			vflg = 1;
218 			break;
219 		case '?':
220 		default:
221 			usage();
222 		}
223 
224 	if (*(argv += optind)) {
225 		for (; *argv; ++argv) {
226 			if (getfname(*argv))
227 				checkfile = 1;
228 		}
229 		if (!checkfile)	/* file(s) specified, but none accessable */
230 			exit(1);
231 	}
232 
233 	ALLOC_OFILES(256);	/* reserve space for file pointers */
234 
235 	if (fsflg && !checkfile) {
236 		/* -f with no files means use wd */
237 		if (getfname(".") == 0)
238 			exit(1);
239 		checkfile = 1;
240 	}
241 
242 	/*
243 	 * Discard setgid privileges.  If not the running kernel, we toss
244 	 * them away totally so that bad guys can't print interesting stuff
245 	 * from kernel memory, otherwise switch back to kmem for the
246 	 * duration of the kvm_openfiles() call.
247 	 */
248 	if (nlistf != NULL || memf != NULL)
249 		(void)setgid(getgid());
250 	else
251 		(void)setegid(egid);
252 
253 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, buf)) == NULL)
254 		errx(1, "%s", buf);
255 
256 	/* get rid of it now anyway */
257 	if (nlistf == NULL && memf == NULL)
258 		(void)setgid(getgid());
259 
260 	if ((p = kvm_getprocs(kd, what, arg, &cnt)) == NULL) {
261 		errx(1, "%s", kvm_geterr(kd));
262 	}
263 	if (nflg)
264 		printf("%s",
265 "USER     CMD          PID   FD  DEV    INUM       MODE SZ|DV R/W");
266 	else
267 		printf("%s",
268 "USER     CMD          PID   FD MOUNT      INUM MODE         SZ|DV R/W");
269 	if (checkfile && fsflg == 0)
270 		printf(" NAME\n");
271 	else
272 		putchar('\n');
273 
274 	for (plast = &p[cnt]; p < plast; ++p) {
275 		if (p->kp_proc.p_stat == SZOMB)
276 			continue;
277 		dofiles(p);
278 	}
279 	exit(0);
280 }
281 
282 const	char *Uname, *Comm;
283 pid_t	Pid;
284 
285 #define PREFIX(i) printf("%-8.8s %-10s %5d", Uname, Comm, Pid); \
286 	switch(i) { \
287 	case TEXT: \
288 		printf(" text"); \
289 		break; \
290 	case CDIR: \
291 		printf("   wd"); \
292 		break; \
293 	case RDIR: \
294 		printf(" root"); \
295 		break; \
296 	case TRACE: \
297 		printf("   tr"); \
298 		break; \
299 	default: \
300 		printf(" %4d", i); \
301 		break; \
302 	}
303 
304 /*
305  * print open files attributed to this process
306  */
307 void
308 dofiles(kp)
309 	struct kinfo_proc *kp;
310 {
311 	int i;
312 	struct file file;
313 	struct filedesc0 filed0;
314 #define	filed	filed0.fd_fd
315 	struct cwdinfo cwdi;
316 	struct proc *p = &kp->kp_proc;
317 	struct eproc *ep = &kp->kp_eproc;
318 
319 	Uname = user_from_uid(ep->e_ucred.cr_uid, 0);
320 	Pid = p->p_pid;
321 	Comm = p->p_comm;
322 
323 	if (p->p_fd == NULL || p->p_cwdi == NULL)
324 		return;
325 	if (!KVM_READ(p->p_fd, &filed0, sizeof (filed0))) {
326 		warnx("can't read filedesc at %p for pid %d", p->p_fd, Pid);
327 		return;
328 	}
329 	if (!KVM_READ(p->p_cwdi, &cwdi, sizeof(cwdi))) {
330 		warnx("can't read cwdinfo at %p for pid %d", p->p_cwdi, Pid);
331 		return;
332 	}
333 	if (filed.fd_nfiles < 0 || filed.fd_lastfile >= filed.fd_nfiles ||
334 	    filed.fd_freefile > filed.fd_lastfile + 1) {
335 		dprintf("filedesc corrupted at %p for pid %d", p->p_fd, Pid);
336 		return;
337 	}
338 	/*
339 	 * root directory vnode, if one
340 	 */
341 	if (cwdi.cwdi_rdir)
342 		vtrans(cwdi.cwdi_rdir, RDIR, FREAD);
343 	/*
344 	 * current working directory vnode
345 	 */
346 	vtrans(cwdi.cwdi_cdir, CDIR, FREAD);
347 	/*
348 	 * ktrace vnode, if one
349 	 */
350 	if (p->p_tracep)
351 		vtrans(p->p_tracep, TRACE, FREAD|FWRITE);
352 	/*
353 	 * open files
354 	 */
355 #define FPSIZE	(sizeof (struct file *))
356 	ALLOC_OFILES(filed.fd_lastfile+1);
357 	if (filed.fd_nfiles > NDFILE) {
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 	} else
365 		memmove(ofiles, filed0.fd_dfiles,
366 		    (filed.fd_lastfile+1) * FPSIZE);
367 	for (i = 0; i <= filed.fd_lastfile; i++) {
368 		if (ofiles[i] == NULL)
369 			continue;
370 		if (!KVM_READ(ofiles[i], &file, sizeof (struct file))) {
371 			dprintf("can't read file %d at %p for pid %d",
372 			    i, ofiles[i], Pid);
373 			continue;
374 		}
375 		if (file.f_type == DTYPE_VNODE)
376 			vtrans((struct vnode *)file.f_data, i, file.f_flag);
377 		else if (file.f_type == DTYPE_SOCKET) {
378 			if (checkfile == 0)
379 				socktrans((struct socket *)file.f_data, i);
380 		}
381 		else {
382 			dprintf("unknown file type %d for file %d of pid %d",
383 				file.f_type, i, Pid);
384 		}
385 	}
386 }
387 
388 void
389 vtrans(vp, i, flag)
390 	struct vnode *vp;
391 	int i;
392 	int flag;
393 {
394 	struct vnode vn;
395 	struct filestat fst;
396 	char mode[15], rw[3];
397 	char *badtype = NULL, *filename;
398 
399 	filename = badtype = NULL;
400 	if (!KVM_READ(vp, &vn, sizeof (struct vnode))) {
401 		dprintf("can't read vnode at %p for pid %d", vp, Pid);
402 		return;
403 	}
404 	if (vn.v_type == VNON || vn.v_tag == VT_NON)
405 		badtype = "none";
406 	else if (vn.v_type == VBAD)
407 		badtype = "bad";
408 	else
409 		switch (vn.v_tag) {
410 		case VT_UFS:
411 			if (!ufs_filestat(&vn, &fst))
412 				badtype = "error";
413 			break;
414 		case VT_MFS:
415 			if (!ufs_filestat(&vn, &fst))
416 				badtype = "error";
417 			break;
418 		case VT_MSDOSFS:
419 			if (!msdosfs_filestat(&vn, &fst))
420 				badtype = "error";
421 			break;
422 		case VT_NFS:
423 			if (!nfs_filestat(&vn, &fst))
424 				badtype = "error";
425 			break;
426 		case VT_EXT2FS:
427 			if (!ext2fs_filestat(&vn, &fst))
428 				badtype = "error";
429 			break;
430 		case VT_ISOFS:
431 			if (!isofs_filestat(&vn, &fst))
432 				badtype = "error";
433 			break;
434 		case VT_NTFS:
435 			if (!ntfs_filestat(&vn, &fst))
436 				badtype = "error";
437 			break;
438 		default: {
439 			static char unknown[10];
440 			(void)snprintf(badtype = unknown, sizeof unknown,
441 			    "?(%x)", vn.v_tag);
442 			break;;
443 		}
444 	}
445 	if (checkfile) {
446 		int fsmatch = 0;
447 		DEVS *d;
448 
449 		if (badtype)
450 			return;
451 		for (d = devs; d != NULL; d = d->next)
452 			if (d->fsid == fst.fsid) {
453 				fsmatch = 1;
454 				if (d->ino == fst.fileid) {
455 					filename = d->name;
456 					break;
457 				}
458 			}
459 		if (fsmatch == 0 || (filename == NULL && fsflg == 0))
460 			return;
461 	}
462 	PREFIX(i);
463 	if (badtype) {
464 		(void)printf(" -         -  %10s    -\n", badtype);
465 		return;
466 	}
467 	if (nflg)
468 		(void)printf(" %2d,%-2d", major(fst.fsid), minor(fst.fsid));
469 	else
470 		(void)printf(" %-8s", getmnton(vn.v_mount));
471 	if (nflg)
472 		(void)snprintf(mode, sizeof mode, "%o", fst.mode);
473 	else
474 		strmode(fst.mode, mode);
475 	(void)printf(" %6ld %10s", (long)fst.fileid, mode);
476 	switch (vn.v_type) {
477 	case VBLK:
478 	case VCHR: {
479 		char *name;
480 
481 		if (nflg || ((name = devname(fst.rdev, vn.v_type == VCHR ?
482 		    S_IFCHR : S_IFBLK)) == NULL))
483 			printf("  %2d,%-2d", major(fst.rdev), minor(fst.rdev));
484 		else
485 			printf(" %6s", name);
486 		break;
487 	}
488 	default:
489 		printf(" %6qd", (long long)fst.size);
490 	}
491 	rw[0] = '\0';
492 	if (flag & FREAD)
493 		strcat(rw, "r");
494 	if (flag & FWRITE)
495 		strcat(rw, "w");
496 	printf(" %-2s", rw);
497 	if (filename && !fsflg)
498 		printf("  %s", filename);
499 	putchar('\n');
500 }
501 
502 int
503 ufs_filestat(vp, fsp)
504 	struct vnode *vp;
505 	struct filestat *fsp;
506 {
507 	struct inode inode;
508 
509 	if (!KVM_READ(VTOI(vp), &inode, sizeof (inode))) {
510 		dprintf("can't read inode at %p for pid %d", VTOI(vp), Pid);
511 		return 0;
512 	}
513 	fsp->fsid = inode.i_dev & 0xffff;
514 	fsp->fileid = (long)inode.i_number;
515 	fsp->mode = (mode_t)inode.i_ffs_mode;
516 	fsp->size = inode.i_ffs_size;
517 	fsp->rdev = inode.i_ffs_rdev;
518 
519 	return 1;
520 }
521 
522 int
523 ext2fs_filestat(vp, fsp)
524 	struct vnode *vp;
525 	struct filestat *fsp;
526 {
527 	struct inode inode;
528 
529 	if (!KVM_READ(VTOI(vp), &inode, sizeof (inode))) {
530 		dprintf("can't read inode at %p for pid %d", VTOI(vp), Pid);
531 		return 0;
532 	}
533 	fsp->fsid = inode.i_dev & 0xffff;
534 	fsp->fileid = (long)inode.i_number;
535 	fsp->mode = (mode_t)inode.i_e2fs_mode;
536 	fsp->size = inode.i_e2fs_size;
537 	fsp->rdev = 0;  /* XXX */
538 	return 1;
539 }
540 
541 int
542 nfs_filestat(vp, fsp)
543 	struct vnode *vp;
544 	struct filestat *fsp;
545 {
546 	struct nfsnode nfsnode;
547 	struct vattr va;
548 
549 	if (!KVM_READ(VTONFS(vp), &nfsnode, sizeof (nfsnode))) {
550 		dprintf("can't read nfsnode at %p for pid %d", VTONFS(vp),
551 		    Pid);
552 		return 0;
553 	}
554 	if (!KVM_READ(nfsnode.n_vattr, &va, sizeof(va))) {
555 		dprintf("can't read vnode attributes at %p for pid %d",
556 		    nfsnode.n_vattr, Pid);
557 		return 0;
558 	}
559 	fsp->fsid = va.va_fsid;
560 	fsp->fileid = va.va_fileid;
561 	fsp->size = nfsnode.n_size;
562 	fsp->rdev = va.va_rdev;
563 	fsp->mode = (mode_t)va.va_mode | getftype(vp->v_type);
564 
565 	return 1;
566 }
567 
568 int
569 msdosfs_filestat(vp, fsp)
570 	struct vnode *vp;
571 	struct filestat *fsp;
572 {
573 	struct denode de;
574 	struct msdosfsmount mp;
575 
576 	if (!KVM_READ(VTONFS(vp), &de, sizeof(de))) {
577 		dprintf("can't read denode at %p for pid %d", VTONFS(vp),
578 		    Pid);
579 		return 0;
580 	}
581 	if (!KVM_READ(de.de_pmp, &mp, sizeof(mp))) {
582 		dprintf("can't read mount struct at %p for pid %d", de.de_pmp,
583 		    Pid);
584 		return 0;
585 	}
586 
587 	fsp->fsid = de.de_dev & 0xffff;
588 	fsp->fileid = 0; /* XXX see msdosfs_vptofh() for more info */
589 	fsp->size = de.de_FileSize;
590 	fsp->rdev = 0;	/* msdosfs doesn't support device files */
591 	fsp->mode = (0777 & mp.pm_mask) | getftype(vp->v_type);
592 	return 1;
593 }
594 
595 char *
596 getmnton(m)
597 	struct mount *m;
598 {
599 	static struct mount mount;
600 	static struct mtab {
601 		struct mtab *next;
602 		struct mount *m;
603 		char mntonname[MNAMELEN];
604 	} *mhead = NULL;
605 	struct mtab *mt;
606 
607 	for (mt = mhead; mt != NULL; mt = mt->next)
608 		if (m == mt->m)
609 			return (mt->mntonname);
610 	if (!KVM_READ(m, &mount, sizeof(struct mount))) {
611 		warnx("can't read mount table at %p", m);
612 		return (NULL);
613 	}
614 	if ((mt = malloc(sizeof (struct mtab))) == NULL) {
615 		err(1, "malloc(%u)", (unsigned int)sizeof(struct mtab));
616 	}
617 	mt->m = m;
618 	memmove(&mt->mntonname[0], &mount.mnt_stat.f_mntonname[0], MNAMELEN);
619 	mt->next = mhead;
620 	mhead = mt;
621 	return (mt->mntonname);
622 }
623 
624 #ifdef INET6
625 static const char *
626 inet6_addrstr(p)
627 	struct in6_addr *p;
628 {
629 	struct sockaddr_in6 sin6;
630 	static char hbuf[NI_MAXHOST];
631 #ifdef NI_WITHSCOPEID
632 	const int niflags = NI_NUMERICHOST | NI_WITHSCOPEID;
633 #else
634 	const int niflags = NI_NUMERICHOST;
635 #endif
636 
637 	memset(&sin6, 0, sizeof(sin6));
638 	sin6.sin6_family = AF_INET6;
639 	sin6.sin6_len = sizeof(struct sockaddr_in6);
640 	sin6.sin6_addr = *p;
641 	if (IN6_IS_ADDR_LINKLOCAL(p) &&
642 	    *(u_int16_t *)&sin6.sin6_addr.s6_addr[2] != 0) {
643 		sin6.sin6_scope_id =
644 			ntohs(*(u_int16_t *)&sin6.sin6_addr.s6_addr[2]);
645 		sin6.sin6_addr.s6_addr[2] = sin6.sin6_addr.s6_addr[3] = 0;
646 	}
647 
648 	if (getnameinfo((struct sockaddr *)&sin6, sin6.sin6_len,
649 			hbuf, sizeof(hbuf), NULL, 0, niflags))
650 		return "invalid";
651 
652 	return hbuf;
653 }
654 #endif
655 
656 void
657 socktrans(sock, i)
658 	struct socket *sock;
659 	int i;
660 {
661 	static char *stypename[] = {
662 		"unused",	/* 0 */
663 		"stream", 	/* 1 */
664 		"dgram",	/* 2 */
665 		"raw",		/* 3 */
666 		"rdm",		/* 4 */
667 		"seqpak"	/* 5 */
668 	};
669 #define	STYPEMAX 5
670 	struct socket	so;
671 	struct protosw	proto;
672 	struct domain	dom;
673 	struct inpcb	inpcb;
674 #ifdef INET6
675 	struct in6pcb	in6pcb;
676 #endif
677 	struct unpcb	unpcb;
678 	int len;
679 	char dname[32];
680 #ifdef INET6
681 	char xaddrbuf[NI_MAXHOST + 2];
682 #endif
683 
684 	PREFIX(i);
685 
686 	/* fill in socket */
687 	if (!KVM_READ(sock, &so, sizeof(struct socket))) {
688 		dprintf("can't read sock at %p", sock);
689 		goto bad;
690 	}
691 
692 	/* fill in protosw entry */
693 	if (!KVM_READ(so.so_proto, &proto, sizeof(struct protosw))) {
694 		dprintf("can't read protosw at %p", so.so_proto);
695 		goto bad;
696 	}
697 
698 	/* fill in domain */
699 	if (!KVM_READ(proto.pr_domain, &dom, sizeof(struct domain))) {
700 		dprintf("can't read domain at %p", proto.pr_domain);
701 		goto bad;
702 	}
703 
704 	if ((len = kvm_read(kd, (u_long)dom.dom_name, dname,
705 	    sizeof(dname) - 1)) != sizeof(dname) -1) {
706 		dprintf("can't read domain name at %p", dom.dom_name);
707 		dname[0] = '\0';
708 	}
709 	else
710 		dname[len] = '\0';
711 
712 	if ((u_short)so.so_type > STYPEMAX)
713 		printf("* %s ?%d", dname, so.so_type);
714 	else
715 		printf("* %s %s", dname, stypename[so.so_type]);
716 
717 	/*
718 	 * protocol specific formatting
719 	 *
720 	 * Try to find interesting things to print.  For TCP, the interesting
721 	 * thing is the address of the tcpcb, for UDP and others, just the
722 	 * inpcb (socket pcb).  For UNIX domain, its the address of the socket
723 	 * pcb and the address of the connected pcb (if connected).  Otherwise
724 	 * just print the protocol number and address of the socket itself.
725 	 * The idea is not to duplicate netstat, but to make available enough
726 	 * information for further analysis.
727 	 */
728 	switch(dom.dom_family) {
729 	case AF_INET:
730 		getinetproto(proto.pr_protocol);
731 		if (proto.pr_protocol == IPPROTO_TCP) {
732 			if (so.so_pcb == NULL)
733 				break;
734 			if (kvm_read(kd, (u_long)so.so_pcb, (char *)&inpcb,
735 			    sizeof(struct inpcb)) != sizeof(struct inpcb)) {
736 				dprintf("can't read inpcb at %p", so.so_pcb);
737 				goto bad;
738 			}
739 			printf(" %lx", (long)inpcb.inp_ppcb);
740 			printf(" %s:%d",
741 			    inpcb.inp_laddr.s_addr == INADDR_ANY ? "*" :
742 			    inet_ntoa(inpcb.inp_laddr), ntohs(inpcb.inp_lport));
743 			if (inpcb.inp_fport) {
744 				printf(" <-> %s:%d",
745 				    inpcb.inp_faddr.s_addr == INADDR_ANY ? "*" :
746 				    inet_ntoa(inpcb.inp_faddr),
747 				    ntohs(inpcb.inp_fport));
748 			}
749 		} else if (proto.pr_protocol == IPPROTO_UDP) {
750 			if (so.so_pcb == NULL)
751 				break;
752 			if (kvm_read(kd, (u_long)so.so_pcb, (char *)&inpcb,
753 			    sizeof(struct inpcb)) != sizeof(struct inpcb)) {
754 				dprintf("can't read inpcb at %p", so.so_pcb);
755 				goto bad;
756 			}
757 			printf(" %lx", (long)so.so_pcb);
758 			printf(" %s:%d",
759 			    inpcb.inp_laddr.s_addr == INADDR_ANY ? "*" :
760 			    inet_ntoa(inpcb.inp_laddr), ntohs(inpcb.inp_lport));
761 			if (inpcb.inp_fport)
762 				printf(" <-> %s:%d",
763 				    inpcb.inp_faddr.s_addr == INADDR_ANY ? "*" :
764 				    inet_ntoa(inpcb.inp_faddr),
765 				    ntohs(inpcb.inp_fport));
766 		} else if (so.so_pcb)
767 			printf(" %lx", (long)so.so_pcb);
768 		break;
769 #ifdef INET6
770 	case AF_INET6:
771 		getinetproto(proto.pr_protocol);
772 		if (proto.pr_protocol == IPPROTO_TCP) {
773 			if (so.so_pcb == NULL)
774 				break;
775 			if (kvm_read(kd, (u_long)so.so_pcb, (char *)&in6pcb,
776 			    sizeof(struct in6pcb)) != sizeof(struct in6pcb)) {
777 				dprintf("can't read in6pcb at %p", so.so_pcb);
778 				goto bad;
779 			}
780 			printf(" %lx", (long)in6pcb.in6p_ppcb);
781 			sprintf(xaddrbuf, "[%s]",
782 			    inet6_addrstr(&in6pcb.in6p_laddr));
783 			printf(" %s:%d",
784 			    IN6_IS_ADDR_UNSPECIFIED(&in6pcb.in6p_laddr) ? "*" :
785 			    xaddrbuf,
786 			    ntohs(in6pcb.in6p_lport));
787 			if (in6pcb.in6p_fport) {
788 				sprintf(xaddrbuf, "[%s]",
789 				    inet6_addrstr(&in6pcb.in6p_faddr));
790 				printf(" <-> %s:%d",
791 			            IN6_IS_ADDR_UNSPECIFIED(&in6pcb.in6p_faddr) ? "*" :
792 				    xaddrbuf,
793 				    ntohs(in6pcb.in6p_fport));
794 			}
795 		} else if (proto.pr_protocol == IPPROTO_UDP) {
796 			if (so.so_pcb == NULL)
797 				break;
798 			if (kvm_read(kd, (u_long)so.so_pcb, (char *)&in6pcb,
799 			    sizeof(struct in6pcb)) != sizeof(struct in6pcb)) {
800 				dprintf("can't read inpcb at %p", so.so_pcb);
801 				goto bad;
802 			}
803 			printf(" %lx", (long)so.so_pcb);
804 			sprintf(xaddrbuf, "[%s]",
805 			    inet6_addrstr(&in6pcb.in6p_laddr));
806 			printf(" %s:%d",
807 		            IN6_IS_ADDR_UNSPECIFIED(&in6pcb.in6p_laddr) ? "*" :
808 			    xaddrbuf,
809 			    ntohs(in6pcb.in6p_lport));
810 			if (in6pcb.in6p_fport) {
811 				sprintf(xaddrbuf, "[%s]",
812 				    inet6_addrstr(&in6pcb.in6p_faddr));
813 				printf(" <-> %s:%d",
814 			            IN6_IS_ADDR_UNSPECIFIED(&in6pcb.in6p_faddr) ? "*" :
815 				    xaddrbuf,
816 				    ntohs(in6pcb.in6p_fport));
817 			}
818 		} else if (so.so_pcb)
819 			printf(" %lx", (long)so.so_pcb);
820 		break;
821 #endif
822 	case AF_LOCAL:
823 		/* print address of pcb and connected pcb */
824 		if (so.so_pcb) {
825 			printf(" %lx", (long)so.so_pcb);
826 			if (kvm_read(kd, (u_long)so.so_pcb, (char *)&unpcb,
827 			    sizeof(struct unpcb)) != sizeof(struct unpcb)){
828 				dprintf("can't read unpcb at %p", so.so_pcb);
829 				goto bad;
830 			}
831 			if (unpcb.unp_conn) {
832 				char shoconn[4], *cp;
833 
834 				cp = shoconn;
835 				if (!(so.so_state & SS_CANTRCVMORE))
836 					*cp++ = '<';
837 				*cp++ = '-';
838 				if (!(so.so_state & SS_CANTSENDMORE))
839 					*cp++ = '>';
840 				*cp = '\0';
841 				printf(" %s %lx", shoconn,
842 				    (long)unpcb.unp_conn);
843 			}
844 		}
845 		break;
846 	default:
847 		/* print protocol number and socket address */
848 		printf(" %d %lx", proto.pr_protocol, (long)sock);
849 	}
850 	printf("\n");
851 	return;
852 bad:
853 	printf("* error\n");
854 }
855 
856 /*
857  * getinetproto --
858  *	print name of protocol number
859  */
860 void
861 getinetproto(number)
862 	int number;
863 {
864 	char *cp;
865 
866 	switch (number) {
867 	case IPPROTO_IP:
868 		cp = "ip"; break;
869 	case IPPROTO_ICMP:
870 		cp ="icmp"; break;
871 	case IPPROTO_GGP:
872 		cp ="ggp"; break;
873 	case IPPROTO_TCP:
874 		cp ="tcp"; break;
875 	case IPPROTO_EGP:
876 		cp ="egp"; break;
877 	case IPPROTO_PUP:
878 		cp ="pup"; break;
879 	case IPPROTO_UDP:
880 		cp ="udp"; break;
881 	case IPPROTO_IDP:
882 		cp ="idp"; break;
883 	case IPPROTO_RAW:
884 		cp ="raw"; break;
885 	case IPPROTO_ICMPV6:
886 		cp ="icmp6"; break;
887 	default:
888 		printf(" %d", number);
889 		return;
890 	}
891 	printf(" %s", cp);
892 }
893 
894 int
895 getfname(filename)
896 	char *filename;
897 {
898 	struct stat statbuf;
899 	DEVS *cur;
900 
901 	if (stat(filename, &statbuf)) {
902 		warn("stat(%s)", filename);
903 		return(0);
904 	}
905 	if ((cur = malloc(sizeof(DEVS))) == NULL) {
906 		err(1, "malloc(%u)", (unsigned int)sizeof(DEVS));
907 	}
908 	cur->next = devs;
909 	devs = cur;
910 
911 	cur->ino = statbuf.st_ino;
912 	cur->fsid = statbuf.st_dev & 0xffff;
913 	cur->name = filename;
914 	return(1);
915 }
916 
917 mode_t
918 getftype(v_type)
919 	enum vtype v_type;
920 {
921 	mode_t ftype;
922 
923 	switch (v_type) {
924 	case VREG:
925 		ftype = S_IFREG;
926 		break;
927 	case VDIR:
928 		ftype = S_IFDIR;
929 		break;
930 	case VBLK:
931 		ftype = S_IFBLK;
932 		break;
933 	case VCHR:
934 		ftype = S_IFCHR;
935 		break;
936 	case VLNK:
937 		ftype = S_IFLNK;
938 		break;
939 	case VSOCK:
940 		ftype = S_IFSOCK;
941 		break;
942 	case VFIFO:
943 		ftype = S_IFIFO;
944 		break;
945 	default:
946 		ftype = 0;
947 		break;
948 	};
949 
950 	return ftype;
951 }
952 
953 void
954 usage()
955 {
956 	errx(1,
957  "usage: fstat [-fnv] [-p pid] [-u user] [-N system] [-M core] [file ...]\n");
958 }
959