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