1 // Copyright 2015 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef NET_BASE_IP_ADDRESS_H_
6 #define NET_BASE_IP_ADDRESS_H_
7
8 #include <stddef.h>
9 #include <stdint.h>
10
11 #include <algorithm>
12 #include <array>
13 #include <string>
14 #include <vector>
15
16 #include "base/check_op.h"
17 #include "base/strings/string_piece.h"
18 #include "base/values.h"
19 #include "net/base/net_export.h"
20 #include "third_party/abseil-cpp/absl/types/optional.h"
21
22 namespace net {
23
24 // Helper class to represent the sequence of bytes in an IP address.
25 // A vector<uint8_t> would be simpler but incurs heap allocation, so
26 // IPAddressBytes uses a fixed size array.
27 class NET_EXPORT IPAddressBytes {
28 public:
29 IPAddressBytes();
30 IPAddressBytes(const uint8_t* data, size_t data_len);
31 IPAddressBytes(const IPAddressBytes& other);
32 ~IPAddressBytes();
33
34 // Copies |data_len| elements from |data| into this object.
35 void Assign(const uint8_t* data, size_t data_len);
36
37 // Returns the number of elements in the underlying array.
size()38 size_t size() const { return size_; }
39
40 // Sets the size to be |size|. Does not actually change the size
41 // of the underlying array or zero-initialize the bytes.
Resize(size_t size)42 void Resize(size_t size) {
43 DCHECK_LE(size, 16u);
44 size_ = static_cast<uint8_t>(size);
45 }
46
47 // Returns true if the underlying array is empty.
empty()48 bool empty() const { return size_ == 0; }
49
50 // Returns a pointer to the underlying array of bytes.
data()51 const uint8_t* data() const { return bytes_.data(); }
data()52 uint8_t* data() { return bytes_.data(); }
53
54 // Returns a pointer to the first element.
begin()55 const uint8_t* begin() const { return data(); }
begin()56 uint8_t* begin() { return data(); }
57
58 // Returns a pointer past the last element.
end()59 const uint8_t* end() const { return data() + size_; }
end()60 uint8_t* end() { return data() + size_; }
61
62 // Returns a reference to the last element.
back()63 uint8_t& back() {
64 DCHECK(!empty());
65 return bytes_[size_ - 1];
66 }
back()67 const uint8_t& back() const {
68 DCHECK(!empty());
69 return bytes_[size_ - 1];
70 }
71
72 // Appends |val| to the end and increments the size.
push_back(uint8_t val)73 void push_back(uint8_t val) {
74 DCHECK_GT(16, size_);
75 bytes_[size_++] = val;
76 }
77
78 // Returns a reference to the byte at index |pos|.
79 uint8_t& operator[](size_t pos) {
80 DCHECK_LT(pos, size_);
81 return bytes_[pos];
82 }
83 const uint8_t& operator[](size_t pos) const {
84 DCHECK_LT(pos, size_);
85 return bytes_[pos];
86 }
87
88 bool operator<(const IPAddressBytes& other) const;
89 bool operator!=(const IPAddressBytes& other) const;
90 bool operator==(const IPAddressBytes& other) const;
91
92 size_t EstimateMemoryUsage() const;
93
94 private:
95 // Underlying sequence of bytes
96 std::array<uint8_t, 16> bytes_;
97
98 // Number of elements in |bytes_|. Should be either kIPv4AddressSize
99 // or kIPv6AddressSize or 0.
100 uint8_t size_;
101 };
102
103 class NET_EXPORT IPAddress {
104 public:
105 enum : size_t { kIPv4AddressSize = 4, kIPv6AddressSize = 16 };
106
107 // Nullopt if `value` is malformed to be deserialized to IPAddress.
108 static absl::optional<IPAddress> FromValue(const base::Value& value);
109
110 // Parses an IP address literal (either IPv4 or IPv6). Returns the resulting
111 // IPAddress on success, or nullopt on error.
112 static absl::optional<IPAddress> FromIPLiteral(base::StringPiece ip_literal);
113
114 // Creates a zero-sized, invalid address.
115 IPAddress();
116
117 IPAddress(const IPAddress& other);
118
119 // Copies the input address to |ip_address_|.
120 explicit IPAddress(const IPAddressBytes& address);
121
122 // Copies the input address to |ip_address_|. The input is expected to be in
123 // network byte order.
124 template <size_t N>
IPAddress(const uint8_t (& address)[N])125 explicit IPAddress(const uint8_t (&address)[N]) : IPAddress(address, N) {}
126
127 // Copies the input address to |ip_address_| taking an additional length
128 // parameter. The input is expected to be in network byte order.
129 IPAddress(const uint8_t* address, size_t address_len);
130
131 // Initializes |ip_address_| from the 4 bX bytes to form an IPv4 address.
132 // The bytes are expected to be in network byte order.
133 IPAddress(uint8_t b0, uint8_t b1, uint8_t b2, uint8_t b3);
134
135 // Initializes |ip_address_| from the 16 bX bytes to form an IPv6 address.
136 // The bytes are expected to be in network byte order.
137 IPAddress(uint8_t b0,
138 uint8_t b1,
139 uint8_t b2,
140 uint8_t b3,
141 uint8_t b4,
142 uint8_t b5,
143 uint8_t b6,
144 uint8_t b7,
145 uint8_t b8,
146 uint8_t b9,
147 uint8_t b10,
148 uint8_t b11,
149 uint8_t b12,
150 uint8_t b13,
151 uint8_t b14,
152 uint8_t b15);
153
154 ~IPAddress();
155
156 // Returns true if the IP has |kIPv4AddressSize| elements.
157 bool IsIPv4() const;
158
159 // Returns true if the IP has |kIPv6AddressSize| elements.
160 bool IsIPv6() const;
161
162 // Returns true if the IP is either an IPv4 or IPv6 address. This function
163 // only checks the address length.
164 bool IsValid() const;
165
166 // Returns true if the IP is not in a range reserved by the IANA for
167 // local networks. Works with both IPv4 and IPv6 addresses.
168 // IPv4-mapped-to-IPv6 addresses are considered publicly routable.
169 bool IsPubliclyRoutable() const;
170
171 // Returns true if the IP is "zero" (e.g. the 0.0.0.0 IPv4 address).
172 bool IsZero() const;
173
174 // Returns true if |ip_address_| is an IPv4-mapped IPv6 address.
175 bool IsIPv4MappedIPv6() const;
176
177 // Returns true if |ip_address_| is 127.0.0.1/8 or ::1/128
178 bool IsLoopback() const;
179
180 // Returns true if |ip_address_| is 169.254.0.0/16 or fe80::/10, or
181 // ::ffff:169.254.0.0/112 (IPv4 mapped IPv6 link-local).
182 bool IsLinkLocal() const;
183
184 // The size in bytes of |ip_address_|.
size()185 size_t size() const { return ip_address_.size(); }
186
187 // Returns true if the IP is an empty, zero-sized (invalid) address.
empty()188 bool empty() const { return ip_address_.empty(); }
189
190 // Returns the canonical string representation of an IP address.
191 // For example: "192.168.0.1" or "::1". Returns the empty string when
192 // |ip_address_| is invalid.
193 std::string ToString() const;
194
195 // Parses an IP address literal (either IPv4 or IPv6) to its numeric value.
196 // Returns true on success and fills |ip_address_| with the numeric value.
197 //
198 // When parsing fails, the original value of |this| will be overwritten such
199 // that |this->empty()| and |!this->IsValid()|.
200 [[nodiscard]] bool AssignFromIPLiteral(base::StringPiece ip_literal);
201
202 // Returns the underlying bytes.
bytes()203 const IPAddressBytes& bytes() const { return ip_address_; }
204
205 // Copies the bytes to a new vector. Generally callers should be using
206 // |bytes()| and the IPAddressBytes abstraction. This method is provided as a
207 // convenience for call sites that existed prior to the introduction of
208 // IPAddressBytes.
209 std::vector<uint8_t> CopyBytesToVector() const;
210
211 // Returns an IPAddress instance representing the 127.0.0.1 address.
212 static IPAddress IPv4Localhost();
213
214 // Returns an IPAddress instance representing the ::1 address.
215 static IPAddress IPv6Localhost();
216
217 // Returns an IPAddress made up of |num_zero_bytes| zeros.
218 static IPAddress AllZeros(size_t num_zero_bytes);
219
220 // Returns an IPAddress instance representing the 0.0.0.0 address.
221 static IPAddress IPv4AllZeros();
222
223 // Returns an IPAddress instance representing the :: address.
224 static IPAddress IPv6AllZeros();
225
226 bool operator==(const IPAddress& that) const;
227 bool operator!=(const IPAddress& that) const;
228 bool operator<(const IPAddress& that) const;
229
230 // Must be a valid address (per IsValid()).
231 base::Value ToValue() const;
232
233 size_t EstimateMemoryUsage() const;
234
235 private:
236 IPAddressBytes ip_address_;
237
238 // This class is copyable and assignable.
239 };
240
241 using IPAddressList = std::vector<IPAddress>;
242
243 // Returns the canonical string representation of an IP address along with its
244 // port. For example: "192.168.0.1:99" or "[::1]:80".
245 NET_EXPORT std::string IPAddressToStringWithPort(const IPAddress& address,
246 uint16_t port);
247
248 // Returns the address as a sequence of bytes in network-byte-order.
249 NET_EXPORT std::string IPAddressToPackedString(const IPAddress& address);
250
251 // Converts an IPv4 address to an IPv4-mapped IPv6 address.
252 // For example 192.168.0.1 would be converted to ::ffff:192.168.0.1.
253 NET_EXPORT IPAddress ConvertIPv4ToIPv4MappedIPv6(const IPAddress& address);
254
255 // Converts an IPv4-mapped IPv6 address to IPv4 address. Should only be called
256 // on IPv4-mapped IPv6 addresses.
257 NET_EXPORT IPAddress ConvertIPv4MappedIPv6ToIPv4(const IPAddress& address);
258
259 // Compares an IP address to see if it falls within the specified IP block.
260 // Returns true if it does, false otherwise.
261 //
262 // The IP block is given by (|ip_prefix|, |prefix_length_in_bits|) -- any
263 // IP address whose |prefix_length_in_bits| most significant bits match
264 // |ip_prefix| will be matched.
265 //
266 // In cases when an IPv4 address is being compared to an IPv6 address prefix
267 // and vice versa, the IPv4 addresses will be converted to IPv4-mapped
268 // (IPv6) addresses.
269 NET_EXPORT bool IPAddressMatchesPrefix(const IPAddress& ip_address,
270 const IPAddress& ip_prefix,
271 size_t prefix_length_in_bits);
272
273 // Parses an IP block specifier from CIDR notation to an
274 // (IP address, prefix length) pair. Returns true on success and fills
275 // |*ip_address| with the numeric value of the IP address and sets
276 // |*prefix_length_in_bits| with the length of the prefix. On failure,
277 // |ip_address| will be cleared to an empty value.
278 //
279 // CIDR notation literals can use either IPv4 or IPv6 literals. Some examples:
280 //
281 // 10.10.3.1/20
282 // a:b:c::/46
283 // ::1/128
284 NET_EXPORT bool ParseCIDRBlock(base::StringPiece cidr_literal,
285 IPAddress* ip_address,
286 size_t* prefix_length_in_bits);
287
288 // Parses a URL-safe IP literal (see RFC 3986, Sec 3.2.2) to its numeric value.
289 // Returns true on success, and fills |ip_address| with the numeric value.
290 // In other words, |hostname| must be an IPv4 literal, or an IPv6 literal
291 // surrounded by brackets as in [::1]. On failure |ip_address| may have been
292 // overwritten and could contain an invalid IPAddress.
293 [[nodiscard]] NET_EXPORT bool ParseURLHostnameToAddress(
294 base::StringPiece hostname,
295 IPAddress* ip_address);
296
297 // Returns number of matching initial bits between the addresses |a1| and |a2|.
298 NET_EXPORT size_t CommonPrefixLength(const IPAddress& a1, const IPAddress& a2);
299
300 // Computes the number of leading 1-bits in |mask|.
301 NET_EXPORT size_t MaskPrefixLength(const IPAddress& mask);
302
303 // Checks whether |address| starts with |prefix|. This provides similar
304 // functionality as IPAddressMatchesPrefix() but doesn't perform automatic IPv4
305 // to IPv4MappedIPv6 conversions and only checks against full bytes.
306 template <size_t N>
IPAddressStartsWith(const IPAddress & address,const uint8_t (& prefix)[N])307 bool IPAddressStartsWith(const IPAddress& address, const uint8_t (&prefix)[N]) {
308 if (address.size() < N)
309 return false;
310 return std::equal(prefix, prefix + N, address.bytes().begin());
311 }
312
313 // According to RFC6052 Section 2.2 IPv4-Embedded IPv6 Address Format.
314 // https://www.rfc-editor.org/rfc/rfc6052#section-2.2
315 // +--+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
316 // |PL| 0-------------32--40--48--56--64--72--80--88--96--104---------|
317 // +--+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
318 // |32| prefix |v4(32) | u | suffix |
319 // +--+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
320 // |40| prefix |v4(24) | u |(8)| suffix |
321 // +--+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
322 // |48| prefix |v4(16) | u | (16) | suffix |
323 // +--+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
324 // |56| prefix |(8)| u | v4(24) | suffix |
325 // +--+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
326 // |64| prefix | u | v4(32) | suffix |
327 // +--+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
328 // |96| prefix | v4(32) |
329 // +--+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
330 //
331 // The NAT64/DNS64 translation prefixes has one of the following lengths.
332 enum class Dns64PrefixLength {
333 k32bit,
334 k40bit,
335 k48bit,
336 k56bit,
337 k64bit,
338 k96bit,
339 kInvalid
340 };
341
342 // Extracts the NAT64 translation prefix from the IPv6 address using the well
343 // known address ipv4only.arpa 192.0.0.170 and 192.0.0.171.
344 // Returns prefix length on success, or Dns64PrefixLength::kInvalid on failure
345 // (when the ipv4only.arpa IPv4 address is not found)
346 NET_EXPORT Dns64PrefixLength
347 ExtractPref64FromIpv4onlyArpaAAAA(const IPAddress& address);
348
349 // Converts an IPv4 address to an IPv4-embedded IPv6 address using the given
350 // prefix. For example 192.168.0.1 and 64:ff9b::/96 would be converted to
351 // 64:ff9b::192.168.0.1
352 // Returns converted IPv6 address when prefix_length is not
353 // Dns64PrefixLength::kInvalid, and returns the original IPv4 address when
354 // prefix_length is Dns64PrefixLength::kInvalid.
355 NET_EXPORT IPAddress
356 ConvertIPv4ToIPv4EmbeddedIPv6(const IPAddress& ipv4_address,
357 const IPAddress& ipv6_address,
358 Dns64PrefixLength prefix_length);
359
360 } // namespace net
361
362 #endif // NET_BASE_IP_ADDRESS_H_
363