start-stop-daemon.c 48 KB

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