start-stop-daemon.c 41 KB

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