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