Home | History | Annotate | Line # | Download | only in pkill
pkill.c revision 1.4
      1 /*	$NetBSD: pkill.c,v 1.4 2002/03/06 12:02:18 ad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2002 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Andrew Doran.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *	This product includes software developed by the NetBSD
     21  *	Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 #ifndef lint
     41 __RCSID("$NetBSD: pkill.c,v 1.4 2002/03/06 12:02:18 ad Exp $");
     42 #endif /* !lint */
     43 
     44 #include <sys/types.h>
     45 #include <sys/param.h>
     46 #include <sys/sysctl.h>
     47 #include <sys/proc.h>
     48 #include <sys/queue.h>
     49 #include <sys/stat.h>
     50 
     51 #include <stdio.h>
     52 #include <stdlib.h>
     53 #include <limits.h>
     54 #include <string.h>
     55 #include <unistd.h>
     56 #include <signal.h>
     57 #include <regex.h>
     58 #include <ctype.h>
     59 #include <kvm.h>
     60 #include <err.h>
     61 #include <pwd.h>
     62 #include <grp.h>
     63 #include <errno.h>
     64 
     65 #define	STATUS_MATCH	0
     66 #define	STATUS_NOMATCH	1
     67 #define	STATUS_BADUSAGE	2
     68 #define	STATUS_ERROR	3
     69 
     70 enum listtype {
     71 	LT_GENERIC,
     72 	LT_USER,
     73 	LT_GROUP,
     74 	LT_TTY,
     75 	LT_PGRP,
     76 	LT_SID
     77 };
     78 
     79 struct list {
     80 	SLIST_ENTRY(list) li_chain;
     81 	long	li_number;
     82 };
     83 
     84 SLIST_HEAD(listhead, list);
     85 
     86 struct kinfo_proc2	*plist;
     87 char	*selected;
     88 char	*delim = "\n";
     89 int	nproc;
     90 int	pgrep;
     91 int	signum = SIGTERM;
     92 int	newest;
     93 int	inverse;
     94 int	longfmt;
     95 int	matchargs;
     96 int	fullmatch;
     97 kvm_t	*kd;
     98 pid_t	mypid;
     99 
    100 struct listhead euidlist = SLIST_HEAD_INITIALIZER(list);
    101 struct listhead ruidlist = SLIST_HEAD_INITIALIZER(list);
    102 struct listhead rgidlist = SLIST_HEAD_INITIALIZER(list);
    103 struct listhead pgrplist = SLIST_HEAD_INITIALIZER(list);
    104 struct listhead ppidlist = SLIST_HEAD_INITIALIZER(list);
    105 struct listhead tdevlist = SLIST_HEAD_INITIALIZER(list);
    106 struct listhead sidlist = SLIST_HEAD_INITIALIZER(list);
    107 
    108 int	main(int, char **);
    109 void	usage(void);
    110 void	killact(struct kinfo_proc2 *);
    111 void	grepact(struct kinfo_proc2 *);
    112 void	makelist(struct listhead *, enum listtype, char *);
    113 
    114 int
    115 main(int argc, char **argv)
    116 {
    117 	extern char *optarg;
    118 	extern int optind;
    119 	char buf[_POSIX2_LINE_MAX], *mstr, **pargv, *p, *q;
    120 	int i, j, ch, bestidx, rv, criteria;
    121 	void (*action)(struct kinfo_proc2 *);
    122 	struct kinfo_proc2 *kp;
    123 	struct list *li;
    124 	u_int32_t bestsec, bestusec;
    125 	regex_t reg;
    126 	regmatch_t regmatch;
    127 
    128 	if (strcmp(getprogname(), "pgrep") == 0) {
    129 		action = grepact;
    130 		pgrep = 1;
    131 	} else {
    132 		action = killact;
    133 		p = argv[1];
    134 
    135 		if (argc > 1 && p[0] == '-') {
    136 			p++;
    137 			i = (int)strtol(p, &q, 10);
    138 			if (*q == '\0') {
    139 				signum = i;
    140 				argv++;
    141 				argc--;
    142 			} else {
    143 				if (strncasecmp(p, "sig", 3) == 0)
    144 					p += 3;
    145 				for (i = 1; i < NSIG; i++)
    146 					if (strcasecmp(sys_signame[i], p) == 0)
    147 						break;
    148 				if (i != NSIG) {
    149 					signum = i;
    150 					argv++;
    151 					argc--;
    152 				}
    153 			}
    154 		}
    155 	}
    156 
    157 	criteria = 0;
    158 
    159 	while ((ch = getopt(argc, argv, "G:P:U:d:fg:lns:t:vx")) != -1)
    160 		switch (ch) {
    161 		case 'G':
    162 			makelist(&rgidlist, LT_GROUP, optarg);
    163 			criteria = 1;
    164 			break;
    165 		case 'P':
    166 			makelist(&ppidlist, LT_GENERIC, optarg);
    167 			criteria = 1;
    168 			break;
    169 		case 'U':
    170 			makelist(&ruidlist, LT_USER, optarg);
    171 			criteria = 1;
    172 			break;
    173 		case 'd':
    174 			if (!pgrep)
    175 				usage();
    176 			delim = optarg;
    177 			break;
    178 		case 'f':
    179 			matchargs = 1;
    180 			break;
    181 		case 'g':
    182 			makelist(&pgrplist, LT_PGRP, optarg);
    183 			criteria = 1;
    184 			break;
    185 		case 'l':
    186 			if (!pgrep)
    187 				usage();
    188 			longfmt = 1;
    189 			break;
    190 		case 'n':
    191 			newest = 1;
    192 			criteria = 1;
    193 			break;
    194 		case 's':
    195 			makelist(&sidlist, LT_SID, optarg);
    196 			criteria = 1;
    197 			break;
    198 		case 't':
    199 			makelist(&tdevlist, LT_TTY, optarg);
    200 			criteria = 1;
    201 			break;
    202 		case 'u':
    203 			makelist(&euidlist, LT_USER, optarg);
    204 			criteria = 1;
    205 			break;
    206 		case 'v':
    207 			inverse = 1;
    208 			break;
    209 		case 'x':
    210 			fullmatch = 1;
    211 			break;
    212 		default:
    213 			usage();
    214 			/* NOTREACHED */
    215 		}
    216 
    217 	argc -= optind;
    218 	argv += optind;
    219 	if (argc != 0)
    220 		criteria = 1;
    221 	if (!criteria)
    222 		usage();
    223 
    224 	mypid = getpid();
    225 
    226 	/*
    227 	 * Retrieve the list of running processes from the kernel.
    228 	 */
    229 	kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, buf);
    230 	if (kd == NULL)
    231 		errx(STATUS_ERROR, "kvm_openfiles(): %s", buf);
    232 
    233 	plist = kvm_getproc2(kd, KERN_PROC_ALL, 0, sizeof(*plist), &nproc);
    234 	if (plist == NULL)
    235 		errx(STATUS_ERROR, "kvm_getprocs2() failed");
    236 
    237 	/*
    238 	 * Allocate memory which will be used to keep track of the
    239 	 * selection.
    240 	 */
    241 	if ((selected = malloc(nproc)) == NULL)
    242 		errx(STATUS_ERROR, "memory allocation failure");
    243 	memset(selected, 0, nproc);
    244 
    245 	/*
    246 	 * Refine the selection.
    247 	 */
    248 	for (; *argv != NULL; argv++) {
    249 		if ((rv = regcomp(&reg, *argv, REG_EXTENDED)) != 0) {
    250 			regerror(rv, &reg, buf, sizeof(buf));
    251 			errx(STATUS_BADUSAGE, "bad expression: %s", buf);
    252 		}
    253 
    254 		for (i = 0, kp = plist; i < nproc; i++, kp++) {
    255 			if ((kp->p_flag & P_SYSTEM) != 0)
    256 				continue;
    257 
    258 			if (matchargs) {
    259 				if ((pargv = kvm_getargv2(kd, kp, 0)) == NULL)
    260 					continue;
    261 
    262 				j = 0;
    263 				while (j < sizeof(buf) && *pargv != NULL) {
    264 					j += snprintf(buf + j, sizeof(buf) - j,
    265 					    pargv[1] != NULL ? "%s " : "%s",
    266 					    pargv[0]);
    267 					pargv++;
    268 				}
    269 
    270 				mstr = buf;
    271 			} else
    272 				mstr = kp->p_comm;
    273 
    274 			rv = regexec(&reg, mstr, 1, &regmatch, 0);
    275 			if (rv == 0) {
    276 				if (fullmatch) {
    277 					if (regmatch.rm_so == 0 &&
    278 					    regmatch.rm_eo == strlen(mstr))
    279 						selected[i] = 1;
    280 				} else
    281 					selected[i] = 1;
    282 			} else if (rv != REG_NOMATCH) {
    283 				regerror(rv, &reg, buf, sizeof(buf));
    284 				errx(STATUS_ERROR, "regexec(): %s", buf);
    285 			}
    286 		}
    287 
    288 		regfree(&reg);
    289 	}
    290 
    291 	for (i = 0, kp = plist; i < nproc; i++, kp++) {
    292 		if ((kp->p_flag & P_SYSTEM) != 0)
    293 			continue;
    294 
    295 		SLIST_FOREACH(li, &ruidlist, li_chain)
    296 			if (kp->p_ruid == (uid_t)li->li_number)
    297 				break;
    298 		if (SLIST_FIRST(&ruidlist) != NULL && li == NULL) {
    299 			selected[i] = 0;
    300 			continue;
    301 		}
    302 
    303 		SLIST_FOREACH(li, &rgidlist, li_chain)
    304 			if (kp->p_rgid == (gid_t)li->li_number)
    305 				break;
    306 		if (SLIST_FIRST(&rgidlist) != NULL && li == NULL) {
    307 			selected[i] = 0;
    308 			continue;
    309 		}
    310 
    311 		SLIST_FOREACH(li, &euidlist, li_chain)
    312 			if (kp->p_uid == (uid_t)li->li_number)
    313 				break;
    314 		if (SLIST_FIRST(&euidlist) != NULL && li == NULL) {
    315 			selected[i] = 0;
    316 			continue;
    317 		}
    318 
    319 		SLIST_FOREACH(li, &ppidlist, li_chain)
    320 			if (kp->p_ppid == (uid_t)li->li_number)
    321 				break;
    322 		if (SLIST_FIRST(&ppidlist) != NULL && li == NULL) {
    323 			selected[i] = 0;
    324 			continue;
    325 		}
    326 
    327 		SLIST_FOREACH(li, &pgrplist, li_chain)
    328 			if (kp->p__pgid == (uid_t)li->li_number)
    329 				break;
    330 		if (SLIST_FIRST(&pgrplist) != NULL && li == NULL) {
    331 			selected[i] = 0;
    332 			continue;
    333 		}
    334 
    335 		SLIST_FOREACH(li, &tdevlist, li_chain) {
    336 			if (li->li_number == -1 &&
    337 			    (kp->p_flag & P_CONTROLT) == 0)
    338 				break;
    339 			if (kp->p_tdev == (uid_t)li->li_number)
    340 				break;
    341 		}
    342 		if (SLIST_FIRST(&tdevlist) != NULL && li == NULL) {
    343 			selected[i] = 0;
    344 			continue;
    345 		}
    346 
    347 		SLIST_FOREACH(li, &sidlist, li_chain)
    348 			if (kp->p_sid == (uid_t)li->li_number)
    349 				break;
    350 		if (SLIST_FIRST(&sidlist) != NULL && li == NULL) {
    351 			selected[i] = 0;
    352 			continue;
    353 		}
    354 
    355 		if (argc == 0)
    356 			selected[i] = 1;
    357 	}
    358 
    359 	if (newest) {
    360 		bestsec = 0;
    361 		bestusec = 0;
    362 		bestidx = -1;
    363 
    364 		for (i = 0, kp = plist; i < nproc; i++, kp++) {
    365 			if (!selected[i])
    366 				continue;
    367 
    368 			if (kp->p_ustart_sec > bestsec ||
    369 			    (kp->p_ustart_sec == bestsec
    370 			    && kp->p_ustart_usec > bestusec)) {
    371 			    	bestsec = kp->p_ustart_sec;
    372 			    	bestusec = kp->p_ustart_usec;
    373 				bestidx = i;
    374 			}
    375 		}
    376 
    377 		memset(selected, 0, nproc);
    378 		if (bestidx != -1)
    379 			selected[bestidx] = 1;
    380 	}
    381 
    382 	/*
    383 	 * Take the appropriate action for each matched process, if any.
    384 	 */
    385 	for (i = 0, rv = 0, kp = plist; i < nproc; i++, kp++) {
    386 		if (kp->p_pid == mypid)
    387 			continue;
    388 		if (selected[i]) {
    389 			if (inverse)
    390 				continue;
    391 		} else if (!inverse)
    392 			continue;
    393 
    394 		if ((kp->p_flag & P_SYSTEM) != 0)
    395 			continue;
    396 
    397 		rv = 1;
    398 		(*action)(kp);
    399 	}
    400 
    401 	exit(rv ? STATUS_MATCH : STATUS_NOMATCH);
    402 }
    403 
    404 void
    405 usage(void)
    406 {
    407 	const char *ustr;
    408 
    409 	if (pgrep)
    410 		ustr = "[-flnvx] [-d delim]";
    411 	else
    412 		ustr = "[-signal] [-fnvx]";
    413 
    414 	fprintf(stderr, "usage: %s %s [-G gid] [-P ppid] [-U uid] [-g pgrp] "
    415 	    "[-s sid] [-t tty] [-u euid] pattern ...\n", getprogname(), ustr);
    416 
    417 	exit(STATUS_ERROR);
    418 }
    419 
    420 void
    421 killact(struct kinfo_proc2 *kp)
    422 {
    423 
    424 	if (kill(kp->p_pid, signum) == -1)
    425 		err(STATUS_ERROR, "signalling pid %d", (int)kp->p_pid);
    426 }
    427 
    428 void
    429 grepact(struct kinfo_proc2 *kp)
    430 {
    431 	char **argv;
    432 
    433 	if (longfmt && matchargs) {
    434 		if ((argv = kvm_getargv2(kd, kp, 0)) == NULL)
    435 			return;
    436 
    437 		printf("%d ", (int)kp->p_pid);
    438 		for (; *argv != NULL; argv++) {
    439 			printf("%s", *argv);
    440 			if (argv[1] != NULL)
    441 				putchar(' ');
    442 		}
    443 	} else if (longfmt)
    444 		printf("%d %s", (int)kp->p_pid, kp->p_comm);
    445 	else
    446 		printf("%d", (int)kp->p_pid);
    447 
    448 	printf("%s", delim);
    449 }
    450 
    451 void
    452 makelist(struct listhead *head, enum listtype type, char *src)
    453 {
    454 	struct list *li;
    455 	struct passwd *pw;
    456 	struct group *gr;
    457 	struct stat st;
    458 	char *sp, *p, buf[MAXPATHLEN];
    459 	int empty;
    460 
    461 	empty = 1;
    462 
    463 	while ((sp = strsep(&src, ",")) != NULL) {
    464 		if (*sp == '\0')
    465 			usage();
    466 
    467 		if ((li = malloc(sizeof(*li))) == NULL)
    468 			errx(STATUS_ERROR, "memory allocation failure");
    469 		SLIST_INSERT_HEAD(head, li, li_chain);
    470 		empty = 0;
    471 
    472 		li->li_number = (uid_t)strtol(sp, &p, 0);
    473 		if (*p == '\0') {
    474 			switch (type) {
    475 			case LT_PGRP:
    476 				if (li->li_number == 0)
    477 					li->li_number = getpgrp();
    478 				break;
    479 			case LT_SID:
    480 				if (li->li_number == 0)
    481 					li->li_number = getsid(mypid);
    482 				break;
    483 			case LT_TTY:
    484 				usage();
    485 			default:
    486 				break;
    487 			}
    488 			continue;
    489 		}
    490 
    491 		switch (type) {
    492 		case LT_USER:
    493 			if ((pw = getpwnam(sp)) == NULL)
    494 				errx(STATUS_BADUSAGE, "unknown user `%s'",
    495 				    optarg);
    496 			li->li_number = pw->pw_uid;
    497 			break;
    498 		case LT_GROUP:
    499 			if ((gr = getgrnam(sp)) == NULL)
    500 				errx(STATUS_BADUSAGE, "unknown group `%s'",
    501 				    optarg);
    502 			li->li_number = gr->gr_gid;
    503 			break;
    504 		case LT_TTY:
    505 			if (strcmp(sp, "-") == 0) {
    506 				li->li_number = -1;
    507 				break;
    508 			} else if (strcmp(sp, "co") == 0)
    509 				p = "console";
    510 			else if (strncmp(sp, "tty", 3) == 0)
    511 				p = sp;
    512 			else
    513 				p = NULL;
    514 
    515 			if (p == NULL)
    516 				snprintf(buf, sizeof(buf), "/dev/tty%s", sp);
    517 			else
    518 				snprintf(buf, sizeof(buf), "/dev/%s", p);
    519 
    520 			if (stat(buf, &st) < 0) {
    521 				if (errno == ENOENT)
    522 					errx(STATUS_BADUSAGE,
    523 					    "no such tty: `%s'", sp);
    524 				err(STATUS_ERROR, "stat(%s)", sp);
    525 			}
    526 
    527 			if ((st.st_mode & S_IFCHR) == 0)
    528 				errx(STATUS_BADUSAGE, "not a tty: `%s'", sp);
    529 
    530 			li->li_number = st.st_rdev;
    531 			break;
    532 		default:
    533 			usage();
    534 		};
    535 	}
    536 
    537 	if (empty)
    538 		usage();
    539 }
    540