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