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