xref: /freebsd/usr.bin/killall/killall.c (revision b3aaa0cc21c63d388230c7ef2a80abd631ff20d5)
1 /*-
2  * Copyright (c) 2000 Peter Wemm <peter@FreeBSD.org>
3  * Copyright (c) 2000 Paul Saab <ps@FreeBSD.org>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 #include <sys/param.h>
32 #include <sys/jail.h>
33 #include <sys/stat.h>
34 #include <sys/user.h>
35 #include <sys/sysctl.h>
36 #include <fcntl.h>
37 #include <dirent.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <pwd.h>
42 #include <signal.h>
43 #include <regex.h>
44 #include <ctype.h>
45 #include <err.h>
46 #include <errno.h>
47 #include <unistd.h>
48 #include <locale.h>
49 
50 static void __dead2
51 usage(void)
52 {
53 
54 	fprintf(stderr, "usage: killall [-delmsvz] [-help] [-j jid]\n");
55 	fprintf(stderr,
56 	    "               [-u user] [-t tty] [-c cmd] [-SIGNAL] [cmd]...\n");
57 	fprintf(stderr, "At least one option or argument to specify processes must be given.\n");
58 	exit(1);
59 }
60 
61 static char *
62 upper(const char *str)
63 {
64 	static char buf[80];
65 	char *s;
66 
67 	strlcpy(buf, str, sizeof(buf));
68 	for (s = buf; *s; s++)
69 		*s = toupper((unsigned char)*s);
70 	return buf;
71 }
72 
73 
74 static void
75 printsig(FILE *fp)
76 {
77 	const char	*const * p;
78 	int		cnt;
79 	int		offset = 0;
80 
81 	for (cnt = NSIG, p = sys_signame + 1; --cnt; ++p) {
82 		offset += fprintf(fp, "%s ", upper(*p));
83 		if (offset >= 75 && cnt > 1) {
84 			offset = 0;
85 			fprintf(fp, "\n");
86 		}
87 	}
88 	fprintf(fp, "\n");
89 }
90 
91 static void
92 nosig(char *name)
93 {
94 
95 	warnx("unknown signal %s; valid signals:", name);
96 	printsig(stderr);
97 	exit(1);
98 }
99 
100 int
101 main(int ac, char **av)
102 {
103 	struct kinfo_proc *procs = NULL, *newprocs;
104 	struct stat	sb;
105 	struct passwd	*pw;
106 	regex_t		rgx;
107 	regmatch_t	pmatch;
108 	int		i, j;
109 	char		buf[256];
110 	char		*user = NULL;
111 	char		*tty = NULL;
112 	char		*cmd = NULL;
113 	int		vflag = 0;
114 	int		sflag = 0;
115 	int		dflag = 0;
116 	int		eflag = 0;
117 	int		jflag = 0;
118 	int		mflag = 0;
119 	int		zflag = 0;
120 	uid_t		uid = 0;
121 	dev_t		tdev = 0;
122 	pid_t		mypid;
123 	char		thiscmd[MAXCOMLEN + 1];
124 	pid_t		thispid;
125 	uid_t		thisuid;
126 	dev_t		thistdev;
127 	int		sig = SIGTERM;
128 	const char *const *p;
129 	char		*ep;
130 	int		errors = 0;
131 	int		jid;
132 	int		mib[4];
133 	size_t		miblen;
134 	int		st, nprocs;
135 	size_t		size;
136 	int		matched;
137 	int		killed = 0;
138 
139 	setlocale(LC_ALL, "");
140 
141 	av++;
142 	ac--;
143 
144 	while (ac > 0) {
145 		if (strcmp(*av, "-l") == 0) {
146 			printsig(stdout);
147 			exit(0);
148 		}
149 		if (strcmp(*av, "-help") == 0)
150 			usage();
151 		if (**av == '-') {
152 			++*av;
153 			switch (**av) {
154 			case 'j':
155 				++*av;
156 				if (**av == '\0') {
157 					++av;
158 					--ac;
159 				}
160 				jflag++;
161 				if (*av == NULL)
162 				    	errx(1, "must specify jid");
163 				jid = strtol(*av, &ep, 10);
164 				if (!*av || *ep)
165 					errx(1, "illegal jid: %s", *av);
166 				if (jail_attach(jid) == -1)
167 					err(1, "jail_attach(): %d", jid);
168 				break;
169 			case 'u':
170 				++*av;
171 				if (**av == '\0') {
172 					++av;
173 					--ac;
174 				}
175 				if (*av == NULL)
176 				    	errx(1, "must specify user");
177 				user = *av;
178 				break;
179 			case 't':
180 				++*av;
181 				if (**av == '\0') {
182 					++av;
183 					--ac;
184 				}
185 				if (*av == NULL)
186 				    	errx(1, "must specify tty");
187 				tty = *av;
188 				break;
189 			case 'c':
190 				++*av;
191 				if (**av == '\0') {
192 					++av;
193 					--ac;
194 				}
195 				if (*av == NULL)
196 				    	errx(1, "must specify procname");
197 				cmd = *av;
198 				break;
199 			case 'v':
200 				vflag++;
201 				break;
202 			case 's':
203 				sflag++;
204 				break;
205 			case 'd':
206 				dflag++;
207 				break;
208 			case 'e':
209 				eflag++;
210 				break;
211 			case 'm':
212 				mflag++;
213 				break;
214 			case 'z':
215 				zflag++;
216 				break;
217 			default:
218 				if (isalpha((unsigned char)**av)) {
219 					if (strncasecmp(*av, "sig", 3) == 0)
220 						*av += 3;
221 					for (sig = NSIG, p = sys_signame + 1;
222 					     --sig; ++p)
223 						if (strcasecmp(*p, *av) == 0) {
224 							sig = p - sys_signame;
225 							break;
226 						}
227 					if (!sig)
228 						nosig(*av);
229 				} else if (isdigit((unsigned char)**av)) {
230 					sig = strtol(*av, &ep, 10);
231 					if (!*av || *ep)
232 						errx(1, "illegal signal number: %s", *av);
233 					if (sig < 0 || sig >= NSIG)
234 						nosig(*av);
235 				} else
236 					nosig(*av);
237 			}
238 			++av;
239 			--ac;
240 		} else {
241 			break;
242 		}
243 	}
244 
245 	if (user == NULL && tty == NULL && cmd == NULL && !jflag && ac == 0)
246 		usage();
247 
248 	if (tty) {
249 		if (strncmp(tty, "/dev/", 5) == 0)
250 			snprintf(buf, sizeof(buf), "%s", tty);
251 		else if (strncmp(tty, "tty", 3) == 0)
252 			snprintf(buf, sizeof(buf), "/dev/%s", tty);
253 		else
254 			snprintf(buf, sizeof(buf), "/dev/tty%s", tty);
255 		if (stat(buf, &sb) < 0)
256 			err(1, "stat(%s)", buf);
257 		if (!S_ISCHR(sb.st_mode))
258 			errx(1, "%s: not a character device", buf);
259 		tdev = sb.st_rdev;
260 		if (dflag)
261 			printf("ttydev:0x%x\n", tdev);
262 	}
263 	if (user) {
264 		uid = strtol(user, &ep, 10);
265 		if (*user == '\0' || *ep != '\0') { /* was it a number? */
266 			pw = getpwnam(user);
267 			if (pw == NULL)
268 				errx(1, "user %s does not exist", user);
269 			uid = pw->pw_uid;
270 			if (dflag)
271 				printf("uid:%d\n", uid);
272 		}
273 	} else {
274 		uid = getuid();
275 		if (uid != 0) {
276 			pw = getpwuid(uid);
277 			if (pw)
278 				user = pw->pw_name;
279 			if (dflag)
280 				printf("uid:%d\n", uid);
281 		}
282 	}
283 	size = 0;
284 	mib[0] = CTL_KERN;
285 	mib[1] = KERN_PROC;
286 	mib[2] = KERN_PROC_PROC;
287 	mib[3] = 0;
288 	miblen = 3;
289 
290 	if (user) {
291 		mib[2] = eflag ? KERN_PROC_UID : KERN_PROC_RUID;
292 		mib[3] = uid;
293 		miblen = 4;
294 	} else if (tty) {
295 		mib[2] = KERN_PROC_TTY;
296 		mib[3] = tdev;
297 		miblen = 4;
298 	}
299 
300 	st = sysctl(mib, miblen, NULL, &size, NULL, 0);
301 	do {
302 		size += size / 10;
303 		newprocs = realloc(procs, size);
304 		if (newprocs == 0) {
305 			if (procs)
306 				free(procs);
307 			errx(1, "could not reallocate memory");
308 		}
309 		procs = newprocs;
310 		st = sysctl(mib, miblen, procs, &size, NULL, 0);
311 	} while (st == -1 && errno == ENOMEM);
312 	if (st == -1)
313 		err(1, "could not sysctl(KERN_PROC)");
314 	if (size % sizeof(struct kinfo_proc) != 0) {
315 		fprintf(stderr, "proc size mismatch (%zu total, %zu chunks)\n",
316 			size, sizeof(struct kinfo_proc));
317 		fprintf(stderr, "userland out of sync with kernel, recompile libkvm etc\n");
318 		exit(1);
319 	}
320 	nprocs = size / sizeof(struct kinfo_proc);
321 	if (dflag)
322 		printf("nprocs %d\n", nprocs);
323 	mypid = getpid();
324 
325 	for (i = 0; i < nprocs; i++) {
326 		if ((procs[i].ki_stat & SZOMB) == SZOMB && !zflag)
327 			continue;
328 		thispid = procs[i].ki_pid;
329 		strlcpy(thiscmd, procs[i].ki_comm, sizeof(thiscmd));
330 		thistdev = procs[i].ki_tdev;
331 		if (eflag)
332 			thisuid = procs[i].ki_uid;	/* effective uid */
333 		else
334 			thisuid = procs[i].ki_ruid;	/* real uid */
335 
336 		if (thispid == mypid)
337 			continue;
338 		matched = 1;
339 		if (user) {
340 			if (thisuid != uid)
341 				matched = 0;
342 		}
343 		if (tty) {
344 			if (thistdev != tdev)
345 				matched = 0;
346 		}
347 		if (cmd) {
348 			if (mflag) {
349 				if (regcomp(&rgx, cmd,
350 				    REG_EXTENDED|REG_NOSUB) != 0) {
351 					mflag = 0;
352 					warnx("%s: illegal regexp", cmd);
353 				}
354 			}
355 			if (mflag) {
356 				pmatch.rm_so = 0;
357 				pmatch.rm_eo = strlen(thiscmd);
358 				if (regexec(&rgx, thiscmd, 0, &pmatch,
359 				    REG_STARTEND) != 0)
360 					matched = 0;
361 				regfree(&rgx);
362 			} else {
363 				if (strncmp(thiscmd, cmd, MAXCOMLEN) != 0)
364 					matched = 0;
365 			}
366 		}
367 		if (jflag && thispid == getpid())
368 			matched = 0;
369 		if (matched == 0)
370 			continue;
371 		if (ac > 0)
372 			matched = 0;
373 		for (j = 0; j < ac; j++) {
374 			if (mflag) {
375 				if (regcomp(&rgx, av[j],
376 				    REG_EXTENDED|REG_NOSUB) != 0) {
377 					mflag = 0;
378 					warnx("%s: illegal regexp", av[j]);
379 				}
380 			}
381 			if (mflag) {
382 				pmatch.rm_so = 0;
383 				pmatch.rm_eo = strlen(thiscmd);
384 				if (regexec(&rgx, thiscmd, 0, &pmatch,
385 				    REG_STARTEND) == 0)
386 					matched = 1;
387 				regfree(&rgx);
388 			} else {
389 				if (strcmp(thiscmd, av[j]) == 0)
390 					matched = 1;
391 			}
392 			if (matched)
393 				break;
394 		}
395 		if (matched == 0)
396 			continue;
397 		if (dflag)
398 			printf("sig:%d, cmd:%s, pid:%d, dev:0x%x uid:%d\n", sig,
399 			    thiscmd, thispid, thistdev, thisuid);
400 
401 		if (vflag || sflag)
402 			printf("kill -%s %d\n", upper(sys_signame[sig]),
403 			    thispid);
404 
405 		killed++;
406 		if (!dflag && !sflag) {
407 			if (kill(thispid, sig) < 0 /* && errno != ESRCH */ ) {
408 				warn("warning: kill -%s %d",
409 				    upper(sys_signame[sig]), thispid);
410 				errors = 1;
411 			}
412 		}
413 	}
414 	if (killed == 0) {
415 		fprintf(stderr, "No matching processes %swere found\n",
416 		    getuid() != 0 ? "belonging to you " : "");
417 		errors = 1;
418 	}
419 	exit(errors);
420 }
421