]> git.proxmox.com Git - mirror_frr.git/blob - tools/start-stop-daemon.c
*: reindent
[mirror_frr.git] / tools / start-stop-daemon.c
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 aswell.
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 * Modified for Gentoo rc-scripts by Donny Davies <woodchip@gentoo.org>:
23 * I removed the BSD/Hurd/OtherOS stuff, added #include <stddef.h>
24 * and stuck in a #define VERSION "1.9.18". Now it compiles without
25 * the whole automake/config.h dance.
26 */
27
28 #ifdef HAVE_LXC
29 #define _GNU_SOURCE
30 #include <sched.h>
31 #endif /* HAVE_LXC */
32
33 #include <stddef.h>
34 #define VERSION "1.9.18"
35
36 #define MIN_POLL_INTERVAL 20000 /*us*/
37
38 #include <errno.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <stdarg.h>
43 #include <signal.h>
44 #include <sys/stat.h>
45 #include <dirent.h>
46 #include <sys/time.h>
47 #include <sys/queue.h>
48 #include <unistd.h>
49 #include <getopt.h>
50 #include <pwd.h>
51 #include <grp.h>
52 #include <sys/ioctl.h>
53 #include <sys/types.h>
54 #include <termios.h>
55 #include <fcntl.h>
56 #include <limits.h>
57 #include <assert.h>
58 #include <ctype.h>
59 #ifdef linux
60 #include <linux/sched.h>
61 #endif
62
63 static int testmode = 0;
64 static int quietmode = 0;
65 static int exitnodo = 1;
66 static int start = 0;
67 static int stop = 0;
68 static int background = 0;
69 static int mpidfile = 0;
70 static int signal_nr = 15;
71 static const char *signal_str = NULL;
72 static int user_id = -1;
73 static int runas_uid = -1;
74 static int runas_gid = -1;
75 static const char *userspec = NULL;
76 static char *changeuser = NULL;
77 static const char *changegroup = NULL;
78 static char *changeroot = NULL;
79 static const char *cmdname = NULL;
80 static char *execname = NULL;
81 static char *startas = NULL;
82 static const char *pidfile = NULL;
83 static char what_stop[1024];
84 static const char *schedule_str = NULL;
85 static const char *progname = "";
86 static int nicelevel = 0;
87
88 static struct stat exec_stat;
89
90 struct pid_list {
91 struct pid_list *next;
92 pid_t pid;
93 };
94
95 static struct pid_list *found = NULL;
96 static struct pid_list *killed = NULL;
97
98 struct schedule_item {
99 enum { sched_timeout, sched_signal, sched_goto, sched_forever } type;
100 int value; /* seconds, signal no., or index into array */
101 /* sched_forever is only seen within parse_schedule and callees */
102 };
103
104 static int schedule_length;
105 static struct schedule_item *schedule = NULL;
106
107 LIST_HEAD(namespace_head, namespace);
108
109 struct namespace
110 {
111 LIST_ENTRY(namespace) list;
112 const char *path;
113 int nstype;
114 };
115
116 static struct namespace_head namespace_head;
117
118 static void *xmalloc(int size);
119 static void push(struct pid_list **list, pid_t pid);
120 static void do_help(void);
121 static void parse_options(int argc, char *const *argv);
122 static int pid_is_user(pid_t pid, uid_t uid);
123 static int pid_is_cmd(pid_t pid, const char *name);
124 static void check(pid_t pid);
125 static void do_pidfile(const char *name);
126 static void do_stop(int signal_nr, int quietmode, int *n_killed,
127 int *n_notkilled, int retry_nr);
128 static int pid_is_exec(pid_t pid, const struct stat *esb);
129
130 #ifdef __GNUC__
131 static void fatal(const char *format, ...)
132 __attribute__((noreturn, format(printf, 1, 2)));
133 static void badusage(const char *msg) __attribute__((noreturn));
134 #else
135 static void fatal(const char *format, ...);
136 static void badusage(const char *msg);
137 #endif
138
139 /* This next part serves only to construct the TVCALC macro, which
140 * is used for doing arithmetic on struct timeval's. It works like this:
141 * TVCALC(result, expression);
142 * where result is a struct timeval (and must be an lvalue) and
143 * expression is the single expression for both components. In this
144 * expression you can use the special values TVELEM, which when fed a
145 * const struct timeval* gives you the relevant component, and
146 * TVADJUST. TVADJUST is necessary when subtracting timevals, to make
147 * it easier to renormalise. Whenver you subtract timeval elements,
148 * you must make sure that TVADJUST is added to the result of the
149 * subtraction (before any resulting multiplication or what have you).
150 * TVELEM must be linear in TVADJUST.
151 */
152 typedef long tvselector(const struct timeval *);
153 static long tvselector_sec(const struct timeval *tv)
154 {
155 return tv->tv_sec;
156 }
157 static long tvselector_usec(const struct timeval *tv)
158 {
159 return tv->tv_usec;
160 }
161 #define TVCALC_ELEM(result, expr, sec, adj) \
162 { \
163 const long TVADJUST = adj; \
164 long (*const TVELEM)(const struct timeval *) = \
165 tvselector_##sec; \
166 (result).tv_##sec = (expr); \
167 }
168 #define TVCALC(result, expr) \
169 do { \
170 TVCALC_ELEM(result, expr, sec, (-1)); \
171 TVCALC_ELEM(result, expr, usec, (+1000000)); \
172 (result).tv_sec += (result).tv_usec / 1000000; \
173 (result).tv_usec %= 1000000; \
174 } while (0)
175
176
177 static void fatal(const char *format, ...)
178 {
179 va_list arglist;
180
181 fprintf(stderr, "%s: ", progname);
182 va_start(arglist, format);
183 vfprintf(stderr, format, arglist);
184 va_end(arglist);
185 putc('\n', stderr);
186 exit(2);
187 }
188
189
190 static void *xmalloc(int size)
191 {
192 void *ptr;
193
194 ptr = malloc(size);
195 if (ptr)
196 return ptr;
197 fatal("malloc(%d) failed", size);
198 }
199
200 static void xgettimeofday(struct timeval *tv)
201 {
202 if (gettimeofday(tv, 0) != 0)
203 fatal("gettimeofday failed: %s", strerror(errno));
204 }
205
206 static void push(struct pid_list **list, pid_t pid)
207 {
208 struct pid_list *p;
209
210 p = xmalloc(sizeof(*p));
211 p->next = *list;
212 p->pid = pid;
213 *list = p;
214 }
215
216 static void clear(struct pid_list **list)
217 {
218 struct pid_list *here, *next;
219
220 for (here = *list; here != NULL; here = next) {
221 next = here->next;
222 free(here);
223 }
224
225 *list = NULL;
226 }
227
228 #ifdef linux
229 static const char *next_dirname(const char *s)
230 {
231 const char *cur;
232
233 cur = (const char *)s;
234
235 if (*cur != '\0') {
236 for (; *cur != '/'; ++cur)
237 if (*cur == '\0')
238 return cur;
239
240 for (; *cur == '/'; ++cur)
241 ;
242 }
243
244 return cur;
245 }
246
247 static void add_namespace(const char *path)
248 {
249 int nstype;
250 const char *nsdirname, *nsname, *cur;
251 struct namespace *namespace;
252
253 cur = (const char *)path;
254 nsdirname = nsname = "";
255
256 while ((cur = next_dirname(cur))[0] != '\0') {
257 nsdirname = nsname;
258 nsname = cur;
259 }
260
261 if (!memcmp(nsdirname, "ipcns/", strlen("ipcns/")))
262 nstype = CLONE_NEWIPC;
263 else if (!memcmp(nsdirname, "netns/", strlen("netns/")))
264 nstype = CLONE_NEWNET;
265 else if (!memcmp(nsdirname, "utcns/", strlen("utcns/")))
266 nstype = CLONE_NEWUTS;
267 else
268 badusage("invalid namepspace path");
269
270 namespace = xmalloc(sizeof(*namespace));
271 namespace->path = (const char *)path;
272 namespace->nstype = nstype;
273 LIST_INSERT_HEAD(&namespace_head, namespace, list);
274 }
275 #endif
276
277 #ifdef HAVE_LXC
278 static void set_namespaces()
279 {
280 struct namespace *namespace;
281 int fd;
282
283 LIST_FOREACH(namespace, &namespace_head, list)
284 {
285 if ((fd = open(namespace->path, O_RDONLY)) == -1)
286 fatal("open namespace %s: %s", namespace->path,
287 strerror(errno));
288 if (setns(fd, namespace->nstype) == -1)
289 fatal("setns %s: %s", namespace->path, strerror(errno));
290 }
291 }
292 #else
293 static void set_namespaces()
294 {
295 if (!LIST_EMPTY(&namespace_head))
296 fatal("LCX namespaces not supported");
297 }
298 #endif
299
300 static void do_help(void)
301 {
302 printf("start-stop-daemon " VERSION
303 " for Debian - small and fast C version written by\n"
304 "Marek Michalkiewicz <marekm@i17linuxb.ists.pwr.wroc.pl>, public domain.\n"
305 "\n"
306 "Usage:\n"
307 " start-stop-daemon -S|--start options ... -- arguments ...\n"
308 " start-stop-daemon -K|--stop options ...\n"
309 " start-stop-daemon -H|--help\n"
310 " start-stop-daemon -V|--version\n"
311 "\n"
312 "Options (at least one of --exec|--pidfile|--user is required):\n"
313 " -x|--exec <executable> program to start/check if it is running\n"
314 " -p|--pidfile <pid-file> pid file to check\n"
315 " -c|--chuid <name|uid[:group|gid]>\n"
316 " change to this user/group before starting process\n"
317 " -u|--user <username>|<uid> stop processes owned by this user\n"
318 " -n|--name <process-name> stop processes with this name\n"
319 " -s|--signal <signal> signal to send (default TERM)\n"
320 " -a|--startas <pathname> program to start (default is <executable>)\n"
321 " -N|--nicelevel <incr> add incr to the process's nice level\n"
322 " -b|--background force the process to detach\n"
323 " -m|--make-pidfile create the pidfile before starting\n"
324 " -R|--retry <schedule> check whether processes die, and retry\n"
325 " -t|--test test mode, don't do anything\n"
326 " -o|--oknodo exit status 0 (not 1) if nothing done\n"
327 " -q|--quiet be more quiet\n"
328 " -v|--verbose be more verbose\n"
329 "Retry <schedule> is <item>|/<item>/... where <item> is one of\n"
330 " -<signal-num>|[-]<signal-name> send that signal\n"
331 " <timeout> wait that many seconds\n"
332 " forever repeat remainder forever\n"
333 "or <schedule> may be just <timeout>, meaning <signal>/<timeout>/KILL/<timeout>\n"
334 "\n"
335 "Exit status: 0 = done 1 = nothing done (=> 0 if --oknodo)\n"
336 " 3 = trouble 2 = with --retry, processes wouldn't die\n");
337 }
338
339
340 static void badusage(const char *msg)
341 {
342 if (msg)
343 fprintf(stderr, "%s: %s\n", progname, msg);
344 fprintf(stderr, "Try `%s --help' for more information.\n", progname);
345 exit(3);
346 }
347
348 struct sigpair {
349 const char *name;
350 int signal;
351 };
352
353 const struct sigpair siglist[] = {
354 {"ABRT", SIGABRT}, {"ALRM", SIGALRM}, {"FPE", SIGFPE},
355 {"HUP", SIGHUP}, {"ILL", SIGILL}, {"INT", SIGINT},
356 {"KILL", SIGKILL}, {"PIPE", SIGPIPE}, {"QUIT", SIGQUIT},
357 {"SEGV", SIGSEGV}, {"TERM", SIGTERM}, {"USR1", SIGUSR1},
358 {"USR2", SIGUSR2}, {"CHLD", SIGCHLD}, {"CONT", SIGCONT},
359 {"STOP", SIGSTOP}, {"TSTP", SIGTSTP}, {"TTIN", SIGTTIN},
360 {"TTOU", SIGTTOU}};
361
362 static int parse_integer(const char *string, int *value_r)
363 {
364 unsigned long ul;
365 char *ep;
366
367 if (!string[0])
368 return -1;
369
370 ul = strtoul(string, &ep, 10);
371 if (ul > INT_MAX || *ep != '\0')
372 return -1;
373
374 *value_r = ul;
375 return 0;
376 }
377
378 static int parse_signal(const char *signal_str, int *signal_nr)
379 {
380 unsigned int i;
381
382 if (parse_integer(signal_str, signal_nr) == 0)
383 return 0;
384
385 for (i = 0; i < sizeof(siglist) / sizeof(siglist[0]); i++) {
386 if (strcmp(signal_str, siglist[i].name) == 0) {
387 *signal_nr = siglist[i].signal;
388 return 0;
389 }
390 }
391 return -1;
392 }
393
394 static void parse_schedule_item(const char *string, struct schedule_item *item)
395 {
396 const char *after_hyph;
397
398 if (!strcmp(string, "forever")) {
399 item->type = sched_forever;
400 } else if (isdigit(string[0])) {
401 item->type = sched_timeout;
402 if (parse_integer(string, &item->value) != 0)
403 badusage("invalid timeout value in schedule");
404 } else if ((after_hyph = string + (string[0] == '-'))
405 && parse_signal(after_hyph, &item->value) == 0) {
406 item->type = sched_signal;
407 } else {
408 badusage(
409 "invalid schedule item (must be [-]<signal-name>, "
410 "-<signal-number>, <timeout> or `forever'");
411 }
412 }
413
414 static void parse_schedule(const char *schedule_str)
415 {
416 char item_buf[20];
417 const char *slash;
418 int count, repeatat;
419 ptrdiff_t str_len;
420
421 count = 0;
422 for (slash = schedule_str; *slash; slash++)
423 if (*slash == '/')
424 count++;
425
426 schedule_length = (count == 0) ? 4 : count + 1;
427 schedule = xmalloc(sizeof(*schedule) * schedule_length);
428
429 if (count == 0) {
430 schedule[0].type = sched_signal;
431 schedule[0].value = signal_nr;
432 parse_schedule_item(schedule_str, &schedule[1]);
433 if (schedule[1].type != sched_timeout) {
434 badusage(
435 "--retry takes timeout, or schedule list"
436 " of at least two items");
437 }
438 schedule[2].type = sched_signal;
439 schedule[2].value = SIGKILL;
440 schedule[3] = schedule[1];
441 } else {
442 count = 0;
443 repeatat = -1;
444 while (schedule_str != NULL) {
445 slash = strchr(schedule_str, '/');
446 str_len = slash ? slash - schedule_str
447 : (ptrdiff_t)strlen(schedule_str);
448 if (str_len >= (ptrdiff_t)sizeof(item_buf))
449 badusage(
450 "invalid schedule item: far too long"
451 " (you must delimit items with slashes)");
452 memcpy(item_buf, schedule_str, str_len);
453 item_buf[str_len] = 0;
454 schedule_str = slash ? slash + 1 : NULL;
455
456 parse_schedule_item(item_buf, &schedule[count]);
457 if (schedule[count].type == sched_forever) {
458 if (repeatat >= 0)
459 badusage(
460 "invalid schedule: `forever'"
461 " appears more than once");
462 repeatat = count;
463 continue;
464 }
465 count++;
466 }
467 if (repeatat >= 0) {
468 schedule[count].type = sched_goto;
469 schedule[count].value = repeatat;
470 count++;
471 }
472 assert(count == schedule_length);
473 }
474 }
475
476 static void parse_options(int argc, char *const *argv)
477 {
478 static struct option longopts[] = {
479 {"help", 0, NULL, 'H'}, {"stop", 0, NULL, 'K'},
480 {"start", 0, NULL, 'S'}, {"version", 0, NULL, 'V'},
481 {"startas", 1, NULL, 'a'}, {"name", 1, NULL, 'n'},
482 {"oknodo", 0, NULL, 'o'}, {"pidfile", 1, NULL, 'p'},
483 {"quiet", 0, NULL, 'q'}, {"signal", 1, NULL, 's'},
484 {"test", 0, NULL, 't'}, {"user", 1, NULL, 'u'},
485 {"chroot", 1, NULL, 'r'}, {"namespace", 1, NULL, 'd'},
486 {"verbose", 0, NULL, 'v'}, {"exec", 1, NULL, 'x'},
487 {"chuid", 1, NULL, 'c'}, {"nicelevel", 1, NULL, 'N'},
488 {"background", 0, NULL, 'b'}, {"make-pidfile", 0, NULL, 'm'},
489 {"retry", 1, NULL, 'R'}, {NULL, 0, NULL, 0}};
490 int c;
491
492 for (;;) {
493 c = getopt_long(argc, argv,
494 "HKSVa:n:op:qr:d:s:tu:vx:c:N:bmR:", longopts,
495 (int *)0);
496 if (c == -1)
497 break;
498 switch (c) {
499 case 'H': /* --help */
500 do_help();
501 exit(0);
502 case 'K': /* --stop */
503 stop = 1;
504 break;
505 case 'S': /* --start */
506 start = 1;
507 break;
508 case 'V': /* --version */
509 printf("start-stop-daemon " VERSION "\n");
510 exit(0);
511 case 'a': /* --startas <pathname> */
512 startas = optarg;
513 break;
514 case 'n': /* --name <process-name> */
515 cmdname = optarg;
516 break;
517 case 'o': /* --oknodo */
518 exitnodo = 0;
519 break;
520 case 'p': /* --pidfile <pid-file> */
521 pidfile = optarg;
522 break;
523 case 'q': /* --quiet */
524 quietmode = 1;
525 break;
526 case 's': /* --signal <signal> */
527 signal_str = optarg;
528 break;
529 case 't': /* --test */
530 testmode = 1;
531 break;
532 case 'u': /* --user <username>|<uid> */
533 userspec = optarg;
534 break;
535 case 'v': /* --verbose */
536 quietmode = -1;
537 break;
538 case 'x': /* --exec <executable> */
539 execname = optarg;
540 break;
541 case 'c': /* --chuid <username>|<uid> */
542 /* we copy the string just in case we need the
543 * argument later. */
544 changeuser = strdup(optarg);
545 changeuser = strtok(changeuser, ":");
546 changegroup = strtok(NULL, ":");
547 break;
548 case 'r': /* --chroot /new/root */
549 changeroot = optarg;
550 break;
551 case 'd': /* --namespace /.../<ipcns>|<netns>|<utsns>/name */
552 #ifdef linux
553 add_namespace(optarg);
554 #endif
555 break;
556 case 'N': /* --nice */
557 nicelevel = atoi(optarg);
558 break;
559 case 'b': /* --background */
560 background = 1;
561 break;
562 case 'm': /* --make-pidfile */
563 mpidfile = 1;
564 break;
565 case 'R': /* --retry <schedule>|<timeout> */
566 schedule_str = optarg;
567 break;
568 default:
569 badusage(NULL); /* message printed by getopt */
570 }
571 }
572
573 if (signal_str != NULL) {
574 if (parse_signal(signal_str, &signal_nr) != 0)
575 badusage(
576 "signal value must be numeric or name"
577 " of signal (KILL, INTR, ...)");
578 }
579
580 if (schedule_str != NULL) {
581 parse_schedule(schedule_str);
582 }
583
584 if (start == stop)
585 badusage("need one of --start or --stop");
586
587 if (!execname && !pidfile && !userspec && !cmdname)
588 badusage(
589 "need at least one of --exec, --pidfile, --user or --name");
590
591 if (!startas)
592 startas = execname;
593
594 if (start && !startas)
595 badusage("--start needs --exec or --startas");
596
597 if (mpidfile && pidfile == NULL)
598 badusage("--make-pidfile is only relevant with --pidfile");
599
600 if (background && !start)
601 badusage("--background is only relevant with --start");
602 }
603
604 static int pid_is_exec(pid_t pid, const struct stat *esb)
605 {
606 struct stat sb;
607 char buf[32];
608
609 sprintf(buf, "/proc/%d/exe", pid);
610 if (stat(buf, &sb) != 0)
611 return 0;
612 return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
613 }
614
615
616 static int pid_is_user(pid_t pid, uid_t uid)
617 {
618 struct stat sb;
619 char buf[32];
620
621 sprintf(buf, "/proc/%d", pid);
622 if (stat(buf, &sb) != 0)
623 return 0;
624 return (sb.st_uid == uid);
625 }
626
627
628 static int pid_is_cmd(pid_t pid, const char *name)
629 {
630 char buf[32];
631 FILE *f;
632 int c;
633
634 sprintf(buf, "/proc/%d/stat", pid);
635 f = fopen(buf, "r");
636 if (!f)
637 return 0;
638 while ((c = getc(f)) != EOF && c != '(')
639 ;
640 if (c != '(') {
641 fclose(f);
642 return 0;
643 }
644 /* this hopefully handles command names containing ')' */
645 while ((c = getc(f)) != EOF && c == *name)
646 name++;
647 fclose(f);
648 return (c == ')' && *name == '\0');
649 }
650
651
652 static void check(pid_t pid)
653 {
654 if (execname && !pid_is_exec(pid, &exec_stat))
655 return;
656 if (userspec && !pid_is_user(pid, user_id))
657 return;
658 if (cmdname && !pid_is_cmd(pid, cmdname))
659 return;
660 push(&found, pid);
661 }
662
663 static void do_pidfile(const char *name)
664 {
665 FILE *f;
666 pid_t pid;
667
668 f = fopen(name, "r");
669 if (f) {
670 if (fscanf(f, "%d", &pid) == 1)
671 check(pid);
672 fclose(f);
673 } else if (errno != ENOENT)
674 fatal("open pidfile %s: %s", name, strerror(errno));
675 }
676
677 /* WTA: this needs to be an autoconf check for /proc/pid existance.
678 */
679 static void do_procinit(void)
680 {
681 DIR *procdir;
682 struct dirent *entry;
683 int foundany;
684 pid_t pid;
685
686 procdir = opendir("/proc");
687 if (!procdir)
688 fatal("opendir /proc: %s", strerror(errno));
689
690 foundany = 0;
691 while ((entry = readdir(procdir)) != NULL) {
692 if (sscanf(entry->d_name, "%d", &pid) != 1)
693 continue;
694 foundany++;
695 check(pid);
696 }
697 closedir(procdir);
698 if (!foundany)
699 fatal("nothing in /proc - not mounted?");
700 }
701
702 static void do_findprocs(void)
703 {
704 clear(&found);
705
706 if (pidfile)
707 do_pidfile(pidfile);
708 else
709 do_procinit();
710 }
711
712 /* return 1 on failure */
713 static void do_stop(int signal_nr, int quietmode, int *n_killed,
714 int *n_notkilled, int retry_nr)
715 {
716 struct pid_list *p;
717
718 do_findprocs();
719
720 *n_killed = 0;
721 *n_notkilled = 0;
722
723 if (!found)
724 return;
725
726 clear(&killed);
727
728 for (p = found; p; p = p->next) {
729 if (testmode)
730 printf("Would send signal %d to %d.\n", signal_nr,
731 p->pid);
732 else if (kill(p->pid, signal_nr) == 0) {
733 push(&killed, p->pid);
734 (*n_killed)++;
735 } else {
736 printf("%s: warning: failed to kill %d: %s\n", progname,
737 p->pid, strerror(errno));
738 (*n_notkilled)++;
739 }
740 }
741 if (quietmode < 0 && killed) {
742 printf("Stopped %s (pid", what_stop);
743 for (p = killed; p; p = p->next)
744 printf(" %d", p->pid);
745 putchar(')');
746 if (retry_nr > 0)
747 printf(", retry #%d", retry_nr);
748 printf(".\n");
749 }
750 }
751
752
753 static void set_what_stop(const char *str)
754 {
755 strncpy(what_stop, str, sizeof(what_stop));
756 what_stop[sizeof(what_stop) - 1] = '\0';
757 }
758
759 static int run_stop_schedule(void)
760 {
761 int r, position, n_killed, n_notkilled, value, ratio, anykilled,
762 retry_nr;
763 struct timeval stopat, before, after, interval, maxinterval;
764
765 if (testmode) {
766 if (schedule != NULL) {
767 printf("Ignoring --retry in test mode\n");
768 schedule = NULL;
769 }
770 }
771
772 if (cmdname)
773 set_what_stop(cmdname);
774 else if (execname)
775 set_what_stop(execname);
776 else if (pidfile)
777 sprintf(what_stop, "process in pidfile `%.200s'", pidfile);
778 else if (userspec)
779 sprintf(what_stop, "process(es) owned by `%.200s'", userspec);
780 else
781 fatal("internal error, please report");
782
783 anykilled = 0;
784 retry_nr = 0;
785 n_killed = 0;
786
787 if (schedule == NULL) {
788 do_stop(signal_nr, quietmode, &n_killed, &n_notkilled, 0);
789 if (n_notkilled > 0 && quietmode <= 0)
790 printf("%d pids were not killed\n", n_notkilled);
791 if (n_killed)
792 anykilled = 1;
793 goto x_finished;
794 }
795
796 for (position = 0; position < schedule_length;) {
797 value = schedule[position].value;
798 n_notkilled = 0;
799
800 switch (schedule[position].type) {
801
802 case sched_goto:
803 position = value;
804 continue;
805
806 case sched_signal:
807 do_stop(value, quietmode, &n_killed, &n_notkilled,
808 retry_nr++);
809 if (!n_killed)
810 goto x_finished;
811 else
812 anykilled = 1;
813 goto next_item;
814
815 case sched_timeout:
816 /* We want to keep polling for the processes, to see if
817 * they've exited,
818 * or until the timeout expires.
819 *
820 * This is a somewhat complicated algorithm to try to
821 * ensure that we
822 * notice reasonably quickly when all the processes have
823 * exited, but
824 * don't spend too much CPU time polling. In
825 * particular, on a fast
826 * machine with quick-exiting daemons we don't want to
827 * delay system
828 * shutdown too much, whereas on a slow one, or where
829 * processes are
830 * taking some time to exit, we want to increase the
831 * polling
832 * interval.
833 *
834 * The algorithm is as follows: we measure the elapsed
835 * time it takes
836 * to do one poll(), and wait a multiple of this time
837 * for the next
838 * poll. However, if that would put us past the end of
839 * the timeout
840 * period we wait only as long as the timeout period,
841 * but in any case
842 * we always wait at least MIN_POLL_INTERVAL (20ms).
843 * The multiple
844 * (`ratio') starts out as 2, and increases by 1 for
845 * each poll to a
846 * maximum of 10; so we use up to between 30% and 10% of
847 * the
848 * machine's resources (assuming a few reasonable things
849 * about system
850 * performance).
851 */
852 xgettimeofday(&stopat);
853 stopat.tv_sec += value;
854 ratio = 1;
855 for (;;) {
856 xgettimeofday(&before);
857 if (timercmp(&before, &stopat, >))
858 goto next_item;
859
860 do_stop(0, 1, &n_killed, &n_notkilled, 0);
861 if (!n_killed)
862 goto x_finished;
863
864 xgettimeofday(&after);
865
866 if (!timercmp(&after, &stopat, <))
867 goto next_item;
868
869 if (ratio < 10)
870 ratio++;
871
872 TVCALC(interval,
873 ratio * (TVELEM(&after) - TVELEM(&before)
874 + TVADJUST));
875 TVCALC(maxinterval,
876 TVELEM(&stopat) - TVELEM(&after)
877 + TVADJUST);
878
879 if (timercmp(&interval, &maxinterval, >))
880 interval = maxinterval;
881
882 if (interval.tv_sec == 0
883 && interval.tv_usec <= MIN_POLL_INTERVAL)
884 interval.tv_usec = MIN_POLL_INTERVAL;
885
886 r = select(0, 0, 0, 0, &interval);
887 if (r < 0 && errno != EINTR)
888 fatal("select() failed for pause: %s",
889 strerror(errno));
890 }
891
892 default:
893 assert(!"schedule[].type value must be valid");
894 }
895
896 next_item:
897 position++;
898 }
899
900 if (quietmode <= 0)
901 printf("Program %s, %d process(es), refused to die.\n",
902 what_stop, n_killed);
903
904 return 2;
905
906 x_finished:
907 if (!anykilled) {
908 if (quietmode <= 0)
909 printf("No %s found running; none killed.\n",
910 what_stop);
911 return exitnodo;
912 } else {
913 return 0;
914 }
915 }
916
917 /*
918 int main(int argc, char **argv) NONRETURNING;
919 */
920
921 int main(int argc, char **argv)
922 {
923 progname = argv[0];
924
925 LIST_INIT(&namespace_head);
926
927 parse_options(argc, argv);
928 argc -= optind;
929 argv += optind;
930
931 if (execname && stat(execname, &exec_stat))
932 fatal("stat %s: %s", execname, strerror(errno));
933
934 if (userspec && sscanf(userspec, "%d", &user_id) != 1) {
935 struct passwd *pw;
936
937 pw = getpwnam(userspec);
938 if (!pw)
939 fatal("user `%s' not found\n", userspec);
940
941 user_id = pw->pw_uid;
942 }
943
944 if (changegroup && sscanf(changegroup, "%d", &runas_gid) != 1) {
945 struct group *gr = getgrnam(changegroup);
946 if (!gr)
947 fatal("group `%s' not found\n", changegroup);
948 runas_gid = gr->gr_gid;
949 }
950 if (changeuser && sscanf(changeuser, "%d", &runas_uid) != 1) {
951 struct passwd *pw = getpwnam(changeuser);
952 if (!pw)
953 fatal("user `%s' not found\n", changeuser);
954 runas_uid = pw->pw_uid;
955 if (changegroup
956 == NULL) { /* pass the default group of this user */
957 changegroup = ""; /* just empty */
958 runas_gid = pw->pw_gid;
959 }
960 }
961
962 if (stop) {
963 int i = run_stop_schedule();
964 exit(i);
965 }
966
967 do_findprocs();
968
969 if (found) {
970 if (quietmode <= 0)
971 printf("%s already running.\n", execname);
972 exit(exitnodo);
973 }
974 if (testmode) {
975 printf("Would start %s ", startas);
976 while (argc-- > 0)
977 printf("%s ", *argv++);
978 if (changeuser != NULL) {
979 printf(" (as user %s[%d]", changeuser, runas_uid);
980 if (changegroup != NULL)
981 printf(", and group %s[%d])", changegroup,
982 runas_gid);
983 else
984 printf(")");
985 }
986 if (changeroot != NULL)
987 printf(" in directory %s", changeroot);
988 if (nicelevel)
989 printf(", and add %i to the priority", nicelevel);
990 printf(".\n");
991 exit(0);
992 }
993 if (quietmode < 0)
994 printf("Starting %s...\n", startas);
995 *--argv = startas;
996 if (changeroot != NULL) {
997 if (chdir(changeroot) < 0)
998 fatal("Unable to chdir() to %s", changeroot);
999 if (chroot(changeroot) < 0)
1000 fatal("Unable to chroot() to %s", changeroot);
1001 }
1002 if (changeuser != NULL) {
1003 if (setgid(runas_gid))
1004 fatal("Unable to set gid to %d", runas_gid);
1005 if (initgroups(changeuser, runas_gid))
1006 fatal("Unable to set initgroups() with gid %d",
1007 runas_gid);
1008 if (setuid(runas_uid))
1009 fatal("Unable to set uid to %s", changeuser);
1010 }
1011
1012 if (background) { /* ok, we need to detach this process */
1013 int i, fd;
1014 if (quietmode < 0)
1015 printf("Detatching to start %s...", startas);
1016 i = fork();
1017 if (i < 0) {
1018 fatal("Unable to fork.\n");
1019 }
1020 if (i) { /* parent */
1021 if (quietmode < 0)
1022 printf("done.\n");
1023 exit(0);
1024 }
1025 /* child continues here */
1026 /* now close all extra fds */
1027 for (i = getdtablesize() - 1; i >= 0; --i)
1028 close(i);
1029 /* change tty */
1030 fd = open("/dev/tty", O_RDWR);
1031 ioctl(fd, TIOCNOTTY, 0);
1032 close(fd);
1033 chdir("/");
1034 umask(022); /* set a default for dumb programs */
1035 setpgid(0, 0); /* set the process group */
1036 fd = open("/dev/null", O_RDWR); /* stdin */
1037 dup(fd); /* stdout */
1038 dup(fd); /* stderr */
1039 }
1040 if (nicelevel) {
1041 errno = 0;
1042 if (nice(nicelevel) < 0 && errno)
1043 fatal("Unable to alter nice level by %i: %s", nicelevel,
1044 strerror(errno));
1045 }
1046 if (mpidfile
1047 && pidfile != NULL) { /* user wants _us_ to make the pidfile :) */
1048 FILE *pidf = fopen(pidfile, "w");
1049 pid_t pidt = getpid();
1050 if (pidf == NULL)
1051 fatal("Unable to open pidfile `%s' for writing: %s",
1052 pidfile, strerror(errno));
1053 fprintf(pidf, "%d\n", pidt);
1054 fclose(pidf);
1055 }
1056 set_namespaces();
1057 execv(startas, argv);
1058 fatal("Unable to start %s: %s", startas, strerror(errno));
1059 }