pkill.c revision 1.10 1 /* $NetBSD: pkill.c,v 1.10 2005/07/16 15:53:56 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.10 2005/07/16 15:53:56 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
65 #define STATUS_MATCH 0
66 #define STATUS_NOMATCH 1
67 #define STATUS_BADUSAGE 2
68 #define STATUS_ERROR 3
69
70 enum listtype {
71 LT_GENERIC,
72 LT_USER,
73 LT_GROUP,
74 LT_TTY,
75 LT_PGRP,
76 LT_SID
77 };
78
79 struct list {
80 SLIST_ENTRY(list) li_chain;
81 long li_number;
82 };
83
84 SLIST_HEAD(listhead, list);
85
86 struct kinfo_proc2 *plist;
87 char *selected;
88 char *delim = "\n";
89 int nproc;
90 int pgrep;
91 int signum = SIGTERM;
92 int newest;
93 int inverse;
94 int longfmt;
95 int matchargs;
96 int fullmatch;
97 int cflags = REG_EXTENDED;
98 kvm_t *kd;
99 pid_t mypid;
100
101 struct listhead euidlist = SLIST_HEAD_INITIALIZER(list);
102 struct listhead ruidlist = SLIST_HEAD_INITIALIZER(list);
103 struct listhead rgidlist = SLIST_HEAD_INITIALIZER(list);
104 struct listhead pgrplist = SLIST_HEAD_INITIALIZER(list);
105 struct listhead ppidlist = SLIST_HEAD_INITIALIZER(list);
106 struct listhead tdevlist = SLIST_HEAD_INITIALIZER(list);
107 struct listhead sidlist = SLIST_HEAD_INITIALIZER(list);
108
109 int main(int, char **);
110 void usage(void);
111 int killact(struct kinfo_proc2 *);
112 int grepact(struct kinfo_proc2 *);
113 void makelist(struct listhead *, enum listtype, char *);
114
115 int
116 main(int argc, char **argv)
117 {
118 extern char *optarg;
119 extern int optind;
120 char buf[_POSIX2_LINE_MAX], *mstr, **pargv, *p, *q;
121 int i, j, ch, bestidx, rv, criteria;
122 int (*action)(struct kinfo_proc2 *);
123 struct kinfo_proc2 *kp;
124 struct list *li;
125 u_int32_t bestsec, bestusec;
126 regex_t reg;
127 regmatch_t regmatch;
128
129 if (strcmp(getprogname(), "pgrep") == 0) {
130 action = grepact;
131 pgrep = 1;
132 } else {
133 action = killact;
134 p = argv[1];
135
136 if (argc > 1 && p[0] == '-') {
137 p++;
138 i = (int)strtol(p, &q, 10);
139 if (*q == '\0') {
140 signum = i;
141 argv++;
142 argc--;
143 } else {
144 if (strncasecmp(p, "sig", 3) == 0)
145 p += 3;
146 for (i = 1; i < NSIG; i++)
147 if (strcasecmp(sys_signame[i], p) == 0)
148 break;
149 if (i != NSIG) {
150 signum = i;
151 argv++;
152 argc--;
153 }
154 }
155 }
156 }
157
158 criteria = 0;
159
160 while ((ch = getopt(argc, argv, "G:P:U:d:fg:ilns:t:u:vx")) != -1)
161 switch (ch) {
162 case 'G':
163 makelist(&rgidlist, LT_GROUP, optarg);
164 criteria = 1;
165 break;
166 case 'P':
167 makelist(&ppidlist, LT_GENERIC, optarg);
168 criteria = 1;
169 break;
170 case 'U':
171 makelist(&ruidlist, LT_USER, optarg);
172 criteria = 1;
173 break;
174 case 'd':
175 if (!pgrep)
176 usage();
177 delim = optarg;
178 break;
179 case 'f':
180 matchargs = 1;
181 break;
182 case 'g':
183 makelist(&pgrplist, LT_PGRP, optarg);
184 criteria = 1;
185 break;
186 case 'i':
187 cflags |= REG_ICASE;
188 break;
189 case 'l':
190 if (!pgrep)
191 usage();
192 longfmt = 1;
193 break;
194 case 'n':
195 newest = 1;
196 criteria = 1;
197 break;
198 case 's':
199 makelist(&sidlist, LT_SID, optarg);
200 criteria = 1;
201 break;
202 case 't':
203 makelist(&tdevlist, LT_TTY, optarg);
204 criteria = 1;
205 break;
206 case 'u':
207 makelist(&euidlist, LT_USER, optarg);
208 criteria = 1;
209 break;
210 case 'v':
211 inverse = 1;
212 break;
213 case 'x':
214 fullmatch = 1;
215 break;
216 default:
217 usage();
218 /* NOTREACHED */
219 }
220
221 argc -= optind;
222 argv += optind;
223 if (argc != 0)
224 criteria = 1;
225 if (!criteria)
226 usage();
227
228 mypid = getpid();
229
230 /*
231 * Retrieve the list of running processes from the kernel.
232 */
233 kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, buf);
234 if (kd == NULL)
235 errx(STATUS_ERROR, "kvm_openfiles(): %s", buf);
236
237 plist = kvm_getproc2(kd, KERN_PROC_ALL, 0, sizeof(*plist), &nproc);
238 if (plist == NULL)
239 errx(STATUS_ERROR, "kvm_getproc2() failed");
240
241 /*
242 * Allocate memory which will be used to keep track of the
243 * selection.
244 */
245 if ((selected = malloc(nproc)) == NULL)
246 errx(STATUS_ERROR, "memory allocation failure");
247 memset(selected, 0, nproc);
248
249 /*
250 * Refine the selection.
251 */
252 for (; *argv != NULL; argv++) {
253 if ((rv = regcomp(®, *argv, cflags)) != 0) {
254 regerror(rv, ®, buf, sizeof(buf));
255 errx(STATUS_BADUSAGE, "bad expression: %s", buf);
256 }
257
258 for (i = 0, kp = plist; i < nproc; i++, kp++) {
259 if ((kp->p_flag & P_SYSTEM) != 0 || kp->p_pid == mypid)
260 continue;
261
262 if (matchargs) {
263 if ((pargv = kvm_getargv2(kd, kp, 0)) == NULL)
264 continue;
265
266 j = 0;
267 while (j < sizeof(buf) && *pargv != NULL) {
268 j += snprintf(buf + j, sizeof(buf) - j,
269 pargv[1] != NULL ? "%s " : "%s",
270 pargv[0]);
271 pargv++;
272 }
273
274 mstr = buf;
275 } else
276 mstr = kp->p_comm;
277
278 rv = regexec(®, mstr, 1, ®match, 0);
279 if (rv == 0) {
280 if (fullmatch) {
281 if (regmatch.rm_so == 0 &&
282 regmatch.rm_eo == strlen(mstr))
283 selected[i] = 1;
284 } else
285 selected[i] = 1;
286 } else if (rv != REG_NOMATCH) {
287 regerror(rv, ®, buf, sizeof(buf));
288 errx(STATUS_ERROR, "regexec(): %s", buf);
289 }
290 }
291
292 regfree(®);
293 }
294
295 for (i = 0, kp = plist; i < nproc; i++, kp++) {
296 if ((kp->p_flag & P_SYSTEM) != 0)
297 continue;
298
299 SLIST_FOREACH(li, &ruidlist, li_chain)
300 if (kp->p_ruid == (uid_t)li->li_number)
301 break;
302 if (SLIST_FIRST(&ruidlist) != NULL && li == NULL) {
303 selected[i] = 0;
304 continue;
305 }
306
307 SLIST_FOREACH(li, &rgidlist, li_chain)
308 if (kp->p_rgid == (gid_t)li->li_number)
309 break;
310 if (SLIST_FIRST(&rgidlist) != NULL && li == NULL) {
311 selected[i] = 0;
312 continue;
313 }
314
315 SLIST_FOREACH(li, &euidlist, li_chain)
316 if (kp->p_uid == (uid_t)li->li_number)
317 break;
318 if (SLIST_FIRST(&euidlist) != NULL && li == NULL) {
319 selected[i] = 0;
320 continue;
321 }
322
323 SLIST_FOREACH(li, &ppidlist, li_chain)
324 if (kp->p_ppid == (uid_t)li->li_number)
325 break;
326 if (SLIST_FIRST(&ppidlist) != NULL && li == NULL) {
327 selected[i] = 0;
328 continue;
329 }
330
331 SLIST_FOREACH(li, &pgrplist, li_chain)
332 if (kp->p__pgid == (uid_t)li->li_number)
333 break;
334 if (SLIST_FIRST(&pgrplist) != NULL && li == NULL) {
335 selected[i] = 0;
336 continue;
337 }
338
339 SLIST_FOREACH(li, &tdevlist, li_chain) {
340 if (li->li_number == -1 &&
341 (kp->p_flag & P_CONTROLT) == 0)
342 break;
343 if (kp->p_tdev == (uid_t)li->li_number)
344 break;
345 }
346 if (SLIST_FIRST(&tdevlist) != NULL && li == NULL) {
347 selected[i] = 0;
348 continue;
349 }
350
351 SLIST_FOREACH(li, &sidlist, li_chain)
352 if (kp->p_sid == (uid_t)li->li_number)
353 break;
354 if (SLIST_FIRST(&sidlist) != NULL && li == NULL) {
355 selected[i] = 0;
356 continue;
357 }
358
359 if (argc == 0)
360 selected[i] = 1;
361 }
362
363 if (newest) {
364 bestsec = 0;
365 bestusec = 0;
366 bestidx = -1;
367
368 for (i = 0, kp = plist; i < nproc; i++, kp++) {
369 if (!selected[i])
370 continue;
371
372 if (kp->p_ustart_sec > bestsec ||
373 (kp->p_ustart_sec == bestsec
374 && kp->p_ustart_usec > bestusec)) {
375 bestsec = kp->p_ustart_sec;
376 bestusec = kp->p_ustart_usec;
377 bestidx = i;
378 }
379 }
380
381 memset(selected, 0, nproc);
382 if (bestidx != -1)
383 selected[bestidx] = 1;
384 }
385
386 /*
387 * Take the appropriate action for each matched process, if any.
388 */
389 for (i = 0, rv = 0, kp = plist; i < nproc; i++, kp++) {
390 if (kp->p_pid == mypid)
391 continue;
392 if (selected[i]) {
393 if (inverse)
394 continue;
395 } else if (!inverse)
396 continue;
397
398 if ((kp->p_flag & P_SYSTEM) != 0)
399 continue;
400
401 rv |= (*action)(kp);
402 }
403
404 exit(rv ? STATUS_MATCH : STATUS_NOMATCH);
405 }
406
407 void
408 usage(void)
409 {
410 const char *ustr;
411
412 if (pgrep)
413 ustr = "[-filnvx] [-d delim]";
414 else
415 ustr = "[-signal] [-finvx]";
416
417 fprintf(stderr,
418 "usage: %s %s [-G gid] [-P ppid] [-U uid] [-g pgrp] [-s sid]\n"
419 " [-t tty] [-u euid] pattern ...\n", getprogname(),
420 ustr);
421
422 exit(STATUS_ERROR);
423 }
424
425 int
426 killact(struct kinfo_proc2 *kp)
427 {
428 if (kill(kp->p_pid, signum) == -1) {
429 if (errno == ESRCH)
430 /*
431 * The process disappeared between us matching
432 * it and us signalling it. Return 0 to
433 * indicate that the process should not be
434 * considered a match.
435 */
436 return 0;
437
438 err(STATUS_ERROR, "signalling pid %d", (int)kp->p_pid);
439 }
440
441 return 1;
442 }
443
444 int
445 grepact(struct kinfo_proc2 *kp)
446 {
447 char **argv;
448
449 if (longfmt && matchargs) {
450 if ((argv = kvm_getargv2(kd, kp, 0)) == NULL)
451 /*
452 * The process disappeared? Return 0 to
453 * indicate that the process should not be
454 * considered a match.
455 */
456 return 0;
457
458 printf("%d ", (int)kp->p_pid);
459 for (; *argv != NULL; argv++) {
460 printf("%s", *argv);
461 if (argv[1] != NULL)
462 putchar(' ');
463 }
464 } else if (longfmt)
465 printf("%d %s", (int)kp->p_pid, kp->p_comm);
466 else
467 printf("%d", (int)kp->p_pid);
468
469 printf("%s", delim);
470
471 return 1;
472 }
473
474 void
475 makelist(struct listhead *head, enum listtype type, char *src)
476 {
477 struct list *li;
478 struct passwd *pw;
479 struct group *gr;
480 struct stat st;
481 char *sp, *p, buf[MAXPATHLEN];
482 int empty;
483
484 empty = 1;
485
486 while ((sp = strsep(&src, ",")) != NULL) {
487 if (*sp == '\0')
488 usage();
489
490 if ((li = malloc(sizeof(*li))) == NULL)
491 errx(STATUS_ERROR, "memory allocation failure");
492 SLIST_INSERT_HEAD(head, li, li_chain);
493 empty = 0;
494
495 li->li_number = (uid_t)strtol(sp, &p, 0);
496 if (*p == '\0') {
497 switch (type) {
498 case LT_PGRP:
499 if (li->li_number == 0)
500 li->li_number = getpgrp();
501 break;
502 case LT_SID:
503 if (li->li_number == 0)
504 li->li_number = getsid(mypid);
505 break;
506 case LT_TTY:
507 usage();
508 default:
509 break;
510 }
511 continue;
512 }
513
514 switch (type) {
515 case LT_USER:
516 if ((pw = getpwnam(sp)) == NULL)
517 errx(STATUS_BADUSAGE, "unknown user `%s'",
518 sp);
519 li->li_number = pw->pw_uid;
520 break;
521 case LT_GROUP:
522 if ((gr = getgrnam(sp)) == NULL)
523 errx(STATUS_BADUSAGE, "unknown group `%s'",
524 sp);
525 li->li_number = gr->gr_gid;
526 break;
527 case LT_TTY:
528 if (strcmp(sp, "-") == 0) {
529 li->li_number = -1;
530 break;
531 } else if (strcmp(sp, "co") == 0)
532 p = "console";
533 else if (strncmp(sp, "tty", 3) == 0)
534 p = sp;
535 else
536 p = NULL;
537
538 if (p == NULL)
539 snprintf(buf, sizeof(buf), "/dev/tty%s", sp);
540 else
541 snprintf(buf, sizeof(buf), "/dev/%s", p);
542
543 if (stat(buf, &st) < 0) {
544 if (errno == ENOENT)
545 errx(STATUS_BADUSAGE,
546 "no such tty: `%s'", sp);
547 err(STATUS_ERROR, "stat(%s)", sp);
548 }
549
550 if ((st.st_mode & S_IFCHR) == 0)
551 errx(STATUS_BADUSAGE, "not a tty: `%s'", sp);
552
553 li->li_number = st.st_rdev;
554 break;
555 default:
556 usage();
557 };
558 }
559
560 if (empty)
561 usage();
562 }
563