init.c 40 KB

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