libp2p_swarm/protocols_handler.rs
1// Copyright 2018 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
21//! Once a connection to a remote peer is established, a `ProtocolsHandler` negotiates
22//! and handles one or more specific protocols on the connection.
23//!
24//! Protocols are negotiated and used on individual substreams of the connection.
25//! Thus a `ProtocolsHandler` defines the inbound and outbound upgrades to apply
26//! when creating a new inbound or outbound substream, respectively, and is notified
27//! by a `Swarm` when these upgrades have been successfully applied, including the
28//! final output of the upgrade. A `ProtocolsHandler` can then continue communicating
29//! with the peer over the substream using the negotiated protocol(s).
30//!
31//! Two `ProtocolsHandler`s can be composed with [`ProtocolsHandler::select()`]
32//! in order to build a new handler supporting the combined set of protocols,
33//! with methods being dispatched to the appropriate handler according to the
34//! used protocol(s) determined by the associated types of the handlers.
35//!
36//! > **Note**: A `ProtocolsHandler` handles one or more protocols in the context of a single
37//! > connection with a remote. In order to handle a protocol that requires knowledge of
38//! > the network as a whole, see the `NetworkBehaviour` trait.
39
40mod dummy;
41mod map_in;
42mod map_out;
43mod node_handler;
44mod one_shot;
45mod select;
46pub mod multi;
47
48pub use crate::upgrade::{
49 InboundUpgradeSend,
50 OutboundUpgradeSend,
51 UpgradeInfoSend,
52};
53
54use libp2p_core::{
55 ConnectedPoint,
56 Multiaddr,
57 PeerId,
58 upgrade::UpgradeError,
59};
60use std::{cmp::Ordering, error, fmt, task::Context, task::Poll, time::Duration};
61use wasm_timer::Instant;
62
63pub use dummy::DummyProtocolsHandler;
64pub use map_in::MapInEvent;
65pub use map_out::MapOutEvent;
66pub use node_handler::{NodeHandlerWrapper, NodeHandlerWrapperBuilder, NodeHandlerWrapperError};
67pub use one_shot::{OneShotHandler, OneShotHandlerConfig};
68pub use select::{IntoProtocolsHandlerSelect, ProtocolsHandlerSelect};
69
70/// A handler for a set of protocols used on a connection with a remote.
71///
72/// This trait should be implemented for a type that maintains the state for
73/// the execution of a specific protocol with a remote.
74///
75/// # Handling a protocol
76///
77/// Communication with a remote over a set of protocols is initiated in one of two ways:
78///
79/// 1. Dialing by initiating a new outbound substream. In order to do so,
80/// [`ProtocolsHandler::poll()`] must return an [`ProtocolsHandlerEvent::OutboundSubstreamRequest`],
81/// providing an instance of [`libp2p_core::upgrade::OutboundUpgrade`] that is used to negotiate the
82/// protocol(s). Upon success, [`ProtocolsHandler::inject_fully_negotiated_outbound`]
83/// is called with the final output of the upgrade.
84///
85/// 2. Listening by accepting a new inbound substream. When a new inbound substream
86/// is created on a connection, [`ProtocolsHandler::listen_protocol`] is called
87/// to obtain an instance of [`libp2p_core::upgrade::InboundUpgrade`] that is used to
88/// negotiate the protocol(s). Upon success,
89/// [`ProtocolsHandler::inject_fully_negotiated_inbound`] is called with the final
90/// output of the upgrade.
91///
92/// # Connection Keep-Alive
93///
94/// A `ProtocolsHandler` can influence the lifetime of the underlying connection
95/// through [`ProtocolsHandler::connection_keep_alive`]. That is, the protocol
96/// implemented by the handler can include conditions for terminating the connection.
97/// The lifetime of successfully negotiated substreams is fully controlled by the handler.
98///
99/// Implementors of this trait should keep in mind that the connection can be closed at any time.
100/// When a connection is closed gracefully, the substreams used by the handler may still
101/// continue reading data until the remote closes its side of the connection.
102pub trait ProtocolsHandler: Send + 'static {
103 /// Custom event that can be received from the outside.
104 type InEvent: Send + 'static;
105 /// Custom event that can be produced by the handler and that will be returned to the outside.
106 type OutEvent: Send + 'static;
107 /// The type of errors returned by [`ProtocolsHandler::poll`].
108 type Error: error::Error + Send + 'static;
109 /// The inbound upgrade for the protocol(s) used by the handler.
110 type InboundProtocol: InboundUpgradeSend;
111 /// The outbound upgrade for the protocol(s) used by the handler.
112 type OutboundProtocol: OutboundUpgradeSend;
113 /// The type of additional information returned from `listen_protocol`.
114 type InboundOpenInfo: Send + 'static;
115 /// The type of additional information passed to an `OutboundSubstreamRequest`.
116 type OutboundOpenInfo: Send + 'static;
117
118 /// The [`InboundUpgrade`](libp2p_core::upgrade::InboundUpgrade) to apply on inbound
119 /// substreams to negotiate the desired protocols.
120 ///
121 /// > **Note**: The returned `InboundUpgrade` should always accept all the generally
122 /// > supported protocols, even if in a specific context a particular one is
123 /// > not supported, (eg. when only allowing one substream at a time for a protocol).
124 /// > This allows a remote to put the list of supported protocols in a cache.
125 fn listen_protocol(&self) -> SubstreamProtocol<Self::InboundProtocol, Self::InboundOpenInfo>;
126
127 /// Injects the output of a successful upgrade on a new inbound substream.
128 fn inject_fully_negotiated_inbound(
129 &mut self,
130 protocol: <Self::InboundProtocol as InboundUpgradeSend>::Output,
131 info: Self::InboundOpenInfo
132 );
133
134 /// Injects the output of a successful upgrade on a new outbound substream.
135 ///
136 /// The second argument is the information that was previously passed to
137 /// [`ProtocolsHandlerEvent::OutboundSubstreamRequest`].
138 fn inject_fully_negotiated_outbound(
139 &mut self,
140 protocol: <Self::OutboundProtocol as OutboundUpgradeSend>::Output,
141 info: Self::OutboundOpenInfo
142 );
143
144 /// Injects an event coming from the outside in the handler.
145 fn inject_event(&mut self, event: Self::InEvent);
146
147 /// Notifies the handler of a change in the address of the remote.
148 fn inject_address_change(&mut self, _new_address: &Multiaddr) {}
149
150 /// Indicates to the handler that upgrading an outbound substream to the given protocol has failed.
151 fn inject_dial_upgrade_error(
152 &mut self,
153 info: Self::OutboundOpenInfo,
154 error: ProtocolsHandlerUpgrErr<
155 <Self::OutboundProtocol as OutboundUpgradeSend>::Error
156 >
157 );
158
159 /// Indicates to the handler that upgrading an inbound substream to the given protocol has failed.
160 fn inject_listen_upgrade_error(
161 &mut self,
162 _: Self::InboundOpenInfo,
163 _: ProtocolsHandlerUpgrErr<<Self::InboundProtocol as InboundUpgradeSend>::Error>
164 ) {}
165
166 /// Returns until when the connection should be kept alive.
167 ///
168 /// This method is called by the `Swarm` after each invocation of
169 /// [`ProtocolsHandler::poll`] to determine if the connection and the associated
170 /// `ProtocolsHandler`s should be kept alive as far as this handler is concerned
171 /// and if so, for how long.
172 ///
173 /// Returning [`KeepAlive::No`] indicates that the connection should be
174 /// closed and this handler destroyed immediately.
175 ///
176 /// Returning [`KeepAlive::Until`] indicates that the connection may be closed
177 /// and this handler destroyed after the specified `Instant`.
178 ///
179 /// Returning [`KeepAlive::Yes`] indicates that the connection should
180 /// be kept alive until the next call to this method.
181 ///
182 /// > **Note**: The connection is always closed and the handler destroyed
183 /// > when [`ProtocolsHandler::poll`] returns an error. Furthermore, the
184 /// > connection may be closed for reasons outside of the control
185 /// > of the handler.
186 fn connection_keep_alive(&self) -> KeepAlive;
187
188 /// Should behave like `Stream::poll()`.
189 fn poll(&mut self, cx: &mut Context<'_>) -> Poll<
190 ProtocolsHandlerEvent<Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, Self::Error>
191 >;
192
193 /// Adds a closure that turns the input event into something else.
194 fn map_in_event<TNewIn, TMap>(self, map: TMap) -> MapInEvent<Self, TNewIn, TMap>
195 where
196 Self: Sized,
197 TMap: Fn(&TNewIn) -> Option<&Self::InEvent>,
198 {
199 MapInEvent::new(self, map)
200 }
201
202 /// Adds a closure that turns the output event into something else.
203 fn map_out_event<TMap, TNewOut>(self, map: TMap) -> MapOutEvent<Self, TMap>
204 where
205 Self: Sized,
206 TMap: FnMut(Self::OutEvent) -> TNewOut,
207 {
208 MapOutEvent::new(self, map)
209 }
210
211 /// Creates a new `ProtocolsHandler` that selects either this handler or
212 /// `other` by delegating methods calls appropriately.
213 ///
214 /// > **Note**: The largest `KeepAlive` returned by the two handlers takes precedence,
215 /// > i.e. is returned from [`ProtocolsHandler::connection_keep_alive`] by the returned
216 /// > handler.
217 fn select<TProto2>(self, other: TProto2) -> ProtocolsHandlerSelect<Self, TProto2>
218 where
219 Self: Sized,
220 {
221 ProtocolsHandlerSelect::new(self, other)
222 }
223
224 /// Creates a builder that allows creating a `NodeHandler` that handles this protocol
225 /// exclusively.
226 ///
227 /// > **Note**: This method should not be redefined in a custom `ProtocolsHandler`.
228 fn into_node_handler_builder(self) -> NodeHandlerWrapperBuilder<Self>
229 where
230 Self: Sized,
231 {
232 IntoProtocolsHandler::into_node_handler_builder(self)
233 }
234}
235
236/// Configuration of inbound or outbound substream protocol(s)
237/// for a [`ProtocolsHandler`].
238///
239/// The inbound substream protocol(s) are defined by [`ProtocolsHandler::listen_protocol`]
240/// and the outbound substream protocol(s) by [`ProtocolsHandlerEvent::OutboundSubstreamRequest`].
241#[derive(Copy, Clone, Debug, PartialEq, Eq)]
242pub struct SubstreamProtocol<TUpgrade, TInfo> {
243 upgrade: TUpgrade,
244 info: TInfo,
245 timeout: Duration,
246}
247
248impl<TUpgrade, TInfo> SubstreamProtocol<TUpgrade, TInfo> {
249 /// Create a new `SubstreamProtocol` from the given upgrade.
250 ///
251 /// The default timeout for applying the given upgrade on a substream is
252 /// 10 seconds.
253 pub fn new(upgrade: TUpgrade, info: TInfo) -> Self {
254 SubstreamProtocol {
255 upgrade,
256 info,
257 timeout: Duration::from_secs(10),
258 }
259 }
260
261 /// Maps a function over the protocol upgrade.
262 pub fn map_upgrade<U, F>(self, f: F) -> SubstreamProtocol<U, TInfo>
263 where
264 F: FnOnce(TUpgrade) -> U,
265 {
266 SubstreamProtocol {
267 upgrade: f(self.upgrade),
268 info: self.info,
269 timeout: self.timeout,
270 }
271 }
272
273 /// Maps a function over the protocol info.
274 pub fn map_info<U, F>(self, f: F) -> SubstreamProtocol<TUpgrade, U>
275 where
276 F: FnOnce(TInfo) -> U,
277 {
278 SubstreamProtocol {
279 upgrade: self.upgrade,
280 info: f(self.info),
281 timeout: self.timeout,
282 }
283 }
284
285 /// Sets a new timeout for the protocol upgrade.
286 pub fn with_timeout(mut self, timeout: Duration) -> Self {
287 self.timeout = timeout;
288 self
289 }
290
291 /// Borrows the contained protocol upgrade.
292 pub fn upgrade(&self) -> &TUpgrade {
293 &self.upgrade
294 }
295
296 /// Borrows the contained protocol info.
297 pub fn info(&self) -> &TInfo {
298 &self.info
299 }
300
301 /// Borrows the timeout for the protocol upgrade.
302 pub fn timeout(&self) -> &Duration {
303 &self.timeout
304 }
305
306 /// Converts the substream protocol configuration into the contained upgrade.
307 pub fn into_upgrade(self) -> (TUpgrade, TInfo) {
308 (self.upgrade, self.info)
309 }
310}
311
312/// Event produced by a handler.
313#[derive(Debug, Copy, Clone, PartialEq, Eq)]
314pub enum ProtocolsHandlerEvent<TConnectionUpgrade, TOutboundOpenInfo, TCustom, TErr> {
315 /// Request a new outbound substream to be opened with the remote.
316 OutboundSubstreamRequest {
317 /// The protocol(s) to apply on the substream.
318 protocol: SubstreamProtocol<TConnectionUpgrade, TOutboundOpenInfo>
319 },
320
321 /// Close the connection for the given reason.
322 Close(TErr),
323
324 /// Other event.
325 Custom(TCustom),
326}
327
328/// Event produced by a handler.
329impl<TConnectionUpgrade, TOutboundOpenInfo, TCustom, TErr>
330 ProtocolsHandlerEvent<TConnectionUpgrade, TOutboundOpenInfo, TCustom, TErr>
331{
332 /// If this is an `OutboundSubstreamRequest`, maps the `info` member from a
333 /// `TOutboundOpenInfo` to something else.
334 pub fn map_outbound_open_info<F, I>(
335 self,
336 map: F,
337 ) -> ProtocolsHandlerEvent<TConnectionUpgrade, I, TCustom, TErr>
338 where
339 F: FnOnce(TOutboundOpenInfo) -> I,
340 {
341 match self {
342 ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol } => {
343 ProtocolsHandlerEvent::OutboundSubstreamRequest {
344 protocol: protocol.map_info(map)
345 }
346 }
347 ProtocolsHandlerEvent::Custom(val) => ProtocolsHandlerEvent::Custom(val),
348 ProtocolsHandlerEvent::Close(val) => ProtocolsHandlerEvent::Close(val),
349 }
350 }
351
352 /// If this is an `OutboundSubstreamRequest`, maps the protocol (`TConnectionUpgrade`)
353 /// to something else.
354 pub fn map_protocol<F, I>(
355 self,
356 map: F,
357 ) -> ProtocolsHandlerEvent<I, TOutboundOpenInfo, TCustom, TErr>
358 where
359 F: FnOnce(TConnectionUpgrade) -> I,
360 {
361 match self {
362 ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol } => {
363 ProtocolsHandlerEvent::OutboundSubstreamRequest {
364 protocol: protocol.map_upgrade(map)
365 }
366 }
367 ProtocolsHandlerEvent::Custom(val) => ProtocolsHandlerEvent::Custom(val),
368 ProtocolsHandlerEvent::Close(val) => ProtocolsHandlerEvent::Close(val),
369 }
370 }
371
372 /// If this is a `Custom` event, maps the content to something else.
373 pub fn map_custom<F, I>(
374 self,
375 map: F,
376 ) -> ProtocolsHandlerEvent<TConnectionUpgrade, TOutboundOpenInfo, I, TErr>
377 where
378 F: FnOnce(TCustom) -> I,
379 {
380 match self {
381 ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol } => {
382 ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol }
383 }
384 ProtocolsHandlerEvent::Custom(val) => ProtocolsHandlerEvent::Custom(map(val)),
385 ProtocolsHandlerEvent::Close(val) => ProtocolsHandlerEvent::Close(val),
386 }
387 }
388
389 /// If this is a `Close` event, maps the content to something else.
390 pub fn map_close<F, I>(
391 self,
392 map: F,
393 ) -> ProtocolsHandlerEvent<TConnectionUpgrade, TOutboundOpenInfo, TCustom, I>
394 where
395 F: FnOnce(TErr) -> I,
396 {
397 match self {
398 ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol } => {
399 ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol }
400 }
401 ProtocolsHandlerEvent::Custom(val) => ProtocolsHandlerEvent::Custom(val),
402 ProtocolsHandlerEvent::Close(val) => ProtocolsHandlerEvent::Close(map(val)),
403 }
404 }
405}
406
407/// Error that can happen on an outbound substream opening attempt.
408#[derive(Debug)]
409pub enum ProtocolsHandlerUpgrErr<TUpgrErr> {
410 /// The opening attempt timed out before the negotiation was fully completed.
411 Timeout,
412 /// There was an error in the timer used.
413 Timer,
414 /// Error while upgrading the substream to the protocol we want.
415 Upgrade(UpgradeError<TUpgrErr>),
416}
417
418impl<TUpgrErr> ProtocolsHandlerUpgrErr<TUpgrErr> {
419 /// Map the inner [`UpgradeError`] type.
420 pub fn map_upgrade_err<F, E>(self, f: F) -> ProtocolsHandlerUpgrErr<E>
421 where
422 F: FnOnce(UpgradeError<TUpgrErr>) -> UpgradeError<E>
423 {
424 match self {
425 ProtocolsHandlerUpgrErr::Timeout => ProtocolsHandlerUpgrErr::Timeout,
426 ProtocolsHandlerUpgrErr::Timer => ProtocolsHandlerUpgrErr::Timer,
427 ProtocolsHandlerUpgrErr::Upgrade(e) => ProtocolsHandlerUpgrErr::Upgrade(f(e))
428 }
429 }
430}
431
432impl<TUpgrErr> fmt::Display for ProtocolsHandlerUpgrErr<TUpgrErr>
433where
434 TUpgrErr: fmt::Display,
435{
436 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
437 match self {
438 ProtocolsHandlerUpgrErr::Timeout => {
439 write!(f, "Timeout error while opening a substream")
440 },
441 ProtocolsHandlerUpgrErr::Timer => {
442 write!(f, "Timer error while opening a substream")
443 },
444 ProtocolsHandlerUpgrErr::Upgrade(err) => write!(f, "{}", err),
445 }
446 }
447}
448
449impl<TUpgrErr> error::Error for ProtocolsHandlerUpgrErr<TUpgrErr>
450where
451 TUpgrErr: error::Error + 'static
452{
453 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
454 match self {
455 ProtocolsHandlerUpgrErr::Timeout => None,
456 ProtocolsHandlerUpgrErr::Timer => None,
457 ProtocolsHandlerUpgrErr::Upgrade(err) => Some(err),
458 }
459 }
460}
461
462/// Prototype for a `ProtocolsHandler`.
463pub trait IntoProtocolsHandler: Send + 'static {
464 /// The protocols handler.
465 type Handler: ProtocolsHandler;
466
467 /// Builds the protocols handler.
468 ///
469 /// The `PeerId` is the id of the node the handler is going to handle.
470 fn into_handler(self, remote_peer_id: &PeerId, connected_point: &ConnectedPoint) -> Self::Handler;
471
472 /// Return the handler's inbound protocol.
473 fn inbound_protocol(&self) -> <Self::Handler as ProtocolsHandler>::InboundProtocol;
474
475 /// Builds an implementation of `IntoProtocolsHandler` that handles both this protocol and the
476 /// other one together.
477 fn select<TProto2>(self, other: TProto2) -> IntoProtocolsHandlerSelect<Self, TProto2>
478 where
479 Self: Sized,
480 {
481 IntoProtocolsHandlerSelect::new(self, other)
482 }
483
484 /// Creates a builder that will allow creating a `NodeHandler` that handles this protocol
485 /// exclusively.
486 fn into_node_handler_builder(self) -> NodeHandlerWrapperBuilder<Self>
487 where
488 Self: Sized,
489 {
490 NodeHandlerWrapperBuilder::new(self)
491 }
492}
493
494impl<T> IntoProtocolsHandler for T
495where T: ProtocolsHandler
496{
497 type Handler = Self;
498
499 fn into_handler(self, _: &PeerId, _: &ConnectedPoint) -> Self {
500 self
501 }
502
503 fn inbound_protocol(&self) -> <Self::Handler as ProtocolsHandler>::InboundProtocol {
504 self.listen_protocol().into_upgrade().0
505 }
506}
507
508/// How long the connection should be kept alive.
509#[derive(Debug, Copy, Clone, PartialEq, Eq)]
510pub enum KeepAlive {
511 /// If nothing new happens, the connection should be closed at the given `Instant`.
512 Until(Instant),
513 /// Keep the connection alive.
514 Yes,
515 /// Close the connection as soon as possible.
516 No,
517}
518
519impl KeepAlive {
520 /// Returns true for `Yes`, false otherwise.
521 pub fn is_yes(&self) -> bool {
522 match *self {
523 KeepAlive::Yes => true,
524 _ => false,
525 }
526 }
527}
528
529impl PartialOrd for KeepAlive {
530 fn partial_cmp(&self, other: &KeepAlive) -> Option<Ordering> {
531 Some(self.cmp(other))
532 }
533}
534
535impl Ord for KeepAlive {
536 fn cmp(&self, other: &KeepAlive) -> Ordering {
537 use self::KeepAlive::*;
538
539 match (self, other) {
540 (No, No) | (Yes, Yes) => Ordering::Equal,
541 (No, _) | (_, Yes) => Ordering::Less,
542 (_, No) | (Yes, _) => Ordering::Greater,
543 (Until(t1), Until(t2)) => t1.cmp(t2),
544 }
545 }
546}