init.c 41 KB

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