Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
7 changes: 5 additions & 2 deletions iroh/examples/0rtt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@ use std::{env, str::FromStr, time::Instant};

use clap::Parser;
use data_encoding::HEXLOWER;
use iroh::{EndpointId, SecretKey, discovery::Discovery, endpoint::ZeroRttStatus};
use iroh::{
EndpointId, SecretKey,
discovery::Discovery,
endpoint::{RecvStream, SendStream, ZeroRttStatus},
};
use n0_error::{Result, StackResultExt, StdResultExt};
use n0_future::StreamExt;
use quinn::{RecvStream, SendStream};
use tracing::{info, trace};

const PINGPONG_ALPN: &[u8] = b"0rtt-pingpong";
Expand Down
5 changes: 3 additions & 2 deletions iroh/examples/auth-hook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,12 +113,13 @@ mod auth {

use iroh::{
Endpoint, EndpointAddr, EndpointId,
endpoint::{AfterHandshakeOutcome, BeforeConnectOutcome, Connection, EndpointHooks},
endpoint::{
AfterHandshakeOutcome, BeforeConnectOutcome, Connection, ConnectionError, EndpointHooks,
},
protocol::{AcceptError, ProtocolHandler},
};
use n0_error::{AnyError, Result, StackResultExt, StdResultExt, anyerr};
use n0_future::task::AbortOnDropHandle;
use quinn::ConnectionError;
use tokio::{
sync::{mpsc, oneshot},
task::JoinSet,
Expand Down
80 changes: 45 additions & 35 deletions iroh/src/endpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ use crate::{
mod connection;
pub(crate) mod hooks;
pub mod presets;
mod quic;
pub(crate) mod quic;

pub use hooks::{AfterHandshakeOutcome, BeforeConnectOutcome, EndpointHooks};

Expand All @@ -55,17 +55,20 @@ pub use self::{
Accept, Accepting, AlpnError, AuthenticationError, Connecting, ConnectingError, Connection,
ConnectionInfo, ConnectionState, HandshakeCompleted, Incoming, IncomingZeroRtt,
IncomingZeroRttConnection, OutgoingZeroRtt, OutgoingZeroRttConnection,
RemoteEndpointIdError, ZeroRttStatus,
RemoteEndpointIdError, RetryError, ZeroRttStatus,
},
quic::{
AcceptBi, AcceptUni, AckFrequencyConfig, AeadKey, ApplicationClose, Chunk, ClosedStream,
ConnectionClose, ConnectionError, ConnectionStats, Controller, ControllerFactory,
CryptoError, CryptoServerConfig, ExportKeyingMaterialError, FrameStats, HandshakeTokenKey,
IdleTimeout, MtuDiscoveryConfig, OpenBi, OpenUni, PathStats, QuicTransportConfig,
ReadDatagram, ReadError, ReadExactError, ReadToEndError, RecvStream, ResetError,
RetryError, SendDatagramError, SendStream, ServerConfig, Side, StoppedError, StreamId,
TransportError, TransportErrorCode, UdpStats, UnsupportedVersion, VarInt,
VarIntBoundsExceeded, WeakConnectionHandle, WriteError, Written,
Codec, ConnectionClose, ConnectionError, ConnectionId, ConnectionStats, Controller,
ControllerFactory, ControllerMetrics, CryptoError, CryptoServerConfig, Dir,
ExportKeyingMaterialError, FrameStats, FrameType, HandshakeTokenKey, HeaderKey,
IdleTimeout, Keys, MtuDiscoveryConfig, OpenBi, OpenUni, PacketKey, PathId, PathStats,
QuicConnectError, QuicTransportConfig, ReadDatagram, ReadError, ReadExactError,
ReadToEndError, RecvStream, ResetError, RttEstimator, SendDatagram, SendDatagramError,
SendStream, ServerConfig, Session, Side, StoppedError, StreamId, TimeSource, TokenLog,
TokenReuseError, TransportError, TransportErrorCode, TransportParameters, UdpStats,
UnsupportedVersion, ValidationTokenConfig, VarInt, VarIntBoundsExceeded, WriteError,
Written,
},
};
pub use crate::magicsock::transports::TransportConfig;
Expand Down Expand Up @@ -169,7 +172,9 @@ impl Builder {
tls_config: tls::TlsConfig::new(secret_key.clone(), self.max_tls_tickets),
keylog: self.keylog,
};
let server_config = static_config.create_server_config(self.alpn_protocols);
let server_config = static_config
.create_server_config(self.alpn_protocols)
.into_inner();

#[cfg(not(wasm_browser))]
let dns_resolver = self.dns_resolver.unwrap_or_default();
Expand Down Expand Up @@ -468,15 +473,15 @@ struct StaticConfig {
}

impl StaticConfig {
/// Create a [`quinn::ServerConfig`] with the specified ALPN protocols.
/// Create a [`ServerConfig`] with the specified ALPN protocols.
fn create_server_config(&self, alpn_protocols: Vec<Vec<u8>>) -> ServerConfig {
let quic_server_config = self
.tls_config
.make_server_config(alpn_protocols, self.keylog);
let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config));
server_config.transport_config(self.transport_config.to_arc());
let mut inner = quinn::ServerConfig::with_crypto(Arc::new(quic_server_config));
inner.transport_config(self.transport_config.to_inner_arc());

server_config
ServerConfig::new(inner, self.transport_config.clone())
}
}

Expand Down Expand Up @@ -525,7 +530,7 @@ pub enum ConnectWithOptsError {
#[error("Unable to connect to remote")]
Quinn {
#[error(std_err)]
source: quinn_proto::ConnectError,
source: QuicConnectError,
},
#[error("Internal consistency error")]
InternalConsistencyError {
Expand Down Expand Up @@ -599,7 +604,9 @@ impl Endpoint {
/// Note that this *overrides* the current list of ALPNs.
pub fn set_alpns(&self, alpns: Vec<Vec<u8>>) {
let server_config = self.static_config.create_server_config(alpns);
self.msock.endpoint().set_server_config(Some(server_config));
self.msock
.endpoint()
.set_server_config(Some(server_config.into_inner()));
}

/// Adds the provided configuration to the [`RelayMap`].
Expand Down Expand Up @@ -715,8 +722,8 @@ impl Endpoint {

let transport_config = options
.transport_config
.map(|cfg| cfg.to_arc())
.unwrap_or(self.static_config.transport_config.to_arc());
.map(|cfg| cfg.to_inner_arc())
.unwrap_or(self.static_config.transport_config.to_inner_arc());

// Start connecting via quinn. This will time out after 10 seconds if no reachable
// address is available.
Expand Down Expand Up @@ -1137,6 +1144,11 @@ impl Endpoint {
self.msock.is_closed()
}

/// Create a [`ServerConfig`] for this endpoint that includes the given alpns.
Copy link
Contributor

Choose a reason for hiding this comment

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

Maybe give some pointers to where and why you need to use this. I know you already link in the other direction, but it doesn't do any harm linking both ways.

pub fn create_server_config(&self, alpns: Vec<Vec<u8>>) -> ServerConfig {
self.static_config.create_server_config(alpns)
}

// # Remaining private methods

#[cfg(test)]
Expand Down Expand Up @@ -1305,7 +1317,6 @@ mod tests {
use n0_error::{AnyError as Error, Result, StdResultExt};
use n0_future::{BufferedStreamExt, StreamExt, stream, time};
use n0_watcher::Watcher;
use quinn::ConnectionError;
use rand::SeedableRng;
use tokio::sync::oneshot;
use tracing::{Instrument, error_span, info, info_span, instrument};
Expand All @@ -1315,7 +1326,7 @@ mod tests {
use crate::{
RelayMap, RelayMode,
discovery::static_provider::StaticProvider,
endpoint::{ConnectOptions, Connection},
endpoint::{ApplicationClose, ConnectOptions, Connection, ConnectionError},
protocol::{AcceptError, ProtocolHandler, Router},
test_utils::{QlogFileGroup, run_relay_server, run_relay_server_with},
};
Expand Down Expand Up @@ -1373,13 +1384,13 @@ mod tests {
conn.close(7u8.into(), b"bye");

let res = conn.accept_uni().await;
assert_eq!(res.unwrap_err(), quinn::ConnectionError::LocallyClosed);
assert_eq!(res.unwrap_err(), ConnectionError::LocallyClosed);

let res = stream.read_to_end(10).await;
assert_eq!(
res.unwrap_err(),
quinn::ReadToEndError::Read(quinn::ReadError::ConnectionLost(
quinn::ConnectionError::LocallyClosed
ConnectionError::LocallyClosed
))
);
info!("server test completed");
Expand Down Expand Up @@ -1410,11 +1421,10 @@ mod tests {
info!("waiting for closed");
// Remote now closes the connection, we should see an error sometime soon.
let err = conn.closed().await;
let expected_err =
quinn::ConnectionError::ApplicationClosed(quinn::ApplicationClose {
error_code: 7u8.into(),
reason: b"bye".to_vec().into(),
});
let expected_err = ConnectionError::ApplicationClosed(ApplicationClose {
error_code: 7u8.into(),
reason: b"bye".to_vec().into(),
});
assert_eq!(err, expected_err);

info!("opening new - expect it to fail");
Expand Down Expand Up @@ -1619,7 +1629,7 @@ mod tests {
let ep1_nodeaddr = ep1.addr();

#[instrument(name = "client", skip_all)]
async fn connect(ep: Endpoint, dst: EndpointAddr) -> Result<quinn::ConnectionError> {
async fn connect(ep: Endpoint, dst: EndpointAddr) -> Result<ConnectionError> {
info!(me = %ep.id().fmt_short(), "client starting");
let conn = ep.connect(dst, TEST_ALPN).await?;
let mut send = conn.open_uni().await.anyerr()?;
Expand Down Expand Up @@ -1648,7 +1658,7 @@ mod tests {
let conn_closed = dbg!(ep2_connect.await.anyerr()??);
assert!(matches!(
conn_closed,
ConnectionError::ApplicationClosed(quinn::ApplicationClose { .. })
ConnectionError::ApplicationClosed(ApplicationClose { .. })
));

Ok(())
Expand All @@ -1668,7 +1678,7 @@ mod tests {
relay_map: RelayMap,
node_addr_rx: oneshot::Receiver<EndpointAddr>,
qlog: Arc<QlogFileGroup>,
) -> Result<quinn::ConnectionError> {
) -> Result<ConnectionError> {
let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
let secret = SecretKey::generate(&mut rng);
let ep = Endpoint::builder()
Expand Down Expand Up @@ -1744,7 +1754,7 @@ mod tests {
let conn_closed = dbg!(client_task.await.anyerr()??);
assert!(matches!(
conn_closed,
ConnectionError::ApplicationClosed(quinn::ApplicationClose { .. })
ConnectionError::ApplicationClosed(ApplicationClose { .. })
));

Ok(())
Expand All @@ -1762,7 +1772,7 @@ mod tests {
async fn connect(
relay_map: RelayMap,
node_addr_rx: oneshot::Receiver<EndpointAddr>,
) -> Result<quinn::ConnectionError> {
) -> Result<ConnectionError> {
let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
let secret = SecretKey::generate(&mut rng);
let ep = Endpoint::builder()
Expand Down Expand Up @@ -1841,7 +1851,7 @@ mod tests {
let conn_closed = dbg!(client_task.await.anyerr()??);
assert!(matches!(
conn_closed,
ConnectionError::ApplicationClosed(quinn::ApplicationClose { .. })
ConnectionError::ApplicationClosed(ApplicationClose { .. })
));

Ok(())
Expand Down Expand Up @@ -1908,7 +1918,7 @@ mod tests {
async fn accept(
relay_map: RelayMap,
node_addr_tx: oneshot::Sender<EndpointAddr>,
) -> Result<quinn::ConnectionError> {
) -> Result<ConnectionError> {
let secret = SecretKey::from([1u8; 32]);
let ep = Endpoint::builder()
.secret_key(secret)
Expand Down Expand Up @@ -1956,7 +1966,7 @@ mod tests {
let conn_closed = dbg!(server_task.await.anyerr()??);
assert!(matches!(
conn_closed,
ConnectionError::ApplicationClosed(quinn::ApplicationClose { .. })
ConnectionError::ApplicationClosed(ApplicationClose { .. })
));

Ok(())
Expand Down
Loading
Loading