start-stop-daemon.c 41 KB

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