start-stop-daemon.c 50 KB

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