mz_ore/netio/
dns.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License in the LICENSE file at the
6// root of this repository, or online at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use std::collections::BTreeSet;
17use std::io;
18use std::net::IpAddr;
19
20use tokio::net::lookup_host;
21
22/// We must provide a port for dns resolution but
23/// dns resolution ignores the port so we use a port
24/// that is easy to spot in logs.
25pub const DUMMY_DNS_PORT: u16 = 11111;
26
27/// An error returned by `resolve_address`.
28#[derive(thiserror::Error, Debug)]
29pub enum DnsResolutionError {
30    /// private ip
31    #[error(
32        "Address resolved to a private IP. The provided host is not routable on the public internet"
33    )]
34    PrivateAddress,
35    /// no addresses
36    #[error("Address did not resolve to any IPs")]
37    NoAddressesFound,
38    /// io error
39    #[error(transparent)]
40    Io(#[from] io::Error),
41}
42
43/// Resolves a host address and ensures it is a global address when `enforce_global` is set.
44/// This parameter is useful when connecting to user-defined unverified addresses.
45pub async fn resolve_address(
46    mut host: &str,
47    enforce_global: bool,
48) -> Result<BTreeSet<IpAddr>, DnsResolutionError> {
49    // `net::lookup_host` requires a port to be specified, but we don't care about the port.
50    let mut port = DUMMY_DNS_PORT;
51    // If a port is already specified, use it and remove it from the host.
52    if let Some(idx) = host.find(':') {
53        if let Ok(p) = host[idx + 1..].parse() {
54            port = p;
55            host = &host[..idx];
56        }
57    }
58
59    let mut addrs = lookup_host((host, port)).await?;
60    let mut ips = BTreeSet::new();
61    while let Some(addr) = addrs.next() {
62        let ip = addr.ip();
63        if enforce_global && !is_global(ip) {
64            Err(DnsResolutionError::PrivateAddress)?
65        } else {
66            ips.insert(ip);
67        }
68    }
69
70    if ips.len() == 0 {
71        Err(DnsResolutionError::NoAddressesFound)?
72    }
73    Ok(ips)
74}
75
76fn is_global(addr: IpAddr) -> bool {
77    // TODO: Switch to `addr.is_global()` once stable: https://github.com/rust-lang/rust/issues/27709
78    match addr {
79        IpAddr::V4(ip) => {
80            !(ip.is_unspecified() || ip.is_private() || ip.is_loopback() || ip.is_link_local())
81        }
82        IpAddr::V6(ip) => !(ip.is_loopback() || ip.is_unspecified()),
83    }
84}