1 //! A private parser implementation of IPv4, IPv6, and socket addresses.
3 //! This module is "publicly exported" through the `FromStr` implementations
9 use crate::convert::TryInto as _;
10 use crate::error::Error;
12 use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
13 use crate::str::FromStr;
15 trait ReadNumberHelper: crate::marker::Sized {
17 fn checked_mul(&self, other: u32) -> Option<Self>;
18 fn checked_add(&self, other: u32) -> Option<Self>;
21 macro_rules! impl_helper {
22 ($($t:ty)*) => ($(impl ReadNumberHelper for $t {
25 fn checked_mul(&self, other: u32) -> Option<Self> {
26 Self::checked_mul(*self, other.try_into().ok()?)
29 fn checked_add(&self, other: u32) -> Option<Self> {
30 Self::checked_add(*self, other.try_into().ok()?)
35 impl_helper! { u8 u16 u32 }
38 // Parsing as ASCII, so can use byte array.
43 fn new(input: &'a str) -> Parser<'a> {
44 Parser { state: input.as_bytes() }
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>
50 F: FnOnce(&mut Parser<'_>) -> Option<T>,
52 let state = self.state;
53 let result = inner(self);
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, kind: AddrKind) -> Result<T, AddrParseError>
64 F: FnOnce(&mut Parser<'_>) -> Option<T>,
66 let result = inner(self);
67 if self.state.is_empty() { result } else { None }.ok_or(AddrParseError(kind))
70 /// Peek the next character from the input
71 fn peek_char(&self) -> Option<char> {
72 self.state.first().map(|&b| char::from(b))
75 /// Read the next character from the input
76 fn read_char(&mut self) -> Option<char> {
77 self.state.split_first().map(|(&b, tail)| {
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 })
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>
97 F: FnOnce(&mut Parser<'_>) -> Option<T>,
99 self.read_atomically(move |p| {
101 p.read_given_char(sep)?;
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>(
113 max_digits: Option<usize>,
114 allow_zero_prefix: bool,
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');
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)?;
125 if let Some(max_digits) = max_digits {
126 if digit_count > max_digits {
132 if digit_count == 0 {
134 } else if !allow_zero_prefix && has_leading_zero && digit_count > 1 {
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];
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)
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();
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.
173 let ipv4 = p.read_separator(':', i, |p| p.read_ipv4_addr());
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);
183 let group = p.read_separator(':', i, |p| p.read_number(16, Some(4), true));
186 Some(g) => *slot = g,
187 None => return (i, false),
190 (groups.len(), false)
193 self.read_atomically(|p| {
194 // Read the front part of the address; either the whole thing, or up
196 let mut head = [0; 8];
197 let (head_size, head_ipv4) = read_groups(p, &mut head);
200 return Some(head.into());
203 // IPv4 part is not allowed before `::`
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(':')?;
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]);
219 // Concat the head and tail of the IP address
220 head[(8 - tail_size)..8].copy_from_slice(&tail[..tail_size]);
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))
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)
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)
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))
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(']')?;
264 let port = p.read_port()?;
265 Some(SocketAddrV6::new(ip, port, 0, scope_id))
269 /// Read an IP address with a port
270 fn read_socket_addr(&mut self) -> Option<SocketAddr> {
271 self.read_socket_addr_v4()
273 .or_else(|| self.read_socket_addr_v6().map(SocketAddr::V6))
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(), AddrKind::Ip)
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
291 Err(AddrParseError(AddrKind::Ipv4))
293 Parser::new(s).parse_with(|p| p.read_ipv4_addr(), AddrKind::Ipv4)
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(), AddrKind::Ipv6)
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(), AddrKind::SocketV4)
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(), AddrKind::SocketV6)
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(), AddrKind::Socket)
330 #[derive(Debug, Clone, PartialEq, Eq)]
340 /// An error which can be returned when parsing an IP address or a socket address.
342 /// This error is used as the error type for the [`FromStr`] implementation for
343 /// [`IpAddr`], [`Ipv4Addr`], [`Ipv6Addr`], [`SocketAddr`], [`SocketAddrV4`], and
344 /// [`SocketAddrV6`].
346 /// # Potential causes
348 /// `AddrParseError` may be thrown because the provided string does not parse as the given type,
349 /// often because it includes information only handled by a different address type.
352 /// use std::net::IpAddr;
353 /// let _foo: IpAddr = "127.0.0.1:8080".parse().expect("Cannot handle the socket port");
356 /// [`IpAddr`] doesn't handle the port. Use [`SocketAddr`] instead.
359 /// use std::net::SocketAddr;
361 /// // No problem, the `panic!` message has disappeared.
362 /// let _foo: SocketAddr = "127.0.0.1:8080".parse().expect("unreachable panic");
364 #[stable(feature = "rust1", since = "1.0.0")]
365 #[derive(Debug, Clone, PartialEq, Eq)]
366 pub struct AddrParseError(AddrKind);
368 #[stable(feature = "addr_parse_error_error", since = "1.4.0")]
369 impl fmt::Display for AddrParseError {
370 #[allow(deprecated, deprecated_in_future)]
371 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
372 fmt.write_str(self.description())
376 #[stable(feature = "addr_parse_error_error", since = "1.4.0")]
377 impl Error for AddrParseError {
379 fn description(&self) -> &str {
381 AddrKind::Ip => "invalid IP address syntax",
382 AddrKind::Ipv4 => "invalid IPv4 address syntax",
383 AddrKind::Ipv6 => "invalid IPv6 address syntax",
384 AddrKind::Socket => "invalid socket address syntax",
385 AddrKind::SocketV4 => "invalid IPv4 socket address syntax",
386 AddrKind::SocketV6 => "invalid IPv6 socket address syntax",