]>
git.wh0rd.org - sysvinit.git/blob - src/init.c
2 * Init A System-V Init Clone.
5 * init [0123456SsQqAaBbCc]
6 * telinit [0123456SsQqAaBbCc]
8 * Version: @(#)init.c 2.86 30-Jul-2004 miquels@cistron.nl
10 #define VERSION "2.89"
11 #define DATE "26-Mar-2010"
13 * This file is part of the sysvinit suite,
14 * Copyright (C) 1991-2004 Miquel van Smoorenburg.
16 * This program is free software; you can redistribute it and/or modify
17 * it under the terms of the GNU General Public License as published by
18 * the Free Software Foundation; either version 2 of the License, or
19 * (at your option) any later version.
21 * This program is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 * GNU General Public License for more details.
26 * You should have received a copy of the GNU General Public License
27 * along with this program; if not, write to the Free Software
28 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
32 #include <sys/types.h>
34 #include <sys/ioctl.h>
39 #include <sys/resource.h>
52 #include <sys/ttydefaults.h>
53 #include <sys/syslog.h>
57 # include <selinux/selinux.h>
63 # define STACK_DEBUG 1
64 # if (__GLIBC__ == 2 && __GLIBC_MINOR__ == 0)
65 /* Only glibc 2.0 needs this */
66 # include <sigcontext.h>
67 # elif ( __GLIBC__ > 2) && ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 1))
68 # include <bits/sigcontext.h>
80 # define SIGPWR SIGUSR2
90 /* Set a signal handler. */
91 #define SETSIG(sa, sig, fun, flags) \
93 memset(&sa, 0, sizeof(sa)); \
94 sa.sa_handler = fun; \
95 sa.sa_flags = flags; \
96 sigemptyset(&sa.sa_mask); \
97 sigaction(sig, &sa, NULL); \
100 /* Version information */
101 char *Version
= "@(#) init " VERSION
" " DATE
" miquels@cistron.nl";
102 char *bootmsg
= "version " VERSION
" %s";
103 #define E_VERSION "INIT_VERSION=sysvinit-" VERSION
105 CHILD
*family
= NULL
; /* The linked list of all entries */
106 CHILD
*newFamily
= NULL
; /* The list after inittab re-read */
108 CHILD ch_emerg
= { /* Emergency shell */
118 char runlevel
= 'S'; /* The current run level */
119 char thislevel
= 'S'; /* The current runlevel */
120 char prevlevel
= 'N'; /* Previous runlevel */
121 int dfl_level
= 0; /* Default runlevel */
122 sig_atomic_t got_cont
= 0; /* Set if we received the SIGCONT signal */
123 sig_atomic_t got_signals
; /* Set if we received a signal. */
124 int emerg_shell
= 0; /* Start emergency shell? */
125 int wrote_wtmp_reboot
= 1; /* Set when we wrote the reboot record */
126 int wrote_utmp_reboot
= 1; /* Set when we wrote the reboot record */
127 int wrote_wtmp_rlevel
= 1; /* Set when we wrote the runlevel record */
128 int wrote_utmp_rlevel
= 1; /* Set when we wrote the runlevel record */
129 int sltime
= 5; /* Sleep time between TERM and KILL */
130 char *argv0
; /* First arguments; show up in ps listing */
131 int maxproclen
; /* Maximal length of argv[0] with \0 */
132 struct utmp utproto
; /* Only used for sizeof(utproto.ut_id) */
133 char *console_dev
; /* Console device. */
134 int pipe_fd
= -1; /* /dev/initctl */
135 int did_boot
= 0; /* Did we already do BOOT* stuff? */
136 int main(int, char **);
138 /* Used by re-exec part */
139 int reload
= 0; /* Should we do initialization stuff? */
140 char *myname
="/sbin/init"; /* What should we exec */
141 int oops_error
; /* Used by some of the re-exec code. */
142 const char *Signature
= "12567362"; /* Signature for re-exec fd */
144 /* Macro to see if this is a special action */
145 #define ISPOWER(i) ((i) == POWERWAIT || (i) == POWERFAIL || \
146 (i) == POWEROKWAIT || (i) == POWERFAILNOW || \
149 /* ascii values for the `action' field. */
154 { "respawn", RESPAWN
},
158 { "bootwait", BOOTWAIT
},
159 { "powerfail", POWERFAIL
},
160 { "powerfailnow",POWERFAILNOW
},
161 { "powerwait", POWERWAIT
},
162 { "powerokwait", POWEROKWAIT
},
163 { "ctrlaltdel", CTRLALTDEL
},
165 { "ondemand", ONDEMAND
},
166 { "initdefault", INITDEFAULT
},
167 { "sysinit", SYSINIT
},
168 { "kbrequest", KBREQUEST
},
173 * State parser token table (see receive_state)
186 { "CMD", C_PROCESS
},
189 { "-RL", D_RUNLEVEL
},
190 { "-TL", D_THISLEVEL
},
191 { "-PL", D_PREVLEVEL
},
192 { "-SI", D_GOTSIGN
},
193 { "-WR", D_WROTE_WTMP_REBOOT
},
194 { "-WU", D_WROTE_UTMP_REBOOT
},
196 { "-DB", D_DIDBOOT
},
197 { "-LW", D_WROTE_WTMP_RLEVEL
},
198 { "-LU", D_WROTE_UTMP_RLEVEL
},
212 #define NR_EXTRA_ENV 16
213 char *extra_env
[NR_EXTRA_ENV
];
217 * Sleep a number of seconds.
219 * This only works correctly because the linux select updates
220 * the elapsed time in the struct timeval passed to select!
223 void do_sleep(int sec
)
230 while(select(0, NULL
, NULL
, NULL
, &tv
) < 0 && errno
== EINTR
)
236 * Non-failing allocation routines (init cannot fail).
239 void *imalloc(size_t size
)
243 while ((m
= malloc(size
)) == NULL
) {
244 initlog(L_VB
, "out of memory");
252 char *istrdup(const char *s
)
265 * Send the state info of the previous running init to
266 * the new one, in a version-independant way.
269 void send_state(int fd
)
277 fprintf(fp
, "VER%s\n", Version
);
278 fprintf(fp
, "-RL%c\n", runlevel
);
279 fprintf(fp
, "-TL%c\n", thislevel
);
280 fprintf(fp
, "-PL%c\n", prevlevel
);
281 fprintf(fp
, "-SI%u\n", got_signals
);
282 fprintf(fp
, "-WR%d\n", wrote_wtmp_reboot
);
283 fprintf(fp
, "-WU%d\n", wrote_utmp_reboot
);
284 fprintf(fp
, "-ST%d\n", sltime
);
285 fprintf(fp
, "-DB%d\n", did_boot
);
287 for (p
= family
; p
; p
= p
->next
) {
288 fprintf(fp
, "REC%s\n", p
->id
);
289 fprintf(fp
, "LEV%s\n", p
->rlevel
);
290 for (i
= 0, val
= p
->flags
; flags
[i
].mask
; i
++)
291 if (val
& flags
[i
].mask
) {
292 val
&= ~flags
[i
].mask
;
293 fprintf(fp
, "FL %s\n",flags
[i
].name
);
295 fprintf(fp
, "PID%d\n",p
->pid
);
296 fprintf(fp
, "EXS%u\n",p
->exstat
);
297 for(i
= 0; actions
[i
].act
; i
++)
298 if (actions
[i
].act
== p
->action
) {
299 fprintf(fp
, "AC %s\n", actions
[i
].name
);
302 fprintf(fp
, "CMD%s\n", p
->process
);
303 fprintf(fp
, "EOR\n");
305 fprintf(fp
, "END\n");
310 * Read a string from a file descriptor.
311 * FIXME: why not use fgets() ?
313 static int get_string(char *p
, int size
, FILE *f
)
317 while ((c
= getc(f
)) != EOF
&& c
!= '\n') {
322 return (c
!= EOF
) && (size
> 0);
326 * Read trailing data from the state pipe until we see a newline.
328 static int get_void(FILE *f
)
332 while ((c
= getc(f
)) != EOF
&& c
!= '\n')
339 * Read the next "command" from the state pipe.
341 static int get_cmd(FILE *f
)
346 if (fread(cmd
, 1, sizeof(cmd
) - 1, f
) != sizeof(cmd
) - 1)
349 for(i
= 0; cmds
[i
].cmd
&& strcmp(cmds
[i
].name
, cmd
) != 0; i
++)
355 * Read a CHILD * from the state pipe.
357 static CHILD
*get_record(FILE *f
)
365 switch (cmd
= get_cmd(f
)) {
375 fscanf(f
, "%c\n", &runlevel
);
378 fscanf(f
, "%c\n", &thislevel
);
381 fscanf(f
, "%c\n", &prevlevel
);
384 fscanf(f
, "%u\n", &got_signals
);
386 case D_WROTE_WTMP_REBOOT
:
387 fscanf(f
, "%d\n", &wrote_wtmp_reboot
);
389 case D_WROTE_UTMP_REBOOT
:
390 fscanf(f
, "%d\n", &wrote_utmp_reboot
);
393 fscanf(f
, "%d\n", &sltime
);
396 fscanf(f
, "%d\n", &did_boot
);
398 case D_WROTE_WTMP_RLEVEL
:
399 fscanf(f
, "%d\n", &wrote_wtmp_rlevel
);
401 case D_WROTE_UTMP_RLEVEL
:
402 fscanf(f
, "%d\n", &wrote_utmp_rlevel
);
405 if (cmd
> 0 || cmd
== C_EOF
) {
410 } while (cmd
!= C_REC
);
412 p
= imalloc(sizeof(CHILD
));
413 get_string(p
->id
, sizeof(p
->id
), f
);
415 do switch(cmd
= get_cmd(f
)) {
421 fscanf(f
, "%d\n", &(p
->pid
));
424 fscanf(f
, "%u\n", &(p
->exstat
));
427 get_string(p
->rlevel
, sizeof(p
->rlevel
), f
);
430 get_string(p
->process
, sizeof(p
->process
), f
);
433 get_string(s
, sizeof(s
), f
);
434 for(i
= 0; flags
[i
].name
; i
++) {
435 if (strcmp(flags
[i
].name
,s
) == 0)
438 p
->flags
|= flags
[i
].mask
;
441 get_string(s
, sizeof(s
), f
);
442 for(i
= 0; actions
[i
].name
; i
++) {
443 if (strcmp(actions
[i
].name
, s
) == 0)
446 p
->action
= actions
[i
].act
? actions
[i
].act
: OFF
;
452 } while( cmd
!= C_EOR
);
458 * Read the complete state info from the state pipe.
459 * Returns 0 on success
462 int receive_state(int fd
)
465 char old_version
[256];
470 if (get_cmd(f
) != C_VER
) {
474 get_string(old_version
, sizeof(old_version
), f
);
476 for (pp
= &family
; (*pp
= get_record(f
)) != NULL
; pp
= &((*pp
)->next
))
483 * Set the process title.
486 __attribute__ ((format (printf
, 1, 2)))
488 static int setproctitle(char *fmt
, ...)
497 len
= vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
500 if (maxproclen
> 1) {
501 memset(argv0
, 0, maxproclen
);
502 strncpy(argv0
, buf
, maxproclen
- 1);
509 * Set console_dev to a working console.
512 void console_init(void)
515 int tried_devcons
= 0;
516 int tried_vtmaster
= 0;
519 if ((s
= getenv("CONSOLE")) != NULL
)
522 console_dev
= CONSOLE
;
526 while ((fd
= open(console_dev
, O_RDONLY
|O_NONBLOCK
)) < 0) {
527 if (!tried_devcons
) {
529 console_dev
= CONSOLE
;
532 if (!tried_vtmaster
) {
534 console_dev
= VT_MASTER
;
540 console_dev
= "/dev/null";
547 * Open the console with retries.
550 int console_open(int mode
)
556 * Open device in nonblocking mode.
558 m
= mode
| O_NONBLOCK
;
561 * Retry the open five times.
563 for(f
= 0; f
< 5; f
++) {
564 if ((fd
= open(console_dev
, m
)) >= 0) break;
568 if (fd
< 0) return fd
;
571 * Set original flags.
574 fcntl(fd
, F_SETFL
, mode
);
579 * We got a signal (HUP PWR WINCH ALRM INT)
582 void signal_handler(int sig
)
584 ADDSET(got_signals
, sig
);
588 * SIGCHLD: one of our children has died.
592 void chld_handler(int sig
__attribute__((unused
)))
594 void chld_handler(int sig
)
599 int saved_errno
= errno
;
602 * Find out which process(es) this was (were)
604 while((pid
= waitpid(-1, &st
, WNOHANG
)) != 0) {
605 if (errno
== ECHILD
) break;
606 for( ch
= family
; ch
; ch
= ch
->next
)
607 if ( ch
->pid
== pid
&& (ch
->flags
& RUNNING
) ) {
609 "chld_handler: marked %d as zombie",
611 ADDSET(got_signals
, SIGCHLD
);
615 ch
->new->exstat
= st
;
616 ch
->new->flags
|= ZOMBIE
;
621 INITDBG(L_VB
, "chld_handler: unknown child %d exited.",
629 * Linux ignores all signals sent to init when the
630 * SIG_DFL handler is installed. Therefore we must catch SIGTSTP
631 * and SIGCONT, or else they won't work....
633 * The SIGCONT handler
637 void cont_handler(int sig
__attribute__((unused
)))
639 void cont_handler(int sig
)
646 * Fork and dump core in /.
651 static int dumped
= 0;
658 if (fork() != 0) return;
661 sigprocmask(SIG_SETMASK
, &mask
, NULL
);
663 rlim
.rlim_cur
= RLIM_INFINITY
;
664 rlim
.rlim_max
= RLIM_INFINITY
;
665 setrlimit(RLIMIT_CORE
, &rlim
);
667 initlog(L_VB
, "unable to chdir to /: %s",
670 signal(SIGSEGV
, SIG_DFL
);
672 sigdelset(&mask
, SIGSEGV
);
673 sigprocmask(SIG_SETMASK
, &mask
, NULL
);
680 * OOPS: segmentation violation!
681 * If we have the info, print where it occured.
682 * Then sleep 30 seconds and try to continue.
685 #if defined(STACK_DEBUG) && defined(__linux__)
687 void segv_handler(int sig
__attribute__((unused
)), struct sigcontext ctx
)
689 void segv_handler(int sig
, struct sigcontext ctx
)
693 int saved_errno
= errno
;
695 if ((void *)ctx
.eip
>= (void *)do_sleep
&&
696 (void *)ctx
.eip
< (void *)main
)
698 initlog(L_VB
, "PANIC: segmentation violation at %p%s! "
699 "sleeping for 30 seconds.", (void *)ctx
.eip
, p
);
706 void segv_handler(int sig
__attribute__((unused
)))
708 void segv_handler(int sig
)
711 int saved_errno
= errno
;
714 "PANIC: segmentation violation! sleeping for 30 seconds.");
722 * The SIGSTOP & SIGTSTP handler
726 void stop_handler(int sig
__attribute__((unused
)))
728 void stop_handler(int sig
)
731 int saved_errno
= errno
;
734 while(!got_cont
) pause();
740 * Set terminal settings to reasonable defaults
743 void console_stty(void)
748 if ((fd
= console_open(O_RDWR
|O_NOCTTY
)) < 0) {
749 initlog(L_VB
, "can't open %s", console_dev
);
753 #ifdef __FreeBSD_kernel__
755 * The kernel of FreeBSD expects userland to set TERM. Usually, we want
756 * "cons25". Later, gettys might disagree on this (i.e. we're not using
757 * syscons) but some boot scripts, like /etc/init.d/xserver-xorg, still
758 * need a non-dumb terminal.
760 putenv ("TERM=cons25");
763 (void) tcgetattr(fd
, &tty
);
765 tty
.c_cflag
&= CBAUD
|CBAUDEX
|CSIZE
|CSTOPB
|PARENB
|PARODD
;
766 tty
.c_cflag
|= HUPCL
|CLOCAL
|CREAD
;
768 tty
.c_cc
[VINTR
] = CINTR
;
769 tty
.c_cc
[VQUIT
] = CQUIT
;
770 tty
.c_cc
[VERASE
] = CERASE
; /* ASCII DEL (0177) */
771 tty
.c_cc
[VKILL
] = CKILL
;
772 tty
.c_cc
[VEOF
] = CEOF
;
775 #ifdef VSWTC /* not defined on FreeBSD */
776 tty
.c_cc
[VSWTC
] = _POSIX_VDISABLE
;
778 tty
.c_cc
[VSTART
] = CSTART
;
779 tty
.c_cc
[VSTOP
] = CSTOP
;
780 tty
.c_cc
[VSUSP
] = CSUSP
;
781 tty
.c_cc
[VEOL
] = _POSIX_VDISABLE
;
782 tty
.c_cc
[VREPRINT
] = CREPRINT
;
783 tty
.c_cc
[VDISCARD
] = CDISCARD
;
784 tty
.c_cc
[VWERASE
] = CWERASE
;
785 tty
.c_cc
[VLNEXT
] = CLNEXT
;
786 tty
.c_cc
[VEOL2
] = _POSIX_VDISABLE
;
789 * Set pre and post processing
791 tty
.c_iflag
= IGNPAR
|ICRNL
|IXON
|IXANY
792 #ifdef IUTF8 /* Not defined on FreeBSD */
793 | (tty
.c_iflag
& IUTF8
)
796 tty
.c_oflag
= OPOST
|ONLCR
;
797 tty
.c_lflag
= ISIG
|ICANON
|ECHO
|ECHOCTL
|ECHOPRT
|ECHOKE
;
799 #if defined(SANE_TIO) && (SANE_TIO == 1)
801 * Disable flow control (-ixon), ignore break (ignbrk),
802 * and make nl/cr more usable (sane).
804 tty
.c_iflag
|= IGNBRK
;
805 tty
.c_iflag
&= ~(BRKINT
|INLCR
|IGNCR
|IXON
);
806 tty
.c_oflag
&= ~(OCRNL
|ONLRET
);
809 * Now set the terminal line.
810 * We don't care about non-transmitted output data
811 * and non-read input data.
813 (void) tcsetattr(fd
, TCSANOW
, &tty
);
814 (void) tcflush(fd
, TCIOFLUSH
);
819 safe_write(int fd
, const char *buffer
, size_t count
)
824 ssize_t block
= write(fd
, &buffer
[offset
], count
);
826 if (block
< 0 && errno
== EINTR
)
829 return offset
? offset
: block
;
837 * Print to the system console
843 if ((fd
= console_open(O_WRONLY
|O_NOCTTY
|O_NDELAY
)) >= 0) {
844 safe_write(fd
, s
, strlen(s
));
850 * Log something to a logfile and the console.
853 __attribute__ ((format (printf
, 2, 3)))
855 void initlog(int loglevel
, char *s
, ...)
859 sigset_t nmask
, omask
;
861 va_start(va_alist
, s
);
862 vsnprintf(buf
, sizeof(buf
), s
, va_alist
);
865 if (loglevel
& L_SY
) {
867 * Re-establish connection with syslogd every time.
868 * Block signals while talking to syslog.
871 sigprocmask(SIG_BLOCK
, &nmask
, &omask
);
872 openlog("init", 0, LOG_DAEMON
);
873 syslog(LOG_INFO
, "%s", buf
);
875 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
879 * And log to the console.
881 if (loglevel
& L_CO
) {
889 * Add or replace specific environment value
891 int addnewenv(const char *new, char **curr
, int n
)
893 size_t nlen
= strcspn(new, "=");
895 for (i
= 0; i
< n
; i
++) {
896 if (nlen
!= strcspn(curr
[i
], "="))
898 if (strncmp (new, curr
[i
], nlen
) == 0)
902 curr
[n
++] = istrdup(new);
905 curr
[i
] = istrdup(new);
911 * Build a new environment for execve().
913 char **init_buildenv(int child
)
915 char i_lvl
[] = "RUNLEVEL=x";
916 char i_prev
[] = "PREVLEVEL=x";
918 char i_shell
[] = "SHELL=" SHELL
;
922 for (n
= 0; environ
[n
]; n
++)
924 n
+= NR_EXTRA_ENV
+ 1; /* Also room for last NULL */
928 while ((e
= (char**)calloc(n
, sizeof(char *))) == NULL
) {
929 initlog(L_VB
, "out of memory");
933 for (n
= 0; environ
[n
]; n
++)
934 e
[n
] = istrdup(environ
[n
]);
936 for (i
= 0; i
< NR_EXTRA_ENV
; i
++) {
937 if (extra_env
[i
] == NULL
|| *extra_env
[i
] == '\0')
939 n
= addnewenv(extra_env
[i
], e
, n
);
943 snprintf(i_cons
, sizeof(i_cons
), "CONSOLE=%s", console_dev
);
944 i_lvl
[9] = thislevel
;
945 i_prev
[10] = prevlevel
;
946 n
= addnewenv(i_shell
, e
, n
);
947 n
= addnewenv(i_lvl
, e
, n
);
948 n
= addnewenv(i_prev
, e
, n
);
949 n
= addnewenv(i_cons
, e
, n
);
950 n
= addnewenv(E_VERSION
, e
, n
);
959 void init_freeenv(char **e
)
963 for (n
= 0; e
[n
]; n
++)
972 * This function is too long and indents too deep.
976 pid_t
spawn(CHILD
*ch
, int *res
)
978 char *args
[16]; /* Argv array */
979 char buf
[136]; /* Line buffer */
980 int f
, st
; /* Scratch variables */
981 char *ptr
; /* Ditto */
982 time_t t
; /* System time */
983 int oldAlarm
; /* Previous alarm value */
984 char *proc
= ch
->process
; /* Command line */
985 pid_t pid
, pgrp
; /* child, console process group. */
986 sigset_t nmask
, omask
; /* For blocking SIGCHLD */
990 buf
[sizeof(buf
) - 1] = 0;
992 /* Skip '+' if it's there */
993 if (proc
[0] == '+') proc
++;
995 ch
->flags
|= XECUTED
;
997 if (ch
->action
== RESPAWN
|| ch
->action
== ONDEMAND
) {
998 /* Is the date stamp from less than 2 minutes ago? */
1000 if (ch
->tm
+ TESTTIME
> t
) {
1007 /* Do we try to respawn too fast? */
1008 if (ch
->count
>= MAXSPAWN
) {
1011 "Id \"%s\" respawning too fast: disabled for %d minutes",
1012 ch
->id
, SLEEPTIME
/ 60);
1013 ch
->flags
&= ~RUNNING
;
1014 ch
->flags
|= FAILING
;
1016 /* Remember the time we stopped */
1019 /* Try again in 5 minutes */
1020 oldAlarm
= alarm(0);
1021 if (oldAlarm
> SLEEPTIME
|| oldAlarm
<= 0) oldAlarm
= SLEEPTIME
;
1027 /* See if there is an "initscript" (except in single user mode). */
1028 if (access(INITSCRIPT
, R_OK
) == 0 && runlevel
!= 'S') {
1029 /* Build command line using "initscript" */
1031 args
[2] = INITSCRIPT
;
1033 args
[4] = ch
->rlevel
;
1034 args
[5] = "unknown";
1035 for(f
= 0; actions
[f
].name
; f
++) {
1036 if (ch
->action
== actions
[f
].act
) {
1037 args
[5] = actions
[f
].name
;
1043 } else if (strpbrk(proc
, "~`!$^&*()=|\\{}[];\"'<>?")) {
1044 /* See if we need to fire off a shell for this command */
1045 /* Give command line to shell */
1048 strcpy(buf
, "exec ");
1049 strncat(buf
, proc
, sizeof(buf
) - strlen(buf
) - 1);
1053 /* Split up command line arguments */
1055 strncat(buf
, proc
, sizeof(buf
) - 1);
1057 for(f
= 1; f
< 15; f
++) {
1058 /* Skip white space */
1059 while(*ptr
== ' ' || *ptr
== '\t') ptr
++;
1062 /* May be trailing space.. */
1063 if (*ptr
== 0) break;
1065 /* Skip this `word' */
1066 while(*ptr
&& *ptr
!= ' ' && *ptr
!= '\t' && *ptr
!= '#')
1069 /* If end-of-line, break */
1070 if (*ptr
== '#' || *ptr
== 0) {
1075 /* End word with \0 and continue */
1083 * Block sigchild while forking.
1085 sigemptyset(&nmask
);
1086 sigaddset(&nmask
, SIGCHLD
);
1087 sigprocmask(SIG_BLOCK
, &nmask
, &omask
);
1089 if ((pid
= fork()) == 0) {
1094 if (pipe_fd
>= 0) close(pipe_fd
);
1096 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
1099 * In sysinit, boot, bootwait or single user mode:
1100 * for any wait-type subprocess we _force_ the console
1101 * to be its controlling tty.
1103 if (strchr("*#sS", runlevel
) && ch
->flags
& WAITING
) {
1105 * We fork once extra. This is so that we can
1106 * wait and change the process group and session
1107 * of the console after exit of the leader.
1110 if ((f
= console_open(O_RDWR
|O_NOCTTY
)) >= 0) {
1111 /* Take over controlling tty by force */
1112 (void)ioctl(f
, TIOCSCTTY
, 1);
1118 * 4 Sep 2001, Andrea Arcangeli:
1119 * Fix a race in spawn() that is used to deadlock init in a
1120 * waitpid() loop: must set the childhandler as default before forking
1121 * off the child or the chld_handler could run before the waitpid loop
1122 * has a chance to find its zombie-child.
1124 SETSIG(sa
, SIGCHLD
, SIG_DFL
, SA_RESTART
);
1125 if ((pid
= fork()) < 0) {
1126 initlog(L_VB
, "cannot fork: %s",
1133 * Ignore keyboard signals etc.
1134 * Then wait for child to exit.
1136 SETSIG(sa
, SIGINT
, SIG_IGN
, SA_RESTART
);
1137 SETSIG(sa
, SIGTSTP
, SIG_IGN
, SA_RESTART
);
1138 SETSIG(sa
, SIGQUIT
, SIG_IGN
, SA_RESTART
);
1140 while ((rc
= waitpid(pid
, &st
, 0)) != pid
)
1141 if (rc
< 0 && errno
== ECHILD
)
1145 * Small optimization. See if stealing
1146 * controlling tty back is needed.
1148 pgrp
= tcgetpgrp(f
);
1149 if (pgrp
!= getpid())
1153 * Steal controlling tty away. We do
1154 * this with a temporary process.
1156 if ((pid
= fork()) < 0) {
1157 initlog(L_VB
, "cannot fork: %s",
1163 (void)ioctl(f
, TIOCSCTTY
, 1);
1166 while((rc
= waitpid(pid
, &st
, 0)) != pid
)
1167 if (rc
< 0 && errno
== ECHILD
)
1172 /* Set ioctl settings to default ones */
1175 } else { /* parent */
1178 if ((fd
= console_open(O_RDWR
|O_NOCTTY
)) < 0) {
1179 initlog(L_VB
, "open(%s): %s", console_dev
,
1181 fd
= open("/dev/null", O_RDWR
);
1188 * Update utmp/wtmp file prior to starting
1189 * any child. This MUST be done right here in
1190 * the child process in order to prevent a race
1191 * condition that occurs when the child
1192 * process' time slice executes before the
1193 * parent (can and does happen in a uniprocessor
1194 * environment). If the child is a getty and
1195 * the race condition happens, then init's utmp
1196 * update will happen AFTER the getty runs
1197 * and expects utmp to be updated already!
1199 * Do NOT log if process field starts with '+'
1200 * FIXME: that's for compatibility with *very*
1201 * old getties - probably it can be taken out.
1203 if (ch
->process
[0] != '+')
1204 write_utmp_wtmp("", ch
->id
, getpid(), INIT_PROCESS
, "");
1206 /* Reset all the signals, set up environment */
1207 for(f
= 1; f
< NSIG
; f
++) SETSIG(sa
, f
, SIG_DFL
, SA_RESTART
);
1208 environ
= init_buildenv(1);
1211 * Execute prog. In case of ENOEXEC try again
1212 * as a shell script.
1214 execvp(args
[1], args
+ 1);
1215 if (errno
== ENOEXEC
) {
1218 strcpy(buf
, "exec ");
1219 strncat(buf
, proc
, sizeof(buf
) - strlen(buf
) - 1);
1222 execvp(args
[1], args
+ 1);
1224 initlog(L_VB
, "cannot execute \"%s\"", args
[1]);
1226 if (ch
->process
[0] != '+')
1227 write_utmp_wtmp("", ch
->id
, getpid(), DEAD_PROCESS
, NULL
);
1231 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
1233 INITDBG(L_VB
, "Started id %s (pid %d)", ch
->id
, pid
);
1236 initlog(L_VB
, "cannot fork, retry..");
1245 * Start a child running!
1248 void startup(CHILD
*ch
)
1251 * See if it's disabled
1253 if (ch
->flags
& FAILING
) return;
1255 switch(ch
->action
) {
1264 if (!(ch
->flags
& XECUTED
)) ch
->flags
|= WAITING
;
1270 if (ch
->flags
& XECUTED
) break;
1273 ch
->flags
|= RUNNING
;
1274 (void)spawn(ch
, &(ch
->pid
));
1281 * Read the inittab file.
1284 void read_inittab(void)
1286 FILE *fp
; /* The INITTAB file */
1287 CHILD
*ch
, *old
, *i
; /* Pointers to CHILD structure */
1288 CHILD
*head
= NULL
; /* Head of linked list */
1290 struct stat st
; /* To stat INITLVL */
1292 sigset_t nmask
, omask
; /* For blocking SIGCHLD. */
1293 char buf
[256]; /* Line buffer */
1294 char err
[64]; /* Error message. */
1296 *action
, *process
; /* Fields of a line */
1298 int lineNo
= 0; /* Line number in INITTAB file */
1299 int actionNo
; /* Decoded action field */
1300 int f
; /* Counter */
1301 int round
; /* round 0 for SIGTERM, 1 for SIGKILL */
1302 int foundOne
= 0; /* No killing no sleep */
1303 int talk
; /* Talk to the user */
1304 int done
= 0; /* Ready yet? */
1307 if (newFamily
!= NULL
) {
1308 INITDBG(L_VB
, "PANIC newFamily != NULL");
1311 INITDBG(L_VB
, "Reading inittab");
1315 * Open INITTAB and read line by line.
1317 if ((fp
= fopen(INITTAB
, "r")) == NULL
)
1318 initlog(L_VB
, "No inittab file found");
1322 * Add single user shell entry at the end.
1324 if (fp
== NULL
|| fgets(buf
, sizeof(buf
), fp
) == NULL
) {
1327 * See if we have a single user entry.
1329 for(old
= newFamily
; old
; old
= old
->next
)
1330 if (strpbrk(old
->rlevel
, "S")) break;
1332 snprintf(buf
, sizeof(buf
), "~~:S:wait:%s\n", SULOGIN
);
1338 * Skip comments and empty lines
1340 for(p
= buf
; *p
== ' ' || *p
== '\t'; p
++)
1342 if (*p
== '#' || *p
== '\n') continue;
1347 id
= strsep(&p
, ":");
1348 rlevel
= strsep(&p
, ":");
1349 action
= strsep(&p
, ":");
1350 process
= strsep(&p
, "\n");
1353 * Check if syntax is OK. Be very verbose here, to
1354 * avoid newbie postings on comp.os.linux.setup :)
1357 if (!id
|| !*id
) strcpy(err
, "missing id field");
1358 if (!rlevel
) strcpy(err
, "missing runlevel field");
1359 if (!process
) strcpy(err
, "missing process field");
1360 if (!action
|| !*action
)
1361 strcpy(err
, "missing action field");
1362 if (id
&& strlen(id
) > sizeof(utproto
.ut_id
))
1363 sprintf(err
, "id field too long (max %d characters)",
1364 (int)sizeof(utproto
.ut_id
));
1365 if (rlevel
&& strlen(rlevel
) > 11)
1366 strcpy(err
, "rlevel field too long (max 11 characters)");
1367 if (process
&& strlen(process
) > 127)
1368 strcpy(err
, "process field too long");
1369 if (action
&& strlen(action
) > 32)
1370 strcpy(err
, "action field too long");
1372 initlog(L_VB
, "%s[%d]: %s", INITTAB
, lineNo
, err
);
1373 INITDBG(L_VB
, "%s:%s:%s:%s", id
, rlevel
, action
, process
);
1378 * Decode the "action" field
1381 for(f
= 0; actions
[f
].name
; f
++)
1382 if (strcasecmp(action
, actions
[f
].name
) == 0) {
1383 actionNo
= actions
[f
].act
;
1386 if (actionNo
== -1) {
1387 initlog(L_VB
, "%s[%d]: %s: unknown action field",
1388 INITTAB
, lineNo
, action
);
1393 * See if the id field is unique
1395 for(old
= newFamily
; old
; old
= old
->next
) {
1396 if(strcmp(old
->id
, id
) == 0 && strcmp(id
, "~~")) {
1397 initlog(L_VB
, "%s[%d]: duplicate ID field \"%s\"",
1398 INITTAB
, lineNo
, id
);
1405 * Allocate a CHILD structure
1407 ch
= imalloc(sizeof(CHILD
));
1412 ch
->action
= actionNo
;
1413 strncpy(ch
->id
, id
, sizeof(utproto
.ut_id
) + 1); /* Hack for different libs. */
1414 strncpy(ch
->process
, process
, sizeof(ch
->process
) - 1);
1416 for(f
= 0; f
< (int)sizeof(rlevel
) - 1 && rlevel
[f
]; f
++) {
1417 ch
->rlevel
[f
] = rlevel
[f
];
1418 if (ch
->rlevel
[f
] == 's') ch
->rlevel
[f
] = 'S';
1420 strncpy(ch
->rlevel
, rlevel
, sizeof(ch
->rlevel
) - 1);
1422 strcpy(ch
->rlevel
, "0123456789");
1423 if (ISPOWER(ch
->action
))
1424 strcpy(ch
->rlevel
, "S0123456789");
1427 * We have the fake runlevel '#' for SYSINIT and
1428 * '*' for BOOT and BOOTWAIT.
1430 if (ch
->action
== SYSINIT
) strcpy(ch
->rlevel
, "#");
1431 if (ch
->action
== BOOT
|| ch
->action
== BOOTWAIT
)
1432 strcpy(ch
->rlevel
, "*");
1435 * Now add it to the linked list. Special for powerfail.
1437 if (ISPOWER(ch
->action
)) {
1440 * Disable by default
1442 ch
->flags
|= XECUTED
;
1445 * Tricky: insert at the front of the list..
1448 for(i
= newFamily
; i
; i
= i
->next
) {
1449 if (!ISPOWER(i
->action
)) break;
1453 * Now add after entry "old"
1458 if (i
== NULL
) head
= ch
;
1460 ch
->next
= newFamily
;
1462 if (ch
->next
== NULL
) head
= ch
;
1466 * Just add at end of the list
1468 if (ch
->action
== KBREQUEST
) ch
->flags
|= XECUTED
;
1478 * Walk through the old list comparing id fields
1480 for(old
= family
; old
; old
= old
->next
)
1481 if (strcmp(old
->id
, ch
->id
) == 0) {
1492 * Loop through the list of children, and see if they need to
1496 INITDBG(L_VB
, "Checking for children to kill");
1497 for(round
= 0; round
< 2; round
++) {
1499 for(ch
= family
; ch
; ch
= ch
->next
) {
1500 ch
->flags
&= ~KILLME
;
1503 * Is this line deleted?
1505 if (ch
->new == NULL
) ch
->flags
|= KILLME
;
1508 * If the entry has changed, kill it anyway. Note that
1509 * we do not check ch->process, only the "action" field.
1510 * This way, you can turn an entry "off" immediately, but
1511 * changes in the command line will only become effective
1512 * after the running version has exited.
1514 if (ch
->new && ch
->action
!= ch
->new->action
) ch
->flags
|= KILLME
;
1517 * Only BOOT processes may live in all levels
1519 if (ch
->action
!= BOOT
&&
1520 strchr(ch
->rlevel
, runlevel
) == NULL
) {
1522 * Ondemand procedures live always,
1523 * except in single user
1525 if (runlevel
== 'S' || !(ch
->flags
& DEMAND
))
1526 ch
->flags
|= KILLME
;
1530 * Now, if this process may live note so in the new list
1532 if ((ch
->flags
& KILLME
) == 0) {
1533 ch
->new->flags
= ch
->flags
;
1534 ch
->new->pid
= ch
->pid
;
1535 ch
->new->exstat
= ch
->exstat
;
1541 * Is this process still around?
1543 if ((ch
->flags
& RUNNING
) == 0) {
1544 ch
->flags
&= ~KILLME
;
1547 INITDBG(L_VB
, "Killing \"%s\"", ch
->process
);
1549 case 0: /* Send TERM signal */
1552 "Sending processes configured via /etc/inittab the TERM signal");
1553 kill(-(ch
->pid
), SIGTERM
);
1556 case 1: /* Send KILL signal and collect status */
1559 "Sending processes configured via /etc/inittab the KILL signal");
1560 kill(-(ch
->pid
), SIGKILL
);
1567 * See if we have to wait 5 seconds
1569 if (foundOne
&& round
== 0) {
1571 * Yup, but check every second if we still have children.
1573 for(f
= 0; f
< sltime
; f
++) {
1574 for(ch
= family
; ch
; ch
= ch
->next
) {
1575 if (!(ch
->flags
& KILLME
)) continue;
1576 if ((ch
->flags
& RUNNING
) && !(ch
->flags
& ZOMBIE
))
1581 * No running children, skip SIGKILL
1584 foundOne
= 0; /* Skip the sleep below. */
1593 * Now give all processes the chance to die and collect exit statuses.
1595 if (foundOne
) do_sleep(1);
1596 for(ch
= family
; ch
; ch
= ch
->next
)
1597 if (ch
->flags
& KILLME
) {
1598 if (!(ch
->flags
& ZOMBIE
))
1599 initlog(L_CO
, "Pid %d [id %s] seems to hang", ch
->pid
,
1602 INITDBG(L_VB
, "Updating utmp for pid %d [id %s]",
1604 ch
->flags
&= ~RUNNING
;
1605 if (ch
->process
[0] != '+')
1606 write_utmp_wtmp("", ch
->id
, ch
->pid
, DEAD_PROCESS
, NULL
);
1611 * Both rounds done; clean up the list.
1613 sigemptyset(&nmask
);
1614 sigaddset(&nmask
, SIGCHLD
);
1615 sigprocmask(SIG_BLOCK
, &nmask
, &omask
);
1616 for(ch
= family
; ch
; ch
= old
) {
1621 for(ch
= family
; ch
; ch
= ch
->next
) ch
->new = NULL
;
1623 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
1627 * Dispose of INITLVL file.
1629 if (lstat(INITLVL
, &st
) >= 0 && S_ISLNK(st
.st_mode
)) {
1631 * INITLVL is a symbolic link, so just truncate the file.
1633 close(open(INITLVL
, O_WRONLY
|O_TRUNC
));
1636 * Delete INITLVL file.
1643 * Dispose of INITLVL2 file.
1645 if (lstat(INITLVL2
, &st
) >= 0 && S_ISLNK(st
.st_mode
)) {
1647 * INITLVL2 is a symbolic link, so just truncate the file.
1649 close(open(INITLVL2
, O_WRONLY
|O_TRUNC
));
1652 * Delete INITLVL2 file.
1660 * Walk through the family list and start up children.
1661 * The entries that do not belong here at all are removed
1665 void start_if_needed(void)
1667 CHILD
*ch
; /* Pointer to child */
1668 int delete; /* Delete this entry from list? */
1670 INITDBG(L_VB
, "Checking for children to start");
1672 for(ch
= family
; ch
; ch
= ch
->next
) {
1675 if (ch
->rlevel
[0] == 'C') {
1676 INITDBG(L_VB
, "%s: flags %d", ch
->process
, ch
->flags
);
1680 /* Are we waiting for this process? Then quit here. */
1681 if (ch
->flags
& WAITING
) break;
1683 /* Already running? OK, don't touch it */
1684 if (ch
->flags
& RUNNING
) continue;
1686 /* See if we have to start it up */
1688 if (strchr(ch
->rlevel
, runlevel
) ||
1689 ((ch
->flags
& DEMAND
) && !strchr("#*Ss", runlevel
))) {
1695 /* FIXME: is this OK? */
1696 ch
->flags
&= ~(RUNNING
|WAITING
);
1697 if (!ISPOWER(ch
->action
) && ch
->action
!= KBREQUEST
)
1698 ch
->flags
&= ~XECUTED
;
1701 /* Do we have to wait for this process? */
1702 if (ch
->flags
& WAITING
) break;
1708 * Ask the user on the console for a runlevel
1711 int ask_runlevel(void)
1713 const char prompt
[] = "\nEnter runlevel: ";
1719 fd
= console_open(O_RDWR
|O_NOCTTY
);
1721 if (fd
< 0) return('S');
1723 while(!strchr("0123456789S", lvl
)) {
1724 safe_write(fd
, prompt
, sizeof(prompt
) - 1);
1725 if (read(fd
, buf
, sizeof(buf
)) <= 0)
1727 if (buf
[0] != 0 && (buf
[1] == '\r' || buf
[1] == '\n'))
1729 if (islower(lvl
)) lvl
= toupper(lvl
);
1736 * Search the INITTAB file for the 'initdefault' field, with the default
1737 * runlevel. If this fails, ask the user to supply a runlevel.
1740 int get_init_default(void)
1747 * Look for initdefault.
1749 for(ch
= family
; ch
; ch
= ch
->next
)
1750 if (ch
->action
== INITDEFAULT
) {
1753 if (*p
> lvl
) lvl
= *p
;
1759 * See if level is valid
1762 if (islower(lvl
)) lvl
= toupper(lvl
);
1763 if (strchr("0123456789S", lvl
) == NULL
) {
1765 "Initdefault level '%c' is invalid", lvl
);
1770 * Ask for runlevel on console if needed.
1772 if (lvl
<= 0) lvl
= ask_runlevel();
1775 * Log the fact that we have a runlevel now.
1784 * Do actions for the new level. If we are compatible with
1785 * the "old" INITLVL and arg == 0, try to read the new
1786 * runlevel from that file first.
1789 int read_level(int arg
)
1791 CHILD
*ch
; /* Walk through list */
1792 unsigned char foo
= 'X'; /* Contents of INITLVL */
1807 if (stat(INITLVL
, &stt
) != 0 || stt
.st_size
!= 0L)
1808 fp
= fopen(INITLVL
, "r");
1811 (stat(INITLVL2
, &stt
) != 0 || stt
.st_size
!= 0L))
1812 fp
= fopen(INITLVL2
, "r");
1815 /* INITLVL file empty or not there - act as 'init q' */
1816 initlog(L_SY
, "Re-reading inittab");
1819 ok
= fscanf(fp
, "%c %d", &foo
, &st
);
1822 /* We go to the new runlevel passed as an argument. */
1826 if (ok
== 2) sltime
= st
;
1828 #endif /* INITLVL */
1830 if (islower(foo
)) foo
= toupper(foo
);
1831 if (ok
< 1 || ok
> 2 || strchr("QS0123456789ABCU", foo
) == NULL
) {
1832 initlog(L_VB
, "bad runlevel: %c", foo
);
1836 /* Log this action */
1839 initlog(L_VB
, "Going single user");
1842 initlog(L_SY
, "Re-reading inittab");
1848 "Activating demand-procedures for '%c'", foo
);
1851 initlog(L_SY
, "Trying to re-exec init");
1854 initlog(L_VB
, "Switching to runlevel: %c", foo
);
1858 #if defined(SIGINT_ONLYONCE) && (SIGINT_ONLYONCE == 1)
1859 /* Re-enable signal from keyboard */
1860 struct sigaction sa
;
1861 SETSIG(sa
, SIGINT
, signal_handler
, 0);
1866 /* Check if this is a runlevel a, b or c */
1867 if (strchr("ABC", foo
)) {
1868 if (runlevel
== 'S') return(runlevel
);
1870 /* Read inittab again first! */
1873 /* Mark those special tasks */
1874 for(ch
= family
; ch
; ch
= ch
->next
)
1875 if (strchr(ch
->rlevel
, foo
) != NULL
||
1876 strchr(ch
->rlevel
, tolower(foo
)) != NULL
) {
1877 ch
->flags
|= DEMAND
;
1878 ch
->flags
&= ~XECUTED
;
1880 "Marking (%s) as ondemand, flags %d",
1886 /* Store both the old and the new runlevel. */
1887 wrote_utmp_rlevel
= 0;
1888 wrote_wtmp_rlevel
= 0;
1889 write_utmp_wtmp("runlevel", "~~", foo
+ 256*runlevel
, RUN_LVL
, "~");
1891 prevlevel
= runlevel
;
1897 * This procedure is called after every signal (SIGHUP, SIGALRM..)
1899 * Only clear the 'failing' flag if the process is sleeping
1900 * longer than 5 minutes, or inittab was read again due
1901 * to user interaction.
1904 void fail_check(void)
1906 CHILD
*ch
; /* Pointer to child structure */
1907 time_t t
; /* System time */
1908 time_t next_alarm
= 0; /* When to set next alarm */
1912 for(ch
= family
; ch
; ch
= ch
->next
) {
1914 if (ch
->flags
& FAILING
) {
1915 /* Can we free this sucker? */
1916 if (ch
->tm
+ SLEEPTIME
< t
) {
1917 ch
->flags
&= ~FAILING
;
1921 /* No, we'll look again later */
1922 if (next_alarm
== 0 ||
1923 ch
->tm
+ SLEEPTIME
> next_alarm
)
1924 next_alarm
= ch
->tm
+ SLEEPTIME
;
1930 if (next_alarm
< 1) next_alarm
= 1;
1935 /* Set all 'Fail' timers to 0 */
1937 void fail_cancel(void)
1941 for(ch
= family
; ch
; ch
= ch
->next
) {
1944 ch
->flags
&= ~FAILING
;
1949 * Start up powerfail entries.
1952 void do_power_fail(int pwrstat
)
1957 * Tell powerwait & powerfail entries to start up
1959 for (ch
= family
; ch
; ch
= ch
->next
) {
1960 if (pwrstat
== 'O') {
1962 * The power is OK again.
1964 if (ch
->action
== POWEROKWAIT
)
1965 ch
->flags
&= ~XECUTED
;
1966 } else if (pwrstat
== 'L') {
1968 * Low battery, shut down now.
1970 if (ch
->action
== POWERFAILNOW
)
1971 ch
->flags
&= ~XECUTED
;
1974 * Power is failing, shutdown imminent
1976 if (ch
->action
== POWERFAIL
|| ch
->action
== POWERWAIT
)
1977 ch
->flags
&= ~XECUTED
;
1983 * Check for state-pipe presence
1986 int check_pipe(int fd
)
1994 t
.tv_sec
= t
.tv_usec
= 0;
1996 if (select(fd
+1, &s
, NULL
, NULL
, &t
) != 1)
1998 if (read(fd
, signature
, 8) != 8)
2000 return strncmp(Signature
, signature
, 8) == 0;
2004 * Make a state-pipe.
2007 int make_pipe(int fd
)
2012 initlog(L_VB
, "pipe: %m");
2017 fcntl(fds
[1], F_SETFD
, 1);
2018 fcntl(fd
, F_SETFD
, 0);
2019 safe_write(fds
[1], Signature
, 8);
2025 * Attempt to re-exec.
2031 sigset_t mask
, oldset
;
2036 if (strchr("S0123456",runlevel
) == NULL
)
2040 * Reset the alarm, and block all signals.
2044 sigprocmask(SIG_BLOCK
, &mask
, &oldset
);
2047 * construct a pipe fd --> STATE_PIPE and write a signature
2049 if ((fd
= make_pipe(STATE_PIPE
)) < 0) {
2050 sigprocmask(SIG_SETMASK
, &oldset
, NULL
);
2051 initlog(L_CO
, "Attempt to re-exec failed");
2055 * It's a backup day today, so I'm pissed off. Being a BOFH, however,
2056 * does have it's advantages...
2061 DELSET(got_signals
, SIGCHLD
);
2062 DELSET(got_signals
, SIGHUP
);
2063 DELSET(got_signals
, SIGUSR1
);
2066 * That should be cleaned.
2068 for(ch
= family
; ch
; ch
= ch
->next
)
2069 if (ch
->flags
& ZOMBIE
) {
2070 INITDBG(L_VB
, "Child died, PID= %d", ch
->pid
);
2071 ch
->flags
&= ~(RUNNING
|ZOMBIE
|WAITING
);
2072 if (ch
->process
[0] != '+')
2073 write_utmp_wtmp("", ch
->id
, ch
->pid
, DEAD_PROCESS
, NULL
);
2076 if ((pid
= fork()) == 0) {
2078 * Child sends state information to the parent.
2085 * The existing init process execs a new init binary.
2087 env
= init_buildenv(0);
2088 execle(myname
, myname
, "--init", NULL
, env
);
2091 * We shouldn't be here, something failed.
2092 * Bitch, close the state pipe, unblock signals and return.
2097 sigprocmask(SIG_SETMASK
, &oldset
, NULL
);
2098 initlog(L_CO
, "Attempt to re-exec failed");
2102 * Redo utmp/wtmp entries if required or requested
2103 * Check for written records and size of utmp
2106 void redo_utmp_wtmp(void)
2109 const int ret
= stat(UTMP_FILE
, &ustat
);
2111 if ((ret
< 0) || (ustat
.st_size
== 0))
2112 wrote_utmp_rlevel
= wrote_utmp_reboot
= 0;
2114 if ((wrote_wtmp_reboot
== 0) || (wrote_utmp_reboot
== 0))
2115 write_utmp_wtmp("reboot", "~~", 0, BOOT_TIME
, "~");
2117 if ((wrote_wtmp_rlevel
== 0) || (wrote_wtmp_rlevel
== 0))
2118 write_utmp_wtmp("runlevel", "~~", thislevel
+ 256 * prevlevel
, RUN_LVL
, "~");
2122 * We got a change runlevel request through the
2123 * init.fifo. Process it.
2126 void fifo_new_level(int level
)
2133 if (level
== runlevel
) return;
2136 /* Are we waiting for a child? */
2137 for(ch
= family
; ch
; ch
= ch
->next
)
2138 if (ch
->flags
& WAITING
) break;
2142 /* We need to go into a new runlevel */
2143 oldlevel
= runlevel
;
2144 runlevel
= read_level(level
);
2145 if (runlevel
== 'U') {
2146 runlevel
= oldlevel
;
2149 if (oldlevel
!= 'S' && runlevel
== 'S') console_stty();
2150 if (runlevel
== '6' || runlevel
== '0' ||
2151 runlevel
== '1') console_stty();
2152 if (runlevel
> '1' && runlevel
< '6') redo_utmp_wtmp();
2155 setproctitle("init [%c]", (int)runlevel
);
2162 * Set/unset environment variables. The variables are
2163 * encoded as KEY=VAL\0KEY=VAL\0\0. With "=VAL" it means
2164 * setenv, without it means unsetenv.
2167 void initcmd_setenv(char *data
, int size
)
2175 while (*data
&& data
< e
) {
2176 for (p
= data
; *p
&& p
< e
; p
++)
2183 * We only allow INIT_* to be set.
2185 if (strncmp(env
, "INIT_", 5) != 0)
2188 sz
= strcspn(env
, "=");
2189 eq
= (env
[sz
] == '=');
2191 /*initlog(L_SY, "init_setenv: %s, %d, %d", env, eq, sz);*/
2193 /* Free existing vars. */
2194 for (i
= 0; i
< NR_EXTRA_ENV
; i
++) {
2195 if (extra_env
[i
] == NULL
)
2197 if (sz
!= strcspn(extra_env
[i
], "="))
2199 if (strncmp(extra_env
[i
], env
, sz
) == 0) {
2201 extra_env
[i
] = NULL
;
2208 /* Set new vars if needed. */
2209 for (i
= 0; i
< NR_EXTRA_ENV
; i
++) {
2210 if (extra_env
[i
] == NULL
) {
2211 extra_env
[i
] = istrdup(env
);
2220 * Read from the init FIFO. Processes like telnetd and rlogind can
2221 * ask us to create login processes on their behalf.
2223 * FIXME: this needs to be finished. NOT that it is buggy, but we need
2224 * to add the telnetd/rlogind stuff so people can start using it.
2225 * Maybe move to using an AF_UNIX socket so we can use
2226 * the 2.2 kernel credential stuff to see who we're talking to.
2230 void check_init_fifo(void)
2232 struct init_request request
;
2234 struct stat st
, st2
;
2240 * First, try to create /dev/initctl if not present.
2242 if (stat(INIT_FIFO
, &st2
) < 0 && errno
== ENOENT
)
2243 (void)mkfifo(INIT_FIFO
, 0600);
2246 * If /dev/initctl is open, stat the file to see if it
2247 * is still the _same_ inode.
2250 fstat(pipe_fd
, &st
);
2251 if (stat(INIT_FIFO
, &st2
) < 0 ||
2252 st
.st_dev
!= st2
.st_dev
||
2253 st
.st_ino
!= st2
.st_ino
) {
2260 * Now finally try to open /dev/initctl
2263 if ((pipe_fd
= open(INIT_FIFO
, O_RDWR
|O_NONBLOCK
)) >= 0) {
2264 fstat(pipe_fd
, &st
);
2265 if (!S_ISFIFO(st
.st_mode
)) {
2266 initlog(L_VB
, "%s is not a fifo", INIT_FIFO
);
2273 * Don't use fd's 0, 1 or 2.
2275 (void) dup2(pipe_fd
, PIPE_FD
);
2280 * Return to caller - we'll be back later.
2285 /* Wait for data to appear, _if_ the pipe was opened. */
2286 if (pipe_fd
>= 0) while(!quit
) {
2288 /* Do select, return on EINTR. */
2290 FD_SET(pipe_fd
, &fds
);
2293 n
= select(pipe_fd
+ 1, &fds
, NULL
, NULL
, &tv
);
2295 if (n
== 0 || errno
== EINTR
) return;
2299 /* Read the data, return on EINTR. */
2300 n
= read(pipe_fd
, &request
, sizeof(request
));
2303 * End of file. This can't happen under Linux (because
2304 * the pipe is opened O_RDWR - see select() in the
2305 * kernel) but you never know...
2312 if (errno
== EINTR
) return;
2313 initlog(L_VB
, "error reading initrequest");
2318 * This is a convenient point to also try to
2319 * find the console device or check if it changed.
2326 if (request
.magic
!= INIT_MAGIC
|| n
!= sizeof(request
)) {
2327 initlog(L_VB
, "got bogus initrequest");
2330 switch(request
.cmd
) {
2331 case INIT_CMD_RUNLVL
:
2332 sltime
= request
.sleeptime
;
2333 fifo_new_level(request
.runlevel
);
2336 case INIT_CMD_POWERFAIL
:
2337 sltime
= request
.sleeptime
;
2341 case INIT_CMD_POWERFAILNOW
:
2342 sltime
= request
.sleeptime
;
2346 case INIT_CMD_POWEROK
:
2347 sltime
= request
.sleeptime
;
2351 case INIT_CMD_SETENV
:
2352 initcmd_setenv(request
.i
.data
, sizeof(request
.i
.data
));
2355 initlog(L_VB
, "got unimplemented initrequest.");
2361 * We come here if the pipe couldn't be opened.
2363 if (pipe_fd
< 0) pause();
2369 * This function is used in the transition
2370 * sysinit (-> single user) boot -> multi-user.
2373 void boot_transitions()
2376 static int newlevel
= 0;
2377 static int warn
= 1;
2381 /* Check if there is something to wait for! */
2382 for( ch
= family
; ch
; ch
= ch
->next
)
2383 if ((ch
->flags
& RUNNING
) && ch
->action
!= BOOT
) break;
2386 /* No processes left in this level, proceed to next level. */
2390 case '#': /* SYSINIT -> BOOT */
2391 INITDBG(L_VB
, "SYSINIT -> BOOT");
2393 /* Write a boot record. */
2394 wrote_utmp_reboot
= 0;
2395 wrote_wtmp_reboot
= 0;
2396 write_utmp_wtmp("reboot", "~~", 0, BOOT_TIME
, "~");
2398 /* Get our run level */
2399 newlevel
= dfl_level
? dfl_level
: get_init_default();
2400 if (newlevel
== 'S') {
2401 runlevel
= newlevel
;
2402 /* Not really 'S' but show anyway. */
2403 setproctitle("init [S]");
2407 case '*': /* BOOT -> NORMAL */
2408 INITDBG(L_VB
, "BOOT -> NORMAL");
2409 if (runlevel
!= newlevel
)
2410 loglevel
= newlevel
;
2411 runlevel
= newlevel
;
2415 case 'S': /* Ended SU mode */
2417 INITDBG(L_VB
, "END SU MODE");
2418 newlevel
= get_init_default();
2419 if (!did_boot
&& newlevel
!= 'S')
2422 if (runlevel
!= newlevel
)
2423 loglevel
= newlevel
;
2424 runlevel
= newlevel
;
2428 for(ch
= family
; ch
; ch
= ch
->next
)
2429 if (strcmp(ch
->rlevel
, "S") == 0)
2430 ch
->flags
&= ~(FAILING
|WAITING
|XECUTED
);
2435 "no more processes left in this runlevel");
2438 if (got_signals
== 0)
2443 initlog(L_VB
, "Entering runlevel: %c", runlevel
);
2444 wrote_utmp_rlevel
= 0;
2445 wrote_wtmp_rlevel
= 0;
2446 write_utmp_wtmp("runlevel", "~~", runlevel
+ 256 * oldlevel
, RUN_LVL
, "~");
2447 thislevel
= runlevel
;
2448 prevlevel
= oldlevel
;
2449 setproctitle("init [%c]", (int)runlevel
);
2455 * Init got hit by a signal. See which signal it is,
2456 * and act accordingly.
2459 void process_signals()
2467 if (ISMEMBER(got_signals
, SIGPWR
)) {
2468 INITDBG(L_VB
, "got SIGPWR");
2469 /* See _what_ kind of SIGPWR this is. */
2471 if ((fd
= open(PWRSTAT
, O_RDONLY
)) >= 0) {
2472 if (read(fd
, &c
, 1) != 1)
2477 } else if ((fd
= open(PWRSTAT_OLD
, O_RDONLY
)) >= 0) {
2478 /* Path changed 2010-03-20. Look for the old path for a while. */
2479 initlog(L_VB
, "warning: found obsolete path %s, use %s instead",
2480 PWRSTAT_OLD
, PWRSTAT
);
2481 if (read(fd
, &c
, 1) != 1)
2485 unlink(PWRSTAT_OLD
);
2487 do_power_fail(pwrstat
);
2488 DELSET(got_signals
, SIGPWR
);
2491 if (ISMEMBER(got_signals
, SIGINT
)) {
2492 #if defined(SIGINT_ONLYONCE) && (SIGINT_ONLYONCE == 1)
2493 /* Ignore any further signal from keyboard */
2494 struct sigaction sa
;
2495 SETSIG(sa
, SIGINT
, SIG_IGN
, SA_RESTART
);
2497 INITDBG(L_VB
, "got SIGINT");
2498 /* Tell ctrlaltdel entry to start up */
2499 for(ch
= family
; ch
; ch
= ch
->next
)
2500 if (ch
->action
== CTRLALTDEL
)
2501 ch
->flags
&= ~XECUTED
;
2502 DELSET(got_signals
, SIGINT
);
2505 if (ISMEMBER(got_signals
, SIGWINCH
)) {
2506 INITDBG(L_VB
, "got SIGWINCH");
2507 /* Tell kbrequest entry to start up */
2508 for(ch
= family
; ch
; ch
= ch
->next
)
2509 if (ch
->action
== KBREQUEST
)
2510 ch
->flags
&= ~XECUTED
;
2511 DELSET(got_signals
, SIGWINCH
);
2514 if (ISMEMBER(got_signals
, SIGALRM
)) {
2515 INITDBG(L_VB
, "got SIGALRM");
2516 /* The timer went off: check it out */
2517 DELSET(got_signals
, SIGALRM
);
2520 if (ISMEMBER(got_signals
, SIGCHLD
)) {
2521 INITDBG(L_VB
, "got SIGCHLD");
2522 /* First set flag to 0 */
2523 DELSET(got_signals
, SIGCHLD
);
2525 /* See which child this was */
2526 for(ch
= family
; ch
; ch
= ch
->next
)
2527 if (ch
->flags
& ZOMBIE
) {
2528 INITDBG(L_VB
, "Child died, PID= %d", ch
->pid
);
2529 ch
->flags
&= ~(RUNNING
|ZOMBIE
|WAITING
);
2530 if (ch
->process
[0] != '+')
2531 write_utmp_wtmp("", ch
->id
, ch
->pid
, DEAD_PROCESS
, NULL
);
2536 if (ISMEMBER(got_signals
, SIGHUP
)) {
2537 INITDBG(L_VB
, "got SIGHUP");
2539 /* Are we waiting for a child? */
2540 for(ch
= family
; ch
; ch
= ch
->next
)
2541 if (ch
->flags
& WAITING
) break;
2545 /* We need to go into a new runlevel */
2546 oldlevel
= runlevel
;
2548 runlevel
= read_level(0);
2550 if (runlevel
== 'U') {
2551 runlevel
= oldlevel
;
2554 if (oldlevel
!= 'S' && runlevel
== 'S') console_stty();
2555 if (runlevel
== '6' || runlevel
== '0' ||
2556 runlevel
== '1') console_stty();
2559 setproctitle("init [%c]", (int)runlevel
);
2560 DELSET(got_signals
, SIGHUP
);
2564 if (ISMEMBER(got_signals
, SIGUSR1
)) {
2566 * SIGUSR1 means close and reopen /dev/initctl
2568 INITDBG(L_VB
, "got SIGUSR1");
2571 DELSET(got_signals
, SIGUSR1
);
2579 void init_main(void)
2582 struct sigaction sa
;
2590 * Fork so we can debug the init process.
2592 if ((f
= fork()) > 0) {
2593 static const char killmsg
[] = "PRNT: init killed.\r\n";
2596 while((rc
= wait(&st
)) != f
)
2597 if (rc
< 0 && errno
== ECHILD
)
2599 safe_write(1, killmsg
, sizeof(killmsg
) - 1);
2606 * Tell the kernel to send us SIGINT when CTRL-ALT-DEL
2607 * is pressed, and that we want to handle keyboard signals.
2609 init_reboot(BMAGIC_SOFT
);
2610 if ((f
= open(VT_MASTER
, O_RDWR
| O_NOCTTY
)) >= 0) {
2611 (void) ioctl(f
, KDSIGACCEPT
, SIGWINCH
);
2614 (void) ioctl(0, KDSIGACCEPT
, SIGWINCH
);
2618 * Ignore all signals.
2620 for(f
= 1; f
<= NSIG
; f
++)
2621 SETSIG(sa
, f
, SIG_IGN
, SA_RESTART
);
2624 SETSIG(sa
, SIGALRM
, signal_handler
, 0);
2625 SETSIG(sa
, SIGHUP
, signal_handler
, 0);
2626 SETSIG(sa
, SIGINT
, signal_handler
, 0);
2627 SETSIG(sa
, SIGCHLD
, chld_handler
, SA_RESTART
);
2628 SETSIG(sa
, SIGPWR
, signal_handler
, 0);
2629 SETSIG(sa
, SIGWINCH
, signal_handler
, 0);
2630 SETSIG(sa
, SIGUSR1
, signal_handler
, 0);
2631 SETSIG(sa
, SIGSTOP
, stop_handler
, SA_RESTART
);
2632 SETSIG(sa
, SIGTSTP
, stop_handler
, SA_RESTART
);
2633 SETSIG(sa
, SIGCONT
, cont_handler
, SA_RESTART
);
2634 SETSIG(sa
, SIGSEGV
, (void (*)(int))segv_handler
, SA_RESTART
);
2641 /* Close whatever files are open, and reset the console. */
2649 * Set default PATH variable.
2651 setenv("PATH", PATH_DEFAULT
, 1 /* Overwrite */);
2654 * Initialize /var/run/utmp (only works if /var is on
2655 * root and mounted rw)
2657 if ((fd
= open(UTMP_FILE
, O_WRONLY
|O_CREAT
|O_TRUNC
, 0644)) >= 0)
2661 * Say hello to the world
2663 initlog(L_CO
, bootmsg
, "booting");
2666 * See if we have to start an emergency shell.
2670 SETSIG(sa
, SIGCHLD
, SIG_DFL
, SA_RESTART
);
2671 if (spawn(&ch_emerg
, &f
) > 0) {
2672 while((rc
= wait(&st
)) != f
)
2673 if (rc
< 0 && errno
== ECHILD
)
2676 SETSIG(sa
, SIGCHLD
, chld_handler
, SA_RESTART
);
2680 * Start normal boot procedure.
2687 * Restart: unblock signals and let the show go on
2689 initlog(L_CO
, bootmsg
, "reloading");
2691 sigprocmask(SIG_UNBLOCK
, &sgt
, NULL
);
2694 * Set default PATH variable.
2696 setenv("PATH", PATH_DEFAULT
, 0 /* Don't overwrite */);
2702 /* See if we need to make the boot transitions. */
2704 INITDBG(L_VB
, "init_main: waiting..");
2706 /* Check if there are processes to be waited on. */
2707 for(ch
= family
; ch
; ch
= ch
->next
)
2708 if ((ch
->flags
& RUNNING
) && ch
->action
!= BOOT
) break;
2711 /* Wait until we get hit by some signal. */
2712 while (ch
!= NULL
&& got_signals
== 0) {
2713 if (ISMEMBER(got_signals
, SIGHUP
)) {
2714 /* See if there are processes to be waited on. */
2715 for(ch
= family
; ch
; ch
= ch
->next
)
2716 if (ch
->flags
& WAITING
) break;
2718 if (ch
!= NULL
) check_init_fifo();
2720 #else /* CHANGE_WAIT */
2721 if (ch
!= NULL
&& got_signals
== 0) check_init_fifo();
2722 #endif /* CHANGE_WAIT */
2724 /* Check the 'failing' flags */
2727 /* Process any signals. */
2730 /* See what we need to start up (again) */
2737 * Tell the user about the syntax we expect.
2742 fprintf(stderr
, "Usage: %s {-e VAR[=VAL] | [-t SECONDS] {0|1|2|3|4|5|6|S|s|Q|q|A|a|B|b|C|c|U|u}}\n", s
);
2747 int telinit(char *progname
, int argc
, char **argv
)
2749 #ifdef TELINIT_USES_INITLVL
2752 struct init_request request
;
2753 struct sigaction sa
;
2757 memset(&request
, 0, sizeof(request
));
2758 request
.magic
= INIT_MAGIC
;
2760 while ((f
= getopt(argc
, argv
, "t:e:")) != EOF
) switch(f
) {
2762 sltime
= atoi(optarg
);
2766 env
= request
.i
.data
;
2768 if (env
+ l
+ 2 > request
.i
.data
+ sizeof(request
.i
.data
)) {
2769 fprintf(stderr
, "%s: -e option data "
2770 "too large\n", progname
);
2773 memcpy(env
, optarg
, l
);
2782 if (env
) *env
++ = 0;
2787 request
.cmd
= INIT_CMD_SETENV
;
2789 if (argc
- optind
!= 1 || strlen(argv
[optind
]) != 1)
2791 if (!strchr("0123456789SsQqAaBbCcUu", argv
[optind
][0]))
2793 request
.cmd
= INIT_CMD_RUNLVL
;
2794 request
.runlevel
= argv
[optind
][0];
2795 request
.sleeptime
= sltime
;
2798 /* Change to the root directory. */
2799 if (0 != chdir("/"))
2800 initlog(L_VB
, "unable to chdir to /: %s",
2803 /* Open the fifo and write a command. */
2804 /* Make sure we don't hang on opening /dev/initctl */
2805 SETSIG(sa
, SIGALRM
, signal_handler
, 0);
2807 if ((fd
= open(INIT_FIFO
, O_WRONLY
)) >= 0) {
2809 size_t s
= sizeof(request
);
2810 void *ptr
= &request
;
2813 p
= write(fd
, ptr
, s
);
2815 if (errno
== EINTR
|| errno
== EAGAIN
)
2827 #ifdef TELINIT_USES_INITLVL
2828 if (request
.cmd
== INIT_CMD_RUNLVL
) {
2829 /* Fallthrough to the old method. */
2831 /* Now write the new runlevel. */
2832 if ((fp
= fopen(INITLVL
, "w")) == NULL
) {
2833 fprintf(stderr
, "%s: cannot create %s\n",
2837 fprintf(fp
, "%s %d", argv
[optind
], sltime
);
2840 /* And tell init about the pending runlevel change. */
2841 if (kill(INITPID
, SIGHUP
) < 0) perror(progname
);
2847 fprintf(stderr
, "%s: ", progname
);
2848 if (ISMEMBER(got_signals
, SIGALRM
)) {
2849 fprintf(stderr
, "timeout opening/writing control channel %s\n",
2858 * Main entry for init and telinit.
2860 int main(int argc
, char **argv
)
2869 /* Get my own name */
2870 if ((p
= strrchr(argv
[0], '/')) != NULL
)
2876 umask(umask(077) | 022);
2879 if (geteuid() != 0) {
2880 fprintf(stderr
, "%s: must be superuser.\n", p
);
2885 * Is this telinit or init ?
2887 isinit
= (getpid() == 1);
2888 for (f
= 1; f
< argc
; f
++) {
2889 if (!strcmp(argv
[f
], "-i") || !strcmp(argv
[f
], "--init")) {
2894 if (!isinit
) exit(telinit(p
, argc
, argv
));
2899 if (check_pipe(STATE_PIPE
)) {
2901 receive_state(STATE_PIPE
);
2903 myname
= istrdup(argv
[0]);
2906 for (f
= 0; f
< argc
; f
++)
2907 maxproclen
+= strlen(argv
[f
]) + 1;
2909 setproctitle("init [%c]", (int)runlevel
);
2914 /* Check command line arguments */
2915 maxproclen
= strlen(argv
[0]) + 1;
2916 for(f
= 1; f
< argc
; f
++) {
2917 if (!strcmp(argv
[f
], "single") || !strcmp(argv
[f
], "-s"))
2919 else if (!strcmp(argv
[f
], "-a") || !strcmp(argv
[f
], "auto"))
2920 putenv("AUTOBOOT=YES");
2921 else if (!strcmp(argv
[f
], "-b") || !strcmp(argv
[f
],"emergency"))
2923 else if (!strcmp(argv
[f
], "-z")) {
2925 if (argv
[f
+ 1]) f
++;
2926 } else if (strchr("0123456789sS", argv
[f
][0])
2927 && strlen(argv
[f
]) == 1)
2928 dfl_level
= argv
[f
][0];
2929 /* "init u" in the very beginning makes no sense */
2930 if (dfl_level
== 's') dfl_level
= 'S';
2931 maxproclen
+= strlen(argv
[f
]) + 1;
2935 if (getenv("SELINUX_INIT") == NULL
) {
2936 if (is_selinux_enabled() != 1) {
2937 if (selinux_init_load_policy(&enforce
) == 0) {
2938 putenv("SELINUX_INIT=YES");
2939 execv(myname
, argv
);
2942 /* SELinux in enforcing mode but load_policy failed */
2943 /* At this point, we probably can't open /dev/console, so log() won't work */
2944 fprintf(stderr
,"Unable to load SELinux Policy. Machine is in enforcing mode. Halting now.\n");
2951 /* Start booting. */
2954 setproctitle("init boot");