]> git.lizzy.rs Git - rust.git/blob - library/std/src/net/addr/parser/mod.rs
Move `net::parser` into `net::addr` module.
[rust.git] / library / std / src / net / addr / parser / mod.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 [u8]) -> Parser<'a> {
43         Parser { state: input }
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 impl IpAddr {
277     /// Parse an IP address from a slice of bytes.
278     ///
279     /// ```
280     /// #![feature(addr_parse_ascii)]
281     ///
282     /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
283     ///
284     /// let localhost_v4 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
285     /// let localhost_v6 = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
286     ///
287     /// assert_eq!(IpAddr::parse_ascii(b"127.0.0.1"), Ok(localhost_v4));
288     /// assert_eq!(IpAddr::parse_ascii(b"::1"), Ok(localhost_v6));
289     /// ```
290     #[unstable(feature = "addr_parse_ascii", issue = "101035")]
291     pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> {
292         Parser::new(b).parse_with(|p| p.read_ip_addr(), AddrKind::Ip)
293     }
294 }
295
296 #[stable(feature = "ip_addr", since = "1.7.0")]
297 impl FromStr for IpAddr {
298     type Err = AddrParseError;
299     fn from_str(s: &str) -> Result<IpAddr, AddrParseError> {
300         Self::parse_ascii(s.as_bytes())
301     }
302 }
303
304 impl Ipv4Addr {
305     /// Parse an IPv4 address from a slice of bytes.
306     ///
307     /// ```
308     /// #![feature(addr_parse_ascii)]
309     ///
310     /// use std::net::Ipv4Addr;
311     ///
312     /// let localhost = Ipv4Addr::new(127, 0, 0, 1);
313     ///
314     /// assert_eq!(Ipv4Addr::parse_ascii(b"127.0.0.1"), Ok(localhost));
315     /// ```
316     #[unstable(feature = "addr_parse_ascii", issue = "101035")]
317     pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> {
318         // don't try to parse if too long
319         if b.len() > 15 {
320             Err(AddrParseError(AddrKind::Ipv4))
321         } else {
322             Parser::new(b).parse_with(|p| p.read_ipv4_addr(), AddrKind::Ipv4)
323         }
324     }
325 }
326
327 #[stable(feature = "rust1", since = "1.0.0")]
328 impl FromStr for Ipv4Addr {
329     type Err = AddrParseError;
330     fn from_str(s: &str) -> Result<Ipv4Addr, AddrParseError> {
331         Self::parse_ascii(s.as_bytes())
332     }
333 }
334
335 impl Ipv6Addr {
336     /// Parse an IPv6 address from a slice of bytes.
337     ///
338     /// ```
339     /// #![feature(addr_parse_ascii)]
340     ///
341     /// use std::net::Ipv6Addr;
342     ///
343     /// let localhost = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
344     ///
345     /// assert_eq!(Ipv6Addr::parse_ascii(b"::1"), Ok(localhost));
346     /// ```
347     #[unstable(feature = "addr_parse_ascii", issue = "101035")]
348     pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> {
349         Parser::new(b).parse_with(|p| p.read_ipv6_addr(), AddrKind::Ipv6)
350     }
351 }
352
353 #[stable(feature = "rust1", since = "1.0.0")]
354 impl FromStr for Ipv6Addr {
355     type Err = AddrParseError;
356     fn from_str(s: &str) -> Result<Ipv6Addr, AddrParseError> {
357         Self::parse_ascii(s.as_bytes())
358     }
359 }
360
361 impl SocketAddrV4 {
362     /// Parse an IPv4 socket address from a slice of bytes.
363     ///
364     /// ```
365     /// #![feature(addr_parse_ascii)]
366     ///
367     /// use std::net::{Ipv4Addr, SocketAddrV4};
368     ///
369     /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
370     ///
371     /// assert_eq!(SocketAddrV4::parse_ascii(b"127.0.0.1:8080"), Ok(socket));
372     /// ```
373     #[unstable(feature = "addr_parse_ascii", issue = "101035")]
374     pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> {
375         Parser::new(b).parse_with(|p| p.read_socket_addr_v4(), AddrKind::SocketV4)
376     }
377 }
378
379 #[stable(feature = "socket_addr_from_str", since = "1.5.0")]
380 impl FromStr for SocketAddrV4 {
381     type Err = AddrParseError;
382     fn from_str(s: &str) -> Result<SocketAddrV4, AddrParseError> {
383         Self::parse_ascii(s.as_bytes())
384     }
385 }
386
387 impl SocketAddrV6 {
388     /// Parse an IPv6 socket address from a slice of bytes.
389     ///
390     /// ```
391     /// #![feature(addr_parse_ascii)]
392     ///
393     /// use std::net::{Ipv6Addr, SocketAddrV6};
394     ///
395     /// let socket = SocketAddrV6::new(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
396     ///
397     /// assert_eq!(SocketAddrV6::parse_ascii(b"[2001:db8::1]:8080"), Ok(socket));
398     /// ```
399     #[unstable(feature = "addr_parse_ascii", issue = "101035")]
400     pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> {
401         Parser::new(b).parse_with(|p| p.read_socket_addr_v6(), AddrKind::SocketV6)
402     }
403 }
404
405 #[stable(feature = "socket_addr_from_str", since = "1.5.0")]
406 impl FromStr for SocketAddrV6 {
407     type Err = AddrParseError;
408     fn from_str(s: &str) -> Result<SocketAddrV6, AddrParseError> {
409         Self::parse_ascii(s.as_bytes())
410     }
411 }
412
413 impl SocketAddr {
414     /// Parse a socket address from a slice of bytes.
415     ///
416     /// ```
417     /// #![feature(addr_parse_ascii)]
418     ///
419     /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
420     ///
421     /// let socket_v4 = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
422     /// let socket_v6 = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8080);
423     ///
424     /// assert_eq!(SocketAddr::parse_ascii(b"127.0.0.1:8080"), Ok(socket_v4));
425     /// assert_eq!(SocketAddr::parse_ascii(b"[::1]:8080"), Ok(socket_v6));
426     /// ```
427     #[unstable(feature = "addr_parse_ascii", issue = "101035")]
428     pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> {
429         Parser::new(b).parse_with(|p| p.read_socket_addr(), AddrKind::Socket)
430     }
431 }
432
433 #[stable(feature = "rust1", since = "1.0.0")]
434 impl FromStr for SocketAddr {
435     type Err = AddrParseError;
436     fn from_str(s: &str) -> Result<SocketAddr, AddrParseError> {
437         Self::parse_ascii(s.as_bytes())
438     }
439 }
440
441 #[derive(Debug, Clone, PartialEq, Eq)]
442 enum AddrKind {
443     Ip,
444     Ipv4,
445     Ipv6,
446     Socket,
447     SocketV4,
448     SocketV6,
449 }
450
451 /// An error which can be returned when parsing an IP address or a socket address.
452 ///
453 /// This error is used as the error type for the [`FromStr`] implementation for
454 /// [`IpAddr`], [`Ipv4Addr`], [`Ipv6Addr`], [`SocketAddr`], [`SocketAddrV4`], and
455 /// [`SocketAddrV6`].
456 ///
457 /// # Potential causes
458 ///
459 /// `AddrParseError` may be thrown because the provided string does not parse as the given type,
460 /// often because it includes information only handled by a different address type.
461 ///
462 /// ```should_panic
463 /// use std::net::IpAddr;
464 /// let _foo: IpAddr = "127.0.0.1:8080".parse().expect("Cannot handle the socket port");
465 /// ```
466 ///
467 /// [`IpAddr`] doesn't handle the port. Use [`SocketAddr`] instead.
468 ///
469 /// ```
470 /// use std::net::SocketAddr;
471 ///
472 /// // No problem, the `panic!` message has disappeared.
473 /// let _foo: SocketAddr = "127.0.0.1:8080".parse().expect("unreachable panic");
474 /// ```
475 #[stable(feature = "rust1", since = "1.0.0")]
476 #[derive(Debug, Clone, PartialEq, Eq)]
477 pub struct AddrParseError(AddrKind);
478
479 #[stable(feature = "addr_parse_error_error", since = "1.4.0")]
480 impl fmt::Display for AddrParseError {
481     #[allow(deprecated, deprecated_in_future)]
482     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
483         fmt.write_str(self.description())
484     }
485 }
486
487 #[stable(feature = "addr_parse_error_error", since = "1.4.0")]
488 impl Error for AddrParseError {
489     #[allow(deprecated)]
490     fn description(&self) -> &str {
491         match self.0 {
492             AddrKind::Ip => "invalid IP address syntax",
493             AddrKind::Ipv4 => "invalid IPv4 address syntax",
494             AddrKind::Ipv6 => "invalid IPv6 address syntax",
495             AddrKind::Socket => "invalid socket address syntax",
496             AddrKind::SocketV4 => "invalid IPv4 socket address syntax",
497             AddrKind::SocketV6 => "invalid IPv6 socket address syntax",
498         }
499     }
500 }