init.c 41 KB

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