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`] stream, or the dialer has run out of
44//! alternatives.
45//!
46//! See [`dialer_select_proto`] and [`listener_select_proto`].
47//!
48//! ## [`Negotiated`]
49//!
50//! A `Negotiated` represents an I/O stream that has settled on a protocol
51//! to use. By default, with [`Version::V1`], protocol negotiation is always
52//! at least one dedicated round-trip message exchange, before application
53//! data for the negotiated protocol can be sent by the dialer. There is
54//! a variant [`Version::V1Lazy`] that permits 0-RTT negotiation if the
55//! dialer only supports a single protocol. In that case, when a dialer
56//! settles on a protocol to use, the [`DialerSelectFuture`] yields a
57//! [`Negotiated`] I/O stream before the negotiation
58//! data has been flushed. It is then expecting confirmation for that protocol
59//! as the first messages read from the stream. This behaviour allows the dialer
60//! to immediately send data relating to the negotiated protocol together with the
61//! remaining negotiation message(s). Note, however, that a dialer that performs
62//! multiple 0-RTT negotiations in sequence for different protocols layered on
63//! top of each other may trigger undesirable behaviour for a listener not
64//! supporting one of the intermediate protocols. See
65//! [`dialer_select_proto`] and the documentation of [`Version::V1Lazy`] for further details.
66//!
67//! ## Examples
68//!
69//! For a dialer:
70//!
71//! ```no_run
72//! use futures::prelude::*;
73//! use multistream_select::{dialer_select_proto, Version};
74//! use tokio::{net::TcpStream, runtime::Runtime};
75//! use tokio_util::compat::TokioAsyncReadCompatExt;
76//!
77//! let rt = Runtime::new().unwrap();
78//! rt.block_on(async move {
79//! let socket = TcpStream::connect("127.0.0.1:10333").await.unwrap();
80//! let compat_socket = socket.compat();
81//!
82//! let protos = vec!["/echo/1.0.0", "/echo/2.5.0"];
83//! let result = dialer_select_proto(compat_socket, protos, Version::V1).await;
84//! let (protocol, _io) = result.unwrap();
85//!
86//! println!("Negotiated protocol: {:?}", protocol);
87//! // You can now use `_io` to communicate with the remote.
88//! });
89//! ```
90
91#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
92
93mod dialer_select;
94mod length_delimited;
95mod listener_select;
96mod negotiated;
97mod protocol;
98
99pub use self::{
100 dialer_select::{dialer_select_proto, DialerSelectFuture},
101 listener_select::{listener_select_proto, ListenerSelectFuture},
102 negotiated::{Negotiated, NegotiatedComplete, NegotiationError},
103 protocol::ProtocolError,
104};
105
106/// Supported multistream-select versions.
107#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
108pub enum Version {
109 /// Version 1 of the multistream-select protocol. See [1] and [2].
110 ///
111 /// [1]: https://github.com/libp2p/specs/blob/master/connections/README.md#protocol-negotiation
112 /// [2]: https://github.com/multiformats/multistream-select
113 #[default]
114 V1,
115 /// A "lazy" variant of version 1 that is identical on the wire but whereby
116 /// the dialer delays flushing protocol negotiation data in order to combine
117 /// it with initial application data, thus performing 0-RTT negotiation.
118 ///
119 /// This strategy is only applicable for the node with the role of "dialer"
120 /// in the negotiation and only if the dialer supports just a single
121 /// application protocol. In that case the dialer immedidately "settles"
122 /// on that protocol, buffering the negotiation messages to be sent
123 /// with the first round of application protocol data (or an attempt
124 /// is made to read from the `Negotiated` I/O stream).
125 ///
126 /// A listener will behave identically to `V1`. This ensures interoperability with `V1`.
127 /// Notably, it will immediately send the multistream header as well as the protocol
128 /// confirmation, resulting in multiple frames being sent on the underlying transport.
129 /// Nevertheless, if the listener supports the protocol that the dialer optimistically
130 /// settled on, it can be a 0-RTT negotiation.
131 ///
132 /// > **Note**: `V1Lazy` is specific to `rust-libp2p`. The wire protocol is identical to `V1`
133 /// > and generally interoperable with peers only supporting `V1`. Nevertheless, there is a
134 /// > pitfall that is rarely encountered: When nesting multiple protocol negotiations, the
135 /// > listener should either be known to support all of the dialer's optimistically chosen
136 /// > protocols or there is must be no intermediate protocol without a payload and none of
137 /// > the protocol payloads must have the potential for being mistaken for a multistream-select
138 /// > protocol message. This avoids rare edge-cases whereby the listener may not recognize
139 /// > upgrade boundaries and erroneously process a request despite not supporting one of
140 /// > the intermediate protocols that the dialer committed to. See [1] and [2].
141 ///
142 /// [1]: https://github.com/multiformats/go-multistream/issues/20
143 /// [2]: https://github.com/libp2p/rust-libp2p/pull/1212
144 V1Lazy,
145 // Draft: https://github.com/libp2p/specs/pull/95
146 // V2,
147}
148
149#[cfg(test)]
150impl quickcheck::Arbitrary for Version {
151 fn arbitrary(g: &mut quickcheck::Gen) -> Self {
152 *g.choose(&[Version::V1, Version::V1Lazy])
153 .expect("slice not empty")
154 }
155}