xref: /freebsd/usr.bin/fstat/fuser.c (revision 2b8331622f0b212cf3bb4fc4914a501e5321d506)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2005-2009 Stanislav Sedov <stas@FreeBSD.org>
5  * 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  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  */
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/queue.h>
33 #include <sys/stat.h>
34 #include <sys/sysctl.h>
35 #include <sys/user.h>
36 
37 #include <assert.h>
38 #include <ctype.h>
39 #include <err.h>
40 #include <fcntl.h>
41 #include <libprocstat.h>
42 #include <limits.h>
43 #include <paths.h>
44 #include <pwd.h>
45 #include <signal.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <sysexits.h>
50 #include <unistd.h>
51 
52 #include "functions.h"
53 
54 /*
55  * File access mode flags table.
56  */
57 static const struct {
58 	int	flag;
59 	char	ch;
60 } fflags[] = {
61 	{PS_FST_FFLAG_WRITE,	'w'},
62 	{PS_FST_FFLAG_APPEND,	'a'},
63 	{PS_FST_FFLAG_DIRECT,	'd'},
64 	{PS_FST_FFLAG_SHLOCK,	's'},
65 	{PS_FST_FFLAG_EXLOCK,	'e'}
66 };
67 #define	NFFLAGS	(sizeof(fflags) / sizeof(*fflags))
68 
69 /*
70  * Usage flags translation table.
71  */
72 static const struct {
73 	int	flag;
74 	char	ch;
75 } uflags[] = {
76 	{PS_FST_UFLAG_RDIR,	'r'},
77 	{PS_FST_UFLAG_CDIR,	'c'},
78 	{PS_FST_UFLAG_JAIL,	'j'},
79 	{PS_FST_UFLAG_TRACE,	't'},
80 	{PS_FST_UFLAG_TEXT,	'x'},
81 	{PS_FST_UFLAG_MMAP,	'm'},
82 	{PS_FST_UFLAG_CTTY,	'y'}
83 };
84 #define	NUFLAGS	(sizeof(uflags) / sizeof(*uflags))
85 
86 struct consumer {
87 	pid_t	pid;
88 	uid_t	uid;
89 	int	fd;
90 	int	flags;
91 	int	uflags;
92 	STAILQ_ENTRY(consumer)	next;
93 };
94 struct reqfile {
95 	dev_t		fsid;
96 	ino_t		fileid;
97 	const char	*name;
98 	STAILQ_HEAD(, consumer) consumers;
99 };
100 
101 /*
102  * Option flags.
103  */
104 #define	UFLAG	0x01	/* -u flag: show users				*/
105 #define	FFLAG	0x02	/* -f flag: specified files only		*/
106 #define	CFLAG	0x04	/* -c flag: treat as mpoints			*/
107 #define	MFLAG	0x10	/* -m flag: mmapped files too			*/
108 #define	KFLAG	0x20	/* -k flag: send signal (SIGKILL by default)	*/
109 
110 static int flags = 0;	/* Option flags. */
111 
112 static void	printflags(struct consumer *consumer);
113 static int	str2sig(const char *str);
114 static void	usage(void) __dead2;
115 static int	addfile(const char *path, struct reqfile *reqfile);
116 static void	dofiles(struct procstat *procstat, struct kinfo_proc *kp,
117     struct reqfile *reqfiles, size_t nfiles);
118 
119 static void
120 usage(void)
121 {
122 
123 	fprintf(stderr,
124 "usage: fuser [-cfhkmu] [-M core] [-N system] [-s signal] file ...\n");
125 	exit(EX_USAGE);
126 }
127 
128 static void
129 printflags(struct consumer *cons)
130 {
131 	unsigned int i;
132 
133 	assert(cons);
134 	for (i = 0; i < NUFLAGS; i++)
135 		if ((cons->uflags & uflags[i].flag) != 0)
136 			fputc(uflags[i].ch, stderr);
137 	for (i = 0; i < NFFLAGS; i++)
138 		if ((cons->flags & fflags[i].flag) != 0)
139 			fputc(fflags[i].ch, stderr);
140 }
141 
142 /*
143  * Add file to the list.
144  */
145 static int
146 addfile(const char *path, struct reqfile *reqfile)
147 {
148 	struct stat sb;
149 
150 	assert(path);
151 	if (stat(path, &sb) != 0) {
152 		warn("%s", path);
153 		return (1);
154 	}
155 	reqfile->fileid = sb.st_ino;
156 	reqfile->fsid = sb.st_dev;
157 	reqfile->name = path;
158 	STAILQ_INIT(&reqfile->consumers);
159 	return (0);
160 }
161 
162 int
163 do_fuser(int argc, char *argv[])
164 {
165 	struct consumer *consumer;
166 	struct kinfo_proc *procs;
167 	struct procstat *procstat;
168 	struct reqfile *reqfiles;
169 	char *ep, *nlistf, *memf;
170 	int ch, sig;
171 	unsigned int i, cnt, nfiles;
172 
173 	sig = SIGKILL;	/* Default to kill. */
174 	nlistf = NULL;
175 	memf = NULL;
176 	while ((ch = getopt(argc, argv, "M:N:cfhkms:u")) != -1)
177 		switch(ch) {
178 		case 'f':
179 			if ((flags & CFLAG) != 0)
180 				usage();
181 			flags |= FFLAG;
182 			break;
183 		case 'c':
184 			if ((flags & FFLAG) != 0)
185 				usage();
186 			flags |= CFLAG;
187 			break;
188 		case 'N':
189 			nlistf = optarg;
190 			break;
191 		case 'M':
192 			memf = optarg;
193 			break;
194 		case 'u':
195 			flags |= UFLAG;
196 			break;
197 		case 'm':
198 			flags |= MFLAG;
199 			break;
200 		case 'k':
201 			flags |= KFLAG;
202 			break;
203 		case 's':
204 			if (isdigit(*optarg)) {
205 				sig = strtol(optarg, &ep, 10);
206 				if (*ep != '\0' || sig < 0 || sig >= sys_nsig)
207 					errx(EX_USAGE, "illegal signal number" ": %s",
208 					    optarg);
209 			} else {
210 				sig = str2sig(optarg);
211 				if (sig < 0)
212 					errx(EX_USAGE, "illegal signal name: "
213 					    "%s", optarg);
214 			}
215 			break;
216 		case 'h':
217 			/* PASSTHROUGH */
218 		default:
219 			usage();
220 			/* NORETURN */
221 		}
222 	argv += optind;
223 	argc -= optind;
224 
225 	assert(argc >= 0);
226 	if (argc == 0)
227 		usage();
228 		/* NORETURN */
229 
230 	/*
231 	 * Process named files.
232 	 */
233 	reqfiles = malloc(argc * sizeof(struct reqfile));
234 	if (reqfiles == NULL)
235 		err(EX_OSERR, "malloc()");
236 	nfiles = 0;
237 	while (argc--)
238 		if (!addfile(*(argv++), &reqfiles[nfiles]))
239 			nfiles++;
240 	if (nfiles == 0)
241 		errx(EX_IOERR, "files not accessible");
242 
243 	if (memf != NULL)
244 		procstat = procstat_open_kvm(nlistf, memf);
245 	else
246 		procstat = procstat_open_sysctl();
247 	if (procstat == NULL)
248 		errx(1, "procstat_open()");
249 	procs = procstat_getprocs(procstat, KERN_PROC_PROC, 0, &cnt);
250 	if (procs == NULL)
251 		 errx(1, "procstat_getprocs()");
252 
253 	/*
254 	 * Walk through process table and look for matching files.
255 	 */
256 	for (i = 0; i < cnt; i++)
257 		if (procs[i].ki_stat != SZOMB)
258 			dofiles(procstat, &procs[i], reqfiles, nfiles);
259 
260 	for (i = 0; i < nfiles; i++) {
261 		fprintf(stderr, "%s:", reqfiles[i].name);
262 		fflush(stderr);
263 		STAILQ_FOREACH(consumer, &reqfiles[i].consumers, next) {
264 			if (consumer->flags != 0) {
265 				fprintf(stdout, "%6d", consumer->pid);
266 				fflush(stdout);
267 				printflags(consumer);
268 				if ((flags & UFLAG) != 0)
269 					fprintf(stderr, "(%s)",
270 					    user_from_uid(consumer->uid, 0));
271 				if ((flags & KFLAG) != 0)
272 					kill(consumer->pid, sig);
273 				fflush(stderr);
274 			}
275 		}
276 		(void)fprintf(stderr, "\n");
277 	}
278 	procstat_freeprocs(procstat, procs);
279 	procstat_close(procstat);
280 	free(reqfiles);
281 	return (0);
282 }
283 
284 static void
285 dofiles(struct procstat *procstat, struct kinfo_proc *kp,
286     struct reqfile *reqfiles, size_t nfiles)
287 {
288 	struct vnstat vn;
289 	struct consumer *cons;
290 	struct filestat *fst;
291 	struct filestat_list *head;
292 	int error, match;
293 	unsigned int i;
294 	char errbuf[_POSIX2_LINE_MAX];
295 
296 	head = procstat_getfiles(procstat, kp, flags & MFLAG);
297 	if (head == NULL)
298 		return;
299 	STAILQ_FOREACH(fst, head, next) {
300 		if (fst->fs_type != PS_FST_TYPE_VNODE)
301 			continue;
302 		error = procstat_get_vnode_info(procstat, fst, &vn, errbuf);
303 		if (error != 0)
304 			continue;
305 		for (i = 0; i < nfiles; i++) {
306 			if (flags & CFLAG && reqfiles[i].fsid == vn.vn_fsid) {
307 				break;
308 			}
309 			else if (reqfiles[i].fsid == vn.vn_fsid &&
310 			    reqfiles[i].fileid == vn.vn_fileid) {
311 				break;
312 			}
313 			else if (!(flags & FFLAG) &&
314 			    (vn.vn_type == PS_FST_VTYPE_VCHR ||
315 			    vn.vn_type == PS_FST_VTYPE_VBLK) &&
316 			    vn.vn_fsid == reqfiles[i].fileid) {
317 				break;
318 			}
319 		}
320 		if (i == nfiles)
321 			continue;	/* No match. */
322 
323 		/*
324 		 * Look for existing entries.
325 		 */
326 		match = 0;
327 		STAILQ_FOREACH(cons, &reqfiles[i].consumers, next)
328 			if (cons->pid == kp->ki_pid) {
329 				match = 1;
330 				break;
331 			}
332 		if (match == 1) {	/* Use old entry. */
333 			cons->flags |= fst->fs_fflags;
334 			cons->uflags |= fst->fs_uflags;
335 		} else {
336 			/*
337 			 * Create new entry in the consumer chain.
338 			 */
339 			cons = calloc(1, sizeof(struct consumer));
340 			if (cons == NULL) {
341 				warn("malloc()");
342 				continue;
343 			}
344 			cons->uid = kp->ki_uid;
345 			cons->pid = kp->ki_pid;
346 			cons->uflags = fst->fs_uflags;
347 			cons->flags = fst->fs_fflags;
348 			STAILQ_INSERT_TAIL(&reqfiles[i].consumers, cons, next);
349 		}
350 	}
351 	procstat_freefiles(procstat, head);
352 }
353 
354 /*
355  * Returns signal number for it's string representation.
356  */
357 static int
358 str2sig(const char *str)
359 {
360 	int i;
361 
362 	if (!strncasecmp(str, "SIG", 3))
363 		str += 3;
364 	for (i = 1; i < sys_nsig; i++) {
365                 if (!strcasecmp(sys_signame[i], str))
366                         return (i);
367         }
368         return (-1);
369 }
370