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