start-stop-daemon.c 46 KB

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