start-stop-daemon.c 46 KB

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