init.c 26 KB

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