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
22const DUMMY_PORT: u16 = 11111;
23
24/// An error returned by `resolve_address`.
25#[derive(thiserror::Error, Debug)]
26pub enum DnsResolutionError {
27 /// private ip
28 #[error(
29 "Address resolved to a private IP. The provided host is not routable on the public internet"
30 )]
31 PrivateAddress,
32 /// no addresses
33 #[error("Address did not resolve to any IPs")]
34 NoAddressesFound,
35 /// io error
36 #[error(transparent)]
37 Io(#[from] io::Error),
38}
39
40/// Resolves a host address and ensures it is a global address when `enforce_global` is set.
41/// This parameter is useful when connecting to user-defined unverified addresses.
42pub async fn resolve_address(
43 mut host: &str,
44 enforce_global: bool,
45) -> Result<BTreeSet<IpAddr>, DnsResolutionError> {
46 // `net::lookup_host` requires a port to be specified, but we don't care about the port.
47 let mut port = DUMMY_PORT;
48 // If a port is already specified, use it and remove it from the host.
49 if let Some(idx) = host.find(':') {
50 if let Ok(p) = host[idx + 1..].parse() {
51 port = p;
52 host = &host[..idx];
53 }
54 }
55
56 let mut addrs = lookup_host((host, port)).await?;
57 let mut ips = BTreeSet::new();
58 while let Some(addr) = addrs.next() {
59 let ip = addr.ip();
60 if enforce_global && !is_global(ip) {
61 Err(DnsResolutionError::PrivateAddress)?
62 } else {
63 ips.insert(ip);
64 }
65 }
66
67 if ips.len() == 0 {
68 Err(DnsResolutionError::NoAddressesFound)?
69 }
70 Ok(ips)
71}
72
73fn is_global(addr: IpAddr) -> bool {
74 // TODO: Switch to `addr.is_global()` once stable: https://github.com/rust-lang/rust/issues/27709
75 match addr {
76 IpAddr::V4(ip) => {
77 !(ip.is_unspecified() || ip.is_private() || ip.is_loopback() || ip.is_link_local())
78 }
79 IpAddr::V6(ip) => !(ip.is_loopback() || ip.is_unspecified()),
80 }
81}