Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make dname_from_addr public. #289

Merged
merged 5 commits into from
Apr 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 60 additions & 1 deletion src/base/name/absolute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
//! This is a private module. Its public types are re-exported by the parent.

use super::super::cmp::CanonicalOrd;
use super::super::net::IpAddr;
use super::super::scan::{Scanner, Symbol, SymbolCharsError, Symbols};
use super::super::wire::{FormError, ParseError};
use super::builder::{FromStrError, NameBuilder};
use super::builder::{FromStrError, NameBuilder, PushError};
use super::label::{Label, LabelTypeError, SplitLabelError};
use super::relative::{NameIter, RelativeName};
use super::traits::{FlattenInto, ToLabelIter, ToName};
Expand Down Expand Up @@ -181,6 +182,42 @@ impl<Octs> Name<Octs> {
{
unsafe { Self::from_octets_unchecked(b"\0".as_ref().into()) }
}

/// Creates a domain name for reverse IP address lookup.
///
/// The returned name will use the standard suffixes of `in-addr.arpa.`
/// for IPv4 addresses and `ip6.arpa.` for IPv6.
pub fn reverse_from_addr(addr: IpAddr) -> Result<Self, PushError>
where
Octs: FromBuilder,
<Octs as FromBuilder>::Builder: EmptyBuilder
+ FreezeBuilder<Octets = Octs>
+ AsRef<[u8]>
+ AsMut<[u8]>,
{
let mut builder =
NameBuilder::<<Octs as FromBuilder>::Builder>::new();
match addr {
IpAddr::V4(addr) => {
let [a, b, c, d] = addr.octets();
builder.append_dec_u8_label(d)?;
builder.append_dec_u8_label(c)?;
builder.append_dec_u8_label(b)?;
builder.append_dec_u8_label(a)?;
builder.append_label(b"in-addr")?;
builder.append_label(b"arpa")?;
}
IpAddr::V6(addr) => {
for &item in addr.octets().iter().rev() {
builder.append_hex_digit_label(item)?;
builder.append_hex_digit_label(item >> 4)?;
}
builder.append_label(b"ip6")?;
builder.append_label(b"arpa")?;
}
}
builder.into_name()
}
}

impl Name<[u8]> {
Expand Down Expand Up @@ -1324,6 +1361,28 @@ pub(crate) mod test {
);
}

#[test]
fn test_dname_from_addr() {
type TestName = Name<octseq::array::Array<128>>;

assert_eq!(
TestName::reverse_from_addr([192, 0, 2, 12].into()).unwrap(),
TestName::from_str("12.2.0.192.in-addr.arpa").unwrap()
);
assert_eq!(
TestName::reverse_from_addr(
[0x2001, 0xdb8, 0x1234, 0x0, 0x5678, 0x1, 0x9abc, 0xdef]
.into()
)
.unwrap(),
TestName::from_str(
"f.e.d.0.c.b.a.9.1.0.0.0.8.7.6.5.\
0.0.0.0.4.3.2.1.8.b.d.0.1.0.0.2.\
ip6.arpa"
)
.unwrap()
);
}
// `Name::from_chars` is covered in the `FromStr` test.
//
// No tests for the simple conversion methods because, well, simple.
Expand Down
64 changes: 64 additions & 0 deletions src/base/name/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,70 @@ where
Ok(())
}

/// Appends a label with the decimal representation of `u8`.
ximon18 marked this conversation as resolved.
Show resolved Hide resolved
///
/// If there currently is a label under construction, it will be ended
/// before appending `label`.
///
/// Returns an error if appending would result in a name longer than 254
/// bytes.
pub fn append_dec_u8_label(
&mut self,
value: u8,
) -> Result<(), PushError> {
self.end_label();
let hecto = value / 100;
if hecto > 0 {
self.push(hecto + b'0')?;
}
let deka = (value / 10) % 10;
if hecto > 0 || deka > 0 {
self.push(deka + b'0')?;
}
self.push(value % 10 + b'0')?;
self.end_label();
Ok(())
}

/// Appends a label with the hex digit.
///
/// If there currently is a label under construction, it will be ended
/// before appending `label`.
///
/// Returns an error if appending would result in a name longer than 254
/// bytes.
pub fn append_hex_digit_label(
&mut self,
nibble: u8,
) -> Result<(), PushError> {
fn hex_digit(nibble: u8) -> u8 {
match nibble & 0x0F {
0 => b'0',
1 => b'1',
2 => b'2',
3 => b'3',
4 => b'4',
5 => b'5',
6 => b'6',
7 => b'7',
8 => b'8',
9 => b'9',
10 => b'A',
11 => b'B',
12 => b'C',
13 => b'D',
14 => b'E',
15 => b'F',
_ => unreachable!(),
}
}

self.end_label();
self.push(hex_digit(nibble))?;
self.end_label();
Ok(())
}

/// Appends a relative domain name.
///
/// If there currently is a label under construction, it will be ended
Expand Down
6 changes: 6 additions & 0 deletions src/base/net/nostd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,12 @@ impl From<[u8; 16]> for IpAddr {
}
}

impl From<[u16; 8]> for IpAddr {
fn from(src: [u16; 8]) -> Self {
IpAddr::V6(src.into())
}
}

impl From<Ipv4Addr> for IpAddr {
fn from(addr: Ipv4Addr) -> Self {
IpAddr::V4(addr)
Expand Down
81 changes: 3 additions & 78 deletions src/resolv/lookup/addr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@

use crate::base::iana::Rtype;
use crate::base::message::RecordIter;
use crate::base::name::{Name, NameBuilder, ParsedName};
use crate::base::name::{Name, ParsedName};
use crate::rdata::Ptr;
use crate::resolv::resolver::Resolver;
use octseq::octets::Octets;
use std::io;
use std::net::IpAddr;
use std::str::FromStr;

//------------ Octets128 -----------------------------------------------------

Expand All @@ -28,7 +27,8 @@ pub async fn lookup_addr<R: Resolver>(
resolv: &R,
addr: IpAddr,
) -> Result<FoundAddrs<R>, io::Error> {
let name = name_from_addr(addr);
let name = Name::<Octets128>::reverse_from_addr(addr)
.expect("address domain name too long");
resolv.query((name, Rtype::PTR)).await.map(FoundAddrs)
}

Expand Down Expand Up @@ -94,78 +94,3 @@ impl<'a, Octs: Octets> Iterator for FoundAddrsIter<'a, Octs> {
None
}
}

//------------ Helper Functions ---------------------------------------------

/// Translates an IP address into a domain name.
fn name_from_addr(addr: IpAddr) -> Name<Octets128> {
match addr {
IpAddr::V4(addr) => {
let octets = addr.octets();
Name::from_str(&format!(
"{}.{}.{}.{}.in-addr.arpa.",
octets[3], octets[2], octets[1], octets[0]
))
.unwrap()
}
IpAddr::V6(addr) => {
let mut res = NameBuilder::<Octets128>::new();
for &item in addr.octets().iter().rev() {
res.append_label(&[hexdigit(item)]).unwrap();
res.append_label(&[hexdigit(item >> 4)]).unwrap();
}
res.append_label(b"ip6").unwrap();
res.append_label(b"arpa").unwrap();
res.into_name().unwrap()
}
}
}

fn hexdigit(nibble: u8) -> u8 {
match nibble & 0x0F {
0 => b'0',
1 => b'1',
2 => b'2',
3 => b'3',
4 => b'4',
5 => b'5',
6 => b'6',
7 => b'7',
8 => b'8',
9 => b'9',
10 => b'A',
11 => b'B',
12 => b'C',
13 => b'D',
14 => b'E',
15 => b'F',
_ => unreachable!(),
}
}

//============ Tests =========================================================

#[cfg(test)]
mod test {
use super::*;

#[test]
fn test_name_from_addr() {
assert_eq!(
name_from_addr([192, 0, 2, 12].into()),
Name::<Octets128>::from_str("12.2.0.192.in-addr.arpa").unwrap()
);
assert_eq!(
name_from_addr(
[0x2001, 0xdb8, 0x1234, 0x0, 0x5678, 0x1, 0x9abc, 0xdef]
.into()
),
Name::<Octets128>::from_str(
"f.e.d.0.c.b.a.9.1.0.0.0.8.7.6.5.\
0.0.0.0.4.3.2.1.8.b.d.0.1.0.0.2.\
ip6.arpa"
)
.unwrap()
);
}
}
Loading