start-stop-daemon.c 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890
  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. #define OPT_PID 500
  690. static void
  691. parse_options(int argc, char * const *argv)
  692. {
  693. static struct option longopts[] = {
  694. { "help", 0, NULL, 'H'},
  695. { "stop", 0, NULL, 'K'},
  696. { "start", 0, NULL, 'S'},
  697. { "status", 0, NULL, 'T'},
  698. { "version", 0, NULL, 'V'},
  699. { "startas", 1, NULL, 'a'},
  700. { "name", 1, NULL, 'n'},
  701. { "oknodo", 0, NULL, 'o'},
  702. { "pid", 1, NULL, OPT_PID},
  703. { "pidfile", 1, NULL, 'p'},
  704. { "quiet", 0, NULL, 'q'},
  705. { "signal", 1, NULL, 's'},
  706. { "test", 0, NULL, 't'},
  707. { "user", 1, NULL, 'u'},
  708. { "group", 1, NULL, 'g'},
  709. { "chroot", 1, NULL, 'r'},
  710. { "verbose", 0, NULL, 'v'},
  711. { "exec", 1, NULL, 'x'},
  712. { "chuid", 1, NULL, 'c'},
  713. { "nicelevel", 1, NULL, 'N'},
  714. { "procsched", 1, NULL, 'P'},
  715. { "iosched", 1, NULL, 'I'},
  716. { "umask", 1, NULL, 'k'},
  717. { "background", 0, NULL, 'b'},
  718. { "no-close", 0, NULL, 'C'},
  719. { "make-pidfile", 0, NULL, 'm'},
  720. { "retry", 1, NULL, 'R'},
  721. { "chdir", 1, NULL, 'd'},
  722. { NULL, 0, NULL, 0 }
  723. };
  724. const char *pid_str = NULL;
  725. const char *umask_str = NULL;
  726. const char *signal_str = NULL;
  727. const char *schedule_str = NULL;
  728. const char *proc_schedule_str = NULL;
  729. const char *io_schedule_str = NULL;
  730. int c;
  731. for (;;) {
  732. c = getopt_long(argc, argv,
  733. "HKSVTa:n:op:qr:s:tu:vx:c:N:P:I:k:bCmR:g:d:",
  734. longopts, NULL);
  735. if (c == -1)
  736. break;
  737. switch (c) {
  738. case 'H': /* --help */
  739. usage();
  740. exit(0);
  741. case 'K': /* --stop */
  742. set_action(action_stop);
  743. break;
  744. case 'S': /* --start */
  745. set_action(action_start);
  746. break;
  747. case 'T': /* --status */
  748. set_action(action_status);
  749. break;
  750. case 'V': /* --version */
  751. do_version();
  752. exit(0);
  753. case 'a': /* --startas <pathname> */
  754. startas = optarg;
  755. break;
  756. case 'n': /* --name <process-name> */
  757. cmdname = optarg;
  758. break;
  759. case 'o': /* --oknodo */
  760. exitnodo = 0;
  761. break;
  762. case OPT_PID: /* --pid <pid> */
  763. pid_str = optarg;
  764. break;
  765. case 'p': /* --pidfile <pid-file> */
  766. pidfile = optarg;
  767. break;
  768. case 'q': /* --quiet */
  769. quietmode = true;
  770. break;
  771. case 's': /* --signal <signal> */
  772. signal_str = optarg;
  773. break;
  774. case 't': /* --test */
  775. testmode = true;
  776. break;
  777. case 'u': /* --user <username>|<uid> */
  778. userspec = optarg;
  779. break;
  780. case 'v': /* --verbose */
  781. quietmode = -1;
  782. break;
  783. case 'x': /* --exec <executable> */
  784. execname = optarg;
  785. break;
  786. case 'c': /* --chuid <username>|<uid> */
  787. /* We copy the string just in case we need the
  788. * argument later. */
  789. changeuser = xstrdup(optarg);
  790. changeuser = strtok(changeuser, ":");
  791. changegroup = strtok(NULL, ":");
  792. break;
  793. case 'g': /* --group <group>|<gid> */
  794. changegroup = optarg;
  795. break;
  796. case 'r': /* --chroot /new/root */
  797. changeroot = optarg;
  798. break;
  799. case 'N': /* --nice */
  800. nicelevel = atoi(optarg);
  801. break;
  802. case 'P': /* --procsched */
  803. proc_schedule_str = optarg;
  804. break;
  805. case 'I': /* --iosched */
  806. io_schedule_str = optarg;
  807. break;
  808. case 'k': /* --umask <mask> */
  809. umask_str = optarg;
  810. break;
  811. case 'b': /* --background */
  812. background = true;
  813. break;
  814. case 'C': /* --no-close */
  815. close_io = false;
  816. break;
  817. case 'm': /* --make-pidfile */
  818. mpidfile = true;
  819. break;
  820. case 'R': /* --retry <schedule>|<timeout> */
  821. schedule_str = optarg;
  822. break;
  823. case 'd': /* --chdir /new/dir */
  824. changedir = optarg;
  825. break;
  826. default:
  827. /* Message printed by getopt. */
  828. badusage(NULL);
  829. }
  830. }
  831. if (pid_str != NULL) {
  832. if (parse_pid(pid_str, &match_pid) != 0)
  833. badusage("pid value must be a number greater than 0");
  834. }
  835. if (signal_str != NULL) {
  836. if (parse_signal(signal_str, &signal_nr) != 0)
  837. badusage("signal value must be numeric or name"
  838. " of signal (KILL, INT, ...)");
  839. }
  840. if (schedule_str != NULL) {
  841. parse_schedule(schedule_str);
  842. }
  843. if (proc_schedule_str != NULL)
  844. parse_proc_schedule(proc_schedule_str);
  845. if (io_schedule_str != NULL)
  846. parse_io_schedule(io_schedule_str);
  847. if (umask_str != NULL) {
  848. if (parse_umask(umask_str, &umask_value) != 0)
  849. badusage("umask value must be a positive number");
  850. }
  851. if (action == action_none)
  852. badusage("need one of --start or --stop or --status");
  853. if (!execname && !pid_str && !pidfile && !userspec && !cmdname)
  854. badusage("need at least one of --exec, --pid, --pidfile, --user or --name");
  855. #ifdef PROCESS_NAME_SIZE
  856. if (cmdname && strlen(cmdname) > PROCESS_NAME_SIZE)
  857. warning("this system is not able to track process names\n"
  858. "longer than %d characters, please use --exec "
  859. "instead of --name.\n", PROCESS_NAME_SIZE);
  860. #endif
  861. if (!startas)
  862. startas = execname;
  863. if (action == action_start && !startas)
  864. badusage("--start needs --exec or --startas");
  865. if (mpidfile && pidfile == NULL)
  866. badusage("--make-pidfile requires --pidfile");
  867. if (pid_str && pidfile)
  868. badusage("need either --pid of --pidfile, not both");
  869. if (background && action != action_start)
  870. badusage("--background is only relevant with --start");
  871. if (!close_io && !background)
  872. badusage("--no-close is only relevant with --background");
  873. }
  874. static void
  875. setup_options(void)
  876. {
  877. if (execname) {
  878. char *fullexecname;
  879. /* If it's a relative path, normalize it. */
  880. if (execname[0] != '/')
  881. execname = newpath(changedir, execname);
  882. if (changeroot)
  883. fullexecname = newpath(changeroot, execname);
  884. else
  885. fullexecname = execname;
  886. if (stat(fullexecname, &exec_stat))
  887. fatal("unable to stat %s", fullexecname);
  888. if (fullexecname != execname)
  889. free(fullexecname);
  890. }
  891. if (userspec && sscanf(userspec, "%d", &user_id) != 1) {
  892. struct passwd *pw;
  893. pw = getpwnam(userspec);
  894. if (!pw)
  895. fatal("user '%s' not found", userspec);
  896. user_id = pw->pw_uid;
  897. }
  898. if (changegroup && sscanf(changegroup, "%d", &runas_gid) != 1) {
  899. struct group *gr;
  900. gr = getgrnam(changegroup);
  901. if (!gr)
  902. fatal("group '%s' not found", changegroup);
  903. changegroup = gr->gr_name;
  904. runas_gid = gr->gr_gid;
  905. }
  906. if (changeuser) {
  907. struct passwd *pw;
  908. struct stat st;
  909. if (sscanf(changeuser, "%d", &runas_uid) == 1)
  910. pw = getpwuid(runas_uid);
  911. else
  912. pw = getpwnam(changeuser);
  913. if (!pw)
  914. fatal("user '%s' not found", changeuser);
  915. changeuser = pw->pw_name;
  916. runas_uid = pw->pw_uid;
  917. if (changegroup == NULL) {
  918. /* Pass the default group of this user. */
  919. changegroup = ""; /* Just empty. */
  920. runas_gid = pw->pw_gid;
  921. }
  922. if (stat(pw->pw_dir, &st) == 0)
  923. setenv("HOME", pw->pw_dir, 1);
  924. }
  925. }
  926. #if defined(OSLinux)
  927. static const char *
  928. proc_status_field(pid_t pid, const char *field)
  929. {
  930. static char *line = NULL;
  931. static size_t line_size = 0;
  932. FILE *fp;
  933. char filename[32];
  934. char *value = NULL;
  935. ssize_t line_len;
  936. size_t field_len = strlen(field);
  937. sprintf(filename, "/proc/%d/status", pid);
  938. fp = fopen(filename, "r");
  939. if (!fp)
  940. return NULL;
  941. while ((line_len = getline(&line, &line_size, fp)) >= 0) {
  942. if (strncasecmp(line, field, field_len) == 0) {
  943. line[line_len - 1] = '\0';
  944. value = line + field_len;
  945. while (isspace(*value))
  946. value++;
  947. break;
  948. }
  949. }
  950. fclose(fp);
  951. return value;
  952. }
  953. #endif
  954. #if defined(OSHurd)
  955. static void
  956. init_procset(void)
  957. {
  958. struct ps_context *context;
  959. error_t err;
  960. err = ps_context_create(getproc(), &context);
  961. if (err)
  962. error(1, err, "ps_context_create");
  963. err = proc_stat_list_create(context, &procset);
  964. if (err)
  965. error(1, err, "proc_stat_list_create");
  966. err = proc_stat_list_add_all(procset, 0, 0);
  967. if (err)
  968. error(1, err, "proc_stat_list_add_all");
  969. }
  970. static struct proc_stat *
  971. get_proc_stat(pid_t pid, ps_flags_t flags)
  972. {
  973. struct proc_stat *ps;
  974. ps_flags_t wanted_flags = PSTAT_PID | flags;
  975. if (!procset)
  976. init_procset();
  977. ps = proc_stat_list_pid_proc_stat(procset, pid);
  978. if (!ps)
  979. return NULL;
  980. if (proc_stat_set_flags(ps, wanted_flags))
  981. return NULL;
  982. if ((proc_stat_flags(ps) & wanted_flags) != wanted_flags)
  983. return NULL;
  984. return ps;
  985. }
  986. #endif
  987. #if defined(OSLinux)
  988. static bool
  989. pid_is_exec(pid_t pid, const struct stat *esb)
  990. {
  991. char lname[32];
  992. char lcontents[_POSIX_PATH_MAX];
  993. const char deleted[] = " (deleted)";
  994. int nread;
  995. struct stat sb;
  996. sprintf(lname, "/proc/%d/exe", pid);
  997. nread = readlink(lname, lcontents, sizeof(lcontents));
  998. if (nread == -1)
  999. return false;
  1000. lcontents[nread] = '\0';
  1001. if (strcmp(lcontents + nread - strlen(deleted), deleted) == 0)
  1002. lcontents[nread - strlen(deleted)] = '\0';
  1003. if (stat(lcontents, &sb) != 0)
  1004. return false;
  1005. return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  1006. }
  1007. #elif defined(OSHurd)
  1008. static bool
  1009. pid_is_exec(pid_t pid, const struct stat *esb)
  1010. {
  1011. struct proc_stat *ps;
  1012. struct stat sb;
  1013. const char *filename;
  1014. ps = get_proc_stat(pid, PSTAT_ARGS);
  1015. if (ps == NULL)
  1016. return false;
  1017. filename = proc_stat_args(ps);
  1018. if (stat(filename, &sb) != 0)
  1019. return false;
  1020. return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  1021. }
  1022. #elif defined(OShpux)
  1023. static bool
  1024. pid_is_exec(pid_t pid, const struct stat *esb)
  1025. {
  1026. struct pst_status pst;
  1027. if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
  1028. return false;
  1029. return ((dev_t)pst.pst_text.psf_fsid.psfs_id == esb->st_dev &&
  1030. (ino_t)pst.pst_text.psf_fileid == esb->st_ino);
  1031. }
  1032. #elif defined(HAVE_KVM_H)
  1033. static bool
  1034. pid_is_exec(pid_t pid, const struct stat *esb)
  1035. {
  1036. kvm_t *kd;
  1037. int nentries, argv_len = 0;
  1038. struct kinfo_proc *kp;
  1039. struct stat sb;
  1040. char errbuf[_POSIX2_LINE_MAX], buf[_POSIX2_LINE_MAX];
  1041. char **pid_argv_p;
  1042. char *start_argv_0_p, *end_argv_0_p;
  1043. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  1044. if (kd == NULL)
  1045. errx(1, "%s", errbuf);
  1046. kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries);
  1047. if (kp == NULL)
  1048. errx(1, "%s", kvm_geterr(kd));
  1049. pid_argv_p = kvm_getargv(kd, kp, argv_len);
  1050. if (pid_argv_p == NULL)
  1051. errx(1, "%s", kvm_geterr(kd));
  1052. /* Find and compare string. */
  1053. start_argv_0_p = *pid_argv_p;
  1054. /* Find end of argv[0] then copy and cut of str there. */
  1055. end_argv_0_p = strchr(*pid_argv_p, ' ');
  1056. if (end_argv_0_p == NULL)
  1057. /* There seems to be no space, so we have the command
  1058. * already in its desired form. */
  1059. start_argv_0_p = *pid_argv_p;
  1060. else {
  1061. /* Tests indicate that this never happens, since
  1062. * kvm_getargv itself cuts of tailing stuff. This is
  1063. * not what the manpage says, however. */
  1064. strncpy(buf, *pid_argv_p, (end_argv_0_p - start_argv_0_p));
  1065. buf[(end_argv_0_p - start_argv_0_p) + 1] = '\0';
  1066. start_argv_0_p = buf;
  1067. }
  1068. if (stat(start_argv_0_p, &sb) != 0)
  1069. return false;
  1070. return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  1071. }
  1072. #endif
  1073. #if defined(OSLinux)
  1074. static bool
  1075. pid_is_user(pid_t pid, uid_t uid)
  1076. {
  1077. struct stat sb;
  1078. char buf[32];
  1079. sprintf(buf, "/proc/%d", pid);
  1080. if (stat(buf, &sb) != 0)
  1081. return false;
  1082. return (sb.st_uid == uid);
  1083. }
  1084. #elif defined(OSHurd)
  1085. static bool
  1086. pid_is_user(pid_t pid, uid_t uid)
  1087. {
  1088. struct proc_stat *ps;
  1089. ps = get_proc_stat(pid, PSTAT_OWNER_UID);
  1090. return ps && (uid_t)proc_stat_owner_uid(ps) == uid;
  1091. }
  1092. #elif defined(OShpux)
  1093. static bool
  1094. pid_is_user(pid_t pid, uid_t uid)
  1095. {
  1096. struct pst_status pst;
  1097. if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
  1098. return false;
  1099. return ((uid_t)pst.pst_uid == uid);
  1100. }
  1101. #elif defined(HAVE_KVM_H)
  1102. static bool
  1103. pid_is_user(pid_t pid, uid_t uid)
  1104. {
  1105. kvm_t *kd;
  1106. int nentries; /* Value not used. */
  1107. uid_t proc_uid;
  1108. struct kinfo_proc *kp;
  1109. char errbuf[_POSIX2_LINE_MAX];
  1110. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  1111. if (kd == NULL)
  1112. errx(1, "%s", errbuf);
  1113. kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries);
  1114. if (kp == NULL)
  1115. errx(1, "%s", kvm_geterr(kd));
  1116. if (kp->kp_proc.p_cred)
  1117. kvm_read(kd, (u_long)&(kp->kp_proc.p_cred->p_ruid),
  1118. &proc_uid, sizeof(uid_t));
  1119. else
  1120. return false;
  1121. return (proc_uid == (uid_t)uid);
  1122. }
  1123. #endif
  1124. #if defined(OSLinux)
  1125. static bool
  1126. pid_is_cmd(pid_t pid, const char *name)
  1127. {
  1128. const char *comm;
  1129. comm = proc_status_field(pid, "Name:");
  1130. if (comm == NULL)
  1131. return false;
  1132. return strcmp(comm, name) == 0;
  1133. }
  1134. #elif defined(OSHurd)
  1135. static bool
  1136. pid_is_cmd(pid_t pid, const char *name)
  1137. {
  1138. struct proc_stat *ps;
  1139. size_t argv0_len;
  1140. const char *argv0;
  1141. const char *binary_name;
  1142. ps = get_proc_stat(pid, PSTAT_ARGS);
  1143. if (ps == NULL)
  1144. return false;
  1145. argv0 = proc_stat_args(ps);
  1146. argv0_len = strlen(argv0) + 1;
  1147. binary_name = basename(argv0);
  1148. if (strcmp(binary_name, name) == 0)
  1149. return true;
  1150. /* XXX: This is all kinds of ugly, but on the Hurd there's no way to
  1151. * know the command name of a process, so we have to try to match
  1152. * also on argv[1] for the case of an interpreted script. */
  1153. if (proc_stat_args_len(ps) > argv0_len) {
  1154. const char *script_name = basename(argv0 + argv0_len);
  1155. return strcmp(script_name, name) == 0;
  1156. }
  1157. return false;
  1158. }
  1159. #elif defined(OShpux)
  1160. static bool
  1161. pid_is_cmd(pid_t pid, const char *name)
  1162. {
  1163. struct pst_status pst;
  1164. if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
  1165. return false;
  1166. return (strcmp(pst.pst_ucomm, name) == 0);
  1167. }
  1168. #elif defined(HAVE_KVM_H)
  1169. static bool
  1170. pid_is_cmd(pid_t pid, const char *name)
  1171. {
  1172. kvm_t *kd;
  1173. int nentries;
  1174. struct kinfo_proc *kp;
  1175. char errbuf[_POSIX2_LINE_MAX], *process_name;
  1176. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  1177. if (kd == NULL)
  1178. errx(1, "%s", errbuf);
  1179. kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries);
  1180. if (kp == NULL)
  1181. errx(1, "%s", kvm_geterr(kd));
  1182. process_name = kp->kp_proc.p_comm;
  1183. if (strlen(name) != strlen(process_name))
  1184. return false;
  1185. return (strcmp(name, process_name) == 0);
  1186. }
  1187. #endif
  1188. #if defined(OSHurd)
  1189. static bool
  1190. pid_is_running(pid_t pid)
  1191. {
  1192. return get_proc_stat(pid, 0) != NULL;
  1193. }
  1194. #else /* !OSHurd */
  1195. static bool
  1196. pid_is_running(pid_t pid)
  1197. {
  1198. if (kill(pid, 0) == 0 || errno == EPERM)
  1199. return true;
  1200. else if (errno == ESRCH)
  1201. return false;
  1202. else
  1203. fatal("error checking pid %u status", pid);
  1204. }
  1205. #endif
  1206. static enum status_code
  1207. pid_check(pid_t pid)
  1208. {
  1209. if (execname && !pid_is_exec(pid, &exec_stat))
  1210. return status_dead;
  1211. if (userspec && !pid_is_user(pid, user_id))
  1212. return status_dead;
  1213. if (cmdname && !pid_is_cmd(pid, cmdname))
  1214. return status_dead;
  1215. if (action != action_stop && !pid_is_running(pid))
  1216. return status_dead;
  1217. pid_list_push(&found, pid);
  1218. return status_ok;
  1219. }
  1220. static enum status_code
  1221. do_pidfile(const char *name)
  1222. {
  1223. FILE *f;
  1224. static pid_t pid = 0;
  1225. if (pid)
  1226. return pid_check(pid);
  1227. f = fopen(name, "r");
  1228. if (f) {
  1229. enum status_code pid_status;
  1230. if (fscanf(f, "%d", &pid) == 1)
  1231. pid_status = pid_check(pid);
  1232. else
  1233. pid_status = status_unknown;
  1234. fclose(f);
  1235. if (pid_status == status_dead)
  1236. return status_dead_pidfile;
  1237. else
  1238. return pid_status;
  1239. } else if (errno == ENOENT)
  1240. return status_dead;
  1241. else
  1242. fatal("unable to open pidfile %s", name);
  1243. }
  1244. #if defined(OSLinux) || defined (OSsunos)
  1245. static enum status_code
  1246. do_procinit(void)
  1247. {
  1248. DIR *procdir;
  1249. struct dirent *entry;
  1250. int foundany;
  1251. pid_t pid;
  1252. enum status_code prog_status = status_dead;
  1253. procdir = opendir("/proc");
  1254. if (!procdir)
  1255. fatal("unable to opendir /proc");
  1256. foundany = 0;
  1257. while ((entry = readdir(procdir)) != NULL) {
  1258. enum status_code pid_status;
  1259. if (sscanf(entry->d_name, "%d", &pid) != 1)
  1260. continue;
  1261. foundany++;
  1262. pid_status = pid_check(pid);
  1263. if (pid_status < prog_status)
  1264. prog_status = pid_status;
  1265. }
  1266. closedir(procdir);
  1267. if (!foundany)
  1268. fatal("nothing in /proc - not mounted?");
  1269. return prog_status;
  1270. }
  1271. #elif defined(OSHurd)
  1272. static int
  1273. check_proc_stat(struct proc_stat *ps)
  1274. {
  1275. pid_check(ps->pid);
  1276. return 0;
  1277. }
  1278. static enum status_code
  1279. do_procinit(void)
  1280. {
  1281. if (!procset)
  1282. init_procset();
  1283. proc_stat_list_for_each(procset, check_proc_stat);
  1284. if (found)
  1285. return status_ok;
  1286. else
  1287. return status_dead;
  1288. }
  1289. #elif defined(OShpux)
  1290. static enum status_code
  1291. do_procinit(void)
  1292. {
  1293. struct pst_status pst[10];
  1294. int i, count;
  1295. int idx = 0;
  1296. enum status_code prog_status = status_dead;
  1297. while ((count = pstat_getproc(pst, sizeof(pst[0]), 10, idx)) > 0) {
  1298. enum status_code pid_status;
  1299. for (i = 0; i < count; i++) {
  1300. pid_status = pid_check(pst[i].pst_pid);
  1301. if (pid_status < prog_status)
  1302. prog_status = pid_status;
  1303. }
  1304. idx = pst[count - 1].pst_idx + 1;
  1305. }
  1306. return prog_status;
  1307. }
  1308. #elif defined(HAVE_KVM_H)
  1309. static enum status_code
  1310. do_procinit(void)
  1311. {
  1312. /* Nothing to do. */
  1313. return status_unknown;
  1314. }
  1315. #endif
  1316. static enum status_code
  1317. do_findprocs(void)
  1318. {
  1319. pid_list_free(&found);
  1320. if (match_pid > 0)
  1321. return pid_check(match_pid);
  1322. else if (pidfile)
  1323. return do_pidfile(pidfile);
  1324. else
  1325. return do_procinit();
  1326. }
  1327. static void
  1328. do_start(int argc, char **argv)
  1329. {
  1330. int devnull_fd = -1;
  1331. gid_t rgid;
  1332. uid_t ruid;
  1333. do_findprocs();
  1334. if (found) {
  1335. if (quietmode <= 0)
  1336. printf("%s already running.\n", execname ? execname : "process");
  1337. exit(exitnodo);
  1338. }
  1339. if (testmode && quietmode <= 0) {
  1340. printf("Would start %s ", startas);
  1341. while (argc-- > 0)
  1342. printf("%s ", *argv++);
  1343. if (changeuser != NULL) {
  1344. printf(" (as user %s[%d]", changeuser, runas_uid);
  1345. if (changegroup != NULL)
  1346. printf(", and group %s[%d])", changegroup, runas_gid);
  1347. else
  1348. printf(")");
  1349. }
  1350. if (changeroot != NULL)
  1351. printf(" in directory %s", changeroot);
  1352. if (nicelevel)
  1353. printf(", and add %i to the priority", nicelevel);
  1354. if (proc_sched)
  1355. printf(", with scheduling policy %s with priority %i",
  1356. proc_sched->policy_name, proc_sched->priority);
  1357. if (io_sched)
  1358. printf(", with IO scheduling class %s with priority %i",
  1359. io_sched->policy_name, io_sched->priority);
  1360. printf(".\n");
  1361. }
  1362. if (testmode)
  1363. exit(0);
  1364. if (quietmode < 0)
  1365. printf("Starting %s...\n", startas);
  1366. *--argv = startas;
  1367. if (background)
  1368. /* Ok, we need to detach this process. */
  1369. daemonize();
  1370. if (background && close_io) {
  1371. devnull_fd = open("/dev/null", O_RDWR);
  1372. if (devnull_fd < 0)
  1373. fatal("unable to open '%s'", "/dev/null");
  1374. }
  1375. if (nicelevel) {
  1376. errno = 0;
  1377. if ((nice(nicelevel) == -1) && (errno != 0))
  1378. fatal("unable to alter nice level by %i", nicelevel);
  1379. }
  1380. if (proc_sched)
  1381. set_proc_schedule(proc_sched);
  1382. if (io_sched)
  1383. set_io_schedule(io_sched);
  1384. if (umask_value >= 0)
  1385. umask(umask_value);
  1386. if (mpidfile && pidfile != NULL)
  1387. /* User wants _us_ to make the pidfile. */
  1388. write_pidfile(pidfile, getpid());
  1389. if (changeroot != NULL) {
  1390. if (chdir(changeroot) < 0)
  1391. fatal("unable to chdir() to %s", changeroot);
  1392. if (chroot(changeroot) < 0)
  1393. fatal("unable to chroot() to %s", changeroot);
  1394. }
  1395. if (chdir(changedir) < 0)
  1396. fatal("unable to chdir() to %s", changedir);
  1397. rgid = getgid();
  1398. ruid = getuid();
  1399. if (changegroup != NULL) {
  1400. if (rgid != (gid_t)runas_gid)
  1401. if (setgid(runas_gid))
  1402. fatal("unable to set gid to %d", runas_gid);
  1403. }
  1404. if (changeuser != NULL) {
  1405. /* We assume that if our real user and group are the same as
  1406. * the ones we should switch to, the supplementary groups
  1407. * will be already in place. */
  1408. if (rgid != (gid_t)runas_gid || ruid != (uid_t)runas_uid)
  1409. if (initgroups(changeuser, runas_gid))
  1410. fatal("unable to set initgroups() with gid %d",
  1411. runas_gid);
  1412. if (ruid != (uid_t)runas_uid)
  1413. if (setuid(runas_uid))
  1414. fatal("unable to set uid to %s", changeuser);
  1415. }
  1416. /* Set a default umask for dumb programs. */
  1417. if (background && umask_value < 0)
  1418. umask(022);
  1419. if (background && close_io) {
  1420. int i;
  1421. dup2(devnull_fd, 0); /* stdin */
  1422. dup2(devnull_fd, 1); /* stdout */
  1423. dup2(devnull_fd, 2); /* stderr */
  1424. /* Now close all extra fds. */
  1425. for (i = get_open_fd_max() - 1; i >= 3; --i)
  1426. close(i);
  1427. }
  1428. execv(startas, argv);
  1429. fatal("unable to start %s", startas);
  1430. }
  1431. static void
  1432. do_stop(int sig_num, int *n_killed, int *n_notkilled)
  1433. {
  1434. struct pid_list *p;
  1435. do_findprocs();
  1436. *n_killed = 0;
  1437. *n_notkilled = 0;
  1438. if (!found)
  1439. return;
  1440. pid_list_free(&killed);
  1441. for (p = found; p; p = p->next) {
  1442. if (testmode) {
  1443. if (quietmode <= 0)
  1444. printf("Would send signal %d to %d.\n",
  1445. sig_num, p->pid);
  1446. (*n_killed)++;
  1447. } else if (kill(p->pid, sig_num) == 0) {
  1448. pid_list_push(&killed, p->pid);
  1449. (*n_killed)++;
  1450. } else {
  1451. if (sig_num)
  1452. warning("failed to kill %d: %s\n",
  1453. p->pid, strerror(errno));
  1454. (*n_notkilled)++;
  1455. }
  1456. }
  1457. }
  1458. static void
  1459. do_stop_summary(int retry_nr)
  1460. {
  1461. struct pid_list *p;
  1462. if (quietmode >= 0 || !killed)
  1463. return;
  1464. printf("Stopped %s (pid", what_stop);
  1465. for (p = killed; p; p = p->next)
  1466. printf(" %d", p->pid);
  1467. putchar(')');
  1468. if (retry_nr > 0)
  1469. printf(", retry #%d", retry_nr);
  1470. printf(".\n");
  1471. }
  1472. static void
  1473. set_what_stop(const char *str)
  1474. {
  1475. strncpy(what_stop, str, sizeof(what_stop));
  1476. what_stop[sizeof(what_stop) - 1] = '\0';
  1477. }
  1478. /*
  1479. * We want to keep polling for the processes, to see if they've exited, or
  1480. * until the timeout expires.
  1481. *
  1482. * This is a somewhat complicated algorithm to try to ensure that we notice
  1483. * reasonably quickly when all the processes have exited, but don't spend
  1484. * too much CPU time polling. In particular, on a fast machine with
  1485. * quick-exiting daemons we don't want to delay system shutdown too much,
  1486. * whereas on a slow one, or where processes are taking some time to exit,
  1487. * we want to increase the polling interval.
  1488. *
  1489. * The algorithm is as follows: we measure the elapsed time it takes to do
  1490. * one poll(), and wait a multiple of this time for the next poll. However,
  1491. * if that would put us past the end of the timeout period we wait only as
  1492. * long as the timeout period, but in any case we always wait at least
  1493. * MIN_POLL_INTERVAL (20ms). The multiple (‘ratio’) starts out as 2, and
  1494. * increases by 1 for each poll to a maximum of 10; so we use up to between
  1495. * 30% and 10% of the machine's resources (assuming a few reasonable things
  1496. * about system performance).
  1497. */
  1498. static bool
  1499. do_stop_timeout(int timeout, int *n_killed, int *n_notkilled)
  1500. {
  1501. struct timeval stopat, before, after, interval, maxinterval;
  1502. int rc, ratio;
  1503. xgettimeofday(&stopat);
  1504. stopat.tv_sec += timeout;
  1505. ratio = 1;
  1506. for (;;) {
  1507. xgettimeofday(&before);
  1508. if (timercmp(&before, &stopat, >))
  1509. return false;
  1510. do_stop(0, n_killed, n_notkilled);
  1511. if (!*n_killed)
  1512. return true;
  1513. xgettimeofday(&after);
  1514. if (!timercmp(&after, &stopat, <))
  1515. return false;
  1516. if (ratio < 10)
  1517. ratio++;
  1518. timersub(&stopat, &after, &maxinterval);
  1519. timersub(&after, &before, &interval);
  1520. tmul(&interval, ratio);
  1521. if (interval.tv_sec < 0 || interval.tv_usec < 0)
  1522. interval.tv_sec = interval.tv_usec = 0;
  1523. if (timercmp(&interval, &maxinterval, >))
  1524. interval = maxinterval;
  1525. if (interval.tv_sec == 0 &&
  1526. interval.tv_usec <= MIN_POLL_INTERVAL)
  1527. interval.tv_usec = MIN_POLL_INTERVAL;
  1528. rc = select(0, NULL, NULL, NULL, &interval);
  1529. if (rc < 0 && errno != EINTR)
  1530. fatal("select() failed for pause");
  1531. }
  1532. }
  1533. static int
  1534. finish_stop_schedule(bool anykilled)
  1535. {
  1536. if (anykilled)
  1537. return 0;
  1538. if (quietmode <= 0)
  1539. printf("No %s found running; none killed.\n", what_stop);
  1540. return exitnodo;
  1541. }
  1542. static int
  1543. run_stop_schedule(void)
  1544. {
  1545. int position, n_killed, n_notkilled, value, retry_nr;
  1546. bool anykilled;
  1547. if (testmode) {
  1548. if (schedule != NULL) {
  1549. if (quietmode <= 0)
  1550. printf("Ignoring --retry in test mode\n");
  1551. schedule = NULL;
  1552. }
  1553. }
  1554. if (cmdname)
  1555. set_what_stop(cmdname);
  1556. else if (execname)
  1557. set_what_stop(execname);
  1558. else if (pidfile)
  1559. sprintf(what_stop, "process in pidfile '%.200s'", pidfile);
  1560. else if (userspec)
  1561. sprintf(what_stop, "process(es) owned by '%.200s'", userspec);
  1562. else
  1563. fatal("internal error, no match option, please report");
  1564. anykilled = false;
  1565. retry_nr = 0;
  1566. if (schedule == NULL) {
  1567. do_stop(signal_nr, &n_killed, &n_notkilled);
  1568. do_stop_summary(0);
  1569. if (n_notkilled > 0 && quietmode <= 0)
  1570. printf("%d pids were not killed\n", n_notkilled);
  1571. if (n_killed)
  1572. anykilled = true;
  1573. return finish_stop_schedule(anykilled);
  1574. }
  1575. for (position = 0; position < schedule_length; position++) {
  1576. reposition:
  1577. value = schedule[position].value;
  1578. n_notkilled = 0;
  1579. switch (schedule[position].type) {
  1580. case sched_goto:
  1581. position = value;
  1582. goto reposition;
  1583. case sched_signal:
  1584. do_stop(value, &n_killed, &n_notkilled);
  1585. do_stop_summary(retry_nr++);
  1586. if (!n_killed)
  1587. return finish_stop_schedule(anykilled);
  1588. else
  1589. anykilled = true;
  1590. continue;
  1591. case sched_timeout:
  1592. if (do_stop_timeout(value, &n_killed, &n_notkilled))
  1593. return finish_stop_schedule(anykilled);
  1594. else
  1595. continue;
  1596. default:
  1597. assert(!"schedule[].type value must be valid");
  1598. }
  1599. }
  1600. if (quietmode <= 0)
  1601. printf("Program %s, %d process(es), refused to die.\n",
  1602. what_stop, n_killed);
  1603. return 2;
  1604. }
  1605. int
  1606. main(int argc, char **argv)
  1607. {
  1608. progname = argv[0];
  1609. parse_options(argc, argv);
  1610. setup_options();
  1611. argc -= optind;
  1612. argv += optind;
  1613. if (action == action_start)
  1614. do_start(argc, argv);
  1615. if (action == action_stop) {
  1616. int i = run_stop_schedule();
  1617. exit(i);
  1618. }
  1619. if (action == action_status) {
  1620. enum status_code prog_status;
  1621. prog_status = do_findprocs();
  1622. exit(prog_status);
  1623. }
  1624. return 0;
  1625. }