1 //! A private parser implementation of IPv4, IPv6, and socket addresses.
3 //! This module is "publicly exported" through the `FromStr` implementations
9 use crate::error::Error;
11 use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
12 use crate::str::FromStr;
14 trait ReadNumberHelper: crate::marker::Sized {
16 fn checked_mul(&self, other: u32) -> Option<Self>;
17 fn checked_add(&self, other: u32) -> Option<Self>;
20 macro_rules! impl_helper {
21 ($($t:ty)*) => ($(impl ReadNumberHelper for $t {
24 fn checked_mul(&self, other: u32) -> Option<Self> {
25 Self::checked_mul(*self, other.try_into().ok()?)
28 fn checked_add(&self, other: u32) -> Option<Self> {
29 Self::checked_add(*self, other.try_into().ok()?)
34 impl_helper! { u8 u16 u32 }
37 // Parsing as ASCII, so can use byte array.
42 fn new(input: &'a [u8]) -> Parser<'a> {
43 Parser { state: input }
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>
49 F: FnOnce(&mut Parser<'_>) -> Option<T>,
51 let state = self.state;
52 let result = inner(self);
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>
63 F: FnOnce(&mut Parser<'_>) -> Option<T>,
65 let result = inner(self);
66 if self.state.is_empty() { result } else { None }.ok_or(AddrParseError(kind))
69 /// Peek the next character from the input
70 fn peek_char(&self) -> Option<char> {
71 self.state.first().map(|&b| char::from(b))
74 /// Read the next character from the input
75 fn read_char(&mut self) -> Option<char> {
76 self.state.split_first().map(|(&b, tail)| {
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 })
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>
96 F: FnOnce(&mut Parser<'_>) -> Option<T>,
98 self.read_atomically(move |p| {
100 p.read_given_char(sep)?;
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>(
112 max_digits: Option<usize>,
113 allow_zero_prefix: bool,
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');
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)?;
124 if let Some(max_digits) = max_digits {
125 if digit_count > max_digits {
131 if digit_count == 0 {
133 } else if !allow_zero_prefix && has_leading_zero && digit_count > 1 {
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];
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)
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();
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.
172 let ipv4 = p.read_separator(':', i, |p| p.read_ipv4_addr());
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);
182 let group = p.read_separator(':', i, |p| p.read_number(16, Some(4), true));
185 Some(g) => *slot = g,
186 None => return (i, false),
189 (groups.len(), false)
192 self.read_atomically(|p| {
193 // Read the front part of the address; either the whole thing, or up
195 let mut head = [0; 8];
196 let (head_size, head_ipv4) = read_groups(p, &mut head);
199 return Some(head.into());
202 // IPv4 part is not allowed before `::`
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(':')?;
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]);
218 // Concat the head and tail of the IP address
219 head[(8 - tail_size)..8].copy_from_slice(&tail[..tail_size]);
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))
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)
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)
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))
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(']')?;
263 let port = p.read_port()?;
264 Some(SocketAddrV6::new(ip, port, 0, scope_id))
268 /// Read an IP address with a port
269 fn read_socket_addr(&mut self) -> Option<SocketAddr> {
270 self.read_socket_addr_v4()
272 .or_else(|| self.read_socket_addr_v6().map(SocketAddr::V6))
277 /// Parse an IP address from a slice of bytes.
280 /// #![feature(addr_parse_ascii)]
282 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
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));
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));
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)
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())
305 /// Parse an IPv4 address from a slice of bytes.
308 /// #![feature(addr_parse_ascii)]
310 /// use std::net::Ipv4Addr;
312 /// let localhost = Ipv4Addr::new(127, 0, 0, 1);
314 /// assert_eq!(Ipv4Addr::parse_ascii(b"127.0.0.1"), Ok(localhost));
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
320 Err(AddrParseError(AddrKind::Ipv4))
322 Parser::new(b).parse_with(|p| p.read_ipv4_addr(), AddrKind::Ipv4)
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())
336 /// Parse an IPv6 address from a slice of bytes.
339 /// #![feature(addr_parse_ascii)]
341 /// use std::net::Ipv6Addr;
343 /// let localhost = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
345 /// assert_eq!(Ipv6Addr::parse_ascii(b"::1"), Ok(localhost));
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)
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())
362 /// Parse an IPv4 socket address from a slice of bytes.
365 /// #![feature(addr_parse_ascii)]
367 /// use std::net::{Ipv4Addr, SocketAddrV4};
369 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
371 /// assert_eq!(SocketAddrV4::parse_ascii(b"127.0.0.1:8080"), Ok(socket));
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)
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())
388 /// Parse an IPv6 socket address from a slice of bytes.
391 /// #![feature(addr_parse_ascii)]
393 /// use std::net::{Ipv6Addr, SocketAddrV6};
395 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
397 /// assert_eq!(SocketAddrV6::parse_ascii(b"[2001:db8::1]:8080"), Ok(socket));
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)
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())
414 /// Parse a socket address from a slice of bytes.
417 /// #![feature(addr_parse_ascii)]
419 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
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);
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));
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)
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())
441 #[derive(Debug, Clone, PartialEq, Eq)]
451 /// An error which can be returned when parsing an IP address or a socket address.
453 /// This error is used as the error type for the [`FromStr`] implementation for
454 /// [`IpAddr`], [`Ipv4Addr`], [`Ipv6Addr`], [`SocketAddr`], [`SocketAddrV4`], and
455 /// [`SocketAddrV6`].
457 /// # Potential causes
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.
463 /// use std::net::IpAddr;
464 /// let _foo: IpAddr = "127.0.0.1:8080".parse().expect("Cannot handle the socket port");
467 /// [`IpAddr`] doesn't handle the port. Use [`SocketAddr`] instead.
470 /// use std::net::SocketAddr;
472 /// // No problem, the `panic!` message has disappeared.
473 /// let _foo: SocketAddr = "127.0.0.1:8080".parse().expect("unreachable panic");
475 #[stable(feature = "rust1", since = "1.0.0")]
476 #[derive(Debug, Clone, PartialEq, Eq)]
477 pub struct AddrParseError(AddrKind);
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())
487 #[stable(feature = "addr_parse_error_error", since = "1.4.0")]
488 impl Error for AddrParseError {
490 fn description(&self) -> &str {
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",