start-stop-daemon.c 40 KB

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