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 */
102 int cd __P((char *));
103 int pwd __P((char *));
104 int echo __P((char *));
105 int xit __P((char *));
106 int set __P((char *));
107 int unset __P((char *));
108 int env __P((char *));
109 int help __P((char *));
110 int sourcer __P((char *));
111 void do_command __P((int shell, char *cmdline));
112 void transition_handler __P((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.
610 if((pid=fork())==0) {
615 fd=open(_PATH_CONSOLE,O_RDWR);
623 execvp("/bin/sh",argv);
624 printf("runcom(): %s\n",strerror(errno));
627 /* Wait for child to exit */
628 while(pid!=waitpid(pid,(int *)0,0)) continue;
632 /* Alternative /etc/rc - default is /etc/oinit.rc. Its format is as follows:
633 * - each empty line or line beginning with a '#' is discarded
634 * - any other line must contain a keyword, or a (nonblocking) command to run.
636 * Thus far, the following keywords are defined:
637 * ncons <number> number of virtual consoles to open
638 * motd <pathname> full path to motd file
640 * Examples of commands to run:
642 * ifconfig lo0 inet 127.0.0.1 netmask 255.0.0.0
643 * ifconfig ed0 inet 148.81.168.10 netmask 255.255.255.0
644 * kbdcontrol -l /usr/share/syscons/my_map.kbd
654 fd=open(_PATH_CONSOLE,O_RDWR);
670 /* Run /etc/rc if not in single user */
672 if(prevtrans==SINGLE) runcom();
674 if(prevtrans==SINGLE) runcom(OINIT_RC);
676 if(transition!=MULTI) return(-1);
678 syslog(LOG_EMERG,"*** Starting multi-user mode ***");
680 /* Fork shell interface for each console */
681 for(i=0;i<ncons;i++) {
685 start_session(i,0,NULL);
688 printf("%s: %s\n",progname,strerror(errno));
696 /* Initialize any other services we'll use - most probably this will
697 * be a 'telnet' service (some day...).
701 /* Emulate multi-user */
702 while(transition==MULTI) {
703 /* XXX Modify this to allow for checking for the input on
704 * XXX listening sockets, and forking a 'telnet' service.
708 /* Wait for any process to exit */
709 pid=waitpid(-1,(int *)0,0);
710 if(pid==-1) continue;
713 /* search if it's one of our sessions */
714 for(i=0;i<ncons;i++) {
715 if(ttys[i].pid==pid) {
723 /* Just collect the process's status */
726 /* restart shell() on a console, if it died */
727 if(transition!=MULTI) return(0);
731 start_session(j,0,NULL);
734 printf("%s: %s\n",progname,strerror(errno));
757 * Start a shell on ttyv0 (i.e. the console).
765 static int sigs[2]={SIGTERM,SIGKILL};
767 syslog(LOG_EMERG,"*** Starting single-user mode ***");
768 /* Kill all existing sessions */
769 syslog(LOG_EMERG,"Killing all existing sessions...");
770 for(i=0;i<MAX_CONS;i++) {
771 kill(ttys[i].pid,SIGHUP);
775 if(kill(-1,sigs[i])==-1 && errno==ESRCH) break;
779 pid=waitpid(-1,(int *)0,WUNTRACED);
780 if(errno==EINTR) continue;
785 syslog(LOG_EMERG,"Some processes would not die; ps -axl advised");
790 start_session(0,0,NULL);
793 printf("%s: %s\n",progname,strerror(errno));
794 printf("The system is seriously hosed. I'm dying...\n");
800 wpid=waitpid(pid,(int *)0,WUNTRACED);
801 } while(wpid!=pid && transition==SINGLE);
802 if(transition!=DEATH) {
803 prevtrans=transition;
812 * Transition handler - installed as signal handler.
816 transition_handler(int sig)
822 prevtrans=transition;
824 syslog(LOG_EMERG,"*** Going from %s -> %s\n",trans[prevtrans],trans[transition]);
825 if(prevtrans!=transition) longjmp(machine,sig);
829 prevtrans=transition;
831 syslog(LOG_EMERG,"*** Going from %s -> %s\n",trans[prevtrans],trans[transition]);
832 if(prevtrans!=transition) longjmp(machine,sig);
835 syslog(LOG_EMERG,"pid=%d sig=%s (ignored)\n",getpid(),sys_siglist[sig]);
841 * Change system state appropriately to the signals
849 while(transition!=DEATH) {
859 syslog(LOG_EMERG,"Killing all existing sessions...");
860 /* Kill all sessions */
862 /* Be nice and wait for them */
863 while(waitpid(-1,(int *)0,WNOHANG|WUNTRACED)>0) continue;
870 main(int argc, char **argv)
874 /* These are copied from real init(8) */
876 errx(1,"%s",strerror(EPERM));
877 openlog("init",LOG_CONS|LOG_ODELAY,LOG_AUTH);
879 warn("initial setsid() failed");
880 if(setlogin("root")<0)
881 warn("setlogin() failed");
888 progname=rindex(argv[0],'/');
895 /* We must recognize the same options as real init does */
896 while((c=getopt(argc,argv,"dsf"))!=-1) {
907 printf("%s: unrecognized flag '-%c'\n",progname,c);
912 mount("devfs","/dev",MNT_NOEXEC|MNT_RDONLY,0);
914 /* Fill in the sess structures. */
915 /* XXX Really, should be filled based upon config file. */
916 for(i=0;i<MAX_CONS;i++) {
918 sprintf(ttys[i].tty,"/dev/console");
920 sprintf(ttys[i].tty,"/dev/ttyv%c",vty[i]);
928 signal(SIGINT,transition_handler);
929 signal(SIGQUIT,transition_handler);
930 signal(SIGTERM,transition_handler);
931 signal(SIGHUP,transition_handler);
932 signal(SIGALRM,kill_timer);
935 transition_machine(transition);