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