summaryrefslogtreecommitdiff
path: root/start-stop-daemon.c
blob: 3947cc0651d521a5ae3d50d37c6a5461b985b265 (plain)
    1 /*
    2  * A rewrite of the original Debian's start-stop-daemon Perl script
    3  * in C (faster - it is executed many times during system startup).
    4  *
    5  * Written by Marek Michalkiewicz <marekm@i17linuxb.ists.pwr.wroc.pl>,
    6  * public domain.  Based conceptually on start-stop-daemon.pl, by Ian
    7  * Jackson <ijackson@gnu.ai.mit.edu>.  May be used and distributed
    8  * freely for any purpose.  Changes by Christian Schwarz
    9  * <schwarz@monet.m.isar.de>, to make output conform to the Debian
   10  * Console Message Standard, also placed in public domain.  Minor
   11  * changes by Klee Dienes <klee@debian.org>, also placed in the Public
   12  * Domain.
   13  *
   14  * Changes by Ben Collins <bcollins@debian.org>, added --chuid, --background
   15  * and --make-pidfile options, placed in public domain as well.
   16  *
   17  * Port to OpenBSD by Sontri Tomo Huynh <huynh.29@osu.edu>
   18  *                 and Andreas Schuldei <andreas@schuldei.org>
   19  *
   20  * Changes by Ian Jackson: added --retry (and associated rearrangements).
   21  */
   22 
   23 #include <config.h>
   24 #include <compat.h>
   25 
   26 #include <dpkg/macros.h>
   27 
   28 #if defined(__linux__)
   29 #  define OS_Linux
   30 #elif defined(__GNU__)
   31 #  define OS_Hurd
   32 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
   33 #  define OS_FreeBSD
   34 #elif defined(__NetBSD__)
   35 #  define OS_NetBSD
   36 #elif defined(__OpenBSD__)
   37 #  define OS_OpenBSD
   38 #elif defined(__DragonFly__)
   39 #  define OS_DragonFlyBSD
   40 #elif defined(__APPLE__) && defined(__MACH__)
   41 #  define OS_Darwin
   42 #elif defined(__sun)
   43 #  define OS_Solaris
   44 #elif defined(_AIX)
   45 #  define OS_AIX
   46 #elif defined(__hpux)
   47 #  define OS_HPUX
   48 #else
   49 #  error Unknown architecture - cannot build start-stop-daemon
   50 #endif
   51 
   52 /* NetBSD needs this to expose struct proc. */
   53 #define _KMEMUSER 1
   54 
   55 #ifdef HAVE_SYS_PARAM_H
   56 #include <sys/param.h>
   57 #endif
   58 #ifdef HAVE_SYS_SYSCALL_H
   59 #include <sys/syscall.h>
   60 #endif
   61 #ifdef HAVE_SYS_SYSCTL_H
   62 #include <sys/sysctl.h>
   63 #endif
   64 #ifdef HAVE_SYS_PROCFS_H
   65 #include <sys/procfs.h>
   66 #endif
   67 #ifdef HAVE_SYS_PROC_H
   68 #include <sys/proc.h>
   69 #endif
   70 #ifdef HAVE_SYS_USER_H
   71 #include <sys/user.h>
   72 #endif
   73 #ifdef HAVE_SYS_PSTAT_H
   74 #include <sys/pstat.h>
   75 #endif
   76 #include <sys/types.h>
   77 #include <sys/time.h>
   78 #include <sys/stat.h>
   79 #include <sys/wait.h>
   80 #include <sys/select.h>
   81 #include <sys/ioctl.h>
   82 #include <sys/socket.h>
   83 #include <sys/un.h>
   84 
   85 #include <errno.h>
   86 #include <limits.h>
   87 #include <time.h>
   88 #include <fcntl.h>
   89 #include <dirent.h>
   90 #include <ctype.h>
   91 #include <string.h>
   92 #include <pwd.h>
   93 #include <grp.h>
   94 #include <signal.h>
   95 #include <termios.h>
   96 #include <unistd.h>
   97 #ifdef HAVE_STDDEF_H
   98 #include <stddef.h>
   99 #endif
  100 #include <stdbool.h>
  101 #include <stdarg.h>
  102 #include <stdlib.h>
  103 #include <stdio.h>
  104 #include <getopt.h>
  105 #ifdef HAVE_ERROR_H
  106 #include <error.h>
  107 #endif
  108 #ifdef HAVE_ERR_H
  109 #include <err.h>
  110 #endif
  111 
  112 #if defined(OS_Hurd)
  113 #include <hurd.h>
  114 #include <ps.h>
  115 #endif
  116 
  117 #if defined(OS_Darwin)
  118 #include <libproc.h>
  119 #endif
  120 
  121 #ifdef HAVE_KVM_H
  122 #include <kvm.h>
  123 #if defined(OS_FreeBSD)
  124 #define KVM_MEMFILE "/dev/null"
  125 #else
  126 #define KVM_MEMFILE NULL
  127 #endif
  128 #endif
  129 
  130 #if defined(_POSIX_PRIORITY_SCHEDULING) && _POSIX_PRIORITY_SCHEDULING > 0
  131 #include <sched.h>
  132 #else
  133 #define SCHED_OTHER -1
  134 #define SCHED_FIFO -1
  135 #define SCHED_RR -1
  136 #endif
  137 
  138 #if defined(OS_Linux)
  139 /* This comes from TASK_COMM_LEN defined in Linux' include/linux/sched.h. */
  140 #define PROCESS_NAME_SIZE 15
  141 #elif defined(OS_Solaris)
  142 #define PROCESS_NAME_SIZE 15
  143 #elif defined(OS_Darwin)
  144 #define PROCESS_NAME_SIZE 16
  145 #elif defined(OS_AIX)
  146 /* This comes from PRFNSZ defined in AIX's <sys/procfs.h>. */
  147 #define PROCESS_NAME_SIZE 16
  148 #elif defined(OS_NetBSD)
  149 #define PROCESS_NAME_SIZE 16
  150 #elif defined(OS_OpenBSD)
  151 #define PROCESS_NAME_SIZE 16
  152 #elif defined(OS_FreeBSD)
  153 #define PROCESS_NAME_SIZE 19
  154 #elif defined(OS_DragonFlyBSD)
  155 /* On DragonFlyBSD MAXCOMLEN expands to 16. */
  156 #define PROCESS_NAME_SIZE MAXCOMLEN
  157 #endif
  158 
  159 #if defined(SYS_ioprio_set) && defined(linux)
  160 #define HAVE_IOPRIO_SET
  161 #endif
  162 
  163 #define IOPRIO_CLASS_SHIFT 13
  164 #define IOPRIO_PRIO_VALUE(class, prio) (((class) << IOPRIO_CLASS_SHIFT) | (prio))
  165 #define IO_SCHED_PRIO_MIN 0
  166 #define IO_SCHED_PRIO_MAX 7
  167 
  168 enum {
  169 	IOPRIO_WHO_PROCESS = 1,
  170 	IOPRIO_WHO_PGRP,
  171 	IOPRIO_WHO_USER,
  172 };
  173 
  174 enum {
  175 	IOPRIO_CLASS_NONE,
  176 	IOPRIO_CLASS_RT,
  177 	IOPRIO_CLASS_BE,
  178 	IOPRIO_CLASS_IDLE,
  179 };
  180 
  181 enum action_code {
  182 	ACTION_NONE,
  183 	ACTION_START,
  184 	ACTION_STOP,
  185 	ACTION_STATUS,
  186 };
  187 
  188 enum match_code {
  189 	MATCH_NONE	= 0,
  190 	MATCH_PID	= 1 << 0,
  191 	MATCH_PPID	= 1 << 1,
  192 	MATCH_PIDFILE	= 1 << 2,
  193 	MATCH_EXEC	= 1 << 3,
  194 	MATCH_NAME	= 1 << 4,
  195 	MATCH_USER	= 1 << 5,
  196 };
  197 
  198 /* Time conversion constants. */
  199 enum {
  200 	NANOSEC_IN_SEC      = 1000000000L,
  201 	NANOSEC_IN_MILLISEC = 1000000L,
  202 	NANOSEC_IN_MICROSEC = 1000L,
  203 };
  204 
  205 /* The minimum polling interval, 20ms. */
  206 static const long MIN_POLL_INTERVAL = 20L * NANOSEC_IN_MILLISEC;
  207 
  208 static enum action_code action;
  209 static enum match_code match_mode;
  210 static bool testmode = false;
  211 static int quietmode = 0;
  212 static int exitnodo = 1;
  213 static bool background = false;
  214 static bool close_io = true;
  215 static bool notify_await = false;
  216 static int notify_timeout = 60;
  217 static char *notify_sockdir;
  218 static char *notify_socket;
  219 static bool mpidfile = false;
  220 static bool rpidfile = false;
  221 static int signal_nr = SIGTERM;
  222 static int user_id = -1;
  223 static int runas_uid = -1;
  224 static int runas_gid = -1;
  225 static const char *userspec = NULL;
  226 static char *changeuser = NULL;
  227 static const char *changegroup = NULL;
  228 static char *changeroot = NULL;
  229 static const char *changedir = "/";
  230 static const char *cmdname = NULL;
  231 static char *execname = NULL;
  232 static char *startas = NULL;
  233 static pid_t match_pid = -1;
  234 static pid_t match_ppid = -1;
  235 static const char *pidfile = NULL;
  236 static char *what_stop = NULL;
  237 static const char *progname = "";
  238 static int nicelevel = 0;
  239 static int umask_value = -1;
  240 
  241 static struct stat exec_stat;
  242 #if defined(OS_Hurd)
  243 static struct proc_stat_list *procset = NULL;
  244 #endif
  245 
  246 /* LSB Init Script process status exit codes. */
  247 enum status_code {
  248 	STATUS_OK = 0,
  249 	STATUS_DEAD_PIDFILE = 1,
  250 	STATUS_DEAD_LOCKFILE = 2,
  251 	STATUS_DEAD = 3,
  252 	STATUS_UNKNOWN = 4,
  253 };
  254 
  255 struct pid_list {
  256 	struct pid_list *next;
  257 	pid_t pid;
  258 };
  259 
  260 static struct pid_list *found = NULL;
  261 static struct pid_list *killed = NULL;
  262 
  263 /* Resource scheduling policy. */
  264 struct res_schedule {
  265 	const char *policy_name;
  266 	int policy;
  267 	int priority;
  268 };
  269 
  270 struct schedule_item {
  271 	enum {
  272 		sched_timeout,
  273 		sched_signal,
  274 		sched_goto,
  275 		/* Only seen within parse_schedule and callees. */
  276 		sched_forever,
  277 	} type;
  278 	/* Seconds, signal no., or index into array. */
  279 	int value;
  280 };
  281 
  282 static struct res_schedule *proc_sched = NULL;
  283 static struct res_schedule *io_sched = NULL;
  284 
  285 static int schedule_length;
  286 static struct schedule_item *schedule = NULL;
  287 
  288 
  289 static void DPKG_ATTR_PRINTF(1)
  290 debug(const char *format, ...)
  291 {
  292 	va_list arglist;
  293 
  294 	if (quietmode >= 0)
  295 		return;
  296 
  297 	va_start(arglist, format);
  298 	vprintf(format, arglist);
  299 	va_end(arglist);
  300 }
  301 
  302 static void DPKG_ATTR_PRINTF(1)
  303 info(const char *format, ...)
  304 {
  305 	va_list arglist;
  306 
  307 	if (quietmode > 0)
  308 		return;
  309 
  310 	va_start(arglist, format);
  311 	vprintf(format, arglist);
  312 	va_end(arglist);
  313 }
  314 
  315 static void DPKG_ATTR_PRINTF(1)
  316 warning(const char *format, ...)
  317 {
  318 	va_list arglist;
  319 
  320 	fprintf(stderr, "%s: warning: ", progname);
  321 	va_start(arglist, format);
  322 	vfprintf(stderr, format, arglist);
  323 	va_end(arglist);
  324 }
  325 
  326 static void DPKG_ATTR_NORET DPKG_ATTR_VPRINTF(2)
  327 fatalv(int errno_fatal, const char *format, va_list args)
  328 {
  329 	va_list args_copy;
  330 
  331 	fprintf(stderr, "%s: ", progname);
  332 	va_copy(args_copy, args);
  333 	vfprintf(stderr, format, args_copy);
  334 	va_end(args_copy);
  335 	if (errno_fatal)
  336 		fprintf(stderr, " (%s)\n", strerror(errno_fatal));
  337 	else
  338 		fprintf(stderr, "\n");
  339 
  340 	if (action == ACTION_STATUS)
  341 		exit(STATUS_UNKNOWN);
  342 	else
  343 		exit(2);
  344 }
  345 
  346 static void DPKG_ATTR_NORET DPKG_ATTR_PRINTF(1)
  347 fatal(const char *format, ...)
  348 {
  349 	va_list args;
  350 
  351 	va_start(args, format);
  352 	fatalv(0, format, args);
  353 }
  354 
  355 static void DPKG_ATTR_NORET DPKG_ATTR_PRINTF(1)
  356 fatale(const char *format, ...)
  357 {
  358 	va_list args;
  359 
  360 	va_start(args, format);
  361 	fatalv(errno, format, args);
  362 }
  363 
  364 #define BUG(...) bug(__FILE__, __LINE__, __func__, __VA_ARGS__)
  365 
  366 static void DPKG_ATTR_NORET DPKG_ATTR_PRINTF(4)
  367 bug(const char *file, int line, const char *func, const char *format, ...)
  368 {
  369 	va_list arglist;
  370 
  371 	fprintf(stderr, "%s:%s:%d:%s: internal error: ",
  372 	        progname, file, line, func);
  373 	va_start(arglist, format);
  374 	vfprintf(stderr, format, arglist);
  375 	va_end(arglist);
  376 
  377 	if (action == ACTION_STATUS)
  378 		exit(STATUS_UNKNOWN);
  379 	else
  380 		exit(3);
  381 }
  382 
  383 static void *
  384 xmalloc(int size)
  385 {
  386 	void *ptr;
  387 
  388 	ptr = malloc(size);
  389 	if (ptr)
  390 		return ptr;
  391 	fatale("malloc(%d) failed", size);
  392 }
  393 
  394 static char *
  395 xstrndup(const char *str, size_t n)
  396 {
  397 	char *new_str;
  398 
  399 	new_str = strndup(str, n);
  400 	if (new_str)
  401 		return new_str;
  402 	fatale("strndup(%s, %zu) failed", str, n);
  403 }
  404 
  405 static void
  406 timespec_gettime(struct timespec *ts)
  407 {
  408 #if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0 && \
  409     defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK > 0
  410 	if (clock_gettime(CLOCK_MONOTONIC, ts) < 0)
  411 		fatale("clock_gettime failed");
  412 #else
  413 	struct timeval tv;
  414 
  415 	if (gettimeofday(&tv, NULL) != 0)
  416 		fatale("gettimeofday failed");
  417 
  418 	ts->tv_sec = tv.tv_sec;
  419 	ts->tv_nsec = tv.tv_usec * NANOSEC_IN_MICROSEC;
  420 #endif
  421 }
  422 
  423 #define timespec_cmp(a, b, OP) \
  424 	(((a)->tv_sec == (b)->tv_sec) ? \
  425 	 ((a)->tv_nsec OP (b)->tv_nsec) : \
  426 	 ((a)->tv_sec OP (b)->tv_sec))
  427 
  428 static void
  429 timespec_sub(struct timespec *a, struct timespec *b, struct timespec *res)
  430 {
  431 	res->tv_sec = a->tv_sec - b->tv_sec;
  432 	res->tv_nsec = a->tv_nsec - b->tv_nsec;
  433 	if (res->tv_nsec < 0) {
  434 		res->tv_sec--;
  435 		res->tv_nsec += NANOSEC_IN_SEC;
  436 	}
  437 }
  438 
  439 static void
  440 timespec_mul(struct timespec *a, int b)
  441 {
  442 	long nsec = a->tv_nsec * b;
  443 
  444 	a->tv_sec *= b;
  445 	a->tv_sec += nsec / NANOSEC_IN_SEC;
  446 	a->tv_nsec = nsec % NANOSEC_IN_SEC;
  447 }
  448 
  449 static char *
  450 newpath(const char *dirname, const char *filename)
  451 {
  452 	char *path;
  453 	size_t path_len;
  454 
  455 	path_len = strlen(dirname) + 1 + strlen(filename) + 1;
  456 	path = xmalloc(path_len);
  457 	snprintf(path, path_len, "%s/%s", dirname, filename);
  458 
  459 	return path;
  460 }
  461 
  462 static int
  463 parse_unsigned(const char *string, int base, int *value_r)
  464 {
  465 	long value;
  466 	char *endptr;
  467 
  468 	errno = 0;
  469 	if (!string[0])
  470 		return -1;
  471 
  472 	value = strtol(string, &endptr, base);
  473 	if (string == endptr || *endptr != '\0' || errno != 0)
  474 		return -1;
  475 	if (value < 0 || value > INT_MAX)
  476 		return -1;
  477 
  478 	*value_r = value;
  479 	return 0;
  480 }
  481 
  482 static long
  483 get_open_fd_max(void)
  484 {
  485 #ifdef HAVE_GETDTABLESIZE
  486 	return getdtablesize();
  487 #else
  488 	return sysconf(_SC_OPEN_MAX);
  489 #endif
  490 }
  491 
  492 #ifndef HAVE_SETSID
  493 static void
  494 detach_controlling_tty(void)
  495 {
  496 #ifdef HAVE_TIOCNOTTY
  497 	int tty_fd;
  498 
  499 	tty_fd = open("/dev/tty", O_RDWR);
  500 
  501 	/* The current process does not have a controlling tty. */
  502 	if (tty_fd < 0)
  503 		return;
  504 
  505 	if (ioctl(tty_fd, TIOCNOTTY, 0) != 0)
  506 		fatale("unable to detach controlling tty");
  507 
  508 	close(tty_fd);
  509 #endif
  510 }
  511 
  512 static pid_t
  513 setsid(void)
  514 {
  515 	if (setpgid(0, 0) < 0)
  516 		return -1:
  517 
  518 	detach_controlling_tty();
  519 
  520 	return 0;
  521 }
  522 #endif
  523 
  524 static void
  525 wait_for_child(pid_t pid)
  526 {
  527 	pid_t child;
  528 	int status;
  529 
  530 	do {
  531 		child = waitpid(pid, &status, 0);
  532 	} while (child == -1 && errno == EINTR);
  533 
  534 	if (child != pid)
  535 		fatal("error waiting for child");
  536 
  537 	if (WIFEXITED(status)) {
  538 		int ret = WEXITSTATUS(status);
  539 
  540 		if (ret != 0)
  541 			fatal("child returned error exit status %d", ret);
  542 	} else if (WIFSIGNALED(status)) {
  543 		int signo = WTERMSIG(status);
  544 
  545 		fatal("child was killed by signal %d", signo);
  546 	} else {
  547 		fatal("unexpected status %d waiting for child", status);
  548 	}
  549 }
  550 
  551 static void
  552 cleanup_socket_dir(void)
  553 {
  554 	(void)unlink(notify_socket);
  555 	(void)rmdir(notify_sockdir);
  556 }
  557 
  558 static char *
  559 setup_socket_name(const char *suffix)
  560 {
  561 	const char *basedir;
  562 
  563 	if (getuid() == 0 && access("/run", F_OK) == 0) {
  564 		basedir = "/run";
  565 	} else {
  566 		basedir = getenv("TMPDIR");
  567 		if (basedir == NULL)
  568 			basedir = P_tmpdir;
  569 	}
  570 
  571 	if (asprintf(&notify_sockdir, "%s/%s.XXXXXX", basedir, suffix) < 0)
  572 		fatale("cannot allocate socket directory name");
  573 
  574 	if (mkdtemp(notify_sockdir) == NULL)
  575 		fatale("cannot create socket directory %s", notify_sockdir);
  576 
  577 	atexit(cleanup_socket_dir);
  578 
  579 	if (chown(notify_sockdir, runas_uid, runas_gid))
  580 		fatale("cannot change socket directory ownership");
  581 
  582 	if (asprintf(&notify_socket, "%s/notify", notify_sockdir) < 0)
  583 		fatale("cannot allocate socket name");
  584 
  585 	setenv("NOTIFY_SOCKET", notify_socket, 1);
  586 
  587 	return notify_socket;
  588 }
  589 
  590 static void
  591 set_socket_passcred(int fd)
  592 {
  593 #ifdef SO_PASSCRED
  594 	static const int enable = 1;
  595 
  596 	(void)setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable));
  597 #endif
  598 }
  599 
  600 static int
  601 create_notify_socket(void)
  602 {
  603 	const char *sockname;
  604 	struct sockaddr_un su;
  605 	int fd, rc, flags;
  606 
  607 	/* Create notification socket. */
  608 	fd = socket(AF_UNIX, SOCK_DGRAM | SOCK_NONBLOCK, 0);
  609 	if (fd < 0)
  610 		fatale("cannot create notification socket");
  611 
  612 	/* We could set SOCK_CLOEXEC instead, but then we would need to
  613 	 * check whether the socket call failed, try and then do this anyway,
  614 	 * when we have no threading problems to worry about. */
  615 	flags = fcntl(fd, F_GETFD);
  616 	if (flags < 0)
  617 		fatale("cannot read fd flags for notification socket");
  618 	if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0)
  619 		fatale("cannot set close-on-exec flag for notification socket");
  620 
  621 	sockname = setup_socket_name(".s-s-d-notify");
  622 
  623 	/* Bind to a socket in a temporary directory, selected based on
  624 	 * the platform. */
  625 	memset(&su, 0, sizeof(su));
  626 	su.sun_family = AF_UNIX;
  627 	strncpy(su.sun_path, sockname, sizeof(su.sun_path) - 1);
  628 
  629 	rc = bind(fd, &su, sizeof(su));
  630 	if (rc < 0)
  631 		fatale("cannot bind to notification socket");
  632 
  633 	rc = chmod(su.sun_path, 0660);
  634 	if (rc < 0)
  635 		fatale("cannot change notification socket permissions");
  636 
  637 	rc = chown(su.sun_path, runas_uid, runas_gid);
  638 	if (rc < 0)
  639 		fatale("cannot change notification socket ownership");
  640 
  641 	/* XXX: Verify we are talking to an expected child? Although it is not
  642 	 * clear whether this is feasible given the knowledge we have got. */
  643 	set_socket_passcred(fd);
  644 
  645 	return fd;
  646 }
  647 
  648 static void
  649 wait_for_notify(int fd)
  650 {
  651 	struct timespec startat, now, elapsed, timeout, timeout_orig;
  652 	fd_set fdrs;
  653 	int rc;
  654 
  655 	timeout.tv_sec = notify_timeout;
  656 	timeout.tv_nsec = 0;
  657 	timeout_orig = timeout;
  658 
  659 	timespec_gettime(&startat);
  660 
  661 	while (timeout.tv_sec >= 0 && timeout.tv_nsec >= 0) {
  662 		FD_ZERO(&fdrs);
  663 		FD_SET(fd, &fdrs);
  664 
  665 		/* Wait for input. */
  666 		debug("Waiting for notifications... (timeout %lusec %lunsec)\n",
  667 		      timeout.tv_sec, timeout.tv_nsec);
  668 		rc = pselect(fd + 1, &fdrs, NULL, NULL, &timeout, NULL);
  669 
  670 		/* Catch non-restartable errors, that is, not signals nor
  671 		 * kernel out of resources. */
  672 		if (rc < 0 && (errno != EINTR && errno != EAGAIN))
  673 			fatale("cannot monitor notification socket for activity");
  674 
  675 		/* Timed-out. */
  676 		if (rc == 0)
  677 			fatal("timed out waiting for a notification");
  678 
  679 		/* Update the timeout, as should not rely on pselect() having
  680 		 * done that for us, which is an unportable assumption. */
  681 		timespec_gettime(&now);
  682 		timespec_sub(&now, &startat, &elapsed);
  683 		timespec_sub(&timeout_orig, &elapsed, &timeout);
  684 
  685 		/* Restartable error, a signal or kernel out of resources. */
  686 		if (rc < 0)
  687 			continue;
  688 
  689 		/* Parse it and check for a supported notification message,
  690 		 * once we get a READY=1, we exit. */
  691 		for (;;) {
  692 			ssize_t nrecv;
  693 			char buf[4096];
  694 			char *line, *line_next;
  695 
  696 			nrecv = recv(fd, buf, sizeof(buf), 0);
  697 			if (nrecv < 0 && (errno != EINTR && errno != EAGAIN))
  698 				fatale("cannot receive notification packet");
  699 			if (nrecv < 0)
  700 				break;
  701 
  702 			buf[nrecv] = '\0';
  703 
  704 			for (line = buf; *line; line = line_next) {
  705 				line_next = strchrnul(line, '\n');
  706 				if (*line_next == '\n')
  707 					*line_next++ = '\0';
  708 
  709 				debug("Child sent some notification...\n");
  710 				if (strncmp(line, "EXTEND_TIMEOUT_USEC=", 20) == 0) {
  711 					int extend_usec = 0;
  712 
  713 					if (parse_unsigned(line + 20, 10, &extend_usec) != 0)
  714 						fatale("cannot parse extended timeout notification %s", line);
  715 
  716 					/* Reset the current timeout. */
  717 					timeout.tv_sec = extend_usec / 1000L;
  718 					timeout.tv_nsec = (extend_usec % 1000L) *
  719 					                  NANOSEC_IN_MILLISEC;
  720 					timeout_orig = timeout;
  721 
  722 					timespec_gettime(&startat);
  723 				} else if (strncmp(line, "ERRNO=", 6) == 0) {
  724 					int suberrno = 0;
  725 
  726 					if (parse_unsigned(line + 6, 10, &suberrno) != 0)
  727 						fatale("cannot parse errno notification %s", line);
  728 					errno = suberrno;
  729 					fatale("program failed to initialize");
  730 				} else if (strcmp(line, "READY=1") == 0) {
  731 					debug("-> Notification => ready for service.\n");
  732 					return;
  733 				} else {
  734 					debug("-> Notification line '%s' received\n", line);
  735 				}
  736 			}
  737 		}
  738 	}
  739 }
  740 
  741 static void
  742 write_pidfile(const char *filename, pid_t pid)
  743 {
  744 	FILE *fp;
  745 	int fd;
  746 
  747 	fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW, 0666);
  748 	if (fd < 0)
  749 		fp = NULL;
  750 	else
  751 		fp = fdopen(fd, "w");
  752 
  753 	if (fp == NULL)
  754 		fatale("unable to open pidfile '%s' for writing", filename);
  755 
  756 	fprintf(fp, "%d\n", pid);
  757 
  758 	if (fclose(fp))
  759 		fatale("unable to close pidfile '%s'", filename);
  760 }
  761 
  762 static void
  763 remove_pidfile(const char *filename)
  764 {
  765 	if (unlink(filename) < 0 && errno != ENOENT)
  766 		fatale("cannot remove pidfile '%s'", filename);
  767 }
  768 
  769 static void
  770 daemonize(void)
  771 {
  772 	int notify_fd = -1;
  773 	pid_t pid;
  774 	sigset_t mask;
  775 	sigset_t oldmask;
  776 
  777 	debug("Detaching to start %s...\n", startas);
  778 
  779 	/* Block SIGCHLD to allow waiting for the child process while it is
  780 	 * performing actions, such as creating a pidfile. */
  781 	sigemptyset(&mask);
  782 	sigaddset(&mask, SIGCHLD);
  783 	if (sigprocmask(SIG_BLOCK, &mask, &oldmask) == -1)
  784 		fatale("cannot block SIGCHLD");
  785 
  786 	if (notify_await)
  787 		notify_fd = create_notify_socket();
  788 
  789 	pid = fork();
  790 	if (pid < 0)
  791 		fatale("unable to do first fork");
  792 	else if (pid) { /* First Parent. */
  793 		/* Wait for the second parent to exit, so that if we need to
  794 		 * perform any actions there, like creating a pidfile, we do
  795 		 * not suffer from race conditions on return. */
  796 		wait_for_child(pid);
  797 
  798 		if (notify_await) {
  799 			/* Wait for a readiness notification from the second
  800 			 * child, so that we can safely exit when the service
  801 			 * is up. */
  802 			wait_for_notify(notify_fd);
  803 			close(notify_fd);
  804 			cleanup_socket_dir();
  805 		}
  806 
  807 		_exit(0);
  808 	}
  809 
  810 	/* Close the notification socket, even though it is close-on-exec. */
  811 	if (notify_await)
  812 		close(notify_fd);
  813 
  814 	/* Create a new session. */
  815 	if (setsid() < 0)
  816 		fatale("cannot set session ID");
  817 
  818 	pid = fork();
  819 	if (pid < 0)
  820 		fatale("unable to do second fork");
  821 	else if (pid) { /* Second parent. */
  822 		/* Set a default umask for dumb programs, which might get
  823 		 * overridden by the --umask option later on, so that we get
  824 		 * a defined umask when creating the pidfile. */
  825 		umask(022);
  826 
  827 		if (mpidfile && pidfile != NULL)
  828 			/* User wants _us_ to make the pidfile. */
  829 			write_pidfile(pidfile, pid);
  830 
  831 		_exit(0);
  832 	}
  833 
  834 	if (sigprocmask(SIG_SETMASK, &oldmask, NULL) == -1)
  835 		fatale("cannot restore signal mask");
  836 
  837 	debug("Detaching complete...\n");
  838 }
  839 
  840 static void
  841 pid_list_push(struct pid_list **list, pid_t pid)
  842 {
  843 	struct pid_list *p;
  844 
  845 	p = xmalloc(sizeof(*p));
  846 	p->next = *list;
  847 	p->pid = pid;
  848 	*list = p;
  849 }
  850 
  851 static void
  852 pid_list_free(struct pid_list **list)
  853 {
  854 	struct pid_list *here, *next;
  855 
  856 	for (here = *list; here != NULL; here = next) {
  857 		next = here->next;
  858 		free(here);
  859 	}
  860 
  861 	*list = NULL;
  862 }
  863 
  864 static void
  865 usage(void)
  866 {
  867 	printf(
  868 "Usage: start-stop-daemon [<option>...] <command>\n"
  869 "\n");
  870 
  871 	printf(
  872 "Commands:\n"
  873 "  -S, --start -- <argument>...  start a program and pass <arguments> to it\n"
  874 "  -K, --stop                    stop a program\n"
  875 "  -T, --status                  get the program status\n"
  876 "  -H, --help                    print help information\n"
  877 "  -V, --version                 print version\n"
  878 "\n");
  879 
  880 	printf(
  881 "Matching options (at least one is required):\n"
  882 "      --pid <pid>               pid to check\n"
  883 "      --ppid <ppid>             parent pid to check\n"
  884 "  -p, --pidfile <pid-file>      pid file to check\n"
  885 "  -x, --exec <executable>       program to start/check if it is running\n"
  886 "  -n, --name <process-name>     process name to check\n"
  887 "  -u, --user <username|uid>     process owner to check\n"
  888 "\n");
  889 
  890 	printf(
  891 "Options:\n"
  892 "  -g, --group <group|gid>       run process as this group\n"
  893 "  -c, --chuid <name|uid[:group|gid]>\n"
  894 "                                change to this user/group before starting\n"
  895 "                                  process\n"
  896 "  -s, --signal <signal>         signal to send (default TERM)\n"
  897 "  -a, --startas <pathname>      program to start (default is <executable>)\n"
  898 "  -r, --chroot <directory>      chroot to <directory> before starting\n"
  899 "  -d, --chdir <directory>       change to <directory> (default is /)\n"
  900 "  -N, --nicelevel <incr>        add incr to the process' nice level\n"
  901 "  -P, --procsched <policy[:prio]>\n"
  902 "                                use <policy> with <prio> for the kernel\n"
  903 "                                  process scheduler (default prio is 0)\n"
  904 "  -I, --iosched <class[:prio]>  use <class> with <prio> to set the IO\n"
  905 "                                  scheduler (default prio is 4)\n"
  906 "  -k, --umask <mask>            change the umask to <mask> before starting\n"
  907 "  -b, --background              force the process to detach\n"
  908 "      --notify-await            wait for a readiness notification\n"
  909 "      --notify-timeout <int>    timeout after <int> seconds of notify wait\n"
  910 "  -C, --no-close                do not close any file descriptor\n"
  911 "  -m, --make-pidfile            create the pidfile before starting\n"
  912 "      --remove-pidfile          delete the pidfile after stopping\n"
  913 "  -R, --retry <schedule>        check whether processes die, and retry\n"
  914 "  -t, --test                    test mode, don't do anything\n"
  915 "  -o, --oknodo                  exit status 0 (not 1) if nothing done\n"
  916 "  -q, --quiet                   be more quiet\n"
  917 "  -v, --verbose                 be more verbose\n"
  918 "\n");
  919 
  920 	printf(
  921 "Retry <schedule> is <item>|/<item>/... where <item> is one of\n"
  922 " -<signal-num>|[-]<signal-name>  send that signal\n"
  923 " <timeout>                       wait that many seconds\n"
  924 " forever                         repeat remainder forever\n"
  925 "or <schedule> may be just <timeout>, meaning <signal>/<timeout>/KILL/<timeout>\n"
  926 "\n");
  927 
  928 	printf(
  929 "The process scheduler <policy> can be one of:\n"
  930 "  other, fifo or rr\n"
  931 "\n");
  932 
  933 	printf(
  934 "The IO scheduler <class> can be one of:\n"
  935 "  real-time, best-effort or idle\n"
  936 "\n");
  937 
  938 	printf(
  939 "Exit status:\n"
  940 "  0 = done\n"
  941 "  1 = nothing done (=> 0 if --oknodo)\n"
  942 "  2 = with --retry, processes would not die\n"
  943 "  3 = trouble\n"
  944 "Exit status with --status:\n"
  945 "  0 = program is running\n"
  946 "  1 = program is not running and the pid file exists\n"
  947 "  3 = program is not running\n"
  948 "  4 = unable to determine status\n");
  949 }
  950 
  951 static void
  952 do_version(void)
  953 {
  954 	printf("start-stop-daemon %s for Debian\n\n", VERSION);
  955 
  956 	printf("Written by Marek Michalkiewicz, public domain.\n");
  957 }
  958 
  959 static void DPKG_ATTR_NORET
  960 badusage(const char *msg)
  961 {
  962 	if (msg)
  963 		fprintf(stderr, "%s: %s\n", progname, msg);
  964 	fprintf(stderr, "Try '%s --help' for more information.\n", progname);
  965 
  966 	if (action == ACTION_STATUS)
  967 		exit(STATUS_UNKNOWN);
  968 	else
  969 		exit(3);
  970 }
  971 
  972 struct sigpair {
  973 	const char *name;
  974 	int signal;
  975 };
  976 
  977 static const struct sigpair siglist[] = {
  978 	{ "ABRT",	SIGABRT	},
  979 	{ "ALRM",	SIGALRM	},
  980 	{ "FPE",	SIGFPE	},
  981 	{ "HUP",	SIGHUP	},
  982 	{ "ILL",	SIGILL	},
  983 	{ "INT",	SIGINT	},
  984 	{ "KILL",	SIGKILL	},
  985 	{ "PIPE",	SIGPIPE	},
  986 	{ "QUIT",	SIGQUIT	},
  987 	{ "SEGV",	SIGSEGV	},
  988 	{ "TERM",	SIGTERM	},
  989 	{ "USR1",	SIGUSR1	},
  990 	{ "USR2",	SIGUSR2	},
  991 	{ "CHLD",	SIGCHLD	},
  992 	{ "CONT",	SIGCONT	},
  993 	{ "STOP",	SIGSTOP	},
  994 	{ "TSTP",	SIGTSTP	},
  995 	{ "TTIN",	SIGTTIN	},
  996 	{ "TTOU",	SIGTTOU	}
  997 };
  998 
  999 static int
 1000 parse_pid(const char *pid_str, int *pid_num)
 1001 {
 1002 	if (parse_unsigned(pid_str, 10, pid_num) != 0)
 1003 		return -1;
 1004 	if (*pid_num == 0)
 1005 		return -1;
 1006 
 1007 	return 0;
 1008 }
 1009 
 1010 static int
 1011 parse_signal(const char *sig_str, int *sig_num)
 1012 {
 1013 	unsigned int i;
 1014 
 1015 	if (parse_unsigned(sig_str, 10, sig_num) == 0)
 1016 		return 0;
 1017 
 1018 	for (i = 0; i < array_count(siglist); i++) {
 1019 		if (strcmp(sig_str, siglist[i].name) == 0) {
 1020 			*sig_num = siglist[i].signal;
 1021 			return 0;
 1022 		}
 1023 	}
 1024 	return -1;
 1025 }
 1026 
 1027 static int
 1028 parse_umask(const char *string, int *value_r)
 1029 {
 1030 	return parse_unsigned(string, 0, value_r);
 1031 }
 1032 
 1033 static void
 1034 validate_proc_schedule(void)
 1035 {
 1036 #if defined(_POSIX_PRIORITY_SCHEDULING) && _POSIX_PRIORITY_SCHEDULING > 0
 1037 	int prio_min, prio_max;
 1038 
 1039 	prio_min = sched_get_priority_min(proc_sched->policy);
 1040 	prio_max = sched_get_priority_max(proc_sched->policy);
 1041 
 1042 	if (proc_sched->priority < prio_min)
 1043 		badusage("process scheduler priority less than min");
 1044 	if (proc_sched->priority > prio_max)
 1045 		badusage("process scheduler priority greater than max");
 1046 #endif
 1047 }
 1048 
 1049 static void
 1050 parse_proc_schedule(const char *string)
 1051 {
 1052 	char *policy_str;
 1053 	size_t policy_len;
 1054 	int prio = 0;
 1055 
 1056 	policy_len = strcspn(string, ":");
 1057 	policy_str = xstrndup(string, policy_len);
 1058 
 1059 	if (string[policy_len] == ':' &&
 1060 	    parse_unsigned(string + policy_len + 1, 10, &prio) != 0)
 1061 		fatale("invalid process scheduler priority");
 1062 
 1063 	proc_sched = xmalloc(sizeof(*proc_sched));
 1064 	proc_sched->policy_name = policy_str;
 1065 
 1066 	if (strcmp(policy_str, "other") == 0) {
 1067 		proc_sched->policy = SCHED_OTHER;
 1068 		proc_sched->priority = 0;
 1069 	} else if (strcmp(policy_str, "fifo") == 0) {
 1070 		proc_sched->policy = SCHED_FIFO;
 1071 		proc_sched->priority = prio;
 1072 	} else if (strcmp(policy_str, "rr") == 0) {
 1073 		proc_sched->policy = SCHED_RR;
 1074 		proc_sched->priority = prio;
 1075 	} else
 1076 		badusage("invalid process scheduler policy");
 1077 
 1078 	validate_proc_schedule();
 1079 }
 1080 
 1081 static void
 1082 parse_io_schedule(const char *string)
 1083 {
 1084 	char *class_str;
 1085 	size_t class_len;
 1086 	int prio = 4;
 1087 
 1088 	class_len = strcspn(string, ":");
 1089 	class_str = xstrndup(string, class_len);
 1090 
 1091 	if (string[class_len] == ':' &&
 1092 	    parse_unsigned(string + class_len + 1, 10, &prio) != 0)
 1093 		fatale("invalid IO scheduler priority");
 1094 
 1095 	io_sched = xmalloc(sizeof(*io_sched));
 1096 	io_sched->policy_name = class_str;
 1097 
 1098 	if (strcmp(class_str, "real-time") == 0) {
 1099 		io_sched->policy = IOPRIO_CLASS_RT;
 1100 		io_sched->priority = prio;
 1101 	} else if (strcmp(class_str, "best-effort") == 0) {
 1102 		io_sched->policy = IOPRIO_CLASS_BE;
 1103 		io_sched->priority = prio;
 1104 	} else if (strcmp(class_str, "idle") == 0) {
 1105 		io_sched->policy = IOPRIO_CLASS_IDLE;
 1106 		io_sched->priority = 7;
 1107 	} else
 1108 		badusage("invalid IO scheduler policy");
 1109 
 1110 	if (io_sched->priority < IO_SCHED_PRIO_MIN)
 1111 		badusage("IO scheduler priority less than min");
 1112 	if (io_sched->priority > IO_SCHED_PRIO_MAX)
 1113 		badusage("IO scheduler priority greater than max");
 1114 }
 1115 
 1116 static void
 1117 set_proc_schedule(struct res_schedule *sched)
 1118 {
 1119 #if defined(_POSIX_PRIORITY_SCHEDULING) && _POSIX_PRIORITY_SCHEDULING > 0
 1120 	struct sched_param param;
 1121 
 1122 	param.sched_priority = sched->priority;
 1123 
 1124 	if (sched_setscheduler(getpid(), sched->policy, &param) == -1)
 1125 		fatale("unable to set process scheduler");
 1126 #endif
 1127 }
 1128 
 1129 #ifdef HAVE_IOPRIO_SET
 1130 static inline int
 1131 ioprio_set(int which, int who, int ioprio)
 1132 {
 1133 	return syscall(SYS_ioprio_set, which, who, ioprio);
 1134 }
 1135 #endif
 1136 
 1137 static void
 1138 set_io_schedule(struct res_schedule *sched)
 1139 {
 1140 #ifdef HAVE_IOPRIO_SET
 1141 	int io_sched_mask;
 1142 
 1143 	io_sched_mask = IOPRIO_PRIO_VALUE(sched->policy, sched->priority);
 1144 	if (ioprio_set(IOPRIO_WHO_PROCESS, getpid(), io_sched_mask) == -1)
 1145 		warning("unable to alter IO priority to mask %i (%s)\n",
 1146 		        io_sched_mask, strerror(errno));
 1147 #endif
 1148 }
 1149 
 1150 static void
 1151 parse_schedule_item(const char *string, struct schedule_item *item)
 1152 {
 1153 	const char *after_hyph;
 1154 
 1155 	if (strcmp(string, "forever") == 0) {
 1156 		item->type = sched_forever;
 1157 	} else if (isdigit(string[0])) {
 1158 		item->type = sched_timeout;
 1159 		if (parse_unsigned(string, 10, &item->value) != 0)
 1160 			badusage("invalid timeout value in schedule");
 1161 	} else if ((after_hyph = string + (string[0] == '-')) &&
 1162 	           parse_signal(after_hyph, &item->value) == 0) {
 1163 		item->type = sched_signal;
 1164 	} else {
 1165 		badusage("invalid schedule item (must be [-]<signal-name>, "
 1166 		         "-<signal-number>, <timeout> or 'forever'");
 1167 	}
 1168 }
 1169 
 1170 static void
 1171 parse_schedule(const char *schedule_str)
 1172 {
 1173 	char item_buf[20];
 1174 	const char *slash;
 1175 	int count, repeatat;
 1176 	size_t str_len;
 1177 
 1178 	count = 0;
 1179 	for (slash = schedule_str; *slash; slash++)
 1180 		if (*slash == '/')
 1181 			count++;
 1182 
 1183 	schedule_length = (count == 0) ? 4 : count + 1;
 1184 	schedule = xmalloc(sizeof(*schedule) * schedule_length);
 1185 
 1186 	if (count == 0) {
 1187 		schedule[0].type = sched_signal;
 1188 		schedule[0].value = signal_nr;
 1189 		parse_schedule_item(schedule_str, &schedule[1]);
 1190 		if (schedule[1].type != sched_timeout) {
 1191 			badusage("--retry takes timeout, or schedule list"
 1192 			         " of at least two items");
 1193 		}
 1194 		schedule[2].type = sched_signal;
 1195 		schedule[2].value = SIGKILL;
 1196 		schedule[3] = schedule[1];
 1197 	} else {
 1198 		count = 0;
 1199 		repeatat = -1;
 1200 		while (*schedule_str) {
 1201 			slash = strchrnul(schedule_str, '/');
 1202 			str_len = (size_t)(slash - schedule_str);
 1203 			if (str_len >= sizeof(item_buf))
 1204 				badusage("invalid schedule item: far too long"
 1205 				         " (you must delimit items with slashes)");
 1206 			memcpy(item_buf, schedule_str, str_len);
 1207 			item_buf[str_len] = '\0';
 1208 			schedule_str = *slash ? slash + 1 : slash;
 1209 
 1210 			parse_schedule_item(item_buf, &schedule[count]);
 1211 			if (schedule[count].type == sched_forever) {
 1212 				if (repeatat >= 0)
 1213 					badusage("invalid schedule: 'forever'"
 1214 					         " appears more than once");
 1215 				repeatat = count;
 1216 				continue;
 1217 			}
 1218 			count++;
 1219 		}
 1220 		if (repeatat == count)
 1221 			badusage("invalid schedule: 'forever' appears last, "
 1222 			         "nothing to repeat");
 1223 		if (repeatat >= 0) {
 1224 			schedule[count].type = sched_goto;
 1225 			schedule[count].value = repeatat;
 1226 			count++;
 1227 		}
 1228 		if (count != schedule_length)
 1229 			BUG("count=%d != schedule_length=%d",
 1230 			    count, schedule_length);
 1231 	}
 1232 }
 1233 
 1234 static void
 1235 set_action(enum action_code new_action)
 1236 {
 1237 	if (action == new_action)
 1238 		return;
 1239 
 1240 	if (action != ACTION_NONE)
 1241 		badusage("only one command can be specified");
 1242 
 1243 	action = new_action;
 1244 }
 1245 
 1246 #define OPT_PID		500
 1247 #define OPT_PPID	501
 1248 #define OPT_RM_PIDFILE	502
 1249 #define OPT_NOTIFY_AWAIT	503
 1250 #define OPT_NOTIFY_TIMEOUT	504
 1251 
 1252 static void
 1253 parse_options(int argc, char * const *argv)
 1254 {
 1255 	static struct option longopts[] = {
 1256 		{ "help",	  0, NULL, 'H'},
 1257 		{ "stop",	  0, NULL, 'K'},
 1258 		{ "start",	  0, NULL, 'S'},
 1259 		{ "status",	  0, NULL, 'T'},
 1260 		{ "version",	  0, NULL, 'V'},
 1261 		{ "startas",	  1, NULL, 'a'},
 1262 		{ "name",	  1, NULL, 'n'},
 1263 		{ "oknodo",	  0, NULL, 'o'},
 1264 		{ "pid",	  1, NULL, OPT_PID},
 1265 		{ "ppid",	  1, NULL, OPT_PPID},
 1266 		{ "pidfile",	  1, NULL, 'p'},
 1267 		{ "quiet",	  0, NULL, 'q'},
 1268 		{ "signal",	  1, NULL, 's'},
 1269 		{ "test",	  0, NULL, 't'},
 1270 		{ "user",	  1, NULL, 'u'},
 1271 		{ "group",	  1, NULL, 'g'},
 1272 		{ "chroot",	  1, NULL, 'r'},
 1273 		{ "verbose",	  0, NULL, 'v'},
 1274 		{ "exec",	  1, NULL, 'x'},
 1275 		{ "chuid",	  1, NULL, 'c'},
 1276 		{ "nicelevel",	  1, NULL, 'N'},
 1277 		{ "procsched",	  1, NULL, 'P'},
 1278 		{ "iosched",	  1, NULL, 'I'},
 1279 		{ "umask",	  1, NULL, 'k'},
 1280 		{ "background",	  0, NULL, 'b'},
 1281 		{ "notify-await", 0, NULL, OPT_NOTIFY_AWAIT},
 1282 		{ "notify-timeout", 1, NULL, OPT_NOTIFY_TIMEOUT},
 1283 		{ "no-close",	  0, NULL, 'C'},
 1284 		{ "make-pidfile", 0, NULL, 'm'},
 1285 		{ "remove-pidfile", 0, NULL, OPT_RM_PIDFILE},
 1286 		{ "retry",	  1, NULL, 'R'},
 1287 		{ "chdir",	  1, NULL, 'd'},
 1288 		{ NULL,		  0, NULL, 0  }
 1289 	};
 1290 	const char *pid_str = NULL;
 1291 	const char *ppid_str = NULL;
 1292 	const char *umask_str = NULL;
 1293 	const char *signal_str = NULL;
 1294 	const char *schedule_str = NULL;
 1295 	const char *proc_schedule_str = NULL;
 1296 	const char *io_schedule_str = NULL;
 1297 	const char *notify_timeout_str = NULL;
 1298 	size_t changeuser_len;
 1299 	int c;
 1300 
 1301 	for (;;) {
 1302 		c = getopt_long(argc, argv,
 1303 		                "HKSVTa:n:op:qr:s:tu:vx:c:N:P:I:k:bCmR:g:d:",
 1304 		                longopts, NULL);
 1305 		if (c == -1)
 1306 			break;
 1307 		switch (c) {
 1308 		case 'H':  /* --help */
 1309 			usage();
 1310 			exit(0);
 1311 		case 'K':  /* --stop */
 1312 			set_action(ACTION_STOP);
 1313 			break;
 1314 		case 'S':  /* --start */
 1315 			set_action(ACTION_START);
 1316 			break;
 1317 		case 'T':  /* --status */
 1318 			set_action(ACTION_STATUS);
 1319 			break;
 1320 		case 'V':  /* --version */
 1321 			do_version();
 1322 			exit(0);
 1323 		case 'a':  /* --startas <pathname> */
 1324 			startas = optarg;
 1325 			break;
 1326 		case 'n':  /* --name <process-name> */
 1327 			match_mode |= MATCH_NAME;
 1328 			cmdname = optarg;
 1329 			break;
 1330 		case 'o':  /* --oknodo */
 1331 			exitnodo = 0;
 1332 			break;
 1333 		case OPT_PID: /* --pid <pid> */
 1334 			match_mode |= MATCH_PID;
 1335 			pid_str = optarg;
 1336 			break;
 1337 		case OPT_PPID: /* --ppid <ppid> */
 1338 			match_mode |= MATCH_PPID;
 1339 			ppid_str = optarg;
 1340 			break;
 1341 		case 'p':  /* --pidfile <pid-file> */
 1342 			match_mode |= MATCH_PIDFILE;
 1343 			pidfile = optarg;
 1344 			break;
 1345 		case 'q':  /* --quiet */
 1346 			quietmode = true;
 1347 			break;
 1348 		case 's':  /* --signal <signal> */
 1349 			signal_str = optarg;
 1350 			break;
 1351 		case 't':  /* --test */
 1352 			testmode = true;
 1353 			break;
 1354 		case 'u':  /* --user <username>|<uid> */
 1355 			match_mode |= MATCH_USER;
 1356 			userspec = optarg;
 1357 			break;
 1358 		case 'v':  /* --verbose */
 1359 			quietmode = -1;
 1360 			break;
 1361 		case 'x':  /* --exec <executable> */
 1362 			match_mode |= MATCH_EXEC;
 1363 			execname = optarg;
 1364 			break;
 1365 		case 'c':  /* --chuid <username>|<uid> */
 1366 			free(changeuser);
 1367 			/* We copy the string just in case we need the
 1368 			 * argument later. */
 1369 			changeuser_len = strcspn(optarg, ":");
 1370 			changeuser = xstrndup(optarg, changeuser_len);
 1371 			if (optarg[changeuser_len] == ':') {
 1372 				if (optarg[changeuser_len + 1] == '\0')
 1373 					fatal("missing group name");
 1374 				changegroup = optarg + changeuser_len + 1;
 1375 			}
 1376 			break;
 1377 		case 'g':  /* --group <group>|<gid> */
 1378 			changegroup = optarg;
 1379 			break;
 1380 		case 'r':  /* --chroot /new/root */
 1381 			changeroot = optarg;
 1382 			break;
 1383 		case 'N':  /* --nice */
 1384 			nicelevel = atoi(optarg);
 1385 			break;
 1386 		case 'P':  /* --procsched */
 1387 			proc_schedule_str = optarg;
 1388 			break;
 1389 		case 'I':  /* --iosched */
 1390 			io_schedule_str = optarg;
 1391 			break;
 1392 		case 'k':  /* --umask <mask> */
 1393 			umask_str = optarg;
 1394 			break;
 1395 		case 'b':  /* --background */
 1396 			background = true;
 1397 			break;
 1398 		case OPT_NOTIFY_AWAIT:
 1399 			notify_await = true;
 1400 			break;
 1401 		case OPT_NOTIFY_TIMEOUT:
 1402 			notify_timeout_str = optarg;
 1403 			break;
 1404 		case 'C': /* --no-close */
 1405 			close_io = false;
 1406 			break;
 1407 		case 'm':  /* --make-pidfile */
 1408 			mpidfile = true;
 1409 			break;
 1410 		case OPT_RM_PIDFILE: /* --remove-pidfile */
 1411 			rpidfile = true;
 1412 			break;
 1413 		case 'R':  /* --retry <schedule>|<timeout> */
 1414 			schedule_str = optarg;
 1415 			break;
 1416 		case 'd':  /* --chdir /new/dir */
 1417 			changedir = optarg;
 1418 			break;
 1419 		default:
 1420 			/* Message printed by getopt. */
 1421 			badusage(NULL);
 1422 		}
 1423 	}
 1424 
 1425 	if (pid_str != NULL) {
 1426 		if (parse_pid(pid_str, &match_pid) != 0)
 1427 			badusage("pid value must be a number greater than 0");
 1428 	}
 1429 
 1430 	if (ppid_str != NULL) {
 1431 		if (parse_pid(ppid_str, &match_ppid) != 0)
 1432 			badusage("ppid value must be a number greater than 0");
 1433 	}
 1434 
 1435 	if (signal_str != NULL) {
 1436 		if (parse_signal(signal_str, &signal_nr) != 0)
 1437 			badusage("signal value must be numeric or name"
 1438 			         " of signal (KILL, INT, ...)");
 1439 	}
 1440 
 1441 	if (schedule_str != NULL) {
 1442 		parse_schedule(schedule_str);
 1443 	}
 1444 
 1445 	if (proc_schedule_str != NULL)
 1446 		parse_proc_schedule(proc_schedule_str);
 1447 
 1448 	if (io_schedule_str != NULL)
 1449 		parse_io_schedule(io_schedule_str);
 1450 
 1451 	if (umask_str != NULL) {
 1452 		if (parse_umask(umask_str, &umask_value) != 0)
 1453 			badusage("umask value must be a positive number");
 1454 	}
 1455 
 1456 	if (notify_timeout_str != NULL)
 1457 		if (parse_unsigned(notify_timeout_str, 10, &notify_timeout) != 0)
 1458 			badusage("invalid notify timeout value");
 1459 
 1460 	if (action == ACTION_NONE)
 1461 		badusage("need one of --start or --stop or --status");
 1462 
 1463 	if (match_mode == MATCH_NONE ||
 1464 	    (!execname && !cmdname && !userspec &&
 1465 	     !pid_str && !ppid_str && !pidfile))
 1466 		badusage("need at least one of --exec, --pid, --ppid, --pidfile, --user or --name");
 1467 
 1468 #ifdef PROCESS_NAME_SIZE
 1469 	if (cmdname && strlen(cmdname) > PROCESS_NAME_SIZE)
 1470 		warning("this system is not able to track process names\n"
 1471 		        "longer than %d characters, please use --exec "
 1472 		        "instead of --name.\n", PROCESS_NAME_SIZE);
 1473 #endif
 1474 
 1475 	if (!startas)
 1476 		startas = execname;
 1477 
 1478 	if (action == ACTION_START && !startas)
 1479 		badusage("--start needs --exec or --startas");
 1480 
 1481 	if (mpidfile && pidfile == NULL)
 1482 		badusage("--make-pidfile requires --pidfile");
 1483 	if (rpidfile && pidfile == NULL)
 1484 		badusage("--remove-pidfile requires --pidfile");
 1485 
 1486 	if (pid_str && pidfile)
 1487 		badusage("need either --pid or --pidfile, not both");
 1488 
 1489 	if (background && action != ACTION_START)
 1490 		badusage("--background is only relevant with --start");
 1491 
 1492 	if (!close_io && !background)
 1493 		badusage("--no-close is only relevant with --background");
 1494 }
 1495 
 1496 static void
 1497 setup_options(void)
 1498 {
 1499 	if (execname) {
 1500 		char *fullexecname;
 1501 
 1502 		/* If it's a relative path, normalize it. */
 1503 		if (execname[0] != '/')
 1504 			execname = newpath(changedir, execname);
 1505 
 1506 		if (changeroot)
 1507 			fullexecname = newpath(changeroot, execname);
 1508 		else
 1509 			fullexecname = execname;
 1510 
 1511 		if (stat(fullexecname, &exec_stat))
 1512 			fatale("unable to stat %s", fullexecname);
 1513 
 1514 		if (fullexecname != execname)
 1515 			free(fullexecname);
 1516 	}
 1517 
 1518 	if (userspec && parse_unsigned(userspec, 10, &user_id) < 0) {
 1519 		struct passwd *pw;
 1520 
 1521 		pw = getpwnam(userspec);
 1522 		if (!pw)
 1523 			fatale("user '%s' not found", userspec);
 1524 
 1525 		user_id = pw->pw_uid;
 1526 	}
 1527 
 1528 	if (changegroup && parse_unsigned(changegroup, 10, &runas_gid) < 0) {
 1529 		struct group *gr;
 1530 
 1531 		gr = getgrnam(changegroup);
 1532 		if (!gr)
 1533 			fatale("group '%s' not found", changegroup);
 1534 		changegroup = gr->gr_name;
 1535 		runas_gid = gr->gr_gid;
 1536 	}
 1537 	if (changeuser) {
 1538 		struct passwd *pw;
 1539 		struct stat st;
 1540 
 1541 		if (parse_unsigned(changeuser, 10, &runas_uid) == 0)
 1542 			pw = getpwuid(runas_uid);
 1543 		else
 1544 			pw = getpwnam(changeuser);
 1545 		if (!pw)
 1546 			fatale("user '%s' not found", changeuser);
 1547 		changeuser = pw->pw_name;
 1548 		runas_uid = pw->pw_uid;
 1549 		if (changegroup == NULL) {
 1550 			/* Pass the default group of this user. */
 1551 			changegroup = ""; /* Just empty. */
 1552 			runas_gid = pw->pw_gid;
 1553 		}
 1554 		if (stat(pw->pw_dir, &st) == 0)
 1555 			setenv("HOME", pw->pw_dir, 1);
 1556 	}
 1557 }
 1558 
 1559 #if defined(OS_Linux)
 1560 static const char *
 1561 proc_status_field(pid_t pid, const char *field)
 1562 {
 1563 	static char *line = NULL;
 1564 	static size_t line_size = 0;
 1565 
 1566 	FILE *fp;
 1567 	char filename[32];
 1568 	char *value = NULL;
 1569 	ssize_t line_len;
 1570 	size_t field_len = strlen(field);
 1571 
 1572 	sprintf(filename, "/proc/%d/status", pid);
 1573 	fp = fopen(filename, "r");
 1574 	if (!fp)
 1575 		return NULL;
 1576 	while ((line_len = getline(&line, &line_size, fp)) >= 0) {
 1577 		if (strncasecmp(line, field, field_len) == 0) {
 1578 			line[line_len - 1] = '\0';
 1579 
 1580 			value = line + field_len;
 1581 			while (isspace(*value))
 1582 				value++;
 1583 
 1584 			break;
 1585 		}
 1586 	}
 1587 	fclose(fp);
 1588 
 1589 	return value;
 1590 }
 1591 #elif defined(OS_AIX)
 1592 static bool
 1593 proc_get_psinfo(pid_t pid, struct psinfo *psinfo)
 1594 {
 1595 	char filename[64];
 1596 	FILE *fp;
 1597 
 1598 	sprintf(filename, "/proc/%d/psinfo", pid);
 1599 	fp = fopen(filename, "r");
 1600 	if (!fp)
 1601 		return false;
 1602 	if (fread(psinfo, sizeof(*psinfo), 1, fp) == 0) {
 1603 		fclose(fp);
 1604 		return false;
 1605 	}
 1606 	if (ferror(fp)) {
 1607 		fclose(fp);
 1608 		return false;
 1609 	}
 1610 
 1611 	fclose(fp);
 1612 
 1613 	return true;
 1614 }
 1615 #elif defined(OS_Hurd)
 1616 static void
 1617 init_procset(void)
 1618 {
 1619 	struct ps_context *context;
 1620 	error_t err;
 1621 
 1622 	err = ps_context_create(getproc(), &context);
 1623 	if (err)
 1624 		error(1, err, "ps_context_create");
 1625 
 1626 	err = proc_stat_list_create(context, &procset);
 1627 	if (err)
 1628 		error(1, err, "proc_stat_list_create");
 1629 
 1630 	err = proc_stat_list_add_all(procset, 0, 0);
 1631 	if (err)
 1632 		error(1, err, "proc_stat_list_add_all");
 1633 }
 1634 
 1635 static struct proc_stat *
 1636 get_proc_stat(pid_t pid, ps_flags_t flags)
 1637 {
 1638 	struct proc_stat *ps;
 1639 	ps_flags_t wanted_flags = PSTAT_PID | flags;
 1640 
 1641 	if (!procset)
 1642 		init_procset();
 1643 
 1644 	ps = proc_stat_list_pid_proc_stat(procset, pid);
 1645 	if (!ps)
 1646 		return NULL;
 1647 	if (proc_stat_set_flags(ps, wanted_flags))
 1648 		return NULL;
 1649 	if ((proc_stat_flags(ps) & wanted_flags) != wanted_flags)
 1650 		return NULL;
 1651 
 1652 	return ps;
 1653 }
 1654 #elif defined(HAVE_KVM_H)
 1655 static kvm_t *
 1656 ssd_kvm_open(void)
 1657 {
 1658 	kvm_t *kd;
 1659 	char errbuf[_POSIX2_LINE_MAX];
 1660 
 1661 	kd = kvm_openfiles(NULL, KVM_MEMFILE, NULL, O_RDONLY, errbuf);
 1662 	if (kd == NULL)
 1663 		errx(1, "%s", errbuf);
 1664 
 1665 	return kd;
 1666 }
 1667 
 1668 static struct kinfo_proc *
 1669 ssd_kvm_get_procs(kvm_t *kd, int op, int arg, int *count)
 1670 {
 1671 	struct kinfo_proc *kp;
 1672 	int lcount;
 1673 
 1674 	if (count == NULL)
 1675 		count = &lcount;
 1676 	*count = 0;
 1677 
 1678 #if defined(OS_OpenBSD)
 1679 	kp = kvm_getprocs(kd, op, arg, sizeof(*kp), count);
 1680 #else
 1681 	kp = kvm_getprocs(kd, op, arg, count);
 1682 #endif
 1683 	if (kp == NULL && errno != ESRCH)
 1684 		errx(1, "%s", kvm_geterr(kd));
 1685 
 1686 	return kp;
 1687 }
 1688 #endif
 1689 
 1690 #if defined(OS_Linux)
 1691 static bool
 1692 pid_is_exec(pid_t pid, const struct stat *esb)
 1693 {
 1694 	char lname[32];
 1695 	char lcontents[_POSIX_PATH_MAX + 1];
 1696 	char *filename;
 1697 	const char deleted[] = " (deleted)";
 1698 	int nread;
 1699 	struct stat sb;
 1700 
 1701 	sprintf(lname, "/proc/%d/exe", pid);
 1702 	nread = readlink(lname, lcontents, sizeof(lcontents) - 1);
 1703 	if (nread == -1)
 1704 		return false;
 1705 
 1706 	filename = lcontents;
 1707 	filename[nread] = '\0';
 1708 
 1709 	/* OpenVZ kernels contain a bogus patch that instead of appending,
 1710 	 * prepends the deleted marker. Workaround those. Otherwise handle
 1711 	 * the normal appended marker. */
 1712 	if (strncmp(filename, deleted, strlen(deleted)) == 0)
 1713 		filename += strlen(deleted);
 1714 	else if (strcmp(filename + nread - strlen(deleted), deleted) == 0)
 1715 		filename[nread - strlen(deleted)] = '\0';
 1716 
 1717 	if (stat(filename, &sb) != 0)
 1718 		return false;
 1719 
 1720 	return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
 1721 }
 1722 #elif defined(OS_AIX)
 1723 static bool
 1724 pid_is_exec(pid_t pid, const struct stat *esb)
 1725 {
 1726 	struct stat sb;
 1727 	char filename[64];
 1728 
 1729 	sprintf(filename, "/proc/%d/object/a.out", pid);
 1730 
 1731 	if (stat(filename, &sb) != 0)
 1732 		return false;
 1733 
 1734 	return sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino;
 1735 }
 1736 #elif defined(OS_Hurd)
 1737 static bool
 1738 pid_is_exec(pid_t pid, const struct stat *esb)
 1739 {
 1740 	struct proc_stat *ps;
 1741 	struct stat sb;
 1742 	const char *filename;
 1743 
 1744 	ps = get_proc_stat(pid, PSTAT_ARGS);
 1745 	if (ps == NULL)
 1746 		return false;
 1747 
 1748 	/* On old Hurd systems we have to use the argv[0] value, because
 1749 	 * there is nothing better. */
 1750 	filename = proc_stat_args(ps);
 1751 #ifdef PSTAT_EXE
 1752 	/* On new Hurd systems we can use the correct value, as long
 1753 	 * as it's not NULL nor empty, as it was the case on the first
 1754 	 * implementation. */
 1755 	if (proc_stat_set_flags(ps, PSTAT_EXE) == 0 &&
 1756 	    proc_stat_flags(ps) & PSTAT_EXE &&
 1757 	    proc_stat_exe(ps) != NULL &&
 1758 	    proc_stat_exe(ps)[0] != '\0')
 1759 		filename = proc_stat_exe(ps);
 1760 #endif
 1761 
 1762 	if (stat(filename, &sb) != 0)
 1763 		return false;
 1764 
 1765 	return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
 1766 }
 1767 #elif defined(OS_Darwin)
 1768 static bool
 1769 pid_is_exec(pid_t pid, const struct stat *esb)
 1770 {
 1771 	struct stat sb;
 1772 	char pathname[_POSIX_PATH_MAX];
 1773 
 1774 	if (proc_pidpath(pid, pathname, sizeof(pathname)) < 0)
 1775 		return false;
 1776 
 1777 	if (stat(pathname, &sb) != 0)
 1778 		return false;
 1779 
 1780 	return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
 1781 }
 1782 #elif defined(OS_HPUX)
 1783 static bool
 1784 pid_is_exec(pid_t pid, const struct stat *esb)
 1785 {
 1786 	struct pst_status pst;
 1787 
 1788 	if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
 1789 		return false;
 1790 	return ((dev_t)pst.pst_text.psf_fsid.psfs_id == esb->st_dev &&
 1791 	        (ino_t)pst.pst_text.psf_fileid == esb->st_ino);
 1792 }
 1793 #elif defined(OS_FreeBSD)
 1794 static bool
 1795 pid_is_exec(pid_t pid, const struct stat *esb)
 1796 {
 1797 	struct stat sb;
 1798 	int error, mib[4];
 1799 	size_t len;
 1800 	char pathname[PATH_MAX];
 1801 
 1802 	mib[0] = CTL_KERN;
 1803 	mib[1] = KERN_PROC;
 1804 	mib[2] = KERN_PROC_PATHNAME;
 1805 	mib[3] = pid;
 1806 	len = sizeof(pathname);
 1807 
 1808 	error = sysctl(mib, 4, pathname, &len, NULL, 0);
 1809 	if (error != 0 && errno != ESRCH)
 1810 		return false;
 1811 	if (len == 0)
 1812 		pathname[0] = '\0';
 1813 
 1814 	if (stat(pathname, &sb) != 0)
 1815 		return false;
 1816 
 1817 	return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
 1818 }
 1819 #elif defined(HAVE_KVM_H)
 1820 static bool
 1821 pid_is_exec(pid_t pid, const struct stat *esb)
 1822 {
 1823 	kvm_t *kd;
 1824 	int argv_len = 0;
 1825 	struct kinfo_proc *kp;
 1826 	struct stat sb;
 1827 	char buf[_POSIX2_LINE_MAX];
 1828 	char **pid_argv_p;
 1829 	char *start_argv_0_p, *end_argv_0_p;
 1830 	bool res = false;
 1831 
 1832 	kd = ssd_kvm_open();
 1833 	kp = ssd_kvm_get_procs(kd, KERN_PROC_PID, pid, NULL);
 1834 	if (kp == NULL)
 1835 		goto cleanup;
 1836 
 1837 	pid_argv_p = kvm_getargv(kd, kp, argv_len);
 1838 	if (pid_argv_p == NULL)
 1839 		errx(1, "%s", kvm_geterr(kd));
 1840 
 1841 	/* Find and compare string. */
 1842 	start_argv_0_p = *pid_argv_p;
 1843 
 1844 	/* Find end of argv[0] then copy and cut of str there. */
 1845 	end_argv_0_p = strchr(*pid_argv_p, ' ');
 1846 	if (end_argv_0_p == NULL)
 1847 		/* There seems to be no space, so we have the command
 1848 		 * already in its desired form. */
 1849 		start_argv_0_p = *pid_argv_p;
 1850 	else {
 1851 		/* Tests indicate that this never happens, since
 1852 		 * kvm_getargv itself cuts of tailing stuff. This is
 1853 		 * not what the manpage says, however. */
 1854 		strncpy(buf, *pid_argv_p, (end_argv_0_p - start_argv_0_p));
 1855 		buf[(end_argv_0_p - start_argv_0_p) + 1] = '\0';
 1856 		start_argv_0_p = buf;
 1857 	}
 1858 
 1859 	if (stat(start_argv_0_p, &sb) != 0)
 1860 		goto cleanup;
 1861 
 1862 	res = (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
 1863 
 1864 cleanup:
 1865 	kvm_close(kd);
 1866 
 1867 	return res;
 1868 }
 1869 #endif
 1870 
 1871 #if defined(OS_Linux)
 1872 static bool
 1873 pid_is_child(pid_t pid, pid_t ppid)
 1874 {
 1875 	const char *ppid_str;
 1876 	pid_t proc_ppid;
 1877 	int rc;
 1878 
 1879 	ppid_str = proc_status_field(pid, "PPid:");
 1880 	if (ppid_str == NULL)
 1881 		return false;
 1882 
 1883 	rc = parse_pid(ppid_str, &proc_ppid);
 1884 	if (rc < 0)
 1885 		return false;
 1886 
 1887 	return proc_ppid == ppid;
 1888 }
 1889 #elif defined(OS_Hurd)
 1890 static bool
 1891 pid_is_child(pid_t pid, pid_t ppid)
 1892 {
 1893 	struct proc_stat *ps;
 1894 	struct procinfo *pi;
 1895 
 1896 	ps = get_proc_stat(pid, PSTAT_PROC_INFO);
 1897 	if (ps == NULL)
 1898 		return false;
 1899 
 1900 	pi = proc_stat_proc_info(ps);
 1901 
 1902 	return pi->ppid == ppid;
 1903 }
 1904 #elif defined(OS_Darwin)
 1905 static bool
 1906 pid_is_child(pid_t pid, pid_t ppid)
 1907 {
 1908 	struct proc_bsdinfo info;
 1909 
 1910 	if (proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, sizeof(info)) < 0)
 1911 		return false;
 1912 
 1913 	return (pid_t)info.pbi_ppid == ppid;
 1914 }
 1915 #elif defined(OS_AIX)
 1916 static bool
 1917 pid_is_child(pid_t pid, pid_t ppid)
 1918 {
 1919 	struct psinfo psi;
 1920 
 1921 	if (!proc_get_psinfo(pid, &psi))
 1922 		return false;
 1923 
 1924 	return (pid_t)psi.pr_ppid == ppid;
 1925 }
 1926 #elif defined(OS_HPUX)
 1927 static bool
 1928 pid_is_child(pid_t pid, pid_t ppid)
 1929 {
 1930 	struct pst_status pst;
 1931 
 1932 	if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
 1933 		return false;
 1934 
 1935 	return pst.pst_ppid == ppid;
 1936 }
 1937 #elif defined(OS_FreeBSD)
 1938 static bool
 1939 pid_is_child(pid_t pid, pid_t ppid)
 1940 {
 1941 	struct kinfo_proc kp;
 1942 	int rc, mib[4];
 1943 	size_t len;
 1944 
 1945 	mib[0] = CTL_KERN;
 1946 	mib[1] = KERN_PROC;
 1947 	mib[2] = KERN_PROC_PID;
 1948 	mib[3] = pid;
 1949 	len = sizeof(kp);
 1950 
 1951 	rc = sysctl(mib, 4, &kp, &len, NULL, 0);
 1952 	if (rc != 0 && errno != ESRCH)
 1953 		return false;
 1954 	if (len == 0 || len != sizeof(kp))
 1955 		return false;
 1956 
 1957 	return kp.ki_ppid == ppid;
 1958 }
 1959 #elif defined(HAVE_KVM_H)
 1960 static bool
 1961 pid_is_child(pid_t pid, pid_t ppid)
 1962 {
 1963 	kvm_t *kd;
 1964 	struct kinfo_proc *kp;
 1965 	pid_t proc_ppid;
 1966 	bool res = false;
 1967 
 1968 	kd = ssd_kvm_open();
 1969 	kp = ssd_kvm_get_procs(kd, KERN_PROC_PID, pid, NULL);
 1970 	if (kp == NULL)
 1971 		goto cleanup;
 1972 
 1973 #if defined(OS_FreeBSD)
 1974 	proc_ppid = kp->ki_ppid;
 1975 #elif defined(OS_OpenBSD)
 1976 	proc_ppid = kp->p_ppid;
 1977 #elif defined(OS_DragonFlyBSD)
 1978 	proc_ppid = kp->kp_ppid;
 1979 #else
 1980 	proc_ppid = kp->kp_proc.p_ppid;
 1981 #endif
 1982 
 1983 	res = (proc_ppid == ppid);
 1984 
 1985 cleanup:
 1986 	kvm_close(kd);
 1987 
 1988 	return res;
 1989 }
 1990 #endif
 1991 
 1992 #if defined(OS_Linux)
 1993 static bool
 1994 pid_is_user(pid_t pid, uid_t uid)
 1995 {
 1996 	struct stat sb;
 1997 	char buf[32];
 1998 
 1999 	sprintf(buf, "/proc/%d", pid);
 2000 	if (stat(buf, &sb) != 0)
 2001 		return false;
 2002 	return (sb.st_uid == uid);
 2003 }
 2004 #elif defined(OS_Hurd)
 2005 static bool
 2006 pid_is_user(pid_t pid, uid_t uid)
 2007 {
 2008 	struct proc_stat *ps;
 2009 
 2010 	ps = get_proc_stat(pid, PSTAT_OWNER_UID);
 2011 	return ps && (uid_t)proc_stat_owner_uid(ps) == uid;
 2012 }
 2013 #elif defined(OS_Darwin)
 2014 static bool
 2015 pid_is_user(pid_t pid, uid_t uid)
 2016 {
 2017 	struct proc_bsdinfo info;
 2018 
 2019 	if (proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, sizeof(info)) < 0)
 2020 		return false;
 2021 
 2022 	return info.pbi_ruid == uid;
 2023 }
 2024 #elif defined(OS_AIX)
 2025 static bool
 2026 pid_is_user(pid_t pid, uid_t uid)
 2027 {
 2028 	struct psinfo psi;
 2029 
 2030 	if (!proc_get_psinfo(pid, &psi))
 2031 		return false;
 2032 
 2033 	return psi.pr_uid == uid;
 2034 }
 2035 #elif defined(OS_HPUX)
 2036 static bool
 2037 pid_is_user(pid_t pid, uid_t uid)
 2038 {
 2039 	struct pst_status pst;
 2040 
 2041 	if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
 2042 		return false;
 2043 	return ((uid_t)pst.pst_uid == uid);
 2044 }
 2045 #elif defined(OS_FreeBSD)
 2046 static bool
 2047 pid_is_user(pid_t pid, uid_t uid)
 2048 {
 2049 	struct kinfo_proc kp;
 2050 	int rc, mib[4];
 2051 	size_t len;
 2052 
 2053 	mib[0] = CTL_KERN;
 2054 	mib[1] = KERN_PROC;
 2055 	mib[2] = KERN_PROC_PID;
 2056 	mib[3] = pid;
 2057 	len = sizeof(kp);
 2058 
 2059 	rc = sysctl(mib, 4, &kp, &len, NULL, 0);
 2060 	if (rc != 0 && errno != ESRCH)
 2061 		return false;
 2062 	if (len == 0 || len != sizeof(kp))
 2063 		return false;
 2064 
 2065 	return kp.ki_ruid == uid;
 2066 }
 2067 #elif defined(HAVE_KVM_H)
 2068 static bool
 2069 pid_is_user(pid_t pid, uid_t uid)
 2070 {
 2071 	kvm_t *kd;
 2072 	uid_t proc_uid;
 2073 	struct kinfo_proc *kp;
 2074 	bool res = false;
 2075 
 2076 	kd = ssd_kvm_open();
 2077 	kp = ssd_kvm_get_procs(kd, KERN_PROC_PID, pid, NULL);
 2078 	if (kp == NULL)
 2079 		goto cleanup;
 2080 
 2081 #if defined(OS_FreeBSD)
 2082 	proc_uid = kp->ki_ruid;
 2083 #elif defined(OS_OpenBSD)
 2084 	proc_uid = kp->p_ruid;
 2085 #elif defined(OS_DragonFlyBSD)
 2086 	proc_uid = kp->kp_ruid;
 2087 #elif defined(OS_NetBSD)
 2088 	proc_uid = kp->kp_eproc.e_pcred.p_ruid;
 2089 #else
 2090 	if (kp->kp_proc.p_cred)
 2091 		kvm_read(kd, (u_long)&(kp->kp_proc.p_cred->p_ruid),
 2092 		         &proc_uid, sizeof(uid_t));
 2093 	else
 2094 		goto cleanup;
 2095 #endif
 2096 
 2097 	res = (proc_uid == (uid_t)uid);
 2098 
 2099 cleanup:
 2100 	kvm_close(kd);
 2101 
 2102 	return res;
 2103 }
 2104 #endif
 2105 
 2106 #if defined(OS_Linux)
 2107 static bool
 2108 pid_is_cmd(pid_t pid, const char *name)
 2109 {
 2110 	const char *comm;
 2111 
 2112 	comm = proc_status_field(pid, "Name:");
 2113 	if (comm == NULL)
 2114 		return false;
 2115 
 2116 	return strcmp(comm, name) == 0;
 2117 }
 2118 #elif defined(OS_Hurd)
 2119 static bool
 2120 pid_is_cmd(pid_t pid, const char *name)
 2121 {
 2122 	struct proc_stat *ps;
 2123 	size_t argv0_len;
 2124 	const char *argv0;
 2125 	const char *binary_name;
 2126 
 2127 	ps = get_proc_stat(pid, PSTAT_ARGS);
 2128 	if (ps == NULL)
 2129 		return false;
 2130 
 2131 	argv0 = proc_stat_args(ps);
 2132 	argv0_len = strlen(argv0) + 1;
 2133 
 2134 	binary_name = basename(argv0);
 2135 	if (strcmp(binary_name, name) == 0)
 2136 		return true;
 2137 
 2138 	/* XXX: This is all kinds of ugly, but on the Hurd there's no way to
 2139 	 * know the command name of a process, so we have to try to match
 2140 	 * also on argv[1] for the case of an interpreted script. */
 2141 	if (proc_stat_args_len(ps) > argv0_len) {
 2142 		const char *script_name = basename(argv0 + argv0_len);
 2143 
 2144 		return strcmp(script_name, name) == 0;
 2145 	}
 2146 
 2147 	return false;
 2148 }
 2149 #elif defined(OS_AIX)
 2150 static bool
 2151 pid_is_cmd(pid_t pid, const char *name)
 2152 {
 2153 	struct psinfo psi;
 2154 
 2155 	if (!proc_get_psinfo(pid, &psi))
 2156 		return false;
 2157 
 2158 	return strcmp(psi.pr_fname, name) == 0;
 2159 }
 2160 #elif defined(OS_HPUX)
 2161 static bool
 2162 pid_is_cmd(pid_t pid, const char *name)
 2163 {
 2164 	struct pst_status pst;
 2165 
 2166 	if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
 2167 		return false;
 2168 	return (strcmp(pst.pst_ucomm, name) == 0);
 2169 }
 2170 #elif defined(OS_Darwin)
 2171 static bool
 2172 pid_is_cmd(pid_t pid, const char *name)
 2173 {
 2174 	char pathname[_POSIX_PATH_MAX];
 2175 
 2176 	if (proc_pidpath(pid, pathname, sizeof(pathname)) < 0)
 2177 		return false;
 2178 
 2179 	return strcmp(pathname, name) == 0;
 2180 }
 2181 #elif defined(OS_FreeBSD)
 2182 static bool
 2183 pid_is_cmd(pid_t pid, const char *name)
 2184 {
 2185 	struct kinfo_proc kp;
 2186 	int rc, mib[4];
 2187 	size_t len;
 2188 
 2189 	mib[0] = CTL_KERN;
 2190 	mib[1] = KERN_PROC;
 2191 	mib[2] = KERN_PROC_PID;
 2192 	mib[3] = pid;
 2193 	len = sizeof(kp);
 2194 
 2195 	rc = sysctl(mib, 4, &kp, &len, NULL, 0);
 2196 	if (rc != 0 && errno != ESRCH)
 2197 		return false;
 2198 	if (len == 0 || len != sizeof(kp))
 2199 		return false;
 2200 
 2201 	return strcmp(kp.ki_comm, name) == 0;
 2202 }
 2203 #elif defined(HAVE_KVM_H)
 2204 static bool
 2205 pid_is_cmd(pid_t pid, const char *name)
 2206 {
 2207 	kvm_t *kd;
 2208 	struct kinfo_proc *kp;
 2209 	char *process_name;
 2210 	bool res = false;
 2211 
 2212 	kd = ssd_kvm_open();
 2213 	kp = ssd_kvm_get_procs(kd, KERN_PROC_PID, pid, NULL);
 2214 	if (kp == NULL)
 2215 		goto cleanup;
 2216 
 2217 #if defined(OS_FreeBSD)
 2218 	process_name = kp->ki_comm;
 2219 #elif defined(OS_OpenBSD)
 2220 	process_name = kp->p_comm;
 2221 #elif defined(OS_DragonFlyBSD)
 2222 	process_name = kp->kp_comm;
 2223 #else
 2224 	process_name = kp->kp_proc.p_comm;
 2225 #endif
 2226 
 2227 	res = (strcmp(name, process_name) == 0);
 2228 
 2229 cleanup:
 2230 	kvm_close(kd);
 2231 
 2232 	return res;
 2233 }
 2234 #endif
 2235 
 2236 #if defined(OS_Hurd)
 2237 static bool
 2238 pid_is_running(pid_t pid)
 2239 {
 2240 	return get_proc_stat(pid, 0) != NULL;
 2241 }
 2242 #else /* !OS_Hurd */
 2243 static bool
 2244 pid_is_running(pid_t pid)
 2245 {
 2246 	if (kill(pid, 0) == 0 || errno == EPERM)
 2247 		return true;
 2248 	else if (errno == ESRCH)
 2249 		return false;
 2250 	else
 2251 		fatale("error checking pid %u status", pid);
 2252 }
 2253 #endif
 2254 
 2255 static enum status_code
 2256 pid_check(pid_t pid)
 2257 {
 2258 	if (execname && !pid_is_exec(pid, &exec_stat))
 2259 		return STATUS_DEAD;
 2260 	if (match_ppid > 0 && !pid_is_child(pid, match_ppid))
 2261 		return STATUS_DEAD;
 2262 	if (userspec && !pid_is_user(pid, user_id))
 2263 		return STATUS_DEAD;
 2264 	if (cmdname && !pid_is_cmd(pid, cmdname))
 2265 		return STATUS_DEAD;
 2266 	if (action != ACTION_STOP && !pid_is_running(pid))
 2267 		return STATUS_DEAD;
 2268 
 2269 	pid_list_push(&found, pid);
 2270 
 2271 	return STATUS_OK;
 2272 }
 2273 
 2274 static enum status_code
 2275 do_pidfile(const char *name)
 2276 {
 2277 	FILE *f;
 2278 	static pid_t pid = 0;
 2279 
 2280 	if (pid)
 2281 		return pid_check(pid);
 2282 
 2283 	f = fopen(name, "r");
 2284 	if (f) {
 2285 		enum status_code pid_status;
 2286 
 2287 		/* If we are only matching on the pidfile, and it is owned by
 2288 		 * a non-root user, then this is a security risk, and the
 2289 		 * contents cannot be trusted, because the daemon might have
 2290 		 * been compromised.
 2291 		 *
 2292 		 * If the pidfile is world-writable we refuse to parse it.
 2293 		 *
 2294 		 * If we got /dev/null specified as the pidfile, we ignore the
 2295 		 * checks, as this is being used to run processes no matter
 2296 		 * what. */
 2297 		if (strcmp(name, "/dev/null") != 0) {
 2298 			struct stat st;
 2299 			int fd = fileno(f);
 2300 
 2301 			if (fstat(fd, &st) < 0)
 2302 				fatale("cannot stat pidfile %s", name);
 2303 
 2304 			if (match_mode == MATCH_PIDFILE &&
 2305 			    ((st.st_uid != getuid() && st.st_uid != 0) ||
 2306 			     (st.st_gid != getgid() && st.st_gid != 0)))
 2307 				fatal("matching only on non-root pidfile %s is insecure", name);
 2308 			if (st.st_mode & 0002)
 2309 				fatal("matching on world-writable pidfile %s is insecure", name);
 2310 
 2311 		}
 2312 
 2313 		if (fscanf(f, "%d", &pid) == 1)
 2314 			pid_status = pid_check(pid);
 2315 		else
 2316 			pid_status = STATUS_UNKNOWN;
 2317 		fclose(f);
 2318 
 2319 		if (pid_status == STATUS_DEAD)
 2320 			return STATUS_DEAD_PIDFILE;
 2321 		else
 2322 			return pid_status;
 2323 	} else if (errno == ENOENT)
 2324 		return STATUS_DEAD;
 2325 	else
 2326 		fatale("unable to open pidfile %s", name);
 2327 }
 2328 
 2329 #if defined(OS_Linux) || defined(OS_Solaris) || defined(OS_AIX)
 2330 static enum status_code
 2331 do_procinit(void)
 2332 {
 2333 	DIR *procdir;
 2334 	struct dirent *entry;
 2335 	int foundany;
 2336 	pid_t pid;
 2337 	enum status_code prog_status = STATUS_DEAD;
 2338 
 2339 	procdir = opendir("/proc");
 2340 	if (!procdir)
 2341 		fatale("unable to opendir /proc");
 2342 
 2343 	foundany = 0;
 2344 	while ((entry = readdir(procdir)) != NULL) {
 2345 		enum status_code pid_status;
 2346 
 2347 		if (sscanf(entry->d_name, "%d", &pid) != 1)
 2348 			continue;
 2349 		foundany++;
 2350 
 2351 		pid_status = pid_check(pid);
 2352 		if (pid_status < prog_status)
 2353 			prog_status = pid_status;
 2354 	}
 2355 	closedir(procdir);
 2356 	if (foundany == 0)
 2357 		fatal("nothing in /proc - not mounted?");
 2358 
 2359 	return prog_status;
 2360 }
 2361 #elif defined(OS_Hurd)
 2362 static int
 2363 check_proc_stat(struct proc_stat *ps)
 2364 {
 2365 	pid_check(proc_stat_pid(ps));
 2366 	return 0;
 2367 }
 2368 
 2369 static enum status_code
 2370 do_procinit(void)
 2371 {
 2372 	if (!procset)
 2373 		init_procset();
 2374 
 2375 	proc_stat_list_for_each(procset, check_proc_stat);
 2376 
 2377 	if (found)
 2378 		return STATUS_OK;
 2379 	else
 2380 		return STATUS_DEAD;
 2381 }
 2382 #elif defined(OS_Darwin)
 2383 static enum status_code
 2384 do_procinit(void)
 2385 {
 2386 	pid_t *pid_buf;
 2387 	int i, npids, pid_bufsize;
 2388 	enum status_code prog_status = STATUS_DEAD;
 2389 
 2390 	npids = proc_listallpids(NULL, 0);
 2391 	if (npids == 0)
 2392 		return STATUS_UNKNOWN;
 2393 
 2394 	/* Try to avoid sudden changes in number of PIDs. */
 2395 	npids += 4096;
 2396 	pid_bufsize = sizeof(pid_t) * npids;
 2397 	pid_buf = xmalloc(pid_bufsize);
 2398 
 2399 	npids = proc_listallpids(pid_buf, pid_bufsize);
 2400 	if (npids == 0)
 2401 		return STATUS_UNKNOWN;
 2402 
 2403 	for (i = 0; i < npids; i++) {
 2404 		enum status_code pid_status;
 2405 
 2406 		pid_status = pid_check(pid_buf[i]);
 2407 		if (pid_status < prog_status)
 2408 			prog_status = pid_status;
 2409 	}
 2410 
 2411 	free(pid_buf);
 2412 
 2413 	return prog_status;
 2414 }
 2415 #elif defined(OS_HPUX)
 2416 static enum status_code
 2417 do_procinit(void)
 2418 {
 2419 	struct pst_status pst[10];
 2420 	int i, count;
 2421 	int idx = 0;
 2422 	enum status_code prog_status = STATUS_DEAD;
 2423 
 2424 	while ((count = pstat_getproc(pst, sizeof(pst[0]), 10, idx)) > 0) {
 2425 		enum status_code pid_status;
 2426 
 2427 		for (i = 0; i < count; i++) {
 2428 			pid_status = pid_check(pst[i].pst_pid);
 2429 			if (pid_status < prog_status)
 2430 				prog_status = pid_status;
 2431 		}
 2432 		idx = pst[count - 1].pst_idx + 1;
 2433 	}
 2434 
 2435 	return prog_status;
 2436 }
 2437 #elif defined(OS_FreeBSD)
 2438 static enum status_code
 2439 do_procinit(void)
 2440 {
 2441 	struct kinfo_proc *kp;
 2442 	int rc, mib[3];
 2443 	size_t len = 0;
 2444 	int nentries, i;
 2445 	enum status_code prog_status = STATUS_DEAD;
 2446 
 2447 	mib[0] = CTL_KERN;
 2448 	mib[1] = KERN_PROC;
 2449 	mib[2] = KERN_PROC_PROC;
 2450 
 2451 	rc = sysctl(mib, 3, NULL, &len, NULL, 0);
 2452 	if (rc != 0 && errno != ESRCH)
 2453 		return STATUS_UNKNOWN;
 2454 	if (len == 0)
 2455 		return STATUS_UNKNOWN;
 2456 
 2457 	kp = xmalloc(len);
 2458 	rc = sysctl(mib, 3, kp, &len, NULL, 0);
 2459 	if (rc != 0 && errno != ESRCH)
 2460 		return STATUS_UNKNOWN;
 2461 	if (len == 0)
 2462 		return STATUS_UNKNOWN;
 2463 	nentries = len / sizeof(*kp);
 2464 
 2465 	for (i = 0; i < nentries; i++) {
 2466 		enum status_code pid_status;
 2467 
 2468 		pid_status = pid_check(kp[i].ki_pid);
 2469 		if (pid_status < prog_status)
 2470 			prog_status = pid_status;
 2471 	}
 2472 
 2473 	free(kp);
 2474 
 2475 	return prog_status;
 2476 }
 2477 #elif defined(HAVE_KVM_H)
 2478 static enum status_code
 2479 do_procinit(void)
 2480 {
 2481 	kvm_t *kd;
 2482 	int nentries, i;
 2483 	struct kinfo_proc *kp;
 2484 	enum status_code prog_status = STATUS_DEAD;
 2485 
 2486 	kd = ssd_kvm_open();
 2487 	kp = ssd_kvm_get_procs(kd, KERN_PROC_ALL, 0, &nentries);
 2488 
 2489 	for (i = 0; i < nentries; i++) {
 2490 		enum status_code pid_status;
 2491 		pid_t pid;
 2492 
 2493 #if defined(OS_FreeBSD)
 2494 		pid = kp[i].ki_pid;
 2495 #elif defined(OS_OpenBSD)
 2496 		pid = kp[i].p_pid;
 2497 #elif defined(OS_DragonFlyBSD)
 2498 		pid = kp[i].kp_pid;
 2499 #else
 2500 		pid = kp[i].kp_proc.p_pid;
 2501 #endif
 2502 
 2503 		pid_status = pid_check(pid);
 2504 		if (pid_status < prog_status)
 2505 			prog_status = pid_status;
 2506 	}
 2507 
 2508 	kvm_close(kd);
 2509 
 2510 	return prog_status;
 2511 }
 2512 #endif
 2513 
 2514 static enum status_code
 2515 do_findprocs(void)
 2516 {
 2517 	pid_list_free(&found);
 2518 
 2519 	if (match_pid > 0)
 2520 		return pid_check(match_pid);
 2521 	else if (pidfile)
 2522 		return do_pidfile(pidfile);
 2523 	else
 2524 		return do_procinit();
 2525 }
 2526 
 2527 static int
 2528 do_start(int argc, char **argv)
 2529 {
 2530 	int devnull_fd = -1;
 2531 	gid_t rgid;
 2532 	uid_t ruid;
 2533 
 2534 	do_findprocs();
 2535 
 2536 	if (found) {
 2537 		info("%s already running.\n", execname ? execname : "process");
 2538 		return exitnodo;
 2539 	}
 2540 	if (testmode && quietmode <= 0) {
 2541 		printf("Would start %s ", startas);
 2542 		while (argc-- > 0)
 2543 			printf("%s ", *argv++);
 2544 		if (changeuser != NULL) {
 2545 			printf(" (as user %s[%d]", changeuser, runas_uid);
 2546 			if (changegroup != NULL)
 2547 				printf(", and group %s[%d])", changegroup, runas_gid);
 2548 			else
 2549 				printf(")");
 2550 		}
 2551 		if (changeroot != NULL)
 2552 			printf(" in directory %s", changeroot);
 2553 		if (nicelevel)
 2554 			printf(", and add %i to the priority", nicelevel);
 2555 		if (proc_sched)
 2556 			printf(", with scheduling policy %s with priority %i",
 2557 			       proc_sched->policy_name, proc_sched->priority);
 2558 		if (io_sched)
 2559 			printf(", with IO scheduling class %s with priority %i",
 2560 			       io_sched->policy_name, io_sched->priority);
 2561 		printf(".\n");
 2562 	}
 2563 	if (testmode)
 2564 		return 0;
 2565 	debug("Starting %s...\n", startas);
 2566 	*--argv = startas;
 2567 	if (background)
 2568 		/* Ok, we need to detach this process. */
 2569 		daemonize();
 2570 	else if (mpidfile && pidfile != NULL)
 2571 		/* User wants _us_ to make the pidfile, but detach themself! */
 2572 		write_pidfile(pidfile, getpid());
 2573 	if (background && close_io) {
 2574 		devnull_fd = open("/dev/null", O_RDWR);
 2575 		if (devnull_fd < 0)
 2576 			fatale("unable to open '%s'", "/dev/null");
 2577 	}
 2578 	if (nicelevel) {
 2579 		errno = 0;
 2580 		if ((nice(nicelevel) == -1) && (errno != 0))
 2581 			fatale("unable to alter nice level by %i", nicelevel);
 2582 	}
 2583 	if (proc_sched)
 2584 		set_proc_schedule(proc_sched);
 2585 	if (io_sched)
 2586 		set_io_schedule(io_sched);
 2587 	if (umask_value >= 0)
 2588 		umask(umask_value);
 2589 	if (changeroot != NULL) {
 2590 		if (chdir(changeroot) < 0)
 2591 			fatale("unable to chdir() to %s", changeroot);
 2592 		if (chroot(changeroot) < 0)
 2593 			fatale("unable to chroot() to %s", changeroot);
 2594 	}
 2595 	if (chdir(changedir) < 0)
 2596 		fatale("unable to chdir() to %s", changedir);
 2597 
 2598 	rgid = getgid();
 2599 	ruid = getuid();
 2600 	if (changegroup != NULL) {
 2601 		if (rgid != (gid_t)runas_gid)
 2602 			if (setgid(runas_gid))
 2603 				fatale("unable to set gid to %d", runas_gid);
 2604 	}
 2605 	if (changeuser != NULL) {
 2606 		/* We assume that if our real user and group are the same as
 2607 		 * the ones we should switch to, the supplementary groups
 2608 		 * will be already in place. */
 2609 		if (rgid != (gid_t)runas_gid || ruid != (uid_t)runas_uid)
 2610 			if (initgroups(changeuser, runas_gid))
 2611 				fatale("unable to set initgroups() with gid %d",
 2612 				      runas_gid);
 2613 
 2614 		if (ruid != (uid_t)runas_uid)
 2615 			if (setuid(runas_uid))
 2616 				fatale("unable to set uid to %s", changeuser);
 2617 	}
 2618 
 2619 	if (background && close_io) {
 2620 		int i;
 2621 
 2622 		dup2(devnull_fd, 0); /* stdin */
 2623 		dup2(devnull_fd, 1); /* stdout */
 2624 		dup2(devnull_fd, 2); /* stderr */
 2625 
 2626 		 /* Now close all extra fds. */
 2627 		for (i = get_open_fd_max() - 1; i >= 3; --i)
 2628 			close(i);
 2629 	}
 2630 	execv(startas, argv);
 2631 	fatale("unable to start %s", startas);
 2632 }
 2633 
 2634 static void
 2635 do_stop(int sig_num, int *n_killed, int *n_notkilled)
 2636 {
 2637 	struct pid_list *p;
 2638 
 2639 	do_findprocs();
 2640 
 2641 	*n_killed = 0;
 2642 	*n_notkilled = 0;
 2643 
 2644 	if (!found)
 2645 		return;
 2646 
 2647 	pid_list_free(&killed);
 2648 
 2649 	for (p = found; p; p = p->next) {
 2650 		if (testmode) {
 2651 			info("Would send signal %d to %d.\n", sig_num, p->pid);
 2652 			(*n_killed)++;
 2653 		} else if (kill(p->pid, sig_num) == 0) {
 2654 			pid_list_push(&killed, p->pid);
 2655 			(*n_killed)++;
 2656 		} else {
 2657 			if (sig_num)
 2658 				warning("failed to kill %d: %s\n",
 2659 				        p->pid, strerror(errno));
 2660 			(*n_notkilled)++;
 2661 		}
 2662 	}
 2663 }
 2664 
 2665 static void
 2666 do_stop_summary(int retry_nr)
 2667 {
 2668 	struct pid_list *p;
 2669 
 2670 	if (quietmode >= 0 || !killed)
 2671 		return;
 2672 
 2673 	printf("Stopped %s (pid", what_stop);
 2674 	for (p = killed; p; p = p->next)
 2675 		printf(" %d", p->pid);
 2676 	putchar(')');
 2677 	if (retry_nr > 0)
 2678 		printf(", retry #%d", retry_nr);
 2679 	printf(".\n");
 2680 }
 2681 
 2682 static void DPKG_ATTR_PRINTF(1)
 2683 set_what_stop(const char *format, ...)
 2684 {
 2685 	va_list arglist;
 2686 	int rc;
 2687 
 2688 	va_start(arglist, format);
 2689 	rc = vasprintf(&what_stop, format, arglist);
 2690 	va_end(arglist);
 2691 
 2692 	if (rc < 0)
 2693 		fatale("cannot allocate formatted string");
 2694 }
 2695 
 2696 /*
 2697  * We want to keep polling for the processes, to see if they've exited, or
 2698  * until the timeout expires.
 2699  *
 2700  * This is a somewhat complicated algorithm to try to ensure that we notice
 2701  * reasonably quickly when all the processes have exited, but don't spend
 2702  * too much CPU time polling. In particular, on a fast machine with
 2703  * quick-exiting daemons we don't want to delay system shutdown too much,
 2704  * whereas on a slow one, or where processes are taking some time to exit,
 2705  * we want to increase the polling interval.
 2706  *
 2707  * The algorithm is as follows: we measure the elapsed time it takes to do
 2708  * one poll(), and wait a multiple of this time for the next poll. However,
 2709  * if that would put us past the end of the timeout period we wait only as
 2710  * long as the timeout period, but in any case we always wait at least
 2711  * MIN_POLL_INTERVAL (20ms). The multiple (‘ratio’) starts out as 2, and
 2712  * increases by 1 for each poll to a maximum of 10; so we use up to between
 2713  * 30% and 10% of the machine's resources (assuming a few reasonable things
 2714  * about system performance).
 2715  */
 2716 static bool
 2717 do_stop_timeout(int timeout, int *n_killed, int *n_notkilled)
 2718 {
 2719 	struct timespec stopat, before, after, interval, maxinterval;
 2720 	int rc, ratio;
 2721 
 2722 	timespec_gettime(&stopat);
 2723 	stopat.tv_sec += timeout;
 2724 	ratio = 1;
 2725 	for (;;) {
 2726 		timespec_gettime(&before);
 2727 		if (timespec_cmp(&before, &stopat, >))
 2728 			return false;
 2729 
 2730 		do_stop(0, n_killed, n_notkilled);
 2731 		if (!*n_killed)
 2732 			return true;
 2733 
 2734 		timespec_gettime(&after);
 2735 
 2736 		if (!timespec_cmp(&after, &stopat, <))
 2737 			return false;
 2738 
 2739 		if (ratio < 10)
 2740 			ratio++;
 2741 
 2742 		timespec_sub(&stopat, &after, &maxinterval);
 2743 		timespec_sub(&after, &before, &interval);
 2744 		timespec_mul(&interval, ratio);
 2745 
 2746 		if (interval.tv_sec < 0 || interval.tv_nsec < 0)
 2747 			interval.tv_sec = interval.tv_nsec = 0;
 2748 
 2749 		if (timespec_cmp(&interval, &maxinterval, >))
 2750 			interval = maxinterval;
 2751 
 2752 		if (interval.tv_sec == 0 &&
 2753 		    interval.tv_nsec <= MIN_POLL_INTERVAL)
 2754 			interval.tv_nsec = MIN_POLL_INTERVAL;
 2755 
 2756 		rc = pselect(0, NULL, NULL, NULL, &interval, NULL);
 2757 		if (rc < 0 && errno != EINTR)
 2758 			fatale("select() failed for pause");
 2759 	}
 2760 }
 2761 
 2762 static int
 2763 finish_stop_schedule(bool anykilled)
 2764 {
 2765 	if (rpidfile && pidfile && !testmode)
 2766 		remove_pidfile(pidfile);
 2767 
 2768 	if (anykilled)
 2769 		return 0;
 2770 
 2771 	info("No %s found running; none killed.\n", what_stop);
 2772 
 2773 	return exitnodo;
 2774 }
 2775 
 2776 static int
 2777 run_stop_schedule(void)
 2778 {
 2779 	int position, n_killed, n_notkilled, value, retry_nr;
 2780 	bool anykilled;
 2781 
 2782 	if (testmode) {
 2783 		if (schedule != NULL) {
 2784 			info("Ignoring --retry in test mode\n");
 2785 			schedule = NULL;
 2786 		}
 2787 	}
 2788 
 2789 	if (cmdname)
 2790 		set_what_stop("%s", cmdname);
 2791 	else if (execname)
 2792 		set_what_stop("%s", execname);
 2793 	else if (pidfile)
 2794 		set_what_stop("process in pidfile '%s'", pidfile);
 2795 	else if (match_pid > 0)
 2796 		set_what_stop("process with pid %d", match_pid);
 2797 	else if (match_ppid > 0)
 2798 		set_what_stop("process(es) with parent pid %d", match_ppid);
 2799 	else if (userspec)
 2800 		set_what_stop("process(es) owned by '%s'", userspec);
 2801 	else
 2802 		BUG("no match option, please report");
 2803 
 2804 	anykilled = false;
 2805 	retry_nr = 0;
 2806 
 2807 	if (schedule == NULL) {
 2808 		do_stop(signal_nr, &n_killed, &n_notkilled);
 2809 		do_stop_summary(0);
 2810 		if (n_notkilled > 0)
 2811 			info("%d pids were not killed\n", n_notkilled);
 2812 		if (n_killed)
 2813 			anykilled = true;
 2814 		return finish_stop_schedule(anykilled);
 2815 	}
 2816 
 2817 	for (position = 0; position < schedule_length; position++) {
 2818 	reposition:
 2819 		value = schedule[position].value;
 2820 		n_notkilled = 0;
 2821 
 2822 		switch (schedule[position].type) {
 2823 		case sched_goto:
 2824 			position = value;
 2825 			goto reposition;
 2826 		case sched_signal:
 2827 			do_stop(value, &n_killed, &n_notkilled);
 2828 			do_stop_summary(retry_nr++);
 2829 			if (!n_killed)
 2830 				return finish_stop_schedule(anykilled);
 2831 			else
 2832 				anykilled = true;
 2833 			continue;
 2834 		case sched_timeout:
 2835 			if (do_stop_timeout(value, &n_killed, &n_notkilled))
 2836 				return finish_stop_schedule(anykilled);
 2837 			else
 2838 				continue;
 2839 		default:
 2840 			BUG("schedule[%d].type value %d is not valid",
 2841 			    position, schedule[position].type);
 2842 		}
 2843 	}
 2844 
 2845 	info("Program %s, %d process(es), refused to die.\n",
 2846 	     what_stop, n_killed);
 2847 
 2848 	return 2;
 2849 }
 2850 
 2851 int
 2852 main(int argc, char **argv)
 2853 {
 2854 	progname = argv[0];
 2855 
 2856 	parse_options(argc, argv);
 2857 	setup_options();
 2858 
 2859 	argc -= optind;
 2860 	argv += optind;
 2861 
 2862 	if (action == ACTION_START)
 2863 		return do_start(argc, argv);
 2864 	else if (action == ACTION_STOP)
 2865 		return run_stop_schedule();
 2866 	else if (action == ACTION_STATUS)
 2867 		return do_findprocs();
 2868 
 2869 	return 0;
 2870 }

Generated by cgit