start-stop-daemon.c 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237
  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[1024];
  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. "Commands:\n"
  468. " -S|--start -- <argument> ... start a program and pass <arguments> to it\n"
  469. " -K|--stop stop a program\n"
  470. " -T|--status get the program status\n"
  471. " -H|--help print help information\n"
  472. " -V|--version print version\n"
  473. "\n"
  474. "Matching options (at least one is required):\n"
  475. " --pid <pid> pid to check\n"
  476. " --ppid <ppid> parent pid to check\n"
  477. " -p|--pidfile <pid-file> pid file to check\n"
  478. " -x|--exec <executable> program to start/check if it is running\n"
  479. " -n|--name <process-name> process name to check\n"
  480. " -u|--user <username|uid> process owner to check\n"
  481. "\n"
  482. "Options:\n"
  483. " -g|--group <group|gid> run process as this group\n"
  484. " -c|--chuid <name|uid[:group|gid]>\n"
  485. " change to this user/group before starting\n"
  486. " process\n"
  487. " -s|--signal <signal> signal to send (default TERM)\n"
  488. " -a|--startas <pathname> program to start (default is <executable>)\n"
  489. " -r|--chroot <directory> chroot to <directory> before starting\n"
  490. " -d|--chdir <directory> change to <directory> (default is /)\n"
  491. " -N|--nicelevel <incr> add incr to the process' nice level\n"
  492. " -P|--procsched <policy[:prio]>\n"
  493. " use <policy> with <prio> for the kernel\n"
  494. " process scheduler (default prio is 0)\n"
  495. " -I|--iosched <class[:prio]> use <class> with <prio> to set the IO\n"
  496. " scheduler (default prio is 4)\n"
  497. " -k|--umask <mask> change the umask to <mask> before starting\n"
  498. " -b|--background force the process to detach\n"
  499. " -C|--no-close do not close any file descriptor\n"
  500. " -m|--make-pidfile create the pidfile before starting\n"
  501. " |--remove-pidfile delete the pidfile after stopping\n"
  502. " -R|--retry <schedule> check whether processes die, and retry\n"
  503. " -t|--test test mode, don't do anything\n"
  504. " -o|--oknodo exit status 0 (not 1) if nothing done\n"
  505. " -q|--quiet be more quiet\n"
  506. " -v|--verbose be more verbose\n"
  507. "\n"
  508. "Retry <schedule> is <item>|/<item>/... where <item> is one of\n"
  509. " -<signal-num>|[-]<signal-name> send that signal\n"
  510. " <timeout> wait that many seconds\n"
  511. " forever repeat remainder forever\n"
  512. "or <schedule> may be just <timeout>, meaning <signal>/<timeout>/KILL/<timeout>\n"
  513. "\n"
  514. "The process scheduler <policy> can be one of:\n"
  515. " other, fifo or rr\n"
  516. "\n"
  517. "The IO scheduler <class> can be one of:\n"
  518. " real-time, best-effort or idle\n"
  519. "\n"
  520. "Exit status:\n"
  521. " 0 = done\n"
  522. " 1 = nothing done (=> 0 if --oknodo)\n"
  523. " 2 = with --retry, processes would not die\n"
  524. " 3 = trouble\n"
  525. "Exit status with --status:\n"
  526. " 0 = program is running\n"
  527. " 1 = program is not running and the pid file exists\n"
  528. " 3 = program is not running\n"
  529. " 4 = unable to determine status\n");
  530. }
  531. static void
  532. do_version(void)
  533. {
  534. printf("start-stop-daemon %s for Debian\n\n", VERSION);
  535. printf("Written by Marek Michalkiewicz, public domain.\n");
  536. }
  537. static void DPKG_ATTR_NORET
  538. badusage(const char *msg)
  539. {
  540. if (msg)
  541. fprintf(stderr, "%s: %s\n", progname, msg);
  542. fprintf(stderr, "Try '%s --help' for more information.\n", progname);
  543. if (action == ACTION_STATUS)
  544. exit(STATUS_UNKNOWN);
  545. else
  546. exit(3);
  547. }
  548. struct sigpair {
  549. const char *name;
  550. int signal;
  551. };
  552. static const struct sigpair siglist[] = {
  553. { "ABRT", SIGABRT },
  554. { "ALRM", SIGALRM },
  555. { "FPE", SIGFPE },
  556. { "HUP", SIGHUP },
  557. { "ILL", SIGILL },
  558. { "INT", SIGINT },
  559. { "KILL", SIGKILL },
  560. { "PIPE", SIGPIPE },
  561. { "QUIT", SIGQUIT },
  562. { "SEGV", SIGSEGV },
  563. { "TERM", SIGTERM },
  564. { "USR1", SIGUSR1 },
  565. { "USR2", SIGUSR2 },
  566. { "CHLD", SIGCHLD },
  567. { "CONT", SIGCONT },
  568. { "STOP", SIGSTOP },
  569. { "TSTP", SIGTSTP },
  570. { "TTIN", SIGTTIN },
  571. { "TTOU", SIGTTOU }
  572. };
  573. static int
  574. parse_unsigned(const char *string, int base, int *value_r)
  575. {
  576. long value;
  577. char *endptr;
  578. if (!string[0])
  579. return -1;
  580. errno = 0;
  581. value = strtol(string, &endptr, base);
  582. if (string == endptr || *endptr != '\0' || errno != 0)
  583. return -1;
  584. if (value < 0 || value > INT_MAX)
  585. return -1;
  586. *value_r = value;
  587. return 0;
  588. }
  589. static int
  590. parse_pid(const char *pid_str, int *pid_num)
  591. {
  592. if (parse_unsigned(pid_str, 10, pid_num) != 0)
  593. return -1;
  594. if (*pid_num == 0)
  595. return -1;
  596. return 0;
  597. }
  598. static int
  599. parse_signal(const char *sig_str, int *sig_num)
  600. {
  601. unsigned int i;
  602. if (parse_unsigned(sig_str, 10, sig_num) == 0)
  603. return 0;
  604. for (i = 0; i < array_count(siglist); i++) {
  605. if (strcmp(sig_str, siglist[i].name) == 0) {
  606. *sig_num = siglist[i].signal;
  607. return 0;
  608. }
  609. }
  610. return -1;
  611. }
  612. static int
  613. parse_umask(const char *string, int *value_r)
  614. {
  615. return parse_unsigned(string, 0, value_r);
  616. }
  617. static void
  618. validate_proc_schedule(void)
  619. {
  620. #ifdef _POSIX_PRIORITY_SCHEDULING
  621. int prio_min, prio_max;
  622. prio_min = sched_get_priority_min(proc_sched->policy);
  623. prio_max = sched_get_priority_max(proc_sched->policy);
  624. if (proc_sched->priority < prio_min)
  625. badusage("process scheduler priority less than min");
  626. if (proc_sched->priority > prio_max)
  627. badusage("process scheduler priority greater than max");
  628. #endif
  629. }
  630. static void
  631. parse_proc_schedule(const char *string)
  632. {
  633. char *policy_str;
  634. size_t policy_len;
  635. int prio = 0;
  636. policy_len = strcspn(string, ":");
  637. policy_str = xstrndup(string, policy_len);
  638. if (string[policy_len] == ':' &&
  639. parse_unsigned(string + policy_len + 1, 10, &prio) != 0)
  640. fatal("invalid process scheduler priority");
  641. proc_sched = xmalloc(sizeof(*proc_sched));
  642. proc_sched->policy_name = policy_str;
  643. if (strcmp(policy_str, "other") == 0) {
  644. proc_sched->policy = SCHED_OTHER;
  645. proc_sched->priority = 0;
  646. } else if (strcmp(policy_str, "fifo") == 0) {
  647. proc_sched->policy = SCHED_FIFO;
  648. proc_sched->priority = prio;
  649. } else if (strcmp(policy_str, "rr") == 0) {
  650. proc_sched->policy = SCHED_RR;
  651. proc_sched->priority = prio;
  652. } else
  653. badusage("invalid process scheduler policy");
  654. validate_proc_schedule();
  655. }
  656. static void
  657. parse_io_schedule(const char *string)
  658. {
  659. char *class_str;
  660. size_t class_len;
  661. int prio = 4;
  662. class_len = strcspn(string, ":");
  663. class_str = xstrndup(string, class_len);
  664. if (string[class_len] == ':' &&
  665. parse_unsigned(string + class_len + 1, 10, &prio) != 0)
  666. fatal("invalid IO scheduler priority");
  667. io_sched = xmalloc(sizeof(*io_sched));
  668. io_sched->policy_name = class_str;
  669. if (strcmp(class_str, "real-time") == 0) {
  670. io_sched->policy = IOPRIO_CLASS_RT;
  671. io_sched->priority = prio;
  672. } else if (strcmp(class_str, "best-effort") == 0) {
  673. io_sched->policy = IOPRIO_CLASS_BE;
  674. io_sched->priority = prio;
  675. } else if (strcmp(class_str, "idle") == 0) {
  676. io_sched->policy = IOPRIO_CLASS_IDLE;
  677. io_sched->priority = 7;
  678. } else
  679. badusage("invalid IO scheduler policy");
  680. if (io_sched->priority < IO_SCHED_PRIO_MIN)
  681. badusage("IO scheduler priority less than min");
  682. if (io_sched->priority > IO_SCHED_PRIO_MAX)
  683. badusage("IO scheduler priority greater than max");
  684. }
  685. static void
  686. set_proc_schedule(struct res_schedule *sched)
  687. {
  688. #ifdef _POSIX_PRIORITY_SCHEDULING
  689. struct sched_param param;
  690. param.sched_priority = sched->priority;
  691. if (sched_setscheduler(getpid(), sched->policy, &param) == -1)
  692. fatal("unable to set process scheduler");
  693. #endif
  694. }
  695. #ifdef HAVE_IOPRIO_SET
  696. static inline int
  697. ioprio_set(int which, int who, int ioprio)
  698. {
  699. return syscall(SYS_ioprio_set, which, who, ioprio);
  700. }
  701. #endif
  702. static void
  703. set_io_schedule(struct res_schedule *sched)
  704. {
  705. #ifdef HAVE_IOPRIO_SET
  706. int io_sched_mask;
  707. io_sched_mask = IOPRIO_PRIO_VALUE(sched->policy, sched->priority);
  708. if (ioprio_set(IOPRIO_WHO_PROCESS, getpid(), io_sched_mask) == -1)
  709. warning("unable to alter IO priority to mask %i (%s)\n",
  710. io_sched_mask, strerror(errno));
  711. #endif
  712. }
  713. static void
  714. parse_schedule_item(const char *string, struct schedule_item *item)
  715. {
  716. const char *after_hyph;
  717. if (strcmp(string, "forever") == 0) {
  718. item->type = sched_forever;
  719. } else if (isdigit(string[0])) {
  720. item->type = sched_timeout;
  721. if (parse_unsigned(string, 10, &item->value) != 0)
  722. badusage("invalid timeout value in schedule");
  723. } else if ((after_hyph = string + (string[0] == '-')) &&
  724. parse_signal(after_hyph, &item->value) == 0) {
  725. item->type = sched_signal;
  726. } else {
  727. badusage("invalid schedule item (must be [-]<signal-name>, "
  728. "-<signal-number>, <timeout> or 'forever'");
  729. }
  730. }
  731. static void
  732. parse_schedule(const char *schedule_str)
  733. {
  734. char item_buf[20];
  735. const char *slash;
  736. int count, repeatat;
  737. size_t str_len;
  738. count = 0;
  739. for (slash = schedule_str; *slash; slash++)
  740. if (*slash == '/')
  741. count++;
  742. schedule_length = (count == 0) ? 4 : count + 1;
  743. schedule = xmalloc(sizeof(*schedule) * schedule_length);
  744. if (count == 0) {
  745. schedule[0].type = sched_signal;
  746. schedule[0].value = signal_nr;
  747. parse_schedule_item(schedule_str, &schedule[1]);
  748. if (schedule[1].type != sched_timeout) {
  749. badusage("--retry takes timeout, or schedule list"
  750. " of at least two items");
  751. }
  752. schedule[2].type = sched_signal;
  753. schedule[2].value = SIGKILL;
  754. schedule[3] = schedule[1];
  755. } else {
  756. count = 0;
  757. repeatat = -1;
  758. while (schedule_str != NULL) {
  759. slash = strchr(schedule_str, '/');
  760. str_len = slash ? (size_t)(slash - schedule_str) : strlen(schedule_str);
  761. if (str_len >= sizeof(item_buf))
  762. badusage("invalid schedule item: far too long"
  763. " (you must delimit items with slashes)");
  764. memcpy(item_buf, schedule_str, str_len);
  765. item_buf[str_len] = '\0';
  766. schedule_str = slash ? slash + 1 : NULL;
  767. parse_schedule_item(item_buf, &schedule[count]);
  768. if (schedule[count].type == sched_forever) {
  769. if (repeatat >= 0)
  770. badusage("invalid schedule: 'forever'"
  771. " appears more than once");
  772. repeatat = count;
  773. continue;
  774. }
  775. count++;
  776. }
  777. if (repeatat == count)
  778. badusage("invalid schedule: 'forever' appears last, "
  779. "nothing to repeat");
  780. if (repeatat >= 0) {
  781. schedule[count].type = sched_goto;
  782. schedule[count].value = repeatat;
  783. count++;
  784. }
  785. assert(count == schedule_length);
  786. }
  787. }
  788. static void
  789. set_action(enum action_code new_action)
  790. {
  791. if (action == new_action)
  792. return;
  793. if (action != ACTION_NONE)
  794. badusage("only one command can be specified");
  795. action = new_action;
  796. }
  797. #define OPT_PID 500
  798. #define OPT_PPID 501
  799. #define OPT_RM_PIDFILE 502
  800. static void
  801. parse_options(int argc, char * const *argv)
  802. {
  803. static struct option longopts[] = {
  804. { "help", 0, NULL, 'H'},
  805. { "stop", 0, NULL, 'K'},
  806. { "start", 0, NULL, 'S'},
  807. { "status", 0, NULL, 'T'},
  808. { "version", 0, NULL, 'V'},
  809. { "startas", 1, NULL, 'a'},
  810. { "name", 1, NULL, 'n'},
  811. { "oknodo", 0, NULL, 'o'},
  812. { "pid", 1, NULL, OPT_PID},
  813. { "ppid", 1, NULL, OPT_PPID},
  814. { "pidfile", 1, NULL, 'p'},
  815. { "quiet", 0, NULL, 'q'},
  816. { "signal", 1, NULL, 's'},
  817. { "test", 0, NULL, 't'},
  818. { "user", 1, NULL, 'u'},
  819. { "group", 1, NULL, 'g'},
  820. { "chroot", 1, NULL, 'r'},
  821. { "verbose", 0, NULL, 'v'},
  822. { "exec", 1, NULL, 'x'},
  823. { "chuid", 1, NULL, 'c'},
  824. { "nicelevel", 1, NULL, 'N'},
  825. { "procsched", 1, NULL, 'P'},
  826. { "iosched", 1, NULL, 'I'},
  827. { "umask", 1, NULL, 'k'},
  828. { "background", 0, NULL, 'b'},
  829. { "no-close", 0, NULL, 'C'},
  830. { "make-pidfile", 0, NULL, 'm'},
  831. { "remove-pidfile", 0, NULL, OPT_RM_PIDFILE},
  832. { "retry", 1, NULL, 'R'},
  833. { "chdir", 1, NULL, 'd'},
  834. { NULL, 0, NULL, 0 }
  835. };
  836. const char *pid_str = NULL;
  837. const char *ppid_str = NULL;
  838. const char *umask_str = NULL;
  839. const char *signal_str = NULL;
  840. const char *schedule_str = NULL;
  841. const char *proc_schedule_str = NULL;
  842. const char *io_schedule_str = NULL;
  843. size_t changeuser_len;
  844. int c;
  845. for (;;) {
  846. c = getopt_long(argc, argv,
  847. "HKSVTa:n:op:qr:s:tu:vx:c:N:P:I:k:bCmR:g:d:",
  848. longopts, NULL);
  849. if (c == -1)
  850. break;
  851. switch (c) {
  852. case 'H': /* --help */
  853. usage();
  854. exit(0);
  855. case 'K': /* --stop */
  856. set_action(ACTION_STOP);
  857. break;
  858. case 'S': /* --start */
  859. set_action(ACTION_START);
  860. break;
  861. case 'T': /* --status */
  862. set_action(ACTION_STATUS);
  863. break;
  864. case 'V': /* --version */
  865. do_version();
  866. exit(0);
  867. case 'a': /* --startas <pathname> */
  868. startas = optarg;
  869. break;
  870. case 'n': /* --name <process-name> */
  871. cmdname = optarg;
  872. break;
  873. case 'o': /* --oknodo */
  874. exitnodo = 0;
  875. break;
  876. case OPT_PID: /* --pid <pid> */
  877. pid_str = optarg;
  878. break;
  879. case OPT_PPID: /* --ppid <ppid> */
  880. ppid_str = optarg;
  881. break;
  882. case 'p': /* --pidfile <pid-file> */
  883. pidfile = optarg;
  884. break;
  885. case 'q': /* --quiet */
  886. quietmode = true;
  887. break;
  888. case 's': /* --signal <signal> */
  889. signal_str = optarg;
  890. break;
  891. case 't': /* --test */
  892. testmode = true;
  893. break;
  894. case 'u': /* --user <username>|<uid> */
  895. userspec = optarg;
  896. break;
  897. case 'v': /* --verbose */
  898. quietmode = -1;
  899. break;
  900. case 'x': /* --exec <executable> */
  901. execname = optarg;
  902. break;
  903. case 'c': /* --chuid <username>|<uid> */
  904. /* We copy the string just in case we need the
  905. * argument later. */
  906. changeuser_len = strcspn(optarg, ":");
  907. changeuser = xstrndup(optarg, changeuser_len);
  908. if (optarg[changeuser_len] == ':') {
  909. if (optarg[changeuser_len + 1] == '\0')
  910. fatal("missing group name");
  911. changegroup = optarg + changeuser_len + 1;
  912. }
  913. break;
  914. case 'g': /* --group <group>|<gid> */
  915. changegroup = optarg;
  916. break;
  917. case 'r': /* --chroot /new/root */
  918. changeroot = optarg;
  919. break;
  920. case 'N': /* --nice */
  921. nicelevel = atoi(optarg);
  922. break;
  923. case 'P': /* --procsched */
  924. proc_schedule_str = optarg;
  925. break;
  926. case 'I': /* --iosched */
  927. io_schedule_str = optarg;
  928. break;
  929. case 'k': /* --umask <mask> */
  930. umask_str = optarg;
  931. break;
  932. case 'b': /* --background */
  933. background = true;
  934. break;
  935. case 'C': /* --no-close */
  936. close_io = false;
  937. break;
  938. case 'm': /* --make-pidfile */
  939. mpidfile = true;
  940. break;
  941. case OPT_RM_PIDFILE: /* --remove-pidfile */
  942. rpidfile = true;
  943. break;
  944. case 'R': /* --retry <schedule>|<timeout> */
  945. schedule_str = optarg;
  946. break;
  947. case 'd': /* --chdir /new/dir */
  948. changedir = optarg;
  949. break;
  950. default:
  951. /* Message printed by getopt. */
  952. badusage(NULL);
  953. }
  954. }
  955. if (pid_str != NULL) {
  956. if (parse_pid(pid_str, &match_pid) != 0)
  957. badusage("pid value must be a number greater than 0");
  958. }
  959. if (ppid_str != NULL) {
  960. if (parse_pid(ppid_str, &match_ppid) != 0)
  961. badusage("ppid value must be a number greater than 0");
  962. }
  963. if (signal_str != NULL) {
  964. if (parse_signal(signal_str, &signal_nr) != 0)
  965. badusage("signal value must be numeric or name"
  966. " of signal (KILL, INT, ...)");
  967. }
  968. if (schedule_str != NULL) {
  969. parse_schedule(schedule_str);
  970. }
  971. if (proc_schedule_str != NULL)
  972. parse_proc_schedule(proc_schedule_str);
  973. if (io_schedule_str != NULL)
  974. parse_io_schedule(io_schedule_str);
  975. if (umask_str != NULL) {
  976. if (parse_umask(umask_str, &umask_value) != 0)
  977. badusage("umask value must be a positive number");
  978. }
  979. if (action == ACTION_NONE)
  980. badusage("need one of --start or --stop or --status");
  981. if (!execname && !pid_str && !ppid_str && !pidfile && !userspec &&
  982. !cmdname)
  983. badusage("need at least one of --exec, --pid, --ppid, --pidfile, --user or --name");
  984. #ifdef PROCESS_NAME_SIZE
  985. if (cmdname && strlen(cmdname) > PROCESS_NAME_SIZE)
  986. warning("this system is not able to track process names\n"
  987. "longer than %d characters, please use --exec "
  988. "instead of --name.\n", PROCESS_NAME_SIZE);
  989. #endif
  990. if (!startas)
  991. startas = execname;
  992. if (action == ACTION_START && !startas)
  993. badusage("--start needs --exec or --startas");
  994. if (mpidfile && pidfile == NULL)
  995. badusage("--make-pidfile requires --pidfile");
  996. if (rpidfile && pidfile == NULL)
  997. badusage("--remove-pidfile requires --pidfile");
  998. if (pid_str && pidfile)
  999. badusage("need either --pid of --pidfile, not both");
  1000. if (background && action != ACTION_START)
  1001. badusage("--background is only relevant with --start");
  1002. if (!close_io && !background)
  1003. badusage("--no-close is only relevant with --background");
  1004. }
  1005. static void
  1006. setup_options(void)
  1007. {
  1008. if (execname) {
  1009. char *fullexecname;
  1010. /* If it's a relative path, normalize it. */
  1011. if (execname[0] != '/')
  1012. execname = newpath(changedir, execname);
  1013. if (changeroot)
  1014. fullexecname = newpath(changeroot, execname);
  1015. else
  1016. fullexecname = execname;
  1017. if (stat(fullexecname, &exec_stat))
  1018. fatal("unable to stat %s", fullexecname);
  1019. if (fullexecname != execname)
  1020. free(fullexecname);
  1021. }
  1022. if (userspec && sscanf(userspec, "%d", &user_id) != 1) {
  1023. struct passwd *pw;
  1024. pw = getpwnam(userspec);
  1025. if (!pw)
  1026. fatal("user '%s' not found", userspec);
  1027. user_id = pw->pw_uid;
  1028. }
  1029. if (changegroup && sscanf(changegroup, "%d", &runas_gid) != 1) {
  1030. struct group *gr;
  1031. gr = getgrnam(changegroup);
  1032. if (!gr)
  1033. fatal("group '%s' not found", changegroup);
  1034. changegroup = gr->gr_name;
  1035. runas_gid = gr->gr_gid;
  1036. }
  1037. if (changeuser) {
  1038. struct passwd *pw;
  1039. struct stat st;
  1040. if (sscanf(changeuser, "%d", &runas_uid) == 1)
  1041. pw = getpwuid(runas_uid);
  1042. else
  1043. pw = getpwnam(changeuser);
  1044. if (!pw)
  1045. fatal("user '%s' not found", changeuser);
  1046. changeuser = pw->pw_name;
  1047. runas_uid = pw->pw_uid;
  1048. if (changegroup == NULL) {
  1049. /* Pass the default group of this user. */
  1050. changegroup = ""; /* Just empty. */
  1051. runas_gid = pw->pw_gid;
  1052. }
  1053. if (stat(pw->pw_dir, &st) == 0)
  1054. setenv("HOME", pw->pw_dir, 1);
  1055. }
  1056. }
  1057. #if defined(OSLinux)
  1058. static const char *
  1059. proc_status_field(pid_t pid, const char *field)
  1060. {
  1061. static char *line = NULL;
  1062. static size_t line_size = 0;
  1063. FILE *fp;
  1064. char filename[32];
  1065. char *value = NULL;
  1066. ssize_t line_len;
  1067. size_t field_len = strlen(field);
  1068. sprintf(filename, "/proc/%d/status", pid);
  1069. fp = fopen(filename, "r");
  1070. if (!fp)
  1071. return NULL;
  1072. while ((line_len = getline(&line, &line_size, fp)) >= 0) {
  1073. if (strncasecmp(line, field, field_len) == 0) {
  1074. line[line_len - 1] = '\0';
  1075. value = line + field_len;
  1076. while (isspace(*value))
  1077. value++;
  1078. break;
  1079. }
  1080. }
  1081. fclose(fp);
  1082. return value;
  1083. }
  1084. #endif
  1085. #if defined(OSHurd)
  1086. static void
  1087. init_procset(void)
  1088. {
  1089. struct ps_context *context;
  1090. error_t err;
  1091. err = ps_context_create(getproc(), &context);
  1092. if (err)
  1093. error(1, err, "ps_context_create");
  1094. err = proc_stat_list_create(context, &procset);
  1095. if (err)
  1096. error(1, err, "proc_stat_list_create");
  1097. err = proc_stat_list_add_all(procset, 0, 0);
  1098. if (err)
  1099. error(1, err, "proc_stat_list_add_all");
  1100. }
  1101. static struct proc_stat *
  1102. get_proc_stat(pid_t pid, ps_flags_t flags)
  1103. {
  1104. struct proc_stat *ps;
  1105. ps_flags_t wanted_flags = PSTAT_PID | flags;
  1106. if (!procset)
  1107. init_procset();
  1108. ps = proc_stat_list_pid_proc_stat(procset, pid);
  1109. if (!ps)
  1110. return NULL;
  1111. if (proc_stat_set_flags(ps, wanted_flags))
  1112. return NULL;
  1113. if ((proc_stat_flags(ps) & wanted_flags) != wanted_flags)
  1114. return NULL;
  1115. return ps;
  1116. }
  1117. #elif defined(HAVE_KVM_H)
  1118. static kvm_t *
  1119. ssd_kvm_open(void)
  1120. {
  1121. kvm_t *kd;
  1122. char errbuf[_POSIX2_LINE_MAX];
  1123. kd = kvm_openfiles(NULL, KVM_MEMFILE, NULL, O_RDONLY, errbuf);
  1124. if (kd == NULL)
  1125. errx(1, "%s", errbuf);
  1126. return kd;
  1127. }
  1128. static struct kinfo_proc *
  1129. ssd_kvm_get_procs(kvm_t *kd, int op, int arg, int *count)
  1130. {
  1131. struct kinfo_proc *kp;
  1132. int lcount;
  1133. if (count == NULL)
  1134. count = &lcount;
  1135. *count = 0;
  1136. kp = kvm_getprocs(kd, op, arg, count);
  1137. if (kp == NULL && errno != ESRCH)
  1138. errx(1, "%s", kvm_geterr(kd));
  1139. return kp;
  1140. }
  1141. #endif
  1142. #if defined(OSLinux)
  1143. static bool
  1144. pid_is_exec(pid_t pid, const struct stat *esb)
  1145. {
  1146. char lname[32];
  1147. char lcontents[_POSIX_PATH_MAX + 1];
  1148. char *filename;
  1149. const char deleted[] = " (deleted)";
  1150. int nread;
  1151. struct stat sb;
  1152. sprintf(lname, "/proc/%d/exe", pid);
  1153. nread = readlink(lname, lcontents, sizeof(lcontents) - 1);
  1154. if (nread == -1)
  1155. return false;
  1156. filename = lcontents;
  1157. filename[nread] = '\0';
  1158. /* OpenVZ kernels contain a bogus patch that instead of appending,
  1159. * prepends the deleted marker. Workaround those. Otherwise handle
  1160. * the normal appended marker. */
  1161. if (strncmp(filename, deleted, strlen(deleted)) == 0)
  1162. filename += strlen(deleted);
  1163. else if (strcmp(filename + nread - strlen(deleted), deleted) == 0)
  1164. filename[nread - strlen(deleted)] = '\0';
  1165. if (stat(filename, &sb) != 0)
  1166. return false;
  1167. return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  1168. }
  1169. #elif defined(OSHurd)
  1170. static bool
  1171. pid_is_exec(pid_t pid, const struct stat *esb)
  1172. {
  1173. struct proc_stat *ps;
  1174. struct stat sb;
  1175. const char *filename;
  1176. ps = get_proc_stat(pid, PSTAT_ARGS);
  1177. if (ps == NULL)
  1178. return false;
  1179. filename = proc_stat_args(ps);
  1180. if (stat(filename, &sb) != 0)
  1181. return false;
  1182. return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  1183. }
  1184. #elif defined(OShpux)
  1185. static bool
  1186. pid_is_exec(pid_t pid, const struct stat *esb)
  1187. {
  1188. struct pst_status pst;
  1189. if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
  1190. return false;
  1191. return ((dev_t)pst.pst_text.psf_fsid.psfs_id == esb->st_dev &&
  1192. (ino_t)pst.pst_text.psf_fileid == esb->st_ino);
  1193. }
  1194. #elif defined(OSFreeBSD)
  1195. static bool
  1196. pid_is_exec(pid_t pid, const struct stat *esb)
  1197. {
  1198. struct stat sb;
  1199. int error, name[4];
  1200. size_t len;
  1201. char pathname[PATH_MAX];
  1202. name[0] = CTL_KERN;
  1203. name[1] = KERN_PROC;
  1204. name[2] = KERN_PROC_PATHNAME;
  1205. name[3] = pid;
  1206. len = sizeof(pathname);
  1207. error = sysctl(name, 4, pathname, &len, NULL, 0);
  1208. if (error != 0 && errno != ESRCH)
  1209. return false;
  1210. if (len == 0)
  1211. pathname[0] = '\0';
  1212. if (stat(pathname, &sb) != 0)
  1213. return false;
  1214. return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  1215. }
  1216. #elif defined(HAVE_KVM_H)
  1217. static bool
  1218. pid_is_exec(pid_t pid, const struct stat *esb)
  1219. {
  1220. kvm_t *kd;
  1221. int argv_len = 0;
  1222. struct kinfo_proc *kp;
  1223. struct stat sb;
  1224. char buf[_POSIX2_LINE_MAX];
  1225. char **pid_argv_p;
  1226. char *start_argv_0_p, *end_argv_0_p;
  1227. bool res = false;
  1228. kd = ssd_kvm_open();
  1229. kp = ssd_kvm_get_procs(kd, KERN_PROC_PID, pid, NULL);
  1230. if (kp == NULL)
  1231. goto cleanup;
  1232. pid_argv_p = kvm_getargv(kd, kp, argv_len);
  1233. if (pid_argv_p == NULL)
  1234. errx(1, "%s", kvm_geterr(kd));
  1235. /* Find and compare string. */
  1236. start_argv_0_p = *pid_argv_p;
  1237. /* Find end of argv[0] then copy and cut of str there. */
  1238. end_argv_0_p = strchr(*pid_argv_p, ' ');
  1239. if (end_argv_0_p == NULL)
  1240. /* There seems to be no space, so we have the command
  1241. * already in its desired form. */
  1242. start_argv_0_p = *pid_argv_p;
  1243. else {
  1244. /* Tests indicate that this never happens, since
  1245. * kvm_getargv itself cuts of tailing stuff. This is
  1246. * not what the manpage says, however. */
  1247. strncpy(buf, *pid_argv_p, (end_argv_0_p - start_argv_0_p));
  1248. buf[(end_argv_0_p - start_argv_0_p) + 1] = '\0';
  1249. start_argv_0_p = buf;
  1250. }
  1251. if (stat(start_argv_0_p, &sb) != 0)
  1252. goto cleanup;
  1253. res = (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  1254. cleanup:
  1255. kvm_close(kd);
  1256. return res;
  1257. }
  1258. #endif
  1259. #if defined(OSLinux)
  1260. static bool
  1261. pid_is_child(pid_t pid, pid_t ppid)
  1262. {
  1263. const char *ppid_str;
  1264. pid_t proc_ppid;
  1265. int rc;
  1266. ppid_str = proc_status_field(pid, "PPid:");
  1267. if (ppid_str == NULL)
  1268. return false;
  1269. rc = parse_pid(ppid_str, &proc_ppid);
  1270. if (rc < 0)
  1271. return false;
  1272. return proc_ppid == ppid;
  1273. }
  1274. #elif defined(OSHurd)
  1275. static bool
  1276. pid_is_child(pid_t pid, pid_t ppid)
  1277. {
  1278. struct proc_stat *ps;
  1279. struct procinfo *pi;
  1280. ps = get_proc_stat(pid, PSTAT_PROC_INFO);
  1281. if (ps == NULL)
  1282. return false;
  1283. pi = proc_stat_proc_info(ps);
  1284. return pi->ppid == ppid;
  1285. }
  1286. #elif defined(OShpux)
  1287. static bool
  1288. pid_is_child(pid_t pid, pid_t ppid)
  1289. {
  1290. struct pst_status pst;
  1291. if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
  1292. return false;
  1293. return pst.pst_ppid == ppid;
  1294. }
  1295. #elif defined(HAVE_KVM_H)
  1296. static bool
  1297. pid_is_child(pid_t pid, pid_t ppid)
  1298. {
  1299. kvm_t *kd;
  1300. struct kinfo_proc *kp;
  1301. pid_t proc_ppid;
  1302. bool res = false;
  1303. kd = ssd_kvm_open();
  1304. kp = ssd_kvm_get_procs(kd, KERN_PROC_PID, pid, NULL);
  1305. if (kp == NULL)
  1306. goto cleanup;
  1307. #if defined(OSFreeBSD)
  1308. proc_ppid = kp->ki_ppid;
  1309. #elif defined(OSOpenBSD)
  1310. proc_ppid = kp->p_ppid;
  1311. #elif defined(OSDragonFlyBSD)
  1312. proc_ppid = kp->kp_ppid;
  1313. #else
  1314. proc_ppid = kp->kp_proc.p_ppid;
  1315. #endif
  1316. res = (proc_ppid == ppid);
  1317. cleanup:
  1318. kvm_close(kd);
  1319. return res;
  1320. }
  1321. #endif
  1322. #if defined(OSLinux)
  1323. static bool
  1324. pid_is_user(pid_t pid, uid_t uid)
  1325. {
  1326. struct stat sb;
  1327. char buf[32];
  1328. sprintf(buf, "/proc/%d", pid);
  1329. if (stat(buf, &sb) != 0)
  1330. return false;
  1331. return (sb.st_uid == uid);
  1332. }
  1333. #elif defined(OSHurd)
  1334. static bool
  1335. pid_is_user(pid_t pid, uid_t uid)
  1336. {
  1337. struct proc_stat *ps;
  1338. ps = get_proc_stat(pid, PSTAT_OWNER_UID);
  1339. return ps && (uid_t)proc_stat_owner_uid(ps) == uid;
  1340. }
  1341. #elif defined(OShpux)
  1342. static bool
  1343. pid_is_user(pid_t pid, uid_t uid)
  1344. {
  1345. struct pst_status pst;
  1346. if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
  1347. return false;
  1348. return ((uid_t)pst.pst_uid == uid);
  1349. }
  1350. #elif defined(HAVE_KVM_H)
  1351. static bool
  1352. pid_is_user(pid_t pid, uid_t uid)
  1353. {
  1354. kvm_t *kd;
  1355. uid_t proc_uid;
  1356. struct kinfo_proc *kp;
  1357. bool res = false;
  1358. kd = ssd_kvm_open();
  1359. kp = ssd_kvm_get_procs(kd, KERN_PROC_PID, pid, NULL);
  1360. if (kp == NULL)
  1361. goto cleanup;
  1362. #if defined(OSFreeBSD)
  1363. proc_uid = kp->ki_ruid;
  1364. #elif defined(OSOpenBSD)
  1365. proc_uid = kp->p_ruid;
  1366. #elif defined(OSDragonFlyBSD)
  1367. proc_uid = kp->kp_ruid;
  1368. #else
  1369. if (kp->kp_proc.p_cred)
  1370. kvm_read(kd, (u_long)&(kp->kp_proc.p_cred->p_ruid),
  1371. &proc_uid, sizeof(uid_t));
  1372. else
  1373. goto cleanup;
  1374. #endif
  1375. res = (proc_uid == (uid_t)uid);
  1376. cleanup:
  1377. kvm_close(kd);
  1378. return res;
  1379. }
  1380. #endif
  1381. #if defined(OSLinux)
  1382. static bool
  1383. pid_is_cmd(pid_t pid, const char *name)
  1384. {
  1385. const char *comm;
  1386. comm = proc_status_field(pid, "Name:");
  1387. if (comm == NULL)
  1388. return false;
  1389. return strcmp(comm, name) == 0;
  1390. }
  1391. #elif defined(OSHurd)
  1392. static bool
  1393. pid_is_cmd(pid_t pid, const char *name)
  1394. {
  1395. struct proc_stat *ps;
  1396. size_t argv0_len;
  1397. const char *argv0;
  1398. const char *binary_name;
  1399. ps = get_proc_stat(pid, PSTAT_ARGS);
  1400. if (ps == NULL)
  1401. return false;
  1402. argv0 = proc_stat_args(ps);
  1403. argv0_len = strlen(argv0) + 1;
  1404. binary_name = basename(argv0);
  1405. if (strcmp(binary_name, name) == 0)
  1406. return true;
  1407. /* XXX: This is all kinds of ugly, but on the Hurd there's no way to
  1408. * know the command name of a process, so we have to try to match
  1409. * also on argv[1] for the case of an interpreted script. */
  1410. if (proc_stat_args_len(ps) > argv0_len) {
  1411. const char *script_name = basename(argv0 + argv0_len);
  1412. return strcmp(script_name, name) == 0;
  1413. }
  1414. return false;
  1415. }
  1416. #elif defined(OShpux)
  1417. static bool
  1418. pid_is_cmd(pid_t pid, const char *name)
  1419. {
  1420. struct pst_status pst;
  1421. if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
  1422. return false;
  1423. return (strcmp(pst.pst_ucomm, name) == 0);
  1424. }
  1425. #elif defined(HAVE_KVM_H)
  1426. static bool
  1427. pid_is_cmd(pid_t pid, const char *name)
  1428. {
  1429. kvm_t *kd;
  1430. struct kinfo_proc *kp;
  1431. char *process_name;
  1432. bool res = false;
  1433. kd = ssd_kvm_open();
  1434. kp = ssd_kvm_get_procs(kd, KERN_PROC_PID, pid, NULL);
  1435. if (kp == NULL)
  1436. goto cleanup;
  1437. #if defined(OSFreeBSD)
  1438. process_name = kp->ki_comm;
  1439. #elif defined(OSOpenBSD)
  1440. process_name = kp->p_comm;
  1441. #elif defined(OSDragonFlyBSD)
  1442. process_name = kp->kp_comm;
  1443. #else
  1444. process_name = kp->kp_proc.p_comm;
  1445. #endif
  1446. res = (strcmp(name, process_name) == 0);
  1447. cleanup:
  1448. kvm_close(kd);
  1449. return res;
  1450. }
  1451. #endif
  1452. #if defined(OSHurd)
  1453. static bool
  1454. pid_is_running(pid_t pid)
  1455. {
  1456. return get_proc_stat(pid, 0) != NULL;
  1457. }
  1458. #else /* !OSHurd */
  1459. static bool
  1460. pid_is_running(pid_t pid)
  1461. {
  1462. if (kill(pid, 0) == 0 || errno == EPERM)
  1463. return true;
  1464. else if (errno == ESRCH)
  1465. return false;
  1466. else
  1467. fatal("error checking pid %u status", pid);
  1468. }
  1469. #endif
  1470. static enum status_code
  1471. pid_check(pid_t pid)
  1472. {
  1473. if (execname && !pid_is_exec(pid, &exec_stat))
  1474. return STATUS_DEAD;
  1475. if (match_ppid > 0 && !pid_is_child(pid, match_ppid))
  1476. return STATUS_DEAD;
  1477. if (userspec && !pid_is_user(pid, user_id))
  1478. return STATUS_DEAD;
  1479. if (cmdname && !pid_is_cmd(pid, cmdname))
  1480. return STATUS_DEAD;
  1481. if (action != ACTION_STOP && !pid_is_running(pid))
  1482. return STATUS_DEAD;
  1483. pid_list_push(&found, pid);
  1484. return STATUS_OK;
  1485. }
  1486. static enum status_code
  1487. do_pidfile(const char *name)
  1488. {
  1489. FILE *f;
  1490. static pid_t pid = 0;
  1491. if (pid)
  1492. return pid_check(pid);
  1493. f = fopen(name, "r");
  1494. if (f) {
  1495. enum status_code pid_status;
  1496. if (fscanf(f, "%d", &pid) == 1)
  1497. pid_status = pid_check(pid);
  1498. else
  1499. pid_status = STATUS_UNKNOWN;
  1500. fclose(f);
  1501. if (pid_status == STATUS_DEAD)
  1502. return STATUS_DEAD_PIDFILE;
  1503. else
  1504. return pid_status;
  1505. } else if (errno == ENOENT)
  1506. return STATUS_DEAD;
  1507. else
  1508. fatal("unable to open pidfile %s", name);
  1509. }
  1510. #if defined(OSLinux) || defined (OSsunos)
  1511. static enum status_code
  1512. do_procinit(void)
  1513. {
  1514. DIR *procdir;
  1515. struct dirent *entry;
  1516. int foundany;
  1517. pid_t pid;
  1518. enum status_code prog_status = STATUS_DEAD;
  1519. procdir = opendir("/proc");
  1520. if (!procdir)
  1521. fatal("unable to opendir /proc");
  1522. foundany = 0;
  1523. while ((entry = readdir(procdir)) != NULL) {
  1524. enum status_code pid_status;
  1525. if (sscanf(entry->d_name, "%d", &pid) != 1)
  1526. continue;
  1527. foundany++;
  1528. pid_status = pid_check(pid);
  1529. if (pid_status < prog_status)
  1530. prog_status = pid_status;
  1531. }
  1532. closedir(procdir);
  1533. if (!foundany)
  1534. fatal("nothing in /proc - not mounted?");
  1535. return prog_status;
  1536. }
  1537. #elif defined(OSHurd)
  1538. static int
  1539. check_proc_stat(struct proc_stat *ps)
  1540. {
  1541. pid_check(ps->pid);
  1542. return 0;
  1543. }
  1544. static enum status_code
  1545. do_procinit(void)
  1546. {
  1547. if (!procset)
  1548. init_procset();
  1549. proc_stat_list_for_each(procset, check_proc_stat);
  1550. if (found)
  1551. return STATUS_OK;
  1552. else
  1553. return STATUS_DEAD;
  1554. }
  1555. #elif defined(OShpux)
  1556. static enum status_code
  1557. do_procinit(void)
  1558. {
  1559. struct pst_status pst[10];
  1560. int i, count;
  1561. int idx = 0;
  1562. enum status_code prog_status = STATUS_DEAD;
  1563. while ((count = pstat_getproc(pst, sizeof(pst[0]), 10, idx)) > 0) {
  1564. enum status_code pid_status;
  1565. for (i = 0; i < count; i++) {
  1566. pid_status = pid_check(pst[i].pst_pid);
  1567. if (pid_status < prog_status)
  1568. prog_status = pid_status;
  1569. }
  1570. idx = pst[count - 1].pst_idx + 1;
  1571. }
  1572. return prog_status;
  1573. }
  1574. #elif defined(HAVE_KVM_H)
  1575. static enum status_code
  1576. do_procinit(void)
  1577. {
  1578. kvm_t *kd;
  1579. int nentries, i;
  1580. struct kinfo_proc *kp;
  1581. enum status_code prog_status = STATUS_DEAD;
  1582. kd = ssd_kvm_open();
  1583. kp = ssd_kvm_get_procs(kd, KERN_PROC_ALL, 0, &nentries);
  1584. for (i = 0; i < nentries; i++) {
  1585. enum status_code pid_status;
  1586. pid_t pid;
  1587. #if defined(OSFreeBSD)
  1588. pid = kp[i].ki_pid;
  1589. #elif defined(OSOpenBSD)
  1590. pid = kp[i].p_pid;
  1591. #elif defined(OSDragonFlyBSD)
  1592. pid = kp[i].kp_pid;
  1593. #else
  1594. pid = kp[i].kp_proc.p_pid;
  1595. #endif
  1596. pid_status = pid_check(pid);
  1597. if (pid_status < prog_status)
  1598. prog_status = pid_status;
  1599. }
  1600. kvm_close(kd);
  1601. return prog_status;
  1602. }
  1603. #endif
  1604. static enum status_code
  1605. do_findprocs(void)
  1606. {
  1607. pid_list_free(&found);
  1608. if (match_pid > 0)
  1609. return pid_check(match_pid);
  1610. else if (pidfile)
  1611. return do_pidfile(pidfile);
  1612. else
  1613. return do_procinit();
  1614. }
  1615. static void
  1616. do_start(int argc, char **argv)
  1617. {
  1618. int devnull_fd = -1;
  1619. gid_t rgid;
  1620. uid_t ruid;
  1621. do_findprocs();
  1622. if (found) {
  1623. if (quietmode <= 0)
  1624. printf("%s already running.\n", execname ? execname : "process");
  1625. exit(exitnodo);
  1626. }
  1627. if (testmode && quietmode <= 0) {
  1628. printf("Would start %s ", startas);
  1629. while (argc-- > 0)
  1630. printf("%s ", *argv++);
  1631. if (changeuser != NULL) {
  1632. printf(" (as user %s[%d]", changeuser, runas_uid);
  1633. if (changegroup != NULL)
  1634. printf(", and group %s[%d])", changegroup, runas_gid);
  1635. else
  1636. printf(")");
  1637. }
  1638. if (changeroot != NULL)
  1639. printf(" in directory %s", changeroot);
  1640. if (nicelevel)
  1641. printf(", and add %i to the priority", nicelevel);
  1642. if (proc_sched)
  1643. printf(", with scheduling policy %s with priority %i",
  1644. proc_sched->policy_name, proc_sched->priority);
  1645. if (io_sched)
  1646. printf(", with IO scheduling class %s with priority %i",
  1647. io_sched->policy_name, io_sched->priority);
  1648. printf(".\n");
  1649. }
  1650. if (testmode)
  1651. exit(0);
  1652. if (quietmode < 0)
  1653. printf("Starting %s...\n", startas);
  1654. *--argv = startas;
  1655. if (background)
  1656. /* Ok, we need to detach this process. */
  1657. daemonize();
  1658. else if (mpidfile && pidfile != NULL)
  1659. /* User wants _us_ to make the pidfile, but detach themself! */
  1660. write_pidfile(pidfile, getpid());
  1661. if (background && close_io) {
  1662. devnull_fd = open("/dev/null", O_RDWR);
  1663. if (devnull_fd < 0)
  1664. fatal("unable to open '%s'", "/dev/null");
  1665. }
  1666. if (nicelevel) {
  1667. errno = 0;
  1668. if ((nice(nicelevel) == -1) && (errno != 0))
  1669. fatal("unable to alter nice level by %i", nicelevel);
  1670. }
  1671. if (proc_sched)
  1672. set_proc_schedule(proc_sched);
  1673. if (io_sched)
  1674. set_io_schedule(io_sched);
  1675. if (umask_value >= 0)
  1676. umask(umask_value);
  1677. if (changeroot != NULL) {
  1678. if (chdir(changeroot) < 0)
  1679. fatal("unable to chdir() to %s", changeroot);
  1680. if (chroot(changeroot) < 0)
  1681. fatal("unable to chroot() to %s", changeroot);
  1682. }
  1683. if (chdir(changedir) < 0)
  1684. fatal("unable to chdir() to %s", changedir);
  1685. rgid = getgid();
  1686. ruid = getuid();
  1687. if (changegroup != NULL) {
  1688. if (rgid != (gid_t)runas_gid)
  1689. if (setgid(runas_gid))
  1690. fatal("unable to set gid to %d", runas_gid);
  1691. }
  1692. if (changeuser != NULL) {
  1693. /* We assume that if our real user and group are the same as
  1694. * the ones we should switch to, the supplementary groups
  1695. * will be already in place. */
  1696. if (rgid != (gid_t)runas_gid || ruid != (uid_t)runas_uid)
  1697. if (initgroups(changeuser, runas_gid))
  1698. fatal("unable to set initgroups() with gid %d",
  1699. runas_gid);
  1700. if (ruid != (uid_t)runas_uid)
  1701. if (setuid(runas_uid))
  1702. fatal("unable to set uid to %s", changeuser);
  1703. }
  1704. if (background && close_io) {
  1705. int i;
  1706. dup2(devnull_fd, 0); /* stdin */
  1707. dup2(devnull_fd, 1); /* stdout */
  1708. dup2(devnull_fd, 2); /* stderr */
  1709. /* Now close all extra fds. */
  1710. for (i = get_open_fd_max() - 1; i >= 3; --i)
  1711. close(i);
  1712. }
  1713. execv(startas, argv);
  1714. fatal("unable to start %s", startas);
  1715. }
  1716. static void
  1717. do_stop(int sig_num, int *n_killed, int *n_notkilled)
  1718. {
  1719. struct pid_list *p;
  1720. do_findprocs();
  1721. *n_killed = 0;
  1722. *n_notkilled = 0;
  1723. if (!found)
  1724. return;
  1725. pid_list_free(&killed);
  1726. for (p = found; p; p = p->next) {
  1727. if (testmode) {
  1728. if (quietmode <= 0)
  1729. printf("Would send signal %d to %d.\n",
  1730. sig_num, p->pid);
  1731. (*n_killed)++;
  1732. } else if (kill(p->pid, sig_num) == 0) {
  1733. pid_list_push(&killed, p->pid);
  1734. (*n_killed)++;
  1735. } else {
  1736. if (sig_num)
  1737. warning("failed to kill %d: %s\n",
  1738. p->pid, strerror(errno));
  1739. (*n_notkilled)++;
  1740. }
  1741. }
  1742. }
  1743. static void
  1744. do_stop_summary(int retry_nr)
  1745. {
  1746. struct pid_list *p;
  1747. if (quietmode >= 0 || !killed)
  1748. return;
  1749. printf("Stopped %s (pid", what_stop);
  1750. for (p = killed; p; p = p->next)
  1751. printf(" %d", p->pid);
  1752. putchar(')');
  1753. if (retry_nr > 0)
  1754. printf(", retry #%d", retry_nr);
  1755. printf(".\n");
  1756. }
  1757. static void
  1758. set_what_stop(const char *str)
  1759. {
  1760. strncpy(what_stop, str, sizeof(what_stop));
  1761. what_stop[sizeof(what_stop) - 1] = '\0';
  1762. }
  1763. /*
  1764. * We want to keep polling for the processes, to see if they've exited, or
  1765. * until the timeout expires.
  1766. *
  1767. * This is a somewhat complicated algorithm to try to ensure that we notice
  1768. * reasonably quickly when all the processes have exited, but don't spend
  1769. * too much CPU time polling. In particular, on a fast machine with
  1770. * quick-exiting daemons we don't want to delay system shutdown too much,
  1771. * whereas on a slow one, or where processes are taking some time to exit,
  1772. * we want to increase the polling interval.
  1773. *
  1774. * The algorithm is as follows: we measure the elapsed time it takes to do
  1775. * one poll(), and wait a multiple of this time for the next poll. However,
  1776. * if that would put us past the end of the timeout period we wait only as
  1777. * long as the timeout period, but in any case we always wait at least
  1778. * MIN_POLL_INTERVAL (20ms). The multiple (‘ratio’) starts out as 2, and
  1779. * increases by 1 for each poll to a maximum of 10; so we use up to between
  1780. * 30% and 10% of the machine's resources (assuming a few reasonable things
  1781. * about system performance).
  1782. */
  1783. static bool
  1784. do_stop_timeout(int timeout, int *n_killed, int *n_notkilled)
  1785. {
  1786. struct timespec stopat, before, after, interval, maxinterval;
  1787. int rc, ratio;
  1788. timespec_gettime(&stopat);
  1789. stopat.tv_sec += timeout;
  1790. ratio = 1;
  1791. for (;;) {
  1792. timespec_gettime(&before);
  1793. if (timespec_cmp(&before, &stopat, >))
  1794. return false;
  1795. do_stop(0, n_killed, n_notkilled);
  1796. if (!*n_killed)
  1797. return true;
  1798. timespec_gettime(&after);
  1799. if (!timespec_cmp(&after, &stopat, <))
  1800. return false;
  1801. if (ratio < 10)
  1802. ratio++;
  1803. timespec_sub(&stopat, &after, &maxinterval);
  1804. timespec_sub(&after, &before, &interval);
  1805. timespec_mul(&interval, ratio);
  1806. if (interval.tv_sec < 0 || interval.tv_nsec < 0)
  1807. interval.tv_sec = interval.tv_nsec = 0;
  1808. if (timespec_cmp(&interval, &maxinterval, >))
  1809. interval = maxinterval;
  1810. if (interval.tv_sec == 0 &&
  1811. interval.tv_nsec <= MIN_POLL_INTERVAL)
  1812. interval.tv_nsec = MIN_POLL_INTERVAL;
  1813. rc = pselect(0, NULL, NULL, NULL, &interval, NULL);
  1814. if (rc < 0 && errno != EINTR)
  1815. fatal("select() failed for pause");
  1816. }
  1817. }
  1818. static int
  1819. finish_stop_schedule(bool anykilled)
  1820. {
  1821. if (rpidfile && pidfile && !testmode)
  1822. remove_pidfile(pidfile);
  1823. if (anykilled)
  1824. return 0;
  1825. if (quietmode <= 0)
  1826. printf("No %s found running; none killed.\n", what_stop);
  1827. return exitnodo;
  1828. }
  1829. static int
  1830. run_stop_schedule(void)
  1831. {
  1832. int position, n_killed, n_notkilled, value, retry_nr;
  1833. bool anykilled;
  1834. if (testmode) {
  1835. if (schedule != NULL) {
  1836. if (quietmode <= 0)
  1837. printf("Ignoring --retry in test mode\n");
  1838. schedule = NULL;
  1839. }
  1840. }
  1841. if (cmdname)
  1842. set_what_stop(cmdname);
  1843. else if (execname)
  1844. set_what_stop(execname);
  1845. else if (pidfile)
  1846. sprintf(what_stop, "process in pidfile '%.200s'", pidfile);
  1847. else if (match_pid > 0)
  1848. sprintf(what_stop, "process with pid %d", match_pid);
  1849. else if (match_ppid > 0)
  1850. sprintf(what_stop, "process(es) with parent pid %d", match_ppid);
  1851. else if (userspec)
  1852. sprintf(what_stop, "process(es) owned by '%.200s'", userspec);
  1853. else
  1854. fatal("internal error, no match option, please report");
  1855. anykilled = false;
  1856. retry_nr = 0;
  1857. if (schedule == NULL) {
  1858. do_stop(signal_nr, &n_killed, &n_notkilled);
  1859. do_stop_summary(0);
  1860. if (n_notkilled > 0 && quietmode <= 0)
  1861. printf("%d pids were not killed\n", n_notkilled);
  1862. if (n_killed)
  1863. anykilled = true;
  1864. return finish_stop_schedule(anykilled);
  1865. }
  1866. for (position = 0; position < schedule_length; position++) {
  1867. reposition:
  1868. value = schedule[position].value;
  1869. n_notkilled = 0;
  1870. switch (schedule[position].type) {
  1871. case sched_goto:
  1872. position = value;
  1873. goto reposition;
  1874. case sched_signal:
  1875. do_stop(value, &n_killed, &n_notkilled);
  1876. do_stop_summary(retry_nr++);
  1877. if (!n_killed)
  1878. return finish_stop_schedule(anykilled);
  1879. else
  1880. anykilled = true;
  1881. continue;
  1882. case sched_timeout:
  1883. if (do_stop_timeout(value, &n_killed, &n_notkilled))
  1884. return finish_stop_schedule(anykilled);
  1885. else
  1886. continue;
  1887. default:
  1888. assert(!"schedule[].type value must be valid");
  1889. }
  1890. }
  1891. if (quietmode <= 0)
  1892. printf("Program %s, %d process(es), refused to die.\n",
  1893. what_stop, n_killed);
  1894. return 2;
  1895. }
  1896. int
  1897. main(int argc, char **argv)
  1898. {
  1899. progname = argv[0];
  1900. parse_options(argc, argv);
  1901. setup_options();
  1902. argc -= optind;
  1903. argv += optind;
  1904. if (action == ACTION_START)
  1905. do_start(argc, argv);
  1906. if (action == ACTION_STOP) {
  1907. int i = run_stop_schedule();
  1908. exit(i);
  1909. }
  1910. if (action == ACTION_STATUS) {
  1911. enum status_code prog_status;
  1912. prog_status = do_findprocs();
  1913. exit(prog_status);
  1914. }
  1915. return 0;
  1916. }