start-stop-daemon.c 52 KB

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