killall.c revision 65177
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 * $FreeBSD: head/usr.bin/killall/killall.c 65177 2000-08-28 22:09:38Z peter $
28 */
29
30#include <sys/cdefs.h>
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
48static char	*prog;
49
50static void __dead2
51usage(void)
52{
53
54	fprintf(stderr, "usage: %s [-l] [-v] [-m] [-sig] [-u user] [-t tty] [-c cmd] [cmd]...\n", prog);
55	fprintf(stderr, "At least one option or argument to specify processes must be given.\n");
56	exit(1);
57}
58
59static char *
60upper(const char *str)
61{
62	static char buf[80];
63	char *s;
64
65	strncpy(buf, str, sizeof(buf));
66	buf[sizeof(buf) - 1] = '\0';
67	for (s = buf; *s; s++)
68		*s = toupper(*s);
69	return buf;
70}
71
72
73static void
74printsig(FILE *fp)
75{
76	const char	*const * p;
77	int		cnt;
78	int		offset = 0;
79
80	for (cnt = NSIG, p = sys_signame + 1; --cnt; ++p) {
81		offset += fprintf(fp, "%s ", upper(*p));
82		if (offset >= 75 && cnt > 1) {
83			offset = 0;
84			fprintf(fp, "\n");
85		}
86	}
87	fprintf(fp, "\n");
88}
89
90static void
91nosig(char *name)
92{
93
94	warnx("unknown signal %s; valid signals:", name);
95	printsig(stderr);
96	exit(1);
97}
98
99int
100main(int ac, char **av)
101{
102	struct kinfo_proc *procs = NULL, *newprocs;
103	struct stat	sb;
104	struct passwd	*pw;
105	regex_t		rgx;
106	regmatch_t	pmatch;
107	int		i, j;
108	char		buf[256];
109	char		*user = NULL;
110	char		*tty = NULL;
111	char		*cmd = NULL;
112	int		vflag = 0;
113	int		sflag = 0;
114	int		dflag = 0;
115	int		mflag = 0;
116	uid_t		uid = 0;
117	dev_t		tdev = 0;
118	char		thiscmd[MAXCOMLEN + 1];
119	pid_t		thispid;
120	uid_t		thisuid;
121	dev_t		thistdev;
122	int		sig = SIGTERM;
123	const char *const *p;
124	char		*ep;
125	int		errors = 0;
126	int		mib[3];
127	size_t		miblen;
128	int		st, nprocs;
129	size_t		size;
130	int		matched;
131	int		killed = 0;
132
133	prog = av[0];
134	av++;
135	ac--;
136
137	while (ac > 0) {
138		if (strcmp(*av, "-l") == 0) {
139			printsig(stdout);
140			exit(0);
141		}
142		if (strcmp(*av, "-help") == 0)
143			usage();
144		if (**av == '-') {
145			++*av;
146			switch (**av) {
147			case 'U':
148			case 'u':
149				++*av;
150				if (**av == '\0')
151					++av;
152				--ac;
153				user = *av;
154				break;
155			case 't':
156				++*av;
157				if (**av == '\0')
158					++av;
159				--ac;
160				tty = *av;
161				break;
162			case 'c':
163				++*av;
164				if (**av == '\0')
165					++av;
166				--ac;
167				cmd = *av;
168				break;
169			case 'v':
170				vflag++;
171				break;
172			case 's':
173				sflag++;
174				break;
175			case 'd':
176				dflag++;
177				break;
178			case 'm':
179				mflag++;
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		pw = getpwnam(user);
229		if (pw == NULL)
230			errx(1, "user %s does not exist", user);
231		uid = pw->pw_uid;
232		if (dflag)
233			printf("uid:%d\n", uid);
234	} else {
235		uid = getuid();
236		if (uid != 0) {
237			pw = getpwuid(uid);
238			if (pw)
239				user = pw->pw_name;
240			if (dflag)
241				printf("uid:%d\n", uid);
242		}
243	}
244	size = 0;
245	mib[0] = CTL_KERN;
246	mib[1] = KERN_PROC;
247	mib[2] = KERN_PROC_ALL;
248	mib[3] = 0;
249	miblen = 3;
250
251	if (user && mib[2] == KERN_PROC_ALL) {
252		mib[2] = KERN_PROC_UID;
253		mib[3] = uid;
254		miblen = 4;
255	}
256	if (tty && mib[2] == KERN_PROC_ALL) {
257		mib[2] = KERN_PROC_TTY;
258		mib[3] = tdev;
259		miblen = 4;
260	}
261
262	st = sysctl(mib, miblen, NULL, &size, NULL, 0);
263	do {
264		size += size / 10;
265		newprocs = realloc(procs, size);
266		if (newprocs == 0) {
267			if (procs)
268				free(procs);
269			errx(1, "could not reallocate memory");
270		}
271		procs = newprocs;
272		st = sysctl(mib, miblen, procs, &size, NULL, 0);
273	} while (st == -1 && errno == ENOMEM);
274	if (st == -1)
275		err(1, "could not sysctl(KERN_PROC)");
276	if (size % sizeof(struct kinfo_proc) != 0) {
277		fprintf(stderr, "proc size mismatch (%d total, %d chunks)\n",
278			size, sizeof(struct kinfo_proc));
279		fprintf(stderr, "userland out of sync with kernel, recompile libkvm etc\n");
280		exit(1);
281	}
282	nprocs = size / sizeof(struct kinfo_proc);
283	if (dflag)
284		printf("nprocs %d\n", nprocs);
285
286	for (i = 0; i < nprocs; i++) {
287		thispid = procs[i].kp_proc.p_pid;
288		strncpy(thiscmd, procs[i].kp_proc.p_comm, MAXCOMLEN);
289		thiscmd[MAXCOMLEN] = '\0';
290		thistdev = procs[i].kp_eproc.e_tdev;
291		thisuid = procs[i].kp_eproc.e_pcred.p_ruid;	/* real uid */
292
293		matched = 1;
294		if (user) {
295			if (thisuid != uid)
296				matched = 0;
297		}
298		if (tty) {
299			if (thistdev != tdev)
300				matched = 0;
301		}
302		if (cmd) {
303			if (mflag) {
304				if (regcomp(&rgx, cmd,
305				    REG_EXTENDED|REG_NOSUB) != 0) {
306					mflag = 0;
307					warnx("%s: illegal regexp", cmd);
308				}
309			}
310			if (mflag) {
311				pmatch.rm_so = 0;
312				pmatch.rm_eo = strlen(thiscmd);
313				if (regexec(&rgx, thiscmd, 0, &pmatch,
314				    REG_STARTEND) != 0)
315					matched = 0;
316				regfree(&rgx);
317			} else {
318				if (strcmp(thiscmd, cmd) != 0)
319					matched = 0;
320			}
321		}
322		if (matched == 0)
323			continue;
324		matched = 0;
325		for (j = 0; j < ac; j++) {
326			if (mflag) {
327				if (regcomp(&rgx, av[j],
328				    REG_EXTENDED|REG_NOSUB) != 0) {
329					mflag = 0;
330					warnx("%s: illegal regexp", av[j]);
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 = 1;
339				regfree(&rgx);
340			} else {
341				if (strcmp(thiscmd, av[j]) == 0)
342					matched = 1;
343			}
344			if (matched)
345				break;
346		}
347		if (matched == 0)
348			continue;
349		if (dflag)
350			printf("sig:%d, cmd:%s, pid:%d, dev:0x%x uid:%d\n", sig,
351			    thiscmd, thispid, thistdev, thisuid);
352
353		if (vflag || sflag)
354			printf("kill -%s %d\n", upper(sys_signame[sig]),
355			    thispid);
356
357		killed++;
358		if (!dflag && !sflag) {
359			if (kill(thispid, sig) < 0 /* && errno != ESRCH */ ) {
360				warn("kill -%s %d", upper(sys_signame[sig]),
361				    thispid);
362				errors = 1;
363			}
364		}
365	}
366	if (killed == 0) {
367		fprintf(stderr, "No matching processes %swere found\n",
368		    getuid() != 0 ? "belonging to you " : "");
369		errors = 1;
370	}
371	exit(errors);
372}
373