3
0

init.c 24 KB

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