start-stop-daemon.c 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804
  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. int fd;
  323. fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW, 0666);
  324. if (fd < 0)
  325. fp = NULL;
  326. else
  327. fp = fdopen(fd, "w");
  328. if (fp == NULL)
  329. fatal("unable to open pidfile '%s' for writing", filename);
  330. fprintf(fp, "%d\n", pid);
  331. if (fclose(fp))
  332. fatal("unable to close pidfile '%s'", filename);
  333. }
  334. static void
  335. pid_list_push(struct pid_list **list, pid_t pid)
  336. {
  337. struct pid_list *p;
  338. p = xmalloc(sizeof(*p));
  339. p->next = *list;
  340. p->pid = pid;
  341. *list = p;
  342. }
  343. static void
  344. pid_list_free(struct pid_list **list)
  345. {
  346. struct pid_list *here, *next;
  347. for (here = *list; here != NULL; here = next) {
  348. next = here->next;
  349. free(here);
  350. }
  351. *list = NULL;
  352. }
  353. static void
  354. usage(void)
  355. {
  356. printf(
  357. "Usage: start-stop-daemon [<option> ...] <command>\n"
  358. "\n"
  359. "Commands:\n"
  360. " -S|--start -- <argument> ... start a program and pass <arguments> to it\n"
  361. " -K|--stop stop a program\n"
  362. " -T|--status get the program status\n"
  363. " -H|--help print help information\n"
  364. " -V|--version print version\n"
  365. "\n"
  366. "Matching options (at least one is required):\n"
  367. " -p|--pidfile <pid-file> pid file to check\n"
  368. " -x|--exec <executable> program to start/check if it is running\n"
  369. " -n|--name <process-name> process name to check\n"
  370. " -u|--user <username|uid> process owner to check\n"
  371. "\n"
  372. "Options:\n"
  373. " -g|--group <group|gid> run process as this group\n"
  374. " -c|--chuid <name|uid[:group|gid]>\n"
  375. " change to this user/group before starting\n"
  376. " process\n"
  377. " -s|--signal <signal> signal to send (default TERM)\n"
  378. " -a|--startas <pathname> program to start (default is <executable>)\n"
  379. " -r|--chroot <directory> chroot to <directory> before starting\n"
  380. " -d|--chdir <directory> change to <directory> (default is /)\n"
  381. " -N|--nicelevel <incr> add incr to the process' nice level\n"
  382. " -P|--procsched <policy[:prio]>\n"
  383. " use <policy> with <prio> for the kernel\n"
  384. " process scheduler (default prio is 0)\n"
  385. " -I|--iosched <class[:prio]> use <class> with <prio> to set the IO\n"
  386. " scheduler (default prio is 4)\n"
  387. " -k|--umask <mask> change the umask to <mask> before starting\n"
  388. " -b|--background force the process to detach\n"
  389. " -m|--make-pidfile create the pidfile before starting\n"
  390. " -R|--retry <schedule> check whether processes die, and retry\n"
  391. " -t|--test test mode, don't do anything\n"
  392. " -o|--oknodo exit status 0 (not 1) if nothing done\n"
  393. " -q|--quiet be more quiet\n"
  394. " -v|--verbose be more verbose\n"
  395. "\n"
  396. "Retry <schedule> is <item>|/<item>/... where <item> is one of\n"
  397. " -<signal-num>|[-]<signal-name> send that signal\n"
  398. " <timeout> wait that many seconds\n"
  399. " forever repeat remainder forever\n"
  400. "or <schedule> may be just <timeout>, meaning <signal>/<timeout>/KILL/<timeout>\n"
  401. "\n"
  402. "The process scheduler <policy> can be one of:\n"
  403. " other, fifo or rr\n"
  404. "\n"
  405. "The IO scheduler <class> can be one of:\n"
  406. " real-time, best-effort or idle\n"
  407. "\n"
  408. "Exit status:\n"
  409. " 0 = done\n"
  410. " 1 = nothing done (=> 0 if --oknodo)\n"
  411. " 2 = with --retry, processes would not die\n"
  412. " 3 = trouble\n"
  413. "Exit status with --status:\n"
  414. " 0 = program is running\n"
  415. " 1 = program is not running and the pid file exists\n"
  416. " 3 = program is not running\n"
  417. " 4 = unable to determine status\n");
  418. }
  419. static void
  420. do_version(void)
  421. {
  422. printf("start-stop-daemon %s for Debian\n\n", VERSION);
  423. printf("Written by Marek Michalkiewicz, public domain.\n");
  424. }
  425. static void DPKG_ATTR_NORET
  426. badusage(const char *msg)
  427. {
  428. if (msg)
  429. fprintf(stderr, "%s: %s\n", progname, msg);
  430. fprintf(stderr, "Try '%s --help' for more information.\n", progname);
  431. if (action == action_status)
  432. exit(status_unknown);
  433. else
  434. exit(3);
  435. }
  436. struct sigpair {
  437. const char *name;
  438. int signal;
  439. };
  440. static const struct sigpair siglist[] = {
  441. { "ABRT", SIGABRT },
  442. { "ALRM", SIGALRM },
  443. { "FPE", SIGFPE },
  444. { "HUP", SIGHUP },
  445. { "ILL", SIGILL },
  446. { "INT", SIGINT },
  447. { "KILL", SIGKILL },
  448. { "PIPE", SIGPIPE },
  449. { "QUIT", SIGQUIT },
  450. { "SEGV", SIGSEGV },
  451. { "TERM", SIGTERM },
  452. { "USR1", SIGUSR1 },
  453. { "USR2", SIGUSR2 },
  454. { "CHLD", SIGCHLD },
  455. { "CONT", SIGCONT },
  456. { "STOP", SIGSTOP },
  457. { "TSTP", SIGTSTP },
  458. { "TTIN", SIGTTIN },
  459. { "TTOU", SIGTTOU }
  460. };
  461. static int
  462. parse_unsigned(const char *string, int base, int *value_r)
  463. {
  464. long value;
  465. char *endptr;
  466. if (!string[0])
  467. return -1;
  468. errno = 0;
  469. value = strtol(string, &endptr, base);
  470. if (string == endptr || *endptr != '\0' || errno != 0)
  471. return -1;
  472. if (value < 0 || value > INT_MAX)
  473. return -1;
  474. *value_r = value;
  475. return 0;
  476. }
  477. static int
  478. parse_signal(const char *sig_str, int *sig_num)
  479. {
  480. unsigned int i;
  481. if (parse_unsigned(sig_str, 10, sig_num) == 0)
  482. return 0;
  483. for (i = 0; i < array_count(siglist); i++) {
  484. if (strcmp(sig_str, siglist[i].name) == 0) {
  485. *sig_num = siglist[i].signal;
  486. return 0;
  487. }
  488. }
  489. return -1;
  490. }
  491. static int
  492. parse_umask(const char *string, int *value_r)
  493. {
  494. return parse_unsigned(string, 0, value_r);
  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_unsigned(prio_str, 10, &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_unsigned(prio_str, 10, &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_unsigned(string, 10, &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. }