forked from darkk/redsocks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
126 lines (105 loc) · 2.55 KB
/
main.c
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
#include <sys/time.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <assert.h>
#include <event.h>
#include "log.h"
#include "main.h"
#include "utils.h"
extern app_subsys redsocks_subsys;
extern app_subsys base_subsys;
// extern app_subsys reddns_subsys;
app_subsys *subsystems[] = {
&redsocks_subsys,
&base_subsys,
// &reddns_subsys,
};
static const char *confname = "redsocks.conf";
static void terminate(int sig, short what, void *_arg)
{
if (event_loopbreak() != 0)
log_error(LOG_WARNING, "event_loopbreak");
}
int main(int argc, char **argv)
{
int error;
app_subsys **ss;
int exit_signals[2] = {SIGTERM, SIGINT};
struct event terminators[2];
bool conftest = false;
int opt;
int i;
while ((opt = getopt(argc, argv, "tc:")) != -1) {
switch (opt) {
case 't':
conftest = true;
break;
case 'c':
confname = optarg;
break;
default:
printf(
"Usage: %s [-t] [-c config]\n"
" -t test config syntax\n",
argv[0]);
return EXIT_FAILURE;
}
}
FILE *f = fopen(confname, "r");
if (!f) {
perror("Unable to open config file");
return EXIT_FAILURE;
}
parser_context* parser = parser_start(f, NULL);
if (!parser) {
perror("Not enough memory for parser");
return EXIT_FAILURE;
}
FOREACH(ss, subsystems)
if ((*ss)->conf_section)
parser_add_section(parser, (*ss)->conf_section);
error = parser_run(parser);
parser_stop(parser);
fclose(f);
if (error)
return EXIT_FAILURE;
if (conftest)
return EXIT_SUCCESS;
event_init();
FOREACH(ss, subsystems) {
if ((*ss)->init) {
error = (*ss)->init();
if (error)
goto shutdown;
}
}
assert(SIZEOF_ARRAY(exit_signals) == SIZEOF_ARRAY(terminators));
memset(terminators, 0, sizeof(terminators));
for (i = 0; i < SIZEOF_ARRAY(exit_signals); i++) {
signal_set(&terminators[i], exit_signals[i], terminate, NULL);
if (signal_add(&terminators[i], NULL) != 0) {
log_errno(LOG_ERR, "signal_add");
goto shutdown;
}
}
log_error(LOG_NOTICE, "redsocks started");
event_dispatch();
shutdown:
for (i = 0; i < SIZEOF_ARRAY(exit_signals); i++) {
if (signal_initialized(&terminators[i])) {
if (signal_del(&terminators[i]) != 0)
log_errno(LOG_WARNING, "signal_del");
memset(&terminators[i], 0, sizeof(terminators[i]));
}
}
for (--ss; ss >= subsystems; ss--)
if ((*ss)->fini)
(*ss)->fini();
event_base_free(NULL);
return !error ? EXIT_SUCCESS : EXIT_FAILURE;
}
/* vim:set tabstop=4 softtabstop=4 shiftwidth=4: */
/* vim:set foldmethod=marker foldlevel=32 foldmarker={,}: */