]> CyberLeo.Net >> Repos - FreeBSD/releng/8.2.git/blob - bin/pkill/pkill.c
Fix named(8) DNSSEC validation Denial of Service.
[FreeBSD/releng/8.2.git] / bin / pkill / pkill.c
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  * 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.
26  *
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.
38  */
39
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
42
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>
51
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>
68
69 #define STATUS_MATCH    0
70 #define STATUS_NOMATCH  1
71 #define STATUS_BADUSAGE 2
72 #define STATUS_ERROR    3
73
74 #define MIN_PID 5
75 #define MAX_PID 99999
76
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))
80
81 enum listtype {
82         LT_GENERIC,
83         LT_USER,
84         LT_GROUP,
85         LT_TTY,
86         LT_PGRP,
87         LT_JID,
88         LT_SID
89 };
90
91 struct list {
92         SLIST_ENTRY(list) li_chain;
93         long    li_number;
94 };
95
96 SLIST_HEAD(listhead, list);
97
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;
115
116 static struct listhead euidlist = SLIST_HEAD_INITIALIZER(euidlist);
117 static struct listhead ruidlist = SLIST_HEAD_INITIALIZER(ruidlist);
118 static struct listhead rgidlist = SLIST_HEAD_INITIALIZER(rgidlist);
119 static struct listhead pgrplist = SLIST_HEAD_INITIALIZER(pgrplist);
120 static struct listhead ppidlist = SLIST_HEAD_INITIALIZER(ppidlist);
121 static struct listhead tdevlist = SLIST_HEAD_INITIALIZER(tdevlist);
122 static struct listhead sidlist = SLIST_HEAD_INITIALIZER(sidlist);
123 static struct listhead jidlist = SLIST_HEAD_INITIALIZER(jidlist);
124
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);
130
131 int
132 main(int argc, char **argv)
133 {
134         char buf[_POSIX2_LINE_MAX], *mstr, **pargv, *p, *q, *pidfile;
135         const char *execf, *coref;
136         int ancestors, debug_opt, did_action;
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;
145         pid_t pid;
146
147         setlocale(LC_ALL, "");
148
149         if (strcmp(getprogname(), "pgrep") == 0) {
150                 action = grepact;
151                 pgrep = 1;
152         } else {
153                 action = killact;
154                 p = argv[1];
155
156                 if (argc > 1 && p[0] == '-') {
157                         p++;
158                         i = (int)strtol(p, &q, 10);
159                         if (*q == '\0') {
160                                 signum = i;
161                                 argv++;
162                                 argc--;
163                         } else {
164                                 if (strncasecmp(p, "sig", 3) == 0)
165                                         p += 3;
166                                 for (i = 1; i < NSIG; i++)
167                                         if (strcasecmp(sys_signame[i], p) == 0)
168                                                 break;
169                                 if (i != NSIG) {
170                                         signum = i;
171                                         argv++;
172                                         argc--;
173                                 }
174                         }
175                 }
176         }
177
178         ancestors = 0;
179         criteria = 0;
180         debug_opt = 0;
181         pidfile = NULL;
182         pidfilelock = 0;
183         execf = NULL;
184         coref = _PATH_DEVNULL;
185
186         while ((ch = getopt(argc, argv, "DF:G:ILM:N:P:SU:ad:fg:ij:lnos: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 'd':
230                         if (!pgrep)
231                                 usage();
232                         delim = optarg;
233                         break;
234                 case 'f':
235                         matchargs = 1;
236                         break;
237                 case 'g':
238                         makelist(&pgrplist, LT_PGRP, optarg);
239                         criteria = 1;
240                         break;
241                 case 'i':
242                         cflags |= REG_ICASE;
243                         break;
244                 case 'j':
245                         makelist(&jidlist, LT_JID, optarg);
246                         criteria = 1;
247                         break;
248                 case 'l':
249                         longfmt = 1;
250                         break;
251                 case 'n':
252                         newest = 1;
253                         criteria = 1;
254                         break;
255                 case 'o':
256                         oldest = 1;
257                         criteria = 1;
258                         break;
259                 case 's':
260                         makelist(&sidlist, LT_SID, optarg);
261                         criteria = 1;
262                         break;
263                 case 't':
264                         makelist(&tdevlist, LT_TTY, optarg);
265                         criteria = 1;
266                         break;
267                 case 'u':
268                         makelist(&euidlist, LT_USER, optarg);
269                         criteria = 1;
270                         break;
271                 case 'v':
272                         inverse = 1;
273                         break;
274                 case 'x':
275                         fullmatch = 1;
276                         break;
277                 default:
278                         usage();
279                         /* NOTREACHED */
280                 }
281
282         argc -= optind;
283         argv += optind;
284         if (argc != 0)
285                 criteria = 1;
286         if (!criteria)
287                 usage();
288         if (newest && oldest)
289                 errx(STATUS_ERROR, "Options -n and -o are mutually exclusive");
290         if (pidfile != NULL)
291                 pidfromfile = takepid(pidfile, pidfilelock);
292         else {
293                 if (pidfilelock) {
294                         errx(STATUS_ERROR,
295                             "Option -L doesn't make sense without -F");
296                 }
297                 pidfromfile = -1;
298         }
299
300         mypid = getpid();
301
302         /*
303          * Retrieve the list of running processes from the kernel.
304          */
305         kd = kvm_openfiles(execf, coref, NULL, O_RDONLY, buf);
306         if (kd == NULL)
307                 errx(STATUS_ERROR, "Cannot open kernel files (%s)", buf);
308
309         /*
310          * Use KERN_PROC_PROC instead of KERN_PROC_ALL, since we
311          * just want processes and not individual kernel threads.
312          */
313         plist = kvm_getprocs(kd, KERN_PROC_PROC, 0, &nproc);
314         if (plist == NULL) {
315                 errx(STATUS_ERROR, "Cannot get process list (%s)",
316                     kvm_geterr(kd));
317         }
318
319         /*
320          * Allocate memory which will be used to keep track of the
321          * selection.
322          */
323         if ((selected = malloc(nproc)) == NULL) {
324                 err(STATUS_ERROR, "Cannot allocate memory for %d processes",
325                     nproc);
326         }
327         memset(selected, 0, nproc);
328
329         /*
330          * Refine the selection.
331          */
332         for (; *argv != NULL; argv++) {
333                 if ((rv = regcomp(&reg, *argv, cflags)) != 0) {
334                         regerror(rv, &reg, buf, sizeof(buf));
335                         errx(STATUS_BADUSAGE,
336                             "Cannot compile regular expression `%s' (%s)",
337                             *argv, buf);
338                 }
339
340                 for (i = 0, kp = plist; i < nproc; i++, kp++) {
341                         if (PSKIP(kp)) {
342                                 if (debug_opt > 0)
343                                     fprintf(stderr, "* Skipped %5d %3d %s\n",
344                                         kp->ki_pid, kp->ki_uid, kp->ki_comm);
345                                 continue;
346                         }
347
348                         if (matchargs &&
349                             (pargv = kvm_getargv(kd, kp, 0)) != NULL) {
350                                 jsz = 0;
351                                 while (jsz < sizeof(buf) && *pargv != NULL) {
352                                         jsz += snprintf(buf + jsz,
353                                             sizeof(buf) - jsz,
354                                             pargv[1] != NULL ? "%s " : "%s",
355                                             pargv[0]);
356                                         pargv++;
357                                 }
358                                 mstr = buf;
359                         } else
360                                 mstr = kp->ki_comm;
361
362                         rv = regexec(&reg, mstr, 1, &regmatch, 0);
363                         if (rv == 0) {
364                                 if (fullmatch) {
365                                         if (regmatch.rm_so == 0 &&
366                                             regmatch.rm_eo ==
367                                             (off_t)strlen(mstr))
368                                                 selected[i] = 1;
369                                 } else
370                                         selected[i] = 1;
371                         } else if (rv != REG_NOMATCH) {
372                                 regerror(rv, &reg, buf, sizeof(buf));
373                                 errx(STATUS_ERROR,
374                                     "Regular expression evaluation error (%s)",
375                                     buf);
376                         }
377                         if (debug_opt > 1) {
378                                 const char *rv_res = "NoMatch";
379                                 if (selected[i])
380                                         rv_res = "Matched";
381                                 fprintf(stderr, "* %s %5d %3d %s\n", rv_res,
382                                     kp->ki_pid, kp->ki_uid, mstr);
383                         }
384                 }
385
386                 regfree(&reg);
387         }
388
389         for (i = 0, kp = plist; i < nproc; i++, kp++) {
390                 if (PSKIP(kp))
391                         continue;
392
393                 if (pidfromfile >= 0 && kp->ki_pid != pidfromfile) {
394                         selected[i] = 0;
395                         continue;
396                 }
397
398                 SLIST_FOREACH(li, &ruidlist, li_chain)
399                         if (kp->ki_ruid == (uid_t)li->li_number)
400                                 break;
401                 if (SLIST_FIRST(&ruidlist) != NULL && li == NULL) {
402                         selected[i] = 0;
403                         continue;
404                 }
405
406                 SLIST_FOREACH(li, &rgidlist, li_chain)
407                         if (kp->ki_rgid == (gid_t)li->li_number)
408                                 break;
409                 if (SLIST_FIRST(&rgidlist) != NULL && li == NULL) {
410                         selected[i] = 0;
411                         continue;
412                 }
413
414                 SLIST_FOREACH(li, &euidlist, li_chain)
415                         if (kp->ki_uid == (uid_t)li->li_number)
416                                 break;
417                 if (SLIST_FIRST(&euidlist) != NULL && li == NULL) {
418                         selected[i] = 0;
419                         continue;
420                 }
421
422                 SLIST_FOREACH(li, &ppidlist, li_chain)
423                         if (kp->ki_ppid == (pid_t)li->li_number)
424                                 break;
425                 if (SLIST_FIRST(&ppidlist) != NULL && li == NULL) {
426                         selected[i] = 0;
427                         continue;
428                 }
429
430                 SLIST_FOREACH(li, &pgrplist, li_chain)
431                         if (kp->ki_pgid == (pid_t)li->li_number)
432                                 break;
433                 if (SLIST_FIRST(&pgrplist) != NULL && li == NULL) {
434                         selected[i] = 0;
435                         continue;
436                 }
437
438                 SLIST_FOREACH(li, &tdevlist, li_chain) {
439                         if (li->li_number == -1 &&
440                             (kp->ki_flag & P_CONTROLT) == 0)
441                                 break;
442                         if (kp->ki_tdev == (dev_t)li->li_number)
443                                 break;
444                 }
445                 if (SLIST_FIRST(&tdevlist) != NULL && li == NULL) {
446                         selected[i] = 0;
447                         continue;
448                 }
449
450                 SLIST_FOREACH(li, &sidlist, li_chain)
451                         if (kp->ki_sid == (pid_t)li->li_number)
452                                 break;
453                 if (SLIST_FIRST(&sidlist) != NULL && li == NULL) {
454                         selected[i] = 0;
455                         continue;
456                 }
457
458                 SLIST_FOREACH(li, &jidlist, li_chain) {
459                         /* A particular jail ID, including 0 (not in jail) */
460                         if (kp->ki_jid == (int)li->li_number)
461                                 break;
462                         /* Any jail */
463                         if (kp->ki_jid > 0 && li->li_number == -1)
464                                 break;
465                 }
466                 if (SLIST_FIRST(&jidlist) != NULL && li == NULL) {
467                         selected[i] = 0;
468                         continue;
469                 }
470
471                 if (argc == 0)
472                         selected[i] = 1;
473         }
474
475         if (!ancestors) {
476                 pid = mypid;
477                 while (pid) {
478                         for (i = 0, kp = plist; i < nproc; i++, kp++) {
479                                 if (PSKIP(kp))
480                                         continue;
481                                 if (kp->ki_pid == pid) {
482                                         selected[i] = 0;
483                                         pid = kp->ki_ppid;
484                                         break;
485                                 }
486                         }
487                         if (i == nproc) {
488                                 if (pid == mypid)
489                                         pid = getppid();
490                                 else
491                                         break;  /* Maybe we're in a jail ? */
492                         }
493                 }
494         }
495
496         if (newest || oldest) {
497                 best_tval.tv_sec = 0;
498                 best_tval.tv_usec = 0;
499                 bestidx = -1;
500
501                 for (i = 0, kp = plist; i < nproc; i++, kp++) {
502                         if (!selected[i])
503                                 continue;
504                         if (bestidx == -1) {
505                                 /* The first entry of the list which matched. */
506                                 ;
507                         } else if (timercmp(&kp->ki_start, &best_tval, >)) {
508                                 /* This entry is newer than previous "best". */
509                                 if (oldest)     /* but we want the oldest */
510                                         continue;
511                         } else {
512                                 /* This entry is older than previous "best". */
513                                 if (newest)     /* but we want the newest */
514                                         continue;
515                         }
516                         /* This entry is better than previous "best" entry. */
517                         best_tval.tv_sec = kp->ki_start.tv_sec;
518                         best_tval.tv_usec = kp->ki_start.tv_usec;
519                         bestidx = i;
520                 }
521
522                 memset(selected, 0, nproc);
523                 if (bestidx != -1)
524                         selected[bestidx] = 1;
525         }
526
527         /*
528          * Take the appropriate action for each matched process, if any.
529          */
530         did_action = 0;
531         for (i = 0, rv = 0, kp = plist; i < nproc; i++, kp++) {
532                 if (PSKIP(kp))
533                         continue;
534                 if (selected[i]) {
535                         if (longfmt && !pgrep) {
536                                 did_action = 1;
537                                 printf("kill -%d %d\n", signum, kp->ki_pid);
538                         }
539                         if (inverse)
540                                 continue;
541                 } else if (!inverse)
542                         continue;
543                 rv |= (*action)(kp);
544         }
545         if (!did_action && !pgrep && longfmt)
546                 fprintf(stderr,
547                     "No matching processes belonging to you were found\n");
548
549         exit(rv ? STATUS_MATCH : STATUS_NOMATCH);
550 }
551
552 static void
553 usage(void)
554 {
555         const char *ustr;
556
557         if (pgrep)
558                 ustr = "[-LSfilnovx] [-d delim]";
559         else
560                 ustr = "[-signal] [-ILfilnovx]";
561
562         fprintf(stderr,
563                 "usage: %s %s [-F pidfile] [-G gid] [-M core] [-N system]\n"
564                 "             [-P ppid] [-U uid] [-g pgrp] [-j jid] [-s sid]\n"
565                 "             [-t tty] [-u euid] pattern ...\n", getprogname(),
566                 ustr);
567
568         exit(STATUS_BADUSAGE);
569 }
570
571 static void
572 show_process(const struct kinfo_proc *kp)
573 {
574         char **argv;
575
576         if ((longfmt || !pgrep) && matchargs &&
577             (argv = kvm_getargv(kd, kp, 0)) != NULL) {
578                 printf("%d ", (int)kp->ki_pid);
579                 for (; *argv != NULL; argv++) {
580                         printf("%s", *argv);
581                         if (argv[1] != NULL)
582                                 putchar(' ');
583                 }
584         } else if (longfmt || !pgrep)
585                 printf("%d %s", (int)kp->ki_pid, kp->ki_comm);
586         else
587                 printf("%d", (int)kp->ki_pid);
588 }
589
590 static int
591 killact(const struct kinfo_proc *kp)
592 {
593         int ch, first;
594
595         if (interactive) {
596                 /*
597                  * Be careful, ask before killing.
598                  */
599                 printf("kill ");
600                 show_process(kp);
601                 printf("? ");
602                 fflush(stdout);
603                 first = ch = getchar();
604                 while (ch != '\n' && ch != EOF)
605                         ch = getchar();
606                 if (first != 'y' && first != 'Y')
607                         return (1);
608         }
609         if (kill(kp->ki_pid, signum) == -1) {
610                 /* 
611                  * Check for ESRCH, which indicates that the process
612                  * disappeared between us matching it and us
613                  * signalling it; don't issue a warning about it.
614                  */
615                 if (errno != ESRCH)
616                         warn("signalling pid %d", (int)kp->ki_pid);
617                 /*
618                  * Return 0 to indicate that the process should not be
619                  * considered a match, since we didn't actually get to
620                  * signal it.
621                  */
622                 return (0);
623         }
624         return (1);
625 }
626
627 static int
628 grepact(const struct kinfo_proc *kp)
629 {
630
631         show_process(kp);
632         printf("%s", delim);
633         return (1);
634 }
635
636 static void
637 makelist(struct listhead *head, enum listtype type, char *src)
638 {
639         struct list *li;
640         struct passwd *pw;
641         struct group *gr;
642         struct stat st;
643         const char *cp;
644         char *sp, *ep, buf[MAXPATHLEN];
645         int empty;
646
647         empty = 1;
648
649         while ((sp = strsep(&src, ",")) != NULL) {
650                 if (*sp == '\0')
651                         usage();
652
653                 if ((li = malloc(sizeof(*li))) == NULL) {
654                         err(STATUS_ERROR, "Cannot allocate %zu bytes",
655                             sizeof(*li));
656                 }
657
658                 SLIST_INSERT_HEAD(head, li, li_chain);
659                 empty = 0;
660
661                 li->li_number = (uid_t)strtol(sp, &ep, 0);
662                 if (*ep == '\0') {
663                         switch (type) {
664                         case LT_PGRP:
665                                 if (li->li_number == 0)
666                                         li->li_number = getpgrp();
667                                 break;
668                         case LT_SID:
669                                 if (li->li_number == 0)
670                                         li->li_number = getsid(mypid);
671                                 break;
672                         case LT_JID:
673                                 if (li->li_number < 0)
674                                         errx(STATUS_BADUSAGE,
675                                              "Negative jail ID `%s'", sp);
676                                 /* For compatibility with old -j */
677                                 if (li->li_number == 0)
678                                         li->li_number = -1;     /* any jail */
679                                 break;
680                         case LT_TTY:
681                                 usage();
682                                 /* NOTREACHED */
683                         default:
684                                 break;
685                         }
686                         continue;
687                 }
688
689                 switch (type) {
690                 case LT_USER:
691                         if ((pw = getpwnam(sp)) == NULL)
692                                 errx(STATUS_BADUSAGE, "Unknown user `%s'", sp);
693                         li->li_number = pw->pw_uid;
694                         break;
695                 case LT_GROUP:
696                         if ((gr = getgrnam(sp)) == NULL)
697                                 errx(STATUS_BADUSAGE, "Unknown group `%s'", sp);
698                         li->li_number = gr->gr_gid;
699                         break;
700                 case LT_TTY:
701                         if (strcmp(sp, "-") == 0) {
702                                 li->li_number = -1;
703                                 break;
704                         } else if (strcmp(sp, "co") == 0) {
705                                 cp = "console";
706                         } else {
707                                 cp = sp;
708                         }
709
710                         snprintf(buf, sizeof(buf), _PATH_DEV "%s", cp);
711                         if (stat(buf, &st) != -1)
712                                 goto foundtty;
713
714                         snprintf(buf, sizeof(buf), _PATH_DEV "tty%s", cp);
715                         if (stat(buf, &st) != -1)
716                                 goto foundtty;
717
718                         if (errno == ENOENT)
719                                 errx(STATUS_BADUSAGE, "No such tty: `%s'", sp);
720                         err(STATUS_ERROR, "Cannot access `%s'", sp);
721
722 foundtty:               if ((st.st_mode & S_IFCHR) == 0)
723                                 errx(STATUS_BADUSAGE, "Not a tty: `%s'", sp);
724
725                         li->li_number = st.st_rdev;
726                         break;
727                 case LT_JID:
728                         if (strcmp(sp, "none") == 0)
729                                 li->li_number = 0;
730                         else if (strcmp(sp, "any") == 0)
731                                 li->li_number = -1;
732                         else if (*ep != '\0')
733                                 errx(STATUS_BADUSAGE,
734                                      "Invalid jail ID `%s'", sp);
735                         break;
736                 default:
737                         usage();
738                 }
739         }
740
741         if (empty)
742                 usage();
743 }
744
745 static int
746 takepid(const char *pidfile, int pidfilelock)
747 {
748         char *endp, line[BUFSIZ];
749         FILE *fh;
750         long rval;
751
752         fh = fopen(pidfile, "r");
753         if (fh == NULL)
754                 err(STATUS_ERROR, "Cannot open pidfile `%s'", pidfile);
755
756         if (pidfilelock) {
757                 /*
758                  * If we can lock pidfile, this means that daemon is not
759                  * running, so would be better not to kill some random process.
760                  */
761                 if (flock(fileno(fh), LOCK_EX | LOCK_NB) == 0) {
762                         (void)fclose(fh);
763                         errx(STATUS_ERROR, "File '%s' can be locked", pidfile);
764                 } else {
765                         if (errno != EWOULDBLOCK) {
766                                 errx(STATUS_ERROR,
767                                     "Error while locking file '%s'", pidfile);
768                         }
769                 }
770         }
771
772         if (fgets(line, sizeof(line), fh) == NULL) {
773                 if (feof(fh)) {
774                         (void)fclose(fh);
775                         errx(STATUS_ERROR, "Pidfile `%s' is empty", pidfile);
776                 }
777                 (void)fclose(fh);
778                 err(STATUS_ERROR, "Cannot read from pid file `%s'", pidfile);
779         }
780         (void)fclose(fh);
781
782         rval = strtol(line, &endp, 10);
783         if (*endp != '\0' && !isspace((unsigned char)*endp))
784                 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);
785         else if (rval < MIN_PID || rval > MAX_PID)
786                 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);
787         return (rval);
788 }