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