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