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