New rldt() to go with lldt()
[freebsd-src/fkvm-freebsd.git] / bin / pkill / pkill.c
blob2547744a5489de4f908d03e69bff1756669691cf
1 /* $NetBSD: pkill.c,v 1.16 2005/10/10 22:13:20 kleink Exp $ */
3 /*-
4 * Copyright (c) 2002 The NetBSD Foundation, Inc.
5 * Copyright (c) 2005 Pawel Jakub Dawidek <pjd@FreeBSD.org>
6 * All rights reserved.
8 * This code is derived from software contributed to The NetBSD Foundation
9 * by Andrew Doran.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the NetBSD
22 * Foundation, Inc. and its contributors.
23 * 4. Neither the name of The NetBSD Foundation nor the names of its
24 * contributors may be used to endorse or promote products derived
25 * from this software without specific prior written permission.
27 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
28 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
29 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
30 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
31 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37 * POSSIBILITY OF SUCH DAMAGE.
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
43 #include <sys/types.h>
44 #include <sys/param.h>
45 #include <sys/sysctl.h>
46 #include <sys/proc.h>
47 #include <sys/queue.h>
48 #include <sys/stat.h>
49 #include <sys/time.h>
50 #include <sys/user.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <limits.h>
55 #include <paths.h>
56 #include <string.h>
57 #include <unistd.h>
58 #include <signal.h>
59 #include <regex.h>
60 #include <ctype.h>
61 #include <fcntl.h>
62 #include <kvm.h>
63 #include <err.h>
64 #include <pwd.h>
65 #include <grp.h>
66 #include <errno.h>
67 #include <locale.h>
69 #define STATUS_MATCH 0
70 #define STATUS_NOMATCH 1
71 #define STATUS_BADUSAGE 2
72 #define STATUS_ERROR 3
74 #define MIN_PID 5
75 #define MAX_PID 99999
77 /* Ignore system-processes (if '-S' flag is not specified) and myself. */
78 #define PSKIP(kp) ((kp)->ki_pid == mypid || \
79 (!kthreads && ((kp)->ki_flag & P_KTHREAD) != 0))
81 enum listtype {
82 LT_GENERIC,
83 LT_USER,
84 LT_GROUP,
85 LT_TTY,
86 LT_PGRP,
87 LT_JID,
88 LT_SID
91 struct list {
92 SLIST_ENTRY(list) li_chain;
93 long li_number;
96 SLIST_HEAD(listhead, list);
98 static struct kinfo_proc *plist;
99 static char *selected;
100 static const char *delim = "\n";
101 static int nproc;
102 static int pgrep;
103 static int signum = SIGTERM;
104 static int newest;
105 static int oldest;
106 static int interactive;
107 static int inverse;
108 static int longfmt;
109 static int matchargs;
110 static int fullmatch;
111 static int kthreads;
112 static int cflags = REG_EXTENDED;
113 static kvm_t *kd;
114 static pid_t mypid;
116 static struct listhead euidlist = SLIST_HEAD_INITIALIZER(list);
117 static struct listhead ruidlist = SLIST_HEAD_INITIALIZER(list);
118 static struct listhead rgidlist = SLIST_HEAD_INITIALIZER(list);
119 static struct listhead pgrplist = SLIST_HEAD_INITIALIZER(list);
120 static struct listhead ppidlist = SLIST_HEAD_INITIALIZER(list);
121 static struct listhead tdevlist = SLIST_HEAD_INITIALIZER(list);
122 static struct listhead sidlist = SLIST_HEAD_INITIALIZER(list);
123 static struct listhead jidlist = SLIST_HEAD_INITIALIZER(list);
125 static void usage(void) __attribute__((__noreturn__));
126 static int killact(const struct kinfo_proc *);
127 static int grepact(const struct kinfo_proc *);
128 static void makelist(struct listhead *, enum listtype, char *);
129 static int takepid(const char *, int);
132 main(int argc, char **argv)
134 char buf[_POSIX2_LINE_MAX], *mstr, **pargv, *p, *q, *pidfile;
135 const char *execf, *coref;
136 int debug_opt;
137 int i, ch, bestidx, rv, criteria, pidfromfile, pidfilelock;
138 size_t jsz;
139 int (*action)(const struct kinfo_proc *);
140 struct kinfo_proc *kp;
141 struct list *li;
142 struct timeval best_tval;
143 regex_t reg;
144 regmatch_t regmatch;
146 setlocale(LC_ALL, "");
148 if (strcmp(getprogname(), "pgrep") == 0) {
149 action = grepact;
150 pgrep = 1;
151 } else {
152 action = killact;
153 p = argv[1];
155 if (argc > 1 && p[0] == '-') {
156 p++;
157 i = (int)strtol(p, &q, 10);
158 if (*q == '\0') {
159 signum = i;
160 argv++;
161 argc--;
162 } else {
163 if (strncasecmp(p, "sig", 3) == 0)
164 p += 3;
165 for (i = 1; i < NSIG; i++)
166 if (strcasecmp(sys_signame[i], p) == 0)
167 break;
168 if (i != NSIG) {
169 signum = i;
170 argv++;
171 argc--;
177 criteria = 0;
178 debug_opt = 0;
179 pidfile = NULL;
180 pidfilelock = 0;
181 execf = coref = _PATH_DEVNULL;
183 while ((ch = getopt(argc, argv, "DF:G:ILM:N:P:SU:d:fg:ij:lnos:t:u:vx")) != -1)
184 switch (ch) {
185 case 'D':
186 debug_opt++;
187 break;
188 case 'F':
189 pidfile = optarg;
190 criteria = 1;
191 break;
192 case 'G':
193 makelist(&rgidlist, LT_GROUP, optarg);
194 criteria = 1;
195 break;
196 case 'I':
197 if (pgrep)
198 usage();
199 interactive = 1;
200 break;
201 case 'L':
202 pidfilelock = 1;
203 break;
204 case 'M':
205 coref = optarg;
206 break;
207 case 'N':
208 execf = optarg;
209 break;
210 case 'P':
211 makelist(&ppidlist, LT_GENERIC, optarg);
212 criteria = 1;
213 break;
214 case 'S':
215 if (!pgrep)
216 usage();
217 kthreads = 1;
218 break;
219 case 'U':
220 makelist(&ruidlist, LT_USER, optarg);
221 criteria = 1;
222 break;
223 case 'd':
224 if (!pgrep)
225 usage();
226 delim = optarg;
227 break;
228 case 'f':
229 matchargs = 1;
230 break;
231 case 'g':
232 makelist(&pgrplist, LT_PGRP, optarg);
233 criteria = 1;
234 break;
235 case 'i':
236 cflags |= REG_ICASE;
237 break;
238 case 'j':
239 makelist(&jidlist, LT_JID, optarg);
240 criteria = 1;
241 break;
242 case 'l':
243 if (!pgrep)
244 usage();
245 longfmt = 1;
246 break;
247 case 'n':
248 newest = 1;
249 criteria = 1;
250 break;
251 case 'o':
252 oldest = 1;
253 criteria = 1;
254 break;
255 case 's':
256 makelist(&sidlist, LT_SID, optarg);
257 criteria = 1;
258 break;
259 case 't':
260 makelist(&tdevlist, LT_TTY, optarg);
261 criteria = 1;
262 break;
263 case 'u':
264 makelist(&euidlist, LT_USER, optarg);
265 criteria = 1;
266 break;
267 case 'v':
268 inverse = 1;
269 break;
270 case 'x':
271 fullmatch = 1;
272 break;
273 default:
274 usage();
275 /* NOTREACHED */
278 argc -= optind;
279 argv += optind;
280 if (argc != 0)
281 criteria = 1;
282 if (!criteria)
283 usage();
284 if (newest && oldest)
285 errx(STATUS_ERROR, "Options -n and -o are mutually exclusive");
286 if (pidfile != NULL)
287 pidfromfile = takepid(pidfile, pidfilelock);
288 else {
289 if (pidfilelock) {
290 errx(STATUS_ERROR,
291 "Option -L doesn't make sense without -F");
293 pidfromfile = -1;
296 mypid = getpid();
299 * Retrieve the list of running processes from the kernel.
301 kd = kvm_openfiles(execf, coref, NULL, O_RDONLY, buf);
302 if (kd == NULL)
303 errx(STATUS_ERROR, "Cannot open kernel files (%s)", buf);
306 * Use KERN_PROC_PROC instead of KERN_PROC_ALL, since we
307 * just want processes and not individual kernel threads.
309 plist = kvm_getprocs(kd, KERN_PROC_PROC, 0, &nproc);
310 if (plist == NULL) {
311 errx(STATUS_ERROR, "Cannot get process list (%s)",
312 kvm_geterr(kd));
316 * Allocate memory which will be used to keep track of the
317 * selection.
319 if ((selected = malloc(nproc)) == NULL) {
320 err(STATUS_ERROR, "Cannot allocate memory for %d processes",
321 nproc);
323 memset(selected, 0, nproc);
326 * Refine the selection.
328 for (; *argv != NULL; argv++) {
329 if ((rv = regcomp(&reg, *argv, cflags)) != 0) {
330 regerror(rv, &reg, buf, sizeof(buf));
331 errx(STATUS_BADUSAGE,
332 "Cannot compile regular expression `%s' (%s)",
333 *argv, buf);
336 for (i = 0, kp = plist; i < nproc; i++, kp++) {
337 if (PSKIP(kp)) {
338 if (debug_opt > 0)
339 fprintf(stderr, "* Skipped %5d %3d %s\n",
340 kp->ki_pid, kp->ki_uid, kp->ki_comm);
341 continue;
344 if (matchargs &&
345 (pargv = kvm_getargv(kd, kp, 0)) != NULL) {
346 jsz = 0;
347 while (jsz < sizeof(buf) && *pargv != NULL) {
348 jsz += snprintf(buf + jsz,
349 sizeof(buf) - jsz,
350 pargv[1] != NULL ? "%s " : "%s",
351 pargv[0]);
352 pargv++;
354 mstr = buf;
355 } else
356 mstr = kp->ki_comm;
358 rv = regexec(&reg, mstr, 1, &regmatch, 0);
359 if (rv == 0) {
360 if (fullmatch) {
361 if (regmatch.rm_so == 0 &&
362 regmatch.rm_eo ==
363 (off_t)strlen(mstr))
364 selected[i] = 1;
365 } else
366 selected[i] = 1;
367 } else if (rv != REG_NOMATCH) {
368 regerror(rv, &reg, buf, sizeof(buf));
369 errx(STATUS_ERROR,
370 "Regular expression evaluation error (%s)",
371 buf);
373 if (debug_opt > 1) {
374 const char *rv_res = "NoMatch";
375 if (selected[i])
376 rv_res = "Matched";
377 fprintf(stderr, "* %s %5d %3d %s\n", rv_res,
378 kp->ki_pid, kp->ki_uid, mstr);
382 regfree(&reg);
385 for (i = 0, kp = plist; i < nproc; i++, kp++) {
386 if (PSKIP(kp))
387 continue;
389 if (pidfromfile >= 0 && kp->ki_pid != pidfromfile) {
390 selected[i] = 0;
391 continue;
394 SLIST_FOREACH(li, &ruidlist, li_chain)
395 if (kp->ki_ruid == (uid_t)li->li_number)
396 break;
397 if (SLIST_FIRST(&ruidlist) != NULL && li == NULL) {
398 selected[i] = 0;
399 continue;
402 SLIST_FOREACH(li, &rgidlist, li_chain)
403 if (kp->ki_rgid == (gid_t)li->li_number)
404 break;
405 if (SLIST_FIRST(&rgidlist) != NULL && li == NULL) {
406 selected[i] = 0;
407 continue;
410 SLIST_FOREACH(li, &euidlist, li_chain)
411 if (kp->ki_uid == (uid_t)li->li_number)
412 break;
413 if (SLIST_FIRST(&euidlist) != NULL && li == NULL) {
414 selected[i] = 0;
415 continue;
418 SLIST_FOREACH(li, &ppidlist, li_chain)
419 if (kp->ki_ppid == (pid_t)li->li_number)
420 break;
421 if (SLIST_FIRST(&ppidlist) != NULL && li == NULL) {
422 selected[i] = 0;
423 continue;
426 SLIST_FOREACH(li, &pgrplist, li_chain)
427 if (kp->ki_pgid == (pid_t)li->li_number)
428 break;
429 if (SLIST_FIRST(&pgrplist) != NULL && li == NULL) {
430 selected[i] = 0;
431 continue;
434 SLIST_FOREACH(li, &tdevlist, li_chain) {
435 if (li->li_number == -1 &&
436 (kp->ki_flag & P_CONTROLT) == 0)
437 break;
438 if (kp->ki_tdev == (dev_t)li->li_number)
439 break;
441 if (SLIST_FIRST(&tdevlist) != NULL && li == NULL) {
442 selected[i] = 0;
443 continue;
446 SLIST_FOREACH(li, &sidlist, li_chain)
447 if (kp->ki_sid == (pid_t)li->li_number)
448 break;
449 if (SLIST_FIRST(&sidlist) != NULL && li == NULL) {
450 selected[i] = 0;
451 continue;
454 SLIST_FOREACH(li, &jidlist, li_chain) {
455 /* A particular jail ID, including 0 (not in jail) */
456 if (kp->ki_jid == (int)li->li_number)
457 break;
458 /* Any jail */
459 if (kp->ki_jid > 0 && li->li_number == -1)
460 break;
462 if (SLIST_FIRST(&jidlist) != NULL && li == NULL) {
463 selected[i] = 0;
464 continue;
467 if (argc == 0)
468 selected[i] = 1;
471 if (newest || oldest) {
472 best_tval.tv_sec = 0;
473 best_tval.tv_usec = 0;
474 bestidx = -1;
476 for (i = 0, kp = plist; i < nproc; i++, kp++) {
477 if (!selected[i])
478 continue;
479 if (bestidx == -1) {
480 /* The first entry of the list which matched. */
482 } else if (timercmp(&kp->ki_start, &best_tval, >)) {
483 /* This entry is newer than previous "best". */
484 if (oldest) /* but we want the oldest */
485 continue;
486 } else {
487 /* This entry is older than previous "best". */
488 if (newest) /* but we want the newest */
489 continue;
491 /* This entry is better than previous "best" entry. */
492 best_tval.tv_sec = kp->ki_start.tv_sec;
493 best_tval.tv_usec = kp->ki_start.tv_usec;
494 bestidx = i;
497 memset(selected, 0, nproc);
498 if (bestidx != -1)
499 selected[bestidx] = 1;
503 * Take the appropriate action for each matched process, if any.
505 for (i = 0, rv = 0, kp = plist; i < nproc; i++, kp++) {
506 if (PSKIP(kp))
507 continue;
508 if (selected[i]) {
509 if (inverse)
510 continue;
511 } else if (!inverse)
512 continue;
513 rv |= (*action)(kp);
516 exit(rv ? STATUS_MATCH : STATUS_NOMATCH);
519 static void
520 usage(void)
522 const char *ustr;
524 if (pgrep)
525 ustr = "[-LSfilnovx] [-d delim]";
526 else
527 ustr = "[-signal] [-ILfinovx]";
529 fprintf(stderr,
530 "usage: %s %s [-F pidfile] [-G gid] [-M core] [-N system]\n"
531 " [-P ppid] [-U uid] [-g pgrp] [-j jid] [-s sid]\n"
532 " [-t tty] [-u euid] pattern ...\n", getprogname(),
533 ustr);
535 exit(STATUS_BADUSAGE);
538 static void
539 show_process(const struct kinfo_proc *kp)
541 char **argv;
543 if ((longfmt || !pgrep) && matchargs &&
544 (argv = kvm_getargv(kd, kp, 0)) != NULL) {
545 printf("%d ", (int)kp->ki_pid);
546 for (; *argv != NULL; argv++) {
547 printf("%s", *argv);
548 if (argv[1] != NULL)
549 putchar(' ');
551 } else if (longfmt || !pgrep)
552 printf("%d %s", (int)kp->ki_pid, kp->ki_comm);
553 else
554 printf("%d", (int)kp->ki_pid);
557 static int
558 killact(const struct kinfo_proc *kp)
560 int ch, first;
562 if (interactive) {
564 * Be careful, ask before killing.
566 printf("kill ");
567 show_process(kp);
568 printf("? ");
569 fflush(stdout);
570 first = ch = getchar();
571 while (ch != '\n' && ch != EOF)
572 ch = getchar();
573 if (first != 'y' && first != 'Y')
574 return (1);
576 if (kill(kp->ki_pid, signum) == -1) {
578 * Check for ESRCH, which indicates that the process
579 * disappeared between us matching it and us
580 * signalling it; don't issue a warning about it.
582 if (errno != ESRCH)
583 warn("signalling pid %d", (int)kp->ki_pid);
585 * Return 0 to indicate that the process should not be
586 * considered a match, since we didn't actually get to
587 * signal it.
589 return (0);
591 return (1);
594 static int
595 grepact(const struct kinfo_proc *kp)
598 show_process(kp);
599 printf("%s", delim);
600 return (1);
603 static void
604 makelist(struct listhead *head, enum listtype type, char *src)
606 struct list *li;
607 struct passwd *pw;
608 struct group *gr;
609 struct stat st;
610 const char *cp, *prefix;
611 char *sp, *ep, buf[MAXPATHLEN];
612 int empty;
614 empty = 1;
615 prefix = _PATH_DEV;
617 while ((sp = strsep(&src, ",")) != NULL) {
618 if (*sp == '\0')
619 usage();
621 if ((li = malloc(sizeof(*li))) == NULL) {
622 err(STATUS_ERROR, "Cannot allocate %zu bytes",
623 sizeof(*li));
626 SLIST_INSERT_HEAD(head, li, li_chain);
627 empty = 0;
629 li->li_number = (uid_t)strtol(sp, &ep, 0);
630 if (*ep == '\0') {
631 switch (type) {
632 case LT_PGRP:
633 if (li->li_number == 0)
634 li->li_number = getpgrp();
635 break;
636 case LT_SID:
637 if (li->li_number == 0)
638 li->li_number = getsid(mypid);
639 break;
640 case LT_JID:
641 if (li->li_number < 0)
642 errx(STATUS_BADUSAGE,
643 "Negative jail ID `%s'", sp);
644 /* For compatibility with old -j */
645 if (li->li_number == 0)
646 li->li_number = -1; /* any jail */
647 break;
648 case LT_TTY:
649 usage();
650 /* NOTREACHED */
651 default:
652 break;
654 continue;
657 switch (type) {
658 case LT_USER:
659 if ((pw = getpwnam(sp)) == NULL)
660 errx(STATUS_BADUSAGE, "Unknown user `%s'", sp);
661 li->li_number = pw->pw_uid;
662 break;
663 case LT_GROUP:
664 if ((gr = getgrnam(sp)) == NULL)
665 errx(STATUS_BADUSAGE, "Unknown group `%s'", sp);
666 li->li_number = gr->gr_gid;
667 break;
668 case LT_TTY:
669 if (strcmp(sp, "-") == 0) {
670 li->li_number = -1;
671 break;
672 } else if (strcmp(sp, "co") == 0) {
673 cp = "console";
674 } else {
675 cp = sp;
676 if (strncmp(sp, "tty", 3) != 0)
677 prefix = _PATH_TTY;
680 snprintf(buf, sizeof(buf), "%s%s", prefix, cp);
682 if (stat(buf, &st) == -1) {
683 if (errno == ENOENT) {
684 errx(STATUS_BADUSAGE,
685 "No such tty: `%s'", sp);
687 err(STATUS_ERROR, "Cannot access `%s'", sp);
690 if ((st.st_mode & S_IFCHR) == 0)
691 errx(STATUS_BADUSAGE, "Not a tty: `%s'", sp);
693 li->li_number = st.st_rdev;
694 break;
695 case LT_JID:
696 if (strcmp(sp, "none") == 0)
697 li->li_number = 0;
698 else if (strcmp(sp, "any") == 0)
699 li->li_number = -1;
700 else if (*ep != '\0')
701 errx(STATUS_BADUSAGE,
702 "Invalid jail ID `%s'", sp);
703 break;
704 default:
705 usage();
709 if (empty)
710 usage();
713 static int
714 takepid(const char *pidfile, int pidfilelock)
716 char *endp, line[BUFSIZ];
717 FILE *fh;
718 long rval;
720 fh = fopen(pidfile, "r");
721 if (fh == NULL)
722 err(STATUS_ERROR, "Cannot open pidfile `%s'", pidfile);
724 if (pidfilelock) {
726 * If we can lock pidfile, this means that daemon is not
727 * running, so would be better not to kill some random process.
729 if (flock(fileno(fh), LOCK_EX | LOCK_NB) == 0) {
730 (void)fclose(fh);
731 errx(STATUS_ERROR, "File '%s' can be locked", pidfile);
732 } else {
733 if (errno != EWOULDBLOCK) {
734 errx(STATUS_ERROR,
735 "Error while locking file '%s'", pidfile);
740 if (fgets(line, sizeof(line), fh) == NULL) {
741 if (feof(fh)) {
742 (void)fclose(fh);
743 errx(STATUS_ERROR, "Pidfile `%s' is empty", pidfile);
745 (void)fclose(fh);
746 err(STATUS_ERROR, "Cannot read from pid file `%s'", pidfile);
748 (void)fclose(fh);
750 rval = strtol(line, &endp, 10);
751 if (*endp != '\0' && !isspace((unsigned char)*endp))
752 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);
753 else if (rval < MIN_PID || rval > MAX_PID)
754 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);
755 return (rval);