summaryrefslogtreecommitdiffstats
path: root/usr.bin/fstat/fstat.c
blob: 1aeee67511dd7f695254706608e53888880e276f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
/*-
 * Copyright (c) 2009 Stanislav Sedov <stas@FreeBSD.org>
 * Copyright (c) 1988, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include <sys/param.h>
#include <sys/user.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/socketvar.h>
#include <sys/sysctl.h>
#include <sys/queue.h>

#include <netinet/in.h>

#include <assert.h>
#include <ctype.h>
#include <err.h>
#include <libprocstat.h>
#include <limits.h>
#include <pwd.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>

#include "functions.h"

static int 	fsflg,	/* show files on same filesystem as file(s) argument */
		pflg,	/* show files open by a particular pid */
		uflg;	/* show files open by a particular (effective) user */
static int 	checkfile; /* restrict to particular files or filesystems */
static int	nflg;	/* (numerical) display f.s. and rdev as dev_t */
static int	mflg;	/* include memory-mapped files */
static int	vflg;	/* be verbose */

typedef struct devs {
	struct devs	*next;
	uint32_t	fsid;
	uint64_t	ino;
	const char	*name;
} DEVS;

static DEVS *devs;
static char *memf, *nlistf;

static int	getfname(const char *filename);
static void	dofiles(struct procstat *procstat, struct kinfo_proc *p);
static void	print_access_flags(int flags);
static void	print_file_info(struct procstat *procstat,
    struct filestat *fst, const char *uname, const char *cmd, int pid);
static void	print_pipe_info(struct procstat *procstat,
    struct filestat *fst);
static void	print_pts_info(struct procstat *procstat,
    struct filestat *fst);
static void	print_sem_info(struct procstat *procstat,
    struct filestat *fst);
static void	print_shm_info(struct procstat *procstat,
    struct filestat *fst);
static void	print_socket_info(struct procstat *procstat,
    struct filestat *fst);
static void	print_vnode_info(struct procstat *procstat,
    struct filestat *fst);
static void	usage(void) __dead2;

int
do_fstat(int argc, char **argv)
{
	struct kinfo_proc *p;
	struct passwd *passwd;
	struct procstat *procstat;
	int arg, ch, what;
	int cnt, i;

	arg = 0;
	what = KERN_PROC_PROC;
	nlistf = memf = NULL;
	while ((ch = getopt(argc, argv, "fmnp:u:vN:M:")) != -1)
		switch((char)ch) {
		case 'f':
			fsflg = 1;
			break;
		case 'M':
			memf = optarg;
			break;
		case 'N':
			nlistf = optarg;
			break;
		case 'm':
			mflg = 1;
			break;
		case 'n':
			nflg = 1;
			break;
		case 'p':
			if (pflg++)
				usage();
			if (!isdigit(*optarg)) {
				warnx("-p requires a process id");
				usage();
			}
			what = KERN_PROC_PID;
			arg = atoi(optarg);
			break;
		case 'u':
			if (uflg++)
				usage();
			if (!(passwd = getpwnam(optarg)))
				errx(1, "%s: unknown uid", optarg);
			what = KERN_PROC_UID;
			arg = passwd->pw_uid;
			break;
		case 'v':
			vflg = 1;
			break;
		case '?':
		default:
			usage();
		}

	if (*(argv += optind)) {
		for (; *argv; ++argv) {
			if (getfname(*argv))
				checkfile = 1;
		}
		if (!checkfile)	/* file(s) specified, but none accessible */
			exit(1);
	}

	if (fsflg && !checkfile) {
		/* -f with no files means use wd */
		if (getfname(".") == 0)
			exit(1);
		checkfile = 1;
	}

	if (memf != NULL)
		procstat = procstat_open_kvm(nlistf, memf);
	else
		procstat = procstat_open_sysctl();
	if (procstat == NULL)
		errx(1, "procstat_open()");
	p = procstat_getprocs(procstat, what, arg, &cnt);
	if (p == NULL)
		errx(1, "procstat_getprocs()");

	/*
	 * Print header.
	 */
	if (nflg)
		printf("%s",
"USER     CMD          PID   FD  DEV    INUM       MODE SZ|DV R/W");
	else
		printf("%s",
"USER     CMD          PID   FD MOUNT      INUM MODE         SZ|DV R/W");
	if (checkfile && fsflg == 0)
		printf(" NAME\n");
	else
		putchar('\n');

	/*
	 * Go through the process list.
	 */
	for (i = 0; i < cnt; i++) {
		if (p[i].ki_stat == SZOMB)
			continue;
		dofiles(procstat, &p[i]);
	}
	procstat_freeprocs(procstat, p);
	procstat_close(procstat);
	return (0);
}

static void
dofiles(struct procstat *procstat, struct kinfo_proc *kp)
{
	const char *cmd;
	const char *uname;
	struct filestat *fst;
	struct filestat_list *head;
	int pid;

	uname = user_from_uid(kp->ki_uid, 0);
	pid = kp->ki_pid;
	cmd = kp->ki_comm;

	head = procstat_getfiles(procstat, kp, mflg);
	if (head == NULL)
		return;
	STAILQ_FOREACH(fst, head, next)
		print_file_info(procstat, fst, uname, cmd, pid);
	procstat_freefiles(procstat, head);
}


static void
print_file_info(struct procstat *procstat, struct filestat *fst,
    const char *uname, const char *cmd, int pid)
{
	struct vnstat vn;
	DEVS *d;
	const char *filename;
	int error, fsmatch = 0;
	char errbuf[_POSIX2_LINE_MAX];

	filename = NULL;
	if (checkfile != 0) {
		if (fst->fs_type != PS_FST_TYPE_VNODE &&
		    fst->fs_type != PS_FST_TYPE_FIFO)
			return;
		error = procstat_get_vnode_info(procstat, fst, &vn, errbuf);
		if (error != 0)
			return;

		for (d = devs; d != NULL; d = d->next)
			if (d->fsid == vn.vn_fsid) {
				fsmatch = 1;
				if (d->ino == vn.vn_fileid) {
					filename = d->name;
					break;
				}
			}
		if (fsmatch == 0 || (filename == NULL && fsflg == 0))
			return;
	}

	/*
	 * Print entry prefix.
	 */
	printf("%-8.8s %-10s %5d", uname, cmd, pid);
	if (fst->fs_uflags & PS_FST_UFLAG_TEXT)
		printf(" text");
	else if (fst->fs_uflags & PS_FST_UFLAG_CDIR)
		printf("   wd");
	else if (fst->fs_uflags & PS_FST_UFLAG_RDIR)
		printf(" root");
	else if (fst->fs_uflags & PS_FST_UFLAG_TRACE)
		printf("   tr");
	else if (fst->fs_uflags & PS_FST_UFLAG_MMAP)
		printf(" mmap");
	else if (fst->fs_uflags & PS_FST_UFLAG_JAIL)
		printf(" jail");
	else if (fst->fs_uflags & PS_FST_UFLAG_CTTY)
		printf(" ctty");
	else
		printf(" %4d", fst->fs_fd);

	/*
	 * Print type-specific data.
	 */
	switch (fst->fs_type) {
	case PS_FST_TYPE_FIFO:
	case PS_FST_TYPE_VNODE:
		print_vnode_info(procstat, fst);
		break;
	case PS_FST_TYPE_SOCKET:
		print_socket_info(procstat, fst);
		break;
	case PS_FST_TYPE_PIPE:
		print_pipe_info(procstat, fst);
		break;
	case PS_FST_TYPE_PTS:
		print_pts_info(procstat, fst);
		break;
	case PS_FST_TYPE_SHM:
		print_shm_info(procstat, fst);
		break;
	case PS_FST_TYPE_SEM:
		print_sem_info(procstat, fst);
		break;
	default:	
		if (vflg)
			fprintf(stderr,
			    "unknown file type %d for file %d of pid %d\n",
			    fst->fs_type, fst->fs_fd, pid);
	}
	if (filename && !fsflg)
		printf("  %s", filename);
	putchar('\n');
}

static void
print_socket_info(struct procstat *procstat, struct filestat *fst)
{
	static const char *stypename[] = {
		"unused",	/* 0 */
		"stream",	/* 1 */
		"dgram",	/* 2 */
		"raw",		/* 3 */
		"rdm",		/* 4 */
		"seqpak"	/* 5 */
	};
#define STYPEMAX 5
	struct sockstat sock;
	struct protoent *pe;
	char errbuf[_POSIX2_LINE_MAX];
	int error;
	static int isopen;

	error = procstat_get_socket_info(procstat, fst, &sock, errbuf);
	if (error != 0) {
		printf("* error");
		return;
	}
	if (sock.type > STYPEMAX)
		printf("* %s ?%d", sock.dname, sock.type);
	else
		printf("* %s %s", sock.dname, stypename[sock.type]);

	/*
	 * protocol specific formatting
	 *
	 * Try to find interesting things to print.  For tcp, the interesting
	 * thing is the address of the tcpcb, for udp and others, just the
	 * inpcb (socket pcb).  For unix domain, its the address of the socket
	 * pcb and the address of the connected pcb (if connected).  Otherwise
	 * just print the protocol number and address of the socket itself.
	 * The idea is not to duplicate netstat, but to make available enough
	 * information for further analysis.
	 */
	switch (sock.dom_family) {
	case AF_INET:
	case AF_INET6:
		if (!isopen)
			setprotoent(++isopen);
		if ((pe = getprotobynumber(sock.proto)) != NULL)
			printf(" %s", pe->p_name);
		else
			printf(" %d", sock.proto);
		if (sock.proto == IPPROTO_TCP ) {
			if (sock.inp_ppcb != 0)
				printf(" %lx", (u_long)sock.inp_ppcb);
		}
		else if (sock.so_pcb != 0)
			printf(" %lx", (u_long)sock.so_pcb);
		break;
	case AF_UNIX:
		/* print address of pcb and connected pcb */
		if (sock.so_pcb != 0) {
			printf(" %lx", (u_long)sock.so_pcb);
			if (sock.unp_conn) {
				char shoconn[4], *cp;

				cp = shoconn;
				if (!(sock.so_rcv_sb_state & SBS_CANTRCVMORE))
					*cp++ = '<';
				*cp++ = '-';
				if (!(sock.so_snd_sb_state & SBS_CANTSENDMORE))
					*cp++ = '>';
				*cp = '\0';
				printf(" %s %lx", shoconn,
				    (u_long)sock.unp_conn);
                        }
		}
		break;
	default:
		/* print protocol number and socket address */
		printf(" %d %lx", sock.proto, (u_long)sock.so_addr);
	}
}

static void
print_pipe_info(struct procstat *procstat, struct filestat *fst)
{
	struct pipestat ps;
	char errbuf[_POSIX2_LINE_MAX];
	int error;

	error = procstat_get_pipe_info(procstat, fst, &ps, errbuf);
	if (error != 0) {
		printf("* error");
		return;
	}
	printf("* pipe %8lx <-> %8lx", (u_long)ps.addr, (u_long)ps.peer);
	printf(" %6zd", ps.buffer_cnt);
	print_access_flags(fst->fs_fflags);
}

static void
print_pts_info(struct procstat *procstat, struct filestat *fst)
{
	struct ptsstat pts;
	char errbuf[_POSIX2_LINE_MAX];
	int error;

	error = procstat_get_pts_info(procstat, fst, &pts, errbuf);
	if (error != 0) {
		printf("* error");
		return;
	}
	printf("* pseudo-terminal master ");
	if (nflg || !*pts.devname) {
		printf("%#10jx", (uintmax_t)pts.dev);
	} else {
		printf("%10s", pts.devname);
	}
	print_access_flags(fst->fs_fflags);
}

static void
print_sem_info(struct procstat *procstat, struct filestat *fst)
{
	struct semstat sem;
	char errbuf[_POSIX2_LINE_MAX];
	char mode[15];
	int error;

	error = procstat_get_sem_info(procstat, fst, &sem, errbuf);
	if (error != 0) {
		printf("* error");
		return;
	}
	if (nflg) {
		printf("             ");
		(void)snprintf(mode, sizeof(mode), "%o", sem.mode);
	} else {
		printf(" %-15s", fst->fs_path != NULL ? fst->fs_path : "-");
		strmode(sem.mode, mode);
	}
	printf(" %10s %6u", mode, sem.value);
	print_access_flags(fst->fs_fflags);
}

static void
print_shm_info(struct procstat *procstat, struct filestat *fst)
{
	struct shmstat shm;
	char errbuf[_POSIX2_LINE_MAX];
	char mode[15];
	int error;

	error = procstat_get_shm_info(procstat, fst, &shm, errbuf);
	if (error != 0) {
		printf("* error");
		return;
	}
	if (nflg) {
		printf("             ");
		(void)snprintf(mode, sizeof(mode), "%o", shm.mode);
	} else {
		printf(" %-15s", fst->fs_path != NULL ? fst->fs_path : "-");
		strmode(shm.mode, mode);
	}
	printf(" %10s %6ju", mode, shm.size);
	print_access_flags(fst->fs_fflags);
}

static void
print_vnode_info(struct procstat *procstat, struct filestat *fst)
{
	struct vnstat vn;
	char errbuf[_POSIX2_LINE_MAX];
	char mode[15];
	const char *badtype;
	int error;

	badtype = NULL;
	error = procstat_get_vnode_info(procstat, fst, &vn, errbuf);
	if (error != 0)
		badtype = errbuf;
	else if (vn.vn_type == PS_FST_VTYPE_VBAD)
		badtype = "bad";
	else if (vn.vn_type == PS_FST_VTYPE_VNON)
		badtype = "none";
	if (badtype != NULL) {
		printf(" -         -  %10s    -", badtype);
		return;
	}

	if (nflg)
		printf(" %#5jx", (uintmax_t)vn.vn_fsid);
	else if (vn.vn_mntdir != NULL)
		(void)printf(" %-8s", vn.vn_mntdir);

	/*
	 * Print access mode.
	 */
	if (nflg)
		(void)snprintf(mode, sizeof(mode), "%o", vn.vn_mode);
	else {
		strmode(vn.vn_mode, mode);
	}
	(void)printf(" %6jd %10s", (intmax_t)vn.vn_fileid, mode);

	if (vn.vn_type == PS_FST_VTYPE_VBLK || vn.vn_type == PS_FST_VTYPE_VCHR) {
		if (nflg || !*vn.vn_devname)
			printf(" %#6jx", (uintmax_t)vn.vn_dev);
		else {
			printf(" %6s", vn.vn_devname);
		}
	} else
		printf(" %6ju", (uintmax_t)vn.vn_size);
	print_access_flags(fst->fs_fflags);
}

static void
print_access_flags(int flags)
{
	char rw[3];

	rw[0] = '\0';
	if (flags & PS_FST_FFLAG_READ)
		strcat(rw, "r");
	if (flags & PS_FST_FFLAG_WRITE)
		strcat(rw, "w");
	printf(" %2s", rw);
}

int
getfname(const char *filename)
{
	struct stat statbuf;
	DEVS *cur;

	if (stat(filename, &statbuf)) {
		warn("%s", filename);
		return (0);
	}
	if ((cur = malloc(sizeof(DEVS))) == NULL)
		err(1, NULL);
	cur->next = devs;
	devs = cur;

	cur->ino = statbuf.st_ino;
	cur->fsid = statbuf.st_dev;
	cur->name = filename;
	return (1);
}

static void
usage(void)
{
	(void)fprintf(stderr,
 "usage: fstat [-fmnv] [-M core] [-N system] [-p pid] [-u user] [file ...]\n");
	exit(1);
}
OpenPOWER on IntegriCloud