start-stop-daemon.c 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633
  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. #include <config.h>
  23. #include <compat.h>
  24. #include <dpkg/macros.h>
  25. #if defined(linux) || (defined(__FreeBSD_kernel__) && defined(__GLIBC__))
  26. # define OSLinux
  27. #elif defined(__GNU__)
  28. # define OSHurd
  29. #elif defined(__sun)
  30. # define OSsunos
  31. #elif defined(OPENBSD) || defined(__OpenBSD__)
  32. # define OSOpenBSD
  33. #elif defined(hpux)
  34. # define OShpux
  35. #elif defined(__FreeBSD__)
  36. # define OSFreeBSD
  37. #elif defined(__NetBSD__)
  38. # define OSNetBSD
  39. #else
  40. # error Unknown architecture - cannot build start-stop-daemon
  41. #endif
  42. #define MIN_POLL_INTERVAL 20000 /* µs */
  43. #ifdef HAVE_SYS_CDEFS_H
  44. #include <sys/cdefs.h>
  45. #endif
  46. #ifdef HAVE_SYS_SYSCALL_H
  47. #include <sys/syscall.h>
  48. #endif
  49. #if defined(OSHurd)
  50. #include <hurd.h>
  51. #include <ps.h>
  52. #endif
  53. #if defined(OSOpenBSD) || defined(OSFreeBSD) || defined(OSNetBSD)
  54. #include <sys/param.h>
  55. #include <sys/proc.h>
  56. #include <err.h>
  57. #endif
  58. #ifdef HAVE_KVM_H
  59. #include <sys/sysctl.h>
  60. #include <sys/user.h>
  61. #include <kvm.h>
  62. #endif
  63. #if defined(OShpux)
  64. #include <sys/param.h>
  65. #include <sys/pstat.h>
  66. #endif
  67. #include <sys/types.h>
  68. #include <sys/time.h>
  69. #include <sys/stat.h>
  70. #include <sys/ioctl.h>
  71. #include <sys/termios.h>
  72. #include <assert.h>
  73. #include <errno.h>
  74. #include <limits.h>
  75. #include <fcntl.h>
  76. #include <dirent.h>
  77. #include <ctype.h>
  78. #include <string.h>
  79. #include <pwd.h>
  80. #include <grp.h>
  81. #include <signal.h>
  82. #include <unistd.h>
  83. #ifdef HAVE_STDDEF_H
  84. #include <stddef.h>
  85. #endif
  86. #include <stdbool.h>
  87. #include <stdarg.h>
  88. #include <stdlib.h>
  89. #include <stdio.h>
  90. #include <getopt.h>
  91. #ifdef HAVE_ERROR_H
  92. #include <error.h>
  93. #endif
  94. #ifdef _POSIX_PRIORITY_SCHEDULING
  95. #include <sched.h>
  96. #else
  97. #define SCHED_OTHER -1
  98. #define SCHED_FIFO -1
  99. #define SCHED_RR -1
  100. #endif
  101. #if defined(OSLinux)
  102. /* This comes from TASK_COMM_LEN defined in linux's include/linux/sched.h. */
  103. #define PROCESS_NAME_SIZE 15
  104. #endif
  105. #if defined(SYS_ioprio_set) && defined(linux)
  106. #define HAVE_IOPRIO_SET
  107. #endif
  108. enum {
  109. IOPRIO_WHO_PROCESS = 1,
  110. IOPRIO_WHO_PGRP,
  111. IOPRIO_WHO_USER,
  112. };
  113. enum {
  114. IOPRIO_CLASS_NONE,
  115. IOPRIO_CLASS_RT,
  116. IOPRIO_CLASS_BE,
  117. IOPRIO_CLASS_IDLE,
  118. };
  119. static int testmode = 0;
  120. static int quietmode = 0;
  121. static int exitnodo = 1;
  122. static int start = 0;
  123. static int stop = 0;
  124. static int background = 0;
  125. static int mpidfile = 0;
  126. static int signal_nr = SIGTERM;
  127. static int user_id = -1;
  128. static int runas_uid = -1;
  129. static int runas_gid = -1;
  130. static const char *userspec = NULL;
  131. static char *changeuser = NULL;
  132. static const char *changegroup = NULL;
  133. static char *changeroot = NULL;
  134. static const char *changedir = "/";
  135. static const char *cmdname = NULL;
  136. static char *execname = NULL;
  137. static char *startas = NULL;
  138. static const char *pidfile = NULL;
  139. static char what_stop[1024];
  140. static const char *progname = "";
  141. static int nicelevel = 0;
  142. static int umask_value = -1;
  143. #define IOPRIO_CLASS_SHIFT 13
  144. #define IOPRIO_PRIO_VALUE(class, prio) (((class) << IOPRIO_CLASS_SHIFT) | (prio))
  145. #define IO_SCHED_PRIO_MIN 0
  146. #define IO_SCHED_PRIO_MAX 7
  147. static struct stat exec_stat;
  148. #if defined(OSHurd)
  149. static struct proc_stat_list *procset = NULL;
  150. #endif
  151. struct pid_list {
  152. struct pid_list *next;
  153. pid_t pid;
  154. };
  155. static struct pid_list *found = NULL;
  156. static struct pid_list *killed = NULL;
  157. /* Resource scheduling policy. */
  158. struct res_schedule {
  159. const char *policy_name;
  160. int policy;
  161. int priority;
  162. };
  163. struct schedule_item {
  164. enum {
  165. sched_timeout,
  166. sched_signal,
  167. sched_goto,
  168. sched_forever /* Only seen within parse_schedule and callees */
  169. } type;
  170. int value; /* Seconds, signal no., or index into array. */
  171. };
  172. static struct res_schedule *proc_sched = NULL;
  173. static struct res_schedule *io_sched = NULL;
  174. static int schedule_length;
  175. static struct schedule_item *schedule = NULL;
  176. static void *xmalloc(int size);
  177. static void push(struct pid_list **list, pid_t pid);
  178. static void do_help(void);
  179. static void parse_options(int argc, char * const *argv);
  180. static bool pid_is_user(pid_t pid, uid_t uid);
  181. static bool pid_is_cmd(pid_t pid, const char *name);
  182. static void check(pid_t pid);
  183. static void do_pidfile(const char *name);
  184. static void do_stop(int sig_num, int quiet,
  185. int *n_killed, int *n_notkilled, int retry_nr);
  186. #if defined(OSLinux) || defined(OShpux)
  187. static bool pid_is_exec(pid_t pid, const struct stat *esb);
  188. #endif
  189. static void DPKG_ATTR_PRINTF(1)
  190. warning(const char *format, ...)
  191. {
  192. va_list arglist;
  193. fprintf(stderr, "%s: warning: ", progname);
  194. va_start(arglist, format);
  195. vfprintf(stderr, format, arglist);
  196. va_end(arglist);
  197. }
  198. static void DPKG_ATTR_NORET DPKG_ATTR_PRINTF(1)
  199. fatal(const char *format, ...)
  200. {
  201. va_list arglist;
  202. int errno_fatal = errno;
  203. fprintf(stderr, "%s: ", progname);
  204. va_start(arglist, format);
  205. vfprintf(stderr, format, arglist);
  206. va_end(arglist);
  207. if (errno_fatal)
  208. fprintf(stderr, " (%s)\n", strerror(errno_fatal));
  209. else
  210. fprintf(stderr, "\n");
  211. exit(2);
  212. }
  213. static void *
  214. xmalloc(int size)
  215. {
  216. void *ptr;
  217. ptr = malloc(size);
  218. if (ptr)
  219. return ptr;
  220. fatal("malloc(%d) failed", size);
  221. }
  222. static char *
  223. xstrdup(const char *str)
  224. {
  225. char *new_str;
  226. new_str = strdup(str);
  227. if (new_str)
  228. return new_str;
  229. fatal("strdup(%s) failed", str);
  230. }
  231. static void
  232. xgettimeofday(struct timeval *tv)
  233. {
  234. if (gettimeofday(tv, NULL) != 0)
  235. fatal("gettimeofday failed: %s", strerror(errno));
  236. }
  237. static void
  238. tmul(struct timeval *a, int b)
  239. {
  240. a->tv_sec *= b;
  241. a->tv_usec *= b;
  242. a->tv_sec = a->tv_sec + a->tv_usec / 1000000;
  243. a->tv_usec %= 1000000;
  244. }
  245. static long
  246. get_open_fd_max(void)
  247. {
  248. #ifdef HAVE_GETDTABLESIZE
  249. return getdtablesize();
  250. #else
  251. return sysconf(_SC_OPEN_MAX);
  252. #endif
  253. }
  254. static void
  255. daemonize(void)
  256. {
  257. pid_t pid;
  258. if (quietmode < 0)
  259. printf("Detaching to start %s...", startas);
  260. pid = fork();
  261. if (pid < 0)
  262. fatal("Unable to do first fork.\n");
  263. else if (pid) /* Parent. */
  264. _exit(0);
  265. /* Create a new session. */
  266. #ifdef HAVE_SETSID
  267. setsid();
  268. #else
  269. setpgid(0, 0);
  270. #endif
  271. pid = fork();
  272. if (pid < 0)
  273. fatal("Unable to do second fork.\n");
  274. else if (pid) /* Parent. */
  275. _exit(0);
  276. if (quietmode < 0)
  277. printf("done.\n");
  278. }
  279. static void
  280. push(struct pid_list **list, pid_t pid)
  281. {
  282. struct pid_list *p;
  283. p = xmalloc(sizeof(*p));
  284. p->next = *list;
  285. p->pid = pid;
  286. *list = p;
  287. }
  288. static void
  289. clear(struct pid_list **list)
  290. {
  291. struct pid_list *here, *next;
  292. for (here = *list; here != NULL; here = next) {
  293. next = here->next;
  294. free(here);
  295. }
  296. *list = NULL;
  297. }
  298. static void
  299. do_help(void)
  300. {
  301. printf(
  302. "Usage: start-stop-daemon [<option> ...] <command>\n"
  303. "\n"
  304. "Commands:\n"
  305. " -S|--start -- <argument> ... start a program and pass <arguments> to it\n"
  306. " -K|--stop stop a program\n"
  307. " -H|--help print help information\n"
  308. " -V|--version print version\n"
  309. "\n"
  310. "Matching options (at least one is required):\n"
  311. " -p|--pidfile <pid-file> pid file to check\n"
  312. " -x|--exec <executable> program to start/check if it is running\n"
  313. " -n|--name <process-name> process name to check\n"
  314. " -u|--user <username|uid> process owner to check\n"
  315. "\n"
  316. "Options:\n"
  317. " -g|--group <group|gid> run process as this group\n"
  318. " -c|--chuid <name|uid[:group|gid]>\n"
  319. " change to this user/group before starting\n"
  320. " process\n"
  321. " -s|--signal <signal> signal to send (default TERM)\n"
  322. " -a|--startas <pathname> program to start (default is <executable>)\n"
  323. " -r|--chroot <directory> chroot to <directory> before starting\n"
  324. " -d|--chdir <directory> change to <directory> (default is /)\n"
  325. " -N|--nicelevel <incr> add incr to the process's nice level\n"
  326. " -P|--procsched <policy[:prio]>\n"
  327. " use <policy> with <prio> for the kernel\n"
  328. " process scheduler (default prio is 0)\n"
  329. " -I|--iosched <class[:prio]> use <class> with <prio> to set the IO\n"
  330. " scheduler (default prio is 4)\n"
  331. " -k|--umask <mask> change the umask to <mask> before starting\n"
  332. " -b|--background force the process to detach\n"
  333. " -m|--make-pidfile create the pidfile before starting\n"
  334. " -R|--retry <schedule> check whether processes die, and retry\n"
  335. " -t|--test test mode, don't do anything\n"
  336. " -o|--oknodo exit status 0 (not 1) if nothing done\n"
  337. " -q|--quiet be more quiet\n"
  338. " -v|--verbose be more verbose\n"
  339. "\n"
  340. "Retry <schedule> is <item>|/<item>/... where <item> is one of\n"
  341. " -<signal-num>|[-]<signal-name> send that signal\n"
  342. " <timeout> wait that many seconds\n"
  343. " forever repeat remainder forever\n"
  344. "or <schedule> may be just <timeout>, meaning <signal>/<timeout>/KILL/<timeout>\n"
  345. "\n"
  346. "The process scheduler <policy> can be one of:\n"
  347. " other, fifo or rr\n"
  348. "\n"
  349. "The IO scheduler <class> can be one of:\n"
  350. " real-time, best-effort or idle\n"
  351. "\n"
  352. "Exit status: 0 = done 1 = nothing done (=> 0 if --oknodo)\n"
  353. " 3 = trouble 2 = with --retry, processes wouldn't die\n");
  354. }
  355. static void
  356. do_version(void)
  357. {
  358. printf("start-stop-daemon %s for Debian\n\n", VERSION);
  359. printf("Written by Marek Michalkiewicz, public domain.\n");
  360. }
  361. static void DPKG_ATTR_NORET
  362. badusage(const char *msg)
  363. {
  364. if (msg)
  365. fprintf(stderr, "%s: %s\n", progname, msg);
  366. fprintf(stderr, "Try '%s --help' for more information.\n", progname);
  367. exit(3);
  368. }
  369. struct sigpair {
  370. const char *name;
  371. int signal;
  372. };
  373. static const struct sigpair siglist[] = {
  374. { "ABRT", SIGABRT },
  375. { "ALRM", SIGALRM },
  376. { "FPE", SIGFPE },
  377. { "HUP", SIGHUP },
  378. { "ILL", SIGILL },
  379. { "INT", SIGINT },
  380. { "KILL", SIGKILL },
  381. { "PIPE", SIGPIPE },
  382. { "QUIT", SIGQUIT },
  383. { "SEGV", SIGSEGV },
  384. { "TERM", SIGTERM },
  385. { "USR1", SIGUSR1 },
  386. { "USR2", SIGUSR2 },
  387. { "CHLD", SIGCHLD },
  388. { "CONT", SIGCONT },
  389. { "STOP", SIGSTOP },
  390. { "TSTP", SIGTSTP },
  391. { "TTIN", SIGTTIN },
  392. { "TTOU", SIGTTOU }
  393. };
  394. static int
  395. parse_integer(const char *string, int *value_r)
  396. {
  397. unsigned long ul;
  398. char *ep;
  399. if (!string[0])
  400. return -1;
  401. ul = strtoul(string, &ep, 10);
  402. if (string == ep || ul > INT_MAX || *ep != '\0')
  403. return -1;
  404. *value_r = ul;
  405. return 0;
  406. }
  407. static int
  408. parse_signal(const char *sig_str, int *sig_num)
  409. {
  410. unsigned int i;
  411. if (parse_integer(sig_str, sig_num) == 0)
  412. return 0;
  413. for (i = 0; i < array_count(siglist); i++) {
  414. if (strcmp(sig_str, siglist[i].name) == 0) {
  415. *sig_num = siglist[i].signal;
  416. return 0;
  417. }
  418. }
  419. return -1;
  420. }
  421. static int
  422. parse_umask(const char *string, int *value_r)
  423. {
  424. if (!string[0])
  425. return -1;
  426. errno = 0;
  427. *value_r = strtoul(string, NULL, 0);
  428. if (errno)
  429. return -1;
  430. else
  431. return 0;
  432. }
  433. static void
  434. validate_proc_schedule(void)
  435. {
  436. #ifdef _POSIX_PRIORITY_SCHEDULING
  437. int prio_min, prio_max;
  438. prio_min = sched_get_priority_min(proc_sched->policy);
  439. prio_max = sched_get_priority_max(proc_sched->policy);
  440. if (proc_sched->priority < prio_min)
  441. badusage("process scheduler priority less than min");
  442. if (proc_sched->priority > prio_max)
  443. badusage("process scheduler priority greater than max");
  444. #endif
  445. }
  446. static void
  447. parse_proc_schedule(const char *string)
  448. {
  449. char *policy_str, *prio_str;
  450. int prio = 0;
  451. policy_str = xstrdup(string);
  452. policy_str = strtok(policy_str, ":");
  453. prio_str = strtok(NULL, ":");
  454. if (prio_str && parse_integer(prio_str, &prio) != 0)
  455. fatal("invalid process scheduler priority");
  456. proc_sched = xmalloc(sizeof(*proc_sched));
  457. proc_sched->policy_name = policy_str;
  458. if (strcmp(policy_str, "other") == 0) {
  459. proc_sched->policy = SCHED_OTHER;
  460. proc_sched->priority = 0;
  461. } else if (strcmp(policy_str, "fifo") == 0) {
  462. proc_sched->policy = SCHED_FIFO;
  463. proc_sched->priority = prio;
  464. } else if (strcmp(policy_str, "rr") == 0) {
  465. proc_sched->policy = SCHED_RR;
  466. proc_sched->priority = prio;
  467. } else
  468. badusage("invalid process scheduler policy");
  469. validate_proc_schedule();
  470. }
  471. static void
  472. parse_io_schedule(const char *string)
  473. {
  474. char *class_str, *prio_str;
  475. int prio = 4;
  476. class_str = xstrdup(string);
  477. class_str = strtok(class_str, ":");
  478. prio_str = strtok(NULL, ":");
  479. if (prio_str && parse_integer(prio_str, &prio) != 0)
  480. fatal("invalid IO scheduler priority");
  481. io_sched = xmalloc(sizeof(*io_sched));
  482. io_sched->policy_name = class_str;
  483. if (strcmp(class_str, "real-time") == 0) {
  484. io_sched->policy = IOPRIO_CLASS_RT;
  485. io_sched->priority = prio;
  486. } else if (strcmp(class_str, "best-effort") == 0) {
  487. io_sched->policy = IOPRIO_CLASS_BE;
  488. io_sched->priority = prio;
  489. } else if (strcmp(class_str, "idle") == 0) {
  490. io_sched->policy = IOPRIO_CLASS_IDLE;
  491. io_sched->priority = 7;
  492. } else
  493. badusage("invalid IO scheduler policy");
  494. if (io_sched->priority < IO_SCHED_PRIO_MIN)
  495. badusage("IO scheduler priority less than min");
  496. if (io_sched->priority > IO_SCHED_PRIO_MAX)
  497. badusage("IO scheduler priority greater than max");
  498. }
  499. static void
  500. set_proc_schedule(struct res_schedule *sched)
  501. {
  502. #ifdef _POSIX_PRIORITY_SCHEDULING
  503. struct sched_param param;
  504. param.sched_priority = sched->priority;
  505. if (sched_setscheduler(getpid(), sched->policy, &param) == -1)
  506. fatal("Unable to set process scheduler");
  507. #endif
  508. }
  509. #ifdef HAVE_IOPRIO_SET
  510. static inline int
  511. ioprio_set(int which, int who, int ioprio)
  512. {
  513. return syscall(SYS_ioprio_set, which, who, ioprio);
  514. }
  515. #endif
  516. static void
  517. set_io_schedule(struct res_schedule *sched)
  518. {
  519. #ifdef HAVE_IOPRIO_SET
  520. int io_sched_mask;
  521. io_sched_mask = IOPRIO_PRIO_VALUE(sched->policy, sched->priority);
  522. if (ioprio_set(IOPRIO_WHO_PROCESS, getpid(), io_sched_mask) == -1)
  523. warning("Unable to alter IO priority to mask %i (%s)\n",
  524. io_sched_mask, strerror(errno));
  525. #endif
  526. }
  527. static void
  528. parse_schedule_item(const char *string, struct schedule_item *item)
  529. {
  530. const char *after_hyph;
  531. if (!strcmp(string, "forever")) {
  532. item->type = sched_forever;
  533. } else if (isdigit(string[0])) {
  534. item->type = sched_timeout;
  535. if (parse_integer(string, &item->value) != 0)
  536. badusage("invalid timeout value in schedule");
  537. } else if ((after_hyph = string + (string[0] == '-')) &&
  538. parse_signal(after_hyph, &item->value) == 0) {
  539. item->type = sched_signal;
  540. } else {
  541. badusage("invalid schedule item (must be [-]<signal-name>, "
  542. "-<signal-number>, <timeout> or 'forever'");
  543. }
  544. }
  545. static void
  546. parse_schedule(const char *schedule_str)
  547. {
  548. char item_buf[20];
  549. const char *slash;
  550. int count, repeatat;
  551. size_t str_len;
  552. count = 0;
  553. for (slash = schedule_str; *slash; slash++)
  554. if (*slash == '/')
  555. count++;
  556. schedule_length = (count == 0) ? 4 : count + 1;
  557. schedule = xmalloc(sizeof(*schedule) * schedule_length);
  558. if (count == 0) {
  559. schedule[0].type = sched_signal;
  560. schedule[0].value = signal_nr;
  561. parse_schedule_item(schedule_str, &schedule[1]);
  562. if (schedule[1].type != sched_timeout) {
  563. badusage ("--retry takes timeout, or schedule list"
  564. " of at least two items");
  565. }
  566. schedule[2].type = sched_signal;
  567. schedule[2].value = SIGKILL;
  568. schedule[3] = schedule[1];
  569. } else {
  570. count = 0;
  571. repeatat = -1;
  572. while (schedule_str != NULL) {
  573. slash = strchr(schedule_str, '/');
  574. str_len = slash ? (size_t)(slash - schedule_str) : strlen(schedule_str);
  575. if (str_len >= sizeof(item_buf))
  576. badusage("invalid schedule item: far too long"
  577. " (you must delimit items with slashes)");
  578. memcpy(item_buf, schedule_str, str_len);
  579. item_buf[str_len] = '\0';
  580. schedule_str = slash ? slash + 1 : NULL;
  581. parse_schedule_item(item_buf, &schedule[count]);
  582. if (schedule[count].type == sched_forever) {
  583. if (repeatat >= 0)
  584. badusage("invalid schedule: 'forever'"
  585. " appears more than once");
  586. repeatat = count;
  587. continue;
  588. }
  589. count++;
  590. }
  591. if (repeatat >= 0) {
  592. schedule[count].type = sched_goto;
  593. schedule[count].value = repeatat;
  594. count++;
  595. }
  596. assert(count == schedule_length);
  597. }
  598. }
  599. static void
  600. parse_options(int argc, char * const *argv)
  601. {
  602. static struct option longopts[] = {
  603. { "help", 0, NULL, 'H'},
  604. { "stop", 0, NULL, 'K'},
  605. { "start", 0, NULL, 'S'},
  606. { "version", 0, NULL, 'V'},
  607. { "startas", 1, NULL, 'a'},
  608. { "name", 1, NULL, 'n'},
  609. { "oknodo", 0, NULL, 'o'},
  610. { "pidfile", 1, NULL, 'p'},
  611. { "quiet", 0, NULL, 'q'},
  612. { "signal", 1, NULL, 's'},
  613. { "test", 0, NULL, 't'},
  614. { "user", 1, NULL, 'u'},
  615. { "group", 1, NULL, 'g'},
  616. { "chroot", 1, NULL, 'r'},
  617. { "verbose", 0, NULL, 'v'},
  618. { "exec", 1, NULL, 'x'},
  619. { "chuid", 1, NULL, 'c'},
  620. { "nicelevel", 1, NULL, 'N'},
  621. { "procsched", 1, NULL, 'P'},
  622. { "iosched", 1, NULL, 'I'},
  623. { "umask", 1, NULL, 'k'},
  624. { "background", 0, NULL, 'b'},
  625. { "make-pidfile", 0, NULL, 'm'},
  626. { "retry", 1, NULL, 'R'},
  627. { "chdir", 1, NULL, 'd'},
  628. { NULL, 0, NULL, 0 }
  629. };
  630. const char *umask_str = NULL;
  631. const char *signal_str = NULL;
  632. const char *schedule_str = NULL;
  633. const char *proc_schedule_str = NULL;
  634. const char *io_schedule_str = NULL;
  635. int c;
  636. for (;;) {
  637. c = getopt_long(argc, argv,
  638. "HKSVa:n:op:qr:s:tu:vx:c:N:P:I:k:bmR:g:d:",
  639. longopts, NULL);
  640. if (c == -1)
  641. break;
  642. switch (c) {
  643. case 'H': /* --help */
  644. do_help();
  645. exit(0);
  646. case 'K': /* --stop */
  647. stop = 1;
  648. break;
  649. case 'S': /* --start */
  650. start = 1;
  651. break;
  652. case 'V': /* --version */
  653. do_version();
  654. exit(0);
  655. case 'a': /* --startas <pathname> */
  656. startas = optarg;
  657. break;
  658. case 'n': /* --name <process-name> */
  659. cmdname = optarg;
  660. break;
  661. case 'o': /* --oknodo */
  662. exitnodo = 0;
  663. break;
  664. case 'p': /* --pidfile <pid-file> */
  665. pidfile = optarg;
  666. break;
  667. case 'q': /* --quiet */
  668. quietmode = 1;
  669. break;
  670. case 's': /* --signal <signal> */
  671. signal_str = optarg;
  672. break;
  673. case 't': /* --test */
  674. testmode = 1;
  675. break;
  676. case 'u': /* --user <username>|<uid> */
  677. userspec = optarg;
  678. break;
  679. case 'v': /* --verbose */
  680. quietmode = -1;
  681. break;
  682. case 'x': /* --exec <executable> */
  683. execname = optarg;
  684. break;
  685. case 'c': /* --chuid <username>|<uid> */
  686. /* we copy the string just in case we need the
  687. * argument later. */
  688. changeuser = xstrdup(optarg);
  689. changeuser = strtok(changeuser, ":");
  690. changegroup = strtok(NULL, ":");
  691. break;
  692. case 'g': /* --group <group>|<gid> */
  693. changegroup = optarg;
  694. break;
  695. case 'r': /* --chroot /new/root */
  696. changeroot = optarg;
  697. break;
  698. case 'N': /* --nice */
  699. nicelevel = atoi(optarg);
  700. break;
  701. case 'P': /* --procsched */
  702. proc_schedule_str = optarg;
  703. break;
  704. case 'I': /* --iosched */
  705. io_schedule_str = optarg;
  706. break;
  707. case 'k': /* --umask <mask> */
  708. umask_str = optarg;
  709. break;
  710. case 'b': /* --background */
  711. background = 1;
  712. break;
  713. case 'm': /* --make-pidfile */
  714. mpidfile = 1;
  715. break;
  716. case 'R': /* --retry <schedule>|<timeout> */
  717. schedule_str = optarg;
  718. break;
  719. case 'd': /* --chdir /new/dir */
  720. changedir = optarg;
  721. break;
  722. default:
  723. /* Message printed by getopt. */
  724. badusage(NULL);
  725. }
  726. }
  727. if (signal_str != NULL) {
  728. if (parse_signal(signal_str, &signal_nr) != 0)
  729. badusage("signal value must be numeric or name"
  730. " of signal (KILL, INT, ...)");
  731. }
  732. if (schedule_str != NULL) {
  733. parse_schedule(schedule_str);
  734. }
  735. if (proc_schedule_str != NULL)
  736. parse_proc_schedule(proc_schedule_str);
  737. if (io_schedule_str != NULL)
  738. parse_io_schedule(io_schedule_str);
  739. if (umask_str != NULL) {
  740. if (parse_umask(umask_str, &umask_value) != 0)
  741. badusage("umask value must be a positive number");
  742. }
  743. if (start == stop)
  744. badusage("need one of --start or --stop");
  745. if (!execname && !pidfile && !userspec && !cmdname)
  746. badusage("need at least one of --exec, --pidfile, --user or --name");
  747. #ifdef PROCESS_NAME_SIZE
  748. if (cmdname && strlen(cmdname) > PROCESS_NAME_SIZE)
  749. warning("this system is not able to track process names\n"
  750. "longer than %d characters, please use --exec "
  751. "instead of --name.\n", PROCESS_NAME_SIZE);
  752. #endif
  753. if (!startas)
  754. startas = execname;
  755. if (start && !startas)
  756. badusage("--start needs --exec or --startas");
  757. if (mpidfile && pidfile == NULL)
  758. badusage("--make-pidfile requires --pidfile");
  759. if (background && !start)
  760. badusage("--background is only relevant with --start");
  761. }
  762. #if defined(OSHurd)
  763. static void
  764. init_procset(void)
  765. {
  766. struct ps_context *context;
  767. error_t err;
  768. err = ps_context_create(getproc(), &context);
  769. if (err)
  770. error(1, err, "ps_context_create");
  771. err = proc_stat_list_create(context, &procset);
  772. if (err)
  773. error(1, err, "proc_stat_list_create");
  774. err = proc_stat_list_add_all(procset, 0, 0);
  775. if (err)
  776. error(1, err, "proc_stat_list_add_all");
  777. }
  778. static struct proc_stat *
  779. get_proc_stat (pid_t pid, ps_flags_t flags)
  780. {
  781. struct proc_stat *ps;
  782. ps_flags_t wanted_flags = PSTAT_PID | flags;
  783. if (!procset)
  784. init_procset();
  785. ps = proc_stat_list_pid_proc_stat(procset, pid);
  786. if (!ps)
  787. return NULL;
  788. if (proc_stat_set_flags(ps, wanted_flags))
  789. return NULL;
  790. if ((proc_stat_flags(ps) & wanted_flags) != wanted_flags)
  791. return NULL;
  792. return ps;
  793. }
  794. #endif
  795. #if defined(OSLinux)
  796. static bool
  797. pid_is_exec(pid_t pid, const struct stat *esb)
  798. {
  799. char lname[32];
  800. char lcontents[_POSIX_PATH_MAX];
  801. const char deleted[] = " (deleted)";
  802. int nread;
  803. struct stat sb;
  804. sprintf(lname, "/proc/%d/exe", pid);
  805. nread = readlink(lname, lcontents, sizeof(lcontents));
  806. if (nread == -1)
  807. return false;
  808. lcontents[nread] = '\0';
  809. if (strcmp(lcontents + nread - strlen(deleted), deleted) == 0)
  810. lcontents[nread - strlen(deleted)] = '\0';
  811. if (stat(lcontents, &sb) != 0)
  812. return false;
  813. return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  814. }
  815. #elif defined(OShpux)
  816. static bool
  817. pid_is_exec(pid_t pid, const struct stat *esb)
  818. {
  819. struct pst_status pst;
  820. if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
  821. return false;
  822. return ((dev_t)pst.pst_text.psf_fsid.psfs_id == esb->st_dev &&
  823. (ino_t)pst.pst_text.psf_fileid == esb->st_ino);
  824. }
  825. #elif defined(HAVE_KVM_H)
  826. static bool
  827. pid_is_exec(pid_t pid, const char *name)
  828. {
  829. kvm_t *kd;
  830. int nentries;
  831. struct kinfo_proc *kp;
  832. char errbuf[_POSIX2_LINE_MAX], *pidexec;
  833. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  834. if (kd == NULL)
  835. errx(1, "%s", errbuf);
  836. kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries);
  837. if (kp == NULL)
  838. errx(1, "%s", kvm_geterr(kd));
  839. pidexec = (&kp->kp_proc)->p_comm;
  840. if (strlen(name) != strlen(pidexec))
  841. return false;
  842. return (strcmp(name, pidexec) == 0) ? 1 : 0;
  843. }
  844. #endif
  845. #if defined(OSLinux)
  846. static bool
  847. pid_is_user(pid_t pid, uid_t uid)
  848. {
  849. struct stat sb;
  850. char buf[32];
  851. sprintf(buf, "/proc/%d", pid);
  852. if (stat(buf, &sb) != 0)
  853. return false;
  854. return (sb.st_uid == uid);
  855. }
  856. #elif defined(OSHurd)
  857. static bool
  858. pid_is_user(pid_t pid, uid_t uid)
  859. {
  860. struct proc_stat *ps;
  861. ps = get_proc_stat(pid, PSTAT_OWNER_UID);
  862. return ps && proc_stat_owner_uid(ps) == uid;
  863. }
  864. #elif defined(OShpux)
  865. static bool
  866. pid_is_user(pid_t pid, uid_t uid)
  867. {
  868. struct pst_status pst;
  869. if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
  870. return false;
  871. return ((uid_t)pst.pst_uid == uid);
  872. }
  873. #elif defined(HAVE_KVM_H)
  874. static bool
  875. pid_is_user(pid_t pid, uid_t uid)
  876. {
  877. kvm_t *kd;
  878. int nentries; /* Value not used. */
  879. uid_t proc_uid;
  880. struct kinfo_proc *kp;
  881. char errbuf[_POSIX2_LINE_MAX];
  882. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  883. if (kd == NULL)
  884. errx(1, "%s", errbuf);
  885. kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries);
  886. if (kp == NULL)
  887. errx(1, "%s", kvm_geterr(kd));
  888. if (kp->kp_proc.p_cred)
  889. kvm_read(kd, (u_long)&(kp->kp_proc.p_cred->p_ruid),
  890. &proc_uid, sizeof(uid_t));
  891. else
  892. return false;
  893. return (proc_uid == (uid_t)uid);
  894. }
  895. #endif
  896. #if defined(OSLinux)
  897. static bool
  898. pid_is_cmd(pid_t pid, const char *name)
  899. {
  900. char buf[32];
  901. FILE *f;
  902. int c;
  903. sprintf(buf, "/proc/%d/stat", pid);
  904. f = fopen(buf, "r");
  905. if (!f)
  906. return false;
  907. while ((c = getc(f)) != EOF && c != '(')
  908. ;
  909. if (c != '(') {
  910. fclose(f);
  911. return false;
  912. }
  913. /* This hopefully handles command names containing ')'. */
  914. while ((c = getc(f)) != EOF && c == *name)
  915. name++;
  916. fclose(f);
  917. return (c == ')' && *name == '\0');
  918. }
  919. #elif defined(OSHurd)
  920. static bool
  921. pid_is_cmd(pid_t pid, const char *name)
  922. {
  923. struct proc_stat *ps;
  924. ps = get_proc_stat(pid, PSTAT_ARGS);
  925. return ps && !strcmp(proc_stat_args(ps), name);
  926. }
  927. #elif defined(OShpux)
  928. static bool
  929. pid_is_cmd(pid_t pid, const char *name)
  930. {
  931. struct pst_status pst;
  932. if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
  933. return false;
  934. return (strcmp(pst.pst_ucomm, name) == 0);
  935. }
  936. #elif defined(HAVE_KVM_H)
  937. static bool
  938. pid_is_cmd(pid_t pid, const char *name)
  939. {
  940. kvm_t *kd;
  941. int nentries, argv_len = 0;
  942. struct kinfo_proc *kp;
  943. char errbuf[_POSIX2_LINE_MAX], buf[_POSIX2_LINE_MAX];
  944. char **pid_argv_p;
  945. char *start_argv_0_p, *end_argv_0_p;
  946. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  947. if (kd == NULL)
  948. errx(1, "%s", errbuf);
  949. kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries);
  950. if (kp == NULL)
  951. errx(1, "%s", kvm_geterr(kd));
  952. pid_argv_p = kvm_getargv(kd, kp, argv_len);
  953. if (pid_argv_p == NULL)
  954. errx(1, "%s", kvm_geterr(kd));
  955. start_argv_0_p = *pid_argv_p;
  956. /* Find and compare string. */
  957. /* Find end of argv[0] then copy and cut of str there. */
  958. end_argv_0_p = strchr(*pid_argv_p, ' ');
  959. if (end_argv_0_p == NULL)
  960. /* There seems to be no space, so we have the command
  961. * allready in its desired form. */
  962. start_argv_0_p = *pid_argv_p;
  963. else {
  964. /* Tests indicate that this never happens, since
  965. * kvm_getargv itself cuts of tailing stuff. This is
  966. * not what the manpage says, however. */
  967. strncpy(buf, *pid_argv_p, (end_argv_0_p - start_argv_0_p));
  968. buf[(end_argv_0_p - start_argv_0_p) + 1] = '\0';
  969. start_argv_0_p = buf;
  970. }
  971. if (strlen(name) != strlen(start_argv_0_p))
  972. return false;
  973. return (strcmp(name, start_argv_0_p) == 0) ? 1 : 0;
  974. }
  975. #endif
  976. #if defined(OSHurd)
  977. static bool
  978. pid_is_running(pid_t pid)
  979. {
  980. return get_proc_stat(pid, 0) != NULL;
  981. }
  982. #else /* !OSHurd */
  983. static bool
  984. pid_is_running(pid_t pid)
  985. {
  986. if (kill(pid, 0) == 0 || errno == EPERM)
  987. return true;
  988. else if (errno == ESRCH)
  989. return false;
  990. else
  991. fatal("Error checking pid %u status: %s", pid, strerror(errno));
  992. }
  993. #endif
  994. static void
  995. check(pid_t pid)
  996. {
  997. #if defined(OSLinux) || defined(OShpux)
  998. if (execname && !pid_is_exec(pid, &exec_stat))
  999. return;
  1000. #elif defined(HAVE_KVM_H)
  1001. if (execname && !pid_is_exec(pid, execname))
  1002. return;
  1003. #elif defined(OSHurd) || defined(OSFreeBSD) || defined(OSNetBSD)
  1004. /* Let's try this to see if it works. */
  1005. if (execname && !pid_is_cmd(pid, execname))
  1006. return;
  1007. #endif
  1008. if (userspec && !pid_is_user(pid, user_id))
  1009. return;
  1010. if (cmdname && !pid_is_cmd(pid, cmdname))
  1011. return;
  1012. if (start && !pid_is_running(pid))
  1013. return;
  1014. push(&found, pid);
  1015. }
  1016. static void
  1017. do_pidfile(const char *name)
  1018. {
  1019. FILE *f;
  1020. static pid_t pid = 0;
  1021. if (pid) {
  1022. check(pid);
  1023. return;
  1024. }
  1025. f = fopen(name, "r");
  1026. if (f) {
  1027. if (fscanf(f, "%d", &pid) == 1)
  1028. check(pid);
  1029. fclose(f);
  1030. } else if (errno != ENOENT)
  1031. fatal("open pidfile %s: %s", name, strerror(errno));
  1032. }
  1033. #if defined(OSLinux) || defined (OSsunos)
  1034. static void
  1035. do_procinit(void)
  1036. {
  1037. DIR *procdir;
  1038. struct dirent *entry;
  1039. int foundany;
  1040. pid_t pid;
  1041. procdir = opendir("/proc");
  1042. if (!procdir)
  1043. fatal("opendir /proc: %s", strerror(errno));
  1044. foundany = 0;
  1045. while ((entry = readdir(procdir)) != NULL) {
  1046. if (sscanf(entry->d_name, "%d", &pid) != 1)
  1047. continue;
  1048. foundany++;
  1049. check(pid);
  1050. }
  1051. closedir(procdir);
  1052. if (!foundany)
  1053. fatal("nothing in /proc - not mounted?");
  1054. }
  1055. #elif defined(OSHurd)
  1056. static int
  1057. check_proc_stat(struct proc_stat *ps)
  1058. {
  1059. check(ps->pid);
  1060. return 0;
  1061. }
  1062. static void
  1063. do_procinit(void)
  1064. {
  1065. if (!procset)
  1066. init_procset();
  1067. proc_stat_list_for_each(procset, check_proc_stat);
  1068. }
  1069. #elif defined(OShpux)
  1070. static void
  1071. do_procinit(void)
  1072. {
  1073. struct pst_status pst[10];
  1074. int i, count;
  1075. int idx = 0;
  1076. while ((count = pstat_getproc(pst, sizeof(pst[0]), 10, idx)) > 0) {
  1077. for (i = 0; i < count; i++)
  1078. check(pst[i].pst_pid);
  1079. idx = pst[count - 1].pst_idx + 1;
  1080. }
  1081. }
  1082. #elif defined(HAVE_KVM_H)
  1083. static void
  1084. do_procinit(void)
  1085. {
  1086. /* Nothing to do. */
  1087. }
  1088. #endif
  1089. static void
  1090. do_findprocs(void)
  1091. {
  1092. clear(&found);
  1093. if (pidfile)
  1094. do_pidfile(pidfile);
  1095. else
  1096. do_procinit();
  1097. }
  1098. static void
  1099. do_stop(int sig_num, int quiet, int *n_killed, int *n_notkilled, int retry_nr)
  1100. {
  1101. struct pid_list *p;
  1102. do_findprocs();
  1103. *n_killed = 0;
  1104. *n_notkilled = 0;
  1105. if (!found)
  1106. return;
  1107. clear(&killed);
  1108. for (p = found; p; p = p->next) {
  1109. if (testmode) {
  1110. if (quietmode <= 0)
  1111. printf("Would send signal %d to %d.\n",
  1112. sig_num, p->pid);
  1113. (*n_killed)++;
  1114. } else if (kill(p->pid, sig_num) == 0) {
  1115. push(&killed, p->pid);
  1116. (*n_killed)++;
  1117. } else {
  1118. if (sig_num)
  1119. warning("failed to kill %d: %s\n",
  1120. p->pid, strerror(errno));
  1121. (*n_notkilled)++;
  1122. }
  1123. }
  1124. if (quietmode < 0 && killed) {
  1125. printf("Stopped %s (pid", what_stop);
  1126. for (p = killed; p; p = p->next)
  1127. printf(" %d", p->pid);
  1128. putchar(')');
  1129. if (retry_nr > 0)
  1130. printf(", retry #%d", retry_nr);
  1131. printf(".\n");
  1132. }
  1133. }
  1134. static void
  1135. set_what_stop(const char *str)
  1136. {
  1137. strncpy(what_stop, str, sizeof(what_stop));
  1138. what_stop[sizeof(what_stop) - 1] = '\0';
  1139. }
  1140. static int
  1141. run_stop_schedule(void)
  1142. {
  1143. int r, position, n_killed, n_notkilled, value, ratio, anykilled, retry_nr;
  1144. struct timeval stopat, before, after, interval, maxinterval;
  1145. if (testmode) {
  1146. if (schedule != NULL) {
  1147. if (quietmode <= 0)
  1148. printf("Ignoring --retry in test mode\n");
  1149. schedule = NULL;
  1150. }
  1151. }
  1152. if (cmdname)
  1153. set_what_stop(cmdname);
  1154. else if (execname)
  1155. set_what_stop(execname);
  1156. else if (pidfile)
  1157. sprintf(what_stop, "process in pidfile '%.200s'", pidfile);
  1158. else if (userspec)
  1159. sprintf(what_stop, "process(es) owned by '%.200s'", userspec);
  1160. else
  1161. fatal("internal error, please report");
  1162. anykilled = 0;
  1163. retry_nr = 0;
  1164. if (schedule == NULL) {
  1165. do_stop(signal_nr, quietmode, &n_killed, &n_notkilled, 0);
  1166. if (n_notkilled > 0 && quietmode <= 0)
  1167. printf("%d pids were not killed\n", n_notkilled);
  1168. if (n_killed)
  1169. anykilled = 1;
  1170. goto x_finished;
  1171. }
  1172. for (position = 0; position < schedule_length; ) {
  1173. value = schedule[position].value;
  1174. n_notkilled = 0;
  1175. switch (schedule[position].type) {
  1176. case sched_goto:
  1177. position = value;
  1178. continue;
  1179. case sched_signal:
  1180. do_stop(value, quietmode, &n_killed, &n_notkilled, retry_nr++);
  1181. if (!n_killed)
  1182. goto x_finished;
  1183. else
  1184. anykilled = 1;
  1185. goto next_item;
  1186. case sched_timeout:
  1187. /* We want to keep polling for the processes, to see if they've exited,
  1188. * or until the timeout expires.
  1189. *
  1190. * This is a somewhat complicated algorithm to try to ensure that we
  1191. * notice reasonably quickly when all the processes have exited, but
  1192. * don't spend too much CPU time polling. In particular, on a fast
  1193. * machine with quick-exiting daemons we don't want to delay system
  1194. * shutdown too much, whereas on a slow one, or where processes are
  1195. * taking some time to exit, we want to increase the polling
  1196. * interval.
  1197. *
  1198. * The algorithm is as follows: we measure the elapsed time it takes
  1199. * to do one poll(), and wait a multiple of this time for the next
  1200. * poll. However, if that would put us past the end of the timeout
  1201. * period we wait only as long as the timeout period, but in any case
  1202. * we always wait at least MIN_POLL_INTERVAL (20ms). The multiple
  1203. * (‘ratio’) starts out as 2, and increases by 1 for each poll to a
  1204. * maximum of 10; so we use up to between 30% and 10% of the
  1205. * machine's resources (assuming a few reasonable things about system
  1206. * performance).
  1207. */
  1208. xgettimeofday(&stopat);
  1209. stopat.tv_sec += value;
  1210. ratio = 1;
  1211. for (;;) {
  1212. xgettimeofday(&before);
  1213. if (timercmp(&before, &stopat, >))
  1214. goto next_item;
  1215. do_stop(0, 1, &n_killed, &n_notkilled, 0);
  1216. if (!n_killed)
  1217. goto x_finished;
  1218. xgettimeofday(&after);
  1219. if (!timercmp(&after, &stopat, <))
  1220. goto next_item;
  1221. if (ratio < 10)
  1222. ratio++;
  1223. timersub(&stopat, &after, &maxinterval);
  1224. timersub(&after, &before, &interval);
  1225. tmul(&interval, ratio);
  1226. if (interval.tv_sec < 0 || interval.tv_usec < 0)
  1227. interval.tv_sec = interval.tv_usec = 0;
  1228. if (timercmp(&interval, &maxinterval, >))
  1229. interval = maxinterval;
  1230. if (interval.tv_sec == 0 &&
  1231. interval.tv_usec <= MIN_POLL_INTERVAL)
  1232. interval.tv_usec = MIN_POLL_INTERVAL;
  1233. r = select(0, NULL, NULL, NULL, &interval);
  1234. if (r < 0 && errno != EINTR)
  1235. fatal("select() failed for pause: %s",
  1236. strerror(errno));
  1237. }
  1238. default:
  1239. assert(!"schedule[].type value must be valid");
  1240. }
  1241. next_item:
  1242. position++;
  1243. }
  1244. if (quietmode <= 0)
  1245. printf("Program %s, %d process(es), refused to die.\n",
  1246. what_stop, n_killed);
  1247. return 2;
  1248. x_finished:
  1249. if (!anykilled) {
  1250. if (quietmode <= 0)
  1251. printf("No %s found running; none killed.\n", what_stop);
  1252. return exitnodo;
  1253. } else {
  1254. return 0;
  1255. }
  1256. }
  1257. int
  1258. main(int argc, char **argv)
  1259. {
  1260. int devnull_fd = -1;
  1261. gid_t rgid;
  1262. uid_t ruid;
  1263. #ifdef HAVE_TIOCNOTTY
  1264. int tty_fd = -1;
  1265. #endif
  1266. progname = argv[0];
  1267. parse_options(argc, argv);
  1268. argc -= optind;
  1269. argv += optind;
  1270. if (execname) {
  1271. char *fullexecname;
  1272. if (changeroot) {
  1273. int fullexecname_len = strlen(changeroot) + 1 +
  1274. strlen(execname) + 1;
  1275. fullexecname = xmalloc(fullexecname_len);
  1276. snprintf(fullexecname, fullexecname_len, "%s/%s",
  1277. changeroot, execname);
  1278. } else
  1279. fullexecname = execname;
  1280. if (stat(fullexecname, &exec_stat))
  1281. fatal("stat %s: %s", fullexecname, strerror(errno));
  1282. if (fullexecname != execname)
  1283. free(fullexecname);
  1284. }
  1285. if (userspec && sscanf(userspec, "%d", &user_id) != 1) {
  1286. struct passwd *pw;
  1287. pw = getpwnam(userspec);
  1288. if (!pw)
  1289. fatal("user '%s' not found\n", userspec);
  1290. user_id = pw->pw_uid;
  1291. }
  1292. if (changegroup && sscanf(changegroup, "%d", &runas_gid) != 1) {
  1293. struct group *gr = getgrnam(changegroup);
  1294. if (!gr)
  1295. fatal("group '%s' not found\n", changegroup);
  1296. runas_gid = gr->gr_gid;
  1297. }
  1298. if (changeuser) {
  1299. struct passwd *pw;
  1300. struct stat st;
  1301. if (sscanf(changeuser, "%d", &runas_uid) == 1)
  1302. pw = getpwuid(runas_uid);
  1303. else
  1304. pw = getpwnam(changeuser);
  1305. if (!pw)
  1306. fatal("user '%s' not found\n", changeuser);
  1307. runas_uid = pw->pw_uid;
  1308. if (changegroup == NULL) {
  1309. /* Pass the default group of this user. */
  1310. changegroup = ""; /* Just empty. */
  1311. runas_gid = pw->pw_gid;
  1312. }
  1313. if (stat(pw->pw_dir, &st) == 0)
  1314. setenv("HOME", pw->pw_dir, 1);
  1315. }
  1316. if (stop) {
  1317. int i = run_stop_schedule();
  1318. exit(i);
  1319. }
  1320. do_findprocs();
  1321. if (found) {
  1322. if (quietmode <= 0)
  1323. printf("%s already running.\n", execname ? execname : "process");
  1324. exit(exitnodo);
  1325. }
  1326. if (testmode && quietmode <= 0) {
  1327. printf("Would start %s ", startas);
  1328. while (argc-- > 0)
  1329. printf("%s ", *argv++);
  1330. if (changeuser != NULL) {
  1331. printf(" (as user %s[%d]", changeuser, runas_uid);
  1332. if (changegroup != NULL)
  1333. printf(", and group %s[%d])", changegroup, runas_gid);
  1334. else
  1335. printf(")");
  1336. }
  1337. if (changeroot != NULL)
  1338. printf(" in directory %s", changeroot);
  1339. if (nicelevel)
  1340. printf(", and add %i to the priority", nicelevel);
  1341. if (proc_sched)
  1342. printf(", with scheduling policy %s with priority %i",
  1343. proc_sched->policy_name, proc_sched->priority);
  1344. if (io_sched)
  1345. printf(", with IO scheduling class %s with priority %i",
  1346. io_sched->policy_name, io_sched->priority);
  1347. printf(".\n");
  1348. }
  1349. if (testmode)
  1350. exit(0);
  1351. if (quietmode < 0)
  1352. printf("Starting %s...\n", startas);
  1353. *--argv = startas;
  1354. if (background) {
  1355. /* Ok, we need to detach this process. */
  1356. daemonize();
  1357. #ifdef HAVE_TIOCNOTTY
  1358. tty_fd = open("/dev/tty", O_RDWR);
  1359. #endif
  1360. devnull_fd = open("/dev/null", O_RDWR);
  1361. }
  1362. if (nicelevel) {
  1363. errno = 0;
  1364. if ((nice(nicelevel) == -1) && (errno != 0))
  1365. fatal("Unable to alter nice level by %i: %s",
  1366. nicelevel, strerror(errno));
  1367. }
  1368. if (proc_sched)
  1369. set_proc_schedule(proc_sched);
  1370. if (io_sched)
  1371. set_io_schedule(io_sched);
  1372. if (umask_value >= 0)
  1373. umask(umask_value);
  1374. if (mpidfile && pidfile != NULL) {
  1375. /* User wants _us_ to make the pidfile. :) */
  1376. FILE *pidf = fopen(pidfile, "w");
  1377. pid_t pidt = getpid();
  1378. if (pidf == NULL)
  1379. fatal("Unable to open pidfile '%s' for writing: %s",
  1380. pidfile, strerror(errno));
  1381. fprintf(pidf, "%d\n", pidt);
  1382. fclose(pidf);
  1383. }
  1384. if (changeroot != NULL) {
  1385. if (chdir(changeroot) < 0)
  1386. fatal("Unable to chdir() to %s", changeroot);
  1387. if (chroot(changeroot) < 0)
  1388. fatal("Unable to chroot() to %s", changeroot);
  1389. }
  1390. if (chdir(changedir) < 0)
  1391. fatal("Unable to chdir() to %s", changedir);
  1392. rgid = getgid();
  1393. ruid = getuid();
  1394. if (changegroup != NULL) {
  1395. if (rgid != (gid_t)runas_gid)
  1396. if (setgid(runas_gid))
  1397. fatal("Unable to set gid to %d", runas_gid);
  1398. }
  1399. if (changeuser != NULL) {
  1400. /* We assume that if our real user and group are the same as
  1401. * the ones we should switch to, the supplementary groups
  1402. * will be already in place. */
  1403. if (rgid != (gid_t)runas_gid || ruid != (uid_t)runas_uid)
  1404. if (initgroups(changeuser, runas_gid))
  1405. fatal("Unable to set initgroups() with gid %d",
  1406. runas_gid);
  1407. if (ruid != (uid_t)runas_uid)
  1408. if (setuid(runas_uid))
  1409. fatal("Unable to set uid to %s", changeuser);
  1410. }
  1411. if (background) {
  1412. /* Continue background setup. */
  1413. int i;
  1414. #ifdef HAVE_TIOCNOTTY
  1415. /* Change tty. */
  1416. ioctl(tty_fd, TIOCNOTTY, 0);
  1417. close(tty_fd);
  1418. #endif
  1419. if (umask_value < 0)
  1420. umask(022); /* Set a default for dumb programs. */
  1421. dup2(devnull_fd, 0); /* stdin */
  1422. dup2(devnull_fd, 1); /* stdout */
  1423. dup2(devnull_fd, 2); /* stderr */
  1424. /* Now close all extra fds. */
  1425. for (i = get_open_fd_max() - 1; i >= 3; --i)
  1426. close(i);
  1427. }
  1428. execv(startas, argv);
  1429. fatal("Unable to start %s: %s", startas, strerror(errno));
  1430. }