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

strings are strings after all #104

Merged
merged 7 commits into from
Jun 7, 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
19 changes: 17 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,23 @@
# Changelog

## Unreleased

## 10.0.0 (7 June 2024)

- string values are `&str`, not `CStr`
- returning `CStr` was ugly but necessary while c-ares made no promises about
the values that it returned
- from its release 1.17.2 c-ares verifies that hostnames are strings, and from
its 1.30.0 it makes the same check for other DNS strings
- therefore this wrapper now prefers to return native rust `&str`
- when using a new enough version of c-ares we trust the c-ares validation,
and make unchecked conversions from C strings to `&str`
- when using older c-ares we make a fallible conversion, and `unwrap()` the
result
- therefore if you are using old c-ares and new rust-c-ares and you are
talking to a server that returns invalid DNS strings: you may see panics
- solve this by using a newer c-ares, or an older rust-c-ares, or by fixing
your DNS server
- CAA record value is bytes, not a string
- c-ares 1.30.0

## 9.2.1 (26 May 2024)

Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "c-ares"
license = "MIT"
version = "9.2.1"
version = "10.0.0"
authors = ["David Hotham"]
description = """
A Rust wrapper for the c-ares library, for asynchronous DNS requests.
Expand Down
10 changes: 10 additions & 0 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ fn main() {
println!("cargo:rustc-cfg=cares1_17");
}

println!("cargo::rustc-check-cfg=cfg(cares1_17_2)");
if version >= 0x1_11_02 {
println!("cargo:rustc-cfg=cares1_17_2");
}

println!("cargo::rustc-check-cfg=cfg(cares1_19)");
if version >= 0x1_13_00 {
println!("cargo:rustc-cfg=cares1_19");
Expand Down Expand Up @@ -43,5 +48,10 @@ fn main() {
if version >= 0x1_1d_00 {
println!("cargo:rustc-cfg=cares1_29");
}

println!("cargo::rustc-check-cfg=cfg(cares1_30)");
if version >= 0x1_1e_00 {
println!("cargo:rustc-cfg=cares1_30");
}
}
}
4 changes: 4 additions & 0 deletions c-ares-sys/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## 9.3.0 (07 June 2024)

- c-ares 1.30.0

## 9.2.1 (26 May 2024)

- Include the whole API in docs
Expand Down
2 changes: 1 addition & 1 deletion c-ares-sys/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "c-ares-sys"
license = "MIT"
version = "9.2.1"
version = "9.3.0"
authors = ["David Hotham"]
build = "build/main.rs"
links = "cares"
Expand Down
2 changes: 1 addition & 1 deletion c-ares-sys/c-ares
8 changes: 4 additions & 4 deletions c-ares-sys/ffi.patch
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
--- src/ffi.rs.orig 2024-05-22 18:19:48.078618559 +0100
+++ src/ffi.rs 2024-05-22 18:22:28.529371085 +0100
--- src/ffi.rs.orig 2024-06-07 18:30:42.815463862 +0100
+++ src/ffi.rs 2024-06-07 18:30:42.835463835 +0100
@@ -1,13 +1,24 @@
/* automatically generated by rust-bindgen 0.69.4 */
+#![allow(non_camel_case_types, non_snake_case)]
Expand Down Expand Up @@ -51,15 +51,15 @@
pub server_failover_opts: ares_server_failover_options,
}
#[repr(C)]
@@ -1451,6 +1469,7 @@
@@ -1471,6 +1489,7 @@
pub struct ares_addrinfo {
pub cnames: *mut ares_addrinfo_cname,
pub nodes: *mut ares_addrinfo_node,
+ #[cfg(cares1_18)]
pub name: *mut ::std::os::raw::c_char,
}
#[repr(C)]
@@ -1661,3 +1680,17 @@
@@ -1681,3 +1700,17 @@
#[doc = " Retrieve the total number of active queries pending answers from servers.\n Some c-ares requests may spawn multiple queries, such as ares_getaddrinfo()\n when using AF_UNSPEC, which will be reflected in this number.\n\n \\param[in] channel Initialized ares channel\n \\return Number of active queries to servers"]
pub fn ares_queue_active_queries(channel: *const ares_channel_t) -> usize;
}
Expand Down
20 changes: 20 additions & 0 deletions c-ares-sys/src/ffi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,8 @@ pub enum ares_dns_rec_type_t {
ARES_REC_TYPE_MX = 15,
#[doc = "< Text strings."]
ARES_REC_TYPE_TXT = 16,
#[doc = "< RFC 2535 / RFC 2931. SIG Record"]
ARES_REC_TYPE_SIG = 24,
#[doc = "< RFC 3596. Ip6 Address."]
ARES_REC_TYPE_AAAA = 28,
#[doc = "< RFC 2782. Server Selection."]
Expand Down Expand Up @@ -366,6 +368,24 @@ pub enum ares_dns_rr_key_t {
ARES_RR_MX_EXCHANGE = 1502,
#[doc = " TXT Record. Data. Datatype: BINP"]
ARES_RR_TXT_DATA = 1601,
#[doc = " SIG Record. Type Covered. Datatype: U16"]
ARES_RR_SIG_TYPE_COVERED = 2401,
#[doc = " SIG Record. Algorithm. Datatype: U8"]
ARES_RR_SIG_ALGORITHM = 2402,
#[doc = " SIG Record. Labels. Datatype: U8"]
ARES_RR_SIG_LABELS = 2403,
#[doc = " SIG Record. Original TTL. Datatype: U32"]
ARES_RR_SIG_ORIGINAL_TTL = 2404,
#[doc = " SIG Record. Signature Expiration. Datatype: U32"]
ARES_RR_SIG_EXPIRATION = 2405,
#[doc = " SIG Record. Signature Inception. Datatype: U32"]
ARES_RR_SIG_INCEPTION = 2406,
#[doc = " SIG Record. Key Tag. Datatype: U16"]
ARES_RR_SIG_KEY_TAG = 2407,
#[doc = " SIG Record. Signers Name. Datatype: NAME"]
ARES_RR_SIG_SIGNERS_NAME = 2408,
#[doc = " SIG Record. Signature. Datatype: BIN"]
ARES_RR_SIG_SIGNATURE = 2409,
#[doc = " AAAA Record. Address. Datatype: INADDR6"]
ARES_RR_AAAA_ADDR = 2801,
#[doc = " SRV Record. Priority. Datatype: U16"]
Expand Down
2 changes: 1 addition & 1 deletion examples/epoll.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ mod example {
for srv_result in srv_results {
println!(
"host: {} (port: {}), priority: {}, weight: {}",
srv_result.host().to_string_lossy(),
srv_result.host(),
srv_result.port(),
srv_result.priority(),
srv_result.weight()
Expand Down
11 changes: 4 additions & 7 deletions examples/select.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,8 @@ mod example {
}
Ok(ref soa_result) => {
println!("Successful SOA lookup...");
println!(
"Name server: {}",
soa_result.name_server().to_string_lossy()
);
println!("Hostmaster: {}", soa_result.hostmaster().to_string_lossy());
println!("Name server: {}", soa_result.name_server());
println!("Hostmaster: {}", soa_result.hostmaster());
println!("Serial: {}", soa_result.serial());
println!("Retry: {}", soa_result.retry());
println!("Expire: {}", soa_result.expire());
Expand All @@ -42,10 +39,10 @@ mod example {
Ok(ref name_info_result) => {
println!("Successful name info lookup...");
if let Some(node) = name_info_result.node() {
println!("Node: {}", node.to_string_lossy());
println!("Node: {}", node);
}
if let Some(service) = name_info_result.service() {
println!("Service: {}", service.to_string_lossy());
println!("Service: {}", service);
}
}
}
Expand Down
16 changes: 4 additions & 12 deletions src/caa.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use std::ffi::CStr;
use std::marker::PhantomData;
use std::os::raw::{c_int, c_uchar, c_void};
use std::{fmt, ptr, slice, str};
Expand All @@ -7,6 +6,7 @@ use itertools::Itertools;

use crate::error::{Error, Result};
use crate::panic;
use crate::utils::dns_string_as_str;

/// The result of a successful CAA lookup.
#[derive(Debug)]
Expand Down Expand Up @@ -103,12 +103,8 @@ impl<'a> CAAResult<'a> {
}

/// The property represented by this `CAAResult`.
///
/// In practice this is very likely to be a valid UTF-8 string, but the underlying `c-ares`
/// library does not guarantee this - so we leave it to users to decide whether they prefer a
/// fallible conversion, a lossy conversion, or something else altogether.
pub fn property(self) -> &'a CStr {
unsafe { CStr::from_ptr(self.caa_reply.property.cast()) }
pub fn property(self) -> &'a str {
unsafe { dns_string_as_str(self.caa_reply.property.cast()) }
}

/// The value represented by this `CAAResult`.
Expand All @@ -120,11 +116,7 @@ impl<'a> CAAResult<'a> {
impl<'a> fmt::Display for CAAResult<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Critical: {}, ", self.critical())?;
write!(
fmt,
"Property: {}, ",
self.property().to_str().unwrap_or("<not utf8>")
)?;
write!(fmt, "Property: {}, ", self.property())?;
let value = str::from_utf8(self.value()).unwrap_or("<binary>");
write!(fmt, "Value: {}", value)
}
Expand Down
10 changes: 5 additions & 5 deletions src/channel.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#[allow(unused_imports)]
use std::ffi::{CStr, CString};
use std::ffi::CString;
use std::marker::PhantomData;
use std::mem;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
Expand Down Expand Up @@ -30,8 +29,10 @@ use crate::string::AresString;
use crate::txt::{query_txt_callback, TXTResults};
use crate::types::{AddressFamily, DnsClass, QueryType, Socket};
use crate::uri::{query_uri_callback, URIResults};
#[allow(unused_imports)]
use crate::utils::{
ipv4_as_in_addr, ipv6_as_in6_addr, socket_addrv4_as_sockaddr_in, socket_addrv6_as_sockaddr_in6,
c_string_as_str_unchecked, ipv4_as_in_addr, ipv6_as_in6_addr, socket_addrv4_as_sockaddr_in,
socket_addrv6_as_sockaddr_in6,
};
use crate::Flags;
#[cfg(cares1_29)]
Expand Down Expand Up @@ -1160,8 +1161,7 @@ unsafe extern "C" fn server_state_callback<F>(
F: FnMut(&str, bool, ServerStateFlags) + Send + 'static,
{
let handler = data.cast::<F>();
let c_str = CStr::from_ptr(server_string);
let server = c_str.to_str().unwrap();
let server = c_string_as_str_unchecked(server_string);
panic::catch(|| {
(*handler)(
server,
Expand Down
7 changes: 1 addition & 6 deletions src/cname.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use std::ffi::CStr;
use std::fmt;
use std::os::raw::{c_int, c_uchar, c_void};
use std::ptr;
Expand Down Expand Up @@ -42,11 +41,7 @@ impl CNameResults {
}

/// Returns the hostname from this `CNameResults`.
///
/// In practice this is very likely to be a valid UTF-8 string, but the underlying `c-ares`
/// library does not guarantee this - so we leave it to users to decide whether they prefer a
/// fallible conversion, a lossy conversion, or something else altogether.
pub fn hostname(&self) -> &CStr {
pub fn hostname(&self) -> &str {
self.hostent.hostname()
}

Expand Down
7 changes: 3 additions & 4 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use std::error;
use std::ffi::CStr;
use std::fmt;
use std::os::raw::c_int;
use std::result;
use std::str;

use crate::utils::c_string_as_str_unchecked;

/// Error codes that the library might return.
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash, PartialOrd, Ord)]
Expand Down Expand Up @@ -96,8 +96,7 @@ impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
let text = unsafe {
let ptr = c_ares_sys::ares_strerror(*self as c_int);
let buf = CStr::from_ptr(ptr).to_bytes();
str::from_utf8_unchecked(buf)
c_string_as_str_unchecked(ptr)
};
fmt.write_str(text)
}
Expand Down
7 changes: 1 addition & 6 deletions src/host.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use std::ffi::CStr;
use std::fmt;
use std::os::raw::{c_int, c_void};

Expand All @@ -20,11 +19,7 @@ impl<'a> HostResults<'a> {
}

/// Returns the hostname from this `HostResults`.
///
/// In practice this is very likely to be a valid UTF-8 string, but the underlying `c-ares`
/// library does not guarantee this - so we leave it to users to decide whether they prefer a
/// fallible conversion, a lossy conversion, or something else altogether.
pub fn hostname(self) -> &'a CStr {
pub fn hostname(self) -> &'a str {
self.hostent.hostname()
}

Expand Down
35 changes: 11 additions & 24 deletions src/hostent.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use std::ffi::CStr;
use std::marker::PhantomData;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::os::raw::c_char;
Expand All @@ -7,10 +6,10 @@ use std::{fmt, ptr, slice};
use itertools::Itertools;

use crate::types::AddressFamily;
use crate::utils::address_family;
use crate::utils::{address_family, hostname_as_str};

fn hostname(hostent: &c_types::hostent) -> &CStr {
unsafe { CStr::from_ptr(hostent.h_name.cast()) }
fn hostname(hostent: &c_types::hostent) -> &str {
unsafe { hostname_as_str(hostent.h_name.cast()) }
}

fn addresses(hostent: &c_types::hostent) -> HostAddressResultsIter {
Expand All @@ -28,23 +27,17 @@ fn aliases(hostent: &c_types::hostent) -> HostAliasResultsIter {
}

fn display(hostent: &c_types::hostent, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(
fmt,
"Hostname: {}, ",
hostname(hostent).to_str().unwrap_or("<not utf8>")
)?;
write!(fmt, "Hostname: {}, ", hostname(hostent))?;
let addresses = addresses(hostent).format(", ");
write!(fmt, "Addresses: [{addresses}], ")?;
let aliases = aliases(hostent)
.map(|cstr| cstr.to_str().unwrap_or("<not utf8>"))
.format(", ");
let aliases = aliases(hostent).format(", ");
write!(fmt, "Aliases: [{aliases}]")
}

pub trait HasHostent<'a>: Sized {
fn hostent(self) -> &'a c_types::hostent;

fn hostname(self) -> &'a CStr {
fn hostname(self) -> &'a str {
let hostent = self.hostent();
hostname(hostent)
}
Expand Down Expand Up @@ -171,28 +164,22 @@ impl<'a> Iterator for HostAddressResultsIter<'a> {
unsafe impl<'a> Send for HostAddressResultsIter<'a> {}
unsafe impl<'a> Sync for HostAddressResultsIter<'a> {}

/// Iterator of `&'a CStr`s.
///
/// Each item is very likely to be a valid UTF-8 string, but the underlying `c-ares` library does
/// not guarantee this - so we leave it to users to decide whether they prefer a fallible
/// conversion, a lossy conversion, or something else altogether.
/// Iterator of `&'a str`s.
#[derive(Clone, Copy, Debug)]
pub struct HostAliasResultsIter<'a> {
next: &'a *const c_char,
}

impl<'a> Iterator for HostAliasResultsIter<'a> {
type Item = &'a CStr;
type Item = &'a str;
fn next(&mut self) -> Option<Self::Item> {
let h_alias = *self.next;
if h_alias.is_null() {
None
} else {
unsafe {
self.next = &*ptr::from_ref(self.next).offset(1);
let c_str = CStr::from_ptr(h_alias);
Some(c_str)
}
self.next = unsafe { &*ptr::from_ref(self.next).offset(1) };
let string = unsafe { hostname_as_str(h_alias) };
Some(string)
}
}
}
Expand Down
Loading