]>
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>
58 # ifndef MNT_DETACH /* present in glibc 2.10, missing in 2.7 */
66 # define STACK_DEBUG 1
67 # if (__GLIBC__ == 2 && __GLIBC_MINOR__ == 0)
68 /* Only glibc 2.0 needs this */
69 # include <sigcontext.h>
70 # elif ( __GLIBC__ > 2) && ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 1))
71 # include <bits/sigcontext.h>
83 # define SIGPWR SIGUSR2
93 /* Set a signal handler. */
94 #define SETSIG(sa, sig, fun, flags) \
96 sa.sa_handler = fun; \
97 sa.sa_flags = flags; \
98 sigemptyset(&sa.sa_mask); \
99 sigaction(sig, &sa, NULL); \
102 /* Version information */
103 char *Version
= "@(#) init " VERSION
" " DATE
" miquels@cistron.nl";
104 char *bootmsg
= "version " VERSION
" %s";
105 #define E_VERSION "INIT_VERSION=sysvinit-" VERSION
107 CHILD
*family
= NULL
; /* The linked list of all entries */
108 CHILD
*newFamily
= NULL
; /* The list after inittab re-read */
110 CHILD ch_emerg
= { /* Emergency shell */
120 char runlevel
= 'S'; /* The current run level */
121 char thislevel
= 'S'; /* The current runlevel */
122 char prevlevel
= 'N'; /* Previous runlevel */
123 int dfl_level
= 0; /* Default runlevel */
124 sig_atomic_t got_cont
= 0; /* Set if we received the SIGCONT signal */
125 sig_atomic_t got_signals
; /* Set if we received a signal. */
126 int emerg_shell
= 0; /* Start emergency shell? */
127 int wrote_wtmp_reboot
= 1; /* Set when we wrote the reboot record */
128 int wrote_utmp_reboot
= 1; /* Set when we wrote the reboot record */
129 int wrote_wtmp_rlevel
= 1; /* Set when we wrote the runlevel record */
130 int wrote_utmp_rlevel
= 1; /* Set when we wrote the runlevel record */
131 int sltime
= 5; /* Sleep time between TERM and KILL */
132 char *argv0
; /* First arguments; show up in ps listing */
133 int maxproclen
; /* Maximal length of argv[0] with \0 */
134 struct utmp utproto
; /* Only used for sizeof(utproto.ut_id) */
135 char *console_dev
; /* Console device. */
136 int pipe_fd
= -1; /* /dev/initctl */
137 int did_boot
= 0; /* Did we already do BOOT* stuff? */
138 int main(int, char **);
140 /* Used by re-exec part */
141 int reload
= 0; /* Should we do initialization stuff? */
142 char *myname
="/sbin/init"; /* What should we exec */
143 int oops_error
; /* Used by some of the re-exec code. */
144 const char *Signature
= "12567362"; /* Signature for re-exec fd */
146 /* Macro to see if this is a special action */
147 #define ISPOWER(i) ((i) == POWERWAIT || (i) == POWERFAIL || \
148 (i) == POWEROKWAIT || (i) == POWERFAILNOW || \
151 /* ascii values for the `action' field. */
156 { "respawn", RESPAWN
},
160 { "bootwait", BOOTWAIT
},
161 { "powerfail", POWERFAIL
},
162 { "powerfailnow",POWERFAILNOW
},
163 { "powerwait", POWERWAIT
},
164 { "powerokwait", POWEROKWAIT
},
165 { "ctrlaltdel", CTRLALTDEL
},
167 { "ondemand", ONDEMAND
},
168 { "initdefault", INITDEFAULT
},
169 { "sysinit", SYSINIT
},
170 { "kbrequest", KBREQUEST
},
175 * State parser token table (see receive_state)
188 { "CMD", C_PROCESS
},
191 { "-RL", D_RUNLEVEL
},
192 { "-TL", D_THISLEVEL
},
193 { "-PL", D_PREVLEVEL
},
194 { "-SI", D_GOTSIGN
},
195 { "-WR", D_WROTE_WTMP_REBOOT
},
196 { "-WU", D_WROTE_UTMP_REBOOT
},
198 { "-DB", D_DIDBOOT
},
199 { "-LW", D_WROTE_WTMP_RLEVEL
},
200 { "-LU", D_WROTE_UTMP_RLEVEL
},
214 #define NR_EXTRA_ENV 16
215 char *extra_env
[NR_EXTRA_ENV
];
219 * Sleep a number of seconds.
221 * This only works correctly because the linux select updates
222 * the elapsed time in the struct timeval passed to select!
225 void do_sleep(int sec
)
232 while(select(0, NULL
, NULL
, NULL
, &tv
) < 0 && errno
== EINTR
)
238 * Non-failing allocation routines (init cannot fail).
241 void *imalloc(size_t size
)
245 while ((m
= malloc(size
)) == NULL
) {
246 initlog(L_VB
, "out of memory");
254 char *istrdup(char *s
)
267 * Send the state info of the previous running init to
268 * the new one, in a version-independant way.
271 void send_state(int fd
)
279 fprintf(fp
, "VER%s\n", Version
);
280 fprintf(fp
, "-RL%c\n", runlevel
);
281 fprintf(fp
, "-TL%c\n", thislevel
);
282 fprintf(fp
, "-PL%c\n", prevlevel
);
283 fprintf(fp
, "-SI%u\n", got_signals
);
284 fprintf(fp
, "-WR%d\n", wrote_wtmp_reboot
);
285 fprintf(fp
, "-WU%d\n", wrote_utmp_reboot
);
286 fprintf(fp
, "-ST%d\n", sltime
);
287 fprintf(fp
, "-DB%d\n", did_boot
);
289 for (p
= family
; p
; p
= p
->next
) {
290 fprintf(fp
, "REC%s\n", p
->id
);
291 fprintf(fp
, "LEV%s\n", p
->rlevel
);
292 for (i
= 0, val
= p
->flags
; flags
[i
].mask
; i
++)
293 if (val
& flags
[i
].mask
) {
294 val
&= ~flags
[i
].mask
;
295 fprintf(fp
, "FL %s\n",flags
[i
].name
);
297 fprintf(fp
, "PID%d\n",p
->pid
);
298 fprintf(fp
, "EXS%u\n",p
->exstat
);
299 for(i
= 0; actions
[i
].act
; i
++)
300 if (actions
[i
].act
== p
->action
) {
301 fprintf(fp
, "AC %s\n", actions
[i
].name
);
304 fprintf(fp
, "CMD%s\n", p
->process
);
305 fprintf(fp
, "EOR\n");
307 fprintf(fp
, "END\n");
312 * Read a string from a file descriptor.
313 * FIXME: why not use fgets() ?
315 static int get_string(char *p
, int size
, FILE *f
)
319 while ((c
= getc(f
)) != EOF
&& c
!= '\n') {
324 return (c
!= EOF
) && (size
> 0);
328 * Read trailing data from the state pipe until we see a newline.
330 static int get_void(FILE *f
)
334 while ((c
= getc(f
)) != EOF
&& c
!= '\n')
341 * Read the next "command" from the state pipe.
343 static int get_cmd(FILE *f
)
348 if (fread(cmd
, 1, sizeof(cmd
) - 1, f
) != sizeof(cmd
) - 1)
351 for(i
= 0; cmds
[i
].cmd
&& strcmp(cmds
[i
].name
, cmd
) != 0; i
++)
357 * Read a CHILD * from the state pipe.
359 static CHILD
*get_record(FILE *f
)
367 switch (cmd
= get_cmd(f
)) {
377 fscanf(f
, "%c\n", &runlevel
);
380 fscanf(f
, "%c\n", &thislevel
);
383 fscanf(f
, "%c\n", &prevlevel
);
386 fscanf(f
, "%u\n", &got_signals
);
388 case D_WROTE_WTMP_REBOOT
:
389 fscanf(f
, "%d\n", &wrote_wtmp_reboot
);
391 case D_WROTE_UTMP_REBOOT
:
392 fscanf(f
, "%d\n", &wrote_utmp_reboot
);
395 fscanf(f
, "%d\n", &sltime
);
398 fscanf(f
, "%d\n", &did_boot
);
400 case D_WROTE_WTMP_RLEVEL
:
401 fscanf(f
, "%d\n", &wrote_wtmp_rlevel
);
403 case D_WROTE_UTMP_RLEVEL
:
404 fscanf(f
, "%d\n", &wrote_utmp_rlevel
);
407 if (cmd
> 0 || cmd
== C_EOF
) {
412 } while (cmd
!= C_REC
);
414 p
= imalloc(sizeof(CHILD
));
415 get_string(p
->id
, sizeof(p
->id
), f
);
417 do switch(cmd
= get_cmd(f
)) {
423 fscanf(f
, "%d\n", &(p
->pid
));
426 fscanf(f
, "%u\n", &(p
->exstat
));
429 get_string(p
->rlevel
, sizeof(p
->rlevel
), f
);
432 get_string(p
->process
, sizeof(p
->process
), f
);
435 get_string(s
, sizeof(s
), f
);
436 for(i
= 0; flags
[i
].name
; i
++) {
437 if (strcmp(flags
[i
].name
,s
) == 0)
440 p
->flags
|= flags
[i
].mask
;
443 get_string(s
, sizeof(s
), f
);
444 for(i
= 0; actions
[i
].name
; i
++) {
445 if (strcmp(actions
[i
].name
, s
) == 0)
448 p
->action
= actions
[i
].act
? actions
[i
].act
: OFF
;
454 } while( cmd
!= C_EOR
);
460 * Read the complete state info from the state pipe.
461 * Returns 0 on success
464 int receive_state(int fd
)
467 char old_version
[256];
472 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
);
668 signal(SIGSEGV
, SIG_DFL
);
670 sigdelset(&mask
, SIGSEGV
);
671 sigprocmask(SIG_SETMASK
, &mask
, NULL
);
678 * OOPS: segmentation violation!
679 * If we have the info, print where it occured.
680 * Then sleep 30 seconds and try to continue.
683 #if defined(STACK_DEBUG) && defined(__linux__)
685 void segv_handler(int sig
__attribute__((unused
)), struct sigcontext ctx
)
687 void segv_handler(int sig
, struct sigcontext ctx
)
691 int saved_errno
= errno
;
693 if ((void *)ctx
.eip
>= (void *)do_sleep
&&
694 (void *)ctx
.eip
< (void *)main
)
696 initlog(L_VB
, "PANIC: segmentation violation at %p%s! "
697 "sleeping for 30 seconds.", (void *)ctx
.eip
, p
);
704 void segv_handler(int sig
__attribute__((unused
)))
706 void segv_handler(int sig
)
709 int saved_errno
= errno
;
712 "PANIC: segmentation violation! sleeping for 30 seconds.");
720 * The SIGSTOP & SIGTSTP handler
724 void stop_handler(int sig
__attribute__((unused
)))
726 void stop_handler(int sig
)
729 int saved_errno
= errno
;
732 while(!got_cont
) pause();
738 * Set terminal settings to reasonable defaults
741 void console_stty(void)
746 if ((fd
= console_open(O_RDWR
|O_NOCTTY
)) < 0) {
747 initlog(L_VB
, "can't open %s", console_dev
);
751 #ifdef __FreeBSD_kernel__
753 * The kernel of FreeBSD expects userland to set TERM. Usually, we want
754 * "cons25". Later, gettys might disagree on this (i.e. we're not using
755 * syscons) but some boot scripts, like /etc/init.d/xserver-xorg, still
756 * need a non-dumb terminal.
758 putenv ("TERM=cons25");
761 (void) tcgetattr(fd
, &tty
);
763 tty
.c_cflag
&= CBAUD
|CBAUDEX
|CSIZE
|CSTOPB
|PARENB
|PARODD
;
764 tty
.c_cflag
|= HUPCL
|CLOCAL
|CREAD
;
766 tty
.c_cc
[VINTR
] = CINTR
;
767 tty
.c_cc
[VQUIT
] = CQUIT
;
768 tty
.c_cc
[VERASE
] = CERASE
; /* ASCII DEL (0177) */
769 tty
.c_cc
[VKILL
] = CKILL
;
770 tty
.c_cc
[VEOF
] = CEOF
;
773 tty
.c_cc
[VSWTC
] = _POSIX_VDISABLE
;
774 tty
.c_cc
[VSTART
] = CSTART
;
775 tty
.c_cc
[VSTOP
] = CSTOP
;
776 tty
.c_cc
[VSUSP
] = CSUSP
;
777 tty
.c_cc
[VEOL
] = _POSIX_VDISABLE
;
778 tty
.c_cc
[VREPRINT
] = CREPRINT
;
779 tty
.c_cc
[VDISCARD
] = CDISCARD
;
780 tty
.c_cc
[VWERASE
] = CWERASE
;
781 tty
.c_cc
[VLNEXT
] = CLNEXT
;
782 tty
.c_cc
[VEOL2
] = _POSIX_VDISABLE
;
785 * Set pre and post processing
787 tty
.c_iflag
= IGNPAR
|ICRNL
|IXON
|IXANY
788 #ifdef IUTF8 /* Not defined on FreeBSD */
789 | (tty
.c_iflag
& IUTF8
)
792 tty
.c_oflag
= OPOST
|ONLCR
;
793 tty
.c_lflag
= ISIG
|ICANON
|ECHO
|ECHOCTL
|ECHOPRT
|ECHOKE
;
795 #if defined(SANE_TIO) && (SANE_TIO == 1)
797 * Disable flow control (-ixon), ignore break (ignbrk),
798 * and make nl/cr more usable (sane).
800 tty
.c_iflag
|= IGNBRK
;
801 tty
.c_iflag
&= ~(BRKINT
|INLCR
|IGNCR
|IXON
);
802 tty
.c_oflag
&= ~(OCRNL
|ONLRET
);
805 * Now set the terminal line.
806 * We don't care about non-transmitted output data
807 * and non-read input data.
809 (void) tcsetattr(fd
, TCSANOW
, &tty
);
810 (void) tcflush(fd
, TCIOFLUSH
);
815 * Print to the system console
821 if ((fd
= console_open(O_WRONLY
|O_NOCTTY
|O_NDELAY
)) >= 0) {
822 write(fd
, s
, strlen(s
));
828 * Log something to a logfile and the console.
831 __attribute__ ((format (printf
, 2, 3)))
833 void initlog(int loglevel
, char *s
, ...)
837 sigset_t nmask
, omask
;
839 va_start(va_alist
, s
);
840 vsnprintf(buf
, sizeof(buf
), s
, va_alist
);
843 if (loglevel
& L_SY
) {
845 * Re-establish connection with syslogd every time.
846 * Block signals while talking to syslog.
849 sigprocmask(SIG_BLOCK
, &nmask
, &omask
);
850 openlog("init", 0, LOG_DAEMON
);
851 syslog(LOG_INFO
, "%s", buf
);
853 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
857 * And log to the console.
859 if (loglevel
& L_CO
) {
868 * Build a new environment for execve().
870 char **init_buildenv(int child
)
872 char i_lvl
[] = "RUNLEVEL=x";
873 char i_prev
[] = "PREVLEVEL=x";
875 char i_shell
[] = "SHELL=" SHELL
;
879 for (n
= 0; environ
[n
]; n
++)
884 e
= calloc(n
, sizeof(char *));
886 for (n
= 0; environ
[n
]; n
++)
887 e
[n
] = istrdup(environ
[n
]);
889 for (i
= 0; i
< NR_EXTRA_ENV
; i
++) {
891 e
[n
++] = istrdup(extra_env
[i
]);
895 snprintf(i_cons
, sizeof(i_cons
), "CONSOLE=%s", console_dev
);
896 i_lvl
[9] = thislevel
;
897 i_prev
[10] = prevlevel
;
898 e
[n
++] = istrdup(i_shell
);
899 e
[n
++] = istrdup(i_lvl
);
900 e
[n
++] = istrdup(i_prev
);
901 e
[n
++] = istrdup(i_cons
);
902 e
[n
++] = istrdup(E_VERSION
);
911 void init_freeenv(char **e
)
915 for (n
= 0; e
[n
]; n
++)
924 * This function is too long and indents too deep.
928 pid_t
spawn(CHILD
*ch
, int *res
)
930 char *args
[16]; /* Argv array */
931 char buf
[136]; /* Line buffer */
932 int f
, st
; /* Scratch variables */
933 char *ptr
; /* Ditto */
934 time_t t
; /* System time */
935 int oldAlarm
; /* Previous alarm value */
936 char *proc
= ch
->process
; /* Command line */
937 pid_t pid
, pgrp
; /* child, console process group. */
938 sigset_t nmask
, omask
; /* For blocking SIGCHLD */
942 buf
[sizeof(buf
) - 1] = 0;
944 /* Skip '+' if it's there */
945 if (proc
[0] == '+') proc
++;
947 ch
->flags
|= XECUTED
;
949 if (ch
->action
== RESPAWN
|| ch
->action
== ONDEMAND
) {
950 /* Is the date stamp from less than 2 minutes ago? */
952 if (ch
->tm
+ TESTTIME
> t
) {
959 /* Do we try to respawn too fast? */
960 if (ch
->count
>= MAXSPAWN
) {
963 "Id \"%s\" respawning too fast: disabled for %d minutes",
964 ch
->id
, SLEEPTIME
/ 60);
965 ch
->flags
&= ~RUNNING
;
966 ch
->flags
|= FAILING
;
968 /* Remember the time we stopped */
971 /* Try again in 5 minutes */
973 if (oldAlarm
> SLEEPTIME
|| oldAlarm
<= 0) oldAlarm
= SLEEPTIME
;
979 /* See if there is an "initscript" (except in single user mode). */
980 if (access(INITSCRIPT
, R_OK
) == 0 && runlevel
!= 'S') {
981 /* Build command line using "initscript" */
983 args
[2] = INITSCRIPT
;
985 args
[4] = ch
->rlevel
;
987 for(f
= 0; actions
[f
].name
; f
++) {
988 if (ch
->action
== actions
[f
].act
) {
989 args
[5] = actions
[f
].name
;
995 } else if (strpbrk(proc
, "~`!$^&*()=|\\{}[];\"'<>?")) {
996 /* See if we need to fire off a shell for this command */
997 /* Give command line to shell */
1000 strcpy(buf
, "exec ");
1001 strncat(buf
, proc
, sizeof(buf
) - strlen(buf
) - 1);
1005 /* Split up command line arguments */
1007 strncat(buf
, proc
, sizeof(buf
) - 1);
1009 for(f
= 1; f
< 15; f
++) {
1010 /* Skip white space */
1011 while(*ptr
== ' ' || *ptr
== '\t') ptr
++;
1014 /* May be trailing space.. */
1015 if (*ptr
== 0) break;
1017 /* Skip this `word' */
1018 while(*ptr
&& *ptr
!= ' ' && *ptr
!= '\t' && *ptr
!= '#')
1021 /* If end-of-line, break */
1022 if (*ptr
== '#' || *ptr
== 0) {
1027 /* End word with \0 and continue */
1035 * Block sigchild while forking.
1037 sigemptyset(&nmask
);
1038 sigaddset(&nmask
, SIGCHLD
);
1039 sigprocmask(SIG_BLOCK
, &nmask
, &omask
);
1041 if ((pid
= fork()) == 0) {
1046 if (pipe_fd
>= 0) close(pipe_fd
);
1048 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
1051 * In sysinit, boot, bootwait or single user mode:
1052 * for any wait-type subprocess we _force_ the console
1053 * to be its controlling tty.
1055 if (strchr("*#sS", runlevel
) && ch
->flags
& WAITING
) {
1057 * We fork once extra. This is so that we can
1058 * wait and change the process group and session
1059 * of the console after exit of the leader.
1062 if ((f
= console_open(O_RDWR
|O_NOCTTY
)) >= 0) {
1063 /* Take over controlling tty by force */
1064 (void)ioctl(f
, TIOCSCTTY
, 1);
1070 * 4 Sep 2001, Andrea Arcangeli:
1071 * Fix a race in spawn() that is used to deadlock init in a
1072 * waitpid() loop: must set the childhandler as default before forking
1073 * off the child or the chld_handler could run before the waitpid loop
1074 * has a chance to find its zombie-child.
1076 SETSIG(sa
, SIGCHLD
, SIG_DFL
, SA_RESTART
);
1077 if ((pid
= fork()) < 0) {
1078 initlog(L_VB
, "cannot fork: %s",
1085 * Ignore keyboard signals etc.
1086 * Then wait for child to exit.
1088 SETSIG(sa
, SIGINT
, SIG_IGN
, SA_RESTART
);
1089 SETSIG(sa
, SIGTSTP
, SIG_IGN
, SA_RESTART
);
1090 SETSIG(sa
, SIGQUIT
, SIG_IGN
, SA_RESTART
);
1092 while ((rc
= waitpid(pid
, &st
, 0)) != pid
)
1093 if (rc
< 0 && errno
== ECHILD
)
1097 * Small optimization. See if stealing
1098 * controlling tty back is needed.
1100 pgrp
= tcgetpgrp(f
);
1101 if (pgrp
!= getpid())
1105 * Steal controlling tty away. We do
1106 * this with a temporary process.
1108 if ((pid
= fork()) < 0) {
1109 initlog(L_VB
, "cannot fork: %s",
1115 (void)ioctl(f
, TIOCSCTTY
, 1);
1118 while((rc
= waitpid(pid
, &st
, 0)) != pid
)
1119 if (rc
< 0 && errno
== ECHILD
)
1124 /* Set ioctl settings to default ones */
1129 if ((f
= console_open(O_RDWR
|O_NOCTTY
)) < 0) {
1130 initlog(L_VB
, "open(%s): %s", console_dev
,
1132 f
= open("/dev/null", O_RDWR
);
1139 * Update utmp/wtmp file prior to starting
1140 * any child. This MUST be done right here in
1141 * the child process in order to prevent a race
1142 * condition that occurs when the child
1143 * process' time slice executes before the
1144 * parent (can and does happen in a uniprocessor
1145 * environment). If the child is a getty and
1146 * the race condition happens, then init's utmp
1147 * update will happen AFTER the getty runs
1148 * and expects utmp to be updated already!
1150 * Do NOT log if process field starts with '+'
1151 * FIXME: that's for compatibility with *very*
1152 * old getties - probably it can be taken out.
1154 if (ch
->process
[0] != '+')
1155 write_utmp_wtmp("", ch
->id
, getpid(), INIT_PROCESS
, "");
1157 /* Reset all the signals, set up environment */
1158 for(f
= 1; f
< NSIG
; f
++) SETSIG(sa
, f
, SIG_DFL
, SA_RESTART
);
1159 environ
= init_buildenv(1);
1162 * Execute prog. In case of ENOEXEC try again
1163 * as a shell script.
1165 execvp(args
[1], args
+ 1);
1166 if (errno
== ENOEXEC
) {
1169 strcpy(buf
, "exec ");
1170 strncat(buf
, proc
, sizeof(buf
) - strlen(buf
) - 1);
1173 execvp(args
[1], args
+ 1);
1175 initlog(L_VB
, "cannot execute \"%s\"", args
[1]);
1177 if (ch
->process
[0] != '+')
1178 write_utmp_wtmp("", ch
->id
, getpid(), DEAD_PROCESS
, NULL
);
1182 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
1184 INITDBG(L_VB
, "Started id %s (pid %d)", ch
->id
, pid
);
1187 initlog(L_VB
, "cannot fork, retry..");
1196 * Start a child running!
1199 void startup(CHILD
*ch
)
1202 * See if it's disabled
1204 if (ch
->flags
& FAILING
) return;
1206 switch(ch
->action
) {
1215 if (!(ch
->flags
& XECUTED
)) ch
->flags
|= WAITING
;
1220 if (ch
->flags
& XECUTED
) break;
1223 ch
->flags
|= RUNNING
;
1224 (void)spawn(ch
, &(ch
->pid
));
1231 * Read the inittab file.
1234 void read_inittab(void)
1236 FILE *fp
; /* The INITTAB file */
1237 CHILD
*ch
, *old
, *i
; /* Pointers to CHILD structure */
1238 CHILD
*head
= NULL
; /* Head of linked list */
1240 struct stat st
; /* To stat INITLVL */
1242 sigset_t nmask
, omask
; /* For blocking SIGCHLD. */
1243 char buf
[256]; /* Line buffer */
1244 char err
[64]; /* Error message. */
1246 *action
, *process
; /* Fields of a line */
1248 int lineNo
= 0; /* Line number in INITTAB file */
1249 int actionNo
; /* Decoded action field */
1250 int f
; /* Counter */
1251 int round
; /* round 0 for SIGTERM, 1 for SIGKILL */
1252 int foundOne
= 0; /* No killing no sleep */
1253 int talk
; /* Talk to the user */
1254 int done
= 0; /* Ready yet? */
1257 if (newFamily
!= NULL
) {
1258 INITDBG(L_VB
, "PANIC newFamily != NULL");
1261 INITDBG(L_VB
, "Reading inittab");
1265 * Open INITTAB and real line by line.
1267 if ((fp
= fopen(INITTAB
, "r")) == NULL
)
1268 initlog(L_VB
, "No inittab file found");
1272 * Add single user shell entry at the end.
1274 if (fp
== NULL
|| fgets(buf
, sizeof(buf
), fp
) == NULL
) {
1277 * See if we have a single user entry.
1279 for(old
= newFamily
; old
; old
= old
->next
)
1280 if (strpbrk(old
->rlevel
, "S")) break;
1282 snprintf(buf
, sizeof(buf
), "~~:S:wait:%s\n", SULOGIN
);
1288 * Skip comments and empty lines
1290 for(p
= buf
; *p
== ' ' || *p
== '\t'; p
++)
1292 if (*p
== '#' || *p
== '\n') continue;
1297 id
= strsep(&p
, ":");
1298 rlevel
= strsep(&p
, ":");
1299 action
= strsep(&p
, ":");
1300 process
= strsep(&p
, "\n");
1303 * Check if syntax is OK. Be very verbose here, to
1304 * avoid newbie postings on comp.os.linux.setup :)
1307 if (!id
|| !*id
) strcpy(err
, "missing id field");
1308 if (!rlevel
) strcpy(err
, "missing runlevel field");
1309 if (!process
) strcpy(err
, "missing process field");
1310 if (!action
|| !*action
)
1311 strcpy(err
, "missing action field");
1312 if (id
&& strlen(id
) > sizeof(utproto
.ut_id
))
1313 sprintf(err
, "id field too long (max %d characters)",
1314 (int)sizeof(utproto
.ut_id
));
1315 if (rlevel
&& strlen(rlevel
) > 11)
1316 strcpy(err
, "rlevel field too long (max 11 characters)");
1317 if (process
&& strlen(process
) > 127)
1318 strcpy(err
, "process field too long");
1319 if (action
&& strlen(action
) > 32)
1320 strcpy(err
, "action field too long");
1322 initlog(L_VB
, "%s[%d]: %s", INITTAB
, lineNo
, err
);
1323 INITDBG(L_VB
, "%s:%s:%s:%s", id
, rlevel
, action
, process
);
1328 * Decode the "action" field
1331 for(f
= 0; actions
[f
].name
; f
++)
1332 if (strcasecmp(action
, actions
[f
].name
) == 0) {
1333 actionNo
= actions
[f
].act
;
1336 if (actionNo
== -1) {
1337 initlog(L_VB
, "%s[%d]: %s: unknown action field",
1338 INITTAB
, lineNo
, action
);
1343 * See if the id field is unique
1345 for(old
= newFamily
; old
; old
= old
->next
) {
1346 if(strcmp(old
->id
, id
) == 0 && strcmp(id
, "~~")) {
1347 initlog(L_VB
, "%s[%d]: duplicate ID field \"%s\"",
1348 INITTAB
, lineNo
, id
);
1355 * Allocate a CHILD structure
1357 ch
= imalloc(sizeof(CHILD
));
1362 ch
->action
= actionNo
;
1363 strncpy(ch
->id
, id
, sizeof(utproto
.ut_id
) + 1); /* Hack for different libs. */
1364 strncpy(ch
->process
, process
, sizeof(ch
->process
) - 1);
1366 for(f
= 0; f
< (int)sizeof(rlevel
) - 1 && rlevel
[f
]; f
++) {
1367 ch
->rlevel
[f
] = rlevel
[f
];
1368 if (ch
->rlevel
[f
] == 's') ch
->rlevel
[f
] = 'S';
1370 strncpy(ch
->rlevel
, rlevel
, sizeof(ch
->rlevel
) - 1);
1372 strcpy(ch
->rlevel
, "0123456789");
1373 if (ISPOWER(ch
->action
))
1374 strcpy(ch
->rlevel
, "S0123456789");
1377 * We have the fake runlevel '#' for SYSINIT and
1378 * '*' for BOOT and BOOTWAIT.
1380 if (ch
->action
== SYSINIT
) strcpy(ch
->rlevel
, "#");
1381 if (ch
->action
== BOOT
|| ch
->action
== BOOTWAIT
)
1382 strcpy(ch
->rlevel
, "*");
1385 * Now add it to the linked list. Special for powerfail.
1387 if (ISPOWER(ch
->action
)) {
1390 * Disable by default
1392 ch
->flags
|= XECUTED
;
1395 * Tricky: insert at the front of the list..
1398 for(i
= newFamily
; i
; i
= i
->next
) {
1399 if (!ISPOWER(i
->action
)) break;
1403 * Now add after entry "old"
1408 if (i
== NULL
) head
= ch
;
1410 ch
->next
= newFamily
;
1412 if (ch
->next
== NULL
) head
= ch
;
1416 * Just add at end of the list
1418 if (ch
->action
== KBREQUEST
) ch
->flags
|= XECUTED
;
1428 * Walk through the old list comparing id fields
1430 for(old
= family
; old
; old
= old
->next
)
1431 if (strcmp(old
->id
, ch
->id
) == 0) {
1442 * Loop through the list of children, and see if they need to
1446 INITDBG(L_VB
, "Checking for children to kill");
1447 for(round
= 0; round
< 2; round
++) {
1449 for(ch
= family
; ch
; ch
= ch
->next
) {
1450 ch
->flags
&= ~KILLME
;
1453 * Is this line deleted?
1455 if (ch
->new == NULL
) ch
->flags
|= KILLME
;
1458 * If the entry has changed, kill it anyway. Note that
1459 * we do not check ch->process, only the "action" field.
1460 * This way, you can turn an entry "off" immediately, but
1461 * changes in the command line will only become effective
1462 * after the running version has exited.
1464 if (ch
->new && ch
->action
!= ch
->new->action
) ch
->flags
|= KILLME
;
1467 * Only BOOT processes may live in all levels
1469 if (ch
->action
!= BOOT
&&
1470 strchr(ch
->rlevel
, runlevel
) == NULL
) {
1472 * Ondemand procedures live always,
1473 * except in single user
1475 if (runlevel
== 'S' || !(ch
->flags
& DEMAND
))
1476 ch
->flags
|= KILLME
;
1480 * Now, if this process may live note so in the new list
1482 if ((ch
->flags
& KILLME
) == 0) {
1483 ch
->new->flags
= ch
->flags
;
1484 ch
->new->pid
= ch
->pid
;
1485 ch
->new->exstat
= ch
->exstat
;
1491 * Is this process still around?
1493 if ((ch
->flags
& RUNNING
) == 0) {
1494 ch
->flags
&= ~KILLME
;
1497 INITDBG(L_VB
, "Killing \"%s\"", ch
->process
);
1499 case 0: /* Send TERM signal */
1502 "Sending processes the TERM signal");
1503 kill(-(ch
->pid
), SIGTERM
);
1506 case 1: /* Send KILL signal and collect status */
1509 "Sending processes the KILL signal");
1510 kill(-(ch
->pid
), SIGKILL
);
1517 * See if we have to wait 5 seconds
1519 if (foundOne
&& round
== 0) {
1521 * Yup, but check every second if we still have children.
1523 for(f
= 0; f
< sltime
; f
++) {
1524 for(ch
= family
; ch
; ch
= ch
->next
) {
1525 if (!(ch
->flags
& KILLME
)) continue;
1526 if ((ch
->flags
& RUNNING
) && !(ch
->flags
& ZOMBIE
))
1531 * No running children, skip SIGKILL
1534 foundOne
= 0; /* Skip the sleep below. */
1543 * Now give all processes the chance to die and collect exit statuses.
1545 if (foundOne
) do_sleep(1);
1546 for(ch
= family
; ch
; ch
= ch
->next
)
1547 if (ch
->flags
& KILLME
) {
1548 if (!(ch
->flags
& ZOMBIE
))
1549 initlog(L_CO
, "Pid %d [id %s] seems to hang", ch
->pid
,
1552 INITDBG(L_VB
, "Updating utmp for pid %d [id %s]",
1554 ch
->flags
&= ~RUNNING
;
1555 if (ch
->process
[0] != '+')
1556 write_utmp_wtmp("", ch
->id
, ch
->pid
, DEAD_PROCESS
, NULL
);
1561 * Both rounds done; clean up the list.
1563 sigemptyset(&nmask
);
1564 sigaddset(&nmask
, SIGCHLD
);
1565 sigprocmask(SIG_BLOCK
, &nmask
, &omask
);
1566 for(ch
= family
; ch
; ch
= old
) {
1571 for(ch
= family
; ch
; ch
= ch
->next
) ch
->new = NULL
;
1573 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
1577 * Dispose of INITLVL file.
1579 if (lstat(INITLVL
, &st
) >= 0 && S_ISLNK(st
.st_mode
)) {
1581 * INITLVL is a symbolic link, so just truncate the file.
1583 close(open(INITLVL
, O_WRONLY
|O_TRUNC
));
1586 * Delete INITLVL file.
1593 * Dispose of INITLVL2 file.
1595 if (lstat(INITLVL2
, &st
) >= 0 && S_ISLNK(st
.st_mode
)) {
1597 * INITLVL2 is a symbolic link, so just truncate the file.
1599 close(open(INITLVL2
, O_WRONLY
|O_TRUNC
));
1602 * Delete INITLVL2 file.
1610 * Walk through the family list and start up children.
1611 * The entries that do not belong here at all are removed
1615 void start_if_needed(void)
1617 CHILD
*ch
; /* Pointer to child */
1618 int delete; /* Delete this entry from list? */
1620 INITDBG(L_VB
, "Checking for children to start");
1622 for(ch
= family
; ch
; ch
= ch
->next
) {
1625 if (ch
->rlevel
[0] == 'C') {
1626 INITDBG(L_VB
, "%s: flags %d", ch
->process
, ch
->flags
);
1630 /* Are we waiting for this process? Then quit here. */
1631 if (ch
->flags
& WAITING
) break;
1633 /* Already running? OK, don't touch it */
1634 if (ch
->flags
& RUNNING
) continue;
1636 /* See if we have to start it up */
1638 if (strchr(ch
->rlevel
, runlevel
) ||
1639 ((ch
->flags
& DEMAND
) && !strchr("#*Ss", runlevel
))) {
1645 /* FIXME: is this OK? */
1646 ch
->flags
&= ~(RUNNING
|WAITING
);
1647 if (!ISPOWER(ch
->action
) && ch
->action
!= KBREQUEST
)
1648 ch
->flags
&= ~XECUTED
;
1651 /* Do we have to wait for this process? */
1652 if (ch
->flags
& WAITING
) break;
1658 * Ask the user on the console for a runlevel
1661 int ask_runlevel(void)
1663 const char prompt
[] = "\nEnter runlevel: ";
1669 fd
= console_open(O_RDWR
|O_NOCTTY
);
1671 if (fd
< 0) return('S');
1673 while(!strchr("0123456789S", lvl
)) {
1674 write(fd
, prompt
, sizeof(prompt
) - 1);
1676 read(fd
, buf
, sizeof(buf
));
1677 if (buf
[0] != 0 && (buf
[1] == '\r' || buf
[1] == '\n'))
1679 if (islower(lvl
)) lvl
= toupper(lvl
);
1686 * Search the INITTAB file for the 'initdefault' field, with the default
1687 * runlevel. If this fails, ask the user to supply a runlevel.
1690 int get_init_default(void)
1697 * Look for initdefault.
1699 for(ch
= family
; ch
; ch
= ch
->next
)
1700 if (ch
->action
== INITDEFAULT
) {
1703 if (*p
> lvl
) lvl
= *p
;
1709 * See if level is valid
1712 if (islower(lvl
)) lvl
= toupper(lvl
);
1713 if (strchr("0123456789S", lvl
) == NULL
) {
1715 "Initdefault level '%c' is invalid", lvl
);
1720 * Ask for runlevel on console if needed.
1722 if (lvl
<= 0) lvl
= ask_runlevel();
1725 * Log the fact that we have a runlevel now.
1734 * Do actions for the new level. If we are compatible with
1735 * the "old" INITLVL and arg == 0, try to read the new
1736 * runlevel from that file first.
1739 int read_level(int arg
)
1741 CHILD
*ch
; /* Walk through list */
1742 unsigned char foo
= 'X'; /* Contents of INITLVL */
1757 if (stat(INITLVL
, &stt
) != 0 || stt
.st_size
!= 0L)
1758 fp
= fopen(INITLVL
, "r");
1761 (stat(INITLVL2
, &stt
) != 0 || stt
.st_size
!= 0L))
1762 fp
= fopen(INITLVL2
, "r");
1765 /* INITLVL file empty or not there - act as 'init q' */
1766 initlog(L_SY
, "Re-reading inittab");
1769 ok
= fscanf(fp
, "%c %d", &foo
, &st
);
1772 /* We go to the new runlevel passed as an argument. */
1776 if (ok
== 2) sltime
= st
;
1778 #endif /* INITLVL */
1780 if (islower(foo
)) foo
= toupper(foo
);
1781 if (ok
< 1 || ok
> 2 || strchr("QS0123456789ABCU", foo
) == NULL
) {
1782 initlog(L_VB
, "bad runlevel: %c", foo
);
1786 /* Log this action */
1789 initlog(L_VB
, "Going single user");
1792 initlog(L_SY
, "Re-reading inittab");
1798 "Activating demand-procedures for '%c'", foo
);
1801 initlog(L_SY
, "Trying to re-exec init");
1804 initlog(L_VB
, "Switching to runlevel: %c", foo
);
1808 #if defined(SIGINT_ONLYONCE) && (SIGINT_ONLYONCE == 1)
1809 /* Re-enable signal from keyboard */
1810 struct sigaction sa
;
1811 SETSIG(sa
, SIGINT
, signal_handler
, 0);
1816 /* Check if this is a runlevel a, b or c */
1817 if (strchr("ABC", foo
)) {
1818 if (runlevel
== 'S') return(runlevel
);
1820 /* Read inittab again first! */
1823 /* Mark those special tasks */
1824 for(ch
= family
; ch
; ch
= ch
->next
)
1825 if (strchr(ch
->rlevel
, foo
) != NULL
||
1826 strchr(ch
->rlevel
, tolower(foo
)) != NULL
) {
1827 ch
->flags
|= DEMAND
;
1828 ch
->flags
&= ~XECUTED
;
1830 "Marking (%s) as ondemand, flags %d",
1836 /* Store both the old and the new runlevel. */
1837 wrote_utmp_rlevel
= 0;
1838 wrote_wtmp_rlevel
= 0;
1839 write_utmp_wtmp("runlevel", "~~", foo
+ 256*runlevel
, RUN_LVL
, "~");
1841 prevlevel
= runlevel
;
1847 * This procedure is called after every signal (SIGHUP, SIGALRM..)
1849 * Only clear the 'failing' flag if the process is sleeping
1850 * longer than 5 minutes, or inittab was read again due
1851 * to user interaction.
1854 void fail_check(void)
1856 CHILD
*ch
; /* Pointer to child structure */
1857 time_t t
; /* System time */
1858 time_t next_alarm
= 0; /* When to set next alarm */
1862 for(ch
= family
; ch
; ch
= ch
->next
) {
1864 if (ch
->flags
& FAILING
) {
1865 /* Can we free this sucker? */
1866 if (ch
->tm
+ SLEEPTIME
< t
) {
1867 ch
->flags
&= ~FAILING
;
1871 /* No, we'll look again later */
1872 if (next_alarm
== 0 ||
1873 ch
->tm
+ SLEEPTIME
> next_alarm
)
1874 next_alarm
= ch
->tm
+ SLEEPTIME
;
1880 if (next_alarm
< 1) next_alarm
= 1;
1885 /* Set all 'Fail' timers to 0 */
1887 void fail_cancel(void)
1891 for(ch
= family
; ch
; ch
= ch
->next
) {
1894 ch
->flags
&= ~FAILING
;
1899 * Start up powerfail entries.
1902 void do_power_fail(int pwrstat
)
1907 * Tell powerwait & powerfail entries to start up
1909 for (ch
= family
; ch
; ch
= ch
->next
) {
1910 if (pwrstat
== 'O') {
1912 * The power is OK again.
1914 if (ch
->action
== POWEROKWAIT
)
1915 ch
->flags
&= ~XECUTED
;
1916 } else if (pwrstat
== 'L') {
1918 * Low battery, shut down now.
1920 if (ch
->action
== POWERFAILNOW
)
1921 ch
->flags
&= ~XECUTED
;
1924 * Power is failing, shutdown imminent
1926 if (ch
->action
== POWERFAIL
|| ch
->action
== POWERWAIT
)
1927 ch
->flags
&= ~XECUTED
;
1933 * Check for state-pipe presence
1936 int check_pipe(int fd
)
1944 t
.tv_sec
= t
.tv_usec
= 0;
1946 if (select(fd
+1, &s
, NULL
, NULL
, &t
) != 1)
1948 if (read(fd
, signature
, 8) != 8)
1950 return strncmp(Signature
, signature
, 8) == 0;
1954 * Make a state-pipe.
1957 int make_pipe(int fd
)
1964 fcntl(fds
[1], F_SETFD
, 1);
1965 fcntl(fd
, F_SETFD
, 0);
1966 write(fds
[1], Signature
, 8);
1972 * Attempt to re-exec.
1978 sigset_t mask
, oldset
;
1983 if (strchr("S0123456",runlevel
) == NULL
)
1987 * Reset the alarm, and block all signals.
1991 sigprocmask(SIG_BLOCK
, &mask
, &oldset
);
1994 * construct a pipe fd --> STATE_PIPE and write a signature
1996 fd
= make_pipe(STATE_PIPE
);
1999 * It's a backup day today, so I'm pissed off. Being a BOFH, however,
2000 * does have it's advantages...
2005 DELSET(got_signals
, SIGCHLD
);
2006 DELSET(got_signals
, SIGHUP
);
2007 DELSET(got_signals
, SIGUSR1
);
2010 * That should be cleaned.
2012 for(ch
= family
; ch
; ch
= ch
->next
)
2013 if (ch
->flags
& ZOMBIE
) {
2014 INITDBG(L_VB
, "Child died, PID= %d", ch
->pid
);
2015 ch
->flags
&= ~(RUNNING
|ZOMBIE
|WAITING
);
2016 if (ch
->process
[0] != '+')
2017 write_utmp_wtmp("", ch
->id
, ch
->pid
, DEAD_PROCESS
, NULL
);
2020 if ((pid
= fork()) == 0) {
2022 * Child sends state information to the parent.
2029 * The existing init process execs a new init binary.
2031 env
= init_buildenv(0);
2032 execle(myname
, myname
, "--init", NULL
, env
);
2035 * We shouldn't be here, something failed.
2036 * Bitch, close the state pipe, unblock signals and return.
2040 sigprocmask(SIG_SETMASK
, &oldset
, NULL
);
2042 initlog(L_CO
, "Attempt to re-exec failed");
2046 * Redo utmp/wtmp entries if required or requested
2047 * Check for written records and size of utmp
2050 void redo_utmp_wtmp(void)
2053 const int ret
= stat(UTMP_FILE
, &ustat
);
2055 if ((ret
< 0) || (ustat
.st_size
== 0))
2056 wrote_utmp_rlevel
= wrote_utmp_reboot
= 0;
2058 if ((wrote_wtmp_reboot
== 0) || (wrote_utmp_reboot
== 0))
2059 write_utmp_wtmp("reboot", "~~", 0, BOOT_TIME
, "~");
2061 if ((wrote_wtmp_rlevel
== 0) || (wrote_wtmp_rlevel
== 0))
2062 write_utmp_wtmp("runlevel", "~~", thislevel
+ 256 * prevlevel
, RUN_LVL
, "~");
2066 * We got a change runlevel request through the
2067 * init.fifo. Process it.
2070 void fifo_new_level(int level
)
2077 if (level
== runlevel
) return;
2080 /* Are we waiting for a child? */
2081 for(ch
= family
; ch
; ch
= ch
->next
)
2082 if (ch
->flags
& WAITING
) break;
2086 /* We need to go into a new runlevel */
2087 oldlevel
= runlevel
;
2088 runlevel
= read_level(level
);
2089 if (runlevel
== 'U') {
2090 runlevel
= oldlevel
;
2093 if (oldlevel
!= 'S' && runlevel
== 'S') console_stty();
2094 if (runlevel
== '6' || runlevel
== '0' ||
2095 runlevel
== '1') console_stty();
2096 if (runlevel
> '1' && runlevel
< '6') redo_utmp_wtmp();
2099 setproctitle("init [%c]", (int)runlevel
);
2106 * Set/unset environment variables. The variables are
2107 * encoded as KEY=VAL\0KEY=VAL\0\0. With "=VAL" it means
2108 * setenv, without it means unsetenv.
2111 void initcmd_setenv(char *data
, int size
)
2113 char *env
, *p
, *e
, *eq
;
2118 while (*data
&& data
< e
) {
2120 for (p
= data
; *p
&& p
< e
; p
++)
2121 if (*p
== '=') eq
= p
;
2126 sz
= eq
? (eq
- env
) : (p
- env
);
2128 /*initlog(L_SY, "init_setenv: %s, %s, %d", env, eq, sz);*/
2131 * We only allow INIT_* to be set.
2133 if (strncmp(env
, "INIT_", 5) != 0)
2136 /* Free existing vars. */
2137 for (i
= 0; i
< NR_EXTRA_ENV
; i
++) {
2138 if (extra_env
[i
] == NULL
) continue;
2139 if (!strncmp(extra_env
[i
], env
, sz
) &&
2140 extra_env
[i
][sz
] == '=') {
2142 extra_env
[i
] = NULL
;
2146 /* Set new vars if needed. */
2147 if (eq
== NULL
) continue;
2148 for (i
= 0; i
< NR_EXTRA_ENV
; i
++) {
2149 if (extra_env
[i
] == NULL
) {
2150 extra_env
[i
] = istrdup(env
);
2159 * Read from the init FIFO. Processes like telnetd and rlogind can
2160 * ask us to create login processes on their behalf.
2162 * FIXME: this needs to be finished. NOT that it is buggy, but we need
2163 * to add the telnetd/rlogind stuff so people can start using it.
2164 * Maybe move to using an AF_UNIX socket so we can use
2165 * the 2.2 kernel credential stuff to see who we're talking to.
2169 void check_init_fifo(void)
2171 struct init_request request
;
2173 struct stat st
, st2
;
2179 * First, try to create /dev/initctl if not present.
2181 if (stat(INIT_FIFO
, &st2
) < 0 && errno
== ENOENT
)
2182 (void)mkfifo(INIT_FIFO
, 0600);
2185 * If /dev/initctl is open, stat the file to see if it
2186 * is still the _same_ inode.
2189 fstat(pipe_fd
, &st
);
2190 if (stat(INIT_FIFO
, &st2
) < 0 ||
2191 st
.st_dev
!= st2
.st_dev
||
2192 st
.st_ino
!= st2
.st_ino
) {
2199 * Now finally try to open /dev/initctl
2202 if ((pipe_fd
= open(INIT_FIFO
, O_RDWR
|O_NONBLOCK
)) >= 0) {
2203 fstat(pipe_fd
, &st
);
2204 if (!S_ISFIFO(st
.st_mode
)) {
2205 initlog(L_VB
, "%s is not a fifo", INIT_FIFO
);
2212 * Don't use fd's 0, 1 or 2.
2214 (void) dup2(pipe_fd
, PIPE_FD
);
2219 * Return to caller - we'll be back later.
2224 /* Wait for data to appear, _if_ the pipe was opened. */
2225 if (pipe_fd
>= 0) while(!quit
) {
2227 /* Do select, return on EINTR. */
2229 FD_SET(pipe_fd
, &fds
);
2232 n
= select(pipe_fd
+ 1, &fds
, NULL
, NULL
, &tv
);
2234 if (n
== 0 || errno
== EINTR
) return;
2238 /* Read the data, return on EINTR. */
2239 n
= read(pipe_fd
, &request
, sizeof(request
));
2242 * End of file. This can't happen under Linux (because
2243 * the pipe is opened O_RDWR - see select() in the
2244 * kernel) but you never know...
2251 if (errno
== EINTR
) return;
2252 initlog(L_VB
, "error reading initrequest");
2257 * This is a convenient point to also try to
2258 * find the console device or check if it changed.
2265 if (request
.magic
!= INIT_MAGIC
|| n
!= sizeof(request
)) {
2266 initlog(L_VB
, "got bogus initrequest");
2269 switch(request
.cmd
) {
2270 case INIT_CMD_RUNLVL
:
2271 sltime
= request
.sleeptime
;
2272 fifo_new_level(request
.runlevel
);
2275 case INIT_CMD_POWERFAIL
:
2276 sltime
= request
.sleeptime
;
2280 case INIT_CMD_POWERFAILNOW
:
2281 sltime
= request
.sleeptime
;
2285 case INIT_CMD_POWEROK
:
2286 sltime
= request
.sleeptime
;
2290 case INIT_CMD_SETENV
:
2291 initcmd_setenv(request
.i
.data
, sizeof(request
.i
.data
));
2294 initlog(L_VB
, "got unimplemented initrequest.");
2300 * We come here if the pipe couldn't be opened.
2302 if (pipe_fd
< 0) pause();
2308 * This function is used in the transition
2309 * sysinit (-> single user) boot -> multi-user.
2312 void boot_transitions()
2315 static int newlevel
= 0;
2316 static int warn
= 1;
2320 /* Check if there is something to wait for! */
2321 for( ch
= family
; ch
; ch
= ch
->next
)
2322 if ((ch
->flags
& RUNNING
) && ch
->action
!= BOOT
) break;
2325 /* No processes left in this level, proceed to next level. */
2329 case '#': /* SYSINIT -> BOOT */
2330 INITDBG(L_VB
, "SYSINIT -> BOOT");
2332 /* Write a boot record. */
2333 wrote_utmp_reboot
= 0;
2334 wrote_wtmp_reboot
= 0;
2335 write_utmp_wtmp("reboot", "~~", 0, BOOT_TIME
, "~");
2337 /* Get our run level */
2338 newlevel
= dfl_level
? dfl_level
: get_init_default();
2339 if (newlevel
== 'S') {
2340 runlevel
= newlevel
;
2341 /* Not really 'S' but show anyway. */
2342 setproctitle("init [S]");
2346 case '*': /* BOOT -> NORMAL */
2347 INITDBG(L_VB
, "BOOT -> NORMAL");
2348 if (runlevel
!= newlevel
)
2349 loglevel
= newlevel
;
2350 runlevel
= newlevel
;
2354 case 'S': /* Ended SU mode */
2356 INITDBG(L_VB
, "END SU MODE");
2357 newlevel
= get_init_default();
2358 if (!did_boot
&& newlevel
!= 'S')
2361 if (runlevel
!= newlevel
)
2362 loglevel
= newlevel
;
2363 runlevel
= newlevel
;
2367 for(ch
= family
; ch
; ch
= ch
->next
)
2368 if (strcmp(ch
->rlevel
, "S") == 0)
2369 ch
->flags
&= ~(FAILING
|WAITING
|XECUTED
);
2374 "no more processes left in this runlevel");
2377 if (got_signals
== 0)
2382 initlog(L_VB
, "Entering runlevel: %c", runlevel
);
2383 wrote_utmp_rlevel
= 0;
2384 wrote_wtmp_rlevel
= 0;
2385 write_utmp_wtmp("runlevel", "~~", runlevel
+ 256 * oldlevel
, RUN_LVL
, "~");
2386 thislevel
= runlevel
;
2387 prevlevel
= oldlevel
;
2388 setproctitle("init [%c]", (int)runlevel
);
2394 * Init got hit by a signal. See which signal it is,
2395 * and act accordingly.
2398 void process_signals()
2406 if (ISMEMBER(got_signals
, SIGPWR
)) {
2407 INITDBG(L_VB
, "got SIGPWR");
2408 /* See _what_ kind of SIGPWR this is. */
2410 if ((fd
= open(PWRSTAT
, O_RDONLY
)) >= 0) {
2416 } else if ((fd
= open(PWRSTAT_OLD
, O_RDONLY
)) >= 0) {
2417 /* Path changed 2010-03-20. Look for the old path for a while. */
2418 initlog(L_VB
, "warning: found obsolete path %s, use %s instead",
2419 PWRSTAT_OLD
, PWRSTAT
);
2424 unlink(PWRSTAT_OLD
);
2426 do_power_fail(pwrstat
);
2427 DELSET(got_signals
, SIGPWR
);
2430 if (ISMEMBER(got_signals
, SIGINT
)) {
2431 #if defined(SIGINT_ONLYONCE) && (SIGINT_ONLYONCE == 1)
2432 /* Ignore any further signal from keyboard */
2433 struct sigaction sa
;
2434 SETSIG(sa
, SIGINT
, SIG_IGN
, SA_RESTART
);
2436 INITDBG(L_VB
, "got SIGINT");
2437 /* Tell ctrlaltdel entry to start up */
2438 for(ch
= family
; ch
; ch
= ch
->next
)
2439 if (ch
->action
== CTRLALTDEL
)
2440 ch
->flags
&= ~XECUTED
;
2441 DELSET(got_signals
, SIGINT
);
2444 if (ISMEMBER(got_signals
, SIGWINCH
)) {
2445 INITDBG(L_VB
, "got SIGWINCH");
2446 /* Tell kbrequest entry to start up */
2447 for(ch
= family
; ch
; ch
= ch
->next
)
2448 if (ch
->action
== KBREQUEST
)
2449 ch
->flags
&= ~XECUTED
;
2450 DELSET(got_signals
, SIGWINCH
);
2453 if (ISMEMBER(got_signals
, SIGALRM
)) {
2454 INITDBG(L_VB
, "got SIGALRM");
2455 /* The timer went off: check it out */
2456 DELSET(got_signals
, SIGALRM
);
2459 if (ISMEMBER(got_signals
, SIGCHLD
)) {
2460 INITDBG(L_VB
, "got SIGCHLD");
2461 /* First set flag to 0 */
2462 DELSET(got_signals
, SIGCHLD
);
2464 /* See which child this was */
2465 for(ch
= family
; ch
; ch
= ch
->next
)
2466 if (ch
->flags
& ZOMBIE
) {
2467 INITDBG(L_VB
, "Child died, PID= %d", ch
->pid
);
2468 ch
->flags
&= ~(RUNNING
|ZOMBIE
|WAITING
);
2469 if (ch
->process
[0] != '+')
2470 write_utmp_wtmp("", ch
->id
, ch
->pid
, DEAD_PROCESS
, NULL
);
2475 if (ISMEMBER(got_signals
, SIGHUP
)) {
2476 INITDBG(L_VB
, "got SIGHUP");
2478 /* Are we waiting for a child? */
2479 for(ch
= family
; ch
; ch
= ch
->next
)
2480 if (ch
->flags
& WAITING
) break;
2484 /* We need to go into a new runlevel */
2485 oldlevel
= runlevel
;
2487 runlevel
= read_level(0);
2489 if (runlevel
== 'U') {
2490 runlevel
= oldlevel
;
2493 if (oldlevel
!= 'S' && runlevel
== 'S') console_stty();
2494 if (runlevel
== '6' || runlevel
== '0' ||
2495 runlevel
== '1') console_stty();
2498 setproctitle("init [%c]", (int)runlevel
);
2499 DELSET(got_signals
, SIGHUP
);
2503 if (ISMEMBER(got_signals
, SIGUSR1
)) {
2505 * SIGUSR1 means close and reopen /dev/initctl
2507 INITDBG(L_VB
, "got SIGUSR1");
2510 DELSET(got_signals
, SIGUSR1
);
2518 void init_main(void)
2521 struct sigaction sa
;
2529 * Fork so we can debug the init process.
2531 if ((f
= fork()) > 0) {
2532 static const char killmsg
[] = "PRNT: init killed.\r\n";
2535 while((rc
= wait(&st
)) != f
)
2536 if (rc
< 0 && errno
== ECHILD
)
2538 write(1, killmsg
, sizeof(killmsg
) - 1);
2545 * Tell the kernel to send us SIGINT when CTRL-ALT-DEL
2546 * is pressed, and that we want to handle keyboard signals.
2548 init_reboot(BMAGIC_SOFT
);
2549 if ((f
= open(VT_MASTER
, O_RDWR
| O_NOCTTY
)) >= 0) {
2550 (void) ioctl(f
, KDSIGACCEPT
, SIGWINCH
);
2553 (void) ioctl(0, KDSIGACCEPT
, SIGWINCH
);
2557 * Ignore all signals.
2559 for(f
= 1; f
<= NSIG
; f
++)
2560 SETSIG(sa
, f
, SIG_IGN
, SA_RESTART
);
2563 SETSIG(sa
, SIGALRM
, signal_handler
, 0);
2564 SETSIG(sa
, SIGHUP
, signal_handler
, 0);
2565 SETSIG(sa
, SIGINT
, signal_handler
, 0);
2566 SETSIG(sa
, SIGCHLD
, chld_handler
, SA_RESTART
);
2567 SETSIG(sa
, SIGPWR
, signal_handler
, 0);
2568 SETSIG(sa
, SIGWINCH
, signal_handler
, 0);
2569 SETSIG(sa
, SIGUSR1
, signal_handler
, 0);
2570 SETSIG(sa
, SIGSTOP
, stop_handler
, SA_RESTART
);
2571 SETSIG(sa
, SIGTSTP
, stop_handler
, SA_RESTART
);
2572 SETSIG(sa
, SIGCONT
, cont_handler
, SA_RESTART
);
2573 SETSIG(sa
, SIGSEGV
, (void (*)(int))segv_handler
, SA_RESTART
);
2580 /* Close whatever files are open, and reset the console. */
2588 * Set default PATH variable.
2590 setenv("PATH", PATH_DEFAULT
, 1 /* Overwrite */);
2593 * Initialize /var/run/utmp (only works if /var is on
2594 * root and mounted rw)
2596 if ((fd
= open(UTMP_FILE
, O_WRONLY
|O_CREAT
|O_TRUNC
, 0644)) >= 0)
2600 * Say hello to the world
2602 initlog(L_CO
, bootmsg
, "booting");
2605 * See if we have to start an emergency shell.
2609 SETSIG(sa
, SIGCHLD
, SIG_DFL
, SA_RESTART
);
2610 if (spawn(&ch_emerg
, &f
) > 0) {
2611 while((rc
= wait(&st
)) != f
)
2612 if (rc
< 0 && errno
== ECHILD
)
2615 SETSIG(sa
, SIGCHLD
, chld_handler
, SA_RESTART
);
2619 * Start normal boot procedure.
2626 * Restart: unblock signals and let the show go on
2628 initlog(L_CO
, bootmsg
, "reloading");
2630 sigprocmask(SIG_UNBLOCK
, &sgt
, NULL
);
2633 * Set default PATH variable.
2635 setenv("PATH", PATH_DEFAULT
, 0 /* Don't overwrite */);
2641 /* See if we need to make the boot transitions. */
2643 INITDBG(L_VB
, "init_main: waiting..");
2645 /* Check if there are processes to be waited on. */
2646 for(ch
= family
; ch
; ch
= ch
->next
)
2647 if ((ch
->flags
& RUNNING
) && ch
->action
!= BOOT
) break;
2650 /* Wait until we get hit by some signal. */
2651 while (ch
!= NULL
&& got_signals
== 0) {
2652 if (ISMEMBER(got_signals
, SIGHUP
)) {
2653 /* See if there are processes to be waited on. */
2654 for(ch
= family
; ch
; ch
= ch
->next
)
2655 if (ch
->flags
& WAITING
) break;
2657 if (ch
!= NULL
) check_init_fifo();
2659 #else /* CHANGE_WAIT */
2660 if (ch
!= NULL
&& got_signals
== 0) check_init_fifo();
2661 #endif /* CHANGE_WAIT */
2663 /* Check the 'failing' flags */
2666 /* Process any signals. */
2669 /* See what we need to start up (again) */
2676 * Tell the user about the syntax we expect.
2681 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
);
2686 int telinit(char *progname
, int argc
, char **argv
)
2688 #ifdef TELINIT_USES_INITLVL
2691 struct init_request request
;
2692 struct sigaction sa
;
2696 memset(&request
, 0, sizeof(request
));
2697 request
.magic
= INIT_MAGIC
;
2699 while ((f
= getopt(argc
, argv
, "t:e:")) != EOF
) switch(f
) {
2701 sltime
= atoi(optarg
);
2705 env
= request
.i
.data
;
2707 if (env
+ l
+ 2 > request
.i
.data
+ sizeof(request
.i
.data
)) {
2708 fprintf(stderr
, "%s: -e option data "
2709 "too large\n", progname
);
2712 memcpy(env
, optarg
, l
);
2721 if (env
) *env
++ = 0;
2726 request
.cmd
= INIT_CMD_SETENV
;
2728 if (argc
- optind
!= 1 || strlen(argv
[optind
]) != 1)
2730 if (!strchr("0123456789SsQqAaBbCcUu", argv
[optind
][0]))
2732 request
.cmd
= INIT_CMD_RUNLVL
;
2733 request
.runlevel
= env
? 0 : argv
[optind
][0];
2734 request
.sleeptime
= sltime
;
2737 /* Change to the root directory. */
2740 /* Open the fifo and write a command. */
2741 /* Make sure we don't hang on opening /dev/initctl */
2742 SETSIG(sa
, SIGALRM
, signal_handler
, 0);
2744 if ((fd
= open(INIT_FIFO
, O_WRONLY
)) >= 0) {
2746 size_t s
= sizeof(request
);
2747 void *ptr
= &request
;
2750 p
= write(fd
, ptr
, s
);
2752 if (errno
== EINTR
|| errno
== EAGAIN
)
2764 #ifdef TELINIT_USES_INITLVL
2765 if (request
.cmd
== INIT_CMD_RUNLVL
) {
2766 /* Fallthrough to the old method. */
2768 /* Now write the new runlevel. */
2769 if ((fp
= fopen(INITLVL
, "w")) == NULL
) {
2770 fprintf(stderr
, "%s: cannot create %s\n",
2774 fprintf(fp
, "%s %d", argv
[optind
], sltime
);
2777 /* And tell init about the pending runlevel change. */
2778 if (kill(INITPID
, SIGHUP
) < 0) perror(progname
);
2784 fprintf(stderr
, "%s: ", progname
);
2785 if (ISMEMBER(got_signals
, SIGALRM
)) {
2786 fprintf(stderr
, "timeout opening/writing control channel %s\n",
2795 * Main entry for init and telinit.
2797 int main(int argc
, char **argv
)
2806 /* Get my own name */
2807 if ((p
= strrchr(argv
[0], '/')) != NULL
)
2816 if (geteuid() != 0) {
2817 fprintf(stderr
, "%s: must be superuser.\n", p
);
2822 * Is this telinit or init ?
2824 isinit
= (getpid() == 1);
2825 for (f
= 1; f
< argc
; f
++) {
2826 if (!strcmp(argv
[f
], "-i") || !strcmp(argv
[f
], "--init")) {
2831 if (!isinit
) exit(telinit(p
, argc
, argv
));
2836 if (check_pipe(STATE_PIPE
)) {
2838 receive_state(STATE_PIPE
);
2840 myname
= istrdup(argv
[0]);
2843 for (f
= 0; f
< argc
; f
++)
2844 maxproclen
+= strlen(argv
[f
]) + 1;
2846 setproctitle("init [%c]", (int)runlevel
);
2851 /* Check command line arguments */
2852 maxproclen
= strlen(argv
[0]) + 1;
2853 for(f
= 1; f
< argc
; f
++) {
2854 if (!strcmp(argv
[f
], "single") || !strcmp(argv
[f
], "-s"))
2856 else if (!strcmp(argv
[f
], "-a") || !strcmp(argv
[f
], "auto"))
2857 putenv("AUTOBOOT=YES");
2858 else if (!strcmp(argv
[f
], "-b") || !strcmp(argv
[f
],"emergency"))
2860 else if (!strcmp(argv
[f
], "-z")) {
2862 if (argv
[f
+ 1]) f
++;
2863 } else if (strchr("0123456789sS", argv
[f
][0])
2864 && strlen(argv
[f
]) == 1)
2865 dfl_level
= argv
[f
][0];
2866 /* "init u" in the very beginning makes no sense */
2867 if (dfl_level
== 's') dfl_level
= 'S';
2868 maxproclen
+= strlen(argv
[f
]) + 1;
2872 if (getenv("SELINUX_INIT") == NULL
) {
2873 const int rc
= mount("proc", "/proc", "proc", 0, 0);
2874 if (is_selinux_enabled() > 0) {
2875 putenv("SELINUX_INIT=YES");
2876 if (rc
== 0) umount2("/proc", MNT_DETACH
);
2877 if (selinux_init_load_policy(&enforce
) == 0) {
2878 execv(myname
, argv
);
2881 /* SELinux in enforcing mode but load_policy failed */
2882 /* At this point, we probably can't open /dev/console, so log() won't work */
2883 fprintf(stderr
,"Unable to load SELinux Policy. Machine is in enforcing mode. Halting now.\n");
2888 if (rc
== 0) umount2("/proc", MNT_DETACH
);
2891 /* Start booting. */
2894 setproctitle("init boot");