]> git.lizzy.rs Git - rust.git/blob - library/std/src/net/parser.rs
Rollup merge of #96129 - mattheww:2022-04_float_rounding, r=Dylan-DPC
[rust.git] / library / std / src / net / parser.rs
1 //! A private parser implementation of IPv4, IPv6, and socket addresses.
2 //!
3 //! This module is "publicly exported" through the `FromStr` implementations
4 //! below.
5
6 #[cfg(test)]
7 mod tests;
8
9 use crate::error::Error;
10 use crate::fmt;
11 use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
12 use crate::str::FromStr;
13
14 trait ReadNumberHelper: crate::marker::Sized {
15     const ZERO: Self;
16     fn checked_mul(&self, other: u32) -> Option<Self>;
17     fn checked_add(&self, other: u32) -> Option<Self>;
18 }
19
20 macro_rules! impl_helper {
21     ($($t:ty)*) => ($(impl ReadNumberHelper for $t {
22         const ZERO: Self = 0;
23         #[inline]
24         fn checked_mul(&self, other: u32) -> Option<Self> {
25             Self::checked_mul(*self, other.try_into().ok()?)
26         }
27         #[inline]
28         fn checked_add(&self, other: u32) -> Option<Self> {
29             Self::checked_add(*self, other.try_into().ok()?)
30         }
31     })*)
32 }
33
34 impl_helper! { u8 u16 u32 }
35
36 struct Parser<'a> {
37     // Parsing as ASCII, so can use byte array.
38     state: &'a [u8],
39 }
40
41 impl<'a> Parser<'a> {
42     fn new(input: &'a str) -> Parser<'a> {
43         Parser { state: input.as_bytes() }
44     }
45
46     /// Run a parser, and restore the pre-parse state if it fails.
47     fn read_atomically<T, F>(&mut self, inner: F) -> Option<T>
48     where
49         F: FnOnce(&mut Parser<'_>) -> Option<T>,
50     {
51         let state = self.state;
52         let result = inner(self);
53         if result.is_none() {
54             self.state = state;
55         }
56         result
57     }
58
59     /// Run a parser, but fail if the entire input wasn't consumed.
60     /// Doesn't run atomically.
61     fn parse_with<T, F>(&mut self, inner: F, kind: AddrKind) -> Result<T, AddrParseError>
62     where
63         F: FnOnce(&mut Parser<'_>) -> Option<T>,
64     {
65         let result = inner(self);
66         if self.state.is_empty() { result } else { None }.ok_or(AddrParseError(kind))
67     }
68
69     /// Peek the next character from the input
70     fn peek_char(&self) -> Option<char> {
71         self.state.first().map(|&b| char::from(b))
72     }
73
74     /// Read the next character from the input
75     fn read_char(&mut self) -> Option<char> {
76         self.state.split_first().map(|(&b, tail)| {
77             self.state = tail;
78             char::from(b)
79         })
80     }
81
82     #[must_use]
83     /// Read the next character from the input if it matches the target.
84     fn read_given_char(&mut self, target: char) -> Option<()> {
85         self.read_atomically(|p| {
86             p.read_char().and_then(|c| if c == target { Some(()) } else { None })
87         })
88     }
89
90     /// Helper for reading separators in an indexed loop. Reads the separator
91     /// character iff index > 0, then runs the parser. When used in a loop,
92     /// the separator character will only be read on index > 0 (see
93     /// read_ipv4_addr for an example)
94     fn read_separator<T, F>(&mut self, sep: char, index: usize, inner: F) -> Option<T>
95     where
96         F: FnOnce(&mut Parser<'_>) -> Option<T>,
97     {
98         self.read_atomically(move |p| {
99             if index > 0 {
100                 p.read_given_char(sep)?;
101             }
102             inner(p)
103         })
104     }
105
106     // Read a number off the front of the input in the given radix, stopping
107     // at the first non-digit character or eof. Fails if the number has more
108     // digits than max_digits or if there is no number.
109     fn read_number<T: ReadNumberHelper>(
110         &mut self,
111         radix: u32,
112         max_digits: Option<usize>,
113         allow_zero_prefix: bool,
114     ) -> Option<T> {
115         self.read_atomically(move |p| {
116             let mut result = T::ZERO;
117             let mut digit_count = 0;
118             let has_leading_zero = p.peek_char() == Some('0');
119
120             while let Some(digit) = p.read_atomically(|p| p.read_char()?.to_digit(radix)) {
121                 result = result.checked_mul(radix)?;
122                 result = result.checked_add(digit)?;
123                 digit_count += 1;
124                 if let Some(max_digits) = max_digits {
125                     if digit_count > max_digits {
126                         return None;
127                     }
128                 }
129             }
130
131             if digit_count == 0 {
132                 None
133             } else if !allow_zero_prefix && has_leading_zero && digit_count > 1 {
134                 None
135             } else {
136                 Some(result)
137             }
138         })
139     }
140
141     /// Read an IPv4 address.
142     fn read_ipv4_addr(&mut self) -> Option<Ipv4Addr> {
143         self.read_atomically(|p| {
144             let mut groups = [0; 4];
145
146             for (i, slot) in groups.iter_mut().enumerate() {
147                 *slot = p.read_separator('.', i, |p| {
148                     // Disallow octal number in IP string.
149                     // https://tools.ietf.org/html/rfc6943#section-3.1.1
150                     p.read_number(10, Some(3), false)
151                 })?;
152             }
153
154             Some(groups.into())
155         })
156     }
157
158     /// Read an IPv6 Address.
159     fn read_ipv6_addr(&mut self) -> Option<Ipv6Addr> {
160         /// Read a chunk of an IPv6 address into `groups`. Returns the number
161         /// of groups read, along with a bool indicating if an embedded
162         /// trailing IPv4 address was read. Specifically, read a series of
163         /// colon-separated IPv6 groups (0x0000 - 0xFFFF), with an optional
164         /// trailing embedded IPv4 address.
165         fn read_groups(p: &mut Parser<'_>, groups: &mut [u16]) -> (usize, bool) {
166             let limit = groups.len();
167
168             for (i, slot) in groups.iter_mut().enumerate() {
169                 // Try to read a trailing embedded IPv4 address. There must be
170                 // at least two groups left.
171                 if i < limit - 1 {
172                     let ipv4 = p.read_separator(':', i, |p| p.read_ipv4_addr());
173
174                     if let Some(v4_addr) = ipv4 {
175                         let [one, two, three, four] = v4_addr.octets();
176                         groups[i + 0] = u16::from_be_bytes([one, two]);
177                         groups[i + 1] = u16::from_be_bytes([three, four]);
178                         return (i + 2, true);
179                     }
180                 }
181
182                 let group = p.read_separator(':', i, |p| p.read_number(16, Some(4), true));
183
184                 match group {
185                     Some(g) => *slot = g,
186                     None => return (i, false),
187                 }
188             }
189             (groups.len(), false)
190         }
191
192         self.read_atomically(|p| {
193             // Read the front part of the address; either the whole thing, or up
194             // to the first ::
195             let mut head = [0; 8];
196             let (head_size, head_ipv4) = read_groups(p, &mut head);
197
198             if head_size == 8 {
199                 return Some(head.into());
200             }
201
202             // IPv4 part is not allowed before `::`
203             if head_ipv4 {
204                 return None;
205             }
206
207             // Read `::` if previous code parsed less than 8 groups.
208             // `::` indicates one or more groups of 16 bits of zeros.
209             p.read_given_char(':')?;
210             p.read_given_char(':')?;
211
212             // Read the back part of the address. The :: must contain at least one
213             // set of zeroes, so our max length is 7.
214             let mut tail = [0; 7];
215             let limit = 8 - (head_size + 1);
216             let (tail_size, _) = read_groups(p, &mut tail[..limit]);
217
218             // Concat the head and tail of the IP address
219             head[(8 - tail_size)..8].copy_from_slice(&tail[..tail_size]);
220
221             Some(head.into())
222         })
223     }
224
225     /// Read an IP Address, either IPv4 or IPv6.
226     fn read_ip_addr(&mut self) -> Option<IpAddr> {
227         self.read_ipv4_addr().map(IpAddr::V4).or_else(move || self.read_ipv6_addr().map(IpAddr::V6))
228     }
229
230     /// Read a `:` followed by a port in base 10.
231     fn read_port(&mut self) -> Option<u16> {
232         self.read_atomically(|p| {
233             p.read_given_char(':')?;
234             p.read_number(10, None, true)
235         })
236     }
237
238     /// Read a `%` followed by a scope ID in base 10.
239     fn read_scope_id(&mut self) -> Option<u32> {
240         self.read_atomically(|p| {
241             p.read_given_char('%')?;
242             p.read_number(10, None, true)
243         })
244     }
245
246     /// Read an IPv4 address with a port.
247     fn read_socket_addr_v4(&mut self) -> Option<SocketAddrV4> {
248         self.read_atomically(|p| {
249             let ip = p.read_ipv4_addr()?;
250             let port = p.read_port()?;
251             Some(SocketAddrV4::new(ip, port))
252         })
253     }
254
255     /// Read an IPv6 address with a port.
256     fn read_socket_addr_v6(&mut self) -> Option<SocketAddrV6> {
257         self.read_atomically(|p| {
258             p.read_given_char('[')?;
259             let ip = p.read_ipv6_addr()?;
260             let scope_id = p.read_scope_id().unwrap_or(0);
261             p.read_given_char(']')?;
262
263             let port = p.read_port()?;
264             Some(SocketAddrV6::new(ip, port, 0, scope_id))
265         })
266     }
267
268     /// Read an IP address with a port
269     fn read_socket_addr(&mut self) -> Option<SocketAddr> {
270         self.read_socket_addr_v4()
271             .map(SocketAddr::V4)
272             .or_else(|| self.read_socket_addr_v6().map(SocketAddr::V6))
273     }
274 }
275
276 #[stable(feature = "ip_addr", since = "1.7.0")]
277 impl FromStr for IpAddr {
278     type Err = AddrParseError;
279     fn from_str(s: &str) -> Result<IpAddr, AddrParseError> {
280         Parser::new(s).parse_with(|p| p.read_ip_addr(), AddrKind::Ip)
281     }
282 }
283
284 #[stable(feature = "rust1", since = "1.0.0")]
285 impl FromStr for Ipv4Addr {
286     type Err = AddrParseError;
287     fn from_str(s: &str) -> Result<Ipv4Addr, AddrParseError> {
288         // don't try to parse if too long
289         if s.len() > 15 {
290             Err(AddrParseError(AddrKind::Ipv4))
291         } else {
292             Parser::new(s).parse_with(|p| p.read_ipv4_addr(), AddrKind::Ipv4)
293         }
294     }
295 }
296
297 #[stable(feature = "rust1", since = "1.0.0")]
298 impl FromStr for Ipv6Addr {
299     type Err = AddrParseError;
300     fn from_str(s: &str) -> Result<Ipv6Addr, AddrParseError> {
301         Parser::new(s).parse_with(|p| p.read_ipv6_addr(), AddrKind::Ipv6)
302     }
303 }
304
305 #[stable(feature = "socket_addr_from_str", since = "1.5.0")]
306 impl FromStr for SocketAddrV4 {
307     type Err = AddrParseError;
308     fn from_str(s: &str) -> Result<SocketAddrV4, AddrParseError> {
309         Parser::new(s).parse_with(|p| p.read_socket_addr_v4(), AddrKind::SocketV4)
310     }
311 }
312
313 #[stable(feature = "socket_addr_from_str", since = "1.5.0")]
314 impl FromStr for SocketAddrV6 {
315     type Err = AddrParseError;
316     fn from_str(s: &str) -> Result<SocketAddrV6, AddrParseError> {
317         Parser::new(s).parse_with(|p| p.read_socket_addr_v6(), AddrKind::SocketV6)
318     }
319 }
320
321 #[stable(feature = "rust1", since = "1.0.0")]
322 impl FromStr for SocketAddr {
323     type Err = AddrParseError;
324     fn from_str(s: &str) -> Result<SocketAddr, AddrParseError> {
325         Parser::new(s).parse_with(|p| p.read_socket_addr(), AddrKind::Socket)
326     }
327 }
328
329 #[derive(Debug, Clone, PartialEq, Eq)]
330 enum AddrKind {
331     Ip,
332     Ipv4,
333     Ipv6,
334     Socket,
335     SocketV4,
336     SocketV6,
337 }
338
339 /// An error which can be returned when parsing an IP address or a socket address.
340 ///
341 /// This error is used as the error type for the [`FromStr`] implementation for
342 /// [`IpAddr`], [`Ipv4Addr`], [`Ipv6Addr`], [`SocketAddr`], [`SocketAddrV4`], and
343 /// [`SocketAddrV6`].
344 ///
345 /// # Potential causes
346 ///
347 /// `AddrParseError` may be thrown because the provided string does not parse as the given type,
348 /// often because it includes information only handled by a different address type.
349 ///
350 /// ```should_panic
351 /// use std::net::IpAddr;
352 /// let _foo: IpAddr = "127.0.0.1:8080".parse().expect("Cannot handle the socket port");
353 /// ```
354 ///
355 /// [`IpAddr`] doesn't handle the port. Use [`SocketAddr`] instead.
356 ///
357 /// ```
358 /// use std::net::SocketAddr;
359 ///
360 /// // No problem, the `panic!` message has disappeared.
361 /// let _foo: SocketAddr = "127.0.0.1:8080".parse().expect("unreachable panic");
362 /// ```
363 #[stable(feature = "rust1", since = "1.0.0")]
364 #[derive(Debug, Clone, PartialEq, Eq)]
365 pub struct AddrParseError(AddrKind);
366
367 #[stable(feature = "addr_parse_error_error", since = "1.4.0")]
368 impl fmt::Display for AddrParseError {
369     #[allow(deprecated, deprecated_in_future)]
370     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
371         fmt.write_str(self.description())
372     }
373 }
374
375 #[stable(feature = "addr_parse_error_error", since = "1.4.0")]
376 impl Error for AddrParseError {
377     #[allow(deprecated)]
378     fn description(&self) -> &str {
379         match self.0 {
380             AddrKind::Ip => "invalid IP address syntax",
381             AddrKind::Ipv4 => "invalid IPv4 address syntax",
382             AddrKind::Ipv6 => "invalid IPv6 address syntax",
383             AddrKind::Socket => "invalid socket address syntax",
384             AddrKind::SocketV4 => "invalid IPv4 socket address syntax",
385             AddrKind::SocketV6 => "invalid IPv6 socket address syntax",
386         }
387     }
388 }