3
0

init.c 30 KB

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