start-stop-daemon.c 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514
  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 as well.
  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. #include <compat.h>
  24. #include <dpkg/macros.h>
  25. #if defined(__linux__)
  26. # define OS_Linux
  27. #elif defined(__GNU__)
  28. # define OS_Hurd
  29. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
  30. # define OS_FreeBSD
  31. #elif defined(__NetBSD__)
  32. # define OS_NetBSD
  33. #elif defined(__OpenBSD__)
  34. # define OS_OpenBSD
  35. #elif defined(__DragonFly__)
  36. # define OS_DragonFlyBSD
  37. #elif defined(__APPLE__) && defined(__MACH__)
  38. # define OS_Darwin
  39. #elif defined(__sun)
  40. # define OS_Solaris
  41. #elif defined(_AIX)
  42. # define OS_AIX
  43. #elif defined(__hpux)
  44. # define OS_HPUX
  45. #else
  46. # error Unknown architecture - cannot build start-stop-daemon
  47. #endif
  48. #ifdef HAVE_SYS_PARAM_H
  49. #include <sys/param.h>
  50. #endif
  51. #ifdef HAVE_SYS_SYSCALL_H
  52. #include <sys/syscall.h>
  53. #endif
  54. #ifdef HAVE_SYS_SYSCTL_H
  55. #include <sys/sysctl.h>
  56. #endif
  57. #ifdef HAVE_SYS_PROCFS_H
  58. #include <sys/procfs.h>
  59. #endif
  60. #ifdef HAVE_SYS_PROC_H
  61. #include <sys/proc.h>
  62. #endif
  63. #ifdef HAVE_SYS_USER_H
  64. #include <sys/user.h>
  65. #endif
  66. #ifdef HAVE_SYS_PSTAT_H
  67. #include <sys/pstat.h>
  68. #endif
  69. #include <sys/types.h>
  70. #include <sys/time.h>
  71. #include <sys/stat.h>
  72. #include <sys/wait.h>
  73. #include <sys/select.h>
  74. #include <sys/ioctl.h>
  75. #include <assert.h>
  76. #include <errno.h>
  77. #include <limits.h>
  78. #include <time.h>
  79. #include <fcntl.h>
  80. #include <dirent.h>
  81. #include <ctype.h>
  82. #include <string.h>
  83. #include <pwd.h>
  84. #include <grp.h>
  85. #include <signal.h>
  86. #include <termios.h>
  87. #include <unistd.h>
  88. #ifdef HAVE_STDDEF_H
  89. #include <stddef.h>
  90. #endif
  91. #include <stdbool.h>
  92. #include <stdarg.h>
  93. #include <stdlib.h>
  94. #include <stdio.h>
  95. #include <getopt.h>
  96. #ifdef HAVE_ERROR_H
  97. #include <error.h>
  98. #endif
  99. #ifdef HAVE_ERR_H
  100. #include <err.h>
  101. #endif
  102. #if defined(OS_Hurd)
  103. #include <hurd.h>
  104. #include <ps.h>
  105. #endif
  106. #if defined(OS_Darwin)
  107. #include <libproc.h>
  108. #endif
  109. #ifdef HAVE_KVM_H
  110. #include <kvm.h>
  111. #if defined(OS_FreeBSD)
  112. #define KVM_MEMFILE "/dev/null"
  113. #else
  114. #define KVM_MEMFILE NULL
  115. #endif
  116. #endif
  117. #if defined(_POSIX_PRIORITY_SCHEDULING) && _POSIX_PRIORITY_SCHEDULING > 0
  118. #include <sched.h>
  119. #else
  120. #define SCHED_OTHER -1
  121. #define SCHED_FIFO -1
  122. #define SCHED_RR -1
  123. #endif
  124. #if defined(OS_Linux)
  125. /* This comes from TASK_COMM_LEN defined in Linux' include/linux/sched.h. */
  126. #define PROCESS_NAME_SIZE 15
  127. #elif defined(OS_Solaris)
  128. #define PROCESS_NAME_SIZE 15
  129. #elif defined(OS_Darwin)
  130. #define PROCESS_NAME_SIZE 16
  131. #elif defined(OS_AIX)
  132. /* This comes from PRFNSZ defined in AIX's <sys/procfs.h>. */
  133. #define PROCESS_NAME_SIZE 16
  134. #elif defined(OS_NetBSD)
  135. #define PROCESS_NAME_SIZE 16
  136. #elif defined(OS_OpenBSD)
  137. #define PROCESS_NAME_SIZE 16
  138. #elif defined(OS_FreeBSD)
  139. #define PROCESS_NAME_SIZE 19
  140. #elif defined(OS_DragonFlyBSD)
  141. /* On DragonFlyBSD MAXCOMLEN expands to 16. */
  142. #define PROCESS_NAME_SIZE MAXCOMLEN
  143. #endif
  144. #if defined(SYS_ioprio_set) && defined(linux)
  145. #define HAVE_IOPRIO_SET
  146. #endif
  147. #define IOPRIO_CLASS_SHIFT 13
  148. #define IOPRIO_PRIO_VALUE(class, prio) (((class) << IOPRIO_CLASS_SHIFT) | (prio))
  149. #define IO_SCHED_PRIO_MIN 0
  150. #define IO_SCHED_PRIO_MAX 7
  151. enum {
  152. IOPRIO_WHO_PROCESS = 1,
  153. IOPRIO_WHO_PGRP,
  154. IOPRIO_WHO_USER,
  155. };
  156. enum {
  157. IOPRIO_CLASS_NONE,
  158. IOPRIO_CLASS_RT,
  159. IOPRIO_CLASS_BE,
  160. IOPRIO_CLASS_IDLE,
  161. };
  162. enum action_code {
  163. ACTION_NONE,
  164. ACTION_START,
  165. ACTION_STOP,
  166. ACTION_STATUS,
  167. };
  168. /* Time conversion constants. */
  169. enum {
  170. NANOSEC_IN_SEC = 1000000000L,
  171. NANOSEC_IN_MILLISEC = 1000000L,
  172. NANOSEC_IN_MICROSEC = 1000L,
  173. };
  174. /* The minimum polling interval, 20ms. */
  175. static const long MIN_POLL_INTERVAL = 20 * NANOSEC_IN_MILLISEC;
  176. static enum action_code action;
  177. static bool testmode = false;
  178. static int quietmode = 0;
  179. static int exitnodo = 1;
  180. static bool background = false;
  181. static bool close_io = true;
  182. static bool mpidfile = false;
  183. static bool rpidfile = false;
  184. static int signal_nr = SIGTERM;
  185. static int user_id = -1;
  186. static int runas_uid = -1;
  187. static int runas_gid = -1;
  188. static const char *userspec = NULL;
  189. static char *changeuser = NULL;
  190. static const char *changegroup = NULL;
  191. static char *changeroot = NULL;
  192. static const char *changedir = "/";
  193. static const char *cmdname = NULL;
  194. static char *execname = NULL;
  195. static char *startas = NULL;
  196. static pid_t match_pid = -1;
  197. static pid_t match_ppid = -1;
  198. static const char *pidfile = NULL;
  199. static char *what_stop = NULL;
  200. static const char *progname = "";
  201. static int nicelevel = 0;
  202. static int umask_value = -1;
  203. static struct stat exec_stat;
  204. #if defined(OS_Hurd)
  205. static struct proc_stat_list *procset = NULL;
  206. #endif
  207. /* LSB Init Script process status exit codes. */
  208. enum status_code {
  209. STATUS_OK = 0,
  210. STATUS_DEAD_PIDFILE = 1,
  211. STATUS_DEAD_LOCKFILE = 2,
  212. STATUS_DEAD = 3,
  213. STATUS_UNKNOWN = 4,
  214. };
  215. struct pid_list {
  216. struct pid_list *next;
  217. pid_t pid;
  218. };
  219. static struct pid_list *found = NULL;
  220. static struct pid_list *killed = NULL;
  221. /* Resource scheduling policy. */
  222. struct res_schedule {
  223. const char *policy_name;
  224. int policy;
  225. int priority;
  226. };
  227. struct schedule_item {
  228. enum {
  229. sched_timeout,
  230. sched_signal,
  231. sched_goto,
  232. /* Only seen within parse_schedule and callees. */
  233. sched_forever,
  234. } type;
  235. /* Seconds, signal no., or index into array. */
  236. int value;
  237. };
  238. static struct res_schedule *proc_sched = NULL;
  239. static struct res_schedule *io_sched = NULL;
  240. static int schedule_length;
  241. static struct schedule_item *schedule = NULL;
  242. static void DPKG_ATTR_PRINTF(1)
  243. warning(const char *format, ...)
  244. {
  245. va_list arglist;
  246. fprintf(stderr, "%s: warning: ", progname);
  247. va_start(arglist, format);
  248. vfprintf(stderr, format, arglist);
  249. va_end(arglist);
  250. }
  251. static void DPKG_ATTR_NORET DPKG_ATTR_PRINTF(1)
  252. fatal(const char *format, ...)
  253. {
  254. va_list arglist;
  255. int errno_fatal = errno;
  256. fprintf(stderr, "%s: ", progname);
  257. va_start(arglist, format);
  258. vfprintf(stderr, format, arglist);
  259. va_end(arglist);
  260. if (errno_fatal)
  261. fprintf(stderr, " (%s)\n", strerror(errno_fatal));
  262. else
  263. fprintf(stderr, "\n");
  264. if (action == ACTION_STATUS)
  265. exit(STATUS_UNKNOWN);
  266. else
  267. exit(2);
  268. }
  269. static void *
  270. xmalloc(int size)
  271. {
  272. void *ptr;
  273. ptr = malloc(size);
  274. if (ptr)
  275. return ptr;
  276. fatal("malloc(%d) failed", size);
  277. }
  278. static char *
  279. xstrndup(const char *str, size_t n)
  280. {
  281. char *new_str;
  282. new_str = strndup(str, n);
  283. if (new_str)
  284. return new_str;
  285. fatal("strndup(%s, %zu) failed", str, n);
  286. }
  287. static void
  288. timespec_gettime(struct timespec *ts)
  289. {
  290. #if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0 && \
  291. defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK > 0
  292. if (clock_gettime(CLOCK_MONOTONIC, ts) < 0)
  293. fatal("clock_gettime failed");
  294. #else
  295. struct timeval tv;
  296. if (gettimeofday(&tv, NULL) != 0)
  297. fatal("gettimeofday failed");
  298. ts->tv_sec = tv.tv_sec;
  299. ts->tv_nsec = tv.tv_usec * NANOSEC_IN_MICROSEC;
  300. #endif
  301. }
  302. #define timespec_cmp(a, b, OP) \
  303. (((a)->tv_sec == (b)->tv_sec) ? \
  304. ((a)->tv_nsec OP (b)->tv_nsec) : \
  305. ((a)->tv_sec OP (b)->tv_sec))
  306. static void
  307. timespec_sub(struct timespec *a, struct timespec *b, struct timespec *res)
  308. {
  309. res->tv_sec = a->tv_sec - b->tv_sec;
  310. res->tv_nsec = a->tv_nsec - b->tv_nsec;
  311. if (res->tv_nsec < 0) {
  312. res->tv_sec--;
  313. res->tv_nsec += NANOSEC_IN_SEC;
  314. }
  315. }
  316. static void
  317. timespec_mul(struct timespec *a, int b)
  318. {
  319. long nsec = a->tv_nsec * b;
  320. a->tv_sec *= b;
  321. a->tv_sec += nsec / NANOSEC_IN_SEC;
  322. a->tv_nsec = nsec % NANOSEC_IN_SEC;
  323. }
  324. static char *
  325. newpath(const char *dirname, const char *filename)
  326. {
  327. char *path;
  328. size_t path_len;
  329. path_len = strlen(dirname) + 1 + strlen(filename) + 1;
  330. path = xmalloc(path_len);
  331. snprintf(path, path_len, "%s/%s", dirname, filename);
  332. return path;
  333. }
  334. static long
  335. get_open_fd_max(void)
  336. {
  337. #ifdef HAVE_GETDTABLESIZE
  338. return getdtablesize();
  339. #else
  340. return sysconf(_SC_OPEN_MAX);
  341. #endif
  342. }
  343. #ifndef HAVE_SETSID
  344. static void
  345. detach_controlling_tty(void)
  346. {
  347. #ifdef HAVE_TIOCNOTTY
  348. int tty_fd;
  349. tty_fd = open("/dev/tty", O_RDWR);
  350. /* The current process does not have a controlling tty. */
  351. if (tty_fd < 0)
  352. return;
  353. if (ioctl(tty_fd, TIOCNOTTY, 0) != 0)
  354. fatal("unable to detach controlling tty");
  355. close(tty_fd);
  356. #endif
  357. }
  358. static pid_t
  359. setsid(void)
  360. {
  361. if (setpgid(0, 0) < 0)
  362. return -1:
  363. detach_controlling_tty();
  364. return 0;
  365. }
  366. #endif
  367. static void
  368. wait_for_child(pid_t pid)
  369. {
  370. pid_t child;
  371. int status;
  372. do {
  373. child = waitpid(pid, &status, 0);
  374. } while (child == -1 && errno == EINTR);
  375. if (child != pid)
  376. fatal("error waiting for child");
  377. if (WIFEXITED(status)) {
  378. int err = WEXITSTATUS(status);
  379. if (err != 0)
  380. fatal("child returned error exit status %d", err);
  381. } else if (WIFSIGNALED(status)) {
  382. int signo = WTERMSIG(status);
  383. fatal("child was killed by signal %d", signo);
  384. } else {
  385. fatal("unexpected status %d waiting for child", status);
  386. }
  387. }
  388. static void
  389. write_pidfile(const char *filename, pid_t pid)
  390. {
  391. FILE *fp;
  392. int fd;
  393. fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW, 0666);
  394. if (fd < 0)
  395. fp = NULL;
  396. else
  397. fp = fdopen(fd, "w");
  398. if (fp == NULL)
  399. fatal("unable to open pidfile '%s' for writing", filename);
  400. fprintf(fp, "%d\n", pid);
  401. if (fclose(fp))
  402. fatal("unable to close pidfile '%s'", filename);
  403. }
  404. static void
  405. remove_pidfile(const char *filename)
  406. {
  407. if (unlink(filename) < 0 && errno != ENOENT)
  408. fatal("cannot remove pidfile '%s'", filename);
  409. }
  410. static void
  411. daemonize(void)
  412. {
  413. pid_t pid;
  414. sigset_t mask;
  415. sigset_t oldmask;
  416. if (quietmode < 0)
  417. printf("Detaching to start %s...", startas);
  418. /* Block SIGCHLD to allow waiting for the child process while it is
  419. * performing actions, such as creating a pidfile. */
  420. sigemptyset(&mask);
  421. sigaddset(&mask, SIGCHLD);
  422. if (sigprocmask(SIG_BLOCK, &mask, &oldmask) == -1)
  423. fatal("cannot block SIGCHLD");
  424. pid = fork();
  425. if (pid < 0)
  426. fatal("unable to do first fork");
  427. else if (pid) { /* First Parent. */
  428. /* Wait for the second parent to exit, so that if we need to
  429. * perform any actions there, like creating a pidfile, we do
  430. * not suffer from race conditions on return. */
  431. wait_for_child(pid);
  432. _exit(0);
  433. }
  434. /* Create a new session. */
  435. if (setsid() < 0)
  436. fatal("cannot set session ID");
  437. pid = fork();
  438. if (pid < 0)
  439. fatal("unable to do second fork");
  440. else if (pid) { /* Second parent. */
  441. /* Set a default umask for dumb programs, which might get
  442. * overridden by the --umask option later on, so that we get
  443. * a defined umask when creating the pidfille. */
  444. umask(022);
  445. if (mpidfile && pidfile != NULL)
  446. /* User wants _us_ to make the pidfile. */
  447. write_pidfile(pidfile, pid);
  448. _exit(0);
  449. }
  450. if (sigprocmask(SIG_SETMASK, &oldmask, NULL) == -1)
  451. fatal("cannot restore signal mask");
  452. if (quietmode < 0)
  453. printf("done.\n");
  454. }
  455. static void
  456. pid_list_push(struct pid_list **list, pid_t pid)
  457. {
  458. struct pid_list *p;
  459. p = xmalloc(sizeof(*p));
  460. p->next = *list;
  461. p->pid = pid;
  462. *list = p;
  463. }
  464. static void
  465. pid_list_free(struct pid_list **list)
  466. {
  467. struct pid_list *here, *next;
  468. for (here = *list; here != NULL; here = next) {
  469. next = here->next;
  470. free(here);
  471. }
  472. *list = NULL;
  473. }
  474. static void
  475. usage(void)
  476. {
  477. printf(
  478. "Usage: start-stop-daemon [<option>...] <command>\n"
  479. "\n");
  480. printf(
  481. "Commands:\n"
  482. " -S, --start -- <argument>... start a program and pass <arguments> to it\n"
  483. " -K, --stop stop a program\n"
  484. " -T, --status get the program status\n"
  485. " -H, --help print help information\n"
  486. " -V, --version print version\n"
  487. "\n");
  488. printf(
  489. "Matching options (at least one is required):\n"
  490. " --pid <pid> pid to check\n"
  491. " --ppid <ppid> parent pid to check\n"
  492. " -p, --pidfile <pid-file> pid file to check\n"
  493. " -x, --exec <executable> program to start/check if it is running\n"
  494. " -n, --name <process-name> process name to check\n"
  495. " -u, --user <username|uid> process owner to check\n"
  496. "\n");
  497. printf(
  498. "Options:\n"
  499. " -g, --group <group|gid> run process as this group\n"
  500. " -c, --chuid <name|uid[:group|gid]>\n"
  501. " change to this user/group before starting\n"
  502. " process\n"
  503. " -s, --signal <signal> signal to send (default TERM)\n"
  504. " -a, --startas <pathname> program to start (default is <executable>)\n"
  505. " -r, --chroot <directory> chroot to <directory> before starting\n"
  506. " -d, --chdir <directory> change to <directory> (default is /)\n"
  507. " -N, --nicelevel <incr> add incr to the process' nice level\n"
  508. " -P, --procsched <policy[:prio]>\n"
  509. " use <policy> with <prio> for the kernel\n"
  510. " process scheduler (default prio is 0)\n"
  511. " -I, --iosched <class[:prio]> use <class> with <prio> to set the IO\n"
  512. " scheduler (default prio is 4)\n"
  513. " -k, --umask <mask> change the umask to <mask> before starting\n"
  514. " -b, --background force the process to detach\n"
  515. " -C, --no-close do not close any file descriptor\n"
  516. " -m, --make-pidfile create the pidfile before starting\n"
  517. " --remove-pidfile delete the pidfile after stopping\n"
  518. " -R, --retry <schedule> check whether processes die, and retry\n"
  519. " -t, --test test mode, don't do anything\n"
  520. " -o, --oknodo exit status 0 (not 1) if nothing done\n"
  521. " -q, --quiet be more quiet\n"
  522. " -v, --verbose be more verbose\n"
  523. "\n");
  524. printf(
  525. "Retry <schedule> is <item>|/<item>/... where <item> is one of\n"
  526. " -<signal-num>|[-]<signal-name> send that signal\n"
  527. " <timeout> wait that many seconds\n"
  528. " forever repeat remainder forever\n"
  529. "or <schedule> may be just <timeout>, meaning <signal>/<timeout>/KILL/<timeout>\n"
  530. "\n");
  531. printf(
  532. "The process scheduler <policy> can be one of:\n"
  533. " other, fifo or rr\n"
  534. "\n");
  535. printf(
  536. "The IO scheduler <class> can be one of:\n"
  537. " real-time, best-effort or idle\n"
  538. "\n");
  539. printf(
  540. "Exit status:\n"
  541. " 0 = done\n"
  542. " 1 = nothing done (=> 0 if --oknodo)\n"
  543. " 2 = with --retry, processes would not die\n"
  544. " 3 = trouble\n"
  545. "Exit status with --status:\n"
  546. " 0 = program is running\n"
  547. " 1 = program is not running and the pid file exists\n"
  548. " 3 = program is not running\n"
  549. " 4 = unable to determine status\n");
  550. }
  551. static void
  552. do_version(void)
  553. {
  554. printf("start-stop-daemon %s for Debian\n\n", VERSION);
  555. printf("Written by Marek Michalkiewicz, public domain.\n");
  556. }
  557. static void DPKG_ATTR_NORET
  558. badusage(const char *msg)
  559. {
  560. if (msg)
  561. fprintf(stderr, "%s: %s\n", progname, msg);
  562. fprintf(stderr, "Try '%s --help' for more information.\n", progname);
  563. if (action == ACTION_STATUS)
  564. exit(STATUS_UNKNOWN);
  565. else
  566. exit(3);
  567. }
  568. struct sigpair {
  569. const char *name;
  570. int signal;
  571. };
  572. static const struct sigpair siglist[] = {
  573. { "ABRT", SIGABRT },
  574. { "ALRM", SIGALRM },
  575. { "FPE", SIGFPE },
  576. { "HUP", SIGHUP },
  577. { "ILL", SIGILL },
  578. { "INT", SIGINT },
  579. { "KILL", SIGKILL },
  580. { "PIPE", SIGPIPE },
  581. { "QUIT", SIGQUIT },
  582. { "SEGV", SIGSEGV },
  583. { "TERM", SIGTERM },
  584. { "USR1", SIGUSR1 },
  585. { "USR2", SIGUSR2 },
  586. { "CHLD", SIGCHLD },
  587. { "CONT", SIGCONT },
  588. { "STOP", SIGSTOP },
  589. { "TSTP", SIGTSTP },
  590. { "TTIN", SIGTTIN },
  591. { "TTOU", SIGTTOU }
  592. };
  593. static int
  594. parse_unsigned(const char *string, int base, int *value_r)
  595. {
  596. long value;
  597. char *endptr;
  598. if (!string[0])
  599. return -1;
  600. errno = 0;
  601. value = strtol(string, &endptr, base);
  602. if (string == endptr || *endptr != '\0' || errno != 0)
  603. return -1;
  604. if (value < 0 || value > INT_MAX)
  605. return -1;
  606. *value_r = value;
  607. return 0;
  608. }
  609. static int
  610. parse_pid(const char *pid_str, int *pid_num)
  611. {
  612. if (parse_unsigned(pid_str, 10, pid_num) != 0)
  613. return -1;
  614. if (*pid_num == 0)
  615. return -1;
  616. return 0;
  617. }
  618. static int
  619. parse_signal(const char *sig_str, int *sig_num)
  620. {
  621. unsigned int i;
  622. if (parse_unsigned(sig_str, 10, sig_num) == 0)
  623. return 0;
  624. for (i = 0; i < array_count(siglist); i++) {
  625. if (strcmp(sig_str, siglist[i].name) == 0) {
  626. *sig_num = siglist[i].signal;
  627. return 0;
  628. }
  629. }
  630. return -1;
  631. }
  632. static int
  633. parse_umask(const char *string, int *value_r)
  634. {
  635. return parse_unsigned(string, 0, value_r);
  636. }
  637. static void
  638. validate_proc_schedule(void)
  639. {
  640. #if defined(_POSIX_PRIORITY_SCHEDULING) && _POSIX_PRIORITY_SCHEDULING > 0
  641. int prio_min, prio_max;
  642. prio_min = sched_get_priority_min(proc_sched->policy);
  643. prio_max = sched_get_priority_max(proc_sched->policy);
  644. if (proc_sched->priority < prio_min)
  645. badusage("process scheduler priority less than min");
  646. if (proc_sched->priority > prio_max)
  647. badusage("process scheduler priority greater than max");
  648. #endif
  649. }
  650. static void
  651. parse_proc_schedule(const char *string)
  652. {
  653. char *policy_str;
  654. size_t policy_len;
  655. int prio = 0;
  656. policy_len = strcspn(string, ":");
  657. policy_str = xstrndup(string, policy_len);
  658. if (string[policy_len] == ':' &&
  659. parse_unsigned(string + policy_len + 1, 10, &prio) != 0)
  660. fatal("invalid process scheduler priority");
  661. proc_sched = xmalloc(sizeof(*proc_sched));
  662. proc_sched->policy_name = policy_str;
  663. if (strcmp(policy_str, "other") == 0) {
  664. proc_sched->policy = SCHED_OTHER;
  665. proc_sched->priority = 0;
  666. } else if (strcmp(policy_str, "fifo") == 0) {
  667. proc_sched->policy = SCHED_FIFO;
  668. proc_sched->priority = prio;
  669. } else if (strcmp(policy_str, "rr") == 0) {
  670. proc_sched->policy = SCHED_RR;
  671. proc_sched->priority = prio;
  672. } else
  673. badusage("invalid process scheduler policy");
  674. validate_proc_schedule();
  675. }
  676. static void
  677. parse_io_schedule(const char *string)
  678. {
  679. char *class_str;
  680. size_t class_len;
  681. int prio = 4;
  682. class_len = strcspn(string, ":");
  683. class_str = xstrndup(string, class_len);
  684. if (string[class_len] == ':' &&
  685. parse_unsigned(string + class_len + 1, 10, &prio) != 0)
  686. fatal("invalid IO scheduler priority");
  687. io_sched = xmalloc(sizeof(*io_sched));
  688. io_sched->policy_name = class_str;
  689. if (strcmp(class_str, "real-time") == 0) {
  690. io_sched->policy = IOPRIO_CLASS_RT;
  691. io_sched->priority = prio;
  692. } else if (strcmp(class_str, "best-effort") == 0) {
  693. io_sched->policy = IOPRIO_CLASS_BE;
  694. io_sched->priority = prio;
  695. } else if (strcmp(class_str, "idle") == 0) {
  696. io_sched->policy = IOPRIO_CLASS_IDLE;
  697. io_sched->priority = 7;
  698. } else
  699. badusage("invalid IO scheduler policy");
  700. if (io_sched->priority < IO_SCHED_PRIO_MIN)
  701. badusage("IO scheduler priority less than min");
  702. if (io_sched->priority > IO_SCHED_PRIO_MAX)
  703. badusage("IO scheduler priority greater than max");
  704. }
  705. static void
  706. set_proc_schedule(struct res_schedule *sched)
  707. {
  708. #if defined(_POSIX_PRIORITY_SCHEDULING) && _POSIX_PRIORITY_SCHEDULING > 0
  709. struct sched_param param;
  710. param.sched_priority = sched->priority;
  711. if (sched_setscheduler(getpid(), sched->policy, &param) == -1)
  712. fatal("unable to set process scheduler");
  713. #endif
  714. }
  715. #ifdef HAVE_IOPRIO_SET
  716. static inline int
  717. ioprio_set(int which, int who, int ioprio)
  718. {
  719. return syscall(SYS_ioprio_set, which, who, ioprio);
  720. }
  721. #endif
  722. static void
  723. set_io_schedule(struct res_schedule *sched)
  724. {
  725. #ifdef HAVE_IOPRIO_SET
  726. int io_sched_mask;
  727. io_sched_mask = IOPRIO_PRIO_VALUE(sched->policy, sched->priority);
  728. if (ioprio_set(IOPRIO_WHO_PROCESS, getpid(), io_sched_mask) == -1)
  729. warning("unable to alter IO priority to mask %i (%s)\n",
  730. io_sched_mask, strerror(errno));
  731. #endif
  732. }
  733. static void
  734. parse_schedule_item(const char *string, struct schedule_item *item)
  735. {
  736. const char *after_hyph;
  737. if (strcmp(string, "forever") == 0) {
  738. item->type = sched_forever;
  739. } else if (isdigit(string[0])) {
  740. item->type = sched_timeout;
  741. if (parse_unsigned(string, 10, &item->value) != 0)
  742. badusage("invalid timeout value in schedule");
  743. } else if ((after_hyph = string + (string[0] == '-')) &&
  744. parse_signal(after_hyph, &item->value) == 0) {
  745. item->type = sched_signal;
  746. } else {
  747. badusage("invalid schedule item (must be [-]<signal-name>, "
  748. "-<signal-number>, <timeout> or 'forever'");
  749. }
  750. }
  751. static void
  752. parse_schedule(const char *schedule_str)
  753. {
  754. char item_buf[20];
  755. const char *slash;
  756. int count, repeatat;
  757. size_t str_len;
  758. count = 0;
  759. for (slash = schedule_str; *slash; slash++)
  760. if (*slash == '/')
  761. count++;
  762. schedule_length = (count == 0) ? 4 : count + 1;
  763. schedule = xmalloc(sizeof(*schedule) * schedule_length);
  764. if (count == 0) {
  765. schedule[0].type = sched_signal;
  766. schedule[0].value = signal_nr;
  767. parse_schedule_item(schedule_str, &schedule[1]);
  768. if (schedule[1].type != sched_timeout) {
  769. badusage("--retry takes timeout, or schedule list"
  770. " of at least two items");
  771. }
  772. schedule[2].type = sched_signal;
  773. schedule[2].value = SIGKILL;
  774. schedule[3] = schedule[1];
  775. } else {
  776. count = 0;
  777. repeatat = -1;
  778. while (schedule_str != NULL) {
  779. slash = strchr(schedule_str, '/');
  780. str_len = slash ? (size_t)(slash - schedule_str) : strlen(schedule_str);
  781. if (str_len >= sizeof(item_buf))
  782. badusage("invalid schedule item: far too long"
  783. " (you must delimit items with slashes)");
  784. memcpy(item_buf, schedule_str, str_len);
  785. item_buf[str_len] = '\0';
  786. schedule_str = slash ? slash + 1 : NULL;
  787. parse_schedule_item(item_buf, &schedule[count]);
  788. if (schedule[count].type == sched_forever) {
  789. if (repeatat >= 0)
  790. badusage("invalid schedule: 'forever'"
  791. " appears more than once");
  792. repeatat = count;
  793. continue;
  794. }
  795. count++;
  796. }
  797. if (repeatat == count)
  798. badusage("invalid schedule: 'forever' appears last, "
  799. "nothing to repeat");
  800. if (repeatat >= 0) {
  801. schedule[count].type = sched_goto;
  802. schedule[count].value = repeatat;
  803. count++;
  804. }
  805. assert(count == schedule_length);
  806. }
  807. }
  808. static void
  809. set_action(enum action_code new_action)
  810. {
  811. if (action == new_action)
  812. return;
  813. if (action != ACTION_NONE)
  814. badusage("only one command can be specified");
  815. action = new_action;
  816. }
  817. #define OPT_PID 500
  818. #define OPT_PPID 501
  819. #define OPT_RM_PIDFILE 502
  820. static void
  821. parse_options(int argc, char * const *argv)
  822. {
  823. static struct option longopts[] = {
  824. { "help", 0, NULL, 'H'},
  825. { "stop", 0, NULL, 'K'},
  826. { "start", 0, NULL, 'S'},
  827. { "status", 0, NULL, 'T'},
  828. { "version", 0, NULL, 'V'},
  829. { "startas", 1, NULL, 'a'},
  830. { "name", 1, NULL, 'n'},
  831. { "oknodo", 0, NULL, 'o'},
  832. { "pid", 1, NULL, OPT_PID},
  833. { "ppid", 1, NULL, OPT_PPID},
  834. { "pidfile", 1, NULL, 'p'},
  835. { "quiet", 0, NULL, 'q'},
  836. { "signal", 1, NULL, 's'},
  837. { "test", 0, NULL, 't'},
  838. { "user", 1, NULL, 'u'},
  839. { "group", 1, NULL, 'g'},
  840. { "chroot", 1, NULL, 'r'},
  841. { "verbose", 0, NULL, 'v'},
  842. { "exec", 1, NULL, 'x'},
  843. { "chuid", 1, NULL, 'c'},
  844. { "nicelevel", 1, NULL, 'N'},
  845. { "procsched", 1, NULL, 'P'},
  846. { "iosched", 1, NULL, 'I'},
  847. { "umask", 1, NULL, 'k'},
  848. { "background", 0, NULL, 'b'},
  849. { "no-close", 0, NULL, 'C'},
  850. { "make-pidfile", 0, NULL, 'm'},
  851. { "remove-pidfile", 0, NULL, OPT_RM_PIDFILE},
  852. { "retry", 1, NULL, 'R'},
  853. { "chdir", 1, NULL, 'd'},
  854. { NULL, 0, NULL, 0 }
  855. };
  856. const char *pid_str = NULL;
  857. const char *ppid_str = NULL;
  858. const char *umask_str = NULL;
  859. const char *signal_str = NULL;
  860. const char *schedule_str = NULL;
  861. const char *proc_schedule_str = NULL;
  862. const char *io_schedule_str = NULL;
  863. size_t changeuser_len;
  864. int c;
  865. for (;;) {
  866. c = getopt_long(argc, argv,
  867. "HKSVTa:n:op:qr:s:tu:vx:c:N:P:I:k:bCmR:g:d:",
  868. longopts, NULL);
  869. if (c == -1)
  870. break;
  871. switch (c) {
  872. case 'H': /* --help */
  873. usage();
  874. exit(0);
  875. case 'K': /* --stop */
  876. set_action(ACTION_STOP);
  877. break;
  878. case 'S': /* --start */
  879. set_action(ACTION_START);
  880. break;
  881. case 'T': /* --status */
  882. set_action(ACTION_STATUS);
  883. break;
  884. case 'V': /* --version */
  885. do_version();
  886. exit(0);
  887. case 'a': /* --startas <pathname> */
  888. startas = optarg;
  889. break;
  890. case 'n': /* --name <process-name> */
  891. cmdname = optarg;
  892. break;
  893. case 'o': /* --oknodo */
  894. exitnodo = 0;
  895. break;
  896. case OPT_PID: /* --pid <pid> */
  897. pid_str = optarg;
  898. break;
  899. case OPT_PPID: /* --ppid <ppid> */
  900. ppid_str = optarg;
  901. break;
  902. case 'p': /* --pidfile <pid-file> */
  903. pidfile = optarg;
  904. break;
  905. case 'q': /* --quiet */
  906. quietmode = true;
  907. break;
  908. case 's': /* --signal <signal> */
  909. signal_str = optarg;
  910. break;
  911. case 't': /* --test */
  912. testmode = true;
  913. break;
  914. case 'u': /* --user <username>|<uid> */
  915. userspec = optarg;
  916. break;
  917. case 'v': /* --verbose */
  918. quietmode = -1;
  919. break;
  920. case 'x': /* --exec <executable> */
  921. execname = optarg;
  922. break;
  923. case 'c': /* --chuid <username>|<uid> */
  924. /* We copy the string just in case we need the
  925. * argument later. */
  926. changeuser_len = strcspn(optarg, ":");
  927. changeuser = xstrndup(optarg, changeuser_len);
  928. if (optarg[changeuser_len] == ':') {
  929. if (optarg[changeuser_len + 1] == '\0')
  930. fatal("missing group name");
  931. changegroup = optarg + changeuser_len + 1;
  932. }
  933. break;
  934. case 'g': /* --group <group>|<gid> */
  935. changegroup = optarg;
  936. break;
  937. case 'r': /* --chroot /new/root */
  938. changeroot = optarg;
  939. break;
  940. case 'N': /* --nice */
  941. nicelevel = atoi(optarg);
  942. break;
  943. case 'P': /* --procsched */
  944. proc_schedule_str = optarg;
  945. break;
  946. case 'I': /* --iosched */
  947. io_schedule_str = optarg;
  948. break;
  949. case 'k': /* --umask <mask> */
  950. umask_str = optarg;
  951. break;
  952. case 'b': /* --background */
  953. background = true;
  954. break;
  955. case 'C': /* --no-close */
  956. close_io = false;
  957. break;
  958. case 'm': /* --make-pidfile */
  959. mpidfile = true;
  960. break;
  961. case OPT_RM_PIDFILE: /* --remove-pidfile */
  962. rpidfile = true;
  963. break;
  964. case 'R': /* --retry <schedule>|<timeout> */
  965. schedule_str = optarg;
  966. break;
  967. case 'd': /* --chdir /new/dir */
  968. changedir = optarg;
  969. break;
  970. default:
  971. /* Message printed by getopt. */
  972. badusage(NULL);
  973. }
  974. }
  975. if (pid_str != NULL) {
  976. if (parse_pid(pid_str, &match_pid) != 0)
  977. badusage("pid value must be a number greater than 0");
  978. }
  979. if (ppid_str != NULL) {
  980. if (parse_pid(ppid_str, &match_ppid) != 0)
  981. badusage("ppid value must be a number greater than 0");
  982. }
  983. if (signal_str != NULL) {
  984. if (parse_signal(signal_str, &signal_nr) != 0)
  985. badusage("signal value must be numeric or name"
  986. " of signal (KILL, INT, ...)");
  987. }
  988. if (schedule_str != NULL) {
  989. parse_schedule(schedule_str);
  990. }
  991. if (proc_schedule_str != NULL)
  992. parse_proc_schedule(proc_schedule_str);
  993. if (io_schedule_str != NULL)
  994. parse_io_schedule(io_schedule_str);
  995. if (umask_str != NULL) {
  996. if (parse_umask(umask_str, &umask_value) != 0)
  997. badusage("umask value must be a positive number");
  998. }
  999. if (action == ACTION_NONE)
  1000. badusage("need one of --start or --stop or --status");
  1001. if (!execname && !pid_str && !ppid_str && !pidfile && !userspec &&
  1002. !cmdname)
  1003. badusage("need at least one of --exec, --pid, --ppid, --pidfile, --user or --name");
  1004. #ifdef PROCESS_NAME_SIZE
  1005. if (cmdname && strlen(cmdname) > PROCESS_NAME_SIZE)
  1006. warning("this system is not able to track process names\n"
  1007. "longer than %d characters, please use --exec "
  1008. "instead of --name.\n", PROCESS_NAME_SIZE);
  1009. #endif
  1010. if (!startas)
  1011. startas = execname;
  1012. if (action == ACTION_START && !startas)
  1013. badusage("--start needs --exec or --startas");
  1014. if (mpidfile && pidfile == NULL)
  1015. badusage("--make-pidfile requires --pidfile");
  1016. if (rpidfile && pidfile == NULL)
  1017. badusage("--remove-pidfile requires --pidfile");
  1018. if (pid_str && pidfile)
  1019. badusage("need either --pid of --pidfile, not both");
  1020. if (background && action != ACTION_START)
  1021. badusage("--background is only relevant with --start");
  1022. if (!close_io && !background)
  1023. badusage("--no-close is only relevant with --background");
  1024. }
  1025. static void
  1026. setup_options(void)
  1027. {
  1028. if (execname) {
  1029. char *fullexecname;
  1030. /* If it's a relative path, normalize it. */
  1031. if (execname[0] != '/')
  1032. execname = newpath(changedir, execname);
  1033. if (changeroot)
  1034. fullexecname = newpath(changeroot, execname);
  1035. else
  1036. fullexecname = execname;
  1037. if (stat(fullexecname, &exec_stat))
  1038. fatal("unable to stat %s", fullexecname);
  1039. if (fullexecname != execname)
  1040. free(fullexecname);
  1041. }
  1042. if (userspec && sscanf(userspec, "%d", &user_id) != 1) {
  1043. struct passwd *pw;
  1044. pw = getpwnam(userspec);
  1045. if (!pw)
  1046. fatal("user '%s' not found", userspec);
  1047. user_id = pw->pw_uid;
  1048. }
  1049. if (changegroup && sscanf(changegroup, "%d", &runas_gid) != 1) {
  1050. struct group *gr;
  1051. gr = getgrnam(changegroup);
  1052. if (!gr)
  1053. fatal("group '%s' not found", changegroup);
  1054. changegroup = gr->gr_name;
  1055. runas_gid = gr->gr_gid;
  1056. }
  1057. if (changeuser) {
  1058. struct passwd *pw;
  1059. struct stat st;
  1060. if (sscanf(changeuser, "%d", &runas_uid) == 1)
  1061. pw = getpwuid(runas_uid);
  1062. else
  1063. pw = getpwnam(changeuser);
  1064. if (!pw)
  1065. fatal("user '%s' not found", changeuser);
  1066. changeuser = pw->pw_name;
  1067. runas_uid = pw->pw_uid;
  1068. if (changegroup == NULL) {
  1069. /* Pass the default group of this user. */
  1070. changegroup = ""; /* Just empty. */
  1071. runas_gid = pw->pw_gid;
  1072. }
  1073. if (stat(pw->pw_dir, &st) == 0)
  1074. setenv("HOME", pw->pw_dir, 1);
  1075. }
  1076. }
  1077. #if defined(OS_Linux)
  1078. static const char *
  1079. proc_status_field(pid_t pid, const char *field)
  1080. {
  1081. static char *line = NULL;
  1082. static size_t line_size = 0;
  1083. FILE *fp;
  1084. char filename[32];
  1085. char *value = NULL;
  1086. ssize_t line_len;
  1087. size_t field_len = strlen(field);
  1088. sprintf(filename, "/proc/%d/status", pid);
  1089. fp = fopen(filename, "r");
  1090. if (!fp)
  1091. return NULL;
  1092. while ((line_len = getline(&line, &line_size, fp)) >= 0) {
  1093. if (strncasecmp(line, field, field_len) == 0) {
  1094. line[line_len - 1] = '\0';
  1095. value = line + field_len;
  1096. while (isspace(*value))
  1097. value++;
  1098. break;
  1099. }
  1100. }
  1101. fclose(fp);
  1102. return value;
  1103. }
  1104. #elif defined(OS_AIX)
  1105. static bool
  1106. proc_get_psinfo(pid_t pid, struct psinfo *psinfo)
  1107. {
  1108. char filename[64];
  1109. FILE *fp;
  1110. sprintf(filename, "/proc/%d/psinfo", pid);
  1111. fp = fopen(filename, "r");
  1112. if (!fp)
  1113. return false;
  1114. if (fread(psinfo, sizeof(*psinfo), 1, fp) == 0)
  1115. return false;
  1116. if (ferror(fp))
  1117. return false;
  1118. return true;
  1119. }
  1120. #elif defined(OS_Hurd)
  1121. static void
  1122. init_procset(void)
  1123. {
  1124. struct ps_context *context;
  1125. error_t err;
  1126. err = ps_context_create(getproc(), &context);
  1127. if (err)
  1128. error(1, err, "ps_context_create");
  1129. err = proc_stat_list_create(context, &procset);
  1130. if (err)
  1131. error(1, err, "proc_stat_list_create");
  1132. err = proc_stat_list_add_all(procset, 0, 0);
  1133. if (err)
  1134. error(1, err, "proc_stat_list_add_all");
  1135. }
  1136. static struct proc_stat *
  1137. get_proc_stat(pid_t pid, ps_flags_t flags)
  1138. {
  1139. struct proc_stat *ps;
  1140. ps_flags_t wanted_flags = PSTAT_PID | flags;
  1141. if (!procset)
  1142. init_procset();
  1143. ps = proc_stat_list_pid_proc_stat(procset, pid);
  1144. if (!ps)
  1145. return NULL;
  1146. if (proc_stat_set_flags(ps, wanted_flags))
  1147. return NULL;
  1148. if ((proc_stat_flags(ps) & wanted_flags) != wanted_flags)
  1149. return NULL;
  1150. return ps;
  1151. }
  1152. #elif defined(HAVE_KVM_H)
  1153. static kvm_t *
  1154. ssd_kvm_open(void)
  1155. {
  1156. kvm_t *kd;
  1157. char errbuf[_POSIX2_LINE_MAX];
  1158. kd = kvm_openfiles(NULL, KVM_MEMFILE, NULL, O_RDONLY, errbuf);
  1159. if (kd == NULL)
  1160. errx(1, "%s", errbuf);
  1161. return kd;
  1162. }
  1163. static struct kinfo_proc *
  1164. ssd_kvm_get_procs(kvm_t *kd, int op, int arg, int *count)
  1165. {
  1166. struct kinfo_proc *kp;
  1167. int lcount;
  1168. if (count == NULL)
  1169. count = &lcount;
  1170. *count = 0;
  1171. kp = kvm_getprocs(kd, op, arg, count);
  1172. if (kp == NULL && errno != ESRCH)
  1173. errx(1, "%s", kvm_geterr(kd));
  1174. return kp;
  1175. }
  1176. #endif
  1177. #if defined(OS_Linux)
  1178. static bool
  1179. pid_is_exec(pid_t pid, const struct stat *esb)
  1180. {
  1181. char lname[32];
  1182. char lcontents[_POSIX_PATH_MAX + 1];
  1183. char *filename;
  1184. const char deleted[] = " (deleted)";
  1185. int nread;
  1186. struct stat sb;
  1187. sprintf(lname, "/proc/%d/exe", pid);
  1188. nread = readlink(lname, lcontents, sizeof(lcontents) - 1);
  1189. if (nread == -1)
  1190. return false;
  1191. filename = lcontents;
  1192. filename[nread] = '\0';
  1193. /* OpenVZ kernels contain a bogus patch that instead of appending,
  1194. * prepends the deleted marker. Workaround those. Otherwise handle
  1195. * the normal appended marker. */
  1196. if (strncmp(filename, deleted, strlen(deleted)) == 0)
  1197. filename += strlen(deleted);
  1198. else if (strcmp(filename + nread - strlen(deleted), deleted) == 0)
  1199. filename[nread - strlen(deleted)] = '\0';
  1200. if (stat(filename, &sb) != 0)
  1201. return false;
  1202. return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  1203. }
  1204. #elif defined(OS_AIX)
  1205. static bool
  1206. pid_is_exec(pid_t pid, const struct stat *esb)
  1207. {
  1208. struct stat sb;
  1209. char filename[64];
  1210. sprintf(filename, "/proc/%d/object/a.out", pid);
  1211. if (stat(filename, &sb) != 0)
  1212. return false;
  1213. return sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino;
  1214. }
  1215. #elif defined(OS_Hurd)
  1216. static bool
  1217. pid_is_exec(pid_t pid, const struct stat *esb)
  1218. {
  1219. struct proc_stat *ps;
  1220. struct stat sb;
  1221. const char *filename;
  1222. ps = get_proc_stat(pid, PSTAT_ARGS);
  1223. if (ps == NULL)
  1224. return false;
  1225. filename = proc_stat_args(ps);
  1226. if (stat(filename, &sb) != 0)
  1227. return false;
  1228. return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  1229. }
  1230. #elif defined(OS_Darwin)
  1231. static bool
  1232. pid_is_exec(pid_t pid, const struct stat *esb)
  1233. {
  1234. struct stat sb;
  1235. char pathname[_POSIX_PATH_MAX];
  1236. if (proc_pidpath(pid, pathname, sizeof(pathname)) < 0)
  1237. return false;
  1238. if (stat(pathname, &sb) != 0)
  1239. return false;
  1240. return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  1241. }
  1242. #elif defined(OS_HPUX)
  1243. static bool
  1244. pid_is_exec(pid_t pid, const struct stat *esb)
  1245. {
  1246. struct pst_status pst;
  1247. if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
  1248. return false;
  1249. return ((dev_t)pst.pst_text.psf_fsid.psfs_id == esb->st_dev &&
  1250. (ino_t)pst.pst_text.psf_fileid == esb->st_ino);
  1251. }
  1252. #elif defined(OS_FreeBSD)
  1253. static bool
  1254. pid_is_exec(pid_t pid, const struct stat *esb)
  1255. {
  1256. struct stat sb;
  1257. int error, mib[4];
  1258. size_t len;
  1259. char pathname[PATH_MAX];
  1260. mib[0] = CTL_KERN;
  1261. mib[1] = KERN_PROC;
  1262. mib[2] = KERN_PROC_PATHNAME;
  1263. mib[3] = pid;
  1264. len = sizeof(pathname);
  1265. error = sysctl(mib, 4, pathname, &len, NULL, 0);
  1266. if (error != 0 && errno != ESRCH)
  1267. return false;
  1268. if (len == 0)
  1269. pathname[0] = '\0';
  1270. if (stat(pathname, &sb) != 0)
  1271. return false;
  1272. return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  1273. }
  1274. #elif defined(HAVE_KVM_H)
  1275. static bool
  1276. pid_is_exec(pid_t pid, const struct stat *esb)
  1277. {
  1278. kvm_t *kd;
  1279. int argv_len = 0;
  1280. struct kinfo_proc *kp;
  1281. struct stat sb;
  1282. char buf[_POSIX2_LINE_MAX];
  1283. char **pid_argv_p;
  1284. char *start_argv_0_p, *end_argv_0_p;
  1285. bool res = false;
  1286. kd = ssd_kvm_open();
  1287. kp = ssd_kvm_get_procs(kd, KERN_PROC_PID, pid, NULL);
  1288. if (kp == NULL)
  1289. goto cleanup;
  1290. pid_argv_p = kvm_getargv(kd, kp, argv_len);
  1291. if (pid_argv_p == NULL)
  1292. errx(1, "%s", kvm_geterr(kd));
  1293. /* Find and compare string. */
  1294. start_argv_0_p = *pid_argv_p;
  1295. /* Find end of argv[0] then copy and cut of str there. */
  1296. end_argv_0_p = strchr(*pid_argv_p, ' ');
  1297. if (end_argv_0_p == NULL)
  1298. /* There seems to be no space, so we have the command
  1299. * already in its desired form. */
  1300. start_argv_0_p = *pid_argv_p;
  1301. else {
  1302. /* Tests indicate that this never happens, since
  1303. * kvm_getargv itself cuts of tailing stuff. This is
  1304. * not what the manpage says, however. */
  1305. strncpy(buf, *pid_argv_p, (end_argv_0_p - start_argv_0_p));
  1306. buf[(end_argv_0_p - start_argv_0_p) + 1] = '\0';
  1307. start_argv_0_p = buf;
  1308. }
  1309. if (stat(start_argv_0_p, &sb) != 0)
  1310. goto cleanup;
  1311. res = (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  1312. cleanup:
  1313. kvm_close(kd);
  1314. return res;
  1315. }
  1316. #endif
  1317. #if defined(OS_Linux)
  1318. static bool
  1319. pid_is_child(pid_t pid, pid_t ppid)
  1320. {
  1321. const char *ppid_str;
  1322. pid_t proc_ppid;
  1323. int rc;
  1324. ppid_str = proc_status_field(pid, "PPid:");
  1325. if (ppid_str == NULL)
  1326. return false;
  1327. rc = parse_pid(ppid_str, &proc_ppid);
  1328. if (rc < 0)
  1329. return false;
  1330. return proc_ppid == ppid;
  1331. }
  1332. #elif defined(OS_Hurd)
  1333. static bool
  1334. pid_is_child(pid_t pid, pid_t ppid)
  1335. {
  1336. struct proc_stat *ps;
  1337. struct procinfo *pi;
  1338. ps = get_proc_stat(pid, PSTAT_PROC_INFO);
  1339. if (ps == NULL)
  1340. return false;
  1341. pi = proc_stat_proc_info(ps);
  1342. return pi->ppid == ppid;
  1343. }
  1344. #elif defined(OS_Darwin)
  1345. static bool
  1346. pid_is_child(pid_t pid, pid_t ppid)
  1347. {
  1348. struct proc_bsdinfo info;
  1349. if (proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, sizeof(info)) < 0)
  1350. return false;
  1351. return (pid_t)info.pbi_ppid == ppid;
  1352. }
  1353. #elif defined(OS_AIX)
  1354. static bool
  1355. pid_is_child(pid_t pid, pid_t ppid)
  1356. {
  1357. struct psinfo psi;
  1358. if (!proc_get_psinfo(pid, &psi))
  1359. return false;
  1360. return (pid_t)psi.pr_ppid == ppid;
  1361. }
  1362. #elif defined(OS_HPUX)
  1363. static bool
  1364. pid_is_child(pid_t pid, pid_t ppid)
  1365. {
  1366. struct pst_status pst;
  1367. if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
  1368. return false;
  1369. return pst.pst_ppid == ppid;
  1370. }
  1371. #elif defined(OS_FreeBSD)
  1372. static bool
  1373. pid_is_child(pid_t pid, pid_t ppid)
  1374. {
  1375. struct kinfo_proc kp;
  1376. int rc, mib[4];
  1377. size_t len;
  1378. mib[0] = CTL_KERN;
  1379. mib[1] = KERN_PROC;
  1380. mib[2] = KERN_PROC_PID;
  1381. mib[3] = pid;
  1382. len = sizeof(kp);
  1383. rc = sysctl(mib, 4, &kp, &len, NULL, 0);
  1384. if (rc != 0 && errno != ESRCH)
  1385. return false;
  1386. if (len == 0 || len != sizeof(kp))
  1387. return false;
  1388. return kp.ki_ppid == ppid;
  1389. }
  1390. #elif defined(HAVE_KVM_H)
  1391. static bool
  1392. pid_is_child(pid_t pid, pid_t ppid)
  1393. {
  1394. kvm_t *kd;
  1395. struct kinfo_proc *kp;
  1396. pid_t proc_ppid;
  1397. bool res = false;
  1398. kd = ssd_kvm_open();
  1399. kp = ssd_kvm_get_procs(kd, KERN_PROC_PID, pid, NULL);
  1400. if (kp == NULL)
  1401. goto cleanup;
  1402. #if defined(OS_FreeBSD)
  1403. proc_ppid = kp->ki_ppid;
  1404. #elif defined(OS_OpenBSD)
  1405. proc_ppid = kp->p_ppid;
  1406. #elif defined(OS_DragonFlyBSD)
  1407. proc_ppid = kp->kp_ppid;
  1408. #else
  1409. proc_ppid = kp->kp_proc.p_ppid;
  1410. #endif
  1411. res = (proc_ppid == ppid);
  1412. cleanup:
  1413. kvm_close(kd);
  1414. return res;
  1415. }
  1416. #endif
  1417. #if defined(OS_Linux)
  1418. static bool
  1419. pid_is_user(pid_t pid, uid_t uid)
  1420. {
  1421. struct stat sb;
  1422. char buf[32];
  1423. sprintf(buf, "/proc/%d", pid);
  1424. if (stat(buf, &sb) != 0)
  1425. return false;
  1426. return (sb.st_uid == uid);
  1427. }
  1428. #elif defined(OS_Hurd)
  1429. static bool
  1430. pid_is_user(pid_t pid, uid_t uid)
  1431. {
  1432. struct proc_stat *ps;
  1433. ps = get_proc_stat(pid, PSTAT_OWNER_UID);
  1434. return ps && (uid_t)proc_stat_owner_uid(ps) == uid;
  1435. }
  1436. #elif defined(OS_Darwin)
  1437. static bool
  1438. pid_is_user(pid_t pid, uid_t uid)
  1439. {
  1440. struct proc_bsdinfo info;
  1441. if (proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, sizeof(info)) < 0)
  1442. return false;
  1443. return info.pbi_ruid == uid;
  1444. }
  1445. #elif defined(OS_AIX)
  1446. static bool
  1447. pid_is_user(pid_t pid, uid_t uid)
  1448. {
  1449. struct psinfo psi;
  1450. if (!proc_get_psinfo(pid, &psi))
  1451. return false;
  1452. return psi.pr_uid == uid;
  1453. }
  1454. #elif defined(OS_HPUX)
  1455. static bool
  1456. pid_is_user(pid_t pid, uid_t uid)
  1457. {
  1458. struct pst_status pst;
  1459. if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
  1460. return false;
  1461. return ((uid_t)pst.pst_uid == uid);
  1462. }
  1463. #elif defined(OS_FreeBSD)
  1464. static bool
  1465. pid_is_user(pid_t pid, uid_t uid)
  1466. {
  1467. struct kinfo_proc kp;
  1468. int rc, mib[4];
  1469. size_t len;
  1470. mib[0] = CTL_KERN;
  1471. mib[1] = KERN_PROC;
  1472. mib[2] = KERN_PROC_PID;
  1473. mib[3] = pid;
  1474. len = sizeof(kp);
  1475. rc = sysctl(mib, 4, &kp, &len, NULL, 0);
  1476. if (rc != 0 && errno != ESRCH)
  1477. return false;
  1478. if (len == 0 || len != sizeof(kp))
  1479. return false;
  1480. return kp.ki_ruid == uid;
  1481. }
  1482. #elif defined(HAVE_KVM_H)
  1483. static bool
  1484. pid_is_user(pid_t pid, uid_t uid)
  1485. {
  1486. kvm_t *kd;
  1487. uid_t proc_uid;
  1488. struct kinfo_proc *kp;
  1489. bool res = false;
  1490. kd = ssd_kvm_open();
  1491. kp = ssd_kvm_get_procs(kd, KERN_PROC_PID, pid, NULL);
  1492. if (kp == NULL)
  1493. goto cleanup;
  1494. #if defined(OS_FreeBSD)
  1495. proc_uid = kp->ki_ruid;
  1496. #elif defined(OS_OpenBSD)
  1497. proc_uid = kp->p_ruid;
  1498. #elif defined(OS_DragonFlyBSD)
  1499. proc_uid = kp->kp_ruid;
  1500. #else
  1501. if (kp->kp_proc.p_cred)
  1502. kvm_read(kd, (u_long)&(kp->kp_proc.p_cred->p_ruid),
  1503. &proc_uid, sizeof(uid_t));
  1504. else
  1505. goto cleanup;
  1506. #endif
  1507. res = (proc_uid == (uid_t)uid);
  1508. cleanup:
  1509. kvm_close(kd);
  1510. return res;
  1511. }
  1512. #endif
  1513. #if defined(OS_Linux)
  1514. static bool
  1515. pid_is_cmd(pid_t pid, const char *name)
  1516. {
  1517. const char *comm;
  1518. comm = proc_status_field(pid, "Name:");
  1519. if (comm == NULL)
  1520. return false;
  1521. return strcmp(comm, name) == 0;
  1522. }
  1523. #elif defined(OS_Hurd)
  1524. static bool
  1525. pid_is_cmd(pid_t pid, const char *name)
  1526. {
  1527. struct proc_stat *ps;
  1528. size_t argv0_len;
  1529. const char *argv0;
  1530. const char *binary_name;
  1531. ps = get_proc_stat(pid, PSTAT_ARGS);
  1532. if (ps == NULL)
  1533. return false;
  1534. argv0 = proc_stat_args(ps);
  1535. argv0_len = strlen(argv0) + 1;
  1536. binary_name = basename(argv0);
  1537. if (strcmp(binary_name, name) == 0)
  1538. return true;
  1539. /* XXX: This is all kinds of ugly, but on the Hurd there's no way to
  1540. * know the command name of a process, so we have to try to match
  1541. * also on argv[1] for the case of an interpreted script. */
  1542. if (proc_stat_args_len(ps) > argv0_len) {
  1543. const char *script_name = basename(argv0 + argv0_len);
  1544. return strcmp(script_name, name) == 0;
  1545. }
  1546. return false;
  1547. }
  1548. #elif defined(OS_AIX)
  1549. static bool
  1550. pid_is_cmd(pid_t pid, const char *name)
  1551. {
  1552. struct psinfo psi;
  1553. if (!proc_get_psinfo(pid, &psi))
  1554. return false;
  1555. return strcmp(psi.pr_fname, name) == 0;
  1556. }
  1557. #elif defined(OS_HPUX)
  1558. static bool
  1559. pid_is_cmd(pid_t pid, const char *name)
  1560. {
  1561. struct pst_status pst;
  1562. if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
  1563. return false;
  1564. return (strcmp(pst.pst_ucomm, name) == 0);
  1565. }
  1566. #elif defined(OS_Darwin)
  1567. static bool
  1568. pid_is_cmd(pid_t pid, const char *name)
  1569. {
  1570. char pathname[_POSIX_PATH_MAX];
  1571. if (proc_pidpath(pid, pathname, sizeof(pathname)) < 0)
  1572. return false;
  1573. return strcmp(pathname, name) == 0;
  1574. }
  1575. #elif defined(OS_FreeBSD)
  1576. static bool
  1577. pid_is_cmd(pid_t pid, const char *name)
  1578. {
  1579. struct kinfo_proc kp;
  1580. int rc, mib[4];
  1581. size_t len;
  1582. mib[0] = CTL_KERN;
  1583. mib[1] = KERN_PROC;
  1584. mib[2] = KERN_PROC_PID;
  1585. mib[3] = pid;
  1586. len = sizeof(kp);
  1587. rc = sysctl(mib, 4, &kp, &len, NULL, 0);
  1588. if (rc != 0 && errno != ESRCH)
  1589. return false;
  1590. if (len == 0 || len != sizeof(kp))
  1591. return false;
  1592. return strcmp(kp.ki_comm, name) == 0;
  1593. }
  1594. #elif defined(HAVE_KVM_H)
  1595. static bool
  1596. pid_is_cmd(pid_t pid, const char *name)
  1597. {
  1598. kvm_t *kd;
  1599. struct kinfo_proc *kp;
  1600. char *process_name;
  1601. bool res = false;
  1602. kd = ssd_kvm_open();
  1603. kp = ssd_kvm_get_procs(kd, KERN_PROC_PID, pid, NULL);
  1604. if (kp == NULL)
  1605. goto cleanup;
  1606. #if defined(OS_FreeBSD)
  1607. process_name = kp->ki_comm;
  1608. #elif defined(OS_OpenBSD)
  1609. process_name = kp->p_comm;
  1610. #elif defined(OS_DragonFlyBSD)
  1611. process_name = kp->kp_comm;
  1612. #else
  1613. process_name = kp->kp_proc.p_comm;
  1614. #endif
  1615. res = (strcmp(name, process_name) == 0);
  1616. cleanup:
  1617. kvm_close(kd);
  1618. return res;
  1619. }
  1620. #endif
  1621. #if defined(OS_Hurd)
  1622. static bool
  1623. pid_is_running(pid_t pid)
  1624. {
  1625. return get_proc_stat(pid, 0) != NULL;
  1626. }
  1627. #else /* !OS_Hurd */
  1628. static bool
  1629. pid_is_running(pid_t pid)
  1630. {
  1631. if (kill(pid, 0) == 0 || errno == EPERM)
  1632. return true;
  1633. else if (errno == ESRCH)
  1634. return false;
  1635. else
  1636. fatal("error checking pid %u status", pid);
  1637. }
  1638. #endif
  1639. static enum status_code
  1640. pid_check(pid_t pid)
  1641. {
  1642. if (execname && !pid_is_exec(pid, &exec_stat))
  1643. return STATUS_DEAD;
  1644. if (match_ppid > 0 && !pid_is_child(pid, match_ppid))
  1645. return STATUS_DEAD;
  1646. if (userspec && !pid_is_user(pid, user_id))
  1647. return STATUS_DEAD;
  1648. if (cmdname && !pid_is_cmd(pid, cmdname))
  1649. return STATUS_DEAD;
  1650. if (action != ACTION_STOP && !pid_is_running(pid))
  1651. return STATUS_DEAD;
  1652. pid_list_push(&found, pid);
  1653. return STATUS_OK;
  1654. }
  1655. static enum status_code
  1656. do_pidfile(const char *name)
  1657. {
  1658. FILE *f;
  1659. static pid_t pid = 0;
  1660. if (pid)
  1661. return pid_check(pid);
  1662. f = fopen(name, "r");
  1663. if (f) {
  1664. enum status_code pid_status;
  1665. if (fscanf(f, "%d", &pid) == 1)
  1666. pid_status = pid_check(pid);
  1667. else
  1668. pid_status = STATUS_UNKNOWN;
  1669. fclose(f);
  1670. if (pid_status == STATUS_DEAD)
  1671. return STATUS_DEAD_PIDFILE;
  1672. else
  1673. return pid_status;
  1674. } else if (errno == ENOENT)
  1675. return STATUS_DEAD;
  1676. else
  1677. fatal("unable to open pidfile %s", name);
  1678. }
  1679. #if defined(OS_Linux) || defined(OS_Solaris) || defined(OS_AIX)
  1680. static enum status_code
  1681. do_procinit(void)
  1682. {
  1683. DIR *procdir;
  1684. struct dirent *entry;
  1685. int foundany;
  1686. pid_t pid;
  1687. enum status_code prog_status = STATUS_DEAD;
  1688. procdir = opendir("/proc");
  1689. if (!procdir)
  1690. fatal("unable to opendir /proc");
  1691. foundany = 0;
  1692. while ((entry = readdir(procdir)) != NULL) {
  1693. enum status_code pid_status;
  1694. if (sscanf(entry->d_name, "%d", &pid) != 1)
  1695. continue;
  1696. foundany++;
  1697. pid_status = pid_check(pid);
  1698. if (pid_status < prog_status)
  1699. prog_status = pid_status;
  1700. }
  1701. closedir(procdir);
  1702. if (!foundany)
  1703. fatal("nothing in /proc - not mounted?");
  1704. return prog_status;
  1705. }
  1706. #elif defined(OS_Hurd)
  1707. static int
  1708. check_proc_stat(struct proc_stat *ps)
  1709. {
  1710. pid_check(ps->pid);
  1711. return 0;
  1712. }
  1713. static enum status_code
  1714. do_procinit(void)
  1715. {
  1716. if (!procset)
  1717. init_procset();
  1718. proc_stat_list_for_each(procset, check_proc_stat);
  1719. if (found)
  1720. return STATUS_OK;
  1721. else
  1722. return STATUS_DEAD;
  1723. }
  1724. #elif defined(OS_Darwin)
  1725. static enum status_code
  1726. do_procinit(void)
  1727. {
  1728. pid_t *pid_buf;
  1729. int i, npids, pid_bufsize;
  1730. enum status_code prog_status = STATUS_DEAD;
  1731. npids = proc_listallpids(NULL, 0);
  1732. if (npids == 0)
  1733. return STATUS_UNKNOWN;
  1734. /* Try to avoid sudden changes in number of PIDs. */
  1735. npids += 4096;
  1736. pid_bufsize = sizeof(pid_t) * npids;
  1737. pid_buf = xmalloc(pid_bufsize);
  1738. npids = proc_listallpids(pid_buf, pid_bufsize);
  1739. if (npids == 0)
  1740. return STATUS_UNKNOWN;
  1741. for (i = 0; i < npids; i++) {
  1742. enum status_code pid_status;
  1743. pid_status = pid_check(pid_buf[i]);
  1744. if (pid_status < prog_status)
  1745. prog_status = pid_status;
  1746. }
  1747. free(pid_buf);
  1748. return prog_status;
  1749. }
  1750. #elif defined(OS_HPUX)
  1751. static enum status_code
  1752. do_procinit(void)
  1753. {
  1754. struct pst_status pst[10];
  1755. int i, count;
  1756. int idx = 0;
  1757. enum status_code prog_status = STATUS_DEAD;
  1758. while ((count = pstat_getproc(pst, sizeof(pst[0]), 10, idx)) > 0) {
  1759. enum status_code pid_status;
  1760. for (i = 0; i < count; i++) {
  1761. pid_status = pid_check(pst[i].pst_pid);
  1762. if (pid_status < prog_status)
  1763. prog_status = pid_status;
  1764. }
  1765. idx = pst[count - 1].pst_idx + 1;
  1766. }
  1767. return prog_status;
  1768. }
  1769. #elif defined(OS_FreeBSD)
  1770. static enum status_code
  1771. do_procinit(void)
  1772. {
  1773. struct kinfo_proc *kp;
  1774. int rc, mib[3];
  1775. size_t len = 0;
  1776. int nentries, i;
  1777. enum status_code prog_status = STATUS_DEAD;
  1778. mib[0] = CTL_KERN;
  1779. mib[1] = KERN_PROC;
  1780. mib[2] = KERN_PROC_PROC;
  1781. rc = sysctl(mib, 3, NULL, &len, NULL, 0);
  1782. if (rc != 0 && errno != ESRCH)
  1783. return STATUS_UNKNOWN;
  1784. if (len == 0)
  1785. return STATUS_UNKNOWN;
  1786. kp = xmalloc(len);
  1787. rc = sysctl(mib, 3, kp, &len, NULL, 0);
  1788. if (rc != 0 && errno != ESRCH)
  1789. return STATUS_UNKNOWN;
  1790. if (len == 0)
  1791. return STATUS_UNKNOWN;
  1792. nentries = len / sizeof(*kp);
  1793. for (i = 0; i < nentries; i++) {
  1794. enum status_code pid_status;
  1795. pid_status = pid_check(kp[i].ki_pid);
  1796. if (pid_status < prog_status)
  1797. prog_status = pid_status;
  1798. }
  1799. free(kp);
  1800. return prog_status;
  1801. }
  1802. #elif defined(HAVE_KVM_H)
  1803. static enum status_code
  1804. do_procinit(void)
  1805. {
  1806. kvm_t *kd;
  1807. int nentries, i;
  1808. struct kinfo_proc *kp;
  1809. enum status_code prog_status = STATUS_DEAD;
  1810. kd = ssd_kvm_open();
  1811. kp = ssd_kvm_get_procs(kd, KERN_PROC_ALL, 0, &nentries);
  1812. for (i = 0; i < nentries; i++) {
  1813. enum status_code pid_status;
  1814. pid_t pid;
  1815. #if defined(OS_FreeBSD)
  1816. pid = kp[i].ki_pid;
  1817. #elif defined(OS_OpenBSD)
  1818. pid = kp[i].p_pid;
  1819. #elif defined(OS_DragonFlyBSD)
  1820. pid = kp[i].kp_pid;
  1821. #else
  1822. pid = kp[i].kp_proc.p_pid;
  1823. #endif
  1824. pid_status = pid_check(pid);
  1825. if (pid_status < prog_status)
  1826. prog_status = pid_status;
  1827. }
  1828. kvm_close(kd);
  1829. return prog_status;
  1830. }
  1831. #endif
  1832. static enum status_code
  1833. do_findprocs(void)
  1834. {
  1835. pid_list_free(&found);
  1836. if (match_pid > 0)
  1837. return pid_check(match_pid);
  1838. else if (pidfile)
  1839. return do_pidfile(pidfile);
  1840. else
  1841. return do_procinit();
  1842. }
  1843. static int
  1844. do_start(int argc, char **argv)
  1845. {
  1846. int devnull_fd = -1;
  1847. gid_t rgid;
  1848. uid_t ruid;
  1849. do_findprocs();
  1850. if (found) {
  1851. if (quietmode <= 0)
  1852. printf("%s already running.\n", execname ? execname : "process");
  1853. return exitnodo;
  1854. }
  1855. if (testmode && quietmode <= 0) {
  1856. printf("Would start %s ", startas);
  1857. while (argc-- > 0)
  1858. printf("%s ", *argv++);
  1859. if (changeuser != NULL) {
  1860. printf(" (as user %s[%d]", changeuser, runas_uid);
  1861. if (changegroup != NULL)
  1862. printf(", and group %s[%d])", changegroup, runas_gid);
  1863. else
  1864. printf(")");
  1865. }
  1866. if (changeroot != NULL)
  1867. printf(" in directory %s", changeroot);
  1868. if (nicelevel)
  1869. printf(", and add %i to the priority", nicelevel);
  1870. if (proc_sched)
  1871. printf(", with scheduling policy %s with priority %i",
  1872. proc_sched->policy_name, proc_sched->priority);
  1873. if (io_sched)
  1874. printf(", with IO scheduling class %s with priority %i",
  1875. io_sched->policy_name, io_sched->priority);
  1876. printf(".\n");
  1877. }
  1878. if (testmode)
  1879. return 0;
  1880. if (quietmode < 0)
  1881. printf("Starting %s...\n", startas);
  1882. *--argv = startas;
  1883. if (background)
  1884. /* Ok, we need to detach this process. */
  1885. daemonize();
  1886. else if (mpidfile && pidfile != NULL)
  1887. /* User wants _us_ to make the pidfile, but detach themself! */
  1888. write_pidfile(pidfile, getpid());
  1889. if (background && close_io) {
  1890. devnull_fd = open("/dev/null", O_RDWR);
  1891. if (devnull_fd < 0)
  1892. fatal("unable to open '%s'", "/dev/null");
  1893. }
  1894. if (nicelevel) {
  1895. errno = 0;
  1896. if ((nice(nicelevel) == -1) && (errno != 0))
  1897. fatal("unable to alter nice level by %i", nicelevel);
  1898. }
  1899. if (proc_sched)
  1900. set_proc_schedule(proc_sched);
  1901. if (io_sched)
  1902. set_io_schedule(io_sched);
  1903. if (umask_value >= 0)
  1904. umask(umask_value);
  1905. if (changeroot != NULL) {
  1906. if (chdir(changeroot) < 0)
  1907. fatal("unable to chdir() to %s", changeroot);
  1908. if (chroot(changeroot) < 0)
  1909. fatal("unable to chroot() to %s", changeroot);
  1910. }
  1911. if (chdir(changedir) < 0)
  1912. fatal("unable to chdir() to %s", changedir);
  1913. rgid = getgid();
  1914. ruid = getuid();
  1915. if (changegroup != NULL) {
  1916. if (rgid != (gid_t)runas_gid)
  1917. if (setgid(runas_gid))
  1918. fatal("unable to set gid to %d", runas_gid);
  1919. }
  1920. if (changeuser != NULL) {
  1921. /* We assume that if our real user and group are the same as
  1922. * the ones we should switch to, the supplementary groups
  1923. * will be already in place. */
  1924. if (rgid != (gid_t)runas_gid || ruid != (uid_t)runas_uid)
  1925. if (initgroups(changeuser, runas_gid))
  1926. fatal("unable to set initgroups() with gid %d",
  1927. runas_gid);
  1928. if (ruid != (uid_t)runas_uid)
  1929. if (setuid(runas_uid))
  1930. fatal("unable to set uid to %s", changeuser);
  1931. }
  1932. if (background && close_io) {
  1933. int i;
  1934. dup2(devnull_fd, 0); /* stdin */
  1935. dup2(devnull_fd, 1); /* stdout */
  1936. dup2(devnull_fd, 2); /* stderr */
  1937. /* Now close all extra fds. */
  1938. for (i = get_open_fd_max() - 1; i >= 3; --i)
  1939. close(i);
  1940. }
  1941. execv(startas, argv);
  1942. fatal("unable to start %s", startas);
  1943. }
  1944. static void
  1945. do_stop(int sig_num, int *n_killed, int *n_notkilled)
  1946. {
  1947. struct pid_list *p;
  1948. do_findprocs();
  1949. *n_killed = 0;
  1950. *n_notkilled = 0;
  1951. if (!found)
  1952. return;
  1953. pid_list_free(&killed);
  1954. for (p = found; p; p = p->next) {
  1955. if (testmode) {
  1956. if (quietmode <= 0)
  1957. printf("Would send signal %d to %d.\n",
  1958. sig_num, p->pid);
  1959. (*n_killed)++;
  1960. } else if (kill(p->pid, sig_num) == 0) {
  1961. pid_list_push(&killed, p->pid);
  1962. (*n_killed)++;
  1963. } else {
  1964. if (sig_num)
  1965. warning("failed to kill %d: %s\n",
  1966. p->pid, strerror(errno));
  1967. (*n_notkilled)++;
  1968. }
  1969. }
  1970. }
  1971. static void
  1972. do_stop_summary(int retry_nr)
  1973. {
  1974. struct pid_list *p;
  1975. if (quietmode >= 0 || !killed)
  1976. return;
  1977. printf("Stopped %s (pid", what_stop);
  1978. for (p = killed; p; p = p->next)
  1979. printf(" %d", p->pid);
  1980. putchar(')');
  1981. if (retry_nr > 0)
  1982. printf(", retry #%d", retry_nr);
  1983. printf(".\n");
  1984. }
  1985. static void DPKG_ATTR_PRINTF(1)
  1986. set_what_stop(const char *format, ...)
  1987. {
  1988. va_list arglist;
  1989. int rc;
  1990. va_start(arglist, format);
  1991. rc = vasprintf(&what_stop, format, arglist);
  1992. va_end(arglist);
  1993. if (rc < 0)
  1994. fatal("cannot allocate formatted string");
  1995. }
  1996. /*
  1997. * We want to keep polling for the processes, to see if they've exited, or
  1998. * until the timeout expires.
  1999. *
  2000. * This is a somewhat complicated algorithm to try to ensure that we notice
  2001. * reasonably quickly when all the processes have exited, but don't spend
  2002. * too much CPU time polling. In particular, on a fast machine with
  2003. * quick-exiting daemons we don't want to delay system shutdown too much,
  2004. * whereas on a slow one, or where processes are taking some time to exit,
  2005. * we want to increase the polling interval.
  2006. *
  2007. * The algorithm is as follows: we measure the elapsed time it takes to do
  2008. * one poll(), and wait a multiple of this time for the next poll. However,
  2009. * if that would put us past the end of the timeout period we wait only as
  2010. * long as the timeout period, but in any case we always wait at least
  2011. * MIN_POLL_INTERVAL (20ms). The multiple (‘ratio’) starts out as 2, and
  2012. * increases by 1 for each poll to a maximum of 10; so we use up to between
  2013. * 30% and 10% of the machine's resources (assuming a few reasonable things
  2014. * about system performance).
  2015. */
  2016. static bool
  2017. do_stop_timeout(int timeout, int *n_killed, int *n_notkilled)
  2018. {
  2019. struct timespec stopat, before, after, interval, maxinterval;
  2020. int rc, ratio;
  2021. timespec_gettime(&stopat);
  2022. stopat.tv_sec += timeout;
  2023. ratio = 1;
  2024. for (;;) {
  2025. timespec_gettime(&before);
  2026. if (timespec_cmp(&before, &stopat, >))
  2027. return false;
  2028. do_stop(0, n_killed, n_notkilled);
  2029. if (!*n_killed)
  2030. return true;
  2031. timespec_gettime(&after);
  2032. if (!timespec_cmp(&after, &stopat, <))
  2033. return false;
  2034. if (ratio < 10)
  2035. ratio++;
  2036. timespec_sub(&stopat, &after, &maxinterval);
  2037. timespec_sub(&after, &before, &interval);
  2038. timespec_mul(&interval, ratio);
  2039. if (interval.tv_sec < 0 || interval.tv_nsec < 0)
  2040. interval.tv_sec = interval.tv_nsec = 0;
  2041. if (timespec_cmp(&interval, &maxinterval, >))
  2042. interval = maxinterval;
  2043. if (interval.tv_sec == 0 &&
  2044. interval.tv_nsec <= MIN_POLL_INTERVAL)
  2045. interval.tv_nsec = MIN_POLL_INTERVAL;
  2046. rc = pselect(0, NULL, NULL, NULL, &interval, NULL);
  2047. if (rc < 0 && errno != EINTR)
  2048. fatal("select() failed for pause");
  2049. }
  2050. }
  2051. static int
  2052. finish_stop_schedule(bool anykilled)
  2053. {
  2054. if (rpidfile && pidfile && !testmode)
  2055. remove_pidfile(pidfile);
  2056. if (anykilled)
  2057. return 0;
  2058. if (quietmode <= 0)
  2059. printf("No %s found running; none killed.\n", what_stop);
  2060. return exitnodo;
  2061. }
  2062. static int
  2063. run_stop_schedule(void)
  2064. {
  2065. int position, n_killed, n_notkilled, value, retry_nr;
  2066. bool anykilled;
  2067. if (testmode) {
  2068. if (schedule != NULL) {
  2069. if (quietmode <= 0)
  2070. printf("Ignoring --retry in test mode\n");
  2071. schedule = NULL;
  2072. }
  2073. }
  2074. if (cmdname)
  2075. set_what_stop("%s", cmdname);
  2076. else if (execname)
  2077. set_what_stop("%s", execname);
  2078. else if (pidfile)
  2079. set_what_stop("process in pidfile '%s'", pidfile);
  2080. else if (match_pid > 0)
  2081. set_what_stop("process with pid %d", match_pid);
  2082. else if (match_ppid > 0)
  2083. set_what_stop("process(es) with parent pid %d", match_ppid);
  2084. else if (userspec)
  2085. set_what_stop("process(es) owned by '%s'", userspec);
  2086. else
  2087. fatal("internal error, no match option, please report");
  2088. anykilled = false;
  2089. retry_nr = 0;
  2090. if (schedule == NULL) {
  2091. do_stop(signal_nr, &n_killed, &n_notkilled);
  2092. do_stop_summary(0);
  2093. if (n_notkilled > 0 && quietmode <= 0)
  2094. printf("%d pids were not killed\n", n_notkilled);
  2095. if (n_killed)
  2096. anykilled = true;
  2097. return finish_stop_schedule(anykilled);
  2098. }
  2099. for (position = 0; position < schedule_length; position++) {
  2100. reposition:
  2101. value = schedule[position].value;
  2102. n_notkilled = 0;
  2103. switch (schedule[position].type) {
  2104. case sched_goto:
  2105. position = value;
  2106. goto reposition;
  2107. case sched_signal:
  2108. do_stop(value, &n_killed, &n_notkilled);
  2109. do_stop_summary(retry_nr++);
  2110. if (!n_killed)
  2111. return finish_stop_schedule(anykilled);
  2112. else
  2113. anykilled = true;
  2114. continue;
  2115. case sched_timeout:
  2116. if (do_stop_timeout(value, &n_killed, &n_notkilled))
  2117. return finish_stop_schedule(anykilled);
  2118. else
  2119. continue;
  2120. default:
  2121. assert(!"schedule[].type value must be valid");
  2122. }
  2123. }
  2124. if (quietmode <= 0)
  2125. printf("Program %s, %d process(es), refused to die.\n",
  2126. what_stop, n_killed);
  2127. return 2;
  2128. }
  2129. int
  2130. main(int argc, char **argv)
  2131. {
  2132. progname = argv[0];
  2133. parse_options(argc, argv);
  2134. setup_options();
  2135. argc -= optind;
  2136. argv += optind;
  2137. if (action == ACTION_START)
  2138. return do_start(argc, argv);
  2139. else if (action == ACTION_STOP)
  2140. return run_stop_schedule();
  2141. else if (action == ACTION_STATUS)
  2142. return do_findprocs();
  2143. return 0;
  2144. }