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

Generated by cgit