start-stop-daemon.c 31 KB

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