multistream_select/
lib.rs

1// Copyright 2017 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//! # Multistream-select Protocol Negotiation
22//!
23//! This crate implements the `multistream-select` protocol, which is the protocol
24//! used by libp2p to negotiate which application-layer protocol to use with the
25//! remote on a connection or substream.
26//!
27//! > **Note**: This crate is used primarily by core components of *libp2p* and it
28//! > is usually not used directly on its own.
29//!
30//! ## Roles
31//!
32//! Two peers using the multistream-select negotiation protocol on an I/O stream
33//! are distinguished by their role as a _dialer_ (or _initiator_) or as a _listener_
34//! (or _responder_). Thereby the dialer plays the active part, driving the protocol,
35//! whereas the listener reacts to the messages received.
36//!
37//! The dialer has two options: it can either pick a protocol from the complete list
38//! of protocols that the listener supports, or it can directly suggest a protocol.
39//! Either way, a selected protocol is sent to the listener who can either accept (by
40//! echoing the same protocol) or reject (by responding with a message stating
41//! "not available"). If a suggested protocol is not available, the dialer may
42//! suggest another protocol. This process continues until a protocol is agreed upon,
43//! yielding a [`Negotiated`](self::Negotiated) stream, or the dialer has run out of
44//! alternatives.
45//!
46//! See [`dialer_select_proto`](self::dialer_select_proto) and
47//! [`listener_select_proto`](self::listener_select_proto).
48//!
49//! ## [`Negotiated`](self::Negotiated)
50//!
51//! A `Negotiated` represents an I/O stream that has settled on a protocol
52//! to use. By default, with [`Version::V1`], protocol negotiation is always
53//! at least one dedicated round-trip message exchange, before application
54//! data for the negotiated protocol can be sent by the dialer. There is
55//! a variant [`Version::V1Lazy`] that permits 0-RTT negotiation if the
56//! dialer only supports a single protocol. In that case, when a dialer
57//! settles on a protocol to use, the [`DialerSelectFuture`] yields a
58//! [`Negotiated`](self::Negotiated) I/O stream before the negotiation
59//! data has been flushed. It is then expecting confirmation for that protocol
60//! as the first messages read from the stream. This behaviour allows the dialer
61//! to immediately send data relating to the negotiated protocol together with the
62//! remaining negotiation message(s). Note, however, that a dialer that performs
63//! multiple 0-RTT negotiations in sequence for different protocols layered on
64//! top of each other may trigger undesirable behaviour for a listener not
65//! supporting one of the intermediate protocols. See
66//! [`dialer_select_proto`](self::dialer_select_proto) and the documentation
67//! of [`Version::V1Lazy`] for further details.
68//!
69//! ## Examples
70//!
71//! For a dialer:
72//!
73//! ```no_run
74//! use async_std::net::TcpStream;
75//! use multistream_select::{dialer_select_proto, Version};
76//! use futures::prelude::*;
77//!
78//! async_std::task::block_on(async move {
79//!     let socket = TcpStream::connect("127.0.0.1:10333").await.unwrap();
80//!
81//!     let protos = vec!["/echo/1.0.0", "/echo/2.5.0"];
82//!     let (protocol, _io) = dialer_select_proto(socket, protos, Version::V1).await.unwrap();
83//!
84//!     println!("Negotiated protocol: {:?}", protocol);
85//!     // You can now use `_io` to communicate with the remote.
86//! });
87//! ```
88//!
89
90#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
91
92mod dialer_select;
93mod length_delimited;
94mod listener_select;
95mod negotiated;
96mod protocol;
97
98pub use self::dialer_select::{dialer_select_proto, DialerSelectFuture};
99pub use self::listener_select::{listener_select_proto, ListenerSelectFuture};
100pub use self::negotiated::{Negotiated, NegotiatedComplete, NegotiationError};
101pub use self::protocol::ProtocolError;
102
103/// Supported multistream-select versions.
104#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
105pub enum Version {
106    /// Version 1 of the multistream-select protocol. See [1] and [2].
107    ///
108    /// [1]: https://github.com/libp2p/specs/blob/master/connections/README.md#protocol-negotiation
109    /// [2]: https://github.com/multiformats/multistream-select
110    #[default]
111    V1,
112    /// A "lazy" variant of version 1 that is identical on the wire but whereby
113    /// the dialer delays flushing protocol negotiation data in order to combine
114    /// it with initial application data, thus performing 0-RTT negotiation.
115    ///
116    /// This strategy is only applicable for the node with the role of "dialer"
117    /// in the negotiation and only if the dialer supports just a single
118    /// application protocol. In that case the dialer immedidately "settles"
119    /// on that protocol, buffering the negotiation messages to be sent
120    /// with the first round of application protocol data (or an attempt
121    /// is made to read from the `Negotiated` I/O stream).
122    ///
123    /// A listener will behave identically to `V1`. This ensures interoperability with `V1`.
124    /// Notably, it will immediately send the multistream header as well as the protocol
125    /// confirmation, resulting in multiple frames being sent on the underlying transport.
126    /// Nevertheless, if the listener supports the protocol that the dialer optimistically
127    /// settled on, it can be a 0-RTT negotiation.
128    ///
129    /// > **Note**: `V1Lazy` is specific to `rust-libp2p`. The wire protocol is identical to `V1`
130    /// > and generally interoperable with peers only supporting `V1`. Nevertheless, there is a
131    /// > pitfall that is rarely encountered: When nesting multiple protocol negotiations, the
132    /// > listener should either be known to support all of the dialer's optimistically chosen
133    /// > protocols or there is must be no intermediate protocol without a payload and none of
134    /// > the protocol payloads must have the potential for being mistaken for a multistream-select
135    /// > protocol message. This avoids rare edge-cases whereby the listener may not recognize
136    /// > upgrade boundaries and erroneously process a request despite not supporting one of
137    /// > the intermediate protocols that the dialer committed to. See [1] and [2].
138    ///
139    /// [1]: https://github.com/multiformats/go-multistream/issues/20
140    /// [2]: https://github.com/libp2p/rust-libp2p/pull/1212
141    V1Lazy,
142    // Draft: https://github.com/libp2p/specs/pull/95
143    // V2,
144}