init.c 42 KB

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