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