init.c 28 KB

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