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