start-stop-daemon.c 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532
  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 ret = WEXITSTATUS(status);
  379. if (ret != 0)
  380. fatal("child returned error exit status %d", ret);
  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. #if defined(OS_OpenBSD)
  1172. kp = kvm_getprocs(kd, op, arg, sizeof(*kp), count);
  1173. #else
  1174. kp = kvm_getprocs(kd, op, arg, count);
  1175. #endif
  1176. if (kp == NULL && errno != ESRCH)
  1177. errx(1, "%s", kvm_geterr(kd));
  1178. return kp;
  1179. }
  1180. #endif
  1181. #if defined(OS_Linux)
  1182. static bool
  1183. pid_is_exec(pid_t pid, const struct stat *esb)
  1184. {
  1185. char lname[32];
  1186. char lcontents[_POSIX_PATH_MAX + 1];
  1187. char *filename;
  1188. const char deleted[] = " (deleted)";
  1189. int nread;
  1190. struct stat sb;
  1191. sprintf(lname, "/proc/%d/exe", pid);
  1192. nread = readlink(lname, lcontents, sizeof(lcontents) - 1);
  1193. if (nread == -1)
  1194. return false;
  1195. filename = lcontents;
  1196. filename[nread] = '\0';
  1197. /* OpenVZ kernels contain a bogus patch that instead of appending,
  1198. * prepends the deleted marker. Workaround those. Otherwise handle
  1199. * the normal appended marker. */
  1200. if (strncmp(filename, deleted, strlen(deleted)) == 0)
  1201. filename += strlen(deleted);
  1202. else if (strcmp(filename + nread - strlen(deleted), deleted) == 0)
  1203. filename[nread - strlen(deleted)] = '\0';
  1204. if (stat(filename, &sb) != 0)
  1205. return false;
  1206. return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  1207. }
  1208. #elif defined(OS_AIX)
  1209. static bool
  1210. pid_is_exec(pid_t pid, const struct stat *esb)
  1211. {
  1212. struct stat sb;
  1213. char filename[64];
  1214. sprintf(filename, "/proc/%d/object/a.out", pid);
  1215. if (stat(filename, &sb) != 0)
  1216. return false;
  1217. return sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino;
  1218. }
  1219. #elif defined(OS_Hurd)
  1220. static bool
  1221. pid_is_exec(pid_t pid, const struct stat *esb)
  1222. {
  1223. struct proc_stat *ps;
  1224. struct stat sb;
  1225. const char *filename;
  1226. ps = get_proc_stat(pid, PSTAT_ARGS);
  1227. if (ps == NULL)
  1228. return false;
  1229. /* On old Hurd systems we have to use the argv[0] value, because
  1230. * there is nothing better. */
  1231. filename = proc_stat_args(ps);
  1232. #ifdef PSTAT_EXE
  1233. /* On new Hurd systems we can use the correct value, as long
  1234. * as it's not NULL nor empty, as it was the case on the first
  1235. * implementation. */
  1236. if (proc_stat_set_flags(ps, PSTAT_EXE) == 0 &&
  1237. proc_stat_flags(ps) & PSTAT_EXE &&
  1238. proc_stat_exe(ps) != NULL &&
  1239. proc_stat_exe(ps)[0] != '\0')
  1240. filename = proc_stat_exe(ps);
  1241. #endif
  1242. if (stat(filename, &sb) != 0)
  1243. return false;
  1244. return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  1245. }
  1246. #elif defined(OS_Darwin)
  1247. static bool
  1248. pid_is_exec(pid_t pid, const struct stat *esb)
  1249. {
  1250. struct stat sb;
  1251. char pathname[_POSIX_PATH_MAX];
  1252. if (proc_pidpath(pid, pathname, sizeof(pathname)) < 0)
  1253. return false;
  1254. if (stat(pathname, &sb) != 0)
  1255. return false;
  1256. return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  1257. }
  1258. #elif defined(OS_HPUX)
  1259. static bool
  1260. pid_is_exec(pid_t pid, const struct stat *esb)
  1261. {
  1262. struct pst_status pst;
  1263. if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
  1264. return false;
  1265. return ((dev_t)pst.pst_text.psf_fsid.psfs_id == esb->st_dev &&
  1266. (ino_t)pst.pst_text.psf_fileid == esb->st_ino);
  1267. }
  1268. #elif defined(OS_FreeBSD)
  1269. static bool
  1270. pid_is_exec(pid_t pid, const struct stat *esb)
  1271. {
  1272. struct stat sb;
  1273. int error, mib[4];
  1274. size_t len;
  1275. char pathname[PATH_MAX];
  1276. mib[0] = CTL_KERN;
  1277. mib[1] = KERN_PROC;
  1278. mib[2] = KERN_PROC_PATHNAME;
  1279. mib[3] = pid;
  1280. len = sizeof(pathname);
  1281. error = sysctl(mib, 4, pathname, &len, NULL, 0);
  1282. if (error != 0 && errno != ESRCH)
  1283. return false;
  1284. if (len == 0)
  1285. pathname[0] = '\0';
  1286. if (stat(pathname, &sb) != 0)
  1287. return false;
  1288. return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  1289. }
  1290. #elif defined(HAVE_KVM_H)
  1291. static bool
  1292. pid_is_exec(pid_t pid, const struct stat *esb)
  1293. {
  1294. kvm_t *kd;
  1295. int argv_len = 0;
  1296. struct kinfo_proc *kp;
  1297. struct stat sb;
  1298. char buf[_POSIX2_LINE_MAX];
  1299. char **pid_argv_p;
  1300. char *start_argv_0_p, *end_argv_0_p;
  1301. bool res = false;
  1302. kd = ssd_kvm_open();
  1303. kp = ssd_kvm_get_procs(kd, KERN_PROC_PID, pid, NULL);
  1304. if (kp == NULL)
  1305. goto cleanup;
  1306. pid_argv_p = kvm_getargv(kd, kp, argv_len);
  1307. if (pid_argv_p == NULL)
  1308. errx(1, "%s", kvm_geterr(kd));
  1309. /* Find and compare string. */
  1310. start_argv_0_p = *pid_argv_p;
  1311. /* Find end of argv[0] then copy and cut of str there. */
  1312. end_argv_0_p = strchr(*pid_argv_p, ' ');
  1313. if (end_argv_0_p == NULL)
  1314. /* There seems to be no space, so we have the command
  1315. * already in its desired form. */
  1316. start_argv_0_p = *pid_argv_p;
  1317. else {
  1318. /* Tests indicate that this never happens, since
  1319. * kvm_getargv itself cuts of tailing stuff. This is
  1320. * not what the manpage says, however. */
  1321. strncpy(buf, *pid_argv_p, (end_argv_0_p - start_argv_0_p));
  1322. buf[(end_argv_0_p - start_argv_0_p) + 1] = '\0';
  1323. start_argv_0_p = buf;
  1324. }
  1325. if (stat(start_argv_0_p, &sb) != 0)
  1326. goto cleanup;
  1327. res = (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  1328. cleanup:
  1329. kvm_close(kd);
  1330. return res;
  1331. }
  1332. #endif
  1333. #if defined(OS_Linux)
  1334. static bool
  1335. pid_is_child(pid_t pid, pid_t ppid)
  1336. {
  1337. const char *ppid_str;
  1338. pid_t proc_ppid;
  1339. int rc;
  1340. ppid_str = proc_status_field(pid, "PPid:");
  1341. if (ppid_str == NULL)
  1342. return false;
  1343. rc = parse_pid(ppid_str, &proc_ppid);
  1344. if (rc < 0)
  1345. return false;
  1346. return proc_ppid == ppid;
  1347. }
  1348. #elif defined(OS_Hurd)
  1349. static bool
  1350. pid_is_child(pid_t pid, pid_t ppid)
  1351. {
  1352. struct proc_stat *ps;
  1353. struct procinfo *pi;
  1354. ps = get_proc_stat(pid, PSTAT_PROC_INFO);
  1355. if (ps == NULL)
  1356. return false;
  1357. pi = proc_stat_proc_info(ps);
  1358. return pi->ppid == ppid;
  1359. }
  1360. #elif defined(OS_Darwin)
  1361. static bool
  1362. pid_is_child(pid_t pid, pid_t ppid)
  1363. {
  1364. struct proc_bsdinfo info;
  1365. if (proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, sizeof(info)) < 0)
  1366. return false;
  1367. return (pid_t)info.pbi_ppid == ppid;
  1368. }
  1369. #elif defined(OS_AIX)
  1370. static bool
  1371. pid_is_child(pid_t pid, pid_t ppid)
  1372. {
  1373. struct psinfo psi;
  1374. if (!proc_get_psinfo(pid, &psi))
  1375. return false;
  1376. return (pid_t)psi.pr_ppid == ppid;
  1377. }
  1378. #elif defined(OS_HPUX)
  1379. static bool
  1380. pid_is_child(pid_t pid, pid_t ppid)
  1381. {
  1382. struct pst_status pst;
  1383. if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
  1384. return false;
  1385. return pst.pst_ppid == ppid;
  1386. }
  1387. #elif defined(OS_FreeBSD)
  1388. static bool
  1389. pid_is_child(pid_t pid, pid_t ppid)
  1390. {
  1391. struct kinfo_proc kp;
  1392. int rc, mib[4];
  1393. size_t len;
  1394. mib[0] = CTL_KERN;
  1395. mib[1] = KERN_PROC;
  1396. mib[2] = KERN_PROC_PID;
  1397. mib[3] = pid;
  1398. len = sizeof(kp);
  1399. rc = sysctl(mib, 4, &kp, &len, NULL, 0);
  1400. if (rc != 0 && errno != ESRCH)
  1401. return false;
  1402. if (len == 0 || len != sizeof(kp))
  1403. return false;
  1404. return kp.ki_ppid == ppid;
  1405. }
  1406. #elif defined(HAVE_KVM_H)
  1407. static bool
  1408. pid_is_child(pid_t pid, pid_t ppid)
  1409. {
  1410. kvm_t *kd;
  1411. struct kinfo_proc *kp;
  1412. pid_t proc_ppid;
  1413. bool res = false;
  1414. kd = ssd_kvm_open();
  1415. kp = ssd_kvm_get_procs(kd, KERN_PROC_PID, pid, NULL);
  1416. if (kp == NULL)
  1417. goto cleanup;
  1418. #if defined(OS_FreeBSD)
  1419. proc_ppid = kp->ki_ppid;
  1420. #elif defined(OS_OpenBSD)
  1421. proc_ppid = kp->p_ppid;
  1422. #elif defined(OS_DragonFlyBSD)
  1423. proc_ppid = kp->kp_ppid;
  1424. #else
  1425. proc_ppid = kp->kp_proc.p_ppid;
  1426. #endif
  1427. res = (proc_ppid == ppid);
  1428. cleanup:
  1429. kvm_close(kd);
  1430. return res;
  1431. }
  1432. #endif
  1433. #if defined(OS_Linux)
  1434. static bool
  1435. pid_is_user(pid_t pid, uid_t uid)
  1436. {
  1437. struct stat sb;
  1438. char buf[32];
  1439. sprintf(buf, "/proc/%d", pid);
  1440. if (stat(buf, &sb) != 0)
  1441. return false;
  1442. return (sb.st_uid == uid);
  1443. }
  1444. #elif defined(OS_Hurd)
  1445. static bool
  1446. pid_is_user(pid_t pid, uid_t uid)
  1447. {
  1448. struct proc_stat *ps;
  1449. ps = get_proc_stat(pid, PSTAT_OWNER_UID);
  1450. return ps && (uid_t)proc_stat_owner_uid(ps) == uid;
  1451. }
  1452. #elif defined(OS_Darwin)
  1453. static bool
  1454. pid_is_user(pid_t pid, uid_t uid)
  1455. {
  1456. struct proc_bsdinfo info;
  1457. if (proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, sizeof(info)) < 0)
  1458. return false;
  1459. return info.pbi_ruid == uid;
  1460. }
  1461. #elif defined(OS_AIX)
  1462. static bool
  1463. pid_is_user(pid_t pid, uid_t uid)
  1464. {
  1465. struct psinfo psi;
  1466. if (!proc_get_psinfo(pid, &psi))
  1467. return false;
  1468. return psi.pr_uid == uid;
  1469. }
  1470. #elif defined(OS_HPUX)
  1471. static bool
  1472. pid_is_user(pid_t pid, uid_t uid)
  1473. {
  1474. struct pst_status pst;
  1475. if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
  1476. return false;
  1477. return ((uid_t)pst.pst_uid == uid);
  1478. }
  1479. #elif defined(OS_FreeBSD)
  1480. static bool
  1481. pid_is_user(pid_t pid, uid_t uid)
  1482. {
  1483. struct kinfo_proc kp;
  1484. int rc, mib[4];
  1485. size_t len;
  1486. mib[0] = CTL_KERN;
  1487. mib[1] = KERN_PROC;
  1488. mib[2] = KERN_PROC_PID;
  1489. mib[3] = pid;
  1490. len = sizeof(kp);
  1491. rc = sysctl(mib, 4, &kp, &len, NULL, 0);
  1492. if (rc != 0 && errno != ESRCH)
  1493. return false;
  1494. if (len == 0 || len != sizeof(kp))
  1495. return false;
  1496. return kp.ki_ruid == uid;
  1497. }
  1498. #elif defined(HAVE_KVM_H)
  1499. static bool
  1500. pid_is_user(pid_t pid, uid_t uid)
  1501. {
  1502. kvm_t *kd;
  1503. uid_t proc_uid;
  1504. struct kinfo_proc *kp;
  1505. bool res = false;
  1506. kd = ssd_kvm_open();
  1507. kp = ssd_kvm_get_procs(kd, KERN_PROC_PID, pid, NULL);
  1508. if (kp == NULL)
  1509. goto cleanup;
  1510. #if defined(OS_FreeBSD)
  1511. proc_uid = kp->ki_ruid;
  1512. #elif defined(OS_OpenBSD)
  1513. proc_uid = kp->p_ruid;
  1514. #elif defined(OS_DragonFlyBSD)
  1515. proc_uid = kp->kp_ruid;
  1516. #elif defined(OS_NetBSD)
  1517. proc_uid = kp->kp_eproc.e_pcred.p_ruid;
  1518. #else
  1519. if (kp->kp_proc.p_cred)
  1520. kvm_read(kd, (u_long)&(kp->kp_proc.p_cred->p_ruid),
  1521. &proc_uid, sizeof(uid_t));
  1522. else
  1523. goto cleanup;
  1524. #endif
  1525. res = (proc_uid == (uid_t)uid);
  1526. cleanup:
  1527. kvm_close(kd);
  1528. return res;
  1529. }
  1530. #endif
  1531. #if defined(OS_Linux)
  1532. static bool
  1533. pid_is_cmd(pid_t pid, const char *name)
  1534. {
  1535. const char *comm;
  1536. comm = proc_status_field(pid, "Name:");
  1537. if (comm == NULL)
  1538. return false;
  1539. return strcmp(comm, name) == 0;
  1540. }
  1541. #elif defined(OS_Hurd)
  1542. static bool
  1543. pid_is_cmd(pid_t pid, const char *name)
  1544. {
  1545. struct proc_stat *ps;
  1546. size_t argv0_len;
  1547. const char *argv0;
  1548. const char *binary_name;
  1549. ps = get_proc_stat(pid, PSTAT_ARGS);
  1550. if (ps == NULL)
  1551. return false;
  1552. argv0 = proc_stat_args(ps);
  1553. argv0_len = strlen(argv0) + 1;
  1554. binary_name = basename(argv0);
  1555. if (strcmp(binary_name, name) == 0)
  1556. return true;
  1557. /* XXX: This is all kinds of ugly, but on the Hurd there's no way to
  1558. * know the command name of a process, so we have to try to match
  1559. * also on argv[1] for the case of an interpreted script. */
  1560. if (proc_stat_args_len(ps) > argv0_len) {
  1561. const char *script_name = basename(argv0 + argv0_len);
  1562. return strcmp(script_name, name) == 0;
  1563. }
  1564. return false;
  1565. }
  1566. #elif defined(OS_AIX)
  1567. static bool
  1568. pid_is_cmd(pid_t pid, const char *name)
  1569. {
  1570. struct psinfo psi;
  1571. if (!proc_get_psinfo(pid, &psi))
  1572. return false;
  1573. return strcmp(psi.pr_fname, name) == 0;
  1574. }
  1575. #elif defined(OS_HPUX)
  1576. static bool
  1577. pid_is_cmd(pid_t pid, const char *name)
  1578. {
  1579. struct pst_status pst;
  1580. if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
  1581. return false;
  1582. return (strcmp(pst.pst_ucomm, name) == 0);
  1583. }
  1584. #elif defined(OS_Darwin)
  1585. static bool
  1586. pid_is_cmd(pid_t pid, const char *name)
  1587. {
  1588. char pathname[_POSIX_PATH_MAX];
  1589. if (proc_pidpath(pid, pathname, sizeof(pathname)) < 0)
  1590. return false;
  1591. return strcmp(pathname, name) == 0;
  1592. }
  1593. #elif defined(OS_FreeBSD)
  1594. static bool
  1595. pid_is_cmd(pid_t pid, const char *name)
  1596. {
  1597. struct kinfo_proc kp;
  1598. int rc, mib[4];
  1599. size_t len;
  1600. mib[0] = CTL_KERN;
  1601. mib[1] = KERN_PROC;
  1602. mib[2] = KERN_PROC_PID;
  1603. mib[3] = pid;
  1604. len = sizeof(kp);
  1605. rc = sysctl(mib, 4, &kp, &len, NULL, 0);
  1606. if (rc != 0 && errno != ESRCH)
  1607. return false;
  1608. if (len == 0 || len != sizeof(kp))
  1609. return false;
  1610. return strcmp(kp.ki_comm, name) == 0;
  1611. }
  1612. #elif defined(HAVE_KVM_H)
  1613. static bool
  1614. pid_is_cmd(pid_t pid, const char *name)
  1615. {
  1616. kvm_t *kd;
  1617. struct kinfo_proc *kp;
  1618. char *process_name;
  1619. bool res = false;
  1620. kd = ssd_kvm_open();
  1621. kp = ssd_kvm_get_procs(kd, KERN_PROC_PID, pid, NULL);
  1622. if (kp == NULL)
  1623. goto cleanup;
  1624. #if defined(OS_FreeBSD)
  1625. process_name = kp->ki_comm;
  1626. #elif defined(OS_OpenBSD)
  1627. process_name = kp->p_comm;
  1628. #elif defined(OS_DragonFlyBSD)
  1629. process_name = kp->kp_comm;
  1630. #else
  1631. process_name = kp->kp_proc.p_comm;
  1632. #endif
  1633. res = (strcmp(name, process_name) == 0);
  1634. cleanup:
  1635. kvm_close(kd);
  1636. return res;
  1637. }
  1638. #endif
  1639. #if defined(OS_Hurd)
  1640. static bool
  1641. pid_is_running(pid_t pid)
  1642. {
  1643. return get_proc_stat(pid, 0) != NULL;
  1644. }
  1645. #else /* !OS_Hurd */
  1646. static bool
  1647. pid_is_running(pid_t pid)
  1648. {
  1649. if (kill(pid, 0) == 0 || errno == EPERM)
  1650. return true;
  1651. else if (errno == ESRCH)
  1652. return false;
  1653. else
  1654. fatal("error checking pid %u status", pid);
  1655. }
  1656. #endif
  1657. static enum status_code
  1658. pid_check(pid_t pid)
  1659. {
  1660. if (execname && !pid_is_exec(pid, &exec_stat))
  1661. return STATUS_DEAD;
  1662. if (match_ppid > 0 && !pid_is_child(pid, match_ppid))
  1663. return STATUS_DEAD;
  1664. if (userspec && !pid_is_user(pid, user_id))
  1665. return STATUS_DEAD;
  1666. if (cmdname && !pid_is_cmd(pid, cmdname))
  1667. return STATUS_DEAD;
  1668. if (action != ACTION_STOP && !pid_is_running(pid))
  1669. return STATUS_DEAD;
  1670. pid_list_push(&found, pid);
  1671. return STATUS_OK;
  1672. }
  1673. static enum status_code
  1674. do_pidfile(const char *name)
  1675. {
  1676. FILE *f;
  1677. static pid_t pid = 0;
  1678. if (pid)
  1679. return pid_check(pid);
  1680. f = fopen(name, "r");
  1681. if (f) {
  1682. enum status_code pid_status;
  1683. if (fscanf(f, "%d", &pid) == 1)
  1684. pid_status = pid_check(pid);
  1685. else
  1686. pid_status = STATUS_UNKNOWN;
  1687. fclose(f);
  1688. if (pid_status == STATUS_DEAD)
  1689. return STATUS_DEAD_PIDFILE;
  1690. else
  1691. return pid_status;
  1692. } else if (errno == ENOENT)
  1693. return STATUS_DEAD;
  1694. else
  1695. fatal("unable to open pidfile %s", name);
  1696. }
  1697. #if defined(OS_Linux) || defined(OS_Solaris) || defined(OS_AIX)
  1698. static enum status_code
  1699. do_procinit(void)
  1700. {
  1701. DIR *procdir;
  1702. struct dirent *entry;
  1703. int foundany;
  1704. pid_t pid;
  1705. enum status_code prog_status = STATUS_DEAD;
  1706. procdir = opendir("/proc");
  1707. if (!procdir)
  1708. fatal("unable to opendir /proc");
  1709. foundany = 0;
  1710. while ((entry = readdir(procdir)) != NULL) {
  1711. enum status_code pid_status;
  1712. if (sscanf(entry->d_name, "%d", &pid) != 1)
  1713. continue;
  1714. foundany++;
  1715. pid_status = pid_check(pid);
  1716. if (pid_status < prog_status)
  1717. prog_status = pid_status;
  1718. }
  1719. closedir(procdir);
  1720. if (!foundany)
  1721. fatal("nothing in /proc - not mounted?");
  1722. return prog_status;
  1723. }
  1724. #elif defined(OS_Hurd)
  1725. static int
  1726. check_proc_stat(struct proc_stat *ps)
  1727. {
  1728. pid_check(proc_stat_pid(ps));
  1729. return 0;
  1730. }
  1731. static enum status_code
  1732. do_procinit(void)
  1733. {
  1734. if (!procset)
  1735. init_procset();
  1736. proc_stat_list_for_each(procset, check_proc_stat);
  1737. if (found)
  1738. return STATUS_OK;
  1739. else
  1740. return STATUS_DEAD;
  1741. }
  1742. #elif defined(OS_Darwin)
  1743. static enum status_code
  1744. do_procinit(void)
  1745. {
  1746. pid_t *pid_buf;
  1747. int i, npids, pid_bufsize;
  1748. enum status_code prog_status = STATUS_DEAD;
  1749. npids = proc_listallpids(NULL, 0);
  1750. if (npids == 0)
  1751. return STATUS_UNKNOWN;
  1752. /* Try to avoid sudden changes in number of PIDs. */
  1753. npids += 4096;
  1754. pid_bufsize = sizeof(pid_t) * npids;
  1755. pid_buf = xmalloc(pid_bufsize);
  1756. npids = proc_listallpids(pid_buf, pid_bufsize);
  1757. if (npids == 0)
  1758. return STATUS_UNKNOWN;
  1759. for (i = 0; i < npids; i++) {
  1760. enum status_code pid_status;
  1761. pid_status = pid_check(pid_buf[i]);
  1762. if (pid_status < prog_status)
  1763. prog_status = pid_status;
  1764. }
  1765. free(pid_buf);
  1766. return prog_status;
  1767. }
  1768. #elif defined(OS_HPUX)
  1769. static enum status_code
  1770. do_procinit(void)
  1771. {
  1772. struct pst_status pst[10];
  1773. int i, count;
  1774. int idx = 0;
  1775. enum status_code prog_status = STATUS_DEAD;
  1776. while ((count = pstat_getproc(pst, sizeof(pst[0]), 10, idx)) > 0) {
  1777. enum status_code pid_status;
  1778. for (i = 0; i < count; i++) {
  1779. pid_status = pid_check(pst[i].pst_pid);
  1780. if (pid_status < prog_status)
  1781. prog_status = pid_status;
  1782. }
  1783. idx = pst[count - 1].pst_idx + 1;
  1784. }
  1785. return prog_status;
  1786. }
  1787. #elif defined(OS_FreeBSD)
  1788. static enum status_code
  1789. do_procinit(void)
  1790. {
  1791. struct kinfo_proc *kp;
  1792. int rc, mib[3];
  1793. size_t len = 0;
  1794. int nentries, i;
  1795. enum status_code prog_status = STATUS_DEAD;
  1796. mib[0] = CTL_KERN;
  1797. mib[1] = KERN_PROC;
  1798. mib[2] = KERN_PROC_PROC;
  1799. rc = sysctl(mib, 3, NULL, &len, NULL, 0);
  1800. if (rc != 0 && errno != ESRCH)
  1801. return STATUS_UNKNOWN;
  1802. if (len == 0)
  1803. return STATUS_UNKNOWN;
  1804. kp = xmalloc(len);
  1805. rc = sysctl(mib, 3, kp, &len, NULL, 0);
  1806. if (rc != 0 && errno != ESRCH)
  1807. return STATUS_UNKNOWN;
  1808. if (len == 0)
  1809. return STATUS_UNKNOWN;
  1810. nentries = len / sizeof(*kp);
  1811. for (i = 0; i < nentries; i++) {
  1812. enum status_code pid_status;
  1813. pid_status = pid_check(kp[i].ki_pid);
  1814. if (pid_status < prog_status)
  1815. prog_status = pid_status;
  1816. }
  1817. free(kp);
  1818. return prog_status;
  1819. }
  1820. #elif defined(HAVE_KVM_H)
  1821. static enum status_code
  1822. do_procinit(void)
  1823. {
  1824. kvm_t *kd;
  1825. int nentries, i;
  1826. struct kinfo_proc *kp;
  1827. enum status_code prog_status = STATUS_DEAD;
  1828. kd = ssd_kvm_open();
  1829. kp = ssd_kvm_get_procs(kd, KERN_PROC_ALL, 0, &nentries);
  1830. for (i = 0; i < nentries; i++) {
  1831. enum status_code pid_status;
  1832. pid_t pid;
  1833. #if defined(OS_FreeBSD)
  1834. pid = kp[i].ki_pid;
  1835. #elif defined(OS_OpenBSD)
  1836. pid = kp[i].p_pid;
  1837. #elif defined(OS_DragonFlyBSD)
  1838. pid = kp[i].kp_pid;
  1839. #else
  1840. pid = kp[i].kp_proc.p_pid;
  1841. #endif
  1842. pid_status = pid_check(pid);
  1843. if (pid_status < prog_status)
  1844. prog_status = pid_status;
  1845. }
  1846. kvm_close(kd);
  1847. return prog_status;
  1848. }
  1849. #endif
  1850. static enum status_code
  1851. do_findprocs(void)
  1852. {
  1853. pid_list_free(&found);
  1854. if (match_pid > 0)
  1855. return pid_check(match_pid);
  1856. else if (pidfile)
  1857. return do_pidfile(pidfile);
  1858. else
  1859. return do_procinit();
  1860. }
  1861. static int
  1862. do_start(int argc, char **argv)
  1863. {
  1864. int devnull_fd = -1;
  1865. gid_t rgid;
  1866. uid_t ruid;
  1867. do_findprocs();
  1868. if (found) {
  1869. if (quietmode <= 0)
  1870. printf("%s already running.\n", execname ? execname : "process");
  1871. return exitnodo;
  1872. }
  1873. if (testmode && quietmode <= 0) {
  1874. printf("Would start %s ", startas);
  1875. while (argc-- > 0)
  1876. printf("%s ", *argv++);
  1877. if (changeuser != NULL) {
  1878. printf(" (as user %s[%d]", changeuser, runas_uid);
  1879. if (changegroup != NULL)
  1880. printf(", and group %s[%d])", changegroup, runas_gid);
  1881. else
  1882. printf(")");
  1883. }
  1884. if (changeroot != NULL)
  1885. printf(" in directory %s", changeroot);
  1886. if (nicelevel)
  1887. printf(", and add %i to the priority", nicelevel);
  1888. if (proc_sched)
  1889. printf(", with scheduling policy %s with priority %i",
  1890. proc_sched->policy_name, proc_sched->priority);
  1891. if (io_sched)
  1892. printf(", with IO scheduling class %s with priority %i",
  1893. io_sched->policy_name, io_sched->priority);
  1894. printf(".\n");
  1895. }
  1896. if (testmode)
  1897. return 0;
  1898. if (quietmode < 0)
  1899. printf("Starting %s...\n", startas);
  1900. *--argv = startas;
  1901. if (background)
  1902. /* Ok, we need to detach this process. */
  1903. daemonize();
  1904. else if (mpidfile && pidfile != NULL)
  1905. /* User wants _us_ to make the pidfile, but detach themself! */
  1906. write_pidfile(pidfile, getpid());
  1907. if (background && close_io) {
  1908. devnull_fd = open("/dev/null", O_RDWR);
  1909. if (devnull_fd < 0)
  1910. fatal("unable to open '%s'", "/dev/null");
  1911. }
  1912. if (nicelevel) {
  1913. errno = 0;
  1914. if ((nice(nicelevel) == -1) && (errno != 0))
  1915. fatal("unable to alter nice level by %i", nicelevel);
  1916. }
  1917. if (proc_sched)
  1918. set_proc_schedule(proc_sched);
  1919. if (io_sched)
  1920. set_io_schedule(io_sched);
  1921. if (umask_value >= 0)
  1922. umask(umask_value);
  1923. if (changeroot != NULL) {
  1924. if (chdir(changeroot) < 0)
  1925. fatal("unable to chdir() to %s", changeroot);
  1926. if (chroot(changeroot) < 0)
  1927. fatal("unable to chroot() to %s", changeroot);
  1928. }
  1929. if (chdir(changedir) < 0)
  1930. fatal("unable to chdir() to %s", changedir);
  1931. rgid = getgid();
  1932. ruid = getuid();
  1933. if (changegroup != NULL) {
  1934. if (rgid != (gid_t)runas_gid)
  1935. if (setgid(runas_gid))
  1936. fatal("unable to set gid to %d", runas_gid);
  1937. }
  1938. if (changeuser != NULL) {
  1939. /* We assume that if our real user and group are the same as
  1940. * the ones we should switch to, the supplementary groups
  1941. * will be already in place. */
  1942. if (rgid != (gid_t)runas_gid || ruid != (uid_t)runas_uid)
  1943. if (initgroups(changeuser, runas_gid))
  1944. fatal("unable to set initgroups() with gid %d",
  1945. runas_gid);
  1946. if (ruid != (uid_t)runas_uid)
  1947. if (setuid(runas_uid))
  1948. fatal("unable to set uid to %s", changeuser);
  1949. }
  1950. if (background && close_io) {
  1951. int i;
  1952. dup2(devnull_fd, 0); /* stdin */
  1953. dup2(devnull_fd, 1); /* stdout */
  1954. dup2(devnull_fd, 2); /* stderr */
  1955. /* Now close all extra fds. */
  1956. for (i = get_open_fd_max() - 1; i >= 3; --i)
  1957. close(i);
  1958. }
  1959. execv(startas, argv);
  1960. fatal("unable to start %s", startas);
  1961. }
  1962. static void
  1963. do_stop(int sig_num, int *n_killed, int *n_notkilled)
  1964. {
  1965. struct pid_list *p;
  1966. do_findprocs();
  1967. *n_killed = 0;
  1968. *n_notkilled = 0;
  1969. if (!found)
  1970. return;
  1971. pid_list_free(&killed);
  1972. for (p = found; p; p = p->next) {
  1973. if (testmode) {
  1974. if (quietmode <= 0)
  1975. printf("Would send signal %d to %d.\n",
  1976. sig_num, p->pid);
  1977. (*n_killed)++;
  1978. } else if (kill(p->pid, sig_num) == 0) {
  1979. pid_list_push(&killed, p->pid);
  1980. (*n_killed)++;
  1981. } else {
  1982. if (sig_num)
  1983. warning("failed to kill %d: %s\n",
  1984. p->pid, strerror(errno));
  1985. (*n_notkilled)++;
  1986. }
  1987. }
  1988. }
  1989. static void
  1990. do_stop_summary(int retry_nr)
  1991. {
  1992. struct pid_list *p;
  1993. if (quietmode >= 0 || !killed)
  1994. return;
  1995. printf("Stopped %s (pid", what_stop);
  1996. for (p = killed; p; p = p->next)
  1997. printf(" %d", p->pid);
  1998. putchar(')');
  1999. if (retry_nr > 0)
  2000. printf(", retry #%d", retry_nr);
  2001. printf(".\n");
  2002. }
  2003. static void DPKG_ATTR_PRINTF(1)
  2004. set_what_stop(const char *format, ...)
  2005. {
  2006. va_list arglist;
  2007. int rc;
  2008. va_start(arglist, format);
  2009. rc = vasprintf(&what_stop, format, arglist);
  2010. va_end(arglist);
  2011. if (rc < 0)
  2012. fatal("cannot allocate formatted string");
  2013. }
  2014. /*
  2015. * We want to keep polling for the processes, to see if they've exited, or
  2016. * until the timeout expires.
  2017. *
  2018. * This is a somewhat complicated algorithm to try to ensure that we notice
  2019. * reasonably quickly when all the processes have exited, but don't spend
  2020. * too much CPU time polling. In particular, on a fast machine with
  2021. * quick-exiting daemons we don't want to delay system shutdown too much,
  2022. * whereas on a slow one, or where processes are taking some time to exit,
  2023. * we want to increase the polling interval.
  2024. *
  2025. * The algorithm is as follows: we measure the elapsed time it takes to do
  2026. * one poll(), and wait a multiple of this time for the next poll. However,
  2027. * if that would put us past the end of the timeout period we wait only as
  2028. * long as the timeout period, but in any case we always wait at least
  2029. * MIN_POLL_INTERVAL (20ms). The multiple (‘ratio’) starts out as 2, and
  2030. * increases by 1 for each poll to a maximum of 10; so we use up to between
  2031. * 30% and 10% of the machine's resources (assuming a few reasonable things
  2032. * about system performance).
  2033. */
  2034. static bool
  2035. do_stop_timeout(int timeout, int *n_killed, int *n_notkilled)
  2036. {
  2037. struct timespec stopat, before, after, interval, maxinterval;
  2038. int rc, ratio;
  2039. timespec_gettime(&stopat);
  2040. stopat.tv_sec += timeout;
  2041. ratio = 1;
  2042. for (;;) {
  2043. timespec_gettime(&before);
  2044. if (timespec_cmp(&before, &stopat, >))
  2045. return false;
  2046. do_stop(0, n_killed, n_notkilled);
  2047. if (!*n_killed)
  2048. return true;
  2049. timespec_gettime(&after);
  2050. if (!timespec_cmp(&after, &stopat, <))
  2051. return false;
  2052. if (ratio < 10)
  2053. ratio++;
  2054. timespec_sub(&stopat, &after, &maxinterval);
  2055. timespec_sub(&after, &before, &interval);
  2056. timespec_mul(&interval, ratio);
  2057. if (interval.tv_sec < 0 || interval.tv_nsec < 0)
  2058. interval.tv_sec = interval.tv_nsec = 0;
  2059. if (timespec_cmp(&interval, &maxinterval, >))
  2060. interval = maxinterval;
  2061. if (interval.tv_sec == 0 &&
  2062. interval.tv_nsec <= MIN_POLL_INTERVAL)
  2063. interval.tv_nsec = MIN_POLL_INTERVAL;
  2064. rc = pselect(0, NULL, NULL, NULL, &interval, NULL);
  2065. if (rc < 0 && errno != EINTR)
  2066. fatal("select() failed for pause");
  2067. }
  2068. }
  2069. static int
  2070. finish_stop_schedule(bool anykilled)
  2071. {
  2072. if (rpidfile && pidfile && !testmode)
  2073. remove_pidfile(pidfile);
  2074. if (anykilled)
  2075. return 0;
  2076. if (quietmode <= 0)
  2077. printf("No %s found running; none killed.\n", what_stop);
  2078. return exitnodo;
  2079. }
  2080. static int
  2081. run_stop_schedule(void)
  2082. {
  2083. int position, n_killed, n_notkilled, value, retry_nr;
  2084. bool anykilled;
  2085. if (testmode) {
  2086. if (schedule != NULL) {
  2087. if (quietmode <= 0)
  2088. printf("Ignoring --retry in test mode\n");
  2089. schedule = NULL;
  2090. }
  2091. }
  2092. if (cmdname)
  2093. set_what_stop("%s", cmdname);
  2094. else if (execname)
  2095. set_what_stop("%s", execname);
  2096. else if (pidfile)
  2097. set_what_stop("process in pidfile '%s'", pidfile);
  2098. else if (match_pid > 0)
  2099. set_what_stop("process with pid %d", match_pid);
  2100. else if (match_ppid > 0)
  2101. set_what_stop("process(es) with parent pid %d", match_ppid);
  2102. else if (userspec)
  2103. set_what_stop("process(es) owned by '%s'", userspec);
  2104. else
  2105. fatal("internal error, no match option, please report");
  2106. anykilled = false;
  2107. retry_nr = 0;
  2108. if (schedule == NULL) {
  2109. do_stop(signal_nr, &n_killed, &n_notkilled);
  2110. do_stop_summary(0);
  2111. if (n_notkilled > 0 && quietmode <= 0)
  2112. printf("%d pids were not killed\n", n_notkilled);
  2113. if (n_killed)
  2114. anykilled = true;
  2115. return finish_stop_schedule(anykilled);
  2116. }
  2117. for (position = 0; position < schedule_length; position++) {
  2118. reposition:
  2119. value = schedule[position].value;
  2120. n_notkilled = 0;
  2121. switch (schedule[position].type) {
  2122. case sched_goto:
  2123. position = value;
  2124. goto reposition;
  2125. case sched_signal:
  2126. do_stop(value, &n_killed, &n_notkilled);
  2127. do_stop_summary(retry_nr++);
  2128. if (!n_killed)
  2129. return finish_stop_schedule(anykilled);
  2130. else
  2131. anykilled = true;
  2132. continue;
  2133. case sched_timeout:
  2134. if (do_stop_timeout(value, &n_killed, &n_notkilled))
  2135. return finish_stop_schedule(anykilled);
  2136. else
  2137. continue;
  2138. default:
  2139. assert(!"schedule[].type value must be valid");
  2140. }
  2141. }
  2142. if (quietmode <= 0)
  2143. printf("Program %s, %d process(es), refused to die.\n",
  2144. what_stop, n_killed);
  2145. return 2;
  2146. }
  2147. int
  2148. main(int argc, char **argv)
  2149. {
  2150. progname = argv[0];
  2151. parse_options(argc, argv);
  2152. setup_options();
  2153. argc -= optind;
  2154. argv += optind;
  2155. if (action == ACTION_START)
  2156. return do_start(argc, argv);
  2157. else if (action == ACTION_STOP)
  2158. return run_stop_schedule();
  2159. else if (action == ACTION_STATUS)
  2160. return do_findprocs();
  2161. return 0;
  2162. }