start-stop-daemon.c 44 KB

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