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) -> 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(()))
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>,
115 self.read_atomically(move |p| {
116 let mut result = T::ZERO;
117 let mut digit_count = 0;
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)?;
123 if let Some(max_digits) = max_digits {
124 if digit_count > max_digits {
130 if digit_count == 0 { None } else { Some(result) }
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];
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,
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();
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.
168 let ipv4 = p.read_separator(':', i, |p| p.read_ipv4_addr());
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);
178 let group = p.read_separator(':', i, |p| p.read_number(16, Some(4)));
181 Some(g) => *slot = g,
182 None => return (i, false),
185 (groups.len(), false)
188 self.read_atomically(|p| {
189 // Read the front part of the address; either the whole thing, or up
191 let mut head = [0; 8];
192 let (head_size, head_ipv4) = read_groups(p, &mut head);
195 return Some(head.into());
198 // IPv4 part is not allowed before `::`
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(':')?;
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]);
214 // Concat the head and tail of the IP address
215 head[(8 - tail_size)..8].copy_from_slice(&tail[..tail_size]);
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))
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)
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)
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))
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(']')?;
259 let port = p.read_port()?;
260 Some(SocketAddrV6::new(ip, port, 0, scope_id))
264 /// Read an IP address with a port
265 fn read_socket_addr(&mut self) -> Option<SocketAddr> {
266 self.read_socket_addr_v4()
268 .or_else(|| self.read_socket_addr_v6().map(SocketAddr::V6))
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())
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())
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())
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())
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())
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())
320 /// An error which can be returned when parsing an IP address or a socket address.
322 /// This error is used as the error type for the [`FromStr`] implementation for
323 /// [`IpAddr`], [`Ipv4Addr`], [`Ipv6Addr`], [`SocketAddr`], [`SocketAddrV4`], and
324 /// [`SocketAddrV6`].
326 /// # Potential causes
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.
332 /// use std::net::IpAddr;
333 /// let _foo: IpAddr = "127.0.0.1:8080".parse().expect("Cannot handle the socket port");
336 /// [`IpAddr`] doesn't handle the port. Use [`SocketAddr`] instead.
339 /// use std::net::SocketAddr;
341 /// // No problem, the `panic!` message has disappeared.
342 /// let _foo: SocketAddr = "127.0.0.1:8080".parse().expect("unreachable panic");
344 #[stable(feature = "rust1", since = "1.0.0")]
345 #[derive(Debug, Clone, PartialEq, Eq)]
346 pub struct AddrParseError(());
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())
356 #[stable(feature = "addr_parse_error_error", since = "1.4.0")]
357 impl Error for AddrParseError {
359 fn description(&self) -> &str {
360 "invalid IP address syntax"