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