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