Added DNS Rechecking of DynDNS Hostname after DNS record ttl timeout.
[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     ;
78
79     // Define valid command line parameters
80     Options_descriptionPtr _opt_desc_cmd(new po::options_description("Command line options"));
81     OptDescCmd = _opt_desc_cmd;
82     _opt_desc_cmd.reset();
83     OptDescCmd->add(opt_desc_cmd_only);
84     OptDescCmd->add(opt_desc_generic);
85     OptDescCmd->add(opt_desc_service);
86
87     // Define valid config file options
88     Options_descriptionPtr _opt_desc_conf_main(new po::options_description("Config file options"));
89     OptDescConfMain = _opt_desc_conf_main;
90     _opt_desc_conf_main.reset();
91     OptDescConfMain->add(opt_desc_generic);
92
93     // Define valid service file options
94     Options_descriptionPtr _opt_desc_conf_service(new po::options_description("Service file options"));
95     OptDescConfService = _opt_desc_conf_service;
96     _opt_desc_conf_service.reset();
97     OptDescConfService->add(opt_desc_service);
98 }
99
100
101 /**
102  * Default Destructor
103  */
104 Config::~Config()
105 {
106 }
107
108
109 /**
110  * Parses the command line arguments and does the needed actions.
111  * @param argc Command line argument number given to main.
112  * @param argv[] Pointer to command line argument array given to main.
113  * @return 0 if all is fine, -1 if not.
114  */
115 int Config::parse_cmd_line(int argc, char *argv[])
116 {
117     try
118     {
119         po::store(po::parse_command_line(argc, argv, *this->OptDescCmd), VariablesMap);
120         po::notify(VariablesMap);
121
122         if ( VariablesMap.count("help") )
123         {
124             Log->print_usage(OptDescCmd);
125             return -1;
126         }
127         else if ( VariablesMap.count("version") )
128         {
129             Log->print_version();
130             return -1;
131         }
132
133         // Create a service object if all needed options are set on the command line
134         if ( VariablesMap.count("protocol") && VariablesMap.count("host") && VariablesMap.count("login") && VariablesMap.count("password") )
135         {
136             // Get the cmd parameter values for protocol host login and password
137             string protocol = VariablesMap["protocol"].as<string>();
138             string host = VariablesMap["host"].as<string>();
139             string login = VariablesMap["login"].as<string>();
140             string password = VariablesMap["password"].as<string>();
141
142             protocol = ba::to_lower_copy(protocol);
143
144             int update_interval = 0;
145             if ( VariablesMap.count("update_interval") )
146                 update_interval = VariablesMap["update_interval"].as<int>();
147
148             int max_updates_within_interval = 0;
149             if ( VariablesMap.count("max_updates_within_interval") )
150                 max_updates_within_interval = VariablesMap["max_updates_within_interval"].as<int>();
151
152             int dns_cache_ttl = 0;
153             if ( VariablesMap.count("dns_cache_ttl") )
154                 dns_cache_ttl = VariablesMap["dns_cache_ttl"].as<int>();
155
156             Service::Ptr service = create_service(protocol,host,login,password,update_interval,max_updates_within_interval,dns_cache_ttl);
157             if ( service )
158             {
159                 ServiceHolder->add_service(service);
160                 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());
161             }
162             else
163                 return -1;
164         }
165         else if ( VariablesMap.count("protocol") || VariablesMap.count("host") || VariablesMap.count("login") || VariablesMap.count("password") )
166         {
167             Log->print_missing_cmd_service_option();
168             Log->print_usage(OptDescCmd);
169             return -1;
170         }
171
172         if ( VariablesMap.count("config") )
173         {
174             fs::path full_config_path = fs::system_complete(fs::path(VariablesMap["config"].as<string>()));
175             ConfigPath = full_config_path.string();
176             if ( !fs::exists(full_config_path) ||  !fs::is_directory(full_config_path) )
177             {
178                 // Config path doesn't exist or is not a directory
179                 Log->print_error_config_path(ConfigPath);
180                 return -1;
181             }
182         }
183
184         if ( VariablesMap.count("daemon_mode") )
185             DaemonMode = VariablesMap["daemon_mode"].as<bool>();
186
187         if ( VariablesMap.count("loglevel") )
188             Loglevel = VariablesMap["loglevel"].as<int>();
189
190         if ( VariablesMap.count("syslog") )
191             Syslog = VariablesMap["syslog"].as<bool>();
192
193         if ( VariablesMap.count("enable_ipv6") )
194             EnableIPv6 = VariablesMap["enable_ipv6"].as<bool>();
195
196         if ( VariablesMap.count("webcheck_url") )
197             WebcheckIpUrl = VariablesMap["webcheck_url"].as<string>();
198
199         if ( VariablesMap.count("webcheck_url_alt") )
200             WebcheckIpUrlAlt = VariablesMap["webcheck_url_alt"].as<string>();
201
202     }
203     catch(po::unknown_option e)
204     {
205         Log->print_unknown_cmd_option(e.what());
206         Log->print_usage(OptDescCmd);
207         return -1;
208     }
209     catch(po::multiple_occurrences e)
210     {
211         Log->print_multiple_cmd_option(e.what());
212         Log->print_usage(OptDescCmd);
213         return -1;
214     }
215     return 0;
216 }
217
218
219 /**
220  * Creates a Service object from the given parameters.
221  * @param protocol Protocol to use.
222  * @param host Hostname to update.
223  * @param login Login.
224  * @param password Password.
225  * @return A pointer to the created Service object.
226  */
227 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)
228 {
229     if(protocol == "dhs")
230     {
231         Service::Ptr service_dhs(new DHS(protocol,hostname,login,password,Log,update_interval,max_updates_within_interval,dns_cache_ttl));
232         return service_dhs;
233     }
234     else if(protocol == "ods")
235     {
236         Service::Ptr service_ods(new ODS(protocol,hostname,login,password,Log,update_interval,max_updates_within_interval,dns_cache_ttl));
237         return service_ods;
238     }
239     else
240     {
241         Log->print_unknown_protocol(protocol);
242         Service::Ptr service;
243         return service;
244     }
245 }
246
247
248 /**
249  * Loads a service config file, invoked by load_config_from_files.
250  * @param full_filename Filename of the service config file to load.
251  * @return 0 if all is fine, -1 otherwise.
252  */
253 int Config::load_service_config_file(const string& full_filename)
254 {
255     Log->print_load_service_conf(full_filename);
256
257     ifstream service_config_file(full_filename.c_str(),ifstream::in);
258     if(service_config_file.is_open())
259     {
260         try
261         {
262             po::variables_map vm;
263             po::parsed_options parsed_service_options = po::parse_config_file(service_config_file,*this->OptDescConfService,true);
264             po::store(parsed_service_options,vm);
265             po::notify(vm);
266
267             if(vm.count("protocol") && vm.count("host") && vm.count("login") && vm.count("password"))
268             {
269                 // create the corresponding service
270                 string protocol = vm["protocol"].as<string>();
271                 string host = vm["host"].as<string>();
272                 string login = vm["login"].as<string>();
273                 string password = vm["password"].as<string>();
274
275                 protocol = ba::to_lower_copy(protocol);
276
277                 int update_interval = 0;
278                 if ( VariablesMap.count("update_interval") )
279                     update_interval = VariablesMap["update_interval"].as<int>();
280
281                 int max_updates_within_interval = 0;
282                 if ( VariablesMap.count("max_updates_within_interval") )
283                     max_updates_within_interval = VariablesMap["max_updates_within_interval"].as<int>();
284
285                 int dns_cache_ttl = 0;
286                 if ( VariablesMap.count("dns_cache_ttl") )
287                     dns_cache_ttl = VariablesMap["dns_cache_ttl"].as<int>();
288
289                 Service::Ptr service = create_service(protocol,host,login,password,update_interval,max_updates_within_interval,dns_cache_ttl);
290                 if ( service )
291                 {
292                     ServiceHolder->add_service(service);
293                     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());
294                 }
295                 else
296                     return -1;
297             }
298         }
299         catch ( po::unknown_option e )
300         {
301             // unknown option in config file detected
302             service_config_file.close();
303             Log->print_unknown_service_conf_option(e.what());
304             return -1;
305         }
306         service_config_file.close();
307     }
308     else
309     {
310         // error opening service config file for reading
311         Log->print_error_opening_r(full_filename);
312         return -1;
313     }
314     return 0;
315 }
316
317
318 /**
319  * Loads the main config file, invoked by load_config_from_files
320  * @param full_filename The full filename of the main config file to load
321  * @return 0 if all is fine, -1 otherwise
322  */
323 int Config::load_main_config_file(const string& full_filename)
324 {
325     Log->print_load_main_conf(full_filename);
326
327     ifstream main_config_file(full_filename.c_str(),ifstream::in);
328     if(main_config_file.is_open())
329     {
330         try
331         {
332             po::parsed_options parsed_main_options = po::parse_config_file(main_config_file,*this->OptDescConfMain,true);
333             po::store(parsed_main_options,VariablesMap);
334             po::notify(VariablesMap);
335
336         if ( VariablesMap.count("daemon_mode") )
337             DaemonMode = VariablesMap["daemon_mode"].as<bool>();
338
339         if ( VariablesMap.count("loglevel") )
340             Loglevel = VariablesMap["loglevel"].as<int>();
341
342         if ( VariablesMap.count("syslog") )
343             Syslog = VariablesMap["syslog"].as<bool>();
344
345         if ( VariablesMap.count("enable_ipv6") )
346             EnableIPv6 = VariablesMap["enable_ipv6"].as<bool>();
347
348         if ( VariablesMap.count("webcheck_url") )
349             WebcheckIpUrl = VariablesMap["webcheck_url"].as<string>();
350
351         if ( VariablesMap.count("webcheck_url_alt") )
352             WebcheckIpUrlAlt = VariablesMap["webcheck_url_alt"].as<string>();
353
354         }
355         catch ( po::unknown_option e )      // at the moment 04-08-2009 this exception is never thrown :-(
356         {
357             // unknown option in main config file detected
358             main_config_file.close();
359             Log->print_unknown_main_conf_option(e.what());
360             return -1;
361         }
362         main_config_file.close();
363     }
364     else
365     {
366         // error opening main config file for reading
367         Log->print_error_opening_r(full_filename);
368         return -1;
369     }
370     return 0;
371 }
372
373
374 /**
375  * Loads the main and the service config file and does the needed action.
376  * @param config_path The path to the config directory.
377  * @return 0 if all is fine, -1 otherwise
378  */
379 int Config::load_config_from_files()
380 {
381     fs::path full_config_path = fs::path(ConfigPath);
382
383     fs::directory_iterator end_iter;
384     for ( fs::directory_iterator dir_itr(full_config_path) ; dir_itr != end_iter ; ++dir_itr )
385     {
386         if( fs::is_regular_file( dir_itr->status() ) )
387         {
388             string actual_file = dir_itr->path().filename();
389             boost::regex expr(".*\\.conf?");
390              // If it is the main config file do the following
391             if ( actual_file == "bpdyndnsd.conf" )
392             {
393                 // Load the main config file
394                 string full_filename = dir_itr->path().string();
395                 if ( load_main_config_file(full_filename) != 0 )
396                     return -1;
397             }
398             // If it is a service definition file *.conf, parse it and generate the corresponding service
399             else if ( boost::regex_search( actual_file,expr ) )
400             {
401                 string full_filename = dir_itr->path().string();
402                 if ( load_service_config_file(full_filename) != 0 )
403                     return -1;
404             }
405         }
406     }
407     // Config file successfully loaded
408     Log->print_conf_loaded(ConfigPath);
409     return 0;
410 }
411
412
413 /**
414  * Getter method for member OptDescCmd.
415  * @return options_description*.
416  */
417 Config::Options_descriptionPtr Config::get_opt_desc_cmd() const
418 {
419     return OptDescCmd;
420 }
421
422
423 /**
424  * Getter method for member OptDescConfMain.
425  * @return options_description*.
426  */
427 Config::Options_descriptionPtr Config::get_opt_desc_conf_main() const
428 {
429     return OptDescConfMain;
430 }
431
432
433 /**
434  * Getter method for member OptDescConfService.
435  * @return options_description*.
436  */
437 Config::Options_descriptionPtr Config::get_opt_desc_conf_service() const
438 {
439     return OptDescConfService;
440 }
441
442
443 /**
444  * Getter for member Loglevel.
445  * @return Member Loglevel.
446  */
447 int Config::get_loglevel() const
448 {
449     return Loglevel;
450 }
451
452
453 /**
454  * Getter for member DaemonMode.
455  * @return TRUE if enabled, FALSE if disabled.
456  */
457 bool Config::get_daemon_mode() const
458 {
459     return DaemonMode;
460 }
461
462
463 /**
464  * Deletes the map with the previously parsed options.
465  * This is needed in case we reload the config and don't want the old cmd options to overwrite new config file options.
466  */
467 void Config::delete_variables_map()
468 {
469     VariablesMap.clear();
470
471     po::variables_map _variables_map;
472     VariablesMap = _variables_map;
473 }
474
475
476 /**
477  * Getter for member Syslog.
478  * @return True if logging through syslog is enabled, false otherwise.
479  */
480 bool Config::get_syslog() const
481 {
482     return Syslog;
483 }
484
485
486 /**
487  * Getter for member EnableIPv6
488  * @return Wether IPv6 should be used or not.
489  */
490 bool Config::get_enable_ipv6() const
491 {
492     return EnableIPv6;
493 }
494
495
496 /**
497  * Getter for member WebcheckIpUrl
498  * @return The primary IP Webcheck URL
499  */
500 string Config::get_webcheck_ip_url() const
501 {
502     return WebcheckIpUrl;
503 }
504
505
506 /**
507  * Getter for member WebcheckIpUrlAlt
508  * @return The alternative IP Webcheck URL
509  */
510 string Config::get_webcheck_ip_url_alt() const
511 {
512     return WebcheckIpUrlAlt;
513 }