start-stop-daemon.c 56 KB

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