pkill.c revision 1.12 1 /* $NetBSD: pkill.c,v 1.12 2005/07/16 19:50:32 christos Exp $ */
2
3 /*-
4 * Copyright (c) 2002 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Andrew Doran.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the NetBSD
21 * Foundation, Inc. and its contributors.
22 * 4. Neither the name of The NetBSD Foundation nor the names of its
23 * contributors may be used to endorse or promote products derived
24 * from this software without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 * POSSIBILITY OF SUCH DAMAGE.
37 */
38
39 #include <sys/cdefs.h>
40 #ifndef lint
41 __RCSID("$NetBSD: pkill.c,v 1.12 2005/07/16 19:50:32 christos Exp $");
42 #endif /* !lint */
43
44 #include <sys/types.h>
45 #include <sys/param.h>
46 #include <sys/sysctl.h>
47 #include <sys/proc.h>
48 #include <sys/queue.h>
49 #include <sys/stat.h>
50
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <limits.h>
54 #include <string.h>
55 #include <unistd.h>
56 #include <signal.h>
57 #include <regex.h>
58 #include <ctype.h>
59 #include <kvm.h>
60 #include <err.h>
61 #include <pwd.h>
62 #include <grp.h>
63 #include <errno.h>
64 #include <paths.h>
65
66 #define STATUS_MATCH 0
67 #define STATUS_NOMATCH 1
68 #define STATUS_BADUSAGE 2
69 #define STATUS_ERROR 3
70
71 enum listtype {
72 LT_GENERIC,
73 LT_USER,
74 LT_GROUP,
75 LT_TTY,
76 LT_PGRP,
77 LT_SID
78 };
79
80 struct list {
81 SLIST_ENTRY(list) li_chain;
82 long li_number;
83 };
84
85 SLIST_HEAD(listhead, list);
86
87 static struct kinfo_proc2 *plist;
88 static char *selected;
89 static const char *delim = "\n";
90 static int nproc;
91 static int pgrep;
92 static int signum = SIGTERM;
93 static int newest;
94 static int inverse;
95 static int longfmt;
96 static int matchargs;
97 static int fullmatch;
98 static int cflags = REG_EXTENDED;
99 static kvm_t *kd;
100 static pid_t mypid;
101
102 static struct listhead euidlist = SLIST_HEAD_INITIALIZER(list);
103 static struct listhead ruidlist = SLIST_HEAD_INITIALIZER(list);
104 static struct listhead rgidlist = SLIST_HEAD_INITIALIZER(list);
105 static struct listhead pgrplist = SLIST_HEAD_INITIALIZER(list);
106 static struct listhead ppidlist = SLIST_HEAD_INITIALIZER(list);
107 static struct listhead tdevlist = SLIST_HEAD_INITIALIZER(list);
108 static struct listhead sidlist = SLIST_HEAD_INITIALIZER(list);
109
110 int main(int, char **);
111 static void usage(void) __attribute__((__noreturn__));
112 static int killact(struct kinfo_proc2 *);
113 static int grepact(struct kinfo_proc2 *);
114 static void makelist(struct listhead *, enum listtype, char *);
115
116 int
117 main(int argc, char **argv)
118 {
119 char buf[_POSIX2_LINE_MAX], *mstr, **pargv, *p, *q;
120 int i, j, ch, bestidx, rv, criteria;
121 int (*action)(struct kinfo_proc2 *);
122 struct kinfo_proc2 *kp;
123 struct list *li;
124 u_int32_t bestsec, bestusec;
125 regex_t reg;
126 regmatch_t regmatch;
127
128 setprogname(argv[0]);
129
130 if (strcmp(getprogname(), "pgrep") == 0) {
131 action = grepact;
132 pgrep = 1;
133 } else {
134 action = killact;
135 p = argv[1];
136
137 if (argc > 1 && p[0] == '-') {
138 p++;
139 i = (int)strtol(p, &q, 10);
140 if (*q == '\0') {
141 signum = i;
142 argv++;
143 argc--;
144 } else {
145 if (strncasecmp(p, "sig", 3) == 0)
146 p += 3;
147 for (i = 1; i < NSIG; i++)
148 if (strcasecmp(sys_signame[i], p) == 0)
149 break;
150 if (i != NSIG) {
151 signum = i;
152 argv++;
153 argc--;
154 }
155 }
156 }
157 }
158
159 criteria = 0;
160
161 while ((ch = getopt(argc, argv, "G:P:U:d:fg:ilns:t:u:vx")) != -1)
162 switch (ch) {
163 case 'G':
164 makelist(&rgidlist, LT_GROUP, optarg);
165 criteria = 1;
166 break;
167 case 'P':
168 makelist(&ppidlist, LT_GENERIC, optarg);
169 criteria = 1;
170 break;
171 case 'U':
172 makelist(&ruidlist, LT_USER, optarg);
173 criteria = 1;
174 break;
175 case 'd':
176 if (!pgrep)
177 usage();
178 delim = optarg;
179 break;
180 case 'f':
181 matchargs = 1;
182 break;
183 case 'g':
184 makelist(&pgrplist, LT_PGRP, optarg);
185 criteria = 1;
186 break;
187 case 'i':
188 cflags |= REG_ICASE;
189 break;
190 case 'l':
191 if (!pgrep)
192 usage();
193 longfmt = 1;
194 break;
195 case 'n':
196 newest = 1;
197 criteria = 1;
198 break;
199 case 's':
200 makelist(&sidlist, LT_SID, optarg);
201 criteria = 1;
202 break;
203 case 't':
204 makelist(&tdevlist, LT_TTY, optarg);
205 criteria = 1;
206 break;
207 case 'u':
208 makelist(&euidlist, LT_USER, optarg);
209 criteria = 1;
210 break;
211 case 'v':
212 inverse = 1;
213 break;
214 case 'x':
215 fullmatch = 1;
216 break;
217 default:
218 usage();
219 /* NOTREACHED */
220 }
221
222 argc -= optind;
223 argv += optind;
224 if (argc != 0)
225 criteria = 1;
226 if (!criteria)
227 usage();
228
229 mypid = getpid();
230
231 /*
232 * Retrieve the list of running processes from the kernel.
233 */
234 kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, buf);
235 if (kd == NULL)
236 errx(STATUS_ERROR, "Cannot open kernel files (%s)", buf);
237
238 plist = kvm_getproc2(kd, KERN_PROC_ALL, 0, sizeof(*plist), &nproc);
239 if (plist == NULL)
240 errx(STATUS_ERROR, "Cannot get process list (%s)",
241 kvm_geterr(kd));
242
243 /*
244 * Allocate memory which will be used to keep track of the
245 * selection.
246 */
247 if ((selected = calloc((size_t)1, (size_t)nproc)) == NULL)
248 err(STATUS_ERROR, "Cannot allocate memory for %d processes",
249 nproc);
250
251 /*
252 * Refine the selection.
253 */
254 for (; *argv != NULL; argv++) {
255 if ((rv = regcomp(®, *argv, cflags)) != 0) {
256 (void)regerror(rv, ®, buf, sizeof(buf));
257 errx(STATUS_BADUSAGE,
258 "Cannot compile regular expression `%s' (%s)",
259 *argv, buf);
260 }
261
262 for (i = 0, kp = plist; i < nproc; i++, kp++) {
263 if ((kp->p_flag & P_SYSTEM) != 0 || kp->p_pid == mypid)
264 continue;
265
266 if (matchargs) {
267 if ((pargv = kvm_getargv2(kd, kp, 0)) == NULL)
268 continue;
269
270 j = 0;
271 while (j < sizeof(buf) && *pargv != NULL) {
272 j += snprintf(buf + j, sizeof(buf) - j,
273 pargv[1] != NULL ? "%s " : "%s",
274 pargv[0]);
275 pargv++;
276 }
277
278 mstr = buf;
279 } else
280 mstr = kp->p_comm;
281
282 rv = regexec(®, mstr, 1, ®match, 0);
283 if (rv == 0) {
284 if (fullmatch) {
285 if (regmatch.rm_so == 0 &&
286 regmatch.rm_eo == strlen(mstr))
287 selected[i] = 1;
288 } else
289 selected[i] = 1;
290 } else if (rv != REG_NOMATCH) {
291 (void)regerror(rv, ®, buf, sizeof(buf));
292 errx(STATUS_ERROR,
293 "Regular expression evaluation error (%s)",
294 buf);
295 }
296 }
297
298 regfree(®);
299 }
300
301 for (i = 0, kp = plist; i < nproc; i++, kp++) {
302 if ((kp->p_flag & P_SYSTEM) != 0)
303 continue;
304
305 SLIST_FOREACH(li, &ruidlist, li_chain)
306 if (kp->p_ruid == (uid_t)li->li_number)
307 break;
308 if (SLIST_FIRST(&ruidlist) != NULL && li == NULL) {
309 selected[i] = 0;
310 continue;
311 }
312
313 SLIST_FOREACH(li, &rgidlist, li_chain)
314 if (kp->p_rgid == (gid_t)li->li_number)
315 break;
316 if (SLIST_FIRST(&rgidlist) != NULL && li == NULL) {
317 selected[i] = 0;
318 continue;
319 }
320
321 SLIST_FOREACH(li, &euidlist, li_chain)
322 if (kp->p_uid == (uid_t)li->li_number)
323 break;
324 if (SLIST_FIRST(&euidlist) != NULL && li == NULL) {
325 selected[i] = 0;
326 continue;
327 }
328
329 SLIST_FOREACH(li, &ppidlist, li_chain)
330 if (kp->p_ppid == (uid_t)li->li_number)
331 break;
332 if (SLIST_FIRST(&ppidlist) != NULL && li == NULL) {
333 selected[i] = 0;
334 continue;
335 }
336
337 SLIST_FOREACH(li, &pgrplist, li_chain)
338 if (kp->p__pgid == (uid_t)li->li_number)
339 break;
340 if (SLIST_FIRST(&pgrplist) != NULL && li == NULL) {
341 selected[i] = 0;
342 continue;
343 }
344
345 SLIST_FOREACH(li, &tdevlist, li_chain) {
346 if (li->li_number == -1 &&
347 (kp->p_flag & P_CONTROLT) == 0)
348 break;
349 if (kp->p_tdev == (uid_t)li->li_number)
350 break;
351 }
352 if (SLIST_FIRST(&tdevlist) != NULL && li == NULL) {
353 selected[i] = 0;
354 continue;
355 }
356
357 SLIST_FOREACH(li, &sidlist, li_chain)
358 if (kp->p_sid == (uid_t)li->li_number)
359 break;
360 if (SLIST_FIRST(&sidlist) != NULL && li == NULL) {
361 selected[i] = 0;
362 continue;
363 }
364
365 if (argc == 0)
366 selected[i] = 1;
367 }
368
369 if (newest) {
370 bestsec = 0;
371 bestusec = 0;
372 bestidx = -1;
373
374 for (i = 0, kp = plist; i < nproc; i++, kp++) {
375 if (!selected[i])
376 continue;
377
378 if (kp->p_ustart_sec > bestsec ||
379 (kp->p_ustart_sec == bestsec
380 && kp->p_ustart_usec > bestusec)) {
381 bestsec = kp->p_ustart_sec;
382 bestusec = kp->p_ustart_usec;
383 bestidx = i;
384 }
385 }
386
387 (void)memset(selected, 0, (size_t)nproc);
388 if (bestidx != -1)
389 selected[bestidx] = 1;
390 }
391
392 /*
393 * Take the appropriate action for each matched process, if any.
394 */
395 for (i = 0, rv = 0, kp = plist; i < nproc; i++, kp++) {
396 if (kp->p_pid == mypid)
397 continue;
398 if (selected[i]) {
399 if (inverse)
400 continue;
401 } else if (!inverse)
402 continue;
403
404 if ((kp->p_flag & P_SYSTEM) != 0)
405 continue;
406
407 rv |= (*action)(kp);
408 }
409
410 return rv ? STATUS_MATCH : STATUS_NOMATCH;
411 }
412
413 static void
414 usage(void)
415 {
416 const char *ustr;
417
418 if (pgrep)
419 ustr = "[-filnvx] [-d delim]";
420 else
421 ustr = "[-signal] [-finvx]";
422
423 (void)fprintf(stderr,
424 "Usage: %s %s [-G gid] [-P ppid] [-U uid] [-g pgrp] [-s sid]\n"
425 " [-t tty] [-u euid] pattern ...\n", getprogname(),
426 ustr);
427
428 exit(STATUS_ERROR);
429 }
430
431 static int
432 killact(struct kinfo_proc2 *kp)
433 {
434 if (kill(kp->p_pid, signum) == -1) {
435 if (errno == ESRCH)
436 /*
437 * The process disappeared between us matching
438 * it and us signalling it. Return 0 to
439 * indicate that the process should not be
440 * considered a match.
441 */
442 return 0;
443
444 err(STATUS_ERROR, "signalling pid %d", (int)kp->p_pid);
445 }
446
447 return 1;
448 }
449
450 static int
451 grepact(struct kinfo_proc2 *kp)
452 {
453 char **argv;
454
455 if (longfmt && matchargs) {
456 if ((argv = kvm_getargv2(kd, kp, 0)) == NULL)
457 /*
458 * The process disappeared? Return 0 to
459 * indicate that the process should not be
460 * considered a match.
461 */
462 return 0;
463
464 (void)printf("%d ", (int)kp->p_pid);
465 for (; *argv != NULL; argv++) {
466 (void)printf("%s", *argv);
467 if (argv[1] != NULL)
468 (void)putchar(' ');
469 }
470 } else if (longfmt)
471 (void)printf("%d %s", (int)kp->p_pid, kp->p_comm);
472 else
473 (void)printf("%d", (int)kp->p_pid);
474
475 (void)printf("%s", delim);
476
477 return 1;
478 }
479
480 static void
481 makelist(struct listhead *head, enum listtype type, char *src)
482 {
483 struct list *li;
484 struct passwd *pw;
485 struct group *gr;
486 struct stat st;
487 char *sp, *ep, buf[MAXPATHLEN];
488 const char *p;
489 int empty;
490 const char *prefix = _PATH_DEV;
491
492 empty = 1;
493
494 while ((sp = strsep(&src, ",")) != NULL) {
495 if (*sp == '\0')
496 usage();
497
498 if ((li = malloc(sizeof(*li))) == NULL)
499 err(STATUS_ERROR, "Cannot allocate %zd bytes",
500 sizeof(*li));
501 SLIST_INSERT_HEAD(head, li, li_chain);
502 empty = 0;
503
504 li->li_number = (uid_t)strtol(sp, &ep, 0);
505 if (*ep == '\0') {
506 switch (type) {
507 case LT_PGRP:
508 if (li->li_number == 0)
509 li->li_number = getpgrp();
510 break;
511 case LT_SID:
512 if (li->li_number == 0)
513 li->li_number = getsid(mypid);
514 break;
515 case LT_TTY:
516 usage();
517 /*NOTREACHED*/
518 default:
519 break;
520 }
521 continue;
522 }
523
524 switch (type) {
525 case LT_USER:
526 if ((pw = getpwnam(sp)) == NULL)
527 errx(STATUS_BADUSAGE, "Unknown user `%s'",
528 sp);
529 li->li_number = pw->pw_uid;
530 break;
531 case LT_GROUP:
532 if ((gr = getgrnam(sp)) == NULL)
533 errx(STATUS_BADUSAGE, "Unknown group `%s'",
534 sp);
535 li->li_number = gr->gr_gid;
536 break;
537 case LT_TTY:
538 if (strcmp(sp, "-") == 0) {
539 li->li_number = -1;
540 break;
541 } else if (strcmp(sp, "co") == 0)
542 p = "console";
543 else if (strncmp(sp, "tty", 3) == 0)
544 p = sp;
545 else {
546 p = sp;
547 prefix = _PATH_TTY;
548 }
549
550 (void)snprintf(buf, sizeof(buf), "%s%s", prefix, p);
551
552 if (stat(buf, &st) == -1) {
553 if (errno == ENOENT)
554 errx(STATUS_BADUSAGE,
555 "No such tty: `%s'", sp);
556 err(STATUS_ERROR, "Cannot access `%s'", sp);
557 }
558
559 if ((st.st_mode & S_IFCHR) == 0)
560 errx(STATUS_BADUSAGE, "Not a tty: `%s'", sp);
561
562 li->li_number = st.st_rdev;
563 break;
564 default:
565 usage();
566 }
567 }
568
569 if (empty)
570 usage();
571 }
572