start-stop-daemon.c 38 KB

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