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