aboutsummaryrefslogtreecommitdiff
path: root/user/sbin/init.c
blob: 6bfe6aec806b7498a9f1875d2f2be50d27af1422 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/*
 * Forks a shell for each terminal and waits for them.
 * This is the final thing you should be executing
 * (with kernel_execve) in kernel-land once everything works.
 */

#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>

char *empty[] = {NULL};

const char *hi = "init: starting shell on ";
const char *sh = "/bin/sh";
const char *ttystr = "tty";
const char *home = "/";
const char *alldone = "init: no remaining processes\n";

static int open_tty(char *tty)
{
    if (-1 == open(tty, O_RDONLY, 0))
    {
        return -1;
    }
    else if (-1 == open(tty, O_WRONLY, 0))
    {
        return -1;
    }
    else if (2 != dup(1))
    {
        return -1;
    }
    else
    {
        return 0;
    }
}

static int canary = 0x12345678;

static void spawn_shell_on(char *tty)
{
    if (!fork())
    {
        close(0);
        close(1);
        close(2);
        if (-1 == open_tty(tty))
        {
            exit(1);
        }

        chdir(home);

        printf("%s%s\n", hi, tty);

        execve(sh, empty, empty);
        fprintf(stderr, "exec failed!\n");
    }
}

int main(int argc, char **argv, char **envp)
{
    int devdir, ii;
    dirent_t d;
    int status;

    for (ii = 0; ii < NFILES; ii++)
    {
        close(ii);
    }
    ii = ii;

    if (-1 == open_tty("/dev/tty0"))
    {
        exit(1);
    }

    chdir("/dev");

    devdir = open("/dev", O_RDONLY, 0);
    while (getdents(devdir, &d, sizeof(d)) > 0)
    {
        if (0 == strncmp(d.d_name, ttystr, strlen(ttystr)))
        {
            spawn_shell_on(d.d_name);
        }
    }
    close(devdir);

    int pid;
    while (0 <= (pid = wait(&status)))
    {
        if (EFAULT == status)
        {
            printf("process %i faulted\n", pid);
        }
    }

    if (ECHILD != errno)
    {
        printf("error: wait: %s\n", strerror(errno));
        return 1;
    }
    else
    {
        printf("%s", alldone);
        return 0;
    }
}