2 * @brief Config class implementation. This class represents the actual configuration.
6 * @copyright Intra2net AG
12 #include "service_dhs.hpp"
13 #include "service_ods.hpp"
14 #include "service_dyndns.hpp"
15 #include "service_dyns.hpp"
16 #include "service_easydns.hpp"
17 #include "service_tzo.hpp"
18 #include "service_zoneedit.hpp"
19 #include "service_gnudip.hpp"
25 #include <boost/foreach.hpp>
26 #include <boost/filesystem.hpp>
27 #include <boost/regex.hpp>
28 #include <boost/algorithm/string.hpp>
31 namespace po = boost::program_options;
32 namespace fs = boost::filesystem;
33 namespace ba = boost::algorithm;
35 typedef boost::shared_ptr<boost::program_options::options_description> Options_descriptionPtr;
41 * Default Constructor. Available command line and config file options with their default values are defined here.
45 , ServiceHolder(new Serviceholder)
50 , ConfigPath("/etc/bpdyndnsd")
53 , ExternalWarningLog("")
54 , ExternalWarningLevel(0)
56 , WebcheckEnabled(false)
57 , ExternalLogOnlyOnce(false)
59 , DialupBurstPeriodSeconds(120)
60 , DialupSleepSeconds(10 * 60)
62 define_config_options();
67 * Constructor with Logger and Serviceholder objects. Available command line and config file options with their default values are defined here.
68 * @todo Move the program options init code to a function used by both constructors
70 Config::Config(Logger::Ptr _log, Serviceholder::Ptr _serviceholder)
72 , ServiceHolder(_serviceholder)
77 , ConfigPath("/etc/bpdyndnsd")
80 , ExternalWarningLog("")
81 , ExternalWarningLevel(0)
83 , WebcheckEnabled(false)
84 , ExternalLogOnlyOnce(false)
86 , DialupBurstPeriodSeconds(120)
87 , DialupSleepSeconds(10 * 60)
89 define_config_options();
102 * Define valid config options with default parameters.
104 void Config::define_config_options()
106 // Available service description config options
107 po::options_description opt_desc_service("Service description options");
108 opt_desc_service.add_options()
109 ("protocol",po::value<string>(),"The service protocol.")
110 ("server",po::value<string>(),"Servername needed for gnudip/dyndns protocol.")
111 ("host",po::value<string>(),"The hostname to update.")
112 ("login",po::value<string>(),"Login name.")
113 ("password",po::value<string>(),"Corresponding password.")
114 ("update_interval",po::value<int>()->default_value(-1),"Update interval in minutes.")
115 ("max_updates_within_interval",po::value<int>()->default_value(-1),"How many updates can be made in one interval.")
116 ("dns_cache_ttl",po::value<int>()->default_value(-1),"How long a dns record is valid.")
119 // Available command line only options
120 po::options_description opt_desc_cmd_only("Command line only options");
121 opt_desc_cmd_only.add_options()
122 ("help,?","Show help.")
123 ("version,v","Show version.")
124 ("config,c",po::value<string>()->default_value("/etc/bpdyndnsd"),"Set the config path.")
127 // Available generic options. Valid on cmd or in config file.
128 po::options_description opt_desc_generic("Generic config options");
129 opt_desc_generic.add_options()
130 ("daemon_mode",po::value<bool>()->default_value(false),"Run as system daemon.")
131 ("loglevel",po::value<int>()->default_value(0),"Loglevel.")
132 ("syslog",po::value<bool>()->default_value(false),"Use syslog facility.")
133 ("enable_ipv6",po::value<bool>()->default_value(false),"Try to use IPv6.")
134 ("webcheck_enabled",po::value<bool>()->default_value(false),"Use webcheck url to determine actual IP address.")
135 ("webcheck_url",po::value<string>()->default_value(""),"Use this URL to determine IP.")
136 ("webcheck_url_alt",po::value<string>()->default_value(""),"Use this alternative URL to determine IP.")
137 ("webcheck_interval",po::value<int>()->default_value(10),"The webcheck interval in minutes.")
138 ("http_proxy",po::value<string>(),"Use this proxy for all http requests.")
139 ("http_proxy_port",po::value<int>(),"Port of the proxy.")
140 ("external_warning_log",po::value<string>()->default_value(""),"External programm to pass warning log messages to.")
141 ("external_warning_level",po::value<int>()->default_value(0),"Warning messages of which loglevel should be passed to external programm.")
142 ("external_log_only_once",po::value<bool>()->default_value(false),"Log the same external message only once until next reload or restart.")
143 ("start_offline",po::value<bool>()->default_value(false),"Start in offline mode.")
144 ("dialup_mode",po::value<bool>()->default_value(false),"Enable dialup mode (sleep periods between network traffic)")
145 ("dialup_burst_period_seconds",po::value<int>()->default_value(120),"Seconds of normal operation before entering dialup mode")
146 ("dialup_sleep_seconds",po::value<int>()->default_value(10 * 60),"Seconds to sleep between network traffic")
149 // Define valid command line parameters
150 OptDescCmd = Options_descriptionPtr(new po::options_description("Command line options"));
151 OptDescCmd->add(opt_desc_cmd_only);
152 OptDescCmd->add(opt_desc_generic);
153 OptDescCmd->add(opt_desc_service);
155 // Define valid config file options
156 OptDescConfMain = Options_descriptionPtr(new po::options_description("Config file options"));
157 OptDescConfMain->add(opt_desc_generic);
159 // Define valid service file options
160 OptDescConfService = Options_descriptionPtr(new po::options_description("Service file options"));
161 OptDescConfService->add(opt_desc_service);
166 * Parses the command line arguments and does the needed actions.
167 * @param argc Command line argument number given to main.
168 * @param argv[] Pointer to command line argument array given to main.
169 * @return 0 if all is fine, -1 if not.
171 int Config::parse_cmd_line(int argc, char *argv[])
175 po::store(po::parse_command_line(argc, argv, *this->OptDescCmd), VariablesMap);
176 po::notify(VariablesMap);
178 if ( VariablesMap.count("help") )
180 Log->print_usage(OptDescCmd);
183 else if ( VariablesMap.count("version") )
185 Log->print_version();
189 // Create a service object if all needed options are set on the command line
190 if ( VariablesMap.count("protocol") && VariablesMap.count("host") && VariablesMap.count("login") && VariablesMap.count("password") )
192 // Get the cmd parameter values for protocol host login and password
193 string protocol = VariablesMap["protocol"].as<string>();
194 string host = VariablesMap["host"].as<string>();
195 string login = VariablesMap["login"].as<string>();
196 string password = VariablesMap["password"].as<string>();
198 protocol = ba::to_lower_copy(protocol);
201 if ( VariablesMap.count("server") )
202 server = VariablesMap["server"].as<string>();
204 int update_interval = 0;
205 if ( VariablesMap.count("update_interval") )
206 update_interval = VariablesMap["update_interval"].as<int>();
208 int max_updates_within_interval = 0;
209 if ( VariablesMap.count("max_updates_within_interval") )
210 max_updates_within_interval = VariablesMap["max_updates_within_interval"].as<int>();
212 int dns_cache_ttl = 0;
213 if ( VariablesMap.count("dns_cache_ttl") )
214 dns_cache_ttl = VariablesMap["dns_cache_ttl"].as<int>();
216 Service::Ptr service = create_service(protocol,server,host,login,password,update_interval,max_updates_within_interval,dns_cache_ttl);
219 ServiceHolder->add_service(service);
220 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_dns_cache_ttl() , service->get_actual_ip(), service->get_last_updates());
224 Log->print_invalid_service_config();
227 else if ( VariablesMap.count("protocol") || VariablesMap.count("host") || VariablesMap.count("login") || VariablesMap.count("password") )
229 Log->print_missing_cmd_service_option();
230 Log->print_usage(OptDescCmd);
234 if ( VariablesMap.count("config") )
236 fs::path full_config_path = fs::system_complete(fs::path(VariablesMap["config"].as<string>()));
237 ConfigPath = full_config_path.string();
238 if ( !fs::exists(full_config_path) || !fs::is_directory(full_config_path) )
240 // Config path doesn't exist or is not a directory
241 Log->print_error_config_path(ConfigPath);
246 if ( VariablesMap.count("daemon_mode") )
247 DaemonMode = VariablesMap["daemon_mode"].as<bool>();
249 if ( VariablesMap.count("loglevel") )
250 Loglevel = VariablesMap["loglevel"].as<int>();
252 if ( VariablesMap.count("syslog") )
253 Syslog = VariablesMap["syslog"].as<bool>();
255 if ( VariablesMap.count("enable_ipv6") )
256 EnableIPv6 = VariablesMap["enable_ipv6"].as<bool>();
258 if ( VariablesMap.count("webcheck_enabled") )
259 WebcheckEnabled = VariablesMap["webcheck_enabled"].as<bool>();
261 if ( VariablesMap.count("webcheck_url") )
262 WebcheckIpUrl = VariablesMap["webcheck_url"].as<string>();
264 if ( VariablesMap.count("webcheck_url_alt") )
265 WebcheckIpUrlAlt = VariablesMap["webcheck_url_alt"].as<string>();
267 if ( VariablesMap.count("webcheck_interval") )
268 WebcheckInterval = VariablesMap["webcheck_interval"].as<int>();
270 if ( VariablesMap.count("http_proxy") && VariablesMap.count("http_proxy_port") )
272 Proxy = VariablesMap["http_proxy"].as<string>();
273 ProxyPort = VariablesMap["http_proxy_port"].as<int>();
275 else if ( VariablesMap.count("http_proxy") || VariablesMap.count("http_proxy_port") )
277 Log->print_missing_cmd_proxy_option();
278 Log->print_usage(OptDescCmd);
282 if ( VariablesMap.count("external_warning_log") )
283 ExternalWarningLog = VariablesMap["external_warning_log"].as<string>();
285 if ( VariablesMap.count("external_warning_level") )
286 ExternalWarningLevel = VariablesMap["external_warning_level"].as<int>();
288 if ( VariablesMap.count("external_log_only_once") )
289 ExternalLogOnlyOnce = VariablesMap["external_log_only_once"].as<bool>();
291 if ( VariablesMap.count("start_offline") )
292 StartOffline = VariablesMap["start_offline"].as<bool>();
294 if ( VariablesMap.count("dialup_mode") )
295 DialupMode = VariablesMap["dialup_mode"].as<bool>();
296 if ( VariablesMap.count("dialup_burst_period_seconds") )
297 DialupBurstPeriodSeconds = VariablesMap["dialup_burst_period_seconds"].as<int>();
298 if ( VariablesMap.count("dialup_sleep_seconds") )
299 DialupSleepSeconds = VariablesMap["dialup_sleep_seconds"].as<int>();
301 catch( const po::unknown_option& e )
303 Log->print_unknown_cmd_option(e.what());
304 Log->print_usage(OptDescCmd);
307 catch( const po::multiple_occurrences& e )
309 Log->print_multiple_cmd_option(e.what());
310 Log->print_usage(OptDescCmd);
313 catch( const po::error& e )
315 Log->print_error_parsing_cmd(e.what());
316 Log->print_usage(OptDescCmd);
324 * Creates a Service object from the given parameters.
325 * @param protocol Protocol to use.
326 * @param host Hostname to update.
327 * @param login Login.
328 * @param password Password.
329 * @return A pointer to the created Service object.
331 Service::Ptr Config::create_service(const string &protocol, const string& server, const string& hostname, const string& login, const string& password, const int update_interval, const int max_updates_within_interval, const int dns_cache_ttl)
333 // Test for valid hostname. Must contain 3 parts minimum.
334 list<string> fqhn_parts;
335 ba::split(fqhn_parts,hostname,boost::is_any_of("."));
336 if ( fqhn_parts.size() < 3 )
338 Log->print_invalid_hostname(hostname);
339 Service::Ptr service;
343 if(protocol == "dhs")
345 Service::Ptr service_dhs(new ServiceDhs(protocol,hostname,login,password,Log,update_interval,max_updates_within_interval,dns_cache_ttl,Proxy,ProxyPort));
348 else if(protocol == "ods")
350 Service::Ptr service_ods(new ServiceOds(protocol,hostname,login,password,Log,update_interval,max_updates_within_interval,dns_cache_ttl));
353 else if(protocol == "dyndns")
355 Service::Ptr service_dyndns(new ServiceDyndns(protocol,hostname,login,password,Log,update_interval,max_updates_within_interval,dns_cache_ttl,Proxy,ProxyPort,server));
356 return service_dyndns;
358 else if(protocol == "dyns")
360 Service::Ptr service_dyns(new ServiceDyns(protocol,hostname,login,password,Log,update_interval,max_updates_within_interval,dns_cache_ttl,Proxy,ProxyPort));
363 else if(protocol == "easydns")
365 Service::Ptr service_easydns(new ServiceEasydns(protocol,hostname,login,password,Log,update_interval,max_updates_within_interval,dns_cache_ttl,Proxy,ProxyPort));
366 return service_easydns;
368 else if(protocol == "tzo")
370 Service::Ptr service_tzo(new ServiceTzo(protocol,hostname,login,password,Log,update_interval,max_updates_within_interval,dns_cache_ttl,Proxy,ProxyPort));
373 else if(protocol == "zoneedit")
375 Service::Ptr service_zoneedit(new ServiceZoneedit(protocol,hostname,login,password,Log,update_interval,max_updates_within_interval,dns_cache_ttl,Proxy,ProxyPort));
376 return service_zoneedit;
378 else if(protocol == "gnudip")
380 if ( !server.empty() )
382 Service::Ptr service_gnudip(new ServiceGnudip(protocol,server,hostname,login,password,Log,update_interval,max_updates_within_interval,dns_cache_ttl,Proxy,ProxyPort));
383 return service_gnudip;
387 Log->print_gnudip_requires_servername();
388 Service::Ptr service;
394 Log->print_unknown_protocol(protocol);
395 Service::Ptr service;
402 * Loads a service config file, invoked by load_config_from_files.
403 * @param full_filename Filename of the service config file to load.
404 * @return 0 if all is fine, -1 otherwise.
406 int Config::load_service_config_file(const string& full_filename)
408 Log->print_load_service_conf(full_filename);
410 ifstream service_config_file(full_filename.c_str(),ifstream::in);
411 if(service_config_file.is_open())
415 po::variables_map vm;
416 po::parsed_options parsed_service_options = po::parse_config_file(service_config_file,*this->OptDescConfService,false);
417 po::store(parsed_service_options,vm);
420 if(vm.count("protocol") && vm.count("host") && vm.count("login") && vm.count("password"))
422 // create the corresponding service
423 string protocol = vm["protocol"].as<string>();
424 string host = vm["host"].as<string>();
425 string login = vm["login"].as<string>();
426 string password = vm["password"].as<string>();
428 protocol = ba::to_lower_copy(protocol);
431 if ( vm.count("server") )
432 server = vm["server"].as<string>();
434 int update_interval = 0;
435 if ( vm.count("update_interval") )
436 update_interval = vm["update_interval"].as<int>();
438 int max_updates_within_interval = 0;
439 if ( vm.count("max_updates_within_interval") )
440 max_updates_within_interval = vm["max_updates_within_interval"].as<int>();
442 int dns_cache_ttl = 0;
443 if ( vm.count("dns_cache_ttl") )
444 dns_cache_ttl = vm["dns_cache_ttl"].as<int>();
446 Service::Ptr service = create_service(protocol,server,host,login,password,update_interval,max_updates_within_interval,dns_cache_ttl);
449 ServiceHolder->add_service(service);
450 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_dns_cache_ttl() , service->get_actual_ip(), service->get_last_updates());
454 Log->print_invalid_service_config();
457 else if ( vm.count("protocol") || vm.count("host") || vm.count("login") || vm.count("password") )
459 service_config_file.close();
460 Log->print_missing_service_conf_option(full_filename);
464 catch( const po::unknown_option& e )
466 // unknown option in config file detected
467 service_config_file.close();
468 Log->print_unknown_service_conf_option(full_filename,e.what());
471 catch( const po::multiple_occurrences& e )
473 service_config_file.close();
474 Log->print_multiple_service_conf_option(full_filename,e.what());
477 catch( const po::error& e )
479 service_config_file.close();
480 Log->print_error_parsing_config_file(full_filename,e.what());
483 service_config_file.close();
487 // error opening service config file for reading
488 Log->print_error_opening_r(full_filename);
496 * Loads the main config file, invoked by load_config_from_files
497 * @param full_filename The full filename of the main config file to load
498 * @return 0 if all is fine, -1 otherwise
500 int Config::load_main_config_file(const string& full_filename)
502 Log->print_load_main_conf(full_filename);
504 ifstream main_config_file(full_filename.c_str(),ifstream::in);
505 if(main_config_file.is_open())
509 po::parsed_options parsed_main_options = po::parse_config_file(main_config_file,*this->OptDescConfMain,false);
510 po::store(parsed_main_options,VariablesMap);
511 po::notify(VariablesMap);
513 if ( VariablesMap.count("daemon_mode") )
514 DaemonMode = VariablesMap["daemon_mode"].as<bool>();
516 if ( VariablesMap.count("loglevel") )
517 Loglevel = VariablesMap["loglevel"].as<int>();
519 if ( VariablesMap.count("syslog") )
520 Syslog = VariablesMap["syslog"].as<bool>();
522 if ( VariablesMap.count("enable_ipv6") )
523 EnableIPv6 = VariablesMap["enable_ipv6"].as<bool>();
525 if ( VariablesMap.count("webcheck_enabled") )
526 WebcheckEnabled = VariablesMap["webcheck_enabled"].as<bool>();
528 if ( VariablesMap.count("webcheck_url") )
529 WebcheckIpUrl = VariablesMap["webcheck_url"].as<string>();
531 if ( VariablesMap.count("webcheck_url_alt") )
532 WebcheckIpUrlAlt = VariablesMap["webcheck_url_alt"].as<string>();
534 if ( VariablesMap.count("webcheck_interval") )
535 WebcheckInterval = VariablesMap["webcheck_interval"].as<int>();
537 if ( VariablesMap.count("http_proxy") && VariablesMap.count("http_proxy_port") )
539 Proxy = VariablesMap["http_proxy"].as<string>();
540 ProxyPort = VariablesMap["http_proxy_port"].as<int>();
542 else if ( VariablesMap.count("http_proxy") || VariablesMap.count("http_proxy_port") )
544 main_config_file.close();
545 Log->print_missing_conf_proxy_option(full_filename);
549 if ( VariablesMap.count("external_warning_log") )
550 ExternalWarningLog = VariablesMap["external_warning_log"].as<string>();
552 if ( VariablesMap.count("external_warning_level") )
553 ExternalWarningLevel = VariablesMap["external_warning_level"].as<int>();
555 if ( VariablesMap.count("external_log_only_once") )
556 ExternalLogOnlyOnce = VariablesMap["external_log_only_once"].as<bool>();
558 if ( VariablesMap.count("start_offline") )
559 StartOffline = VariablesMap["start_offline"].as<bool>();
561 if ( VariablesMap.count("dialup_mode") )
562 DialupMode = VariablesMap["dialup_mode"].as<bool>();
563 if ( VariablesMap.count("dialup_burst_period_seconds") )
564 DialupBurstPeriodSeconds = VariablesMap["dialup_burst_period_seconds"].as<int>();
565 if ( VariablesMap.count("dialup_sleep_seconds") )
566 DialupSleepSeconds = VariablesMap["dialup_sleep_seconds"].as<int>();
568 catch( const po::unknown_option& e )
570 // unknown option in main config file detected
571 main_config_file.close();
572 Log->print_unknown_main_conf_option(e.what());
575 catch( const po::multiple_occurrences& e )
577 main_config_file.close();
578 Log->print_multiple_main_conf_option(full_filename,e.what());
581 main_config_file.close();
585 // error opening main config file for reading
586 Log->print_error_opening_r(full_filename);
594 * Loads the main and the service config file and does the needed action.
595 * @param config_path The path to the config directory.
596 * @return 0 if all is fine, -1 otherwise
598 int Config::load_config_from_files()
600 fs::path full_config_path = fs::path(ConfigPath);
602 fs::directory_iterator end_iter;
603 for ( fs::directory_iterator dir_itr(full_config_path) ; dir_itr != end_iter ; ++dir_itr )
605 if( fs::is_regular_file( dir_itr->status() ) )
607 string actual_file = dir_itr->path().filename();
608 boost::regex expr(".*\\.conf$");
609 // If it is the main config file do the following
610 if ( actual_file == "bpdyndnsd.conf" )
612 // Load the main config file
613 string full_filename = dir_itr->path().string();
614 if ( load_main_config_file(full_filename) != 0 )
617 // If it is a service definition file *.conf, parse it and generate the corresponding service
618 else if ( boost::regex_search( actual_file,expr ) )
620 string full_filename = dir_itr->path().string();
621 if ( load_service_config_file(full_filename) != 0 )
626 // Config file successfully loaded
627 Log->print_conf_loaded(ConfigPath);
633 * Getter method for member OptDescCmd.
634 * @return options_description*.
636 Options_descriptionPtr Config::get_opt_desc_cmd() const
643 * Getter method for member OptDescConfMain.
644 * @return options_description*.
646 Options_descriptionPtr Config::get_opt_desc_conf_main() const
648 return OptDescConfMain;
653 * Getter method for member OptDescConfService.
654 * @return options_description*.
656 Options_descriptionPtr Config::get_opt_desc_conf_service() const
658 return OptDescConfService;
663 * Getter for member Loglevel.
664 * @return Member Loglevel.
666 int Config::get_loglevel() const
673 * Getter for member DaemonMode.
674 * @return TRUE if enabled, FALSE if disabled.
676 bool Config::get_daemon_mode() const
683 * Deletes the map with the previously parsed options.
684 * This is needed in case we reload the config and don't want the old cmd options to overwrite new config file options.
686 void Config::delete_variables_map()
688 VariablesMap.clear();
690 po::variables_map _variables_map;
691 VariablesMap = _variables_map;
696 * Getter for member Syslog.
697 * @return True if logging through syslog is enabled, false otherwise.
699 bool Config::get_syslog() const
706 * Getter for member EnableIPv6
707 * @return Wether IPv6 should be used or not.
709 bool Config::get_enable_ipv6() const
716 * Getter for member WebcheckEnabled
717 * @return Is webcheck enabled by default.
719 bool Config::get_webcheck_enabled() const
721 return WebcheckEnabled;
726 * Setter for member WebcheckEnabled
727 * @return Is webcheck enabled by default.
729 void Config::set_webcheck_enabled( bool webcheck_enabled )
731 WebcheckEnabled = webcheck_enabled;
736 * Getter for member WebcheckIpUrl
737 * @return The primary IP Webcheck URL
739 string Config::get_webcheck_ip_url() const
741 return WebcheckIpUrl;
746 * Getter for member WebcheckIpUrlAlt
747 * @return The alternative IP Webcheck URL
749 string Config::get_webcheck_ip_url_alt() const
751 return WebcheckIpUrlAlt;
756 * Get member WebcheckInterval
757 * @return WebcheckInterval
759 int Config::get_webcheck_interval() const
761 return WebcheckInterval;
769 string Config::get_proxy() const
776 * Get member ProxyPort
779 int Config::get_proxy_port() const
786 * Get member ExternalWarningLog
787 * @return ExternalWarningLog
789 string Config::get_external_warning_log() const
791 return ExternalWarningLog;
796 * Get member ExternalWarningLevel
797 * @return ExternalWaringLevel
799 int Config::get_external_warning_level() const
801 return ExternalWarningLevel;
806 * Get member StartOffline
807 * @return StartOffline
809 bool Config::get_start_offline() const
816 * Get member ExternalLogOnlyOnce
817 * @return StartOffline
819 bool Config::get_external_log_only_once() const
821 return ExternalLogOnlyOnce;
826 * Get member DialupMode
829 bool Config::get_dialup_mode() const
835 * Get member DialupBurstPeriodSeconds
836 * @return DialupBurstPeriodSeconds
838 int Config::get_dialup_burst_period_seconds() const
840 return DialupBurstPeriodSeconds;
844 * Get member DialupSleepSeconds
845 * @return DialupSleepSeconds
847 int Config::get_dialup_sleep_seconds() const
849 return DialupSleepSeconds;