start-stop-daemon.c 30 KB

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