start-stop-daemon.c 47 KB

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