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 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
use std::{
future::Future,
io,
os::raw::{
c_char,
c_void,
},
pin::Pin,
task::{
Context,
Poll,
},
};
use crate::{
cstr,
dns_consts::Type,
ffi,
inner,
interface::Interface,
};
type CallbackFuture = crate::future::ServiceFuture<inner::SharedService, RegisterResult>;
bitflags::bitflags! {
/// Flags used to register service
#[derive(Default)]
pub struct RegisterFlags: ffi::DNSServiceFlags {
/// Indicates a name conflict should not get handled automatically.
///
/// See [`kDNSServiceFlagsNoAutoRename`](https://developer.apple.com/documentation/dnssd/1823436-anonymous/kdnsserviceflagsnoautorename).
const NO_AUTO_RENAME = ffi::FLAGS_NO_AUTO_RENAME;
/// Indicates there might me multiple records with the given name, type and class.
///
/// See [`kDNSServiceFlagsShared`](https://developer.apple.com/documentation/dnssd/1823436-anonymous/kdnsserviceflagsshared).
const SHARED = ffi::FLAGS_SHARED;
/// Indicates the records with the given name, type and class is unique.
///
/// See [`kDNSServiceFlagsUnique`](https://developer.apple.com/documentation/dnssd/1823436-anonymous/kdnsserviceflagsunique).
const UNIQUE = ffi::FLAGS_UNIQUE;
}
}
/// Successful registration
///
/// On dropping the registration the service will be unregistered.
/// Registered [`Record`](struct.Record.html)s from this `Registration`
/// or the originating [`Register`](struct.Register.html) future will
/// keep the `Registration` alive.
pub struct Registration(inner::SharedService);
impl Registration {
/// Add a record to a registered service
///
/// See [`DNSServiceAddRecord`](https://developer.apple.com/documentation/dnssd/1804730-dnsserviceaddrecord)
#[doc(alias = "DNSServiceAddRecord")]
pub fn add_record(&self, rr_type: Type, rdata: &[u8], ttl: u32) -> io::Result<crate::Record> {
Ok(self
.0
.clone()
.add_record(0 /* no flags */, rr_type, rdata, ttl)?
.into())
}
/// Get [`Record`](struct.Record.html) handle for default TXT record
/// associated with the service registration (e.g. to update it).
///
/// [`Record::keep`](struct.Record.html#method.keep) doesn't do
/// anything useful on that handle.
pub fn get_default_txt_record(&self) -> crate::Record {
self.0.clone().get_default_txt_record().into()
}
}
/// Pending registration
///
/// Becomes invalid when the future completes; use the returned
/// [`Registration`](struct.Registration.html) instead.
#[must_use = "futures do nothing unless polled"]
pub struct Register {
future: CallbackFuture,
}
impl Register {
pin_utils::unsafe_pinned!(future: CallbackFuture);
/// Add a record to a registered service
///
/// See [`DNSServiceAddRecord`](https://developer.apple.com/documentation/dnssd/1804730-dnsserviceaddrecord)
#[doc(alias = "DNSServiceAddRecord")]
pub fn add_record(&self, rr_type: Type, rdata: &[u8], ttl: u32) -> io::Result<crate::Record> {
Ok(self
.future
.service()
.clone()
.add_record(0 /* no flags */, rr_type, rdata, ttl)?
.into())
}
/// Get [`Record`](struct.Record.html) handle for default TXT record
/// associated with the service registration (e.g. to update it).
///
/// [`Record::keep`](struct.Record.html#method.keep) doesn't do
/// anything useful on that handle.
pub fn get_default_txt_record(&self) -> crate::Record {
self.future
.service()
.clone()
.get_default_txt_record()
.into()
}
}
impl Future for Register {
type Output = io::Result<(Registration, RegisterResult)>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let (service, item) = futures_core::ready!(self.future().poll(cx))?;
Poll::Ready(Ok((Registration(service), item)))
}
}
/// Service registration result
///
/// See [`DNSServiceRegisterReply`](https://developer.apple.com/documentation/dnssd/dnsserviceregisterreply).
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct RegisterResult {
/// if [`NoAutoRename`](enum.RegisterFlag.html#variant.NoAutoRename)
/// was set this is the original name, otherwise it might be
/// different.
pub name: String,
/// the registered service type
pub reg_type: String,
/// domain the service was registered on
pub domain: String,
}
unsafe extern "C" fn register_callback(
_sd_ref: ffi::DNSServiceRef,
_flags: ffi::DNSServiceFlags,
error_code: ffi::DNSServiceErrorType,
name: *const c_char,
reg_type: *const c_char,
domain: *const c_char,
context: *mut c_void,
) {
CallbackFuture::run_callback(context, error_code, || {
let name = cstr::from_cstr(name)?;
let reg_type = cstr::from_cstr(reg_type)?;
let domain = cstr::from_cstr(domain)?;
Ok(RegisterResult {
name: name.to_string(),
reg_type: reg_type.to_string(),
domain: domain.to_string(),
})
});
}
/// Optional data when registering a service; either use its default
/// value or customize it like:
///
/// ```
/// # use async_dnssd::RegisterData;
/// RegisterData {
/// txt: b"some text data",
/// ..Default::default()
/// };
/// ```
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct RegisterData<'a> {
/// flags for registration
pub flags: RegisterFlags,
/// interface to register service on
pub interface: Interface,
/// service name, defaults to hostname
pub name: Option<&'a str>,
/// domain on which to advertise the service
pub domain: Option<&'a str>,
/// the SRV target host name, defaults to local hostname(s).
/// Address records are NOT automatically generated for other names.
pub host: Option<&'a str>,
/// The TXT record rdata. Empty RDATA is treated like `b"\0"`, i.e.
/// a TXT record with a single empty string.
///
/// You can use [`TxtRecord`] to create the value for this field
/// (both [`TxtRecord::data`] and [`TxtRecord::rdata`] produce
/// appropriate values).
///
/// [`TxtRecord`]: struct.TxtRecord.html
/// [`TxtRecord::data`]: struct.TxtRecord.html#method.data
/// [`TxtRecord::rdata`]: struct.TxtRecord.html#method.rdata
pub txt: &'a [u8],
#[doc(hidden)]
pub _non_exhaustive: crate::non_exhaustive_struct::NonExhaustiveMarker,
}
impl<'a> Default for RegisterData<'a> {
fn default() -> Self {
Self {
flags: RegisterFlags::default(),
interface: Interface::default(),
name: None,
domain: None,
host: None,
txt: b"",
_non_exhaustive: crate::non_exhaustive_struct::NonExhaustiveMarker,
}
}
}
/// Register a service
///
/// * `reg_type`: the service type followed by the protocol, separated
/// by a dot (for example, "_ssh._tcp"). For details see
/// [`DNSServiceRegister`]
/// * `port`: The port (in native byte order) on which the service
/// accepts connections. Pass 0 for a "placeholder" service.
/// * `data`: additional service data
///
/// See [`DNSServiceRegister`].
///
/// [`DNSServiceRegister`]: https://developer.apple.com/documentation/dnssd/1804733-dnsserviceregister
#[doc(alias = "DNSServiceRegister")]
#[allow(clippy::too_many_arguments)]
pub fn register_extended(
reg_type: &str,
port: u16,
data: RegisterData<'_>,
) -> io::Result<Register> {
crate::init();
let name = cstr::NullableCStr::from(&data.name)?;
let reg_type = cstr::CStr::from(®_type)?;
let domain = cstr::NullableCStr::from(&data.domain)?;
let host = cstr::NullableCStr::from(&data.host)?;
let future = CallbackFuture::new(move |sender| {
inner::OwnedService::register(
data.flags.bits(),
data.interface.into_raw(),
&name,
®_type,
&domain,
&host,
port.to_be(),
data.txt,
Some(register_callback),
sender,
)
.map(|s| s.share())
})?;
Ok(Register { future })
}
/// Register a service
///
/// * `reg_type`: the service type followed by the protocol, separated
/// by a dot (for example, "_ssh._tcp"). For details see
/// [`DNSServiceRegister`]
/// * `port`: The port (in native byte order) on which the service
/// accepts connections. Pass 0 for a "placeholder" service.
/// * `handle`: the tokio event loop handle
///
/// Uses [`register_extended`] with default [`RegisterData`].
///
/// [`register_extended`]: fn.register_extended.html
/// [`RegisterData`]: struct.RegisterData.html
///
/// See [`DNSServiceRegister`].
///
/// [`DNSServiceRegister`]: https://developer.apple.com/documentation/dnssd/1804733-dnsserviceregister
///
/// # Example
///
/// ```no_run
/// # use async_dnssd::register;
/// # #[deny(unused_must_use)]
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() -> std::io::Result<()> {
/// let registration = register("_ssh._tcp", 22)?.await?;
/// # Ok(())
/// # }
/// ```
#[doc(alias = "DNSServiceRegister")]
#[allow(clippy::too_many_arguments)]
pub fn register(reg_type: &str, port: u16) -> io::Result<Register> {
register_extended(reg_type, port, RegisterData::default())
}