start-stop-daemon.c 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262
  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. else if (kill(p->pid, signal_nr) == 0) {
  819. push(&killed, p->pid);
  820. (*n_killed)++;
  821. } else {
  822. printf("%s: warning: failed to kill %d: %s\n",
  823. progname, p->pid, strerror(errno));
  824. (*n_notkilled)++;
  825. }
  826. }
  827. if (quietmode < 0 && killed) {
  828. printf("Stopped %s (pid", what_stop);
  829. for (p = killed; p; p = p->next)
  830. printf(" %d", p->pid);
  831. putchar(')');
  832. if (retry_nr > 0)
  833. printf(", retry #%d", retry_nr);
  834. printf(".\n");
  835. }
  836. }
  837. static void
  838. set_what_stop(const char *str)
  839. {
  840. strncpy(what_stop, str, sizeof(what_stop));
  841. what_stop[sizeof(what_stop)-1] = '\0';
  842. }
  843. static int
  844. run_stop_schedule(void)
  845. {
  846. int r, position, n_killed, n_notkilled, value, ratio, anykilled, retry_nr;
  847. struct timeval stopat, before, after, interval, maxinterval;
  848. if (testmode) {
  849. if (schedule != NULL) {
  850. printf("Ignoring --retry in test mode\n");
  851. schedule = NULL;
  852. }
  853. }
  854. if (cmdname)
  855. set_what_stop(cmdname);
  856. else if (execname)
  857. set_what_stop(execname);
  858. else if (pidfile)
  859. sprintf(what_stop, "process in pidfile `%.200s'", pidfile);
  860. else if (userspec)
  861. sprintf(what_stop, "process(es) owned by `%.200s'", userspec);
  862. else
  863. fatal("internal error, please report");
  864. anykilled = 0;
  865. retry_nr = 0;
  866. if (schedule == NULL) {
  867. do_stop(signal_nr, quietmode, &n_killed, &n_notkilled, 0);
  868. if (n_notkilled > 0 && quietmode <= 0)
  869. printf("%d pids were not killed\n", n_notkilled);
  870. if (n_killed)
  871. anykilled = 1;
  872. goto x_finished;
  873. }
  874. for (position = 0; position < schedule_length; ) {
  875. value= schedule[position].value;
  876. n_notkilled = 0;
  877. switch (schedule[position].type) {
  878. case sched_goto:
  879. position = value;
  880. continue;
  881. case sched_signal:
  882. do_stop(value, quietmode, &n_killed, &n_notkilled, retry_nr++);
  883. if (!n_killed)
  884. goto x_finished;
  885. else
  886. anykilled = 1;
  887. goto next_item;
  888. case sched_timeout:
  889. /* We want to keep polling for the processes, to see if they've exited,
  890. * or until the timeout expires.
  891. *
  892. * This is a somewhat complicated algorithm to try to ensure that we
  893. * notice reasonably quickly when all the processes have exited, but
  894. * don't spend too much CPU time polling. In particular, on a fast
  895. * machine with quick-exiting daemons we don't want to delay system
  896. * shutdown too much, whereas on a slow one, or where processes are
  897. * taking some time to exit, we want to increase the polling
  898. * interval.
  899. *
  900. * The algorithm is as follows: we measure the elapsed time it takes
  901. * to do one poll(), and wait a multiple of this time for the next
  902. * poll. However, if that would put us past the end of the timeout
  903. * period we wait only as long as the timeout period, but in any case
  904. * we always wait at least MIN_POLL_INTERVAL (20ms). The multiple
  905. * (`ratio') starts out as 2, and increases by 1 for each poll to a
  906. * maximum of 10; so we use up to between 30% and 10% of the
  907. * machine's resources (assuming a few reasonable things about system
  908. * performance).
  909. */
  910. xgettimeofday(&stopat);
  911. stopat.tv_sec += value;
  912. ratio = 1;
  913. for (;;) {
  914. xgettimeofday(&before);
  915. if (timercmp(&before,&stopat,>))
  916. goto next_item;
  917. do_stop(0, 1, &n_killed, &n_notkilled, 0);
  918. if (!n_killed)
  919. goto x_finished;
  920. xgettimeofday(&after);
  921. if (!timercmp(&after,&stopat,<))
  922. goto next_item;
  923. if (ratio < 10)
  924. ratio++;
  925. TVCALC(interval, ratio * (TVELEM(&after) - TVELEM(&before) + TVADJUST));
  926. TVCALC(maxinterval, TVELEM(&stopat) - TVELEM(&after) + TVADJUST);
  927. if (timercmp(&interval,&maxinterval,>))
  928. interval = maxinterval;
  929. if (interval.tv_sec == 0 &&
  930. interval.tv_usec <= MIN_POLL_INTERVAL)
  931. interval.tv_usec = MIN_POLL_INTERVAL;
  932. r = select(0,0,0,0,&interval);
  933. if (r < 0 && errno != EINTR)
  934. fatal("select() failed for pause: %s",
  935. strerror(errno));
  936. }
  937. default:
  938. assert(!"schedule[].type value must be valid");
  939. }
  940. next_item:
  941. position++;
  942. }
  943. if (quietmode <= 0)
  944. printf("Program %s, %d process(es), refused to die.\n",
  945. what_stop, n_killed);
  946. return 2;
  947. x_finished:
  948. if (!anykilled) {
  949. if (quietmode <= 0)
  950. printf("No %s found running; none killed.\n", what_stop);
  951. return exitnodo;
  952. } else {
  953. return 0;
  954. }
  955. }
  956. int main(int argc, char **argv) NONRETURNING;
  957. int
  958. main(int argc, char **argv)
  959. {
  960. progname = argv[0];
  961. parse_options(argc, argv);
  962. argc -= optind;
  963. argv += optind;
  964. if (execname && stat(execname, &exec_stat))
  965. fatal("stat %s: %s", execname, strerror(errno));
  966. if (userspec && sscanf(userspec, "%d", &user_id) != 1) {
  967. struct passwd *pw;
  968. pw = getpwnam(userspec);
  969. if (!pw)
  970. fatal("user `%s' not found\n", userspec);
  971. user_id = pw->pw_uid;
  972. }
  973. if (changegroup && sscanf(changegroup, "%d", &runas_gid) != 1) {
  974. struct group *gr = getgrnam(changegroup);
  975. if (!gr)
  976. fatal("group `%s' not found\n", changegroup);
  977. runas_gid = gr->gr_gid;
  978. }
  979. if (changeuser && sscanf(changeuser, "%d", &runas_uid) != 1) {
  980. struct passwd *pw = getpwnam(changeuser);
  981. if (!pw)
  982. fatal("user `%s' not found\n", changeuser);
  983. runas_uid = pw->pw_uid;
  984. if (changegroup == NULL) { /* pass the default group of this user */
  985. changegroup = ""; /* just empty */
  986. runas_gid = pw->pw_gid;
  987. }
  988. }
  989. if (stop) {
  990. int i = run_stop_schedule();
  991. exit(i);
  992. }
  993. do_findprocs();
  994. if (found) {
  995. if (quietmode <= 0)
  996. printf("%s already running.\n", execname);
  997. exit(exitnodo);
  998. }
  999. if (testmode) {
  1000. printf("Would start %s ", startas);
  1001. while (argc-- > 0)
  1002. printf("%s ", *argv++);
  1003. if (changeuser != NULL) {
  1004. printf(" (as user %s[%d]", changeuser, runas_uid);
  1005. if (changegroup != NULL)
  1006. printf(", and group %s[%d])", changegroup, runas_gid);
  1007. else
  1008. printf(")");
  1009. }
  1010. if (changeroot != NULL)
  1011. printf(" in directory %s", changeroot);
  1012. if (nicelevel)
  1013. printf(", and add %i to the priority", nicelevel);
  1014. printf(".\n");
  1015. exit(0);
  1016. }
  1017. if (quietmode < 0)
  1018. printf("Starting %s...\n", startas);
  1019. *--argv = startas;
  1020. if (changeroot != NULL) {
  1021. if (chdir(changeroot) < 0)
  1022. fatal("Unable to chdir() to %s", changeroot);
  1023. if (chroot(changeroot) < 0)
  1024. fatal("Unable to chroot() to %s", changeroot);
  1025. }
  1026. if (changeuser != NULL) {
  1027. if (setgid(runas_gid))
  1028. fatal("Unable to set gid to %d", runas_gid);
  1029. if (initgroups(changeuser, runas_gid))
  1030. fatal("Unable to set initgroups() with gid %d", runas_gid);
  1031. if (setuid(runas_uid))
  1032. fatal("Unable to set uid to %s", changeuser);
  1033. }
  1034. if (background) { /* ok, we need to detach this process */
  1035. int i, fd;
  1036. if (quietmode < 0)
  1037. printf("Detatching to start %s...", startas);
  1038. i = fork();
  1039. if (i<0) {
  1040. fatal("Unable to fork.\n");
  1041. }
  1042. if (i) { /* parent */
  1043. if (quietmode < 0)
  1044. printf("done.\n");
  1045. exit(0);
  1046. }
  1047. /* child continues here */
  1048. /* create a new session */
  1049. #ifdef HAVE_SETSID
  1050. setsid();
  1051. #else
  1052. setpgid(0,0);
  1053. #endif
  1054. #if defined(OShpux)
  1055. /* now close all extra fds */
  1056. for (i=sysconf(_SC_OPEN_MAX)-1; i>=0; --i) close(i);
  1057. #else
  1058. /* now close all extra fds */
  1059. for (i=getdtablesize()-1; i>=0; --i) close(i);
  1060. #endif
  1061. #ifdef HAVE_TIOCNOTTY
  1062. /* change tty */
  1063. fd = open("/dev/tty", O_RDWR);
  1064. ioctl(fd, TIOCNOTTY, 0);
  1065. close(fd);
  1066. #endif
  1067. chdir("/");
  1068. umask(022); /* set a default for dumb programs */
  1069. fd=open("/dev/null", O_RDWR); /* stdin */
  1070. dup(fd); /* stdout */
  1071. dup(fd); /* stderr */
  1072. }
  1073. if (nicelevel) {
  1074. errno=0;
  1075. if ((nice(nicelevel)==-1) && (errno!=0))
  1076. fatal("Unable to alter nice level by %i: %s", nicelevel,
  1077. strerror(errno));
  1078. }
  1079. if (mpidfile && pidfile != NULL) { /* user wants _us_ to make the pidfile :) */
  1080. FILE *pidf = fopen(pidfile, "w");
  1081. pid_t pidt = getpid();
  1082. if (pidf == NULL)
  1083. fatal("Unable to open pidfile `%s' for writing: %s", pidfile,
  1084. strerror(errno));
  1085. fprintf(pidf, "%d\n", pidt);
  1086. fclose(pidf);
  1087. }
  1088. execv(startas, argv);
  1089. fatal("Unable to start %s: %s", startas, strerror(errno));
  1090. }