1 /* $NetBSD: pkill.c,v 1.16 2005/10/10 22:13:20 kleink Exp $ */ 2 3 /*- 4 * Copyright (c) 2002 The NetBSD Foundation, Inc. 5 * Copyright (c) 2005 Pawel Jakub Dawidek <pjd@FreeBSD.org> 6 * All rights reserved. 7 * 8 * This code is derived from software contributed to The NetBSD Foundation 9 * by Andrew Doran. 10 * 11 * Redistribution and use in source and binary forms, with or without 12 * modification, are permitted provided that the following conditions 13 * are met: 14 * 1. Redistributions of source code must retain the above copyright 15 * notice, this list of conditions and the following disclaimer. 16 * 2. Redistributions in binary form must reproduce the above copyright 17 * notice, this list of conditions and the following disclaimer in the 18 * documentation and/or other materials provided with the distribution. 19 * 3. All advertising materials mentioning features or use of this software 20 * must display the following acknowledgement: 21 * This product includes software developed by the NetBSD 22 * Foundation, Inc. and its contributors. 23 * 4. Neither the name of The NetBSD Foundation nor the names of its 24 * contributors may be used to endorse or promote products derived 25 * from this software without specific prior written permission. 26 * 27 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 28 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 29 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 30 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 31 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 32 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 33 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 34 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 35 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 36 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 37 * POSSIBILITY OF SUCH DAMAGE. 38 */ 39 40 #include <sys/cdefs.h> 41 __FBSDID("$FreeBSD$"); 42 43 #include <sys/types.h> 44 #include <sys/param.h> 45 #include <sys/sysctl.h> 46 #include <sys/proc.h> 47 #include <sys/queue.h> 48 #include <sys/stat.h> 49 #include <sys/time.h> 50 #include <sys/user.h> 51 52 #include <stdio.h> 53 #include <stdlib.h> 54 #include <limits.h> 55 #include <paths.h> 56 #include <string.h> 57 #include <unistd.h> 58 #include <signal.h> 59 #include <regex.h> 60 #include <ctype.h> 61 #include <fcntl.h> 62 #include <kvm.h> 63 #include <err.h> 64 #include <pwd.h> 65 #include <grp.h> 66 #include <errno.h> 67 #include <locale.h> 68 69 #define STATUS_MATCH 0 70 #define STATUS_NOMATCH 1 71 #define STATUS_BADUSAGE 2 72 #define STATUS_ERROR 3 73 74 #define MIN_PID 5 75 #define MAX_PID 99999 76 77 /* Ignore system-processes (if '-S' flag is not specified) and myself. */ 78 #define PSKIP(kp) ((kp)->ki_pid == mypid || \ 79 (!kthreads && ((kp)->ki_flag & P_KTHREAD) != 0)) 80 81 enum listtype { 82 LT_GENERIC, 83 LT_USER, 84 LT_GROUP, 85 LT_TTY, 86 LT_PGRP, 87 LT_JID, 88 LT_SID 89 }; 90 91 struct list { 92 SLIST_ENTRY(list) li_chain; 93 long li_number; 94 }; 95 96 SLIST_HEAD(listhead, list); 97 98 static struct kinfo_proc *plist; 99 static char *selected; 100 static const char *delim = "\n"; 101 static int nproc; 102 static int pgrep; 103 static int signum = SIGTERM; 104 static int newest; 105 static int oldest; 106 static int interactive; 107 static int inverse; 108 static int longfmt; 109 static int matchargs; 110 static int fullmatch; 111 static int kthreads; 112 static int cflags = REG_EXTENDED; 113 static kvm_t *kd; 114 static pid_t mypid; 115 116 static struct listhead euidlist = SLIST_HEAD_INITIALIZER(list); 117 static struct listhead ruidlist = SLIST_HEAD_INITIALIZER(list); 118 static struct listhead rgidlist = SLIST_HEAD_INITIALIZER(list); 119 static struct listhead pgrplist = SLIST_HEAD_INITIALIZER(list); 120 static struct listhead ppidlist = SLIST_HEAD_INITIALIZER(list); 121 static struct listhead tdevlist = SLIST_HEAD_INITIALIZER(list); 122 static struct listhead sidlist = SLIST_HEAD_INITIALIZER(list); 123 static struct listhead jidlist = SLIST_HEAD_INITIALIZER(list); 124 125 static void usage(void) __attribute__((__noreturn__)); 126 static int killact(const struct kinfo_proc *); 127 static int grepact(const struct kinfo_proc *); 128 static void makelist(struct listhead *, enum listtype, char *); 129 static int takepid(const char *, int); 130 131 int 132 main(int argc, char **argv) 133 { 134 char buf[_POSIX2_LINE_MAX], *mstr, **pargv, *p, *q, *pidfile; 135 const char *execf, *coref; 136 int debug_opt; 137 int i, ch, bestidx, rv, criteria, pidfromfile, pidfilelock; 138 size_t jsz; 139 int (*action)(const struct kinfo_proc *); 140 struct kinfo_proc *kp; 141 struct list *li; 142 struct timeval best_tval; 143 regex_t reg; 144 regmatch_t regmatch; 145 146 setlocale(LC_ALL, ""); 147 148 if (strcmp(getprogname(), "pgrep") == 0) { 149 action = grepact; 150 pgrep = 1; 151 } else { 152 action = killact; 153 p = argv[1]; 154 155 if (argc > 1 && p[0] == '-') { 156 p++; 157 i = (int)strtol(p, &q, 10); 158 if (*q == '\0') { 159 signum = i; 160 argv++; 161 argc--; 162 } else { 163 if (strncasecmp(p, "sig", 3) == 0) 164 p += 3; 165 for (i = 1; i < NSIG; i++) 166 if (strcasecmp(sys_signame[i], p) == 0) 167 break; 168 if (i != NSIG) { 169 signum = i; 170 argv++; 171 argc--; 172 } 173 } 174 } 175 } 176 177 criteria = 0; 178 debug_opt = 0; 179 pidfile = NULL; 180 pidfilelock = 0; 181 execf = coref = _PATH_DEVNULL; 182 183 while ((ch = getopt(argc, argv, "DF:G:ILM:N:P:SU:d:fg:ij:lnos: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 'd': 224 if (!pgrep) 225 usage(); 226 delim = optarg; 227 break; 228 case 'f': 229 matchargs = 1; 230 break; 231 case 'g': 232 makelist(&pgrplist, LT_PGRP, optarg); 233 criteria = 1; 234 break; 235 case 'i': 236 cflags |= REG_ICASE; 237 break; 238 case 'j': 239 makelist(&jidlist, LT_JID, optarg); 240 criteria = 1; 241 break; 242 case 'l': 243 if (!pgrep) 244 usage(); 245 longfmt = 1; 246 break; 247 case 'n': 248 newest = 1; 249 criteria = 1; 250 break; 251 case 'o': 252 oldest = 1; 253 criteria = 1; 254 break; 255 case 's': 256 makelist(&sidlist, LT_SID, optarg); 257 criteria = 1; 258 break; 259 case 't': 260 makelist(&tdevlist, LT_TTY, optarg); 261 criteria = 1; 262 break; 263 case 'u': 264 makelist(&euidlist, LT_USER, optarg); 265 criteria = 1; 266 break; 267 case 'v': 268 inverse = 1; 269 break; 270 case 'x': 271 fullmatch = 1; 272 break; 273 default: 274 usage(); 275 /* NOTREACHED */ 276 } 277 278 argc -= optind; 279 argv += optind; 280 if (argc != 0) 281 criteria = 1; 282 if (!criteria) 283 usage(); 284 if (newest && oldest) 285 errx(STATUS_ERROR, "Options -n and -o are mutually exclusive"); 286 if (pidfile != NULL) 287 pidfromfile = takepid(pidfile, pidfilelock); 288 else { 289 if (pidfilelock) { 290 errx(STATUS_ERROR, 291 "Option -L doesn't make sense without -F"); 292 } 293 pidfromfile = -1; 294 } 295 296 mypid = getpid(); 297 298 /* 299 * Retrieve the list of running processes from the kernel. 300 */ 301 kd = kvm_openfiles(execf, coref, NULL, O_RDONLY, buf); 302 if (kd == NULL) 303 errx(STATUS_ERROR, "Cannot open kernel files (%s)", buf); 304 305 /* 306 * Use KERN_PROC_PROC instead of KERN_PROC_ALL, since we 307 * just want processes and not individual kernel threads. 308 */ 309 plist = kvm_getprocs(kd, KERN_PROC_PROC, 0, &nproc); 310 if (plist == NULL) { 311 errx(STATUS_ERROR, "Cannot get process list (%s)", 312 kvm_geterr(kd)); 313 } 314 315 /* 316 * Allocate memory which will be used to keep track of the 317 * selection. 318 */ 319 if ((selected = malloc(nproc)) == NULL) { 320 err(STATUS_ERROR, "Cannot allocate memory for %d processes", 321 nproc); 322 } 323 memset(selected, 0, nproc); 324 325 /* 326 * Refine the selection. 327 */ 328 for (; *argv != NULL; argv++) { 329 if ((rv = regcomp(®, *argv, cflags)) != 0) { 330 regerror(rv, ®, buf, sizeof(buf)); 331 errx(STATUS_BADUSAGE, 332 "Cannot compile regular expression `%s' (%s)", 333 *argv, buf); 334 } 335 336 for (i = 0, kp = plist; i < nproc; i++, kp++) { 337 if (PSKIP(kp)) { 338 if (debug_opt > 0) 339 fprintf(stderr, "* Skipped %5d %3d %s\n", 340 kp->ki_pid, kp->ki_uid, kp->ki_comm); 341 continue; 342 } 343 344 if (matchargs && 345 (pargv = kvm_getargv(kd, kp, 0)) != NULL) { 346 jsz = 0; 347 while (jsz < sizeof(buf) && *pargv != NULL) { 348 jsz += snprintf(buf + jsz, 349 sizeof(buf) - jsz, 350 pargv[1] != NULL ? "%s " : "%s", 351 pargv[0]); 352 pargv++; 353 } 354 mstr = buf; 355 } else 356 mstr = kp->ki_comm; 357 358 rv = regexec(®, mstr, 1, ®match, 0); 359 if (rv == 0) { 360 if (fullmatch) { 361 if (regmatch.rm_so == 0 && 362 regmatch.rm_eo == 363 (off_t)strlen(mstr)) 364 selected[i] = 1; 365 } else 366 selected[i] = 1; 367 } else if (rv != REG_NOMATCH) { 368 regerror(rv, ®, buf, sizeof(buf)); 369 errx(STATUS_ERROR, 370 "Regular expression evaluation error (%s)", 371 buf); 372 } 373 if (debug_opt > 1) { 374 const char *rv_res = "NoMatch"; 375 if (selected[i]) 376 rv_res = "Matched"; 377 fprintf(stderr, "* %s %5d %3d %s\n", rv_res, 378 kp->ki_pid, kp->ki_uid, mstr); 379 } 380 } 381 382 regfree(®); 383 } 384 385 for (i = 0, kp = plist; i < nproc; i++, kp++) { 386 if (PSKIP(kp)) 387 continue; 388 389 if (pidfromfile >= 0 && kp->ki_pid != pidfromfile) { 390 selected[i] = 0; 391 continue; 392 } 393 394 SLIST_FOREACH(li, &ruidlist, li_chain) 395 if (kp->ki_ruid == (uid_t)li->li_number) 396 break; 397 if (SLIST_FIRST(&ruidlist) != NULL && li == NULL) { 398 selected[i] = 0; 399 continue; 400 } 401 402 SLIST_FOREACH(li, &rgidlist, li_chain) 403 if (kp->ki_rgid == (gid_t)li->li_number) 404 break; 405 if (SLIST_FIRST(&rgidlist) != NULL && li == NULL) { 406 selected[i] = 0; 407 continue; 408 } 409 410 SLIST_FOREACH(li, &euidlist, li_chain) 411 if (kp->ki_uid == (uid_t)li->li_number) 412 break; 413 if (SLIST_FIRST(&euidlist) != NULL && li == NULL) { 414 selected[i] = 0; 415 continue; 416 } 417 418 SLIST_FOREACH(li, &ppidlist, li_chain) 419 if (kp->ki_ppid == (pid_t)li->li_number) 420 break; 421 if (SLIST_FIRST(&ppidlist) != NULL && li == NULL) { 422 selected[i] = 0; 423 continue; 424 } 425 426 SLIST_FOREACH(li, &pgrplist, li_chain) 427 if (kp->ki_pgid == (pid_t)li->li_number) 428 break; 429 if (SLIST_FIRST(&pgrplist) != NULL && li == NULL) { 430 selected[i] = 0; 431 continue; 432 } 433 434 SLIST_FOREACH(li, &tdevlist, li_chain) { 435 if (li->li_number == -1 && 436 (kp->ki_flag & P_CONTROLT) == 0) 437 break; 438 if (kp->ki_tdev == (dev_t)li->li_number) 439 break; 440 } 441 if (SLIST_FIRST(&tdevlist) != NULL && li == NULL) { 442 selected[i] = 0; 443 continue; 444 } 445 446 SLIST_FOREACH(li, &sidlist, li_chain) 447 if (kp->ki_sid == (pid_t)li->li_number) 448 break; 449 if (SLIST_FIRST(&sidlist) != NULL && li == NULL) { 450 selected[i] = 0; 451 continue; 452 } 453 454 SLIST_FOREACH(li, &jidlist, li_chain) { 455 /* A particular jail ID, including 0 (not in jail) */ 456 if (kp->ki_jid == (int)li->li_number) 457 break; 458 /* Any jail */ 459 if (kp->ki_jid > 0 && li->li_number == -1) 460 break; 461 } 462 if (SLIST_FIRST(&jidlist) != NULL && li == NULL) { 463 selected[i] = 0; 464 continue; 465 } 466 467 if (argc == 0) 468 selected[i] = 1; 469 } 470 471 if (newest || oldest) { 472 best_tval.tv_sec = 0; 473 best_tval.tv_usec = 0; 474 bestidx = -1; 475 476 for (i = 0, kp = plist; i < nproc; i++, kp++) { 477 if (!selected[i]) 478 continue; 479 if (bestidx == -1) { 480 /* The first entry of the list which matched. */ 481 ; 482 } else if (timercmp(&kp->ki_start, &best_tval, >)) { 483 /* This entry is newer than previous "best". */ 484 if (oldest) /* but we want the oldest */ 485 continue; 486 } else { 487 /* This entry is older than previous "best". */ 488 if (newest) /* but we want the newest */ 489 continue; 490 } 491 /* This entry is better than previous "best" entry. */ 492 best_tval.tv_sec = kp->ki_start.tv_sec; 493 best_tval.tv_usec = kp->ki_start.tv_usec; 494 bestidx = i; 495 } 496 497 memset(selected, 0, nproc); 498 if (bestidx != -1) 499 selected[bestidx] = 1; 500 } 501 502 /* 503 * Take the appropriate action for each matched process, if any. 504 */ 505 for (i = 0, rv = 0, kp = plist; i < nproc; i++, kp++) { 506 if (PSKIP(kp)) 507 continue; 508 if (selected[i]) { 509 if (inverse) 510 continue; 511 } else if (!inverse) 512 continue; 513 rv |= (*action)(kp); 514 } 515 516 exit(rv ? STATUS_MATCH : STATUS_NOMATCH); 517 } 518 519 static void 520 usage(void) 521 { 522 const char *ustr; 523 524 if (pgrep) 525 ustr = "[-LSfilnovx] [-d delim]"; 526 else 527 ustr = "[-signal] [-ILfinovx]"; 528 529 fprintf(stderr, 530 "usage: %s %s [-F pidfile] [-G gid] [-M core] [-N system]\n" 531 " [-P ppid] [-U uid] [-g pgrp] [-j jid] [-s sid]\n" 532 " [-t tty] [-u euid] pattern ...\n", getprogname(), 533 ustr); 534 535 exit(STATUS_BADUSAGE); 536 } 537 538 static void 539 show_process(const struct kinfo_proc *kp) 540 { 541 char **argv; 542 543 if ((longfmt || !pgrep) && matchargs && 544 (argv = kvm_getargv(kd, kp, 0)) != NULL) { 545 printf("%d ", (int)kp->ki_pid); 546 for (; *argv != NULL; argv++) { 547 printf("%s", *argv); 548 if (argv[1] != NULL) 549 putchar(' '); 550 } 551 } else if (longfmt || !pgrep) 552 printf("%d %s", (int)kp->ki_pid, kp->ki_comm); 553 else 554 printf("%d", (int)kp->ki_pid); 555 } 556 557 static int 558 killact(const struct kinfo_proc *kp) 559 { 560 int ch, first; 561 562 if (interactive) { 563 /* 564 * Be careful, ask before killing. 565 */ 566 printf("kill "); 567 show_process(kp); 568 printf("? "); 569 fflush(stdout); 570 first = ch = getchar(); 571 while (ch != '\n' && ch != EOF) 572 ch = getchar(); 573 if (first != 'y' && first != 'Y') 574 return (1); 575 } 576 if (kill(kp->ki_pid, signum) == -1) { 577 /* 578 * Check for ESRCH, which indicates that the process 579 * disappeared between us matching it and us 580 * signalling it; don't issue a warning about it. 581 */ 582 if (errno != ESRCH) 583 warn("signalling pid %d", (int)kp->ki_pid); 584 /* 585 * Return 0 to indicate that the process should not be 586 * considered a match, since we didn't actually get to 587 * signal it. 588 */ 589 return (0); 590 } 591 return (1); 592 } 593 594 static int 595 grepact(const struct kinfo_proc *kp) 596 { 597 598 show_process(kp); 599 printf("%s", delim); 600 return (1); 601 } 602 603 static void 604 makelist(struct listhead *head, enum listtype type, char *src) 605 { 606 struct list *li; 607 struct passwd *pw; 608 struct group *gr; 609 struct stat st; 610 const char *cp; 611 char *sp, *ep, buf[MAXPATHLEN]; 612 int empty; 613 614 empty = 1; 615 616 while ((sp = strsep(&src, ",")) != NULL) { 617 if (*sp == '\0') 618 usage(); 619 620 if ((li = malloc(sizeof(*li))) == NULL) { 621 err(STATUS_ERROR, "Cannot allocate %zu bytes", 622 sizeof(*li)); 623 } 624 625 SLIST_INSERT_HEAD(head, li, li_chain); 626 empty = 0; 627 628 li->li_number = (uid_t)strtol(sp, &ep, 0); 629 if (*ep == '\0') { 630 switch (type) { 631 case LT_PGRP: 632 if (li->li_number == 0) 633 li->li_number = getpgrp(); 634 break; 635 case LT_SID: 636 if (li->li_number == 0) 637 li->li_number = getsid(mypid); 638 break; 639 case LT_JID: 640 if (li->li_number < 0) 641 errx(STATUS_BADUSAGE, 642 "Negative jail ID `%s'", sp); 643 /* For compatibility with old -j */ 644 if (li->li_number == 0) 645 li->li_number = -1; /* any jail */ 646 break; 647 case LT_TTY: 648 usage(); 649 /* NOTREACHED */ 650 default: 651 break; 652 } 653 continue; 654 } 655 656 switch (type) { 657 case LT_USER: 658 if ((pw = getpwnam(sp)) == NULL) 659 errx(STATUS_BADUSAGE, "Unknown user `%s'", sp); 660 li->li_number = pw->pw_uid; 661 break; 662 case LT_GROUP: 663 if ((gr = getgrnam(sp)) == NULL) 664 errx(STATUS_BADUSAGE, "Unknown group `%s'", sp); 665 li->li_number = gr->gr_gid; 666 break; 667 case LT_TTY: 668 if (strcmp(sp, "-") == 0) { 669 li->li_number = -1; 670 break; 671 } else if (strcmp(sp, "co") == 0) { 672 cp = "console"; 673 } else { 674 cp = sp; 675 } 676 677 snprintf(buf, sizeof(buf), _PATH_DEV "%s", cp); 678 if (stat(buf, &st) != -1) 679 goto foundtty; 680 681 snprintf(buf, sizeof(buf), _PATH_DEV "tty%s", cp); 682 if (stat(buf, &st) != -1) 683 goto foundtty; 684 685 if (errno == ENOENT) 686 errx(STATUS_BADUSAGE, "No such tty: `%s'", sp); 687 err(STATUS_ERROR, "Cannot access `%s'", sp); 688 689 foundtty: if ((st.st_mode & S_IFCHR) == 0) 690 errx(STATUS_BADUSAGE, "Not a tty: `%s'", sp); 691 692 li->li_number = st.st_rdev; 693 break; 694 case LT_JID: 695 if (strcmp(sp, "none") == 0) 696 li->li_number = 0; 697 else if (strcmp(sp, "any") == 0) 698 li->li_number = -1; 699 else if (*ep != '\0') 700 errx(STATUS_BADUSAGE, 701 "Invalid jail ID `%s'", sp); 702 break; 703 default: 704 usage(); 705 } 706 } 707 708 if (empty) 709 usage(); 710 } 711 712 static int 713 takepid(const char *pidfile, int pidfilelock) 714 { 715 char *endp, line[BUFSIZ]; 716 FILE *fh; 717 long rval; 718 719 fh = fopen(pidfile, "r"); 720 if (fh == NULL) 721 err(STATUS_ERROR, "Cannot open pidfile `%s'", pidfile); 722 723 if (pidfilelock) { 724 /* 725 * If we can lock pidfile, this means that daemon is not 726 * running, so would be better not to kill some random process. 727 */ 728 if (flock(fileno(fh), LOCK_EX | LOCK_NB) == 0) { 729 (void)fclose(fh); 730 errx(STATUS_ERROR, "File '%s' can be locked", pidfile); 731 } else { 732 if (errno != EWOULDBLOCK) { 733 errx(STATUS_ERROR, 734 "Error while locking file '%s'", pidfile); 735 } 736 } 737 } 738 739 if (fgets(line, sizeof(line), fh) == NULL) { 740 if (feof(fh)) { 741 (void)fclose(fh); 742 errx(STATUS_ERROR, "Pidfile `%s' is empty", pidfile); 743 } 744 (void)fclose(fh); 745 err(STATUS_ERROR, "Cannot read from pid file `%s'", pidfile); 746 } 747 (void)fclose(fh); 748 749 rval = strtol(line, &endp, 10); 750 if (*endp != '\0' && !isspace((unsigned char)*endp)) 751 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile); 752 else if (rval < MIN_PID || rval > MAX_PID) 753 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile); 754 return (rval); 755 } 756