xref: /freebsd/usr.bin/killall/killall.c (revision 7660b554bc59a07be0431c17e0e33815818baa69)
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 = 4;
272 
273 	if (user) {
274 		mib[2] = KERN_PROC_RUID;
275 		mib[3] = uid;
276 	} else if (tty) {
277 		mib[2] = KERN_PROC_TTY;
278 		mib[3] = tdev;
279 	}
280 
281 	st = sysctl(mib, miblen, NULL, &size, NULL, 0);
282 	do {
283 		size += size / 10;
284 		newprocs = realloc(procs, size);
285 		if (newprocs == 0) {
286 			if (procs)
287 				free(procs);
288 			errx(1, "could not reallocate memory");
289 		}
290 		procs = newprocs;
291 		st = sysctl(mib, miblen, procs, &size, NULL, 0);
292 	} while (st == -1 && errno == ENOMEM);
293 	if (st == -1)
294 		err(1, "could not sysctl(KERN_PROC)");
295 	if (size % sizeof(struct kinfo_proc) != 0) {
296 		fprintf(stderr, "proc size mismatch (%d total, %d chunks)\n",
297 			size, sizeof(struct kinfo_proc));
298 		fprintf(stderr, "userland out of sync with kernel, recompile libkvm etc\n");
299 		exit(1);
300 	}
301 	nprocs = size / sizeof(struct kinfo_proc);
302 	if (dflag)
303 		printf("nprocs %d\n", nprocs);
304 
305 	for (i = 0; i < nprocs; i++) {
306 		if ((procs[i].ki_stat & SZOMB) == SZOMB && !zflag)
307 			continue;
308 		thispid = procs[i].ki_pid;
309 		strncpy(thiscmd, procs[i].ki_comm, MAXCOMLEN);
310 		thiscmd[MAXCOMLEN] = '\0';
311 		thistdev = procs[i].ki_tdev;
312 		thisuid = procs[i].ki_ruid;	/* real uid */
313 
314 		matched = 1;
315 		if (user) {
316 			if (thisuid != uid)
317 				matched = 0;
318 		}
319 		if (tty) {
320 			if (thistdev != tdev)
321 				matched = 0;
322 		}
323 		if (cmd) {
324 			if (mflag) {
325 				if (regcomp(&rgx, cmd,
326 				    REG_EXTENDED|REG_NOSUB) != 0) {
327 					mflag = 0;
328 					warnx("%s: illegal regexp", cmd);
329 				}
330 			}
331 			if (mflag) {
332 				pmatch.rm_so = 0;
333 				pmatch.rm_eo = strlen(thiscmd);
334 				if (regexec(&rgx, thiscmd, 0, &pmatch,
335 				    REG_STARTEND) != 0)
336 					matched = 0;
337 				regfree(&rgx);
338 			} else {
339 				if (strncmp(thiscmd, cmd, MAXCOMLEN) != 0)
340 					matched = 0;
341 			}
342 		}
343 		if (jflag && thispid == getpid())
344 			matched = 0;
345 		if (matched == 0)
346 			continue;
347 		if (ac > 0)
348 			matched = 0;
349 		for (j = 0; j < ac; j++) {
350 			if (mflag) {
351 				if (regcomp(&rgx, av[j],
352 				    REG_EXTENDED|REG_NOSUB) != 0) {
353 					mflag = 0;
354 					warnx("%s: illegal regexp", av[j]);
355 				}
356 			}
357 			if (mflag) {
358 				pmatch.rm_so = 0;
359 				pmatch.rm_eo = strlen(thiscmd);
360 				if (regexec(&rgx, thiscmd, 0, &pmatch,
361 				    REG_STARTEND) == 0)
362 					matched = 1;
363 				regfree(&rgx);
364 			} else {
365 				if (strcmp(thiscmd, av[j]) == 0)
366 					matched = 1;
367 			}
368 			if (matched)
369 				break;
370 		}
371 		if (matched == 0)
372 			continue;
373 		if (dflag)
374 			printf("sig:%d, cmd:%s, pid:%d, dev:0x%x uid:%d\n", sig,
375 			    thiscmd, thispid, thistdev, thisuid);
376 
377 		if (vflag || sflag)
378 			printf("kill -%s %d\n", upper(sys_signame[sig]),
379 			    thispid);
380 
381 		killed++;
382 		if (!dflag && !sflag) {
383 			if (kill(thispid, sig) < 0 /* && errno != ESRCH */ ) {
384 				warn("warning: kill -%s %d",
385 				    upper(sys_signame[sig]), thispid);
386 				errors = 1;
387 			}
388 		}
389 	}
390 	if (killed == 0) {
391 		fprintf(stderr, "No matching processes %swere found\n",
392 		    getuid() != 0 ? "belonging to you " : "");
393 		errors = 1;
394 	}
395 	exit(errors);
396 }
397