start-stop-daemon.c 38 KB

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