3
0

init.c 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  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 tarball for details.
  10. */
  11. #include "libbb.h"
  12. #include <syslog.h>
  13. #include <paths.h>
  14. #include <sys/reboot.h>
  15. #include <sys/resource.h>
  16. #include <linux/vt.h>
  17. /* Was a CONFIG_xxx option. A lot of people were building
  18. * not fully functional init by switching it on! */
  19. #define DEBUG_INIT 0
  20. #define COMMAND_SIZE 256
  21. #define CONSOLE_NAME_SIZE 32
  22. /* Default sysinit script. */
  23. #ifndef INIT_SCRIPT
  24. #define INIT_SCRIPT "/etc/init.d/rcS"
  25. #endif
  26. /* Each type of actions can appear many times. They will be
  27. * handled in order. RESTART is an exception, only 1st is used.
  28. */
  29. /* Start these actions first and wait for completion */
  30. #define SYSINIT 0x01
  31. /* Start these after SYSINIT and wait for completion */
  32. #define WAIT 0x02
  33. /* Start these after WAIT and *dont* wait for completion */
  34. #define ONCE 0x04
  35. /*
  36. * NB: while SYSINIT/WAIT/ONCE are being processed,
  37. * SIGHUP ("reread /etc/inittab") will be ignored.
  38. * Rationale: it would be ambiguous whether SYSINIT/WAIT/ONCE
  39. * need to be rerun or not.
  40. */
  41. /* Start these after ONCE are started, restart on exit */
  42. #define RESPAWN 0x08
  43. /* Like RESPAWN, but wait for <Enter> to be pressed on tty */
  44. #define ASKFIRST 0x10
  45. /*
  46. * Start these on SIGINT, and wait for completion.
  47. * Then go back to respawning RESPAWN and ASKFIRST actions.
  48. * NB: kernel sends SIGINT to us if Ctrl-Alt-Del was pressed.
  49. */
  50. #define CTRLALTDEL 0x20
  51. /*
  52. * Start these before killing all processes in preparation for
  53. * running RESTART actions or doing low-level halt/reboot/poweroff
  54. * (initiated by SIGUSR1/SIGTERM/SIGUSR2).
  55. * Wait for completion before proceeding.
  56. */
  57. #define SHUTDOWN 0x40
  58. /*
  59. * exec() on SIGQUIT. SHUTDOWN actions are started and waited for,
  60. * then all processes are killed, then init exec's 1st RESTART action,
  61. * replacing itself by it. If no RESTART action specified,
  62. * SIGQUIT has no effect.
  63. */
  64. #define RESTART 0x80
  65. /* A linked list of init_actions, to be read from inittab */
  66. struct init_action {
  67. struct init_action *next;
  68. pid_t pid;
  69. uint8_t action_type;
  70. char terminal[CONSOLE_NAME_SIZE];
  71. char command[COMMAND_SIZE];
  72. };
  73. static struct init_action *init_action_list = NULL;
  74. static const char *log_console = VC_5;
  75. enum {
  76. L_LOG = 0x1,
  77. L_CONSOLE = 0x2,
  78. MAYBE_CONSOLE = L_CONSOLE * !ENABLE_FEATURE_EXTRA_QUIET,
  79. #ifndef RB_HALT_SYSTEM
  80. RB_HALT_SYSTEM = 0xcdef0123, /* FIXME: this overflows enum */
  81. RB_ENABLE_CAD = 0x89abcdef,
  82. RB_DISABLE_CAD = 0,
  83. RB_POWER_OFF = 0x4321fedc,
  84. RB_AUTOBOOT = 0x01234567,
  85. #endif
  86. };
  87. /* Print a message to the specified device.
  88. * "where" may be bitwise-or'd from L_LOG | L_CONSOLE
  89. * NB: careful, we can be called after vfork!
  90. */
  91. #define dbg_message(...) do { if (DEBUG_INIT) message(__VA_ARGS__); } while (0)
  92. static void message(int where, const char *fmt, ...)
  93. __attribute__ ((format(printf, 2, 3)));
  94. static void message(int where, const char *fmt, ...)
  95. {
  96. va_list arguments;
  97. unsigned l;
  98. char msg[128];
  99. msg[0] = '\r';
  100. va_start(arguments, fmt);
  101. l = 1 + vsnprintf(msg + 1, sizeof(msg) - 2, fmt, arguments);
  102. if (l > sizeof(msg) - 1)
  103. l = sizeof(msg) - 1;
  104. va_end(arguments);
  105. #if ENABLE_FEATURE_INIT_SYSLOG
  106. msg[l] = '\0';
  107. if (where & L_LOG) {
  108. /* Log the message to syslogd */
  109. openlog("init", 0, LOG_DAEMON);
  110. /* don't print "\r" */
  111. syslog(LOG_INFO, "%s", msg + 1);
  112. closelog();
  113. }
  114. msg[l++] = '\n';
  115. msg[l] = '\0';
  116. #else
  117. {
  118. static int log_fd = -1;
  119. msg[l++] = '\n';
  120. msg[l] = '\0';
  121. /* Take full control of the log tty, and never close it.
  122. * It's mine, all mine! Muhahahaha! */
  123. if (log_fd < 0) {
  124. if (!log_console) {
  125. log_fd = STDERR_FILENO;
  126. } else {
  127. log_fd = device_open(log_console, O_WRONLY | O_NONBLOCK | O_NOCTTY);
  128. if (log_fd < 0) {
  129. bb_error_msg("can't log to %s", log_console);
  130. where = L_CONSOLE;
  131. } else {
  132. close_on_exec_on(log_fd);
  133. }
  134. }
  135. }
  136. if (where & L_LOG) {
  137. full_write(log_fd, msg, l);
  138. if (log_fd == STDERR_FILENO)
  139. return; /* don't print dup messages */
  140. }
  141. }
  142. #endif
  143. if (where & L_CONSOLE) {
  144. /* Send console messages to console so people will see them. */
  145. full_write(STDERR_FILENO, msg, l);
  146. }
  147. }
  148. static void console_init(void)
  149. {
  150. int vtno;
  151. char *s;
  152. s = getenv("CONSOLE");
  153. if (!s)
  154. s = getenv("console");
  155. if (s) {
  156. int fd = open(s, O_RDWR | O_NONBLOCK | O_NOCTTY);
  157. if (fd >= 0) {
  158. dup2(fd, STDIN_FILENO);
  159. dup2(fd, STDOUT_FILENO);
  160. xmove_fd(fd, STDERR_FILENO);
  161. }
  162. dbg_message(L_LOG, "console='%s'", s);
  163. } else {
  164. /* Make sure fd 0,1,2 are not closed
  165. * (so that they won't be used by future opens) */
  166. bb_sanitize_stdio();
  167. // Users report problems
  168. // /* Make sure init can't be blocked by writing to stderr */
  169. // fcntl(STDERR_FILENO, F_SETFL, fcntl(STDERR_FILENO, F_GETFL) | O_NONBLOCK);
  170. }
  171. s = getenv("TERM");
  172. if (ioctl(STDIN_FILENO, VT_OPENQRY, &vtno) != 0) {
  173. /* Not a linux terminal, probably serial console.
  174. * Force the TERM setting to vt102
  175. * if TERM is set to linux (the default) */
  176. if (!s || strcmp(s, "linux") == 0)
  177. putenv((char*)"TERM=vt102");
  178. if (!ENABLE_FEATURE_INIT_SYSLOG)
  179. log_console = NULL;
  180. } else if (!s)
  181. putenv((char*)"TERM=linux");
  182. }
  183. /* Set terminal settings to reasonable defaults.
  184. * NB: careful, we can be called after vfork! */
  185. static void set_sane_term(void)
  186. {
  187. struct termios tty;
  188. tcgetattr(STDIN_FILENO, &tty);
  189. /* set control chars */
  190. tty.c_cc[VINTR] = 3; /* C-c */
  191. tty.c_cc[VQUIT] = 28; /* C-\ */
  192. tty.c_cc[VERASE] = 127; /* C-? */
  193. tty.c_cc[VKILL] = 21; /* C-u */
  194. tty.c_cc[VEOF] = 4; /* C-d */
  195. tty.c_cc[VSTART] = 17; /* C-q */
  196. tty.c_cc[VSTOP] = 19; /* C-s */
  197. tty.c_cc[VSUSP] = 26; /* C-z */
  198. /* use line discipline 0 */
  199. tty.c_line = 0;
  200. /* Make it be sane */
  201. tty.c_cflag &= CBAUD | CBAUDEX | CSIZE | CSTOPB | PARENB | PARODD;
  202. tty.c_cflag |= CREAD | HUPCL | CLOCAL;
  203. /* input modes */
  204. tty.c_iflag = ICRNL | IXON | IXOFF;
  205. /* output modes */
  206. tty.c_oflag = OPOST | ONLCR;
  207. /* local modes */
  208. tty.c_lflag =
  209. ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE | IEXTEN;
  210. tcsetattr_stdin_TCSANOW(&tty);
  211. }
  212. /* Open the new terminal device.
  213. * NB: careful, we can be called after vfork! */
  214. static int open_stdio_to_tty(const char* tty_name)
  215. {
  216. /* empty tty_name means "use init's tty", else... */
  217. if (tty_name[0]) {
  218. int fd;
  219. close(STDIN_FILENO);
  220. /* fd can be only < 0 or 0: */
  221. fd = device_open(tty_name, O_RDWR);
  222. if (fd) {
  223. message(L_LOG | L_CONSOLE, "can't open %s: %s",
  224. tty_name, strerror(errno));
  225. return 0; /* failure */
  226. }
  227. dup2(STDIN_FILENO, STDOUT_FILENO);
  228. dup2(STDIN_FILENO, STDERR_FILENO);
  229. }
  230. set_sane_term();
  231. return 1; /* success */
  232. }
  233. /* Wrapper around exec:
  234. * Takes string (max COMMAND_SIZE chars).
  235. * If chars like '>' detected, execs '[-]/bin/sh -c "exec ......."'.
  236. * Otherwise splits words on whitespace, deals with leading dash,
  237. * and uses plain exec().
  238. * NB: careful, we can be called after vfork!
  239. */
  240. static void init_exec(const char *command)
  241. {
  242. char *cmd[COMMAND_SIZE / 2];
  243. char buf[COMMAND_SIZE + 6]; /* COMMAND_SIZE+strlen("exec ")+1 */
  244. int dash = (command[0] == '-' /* maybe? && command[1] == '/' */);
  245. /* See if any special /bin/sh requiring characters are present */
  246. if (strpbrk(command, "~`!$^&*()=|\\{}[];\"'<>?") != NULL) {
  247. strcpy(buf, "exec ");
  248. strcpy(buf + 5, command + dash); /* excluding "-" */
  249. /* NB: LIBBB_DEFAULT_LOGIN_SHELL define has leading dash */
  250. cmd[0] = (char*)(LIBBB_DEFAULT_LOGIN_SHELL + !dash);
  251. cmd[1] = (char*)"-c";
  252. cmd[2] = buf;
  253. cmd[3] = NULL;
  254. } else {
  255. /* Convert command (char*) into cmd (char**, one word per string) */
  256. char *word, *next;
  257. int i = 0;
  258. next = strcpy(buf, command); /* including "-" */
  259. while ((word = strsep(&next, " \t")) != NULL) {
  260. if (*word != '\0') { /* not two spaces/tabs together? */
  261. cmd[i] = word;
  262. i++;
  263. }
  264. }
  265. cmd[i] = NULL;
  266. }
  267. /* If we saw leading "-", it is interactive shell.
  268. * Try harder to give it a controlling tty.
  269. * And skip "-" in actual exec call. */
  270. if (dash) {
  271. /* _Attempt_ to make stdin a controlling tty. */
  272. if (ENABLE_FEATURE_INIT_SCTTY)
  273. ioctl(STDIN_FILENO, TIOCSCTTY, 0 /*only try, don't steal*/);
  274. }
  275. BB_EXECVP(cmd[0] + dash, cmd);
  276. message(L_LOG | L_CONSOLE, "cannot run '%s': %s", cmd[0], strerror(errno));
  277. /* returns if execvp fails */
  278. }
  279. /* Used only by run_actions */
  280. static pid_t run(const struct init_action *a)
  281. {
  282. pid_t pid;
  283. /* Careful: don't be affected by a signal in vforked child */
  284. sigprocmask_allsigs(SIG_BLOCK);
  285. if (BB_MMU && (a->action_type & ASKFIRST))
  286. pid = fork();
  287. else
  288. pid = vfork();
  289. if (pid < 0)
  290. message(L_LOG | L_CONSOLE, "can't fork");
  291. if (pid) {
  292. sigprocmask_allsigs(SIG_UNBLOCK);
  293. return pid; /* Parent or error */
  294. }
  295. /* Child */
  296. /* Reset signal handlers that were set by the parent process */
  297. bb_signals(0
  298. + (1 << SIGUSR1)
  299. + (1 << SIGUSR2)
  300. + (1 << SIGTERM)
  301. + (1 << SIGQUIT)
  302. + (1 << SIGINT)
  303. + (1 << SIGHUP)
  304. + (1 << SIGTSTP)
  305. , SIG_DFL);
  306. sigprocmask_allsigs(SIG_UNBLOCK);
  307. /* Create a new session and make ourself the process group leader */
  308. setsid();
  309. /* Open the new terminal device */
  310. if (!open_stdio_to_tty(a->terminal))
  311. _exit(EXIT_FAILURE);
  312. /* NB: on NOMMU we can't wait for input in child, so
  313. * "askfirst" will work the same as "respawn". */
  314. if (BB_MMU && (a->action_type & ASKFIRST)) {
  315. static const char press_enter[] ALIGN1 =
  316. #ifdef CUSTOMIZED_BANNER
  317. #include CUSTOMIZED_BANNER
  318. #endif
  319. "\nPlease press Enter to activate this console. ";
  320. char c;
  321. /*
  322. * Save memory by not exec-ing anything large (like a shell)
  323. * before the user wants it. This is critical if swap is not
  324. * enabled and the system has low memory. Generally this will
  325. * be run on the second virtual console, and the first will
  326. * be allowed to start a shell or whatever an init script
  327. * specifies.
  328. */
  329. dbg_message(L_LOG, "waiting for enter to start '%s'"
  330. "(pid %d, tty '%s')\n",
  331. a->command, getpid(), a->terminal);
  332. full_write(STDOUT_FILENO, press_enter, sizeof(press_enter) - 1);
  333. while (safe_read(STDIN_FILENO, &c, 1) == 1 && c != '\n')
  334. continue;
  335. }
  336. /*
  337. * When a file named /.init_enable_core exists, setrlimit is called
  338. * before processes are spawned to set core file size as unlimited.
  339. * This is for debugging only. Don't use this is production, unless
  340. * you want core dumps lying about....
  341. */
  342. if (ENABLE_FEATURE_INIT_COREDUMPS) {
  343. if (access("/.init_enable_core", F_OK) == 0) {
  344. struct rlimit limit;
  345. limit.rlim_cur = RLIM_INFINITY;
  346. limit.rlim_max = RLIM_INFINITY;
  347. setrlimit(RLIMIT_CORE, &limit);
  348. }
  349. }
  350. /* Log the process name and args */
  351. message(L_LOG, "starting pid %d, tty '%s': '%s'",
  352. getpid(), a->terminal, a->command);
  353. /* Now run it. The new program will take over this PID,
  354. * so nothing further in init.c should be run. */
  355. init_exec(a->command);
  356. /* We're still here? Some error happened. */
  357. _exit(-1);
  358. }
  359. static struct init_action *mark_terminated(pid_t pid)
  360. {
  361. struct init_action *a;
  362. if (pid > 0) {
  363. for (a = init_action_list; a; a = a->next) {
  364. if (a->pid == pid) {
  365. a->pid = 0;
  366. return a;
  367. }
  368. }
  369. }
  370. return NULL;
  371. }
  372. static void waitfor(pid_t pid)
  373. {
  374. /* waitfor(run(x)): protect against failed fork inside run() */
  375. if (pid <= 0)
  376. return;
  377. /* Wait for any child (prevent zombies from exiting orphaned processes)
  378. * but exit the loop only when specified one has exited. */
  379. while (1) {
  380. pid_t wpid = wait(NULL);
  381. mark_terminated(wpid);
  382. /* Unsafe. SIGTSTP handler might have wait'ed it already */
  383. /*if (wpid == pid) break;*/
  384. /* More reliable: */
  385. if (kill(pid, 0))
  386. break;
  387. }
  388. }
  389. /* Run all commands of a particular type */
  390. static void run_actions(int action_type)
  391. {
  392. struct init_action *a;
  393. for (a = init_action_list; a; a = a->next) {
  394. if (!(a->action_type & action_type))
  395. continue;
  396. if (a->action_type & (SYSINIT | WAIT | ONCE | CTRLALTDEL | SHUTDOWN)) {
  397. pid_t pid = run(a);
  398. if (a->action_type & (SYSINIT | WAIT | CTRLALTDEL | SHUTDOWN))
  399. waitfor(pid);
  400. }
  401. if (a->action_type & (RESPAWN | ASKFIRST)) {
  402. /* Only run stuff with pid == 0. If pid != 0,
  403. * it is already running
  404. */
  405. if (a->pid == 0)
  406. a->pid = run(a);
  407. }
  408. }
  409. }
  410. static void new_init_action(uint8_t action_type, const char *command, const char *cons)
  411. {
  412. struct init_action *a, **nextp;
  413. /* Scenario:
  414. * old inittab:
  415. * ::shutdown:umount -a -r
  416. * ::shutdown:swapoff -a
  417. * new inittab:
  418. * ::shutdown:swapoff -a
  419. * ::shutdown:umount -a -r
  420. * On reload, we must ensure entries end up in correct order.
  421. * To achieve that, if we find a matching entry, we move it
  422. * to the end.
  423. */
  424. nextp = &init_action_list;
  425. while ((a = *nextp) != NULL) {
  426. /* Don't enter action if it's already in the list,
  427. * This prevents losing running RESPAWNs.
  428. */
  429. if ((strcmp(a->command, command) == 0)
  430. && (strcmp(a->terminal, cons) == 0)
  431. ) {
  432. /* Remove from list */
  433. *nextp = a->next;
  434. /* Find the end of the list */
  435. while (*nextp != NULL)
  436. nextp = &(*nextp)->next;
  437. a->next = NULL;
  438. break;
  439. }
  440. nextp = &a->next;
  441. }
  442. if (!a)
  443. a = xzalloc(sizeof(*a));
  444. /* Append to the end of the list */
  445. *nextp = a;
  446. a->action_type = action_type;
  447. safe_strncpy(a->command, command, sizeof(a->command));
  448. safe_strncpy(a->terminal, cons, sizeof(a->terminal));
  449. dbg_message(L_LOG | L_CONSOLE, "command='%s' action=%d tty='%s'\n",
  450. a->command, a->action_type, a->terminal);
  451. }
  452. /* NOTE that if CONFIG_FEATURE_USE_INITTAB is NOT defined,
  453. * then parse_inittab() simply adds in some default
  454. * actions(i.e., runs INIT_SCRIPT and then starts a pair
  455. * of "askfirst" shells). If CONFIG_FEATURE_USE_INITTAB
  456. * _is_ defined, but /etc/inittab is missing, this
  457. * results in the same set of default behaviors.
  458. */
  459. static void parse_inittab(void)
  460. {
  461. #if ENABLE_FEATURE_USE_INITTAB
  462. char *token[4];
  463. parser_t *parser = config_open2("/etc/inittab", fopen_for_read);
  464. if (parser == NULL)
  465. #endif
  466. {
  467. /* No inittab file - set up some default behavior */
  468. /* Reboot on Ctrl-Alt-Del */
  469. new_init_action(CTRLALTDEL, "reboot", "");
  470. /* Umount all filesystems on halt/reboot */
  471. new_init_action(SHUTDOWN, "umount -a -r", "");
  472. /* Swapoff on halt/reboot */
  473. if (ENABLE_SWAPONOFF)
  474. new_init_action(SHUTDOWN, "swapoff -a", "");
  475. /* Prepare to restart init when a QUIT is received */
  476. new_init_action(RESTART, "init", "");
  477. /* Askfirst shell on tty1-4 */
  478. new_init_action(ASKFIRST, bb_default_login_shell, "");
  479. //TODO: VC_1 instead of ""? "" is console -> ctty problems -> angry users
  480. new_init_action(ASKFIRST, bb_default_login_shell, VC_2);
  481. new_init_action(ASKFIRST, bb_default_login_shell, VC_3);
  482. new_init_action(ASKFIRST, bb_default_login_shell, VC_4);
  483. /* sysinit */
  484. new_init_action(SYSINIT, INIT_SCRIPT, "");
  485. return;
  486. }
  487. #if ENABLE_FEATURE_USE_INITTAB
  488. /* optional_tty:ignored_runlevel:action:command
  489. * Delims are not to be collapsed and need exactly 4 tokens
  490. */
  491. while (config_read(parser, token, 4, 0, "#:",
  492. PARSE_NORMAL & ~(PARSE_TRIM | PARSE_COLLAPSE))) {
  493. /* order must correspond to SYSINIT..RESTART constants */
  494. static const char actions[] ALIGN1 =
  495. "sysinit\0""wait\0""once\0""respawn\0""askfirst\0"
  496. "ctrlaltdel\0""shutdown\0""restart\0";
  497. int action;
  498. char *tty = token[0];
  499. if (!token[3]) /* less than 4 tokens */
  500. goto bad_entry;
  501. action = index_in_strings(actions, token[2]);
  502. if (action < 0 || !token[3][0]) /* token[3]: command */
  503. goto bad_entry;
  504. /* turn .*TTY -> /dev/TTY */
  505. if (tty[0]) {
  506. if (strncmp(tty, "/dev/", 5) == 0)
  507. tty += 5;
  508. tty = concat_path_file("/dev/", tty);
  509. }
  510. new_init_action(1 << action, token[3], tty);
  511. if (tty[0])
  512. free(tty);
  513. continue;
  514. bad_entry:
  515. message(L_LOG | L_CONSOLE, "Bad inittab entry at line %d",
  516. parser->lineno);
  517. }
  518. config_close(parser);
  519. #endif
  520. }
  521. static void pause_and_low_level_reboot(unsigned magic) NORETURN;
  522. static void pause_and_low_level_reboot(unsigned magic)
  523. {
  524. pid_t pid;
  525. /* Allow time for last message to reach serial console, etc */
  526. sleep(1);
  527. /* We have to fork here, since the kernel calls do_exit(EXIT_SUCCESS)
  528. * in linux/kernel/sys.c, which can cause the machine to panic when
  529. * the init process exits... */
  530. pid = vfork();
  531. if (pid == 0) { /* child */
  532. reboot(magic);
  533. _exit(EXIT_SUCCESS);
  534. }
  535. while (1)
  536. sleep(1);
  537. }
  538. static void run_shutdown_and_kill_processes(void)
  539. {
  540. /* Run everything to be run at "shutdown". This is done _prior_
  541. * to killing everything, in case people wish to use scripts to
  542. * shut things down gracefully... */
  543. run_actions(SHUTDOWN);
  544. message(L_CONSOLE | L_LOG, "The system is going down NOW!");
  545. /* Send signals to every process _except_ pid 1 */
  546. kill(-1, SIGTERM);
  547. message(L_CONSOLE | L_LOG, "Sent SIG%s to all processes", "TERM");
  548. sync();
  549. sleep(1);
  550. kill(-1, SIGKILL);
  551. message(L_CONSOLE, "Sent SIG%s to all processes", "KILL");
  552. sync();
  553. /*sleep(1); - callers take care about making a pause */
  554. }
  555. /* Signal handling by init:
  556. *
  557. * For process with PID==1, on entry kernel sets all signals to SIG_DFL
  558. * and unmasks all signals. However, for process with PID==1,
  559. * default action (SIG_DFL) on any signal is to ignore it,
  560. * even for special signals SIGKILL and SIGCONT.
  561. * Also, any signal can be caught or blocked.
  562. * (but SIGSTOP is still handled specially, at least in 2.6.20)
  563. *
  564. * We install two kinds of handlers, "immediate" and "delayed".
  565. *
  566. * Immediate handlers execute at any time, even while, say, sysinit
  567. * is running.
  568. *
  569. * Delayed handlers just set a flag variable. The variable is checked
  570. * in the main loop and acted upon.
  571. *
  572. * halt/poweroff/reboot and restart have immediate handlers.
  573. * They only traverse linked list of struct action's, never modify it,
  574. * this should be safe to do even in signal handler. Also they
  575. * never return.
  576. *
  577. * SIGSTOP and SIGTSTP have immediate handlers. They just wait
  578. * for SIGCONT to happen.
  579. *
  580. * SIGHUP has a delayed handler, because modifying linked list
  581. * of struct action's from a signal handler while it is manipulated
  582. * by the program may be disastrous.
  583. *
  584. * Ctrl-Alt-Del has a delayed handler. Not a must, but allowing
  585. * it to happen even somewhere inside "sysinit" would be a bit awkward.
  586. *
  587. * There is a tiny probability that SIGHUP and Ctrl-Alt-Del will collide
  588. * and only one will be remembered and acted upon.
  589. */
  590. static void halt_reboot_pwoff(int sig) NORETURN;
  591. static void halt_reboot_pwoff(int sig)
  592. {
  593. const char *m;
  594. unsigned rb;
  595. run_shutdown_and_kill_processes();
  596. m = "halt";
  597. rb = RB_HALT_SYSTEM;
  598. if (sig == SIGTERM) {
  599. m = "reboot";
  600. rb = RB_AUTOBOOT;
  601. } else if (sig == SIGUSR2) {
  602. m = "poweroff";
  603. rb = RB_POWER_OFF;
  604. }
  605. message(L_CONSOLE, "Requesting system %s", m);
  606. pause_and_low_level_reboot(rb);
  607. /* not reached */
  608. }
  609. /* The SIGSTOP/SIGTSTP handler
  610. * NB: inside it, all signals except SIGCONT are masked
  611. * via appropriate setup in sigaction().
  612. */
  613. static void stop_handler(int sig UNUSED_PARAM)
  614. {
  615. smallint saved_bb_got_signal;
  616. int saved_errno;
  617. saved_bb_got_signal = bb_got_signal;
  618. saved_errno = errno;
  619. signal(SIGCONT, record_signo);
  620. while (1) {
  621. pid_t wpid;
  622. if (bb_got_signal == SIGCONT)
  623. break;
  624. /* NB: this can accidentally wait() for a process
  625. * which we waitfor() elsewhere! waitfor() must have
  626. * code which is resilient against this.
  627. */
  628. wpid = wait_any_nohang(NULL);
  629. mark_terminated(wpid);
  630. sleep(1);
  631. }
  632. signal(SIGCONT, SIG_DFL);
  633. errno = saved_errno;
  634. bb_got_signal = saved_bb_got_signal;
  635. }
  636. /* Handler for QUIT - exec "restart" action,
  637. * else (no such action defined) do nothing */
  638. static void restart_handler(int sig UNUSED_PARAM)
  639. {
  640. struct init_action *a;
  641. for (a = init_action_list; a; a = a->next) {
  642. if (!(a->action_type & RESTART))
  643. continue;
  644. /* Starting from here, we won't return.
  645. * Thus don't need to worry about preserving errno
  646. * and such.
  647. */
  648. run_shutdown_and_kill_processes();
  649. /* Allow Ctrl-Alt-Del to reboot the system.
  650. * This is how kernel sets it up for init, we follow suit.
  651. */
  652. reboot(RB_ENABLE_CAD); /* misnomer */
  653. if (open_stdio_to_tty(a->terminal)) {
  654. dbg_message(L_CONSOLE, "Trying to re-exec %s", a->command);
  655. /* Theoretically should be safe.
  656. * But in practice, kernel bugs may leave
  657. * unkillable processes, and wait() may block forever.
  658. * Oh well. Hoping "new" init won't be too surprised
  659. * by having children it didn't create.
  660. */
  661. //while (wait(NULL) > 0)
  662. // continue;
  663. init_exec(a->command);
  664. }
  665. /* Open or exec failed */
  666. pause_and_low_level_reboot(RB_HALT_SYSTEM);
  667. /* not reached */
  668. }
  669. }
  670. #if ENABLE_FEATURE_USE_INITTAB
  671. static void reload_inittab(void)
  672. {
  673. struct init_action *a, **nextp;
  674. message(L_LOG, "reloading /etc/inittab");
  675. /* Disable old entries */
  676. for (a = init_action_list; a; a = a->next)
  677. a->action_type = ONCE;
  678. /* Append new entries, or modify existing entries
  679. * (set a->action_type) if cmd and device name
  680. * match new ones. End result: only entries with
  681. * a->action_type == ONCE are stale.
  682. */
  683. parse_inittab();
  684. #if ENABLE_FEATURE_KILL_REMOVED
  685. /* Kill stale entries */
  686. /* Be nice and send SIGTERM first */
  687. for (a = init_action_list; a; a = a->next)
  688. if (a->action_type == ONCE && a->pid != 0)
  689. kill(a->pid, SIGTERM);
  690. if (CONFIG_FEATURE_KILL_DELAY) {
  691. /* NB: parent will wait in NOMMU case */
  692. if ((BB_MMU ? fork() : vfork()) == 0) { /* child */
  693. sleep(CONFIG_FEATURE_KILL_DELAY);
  694. for (a = init_action_list; a; a = a->next)
  695. if (a->action_type == ONCE && a->pid != 0)
  696. kill(a->pid, SIGKILL);
  697. _exit(EXIT_SUCCESS);
  698. }
  699. }
  700. #endif
  701. /* Remove stale (ONCE) and not useful (SYSINIT,WAIT) entries */
  702. nextp = &init_action_list;
  703. while ((a = *nextp) != NULL) {
  704. if (a->action_type & (ONCE | SYSINIT | WAIT)) {
  705. *nextp = a->next;
  706. free(a);
  707. } else {
  708. nextp = &a->next;
  709. }
  710. }
  711. /* Not needed: */
  712. /* run_actions(RESPAWN | ASKFIRST); */
  713. /* - we return to main loop, which does this automagically */
  714. }
  715. #endif
  716. static int check_delayed_sigs(void)
  717. {
  718. int sigs_seen = 0;
  719. while (1) {
  720. smallint sig = bb_got_signal;
  721. if (!sig)
  722. return sigs_seen;
  723. bb_got_signal = 0;
  724. sigs_seen = 1;
  725. #if ENABLE_FEATURE_USE_INITTAB
  726. if (sig == SIGHUP)
  727. reload_inittab();
  728. #endif
  729. if (sig == SIGINT)
  730. run_actions(CTRLALTDEL);
  731. }
  732. }
  733. int init_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  734. int init_main(int argc UNUSED_PARAM, char **argv)
  735. {
  736. die_sleep = 30 * 24*60*60; /* if xmalloc would ever die... */
  737. if (argv[1] && !strcmp(argv[1], "-q")) {
  738. return kill(1, SIGHUP);
  739. }
  740. if (!DEBUG_INIT) {
  741. /* Expect to be invoked as init with PID=1 or be invoked as linuxrc */
  742. if (getpid() != 1
  743. && (!ENABLE_FEATURE_INITRD || !strstr(applet_name, "linuxrc"))
  744. ) {
  745. bb_show_usage();
  746. }
  747. /* Turn off rebooting via CTL-ALT-DEL - we get a
  748. * SIGINT on CAD so we can shut things down gracefully... */
  749. reboot(RB_DISABLE_CAD); /* misnomer */
  750. }
  751. /* Figure out where the default console should be */
  752. console_init();
  753. set_sane_term();
  754. xchdir("/");
  755. setsid();
  756. /* Make sure environs is set to something sane */
  757. putenv((char *) "HOME=/");
  758. putenv((char *) bb_PATH_root_path);
  759. putenv((char *) "SHELL=/bin/sh");
  760. putenv((char *) "USER=root"); /* needed? why? */
  761. if (argv[1])
  762. xsetenv("RUNLEVEL", argv[1]);
  763. /* Hello world */
  764. message(MAYBE_CONSOLE | L_LOG, "init started: %s", bb_banner);
  765. /* Make sure there is enough memory to do something useful. */
  766. if (ENABLE_SWAPONOFF) {
  767. struct sysinfo info;
  768. if (sysinfo(&info) == 0
  769. && (info.mem_unit ? : 1) * (long long)info.totalram < 1024*1024
  770. ) {
  771. message(L_CONSOLE, "Low memory, forcing swapon");
  772. /* swapon -a requires /proc typically */
  773. new_init_action(SYSINIT, "mount -t proc proc /proc", "");
  774. /* Try to turn on swap */
  775. new_init_action(SYSINIT, "swapon -a", "");
  776. run_actions(SYSINIT); /* wait and removing */
  777. }
  778. }
  779. /* Check if we are supposed to be in single user mode */
  780. if (argv[1]
  781. && (!strcmp(argv[1], "single") || !strcmp(argv[1], "-s") || LONE_CHAR(argv[1], '1'))
  782. ) {
  783. /* ??? shouldn't we set RUNLEVEL="b" here? */
  784. /* Start a shell on console */
  785. new_init_action(RESPAWN, bb_default_login_shell, "");
  786. } else {
  787. /* Not in single user mode - see what inittab says */
  788. /* NOTE that if CONFIG_FEATURE_USE_INITTAB is NOT defined,
  789. * then parse_inittab() simply adds in some default
  790. * actions(i.e., INIT_SCRIPT and a pair
  791. * of "askfirst" shells */
  792. parse_inittab();
  793. }
  794. #if ENABLE_SELINUX
  795. if (getenv("SELINUX_INIT") == NULL) {
  796. int enforce = 0;
  797. putenv((char*)"SELINUX_INIT=YES");
  798. if (selinux_init_load_policy(&enforce) == 0) {
  799. BB_EXECVP(argv[0], argv);
  800. } else if (enforce > 0) {
  801. /* SELinux in enforcing mode but load_policy failed */
  802. message(L_CONSOLE, "cannot load SELinux Policy. "
  803. "Machine is in enforcing mode. Halting now.");
  804. exit(EXIT_FAILURE);
  805. }
  806. }
  807. #endif
  808. /* Make the command line just say "init" - thats all, nothing else */
  809. strncpy(argv[0], "init", strlen(argv[0]));
  810. /* Wipe argv[1]-argv[N] so they don't clutter the ps listing */
  811. while (*++argv)
  812. memset(*argv, 0, strlen(*argv));
  813. /* Set up signal handlers */
  814. if (!DEBUG_INIT) {
  815. struct sigaction sa;
  816. bb_signals(0
  817. + (1 << SIGUSR1) /* halt */
  818. + (1 << SIGTERM) /* reboot */
  819. + (1 << SIGUSR2) /* poweroff */
  820. , halt_reboot_pwoff);
  821. signal(SIGQUIT, restart_handler); /* re-exec another init */
  822. /* Stop handler must allow only SIGCONT inside itself */
  823. memset(&sa, 0, sizeof(sa));
  824. sigfillset(&sa.sa_mask);
  825. sigdelset(&sa.sa_mask, SIGCONT);
  826. sa.sa_handler = stop_handler;
  827. /* NB: sa_flags doesn't have SA_RESTART.
  828. * It must be able to interrupt wait().
  829. */
  830. sigaction_set(SIGTSTP, &sa); /* pause */
  831. /* Does not work as intended, at least in 2.6.20.
  832. * SIGSTOP is simply ignored by init:
  833. */
  834. sigaction_set(SIGSTOP, &sa); /* pause */
  835. /* SIGINT (Ctrl-Alt-Del) must interrupt wait(),
  836. * setting handler without SA_RESTART flag.
  837. */
  838. bb_signals_recursive_norestart((1 << SIGINT), record_signo);
  839. }
  840. /* Now run everything that needs to be run */
  841. /* First run the sysinit command */
  842. run_actions(SYSINIT);
  843. check_delayed_sigs();
  844. /* Next run anything that wants to block */
  845. run_actions(WAIT);
  846. check_delayed_sigs();
  847. /* Next run anything to be run only once */
  848. run_actions(ONCE);
  849. /* Set up "reread /etc/inittab" handler.
  850. * Handler is set up without SA_RESTART, it will interrupt syscalls.
  851. */
  852. if (!DEBUG_INIT && ENABLE_FEATURE_USE_INITTAB)
  853. bb_signals_recursive_norestart((1 << SIGHUP), record_signo);
  854. /* Now run the looping stuff for the rest of forever.
  855. */
  856. while (1) {
  857. int maybe_WNOHANG;
  858. maybe_WNOHANG = check_delayed_sigs();
  859. /* (Re)run the respawn/askfirst stuff */
  860. run_actions(RESPAWN | ASKFIRST);
  861. maybe_WNOHANG |= check_delayed_sigs();
  862. /* Don't consume all CPU time - sleep a bit */
  863. sleep(1);
  864. maybe_WNOHANG |= check_delayed_sigs();
  865. /* Wait for any child process(es) to exit.
  866. *
  867. * If check_delayed_sigs above reported that a signal
  868. * was caught, wait will be nonblocking. This ensures
  869. * that if SIGHUP has reloaded inittab, respawn and askfirst
  870. * actions will not be delayed until next child death.
  871. */
  872. if (maybe_WNOHANG)
  873. maybe_WNOHANG = WNOHANG;
  874. while (1) {
  875. pid_t wpid;
  876. struct init_action *a;
  877. /* If signals happen _in_ the wait, they interrupt it,
  878. * bb_signals_recursive_norestart set them up that way
  879. */
  880. wpid = waitpid(-1, NULL, maybe_WNOHANG);
  881. if (wpid <= 0)
  882. break;
  883. a = mark_terminated(wpid);
  884. if (a) {
  885. message(L_LOG, "process '%s' (pid %d) exited. "
  886. "Scheduling for restart.",
  887. a->command, wpid);
  888. }
  889. /* See if anyone else is waiting to be reaped */
  890. maybe_WNOHANG = WNOHANG;
  891. }
  892. } /* while (1) */
  893. }