start-stop-daemon.c 30 KB

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