xref: /original-bsd/usr.bin/fstat/fstat.c (revision 00695d63)
1 /*-
2  * Copyright (c) 1988, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #ifndef lint
9 static char copyright[] =
10 "@(#) Copyright (c) 1988, 1993\n\
11 	The Regents of the University of California.  All rights reserved.\n";
12 #endif /* not lint */
13 
14 #ifndef lint
15 static char sccsid[] = "@(#)fstat.c	8.2 (Berkeley) 04/28/95";
16 #endif /* not lint */
17 
18 #include <sys/param.h>
19 #include <sys/time.h>
20 #include <sys/proc.h>
21 #include <sys/user.h>
22 #include <sys/stat.h>
23 #include <sys/vnode.h>
24 #include <sys/socket.h>
25 #include <sys/socketvar.h>
26 #include <sys/domain.h>
27 #include <sys/protosw.h>
28 #include <sys/unpcb.h>
29 #include <sys/sysctl.h>
30 #include <sys/filedesc.h>
31 #define	KERNEL
32 #include <sys/file.h>
33 #include <ufs/ufs/quota.h>
34 #include <ufs/ufs/inode.h>
35 #undef KERNEL
36 #define NFS
37 #include <sys/mount.h>
38 #include <nfs/nfsv2.h>
39 #include <nfs/rpcv2.h>
40 #include <nfs/nfs.h>
41 #include <nfs/nfsnode.h>
42 #undef NFS
43 
44 #include <net/route.h>
45 #include <netinet/in.h>
46 #include <netinet/in_systm.h>
47 #include <netinet/ip.h>
48 #include <netinet/in_pcb.h>
49 
50 #include <ctype.h>
51 #include <errno.h>
52 #include <kvm.h>
53 #include <limits.h>
54 #include <nlist.h>
55 #include <paths.h>
56 #include <pwd.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 
61 #define	TEXT	-1
62 #define	CDIR	-2
63 #define	RDIR	-3
64 #define	TRACE	-4
65 
66 typedef struct devs {
67 	struct	devs *next;
68 	long	fsid;
69 	ino_t	ino;
70 	char	*name;
71 } DEVS;
72 DEVS *devs;
73 
74 struct  filestat {
75 	long	fsid;
76 	long	fileid;
77 	mode_t	mode;
78 	u_long	size;
79 	dev_t	rdev;
80 };
81 
82 #ifdef notdef
83 struct nlist nl[] = {
84 	{ "" },
85 };
86 #endif
87 
88 int 	fsflg,	/* show files on same filesystem as file(s) argument */
89 	pflg,	/* show files open by a particular pid */
90 	uflg;	/* show files open by a particular (effective) user */
91 int 	checkfile; /* true if restricting to particular files or filesystems */
92 int	nflg;	/* (numerical) display f.s. and rdev as dev_t */
93 int	vflg;	/* display errors in locating kernel data objects etc... */
94 
95 #define dprintf	if (vflg) fprintf
96 
97 struct file **ofiles;	/* buffer of pointers to file structures */
98 int maxfiles;
99 #define ALLOC_OFILES(d)	\
100 	if ((d) > maxfiles) { \
101 		free(ofiles); \
102 		ofiles = malloc((d) * sizeof(struct file *)); \
103 		if (ofiles == NULL) { \
104 			fprintf(stderr, "fstat: %s\n", strerror(errno)); \
105 			exit(1); \
106 		} \
107 		maxfiles = (d); \
108 	}
109 
110 /*
111  * a kvm_read that returns true if everything is read
112  */
113 #define KVM_READ(kaddr, paddr, len) \
114 	(kvm_read(kd, (u_long)(kaddr), (char *)(paddr), (len)) == (len))
115 
116 kvm_t *kd;
117 
118 int ufs_filestat(), nfs_filestat();
119 void dofiles(), getinetproto(), socktrans();
120 void usage(), vtrans();
121 
122 main(argc, argv)
123 	int argc;
124 	char **argv;
125 {
126 	extern char *optarg;
127 	extern int optind;
128 	register struct passwd *passwd;
129 	struct kinfo_proc *p, *plast;
130 	int arg, ch, what;
131 	char *memf, *nlistf;
132 	char buf[_POSIX2_LINE_MAX];
133 	int cnt;
134 
135 	arg = 0;
136 	what = KERN_PROC_ALL;
137 	nlistf = memf = NULL;
138 	while ((ch = getopt(argc, argv, "fnp:u:vNM")) != EOF)
139 		switch((char)ch) {
140 		case 'f':
141 			fsflg = 1;
142 			break;
143 		case 'M':
144 			memf = optarg;
145 			break;
146 		case 'N':
147 			nlistf = optarg;
148 			break;
149 		case 'n':
150 			nflg = 1;
151 			break;
152 		case 'p':
153 			if (pflg++)
154 				usage();
155 			if (!isdigit(*optarg)) {
156 				fprintf(stderr,
157 				    "fstat: -p requires a process id\n");
158 				usage();
159 			}
160 			what = KERN_PROC_PID;
161 			arg = atoi(optarg);
162 			break;
163 		case 'u':
164 			if (uflg++)
165 				usage();
166 			if (!(passwd = getpwnam(optarg))) {
167 				fprintf(stderr, "%s: unknown uid\n",
168 				    optarg);
169 				exit(1);
170 			}
171 			what = KERN_PROC_UID;
172 			arg = passwd->pw_uid;
173 			break;
174 		case 'v':
175 			vflg = 1;
176 			break;
177 		case '?':
178 		default:
179 			usage();
180 		}
181 
182 	if (*(argv += optind)) {
183 		for (; *argv; ++argv) {
184 			if (getfname(*argv))
185 				checkfile = 1;
186 		}
187 		if (!checkfile)	/* file(s) specified, but none accessable */
188 			exit(1);
189 	}
190 
191 	ALLOC_OFILES(256);	/* reserve space for file pointers */
192 
193 	if (fsflg && !checkfile) {
194 		/* -f with no files means use wd */
195 		if (getfname(".") == 0)
196 			exit(1);
197 		checkfile = 1;
198 	}
199 
200 	/*
201 	 * Discard setgid privileges if not the running kernel so that bad
202 	 * guys can't print interesting stuff from kernel memory.
203 	 */
204 	if (nlistf != NULL || memf != NULL)
205 		setgid(getgid());
206 
207 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, buf)) == NULL) {
208 		fprintf(stderr, "fstat: %s\n", buf);
209 		exit(1);
210 	}
211 #ifdef notdef
212 	if (kvm_nlist(kd, nl) != 0) {
213 		fprintf(stderr, "fstat: no namelist: %s\n", kvm_geterr(kd));
214 		exit(1);
215 	}
216 #endif
217 	if ((p = kvm_getprocs(kd, what, arg, &cnt)) == NULL) {
218 		fprintf(stderr, "fstat: %s\n", kvm_geterr(kd));
219 		exit(1);
220 	}
221 	if (nflg)
222 		printf("%s",
223 "USER     CMD          PID   FD  DEV    INUM       MODE SZ|DV R/W");
224 	else
225 		printf("%s",
226 "USER     CMD          PID   FD MOUNT      INUM MODE         SZ|DV R/W");
227 	if (checkfile && fsflg == 0)
228 		printf(" NAME\n");
229 	else
230 		putchar('\n');
231 
232 	for (plast = &p[cnt]; p < plast; ++p) {
233 		if (p->kp_proc.p_stat == SZOMB)
234 			continue;
235 		dofiles(p);
236 	}
237 	exit(0);
238 }
239 
240 char	*Uname, *Comm;
241 int	Pid;
242 
243 #define PREFIX(i) printf("%-8.8s %-10s %5d", Uname, Comm, Pid); \
244 	switch(i) { \
245 	case TEXT: \
246 		printf(" text"); \
247 		break; \
248 	case CDIR: \
249 		printf("   wd"); \
250 		break; \
251 	case RDIR: \
252 		printf(" root"); \
253 		break; \
254 	case TRACE: \
255 		printf("   tr"); \
256 		break; \
257 	default: \
258 		printf(" %4d", i); \
259 		break; \
260 	}
261 
262 /*
263  * print open files attributed to this process
264  */
265 void
266 dofiles(kp)
267 	struct kinfo_proc *kp;
268 {
269 	int i, last;
270 	struct file file;
271 	struct filedesc0 filed0;
272 #define	filed	filed0.fd_fd
273 	struct proc *p = &kp->kp_proc;
274 	struct eproc *ep = &kp->kp_eproc;
275 
276 	extern char *user_from_uid();
277 
278 	Uname = user_from_uid(ep->e_ucred.cr_uid, 0);
279 	Pid = p->p_pid;
280 	Comm = p->p_comm;
281 
282 	if (p->p_fd == NULL)
283 		return;
284 	if (!KVM_READ(p->p_fd, &filed0, sizeof (filed0))) {
285 		dprintf(stderr, "can't read filedesc at %x for pid %d\n",
286 			p->p_fd, Pid);
287 		return;
288 	}
289 	/*
290 	 * root directory vnode, if one
291 	 */
292 	if (filed.fd_rdir)
293 		vtrans(filed.fd_rdir, RDIR, FREAD);
294 	/*
295 	 * current working directory vnode
296 	 */
297 	vtrans(filed.fd_cdir, CDIR, FREAD);
298 	/*
299 	 * ktrace vnode, if one
300 	 */
301 	if (p->p_tracep)
302 		vtrans(p->p_tracep, TRACE, FREAD|FWRITE);
303 	/*
304 	 * open files
305 	 */
306 #define FPSIZE	(sizeof (struct file *))
307 	ALLOC_OFILES(filed.fd_lastfile+1);
308 	if (filed.fd_nfiles > NDFILE) {
309 		if (!KVM_READ(filed.fd_ofiles, ofiles,
310 		    (filed.fd_lastfile+1) * FPSIZE)) {
311 			dprintf(stderr,
312 			    "can't read file structures at %x for pid %d\n",
313 			    filed.fd_ofiles, Pid);
314 			return;
315 		}
316 	} else
317 		bcopy(filed0.fd_dfiles, ofiles, (filed.fd_lastfile+1) * FPSIZE);
318 	for (i = 0; i <= filed.fd_lastfile; i++) {
319 		if (ofiles[i] == NULL)
320 			continue;
321 		if (!KVM_READ(ofiles[i], &file, sizeof (struct file))) {
322 			dprintf(stderr, "can't read file %d at %x for pid %d\n",
323 				i, ofiles[i], Pid);
324 			continue;
325 		}
326 		if (file.f_type == DTYPE_VNODE)
327 			vtrans((struct vnode *)file.f_data, i, file.f_flag);
328 		else if (file.f_type == DTYPE_SOCKET) {
329 			if (checkfile == 0)
330 				socktrans((struct socket *)file.f_data, i);
331 		}
332 		else {
333 			dprintf(stderr,
334 				"unknown file type %d for file %d of pid %d\n",
335 				file.f_type, i, Pid);
336 		}
337 	}
338 }
339 
340 void
341 vtrans(vp, i, flag)
342 	struct vnode *vp;
343 	int i;
344 	int flag;
345 {
346 	struct vnode vn;
347 	struct filestat fst;
348 	char rw[3], mode[15];
349 	char *badtype = NULL, *filename, *getmnton();
350 
351 	filename = badtype = NULL;
352 	if (!KVM_READ(vp, &vn, sizeof (struct vnode))) {
353 		dprintf(stderr, "can't read vnode at %x for pid %d\n",
354 			vp, Pid);
355 		return;
356 	}
357 	if (vn.v_type == VNON || vn.v_tag == VT_NON)
358 		badtype = "none";
359 	else if (vn.v_type == VBAD)
360 		badtype = "bad";
361 	else
362 		switch (vn.v_tag) {
363 		case VT_UFS:
364 			if (!ufs_filestat(&vn, &fst))
365 				badtype = "error";
366 			break;
367 		case VT_MFS:
368 			if (!ufs_filestat(&vn, &fst))
369 				badtype = "error";
370 			break;
371 		case VT_NFS:
372 			if (!nfs_filestat(&vn, &fst))
373 				badtype = "error";
374 			break;
375 		default: {
376 			static char unknown[10];
377 			sprintf(badtype = unknown, "?(%x)", vn.v_tag);
378 			break;;
379 		}
380 	}
381 	if (checkfile) {
382 		int fsmatch = 0;
383 		register DEVS *d;
384 
385 		if (badtype)
386 			return;
387 		for (d = devs; d != NULL; d = d->next)
388 			if (d->fsid == fst.fsid) {
389 				fsmatch = 1;
390 				if (d->ino == fst.fileid) {
391 					filename = d->name;
392 					break;
393 				}
394 			}
395 		if (fsmatch == 0 || (filename == NULL && fsflg == 0))
396 			return;
397 	}
398 	PREFIX(i);
399 	if (badtype) {
400 		(void)printf(" -         -  %10s    -\n", badtype);
401 		return;
402 	}
403 	if (nflg)
404 		(void)printf(" %2d,%-2d", major(fst.fsid), minor(fst.fsid));
405 	else
406 		(void)printf(" %-8s", getmnton(vn.v_mount));
407 	if (nflg)
408 		(void)sprintf(mode, "%o", fst.mode);
409 	else
410 		strmode(fst.mode, mode);
411 	(void)printf(" %6d %10s", fst.fileid, mode);
412 	switch (vn.v_type) {
413 	case VBLK:
414 	case VCHR: {
415 		char *name;
416 
417 		if (nflg || ((name = devname(fst.rdev, vn.v_type == VCHR ?
418 		    S_IFCHR : S_IFBLK)) == NULL))
419 			printf("  %2d,%-2d", major(fst.rdev), minor(fst.rdev));
420 		else
421 			printf(" %6s", name);
422 		break;
423 	}
424 	default:
425 		printf(" %6d", fst.size);
426 	}
427 	rw[0] = '\0';
428 	if (flag & FREAD)
429 		strcat(rw, "r");
430 	if (flag & FWRITE)
431 		strcat(rw, "w");
432 	printf(" %2s", rw);
433 	if (filename && !fsflg)
434 		printf("  %s", filename);
435 	putchar('\n');
436 }
437 
438 int
439 ufs_filestat(vp, fsp)
440 	struct vnode *vp;
441 	struct filestat *fsp;
442 {
443 	struct inode inode;
444 
445 	if (!KVM_READ(VTOI(vp), &inode, sizeof (inode))) {
446 		dprintf(stderr, "can't read inode at %x for pid %d\n",
447 			VTOI(vp), Pid);
448 		return 0;
449 	}
450 	fsp->fsid = inode.i_dev & 0xffff;
451 	fsp->fileid = (long)inode.i_number;
452 	fsp->mode = (mode_t)inode.i_mode;
453 	fsp->size = (u_long)inode.i_size;
454 	fsp->rdev = inode.i_rdev;
455 
456 	return 1;
457 }
458 
459 int
460 nfs_filestat(vp, fsp)
461 	struct vnode *vp;
462 	struct filestat *fsp;
463 {
464 	struct nfsnode nfsnode;
465 	register mode_t mode;
466 
467 	if (!KVM_READ(VTONFS(vp), &nfsnode, sizeof (nfsnode))) {
468 		dprintf(stderr, "can't read nfsnode at %x for pid %d\n",
469 			VTONFS(vp), Pid);
470 		return 0;
471 	}
472 	fsp->fsid = nfsnode.n_vattr.va_fsid;
473 	fsp->fileid = nfsnode.n_vattr.va_fileid;
474 	fsp->size = nfsnode.n_size;
475 	fsp->rdev = nfsnode.n_vattr.va_rdev;
476 	mode = (mode_t)nfsnode.n_vattr.va_mode;
477 	switch (vp->v_type) {
478 	case VREG:
479 		mode |= S_IFREG;
480 		break;
481 	case VDIR:
482 		mode |= S_IFDIR;
483 		break;
484 	case VBLK:
485 		mode |= S_IFBLK;
486 		break;
487 	case VCHR:
488 		mode |= S_IFCHR;
489 		break;
490 	case VLNK:
491 		mode |= S_IFLNK;
492 		break;
493 	case VSOCK:
494 		mode |= S_IFSOCK;
495 		break;
496 	case VFIFO:
497 		mode |= S_IFIFO;
498 		break;
499 	};
500 	fsp->mode = mode;
501 
502 	return 1;
503 }
504 
505 
506 char *
507 getmnton(m)
508 	struct mount *m;
509 {
510 	static struct mount mount;
511 	static struct mtab {
512 		struct mtab *next;
513 		struct mount *m;
514 		char mntonname[MNAMELEN];
515 	} *mhead = NULL;
516 	register struct mtab *mt;
517 
518 	for (mt = mhead; mt != NULL; mt = mt->next)
519 		if (m == mt->m)
520 			return (mt->mntonname);
521 	if (!KVM_READ(m, &mount, sizeof(struct mount))) {
522 		fprintf(stderr, "can't read mount table at %x\n", m);
523 		return (NULL);
524 	}
525 	if ((mt = malloc(sizeof (struct mtab))) == NULL) {
526 		fprintf(stderr, "fstat: %s\n", strerror(errno));
527 		exit(1);
528 	}
529 	mt->m = m;
530 	bcopy(&mount.mnt_stat.f_mntonname[0], &mt->mntonname[0], MNAMELEN);
531 	mt->next = mhead;
532 	mhead = mt;
533 	return (mt->mntonname);
534 }
535 
536 void
537 socktrans(sock, i)
538 	struct socket *sock;
539 	int i;
540 {
541 	static char *stypename[] = {
542 		"unused",	/* 0 */
543 		"stream", 	/* 1 */
544 		"dgram",	/* 2 */
545 		"raw",		/* 3 */
546 		"rdm",		/* 4 */
547 		"seqpak"	/* 5 */
548 	};
549 #define	STYPEMAX 5
550 	struct socket	so;
551 	struct protosw	proto;
552 	struct domain	dom;
553 	struct inpcb	inpcb;
554 	struct unpcb	unpcb;
555 	int len;
556 	char dname[32], *strcpy();
557 
558 	PREFIX(i);
559 
560 	/* fill in socket */
561 	if (!KVM_READ(sock, &so, sizeof(struct socket))) {
562 		dprintf(stderr, "can't read sock at %x\n", sock);
563 		goto bad;
564 	}
565 
566 	/* fill in protosw entry */
567 	if (!KVM_READ(so.so_proto, &proto, sizeof(struct protosw))) {
568 		dprintf(stderr, "can't read protosw at %x", so.so_proto);
569 		goto bad;
570 	}
571 
572 	/* fill in domain */
573 	if (!KVM_READ(proto.pr_domain, &dom, sizeof(struct domain))) {
574 		dprintf(stderr, "can't read domain at %x\n", proto.pr_domain);
575 		goto bad;
576 	}
577 
578 	if ((len = kvm_read(kd, (u_long)dom.dom_name, dname,
579 	    sizeof(dname) - 1)) < 0) {
580 		dprintf(stderr, "can't read domain name at %x\n",
581 			dom.dom_name);
582 		dname[0] = '\0';
583 	}
584 	else
585 		dname[len] = '\0';
586 
587 	if ((u_short)so.so_type > STYPEMAX)
588 		printf("* %s ?%d", dname, so.so_type);
589 	else
590 		printf("* %s %s", dname, stypename[so.so_type]);
591 
592 	/*
593 	 * protocol specific formatting
594 	 *
595 	 * Try to find interesting things to print.  For tcp, the interesting
596 	 * thing is the address of the tcpcb, for udp and others, just the
597 	 * inpcb (socket pcb).  For unix domain, its the address of the socket
598 	 * pcb and the address of the connected pcb (if connected).  Otherwise
599 	 * just print the protocol number and address of the socket itself.
600 	 * The idea is not to duplicate netstat, but to make available enough
601 	 * information for further analysis.
602 	 */
603 	switch(dom.dom_family) {
604 	case AF_INET:
605 		getinetproto(proto.pr_protocol);
606 		if (proto.pr_protocol == IPPROTO_TCP ) {
607 			if (so.so_pcb) {
608 				if (kvm_read(kd, (u_long)so.so_pcb,
609 				    (char *)&inpcb, sizeof(struct inpcb))
610 				    != sizeof(struct inpcb)) {
611 					dprintf(stderr,
612 					    "can't read inpcb at %x\n",
613 					    so.so_pcb);
614 					goto bad;
615 				}
616 				printf(" %x", (int)inpcb.inp_ppcb);
617 			}
618 		}
619 		else if (so.so_pcb)
620 			printf(" %x", (int)so.so_pcb);
621 		break;
622 	case AF_UNIX:
623 		/* print address of pcb and connected pcb */
624 		if (so.so_pcb) {
625 			printf(" %x", (int)so.so_pcb);
626 			if (kvm_read(kd, (u_long)so.so_pcb, (char *)&unpcb,
627 			    sizeof(struct unpcb)) != sizeof(struct unpcb)){
628 				dprintf(stderr, "can't read unpcb at %x\n",
629 				    so.so_pcb);
630 				goto bad;
631 			}
632 			if (unpcb.unp_conn) {
633 				char shoconn[4], *cp;
634 
635 				cp = shoconn;
636 				if (!(so.so_state & SS_CANTRCVMORE))
637 					*cp++ = '<';
638 				*cp++ = '-';
639 				if (!(so.so_state & SS_CANTSENDMORE))
640 					*cp++ = '>';
641 				*cp = '\0';
642 				printf(" %s %x", shoconn,
643 				    (int)unpcb.unp_conn);
644 			}
645 		}
646 		break;
647 	default:
648 		/* print protocol number and socket address */
649 		printf(" %d %x", proto.pr_protocol, (int)sock);
650 	}
651 	printf("\n");
652 	return;
653 bad:
654 	printf("* error\n");
655 }
656 
657 /*
658  * getinetproto --
659  *	print name of protocol number
660  */
661 void
662 getinetproto(number)
663 	int number;
664 {
665 	char *cp;
666 
667 	switch(number) {
668 	case IPPROTO_IP:
669 		cp = "ip"; break;
670 	case IPPROTO_ICMP:
671 		cp ="icmp"; break;
672 	case IPPROTO_GGP:
673 		cp ="ggp"; break;
674 	case IPPROTO_TCP:
675 		cp ="tcp"; break;
676 	case IPPROTO_EGP:
677 		cp ="egp"; break;
678 	case IPPROTO_PUP:
679 		cp ="pup"; break;
680 	case IPPROTO_UDP:
681 		cp ="udp"; break;
682 	case IPPROTO_IDP:
683 		cp ="idp"; break;
684 	case IPPROTO_RAW:
685 		cp ="raw"; break;
686 	default:
687 		printf(" %d", number);
688 		return;
689 	}
690 	printf(" %s", cp);
691 }
692 
693 getfname(filename)
694 	char *filename;
695 {
696 	struct stat statbuf;
697 	DEVS *cur;
698 
699 	if (stat(filename, &statbuf)) {
700 		fprintf(stderr, "fstat: %s: %s\n", filename, strerror(errno));
701 		return(0);
702 	}
703 	if ((cur = malloc(sizeof(DEVS))) == NULL) {
704 		fprintf(stderr, "fstat: %s\n", strerror(errno));
705 		exit(1);
706 	}
707 	cur->next = devs;
708 	devs = cur;
709 
710 	cur->ino = statbuf.st_ino;
711 	cur->fsid = statbuf.st_dev & 0xffff;
712 	cur->name = filename;
713 	return(1);
714 }
715 
716 void
717 usage()
718 {
719 	(void)fprintf(stderr,
720  "usage: fstat [-fnv] [-p pid] [-u user] [-N system] [-M core] [file ...]\n");
721 	exit(1);
722 }
723