start-stop-daemon.c 56 KB

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