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 <sys/types.h>
13 #include <sys/socket.h>
14 #include <netinet/in.h>
15 #ifdef OPENBSD
16 #include <netinet/in_systm.h>
17 #endif
18 #ifndef __native_client__
19 #include <netinet/ip.h>
20 #endif
21 #include <arpa/inet.h>
22 #include <netdb.h>
23 #include <unistd.h>
24 #endif
25 
26 #include <stdio.h>
27 
28 #include "webrtc/base/ipaddress.h"
29 #include "webrtc/base/byteorder.h"
30 #include "webrtc/base/nethelpers.h"
31 #include "webrtc/base/logging.h"
32 #include "webrtc/base/win32.h"
33 
34 namespace rtc {
35 
36 // Prefixes used for categorizing IPv6 addresses.
37 static const in6_addr kV4MappedPrefix = {{{0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
38                                            0xFF, 0xFF, 0}}};
39 static const in6_addr k6To4Prefix = {{{0x20, 0x02, 0}}};
40 static const in6_addr kTeredoPrefix = {{{0x20, 0x01, 0x00, 0x00}}};
41 static const in6_addr kV4CompatibilityPrefix = {{{0}}};
42 static const in6_addr k6BonePrefix = {{{0x3f, 0xfe, 0}}};
43 
44 bool IPAddress::strip_sensitive_ = false;
45 
46 static bool IsPrivateV4(uint32_t ip);
47 static in_addr ExtractMappedAddress(const in6_addr& addr);
48 
v4AddressAsHostOrderInteger() const49 uint32_t IPAddress::v4AddressAsHostOrderInteger() const {
50   if (family_ == AF_INET) {
51     return NetworkToHost32(u_.ip4.s_addr);
52   } else {
53     return 0;
54   }
55 }
56 
IsNil() const57 bool IPAddress::IsNil() const {
58   return IPIsUnspec(*this);
59 }
60 
Size() const61 size_t IPAddress::Size() const {
62   switch (family_) {
63     case AF_INET:
64       return sizeof(in_addr);
65     case AF_INET6:
66       return sizeof(in6_addr);
67   }
68   return 0;
69 }
70 
71 
operator ==(const IPAddress & other) const72 bool IPAddress::operator==(const IPAddress &other) const {
73   if (family_ != other.family_) {
74     return false;
75   }
76   if (family_ == AF_INET) {
77     return memcmp(&u_.ip4, &other.u_.ip4, sizeof(u_.ip4)) == 0;
78   }
79   if (family_ == AF_INET6) {
80     return memcmp(&u_.ip6, &other.u_.ip6, sizeof(u_.ip6)) == 0;
81   }
82   return family_ == AF_UNSPEC;
83 }
84 
operator !=(const IPAddress & other) const85 bool IPAddress::operator!=(const IPAddress &other) const {
86   return !((*this) == other);
87 }
88 
operator >(const IPAddress & other) const89 bool IPAddress::operator >(const IPAddress &other) const {
90   return (*this) != other && !((*this) < other);
91 }
92 
operator <(const IPAddress & other) const93 bool IPAddress::operator <(const IPAddress &other) const {
94   // IPv4 is 'less than' IPv6
95   if (family_ != other.family_) {
96     if (family_ == AF_UNSPEC) {
97       return true;
98     }
99     if (family_ == AF_INET && other.family_ == AF_INET6) {
100       return true;
101     }
102     return false;
103   }
104   // Comparing addresses of the same family.
105   switch (family_) {
106     case AF_INET: {
107       return NetworkToHost32(u_.ip4.s_addr) <
108           NetworkToHost32(other.u_.ip4.s_addr);
109     }
110     case AF_INET6: {
111       return memcmp(&u_.ip6.s6_addr, &other.u_.ip6.s6_addr, 16) < 0;
112     }
113   }
114   // Catches AF_UNSPEC and invalid addresses.
115   return false;
116 }
117 
operator <<(std::ostream & os,const IPAddress & ip)118 std::ostream& operator<<(std::ostream& os, const IPAddress& ip) {
119   os << ip.ToString();
120   return os;
121 }
122 
ipv6_address() const123 in6_addr IPAddress::ipv6_address() const {
124   return u_.ip6;
125 }
126 
ipv4_address() const127 in_addr IPAddress::ipv4_address() const {
128   return u_.ip4;
129 }
130 
ToString() const131 std::string IPAddress::ToString() const {
132   if (family_ != AF_INET && family_ != AF_INET6) {
133     return std::string();
134   }
135   char buf[INET6_ADDRSTRLEN] = {0};
136   const void* src = &u_.ip4;
137   if (family_ == AF_INET6) {
138     src = &u_.ip6;
139   }
140   if (!rtc::inet_ntop(family_, src, buf, sizeof(buf))) {
141     return std::string();
142   }
143   return std::string(buf);
144 }
145 
ToSensitiveString() const146 std::string IPAddress::ToSensitiveString() const {
147   if (!strip_sensitive_)
148     return ToString();
149 
150   switch (family_) {
151     case AF_INET: {
152       std::string address = ToString();
153       size_t find_pos = address.rfind('.');
154       if (find_pos == std::string::npos)
155         return std::string();
156       address.resize(find_pos);
157       address += ".x";
158       return address;
159     }
160     case AF_INET6: {
161       // TODO(grunell): Return a string of format 1:2:3:x:x:x:x:x or such
162       // instead of zeroing out.
163       return TruncateIP(*this, 128 - 80).ToString();
164     }
165   }
166   return std::string();
167 }
168 
Normalized() const169 IPAddress IPAddress::Normalized() const {
170   if (family_ != AF_INET6) {
171     return *this;
172   }
173   if (!IPIsV4Mapped(*this)) {
174     return *this;
175   }
176   in_addr addr = ExtractMappedAddress(u_.ip6);
177   return IPAddress(addr);
178 }
179 
AsIPv6Address() const180 IPAddress IPAddress::AsIPv6Address() const {
181   if (family_ != AF_INET) {
182     return *this;
183   }
184   in6_addr v6addr = kV4MappedPrefix;
185   ::memcpy(&v6addr.s6_addr[12], &u_.ip4.s_addr, sizeof(u_.ip4.s_addr));
186   return IPAddress(v6addr);
187 }
188 
set_strip_sensitive(bool enable)189 void IPAddress::set_strip_sensitive(bool enable) {
190   strip_sensitive_ = enable;
191 }
192 
operator ==(const InterfaceAddress & other) const193 bool InterfaceAddress::operator==(const InterfaceAddress &other) const {
194   return ipv6_flags_ == other.ipv6_flags() &&
195     static_cast<const IPAddress&>(*this) == other;
196 }
197 
operator !=(const InterfaceAddress & other) const198 bool InterfaceAddress::operator!=(const InterfaceAddress &other) const {
199   return !((*this) == other);
200 }
201 
operator =(const InterfaceAddress & other)202 const InterfaceAddress& InterfaceAddress::operator=(
203   const InterfaceAddress& other) {
204   ipv6_flags_ = other.ipv6_flags_;
205   static_cast<IPAddress&>(*this) = other;
206   return *this;
207 }
208 
operator <<(std::ostream & os,const InterfaceAddress & ip)209 std::ostream& operator<<(std::ostream& os, const InterfaceAddress& ip) {
210   os << static_cast<const IPAddress&>(ip);
211 
212   if (ip.family() == AF_INET6)
213     os << "|flags:0x" << std::hex << ip.ipv6_flags();
214 
215   return os;
216 }
217 
IsPrivateV4(uint32_t ip_in_host_order)218 bool IsPrivateV4(uint32_t ip_in_host_order) {
219   return ((ip_in_host_order >> 24) == 127) ||
220       ((ip_in_host_order >> 24) == 10) ||
221       ((ip_in_host_order >> 20) == ((172 << 4) | 1)) ||
222       ((ip_in_host_order >> 16) == ((192 << 8) | 168)) ||
223       ((ip_in_host_order >> 16) == ((169 << 8) | 254));
224 }
225 
ExtractMappedAddress(const in6_addr & in6)226 in_addr ExtractMappedAddress(const in6_addr& in6) {
227   in_addr ipv4;
228   ::memcpy(&ipv4.s_addr, &in6.s6_addr[12], sizeof(ipv4.s_addr));
229   return ipv4;
230 }
231 
IPFromAddrInfo(struct addrinfo * info,IPAddress * out)232 bool IPFromAddrInfo(struct addrinfo* info, IPAddress* out) {
233   if (!info || !info->ai_addr) {
234     return false;
235   }
236   if (info->ai_addr->sa_family == AF_INET) {
237     sockaddr_in* addr = reinterpret_cast<sockaddr_in*>(info->ai_addr);
238     *out = IPAddress(addr->sin_addr);
239     return true;
240   } else if (info->ai_addr->sa_family == AF_INET6) {
241     sockaddr_in6* addr = reinterpret_cast<sockaddr_in6*>(info->ai_addr);
242     *out = IPAddress(addr->sin6_addr);
243     return true;
244   }
245   return false;
246 }
247 
IPFromString(const std::string & str,IPAddress * out)248 bool IPFromString(const std::string& str, IPAddress* out) {
249   if (!out) {
250     return false;
251   }
252   in_addr addr;
253   if (rtc::inet_pton(AF_INET, str.c_str(), &addr) == 0) {
254     in6_addr addr6;
255     if (rtc::inet_pton(AF_INET6, str.c_str(), &addr6) == 0) {
256       *out = IPAddress();
257       return false;
258     }
259     *out = IPAddress(addr6);
260   } else {
261     *out = IPAddress(addr);
262   }
263   return true;
264 }
265 
IPFromString(const std::string & str,int flags,InterfaceAddress * out)266 bool IPFromString(const std::string& str, int flags,
267                   InterfaceAddress* out) {
268   IPAddress ip;
269   if (!IPFromString(str, &ip)) {
270     return false;
271   }
272 
273   *out = InterfaceAddress(ip, flags);
274   return true;
275 }
276 
IPIsAny(const IPAddress & ip)277 bool IPIsAny(const IPAddress& ip) {
278   switch (ip.family()) {
279     case AF_INET:
280       return ip == IPAddress(INADDR_ANY);
281     case AF_INET6:
282       return ip == IPAddress(in6addr_any) || ip == IPAddress(kV4MappedPrefix);
283     case AF_UNSPEC:
284       return false;
285   }
286   return false;
287 }
288 
IPIsLoopback(const IPAddress & ip)289 bool IPIsLoopback(const IPAddress& ip) {
290   switch (ip.family()) {
291     case AF_INET: {
292       return ip == IPAddress(INADDR_LOOPBACK);
293     }
294     case AF_INET6: {
295       return ip == IPAddress(in6addr_loopback);
296     }
297   }
298   return false;
299 }
300 
IPIsPrivate(const IPAddress & ip)301 bool IPIsPrivate(const IPAddress& ip) {
302   switch (ip.family()) {
303     case AF_INET: {
304       return IsPrivateV4(ip.v4AddressAsHostOrderInteger());
305     }
306     case AF_INET6: {
307       return IPIsLinkLocal(ip) || IPIsLoopback(ip);
308     }
309   }
310   return false;
311 }
312 
IPIsUnspec(const IPAddress & ip)313 bool IPIsUnspec(const IPAddress& ip) {
314   return ip.family() == AF_UNSPEC;
315 }
316 
HashIP(const IPAddress & ip)317 size_t HashIP(const IPAddress& ip) {
318   switch (ip.family()) {
319     case AF_INET: {
320       return ip.ipv4_address().s_addr;
321     }
322     case AF_INET6: {
323       in6_addr v6addr = ip.ipv6_address();
324       const uint32_t* v6_as_ints =
325           reinterpret_cast<const uint32_t*>(&v6addr.s6_addr);
326       return v6_as_ints[0] ^ v6_as_ints[1] ^ v6_as_ints[2] ^ v6_as_ints[3];
327     }
328   }
329   return 0;
330 }
331 
TruncateIP(const IPAddress & ip,int length)332 IPAddress TruncateIP(const IPAddress& ip, int length) {
333   if (length < 0) {
334     return IPAddress();
335   }
336   if (ip.family() == AF_INET) {
337     if (length > 31) {
338       return ip;
339     }
340     if (length == 0) {
341       return IPAddress(INADDR_ANY);
342     }
343     int mask = (0xFFFFFFFF << (32 - length));
344     uint32_t host_order_ip = NetworkToHost32(ip.ipv4_address().s_addr);
345     in_addr masked;
346     masked.s_addr = HostToNetwork32(host_order_ip & mask);
347     return IPAddress(masked);
348   } else if (ip.family() == AF_INET6) {
349     if (length > 127) {
350       return ip;
351     }
352     if (length == 0) {
353       return IPAddress(in6addr_any);
354     }
355     in6_addr v6addr = ip.ipv6_address();
356     int position = length / 32;
357     int inner_length = 32 - (length - (position * 32));
358     // Note: 64bit mask constant needed to allow possible 32-bit left shift.
359     uint32_t inner_mask = 0xFFFFFFFFLL << inner_length;
360     uint32_t* v6_as_ints = reinterpret_cast<uint32_t*>(&v6addr.s6_addr);
361     for (int i = 0; i < 4; ++i) {
362       if (i == position) {
363         uint32_t host_order_inner = NetworkToHost32(v6_as_ints[i]);
364         v6_as_ints[i] = HostToNetwork32(host_order_inner & inner_mask);
365       } else if (i > position) {
366         v6_as_ints[i] = 0;
367       }
368     }
369     return IPAddress(v6addr);
370   }
371   return IPAddress();
372 }
373 
CountIPMaskBits(IPAddress mask)374 int CountIPMaskBits(IPAddress mask) {
375   uint32_t word_to_count = 0;
376   int bits = 0;
377   switch (mask.family()) {
378     case AF_INET: {
379       word_to_count = NetworkToHost32(mask.ipv4_address().s_addr);
380       break;
381     }
382     case AF_INET6: {
383       in6_addr v6addr = mask.ipv6_address();
384       const uint32_t* v6_as_ints =
385           reinterpret_cast<const uint32_t*>(&v6addr.s6_addr);
386       int i = 0;
387       for (; i < 4; ++i) {
388         if (v6_as_ints[i] != 0xFFFFFFFF) {
389           break;
390         }
391       }
392       if (i < 4) {
393         word_to_count = NetworkToHost32(v6_as_ints[i]);
394       }
395       bits = (i * 32);
396       break;
397     }
398     default: {
399       return 0;
400     }
401   }
402   if (word_to_count == 0) {
403     return bits;
404   }
405 
406   // Public domain bit-twiddling hack from:
407   // http://graphics.stanford.edu/~seander/bithacks.html
408   // Counts the trailing 0s in the word.
409   unsigned int zeroes = 32;
410   word_to_count &= -static_cast<int32_t>(word_to_count);
411   if (word_to_count) zeroes--;
412   if (word_to_count & 0x0000FFFF) zeroes -= 16;
413   if (word_to_count & 0x00FF00FF) zeroes -= 8;
414   if (word_to_count & 0x0F0F0F0F) zeroes -= 4;
415   if (word_to_count & 0x33333333) zeroes -= 2;
416   if (word_to_count & 0x55555555) zeroes -= 1;
417 
418   return bits + (32 - zeroes);
419 }
420 
IPIsHelper(const IPAddress & ip,const in6_addr & tomatch,int length)421 bool IPIsHelper(const IPAddress& ip, const in6_addr& tomatch, int length) {
422   // Helper method for checking IP prefix matches (but only on whole byte
423   // lengths). Length is in bits.
424   in6_addr addr = ip.ipv6_address();
425   return ::memcmp(&addr, &tomatch, (length >> 3)) == 0;
426 }
427 
IPIs6Bone(const IPAddress & ip)428 bool IPIs6Bone(const IPAddress& ip) {
429   return IPIsHelper(ip, k6BonePrefix, 16);
430 }
431 
IPIs6To4(const IPAddress & ip)432 bool IPIs6To4(const IPAddress& ip) {
433   return IPIsHelper(ip, k6To4Prefix, 16);
434 }
435 
IPIsLinkLocal(const IPAddress & ip)436 bool IPIsLinkLocal(const IPAddress& ip) {
437   // Can't use the helper because the prefix is 10 bits.
438   in6_addr addr = ip.ipv6_address();
439   return addr.s6_addr[0] == 0xFE && addr.s6_addr[1] == 0x80;
440 }
441 
442 // According to http://www.ietf.org/rfc/rfc2373.txt, Appendix A, page 19.  An
443 // address which contains MAC will have its 11th and 12th bytes as FF:FE as well
444 // as the U/L bit as 1.
IPIsMacBased(const IPAddress & ip)445 bool IPIsMacBased(const IPAddress& ip) {
446   in6_addr addr = ip.ipv6_address();
447   return ((addr.s6_addr[8] & 0x02) && addr.s6_addr[11] == 0xFF &&
448           addr.s6_addr[12] == 0xFE);
449 }
450 
IPIsSiteLocal(const IPAddress & ip)451 bool IPIsSiteLocal(const IPAddress& ip) {
452   // Can't use the helper because the prefix is 10 bits.
453   in6_addr addr = ip.ipv6_address();
454   return addr.s6_addr[0] == 0xFE && (addr.s6_addr[1] & 0xC0) == 0xC0;
455 }
456 
IPIsULA(const IPAddress & ip)457 bool IPIsULA(const IPAddress& ip) {
458   // Can't use the helper because the prefix is 7 bits.
459   in6_addr addr = ip.ipv6_address();
460   return (addr.s6_addr[0] & 0xFE) == 0xFC;
461 }
462 
IPIsTeredo(const IPAddress & ip)463 bool IPIsTeredo(const IPAddress& ip) {
464   return IPIsHelper(ip, kTeredoPrefix, 32);
465 }
466 
IPIsV4Compatibility(const IPAddress & ip)467 bool IPIsV4Compatibility(const IPAddress& ip) {
468   return IPIsHelper(ip, kV4CompatibilityPrefix, 96);
469 }
470 
IPIsV4Mapped(const IPAddress & ip)471 bool IPIsV4Mapped(const IPAddress& ip) {
472   return IPIsHelper(ip, kV4MappedPrefix, 96);
473 }
474 
IPAddressPrecedence(const IPAddress & ip)475 int IPAddressPrecedence(const IPAddress& ip) {
476   // Precedence values from RFC 3484-bis. Prefers native v4 over 6to4/Teredo.
477   if (ip.family() == AF_INET) {
478     return 30;
479   } else if (ip.family() == AF_INET6) {
480     if (IPIsLoopback(ip)) {
481       return 60;
482     } else if (IPIsULA(ip)) {
483       return 50;
484     } else if (IPIsV4Mapped(ip)) {
485       return 30;
486     } else if (IPIs6To4(ip)) {
487       return 20;
488     } else if (IPIsTeredo(ip)) {
489       return 10;
490     } else if (IPIsV4Compatibility(ip) || IPIsSiteLocal(ip) || IPIs6Bone(ip)) {
491       return 1;
492     } else {
493       // A 'normal' IPv6 address.
494       return 40;
495     }
496   }
497   return 0;
498 }
499 
GetLoopbackIP(int family)500 IPAddress GetLoopbackIP(int family) {
501   if (family == AF_INET) {
502     return rtc::IPAddress(INADDR_LOOPBACK);
503   }
504   if (family == AF_INET6) {
505     return rtc::IPAddress(in6addr_loopback);
506   }
507   return rtc::IPAddress();
508 }
509 }  // Namespace rtc
510