cs_mwc_libp2p_swarm/
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 crate::{NetworkBehaviour, NetworkBehaviourAction, NetworkBehaviourEventProcess, PollParameters};
22use crate::upgrade::{SendWrapper, InboundUpgradeSend, OutboundUpgradeSend};
23use crate::protocols_handler::{
24    KeepAlive,
25    SubstreamProtocol,
26    ProtocolsHandler,
27    ProtocolsHandlerEvent,
28    ProtocolsHandlerUpgrErr,
29    IntoProtocolsHandler
30};
31use either::Either;
32use mwc_libp2p_core::{
33    ConnectedPoint,
34    PeerId,
35    Multiaddr,
36    connection::ConnectionId,
37    either::{EitherError, EitherOutput},
38    upgrade::{DeniedUpgrade, EitherUpgrade}
39};
40use std::{error, task::Context, task::Poll};
41
42/// Implementation of `NetworkBehaviour` that can be either in the disabled or enabled state.
43///
44/// The state can only be chosen at initialization.
45pub struct Toggle<TBehaviour> {
46    inner: Option<TBehaviour>,
47}
48
49impl<TBehaviour> Toggle<TBehaviour> {
50    /// Returns `true` if `Toggle` is enabled and `false` if it's disabled.
51    pub fn is_enabled(&self) -> bool {
52        self.inner.is_some()
53    }
54
55    /// Returns a reference to the inner `NetworkBehaviour`.
56    pub fn as_ref(&self) -> Option<&TBehaviour> {
57        self.inner.as_ref()
58    }
59
60    /// Returns a mutable reference to the inner `NetworkBehaviour`.
61    pub fn as_mut(&mut self) -> Option<&mut TBehaviour> {
62        self.inner.as_mut()
63    }
64}
65
66impl<TBehaviour> From<Option<TBehaviour>> for Toggle<TBehaviour> {
67    fn from(inner: Option<TBehaviour>) -> Self {
68        Toggle { inner }
69    }
70}
71
72impl<TBehaviour> NetworkBehaviour for Toggle<TBehaviour>
73where
74    TBehaviour: NetworkBehaviour
75{
76    type ProtocolsHandler = ToggleIntoProtoHandler<TBehaviour::ProtocolsHandler>;
77    type OutEvent = TBehaviour::OutEvent;
78
79    fn new_handler(&mut self) -> Self::ProtocolsHandler {
80        ToggleIntoProtoHandler {
81            inner: self.inner.as_mut().map(|i| i.new_handler())
82        }
83    }
84
85    fn addresses_of_peer(&mut self, peer_id: &PeerId) -> Vec<Multiaddr> {
86        self.inner.as_mut().map(|b| b.addresses_of_peer(peer_id)).unwrap_or_else(Vec::new)
87    }
88
89    fn inject_connected(&mut self, peer_id: &PeerId) {
90        if let Some(inner) = self.inner.as_mut() {
91            inner.inject_connected(peer_id)
92        }
93    }
94
95    fn inject_disconnected(&mut self, peer_id: &PeerId) {
96        if let Some(inner) = self.inner.as_mut() {
97            inner.inject_disconnected(peer_id)
98        }
99    }
100
101    fn inject_connection_established(&mut self, peer_id: &PeerId, connection: &ConnectionId, endpoint: &ConnectedPoint) {
102        if let Some(inner) = self.inner.as_mut() {
103            inner.inject_connection_established(peer_id, connection, endpoint)
104        }
105    }
106
107    fn inject_connection_closed(&mut self, peer_id: &PeerId, connection: &ConnectionId, endpoint: &ConnectedPoint) {
108        if let Some(inner) = self.inner.as_mut() {
109            inner.inject_connection_closed(peer_id, connection, endpoint)
110        }
111    }
112
113    fn inject_event(
114        &mut self,
115        peer_id: PeerId,
116        connection: ConnectionId,
117        event: <<Self::ProtocolsHandler as IntoProtocolsHandler>::Handler as ProtocolsHandler>::OutEvent
118    ) {
119        if let Some(inner) = self.inner.as_mut() {
120            inner.inject_event(peer_id, connection, event);
121        }
122    }
123
124    fn inject_addr_reach_failure(&mut self, peer_id: Option<&PeerId>, addr: &Multiaddr, error: &dyn error::Error) {
125        if let Some(inner) = self.inner.as_mut() {
126            inner.inject_addr_reach_failure(peer_id, addr, error)
127        }
128    }
129
130    fn inject_dial_failure(&mut self, peer_id: &PeerId) {
131        if let Some(inner) = self.inner.as_mut() {
132            inner.inject_dial_failure(peer_id)
133        }
134    }
135
136    fn inject_new_listen_addr(&mut self, addr: &Multiaddr) {
137        if let Some(inner) = self.inner.as_mut() {
138            inner.inject_new_listen_addr(addr)
139        }
140    }
141
142    fn inject_expired_listen_addr(&mut self, addr: &Multiaddr) {
143        if let Some(inner) = self.inner.as_mut() {
144            inner.inject_expired_listen_addr(addr)
145        }
146    }
147
148    fn inject_new_external_addr(&mut self, addr: &Multiaddr) {
149        if let Some(inner) = self.inner.as_mut() {
150            inner.inject_new_external_addr(addr)
151        }
152    }
153
154    fn poll(&mut self, cx: &mut Context<'_>, params: &mut impl PollParameters)
155        -> Poll<NetworkBehaviourAction<<<Self::ProtocolsHandler as IntoProtocolsHandler>::Handler as ProtocolsHandler>::InEvent, Self::OutEvent>>
156    {
157        if let Some(inner) = self.inner.as_mut() {
158            inner.poll(cx, params)
159        } else {
160            Poll::Pending
161        }
162    }
163}
164
165impl<TEvent, TBehaviour> NetworkBehaviourEventProcess<TEvent> for Toggle<TBehaviour>
166where
167    TBehaviour: NetworkBehaviourEventProcess<TEvent>
168{
169    fn inject_event(&mut self, event: TEvent) {
170        if let Some(inner) = self.inner.as_mut() {
171            inner.inject_event(event);
172        }
173    }
174}
175
176/// Implementation of `IntoProtocolsHandler` that can be in the disabled state.
177pub struct ToggleIntoProtoHandler<TInner> {
178    inner: Option<TInner>,
179}
180
181impl<TInner> IntoProtocolsHandler for ToggleIntoProtoHandler<TInner>
182where
183    TInner: IntoProtocolsHandler
184{
185    type Handler = ToggleProtoHandler<TInner::Handler>;
186
187    fn into_handler(self, remote_peer_id: &PeerId, connected_point: &ConnectedPoint) -> Self::Handler {
188        ToggleProtoHandler {
189            inner: self.inner.map(|h| h.into_handler(remote_peer_id, connected_point))
190        }
191    }
192
193    fn inbound_protocol(&self) -> <Self::Handler as ProtocolsHandler>::InboundProtocol {
194        if let Some(inner) = self.inner.as_ref() {
195            EitherUpgrade::A(SendWrapper(inner.inbound_protocol()))
196        } else {
197            EitherUpgrade::B(SendWrapper(DeniedUpgrade))
198        }
199    }
200}
201
202/// Implementation of `ProtocolsHandler` that can be in the disabled state.
203pub struct ToggleProtoHandler<TInner> {
204    inner: Option<TInner>,
205}
206
207impl<TInner> ProtocolsHandler for ToggleProtoHandler<TInner>
208where
209    TInner: ProtocolsHandler,
210{
211    type InEvent = TInner::InEvent;
212    type OutEvent = TInner::OutEvent;
213    type Error = TInner::Error;
214    type InboundProtocol = EitherUpgrade<SendWrapper<TInner::InboundProtocol>, SendWrapper<DeniedUpgrade>>;
215    type OutboundProtocol = TInner::OutboundProtocol;
216    type OutboundOpenInfo = TInner::OutboundOpenInfo;
217    type InboundOpenInfo = Either<TInner::InboundOpenInfo, ()>;
218
219    fn listen_protocol(&self) -> SubstreamProtocol<Self::InboundProtocol, Self::InboundOpenInfo> {
220        if let Some(inner) = self.inner.as_ref() {
221            inner.listen_protocol()
222                .map_upgrade(|u| EitherUpgrade::A(SendWrapper(u)))
223                .map_info(Either::Left)
224        } else {
225            SubstreamProtocol::new(EitherUpgrade::B(SendWrapper(DeniedUpgrade)), Either::Right(()))
226        }
227    }
228
229    fn inject_fully_negotiated_inbound(
230        &mut self,
231        out: <Self::InboundProtocol as InboundUpgradeSend>::Output,
232        info: Self::InboundOpenInfo
233    ) {
234        let out = match out {
235            EitherOutput::First(out) => out,
236            EitherOutput::Second(v) => void::unreachable(v),
237        };
238
239        if let Either::Left(info) = info {
240            self.inner.as_mut()
241                .expect("Can't receive an inbound substream if disabled; QED")
242                .inject_fully_negotiated_inbound(out, info)
243        } else {
244            panic!("Unexpected Either::Right in enabled `inject_fully_negotiated_inbound`.")
245        }
246    }
247
248    fn inject_fully_negotiated_outbound(
249        &mut self,
250        out: <Self::OutboundProtocol as OutboundUpgradeSend>::Output,
251        info: Self::OutboundOpenInfo
252    ) {
253        self.inner.as_mut().expect("Can't receive an outbound substream if disabled; QED")
254            .inject_fully_negotiated_outbound(out, info)
255    }
256
257    fn inject_event(&mut self, event: Self::InEvent) {
258        self.inner.as_mut().expect("Can't receive events if disabled; QED")
259            .inject_event(event)
260    }
261
262    fn inject_address_change(&mut self, addr: &Multiaddr) {
263        if let Some(inner) = self.inner.as_mut() {
264            inner.inject_address_change(addr)
265        }
266    }
267
268    fn inject_dial_upgrade_error(&mut self, info: Self::OutboundOpenInfo, err: ProtocolsHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>) {
269        self.inner.as_mut().expect("Can't receive an outbound substream if disabled; QED")
270            .inject_dial_upgrade_error(info, err)
271    }
272
273    fn inject_listen_upgrade_error(&mut self, info: Self::InboundOpenInfo, err: ProtocolsHandlerUpgrErr<<Self::InboundProtocol as InboundUpgradeSend>::Error>) {
274        let (inner, info) = match (self.inner.as_mut(), info) {
275            (Some(inner), Either::Left(info)) => (inner, info),
276            // Ignore listen upgrade errors in disabled state.
277            (None, Either::Right(())) => return,
278            (Some(_), Either::Right(())) => panic!(
279                "Unexpected `Either::Right` inbound info through \
280                 `inject_listen_upgrade_error` in enabled state.",
281            ),
282            (None, Either::Left(_)) => panic!(
283                "Unexpected `Either::Left` inbound info through \
284                 `inject_listen_upgrade_error` in disabled state.",
285            ),
286
287        };
288
289        let err = match err {
290            ProtocolsHandlerUpgrErr::Timeout => ProtocolsHandlerUpgrErr::Timeout,
291            ProtocolsHandlerUpgrErr::Timer => ProtocolsHandlerUpgrErr::Timer,
292            ProtocolsHandlerUpgrErr::Upgrade(err) =>
293                ProtocolsHandlerUpgrErr::Upgrade(err.map_err(|err| match err {
294                    EitherError::A(e) => e,
295                    EitherError::B(v) => void::unreachable(v)
296                }))
297        };
298
299        inner.inject_listen_upgrade_error(info, err)
300    }
301
302    fn connection_keep_alive(&self) -> KeepAlive {
303        self.inner.as_ref().map(|h| h.connection_keep_alive())
304            .unwrap_or(KeepAlive::No)
305    }
306
307    fn poll(
308        &mut self,
309        cx: &mut Context<'_>,
310    ) -> Poll<
311        ProtocolsHandlerEvent<Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, Self::Error>
312    > {
313        if let Some(inner) = self.inner.as_mut() {
314            inner.poll(cx)
315        } else {
316            Poll::Pending
317        }
318    }
319}
320
321#[cfg(test)]
322mod tests {
323    use super::*;
324    use crate::protocols_handler::DummyProtocolsHandler;
325
326    /// A disabled [`ToggleProtoHandler`] can receive listen upgrade errors in
327    /// the following two cases:
328    ///
329    /// 1. Protocol negotiation on an incoming stream failed with no protocol
330    ///    being agreed on.
331    ///
332    /// 2. When combining [`ProtocolsHandler`] implementations a single
333    ///    [`ProtocolsHandler`] might be notified of an inbound upgrade error
334    ///    unrelated to its own upgrade logic. For example when nesting a
335    ///    [`ToggleProtoHandler`] in a
336    ///    [`ProtocolsHandlerSelect`](crate::protocols_handler::ProtocolsHandlerSelect)
337    ///    the former might receive an inbound upgrade error even when disabled.
338    ///
339    /// [`ToggleProtoHandler`] should ignore the error in both of these cases.
340    #[test]
341    fn ignore_listen_upgrade_error_when_disabled() {
342        let mut handler = ToggleProtoHandler::<DummyProtocolsHandler> {
343            inner: None,
344        };
345
346        handler.inject_listen_upgrade_error(Either::Right(()), ProtocolsHandlerUpgrErr::Timeout);
347    }
348}