xref: /freebsd/usr.bin/killall/killall.c (revision a812392203d7c4c3f0db9d8a0f3391374c49c71f)
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/uio.h>
35 #include <sys/user.h>
36 #include <sys/sysctl.h>
37 #include <fcntl.h>
38 #include <dirent.h>
39 #include <jail.h>
40 #include <stdint.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <pwd.h>
45 #include <signal.h>
46 #include <regex.h>
47 #include <ctype.h>
48 #include <err.h>
49 #include <errno.h>
50 #include <unistd.h>
51 #include <locale.h>
52 
53 static void __dead2
54 usage(void)
55 {
56 
57 	fprintf(stderr, "usage: killall [-delmsqvz] [-help] [-I] [-j jail]\n");
58 	fprintf(stderr,
59 	    "               [-u user] [-t tty] [-c cmd] [-SIGNAL] [cmd]...\n");
60 	fprintf(stderr, "At least one option or argument to specify processes must be given.\n");
61 	exit(1);
62 }
63 
64 
65 static void
66 printsig(FILE *fp)
67 {
68 	const char	*const * p;
69 	int		cnt;
70 	int		offset = 0;
71 
72 	for (cnt = NSIG, p = sys_signame + 1; --cnt; ++p) {
73 		offset += fprintf(fp, "%s ", *p);
74 		if (offset >= 75 && cnt > 1) {
75 			offset = 0;
76 			fprintf(fp, "\n");
77 		}
78 	}
79 	fprintf(fp, "\n");
80 }
81 
82 static void
83 nosig(char *name)
84 {
85 
86 	warnx("unknown signal %s; valid signals:", name);
87 	printsig(stderr);
88 	exit(1);
89 }
90 
91 int
92 main(int ac, char **av)
93 {
94 	char		**saved_av;
95 	struct kinfo_proc *procs, *newprocs;
96 	struct stat	sb;
97 	struct passwd	*pw;
98 	regex_t		rgx;
99 	regmatch_t	pmatch;
100 	int		i, j, ch;
101 	char		buf[256];
102 	char		first;
103 	char		*user = NULL;
104 	char		*tty = NULL;
105 	char		*cmd = NULL;
106 	int		qflag = 0;
107 	int		vflag = 0;
108 	int		sflag = 0;
109 	int		dflag = 0;
110 	int		eflag = 0;
111 	int		Iflag = 0;
112 	int		jflag = 0;
113 	int		mflag = 0;
114 	int		zflag = 0;
115 	uid_t		uid = 0;
116 	dev_t		tdev = 0;
117 	pid_t		mypid;
118 	char		thiscmd[MAXCOMLEN + 1];
119 	pid_t		thispid;
120 	uid_t		thisuid;
121 	dev_t		thistdev;
122 	int		sig = SIGTERM;
123 	const char *const *p;
124 	char		*ep;
125 	int		errors = 0;
126 	int		jid;
127 	int		mib[4];
128 	size_t		miblen;
129 	int		st, nprocs;
130 	size_t		size;
131 	int		matched;
132 	int		killed = 0;
133 
134 	setlocale(LC_ALL, "");
135 
136 	av++;
137 	ac--;
138 
139 	while (ac > 0) {
140 		if (strcmp(*av, "-l") == 0) {
141 			printsig(stdout);
142 			exit(0);
143 		}
144 		if (strcmp(*av, "-help") == 0)
145 			usage();
146 		if (**av == '-') {
147 			++*av;
148 			switch (**av) {
149 			case 'j':
150 				++*av;
151 				if (**av == '\0') {
152 					++av;
153 					--ac;
154 				}
155 				jflag++;
156 				if (*av == NULL)
157 				    	errx(1, "must specify jail");
158 				jid = jail_getid(*av);
159 				if (jid < 0)
160 					errx(1, "%s", jail_errmsg);
161 				if (jail_attach(jid) == -1)
162 					err(1, "jail_attach(%d)", jid);
163 				break;
164 			case 'u':
165 				++*av;
166 				if (**av == '\0') {
167 					++av;
168 					--ac;
169 				}
170 				if (*av == NULL)
171 				    	errx(1, "must specify user");
172 				user = *av;
173 				break;
174 			case 't':
175 				++*av;
176 				if (**av == '\0') {
177 					++av;
178 					--ac;
179 				}
180 				if (*av == NULL)
181 				    	errx(1, "must specify tty");
182 				tty = *av;
183 				break;
184 			case 'c':
185 				++*av;
186 				if (**av == '\0') {
187 					++av;
188 					--ac;
189 				}
190 				if (*av == NULL)
191 				    	errx(1, "must specify procname");
192 				cmd = *av;
193 				break;
194 			case 'q':
195 				qflag++;
196 				break;
197 			case 'v':
198 				vflag++;
199 				break;
200 			case 's':
201 				sflag++;
202 				break;
203 			case 'd':
204 				dflag++;
205 				break;
206 			case 'e':
207 				eflag++;
208 				break;
209 			case 'm':
210 				mflag++;
211 				break;
212 			case 'z':
213 				zflag++;
214 				break;
215 			default:
216 				saved_av = av;
217 				if (isalpha((unsigned char)**av)) {
218 					if (strncasecmp(*av, "SIG", 3) == 0)
219 						*av += 3;
220 					for (sig = NSIG, p = sys_signame + 1;
221 					     --sig; ++p)
222 						if (strcasecmp(*p, *av) == 0) {
223 							sig = p - sys_signame;
224 							break;
225 						}
226 					if (!sig) {
227 						if (**saved_av == 'I') {
228 							av = saved_av;
229 							Iflag = 1;
230 							break;
231 						} else
232 							nosig(*av);
233 					}
234 				} else if (isdigit((unsigned char)**av)) {
235 					sig = strtol(*av, &ep, 10);
236 					if (!*av || *ep)
237 						errx(1, "illegal signal number: %s", *av);
238 					if (sig < 0 || sig >= NSIG)
239 						nosig(*av);
240 				} else
241 					nosig(*av);
242 			}
243 			++av;
244 			--ac;
245 		} else {
246 			break;
247 		}
248 	}
249 
250 	if (user == NULL && tty == NULL && cmd == NULL && !jflag && ac == 0)
251 		usage();
252 
253 	if (tty) {
254 		if (strncmp(tty, "/dev/", 5) == 0)
255 			snprintf(buf, sizeof(buf), "%s", tty);
256 		else if (strncmp(tty, "tty", 3) == 0)
257 			snprintf(buf, sizeof(buf), "/dev/%s", tty);
258 		else
259 			snprintf(buf, sizeof(buf), "/dev/tty%s", tty);
260 		if (stat(buf, &sb) < 0)
261 			err(1, "stat(%s)", buf);
262 		if (!S_ISCHR(sb.st_mode))
263 			errx(1, "%s: not a character device", buf);
264 		tdev = sb.st_rdev;
265 		if (dflag)
266 			printf("ttydev:0x%jx\n", (uintmax_t)tdev);
267 	}
268 	if (user) {
269 		uid = strtol(user, &ep, 10);
270 		if (*user == '\0' || *ep != '\0') { /* was it a number? */
271 			pw = getpwnam(user);
272 			if (pw == NULL)
273 				errx(1, "user %s does not exist", user);
274 			uid = pw->pw_uid;
275 			if (dflag)
276 				printf("uid:%d\n", uid);
277 		}
278 	} else {
279 		uid = getuid();
280 		if (uid != 0) {
281 			pw = getpwuid(uid);
282 			if (pw)
283 				user = pw->pw_name;
284 			if (dflag)
285 				printf("uid:%d\n", uid);
286 		}
287 	}
288 	size = 0;
289 	mib[0] = CTL_KERN;
290 	mib[1] = KERN_PROC;
291 
292 	if (user) {
293 		mib[2] = eflag ? KERN_PROC_UID : KERN_PROC_RUID;
294 		mib[3] = uid;
295 		miblen = 4;
296 	} else if (tty) {
297 		mib[2] = KERN_PROC_TTY;
298 		mib[3] = tdev;
299 		miblen = 4;
300 	} else {
301 		mib[2] = KERN_PROC_PROC;
302 		mib[3] = 0;
303 		miblen = 3;
304 	}
305 
306 	procs = NULL;
307 	st = sysctl(mib, miblen, NULL, &size, NULL, 0);
308 	do {
309 		size += size / 10;
310 		newprocs = realloc(procs, size);
311 		if (newprocs == NULL) {
312 			free(procs);
313 			err(1, "could not reallocate memory");
314 		}
315 		procs = newprocs;
316 		st = sysctl(mib, miblen, procs, &size, NULL, 0);
317 	} while (st == -1 && errno == ENOMEM);
318 	if (st == -1)
319 		err(1, "could not sysctl(KERN_PROC)");
320 	if (size % sizeof(struct kinfo_proc) != 0) {
321 		fprintf(stderr, "proc size mismatch (%zu total, %zu chunks)\n",
322 			size, sizeof(struct kinfo_proc));
323 		fprintf(stderr, "userland out of sync with kernel\n");
324 		exit(1);
325 	}
326 	nprocs = size / sizeof(struct kinfo_proc);
327 	if (dflag)
328 		printf("nprocs %d\n", nprocs);
329 	mypid = getpid();
330 
331 	for (i = 0; i < nprocs; i++) {
332 		if (procs[i].ki_stat == SZOMB && !zflag)
333 			continue;
334 		thispid = procs[i].ki_pid;
335 		strlcpy(thiscmd, procs[i].ki_comm, sizeof(thiscmd));
336 		thistdev = procs[i].ki_tdev;
337 		if (eflag)
338 			thisuid = procs[i].ki_uid;	/* effective uid */
339 		else
340 			thisuid = procs[i].ki_ruid;	/* real uid */
341 
342 		if (thispid == mypid)
343 			continue;
344 		matched = 1;
345 		if (user) {
346 			if (thisuid != uid)
347 				matched = 0;
348 		}
349 		if (tty) {
350 			if (thistdev != tdev)
351 				matched = 0;
352 		}
353 		if (cmd) {
354 			if (mflag) {
355 				if (regcomp(&rgx, cmd,
356 				    REG_EXTENDED|REG_NOSUB) != 0) {
357 					mflag = 0;
358 					warnx("%s: illegal regexp", cmd);
359 				}
360 			}
361 			if (mflag) {
362 				pmatch.rm_so = 0;
363 				pmatch.rm_eo = strlen(thiscmd);
364 				if (regexec(&rgx, thiscmd, 0, &pmatch,
365 				    REG_STARTEND) != 0)
366 					matched = 0;
367 				regfree(&rgx);
368 			} else {
369 				if (strncmp(thiscmd, cmd, MAXCOMLEN) != 0)
370 					matched = 0;
371 			}
372 		}
373 		if (jflag && thispid == getpid())
374 			matched = 0;
375 		if (matched == 0)
376 			continue;
377 		if (ac > 0)
378 			matched = 0;
379 		for (j = 0; j < ac; j++) {
380 			if (mflag) {
381 				if (regcomp(&rgx, av[j],
382 				    REG_EXTENDED|REG_NOSUB) != 0) {
383 					mflag = 0;
384 					warnx("%s: illegal regexp", av[j]);
385 				}
386 			}
387 			if (mflag) {
388 				pmatch.rm_so = 0;
389 				pmatch.rm_eo = strlen(thiscmd);
390 				if (regexec(&rgx, thiscmd, 0, &pmatch,
391 				    REG_STARTEND) == 0)
392 					matched = 1;
393 				regfree(&rgx);
394 			} else {
395 				if (strcmp(thiscmd, av[j]) == 0)
396 					matched = 1;
397 			}
398 			if (matched)
399 				break;
400 		}
401 		if (matched != 0 && Iflag) {
402 			printf("Send signal %d to %s (pid %d uid %d)? ",
403 				sig, thiscmd, thispid, thisuid);
404 			fflush(stdout);
405 			first = ch = getchar();
406 			while (ch != '\n' && ch != EOF)
407 				ch = getchar();
408 			if (first != 'y' && first != 'Y')
409 				matched = 0;
410 		}
411 		if (matched == 0)
412 			continue;
413 		if (dflag)
414 			printf("sig:%d, cmd:%s, pid:%d, dev:0x%jx uid:%d\n",
415 			    sig, thiscmd, thispid, (uintmax_t)thistdev,
416 			    thisuid);
417 
418 		if (vflag || sflag)
419 			printf("kill -%s %d\n", sys_signame[sig], thispid);
420 
421 		killed++;
422 		if (!dflag && !sflag) {
423 			if (kill(thispid, sig) < 0 /* && errno != ESRCH */ ) {
424 				warn("warning: kill -%s %d",
425 				    sys_signame[sig], thispid);
426 				errors = 1;
427 			}
428 		}
429 	}
430 	if (killed == 0) {
431 		if (!qflag)
432 			fprintf(stderr, "No matching processes %swere found\n",
433 			    getuid() != 0 ? "belonging to you " : "");
434 		errors = 1;
435 	}
436 	exit(errors);
437 }
438