1 | //! A private parser implementation of IPv4 and IPv6 network addresses. |
2 | //! |
3 | //! The existing `std::net::parser` module cannot be extended because it |
4 | //! is private. It is copied and extended here with methods for parsing |
5 | //! IP network addresses. |
6 | |
7 | use alloc::{str::FromStr, boxed::Box}; |
8 | use core::fmt; |
9 | #[cfg (not(feature = "std" ))] |
10 | use core::error::Error; |
11 | #[cfg (feature = "std" )] |
12 | use std::error::Error; |
13 | #[cfg (not(feature = "std" ))] |
14 | use core::net::{Ipv4Addr, Ipv6Addr}; |
15 | #[cfg (feature = "std" )] |
16 | use std::net::{Ipv4Addr, Ipv6Addr}; |
17 | |
18 | use crate::ipnet::{IpNet, Ipv4Net, Ipv6Net}; |
19 | |
20 | pub struct Parser<'a> { |
21 | // parsing as ASCII, so can use byte array |
22 | s: &'a [u8], |
23 | pos: usize, |
24 | } |
25 | |
26 | impl<'a> Parser<'a> { |
27 | fn new(s: &'a str) -> Parser<'a> { |
28 | Parser { |
29 | s: s.as_bytes(), |
30 | pos: 0, |
31 | } |
32 | } |
33 | |
34 | fn is_eof(&self) -> bool { |
35 | self.pos == self.s.len() |
36 | } |
37 | |
38 | // Commit only if parser returns Some |
39 | fn read_atomically<T, F>(&mut self, cb: F) -> Option<T> where |
40 | F: FnOnce(&mut Parser) -> Option<T>, |
41 | { |
42 | let pos = self.pos; |
43 | let r = cb(self); |
44 | if r.is_none() { |
45 | self.pos = pos; |
46 | } |
47 | r |
48 | } |
49 | |
50 | // Commit only if parser read till EOF |
51 | fn read_till_eof<T, F>(&mut self, cb: F) -> Option<T> where |
52 | F: FnOnce(&mut Parser) -> Option<T>, |
53 | { |
54 | self.read_atomically(move |p| { |
55 | match cb(p) { |
56 | Some(x) => if p.is_eof() {Some(x)} else {None}, |
57 | None => None, |
58 | } |
59 | }) |
60 | } |
61 | |
62 | // Return result of first successful parser |
63 | fn read_or<T>(&mut self, parsers: &mut [Box<dyn FnMut(&mut Parser) -> Option<T> + 'static>]) |
64 | -> Option<T> { |
65 | for pf in parsers { |
66 | if let Some(r) = self.read_atomically(|p: &mut Parser| pf(p)) { |
67 | return Some(r); |
68 | } |
69 | } |
70 | None |
71 | } |
72 | |
73 | // Apply 3 parsers sequentially |
74 | fn read_seq_3<A, B, C, PA, PB, PC>(&mut self, |
75 | pa: PA, |
76 | pb: PB, |
77 | pc: PC) |
78 | -> Option<(A, B, C)> where |
79 | PA: FnOnce(&mut Parser) -> Option<A>, |
80 | PB: FnOnce(&mut Parser) -> Option<B>, |
81 | PC: FnOnce(&mut Parser) -> Option<C>, |
82 | { |
83 | self.read_atomically(move |p| { |
84 | let a = pa(p); |
85 | let b = if a.is_some() { pb(p) } else { None }; |
86 | let c = if b.is_some() { pc(p) } else { None }; |
87 | match (a, b, c) { |
88 | (Some(a), Some(b), Some(c)) => Some((a, b, c)), |
89 | _ => None |
90 | } |
91 | }) |
92 | } |
93 | |
94 | // Read next char |
95 | fn read_char(&mut self) -> Option<char> { |
96 | if self.is_eof() { |
97 | None |
98 | } else { |
99 | let r = self.s[self.pos] as char; |
100 | self.pos += 1; |
101 | Some(r) |
102 | } |
103 | } |
104 | |
105 | // Return char and advance iff next char is equal to requested |
106 | fn read_given_char(&mut self, c: char) -> Option<char> { |
107 | self.read_atomically(|p| { |
108 | match p.read_char() { |
109 | Some(next) if next == c => Some(next), |
110 | _ => None, |
111 | } |
112 | }) |
113 | } |
114 | |
115 | // Read digit |
116 | fn read_digit(&mut self, radix: u8) -> Option<u8> { |
117 | fn parse_digit(c: char, radix: u8) -> Option<u8> { |
118 | let c = c as u8; |
119 | // assuming radix is either 10 or 16 |
120 | if c >= b'0' && c <= b'9' { |
121 | Some(c - b'0' ) |
122 | } else if radix > 10 && c >= b'a' && c < b'a' + (radix - 10) { |
123 | Some(c - b'a' + 10) |
124 | } else if radix > 10 && c >= b'A' && c < b'A' + (radix - 10) { |
125 | Some(c - b'A' + 10) |
126 | } else { |
127 | None |
128 | } |
129 | } |
130 | |
131 | self.read_atomically(|p| { |
132 | p.read_char().and_then(|c| parse_digit(c, radix)) |
133 | }) |
134 | } |
135 | |
136 | fn read_number_impl(&mut self, radix: u8, max_digits: u32, upto: u32) -> Option<u32> { |
137 | let mut r = 0; |
138 | let mut digit_count = 0; |
139 | loop { |
140 | match self.read_digit(radix) { |
141 | Some(d) => { |
142 | r = r * (radix as u32) + (d as u32); |
143 | digit_count += 1; |
144 | if digit_count > max_digits || r >= upto { |
145 | return None |
146 | } |
147 | } |
148 | None => { |
149 | if digit_count == 0 { |
150 | return None |
151 | } else { |
152 | return Some(r) |
153 | } |
154 | } |
155 | }; |
156 | } |
157 | } |
158 | |
159 | // Read number, failing if max_digits of number value exceeded |
160 | fn read_number(&mut self, radix: u8, max_digits: u32, upto: u32) -> Option<u32> { |
161 | self.read_atomically(|p| p.read_number_impl(radix, max_digits, upto)) |
162 | } |
163 | |
164 | fn read_ipv4_addr_impl(&mut self) -> Option<Ipv4Addr> { |
165 | let mut bs = [0; 4]; |
166 | let mut i = 0; |
167 | while i < 4 { |
168 | if i != 0 && self.read_given_char('.' ).is_none() { |
169 | return None; |
170 | } |
171 | |
172 | let octet = self.read_number(10, 3, 0x100).map(|n| n as u8); |
173 | match octet { |
174 | Some(d) => bs[i] = d, |
175 | None => return None, |
176 | }; |
177 | i += 1; |
178 | } |
179 | Some(Ipv4Addr::new(bs[0], bs[1], bs[2], bs[3])) |
180 | } |
181 | |
182 | // Read IPv4 address |
183 | fn read_ipv4_addr(&mut self) -> Option<Ipv4Addr> { |
184 | self.read_atomically(|p| p.read_ipv4_addr_impl()) |
185 | } |
186 | |
187 | fn read_ipv6_addr_impl(&mut self) -> Option<Ipv6Addr> { |
188 | fn ipv6_addr_from_head_tail(head: &[u16], tail: &[u16]) -> Ipv6Addr { |
189 | assert!(head.len() + tail.len() <= 8); |
190 | let mut gs = [0; 8]; |
191 | gs[..head.len()].copy_from_slice(head); |
192 | gs[(8 - tail.len()) .. 8].copy_from_slice(tail); |
193 | Ipv6Addr::new(gs[0], gs[1], gs[2], gs[3], gs[4], gs[5], gs[6], gs[7]) |
194 | } |
195 | |
196 | fn read_groups(p: &mut Parser, groups: &mut [u16; 8], limit: usize) |
197 | -> (usize, bool) { |
198 | let mut i = 0; |
199 | while i < limit { |
200 | if i < limit - 1 { |
201 | let ipv4 = p.read_atomically(|p| { |
202 | if i == 0 || p.read_given_char(':' ).is_some() { |
203 | p.read_ipv4_addr() |
204 | } else { |
205 | None |
206 | } |
207 | }); |
208 | if let Some(v4_addr) = ipv4 { |
209 | let octets = v4_addr.octets(); |
210 | groups[i + 0] = ((octets[0] as u16) << 8) | (octets[1] as u16); |
211 | groups[i + 1] = ((octets[2] as u16) << 8) | (octets[3] as u16); |
212 | return (i + 2, true); |
213 | } |
214 | } |
215 | |
216 | let group = p.read_atomically(|p| { |
217 | if i == 0 || p.read_given_char(':' ).is_some() { |
218 | p.read_number(16, 4, 0x10000).map(|n| n as u16) |
219 | } else { |
220 | None |
221 | } |
222 | }); |
223 | match group { |
224 | Some(g) => groups[i] = g, |
225 | None => return (i, false) |
226 | } |
227 | i += 1; |
228 | } |
229 | (i, false) |
230 | } |
231 | |
232 | let mut head = [0; 8]; |
233 | let (head_size, head_ipv4) = read_groups(self, &mut head, 8); |
234 | |
235 | if head_size == 8 { |
236 | return Some(Ipv6Addr::new( |
237 | head[0], head[1], head[2], head[3], |
238 | head[4], head[5], head[6], head[7])) |
239 | } |
240 | |
241 | // IPv4 part is not allowed before `::` |
242 | if head_ipv4 { |
243 | return None |
244 | } |
245 | |
246 | // read `::` if previous code parsed less than 8 groups |
247 | if !self.read_given_char(':' ).is_some() || !self.read_given_char(':' ).is_some() { |
248 | return None; |
249 | } |
250 | |
251 | let mut tail = [0; 8]; |
252 | let (tail_size, _) = read_groups(self, &mut tail, 8 - head_size); |
253 | Some(ipv6_addr_from_head_tail(&head[..head_size], &tail[..tail_size])) |
254 | } |
255 | |
256 | fn read_ipv6_addr(&mut self) -> Option<Ipv6Addr> { |
257 | self.read_atomically(|p| p.read_ipv6_addr_impl()) |
258 | } |
259 | |
260 | /* Additions for IpNet below. */ |
261 | |
262 | // Read IPv4 network |
263 | fn read_ipv4_net(&mut self) -> Option<Ipv4Net> { |
264 | let ip_addr = |p: &mut Parser| p.read_ipv4_addr(); |
265 | let slash = |p: &mut Parser| p.read_given_char('/' ); |
266 | let prefix_len = |p: &mut Parser| { |
267 | p.read_number(10, 2, 33).map(|n| n as u8) |
268 | }; |
269 | |
270 | self.read_seq_3(ip_addr, slash, prefix_len).map(|t| { |
271 | let (ip, _, prefix_len): (Ipv4Addr, char, u8) = t; |
272 | Ipv4Net::new(ip, prefix_len).unwrap() |
273 | }) |
274 | } |
275 | |
276 | // Read Ipv6 network |
277 | fn read_ipv6_net(&mut self) -> Option<Ipv6Net> { |
278 | let ip_addr = |p: &mut Parser| p.read_ipv6_addr(); |
279 | let slash = |p: &mut Parser| p.read_given_char('/' ); |
280 | let prefix_len = |p: &mut Parser| { |
281 | p.read_number(10, 3, 129).map(|n| n as u8) |
282 | }; |
283 | |
284 | self.read_seq_3(ip_addr, slash, prefix_len).map(|t| { |
285 | let (ip, _, prefix_len): (Ipv6Addr, char, u8) = t; |
286 | Ipv6Net::new(ip, prefix_len).unwrap() |
287 | }) |
288 | } |
289 | |
290 | fn read_ip_net(&mut self) -> Option<IpNet> { |
291 | let ipv4_net = |p: &mut Parser| p.read_ipv4_net().map(IpNet::V4); |
292 | let ipv6_net = |p: &mut Parser| p.read_ipv6_net().map(IpNet::V6); |
293 | self.read_or(&mut [Box::new(ipv4_net), Box::new(ipv6_net)]) |
294 | } |
295 | |
296 | /* Additions for IpNet above. */ |
297 | } |
298 | |
299 | /* Additions for IpNet below. */ |
300 | |
301 | impl FromStr for IpNet { |
302 | type Err = AddrParseError; |
303 | fn from_str(s: &str) -> Result<IpNet, AddrParseError> { |
304 | match Parser::new(s).read_till_eof(|p: &mut Parser<'_>| p.read_ip_net()) { |
305 | Some(s: IpNet) => Ok(s), |
306 | None => Err(AddrParseError(())) |
307 | } |
308 | } |
309 | } |
310 | |
311 | impl FromStr for Ipv4Net { |
312 | type Err = AddrParseError; |
313 | fn from_str(s: &str) -> Result<Ipv4Net, AddrParseError> { |
314 | match Parser::new(s).read_till_eof(|p: &mut Parser<'_>| p.read_ipv4_net()) { |
315 | Some(s: Ipv4Net) => Ok(s), |
316 | None => Err(AddrParseError(())) |
317 | } |
318 | } |
319 | } |
320 | |
321 | impl FromStr for Ipv6Net { |
322 | type Err = AddrParseError; |
323 | fn from_str(s: &str) -> Result<Ipv6Net, AddrParseError> { |
324 | match Parser::new(s).read_till_eof(|p: &mut Parser<'_>| p.read_ipv6_net()) { |
325 | Some(s: Ipv6Net) => Ok(s), |
326 | None => Err(AddrParseError(())) |
327 | } |
328 | } |
329 | } |
330 | |
331 | /* Additions for IpNet above. */ |
332 | |
333 | /// An error which can be returned when parsing an IP network address. |
334 | /// |
335 | /// This error is used as the error type for the [`FromStr`] implementation for |
336 | /// [`IpNet`], [`Ipv4Net`], and [`Ipv6Net`]. |
337 | /// |
338 | /// [`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html |
339 | /// [`IpNet`]: enum.IpNet.html |
340 | /// [`Ipv4Net`]: struct.Ipv4Net.html |
341 | /// [`Ipv6Net`]: struct.Ipv6Net.html |
342 | #[derive (Debug, Clone, PartialEq, Eq)] |
343 | pub struct AddrParseError(()); |
344 | |
345 | impl fmt::Display for AddrParseError { |
346 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |
347 | fmt.write_str(data:"invalid IP address syntax" ) |
348 | } |
349 | } |
350 | |
351 | impl Error for AddrParseError {} |
352 | |