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
mod dns;
mod query;
use self::dns::{build_query, build_query_response, build_service_discovery_response};
use self::query::MdnsPacket;
use crate::MdnsConfig;
use async_io::{Async, Timer};
use futures::prelude::*;
use libp2p_core::{address_translation, multiaddr::Protocol, Multiaddr, PeerId};
use libp2p_swarm::PollParameters;
use socket2::{Domain, Socket, Type};
use std::{
collections::VecDeque,
io, iter,
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, UdpSocket},
pin::Pin,
task::Context,
time::{Duration, Instant},
};
#[derive(Debug)]
pub struct InterfaceState {
addr: IpAddr,
recv_socket: Async<UdpSocket>,
send_socket: Async<UdpSocket>,
recv_buffer: [u8; 4096],
send_buffer: VecDeque<Vec<u8>>,
query_interval: Duration,
timeout: Timer,
multicast_addr: IpAddr,
discovered: VecDeque<(PeerId, Multiaddr, Instant)>,
ttl: Duration,
}
impl InterfaceState {
pub fn new(addr: IpAddr, config: MdnsConfig) -> io::Result<Self> {
log::info!("creating instance on iface {}", addr);
let recv_socket = match addr {
IpAddr::V4(addr) => {
let socket = Socket::new(Domain::IPV4, Type::DGRAM, Some(socket2::Protocol::UDP))?;
socket.set_reuse_address(true)?;
#[cfg(unix)]
socket.set_reuse_port(true)?;
socket.bind(&SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 5353).into())?;
socket.set_multicast_loop_v4(true)?;
socket.set_multicast_ttl_v4(255)?;
socket.join_multicast_v4(&*crate::IPV4_MDNS_MULTICAST_ADDRESS, &addr)?;
Async::new(UdpSocket::from(socket))?
}
IpAddr::V6(_) => {
let socket = Socket::new(Domain::IPV6, Type::DGRAM, Some(socket2::Protocol::UDP))?;
socket.set_reuse_address(true)?;
#[cfg(unix)]
socket.set_reuse_port(true)?;
socket.bind(&SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 5353).into())?;
socket.set_multicast_loop_v6(true)?;
socket.join_multicast_v6(&*crate::IPV6_MDNS_MULTICAST_ADDRESS, 0)?;
Async::new(UdpSocket::from(socket))?
}
};
let bind_addr = match addr {
IpAddr::V4(_) => SocketAddr::new(addr, 0),
IpAddr::V6(_addr) => {
SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 0)
}
};
let send_socket = Async::new(UdpSocket::bind(bind_addr)?)?;
let query_interval = {
use rand::Rng;
let mut rng = rand::thread_rng();
let jitter = rng.gen_range(0..100);
config.query_interval + Duration::from_millis(jitter)
};
let multicast_addr = match addr {
IpAddr::V4(_) => IpAddr::V4(*crate::IPV4_MDNS_MULTICAST_ADDRESS),
IpAddr::V6(_) => IpAddr::V6(*crate::IPV6_MDNS_MULTICAST_ADDRESS),
};
Ok(Self {
addr,
recv_socket,
send_socket,
recv_buffer: [0; 4096],
send_buffer: Default::default(),
discovered: Default::default(),
query_interval,
timeout: Timer::interval_at(Instant::now(), query_interval),
multicast_addr,
ttl: config.ttl,
})
}
pub fn reset_timer(&mut self) {
self.timeout.set_interval(self.query_interval);
}
pub fn fire_timer(&mut self) {
self.timeout
.set_interval_at(Instant::now(), self.query_interval);
}
fn inject_mdns_packet(&mut self, packet: MdnsPacket, params: &impl PollParameters) {
log::trace!("received packet on iface {} {:?}", self.addr, packet);
match packet {
MdnsPacket::Query(query) => {
self.reset_timer();
log::trace!("sending response on iface {}", self.addr);
for packet in build_query_response(
query.query_id(),
*params.local_peer_id(),
params.listened_addresses(),
self.ttl,
) {
self.send_buffer.push_back(packet);
}
}
MdnsPacket::Response(response) => {
let obs_ip = Protocol::from(response.remote_addr().ip());
let obs_port = Protocol::Udp(response.remote_addr().port());
let observed: Multiaddr = iter::once(obs_ip).chain(iter::once(obs_port)).collect();
for peer in response.discovered_peers() {
if peer.id() == params.local_peer_id() {
continue;
}
let new_expiration = Instant::now() + peer.ttl();
let mut addrs: Vec<Multiaddr> = Vec::new();
for addr in peer.addresses() {
if let Some(new_addr) = address_translation(addr, &observed) {
addrs.push(new_addr.clone())
}
addrs.push(addr.clone())
}
for addr in addrs {
self.discovered
.push_back((*peer.id(), addr, new_expiration));
}
}
}
MdnsPacket::ServiceDiscovery(disc) => {
let resp = build_service_discovery_response(disc.query_id(), self.ttl);
self.send_buffer.push_back(resp);
}
}
}
pub fn poll(
&mut self,
cx: &mut Context,
params: &impl PollParameters,
) -> Option<(PeerId, Multiaddr, Instant)> {
while self.recv_socket.poll_readable(cx).is_ready() {
match self
.recv_socket
.recv_from(&mut self.recv_buffer)
.now_or_never()
{
Some(Ok((len, from))) => {
if let Some(packet) = MdnsPacket::new_from_bytes(&self.recv_buffer[..len], from)
{
self.inject_mdns_packet(packet, params);
}
}
Some(Err(err)) => log::error!("Failed reading datagram: {}", err),
None => {}
}
}
while self.send_socket.poll_writable(cx).is_ready() {
if let Some(packet) = self.send_buffer.pop_front() {
match self
.send_socket
.send_to(&packet, SocketAddr::new(self.multicast_addr, 5353))
.now_or_never()
{
Some(Ok(_)) => log::trace!("sent packet on iface {}", self.addr),
Some(Err(err)) => {
log::error!("error sending packet on iface {}: {}", self.addr, err)
}
None => self.send_buffer.push_front(packet),
}
} else if Pin::new(&mut self.timeout).poll_next(cx).is_ready() {
log::trace!("sending query on iface {}", self.addr);
self.send_buffer.push_back(build_query());
} else {
break;
}
}
self.discovered.pop_front()
}
}