start-stop-daemon.c 40 KB

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