libp2p_swarm/behaviour/
toggle.rs

1// Copyright 2019 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21use std::task::{Context, Poll};
22
23use either::Either;
24use futures::future;
25use libp2p_core::{transport::PortUse, upgrade::DeniedUpgrade, Endpoint, Multiaddr};
26use libp2p_identity::PeerId;
27
28use crate::{
29    behaviour::FromSwarm,
30    connection::ConnectionId,
31    handler::{
32        AddressChange, ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent,
33        DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound, ListenUpgradeError,
34        SubstreamProtocol,
35    },
36    upgrade::SendWrapper,
37    ConnectionDenied, NetworkBehaviour, THandler, THandlerInEvent, THandlerOutEvent, ToSwarm,
38};
39
40/// Implementation of `NetworkBehaviour` that can be either in the disabled or enabled state.
41///
42/// The state can only be chosen at initialization.
43pub struct Toggle<TBehaviour> {
44    inner: Option<TBehaviour>,
45}
46
47impl<TBehaviour> Toggle<TBehaviour> {
48    /// Returns `true` if `Toggle` is enabled and `false` if it's disabled.
49    pub fn is_enabled(&self) -> bool {
50        self.inner.is_some()
51    }
52
53    /// Returns a reference to the inner `NetworkBehaviour`.
54    pub fn as_ref(&self) -> Option<&TBehaviour> {
55        self.inner.as_ref()
56    }
57
58    /// Returns a mutable reference to the inner `NetworkBehaviour`.
59    pub fn as_mut(&mut self) -> Option<&mut TBehaviour> {
60        self.inner.as_mut()
61    }
62}
63
64impl<TBehaviour> From<Option<TBehaviour>> for Toggle<TBehaviour> {
65    fn from(inner: Option<TBehaviour>) -> Self {
66        Toggle { inner }
67    }
68}
69
70impl<TBehaviour> NetworkBehaviour for Toggle<TBehaviour>
71where
72    TBehaviour: NetworkBehaviour,
73{
74    type ConnectionHandler = ToggleConnectionHandler<THandler<TBehaviour>>;
75    type ToSwarm = TBehaviour::ToSwarm;
76
77    fn handle_pending_inbound_connection(
78        &mut self,
79        connection_id: ConnectionId,
80        local_addr: &Multiaddr,
81        remote_addr: &Multiaddr,
82    ) -> Result<(), ConnectionDenied> {
83        let inner = match self.inner.as_mut() {
84            None => return Ok(()),
85            Some(inner) => inner,
86        };
87
88        inner.handle_pending_inbound_connection(connection_id, local_addr, remote_addr)?;
89
90        Ok(())
91    }
92
93    fn handle_established_inbound_connection(
94        &mut self,
95        connection_id: ConnectionId,
96        peer: PeerId,
97        local_addr: &Multiaddr,
98        remote_addr: &Multiaddr,
99    ) -> Result<THandler<Self>, ConnectionDenied> {
100        let inner = match self.inner.as_mut() {
101            None => return Ok(ToggleConnectionHandler { inner: None }),
102            Some(inner) => inner,
103        };
104
105        let handler = inner.handle_established_inbound_connection(
106            connection_id,
107            peer,
108            local_addr,
109            remote_addr,
110        )?;
111
112        Ok(ToggleConnectionHandler {
113            inner: Some(handler),
114        })
115    }
116
117    fn handle_pending_outbound_connection(
118        &mut self,
119        connection_id: ConnectionId,
120        maybe_peer: Option<PeerId>,
121        addresses: &[Multiaddr],
122        effective_role: Endpoint,
123    ) -> Result<Vec<Multiaddr>, ConnectionDenied> {
124        let inner = match self.inner.as_mut() {
125            None => return Ok(vec![]),
126            Some(inner) => inner,
127        };
128
129        let addresses = inner.handle_pending_outbound_connection(
130            connection_id,
131            maybe_peer,
132            addresses,
133            effective_role,
134        )?;
135
136        Ok(addresses)
137    }
138
139    fn handle_established_outbound_connection(
140        &mut self,
141        connection_id: ConnectionId,
142        peer: PeerId,
143        addr: &Multiaddr,
144        role_override: Endpoint,
145        port_use: PortUse,
146    ) -> Result<THandler<Self>, ConnectionDenied> {
147        let inner = match self.inner.as_mut() {
148            None => return Ok(ToggleConnectionHandler { inner: None }),
149            Some(inner) => inner,
150        };
151
152        let handler = inner.handle_established_outbound_connection(
153            connection_id,
154            peer,
155            addr,
156            role_override,
157            port_use,
158        )?;
159
160        Ok(ToggleConnectionHandler {
161            inner: Some(handler),
162        })
163    }
164
165    fn on_swarm_event(&mut self, event: FromSwarm) {
166        if let Some(behaviour) = &mut self.inner {
167            behaviour.on_swarm_event(event);
168        }
169    }
170
171    fn on_connection_handler_event(
172        &mut self,
173        peer_id: PeerId,
174        connection_id: ConnectionId,
175        event: THandlerOutEvent<Self>,
176    ) {
177        if let Some(behaviour) = &mut self.inner {
178            behaviour.on_connection_handler_event(peer_id, connection_id, event)
179        }
180    }
181
182    fn poll(
183        &mut self,
184        cx: &mut Context<'_>,
185    ) -> Poll<ToSwarm<Self::ToSwarm, THandlerInEvent<Self>>> {
186        if let Some(inner) = self.inner.as_mut() {
187            inner.poll(cx)
188        } else {
189            Poll::Pending
190        }
191    }
192}
193
194/// Implementation of [`ConnectionHandler`] that can be in the disabled state.
195pub struct ToggleConnectionHandler<TInner> {
196    inner: Option<TInner>,
197}
198
199impl<TInner> ToggleConnectionHandler<TInner>
200where
201    TInner: ConnectionHandler,
202{
203    fn on_fully_negotiated_inbound(
204        &mut self,
205        FullyNegotiatedInbound {
206            protocol: out,
207            info,
208        }: FullyNegotiatedInbound<
209            <Self as ConnectionHandler>::InboundProtocol,
210            <Self as ConnectionHandler>::InboundOpenInfo,
211        >,
212    ) {
213        let out = match out {
214            future::Either::Left(out) => out,
215            future::Either::Right(v) => libp2p_core::util::unreachable(v),
216        };
217
218        if let Either::Left(info) = info {
219            self.inner
220                .as_mut()
221                .expect("Can't receive an inbound substream if disabled; QED")
222                .on_connection_event(ConnectionEvent::FullyNegotiatedInbound(
223                    FullyNegotiatedInbound {
224                        protocol: out,
225                        info,
226                    },
227                ));
228        } else {
229            panic!("Unexpected Either::Right in enabled `on_fully_negotiated_inbound`.")
230        }
231    }
232    fn on_listen_upgrade_error(
233        &mut self,
234        ListenUpgradeError { info, error: err }: ListenUpgradeError<
235            <Self as ConnectionHandler>::InboundOpenInfo,
236            <Self as ConnectionHandler>::InboundProtocol,
237        >,
238    ) {
239        let (inner, info) = match (self.inner.as_mut(), info) {
240            (Some(inner), Either::Left(info)) => (inner, info),
241            // Ignore listen upgrade errors in disabled state.
242            (None, Either::Right(())) => return,
243            (Some(_), Either::Right(())) => panic!(
244                "Unexpected `Either::Right` inbound info through \
245                 `on_listen_upgrade_error` in enabled state.",
246            ),
247            (None, Either::Left(_)) => panic!(
248                "Unexpected `Either::Left` inbound info through \
249                 `on_listen_upgrade_error` in disabled state.",
250            ),
251        };
252
253        let err = match err {
254            Either::Left(e) => e,
255            Either::Right(v) => libp2p_core::util::unreachable(v),
256        };
257
258        inner.on_connection_event(ConnectionEvent::ListenUpgradeError(ListenUpgradeError {
259            info,
260            error: err,
261        }));
262    }
263}
264
265impl<TInner> ConnectionHandler for ToggleConnectionHandler<TInner>
266where
267    TInner: ConnectionHandler,
268{
269    type FromBehaviour = TInner::FromBehaviour;
270    type ToBehaviour = TInner::ToBehaviour;
271    type InboundProtocol = Either<SendWrapper<TInner::InboundProtocol>, SendWrapper<DeniedUpgrade>>;
272    type OutboundProtocol = TInner::OutboundProtocol;
273    type OutboundOpenInfo = TInner::OutboundOpenInfo;
274    type InboundOpenInfo = Either<TInner::InboundOpenInfo, ()>;
275
276    fn listen_protocol(&self) -> SubstreamProtocol<Self::InboundProtocol, Self::InboundOpenInfo> {
277        if let Some(inner) = self.inner.as_ref() {
278            inner
279                .listen_protocol()
280                .map_upgrade(|u| Either::Left(SendWrapper(u)))
281                .map_info(Either::Left)
282        } else {
283            SubstreamProtocol::new(Either::Right(SendWrapper(DeniedUpgrade)), Either::Right(()))
284        }
285    }
286
287    fn on_behaviour_event(&mut self, event: Self::FromBehaviour) {
288        self.inner
289            .as_mut()
290            .expect("Can't receive events if disabled; QED")
291            .on_behaviour_event(event)
292    }
293
294    fn connection_keep_alive(&self) -> bool {
295        self.inner
296            .as_ref()
297            .map(|h| h.connection_keep_alive())
298            .unwrap_or(false)
299    }
300
301    fn poll(
302        &mut self,
303        cx: &mut Context<'_>,
304    ) -> Poll<
305        ConnectionHandlerEvent<Self::OutboundProtocol, Self::OutboundOpenInfo, Self::ToBehaviour>,
306    > {
307        if let Some(inner) = self.inner.as_mut() {
308            inner.poll(cx)
309        } else {
310            Poll::Pending
311        }
312    }
313
314    fn on_connection_event(
315        &mut self,
316        event: ConnectionEvent<
317            Self::InboundProtocol,
318            Self::OutboundProtocol,
319            Self::InboundOpenInfo,
320            Self::OutboundOpenInfo,
321        >,
322    ) {
323        match event {
324            ConnectionEvent::FullyNegotiatedInbound(fully_negotiated_inbound) => {
325                self.on_fully_negotiated_inbound(fully_negotiated_inbound)
326            }
327            ConnectionEvent::FullyNegotiatedOutbound(FullyNegotiatedOutbound {
328                protocol: out,
329                info,
330            }) => self
331                .inner
332                .as_mut()
333                .expect("Can't receive an outbound substream if disabled; QED")
334                .on_connection_event(ConnectionEvent::FullyNegotiatedOutbound(
335                    FullyNegotiatedOutbound {
336                        protocol: out,
337                        info,
338                    },
339                )),
340            ConnectionEvent::AddressChange(address_change) => {
341                if let Some(inner) = self.inner.as_mut() {
342                    inner.on_connection_event(ConnectionEvent::AddressChange(AddressChange {
343                        new_address: address_change.new_address,
344                    }));
345                }
346            }
347            ConnectionEvent::DialUpgradeError(DialUpgradeError { info, error: err }) => self
348                .inner
349                .as_mut()
350                .expect("Can't receive an outbound substream if disabled; QED")
351                .on_connection_event(ConnectionEvent::DialUpgradeError(DialUpgradeError {
352                    info,
353                    error: err,
354                })),
355            ConnectionEvent::ListenUpgradeError(listen_upgrade_error) => {
356                self.on_listen_upgrade_error(listen_upgrade_error)
357            }
358            ConnectionEvent::LocalProtocolsChange(change) => {
359                if let Some(inner) = self.inner.as_mut() {
360                    inner.on_connection_event(ConnectionEvent::LocalProtocolsChange(change));
361                }
362            }
363            ConnectionEvent::RemoteProtocolsChange(change) => {
364                if let Some(inner) = self.inner.as_mut() {
365                    inner.on_connection_event(ConnectionEvent::RemoteProtocolsChange(change));
366                }
367            }
368        }
369    }
370
371    fn poll_close(&mut self, cx: &mut Context<'_>) -> Poll<Option<Self::ToBehaviour>> {
372        let Some(inner) = self.inner.as_mut() else {
373            return Poll::Ready(None);
374        };
375
376        inner.poll_close(cx)
377    }
378}