start-stop-daemon.c 38 KB

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