summaryrefslogtreecommitdiffstats
path: root/usr.bin/fstat/fuser.c
blob: dbb0d863a3a4950d0af7968ac8d9285a0d12327e (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
/*-
 * Copyright (c) 2005-2009 Stanislav Sedov <stas@FreeBSD.org>
 * 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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/queue.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/user.h>

#include <assert.h>
#include <ctype.h>
#include <err.h>
#include <fcntl.h>
#include <libprocstat.h>
#include <limits.h>
#include <paths.h>
#include <pwd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <unistd.h>

#include "functions.h"

/*
 * File access mode flags table.
 */
static const struct {
	int	flag;
	char	ch;
} fflags[] = {
	{PS_FST_FFLAG_WRITE,	'w'},
	{PS_FST_FFLAG_APPEND,	'a'},
	{PS_FST_FFLAG_DIRECT,	'd'},
	{PS_FST_FFLAG_SHLOCK,	's'},
	{PS_FST_FFLAG_EXLOCK,	'e'}
};
#define	NFFLAGS	(sizeof(fflags) / sizeof(*fflags))

/*
 * Usage flags translation table.
 */
static const struct {
	int	flag;
	char	ch;
} uflags[] = {
	{PS_FST_UFLAG_RDIR,	'r'},
	{PS_FST_UFLAG_CDIR,	'c'},
	{PS_FST_UFLAG_JAIL,	'j'},
	{PS_FST_UFLAG_TRACE,	't'},
	{PS_FST_UFLAG_TEXT,	'x'},
	{PS_FST_UFLAG_MMAP,	'm'},
	{PS_FST_UFLAG_CTTY,	'y'}
};
#define	NUFLAGS	(sizeof(uflags) / sizeof(*uflags))

struct consumer {
	pid_t	pid;
	uid_t	uid;
	int	fd;
	int	flags;
	int	uflags;
	STAILQ_ENTRY(consumer)	next;
};
struct reqfile {
	uint32_t	fsid;
	uint64_t	fileid;
	const char	*name;
	STAILQ_HEAD(, consumer) consumers;
};

/*
 * Option flags.
 */
#define	UFLAG	0x01	/* -u flag: show users				*/
#define	FFLAG	0x02	/* -f flag: specified files only		*/
#define	CFLAG	0x04	/* -c flag: treat as mpoints			*/
#define	MFLAG	0x10	/* -m flag: mmapped files too			*/
#define	KFLAG	0x20	/* -k flag: send signal (SIGKILL by default)	*/

static int flags = 0;	/* Option flags. */

static void	printflags(struct consumer *consumer);
static int	str2sig(const char *str);
static void	usage(void) __dead2;
static int	addfile(const char *path, struct reqfile *reqfile);
static void	dofiles(struct procstat *procstat, struct kinfo_proc *kp,
    struct reqfile *reqfiles, size_t nfiles);

static void
usage(void)
{

	fprintf(stderr,
"usage: fuser [-cfhkmu] [-M core] [-N system] [-s signal] file ...\n");
	exit(EX_USAGE);
}

static void
printflags(struct consumer *cons)
{
	unsigned int i;

	assert(cons);
	for (i = 0; i < NUFLAGS; i++)
		if ((cons->uflags & uflags[i].flag) != 0)
			fputc(uflags[i].ch, stderr);
	for (i = 0; i < NFFLAGS; i++)
		if ((cons->flags & fflags[i].flag) != 0)
			fputc(fflags[i].ch, stderr);
}

/*
 * Add file to the list.
 */
static int
addfile(const char *path, struct reqfile *reqfile)
{
	struct stat sb;

	assert(path);
	if (stat(path, &sb) != 0) {
		warn("%s", path);
		return (1);
	}
	reqfile->fileid = sb.st_ino;
	reqfile->fsid = sb.st_dev;
	reqfile->name = path;
	STAILQ_INIT(&reqfile->consumers);
	return (0);
}

int
do_fuser(int argc, char *argv[])
{
	struct consumer *consumer;
	struct kinfo_proc *p, *procs;
	struct procstat *procstat;
	struct reqfile *reqfiles;
	char *ep, *nlistf, *memf;
	int ch, cnt, sig;
	unsigned int i, nfiles;

	sig = SIGKILL;	/* Default to kill. */
	nlistf = NULL;
	memf = NULL;
	while ((ch = getopt(argc, argv, "M:N:cfhkms:u")) != -1)
		switch(ch) {
		case 'f':
			if ((flags & CFLAG) != 0)
				usage();
			flags |= FFLAG;
			break;
		case 'c':
			if ((flags & FFLAG) != 0)
				usage();
			flags |= CFLAG;
			break;
		case 'N':
			nlistf = optarg;
			break;
		case 'M':
			memf = optarg;
			break;
		case 'u':
			flags |= UFLAG;
			break;
		case 'm':
			flags |= MFLAG;
			break;
		case 'k':
			flags |= KFLAG;
			break;
		case 's':
			if (isdigit(*optarg)) {
				sig = strtol(optarg, &ep, 10);
				if (*ep != '\0' || sig < 0 || sig >= sys_nsig)
					errx(EX_USAGE, "illegal signal number" ": %s",
					    optarg);
			} else {
				sig = str2sig(optarg);
				if (sig < 0)
					errx(EX_USAGE, "illegal signal name: "
					    "%s", optarg);
			}
			break;
		case 'h':
			/* PASSTHROUGH */
		default:
			usage();
			/* NORETURN */
		}
	argv += optind;
	argc -= optind;

	assert(argc >= 0);
	if (argc == 0)
		usage();
		/* NORETURN */

	/*
	 * Process named files.
	 */
	reqfiles = malloc(argc * sizeof(struct reqfile));
	if (reqfiles == NULL)
		err(EX_OSERR, "malloc()");
	nfiles = 0;
	while (argc--)
		if (!addfile(*(argv++), &reqfiles[nfiles]))
			nfiles++;
	if (nfiles == 0)
		errx(EX_IOERR, "files not accessible");

	if (memf != NULL)
		procstat = procstat_open_kvm(nlistf, memf);
	else
		procstat = procstat_open_sysctl();
	if (procstat == NULL)
		errx(1, "procstat_open()");
	procs = procstat_getprocs(procstat, KERN_PROC_PROC, 0, &cnt);
	if (procs == NULL)
		 errx(1, "procstat_getprocs()");

	/*
	 * Walk through process table and look for matching files.
	 */
	p = procs;
	while(cnt--)
		if (p->ki_stat != SZOMB)
			dofiles(procstat, p++, reqfiles, nfiles);

	for (i = 0; i < nfiles; i++) {
		fprintf(stderr, "%s:", reqfiles[i].name);
		fflush(stderr);
		STAILQ_FOREACH(consumer, &reqfiles[i].consumers, next) {
			if (consumer->flags != 0) {
				fprintf(stdout, "%6d", consumer->pid);
				fflush(stdout);
				printflags(consumer);
				if ((flags & UFLAG) != 0)
					fprintf(stderr, "(%s)",
					    user_from_uid(consumer->uid, 0));
				if ((flags & KFLAG) != 0)
					kill(consumer->pid, sig);
				fflush(stderr);
			}
		}
		(void)fprintf(stderr, "\n");
	}
	procstat_freeprocs(procstat, procs);
	procstat_close(procstat);
	free(reqfiles);
	return (0);
}

static void
dofiles(struct procstat *procstat, struct kinfo_proc *kp,
    struct reqfile *reqfiles, size_t nfiles)
{
	struct vnstat vn;
	struct consumer *cons;
	struct filestat *fst;
	struct filestat_list *head;
	int error, match;
	unsigned int i;
	char errbuf[_POSIX2_LINE_MAX];
	
	head = procstat_getfiles(procstat, kp, flags & MFLAG);
	if (head == NULL)
		return;
	STAILQ_FOREACH(fst, head, next) {
		if (fst->fs_type != PS_FST_TYPE_VNODE)
			continue;
		error = procstat_get_vnode_info(procstat, fst, &vn, errbuf);
		if (error != 0)
			continue;
		for (i = 0; i < nfiles; i++) {
			if (flags & CFLAG && reqfiles[i].fsid == vn.vn_fsid) {
				break;
			}
			else if (reqfiles[i].fsid == vn.vn_fsid &&
			    reqfiles[i].fileid == vn.vn_fileid) {
				break;
			}
			else if (!(flags & FFLAG) &&
			    (vn.vn_type == PS_FST_VTYPE_VCHR ||
			    vn.vn_type == PS_FST_VTYPE_VBLK) &&
			    vn.vn_fsid == reqfiles[i].fileid) {
				break;
			}
		}
		if (i == nfiles)
			continue;	/* No match. */

		/*
		 * Look for existing entries.
		 */
		match = 0;
		STAILQ_FOREACH(cons, &reqfiles[i].consumers, next)
			if (cons->pid == kp->ki_pid) {
				match = 1;
				break;
			}
		if (match == 1) {	/* Use old entry. */
			cons->flags |= fst->fs_fflags;
			cons->uflags |= fst->fs_uflags;
		} else {
			/*
			 * Create new entry in the consumer chain.
			 */
			cons = calloc(1, sizeof(struct consumer));
			if (cons == NULL) {
				warn("malloc()");
				continue;
			}
			cons->uid = kp->ki_uid;
			cons->pid = kp->ki_pid;
			cons->uflags = fst->fs_uflags;
			cons->flags = fst->fs_fflags;
			STAILQ_INSERT_TAIL(&reqfiles[i].consumers, cons, next);
		}
	}
	procstat_freefiles(procstat, head);
}

/*
 * Returns signal number for it's string representation.
 */
static int
str2sig(const char *str)
{
	int i;

	if (!strncasecmp(str, "SIG", 3))
		str += 3;
	for (i = 1; i < sys_nsig; i++) {
                if (!strcasecmp(sys_signame[i], str))
                        return (i);
        }
        return (-1);
}
OpenPOWER on IntegriCloud