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