start-stop-daemon.c 41 KB

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