summaryrefslogtreecommitdiff
path: root/start-stop-daemon.c
blob: 88c9726639c716100f6f9de2d3567b1925d49070 (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 	unlink(notify_socket);
  555 	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 	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 	/* Create a new session. */
  811 	if (setsid() < 0)
  812 		fatale("cannot set session ID");
  813 
  814 	pid = fork();
  815 	if (pid < 0)
  816 		fatale("unable to do second fork");
  817 	else if (pid) { /* Second parent. */
  818 		/* Set a default umask for dumb programs, which might get
  819 		 * overridden by the --umask option later on, so that we get
  820 		 * a defined umask when creating the pidfile. */
  821 		umask(022);
  822 
  823 		if (mpidfile && pidfile != NULL)
  824 			/* User wants _us_ to make the pidfile. */
  825 			write_pidfile(pidfile, pid);
  826 
  827 		_exit(0);
  828 	}
  829 
  830 	if (sigprocmask(SIG_SETMASK, &oldmask, NULL) == -1)
  831 		fatale("cannot restore signal mask");
  832 
  833 	debug("Detaching complete...\n");
  834 }
  835 
  836 static void
  837 pid_list_push(struct pid_list **list, pid_t pid)
  838 {
  839 	struct pid_list *p;
  840 
  841 	p = xmalloc(sizeof(*p));
  842 	p->next = *list;
  843 	p->pid = pid;
  844 	*list = p;
  845 }
  846 
  847 static void
  848 pid_list_free(struct pid_list **list)
  849 {
  850 	struct pid_list *here, *next;
  851 
  852 	for (here = *list; here != NULL; here = next) {
  853 		next = here->next;
  854 		free(here);
  855 	}
  856 
  857 	*list = NULL;
  858 }
  859 
  860 static void
  861 usage(void)
  862 {
  863 	printf(
  864 "Usage: start-stop-daemon [<option>...] <command>\n"
  865 "\n");
  866 
  867 	printf(
  868 "Commands:\n"
  869 "  -S, --start -- <argument>...  start a program and pass <arguments> to it\n"
  870 "  -K, --stop                    stop a program\n"
  871 "  -T, --status                  get the program status\n"
  872 "  -H, --help                    print help information\n"
  873 "  -V, --version                 print version\n"
  874 "\n");
  875 
  876 	printf(
  877 "Matching options (at least one is required):\n"
  878 "      --pid <pid>               pid to check\n"
  879 "      --ppid <ppid>             parent pid to check\n"
  880 "  -p, --pidfile <pid-file>      pid file to check\n"
  881 "  -x, --exec <executable>       program to start/check if it is running\n"
  882 "  -n, --name <process-name>     process name to check\n"
  883 "  -u, --user <username|uid>     process owner to check\n"
  884 "\n");
  885 
  886 	printf(
  887 "Options:\n"
  888 "  -g, --group <group|gid>       run process as this group\n"
  889 "  -c, --chuid <name|uid[:group|gid]>\n"
  890 "                                change to this user/group before starting\n"
  891 "                                  process\n"
  892 "  -s, --signal <signal>         signal to send (default TERM)\n"
  893 "  -a, --startas <pathname>      program to start (default is <executable>)\n"
  894 "  -r, --chroot <directory>      chroot to <directory> before starting\n"
  895 "  -d, --chdir <directory>       change to <directory> (default is /)\n"
  896 "  -N, --nicelevel <incr>        add incr to the process' nice level\n"
  897 "  -P, --procsched <policy[:prio]>\n"
  898 "                                use <policy> with <prio> for the kernel\n"
  899 "                                  process scheduler (default prio is 0)\n"
  900 "  -I, --iosched <class[:prio]>  use <class> with <prio> to set the IO\n"
  901 "                                  scheduler (default prio is 4)\n"
  902 "  -k, --umask <mask>            change the umask to <mask> before starting\n"
  903 "  -b, --background              force the process to detach\n"
  904 "      --notify-await            wait for a readiness notification\n"
  905 "      --notify-timeout <int>    timeout after <int> seconds of notify wait\n"
  906 "  -C, --no-close                do not close any file descriptor\n"
  907 "  -m, --make-pidfile            create the pidfile before starting\n"
  908 "      --remove-pidfile          delete the pidfile after stopping\n"
  909 "  -R, --retry <schedule>        check whether processes die, and retry\n"
  910 "  -t, --test                    test mode, don't do anything\n"
  911 "  -o, --oknodo                  exit status 0 (not 1) if nothing done\n"
  912 "  -q, --quiet                   be more quiet\n"
  913 "  -v, --verbose                 be more verbose\n"
  914 "\n");
  915 
  916 	printf(
  917 "Retry <schedule> is <item>|/<item>/... where <item> is one of\n"
  918 " -<signal-num>|[-]<signal-name>  send that signal\n"
  919 " <timeout>                       wait that many seconds\n"
  920 " forever                         repeat remainder forever\n"
  921 "or <schedule> may be just <timeout>, meaning <signal>/<timeout>/KILL/<timeout>\n"
  922 "\n");
  923 
  924 	printf(
  925 "The process scheduler <policy> can be one of:\n"
  926 "  other, fifo or rr\n"
  927 "\n");
  928 
  929 	printf(
  930 "The IO scheduler <class> can be one of:\n"
  931 "  real-time, best-effort or idle\n"
  932 "\n");
  933 
  934 	printf(
  935 "Exit status:\n"
  936 "  0 = done\n"
  937 "  1 = nothing done (=> 0 if --oknodo)\n"
  938 "  2 = with --retry, processes would not die\n"
  939 "  3 = trouble\n"
  940 "Exit status with --status:\n"
  941 "  0 = program is running\n"
  942 "  1 = program is not running and the pid file exists\n"
  943 "  3 = program is not running\n"
  944 "  4 = unable to determine status\n");
  945 }
  946 
  947 static void
  948 do_version(void)
  949 {
  950 	printf("start-stop-daemon %s for Debian\n\n", VERSION);
  951 
  952 	printf("Written by Marek Michalkiewicz, public domain.\n");
  953 }
  954 
  955 static void DPKG_ATTR_NORET
  956 badusage(const char *msg)
  957 {
  958 	if (msg)
  959 		fprintf(stderr, "%s: %s\n", progname, msg);
  960 	fprintf(stderr, "Try '%s --help' for more information.\n", progname);
  961 
  962 	if (action == ACTION_STATUS)
  963 		exit(STATUS_UNKNOWN);
  964 	else
  965 		exit(3);
  966 }
  967 
  968 struct sigpair {
  969 	const char *name;
  970 	int signal;
  971 };
  972 
  973 static const struct sigpair siglist[] = {
  974 	{ "ABRT",	SIGABRT	},
  975 	{ "ALRM",	SIGALRM	},
  976 	{ "FPE",	SIGFPE	},
  977 	{ "HUP",	SIGHUP	},
  978 	{ "ILL",	SIGILL	},
  979 	{ "INT",	SIGINT	},
  980 	{ "KILL",	SIGKILL	},
  981 	{ "PIPE",	SIGPIPE	},
  982 	{ "QUIT",	SIGQUIT	},
  983 	{ "SEGV",	SIGSEGV	},
  984 	{ "TERM",	SIGTERM	},
  985 	{ "USR1",	SIGUSR1	},
  986 	{ "USR2",	SIGUSR2	},
  987 	{ "CHLD",	SIGCHLD	},
  988 	{ "CONT",	SIGCONT	},
  989 	{ "STOP",	SIGSTOP	},
  990 	{ "TSTP",	SIGTSTP	},
  991 	{ "TTIN",	SIGTTIN	},
  992 	{ "TTOU",	SIGTTOU	}
  993 };
  994 
  995 static int
  996 parse_pid(const char *pid_str, int *pid_num)
  997 {
  998 	if (parse_unsigned(pid_str, 10, pid_num) != 0)
  999 		return -1;
 1000 	if (*pid_num == 0)
 1001 		return -1;
 1002 
 1003 	return 0;
 1004 }
 1005 
 1006 static int
 1007 parse_signal(const char *sig_str, int *sig_num)
 1008 {
 1009 	unsigned int i;
 1010 
 1011 	if (parse_unsigned(sig_str, 10, sig_num) == 0)
 1012 		return 0;
 1013 
 1014 	for (i = 0; i < array_count(siglist); i++) {
 1015 		if (strcmp(sig_str, siglist[i].name) == 0) {
 1016 			*sig_num = siglist[i].signal;
 1017 			return 0;
 1018 		}
 1019 	}
 1020 	return -1;
 1021 }
 1022 
 1023 static int
 1024 parse_umask(const char *string, int *value_r)
 1025 {
 1026 	return parse_unsigned(string, 0, value_r);
 1027 }
 1028 
 1029 static void
 1030 validate_proc_schedule(void)
 1031 {
 1032 #if defined(_POSIX_PRIORITY_SCHEDULING) && _POSIX_PRIORITY_SCHEDULING > 0
 1033 	int prio_min, prio_max;
 1034 
 1035 	prio_min = sched_get_priority_min(proc_sched->policy);
 1036 	prio_max = sched_get_priority_max(proc_sched->policy);
 1037 
 1038 	if (proc_sched->priority < prio_min)
 1039 		badusage("process scheduler priority less than min");
 1040 	if (proc_sched->priority > prio_max)
 1041 		badusage("process scheduler priority greater than max");
 1042 #endif
 1043 }
 1044 
 1045 static void
 1046 parse_proc_schedule(const char *string)
 1047 {
 1048 	char *policy_str;
 1049 	size_t policy_len;
 1050 	int prio = 0;
 1051 
 1052 	policy_len = strcspn(string, ":");
 1053 	policy_str = xstrndup(string, policy_len);
 1054 
 1055 	if (string[policy_len] == ':' &&
 1056 	    parse_unsigned(string + policy_len + 1, 10, &prio) != 0)
 1057 		fatale("invalid process scheduler priority");
 1058 
 1059 	proc_sched = xmalloc(sizeof(*proc_sched));
 1060 	proc_sched->policy_name = policy_str;
 1061 
 1062 	if (strcmp(policy_str, "other") == 0) {
 1063 		proc_sched->policy = SCHED_OTHER;
 1064 		proc_sched->priority = 0;
 1065 	} else if (strcmp(policy_str, "fifo") == 0) {
 1066 		proc_sched->policy = SCHED_FIFO;
 1067 		proc_sched->priority = prio;
 1068 	} else if (strcmp(policy_str, "rr") == 0) {
 1069 		proc_sched->policy = SCHED_RR;
 1070 		proc_sched->priority = prio;
 1071 	} else
 1072 		badusage("invalid process scheduler policy");
 1073 
 1074 	validate_proc_schedule();
 1075 }
 1076 
 1077 static void
 1078 parse_io_schedule(const char *string)
 1079 {
 1080 	char *class_str;
 1081 	size_t class_len;
 1082 	int prio = 4;
 1083 
 1084 	class_len = strcspn(string, ":");
 1085 	class_str = xstrndup(string, class_len);
 1086 
 1087 	if (string[class_len] == ':' &&
 1088 	    parse_unsigned(string + class_len + 1, 10, &prio) != 0)
 1089 		fatale("invalid IO scheduler priority");
 1090 
 1091 	io_sched = xmalloc(sizeof(*io_sched));
 1092 	io_sched->policy_name = class_str;
 1093 
 1094 	if (strcmp(class_str, "real-time") == 0) {
 1095 		io_sched->policy = IOPRIO_CLASS_RT;
 1096 		io_sched->priority = prio;
 1097 	} else if (strcmp(class_str, "best-effort") == 0) {
 1098 		io_sched->policy = IOPRIO_CLASS_BE;
 1099 		io_sched->priority = prio;
 1100 	} else if (strcmp(class_str, "idle") == 0) {
 1101 		io_sched->policy = IOPRIO_CLASS_IDLE;
 1102 		io_sched->priority = 7;
 1103 	} else
 1104 		badusage("invalid IO scheduler policy");
 1105 
 1106 	if (io_sched->priority < IO_SCHED_PRIO_MIN)
 1107 		badusage("IO scheduler priority less than min");
 1108 	if (io_sched->priority > IO_SCHED_PRIO_MAX)
 1109 		badusage("IO scheduler priority greater than max");
 1110 }
 1111 
 1112 static void
 1113 set_proc_schedule(struct res_schedule *sched)
 1114 {
 1115 #if defined(_POSIX_PRIORITY_SCHEDULING) && _POSIX_PRIORITY_SCHEDULING > 0
 1116 	struct sched_param param;
 1117 
 1118 	param.sched_priority = sched->priority;
 1119 
 1120 	if (sched_setscheduler(getpid(), sched->policy, &param) == -1)
 1121 		fatale("unable to set process scheduler");
 1122 #endif
 1123 }
 1124 
 1125 #ifdef HAVE_IOPRIO_SET
 1126 static inline int
 1127 ioprio_set(int which, int who, int ioprio)
 1128 {
 1129 	return syscall(SYS_ioprio_set, which, who, ioprio);
 1130 }
 1131 #endif
 1132 
 1133 static void
 1134 set_io_schedule(struct res_schedule *sched)
 1135 {
 1136 #ifdef HAVE_IOPRIO_SET
 1137 	int io_sched_mask;
 1138 
 1139 	io_sched_mask = IOPRIO_PRIO_VALUE(sched->policy, sched->priority);
 1140 	if (ioprio_set(IOPRIO_WHO_PROCESS, getpid(), io_sched_mask) == -1)
 1141 		warning("unable to alter IO priority to mask %i (%s)\n",
 1142 		        io_sched_mask, strerror(errno));
 1143 #endif
 1144 }
 1145 
 1146 static void
 1147 parse_schedule_item(const char *string, struct schedule_item *item)
 1148 {
 1149 	const char *after_hyph;
 1150 
 1151 	if (strcmp(string, "forever") == 0) {
 1152 		item->type = sched_forever;
 1153 	} else if (isdigit(string[0])) {
 1154 		item->type = sched_timeout;
 1155 		if (parse_unsigned(string, 10, &item->value) != 0)
 1156 			badusage("invalid timeout value in schedule");
 1157 	} else if ((after_hyph = string + (string[0] == '-')) &&
 1158 	           parse_signal(after_hyph, &item->value) == 0) {
 1159 		item->type = sched_signal;
 1160 	} else {
 1161 		badusage("invalid schedule item (must be [-]<signal-name>, "
 1162 		         "-<signal-number>, <timeout> or 'forever'");
 1163 	}
 1164 }
 1165 
 1166 static void
 1167 parse_schedule(const char *schedule_str)
 1168 {
 1169 	char item_buf[20];
 1170 	const char *slash;
 1171 	int count, repeatat;
 1172 	size_t str_len;
 1173 
 1174 	count = 0;
 1175 	for (slash = schedule_str; *slash; slash++)
 1176 		if (*slash == '/')
 1177 			count++;
 1178 
 1179 	schedule_length = (count == 0) ? 4 : count + 1;
 1180 	schedule = xmalloc(sizeof(*schedule) * schedule_length);
 1181 
 1182 	if (count == 0) {
 1183 		schedule[0].type = sched_signal;
 1184 		schedule[0].value = signal_nr;
 1185 		parse_schedule_item(schedule_str, &schedule[1]);
 1186 		if (schedule[1].type != sched_timeout) {
 1187 			badusage("--retry takes timeout, or schedule list"
 1188 			         " of at least two items");
 1189 		}
 1190 		schedule[2].type = sched_signal;
 1191 		schedule[2].value = SIGKILL;
 1192 		schedule[3] = schedule[1];
 1193 	} else {
 1194 		count = 0;
 1195 		repeatat = -1;
 1196 		while (*schedule_str) {
 1197 			slash = strchrnul(schedule_str, '/');
 1198 			str_len = (size_t)(slash - schedule_str);
 1199 			if (str_len >= sizeof(item_buf))
 1200 				badusage("invalid schedule item: far too long"
 1201 				         " (you must delimit items with slashes)");
 1202 			memcpy(item_buf, schedule_str, str_len);
 1203 			item_buf[str_len] = '\0';
 1204 			schedule_str = *slash ? slash + 1 : slash;
 1205 
 1206 			parse_schedule_item(item_buf, &schedule[count]);
 1207 			if (schedule[count].type == sched_forever) {
 1208 				if (repeatat >= 0)
 1209 					badusage("invalid schedule: 'forever'"
 1210 					         " appears more than once");
 1211 				repeatat = count;
 1212 				continue;
 1213 			}
 1214 			count++;
 1215 		}
 1216 		if (repeatat == count)
 1217 			badusage("invalid schedule: 'forever' appears last, "
 1218 			         "nothing to repeat");
 1219 		if (repeatat >= 0) {
 1220 			schedule[count].type = sched_goto;
 1221 			schedule[count].value = repeatat;
 1222 			count++;
 1223 		}
 1224 		if (count != schedule_length)
 1225 			BUG("count=%d != schedule_length=%d",
 1226 			    count, schedule_length);
 1227 	}
 1228 }
 1229 
 1230 static void
 1231 set_action(enum action_code new_action)
 1232 {
 1233 	if (action == new_action)
 1234 		return;
 1235 
 1236 	if (action != ACTION_NONE)
 1237 		badusage("only one command can be specified");
 1238 
 1239 	action = new_action;
 1240 }
 1241 
 1242 #define OPT_PID		500
 1243 #define OPT_PPID	501
 1244 #define OPT_RM_PIDFILE	502
 1245 #define OPT_NOTIFY_AWAIT	503
 1246 #define OPT_NOTIFY_TIMEOUT	504
 1247 
 1248 static void
 1249 parse_options(int argc, char * const *argv)
 1250 {
 1251 	static struct option longopts[] = {
 1252 		{ "help",	  0, NULL, 'H'},
 1253 		{ "stop",	  0, NULL, 'K'},
 1254 		{ "start",	  0, NULL, 'S'},
 1255 		{ "status",	  0, NULL, 'T'},
 1256 		{ "version",	  0, NULL, 'V'},
 1257 		{ "startas",	  1, NULL, 'a'},
 1258 		{ "name",	  1, NULL, 'n'},
 1259 		{ "oknodo",	  0, NULL, 'o'},
 1260 		{ "pid",	  1, NULL, OPT_PID},
 1261 		{ "ppid",	  1, NULL, OPT_PPID},
 1262 		{ "pidfile",	  1, NULL, 'p'},
 1263 		{ "quiet",	  0, NULL, 'q'},
 1264 		{ "signal",	  1, NULL, 's'},
 1265 		{ "test",	  0, NULL, 't'},
 1266 		{ "user",	  1, NULL, 'u'},
 1267 		{ "group",	  1, NULL, 'g'},
 1268 		{ "chroot",	  1, NULL, 'r'},
 1269 		{ "verbose",	  0, NULL, 'v'},
 1270 		{ "exec",	  1, NULL, 'x'},
 1271 		{ "chuid",	  1, NULL, 'c'},
 1272 		{ "nicelevel",	  1, NULL, 'N'},
 1273 		{ "procsched",	  1, NULL, 'P'},
 1274 		{ "iosched",	  1, NULL, 'I'},
 1275 		{ "umask",	  1, NULL, 'k'},
 1276 		{ "background",	  0, NULL, 'b'},
 1277 		{ "notify-await", 0, NULL, OPT_NOTIFY_AWAIT},
 1278 		{ "notify-timeout", 1, NULL, OPT_NOTIFY_TIMEOUT},
 1279 		{ "no-close",	  0, NULL, 'C'},
 1280 		{ "make-pidfile", 0, NULL, 'm'},
 1281 		{ "remove-pidfile", 0, NULL, OPT_RM_PIDFILE},
 1282 		{ "retry",	  1, NULL, 'R'},
 1283 		{ "chdir",	  1, NULL, 'd'},
 1284 		{ NULL,		  0, NULL, 0  }
 1285 	};
 1286 	const char *pid_str = NULL;
 1287 	const char *ppid_str = NULL;
 1288 	const char *umask_str = NULL;
 1289 	const char *signal_str = NULL;
 1290 	const char *schedule_str = NULL;
 1291 	const char *proc_schedule_str = NULL;
 1292 	const char *io_schedule_str = NULL;
 1293 	const char *notify_timeout_str = NULL;
 1294 	size_t changeuser_len;
 1295 	int c;
 1296 
 1297 	for (;;) {
 1298 		c = getopt_long(argc, argv,
 1299 		                "HKSVTa:n:op:qr:s:tu:vx:c:N:P:I:k:bCmR:g:d:",
 1300 		                longopts, NULL);
 1301 		if (c == -1)
 1302 			break;
 1303 		switch (c) {
 1304 		case 'H':  /* --help */
 1305 			usage();
 1306 			exit(0);
 1307 		case 'K':  /* --stop */
 1308 			set_action(ACTION_STOP);
 1309 			break;
 1310 		case 'S':  /* --start */
 1311 			set_action(ACTION_START);
 1312 			break;
 1313 		case 'T':  /* --status */
 1314 			set_action(ACTION_STATUS);
 1315 			break;
 1316 		case 'V':  /* --version */
 1317 			do_version();
 1318 			exit(0);
 1319 		case 'a':  /* --startas <pathname> */
 1320 			startas = optarg;
 1321 			break;
 1322 		case 'n':  /* --name <process-name> */
 1323 			match_mode |= MATCH_NAME;
 1324 			cmdname = optarg;
 1325 			break;
 1326 		case 'o':  /* --oknodo */
 1327 			exitnodo = 0;
 1328 			break;
 1329 		case OPT_PID: /* --pid <pid> */
 1330 			match_mode |= MATCH_PID;
 1331 			pid_str = optarg;
 1332 			break;
 1333 		case OPT_PPID: /* --ppid <ppid> */
 1334 			match_mode |= MATCH_PPID;
 1335 			ppid_str = optarg;
 1336 			break;
 1337 		case 'p':  /* --pidfile <pid-file> */
 1338 			match_mode |= MATCH_PIDFILE;
 1339 			pidfile = optarg;
 1340 			break;
 1341 		case 'q':  /* --quiet */
 1342 			quietmode = true;
 1343 			break;
 1344 		case 's':  /* --signal <signal> */
 1345 			signal_str = optarg;
 1346 			break;
 1347 		case 't':  /* --test */
 1348 			testmode = true;
 1349 			break;
 1350 		case 'u':  /* --user <username>|<uid> */
 1351 			match_mode |= MATCH_USER;
 1352 			userspec = optarg;
 1353 			break;
 1354 		case 'v':  /* --verbose */
 1355 			quietmode = -1;
 1356 			break;
 1357 		case 'x':  /* --exec <executable> */
 1358 			match_mode |= MATCH_EXEC;
 1359 			execname = optarg;
 1360 			break;
 1361 		case 'c':  /* --chuid <username>|<uid> */
 1362 			/* We copy the string just in case we need the
 1363 			 * argument later. */
 1364 			changeuser_len = strcspn(optarg, ":");
 1365 			changeuser = xstrndup(optarg, changeuser_len);
 1366 			if (optarg[changeuser_len] == ':') {
 1367 				if (optarg[changeuser_len + 1] == '\0')
 1368 					fatal("missing group name");
 1369 				changegroup = optarg + changeuser_len + 1;
 1370 			}
 1371 			break;
 1372 		case 'g':  /* --group <group>|<gid> */
 1373 			changegroup = optarg;
 1374 			break;
 1375 		case 'r':  /* --chroot /new/root */
 1376 			changeroot = optarg;
 1377 			break;
 1378 		case 'N':  /* --nice */
 1379 			nicelevel = atoi(optarg);
 1380 			break;
 1381 		case 'P':  /* --procsched */
 1382 			proc_schedule_str = optarg;
 1383 			break;
 1384 		case 'I':  /* --iosched */
 1385 			io_schedule_str = optarg;
 1386 			break;
 1387 		case 'k':  /* --umask <mask> */
 1388 			umask_str = optarg;
 1389 			break;
 1390 		case 'b':  /* --background */
 1391 			background = true;
 1392 			break;
 1393 		case OPT_NOTIFY_AWAIT:
 1394 			notify_await = true;
 1395 			break;
 1396 		case OPT_NOTIFY_TIMEOUT:
 1397 			notify_timeout_str = optarg;
 1398 			break;
 1399 		case 'C': /* --no-close */
 1400 			close_io = false;
 1401 			break;
 1402 		case 'm':  /* --make-pidfile */
 1403 			mpidfile = true;
 1404 			break;
 1405 		case OPT_RM_PIDFILE: /* --remove-pidfile */
 1406 			rpidfile = true;
 1407 			break;
 1408 		case 'R':  /* --retry <schedule>|<timeout> */
 1409 			schedule_str = optarg;
 1410 			break;
 1411 		case 'd':  /* --chdir /new/dir */
 1412 			changedir = optarg;
 1413 			break;
 1414 		default:
 1415 			/* Message printed by getopt. */
 1416 			badusage(NULL);
 1417 		}
 1418 	}
 1419 
 1420 	if (pid_str != NULL) {
 1421 		if (parse_pid(pid_str, &match_pid) != 0)
 1422 			badusage("pid value must be a number greater than 0");
 1423 	}
 1424 
 1425 	if (ppid_str != NULL) {
 1426 		if (parse_pid(ppid_str, &match_ppid) != 0)
 1427 			badusage("ppid value must be a number greater than 0");
 1428 	}
 1429 
 1430 	if (signal_str != NULL) {
 1431 		if (parse_signal(signal_str, &signal_nr) != 0)
 1432 			badusage("signal value must be numeric or name"
 1433 			         " of signal (KILL, INT, ...)");
 1434 	}
 1435 
 1436 	if (schedule_str != NULL) {
 1437 		parse_schedule(schedule_str);
 1438 	}
 1439 
 1440 	if (proc_schedule_str != NULL)
 1441 		parse_proc_schedule(proc_schedule_str);
 1442 
 1443 	if (io_schedule_str != NULL)
 1444 		parse_io_schedule(io_schedule_str);
 1445 
 1446 	if (umask_str != NULL) {
 1447 		if (parse_umask(umask_str, &umask_value) != 0)
 1448 			badusage("umask value must be a positive number");
 1449 	}
 1450 
 1451 	if (notify_timeout_str != NULL)
 1452 		if (parse_unsigned(notify_timeout_str, 10, &notify_timeout) != 0)
 1453 			badusage("invalid notify timeout value");
 1454 
 1455 	if (action == ACTION_NONE)
 1456 		badusage("need one of --start or --stop or --status");
 1457 
 1458 	if (match_mode == MATCH_NONE ||
 1459 	    (!execname && !cmdname && !userspec &&
 1460 	     !pid_str && !ppid_str && !pidfile))
 1461 		badusage("need at least one of --exec, --pid, --ppid, --pidfile, --user or --name");
 1462 
 1463 #ifdef PROCESS_NAME_SIZE
 1464 	if (cmdname && strlen(cmdname) > PROCESS_NAME_SIZE)
 1465 		warning("this system is not able to track process names\n"
 1466 		        "longer than %d characters, please use --exec "
 1467 		        "instead of --name.\n", PROCESS_NAME_SIZE);
 1468 #endif
 1469 
 1470 	if (!startas)
 1471 		startas = execname;
 1472 
 1473 	if (action == ACTION_START && !startas)
 1474 		badusage("--start needs --exec or --startas");
 1475 
 1476 	if (mpidfile && pidfile == NULL)
 1477 		badusage("--make-pidfile requires --pidfile");
 1478 	if (rpidfile && pidfile == NULL)
 1479 		badusage("--remove-pidfile requires --pidfile");
 1480 
 1481 	if (pid_str && pidfile)
 1482 		badusage("need either --pid or --pidfile, not both");
 1483 
 1484 	if (background && action != ACTION_START)
 1485 		badusage("--background is only relevant with --start");
 1486 
 1487 	if (!close_io && !background)
 1488 		badusage("--no-close is only relevant with --background");
 1489 }
 1490 
 1491 static void
 1492 setup_options(void)
 1493 {
 1494 	if (execname) {
 1495 		char *fullexecname;
 1496 
 1497 		/* If it's a relative path, normalize it. */
 1498 		if (execname[0] != '/')
 1499 			execname = newpath(changedir, execname);
 1500 
 1501 		if (changeroot)
 1502 			fullexecname = newpath(changeroot, execname);
 1503 		else
 1504 			fullexecname = execname;
 1505 
 1506 		if (stat(fullexecname, &exec_stat))
 1507 			fatale("unable to stat %s", fullexecname);
 1508 
 1509 		if (fullexecname != execname)
 1510 			free(fullexecname);
 1511 	}
 1512 
 1513 	if (userspec && parse_unsigned(userspec, 10, &user_id) < 0) {
 1514 		struct passwd *pw;
 1515 
 1516 		pw = getpwnam(userspec);
 1517 		if (!pw)
 1518 			fatale("user '%s' not found", userspec);
 1519 
 1520 		user_id = pw->pw_uid;
 1521 	}
 1522 
 1523 	if (changegroup && parse_unsigned(changegroup, 10, &runas_gid) < 0) {
 1524 		struct group *gr;
 1525 
 1526 		gr = getgrnam(changegroup);
 1527 		if (!gr)
 1528 			fatale("group '%s' not found", changegroup);
 1529 		changegroup = gr->gr_name;
 1530 		runas_gid = gr->gr_gid;
 1531 	}
 1532 	if (changeuser) {
 1533 		struct passwd *pw;
 1534 		struct stat st;
 1535 
 1536 		if (parse_unsigned(changeuser, 10, &runas_uid) == 0)
 1537 			pw = getpwuid(runas_uid);
 1538 		else
 1539 			pw = getpwnam(changeuser);
 1540 		if (!pw)
 1541 			fatale("user '%s' not found", changeuser);
 1542 		changeuser = pw->pw_name;
 1543 		runas_uid = pw->pw_uid;
 1544 		if (changegroup == NULL) {
 1545 			/* Pass the default group of this user. */
 1546 			changegroup = ""; /* Just empty. */
 1547 			runas_gid = pw->pw_gid;
 1548 		}
 1549 		if (stat(pw->pw_dir, &st) == 0)
 1550 			setenv("HOME", pw->pw_dir, 1);
 1551 	}
 1552 }
 1553 
 1554 #if defined(OS_Linux)
 1555 static const char *
 1556 proc_status_field(pid_t pid, const char *field)
 1557 {
 1558 	static char *line = NULL;
 1559 	static size_t line_size = 0;
 1560 
 1561 	FILE *fp;
 1562 	char filename[32];
 1563 	char *value = NULL;
 1564 	ssize_t line_len;
 1565 	size_t field_len = strlen(field);
 1566 
 1567 	sprintf(filename, "/proc/%d/status", pid);
 1568 	fp = fopen(filename, "r");
 1569 	if (!fp)
 1570 		return NULL;
 1571 	while ((line_len = getline(&line, &line_size, fp)) >= 0) {
 1572 		if (strncasecmp(line, field, field_len) == 0) {
 1573 			line[line_len - 1] = '\0';
 1574 
 1575 			value = line + field_len;
 1576 			while (isspace(*value))
 1577 				value++;
 1578 
 1579 			break;
 1580 		}
 1581 	}
 1582 	fclose(fp);
 1583 
 1584 	return value;
 1585 }
 1586 #elif defined(OS_AIX)
 1587 static bool
 1588 proc_get_psinfo(pid_t pid, struct psinfo *psinfo)
 1589 {
 1590 	char filename[64];
 1591 	FILE *fp;
 1592 
 1593 	sprintf(filename, "/proc/%d/psinfo", pid);
 1594 	fp = fopen(filename, "r");
 1595 	if (!fp)
 1596 		return false;
 1597 	if (fread(psinfo, sizeof(*psinfo), 1, fp) == 0) {
 1598 		fclose(fp);
 1599 		return false;
 1600 	}
 1601 	if (ferror(fp)) {
 1602 		fclose(fp);
 1603 		return false;
 1604 	}
 1605 
 1606 	fclose(fp);
 1607 
 1608 	return true;
 1609 }
 1610 #elif defined(OS_Hurd)
 1611 static void
 1612 init_procset(void)
 1613 {
 1614 	struct ps_context *context;
 1615 	error_t err;
 1616 
 1617 	err = ps_context_create(getproc(), &context);
 1618 	if (err)
 1619 		error(1, err, "ps_context_create");
 1620 
 1621 	err = proc_stat_list_create(context, &procset);
 1622 	if (err)
 1623 		error(1, err, "proc_stat_list_create");
 1624 
 1625 	err = proc_stat_list_add_all(procset, 0, 0);
 1626 	if (err)
 1627 		error(1, err, "proc_stat_list_add_all");
 1628 }
 1629 
 1630 static struct proc_stat *
 1631 get_proc_stat(pid_t pid, ps_flags_t flags)
 1632 {
 1633 	struct proc_stat *ps;
 1634 	ps_flags_t wanted_flags = PSTAT_PID | flags;
 1635 
 1636 	if (!procset)
 1637 		init_procset();
 1638 
 1639 	ps = proc_stat_list_pid_proc_stat(procset, pid);
 1640 	if (!ps)
 1641 		return NULL;
 1642 	if (proc_stat_set_flags(ps, wanted_flags))
 1643 		return NULL;
 1644 	if ((proc_stat_flags(ps) & wanted_flags) != wanted_flags)
 1645 		return NULL;
 1646 
 1647 	return ps;
 1648 }
 1649 #elif defined(HAVE_KVM_H)
 1650 static kvm_t *
 1651 ssd_kvm_open(void)
 1652 {
 1653 	kvm_t *kd;
 1654 	char errbuf[_POSIX2_LINE_MAX];
 1655 
 1656 	kd = kvm_openfiles(NULL, KVM_MEMFILE, NULL, O_RDONLY, errbuf);
 1657 	if (kd == NULL)
 1658 		errx(1, "%s", errbuf);
 1659 
 1660 	return kd;
 1661 }
 1662 
 1663 static struct kinfo_proc *
 1664 ssd_kvm_get_procs(kvm_t *kd, int op, int arg, int *count)
 1665 {
 1666 	struct kinfo_proc *kp;
 1667 	int lcount;
 1668 
 1669 	if (count == NULL)
 1670 		count = &lcount;
 1671 	*count = 0;
 1672 
 1673 #if defined(OS_OpenBSD)
 1674 	kp = kvm_getprocs(kd, op, arg, sizeof(*kp), count);
 1675 #else
 1676 	kp = kvm_getprocs(kd, op, arg, count);
 1677 #endif
 1678 	if (kp == NULL && errno != ESRCH)
 1679 		errx(1, "%s", kvm_geterr(kd));
 1680 
 1681 	return kp;
 1682 }
 1683 #endif
 1684 
 1685 #if defined(OS_Linux)
 1686 static bool
 1687 pid_is_exec(pid_t pid, const struct stat *esb)
 1688 {
 1689 	char lname[32];
 1690 	char lcontents[_POSIX_PATH_MAX + 1];
 1691 	char *filename;
 1692 	const char deleted[] = " (deleted)";
 1693 	int nread;
 1694 	struct stat sb;
 1695 
 1696 	sprintf(lname, "/proc/%d/exe", pid);
 1697 	nread = readlink(lname, lcontents, sizeof(lcontents) - 1);
 1698 	if (nread == -1)
 1699 		return false;
 1700 
 1701 	filename = lcontents;
 1702 	filename[nread] = '\0';
 1703 
 1704 	/* OpenVZ kernels contain a bogus patch that instead of appending,
 1705 	 * prepends the deleted marker. Workaround those. Otherwise handle
 1706 	 * the normal appended marker. */
 1707 	if (strncmp(filename, deleted, strlen(deleted)) == 0)
 1708 		filename += strlen(deleted);
 1709 	else if (strcmp(filename + nread - strlen(deleted), deleted) == 0)
 1710 		filename[nread - strlen(deleted)] = '\0';
 1711 
 1712 	if (stat(filename, &sb) != 0)
 1713 		return false;
 1714 
 1715 	return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
 1716 }
 1717 #elif defined(OS_AIX)
 1718 static bool
 1719 pid_is_exec(pid_t pid, const struct stat *esb)
 1720 {
 1721 	struct stat sb;
 1722 	char filename[64];
 1723 
 1724 	sprintf(filename, "/proc/%d/object/a.out", pid);
 1725 
 1726 	if (stat(filename, &sb) != 0)
 1727 		return false;
 1728 
 1729 	return sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino;
 1730 }
 1731 #elif defined(OS_Hurd)
 1732 static bool
 1733 pid_is_exec(pid_t pid, const struct stat *esb)
 1734 {
 1735 	struct proc_stat *ps;
 1736 	struct stat sb;
 1737 	const char *filename;
 1738 
 1739 	ps = get_proc_stat(pid, PSTAT_ARGS);
 1740 	if (ps == NULL)
 1741 		return false;
 1742 
 1743 	/* On old Hurd systems we have to use the argv[0] value, because
 1744 	 * there is nothing better. */
 1745 	filename = proc_stat_args(ps);
 1746 #ifdef PSTAT_EXE
 1747 	/* On new Hurd systems we can use the correct value, as long
 1748 	 * as it's not NULL nor empty, as it was the case on the first
 1749 	 * implementation. */
 1750 	if (proc_stat_set_flags(ps, PSTAT_EXE) == 0 &&
 1751 	    proc_stat_flags(ps) & PSTAT_EXE &&
 1752 	    proc_stat_exe(ps) != NULL &&
 1753 	    proc_stat_exe(ps)[0] != '\0')
 1754 		filename = proc_stat_exe(ps);
 1755 #endif
 1756 
 1757 	if (stat(filename, &sb) != 0)
 1758 		return false;
 1759 
 1760 	return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
 1761 }
 1762 #elif defined(OS_Darwin)
 1763 static bool
 1764 pid_is_exec(pid_t pid, const struct stat *esb)
 1765 {
 1766 	struct stat sb;
 1767 	char pathname[_POSIX_PATH_MAX];
 1768 
 1769 	if (proc_pidpath(pid, pathname, sizeof(pathname)) < 0)
 1770 		return false;
 1771 
 1772 	if (stat(pathname, &sb) != 0)
 1773 		return false;
 1774 
 1775 	return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
 1776 }
 1777 #elif defined(OS_HPUX)
 1778 static bool
 1779 pid_is_exec(pid_t pid, const struct stat *esb)
 1780 {
 1781 	struct pst_status pst;
 1782 
 1783 	if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
 1784 		return false;
 1785 	return ((dev_t)pst.pst_text.psf_fsid.psfs_id == esb->st_dev &&
 1786 	        (ino_t)pst.pst_text.psf_fileid == esb->st_ino);
 1787 }
 1788 #elif defined(OS_FreeBSD)
 1789 static bool
 1790 pid_is_exec(pid_t pid, const struct stat *esb)
 1791 {
 1792 	struct stat sb;
 1793 	int error, mib[4];
 1794 	size_t len;
 1795 	char pathname[PATH_MAX];
 1796 
 1797 	mib[0] = CTL_KERN;
 1798 	mib[1] = KERN_PROC;
 1799 	mib[2] = KERN_PROC_PATHNAME;
 1800 	mib[3] = pid;
 1801 	len = sizeof(pathname);
 1802 
 1803 	error = sysctl(mib, 4, pathname, &len, NULL, 0);
 1804 	if (error != 0 && errno != ESRCH)
 1805 		return false;
 1806 	if (len == 0)
 1807 		pathname[0] = '\0';
 1808 
 1809 	if (stat(pathname, &sb) != 0)
 1810 		return false;
 1811 
 1812 	return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
 1813 }
 1814 #elif defined(HAVE_KVM_H)
 1815 static bool
 1816 pid_is_exec(pid_t pid, const struct stat *esb)
 1817 {
 1818 	kvm_t *kd;
 1819 	int argv_len = 0;
 1820 	struct kinfo_proc *kp;
 1821 	struct stat sb;
 1822 	char buf[_POSIX2_LINE_MAX];
 1823 	char **pid_argv_p;
 1824 	char *start_argv_0_p, *end_argv_0_p;
 1825 	bool res = false;
 1826 
 1827 	kd = ssd_kvm_open();
 1828 	kp = ssd_kvm_get_procs(kd, KERN_PROC_PID, pid, NULL);
 1829 	if (kp == NULL)
 1830 		goto cleanup;
 1831 
 1832 	pid_argv_p = kvm_getargv(kd, kp, argv_len);
 1833 	if (pid_argv_p == NULL)
 1834 		errx(1, "%s", kvm_geterr(kd));
 1835 
 1836 	/* Find and compare string. */
 1837 	start_argv_0_p = *pid_argv_p;
 1838 
 1839 	/* Find end of argv[0] then copy and cut of str there. */
 1840 	end_argv_0_p = strchr(*pid_argv_p, ' ');
 1841 	if (end_argv_0_p == NULL)
 1842 		/* There seems to be no space, so we have the command
 1843 		 * already in its desired form. */
 1844 		start_argv_0_p = *pid_argv_p;
 1845 	else {
 1846 		/* Tests indicate that this never happens, since
 1847 		 * kvm_getargv itself cuts of tailing stuff. This is
 1848 		 * not what the manpage says, however. */
 1849 		strncpy(buf, *pid_argv_p, (end_argv_0_p - start_argv_0_p));
 1850 		buf[(end_argv_0_p - start_argv_0_p) + 1] = '\0';
 1851 		start_argv_0_p = buf;
 1852 	}
 1853 
 1854 	if (stat(start_argv_0_p, &sb) != 0)
 1855 		goto cleanup;
 1856 
 1857 	res = (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
 1858 
 1859 cleanup:
 1860 	kvm_close(kd);
 1861 
 1862 	return res;
 1863 }
 1864 #endif
 1865 
 1866 #if defined(OS_Linux)
 1867 static bool
 1868 pid_is_child(pid_t pid, pid_t ppid)
 1869 {
 1870 	const char *ppid_str;
 1871 	pid_t proc_ppid;
 1872 	int rc;
 1873 
 1874 	ppid_str = proc_status_field(pid, "PPid:");
 1875 	if (ppid_str == NULL)
 1876 		return false;
 1877 
 1878 	rc = parse_pid(ppid_str, &proc_ppid);
 1879 	if (rc < 0)
 1880 		return false;
 1881 
 1882 	return proc_ppid == ppid;
 1883 }
 1884 #elif defined(OS_Hurd)
 1885 static bool
 1886 pid_is_child(pid_t pid, pid_t ppid)
 1887 {
 1888 	struct proc_stat *ps;
 1889 	struct procinfo *pi;
 1890 
 1891 	ps = get_proc_stat(pid, PSTAT_PROC_INFO);
 1892 	if (ps == NULL)
 1893 		return false;
 1894 
 1895 	pi = proc_stat_proc_info(ps);
 1896 
 1897 	return pi->ppid == ppid;
 1898 }
 1899 #elif defined(OS_Darwin)
 1900 static bool
 1901 pid_is_child(pid_t pid, pid_t ppid)
 1902 {
 1903 	struct proc_bsdinfo info;
 1904 
 1905 	if (proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, sizeof(info)) < 0)
 1906 		return false;
 1907 
 1908 	return (pid_t)info.pbi_ppid == ppid;
 1909 }
 1910 #elif defined(OS_AIX)
 1911 static bool
 1912 pid_is_child(pid_t pid, pid_t ppid)
 1913 {
 1914 	struct psinfo psi;
 1915 
 1916 	if (!proc_get_psinfo(pid, &psi))
 1917 		return false;
 1918 
 1919 	return (pid_t)psi.pr_ppid == ppid;
 1920 }
 1921 #elif defined(OS_HPUX)
 1922 static bool
 1923 pid_is_child(pid_t pid, pid_t ppid)
 1924 {
 1925 	struct pst_status pst;
 1926 
 1927 	if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
 1928 		return false;
 1929 
 1930 	return pst.pst_ppid == ppid;
 1931 }
 1932 #elif defined(OS_FreeBSD)
 1933 static bool
 1934 pid_is_child(pid_t pid, pid_t ppid)
 1935 {
 1936 	struct kinfo_proc kp;
 1937 	int rc, mib[4];
 1938 	size_t len;
 1939 
 1940 	mib[0] = CTL_KERN;
 1941 	mib[1] = KERN_PROC;
 1942 	mib[2] = KERN_PROC_PID;
 1943 	mib[3] = pid;
 1944 	len = sizeof(kp);
 1945 
 1946 	rc = sysctl(mib, 4, &kp, &len, NULL, 0);
 1947 	if (rc != 0 && errno != ESRCH)
 1948 		return false;
 1949 	if (len == 0 || len != sizeof(kp))
 1950 		return false;
 1951 
 1952 	return kp.ki_ppid == ppid;
 1953 }
 1954 #elif defined(HAVE_KVM_H)
 1955 static bool
 1956 pid_is_child(pid_t pid, pid_t ppid)
 1957 {
 1958 	kvm_t *kd;
 1959 	struct kinfo_proc *kp;
 1960 	pid_t proc_ppid;
 1961 	bool res = false;
 1962 
 1963 	kd = ssd_kvm_open();
 1964 	kp = ssd_kvm_get_procs(kd, KERN_PROC_PID, pid, NULL);
 1965 	if (kp == NULL)
 1966 		goto cleanup;
 1967 
 1968 #if defined(OS_FreeBSD)
 1969 	proc_ppid = kp->ki_ppid;
 1970 #elif defined(OS_OpenBSD)
 1971 	proc_ppid = kp->p_ppid;
 1972 #elif defined(OS_DragonFlyBSD)
 1973 	proc_ppid = kp->kp_ppid;
 1974 #else
 1975 	proc_ppid = kp->kp_proc.p_ppid;
 1976 #endif
 1977 
 1978 	res = (proc_ppid == ppid);
 1979 
 1980 cleanup:
 1981 	kvm_close(kd);
 1982 
 1983 	return res;
 1984 }
 1985 #endif
 1986 
 1987 #if defined(OS_Linux)
 1988 static bool
 1989 pid_is_user(pid_t pid, uid_t uid)
 1990 {
 1991 	struct stat sb;
 1992 	char buf[32];
 1993 
 1994 	sprintf(buf, "/proc/%d", pid);
 1995 	if (stat(buf, &sb) != 0)
 1996 		return false;
 1997 	return (sb.st_uid == uid);
 1998 }
 1999 #elif defined(OS_Hurd)
 2000 static bool
 2001 pid_is_user(pid_t pid, uid_t uid)
 2002 {
 2003 	struct proc_stat *ps;
 2004 
 2005 	ps = get_proc_stat(pid, PSTAT_OWNER_UID);
 2006 	return ps && (uid_t)proc_stat_owner_uid(ps) == uid;
 2007 }
 2008 #elif defined(OS_Darwin)
 2009 static bool
 2010 pid_is_user(pid_t pid, uid_t uid)
 2011 {
 2012 	struct proc_bsdinfo info;
 2013 
 2014 	if (proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, sizeof(info)) < 0)
 2015 		return false;
 2016 
 2017 	return info.pbi_ruid == uid;
 2018 }
 2019 #elif defined(OS_AIX)
 2020 static bool
 2021 pid_is_user(pid_t pid, uid_t uid)
 2022 {
 2023 	struct psinfo psi;
 2024 
 2025 	if (!proc_get_psinfo(pid, &psi))
 2026 		return false;
 2027 
 2028 	return psi.pr_uid == uid;
 2029 }
 2030 #elif defined(OS_HPUX)
 2031 static bool
 2032 pid_is_user(pid_t pid, uid_t uid)
 2033 {
 2034 	struct pst_status pst;
 2035 
 2036 	if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
 2037 		return false;
 2038 	return ((uid_t)pst.pst_uid == uid);
 2039 }
 2040 #elif defined(OS_FreeBSD)
 2041 static bool
 2042 pid_is_user(pid_t pid, uid_t uid)
 2043 {
 2044 	struct kinfo_proc kp;
 2045 	int rc, mib[4];
 2046 	size_t len;
 2047 
 2048 	mib[0] = CTL_KERN;
 2049 	mib[1] = KERN_PROC;
 2050 	mib[2] = KERN_PROC_PID;
 2051 	mib[3] = pid;
 2052 	len = sizeof(kp);
 2053 
 2054 	rc = sysctl(mib, 4, &kp, &len, NULL, 0);
 2055 	if (rc != 0 && errno != ESRCH)
 2056 		return false;
 2057 	if (len == 0 || len != sizeof(kp))
 2058 		return false;
 2059 
 2060 	return kp.ki_ruid == uid;
 2061 }
 2062 #elif defined(HAVE_KVM_H)
 2063 static bool
 2064 pid_is_user(pid_t pid, uid_t uid)
 2065 {
 2066 	kvm_t *kd;
 2067 	uid_t proc_uid;
 2068 	struct kinfo_proc *kp;
 2069 	bool res = false;
 2070 
 2071 	kd = ssd_kvm_open();
 2072 	kp = ssd_kvm_get_procs(kd, KERN_PROC_PID, pid, NULL);
 2073 	if (kp == NULL)
 2074 		goto cleanup;
 2075 
 2076 #if defined(OS_FreeBSD)
 2077 	proc_uid = kp->ki_ruid;
 2078 #elif defined(OS_OpenBSD)
 2079 	proc_uid = kp->p_ruid;
 2080 #elif defined(OS_DragonFlyBSD)
 2081 	proc_uid = kp->kp_ruid;
 2082 #elif defined(OS_NetBSD)
 2083 	proc_uid = kp->kp_eproc.e_pcred.p_ruid;
 2084 #else
 2085 	if (kp->kp_proc.p_cred)
 2086 		kvm_read(kd, (u_long)&(kp->kp_proc.p_cred->p_ruid),
 2087 		         &proc_uid, sizeof(uid_t));
 2088 	else
 2089 		goto cleanup;
 2090 #endif
 2091 
 2092 	res = (proc_uid == (uid_t)uid);
 2093 
 2094 cleanup:
 2095 	kvm_close(kd);
 2096 
 2097 	return res;
 2098 }
 2099 #endif
 2100 
 2101 #if defined(OS_Linux)
 2102 static bool
 2103 pid_is_cmd(pid_t pid, const char *name)
 2104 {
 2105 	const char *comm;
 2106 
 2107 	comm = proc_status_field(pid, "Name:");
 2108 	if (comm == NULL)
 2109 		return false;
 2110 
 2111 	return strcmp(comm, name) == 0;
 2112 }
 2113 #elif defined(OS_Hurd)
 2114 static bool
 2115 pid_is_cmd(pid_t pid, const char *name)
 2116 {
 2117 	struct proc_stat *ps;
 2118 	size_t argv0_len;
 2119 	const char *argv0;
 2120 	const char *binary_name;
 2121 
 2122 	ps = get_proc_stat(pid, PSTAT_ARGS);
 2123 	if (ps == NULL)
 2124 		return false;
 2125 
 2126 	argv0 = proc_stat_args(ps);
 2127 	argv0_len = strlen(argv0) + 1;
 2128 
 2129 	binary_name = basename(argv0);
 2130 	if (strcmp(binary_name, name) == 0)
 2131 		return true;
 2132 
 2133 	/* XXX: This is all kinds of ugly, but on the Hurd there's no way to
 2134 	 * know the command name of a process, so we have to try to match
 2135 	 * also on argv[1] for the case of an interpreted script. */
 2136 	if (proc_stat_args_len(ps) > argv0_len) {
 2137 		const char *script_name = basename(argv0 + argv0_len);
 2138 
 2139 		return strcmp(script_name, name) == 0;
 2140 	}
 2141 
 2142 	return false;
 2143 }
 2144 #elif defined(OS_AIX)
 2145 static bool
 2146 pid_is_cmd(pid_t pid, const char *name)
 2147 {
 2148 	struct psinfo psi;
 2149 
 2150 	if (!proc_get_psinfo(pid, &psi))
 2151 		return false;
 2152 
 2153 	return strcmp(psi.pr_fname, name) == 0;
 2154 }
 2155 #elif defined(OS_HPUX)
 2156 static bool
 2157 pid_is_cmd(pid_t pid, const char *name)
 2158 {
 2159 	struct pst_status pst;
 2160 
 2161 	if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
 2162 		return false;
 2163 	return (strcmp(pst.pst_ucomm, name) == 0);
 2164 }
 2165 #elif defined(OS_Darwin)
 2166 static bool
 2167 pid_is_cmd(pid_t pid, const char *name)
 2168 {
 2169 	char pathname[_POSIX_PATH_MAX];
 2170 
 2171 	if (proc_pidpath(pid, pathname, sizeof(pathname)) < 0)
 2172 		return false;
 2173 
 2174 	return strcmp(pathname, name) == 0;
 2175 }
 2176 #elif defined(OS_FreeBSD)
 2177 static bool
 2178 pid_is_cmd(pid_t pid, const char *name)
 2179 {
 2180 	struct kinfo_proc kp;
 2181 	int rc, mib[4];
 2182 	size_t len;
 2183 
 2184 	mib[0] = CTL_KERN;
 2185 	mib[1] = KERN_PROC;
 2186 	mib[2] = KERN_PROC_PID;
 2187 	mib[3] = pid;
 2188 	len = sizeof(kp);
 2189 
 2190 	rc = sysctl(mib, 4, &kp, &len, NULL, 0);
 2191 	if (rc != 0 && errno != ESRCH)
 2192 		return false;
 2193 	if (len == 0 || len != sizeof(kp))
 2194 		return false;
 2195 
 2196 	return strcmp(kp.ki_comm, name) == 0;
 2197 }
 2198 #elif defined(HAVE_KVM_H)
 2199 static bool
 2200 pid_is_cmd(pid_t pid, const char *name)
 2201 {
 2202 	kvm_t *kd;
 2203 	struct kinfo_proc *kp;
 2204 	char *process_name;
 2205 	bool res = false;
 2206 
 2207 	kd = ssd_kvm_open();
 2208 	kp = ssd_kvm_get_procs(kd, KERN_PROC_PID, pid, NULL);
 2209 	if (kp == NULL)
 2210 		goto cleanup;
 2211 
 2212 #if defined(OS_FreeBSD)
 2213 	process_name = kp->ki_comm;
 2214 #elif defined(OS_OpenBSD)
 2215 	process_name = kp->p_comm;
 2216 #elif defined(OS_DragonFlyBSD)
 2217 	process_name = kp->kp_comm;
 2218 #else
 2219 	process_name = kp->kp_proc.p_comm;
 2220 #endif
 2221 
 2222 	res = (strcmp(name, process_name) == 0);
 2223 
 2224 cleanup:
 2225 	kvm_close(kd);
 2226 
 2227 	return res;
 2228 }
 2229 #endif
 2230 
 2231 #if defined(OS_Hurd)
 2232 static bool
 2233 pid_is_running(pid_t pid)
 2234 {
 2235 	return get_proc_stat(pid, 0) != NULL;
 2236 }
 2237 #else /* !OS_Hurd */
 2238 static bool
 2239 pid_is_running(pid_t pid)
 2240 {
 2241 	if (kill(pid, 0) == 0 || errno == EPERM)
 2242 		return true;
 2243 	else if (errno == ESRCH)
 2244 		return false;
 2245 	else
 2246 		fatale("error checking pid %u status", pid);
 2247 }
 2248 #endif
 2249 
 2250 static enum status_code
 2251 pid_check(pid_t pid)
 2252 {
 2253 	if (execname && !pid_is_exec(pid, &exec_stat))
 2254 		return STATUS_DEAD;
 2255 	if (match_ppid > 0 && !pid_is_child(pid, match_ppid))
 2256 		return STATUS_DEAD;
 2257 	if (userspec && !pid_is_user(pid, user_id))
 2258 		return STATUS_DEAD;
 2259 	if (cmdname && !pid_is_cmd(pid, cmdname))
 2260 		return STATUS_DEAD;
 2261 	if (action != ACTION_STOP && !pid_is_running(pid))
 2262 		return STATUS_DEAD;
 2263 
 2264 	pid_list_push(&found, pid);
 2265 
 2266 	return STATUS_OK;
 2267 }
 2268 
 2269 static enum status_code
 2270 do_pidfile(const char *name)
 2271 {
 2272 	FILE *f;
 2273 	static pid_t pid = 0;
 2274 
 2275 	if (pid)
 2276 		return pid_check(pid);
 2277 
 2278 	f = fopen(name, "r");
 2279 	if (f) {
 2280 		enum status_code pid_status;
 2281 
 2282 		/* If we are only matching on the pidfile, and it is owned by
 2283 		 * a non-root user, then this is a security risk, and the
 2284 		 * contents cannot be trusted, because the daemon might have
 2285 		 * been compromised.
 2286 		 *
 2287 		 * If the pidfile is world-writable we refuse to parse it.
 2288 		 *
 2289 		 * If we got /dev/null specified as the pidfile, we ignore the
 2290 		 * checks, as this is being used to run processes no matter
 2291 		 * what. */
 2292 		if (strcmp(name, "/dev/null") != 0) {
 2293 			struct stat st;
 2294 			int fd = fileno(f);
 2295 
 2296 			if (fstat(fd, &st) < 0)
 2297 				fatale("cannot stat pidfile %s", name);
 2298 
 2299 			if (match_mode == MATCH_PIDFILE &&
 2300 			    ((st.st_uid != getuid() && st.st_uid != 0) ||
 2301 			     (st.st_gid != getgid() && st.st_gid != 0)))
 2302 				fatal("matching only on non-root pidfile %s is insecure", name);
 2303 			if (st.st_mode & 0002)
 2304 				fatal("matching on world-writable pidfile %s is insecure", name);
 2305 
 2306 		}
 2307 
 2308 		if (fscanf(f, "%d", &pid) == 1)
 2309 			pid_status = pid_check(pid);
 2310 		else
 2311 			pid_status = STATUS_UNKNOWN;
 2312 		fclose(f);
 2313 
 2314 		if (pid_status == STATUS_DEAD)
 2315 			return STATUS_DEAD_PIDFILE;
 2316 		else
 2317 			return pid_status;
 2318 	} else if (errno == ENOENT)
 2319 		return STATUS_DEAD;
 2320 	else
 2321 		fatale("unable to open pidfile %s", name);
 2322 }
 2323 
 2324 #if defined(OS_Linux) || defined(OS_Solaris) || defined(OS_AIX)
 2325 static enum status_code
 2326 do_procinit(void)
 2327 {
 2328 	DIR *procdir;
 2329 	struct dirent *entry;
 2330 	int foundany;
 2331 	pid_t pid;
 2332 	enum status_code prog_status = STATUS_DEAD;
 2333 
 2334 	procdir = opendir("/proc");
 2335 	if (!procdir)
 2336 		fatale("unable to opendir /proc");
 2337 
 2338 	foundany = 0;
 2339 	while ((entry = readdir(procdir)) != NULL) {
 2340 		enum status_code pid_status;
 2341 
 2342 		if (sscanf(entry->d_name, "%d", &pid) != 1)
 2343 			continue;
 2344 		foundany++;
 2345 
 2346 		pid_status = pid_check(pid);
 2347 		if (pid_status < prog_status)
 2348 			prog_status = pid_status;
 2349 	}
 2350 	closedir(procdir);
 2351 	if (foundany == 0)
 2352 		fatal("nothing in /proc - not mounted?");
 2353 
 2354 	return prog_status;
 2355 }
 2356 #elif defined(OS_Hurd)
 2357 static int
 2358 check_proc_stat(struct proc_stat *ps)
 2359 {
 2360 	pid_check(proc_stat_pid(ps));
 2361 	return 0;
 2362 }
 2363 
 2364 static enum status_code
 2365 do_procinit(void)
 2366 {
 2367 	if (!procset)
 2368 		init_procset();
 2369 
 2370 	proc_stat_list_for_each(procset, check_proc_stat);
 2371 
 2372 	if (found)
 2373 		return STATUS_OK;
 2374 	else
 2375 		return STATUS_DEAD;
 2376 }
 2377 #elif defined(OS_Darwin)
 2378 static enum status_code
 2379 do_procinit(void)
 2380 {
 2381 	pid_t *pid_buf;
 2382 	int i, npids, pid_bufsize;
 2383 	enum status_code prog_status = STATUS_DEAD;
 2384 
 2385 	npids = proc_listallpids(NULL, 0);
 2386 	if (npids == 0)
 2387 		return STATUS_UNKNOWN;
 2388 
 2389 	/* Try to avoid sudden changes in number of PIDs. */
 2390 	npids += 4096;
 2391 	pid_bufsize = sizeof(pid_t) * npids;
 2392 	pid_buf = xmalloc(pid_bufsize);
 2393 
 2394 	npids = proc_listallpids(pid_buf, pid_bufsize);
 2395 	if (npids == 0)
 2396 		return STATUS_UNKNOWN;
 2397 
 2398 	for (i = 0; i < npids; i++) {
 2399 		enum status_code pid_status;
 2400 
 2401 		pid_status = pid_check(pid_buf[i]);
 2402 		if (pid_status < prog_status)
 2403 			prog_status = pid_status;
 2404 	}
 2405 
 2406 	free(pid_buf);
 2407 
 2408 	return prog_status;
 2409 }
 2410 #elif defined(OS_HPUX)
 2411 static enum status_code
 2412 do_procinit(void)
 2413 {
 2414 	struct pst_status pst[10];
 2415 	int i, count;
 2416 	int idx = 0;
 2417 	enum status_code prog_status = STATUS_DEAD;
 2418 
 2419 	while ((count = pstat_getproc(pst, sizeof(pst[0]), 10, idx)) > 0) {
 2420 		enum status_code pid_status;
 2421 
 2422 		for (i = 0; i < count; i++) {
 2423 			pid_status = pid_check(pst[i].pst_pid);
 2424 			if (pid_status < prog_status)
 2425 				prog_status = pid_status;
 2426 		}
 2427 		idx = pst[count - 1].pst_idx + 1;
 2428 	}
 2429 
 2430 	return prog_status;
 2431 }
 2432 #elif defined(OS_FreeBSD)
 2433 static enum status_code
 2434 do_procinit(void)
 2435 {
 2436 	struct kinfo_proc *kp;
 2437 	int rc, mib[3];
 2438 	size_t len = 0;
 2439 	int nentries, i;
 2440 	enum status_code prog_status = STATUS_DEAD;
 2441 
 2442 	mib[0] = CTL_KERN;
 2443 	mib[1] = KERN_PROC;
 2444 	mib[2] = KERN_PROC_PROC;
 2445 
 2446 	rc = sysctl(mib, 3, NULL, &len, NULL, 0);
 2447 	if (rc != 0 && errno != ESRCH)
 2448 		return STATUS_UNKNOWN;
 2449 	if (len == 0)
 2450 		return STATUS_UNKNOWN;
 2451 
 2452 	kp = xmalloc(len);
 2453 	rc = sysctl(mib, 3, kp, &len, NULL, 0);
 2454 	if (rc != 0 && errno != ESRCH)
 2455 		return STATUS_UNKNOWN;
 2456 	if (len == 0)
 2457 		return STATUS_UNKNOWN;
 2458 	nentries = len / sizeof(*kp);
 2459 
 2460 	for (i = 0; i < nentries; i++) {
 2461 		enum status_code pid_status;
 2462 
 2463 		pid_status = pid_check(kp[i].ki_pid);
 2464 		if (pid_status < prog_status)
 2465 			prog_status = pid_status;
 2466 	}
 2467 
 2468 	free(kp);
 2469 
 2470 	return prog_status;
 2471 }
 2472 #elif defined(HAVE_KVM_H)
 2473 static enum status_code
 2474 do_procinit(void)
 2475 {
 2476 	kvm_t *kd;
 2477 	int nentries, i;
 2478 	struct kinfo_proc *kp;
 2479 	enum status_code prog_status = STATUS_DEAD;
 2480 
 2481 	kd = ssd_kvm_open();
 2482 	kp = ssd_kvm_get_procs(kd, KERN_PROC_ALL, 0, &nentries);
 2483 
 2484 	for (i = 0; i < nentries; i++) {
 2485 		enum status_code pid_status;
 2486 		pid_t pid;
 2487 
 2488 #if defined(OS_FreeBSD)
 2489 		pid = kp[i].ki_pid;
 2490 #elif defined(OS_OpenBSD)
 2491 		pid = kp[i].p_pid;
 2492 #elif defined(OS_DragonFlyBSD)
 2493 		pid = kp[i].kp_pid;
 2494 #else
 2495 		pid = kp[i].kp_proc.p_pid;
 2496 #endif
 2497 
 2498 		pid_status = pid_check(pid);
 2499 		if (pid_status < prog_status)
 2500 			prog_status = pid_status;
 2501 	}
 2502 
 2503 	kvm_close(kd);
 2504 
 2505 	return prog_status;
 2506 }
 2507 #endif
 2508 
 2509 static enum status_code
 2510 do_findprocs(void)
 2511 {
 2512 	pid_list_free(&found);
 2513 
 2514 	if (match_pid > 0)
 2515 		return pid_check(match_pid);
 2516 	else if (pidfile)
 2517 		return do_pidfile(pidfile);
 2518 	else
 2519 		return do_procinit();
 2520 }
 2521 
 2522 static int
 2523 do_start(int argc, char **argv)
 2524 {
 2525 	int devnull_fd = -1;
 2526 	gid_t rgid;
 2527 	uid_t ruid;
 2528 
 2529 	do_findprocs();
 2530 
 2531 	if (found) {
 2532 		info("%s already running.\n", execname ? execname : "process");
 2533 		return exitnodo;
 2534 	}
 2535 	if (testmode && quietmode <= 0) {
 2536 		printf("Would start %s ", startas);
 2537 		while (argc-- > 0)
 2538 			printf("%s ", *argv++);
 2539 		if (changeuser != NULL) {
 2540 			printf(" (as user %s[%d]", changeuser, runas_uid);
 2541 			if (changegroup != NULL)
 2542 				printf(", and group %s[%d])", changegroup, runas_gid);
 2543 			else
 2544 				printf(")");
 2545 		}
 2546 		if (changeroot != NULL)
 2547 			printf(" in directory %s", changeroot);
 2548 		if (nicelevel)
 2549 			printf(", and add %i to the priority", nicelevel);
 2550 		if (proc_sched)
 2551 			printf(", with scheduling policy %s with priority %i",
 2552 			       proc_sched->policy_name, proc_sched->priority);
 2553 		if (io_sched)
 2554 			printf(", with IO scheduling class %s with priority %i",
 2555 			       io_sched->policy_name, io_sched->priority);
 2556 		printf(".\n");
 2557 	}
 2558 	if (testmode)
 2559 		return 0;
 2560 	debug("Starting %s...\n", startas);
 2561 	*--argv = startas;
 2562 	if (background)
 2563 		/* Ok, we need to detach this process. */
 2564 		daemonize();
 2565 	else if (mpidfile && pidfile != NULL)
 2566 		/* User wants _us_ to make the pidfile, but detach themself! */
 2567 		write_pidfile(pidfile, getpid());
 2568 	if (background && close_io) {
 2569 		devnull_fd = open("/dev/null", O_RDWR);
 2570 		if (devnull_fd < 0)
 2571 			fatale("unable to open '%s'", "/dev/null");
 2572 	}
 2573 	if (nicelevel) {
 2574 		errno = 0;
 2575 		if ((nice(nicelevel) == -1) && (errno != 0))
 2576 			fatale("unable to alter nice level by %i", nicelevel);
 2577 	}
 2578 	if (proc_sched)
 2579 		set_proc_schedule(proc_sched);
 2580 	if (io_sched)
 2581 		set_io_schedule(io_sched);
 2582 	if (umask_value >= 0)
 2583 		umask(umask_value);
 2584 	if (changeroot != NULL) {
 2585 		if (chdir(changeroot) < 0)
 2586 			fatale("unable to chdir() to %s", changeroot);
 2587 		if (chroot(changeroot) < 0)
 2588 			fatale("unable to chroot() to %s", changeroot);
 2589 	}
 2590 	if (chdir(changedir) < 0)
 2591 		fatale("unable to chdir() to %s", changedir);
 2592 
 2593 	rgid = getgid();
 2594 	ruid = getuid();
 2595 	if (changegroup != NULL) {
 2596 		if (rgid != (gid_t)runas_gid)
 2597 			if (setgid(runas_gid))
 2598 				fatale("unable to set gid to %d", runas_gid);
 2599 	}
 2600 	if (changeuser != NULL) {
 2601 		/* We assume that if our real user and group are the same as
 2602 		 * the ones we should switch to, the supplementary groups
 2603 		 * will be already in place. */
 2604 		if (rgid != (gid_t)runas_gid || ruid != (uid_t)runas_uid)
 2605 			if (initgroups(changeuser, runas_gid))
 2606 				fatale("unable to set initgroups() with gid %d",
 2607 				      runas_gid);
 2608 
 2609 		if (ruid != (uid_t)runas_uid)
 2610 			if (setuid(runas_uid))
 2611 				fatale("unable to set uid to %s", changeuser);
 2612 	}
 2613 
 2614 	if (background && close_io) {
 2615 		int i;
 2616 
 2617 		dup2(devnull_fd, 0); /* stdin */
 2618 		dup2(devnull_fd, 1); /* stdout */
 2619 		dup2(devnull_fd, 2); /* stderr */
 2620 
 2621 		 /* Now close all extra fds. */
 2622 		for (i = get_open_fd_max() - 1; i >= 3; --i)
 2623 			close(i);
 2624 	}
 2625 	execv(startas, argv);
 2626 	fatale("unable to start %s", startas);
 2627 }
 2628 
 2629 static void
 2630 do_stop(int sig_num, int *n_killed, int *n_notkilled)
 2631 {
 2632 	struct pid_list *p;
 2633 
 2634 	do_findprocs();
 2635 
 2636 	*n_killed = 0;
 2637 	*n_notkilled = 0;
 2638 
 2639 	if (!found)
 2640 		return;
 2641 
 2642 	pid_list_free(&killed);
 2643 
 2644 	for (p = found; p; p = p->next) {
 2645 		if (testmode) {
 2646 			info("Would send signal %d to %d.\n", sig_num, p->pid);
 2647 			(*n_killed)++;
 2648 		} else if (kill(p->pid, sig_num) == 0) {
 2649 			pid_list_push(&killed, p->pid);
 2650 			(*n_killed)++;
 2651 		} else {
 2652 			if (sig_num)
 2653 				warning("failed to kill %d: %s\n",
 2654 				        p->pid, strerror(errno));
 2655 			(*n_notkilled)++;
 2656 		}
 2657 	}
 2658 }
 2659 
 2660 static void
 2661 do_stop_summary(int retry_nr)
 2662 {
 2663 	struct pid_list *p;
 2664 
 2665 	if (quietmode >= 0 || !killed)
 2666 		return;
 2667 
 2668 	printf("Stopped %s (pid", what_stop);
 2669 	for (p = killed; p; p = p->next)
 2670 		printf(" %d", p->pid);
 2671 	putchar(')');
 2672 	if (retry_nr > 0)
 2673 		printf(", retry #%d", retry_nr);
 2674 	printf(".\n");
 2675 }
 2676 
 2677 static void DPKG_ATTR_PRINTF(1)
 2678 set_what_stop(const char *format, ...)
 2679 {
 2680 	va_list arglist;
 2681 	int rc;
 2682 
 2683 	va_start(arglist, format);
 2684 	rc = vasprintf(&what_stop, format, arglist);
 2685 	va_end(arglist);
 2686 
 2687 	if (rc < 0)
 2688 		fatale("cannot allocate formatted string");
 2689 }
 2690 
 2691 /*
 2692  * We want to keep polling for the processes, to see if they've exited, or
 2693  * until the timeout expires.
 2694  *
 2695  * This is a somewhat complicated algorithm to try to ensure that we notice
 2696  * reasonably quickly when all the processes have exited, but don't spend
 2697  * too much CPU time polling. In particular, on a fast machine with
 2698  * quick-exiting daemons we don't want to delay system shutdown too much,
 2699  * whereas on a slow one, or where processes are taking some time to exit,
 2700  * we want to increase the polling interval.
 2701  *
 2702  * The algorithm is as follows: we measure the elapsed time it takes to do
 2703  * one poll(), and wait a multiple of this time for the next poll. However,
 2704  * if that would put us past the end of the timeout period we wait only as
 2705  * long as the timeout period, but in any case we always wait at least
 2706  * MIN_POLL_INTERVAL (20ms). The multiple (‘ratio’) starts out as 2, and
 2707  * increases by 1 for each poll to a maximum of 10; so we use up to between
 2708  * 30% and 10% of the machine's resources (assuming a few reasonable things
 2709  * about system performance).
 2710  */
 2711 static bool
 2712 do_stop_timeout(int timeout, int *n_killed, int *n_notkilled)
 2713 {
 2714 	struct timespec stopat, before, after, interval, maxinterval;
 2715 	int rc, ratio;
 2716 
 2717 	timespec_gettime(&stopat);
 2718 	stopat.tv_sec += timeout;
 2719 	ratio = 1;
 2720 	for (;;) {
 2721 		timespec_gettime(&before);
 2722 		if (timespec_cmp(&before, &stopat, >))
 2723 			return false;
 2724 
 2725 		do_stop(0, n_killed, n_notkilled);
 2726 		if (!*n_killed)
 2727 			return true;
 2728 
 2729 		timespec_gettime(&after);
 2730 
 2731 		if (!timespec_cmp(&after, &stopat, <))
 2732 			return false;
 2733 
 2734 		if (ratio < 10)
 2735 			ratio++;
 2736 
 2737 		timespec_sub(&stopat, &after, &maxinterval);
 2738 		timespec_sub(&after, &before, &interval);
 2739 		timespec_mul(&interval, ratio);
 2740 
 2741 		if (interval.tv_sec < 0 || interval.tv_nsec < 0)
 2742 			interval.tv_sec = interval.tv_nsec = 0;
 2743 
 2744 		if (timespec_cmp(&interval, &maxinterval, >))
 2745 			interval = maxinterval;
 2746 
 2747 		if (interval.tv_sec == 0 &&
 2748 		    interval.tv_nsec <= MIN_POLL_INTERVAL)
 2749 			interval.tv_nsec = MIN_POLL_INTERVAL;
 2750 
 2751 		rc = pselect(0, NULL, NULL, NULL, &interval, NULL);
 2752 		if (rc < 0 && errno != EINTR)
 2753 			fatale("select() failed for pause");
 2754 	}
 2755 }
 2756 
 2757 static int
 2758 finish_stop_schedule(bool anykilled)
 2759 {
 2760 	if (rpidfile && pidfile && !testmode)
 2761 		remove_pidfile(pidfile);
 2762 
 2763 	if (anykilled)
 2764 		return 0;
 2765 
 2766 	info("No %s found running; none killed.\n", what_stop);
 2767 
 2768 	return exitnodo;
 2769 }
 2770 
 2771 static int
 2772 run_stop_schedule(void)
 2773 {
 2774 	int position, n_killed, n_notkilled, value, retry_nr;
 2775 	bool anykilled;
 2776 
 2777 	if (testmode) {
 2778 		if (schedule != NULL) {
 2779 			info("Ignoring --retry in test mode\n");
 2780 			schedule = NULL;
 2781 		}
 2782 	}
 2783 
 2784 	if (cmdname)
 2785 		set_what_stop("%s", cmdname);
 2786 	else if (execname)
 2787 		set_what_stop("%s", execname);
 2788 	else if (pidfile)
 2789 		set_what_stop("process in pidfile '%s'", pidfile);
 2790 	else if (match_pid > 0)
 2791 		set_what_stop("process with pid %d", match_pid);
 2792 	else if (match_ppid > 0)
 2793 		set_what_stop("process(es) with parent pid %d", match_ppid);
 2794 	else if (userspec)
 2795 		set_what_stop("process(es) owned by '%s'", userspec);
 2796 	else
 2797 		BUG("no match option, please report");
 2798 
 2799 	anykilled = false;
 2800 	retry_nr = 0;
 2801 
 2802 	if (schedule == NULL) {
 2803 		do_stop(signal_nr, &n_killed, &n_notkilled);
 2804 		do_stop_summary(0);
 2805 		if (n_notkilled > 0)
 2806 			info("%d pids were not killed\n", n_notkilled);
 2807 		if (n_killed)
 2808 			anykilled = true;
 2809 		return finish_stop_schedule(anykilled);
 2810 	}
 2811 
 2812 	for (position = 0; position < schedule_length; position++) {
 2813 	reposition:
 2814 		value = schedule[position].value;
 2815 		n_notkilled = 0;
 2816 
 2817 		switch (schedule[position].type) {
 2818 		case sched_goto:
 2819 			position = value;
 2820 			goto reposition;
 2821 		case sched_signal:
 2822 			do_stop(value, &n_killed, &n_notkilled);
 2823 			do_stop_summary(retry_nr++);
 2824 			if (!n_killed)
 2825 				return finish_stop_schedule(anykilled);
 2826 			else
 2827 				anykilled = true;
 2828 			continue;
 2829 		case sched_timeout:
 2830 			if (do_stop_timeout(value, &n_killed, &n_notkilled))
 2831 				return finish_stop_schedule(anykilled);
 2832 			else
 2833 				continue;
 2834 		default:
 2835 			BUG("schedule[%d].type value %d is not valid",
 2836 			    position, schedule[position].type);
 2837 		}
 2838 	}
 2839 
 2840 	info("Program %s, %d process(es), refused to die.\n",
 2841 	     what_stop, n_killed);
 2842 
 2843 	return 2;
 2844 }
 2845 
 2846 int
 2847 main(int argc, char **argv)
 2848 {
 2849 	progname = argv[0];
 2850 
 2851 	parse_options(argc, argv);
 2852 	setup_options();
 2853 
 2854 	argc -= optind;
 2855 	argv += optind;
 2856 
 2857 	if (action == ACTION_START)
 2858 		return do_start(argc, argv);
 2859 	else if (action == ACTION_STOP)
 2860 		return run_stop_schedule();
 2861 	else if (action == ACTION_STATUS)
 2862 		return do_findprocs();
 2863 
 2864 	return 0;
 2865 }

Generated by cgit