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