xref: /freebsd/bin/pkill/pkill.c (revision 640235e2c2ba32947f7c59d168437ffa1280f1e6)
1 /*	$NetBSD: pkill.c,v 1.16 2005/10/10 22:13:20 kleink Exp $	*/
2 
3 /*-
4  * Copyright (c) 2002 The NetBSD Foundation, Inc.
5  * Copyright (c) 2005 Pawel Jakub Dawidek <pjd@FreeBSD.org>
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to The NetBSD Foundation
9  * by Andrew Doran.
10  *
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  *
20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35 
36 #include <sys/types.h>
37 #include <sys/param.h>
38 #include <sys/sysctl.h>
39 #include <sys/proc.h>
40 #include <sys/queue.h>
41 #include <sys/stat.h>
42 #include <sys/time.h>
43 #include <sys/user.h>
44 
45 #include <assert.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <limits.h>
49 #include <paths.h>
50 #include <string.h>
51 #include <unistd.h>
52 #include <signal.h>
53 #include <regex.h>
54 #include <ctype.h>
55 #include <fcntl.h>
56 #include <kvm.h>
57 #include <err.h>
58 #include <pwd.h>
59 #include <grp.h>
60 #include <errno.h>
61 #include <locale.h>
62 #include <jail.h>
63 
64 #define	STATUS_MATCH	0
65 #define	STATUS_NOMATCH	1
66 #define	STATUS_BADUSAGE	2
67 #define	STATUS_ERROR	3
68 
69 #define	MIN_PID	5
70 #define	MAX_PID	99999
71 
72 /* Ignore system-processes (if '-S' flag is not specified) and myself. */
73 #define	PSKIP(kp)	((kp)->ki_pid == mypid ||			\
74 			 (!kthreads && ((kp)->ki_flag & P_KPROC) != 0))
75 
76 enum listtype {
77 	LT_GENERIC,
78 	LT_USER,
79 	LT_GROUP,
80 	LT_TTY,
81 	LT_PGRP,
82 	LT_JAIL,
83 	LT_SID,
84 	LT_CLASS
85 };
86 
87 struct list {
88 	SLIST_ENTRY(list) li_chain;
89 	long	li_number;
90 	char	*li_name;
91 };
92 
93 SLIST_HEAD(listhead, list);
94 
95 static struct kinfo_proc *plist;
96 static char	*selected;
97 static const char *delim = "\n";
98 static int	nproc;
99 static int	pgrep;
100 static int	signum = SIGTERM;
101 static int	newest;
102 static int	oldest;
103 static int	interactive;
104 static int	inverse;
105 static int	longfmt;
106 static int	matchargs;
107 static int	fullmatch;
108 static int	kthreads;
109 static int	cflags = REG_EXTENDED;
110 static int	quiet;
111 static kvm_t	*kd;
112 static pid_t	mypid;
113 
114 static struct listhead euidlist = SLIST_HEAD_INITIALIZER(euidlist);
115 static struct listhead ruidlist = SLIST_HEAD_INITIALIZER(ruidlist);
116 static struct listhead rgidlist = SLIST_HEAD_INITIALIZER(rgidlist);
117 static struct listhead pgrplist = SLIST_HEAD_INITIALIZER(pgrplist);
118 static struct listhead ppidlist = SLIST_HEAD_INITIALIZER(ppidlist);
119 static struct listhead tdevlist = SLIST_HEAD_INITIALIZER(tdevlist);
120 static struct listhead sidlist = SLIST_HEAD_INITIALIZER(sidlist);
121 static struct listhead jidlist = SLIST_HEAD_INITIALIZER(jidlist);
122 static struct listhead classlist = SLIST_HEAD_INITIALIZER(classlist);
123 
124 static void	usage(void) __attribute__((__noreturn__));
125 static int	killact(const struct kinfo_proc *);
126 static int	grepact(const struct kinfo_proc *);
127 static void	makelist(struct listhead *, enum listtype, char *);
128 static int	takepid(const char *, int);
129 
130 int
131 main(int argc, char **argv)
132 {
133 	char buf[_POSIX2_LINE_MAX], *mstr, **pargv, *p, *q, *pidfile;
134 	const char *execf, *coref;
135 	int ancestors, debug_opt, did_action;
136 	int i, ch, bestidx, rv, criteria, pidfromfile, pidfilelock;
137 	size_t jsz;
138 	int (*action)(const struct kinfo_proc *);
139 	struct kinfo_proc *kp;
140 	struct list *li;
141 	struct timeval best_tval;
142 	regex_t reg;
143 	regmatch_t regmatch;
144 	pid_t pid;
145 
146 	setlocale(LC_ALL, "");
147 
148 	if (strcmp(getprogname(), "pgrep") == 0) {
149 		action = grepact;
150 		pgrep = 1;
151 	} else {
152 		action = killact;
153 		p = argv[1];
154 
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--;
172 				}
173 			}
174 		}
175 	}
176 
177 	ancestors = 0;
178 	criteria = 0;
179 	debug_opt = 0;
180 	pidfile = NULL;
181 	pidfilelock = 0;
182 	quiet = 0;
183 	execf = NULL;
184 	coref = _PATH_DEVNULL;
185 
186 	while ((ch = getopt(argc, argv, "DF:G:ILM:N:P:SU:ac:d:fg:ij:lnoqs:t:u:vx")) != -1)
187 		switch (ch) {
188 		case 'D':
189 			debug_opt++;
190 			break;
191 		case 'F':
192 			pidfile = optarg;
193 			criteria = 1;
194 			break;
195 		case 'G':
196 			makelist(&rgidlist, LT_GROUP, optarg);
197 			criteria = 1;
198 			break;
199 		case 'I':
200 			if (pgrep)
201 				usage();
202 			interactive = 1;
203 			break;
204 		case 'L':
205 			pidfilelock = 1;
206 			break;
207 		case 'M':
208 			coref = optarg;
209 			break;
210 		case 'N':
211 			execf = optarg;
212 			break;
213 		case 'P':
214 			makelist(&ppidlist, LT_GENERIC, optarg);
215 			criteria = 1;
216 			break;
217 		case 'S':
218 			if (!pgrep)
219 				usage();
220 			kthreads = 1;
221 			break;
222 		case 'U':
223 			makelist(&ruidlist, LT_USER, optarg);
224 			criteria = 1;
225 			break;
226 		case 'a':
227 			ancestors++;
228 			break;
229 		case 'c':
230 			makelist(&classlist, LT_CLASS, optarg);
231 			criteria = 1;
232 			break;
233 		case 'd':
234 			if (!pgrep)
235 				usage();
236 			delim = optarg;
237 			break;
238 		case 'f':
239 			matchargs = 1;
240 			break;
241 		case 'g':
242 			makelist(&pgrplist, LT_PGRP, optarg);
243 			criteria = 1;
244 			break;
245 		case 'i':
246 			cflags |= REG_ICASE;
247 			break;
248 		case 'j':
249 			makelist(&jidlist, LT_JAIL, optarg);
250 			criteria = 1;
251 			break;
252 		case 'l':
253 			longfmt = 1;
254 			break;
255 		case 'n':
256 			newest = 1;
257 			criteria = 1;
258 			break;
259 		case 'o':
260 			oldest = 1;
261 			criteria = 1;
262 			break;
263 		case 'q':
264 			if (!pgrep)
265 				usage();
266 			quiet = 1;
267 			break;
268 		case 's':
269 			makelist(&sidlist, LT_SID, optarg);
270 			criteria = 1;
271 			break;
272 		case 't':
273 			makelist(&tdevlist, LT_TTY, optarg);
274 			criteria = 1;
275 			break;
276 		case 'u':
277 			makelist(&euidlist, LT_USER, optarg);
278 			criteria = 1;
279 			break;
280 		case 'v':
281 			inverse = 1;
282 			break;
283 		case 'x':
284 			fullmatch = 1;
285 			break;
286 		default:
287 			usage();
288 			/* NOTREACHED */
289 		}
290 
291 	argc -= optind;
292 	argv += optind;
293 	if (argc != 0)
294 		criteria = 1;
295 	if (!criteria)
296 		usage();
297 	if (newest && oldest)
298 		errx(STATUS_ERROR, "Options -n and -o are mutually exclusive");
299 	if (pidfile != NULL)
300 		pidfromfile = takepid(pidfile, pidfilelock);
301 	else {
302 		if (pidfilelock) {
303 			errx(STATUS_ERROR,
304 			    "Option -L doesn't make sense without -F");
305 		}
306 		pidfromfile = -1;
307 	}
308 
309 	mypid = getpid();
310 
311 	/*
312 	 * Retrieve the list of running processes from the kernel.
313 	 */
314 	kd = kvm_openfiles(execf, coref, NULL, O_RDONLY, buf);
315 	if (kd == NULL)
316 		errx(STATUS_ERROR, "Cannot open kernel files (%s)", buf);
317 
318 	/*
319 	 * Use KERN_PROC_PROC instead of KERN_PROC_ALL, since we
320 	 * just want processes and not individual kernel threads.
321 	 */
322 	if (pidfromfile >= 0)
323 		plist = kvm_getprocs(kd, KERN_PROC_PID, pidfromfile, &nproc);
324 	else
325 		plist = kvm_getprocs(kd, KERN_PROC_PROC, 0, &nproc);
326 	if (plist == NULL) {
327 		errx(STATUS_ERROR, "Cannot get process list (%s)",
328 		    kvm_geterr(kd));
329 	}
330 
331 	/*
332 	 * Allocate memory which will be used to keep track of the
333 	 * selection.
334 	 */
335 	if ((selected = malloc(nproc)) == NULL) {
336 		err(STATUS_ERROR, "Cannot allocate memory for %d processes",
337 		    nproc);
338 	}
339 	memset(selected, 0, nproc);
340 
341 	/*
342 	 * Refine the selection.
343 	 */
344 	for (; *argv != NULL; argv++) {
345 		if ((rv = regcomp(&reg, *argv, cflags)) != 0) {
346 			regerror(rv, &reg, buf, sizeof(buf));
347 			errx(STATUS_BADUSAGE,
348 			    "Cannot compile regular expression `%s' (%s)",
349 			    *argv, buf);
350 		}
351 
352 		for (i = 0, kp = plist; i < nproc; i++, kp++) {
353 			if (PSKIP(kp)) {
354 				if (debug_opt > 0)
355 				    fprintf(stderr, "* Skipped %5d %3d %s\n",
356 					kp->ki_pid, kp->ki_uid, kp->ki_comm);
357 				continue;
358 			}
359 
360 			if (matchargs &&
361 			    (pargv = kvm_getargv(kd, kp, 0)) != NULL) {
362 				jsz = 0;
363 				while (jsz < sizeof(buf) && *pargv != NULL) {
364 					jsz += snprintf(buf + jsz,
365 					    sizeof(buf) - jsz,
366 					    pargv[1] != NULL ? "%s " : "%s",
367 					    pargv[0]);
368 					pargv++;
369 				}
370 				mstr = buf;
371 			} else
372 				mstr = kp->ki_comm;
373 
374 			rv = regexec(&reg, mstr, 1, &regmatch, 0);
375 			if (rv == 0) {
376 				if (fullmatch) {
377 					if (regmatch.rm_so == 0 &&
378 					    regmatch.rm_eo ==
379 					    (off_t)strlen(mstr))
380 						selected[i] = 1;
381 				} else
382 					selected[i] = 1;
383 			} else if (rv != REG_NOMATCH) {
384 				regerror(rv, &reg, buf, sizeof(buf));
385 				errx(STATUS_ERROR,
386 				    "Regular expression evaluation error (%s)",
387 				    buf);
388 			}
389 			if (debug_opt > 1) {
390 				const char *rv_res = "NoMatch";
391 				if (selected[i])
392 					rv_res = "Matched";
393 				fprintf(stderr, "* %s %5d %3d %s\n", rv_res,
394 				    kp->ki_pid, kp->ki_uid, mstr);
395 			}
396 		}
397 
398 		regfree(&reg);
399 	}
400 
401 	for (i = 0, kp = plist; i < nproc; i++, kp++) {
402 		if (PSKIP(kp))
403 			continue;
404 
405 		if (pidfromfile >= 0 && kp->ki_pid != pidfromfile) {
406 			selected[i] = 0;
407 			continue;
408 		}
409 
410 		SLIST_FOREACH(li, &ruidlist, li_chain)
411 			if (kp->ki_ruid == (uid_t)li->li_number)
412 				break;
413 		if (SLIST_FIRST(&ruidlist) != NULL && li == NULL) {
414 			selected[i] = 0;
415 			continue;
416 		}
417 
418 		SLIST_FOREACH(li, &rgidlist, li_chain)
419 			if (kp->ki_rgid == (gid_t)li->li_number)
420 				break;
421 		if (SLIST_FIRST(&rgidlist) != NULL && li == NULL) {
422 			selected[i] = 0;
423 			continue;
424 		}
425 
426 		SLIST_FOREACH(li, &euidlist, li_chain)
427 			if (kp->ki_uid == (uid_t)li->li_number)
428 				break;
429 		if (SLIST_FIRST(&euidlist) != NULL && li == NULL) {
430 			selected[i] = 0;
431 			continue;
432 		}
433 
434 		SLIST_FOREACH(li, &ppidlist, li_chain)
435 			if (kp->ki_ppid == (pid_t)li->li_number)
436 				break;
437 		if (SLIST_FIRST(&ppidlist) != NULL && li == NULL) {
438 			selected[i] = 0;
439 			continue;
440 		}
441 
442 		SLIST_FOREACH(li, &pgrplist, li_chain)
443 			if (kp->ki_pgid == (pid_t)li->li_number)
444 				break;
445 		if (SLIST_FIRST(&pgrplist) != NULL && li == NULL) {
446 			selected[i] = 0;
447 			continue;
448 		}
449 
450 		SLIST_FOREACH(li, &tdevlist, li_chain) {
451 			if (li->li_number == -1 &&
452 			    (kp->ki_flag & P_CONTROLT) == 0)
453 				break;
454 			if (kp->ki_tdev == (dev_t)li->li_number)
455 				break;
456 		}
457 		if (SLIST_FIRST(&tdevlist) != NULL && li == NULL) {
458 			selected[i] = 0;
459 			continue;
460 		}
461 
462 		SLIST_FOREACH(li, &sidlist, li_chain)
463 			if (kp->ki_sid == (pid_t)li->li_number)
464 				break;
465 		if (SLIST_FIRST(&sidlist) != NULL && li == NULL) {
466 			selected[i] = 0;
467 			continue;
468 		}
469 
470 		SLIST_FOREACH(li, &jidlist, li_chain) {
471 			/* A particular jail ID, including 0 (not in jail) */
472 			if (kp->ki_jid == (int)li->li_number)
473 				break;
474 			/* Any jail */
475 			if (kp->ki_jid > 0 && li->li_number == -1)
476 				break;
477 		}
478 		if (SLIST_FIRST(&jidlist) != NULL && li == NULL) {
479 			selected[i] = 0;
480 			continue;
481 		}
482 
483 		SLIST_FOREACH(li, &classlist, li_chain) {
484 			/*
485 			 * We skip P_SYSTEM processes to match ps(1) output.
486 			 */
487 			if ((kp->ki_flag & P_SYSTEM) == 0 &&
488 			    strcmp(kp->ki_loginclass, li->li_name) == 0)
489 				break;
490 		}
491 		if (SLIST_FIRST(&classlist) != NULL && li == NULL) {
492 			selected[i] = 0;
493 			continue;
494 		}
495 
496 		if (argc == 0)
497 			selected[i] = 1;
498 	}
499 
500 	if (!ancestors) {
501 		pid = mypid;
502 		while (pid) {
503 			for (i = 0, kp = plist; i < nproc; i++, kp++) {
504 				if (PSKIP(kp))
505 					continue;
506 				if (kp->ki_pid == pid) {
507 					selected[i] = 0;
508 					pid = kp->ki_ppid;
509 					break;
510 				}
511 			}
512 			if (i == nproc) {
513 				if (pid == mypid)
514 					pid = getppid();
515 				else
516 					break;	/* Maybe we're in a jail ? */
517 			}
518 		}
519 	}
520 
521 	if (newest || oldest) {
522 		best_tval.tv_sec = 0;
523 		best_tval.tv_usec = 0;
524 		bestidx = -1;
525 
526 		for (i = 0, kp = plist; i < nproc; i++, kp++) {
527 			if (!selected[i])
528 				continue;
529 			if (bestidx == -1) {
530 				/* The first entry of the list which matched. */
531 				;
532 			} else if (timercmp(&kp->ki_start, &best_tval, >)) {
533 				/* This entry is newer than previous "best". */
534 				if (oldest)	/* but we want the oldest */
535 					continue;
536 			} else {
537 				/* This entry is older than previous "best". */
538 				if (newest)	/* but we want the newest */
539 					continue;
540 			}
541 			/* This entry is better than previous "best" entry. */
542 			best_tval.tv_sec = kp->ki_start.tv_sec;
543 			best_tval.tv_usec = kp->ki_start.tv_usec;
544 			bestidx = i;
545 		}
546 
547 		memset(selected, 0, nproc);
548 		if (bestidx != -1)
549 			selected[bestidx] = 1;
550 	}
551 
552 	/*
553 	 * Take the appropriate action for each matched process, if any.
554 	 */
555 	did_action = 0;
556 	for (i = 0, rv = 0, kp = plist; i < nproc; i++, kp++) {
557 		if (PSKIP(kp))
558 			continue;
559 		if (selected[i]) {
560 			if (longfmt && !pgrep) {
561 				did_action = 1;
562 				printf("kill -%d %d\n", signum, kp->ki_pid);
563 			}
564 			if (inverse)
565 				continue;
566 		} else if (!inverse)
567 			continue;
568 		rv |= (*action)(kp);
569 	}
570 	if (!did_action && !pgrep && longfmt)
571 		fprintf(stderr,
572 		    "No matching processes belonging to you were found\n");
573 
574 	exit(rv ? STATUS_MATCH : STATUS_NOMATCH);
575 }
576 
577 static void
578 usage(void)
579 {
580 	const char *ustr;
581 
582 	if (pgrep)
583 		ustr = "[-LSfilnoqvx] [-d delim]";
584 	else
585 		ustr = "[-signal] [-ILfilnovx]";
586 
587 	fprintf(stderr,
588 		"usage: %s %s [-F pidfile] [-G gid] [-M core] [-N system]\n"
589 		"             [-P ppid] [-U uid] [-c class] [-g pgrp] [-j jail]\n"
590 		"             [-s sid] [-t tty] [-u euid] pattern ...\n",
591 		getprogname(), ustr);
592 
593 	exit(STATUS_BADUSAGE);
594 }
595 
596 static void
597 show_process(const struct kinfo_proc *kp)
598 {
599 	char **argv;
600 
601 	if (quiet) {
602 		assert(pgrep);
603 		return;
604 	}
605 	if ((longfmt || !pgrep) && matchargs &&
606 	    (argv = kvm_getargv(kd, kp, 0)) != NULL) {
607 		printf("%d ", (int)kp->ki_pid);
608 		for (; *argv != NULL; argv++) {
609 			printf("%s", *argv);
610 			if (argv[1] != NULL)
611 				putchar(' ');
612 		}
613 	} else if (longfmt || !pgrep)
614 		printf("%d %s", (int)kp->ki_pid, kp->ki_comm);
615 	else
616 		printf("%d", (int)kp->ki_pid);
617 }
618 
619 static int
620 killact(const struct kinfo_proc *kp)
621 {
622 	int ch, first;
623 
624 	if (interactive) {
625 		/*
626 		 * Be careful, ask before killing.
627 		 */
628 		printf("kill ");
629 		show_process(kp);
630 		printf("? ");
631 		fflush(stdout);
632 		first = ch = getchar();
633 		while (ch != '\n' && ch != EOF)
634 			ch = getchar();
635 		if (first != 'y' && first != 'Y')
636 			return (1);
637 	}
638 	if (kill(kp->ki_pid, signum) == -1) {
639 		/*
640 		 * Check for ESRCH, which indicates that the process
641 		 * disappeared between us matching it and us
642 		 * signalling it; don't issue a warning about it.
643 		 */
644 		if (errno != ESRCH)
645 			warn("signalling pid %d", (int)kp->ki_pid);
646 		/*
647 		 * Return 0 to indicate that the process should not be
648 		 * considered a match, since we didn't actually get to
649 		 * signal it.
650 		 */
651 		return (0);
652 	}
653 	return (1);
654 }
655 
656 static int
657 grepact(const struct kinfo_proc *kp)
658 {
659 
660 	show_process(kp);
661 	if (!quiet)
662 		printf("%s", delim);
663 	return (1);
664 }
665 
666 static void
667 makelist(struct listhead *head, enum listtype type, char *src)
668 {
669 	struct list *li;
670 	struct passwd *pw;
671 	struct group *gr;
672 	struct stat st;
673 	const char *cp;
674 	char *sp, *ep, buf[MAXPATHLEN];
675 	int empty;
676 
677 	empty = 1;
678 
679 	while ((sp = strsep(&src, ",")) != NULL) {
680 		if (*sp == '\0')
681 			usage();
682 
683 		if ((li = malloc(sizeof(*li))) == NULL) {
684 			err(STATUS_ERROR, "Cannot allocate %zu bytes",
685 			    sizeof(*li));
686 		}
687 
688 		SLIST_INSERT_HEAD(head, li, li_chain);
689 		empty = 0;
690 
691 		if (type != LT_CLASS)
692 			li->li_number = (uid_t)strtol(sp, &ep, 0);
693 
694 		if (type != LT_CLASS && *ep == '\0') {
695 			switch (type) {
696 			case LT_PGRP:
697 				if (li->li_number == 0)
698 					li->li_number = getpgrp();
699 				break;
700 			case LT_SID:
701 				if (li->li_number == 0)
702 					li->li_number = getsid(mypid);
703 				break;
704 			case LT_JAIL:
705 				if (li->li_number < 0)
706 					errx(STATUS_BADUSAGE,
707 					     "Negative jail ID `%s'", sp);
708 				/* For compatibility with old -j */
709 				if (li->li_number == 0)
710 					li->li_number = -1;	/* any jail */
711 				break;
712 			case LT_TTY:
713 				if (li->li_number < 0)
714 					errx(STATUS_BADUSAGE,
715 					     "Negative /dev/pts tty `%s'", sp);
716 				snprintf(buf, sizeof(buf), _PATH_DEV "pts/%s",
717 				    sp);
718 				if (stat(buf, &st) != -1)
719 					goto foundtty;
720 				if (errno == ENOENT)
721 					errx(STATUS_BADUSAGE, "No such tty: `"
722 					    _PATH_DEV "pts/%s'", sp);
723 				err(STATUS_ERROR, "Cannot access `"
724 				    _PATH_DEV "pts/%s'", sp);
725 				break;
726 			default:
727 				break;
728 			}
729 			continue;
730 		}
731 
732 		switch (type) {
733 		case LT_USER:
734 			if ((pw = getpwnam(sp)) == NULL)
735 				errx(STATUS_BADUSAGE, "Unknown user `%s'", sp);
736 			li->li_number = pw->pw_uid;
737 			break;
738 		case LT_GROUP:
739 			if ((gr = getgrnam(sp)) == NULL)
740 				errx(STATUS_BADUSAGE, "Unknown group `%s'", sp);
741 			li->li_number = gr->gr_gid;
742 			break;
743 		case LT_TTY:
744 			if (strcmp(sp, "-") == 0) {
745 				li->li_number = -1;
746 				break;
747 			} else if (strcmp(sp, "co") == 0) {
748 				cp = "console";
749 			} else {
750 				cp = sp;
751 			}
752 
753 			snprintf(buf, sizeof(buf), _PATH_DEV "%s", cp);
754 			if (stat(buf, &st) != -1)
755 				goto foundtty;
756 
757 			snprintf(buf, sizeof(buf), _PATH_DEV "tty%s", cp);
758 			if (stat(buf, &st) != -1)
759 				goto foundtty;
760 
761 			if (errno == ENOENT)
762 				errx(STATUS_BADUSAGE, "No such tty: `%s'", sp);
763 			err(STATUS_ERROR, "Cannot access `%s'", sp);
764 
765 foundtty:		if ((st.st_mode & S_IFCHR) == 0)
766 				errx(STATUS_BADUSAGE, "Not a tty: `%s'", sp);
767 
768 			li->li_number = st.st_rdev;
769 			break;
770 		case LT_JAIL: {
771 			int jid;
772 
773 			if (strcmp(sp, "none") == 0)
774 				li->li_number = 0;
775 			else if (strcmp(sp, "any") == 0)
776 				li->li_number = -1;
777 			else if ((jid = jail_getid(sp)) != -1)
778 				li->li_number = jid;
779 			else if (*ep != '\0')
780 				errx(STATUS_BADUSAGE,
781 				     "Invalid jail ID or name `%s'", sp);
782 			break;
783 		}
784 		case LT_CLASS:
785 			li->li_number = -1;
786 			li->li_name = strdup(sp);
787 			if (li->li_name == NULL)
788 				err(STATUS_ERROR, "Cannot allocate memory");
789 			break;
790 		default:
791 			usage();
792 		}
793 	}
794 
795 	if (empty)
796 		usage();
797 }
798 
799 static int
800 takepid(const char *pidfile, int pidfilelock)
801 {
802 	char *endp, line[BUFSIZ];
803 	FILE *fh;
804 	long rval;
805 
806 	fh = fopen(pidfile, "r");
807 	if (fh == NULL)
808 		err(STATUS_ERROR, "Cannot open pidfile `%s'", pidfile);
809 
810 	if (pidfilelock) {
811 		/*
812 		 * If we can lock pidfile, this means that daemon is not
813 		 * running, so would be better not to kill some random process.
814 		 */
815 		if (flock(fileno(fh), LOCK_EX | LOCK_NB) == 0) {
816 			(void)fclose(fh);
817 			errx(STATUS_ERROR, "File '%s' can be locked", pidfile);
818 		} else {
819 			if (errno != EWOULDBLOCK) {
820 				errx(STATUS_ERROR,
821 				    "Error while locking file '%s'", pidfile);
822 			}
823 		}
824 	}
825 
826 	if (fgets(line, sizeof(line), fh) == NULL) {
827 		if (feof(fh)) {
828 			(void)fclose(fh);
829 			errx(STATUS_ERROR, "Pidfile `%s' is empty", pidfile);
830 		}
831 		(void)fclose(fh);
832 		err(STATUS_ERROR, "Cannot read from pid file `%s'", pidfile);
833 	}
834 	(void)fclose(fh);
835 
836 	rval = strtol(line, &endp, 10);
837 	if (*endp != '\0' && !isspace((unsigned char)*endp))
838 		errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);
839 	else if (rval < MIN_PID || rval > MAX_PID)
840 		errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);
841 	return (rval);
842 }
843