1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
//! `zeroconf` is a cross-platform library that wraps underlying [ZeroConf/mDNS] implementations
//! such as [Bonjour] or [Avahi], providing an easy and idiomatic way to both register and
//! browse services.
//!
//! This crate provides the cross-platform [`MdnsService`] and [`MdnsBrowser`] available for each
//! supported platform as well as platform-specific modules for lower-level access to the mDNS
//! implementation should that be necessary.
//!
//! Most users of this crate need only [`MdnsService`] and [`MdnsBrowser`].
//!
//! # Examples
//!
//! ## Register a service
//!
//! When registering a service, you may optionally pass a "context" to pass state through the
//! callback. The only requirement is that this context implements the [`Any`] trait, which most
//! types will automatically. See [`MdnsService`] for more information about contexts.
//!
//! ```no_run
//! #[macro_use]
//! extern crate log;
//!
//! use clap::Parser;
//!
//! use std::any::Any;
//! use std::sync::{Arc, Mutex};
//! use std::time::Duration;
//! use zeroconf::prelude::*;
//! use zeroconf::{MdnsService, ServiceRegistration, ServiceType, TxtRecord};
//!
//! #[derive(Parser, Debug)]
//! #[command(author, version, about)]
//! struct Args {
//! /// Name of the service type to register
//! #[clap(short, long, default_value = "http")]
//! name: String,
//!
//! /// Protocol of the service type to register
//! #[clap(short, long, default_value = "tcp")]
//! protocol: String,
//!
//! /// Sub-types of the service type to register
//! #[clap(short, long)]
//! sub_types: Vec<String>,
//! }
//!
//! #[derive(Default, Debug)]
//! pub struct Context {
//! service_name: String,
//! }
//!
//! fn main() -> zeroconf::Result<()> {
//! env_logger::init();
//!
//! let Args {
//! name,
//! protocol,
//! sub_types,
//! } = Args::parse();
//!
//! let sub_types = sub_types.iter().map(|s| s.as_str()).collect::<Vec<_>>();
//! let service_type = ServiceType::with_sub_types(&name, &protocol, sub_types)?;
//! let mut service = MdnsService::new(service_type, 8080);
//! let mut txt_record = TxtRecord::new();
//! let context: Arc<Mutex<Context>> = Arc::default();
//!
//! txt_record.insert("foo", "bar")?;
//!
//! service.set_name("zeroconf_example_service");
//! service.set_registered_callback(Box::new(on_service_registered));
//! service.set_context(Box::new(context));
//! service.set_txt_record(txt_record);
//!
//! let event_loop = service.register()?;
//!
//! loop {
//! // calling `poll()` will keep this service alive
//! event_loop.poll(Duration::from_secs(0))?;
//! }
//! }
//!
//! fn on_service_registered(
//! result: zeroconf::Result<ServiceRegistration>,
//! context: Option<Arc<dyn Any>>,
//! ) {
//! let service = result.expect("failed to register service");
//!
//! info!("Service registered: {:?}", service);
//!
//! let context = context
//! .as_ref()
//! .expect("could not get context")
//! .downcast_ref::<Arc<Mutex<Context>>>()
//! .expect("error down-casting context")
//! .clone();
//!
//! context
//! .lock()
//! .expect("failed to obtain context lock")
//! .service_name = service.name().clone();
//!
//! info!("Context: {:?}", context);
//!
//! // ...
//! }
//! ```
//!
//! ## Browsing services
//! ```no_run
//! #[macro_use]
//! extern crate log;
//!
//! use clap::Parser;
//!
//! use std::any::Any;
//! use std::sync::Arc;
//! use std::time::Duration;
//! use zeroconf::prelude::*;
//! use zeroconf::{MdnsBrowser, ServiceDiscovery, ServiceType};
//!
//! /// Example of a simple mDNS browser
//! #[derive(Parser, Debug)]
//! #[command(author, version, about)]
//! struct Args {
//! /// Name of the service type to browse
//! #[clap(short, long, default_value = "http")]
//! name: String,
//!
//! /// Protocol of the service type to browse
//! #[clap(short, long, default_value = "tcp")]
//! protocol: String,
//!
//! /// Sub-type of the service type to browse
//! #[clap(short, long)]
//! sub_type: Option<String>,
//! }
//!
//! fn main() -> zeroconf::Result<()> {
//! env_logger::init();
//!
//! let Args {
//! name,
//! protocol,
//! sub_type,
//! } = Args::parse();
//!
//! let sub_types: Vec<&str> = match sub_type.as_ref() {
//! Some(sub_type) => vec![sub_type],
//! None => vec![],
//! };
//!
//! let service_type =
//! ServiceType::with_sub_types(&name, &protocol, sub_types).expect("invalid service type");
//!
//! let mut browser = MdnsBrowser::new(service_type);
//!
//! browser.set_service_discovered_callback(Box::new(on_service_discovered));
//!
//! let event_loop = browser.browse_services()?;
//!
//! loop {
//! // calling `poll()` will keep this browser alive
//! event_loop.poll(Duration::from_secs(0))?;
//! }
//! }
//!
//! fn on_service_discovered(
//! result: zeroconf::Result<ServiceDiscovery>,
//! _context: Option<Arc<dyn Any>>,
//! ) {
//! info!(
//! "Service discovered: {:?}",
//! result.expect("service discovery failed")
//! );
//!
//! // ...
//! }
//! ```
//!
//! [ZeroConf/mDNS]: https://en.wikipedia.org/wiki/Zero-configuration_networking
//! [Bonjour]: https://en.wikipedia.org/wiki/Bonjour_(software)
//! [Avahi]: https://en.wikipedia.org/wiki/Avahi_(software)
//! [`MdnsService`]: type.MdnsService.html
//! [`MdnsBrowser`]: type.MdnsBrowser.html
//! [`Any`]: https://doc.rust-lang.org/std/any/trait.Any.html
#![allow(clippy::needless_doctest_main)]
#[macro_use]
extern crate serde;
#[macro_use]
extern crate derive_builder;
#[macro_use]
extern crate zeroconf_macros;
#[cfg(target_os = "linux")]
extern crate avahi_sys;
#[cfg(any(target_vendor = "apple", target_vendor = "pc"))]
extern crate bonjour_sys;
#[macro_use]
extern crate derive_getters;
#[macro_use]
extern crate log;
#[macro_use]
extern crate derive_new;
#[macro_use]
#[cfg(test)]
#[allow(unused_imports)]
extern crate maplit;
#[macro_use]
mod macros;
mod ffi;
mod interface;
mod service_type;
#[cfg(test)]
mod tests;
pub mod browser;
pub mod error;
pub mod event_loop;
pub mod prelude;
pub mod service;
pub mod txt_record;
#[cfg(target_os = "linux")]
pub mod avahi;
#[cfg(any(target_vendor = "apple", target_vendor = "pc"))]
pub mod bonjour;
pub use browser::{ServiceDiscoveredCallback, ServiceDiscovery};
pub use interface::*;
pub use service::{ServiceRegisteredCallback, ServiceRegistration};
pub use service_type::*;
/// Type alias for the platform-specific mDNS browser implementation
#[cfg(target_os = "linux")]
pub type MdnsBrowser = avahi::browser::AvahiMdnsBrowser;
/// Type alias for the platform-specific mDNS browser implementation
#[cfg(any(target_vendor = "apple", target_vendor = "pc"))]
pub type MdnsBrowser = bonjour::browser::BonjourMdnsBrowser;
/// Type alias for the platform-specific mDNS service implementation
#[cfg(target_os = "linux")]
pub type MdnsService = avahi::service::AvahiMdnsService;
/// Type alias for the platform-specific mDNS service implementation
#[cfg(any(target_vendor = "apple", target_vendor = "pc"))]
pub type MdnsService = bonjour::service::BonjourMdnsService;
/// Type alias for the platform-specific structure responsible for polling the mDNS event loop
#[cfg(target_os = "linux")]
pub type EventLoop = avahi::event_loop::AvahiEventLoop;
/// Type alias for the platform-specific structure responsible for polling the mDNS event loop
#[cfg(any(target_vendor = "apple", target_vendor = "pc"))]
pub type EventLoop = bonjour::event_loop::BonjourEventLoop;
/// Type alias for the platform-specific structure responsible for storing and accessing TXT
/// record data
#[cfg(target_os = "linux")]
pub type TxtRecord = avahi::txt_record::AvahiTxtRecord;
/// Type alias for the platform-specific structure responsible for storing and accessing TXT
/// record data
#[cfg(any(target_vendor = "apple", target_vendor = "pc"))]
pub type TxtRecord = bonjour::txt_record::BonjourTxtRecord;
/// Result type for this library
pub type Result<T> = std::result::Result<T, error::Error>;