Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: enforce protocols to always be valid utf8 strings #3745

Closed
wants to merge 23 commits into from
Closed
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 1 addition & 10 deletions core/src/either.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use crate::muxing::StreamMuxerEvent;
use crate::{
muxing::StreamMuxer,
transport::{ListenerId, Transport, TransportError, TransportEvent},
Multiaddr, ProtocolName,
Multiaddr,
};
use either::Either;
use futures::prelude::*;
Expand Down Expand Up @@ -121,15 +121,6 @@ pub enum EitherName<A, B> {
B(B),
}

impl<A: ProtocolName, B: ProtocolName> ProtocolName for EitherName<A, B> {
fn protocol_name(&self) -> &[u8] {
match self {
EitherName::A(a) => a.protocol_name(),
EitherName::B(b) => b.protocol_name(),
}
}
}

impl<A, B> Transport for Either<A, B>
where
B: Transport,
Expand Down
7 changes: 6 additions & 1 deletion core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,12 @@ pub use peer_record::PeerRecord;
pub use signed_envelope::SignedEnvelope;
pub use translation::address_translation;
pub use transport::Transport;
pub use upgrade::{InboundUpgrade, OutboundUpgrade, ProtocolName, UpgradeError, UpgradeInfo};
#[allow(deprecated)]
pub use upgrade::ProtocolName;
pub use upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeError, ToProtocolsIter};

#[allow(deprecated)]
pub use upgrade::UpgradeInfo;

#[derive(Debug, thiserror::Error)]
pub struct DecodeError(String);
Expand Down
123 changes: 119 additions & 4 deletions core/src/upgrade.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ mod select;
mod transfer;

use futures::future::Future;
use std::fmt;
use std::iter::FilterMap;

pub use self::{
apply::{apply, apply_inbound, apply_outbound, InboundUpgradeApply, OutboundUpgradeApply},
Expand Down Expand Up @@ -119,6 +121,7 @@ pub use multistream_select::{NegotiatedComplete, NegotiationError, ProtocolError
/// }
/// ```
///
#[deprecated(note = "Use the `Protocol` new-type instead.")]
pub trait ProtocolName {
/// The protocol name as bytes. Transmitted on the network.
///
Expand All @@ -127,6 +130,7 @@ pub trait ProtocolName {
fn protocol_name(&self) -> &[u8];
}

#[allow(deprecated)]
impl<T: AsRef<[u8]>> ProtocolName for T {
fn protocol_name(&self) -> &[u8] {
self.as_ref()
Expand All @@ -135,6 +139,8 @@ impl<T: AsRef<[u8]>> ProtocolName for T {

/// Common trait for upgrades that can be applied on inbound substreams, outbound substreams,
/// or both.
#[deprecated(note = "Implement `UpgradeProtocols` instead.")]
thomaseizinger marked this conversation as resolved.
Show resolved Hide resolved
#[allow(deprecated)]
pub trait UpgradeInfo {
/// Opaque type representing a negotiable protocol.
type Info: ProtocolName + Clone;
Expand All @@ -145,8 +151,117 @@ pub trait UpgradeInfo {
fn protocol_info(&self) -> Self::InfoIter;
}

#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Protocol {
inner: multistream_select::Protocol,
}

impl Protocol {
/// Construct a new protocol from a static string slice.
///
/// # Panics
///
/// This function panics if the protocol does not start with a forward slash: `/`.
pub const fn from_static(s: &'static str) -> Self {
Protocol {
inner: multistream_select::Protocol::from_static(s),
}
}

/// Attempt to construct a protocol from an owned string.
///
/// This function will fail if the protocol does not start with a forward slash: `/`.
/// Where possible, you should use [`Protocol::from_static`] instead to avoid allocations.
pub fn try_from_owned(protocol: String) -> Result<Self, InvalidProtocol> {
Ok(Protocol {
inner: multistream_select::Protocol::try_from_owned(protocol)
.map_err(InvalidProtocol)?,
})
}

/// View the protocol as a string slice.
pub fn as_str(&self) -> &str {
self.inner.as_str()
}

pub(crate) fn from_inner(inner: multistream_select::Protocol) -> Self {
Protocol { inner }
}

pub(crate) fn into_inner(self) -> multistream_select::Protocol {
self.inner
}
}

impl fmt::Display for Protocol {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.inner.fmt(f)
}
}

impl PartialEq<str> for Protocol {
fn eq(&self, other: &str) -> bool {
self.inner.as_str() == other
}
}

#[derive(Debug)]
pub struct InvalidProtocol(multistream_select::ProtocolError);

impl fmt::Display for InvalidProtocol {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "invalid protocol")
}
}

impl std::error::Error for InvalidProtocol {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.0)
}
}

/// Each protocol upgrade must implement the [`ToProtocolsIter`] trait.
///
/// The returned iterator should yield the protocols that the upgrade supports.
pub trait ToProtocolsIter {
type Iter: Iterator<Item = Protocol>;
thomaseizinger marked this conversation as resolved.
Show resolved Hide resolved
thomaseizinger marked this conversation as resolved.
Show resolved Hide resolved

fn to_protocols_iter(&self) -> Self::Iter;
}

#[allow(deprecated)]
impl<U> ToProtocolsIter for U
where
U: UpgradeInfo,
{
type Iter = FilterMap<<U::InfoIter as IntoIterator>::IntoIter, fn(U::Info) -> Option<Protocol>>;

fn to_protocols_iter(&self) -> Self::Iter {
self.protocol_info()
.into_iter()
.filter_map(filter_non_utf8_protocols)
}
}

#[allow(deprecated)]
fn filter_non_utf8_protocols(p: impl ProtocolName) -> Option<Protocol> {
let name = p.protocol_name();

match multistream_select::Protocol::try_from(name) {
Ok(p) => Some(Protocol::from_inner(p)),
Err(e) => {
log::warn!(
"ignoring protocol {} during upgrade because it is malformed: {e}",
String::from_utf8_lossy(name)
);

None
}
}
}

/// Possible upgrade on an inbound connection or substream.
pub trait InboundUpgrade<C>: UpgradeInfo {
pub trait InboundUpgrade<C>: ToProtocolsIter {
/// Output after the upgrade has been successfully negotiated and the handshake performed.
type Output;
/// Possible error during the handshake.
Expand All @@ -158,7 +273,7 @@ pub trait InboundUpgrade<C>: UpgradeInfo {
/// method is called to start the handshake.
///
/// The `info` is the identifier of the protocol, as produced by `protocol_info`.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs updating.

fn upgrade_inbound(self, socket: C, info: Self::Info) -> Self::Future;
fn upgrade_inbound(self, socket: C, selected_protocol: Protocol) -> Self::Future;
}

/// Extension trait for `InboundUpgrade`. Automatically implemented on all types that implement
Expand Down Expand Up @@ -186,7 +301,7 @@ pub trait InboundUpgradeExt<C>: InboundUpgrade<C> {
impl<C, U: InboundUpgrade<C>> InboundUpgradeExt<C> for U {}

/// Possible upgrade on an outbound connection or substream.
pub trait OutboundUpgrade<C>: UpgradeInfo {
pub trait OutboundUpgrade<C>: ToProtocolsIter {
/// Output after the upgrade has been successfully negotiated and the handshake performed.
type Output;
/// Possible error during the handshake.
Expand All @@ -198,7 +313,7 @@ pub trait OutboundUpgrade<C>: UpgradeInfo {
/// method is called to start the handshake.
///
/// The `info` is the identifier of the protocol, as produced by `protocol_info`.
fn upgrade_outbound(self, socket: C, info: Self::Info) -> Self::Future;
fn upgrade_outbound(self, socket: C, selected_protocol: Protocol) -> Self::Future;
}

/// Extention trait for `OutboundUpgrade`. Automatically implemented on all types that implement
Expand Down
Loading