2 * @brief IPHelper class implementation. This class represents a Helper to get the actual IP.
6 * @copyright Intra2net AG
10 #include "ip_addr_helper.h"
11 #include <boost/asio.hpp>
12 #include <boost/regex.hpp>
13 #include <arpa/inet.h>
14 #include <sys/socket.h>
21 namespace net = boost::asio;
24 * Default constructor.
26 IPAddrHelper::IPAddrHelper()
39 IPAddrHelper::IPAddrHelper(const Logger::Ptr _log, const string& _webcheck_url, const string& _webcheck_url_alt, const int _webcheck_interval, const int _last_webcheck ,const bool _use_ipv6, const string& _proxy, const int _proxy_port)
41 , WebcheckIpUrl(_webcheck_url)
42 , WebcheckIpUrlAlt(_webcheck_url_alt)
43 , WebcheckInterval(_webcheck_interval)
44 , LastWebcheck(_last_webcheck)
46 , ProxyPort(_proxy_port)
49 Hostname = net::ip::host_name();
50 Log->print_hostname(Hostname);
57 IPAddrHelper::~IPAddrHelper()
63 * Tests if a given IP is a local IPv6 address
64 * @param ip The IP to test
65 * @return true if given IP is local, false if not.
67 bool IPAddrHelper::is_local_ipv6(const string ip) const
70 boost::regex expr_any_ipv6("^::$");
73 boost::regex expr_loopback_ipv6("^::1$");
75 // IPV6 local unicast address
76 boost::regex expr_local_unicast_ipv6("^fc00:");
79 boost::regex expr_link_local_ipv6("^fe[8,9,a,b]{1}");
82 boost::regex expr_site_local_ipv6("^fe[c,d,e,f]{1}");
84 // It's time to test against the regex patterns
85 if ( boost::regex_search(ip,expr_any_ipv6) )
87 Log->print_regex_match(expr_any_ipv6.str(),ip);
90 else if ( boost::regex_search(ip,expr_loopback_ipv6) )
92 Log->print_regex_match(expr_loopback_ipv6.str(),ip);
95 else if ( boost::regex_search(ip,expr_local_unicast_ipv6) )
97 Log->print_regex_match(expr_local_unicast_ipv6.str(),ip);
100 else if ( boost::regex_search(ip,expr_link_local_ipv6) )
102 Log->print_regex_match(expr_link_local_ipv6.str(),ip);
105 else if ( boost::regex_search(ip,expr_site_local_ipv6) )
107 Log->print_regex_match(expr_site_local_ipv6.str(),ip);
116 * Tests if a given IP is a local IPv4 address
117 * @param ip The IP to test
118 * @return true if given IP is local, false if not.
120 bool IPAddrHelper::is_local_ipv4(const string ip) const
123 boost::regex expr_loopback("127\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}");
126 boost::regex expr_192("192\\.168\\.[0-9]{1,3}\\.[0-9]{1,3}");
129 boost::regex expr_10("10\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}");
132 boost::regex expr_169_254("169\\.254\\.[0-9]{1,3}\\.[0-9]{1,3}");
134 // 172.16.x.x -> 172.31.x.x
135 boost::regex expr_172_1("172\\.1[6-9]{1}\\.[0-9]{1,3}\\.[0-9]{1,3}");
136 boost::regex expr_172_2("172\\.2[0-9]{1}\\.[0-9]{1,3}\\.[0-9]{1,3}");
137 boost::regex expr_172_3("172\\.3[0-1]{1}\\.[0-9]{1,3}\\.[0-9]{1,3}");
139 // It's time to test against the regex patterns
140 if ( boost::regex_search(ip,expr_loopback) )
142 Log->print_regex_match(expr_loopback.str(),ip);
145 else if ( boost::regex_search(ip,expr_192) )
147 Log->print_regex_match(expr_192.str(),ip);
150 else if ( boost::regex_search(ip,expr_10) )
152 Log->print_regex_match(expr_10.str(),ip);
155 else if ( boost::regex_search(ip,expr_169_254) )
157 Log->print_regex_match(expr_169_254.str(),ip);
160 else if ( boost::regex_search(ip,expr_172_1) )
162 Log->print_regex_match(expr_172_1.str(),ip);
165 else if ( boost::regex_search(ip,expr_172_2) )
167 Log->print_regex_match(expr_172_2.str(),ip);
170 else if ( boost::regex_search(ip,expr_172_3) )
172 Log->print_regex_match(expr_172_3.str(),ip);
181 * Get the actual IP of this host through a conventional DNS query or through a IP webcheck URL if configured so.
182 * @return A string representation of the actual IP in dotted format or an empty string if something went wrong.
184 string IPAddrHelper::get_actual_ip()
188 if ( WebcheckIpUrl.empty() )
189 ip = get_local_wan_nic_ip();
198 * Get the IP address of the local wan interface if there is one.
199 * @return The IP address of the wan interface or an empty string if something went wrong.
201 string IPAddrHelper::get_local_wan_nic_ip()
203 struct ifaddrs *if_addr_struct, *ifa;
204 int address_family, ret_val;
205 char ip_addr_buff[NI_MAXHOST];
206 list<string> external_ipv4_addresses;
207 list<string> external_ipv6_addresses;
209 // Get linked list of all interface addresses.
210 if ( getifaddrs(&if_addr_struct) == -1 )
212 Log->print_error_getting_local_wan_ip("getifaddrs", strerror(errno));
213 freeifaddrs(if_addr_struct);
217 // Iterate through the linked list.
218 for ( ifa = if_addr_struct; ifa != NULL; ifa = ifa->ifa_next)
220 // Get the address family of the actual address.
221 address_family = ifa->ifa_addr->sa_family;
223 // If it is an IPv4 then process further.
224 if ( address_family == AF_INET )
226 // Translate the address to a protocol independent representation (dottet format). Copy address into ip_addr_buff.
227 ret_val = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), ip_addr_buff, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
230 Log->print_error_getting_local_wan_ip("getnameinfo", gai_strerror(ret_val));
231 freeifaddrs(if_addr_struct);
235 // Generate IPv4 string out of char array.
236 string ipv4_addr(ip_addr_buff);
238 Log->print_own_ipv4(ipv4_addr, Hostname);
240 // Test if it is a local address.
241 if ( !is_local_ipv4(ipv4_addr) )
242 external_ipv4_addresses.push_back(ipv4_addr);
244 Log->print_ip_is_local(ipv4_addr);
246 // If it is an IPv6 address and IPv6 is enabled then process further.
247 else if ( (address_family == AF_INET6) && (UseIPv6 == true) )
249 // Translate the address to a protocol independent representation (dottet format). Copy address into ip_addr_buff.
250 ret_val = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in6), ip_addr_buff, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
253 Log->print_error_getting_local_wan_ip("getnameinfo", gai_strerror(ret_val));
254 freeifaddrs(if_addr_struct);
258 // Generate IPv6 string out of char array.
259 string ipv6_addr(ip_addr_buff);
261 Log->print_own_ipv6(ipv6_addr, Hostname);
263 // Test if it is a local address.
264 if ( !is_local_ipv6(ipv6_addr) )
265 external_ipv6_addresses.push_back(ipv6_addr);
267 Log->print_ip_is_local(ipv6_addr);
270 freeifaddrs(if_addr_struct);
272 // Return the first element in IPv6 list if IPv6 is enabled, otherwise return first element in IPv4 list.
273 if ( (UseIPv6 == true) && (!external_ipv6_addresses.empty()) )
274 return external_ipv6_addresses.front();
275 else if ( !external_ipv4_addresses.empty() )
276 return external_ipv4_addresses.front();
283 * Get the actual IP of the given host through a DNS query.
284 * @param _hostname The hostname for the dns lookup, if empty string, then perform a dns lookup to the local hostname.
285 * @return A string representation of the actual IP in dotted format or an empty string if something went wrong.
287 string IPAddrHelper::dns_query(const string& _hostname) const
289 list<string> external_ipv4_addresses;
290 list<string> external_ipv6_addresses;
292 // Init the hostname with the given _hostname or with local Hostname if empty.
293 string hostname = Hostname;
294 if ( !_hostname.empty() )
295 hostname = _hostname;
299 // BOOST asio isn't the simplest way to perform a DNS lookup, but it works just fine.
300 net::io_service io_service;
301 net::ip::tcp::resolver resolver(io_service);
303 // Define the DNS query.
304 net::ip::tcp::resolver::query query(hostname, "0", net::ip::resolver_query_base::address_configured | net::ip::resolver_query_base::all_matching);
306 // Perform the DNS query.
307 net::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
308 net::ip::tcp::resolver::iterator end;
310 // Iterate through the returned IP addresses.
311 while(endpoint_iterator != end)
313 // Get the IP address out of the endpoint iterator.
315 ip = endpoint_iterator->endpoint().address();
317 // Test if it is a IPv4 address.
320 // Get the string representation.
321 string ipv4_addr = ip.to_string();
323 Log->print_own_ipv4(ipv4_addr, hostname);
325 // If it is not a local address then push it in the external ipv4 address list.
326 if ( !is_local_ipv4(ipv4_addr) )
327 external_ipv4_addresses.push_back(ipv4_addr);
329 Log->print_ip_is_local(ipv4_addr);
331 // Test if it is a IPv6 address and if IPv6 is enabled.
332 else if ( (ip.is_v6()) && (UseIPv6 == true) )
334 // Get the string representation.
335 string ipv6_addr = ip.to_string();
337 Log->print_own_ipv6(ipv6_addr, hostname);
339 // If it is not a local address then push it in the external ipv6 address list.
340 if ( !is_local_ipv6(ipv6_addr) )
341 external_ipv6_addresses.push_back(ipv6_addr);
343 Log->print_ip_is_local(ipv6_addr);
351 Log->print_error_hostname_to_ip(e.what(),hostname);
355 // Return the first element in IPv6 list if IPv6 is enabled, otherwise return first element in IPv4 list.
356 if ( (UseIPv6 == true) && (!external_ipv6_addresses.empty()) )
357 return external_ipv6_addresses.front();
358 else if ( !external_ipv4_addresses.empty() )
359 return external_ipv4_addresses.front();
361 // Could not get a external IP address, so return empty string.
367 * Get the actual IP of this host through a IP webcheck URL.
368 * @return A string representation of the actual IP in dotted format or an empty string if something went wrong.
370 string IPAddrHelper::webcheck_ip()
372 // Init IPAddress with a empty string.
375 // Get the current time.
376 int current_time = time(NULL);
378 // Test if webcheck is allowed due to webcheck_interval.
379 if ( (LastWebcheck + (WebcheckInterval*60)) >= current_time )
381 // Webcheck not allowed, log it and return empty string.
382 Log->print_webcheck_exceed_interval( LastWebcheck, (WebcheckInterval*60), current_time );
387 string curl_writedata_buff;
388 char curl_err_buff[CURL_ERROR_SIZE];
392 list<string> url_list;
393 url_list.push_back(WebcheckIpUrl);
394 url_list.push_back(WebcheckIpUrlAlt);
398 CURL * curl_easy_handle = init_curl(curl_writedata_buff,curl_err_buff);
400 // If perform_curl_operation returns a connection problem indicating return code, try the next ip webcheck url if there is one.
401 while ( (curl_err_code == 1) && (url_list.size() != 0) && (url_list.front() != "") )
404 actual_url = url_list.front();
405 url_list.pop_front();
406 set_curl_url(curl_easy_handle,actual_url);
408 // Perform curl operation, err_code of 1 indicated connection problem, so try next url.
409 curl_err_code = perform_curl_operation(curl_easy_handle, curl_err_buff, actual_url);
412 // Cleanup CURL handle
413 curl_easy_cleanup(curl_easy_handle);
415 // If curl_err_code is not 0, the ip couldn't be determined through any configured webcheck url.
416 if ( curl_err_code != 0 )
418 // Log it and return the empty string.
419 Log->print_webcheck_no_ip();
423 // Log the received curl data.
424 Log->print_received_curl_data(curl_writedata_buff);
426 // Try to parse a IPv4 address out of the received data.
427 ip_addr = parse_ipv4(curl_writedata_buff);
429 // TODO: Parsing of IPv6 address out of received curl data via webcheck IP.
431 if ( !ip_addr.empty() )
433 // Got a IPv4 address out of the received data.
434 Log->print_own_ipv4(ip_addr, Hostname);
441 // Set the LastWebcheck time to current time.
442 LastWebcheck = current_time;
444 // If IP is within a private range then return ""
445 if ( is_local_ipv4(ip_addr) )
447 Log->print_ip_is_local(ip_addr);
451 // Return the parsed IPAddress.
457 * Tries to find a IPv4 Address in dottet format in a given string and returns the IP-Address found.
458 * @param data The string data to search in for a valid IPv4-Address.
459 * @return The IP Address found or an empty string.
461 string IPAddrHelper::parse_ipv4(const string& data) const
465 // Regex for ipv4 address in dottet format
466 boost::regex expr("([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})");
468 boost::smatch matches;
470 if ( boost::regex_search(data,matches,expr) )
473 Log->print_regex_match(expr.str(),ip);
477 Log->print_regex_ip_not_found(data);
485 * Performs the curl operation.
486 * @param curl_easy_handle The initialized and configured curl handle.
487 * @param curl_err_buff The pointer to the curl error buffer to get error messages from.
488 * @param actual_url The actual configured URL.
489 * @return 0 if all is fine, 1 if an connection problem to the configured url occurs, -1 on other errors.
491 int IPAddrHelper::perform_curl_operation(CURL * curl_easy_handle, char* curl_err_buff, const string& actual_url) const
494 if ( (curl_err_code = curl_easy_perform(curl_easy_handle) ) != 0 )
496 // CURL error occured
497 if ( (curl_err_code == CURLE_COULDNT_CONNECT) || (curl_err_code == CURLE_OPERATION_TIMEOUTED) || (curl_err_code == CURLE_COULDNT_RESOLVE_HOST) )
499 // In case of connection problems we should return 1, that the fallback url will be used.
500 Log->print_webcheck_url_connection_problem(curl_err_buff, actual_url);
506 Log->print_webcheck_error(curl_err_buff, actual_url);
510 // Operation performed without any problems
516 * Sets a url to the easy curl handle
517 * @param curl_easy_handle The easy curl handle to set the url for.
518 * @param url The url to set.
520 void IPAddrHelper::set_curl_url(CURL * curl_easy_handle, const string& url) const
522 curl_easy_setopt(curl_easy_handle,CURLOPT_URL,url.c_str());
527 * Initialized curl easy handle with a few options.
528 * @param curl_writedata_buff Reference to a string wich will be filled with the curl result
529 * @param curl_err_buff A pointer to an char array which will be filled with error message.
530 * @return A pointer to the easy curl handle.
532 CURL * IPAddrHelper::init_curl(string& curl_writedata_buff,char* curl_err_buff) const
534 CURL *curl_easy_handle = curl_easy_init();
536 curl_easy_setopt(curl_easy_handle,CURLOPT_NOPROGRESS,1);
537 curl_easy_setopt(curl_easy_handle,CURLOPT_CONNECTTIMEOUT,5);
538 curl_easy_setopt(curl_easy_handle,CURLOPT_TIMEOUT,10);
539 curl_easy_setopt(curl_easy_handle,CURLOPT_BUFFERSIZE,1024);
540 curl_easy_setopt(curl_easy_handle,CURLOPT_ERRORBUFFER,curl_err_buff);
541 curl_easy_setopt(curl_easy_handle,CURLOPT_WRITEFUNCTION,http_receive);
542 curl_easy_setopt(curl_easy_handle,CURLOPT_WRITEDATA,&curl_writedata_buff);
544 if ( !Proxy.empty() )
546 curl_easy_setopt(curl_easy_handle,CURLOPT_PROXY,Proxy.c_str());
547 curl_easy_setopt(curl_easy_handle,CURLOPT_PROXYPORT,ProxyPort);
550 return curl_easy_handle;
555 * Callback Function is called every time CURL is receiving data from HTTPS-Server and will copy all received Data to the given stream pointer
556 * @param inBuffer Pointer to input.
557 * @param size How many mem blocks are received
558 * @param nmemb size of each memblock
559 * @param outBuffer Pointer to output stream.
560 * @return The size received.
562 int IPAddrHelper::http_receive( char *inBuffer, size_t size, size_t nmemb, string *outBuffer )
564 outBuffer->append(inBuffer);
570 * Get member LastWebcheck
571 * @return LastWebcheck
573 int IPAddrHelper::get_last_webcheck() const