start-stop-daemon.c 30 KB

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