Botan 3.13.0
Crypto and TLS for C&
ipv6_address.cpp
Go to the documentation of this file.
1/*
2* (C) 2026 Jack Lloyd
3*
4* Botan is released under the Simplified BSD License (see license.txt)
5*/
6
7#include <botan/ipv6_address.h>
8
9#include <botan/ipv4_address.h>
10#include <botan/internal/fmt.h>
11#include <botan/internal/loadstor.h>
12#include <botan/internal/parsing.h>
13#include <bit>
14
15namespace Botan {
16
17IPv6Address::IPv6Address(std::span<const uint8_t, 16> ip) : m_ip{} {
18 for(size_t i = 0; i != 16; ++i) {
19 m_ip[i] = ip[i];
20 }
21}
22
23//static
24std::optional<IPv6Address> IPv6Address::from_string(std::string_view str) {
25 if(str.empty()) {
26 return {};
27 }
28
29 // Parsed hex groups, split by whether they appeared before or after a "::".
30 // If no "::" appears, only `pre` is populated and must reach exactly 8 groups.
31 std::array<uint16_t, 8> pre{};
32 std::array<uint16_t, 8> post{};
33 size_t pre_count = 0;
34 size_t post_count = 0;
35 bool seen_double_colon = false;
36
37 auto hex_value = [](char c) -> std::optional<uint8_t> {
38 if(c >= '0' && c <= '9') {
39 return c - '0';
40 } else if(c >= 'a' && c <= 'f') {
41 return 10 + (c - 'a');
42 } else if(c >= 'A' && c <= 'F') {
43 return 10 + (c - 'A');
44 } else {
45 return {};
46 }
47 };
48
49 size_t idx = 0;
50 bool expect_group = true; // set after any separator, cleared after a group
51
52 while(idx < str.size()) {
53 if(str[idx] == ':') {
54 if(idx + 1 < str.size() && str[idx + 1] == ':') {
55 if(seen_double_colon) {
56 return {}; // at most one "::"
57 }
58 seen_double_colon = true;
59 idx += 2;
60 expect_group = (idx < str.size());
61 continue;
62 }
63 // single ':' separator between groups, only valid after a group
64 if(expect_group) {
65 return {};
66 }
67 expect_group = true;
68 idx += 1;
69 continue;
70 }
71
72 // Parse a hex group of 1..4 digits
73 const size_t group_start = idx;
74 uint32_t group = 0;
75 size_t hex_chars = 0;
76 while(idx < str.size() && hex_chars < 4) {
77 const auto digit = hex_value(str[idx]);
78 if(digit.has_value() == false) {
79 break;
80 }
81 group = (group << 4) | static_cast<uint32_t>(digit.value());
82 idx += 1;
83 hex_chars += 1;
84 }
85 if(hex_chars == 0) {
86 return {};
87 }
88 // If a 5th hex digit follows, the group is oversized.
89 if(hex_chars == 4 && idx < str.size() && hex_value(str[idx]).has_value()) {
90 return {};
91 }
92
93 /*
94 RFC 4291 2.2 allows the final 32 bits in dotted decimal, eg
95 "::ffff:1.2.3.4". The dotted quad must consume the remainder of the
96 input, and accounts for two 16-bit groups.
97 */
98 if(idx < str.size() && str[idx] == '.') {
99 const auto ipv4 = IPv4Address::from_string(str.substr(group_start));
100 if(!ipv4.has_value()) {
101 return {};
102 }
103 const uint32_t v4 = ipv4->address();
104 const std::array<uint16_t, 2> v4_groups{static_cast<uint16_t>(v4 >> 16), static_cast<uint16_t>(v4 & 0xFFFF)};
105 for(const auto g : v4_groups) {
106 if(seen_double_colon) {
107 if(post_count >= 8) {
108 return {};
109 }
110 post[post_count++] = g;
111 } else {
112 if(pre_count >= 8) {
113 return {};
114 }
115 pre[pre_count++] = g;
116 }
117 }
118 idx = str.size();
119 expect_group = false;
120 continue;
121 }
122
123 if(seen_double_colon) {
124 if(post_count >= 8) {
125 return {};
126 }
127 post[post_count++] = static_cast<uint16_t>(group);
128 } else {
129 if(pre_count >= 8) {
130 return {};
131 }
132 pre[pre_count++] = static_cast<uint16_t>(group);
133 }
134 expect_group = false;
135 }
136
137 // Trailing single ':' is invalid
138 if(expect_group) {
139 return {};
140 }
141
142 const size_t total_groups = pre_count + post_count;
143 if(seen_double_colon) {
144 // "::" has to cover at least one zero group
145 if(total_groups > 7) {
146 return {};
147 }
148 } else {
149 if(total_groups != 8) {
150 return {};
151 }
152 }
153
154 std::array<uint8_t, 16> out{};
155 for(size_t i = 0; i != pre_count; ++i) {
156 out[2 * i] = get_byte<0>(pre[i]);
157 out[2 * i + 1] = get_byte<1>(pre[i]);
158 }
159 const size_t gap = 8 - total_groups;
160 for(size_t i = 0; i != post_count; ++i) {
161 const size_t target = pre_count + gap + i;
162 out[2 * target] = get_byte<0>(post[i]);
163 out[2 * target + 1] = get_byte<1>(post[i]);
164 }
165 return IPv6Address(out);
166}
167
168//static
170 BOTAN_ARG_CHECK(bits <= 128, "IPv6 netmask prefix length must be at most 128");
171
172 const size_t full_bytes = bits / 8;
173 const size_t leftover = bits % 8;
174
175 std::array<uint8_t, 16> m{};
176 for(size_t i = 0; i != full_bytes; ++i) {
177 m[i] = 0xFF;
178 }
179
180 if(leftover > 0) {
181 m[full_bytes] = static_cast<uint8_t>(0xFF << (8 - leftover));
182 }
183
184 return IPv6Address(m);
185}
186
187std::string IPv6Address::to_string() const {
188 static const char* hex = "0123456789abcdef";
189
190 std::array<uint16_t, 8> groups{};
191 for(size_t i = 0; i != 8; ++i) {
192 groups[i] = make_uint16(m_ip[2 * i], m_ip[2 * i + 1]);
193 }
194
195 /*
196 Find the run of zero groups to elide with "::", per RFC 5952 4.2:
197 "The use of the symbol '::' MUST be used to its maximum capability",
198 "The symbol '::' MUST NOT be used to shorten just one 16-bit 0 field",
199 and on ties "the first sequence of zero bits MUST be shortened".
200 */
201 size_t best_start = 0;
202 size_t best_len = 0;
203 size_t run_len = 0;
204 for(size_t i = 0; i != 8; ++i) {
205 if(groups[i] == 0) {
206 run_len += 1;
207 if(run_len > best_len) {
208 best_len = run_len;
209 best_start = i + 1 - run_len;
210 }
211 } else {
212 run_len = 0;
213 }
214 }
215
216 std::string out;
217 out.reserve(39);
218
219 auto append_group = [&](uint16_t group) {
220 bool started = false;
221 // Write each nibble omitting leading 0s
222 for(int s = 12; s >= 0; s -= 4) {
223 const auto nibble = (group >> s) & 0xF;
224 if(nibble != 0 || started || s == 0) {
225 out.push_back(hex[nibble]);
226 started = true;
227 }
228 }
229 };
230
231 if(best_len < 2) {
232 // No run of two or more zero groups; write the full form
233 for(size_t i = 0; i != 8; ++i) {
234 if(i > 0) {
235 out.push_back(':');
236 }
237 append_group(groups[i]);
238 }
239 } else {
240 for(size_t i = 0; i != best_start; ++i) {
241 if(i > 0) {
242 out.push_back(':');
243 }
244 append_group(groups[i]);
245 }
246 out += "::";
247 for(size_t i = best_start + best_len; i != 8; ++i) {
248 if(i > best_start + best_len) {
249 out.push_back(':');
250 }
251 append_group(groups[i]);
252 }
253 }
254 return out;
255}
256
258 std::array<uint8_t, 16> masked{};
259 for(size_t i = 0; i != 16; ++i) {
260 masked[i] = m_ip[i] & other.m_ip[i];
261 }
262 return IPv6Address(masked);
263}
264
265std::optional<size_t> IPv6Address::prefix_length() const {
266 // Count leading one bits, stopping at the first byte that isn't fully set.
267 size_t leading = 0;
268 for(size_t i = 0; i != 16; ++i) {
269 const size_t hw = (m_ip[i] == 0xFF) ? 8 : std::countl_one(m_ip[i]);
270 leading += hw;
271 if(hw != 8) {
272 break;
273 }
274 }
275
276 // Verify this is exactly equal to a netmask of that size
277 if(*this != netmask(leading)) {
278 return std::nullopt;
279 }
280 return leading;
281}
282
283std::optional<IPv4Address> IPv6Address::as_ipv4() const {
284 const uint32_t ip0 = load_be<uint32_t>(m_ip.data(), 0);
285 const uint32_t ip1 = load_be<uint32_t>(m_ip.data(), 1);
286 const uint32_t ip2 = load_be<uint32_t>(m_ip.data(), 2);
287 const uint32_t ip3 = load_be<uint32_t>(m_ip.data(), 3);
288
289 if(ip0 == 0x00000000 && ip1 == 0x00000000 && (ip2 == 0x00000000 || ip2 == 0x0000FFFF)) {
290 return IPv4Address(ip3);
291 } else {
292 return {};
293 }
294}
295
297 m_address(address & IPv6Address::netmask(prefix_length)), m_prefix_length(static_cast<uint8_t>(prefix_length)) {
298 // IPv6Address::netmask validates prefix_length <= 128, so by this point
299 // the static_cast is in range.
300}
301
302//static
303std::optional<IPv6Subnet> IPv6Subnet::from_address_and_mask(std::span<const uint8_t, 32> addr_and_mask) {
304 const auto addr = IPv6Address(addr_and_mask.first<16>());
305 const auto mask = IPv6Address(addr_and_mask.last<16>());
306
307 if(const auto plen = mask.prefix_length()) {
308 return IPv6Subnet(addr, *plen);
309 } else {
310 return {};
311 }
312}
313
314//static
315std::optional<IPv6Subnet> IPv6Subnet::from_string(std::string_view str) {
316 const auto slash = str.find('/');
317 if(slash == std::string_view::npos) {
318 return std::nullopt;
319 }
320
321 auto addr = IPv6Address::from_string(str.substr(0, slash));
322 if(!addr.has_value()) {
323 return std::nullopt;
324 }
325
326 // Parse the prefix length as a canonical decimal integer in [0, 128]
327 const auto plen_str = str.substr(slash + 1);
328
329 const auto plen = parse_sz(plen_str, /*require_canonical=*/true);
330
331 if(!plen.has_value() || plen.value() > 128) {
332 return std::nullopt;
333 }
334
335 const IPv6Subnet subnet(*addr, plen.value());
336
337 // Require the input to already be canonical: from_string and to_string are
338 // exact inverses, so a non-canonical address (including the IPv4-mapped
339 // dotted form) or a set host bit is rejected rather than masked away
340 if(subnet.to_string() != str) {
341 return std::nullopt;
342 }
343
344 return subnet;
345}
346
347bool IPv6Subnet::contains(const IPv6Address& ip) const {
348 return (ip & IPv6Address::netmask(m_prefix_length)) == m_address;
349}
350
351std::string IPv6Subnet::to_string() const {
352 return fmt("{}/{}", m_address.to_string(), static_cast<size_t>(m_prefix_length));
353}
354
355std::vector<uint8_t> IPv6Subnet::serialize() const {
356 const auto addr = m_address.address();
357 if(is_host()) {
358 return std::vector<uint8_t>(addr.begin(), addr.end());
359 }
360 const auto mask = IPv6Address::netmask(m_prefix_length).address();
361 std::vector<uint8_t> out;
362 out.reserve(32);
363 out.insert(out.end(), addr.begin(), addr.end());
364 out.insert(out.end(), mask.begin(), mask.end());
365 return out;
366}
367
368} // namespace Botan
#define BOTAN_ARG_CHECK(expr, msg)
Definition assert.h:33
std::array< uint8_t, 16 > address() const
std::optional< IPv4Address > as_ipv4() const
IPv6Address(std::span< const uint8_t, 16 > ip)
std::string to_string() const
static IPv6Address netmask(size_t bits)
static std::optional< IPv6Address > from_string(std::string_view str)
IPv6Address operator&(const IPv6Address &other) const
std::optional< size_t > prefix_length() const
bool contains(const IPv6Address &ip) const
True iff ip falls within this subnet.
size_t prefix_length() const
Prefix length in [0, 128].
std::string to_string() const
CIDR-style "2001:db8::/32".
static std::optional< IPv6Subnet > from_address_and_mask(std::span< const uint8_t, 32 > addr_and_mask)
const IPv6Address & address() const
The network address (host bits already zeroed).
static std::optional< IPv6Subnet > from_string(std::string_view str)
IPv6Subnet(IPv6Address address, size_t prefix_length)
bool is_host() const
True iff prefix_length() == 128.
std::vector< uint8_t > serialize() const
std::string fmt(std::string_view format, const T &... args)
Definition fmt.h:53
std::optional< size_t > parse_sz(std::string_view input, bool require_canonical)
Definition parsing.cpp:72
constexpr auto load_be(ParamTs &&... params)
Definition loadstor.h:504
constexpr uint16_t make_uint16(uint8_t i0, uint8_t i1)
Definition loadstor.h:92