OpenSDN source code
address_util.cc
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
3  * Copyright Contributors to the OpenSDN project
4  */
5 #include "base/address_util.h"
6 
7 #include <endian.h>
8 #include <boost/algorithm/string.hpp>
9 #include <boost/asio/io_service.hpp>
10 #include <boost/asio/ip/tcp.hpp>
11 #include <boost/asio/ip/host_name.hpp>
12 #include <boost/foreach.hpp>
13 
14 /* Returns true if the given IPv4 address is member of the IPv4 subnet
15  * indicated by IPv4 address and prefix length. Otherwise returns false.
16  * We convert both the input IPv4 addresses to their subnet addresses and
17  * then compare with each other to conclude whether the IPv4 address is
18  * member of the subnet or not.
19  */
21  const Ip4Address &ip, const Ip4Address &prefix_ip, uint16_t plen) {
22  Ip4Address prefix = Address::GetIp4SubnetAddress(prefix_ip, plen);
23  return ((prefix.to_ulong() | ~(0xFFFFFFFF << (32 - plen))) ==
24  (ip.to_ulong() | ~(0xFFFFFFFF << (32 - plen))));
25 }
26 
27 /* Returns true if the given IPv6 address is member of the IPv6 subnet
28  * indicated by IPv6 address and prefix length. Otherwise returns false.
29  */
31  const Ip6Address &ip, const Ip6Address &subnet, uint8_t plen) {
32  Ip6Address mask = Address::GetIp6SubnetAddress(subnet, plen);
34  return (ip1 == mask);
35 }
36 
37 /*
38  * Returns the canonical hostname (FQDN)
39 */
40 
41 std::string ResolveCanonicalName()
42 {
43  boost::asio::io_context io_service;
44  boost::system::error_code error;
45  boost::asio::ip::tcp::resolver resolver (io_service);
46  boost::asio::ip::tcp::resolver::query query(boost::asio::ip::host_name(),
47  "", boost::asio::ip::resolver_query_base::canonical_name);
48  boost::asio::ip::tcp::resolver::iterator iter =
49  resolver.resolve (query,error), end;
50  if (error) {
51  return boost::asio::ip::host_name();
52  }
53  while (iter != end) {
54  if (iter->host_name() != "") {
55  return iter->host_name();
56  }
57  iter++;
58  }
59  return boost::asio::ip::host_name();
60 }
61 
62 /*
63  * Returns the canonical hostname (FQDN) by IPv4 address
64 */
65 std::string ResolveCanonicalName(const std::string& ipv4)
66 {
67  if (boost::starts_with(ipv4, "127."))
68  return "localhost";
69  boost::asio::ip::tcp::endpoint endpoint;
70  boost::asio::io_context io_service;
71  boost::asio::ip::address_v4 ip =
72  boost::asio::ip::address_v4::from_string(ipv4);
73  endpoint.address(ip);
74  boost::asio::ip::tcp::resolver resolver(io_service);
75  boost::asio::ip::tcp::resolver::iterator iter =
76  resolver.resolve (endpoint), end;
77  while (iter != end){
78  if(iter->host_name() != ""){
79  return iter->host_name();
80  }
81  iter++;
82  }
83  return boost::asio::ip::host_name();
84 }
85 
86 /* This variant passes all tests
87  * To be covered by more tests later
88  * Returns the canonical hostname (FQDN) by IPv6 address
89 */
90 std::string ResolveCanonicalNameIPv6(const std::string& ipv6)
91 {
92  std::string loc_ip = ipv6;
93  if (boost::starts_with(loc_ip, "::1"))
94  return "localhost";
95  unsigned int perc_pos = loc_ip.find("%");
96  if (perc_pos != std::string::npos) {
97  loc_ip = loc_ip.substr(0,perc_pos);
98  }
99  return loc_ip;
100 // Next code is incompatible with schema_transformer:
101 // boost::asio::ip::tcp::endpoint endpoint;
102 // boost::asio::io_context io_service;
103 // boost::asio::ip::address_v6 ip =
104 // boost::asio::ip::address_v6::from_string(loc_ip);
105 // endpoint.address(ip);
106 // boost::asio::ip::tcp::resolver resolver(io_service);
107 // boost::asio::ip::tcp::resolver::iterator iter =
108 // resolver.resolve (endpoint), end;
109 // while (iter != end){
110 // if(iter->host_name() != ""){
111 // return iter->host_name();
112 // }
113 // iter++;
114 // }
115 // return boost::asio::ip::host_name();
116 }
117 
118 /*
119  * Returns boost::asio::ip::address if given string is either valid
120  * IPv4, IPv6 or a resolvable FQDN
121 */
122 
124  const std::string &ip_address_str,
125  boost::system::error_code *ec) {
126  IpAddress addr =
127  boost::asio::ip::address::from_string(ip_address_str, *ec);
128  boost::system::error_code error_code = *ec;
129  if (error_code.value() != 0) {
130  boost::asio::io_context io_service;
131  std::string ip_string = GetHostIp(&io_service, ip_address_str);
132  addr = boost::asio::ip::address::from_string(ip_string, *ec);
133  }
134  return addr;
135 }
136 
138  const Ip4Address &ip_prefix, uint16_t plen) {
139  Ip4Address subnet(ip_prefix.to_ulong() | ~(0xFFFFFFFF << (32 - plen)));
140  return subnet;
141 }
142 
143 // Validate IPv4/IPv6 address string.
144 bool ValidateIPAddressString(std::string ip_address_str,
145  std::string *error_msg) {
146  boost::system::error_code error;
147  AddressFromString(ip_address_str, &error);
148  if (error.value() != 0) {
149  std::ostringstream out;
150  out << "Invalid IP address: " << ip_address_str << std::endl;
151  *error_msg = out.str();
152  return false;
153  }
154  return true;
155 }
156 
157 IpAddress PrefixToIpNetmask(uint32_t prefix_len) {
158  uint32_t mask;
159 
160  if (prefix_len == 0) {
161  mask = 0;
162  } else {
163  mask = (~((1 << (32 - prefix_len)) - 1));
164  }
165  return IpAddress(Ip4Address(mask));
166 }
167 
168 uint32_t NetmaskToPrefix(uint32_t netmask) {
169  uint32_t count = 0;
170 
171  while (netmask) {
172  count++;
173  netmask = (netmask - 1) & netmask;
174  }
175  return count;
176 }
177 
179  if (plen == 0) {
180  return IpAddress(Ip6Address());
181  }
182 
183  if (plen == 128) {
184  boost::system::error_code ec;
185  Ip6Address all_fs = Ip6Address::from_string
186  ("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", ec);
187  return IpAddress(all_fs);
188  }
189 
190  Ip6Address::bytes_type bytes;
191 
192  int index = (int) (plen / 8);
193  int remain_mask = plen % 8;
194 
195  for (int i = 0; i < index; i++) {
196  bytes.at(i) = 0xff;
197  }
198 
199  switch (remain_mask) {
200  case 0:
201  bytes.at(index++) = 0;
202  break;
203  case 1:
204  bytes.at(index++) = 0x80;
205  break;
206  case 2:
207  bytes.at(index++) = 0xc0;
208  break;
209  case 3:
210  bytes.at(index++) = 0xe0;
211  break;
212  case 4:
213  bytes.at(index++) = 0xf0;
214  break;
215  case 5:
216  bytes.at(index++) = 0xf8;
217  break;
218  case 6:
219  bytes.at(index++) = 0xfc;
220  break;
221  case 7:
222  bytes.at(index++) = 0xfe;
223  break;
224  }
225 
226  for (int i = index; i < 16; ++i) {
227  bytes.at(i) = 0;
228  }
229 
230  return IpAddress(Ip6Address(bytes));
231 }
232 
233 // Validate a list of <ip-address>:<port> endpoints.
234 bool ValidateServerEndpoints(std::vector<std::string> list,
235  std::string *error_msg) {
236  std::ostringstream out;
237 
238  BOOST_FOREACH(std::string endpoint, list) {
239  std::vector<std::string> tokens;
240  boost::split(tokens, endpoint, boost::is_any_of(":"));
241  if (tokens.size() != 2) {
242  out << "Invalid endpoint " << endpoint << std::endl;
243  *error_msg = out.str();
244  return false;
245  }
246 
247  boost::system::error_code error;
248  AddressFromString(tokens[0], &error);
249 
250  if (error) {
251  out << "Invalid IP address: " << tokens[0] << std::endl;
252  *error_msg = out.str();
253  return false;
254  }
255 
256  unsigned long port = strtoul(tokens[1].c_str(), NULL, 0);
257  if (errno || port > 0xffFF) {
258  out << "Invalid port : " << tokens[1];
259  if (errno) {
260  out << " " << strerror(errno) << std::endl;
261  }
262  *error_msg = out.str();
263  return false;
264  }
265  }
266 
267  return true;
268 }
269 
270 // Return IP address string for a host if it is resolvable, empty string
271 // otherwise.
272 std::string GetHostIp(boost::asio::io_context *io_service,
273  const std::string &hostname) {
274  boost::asio::ip::tcp::resolver::iterator iter, end;
275  boost::system::error_code error;
276  boost::asio::ip::tcp::resolver resolver(*io_service);
277  boost::asio::ip::tcp::resolver::query query(hostname, "");
278 
279  std::string result;
280 
281  iter = resolver.resolve(query, error);
282  if (error) {
283  return result;
284  }
285 
286  for (; iter != end; ++iter) {
287  const boost::asio::ip::address &addr = iter->endpoint().address();
288  if (addr.is_v6()) {
289  boost::asio::ip::address_v6 addr6 = addr.to_v6();
290  if (addr6.is_link_local()) {
291  continue;
292  }
293  }
294  result = addr.to_string();
295  if (addr.is_v4()) {
296  return result;
297  }
298  }
299  return result;
300 }
301 
302 //
303 // Get VN name from routing instance
304 //
305 std::string GetVNFromRoutingInstance(const std::string &vn) {
306  std::vector<std::string> tokens;
307  boost::split(tokens, vn, boost::is_any_of(":"), boost::token_compress_on);
308  if (tokens.size() < 3) return "";
309  return tokens[0] + ":" + tokens[1] + ":" + tokens[2];
310 }
311 
312 void IpToU64(const IpAddress &sip, const IpAddress &dip,
313  uint64_t *sip_u, uint64_t *sip_l,
314  uint64_t *dip_u, uint64_t *dip_l) {
315  if (sip.is_v4()) {
316  *sip_l = htonl(sip.to_v4().to_ulong());
317  *sip_u = 0;
318  } else {
319  uint64_t data[2];
320  Ip6AddressToU64Array(sip.to_v6(), data, 2);
321  *sip_u = data[0];
322  *sip_l = data[1];
323  }
324 
325  if (dip.is_v4()) {
326  *dip_l = htonl(dip.to_v4().to_ulong());
327  *dip_u = 0;
328  } else {
329  uint64_t data[2];
330  Ip6AddressToU64Array(dip.to_v6(), data, 2);
331  *dip_u = data[0];
332  *dip_l = data[1];
333  }
334 }
335 
336 void U64ToIpv6(uint64_t upper, uint64_t lower, IpAddress *ip) {
337  boost::asio::ip::address_v6::bytes_type bytes;
338  const unsigned char *ptr = (const unsigned char *)&lower;
339  for (unsigned int i = 0; i < sizeof(uint64_t); i++) {
340  bytes[i] = ptr[i];
341  }
342  ptr = (const unsigned char *)&upper;
343  for (unsigned int i = 0; i < sizeof(uint64_t); i++) {
344  bytes[8 + i] = ptr[i];
345  }
346  *ip = Ip6Address(bytes);
347 }
348 
349 void U64ToIp(uint64_t sip_u, uint64_t sip_l, uint64_t dip_u, uint64_t dip_l,
350  int family, IpAddress *sip, IpAddress *dip) {
351  if (family == Address::INET) {
352  *sip = Ip4Address(ntohl(sip_l & 0xFFFFFFFF));
353  *dip = Ip4Address(ntohl(dip_l & 0xFFFFFFFF));
354  } else {
355  U64ToIpv6(sip_u, sip_l, sip);
356  U64ToIpv6(dip_u, dip_l, dip);
357  }
358 }
359 
360 void Ip6AddressToU64Array(const Ip6Address &addr, uint64_t *arr, int size) {
361  unsigned char b[16];
362  uint64_t ip;
363  unsigned int i, j, k;
364 
365  if (size != 2)
366  return;
367 
368  memcpy(b, addr.to_bytes().data(), sizeof(b));
369 
370  for (i = 0, j = 0, k = 0; i < 4; i++, j = j+4) {
371  ip = 0;
372 
373  ip = ((((uint32_t)b[j]) << 24) & 0xFF000000) |
374  ((((uint32_t)b[j+1]) << 16) & 0x00FF0000) |
375  ((((uint32_t)b[j+2]) << 8) & 0x0000FF00) |
376  (((uint32_t)b[j+3]) & 0x000000FF);
377 
378  if (i >= 2)
379  k = 1;
380 
381  if (i%2) {
382  arr[k] = arr[k] | (ip & 0x00000000FFFFFFFFU);
383  } else {
384  arr[k] = (ip << 32) & 0xFFFFFFFF00000000U;
385  }
386  }
387 
388 
389  arr[0] = htobe64(arr[0]);
390  arr[1] = htobe64(arr[1]);
391 }
392 
393 std::string VectorIpv6ToString(const std::vector<signed char> &ipv6) {
394 
395  if (ipv6.size() != 16) {
396  return "0000:0000:0000:0000";
397  }
398  std::ostringstream strm;
399  int count = 1;
400  for(std::vector<signed char>::const_iterator it = ipv6.begin();
401  it != ipv6.end(); ++it) {
402  strm << std::hex << (int)((uint8_t) *it);
403  if((count % 4) ==0)
404  strm << ":";
405  count++;
406  }
407  return strm.str();
408 }
boost::asio::ip::address_v6 Ip6Address
Definition: address.h:16
boost::asio::ip::address IpAddress
Definition: address.h:14
boost::asio::ip::address_v4 Ip4Address
Definition: address.h:15
void U64ToIp(uint64_t sip_u, uint64_t sip_l, uint64_t dip_u, uint64_t dip_l, int family, IpAddress *sip, IpAddress *dip)
bool IsIp6SubnetMember(const Ip6Address &ip, const Ip6Address &subnet, uint8_t plen)
Definition: address_util.cc:30
std::string ResolveCanonicalNameIPv6(const std::string &ipv6)
Definition: address_util.cc:90
std::string VectorIpv6ToString(const std::vector< signed char > &ipv6)
void IpToU64(const IpAddress &sip, const IpAddress &dip, uint64_t *sip_u, uint64_t *sip_l, uint64_t *dip_u, uint64_t *dip_l)
std::string GetHostIp(boost::asio::io_context *io_service, const std::string &hostname)
IpAddress PrefixToIpNetmask(uint32_t prefix_len)
std::string GetVNFromRoutingInstance(const std::string &vn)
bool IsIp4SubnetMember(const Ip4Address &ip, const Ip4Address &prefix_ip, uint16_t plen)
Definition: address_util.cc:20
uint32_t NetmaskToPrefix(uint32_t netmask)
bool ValidateServerEndpoints(std::vector< std::string > list, std::string *error_msg)
Ip4Address GetIp4SubnetBroadcastAddress(const Ip4Address &ip_prefix, uint16_t plen)
bool ValidateIPAddressString(std::string ip_address_str, std::string *error_msg)
void U64ToIpv6(uint64_t upper, uint64_t lower, IpAddress *ip)
void Ip6AddressToU64Array(const Ip6Address &addr, uint64_t *arr, int size)
IpAddress PrefixToIp6Netmask(uint32_t plen)
std::string ResolveCanonicalName()
Definition: address_util.cc:41
IpAddress AddressFromString(const std::string &ip_address_str, boost::system::error_code *ec)
static Ip4Address GetIp4SubnetAddress(const Ip4Address &prefix, uint16_t plen)
Definition: address.cc:180
@ INET
Definition: address.h:27
static Ip6Address GetIp6SubnetAddress(const Ip6Address &prefix, uint16_t plen)
Definition: address.cc:201