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