Implemented first part of http proxy ability.
[bpdyndnsd] / src / config.cpp
1 /** @file
2  * @brief Config class implementation. This class represents the actual configuration.
3  *
4  *
5  *
6  * @copyright Intra2net AG
7  * @license GPLv2
8 */
9
10 #include "config.h"
11
12 #include "dhs.h"
13 #include "ods.h"
14
15 #include <time.h>
16 #include <iostream>
17 #include <fstream>
18
19 #include <boost/foreach.hpp>
20 #include <boost/filesystem.hpp>
21 #include <boost/regex.hpp>
22 #include <boost/algorithm/string.hpp>
23
24
25
26 namespace po = boost::program_options;
27 namespace fs = boost::filesystem;
28 namespace ba = boost::algorithm;
29
30 using namespace std;
31
32 /**
33  * Default Constructor. Available command line and config file options with their default values are defined here.
34  */
35 Config::Config(Logger::Ptr _log, Serviceholder::Ptr _serviceholder)
36     : DaemonMode(false)
37     , Syslog(false)
38     , EnableIPv6(false)
39     , Loglevel(0)
40     , ConfigPath("/etc/bpdyndnsd")
41 {
42     // initialize Logger
43     Log = _log;
44
45     // initialize Serviceholder
46     ServiceHolder = _serviceholder;
47
48     // Available service description config options
49     po::options_description opt_desc_service("Service description options");
50     opt_desc_service.add_options()
51         ("protocol",po::value<string>(),"The service protocol.")
52         ("host",po::value<string>(),"The hostname to update.")
53         ("login",po::value<string>(),"Login name.")
54         ("password",po::value<string>(),"Corresponding password.")
55         ("update_interval",po::value<int>()->default_value(-1),"Update interval in minutes.")
56         ("max_updates_within_interval",po::value<int>()->default_value(-1),"How many updates can be made in one interval.")
57         ("dns_cache_ttl",po::value<int>()->default_value(-1),"How long a dns record is valid.")
58     ;
59
60     // Available command line only options
61     po::options_description opt_desc_cmd_only("Command line only options");
62     opt_desc_cmd_only.add_options()
63         ("help,?","Show help.")
64         ("version,v","Show version.")
65         ("config,c",po::value<string>()->default_value("/etc/bpdyndnsd"),"Set the config path.")
66     ;
67
68      // Available generic options. Valid on cmd or in config file.
69     po::options_description opt_desc_generic("Generic config options");
70     opt_desc_generic.add_options()
71         ("daemon_mode",po::value<bool>()->default_value(false),"Run as system daemon.")
72         ("loglevel",po::value<int>()->default_value(0),"Loglevel.")
73         ("syslog",po::value<bool>()->default_value(false),"Use syslog facility.")
74         ("enable_ipv6",po::value<bool>()->default_value(false),"Try to use IPv6.")
75         ("webcheck_url",po::value<string>()->default_value(""),"Use this URL to determine IP.")
76         ("webcheck_url_alt",po::value<string>()->default_value(""),"Use this alternative URL to determine IP.")
77         ("http_proxy",po::value<string>()->default_value(""),"Use this proxy for all http requests.")
78         ("http_proxy_port",po::value<int>()->default_value(0),"Port of the proxy.")
79     ;
80
81     // Define valid command line parameters
82     Options_descriptionPtr _opt_desc_cmd(new po::options_description("Command line options"));
83     OptDescCmd = _opt_desc_cmd;
84     _opt_desc_cmd.reset();
85     OptDescCmd->add(opt_desc_cmd_only);
86     OptDescCmd->add(opt_desc_generic);
87     OptDescCmd->add(opt_desc_service);
88
89     // Define valid config file options
90     Options_descriptionPtr _opt_desc_conf_main(new po::options_description("Config file options"));
91     OptDescConfMain = _opt_desc_conf_main;
92     _opt_desc_conf_main.reset();
93     OptDescConfMain->add(opt_desc_generic);
94
95     // Define valid service file options
96     Options_descriptionPtr _opt_desc_conf_service(new po::options_description("Service file options"));
97     OptDescConfService = _opt_desc_conf_service;
98     _opt_desc_conf_service.reset();
99     OptDescConfService->add(opt_desc_service);
100 }
101
102
103 /**
104  * Default Destructor
105  */
106 Config::~Config()
107 {
108 }
109
110
111 /**
112  * Parses the command line arguments and does the needed actions.
113  * @param argc Command line argument number given to main.
114  * @param argv[] Pointer to command line argument array given to main.
115  * @return 0 if all is fine, -1 if not.
116  */
117 int Config::parse_cmd_line(int argc, char *argv[])
118 {
119     try
120     {
121         po::store(po::parse_command_line(argc, argv, *this->OptDescCmd), VariablesMap);
122         po::notify(VariablesMap);
123
124         if ( VariablesMap.count("help") )
125         {
126             Log->print_usage(OptDescCmd);
127             return -1;
128         }
129         else if ( VariablesMap.count("version") )
130         {
131             Log->print_version();
132             return -1;
133         }
134
135         // Create a service object if all needed options are set on the command line
136         if ( VariablesMap.count("protocol") && VariablesMap.count("host") && VariablesMap.count("login") && VariablesMap.count("password") )
137         {
138             // Get the cmd parameter values for protocol host login and password
139             string protocol = VariablesMap["protocol"].as<string>();
140             string host = VariablesMap["host"].as<string>();
141             string login = VariablesMap["login"].as<string>();
142             string password = VariablesMap["password"].as<string>();
143
144             protocol = ba::to_lower_copy(protocol);
145
146             int update_interval = 0;
147             if ( VariablesMap.count("update_interval") )
148                 update_interval = VariablesMap["update_interval"].as<int>();
149
150             int max_updates_within_interval = 0;
151             if ( VariablesMap.count("max_updates_within_interval") )
152                 max_updates_within_interval = VariablesMap["max_updates_within_interval"].as<int>();
153
154             int dns_cache_ttl = 0;
155             if ( VariablesMap.count("dns_cache_ttl") )
156                 dns_cache_ttl = VariablesMap["dns_cache_ttl"].as<int>();
157
158             Service::Ptr service = create_service(protocol,host,login,password,update_interval,max_updates_within_interval,dns_cache_ttl);
159             if ( service )
160             {
161                 ServiceHolder->add_service(service);
162                 Log->print_service_object("New Service object from command line options:", service->get_protocol(), service->get_hostname(), service->get_login() ,service->get_password(), service->get_update_interval(), service->get_max_updates_within_interval(), service->get_actual_ip(), service->get_last_updates());
163             }
164             else
165                 return -1;
166         }
167         else if ( VariablesMap.count("protocol") || VariablesMap.count("host") || VariablesMap.count("login") || VariablesMap.count("password") )
168         {
169             Log->print_missing_cmd_service_option();
170             Log->print_usage(OptDescCmd);
171             return -1;
172         }
173
174         if ( VariablesMap.count("config") )
175         {
176             fs::path full_config_path = fs::system_complete(fs::path(VariablesMap["config"].as<string>()));
177             ConfigPath = full_config_path.string();
178             if ( !fs::exists(full_config_path) ||  !fs::is_directory(full_config_path) )
179             {
180                 // Config path doesn't exist or is not a directory
181                 Log->print_error_config_path(ConfigPath);
182                 return -1;
183             }
184         }
185
186         if ( VariablesMap.count("daemon_mode") )
187             DaemonMode = VariablesMap["daemon_mode"].as<bool>();
188
189         if ( VariablesMap.count("loglevel") )
190             Loglevel = VariablesMap["loglevel"].as<int>();
191
192         if ( VariablesMap.count("syslog") )
193             Syslog = VariablesMap["syslog"].as<bool>();
194
195         if ( VariablesMap.count("enable_ipv6") )
196             EnableIPv6 = VariablesMap["enable_ipv6"].as<bool>();
197
198         if ( VariablesMap.count("webcheck_url") )
199             WebcheckIpUrl = VariablesMap["webcheck_url"].as<string>();
200
201         if ( VariablesMap.count("webcheck_url_alt") )
202             WebcheckIpUrlAlt = VariablesMap["webcheck_url_alt"].as<string>();
203
204         if ( VariablesMap.count("http_proxy") )
205             Proxy = VariablesMap["http_proxy"].as<string>();
206
207         if ( VariablesMap.count("http_proxy_port") )
208             ProxyPort = VariablesMap["http_proxy_port"].as<int>();
209
210     }
211     catch(po::unknown_option e)
212     {
213         Log->print_unknown_cmd_option(e.what());
214         Log->print_usage(OptDescCmd);
215         return -1;
216     }
217     catch(po::multiple_occurrences e)
218     {
219         Log->print_multiple_cmd_option(e.what());
220         Log->print_usage(OptDescCmd);
221         return -1;
222     }
223     return 0;
224 }
225
226
227 /**
228  * Creates a Service object from the given parameters.
229  * @param protocol Protocol to use.
230  * @param host Hostname to update.
231  * @param login Login.
232  * @param password Password.
233  * @return A pointer to the created Service object.
234  */
235 Service::Ptr Config::create_service(const string &protocol,const string &hostname, const string &login, const string &password, const int update_interval, const int max_updates_within_interval, const int dns_cache_ttl)
236 {
237     if(protocol == "dhs")
238     {
239         Service::Ptr service_dhs(new DHS(protocol,hostname,login,password,Log,update_interval,max_updates_within_interval,dns_cache_ttl));
240         return service_dhs;
241     }
242     else if(protocol == "ods")
243     {
244         Service::Ptr service_ods(new ODS(protocol,hostname,login,password,Log,update_interval,max_updates_within_interval,dns_cache_ttl));
245         return service_ods;
246     }
247     else
248     {
249         Log->print_unknown_protocol(protocol);
250         Service::Ptr service;
251         return service;
252     }
253 }
254
255
256 /**
257  * Loads a service config file, invoked by load_config_from_files.
258  * @param full_filename Filename of the service config file to load.
259  * @return 0 if all is fine, -1 otherwise.
260  */
261 int Config::load_service_config_file(const string& full_filename)
262 {
263     Log->print_load_service_conf(full_filename);
264
265     ifstream service_config_file(full_filename.c_str(),ifstream::in);
266     if(service_config_file.is_open())
267     {
268         try
269         {
270             po::variables_map vm;
271             po::parsed_options parsed_service_options = po::parse_config_file(service_config_file,*this->OptDescConfService,true);
272             po::store(parsed_service_options,vm);
273             po::notify(vm);
274
275             if(vm.count("protocol") && vm.count("host") && vm.count("login") && vm.count("password"))
276             {
277                 // create the corresponding service
278                 string protocol = vm["protocol"].as<string>();
279                 string host = vm["host"].as<string>();
280                 string login = vm["login"].as<string>();
281                 string password = vm["password"].as<string>();
282
283                 protocol = ba::to_lower_copy(protocol);
284
285                 int update_interval = 0;
286                 if ( VariablesMap.count("update_interval") )
287                     update_interval = VariablesMap["update_interval"].as<int>();
288
289                 int max_updates_within_interval = 0;
290                 if ( VariablesMap.count("max_updates_within_interval") )
291                     max_updates_within_interval = VariablesMap["max_updates_within_interval"].as<int>();
292
293                 int dns_cache_ttl = 0;
294                 if ( VariablesMap.count("dns_cache_ttl") )
295                     dns_cache_ttl = VariablesMap["dns_cache_ttl"].as<int>();
296
297                 Service::Ptr service = create_service(protocol,host,login,password,update_interval,max_updates_within_interval,dns_cache_ttl);
298                 if ( service )
299                 {
300                     ServiceHolder->add_service(service);
301                     Log->print_service_object("New Service object from config:", service->get_protocol(), service->get_hostname(), service->get_login() ,service->get_password(), service->get_update_interval(), service->get_max_updates_within_interval(), service->get_actual_ip(), service->get_last_updates());
302                 }
303                 else
304                     return -1;
305             }
306         }
307         catch ( po::unknown_option e )
308         {
309             // unknown option in config file detected
310             service_config_file.close();
311             Log->print_unknown_service_conf_option(e.what());
312             return -1;
313         }
314         service_config_file.close();
315     }
316     else
317     {
318         // error opening service config file for reading
319         Log->print_error_opening_r(full_filename);
320         return -1;
321     }
322     return 0;
323 }
324
325
326 /**
327  * Loads the main config file, invoked by load_config_from_files
328  * @param full_filename The full filename of the main config file to load
329  * @return 0 if all is fine, -1 otherwise
330  */
331 int Config::load_main_config_file(const string& full_filename)
332 {
333     Log->print_load_main_conf(full_filename);
334
335     ifstream main_config_file(full_filename.c_str(),ifstream::in);
336     if(main_config_file.is_open())
337     {
338         try
339         {
340             po::parsed_options parsed_main_options = po::parse_config_file(main_config_file,*this->OptDescConfMain,true);
341             po::store(parsed_main_options,VariablesMap);
342             po::notify(VariablesMap);
343
344         if ( VariablesMap.count("daemon_mode") )
345             DaemonMode = VariablesMap["daemon_mode"].as<bool>();
346
347         if ( VariablesMap.count("loglevel") )
348             Loglevel = VariablesMap["loglevel"].as<int>();
349
350         if ( VariablesMap.count("syslog") )
351             Syslog = VariablesMap["syslog"].as<bool>();
352
353         if ( VariablesMap.count("enable_ipv6") )
354             EnableIPv6 = VariablesMap["enable_ipv6"].as<bool>();
355
356         if ( VariablesMap.count("webcheck_url") )
357             WebcheckIpUrl = VariablesMap["webcheck_url"].as<string>();
358
359         if ( VariablesMap.count("webcheck_url_alt") )
360             WebcheckIpUrlAlt = VariablesMap["webcheck_url_alt"].as<string>();
361
362         if ( VariablesMap.count("http_proxy") )
363             Proxy = VariablesMap["http_proxy"].as<string>();
364
365         if ( VariablesMap.count("http_proxy_port") )
366             ProxyPort = VariablesMap["http_proxy_port"].as<int>();
367
368         }
369         catch ( po::unknown_option e )      // at the moment 04-08-2009 this exception is never thrown :-(
370         {
371             // unknown option in main config file detected
372             main_config_file.close();
373             Log->print_unknown_main_conf_option(e.what());
374             return -1;
375         }
376         main_config_file.close();
377     }
378     else
379     {
380         // error opening main config file for reading
381         Log->print_error_opening_r(full_filename);
382         return -1;
383     }
384     return 0;
385 }
386
387
388 /**
389  * Loads the main and the service config file and does the needed action.
390  * @param config_path The path to the config directory.
391  * @return 0 if all is fine, -1 otherwise
392  */
393 int Config::load_config_from_files()
394 {
395     fs::path full_config_path = fs::path(ConfigPath);
396
397     fs::directory_iterator end_iter;
398     for ( fs::directory_iterator dir_itr(full_config_path) ; dir_itr != end_iter ; ++dir_itr )
399     {
400         if( fs::is_regular_file( dir_itr->status() ) )
401         {
402             string actual_file = dir_itr->path().filename();
403             boost::regex expr(".*\\.conf?");
404              // If it is the main config file do the following
405             if ( actual_file == "bpdyndnsd.conf" )
406             {
407                 // Load the main config file
408                 string full_filename = dir_itr->path().string();
409                 if ( load_main_config_file(full_filename) != 0 )
410                     return -1;
411             }
412             // If it is a service definition file *.conf, parse it and generate the corresponding service
413             else if ( boost::regex_search( actual_file,expr ) )
414             {
415                 string full_filename = dir_itr->path().string();
416                 if ( load_service_config_file(full_filename) != 0 )
417                     return -1;
418             }
419         }
420     }
421     // Config file successfully loaded
422     Log->print_conf_loaded(ConfigPath);
423     return 0;
424 }
425
426
427 /**
428  * Getter method for member OptDescCmd.
429  * @return options_description*.
430  */
431 Config::Options_descriptionPtr Config::get_opt_desc_cmd() const
432 {
433     return OptDescCmd;
434 }
435
436
437 /**
438  * Getter method for member OptDescConfMain.
439  * @return options_description*.
440  */
441 Config::Options_descriptionPtr Config::get_opt_desc_conf_main() const
442 {
443     return OptDescConfMain;
444 }
445
446
447 /**
448  * Getter method for member OptDescConfService.
449  * @return options_description*.
450  */
451 Config::Options_descriptionPtr Config::get_opt_desc_conf_service() const
452 {
453     return OptDescConfService;
454 }
455
456
457 /**
458  * Getter for member Loglevel.
459  * @return Member Loglevel.
460  */
461 int Config::get_loglevel() const
462 {
463     return Loglevel;
464 }
465
466
467 /**
468  * Getter for member DaemonMode.
469  * @return TRUE if enabled, FALSE if disabled.
470  */
471 bool Config::get_daemon_mode() const
472 {
473     return DaemonMode;
474 }
475
476
477 /**
478  * Deletes the map with the previously parsed options.
479  * This is needed in case we reload the config and don't want the old cmd options to overwrite new config file options.
480  */
481 void Config::delete_variables_map()
482 {
483     VariablesMap.clear();
484
485     po::variables_map _variables_map;
486     VariablesMap = _variables_map;
487 }
488
489
490 /**
491  * Getter for member Syslog.
492  * @return True if logging through syslog is enabled, false otherwise.
493  */
494 bool Config::get_syslog() const
495 {
496     return Syslog;
497 }
498
499
500 /**
501  * Getter for member EnableIPv6
502  * @return Wether IPv6 should be used or not.
503  */
504 bool Config::get_enable_ipv6() const
505 {
506     return EnableIPv6;
507 }
508
509
510 /**
511  * Getter for member WebcheckIpUrl
512  * @return The primary IP Webcheck URL
513  */
514 string Config::get_webcheck_ip_url() const
515 {
516     return WebcheckIpUrl;
517 }
518
519
520 /**
521  * Getter for member WebcheckIpUrlAlt
522  * @return The alternative IP Webcheck URL
523  */
524 string Config::get_webcheck_ip_url_alt() const
525 {
526     return WebcheckIpUrlAlt;
527 }
528
529
530 /**
531  * Get member Proxy
532  * @return Proxy
533  */
534 string Config::get_proxy() const
535 {
536     return Proxy;
537 }
538
539
540 /**
541  * Get member ProxyPort
542  * @return ProxyPort
543  */
544 int Config::get_proxy_port() const
545 {
546     return ProxyPort;
547 }