]> git.lizzy.rs Git - rust.git/blob - library/std/src/net/parser.rs
Add 'library/portable-simd/' from commit '1ce1c645cf27c4acdefe6ec8a11d1f0491954a99'
[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     ) -> Option<T> {
115         self.read_atomically(move |p| {
116             let mut result = T::ZERO;
117             let mut digit_count = 0;
118
119             while let Some(digit) = p.read_atomically(|p| p.read_char()?.to_digit(radix)) {
120                 result = result.checked_mul(radix)?;
121                 result = result.checked_add(digit)?;
122                 digit_count += 1;
123                 if let Some(max_digits) = max_digits {
124                     if digit_count > max_digits {
125                         return None;
126                     }
127                 }
128             }
129
130             if digit_count == 0 { None } else { Some(result) }
131         })
132     }
133
134     /// Read an IPv4 address.
135     fn read_ipv4_addr(&mut self) -> Option<Ipv4Addr> {
136         self.read_atomically(|p| {
137             let mut groups = [0; 4];
138
139             for (i, slot) in groups.iter_mut().enumerate() {
140                 *slot = p.read_separator('.', i, |p| {
141                     // Disallow octal number in IP string.
142                     // https://tools.ietf.org/html/rfc6943#section-3.1.1
143                     match (p.peek_char(), p.read_number(10, None)) {
144                         (Some('0'), Some(number)) if number != 0 => None,
145                         (_, number) => number,
146                     }
147                 })?;
148             }
149
150             Some(groups.into())
151         })
152     }
153
154     /// Read an IPv6 Address.
155     fn read_ipv6_addr(&mut self) -> Option<Ipv6Addr> {
156         /// Read a chunk of an IPv6 address into `groups`. Returns the number
157         /// of groups read, along with a bool indicating if an embedded
158         /// trailing IPv4 address was read. Specifically, read a series of
159         /// colon-separated IPv6 groups (0x0000 - 0xFFFF), with an optional
160         /// trailing embedded IPv4 address.
161         fn read_groups(p: &mut Parser<'_>, groups: &mut [u16]) -> (usize, bool) {
162             let limit = groups.len();
163
164             for (i, slot) in groups.iter_mut().enumerate() {
165                 // Try to read a trailing embedded IPv4 address. There must be
166                 // at least two groups left.
167                 if i < limit - 1 {
168                     let ipv4 = p.read_separator(':', i, |p| p.read_ipv4_addr());
169
170                     if let Some(v4_addr) = ipv4 {
171                         let [one, two, three, four] = v4_addr.octets();
172                         groups[i + 0] = u16::from_be_bytes([one, two]);
173                         groups[i + 1] = u16::from_be_bytes([three, four]);
174                         return (i + 2, true);
175                     }
176                 }
177
178                 let group = p.read_separator(':', i, |p| p.read_number(16, Some(4)));
179
180                 match group {
181                     Some(g) => *slot = g,
182                     None => return (i, false),
183                 }
184             }
185             (groups.len(), false)
186         }
187
188         self.read_atomically(|p| {
189             // Read the front part of the address; either the whole thing, or up
190             // to the first ::
191             let mut head = [0; 8];
192             let (head_size, head_ipv4) = read_groups(p, &mut head);
193
194             if head_size == 8 {
195                 return Some(head.into());
196             }
197
198             // IPv4 part is not allowed before `::`
199             if head_ipv4 {
200                 return None;
201             }
202
203             // Read `::` if previous code parsed less than 8 groups.
204             // `::` indicates one or more groups of 16 bits of zeros.
205             p.read_given_char(':')?;
206             p.read_given_char(':')?;
207
208             // Read the back part of the address. The :: must contain at least one
209             // set of zeroes, so our max length is 7.
210             let mut tail = [0; 7];
211             let limit = 8 - (head_size + 1);
212             let (tail_size, _) = read_groups(p, &mut tail[..limit]);
213
214             // Concat the head and tail of the IP address
215             head[(8 - tail_size)..8].copy_from_slice(&tail[..tail_size]);
216
217             Some(head.into())
218         })
219     }
220
221     /// Read an IP Address, either IPv4 or IPv6.
222     fn read_ip_addr(&mut self) -> Option<IpAddr> {
223         self.read_ipv4_addr().map(IpAddr::V4).or_else(move || self.read_ipv6_addr().map(IpAddr::V6))
224     }
225
226     /// Read a `:` followed by a port in base 10.
227     fn read_port(&mut self) -> Option<u16> {
228         self.read_atomically(|p| {
229             p.read_given_char(':')?;
230             p.read_number(10, None)
231         })
232     }
233
234     /// Read a `%` followed by a scope ID in base 10.
235     fn read_scope_id(&mut self) -> Option<u32> {
236         self.read_atomically(|p| {
237             p.read_given_char('%')?;
238             p.read_number(10, None)
239         })
240     }
241
242     /// Read an IPv4 address with a port.
243     fn read_socket_addr_v4(&mut self) -> Option<SocketAddrV4> {
244         self.read_atomically(|p| {
245             let ip = p.read_ipv4_addr()?;
246             let port = p.read_port()?;
247             Some(SocketAddrV4::new(ip, port))
248         })
249     }
250
251     /// Read an IPv6 address with a port.
252     fn read_socket_addr_v6(&mut self) -> Option<SocketAddrV6> {
253         self.read_atomically(|p| {
254             p.read_given_char('[')?;
255             let ip = p.read_ipv6_addr()?;
256             let scope_id = p.read_scope_id().unwrap_or(0);
257             p.read_given_char(']')?;
258
259             let port = p.read_port()?;
260             Some(SocketAddrV6::new(ip, port, 0, scope_id))
261         })
262     }
263
264     /// Read an IP address with a port
265     fn read_socket_addr(&mut self) -> Option<SocketAddr> {
266         self.read_socket_addr_v4()
267             .map(SocketAddr::V4)
268             .or_else(|| self.read_socket_addr_v6().map(SocketAddr::V6))
269     }
270 }
271
272 #[stable(feature = "ip_addr", since = "1.7.0")]
273 impl FromStr for IpAddr {
274     type Err = AddrParseError;
275     fn from_str(s: &str) -> Result<IpAddr, AddrParseError> {
276         Parser::new(s).parse_with(|p| p.read_ip_addr())
277     }
278 }
279
280 #[stable(feature = "rust1", since = "1.0.0")]
281 impl FromStr for Ipv4Addr {
282     type Err = AddrParseError;
283     fn from_str(s: &str) -> Result<Ipv4Addr, AddrParseError> {
284         Parser::new(s).parse_with(|p| p.read_ipv4_addr())
285     }
286 }
287
288 #[stable(feature = "rust1", since = "1.0.0")]
289 impl FromStr for Ipv6Addr {
290     type Err = AddrParseError;
291     fn from_str(s: &str) -> Result<Ipv6Addr, AddrParseError> {
292         Parser::new(s).parse_with(|p| p.read_ipv6_addr())
293     }
294 }
295
296 #[stable(feature = "socket_addr_from_str", since = "1.5.0")]
297 impl FromStr for SocketAddrV4 {
298     type Err = AddrParseError;
299     fn from_str(s: &str) -> Result<SocketAddrV4, AddrParseError> {
300         Parser::new(s).parse_with(|p| p.read_socket_addr_v4())
301     }
302 }
303
304 #[stable(feature = "socket_addr_from_str", since = "1.5.0")]
305 impl FromStr for SocketAddrV6 {
306     type Err = AddrParseError;
307     fn from_str(s: &str) -> Result<SocketAddrV6, AddrParseError> {
308         Parser::new(s).parse_with(|p| p.read_socket_addr_v6())
309     }
310 }
311
312 #[stable(feature = "rust1", since = "1.0.0")]
313 impl FromStr for SocketAddr {
314     type Err = AddrParseError;
315     fn from_str(s: &str) -> Result<SocketAddr, AddrParseError> {
316         Parser::new(s).parse_with(|p| p.read_socket_addr())
317     }
318 }
319
320 /// An error which can be returned when parsing an IP address or a socket address.
321 ///
322 /// This error is used as the error type for the [`FromStr`] implementation for
323 /// [`IpAddr`], [`Ipv4Addr`], [`Ipv6Addr`], [`SocketAddr`], [`SocketAddrV4`], and
324 /// [`SocketAddrV6`].
325 ///
326 /// # Potential causes
327 ///
328 /// `AddrParseError` may be thrown because the provided string does not parse as the given type,
329 /// often because it includes information only handled by a different address type.
330 ///
331 /// ```should_panic
332 /// use std::net::IpAddr;
333 /// let _foo: IpAddr = "127.0.0.1:8080".parse().expect("Cannot handle the socket port");
334 /// ```
335 ///
336 /// [`IpAddr`] doesn't handle the port. Use [`SocketAddr`] instead.
337 ///
338 /// ```
339 /// use std::net::SocketAddr;
340 ///
341 /// // No problem, the `panic!` message has disappeared.
342 /// let _foo: SocketAddr = "127.0.0.1:8080".parse().expect("unreachable panic");
343 /// ```
344 #[stable(feature = "rust1", since = "1.0.0")]
345 #[derive(Debug, Clone, PartialEq, Eq)]
346 pub struct AddrParseError(());
347
348 #[stable(feature = "addr_parse_error_error", since = "1.4.0")]
349 impl fmt::Display for AddrParseError {
350     #[allow(deprecated, deprecated_in_future)]
351     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
352         fmt.write_str(self.description())
353     }
354 }
355
356 #[stable(feature = "addr_parse_error_error", since = "1.4.0")]
357 impl Error for AddrParseError {
358     #[allow(deprecated)]
359     fn description(&self) -> &str {
360         "invalid IP address syntax"
361     }
362 }