init.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  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 "busybox.h"
  12. #include <errno.h>
  13. #include <paths.h>
  14. #include <signal.h>
  15. #include <sys/ioctl.h>
  16. #include <sys/wait.h>
  17. #include <sys/reboot.h>
  18. #include "init_shared.h"
  19. #ifdef CONFIG_SYSLOGD
  20. # include <sys/syslog.h>
  21. #endif
  22. #define INIT_BUFFS_SIZE 256
  23. /* From <linux/vt.h> */
  24. struct vt_stat {
  25. unsigned short v_active; /* active vt */
  26. unsigned short v_signal; /* signal to send */
  27. unsigned short v_state; /* vt bitmask */
  28. };
  29. enum { VT_GETSTATE = 0x5603 }; /* get global vt state info */
  30. /* From <linux/serial.h> */
  31. struct serial_struct {
  32. int type;
  33. int line;
  34. unsigned int port;
  35. int irq;
  36. int flags;
  37. int xmit_fifo_size;
  38. int custom_divisor;
  39. int baud_base;
  40. unsigned short close_delay;
  41. char io_type;
  42. char reserved_char[1];
  43. int hub6;
  44. unsigned short closing_wait; /* time to wait before closing */
  45. unsigned short closing_wait2; /* no longer used... */
  46. unsigned char *iomem_base;
  47. unsigned short iomem_reg_shift;
  48. unsigned int port_high;
  49. unsigned long iomap_base; /* cookie passed into ioremap */
  50. int reserved[1];
  51. };
  52. #ifndef _PATH_STDPATH
  53. #define _PATH_STDPATH "/usr/bin:/bin:/usr/sbin:/sbin"
  54. #endif
  55. #if defined CONFIG_FEATURE_INIT_COREDUMPS
  56. /*
  57. * When a file named CORE_ENABLE_FLAG_FILE exists, setrlimit is called
  58. * before processes are spawned to set core file size as unlimited.
  59. * This is for debugging only. Don't use this is production, unless
  60. * you want core dumps lying about....
  61. */
  62. #define CORE_ENABLE_FLAG_FILE "/.init_enable_core"
  63. #include <sys/resource.h>
  64. #endif
  65. #define INITTAB "/etc/inittab" /* inittab file location */
  66. #ifndef INIT_SCRIPT
  67. #define INIT_SCRIPT "/etc/init.d/rcS" /* Default sysinit script. */
  68. #endif
  69. #define MAXENV 16 /* Number of env. vars */
  70. #define CONSOLE_BUFF_SIZE 32
  71. /* Allowed init action types */
  72. #define SYSINIT 0x001
  73. #define RESPAWN 0x002
  74. #define ASKFIRST 0x004
  75. #define WAIT 0x008
  76. #define ONCE 0x010
  77. #define CTRLALTDEL 0x020
  78. #define SHUTDOWN 0x040
  79. #define RESTART 0x080
  80. /* A mapping between "inittab" action name strings and action type codes. */
  81. struct init_action_type {
  82. const char *name;
  83. int action;
  84. };
  85. static const struct init_action_type actions[] = {
  86. {"sysinit", SYSINIT},
  87. {"respawn", RESPAWN},
  88. {"askfirst", ASKFIRST},
  89. {"wait", WAIT},
  90. {"once", ONCE},
  91. {"ctrlaltdel", CTRLALTDEL},
  92. {"shutdown", SHUTDOWN},
  93. {"restart", RESTART},
  94. {0, 0}
  95. };
  96. /* Set up a linked list of init_actions, to be read from inittab */
  97. struct init_action {
  98. pid_t pid;
  99. char command[INIT_BUFFS_SIZE];
  100. char terminal[CONSOLE_BUFF_SIZE];
  101. struct init_action *next;
  102. int action;
  103. };
  104. /* Static variables */
  105. static struct init_action *init_action_list = NULL;
  106. static char console[CONSOLE_BUFF_SIZE] = CONSOLE_DEV;
  107. #ifndef CONFIG_SYSLOGD
  108. static char *log_console = VC_5;
  109. #endif
  110. #if !ENABLE_DEBUG_INIT
  111. static sig_atomic_t got_cont = 0;
  112. #endif
  113. enum {
  114. LOG = 0x1,
  115. CONSOLE = 0x2,
  116. #if defined CONFIG_FEATURE_EXTRA_QUIET
  117. MAYBE_CONSOLE = 0x0,
  118. #else
  119. MAYBE_CONSOLE = CONSOLE,
  120. #endif
  121. #ifndef RB_HALT_SYSTEM
  122. RB_HALT_SYSTEM = 0xcdef0123, /* FIXME: this overflows enum */
  123. RB_ENABLE_CAD = 0x89abcdef,
  124. RB_DISABLE_CAD = 0,
  125. RB_POWER_OFF = 0x4321fedc,
  126. RB_AUTOBOOT = 0x01234567,
  127. #endif
  128. };
  129. static const char * const environment[] = {
  130. "HOME=/",
  131. "PATH=" _PATH_STDPATH,
  132. "SHELL=/bin/sh",
  133. "USER=root",
  134. NULL
  135. };
  136. /* Function prototypes */
  137. static void delete_init_action(struct init_action *a);
  138. static int waitfor(const struct init_action *a, pid_t pid);
  139. #if !ENABLE_DEBUG_INIT
  140. static void shutdown_signal(int sig);
  141. #endif
  142. static void loop_forever(void)
  143. {
  144. while (1)
  145. sleep(1);
  146. }
  147. /* Print a message to the specified device.
  148. * Device may be bitwise-or'd from LOG | CONSOLE */
  149. #if ENABLE_DEBUG_INIT
  150. #define messageD message
  151. #else
  152. #define messageD(...) do {;} while(0);
  153. #endif
  154. static void message(int device, const char *fmt, ...)
  155. __attribute__ ((format(printf, 2, 3)));
  156. static void message(int device, const char *fmt, ...)
  157. {
  158. va_list arguments;
  159. int l;
  160. RESERVE_CONFIG_BUFFER(msg, 1024);
  161. #ifndef CONFIG_SYSLOGD
  162. static int log_fd = -1;
  163. #endif
  164. msg[0] = '\r';
  165. va_start(arguments, fmt);
  166. l = vsnprintf(msg + 1, 1024 - 2, fmt, arguments) + 1;
  167. va_end(arguments);
  168. #ifdef CONFIG_SYSLOGD
  169. /* Log the message to syslogd */
  170. if (device & LOG) {
  171. /* don`t out "\r\n" */
  172. openlog(applet_name, 0, LOG_DAEMON);
  173. syslog(LOG_INFO, "%s", msg + 1);
  174. closelog();
  175. }
  176. msg[l++] = '\n';
  177. msg[l] = 0;
  178. #else
  179. msg[l++] = '\n';
  180. msg[l] = 0;
  181. /* Take full control of the log tty, and never close it.
  182. * It's mine, all mine! Muhahahaha! */
  183. if (log_fd < 0) {
  184. if ((log_fd = device_open(log_console, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0) {
  185. log_fd = -2;
  186. bb_error_msg("bummer, can't write to log on %s!", log_console);
  187. device = CONSOLE;
  188. } else {
  189. fcntl(log_fd, F_SETFD, FD_CLOEXEC);
  190. }
  191. }
  192. if ((device & LOG) && (log_fd >= 0)) {
  193. full_write(log_fd, msg, l);
  194. }
  195. #endif
  196. if (device & CONSOLE) {
  197. int fd = device_open(CONSOLE_DEV,
  198. O_WRONLY | O_NOCTTY | O_NONBLOCK);
  199. /* Always send console messages to /dev/console so people will see them. */
  200. if (fd >= 0) {
  201. full_write(fd, msg, l);
  202. close(fd);
  203. #if ENABLE_DEBUG_INIT
  204. /* all descriptors may be closed */
  205. } else {
  206. bb_error_msg("bummer, can't print: ");
  207. va_start(arguments, fmt);
  208. vfprintf(stderr, fmt, arguments);
  209. va_end(arguments);
  210. #endif
  211. }
  212. }
  213. RELEASE_CONFIG_BUFFER(msg);
  214. }
  215. /* Set terminal settings to reasonable defaults */
  216. static void set_term(void)
  217. {
  218. struct termios tty;
  219. tcgetattr(STDIN_FILENO, &tty);
  220. /* set control chars */
  221. tty.c_cc[VINTR] = 3; /* C-c */
  222. tty.c_cc[VQUIT] = 28; /* C-\ */
  223. tty.c_cc[VERASE] = 127; /* C-? */
  224. tty.c_cc[VKILL] = 21; /* C-u */
  225. tty.c_cc[VEOF] = 4; /* C-d */
  226. tty.c_cc[VSTART] = 17; /* C-q */
  227. tty.c_cc[VSTOP] = 19; /* C-s */
  228. tty.c_cc[VSUSP] = 26; /* C-z */
  229. /* use line dicipline 0 */
  230. tty.c_line = 0;
  231. /* Make it be sane */
  232. tty.c_cflag &= CBAUD | CBAUDEX | CSIZE | CSTOPB | PARENB | PARODD;
  233. tty.c_cflag |= CREAD | HUPCL | CLOCAL;
  234. /* input modes */
  235. tty.c_iflag = ICRNL | IXON | IXOFF;
  236. /* output modes */
  237. tty.c_oflag = OPOST | ONLCR;
  238. /* local modes */
  239. tty.c_lflag =
  240. ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE | IEXTEN;
  241. tcsetattr(STDIN_FILENO, TCSANOW, &tty);
  242. }
  243. static void console_init(void)
  244. {
  245. int fd;
  246. int tried = 0;
  247. struct vt_stat vt;
  248. struct serial_struct sr;
  249. char *s;
  250. if ((s = getenv("CONSOLE")) != NULL || (s = getenv("console")) != NULL) {
  251. safe_strncpy(console, s, sizeof(console));
  252. } else {
  253. /* 2.2 kernels: identify the real console backend and try to use it */
  254. if (ioctl(0, TIOCGSERIAL, &sr) == 0) {
  255. /* this is a serial console */
  256. snprintf(console, sizeof(console) - 1, SC_FORMAT, sr.line);
  257. } else if (ioctl(0, VT_GETSTATE, &vt) == 0) {
  258. /* this is linux virtual tty */
  259. snprintf(console, sizeof(console) - 1, VC_FORMAT, vt.v_active);
  260. } else {
  261. safe_strncpy(console, CONSOLE_DEV, sizeof(console));
  262. tried++;
  263. }
  264. }
  265. while ((fd = open(console, O_RDONLY | O_NONBLOCK)) < 0 && tried < 2) {
  266. /* Can't open selected console -- try
  267. logical system console and VT_MASTER */
  268. safe_strncpy(console, (tried == 0 ? CONSOLE_DEV : CURRENT_VC),
  269. sizeof(console));
  270. tried++;
  271. }
  272. if (fd < 0) {
  273. /* Perhaps we should panic here? */
  274. #ifndef CONFIG_SYSLOGD
  275. log_console =
  276. #endif
  277. safe_strncpy(console, bb_dev_null, sizeof(console));
  278. } else {
  279. s = getenv("TERM");
  280. /* check for serial console */
  281. if (ioctl(fd, TIOCGSERIAL, &sr) == 0) {
  282. /* Force the TERM setting to vt102 for serial console --
  283. * if TERM is set to linux (the default) */
  284. if (s == NULL || strcmp(s, "linux") == 0)
  285. putenv("TERM=vt102");
  286. #ifndef CONFIG_SYSLOGD
  287. log_console = console;
  288. #endif
  289. } else {
  290. if (s == NULL)
  291. putenv("TERM=linux");
  292. }
  293. close(fd);
  294. }
  295. messageD(LOG, "console=%s", console);
  296. }
  297. static void fixup_argv(int argc, char **argv, char *new_argv0)
  298. {
  299. int len;
  300. /* Fix up argv[0] to be certain we claim to be init */
  301. len = strlen(argv[0]);
  302. memset(argv[0], 0, len);
  303. safe_strncpy(argv[0], new_argv0, len + 1);
  304. /* Wipe argv[1]-argv[N] so they don't clutter the ps listing */
  305. len = 1;
  306. while (argc > len) {
  307. memset(argv[len], 0, strlen(argv[len]));
  308. len++;
  309. }
  310. }
  311. /* Open the new terminal device */
  312. static void open_new_terminal(const char * const device, const int fail) {
  313. struct stat sb;
  314. if ((device_open(device, O_RDWR)) < 0) {
  315. if (stat(device, &sb) != 0) {
  316. message(LOG | CONSOLE, "device '%s' does not exist.", device);
  317. } else {
  318. message(LOG | CONSOLE, "Bummer, can't open %s", device);
  319. }
  320. if (fail)
  321. _exit(1);
  322. /* else */
  323. #if !ENABLE_DEBUG_INIT
  324. shutdown_signal(SIGUSR1);
  325. #else
  326. _exit(2);
  327. #endif
  328. }
  329. }
  330. static pid_t run(const struct init_action *a)
  331. {
  332. int i;
  333. pid_t pid;
  334. char *s, *tmpCmd, *cmd[INIT_BUFFS_SIZE], *cmdpath;
  335. char buf[INIT_BUFFS_SIZE + 6]; /* INIT_BUFFS_SIZE+strlen("exec ")+1 */
  336. sigset_t nmask, omask;
  337. static const char press_enter[] =
  338. #ifdef CUSTOMIZED_BANNER
  339. #include CUSTOMIZED_BANNER
  340. #endif
  341. "\nPlease press Enter to activate this console. ";
  342. /* Block sigchild while forking. */
  343. sigemptyset(&nmask);
  344. sigaddset(&nmask, SIGCHLD);
  345. sigprocmask(SIG_BLOCK, &nmask, &omask);
  346. if ((pid = fork()) == 0) {
  347. /* Clean up */
  348. close(0);
  349. close(1);
  350. close(2);
  351. sigprocmask(SIG_SETMASK, &omask, NULL);
  352. /* Reset signal handlers that were set by the parent process */
  353. signal(SIGUSR1, SIG_DFL);
  354. signal(SIGUSR2, SIG_DFL);
  355. signal(SIGINT, SIG_DFL);
  356. signal(SIGTERM, SIG_DFL);
  357. signal(SIGHUP, SIG_DFL);
  358. signal(SIGQUIT, SIG_DFL);
  359. signal(SIGCONT, SIG_DFL);
  360. signal(SIGSTOP, SIG_DFL);
  361. signal(SIGTSTP, SIG_DFL);
  362. /* Create a new session and make ourself the process
  363. * group leader */
  364. setsid();
  365. /* Open the new terminal device */
  366. open_new_terminal(a->terminal, 1);
  367. /* Make sure the terminal will act fairly normal for us */
  368. set_term();
  369. /* Setup stdout, stderr for the new process so
  370. * they point to the supplied terminal */
  371. dup(0);
  372. dup(0);
  373. /* If the init Action requires us to wait, then force the
  374. * supplied terminal to be the controlling tty. */
  375. if (a->action & (SYSINIT | WAIT | CTRLALTDEL | SHUTDOWN | RESTART)) {
  376. /* Now fork off another process to just hang around */
  377. if ((pid = fork()) < 0) {
  378. message(LOG | CONSOLE, "Can't fork!");
  379. _exit(1);
  380. }
  381. if (pid > 0) {
  382. /* We are the parent -- wait till the child is done */
  383. signal(SIGINT, SIG_IGN);
  384. signal(SIGTSTP, SIG_IGN);
  385. signal(SIGQUIT, SIG_IGN);
  386. signal(SIGCHLD, SIG_DFL);
  387. waitfor(NULL, pid);
  388. /* See if stealing the controlling tty back is necessary */
  389. if (tcgetpgrp(0) != getpid())
  390. _exit(0);
  391. /* Use a temporary process to steal the controlling tty. */
  392. if ((pid = fork()) < 0) {
  393. message(LOG | CONSOLE, "Can't fork!");
  394. _exit(1);
  395. }
  396. if (pid == 0) {
  397. setsid();
  398. ioctl(0, TIOCSCTTY, 1);
  399. _exit(0);
  400. }
  401. waitfor(NULL, pid);
  402. _exit(0);
  403. }
  404. /* Now fall though to actually execute things */
  405. }
  406. /* See if any special /bin/sh requiring characters are present */
  407. if (strpbrk(a->command, "~`!$^&*()=|\\{}[];\"'<>?") != NULL) {
  408. cmd[0] = (char *)DEFAULT_SHELL;
  409. cmd[1] = "-c";
  410. cmd[2] = strcat(strcpy(buf, "exec "), a->command);
  411. cmd[3] = NULL;
  412. } else {
  413. /* Convert command (char*) into cmd (char**, one word per string) */
  414. strcpy(buf, a->command);
  415. s = buf;
  416. for (tmpCmd = buf, i = 0; (tmpCmd = strsep(&s, " \t")) != NULL;) {
  417. if (*tmpCmd != '\0') {
  418. cmd[i] = tmpCmd;
  419. i++;
  420. }
  421. }
  422. cmd[i] = NULL;
  423. }
  424. cmdpath = cmd[0];
  425. /*
  426. Interactive shells want to see a dash in argv[0]. This
  427. typically is handled by login, argv will be setup this
  428. way if a dash appears at the front of the command path
  429. (like "-/bin/sh").
  430. */
  431. if (*cmdpath == '-') {
  432. /* skip over the dash */
  433. ++cmdpath;
  434. /* find the last component in the command pathname */
  435. s = bb_get_last_path_component(cmdpath);
  436. /* make a new argv[0] */
  437. if ((cmd[0] = malloc(strlen(s) + 2)) == NULL) {
  438. message(LOG | CONSOLE, bb_msg_memory_exhausted);
  439. cmd[0] = cmdpath;
  440. } else {
  441. cmd[0][0] = '-';
  442. strcpy(cmd[0] + 1, s);
  443. }
  444. #ifdef CONFIG_FEATURE_INIT_SCTTY
  445. /* Establish this process as session leader and
  446. * (attempt) to make the tty (if any) a controlling tty.
  447. */
  448. (void) setsid();
  449. (void) ioctl(0, TIOCSCTTY, 0/*don't steal it*/);
  450. #endif
  451. }
  452. #if !defined(__UCLIBC__) || defined(__ARCH_HAS_MMU__)
  453. if (a->action & ASKFIRST) {
  454. char c;
  455. /*
  456. * Save memory by not exec-ing anything large (like a shell)
  457. * before the user wants it. This is critical if swap is not
  458. * enabled and the system has low memory. Generally this will
  459. * be run on the second virtual console, and the first will
  460. * be allowed to start a shell or whatever an init script
  461. * specifies.
  462. */
  463. messageD(LOG, "Waiting for enter to start '%s'"
  464. "(pid %d, terminal %s)\n",
  465. cmdpath, getpid(), a->terminal);
  466. full_write(1, press_enter, sizeof(press_enter) - 1);
  467. while(read(0, &c, 1) == 1 && c != '\n')
  468. ;
  469. }
  470. #endif
  471. /* Log the process name and args */
  472. message(LOG, "Starting pid %d, console %s: '%s'",
  473. getpid(), a->terminal, cmdpath);
  474. #if defined CONFIG_FEATURE_INIT_COREDUMPS
  475. {
  476. struct stat sb;
  477. if (stat(CORE_ENABLE_FLAG_FILE, &sb) == 0) {
  478. struct rlimit limit;
  479. limit.rlim_cur = RLIM_INFINITY;
  480. limit.rlim_max = RLIM_INFINITY;
  481. setrlimit(RLIMIT_CORE, &limit);
  482. }
  483. }
  484. #endif
  485. /* Now run it. The new program will take over this PID,
  486. * so nothing further in init.c should be run. */
  487. execv(cmdpath, cmd);
  488. /* We're still here? Some error happened. */
  489. message(LOG | CONSOLE, "Bummer, cannot run '%s': %m", cmdpath);
  490. _exit(-1);
  491. }
  492. sigprocmask(SIG_SETMASK, &omask, NULL);
  493. return pid;
  494. }
  495. static int waitfor(const struct init_action *a, pid_t pid)
  496. {
  497. int runpid;
  498. int status, wpid;
  499. runpid = (NULL == a)? pid : run(a);
  500. while (1) {
  501. wpid = waitpid(runpid,&status,0);
  502. if (wpid == runpid)
  503. break;
  504. if (wpid == -1 && errno == ECHILD) {
  505. /* we missed its termination */
  506. break;
  507. }
  508. /* FIXME other errors should maybe trigger an error, but allow
  509. * the program to continue */
  510. }
  511. return wpid;
  512. }
  513. /* Run all commands of a particular type */
  514. static void run_actions(int action)
  515. {
  516. struct init_action *a, *tmp;
  517. for (a = init_action_list; a; a = tmp) {
  518. tmp = a->next;
  519. if (a->action == action) {
  520. if (access(a->terminal, R_OK | W_OK)) {
  521. delete_init_action(a);
  522. } else if (a->action & (SYSINIT | WAIT | CTRLALTDEL | SHUTDOWN | RESTART)) {
  523. waitfor(a, 0);
  524. delete_init_action(a);
  525. } else if (a->action & ONCE) {
  526. run(a);
  527. delete_init_action(a);
  528. } else if (a->action & (RESPAWN | ASKFIRST)) {
  529. /* Only run stuff with pid==0. If they have
  530. * a pid, that means it is still running */
  531. if (a->pid == 0) {
  532. a->pid = run(a);
  533. }
  534. }
  535. }
  536. }
  537. }
  538. #if !ENABLE_DEBUG_INIT
  539. static void init_reboot(unsigned long magic)
  540. {
  541. pid_t pid;
  542. /* We have to fork here, since the kernel calls do_exit(0) in
  543. * linux/kernel/sys.c, which can cause the machine to panic when
  544. * the init process is killed.... */
  545. if ((pid = fork()) == 0) {
  546. reboot(magic);
  547. _exit(0);
  548. }
  549. waitpid (pid, NULL, 0);
  550. }
  551. static void shutdown_system(void)
  552. {
  553. sigset_t block_signals;
  554. /* run everything to be run at "shutdown". This is done _prior_
  555. * to killing everything, in case people wish to use scripts to
  556. * shut things down gracefully... */
  557. run_actions(SHUTDOWN);
  558. /* first disable all our signals */
  559. sigemptyset(&block_signals);
  560. sigaddset(&block_signals, SIGHUP);
  561. sigaddset(&block_signals, SIGQUIT);
  562. sigaddset(&block_signals, SIGCHLD);
  563. sigaddset(&block_signals, SIGUSR1);
  564. sigaddset(&block_signals, SIGUSR2);
  565. sigaddset(&block_signals, SIGINT);
  566. sigaddset(&block_signals, SIGTERM);
  567. sigaddset(&block_signals, SIGCONT);
  568. sigaddset(&block_signals, SIGSTOP);
  569. sigaddset(&block_signals, SIGTSTP);
  570. sigprocmask(SIG_BLOCK, &block_signals, NULL);
  571. /* Allow Ctrl-Alt-Del to reboot system. */
  572. init_reboot(RB_ENABLE_CAD);
  573. message(CONSOLE | LOG, "The system is going down NOW !!");
  574. sync();
  575. /* Send signals to every process _except_ pid 1 */
  576. message(CONSOLE | LOG, init_sending_format, "TERM");
  577. kill(-1, SIGTERM);
  578. sleep(1);
  579. sync();
  580. message(CONSOLE | LOG, init_sending_format, "KILL");
  581. kill(-1, SIGKILL);
  582. sleep(1);
  583. sync();
  584. }
  585. static void exec_signal(int sig ATTRIBUTE_UNUSED)
  586. {
  587. struct init_action *a, *tmp;
  588. sigset_t unblock_signals;
  589. for (a = init_action_list; a; a = tmp) {
  590. tmp = a->next;
  591. if (a->action & RESTART) {
  592. shutdown_system();
  593. /* unblock all signals, blocked in shutdown_system() */
  594. sigemptyset(&unblock_signals);
  595. sigaddset(&unblock_signals, SIGHUP);
  596. sigaddset(&unblock_signals, SIGQUIT);
  597. sigaddset(&unblock_signals, SIGCHLD);
  598. sigaddset(&unblock_signals, SIGUSR1);
  599. sigaddset(&unblock_signals, SIGUSR2);
  600. sigaddset(&unblock_signals, SIGINT);
  601. sigaddset(&unblock_signals, SIGTERM);
  602. sigaddset(&unblock_signals, SIGCONT);
  603. sigaddset(&unblock_signals, SIGSTOP);
  604. sigaddset(&unblock_signals, SIGTSTP);
  605. sigprocmask(SIG_UNBLOCK, &unblock_signals, NULL);
  606. /* Close whatever files are open. */
  607. close(0);
  608. close(1);
  609. close(2);
  610. /* Open the new terminal device */
  611. open_new_terminal(a->terminal, 0);
  612. /* Make sure the terminal will act fairly normal for us */
  613. set_term();
  614. /* Setup stdout, stderr on the supplied terminal */
  615. dup(0);
  616. dup(0);
  617. messageD(CONSOLE | LOG, "Trying to re-exec %s", a->command);
  618. execl(a->command, a->command, NULL);
  619. message(CONSOLE | LOG, "exec of '%s' failed: %m",
  620. a->command);
  621. sync();
  622. sleep(2);
  623. init_reboot(RB_HALT_SYSTEM);
  624. loop_forever();
  625. }
  626. }
  627. }
  628. static void shutdown_signal(int sig)
  629. {
  630. char *m;
  631. int rb;
  632. shutdown_system();
  633. if (sig == SIGTERM) {
  634. m = "reboot";
  635. rb = RB_AUTOBOOT;
  636. } else if (sig == SIGUSR2) {
  637. m = "poweroff";
  638. rb = RB_POWER_OFF;
  639. } else {
  640. m = "halt";
  641. rb = RB_HALT_SYSTEM;
  642. }
  643. message(CONSOLE | LOG, "Requesting system %s.", m);
  644. sync();
  645. /* allow time for last message to reach serial console */
  646. sleep(2);
  647. init_reboot(rb);
  648. loop_forever();
  649. }
  650. static void ctrlaltdel_signal(int sig ATTRIBUTE_UNUSED)
  651. {
  652. run_actions(CTRLALTDEL);
  653. }
  654. /* The SIGSTOP & SIGTSTP handler */
  655. static void stop_handler(int sig ATTRIBUTE_UNUSED)
  656. {
  657. int saved_errno = errno;
  658. got_cont = 0;
  659. while (!got_cont)
  660. pause();
  661. got_cont = 0;
  662. errno = saved_errno;
  663. }
  664. /* The SIGCONT handler */
  665. static void cont_handler(int sig ATTRIBUTE_UNUSED)
  666. {
  667. got_cont = 1;
  668. }
  669. #endif /* ! ENABLE_DEBUG_INIT */
  670. static void new_init_action(int action, const char *command, const char *cons)
  671. {
  672. struct init_action *new_action, *a, *last;
  673. if (*cons == '\0')
  674. cons = console;
  675. if (strcmp(cons, bb_dev_null) == 0 && (action & ASKFIRST))
  676. return;
  677. new_action = calloc((size_t) (1), sizeof(struct init_action));
  678. if (!new_action) {
  679. message(LOG | CONSOLE, "Memory allocation failure");
  680. loop_forever();
  681. }
  682. /* Append to the end of the list */
  683. for (a = last = init_action_list; a; a = a->next) {
  684. /* don't enter action if it's already in the list,
  685. * but do overwrite existing actions */
  686. if ((strcmp(a->command, command) == 0) &&
  687. (strcmp(a->terminal, cons) ==0)) {
  688. a->action = action;
  689. free(new_action);
  690. return;
  691. }
  692. last = a;
  693. }
  694. if (last) {
  695. last->next = new_action;
  696. } else {
  697. init_action_list = new_action;
  698. }
  699. strcpy(new_action->command, command);
  700. new_action->action = action;
  701. strcpy(new_action->terminal, cons);
  702. messageD(LOG|CONSOLE, "command='%s' action='%d' terminal='%s'\n",
  703. new_action->command, new_action->action, new_action->terminal);
  704. }
  705. static void delete_init_action(struct init_action *action)
  706. {
  707. struct init_action *a, *b = NULL;
  708. for (a = init_action_list; a; b = a, a = a->next) {
  709. if (a == action) {
  710. if (b == NULL) {
  711. init_action_list = a->next;
  712. } else {
  713. b->next = a->next;
  714. }
  715. free(a);
  716. break;
  717. }
  718. }
  719. }
  720. /* NOTE that if CONFIG_FEATURE_USE_INITTAB is NOT defined,
  721. * then parse_inittab() simply adds in some default
  722. * actions(i.e., runs INIT_SCRIPT and then starts a pair
  723. * of "askfirst" shells). If CONFIG_FEATURE_USE_INITTAB
  724. * _is_ defined, but /etc/inittab is missing, this
  725. * results in the same set of default behaviors.
  726. */
  727. static void parse_inittab(void)
  728. {
  729. #ifdef CONFIG_FEATURE_USE_INITTAB
  730. FILE *file;
  731. char buf[INIT_BUFFS_SIZE], lineAsRead[INIT_BUFFS_SIZE];
  732. char tmpConsole[CONSOLE_BUFF_SIZE];
  733. char *id, *runlev, *action, *command, *eol;
  734. const struct init_action_type *a = actions;
  735. file = fopen(INITTAB, "r");
  736. if (file == NULL) {
  737. /* No inittab file -- set up some default behavior */
  738. #endif
  739. /* Reboot on Ctrl-Alt-Del */
  740. new_init_action(CTRLALTDEL, "/sbin/reboot", "");
  741. /* Umount all filesystems on halt/reboot */
  742. new_init_action(SHUTDOWN, "/bin/umount -a -r", "");
  743. /* Swapoff on halt/reboot */
  744. if(ENABLE_SWAPONOFF) new_init_action(SHUTDOWN, "/sbin/swapoff -a", "");
  745. /* Prepare to restart init when a HUP is received */
  746. new_init_action(RESTART, "/sbin/init", "");
  747. /* Askfirst shell on tty1-4 */
  748. new_init_action(ASKFIRST, bb_default_login_shell, "");
  749. new_init_action(ASKFIRST, bb_default_login_shell, VC_2);
  750. new_init_action(ASKFIRST, bb_default_login_shell, VC_3);
  751. new_init_action(ASKFIRST, bb_default_login_shell, VC_4);
  752. /* sysinit */
  753. new_init_action(SYSINIT, INIT_SCRIPT, "");
  754. return;
  755. #ifdef CONFIG_FEATURE_USE_INITTAB
  756. }
  757. while (fgets(buf, INIT_BUFFS_SIZE, file) != NULL) {
  758. /* Skip leading spaces */
  759. for (id = buf; *id == ' ' || *id == '\t'; id++);
  760. /* Skip the line if it's a comment */
  761. if (*id == '#' || *id == '\n')
  762. continue;
  763. /* Trim the trailing \n */
  764. eol = strrchr(id, '\n');
  765. if (eol != NULL)
  766. *eol = '\0';
  767. /* Keep a copy around for posterity's sake (and error msgs) */
  768. strcpy(lineAsRead, buf);
  769. /* Separate the ID field from the runlevels */
  770. runlev = strchr(id, ':');
  771. if (runlev == NULL || *(runlev + 1) == '\0') {
  772. message(LOG | CONSOLE, "Bad inittab entry: %s", lineAsRead);
  773. continue;
  774. } else {
  775. *runlev = '\0';
  776. ++runlev;
  777. }
  778. /* Separate the runlevels from the action */
  779. action = strchr(runlev, ':');
  780. if (action == NULL || *(action + 1) == '\0') {
  781. message(LOG | CONSOLE, "Bad inittab entry: %s", lineAsRead);
  782. continue;
  783. } else {
  784. *action = '\0';
  785. ++action;
  786. }
  787. /* Separate the action from the command */
  788. command = strchr(action, ':');
  789. if (command == NULL || *(command + 1) == '\0') {
  790. message(LOG | CONSOLE, "Bad inittab entry: %s", lineAsRead);
  791. continue;
  792. } else {
  793. *command = '\0';
  794. ++command;
  795. }
  796. /* Ok, now process it */
  797. for (a = actions; a->name != 0; a++) {
  798. if (strcmp(a->name, action) == 0) {
  799. if (*id != '\0') {
  800. if(strncmp(id, "/dev/", 5) == 0)
  801. id += 5;
  802. strcpy(tmpConsole, "/dev/");
  803. safe_strncpy(tmpConsole + 5, id,
  804. CONSOLE_BUFF_SIZE - 5);
  805. id = tmpConsole;
  806. }
  807. new_init_action(a->action, command, id);
  808. break;
  809. }
  810. }
  811. if (a->name == 0) {
  812. /* Choke on an unknown action */
  813. message(LOG | CONSOLE, "Bad inittab entry: %s", lineAsRead);
  814. }
  815. }
  816. fclose(file);
  817. return;
  818. #endif /* CONFIG_FEATURE_USE_INITTAB */
  819. }
  820. #ifdef CONFIG_FEATURE_USE_INITTAB
  821. static void reload_signal(int sig ATTRIBUTE_UNUSED)
  822. {
  823. struct init_action *a, *tmp;
  824. message(LOG, "Reloading /etc/inittab");
  825. /* disable old entrys */
  826. for (a = init_action_list; a; a = a->next ) {
  827. a->action = ONCE;
  828. }
  829. parse_inittab();
  830. /* remove unused entrys */
  831. for (a = init_action_list; a; a = tmp) {
  832. tmp = a->next;
  833. if (a->action & (ONCE | SYSINIT | WAIT ) &&
  834. a->pid == 0 ) {
  835. delete_init_action(a);
  836. }
  837. }
  838. run_actions(RESPAWN);
  839. return;
  840. }
  841. #endif /* CONFIG_FEATURE_USE_INITTAB */
  842. int init_main(int argc, char **argv)
  843. {
  844. struct init_action *a;
  845. pid_t wpid;
  846. if (argc > 1 && !strcmp(argv[1], "-q")) {
  847. return kill(1,SIGHUP);
  848. }
  849. #if !ENABLE_DEBUG_INIT
  850. /* Expect to be invoked as init with PID=1 or be invoked as linuxrc */
  851. if (getpid() != 1 &&
  852. (!ENABLE_FEATURE_INITRD || !strstr(applet_name, "linuxrc")))
  853. {
  854. bb_show_usage();
  855. }
  856. /* Set up sig handlers -- be sure to
  857. * clear all of these in run() */
  858. signal(SIGHUP, exec_signal);
  859. signal(SIGQUIT, exec_signal);
  860. signal(SIGUSR1, shutdown_signal);
  861. signal(SIGUSR2, shutdown_signal);
  862. signal(SIGINT, ctrlaltdel_signal);
  863. signal(SIGTERM, shutdown_signal);
  864. signal(SIGCONT, cont_handler);
  865. signal(SIGSTOP, stop_handler);
  866. signal(SIGTSTP, stop_handler);
  867. /* Turn off rebooting via CTL-ALT-DEL -- we get a
  868. * SIGINT on CAD so we can shut things down gracefully... */
  869. init_reboot(RB_DISABLE_CAD);
  870. #endif
  871. /* Figure out where the default console should be */
  872. console_init();
  873. /* Close whatever files are open, and reset the console. */
  874. close(0);
  875. close(1);
  876. close(2);
  877. if (device_open(console, O_RDWR | O_NOCTTY) == 0) {
  878. set_term();
  879. close(0);
  880. }
  881. chdir("/");
  882. setsid();
  883. {
  884. const char * const *e;
  885. /* Make sure environs is set to something sane */
  886. for(e = environment; *e; e++)
  887. putenv((char *) *e);
  888. }
  889. if (argc > 1) setenv("RUNLEVEL", argv[1], 1);
  890. /* Hello world */
  891. message(MAYBE_CONSOLE | LOG, "init started: %s", bb_msg_full_version);
  892. /* Make sure there is enough memory to do something useful. */
  893. if (ENABLE_SWAPONOFF) {
  894. struct sysinfo info;
  895. if (!sysinfo(&info) &&
  896. (info.mem_unit ? : 1) * (long long)info.totalram < 1024*1024)
  897. {
  898. message(CONSOLE,"Low memory: forcing swapon.");
  899. /* swapon -a requires /proc typically */
  900. new_init_action(SYSINIT, "/bin/mount -t proc proc /proc", "");
  901. /* Try to turn on swap */
  902. new_init_action(SYSINIT, "/sbin/swapon -a", "");
  903. run_actions(SYSINIT); /* wait and removing */
  904. }
  905. }
  906. /* Check if we are supposed to be in single user mode */
  907. if (argc > 1 && (!strcmp(argv[1], "single") ||
  908. !strcmp(argv[1], "-s") || !strcmp(argv[1], "1"))) {
  909. /* Start a shell on console */
  910. new_init_action(RESPAWN, bb_default_login_shell, "");
  911. } else {
  912. /* Not in single user mode -- see what inittab says */
  913. /* NOTE that if CONFIG_FEATURE_USE_INITTAB is NOT defined,
  914. * then parse_inittab() simply adds in some default
  915. * actions(i.e., runs INIT_SCRIPT and then starts a pair
  916. * of "askfirst" shells */
  917. parse_inittab();
  918. }
  919. #ifdef CONFIG_SELINUX
  920. if (getenv("SELINUX_INIT") == NULL) {
  921. int enforce = 0;
  922. putenv("SELINUX_INIT=YES");
  923. if (selinux_init_load_policy(&enforce) == 0) {
  924. execv(argv[0], argv);
  925. } else if (enforce > 0) {
  926. /* SELinux in enforcing mode but load_policy failed */
  927. /* At this point, we probably can't open /dev/console, so log() won't work */
  928. message(CONSOLE,"Unable to load SELinux Policy. Machine is in enforcing mode. Halting now.");
  929. exit(1);
  930. }
  931. }
  932. #endif /* CONFIG_SELINUX */
  933. /* Make the command line just say "init" -- thats all, nothing else */
  934. fixup_argv(argc, argv, "init");
  935. /* Now run everything that needs to be run */
  936. /* First run the sysinit command */
  937. run_actions(SYSINIT);
  938. /* Next run anything that wants to block */
  939. run_actions(WAIT);
  940. /* Next run anything to be run only once */
  941. run_actions(ONCE);
  942. #ifdef CONFIG_FEATURE_USE_INITTAB
  943. /* Redefine SIGHUP to reread /etc/inittab */
  944. signal(SIGHUP, reload_signal);
  945. #else
  946. signal(SIGHUP, SIG_IGN);
  947. #endif /* CONFIG_FEATURE_USE_INITTAB */
  948. /* Now run the looping stuff for the rest of forever */
  949. while (1) {
  950. /* run the respawn stuff */
  951. run_actions(RESPAWN);
  952. /* run the askfirst stuff */
  953. run_actions(ASKFIRST);
  954. /* Don't consume all CPU time -- sleep a bit */
  955. sleep(1);
  956. /* Wait for a child process to exit */
  957. wpid = wait(NULL);
  958. while (wpid > 0) {
  959. /* Find out who died and clean up their corpse */
  960. for (a = init_action_list; a; a = a->next) {
  961. if (a->pid == wpid) {
  962. /* Set the pid to 0 so that the process gets
  963. * restarted by run_actions() */
  964. a->pid = 0;
  965. message(LOG, "Process '%s' (pid %d) exited. "
  966. "Scheduling it for restart.",
  967. a->command, wpid);
  968. }
  969. }
  970. /* see if anyone else is waiting to be reaped */
  971. wpid = waitpid(-1, NULL, WNOHANG);
  972. }
  973. }
  974. }