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