pkill.c revision 287269
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: stable/10/bin/pkill/pkill.c 287269 2015-08-29 02:41:59Z jamie $");
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_KTHREAD) != 0))
75
76enum 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
87struct list {
88	SLIST_ENTRY(list) li_chain;
89	long	li_number;
90	char	*li_name;
91};
92
93SLIST_HEAD(listhead, list);
94
95static struct kinfo_proc *plist;
96static char	*selected;
97static const char *delim = "\n";
98static int	nproc;
99static int	pgrep;
100static int	signum = SIGTERM;
101static int	newest;
102static int	oldest;
103static int	interactive;
104static int	inverse;
105static int	longfmt;
106static int	matchargs;
107static int	fullmatch;
108static int	kthreads;
109static int	cflags = REG_EXTENDED;
110static int	quiet;
111static kvm_t	*kd;
112static pid_t	mypid;
113
114static struct listhead euidlist = SLIST_HEAD_INITIALIZER(euidlist);
115static struct listhead ruidlist = SLIST_HEAD_INITIALIZER(ruidlist);
116static struct listhead rgidlist = SLIST_HEAD_INITIALIZER(rgidlist);
117static struct listhead pgrplist = SLIST_HEAD_INITIALIZER(pgrplist);
118static struct listhead ppidlist = SLIST_HEAD_INITIALIZER(ppidlist);
119static struct listhead tdevlist = SLIST_HEAD_INITIALIZER(tdevlist);
120static struct listhead sidlist = SLIST_HEAD_INITIALIZER(sidlist);
121static struct listhead jidlist = SLIST_HEAD_INITIALIZER(jidlist);
122static struct listhead classlist = SLIST_HEAD_INITIALIZER(classlist);
123
124static void	usage(void) __attribute__((__noreturn__));
125static int	killact(const struct kinfo_proc *);
126static int	grepact(const struct kinfo_proc *);
127static void	makelist(struct listhead *, enum listtype, char *);
128static int	takepid(const char *, int);
129
130int
131main(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	plist = kvm_getprocs(kd, KERN_PROC_PROC, 0, &nproc);
323	if (plist == NULL) {
324		errx(STATUS_ERROR, "Cannot get process list (%s)",
325		    kvm_geterr(kd));
326	}
327
328	/*
329	 * Allocate memory which will be used to keep track of the
330	 * selection.
331	 */
332	if ((selected = malloc(nproc)) == NULL) {
333		err(STATUS_ERROR, "Cannot allocate memory for %d processes",
334		    nproc);
335	}
336	memset(selected, 0, nproc);
337
338	/*
339	 * Refine the selection.
340	 */
341	for (; *argv != NULL; argv++) {
342		if ((rv = regcomp(&reg, *argv, cflags)) != 0) {
343			regerror(rv, &reg, buf, sizeof(buf));
344			errx(STATUS_BADUSAGE,
345			    "Cannot compile regular expression `%s' (%s)",
346			    *argv, buf);
347		}
348
349		for (i = 0, kp = plist; i < nproc; i++, kp++) {
350			if (PSKIP(kp)) {
351				if (debug_opt > 0)
352				    fprintf(stderr, "* Skipped %5d %3d %s\n",
353					kp->ki_pid, kp->ki_uid, kp->ki_comm);
354				continue;
355			}
356
357			if (matchargs &&
358			    (pargv = kvm_getargv(kd, kp, 0)) != NULL) {
359				jsz = 0;
360				while (jsz < sizeof(buf) && *pargv != NULL) {
361					jsz += snprintf(buf + jsz,
362					    sizeof(buf) - jsz,
363					    pargv[1] != NULL ? "%s " : "%s",
364					    pargv[0]);
365					pargv++;
366				}
367				mstr = buf;
368			} else
369				mstr = kp->ki_comm;
370
371			rv = regexec(&reg, mstr, 1, &regmatch, 0);
372			if (rv == 0) {
373				if (fullmatch) {
374					if (regmatch.rm_so == 0 &&
375					    regmatch.rm_eo ==
376					    (off_t)strlen(mstr))
377						selected[i] = 1;
378				} else
379					selected[i] = 1;
380			} else if (rv != REG_NOMATCH) {
381				regerror(rv, &reg, buf, sizeof(buf));
382				errx(STATUS_ERROR,
383				    "Regular expression evaluation error (%s)",
384				    buf);
385			}
386			if (debug_opt > 1) {
387				const char *rv_res = "NoMatch";
388				if (selected[i])
389					rv_res = "Matched";
390				fprintf(stderr, "* %s %5d %3d %s\n", rv_res,
391				    kp->ki_pid, kp->ki_uid, mstr);
392			}
393		}
394
395		regfree(&reg);
396	}
397
398	for (i = 0, kp = plist; i < nproc; i++, kp++) {
399		if (PSKIP(kp))
400			continue;
401
402		if (pidfromfile >= 0 && kp->ki_pid != pidfromfile) {
403			selected[i] = 0;
404			continue;
405		}
406
407		SLIST_FOREACH(li, &ruidlist, li_chain)
408			if (kp->ki_ruid == (uid_t)li->li_number)
409				break;
410		if (SLIST_FIRST(&ruidlist) != NULL && li == NULL) {
411			selected[i] = 0;
412			continue;
413		}
414
415		SLIST_FOREACH(li, &rgidlist, li_chain)
416			if (kp->ki_rgid == (gid_t)li->li_number)
417				break;
418		if (SLIST_FIRST(&rgidlist) != NULL && li == NULL) {
419			selected[i] = 0;
420			continue;
421		}
422
423		SLIST_FOREACH(li, &euidlist, li_chain)
424			if (kp->ki_uid == (uid_t)li->li_number)
425				break;
426		if (SLIST_FIRST(&euidlist) != NULL && li == NULL) {
427			selected[i] = 0;
428			continue;
429		}
430
431		SLIST_FOREACH(li, &ppidlist, li_chain)
432			if (kp->ki_ppid == (pid_t)li->li_number)
433				break;
434		if (SLIST_FIRST(&ppidlist) != NULL && li == NULL) {
435			selected[i] = 0;
436			continue;
437		}
438
439		SLIST_FOREACH(li, &pgrplist, li_chain)
440			if (kp->ki_pgid == (pid_t)li->li_number)
441				break;
442		if (SLIST_FIRST(&pgrplist) != NULL && li == NULL) {
443			selected[i] = 0;
444			continue;
445		}
446
447		SLIST_FOREACH(li, &tdevlist, li_chain) {
448			if (li->li_number == -1 &&
449			    (kp->ki_flag & P_CONTROLT) == 0)
450				break;
451			if (kp->ki_tdev == (dev_t)li->li_number)
452				break;
453		}
454		if (SLIST_FIRST(&tdevlist) != NULL && li == NULL) {
455			selected[i] = 0;
456			continue;
457		}
458
459		SLIST_FOREACH(li, &sidlist, li_chain)
460			if (kp->ki_sid == (pid_t)li->li_number)
461				break;
462		if (SLIST_FIRST(&sidlist) != NULL && li == NULL) {
463			selected[i] = 0;
464			continue;
465		}
466
467		SLIST_FOREACH(li, &jidlist, li_chain) {
468			/* A particular jail ID, including 0 (not in jail) */
469			if (kp->ki_jid == (int)li->li_number)
470				break;
471			/* Any jail */
472			if (kp->ki_jid > 0 && li->li_number == -1)
473				break;
474		}
475		if (SLIST_FIRST(&jidlist) != NULL && li == NULL) {
476			selected[i] = 0;
477			continue;
478		}
479
480		SLIST_FOREACH(li, &classlist, li_chain) {
481			/*
482			 * We skip P_SYSTEM processes to match ps(1) output.
483			 */
484			if ((kp->ki_flag & P_SYSTEM) == 0 &&
485			    strcmp(kp->ki_loginclass, li->li_name) == 0)
486				break;
487		}
488		if (SLIST_FIRST(&classlist) != NULL && li == NULL) {
489			selected[i] = 0;
490			continue;
491		}
492
493		if (argc == 0)
494			selected[i] = 1;
495	}
496
497	if (!ancestors) {
498		pid = mypid;
499		while (pid) {
500			for (i = 0, kp = plist; i < nproc; i++, kp++) {
501				if (PSKIP(kp))
502					continue;
503				if (kp->ki_pid == pid) {
504					selected[i] = 0;
505					pid = kp->ki_ppid;
506					break;
507				}
508			}
509			if (i == nproc) {
510				if (pid == mypid)
511					pid = getppid();
512				else
513					break;	/* Maybe we're in a jail ? */
514			}
515		}
516	}
517
518	if (newest || oldest) {
519		best_tval.tv_sec = 0;
520		best_tval.tv_usec = 0;
521		bestidx = -1;
522
523		for (i = 0, kp = plist; i < nproc; i++, kp++) {
524			if (!selected[i])
525				continue;
526			if (bestidx == -1) {
527				/* The first entry of the list which matched. */
528				;
529			} else if (timercmp(&kp->ki_start, &best_tval, >)) {
530				/* This entry is newer than previous "best". */
531				if (oldest)	/* but we want the oldest */
532					continue;
533			} else {
534				/* This entry is older than previous "best". */
535				if (newest)	/* but we want the newest */
536					continue;
537			}
538			/* This entry is better than previous "best" entry. */
539			best_tval.tv_sec = kp->ki_start.tv_sec;
540			best_tval.tv_usec = kp->ki_start.tv_usec;
541			bestidx = i;
542		}
543
544		memset(selected, 0, nproc);
545		if (bestidx != -1)
546			selected[bestidx] = 1;
547	}
548
549	/*
550	 * Take the appropriate action for each matched process, if any.
551	 */
552	did_action = 0;
553	for (i = 0, rv = 0, kp = plist; i < nproc; i++, kp++) {
554		if (PSKIP(kp))
555			continue;
556		if (selected[i]) {
557			if (longfmt && !pgrep) {
558				did_action = 1;
559				printf("kill -%d %d\n", signum, kp->ki_pid);
560			}
561			if (inverse)
562				continue;
563		} else if (!inverse)
564			continue;
565		rv |= (*action)(kp);
566	}
567	if (!did_action && !pgrep && longfmt)
568		fprintf(stderr,
569		    "No matching processes belonging to you were found\n");
570
571	exit(rv ? STATUS_MATCH : STATUS_NOMATCH);
572}
573
574static void
575usage(void)
576{
577	const char *ustr;
578
579	if (pgrep)
580		ustr = "[-LSfilnoqvx] [-d delim]";
581	else
582		ustr = "[-signal] [-ILfilnovx]";
583
584	fprintf(stderr,
585		"usage: %s %s [-F pidfile] [-G gid] [-M core] [-N system]\n"
586		"             [-P ppid] [-U uid] [-c class] [-g pgrp] [-j jail]\n"
587		"             [-s sid] [-t tty] [-u euid] pattern ...\n",
588		getprogname(), ustr);
589
590	exit(STATUS_BADUSAGE);
591}
592
593static void
594show_process(const struct kinfo_proc *kp)
595{
596	char **argv;
597
598	if (quiet) {
599		assert(pgrep);
600		return;
601	}
602	if ((longfmt || !pgrep) && matchargs &&
603	    (argv = kvm_getargv(kd, kp, 0)) != NULL) {
604		printf("%d ", (int)kp->ki_pid);
605		for (; *argv != NULL; argv++) {
606			printf("%s", *argv);
607			if (argv[1] != NULL)
608				putchar(' ');
609		}
610	} else if (longfmt || !pgrep)
611		printf("%d %s", (int)kp->ki_pid, kp->ki_comm);
612	else
613		printf("%d", (int)kp->ki_pid);
614}
615
616static int
617killact(const struct kinfo_proc *kp)
618{
619	int ch, first;
620
621	if (interactive) {
622		/*
623		 * Be careful, ask before killing.
624		 */
625		printf("kill ");
626		show_process(kp);
627		printf("? ");
628		fflush(stdout);
629		first = ch = getchar();
630		while (ch != '\n' && ch != EOF)
631			ch = getchar();
632		if (first != 'y' && first != 'Y')
633			return (1);
634	}
635	if (kill(kp->ki_pid, signum) == -1) {
636		/*
637		 * Check for ESRCH, which indicates that the process
638		 * disappeared between us matching it and us
639		 * signalling it; don't issue a warning about it.
640		 */
641		if (errno != ESRCH)
642			warn("signalling pid %d", (int)kp->ki_pid);
643		/*
644		 * Return 0 to indicate that the process should not be
645		 * considered a match, since we didn't actually get to
646		 * signal it.
647		 */
648		return (0);
649	}
650	return (1);
651}
652
653static int
654grepact(const struct kinfo_proc *kp)
655{
656
657	show_process(kp);
658	if (!quiet)
659		printf("%s", delim);
660	return (1);
661}
662
663static void
664makelist(struct listhead *head, enum listtype type, char *src)
665{
666	struct list *li;
667	struct passwd *pw;
668	struct group *gr;
669	struct stat st;
670	const char *cp;
671	char *sp, *ep, buf[MAXPATHLEN];
672	int empty;
673
674	empty = 1;
675
676	while ((sp = strsep(&src, ",")) != NULL) {
677		if (*sp == '\0')
678			usage();
679
680		if ((li = malloc(sizeof(*li))) == NULL) {
681			err(STATUS_ERROR, "Cannot allocate %zu bytes",
682			    sizeof(*li));
683		}
684
685		SLIST_INSERT_HEAD(head, li, li_chain);
686		empty = 0;
687
688		if (type != LT_CLASS)
689			li->li_number = (uid_t)strtol(sp, &ep, 0);
690
691		if (type != LT_CLASS && *ep == '\0') {
692			switch (type) {
693			case LT_PGRP:
694				if (li->li_number == 0)
695					li->li_number = getpgrp();
696				break;
697			case LT_SID:
698				if (li->li_number == 0)
699					li->li_number = getsid(mypid);
700				break;
701			case LT_JAIL:
702				if (li->li_number < 0)
703					errx(STATUS_BADUSAGE,
704					     "Negative jail ID `%s'", sp);
705				/* For compatibility with old -j */
706				if (li->li_number == 0)
707					li->li_number = -1;	/* any jail */
708				break;
709			case LT_TTY:
710				if (li->li_number < 0)
711					errx(STATUS_BADUSAGE,
712					     "Negative /dev/pts tty `%s'", sp);
713				snprintf(buf, sizeof(buf), _PATH_DEV "pts/%s",
714				    sp);
715				if (stat(buf, &st) != -1)
716					goto foundtty;
717				if (errno == ENOENT)
718					errx(STATUS_BADUSAGE, "No such tty: `"
719					    _PATH_DEV "pts/%s'", sp);
720				err(STATUS_ERROR, "Cannot access `"
721				    _PATH_DEV "pts/%s'", sp);
722				break;
723			default:
724				break;
725			}
726			continue;
727		}
728
729		switch (type) {
730		case LT_USER:
731			if ((pw = getpwnam(sp)) == NULL)
732				errx(STATUS_BADUSAGE, "Unknown user `%s'", sp);
733			li->li_number = pw->pw_uid;
734			break;
735		case LT_GROUP:
736			if ((gr = getgrnam(sp)) == NULL)
737				errx(STATUS_BADUSAGE, "Unknown group `%s'", sp);
738			li->li_number = gr->gr_gid;
739			break;
740		case LT_TTY:
741			if (strcmp(sp, "-") == 0) {
742				li->li_number = -1;
743				break;
744			} else if (strcmp(sp, "co") == 0) {
745				cp = "console";
746			} else {
747				cp = sp;
748			}
749
750			snprintf(buf, sizeof(buf), _PATH_DEV "%s", cp);
751			if (stat(buf, &st) != -1)
752				goto foundtty;
753
754			snprintf(buf, sizeof(buf), _PATH_DEV "tty%s", cp);
755			if (stat(buf, &st) != -1)
756				goto foundtty;
757
758			if (errno == ENOENT)
759				errx(STATUS_BADUSAGE, "No such tty: `%s'", sp);
760			err(STATUS_ERROR, "Cannot access `%s'", sp);
761
762foundtty:		if ((st.st_mode & S_IFCHR) == 0)
763				errx(STATUS_BADUSAGE, "Not a tty: `%s'", sp);
764
765			li->li_number = st.st_rdev;
766			break;
767		case LT_JAIL: {
768			int jid;
769
770			if (strcmp(sp, "none") == 0)
771				li->li_number = 0;
772			else if (strcmp(sp, "any") == 0)
773				li->li_number = -1;
774			else if ((jid = jail_getid(sp)) != -1)
775				li->li_number = jid;
776			else if (*ep != '\0')
777				errx(STATUS_BADUSAGE,
778				     "Invalid jail ID or name `%s'", sp);
779			break;
780		}
781		case LT_CLASS:
782			li->li_number = -1;
783			li->li_name = strdup(sp);
784			if (li->li_name == NULL)
785				err(STATUS_ERROR, "Cannot allocate memory");
786			break;
787		default:
788			usage();
789		}
790	}
791
792	if (empty)
793		usage();
794}
795
796static int
797takepid(const char *pidfile, int pidfilelock)
798{
799	char *endp, line[BUFSIZ];
800	FILE *fh;
801	long rval;
802
803	fh = fopen(pidfile, "r");
804	if (fh == NULL)
805		err(STATUS_ERROR, "Cannot open pidfile `%s'", pidfile);
806
807	if (pidfilelock) {
808		/*
809		 * If we can lock pidfile, this means that daemon is not
810		 * running, so would be better not to kill some random process.
811		 */
812		if (flock(fileno(fh), LOCK_EX | LOCK_NB) == 0) {
813			(void)fclose(fh);
814			errx(STATUS_ERROR, "File '%s' can be locked", pidfile);
815		} else {
816			if (errno != EWOULDBLOCK) {
817				errx(STATUS_ERROR,
818				    "Error while locking file '%s'", pidfile);
819			}
820		}
821	}
822
823	if (fgets(line, sizeof(line), fh) == NULL) {
824		if (feof(fh)) {
825			(void)fclose(fh);
826			errx(STATUS_ERROR, "Pidfile `%s' is empty", pidfile);
827		}
828		(void)fclose(fh);
829		err(STATUS_ERROR, "Cannot read from pid file `%s'", pidfile);
830	}
831	(void)fclose(fh);
832
833	rval = strtol(line, &endp, 10);
834	if (*endp != '\0' && !isspace((unsigned char)*endp))
835		errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);
836	else if (rval < MIN_PID || rval > MAX_PID)
837		errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);
838	return (rval);
839}
840