start-stop-daemon.c 48 KB

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