1 /*
2  *  Copyright 2004 The WebRTC Project Authors. All rights reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #if defined(WEBRTC_POSIX)
12 #include <netinet/in.h>
13 #include <sys/socket.h>
14 #ifdef OPENBSD
15 #include <netinet/in_systm.h>
16 #endif
17 #ifndef __native_client__
18 #include <netinet/ip.h>
19 #endif
20 #include <netdb.h>
21 #endif
22 
23 #include "rtc_base/byte_order.h"
24 #include "rtc_base/ip_address.h"
25 #include "rtc_base/net_helpers.h"
26 #include "rtc_base/string_utils.h"
27 
28 #if defined(WEBRTC_WIN)
29 #include "rtc_base/win32.h"
30 #endif  // WEBRTC_WIN
31 
32 namespace rtc {
33 
34 // Prefixes used for categorizing IPv6 addresses.
35 static const in6_addr kV4MappedPrefix = {
36     {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0}}};
37 static const in6_addr k6To4Prefix = {{{0x20, 0x02, 0}}};
38 static const in6_addr kTeredoPrefix = {{{0x20, 0x01, 0x00, 0x00}}};
39 static const in6_addr kV4CompatibilityPrefix = {{{0}}};
40 static const in6_addr k6BonePrefix = {{{0x3f, 0xfe, 0}}};
41 static const in6_addr kPrivateNetworkPrefix = {{{0xFD}}};
42 
43 static bool IPIsHelper(const IPAddress& ip,
44                        const in6_addr& tomatch,
45                        int length);
46 static in_addr ExtractMappedAddress(const in6_addr& addr);
47 
v4AddressAsHostOrderInteger() const48 uint32_t IPAddress::v4AddressAsHostOrderInteger() const {
49   if (family_ == AF_INET) {
50     return NetworkToHost32(u_.ip4.s_addr);
51   } else {
52     return 0;
53   }
54 }
55 
overhead() const56 int IPAddress::overhead() const {
57   switch (family_) {
58     case AF_INET:  // IPv4
59       return 20;
60     case AF_INET6:  // IPv6
61       return 40;
62     default:
63       return 0;
64   }
65 }
66 
IsNil() const67 bool IPAddress::IsNil() const {
68   return IPIsUnspec(*this);
69 }
70 
Size() const71 size_t IPAddress::Size() const {
72   switch (family_) {
73     case AF_INET:
74       return sizeof(in_addr);
75     case AF_INET6:
76       return sizeof(in6_addr);
77   }
78   return 0;
79 }
80 
operator ==(const IPAddress & other) const81 bool IPAddress::operator==(const IPAddress& other) const {
82   if (family_ != other.family_) {
83     return false;
84   }
85   if (family_ == AF_INET) {
86     return memcmp(&u_.ip4, &other.u_.ip4, sizeof(u_.ip4)) == 0;
87   }
88   if (family_ == AF_INET6) {
89     return memcmp(&u_.ip6, &other.u_.ip6, sizeof(u_.ip6)) == 0;
90   }
91   return family_ == AF_UNSPEC;
92 }
93 
operator !=(const IPAddress & other) const94 bool IPAddress::operator!=(const IPAddress& other) const {
95   return !((*this) == other);
96 }
97 
operator >(const IPAddress & other) const98 bool IPAddress::operator>(const IPAddress& other) const {
99   return (*this) != other && !((*this) < other);
100 }
101 
operator <(const IPAddress & other) const102 bool IPAddress::operator<(const IPAddress& other) const {
103   // IPv4 is 'less than' IPv6
104   if (family_ != other.family_) {
105     if (family_ == AF_UNSPEC) {
106       return true;
107     }
108     if (family_ == AF_INET && other.family_ == AF_INET6) {
109       return true;
110     }
111     return false;
112   }
113   // Comparing addresses of the same family.
114   switch (family_) {
115     case AF_INET: {
116       return NetworkToHost32(u_.ip4.s_addr) <
117              NetworkToHost32(other.u_.ip4.s_addr);
118     }
119     case AF_INET6: {
120       return memcmp(&u_.ip6.s6_addr, &other.u_.ip6.s6_addr, 16) < 0;
121     }
122   }
123   // Catches AF_UNSPEC and invalid addresses.
124   return false;
125 }
126 
ipv6_address() const127 in6_addr IPAddress::ipv6_address() const {
128   return u_.ip6;
129 }
130 
ipv4_address() const131 in_addr IPAddress::ipv4_address() const {
132   return u_.ip4;
133 }
134 
ToString() const135 std::string IPAddress::ToString() const {
136   if (family_ != AF_INET && family_ != AF_INET6) {
137     return std::string();
138   }
139   char buf[INET6_ADDRSTRLEN] = {0};
140   const void* src = &u_.ip4;
141   if (family_ == AF_INET6) {
142     src = &u_.ip6;
143   }
144   if (!rtc::inet_ntop(family_, src, buf, sizeof(buf))) {
145     return std::string();
146   }
147   return std::string(buf);
148 }
149 
ToSensitiveString() const150 std::string IPAddress::ToSensitiveString() const {
151 #if !defined(NDEBUG)
152   // Return non-stripped in debug.
153   return ToString();
154 #else
155   switch (family_) {
156     case AF_INET: {
157       std::string address = ToString();
158       size_t find_pos = address.rfind('.');
159       if (find_pos == std::string::npos)
160         return std::string();
161       address.resize(find_pos);
162       address += ".x";
163       return address;
164     }
165     case AF_INET6: {
166       std::string result;
167       result.resize(INET6_ADDRSTRLEN);
168       in6_addr addr = ipv6_address();
169       size_t len = snprintf(&(result[0]), result.size(), "%x:%x:%x:x:x:x:x:x",
170                             (addr.s6_addr[0] << 8) + addr.s6_addr[1],
171                             (addr.s6_addr[2] << 8) + addr.s6_addr[3],
172                             (addr.s6_addr[4] << 8) + addr.s6_addr[5]);
173       result.resize(len);
174       return result;
175     }
176   }
177   return std::string();
178 #endif
179 }
180 
Normalized() const181 IPAddress IPAddress::Normalized() const {
182   if (family_ != AF_INET6) {
183     return *this;
184   }
185   if (!IPIsV4Mapped(*this)) {
186     return *this;
187   }
188   in_addr addr = ExtractMappedAddress(u_.ip6);
189   return IPAddress(addr);
190 }
191 
AsIPv6Address() const192 IPAddress IPAddress::AsIPv6Address() const {
193   if (family_ != AF_INET) {
194     return *this;
195   }
196   in6_addr v6addr = kV4MappedPrefix;
197   ::memcpy(&v6addr.s6_addr[12], &u_.ip4.s_addr, sizeof(u_.ip4.s_addr));
198   return IPAddress(v6addr);
199 }
200 
operator ==(const InterfaceAddress & other) const201 bool InterfaceAddress::operator==(const InterfaceAddress& other) const {
202   return ipv6_flags_ == other.ipv6_flags() &&
203          static_cast<const IPAddress&>(*this) == other;
204 }
205 
operator !=(const InterfaceAddress & other) const206 bool InterfaceAddress::operator!=(const InterfaceAddress& other) const {
207   return !((*this) == other);
208 }
209 
operator =(const InterfaceAddress & other)210 const InterfaceAddress& InterfaceAddress::operator=(
211     const InterfaceAddress& other) {
212   ipv6_flags_ = other.ipv6_flags_;
213   static_cast<IPAddress&>(*this) = other;
214   return *this;
215 }
216 
ToString() const217 std::string InterfaceAddress::ToString() const {
218   std::string result = IPAddress::ToString();
219 
220   if (family() == AF_INET6)
221     result += "|flags:0x" + rtc::ToHex(ipv6_flags());
222 
223   return result;
224 }
225 
IPIsPrivateNetworkV4(const IPAddress & ip)226 static bool IPIsPrivateNetworkV4(const IPAddress& ip) {
227   uint32_t ip_in_host_order = ip.v4AddressAsHostOrderInteger();
228   return ((ip_in_host_order >> 24) == 10) ||
229          ((ip_in_host_order >> 20) == ((172 << 4) | 1)) ||
230          ((ip_in_host_order >> 16) == ((192 << 8) | 168));
231 }
232 
IPIsPrivateNetworkV6(const IPAddress & ip)233 static bool IPIsPrivateNetworkV6(const IPAddress& ip) {
234   return IPIsHelper(ip, kPrivateNetworkPrefix, 8);
235 }
236 
IPIsPrivateNetwork(const IPAddress & ip)237 bool IPIsPrivateNetwork(const IPAddress& ip) {
238   switch (ip.family()) {
239     case AF_INET: {
240       return IPIsPrivateNetworkV4(ip);
241     }
242     case AF_INET6: {
243       return IPIsPrivateNetworkV6(ip);
244     }
245   }
246   return false;
247 }
248 
IPIsSharedNetworkV4(const IPAddress & ip)249 static bool IPIsSharedNetworkV4(const IPAddress& ip) {
250   uint32_t ip_in_host_order = ip.v4AddressAsHostOrderInteger();
251   return (ip_in_host_order >> 22) == ((100 << 2) | 1);
252 }
253 
IPIsSharedNetwork(const IPAddress & ip)254 bool IPIsSharedNetwork(const IPAddress& ip) {
255   if (ip.family() == AF_INET) {
256     return IPIsSharedNetworkV4(ip);
257   }
258   return false;
259 }
260 
ExtractMappedAddress(const in6_addr & in6)261 in_addr ExtractMappedAddress(const in6_addr& in6) {
262   in_addr ipv4;
263   ::memcpy(&ipv4.s_addr, &in6.s6_addr[12], sizeof(ipv4.s_addr));
264   return ipv4;
265 }
266 
IPFromAddrInfo(struct addrinfo * info,IPAddress * out)267 bool IPFromAddrInfo(struct addrinfo* info, IPAddress* out) {
268   if (!info || !info->ai_addr) {
269     return false;
270   }
271   if (info->ai_addr->sa_family == AF_INET) {
272     sockaddr_in* addr = reinterpret_cast<sockaddr_in*>(info->ai_addr);
273     *out = IPAddress(addr->sin_addr);
274     return true;
275   } else if (info->ai_addr->sa_family == AF_INET6) {
276     sockaddr_in6* addr = reinterpret_cast<sockaddr_in6*>(info->ai_addr);
277     *out = IPAddress(addr->sin6_addr);
278     return true;
279   }
280   return false;
281 }
282 
IPFromString(const std::string & str,IPAddress * out)283 bool IPFromString(const std::string& str, IPAddress* out) {
284   if (!out) {
285     return false;
286   }
287   in_addr addr;
288   if (rtc::inet_pton(AF_INET, str.c_str(), &addr) == 0) {
289     in6_addr addr6;
290     if (rtc::inet_pton(AF_INET6, str.c_str(), &addr6) == 0) {
291       *out = IPAddress();
292       return false;
293     }
294     *out = IPAddress(addr6);
295   } else {
296     *out = IPAddress(addr);
297   }
298   return true;
299 }
300 
IPFromString(const std::string & str,int flags,InterfaceAddress * out)301 bool IPFromString(const std::string& str, int flags, InterfaceAddress* out) {
302   IPAddress ip;
303   if (!IPFromString(str, &ip)) {
304     return false;
305   }
306 
307   *out = InterfaceAddress(ip, flags);
308   return true;
309 }
310 
IPIsAny(const IPAddress & ip)311 bool IPIsAny(const IPAddress& ip) {
312   switch (ip.family()) {
313     case AF_INET:
314       return ip == IPAddress(INADDR_ANY);
315     case AF_INET6:
316       return ip == IPAddress(in6addr_any) || ip == IPAddress(kV4MappedPrefix);
317     case AF_UNSPEC:
318       return false;
319   }
320   return false;
321 }
322 
IPIsLoopbackV4(const IPAddress & ip)323 static bool IPIsLoopbackV4(const IPAddress& ip) {
324   uint32_t ip_in_host_order = ip.v4AddressAsHostOrderInteger();
325   return ((ip_in_host_order >> 24) == 127);
326 }
327 
IPIsLoopbackV6(const IPAddress & ip)328 static bool IPIsLoopbackV6(const IPAddress& ip) {
329   return ip == IPAddress(in6addr_loopback);
330 }
331 
IPIsLoopback(const IPAddress & ip)332 bool IPIsLoopback(const IPAddress& ip) {
333   switch (ip.family()) {
334     case AF_INET: {
335       return IPIsLoopbackV4(ip);
336     }
337     case AF_INET6: {
338       return IPIsLoopbackV6(ip);
339     }
340   }
341   return false;
342 }
343 
IPIsPrivate(const IPAddress & ip)344 bool IPIsPrivate(const IPAddress& ip) {
345   return IPIsLinkLocal(ip) || IPIsLoopback(ip) || IPIsPrivateNetwork(ip) ||
346          IPIsSharedNetwork(ip);
347 }
348 
IPIsUnspec(const IPAddress & ip)349 bool IPIsUnspec(const IPAddress& ip) {
350   return ip.family() == AF_UNSPEC;
351 }
352 
HashIP(const IPAddress & ip)353 size_t HashIP(const IPAddress& ip) {
354   switch (ip.family()) {
355     case AF_INET: {
356       return ip.ipv4_address().s_addr;
357     }
358     case AF_INET6: {
359       in6_addr v6addr = ip.ipv6_address();
360       const uint32_t* v6_as_ints =
361           reinterpret_cast<const uint32_t*>(&v6addr.s6_addr);
362       return v6_as_ints[0] ^ v6_as_ints[1] ^ v6_as_ints[2] ^ v6_as_ints[3];
363     }
364   }
365   return 0;
366 }
367 
TruncateIP(const IPAddress & ip,int length)368 IPAddress TruncateIP(const IPAddress& ip, int length) {
369   if (length < 0) {
370     return IPAddress();
371   }
372   if (ip.family() == AF_INET) {
373     if (length > 31) {
374       return ip;
375     }
376     if (length == 0) {
377       return IPAddress(INADDR_ANY);
378     }
379     int mask = (0xFFFFFFFF << (32 - length));
380     uint32_t host_order_ip = NetworkToHost32(ip.ipv4_address().s_addr);
381     in_addr masked;
382     masked.s_addr = HostToNetwork32(host_order_ip & mask);
383     return IPAddress(masked);
384   } else if (ip.family() == AF_INET6) {
385     if (length > 127) {
386       return ip;
387     }
388     if (length == 0) {
389       return IPAddress(in6addr_any);
390     }
391     in6_addr v6addr = ip.ipv6_address();
392     int position = length / 32;
393     int inner_length = 32 - (length - (position * 32));
394     // Note: 64bit mask constant needed to allow possible 32-bit left shift.
395     uint32_t inner_mask = 0xFFFFFFFFLL << inner_length;
396     uint32_t* v6_as_ints = reinterpret_cast<uint32_t*>(&v6addr.s6_addr);
397     for (int i = 0; i < 4; ++i) {
398       if (i == position) {
399         uint32_t host_order_inner = NetworkToHost32(v6_as_ints[i]);
400         v6_as_ints[i] = HostToNetwork32(host_order_inner & inner_mask);
401       } else if (i > position) {
402         v6_as_ints[i] = 0;
403       }
404     }
405     return IPAddress(v6addr);
406   }
407   return IPAddress();
408 }
409 
CountIPMaskBits(const IPAddress & mask)410 int CountIPMaskBits(const IPAddress& mask) {
411   uint32_t word_to_count = 0;
412   int bits = 0;
413   switch (mask.family()) {
414     case AF_INET: {
415       word_to_count = NetworkToHost32(mask.ipv4_address().s_addr);
416       break;
417     }
418     case AF_INET6: {
419       in6_addr v6addr = mask.ipv6_address();
420       const uint32_t* v6_as_ints =
421           reinterpret_cast<const uint32_t*>(&v6addr.s6_addr);
422       int i = 0;
423       for (; i < 4; ++i) {
424         if (v6_as_ints[i] != 0xFFFFFFFF) {
425           break;
426         }
427       }
428       if (i < 4) {
429         word_to_count = NetworkToHost32(v6_as_ints[i]);
430       }
431       bits = (i * 32);
432       break;
433     }
434     default: {
435       return 0;
436     }
437   }
438   if (word_to_count == 0) {
439     return bits;
440   }
441 
442   // Public domain bit-twiddling hack from:
443   // http://graphics.stanford.edu/~seander/bithacks.html
444   // Counts the trailing 0s in the word.
445   unsigned int zeroes = 32;
446   // This could also be written word_to_count &= -word_to_count, but
447   // MSVC emits warning C4146 when negating an unsigned number.
448   word_to_count &= ~word_to_count + 1;  // Isolate lowest set bit.
449   if (word_to_count)
450     zeroes--;
451   if (word_to_count & 0x0000FFFF)
452     zeroes -= 16;
453   if (word_to_count & 0x00FF00FF)
454     zeroes -= 8;
455   if (word_to_count & 0x0F0F0F0F)
456     zeroes -= 4;
457   if (word_to_count & 0x33333333)
458     zeroes -= 2;
459   if (word_to_count & 0x55555555)
460     zeroes -= 1;
461 
462   return bits + (32 - zeroes);
463 }
464 
IPIsHelper(const IPAddress & ip,const in6_addr & tomatch,int length)465 bool IPIsHelper(const IPAddress& ip, const in6_addr& tomatch, int length) {
466   // Helper method for checking IP prefix matches (but only on whole byte
467   // lengths). Length is in bits.
468   in6_addr addr = ip.ipv6_address();
469   return ::memcmp(&addr, &tomatch, (length >> 3)) == 0;
470 }
471 
IPIs6Bone(const IPAddress & ip)472 bool IPIs6Bone(const IPAddress& ip) {
473   return IPIsHelper(ip, k6BonePrefix, 16);
474 }
475 
IPIs6To4(const IPAddress & ip)476 bool IPIs6To4(const IPAddress& ip) {
477   return IPIsHelper(ip, k6To4Prefix, 16);
478 }
479 
IPIsLinkLocalV4(const IPAddress & ip)480 static bool IPIsLinkLocalV4(const IPAddress& ip) {
481   uint32_t ip_in_host_order = ip.v4AddressAsHostOrderInteger();
482   return ((ip_in_host_order >> 16) == ((169 << 8) | 254));
483 }
484 
IPIsLinkLocalV6(const IPAddress & ip)485 static bool IPIsLinkLocalV6(const IPAddress& ip) {
486   // Can't use the helper because the prefix is 10 bits.
487   in6_addr addr = ip.ipv6_address();
488   return (addr.s6_addr[0] == 0xFE) && ((addr.s6_addr[1] & 0xC0) == 0x80);
489 }
490 
IPIsLinkLocal(const IPAddress & ip)491 bool IPIsLinkLocal(const IPAddress& ip) {
492   switch (ip.family()) {
493     case AF_INET: {
494       return IPIsLinkLocalV4(ip);
495     }
496     case AF_INET6: {
497       return IPIsLinkLocalV6(ip);
498     }
499   }
500   return false;
501 }
502 
503 // According to http://www.ietf.org/rfc/rfc2373.txt, Appendix A, page 19.  An
504 // address which contains MAC will have its 11th and 12th bytes as FF:FE as well
505 // as the U/L bit as 1.
IPIsMacBased(const IPAddress & ip)506 bool IPIsMacBased(const IPAddress& ip) {
507   in6_addr addr = ip.ipv6_address();
508   return ((addr.s6_addr[8] & 0x02) && addr.s6_addr[11] == 0xFF &&
509           addr.s6_addr[12] == 0xFE);
510 }
511 
IPIsSiteLocal(const IPAddress & ip)512 bool IPIsSiteLocal(const IPAddress& ip) {
513   // Can't use the helper because the prefix is 10 bits.
514   in6_addr addr = ip.ipv6_address();
515   return addr.s6_addr[0] == 0xFE && (addr.s6_addr[1] & 0xC0) == 0xC0;
516 }
517 
IPIsULA(const IPAddress & ip)518 bool IPIsULA(const IPAddress& ip) {
519   // Can't use the helper because the prefix is 7 bits.
520   in6_addr addr = ip.ipv6_address();
521   return (addr.s6_addr[0] & 0xFE) == 0xFC;
522 }
523 
IPIsTeredo(const IPAddress & ip)524 bool IPIsTeredo(const IPAddress& ip) {
525   return IPIsHelper(ip, kTeredoPrefix, 32);
526 }
527 
IPIsV4Compatibility(const IPAddress & ip)528 bool IPIsV4Compatibility(const IPAddress& ip) {
529   return IPIsHelper(ip, kV4CompatibilityPrefix, 96);
530 }
531 
IPIsV4Mapped(const IPAddress & ip)532 bool IPIsV4Mapped(const IPAddress& ip) {
533   return IPIsHelper(ip, kV4MappedPrefix, 96);
534 }
535 
IPAddressPrecedence(const IPAddress & ip)536 int IPAddressPrecedence(const IPAddress& ip) {
537   // Precedence values from RFC 3484-bis. Prefers native v4 over 6to4/Teredo.
538   if (ip.family() == AF_INET) {
539     return 30;
540   } else if (ip.family() == AF_INET6) {
541     if (IPIsLoopback(ip)) {
542       return 60;
543     } else if (IPIsULA(ip)) {
544       return 50;
545     } else if (IPIsV4Mapped(ip)) {
546       return 30;
547     } else if (IPIs6To4(ip)) {
548       return 20;
549     } else if (IPIsTeredo(ip)) {
550       return 10;
551     } else if (IPIsV4Compatibility(ip) || IPIsSiteLocal(ip) || IPIs6Bone(ip)) {
552       return 1;
553     } else {
554       // A 'normal' IPv6 address.
555       return 40;
556     }
557   }
558   return 0;
559 }
560 
GetLoopbackIP(int family)561 IPAddress GetLoopbackIP(int family) {
562   if (family == AF_INET) {
563     return rtc::IPAddress(INADDR_LOOPBACK);
564   }
565   if (family == AF_INET6) {
566     return rtc::IPAddress(in6addr_loopback);
567   }
568   return rtc::IPAddress();
569 }
570 
GetAnyIP(int family)571 IPAddress GetAnyIP(int family) {
572   if (family == AF_INET) {
573     return rtc::IPAddress(INADDR_ANY);
574   }
575   if (family == AF_INET6) {
576     return rtc::IPAddress(in6addr_any);
577   }
578   return rtc::IPAddress();
579 }
580 
581 }  // namespace rtc
582