Home | History | Annotate | Line # | Download | only in pkill
pkill.c revision 1.1
      1 /*	$NetBSD: pkill.c,v 1.1 2002/03/01 11:21:58 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.1 2002/03/01 11:21:58 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;
    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 (p[0] == '-') {
    136 			p++;
    137 			i = (int)strtol(p, &p, 10);
    138 			if (*p == '\0') {
    139 				signum = i;
    140 				argv++;
    141 			} else {
    142 				if (strncasecmp(p, "sig", 3) == 0)
    143 					p += 3;
    144 				for (i = 1; i < NSIG; i++)
    145 					if (strcasecmp(sys_signame[i], p) == 0)
    146 						break;
    147 				if (i != NSIG) {
    148 					signum = i;
    149 					argv++;
    150 				}
    151 			}
    152 		}
    153 	}
    154 
    155 	criteria = 0;
    156 
    157 	while ((ch = getopt(argc, argv, "G:P:U:d:fg:lns:t:vx")) != -1)
    158 		switch (ch) {
    159 		case 'G':
    160 			makelist(&rgidlist, LT_GROUP, optarg);
    161 			criteria = 1;
    162 			break;
    163 		case 'P':
    164 			makelist(&ppidlist, LT_GENERIC, optarg);
    165 			criteria = 1;
    166 			break;
    167 		case 'U':
    168 			makelist(&ruidlist, LT_USER, optarg);
    169 			criteria = 1;
    170 			break;
    171 		case 'd':
    172 			if (!pgrep)
    173 				usage();
    174 			delim = optarg;
    175 			break;
    176 		case 'f':
    177 			matchargs = 1;
    178 			break;
    179 		case 'g':
    180 			makelist(&pgrplist, LT_PGRP, optarg);
    181 			criteria = 1;
    182 			break;
    183 		case 'l':
    184 			if (!pgrep)
    185 				usage();
    186 			longfmt = 1;
    187 			break;
    188 		case 'n':
    189 			newest = 1;
    190 			criteria = 1;
    191 			break;
    192 		case 's':
    193 			makelist(&sidlist, LT_SID, optarg);
    194 			criteria = 1;
    195 			break;
    196 		case 't':
    197 			makelist(&tdevlist, LT_TTY, optarg);
    198 			criteria = 1;
    199 			break;
    200 		case 'u':
    201 			makelist(&euidlist, LT_USER, optarg);
    202 			criteria = 1;
    203 			break;
    204 		case 'v':
    205 			inverse = 1;
    206 			break;
    207 		case 'x':
    208 			fullmatch = 1;
    209 			break;
    210 		default:
    211 			usage();
    212 			/* NOTREACHED */
    213 		}
    214 
    215 	argc -= optind;
    216 	argv += optind;
    217 	if (argc != 0)
    218 		criteria = 1;
    219 	if (!criteria)
    220 		usage();
    221 
    222 	mypid = getpid();
    223 
    224 	/*
    225 	 * Retrieve the list of running processes from the kernel.
    226 	 */
    227 	kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, buf);
    228 	if (kd == NULL)
    229 		errx(STATUS_ERROR, "kvm_openfiles(): %s", buf);
    230 
    231 	plist = kvm_getproc2(kd, KERN_PROC_ALL, 0, sizeof(*plist), &nproc);
    232 	if (plist == NULL)
    233 		errx(STATUS_ERROR, "kvm_getprocs2() failed");
    234 
    235 	/*
    236 	 * Allocate memory which will be used to keep track of the
    237 	 * selection.
    238 	 */
    239 	if ((selected = malloc(nproc)) == NULL)
    240 		errx(STATUS_ERROR, "memory allocation failure");
    241 	memset(selected, 0, nproc);
    242 
    243 	/*
    244 	 * Refine the selection.
    245 	 */
    246 	for (; *argv != NULL; argv++) {
    247 		if ((rv = regcomp(&reg, *argv, REG_EXTENDED)) != 0) {
    248 			regerror(rv, &reg, buf, sizeof(buf));
    249 			errx(STATUS_BADUSAGE, "bad expression: %s", buf);
    250 		}
    251 
    252 		for (i = 0, kp = plist; i < nproc; i++, kp++) {
    253 			if ((kp->p_flag & P_SYSTEM) != 0)
    254 				continue;
    255 
    256 			if (matchargs) {
    257 				if ((pargv = kvm_getargv2(kd, kp, 0)) == NULL)
    258 					continue;
    259 
    260 				j = 0;
    261 				while (j < sizeof(buf) && *pargv != NULL) {
    262 					j += snprintf(buf + j, sizeof(buf) - j,
    263 					    pargv[1] != NULL ? "%s " : "%s",
    264 					    pargv[0]);
    265 					pargv++;
    266 				}
    267 
    268 				mstr = buf;
    269 			} else
    270 				mstr = kp->p_comm;
    271 
    272 			rv = regexec(&reg, mstr, 1, &regmatch, 0);
    273 			if (rv == 0) {
    274 				if (fullmatch) {
    275 					if (regmatch.rm_so == 0 &&
    276 					    regmatch.rm_eo == strlen(mstr))
    277 						selected[i] = 1;
    278 				} else
    279 					selected[i] = 1;
    280 			} else if (rv != REG_NOMATCH) {
    281 				regerror(rv, &reg, buf, sizeof(buf));
    282 				errx(STATUS_ERROR, "regexec(): %s", buf);
    283 			}
    284 		}
    285 
    286 		regfree(&reg);
    287 	}
    288 
    289 	for (i = 0, kp = plist; i < nproc; i++, kp++) {
    290 		if ((kp->p_flag & P_SYSTEM) != 0)
    291 			continue;
    292 
    293 		SLIST_FOREACH(li, &ruidlist, li_chain)
    294 			if (kp->p_ruid == (uid_t)li->li_number)
    295 				break;
    296 		if (SLIST_FIRST(&ruidlist) != NULL && li == NULL) {
    297 			selected[i] = 0;
    298 			continue;
    299 		}
    300 
    301 		SLIST_FOREACH(li, &rgidlist, li_chain)
    302 			if (kp->p_rgid == (gid_t)li->li_number)
    303 				break;
    304 		if (SLIST_FIRST(&rgidlist) != NULL && li == NULL) {
    305 			selected[i] = 0;
    306 			continue;
    307 		}
    308 
    309 		SLIST_FOREACH(li, &euidlist, li_chain)
    310 			if (kp->p_uid == (uid_t)li->li_number)
    311 				break;
    312 		if (SLIST_FIRST(&euidlist) != NULL && li == NULL) {
    313 			selected[i] = 0;
    314 			continue;
    315 		}
    316 
    317 		SLIST_FOREACH(li, &ppidlist, li_chain)
    318 			if (kp->p_ppid == (uid_t)li->li_number)
    319 				break;
    320 		if (SLIST_FIRST(&ppidlist) != NULL && li == NULL) {
    321 			selected[i] = 0;
    322 			continue;
    323 		}
    324 
    325 		SLIST_FOREACH(li, &pgrplist, li_chain)
    326 			if (kp->p__pgid == (uid_t)li->li_number)
    327 				break;
    328 		if (SLIST_FIRST(&pgrplist) != NULL && li == NULL) {
    329 			selected[i] = 0;
    330 			continue;
    331 		}
    332 
    333 		SLIST_FOREACH(li, &tdevlist, li_chain) {
    334 			if (li->li_number == -1 &&
    335 			    (kp->p_flag & P_CONTROLT) == 0)
    336 				break;
    337 			if (kp->p_tdev == (uid_t)li->li_number)
    338 				break;
    339 		}
    340 		if (SLIST_FIRST(&tdevlist) != NULL && li == NULL) {
    341 			selected[i] = 0;
    342 			continue;
    343 		}
    344 
    345 		SLIST_FOREACH(li, &sidlist, li_chain)
    346 			if (kp->p_sid == (uid_t)li->li_number)
    347 				break;
    348 		if (SLIST_FIRST(&sidlist) != NULL && li == NULL) {
    349 			selected[i] = 0;
    350 			continue;
    351 		}
    352 
    353 		if (argc == 0)
    354 			selected[i] = 1;
    355 	}
    356 
    357 	if (newest) {
    358 		bestsec = 0;
    359 		bestusec = 0;
    360 		bestidx = -1;
    361 
    362 		for (i = 0, kp = plist; i < nproc; i++, kp++) {
    363 			if (!selected[i])
    364 				continue;
    365 
    366 			if (kp->p_ustart_sec > bestsec ||
    367 			    (kp->p_ustart_sec == bestsec
    368 			    && kp->p_ustart_usec > bestusec)) {
    369 			    	bestsec = kp->p_ustart_sec;
    370 			    	bestusec = kp->p_ustart_usec;
    371 				bestidx = i;
    372 			}
    373 		}
    374 
    375 		memset(selected, 0, nproc);
    376 		if (bestidx != -1)
    377 			selected[bestidx] = 1;
    378 	}
    379 
    380 	/*
    381 	 * Take the appropriate action for each matched process, if any.
    382 	 */
    383 	for (i = 0, rv = 0, kp = plist; i < nproc; i++, kp++) {
    384 		if (kp->p_pid == mypid)
    385 			continue;
    386 		if (selected[i]) {
    387 			if (inverse)
    388 				continue;
    389 		} else if (!inverse)
    390 			continue;
    391 
    392 		rv = 1;
    393 		(*action)(kp);
    394 	}
    395 
    396 	exit(rv ? STATUS_MATCH : STATUS_NOMATCH);
    397 }
    398 
    399 void
    400 usage(void)
    401 {
    402 	const char *ustr;
    403 
    404 	if (pgrep)
    405 		ustr = "[-flnvx] [-d delim]";
    406 	else
    407 		ustr = "[-signal] [-fnvx]";
    408 
    409 	fprintf(stderr, "usage: %s %s [-G gid] [-P ppid] [-U uid] [-g pgrp] "
    410 	    "[-s sid] [-t tty] [-u euid] pattern ...\n", getprogname(), ustr);
    411 
    412 	exit(STATUS_ERROR);
    413 }
    414 
    415 void
    416 killact(struct kinfo_proc2 *kp)
    417 {
    418 
    419 	if (kill(kp->p_pid, signum) == -1)
    420 		err(STATUS_ERROR, "signalling pid %d", (int)kp->p_pid);
    421 }
    422 
    423 void
    424 grepact(struct kinfo_proc2 *kp)
    425 {
    426 	char **argv;
    427 
    428 	if (longfmt && matchargs) {
    429 		if ((argv = kvm_getargv2(kd, kp, 0)) == NULL)
    430 			return;
    431 
    432 		printf("%d ", (int)kp->p_pid);
    433 		for (; *argv != NULL; argv++) {
    434 			printf("%s", *argv);
    435 			if (argv[1] != NULL)
    436 				putchar(' ');
    437 		}
    438 	} else if (longfmt)
    439 		printf("%d %s", (int)kp->p_pid, kp->p_comm);
    440 	else
    441 		printf("%d", (int)kp->p_pid);
    442 
    443 	printf("%s", delim);
    444 }
    445 
    446 void
    447 makelist(struct listhead *head, enum listtype type, char *src)
    448 {
    449 	struct list *li;
    450 	struct passwd *pw;
    451 	struct group *gr;
    452 	struct stat st;
    453 	char *sp, *p, buf[MAXPATHLEN];
    454 	int empty;
    455 
    456 	empty = 1;
    457 
    458 	while ((sp = strsep(&src, ",")) != NULL) {
    459 		if (*sp == '\0')
    460 			usage();
    461 
    462 		if ((li = malloc(sizeof(*li))) == NULL)
    463 			errx(STATUS_ERROR, "memory allocation failure");
    464 		SLIST_INSERT_HEAD(head, li, li_chain);
    465 		empty = 0;
    466 
    467 		li->li_number = (uid_t)strtol(sp, &p, 0);
    468 		if (*p == '\0') {
    469 			switch (type) {
    470 			case LT_PGRP:
    471 				if (li->li_number == 0)
    472 					li->li_number = getpgrp();
    473 				break;
    474 			case LT_SID:
    475 				if (li->li_number == 0)
    476 					li->li_number = getsid(mypid);
    477 				break;
    478 			case LT_TTY:
    479 				usage();
    480 			default:
    481 				break;
    482 			}
    483 			continue;
    484 		}
    485 
    486 		switch (type) {
    487 		case LT_USER:
    488 			if ((pw = getpwnam(sp)) == NULL)
    489 				errx(STATUS_BADUSAGE, "unknown user `%s'",
    490 				    optarg);
    491 			li->li_number = pw->pw_uid;
    492 			break;
    493 		case LT_GROUP:
    494 			if ((gr = getgrnam(sp)) == NULL)
    495 				errx(STATUS_BADUSAGE, "unknown group `%s'",
    496 				    optarg);
    497 			li->li_number = gr->gr_gid;
    498 			break;
    499 		case LT_TTY:
    500 			if (strcmp(sp, "-") == 0) {
    501 				li->li_number = -1;
    502 				break;
    503 			} else if (strcmp(sp, "co") == 0)
    504 				p = "console";
    505 			else if (strncmp(sp, "tty", 3) == 0)
    506 				p = sp;
    507 			else
    508 				p = NULL;
    509 
    510 			if (p == NULL)
    511 				snprintf(buf, sizeof(buf), "/dev/tty%s", sp);
    512 			else
    513 				snprintf(buf, sizeof(buf), "/dev/%s", p);
    514 
    515 			if (stat(buf, &st) < 0) {
    516 				if (errno == ENOENT)
    517 					errx(STATUS_BADUSAGE,
    518 					    "no such tty: `%s'", sp);
    519 				err(STATUS_ERROR, "stat(%s)", sp);
    520 			}
    521 
    522 			if ((st.st_mode & S_IFCHR) == 0)
    523 				errx(STATUS_BADUSAGE, "not a tty: `%s'", sp);
    524 
    525 			li->li_number = st.st_rdev;
    526 			break;
    527 		default:
    528 			usage();
    529 		};
    530 	}
    531 
    532 	if (empty)
    533 		usage();
    534 }
    535