aboutsummaryrefslogtreecommitdiffstats
path: root/src/transport/libp2p/ignore.rs
blob: eca93424fc55ec349f466d0f945d13f10866b65c (plain)
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
//! `--libp2p-ignore`: address ranges neither published nor dialled, nor connected over
//! (`Ignoring`, a behaviour that denies connections there), nor told peers by identify
//! (`Identifying`).

use std::fmt;

use super::*;

/// An address range (`10.244.0.0/16`, `42::/16`; a bare address is a range of one), for
/// `Libp2pConfig::ignore`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct IpRange {
    pub(super) network: std::net::IpAddr,
    pub(super) prefix: u8,
}

impl FromStr for IpRange {
    type Err = anyhow::Error;

    fn from_str(text: &str) -> Result<Self> {
        let (address, prefix) = match text.split_once('/') {
            Some((address, prefix)) => (address, Some(prefix)),
            None => (text, None),
        };
        let network: std::net::IpAddr = address
            .parse()
            .with_context(|| format!("{text:?} is no address range (e.g. 10.244.0.0/16)"))?;
        let bits = if network.is_ipv4() { 32 } else { 128 };
        let prefix = match prefix {
            Some(prefix) => prefix
                .parse::<u8>()
                .ok()
                .filter(|prefix| *prefix <= bits)
                .with_context(|| format!("{text:?}: the prefix is 0 to {bits}"))?,
            None => bits,
        };
        Ok(Self { network, prefix })
    }
}

impl fmt::Display for IpRange {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}/{}", self.network, self.prefix)
    }
}

impl IpRange {
    /// The range of the `prefix` bits of `ip` (the rest zero).
    pub(super) fn masked(ip: std::net::IpAddr, prefix: u8) -> Self {
        use std::net::IpAddr;
        let network = match ip {
            IpAddr::V4(ip) => {
                let mask = u32::MAX.checked_shl(32 - u32::from(prefix)).unwrap_or(0);
                IpAddr::V4((u32::from(ip) & mask).into())
            }
            IpAddr::V6(ip) => {
                let mask = u128::MAX.checked_shl(128 - u32::from(prefix)).unwrap_or(0);
                IpAddr::V6((u128::from(ip) & mask).into())
            }
        };
        Self { network, prefix }
    }

    /// Whether every address of `other` is in this range too.
    pub(super) fn covers(&self, other: &IpRange) -> bool {
        self.network.is_ipv4() == other.network.is_ipv4()
            && self.prefix <= other.prefix
            && self.contains(other.network)
    }

    pub(super) fn contains(&self, ip: std::net::IpAddr) -> bool {
        use std::net::IpAddr;
        match (self.network, ip) {
            (IpAddr::V4(network), IpAddr::V4(ip)) => {
                let mask = u32::MAX
                    .checked_shl(32 - u32::from(self.prefix))
                    .unwrap_or(0);
                u32::from(network) & mask == u32::from(ip) & mask
            }
            (IpAddr::V6(network), IpAddr::V6(ip)) => {
                let mask = u128::MAX
                    .checked_shl(128 - u32::from(self.prefix))
                    .unwrap_or(0);
                u128::from(network) & mask == u128::from(ip) & mask
            }
            _ => false,
        }
    }
}

/// Whether `address` is in one of `ranges`: a direct address there (one through a relay
/// is judged by the connection to the relay).
pub(super) fn ignored(ranges: &[IpRange], address: &Multiaddr) -> bool {
    if ranges.is_empty() || is_relayed(address) {
        return false;
    }
    let ip = match address.iter().next() {
        Some(Protocol::Ip4(ip)) => std::net::IpAddr::V4(ip),
        Some(Protocol::Ip6(ip)) => std::net::IpAddr::V6(ip),
        _ => return false,
    };
    ranges.iter().any(|range| range.contains(ip))
}

/// Whether `address` can only be reached over a range of `ranges`: a direct address
/// there, or one through a relay whose own address is there (dialling the relay is
/// refused, `Ignoring`). For what's kept and dialled; connections are judged by
/// `ignored`.
pub(super) fn left_out(ranges: &[IpRange], address: &Multiaddr) -> bool {
    if !is_relayed(address) {
        return ignored(ranges, address);
    }
    let relay: Multiaddr = address
        .iter()
        .take_while(|protocol| !matches!(protocol, Protocol::P2pCircuit))
        .collect();
    ignored(ranges, &without_peer(relay))
}

/// Keeps connections off the address ranges `libp2p-ignore` names, whoever dialled:
/// hole punching and identify bring addresses there too, and a peer may dial us there.
pub(super) struct Ignoring {
    pub(super) ranges: Vec<IpRange>,
}

#[derive(Debug, thiserror::Error)]
#[error("{0} is in a range left out (libp2p-ignore)")]
pub(super) struct IgnoredAddress(Multiaddr);

impl ::libp2p::swarm::NetworkBehaviour for Ignoring {
    type ConnectionHandler = ::libp2p::swarm::dummy::ConnectionHandler;
    type ToSwarm = std::convert::Infallible;

    fn handle_pending_inbound_connection(
        &mut self,
        _connection_id: ConnectionId,
        _local_addr: &Multiaddr,
        remote_addr: &Multiaddr,
    ) -> Result<(), ::libp2p::swarm::ConnectionDenied> {
        if ignored(&self.ranges, remote_addr) {
            return Err(::libp2p::swarm::ConnectionDenied::new(IgnoredAddress(
                remote_addr.clone(),
            )));
        }
        Ok(())
    }

    fn handle_established_inbound_connection(
        &mut self,
        _connection_id: ConnectionId,
        _peer: PeerId,
        _local_addr: &Multiaddr,
        _remote_addr: &Multiaddr,
    ) -> Result<::libp2p::swarm::THandler<Self>, ::libp2p::swarm::ConnectionDenied> {
        Ok(::libp2p::swarm::dummy::ConnectionHandler)
    }

    /// Dials libp2p makes itself (hole punching, AutoNAT, the DHT) to addresses all in
    /// ranges left out are refused before they go out; ours never go there
    /// (`Book::usable`). A dial with an address elsewhere too goes, and a connection it
    /// makes in a range left out is refused once established (below).
    fn handle_pending_outbound_connection(
        &mut self,
        _connection_id: ConnectionId,
        _maybe_peer: Option<PeerId>,
        addresses: &[Multiaddr],
        _effective_role: ::libp2p::core::Endpoint,
    ) -> Result<Vec<Multiaddr>, ::libp2p::swarm::ConnectionDenied> {
        if let Some(first) = addresses.first()
            && addresses
                .iter()
                .all(|address| ignored(&self.ranges, address))
        {
            return Err(::libp2p::swarm::ConnectionDenied::new(IgnoredAddress(
                first.clone(),
            )));
        }
        Ok(Vec::new())
    }

    fn handle_established_outbound_connection(
        &mut self,
        _connection_id: ConnectionId,
        _peer: PeerId,
        addr: &Multiaddr,
        _role_override: ::libp2p::core::Endpoint,
        _port_use: ::libp2p::core::transport::PortUse,
    ) -> Result<::libp2p::swarm::THandler<Self>, ::libp2p::swarm::ConnectionDenied> {
        if ignored(&self.ranges, addr) {
            return Err(::libp2p::swarm::ConnectionDenied::new(IgnoredAddress(
                addr.clone(),
            )));
        }
        Ok(::libp2p::swarm::dummy::ConnectionHandler)
    }

    fn on_swarm_event(&mut self, _event: ::libp2p::swarm::FromSwarm) {}

    fn on_connection_handler_event(
        &mut self,
        _peer_id: PeerId,
        _connection_id: ConnectionId,
        event: ::libp2p::swarm::THandlerOutEvent<Self>,
    ) {
        match event {}
    }

    fn poll(
        &mut self,
        _cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<
        ::libp2p::swarm::ToSwarm<Self::ToSwarm, ::libp2p::swarm::THandlerInEvent<Self>>,
    > {
        std::task::Poll::Pending
    }
}

/// libp2p's identify, not told our listen addresses, nor external ones (found by UPnP,
/// AutoNAT, a relay), in the ranges `libp2p-ignore` names: peers would remember them,
/// show them, and dial them in vain. Announced addresses (`--libp2p-announce`) are told
/// whatever range they are in.
pub(super) struct Identifying {
    pub(super) inner: ::libp2p::identify::Behaviour,
    pub(super) ranges: Vec<IpRange>,
    pub(super) announced: Vec<Multiaddr>,
}

impl Identifying {
    /// An external address identify isn't told: in an ignored range, and not announced.
    fn left_out(&self, address: &Multiaddr) -> bool {
        ignored(&self.ranges, address) && !self.announced.contains(address)
    }
}

impl ::libp2p::swarm::NetworkBehaviour for Identifying {
    type ConnectionHandler =
        <::libp2p::identify::Behaviour as ::libp2p::swarm::NetworkBehaviour>::ConnectionHandler;
    type ToSwarm = ::libp2p::identify::Event;

    fn handle_pending_inbound_connection(
        &mut self,
        connection_id: ConnectionId,
        local_addr: &Multiaddr,
        remote_addr: &Multiaddr,
    ) -> Result<(), ::libp2p::swarm::ConnectionDenied> {
        self.inner
            .handle_pending_inbound_connection(connection_id, local_addr, remote_addr)
    }

    fn handle_established_inbound_connection(
        &mut self,
        connection_id: ConnectionId,
        peer: PeerId,
        local_addr: &Multiaddr,
        remote_addr: &Multiaddr,
    ) -> Result<::libp2p::swarm::THandler<Self>, ::libp2p::swarm::ConnectionDenied> {
        self.inner.handle_established_inbound_connection(
            connection_id,
            peer,
            local_addr,
            remote_addr,
        )
    }

    fn handle_pending_outbound_connection(
        &mut self,
        connection_id: ConnectionId,
        maybe_peer: Option<PeerId>,
        addresses: &[Multiaddr],
        effective_role: ::libp2p::core::Endpoint,
    ) -> Result<Vec<Multiaddr>, ::libp2p::swarm::ConnectionDenied> {
        self.inner.handle_pending_outbound_connection(
            connection_id,
            maybe_peer,
            addresses,
            effective_role,
        )
    }

    fn handle_established_outbound_connection(
        &mut self,
        connection_id: ConnectionId,
        peer: PeerId,
        addr: &Multiaddr,
        role_override: ::libp2p::core::Endpoint,
        port_use: ::libp2p::core::transport::PortUse,
    ) -> Result<::libp2p::swarm::THandler<Self>, ::libp2p::swarm::ConnectionDenied> {
        self.inner.handle_established_outbound_connection(
            connection_id,
            peer,
            addr,
            role_override,
            port_use,
        )
    }

    fn on_swarm_event(&mut self, event: ::libp2p::swarm::FromSwarm) {
        use ::libp2p::swarm::FromSwarm;
        match event {
            FromSwarm::NewListenAddr(new) if ignored(&self.ranges, new.addr) => {}
            FromSwarm::ExpiredListenAddr(expired) if ignored(&self.ranges, expired.addr) => {}
            FromSwarm::ExternalAddrConfirmed(confirmed) if self.left_out(confirmed.addr) => {}
            FromSwarm::ExternalAddrExpired(expired) if self.left_out(expired.addr) => {}
            _ => self.inner.on_swarm_event(event),
        }
    }

    fn on_connection_handler_event(
        &mut self,
        peer_id: PeerId,
        connection_id: ConnectionId,
        event: ::libp2p::swarm::THandlerOutEvent<Self>,
    ) {
        self.inner
            .on_connection_handler_event(peer_id, connection_id, event)
    }

    fn poll(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<
        ::libp2p::swarm::ToSwarm<Self::ToSwarm, ::libp2p::swarm::THandlerInEvent<Self>>,
    > {
        self.inner.poll(cx)
    }
}