start-stop-daemon.c 54 KB

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