start-stop-daemon.c 41 KB

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