2 * Copyright (c) 1998 Andrzej Bialecki
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * A primitive version of init(8) with simplistic user interface
33 #include <sys/types.h>
34 #include <sys/param.h>
35 #include <sys/mount.h>
36 #include <sys/reboot.h>
38 #include <sys/resource.h>
44 #error "Not yet. But it's quite simple to add - patches are welcome!"
71 char vty[]="0123456789abcdef";
80 char *trans[]={ "NONE", "SINGLE", "MULTI", "DEATH" };
82 extern char **environ;
84 /* Struct for holding session state */
86 char tty[16]; /* vty device path */
87 pid_t pid; /* pid of process running on it */
88 int (*func)(int argc, char **argv);
89 /* internal function to run on it (after forking) */
92 /* Struct for built-in command */
94 char *cmd; /* command name */
95 char *descr; /* command description */
96 char *usage; /* usage */
97 char *example; /* example of usage */
98 int (*func)(char *); /* callback function */
111 void do_command(int shell, char *cmdline);
112 void transition_handler(int);
114 /* Table of built-in functions */
115 struct command bltins[]={
116 {"cd","Change working directory","cd [dir]","cd /etc",cd},
117 {"pwd","Print current directory","pwd","pwd",pwd},
118 {"exit","Exit from shell()","exit","exit",xit},
119 {"set","Set environment variable","set [VAR=value]","set TERM=cons25",set},
120 {"unset","Unset environment variable","unset VAR","unset EDITOR",unset},
121 {"echo","Echo arguments on stdout","echo arg1 arg2 ...","echo Hello World!",echo},
122 {"env","Print all environment variables","env","env",env},
123 {".","Source-in a file with commands",". filename",". /etc/rc",sourcer},
124 {"?","Print this help :-)","? [command]","? set",help},
125 {NULL,NULL,NULL,NULL,NULL}
129 * Built-in 'cd <path>' handler
134 if(chdir(path)) return(-1);
140 * Built-in 'pwd' handler
146 if(getcwd(cwd,BUFSIZE)==NULL) return(-1);
152 * Built-in 'exit' handler
161 * Built-in 'echo' handler
169 int s_quote=0,d_quote=0;
178 if(args[0]=='-' && args[1]=='n') {
181 while(i<len && (args[i]==' ' || args[i]=='\t')) i++;
189 if(s_quote||d_quote) {
220 for(j=i+1;j<len;j++) {
231 printf("\necho(): unmatched \"\n");
239 for(j=i+1;j<len;j++) {
250 printf("\necho(): unmatched '\n");
256 printf("echo(): backquote not implemented yet!\n");
265 if(!no_lf) putchar('\n');
270 * Built-in 'set VAR=value' handler
277 if(var==NULL) return(env(NULL));
279 if(res) printf("set: %s\n",strerror(errno));
284 * Built-in 'env' handler
299 * Built-in 'unset VAR' handler
305 printf("%s: parameter required.\n",progname);
308 return(unsetenv(var));
312 * Built-in '?' handler
321 printf("\nBuilt-in commands:\n");
322 printf("-------------------\n");
324 while(x->cmd!=NULL) {
325 printf("%s\t%s\n",x->cmd,x->descr);
328 printf("\nEnter '? <cmd>' for details.\n\n");
332 while(x->cmd!=NULL) {
333 if(strcmp(x->cmd,cmd)==0) {
340 printf("\n%s\t%s:\n",x->cmd,x->descr);
341 printf("\tUsage:\n\t\t%s\n",x->usage);
342 printf("\te.g:\n\t\t%s\n\n",x->example);
345 printf("\n%s: no such command.\n\n",cmd);
352 * Signal handler for shell()
369 * Built-in '.' handler (read-in and execute commands from file)
375 char buf[512],*tok,*arg,**av;
382 printf("Couldn't open file '%s'\n",fname);
387 if(fgets(buf,512,fd)==NULL) continue;
388 if((*buf=='#') || (*buf=='\n')) continue;
391 if(strncmp(buf,"ncons",5)==0) {
393 tok=strtok(NULL,sep);
395 if((ncons<1)||(ncons>MAX_CONS)) {
396 syslog(LOG_EMERG,"%s: bad ncons value; defaulting to %d\n",fname,MAX_CONS);
400 } else if(strncmp(buf,"motd",4)==0) {
402 motd=strdup(strtok(NULL,sep));
407 /* Next command, please. */
410 syslog(LOG_EMERG,"Done with %s",fname);
414 do_command(int shell, char *cmdline)
416 char *tok,*c,*sep=" \t";
425 if(cmdline[len-1]=='&') {
430 tok=strtok(cmdline,sep);
433 while(x->cmd!=NULL) {
434 if(strcmp(x->cmd,tok)==0) {
441 tok=cmdline+strlen(x->cmd)+1;
442 while(*tok && isblank(*tok) && (tok<(cmdline+len))) tok++;
443 if(*tok==NULL) tok=NULL;
448 av=(char **)calloc(((len+1)/2+1),sizeof(char *));
450 while((av[ac++]=strtok(NULL,sep))!=NULL)
452 switch((pid=fork())) {
455 signal(SIGINT,SIG_DFL);
456 signal(SIGQUIT,SIG_DFL);
457 signal(SIGTERM,SIG_DFL);
458 signal(SIGHUP,SIG_DFL);
463 f=open(_PATH_CONSOLE,O_RDWR);
471 printf("do_command(%s): failed to run bg: %s\n",
472 av[0],strerror(errno));
477 /* Something went wrong... */
478 printf("do_command(%s): %s\n",av[0],strerror(errno));
482 printf("do_command(): %s\n",strerror(errno));
485 while(waitpid(pid,&res,0)!=pid) continue;
486 if(WEXITSTATUS(res)) {
487 printf("do_command(%s): exit code=%d\n",
488 av[0],WEXITSTATUS(res));
497 * This is the user interface. This routine gets executed on each
498 * virtual console serviced by init.
500 * It works as normal shell does - for each external command it forks
501 * and execs, for each internal command just executes a function.
505 shell(int argc, char **argv)
514 if((fd=open(motd,O_RDONLY))!=-1) {
516 res=read(fd,buf,BUFSIZE);
517 res=write(1,buf,res);
523 printf("\n\n+=========================================================+\n");
524 printf("| Built-in shell() (enter '?' for short help on commands) |\n");
525 printf("+=========================================================+\n\n");
528 signal(SIGINT,shell_sig);
529 signal(SIGQUIT,shell_sig);
530 signal(SIGTERM,shell_sig);
531 while(!feof(stdin)) {
532 memset(buf,0,BUFSIZE);
533 printf("(%d)%s%s",mypid,cwd,prompt);
535 if(fgets(buf,BUFSIZE-1,stdin)==NULL) continue;
536 buf[strlen(buf)-1]='\0';
537 if(strlen(buf)==0) continue;
544 * Stub for executing some external program on a console. This is called
545 * from previously forked copy of our process, so that exec is ok.
548 external_cmd(int argc, char **argv)
550 execvp(argv[0],argv);
554 * Acquire vty and properly attach ourselves to it.
555 * Also, build basic environment for running user interface.
559 start_session(int vty, int argc, char **argv)
567 revoke(ttys[vty].tty);
568 fd=open(ttys[vty].tty,O_RDWR);
575 putenv("TERM=cons25");
577 putenv("PATH=/stand:/bin:/usr/bin:/sbin:.");
578 signal(SIGHUP,SIG_DFL);
579 signal(SIGINT,SIG_DFL);
580 signal(SIGQUIT,SIG_DFL);
581 signal(SIGTERM,SIG_DFL);
583 t=(char *)(rindex(ttys[vty].tty,'/')+1);
584 printf("\n\n\nStarting session on %s.\n",t);
585 ttys[vty].func(argc,argv);
590 * Execute system startup script /etc/rc
592 * (Of course if you don't like it - I don't - you can run anything you
593 * want here. Perhaps it would be useful just to read some config DB and
594 * do these things ourselves, avoiding forking lots of shells and scripts.)
597 /* If OINIT_RC is defined, oinit will use it's own configuration file,
598 * /etc/oinit.rc. It's format is described below. Otherwise, it will use
599 * normal /etc/rc interpreted by Bourne shell.
603 #define SH_NAME "-sh"
606 #define SH_PATH _PATH_BSHELL
609 #define SH_ARG "/etc/rc"
619 if((pid=fork())==0) {
624 fd=open(_PATH_CONSOLE,O_RDWR);
632 execvp(SH_PATH,argv);
633 printf("runcom(): %s\n",strerror(errno));
636 /* Wait for child to exit */
637 while(pid!=waitpid(pid,(int *)0,0)) continue;
641 /* Alternative /etc/rc - default is /etc/oinit.rc. Its format is as follows:
642 * - each empty line or line beginning with a '#' is discarded
643 * - any other line must contain a keyword, or a (nonblocking) command to run.
645 * Thus far, the following keywords are defined:
646 * ncons <number> number of virtual consoles to open
647 * motd <pathname> full path to motd file
649 * Examples of commands to run:
651 * ifconfig lo0 inet 127.0.0.1 netmask 255.0.0.0
652 * ifconfig ed0 inet 148.81.168.10 netmask 255.255.255.0
653 * kbdcontrol -l /usr/share/syscons/my_map.kbd
663 fd=open(_PATH_CONSOLE,O_RDWR);
679 /* Run /etc/rc if not in single user */
681 if(prevtrans==SINGLE) runcom();
683 if(prevtrans==SINGLE) runcom(OINIT_RC);
685 if(transition!=MULTI) return(-1);
687 syslog(LOG_EMERG,"*** Starting multi-user mode ***");
689 /* Fork shell interface for each console */
690 for(i=0;i<ncons;i++) {
694 start_session(i,0,NULL);
697 printf("%s: %s\n",progname,strerror(errno));
705 /* Initialize any other services we'll use - most probably this will
706 * be a 'telnet' service (some day...).
710 /* Emulate multi-user */
711 while(transition==MULTI) {
712 /* XXX Modify this to allow for checking for the input on
713 * XXX listening sockets, and forking a 'telnet' service.
717 /* Wait for any process to exit */
718 pid=waitpid(-1,(int *)0,0);
719 if(pid==-1) continue;
722 /* search if it's one of our sessions */
723 for(i=0;i<ncons;i++) {
724 if(ttys[i].pid==pid) {
732 /* Just collect the process's status */
735 /* restart shell() on a console, if it died */
736 if(transition!=MULTI) return(0);
740 start_session(j,0,NULL);
743 printf("%s: %s\n",progname,strerror(errno));
766 * Start a shell on ttyv0 (i.e. the console).
774 static int sigs[2]={SIGTERM,SIGKILL};
776 syslog(LOG_EMERG,"*** Starting single-user mode ***");
777 /* Kill all existing sessions */
778 syslog(LOG_EMERG,"Killing all existing sessions...");
779 for(i=0;i<MAX_CONS;i++) {
780 kill(ttys[i].pid,SIGHUP);
784 if(kill(-1,sigs[i])==-1 && errno==ESRCH) break;
788 pid=waitpid(-1,(int *)0,WUNTRACED);
789 if(errno==EINTR) continue;
794 syslog(LOG_EMERG,"Some processes would not die; ps -axl advised");
799 start_session(0,0,NULL);
802 printf("%s: %s\n",progname,strerror(errno));
803 printf("The system is seriously hosed. I'm dying...\n");
809 wpid=waitpid(pid,(int *)0,WUNTRACED);
810 } while(wpid!=pid && transition==SINGLE);
811 if(transition!=DEATH) {
812 prevtrans=transition;
821 * Transition handler - installed as signal handler.
825 transition_handler(int sig)
831 prevtrans=transition;
833 syslog(LOG_EMERG,"*** Going from %s -> %s\n",trans[prevtrans],trans[transition]);
834 if(prevtrans!=transition) longjmp(machine,sig);
838 prevtrans=transition;
840 syslog(LOG_EMERG,"*** Going from %s -> %s\n",trans[prevtrans],trans[transition]);
841 if(prevtrans!=transition) longjmp(machine,sig);
844 syslog(LOG_EMERG,"pid=%d sig=%s (ignored)\n",getpid(),sys_siglist[sig]);
850 * Change system state appropriately to the signals
858 while(transition!=DEATH) {
868 syslog(LOG_EMERG,"Killing all existing sessions...");
869 /* Kill all sessions */
871 /* Be nice and wait for them */
872 while(waitpid(-1,(int *)0,WNOHANG|WUNTRACED)>0) continue;
879 main(int argc, char **argv)
883 /* These are copied from real init(8) */
885 errx(1,"%s",strerror(EPERM));
886 openlog("init",LOG_CONS|LOG_ODELAY,LOG_AUTH);
888 warn("initial setsid() failed");
889 if(setlogin("root")<0)
890 warn("setlogin() failed");
897 progname=rindex(argv[0],'/');
904 /* We must recognize the same options as real init does */
905 while((c=getopt(argc,argv,"dsf"))!=-1) {
916 printf("%s: unrecognized flag '-%c'\n",progname,c);
921 mount("devfs",_PATH_DEV,MNT_NOEXEC|MNT_RDONLY,0);
923 /* Fill in the sess structures. */
924 /* XXX Really, should be filled based upon config file. */
925 for(i=0;i<MAX_CONS;i++) {
927 sprintf(ttys[i].tty,_PATH_CONSOLE);
929 sprintf(ttys[i].tty,"%sv%c",_PATH_TTY,vty[i]);
937 signal(SIGINT,transition_handler);
938 signal(SIGQUIT,transition_handler);
939 signal(SIGTERM,transition_handler);
940 signal(SIGHUP,transition_handler);
941 signal(SIGALRM,kill_timer);
944 transition_machine(transition);