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 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
// Copyright 2018 Parity Technologies (UK) Ltd.
// Copyright 2023 litep2p developers
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//! [Multicast DNS](https://en.wikipedia.org/wiki/Multicast_DNS) implementation.
use crate::{error::Error, transport::manager::TransportManagerHandle, DEFAULT_CHANNEL_SIZE};
use futures::Stream;
use multiaddr::Multiaddr;
use rand::{distributions::Alphanumeric, Rng};
use simple_dns::{
rdata::{RData, PTR, TXT},
Name, Packet, PacketFlag, Question, ResourceRecord, CLASS, QCLASS, QTYPE, TYPE,
};
use socket2::{Domain, Protocol, Socket, Type};
use tokio::{
net::UdpSocket,
sync::mpsc::{channel, Sender},
};
use tokio_stream::wrappers::ReceiverStream;
use std::{
collections::HashSet,
net,
net::{IpAddr, Ipv4Addr, SocketAddr},
sync::Arc,
time::Duration,
};
/// Logging target for the file.
const LOG_TARGET: &str = "litep2p::mdns";
/// IPv4 multicast address.
const IPV4_MULTICAST_ADDRESS: Ipv4Addr = Ipv4Addr::new(224, 0, 0, 251);
/// IPV4 multicast port.
const IPV4_MULTICAST_PORT: u16 = 5353;
/// Service name.
const SERVICE_NAME: &str = "_p2p._udp.local";
/// Events emitted by mDNS.
// #[derive(Debug, Clone)]
pub enum MdnsEvent {
/// One or more addresses discovered.
Discovered(Vec<Multiaddr>),
}
/// mDNS configuration.
// #[derive(Debug)]
pub struct Config {
/// How often the network should be queried for new peers.
query_interval: Duration,
/// TX channel for sending mDNS events to user.
tx: Sender<MdnsEvent>,
}
impl Config {
/// Create new [`Config`].
///
/// Return the configuration and an event stream for receiving [`MdnsEvent`]s.
pub fn new(
query_interval: Duration,
) -> (Self, Box<dyn Stream<Item = MdnsEvent> + Send + Unpin>) {
let (tx, rx) = channel(DEFAULT_CHANNEL_SIZE);
(
Self { query_interval, tx },
Box::new(ReceiverStream::new(rx)),
)
}
}
/// Main mDNS object.
pub(crate) struct Mdns {
/// UDP socket for multicast requests/responses.
socket: UdpSocket,
/// Query interval.
query_interval: Duration,
/// TX channel for sending events to user.
event_tx: Sender<MdnsEvent>,
/// Handle to `TransportManager`.
_transport_handle: TransportManagerHandle,
// Username.
username: String,
/// Next query ID.
next_query_id: u16,
/// Buffer for incoming messages.
receive_buffer: Vec<u8>,
/// Listen addresses.
listen_addresses: Vec<Arc<str>>,
/// Discovered addresses.
discovered: HashSet<Multiaddr>,
}
impl Mdns {
/// Create new [`Mdns`].
pub(crate) fn new(
_transport_handle: TransportManagerHandle,
config: Config,
listen_addresses: Vec<Multiaddr>,
) -> crate::Result<Self> {
let socket = Socket::new(Domain::IPV4, Type::DGRAM, Some(Protocol::UDP))?;
socket.set_reuse_address(true)?;
#[cfg(unix)]
socket.set_reuse_port(true)?;
socket.bind(
&SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), IPV4_MULTICAST_PORT).into(),
)?;
socket.set_multicast_loop_v4(true)?;
socket.set_multicast_ttl_v4(255)?;
socket.join_multicast_v4(&IPV4_MULTICAST_ADDRESS, &Ipv4Addr::UNSPECIFIED)?;
socket.set_nonblocking(true)?;
Ok(Self {
_transport_handle,
event_tx: config.tx,
next_query_id: 1337u16,
discovered: HashSet::new(),
query_interval: config.query_interval,
receive_buffer: vec![0u8; 4096],
username: rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(32)
.map(char::from)
.collect(),
socket: UdpSocket::from_std(net::UdpSocket::from(socket))?,
listen_addresses: listen_addresses
.into_iter()
.map(|address| format!("dnsaddr={address}").into())
.collect(),
})
}
/// Get next query ID.
fn next_query_id(&mut self) -> u16 {
let query_id = self.next_query_id;
self.next_query_id += 1;
query_id
}
/// Send mDNS query on the network.
async fn on_outbound_request(&mut self) -> crate::Result<()> {
tracing::debug!(target: LOG_TARGET, "send outbound query");
let mut packet = Packet::new_query(self.next_query_id());
packet.questions.push(Question {
qname: Name::new_unchecked(SERVICE_NAME),
qtype: QTYPE::TYPE(TYPE::PTR),
qclass: QCLASS::CLASS(CLASS::IN),
unicast_response: false,
});
self.socket
.send_to(
&packet.build_bytes_vec().expect("valid packet"),
(IPV4_MULTICAST_ADDRESS, IPV4_MULTICAST_PORT),
)
.await
.map(|_| ())
.map_err(From::from)
}
/// Handle inbound query.
fn on_inbound_request(&self, packet: Packet) -> Option<Vec<u8>> {
tracing::debug!(target: LOG_TARGET, ?packet, "handle inbound request");
let mut packet = Packet::new_reply(packet.id());
let srv_name = Name::new_unchecked(SERVICE_NAME);
packet.answers.push(ResourceRecord::new(
srv_name.clone(),
CLASS::IN,
360,
RData::PTR(PTR(Name::new_unchecked(&self.username))),
));
for address in &self.listen_addresses {
let mut record = TXT::new();
record.add_string(address).expect("valid string");
packet.additional_records.push(ResourceRecord {
name: Name::new_unchecked(&self.username),
class: CLASS::IN,
ttl: 360,
rdata: RData::TXT(record),
cache_flush: false,
});
}
Some(packet.build_bytes_vec().expect("valid packet"))
}
/// Handle inbound response.
fn on_inbound_response(&self, packet: Packet) -> Vec<Multiaddr> {
tracing::debug!(target: LOG_TARGET, "handle inbound response");
let names = packet
.answers
.iter()
.filter_map(|answer| {
if answer.name != Name::new_unchecked(SERVICE_NAME) {
return None;
}
match answer.rdata {
RData::PTR(PTR(ref name)) if name != &Name::new_unchecked(&self.username) =>
Some(name),
_ => None,
}
})
.collect::<Vec<&Name>>();
let name = match names.len() {
0 => return Vec::new(),
_ => {
tracing::debug!(
target: LOG_TARGET,
?names,
"response name"
);
names[0]
}
};
packet
.additional_records
.iter()
.flat_map(|record| {
if &record.name != name {
return vec![];
}
// TODO: `filter_map` is not necessary as there's at most one entry
match &record.rdata {
RData::TXT(text) => text
.attributes()
.iter()
.filter_map(|(_, address)| {
address.as_ref().and_then(|inner| inner.parse().ok())
})
.collect(),
_ => vec![],
}
})
.collect()
}
/// Event loop for [`Mdns`].
pub(crate) async fn start(mut self) -> crate::Result<()> {
tracing::debug!(target: LOG_TARGET, "starting mdns event loop");
// before starting the loop, make an initial query to the network
//
// bail early if the socket is not working
self.on_outbound_request().await?;
loop {
tokio::select! {
_ = tokio::time::sleep(self.query_interval) => {
tracing::trace!(target: LOG_TARGET, "timeout expired");
if let Err(error) = self.on_outbound_request().await {
tracing::error!(target: LOG_TARGET, ?error, "failed to send mdns query");
return Err(error);
}
}
result = self.socket.recv_from(&mut self.receive_buffer) => match result {
Ok((nread, address)) => match Packet::parse(&self.receive_buffer[..nread]) {
Ok(packet) => match packet.has_flags(PacketFlag::RESPONSE) {
true => {
let to_forward = self.on_inbound_response(packet).into_iter().filter_map(|address| {
self.discovered.insert(address.clone()).then_some(address)
})
.collect::<Vec<_>>();
if !to_forward.is_empty() {
let _ = self.event_tx.send(MdnsEvent::Discovered(to_forward)).await;
}
}
false => if let Some(response) = self.on_inbound_request(packet) {
self.socket
.send_to(&response, (IPV4_MULTICAST_ADDRESS, IPV4_MULTICAST_PORT))
.await?;
}
}
Err(error) => tracing::debug!(
target: LOG_TARGET,
?address,
?error,
?nread,
"failed to parse mdns packet"
),
}
Err(error) => {
tracing::error!(target: LOG_TARGET, ?error, "failed to read from socket");
return Err(Error::from(error));
}
},
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
crypto::ed25519::Keypair,
transport::manager::{limits::ConnectionLimitsConfig, TransportManager},
BandwidthSink,
};
use futures::StreamExt;
use multiaddr::Protocol;
#[tokio::test]
async fn mdns_works() {
let _ = tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.try_init();
let (config1, mut stream1) = Config::new(Duration::from_secs(5));
let (_manager1, handle1) = TransportManager::new(
Keypair::generate(),
HashSet::new(),
BandwidthSink::new(),
8usize,
ConnectionLimitsConfig::default(),
);
let mdns1 = Mdns::new(
handle1,
config1,
vec![
"/ip6/::1/tcp/8888/p2p/12D3KooWNP463TyS3vUpmekjjZ2dg7xy1WHNMM7MqfsMevMTaaaa"
.parse()
.unwrap(),
"/ip4/127.0.0.1/tcp/8888/p2p/12D3KooWNP463TyS3vUpmekjjZ2dg7xy1WHNMM7MqfsMevMTaaaa"
.parse()
.unwrap(),
],
)
.unwrap();
let (config2, mut stream2) = Config::new(Duration::from_secs(5));
let (_manager1, handle2) = TransportManager::new(
Keypair::generate(),
HashSet::new(),
BandwidthSink::new(),
8usize,
ConnectionLimitsConfig::default(),
);
let mdns2 = Mdns::new(
handle2,
config2,
vec![
"/ip6/::1/tcp/9999/p2p/12D3KooWNP463TyS3vUpmekjjZ2dg7xy1WHNMM7MqfsMevMTbbbb"
.parse()
.unwrap(),
"/ip4/127.0.0.1/tcp/9999/p2p/12D3KooWNP463TyS3vUpmekjjZ2dg7xy1WHNMM7MqfsMevMTbbbb"
.parse()
.unwrap(),
],
)
.unwrap();
tokio::spawn(mdns1.start());
tokio::spawn(mdns2.start());
let mut peer1_discovered = false;
let mut peer2_discovered = false;
while !peer1_discovered && !peer2_discovered {
tokio::select! {
event = stream1.next() => match event.unwrap() {
MdnsEvent::Discovered(addrs) => {
if addrs.len() == 2 {
let mut iter = addrs[0].iter();
if !std::matches!(iter.next(), Some(Protocol::Ip4(_) | Protocol::Ip6(_))) {
continue
}
match iter.next() {
Some(Protocol::Tcp(port)) => {
if port != 9999 {
continue
}
}
_ => continue,
}
peer1_discovered = true;
}
}
},
event = stream2.next() => match event.unwrap() {
MdnsEvent::Discovered(addrs) => {
if addrs.len() == 2 {
let mut iter = addrs[0].iter();
if !std::matches!(iter.next(), Some(Protocol::Ip4(_) | Protocol::Ip6(_))) {
continue
}
match iter.next() {
Some(Protocol::Tcp(port)) => {
if port != 8888 {
continue
}
}
_ => continue,
}
peer2_discovered = true;
}
}
}
}
}
}
}