]>
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/syslog.h>
56 # include <selinux/selinux.h>
57 # include <sys/mount.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 sa.sa_handler = fun; \
94 sa.sa_flags = flags; \
95 sigemptyset(&sa.sa_mask); \
96 sigaction(sig, &sa, NULL); \
99 /* Version information */
100 char *Version
= "@(#) init " VERSION
" " DATE
" miquels@cistron.nl";
101 char *bootmsg
= "version " VERSION
" %s";
102 #define E_VERSION "INIT_VERSION=sysvinit-" VERSION
104 CHILD
*family
= NULL
; /* The linked list of all entries */
105 CHILD
*newFamily
= NULL
; /* The list after inittab re-read */
107 CHILD ch_emerg
= { /* Emergency shell */
117 char runlevel
= 'S'; /* The current run level */
118 char thislevel
= 'S'; /* The current runlevel */
119 char prevlevel
= 'N'; /* Previous runlevel */
120 int dfl_level
= 0; /* Default runlevel */
121 sig_atomic_t got_cont
= 0; /* Set if we received the SIGCONT signal */
122 sig_atomic_t got_signals
; /* Set if we received a signal. */
123 int emerg_shell
= 0; /* Start emergency shell? */
124 int wrote_wtmp_reboot
= 1; /* Set when we wrote the reboot record */
125 int wrote_utmp_reboot
= 1; /* Set when we wrote the reboot record */
126 int wrote_wtmp_rlevel
= 1; /* Set when we wrote the runlevel record */
127 int wrote_utmp_rlevel
= 1; /* Set when we wrote the runlevel record */
128 int sltime
= 5; /* Sleep time between TERM and KILL */
129 char *argv0
; /* First arguments; show up in ps listing */
130 int maxproclen
; /* Maximal length of argv[0] with \0 */
131 struct utmp utproto
; /* Only used for sizeof(utproto.ut_id) */
132 char *console_dev
; /* Console device. */
133 int pipe_fd
= -1; /* /dev/initctl */
134 int did_boot
= 0; /* Did we already do BOOT* stuff? */
135 int main(int, char **);
137 /* Used by re-exec part */
138 int reload
= 0; /* Should we do initialization stuff? */
139 char *myname
="/sbin/init"; /* What should we exec */
140 int oops_error
; /* Used by some of the re-exec code. */
141 const char *Signature
= "12567362"; /* Signature for re-exec fd */
143 /* Macro to see if this is a special action */
144 #define ISPOWER(i) ((i) == POWERWAIT || (i) == POWERFAIL || \
145 (i) == POWEROKWAIT || (i) == POWERFAILNOW || \
148 /* ascii values for the `action' field. */
153 { "respawn", RESPAWN
},
157 { "bootwait", BOOTWAIT
},
158 { "powerfail", POWERFAIL
},
159 { "powerfailnow",POWERFAILNOW
},
160 { "powerwait", POWERWAIT
},
161 { "powerokwait", POWEROKWAIT
},
162 { "ctrlaltdel", CTRLALTDEL
},
164 { "ondemand", ONDEMAND
},
165 { "initdefault", INITDEFAULT
},
166 { "sysinit", SYSINIT
},
167 { "kbrequest", KBREQUEST
},
172 * State parser token table (see receive_state)
185 { "CMD", C_PROCESS
},
188 { "-RL", D_RUNLEVEL
},
189 { "-TL", D_THISLEVEL
},
190 { "-PL", D_PREVLEVEL
},
191 { "-SI", D_GOTSIGN
},
192 { "-WR", D_WROTE_WTMP_REBOOT
},
193 { "-WU", D_WROTE_UTMP_REBOOT
},
195 { "-DB", D_DIDBOOT
},
196 { "-LW", D_WROTE_WTMP_RLEVEL
},
197 { "-LU", D_WROTE_UTMP_RLEVEL
},
211 #define NR_EXTRA_ENV 16
212 char *extra_env
[NR_EXTRA_ENV
];
216 * Sleep a number of seconds.
218 * This only works correctly because the linux select updates
219 * the elapsed time in the struct timeval passed to select!
222 void do_sleep(int sec
)
229 while(select(0, NULL
, NULL
, NULL
, &tv
) < 0 && errno
== EINTR
)
235 * Non-failing allocation routines (init cannot fail).
238 void *imalloc(size_t size
)
242 while ((m
= malloc(size
)) == NULL
) {
243 initlog(L_VB
, "out of memory");
251 char *istrdup(char *s
)
264 * Send the state info of the previous running init to
265 * the new one, in a version-independant way.
268 void send_state(int fd
)
276 fprintf(fp
, "VER%s\n", Version
);
277 fprintf(fp
, "-RL%c\n", runlevel
);
278 fprintf(fp
, "-TL%c\n", thislevel
);
279 fprintf(fp
, "-PL%c\n", prevlevel
);
280 fprintf(fp
, "-SI%u\n", got_signals
);
281 fprintf(fp
, "-WR%d\n", wrote_wtmp_reboot
);
282 fprintf(fp
, "-WU%d\n", wrote_utmp_reboot
);
283 fprintf(fp
, "-ST%d\n", sltime
);
284 fprintf(fp
, "-DB%d\n", did_boot
);
286 for (p
= family
; p
; p
= p
->next
) {
287 fprintf(fp
, "REC%s\n", p
->id
);
288 fprintf(fp
, "LEV%s\n", p
->rlevel
);
289 for (i
= 0, val
= p
->flags
; flags
[i
].mask
; i
++)
290 if (val
& flags
[i
].mask
) {
291 val
&= ~flags
[i
].mask
;
292 fprintf(fp
, "FL %s\n",flags
[i
].name
);
294 fprintf(fp
, "PID%d\n",p
->pid
);
295 fprintf(fp
, "EXS%u\n",p
->exstat
);
296 for(i
= 0; actions
[i
].act
; i
++)
297 if (actions
[i
].act
== p
->action
) {
298 fprintf(fp
, "AC %s\n", actions
[i
].name
);
301 fprintf(fp
, "CMD%s\n", p
->process
);
302 fprintf(fp
, "EOR\n");
304 fprintf(fp
, "END\n");
309 * Read a string from a file descriptor.
310 * FIXME: why not use fgets() ?
312 static int get_string(char *p
, int size
, FILE *f
)
316 while ((c
= getc(f
)) != EOF
&& c
!= '\n') {
321 return (c
!= EOF
) && (size
> 0);
325 * Read trailing data from the state pipe until we see a newline.
327 static int get_void(FILE *f
)
331 while ((c
= getc(f
)) != EOF
&& c
!= '\n')
338 * Read the next "command" from the state pipe.
340 static int get_cmd(FILE *f
)
345 if (fread(cmd
, 1, sizeof(cmd
) - 1, f
) != sizeof(cmd
) - 1)
348 for(i
= 0; cmds
[i
].cmd
&& strcmp(cmds
[i
].name
, cmd
) != 0; i
++)
354 * Read a CHILD * from the state pipe.
356 static CHILD
*get_record(FILE *f
)
364 switch (cmd
= get_cmd(f
)) {
374 fscanf(f
, "%c\n", &runlevel
);
377 fscanf(f
, "%c\n", &thislevel
);
380 fscanf(f
, "%c\n", &prevlevel
);
383 fscanf(f
, "%u\n", &got_signals
);
385 case D_WROTE_WTMP_REBOOT
:
386 fscanf(f
, "%d\n", &wrote_wtmp_reboot
);
388 case D_WROTE_UTMP_REBOOT
:
389 fscanf(f
, "%d\n", &wrote_utmp_reboot
);
392 fscanf(f
, "%d\n", &sltime
);
395 fscanf(f
, "%d\n", &did_boot
);
397 case D_WROTE_WTMP_RLEVEL
:
398 fscanf(f
, "%d\n", &wrote_wtmp_rlevel
);
400 case D_WROTE_UTMP_RLEVEL
:
401 fscanf(f
, "%d\n", &wrote_utmp_rlevel
);
404 if (cmd
> 0 || cmd
== C_EOF
) {
409 } while (cmd
!= C_REC
);
411 p
= imalloc(sizeof(CHILD
));
412 get_string(p
->id
, sizeof(p
->id
), f
);
414 do switch(cmd
= get_cmd(f
)) {
420 fscanf(f
, "%d\n", &(p
->pid
));
423 fscanf(f
, "%u\n", &(p
->exstat
));
426 get_string(p
->rlevel
, sizeof(p
->rlevel
), f
);
429 get_string(p
->process
, sizeof(p
->process
), f
);
432 get_string(s
, sizeof(s
), f
);
433 for(i
= 0; flags
[i
].name
; i
++) {
434 if (strcmp(flags
[i
].name
,s
) == 0)
437 p
->flags
|= flags
[i
].mask
;
440 get_string(s
, sizeof(s
), f
);
441 for(i
= 0; actions
[i
].name
; i
++) {
442 if (strcmp(actions
[i
].name
, s
) == 0)
445 p
->action
= actions
[i
].act
? actions
[i
].act
: OFF
;
451 } while( cmd
!= C_EOR
);
457 * Read the complete state info from the state pipe.
458 * Returns 0 on success
461 int receive_state(int fd
)
464 char old_version
[256];
469 if (get_cmd(f
) != C_VER
)
471 get_string(old_version
, sizeof(old_version
), f
);
473 for (pp
= &family
; (*pp
= get_record(f
)) != NULL
; pp
= &((*pp
)->next
))
480 * Set the process title.
483 __attribute__ ((format (printf
, 1, 2)))
485 static int setproctitle(char *fmt
, ...)
494 len
= vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
497 if (maxproclen
> 1) {
498 memset(argv0
, 0, maxproclen
);
499 strncpy(argv0
, buf
, maxproclen
- 1);
506 * Set console_dev to a working console.
509 void console_init(void)
512 int tried_devcons
= 0;
513 int tried_vtmaster
= 0;
516 if ((s
= getenv("CONSOLE")) != NULL
)
519 console_dev
= CONSOLE
;
523 while ((fd
= open(console_dev
, O_RDONLY
|O_NONBLOCK
)) < 0) {
524 if (!tried_devcons
) {
526 console_dev
= CONSOLE
;
529 if (!tried_vtmaster
) {
531 console_dev
= VT_MASTER
;
537 console_dev
= "/dev/null";
544 * Open the console with retries.
547 int console_open(int mode
)
553 * Open device in nonblocking mode.
555 m
= mode
| O_NONBLOCK
;
558 * Retry the open five times.
560 for(f
= 0; f
< 5; f
++) {
561 if ((fd
= open(console_dev
, m
)) >= 0) break;
565 if (fd
< 0) return fd
;
568 * Set original flags.
571 fcntl(fd
, F_SETFL
, mode
);
576 * We got a signal (HUP PWR WINCH ALRM INT)
579 void signal_handler(int sig
)
581 ADDSET(got_signals
, sig
);
585 * SIGCHLD: one of our children has died.
589 void chld_handler(int sig
__attribute__((unused
)))
591 void chld_handler(int sig
)
596 int saved_errno
= errno
;
599 * Find out which process(es) this was (were)
601 while((pid
= waitpid(-1, &st
, WNOHANG
)) != 0) {
602 if (errno
== ECHILD
) break;
603 for( ch
= family
; ch
; ch
= ch
->next
)
604 if ( ch
->pid
== pid
&& (ch
->flags
& RUNNING
) ) {
606 "chld_handler: marked %d as zombie",
608 ADDSET(got_signals
, SIGCHLD
);
612 ch
->new->exstat
= st
;
613 ch
->new->flags
|= ZOMBIE
;
618 INITDBG(L_VB
, "chld_handler: unknown child %d exited.",
626 * Linux ignores all signals sent to init when the
627 * SIG_DFL handler is installed. Therefore we must catch SIGTSTP
628 * and SIGCONT, or else they won't work....
630 * The SIGCONT handler
634 void cont_handler(int sig
__attribute__((unused
)))
636 void cont_handler(int sig
)
643 * Fork and dump core in /.
648 static int dumped
= 0;
655 if (fork() != 0) return;
658 sigprocmask(SIG_SETMASK
, &mask
, NULL
);
660 rlim
.rlim_cur
= RLIM_INFINITY
;
661 rlim
.rlim_max
= RLIM_INFINITY
;
662 setrlimit(RLIMIT_CORE
, &rlim
);
665 signal(SIGSEGV
, SIG_DFL
);
667 sigdelset(&mask
, SIGSEGV
);
668 sigprocmask(SIG_SETMASK
, &mask
, NULL
);
675 * OOPS: segmentation violation!
676 * If we have the info, print where it occured.
677 * Then sleep 30 seconds and try to continue.
680 #if defined(STACK_DEBUG) && defined(__linux__)
682 void segv_handler(int sig
__attribute__((unused
)), struct sigcontext ctx
)
684 void segv_handler(int sig
, struct sigcontext ctx
)
688 int saved_errno
= errno
;
690 if ((void *)ctx
.eip
>= (void *)do_sleep
&&
691 (void *)ctx
.eip
< (void *)main
)
693 initlog(L_VB
, "PANIC: segmentation violation at %p%s! "
694 "sleeping for 30 seconds.", (void *)ctx
.eip
, p
);
701 void segv_handler(int sig
__attribute__((unused
)))
703 void segv_handler(int sig
)
706 int saved_errno
= errno
;
709 "PANIC: segmentation violation! sleeping for 30 seconds.");
717 * The SIGSTOP & SIGTSTP handler
721 void stop_handler(int sig
__attribute__((unused
)))
723 void stop_handler(int sig
)
726 int saved_errno
= errno
;
729 while(!got_cont
) pause();
735 * Set terminal settings to reasonable defaults
738 void console_stty(void)
743 if ((fd
= console_open(O_RDWR
|O_NOCTTY
)) < 0) {
744 initlog(L_VB
, "can't open %s", console_dev
);
748 #ifdef __FreeBSD_kernel__
750 * The kernel of FreeBSD expects userland to set TERM. Usually, we want
751 * "cons25". Later, gettys might disagree on this (i.e. we're not using
752 * syscons) but some boot scripts, like /etc/init.d/xserver-xorg, still
753 * need a non-dumb terminal.
755 putenv ("TERM=cons25");
758 (void) tcgetattr(fd
, &tty
);
760 tty
.c_cflag
&= CBAUD
|CBAUDEX
|CSIZE
|CSTOPB
|PARENB
|PARODD
;
761 tty
.c_cflag
|= HUPCL
|CLOCAL
|CREAD
;
763 tty
.c_cc
[VINTR
] = CINTR
;
764 tty
.c_cc
[VQUIT
] = CQUIT
;
765 tty
.c_cc
[VERASE
] = CERASE
; /* ASCII DEL (0177) */
766 tty
.c_cc
[VKILL
] = CKILL
;
767 tty
.c_cc
[VEOF
] = CEOF
;
770 tty
.c_cc
[VSWTC
] = _POSIX_VDISABLE
;
771 tty
.c_cc
[VSTART
] = CSTART
;
772 tty
.c_cc
[VSTOP
] = CSTOP
;
773 tty
.c_cc
[VSUSP
] = CSUSP
;
774 tty
.c_cc
[VEOL
] = _POSIX_VDISABLE
;
775 tty
.c_cc
[VREPRINT
] = CREPRINT
;
776 tty
.c_cc
[VDISCARD
] = CDISCARD
;
777 tty
.c_cc
[VWERASE
] = CWERASE
;
778 tty
.c_cc
[VLNEXT
] = CLNEXT
;
779 tty
.c_cc
[VEOL2
] = _POSIX_VDISABLE
;
782 * Set pre and post processing
784 tty
.c_iflag
= IGNPAR
|ICRNL
|IXON
|IXANY
;
785 #ifdef IUTF8 /* Not defined on FreeBSD */
786 tty
.c_iflag
|= IUTF8
;
788 tty
.c_oflag
= OPOST
|ONLCR
;
789 tty
.c_lflag
= ISIG
|ICANON
|ECHO
|ECHOCTL
|ECHOPRT
|ECHOKE
;
791 #if defined(SANE_TIO) && (SANE_TIO == 1)
793 * Disable flow control (-ixon), ignore break (ignbrk),
794 * and make nl/cr more usable (sane).
796 tty
.c_iflag
|= IGNBRK
;
797 tty
.c_iflag
&= ~(BRKINT
|INLCR
|IGNCR
|IXON
);
798 tty
.c_oflag
&= ~(OCRNL
|ONLRET
);
801 * Now set the terminal line.
802 * We don't care about non-transmitted output data
803 * and non-read input data.
805 (void) tcsetattr(fd
, TCSANOW
, &tty
);
806 (void) tcflush(fd
, TCIOFLUSH
);
811 * Print to the system console
817 if ((fd
= console_open(O_WRONLY
|O_NOCTTY
|O_NDELAY
)) >= 0) {
818 write(fd
, s
, strlen(s
));
824 * Log something to a logfile and the console.
827 __attribute__ ((format (printf
, 2, 3)))
829 void initlog(int loglevel
, char *s
, ...)
833 sigset_t nmask
, omask
;
835 va_start(va_alist
, s
);
836 vsnprintf(buf
, sizeof(buf
), s
, va_alist
);
839 if (loglevel
& L_SY
) {
841 * Re-establish connection with syslogd every time.
842 * Block signals while talking to syslog.
845 sigprocmask(SIG_BLOCK
, &nmask
, &omask
);
846 openlog("init", 0, LOG_DAEMON
);
847 syslog(LOG_INFO
, "%s", buf
);
849 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
853 * And log to the console.
855 if (loglevel
& L_CO
) {
864 * Build a new environment for execve().
866 char **init_buildenv(int child
)
868 char i_lvl
[] = "RUNLEVEL=x";
869 char i_prev
[] = "PREVLEVEL=x";
871 char i_shell
[] = "SHELL=" SHELL
;
875 for (n
= 0; environ
[n
]; n
++)
880 e
= calloc(n
, sizeof(char *));
882 for (n
= 0; environ
[n
]; n
++)
883 e
[n
] = istrdup(environ
[n
]);
885 for (i
= 0; i
< NR_EXTRA_ENV
; i
++) {
887 e
[n
++] = istrdup(extra_env
[i
]);
891 snprintf(i_cons
, sizeof(i_cons
), "CONSOLE=%s", console_dev
);
892 i_lvl
[9] = thislevel
;
893 i_prev
[10] = prevlevel
;
894 e
[n
++] = istrdup(i_shell
);
895 e
[n
++] = istrdup(i_lvl
);
896 e
[n
++] = istrdup(i_prev
);
897 e
[n
++] = istrdup(i_cons
);
898 e
[n
++] = istrdup(E_VERSION
);
907 void init_freeenv(char **e
)
911 for (n
= 0; e
[n
]; n
++)
920 * This function is too long and indents too deep.
924 pid_t
spawn(CHILD
*ch
, int *res
)
926 char *args
[16]; /* Argv array */
927 char buf
[136]; /* Line buffer */
928 int f
, st
; /* Scratch variables */
929 char *ptr
; /* Ditto */
930 time_t t
; /* System time */
931 int oldAlarm
; /* Previous alarm value */
932 char *proc
= ch
->process
; /* Command line */
933 pid_t pid
, pgrp
; /* child, console process group. */
934 sigset_t nmask
, omask
; /* For blocking SIGCHLD */
938 buf
[sizeof(buf
) - 1] = 0;
940 /* Skip '+' if it's there */
941 if (proc
[0] == '+') proc
++;
943 ch
->flags
|= XECUTED
;
945 if (ch
->action
== RESPAWN
|| ch
->action
== ONDEMAND
) {
946 /* Is the date stamp from less than 2 minutes ago? */
948 if (ch
->tm
+ TESTTIME
> t
) {
955 /* Do we try to respawn too fast? */
956 if (ch
->count
>= MAXSPAWN
) {
959 "Id \"%s\" respawning too fast: disabled for %d minutes",
960 ch
->id
, SLEEPTIME
/ 60);
961 ch
->flags
&= ~RUNNING
;
962 ch
->flags
|= FAILING
;
964 /* Remember the time we stopped */
967 /* Try again in 5 minutes */
969 if (oldAlarm
> SLEEPTIME
|| oldAlarm
<= 0) oldAlarm
= SLEEPTIME
;
975 /* See if there is an "initscript" (except in single user mode). */
976 if (access(INITSCRIPT
, R_OK
) == 0 && runlevel
!= 'S') {
977 /* Build command line using "initscript" */
979 args
[2] = INITSCRIPT
;
981 args
[4] = ch
->rlevel
;
983 for(f
= 0; actions
[f
].name
; f
++) {
984 if (ch
->action
== actions
[f
].act
) {
985 args
[5] = actions
[f
].name
;
991 } else if (strpbrk(proc
, "~`!$^&*()=|\\{}[];\"'<>?")) {
992 /* See if we need to fire off a shell for this command */
993 /* Give command line to shell */
996 strcpy(buf
, "exec ");
997 strncat(buf
, proc
, sizeof(buf
) - strlen(buf
) - 1);
1001 /* Split up command line arguments */
1003 strncat(buf
, proc
, sizeof(buf
) - 1);
1005 for(f
= 1; f
< 15; f
++) {
1006 /* Skip white space */
1007 while(*ptr
== ' ' || *ptr
== '\t') ptr
++;
1010 /* May be trailing space.. */
1011 if (*ptr
== 0) break;
1013 /* Skip this `word' */
1014 while(*ptr
&& *ptr
!= ' ' && *ptr
!= '\t' && *ptr
!= '#')
1017 /* If end-of-line, break */
1018 if (*ptr
== '#' || *ptr
== 0) {
1023 /* End word with \0 and continue */
1031 * Block sigchild while forking.
1033 sigemptyset(&nmask
);
1034 sigaddset(&nmask
, SIGCHLD
);
1035 sigprocmask(SIG_BLOCK
, &nmask
, &omask
);
1037 if ((pid
= fork()) == 0) {
1042 if (pipe_fd
>= 0) close(pipe_fd
);
1044 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
1047 * In sysinit, boot, bootwait or single user mode:
1048 * for any wait-type subprocess we _force_ the console
1049 * to be its controlling tty.
1051 if (strchr("*#sS", runlevel
) && ch
->flags
& WAITING
) {
1053 * We fork once extra. This is so that we can
1054 * wait and change the process group and session
1055 * of the console after exit of the leader.
1058 if ((f
= console_open(O_RDWR
|O_NOCTTY
)) >= 0) {
1059 /* Take over controlling tty by force */
1060 (void)ioctl(f
, TIOCSCTTY
, 1);
1066 * 4 Sep 2001, Andrea Arcangeli:
1067 * Fix a race in spawn() that is used to deadlock init in a
1068 * waitpid() loop: must set the childhandler as default before forking
1069 * off the child or the chld_handler could run before the waitpid loop
1070 * has a chance to find its zombie-child.
1072 SETSIG(sa
, SIGCHLD
, SIG_DFL
, SA_RESTART
);
1073 if ((pid
= fork()) < 0) {
1074 initlog(L_VB
, "cannot fork: %s",
1081 * Ignore keyboard signals etc.
1082 * Then wait for child to exit.
1084 SETSIG(sa
, SIGINT
, SIG_IGN
, SA_RESTART
);
1085 SETSIG(sa
, SIGTSTP
, SIG_IGN
, SA_RESTART
);
1086 SETSIG(sa
, SIGQUIT
, SIG_IGN
, SA_RESTART
);
1088 while ((rc
= waitpid(pid
, &st
, 0)) != pid
)
1089 if (rc
< 0 && errno
== ECHILD
)
1093 * Small optimization. See if stealing
1094 * controlling tty back is needed.
1096 pgrp
= tcgetpgrp(f
);
1097 if (pgrp
!= getpid())
1101 * Steal controlling tty away. We do
1102 * this with a temporary process.
1104 if ((pid
= fork()) < 0) {
1105 initlog(L_VB
, "cannot fork: %s",
1111 (void)ioctl(f
, TIOCSCTTY
, 1);
1114 while((rc
= waitpid(pid
, &st
, 0)) != pid
)
1115 if (rc
< 0 && errno
== ECHILD
)
1120 /* Set ioctl settings to default ones */
1125 if ((f
= console_open(O_RDWR
|O_NOCTTY
)) < 0) {
1126 initlog(L_VB
, "open(%s): %s", console_dev
,
1128 f
= open("/dev/null", O_RDWR
);
1135 * Update utmp/wtmp file prior to starting
1136 * any child. This MUST be done right here in
1137 * the child process in order to prevent a race
1138 * condition that occurs when the child
1139 * process' time slice executes before the
1140 * parent (can and does happen in a uniprocessor
1141 * environment). If the child is a getty and
1142 * the race condition happens, then init's utmp
1143 * update will happen AFTER the getty runs
1144 * and expects utmp to be updated already!
1146 * Do NOT log if process field starts with '+'
1147 * FIXME: that's for compatibility with *very*
1148 * old getties - probably it can be taken out.
1150 if (ch
->process
[0] != '+')
1151 write_utmp_wtmp("", ch
->id
, getpid(), INIT_PROCESS
, "");
1153 /* Reset all the signals, set up environment */
1154 for(f
= 1; f
< NSIG
; f
++) SETSIG(sa
, f
, SIG_DFL
, SA_RESTART
);
1155 environ
= init_buildenv(1);
1158 * Execute prog. In case of ENOEXEC try again
1159 * as a shell script.
1161 execvp(args
[1], args
+ 1);
1162 if (errno
== ENOEXEC
) {
1165 strcpy(buf
, "exec ");
1166 strncat(buf
, proc
, sizeof(buf
) - strlen(buf
) - 1);
1169 execvp(args
[1], args
+ 1);
1171 initlog(L_VB
, "cannot execute \"%s\"", args
[1]);
1173 if (ch
->process
[0] != '+')
1174 write_utmp_wtmp("", ch
->id
, getpid(), DEAD_PROCESS
, NULL
);
1178 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
1180 INITDBG(L_VB
, "Started id %s (pid %d)", ch
->id
, pid
);
1183 initlog(L_VB
, "cannot fork, retry..");
1192 * Start a child running!
1195 void startup(CHILD
*ch
)
1198 * See if it's disabled
1200 if (ch
->flags
& FAILING
) return;
1202 switch(ch
->action
) {
1211 if (!(ch
->flags
& XECUTED
)) ch
->flags
|= WAITING
;
1216 if (ch
->flags
& XECUTED
) break;
1219 ch
->flags
|= RUNNING
;
1220 (void)spawn(ch
, &(ch
->pid
));
1227 * Read the inittab file.
1230 void read_inittab(void)
1232 FILE *fp
; /* The INITTAB file */
1233 CHILD
*ch
, *old
, *i
; /* Pointers to CHILD structure */
1234 CHILD
*head
= NULL
; /* Head of linked list */
1236 struct stat st
; /* To stat INITLVL */
1238 sigset_t nmask
, omask
; /* For blocking SIGCHLD. */
1239 char buf
[256]; /* Line buffer */
1240 char err
[64]; /* Error message. */
1242 *action
, *process
; /* Fields of a line */
1244 int lineNo
= 0; /* Line number in INITTAB file */
1245 int actionNo
; /* Decoded action field */
1246 int f
; /* Counter */
1247 int round
; /* round 0 for SIGTERM, 1 for SIGKILL */
1248 int foundOne
= 0; /* No killing no sleep */
1249 int talk
; /* Talk to the user */
1250 int done
= 0; /* Ready yet? */
1253 if (newFamily
!= NULL
) {
1254 INITDBG(L_VB
, "PANIC newFamily != NULL");
1257 INITDBG(L_VB
, "Reading inittab");
1261 * Open INITTAB and real line by line.
1263 if ((fp
= fopen(INITTAB
, "r")) == NULL
)
1264 initlog(L_VB
, "No inittab file found");
1268 * Add single user shell entry at the end.
1270 if (fp
== NULL
|| fgets(buf
, sizeof(buf
), fp
) == NULL
) {
1273 * See if we have a single user entry.
1275 for(old
= newFamily
; old
; old
= old
->next
)
1276 if (strpbrk(old
->rlevel
, "S")) break;
1278 snprintf(buf
, sizeof(buf
), "~~:S:wait:%s\n", SULOGIN
);
1284 * Skip comments and empty lines
1286 for(p
= buf
; *p
== ' ' || *p
== '\t'; p
++)
1288 if (*p
== '#' || *p
== '\n') continue;
1293 id
= strsep(&p
, ":");
1294 rlevel
= strsep(&p
, ":");
1295 action
= strsep(&p
, ":");
1296 process
= strsep(&p
, "\n");
1299 * Check if syntax is OK. Be very verbose here, to
1300 * avoid newbie postings on comp.os.linux.setup :)
1303 if (!id
|| !*id
) strcpy(err
, "missing id field");
1304 if (!rlevel
) strcpy(err
, "missing runlevel field");
1305 if (!process
) strcpy(err
, "missing process field");
1306 if (!action
|| !*action
)
1307 strcpy(err
, "missing action field");
1308 if (id
&& strlen(id
) > sizeof(utproto
.ut_id
))
1309 sprintf(err
, "id field too long (max %d characters)",
1310 (int)sizeof(utproto
.ut_id
));
1311 if (rlevel
&& strlen(rlevel
) > 11)
1312 strcpy(err
, "rlevel field too long (max 11 characters)");
1313 if (process
&& strlen(process
) > 127)
1314 strcpy(err
, "process field too long");
1315 if (action
&& strlen(action
) > 32)
1316 strcpy(err
, "action field too long");
1318 initlog(L_VB
, "%s[%d]: %s", INITTAB
, lineNo
, err
);
1319 INITDBG(L_VB
, "%s:%s:%s:%s", id
, rlevel
, action
, process
);
1324 * Decode the "action" field
1327 for(f
= 0; actions
[f
].name
; f
++)
1328 if (strcasecmp(action
, actions
[f
].name
) == 0) {
1329 actionNo
= actions
[f
].act
;
1332 if (actionNo
== -1) {
1333 initlog(L_VB
, "%s[%d]: %s: unknown action field",
1334 INITTAB
, lineNo
, action
);
1339 * See if the id field is unique
1341 for(old
= newFamily
; old
; old
= old
->next
) {
1342 if(strcmp(old
->id
, id
) == 0 && strcmp(id
, "~~")) {
1343 initlog(L_VB
, "%s[%d]: duplicate ID field \"%s\"",
1344 INITTAB
, lineNo
, id
);
1351 * Allocate a CHILD structure
1353 ch
= imalloc(sizeof(CHILD
));
1358 ch
->action
= actionNo
;
1359 strncpy(ch
->id
, id
, sizeof(utproto
.ut_id
) + 1); /* Hack for different libs. */
1360 strncpy(ch
->process
, process
, sizeof(ch
->process
) - 1);
1362 for(f
= 0; f
< (int)sizeof(rlevel
) - 1 && rlevel
[f
]; f
++) {
1363 ch
->rlevel
[f
] = rlevel
[f
];
1364 if (ch
->rlevel
[f
] == 's') ch
->rlevel
[f
] = 'S';
1366 strncpy(ch
->rlevel
, rlevel
, sizeof(ch
->rlevel
) - 1);
1368 strcpy(ch
->rlevel
, "0123456789");
1369 if (ISPOWER(ch
->action
))
1370 strcpy(ch
->rlevel
, "S0123456789");
1373 * We have the fake runlevel '#' for SYSINIT and
1374 * '*' for BOOT and BOOTWAIT.
1376 if (ch
->action
== SYSINIT
) strcpy(ch
->rlevel
, "#");
1377 if (ch
->action
== BOOT
|| ch
->action
== BOOTWAIT
)
1378 strcpy(ch
->rlevel
, "*");
1381 * Now add it to the linked list. Special for powerfail.
1383 if (ISPOWER(ch
->action
)) {
1386 * Disable by default
1388 ch
->flags
|= XECUTED
;
1391 * Tricky: insert at the front of the list..
1394 for(i
= newFamily
; i
; i
= i
->next
) {
1395 if (!ISPOWER(i
->action
)) break;
1399 * Now add after entry "old"
1404 if (i
== NULL
) head
= ch
;
1406 ch
->next
= newFamily
;
1408 if (ch
->next
== NULL
) head
= ch
;
1412 * Just add at end of the list
1414 if (ch
->action
== KBREQUEST
) ch
->flags
|= XECUTED
;
1424 * Walk through the old list comparing id fields
1426 for(old
= family
; old
; old
= old
->next
)
1427 if (strcmp(old
->id
, ch
->id
) == 0) {
1438 * Loop through the list of children, and see if they need to
1442 INITDBG(L_VB
, "Checking for children to kill");
1443 for(round
= 0; round
< 2; round
++) {
1445 for(ch
= family
; ch
; ch
= ch
->next
) {
1446 ch
->flags
&= ~KILLME
;
1449 * Is this line deleted?
1451 if (ch
->new == NULL
) ch
->flags
|= KILLME
;
1454 * If the entry has changed, kill it anyway. Note that
1455 * we do not check ch->process, only the "action" field.
1456 * This way, you can turn an entry "off" immediately, but
1457 * changes in the command line will only become effective
1458 * after the running version has exited.
1460 if (ch
->new && ch
->action
!= ch
->new->action
) ch
->flags
|= KILLME
;
1463 * Only BOOT processes may live in all levels
1465 if (ch
->action
!= BOOT
&&
1466 strchr(ch
->rlevel
, runlevel
) == NULL
) {
1468 * Ondemand procedures live always,
1469 * except in single user
1471 if (runlevel
== 'S' || !(ch
->flags
& DEMAND
))
1472 ch
->flags
|= KILLME
;
1476 * Now, if this process may live note so in the new list
1478 if ((ch
->flags
& KILLME
) == 0) {
1479 ch
->new->flags
= ch
->flags
;
1480 ch
->new->pid
= ch
->pid
;
1481 ch
->new->exstat
= ch
->exstat
;
1487 * Is this process still around?
1489 if ((ch
->flags
& RUNNING
) == 0) {
1490 ch
->flags
&= ~KILLME
;
1493 INITDBG(L_VB
, "Killing \"%s\"", ch
->process
);
1495 case 0: /* Send TERM signal */
1498 "Sending processes the TERM signal");
1499 kill(-(ch
->pid
), SIGTERM
);
1502 case 1: /* Send KILL signal and collect status */
1505 "Sending processes the KILL signal");
1506 kill(-(ch
->pid
), SIGKILL
);
1513 * See if we have to wait 5 seconds
1515 if (foundOne
&& round
== 0) {
1517 * Yup, but check every second if we still have children.
1519 for(f
= 0; f
< sltime
; f
++) {
1520 for(ch
= family
; ch
; ch
= ch
->next
) {
1521 if (!(ch
->flags
& KILLME
)) continue;
1522 if ((ch
->flags
& RUNNING
) && !(ch
->flags
& ZOMBIE
))
1527 * No running children, skip SIGKILL
1530 foundOne
= 0; /* Skip the sleep below. */
1539 * Now give all processes the chance to die and collect exit statuses.
1541 if (foundOne
) do_sleep(1);
1542 for(ch
= family
; ch
; ch
= ch
->next
)
1543 if (ch
->flags
& KILLME
) {
1544 if (!(ch
->flags
& ZOMBIE
))
1545 initlog(L_CO
, "Pid %d [id %s] seems to hang", ch
->pid
,
1548 INITDBG(L_VB
, "Updating utmp for pid %d [id %s]",
1550 ch
->flags
&= ~RUNNING
;
1551 if (ch
->process
[0] != '+')
1552 write_utmp_wtmp("", ch
->id
, ch
->pid
, DEAD_PROCESS
, NULL
);
1557 * Both rounds done; clean up the list.
1559 sigemptyset(&nmask
);
1560 sigaddset(&nmask
, SIGCHLD
);
1561 sigprocmask(SIG_BLOCK
, &nmask
, &omask
);
1562 for(ch
= family
; ch
; ch
= old
) {
1567 for(ch
= family
; ch
; ch
= ch
->next
) ch
->new = NULL
;
1569 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
1573 * Dispose of INITLVL file.
1575 if (lstat(INITLVL
, &st
) >= 0 && S_ISLNK(st
.st_mode
)) {
1577 * INITLVL is a symbolic link, so just truncate the file.
1579 close(open(INITLVL
, O_WRONLY
|O_TRUNC
));
1582 * Delete INITLVL file.
1589 * Dispose of INITLVL2 file.
1591 if (lstat(INITLVL2
, &st
) >= 0 && S_ISLNK(st
.st_mode
)) {
1593 * INITLVL2 is a symbolic link, so just truncate the file.
1595 close(open(INITLVL2
, O_WRONLY
|O_TRUNC
));
1598 * Delete INITLVL2 file.
1606 * Walk through the family list and start up children.
1607 * The entries that do not belong here at all are removed
1611 void start_if_needed(void)
1613 CHILD
*ch
; /* Pointer to child */
1614 int delete; /* Delete this entry from list? */
1616 INITDBG(L_VB
, "Checking for children to start");
1618 for(ch
= family
; ch
; ch
= ch
->next
) {
1621 if (ch
->rlevel
[0] == 'C') {
1622 INITDBG(L_VB
, "%s: flags %d", ch
->process
, ch
->flags
);
1626 /* Are we waiting for this process? Then quit here. */
1627 if (ch
->flags
& WAITING
) break;
1629 /* Already running? OK, don't touch it */
1630 if (ch
->flags
& RUNNING
) continue;
1632 /* See if we have to start it up */
1634 if (strchr(ch
->rlevel
, runlevel
) ||
1635 ((ch
->flags
& DEMAND
) && !strchr("#*Ss", runlevel
))) {
1641 /* FIXME: is this OK? */
1642 ch
->flags
&= ~(RUNNING
|WAITING
);
1643 if (!ISPOWER(ch
->action
) && ch
->action
!= KBREQUEST
)
1644 ch
->flags
&= ~XECUTED
;
1647 /* Do we have to wait for this process? */
1648 if (ch
->flags
& WAITING
) break;
1654 * Ask the user on the console for a runlevel
1657 int ask_runlevel(void)
1659 const char prompt
[] = "\nEnter runlevel: ";
1665 fd
= console_open(O_RDWR
|O_NOCTTY
);
1667 if (fd
< 0) return('S');
1669 while(!strchr("0123456789S", lvl
)) {
1670 write(fd
, prompt
, sizeof(prompt
) - 1);
1672 read(fd
, buf
, sizeof(buf
));
1673 if (buf
[0] != 0 && (buf
[1] == '\r' || buf
[1] == '\n'))
1675 if (islower(lvl
)) lvl
= toupper(lvl
);
1682 * Search the INITTAB file for the 'initdefault' field, with the default
1683 * runlevel. If this fails, ask the user to supply a runlevel.
1686 int get_init_default(void)
1693 * Look for initdefault.
1695 for(ch
= family
; ch
; ch
= ch
->next
)
1696 if (ch
->action
== INITDEFAULT
) {
1699 if (*p
> lvl
) lvl
= *p
;
1705 * See if level is valid
1708 if (islower(lvl
)) lvl
= toupper(lvl
);
1709 if (strchr("0123456789S", lvl
) == NULL
) {
1711 "Initdefault level '%c' is invalid", lvl
);
1716 * Ask for runlevel on console if needed.
1718 if (lvl
<= 0) lvl
= ask_runlevel();
1721 * Log the fact that we have a runlevel now.
1730 * Do actions for the new level. If we are compatible with
1731 * the "old" INITLVL and arg == 0, try to read the new
1732 * runlevel from that file first.
1735 int read_level(int arg
)
1737 CHILD
*ch
; /* Walk through list */
1738 unsigned char foo
= 'X'; /* Contents of INITLVL */
1753 if (stat(INITLVL
, &stt
) != 0 || stt
.st_size
!= 0L)
1754 fp
= fopen(INITLVL
, "r");
1757 (stat(INITLVL2
, &stt
) != 0 || stt
.st_size
!= 0L))
1758 fp
= fopen(INITLVL2
, "r");
1761 /* INITLVL file empty or not there - act as 'init q' */
1762 initlog(L_SY
, "Re-reading inittab");
1765 ok
= fscanf(fp
, "%c %d", &foo
, &st
);
1768 /* We go to the new runlevel passed as an argument. */
1772 if (ok
== 2) sltime
= st
;
1774 #endif /* INITLVL */
1776 if (islower(foo
)) foo
= toupper(foo
);
1777 if (ok
< 1 || ok
> 2 || strchr("QS0123456789ABCU", foo
) == NULL
) {
1778 initlog(L_VB
, "bad runlevel: %c", foo
);
1782 /* Log this action */
1785 initlog(L_VB
, "Going single user");
1788 initlog(L_SY
, "Re-reading inittab");
1794 "Activating demand-procedures for '%c'", foo
);
1797 initlog(L_SY
, "Trying to re-exec init");
1800 initlog(L_VB
, "Switching to runlevel: %c", foo
);
1804 #if defined(SIGINT_ONLYONCE) && (SIGINT_ONLYONCE == 1)
1805 /* Re-enable signal from keyboard */
1806 struct sigaction sa
;
1807 SETSIG(sa
, SIGINT
, signal_handler
, 0);
1812 /* Check if this is a runlevel a, b or c */
1813 if (strchr("ABC", foo
)) {
1814 if (runlevel
== 'S') return(runlevel
);
1816 /* Read inittab again first! */
1819 /* Mark those special tasks */
1820 for(ch
= family
; ch
; ch
= ch
->next
)
1821 if (strchr(ch
->rlevel
, foo
) != NULL
||
1822 strchr(ch
->rlevel
, tolower(foo
)) != NULL
) {
1823 ch
->flags
|= DEMAND
;
1824 ch
->flags
&= ~XECUTED
;
1826 "Marking (%s) as ondemand, flags %d",
1832 /* Store both the old and the new runlevel. */
1833 wrote_utmp_rlevel
= 0;
1834 wrote_wtmp_rlevel
= 0;
1835 write_utmp_wtmp("runlevel", "~~", foo
+ 256*runlevel
, RUN_LVL
, "~");
1837 prevlevel
= runlevel
;
1843 * This procedure is called after every signal (SIGHUP, SIGALRM..)
1845 * Only clear the 'failing' flag if the process is sleeping
1846 * longer than 5 minutes, or inittab was read again due
1847 * to user interaction.
1850 void fail_check(void)
1852 CHILD
*ch
; /* Pointer to child structure */
1853 time_t t
; /* System time */
1854 time_t next_alarm
= 0; /* When to set next alarm */
1858 for(ch
= family
; ch
; ch
= ch
->next
) {
1860 if (ch
->flags
& FAILING
) {
1861 /* Can we free this sucker? */
1862 if (ch
->tm
+ SLEEPTIME
< t
) {
1863 ch
->flags
&= ~FAILING
;
1867 /* No, we'll look again later */
1868 if (next_alarm
== 0 ||
1869 ch
->tm
+ SLEEPTIME
> next_alarm
)
1870 next_alarm
= ch
->tm
+ SLEEPTIME
;
1876 if (next_alarm
< 1) next_alarm
= 1;
1881 /* Set all 'Fail' timers to 0 */
1883 void fail_cancel(void)
1887 for(ch
= family
; ch
; ch
= ch
->next
) {
1890 ch
->flags
&= ~FAILING
;
1895 * Start up powerfail entries.
1898 void do_power_fail(int pwrstat
)
1903 * Tell powerwait & powerfail entries to start up
1905 for (ch
= family
; ch
; ch
= ch
->next
) {
1906 if (pwrstat
== 'O') {
1908 * The power is OK again.
1910 if (ch
->action
== POWEROKWAIT
)
1911 ch
->flags
&= ~XECUTED
;
1912 } else if (pwrstat
== 'L') {
1914 * Low battery, shut down now.
1916 if (ch
->action
== POWERFAILNOW
)
1917 ch
->flags
&= ~XECUTED
;
1920 * Power is failing, shutdown imminent
1922 if (ch
->action
== POWERFAIL
|| ch
->action
== POWERWAIT
)
1923 ch
->flags
&= ~XECUTED
;
1929 * Check for state-pipe presence
1932 int check_pipe(int fd
)
1940 t
.tv_sec
= t
.tv_usec
= 0;
1942 if (select(fd
+1, &s
, NULL
, NULL
, &t
) != 1)
1944 if (read(fd
, signature
, 8) != 8)
1946 return strncmp(Signature
, signature
, 8) == 0;
1950 * Make a state-pipe.
1953 int make_pipe(int fd
)
1960 fcntl(fds
[1], F_SETFD
, 1);
1961 fcntl(fd
, F_SETFD
, 0);
1962 write(fds
[1], Signature
, 8);
1968 * Attempt to re-exec.
1974 sigset_t mask
, oldset
;
1979 if (strchr("S0123456",runlevel
) == NULL
)
1983 * Reset the alarm, and block all signals.
1987 sigprocmask(SIG_BLOCK
, &mask
, &oldset
);
1990 * construct a pipe fd --> STATE_PIPE and write a signature
1992 fd
= make_pipe(STATE_PIPE
);
1995 * It's a backup day today, so I'm pissed off. Being a BOFH, however,
1996 * does have it's advantages...
2001 DELSET(got_signals
, SIGCHLD
);
2002 DELSET(got_signals
, SIGHUP
);
2003 DELSET(got_signals
, SIGUSR1
);
2006 * That should be cleaned.
2008 for(ch
= family
; ch
; ch
= ch
->next
)
2009 if (ch
->flags
& ZOMBIE
) {
2010 INITDBG(L_VB
, "Child died, PID= %d", ch
->pid
);
2011 ch
->flags
&= ~(RUNNING
|ZOMBIE
|WAITING
);
2012 if (ch
->process
[0] != '+')
2013 write_utmp_wtmp("", ch
->id
, ch
->pid
, DEAD_PROCESS
, NULL
);
2016 if ((pid
= fork()) == 0) {
2018 * Child sends state information to the parent.
2025 * The existing init process execs a new init binary.
2027 env
= init_buildenv(0);
2028 execle(myname
, myname
, "--init", NULL
, env
);
2031 * We shouldn't be here, something failed.
2032 * Bitch, close the state pipe, unblock signals and return.
2036 sigprocmask(SIG_SETMASK
, &oldset
, NULL
);
2038 initlog(L_CO
, "Attempt to re-exec failed");
2042 * Redo utmp/wtmp entries if required or requested
2043 * Check for written records and size of utmp
2046 void redo_utmp_wtmp(void)
2049 const int ret
= stat(UTMP_FILE
, &ustat
);
2051 if ((ret
< 0) || (ustat
.st_size
== 0))
2052 wrote_utmp_rlevel
= wrote_utmp_reboot
= 0;
2054 if ((wrote_wtmp_reboot
== 0) || (wrote_utmp_reboot
== 0))
2055 write_utmp_wtmp("reboot", "~~", 0, BOOT_TIME
, "~");
2057 if ((wrote_wtmp_rlevel
== 0) || (wrote_wtmp_rlevel
== 0))
2058 write_utmp_wtmp("runlevel", "~~", thislevel
+ 256 * prevlevel
, RUN_LVL
, "~");
2062 * We got a change runlevel request through the
2063 * init.fifo. Process it.
2066 void fifo_new_level(int level
)
2073 if (level
== runlevel
) return;
2076 /* Are we waiting for a child? */
2077 for(ch
= family
; ch
; ch
= ch
->next
)
2078 if (ch
->flags
& WAITING
) break;
2082 /* We need to go into a new runlevel */
2083 oldlevel
= runlevel
;
2084 runlevel
= read_level(level
);
2085 if (runlevel
== 'U') {
2086 runlevel
= oldlevel
;
2089 if (oldlevel
!= 'S' && runlevel
== 'S') console_stty();
2090 if (runlevel
== '6' || runlevel
== '0' ||
2091 runlevel
== '1') console_stty();
2092 if (runlevel
> '1' && runlevel
< '6') redo_utmp_wtmp();
2095 setproctitle("init [%c]", (int)runlevel
);
2102 * Set/unset environment variables. The variables are
2103 * encoded as KEY=VAL\0KEY=VAL\0\0. With "=VAL" it means
2104 * setenv, without it means unsetenv.
2107 void initcmd_setenv(char *data
, int size
)
2109 char *env
, *p
, *e
, *eq
;
2114 while (*data
&& data
< e
) {
2116 for (p
= data
; *p
&& p
< e
; p
++)
2117 if (*p
== '=') eq
= p
;
2122 sz
= eq
? (eq
- env
) : (p
- env
);
2124 /*initlog(L_SY, "init_setenv: %s, %s, %d", env, eq, sz);*/
2127 * We only allow INIT_* to be set.
2129 if (strncmp(env
, "INIT_", 5) != 0)
2132 /* Free existing vars. */
2133 for (i
= 0; i
< NR_EXTRA_ENV
; i
++) {
2134 if (extra_env
[i
] == NULL
) continue;
2135 if (!strncmp(extra_env
[i
], env
, sz
) &&
2136 extra_env
[i
][sz
] == '=') {
2138 extra_env
[i
] = NULL
;
2142 /* Set new vars if needed. */
2143 if (eq
== NULL
) continue;
2144 for (i
= 0; i
< NR_EXTRA_ENV
; i
++) {
2145 if (extra_env
[i
] == NULL
) {
2146 extra_env
[i
] = istrdup(env
);
2155 * Read from the init FIFO. Processes like telnetd and rlogind can
2156 * ask us to create login processes on their behalf.
2158 * FIXME: this needs to be finished. NOT that it is buggy, but we need
2159 * to add the telnetd/rlogind stuff so people can start using it.
2160 * Maybe move to using an AF_UNIX socket so we can use
2161 * the 2.2 kernel credential stuff to see who we're talking to.
2165 void check_init_fifo(void)
2167 struct init_request request
;
2169 struct stat st
, st2
;
2175 * First, try to create /dev/initctl if not present.
2177 if (stat(INIT_FIFO
, &st2
) < 0 && errno
== ENOENT
)
2178 (void)mkfifo(INIT_FIFO
, 0600);
2181 * If /dev/initctl is open, stat the file to see if it
2182 * is still the _same_ inode.
2185 fstat(pipe_fd
, &st
);
2186 if (stat(INIT_FIFO
, &st2
) < 0 ||
2187 st
.st_dev
!= st2
.st_dev
||
2188 st
.st_ino
!= st2
.st_ino
) {
2195 * Now finally try to open /dev/initctl
2198 if ((pipe_fd
= open(INIT_FIFO
, O_RDWR
|O_NONBLOCK
)) >= 0) {
2199 fstat(pipe_fd
, &st
);
2200 if (!S_ISFIFO(st
.st_mode
)) {
2201 initlog(L_VB
, "%s is not a fifo", INIT_FIFO
);
2208 * Don't use fd's 0, 1 or 2.
2210 (void) dup2(pipe_fd
, PIPE_FD
);
2215 * Return to caller - we'll be back later.
2220 /* Wait for data to appear, _if_ the pipe was opened. */
2221 if (pipe_fd
>= 0) while(!quit
) {
2223 /* Do select, return on EINTR. */
2225 FD_SET(pipe_fd
, &fds
);
2228 n
= select(pipe_fd
+ 1, &fds
, NULL
, NULL
, &tv
);
2230 if (n
== 0 || errno
== EINTR
) return;
2234 /* Read the data, return on EINTR. */
2235 n
= read(pipe_fd
, &request
, sizeof(request
));
2238 * End of file. This can't happen under Linux (because
2239 * the pipe is opened O_RDWR - see select() in the
2240 * kernel) but you never know...
2247 if (errno
== EINTR
) return;
2248 initlog(L_VB
, "error reading initrequest");
2253 * This is a convenient point to also try to
2254 * find the console device or check if it changed.
2261 if (request
.magic
!= INIT_MAGIC
|| n
!= sizeof(request
)) {
2262 initlog(L_VB
, "got bogus initrequest");
2265 switch(request
.cmd
) {
2266 case INIT_CMD_RUNLVL
:
2267 sltime
= request
.sleeptime
;
2268 fifo_new_level(request
.runlevel
);
2271 case INIT_CMD_POWERFAIL
:
2272 sltime
= request
.sleeptime
;
2276 case INIT_CMD_POWERFAILNOW
:
2277 sltime
= request
.sleeptime
;
2281 case INIT_CMD_POWEROK
:
2282 sltime
= request
.sleeptime
;
2286 case INIT_CMD_SETENV
:
2287 initcmd_setenv(request
.i
.data
, sizeof(request
.i
.data
));
2290 initlog(L_VB
, "got unimplemented initrequest.");
2296 * We come here if the pipe couldn't be opened.
2298 if (pipe_fd
< 0) pause();
2304 * This function is used in the transition
2305 * sysinit (-> single user) boot -> multi-user.
2308 void boot_transitions()
2311 static int newlevel
= 0;
2312 static int warn
= 1;
2316 /* Check if there is something to wait for! */
2317 for( ch
= family
; ch
; ch
= ch
->next
)
2318 if ((ch
->flags
& RUNNING
) && ch
->action
!= BOOT
) break;
2321 /* No processes left in this level, proceed to next level. */
2325 case '#': /* SYSINIT -> BOOT */
2326 INITDBG(L_VB
, "SYSINIT -> BOOT");
2328 /* Write a boot record. */
2329 wrote_utmp_reboot
= 0;
2330 wrote_wtmp_reboot
= 0;
2331 write_utmp_wtmp("reboot", "~~", 0, BOOT_TIME
, "~");
2333 /* Get our run level */
2334 newlevel
= dfl_level
? dfl_level
: get_init_default();
2335 if (newlevel
== 'S') {
2336 runlevel
= newlevel
;
2337 /* Not really 'S' but show anyway. */
2338 setproctitle("init [S]");
2342 case '*': /* BOOT -> NORMAL */
2343 INITDBG(L_VB
, "BOOT -> NORMAL");
2344 if (runlevel
!= newlevel
)
2345 loglevel
= newlevel
;
2346 runlevel
= newlevel
;
2350 case 'S': /* Ended SU mode */
2352 INITDBG(L_VB
, "END SU MODE");
2353 newlevel
= get_init_default();
2354 if (!did_boot
&& newlevel
!= 'S')
2357 if (runlevel
!= newlevel
)
2358 loglevel
= newlevel
;
2359 runlevel
= newlevel
;
2363 for(ch
= family
; ch
; ch
= ch
->next
)
2364 if (strcmp(ch
->rlevel
, "S") == 0)
2365 ch
->flags
&= ~(FAILING
|WAITING
|XECUTED
);
2370 "no more processes left in this runlevel");
2373 if (got_signals
== 0)
2378 initlog(L_VB
, "Entering runlevel: %c", runlevel
);
2379 wrote_utmp_rlevel
= 0;
2380 wrote_wtmp_rlevel
= 0;
2381 write_utmp_wtmp("runlevel", "~~", runlevel
+ 256 * oldlevel
, RUN_LVL
, "~");
2382 thislevel
= runlevel
;
2383 prevlevel
= oldlevel
;
2384 setproctitle("init [%c]", (int)runlevel
);
2390 * Init got hit by a signal. See which signal it is,
2391 * and act accordingly.
2394 void process_signals()
2402 if (ISMEMBER(got_signals
, SIGPWR
)) {
2403 INITDBG(L_VB
, "got SIGPWR");
2404 /* See _what_ kind of SIGPWR this is. */
2406 if ((fd
= open(PWRSTAT
, O_RDONLY
)) >= 0) {
2412 } else if ((fd
= open(PWRSTAT_OLD
, O_RDONLY
)) >= 0) {
2413 /* Path changed 2010-03-20. Look for the old path for a while. */
2414 initlog(L_VB
, "warning: found obsolete path %s, use %s instead",
2415 PWRSTAT_OLD
, PWRSTAT
);
2420 unlink(PWRSTAT_OLD
);
2422 do_power_fail(pwrstat
);
2423 DELSET(got_signals
, SIGPWR
);
2426 if (ISMEMBER(got_signals
, SIGINT
)) {
2427 #if defined(SIGINT_ONLYONCE) && (SIGINT_ONLYONCE == 1)
2428 /* Ignore any further signal from keyboard */
2429 struct sigaction sa
;
2430 SETSIG(sa
, SIGINT
, SIG_IGN
, SA_RESTART
);
2432 INITDBG(L_VB
, "got SIGINT");
2433 /* Tell ctrlaltdel entry to start up */
2434 for(ch
= family
; ch
; ch
= ch
->next
)
2435 if (ch
->action
== CTRLALTDEL
)
2436 ch
->flags
&= ~XECUTED
;
2437 DELSET(got_signals
, SIGINT
);
2440 if (ISMEMBER(got_signals
, SIGWINCH
)) {
2441 INITDBG(L_VB
, "got SIGWINCH");
2442 /* Tell kbrequest entry to start up */
2443 for(ch
= family
; ch
; ch
= ch
->next
)
2444 if (ch
->action
== KBREQUEST
)
2445 ch
->flags
&= ~XECUTED
;
2446 DELSET(got_signals
, SIGWINCH
);
2449 if (ISMEMBER(got_signals
, SIGALRM
)) {
2450 INITDBG(L_VB
, "got SIGALRM");
2451 /* The timer went off: check it out */
2452 DELSET(got_signals
, SIGALRM
);
2455 if (ISMEMBER(got_signals
, SIGCHLD
)) {
2456 INITDBG(L_VB
, "got SIGCHLD");
2457 /* First set flag to 0 */
2458 DELSET(got_signals
, SIGCHLD
);
2460 /* See which child this was */
2461 for(ch
= family
; ch
; ch
= ch
->next
)
2462 if (ch
->flags
& ZOMBIE
) {
2463 INITDBG(L_VB
, "Child died, PID= %d", ch
->pid
);
2464 ch
->flags
&= ~(RUNNING
|ZOMBIE
|WAITING
);
2465 if (ch
->process
[0] != '+')
2466 write_utmp_wtmp("", ch
->id
, ch
->pid
, DEAD_PROCESS
, NULL
);
2471 if (ISMEMBER(got_signals
, SIGHUP
)) {
2472 INITDBG(L_VB
, "got SIGHUP");
2474 /* Are we waiting for a child? */
2475 for(ch
= family
; ch
; ch
= ch
->next
)
2476 if (ch
->flags
& WAITING
) break;
2480 /* We need to go into a new runlevel */
2481 oldlevel
= runlevel
;
2483 runlevel
= read_level(0);
2485 if (runlevel
== 'U') {
2486 runlevel
= oldlevel
;
2489 if (oldlevel
!= 'S' && runlevel
== 'S') console_stty();
2490 if (runlevel
== '6' || runlevel
== '0' ||
2491 runlevel
== '1') console_stty();
2494 setproctitle("init [%c]", (int)runlevel
);
2495 DELSET(got_signals
, SIGHUP
);
2499 if (ISMEMBER(got_signals
, SIGUSR1
)) {
2501 * SIGUSR1 means close and reopen /dev/initctl
2503 INITDBG(L_VB
, "got SIGUSR1");
2506 DELSET(got_signals
, SIGUSR1
);
2514 void init_main(void)
2517 struct sigaction sa
;
2525 * Fork so we can debug the init process.
2527 if ((f
= fork()) > 0) {
2528 static const char killmsg
[] = "PRNT: init killed.\r\n";
2531 while((rc
= wait(&st
)) != f
)
2532 if (rc
< 0 && errno
== ECHILD
)
2534 write(1, killmsg
, sizeof(killmsg
) - 1);
2541 * Tell the kernel to send us SIGINT when CTRL-ALT-DEL
2542 * is pressed, and that we want to handle keyboard signals.
2544 init_reboot(BMAGIC_SOFT
);
2545 if ((f
= open(VT_MASTER
, O_RDWR
| O_NOCTTY
)) >= 0) {
2546 (void) ioctl(f
, KDSIGACCEPT
, SIGWINCH
);
2549 (void) ioctl(0, KDSIGACCEPT
, SIGWINCH
);
2553 * Ignore all signals.
2555 for(f
= 1; f
<= NSIG
; f
++)
2556 SETSIG(sa
, f
, SIG_IGN
, SA_RESTART
);
2559 SETSIG(sa
, SIGALRM
, signal_handler
, 0);
2560 SETSIG(sa
, SIGHUP
, signal_handler
, 0);
2561 SETSIG(sa
, SIGINT
, signal_handler
, 0);
2562 SETSIG(sa
, SIGCHLD
, chld_handler
, SA_RESTART
);
2563 SETSIG(sa
, SIGPWR
, signal_handler
, 0);
2564 SETSIG(sa
, SIGWINCH
, signal_handler
, 0);
2565 SETSIG(sa
, SIGUSR1
, signal_handler
, 0);
2566 SETSIG(sa
, SIGSTOP
, stop_handler
, SA_RESTART
);
2567 SETSIG(sa
, SIGTSTP
, stop_handler
, SA_RESTART
);
2568 SETSIG(sa
, SIGCONT
, cont_handler
, SA_RESTART
);
2569 SETSIG(sa
, SIGSEGV
, (void (*)(int))segv_handler
, SA_RESTART
);
2576 /* Close whatever files are open, and reset the console. */
2584 * Set default PATH variable.
2586 setenv("PATH", PATH_DEFAULT
, 1 /* Overwrite */);
2589 * Initialize /var/run/utmp (only works if /var is on
2590 * root and mounted rw)
2592 if ((fd
= open(UTMP_FILE
, O_WRONLY
|O_CREAT
|O_TRUNC
, 0644)) >= 0)
2596 * Say hello to the world
2598 initlog(L_CO
, bootmsg
, "booting");
2601 * See if we have to start an emergency shell.
2605 SETSIG(sa
, SIGCHLD
, SIG_DFL
, SA_RESTART
);
2606 if (spawn(&ch_emerg
, &f
) > 0) {
2607 while((rc
= wait(&st
)) != f
)
2608 if (rc
< 0 && errno
== ECHILD
)
2611 SETSIG(sa
, SIGCHLD
, chld_handler
, SA_RESTART
);
2615 * Start normal boot procedure.
2622 * Restart: unblock signals and let the show go on
2624 initlog(L_CO
, bootmsg
, "reloading");
2626 sigprocmask(SIG_UNBLOCK
, &sgt
, NULL
);
2629 * Set default PATH variable.
2631 setenv("PATH", PATH_DEFAULT
, 0 /* Don't overwrite */);
2637 /* See if we need to make the boot transitions. */
2639 INITDBG(L_VB
, "init_main: waiting..");
2641 /* Check if there are processes to be waited on. */
2642 for(ch
= family
; ch
; ch
= ch
->next
)
2643 if ((ch
->flags
& RUNNING
) && ch
->action
!= BOOT
) break;
2646 /* Wait until we get hit by some signal. */
2647 while (ch
!= NULL
&& got_signals
== 0) {
2648 if (ISMEMBER(got_signals
, SIGHUP
)) {
2649 /* See if there are processes to be waited on. */
2650 for(ch
= family
; ch
; ch
= ch
->next
)
2651 if (ch
->flags
& WAITING
) break;
2653 if (ch
!= NULL
) check_init_fifo();
2655 #else /* CHANGE_WAIT */
2656 if (ch
!= NULL
&& got_signals
== 0) check_init_fifo();
2657 #endif /* CHANGE_WAIT */
2659 /* Check the 'failing' flags */
2662 /* Process any signals. */
2665 /* See what we need to start up (again) */
2672 * Tell the user about the syntax we expect.
2677 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
);
2682 int telinit(char *progname
, int argc
, char **argv
)
2684 #ifdef TELINIT_USES_INITLVL
2687 struct init_request request
;
2688 struct sigaction sa
;
2692 memset(&request
, 0, sizeof(request
));
2693 request
.magic
= INIT_MAGIC
;
2695 while ((f
= getopt(argc
, argv
, "t:e:")) != EOF
) switch(f
) {
2697 sltime
= atoi(optarg
);
2701 env
= request
.i
.data
;
2703 if (env
+ l
+ 2 > request
.i
.data
+ sizeof(request
.i
.data
)) {
2704 fprintf(stderr
, "%s: -e option data "
2705 "too large\n", progname
);
2708 memcpy(env
, optarg
, l
);
2717 if (env
) *env
++ = 0;
2722 request
.cmd
= INIT_CMD_SETENV
;
2724 if (argc
- optind
!= 1 || strlen(argv
[optind
]) != 1)
2726 if (!strchr("0123456789SsQqAaBbCcUu", argv
[optind
][0]))
2728 request
.cmd
= INIT_CMD_RUNLVL
;
2729 request
.runlevel
= env
? 0 : argv
[optind
][0];
2730 request
.sleeptime
= sltime
;
2733 /* Change to the root directory. */
2736 /* Open the fifo and write a command. */
2737 /* Make sure we don't hang on opening /dev/initctl */
2738 SETSIG(sa
, SIGALRM
, signal_handler
, 0);
2740 if ((fd
= open(INIT_FIFO
, O_WRONLY
)) >= 0) {
2742 size_t s
= sizeof(request
);
2743 void *ptr
= &request
;
2746 p
= write(fd
, ptr
, s
);
2748 if (errno
== EINTR
|| errno
== EAGAIN
)
2760 #ifdef TELINIT_USES_INITLVL
2761 if (request
.cmd
== INIT_CMD_RUNLVL
) {
2762 /* Fallthrough to the old method. */
2764 /* Now write the new runlevel. */
2765 if ((fp
= fopen(INITLVL
, "w")) == NULL
) {
2766 fprintf(stderr
, "%s: cannot create %s\n",
2770 fprintf(fp
, "%s %d", argv
[optind
], sltime
);
2773 /* And tell init about the pending runlevel change. */
2774 if (kill(INITPID
, SIGHUP
) < 0) perror(progname
);
2780 fprintf(stderr
, "%s: ", progname
);
2781 if (ISMEMBER(got_signals
, SIGALRM
)) {
2782 fprintf(stderr
, "timeout opening/writing control channel %s\n",
2791 * Main entry for init and telinit.
2793 int main(int argc
, char **argv
)
2802 /* Get my own name */
2803 if ((p
= strrchr(argv
[0], '/')) != NULL
)
2812 if (geteuid() != 0) {
2813 fprintf(stderr
, "%s: must be superuser.\n", p
);
2818 * Is this telinit or init ?
2820 isinit
= (getpid() == 1);
2821 for (f
= 1; f
< argc
; f
++) {
2822 if (!strcmp(argv
[f
], "-i") || !strcmp(argv
[f
], "--init")) {
2827 if (!isinit
) exit(telinit(p
, argc
, argv
));
2832 if (check_pipe(STATE_PIPE
)) {
2834 receive_state(STATE_PIPE
);
2836 myname
= istrdup(argv
[0]);
2839 for (f
= 0; f
< argc
; f
++)
2840 maxproclen
+= strlen(argv
[f
]) + 1;
2842 setproctitle("init [%c]", (int)runlevel
);
2847 /* Check command line arguments */
2848 maxproclen
= strlen(argv
[0]) + 1;
2849 for(f
= 1; f
< argc
; f
++) {
2850 if (!strcmp(argv
[f
], "single") || !strcmp(argv
[f
], "-s"))
2852 else if (!strcmp(argv
[f
], "-a") || !strcmp(argv
[f
], "auto"))
2853 putenv("AUTOBOOT=YES");
2854 else if (!strcmp(argv
[f
], "-b") || !strcmp(argv
[f
],"emergency"))
2856 else if (!strcmp(argv
[f
], "-z")) {
2858 if (argv
[f
+ 1]) f
++;
2859 } else if (strchr("0123456789sS", argv
[f
][0])
2860 && strlen(argv
[f
]) == 1)
2861 dfl_level
= argv
[f
][0];
2862 /* "init u" in the very beginning makes no sense */
2863 if (dfl_level
== 's') dfl_level
= 'S';
2864 maxproclen
+= strlen(argv
[f
]) + 1;
2868 if (getenv("SELINUX_INIT") == NULL
) {
2869 const int rc
= mount("proc", "/proc", "proc", 0, 0);
2870 if (is_selinux_enabled() > 0) {
2871 putenv("SELINUX_INIT=YES");
2872 if (rc
== 0) umount2("/proc", MNT_DETACH
);
2873 if (selinux_init_load_policy(&enforce
) == 0) {
2874 execv(myname
, argv
);
2877 /* SELinux in enforcing mode but load_policy failed */
2878 /* At this point, we probably can't open /dev/console, so log() won't work */
2879 fprintf(stderr
,"Unable to load SELinux Policy. Machine is in enforcing mode. Halting now.\n");
2884 if (rc
== 0) umount2("/proc", MNT_DETACH
);
2887 /* Start booting. */
2890 setproctitle("init boot");