start-stop-daemon.c 41 KB

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