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
#![warn(missing_docs)]
#[macro_use]
extern crate lazy_static;
use std::{
net::{Ipv4Addr, SocketAddr},
time::Duration,
};
use simple_dns::{PacketBuf, SimpleDnsError};
use thiserror::Error;
use tokio::net::UdpSocket;
pub mod conversion_utils;
mod oneshot_resolver;
mod resource_record_manager;
mod service_discovery;
mod simple_responder;
pub use oneshot_resolver::OneShotMdnsResolver;
pub use service_discovery::ServiceDiscovery;
pub use simple_responder::SimpleMdnsResponder;
const ENABLE_LOOPBACK: bool = cfg!(test);
const UNICAST_RESPONSE: bool = cfg!(not(test));
const MULTICAST_IPV4: Ipv4Addr = Ipv4Addr::new(224, 0, 0, 251);
const MULTICAST_PORT: u16 = 5353;
lazy_static! {
pub(crate) static ref MULTICAST_IPV4_SOCKET: SocketAddr =
SocketAddr::new(MULTICAST_IPV4.into(), MULTICAST_PORT);
}
#[derive(Debug, Error)]
pub enum SimpleMdnsError {
#[error("There was an error related to UDP socket")]
UdpSocketError(#[from] std::io::Error),
#[error("Failed to parse dns packet")]
DnsParsing(#[from] SimpleDnsError),
}
async fn send_packet_to_multicast_socket(
socket: &UdpSocket,
packet: &PacketBuf,
) -> Result<(), SimpleMdnsError> {
socket.send_to(&packet, *MULTICAST_IPV4_SOCKET).await?;
Ok(())
}
fn create_udp_socket(multicast_loop: bool) -> Result<tokio::net::UdpSocket, SimpleMdnsError> {
let socket = socket2::Socket::new(socket2::Domain::ipv4(), socket2::Type::dgram(), None)?;
socket.set_multicast_loop_v4(multicast_loop)?;
socket.join_multicast_v4(&MULTICAST_IPV4, &Ipv4Addr::new(0, 0, 0, 0))?;
socket.set_reuse_address(true)?;
socket.set_nonblocking(true)?;
#[cfg(not(windows))]
socket.set_reuse_port(true)?;
socket.bind(&SocketAddr::from(([0, 0, 0, 0], MULTICAST_PORT)).into())?;
let socket = tokio::net::UdpSocket::from_std(socket.into_udp_socket())?;
Ok(socket)
}
async fn timeout<T: futures::Future>(
duration: Duration,
future: T,
) -> Result<T::Output, Box<dyn std::error::Error>> {
match tokio::time::timeout(duration, future).await {
Ok(result) => Ok(result),
Err(err) => Err(Box::new(err)),
}
}