Skip to content

Commit

Permalink
Merge pull request #8 from sticnarf/totargetaddr
Browse files Browse the repository at this point in the history
Implement ToTargetAddr for more
  • Loading branch information
sticnarf authored Sep 5, 2019
2 parents c7fb571 + e435b5e commit 6911baa
Showing 1 changed file with 41 additions and 3 deletions.
44 changes: 41 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,12 @@ trivial_impl_into_target_addr!((Ipv6Addr, u16));
trivial_impl_into_target_addr!(SocketAddrV4);
trivial_impl_into_target_addr!(SocketAddrV6);

impl<'a> IntoTargetAddr<'a> for TargetAddr<'a> {
fn into_target_addr(self) -> Result<TargetAddr<'a>> {
Ok(self)
}
}

impl<'a> IntoTargetAddr<'a> for (&'a str, u16) {
fn into_target_addr(self) -> Result<TargetAddr<'a>> {
// Try IP address first
Expand All @@ -162,8 +168,7 @@ impl<'a> IntoTargetAddr<'a> for (&'a str, u16) {
}

// Treat as domain name
let len = self.0.as_bytes().len();
if len > 255 {
if self.0.len() > 255 {
return Err(Error::InvalidTargetAddress("overlong domain"));
}
// TODO: Should we validate the domain format here?
Expand All @@ -187,7 +192,34 @@ impl<'a> IntoTargetAddr<'a> for &'a str {
let domain = parts_iter
.next()
.ok_or(Error::InvalidTargetAddress("invalid address format"))?;
(domain, port).into_target_addr()
if domain.len() > 255 {
return Err(Error::InvalidTargetAddress("overlong domain"));
}
Ok(TargetAddr::Domain(domain.into(), port))
}
}

impl IntoTargetAddr<'static> for String {
fn into_target_addr(mut self) -> Result<TargetAddr<'static>> {
// Try IP address first
if let Ok(addr) = self.parse::<SocketAddr>() {
return addr.into_target_addr();
}

let mut parts_iter = self.rsplitn(2, ':');
let port: u16 = parts_iter
.next()
.and_then(|port_str| port_str.parse().ok())
.ok_or(Error::InvalidTargetAddress("invalid address format"))?;
let domain_len = parts_iter
.next()
.ok_or(Error::InvalidTargetAddress("invalid address format"))?
.len();
if domain_len > 255 {
return Err(Error::InvalidTargetAddress("overlong domain"));
}
self.truncate(domain_len);
Ok(TargetAddr::Domain(self.into(), port))
}
}

Expand Down Expand Up @@ -317,6 +349,12 @@ mod tests {
TargetAddr::Domain(Cow::Borrowed("www.example.com"), 80),
res
);

let res = into_target_addr(domain.to_owned())?;
assert_eq!(
TargetAddr::Domain(Cow::Owned("www.example.com".to_owned()), 80),
res
);
Ok(())
}

Expand Down

0 comments on commit 6911baa

Please sign in to comment.