]> git.sesse.net Git - cubemap/blob - config.cpp
Merge branch 'master' of /srv/git.sesse.net/www/cubemap
[cubemap] / config.cpp
1 #include <assert.h>
2 #include <ctype.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <map>
7 #include <string>
8 #include <utility>
9 #include <vector>
10
11 #include "config.h"
12 #include "log.h"
13 #include "parse.h"
14
15 using namespace std;
16
17 #define DEFAULT_BACKLOG_SIZE 1048576
18
19 struct ConfigLine {
20         string keyword;
21         vector<string> arguments;
22         map<string, string> parameters;
23 };
24
25 bool read_config(const string &filename, vector<ConfigLine> *lines)
26 {
27         FILE *fp = fopen(filename.c_str(), "r");
28         if (fp == NULL) {
29                 log_perror(filename.c_str());
30                 return false;
31         }
32
33         char buf[4096];
34         while (!feof(fp)) {
35                 if (fgets(buf, sizeof(buf), fp) == NULL) {
36                         break;
37                 }
38
39                 // Chop off the string at the first #, \r or \n.
40                 buf[strcspn(buf, "#\r\n")] = 0;
41
42                 // Remove all whitespace from the end of the string.
43                 size_t len = strlen(buf);
44                 while (len > 0 && isspace(buf[len - 1])) {
45                         buf[--len] = 0;
46                 }
47
48                 // If the line is now all blank, ignore it.
49                 if (len == 0) {
50                         continue;
51                 }
52
53                 vector<string> tokens = split_tokens(buf);
54                 assert(!tokens.empty());
55                 
56                 ConfigLine line;
57                 line.keyword = tokens[0];
58
59                 for (size_t i = 1; i < tokens.size(); ++i) {
60                         // foo=bar is a parameter; anything else is an argument.
61                         size_t equals_pos = tokens[i].find_first_of('=');
62                         if (equals_pos == string::npos) {
63                                 line.arguments.push_back(tokens[i]);
64                         } else {
65                                 string key = tokens[i].substr(0, equals_pos);
66                                 string value = tokens[i].substr(equals_pos + 1, string::npos);
67                                 line.parameters.insert(make_pair(key, value));
68                         }
69                 }
70
71                 lines->push_back(line);
72         }
73
74         fclose(fp);
75         return true;
76 }
77
78 bool fetch_config_string(const vector<ConfigLine> &config, const string &keyword, string *value)
79 {
80         for (unsigned i = 0; i < config.size(); ++i) {
81                 if (config[i].keyword != keyword) {
82                         continue;
83                 }
84                 if (config[i].parameters.size() > 0 ||
85                     config[i].arguments.size() != 1) {
86                         log(ERROR, "'%s' takes one argument and no parameters", keyword.c_str());
87                         return false;
88                 }
89                 *value = config[i].arguments[0];
90                 return true;
91         }
92         return false;
93 }
94
95 bool fetch_config_int(const vector<ConfigLine> &config, const string &keyword, int *value)
96 {
97         for (unsigned i = 0; i < config.size(); ++i) {
98                 if (config[i].keyword != keyword) {
99                         continue;
100                 }
101                 if (config[i].parameters.size() > 0 ||
102                     config[i].arguments.size() != 1) {
103                         log(ERROR, "'%s' takes one argument and no parameters", keyword.c_str());
104                         return false;
105                 }
106                 *value = atoi(config[i].arguments[0].c_str());  // TODO: verify int validity.
107                 return true;
108         }
109         return false;
110 }
111
112 bool parse_port(const ConfigLine &line, Config *config)
113 {
114         if (line.arguments.size() != 1) {
115                 log(ERROR, "'port' takes exactly one argument");
116                 return false;
117         }
118
119         AcceptorConfig acceptor;
120         acceptor.port = atoi(line.arguments[0].c_str());
121         if (acceptor.port < 1 || acceptor.port >= 65536) {
122                 log(ERROR, "port %d is out of range (must be [1,65536>).", acceptor.port);
123                 return false;
124         }
125
126         config->acceptors.push_back(acceptor);
127         return true;
128 }
129
130 int allocate_mark_pool(int from, int to, Config *config)
131 {
132         int pool_index = -1;    
133
134         // Reuse mark pools if an identical one exists.
135         // Otherwise, check if we're overlapping some other mark pool.
136         for (size_t i = 0; i < config->mark_pools.size(); ++i) {
137                 const MarkPoolConfig &pool = config->mark_pools[i];
138                 if (from == pool.from && to == pool.to) {
139                         pool_index = i;
140                 } else if ((from >= pool.from && from < pool.to) ||
141                            (to >= pool.from && to < pool.to)) {
142                         log(WARNING, "Mark pool %d-%d partially overlaps with %d-%d, you may get duplicate marks."
143                                      "Mark pools must either be completely disjunct, or completely overlapping.",
144                                      from, to, pool.from, pool.to);
145                 }
146         }
147
148         if (pool_index != -1) {
149                 return pool_index;
150         }
151
152         // No match to existing pools.
153         MarkPoolConfig pool;
154         pool.from = from;
155         pool.to = to;
156         config->mark_pools.push_back(pool);
157
158         return config->mark_pools.size() - 1;
159 }
160
161 bool parse_mark_pool(const string &mark_str, int *from, int *to)
162 {
163         size_t split = mark_str.find_first_of('-');
164         if (split == string::npos) {
165                 log(ERROR, "Invalid mark specification '%s' (expected 'X-Y').",
166                         mark_str.c_str());
167                 return false;
168         }
169
170         string from_str(mark_str.begin(), mark_str.begin() + split);
171         string to_str(mark_str.begin() + split + 1, mark_str.end());
172         *from = atoi(from_str.c_str());
173         *to = atoi(to_str.c_str());
174
175         if (*from <= 0 || *from >= 65536 || *to <= 0 || *to >= 65536) {
176                 log(ERROR, "Mark pool range %d-%d is outside legal range [1,65536>.",
177                         *from, *to);
178                 return false;
179         }
180
181         return true;
182 }
183
184 bool parse_stream(const ConfigLine &line, Config *config)
185 {
186         if (line.arguments.size() != 1) {
187                 log(ERROR, "'stream' takes exactly one argument");
188                 return false;
189         }
190
191         StreamConfig stream;
192         stream.url = line.arguments[0];
193
194         map<string, string>::const_iterator src_it = line.parameters.find("src");
195         if (src_it == line.parameters.end()) {
196                 log(WARNING, "stream '%s' has no src= attribute, clients will not get any data.",
197                         stream.url.c_str());
198         } else {
199                 stream.src = src_it->second;
200                 // TODO: Verify that the URL is parseable?
201         }
202
203         map<string, string>::const_iterator backlog_it = line.parameters.find("backlog_size");
204         if (backlog_it == line.parameters.end()) {
205                 stream.backlog_size = DEFAULT_BACKLOG_SIZE;
206         } else {
207                 stream.backlog_size = atoi(backlog_it->second.c_str());
208         }
209
210         // Parse encoding.
211         map<string, string>::const_iterator encoding_parm_it = line.parameters.find("encoding");
212         if (encoding_parm_it == line.parameters.end() ||
213             encoding_parm_it->second == "raw") {
214                 stream.encoding = StreamConfig::STREAM_ENCODING_RAW;
215         } else if (encoding_parm_it->second == "metacube") {
216                 stream.encoding = StreamConfig::STREAM_ENCODING_METACUBE;
217         } else {
218                 log(ERROR, "Parameter 'encoding' must be either 'raw' (default) or 'metacube'");
219                 return false;
220         }
221
222         // Parse marks, if so desired.
223         map<string, string>::const_iterator mark_parm_it = line.parameters.find("mark");
224         if (mark_parm_it == line.parameters.end()) {
225                 stream.mark_pool = -1;
226         } else {
227                 int from, to;
228                 if (!parse_mark_pool(mark_parm_it->second, &from, &to)) {
229                         return false;
230                 }
231                 stream.mark_pool = allocate_mark_pool(from, to, config);
232         }
233
234         config->streams.push_back(stream);
235         return true;
236 }
237
238 bool parse_udpstream(const ConfigLine &line, Config *config)
239 {
240         if (line.arguments.size() != 1) {
241                 log(ERROR, "'udpstream' takes exactly one argument");
242                 return false;
243         }
244
245         UDPStreamConfig udpstream;
246
247         string hostport = line.arguments[0];
248
249         // See if the argument if on the type [ipv6addr]:port.
250         if (!hostport.empty() && hostport[0] == '[') {
251                 size_t split = hostport.find("]:");
252                 if (split == string::npos) {
253                         log(ERROR, "udpstream destination '%s' is malformed; must be either [ipv6addr]:port or ipv4addr:port");
254                         return false;
255                 }
256
257                 string host(hostport.begin() + 1, hostport.begin() + split);
258                 string port = hostport.substr(split + 2);
259
260                 udpstream.dst.sin6_family = AF_INET6;
261                 if (inet_pton(AF_INET6, host.c_str(), &udpstream.dst.sin6_addr) != 1) {
262                         log(ERROR, "udpstream destination host '%s' is not a valid IPv6 address");
263                         return false;
264                 }
265
266                 udpstream.dst.sin6_port = htons(atoi(port.c_str()));  // TODO: Verify validity.
267         } else {
268                 // OK, then it must be ipv4addr:port.
269                 size_t split = hostport.find(":");
270                 if (split == string::npos) {
271                         log(ERROR, "udpstream destination '%s' is malformed; must be either [ipv6addr]:port or ipv4addr:port");
272                         return false;
273                 }
274
275                 string host(hostport.begin(), hostport.begin() + split);
276                 string port = hostport.substr(split + 1);
277
278                 // Parse to an IPv4 address, then construct a mapped-v4 address from that.
279                 in_addr addr4;
280
281                 if (inet_pton(AF_INET, host.c_str(), &addr4) != 1) {
282                         log(ERROR, "udpstream destination host '%s' is not a valid IPv4 address");
283                         return false;
284                 }
285
286                 udpstream.dst.sin6_family = AF_INET6;
287                 udpstream.dst.sin6_addr.s6_addr32[0] = 0;
288                 udpstream.dst.sin6_addr.s6_addr32[1] = 0;
289                 udpstream.dst.sin6_addr.s6_addr32[2] = htonl(0xffff);
290                 udpstream.dst.sin6_addr.s6_addr32[3] = addr4.s_addr;
291                 udpstream.dst.sin6_port = htons(atoi(port.c_str()));  // TODO: Verify validity.
292         }
293
294         map<string, string>::const_iterator src_it = line.parameters.find("src");
295         if (src_it == line.parameters.end()) {
296                 // This is pretty meaningless, but OK, consistency is good.
297                 log(WARNING, "udpstream to %s has no src= attribute, clients will not get any data.",
298                         hostport.c_str());
299         } else {
300                 udpstream.src = src_it->second;
301                 // TODO: Verify that the URL is parseable?
302         }
303
304         // Parse marks, if so desired.
305         map<string, string>::const_iterator mark_parm_it = line.parameters.find("mark");
306         if (mark_parm_it == line.parameters.end()) {
307                 udpstream.mark_pool = -1;
308         } else {
309                 int from, to;
310                 if (!parse_mark_pool(mark_parm_it->second, &from, &to)) {
311                         return false;
312                 }
313                 udpstream.mark_pool = allocate_mark_pool(from, to, config);
314         }
315
316         config->udpstreams.push_back(udpstream);
317         return true;
318 }
319 bool parse_error_log(const ConfigLine &line, Config *config)
320 {
321         if (line.arguments.size() != 0) {
322                 log(ERROR, "'error_log' takes no arguments (only parameters type= and filename=)");
323                 return false;
324         }
325
326         LogConfig log_config;
327         map<string, string>::const_iterator type_it = line.parameters.find("type");
328         if (type_it == line.parameters.end()) {
329                 log(ERROR, "'error_log' has no type= parameter");
330                 return false; 
331         }
332
333         string type = type_it->second;
334         if (type == "file") {
335                 log_config.type = LogConfig::LOG_TYPE_FILE;
336         } else if (type == "syslog") {
337                 log_config.type = LogConfig::LOG_TYPE_SYSLOG;
338         } else if (type == "console") {
339                 log_config.type = LogConfig::LOG_TYPE_CONSOLE;
340         } else {
341                 log(ERROR, "Unknown log type '%s'", type.c_str());
342                 return false; 
343         }
344
345         if (log_config.type == LogConfig::LOG_TYPE_FILE) {
346                 map<string, string>::const_iterator filename_it = line.parameters.find("filename");
347                 if (filename_it == line.parameters.end()) {
348                         log(ERROR, "error_log type 'file' with no filename= parameter");
349                         return false; 
350                 }
351                 log_config.filename = filename_it->second;
352         }
353
354         config->log_destinations.push_back(log_config);
355         return true;
356 }
357
358 bool parse_config(const string &filename, Config *config)
359 {
360         vector<ConfigLine> lines;
361         if (!read_config(filename, &lines)) {
362                 return false;
363         }
364
365         config->daemonize = false;
366
367         if (!fetch_config_int(lines, "num_servers", &config->num_servers)) {
368                 log(ERROR, "Missing 'num_servers' statement in config file.");
369                 return false;
370         }
371         if (config->num_servers < 1 || config->num_servers >= 20000) {  // Insanely high max limit.
372                 log(ERROR, "'num_servers' is %d, needs to be in [1, 20000>.", config->num_servers);
373                 return false;
374         }
375
376         // See if the user wants stats.
377         config->stats_interval = 60;
378         bool has_stats_file = fetch_config_string(lines, "stats_file", &config->stats_file);
379         bool has_stats_interval = fetch_config_int(lines, "stats_interval", &config->stats_interval);
380         if (has_stats_interval && !has_stats_file) {
381                 log(WARNING, "'stats_interval' given, but no 'stats_file'. No statistics will be written.");
382         }
383         
384         fetch_config_string(lines, "access_log", &config->access_log_file);
385
386         for (size_t i = 0; i < lines.size(); ++i) {
387                 const ConfigLine &line = lines[i];
388                 if (line.keyword == "num_servers" ||
389                     line.keyword == "stats_file" ||
390                     line.keyword == "stats_interval" ||
391                     line.keyword == "access_log") {
392                         // Already taken care of, above.
393                 } else if (line.keyword == "port") {
394                         if (!parse_port(line, config)) {
395                                 return false;
396                         }
397                 } else if (line.keyword == "stream") {
398                         if (!parse_stream(line, config)) {
399                                 return false;
400                         }
401                 } else if (line.keyword == "udpstream") {
402                         if (!parse_udpstream(line, config)) {
403                                 return false;
404                         }
405                 } else if (line.keyword == "error_log") {
406                         if (!parse_error_log(line, config)) {
407                                 return false;
408                         }
409                 } else if (line.keyword == "daemonize") {
410                         config->daemonize = true;
411                 } else {
412                         log(ERROR, "Unknown configuration keyword '%s'.",
413                                 line.keyword.c_str());
414                         return false;
415                 }
416         }
417
418         return true;
419 }