start-stop-daemon.c 38 KB

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