init.c 41 KB

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