aboutsummaryrefslogtreecommitdiff
path: root/initd/main.c
blob: d92a823037d12a0d66ee552a04609eb11cb1c449 (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
118
119
120
121
122
123
124
125
126
127
128
/* SPDX-License-Identifier: ISC */
#include "init.h"

static void respawn(svc_run_data_t *rt)
{
	if (rt->svc->rspwn_limit > 0) {
		rt->rspwn_count += 1;

		if (rt->rspwn_count >= rt->svc->rspwn_limit)
			goto fail;
	}

	rt->pid = runsvc(rt->svc);
	if (rt->pid == -1)
		goto fail;

	rt->state = STATE_RUNNING;
	return;
fail:
	rt->state = STATE_FAILED;
	print_status(rt);
	return;
}

static void handle_exited(svc_run_data_t *rt)
{
	if (rt->svc->type == SVC_RESPAWN) {
		if (config_should_respawn())
			respawn(rt);
	} else {
		if (rt->status == EXIT_SUCCESS) {
			rt->state = STATE_COMPLETED;
		} else {
			rt->state = STATE_FAILED;
		}

		print_status(rt);
	}
}

static void start_service(svc_run_data_t *rt)
{
	if (rt->svc->flags & SVC_FLAG_HAS_EXEC) {
		rt->pid = runsvc(rt->svc);
		if (rt->pid == -1) {
			rt->state = STATE_FAILED;
		} else {
			rt->state = STATE_RUNNING;

			if (rt->svc->type == SVC_WAIT)
				config_set_waiting(rt);
		}
	} else {
		rt->status = EXIT_SUCCESS;
		rt->state = STATE_COMPLETED;
	}

	print_status(rt);
}

static void handle_signal(int signo)
{
	svc_run_data_t *rt;
	int status;
	pid_t pid;

	switch (signo) {
	case SIGTERM:
		config_set_target(TGT_SHUTDOWN);
		break;
	case SIGINT:
		config_set_target(TGT_REBOOT);
		break;
	case SIGCHLD:
		while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
			rt = config_rt_data_by_pid(pid);
			if (rt == NULL)
				continue;

			if (WIFEXITED(status)) {
				rt->status = WEXITSTATUS(status);
			} else {
				rt->status = EXIT_FAILURE;
			}

			rt->pid = -1;
			handle_exited(rt);
		}
		break;
	case SIGHUP:
		break;
	case SIGUSR1:
		break;
	}
}

int main(void)
{
	svc_run_data_t *rt;
	struct sigaction act;

	if (config_load())
		return EXIT_FAILURE;

	memset(&act, 0, sizeof(act));
	act.sa_handler = handle_signal;

	sigaction(SIGTERM, &act, NULL);
	sigaction(SIGINT, &act, NULL);
	sigaction(SIGHUP, &act, NULL);
	sigaction(SIGUSR1, &act, NULL);
	sigaction(SIGCHLD, &act, NULL);

	if (reboot(LINUX_REBOOT_CMD_CAD_OFF))
		perror("cannot disable CTRL+ALT+DEL");

	for (;;) {
		rt = config_dequeue();

		if (rt == NULL) {
			pause();
		} else {
			start_service(rt);
		}
	}

	return EXIT_SUCCESS;
}