3
0

init.c 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini init implementation for busybox
  4. *
  5. * Copyright (C) 1995, 1996 by Bruce Perens <bruce@pixar.com>.
  6. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  7. * Adjusted by so many folks, it's impossible to keep track.
  8. *
  9. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  10. */
  11. //config:config INIT
  12. //config: bool "init"
  13. //config: default y
  14. //config: select FEATURE_SYSLOG
  15. //config: help
  16. //config: init is the first program run when the system boots.
  17. //config:
  18. //config:config FEATURE_USE_INITTAB
  19. //config: bool "Support reading an inittab file"
  20. //config: default y
  21. //config: depends on INIT
  22. //config: help
  23. //config: Allow init to read an inittab file when the system boot.
  24. //config:
  25. //config:config FEATURE_KILL_REMOVED
  26. //config: bool "Support killing processes that have been removed from inittab"
  27. //config: default n
  28. //config: depends on FEATURE_USE_INITTAB
  29. //config: help
  30. //config: When respawn entries are removed from inittab and a SIGHUP is
  31. //config: sent to init, this option will make init kill the processes
  32. //config: that have been removed.
  33. //config:
  34. //config:config FEATURE_KILL_DELAY
  35. //config: int "How long to wait between TERM and KILL (0 - send TERM only)" if FEATURE_KILL_REMOVED
  36. //config: range 0 1024
  37. //config: default 0
  38. //config: depends on FEATURE_KILL_REMOVED
  39. //config: help
  40. //config: With nonzero setting, init sends TERM, forks, child waits N
  41. //config: seconds, sends KILL and exits. Setting it too high is unwise
  42. //config: (child will hang around for too long and could actually kill
  43. //config: the wrong process!)
  44. //config:
  45. //config:config FEATURE_INIT_SCTTY
  46. //config: bool "Run commands with leading dash with controlling tty"
  47. //config: default y
  48. //config: depends on INIT
  49. //config: help
  50. //config: If this option is enabled, init will try to give a controlling
  51. //config: tty to any command which has leading hyphen (often it's "-/bin/sh").
  52. //config: More precisely, init will do "ioctl(STDIN_FILENO, TIOCSCTTY, 0)".
  53. //config: If device attached to STDIN_FILENO can be a ctty but is not yet
  54. //config: a ctty for other session, it will become this process' ctty.
  55. //config: This is not the traditional init behavour, but is often what you want
  56. //config: in an embedded system where the console is only accessed during
  57. //config: development or for maintenance.
  58. //config: NB: using cttyhack applet may work better.
  59. //config:
  60. //config:config FEATURE_INIT_SYSLOG
  61. //config: bool "Enable init to write to syslog"
  62. //config: default y
  63. //config: depends on INIT
  64. //config:
  65. //config:config FEATURE_EXTRA_QUIET
  66. //config: bool "Be _extra_ quiet on boot"
  67. //config: default y
  68. //config: depends on INIT
  69. //config: help
  70. //config: Prevent init from logging some messages to the console during boot.
  71. //config:
  72. //config:config FEATURE_INIT_COREDUMPS
  73. //config: bool "Support dumping core for child processes (debugging only)"
  74. //config: default y
  75. //config: depends on INIT
  76. //config: help
  77. //config: If this option is enabled and the file /.init_enable_core
  78. //config: exists, then init will call setrlimit() to allow unlimited
  79. //config: core file sizes. If this option is disabled, processes
  80. //config: will not generate any core files.
  81. //config:
  82. //config:config FEATURE_INITRD
  83. //config: bool "Support running init from within an initrd (not initramfs)"
  84. //config: default y
  85. //config: depends on INIT
  86. //config: help
  87. //config: Legacy support for running init under the old-style initrd. Allows
  88. //config: the name linuxrc to act as init, and it doesn't assume init is PID 1.
  89. //config:
  90. //config: This does not apply to initramfs, which runs /init as PID 1 and
  91. //config: requires no special support.
  92. //config:
  93. //config:config INIT_TERMINAL_TYPE
  94. //config: string "Initial terminal type"
  95. //config: default "linux"
  96. //config: depends on INIT
  97. //config: help
  98. //config: This is the initial value set by init for the TERM environment
  99. //config: variable. This variable is used by programs which make use of
  100. //config: extended terminal capabilities.
  101. //config:
  102. //config: Note that on Linux, init attempts to detect serial terminal and
  103. //config: sets TERM to "vt102" if one is found.
  104. //applet:IF_INIT(APPLET(init, BB_DIR_SBIN, BB_SUID_DROP))
  105. //applet:IF_FEATURE_INITRD(APPLET_ODDNAME(linuxrc, init, BB_DIR_ROOT, BB_SUID_DROP, linuxrc))
  106. //kbuild:lib-$(CONFIG_INIT) += init.o
  107. #define DEBUG_SEGV_HANDLER 0
  108. #include "libbb.h"
  109. #include <syslog.h>
  110. #include <paths.h>
  111. #include <sys/resource.h>
  112. #ifdef __linux__
  113. # include <linux/vt.h>
  114. # include <sys/sysinfo.h>
  115. #endif
  116. #include "reboot.h" /* reboot() constants */
  117. #if DEBUG_SEGV_HANDLER
  118. # undef _GNU_SOURCE
  119. # define _GNU_SOURCE 1
  120. # undef __USE_GNU
  121. # define __USE_GNU 1
  122. # include <execinfo.h>
  123. # include <sys/ucontext.h>
  124. #endif
  125. /* Used only for sanitizing purposes in set_sane_term() below. On systems where
  126. * the baud rate is stored in a separate field, we can safely disable them. */
  127. #ifndef CBAUD
  128. # define CBAUD 0
  129. # define CBAUDEX 0
  130. #endif
  131. /* Was a CONFIG_xxx option. A lot of people were building
  132. * not fully functional init by switching it on! */
  133. #define DEBUG_INIT 0
  134. #define CONSOLE_NAME_SIZE 32
  135. /* Default sysinit script. */
  136. #ifndef INIT_SCRIPT
  137. # define INIT_SCRIPT "/etc/init.d/rcS"
  138. #endif
  139. /* Each type of actions can appear many times. They will be
  140. * handled in order. RESTART is an exception, only 1st is used.
  141. */
  142. /* Start these actions first and wait for completion */
  143. #define SYSINIT 0x01
  144. /* Start these after SYSINIT and wait for completion */
  145. #define WAIT 0x02
  146. /* Start these after WAIT and *dont* wait for completion */
  147. #define ONCE 0x04
  148. /*
  149. * NB: while SYSINIT/WAIT/ONCE are being processed,
  150. * SIGHUP ("reread /etc/inittab") will be processed only after
  151. * each group of actions. If new inittab adds, say, a SYSINIT action,
  152. * it will not be run, since init is already "past SYSINIT stage".
  153. */
  154. /* Start these after ONCE are started, restart on exit */
  155. #define RESPAWN 0x08
  156. /* Like RESPAWN, but wait for <Enter> to be pressed on tty */
  157. #define ASKFIRST 0x10
  158. /*
  159. * Start these on SIGINT, and wait for completion.
  160. * Then go back to respawning RESPAWN and ASKFIRST actions.
  161. * NB: kernel sends SIGINT to us if Ctrl-Alt-Del was pressed.
  162. */
  163. #define CTRLALTDEL 0x20
  164. /*
  165. * Start these before killing all processes in preparation for
  166. * running RESTART actions or doing low-level halt/reboot/poweroff
  167. * (initiated by SIGUSR1/SIGTERM/SIGUSR2).
  168. * Wait for completion before proceeding.
  169. */
  170. #define SHUTDOWN 0x40
  171. /*
  172. * exec() on SIGQUIT. SHUTDOWN actions are started and waited for,
  173. * then all processes are killed, then init exec's 1st RESTART action,
  174. * replacing itself by it. If no RESTART action specified,
  175. * SIGQUIT has no effect.
  176. */
  177. #define RESTART 0x80
  178. /* A linked list of init_actions, to be read from inittab */
  179. struct init_action {
  180. struct init_action *next;
  181. pid_t pid;
  182. uint8_t action_type;
  183. char terminal[CONSOLE_NAME_SIZE];
  184. char command[1];
  185. };
  186. static struct init_action *init_action_list = NULL;
  187. static const char *log_console = VC_5;
  188. enum {
  189. L_LOG = 0x1,
  190. L_CONSOLE = 0x2,
  191. };
  192. /* Print a message to the specified device.
  193. * "where" may be bitwise-or'd from L_LOG | L_CONSOLE
  194. * NB: careful, we can be called after vfork!
  195. */
  196. #define dbg_message(...) do { if (DEBUG_INIT) message(__VA_ARGS__); } while (0)
  197. static void message(int where, const char *fmt, ...)
  198. __attribute__ ((format(printf, 2, 3)));
  199. static void message(int where, const char *fmt, ...)
  200. {
  201. va_list arguments;
  202. unsigned l;
  203. char msg[128];
  204. msg[0] = '\r';
  205. va_start(arguments, fmt);
  206. l = 1 + vsnprintf(msg + 1, sizeof(msg) - 2, fmt, arguments);
  207. if (l > sizeof(msg) - 2)
  208. l = sizeof(msg) - 2;
  209. va_end(arguments);
  210. #if ENABLE_FEATURE_INIT_SYSLOG
  211. msg[l] = '\0';
  212. if (where & L_LOG) {
  213. /* Log the message to syslogd */
  214. openlog(applet_name, 0, LOG_DAEMON);
  215. /* don't print "\r" */
  216. syslog(LOG_INFO, "%s", msg + 1);
  217. closelog();
  218. }
  219. msg[l++] = '\n';
  220. msg[l] = '\0';
  221. #else
  222. {
  223. static int log_fd = -1;
  224. msg[l++] = '\n';
  225. msg[l] = '\0';
  226. /* Take full control of the log tty, and never close it.
  227. * It's mine, all mine! Muhahahaha! */
  228. if (log_fd < 0) {
  229. if (!log_console) {
  230. log_fd = STDERR_FILENO;
  231. } else {
  232. log_fd = device_open(log_console, O_WRONLY | O_NONBLOCK | O_NOCTTY);
  233. if (log_fd < 0) {
  234. bb_error_msg("can't log to %s", log_console);
  235. where = L_CONSOLE;
  236. } else {
  237. close_on_exec_on(log_fd);
  238. }
  239. }
  240. }
  241. if (where & L_LOG) {
  242. full_write(log_fd, msg, l);
  243. if (log_fd == STDERR_FILENO)
  244. return; /* don't print dup messages */
  245. }
  246. }
  247. #endif
  248. if (where & L_CONSOLE) {
  249. /* Send console messages to console so people will see them. */
  250. full_write(STDERR_FILENO, msg, l);
  251. }
  252. }
  253. static void console_init(void)
  254. {
  255. #ifdef VT_OPENQRY
  256. int vtno;
  257. #endif
  258. char *s;
  259. s = getenv("CONSOLE");
  260. if (!s)
  261. s = getenv("console");
  262. if (s) {
  263. int fd = open(s, O_RDWR | O_NONBLOCK | O_NOCTTY);
  264. if (fd >= 0) {
  265. dup2(fd, STDIN_FILENO);
  266. dup2(fd, STDOUT_FILENO);
  267. xmove_fd(fd, STDERR_FILENO);
  268. }
  269. dbg_message(L_LOG, "console='%s'", s);
  270. } else {
  271. /* Make sure fd 0,1,2 are not closed
  272. * (so that they won't be used by future opens) */
  273. bb_sanitize_stdio();
  274. // Users report problems
  275. // /* Make sure init can't be blocked by writing to stderr */
  276. // fcntl(STDERR_FILENO, F_SETFL, fcntl(STDERR_FILENO, F_GETFL) | O_NONBLOCK);
  277. }
  278. s = getenv("TERM");
  279. #ifdef VT_OPENQRY
  280. if (ioctl(STDIN_FILENO, VT_OPENQRY, &vtno) != 0) {
  281. /* Not a linux terminal, probably serial console.
  282. * Force the TERM setting to vt102
  283. * if TERM is set to linux (the default) */
  284. if (!s || strcmp(s, "linux") == 0)
  285. putenv((char*)"TERM=vt102");
  286. if (!ENABLE_FEATURE_INIT_SYSLOG)
  287. log_console = NULL;
  288. } else
  289. #endif
  290. if (!s)
  291. putenv((char*)"TERM=" CONFIG_INIT_TERMINAL_TYPE);
  292. }
  293. /* Set terminal settings to reasonable defaults.
  294. * NB: careful, we can be called after vfork! */
  295. static void set_sane_term(void)
  296. {
  297. struct termios tty;
  298. tcgetattr(STDIN_FILENO, &tty);
  299. /* set control chars */
  300. tty.c_cc[VINTR] = 3; /* C-c */
  301. tty.c_cc[VQUIT] = 28; /* C-\ */
  302. tty.c_cc[VERASE] = 127; /* C-? */
  303. tty.c_cc[VKILL] = 21; /* C-u */
  304. tty.c_cc[VEOF] = 4; /* C-d */
  305. tty.c_cc[VSTART] = 17; /* C-q */
  306. tty.c_cc[VSTOP] = 19; /* C-s */
  307. tty.c_cc[VSUSP] = 26; /* C-z */
  308. #ifdef __linux__
  309. /* use line discipline 0 */
  310. tty.c_line = 0;
  311. #endif
  312. /* Make it be sane */
  313. #ifndef CRTSCTS
  314. # define CRTSCTS 0
  315. #endif
  316. /* added CRTSCTS to fix Debian bug 528560 */
  317. tty.c_cflag &= CBAUD | CBAUDEX | CSIZE | CSTOPB | PARENB | PARODD | CRTSCTS;
  318. tty.c_cflag |= CREAD | HUPCL | CLOCAL;
  319. /* input modes */
  320. tty.c_iflag = ICRNL | IXON | IXOFF;
  321. /* output modes */
  322. tty.c_oflag = OPOST | ONLCR;
  323. /* local modes */
  324. tty.c_lflag = ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE | IEXTEN;
  325. tcsetattr_stdin_TCSANOW(&tty);
  326. }
  327. /* Open the new terminal device.
  328. * NB: careful, we can be called after vfork! */
  329. static int open_stdio_to_tty(const char* tty_name)
  330. {
  331. /* empty tty_name means "use init's tty", else... */
  332. if (tty_name[0]) {
  333. int fd;
  334. close(STDIN_FILENO);
  335. /* fd can be only < 0 or 0: */
  336. fd = device_open(tty_name, O_RDWR);
  337. if (fd) {
  338. message(L_LOG | L_CONSOLE, "can't open %s: %s",
  339. tty_name, strerror(errno));
  340. return 0; /* failure */
  341. }
  342. dup2(STDIN_FILENO, STDOUT_FILENO);
  343. dup2(STDIN_FILENO, STDERR_FILENO);
  344. }
  345. set_sane_term();
  346. return 1; /* success */
  347. }
  348. static void reset_sighandlers_and_unblock_sigs(void)
  349. {
  350. bb_signals(0
  351. + (1 << SIGUSR1)
  352. + (1 << SIGUSR2)
  353. + (1 << SIGTERM)
  354. + (1 << SIGQUIT)
  355. + (1 << SIGINT)
  356. + (1 << SIGHUP)
  357. + (1 << SIGTSTP)
  358. + (1 << SIGSTOP)
  359. , SIG_DFL);
  360. sigprocmask_allsigs(SIG_UNBLOCK);
  361. }
  362. /* Wrapper around exec:
  363. * Takes string.
  364. * If chars like '>' detected, execs '[-]/bin/sh -c "exec ......."'.
  365. * Otherwise splits words on whitespace, deals with leading dash,
  366. * and uses plain exec().
  367. * NB: careful, we can be called after vfork!
  368. */
  369. static void init_exec(const char *command)
  370. {
  371. /* +8 allows to write VLA sizes below more efficiently: */
  372. unsigned command_size = strlen(command) + 8;
  373. /* strlen(command) + strlen("exec ")+1: */
  374. char buf[command_size];
  375. /* strlen(command) / 2 + 4: */
  376. char *cmd[command_size / 2];
  377. int dash;
  378. dash = (command[0] == '-' /* maybe? && command[1] == '/' */);
  379. command += dash;
  380. /* See if any special /bin/sh requiring characters are present */
  381. if (strpbrk(command, "~`!$^&*()=|\\{}[];\"'<>?") != NULL) {
  382. sprintf(buf, "exec %s", command); /* excluding "-" */
  383. /* NB: LIBBB_DEFAULT_LOGIN_SHELL define has leading dash */
  384. cmd[0] = (char*)(LIBBB_DEFAULT_LOGIN_SHELL + !dash);
  385. cmd[1] = (char*)"-c";
  386. cmd[2] = buf;
  387. cmd[3] = NULL;
  388. command = LIBBB_DEFAULT_LOGIN_SHELL + 1;
  389. } else {
  390. /* Convert command (char*) into cmd (char**, one word per string) */
  391. char *word, *next;
  392. int i = 0;
  393. next = strcpy(buf, command - dash); /* command including "-" */
  394. command = next + dash;
  395. while ((word = strsep(&next, " \t")) != NULL) {
  396. if (*word != '\0') { /* not two spaces/tabs together? */
  397. cmd[i] = word;
  398. i++;
  399. }
  400. }
  401. cmd[i] = NULL;
  402. }
  403. /* If we saw leading "-", it is interactive shell.
  404. * Try harder to give it a controlling tty.
  405. */
  406. if (ENABLE_FEATURE_INIT_SCTTY && dash) {
  407. /* _Attempt_ to make stdin a controlling tty. */
  408. ioctl(STDIN_FILENO, TIOCSCTTY, 0 /*only try, don't steal*/);
  409. }
  410. /* Here command never contains the dash, cmd[0] might */
  411. BB_EXECVP(command, cmd);
  412. message(L_LOG | L_CONSOLE, "can't run '%s': %s", command, strerror(errno));
  413. /* returns if execvp fails */
  414. }
  415. /* Used only by run_actions */
  416. static pid_t run(const struct init_action *a)
  417. {
  418. pid_t pid;
  419. /* Careful: don't be affected by a signal in vforked child */
  420. sigprocmask_allsigs(SIG_BLOCK);
  421. if (BB_MMU && (a->action_type & ASKFIRST))
  422. pid = fork();
  423. else
  424. pid = vfork();
  425. if (pid < 0)
  426. message(L_LOG | L_CONSOLE, "can't fork");
  427. if (pid) {
  428. sigprocmask_allsigs(SIG_UNBLOCK);
  429. return pid; /* Parent or error */
  430. }
  431. /* Child */
  432. /* Reset signal handlers that were set by the parent process */
  433. reset_sighandlers_and_unblock_sigs();
  434. /* Create a new session and make ourself the process group leader */
  435. setsid();
  436. /* Open the new terminal device */
  437. if (!open_stdio_to_tty(a->terminal))
  438. _exit(EXIT_FAILURE);
  439. /* NB: on NOMMU we can't wait for input in child, so
  440. * "askfirst" will work the same as "respawn". */
  441. if (BB_MMU && (a->action_type & ASKFIRST)) {
  442. static const char press_enter[] ALIGN1 =
  443. #ifdef CUSTOMIZED_BANNER
  444. #include CUSTOMIZED_BANNER
  445. #endif
  446. "\nPlease press Enter to activate this console. ";
  447. char c;
  448. /*
  449. * Save memory by not exec-ing anything large (like a shell)
  450. * before the user wants it. This is critical if swap is not
  451. * enabled and the system has low memory. Generally this will
  452. * be run on the second virtual console, and the first will
  453. * be allowed to start a shell or whatever an init script
  454. * specifies.
  455. */
  456. dbg_message(L_LOG, "waiting for enter to start '%s'"
  457. "(pid %d, tty '%s')\n",
  458. a->command, getpid(), a->terminal);
  459. full_write(STDOUT_FILENO, press_enter, sizeof(press_enter) - 1);
  460. while (safe_read(STDIN_FILENO, &c, 1) == 1 && c != '\n')
  461. continue;
  462. }
  463. /*
  464. * When a file named /.init_enable_core exists, setrlimit is called
  465. * before processes are spawned to set core file size as unlimited.
  466. * This is for debugging only. Don't use this is production, unless
  467. * you want core dumps lying about....
  468. */
  469. if (ENABLE_FEATURE_INIT_COREDUMPS) {
  470. if (access("/.init_enable_core", F_OK) == 0) {
  471. struct rlimit limit;
  472. limit.rlim_cur = RLIM_INFINITY;
  473. limit.rlim_max = RLIM_INFINITY;
  474. setrlimit(RLIMIT_CORE, &limit);
  475. }
  476. }
  477. /* Log the process name and args */
  478. message(L_LOG, "starting pid %d, tty '%s': '%s'",
  479. getpid(), a->terminal, a->command);
  480. /* Now run it. The new program will take over this PID,
  481. * so nothing further in init.c should be run. */
  482. init_exec(a->command);
  483. /* We're still here? Some error happened. */
  484. _exit(-1);
  485. }
  486. static struct init_action *mark_terminated(pid_t pid)
  487. {
  488. struct init_action *a;
  489. if (pid > 0) {
  490. update_utmp_DEAD_PROCESS(pid);
  491. for (a = init_action_list; a; a = a->next) {
  492. if (a->pid == pid) {
  493. a->pid = 0;
  494. return a;
  495. }
  496. }
  497. }
  498. return NULL;
  499. }
  500. static void waitfor(pid_t pid)
  501. {
  502. /* waitfor(run(x)): protect against failed fork inside run() */
  503. if (pid <= 0)
  504. return;
  505. /* Wait for any child (prevent zombies from exiting orphaned processes)
  506. * but exit the loop only when specified one has exited. */
  507. while (1) {
  508. pid_t wpid = wait(NULL);
  509. mark_terminated(wpid);
  510. /* Unsafe. SIGTSTP handler might have wait'ed it already */
  511. /*if (wpid == pid) break;*/
  512. /* More reliable: */
  513. if (kill(pid, 0))
  514. break;
  515. }
  516. }
  517. /* Run all commands of a particular type */
  518. static void run_actions(int action_type)
  519. {
  520. struct init_action *a;
  521. for (a = init_action_list; a; a = a->next) {
  522. if (!(a->action_type & action_type))
  523. continue;
  524. if (a->action_type & (SYSINIT | WAIT | ONCE | CTRLALTDEL | SHUTDOWN)) {
  525. pid_t pid = run(a);
  526. if (a->action_type & (SYSINIT | WAIT | CTRLALTDEL | SHUTDOWN))
  527. waitfor(pid);
  528. }
  529. if (a->action_type & (RESPAWN | ASKFIRST)) {
  530. /* Only run stuff with pid == 0. If pid != 0,
  531. * it is already running
  532. */
  533. if (a->pid == 0)
  534. a->pid = run(a);
  535. }
  536. }
  537. }
  538. static void new_init_action(uint8_t action_type, const char *command, const char *cons)
  539. {
  540. struct init_action *a, **nextp;
  541. /* Scenario:
  542. * old inittab:
  543. * ::shutdown:umount -a -r
  544. * ::shutdown:swapoff -a
  545. * new inittab:
  546. * ::shutdown:swapoff -a
  547. * ::shutdown:umount -a -r
  548. * On reload, we must ensure entries end up in correct order.
  549. * To achieve that, if we find a matching entry, we move it
  550. * to the end.
  551. */
  552. nextp = &init_action_list;
  553. while ((a = *nextp) != NULL) {
  554. /* Don't enter action if it's already in the list.
  555. * This prevents losing running RESPAWNs.
  556. */
  557. if (strcmp(a->command, command) == 0
  558. && strcmp(a->terminal, cons) == 0
  559. ) {
  560. /* Remove from list */
  561. *nextp = a->next;
  562. /* Find the end of the list */
  563. while (*nextp != NULL)
  564. nextp = &(*nextp)->next;
  565. a->next = NULL;
  566. goto append;
  567. }
  568. nextp = &a->next;
  569. }
  570. a = xzalloc(sizeof(*a) + strlen(command));
  571. /* Append to the end of the list */
  572. append:
  573. *nextp = a;
  574. a->action_type = action_type;
  575. strcpy(a->command, command);
  576. safe_strncpy(a->terminal, cons, sizeof(a->terminal));
  577. dbg_message(L_LOG | L_CONSOLE, "command='%s' action=%x tty='%s'\n",
  578. a->command, a->action_type, a->terminal);
  579. }
  580. /* NOTE that if CONFIG_FEATURE_USE_INITTAB is NOT defined,
  581. * then parse_inittab() simply adds in some default
  582. * actions (i.e., runs INIT_SCRIPT and then starts a pair
  583. * of "askfirst" shells). If CONFIG_FEATURE_USE_INITTAB
  584. * _is_ defined, but /etc/inittab is missing, this
  585. * results in the same set of default behaviors.
  586. */
  587. static void parse_inittab(void)
  588. {
  589. #if ENABLE_FEATURE_USE_INITTAB
  590. char *token[4];
  591. parser_t *parser = config_open2("/etc/inittab", fopen_for_read);
  592. if (parser == NULL)
  593. #endif
  594. {
  595. /* No inittab file - set up some default behavior */
  596. /* Sysinit */
  597. new_init_action(SYSINIT, INIT_SCRIPT, "");
  598. /* Askfirst shell on tty1-4 */
  599. new_init_action(ASKFIRST, bb_default_login_shell, "");
  600. //TODO: VC_1 instead of ""? "" is console -> ctty problems -> angry users
  601. new_init_action(ASKFIRST, bb_default_login_shell, VC_2);
  602. new_init_action(ASKFIRST, bb_default_login_shell, VC_3);
  603. new_init_action(ASKFIRST, bb_default_login_shell, VC_4);
  604. /* Reboot on Ctrl-Alt-Del */
  605. new_init_action(CTRLALTDEL, "reboot", "");
  606. /* Umount all filesystems on halt/reboot */
  607. new_init_action(SHUTDOWN, "umount -a -r", "");
  608. /* Swapoff on halt/reboot */
  609. new_init_action(SHUTDOWN, "swapoff -a", "");
  610. /* Restart init when a QUIT is received */
  611. new_init_action(RESTART, "init", "");
  612. return;
  613. }
  614. #if ENABLE_FEATURE_USE_INITTAB
  615. /* optional_tty:ignored_runlevel:action:command
  616. * Delims are not to be collapsed and need exactly 4 tokens
  617. */
  618. while (config_read(parser, token, 4, 0, "#:",
  619. PARSE_NORMAL & ~(PARSE_TRIM | PARSE_COLLAPSE))) {
  620. /* order must correspond to SYSINIT..RESTART constants */
  621. static const char actions[] ALIGN1 =
  622. "sysinit\0""wait\0""once\0""respawn\0""askfirst\0"
  623. "ctrlaltdel\0""shutdown\0""restart\0";
  624. int action;
  625. char *tty = token[0];
  626. if (!token[3]) /* less than 4 tokens */
  627. goto bad_entry;
  628. action = index_in_strings(actions, token[2]);
  629. if (action < 0 || !token[3][0]) /* token[3]: command */
  630. goto bad_entry;
  631. /* turn .*TTY -> /dev/TTY */
  632. if (tty[0]) {
  633. tty = concat_path_file("/dev/", skip_dev_pfx(tty));
  634. }
  635. new_init_action(1 << action, token[3], tty);
  636. if (tty[0])
  637. free(tty);
  638. continue;
  639. bad_entry:
  640. message(L_LOG | L_CONSOLE, "Bad inittab entry at line %d",
  641. parser->lineno);
  642. }
  643. config_close(parser);
  644. #endif
  645. }
  646. static void pause_and_low_level_reboot(unsigned magic) NORETURN;
  647. static void pause_and_low_level_reboot(unsigned magic)
  648. {
  649. pid_t pid;
  650. /* Allow time for last message to reach serial console, etc */
  651. sleep(1);
  652. /* We have to fork here, since the kernel calls do_exit(EXIT_SUCCESS)
  653. * in linux/kernel/sys.c, which can cause the machine to panic when
  654. * the init process exits... */
  655. pid = vfork();
  656. if (pid == 0) { /* child */
  657. reboot(magic);
  658. _exit(EXIT_SUCCESS);
  659. }
  660. while (1)
  661. sleep(1);
  662. }
  663. static void run_shutdown_and_kill_processes(void)
  664. {
  665. /* Run everything to be run at "shutdown". This is done _prior_
  666. * to killing everything, in case people wish to use scripts to
  667. * shut things down gracefully... */
  668. run_actions(SHUTDOWN);
  669. message(L_CONSOLE | L_LOG, "The system is going down NOW!");
  670. /* Send signals to every process _except_ pid 1 */
  671. kill(-1, SIGTERM);
  672. message(L_CONSOLE | L_LOG, "Sent SIG%s to all processes", "TERM");
  673. sync();
  674. sleep(1);
  675. kill(-1, SIGKILL);
  676. message(L_CONSOLE, "Sent SIG%s to all processes", "KILL");
  677. sync();
  678. /*sleep(1); - callers take care about making a pause */
  679. }
  680. /* Signal handling by init:
  681. *
  682. * For process with PID==1, on entry kernel sets all signals to SIG_DFL
  683. * and unmasks all signals. However, for process with PID==1,
  684. * default action (SIG_DFL) on any signal is to ignore it,
  685. * even for special signals SIGKILL and SIGCONT.
  686. * Also, any signal can be caught or blocked.
  687. * (but SIGSTOP is still handled specially, at least in 2.6.20)
  688. *
  689. * We install two kinds of handlers, "immediate" and "delayed".
  690. *
  691. * Immediate handlers execute at any time, even while, say, sysinit
  692. * is running.
  693. *
  694. * Delayed handlers just set a flag variable. The variable is checked
  695. * in the main loop and acted upon.
  696. *
  697. * halt/poweroff/reboot and restart have immediate handlers.
  698. * They only traverse linked list of struct action's, never modify it,
  699. * this should be safe to do even in signal handler. Also they
  700. * never return.
  701. *
  702. * SIGSTOP and SIGTSTP have immediate handlers. They just wait
  703. * for SIGCONT to happen.
  704. *
  705. * SIGHUP has a delayed handler, because modifying linked list
  706. * of struct action's from a signal handler while it is manipulated
  707. * by the program may be disastrous.
  708. *
  709. * Ctrl-Alt-Del has a delayed handler. Not a must, but allowing
  710. * it to happen even somewhere inside "sysinit" would be a bit awkward.
  711. *
  712. * There is a tiny probability that SIGHUP and Ctrl-Alt-Del will collide
  713. * and only one will be remembered and acted upon.
  714. */
  715. /* The SIGPWR/SIGUSR[12]/SIGTERM handler */
  716. static void halt_reboot_pwoff(int sig) NORETURN;
  717. static void halt_reboot_pwoff(int sig)
  718. {
  719. const char *m;
  720. unsigned rb;
  721. /* We may call run() and it unmasks signals,
  722. * including the one masked inside this signal handler.
  723. * Testcase which would start multiple reboot scripts:
  724. * while true; do reboot; done
  725. * Preventing it:
  726. */
  727. reset_sighandlers_and_unblock_sigs();
  728. run_shutdown_and_kill_processes();
  729. m = "halt";
  730. rb = RB_HALT_SYSTEM;
  731. if (sig == SIGTERM) {
  732. m = "reboot";
  733. rb = RB_AUTOBOOT;
  734. } else if (sig == SIGUSR2) {
  735. m = "poweroff";
  736. rb = RB_POWER_OFF;
  737. }
  738. message(L_CONSOLE, "Requesting system %s", m);
  739. pause_and_low_level_reboot(rb);
  740. /* not reached */
  741. }
  742. /* Handler for QUIT - exec "restart" action,
  743. * else (no such action defined) do nothing */
  744. static void exec_restart_action(void)
  745. {
  746. struct init_action *a;
  747. for (a = init_action_list; a; a = a->next) {
  748. if (!(a->action_type & RESTART))
  749. continue;
  750. /* Starting from here, we won't return.
  751. * Thus don't need to worry about preserving errno
  752. * and such.
  753. */
  754. reset_sighandlers_and_unblock_sigs();
  755. run_shutdown_and_kill_processes();
  756. #ifdef RB_ENABLE_CAD
  757. /* Allow Ctrl-Alt-Del to reboot the system.
  758. * This is how kernel sets it up for init, we follow suit.
  759. */
  760. reboot(RB_ENABLE_CAD); /* misnomer */
  761. #endif
  762. if (open_stdio_to_tty(a->terminal)) {
  763. dbg_message(L_CONSOLE, "Trying to re-exec %s", a->command);
  764. /* Theoretically should be safe.
  765. * But in practice, kernel bugs may leave
  766. * unkillable processes, and wait() may block forever.
  767. * Oh well. Hoping "new" init won't be too surprised
  768. * by having children it didn't create.
  769. */
  770. //while (wait(NULL) > 0)
  771. // continue;
  772. init_exec(a->command);
  773. }
  774. /* Open or exec failed */
  775. pause_and_low_level_reboot(RB_HALT_SYSTEM);
  776. /* not reached */
  777. }
  778. }
  779. /* The SIGSTOP/SIGTSTP handler
  780. * NB: inside it, all signals except SIGCONT are masked
  781. * via appropriate setup in sigaction().
  782. */
  783. static void stop_handler(int sig UNUSED_PARAM)
  784. {
  785. smallint saved_bb_got_signal;
  786. int saved_errno;
  787. saved_bb_got_signal = bb_got_signal;
  788. saved_errno = errno;
  789. signal(SIGCONT, record_signo);
  790. while (1) {
  791. pid_t wpid;
  792. if (bb_got_signal == SIGCONT)
  793. break;
  794. /* NB: this can accidentally wait() for a process
  795. * which we waitfor() elsewhere! waitfor() must have
  796. * code which is resilient against this.
  797. */
  798. wpid = wait_any_nohang(NULL);
  799. mark_terminated(wpid);
  800. sleep(1);
  801. }
  802. signal(SIGCONT, SIG_DFL);
  803. errno = saved_errno;
  804. bb_got_signal = saved_bb_got_signal;
  805. }
  806. #if ENABLE_FEATURE_USE_INITTAB
  807. static void reload_inittab(void)
  808. {
  809. struct init_action *a, **nextp;
  810. message(L_LOG, "reloading /etc/inittab");
  811. /* Disable old entries */
  812. for (a = init_action_list; a; a = a->next)
  813. a->action_type = 0;
  814. /* Append new entries, or modify existing entries
  815. * (incl. setting a->action_type) if cmd and device name
  816. * match new ones. End result: only entries with
  817. * a->action_type == 0 are stale.
  818. */
  819. parse_inittab();
  820. #if ENABLE_FEATURE_KILL_REMOVED
  821. /* Kill stale entries */
  822. /* Be nice and send SIGTERM first */
  823. for (a = init_action_list; a; a = a->next)
  824. if (a->action_type == 0 && a->pid != 0)
  825. kill(a->pid, SIGTERM);
  826. if (CONFIG_FEATURE_KILL_DELAY) {
  827. /* NB: parent will wait in NOMMU case */
  828. if ((BB_MMU ? fork() : vfork()) == 0) { /* child */
  829. sleep(CONFIG_FEATURE_KILL_DELAY);
  830. for (a = init_action_list; a; a = a->next)
  831. if (a->action_type == 0 && a->pid != 0)
  832. kill(a->pid, SIGKILL);
  833. _exit(EXIT_SUCCESS);
  834. }
  835. }
  836. #endif
  837. /* Remove stale entries and SYSINIT entries.
  838. * We never rerun SYSINIT entries anyway,
  839. * removing them too saves a few bytes
  840. */
  841. nextp = &init_action_list;
  842. while ((a = *nextp) != NULL) {
  843. /*
  844. * Why pid == 0 check?
  845. * Process can be removed from inittab and added *later*.
  846. * If we delete its entry but process still runs,
  847. * duplicate is spawned when the entry is re-added.
  848. */
  849. if ((a->action_type & ~SYSINIT) == 0 && a->pid == 0) {
  850. *nextp = a->next;
  851. free(a);
  852. } else {
  853. nextp = &a->next;
  854. }
  855. }
  856. /* Not needed: */
  857. /* run_actions(RESPAWN | ASKFIRST); */
  858. /* - we return to main loop, which does this automagically */
  859. }
  860. #endif
  861. static int check_delayed_sigs(void)
  862. {
  863. int sigs_seen = 0;
  864. while (1) {
  865. smallint sig = bb_got_signal;
  866. if (!sig)
  867. return sigs_seen;
  868. bb_got_signal = 0;
  869. sigs_seen = 1;
  870. #if ENABLE_FEATURE_USE_INITTAB
  871. if (sig == SIGHUP)
  872. reload_inittab();
  873. #endif
  874. if (sig == SIGINT)
  875. run_actions(CTRLALTDEL);
  876. if (sig == SIGQUIT) {
  877. exec_restart_action();
  878. /* returns only if no restart action defined */
  879. }
  880. if ((1 << sig) & (0
  881. #ifdef SIGPWR
  882. + (1 << SIGPWR)
  883. #endif
  884. + (1 << SIGUSR1)
  885. + (1 << SIGUSR2)
  886. + (1 << SIGTERM)
  887. )) {
  888. halt_reboot_pwoff(sig);
  889. }
  890. }
  891. }
  892. #if DEBUG_SEGV_HANDLER
  893. static
  894. void handle_sigsegv(int sig, siginfo_t *info, void *ucontext)
  895. {
  896. long ip;
  897. ucontext_t *uc;
  898. uc = ucontext;
  899. ip = uc->uc_mcontext.gregs[REG_EIP];
  900. fdprintf(2, "signal:%d address:0x%lx ip:0x%lx\n",
  901. sig,
  902. /* this is void*, but using %p would print "(null)"
  903. * even for ptrs which are not exactly 0, but, say, 0x123:
  904. */
  905. (long)info->si_addr,
  906. ip);
  907. {
  908. /* glibc extension */
  909. void *array[50];
  910. int size;
  911. size = backtrace(array, 50);
  912. backtrace_symbols_fd(array, size, 2);
  913. }
  914. for (;;) sleep(9999);
  915. }
  916. #endif
  917. static void sleep_much(void)
  918. {
  919. sleep(30 * 24*60*60);
  920. }
  921. int init_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  922. int init_main(int argc UNUSED_PARAM, char **argv)
  923. {
  924. if (argv[1] && strcmp(argv[1], "-q") == 0) {
  925. return kill(1, SIGHUP);
  926. }
  927. #if DEBUG_SEGV_HANDLER
  928. {
  929. struct sigaction sa;
  930. memset(&sa, 0, sizeof(sa));
  931. sa.sa_sigaction = handle_sigsegv;
  932. sa.sa_flags = SA_SIGINFO;
  933. sigaction(SIGSEGV, &sa, NULL);
  934. sigaction(SIGILL, &sa, NULL);
  935. sigaction(SIGFPE, &sa, NULL);
  936. sigaction(SIGBUS, &sa, NULL);
  937. }
  938. #endif
  939. if (!DEBUG_INIT) {
  940. /* Expect to be invoked as init with PID=1 or be invoked as linuxrc */
  941. if (getpid() != 1
  942. && (!ENABLE_FEATURE_INITRD || applet_name[0] != 'l') /* not linuxrc? */
  943. ) {
  944. bb_error_msg_and_die("must be run as PID 1");
  945. }
  946. #ifdef RB_DISABLE_CAD
  947. /* Turn off rebooting via CTL-ALT-DEL - we get a
  948. * SIGINT on CAD so we can shut things down gracefully... */
  949. reboot(RB_DISABLE_CAD); /* misnomer */
  950. #endif
  951. }
  952. /* If, say, xmalloc would ever die, we don't want to oops kernel
  953. * by exiting.
  954. * NB: we set die_func *after* PID 1 check and bb_show_usage.
  955. * Otherwise, for example, "init u" ("please rexec yourself"
  956. * command for sysvinit) will show help text (which isn't too bad),
  957. * *and sleep forever* (which is bad!)
  958. */
  959. die_func = sleep_much;
  960. /* Figure out where the default console should be */
  961. console_init();
  962. set_sane_term();
  963. xchdir("/");
  964. setsid();
  965. /* Make sure environs is set to something sane */
  966. putenv((char *) "HOME=/");
  967. putenv((char *) bb_PATH_root_path);
  968. putenv((char *) "SHELL=/bin/sh");
  969. putenv((char *) "USER=root"); /* needed? why? */
  970. if (argv[1])
  971. xsetenv("RUNLEVEL", argv[1]);
  972. #if !ENABLE_FEATURE_EXTRA_QUIET
  973. /* Hello world */
  974. message(L_CONSOLE | L_LOG, "init started: %s", bb_banner);
  975. #endif
  976. #if 0
  977. /* It's 2013, does anyone really still depend on this? */
  978. /* If you do, consider adding swapon to sysinit actions then! */
  979. /* struct sysinfo is linux-specific */
  980. # ifdef __linux__
  981. /* Make sure there is enough memory to do something useful. */
  982. /*if (ENABLE_SWAPONOFF) - WRONG: we may have non-bbox swapon*/ {
  983. struct sysinfo info;
  984. if (sysinfo(&info) == 0
  985. && (info.mem_unit ? info.mem_unit : 1) * (long long)info.totalram < 1024*1024
  986. ) {
  987. message(L_CONSOLE, "Low memory, forcing swapon");
  988. /* swapon -a requires /proc typically */
  989. new_init_action(SYSINIT, "mount -t proc proc /proc", "");
  990. /* Try to turn on swap */
  991. new_init_action(SYSINIT, "swapon -a", "");
  992. run_actions(SYSINIT); /* wait and removing */
  993. }
  994. }
  995. # endif
  996. #endif
  997. /* Check if we are supposed to be in single user mode */
  998. if (argv[1]
  999. && (strcmp(argv[1], "single") == 0 || strcmp(argv[1], "-s") == 0 || LONE_CHAR(argv[1], '1'))
  1000. ) {
  1001. /* ??? shouldn't we set RUNLEVEL="b" here? */
  1002. /* Start a shell on console */
  1003. new_init_action(RESPAWN, bb_default_login_shell, "");
  1004. } else {
  1005. /* Not in single user mode - see what inittab says */
  1006. /* NOTE that if CONFIG_FEATURE_USE_INITTAB is NOT defined,
  1007. * then parse_inittab() simply adds in some default
  1008. * actions (i.e., INIT_SCRIPT and a pair
  1009. * of "askfirst" shells) */
  1010. parse_inittab();
  1011. }
  1012. #if ENABLE_SELINUX
  1013. if (getenv("SELINUX_INIT") == NULL) {
  1014. int enforce = 0;
  1015. putenv((char*)"SELINUX_INIT=YES");
  1016. if (selinux_init_load_policy(&enforce) == 0) {
  1017. BB_EXECVP(argv[0], argv);
  1018. } else if (enforce > 0) {
  1019. /* SELinux in enforcing mode but load_policy failed */
  1020. message(L_CONSOLE, "can't load SELinux Policy. "
  1021. "Machine is in enforcing mode. Halting now.");
  1022. return EXIT_FAILURE;
  1023. }
  1024. }
  1025. #endif
  1026. /* Make the command line just say "init" - thats all, nothing else */
  1027. strncpy(argv[0], "init", strlen(argv[0]));
  1028. /* Wipe argv[1]-argv[N] so they don't clutter the ps listing */
  1029. while (*++argv)
  1030. nuke_str(*argv);
  1031. /* Set up signal handlers */
  1032. if (!DEBUG_INIT) {
  1033. struct sigaction sa;
  1034. /* Stop handler must allow only SIGCONT inside itself */
  1035. memset(&sa, 0, sizeof(sa));
  1036. sigfillset(&sa.sa_mask);
  1037. sigdelset(&sa.sa_mask, SIGCONT);
  1038. sa.sa_handler = stop_handler;
  1039. /* NB: sa_flags doesn't have SA_RESTART.
  1040. * It must be able to interrupt wait().
  1041. */
  1042. sigaction_set(SIGTSTP, &sa); /* pause */
  1043. /* Does not work as intended, at least in 2.6.20.
  1044. * SIGSTOP is simply ignored by init:
  1045. */
  1046. sigaction_set(SIGSTOP, &sa); /* pause */
  1047. /* These signals must interrupt wait(),
  1048. * setting handler without SA_RESTART flag.
  1049. */
  1050. bb_signals_recursive_norestart(0
  1051. + (1 << SIGINT) /* Ctrl-Alt-Del */
  1052. + (1 << SIGQUIT) /* re-exec another init */
  1053. #ifdef SIGPWR
  1054. + (1 << SIGPWR) /* halt */
  1055. #endif
  1056. + (1 << SIGUSR1) /* halt */
  1057. + (1 << SIGTERM) /* reboot */
  1058. + (1 << SIGUSR2) /* poweroff */
  1059. #if ENABLE_FEATURE_USE_INITTAB
  1060. + (1 << SIGHUP) /* reread /etc/inittab */
  1061. #endif
  1062. , record_signo);
  1063. }
  1064. /* Now run everything that needs to be run */
  1065. /* First run the sysinit command */
  1066. run_actions(SYSINIT);
  1067. check_delayed_sigs();
  1068. /* Next run anything that wants to block */
  1069. run_actions(WAIT);
  1070. check_delayed_sigs();
  1071. /* Next run anything to be run only once */
  1072. run_actions(ONCE);
  1073. /* Now run the looping stuff for the rest of forever.
  1074. */
  1075. while (1) {
  1076. int maybe_WNOHANG;
  1077. maybe_WNOHANG = check_delayed_sigs();
  1078. /* (Re)run the respawn/askfirst stuff */
  1079. run_actions(RESPAWN | ASKFIRST);
  1080. maybe_WNOHANG |= check_delayed_sigs();
  1081. /* Don't consume all CPU time - sleep a bit */
  1082. sleep(1);
  1083. maybe_WNOHANG |= check_delayed_sigs();
  1084. /* Wait for any child process(es) to exit.
  1085. *
  1086. * If check_delayed_sigs above reported that a signal
  1087. * was caught, wait will be nonblocking. This ensures
  1088. * that if SIGHUP has reloaded inittab, respawn and askfirst
  1089. * actions will not be delayed until next child death.
  1090. */
  1091. if (maybe_WNOHANG)
  1092. maybe_WNOHANG = WNOHANG;
  1093. while (1) {
  1094. pid_t wpid;
  1095. struct init_action *a;
  1096. /* If signals happen _in_ the wait, they interrupt it,
  1097. * bb_signals_recursive_norestart set them up that way
  1098. */
  1099. wpid = waitpid(-1, NULL, maybe_WNOHANG);
  1100. if (wpid <= 0)
  1101. break;
  1102. a = mark_terminated(wpid);
  1103. if (a) {
  1104. message(L_LOG, "process '%s' (pid %d) exited. "
  1105. "Scheduling for restart.",
  1106. a->command, wpid);
  1107. }
  1108. /* See if anyone else is waiting to be reaped */
  1109. maybe_WNOHANG = WNOHANG;
  1110. }
  1111. } /* while (1) */
  1112. }
  1113. //usage:#define linuxrc_trivial_usage NOUSAGE_STR
  1114. //usage:#define linuxrc_full_usage ""
  1115. //usage:#define init_trivial_usage
  1116. //usage: ""
  1117. //usage:#define init_full_usage "\n\n"
  1118. //usage: "Init is the first process started during boot. It never exits."
  1119. //usage: IF_FEATURE_USE_INITTAB(
  1120. //usage: "\n""It (re)spawns children according to /etc/inittab."
  1121. //usage: )
  1122. //usage: IF_NOT_FEATURE_USE_INITTAB(
  1123. //usage: "\n""This version of init doesn't use /etc/inittab,"
  1124. //usage: "\n""has fixed set of processed to run."
  1125. //usage: )
  1126. //usage:
  1127. //usage:#define init_notes_usage
  1128. //usage: "This version of init is designed to be run only by the kernel.\n"
  1129. //usage: "\n"
  1130. //usage: "BusyBox init doesn't support multiple runlevels. The runlevels field of\n"
  1131. //usage: "the /etc/inittab file is completely ignored by BusyBox init. If you want\n"
  1132. //usage: "runlevels, use sysvinit.\n"
  1133. //usage: "\n"
  1134. //usage: "BusyBox init works just fine without an inittab. If no inittab is found,\n"
  1135. //usage: "it has the following default behavior:\n"
  1136. //usage: "\n"
  1137. //usage: " ::sysinit:/etc/init.d/rcS\n"
  1138. //usage: " ::askfirst:/bin/sh\n"
  1139. //usage: " ::ctrlaltdel:/sbin/reboot\n"
  1140. //usage: " ::shutdown:/sbin/swapoff -a\n"
  1141. //usage: " ::shutdown:/bin/umount -a -r\n"
  1142. //usage: " ::restart:/sbin/init\n"
  1143. //usage: " tty2::askfirst:/bin/sh\n"
  1144. //usage: " tty3::askfirst:/bin/sh\n"
  1145. //usage: " tty4::askfirst:/bin/sh\n"
  1146. //usage: "\n"
  1147. //usage: "If you choose to use an /etc/inittab file, the inittab entry format is as follows:\n"
  1148. //usage: "\n"
  1149. //usage: " <id>:<runlevels>:<action>:<process>\n"
  1150. //usage: "\n"
  1151. //usage: " <id>:\n"
  1152. //usage: "\n"
  1153. //usage: " WARNING: This field has a non-traditional meaning for BusyBox init!\n"
  1154. //usage: " The id field is used by BusyBox init to specify the controlling tty for\n"
  1155. //usage: " the specified process to run on. The contents of this field are\n"
  1156. //usage: " appended to \"/dev/\" and used as-is. There is no need for this field to\n"
  1157. //usage: " be unique, although if it isn't you may have strange results. If this\n"
  1158. //usage: " field is left blank, then the init's stdin/out will be used.\n"
  1159. //usage: "\n"
  1160. //usage: " <runlevels>:\n"
  1161. //usage: "\n"
  1162. //usage: " The runlevels field is completely ignored.\n"
  1163. //usage: "\n"
  1164. //usage: " <action>:\n"
  1165. //usage: "\n"
  1166. //usage: " Valid actions include: sysinit, respawn, askfirst, wait,\n"
  1167. //usage: " once, restart, ctrlaltdel, and shutdown.\n"
  1168. //usage: "\n"
  1169. //usage: " The available actions can be classified into two groups: actions\n"
  1170. //usage: " that are run only once, and actions that are re-run when the specified\n"
  1171. //usage: " process exits.\n"
  1172. //usage: "\n"
  1173. //usage: " Run only-once actions:\n"
  1174. //usage: "\n"
  1175. //usage: " 'sysinit' is the first item run on boot. init waits until all\n"
  1176. //usage: " sysinit actions are completed before continuing. Following the\n"
  1177. //usage: " completion of all sysinit actions, all 'wait' actions are run.\n"
  1178. //usage: " 'wait' actions, like 'sysinit' actions, cause init to wait until\n"
  1179. //usage: " the specified task completes. 'once' actions are asynchronous,\n"
  1180. //usage: " therefore, init does not wait for them to complete. 'restart' is\n"
  1181. //usage: " the action taken to restart the init process. By default this should\n"
  1182. //usage: " simply run /sbin/init, but can be a script which runs pivot_root or it\n"
  1183. //usage: " can do all sorts of other interesting things. The 'ctrlaltdel' init\n"
  1184. //usage: " actions are run when the system detects that someone on the system\n"
  1185. //usage: " console has pressed the CTRL-ALT-DEL key combination. Typically one\n"
  1186. //usage: " wants to run 'reboot' at this point to cause the system to reboot.\n"
  1187. //usage: " Finally the 'shutdown' action specifies the actions to taken when\n"
  1188. //usage: " init is told to reboot. Unmounting filesystems and disabling swap\n"
  1189. //usage: " is a very good here.\n"
  1190. //usage: "\n"
  1191. //usage: " Run repeatedly actions:\n"
  1192. //usage: "\n"
  1193. //usage: " 'respawn' actions are run after the 'once' actions. When a process\n"
  1194. //usage: " started with a 'respawn' action exits, init automatically restarts\n"
  1195. //usage: " it. Unlike sysvinit, BusyBox init does not stop processes from\n"
  1196. //usage: " respawning out of control. The 'askfirst' actions acts just like\n"
  1197. //usage: " respawn, except that before running the specified process it\n"
  1198. //usage: " displays the line \"Please press Enter to activate this console.\"\n"
  1199. //usage: " and then waits for the user to press enter before starting the\n"
  1200. //usage: " specified process.\n"
  1201. //usage: "\n"
  1202. //usage: " Unrecognized actions (like initdefault) will cause init to emit an\n"
  1203. //usage: " error message, and then go along with its business. All actions are\n"
  1204. //usage: " run in the order they appear in /etc/inittab.\n"
  1205. //usage: "\n"
  1206. //usage: " <process>:\n"
  1207. //usage: "\n"
  1208. //usage: " Specifies the process to be executed and its command line.\n"
  1209. //usage: "\n"
  1210. //usage: "Example /etc/inittab file:\n"
  1211. //usage: "\n"
  1212. //usage: " # This is run first except when booting in single-user mode\n"
  1213. //usage: " #\n"
  1214. //usage: " ::sysinit:/etc/init.d/rcS\n"
  1215. //usage: " \n"
  1216. //usage: " # /bin/sh invocations on selected ttys\n"
  1217. //usage: " #\n"
  1218. //usage: " # Start an \"askfirst\" shell on the console (whatever that may be)\n"
  1219. //usage: " ::askfirst:-/bin/sh\n"
  1220. //usage: " # Start an \"askfirst\" shell on /dev/tty2-4\n"
  1221. //usage: " tty2::askfirst:-/bin/sh\n"
  1222. //usage: " tty3::askfirst:-/bin/sh\n"
  1223. //usage: " tty4::askfirst:-/bin/sh\n"
  1224. //usage: " \n"
  1225. //usage: " # /sbin/getty invocations for selected ttys\n"
  1226. //usage: " #\n"
  1227. //usage: " tty4::respawn:/sbin/getty 38400 tty4\n"
  1228. //usage: " tty5::respawn:/sbin/getty 38400 tty5\n"
  1229. //usage: " \n"
  1230. //usage: " \n"
  1231. //usage: " # Example of how to put a getty on a serial line (for a terminal)\n"
  1232. //usage: " #\n"
  1233. //usage: " #::respawn:/sbin/getty -L ttyS0 9600 vt100\n"
  1234. //usage: " #::respawn:/sbin/getty -L ttyS1 9600 vt100\n"
  1235. //usage: " #\n"
  1236. //usage: " # Example how to put a getty on a modem line\n"
  1237. //usage: " #::respawn:/sbin/getty 57600 ttyS2\n"
  1238. //usage: " \n"
  1239. //usage: " # Stuff to do when restarting the init process\n"
  1240. //usage: " ::restart:/sbin/init\n"
  1241. //usage: " \n"
  1242. //usage: " # Stuff to do before rebooting\n"
  1243. //usage: " ::ctrlaltdel:/sbin/reboot\n"
  1244. //usage: " ::shutdown:/bin/umount -a -r\n"
  1245. //usage: " ::shutdown:/sbin/swapoff -a\n"