├── src ├── bindings │ ├── mod.rs │ └── avahi │ │ ├── mod.rs │ │ ├── types.rs │ │ ├── enums.rs │ │ └── functions.rs ├── adapters │ ├── fake │ │ ├── mod.rs │ │ └── adapter.rs │ ├── avahi │ │ ├── mod.rs │ │ ├── utils.rs │ │ ├── callbacks.rs │ │ ├── errors.rs │ │ └── adapter.rs │ ├── mod.rs │ ├── errors.rs │ └── adapter.rs ├── host │ ├── mod.rs │ └── host_manager.rs ├── discovery │ ├── mod.rs │ └── discovery_manager.rs └── lib.rs ├── .gitignore ├── Cargo.toml ├── examples ├── annouce.rs ├── host_name.rs └── discovery.rs ├── .travis.yml ├── Cargo.lock ├── README.md └── LICENSE /src/bindings/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod avahi; 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | .vscode 3 | .idea 4 | *.iml 5 | -------------------------------------------------------------------------------- /src/adapters/fake/mod.rs: -------------------------------------------------------------------------------- 1 | pub use self::adapter::*; 2 | 3 | mod adapter; 4 | -------------------------------------------------------------------------------- /src/host/mod.rs: -------------------------------------------------------------------------------- 1 | pub use self::host_manager::HostManager; 2 | 3 | pub mod host_manager; 4 | -------------------------------------------------------------------------------- /src/discovery/mod.rs: -------------------------------------------------------------------------------- 1 | pub use self::discovery_manager::*; 2 | 3 | pub mod discovery_manager; 4 | -------------------------------------------------------------------------------- /src/adapters/avahi/mod.rs: -------------------------------------------------------------------------------- 1 | pub use self::adapter::*; 2 | 3 | mod adapter; 4 | mod callbacks; 5 | pub mod errors; 6 | mod utils; 7 | -------------------------------------------------------------------------------- /src/bindings/avahi/mod.rs: -------------------------------------------------------------------------------- 1 | pub use self::enums::*; 2 | pub use self::functions::*; 3 | pub use self::types::*; 4 | 5 | mod enums; 6 | mod functions; 7 | mod types; 8 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | extern crate log; 3 | 4 | extern crate libc; 5 | 6 | mod adapters; 7 | #[cfg(target_os = "linux")] 8 | mod bindings; 9 | 10 | pub mod discovery; 11 | pub mod host; 12 | pub use adapters::errors; 13 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "multicast_dns" 3 | version = "0.5.0" 4 | authors = ["Aleh Zasypkin "] 5 | license = "MPL-2.0" 6 | keywords = ["multicast", "discovery", "mdns", "dns", "avahi"] 7 | description = "Simple Rust wrapper around Avahi Daemon" 8 | 9 | [dependencies] 10 | libc = "0.2.67" 11 | log = "0.4.8" 12 | -------------------------------------------------------------------------------- /src/adapters/mod.rs: -------------------------------------------------------------------------------- 1 | pub use self::adapter::Adapter; 2 | 3 | #[cfg(target_os = "linux")] 4 | mod avahi; 5 | #[cfg(target_os = "linux")] 6 | pub use adapters::avahi::AvahiAdapter as PlatformDependentAdapter; 7 | 8 | #[cfg(not(target_os = "linux"))] 9 | mod fake; 10 | #[cfg(not(target_os = "linux"))] 11 | pub use adapters::fake::FakeAdapter as PlatformDependentAdapter; 12 | 13 | pub mod adapter; 14 | pub mod errors; 15 | -------------------------------------------------------------------------------- /examples/annouce.rs: -------------------------------------------------------------------------------- 1 | extern crate multicast_dns; 2 | use multicast_dns::host::*; 3 | 4 | fn main() { 5 | let service_type = "_something._tcp"; 6 | let port = 8083; 7 | 8 | let host_manager = HostManager::new(); 9 | 10 | host_manager.announce_service("my local service", service_type, port).unwrap(); 11 | 12 | println!("Press enter to exit example"); 13 | std::io::stdin().read_line(&mut String::new()).unwrap(); 14 | } 15 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: required 2 | language: rust 3 | rust: 4 | - nightly 5 | 6 | cache: 7 | directories: 8 | - $HOME/.cargo 9 | - $TRAVIS_BUILD_DIR/target 10 | 11 | before_install: 12 | - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then sudo apt-get -qq update; fi 13 | - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then sudo apt-get install -y libavahi-client-dev libavahi-common-dev libavahi-common3 libdbus-1-dev; fi 14 | 15 | script: 16 | - cargo build --examples 17 | 18 | os: 19 | - linux 20 | - osx 21 | 22 | notifications: 23 | email: 24 | on_success: never 25 | 26 | branches: 27 | only: 28 | - master 29 | -------------------------------------------------------------------------------- /examples/host_name.rs: -------------------------------------------------------------------------------- 1 | extern crate multicast_dns; 2 | use multicast_dns::host::HostManager; 3 | 4 | fn main() { 5 | let host_name = format!("custom-host"); 6 | 7 | let host_manager = HostManager::new(); 8 | 9 | if !host_manager.is_valid_name(&host_name).unwrap() { 10 | panic!("Host name `{}` is not a valid host name!", &host_name); 11 | } 12 | 13 | // The `new_host_name` can be different from the one we are trying to set, 14 | // due to possible collisions that may happen. 15 | let new_host_name = host_manager.set_name(&host_name).unwrap(); 16 | 17 | println!("New host name is: {:?}", &new_host_name); 18 | } 19 | -------------------------------------------------------------------------------- /src/adapters/errors.rs: -------------------------------------------------------------------------------- 1 | use std::error::Error as StdError; 2 | use std::fmt; 3 | 4 | #[derive(Debug)] 5 | pub enum Error { 6 | AdapterFailure(String), 7 | Internal(String), 8 | } 9 | 10 | impl fmt::Display for Error { 11 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 12 | match *self { 13 | Error::AdapterFailure(ref message) => f.write_str(message), 14 | Error::Internal(ref message) => f.write_str(message), 15 | } 16 | } 17 | } 18 | 19 | impl StdError for Error { 20 | fn cause(&self) -> Option<&dyn StdError> { 21 | None 22 | } 23 | } 24 | 25 | #[cfg(target_os = "linux")] 26 | use adapters::avahi; 27 | #[cfg(target_os = "linux")] 28 | impl From for Error { 29 | fn from(err: avahi::errors::Error) -> Error { 30 | Error::AdapterFailure(format!("Avahi - {}", err)) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/adapters/adapter.rs: -------------------------------------------------------------------------------- 1 | use adapters::errors::Error; 2 | use discovery::discovery_manager::*; 3 | 4 | pub trait DiscoveryAdapter { 5 | fn start_discovery( 6 | &self, 7 | service_type: &str, 8 | listeners: DiscoveryListeners, 9 | ) -> Result<(), Error>; 10 | fn resolve(&self, service: ServiceInfo, listeners: ResolveListeners); 11 | fn stop_discovery(&self); 12 | } 13 | 14 | pub trait HostAdapter { 15 | fn get_name(&self) -> Result; 16 | fn get_name_fqdn(&self) -> Result; 17 | fn set_name(&self, host_name: &str) -> Result; 18 | fn is_valid_name(&self, host_name: &str) -> Result; 19 | fn get_alternative_name(&self, host_name: &str) -> Result; 20 | fn add_name_alias(&self, host_name: &str) -> Result<(), Error>; 21 | fn announce_service(&self, service_name: &str, service_type: &str, port: u16) -> Result<(), Error>; 22 | } 23 | 24 | pub trait Adapter: DiscoveryAdapter + HostAdapter + Drop { 25 | fn new() -> Self 26 | where 27 | Self: Sized; 28 | } 29 | -------------------------------------------------------------------------------- /examples/discovery.rs: -------------------------------------------------------------------------------- 1 | extern crate multicast_dns; 2 | use multicast_dns::discovery::*; 3 | 4 | fn main() { 5 | let service_type = format!("_device-info._tcp"); 6 | 7 | let discovery_manager = DiscoveryManager::new(); 8 | 9 | let on_service_resolved = |service: ServiceInfo| { 10 | println!("Service resolved: {:?}", service); 11 | }; 12 | 13 | let on_service_discovered = |service: ServiceInfo| { 14 | println!("Service discovered: {:?}", service); 15 | 16 | let resolve_listeners = ResolveListeners { 17 | on_service_resolved: Some(&on_service_resolved), 18 | }; 19 | 20 | discovery_manager.resolve_service(service, resolve_listeners); 21 | }; 22 | 23 | let on_all_discovered = || { 24 | println!("All services has been discovered"); 25 | }; 26 | 27 | let discovery_listeners = DiscoveryListeners { 28 | on_service_discovered: Some(&on_service_discovered), 29 | on_all_discovered: Some(&on_all_discovered), 30 | }; 31 | 32 | discovery_manager.discover_services(&service_type, discovery_listeners).unwrap(); 33 | } -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "cfg-if" 5 | version = "0.1.10" 6 | source = "registry+https://github.com/rust-lang/crates.io-index" 7 | 8 | [[package]] 9 | name = "libc" 10 | version = "0.2.67" 11 | source = "registry+https://github.com/rust-lang/crates.io-index" 12 | 13 | [[package]] 14 | name = "log" 15 | version = "0.4.8" 16 | source = "registry+https://github.com/rust-lang/crates.io-index" 17 | dependencies = [ 18 | "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", 19 | ] 20 | 21 | [[package]] 22 | name = "multicast_dns" 23 | version = "0.5.0" 24 | dependencies = [ 25 | "libc 0.2.67 (registry+https://github.com/rust-lang/crates.io-index)", 26 | "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", 27 | ] 28 | 29 | [metadata] 30 | "checksum cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" 31 | "checksum libc 0.2.67 (registry+https://github.com/rust-lang/crates.io-index)" = "eb147597cdf94ed43ab7a9038716637d2d1bf2bc571da995d0028dec06bd3018" 32 | "checksum log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)" = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7" 33 | -------------------------------------------------------------------------------- /src/host/host_manager.rs: -------------------------------------------------------------------------------- 1 | use adapters::adapter::Adapter; 2 | use adapters::adapter::HostAdapter; 3 | use adapters::errors::Error; 4 | use adapters::PlatformDependentAdapter; 5 | 6 | pub struct HostManager { 7 | adapter: Box, 8 | } 9 | 10 | impl HostManager { 11 | pub fn new() -> Self { 12 | Default::default() 13 | } 14 | 15 | pub fn get_name(&self) -> Result { 16 | self.adapter.get_name() 17 | } 18 | 19 | pub fn set_name(&self, name: &str) -> Result { 20 | self.adapter.set_name(name) 21 | } 22 | 23 | pub fn is_valid_name(&self, name: &str) -> Result { 24 | self.adapter.is_valid_name(name) 25 | } 26 | 27 | pub fn get_alternative_name(&self, name: &str) -> Result { 28 | self.adapter.get_alternative_name(name) 29 | } 30 | 31 | pub fn add_name_alias(&self, name: &str) -> Result<(), Error> { 32 | self.adapter.add_name_alias(name) 33 | } 34 | 35 | pub fn announce_service(&self, name: &str, service_type: &str, port: u16) -> Result<(), Error> { 36 | self.adapter.announce_service(name, service_type, port) 37 | } 38 | } 39 | 40 | impl Default for HostManager { 41 | fn default() -> Self { 42 | let adapter: Box = Box::new(PlatformDependentAdapter::new()); 43 | 44 | HostManager { adapter } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/adapters/avahi/utils.rs: -------------------------------------------------------------------------------- 1 | use libc::{c_char, c_void}; 2 | use std::ffi::CStr; 3 | use std::ffi::CString; 4 | 5 | use bindings::avahi::*; 6 | 7 | pub struct AvahiUtils; 8 | 9 | impl AvahiUtils { 10 | pub fn to_c_string(r_string: String) -> CString { 11 | CString::new(r_string).unwrap() 12 | } 13 | 14 | pub fn to_owned_string(c_string: *const c_char) -> Option { 15 | if c_string.is_null() { 16 | None 17 | } else { 18 | Some( 19 | unsafe { CStr::from_ptr(c_string) } 20 | .to_string_lossy() 21 | .into_owned(), 22 | ) 23 | } 24 | } 25 | 26 | pub fn parse_address(address: *const AvahiAddress) -> Option { 27 | if address.is_null() { 28 | None 29 | } else { 30 | let address_vector = Vec::with_capacity(AVAHI_ADDRESS_STR_MAX); 31 | unsafe { 32 | avahi_address_snprint(address_vector.as_ptr(), AVAHI_ADDRESS_STR_MAX, address) 33 | }; 34 | 35 | AvahiUtils::to_owned_string(address_vector.as_ptr()) 36 | } 37 | } 38 | 39 | pub fn parse_txt(txt: *mut AvahiStringList) -> Option { 40 | if txt.is_null() { 41 | None 42 | } else { 43 | unsafe { 44 | let txt_pointer = avahi_string_list_to_string(txt); 45 | let txt = AvahiUtils::to_owned_string(txt_pointer); 46 | avahi_free(txt_pointer as *mut c_void); 47 | 48 | txt 49 | } 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/discovery/discovery_manager.rs: -------------------------------------------------------------------------------- 1 | use adapters::adapter::Adapter; 2 | use adapters::adapter::DiscoveryAdapter; 3 | use adapters::errors::Error; 4 | use adapters::PlatformDependentAdapter; 5 | 6 | #[derive(Clone, Copy, Debug)] 7 | pub enum ServiceProtocol { 8 | IPv4 = 0, 9 | IPv6 = 1, 10 | Unspecified = -1, 11 | } 12 | 13 | #[derive(Debug)] 14 | pub struct ServiceInfo { 15 | pub address: Option, 16 | pub domain: Option, 17 | pub host_name: Option, 18 | pub interface: i32, 19 | pub name: Option, 20 | pub port: u16, 21 | pub protocol: ServiceProtocol, 22 | pub type_name: Option, 23 | pub txt: Option, 24 | } 25 | 26 | pub struct DiscoveryListeners<'a> { 27 | pub on_service_discovered: Option<&'a dyn Fn(ServiceInfo)>, 28 | pub on_all_discovered: Option<&'a dyn Fn()>, 29 | } 30 | 31 | pub struct ResolveListeners<'a> { 32 | pub on_service_resolved: Option<&'a dyn Fn(ServiceInfo)>, 33 | } 34 | 35 | pub struct DiscoveryManager { 36 | adapter: Box, 37 | } 38 | 39 | impl DiscoveryManager { 40 | pub fn new() -> Self { 41 | Default::default() 42 | } 43 | 44 | pub fn discover_services( 45 | &self, 46 | service_type: &str, 47 | listeners: DiscoveryListeners, 48 | ) -> Result<(), Error> { 49 | self.adapter.start_discovery(service_type, listeners) 50 | } 51 | 52 | pub fn resolve_service(&self, service: ServiceInfo, listeners: ResolveListeners) { 53 | self.adapter.resolve(service, listeners); 54 | } 55 | 56 | pub fn stop_service_discovery(&self) { 57 | self.adapter.stop_discovery(); 58 | } 59 | } 60 | 61 | impl Default for DiscoveryManager { 62 | fn default() -> Self { 63 | let adapter: Box = Box::new(PlatformDependentAdapter::new()); 64 | 65 | DiscoveryManager { adapter } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Multicast DNS 2 | 3 | [![Build Status](https://travis-ci.org/fxbox/multicast-dns.svg?branch=master)](https://travis-ci.org/fxbox/multicast-dns) 4 | 5 | ```multicust_dns``` - is essentially a Rust wrapper around Avahi that internally uses AvahiDaemon to manage host name and browse services on the local network. 6 | 7 | Requires ```avahi-common```, ```avahi-client``` and ```dbus-1``` libs to compile sucessfully. 8 | 9 | For non-linux platforms that don't have required avahi libs, fake implementation is used. 10 | 11 | See [Multicast DNS Utils](https://github.com/fxbox/multicast-dns-utils) command line app as an example. 12 | 13 | Examples (see `./examples` folder): 14 | 15 | ```rust 16 | extern crate multicast_dns; 17 | use multicast_dns::host::HostManager; 18 | 19 | fn main() { 20 | let host_name = format!("custom-host"); 21 | 22 | let host_manager = HostManager::new(); 23 | 24 | if !host_manager.is_valid_name(&host_name).unwrap() { 25 | panic!("Host name `{}` is not a valid host name!", &host_name); 26 | } 27 | 28 | // The `new_host_name` can be different from the one we are trying to set, 29 | // due to possible collisions that may happen. 30 | let new_host_name = host_manager.set_name(&host_name).unwrap(); 31 | 32 | println!("New host name is: {:?}", &new_host_name); 33 | } 34 | ``` 35 | 36 | or 37 | 38 | ```rust 39 | extern crate multicast_dns; 40 | use multicast_dns::discovery::*; 41 | 42 | fn main() { 43 | let service_type = format!("_device-info._tcp"); 44 | 45 | let discovery_manager = DiscoveryManager::new(); 46 | 47 | let on_service_resolved = |service: ServiceInfo| { 48 | println!("Service resolved: {:?}", service); 49 | }; 50 | 51 | let on_service_discovered = |service: ServiceInfo| { 52 | println!("Service discovered: {:?}", service); 53 | 54 | let resolve_listeners = ResolveListeners { 55 | on_service_resolved: Some(&on_service_resolved), 56 | }; 57 | 58 | discovery_manager.resolve_service(service, resolve_listeners); 59 | }; 60 | 61 | let on_all_discovered = || { 62 | println!("All services has been discovered"); 63 | }; 64 | 65 | let discovery_listeners = DiscoveryListeners { 66 | on_service_discovered: Some(&on_service_discovered), 67 | on_all_discovered: Some(&on_all_discovered), 68 | }; 69 | 70 | discovery_manager.discover_services(&service_type, discovery_listeners); 71 | } 72 | ``` 73 | 74 | Look at [RFC 6762](https://tools.ietf.org/html/rfc6762) and [RFC 6763](https://tools.ietf.org/html/rfc6763) for the standard specifications. 75 | 76 | Also one can take a look at [Service Name and Transport Protocol Port Number Registry](http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml) to see currently available and registered services. -------------------------------------------------------------------------------- /src/bindings/avahi/types.rs: -------------------------------------------------------------------------------- 1 | use super::enums::*; 2 | use libc::{c_char, c_int, c_void}; 3 | 4 | /// A main loop object. 5 | /// Main loops of this type aren't very flexible since they only support a single wakeup type. 6 | #[repr(C)] 7 | #[allow(dead_code)] 8 | pub struct AvahiSimplePoll; 9 | 10 | #[repr(C)] 11 | pub struct AvahiThreadedPoll; 12 | 13 | #[repr(C)] 14 | pub struct AvahiPoll; 15 | 16 | #[repr(C)] 17 | pub struct DBusConnection; 18 | 19 | #[repr(C)] 20 | pub struct AvahiEntryGroup; 21 | 22 | #[repr(C)] 23 | pub struct AvahiDomainBrowser; 24 | 25 | #[repr(C)] 26 | pub struct AvahiServiceBrowser { 27 | path: *const c_char, 28 | client: *const AvahiClient, 29 | callback: ServiceBrowserCallback, 30 | pub userdata: *mut c_void, 31 | } 32 | 33 | #[repr(C)] 34 | pub struct AvahiServiceTypeBrowser; 35 | 36 | #[repr(C)] 37 | pub struct AvahiServiceResolver; 38 | 39 | #[repr(C)] 40 | pub struct AvahiHostNameResolver; 41 | 42 | #[repr(C)] 43 | pub struct AvahiAddressResolver; 44 | 45 | #[repr(C)] 46 | pub struct AvahiRecordBrowser; 47 | 48 | #[repr(C)] 49 | pub struct AvahiAddress; 50 | 51 | #[repr(C)] 52 | pub struct AvahiStringList; 53 | 54 | #[repr(C)] 55 | pub struct AvahiClient { 56 | poll_api: *const AvahiPoll, 57 | bus: *const DBusConnection, 58 | error: u16, 59 | state: AvahiClientState, 60 | flags: AvahiClientFlags, 61 | version_string: *const c_char, 62 | host_name: *const c_char, 63 | host_name_fqdn: *const c_char, 64 | domain_name: *const c_char, 65 | local_service_cookie: u32, 66 | local_service_cookie_valid: u16, 67 | callback: ClientCallback, 68 | pub userdata: *mut c_void, 69 | groups: *const AvahiEntryGroup, 70 | domain_browsers: *const AvahiDomainBrowser, 71 | service_browsers: *const AvahiServiceBrowser, 72 | service_type_browsers: *const AvahiServiceTypeBrowser, 73 | service_resolvers: *const AvahiServiceResolver, 74 | hsot_name_resolvers: *const AvahiHostNameResolver, 75 | address_resolvers: *const AvahiAddressResolver, 76 | record_browsers: *const AvahiRecordBrowser, 77 | } 78 | 79 | pub type ClientCallback = extern "C" fn(*const AvahiClient, AvahiClientState, *const c_void); 80 | 81 | pub type ServiceBrowserCallback = extern "C" fn( 82 | *const AvahiServiceBrowser, 83 | c_int, 84 | AvahiProtocol, 85 | AvahiBrowserEvent, 86 | *const c_char, 87 | *const c_char, 88 | *const c_char, 89 | AvahiLookupResultFlags, 90 | *const c_void, 91 | ); 92 | 93 | pub type ServiceResolverCallback = extern "C" fn( 94 | *const AvahiServiceResolver, 95 | c_int, 96 | AvahiProtocol, 97 | AvahiResolverEvent, 98 | *const c_char, 99 | *const c_char, 100 | *const c_char, 101 | *const c_char, 102 | *const AvahiAddress, 103 | u16, 104 | *mut AvahiStringList, 105 | AvahiLookupResultFlags, 106 | *const c_void, 107 | ); 108 | 109 | pub type AvahiEntryGroupCallback = 110 | extern "C" fn(*const AvahiEntryGroup, AvahiEntryGroupState, *const c_void); 111 | 112 | pub static AVAHI_ADDRESS_STR_MAX: usize = 4 * 8 + 7 + 1; // 1 is for NUL 113 | -------------------------------------------------------------------------------- /src/adapters/fake/adapter.rs: -------------------------------------------------------------------------------- 1 | use adapters::adapter::*; 2 | use adapters::errors::Error; 3 | use discovery::discovery_manager::*; 4 | 5 | pub struct FakeAdapter; 6 | 7 | impl DiscoveryAdapter for FakeAdapter { 8 | fn start_discovery( 9 | &self, 10 | service_type: &str, 11 | listeners: DiscoveryListeners, 12 | ) -> Result<(), Error> { 13 | FakeAdapter::print_warning(); 14 | 15 | if listeners.on_service_discovered.is_some() { 16 | (*listeners.on_service_discovered.unwrap())(ServiceInfo { 17 | address: None, 18 | domain: Some(format!("local")), 19 | host_name: None, 20 | interface: 1, 21 | name: Some(format!("fake")), 22 | port: 0, 23 | protocol: ServiceProtocol::IPv4, 24 | txt: None, 25 | type_name: Some(service_type.to_string()), 26 | }); 27 | } 28 | 29 | if listeners.on_all_discovered.is_some() { 30 | (*listeners.on_all_discovered.unwrap())(); 31 | } 32 | 33 | Ok(()) 34 | } 35 | 36 | fn resolve(&self, service: ServiceInfo, listeners: ResolveListeners) { 37 | let service = ServiceInfo { 38 | address: Some(format!("192.168.1.1")), 39 | domain: service.domain, 40 | host_name: Some(format!("fake.local")), 41 | interface: service.interface, 42 | name: service.name, 43 | port: 80, 44 | protocol: service.protocol, 45 | txt: Some(format!("\"model=Xserve\"")), 46 | type_name: service.type_name, 47 | }; 48 | 49 | if listeners.on_service_resolved.is_some() { 50 | (*listeners.on_service_resolved.unwrap())(service); 51 | } 52 | } 53 | 54 | fn stop_discovery(&self) {} 55 | } 56 | 57 | impl HostAdapter for FakeAdapter { 58 | fn get_name(&self) -> Result { 59 | FakeAdapter::print_warning(); 60 | return Ok("fake".to_owned()); 61 | } 62 | 63 | fn get_name_fqdn(&self) -> Result { 64 | return Ok("fake.local".to_owned()); 65 | } 66 | 67 | fn set_name(&self, host_name: &str) -> Result { 68 | FakeAdapter::print_warning(); 69 | Ok(host_name.to_owned()) 70 | } 71 | 72 | fn is_valid_name(&self, host_name: &str) -> Result { 73 | FakeAdapter::print_warning(); 74 | debug!("Verifying host name: {}.", host_name); 75 | Ok(true) 76 | } 77 | 78 | fn get_alternative_name(&self, host_name: &str) -> Result { 79 | FakeAdapter::print_warning(); 80 | Ok(format!("{}-2", host_name)) 81 | } 82 | 83 | fn add_name_alias(&self, host_name: &str) -> Result<(), Error> { 84 | warn!( 85 | "Host name change request (-> {}) will be ignored.", 86 | host_name 87 | ); 88 | Ok(()) 89 | } 90 | 91 | fn announce_service(&self, service_name: &str, service_type: &str, port: u16) -> Result<(), Error> { 92 | FakeAdapter::print_warning(); 93 | Ok(()) 94 | } 95 | } 96 | 97 | impl Drop for FakeAdapter { 98 | fn drop(&mut self) { 99 | debug!("There is no need to do anything, just letting you know that I'm being dropped!"); 100 | } 101 | } 102 | 103 | impl Adapter for FakeAdapter { 104 | fn new() -> FakeAdapter { 105 | FakeAdapter::print_warning(); 106 | FakeAdapter 107 | } 108 | } 109 | 110 | impl FakeAdapter { 111 | fn print_warning() { 112 | println!( 113 | "WARNING: Your platform is not supported by real mDNS adapter, fake adapter is \ 114 | used!" 115 | ); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/bindings/avahi/enums.rs: -------------------------------------------------------------------------------- 1 | #[repr(C)] 2 | #[allow(dead_code, non_camel_case_types)] 3 | pub enum AvahiClientFlags { 4 | /// Don't read user configuration. 5 | AVAHI_CLIENT_IGNORE_USER_CONFIG, 6 | 7 | /// Don't fail if the daemon is not available when avahi_client_new() is called, 8 | /// instead enter AVAHI_CLIENT_CONNECTING state and wait for the daemon to appear. 9 | AVAHI_CLIENT_NO_FAIL, 10 | } 11 | 12 | #[repr(C)] 13 | #[allow(dead_code, non_camel_case_types)] 14 | #[derive(Debug)] 15 | pub enum AvahiClientState { 16 | AVAHI_CLIENT_S_REGISTERING = 1, 17 | AVAHI_CLIENT_S_RUNNING = 2, 18 | AVAHI_CLIENT_S_COLLISION = 3, 19 | AVAHI_CLIENT_FAILURE = 100, 20 | AVAHI_CLIENT_CONNECTING = 101, 21 | } 22 | 23 | #[repr(C)] 24 | #[allow(dead_code, non_camel_case_types)] 25 | pub enum AvahiLookupFlags { 26 | AVAHI_LOOKUP_UNSPEC = 0, 27 | /// When doing service resolving, don't lookup TXT record. 28 | AVAHI_LOOKUP_NO_TXT, 29 | 30 | /// When doing service resolving, don't lookup A/AAAA record. 31 | AVAHI_LOOKUP_NO_ADDRESS, 32 | } 33 | 34 | #[repr(C)] 35 | #[allow(dead_code, non_camel_case_types)] 36 | #[derive(Debug)] 37 | pub enum AvahiLookupResultFlags { 38 | AVAHI_LOOKUP_RESULT_CACHED, 39 | AVAHI_LOOKUP_RESULT_WIDE_AREA, 40 | AVAHI_LOOKUP_RESULT_MULTICAST, 41 | AVAHI_LOOKUP_RESULT_LOCAL, 42 | AVAHI_LOOKUP_RESULT_OUR_OWN, 43 | AVAHI_LOOKUP_RESULT_STATIC, 44 | } 45 | 46 | #[repr(C)] 47 | #[derive(Debug)] 48 | #[allow(dead_code, non_camel_case_types)] 49 | pub enum AvahiBrowserEvent { 50 | AVAHI_BROWSER_NEW, 51 | AVAHI_BROWSER_REMOVE, 52 | AVAHI_BROWSER_CACHE_EXHAUSTED, 53 | AVAHI_BROWSER_ALL_FOR_NOW, 54 | AVAHI_BROWSER_FAILURE, 55 | } 56 | 57 | #[repr(C)] 58 | #[derive(Clone, Copy, Debug)] 59 | #[allow(dead_code, non_camel_case_types)] 60 | pub enum AvahiProtocol { 61 | /// IPv4. 62 | AVAHI_PROTO_INET = 0, 63 | 64 | /// IPv6. 65 | AVAHI_PROTO_INET6 = 1, 66 | 67 | /// Unspecified/all protocol(s). 68 | AVAHI_PROTO_UNSPEC = -1, 69 | } 70 | 71 | #[repr(C)] 72 | #[allow(dead_code, non_camel_case_types)] 73 | pub enum AvahiIfIndex { 74 | /// Dummy variant to overcome [E0083]. 75 | DUMMY = 0, 76 | /// Unspecified/all interface(s). 77 | AVAHI_IF_UNSPEC = -1, 78 | } 79 | 80 | #[repr(C)] 81 | #[allow(dead_code, non_camel_case_types)] 82 | #[derive(Debug)] 83 | pub enum AvahiResolverEvent { 84 | AVAHI_RESOLVER_FOUND, 85 | AVAHI_RESOLVER_FAILURE, 86 | } 87 | 88 | #[repr(C)] 89 | #[allow(dead_code, non_camel_case_types)] 90 | pub enum AvahiDomainBrowserType { 91 | /// Browse for a list of available browsing domains. 92 | AVAHI_DOMAIN_BROWSER_BROWSE, 93 | 94 | /// Browse for the default browsing domain. 95 | AVAHI_DOMAIN_BROWSER_BROWSE_DEFAULT, 96 | 97 | /// Browse for a list of available registering domains. 98 | AVAHI_DOMAIN_BROWSER_REGISTER, 99 | 100 | /// Browse for the default registering domain. 101 | AVAHI_DOMAIN_BROWSER_REGISTER_DEFAULT, 102 | 103 | /// Legacy browse domain - see DNS-SD spec for more information. 104 | AVAHI_DOMAIN_BROWSER_BROWSE_LEGACY, 105 | 106 | AVAHI_DOMAIN_BROWSER_MAX, 107 | } 108 | 109 | #[repr(C)] 110 | #[allow(dead_code, non_camel_case_types)] 111 | #[derive(Clone, Copy, Debug)] 112 | pub enum AvahiEntryGroupState { 113 | AVAHI_ENTRY_GROUP_UNCOMMITED, 114 | AVAHI_ENTRY_GROUP_REGISTERING, 115 | AVAHI_ENTRY_GROUP_ESTABLISHED, 116 | AVAHI_ENTRY_GROUP_COLLISION, 117 | AVAHI_ENTRY_GROUP_FAILURE, 118 | } 119 | 120 | #[repr(C)] 121 | #[allow(dead_code, non_camel_case_types)] 122 | #[derive(Debug)] 123 | pub enum AvahiPublishFlags { 124 | AVAHI_PUBLISH_UNIQUE = 1, 125 | AVAHI_PUBLISH_NO_PROBE = 2, 126 | AVAHI_PUBLISH_NO_ANNOUNCE = 4, 127 | AVAHI_PUBLISH_ALLOW_MULTIPLE = 8, 128 | AVAHI_PUBLISH_NO_REVERSE = 16, 129 | AVAHI_PUBLISH_NO_COOKIE = 32, 130 | AVAHI_PUBLISH_UPDATE = 64, 131 | AVAHI_PUBLISH_USE_WIDE_AREA = 128, 132 | AVAHI_PUBLISH_USE_MULTICAST = 256, 133 | } 134 | 135 | #[repr(C)] 136 | #[allow(dead_code, non_camel_case_types)] 137 | #[derive(Debug)] 138 | pub enum AvahiRecordClass { 139 | AVAHI_IN = 1, 140 | } 141 | 142 | #[repr(C)] 143 | #[allow(dead_code, non_camel_case_types)] 144 | #[derive(Debug)] 145 | pub enum AvahiRecordType { 146 | AVAHI_A = 1, 147 | AVAHI_NS = 2, 148 | AVAHI_CNAME = 5, 149 | AVAHI_SOA = 6, 150 | AVAHI_PTR = 12, 151 | AVAHI_HINFO = 13, 152 | AVAHI_MX = 15, 153 | AVAHI_TXT = 16, 154 | AVAHI_AAA = 28, 155 | AVAHI_SRV = 33, 156 | } 157 | -------------------------------------------------------------------------------- /src/adapters/avahi/callbacks.rs: -------------------------------------------------------------------------------- 1 | use libc::{c_char, c_int, c_void}; 2 | 3 | use std::sync::mpsc; 4 | 5 | use bindings::avahi::*; 6 | 7 | use adapters::avahi::utils::*; 8 | 9 | pub struct AvahiCallbacks; 10 | 11 | #[derive(Debug)] 12 | pub struct ClientCallbackParameters { 13 | pub state: AvahiClientState, 14 | } 15 | 16 | #[derive(Debug)] 17 | pub struct BrowseCallbackParameters { 18 | pub event: AvahiBrowserEvent, 19 | pub interface: i32, 20 | pub protocol: AvahiProtocol, 21 | pub name: Option, 22 | pub service_type: Option, 23 | pub domain: Option, 24 | pub flags: AvahiLookupResultFlags, 25 | } 26 | 27 | #[derive(Debug)] 28 | pub struct ResolveCallbackParameters { 29 | pub event: AvahiResolverEvent, 30 | pub address: Option, 31 | pub interface: i32, 32 | pub port: u16, 33 | pub protocol: AvahiProtocol, 34 | pub name: Option, 35 | pub service_type: Option, 36 | pub domain: Option, 37 | pub host_name: Option, 38 | pub txt: Option, 39 | pub flags: AvahiLookupResultFlags, 40 | } 41 | 42 | impl AvahiCallbacks { 43 | #[allow(unused_variables)] 44 | pub extern "C" fn client_callback( 45 | client: *const AvahiClient, 46 | state: AvahiClientState, 47 | userdata: *const c_void, 48 | ) { 49 | let parameters = ClientCallbackParameters { state }; 50 | 51 | debug!("Client state has changed: {:?}.", parameters); 52 | 53 | let sender: Box> = 54 | unsafe { Box::from_raw(userdata as *mut _) }; 55 | 56 | sender.send(parameters).unwrap(); 57 | 58 | // Leak pointer to the sender so that it can be reused later. 59 | Box::into_raw(sender); 60 | } 61 | 62 | #[allow(unused_variables)] 63 | pub extern "C" fn browse_callback( 64 | service_browser: *const AvahiServiceBrowser, 65 | interface: c_int, 66 | protocol: AvahiProtocol, 67 | event: AvahiBrowserEvent, 68 | name: *const c_char, 69 | service_type: *const c_char, 70 | domain: *const c_char, 71 | flags: AvahiLookupResultFlags, 72 | userdata: *const c_void, 73 | ) { 74 | let parameters = BrowseCallbackParameters { 75 | event, 76 | interface, 77 | protocol, 78 | name: AvahiUtils::to_owned_string(name), 79 | service_type: AvahiUtils::to_owned_string(service_type), 80 | domain: AvahiUtils::to_owned_string(domain), 81 | flags, 82 | }; 83 | 84 | debug!("Service state has changed: {:?}.", parameters); 85 | 86 | let sender: Box>> = 87 | unsafe { Box::from_raw(userdata as *mut _) }; 88 | 89 | sender.send(Some(parameters)).unwrap(); 90 | 91 | // Leak pointer to the sender so that it can be reused later. 92 | Box::into_raw(sender); 93 | } 94 | 95 | #[allow(unused_variables)] 96 | pub extern "C" fn resolve_callback( 97 | r: *const AvahiServiceResolver, 98 | interface: c_int, 99 | protocol: AvahiProtocol, 100 | event: AvahiResolverEvent, 101 | name: *const c_char, 102 | service_type: *const c_char, 103 | domain: *const c_char, 104 | host_name: *const c_char, 105 | address: *const AvahiAddress, 106 | port: u16, 107 | txt: *mut AvahiStringList, 108 | flags: AvahiLookupResultFlags, 109 | userdata: *const c_void, 110 | ) { 111 | let parameters = ResolveCallbackParameters { 112 | event, 113 | address: AvahiUtils::parse_address(address), 114 | interface, 115 | protocol, 116 | port, 117 | host_name: AvahiUtils::to_owned_string(host_name), 118 | name: AvahiUtils::to_owned_string(name), 119 | service_type: AvahiUtils::to_owned_string(service_type), 120 | domain: AvahiUtils::to_owned_string(domain), 121 | txt: AvahiUtils::parse_txt(txt), 122 | flags, 123 | }; 124 | 125 | debug!("Service resolution state has changed: {:?}.", parameters); 126 | 127 | let sender: Box> = 128 | unsafe { Box::from_raw(userdata as *mut _) }; 129 | 130 | sender.send(parameters).unwrap(); 131 | } 132 | 133 | #[allow(unused_variables)] 134 | pub extern "C" fn entry_group_callback( 135 | group: *const AvahiEntryGroup, 136 | state: AvahiEntryGroupState, 137 | userdata: *const c_void, 138 | ) { 139 | debug!("Entry group state has changed to {:?}.", state); 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /src/adapters/avahi/errors.rs: -------------------------------------------------------------------------------- 1 | use std::error::Error as StdError; 2 | use std::fmt::{Display, Formatter}; 3 | 4 | use adapters::avahi::utils::*; 5 | use bindings::avahi::*; 6 | 7 | #[derive(Debug)] 8 | pub enum Error { 9 | Failure(i32, String), 10 | BadState(i32, String), 11 | InvalidHostName(i32, String), 12 | InvalidDomainName(i32, String), 13 | NoNetwork(i32, String), 14 | InvalidTTL(i32, String), 15 | IsPattern(i32, String), 16 | Collision(i32, String), 17 | InvalidRecord(i32, String), 18 | InvalidServiceName(i32, String), 19 | InvalidServiceType(i32, String), 20 | InvalidPort(i32, String), 21 | InvalidKey(i32, String), 22 | InvalidAddress(i32, String), 23 | Timeout(i32, String), 24 | TooManyClients(i32, String), 25 | TooManyObjects(i32, String), 26 | TooManyEntries(i32, String), 27 | OS(i32, String), 28 | AccessDenied(i32, String), 29 | InvalidOperation(i32, String), 30 | DBusError(i32, String), 31 | Disconnected(i32, String), 32 | NoMemory(i32, String), 33 | InvalidObject(i32, String), 34 | NoDaemon(i32, String), 35 | InvalidInterface(i32, String), 36 | InvalidProtocol(i32, String), 37 | InvalidFlags(i32, String), 38 | NotFound(i32, String), 39 | InvalidConfig(i32, String), 40 | VersionMismatch(i32, String), 41 | InvalidServiceSubType(i32, String), 42 | InvalidPacket(i32, String), 43 | InvalidDnsError(i32, String), 44 | DnsFormError(i32, String), 45 | DnsServiceFail(i32, String), 46 | DnsNxDomain(i32, String), 47 | DnsNotImp(i32, String), 48 | DnsRefused(i32, String), 49 | DnsYxDomain(i32, String), 50 | DnsYxRrSet(i32, String), 51 | DnsNxRrSet(i32, String), 52 | DnsNotAuth(i32, String), 53 | DnsNotZone(i32, String), 54 | InvalidRData(i32, String), 55 | InvalidDnsClass(i32, String), 56 | InvalidDnsType(i32, String), 57 | NotSupported(i32, String), 58 | NotPermitted(i32, String), 59 | InvalidArgument(i32, String), 60 | IsEmpty(i32, String), 61 | NoChange(i32, String), 62 | Max(i32, String), 63 | Unknown(i32, String), 64 | } 65 | 66 | impl Display for Error { 67 | fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> { 68 | f.write_str(match *self { 69 | Error::Failure(_, ref message) => message, 70 | Error::BadState(_, ref message) => message, 71 | Error::InvalidHostName(_, ref message) => message, 72 | Error::InvalidDomainName(_, ref message) => message, 73 | Error::NoNetwork(_, ref message) => message, 74 | Error::InvalidTTL(_, ref message) => message, 75 | Error::IsPattern(_, ref message) => message, 76 | Error::Collision(_, ref message) => message, 77 | Error::InvalidRecord(_, ref message) => message, 78 | Error::InvalidServiceName(_, ref message) => message, 79 | Error::InvalidServiceType(_, ref message) => message, 80 | Error::InvalidPort(_, ref message) => message, 81 | Error::InvalidKey(_, ref message) => message, 82 | Error::InvalidAddress(_, ref message) => message, 83 | Error::Timeout(_, ref message) => message, 84 | Error::TooManyClients(_, ref message) => message, 85 | Error::TooManyObjects(_, ref message) => message, 86 | Error::TooManyEntries(_, ref message) => message, 87 | Error::OS(_, ref message) => message, 88 | Error::AccessDenied(_, ref message) => message, 89 | Error::InvalidOperation(_, ref message) => message, 90 | Error::DBusError(_, ref message) => message, 91 | Error::Disconnected(_, ref message) => message, 92 | Error::NoMemory(_, ref message) => message, 93 | Error::InvalidObject(_, ref message) => message, 94 | Error::NoDaemon(_, ref message) => message, 95 | Error::InvalidInterface(_, ref message) => message, 96 | Error::InvalidProtocol(_, ref message) => message, 97 | Error::InvalidFlags(_, ref message) => message, 98 | Error::NotFound(_, ref message) => message, 99 | Error::InvalidConfig(_, ref message) => message, 100 | Error::VersionMismatch(_, ref message) => message, 101 | Error::InvalidServiceSubType(_, ref message) => message, 102 | Error::InvalidPacket(_, ref message) => message, 103 | Error::InvalidDnsError(_, ref message) => message, 104 | Error::DnsFormError(_, ref message) => message, 105 | Error::DnsServiceFail(_, ref message) => message, 106 | Error::DnsNxDomain(_, ref message) => message, 107 | Error::DnsNotImp(_, ref message) => message, 108 | Error::DnsRefused(_, ref message) => message, 109 | Error::DnsYxDomain(_, ref message) => message, 110 | Error::DnsYxRrSet(_, ref message) => message, 111 | Error::DnsNxRrSet(_, ref message) => message, 112 | Error::DnsNotAuth(_, ref message) => message, 113 | Error::DnsNotZone(_, ref message) => message, 114 | Error::InvalidRData(_, ref message) => message, 115 | Error::InvalidDnsClass(_, ref message) => message, 116 | Error::InvalidDnsType(_, ref message) => message, 117 | Error::NotSupported(_, ref message) => message, 118 | Error::NotPermitted(_, ref message) => message, 119 | Error::InvalidArgument(_, ref message) => message, 120 | Error::IsEmpty(_, ref message) => message, 121 | Error::NoChange(_, ref message) => message, 122 | Error::Max(_, ref message) => message, 123 | Error::Unknown(_, ref message) => message, 124 | }) 125 | } 126 | } 127 | 128 | impl StdError for Error { 129 | fn cause(&self) -> Option<&dyn StdError> { 130 | None 131 | } 132 | } 133 | 134 | impl Error { 135 | pub fn from_error_code(error_code: i32) -> Error { 136 | let error_string = AvahiUtils::to_owned_string(unsafe { avahi_strerror(error_code) }) 137 | .unwrap_or_else(|| "Description is not available.".to_owned()); 138 | 139 | match error_code { 140 | -1 => Error::Failure(error_code, error_string), 141 | -2 => Error::BadState(error_code, error_string), 142 | -3 => Error::InvalidHostName(error_code, error_string), 143 | -4 => Error::InvalidDomainName(error_code, error_string), 144 | -5 => Error::NoNetwork(error_code, error_string), 145 | -6 => Error::InvalidTTL(error_code, error_string), 146 | -7 => Error::IsPattern(error_code, error_string), 147 | -8 => Error::Collision(error_code, error_string), 148 | -9 => Error::InvalidRecord(error_code, error_string), 149 | -10 => Error::InvalidServiceName(error_code, error_string), 150 | -11 => Error::InvalidServiceType(error_code, error_string), 151 | -12 => Error::InvalidPort(error_code, error_string), 152 | -13 => Error::InvalidKey(error_code, error_string), 153 | -14 => Error::InvalidAddress(error_code, error_string), 154 | -15 => Error::Timeout(error_code, error_string), 155 | -16 => Error::TooManyClients(error_code, error_string), 156 | -17 => Error::TooManyObjects(error_code, error_string), 157 | -18 => Error::TooManyEntries(error_code, error_string), 158 | -19 => Error::OS(error_code, error_string), 159 | -20 => Error::AccessDenied(error_code, error_string), 160 | -21 => Error::InvalidOperation(error_code, error_string), 161 | -22 => Error::DBusError(error_code, error_string), 162 | -23 => Error::Disconnected(error_code, error_string), 163 | -24 => Error::NoMemory(error_code, error_string), 164 | -25 => Error::InvalidObject(error_code, error_string), 165 | -26 => Error::NoDaemon(error_code, error_string), 166 | -27 => Error::InvalidInterface(error_code, error_string), 167 | -28 => Error::InvalidProtocol(error_code, error_string), 168 | -29 => Error::InvalidFlags(error_code, error_string), 169 | -30 => Error::NotFound(error_code, error_string), 170 | -31 => Error::InvalidConfig(error_code, error_string), 171 | -32 => Error::VersionMismatch(error_code, error_string), 172 | -33 => Error::InvalidServiceSubType(error_code, error_string), 173 | -34 => Error::InvalidPacket(error_code, error_string), 174 | -35 => Error::InvalidDnsError(error_code, error_string), 175 | -36 => Error::DnsFormError(error_code, error_string), 176 | -37 => Error::DnsServiceFail(error_code, error_string), 177 | -38 => Error::DnsNxDomain(error_code, error_string), 178 | -39 => Error::DnsNotImp(error_code, error_string), 179 | -40 => Error::DnsRefused(error_code, error_string), 180 | -41 => Error::DnsYxDomain(error_code, error_string), 181 | -42 => Error::DnsYxRrSet(error_code, error_string), 182 | -43 => Error::DnsNxRrSet(error_code, error_string), 183 | -44 => Error::DnsNotAuth(error_code, error_string), 184 | -45 => Error::DnsNotZone(error_code, error_string), 185 | -46 => Error::InvalidRData(error_code, error_string), 186 | -47 => Error::InvalidDnsClass(error_code, error_string), 187 | -48 => Error::InvalidDnsType(error_code, error_string), 188 | -49 => Error::NotSupported(error_code, error_string), 189 | -50 => Error::NotPermitted(error_code, error_string), 190 | -51 => Error::InvalidArgument(error_code, error_string), 191 | -52 => Error::IsEmpty(error_code, error_string), 192 | -53 => Error::NoChange(error_code, error_string), 193 | -54 => Error::Max(error_code, error_string), 194 | _ => Error::Unknown(error_code, error_string), 195 | } 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /src/bindings/avahi/functions.rs: -------------------------------------------------------------------------------- 1 | use super::enums::*; 2 | use super::types::*; 3 | use libc::{c_char, c_int, c_void, size_t}; 4 | 5 | #[link(name = "avahi-common")] 6 | #[link(name = "avahi-client")] 7 | #[link(name = "dbus-1")] 8 | #[allow(improper_ctypes, dead_code)] 9 | extern "C" { 10 | /// Create a new main loop object. 11 | /// 12 | /// # Return value 13 | /// 14 | /// Main loop object - `AvahiSimplePoll`. 15 | pub fn avahi_simple_poll_new() -> *mut AvahiSimplePoll; 16 | 17 | /// Return the abstracted poll API object for this main loop object. 18 | /// The is will return the same pointer each time it is called. 19 | /// 20 | /// # Arguments 21 | /// 22 | /// * `simple_poll` - Main loop object returned from `avahi_simple_poll_new`. 23 | /// 24 | /// # Return value 25 | /// 26 | /// Abstracted poll API object - `AvahiPoll`. 27 | pub fn avahi_simple_poll_get(simple_poll: *mut AvahiSimplePoll) -> *mut AvahiPoll; 28 | 29 | /// Call `avahi_simple_poll_iterate` in a loop and return if it 30 | /// returns non-zero. 31 | /// 32 | /// # Arguments 33 | /// 34 | /// * `simple_poll` - Main loop object returned from `avahi_simple_poll_new`. 35 | /// 36 | /// # Return value 37 | /// 38 | /// Non-zero if `avahi_simple_poll_iterate` return non-zero value. 39 | pub fn avahi_simple_poll_loop(simple_poll: *mut AvahiSimplePoll) -> c_int; 40 | 41 | /// Free a main loop object. 42 | /// 43 | /// # Arguments 44 | /// 45 | /// * `simple_poll` - Main loop object returned from `avahi_simple_poll_new`. 46 | pub fn avahi_simple_poll_free(simple_poll: *mut AvahiSimplePoll); 47 | 48 | /// Creates a new client instance. 49 | /// 50 | /// # Arguments 51 | /// * `poll_api` - The abstract event loop API to use. 52 | /// * `flags` - Some flags to modify the behaviour of the client library. 53 | /// * `callback` - A callback that is called whenever the state of the client changes. 54 | /// This may be NULL. Please note that this function is called for the 55 | /// first time from within the avahi_client_new() context! Thus, in the 56 | /// callback you should not make use of global variables that are initialized 57 | /// only after your call to avahi_client_new(). A common mistake is to store 58 | /// the AvahiClient pointer returned by avahi_client_new() in a global 59 | /// variable and assume that this global variable already contains the valid 60 | /// pointer when the callback is called for the first time. A work-around for 61 | /// this is to always use the AvahiClient pointer passed to the callback 62 | /// function instead of the global pointer. 63 | /// * `userdata` - Some arbitrary user data pointer that will be passed to the callback. 64 | /// * `error` - If creation of the client fails, this integer will contain the error cause. 65 | /// May be NULL if you aren't interested in the reason why `avahi_client_new()` 66 | /// has failed. 67 | /// 68 | /// # Return value 69 | /// 70 | /// New client instance - `AvahiClient`. 71 | pub fn avahi_client_new( 72 | poll_api: *const AvahiPoll, 73 | flags: AvahiClientFlags, 74 | callback: ClientCallback, 75 | userdata: *mut c_void, 76 | error: *mut c_int, 77 | ) -> *mut AvahiClient; 78 | 79 | /// Free a client instance. 80 | /// This will automatically free all associated browser, resolve and entry group objects. 81 | /// All pointers to such objects become invalid! 82 | /// 83 | /// # Arguments 84 | /// 85 | /// * `client` - Active `AvahiClient` instance. 86 | pub fn avahi_client_free(client: *mut AvahiClient); 87 | 88 | pub fn avahi_client_get_host_name(client: *mut AvahiClient) -> *const c_char; 89 | 90 | pub fn avahi_client_set_host_name(client: *mut AvahiClient, name: *const c_char) -> c_int; 91 | 92 | pub fn avahi_client_get_host_name_fqdn(client: *mut AvahiClient) -> *const c_char; 93 | 94 | pub fn avahi_client_get_state(client: *mut AvahiClient) -> AvahiClientState; 95 | 96 | /// Get the last error number. 97 | /// See avahi_strerror() for converting this error code into a human readable string. 98 | /// 99 | /// # Arguments 100 | /// 101 | /// * `client` - Active `AvahiClient` instance. 102 | /// 103 | /// # Return value 104 | /// 105 | /// Non-zero error code if any. 106 | pub fn avahi_client_errno(client: *const AvahiClient) -> c_int; 107 | 108 | pub fn avahi_is_valid_host_name(host_name: *const c_char) -> c_int; 109 | 110 | pub fn avahi_alternative_host_name(host_name: *const c_char) -> *const c_char; 111 | 112 | /// Browse for domains on the local network. 113 | /// 114 | /// # Arguments 115 | /// 116 | /// * `client` - Active `AvahiClient` instance. 117 | /// * `interface` - Numeric network interface index. Takes OS dependent values and 118 | /// the special constant AVAHI_IF_UNSPEC (-1). 119 | /// * `protocol` - Protocol family specification `AvahiProtocol`. 120 | /// * `domain` - Domain to look for. 121 | /// * `service_type` - The type of domain to browse for `AvahiDomainBrowserType`. 122 | /// * `flags` - Flags for lookup functions `AvahiLookupFlags`. 123 | /// * `callback` - `AvahiDomainBrowserCallback` callback to be called for every new 124 | /// found service. 125 | /// * `userdata` - Some arbitrary user data pointer that will be passed to the callback. 126 | /// 127 | /// # Return value 128 | /// 129 | /// A domain browser `AvahiServiceBrowser` object. 130 | pub fn avahi_service_browser_new( 131 | client: *mut AvahiClient, 132 | interface: AvahiIfIndex, 133 | protocol: AvahiProtocol, 134 | service_type: *const c_char, 135 | domain: *const c_char, 136 | flags: AvahiLookupFlags, 137 | callback: ServiceBrowserCallback, 138 | userdata: *mut c_void, 139 | ) -> *mut AvahiServiceBrowser; 140 | 141 | /// Cleans up and frees an `AvahiServiceBrowser` object. 142 | /// 143 | /// # Arguments 144 | /// 145 | /// * `service_browser` - instance of `AvahiServiceBrowser`. 146 | pub fn avahi_service_browser_free(service_browser: *mut AvahiServiceBrowser) -> c_int; 147 | 148 | /// Create a new service resolver object. 149 | /// 150 | /// Please make sure to pass all the service data you received via 151 | /// `avahi_service_browser_new()` callback function, especially `interface` 152 | /// and `protocol`. 153 | /// 154 | /// # Arguments 155 | /// 156 | /// * `client` - Active `AvahiClient` instance. 157 | /// * `interface` - Interface argument received in `AvahiServiceBrowserCallback`. 158 | /// * `protocol` - The protocol argument specifies the protocol (IPv4 or IPv6) 159 | /// to use as transport for the queries which are sent out by this 160 | /// resolver. Generally, on `protocol` you should only pass what was 161 | /// supplied to you as parameter to your `AvahiServiceBrowserCallback`. 162 | /// Or, more technically speaking: protocol specifies if the mDNS 163 | /// queries should be sent as UDP/IPv4 resp. UDP/IPv6 packets. 164 | /// * `name` - Name argument received in `AvahiServiceBrowserCallback`. 165 | /// * `service_type` - Service type argument received in `AvahiServiceBrowserCallback`. 166 | /// * `domain` - Domain argument received in `AvahiServiceBrowserCallback`. 167 | /// * `aprotocol` - The `aprotocol` argument specifies the adress family 168 | /// (IPv4 or IPv6) of the address of the service we are looking for. 169 | /// In `aprotocol` you should pass what your application code can deal 170 | /// with when connecting to the service. Or, more technically speaking: 171 | /// `aprotocol` specifies whether the query is for a A resp. AAAA 172 | /// resource record. AVAHI_PROTO_UNSPEC if your application can deal 173 | /// with both IPv4 and IPv6 174 | /// * `flags` - Flags for lookup functions `AvahiLookupFlags`. 175 | /// * `callback` - `ServiceResolverCallback` callback to be called for every new 176 | /// resolved service. 177 | /// * `userdata` - Some arbitrary user data pointer that will be passed to the callback. 178 | /// 179 | /// # Return value 180 | /// 181 | /// A service resolver `AvahiServiceResolver` object. 182 | pub fn avahi_service_resolver_new( 183 | client: *mut AvahiClient, 184 | interface: c_int, 185 | protocol: AvahiProtocol, 186 | name: *const c_char, 187 | service_type: *const c_char, 188 | domain: *const c_char, 189 | aprotocol: AvahiProtocol, 190 | flags: AvahiLookupFlags, 191 | callback: ServiceResolverCallback, 192 | userdata: *mut c_void, 193 | ) -> *mut AvahiServiceResolver; 194 | 195 | pub fn avahi_service_resolver_free(resolver: *mut AvahiServiceResolver) -> c_int; 196 | 197 | pub fn avahi_address_snprint(ret_s: *const c_char, length: size_t, a: *const AvahiAddress); 198 | 199 | /// Convert the string list object to a single character string, seperated by spaces 200 | /// and enclosed in "". `avahi_free` should always be called for the result! 201 | /// This function doesn't work well with strings that contain NUL bytes. 202 | /// 203 | /// # Arguments 204 | /// 205 | /// * `string_list` - string list instance. 206 | /// 207 | /// # Return value 208 | /// 209 | /// Single character string, seperated by spaces and enclosed in "". 210 | pub fn avahi_string_list_to_string(string_list: *mut AvahiStringList) -> *const c_char; 211 | 212 | /// Free some memory. 213 | /// 214 | /// # Arguments 215 | /// 216 | /// * `pointer` - pointer to free memory for. 217 | pub fn avahi_free(pointer: *mut c_void); 218 | 219 | /// Return a human readable error string for the specified error code. 220 | /// 221 | /// # Arguments 222 | /// 223 | /// * `error` - Integer error code used by avahi. 224 | /// 225 | /// # Return value 226 | /// 227 | /// Human readable error string. 228 | pub fn avahi_strerror(error: c_int) -> *const c_char; 229 | 230 | /// Create a new main loop object (will be performed in a separate thread). 231 | /// 232 | /// # Return value 233 | /// 234 | /// Main loop object - `AvahiThreadedPoll`. 235 | pub fn avahi_threaded_poll_new() -> *mut AvahiThreadedPoll; 236 | 237 | /// Return the abstracted poll API object for this main loop object. 238 | /// The is will return the same pointer each time it is called. 239 | /// 240 | /// # Arguments 241 | /// 242 | /// * `threaded_poll` - Main loop object returned from `avahi_threaded_poll_new`. 243 | /// 244 | /// # Return value 245 | /// 246 | /// Abstracted poll API object - `AvahiPoll`. 247 | pub fn avahi_threaded_poll_get(threaded_poll: *mut AvahiThreadedPoll) -> *mut AvahiPoll; 248 | 249 | /// Start the event loop helper thread. 250 | /// 251 | /// After the thread has started you must make sure to access the event loop object 252 | /// (`AvahiThreadedPoll`, `AvahiPoll` and all its associated objects) synchronized, 253 | /// i.e. with proper locking. You may want to use `avahi_threaded_poll_lock` and 254 | /// `avahi_threaded_poll_unlock` for this, which will lock the the entire event loop. 255 | /// Please note that event loop callback functions are called from the event loop 256 | /// helper thread with that lock held, i.e. `avahi_threaded_poll_lock` calls are not 257 | /// required from event callbacks. 258 | /// 259 | /// # Arguments 260 | /// 261 | /// * `threaded_poll` - Main loop object returned from `avahi_threaded_poll_new`. 262 | pub fn avahi_threaded_poll_start(threaded_poll: *mut AvahiThreadedPoll) -> c_int; 263 | 264 | /// Request that the event loop quits and the associated thread stops. 265 | /// 266 | /// Call this from outside the helper thread if you want to shut it down. 267 | /// 268 | /// # Arguments 269 | /// 270 | /// * `threaded_poll` - Main loop object returned from `avahi_threaded_poll_new`. 271 | pub fn avahi_threaded_poll_stop(threaded_poll: *mut AvahiThreadedPoll) -> c_int; 272 | 273 | pub fn avahi_threaded_poll_quit(threaded_poll: *mut AvahiThreadedPoll) -> c_void; 274 | 275 | /// Free an event loop object. 276 | /// 277 | /// This will stop the associated event loop thread (if it is running). 278 | /// 279 | /// # Arguments 280 | /// 281 | /// * `threaded_poll` - Main loop object returned from `avahi_threaded_poll_new`. 282 | pub fn avahi_threaded_poll_free(threaded_poll: *mut AvahiThreadedPoll) -> c_void; 283 | 284 | pub fn avahi_entry_group_new( 285 | client: *mut AvahiClient, 286 | callback: AvahiEntryGroupCallback, 287 | userdata: *mut c_void, 288 | ) -> *mut AvahiEntryGroup; 289 | 290 | pub fn avahi_entry_group_add_record( 291 | group: *mut AvahiEntryGroup, 292 | interface: c_int, 293 | protocol: AvahiProtocol, 294 | flags: AvahiPublishFlags, 295 | name: *const c_char, 296 | record_class: AvahiRecordClass, 297 | record_type: AvahiRecordType, 298 | ttl: u32, 299 | rdata: *const c_void, 300 | size: usize, 301 | ) -> c_int; 302 | 303 | pub fn avahi_entry_group_add_service( 304 | group: *mut AvahiEntryGroup, 305 | interface: AvahiIfIndex, 306 | protocol: AvahiProtocol, 307 | flags: AvahiPublishFlags, 308 | name: *const c_char, 309 | record_type: *const c_char, 310 | domain: *const c_char, 311 | host: *const c_char, 312 | port: u16, 313 | text: *const c_void, 314 | ) -> c_int; 315 | 316 | pub fn avahi_entry_group_commit(group: *mut AvahiEntryGroup) -> c_int; 317 | 318 | pub fn avahi_entry_group_get_state(group: *mut AvahiEntryGroup) -> c_int; 319 | } 320 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /src/adapters/avahi/adapter.rs: -------------------------------------------------------------------------------- 1 | use std::cell::Cell; 2 | use std::ffi::CString; 3 | use std::ptr; 4 | use std::sync::mpsc; 5 | 6 | use libc::c_void; 7 | 8 | use bindings::avahi::*; 9 | use discovery::discovery_manager::*; 10 | 11 | use adapters::adapter::*; 12 | use adapters::avahi::callbacks::*; 13 | use adapters::avahi::errors::Error as AvahiError; 14 | use adapters::avahi::utils::*; 15 | use adapters::errors::Error as AdapterError; 16 | 17 | pub struct Channel { 18 | pub receiver: mpsc::Receiver, 19 | pub sender: mpsc::Sender, 20 | } 21 | 22 | pub struct AvahiAdapter { 23 | poll: Cell>, 24 | 25 | client: Cell>, 26 | client_channel: Channel, 27 | 28 | service_browser: Cell>, 29 | service_browser_channel: Channel>, 30 | } 31 | 32 | fn avahi_protocol_to_service_protocol(protocol: AvahiProtocol) -> ServiceProtocol { 33 | match protocol { 34 | AvahiProtocol::AVAHI_PROTO_INET => ServiceProtocol::IPv4, 35 | AvahiProtocol::AVAHI_PROTO_INET6 => ServiceProtocol::IPv6, 36 | AvahiProtocol::AVAHI_PROTO_UNSPEC => ServiceProtocol::Unspecified, 37 | } 38 | } 39 | 40 | fn service_protocol_to_avahi_protocol(protocol: ServiceProtocol) -> AvahiProtocol { 41 | match protocol { 42 | ServiceProtocol::IPv4 => AvahiProtocol::AVAHI_PROTO_INET, 43 | ServiceProtocol::IPv6 => AvahiProtocol::AVAHI_PROTO_INET6, 44 | ServiceProtocol::Unspecified => AvahiProtocol::AVAHI_PROTO_UNSPEC, 45 | } 46 | } 47 | 48 | fn name_fqdn_to_cname_rdata(name_fqdn: &str) -> Vec { 49 | let mut rdata: Vec = Vec::new(); 50 | 51 | for part in name_fqdn.split('.') { 52 | rdata.push(part.len() as u8); 53 | rdata.extend_from_slice(part.as_bytes()); 54 | } 55 | 56 | // Push NULL byte. 57 | rdata.push(0); 58 | 59 | rdata 60 | } 61 | 62 | impl AvahiAdapter { 63 | /// Creates `AvahiClient` instance for the provided `AvahiPoll` object. If there 64 | /// was an error while creating client, corresponding error will be returned. 65 | /// 66 | /// # Arguments 67 | /// 68 | /// * `poll` - Abstracted `AvahiPoll` object that we'd like to create client for. 69 | fn create_client(&self, poll: *mut AvahiPoll) -> Result<(), AvahiError> { 70 | let mut client_error_code: i32 = 0; 71 | 72 | let sender = Box::new(self.client_channel.sender.clone()); 73 | let avahi_client = unsafe { 74 | avahi_client_new( 75 | poll, 76 | AvahiClientFlags::AVAHI_CLIENT_IGNORE_USER_CONFIG, 77 | *Box::new(AvahiCallbacks::client_callback), 78 | Box::into_raw(sender) as *mut _ as *mut c_void, 79 | &mut client_error_code, 80 | ) 81 | }; 82 | 83 | // Check that we've created client successfully, otherwise try to resolve error 84 | // into human-readable string. 85 | if client_error_code != 0 || avahi_client.is_null() { 86 | return Err(AvahiError::from_error_code(client_error_code)); 87 | } 88 | 89 | for message in self.client_channel.receiver.iter() { 90 | if let AvahiClientState::AVAHI_CLIENT_S_RUNNING = message.state { 91 | break; 92 | } 93 | } 94 | 95 | self.client.set(Some(avahi_client)); 96 | 97 | debug!("Client is created."); 98 | Ok(()) 99 | } 100 | 101 | /// Initializes `AvahiClient` and `AvahiPoll` objects and runs polling. If client 102 | /// has been already initialized, this method does nothing. 103 | fn initialize(&self) -> Result<(), AvahiError> { 104 | if self.client.get().is_some() { 105 | return Ok(()); 106 | } 107 | 108 | debug!("New client initialization is requested."); 109 | 110 | // AvahiClient works with abstracted poll object only, so we need both threaded 111 | // and abstracted polls. 112 | let (threaded_poll, abstracted_poll) = unsafe { 113 | let threaded_poll = avahi_threaded_poll_new(); 114 | (threaded_poll, avahi_threaded_poll_get(threaded_poll)) 115 | }; 116 | 117 | debug!("Threaded poll is created."); 118 | 119 | self.create_client(abstracted_poll)?; 120 | 121 | let result_code = unsafe { avahi_threaded_poll_start(threaded_poll) }; 122 | if result_code != 0 { 123 | return Err(AvahiError::from_error_code(result_code)); 124 | } 125 | 126 | self.poll.set(Some(threaded_poll)); 127 | 128 | Ok(()) 129 | } 130 | 131 | fn destroy(&self) { 132 | debug!("Avahi adapter is going to be dropped."); 133 | 134 | let client = self.client.get(); 135 | if client.is_some() { 136 | let avahi_poll = self.poll.get().unwrap(); 137 | let avahi_client = client.unwrap(); 138 | 139 | unsafe { 140 | avahi_threaded_poll_stop(avahi_poll); 141 | debug!("Avahi threaded poll has been stopped successfully."); 142 | 143 | // Free memory from our custom userdata. 144 | Box::from_raw((*avahi_client).userdata); 145 | 146 | // This will remove service browser as well as resolver. 147 | avahi_client_free(avahi_client); 148 | debug!("Avahi client has been destroyed successfully."); 149 | 150 | avahi_threaded_poll_free(avahi_poll); 151 | debug!("Avahi threaded poll has been destroyed successfully."); 152 | } 153 | 154 | self.poll.set(None); 155 | self.client.set(None); 156 | self.service_browser.set(None); 157 | 158 | debug!("Avahi adapter has been dropped successfully."); 159 | } 160 | } 161 | } 162 | 163 | impl DiscoveryAdapter for AvahiAdapter { 164 | fn start_discovery( 165 | &self, 166 | service_type: &str, 167 | listeners: DiscoveryListeners, 168 | ) -> Result<(), AdapterError> { 169 | debug!("Discovery started for the service: {}.", service_type); 170 | 171 | self.initialize()?; 172 | 173 | let service_type = AvahiUtils::to_c_string(service_type.to_owned()).into_raw(); 174 | let sender = Box::new(self.service_browser_channel.sender.clone()); 175 | 176 | let avahi_service_browser = unsafe { 177 | avahi_service_browser_new( 178 | self.client.get().unwrap(), 179 | AvahiIfIndex::AVAHI_IF_UNSPEC, 180 | AvahiProtocol::AVAHI_PROTO_UNSPEC, 181 | service_type, 182 | ptr::null_mut(), 183 | AvahiLookupFlags::AVAHI_LOOKUP_UNSPEC, 184 | *Box::new(AvahiCallbacks::browse_callback), 185 | Box::into_raw(sender) as *mut _ as *mut c_void, 186 | ) 187 | }; 188 | 189 | self.service_browser.set(Some(avahi_service_browser)); 190 | 191 | for message in self.service_browser_channel.receiver.iter() { 192 | if message.is_none() { 193 | break; 194 | } 195 | 196 | let parameters = message.unwrap(); 197 | 198 | match parameters.event { 199 | AvahiBrowserEvent::AVAHI_BROWSER_NEW => { 200 | let service = ServiceInfo { 201 | address: None, 202 | domain: parameters.domain, 203 | host_name: None, 204 | interface: parameters.interface, 205 | name: parameters.name, 206 | port: 0, 207 | protocol: avahi_protocol_to_service_protocol(parameters.protocol), 208 | txt: None, 209 | type_name: parameters.service_type, 210 | }; 211 | 212 | if listeners.on_service_discovered.is_some() { 213 | (*listeners.on_service_discovered.unwrap())(service); 214 | } 215 | } 216 | AvahiBrowserEvent::AVAHI_BROWSER_ALL_FOR_NOW => { 217 | if listeners.on_all_discovered.is_some() { 218 | (*listeners.on_all_discovered.unwrap())(); 219 | } 220 | } 221 | AvahiBrowserEvent::AVAHI_BROWSER_FAILURE => { 222 | let error_code = unsafe { avahi_client_errno(self.client.get().unwrap()) }; 223 | error!( 224 | "Service browser failed: {}", 225 | AvahiError::from_error_code(error_code) 226 | ); 227 | } 228 | _ => {} 229 | } 230 | } 231 | 232 | // Reconstruct string to properly free up memory. 233 | unsafe { CString::from_raw(service_type) }; 234 | 235 | Ok(()) 236 | } 237 | 238 | fn resolve(&self, service: ServiceInfo, listeners: ResolveListeners) { 239 | debug!("Resolution is requested for service: {:?}.", service); 240 | 241 | let (tx, rx) = mpsc::channel::(); 242 | 243 | let avahi_service_resolver = unsafe { 244 | avahi_service_resolver_new( 245 | self.client.get().unwrap(), 246 | service.interface, 247 | service_protocol_to_avahi_protocol(service.protocol), 248 | AvahiUtils::to_c_string(service.name.unwrap()).as_ptr(), 249 | AvahiUtils::to_c_string(service.type_name.unwrap()).as_ptr(), 250 | AvahiUtils::to_c_string(service.domain.unwrap()).as_ptr(), 251 | AvahiProtocol::AVAHI_PROTO_UNSPEC, 252 | AvahiLookupFlags::AVAHI_LOOKUP_UNSPEC, 253 | *Box::new(AvahiCallbacks::resolve_callback), 254 | Box::into_raw(Box::new(tx)) as *mut _ as *mut c_void, 255 | ) 256 | }; 257 | 258 | for message in rx.iter() { 259 | if let AvahiResolverEvent::AVAHI_RESOLVER_FOUND = message.event { 260 | let service = ServiceInfo { 261 | address: message.address, 262 | domain: message.domain, 263 | host_name: message.host_name, 264 | interface: message.interface, 265 | name: message.name, 266 | port: message.port, 267 | protocol: avahi_protocol_to_service_protocol(message.protocol), 268 | txt: message.txt, 269 | type_name: message.service_type, 270 | }; 271 | 272 | if listeners.on_service_resolved.is_some() { 273 | (*listeners.on_service_resolved.unwrap())(service); 274 | } 275 | 276 | break; 277 | } 278 | } 279 | 280 | unsafe { 281 | avahi_service_resolver_free(avahi_service_resolver); 282 | } 283 | } 284 | 285 | fn stop_discovery(&self) { 286 | let service_browser = self.service_browser.get(); 287 | if service_browser.is_some() { 288 | let avahi_service_browser = service_browser.unwrap(); 289 | unsafe { 290 | // Free memory from our custom userdata. 291 | Box::from_raw((*avahi_service_browser).userdata); 292 | 293 | avahi_service_browser_free(avahi_service_browser); 294 | debug!("Avahi service browser has been destroyed successfully."); 295 | } 296 | 297 | self.service_browser.set(None); 298 | self.service_browser_channel.sender.send(None).unwrap(); 299 | } 300 | } 301 | } 302 | 303 | impl HostAdapter for AvahiAdapter { 304 | fn get_name(&self) -> Result { 305 | debug!("Host name is requested."); 306 | 307 | self.initialize()?; 308 | 309 | let host_name_ptr = unsafe { avahi_client_get_host_name(self.client.get().unwrap()) }; 310 | 311 | AvahiUtils::to_owned_string(host_name_ptr) 312 | .ok_or_else(|| AdapterError::Internal("Name is not available".to_owned())) 313 | } 314 | 315 | fn get_name_fqdn(&self) -> Result { 316 | debug!("Host name FQDN is requested."); 317 | 318 | self.initialize()?; 319 | 320 | let host_name_fqdn_ptr = 321 | unsafe { avahi_client_get_host_name_fqdn(self.client.get().unwrap()) }; 322 | 323 | AvahiUtils::to_owned_string(host_name_fqdn_ptr) 324 | .ok_or_else(|| AdapterError::Internal("Name is not available".to_owned())) 325 | } 326 | 327 | fn set_name(&self, host_name: &str) -> Result { 328 | debug!("Host name change (-> {}) is requested.", host_name); 329 | 330 | self.initialize()?; 331 | let current_host_name = self.get_name()?; 332 | 333 | if host_name == current_host_name { 334 | debug!("No need to change name, name is already set."); 335 | return Ok(host_name.to_owned()); 336 | } 337 | 338 | let client = self.client.get().unwrap(); 339 | let host_name = AvahiUtils::to_c_string(host_name.to_owned()).into_raw(); 340 | 341 | let result_code = unsafe { avahi_client_set_host_name(client, host_name) }; 342 | if result_code != 0 { 343 | return Err(From::from(AvahiError::from_error_code(result_code))); 344 | } 345 | 346 | debug!("Waiting for the name to be applied."); 347 | 348 | for message in self.client_channel.receiver.iter() { 349 | if let AvahiClientState::AVAHI_CLIENT_S_RUNNING = message.state { 350 | break; 351 | } 352 | } 353 | 354 | debug!("Host name is successfully updated."); 355 | 356 | // Reconstruct string to properly free up memory. 357 | unsafe { CString::from_raw(host_name) }; 358 | 359 | self.get_name() 360 | } 361 | 362 | fn is_valid_name(&self, host_name: &str) -> Result { 363 | debug!("Host name {:?} validation is requested.", host_name); 364 | 365 | let host_name = AvahiUtils::to_c_string(host_name.to_owned()).into_raw(); 366 | 367 | let is_valid = unsafe { avahi_is_valid_host_name(host_name) } == 1; 368 | 369 | debug!("Host name is valid: {:?}.", is_valid); 370 | 371 | // Reconstruct string to properly free up memory. 372 | unsafe { CString::from_raw(host_name) }; 373 | 374 | Ok(is_valid) 375 | } 376 | 377 | fn get_alternative_name(&self, host_name: &str) -> Result { 378 | let original_host_name = AvahiUtils::to_c_string(host_name.to_owned()).into_raw(); 379 | 380 | let alternative_host_name_ptr = unsafe { avahi_alternative_host_name(original_host_name) }; 381 | 382 | let alternative_host_name = AvahiUtils::to_owned_string(alternative_host_name_ptr); 383 | 384 | unsafe { avahi_free(alternative_host_name_ptr as *mut c_void) }; 385 | 386 | // Reconstruct string to properly free up memory. 387 | unsafe { CString::from_raw(original_host_name) }; 388 | 389 | alternative_host_name 390 | .ok_or_else(|| AdapterError::Internal("Name is not available".to_owned())) 391 | } 392 | 393 | fn add_name_alias(&self, host_name: &str) -> Result<(), AdapterError> { 394 | self.initialize()?; 395 | 396 | let current_host_name = self.get_name()?; 397 | if host_name == current_host_name { 398 | return Ok(()); 399 | } 400 | 401 | let client = self.client.get().unwrap(); 402 | 403 | let entry_group = unsafe { 404 | avahi_entry_group_new( 405 | client, 406 | *Box::new(AvahiCallbacks::entry_group_callback), 407 | ptr::null_mut(), 408 | ) 409 | }; 410 | 411 | let rdata = &name_fqdn_to_cname_rdata(&self.get_name_fqdn()?); 412 | 413 | let host_name = AvahiUtils::to_c_string(host_name.to_owned()).into_raw(); 414 | 415 | let result_code = unsafe { 416 | avahi_entry_group_add_record( 417 | entry_group, 418 | -1, 419 | AvahiProtocol::AVAHI_PROTO_UNSPEC, 420 | AvahiPublishFlags::AVAHI_PUBLISH_USE_MULTICAST, 421 | host_name, 422 | AvahiRecordClass::AVAHI_IN, 423 | AvahiRecordType::AVAHI_CNAME, 424 | 60, 425 | rdata.as_ptr() as *mut _, 426 | rdata.len(), 427 | ) 428 | }; 429 | 430 | if result_code != 0 { 431 | let error = AvahiError::from_error_code(result_code); 432 | error!("Failed to add new entry group record: {}", error); 433 | return Err(From::from(error)); 434 | } 435 | 436 | let result_code = unsafe { avahi_entry_group_commit(entry_group) }; 437 | if result_code != 0 { 438 | let error = AvahiError::from_error_code(result_code); 439 | error!("Failed to commit new entry group record: {}", error); 440 | return Err(From::from(error)); 441 | } 442 | 443 | // Reconstruct string to properly free up memory. 444 | unsafe { CString::from_raw(host_name) }; 445 | 446 | Ok(()) 447 | } 448 | 449 | fn announce_service(&self, service_name: &str, service_type: &str, port: u16) -> Result<(), AdapterError> { 450 | self.initialize()?; 451 | let client = self.client.get().unwrap(); 452 | let entry_group = unsafe { 453 | avahi_entry_group_new( 454 | client, 455 | *Box::new(AvahiCallbacks::entry_group_callback), 456 | ptr::null_mut(), 457 | ) 458 | }; 459 | 460 | if entry_group == 0 as _ { 461 | let code = unsafe { 462 | avahi_client_errno(client) 463 | }; 464 | let error = AvahiError::from_error_code(code); 465 | return Err(From::from(error)); 466 | } 467 | 468 | let service_name = AvahiUtils::to_c_string(service_name.to_owned()).into_raw(); 469 | let service_type = AvahiUtils::to_c_string(service_type.to_owned()).into_raw(); 470 | let result_code = unsafe { 471 | avahi_entry_group_add_service( 472 | entry_group, 473 | AvahiIfIndex::AVAHI_IF_UNSPEC, 474 | AvahiProtocol::AVAHI_PROTO_UNSPEC, 475 | AvahiPublishFlags::AVAHI_PUBLISH_USE_MULTICAST, 476 | service_name, 477 | service_type, 478 | ptr::null_mut(), 479 | ptr::null_mut(), 480 | port, 481 | ptr::null_mut(), 482 | ) 483 | }; 484 | 485 | if result_code != 0 { 486 | let error = AvahiError::from_error_code(result_code); 487 | error!("Failed to add a new entry group record: {}", error); 488 | return Err(From::from(error)); 489 | } 490 | 491 | let result_code = unsafe { avahi_entry_group_commit(entry_group) }; 492 | if result_code != 0 { 493 | let error = AvahiError::from_error_code(result_code); 494 | error!("Failed to commit new entry group record: {}", error); 495 | return Err(From::from(error)); 496 | } 497 | 498 | // Reconstruct string to properly free up memory. 499 | unsafe { CString::from_raw(service_type) }; 500 | unsafe { CString::from_raw(service_name) }; 501 | 502 | Ok(()) 503 | } 504 | } 505 | 506 | impl Drop for AvahiAdapter { 507 | fn drop(&mut self) { 508 | self.destroy(); 509 | } 510 | } 511 | 512 | impl Adapter for AvahiAdapter { 513 | fn new() -> AvahiAdapter { 514 | let (client_sender, client_receiver) = mpsc::channel::(); 515 | 516 | let (service_browser_sender, service_browser_receiver) = 517 | mpsc::channel::>(); 518 | 519 | AvahiAdapter { 520 | poll: Cell::new(None), 521 | 522 | client: Cell::new(None), 523 | client_channel: Channel { 524 | receiver: client_receiver, 525 | sender: client_sender, 526 | }, 527 | 528 | service_browser: Cell::new(None), 529 | service_browser_channel: Channel { 530 | receiver: service_browser_receiver, 531 | sender: service_browser_sender, 532 | }, 533 | } 534 | } 535 | } 536 | --------------------------------------------------------------------------------