]> git.cameronkatri.com Git - apple_cmds.git/blob - adv_cmds/pkill/pkill.c
basic_cmds: Makefiles
[apple_cmds.git] / adv_cmds / 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: src/bin/pkill/pkill.c,v 1.12 2011/02/04 16:40:50 jilles Exp $");
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 #ifndef __APPLE__
57 #include <kvm.h>
58 #endif
59 #include <err.h>
60 #include <pwd.h>
61 #include <grp.h>
62 #include <errno.h>
63 #include <locale.h>
64
65 #ifdef __APPLE__
66 #include <xpc/xpc.h>
67 #include <sys/proc_info.h>
68 #include <os/assumes.h>
69 #include <sysmon.h>
70 #endif
71
72 #define STATUS_MATCH 0
73 #define STATUS_NOMATCH 1
74 #define STATUS_BADUSAGE 2
75 #define STATUS_ERROR 3
76
77 #define MIN_PID 5
78 #define MAX_PID 99999
79
80 #ifdef __APPLE__
81 /* Ignore system processes and myself. */
82 #define PSKIP(kp) ((pid_t)xpc_uint64_get_value(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_PID)) == mypid || \
83 ((xpc_uint64_get_value(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_FLAGS)) & PROC_FLAG_SYSTEM) != 0))
84 #else
85 /* Ignore system-processes (if '-S' flag is not specified) and myself. */
86 #define PSKIP(kp) ((kp)->ki_pid == mypid || \
87 (!kthreads && ((kp)->ki_flag & P_KTHREAD) != 0))
88 #endif
89
90 enum listtype {
91 LT_GENERIC,
92 LT_USER,
93 LT_GROUP,
94 LT_TTY,
95 LT_PGRP,
96 #ifndef __APPLE__
97 LT_JID,
98 #endif
99 LT_SID
100 };
101
102 struct list {
103 SLIST_ENTRY(list) li_chain;
104 long li_number;
105 };
106
107 SLIST_HEAD(listhead, list);
108
109 #ifdef __APPLE__
110 static sysmon_table_t plist;
111 #else
112 static struct kinfo_proc *plist;
113 #endif
114 static char *selected;
115 static const char *delim = "\n";
116 static int nproc;
117 static int pgrep;
118 static int signum = SIGTERM;
119 static int newest;
120 static int oldest;
121 static int interactive;
122 static int inverse;
123 static int longfmt;
124 static int matchargs;
125 static int fullmatch;
126 #ifndef __APPLE__
127 static int kthreads;
128 #endif
129 static int cflags = REG_EXTENDED;
130 static int quiet;
131 #ifndef __APPLE__
132 static kvm_t *kd;
133 #endif
134 static pid_t mypid;
135
136 static struct listhead euidlist = SLIST_HEAD_INITIALIZER(euidlist);
137 static struct listhead ruidlist = SLIST_HEAD_INITIALIZER(ruidlist);
138 static struct listhead rgidlist = SLIST_HEAD_INITIALIZER(rgidlist);
139 static struct listhead pgrplist = SLIST_HEAD_INITIALIZER(pgrplist);
140 static struct listhead ppidlist = SLIST_HEAD_INITIALIZER(ppidlist);
141 static struct listhead tdevlist = SLIST_HEAD_INITIALIZER(tdevlist);
142 #ifndef __APPLE__
143 static struct listhead sidlist = SLIST_HEAD_INITIALIZER(sidlist);
144 static struct listhead jidlist = SLIST_HEAD_INITIALIZER(jidlist);
145 #endif
146
147 static void usage(void) __attribute__((__noreturn__));
148 #ifdef __APPLE__
149 static int killact(const sysmon_row_t);
150 static int grepact(const sysmon_row_t);
151 #else
152 static int killact(const struct kinfo_proc *);
153 static int grepact(const struct kinfo_proc *);
154 #endif
155 static void makelist(struct listhead *, enum listtype, char *);
156 static int takepid(const char *, int);
157
158 #ifdef __APPLE__
159 static sysmon_table_t
160 copy_process_info(void)
161 {
162 dispatch_semaphore_t sema;
163 sysmon_request_t request;
164 __block sysmon_table_t result = NULL;
165
166 sema = dispatch_semaphore_create(0);
167 request = sysmon_request_create_with_error(SYSMON_REQUEST_TYPE_PROCESS, ^(sysmon_table_t table, const char *error_str) {
168 if (table) {
169 result = sysmon_retain(table);
170 } else {
171 fprintf(stderr, "sysmon request failed with error: %s\n", error_str);
172 }
173 dispatch_semaphore_signal(sema);
174 });
175 sysmon_request_add_attribute(request, SYSMON_ATTR_PROC_PID);
176 sysmon_request_add_attribute(request, SYSMON_ATTR_PROC_FLAGS);
177 sysmon_request_add_attribute(request, SYSMON_ATTR_PROC_UID);
178 sysmon_request_add_attribute(request, SYSMON_ATTR_PROC_COMM);
179 sysmon_request_add_attribute(request, SYSMON_ATTR_PROC_ARGUMENTS);
180 sysmon_request_add_attribute(request, SYSMON_ATTR_PROC_RUID);
181 sysmon_request_add_attribute(request, SYSMON_ATTR_PROC_RGID);
182 sysmon_request_add_attribute(request, SYSMON_ATTR_PROC_PPID);
183 sysmon_request_add_attribute(request, SYSMON_ATTR_PROC_PGID);
184 sysmon_request_add_attribute(request, SYSMON_ATTR_PROC_TDEV);
185 sysmon_request_add_attribute(request, SYSMON_ATTR_PROC_START);
186 sysmon_request_execute(request);
187 dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
188 dispatch_release(sema);
189 sysmon_release(request);
190
191 return result;
192 }
193 #endif /* __APPLE__ */
194
195 int
196 main(int argc, char **argv)
197 {
198 #ifdef __APPLE__
199 char buf[_POSIX2_LINE_MAX], *bufp, *mstr, *p, *q, *pidfile;
200 xpc_object_t pargv;
201 #else
202 char buf[_POSIX2_LINE_MAX], *mstr, **pargv, *p, *q, *pidfile;
203 const char *execf, *coref;
204 #endif
205 int ancestors, debug_opt, did_action;
206 int i, ch, bestidx, rv, criteria, pidfromfile, pidfilelock;
207 #ifdef __APPLE__
208 __block size_t jsz;
209 int (*action)(const sysmon_row_t);
210 sysmon_row_t kp;
211 #else
212 size_t jsz;
213 int (*action)(const struct kinfo_proc *);
214 struct kinfo_proc *kp;
215 #endif
216 struct list *li;
217 #ifdef __APPLE__
218 int64_t best_tval;
219 #else
220 struct timeval best_tval;
221 #endif
222 regex_t reg;
223 regmatch_t regmatch;
224 pid_t pid;
225
226 setlocale(LC_ALL, "");
227
228 if (strcmp(getprogname(), "pgrep") == 0) {
229 action = grepact;
230 pgrep = 1;
231 } else {
232 action = killact;
233 p = argv[1];
234
235 if (argc > 1 && p[0] == '-') {
236 p++;
237 i = (int)strtol(p, &q, 10);
238 if (*q == '\0') {
239 signum = i;
240 argv++;
241 argc--;
242 } else {
243 if (strncasecmp(p, "SIG", 3) == 0)
244 p += 3;
245 for (i = 1; i < NSIG; i++)
246 if (strcasecmp(sys_signame[i], p) == 0)
247 break;
248 if (i != NSIG) {
249 signum = i;
250 argv++;
251 argc--;
252 }
253 }
254 }
255 }
256
257 ancestors = 0;
258 criteria = 0;
259 debug_opt = 0;
260 pidfile = NULL;
261 pidfilelock = 0;
262 quiet = 0;
263 #ifndef __APPLE__
264 execf = NULL;
265 coref = _PATH_DEVNULL;
266 #endif
267
268 #ifdef __APPLE__
269 while ((ch = getopt(argc, argv, "DF:G:ILP:U:ad:fg:ilnoqt:u:vx")) != -1)
270 #else
271 while ((ch = getopt(argc, argv, "DF:G:ILM:N:P:SU:ad:fg:ij:lnoqs:t:u:vx")) != -1)
272 #endif
273 switch (ch) {
274 case 'D':
275 debug_opt++;
276 break;
277 case 'F':
278 pidfile = optarg;
279 criteria = 1;
280 break;
281 case 'G':
282 makelist(&rgidlist, LT_GROUP, optarg);
283 criteria = 1;
284 break;
285 case 'I':
286 if (pgrep)
287 usage();
288 interactive = 1;
289 break;
290 case 'L':
291 pidfilelock = 1;
292 break;
293 #ifndef __APPLE__
294 case 'M':
295 coref = optarg;
296 break;
297 case 'N':
298 execf = optarg;
299 break;
300 #endif
301 case 'P':
302 makelist(&ppidlist, LT_GENERIC, optarg);
303 criteria = 1;
304 break;
305 #ifndef __APPLE__
306 case 'S':
307 if (!pgrep)
308 usage();
309 kthreads = 1;
310 break;
311 #endif
312 case 'U':
313 makelist(&ruidlist, LT_USER, optarg);
314 criteria = 1;
315 break;
316 case 'a':
317 ancestors++;
318 break;
319 case 'd':
320 if (!pgrep)
321 usage();
322 delim = optarg;
323 break;
324 case 'f':
325 matchargs = 1;
326 break;
327 case 'g':
328 makelist(&pgrplist, LT_PGRP, optarg);
329 criteria = 1;
330 break;
331 case 'i':
332 cflags |= REG_ICASE;
333 break;
334 #ifndef __APPLE__
335 case 'j':
336 makelist(&jidlist, LT_JID, optarg);
337 criteria = 1;
338 break;
339 #endif
340 case 'l':
341 longfmt = 1;
342 break;
343 case 'n':
344 newest = 1;
345 criteria = 1;
346 break;
347 case 'o':
348 oldest = 1;
349 criteria = 1;
350 break;
351 case 'q':
352 if (!pgrep)
353 usage();
354 quiet = 1;
355 break;
356 #ifndef __APPLE__
357 case 's':
358 makelist(&sidlist, LT_SID, optarg);
359 criteria = 1;
360 break;
361 #endif /* !__APPLE__ */
362 case 't':
363 makelist(&tdevlist, LT_TTY, optarg);
364 criteria = 1;
365 break;
366 case 'u':
367 makelist(&euidlist, LT_USER, optarg);
368 criteria = 1;
369 break;
370 case 'v':
371 inverse = 1;
372 break;
373 case 'x':
374 fullmatch = 1;
375 break;
376 default:
377 usage();
378 /* NOTREACHED */
379 }
380
381 argc -= optind;
382 argv += optind;
383 if (argc != 0)
384 criteria = 1;
385 if (!criteria)
386 usage();
387 if (newest && oldest)
388 errx(STATUS_ERROR, "Options -n and -o are mutually exclusive");
389 if (pidfile != NULL)
390 pidfromfile = takepid(pidfile, pidfilelock);
391 else {
392 if (pidfilelock) {
393 errx(STATUS_ERROR,
394 "Option -L doesn't make sense without -F");
395 }
396 pidfromfile = -1;
397 }
398
399 mypid = getpid();
400
401 #ifdef __APPLE__
402 plist = copy_process_info();
403 if (plist == NULL) {
404 errx(STATUS_ERROR, "Cannot get process list");
405 }
406 nproc = sysmon_table_get_count(plist);
407 #else
408 /*
409 * Retrieve the list of running processes from the kernel.
410 */
411 kd = kvm_openfiles(execf, coref, NULL, O_RDONLY, buf);
412 if (kd == NULL)
413 errx(STATUS_ERROR, "Cannot open kernel files (%s)", buf);
414
415 /*
416 * Use KERN_PROC_PROC instead of KERN_PROC_ALL, since we
417 * just want processes and not individual kernel threads.
418 */
419 plist = kvm_getprocs(kd, KERN_PROC_PROC, 0, &nproc);
420 if (plist == NULL) {
421 errx(STATUS_ERROR, "Cannot get process list (%s)",
422 kvm_geterr(kd));
423 }
424 #endif
425
426 /*
427 * Allocate memory which will be used to keep track of the
428 * selection.
429 */
430 if ((selected = malloc(nproc)) == NULL) {
431 err(STATUS_ERROR, "Cannot allocate memory for %d processes",
432 nproc);
433 }
434 memset(selected, 0, nproc);
435
436 /*
437 * Refine the selection.
438 */
439 for (; *argv != NULL; argv++) {
440 if ((rv = regcomp(&reg, *argv, cflags)) != 0) {
441 regerror(rv, &reg, buf, sizeof(buf));
442 errx(STATUS_BADUSAGE,
443 "Cannot compile regular expression `%s' (%s)",
444 *argv, buf);
445 }
446
447 #ifdef __APPLE__
448 for (i = 0; i < nproc; i++) {
449 kp = sysmon_table_get_row(plist, i);
450 #else
451 for (i = 0, kp = plist; i < nproc; i++, kp++) {
452 #endif
453 if (PSKIP(kp)) {
454 if (debug_opt > 0)
455 fprintf(stderr, "* Skipped %5d %3d %s\n",
456 #ifdef __APPLE__
457 (pid_t)xpc_uint64_get_value(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_PID)),
458 (uid_t)xpc_uint64_get_value(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_UID)),
459 xpc_string_get_string_ptr(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_COMM)));
460 #else
461 kp->ki_pid, kp->ki_uid, kp->ki_comm);
462 #endif
463 continue;
464 }
465
466 #ifdef __APPLE__
467 if (matchargs &&
468 (pargv = sysmon_row_get_value(kp, SYSMON_ATTR_PROC_ARGUMENTS)) != NULL) {
469 jsz = 0;
470 os_assert(sizeof(buf) == _POSIX2_LINE_MAX);
471 bufp = buf;
472 xpc_array_apply(pargv, ^(size_t index, xpc_object_t value) {
473 if (jsz >= _POSIX2_LINE_MAX) {
474 return (bool)false;
475 }
476 jsz += snprintf(bufp + jsz,
477 _POSIX2_LINE_MAX - jsz,
478 index < xpc_array_get_count(pargv) - 1 ? "%s " : "%s",
479 xpc_string_get_string_ptr(value));
480 return (bool)true;
481 });
482 #else
483 if (matchargs &&
484 (pargv = kvm_getargv(kd, kp, 0)) != NULL) {
485 jsz = 0;
486 while (jsz < sizeof(buf) && *pargv != NULL) {
487 jsz += snprintf(buf + jsz,
488 sizeof(buf) - jsz,
489 pargv[1] != NULL ? "%s " : "%s",
490 pargv[0]);
491 pargv++;
492 }
493 #endif
494 mstr = buf;
495 } else
496 #ifdef __APPLE__
497 {
498 /*
499 * comm is limited to 15 bytes (MAXCOMLEN - 1).
500 * Try to use argv[0] (trimmed) if available.
501 */
502 mstr = NULL;
503 pargv = sysmon_row_get_value(kp, SYSMON_ATTR_PROC_ARGUMENTS);
504 if (pargv != NULL && xpc_array_get_count(pargv) > 0) {
505 const char *tmp = xpc_array_get_string(pargv, 0);
506 if (tmp != NULL) {
507 mstr = strrchr(tmp, '/');
508 if (mstr != NULL) {
509 mstr++;
510 } else {
511 mstr = (char *)tmp;
512 }
513 }
514 }
515
516 /* Fall back to "comm" if we failed to get argv[0]. */
517 if (mstr == NULL || *mstr == '\0') {
518 mstr = (char *)xpc_string_get_string_ptr(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_COMM));
519 }
520
521 /* Couldn't find process name, it probably exited. */
522 if (mstr == NULL) {
523 continue;
524 }
525 }
526 #else
527 mstr = kp->ki_comm;
528 #endif
529
530 rv = regexec(&reg, mstr, 1, &regmatch, 0);
531 if (rv == 0) {
532 if (fullmatch) {
533 if (regmatch.rm_so == 0 &&
534 regmatch.rm_eo ==
535 (off_t)strlen(mstr))
536 selected[i] = 1;
537 } else
538 selected[i] = 1;
539 } else if (rv != REG_NOMATCH) {
540 regerror(rv, &reg, buf, sizeof(buf));
541 errx(STATUS_ERROR,
542 "Regular expression evaluation error (%s)",
543 buf);
544 }
545 if (debug_opt > 1) {
546 const char *rv_res = "NoMatch";
547 if (selected[i])
548 rv_res = "Matched";
549 fprintf(stderr, "* %s %5d %3d %s\n", rv_res,
550 #ifdef __APPLE__
551 (pid_t)xpc_uint64_get_value(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_PID)),
552 (uid_t)xpc_uint64_get_value(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_UID)),
553 mstr);
554 #else
555 kp->ki_pid, kp->ki_uid, mstr);
556 #endif
557 }
558 }
559
560 regfree(&reg);
561 }
562
563 #ifdef __APPLE__
564 for (i = 0; i < nproc; i++) {
565 kp = sysmon_table_get_row(plist, i);
566 #else
567 for (i = 0, kp = plist; i < nproc; i++, kp++) {
568 #endif
569 if (PSKIP(kp))
570 continue;
571
572 #ifdef __APPLE__
573 if (pidfromfile >= 0 && (pid_t)xpc_uint64_get_value(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_PID)) != pidfromfile) {
574 #else
575 if (pidfromfile >= 0 && kp->ki_pid != pidfromfile) {
576 #endif
577 selected[i] = 0;
578 continue;
579 }
580
581 SLIST_FOREACH(li, &ruidlist, li_chain)
582 #ifdef __APPLE__
583 if ((uid_t)xpc_uint64_get_value(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_RUID)) == (uid_t)li->li_number)
584 #else
585 if (kp->ki_ruid == (uid_t)li->li_number)
586 #endif
587 break;
588 if (SLIST_FIRST(&ruidlist) != NULL && li == NULL) {
589 selected[i] = 0;
590 continue;
591 }
592
593 SLIST_FOREACH(li, &rgidlist, li_chain)
594 #ifdef __APPLE__
595 if ((gid_t)xpc_uint64_get_value(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_RGID)) == (gid_t)li->li_number)
596 #else
597 if (kp->ki_rgid == (gid_t)li->li_number)
598 #endif
599 break;
600 if (SLIST_FIRST(&rgidlist) != NULL && li == NULL) {
601 selected[i] = 0;
602 continue;
603 }
604
605 SLIST_FOREACH(li, &euidlist, li_chain)
606 #ifdef __APPLE__
607 if ((uid_t)xpc_uint64_get_value(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_UID)) == (uid_t)li->li_number)
608 #else
609 if (kp->ki_uid == (uid_t)li->li_number)
610 #endif
611 break;
612 if (SLIST_FIRST(&euidlist) != NULL && li == NULL) {
613 selected[i] = 0;
614 continue;
615 }
616
617 SLIST_FOREACH(li, &ppidlist, li_chain)
618 #ifdef __APPLE__
619 if ((pid_t)xpc_uint64_get_value(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_PPID)) == (pid_t)li->li_number)
620 #else
621 if (kp->ki_ppid == (pid_t)li->li_number)
622 #endif
623 break;
624 if (SLIST_FIRST(&ppidlist) != NULL && li == NULL) {
625 selected[i] = 0;
626 continue;
627 }
628
629 SLIST_FOREACH(li, &pgrplist, li_chain)
630 #ifdef __APPLE__
631 if ((pid_t)xpc_uint64_get_value(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_PGID)) == (pid_t)li->li_number)
632 #else
633 if (kp->ki_pgid == (pid_t)li->li_number)
634 #endif
635 break;
636 if (SLIST_FIRST(&pgrplist) != NULL && li == NULL) {
637 selected[i] = 0;
638 continue;
639 }
640
641 SLIST_FOREACH(li, &tdevlist, li_chain) {
642 if (li->li_number == -1 &&
643 #ifdef __APPLE__
644 (xpc_uint64_get_value(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_FLAGS)) & PROC_FLAG_CONTROLT) == 0)
645 #else
646 (kp->ki_flag & P_CONTROLT) == 0)
647 #endif
648 break;
649 #ifdef __APPLE__
650 if ((dev_t)xpc_uint64_get_value(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_TDEV)) == (dev_t)li->li_number)
651 #else
652 if (kp->ki_tdev == (dev_t)li->li_number)
653 #endif
654 break;
655 }
656 if (SLIST_FIRST(&tdevlist) != NULL && li == NULL) {
657 selected[i] = 0;
658 continue;
659 }
660
661 #ifndef __APPLE__
662 SLIST_FOREACH(li, &sidlist, li_chain)
663 if (kp->ki_sid == (pid_t)li->li_number)
664 break;
665 if (SLIST_FIRST(&sidlist) != NULL && li == NULL) {
666 selected[i] = 0;
667 continue;
668 }
669
670 SLIST_FOREACH(li, &jidlist, li_chain) {
671 /* A particular jail ID, including 0 (not in jail) */
672 if (kp->ki_jid == (int)li->li_number)
673 break;
674 /* Any jail */
675 if (kp->ki_jid > 0 && li->li_number == -1)
676 break;
677 }
678 if (SLIST_FIRST(&jidlist) != NULL && li == NULL) {
679 selected[i] = 0;
680 continue;
681 }
682 #endif /* !__APPLE__ */
683
684 if (argc == 0)
685 selected[i] = 1;
686 }
687
688 if (!ancestors) {
689 pid = mypid;
690 while (pid) {
691 #ifdef __APPLE__
692 for (i = 0; i < nproc; i++) {
693 kp = sysmon_table_get_row(plist, i);
694 #else
695 for (i = 0, kp = plist; i < nproc; i++, kp++) {
696 #endif
697 if (PSKIP(kp))
698 continue;
699 #ifdef __APPLE__
700 if ((pid_t)xpc_uint64_get_value(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_PID)) == pid) {
701 selected[i] = 0;
702 pid = (pid_t)xpc_uint64_get_value(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_PPID));
703 break;
704 }
705 #else
706 if (kp->ki_pid == pid) {
707 selected[i] = 0;
708 pid = kp->ki_ppid;
709 break;
710 }
711 #endif
712 }
713 if (i == nproc) {
714 if (pid == mypid)
715 pid = getppid();
716 else
717 break; /* Maybe we're in a jail ? */
718 }
719 }
720 }
721
722 if (newest || oldest) {
723 #ifdef __APPLE__
724 best_tval = 0;
725 #else
726 best_tval.tv_sec = 0;
727 best_tval.tv_usec = 0;
728 #endif
729 bestidx = -1;
730
731 #ifdef __APPLE__
732 for (i = 0; i < nproc; i++) {
733 kp = sysmon_table_get_row(plist, i);
734 #else
735 for (i = 0, kp = plist; i < nproc; i++, kp++) {
736 #endif
737 if (!selected[i])
738 continue;
739 if (bestidx == -1) {
740 /* The first entry of the list which matched. */
741 ;
742 #ifdef __APPLE__
743 } else if (xpc_date_get_value(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_START)) > best_tval) {
744 #else
745 } else if (timercmp(&kp->ki_start, &best_tval, >)) {
746 #endif
747 /* This entry is newer than previous "best". */
748 if (oldest) /* but we want the oldest */
749 continue;
750 } else {
751 /* This entry is older than previous "best". */
752 if (newest) /* but we want the newest */
753 continue;
754 }
755 /* This entry is better than previous "best" entry. */
756 #ifdef __APPLE__
757 best_tval = xpc_date_get_value(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_START));
758 #else
759 best_tval.tv_sec = kp->ki_start.tv_sec;
760 best_tval.tv_usec = kp->ki_start.tv_usec;
761 #endif
762 bestidx = i;
763 }
764
765 memset(selected, 0, nproc);
766 if (bestidx != -1)
767 selected[bestidx] = 1;
768 }
769
770 /*
771 * Take the appropriate action for each matched process, if any.
772 */
773 did_action = 0;
774 #ifdef __APPLE__
775 for (i = 0, rv = 0; i < nproc; i++) {
776 kp = sysmon_table_get_row(plist, i);
777 #else
778 for (i = 0, rv = 0, kp = plist; i < nproc; i++, kp++) {
779 #endif
780 if (PSKIP(kp))
781 continue;
782 if (selected[i]) {
783 if (longfmt && !pgrep) {
784 did_action = 1;
785 #ifdef __APPLE__
786 printf("kill -%d %d\n", signum, (int)xpc_uint64_get_value(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_PID)));
787 #else
788 printf("kill -%d %d\n", signum, kp->ki_pid);
789 #endif
790 }
791 if (inverse)
792 continue;
793 } else if (!inverse)
794 continue;
795 rv |= (*action)(kp);
796 }
797 if (!did_action && !pgrep && longfmt)
798 fprintf(stderr,
799 "No matching processes belonging to you were found\n");
800
801 exit(rv ? STATUS_MATCH : STATUS_NOMATCH);
802 }
803
804 static void
805 usage(void)
806 {
807 const char *ustr;
808
809 if (pgrep)
810 #ifdef __APPLE__
811 ustr = "[-Lfilnoqvx] [-d delim]";
812 #else
813 ustr = "[-LSfilnoqvx] [-d delim]";
814 #endif
815 else
816 ustr = "[-signal] [-ILfilnovx]";
817
818 fprintf(stderr,
819 #ifdef __APPLE__
820 "usage: %s %s [-F pidfile] [-G gid]\n"
821 " [-P ppid] [-U uid] [-g pgrp]\n"
822 #else
823 "usage: %s %s [-F pidfile] [-G gid] [-M core] [-N system]\n"
824 " [-P ppid] [-U uid] [-g pgrp] [-j jid] [-s sid]\n"
825 #endif
826 " [-t tty] [-u euid] pattern ...\n", getprogname(),
827 ustr);
828
829 exit(STATUS_BADUSAGE);
830 }
831
832 static void
833 #ifdef __APPLE__
834 show_process(const sysmon_row_t kp)
835 #else
836 show_process(const struct kinfo_proc *kp)
837 #endif
838 {
839 #ifdef __APPLE__
840 xpc_object_t argv;
841 #else
842 char **argv;
843 #endif
844
845 if (quiet) {
846 assert(pgrep);
847 return;
848 }
849 #ifdef __APPLE__
850 if ((longfmt || !pgrep) && matchargs &&
851 (argv = sysmon_row_get_value(kp, SYSMON_ATTR_PROC_ARGUMENTS)) != NULL) {
852 printf("%d ", (int)xpc_uint64_get_value(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_PID)));
853 (void)xpc_array_apply(argv, ^(size_t index, xpc_object_t value) {
854 printf("%s", xpc_string_get_string_ptr(value));
855 if (index < xpc_array_get_count(argv) - 1)
856 putchar(' ');
857 return (bool)true;
858 });
859 } else if (longfmt || !pgrep)
860 printf("%d %s",
861 (int)xpc_uint64_get_value(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_PID)),
862 xpc_string_get_string_ptr(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_COMM)));
863 else
864 printf("%d", (int)xpc_uint64_get_value(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_PID)));
865 #else
866 if ((longfmt || !pgrep) && matchargs &&
867 (argv = kvm_getargv(kd, kp, 0)) != NULL) {
868 printf("%d ", (int)kp->ki_pid);
869 for (; *argv != NULL; argv++) {
870 printf("%s", *argv);
871 if (argv[1] != NULL)
872 putchar(' ');
873 }
874 } else if (longfmt || !pgrep)
875 printf("%d %s", (int)kp->ki_pid, kp->ki_comm);
876 else
877 printf("%d", (int)kp->ki_pid);
878 #endif
879 }
880
881 static int
882 #ifdef __APPLE__
883 killact(const sysmon_row_t kp)
884 #else
885 killact(const struct kinfo_proc *kp)
886 #endif
887 {
888 int ch, first;
889
890 if (interactive) {
891 /*
892 * Be careful, ask before killing.
893 */
894 printf("kill ");
895 show_process(kp);
896 printf("? ");
897 fflush(stdout);
898 first = ch = getchar();
899 while (ch != '\n' && ch != EOF)
900 ch = getchar();
901 if (first != 'y' && first != 'Y')
902 return (1);
903 }
904 #ifdef __APPLE__
905 if (kill((pid_t)xpc_uint64_get_value(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_PID)), signum) == -1) {
906 #else
907 if (kill(kp->ki_pid, signum) == -1) {
908 #endif
909 /*
910 * Check for ESRCH, which indicates that the process
911 * disappeared between us matching it and us
912 * signalling it; don't issue a warning about it.
913 */
914 if (errno != ESRCH)
915 #ifdef __APPLE__
916 warn("signalling pid %d", (int)xpc_uint64_get_value(sysmon_row_get_value(kp, SYSMON_ATTR_PROC_PID)));
917 #else
918 warn("signalling pid %d", (int)kp->ki_pid);
919 #endif
920 /*
921 * Return 0 to indicate that the process should not be
922 * considered a match, since we didn't actually get to
923 * signal it.
924 */
925 return (0);
926 }
927 return (1);
928 }
929
930 static int
931 #ifdef __APPLE__
932 grepact(const sysmon_row_t kp)
933 #else
934 grepact(const struct kinfo_proc *kp)
935 #endif
936 {
937
938 show_process(kp);
939 if (!quiet)
940 printf("%s", delim);
941 return (1);
942 }
943
944 static void
945 makelist(struct listhead *head, enum listtype type, char *src)
946 {
947 struct list *li;
948 struct passwd *pw;
949 struct group *gr;
950 struct stat st;
951 const char *cp;
952 char *sp, *ep, buf[MAXPATHLEN];
953 int empty;
954
955 empty = 1;
956
957 while ((sp = strsep(&src, ",")) != NULL) {
958 if (*sp == '\0')
959 usage();
960
961 if ((li = malloc(sizeof(*li))) == NULL) {
962 err(STATUS_ERROR, "Cannot allocate %zu bytes",
963 sizeof(*li));
964 }
965
966 SLIST_INSERT_HEAD(head, li, li_chain);
967 empty = 0;
968
969 li->li_number = (uid_t)strtol(sp, &ep, 0);
970 if (*ep == '\0') {
971 switch (type) {
972 case LT_PGRP:
973 if (li->li_number == 0)
974 li->li_number = getpgrp();
975 break;
976 #ifndef __APPLE__
977 case LT_SID:
978 if (li->li_number == 0)
979 li->li_number = getsid(mypid);
980 break;
981 case LT_JID:
982 if (li->li_number < 0)
983 errx(STATUS_BADUSAGE,
984 "Negative jail ID `%s'", sp);
985 /* For compatibility with old -j */
986 if (li->li_number == 0)
987 li->li_number = -1; /* any jail */
988 break;
989 #endif /* !__APPLE__ */
990 case LT_TTY:
991 if (li->li_number < 0)
992 errx(STATUS_BADUSAGE,
993 "Negative /dev/pts tty `%s'", sp);
994 snprintf(buf, sizeof(buf), _PATH_DEV "pts/%s",
995 sp);
996 if (stat(buf, &st) != -1)
997 goto foundtty;
998 if (errno == ENOENT)
999 errx(STATUS_BADUSAGE, "No such tty: `"
1000 _PATH_DEV "pts/%s'", sp);
1001 err(STATUS_ERROR, "Cannot access `"
1002 _PATH_DEV "pts/%s'", sp);
1003 break;
1004 default:
1005 break;
1006 }
1007 continue;
1008 }
1009
1010 switch (type) {
1011 case LT_USER:
1012 if ((pw = getpwnam(sp)) == NULL)
1013 errx(STATUS_BADUSAGE, "Unknown user `%s'", sp);
1014 li->li_number = pw->pw_uid;
1015 break;
1016 case LT_GROUP:
1017 if ((gr = getgrnam(sp)) == NULL)
1018 errx(STATUS_BADUSAGE, "Unknown group `%s'", sp);
1019 li->li_number = gr->gr_gid;
1020 break;
1021 case LT_TTY:
1022 if (strcmp(sp, "-") == 0) {
1023 li->li_number = -1;
1024 break;
1025 } else if (strcmp(sp, "co") == 0) {
1026 cp = "console";
1027 } else {
1028 cp = sp;
1029 }
1030
1031 snprintf(buf, sizeof(buf), _PATH_DEV "%s", cp);
1032 if (stat(buf, &st) != -1)
1033 goto foundtty;
1034
1035 snprintf(buf, sizeof(buf), _PATH_DEV "tty%s", cp);
1036 if (stat(buf, &st) != -1)
1037 goto foundtty;
1038
1039 if (errno == ENOENT)
1040 errx(STATUS_BADUSAGE, "No such tty: `%s'", sp);
1041 err(STATUS_ERROR, "Cannot access `%s'", sp);
1042
1043 foundtty: if ((st.st_mode & S_IFCHR) == 0)
1044 errx(STATUS_BADUSAGE, "Not a tty: `%s'", sp);
1045
1046 li->li_number = st.st_rdev;
1047 break;
1048 #ifndef __APPLE__
1049 case LT_JID:
1050 if (strcmp(sp, "none") == 0)
1051 li->li_number = 0;
1052 else if (strcmp(sp, "any") == 0)
1053 li->li_number = -1;
1054 else if (*ep != '\0')
1055 errx(STATUS_BADUSAGE,
1056 "Invalid jail ID `%s'", sp);
1057 break;
1058 #endif /* !__APPLE__ */
1059 default:
1060 usage();
1061 }
1062 }
1063
1064 if (empty)
1065 usage();
1066 }
1067
1068 static int
1069 takepid(const char *pidfile, int pidfilelock)
1070 {
1071 char *endp, line[BUFSIZ];
1072 FILE *fh;
1073 long rval;
1074
1075 fh = fopen(pidfile, "r");
1076 if (fh == NULL)
1077 err(STATUS_ERROR, "Cannot open pidfile `%s'", pidfile);
1078
1079 if (pidfilelock) {
1080 /*
1081 * If we can lock pidfile, this means that daemon is not
1082 * running, so would be better not to kill some random process.
1083 */
1084 if (flock(fileno(fh), LOCK_EX | LOCK_NB) == 0) {
1085 (void)fclose(fh);
1086 errx(STATUS_ERROR, "File '%s' can be locked", pidfile);
1087 } else {
1088 if (errno != EWOULDBLOCK) {
1089 errx(STATUS_ERROR,
1090 "Error while locking file '%s'", pidfile);
1091 }
1092 }
1093 }
1094
1095 if (fgets(line, sizeof(line), fh) == NULL) {
1096 if (feof(fh)) {
1097 (void)fclose(fh);
1098 errx(STATUS_ERROR, "Pidfile `%s' is empty", pidfile);
1099 }
1100 (void)fclose(fh);
1101 err(STATUS_ERROR, "Cannot read from pid file `%s'", pidfile);
1102 }
1103 (void)fclose(fh);
1104
1105 rval = strtol(line, &endp, 10);
1106 if (*endp != '\0' && !isspace((unsigned char)*endp))
1107 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);
1108 else if (rval < MIN_PID || rval > MAX_PID)
1109 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);
1110 return (rval);
1111 }