aboutsummaryrefslogtreecommitdiff
path: root/sinit.c
blob: c2552050f14e01739d1f09165339dee9c7f290be (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
116
117
/* See LICENSE file for copyright and license details. */

#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "util.h"

typedef union {
        const void *v;
} Arg;

typedef struct {
        const char *name;
        void (*func)(const Arg *arg);
        const Arg arg;
} Command;

static void dispatchcmd(int);
static void spawn(const Arg *);

#include "config.h"

int
main(void)
{
	sigset_t set;
	pid_t pid;
	fd_set rfds;
	int c, fd, n;

	if (getpid() != 1)
		return EXIT_FAILURE;

	sigfillset(&set);
	sigprocmask(SIG_BLOCK, &set, 0);

	pid = fork();
	if (pid < 0)
		return EXIT_FAILURE;
	if (pid > 0)
		for (;;)
			wait(&c);

	sigprocmask(SIG_UNBLOCK, &set, 0);

	spawn(&rcinitarg);

	unlink(fifopath);
	umask(0);
	if (mkfifo(fifopath, 0600) < 0)
		weprintf("sinit: mkfifo %s:");

	fd = open(fifopath, O_RDWR | O_NONBLOCK);
	if (fd < 0)
		weprintf("sinit: open %s:", fifopath);
	if (fd >= 0) {
		while (1) {
			FD_ZERO(&rfds);
			FD_SET(fd, &rfds);
			n = select(fd + 1, &rfds, NULL, NULL, NULL);
			if (n < 0)
				eprintf("sinit: select:");
			if (FD_ISSET(fd, &rfds))
				dispatchcmd(fd);
		}
	}

	return EXIT_SUCCESS;
}

static void
dispatchcmd(int fd)
{
	int i;
	char buf[BUFSIZ], *p;
	ssize_t n;

	n = read(fd, buf, sizeof(buf) - 1);
	if (n < 0)
		weprintf("sinit: read:");
	buf[n] = '\0';
	p = strchr(buf, '\n');
	if (p)
		*p = '\0';
	for (i = 0; i < LEN(commands); i++) {
		if (strcmp(commands[i].name, buf) == 0) {
			commands[i].func(&commands[i].arg);
			break;
		}
	}
}

static void
spawn(const Arg *arg)
{
	pid_t pid;
	const char *p = arg->v;

	pid = fork();
	if (pid < 0)
		weprintf("sinit: fork:");
	if (pid == 0) {
		setsid();
		setpgid(0, 0);
		execvp(p, arg->v);
		weprintf("sinit: execvp %s:", p);
		_exit(errno == ENOENT ? 127 : 126);
	}
}