start-stop-daemon.c 42 KB

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