]>
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
) {
1104 int ftty
; /* Handler for tty controlling */
1106 * We fork once extra. This is so that we can
1107 * wait and change the process group and session
1108 * of the console after exit of the leader.
1111 if ((ftty
= console_open(O_RDWR
|O_NOCTTY
)) >= 0) {
1112 /* Take over controlling tty by force */
1113 (void)ioctl(ftty
, TIOCSCTTY
, 1);
1116 initlog(L_VB
, "cannot duplicate console fd");
1120 initlog(L_VB
, "cannot duplicate console fd");
1126 * 4 Sep 2001, Andrea Arcangeli:
1127 * Fix a race in spawn() that is used to deadlock init in a
1128 * waitpid() loop: must set the childhandler as default before forking
1129 * off the child or the chld_handler could run before the waitpid loop
1130 * has a chance to find its zombie-child.
1132 SETSIG(sa
, SIGCHLD
, SIG_DFL
, SA_RESTART
);
1133 if ((pid
= fork()) < 0) {
1134 initlog(L_VB
, "cannot fork: %s",
1141 * Ignore keyboard signals etc.
1142 * Then wait for child to exit.
1144 SETSIG(sa
, SIGINT
, SIG_IGN
, SA_RESTART
);
1145 SETSIG(sa
, SIGTSTP
, SIG_IGN
, SA_RESTART
);
1146 SETSIG(sa
, SIGQUIT
, SIG_IGN
, SA_RESTART
);
1148 while ((rc
= waitpid(pid
, &st
, 0)) != pid
)
1149 if (rc
< 0 && errno
== ECHILD
)
1153 * Small optimization. See if stealing
1154 * controlling tty back is needed.
1156 pgrp
= tcgetpgrp(ftty
);
1157 if (pgrp
!= getpid())
1161 * Steal controlling tty away. We do
1162 * this with a temporary process.
1164 if ((pid
= fork()) < 0) {
1165 initlog(L_VB
, "cannot fork: %s",
1171 (void)ioctl(ftty
, TIOCSCTTY
, 1);
1174 while((rc
= waitpid(pid
, &st
, 0)) != pid
)
1175 if (rc
< 0 && errno
== ECHILD
)
1180 /* Set ioctl settings to default ones */
1183 } else { /* parent */
1186 if ((fd
= console_open(O_RDWR
|O_NOCTTY
)) < 0) {
1187 initlog(L_VB
, "open(%s): %s", console_dev
,
1189 fd
= open("/dev/null", O_RDWR
);
1193 initlog(L_VB
, "cannot duplicate /dev/null fd");
1197 initlog(L_VB
, "cannot duplicate /dev/null fd");
1203 * Update utmp/wtmp file prior to starting
1204 * any child. This MUST be done right here in
1205 * the child process in order to prevent a race
1206 * condition that occurs when the child
1207 * process' time slice executes before the
1208 * parent (can and does happen in a uniprocessor
1209 * environment). If the child is a getty and
1210 * the race condition happens, then init's utmp
1211 * update will happen AFTER the getty runs
1212 * and expects utmp to be updated already!
1214 * Do NOT log if process field starts with '+'
1215 * FIXME: that's for compatibility with *very*
1216 * old getties - probably it can be taken out.
1218 if (ch
->process
[0] != '+')
1219 write_utmp_wtmp("", ch
->id
, getpid(), INIT_PROCESS
, "");
1221 /* Reset all the signals, set up environment */
1222 for(f
= 1; f
< NSIG
; f
++) SETSIG(sa
, f
, SIG_DFL
, SA_RESTART
);
1223 environ
= init_buildenv(1);
1226 * Execute prog. In case of ENOEXEC try again
1227 * as a shell script.
1229 execvp(args
[1], args
+ 1);
1230 if (errno
== ENOEXEC
) {
1233 strcpy(buf
, "exec ");
1234 strncat(buf
, proc
, sizeof(buf
) - strlen(buf
) - 1);
1237 execvp(args
[1], args
+ 1);
1239 initlog(L_VB
, "cannot execute \"%s\"", args
[1]);
1241 if (ch
->process
[0] != '+')
1242 write_utmp_wtmp("", ch
->id
, getpid(), DEAD_PROCESS
, NULL
);
1246 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
1248 INITDBG(L_VB
, "Started id %s (pid %d)", ch
->id
, pid
);
1251 initlog(L_VB
, "cannot fork, retry..");
1260 * Start a child running!
1263 void startup(CHILD
*ch
)
1266 * See if it's disabled
1268 if (ch
->flags
& FAILING
) return;
1270 switch(ch
->action
) {
1279 if (!(ch
->flags
& XECUTED
)) ch
->flags
|= WAITING
;
1285 if (ch
->flags
& XECUTED
) break;
1288 ch
->flags
|= RUNNING
;
1289 (void)spawn(ch
, &(ch
->pid
));
1296 * Read the inittab file.
1299 void read_inittab(void)
1301 FILE *fp
; /* The INITTAB file */
1302 CHILD
*ch
, *old
, *i
; /* Pointers to CHILD structure */
1303 CHILD
*head
= NULL
; /* Head of linked list */
1305 struct stat st
; /* To stat INITLVL */
1307 sigset_t nmask
, omask
; /* For blocking SIGCHLD. */
1308 char buf
[256]; /* Line buffer */
1309 char err
[64]; /* Error message. */
1311 *action
, *process
; /* Fields of a line */
1313 int lineNo
= 0; /* Line number in INITTAB file */
1314 int actionNo
; /* Decoded action field */
1315 int f
; /* Counter */
1316 int round
; /* round 0 for SIGTERM, 1 for SIGKILL */
1317 int foundOne
= 0; /* No killing no sleep */
1318 int talk
; /* Talk to the user */
1319 int done
= 0; /* Ready yet? */
1322 if (newFamily
!= NULL
) {
1323 INITDBG(L_VB
, "PANIC newFamily != NULL");
1326 INITDBG(L_VB
, "Reading inittab");
1330 * Open INITTAB and read line by line.
1332 if ((fp
= fopen(INITTAB
, "r")) == NULL
)
1333 initlog(L_VB
, "No inittab file found");
1337 * Add single user shell entry at the end.
1339 if (fp
== NULL
|| fgets(buf
, sizeof(buf
), fp
) == NULL
) {
1342 * See if we have a single user entry.
1344 for(old
= newFamily
; old
; old
= old
->next
)
1345 if (strpbrk(old
->rlevel
, "S")) break;
1347 snprintf(buf
, sizeof(buf
), "~~:S:wait:%s\n", SULOGIN
);
1353 * Skip comments and empty lines
1355 for(p
= buf
; *p
== ' ' || *p
== '\t'; p
++)
1357 if (*p
== '#' || *p
== '\n') continue;
1362 id
= strsep(&p
, ":");
1363 rlevel
= strsep(&p
, ":");
1364 action
= strsep(&p
, ":");
1365 process
= strsep(&p
, "\n");
1368 * Check if syntax is OK. Be very verbose here, to
1369 * avoid newbie postings on comp.os.linux.setup :)
1372 if (!id
|| !*id
) strcpy(err
, "missing id field");
1373 if (!rlevel
) strcpy(err
, "missing runlevel field");
1374 if (!process
) strcpy(err
, "missing process field");
1375 if (!action
|| !*action
)
1376 strcpy(err
, "missing action field");
1377 if (id
&& strlen(id
) > sizeof(utproto
.ut_id
))
1378 sprintf(err
, "id field too long (max %d characters)",
1379 (int)sizeof(utproto
.ut_id
));
1380 if (rlevel
&& strlen(rlevel
) > 11)
1381 strcpy(err
, "rlevel field too long (max 11 characters)");
1382 if (process
&& strlen(process
) > 127)
1383 strcpy(err
, "process field too long (max 127 characters)");
1384 if (action
&& strlen(action
) > 32)
1385 strcpy(err
, "action field too long");
1387 initlog(L_VB
, "%s[%d]: %s", INITTAB
, lineNo
, err
);
1388 INITDBG(L_VB
, "%s:%s:%s:%s", id
, rlevel
, action
, process
);
1393 * Decode the "action" field
1396 for(f
= 0; actions
[f
].name
; f
++)
1397 if (strcasecmp(action
, actions
[f
].name
) == 0) {
1398 actionNo
= actions
[f
].act
;
1401 if (actionNo
== -1) {
1402 initlog(L_VB
, "%s[%d]: %s: unknown action field",
1403 INITTAB
, lineNo
, action
);
1408 * See if the id field is unique
1410 for(old
= newFamily
; old
; old
= old
->next
) {
1411 if(strcmp(old
->id
, id
) == 0 && strcmp(id
, "~~")) {
1412 initlog(L_VB
, "%s[%d]: duplicate ID field \"%s\"",
1413 INITTAB
, lineNo
, id
);
1420 * Allocate a CHILD structure
1422 ch
= imalloc(sizeof(CHILD
));
1427 ch
->action
= actionNo
;
1428 strncpy(ch
->id
, id
, sizeof(utproto
.ut_id
) + 1); /* Hack for different libs. */
1429 strncpy(ch
->process
, process
, sizeof(ch
->process
) - 1);
1431 for(f
= 0; f
< (int)sizeof(rlevel
) - 1 && rlevel
[f
]; f
++) {
1432 ch
->rlevel
[f
] = rlevel
[f
];
1433 if (ch
->rlevel
[f
] == 's') ch
->rlevel
[f
] = 'S';
1435 strncpy(ch
->rlevel
, rlevel
, sizeof(ch
->rlevel
) - 1);
1437 strcpy(ch
->rlevel
, "0123456789");
1438 if (ISPOWER(ch
->action
))
1439 strcpy(ch
->rlevel
, "S0123456789");
1442 * We have the fake runlevel '#' for SYSINIT and
1443 * '*' for BOOT and BOOTWAIT.
1445 if (ch
->action
== SYSINIT
) strcpy(ch
->rlevel
, "#");
1446 if (ch
->action
== BOOT
|| ch
->action
== BOOTWAIT
)
1447 strcpy(ch
->rlevel
, "*");
1450 * Now add it to the linked list. Special for powerfail.
1452 if (ISPOWER(ch
->action
)) {
1455 * Disable by default
1457 ch
->flags
|= XECUTED
;
1460 * Tricky: insert at the front of the list..
1463 for(i
= newFamily
; i
; i
= i
->next
) {
1464 if (!ISPOWER(i
->action
)) break;
1468 * Now add after entry "old"
1473 if (i
== NULL
) head
= ch
;
1475 ch
->next
= newFamily
;
1477 if (ch
->next
== NULL
) head
= ch
;
1481 * Just add at end of the list
1483 if (ch
->action
== KBREQUEST
) ch
->flags
|= XECUTED
;
1493 * Walk through the old list comparing id fields
1495 for(old
= family
; old
; old
= old
->next
)
1496 if (strcmp(old
->id
, ch
->id
) == 0) {
1507 * Loop through the list of children, and see if they need to
1511 INITDBG(L_VB
, "Checking for children to kill");
1512 for(round
= 0; round
< 2; round
++) {
1514 for(ch
= family
; ch
; ch
= ch
->next
) {
1515 ch
->flags
&= ~KILLME
;
1518 * Is this line deleted?
1520 if (ch
->new == NULL
) ch
->flags
|= KILLME
;
1523 * If the entry has changed, kill it anyway. Note that
1524 * we do not check ch->process, only the "action" field.
1525 * This way, you can turn an entry "off" immediately, but
1526 * changes in the command line will only become effective
1527 * after the running version has exited.
1529 if (ch
->new && ch
->action
!= ch
->new->action
) ch
->flags
|= KILLME
;
1532 * Only BOOT processes may live in all levels
1534 if (ch
->action
!= BOOT
&&
1535 strchr(ch
->rlevel
, runlevel
) == NULL
) {
1537 * Ondemand procedures live always,
1538 * except in single user
1540 if (runlevel
== 'S' || !(ch
->flags
& DEMAND
))
1541 ch
->flags
|= KILLME
;
1545 * Now, if this process may live note so in the new list
1547 if ((ch
->flags
& KILLME
) == 0) {
1548 ch
->new->flags
= ch
->flags
;
1549 ch
->new->pid
= ch
->pid
;
1550 ch
->new->exstat
= ch
->exstat
;
1556 * Is this process still around?
1558 if ((ch
->flags
& RUNNING
) == 0) {
1559 ch
->flags
&= ~KILLME
;
1562 INITDBG(L_VB
, "Killing \"%s\"", ch
->process
);
1564 case 0: /* Send TERM signal */
1567 "Sending processes configured via /etc/inittab the TERM signal");
1568 kill(-(ch
->pid
), SIGTERM
);
1571 case 1: /* Send KILL signal and collect status */
1574 "Sending processes configured via /etc/inittab the KILL signal");
1575 kill(-(ch
->pid
), SIGKILL
);
1582 * See if we have to wait 5 seconds
1584 if (foundOne
&& round
== 0) {
1586 * Yup, but check every second if we still have children.
1588 for(f
= 0; f
< sltime
; f
++) {
1589 for(ch
= family
; ch
; ch
= ch
->next
) {
1590 if (!(ch
->flags
& KILLME
)) continue;
1591 if ((ch
->flags
& RUNNING
) && !(ch
->flags
& ZOMBIE
))
1596 * No running children, skip SIGKILL
1599 foundOne
= 0; /* Skip the sleep below. */
1608 * Now give all processes the chance to die and collect exit statuses.
1610 if (foundOne
) do_sleep(1);
1611 for(ch
= family
; ch
; ch
= ch
->next
)
1612 if (ch
->flags
& KILLME
) {
1613 if (!(ch
->flags
& ZOMBIE
))
1614 initlog(L_CO
, "Pid %d [id %s] seems to hang", ch
->pid
,
1617 INITDBG(L_VB
, "Updating utmp for pid %d [id %s]",
1619 ch
->flags
&= ~RUNNING
;
1620 if (ch
->process
[0] != '+')
1621 write_utmp_wtmp("", ch
->id
, ch
->pid
, DEAD_PROCESS
, NULL
);
1626 * Both rounds done; clean up the list.
1628 sigemptyset(&nmask
);
1629 sigaddset(&nmask
, SIGCHLD
);
1630 sigprocmask(SIG_BLOCK
, &nmask
, &omask
);
1631 for(ch
= family
; ch
; ch
= old
) {
1636 for(ch
= family
; ch
; ch
= ch
->next
) ch
->new = NULL
;
1638 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
1642 * Dispose of INITLVL file.
1644 if (lstat(INITLVL
, &st
) >= 0 && S_ISLNK(st
.st_mode
)) {
1646 * INITLVL is a symbolic link, so just truncate the file.
1648 close(open(INITLVL
, O_WRONLY
|O_TRUNC
));
1651 * Delete INITLVL file.
1658 * Dispose of INITLVL2 file.
1660 if (lstat(INITLVL2
, &st
) >= 0 && S_ISLNK(st
.st_mode
)) {
1662 * INITLVL2 is a symbolic link, so just truncate the file.
1664 close(open(INITLVL2
, O_WRONLY
|O_TRUNC
));
1667 * Delete INITLVL2 file.
1675 * Walk through the family list and start up children.
1676 * The entries that do not belong here at all are removed
1680 void start_if_needed(void)
1682 CHILD
*ch
; /* Pointer to child */
1683 int delete; /* Delete this entry from list? */
1685 INITDBG(L_VB
, "Checking for children to start");
1687 for(ch
= family
; ch
; ch
= ch
->next
) {
1690 if (ch
->rlevel
[0] == 'C') {
1691 INITDBG(L_VB
, "%s: flags %d", ch
->process
, ch
->flags
);
1695 /* Are we waiting for this process? Then quit here. */
1696 if (ch
->flags
& WAITING
) break;
1698 /* Already running? OK, don't touch it */
1699 if (ch
->flags
& RUNNING
) continue;
1701 /* See if we have to start it up */
1703 if (strchr(ch
->rlevel
, runlevel
) ||
1704 ((ch
->flags
& DEMAND
) && !strchr("#*Ss", runlevel
))) {
1710 /* FIXME: is this OK? */
1711 ch
->flags
&= ~(RUNNING
|WAITING
);
1712 if (!ISPOWER(ch
->action
) && ch
->action
!= KBREQUEST
)
1713 ch
->flags
&= ~XECUTED
;
1716 /* Do we have to wait for this process? */
1717 if (ch
->flags
& WAITING
) break;
1723 * Ask the user on the console for a runlevel
1726 int ask_runlevel(void)
1728 const char prompt
[] = "\nEnter runlevel: ";
1734 fd
= console_open(O_RDWR
|O_NOCTTY
);
1736 if (fd
< 0) return('S');
1738 while(!strchr("0123456789S", lvl
)) {
1739 safe_write(fd
, prompt
, sizeof(prompt
) - 1);
1740 if (read(fd
, buf
, sizeof(buf
)) <= 0)
1742 if (buf
[0] != 0 && (buf
[1] == '\r' || buf
[1] == '\n'))
1744 if (islower(lvl
)) lvl
= toupper(lvl
);
1751 * Search the INITTAB file for the 'initdefault' field, with the default
1752 * runlevel. If this fails, ask the user to supply a runlevel.
1755 int get_init_default(void)
1762 * Look for initdefault.
1764 for(ch
= family
; ch
; ch
= ch
->next
)
1765 if (ch
->action
== INITDEFAULT
) {
1768 if (*p
> lvl
) lvl
= *p
;
1774 * See if level is valid
1777 if (islower(lvl
)) lvl
= toupper(lvl
);
1778 if (strchr("0123456789S", lvl
) == NULL
) {
1780 "Initdefault level '%c' is invalid", lvl
);
1785 * Ask for runlevel on console if needed.
1787 if (lvl
<= 0) lvl
= ask_runlevel();
1790 * Log the fact that we have a runlevel now.
1799 * Do actions for the new level. If we are compatible with
1800 * the "old" INITLVL and arg == 0, try to read the new
1801 * runlevel from that file first.
1804 int read_level(int arg
)
1806 CHILD
*ch
; /* Walk through list */
1807 unsigned char foo
= 'X'; /* Contents of INITLVL */
1822 if (stat(INITLVL
, &stt
) != 0 || stt
.st_size
!= 0L)
1823 fp
= fopen(INITLVL
, "r");
1826 (stat(INITLVL2
, &stt
) != 0 || stt
.st_size
!= 0L))
1827 fp
= fopen(INITLVL2
, "r");
1830 /* INITLVL file empty or not there - act as 'init q' */
1831 initlog(L_SY
, "Re-reading inittab");
1834 ok
= fscanf(fp
, "%c %d", &foo
, &st
);
1837 /* We go to the new runlevel passed as an argument. */
1841 if (ok
== 2) sltime
= st
;
1843 #endif /* INITLVL */
1845 if (islower(foo
)) foo
= toupper(foo
);
1846 if (ok
< 1 || ok
> 2 || strchr("QS0123456789ABCU", foo
) == NULL
) {
1847 initlog(L_VB
, "bad runlevel: %c", foo
);
1851 /* Log this action */
1854 initlog(L_VB
, "Going single user");
1857 initlog(L_SY
, "Re-reading inittab");
1863 "Activating demand-procedures for '%c'", foo
);
1866 initlog(L_SY
, "Trying to re-exec init");
1869 initlog(L_VB
, "Switching to runlevel: %c", foo
);
1873 #if defined(SIGINT_ONLYONCE) && (SIGINT_ONLYONCE == 1)
1874 /* Re-enable signal from keyboard */
1875 struct sigaction sa
;
1876 SETSIG(sa
, SIGINT
, signal_handler
, 0);
1881 /* Check if this is a runlevel a, b or c */
1882 if (strchr("ABC", foo
)) {
1883 if (runlevel
== 'S') return(runlevel
);
1885 /* Read inittab again first! */
1888 /* Mark those special tasks */
1889 for(ch
= family
; ch
; ch
= ch
->next
)
1890 if (strchr(ch
->rlevel
, foo
) != NULL
||
1891 strchr(ch
->rlevel
, tolower(foo
)) != NULL
) {
1892 ch
->flags
|= DEMAND
;
1893 ch
->flags
&= ~XECUTED
;
1895 "Marking (%s) as ondemand, flags %d",
1901 /* Store both the old and the new runlevel. */
1902 wrote_utmp_rlevel
= 0;
1903 wrote_wtmp_rlevel
= 0;
1904 write_utmp_wtmp("runlevel", "~~", foo
+ 256*runlevel
, RUN_LVL
, "~");
1906 prevlevel
= runlevel
;
1912 * This procedure is called after every signal (SIGHUP, SIGALRM..)
1914 * Only clear the 'failing' flag if the process is sleeping
1915 * longer than 5 minutes, or inittab was read again due
1916 * to user interaction.
1919 void fail_check(void)
1921 CHILD
*ch
; /* Pointer to child structure */
1922 time_t t
; /* System time */
1923 time_t next_alarm
= 0; /* When to set next alarm */
1927 for(ch
= family
; ch
; ch
= ch
->next
) {
1929 if (ch
->flags
& FAILING
) {
1930 /* Can we free this sucker? */
1931 if (ch
->tm
+ SLEEPTIME
< t
) {
1932 ch
->flags
&= ~FAILING
;
1936 /* No, we'll look again later */
1937 if (next_alarm
== 0 ||
1938 ch
->tm
+ SLEEPTIME
> next_alarm
)
1939 next_alarm
= ch
->tm
+ SLEEPTIME
;
1945 if (next_alarm
< 1) next_alarm
= 1;
1950 /* Set all 'Fail' timers to 0 */
1952 void fail_cancel(void)
1956 for(ch
= family
; ch
; ch
= ch
->next
) {
1959 ch
->flags
&= ~FAILING
;
1964 * Start up powerfail entries.
1967 void do_power_fail(int pwrstat
)
1972 * Tell powerwait & powerfail entries to start up
1974 for (ch
= family
; ch
; ch
= ch
->next
) {
1975 if (pwrstat
== 'O') {
1977 * The power is OK again.
1979 if (ch
->action
== POWEROKWAIT
)
1980 ch
->flags
&= ~XECUTED
;
1981 } else if (pwrstat
== 'L') {
1983 * Low battery, shut down now.
1985 if (ch
->action
== POWERFAILNOW
)
1986 ch
->flags
&= ~XECUTED
;
1989 * Power is failing, shutdown imminent
1991 if (ch
->action
== POWERFAIL
|| ch
->action
== POWERWAIT
)
1992 ch
->flags
&= ~XECUTED
;
1998 * Check for state-pipe presence
2001 int check_pipe(int fd
)
2009 t
.tv_sec
= t
.tv_usec
= 0;
2011 if (select(fd
+1, &s
, NULL
, NULL
, &t
) != 1)
2013 if (read(fd
, signature
, 8) != 8)
2015 return strncmp(Signature
, signature
, 8) == 0;
2019 * Make a state-pipe.
2022 int make_pipe(int fd
)
2027 initlog(L_VB
, "pipe: %m");
2032 fcntl(fds
[1], F_SETFD
, 1);
2033 fcntl(fd
, F_SETFD
, 0);
2034 safe_write(fds
[1], Signature
, 8);
2040 * Attempt to re-exec.
2046 sigset_t mask
, oldset
;
2051 if (strchr("S0123456",runlevel
) == NULL
)
2055 * Reset the alarm, and block all signals.
2059 sigprocmask(SIG_BLOCK
, &mask
, &oldset
);
2062 * construct a pipe fd --> STATE_PIPE and write a signature
2064 if ((fd
= make_pipe(STATE_PIPE
)) < 0) {
2065 sigprocmask(SIG_SETMASK
, &oldset
, NULL
);
2066 initlog(L_CO
, "Attempt to re-exec failed");
2070 * It's a backup day today, so I'm pissed off. Being a BOFH, however,
2071 * does have it's advantages...
2076 DELSET(got_signals
, SIGCHLD
);
2077 DELSET(got_signals
, SIGHUP
);
2078 DELSET(got_signals
, SIGUSR1
);
2081 * That should be cleaned.
2083 for(ch
= family
; ch
; ch
= ch
->next
)
2084 if (ch
->flags
& ZOMBIE
) {
2085 INITDBG(L_VB
, "Child died, PID= %d", ch
->pid
);
2086 ch
->flags
&= ~(RUNNING
|ZOMBIE
|WAITING
);
2087 if (ch
->process
[0] != '+')
2088 write_utmp_wtmp("", ch
->id
, ch
->pid
, DEAD_PROCESS
, NULL
);
2091 if ((pid
= fork()) == 0) {
2093 * Child sends state information to the parent.
2100 * The existing init process execs a new init binary.
2102 env
= init_buildenv(0);
2103 execle(myname
, myname
, "--init", NULL
, env
);
2106 * We shouldn't be here, something failed.
2107 * Bitch, close the state pipe, unblock signals and return.
2112 sigprocmask(SIG_SETMASK
, &oldset
, NULL
);
2113 initlog(L_CO
, "Attempt to re-exec failed");
2117 * Redo utmp/wtmp entries if required or requested
2118 * Check for written records and size of utmp
2121 void redo_utmp_wtmp(void)
2124 const int ret
= stat(UTMP_FILE
, &ustat
);
2126 if ((ret
< 0) || (ustat
.st_size
== 0))
2127 wrote_utmp_rlevel
= wrote_utmp_reboot
= 0;
2129 if ((wrote_wtmp_reboot
== 0) || (wrote_utmp_reboot
== 0))
2130 write_utmp_wtmp("reboot", "~~", 0, BOOT_TIME
, "~");
2132 if ((wrote_wtmp_rlevel
== 0) || (wrote_wtmp_rlevel
== 0))
2133 write_utmp_wtmp("runlevel", "~~", thislevel
+ 256 * prevlevel
, RUN_LVL
, "~");
2137 * We got a change runlevel request through the
2138 * init.fifo. Process it.
2141 void fifo_new_level(int level
)
2148 if (level
== runlevel
) return;
2151 /* Are we waiting for a child? */
2152 for(ch
= family
; ch
; ch
= ch
->next
)
2153 if (ch
->flags
& WAITING
) break;
2157 /* We need to go into a new runlevel */
2158 oldlevel
= runlevel
;
2159 runlevel
= read_level(level
);
2160 if (runlevel
== 'U') {
2161 runlevel
= oldlevel
;
2164 if (oldlevel
!= 'S' && runlevel
== 'S') console_stty();
2165 if (runlevel
== '6' || runlevel
== '0' ||
2166 runlevel
== '1') console_stty();
2167 if (runlevel
> '1' && runlevel
< '6') redo_utmp_wtmp();
2170 setproctitle("init [%c]", (int)runlevel
);
2177 * Set/unset environment variables. The variables are
2178 * encoded as KEY=VAL\0KEY=VAL\0\0. With "=VAL" it means
2179 * setenv, without it means unsetenv.
2182 void initcmd_setenv(char *data
, int size
)
2190 while (*data
&& data
< e
) {
2191 for (p
= data
; *p
&& p
< e
; p
++)
2198 * We only allow INIT_* to be set.
2200 if (strncmp(env
, "INIT_", 5) != 0)
2203 sz
= strcspn(env
, "=");
2204 eq
= (env
[sz
] == '=');
2206 /*initlog(L_SY, "init_setenv: %s, %d, %d", env, eq, sz);*/
2208 /* Free existing vars. */
2209 for (i
= 0; i
< NR_EXTRA_ENV
; i
++) {
2210 if (extra_env
[i
] == NULL
)
2212 if (sz
!= strcspn(extra_env
[i
], "="))
2214 if (strncmp(extra_env
[i
], env
, sz
) == 0) {
2216 extra_env
[i
] = NULL
;
2223 /* Set new vars if needed. */
2224 for (i
= 0; i
< NR_EXTRA_ENV
; i
++) {
2225 if (extra_env
[i
] == NULL
) {
2226 extra_env
[i
] = istrdup(env
);
2235 * Read from the init FIFO. Processes like telnetd and rlogind can
2236 * ask us to create login processes on their behalf.
2238 * FIXME: this needs to be finished. NOT that it is buggy, but we need
2239 * to add the telnetd/rlogind stuff so people can start using it.
2240 * Maybe move to using an AF_UNIX socket so we can use
2241 * the 2.2 kernel credential stuff to see who we're talking to.
2245 void check_init_fifo(void)
2247 struct init_request request
;
2249 struct stat st
, st2
;
2255 * First, try to create /dev/initctl if not present.
2257 if (stat(INIT_FIFO
, &st2
) < 0 && errno
== ENOENT
)
2258 (void)mkfifo(INIT_FIFO
, 0600);
2261 * If /dev/initctl is open, stat the file to see if it
2262 * is still the _same_ inode.
2265 fstat(pipe_fd
, &st
);
2266 if (stat(INIT_FIFO
, &st2
) < 0 ||
2267 st
.st_dev
!= st2
.st_dev
||
2268 st
.st_ino
!= st2
.st_ino
) {
2275 * Now finally try to open /dev/initctl
2278 if ((pipe_fd
= open(INIT_FIFO
, O_RDWR
|O_NONBLOCK
)) >= 0) {
2279 fstat(pipe_fd
, &st
);
2280 if (!S_ISFIFO(st
.st_mode
)) {
2281 initlog(L_VB
, "%s is not a fifo", INIT_FIFO
);
2288 * Don't use fd's 0, 1 or 2.
2290 (void) dup2(pipe_fd
, PIPE_FD
);
2295 * Return to caller - we'll be back later.
2300 /* Wait for data to appear, _if_ the pipe was opened. */
2301 if (pipe_fd
>= 0) while(!quit
) {
2303 /* Do select, return on EINTR. */
2305 FD_SET(pipe_fd
, &fds
);
2308 n
= select(pipe_fd
+ 1, &fds
, NULL
, NULL
, &tv
);
2310 if (n
== 0 || errno
== EINTR
) return;
2314 /* Read the data, return on EINTR. */
2315 n
= read(pipe_fd
, &request
, sizeof(request
));
2318 * End of file. This can't happen under Linux (because
2319 * the pipe is opened O_RDWR - see select() in the
2320 * kernel) but you never know...
2327 if (errno
== EINTR
) return;
2328 initlog(L_VB
, "error reading initrequest");
2333 * This is a convenient point to also try to
2334 * find the console device or check if it changed.
2341 if (request
.magic
!= INIT_MAGIC
|| n
!= sizeof(request
)) {
2342 initlog(L_VB
, "got bogus initrequest");
2345 switch(request
.cmd
) {
2346 case INIT_CMD_RUNLVL
:
2347 sltime
= request
.sleeptime
;
2348 fifo_new_level(request
.runlevel
);
2351 case INIT_CMD_POWERFAIL
:
2352 sltime
= request
.sleeptime
;
2356 case INIT_CMD_POWERFAILNOW
:
2357 sltime
= request
.sleeptime
;
2361 case INIT_CMD_POWEROK
:
2362 sltime
= request
.sleeptime
;
2366 case INIT_CMD_SETENV
:
2367 initcmd_setenv(request
.i
.data
, sizeof(request
.i
.data
));
2370 initlog(L_VB
, "got unimplemented initrequest.");
2376 * We come here if the pipe couldn't be opened.
2378 if (pipe_fd
< 0) pause();
2384 * This function is used in the transition
2385 * sysinit (-> single user) boot -> multi-user.
2388 void boot_transitions()
2391 static int newlevel
= 0;
2392 static int warn
= 1;
2396 /* Check if there is something to wait for! */
2397 for( ch
= family
; ch
; ch
= ch
->next
)
2398 if ((ch
->flags
& RUNNING
) && ch
->action
!= BOOT
) break;
2401 /* No processes left in this level, proceed to next level. */
2405 case '#': /* SYSINIT -> BOOT */
2406 INITDBG(L_VB
, "SYSINIT -> BOOT");
2408 /* Write a boot record. */
2409 wrote_utmp_reboot
= 0;
2410 wrote_wtmp_reboot
= 0;
2411 write_utmp_wtmp("reboot", "~~", 0, BOOT_TIME
, "~");
2413 /* Get our run level */
2414 newlevel
= dfl_level
? dfl_level
: get_init_default();
2415 if (newlevel
== 'S') {
2416 runlevel
= newlevel
;
2417 /* Not really 'S' but show anyway. */
2418 setproctitle("init [S]");
2422 case '*': /* BOOT -> NORMAL */
2423 INITDBG(L_VB
, "BOOT -> NORMAL");
2424 if (runlevel
!= newlevel
)
2425 loglevel
= newlevel
;
2426 runlevel
= newlevel
;
2430 case 'S': /* Ended SU mode */
2432 INITDBG(L_VB
, "END SU MODE");
2433 newlevel
= get_init_default();
2434 if (!did_boot
&& newlevel
!= 'S')
2437 if (runlevel
!= newlevel
)
2438 loglevel
= newlevel
;
2439 runlevel
= newlevel
;
2443 for(ch
= family
; ch
; ch
= ch
->next
)
2444 if (strcmp(ch
->rlevel
, "S") == 0)
2445 ch
->flags
&= ~(FAILING
|WAITING
|XECUTED
);
2450 "no more processes left in this runlevel");
2453 if (got_signals
== 0)
2458 initlog(L_VB
, "Entering runlevel: %c", runlevel
);
2459 wrote_utmp_rlevel
= 0;
2460 wrote_wtmp_rlevel
= 0;
2461 write_utmp_wtmp("runlevel", "~~", runlevel
+ 256 * oldlevel
, RUN_LVL
, "~");
2462 thislevel
= runlevel
;
2463 prevlevel
= oldlevel
;
2464 setproctitle("init [%c]", (int)runlevel
);
2470 * Init got hit by a signal. See which signal it is,
2471 * and act accordingly.
2474 void process_signals()
2482 if (ISMEMBER(got_signals
, SIGPWR
)) {
2483 INITDBG(L_VB
, "got SIGPWR");
2484 /* See _what_ kind of SIGPWR this is. */
2486 if ((fd
= open(PWRSTAT
, O_RDONLY
)) >= 0) {
2487 if (read(fd
, &c
, 1) != 1)
2492 } else if ((fd
= open(PWRSTAT_OLD
, O_RDONLY
)) >= 0) {
2493 /* Path changed 2010-03-20. Look for the old path for a while. */
2494 initlog(L_VB
, "warning: found obsolete path %s, use %s instead",
2495 PWRSTAT_OLD
, PWRSTAT
);
2496 if (read(fd
, &c
, 1) != 1)
2500 unlink(PWRSTAT_OLD
);
2502 do_power_fail(pwrstat
);
2503 DELSET(got_signals
, SIGPWR
);
2506 if (ISMEMBER(got_signals
, SIGINT
)) {
2507 #if defined(SIGINT_ONLYONCE) && (SIGINT_ONLYONCE == 1)
2508 /* Ignore any further signal from keyboard */
2509 struct sigaction sa
;
2510 SETSIG(sa
, SIGINT
, SIG_IGN
, SA_RESTART
);
2512 INITDBG(L_VB
, "got SIGINT");
2513 /* Tell ctrlaltdel entry to start up */
2514 for(ch
= family
; ch
; ch
= ch
->next
)
2515 if (ch
->action
== CTRLALTDEL
)
2516 ch
->flags
&= ~XECUTED
;
2517 DELSET(got_signals
, SIGINT
);
2520 if (ISMEMBER(got_signals
, SIGWINCH
)) {
2521 INITDBG(L_VB
, "got SIGWINCH");
2522 /* Tell kbrequest entry to start up */
2523 for(ch
= family
; ch
; ch
= ch
->next
)
2524 if (ch
->action
== KBREQUEST
)
2525 ch
->flags
&= ~XECUTED
;
2526 DELSET(got_signals
, SIGWINCH
);
2529 if (ISMEMBER(got_signals
, SIGALRM
)) {
2530 INITDBG(L_VB
, "got SIGALRM");
2531 /* The timer went off: check it out */
2532 DELSET(got_signals
, SIGALRM
);
2535 if (ISMEMBER(got_signals
, SIGCHLD
)) {
2536 INITDBG(L_VB
, "got SIGCHLD");
2537 /* First set flag to 0 */
2538 DELSET(got_signals
, SIGCHLD
);
2540 /* See which child this was */
2541 for(ch
= family
; ch
; ch
= ch
->next
)
2542 if (ch
->flags
& ZOMBIE
) {
2543 INITDBG(L_VB
, "Child died, PID= %d", ch
->pid
);
2544 ch
->flags
&= ~(RUNNING
|ZOMBIE
|WAITING
);
2545 if (ch
->process
[0] != '+')
2546 write_utmp_wtmp("", ch
->id
, ch
->pid
, DEAD_PROCESS
, NULL
);
2551 if (ISMEMBER(got_signals
, SIGHUP
)) {
2552 INITDBG(L_VB
, "got SIGHUP");
2554 /* Are we waiting for a child? */
2555 for(ch
= family
; ch
; ch
= ch
->next
)
2556 if (ch
->flags
& WAITING
) break;
2560 /* We need to go into a new runlevel */
2561 oldlevel
= runlevel
;
2563 runlevel
= read_level(0);
2565 if (runlevel
== 'U') {
2566 runlevel
= oldlevel
;
2569 if (oldlevel
!= 'S' && runlevel
== 'S') console_stty();
2570 if (runlevel
== '6' || runlevel
== '0' ||
2571 runlevel
== '1') console_stty();
2574 setproctitle("init [%c]", (int)runlevel
);
2575 DELSET(got_signals
, SIGHUP
);
2579 if (ISMEMBER(got_signals
, SIGUSR1
)) {
2581 * SIGUSR1 means close and reopen /dev/initctl
2583 INITDBG(L_VB
, "got SIGUSR1");
2586 DELSET(got_signals
, SIGUSR1
);
2594 void init_main(void)
2597 struct sigaction sa
;
2605 * Fork so we can debug the init process.
2607 if ((f
= fork()) > 0) {
2608 static const char killmsg
[] = "PRNT: init killed.\r\n";
2611 while((rc
= wait(&st
)) != f
)
2612 if (rc
< 0 && errno
== ECHILD
)
2614 safe_write(1, killmsg
, sizeof(killmsg
) - 1);
2621 * Tell the kernel to send us SIGINT when CTRL-ALT-DEL
2622 * is pressed, and that we want to handle keyboard signals.
2624 init_reboot(BMAGIC_SOFT
);
2625 if ((f
= open(VT_MASTER
, O_RDWR
| O_NOCTTY
)) >= 0) {
2626 (void) ioctl(f
, KDSIGACCEPT
, SIGWINCH
);
2629 (void) ioctl(0, KDSIGACCEPT
, SIGWINCH
);
2633 * Ignore all signals.
2635 for(f
= 1; f
<= NSIG
; f
++)
2636 SETSIG(sa
, f
, SIG_IGN
, SA_RESTART
);
2639 SETSIG(sa
, SIGALRM
, signal_handler
, 0);
2640 SETSIG(sa
, SIGHUP
, signal_handler
, 0);
2641 SETSIG(sa
, SIGINT
, signal_handler
, 0);
2642 SETSIG(sa
, SIGCHLD
, chld_handler
, SA_RESTART
);
2643 SETSIG(sa
, SIGPWR
, signal_handler
, 0);
2644 SETSIG(sa
, SIGWINCH
, signal_handler
, 0);
2645 SETSIG(sa
, SIGUSR1
, signal_handler
, 0);
2646 SETSIG(sa
, SIGSTOP
, stop_handler
, SA_RESTART
);
2647 SETSIG(sa
, SIGTSTP
, stop_handler
, SA_RESTART
);
2648 SETSIG(sa
, SIGCONT
, cont_handler
, SA_RESTART
);
2649 SETSIG(sa
, SIGSEGV
, (void (*)(int))segv_handler
, SA_RESTART
);
2656 /* Close whatever files are open, and reset the console. */
2664 * Set default PATH variable.
2666 setenv("PATH", PATH_DEFAULT
, 1 /* Overwrite */);
2669 * Initialize /var/run/utmp (only works if /var is on
2670 * root and mounted rw)
2672 if ((fd
= open(UTMP_FILE
, O_WRONLY
|O_CREAT
|O_TRUNC
, 0644)) >= 0)
2676 * Say hello to the world
2678 initlog(L_CO
, bootmsg
, "booting");
2681 * See if we have to start an emergency shell.
2685 SETSIG(sa
, SIGCHLD
, SIG_DFL
, SA_RESTART
);
2686 if (spawn(&ch_emerg
, &f
) > 0) {
2687 while((rc
= wait(&st
)) != f
)
2688 if (rc
< 0 && errno
== ECHILD
)
2691 SETSIG(sa
, SIGCHLD
, chld_handler
, SA_RESTART
);
2695 * Start normal boot procedure.
2702 * Restart: unblock signals and let the show go on
2704 initlog(L_CO
, bootmsg
, "reloading");
2706 sigprocmask(SIG_UNBLOCK
, &sgt
, NULL
);
2709 * Set default PATH variable.
2711 setenv("PATH", PATH_DEFAULT
, 0 /* Don't overwrite */);
2717 /* See if we need to make the boot transitions. */
2719 INITDBG(L_VB
, "init_main: waiting..");
2721 /* Check if there are processes to be waited on. */
2722 for(ch
= family
; ch
; ch
= ch
->next
)
2723 if ((ch
->flags
& RUNNING
) && ch
->action
!= BOOT
) break;
2726 /* Wait until we get hit by some signal. */
2727 while (ch
!= NULL
&& got_signals
== 0) {
2728 if (ISMEMBER(got_signals
, SIGHUP
)) {
2729 /* See if there are processes to be waited on. */
2730 for(ch
= family
; ch
; ch
= ch
->next
)
2731 if (ch
->flags
& WAITING
) break;
2733 if (ch
!= NULL
) check_init_fifo();
2735 #else /* CHANGE_WAIT */
2736 if (ch
!= NULL
&& got_signals
== 0) check_init_fifo();
2737 #endif /* CHANGE_WAIT */
2739 /* Check the 'failing' flags */
2742 /* Process any signals. */
2745 /* See what we need to start up (again) */
2752 * Tell the user about the syntax we expect.
2757 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
);
2762 int telinit(char *progname
, int argc
, char **argv
)
2764 #ifdef TELINIT_USES_INITLVL
2767 struct init_request request
;
2768 struct sigaction sa
;
2772 memset(&request
, 0, sizeof(request
));
2773 request
.magic
= INIT_MAGIC
;
2775 while ((f
= getopt(argc
, argv
, "t:e:")) != EOF
) switch(f
) {
2777 sltime
= atoi(optarg
);
2781 env
= request
.i
.data
;
2783 if (env
+ l
+ 2 > request
.i
.data
+ sizeof(request
.i
.data
)) {
2784 fprintf(stderr
, "%s: -e option data "
2785 "too large\n", progname
);
2788 memcpy(env
, optarg
, l
);
2797 if (env
) *env
++ = 0;
2802 request
.cmd
= INIT_CMD_SETENV
;
2804 if (argc
- optind
!= 1 || strlen(argv
[optind
]) != 1)
2806 if (!strchr("0123456789SsQqAaBbCcUu", argv
[optind
][0]))
2808 request
.cmd
= INIT_CMD_RUNLVL
;
2809 request
.runlevel
= argv
[optind
][0];
2810 request
.sleeptime
= sltime
;
2813 /* Change to the root directory. */
2814 if (0 != chdir("/"))
2815 initlog(L_VB
, "unable to chdir to /: %s",
2818 /* Open the fifo and write a command. */
2819 /* Make sure we don't hang on opening /dev/initctl */
2820 SETSIG(sa
, SIGALRM
, signal_handler
, 0);
2822 if ((fd
= open(INIT_FIFO
, O_WRONLY
)) >= 0) {
2824 size_t s
= sizeof(request
);
2825 void *ptr
= &request
;
2828 p
= write(fd
, ptr
, s
);
2830 if (errno
== EINTR
|| errno
== EAGAIN
)
2842 #ifdef TELINIT_USES_INITLVL
2843 if (request
.cmd
== INIT_CMD_RUNLVL
) {
2844 /* Fallthrough to the old method. */
2846 /* Now write the new runlevel. */
2847 if ((fp
= fopen(INITLVL
, "w")) == NULL
) {
2848 fprintf(stderr
, "%s: cannot create %s\n",
2852 fprintf(fp
, "%s %d", argv
[optind
], sltime
);
2855 /* And tell init about the pending runlevel change. */
2856 if (kill(INITPID
, SIGHUP
) < 0) perror(progname
);
2862 fprintf(stderr
, "%s: ", progname
);
2863 if (ISMEMBER(got_signals
, SIGALRM
)) {
2864 fprintf(stderr
, "timeout opening/writing control channel %s\n",
2873 * Main entry for init and telinit.
2875 int main(int argc
, char **argv
)
2884 /* Get my own name */
2885 if ((p
= strrchr(argv
[0], '/')) != NULL
)
2891 umask(umask(077) | 022);
2894 if (geteuid() != 0) {
2895 fprintf(stderr
, "%s: must be superuser.\n", p
);
2900 * Is this telinit or init ?
2902 isinit
= (getpid() == 1);
2903 for (f
= 1; f
< argc
; f
++) {
2904 if (!strcmp(argv
[f
], "-i") || !strcmp(argv
[f
], "--init")) {
2909 if (!isinit
) exit(telinit(p
, argc
, argv
));
2914 if (check_pipe(STATE_PIPE
)) {
2916 receive_state(STATE_PIPE
);
2918 myname
= istrdup(argv
[0]);
2921 for (f
= 0; f
< argc
; f
++)
2922 maxproclen
+= strlen(argv
[f
]) + 1;
2924 setproctitle("init [%c]", (int)runlevel
);
2929 /* Check command line arguments */
2930 maxproclen
= strlen(argv
[0]) + 1;
2931 for(f
= 1; f
< argc
; f
++) {
2932 if (!strcmp(argv
[f
], "single") || !strcmp(argv
[f
], "-s"))
2934 else if (!strcmp(argv
[f
], "-a") || !strcmp(argv
[f
], "auto"))
2935 putenv("AUTOBOOT=YES");
2936 else if (!strcmp(argv
[f
], "-b") || !strcmp(argv
[f
],"emergency"))
2938 else if (!strcmp(argv
[f
], "-z")) {
2940 if (argv
[f
+ 1]) f
++;
2941 } else if (strchr("0123456789sS", argv
[f
][0])
2942 && strlen(argv
[f
]) == 1)
2943 dfl_level
= argv
[f
][0];
2944 /* "init u" in the very beginning makes no sense */
2945 if (dfl_level
== 's') dfl_level
= 'S';
2946 maxproclen
+= strlen(argv
[f
]) + 1;
2950 if (getenv("SELINUX_INIT") == NULL
) {
2951 if (is_selinux_enabled() != 1) {
2952 if (selinux_init_load_policy(&enforce
) == 0) {
2953 putenv("SELINUX_INIT=YES");
2954 execv(myname
, argv
);
2957 /* SELinux in enforcing mode but load_policy failed */
2958 /* At this point, we probably can't open /dev/console, so log() won't work */
2959 fprintf(stderr
,"Unable to load SELinux Policy. Machine is in enforcing mode. Halting now.\n");
2966 /* Start booting. */
2969 setproctitle("init boot");