start-stop-daemon.c 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  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 aswell.
  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. #if defined(linux) || (defined(__FreeBSD_kernel__) && defined(__GLIBC__))
  24. # define OSLinux
  25. #elif defined(__GNU__)
  26. # define OSHURD
  27. #elif defined(__sparc__)
  28. # define OSsunos
  29. #elif defined(OPENBSD) || defined(__OpenBSD__)
  30. # define OSOpenBSD
  31. #elif defined(hpux)
  32. # define OShpux
  33. #elif defined(__FreeBSD__)
  34. # define OSFreeBSD
  35. #elif defined(__NetBSD__)
  36. # define OSNetBSD
  37. #else
  38. # error Unknown architecture - cannot build start-stop-daemon
  39. #endif
  40. #define MIN_POLL_INTERVAL 20000 /*us*/
  41. #if defined(OSHURD)
  42. # include <hurd.h>
  43. # include <ps.h>
  44. #endif
  45. #if defined(OSOpenBSD) || defined(OSFreeBSD) || defined(OSNetBSD)
  46. #include <sys/param.h>
  47. #include <sys/proc.h>
  48. #include <sys/stat.h>
  49. #include <sys/types.h>
  50. #include <err.h>
  51. #include <limits.h>
  52. #endif
  53. #ifdef HAVE_KVM_H
  54. #include <kvm.h>
  55. #include <sys/sysctl.h>
  56. #include <sys/user.h>
  57. #endif
  58. #if defined(OShpux)
  59. #include <sys/param.h>
  60. #include <sys/pstat.h>
  61. #endif
  62. #include <errno.h>
  63. #include <stdio.h>
  64. #include <stdlib.h>
  65. #include <string.h>
  66. #include <stdarg.h>
  67. #include <signal.h>
  68. #include <sys/stat.h>
  69. #include <dirent.h>
  70. #include <sys/time.h>
  71. #include <unistd.h>
  72. #include <getopt.h>
  73. #include <pwd.h>
  74. #include <grp.h>
  75. #include <sys/ioctl.h>
  76. #include <sys/types.h>
  77. #include <sys/termios.h>
  78. #include <fcntl.h>
  79. #include <limits.h>
  80. #include <assert.h>
  81. #include <ctype.h>
  82. #ifdef HAVE_SYS_CDEFS_H
  83. #include <sys/cdefs.h>
  84. #endif
  85. #ifdef HAVE_STDDEF_H
  86. #include <stddef.h>
  87. #endif
  88. #ifdef HAVE_ERROR_H
  89. # include <error.h>
  90. #endif
  91. #if HAVE_C_ATTRIBUTE
  92. # define CONSTANT __attribute__((constant))
  93. # define PRINTFFORMAT(si, tc) __attribute__((format(printf,si,tc)))
  94. # define NONRETURNING __attribute__((noreturn))
  95. # define UNUSED __attribute__((unused))
  96. # define NONRETURNPRINTFFORMAT(si, tc) __attribute__((format(printf,si,tc),noreturn))
  97. #else
  98. # define CONSTANT
  99. # define PRINTFFORMAT(si, tc)
  100. # define NONRETURNING
  101. # define UNUSED
  102. # define NONRETURNPRINTFFORMAT(si, tc)
  103. #endif
  104. static int testmode = 0;
  105. static int quietmode = 0;
  106. static int exitnodo = 1;
  107. static int start = 0;
  108. static int stop = 0;
  109. static int background = 0;
  110. static int mpidfile = 0;
  111. static int signal_nr = 15;
  112. static const char *signal_str = NULL;
  113. static int user_id = -1;
  114. static int runas_uid = -1;
  115. static int runas_gid = -1;
  116. static const char *userspec = NULL;
  117. static char *changeuser = NULL;
  118. static const char *changegroup = NULL;
  119. static char *changeroot = NULL;
  120. static const char *changedir = "/";
  121. static const char *cmdname = NULL;
  122. static char *execname = NULL;
  123. static char *startas = NULL;
  124. static const char *pidfile = NULL;
  125. static char what_stop[1024];
  126. static const char *schedule_str = NULL;
  127. static const char *progname = "";
  128. static int nicelevel = 0;
  129. static struct stat exec_stat;
  130. #if defined(OSHURD)
  131. static struct proc_stat_list *procset = NULL;
  132. #endif
  133. struct pid_list {
  134. struct pid_list *next;
  135. pid_t pid;
  136. };
  137. static struct pid_list *found = NULL;
  138. static struct pid_list *killed = NULL;
  139. struct schedule_item {
  140. enum { sched_timeout, sched_signal, sched_goto, sched_forever } type;
  141. int value; /* seconds, signal no., or index into array */
  142. /* sched_forever is only seen within parse_schedule and callees */
  143. };
  144. static int schedule_length;
  145. static struct schedule_item *schedule = NULL;
  146. static void *xmalloc(int size);
  147. static void push(struct pid_list **list, pid_t pid);
  148. static void do_help(void);
  149. static void parse_options(int argc, char * const *argv);
  150. static int pid_is_user(pid_t pid, uid_t uid);
  151. static int pid_is_cmd(pid_t pid, const char *name);
  152. static void check(pid_t pid);
  153. static void do_pidfile(const char *name);
  154. static void do_stop(int signal_nr, int quietmode,
  155. int *n_killed, int *n_notkilled, int retry_nr);
  156. #if defined(OSLinux) || defined(OShpux)
  157. static int pid_is_exec(pid_t pid, const struct stat *esb);
  158. #endif
  159. #ifdef __GNUC__
  160. static void fatal(const char *format, ...)
  161. NONRETURNPRINTFFORMAT(1, 2);
  162. static void badusage(const char *msg)
  163. NONRETURNING;
  164. #else
  165. static void fatal(const char *format, ...);
  166. static void badusage(const char *msg);
  167. #endif
  168. /* This next part serves only to construct the TVCALC macro, which
  169. * is used for doing arithmetic on struct timeval's. It works like this:
  170. * TVCALC(result, expression);
  171. * where result is a struct timeval (and must be an lvalue) and
  172. * expression is the single expression for both components. In this
  173. * expression you can use the special values TVELEM, which when fed a
  174. * const struct timeval* gives you the relevant component, and
  175. * TVADJUST. TVADJUST is necessary when subtracting timevals, to make
  176. * it easier to renormalise. Whenver you subtract timeval elements,
  177. * you must make sure that TVADJUST is added to the result of the
  178. * subtraction (before any resulting multiplication or what have you).
  179. * TVELEM must be linear in TVADJUST.
  180. */
  181. typedef long tvselector(const struct timeval*);
  182. static long tvselector_sec(const struct timeval *tv) { return tv->tv_sec; }
  183. static long tvselector_usec(const struct timeval *tv) { return tv->tv_usec; }
  184. #define TVCALC_ELEM(result, expr, sec, adj) \
  185. { \
  186. const long TVADJUST = adj; \
  187. long (*const TVELEM)(const struct timeval*) = tvselector_##sec; \
  188. (result).tv_##sec = (expr); \
  189. }
  190. #define TVCALC(result,expr) \
  191. do { \
  192. TVCALC_ELEM(result, expr, sec, (-1)); \
  193. TVCALC_ELEM(result, expr, usec, (+1000000)); \
  194. (result).tv_sec += (result).tv_usec / 1000000; \
  195. (result).tv_usec %= 1000000; \
  196. } while(0)
  197. static void
  198. fatal(const char *format, ...)
  199. {
  200. va_list arglist;
  201. fprintf(stderr, "%s: ", progname);
  202. va_start(arglist, format);
  203. vfprintf(stderr, format, arglist);
  204. va_end(arglist);
  205. fprintf(stderr, " (%s)\n", strerror (errno));
  206. exit(2);
  207. }
  208. static void *
  209. xmalloc(int size)
  210. {
  211. void *ptr;
  212. ptr = malloc(size);
  213. if (ptr)
  214. return ptr;
  215. fatal("malloc(%d) failed", size);
  216. }
  217. static void
  218. xgettimeofday(struct timeval *tv)
  219. {
  220. if (gettimeofday(tv,0) != 0)
  221. fatal("gettimeofday failed: %s", strerror(errno));
  222. }
  223. static void
  224. push(struct pid_list **list, pid_t pid)
  225. {
  226. struct pid_list *p;
  227. p = xmalloc(sizeof(*p));
  228. p->next = *list;
  229. p->pid = pid;
  230. *list = p;
  231. }
  232. static void
  233. clear(struct pid_list **list)
  234. {
  235. struct pid_list *here, *next;
  236. for (here = *list; here != NULL; here = next) {
  237. next = here->next;
  238. free(here);
  239. }
  240. *list = NULL;
  241. }
  242. static void
  243. do_help(void)
  244. {
  245. printf(
  246. "start-stop-daemon %s for Debian - small and fast C version written by\n"
  247. "Marek Michalkiewicz <marekm@i17linuxb.ists.pwr.wroc.pl>, public domain.\n"
  248. "\n"
  249. "Usage: start-stop-daemon [<option> ...] <command>\n"
  250. "\n"
  251. "Commands:\n"
  252. " -S|--start -- <argument> ... start a program and pass <arguments> to it\n"
  253. " -K|--stop stop a program\n"
  254. " -H|--help print help information\n"
  255. " -V|--version print version\n"
  256. "\n"
  257. "Options (at least one of --exec|--pidfile|--user is required):\n"
  258. " -x|--exec <executable> program to start/check if it is running\n"
  259. " -p|--pidfile <pid-file> pid file to check\n"
  260. " -c|--chuid <name|uid[:group|gid]>\n"
  261. " change to this user/group before starting\n"
  262. " process\n"
  263. " -u|--user <username>|<uid> stop processes owned by this user\n"
  264. " -g|--group <group|gid> run process as this group\n"
  265. " -n|--name <process-name> stop processes with this name\n"
  266. " -s|--signal <signal> signal to send (default TERM)\n"
  267. " -a|--startas <pathname> program to start (default is <executable>)\n"
  268. " -r|--chroot <directory> chroot to <directory> before starting\n"
  269. " -d|--chdir <directory> change to <directory> (default is /)\n"
  270. " -N|--nicelevel <incr> add incr to the process's nice level\n"
  271. " -b|--background force the process to detach\n"
  272. " -m|--make-pidfile create the pidfile before starting\n"
  273. " -R|--retry <schedule> check whether processes die, and retry\n"
  274. " -t|--test test mode, don't do anything\n"
  275. " -o|--oknodo exit status 0 (not 1) if nothing done\n"
  276. " -q|--quiet be more quiet\n"
  277. " -v|--verbose be more verbose\n"
  278. "\n"
  279. "Retry <schedule> is <item>|/<item>/... where <item> is one of\n"
  280. " -<signal-num>|[-]<signal-name> send that signal\n"
  281. " <timeout> wait that many seconds\n"
  282. " forever repeat remainder forever\n"
  283. "or <schedule> may be just <timeout>, meaning <signal>/<timeout>/KILL/<timeout>\n"
  284. "\n"
  285. "Exit status: 0 = done 1 = nothing done (=> 0 if --oknodo)\n"
  286. " 3 = trouble 2 = with --retry, processes wouldn't die\n",
  287. VERSION);
  288. }
  289. static void
  290. badusage(const char *msg)
  291. {
  292. if (msg)
  293. fprintf(stderr, "%s: %s\n", progname, msg);
  294. fprintf(stderr, "Try `%s --help' for more information.\n", progname);
  295. exit(3);
  296. }
  297. struct sigpair {
  298. const char *name;
  299. int signal;
  300. };
  301. const struct sigpair siglist[] = {
  302. { "ABRT", SIGABRT },
  303. { "ALRM", SIGALRM },
  304. { "FPE", SIGFPE },
  305. { "HUP", SIGHUP },
  306. { "ILL", SIGILL },
  307. { "INT", SIGINT },
  308. { "KILL", SIGKILL },
  309. { "PIPE", SIGPIPE },
  310. { "QUIT", SIGQUIT },
  311. { "SEGV", SIGSEGV },
  312. { "TERM", SIGTERM },
  313. { "USR1", SIGUSR1 },
  314. { "USR2", SIGUSR2 },
  315. { "CHLD", SIGCHLD },
  316. { "CONT", SIGCONT },
  317. { "STOP", SIGSTOP },
  318. { "TSTP", SIGTSTP },
  319. { "TTIN", SIGTTIN },
  320. { "TTOU", SIGTTOU }
  321. };
  322. static int parse_integer(const char *string, int *value_r) {
  323. unsigned long ul;
  324. char *ep;
  325. if (!string[0])
  326. return -1;
  327. ul= strtoul(string,&ep,10);
  328. if (ul > INT_MAX || *ep != '\0')
  329. return -1;
  330. *value_r= ul;
  331. return 0;
  332. }
  333. static int parse_signal(const char *signal_str, int *signal_nr)
  334. {
  335. unsigned int i;
  336. if (parse_integer(signal_str, signal_nr) == 0)
  337. return 0;
  338. for (i = 0; i < sizeof (siglist) / sizeof (siglist[0]); i++) {
  339. if (strcmp (signal_str, siglist[i].name) == 0) {
  340. *signal_nr = siglist[i].signal;
  341. return 0;
  342. }
  343. }
  344. return -1;
  345. }
  346. static void
  347. parse_schedule_item(const char *string, struct schedule_item *item) {
  348. const char *after_hyph;
  349. if (!strcmp(string,"forever")) {
  350. item->type = sched_forever;
  351. } else if (isdigit(string[0])) {
  352. item->type = sched_timeout;
  353. if (parse_integer(string, &item->value) != 0)
  354. badusage("invalid timeout value in schedule");
  355. } else if ((after_hyph = string + (string[0] == '-')) &&
  356. parse_signal(after_hyph, &item->value) == 0) {
  357. item->type = sched_signal;
  358. } else {
  359. badusage("invalid schedule item (must be [-]<signal-name>, "
  360. "-<signal-number>, <timeout> or `forever'");
  361. }
  362. }
  363. static void
  364. parse_schedule(const char *schedule_str) {
  365. char item_buf[20];
  366. const char *slash;
  367. int count, repeatat;
  368. ptrdiff_t str_len;
  369. count = 0;
  370. for (slash = schedule_str; *slash; slash++)
  371. if (*slash == '/')
  372. count++;
  373. schedule_length = (count == 0) ? 4 : count+1;
  374. schedule = xmalloc(sizeof(*schedule) * schedule_length);
  375. if (count == 0) {
  376. schedule[0].type = sched_signal;
  377. schedule[0].value = signal_nr;
  378. parse_schedule_item(schedule_str, &schedule[1]);
  379. if (schedule[1].type != sched_timeout) {
  380. badusage ("--retry takes timeout, or schedule list"
  381. " of at least two items");
  382. }
  383. schedule[2].type = sched_signal;
  384. schedule[2].value = SIGKILL;
  385. schedule[3]= schedule[1];
  386. } else {
  387. count = 0;
  388. repeatat = -1;
  389. while (schedule_str != NULL) {
  390. slash = strchr(schedule_str,'/');
  391. str_len = slash ? slash - schedule_str : strlen(schedule_str);
  392. if (str_len >= (ptrdiff_t)sizeof(item_buf))
  393. badusage("invalid schedule item: far too long"
  394. " (you must delimit items with slashes)");
  395. memcpy(item_buf, schedule_str, str_len);
  396. item_buf[str_len] = 0;
  397. schedule_str = slash ? slash+1 : NULL;
  398. parse_schedule_item(item_buf, &schedule[count]);
  399. if (schedule[count].type == sched_forever) {
  400. if (repeatat >= 0)
  401. badusage("invalid schedule: `forever'"
  402. " appears more than once");
  403. repeatat = count;
  404. continue;
  405. }
  406. count++;
  407. }
  408. if (repeatat >= 0) {
  409. schedule[count].type = sched_goto;
  410. schedule[count].value = repeatat;
  411. count++;
  412. }
  413. assert(count == schedule_length);
  414. }
  415. }
  416. static void
  417. parse_options(int argc, char * const *argv)
  418. {
  419. static struct option longopts[] = {
  420. { "help", 0, NULL, 'H'},
  421. { "stop", 0, NULL, 'K'},
  422. { "start", 0, NULL, 'S'},
  423. { "version", 0, NULL, 'V'},
  424. { "startas", 1, NULL, 'a'},
  425. { "name", 1, NULL, 'n'},
  426. { "oknodo", 0, NULL, 'o'},
  427. { "pidfile", 1, NULL, 'p'},
  428. { "quiet", 0, NULL, 'q'},
  429. { "signal", 1, NULL, 's'},
  430. { "test", 0, NULL, 't'},
  431. { "user", 1, NULL, 'u'},
  432. { "group", 1, NULL, 'g'},
  433. { "chroot", 1, NULL, 'r'},
  434. { "verbose", 0, NULL, 'v'},
  435. { "exec", 1, NULL, 'x'},
  436. { "chuid", 1, NULL, 'c'},
  437. { "nicelevel", 1, NULL, 'N'},
  438. { "background", 0, NULL, 'b'},
  439. { "make-pidfile", 0, NULL, 'm'},
  440. { "retry", 1, NULL, 'R'},
  441. { "chdir", 1, NULL, 'd'},
  442. { NULL, 0, NULL, 0}
  443. };
  444. int c;
  445. for (;;) {
  446. c = getopt_long(argc, argv, "HKSVa:n:op:qr:s:tu:vx:c:N:bmR:g:d:",
  447. longopts, (int *) 0);
  448. if (c == -1)
  449. break;
  450. switch (c) {
  451. case 'H': /* --help */
  452. do_help();
  453. exit(0);
  454. case 'K': /* --stop */
  455. stop = 1;
  456. break;
  457. case 'S': /* --start */
  458. start = 1;
  459. break;
  460. case 'V': /* --version */
  461. printf("start-stop-daemon " VERSION "\n");
  462. exit(0);
  463. case 'a': /* --startas <pathname> */
  464. startas = optarg;
  465. break;
  466. case 'n': /* --name <process-name> */
  467. cmdname = optarg;
  468. break;
  469. case 'o': /* --oknodo */
  470. exitnodo = 0;
  471. break;
  472. case 'p': /* --pidfile <pid-file> */
  473. pidfile = optarg;
  474. break;
  475. case 'q': /* --quiet */
  476. quietmode = 1;
  477. break;
  478. case 's': /* --signal <signal> */
  479. signal_str = optarg;
  480. break;
  481. case 't': /* --test */
  482. testmode = 1;
  483. break;
  484. case 'u': /* --user <username>|<uid> */
  485. userspec = optarg;
  486. break;
  487. case 'v': /* --verbose */
  488. quietmode = -1;
  489. break;
  490. case 'x': /* --exec <executable> */
  491. execname = optarg;
  492. break;
  493. case 'c': /* --chuid <username>|<uid> */
  494. /* we copy the string just in case we need the
  495. * argument later. */
  496. changeuser = strdup(optarg);
  497. changeuser = strtok(changeuser, ":");
  498. changegroup = strtok(NULL, ":");
  499. break;
  500. case 'g': /* --group <group>|<gid> */
  501. changegroup = optarg;
  502. break;
  503. case 'r': /* --chroot /new/root */
  504. changeroot = optarg;
  505. break;
  506. case 'N': /* --nice */
  507. nicelevel = atoi(optarg);
  508. break;
  509. case 'b': /* --background */
  510. background = 1;
  511. break;
  512. case 'm': /* --make-pidfile */
  513. mpidfile = 1;
  514. break;
  515. case 'R': /* --retry <schedule>|<timeout> */
  516. schedule_str = optarg;
  517. break;
  518. case 'd': /* --chdir /new/dir */
  519. changedir = optarg;
  520. break;
  521. default:
  522. badusage(NULL); /* message printed by getopt */
  523. }
  524. }
  525. if (signal_str != NULL) {
  526. if (parse_signal (signal_str, &signal_nr) != 0)
  527. badusage("signal value must be numeric or name"
  528. " of signal (KILL, INT, ...)");
  529. }
  530. if (schedule_str != NULL) {
  531. parse_schedule(schedule_str);
  532. }
  533. if (start == stop)
  534. badusage("need one of --start or --stop");
  535. if (!execname && !pidfile && !userspec && !cmdname)
  536. badusage("need at least one of --exec, --pidfile, --user or --name");
  537. if (!startas)
  538. startas = execname;
  539. if (start && !startas)
  540. badusage("--start needs --exec or --startas");
  541. if (mpidfile && pidfile == NULL)
  542. badusage("--make-pidfile is only relevant with --pidfile");
  543. if (background && !start)
  544. badusage("--background is only relevant with --start");
  545. }
  546. #if defined(OSLinux)
  547. static int
  548. pid_is_exec(pid_t pid, const struct stat *esb)
  549. {
  550. char lname[32];
  551. char lcontents[_POSIX_PATH_MAX];
  552. const char deleted[] = " (deleted)";
  553. int nread;
  554. struct stat sb;
  555. sprintf(lname, "/proc/%d/exe", pid);
  556. nread = readlink(lname, lcontents, sizeof(lcontents));
  557. if (nread == -1)
  558. return 0;
  559. lcontents[nread] = '\0';
  560. if (strcmp(lcontents + nread - strlen(deleted), deleted) == 0)
  561. lcontents[nread - strlen(deleted)] = '\0';
  562. if (stat(lcontents, &sb) != 0)
  563. return 0;
  564. return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  565. }
  566. static int
  567. pid_is_user(pid_t pid, uid_t uid)
  568. {
  569. struct stat sb;
  570. char buf[32];
  571. sprintf(buf, "/proc/%d", pid);
  572. if (stat(buf, &sb) != 0)
  573. return 0;
  574. return (sb.st_uid == uid);
  575. }
  576. static int
  577. pid_is_cmd(pid_t pid, const char *name)
  578. {
  579. char buf[32];
  580. FILE *f;
  581. int c;
  582. sprintf(buf, "/proc/%d/stat", pid);
  583. f = fopen(buf, "r");
  584. if (!f)
  585. return 0;
  586. while ((c = getc(f)) != EOF && c != '(')
  587. ;
  588. if (c != '(') {
  589. fclose(f);
  590. return 0;
  591. }
  592. /* this hopefully handles command names containing ')' */
  593. while ((c = getc(f)) != EOF && c == *name)
  594. name++;
  595. fclose(f);
  596. return (c == ')' && *name == '\0');
  597. }
  598. #endif /* OSLinux */
  599. #if defined(OSHURD)
  600. static void
  601. init_procset(void)
  602. {
  603. struct ps_context *context;
  604. error_t err;
  605. err = ps_context_create(getproc(), &context);
  606. if (err)
  607. error(1, err, "ps_context_create");
  608. err = proc_stat_list_create(context, &procset);
  609. if (err)
  610. error(1, err, "proc_stat_list_create");
  611. err = proc_stat_list_add_all(procset, 0, 0);
  612. if (err)
  613. error(1, err, "proc_stat_list_add_all");
  614. }
  615. static struct proc_stat *
  616. get_proc_stat (pid_t pid, ps_flags_t flags)
  617. {
  618. struct proc_stat *ps;
  619. ps_flags_t wanted_flags = PSTAT_PID | flags;
  620. if (!procset)
  621. init_procset();
  622. ps = proc_stat_list_pid_proc_stat(procset, pid);
  623. if (!ps)
  624. return NULL;
  625. if (proc_stat_set_flags(ps, wanted_flags))
  626. return NULL;
  627. if ((proc_stat_flags(ps) & wanted_flags) != wanted_flags)
  628. return NULL;
  629. return ps;
  630. }
  631. static int
  632. pid_is_user(pid_t pid, uid_t uid)
  633. {
  634. struct proc_stat *ps;
  635. ps = get_proc_stat(pid, PSTAT_OWNER_UID);
  636. return ps && proc_stat_owner_uid(ps) == uid;
  637. }
  638. static int
  639. pid_is_cmd(pid_t pid, const char *name)
  640. {
  641. struct proc_stat *ps;
  642. ps = get_proc_stat(pid, PSTAT_ARGS);
  643. return ps && !strcmp(proc_stat_args(ps), name);
  644. }
  645. static int
  646. pid_is_running(pid_t pid)
  647. {
  648. return get_proc_stat(pid, 0) != NULL;
  649. }
  650. #else /* !OSHURD */
  651. static int
  652. pid_is_running(pid_t pid)
  653. {
  654. struct stat sb;
  655. char buf[32];
  656. sprintf(buf, "/proc/%d", pid);
  657. if (stat(buf, &sb) != 0) {
  658. if (errno!=ENOENT)
  659. fatal("Error stating %s: %s", buf, strerror(errno));
  660. return 0;
  661. }
  662. return 1;
  663. }
  664. #endif /* OSHURD */
  665. static void
  666. check(pid_t pid)
  667. {
  668. #if defined(OSLinux) || defined(OShpux)
  669. if (execname && !pid_is_exec(pid, &exec_stat))
  670. #elif defined(OSHURD) || defined(OSFreeBSD) || defined(OSNetBSD)
  671. /* I will try this to see if it works */
  672. if (execname && !pid_is_cmd(pid, execname))
  673. #endif
  674. return;
  675. if (userspec && !pid_is_user(pid, user_id))
  676. return;
  677. if (cmdname && !pid_is_cmd(pid, cmdname))
  678. return;
  679. if (start && !pid_is_running(pid))
  680. return;
  681. push(&found, pid);
  682. }
  683. static void
  684. do_pidfile(const char *name)
  685. {
  686. FILE *f;
  687. pid_t pid;
  688. f = fopen(name, "r");
  689. if (f) {
  690. if (fscanf(f, "%d", &pid) == 1)
  691. check(pid);
  692. fclose(f);
  693. } else if (errno != ENOENT)
  694. fatal("open pidfile %s: %s", name, strerror(errno));
  695. }
  696. /* WTA: this needs to be an autoconf check for /proc/pid existance.
  697. */
  698. #if defined(OSLinux) || defined (OSsunos)
  699. static void
  700. do_procinit(void)
  701. {
  702. DIR *procdir;
  703. struct dirent *entry;
  704. int foundany;
  705. pid_t pid;
  706. procdir = opendir("/proc");
  707. if (!procdir)
  708. fatal("opendir /proc: %s", strerror(errno));
  709. foundany = 0;
  710. while ((entry = readdir(procdir)) != NULL) {
  711. if (sscanf(entry->d_name, "%d", &pid) != 1)
  712. continue;
  713. foundany++;
  714. check(pid);
  715. }
  716. closedir(procdir);
  717. if (!foundany)
  718. fatal("nothing in /proc - not mounted?");
  719. }
  720. #endif /* OSLinux */
  721. #if defined(OSHURD)
  722. static int
  723. check_proc_stat (struct proc_stat *ps)
  724. {
  725. check(ps->pid);
  726. return 0;
  727. }
  728. static void
  729. do_procinit(void)
  730. {
  731. if (!procset)
  732. init_procset();
  733. proc_stat_list_for_each (procset, check_proc_stat);
  734. }
  735. #endif /* OSHURD */
  736. #ifdef HAVE_KVM_H
  737. static int
  738. pid_is_cmd(pid_t pid, const char *name)
  739. {
  740. kvm_t *kd;
  741. int nentries, argv_len=0;
  742. struct kinfo_proc *kp;
  743. char errbuf[_POSIX2_LINE_MAX], buf[_POSIX2_LINE_MAX];
  744. char **pid_argv_p;
  745. char *start_argv_0_p, *end_argv_0_p;
  746. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  747. if (kd == 0)
  748. errx(1, "%s", errbuf);
  749. if ((kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries)) == 0)
  750. errx(1, "%s", kvm_geterr(kd));
  751. if ((pid_argv_p = kvm_getargv(kd, kp, argv_len)) == 0)
  752. errx(1, "%s", kvm_geterr(kd));
  753. start_argv_0_p = *pid_argv_p;
  754. /* find and compare string */
  755. /* find end of argv[0] then copy and cut of str there. */
  756. if ((end_argv_0_p = strchr(*pid_argv_p, ' ')) == 0 )
  757. /* There seems to be no space, so we have the command
  758. * allready in its desired form. */
  759. start_argv_0_p = *pid_argv_p;
  760. else {
  761. /* Tests indicate that this never happens, since
  762. * kvm_getargv itselfe cuts of tailing stuff. This is
  763. * not what the manpage says, however. */
  764. strncpy(buf, *pid_argv_p, (end_argv_0_p - start_argv_0_p));
  765. buf[(end_argv_0_p - start_argv_0_p) + 1] = '\0';
  766. start_argv_0_p = buf;
  767. }
  768. if (strlen(name) != strlen(start_argv_0_p))
  769. return 0;
  770. return (strcmp(name, start_argv_0_p) == 0) ? 1 : 0;
  771. }
  772. static int
  773. pid_is_user(pid_t pid, uid_t uid)
  774. {
  775. kvm_t *kd;
  776. int nentries; /* Value not used */
  777. uid_t proc_uid;
  778. struct kinfo_proc *kp;
  779. char errbuf[_POSIX2_LINE_MAX];
  780. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  781. if (kd == 0)
  782. errx(1, "%s", errbuf);
  783. if ((kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries)) == 0)
  784. errx(1, "%s", kvm_geterr(kd));
  785. if (kp->kp_proc.p_cred )
  786. kvm_read(kd, (u_long)&(kp->kp_proc.p_cred->p_ruid),
  787. &proc_uid, sizeof(uid_t));
  788. else
  789. return 0;
  790. return (proc_uid == (uid_t)uid);
  791. }
  792. static int
  793. pid_is_exec(pid_t pid, const char *name)
  794. {
  795. kvm_t *kd;
  796. int nentries;
  797. struct kinfo_proc *kp;
  798. char errbuf[_POSIX2_LINE_MAX], *pidexec;
  799. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  800. if (kd == 0)
  801. errx(1, "%s", errbuf);
  802. if ((kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries)) == 0)
  803. errx(1, "%s", kvm_geterr(kd));
  804. pidexec = (&kp->kp_proc)->p_comm;
  805. if (strlen(name) != strlen(pidexec))
  806. return 0;
  807. return (strcmp(name, pidexec) == 0) ? 1 : 0;
  808. }
  809. static void
  810. do_procinit(void)
  811. {
  812. /* Nothing to do */
  813. }
  814. #endif /* OSOpenBSD */
  815. #if defined(OShpux)
  816. static int
  817. pid_is_user(pid_t pid, uid_t uid)
  818. {
  819. struct pst_status pst;
  820. if (pstat_getproc(&pst, sizeof(pst), (size_t) 0, (int) pid) < 0)
  821. return 0;
  822. return ((uid_t) pst.pst_uid == uid);
  823. }
  824. static int
  825. pid_is_cmd(pid_t pid, const char *name)
  826. {
  827. struct pst_status pst;
  828. if (pstat_getproc(&pst, sizeof(pst), (size_t) 0, (int) pid) < 0)
  829. return 0;
  830. return (strcmp(pst.pst_ucomm, name) == 0);
  831. }
  832. static int
  833. pid_is_exec(pid_t pid, const struct stat *esb)
  834. {
  835. struct pst_status pst;
  836. if (pstat_getproc(&pst, sizeof(pst), (size_t) 0, (int) pid) < 0)
  837. return 0;
  838. return ((dev_t) pst.pst_text.psf_fsid.psfs_id == esb->st_dev
  839. && (ino_t) pst.pst_text.psf_fileid == esb->st_ino);
  840. }
  841. static void
  842. do_procinit(void)
  843. {
  844. struct pst_status pst[10];
  845. int i, count;
  846. int idx = 0;
  847. while ((count = pstat_getproc(pst, sizeof(pst[0]), 10, idx)) > 0) {
  848. for (i = 0; i < count; i++)
  849. check(pst[i].pst_pid);
  850. idx = pst[count - 1].pst_idx + 1;
  851. }
  852. }
  853. #endif /* OShpux */
  854. static void
  855. do_findprocs(void)
  856. {
  857. clear(&found);
  858. if (pidfile)
  859. do_pidfile(pidfile);
  860. else
  861. do_procinit();
  862. }
  863. /* return 1 on failure */
  864. static void
  865. do_stop(int signal_nr, int quietmode, int *n_killed, int *n_notkilled, int retry_nr)
  866. {
  867. struct pid_list *p;
  868. do_findprocs();
  869. *n_killed = 0;
  870. *n_notkilled = 0;
  871. if (!found)
  872. return;
  873. clear(&killed);
  874. for (p = found; p; p = p->next) {
  875. if (testmode) {
  876. printf("Would send signal %d to %d.\n",
  877. signal_nr, p->pid);
  878. (*n_killed)++;
  879. } else if (kill(p->pid, signal_nr) == 0) {
  880. push(&killed, p->pid);
  881. (*n_killed)++;
  882. } else {
  883. printf("%s: warning: failed to kill %d: %s\n",
  884. progname, p->pid, strerror(errno));
  885. (*n_notkilled)++;
  886. }
  887. }
  888. if (quietmode < 0 && killed) {
  889. printf("Stopped %s (pid", what_stop);
  890. for (p = killed; p; p = p->next)
  891. printf(" %d", p->pid);
  892. putchar(')');
  893. if (retry_nr > 0)
  894. printf(", retry #%d", retry_nr);
  895. printf(".\n");
  896. }
  897. }
  898. static void
  899. set_what_stop(const char *str)
  900. {
  901. strncpy(what_stop, str, sizeof(what_stop));
  902. what_stop[sizeof(what_stop)-1] = '\0';
  903. }
  904. static int
  905. run_stop_schedule(void)
  906. {
  907. int r, position, n_killed, n_notkilled, value, ratio, anykilled, retry_nr;
  908. struct timeval stopat, before, after, interval, maxinterval;
  909. if (testmode) {
  910. if (schedule != NULL) {
  911. printf("Ignoring --retry in test mode\n");
  912. schedule = NULL;
  913. }
  914. }
  915. if (cmdname)
  916. set_what_stop(cmdname);
  917. else if (execname)
  918. set_what_stop(execname);
  919. else if (pidfile)
  920. sprintf(what_stop, "process in pidfile `%.200s'", pidfile);
  921. else if (userspec)
  922. sprintf(what_stop, "process(es) owned by `%.200s'", userspec);
  923. else
  924. fatal("internal error, please report");
  925. anykilled = 0;
  926. retry_nr = 0;
  927. if (schedule == NULL) {
  928. do_stop(signal_nr, quietmode, &n_killed, &n_notkilled, 0);
  929. if (n_notkilled > 0 && quietmode <= 0)
  930. printf("%d pids were not killed\n", n_notkilled);
  931. if (n_killed)
  932. anykilled = 1;
  933. goto x_finished;
  934. }
  935. for (position = 0; position < schedule_length; ) {
  936. value= schedule[position].value;
  937. n_notkilled = 0;
  938. switch (schedule[position].type) {
  939. case sched_goto:
  940. position = value;
  941. continue;
  942. case sched_signal:
  943. do_stop(value, quietmode, &n_killed, &n_notkilled, retry_nr++);
  944. if (!n_killed)
  945. goto x_finished;
  946. else
  947. anykilled = 1;
  948. goto next_item;
  949. case sched_timeout:
  950. /* We want to keep polling for the processes, to see if they've exited,
  951. * or until the timeout expires.
  952. *
  953. * This is a somewhat complicated algorithm to try to ensure that we
  954. * notice reasonably quickly when all the processes have exited, but
  955. * don't spend too much CPU time polling. In particular, on a fast
  956. * machine with quick-exiting daemons we don't want to delay system
  957. * shutdown too much, whereas on a slow one, or where processes are
  958. * taking some time to exit, we want to increase the polling
  959. * interval.
  960. *
  961. * The algorithm is as follows: we measure the elapsed time it takes
  962. * to do one poll(), and wait a multiple of this time for the next
  963. * poll. However, if that would put us past the end of the timeout
  964. * period we wait only as long as the timeout period, but in any case
  965. * we always wait at least MIN_POLL_INTERVAL (20ms). The multiple
  966. * (`ratio') starts out as 2, and increases by 1 for each poll to a
  967. * maximum of 10; so we use up to between 30% and 10% of the
  968. * machine's resources (assuming a few reasonable things about system
  969. * performance).
  970. */
  971. xgettimeofday(&stopat);
  972. stopat.tv_sec += value;
  973. ratio = 1;
  974. for (;;) {
  975. xgettimeofday(&before);
  976. if (timercmp(&before,&stopat,>))
  977. goto next_item;
  978. do_stop(0, 1, &n_killed, &n_notkilled, 0);
  979. if (!n_killed)
  980. goto x_finished;
  981. xgettimeofday(&after);
  982. if (!timercmp(&after,&stopat,<))
  983. goto next_item;
  984. if (ratio < 10)
  985. ratio++;
  986. TVCALC(interval, ratio * (TVELEM(&after) - TVELEM(&before) + TVADJUST));
  987. TVCALC(maxinterval, TVELEM(&stopat) - TVELEM(&after) + TVADJUST);
  988. if (timercmp(&interval,&maxinterval,>))
  989. interval = maxinterval;
  990. if (interval.tv_sec == 0 &&
  991. interval.tv_usec <= MIN_POLL_INTERVAL)
  992. interval.tv_usec = MIN_POLL_INTERVAL;
  993. r = select(0,0,0,0,&interval);
  994. if (r < 0 && errno != EINTR)
  995. fatal("select() failed for pause: %s",
  996. strerror(errno));
  997. }
  998. default:
  999. assert(!"schedule[].type value must be valid");
  1000. }
  1001. next_item:
  1002. position++;
  1003. }
  1004. if (quietmode <= 0)
  1005. printf("Program %s, %d process(es), refused to die.\n",
  1006. what_stop, n_killed);
  1007. return 2;
  1008. x_finished:
  1009. if (!anykilled) {
  1010. if (quietmode <= 0)
  1011. printf("No %s found running; none killed.\n", what_stop);
  1012. return exitnodo;
  1013. } else {
  1014. return 0;
  1015. }
  1016. }
  1017. int
  1018. main(int argc, char **argv)
  1019. {
  1020. int devnull_fd = -1;
  1021. #ifdef HAVE_TIOCNOTTY
  1022. int tty_fd = -1;
  1023. #endif
  1024. progname = argv[0];
  1025. parse_options(argc, argv);
  1026. argc -= optind;
  1027. argv += optind;
  1028. if (execname) {
  1029. char *fullexecname;
  1030. if (changeroot) {
  1031. int fullexecname_len = strlen(changeroot) + 1 +
  1032. strlen(execname) + 1;
  1033. fullexecname = xmalloc(fullexecname_len);
  1034. snprintf(fullexecname, fullexecname_len, "%s/%s",
  1035. changeroot, execname);
  1036. } else
  1037. fullexecname = execname;
  1038. if (stat(fullexecname, &exec_stat))
  1039. fatal("stat %s: %s", fullexecname, strerror(errno));
  1040. if (fullexecname != execname)
  1041. free(fullexecname);
  1042. }
  1043. if (userspec && sscanf(userspec, "%d", &user_id) != 1) {
  1044. struct passwd *pw;
  1045. pw = getpwnam(userspec);
  1046. if (!pw)
  1047. fatal("user `%s' not found\n", userspec);
  1048. user_id = pw->pw_uid;
  1049. }
  1050. if (changegroup && sscanf(changegroup, "%d", &runas_gid) != 1) {
  1051. struct group *gr = getgrnam(changegroup);
  1052. if (!gr)
  1053. fatal("group `%s' not found\n", changegroup);
  1054. runas_gid = gr->gr_gid;
  1055. }
  1056. if (changeuser && sscanf(changeuser, "%d", &runas_uid) != 1) {
  1057. struct passwd *pw = getpwnam(changeuser);
  1058. if (!pw)
  1059. fatal("user `%s' not found\n", changeuser);
  1060. runas_uid = pw->pw_uid;
  1061. if (changegroup == NULL) { /* pass the default group of this user */
  1062. changegroup = ""; /* just empty */
  1063. runas_gid = pw->pw_gid;
  1064. }
  1065. if (access(pw->pw_dir, F_OK) == 0)
  1066. setenv("HOME", pw->pw_dir, 1);
  1067. }
  1068. if (stop) {
  1069. int i = run_stop_schedule();
  1070. exit(i);
  1071. }
  1072. do_findprocs();
  1073. if (found) {
  1074. if (quietmode <= 0)
  1075. printf("%s already running.\n", execname ? execname : "process");
  1076. exit(exitnodo);
  1077. }
  1078. if (testmode) {
  1079. printf("Would start %s ", startas);
  1080. while (argc-- > 0)
  1081. printf("%s ", *argv++);
  1082. if (changeuser != NULL) {
  1083. printf(" (as user %s[%d]", changeuser, runas_uid);
  1084. if (changegroup != NULL)
  1085. printf(", and group %s[%d])", changegroup, runas_gid);
  1086. else
  1087. printf(")");
  1088. }
  1089. if (changeroot != NULL)
  1090. printf(" in directory %s", changeroot);
  1091. if (nicelevel)
  1092. printf(", and add %i to the priority", nicelevel);
  1093. printf(".\n");
  1094. exit(0);
  1095. }
  1096. if (quietmode < 0)
  1097. printf("Starting %s...\n", startas);
  1098. *--argv = startas;
  1099. if (background) { /* ok, we need to detach this process */
  1100. int i;
  1101. if (quietmode < 0)
  1102. printf("Detaching to start %s...", startas);
  1103. i = fork();
  1104. if (i<0) {
  1105. fatal("Unable to fork.\n");
  1106. }
  1107. if (i) { /* parent */
  1108. if (quietmode < 0)
  1109. printf("done.\n");
  1110. exit(0);
  1111. }
  1112. /* child continues here */
  1113. #ifdef HAVE_TIOCNOTTY
  1114. tty_fd=open("/dev/tty", O_RDWR);
  1115. #endif
  1116. devnull_fd=open("/dev/null", O_RDWR);
  1117. }
  1118. if (nicelevel) {
  1119. errno=0;
  1120. if ((nice(nicelevel)==-1) && (errno!=0))
  1121. fatal("Unable to alter nice level by %i: %s", nicelevel,
  1122. strerror(errno));
  1123. }
  1124. if (mpidfile && pidfile != NULL) { /* user wants _us_ to make the pidfile :) */
  1125. FILE *pidf = fopen(pidfile, "w");
  1126. pid_t pidt = getpid();
  1127. if (pidf == NULL)
  1128. fatal("Unable to open pidfile `%s' for writing: %s", pidfile,
  1129. strerror(errno));
  1130. fprintf(pidf, "%d\n", pidt);
  1131. fclose(pidf);
  1132. }
  1133. if (changeroot != NULL) {
  1134. if (chdir(changeroot) < 0)
  1135. fatal("Unable to chdir() to %s", changeroot);
  1136. if (chroot(changeroot) < 0)
  1137. fatal("Unable to chroot() to %s", changeroot);
  1138. }
  1139. if (chdir(changedir) < 0)
  1140. fatal("Unable to chdir() to %s", changedir);
  1141. if (changeuser != NULL) {
  1142. if (setgid(runas_gid))
  1143. fatal("Unable to set gid to %d", runas_gid);
  1144. if (initgroups(changeuser, runas_gid))
  1145. fatal("Unable to set initgroups() with gid %d", runas_gid);
  1146. if (setuid(runas_uid))
  1147. fatal("Unable to set uid to %s", changeuser);
  1148. }
  1149. if (background) { /* continue background setup */
  1150. int i;
  1151. #ifdef HAVE_TIOCNOTTY
  1152. /* change tty */
  1153. ioctl(tty_fd, TIOCNOTTY, 0);
  1154. close(tty_fd);
  1155. #endif
  1156. umask(022); /* set a default for dumb programs */
  1157. dup2(devnull_fd,0); /* stdin */
  1158. dup2(devnull_fd,1); /* stdout */
  1159. dup2(devnull_fd,2); /* stderr */
  1160. #if defined(OShpux)
  1161. /* now close all extra fds */
  1162. for (i=sysconf(_SC_OPEN_MAX)-1; i>=3; --i) close(i);
  1163. #else
  1164. /* now close all extra fds */
  1165. for (i=getdtablesize()-1; i>=3; --i) close(i);
  1166. #endif
  1167. /* create a new session */
  1168. #ifdef HAVE_SETSID
  1169. setsid();
  1170. #else
  1171. setpgid(0,0);
  1172. #endif
  1173. }
  1174. execv(startas, argv);
  1175. fatal("Unable to start %s: %s", startas, strerror(errno));
  1176. }