1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
use crate::error::Error;
use crate::path::IpfsPath;
use std::str::FromStr;
use tracing_futures::Instrument;
pub async fn resolve(domain: &str) -> Result<IpfsPath, Error> {
use std::borrow::Cow;
use trust_dns_resolver::AsyncResolver;
let span = tracing::trace_span!("dnslink", %domain);
async move {
let searched = Some(Cow::Borrowed(domain));
let prefix = "_dnslink.";
let prefixed = if !domain.starts_with(prefix) {
let mut next = String::with_capacity(domain.len() + prefix.len());
next.push_str(prefix);
next.push_str(domain);
Some(Cow::Owned(next))
} else {
None
};
let searched = searched.into_iter().chain(prefixed.into_iter());
let resolver = AsyncResolver::tokio_from_system_conf()?;
for domain in searched {
let res = match resolver.txt_lookup(&*domain).await {
Ok(res) => res,
Err(e) => {
tracing::debug!("resolving dnslink of {:?} failed: {}", domain, e);
continue;
}
};
let mut paths = res
.iter()
.flat_map(|txt| txt.iter())
.filter_map(|txt| {
if txt.starts_with(b"dnslink=") {
Some(&txt[b"dnslink=".len()..])
} else {
None
}
})
.map(|suffix| {
std::str::from_utf8(suffix)
.map_err(Error::from)
.and_then(IpfsPath::from_str)
});
if let Some(Ok(x)) = paths.next() {
tracing::trace!("dnslink found for {:?}", domain);
return Ok(x);
}
tracing::trace!("zero TXT records found for {:?}", domain);
}
Err(anyhow::anyhow!("failed to resolve {:?}", domain))
}
.instrument(span)
.await
}
#[cfg(test)]
mod tests {
use super::resolve;
#[tokio::test]
async fn resolve_ipfs_io() {
tracing_subscriber::fmt::init();
let res = resolve("ipfs.io").await.unwrap().to_string();
assert_eq!(res, "/ipns/website.ipfs.io");
}
#[tokio::test]
async fn resolve_website_ipfs_io() {
let res = resolve("website.ipfs.io").await.unwrap();
assert!(
matches!(res.root(), crate::path::PathRoot::Ipld(_)),
"expected an /ipfs/cid path"
);
}
}