• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* init.c - init program.
2  *
3  * Copyright 2012 Harvind Singh <harvindsingh1981@gmail.com>
4  * Copyright 2013 Kyungwan Han  <asura321@gmail.com>
5  *
6  * No Standard
7 
8 USE_INIT(NEWTOY(init, "", TOYFLAG_SBIN))
9 
10 config INIT
11   bool "init"
12   default n
13   help
14     usage: init
15 
16     System V style init.
17 
18     First program to run (as PID 1) when the system comes up, reading
19     /etc/inittab to determine actions.
20 */
21 
22 #include "toys.h"
23 #include <sys/reboot.h>
24 
25 struct action_list_seed {
26   struct action_list_seed *next;
27   pid_t pid;
28   uint8_t action;
29   char *terminal_name;
30   char *command;
31 } *action_list_pointer = NULL;
32 int caught_signal;
33 
34 //INITTAB action defination
35 #define SYSINIT     0x01
36 #define WAIT        0x02
37 #define ONCE        0x04
38 #define RESPAWN     0x08
39 #define ASKFIRST    0x10
40 #define CTRLALTDEL  0x20
41 #define SHUTDOWN    0x40
42 #define RESTART     0x80
43 
initialize_console(void)44 static void initialize_console(void)
45 {
46   int fd;
47   char *p = getenv("CONSOLE");
48 
49   if (!p) p = getenv("console");
50   if (!p) {
51     fd = open("/dev/null", O_RDWR);
52     if (fd >= 0) {
53       while (fd < 2) fd = dup(fd);
54       while (fd > 2) close(fd--);
55     }
56   } else {
57     fd = open(p, O_RDWR | O_NONBLOCK | O_NOCTTY);
58     if (fd < 0) printf("Unable to open console %s\n",p);
59     else {
60       dup2(fd,0);
61       dup2(fd,1);
62       dup2(fd,2);
63     }
64   }
65 
66   if (!getenv("TERM")) putenv("TERM=linux");
67 }
68 
reset_term(int fd)69 static void reset_term(int fd)
70 {
71   struct termios terminal;
72 
73   tcgetattr(fd, &terminal);
74   terminal.c_cc[VINTR] = 3;    //ctrl-c
75   terminal.c_cc[VQUIT] = 28;   /*ctrl-\*/
76   terminal.c_cc[VERASE] = 127; //ctrl-?
77   terminal.c_cc[VKILL] = 21;   //ctrl-u
78   terminal.c_cc[VEOF] = 4;     //ctrl-d
79   terminal.c_cc[VSTART] = 17;  //ctrl-q
80   terminal.c_cc[VSTOP] = 19;   //ctrl-s
81   terminal.c_cc[VSUSP] = 26;   //ctrl-z
82 
83   terminal.c_line = 0;
84   terminal.c_cflag &= CRTSCTS|PARODD|PARENB|CSTOPB|CSIZE|CBAUDEX|CBAUD;
85   terminal.c_cflag |= CLOCAL|HUPCL|CREAD;
86 
87   //enable start/stop input and output control + map CR to NL on input
88   terminal.c_iflag = IXON|IXOFF|ICRNL;
89 
90   //Map NL to CR-NL on output
91   terminal.c_oflag = ONLCR|OPOST;
92   terminal.c_lflag = IEXTEN|ECHOKE|ECHOCTL|ECHOK|ECHOE|ECHO|ICANON|ISIG;
93   tcsetattr(fd, TCSANOW, &terminal);
94 }
95 
add_new_action(uint8_t action,char * command,char * term)96 static void add_new_action(uint8_t action,char *command,char *term)
97 {
98   struct action_list_seed *x,**y;
99 
100   y = &action_list_pointer;
101   x = *y;
102   while (x) {
103     if (!(strcmp(x->command, command)) && !(strcmp(x->terminal_name, term))) {
104       *y = x->next; //remove from the list
105       while(*y) y = &(*y)->next; //traverse through list till end
106       x->next = NULL;
107       break;
108     }
109     y = &(x)->next;
110     x = *y;
111   }
112 
113   //create a new node
114   if (!x) {
115     x = xzalloc(sizeof(*x));
116     x->command = xstrdup(command);
117     x->terminal_name = xstrdup(term);
118   }
119   x->action = action;
120   *y = x;
121 }
122 
inittab_parsing(void)123 static void inittab_parsing(void)
124 {
125   int i, fd, line_number = 0, token_count = 0;
126   char *p, *q, *extracted_token, *tty_name = NULL, *command = NULL, *tmp;
127   uint8_t action = 0;
128   char *act_name = "sysinit\0wait\0once\0respawn\0askfirst\0ctrlaltdel\0"
129                     "shutdown\0restart\0";
130 
131   fd = open("/etc/inittab", O_RDONLY);
132   if (fd < 0) {
133     error_msg("Unable to open /etc/inittab. Using Default inittab");
134     add_new_action(SYSINIT, "/etc/init.d/rcS", "");
135     add_new_action(RESPAWN, "/sbin/getty -n -l /bin/sh -L 115200 tty1 vt100", "");
136   } else {
137     while((q = p = get_line(fd))) { //read single line from /etc/inittab
138       char *x;
139 
140       if ((x = strchr(p, '#'))) *x = '\0';
141       line_number++;
142       token_count = 0;
143       action = 0;
144       tty_name = command = NULL;
145 
146       while ((extracted_token = strsep(&p,":"))) {
147         token_count++;
148         switch (token_count) {
149           case 1:
150             if (*extracted_token) {
151               if (!strncmp(extracted_token, "/dev/", 5))
152                 tty_name = xmprintf("%s",extracted_token);
153               else tty_name = xmprintf("/dev/%s",extracted_token);
154             } else tty_name = xstrdup("");
155             break;
156           case 2:
157             break;
158           case 3:
159             for (tmp = act_name, i = 0; *tmp; i++, tmp += strlen(tmp) +1) {
160               if (!strcmp(tmp, extracted_token)) {
161                 action = 1 << i;
162                 break;
163               }
164             }
165             if (!*tmp) error_msg("Invalid action at line number %d ---- ignoring",line_number);
166             break;
167           case 4:
168             command = xstrdup(extracted_token);
169             break;
170           default:
171             error_msg("Bad inittab entry at line %d", line_number);
172             break;
173         }
174       }  //while token
175 
176       if (q) free(q);
177       if (token_count != 4) {
178         free(tty_name);
179         free(command);
180         continue;
181       }
182       if (action) add_new_action(action, command, tty_name);
183       free(tty_name);
184       free(command);
185     } //while line
186 
187     close(fd);
188   }
189 }
190 
reload_inittab(void)191 static void reload_inittab(void)
192 {
193   // Remove all inactive actions, then reload /etc/inittab
194   struct action_list_seed **y;
195   y = &action_list_pointer;
196   while (*y) {
197     if (!(*y)->pid) {
198       struct action_list_seed *x = *y;
199       free(x->terminal_name);
200       free(x->command);
201       *y = (*y)->next;
202       free(x);
203       continue;
204     }
205     y = &(*y)->next;
206   }
207   inittab_parsing();
208 }
209 
run_command(char * command)210 static void run_command(char *command)
211 {
212   char *final_command[128];
213   int hyphen = (command[0]=='-');
214 
215   command = command + hyphen;
216   if (!strpbrk(command, "?<>'\";[]{}\\|=()*&^$!`~")) {
217     char *next_command;
218     char *extracted_command;
219     int x = 0;
220 
221     next_command = strncpy(toybuf, command - hyphen, sizeof(toybuf));
222     next_command[sizeof(toybuf) - 1] = toybuf[sizeof(toybuf) - 1 ] = '\0';
223     command = next_command + hyphen;
224     while ((extracted_command = strsep(&next_command," \t"))) {
225       if (*extracted_command) {
226         final_command[x] = extracted_command;
227         x++;
228       }
229     }
230     final_command[x] = NULL;
231   } else {
232     snprintf(toybuf, sizeof(toybuf), "exec %s", command);
233     command = "-/bin/sh"+1;
234     final_command[0] = ("-/bin/sh"+!hyphen);
235     final_command[1] = "-c";
236     final_command[2] = toybuf;
237     final_command[3] = NULL;
238   }
239   if (hyphen) ioctl(0, TIOCSCTTY, 0);
240   execvp(command, final_command);
241   error_msg("unable to run %s",command);
242 }
243 
244 //runs all same type of actions
final_run(struct action_list_seed * x)245 static pid_t final_run(struct action_list_seed *x)
246 {
247   pid_t pid;
248   int fd;
249   sigset_t signal_set;
250 
251   sigfillset(&signal_set);
252   sigprocmask(SIG_BLOCK, &signal_set, NULL);
253   if (x->action & ASKFIRST) pid = fork();
254   else pid = vfork();
255 
256   if (pid > 0) {
257     //parent process or error
258     //unblock the signals
259     sigfillset(&signal_set);
260     sigprocmask(SIG_UNBLOCK, &signal_set, NULL);
261 
262     return pid;
263   } else if (pid < 0) {
264     perror_msg("fork fail");
265     sleep(1);
266     return 0;
267   }
268 
269   //new born child process
270   sigset_t signal_set_c;
271   sigfillset(&signal_set_c);
272   sigprocmask(SIG_UNBLOCK, &signal_set_c, NULL);
273   setsid(); //new session
274 
275   if (x->terminal_name[0]) {
276     close(0);
277     fd = open(x->terminal_name, (O_RDWR|O_NONBLOCK),0600);
278     if (fd != 0) {
279       error_msg("Unable to open %s,%s\n", x->terminal_name, strerror(errno));
280       _exit(EXIT_FAILURE);
281     } else {
282       dup2(0, 1);
283       dup2(0, 2);
284     }
285   }
286   reset_term(0);
287   run_command(x->command);
288   _exit(-1);
289 }
290 
mark_as_terminated_process(pid_t pid)291 static struct action_list_seed* mark_as_terminated_process(pid_t pid)
292 {
293   struct action_list_seed *x;
294 
295   if (pid > 0) {
296     for (x = action_list_pointer; x; x = x->next) {
297       if (x->pid == pid) {
298         x->pid = 0;
299         return x;
300       }
301     }
302   }
303 
304   return NULL;
305 }
306 
waitforpid(pid_t pid)307 static void waitforpid(pid_t pid)
308 {
309   if (pid <= 0) return;
310 
311   while (!kill(pid, 0)) mark_as_terminated_process(wait(NULL));
312 }
313 
run_action_from_list(int action)314 static void run_action_from_list(int action)
315 {
316   pid_t pid;
317   struct action_list_seed *x = action_list_pointer;
318 
319   for (; x; x = x->next) {
320     if (!(x->action & action)) continue;
321     if (x->action & (SHUTDOWN|ONCE|SYSINIT|CTRLALTDEL|WAIT)) {
322       pid = final_run(x);
323       if (!pid) return;
324       if (x->action & (SHUTDOWN|SYSINIT|CTRLALTDEL|WAIT)) waitforpid(pid);
325     }
326     if (x->action & (ASKFIRST|RESPAWN))
327       if (!(x->pid)) x->pid = final_run(x);
328   }
329  }
330 
set_default(void)331 static void set_default(void)
332 {
333   sigset_t signal_set_c;
334 
335   sigatexit(SIG_DFL);
336   sigfillset(&signal_set_c);
337   sigprocmask(SIG_UNBLOCK,&signal_set_c, NULL);
338 
339   run_action_from_list(SHUTDOWN);
340   error_msg("The system is going down NOW!");
341   kill(-1, SIGTERM);
342   error_msg("Sent SIGTERM to all processes");
343   sync();
344   sleep(1);
345   kill(-1,SIGKILL);
346   sync();
347 }
348 
halt_poweroff_reboot_handler(int sig_no)349 static void halt_poweroff_reboot_handler(int sig_no)
350 {
351   unsigned int reboot_magic_no = 0;
352   pid_t pid;
353 
354   set_default();
355 
356   switch (sig_no) {
357     case SIGUSR1:
358       error_msg("Requesting system halt");
359       reboot_magic_no=RB_HALT_SYSTEM;
360       break;
361     case SIGUSR2:
362       error_msg("Requesting system poweroff");
363       reboot_magic_no=RB_POWER_OFF;
364       break;
365     case SIGTERM:
366       error_msg("Requesting system reboot");
367       reboot_magic_no=RB_AUTOBOOT;
368       break;
369     default:
370       break;
371   }
372 
373   sleep(1);
374   pid = vfork();
375 
376   if (pid == 0) {
377     reboot(reboot_magic_no);
378     _exit(EXIT_SUCCESS);
379   }
380 
381   while(1) sleep(1);
382 }
383 
restart_init_handler(int sig_no)384 static void restart_init_handler(int sig_no)
385 {
386   struct action_list_seed *x;
387   pid_t pid;
388   int fd;
389 
390   for (x = action_list_pointer; x; x = x->next) {
391     if (!(x->action & RESTART)) continue;
392 
393     set_default();
394 
395     if (x->terminal_name[0]) {
396       close(0);
397       fd = open(x->terminal_name, (O_RDWR|O_NONBLOCK),0600);
398 
399       if (fd != 0) {
400         error_msg("Unable to open %s,%s\n", x->terminal_name, strerror(errno));
401         sleep(1);
402         pid = vfork();
403 
404         if (pid == 0) {
405           reboot(RB_HALT_SYSTEM);
406           _exit(EXIT_SUCCESS);
407         }
408 
409         while(1) sleep(1);
410       } else {
411         dup2(0, 1);
412         dup2(0, 2);
413         reset_term(0);
414         run_command(x->command);
415       }
416     }
417   }
418 }
419 
catch_signal(int sig_no)420 static void catch_signal(int sig_no)
421 {
422   caught_signal = sig_no;
423   error_msg("signal seen: %d", sig_no);
424 }
425 
pause_handler(int sig_no)426 static void pause_handler(int sig_no)
427 {
428   int signal_backup,errno_backup;
429   pid_t pid;
430 
431   errno_backup = errno;
432   signal_backup = caught_signal;
433   xsignal(SIGCONT, catch_signal);
434 
435   while(1) {
436     if (caught_signal == SIGCONT) break;
437     do pid = waitpid(-1,NULL,WNOHANG); while((pid==-1) && (errno=EINTR));
438     mark_as_terminated_process(pid);
439     sleep(1);
440   }
441 
442   signal(SIGCONT, SIG_DFL);
443   errno = errno_backup;
444   caught_signal = signal_backup;
445 }
446 
check_if_pending_signals(void)447 static int check_if_pending_signals(void)
448 {
449   int signal_caught = 0;
450 
451   while(1) {
452     int sig = caught_signal;
453     if (!sig) return signal_caught;
454     caught_signal = 0;
455     signal_caught = 1;
456     if (sig == SIGINT) run_action_from_list(CTRLALTDEL);
457     else if (sig == SIGHUP) {
458       error_msg("reloading inittab");
459       reload_inittab();
460     }
461   }
462 }
463 
init_main(void)464 void init_main(void)
465 {
466   struct sigaction sig_act;
467 
468   if (getpid() != 1) error_exit("Already running");
469   printf("Started init\n");
470   initialize_console();
471   reset_term(0);
472 
473   if (chdir("/")) perror_exit("Can't cd to /");
474   setsid();
475 
476   putenv("HOME=/");
477   putenv("PATH=/sbin:/usr/sbin:/bin:/usr/bin");
478   putenv("SHELL=/bin/sh");
479   putenv("USER=root");
480 
481   inittab_parsing();
482   xsignal(SIGUSR1, halt_poweroff_reboot_handler);//halt
483   xsignal(SIGUSR2, halt_poweroff_reboot_handler);//poweroff
484   xsignal(SIGTERM, halt_poweroff_reboot_handler);//reboot
485   xsignal(SIGQUIT, restart_init_handler);//restart init
486   memset(&sig_act, 0, sizeof(sig_act));
487   sigfillset(&sig_act.sa_mask);
488   sigdelset(&sig_act.sa_mask, SIGCONT);
489   sig_act.sa_handler = pause_handler;
490   sigaction(SIGTSTP, &sig_act, NULL);
491   memset(&sig_act, 0, sizeof(sig_act));
492   sig_act.sa_handler = catch_signal;
493   sigaction(SIGINT, &sig_act, NULL);
494   sigaction(SIGHUP, &sig_act, NULL);
495   run_action_from_list(SYSINIT);
496   check_if_pending_signals();
497   run_action_from_list(WAIT);
498   check_if_pending_signals();
499   run_action_from_list(ONCE);
500   while (1) {
501     int suspected_WNOHANG = check_if_pending_signals();
502 
503     run_action_from_list(RESPAWN | ASKFIRST);
504     suspected_WNOHANG = suspected_WNOHANG|check_if_pending_signals();
505     sleep(1);//let cpu breath
506     suspected_WNOHANG = suspected_WNOHANG|check_if_pending_signals();
507     if (suspected_WNOHANG) suspected_WNOHANG=WNOHANG;
508 
509     while(1) {
510       pid_t pid = waitpid(-1, NULL, suspected_WNOHANG);
511 
512       if (pid <= 0) break;
513       mark_as_terminated_process(pid);
514       suspected_WNOHANG = WNOHANG;
515     }
516   }
517 }
518