• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * libjingle
3  * Copyright 2004--2011, Google Inc.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  *  1. Redistributions of source code must retain the above copyright notice,
9  *     this list of conditions and the following disclaimer.
10  *  2. Redistributions in binary form must reproduce the above copyright notice,
11  *     this list of conditions and the following disclaimer in the documentation
12  *     and/or other materials provided with the distribution.
13  *  3. The name of the author may not be used to endorse or promote products
14  *     derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19  * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #ifdef POSIX
29 #include <sys/types.h>
30 #include <sys/socket.h>
31 #include <netinet/in.h>
32 #ifdef OPENBSD
33 #include <netinet/in_systm.h>
34 #endif
35 #include <netinet/ip.h>
36 #include <arpa/inet.h>
37 #include <netdb.h>
38 #include <unistd.h>
39 #endif
40 
41 #include <stdio.h>
42 
43 #include "talk/base/ipaddress.h"
44 #include "talk/base/byteorder.h"
45 #include "talk/base/nethelpers.h"
46 #include "talk/base/logging.h"
47 #include "talk/base/win32.h"
48 
49 namespace talk_base {
50 
51 // Prefixes used for categorizing IPv6 addresses.
52 static const in6_addr kULAPrefix = {{{0xfc, 0}}};
53 static const in6_addr kV4MappedPrefix = {{{0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
54                                            0xFF, 0xFF, 0}}};
55 static const in6_addr k6To4Prefix = {{{0x20, 0x02, 0}}};
56 static const in6_addr kTeredoPrefix = {{{0x20, 0x01, 0x00, 0x00}}};
57 static const in6_addr kV4CompatibilityPrefix = {{{0}}};
58 static const in6_addr kSiteLocalPrefix = {{{0xfe, 0xc0, 0}}};
59 static const in6_addr k6BonePrefix = {{{0x3f, 0xfe, 0}}};
60 
61 bool IPAddress::strip_sensitive_ = false;
62 
63 static bool IsPrivateV4(uint32 ip);
64 static in_addr ExtractMappedAddress(const in6_addr& addr);
65 
v4AddressAsHostOrderInteger() const66 uint32 IPAddress::v4AddressAsHostOrderInteger() const {
67   if (family_ == AF_INET) {
68     return NetworkToHost32(u_.ip4.s_addr);
69   } else {
70     return 0;
71   }
72 }
73 
Size() const74 size_t IPAddress::Size() const {
75   switch (family_) {
76     case AF_INET:
77       return sizeof(in_addr);
78     case AF_INET6:
79       return sizeof(in6_addr);
80   }
81   return 0;
82 }
83 
84 
operator ==(const IPAddress & other) const85 bool IPAddress::operator==(const IPAddress &other) const {
86   if (family_ != other.family_) {
87     return false;
88   }
89   if (family_ == AF_INET) {
90     return memcmp(&u_.ip4, &other.u_.ip4, sizeof(u_.ip4)) == 0;
91   }
92   if (family_ == AF_INET6) {
93     return memcmp(&u_.ip6, &other.u_.ip6, sizeof(u_.ip6)) == 0;
94   }
95   return family_ == AF_UNSPEC;
96 }
97 
operator !=(const IPAddress & other) const98 bool IPAddress::operator!=(const IPAddress &other) const {
99   return !((*this) == other);
100 }
101 
operator >(const IPAddress & other) const102 bool IPAddress::operator >(const IPAddress &other) const {
103   return (*this) != other && !((*this) < other);
104 }
105 
operator <(const IPAddress & other) const106 bool IPAddress::operator <(const IPAddress &other) const {
107   // IPv4 is 'less than' IPv6
108   if (family_ != other.family_) {
109     if (family_ == AF_UNSPEC) {
110       return true;
111     }
112     if (family_ == AF_INET && other.family_ == AF_INET6) {
113       return true;
114     }
115     return false;
116   }
117   // Comparing addresses of the same family.
118   switch (family_) {
119     case AF_INET: {
120       return NetworkToHost32(u_.ip4.s_addr) <
121           NetworkToHost32(other.u_.ip4.s_addr);
122     }
123     case AF_INET6: {
124       return memcmp(&u_.ip6.s6_addr, &other.u_.ip6.s6_addr, 16) < 0;
125     }
126   }
127   // Catches AF_UNSPEC and invalid addresses.
128   return false;
129 }
130 
operator <<(std::ostream & os,const IPAddress & ip)131 std::ostream& operator<<(std::ostream& os, const IPAddress& ip) {
132   os << ip.ToString();
133   return os;
134 }
135 
ipv6_address() const136 in6_addr IPAddress::ipv6_address() const {
137   return u_.ip6;
138 }
139 
ipv4_address() const140 in_addr IPAddress::ipv4_address() const {
141   return u_.ip4;
142 }
143 
ToString() const144 std::string IPAddress::ToString() const {
145   if (family_ != AF_INET && family_ != AF_INET6) {
146     return std::string();
147   }
148   char buf[INET6_ADDRSTRLEN] = {0};
149   const void* src = &u_.ip4;
150   if (family_ == AF_INET6) {
151     src = &u_.ip6;
152   }
153   if (!talk_base::inet_ntop(family_, src, buf, sizeof(buf))) {
154     return std::string();
155   }
156   return std::string(buf);
157 }
158 
ToSensitiveString() const159 std::string IPAddress::ToSensitiveString() const {
160   if (!strip_sensitive_)
161     return ToString();
162 
163   switch (family_) {
164     case AF_INET: {
165       std::string address = ToString();
166       size_t find_pos = address.rfind('.');
167       if (find_pos == std::string::npos)
168         return std::string();
169       address.resize(find_pos);
170       address += ".x";
171       return address;
172     }
173     case AF_INET6: {
174       // TODO(grunell): Return a string of format 1:2:3:x:x:x:x:x or such
175       // instead of zeroing out.
176       return TruncateIP(*this, 128 - 80).ToString();
177     }
178   }
179   return std::string();
180 }
181 
Normalized() const182 IPAddress IPAddress::Normalized() const {
183   if (family_ != AF_INET6) {
184     return *this;
185   }
186   if (!IPIsV4Mapped(*this)) {
187     return *this;
188   }
189   in_addr addr = ExtractMappedAddress(u_.ip6);
190   return IPAddress(addr);
191 }
192 
AsIPv6Address() const193 IPAddress IPAddress::AsIPv6Address() const {
194   if (family_ != AF_INET) {
195     return *this;
196   }
197   in6_addr v6addr = kV4MappedPrefix;
198   ::memcpy(&v6addr.s6_addr[12], &u_.ip4.s_addr, sizeof(u_.ip4.s_addr));
199   return IPAddress(v6addr);
200 }
201 
set_strip_sensitive(bool enable)202 void IPAddress::set_strip_sensitive(bool enable) {
203   strip_sensitive_ = enable;
204 }
205 
206 
IsPrivateV4(uint32 ip_in_host_order)207 bool IsPrivateV4(uint32 ip_in_host_order) {
208   return ((ip_in_host_order >> 24) == 127) ||
209       ((ip_in_host_order >> 24) == 10) ||
210       ((ip_in_host_order >> 20) == ((172 << 4) | 1)) ||
211       ((ip_in_host_order >> 16) == ((192 << 8) | 168)) ||
212       ((ip_in_host_order >> 16) == ((169 << 8) | 254));
213 }
214 
ExtractMappedAddress(const in6_addr & in6)215 in_addr ExtractMappedAddress(const in6_addr& in6) {
216   in_addr ipv4;
217   ::memcpy(&ipv4.s_addr, &in6.s6_addr[12], sizeof(ipv4.s_addr));
218   return ipv4;
219 }
220 
IPFromAddrInfo(struct addrinfo * info,IPAddress * out)221 bool IPFromAddrInfo(struct addrinfo* info, IPAddress* out) {
222   if (!info || !info->ai_addr) {
223     return false;
224   }
225   if (info->ai_addr->sa_family == AF_INET) {
226     sockaddr_in* addr = reinterpret_cast<sockaddr_in*>(info->ai_addr);
227     *out = IPAddress(addr->sin_addr);
228     return true;
229   } else if (info->ai_addr->sa_family == AF_INET6) {
230     sockaddr_in6* addr = reinterpret_cast<sockaddr_in6*>(info->ai_addr);
231     *out = IPAddress(addr->sin6_addr);
232     return true;
233   }
234   return false;
235 }
236 
IPFromString(const std::string & str,IPAddress * out)237 bool IPFromString(const std::string& str, IPAddress* out) {
238   if (!out) {
239     return false;
240   }
241   in_addr addr;
242   if (talk_base::inet_pton(AF_INET, str.c_str(), &addr) == 0) {
243     in6_addr addr6;
244     if (talk_base::inet_pton(AF_INET6, str.c_str(), &addr6) == 0) {
245       *out = IPAddress();
246       return false;
247     }
248     *out = IPAddress(addr6);
249   } else {
250     *out = IPAddress(addr);
251   }
252   return true;
253 }
254 
IPIsAny(const IPAddress & ip)255 bool IPIsAny(const IPAddress& ip) {
256   switch (ip.family()) {
257     case AF_INET:
258       return ip == IPAddress(INADDR_ANY);
259     case AF_INET6:
260       return ip == IPAddress(in6addr_any);
261     case AF_UNSPEC:
262       return false;
263   }
264   return false;
265 }
266 
IPIsLoopback(const IPAddress & ip)267 bool IPIsLoopback(const IPAddress& ip) {
268   switch (ip.family()) {
269     case AF_INET: {
270       return ip == IPAddress(INADDR_LOOPBACK);
271     }
272     case AF_INET6: {
273       return ip == IPAddress(in6addr_loopback);
274     }
275   }
276   return false;
277 }
278 
IPIsPrivate(const IPAddress & ip)279 bool IPIsPrivate(const IPAddress& ip) {
280   switch (ip.family()) {
281     case AF_INET: {
282       return IsPrivateV4(ip.v4AddressAsHostOrderInteger());
283     }
284     case AF_INET6: {
285       in6_addr v6 = ip.ipv6_address();
286       return (v6.s6_addr[0] == 0xFE && v6.s6_addr[1] == 0x80) ||
287           IPIsLoopback(ip);
288     }
289   }
290   return false;
291 }
292 
IPIsUnspec(const IPAddress & ip)293 bool IPIsUnspec(const IPAddress& ip) {
294   return ip.family() == AF_UNSPEC;
295 }
296 
HashIP(const IPAddress & ip)297 size_t HashIP(const IPAddress& ip) {
298   switch (ip.family()) {
299     case AF_INET: {
300       return ip.ipv4_address().s_addr;
301     }
302     case AF_INET6: {
303       in6_addr v6addr = ip.ipv6_address();
304       const uint32* v6_as_ints =
305           reinterpret_cast<const uint32*>(&v6addr.s6_addr);
306       return v6_as_ints[0] ^ v6_as_ints[1] ^ v6_as_ints[2] ^ v6_as_ints[3];
307     }
308   }
309   return 0;
310 }
311 
TruncateIP(const IPAddress & ip,int length)312 IPAddress TruncateIP(const IPAddress& ip, int length) {
313   if (length < 0) {
314     return IPAddress();
315   }
316   if (ip.family() == AF_INET) {
317     if (length > 31) {
318       return ip;
319     }
320     if (length == 0) {
321       return IPAddress(INADDR_ANY);
322     }
323     int mask = (0xFFFFFFFF << (32 - length));
324     uint32 host_order_ip = NetworkToHost32(ip.ipv4_address().s_addr);
325     in_addr masked;
326     masked.s_addr = HostToNetwork32(host_order_ip & mask);
327     return IPAddress(masked);
328   } else if (ip.family() == AF_INET6) {
329     if (length > 127) {
330       return ip;
331     }
332     if (length == 0) {
333       return IPAddress(in6addr_any);
334     }
335     in6_addr v6addr = ip.ipv6_address();
336     int position = length / 32;
337     int inner_length = 32 - (length - (position * 32));
338     // Note: 64bit mask constant needed to allow possible 32-bit left shift.
339     uint32 inner_mask = 0xFFFFFFFFLL  << inner_length;
340     uint32* v6_as_ints =
341         reinterpret_cast<uint32*>(&v6addr.s6_addr);
342     for (int i = 0; i < 4; ++i) {
343       if (i == position) {
344         uint32 host_order_inner = NetworkToHost32(v6_as_ints[i]);
345         v6_as_ints[i] = HostToNetwork32(host_order_inner & inner_mask);
346       } else if (i > position) {
347         v6_as_ints[i] = 0;
348       }
349     }
350     return IPAddress(v6addr);
351   }
352   return IPAddress();
353 }
354 
CountIPMaskBits(IPAddress mask)355 int CountIPMaskBits(IPAddress mask) {
356   uint32 word_to_count = 0;
357   int bits = 0;
358   switch (mask.family()) {
359     case AF_INET: {
360       word_to_count = NetworkToHost32(mask.ipv4_address().s_addr);
361       break;
362     }
363     case AF_INET6: {
364       in6_addr v6addr = mask.ipv6_address();
365       const uint32* v6_as_ints =
366           reinterpret_cast<const uint32*>(&v6addr.s6_addr);
367       int i = 0;
368       for (; i < 4; ++i) {
369         if (v6_as_ints[i] != 0xFFFFFFFF) {
370           break;
371         }
372       }
373       if (i < 4) {
374         word_to_count = NetworkToHost32(v6_as_ints[i]);
375       }
376       bits = (i * 32);
377       break;
378     }
379     default: {
380       return 0;
381     }
382   }
383   if (word_to_count == 0) {
384     return bits;
385   }
386 
387   // Public domain bit-twiddling hack from:
388   // http://graphics.stanford.edu/~seander/bithacks.html
389   // Counts the trailing 0s in the word.
390   unsigned int zeroes = 32;
391   word_to_count &= -static_cast<int32>(word_to_count);
392   if (word_to_count) zeroes--;
393   if (word_to_count & 0x0000FFFF) zeroes -= 16;
394   if (word_to_count & 0x00FF00FF) zeroes -= 8;
395   if (word_to_count & 0x0F0F0F0F) zeroes -= 4;
396   if (word_to_count & 0x33333333) zeroes -= 2;
397   if (word_to_count & 0x55555555) zeroes -= 1;
398 
399   return bits + (32 - zeroes);
400 }
401 
IPIsHelper(const IPAddress & ip,const in6_addr & tomatch,int length)402 bool IPIsHelper(const IPAddress& ip, const in6_addr& tomatch, int length) {
403   // Helper method for checking IP prefix matches (but only on whole byte
404   // lengths). Length is in bits.
405   in6_addr addr = ip.ipv6_address();
406   return ::memcmp(&addr, &tomatch, (length >> 3)) == 0;
407 }
408 
IPIs6Bone(const IPAddress & ip)409 bool IPIs6Bone(const IPAddress& ip) {
410   return IPIsHelper(ip, k6BonePrefix, 16);
411 }
412 
IPIs6To4(const IPAddress & ip)413 bool IPIs6To4(const IPAddress& ip) {
414   return IPIsHelper(ip, k6To4Prefix, 16);
415 }
416 
IPIsSiteLocal(const IPAddress & ip)417 bool IPIsSiteLocal(const IPAddress& ip) {
418   // Can't use the helper because the prefix is 10 bits.
419   in6_addr addr = ip.ipv6_address();
420   return addr.s6_addr[0] == 0xFE && (addr.s6_addr[1] & 0xC0) == 0xC0;
421 }
422 
IPIsULA(const IPAddress & ip)423 bool IPIsULA(const IPAddress& ip) {
424   // Can't use the helper because the prefix is 7 bits.
425   in6_addr addr = ip.ipv6_address();
426   return (addr.s6_addr[0] & 0xFE) == 0xFC;
427 }
428 
IPIsTeredo(const IPAddress & ip)429 bool IPIsTeredo(const IPAddress& ip) {
430   return IPIsHelper(ip, kTeredoPrefix, 32);
431 }
432 
IPIsV4Compatibility(const IPAddress & ip)433 bool IPIsV4Compatibility(const IPAddress& ip) {
434   return IPIsHelper(ip, kV4CompatibilityPrefix, 96);
435 }
436 
IPIsV4Mapped(const IPAddress & ip)437 bool IPIsV4Mapped(const IPAddress& ip) {
438   return IPIsHelper(ip, kV4MappedPrefix, 96);
439 }
440 
IPAddressPrecedence(const IPAddress & ip)441 int IPAddressPrecedence(const IPAddress& ip) {
442   // Precedence values from RFC 3484-bis. Prefers native v4 over 6to4/Teredo.
443   if (ip.family() == AF_INET) {
444     return 30;
445   } else if (ip.family() == AF_INET6) {
446     if (IPIsLoopback(ip)) {
447       return 60;
448     } else if (IPIsULA(ip)) {
449       return 50;
450     } else if (IPIsV4Mapped(ip)) {
451       return 30;
452     } else if (IPIs6To4(ip)) {
453       return 20;
454     } else if (IPIsTeredo(ip)) {
455       return 10;
456     } else if (IPIsV4Compatibility(ip) || IPIsSiteLocal(ip) || IPIs6Bone(ip)) {
457       return 1;
458     } else {
459       // A 'normal' IPv6 address.
460       return 40;
461     }
462   }
463   return 0;
464 }
465 
466 }  // Namespace talk base
467