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
// Copyright 2018 Parity Technologies (UK) Ltd.
//
// 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.

use crate::service::{MdnsPacket, MdnsService, build_query_response, build_service_discovery_response};
use async_io::Timer;
use futures::prelude::*;
use libp2p_core::{
    Multiaddr,
    PeerId,
    address_translation,
    connection::ConnectionId,
    multiaddr::Protocol
};
use libp2p_swarm::{
    NetworkBehaviour,
    NetworkBehaviourAction,
    PollParameters,
    ProtocolsHandler,
    protocols_handler::DummyProtocolsHandler
};
use smallvec::SmallVec;
use std::{cmp, fmt, io, iter, mem, pin::Pin, time::{Duration, Instant}, task::Context, task::Poll};

const MDNS_RESPONSE_TTL: std::time::Duration = Duration::from_secs(5 * 60);

/// A `NetworkBehaviour` for mDNS. Automatically discovers peers on the local network and adds
/// them to the topology.
pub struct Mdns {
    /// The inner service.
    service: MdnsBusyWrapper,

    /// List of nodes that we have discovered, the address, and when their TTL expires.
    ///
    /// Each combination of `PeerId` and `Multiaddr` can only appear once, but the same `PeerId`
    /// can appear multiple times.
    discovered_nodes: SmallVec<[(PeerId, Multiaddr, Instant); 8]>,

    /// Future that fires when the TTL of at least one node in `discovered_nodes` expires.
    ///
    /// `None` if `discovered_nodes` is empty.
    closest_expiration: Option<Timer>,
}

/// `MdnsService::next` takes ownership of `self`, returning a future that resolves with both itself
/// and a `MdnsPacket` (similar to the old Tokio socket send style). The two states are thus `Free`
/// with an `MdnsService` or `Busy` with a future returning the original `MdnsService` and an
/// `MdnsPacket`.
enum MdnsBusyWrapper {
    Free(MdnsService),
    Busy(Pin<Box<dyn Future<Output = (MdnsService, MdnsPacket)> + Send>>),
    Poisoned,
}

impl fmt::Debug for MdnsBusyWrapper {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Free(service) => {
                fmt.debug_struct("MdnsBusyWrapper::Free")
                    .field("service", service)
                    .finish()
            },
            Self::Busy(_) => {
                fmt.debug_struct("MdnsBusyWrapper::Busy")
                    .finish()
            }
            Self::Poisoned => {
                fmt.debug_struct("MdnsBusyWrapper::Poisoned")
                    .finish()
            }
        }
    }
}

impl Mdns {
    /// Builds a new `Mdns` behaviour.
    pub async fn new() -> io::Result<Self> {
        Ok(Self {
            service: MdnsBusyWrapper::Free(MdnsService::new().await?),
            discovered_nodes: SmallVec::new(),
            closest_expiration: None,
        })
    }

    /// Returns true if the given `PeerId` is in the list of nodes discovered through mDNS.
    pub fn has_node(&self, peer_id: &PeerId) -> bool {
        self.discovered_nodes().any(|p| p == peer_id)
    }

    /// Returns the list of nodes that we have discovered through mDNS and that are not expired.
    pub fn discovered_nodes(&self) -> impl ExactSizeIterator<Item = &PeerId> {
        self.discovered_nodes.iter().map(|(p, _, _)| p)
    }
}

impl NetworkBehaviour for Mdns {
    type ProtocolsHandler = DummyProtocolsHandler;
    type OutEvent = MdnsEvent;

    fn new_handler(&mut self) -> Self::ProtocolsHandler {
        DummyProtocolsHandler::default()
    }

    fn addresses_of_peer(&mut self, peer_id: &PeerId) -> Vec<Multiaddr> {
        let now = Instant::now();
        self.discovered_nodes
            .iter()
            .filter(move |(p, _, expires)| p == peer_id && *expires > now)
            .map(|(_, addr, _)| addr.clone())
            .collect()
    }

    fn inject_connected(&mut self, _: &PeerId) {}

    fn inject_disconnected(&mut self, _: &PeerId) {}

    fn inject_event(
        &mut self,
        _: PeerId,
        _: ConnectionId,
        ev: <Self::ProtocolsHandler as ProtocolsHandler>::OutEvent,
    ) {
        void::unreachable(ev)
    }

    fn poll(
        &mut self,
        cx: &mut Context<'_>,
        params: &mut impl PollParameters,
    ) -> Poll<
        NetworkBehaviourAction<
            <Self::ProtocolsHandler as ProtocolsHandler>::InEvent,
            Self::OutEvent,
        >,
    > {
        // Remove expired peers.
        if let Some(ref mut closest_expiration) = self.closest_expiration {
            match Pin::new(closest_expiration).poll(cx) {
                Poll::Ready(now) => {
                    let mut expired = SmallVec::<[(PeerId, Multiaddr); 4]>::new();
                    while let Some(pos) = self.discovered_nodes.iter().position(|(_, _, exp)| *exp < now) {
                        let (peer_id, addr, _) = self.discovered_nodes.remove(pos);
                        expired.push((peer_id, addr));
                    }

                    if !expired.is_empty() {
                        let event = MdnsEvent::Expired(ExpiredAddrsIter {
                            inner: expired.into_iter(),
                        });

                        return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event));
                    }
                },
                Poll::Pending => (),
            }
        }

        // Polling the mDNS service, and obtain the list of nodes discovered this round.
        let discovered = loop {
            let service = mem::replace(&mut self.service, MdnsBusyWrapper::Poisoned);

            let packet = match service {
                MdnsBusyWrapper::Free(service) => {
                    self.service = MdnsBusyWrapper::Busy(Box::pin(service.next()));
                    continue;
                },
                MdnsBusyWrapper::Busy(mut fut) => {
                    match fut.as_mut().poll(cx) {
                        Poll::Ready((service, packet)) => {
                            self.service = MdnsBusyWrapper::Free(service);
                            packet
                        },
                        Poll::Pending => {
                            self.service = MdnsBusyWrapper::Busy(fut);
                            return Poll::Pending;
                        }
                    }
                },
                MdnsBusyWrapper::Poisoned => panic!("Mdns poisoned"),
            };

            match packet {
                MdnsPacket::Query(query) => {
                    // MaybeBusyMdnsService should always be Free.
                    if let MdnsBusyWrapper::Free(ref mut service) = self.service {
                        for packet in build_query_response(
                            query.query_id(),
                            *params.local_peer_id(),
                            params.listened_addresses(),
                            MDNS_RESPONSE_TTL,
                        ) {
                            service.enqueue_response(packet)
                        }
                    } else { debug_assert!(false); }
                },
                MdnsPacket::Response(response) => {
                    // We replace the IP address with the address we observe the
                    // remote as and the address they listen on.
                    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();

                    let mut discovered: SmallVec<[_; 4]> = SmallVec::new();
                    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 {
                            if let Some((_, _, cur_expires)) = self.discovered_nodes.iter_mut()
                                .find(|(p, a, _)| p == peer.id() && *a == addr)
                            {
                                *cur_expires = cmp::max(*cur_expires, new_expiration);
                            } else {
                                self.discovered_nodes.push((*peer.id(), addr.clone(), new_expiration));
                            }

                            discovered.push((*peer.id(), addr));
                        }
                    }

                    break discovered;
                },
                MdnsPacket::ServiceDiscovery(disc) => {
                    // MaybeBusyMdnsService should always be Free.
                    if let MdnsBusyWrapper::Free(ref mut service) = self.service {
                        let resp = build_service_discovery_response(
                            disc.query_id(),
                            MDNS_RESPONSE_TTL,
                        );
                        service.enqueue_response(resp);
                    } else { debug_assert!(false); }
                },
            }
        };

        // Getting this far implies that we discovered new nodes. As the final step, we need to
        // refresh `closest_expiration`.
        self.closest_expiration = self.discovered_nodes.iter()
            .fold(None, |exp, &(_, _, elem_exp)| {
                Some(exp.map(|exp| cmp::min(exp, elem_exp)).unwrap_or(elem_exp))
            })
            .map(Timer::at);

        Poll::Ready(NetworkBehaviourAction::GenerateEvent(MdnsEvent::Discovered(DiscoveredAddrsIter {
            inner: discovered.into_iter(),
        })))
    }
}

impl fmt::Debug for Mdns {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.debug_struct("Mdns")
            .field("service", &self.service)
            .finish()
    }
}

/// Event that can be produced by the `Mdns` behaviour.
#[derive(Debug)]
pub enum MdnsEvent {
    /// Discovered nodes through mDNS.
    Discovered(DiscoveredAddrsIter),

    /// The given combinations of `PeerId` and `Multiaddr` have expired.
    ///
    /// Each discovered record has a time-to-live. When this TTL expires and the address hasn't
    /// been refreshed, we remove it from the list and emit it as an `Expired` event.
    Expired(ExpiredAddrsIter),
}

/// Iterator that produces the list of addresses that have been discovered.
pub struct DiscoveredAddrsIter {
    inner: smallvec::IntoIter<[(PeerId, Multiaddr); 4]>
}

impl Iterator for DiscoveredAddrsIter {
    type Item = (PeerId, Multiaddr);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl ExactSizeIterator for DiscoveredAddrsIter {
}

impl fmt::Debug for DiscoveredAddrsIter {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.debug_struct("DiscoveredAddrsIter")
            .finish()
    }
}

/// Iterator that produces the list of addresses that have expired.
pub struct ExpiredAddrsIter {
    inner: smallvec::IntoIter<[(PeerId, Multiaddr); 4]>
}

impl Iterator for ExpiredAddrsIter {
    type Item = (PeerId, Multiaddr);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl ExactSizeIterator for ExpiredAddrsIter {
}

impl fmt::Debug for ExpiredAddrsIter {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.debug_struct("ExpiredAddrsIter")
            .finish()
    }
}