xref: /freebsd/usr.bin/killall/killall.c (revision d37ea99837e6ad50837fd9fe1771ddf1c3ba6002)
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 
49 static void __dead2
50 usage(void)
51 {
52 
53 	fprintf(stderr, "usage: killall [-delmsvz] [-help] [-j jid]\n");
54 	fprintf(stderr,
55 	    "               [-u user] [-t tty] [-c cmd] [-SIGNAL] [cmd]...\n");
56 	fprintf(stderr, "At least one option or argument to specify processes must be given.\n");
57 	exit(1);
58 }
59 
60 static char *
61 upper(const char *str)
62 {
63 	static char buf[80];
64 	char *s;
65 
66 	strncpy(buf, str, sizeof(buf));
67 	buf[sizeof(buf) - 1] = '\0';
68 	for (s = buf; *s; s++)
69 		*s = toupper(*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 	av++;
140 	ac--;
141 
142 	while (ac > 0) {
143 		if (strcmp(*av, "-l") == 0) {
144 			printsig(stdout);
145 			exit(0);
146 		}
147 		if (strcmp(*av, "-help") == 0)
148 			usage();
149 		if (**av == '-') {
150 			++*av;
151 			switch (**av) {
152 			case 'j':
153 				++*av;
154 				if (**av == '\0')
155 					++av;
156 				--ac;
157 				jflag++;
158 				if (!*av)
159 				    	errx(1, "must specify jid");
160 				jid = strtol(*av, &ep, 10);
161 				if (!*av || *ep)
162 					errx(1, "illegal jid: %s", *av);
163 				if (jail_attach(jid) == -1)
164 					err(1, "jail_attach(): %d", jid);
165 				break;
166 			case 'u':
167 				++*av;
168 				if (**av == '\0')
169 					++av;
170 				--ac;
171 				user = *av;
172 				break;
173 			case 't':
174 				++*av;
175 				if (**av == '\0')
176 					++av;
177 				--ac;
178 				tty = *av;
179 				break;
180 			case 'c':
181 				++*av;
182 				if (**av == '\0')
183 					++av;
184 				--ac;
185 				cmd = *av;
186 				break;
187 			case 'v':
188 				vflag++;
189 				break;
190 			case 's':
191 				sflag++;
192 				break;
193 			case 'd':
194 				dflag++;
195 				break;
196 			case 'e':
197 				eflag++;
198 				break;
199 			case 'm':
200 				mflag++;
201 				break;
202 			case 'z':
203 				zflag++;
204 				break;
205 			default:
206 				if (isalpha(**av)) {
207 					if (strncasecmp(*av, "sig", 3) == 0)
208 						*av += 3;
209 					for (sig = NSIG, p = sys_signame + 1;
210 					     --sig; ++p)
211 						if (strcasecmp(*p, *av) == 0) {
212 							sig = p - sys_signame;
213 							break;
214 						}
215 					if (!sig)
216 						nosig(*av);
217 				} else if (isdigit(**av)) {
218 					sig = strtol(*av, &ep, 10);
219 					if (!*av || *ep)
220 						errx(1, "illegal signal number: %s", *av);
221 					if (sig < 0 || sig > NSIG)
222 						nosig(*av);
223 				} else
224 					nosig(*av);
225 			}
226 			++av;
227 			--ac;
228 		} else {
229 			break;
230 		}
231 	}
232 
233 	if (user == NULL && tty == NULL && cmd == NULL && !jflag && ac == 0)
234 		usage();
235 
236 	if (tty) {
237 		if (strncmp(tty, "/dev/", 5) == 0)
238 			snprintf(buf, sizeof(buf), "%s", tty);
239 		else if (strncmp(tty, "tty", 3) == 0)
240 			snprintf(buf, sizeof(buf), "/dev/%s", tty);
241 		else
242 			snprintf(buf, sizeof(buf), "/dev/tty%s", tty);
243 		if (stat(buf, &sb) < 0)
244 			err(1, "stat(%s)", buf);
245 		if (!S_ISCHR(sb.st_mode))
246 			errx(1, "%s: not a character device", buf);
247 		tdev = sb.st_rdev;
248 		if (dflag)
249 			printf("ttydev:0x%x\n", tdev);
250 	}
251 	if (user) {
252 		uid = strtol(user, &ep, 10);
253 		if (*user == '\0' || *ep != '\0') { /* was it a number? */
254 			pw = getpwnam(user);
255 			if (pw == NULL)
256 				errx(1, "user %s does not exist", user);
257 			uid = pw->pw_uid;
258 			if (dflag)
259 				printf("uid:%d\n", uid);
260 		}
261 	} else {
262 		uid = getuid();
263 		if (uid != 0) {
264 			pw = getpwuid(uid);
265 			if (pw)
266 				user = pw->pw_name;
267 			if (dflag)
268 				printf("uid:%d\n", uid);
269 		}
270 	}
271 	size = 0;
272 	mib[0] = CTL_KERN;
273 	mib[1] = KERN_PROC;
274 	mib[2] = KERN_PROC_PROC;
275 	mib[3] = 0;
276 	miblen = 3;
277 
278 	if (user) {
279 		mib[2] = eflag ? KERN_PROC_UID : KERN_PROC_RUID;
280 		mib[3] = uid;
281 		miblen = 4;
282 	} else if (tty) {
283 		mib[2] = KERN_PROC_TTY;
284 		mib[3] = tdev;
285 		miblen = 4;
286 	}
287 
288 	st = sysctl(mib, miblen, NULL, &size, NULL, 0);
289 	do {
290 		size += size / 10;
291 		newprocs = realloc(procs, size);
292 		if (newprocs == 0) {
293 			if (procs)
294 				free(procs);
295 			errx(1, "could not reallocate memory");
296 		}
297 		procs = newprocs;
298 		st = sysctl(mib, miblen, procs, &size, NULL, 0);
299 	} while (st == -1 && errno == ENOMEM);
300 	if (st == -1)
301 		err(1, "could not sysctl(KERN_PROC)");
302 	if (size % sizeof(struct kinfo_proc) != 0) {
303 		fprintf(stderr, "proc size mismatch (%d total, %d chunks)\n",
304 			size, sizeof(struct kinfo_proc));
305 		fprintf(stderr, "userland out of sync with kernel, recompile libkvm etc\n");
306 		exit(1);
307 	}
308 	nprocs = size / sizeof(struct kinfo_proc);
309 	if (dflag)
310 		printf("nprocs %d\n", nprocs);
311 	mypid = getpid();
312 
313 	for (i = 0; i < nprocs; i++) {
314 		if ((procs[i].ki_stat & SZOMB) == SZOMB && !zflag)
315 			continue;
316 		thispid = procs[i].ki_pid;
317 		strncpy(thiscmd, procs[i].ki_comm, MAXCOMLEN);
318 		thiscmd[MAXCOMLEN] = '\0';
319 		thistdev = procs[i].ki_tdev;
320 		if (eflag)
321 			thisuid = procs[i].ki_uid;	/* effective uid */
322 		else
323 			thisuid = procs[i].ki_ruid;	/* real uid */
324 
325 		if (thispid == mypid)
326 			continue;
327 		matched = 1;
328 		if (user) {
329 			if (thisuid != uid)
330 				matched = 0;
331 		}
332 		if (tty) {
333 			if (thistdev != tdev)
334 				matched = 0;
335 		}
336 		if (cmd) {
337 			if (mflag) {
338 				if (regcomp(&rgx, cmd,
339 				    REG_EXTENDED|REG_NOSUB) != 0) {
340 					mflag = 0;
341 					warnx("%s: illegal regexp", cmd);
342 				}
343 			}
344 			if (mflag) {
345 				pmatch.rm_so = 0;
346 				pmatch.rm_eo = strlen(thiscmd);
347 				if (regexec(&rgx, thiscmd, 0, &pmatch,
348 				    REG_STARTEND) != 0)
349 					matched = 0;
350 				regfree(&rgx);
351 			} else {
352 				if (strncmp(thiscmd, cmd, MAXCOMLEN) != 0)
353 					matched = 0;
354 			}
355 		}
356 		if (jflag && thispid == getpid())
357 			matched = 0;
358 		if (matched == 0)
359 			continue;
360 		if (ac > 0)
361 			matched = 0;
362 		for (j = 0; j < ac; j++) {
363 			if (mflag) {
364 				if (regcomp(&rgx, av[j],
365 				    REG_EXTENDED|REG_NOSUB) != 0) {
366 					mflag = 0;
367 					warnx("%s: illegal regexp", av[j]);
368 				}
369 			}
370 			if (mflag) {
371 				pmatch.rm_so = 0;
372 				pmatch.rm_eo = strlen(thiscmd);
373 				if (regexec(&rgx, thiscmd, 0, &pmatch,
374 				    REG_STARTEND) == 0)
375 					matched = 1;
376 				regfree(&rgx);
377 			} else {
378 				if (strcmp(thiscmd, av[j]) == 0)
379 					matched = 1;
380 			}
381 			if (matched)
382 				break;
383 		}
384 		if (matched == 0)
385 			continue;
386 		if (dflag)
387 			printf("sig:%d, cmd:%s, pid:%d, dev:0x%x uid:%d\n", sig,
388 			    thiscmd, thispid, thistdev, thisuid);
389 
390 		if (vflag || sflag)
391 			printf("kill -%s %d\n", upper(sys_signame[sig]),
392 			    thispid);
393 
394 		killed++;
395 		if (!dflag && !sflag) {
396 			if (kill(thispid, sig) < 0 /* && errno != ESRCH */ ) {
397 				warn("warning: kill -%s %d",
398 				    upper(sys_signame[sig]), thispid);
399 				errors = 1;
400 			}
401 		}
402 	}
403 	if (killed == 0) {
404 		fprintf(stderr, "No matching processes %swere found\n",
405 		    getuid() != 0 ? "belonging to you " : "");
406 		errors = 1;
407 	}
408 	exit(errors);
409 }
410