]>
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.88"
11 #define DATE "31-Jul-2004"
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>
63 # define STACK_DEBUG 1
64 # if (__GLIBC__ == 2 && __GLIBC_MINOR__ == 0)
65 /* Only glibc 2.0 needs this */
66 # include <sigcontext.h>
78 # define SIGPWR SIGUSR2
88 /* Set a signal handler. */
89 #define SETSIG(sa, sig, fun, flags) \
91 sa.sa_handler = fun; \
92 sa.sa_flags = flags; \
93 sigemptyset(&sa.sa_mask); \
94 sigaction(sig, &sa, NULL); \
97 /* Version information */
98 char *Version
= "@(#) init " VERSION
" " DATE
" miquels@cistron.nl";
99 char *bootmsg
= "version " VERSION
" %s";
100 #define E_VERSION "INIT_VERSION=sysvinit-" VERSION
102 CHILD
*family
= NULL
; /* The linked list of all entries */
103 CHILD
*newFamily
= NULL
; /* The list after inittab re-read */
105 CHILD ch_emerg
= { /* Emergency shell */
115 char runlevel
= 'S'; /* The current run level */
116 char thislevel
= 'S'; /* The current runlevel */
117 char prevlevel
= 'N'; /* Previous runlevel */
118 int dfl_level
= 0; /* Default runlevel */
119 sig_atomic_t got_cont
= 0; /* Set if we received the SIGCONT signal */
120 sig_atomic_t got_signals
; /* Set if we received a signal. */
121 int emerg_shell
= 0; /* Start emergency shell? */
122 int wrote_wtmp_reboot
= 1; /* Set when we wrote the reboot record */
123 int wrote_utmp_reboot
= 1; /* Set when we wrote the reboot record */
124 int sltime
= 5; /* Sleep time between TERM and KILL */
125 char *argv0
; /* First arguments; show up in ps listing */
126 int maxproclen
; /* Maximal length of argv[0] with \0 */
127 struct utmp utproto
; /* Only used for sizeof(utproto.ut_id) */
128 char *console_dev
; /* Console device. */
129 int pipe_fd
= -1; /* /dev/initctl */
130 int did_boot
= 0; /* Did we already do BOOT* stuff? */
131 int main(int, char **);
133 /* Used by re-exec part */
134 int reload
= 0; /* Should we do initialization stuff? */
135 char *myname
="/sbin/init"; /* What should we exec */
136 int oops_error
; /* Used by some of the re-exec code. */
137 const char *Signature
= "12567362"; /* Signature for re-exec fd */
139 /* Macro to see if this is a special action */
140 #define ISPOWER(i) ((i) == POWERWAIT || (i) == POWERFAIL || \
141 (i) == POWEROKWAIT || (i) == POWERFAILNOW || \
144 /* ascii values for the `action' field. */
149 { "respawn", RESPAWN
},
153 { "bootwait", BOOTWAIT
},
154 { "powerfail", POWERFAIL
},
155 { "powerfailnow",POWERFAILNOW
},
156 { "powerwait", POWERWAIT
},
157 { "powerokwait", POWEROKWAIT
},
158 { "ctrlaltdel", CTRLALTDEL
},
160 { "ondemand", ONDEMAND
},
161 { "initdefault", INITDEFAULT
},
162 { "sysinit", SYSINIT
},
163 { "kbrequest", KBREQUEST
},
168 * State parser token table (see receive_state)
181 { "CMD", C_PROCESS
},
184 { "-RL", D_RUNLEVEL
},
185 { "-TL", D_THISLEVEL
},
186 { "-PL", D_PREVLEVEL
},
187 { "-SI", D_GOTSIGN
},
188 { "-WR", D_WROTE_WTMP_REBOOT
},
189 { "-WU", D_WROTE_UTMP_REBOOT
},
191 { "-DB", D_DIDBOOT
},
205 #define NR_EXTRA_ENV 16
206 char *extra_env
[NR_EXTRA_ENV
];
210 * Sleep a number of seconds.
212 * This only works correctly because the linux select updates
213 * the elapsed time in the struct timeval passed to select!
215 void do_sleep(int sec
)
222 while(select(0, NULL
, NULL
, NULL
, &tv
) < 0 && errno
== EINTR
)
228 * Non-failing allocation routines (init cannot fail).
230 void *imalloc(size_t size
)
234 while ((m
= malloc(size
)) == NULL
) {
235 initlog(L_VB
, "out of memory");
243 char *istrdup(char *s
)
256 * Send the state info of the previous running init to
257 * the new one, in a version-independant way.
259 void send_state(int fd
)
267 fprintf(fp
, "VER%s\n", Version
);
268 fprintf(fp
, "-RL%c\n", runlevel
);
269 fprintf(fp
, "-TL%c\n", thislevel
);
270 fprintf(fp
, "-PL%c\n", prevlevel
);
271 fprintf(fp
, "-SI%u\n", got_signals
);
272 fprintf(fp
, "-WR%d\n", wrote_wtmp_reboot
);
273 fprintf(fp
, "-WU%d\n", wrote_utmp_reboot
);
274 fprintf(fp
, "-ST%d\n", sltime
);
275 fprintf(fp
, "-DB%d\n", did_boot
);
277 for (p
= family
; p
; p
= p
->next
) {
278 fprintf(fp
, "REC%s\n", p
->id
);
279 fprintf(fp
, "LEV%s\n", p
->rlevel
);
280 for (i
= 0, val
= p
->flags
; flags
[i
].mask
; i
++)
281 if (val
& flags
[i
].mask
) {
282 val
&= ~flags
[i
].mask
;
283 fprintf(fp
, "FL %s\n",flags
[i
].name
);
285 fprintf(fp
, "PID%d\n",p
->pid
);
286 fprintf(fp
, "EXS%u\n",p
->exstat
);
287 for(i
= 0; actions
[i
].act
; i
++)
288 if (actions
[i
].act
== p
->action
) {
289 fprintf(fp
, "AC %s\n", actions
[i
].name
);
292 fprintf(fp
, "CMD%s\n", p
->process
);
293 fprintf(fp
, "EOR\n");
295 fprintf(fp
, "END\n");
300 * Read a string from a file descriptor.
301 * FIXME: why not use fgets() ?
303 static int get_string(char *p
, int size
, FILE *f
)
307 while ((c
= getc(f
)) != EOF
&& c
!= '\n') {
312 return (c
!= EOF
) && (size
> 0);
316 * Read trailing data from the state pipe until we see a newline.
318 static int get_void(FILE *f
)
322 while ((c
= getc(f
)) != EOF
&& c
!= '\n')
329 * Read the next "command" from the state pipe.
331 static int get_cmd(FILE *f
)
336 if (fread(cmd
, 1, sizeof(cmd
) - 1, f
) != sizeof(cmd
) - 1)
339 for(i
= 0; cmds
[i
].cmd
&& strcmp(cmds
[i
].name
, cmd
) != 0; i
++)
345 * Read a CHILD * from the state pipe.
347 static CHILD
*get_record(FILE *f
)
355 switch (cmd
= get_cmd(f
)) {
365 fscanf(f
, "%c\n", &runlevel
);
368 fscanf(f
, "%c\n", &thislevel
);
371 fscanf(f
, "%c\n", &prevlevel
);
374 fscanf(f
, "%u\n", &got_signals
);
376 case D_WROTE_WTMP_REBOOT
:
377 fscanf(f
, "%d\n", &wrote_wtmp_reboot
);
379 case D_WROTE_UTMP_REBOOT
:
380 fscanf(f
, "%d\n", &wrote_utmp_reboot
);
383 fscanf(f
, "%d\n", &sltime
);
386 fscanf(f
, "%d\n", &did_boot
);
389 if (cmd
> 0 || cmd
== C_EOF
) {
394 } while (cmd
!= C_REC
);
396 p
= imalloc(sizeof(CHILD
));
397 get_string(p
->id
, sizeof(p
->id
), f
);
399 do switch(cmd
= get_cmd(f
)) {
405 fscanf(f
, "%d\n", &(p
->pid
));
408 fscanf(f
, "%u\n", &(p
->exstat
));
411 get_string(p
->rlevel
, sizeof(p
->rlevel
), f
);
414 get_string(p
->process
, sizeof(p
->process
), f
);
417 get_string(s
, sizeof(s
), f
);
418 for(i
= 0; flags
[i
].name
; i
++) {
419 if (strcmp(flags
[i
].name
,s
) == 0)
422 p
->flags
|= flags
[i
].mask
;
425 get_string(s
, sizeof(s
), f
);
426 for(i
= 0; actions
[i
].name
; i
++) {
427 if (strcmp(actions
[i
].name
, s
) == 0)
430 p
->action
= actions
[i
].act
? actions
[i
].act
: OFF
;
436 } while( cmd
!= C_EOR
);
442 * Read the complete state info from the state pipe.
443 * Returns 0 on success
445 int receive_state(int fd
)
448 char old_version
[256];
453 if (get_cmd(f
) != C_VER
)
455 get_string(old_version
, sizeof(old_version
), f
);
457 for (pp
= &family
; (*pp
= get_record(f
)) != NULL
; pp
= &((*pp
)->next
))
464 * Set the process title.
467 __attribute__ ((format (printf
, 1, 2)))
469 static int setproctitle(char *fmt
, ...)
478 len
= vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
481 if (maxproclen
> 1) {
482 memset(argv0
, 0, maxproclen
);
483 strncpy(argv0
, buf
, maxproclen
- 1);
490 * Set console_dev to a working console.
492 void console_init(void)
495 int tried_devcons
= 0;
496 int tried_vtmaster
= 0;
499 if ((s
= getenv("CONSOLE")) != NULL
)
502 console_dev
= CONSOLE
;
506 while ((fd
= open(console_dev
, O_RDONLY
|O_NONBLOCK
)) < 0) {
507 if (!tried_devcons
) {
509 console_dev
= CONSOLE
;
512 if (!tried_vtmaster
) {
514 console_dev
= VT_MASTER
;
520 console_dev
= "/dev/null";
527 * Open the console with retries.
529 int console_open(int mode
)
535 * Open device in nonblocking mode.
537 m
= mode
| O_NONBLOCK
;
540 * Retry the open five times.
542 for(f
= 0; f
< 5; f
++) {
543 if ((fd
= open(console_dev
, m
)) >= 0) break;
547 if (fd
< 0) return fd
;
550 * Set original flags.
553 fcntl(fd
, F_SETFL
, mode
);
558 * We got a signal (HUP PWR WINCH ALRM INT)
560 void signal_handler(int sig
)
562 ADDSET(got_signals
, sig
);
566 * SIGCHLD: one of our children has died.
572 int saved_errno
= errno
;
575 * Find out which process(es) this was (were)
577 while((pid
= waitpid(-1, &st
, WNOHANG
)) != 0) {
578 if (errno
== ECHILD
) break;
579 for( ch
= family
; ch
; ch
= ch
->next
)
580 if ( ch
->pid
== pid
&& (ch
->flags
& RUNNING
) ) {
582 "chld_handler: marked %d as zombie",
584 ADDSET(got_signals
, SIGCHLD
);
588 ch
->new->exstat
= st
;
589 ch
->new->flags
|= ZOMBIE
;
594 INITDBG(L_VB
, "chld_handler: unknown child %d exited.",
602 * Linux ignores all signals sent to init when the
603 * SIG_DFL handler is installed. Therefore we must catch SIGTSTP
604 * and SIGCONT, or else they won't work....
606 * The SIGCONT handler
614 * Fork and dump core in /.
618 static int dumped
= 0;
625 if (fork() != 0) return;
628 sigprocmask(SIG_SETMASK
, &mask
, NULL
);
630 rlim
.rlim_cur
= RLIM_INFINITY
;
631 rlim
.rlim_max
= RLIM_INFINITY
;
632 setrlimit(RLIMIT_CORE
, &rlim
);
635 signal(SIGSEGV
, SIG_DFL
);
637 sigdelset(&mask
, SIGSEGV
);
638 sigprocmask(SIG_SETMASK
, &mask
, NULL
);
645 * OOPS: segmentation violation!
646 * If we have the info, print where it occured.
647 * Then sleep 30 seconds and try to continue.
649 #if defined(STACK_DEBUG) && defined(__linux__)
650 void segv_handler(int sig
, struct sigcontext ctx
)
653 int saved_errno
= errno
;
655 if ((void *)ctx
.eip
>= (void *)do_sleep
&&
656 (void *)ctx
.eip
< (void *)main
)
658 initlog(L_VB
, "PANIC: segmentation violation at %p%s! "
659 "sleeping for 30 seconds.", (void *)ctx
.eip
, p
);
667 int saved_errno
= errno
;
670 "PANIC: segmentation violation! sleeping for 30 seconds.");
678 * The SIGSTOP & SIGTSTP handler
682 int saved_errno
= errno
;
685 while(!got_cont
) pause();
691 * Set terminal settings to reasonable defaults
693 void console_stty(void)
698 if ((fd
= console_open(O_RDWR
|O_NOCTTY
)) < 0) {
699 initlog(L_VB
, "can't open %s", console_dev
);
703 (void) tcgetattr(fd
, &tty
);
705 tty
.c_cflag
&= CBAUD
|CBAUDEX
|CSIZE
|CSTOPB
|PARENB
|PARODD
;
706 tty
.c_cflag
|= HUPCL
|CLOCAL
|CREAD
;
708 tty
.c_cc
[VINTR
] = 3; /* ctrl('c') */
709 tty
.c_cc
[VQUIT
] = 28; /* ctrl('\\') */
710 tty
.c_cc
[VERASE
] = 127;
711 tty
.c_cc
[VKILL
] = 24; /* ctrl('x') */
712 tty
.c_cc
[VEOF
] = 4; /* ctrl('d') */
715 tty
.c_cc
[VSTART
] = 17; /* ctrl('q') */
716 tty
.c_cc
[VSTOP
] = 19; /* ctrl('s') */
717 tty
.c_cc
[VSUSP
] = 26; /* ctrl('z') */
720 * Set pre and post processing
722 tty
.c_iflag
= IGNPAR
|ICRNL
|IXON
|IXANY
723 #ifdef IUTF8 /* Not defined on FreeBSD */
724 | (tty
.c_iflag
& IUTF8
)
727 tty
.c_oflag
= OPOST
|ONLCR
;
728 tty
.c_lflag
= ISIG
|ICANON
|ECHO
|ECHOCTL
|ECHOPRT
|ECHOKE
;
731 * Now set the terminal line.
732 * We don't care about non-transmitted output data
733 * and non-read input data.
735 (void) tcsetattr(fd
, TCSANOW
, &tty
);
736 (void) tcflush(fd
, TCIOFLUSH
);
741 * Print to the system console
747 if ((fd
= console_open(O_WRONLY
|O_NOCTTY
|O_NDELAY
)) >= 0) {
748 write(fd
, s
, strlen(s
));
754 * Log something to a logfile and the console.
757 __attribute__ ((format (printf
, 2, 3)))
759 void initlog(int loglevel
, char *s
, ...)
763 sigset_t nmask
, omask
;
765 va_start(va_alist
, s
);
766 vsnprintf(buf
, sizeof(buf
), s
, va_alist
);
769 if (loglevel
& L_SY
) {
771 * Re-establish connection with syslogd every time.
772 * Block signals while talking to syslog.
775 sigprocmask(SIG_BLOCK
, &nmask
, &omask
);
776 openlog("init", 0, LOG_DAEMON
);
777 syslog(LOG_INFO
, "%s", buf
);
779 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
783 * And log to the console.
785 if (loglevel
& L_CO
) {
794 * Build a new environment for execve().
796 char **init_buildenv(int child
)
798 char i_lvl
[] = "RUNLEVEL=x";
799 char i_prev
[] = "PREVLEVEL=x";
804 for (n
= 0; environ
[n
]; n
++)
806 n
+= NR_EXTRA_ENV
+ 8;
807 e
= calloc(n
, sizeof(char *));
809 for (n
= 0; environ
[n
]; n
++)
810 e
[n
] = istrdup(environ
[n
]);
812 for (i
= 0; i
< NR_EXTRA_ENV
; i
++)
814 e
[n
++] = istrdup(extra_env
[i
]);
817 snprintf(i_cons
, sizeof(i_cons
), "CONSOLE=%s", console_dev
);
818 i_lvl
[9] = thislevel
;
819 i_prev
[10] = prevlevel
;
820 e
[n
++] = istrdup(i_lvl
);
821 e
[n
++] = istrdup(i_prev
);
822 e
[n
++] = istrdup(i_cons
);
823 e
[n
++] = istrdup(E_VERSION
);
832 void init_freeenv(char **e
)
836 for (n
= 0; e
[n
]; n
++)
845 * This function is too long and indents too deep.
848 int spawn(CHILD
*ch
, int *res
)
850 char *args
[16]; /* Argv array */
851 char buf
[136]; /* Line buffer */
852 int f
, st
, rc
; /* Scratch variables */
853 char *ptr
; /* Ditto */
854 time_t t
; /* System time */
855 int oldAlarm
; /* Previous alarm value */
856 char *proc
= ch
->process
; /* Command line */
857 pid_t pid
, pgrp
; /* child, console process group. */
858 sigset_t nmask
, omask
; /* For blocking SIGCHLD */
862 buf
[sizeof(buf
) - 1] = 0;
864 /* Skip '+' if it's there */
865 if (proc
[0] == '+') proc
++;
867 ch
->flags
|= XECUTED
;
869 if (ch
->action
== RESPAWN
|| ch
->action
== ONDEMAND
) {
870 /* Is the date stamp from less than 2 minutes ago? */
872 if (ch
->tm
+ TESTTIME
> t
) {
879 /* Do we try to respawn too fast? */
880 if (ch
->count
>= MAXSPAWN
) {
883 "Id \"%s\" respawning too fast: disabled for %d minutes",
884 ch
->id
, SLEEPTIME
/ 60);
885 ch
->flags
&= ~RUNNING
;
886 ch
->flags
|= FAILING
;
888 /* Remember the time we stopped */
891 /* Try again in 5 minutes */
893 if (oldAlarm
> SLEEPTIME
|| oldAlarm
<= 0) oldAlarm
= SLEEPTIME
;
899 /* See if there is an "initscript" (except in single user mode). */
900 if (access(INITSCRIPT
, R_OK
) == 0 && runlevel
!= 'S') {
901 /* Build command line using "initscript" */
903 args
[2] = INITSCRIPT
;
905 args
[4] = ch
->rlevel
;
907 for(f
= 0; actions
[f
].name
; f
++) {
908 if (ch
->action
== actions
[f
].act
) {
909 args
[5] = actions
[f
].name
;
915 } else if (strpbrk(proc
, "~`!$^&*()=|\\{}[];\"'<>?")) {
916 /* See if we need to fire off a shell for this command */
917 /* Give command line to shell */
920 strcpy(buf
, "exec ");
921 strncat(buf
, proc
, sizeof(buf
) - strlen(buf
) - 1);
925 /* Split up command line arguments */
927 strncat(buf
, proc
, sizeof(buf
) - 1);
929 for(f
= 1; f
< 15; f
++) {
930 /* Skip white space */
931 while(*ptr
== ' ' || *ptr
== '\t') ptr
++;
934 /* May be trailing space.. */
935 if (*ptr
== 0) break;
937 /* Skip this `word' */
938 while(*ptr
&& *ptr
!= ' ' && *ptr
!= '\t' && *ptr
!= '#')
941 /* If end-of-line, break */
942 if (*ptr
== '#' || *ptr
== 0) {
947 /* End word with \0 and continue */
955 * Block sigchild while forking.
958 sigaddset(&nmask
, SIGCHLD
);
959 sigprocmask(SIG_BLOCK
, &nmask
, &omask
);
961 if ((pid
= fork()) == 0) {
966 if (pipe_fd
>= 0) close(pipe_fd
);
968 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
971 * In sysinit, boot, bootwait or single user mode:
972 * for any wait-type subprocess we _force_ the console
973 * to be its controlling tty.
975 if (strchr("*#sS", runlevel
) && ch
->flags
& WAITING
) {
977 * We fork once extra. This is so that we can
978 * wait and change the process group and session
979 * of the console after exit of the leader.
982 if ((f
= console_open(O_RDWR
|O_NOCTTY
)) >= 0) {
983 /* Take over controlling tty by force */
984 (void)ioctl(f
, TIOCSCTTY
, 1);
988 SETSIG(sa
, SIGCHLD
, SIG_DFL
, SA_RESTART
);
989 if ((pid
= fork()) < 0) {
990 initlog(L_VB
, "cannot fork: %s",
996 * Ignore keyboard signals etc.
997 * Then wait for child to exit.
999 SETSIG(sa
, SIGINT
, SIG_IGN
, SA_RESTART
);
1000 SETSIG(sa
, SIGTSTP
, SIG_IGN
, SA_RESTART
);
1001 SETSIG(sa
, SIGQUIT
, SIG_IGN
, SA_RESTART
);
1003 while ((rc
= waitpid(pid
, &st
, 0)) != pid
)
1004 if (rc
< 0 && errno
== ECHILD
)
1008 * Small optimization. See if stealing
1009 * controlling tty back is needed.
1011 pgrp
= tcgetpgrp(f
);
1012 if (pgrp
!= getpid())
1016 * Steal controlling tty away. We do
1017 * this with a temporary process.
1019 if ((pid
= fork()) < 0) {
1020 initlog(L_VB
, "cannot fork: %s",
1026 (void)ioctl(f
, TIOCSCTTY
, 1);
1029 while((rc
= waitpid(pid
, &st
, 0)) != pid
)
1030 if (rc
< 0 && errno
== ECHILD
)
1035 /* Set ioctl settings to default ones */
1040 if ((f
= console_open(O_RDWR
|O_NOCTTY
)) < 0) {
1041 initlog(L_VB
, "open(%s): %s", console_dev
,
1043 f
= open("/dev/null", O_RDWR
);
1049 /* Reset all the signals, set up environment */
1050 for(f
= 1; f
< NSIG
; f
++) SETSIG(sa
, f
, SIG_DFL
, SA_RESTART
);
1051 environ
= init_buildenv(1);
1054 * Execute prog. In case of ENOEXEC try again
1055 * as a shell script.
1057 execvp(args
[1], args
+ 1);
1058 if (errno
== ENOEXEC
) {
1061 strcpy(buf
, "exec ");
1062 strncat(buf
, proc
, sizeof(buf
) - strlen(buf
) - 1);
1065 execvp(args
[1], args
+ 1);
1067 initlog(L_VB
, "cannot execute \"%s\"", args
[1]);
1071 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
1073 INITDBG(L_VB
, "Started id %s (pid %d)", ch
->id
, pid
);
1076 initlog(L_VB
, "cannot fork, retry..");
1085 * Start a child running!
1087 void startup(CHILD
*ch
)
1090 * See if it's disabled
1092 if (ch
->flags
& FAILING
) return;
1094 switch(ch
->action
) {
1103 if (!(ch
->flags
& XECUTED
)) ch
->flags
|= WAITING
;
1108 if (ch
->flags
& XECUTED
) break;
1111 ch
->flags
|= RUNNING
;
1112 if (spawn(ch
, &(ch
->pid
)) < 0) break;
1114 * Do NOT log if process field starts with '+'
1115 * FIXME: that's for compatibility with *very*
1116 * old getties - probably it can be taken out.
1118 if (ch
->process
[0] != '+')
1119 write_utmp_wtmp("", ch
->id
, ch
->pid
,
1127 * Read the inittab file.
1129 void read_inittab(void)
1131 FILE *fp
; /* The INITTAB file */
1132 CHILD
*ch
, *old
, *i
; /* Pointers to CHILD structure */
1133 CHILD
*head
= NULL
; /* Head of linked list */
1135 struct stat st
; /* To stat INITLVL */
1137 sigset_t nmask
, omask
; /* For blocking SIGCHLD. */
1138 char buf
[256]; /* Line buffer */
1139 char err
[64]; /* Error message. */
1141 *action
, *process
; /* Fields of a line */
1143 int lineNo
= 0; /* Line number in INITTAB file */
1144 int actionNo
; /* Decoded action field */
1145 int f
; /* Counter */
1146 int round
; /* round 0 for SIGTERM, 1 for SIGKILL */
1147 int foundOne
= 0; /* No killing no sleep */
1148 int talk
; /* Talk to the user */
1149 int done
= 0; /* Ready yet? */
1152 if (newFamily
!= NULL
) {
1153 INITDBG(L_VB
, "PANIC newFamily != NULL");
1156 INITDBG(L_VB
, "Reading inittab");
1160 * Open INITTAB and real line by line.
1162 if ((fp
= fopen(INITTAB
, "r")) == NULL
)
1163 initlog(L_VB
, "No inittab file found");
1167 * Add single user shell entry at the end.
1169 if (fp
== NULL
|| fgets(buf
, sizeof(buf
), fp
) == NULL
) {
1172 * See if we have a single user entry.
1174 for(old
= newFamily
; old
; old
= old
->next
)
1175 if (strpbrk(old
->rlevel
, "S")) break;
1177 snprintf(buf
, sizeof(buf
), "~~:S:wait:%s\n", SULOGIN
);
1183 * Skip comments and empty lines
1185 for(p
= buf
; *p
== ' ' || *p
== '\t'; p
++)
1187 if (*p
== '#' || *p
== '\n') continue;
1192 id
= strsep(&p
, ":");
1193 rlevel
= strsep(&p
, ":");
1194 action
= strsep(&p
, ":");
1195 process
= strsep(&p
, "\n");
1198 * Check if syntax is OK. Be very verbose here, to
1199 * avoid newbie postings on comp.os.linux.setup :)
1202 if (!id
|| !*id
) strcpy(err
, "missing id field");
1203 if (!rlevel
) strcpy(err
, "missing runlevel field");
1204 if (!process
) strcpy(err
, "missing process field");
1205 if (!action
|| !*action
)
1206 strcpy(err
, "missing action field");
1207 if (id
&& strlen(id
) > sizeof(utproto
.ut_id
))
1208 sprintf(err
, "id field too long (max %d characters)",
1209 (int)sizeof(utproto
.ut_id
));
1210 if (rlevel
&& strlen(rlevel
) > 11)
1211 strcpy(err
, "rlevel field too long (max 11 characters)");
1212 if (process
&& strlen(process
) > 127)
1213 strcpy(err
, "process field too long");
1214 if (action
&& strlen(action
) > 32)
1215 strcpy(err
, "action field too long");
1217 initlog(L_VB
, "%s[%d]: %s", INITTAB
, lineNo
, err
);
1218 INITDBG(L_VB
, "%s:%s:%s:%s", id
, rlevel
, action
, process
);
1223 * Decode the "action" field
1226 for(f
= 0; actions
[f
].name
; f
++)
1227 if (strcasecmp(action
, actions
[f
].name
) == 0) {
1228 actionNo
= actions
[f
].act
;
1231 if (actionNo
== -1) {
1232 initlog(L_VB
, "%s[%d]: %s: unknown action field",
1233 INITTAB
, lineNo
, action
);
1238 * See if the id field is unique
1240 for(old
= newFamily
; old
; old
= old
->next
) {
1241 if(strcmp(old
->id
, id
) == 0 && strcmp(id
, "~~")) {
1242 initlog(L_VB
, "%s[%d]: duplicate ID field \"%s\"",
1243 INITTAB
, lineNo
, id
);
1250 * Allocate a CHILD structure
1252 ch
= imalloc(sizeof(CHILD
));
1257 ch
->action
= actionNo
;
1258 strncpy(ch
->id
, id
, sizeof(utproto
.ut_id
) + 1); /* Hack for different libs. */
1259 strncpy(ch
->process
, process
, sizeof(ch
->process
) - 1);
1261 for(f
= 0; f
< (int)sizeof(rlevel
) - 1 && rlevel
[f
]; f
++) {
1262 ch
->rlevel
[f
] = rlevel
[f
];
1263 if (ch
->rlevel
[f
] == 's') ch
->rlevel
[f
] = 'S';
1265 strncpy(ch
->rlevel
, rlevel
, sizeof(ch
->rlevel
) - 1);
1267 strcpy(ch
->rlevel
, "0123456789");
1268 if (ISPOWER(ch
->action
))
1269 strcpy(ch
->rlevel
, "S0123456789");
1272 * We have the fake runlevel '#' for SYSINIT and
1273 * '*' for BOOT and BOOTWAIT.
1275 if (ch
->action
== SYSINIT
) strcpy(ch
->rlevel
, "#");
1276 if (ch
->action
== BOOT
|| ch
->action
== BOOTWAIT
)
1277 strcpy(ch
->rlevel
, "*");
1280 * Now add it to the linked list. Special for powerfail.
1282 if (ISPOWER(ch
->action
)) {
1285 * Disable by default
1287 ch
->flags
|= XECUTED
;
1290 * Tricky: insert at the front of the list..
1293 for(i
= newFamily
; i
; i
= i
->next
) {
1294 if (!ISPOWER(i
->action
)) break;
1298 * Now add after entry "old"
1303 if (i
== NULL
) head
= ch
;
1305 ch
->next
= newFamily
;
1307 if (ch
->next
== NULL
) head
= ch
;
1311 * Just add at end of the list
1313 if (ch
->action
== KBREQUEST
) ch
->flags
|= XECUTED
;
1323 * Walk through the old list comparing id fields
1325 for(old
= family
; old
; old
= old
->next
)
1326 if (strcmp(old
->id
, ch
->id
) == 0) {
1337 * Loop through the list of children, and see if they need to
1341 INITDBG(L_VB
, "Checking for children to kill");
1342 for(round
= 0; round
< 2; round
++) {
1344 for(ch
= family
; ch
; ch
= ch
->next
) {
1345 ch
->flags
&= ~KILLME
;
1348 * Is this line deleted?
1350 if (ch
->new == NULL
) ch
->flags
|= KILLME
;
1353 * If the entry has changed, kill it anyway. Note that
1354 * we do not check ch->process, only the "action" field.
1355 * This way, you can turn an entry "off" immediately, but
1356 * changes in the command line will only become effective
1357 * after the running version has exited.
1359 if (ch
->new && ch
->action
!= ch
->new->action
) ch
->flags
|= KILLME
;
1362 * Only BOOT processes may live in all levels
1364 if (ch
->action
!= BOOT
&&
1365 strchr(ch
->rlevel
, runlevel
) == NULL
) {
1367 * Ondemand procedures live always,
1368 * except in single user
1370 if (runlevel
== 'S' || !(ch
->flags
& DEMAND
))
1371 ch
->flags
|= KILLME
;
1375 * Now, if this process may live note so in the new list
1377 if ((ch
->flags
& KILLME
) == 0) {
1378 ch
->new->flags
= ch
->flags
;
1379 ch
->new->pid
= ch
->pid
;
1380 ch
->new->exstat
= ch
->exstat
;
1386 * Is this process still around?
1388 if ((ch
->flags
& RUNNING
) == 0) {
1389 ch
->flags
&= ~KILLME
;
1392 INITDBG(L_VB
, "Killing \"%s\"", ch
->process
);
1394 case 0: /* Send TERM signal */
1397 "Sending processes the TERM signal");
1398 kill(-(ch
->pid
), SIGTERM
);
1401 case 1: /* Send KILL signal and collect status */
1404 "Sending processes the KILL signal");
1405 kill(-(ch
->pid
), SIGKILL
);
1412 * See if we have to wait 5 seconds
1414 if (foundOne
&& round
== 0) {
1416 * Yup, but check every second if we still have children.
1418 for(f
= 0; f
< sltime
; f
++) {
1419 for(ch
= family
; ch
; ch
= ch
->next
) {
1420 if (!(ch
->flags
& KILLME
)) continue;
1421 if ((ch
->flags
& RUNNING
) && !(ch
->flags
& ZOMBIE
))
1426 * No running children, skip SIGKILL
1429 foundOne
= 0; /* Skip the sleep below. */
1438 * Now give all processes the chance to die and collect exit statuses.
1440 if (foundOne
) do_sleep(1);
1441 for(ch
= family
; ch
; ch
= ch
->next
)
1442 if (ch
->flags
& KILLME
) {
1443 if (!(ch
->flags
& ZOMBIE
))
1444 initlog(L_CO
, "Pid %d [id %s] seems to hang", ch
->pid
,
1447 INITDBG(L_VB
, "Updating utmp for pid %d [id %s]",
1449 ch
->flags
&= ~RUNNING
;
1450 if (ch
->process
[0] != '+')
1451 write_utmp_wtmp("", ch
->id
, ch
->pid
, DEAD_PROCESS
, NULL
);
1456 * Both rounds done; clean up the list.
1458 sigemptyset(&nmask
);
1459 sigaddset(&nmask
, SIGCHLD
);
1460 sigprocmask(SIG_BLOCK
, &nmask
, &omask
);
1461 for(ch
= family
; ch
; ch
= old
) {
1466 for(ch
= family
; ch
; ch
= ch
->next
) ch
->new = NULL
;
1468 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
1472 * Dispose of INITLVL file.
1474 if (lstat(INITLVL
, &st
) >= 0 && S_ISLNK(st
.st_mode
)) {
1476 * INITLVL is a symbolic link, so just truncate the file.
1478 close(open(INITLVL
, O_WRONLY
|O_TRUNC
));
1481 * Delete INITLVL file.
1488 * Dispose of INITLVL2 file.
1490 if (lstat(INITLVL2
, &st
) >= 0 && S_ISLNK(st
.st_mode
)) {
1492 * INITLVL2 is a symbolic link, so just truncate the file.
1494 close(open(INITLVL2
, O_WRONLY
|O_TRUNC
));
1497 * Delete INITLVL2 file.
1505 * Walk through the family list and start up children.
1506 * The entries that do not belong here at all are removed
1509 void start_if_needed(void)
1511 CHILD
*ch
; /* Pointer to child */
1512 int delete; /* Delete this entry from list? */
1514 INITDBG(L_VB
, "Checking for children to start");
1516 for(ch
= family
; ch
; ch
= ch
->next
) {
1519 if (ch
->rlevel
[0] == 'C') {
1520 INITDBG(L_VB
, "%s: flags %d", ch
->process
, ch
->flags
);
1524 /* Are we waiting for this process? Then quit here. */
1525 if (ch
->flags
& WAITING
) break;
1527 /* Already running? OK, don't touch it */
1528 if (ch
->flags
& RUNNING
) continue;
1530 /* See if we have to start it up */
1532 if (strchr(ch
->rlevel
, runlevel
) ||
1533 ((ch
->flags
& DEMAND
) && !strchr("#*Ss", runlevel
))) {
1539 /* FIXME: is this OK? */
1540 ch
->flags
&= ~(RUNNING
|WAITING
);
1541 if (!ISPOWER(ch
->action
) && ch
->action
!= KBREQUEST
)
1542 ch
->flags
&= ~XECUTED
;
1545 /* Do we have to wait for this process? */
1546 if (ch
->flags
& WAITING
) break;
1552 * Ask the user on the console for a runlevel
1554 int ask_runlevel(void)
1556 const char prompt
[] = "\nEnter runlevel: ";
1562 fd
= console_open(O_RDWR
|O_NOCTTY
);
1564 if (fd
< 0) return('S');
1566 while(!strchr("0123456789S", lvl
)) {
1567 write(fd
, prompt
, sizeof(prompt
) - 1);
1569 read(fd
, buf
, sizeof(buf
));
1570 if (buf
[0] != 0 && (buf
[1] == '\r' || buf
[1] == '\n'))
1572 if (islower(lvl
)) lvl
= toupper(lvl
);
1579 * Search the INITTAB file for the 'initdefault' field, with the default
1580 * runlevel. If this fails, ask the user to supply a runlevel.
1582 int get_init_default(void)
1589 * Look for initdefault.
1591 for(ch
= family
; ch
; ch
= ch
->next
)
1592 if (ch
->action
== INITDEFAULT
) {
1595 if (*p
> lvl
) lvl
= *p
;
1601 * See if level is valid
1604 if (islower(lvl
)) lvl
= toupper(lvl
);
1605 if (strchr("0123456789S", lvl
) == NULL
) {
1607 "Initdefault level '%c' is invalid", lvl
);
1612 * Ask for runlevel on console if needed.
1614 if (lvl
<= 0) lvl
= ask_runlevel();
1617 * Log the fact that we have a runlevel now.
1626 * Do actions for the new level. If we are compatible with
1627 * the "old" INITLVL and arg == 0, try to read the new
1628 * runlevel from that file first.
1630 int read_level(int arg
)
1632 CHILD
*ch
; /* Walk through list */
1633 unsigned char foo
= 'X'; /* Contents of INITLVL */
1648 if (stat(INITLVL
, &stt
) != 0 || stt
.st_size
!= 0L)
1649 fp
= fopen(INITLVL
, "r");
1652 (stat(INITLVL2
, &stt
) != 0 || stt
.st_size
!= 0L))
1653 fp
= fopen(INITLVL2
, "r");
1656 /* INITLVL file empty or not there - act as 'init q' */
1657 initlog(L_SY
, "Re-reading inittab");
1660 ok
= fscanf(fp
, "%c %d", &foo
, &st
);
1663 /* We go to the new runlevel passed as an argument. */
1667 if (ok
== 2) sltime
= st
;
1669 #endif /* INITLVL */
1671 if (islower(foo
)) foo
= toupper(foo
);
1672 if (ok
< 1 || ok
> 2 || strchr("QS0123456789ABCU", foo
) == NULL
) {
1673 initlog(L_VB
, "bad runlevel: %c", foo
);
1677 /* Log this action */
1680 initlog(L_VB
, "Going single user");
1683 initlog(L_SY
, "Re-reading inittab");
1689 "Activating demand-procedures for '%c'", foo
);
1692 initlog(L_SY
, "Trying to re-exec init");
1695 initlog(L_VB
, "Switching to runlevel: %c", foo
);
1698 if (foo
== 'Q') return runlevel
;
1700 /* Check if this is a runlevel a, b or c */
1701 if (strchr("ABC", foo
)) {
1702 if (runlevel
== 'S') return(runlevel
);
1704 /* Read inittab again first! */
1707 /* Mark those special tasks */
1708 for(ch
= family
; ch
; ch
= ch
->next
)
1709 if (strchr(ch
->rlevel
, foo
) != NULL
||
1710 strchr(ch
->rlevel
, tolower(foo
)) != NULL
) {
1711 ch
->flags
|= DEMAND
;
1712 ch
->flags
&= ~XECUTED
;
1714 "Marking (%s) as ondemand, flags %d",
1720 /* Store both the old and the new runlevel. */
1721 write_utmp_wtmp("runlevel", "~~", foo
+ 256*runlevel
, RUN_LVL
, "~");
1723 prevlevel
= runlevel
;
1729 * This procedure is called after every signal (SIGHUP, SIGALRM..)
1731 * Only clear the 'failing' flag if the process is sleeping
1732 * longer than 5 minutes, or inittab was read again due
1733 * to user interaction.
1735 void fail_check(void)
1737 CHILD
*ch
; /* Pointer to child structure */
1738 time_t t
; /* System time */
1739 time_t next_alarm
= 0; /* When to set next alarm */
1743 for(ch
= family
; ch
; ch
= ch
->next
) {
1745 if (ch
->flags
& FAILING
) {
1746 /* Can we free this sucker? */
1747 if (ch
->tm
+ SLEEPTIME
< t
) {
1748 ch
->flags
&= ~FAILING
;
1752 /* No, we'll look again later */
1753 if (next_alarm
== 0 ||
1754 ch
->tm
+ SLEEPTIME
> next_alarm
)
1755 next_alarm
= ch
->tm
+ SLEEPTIME
;
1761 if (next_alarm
< 1) next_alarm
= 1;
1766 /* Set all 'Fail' timers to 0 */
1767 void fail_cancel(void)
1771 for(ch
= family
; ch
; ch
= ch
->next
) {
1774 ch
->flags
&= ~FAILING
;
1779 * Start up powerfail entries.
1781 void do_power_fail(int pwrstat
)
1786 * Tell powerwait & powerfail entries to start up
1788 for (ch
= family
; ch
; ch
= ch
->next
) {
1789 if (pwrstat
== 'O') {
1791 * The power is OK again.
1793 if (ch
->action
== POWEROKWAIT
)
1794 ch
->flags
&= ~XECUTED
;
1795 } else if (pwrstat
== 'L') {
1797 * Low battery, shut down now.
1799 if (ch
->action
== POWERFAILNOW
)
1800 ch
->flags
&= ~XECUTED
;
1803 * Power is failing, shutdown imminent
1805 if (ch
->action
== POWERFAIL
|| ch
->action
== POWERWAIT
)
1806 ch
->flags
&= ~XECUTED
;
1812 * Check for state-pipe presence
1814 int check_pipe(int fd
)
1822 t
.tv_sec
= t
.tv_usec
= 0;
1824 if (select(fd
+1, &s
, NULL
, NULL
, &t
) != 1)
1826 if (read(fd
, signature
, 8) != 8)
1828 return strncmp(Signature
, signature
, 8) == 0;
1832 * Make a state-pipe.
1834 int make_pipe(int fd
)
1841 fcntl(fds
[1], F_SETFD
, 1);
1842 fcntl(fd
, F_SETFD
, 0);
1843 write(fds
[1], Signature
, 8);
1849 * Attempt to re-exec.
1854 sigset_t mask
, oldset
;
1859 if (strchr("S0123456",runlevel
) == NULL
)
1863 * Reset the alarm, and block all signals.
1867 sigprocmask(SIG_BLOCK
, &mask
, &oldset
);
1870 * construct a pipe fd --> STATE_PIPE and write a signature
1872 fd
= make_pipe(STATE_PIPE
);
1875 * It's a backup day today, so I'm pissed off. Being a BOFH, however,
1876 * does have it's advantages...
1881 DELSET(got_signals
, SIGCHLD
);
1882 DELSET(got_signals
, SIGHUP
);
1883 DELSET(got_signals
, SIGUSR1
);
1886 * That should be cleaned.
1888 for(ch
= family
; ch
; ch
= ch
->next
)
1889 if (ch
->flags
& ZOMBIE
) {
1890 INITDBG(L_VB
, "Child died, PID= %d", ch
->pid
);
1891 ch
->flags
&= ~(RUNNING
|ZOMBIE
|WAITING
);
1892 if (ch
->process
[0] != '+')
1893 write_utmp_wtmp("", ch
->id
, ch
->pid
, DEAD_PROCESS
, NULL
);
1896 if ((pid
= fork()) == 0) {
1898 * Child sends state information to the parent.
1905 * The existing init process execs a new init binary.
1907 env
= init_buildenv(0);
1908 execle(myname
, myname
, "--init", NULL
, env
);
1911 * We shouldn't be here, something failed.
1912 * Bitch, close the state pipe, unblock signals and return.
1916 sigprocmask(SIG_SETMASK
, &oldset
, NULL
);
1918 initlog(L_CO
, "Attempt to re-exec failed");
1923 * We got a change runlevel request through the
1924 * init.fifo. Process it.
1926 void fifo_new_level(int level
)
1933 if (level
== runlevel
) return;
1936 /* Are we waiting for a child? */
1937 for(ch
= family
; ch
; ch
= ch
->next
)
1938 if (ch
->flags
& WAITING
) break;
1942 /* We need to go into a new runlevel */
1943 oldlevel
= runlevel
;
1944 runlevel
= read_level(level
);
1945 if (runlevel
== 'U') {
1946 runlevel
= oldlevel
;
1949 if (oldlevel
!= 'S' && runlevel
== 'S') console_stty();
1950 if (runlevel
== '6' || runlevel
== '0' ||
1951 runlevel
== '1') console_stty();
1954 setproctitle("init [%c]", runlevel
);
1961 * Set/unset environment variables. The variables are
1962 * encoded as KEY=VAL\0KEY=VAL\0\0. With "=VAL" it means
1963 * setenv, without it means unsetenv.
1965 void initcmd_setenv(char *data
, int size
)
1967 char *env
, *p
, *e
, *eq
;
1972 while (*data
&& data
< e
) {
1974 for (p
= data
; *p
&& p
< e
; p
++)
1975 if (*p
== '=') eq
= p
;
1980 sz
= eq
? (eq
- env
) : (p
- env
);
1982 /*initlog(L_SY, "init_setenv: %s, %s, %d", env, eq, sz);*/
1985 * We only allow INIT_* to be set.
1987 if (strncmp(env
, "INIT_", 5) != 0)
1990 /* Free existing vars. */
1991 for (i
= 0; i
< NR_EXTRA_ENV
; i
++) {
1992 if (extra_env
[i
] == NULL
) continue;
1993 if (!strncmp(extra_env
[i
], env
, sz
) &&
1994 extra_env
[i
][sz
] == '=') {
1996 extra_env
[i
] = NULL
;
2000 /* Set new vars if needed. */
2001 if (eq
== NULL
) continue;
2002 for (i
= 0; i
< NR_EXTRA_ENV
; i
++) {
2003 if (extra_env
[i
] == NULL
) {
2004 extra_env
[i
] = istrdup(env
);
2013 * Read from the init FIFO. Processes like telnetd and rlogind can
2014 * ask us to create login processes on their behalf.
2016 * FIXME: this needs to be finished. NOT that it is buggy, but we need
2017 * to add the telnetd/rlogind stuff so people can start using it.
2018 * Maybe move to using an AF_UNIX socket so we can use
2019 * the 2.2 kernel credential stuff to see who we're talking to.
2022 void check_init_fifo(void)
2024 struct init_request request
;
2026 struct stat st
, st2
;
2032 * First, try to create /dev/initctl if not present.
2034 if (stat(INIT_FIFO
, &st2
) < 0 && errno
== ENOENT
)
2035 (void)mkfifo(INIT_FIFO
, 0600);
2038 * If /dev/initctl is open, stat the file to see if it
2039 * is still the _same_ inode.
2042 fstat(pipe_fd
, &st
);
2043 if (stat(INIT_FIFO
, &st2
) < 0 ||
2044 st
.st_dev
!= st2
.st_dev
||
2045 st
.st_ino
!= st2
.st_ino
) {
2052 * Now finally try to open /dev/initctl
2055 if ((pipe_fd
= open(INIT_FIFO
, O_RDWR
|O_NONBLOCK
)) >= 0) {
2056 fstat(pipe_fd
, &st
);
2057 if (!S_ISFIFO(st
.st_mode
)) {
2058 initlog(L_VB
, "%s is not a fifo", INIT_FIFO
);
2065 * Don't use fd's 0, 1 or 2.
2067 (void) dup2(pipe_fd
, PIPE_FD
);
2072 * Return to caller - we'll be back later.
2077 /* Wait for data to appear, _if_ the pipe was opened. */
2078 if (pipe_fd
>= 0) while(!quit
) {
2080 /* Do select, return on EINTR. */
2082 FD_SET(pipe_fd
, &fds
);
2085 n
= select(pipe_fd
+ 1, &fds
, NULL
, NULL
, &tv
);
2087 if (n
== 0 || errno
== EINTR
) return;
2091 /* Read the data, return on EINTR. */
2092 n
= read(pipe_fd
, &request
, sizeof(request
));
2095 * End of file. This can't happen under Linux (because
2096 * the pipe is opened O_RDWR - see select() in the
2097 * kernel) but you never know...
2104 if (errno
== EINTR
) return;
2105 initlog(L_VB
, "error reading initrequest");
2110 * This is a convenient point to also try to
2111 * find the console device or check if it changed.
2118 if (request
.magic
!= INIT_MAGIC
|| n
!= sizeof(request
)) {
2119 initlog(L_VB
, "got bogus initrequest");
2122 switch(request
.cmd
) {
2123 case INIT_CMD_RUNLVL
:
2124 sltime
= request
.sleeptime
;
2125 fifo_new_level(request
.runlevel
);
2128 case INIT_CMD_POWERFAIL
:
2129 sltime
= request
.sleeptime
;
2133 case INIT_CMD_POWERFAILNOW
:
2134 sltime
= request
.sleeptime
;
2138 case INIT_CMD_POWEROK
:
2139 sltime
= request
.sleeptime
;
2143 case INIT_CMD_SETENV
:
2144 initcmd_setenv(request
.i
.data
, sizeof(request
.i
.data
));
2147 initlog(L_VB
, "got unimplemented initrequest.");
2153 * We come here if the pipe couldn't be opened.
2155 if (pipe_fd
< 0) pause();
2161 * This function is used in the transition
2162 * sysinit (-> single user) boot -> multi-user.
2164 void boot_transitions()
2167 static int newlevel
= 0;
2168 static int warn
= 1;
2172 /* Check if there is something to wait for! */
2173 for( ch
= family
; ch
; ch
= ch
->next
)
2174 if ((ch
->flags
& RUNNING
) && ch
->action
!= BOOT
) break;
2177 /* No processes left in this level, proceed to next level. */
2181 case '#': /* SYSINIT -> BOOT */
2182 INITDBG(L_VB
, "SYSINIT -> BOOT");
2184 /* Write a boot record. */
2185 wrote_utmp_reboot
= 0;
2186 wrote_wtmp_reboot
= 0;
2187 write_utmp_wtmp("reboot", "~~", 0, BOOT_TIME
, "~");
2189 /* Get our run level */
2190 newlevel
= dfl_level
? dfl_level
: get_init_default();
2191 if (newlevel
== 'S') {
2192 runlevel
= newlevel
;
2193 /* Not really 'S' but show anyway. */
2194 setproctitle("init [S]");
2198 case '*': /* BOOT -> NORMAL */
2199 INITDBG(L_VB
, "BOOT -> NORMAL");
2200 if (runlevel
!= newlevel
)
2201 loglevel
= newlevel
;
2202 runlevel
= newlevel
;
2206 case 'S': /* Ended SU mode */
2208 INITDBG(L_VB
, "END SU MODE");
2209 newlevel
= get_init_default();
2210 if (!did_boot
&& newlevel
!= 'S')
2213 if (runlevel
!= newlevel
)
2214 loglevel
= newlevel
;
2215 runlevel
= newlevel
;
2219 for(ch
= family
; ch
; ch
= ch
->next
)
2220 if (strcmp(ch
->rlevel
, "S") == 0)
2221 ch
->flags
&= ~(FAILING
|WAITING
|XECUTED
);
2226 "no more processes left in this runlevel");
2229 if (got_signals
== 0)
2234 initlog(L_VB
, "Entering runlevel: %c", runlevel
);
2235 write_utmp_wtmp("runlevel", "~~", runlevel
+ 256 * oldlevel
, RUN_LVL
, "~");
2236 thislevel
= runlevel
;
2237 prevlevel
= oldlevel
;
2238 setproctitle("init [%c]", runlevel
);
2244 * Init got hit by a signal. See which signal it is,
2245 * and act accordingly.
2247 void process_signals()
2255 if (ISMEMBER(got_signals
, SIGPWR
)) {
2256 INITDBG(L_VB
, "got SIGPWR");
2257 /* See _what_ kind of SIGPWR this is. */
2259 if ((fd
= open(PWRSTAT
, O_RDONLY
)) >= 0) {
2266 do_power_fail(pwrstat
);
2267 DELSET(got_signals
, SIGPWR
);
2270 if (ISMEMBER(got_signals
, SIGINT
)) {
2271 INITDBG(L_VB
, "got SIGINT");
2272 /* Tell ctrlaltdel entry to start up */
2273 for(ch
= family
; ch
; ch
= ch
->next
)
2274 if (ch
->action
== CTRLALTDEL
)
2275 ch
->flags
&= ~XECUTED
;
2276 DELSET(got_signals
, SIGINT
);
2279 if (ISMEMBER(got_signals
, SIGWINCH
)) {
2280 INITDBG(L_VB
, "got SIGWINCH");
2281 /* Tell kbrequest entry to start up */
2282 for(ch
= family
; ch
; ch
= ch
->next
)
2283 if (ch
->action
== KBREQUEST
)
2284 ch
->flags
&= ~XECUTED
;
2285 DELSET(got_signals
, SIGWINCH
);
2288 if (ISMEMBER(got_signals
, SIGALRM
)) {
2289 INITDBG(L_VB
, "got SIGALRM");
2290 /* The timer went off: check it out */
2291 DELSET(got_signals
, SIGALRM
);
2294 if (ISMEMBER(got_signals
, SIGCHLD
)) {
2295 INITDBG(L_VB
, "got SIGCHLD");
2296 /* First set flag to 0 */
2297 DELSET(got_signals
, SIGCHLD
);
2299 /* See which child this was */
2300 for(ch
= family
; ch
; ch
= ch
->next
)
2301 if (ch
->flags
& ZOMBIE
) {
2302 INITDBG(L_VB
, "Child died, PID= %d", ch
->pid
);
2303 ch
->flags
&= ~(RUNNING
|ZOMBIE
|WAITING
);
2304 if (ch
->process
[0] != '+')
2305 write_utmp_wtmp("", ch
->id
, ch
->pid
, DEAD_PROCESS
, NULL
);
2310 if (ISMEMBER(got_signals
, SIGHUP
)) {
2311 INITDBG(L_VB
, "got SIGHUP");
2313 /* Are we waiting for a child? */
2314 for(ch
= family
; ch
; ch
= ch
->next
)
2315 if (ch
->flags
& WAITING
) break;
2319 /* We need to go into a new runlevel */
2320 oldlevel
= runlevel
;
2322 runlevel
= read_level(0);
2324 if (runlevel
== 'U') {
2325 runlevel
= oldlevel
;
2328 if (oldlevel
!= 'S' && runlevel
== 'S') console_stty();
2329 if (runlevel
== '6' || runlevel
== '0' ||
2330 runlevel
== '1') console_stty();
2333 setproctitle("init [%c]", runlevel
);
2334 DELSET(got_signals
, SIGHUP
);
2338 if (ISMEMBER(got_signals
, SIGUSR1
)) {
2340 * SIGUSR1 means close and reopen /dev/initctl
2342 INITDBG(L_VB
, "got SIGUSR1");
2345 DELSET(got_signals
, SIGUSR1
);
2355 struct sigaction sa
;
2364 * Fork so we can debug the init process.
2366 if ((f
= fork()) > 0) {
2367 static const char killmsg
[] = "PRNT: init killed.\r\n";
2370 while((rc
= wait(&st
)) != f
)
2371 if (rc
< 0 && errno
== ECHILD
)
2373 write(1, killmsg
, sizeof(killmsg
) - 1);
2380 * Tell the kernel to send us SIGINT when CTRL-ALT-DEL
2381 * is pressed, and that we want to handle keyboard signals.
2383 init_reboot(BMAGIC_SOFT
);
2384 if ((f
= open(VT_MASTER
, O_RDWR
| O_NOCTTY
)) >= 0) {
2385 (void) ioctl(f
, KDSIGACCEPT
, SIGWINCH
);
2388 (void) ioctl(0, KDSIGACCEPT
, SIGWINCH
);
2392 * Ignore all signals.
2394 for(f
= 1; f
<= NSIG
; f
++)
2395 SETSIG(sa
, f
, SIG_IGN
, SA_RESTART
);
2398 SETSIG(sa
, SIGALRM
, signal_handler
, 0);
2399 SETSIG(sa
, SIGHUP
, signal_handler
, 0);
2400 SETSIG(sa
, SIGINT
, signal_handler
, 0);
2401 SETSIG(sa
, SIGCHLD
, chld_handler
, SA_RESTART
);
2402 SETSIG(sa
, SIGPWR
, signal_handler
, 0);
2403 SETSIG(sa
, SIGWINCH
, signal_handler
, 0);
2404 SETSIG(sa
, SIGUSR1
, signal_handler
, 0);
2405 SETSIG(sa
, SIGSTOP
, stop_handler
, SA_RESTART
);
2406 SETSIG(sa
, SIGTSTP
, stop_handler
, SA_RESTART
);
2407 SETSIG(sa
, SIGCONT
, cont_handler
, SA_RESTART
);
2408 SETSIG(sa
, SIGSEGV
, (void (*)(int))segv_handler
, SA_RESTART
);
2414 /* Close whatever files are open, and reset the console. */
2422 * Set default PATH variable.
2424 setenv("PATH", PATH_DEFAULT
, 1 /* Overwrite */);
2427 * Initialize /var/run/utmp (only works if /var is on
2428 * root and mounted rw)
2430 (void) close(open(UTMP_FILE
, O_WRONLY
|O_CREAT
|O_TRUNC
, 0644));
2433 * Say hello to the world
2435 initlog(L_CO
, bootmsg
, "booting");
2438 * See if we have to start an emergency shell.
2441 SETSIG(sa
, SIGCHLD
, SIG_DFL
, SA_RESTART
);
2442 if (spawn(&ch_emerg
, &f
) > 0) {
2443 while((rc
= wait(&st
)) != f
)
2444 if (rc
< 0 && errno
== ECHILD
)
2447 SETSIG(sa
, SIGCHLD
, chld_handler
, SA_RESTART
);
2451 * Start normal boot procedure.
2458 * Restart: unblock signals and let the show go on
2460 initlog(L_CO
, bootmsg
, "reloading");
2462 sigprocmask(SIG_UNBLOCK
, &sgt
, NULL
);
2465 * Set default PATH variable.
2467 setenv("PATH", PATH_DEFAULT
, 0 /* Don't overwrite */);
2473 /* See if we need to make the boot transitions. */
2475 INITDBG(L_VB
, "init_main: waiting..");
2477 /* Check if there are processes to be waited on. */
2478 for(ch
= family
; ch
; ch
= ch
->next
)
2479 if ((ch
->flags
& RUNNING
) && ch
->action
!= BOOT
) break;
2482 /* Wait until we get hit by some signal. */
2483 while (ch
!= NULL
&& got_signals
== 0) {
2484 if (ISMEMBER(got_signals
, SIGHUP
)) {
2485 /* See if there are processes to be waited on. */
2486 for(ch
= family
; ch
; ch
= ch
->next
)
2487 if (ch
->flags
& WAITING
) break;
2489 if (ch
!= NULL
) check_init_fifo();
2491 #else /* CHANGE_WAIT */
2492 if (ch
!= NULL
&& got_signals
== 0) check_init_fifo();
2493 #endif /* CHANGE_WAIT */
2495 /* Check the 'failing' flags */
2498 /* Process any signals. */
2501 /* See what we need to start up (again) */
2508 * Tell the user about the syntax we expect.
2512 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
);
2516 int telinit(char *progname
, int argc
, char **argv
)
2518 #ifdef TELINIT_USES_INITLVL
2521 struct init_request request
;
2522 struct sigaction sa
;
2526 memset(&request
, 0, sizeof(request
));
2527 request
.magic
= INIT_MAGIC
;
2529 while ((f
= getopt(argc
, argv
, "t:e:")) != EOF
) switch(f
) {
2531 sltime
= atoi(optarg
);
2535 env
= request
.i
.data
;
2537 if (env
+ l
+ 2 > request
.i
.data
+ sizeof(request
.i
.data
)) {
2538 fprintf(stderr
, "%s: -e option data "
2539 "too large\n", progname
);
2542 memcpy(env
, optarg
, l
);
2551 if (env
) *env
++ = 0;
2556 request
.cmd
= INIT_CMD_SETENV
;
2558 if (argc
- optind
!= 1 || strlen(argv
[optind
]) != 1)
2560 if (!strchr("0123456789SsQqAaBbCcUu", argv
[optind
][0]))
2562 request
.cmd
= INIT_CMD_RUNLVL
;
2563 request
.runlevel
= env
? 0 : argv
[optind
][0];
2564 request
.sleeptime
= sltime
;
2567 /* Open the fifo and write a command. */
2568 /* Make sure we don't hang on opening /dev/initctl */
2569 SETSIG(sa
, SIGALRM
, signal_handler
, 0);
2571 if ((fd
= open(INIT_FIFO
, O_WRONLY
)) >= 0 &&
2572 write(fd
, &request
, sizeof(request
)) == sizeof(request
)) {
2578 #ifdef TELINIT_USES_INITLVL
2579 if (request
.cmd
== INIT_CMD_RUNLVL
) {
2580 /* Fallthrough to the old method. */
2582 /* Now write the new runlevel. */
2583 if ((fp
= fopen(INITLVL
, "w")) == NULL
) {
2584 fprintf(stderr
, "%s: cannot create %s\n",
2588 fprintf(fp
, "%s %d", argv
[optind
], sltime
);
2591 /* And tell init about the pending runlevel change. */
2592 if (kill(INITPID
, SIGHUP
) < 0) perror(progname
);
2598 fprintf(stderr
, "%s: ", progname
);
2599 if (ISMEMBER(got_signals
, SIGALRM
)) {
2600 fprintf(stderr
, "timeout opening/writing control channel %s\n",
2609 * Main entry for init and telinit.
2611 int main(int argc
, char **argv
)
2618 /* Get my own name */
2619 if ((p
= strrchr(argv
[0], '/')) != NULL
)
2626 if (geteuid() != 0) {
2627 fprintf(stderr
, "%s: must be superuser.\n", p
);
2632 * Is this telinit or init ?
2634 isinit
= (getpid() == 1);
2635 for (f
= 1; f
< argc
; f
++) {
2636 if (!strcmp(argv
[f
], "-i") || !strcmp(argv
[f
], "--init")) {
2641 if (!isinit
) exit(telinit(p
, argc
, argv
));
2646 if (check_pipe(STATE_PIPE
)) {
2648 receive_state(STATE_PIPE
);
2650 myname
= istrdup(argv
[0]);
2653 for (f
= 0; f
< argc
; f
++)
2654 maxproclen
+= strlen(argv
[f
]) + 1;
2656 setproctitle("init [%c]",runlevel
);
2661 /* Check command line arguments */
2662 maxproclen
= strlen(argv
[0]) + 1;
2663 for(f
= 1; f
< argc
; f
++) {
2664 if (!strcmp(argv
[f
], "single") || !strcmp(argv
[f
], "-s"))
2666 else if (!strcmp(argv
[f
], "-a") || !strcmp(argv
[f
], "auto"))
2667 putenv("AUTOBOOT=YES");
2668 else if (!strcmp(argv
[f
], "-b") || !strcmp(argv
[f
],"emergency"))
2670 else if (!strcmp(argv
[f
], "-z")) {
2672 if (argv
[f
+ 1]) f
++;
2673 } else if (strchr("0123456789sS", argv
[f
][0])
2674 && strlen(argv
[f
]) == 1)
2675 dfl_level
= argv
[f
][0];
2676 /* "init u" in the very beginning makes no sense */
2677 if (dfl_level
== 's') dfl_level
= 'S';
2678 maxproclen
+= strlen(argv
[f
]) + 1;
2682 if (getenv("SELINUX_INIT") == NULL
&& !is_selinux_enabled()) {
2683 putenv("SELINUX_INIT=YES");
2684 if (selinux_init_load_policy(&enforce
) == 0 ) {
2685 execv(myname
, argv
);
2688 /* SELinux in enforcing mode but load_policy failed */
2689 /* At this point, we probably can't open /dev/console, so log() won't work */
2690 fprintf(stderr
,"Unable to load SELinux Policy. Machine is in enforcing mode. Halting now.\n");
2696 /* Start booting. */
2699 setproctitle("init boot");
2700 init_main(dfl_level
);