Skip to main content

libnss_host4/
lib.rs

1//! Implementing the trait and macro in this crate will publish a
2//! `gethostbyname4_r` NSS hook in your Rust `cdylib`.
3//!
4//! # Example
5//!
6//! ```
7//! use libnss_host4::{Addr, HostResolver, err::NssErr, impl_gethostbyname4_r};
8//! use std::net::Ipv6Addr;
9//!
10//! /// This resolver maps "localhost" to [::1%0].
11//! struct LocalDns;
12//! impl_gethostbyname4_r!(local, LocalDns);
13//!
14//! impl HostResolver for LocalDns {
15//!     fn resolve_host(hostname: &str) -> Result<impl IntoIterator<Item = Addr>, NssErr> {
16//!         if hostname == "localhost" {
17//!             return Ok([Addr {
18//!                 ip: Ipv6Addr::LOCALHOST.into(),
19//!                 scope_id: 0,
20//!             }]);
21//!         }
22//!         Err(NssErr::NO_RESULT)
23//!     }
24//! }
25//! ```
26//!
27//! # Background
28//!
29//! glibc defines a Name Service Switch interface for querying hostnames.
30//!
31//! <https://sourceware.org/glibc/manual/2.43/html_mono/libc.html#Host-Names>
32//!
33//! This once-simple lookup API has unfortunately degenerated into a sedimentary
34//! chaos of numbered functions differentiated by reentrance and lack thereof.
35//! An early indication of which is the conspicuous absence of `gethostbyname3_r`
36//! and `gethostbyname4_r` in the docs linked above.
37//!
38//! However, as of writing, `gethostbyname4_r` is the only NSS host hook that
39//! can return IPv6 addresses with a `scope_id`, which makes it a big deal
40//! for the chosen few who care about such things.
41//!
42//! Other Rust NSS usage is already well supported by the [libnss crate](https://crates.io/crates/libnss).
43//! The motivating cause for this crate cannot accomodate its GPL license,
44//! which is why this is standalone. Presumably both crates can be used in
45//! the same `cdylib` to cover the full NSS host API.
46//!
47//! If the other hooks aren't needed, though, a cdylib with just `gethostbyname4_r`
48//! is sufficient for `getaddrinfo`-based resolution via `/etc/nsswitch.conf`.
49
50// This crate was previously `no_std`. It still could be if not for `std::panic::catch_unwind`.
51// But `catch_unwind` is warranted since uncaught panic across FFI is terrible,
52// especially in the types of apps that use NSS hooks. Panic is unavoidably possible
53// since this wraps unknown user code.
54
55mod buf;
56pub mod err;
57
58use core::ffi::CStr;
59use core::net::Ipv4Addr;
60use core::net::Ipv6Addr;
61use std::net::IpAddr;
62
63use crate::buf::Gaih4Buf;
64use crate::err::NssErr;
65use crate::err::NssStatus;
66
67#[doc(hidden)]
68pub mod _macro_internal {
69    pub use paste;
70}
71
72/// This macro expands into an NSS-compatible hook for the `gethostbyname4_r`
73/// hostname resolution API.
74///
75/// # Safety
76///
77/// There must not be any other exported function named `_nss_{name}_gethostbyname4_r`
78/// in your `cdylib`.
79#[macro_export]
80macro_rules! impl_gethostbyname4_r {
81    ($nss_name:ident, $resolver:ident) => {
82        $crate::_macro_internal::paste::paste! {
83            #[unsafe(no_mangle)]
84            pub unsafe extern "C" fn [<_nss_ $nss_name _gethostbyname4_r>](
85                name: *const ::libc::c_char,
86                pat: *mut *mut $crate::GaihAddrTuple,
87                buffer: *mut ::libc::c_char,
88                buflen: ::libc::size_t,
89                errnop: *mut ::libc::c_int,
90                h_errnop: *mut ::libc::c_int,
91                ttlp: *mut ::libc::c_int,
92            ) -> ::libc::c_int {
93                std::panic::catch_unwind(|| {
94                    unsafe { $crate::gethostbyname4_r::<$resolver>(name, pat, buffer, buflen, errnop, h_errnop, ttlp) }
95                }).unwrap_or_else(|_| {
96                    unsafe {
97                        if !errnop.is_null() {
98                            *errnop = ::libc::EIO;
99                        }
100                        if !h_errnop.is_null() {
101                            *h_errnop = $crate::err::HostStatus::NoRecovery as i32;
102                        }
103                    }
104                    $crate::err::NssStatus::Unavailable as i32
105                })
106            }
107        }
108    };
109}
110
111/// An address that can be returned from gethostbyname4_r.
112#[derive(Debug, PartialEq, Eq, Clone, Copy)]
113pub struct Addr {
114    /// The IP address that was resolved.
115    pub ip: IpAddr,
116
117    /// This is typically only used for IPv6.
118    ///
119    /// Zero is a safe default if you're using IPv4 or don't know
120    /// what to put here.
121    //
122    // Leaving this as an option in IPv4 to enable whatever shenanigans
123    // the API user might be up to.
124    pub scope_id: u32,
125}
126
127/// Implement this trait with the actual address business logic
128/// that `gethostbyname4_r` should expose. The C interop layer
129/// simply wraps the resolution defined here.
130pub trait HostResolver {
131    /// Returns zero or more host addresses matching the hostname query
132    /// or an NSS-contextualized error on failure.
133    fn resolve_host(hostname: &str) -> Result<impl IntoIterator<Item = Addr>, NssErr>;
134
135    /// Optionally sets the "Time to Live Pointer" for the given
136    /// hostname's NSS result. This influences address cache lifespan.
137    ///
138    /// It is perfectly fine to ignore this. Only implement it if you
139    /// have a reason.
140    ///
141    /// This function is only invoked if the caller's TTLP is not null,
142    /// and returning None will skip writing to the pointer entirely.
143    fn set_ttlp(hostname: &str) -> Option<i32> {
144        let _ = hostname;
145        None
146    }
147}
148
149/// GETHOSTBYNAME4_R
150///
151/// This majestically-named function is used by glibc's `getaddrinfo`
152/// lookup when the "simple, old functions" are unsuitable. The motivating
153/// case is IPv6 scope IDs:
154///
155/// <https://github.com/lattera/glibc/blob/895ef79e04a953cac1493863bcae29ad85657ee1/sysdeps/posix/getaddrinfo.c#L563-L565>
156///
157/// Authoritative docs for implementing this API were elusive, so this
158/// effort is based largely on avahi nss-mdns source. My own understanding of
159/// this API is documented here in-excess with the hope that anything incorrect
160/// can be swiftly identified and fixed. If it is somehow fully correct, then
161/// it may also be a useful reference for others implementing NSS hooks.
162///
163/// # Safety
164///
165/// This function should never be called outside the NSS lookup path.
166/// Within glibc NSS, this implementation expects the following:
167///
168/// - `name` is a valid C string.
169/// - `*pat` is always a valid pointer. `**pat` may be either NULL or a valid
170///   `GaihAddrTuple` into which the first NSS result is written. The caller
171///   will only explore this list if it receives a success return value.
172/// - `buffer` + `buflen` are equivalent to a `&mut [u8]` with all the expectations
173///   byte slices carry in safe rust.
174/// - `errnop` and `h_errnop` are safe to dereference.
175/// - `ttlp` is either NULL or safe to dereference.
176///
177/// # Returns
178///
179/// Return value is an enum defined here:
180///
181/// <https://github.com/lattera/glibc/blob/895ef79e04a953cac1493863bcae29ad85657ee1/nss/nss.h#L30-L38>
182#[inline]
183#[doc(hidden)]
184pub unsafe fn gethostbyname4_r<R: HostResolver>(
185    // The hostname to be resolved. This is a null-terminated C-string and
186    // must not be used in the returned gaih_addrtuple. The gaih_addrtuple
187    // name should be stored within the given return buffer:
188    //
189    // https://github.com/avahi/nss-mdns/blob/3292b172ce0100a1aed8b67c381760bc3fb87f2e/src/util.c#L234-L236
190    name: *const libc::c_char,
191
192    // "Pointer to Address Tuple"
193    // Pointer to the linked list node in which this function's results are stored.
194    // Said list must live entirely within the given buffer.
195    //
196    // HOWEVER, if `*pat` is not null, then the first node in the list should
197    // be placed there, and all subsequent nodes should live in the buffer.
198    //
199    // https://github.com/avahi/nss-mdns/blob/3292b172ce0100a1aed8b67c381760bc3fb87f2e/src/util.c#L242-L255
200    pat: *mut *mut GaihAddrTuple,
201
202    // A buffer in which all results must be stored including the hostname.
203    buffer: *mut libc::c_char,
204
205    // The length of this buffer in bytes.
206    buflen: libc::size_t,
207
208    // A canonical linux error code.
209    errnop: *mut libc::c_int,
210
211    // "Host" lookup errno. Extends the standard errno.
212    //
213    // https://github.com/lattera/glibc/blob/895ef79e04a953cac1493863bcae29ad85657ee1/resolv/netdb.h#L62-L69
214    h_errnop: *mut libc::c_int,
215
216    // DNS time to live hint.
217    //
218    // NCSD initializes it to i32::MAX.
219    //
220    // https://github.com/lattera/glibc/blob/895ef79e04a953cac1493863bcae29ad85657ee1/nscd/aicache.c#L119
221    //
222    // And nss-mdns just ignores it.
223    //
224    // https://github.com/avahi/nss-mdns/blob/3292b172ce0100a1aed8b67c381760bc3fb87f2e/src/nss.c#L164
225    ttlp: *mut libc::c_int,
226) -> libc::c_int {
227    if name.is_null() || pat.is_null() || buffer.is_null() || errnop.is_null() || h_errnop.is_null()
228    // Allow null ttlp
229    {
230        return NssStatus::Unavailable as i32;
231    }
232
233    let (hostname, pat, errnop, h_errnop) = unsafe {
234        (
235            CStr::from_ptr(name),
236            &mut *pat,
237            &mut *errnop,
238            &mut *h_errnop,
239        )
240    };
241
242    let maybe_buf = unsafe { Gaih4Buf::try_new(hostname, pat, buffer, buflen) };
243    let mut buffer = match maybe_buf {
244        Ok(b) => b,
245        Err(e) => return e.bail(errnop, h_errnop),
246    };
247
248    let Ok(hostname) = hostname.to_str() else {
249        // Require a UTF-8 hostname.
250        return NssErr::INVALID_INPUT.bail(errnop, h_errnop);
251    };
252
253    let addrs = match R::resolve_host(hostname) {
254        Ok(res) => res,
255        Err(e) => return e.bail(errnop, h_errnop),
256    };
257
258    let mut found = false;
259    for addr in addrs {
260        if !buffer.push(addr) {
261            return NssErr::BUF_TOO_SMALL.bail(errnop, h_errnop);
262        }
263        found = true;
264    }
265
266    if !found {
267        return NssErr::NO_RESULT.bail(errnop, h_errnop);
268    }
269
270    if !ttlp.is_null()
271        && let Some(user_ttlp) = R::set_ttlp(hostname)
272    {
273        unsafe {
274            *ttlp = user_ttlp;
275        }
276    }
277
278    NssErr::SUCCESS.bail(errnop, h_errnop)
279}
280
281/// Recursive host object returned from `gethostbyname4`.
282///
283/// Defined in `nss.h`.
284///
285/// <https://github.com/lattera/glibc/blob/895ef79e04a953cac1493863bcae29ad85657ee1/nss/nss.h#L42-L49>
286#[repr(C)]
287#[derive(Debug)]
288#[doc(hidden)]
289pub struct GaihAddrTuple {
290    next: *mut GaihAddrTuple,
291    name: *const libc::c_char,
292    family: libc::c_int,
293
294    /// Stored big endian.
295    ///
296    /// <https://www.man7.org/linux/man-pages/man3/gethostbyname.3.html#:~:text=address%20in%20bytes.-,h_addr_list,-An%20array%20of>
297    addr: [libc::c_uint; 4],
298
299    /// Stored native endian.
300    ///
301    /// <https://sourceware.org/glibc/manual/2.41/html_node/Internet-Address-Formats.html#:~:text=The%20scope%20ID%20is%20stored%20in%20host%20byte%20order>
302    scope_id: libc::c_uint,
303}
304
305impl GaihAddrTuple {
306    fn new(hostname: *const libc::c_char) -> Self {
307        Self {
308            next: core::ptr::null_mut(),
309            name: hostname,
310            family: libc::AF_UNSPEC,
311            addr: [0u32; 4],
312            scope_id: 0,
313        }
314    }
315
316    /// Constructs a new node for the given address.
317    fn new_addr(hostname: *const libc::c_char, addr: Addr) -> Self {
318        let mut pat = match addr.ip {
319            IpAddr::V4(v4) => Self::new_v4(hostname, v4),
320            IpAddr::V6(v6) => Self::new_v6(hostname, v6),
321        };
322        pat.scope_id = addr.scope_id;
323        pat
324    }
325
326    /// Constructs a new IPv4 address node.
327    fn new_v4(hostname: *const libc::c_char, ipv4: Ipv4Addr) -> Self {
328        // This and `new_v6` are informed by avahi's use of inet_pton.
329        // https://github.com/avahi/nss-mdns/blob/3292b172ce0100a1aed8b67c381760bc3fb87f2e/src/avahi.c#L108
330        let mut pat = Self::new(hostname);
331        pat.family = libc::AF_INET;
332        pat.addr[0] = u32::from_ne_bytes(ipv4.octets());
333        pat
334    }
335
336    /// Constructs a new IPv6 address node.
337    fn new_v6(hostname: *const libc::c_char, ipv6: Ipv6Addr) -> Self {
338        let mut pat = Self::new(hostname);
339        pat.family = libc::AF_INET6;
340
341        ipv6.octets()
342            .chunks_exact(4)
343            .map(|bits| <[_; 4]>::try_from(bits).expect("exact chunk size is four"))
344            .map(u32::from_ne_bytes)
345            .zip(&mut pat.addr)
346            .for_each(|(val, slot)| *slot = val);
347
348        pat
349    }
350}
351
352#[cfg(test)]
353mod conversion_tests {
354    use core::net::Ipv4Addr;
355    use core::net::Ipv6Addr;
356
357    use crate::GaihAddrTuple;
358
359    /// NSS expects `gaih_addrtuple.addr` to hold the address in
360    /// big endian order. This test verifies with a direct conversion.
361    #[test]
362    fn ipv4_addr_is_network_byte_order() {
363        let t = GaihAddrTuple::new_v4(core::ptr::null(), Ipv4Addr::LOCALHOST);
364        let bytes: [u8; 16] = unsafe { core::mem::transmute(t.addr) };
365        assert_eq!(bytes[..4], Ipv4Addr::LOCALHOST.octets());
366    }
367
368    // IPv6 equivalent of the test above
369    #[test]
370    fn ipv6_addr_is_network_byte_order() {
371        let t = GaihAddrTuple::new_v6(core::ptr::null(), Ipv6Addr::LOCALHOST);
372        let bytes: [u8; 16] = unsafe { core::mem::transmute(t.addr) };
373        assert_eq!(bytes, Ipv6Addr::LOCALHOST.octets());
374    }
375}