init.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  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. /* Was a CONFIG_xxx option. A lot of people were building
  16. * not fully functional init by switching it on! */
  17. #define DEBUG_INIT 0
  18. #define COMMAND_SIZE 256
  19. #define CONSOLE_NAME_SIZE 32
  20. #define MAXENV 16 /* Number of env. vars */
  21. /*
  22. * When a file named CORE_ENABLE_FLAG_FILE exists, setrlimit is called
  23. * before processes are spawned to set core file size as unlimited.
  24. * This is for debugging only. Don't use this is production, unless
  25. * you want core dumps lying about....
  26. */
  27. #define CORE_ENABLE_FLAG_FILE "/.init_enable_core"
  28. #include <sys/resource.h>
  29. #define INITTAB "/etc/inittab" /* inittab file location */
  30. #ifndef INIT_SCRIPT
  31. #define INIT_SCRIPT "/etc/init.d/rcS" /* Default sysinit script. */
  32. #endif
  33. /* Allowed init action types */
  34. #define SYSINIT 0x01
  35. #define RESPAWN 0x02
  36. /* like respawn, but wait for <Enter> to be pressed on tty: */
  37. #define ASKFIRST 0x04
  38. #define WAIT 0x08
  39. #define ONCE 0x10
  40. #define CTRLALTDEL 0x20
  41. #define SHUTDOWN 0x40
  42. #define RESTART 0x80
  43. /* Set up a linked list of init_actions, to be read from inittab */
  44. struct init_action {
  45. struct init_action *next;
  46. pid_t pid;
  47. uint8_t action_type;
  48. char terminal[CONSOLE_NAME_SIZE];
  49. char command[COMMAND_SIZE];
  50. };
  51. /* Static variables */
  52. static struct init_action *init_action_list = NULL;
  53. static const char *log_console = VC_5;
  54. enum {
  55. L_LOG = 0x1,
  56. L_CONSOLE = 0x2,
  57. #if ENABLE_FEATURE_EXTRA_QUIET
  58. MAYBE_CONSOLE = 0x0,
  59. #else
  60. MAYBE_CONSOLE = L_CONSOLE,
  61. #endif
  62. #ifndef RB_HALT_SYSTEM
  63. RB_HALT_SYSTEM = 0xcdef0123, /* FIXME: this overflows enum */
  64. RB_ENABLE_CAD = 0x89abcdef,
  65. RB_DISABLE_CAD = 0,
  66. RB_POWER_OFF = 0x4321fedc,
  67. RB_AUTOBOOT = 0x01234567,
  68. #endif
  69. };
  70. /* Function prototypes */
  71. static void halt_reboot_pwoff(int sig) NORETURN;
  72. static void waitfor(pid_t pid)
  73. {
  74. /* waitfor(run(x)): protect against failed fork inside run() */
  75. if (pid <= 0)
  76. return;
  77. /* Wait for any child (prevent zombies from exiting orphaned processes)
  78. * but exit the loop only when specified one has exited. */
  79. while (wait(NULL) != pid)
  80. continue;
  81. }
  82. static void loop_forever(void) NORETURN;
  83. static void loop_forever(void)
  84. {
  85. while (1)
  86. sleep(1);
  87. }
  88. /* Print a message to the specified device.
  89. * "where" may be bitwise-or'd from L_LOG | L_CONSOLE
  90. * NB: careful, we can be called after vfork!
  91. */
  92. #define messageD(...) do { if (DEBUG_INIT) message(__VA_ARGS__); } while (0)
  93. static void message(int where, const char *fmt, ...)
  94. __attribute__ ((format(printf, 2, 3)));
  95. static void message(int where, const char *fmt, ...)
  96. {
  97. static int log_fd = -1;
  98. va_list arguments;
  99. unsigned l;
  100. char msg[128];
  101. msg[0] = '\r';
  102. va_start(arguments, fmt);
  103. l = 1 + vsnprintf(msg + 1, sizeof(msg) - 2, fmt, arguments);
  104. if (l > sizeof(msg) - 1)
  105. l = sizeof(msg) - 1;
  106. msg[l] = '\0';
  107. va_end(arguments);
  108. if (ENABLE_FEATURE_INIT_SYSLOG) {
  109. if (where & L_LOG) {
  110. /* Log the message to syslogd */
  111. openlog("init", 0, LOG_DAEMON);
  112. /* don't print "\r" */
  113. syslog(LOG_INFO, "%s", msg + 1);
  114. closelog();
  115. }
  116. msg[l++] = '\n';
  117. msg[l] = '\0';
  118. } else {
  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. if (where & L_CONSOLE) {
  143. /* Send console messages to console so people will see them. */
  144. full_write(STDERR_FILENO, msg, l);
  145. }
  146. }
  147. /* From <linux/serial.h> */
  148. struct serial_struct {
  149. int type;
  150. int line;
  151. unsigned int port;
  152. int irq;
  153. int flags;
  154. int xmit_fifo_size;
  155. int custom_divisor;
  156. int baud_base;
  157. unsigned short close_delay;
  158. char io_type;
  159. char reserved_char[1];
  160. int hub6;
  161. unsigned short closing_wait; /* time to wait before closing */
  162. unsigned short closing_wait2; /* no longer used... */
  163. unsigned char *iomem_base;
  164. unsigned short iomem_reg_shift;
  165. unsigned int port_high;
  166. unsigned long iomap_base; /* cookie passed into ioremap */
  167. int reserved[1];
  168. /* Paranoia (imagine 64bit kernel overwriting 32bit userspace stack) */
  169. uint32_t bbox_reserved[16];
  170. };
  171. static void console_init(void)
  172. {
  173. struct serial_struct sr;
  174. char *s;
  175. s = getenv("CONSOLE");
  176. if (!s)
  177. s = getenv("console");
  178. if (s) {
  179. int fd = open(s, O_RDWR | O_NONBLOCK | O_NOCTTY);
  180. if (fd >= 0) {
  181. dup2(fd, STDIN_FILENO);
  182. dup2(fd, STDOUT_FILENO);
  183. xmove_fd(fd, STDERR_FILENO);
  184. }
  185. messageD(L_LOG, "console='%s'", s);
  186. } else {
  187. /* Make sure fd 0,1,2 are not closed
  188. * (so that they won't be used by future opens) */
  189. bb_sanitize_stdio();
  190. // Users report problems
  191. // /* Make sure init can't be blocked by writing to stderr */
  192. // fcntl(STDERR_FILENO, F_SETFL, fcntl(STDERR_FILENO, F_GETFL) | O_NONBLOCK);
  193. }
  194. s = getenv("TERM");
  195. if (ioctl(STDIN_FILENO, TIOCGSERIAL, &sr) == 0) {
  196. /* Force the TERM setting to vt102 for serial console
  197. * if TERM is set to linux (the default) */
  198. if (!s || strcmp(s, "linux") == 0)
  199. putenv((char*)"TERM=vt102");
  200. if (!ENABLE_FEATURE_INIT_SYSLOG)
  201. log_console = NULL;
  202. } else if (!s)
  203. putenv((char*)"TERM=linux");
  204. }
  205. /* Set terminal settings to reasonable defaults.
  206. * NB: careful, we can be called after vfork! */
  207. static void set_sane_term(void)
  208. {
  209. struct termios tty;
  210. tcgetattr(STDIN_FILENO, &tty);
  211. /* set control chars */
  212. tty.c_cc[VINTR] = 3; /* C-c */
  213. tty.c_cc[VQUIT] = 28; /* C-\ */
  214. tty.c_cc[VERASE] = 127; /* C-? */
  215. tty.c_cc[VKILL] = 21; /* C-u */
  216. tty.c_cc[VEOF] = 4; /* C-d */
  217. tty.c_cc[VSTART] = 17; /* C-q */
  218. tty.c_cc[VSTOP] = 19; /* C-s */
  219. tty.c_cc[VSUSP] = 26; /* C-z */
  220. /* use line discipline 0 */
  221. tty.c_line = 0;
  222. /* Make it be sane */
  223. tty.c_cflag &= CBAUD | CBAUDEX | CSIZE | CSTOPB | PARENB | PARODD;
  224. tty.c_cflag |= CREAD | HUPCL | CLOCAL;
  225. /* input modes */
  226. tty.c_iflag = ICRNL | IXON | IXOFF;
  227. /* output modes */
  228. tty.c_oflag = OPOST | ONLCR;
  229. /* local modes */
  230. tty.c_lflag =
  231. ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE | IEXTEN;
  232. tcsetattr_stdin_TCSANOW(&tty);
  233. }
  234. /* Open the new terminal device.
  235. * NB: careful, we can be called after vfork! */
  236. static void open_stdio_to_tty(const char* tty_name, int exit_on_failure)
  237. {
  238. /* empty tty_name means "use init's tty", else... */
  239. if (tty_name[0]) {
  240. int fd;
  241. close(STDIN_FILENO);
  242. /* fd can be only < 0 or 0: */
  243. fd = device_open(tty_name, O_RDWR);
  244. if (fd) {
  245. message(L_LOG | L_CONSOLE, "can't open %s: %s",
  246. tty_name, strerror(errno));
  247. if (exit_on_failure)
  248. _exit(EXIT_FAILURE);
  249. if (DEBUG_INIT)
  250. _exit(2);
  251. /* NB: we don't reach this if we were called after vfork.
  252. * Thus halt_reboot_pwoff() itself need not be vfork-safe. */
  253. halt_reboot_pwoff(SIGUSR1); /* halt the system */
  254. }
  255. dup2(STDIN_FILENO, STDOUT_FILENO);
  256. dup2(STDIN_FILENO, STDERR_FILENO);
  257. }
  258. set_sane_term();
  259. }
  260. /* Wrapper around exec:
  261. * Takes string (max COMMAND_SIZE chars).
  262. * If chars like '>' detected, execs '[-]/bin/sh -c "exec ......."'.
  263. * Otherwise splits words on whitespace, deals with leading dash,
  264. * and uses plain exec().
  265. * NB: careful, we can be called after vfork!
  266. */
  267. static void init_exec(const char *command)
  268. {
  269. char *cmd[COMMAND_SIZE / 2];
  270. char buf[COMMAND_SIZE + 6]; /* COMMAND_SIZE+strlen("exec ")+1 */
  271. int dash = (command[0] == '-' /* maybe? && command[1] == '/' */);
  272. /* See if any special /bin/sh requiring characters are present */
  273. if (strpbrk(command, "~`!$^&*()=|\\{}[];\"'<>?") != NULL) {
  274. strcpy(buf, "exec ");
  275. strcpy(buf + 5, command + dash); /* excluding "-" */
  276. /* NB: LIBBB_DEFAULT_LOGIN_SHELL define has leading dash */
  277. cmd[0] = (char*)(LIBBB_DEFAULT_LOGIN_SHELL + !dash);
  278. cmd[1] = (char*)"-c";
  279. cmd[2] = buf;
  280. cmd[3] = NULL;
  281. } else {
  282. /* Convert command (char*) into cmd (char**, one word per string) */
  283. char *word, *next;
  284. int i = 0;
  285. next = strcpy(buf, command); /* including "-" */
  286. while ((word = strsep(&next, " \t")) != NULL) {
  287. if (*word != '\0') { /* not two spaces/tabs together? */
  288. cmd[i] = word;
  289. i++;
  290. }
  291. }
  292. cmd[i] = NULL;
  293. }
  294. /* If we saw leading "-", it is interactive shell.
  295. * Try harder to give it a controlling tty.
  296. * And skip "-" in actual exec call. */
  297. if (dash) {
  298. /* _Attempt_ to make stdin a controlling tty. */
  299. if (ENABLE_FEATURE_INIT_SCTTY)
  300. ioctl(STDIN_FILENO, TIOCSCTTY, 0 /*only try, don't steal*/);
  301. }
  302. BB_EXECVP(cmd[0] + dash, cmd);
  303. message(L_LOG | L_CONSOLE, "cannot run '%s': %s", cmd[0], strerror(errno));
  304. /* returns if execvp fails */
  305. }
  306. /* Used only by run_actions */
  307. static pid_t run(const struct init_action *a)
  308. {
  309. pid_t pid;
  310. sigset_t nmask, omask;
  311. /* Block sigchild while forking (why?) */
  312. sigemptyset(&nmask);
  313. sigaddset(&nmask, SIGCHLD);
  314. sigprocmask(SIG_BLOCK, &nmask, &omask);
  315. if (BB_MMU && (a->action_type & ASKFIRST))
  316. pid = fork();
  317. else
  318. pid = vfork();
  319. sigprocmask(SIG_SETMASK, &omask, NULL);
  320. if (pid < 0)
  321. message(L_LOG | L_CONSOLE, "can't fork");
  322. if (pid)
  323. return pid;
  324. /* Child */
  325. /* Reset signal handlers that were set by the parent process */
  326. bb_signals(0
  327. + (1 << SIGUSR1)
  328. + (1 << SIGUSR2)
  329. + (1 << SIGINT)
  330. + (1 << SIGTERM)
  331. + (1 << SIGHUP)
  332. + (1 << SIGQUIT)
  333. + (1 << SIGCONT)
  334. + (1 << SIGSTOP)
  335. + (1 << SIGTSTP)
  336. , SIG_DFL);
  337. /* Create a new session and make ourself the process
  338. * group leader */
  339. setsid();
  340. /* Open the new terminal device */
  341. open_stdio_to_tty(a->terminal, 1 /* - exit if open fails */);
  342. // NB: do not enable unless you change vfork to fork above
  343. #ifdef BUT_RUN_ACTIONS_ALREADY_DOES_WAITING
  344. /* If the init Action requires us to wait, then force the
  345. * supplied terminal to be the controlling tty. */
  346. if (a->action_type & (SYSINIT | WAIT | CTRLALTDEL | SHUTDOWN | RESTART)) {
  347. /* Now fork off another process to just hang around */
  348. pid = fork();
  349. if (pid < 0) {
  350. message(L_LOG | L_CONSOLE, "can't fork");
  351. _exit(EXIT_FAILURE);
  352. }
  353. if (pid > 0) {
  354. /* Parent - wait till the child is done */
  355. bb_signals(0
  356. + (1 << SIGINT)
  357. + (1 << SIGTSTP)
  358. + (1 << SIGQUIT)
  359. , SIG_IGN);
  360. signal(SIGCHLD, SIG_DFL);
  361. waitfor(pid);
  362. /* See if stealing the controlling tty back is necessary */
  363. if (tcgetpgrp(0) != getpid())
  364. _exit(EXIT_SUCCESS);
  365. /* Use a temporary process to steal the controlling tty. */
  366. pid = fork();
  367. if (pid < 0) {
  368. message(L_LOG | L_CONSOLE, "can't fork");
  369. _exit(EXIT_FAILURE);
  370. }
  371. if (pid == 0) {
  372. setsid();
  373. ioctl(0, TIOCSCTTY, 1);
  374. _exit(EXIT_SUCCESS);
  375. }
  376. waitfor(pid);
  377. _exit(EXIT_SUCCESS);
  378. }
  379. /* Child - fall though to actually execute things */
  380. }
  381. #endif
  382. /* NB: on NOMMU we can't wait for input in child, so
  383. * "askfirst" will work the same as "respawn". */
  384. if (BB_MMU && (a->action_type & ASKFIRST)) {
  385. static const char press_enter[] ALIGN1 =
  386. #ifdef CUSTOMIZED_BANNER
  387. #include CUSTOMIZED_BANNER
  388. #endif
  389. "\nPlease press Enter to activate this console. ";
  390. char c;
  391. /*
  392. * Save memory by not exec-ing anything large (like a shell)
  393. * before the user wants it. This is critical if swap is not
  394. * enabled and the system has low memory. Generally this will
  395. * be run on the second virtual console, and the first will
  396. * be allowed to start a shell or whatever an init script
  397. * specifies.
  398. */
  399. messageD(L_LOG, "waiting for enter to start '%s'"
  400. "(pid %d, tty '%s')\n",
  401. a->command, getpid(), a->terminal);
  402. full_write(STDOUT_FILENO, press_enter, sizeof(press_enter) - 1);
  403. while (safe_read(STDIN_FILENO, &c, 1) == 1 && c != '\n')
  404. continue;
  405. }
  406. if (ENABLE_FEATURE_INIT_COREDUMPS) {
  407. struct stat sb;
  408. if (stat(CORE_ENABLE_FLAG_FILE, &sb) == 0) {
  409. struct rlimit limit;
  410. limit.rlim_cur = RLIM_INFINITY;
  411. limit.rlim_max = RLIM_INFINITY;
  412. setrlimit(RLIMIT_CORE, &limit);
  413. }
  414. }
  415. /* Log the process name and args */
  416. message(L_LOG, "starting pid %d, tty '%s': '%s'",
  417. getpid(), a->terminal, a->command);
  418. /* Now run it. The new program will take over this PID,
  419. * so nothing further in init.c should be run. */
  420. init_exec(a->command);
  421. /* We're still here? Some error happened. */
  422. _exit(-1);
  423. }
  424. static void delete_init_action(struct init_action *action)
  425. {
  426. struct init_action *a, *b = NULL;
  427. for (a = init_action_list; a; b = a, a = a->next) {
  428. if (a == action) {
  429. if (b == NULL) {
  430. init_action_list = a->next;
  431. } else {
  432. b->next = a->next;
  433. }
  434. free(a);
  435. break;
  436. }
  437. }
  438. }
  439. /* Run all commands of a particular type */
  440. static void run_actions(int action_type)
  441. {
  442. struct init_action *a, *tmp;
  443. for (a = init_action_list; a; a = tmp) {
  444. tmp = a->next;
  445. if (a->action_type & action_type) {
  446. // Pointless: run() will error out if open of device fails.
  447. ///* a->terminal of "" means "init's console" */
  448. //if (a->terminal[0] && access(a->terminal, R_OK | W_OK)) {
  449. // //message(L_LOG | L_CONSOLE, "Device %s cannot be opened in RW mode", a->terminal /*, strerror(errno)*/);
  450. // delete_init_action(a);
  451. //} else
  452. if (a->action_type & (SYSINIT | WAIT | CTRLALTDEL | SHUTDOWN | RESTART)) {
  453. waitfor(run(a));
  454. delete_init_action(a);
  455. } else if (a->action_type & ONCE) {
  456. run(a);
  457. delete_init_action(a);
  458. } else if (a->action_type & (RESPAWN | ASKFIRST)) {
  459. /* Only run stuff with pid==0. If they have
  460. * a pid, that means it is still running */
  461. if (a->pid == 0) {
  462. a->pid = run(a);
  463. }
  464. }
  465. }
  466. }
  467. }
  468. static void init_reboot(unsigned long magic)
  469. {
  470. pid_t pid;
  471. /* We have to fork here, since the kernel calls do_exit(EXIT_SUCCESS) in
  472. * linux/kernel/sys.c, which can cause the machine to panic when
  473. * the init process is killed.... */
  474. pid = vfork();
  475. if (pid == 0) { /* child */
  476. reboot(magic);
  477. _exit(EXIT_SUCCESS);
  478. }
  479. waitfor(pid);
  480. }
  481. static void kill_all_processes(void)
  482. {
  483. /* run everything to be run at "shutdown". This is done _prior_
  484. * to killing everything, in case people wish to use scripts to
  485. * shut things down gracefully... */
  486. run_actions(SHUTDOWN);
  487. /* first disable all our signals */
  488. sigprocmask_allsigs(SIG_BLOCK);
  489. message(L_CONSOLE | L_LOG, "The system is going down NOW!");
  490. /* Allow Ctrl-Alt-Del to reboot system. */
  491. init_reboot(RB_ENABLE_CAD);
  492. /* Send signals to every process _except_ pid 1 */
  493. message(L_CONSOLE | L_LOG, "Sending SIG%s to all processes", "TERM");
  494. kill(-1, SIGTERM);
  495. sync();
  496. sleep(1);
  497. message(L_CONSOLE | L_LOG, "Sending SIG%s to all processes", "KILL");
  498. kill(-1, SIGKILL);
  499. sync();
  500. sleep(1);
  501. }
  502. static void halt_reboot_pwoff(int sig)
  503. {
  504. const char *m = "halt";
  505. int rb;
  506. kill_all_processes();
  507. rb = RB_HALT_SYSTEM;
  508. if (sig == SIGTERM) {
  509. m = "reboot";
  510. rb = RB_AUTOBOOT;
  511. } else if (sig == SIGUSR2) {
  512. m = "poweroff";
  513. rb = RB_POWER_OFF;
  514. }
  515. message(L_CONSOLE | L_LOG, "Requesting system %s", m);
  516. /* allow time for last message to reach serial console */
  517. sleep(2);
  518. init_reboot(rb);
  519. loop_forever();
  520. }
  521. /* Handler for QUIT - exec "restart" action,
  522. * else (no such action defined) do nothing */
  523. static void exec_restart_action(int sig UNUSED_PARAM)
  524. {
  525. struct init_action *a;
  526. for (a = init_action_list; a; a = a->next) {
  527. if (a->action_type & RESTART) {
  528. kill_all_processes();
  529. /* unblock all signals (blocked in kill_all_processes()) */
  530. sigprocmask_allsigs(SIG_UNBLOCK);
  531. /* Open the new terminal device */
  532. open_stdio_to_tty(a->terminal, 0 /* - halt if open fails */);
  533. messageD(L_CONSOLE | L_LOG, "Trying to re-exec %s", a->command);
  534. init_exec(a->command);
  535. sleep(2);
  536. init_reboot(RB_HALT_SYSTEM);
  537. loop_forever();
  538. }
  539. }
  540. }
  541. static void ctrlaltdel_signal(int sig UNUSED_PARAM)
  542. {
  543. run_actions(CTRLALTDEL);
  544. }
  545. /* The SIGCONT handler is set to record_signo().
  546. * It just sets bb_got_signal = SIGCONT. */
  547. /* The SIGSTOP & SIGTSTP handler */
  548. static void stop_handler(int sig UNUSED_PARAM)
  549. {
  550. int saved_errno = errno;
  551. bb_got_signal = 0;
  552. while (bb_got_signal == 0)
  553. pause();
  554. errno = saved_errno;
  555. }
  556. static void new_init_action(uint8_t action_type, const char *command, const char *cons)
  557. {
  558. struct init_action *a, *last;
  559. // Why?
  560. // if (strcmp(cons, bb_dev_null) == 0 && (action & ASKFIRST))
  561. // return;
  562. /* Append to the end of the list */
  563. for (a = last = init_action_list; a; a = a->next) {
  564. /* don't enter action if it's already in the list,
  565. * but do overwrite existing actions */
  566. if ((strcmp(a->command, command) == 0)
  567. && (strcmp(a->terminal, cons) == 0)
  568. ) {
  569. a->action_type = action_type;
  570. return;
  571. }
  572. last = a;
  573. }
  574. a = xzalloc(sizeof(*a));
  575. if (last) {
  576. last->next = a;
  577. } else {
  578. init_action_list = a;
  579. }
  580. a->action_type = action_type;
  581. safe_strncpy(a->command, command, sizeof(a->command));
  582. safe_strncpy(a->terminal, cons, sizeof(a->terminal));
  583. messageD(L_LOG | L_CONSOLE, "command='%s' action=%d tty='%s'\n",
  584. a->command, a->action_type, a->terminal);
  585. }
  586. /* NOTE that if CONFIG_FEATURE_USE_INITTAB is NOT defined,
  587. * then parse_inittab() simply adds in some default
  588. * actions(i.e., runs INIT_SCRIPT and then starts a pair
  589. * of "askfirst" shells). If CONFIG_FEATURE_USE_INITTAB
  590. * _is_ defined, but /etc/inittab is missing, this
  591. * results in the same set of default behaviors.
  592. */
  593. static void parse_inittab(void)
  594. {
  595. #if ENABLE_FEATURE_USE_INITTAB
  596. char *token[4];
  597. parser_t *parser = config_open2("/etc/inittab", fopen_for_read);
  598. if (parser == NULL)
  599. #endif
  600. {
  601. /* No inittab file -- set up some default behavior */
  602. /* Reboot on Ctrl-Alt-Del */
  603. new_init_action(CTRLALTDEL, "reboot", "");
  604. /* Umount all filesystems on halt/reboot */
  605. new_init_action(SHUTDOWN, "umount -a -r", "");
  606. /* Swapoff on halt/reboot */
  607. if (ENABLE_SWAPONOFF)
  608. new_init_action(SHUTDOWN, "swapoff -a", "");
  609. /* Prepare to restart init when a QUIT is received */
  610. new_init_action(RESTART, "init", "");
  611. /* Askfirst shell on tty1-4 */
  612. new_init_action(ASKFIRST, bb_default_login_shell, "");
  613. //TODO: VC_1 instead of ""? "" is console -> ctty problems -> angry users
  614. new_init_action(ASKFIRST, bb_default_login_shell, VC_2);
  615. new_init_action(ASKFIRST, bb_default_login_shell, VC_3);
  616. new_init_action(ASKFIRST, bb_default_login_shell, VC_4);
  617. /* sysinit */
  618. new_init_action(SYSINIT, INIT_SCRIPT, "");
  619. return;
  620. }
  621. #if ENABLE_FEATURE_USE_INITTAB
  622. /* optional_tty:ignored_runlevel:action:command
  623. * Delims are not to be collapsed and need exactly 4 tokens
  624. */
  625. while (config_read(parser, token, 4, 0, "#:",
  626. PARSE_NORMAL & ~(PARSE_TRIM | PARSE_COLLAPSE))) {
  627. /* order must correspond to SYSINIT..RESTART constants */
  628. static const char actions[] ALIGN1 =
  629. "sysinit\0""respawn\0""askfirst\0""wait\0""once\0"
  630. "ctrlaltdel\0""shutdown\0""restart\0";
  631. int action;
  632. char *tty = token[0];
  633. if (!token[3]) /* less than 4 tokens */
  634. goto bad_entry;
  635. action = index_in_strings(actions, token[2]);
  636. if (action < 0 || !token[3][0]) /* token[3]: command */
  637. goto bad_entry;
  638. /* turn .*TTY -> /dev/TTY */
  639. if (tty[0]) {
  640. if (strncmp(tty, "/dev/", 5) == 0)
  641. tty += 5;
  642. tty = concat_path_file("/dev/", tty);
  643. }
  644. new_init_action(1 << action, token[3], tty);
  645. if (tty[0])
  646. free(tty);
  647. continue;
  648. bad_entry:
  649. message(L_LOG | L_CONSOLE, "Bad inittab entry at line %d",
  650. parser->lineno);
  651. }
  652. config_close(parser);
  653. #endif
  654. }
  655. #if ENABLE_FEATURE_USE_INITTAB
  656. static void reload_signal(int sig UNUSED_PARAM)
  657. {
  658. struct init_action *a, *tmp;
  659. message(L_LOG, "reloading /etc/inittab");
  660. /* disable old entrys */
  661. for (a = init_action_list; a; a = a->next) {
  662. a->action_type = ONCE;
  663. }
  664. parse_inittab();
  665. if (ENABLE_FEATURE_KILL_REMOVED) {
  666. /* Be nice and send SIGTERM first */
  667. for (a = init_action_list; a; a = a->next) {
  668. pid_t pid = a->pid;
  669. if ((a->action_type & ONCE) && pid != 0) {
  670. kill(pid, SIGTERM);
  671. }
  672. }
  673. #if CONFIG_FEATURE_KILL_DELAY
  674. /* NB: parent will wait in NOMMU case */
  675. if ((BB_MMU ? fork() : vfork()) == 0) { /* child */
  676. sleep(CONFIG_FEATURE_KILL_DELAY);
  677. for (a = init_action_list; a; a = a->next) {
  678. pid_t pid = a->pid;
  679. if ((a->action_type & ONCE) && pid != 0) {
  680. kill(pid, SIGKILL);
  681. }
  682. }
  683. _exit(EXIT_SUCCESS);
  684. }
  685. #endif
  686. }
  687. /* remove unused entrys */
  688. for (a = init_action_list; a; a = tmp) {
  689. tmp = a->next;
  690. if ((a->action_type & (ONCE | SYSINIT | WAIT)) && a->pid == 0) {
  691. delete_init_action(a);
  692. }
  693. }
  694. run_actions(RESPAWN | ASKFIRST);
  695. }
  696. #endif
  697. int init_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  698. int init_main(int argc UNUSED_PARAM, char **argv)
  699. {
  700. struct init_action *a;
  701. pid_t wpid;
  702. die_sleep = 30 * 24*60*60; /* if xmalloc will ever die... */
  703. if (argv[1] && !strcmp(argv[1], "-q")) {
  704. return kill(1, SIGHUP);
  705. }
  706. if (!DEBUG_INIT) {
  707. /* Expect to be invoked as init with PID=1 or be invoked as linuxrc */
  708. if (getpid() != 1
  709. && (!ENABLE_FEATURE_INITRD || !strstr(applet_name, "linuxrc"))
  710. ) {
  711. bb_show_usage();
  712. }
  713. /* Set up sig handlers -- be sure to
  714. * clear all of these in run() */
  715. signal(SIGQUIT, exec_restart_action);
  716. bb_signals(0
  717. + (1 << SIGUSR1) /* halt */
  718. + (1 << SIGUSR2) /* poweroff */
  719. + (1 << SIGTERM) /* reboot */
  720. , halt_reboot_pwoff);
  721. signal(SIGINT, ctrlaltdel_signal);
  722. signal(SIGCONT, record_signo);
  723. bb_signals(0
  724. + (1 << SIGSTOP)
  725. + (1 << SIGTSTP)
  726. , stop_handler);
  727. /* Turn off rebooting via CTL-ALT-DEL -- we get a
  728. * SIGINT on CAD so we can shut things down gracefully... */
  729. init_reboot(RB_DISABLE_CAD);
  730. }
  731. /* Figure out where the default console should be */
  732. console_init();
  733. set_sane_term();
  734. xchdir("/");
  735. setsid();
  736. /* Make sure environs is set to something sane */
  737. putenv((char *) "HOME=/");
  738. putenv((char *) bb_PATH_root_path);
  739. putenv((char *) "SHELL=/bin/sh");
  740. putenv((char *) "USER=root"); /* needed? why? */
  741. if (argv[1])
  742. xsetenv("RUNLEVEL", argv[1]);
  743. /* Hello world */
  744. message(MAYBE_CONSOLE | L_LOG, "init started: %s", bb_banner);
  745. /* Make sure there is enough memory to do something useful. */
  746. if (ENABLE_SWAPONOFF) {
  747. struct sysinfo info;
  748. if (!sysinfo(&info) &&
  749. (info.mem_unit ? : 1) * (long long)info.totalram < 1024*1024)
  750. {
  751. message(L_CONSOLE, "Low memory, forcing swapon");
  752. /* swapon -a requires /proc typically */
  753. new_init_action(SYSINIT, "mount -t proc proc /proc", "");
  754. /* Try to turn on swap */
  755. new_init_action(SYSINIT, "swapon -a", "");
  756. run_actions(SYSINIT); /* wait and removing */
  757. }
  758. }
  759. /* Check if we are supposed to be in single user mode */
  760. if (argv[1]
  761. && (!strcmp(argv[1], "single") || !strcmp(argv[1], "-s") || LONE_CHAR(argv[1], '1'))
  762. ) {
  763. /* ??? shouldn't we set RUNLEVEL="b" here? */
  764. /* Start a shell on console */
  765. new_init_action(RESPAWN, bb_default_login_shell, "");
  766. } else {
  767. /* Not in single user mode -- see what inittab says */
  768. /* NOTE that if CONFIG_FEATURE_USE_INITTAB is NOT defined,
  769. * then parse_inittab() simply adds in some default
  770. * actions(i.e., runs INIT_SCRIPT and then starts a pair
  771. * of "askfirst" shells */
  772. parse_inittab();
  773. }
  774. #if ENABLE_SELINUX
  775. if (getenv("SELINUX_INIT") == NULL) {
  776. int enforce = 0;
  777. putenv((char*)"SELINUX_INIT=YES");
  778. if (selinux_init_load_policy(&enforce) == 0) {
  779. BB_EXECVP(argv[0], argv);
  780. } else if (enforce > 0) {
  781. /* SELinux in enforcing mode but load_policy failed */
  782. message(L_CONSOLE, "cannot load SELinux Policy. "
  783. "Machine is in enforcing mode. Halting now.");
  784. exit(EXIT_FAILURE);
  785. }
  786. }
  787. #endif /* CONFIG_SELINUX */
  788. /* Make the command line just say "init" - thats all, nothing else */
  789. strncpy(argv[0], "init", strlen(argv[0]));
  790. /* Wipe argv[1]-argv[N] so they don't clutter the ps listing */
  791. while (*++argv)
  792. memset(*argv, 0, strlen(*argv));
  793. /* Now run everything that needs to be run */
  794. /* First run the sysinit command */
  795. run_actions(SYSINIT);
  796. /* Next run anything that wants to block */
  797. run_actions(WAIT);
  798. /* Next run anything to be run only once */
  799. run_actions(ONCE);
  800. /* Redefine SIGHUP to reread /etc/inittab */
  801. #if ENABLE_FEATURE_USE_INITTAB
  802. signal(SIGHUP, reload_signal);
  803. #else
  804. signal(SIGHUP, SIG_IGN);
  805. #endif
  806. /* Now run the looping stuff for the rest of forever */
  807. while (1) {
  808. /* run the respawn/askfirst stuff */
  809. run_actions(RESPAWN | ASKFIRST);
  810. /* Don't consume all CPU time -- sleep a bit */
  811. sleep(1);
  812. /* Wait for any child process to exit */
  813. wpid = wait(NULL);
  814. while (wpid > 0) {
  815. /* Find out who died and clean up their corpse */
  816. for (a = init_action_list; a; a = a->next) {
  817. if (a->pid == wpid) {
  818. /* Set the pid to 0 so that the process gets
  819. * restarted by run_actions() */
  820. a->pid = 0;
  821. message(L_LOG, "process '%s' (pid %d) exited. "
  822. "Scheduling for restart.",
  823. a->command, wpid);
  824. }
  825. }
  826. /* see if anyone else is waiting to be reaped */
  827. wpid = wait_any_nohang(NULL);
  828. }
  829. }
  830. }