Skip to main content

mdns_sd/
lib.rs

1//! A small and safe library for Multicast DNS-SD (Service Discovery).
2//!
3//! This library creates one new thread to run a mDNS daemon, and exposes
4//! its API that interacts with the daemon via a
5//! [`flume`](https://crates.io/crates/flume) channel. The channel supports
6//! both `recv()` and `recv_async()`.
7//!
8//! For example, a client querying (browsing) a service behaves like this:
9//!```text
10//!  Client       <channel>       mDNS daemon thread
11//!    |                             | starts its run-loop.
12//!    |       --- Browse -->        |
13//!    |                             | detects services
14//!    |                             | finds service instance A
15//!    |       <-- Found A --        |
16//!    |           ...               | resolves service A
17//!    |       <-- Resolved A --     |
18//!    |           ...               |
19//!```
20//! All commands in the public API are sent to the daemon using the unblocking `try_send()`
21//! so that the caller can use it with both sync and async code, with no dependency on any
22//! particular async runtimes.
23//!
24//! # Usage
25//!
26//! The user starts with creating a daemon by calling [`ServiceDaemon::new()`].
27//! Then as a mDNS querier, the user would call [`browse`](`ServiceDaemon::browse`) to
28//! search for services, and/or as a mDNS responder, call [`register`](`ServiceDaemon::register`)
29//! to publish (i.e. announce) its own service. And, the daemon type can be cloned and passed
30//! around between threads.
31//!
32//! The user can also call [`resolve_hostname`](`ServiceDaemon::resolve_hostname`) to
33//! resolve a hostname to IP addresses using mDNS, regardless if the host publishes a service name.
34//!
35//! ## Example: a client querying for a service type.
36//!
37//! ```rust
38//! use mdns_sd::{ServiceDaemon, ServiceEvent};
39//!
40//! // Create a daemon
41//! let mdns = ServiceDaemon::new().expect("Failed to create daemon");
42//!
43//! // Browse for a service type.
44//! let service_type = "_mdns-sd-my-test._udp.local.";
45//! let receiver = mdns.browse(service_type).expect("Failed to browse");
46//!
47//! // Receive the browse events in sync or async. Here is
48//! // an example of using a thread. Users can call `receiver.recv_async().await`
49//! // if running in async environment.
50//! std::thread::spawn(move || {
51//!     while let Ok(event) = receiver.recv() {
52//!         match event {
53//!             ServiceEvent::ServiceResolved(resolved) => {
54//!                 println!("Resolved a new service: {}", resolved.fullname);
55//!             }
56//!             other_event => {
57//!                 println!("Received other event: {:?}", &other_event);
58//!             }
59//!         }
60//!     }
61//! });
62//!
63//! // Gracefully shutdown the daemon.
64//! std::thread::sleep(std::time::Duration::from_secs(1));
65//! mdns.shutdown().unwrap();
66//! ```
67//!
68//! ## Example: a server publishs a service and responds to queries.
69//!
70//! ```rust
71//! use mdns_sd::{ServiceDaemon, ServiceInfo};
72//! use std::collections::HashMap;
73//!
74//! // Create a daemon
75//! let mdns = ServiceDaemon::new().expect("Failed to create daemon");
76//!
77//! // Optional: setup a monitor channel to receive events, especially errors from the daemon.
78//! let receiver = mdns.monitor().expect("Failed to monitor daemon");
79//! std::thread::spawn(move || {
80//!     while let Ok(event) = receiver.recv() {
81//!         match event {
82//!             mdns_sd::DaemonEvent::Error(error) => {
83//!                 eprintln!("Daemon error: {error}");
84//!             }
85//!             _ => {}
86//!         }
87//!     }
88//! });
89//!
90//! // Create a service info.
91//! // Make sure that the service name: "mdns-sd-my-test" is not longer than the max length limit (15 by default).
92//! let service_type = "_mdns-sd-my-test._udp.local.";
93//! let instance_name = "my_instance";
94//! let ip = "192.168.1.12";
95//! let host_name = "192.168.1.12.local.";
96//! let port = 5200;
97//! let properties = [("property_1", "test"), ("property_2", "1234")];
98//!
99//! let my_service = ServiceInfo::new(
100//!     service_type,
101//!     instance_name,
102//!     host_name,
103//!     ip,
104//!     port,
105//!     &properties[..],
106//! ).unwrap();
107//!
108//! // Register with the daemon, which publishes the service.
109//! mdns.register(my_service).expect("Failed to register our service");
110//!
111//! // Gracefully shutdown the daemon
112//! std::thread::sleep(std::time::Duration::from_secs(1));
113//! mdns.shutdown().unwrap();
114//! ```
115//!
116//! ## Conflict resolution
117//!
118//! When a service responder receives another DNS record with the same name as its own record, a conflict occurs.
119//! The mDNS [RFC 6762 section 9](https://datatracker.ietf.org/doc/html/rfc6762#section-9) defines a conflict resolution
120//! mechanism, which is implemented in this library. When an application wishes to be notified of conflict resolutions,
121//! it follows the steps below:
122//!
123//! 1. The application calls [`ServiceDaemon::monitor()`] to monitor all events from the daemon service responder.
124//! 2. When a conflict resolution causes a name change, the library sends an event to the application: [`DaemonEvent::NameChange`],
125//!    which provides [`DnsNameChange`] with details.
126//!
127//! # Limitations
128//!
129//! This implementation is based on the following RFCs:
130//! - mDNS:   [RFC 6762](https://tools.ietf.org/html/rfc6762)
131//! - DNS-SD: [RFC 6763](https://tools.ietf.org/html/rfc6763)
132//! - DNS:    [RFC 1035](https://tools.ietf.org/html/rfc1035)
133//!
134//! We focus on the common use cases at first, and currently have the following limitations:
135//! - Only support multicast, not unicast send/recv.
136//! - Only support 32-bit or bigger platforms, not 16-bit platforms.
137//!
138//! # Use logging in tests and examples
139//!
140//! Often times it is helpful to enable logging running tests or examples to examine the details.
141//! For tests and examples, we use [`env_logger`](https://docs.rs/env_logger/latest/env_logger/)
142//! as the logger and use [`test-log`](https://docs.rs/test-log/latest/test_log/) to enable logging for tests.
143//! For instance you can show all test logs using:
144//!
145//! ```shell
146//! RUST_LOG=debug cargo test integration_success -- --nocapture
147//! ```
148//!
149//! We also enabled the logging for the examples. For instance you can do:
150//!
151//! ```shell
152//! RUST_LOG=debug cargo run --example query _printer._tcp
153//! ```
154//!
155
156#![forbid(unsafe_code)]
157#![allow(clippy::single_component_path_imports)]
158
159// log for logging (optional).
160#[cfg(feature = "logging")]
161use log;
162
163#[cfg(not(feature = "logging"))]
164#[macro_use]
165mod log {
166    macro_rules! trace    ( ($($tt:tt)*) => {{}} );
167    macro_rules! debug    ( ($($tt:tt)*) => {{}} );
168    macro_rules! info     ( ($($tt:tt)*) => {{}} );
169    macro_rules! warn     ( ($($tt:tt)*) => {{}} );
170    macro_rules! error    ( ($($tt:tt)*) => {{}} );
171}
172
173mod dns_cache;
174mod dns_parser;
175mod error;
176mod service_daemon;
177mod service_info;
178
179pub use dns_parser::{InterfaceId, RRType, ScopedIp, ScopedIpV4, ScopedIpV6};
180pub use error::{Error, Result};
181pub use service_daemon::{
182    DaemonEvent, DaemonStatus, DnsNameChange, HostnameResolutionEvent, IfKind, Metrics,
183    ServiceDaemon, ServiceEvent, UnregisterStatus, IP_CHECK_INTERVAL_IN_SECS_DEFAULT, MDNS_PORT,
184    SERVICE_NAME_LEN_MAX_DEFAULT, VERIFY_TIMEOUT_DEFAULT,
185};
186pub use service_info::{
187    AsIpAddrs, IntoTxtProperties, ResolvedService, ServiceInfo, TxtProperties, TxtProperty,
188};
189
190/// A handler to receive messages from [ServiceDaemon]. Re-export from `flume` crate.
191pub use flume::Receiver;