strat9_abi/ip.rs
1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! IPv4/IPv6 literal parsing helpers.
24//!
25//! These functions parse IP address literals from strings into byte arrays
26//! suitable for network operations. They handle both dotted-decimal (IPv4)
27//! and colon-hex (IPv6) formats.
28//!
29//! # Examples
30//!
31//! ```ignore
32//! use strat9_abi::ip::{parse_ipv4_literal, parse_ipv6_literal};
33//!
34//! // IPv4
35//! assert_eq!(parse_ipv4_literal("192.168.1.10"), Some([192, 168, 1, 10]));
36//! assert_eq!(parse_ipv4_literal("10.0.0.1"), Some([10, 0, 0, 1]));
37//! assert_eq!(parse_ipv4_literal("256.1.1.1"), None); // octet > 255
38//!
39//! // IPv6
40//! assert_eq!(
41//! parse_ipv6_literal("::1"),
42//! Some([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
43//! );
44//! assert_eq!(
45//! parse_ipv6_literal("fe80::1"),
46//! Some([0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
47//! );
48//! ```
49
50/// Returns true when the input looks like a dotted IPv4 literal candidate.
51///
52/// This is a fast pre-filter: it checks that the string contains only
53/// digits and dots, and has at least one dot. It does NOT validate the
54/// actual address format : use [`parse_ipv4_literal`] for that.
55///
56/// # Example
57///
58/// ```ignore
59/// assert!(is_ipv4_literal_candidate("192.168.1.1"));
60/// assert!(!is_ipv4_literal_candidate("hello"));
61/// assert!(is_ipv4_literal_candidate("999.999.999.999")); // passes filter, fails parse
62/// ```
63pub fn is_ipv4_literal_candidate(s: &str) -> bool {
64 let bytes = s.as_bytes();
65 !bytes.is_empty()
66 && bytes.iter().all(|b| b.is_ascii_digit() || *b == b'.')
67 && bytes.contains(&b'.')
68}
69
70/// Returns true when the input looks like an IPv6 literal candidate.
71///
72/// This is a fast pre-filter: it checks that the string contains only
73/// hex digits, colons, and dots, and has at least one colon.
74///
75/// # Limitations
76///
77/// - IPv4-mapped/embedded forms (e.g. `::ffff:192.168.1.1`) are **not** recognised
78/// as candidates: the embedded decimal octets are not valid hex digits.
79/// - Zone IDs (e.g. `fe80::1%eth0`) are **not** recognised: `%` is not in the
80/// allowed character set.
81pub fn is_ipv6_literal_candidate(s: &str) -> bool {
82 let bytes = s.as_bytes();
83 !bytes.is_empty()
84 && bytes
85 .iter()
86 .all(|b| b.is_ascii_hexdigit() || *b == b':' || *b == b'.')
87 && bytes.contains(&b':')
88}
89
90/// Parses an IPv4 literal into network-order octets.
91///
92/// Input must be in standard dotted-decimal format: `A.B.C.D` where
93/// each octet is 0-255.
94///
95/// Returns `None` if the format is invalid.
96///
97/// # Example
98///
99/// ```ignore
100/// assert_eq!(parse_ipv4_literal("192.168.1.10"), Some([192, 168, 1, 10]));
101/// assert_eq!(parse_ipv4_literal("10.0.0.1"), Some([10, 0, 0, 1]));
102/// assert_eq!(parse_ipv4_literal("0.0.0.0"), Some([0, 0, 0, 0]));
103/// assert_eq!(parse_ipv4_literal("255.255.255.255"), Some([255, 255, 255, 255]));
104///
105/// // Invalid formats
106/// assert_eq!(parse_ipv4_literal(""), None);
107/// assert_eq!(parse_ipv4_literal("192.168.1"), None); // too few octets
108/// assert_eq!(parse_ipv4_literal("192.168.1.1.1"), None); // too many octets
109/// assert_eq!(parse_ipv4_literal("256.1.1.1"), None); // octet > 255
110/// assert_eq!(parse_ipv4_literal("abc.def.ghi.jkl"), None); // non-numeric
111/// ```
112pub fn parse_ipv4_literal(s: &str) -> Option<[u8; 4]> {
113 let mut octets = [0u8; 4];
114 let mut idx = 0usize;
115 let mut val: u16 = 0;
116 let mut has_digit = false;
117
118 for &b in s.as_bytes() {
119 if b == b'.' {
120 if !has_digit || idx >= 3 || val > 255 {
121 return None;
122 }
123 octets[idx] = val as u8;
124 idx += 1;
125 val = 0;
126 has_digit = false;
127 continue;
128 }
129
130 if !b.is_ascii_digit() {
131 return None;
132 }
133
134 val = val.checked_mul(10)?.checked_add((b - b'0') as u16)?;
135 has_digit = true;
136 }
137
138 if !has_digit || idx != 3 || val > 255 {
139 return None;
140 }
141
142 octets[3] = val as u8;
143 Some(octets)
144}
145
146/// Parses a hex string of 1-4 digits into a `u16`.
147fn parse_hex_u16(s: &str) -> Option<u16> {
148 if s.is_empty() || s.len() > 4 {
149 return None;
150 }
151
152 let mut value = 0u16;
153 for &b in s.as_bytes() {
154 let digit = match b {
155 b'0'..=b'9' => (b - b'0') as u16,
156 b'a'..=b'f' => 10 + (b - b'a') as u16,
157 b'A'..=b'F' => 10 + (b - b'A') as u16,
158 _ => return None,
159 };
160 value = value.checked_mul(16)?.checked_add(digit)?;
161 }
162
163 Some(value)
164}
165
166/// Parses an IPv6 literal into network-order octets.
167///
168/// Supports standard colon-hex notation (RFC 4291) with `::` compression.
169///
170/// # Limitations
171///
172/// - IPv4-mapped/embedded forms (e.g. `::ffff:192.168.1.1`) are **not** supported;
173/// only pure colon-hex notation is accepted.
174/// - Zone IDs (e.g. `fe80::1%eth0`) are **not** supported; the zone identifier
175/// must be stripped before calling this function.
176///
177/// # Example
178///
179/// ```ignore
180/// assert_eq!(
181/// parse_ipv6_literal("2001:0db8:0000:0000:0000:ff00:0042:8329"),
182/// Some([
183/// 0x20, 0x01, 0x0d, 0xb8, 0x00, 0x00, 0x00, 0x00,
184/// 0x00, 0x00, 0xff, 0x00, 0x00, 0x42, 0x83, 0x29,
185/// ])
186/// );
187///
188/// // Compressed forms
189/// assert_eq!(
190/// parse_ipv6_literal("::1"),
191/// Some([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
192/// );
193/// assert_eq!(
194/// parse_ipv6_literal("fe80::5054:ff:fe12:3456"),
195/// Some([
196/// 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
197/// 0x50, 0x54, 0x00, 0xff, 0xfe, 0x12, 0x34, 0x56,
198/// ])
199/// );
200///
201/// // Loopback
202/// assert_eq!(
203/// parse_ipv6_literal("::1"),
204/// Some([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
205/// );
206/// ```
207pub fn parse_ipv6_literal(s: &str) -> Option<[u8; 16]> {
208 let mut groups = [0u16; 8];
209
210 if let Some(dc) = s.find("::") {
211 let left = &s[..dc];
212 let right = &s[dc + 2..];
213 let mut left_count = 0usize;
214 if !left.is_empty() {
215 for part in left.split(':') {
216 if left_count >= 8 {
217 return None;
218 }
219 groups[left_count] = parse_hex_u16(part)?;
220 left_count += 1;
221 }
222 }
223
224 let mut right_groups = [0u16; 8];
225 let mut right_count = 0usize;
226 if !right.is_empty() {
227 for part in right.split(':') {
228 if right_count >= 8 {
229 return None;
230 }
231 right_groups[right_count] = parse_hex_u16(part)?;
232 right_count += 1;
233 }
234 }
235
236 if left_count + right_count > 8 {
237 return None;
238 }
239
240 let start = 8 - right_count;
241 for i in 0..right_count {
242 groups[start + i] = right_groups[i];
243 }
244 } else {
245 let mut count = 0usize;
246 for part in s.split(':') {
247 if count >= 8 {
248 return None;
249 }
250 groups[count] = parse_hex_u16(part)?;
251 count += 1;
252 }
253 if count != 8 {
254 return None;
255 }
256 }
257
258 let mut octets = [0u8; 16];
259 for (idx, &group) in groups.iter().enumerate() {
260 octets[2 * idx] = (group >> 8) as u8;
261 octets[2 * idx + 1] = (group & 0xFF) as u8;
262 }
263
264 Some(octets)
265}
266
267#[cfg(test)]
268mod tests {
269 use super::{parse_ipv4_literal, parse_ipv6_literal};
270
271 #[test]
272 fn parses_ipv4_literal() {
273 assert_eq!(parse_ipv4_literal("192.168.1.10"), Some([192, 168, 1, 10]));
274 }
275
276 #[test]
277 fn parses_full_ipv6_literal() {
278 assert_eq!(
279 parse_ipv6_literal("2001:0db8:0000:0000:0000:ff00:0042:8329"),
280 Some([
281 0x20, 0x01, 0x0d, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x42,
282 0x83, 0x29,
283 ])
284 );
285 }
286
287 #[test]
288 fn parses_compressed_ipv6_literal() {
289 assert_eq!(
290 parse_ipv6_literal("fe80::5054:ff:fe12:3456"),
291 Some([
292 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x54, 0x00, 0xff, 0xfe, 0x12,
293 0x34, 0x56,
294 ])
295 );
296 }
297
298 #[test]
299 fn rejects_multiple_double_colons() {
300 assert_eq!(parse_ipv6_literal("fe80::5054::ff::fe12::3456"), None);
301 }
302}