The Endpoint allows establishing connections to other iroh nodes.
+
iroh::endpoint - Rust Module endpoint Copy item path Source Expand description The Endpoint allows establishing connections to other iroh nodes.
The Endpoint is the main API interface to manage a local iroh node. It allows
connecting to and accepting connections from other nodes. See the module docs for
more details on how iroh connections work.
diff --git a/pr/3434/docs/src/iroh/discovery/pkarr/dht.rs.html b/pr/3434/docs/src/iroh/discovery/pkarr/dht.rs.html
index c6b7aecacc..b994019d54 100644
--- a/pr/3434/docs/src/iroh/discovery/pkarr/dht.rs.html
+++ b/pr/3434/docs/src/iroh/discovery/pkarr/dht.rs.html
@@ -216,7 +216,7 @@
216 }
217 if let Some (url) =
& self .pkarr_relay {
218 builder
-
219 .relays(
& [url.clone()])
+
219 .relays(std::slice::from_ref(url))
220 .map_err(|e| IntoDiscoveryError::from_err(
"pkarr" , e))
? ;
221 }
222 builder
diff --git a/pr/3434/docs/src/iroh/endpoint.rs.html b/pr/3434/docs/src/iroh/endpoint.rs.html
index 0adb820b6b..3c07e4fa36 100644
--- a/pr/3434/docs/src/iroh/endpoint.rs.html
+++ b/pr/3434/docs/src/iroh/endpoint.rs.html
@@ -3197,76 +3197,78 @@
3197 Ok (())
3198 }
3199
-
3200 #[tokio::test]
-3202 #[traced_test]
-3203 async fn connect_multi_time() ->
Result {
-
3204 let n =
32 ;
-
3205
-
3206 const NOOP_ALPN:
& [u8] =
b"noop" ;
-
3207
-
3208 #[derive(Debug, Clone)]
-3209 struct Noop;
-
3210
-
3211 impl ProtocolHandler
for Noop {
-
3212 async fn accept(
& self , connection: Connection) ->
Result <(), AcceptError> {
-
3213 connection.closed().
await ;
-
3214 Ok (())
-
3215 }
-
3216 }
-
3217
-
3218 async fn noop_server() ->
Result <(Router, NodeAddr)> {
-
3219 let endpoint = Endpoint::builder()
-
3220 .relay_mode(RelayMode::Disabled)
-
3221 .bind()
-
3222 .
await
-3223 .e()
? ;
-
3224 let addr = endpoint.node_addr().initialized().
await ;
-
3225 let router = Router::builder(endpoint).accept(NOOP_ALPN, Noop).spawn();
-
3226 Ok ((router, addr))
-
3227 }
-
3228
-
3229 let routers = stream::iter(
0 ..n)
-
3230 .map(|
_ | noop_server())
-
3231 .buffered_unordered(
32 )
-
3232 .collect::<Vec<
_ >>()
-
3233 .
await
-3234 .into_iter()
-
3235 .collect::<
Result <Vec<
_ >,
_ >>()
-
3236 .e()
? ;
-
3237
-
3238 let addrs = routers
-
3239 .iter()
-
3240 .map(|(
_ , addr)| addr.clone())
-
3241 .collect::<Vec<
_ >>();
-
3242 let ids = addrs.iter().map(|addr| addr.node_id).collect::<Vec<
_ >>();
-
3243 let discovery = StaticProvider::from_node_info(addrs);
-
3244 let endpoint = Endpoint::builder()
-
3245 .relay_mode(RelayMode::Disabled)
-
3246 .discovery(discovery)
-
3247 .bind()
-
3248 .
await
-3249 .e()
? ;
-
3250 endpoint.node_addr().initialized().
await ;
-
3254 let t0 = Instant::now();
-
3255 for id
in & ids {
-
3256 let conn = endpoint.connect(
* id, NOOP_ALPN).
await ? ;
-
3257 conn.close(
0u32 .into(),
b"done" );
-
3258 }
-
3259 let dt0 = t0.elapsed().as_secs_f64();
-
3260 let t1 = Instant::now();
-
3261 for id
in & ids {
-
3262 let conn = endpoint.connect(
* id, NOOP_ALPN).
await ? ;
-
3263 conn.close(
0u32 .into(),
b"done" );
-
3264 }
-
3265 let dt1 = t1.elapsed().as_secs_f64();
-
3266
-
3267 println! (
"Round 0: {}s, {}s per connection" , dt0, dt0 / (n
as f64));
-
3268 println! (
"Round 1: {}s, {}s per connection" , dt1, dt1 / (n
as f64));
-
3269 assert! (dt0 / dt1 <
20.0 ,
"First round: {dt0}s, second round {dt1}s" );
-
3270 Ok (())
-
3271 }
-
3272 }
\ No newline at end of file
+
3200 #[tokio::test]
+3206 #[traced_test]
+3207 async fn connect_multi_time() ->
Result {
+
3208 let n =
32 ;
+
3209
+
3210 const NOOP_ALPN:
& [u8] =
b"noop" ;
+
3211
+
3212 #[derive(Debug, Clone)]
+3213 struct Noop;
+
3214
+
3215 impl ProtocolHandler
for Noop {
+
3216 async fn accept(
& self , connection: Connection) ->
Result <(), AcceptError> {
+
3217 connection.closed().
await ;
+
3218 Ok (())
+
3219 }
+
3220 }
+
3221
+
3222 async fn noop_server() ->
Result <(Router, NodeAddr)> {
+
3223 let endpoint = Endpoint::builder()
+
3224 .relay_mode(RelayMode::Disabled)
+
3225 .bind()
+
3226 .
await
+3227 .e()
? ;
+
3228 let addr = endpoint.node_addr().initialized().
await ;
+
3229 let router = Router::builder(endpoint).accept(NOOP_ALPN, Noop).spawn();
+
3230 Ok ((router, addr))
+
3231 }
+
3232
+
3233 let routers = stream::iter(
0 ..n)
+
3234 .map(|
_ | noop_server())
+
3235 .buffered_unordered(
32 )
+
3236 .collect::<Vec<
_ >>()
+
3237 .
await
+3238 .into_iter()
+
3239 .collect::<
Result <Vec<
_ >,
_ >>()
+
3240 .e()
? ;
+
3241
+
3242 let addrs = routers
+
3243 .iter()
+
3244 .map(|(
_ , addr)| addr.clone())
+
3245 .collect::<Vec<
_ >>();
+
3246 let ids = addrs.iter().map(|addr| addr.node_id).collect::<Vec<
_ >>();
+
3247 let discovery = StaticProvider::from_node_info(addrs);
+
3248 let endpoint = Endpoint::builder()
+
3249 .relay_mode(RelayMode::Disabled)
+
3250 .discovery(discovery)
+
3251 .bind()
+
3252 .
await
+3253 .e()
? ;
+
3254 endpoint.node_addr().initialized().
await ;
+
3258 let t0 = Instant::now();
+
3259 for id
in & ids {
+
3260 let conn = endpoint.connect(
* id, NOOP_ALPN).
await ? ;
+
3261 conn.close(
0u32 .into(),
b"done" );
+
3262 }
+
3263 let dt0 = t0.elapsed().as_secs_f64();
+
3264 let t1 = Instant::now();
+
3265 for id
in & ids {
+
3266 let conn = endpoint.connect(
* id, NOOP_ALPN).
await ? ;
+
3267 conn.close(
0u32 .into(),
b"done" );
+
3268 }
+
3269 let dt1 = t1.elapsed().as_secs_f64();
+
3270
+
3271 assert! (dt0 / dt1 <
20.0 ,
"First round: {dt0}s, second round {dt1}s" );
+
3272 Ok (())
+
3273 }
+
3274 }
\ No newline at end of file
diff --git a/pr/3434/docs/src/iroh_relay/server/http_server.rs.html b/pr/3434/docs/src/iroh_relay/server/http_server.rs.html
index 288c9b7760..27b8c04114 100644
--- a/pr/3434/docs/src/iroh_relay/server/http_server.rs.html
+++ b/pr/3434/docs/src/iroh_relay/server/http_server.rs.html
@@ -665,463 +665,463 @@
665 let io = RateLimited::from_cfg(
self .rate_limit, io,
self .metrics.clone())
666 .context(RateLimitingMisconfiguredSnafu)
? ;
667
-
668 self .metrics.accepts.inc();
-
669 let websocket = tokio_websockets::ServerBuilder::new()
-
671 .limits(tokio_websockets::Limits::default().max_payload_len(
Some (MAX_FRAME_SIZE)))
-
672 .serve(io);
-
674
-
675 let mut io = WsBytesFramed { io: websocket };
-
676
-
677 let authentication =
-
678 handshake::serverside(
&mut io, client_auth_header, rand::rngs::OsRng).
await ? ;
-
679
-
680 trace! (
? authentication.mechanism,
"accept: verified authentication" );
-
681
-
682 let is_authorized =
self .access.is_allowed(authentication.client_key).
await ;
-
683 let client_key = authentication.authorize_if(is_authorized,
&mut io).
await ? ;
-
684
-
685 trace! (
"accept: verified authorization" );
-
686
-
687 let io = RelayedStream {
-
688 inner: io,
-
689 key_cache:
self .key_cache.clone(),
-
690 };
-
691
-
692 trace! (
"accept: build client conn" );
-
693 let client_conn_builder = Config {
-
694 node_id: client_key,
-
695 stream: io,
-
696 write_timeout:
self .write_timeout,
-
697 channel_capacity: PER_CLIENT_SEND_QUEUE_DEPTH,
-
698 };
-
699 trace! (
"accept: create client" );
-
700 let node_id = client_conn_builder.node_id;
-
701 trace! (node_id = node_id.fmt_short(),
"create client" );
-
702
-
703 self .clients
-
706 .register(client_conn_builder,
self .metrics.clone())
-
707 .
await ;
-
708 Ok (())
-
709 }
-
710 }
-
711
-
712 #[derive(Clone, derive_more::Debug)]
-714 pub (
super )
enum TlsAcceptor {
-
715 LetsEncrypt(
#[debug("tokio_rustls_acme::AcmeAcceptor" )] AcmeAcceptor),
-
717 Manual(
#[debug("tokio_rustls::TlsAcceptor" )] tokio_rustls::TlsAcceptor),
-
720 }
-
721
-
722 impl RelayService {
-
723 fn new(
-
724 handlers: Handlers,
-
725 headers: HeaderMap,
-
726 rate_limit:
Option <ClientRateLimit>,
-
727 key_cache: KeyCache,
-
728 access: AccessConfig,
-
729 metrics: Arc<Metrics>,
-
730 ) ->
Self {
-
731 Self (Arc::new(Inner {
-
732 handlers,
-
733 headers,
-
734 clients: Clients::default(),
-
735 write_timeout: SERVER_WRITE_TIMEOUT,
-
736 rate_limit,
-
737 key_cache,
-
738 access,
-
739 metrics,
-
740 }))
-
741 }
-
742
-
743 async fn shutdown(
& self ) {
-
744 self .
0 .clients.shutdown().
await ;
-
745 }
-
746
-
747 async fn handle_connection(
self , stream: TcpStream, tls_config:
Option <TlsConfig>) {
-
751 let res =
match tls_config {
-
752 Some (tls_config) => {
-
753 debug! (
"HTTPS: serve connection" );
-
754 self .tls_serve_connection(stream, tls_config).
await
-755 }
-
756 None => {
-
757 debug! (
"HTTP: serve connection" );
-
758 self .serve_connection(MaybeTlsStream::Plain(stream))
-
759 .
await
-760 .context(HttpSnafu)
-
761 }
-
762 };
-
763 match res {
-
764 Ok (()) => {}
-
765 Err (error) =>
match error {
-
766 ServeConnectionError::ManualAccept { source, .. }
-
767 | ServeConnectionError::LetsEncryptAccept { source, .. }
-
768 if source.kind() == std::io::ErrorKind::UnexpectedEof =>
-
769 {
-
770 debug! (reason=
? source,
"peer disconnected" );
-
771 }
-
772 ServeConnectionError::Https { source, .. }
-
775 | ServeConnectionError::Http { source, .. }
-
776 if source.is_incomplete_message() =>
-
777 {
-
778 debug! (reason=
? source,
"peer disconnected" );
-
779 }
-
780 _ => {
-
781 error! (
? error,
"failed to handle connection" );
-
782 }
-
783 },
-
784 }
-
785 }
-
786
-
787 async fn tls_serve_connection(
-
789 self ,
-
790 stream: TcpStream,
-
791 tls_config: TlsConfig,
-
792 ) ->
Result <(), ServeConnectionError> {
-
793 let TlsConfig { acceptor, config } = tls_config;
-
794 match acceptor {
-
795 TlsAcceptor::LetsEncrypt(a) => {
-
796 match a.accept(stream).
await .context(LetsEncryptAcceptSnafu)
? {
-
797 None => {
-
798 info! (
"TLS[acme]: received TLS-ALPN-01 validation request" );
-
799 }
-
800 Some (start_handshake) => {
-
801 debug! (
"TLS[acme]: start handshake" );
-
802 let tls_stream = start_handshake
-
803 .into_stream(config)
-
804 .
await
-805 .context(TlsHandshakeSnafu)
? ;
-
806 self .serve_connection(MaybeTlsStream::Tls(tls_stream))
-
807 .
await
-808 .context(HttpsSnafu)
? ;
-
809 }
-
810 }
-
811 }
-
812 TlsAcceptor::Manual(a) => {
-
813 debug! (
"TLS[manual]: accept" );
-
814 let tls_stream = tokio::time::timeout(Duration::from_secs(
30 ), a.accept(stream))
-
815 .
await
-816 .context(TimeoutSnafu)
?
-817 .context(ManualAcceptSnafu)
? ;
-
818
-
819 self .serve_connection(MaybeTlsStream::Tls(tls_stream))
-
820 .
await
-821 .context(ServeConnectionSnafu)
? ;
-
822 }
-
823 }
-
824 Ok (())
-
825 }
-
826
-
827 async fn serve_connection<I>(
self , io: I) ->
Result <(), hyper::Error>
-
829 where
-830 I: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + Sync +
'static ,
-
831 {
-
832 hyper::server::conn::http1::Builder::new()
-
833 .serve_connection(hyper_util::rt::TokioIo::new(io),
self )
-
834 .with_upgrades()
-
835 .
await
-836 }
-
837 }
-
838
-
839 #[derive(Default)]
-840 struct Handlers(HashMap<(Method,
& 'static str), HyperHandler>);
-
841
-
842 impl std::fmt::Debug
for Handlers {
-
843 fn fmt(
& self , f:
&mut std::fmt::Formatter<
'_ >) -> std::fmt::Result {
-
844 let s =
self .
0 .keys().fold(String::new(), |curr, next| {
-
845 let (method, uri) = next;
-
846 format! (
"{curr}\n({method},{uri}): Box<Fn(ResponseBuilder) -> Result<Response<Body>> + Send + Sync + 'static>" )
-
847 });
-
848 write! (f,
"HashMap<{s}>" )
-
849 }
-
850 }
-
851
-
852 impl std::ops::Deref
for Handlers {
-
853 type Target = HashMap<(Method,
& 'static str), HyperHandler>;
-
854
-
855 fn deref(
& self ) ->
& Self ::Target {
-
856 & self .
0
-857 }
-
858 }
-
859
-
860 impl std::ops::DerefMut
for Handlers {
-
861 fn deref_mut(
&mut self ) ->
&mut Self ::Target {
-
862 &mut self .
0
-863 }
-
864 }
-
865
-
866 #[cfg(test)]
-867 mod tests {
-
868 use std::sync::Arc;
-
869
-
870 use iroh_base::{PublicKey, SecretKey};
-
871 use n0_future::{SinkExt, StreamExt};
-
872 use n0_snafu::{
Result , ResultExt};
-
873 use reqwest::Url;
-
874 use snafu::whatever;
-
875 use tracing::info;
-
876 use tracing_test::traced_test;
-
877
-
878 use super ::
* ;
-
879 use crate ::{
-
880 client::{Client, ClientBuilder, ConnectError, conn::Conn},
-
881 dns::DnsResolver,
-
882 protos::relay::{ClientToRelayMsg, Datagrams, RelayToClientMsg},
-
883 };
-
884
-
885 pub (
crate )
fn make_tls_config() -> TlsConfig {
-
886 let subject_alt_names =
vec! [
"localhost" .to_string()];
-
887
-
888 let cert = rcgen::generate_simple_self_signed(subject_alt_names).unwrap();
-
889 let rustls_certificate = cert.cert.der().clone();
-
890 let rustls_key =
-
891 rustls::pki_types::PrivatePkcs8KeyDer::from(cert.signing_key.serialize_der());
-
892 let config = rustls::ServerConfig::builder_with_provider(Arc::new(
-
893 rustls::crypto::ring::default_provider(),
-
894 ))
-
895 .with_safe_default_protocol_versions()
-
896 .expect(
"protocols supported by ring" )
-
897 .with_no_client_auth()
-
898 .with_single_cert(
vec! [(rustls_certificate)], rustls_key.into())
-
899 .expect(
"cert is right" );
-
900
-
901 let config = Arc::new(config);
-
902 let acceptor = tokio_rustls::TlsAcceptor::from(config.clone());
-
903
-
904 TlsConfig {
-
905 config,
-
906 acceptor: TlsAcceptor::Manual(acceptor),
-
907 }
-
908 }
-
909
-
910 #[tokio::test]
-911 #[traced_test]
-912 async fn test_http_clients_and_server() ->
Result {
-
913 let a_key = SecretKey::generate(rand::thread_rng());
-
914 let b_key = SecretKey::generate(rand::thread_rng());
-
915
-
916 let server = ServerBuilder::new(
"127.0.0.1:0" .parse().unwrap())
-
918 .spawn()
-
919 .
await ? ;
-
920
-
921 let addr = server.addr();
-
922
-
923 let port = addr.port();
-
925 let addr =
if let std::net::IpAddr::V4(ipv4_addr) = addr.ip() {
-
926 ipv4_addr
-
927 }
else {
-
928 whatever! (
"cannot get ipv4 addr from socket addr {addr:?}" );
-
929 };
-
930
-
931 info! (
"addr: {addr}:{port}" );
-
932 let relay_addr: Url =
format! (
"http://{addr}:{port}" ).parse().unwrap();
-
933
-
934 let (a_key,
mut client_a) = create_test_client(a_key, relay_addr.clone()).
await ? ;
-
936 info! (
"created client {a_key:?}" );
-
937 let (b_key,
mut client_b) = create_test_client(b_key, relay_addr).
await ? ;
-
938 info! (
"created client {b_key:?}" );
-
939
-
940 info! (
"ping a" );
-
941 client_a.send(ClientToRelayMsg::Ping([
1u8 ;
8 ])).
await ? ;
-
942 let pong = client_a.next().
await .expect(
"eos" )
? ;
-
943 assert! (
matches! (pong, RelayToClientMsg::Pong { .. }));
-
944
-
945 info! (
"ping b" );
-
946 client_b.send(ClientToRelayMsg::Ping([
2u8 ;
8 ])).
await ? ;
-
947 let pong = client_b.next().
await .expect(
"eos" )
? ;
-
948 assert! (
matches! (pong, RelayToClientMsg::Pong { .. }));
-
949
-
950 info! (
"sending message from a to b" );
-
951 let msg = Datagrams::from(
b"hi there, client b!" );
-
952 client_a
-
953 .send(ClientToRelayMsg::Datagrams {
-
954 dst_node_id: b_key,
-
955 datagrams: msg.clone(),
-
956 })
-
957 .
await ? ;
-
958 info! (
"waiting for message from a on b" );
-
959 let (got_key, got_msg) =
-
960 process_msg(client_b.next().
await ).expect(
"expected message from client_a" );
-
961 assert_eq! (a_key, got_key);
-
962 assert_eq! (msg, got_msg);
-
963
-
964 info! (
"sending message from b to a" );
-
965 let msg = Datagrams::from(
b"right back at ya, client b!" );
-
966 client_b
-
967 .send(ClientToRelayMsg::Datagrams {
-
968 dst_node_id: a_key,
-
969 datagrams: msg.clone(),
-
970 })
-
971 .
await ? ;
-
972 info! (
"waiting for message b on a" );
-
973 let (got_key, got_msg) =
-
974 process_msg(client_a.next().
await ).expect(
"expected message from client_b" );
-
975 assert_eq! (b_key, got_key);
-
976 assert_eq! (msg, got_msg);
-
977
-
978 client_a.close().
await ? ;
-
980 client_b.close().
await ? ;
-
981 server.shutdown();
-
982
-
983 Ok (())
-
984 }
-
985
-
986 async fn create_test_client(
-
987 key: SecretKey,
-
988 server_url: Url,
-
989 ) ->
Result <(PublicKey, Client), ConnectError> {
-
990 let public_key = key.public();
-
991 let client =
-
992 ClientBuilder::new(server_url, key, DnsResolver::new()).insecure_skip_cert_verify(
true );
-
993 let client = client.connect().
await ? ;
-
994
-
995 Ok ((public_key, client))
-
996 }
-
997
-
998 fn process_msg(
-
999 msg:
Option <
Result <RelayToClientMsg,
crate ::client::RecvError>>,
-
1000 ) ->
Option <(PublicKey, Datagrams)> {
-
1001 match msg {
-
1002 Some (
Err (e)) => {
-
1003 info! (
"client `recv` error {e}" );
-
1004 None
-1005 }
-
1006 Some (
Ok (msg)) => {
-
1007 info! (
"got message on: {msg:?}" );
-
1008 if let RelayToClientMsg::Datagrams {
-
1009 remote_node_id: source,
-
1010 datagrams,
-
1011 } = msg
-
1012 {
-
1013 Some ((source, datagrams))
-
1014 }
else {
-
1015 None
-1016 }
-
1017 }
-
1018 None => {
-
1019 info! (
"client end of stream" );
-
1020 None
-1021 }
-
1022 }
-
1023 }
-
1024
-
1025 #[tokio::test]
-1026 #[traced_test]
-1027 async fn test_https_clients_and_server() ->
Result {
-
1028 let a_key = SecretKey::generate(rand::thread_rng());
-
1029 let b_key = SecretKey::generate(rand::thread_rng());
-
1030
-
1031 let tls_config = make_tls_config();
-
1033
-
1034 let mut server = ServerBuilder::new(
"127.0.0.1:0" .parse().unwrap())
-
1036 .tls_config(
Some (tls_config))
-
1037 .spawn()
-
1038 .
await ? ;
-
1039
-
1040 let addr = server.addr();
-
1041
-
1042 let port = addr.port();
-
1044 let addr =
if let std::net::IpAddr::V4(ipv4_addr) = addr.ip() {
-
1045 ipv4_addr
-
1046 }
else {
-
1047 whatever! (
"cannot get ipv4 addr from socket addr {addr:?}" );
-
1048 };
-
1049
-
1050 info! (
"Relay listening on: {addr}:{port}" );
-
1051
-
1052 let url: Url =
format! (
"https://localhost:{port}" ).parse().unwrap();
-
1053
-
1054 let (a_key,
mut client_a) = create_test_client(a_key, url.clone()).
await ? ;
-
1056 info! (
"created client {a_key:?}" );
-
1057 let (b_key,
mut client_b) = create_test_client(b_key, url).
await ? ;
-
1058 info! (
"created client {b_key:?}" );
-
1059
-
1060 info! (
"ping a" );
-
1061 client_a.send(ClientToRelayMsg::Ping([
1u8 ;
8 ])).
await ? ;
-
1062 let pong = client_a.next().
await .expect(
"eos" )
? ;
-
1063 assert! (
matches! (pong, RelayToClientMsg::Pong { .. }));
-
1064
-
1065 info! (
"ping b" );
-
1066 client_b.send(ClientToRelayMsg::Ping([
2u8 ;
8 ])).
await ? ;
-
1067 let pong = client_b.next().
await .expect(
"eos" )
? ;
-
1068 assert! (
matches! (pong, RelayToClientMsg::Pong { .. }));
-
1069
-
1070 info! (
"sending message from a to b" );
-
1071 let msg = Datagrams::from(
b"hi there, client b!" );
-
1072 client_a
-
1073 .send(ClientToRelayMsg::Datagrams {
-
1074 dst_node_id: b_key,
-
1075 datagrams: msg.clone(),
-
1076 })
-
1077 .
await ? ;
-
1078 info! (
"waiting for message from a on b" );
-
1079 let (got_key, got_msg) =
-
1080 process_msg(client_b.next().
await ).expect(
"expected message from client_a" );
-
1081 assert_eq! (a_key, got_key);
-
1082 assert_eq! (msg, got_msg);
-
1083
-
1084 info! (
"sending message from b to a" );
-
1085 let msg = Datagrams::from(
b"right back at ya, client b!" );
-
1086 client_b
-
1087 .send(ClientToRelayMsg::Datagrams {
-
1088 dst_node_id: a_key,
-
1089 datagrams: msg.clone(),
-
1090 })
-
1091 .
await ? ;
-
1092 info! (
"waiting for message b on a" );
-
1093 let (got_key, got_msg) =
-
1094 process_msg(client_a.next().
await ).expect(
"expected message from client_b" );
-
1095 assert_eq! (b_key, got_key);
-
1096 assert_eq! (msg, got_msg);
-
1097
-
1098 client_a.close().
await ? ;
-
1100 client_b.close().
await ? ;
-
1101 server.shutdown();
-
1102 server.task_handle().
await .context(
"join" )
? ;
-
1103
-
1104 Ok (())
-
1105 }
-
1106
-
1107 async fn make_test_client(client: tokio::io::DuplexStream, key:
& SecretKey) ->
Result <Conn> {
-
1108 let client =
crate ::client::streams::MaybeTlsStream::Test(client);
-
1109 let client = tokio_websockets::ClientBuilder::new().take_over(client);
-
1110 let client = Conn::new(client, KeyCache::test(), key).
await ? ;
-
1111 Ok (client)
-
1112 }
-
1113
-
1114 #[tokio::test]
-1115 #[traced_test]
-1116 async fn test_server_basic() ->
Result {
-
1117 info! (
"Create the server." );
+
668 let websocket = tokio_websockets::ServerBuilder::new()
+
670 .limits(tokio_websockets::Limits::default().max_payload_len(
Some (MAX_FRAME_SIZE)))
+
671 .serve(io);
+
673
+
674 let mut io = WsBytesFramed { io: websocket };
+
675
+
676 let authentication =
+
677 handshake::serverside(
&mut io, client_auth_header, rand::rngs::OsRng).
await ? ;
+
678
+
679 trace! (
? authentication.mechanism,
"accept: verified authentication" );
+
680
+
681 let is_authorized =
self .access.is_allowed(authentication.client_key).
await ;
+
682 let client_key = authentication.authorize_if(is_authorized,
&mut io).
await ? ;
+
683
+
684 trace! (
"accept: verified authorization" );
+
685
+
686 let io = RelayedStream {
+
687 inner: io,
+
688 key_cache:
self .key_cache.clone(),
+
689 };
+
690
+
691 trace! (
"accept: build client conn" );
+
692 let client_conn_builder = Config {
+
693 node_id: client_key,
+
694 stream: io,
+
695 write_timeout:
self .write_timeout,
+
696 channel_capacity: PER_CLIENT_SEND_QUEUE_DEPTH,
+
697 };
+
698 trace! (
"accept: create client" );
+
699 let node_id = client_conn_builder.node_id;
+
700 trace! (node_id = node_id.fmt_short(),
"create client" );
+
701
+
702 self .clients
+
705 .register(client_conn_builder,
self .metrics.clone())
+
706 .
await ;
+
707 Ok (())
+
708 }
+
709 }
+
710
+
711 #[derive(Clone, derive_more::Debug)]
+713 pub (
super )
enum TlsAcceptor {
+
714 LetsEncrypt(
#[debug("tokio_rustls_acme::AcmeAcceptor" )] AcmeAcceptor),
+
716 Manual(
#[debug("tokio_rustls::TlsAcceptor" )] tokio_rustls::TlsAcceptor),
+
719 }
+
720
+
721 impl RelayService {
+
722 fn new(
+
723 handlers: Handlers,
+
724 headers: HeaderMap,
+
725 rate_limit:
Option <ClientRateLimit>,
+
726 key_cache: KeyCache,
+
727 access: AccessConfig,
+
728 metrics: Arc<Metrics>,
+
729 ) ->
Self {
+
730 Self (Arc::new(Inner {
+
731 handlers,
+
732 headers,
+
733 clients: Clients::default(),
+
734 write_timeout: SERVER_WRITE_TIMEOUT,
+
735 rate_limit,
+
736 key_cache,
+
737 access,
+
738 metrics,
+
739 }))
+
740 }
+
741
+
742 async fn shutdown(
& self ) {
+
743 self .
0 .clients.shutdown().
await ;
+
744 }
+
745
+
746 async fn handle_connection(
self , stream: TcpStream, tls_config:
Option <TlsConfig>) {
+
750 let res =
match tls_config {
+
751 Some (tls_config) => {
+
752 debug! (
"HTTPS: serve connection" );
+
753 self .tls_serve_connection(stream, tls_config).
await
+754 }
+
755 None => {
+
756 debug! (
"HTTP: serve connection" );
+
757 self .serve_connection(MaybeTlsStream::Plain(stream))
+
758 .
await
+759 .context(HttpSnafu)
+
760 }
+
761 };
+
762 match res {
+
763 Ok (()) => {}
+
764 Err (error) =>
match error {
+
765 ServeConnectionError::ManualAccept { source, .. }
+
766 | ServeConnectionError::LetsEncryptAccept { source, .. }
+
767 if source.kind() == std::io::ErrorKind::UnexpectedEof =>
+
768 {
+
769 debug! (reason=
? source,
"peer disconnected" );
+
770 }
+
771 ServeConnectionError::Https { source, .. }
+
774 | ServeConnectionError::Http { source, .. }
+
775 if source.is_incomplete_message() =>
+
776 {
+
777 debug! (reason=
? source,
"peer disconnected" );
+
778 }
+
779 _ => {
+
780 error! (
? error,
"failed to handle connection" );
+
781 }
+
782 },
+
783 }
+
784 }
+
785
+
786 async fn tls_serve_connection(
+
788 self ,
+
789 stream: TcpStream,
+
790 tls_config: TlsConfig,
+
791 ) ->
Result <(), ServeConnectionError> {
+
792 let TlsConfig { acceptor, config } = tls_config;
+
793 match acceptor {
+
794 TlsAcceptor::LetsEncrypt(a) => {
+
795 match a.accept(stream).
await .context(LetsEncryptAcceptSnafu)
? {
+
796 None => {
+
797 info! (
"TLS[acme]: received TLS-ALPN-01 validation request" );
+
798 }
+
799 Some (start_handshake) => {
+
800 debug! (
"TLS[acme]: start handshake" );
+
801 let tls_stream = start_handshake
+
802 .into_stream(config)
+
803 .
await
+804 .context(TlsHandshakeSnafu)
? ;
+
805 self .serve_connection(MaybeTlsStream::Tls(tls_stream))
+
806 .
await
+807 .context(HttpsSnafu)
? ;
+
808 }
+
809 }
+
810 }
+
811 TlsAcceptor::Manual(a) => {
+
812 debug! (
"TLS[manual]: accept" );
+
813 let tls_stream = tokio::time::timeout(Duration::from_secs(
30 ), a.accept(stream))
+
814 .
await
+815 .context(TimeoutSnafu)
?
+816 .context(ManualAcceptSnafu)
? ;
+
817
+
818 self .serve_connection(MaybeTlsStream::Tls(tls_stream))
+
819 .
await
+820 .context(ServeConnectionSnafu)
? ;
+
821 }
+
822 }
+
823 Ok (())
+
824 }
+
825
+
826 async fn serve_connection<I>(
self , io: I) ->
Result <(), hyper::Error>
+
828 where
+829 I: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + Sync +
'static ,
+
830 {
+
831 hyper::server::conn::http1::Builder::new()
+
832 .serve_connection(hyper_util::rt::TokioIo::new(io),
self )
+
833 .with_upgrades()
+
834 .
await
+835 }
+
836 }
+
837
+
838 #[derive(Default)]
+839 struct Handlers(HashMap<(Method,
& 'static str), HyperHandler>);
+
840
+
841 impl std::fmt::Debug
for Handlers {
+
842 fn fmt(
& self , f:
&mut std::fmt::Formatter<
'_ >) -> std::fmt::Result {
+
843 let s =
self .
0 .keys().fold(String::new(), |curr, next| {
+
844 let (method, uri) = next;
+
845 format! (
"{curr}\n({method},{uri}): Box<Fn(ResponseBuilder) -> Result<Response<Body>> + Send + Sync + 'static>" )
+
846 });
+
847 write! (f,
"HashMap<{s}>" )
+
848 }
+
849 }
+
850
+
851 impl std::ops::Deref
for Handlers {
+
852 type Target = HashMap<(Method,
& 'static str), HyperHandler>;
+
853
+
854 fn deref(
& self ) ->
& Self ::Target {
+
855 & self .
0
+856 }
+
857 }
+
858
+
859 impl std::ops::DerefMut
for Handlers {
+
860 fn deref_mut(
&mut self ) ->
&mut Self ::Target {
+
861 &mut self .
0
+862 }
+
863 }
+
864
+
865 #[cfg(test)]
+866 mod tests {
+
867 use std::sync::Arc;
+
868
+
869 use iroh_base::{PublicKey, SecretKey};
+
870 use n0_future::{SinkExt, StreamExt};
+
871 use n0_snafu::{
Result , ResultExt};
+
872 use reqwest::Url;
+
873 use snafu::whatever;
+
874 use tracing::info;
+
875 use tracing_test::traced_test;
+
876
+
877 use super ::
* ;
+
878 use crate ::{
+
879 client::{Client, ClientBuilder, ConnectError, conn::Conn},
+
880 dns::DnsResolver,
+
881 protos::relay::{ClientToRelayMsg, Datagrams, RelayToClientMsg},
+
882 };
+
883
+
884 pub (
crate )
fn make_tls_config() -> TlsConfig {
+
885 let subject_alt_names =
vec! [
"localhost" .to_string()];
+
886
+
887 let cert = rcgen::generate_simple_self_signed(subject_alt_names).unwrap();
+
888 let rustls_certificate = cert.cert.der().clone();
+
889 let rustls_key =
+
890 rustls::pki_types::PrivatePkcs8KeyDer::from(cert.signing_key.serialize_der());
+
891 let config = rustls::ServerConfig::builder_with_provider(Arc::new(
+
892 rustls::crypto::ring::default_provider(),
+
893 ))
+
894 .with_safe_default_protocol_versions()
+
895 .expect(
"protocols supported by ring" )
+
896 .with_no_client_auth()
+
897 .with_single_cert(
vec! [(rustls_certificate)], rustls_key.into())
+
898 .expect(
"cert is right" );
+
899
+
900 let config = Arc::new(config);
+
901 let acceptor = tokio_rustls::TlsAcceptor::from(config.clone());
+
902
+
903 TlsConfig {
+
904 config,
+
905 acceptor: TlsAcceptor::Manual(acceptor),
+
906 }
+
907 }
+
908
+
909 #[tokio::test]
+910 #[traced_test]
+911 async fn test_http_clients_and_server() ->
Result {
+
912 let a_key = SecretKey::generate(rand::thread_rng());
+
913 let b_key = SecretKey::generate(rand::thread_rng());
+
914
+
915 let server = ServerBuilder::new(
"127.0.0.1:0" .parse().unwrap())
+
917 .spawn()
+
918 .
await ? ;
+
919
+
920 let addr = server.addr();
+
921
+
922 let port = addr.port();
+
924 let addr =
if let std::net::IpAddr::V4(ipv4_addr) = addr.ip() {
+
925 ipv4_addr
+
926 }
else {
+
927 whatever! (
"cannot get ipv4 addr from socket addr {addr:?}" );
+
928 };
+
929
+
930 info! (
"addr: {addr}:{port}" );
+
931 let relay_addr: Url =
format! (
"http://{addr}:{port}" ).parse().unwrap();
+
932
+
933 let (a_key,
mut client_a) = create_test_client(a_key, relay_addr.clone()).
await ? ;
+
935 info! (
"created client {a_key:?}" );
+
936 let (b_key,
mut client_b) = create_test_client(b_key, relay_addr).
await ? ;
+
937 info! (
"created client {b_key:?}" );
+
938
+
939 info! (
"ping a" );
+
940 client_a.send(ClientToRelayMsg::Ping([
1u8 ;
8 ])).
await ? ;
+
941 let pong = client_a.next().
await .expect(
"eos" )
? ;
+
942 assert! (
matches! (pong, RelayToClientMsg::Pong { .. }));
+
943
+
944 info! (
"ping b" );
+
945 client_b.send(ClientToRelayMsg::Ping([
2u8 ;
8 ])).
await ? ;
+
946 let pong = client_b.next().
await .expect(
"eos" )
? ;
+
947 assert! (
matches! (pong, RelayToClientMsg::Pong { .. }));
+
948
+
949 info! (
"sending message from a to b" );
+
950 let msg = Datagrams::from(
b"hi there, client b!" );
+
951 client_a
+
952 .send(ClientToRelayMsg::Datagrams {
+
953 dst_node_id: b_key,
+
954 datagrams: msg.clone(),
+
955 })
+
956 .
await ? ;
+
957 info! (
"waiting for message from a on b" );
+
958 let (got_key, got_msg) =
+
959 process_msg(client_b.next().
await ).expect(
"expected message from client_a" );
+
960 assert_eq! (a_key, got_key);
+
961 assert_eq! (msg, got_msg);
+
962
+
963 info! (
"sending message from b to a" );
+
964 let msg = Datagrams::from(
b"right back at ya, client b!" );
+
965 client_b
+
966 .send(ClientToRelayMsg::Datagrams {
+
967 dst_node_id: a_key,
+
968 datagrams: msg.clone(),
+
969 })
+
970 .
await ? ;
+
971 info! (
"waiting for message b on a" );
+
972 let (got_key, got_msg) =
+
973 process_msg(client_a.next().
await ).expect(
"expected message from client_b" );
+
974 assert_eq! (b_key, got_key);
+
975 assert_eq! (msg, got_msg);
+
976
+
977 client_a.close().
await ? ;
+
979 client_b.close().
await ? ;
+
980 server.shutdown();
+
981
+
982 Ok (())
+
983 }
+
984
+
985 async fn create_test_client(
+
986 key: SecretKey,
+
987 server_url: Url,
+
988 ) ->
Result <(PublicKey, Client), ConnectError> {
+
989 let public_key = key.public();
+
990 let client =
+
991 ClientBuilder::new(server_url, key, DnsResolver::new()).insecure_skip_cert_verify(
true );
+
992 let client = client.connect().
await ? ;
+
993
+
994 Ok ((public_key, client))
+
995 }
+
996
+
997 fn process_msg(
+
998 msg:
Option <
Result <RelayToClientMsg,
crate ::client::RecvError>>,
+
999 ) ->
Option <(PublicKey, Datagrams)> {
+
1000 match msg {
+
1001 Some (
Err (e)) => {
+
1002 info! (
"client `recv` error {e}" );
+
1003 None
+1004 }
+
1005 Some (
Ok (msg)) => {
+
1006 info! (
"got message on: {msg:?}" );
+
1007 if let RelayToClientMsg::Datagrams {
+
1008 remote_node_id: source,
+
1009 datagrams,
+
1010 } = msg
+
1011 {
+
1012 Some ((source, datagrams))
+
1013 }
else {
+
1014 None
+1015 }
+
1016 }
+
1017 None => {
+
1018 info! (
"client end of stream" );
+
1019 None
+1020 }
+
1021 }
+
1022 }
+
1023
+
1024 #[tokio::test]
+1025 #[traced_test]
+1026 async fn test_https_clients_and_server() ->
Result {
+
1027 let a_key = SecretKey::generate(rand::thread_rng());
+
1028 let b_key = SecretKey::generate(rand::thread_rng());
+
1029
+
1030 let tls_config = make_tls_config();
+
1032
+
1033 let mut server = ServerBuilder::new(
"127.0.0.1:0" .parse().unwrap())
+
1035 .tls_config(
Some (tls_config))
+
1036 .spawn()
+
1037 .
await ? ;
+
1038
+
1039 let addr = server.addr();
+
1040
+
1041 let port = addr.port();
+
1043 let addr =
if let std::net::IpAddr::V4(ipv4_addr) = addr.ip() {
+
1044 ipv4_addr
+
1045 }
else {
+
1046 whatever! (
"cannot get ipv4 addr from socket addr {addr:?}" );
+
1047 };
+
1048
+
1049 info! (
"Relay listening on: {addr}:{port}" );
+
1050
+
1051 let url: Url =
format! (
"https://localhost:{port}" ).parse().unwrap();
+
1052
+
1053 let (a_key,
mut client_a) = create_test_client(a_key, url.clone()).
await ? ;
+
1055 info! (
"created client {a_key:?}" );
+
1056 let (b_key,
mut client_b) = create_test_client(b_key, url).
await ? ;
+
1057 info! (
"created client {b_key:?}" );
+
1058
+
1059 info! (
"ping a" );
+
1060 client_a.send(ClientToRelayMsg::Ping([
1u8 ;
8 ])).
await ? ;
+
1061 let pong = client_a.next().
await .expect(
"eos" )
? ;
+
1062 assert! (
matches! (pong, RelayToClientMsg::Pong { .. }));
+
1063
+
1064 info! (
"ping b" );
+
1065 client_b.send(ClientToRelayMsg::Ping([
2u8 ;
8 ])).
await ? ;
+
1066 let pong = client_b.next().
await .expect(
"eos" )
? ;
+
1067 assert! (
matches! (pong, RelayToClientMsg::Pong { .. }));
+
1068
+
1069 info! (
"sending message from a to b" );
+
1070 let msg = Datagrams::from(
b"hi there, client b!" );
+
1071 client_a
+
1072 .send(ClientToRelayMsg::Datagrams {
+
1073 dst_node_id: b_key,
+
1074 datagrams: msg.clone(),
+
1075 })
+
1076 .
await ? ;
+
1077 info! (
"waiting for message from a on b" );
+
1078 let (got_key, got_msg) =
+
1079 process_msg(client_b.next().
await ).expect(
"expected message from client_a" );
+
1080 assert_eq! (a_key, got_key);
+
1081 assert_eq! (msg, got_msg);
+
1082
+
1083 info! (
"sending message from b to a" );
+
1084 let msg = Datagrams::from(
b"right back at ya, client b!" );
+
1085 client_b
+
1086 .send(ClientToRelayMsg::Datagrams {
+
1087 dst_node_id: a_key,
+
1088 datagrams: msg.clone(),
+
1089 })
+
1090 .
await ? ;
+
1091 info! (
"waiting for message b on a" );
+
1092 let (got_key, got_msg) =
+
1093 process_msg(client_a.next().
await ).expect(
"expected message from client_b" );
+
1094 assert_eq! (b_key, got_key);
+
1095 assert_eq! (msg, got_msg);
+
1096
+
1097 client_a.close().
await ? ;
+
1099 client_b.close().
await ? ;
+
1100 server.shutdown();
+
1101 server.task_handle().
await .context(
"join" )
? ;
+
1102
+
1103 Ok (())
+
1104 }
+
1105
+
1106 async fn make_test_client(client: tokio::io::DuplexStream, key:
& SecretKey) ->
Result <Conn> {
+
1107 let client =
crate ::client::streams::MaybeTlsStream::Test(client);
+
1108 let client = tokio_websockets::ClientBuilder::new().take_over(client);
+
1109 let client = Conn::new(client, KeyCache::test(), key).
await ? ;
+
1110 Ok (client)
+
1111 }
+
1112
+
1113 #[tokio::test]
+1114 #[traced_test]
+1115 async fn test_server_basic() ->
Result {
+
1116 info! (
"Create the server." );
+
1117 let metrics = Arc::new(Metrics::default());
1118 let service = RelayService::new(
1119 Default::default(),
1120 Default::default(),
1121 None ,
1122 KeyCache::test(),
1123 AccessConfig::Everyone,
-
1124 Default::default(),
+
1124 metrics.clone(),
1125 );
1126
1127 info! (
"Create client A and connect it to the server." );
@@ -1199,147 +1199,155 @@
1199 .
await ;
1200 assert! (res.is_err());
1201 assert! (client_b.next().
await .is_none());
-
1202 Ok (())
-
1203 }
-
1204
-
1205 #[tokio::test]
-1206 async fn test_server_replace_client() ->
Result {
-
1207 info! (
"Create the server." );
-
1208 let service = RelayService::new(
-
1209 Default::default(),
-
1210 Default::default(),
-
1211 None ,
-
1212 KeyCache::test(),
-
1213 AccessConfig::Everyone,
-
1214 Default::default(),
-
1215 );
-
1216
-
1217 info! (
"Create client A and connect it to the server." );
-
1218 let key_a = SecretKey::generate(rand::thread_rng());
-
1219 let public_key_a = key_a.public();
-
1220 let (client_a, rw_a) = tokio::io::duplex(
10 );
-
1221 let s = service.clone();
-
1222 let handler_task =
-
1223 tokio::spawn(
async move { s.
0 .accept(MaybeTlsStream::Test(rw_a),
None ).
await });
-
1224 let mut client_a = make_test_client(client_a,
& key_a).
await ? ;
-
1225 handler_task.
await .context(
"join" )
?? ;
-
1226
-
1227 info! (
"Create client B and connect it to the server." );
-
1228 let key_b = SecretKey::generate(rand::thread_rng());
-
1229 let public_key_b = key_b.public();
-
1230 let (client_b, rw_b) = tokio::io::duplex(
10 );
-
1231 let s = service.clone();
-
1232 let handler_task =
-
1233 tokio::spawn(
async move { s.
0 .accept(MaybeTlsStream::Test(rw_b),
None ).
await });
-
1234 let mut client_b = make_test_client(client_b,
& key_b).
await ? ;
-
1235 handler_task.
await .context(
"join" )
?? ;
-
1236
-
1237 info! (
"Send message from A to B." );
-
1238 let msg = Datagrams::from(
b"hello client b!!" );
-
1239 client_a
-
1240 .send(ClientToRelayMsg::Datagrams {
-
1241 dst_node_id: public_key_b,
-
1242 datagrams: msg.clone(),
-
1243 })
-
1244 .
await ? ;
-
1245 match client_b.next().
await .expect(
"eos" )
? {
-
1246 RelayToClientMsg::Datagrams {
-
1247 remote_node_id,
-
1248 datagrams,
-
1249 } => {
-
1250 assert_eq! (public_key_a, remote_node_id);
-
1251 assert_eq! (msg, datagrams);
-
1252 }
-
1253 msg => {
-
1254 whatever! (
"expected ReceivedDatagrams msg, got {msg:?}" );
-
1255 }
-
1256 }
-
1257
-
1258 info! (
"Send message from B to A." );
-
1259 let msg = Datagrams::from(
b"nice to meet you client a!!" );
-
1260 client_b
-
1261 .send(ClientToRelayMsg::Datagrams {
-
1262 dst_node_id: public_key_a,
-
1263 datagrams: msg.clone(),
-
1264 })
-
1265 .
await ? ;
-
1266 match client_a.next().
await .expect(
"eos" )
? {
-
1267 RelayToClientMsg::Datagrams {
-
1268 remote_node_id,
-
1269 datagrams,
-
1270 } => {
-
1271 assert_eq! (public_key_b, remote_node_id);
-
1272 assert_eq! (msg, datagrams);
-
1273 }
-
1274 msg => {
-
1275 whatever! (
"expected ReceivedDatagrams msg, got {msg:?}" );
-
1276 }
-
1277 }
-
1278
-
1279 info! (
"Create client B and connect it to the server" );
-
1280 let (new_client_b, new_rw_b) = tokio::io::duplex(
10 );
-
1281 let s = service.clone();
-
1282 let handler_task =
-
1283 tokio::spawn(
async move { s.
0 .accept(MaybeTlsStream::Test(new_rw_b),
None ).
await });
-
1284 let mut new_client_b = make_test_client(new_client_b,
& key_b).
await ? ;
-
1285 handler_task.
await .context(
"join" )
?? ;
+
1202
+
1203 drop(client_a);
+
1204 drop(client_b);
+
1205
+
1206 service.shutdown().
await ;
+
1207
+
1208 assert_eq! (metrics.accepts.get(), metrics.disconnects.get());
+
1209
+
1210 Ok (())
+
1211 }
+
1212
+
1213 #[tokio::test]
+1214 async fn test_server_replace_client() ->
Result {
+
1215 info! (
"Create the server." );
+
1216 let service = RelayService::new(
+
1217 Default::default(),
+
1218 Default::default(),
+
1219 None ,
+
1220 KeyCache::test(),
+
1221 AccessConfig::Everyone,
+
1222 Default::default(),
+
1223 );
+
1224
+
1225 info! (
"Create client A and connect it to the server." );
+
1226 let key_a = SecretKey::generate(rand::thread_rng());
+
1227 let public_key_a = key_a.public();
+
1228 let (client_a, rw_a) = tokio::io::duplex(
10 );
+
1229 let s = service.clone();
+
1230 let handler_task =
+
1231 tokio::spawn(
async move { s.
0 .accept(MaybeTlsStream::Test(rw_a),
None ).
await });
+
1232 let mut client_a = make_test_client(client_a,
& key_a).
await ? ;
+
1233 handler_task.
await .context(
"join" )
?? ;
+
1234
+
1235 info! (
"Create client B and connect it to the server." );
+
1236 let key_b = SecretKey::generate(rand::thread_rng());
+
1237 let public_key_b = key_b.public();
+
1238 let (client_b, rw_b) = tokio::io::duplex(
10 );
+
1239 let s = service.clone();
+
1240 let handler_task =
+
1241 tokio::spawn(
async move { s.
0 .accept(MaybeTlsStream::Test(rw_b),
None ).
await });
+
1242 let mut client_b = make_test_client(client_b,
& key_b).
await ? ;
+
1243 handler_task.
await .context(
"join" )
?? ;
+
1244
+
1245 info! (
"Send message from A to B." );
+
1246 let msg = Datagrams::from(
b"hello client b!!" );
+
1247 client_a
+
1248 .send(ClientToRelayMsg::Datagrams {
+
1249 dst_node_id: public_key_b,
+
1250 datagrams: msg.clone(),
+
1251 })
+
1252 .
await ? ;
+
1253 match client_b.next().
await .expect(
"eos" )
? {
+
1254 RelayToClientMsg::Datagrams {
+
1255 remote_node_id,
+
1256 datagrams,
+
1257 } => {
+
1258 assert_eq! (public_key_a, remote_node_id);
+
1259 assert_eq! (msg, datagrams);
+
1260 }
+
1261 msg => {
+
1262 whatever! (
"expected ReceivedDatagrams msg, got {msg:?}" );
+
1263 }
+
1264 }
+
1265
+
1266 info! (
"Send message from B to A." );
+
1267 let msg = Datagrams::from(
b"nice to meet you client a!!" );
+
1268 client_b
+
1269 .send(ClientToRelayMsg::Datagrams {
+
1270 dst_node_id: public_key_a,
+
1271 datagrams: msg.clone(),
+
1272 })
+
1273 .
await ? ;
+
1274 match client_a.next().
await .expect(
"eos" )
? {
+
1275 RelayToClientMsg::Datagrams {
+
1276 remote_node_id,
+
1277 datagrams,
+
1278 } => {
+
1279 assert_eq! (public_key_b, remote_node_id);
+
1280 assert_eq! (msg, datagrams);
+
1281 }
+
1282 msg => {
+
1283 whatever! (
"expected ReceivedDatagrams msg, got {msg:?}" );
+
1284 }
+
1285 }
1286
-
1287 info! (
"Send message from A to B." );
-
1290 let msg = Datagrams::from(
b"are you still there, b?!" );
-
1291 client_a
-
1292 .send(ClientToRelayMsg::Datagrams {
-
1293 dst_node_id: public_key_b,
-
1294 datagrams: msg.clone(),
-
1295 })
-
1296 .
await ? ;
-
1297 match new_client_b.next().
await .expect(
"eos" )
? {
-
1298 RelayToClientMsg::Datagrams {
-
1299 remote_node_id,
-
1300 datagrams,
-
1301 } => {
-
1302 assert_eq! (public_key_a, remote_node_id);
-
1303 assert_eq! (msg, datagrams);
-
1304 }
-
1305 msg => {
-
1306 whatever! (
"expected ReceivedDatagrams msg, got {msg:?}" );
-
1307 }
-
1308 }
-
1309
-
1310 info! (
"Send message from B to A." );
-
1311 let msg = Datagrams::from(
b"just had a spot of trouble but I'm back now,a!!" );
-
1312 new_client_b
-
1313 .send(ClientToRelayMsg::Datagrams {
-
1314 dst_node_id: public_key_a,
-
1315 datagrams: msg.clone(),
-
1316 })
-
1317 .
await ? ;
-
1318 match client_a.next().
await .expect(
"eos" )
? {
-
1319 RelayToClientMsg::Datagrams {
-
1320 remote_node_id,
-
1321 datagrams,
-
1322 } => {
-
1323 assert_eq! (public_key_b, remote_node_id);
-
1324 assert_eq! (msg, datagrams);
-
1325 }
-
1326 msg => {
-
1327 whatever! (
"expected ReceivedDatagrams msg, got {msg:?}" );
-
1328 }
-
1329 }
-
1330
-
1331 info! (
"Close the server and clients" );
-
1332 service.shutdown().
await ;
-
1333
-
1334 info! (
"Sending message from A to B fails" );
-
1335 let res = client_a
-
1336 .send(ClientToRelayMsg::Datagrams {
-
1337 dst_node_id: public_key_b,
-
1338 datagrams: Datagrams::from(
b"try to send" ),
-
1339 })
-
1340 .
await ;
-
1341 assert! (res.is_err());
-
1342 assert! (new_client_b.next().
await .is_none());
-
1343 Ok (())
-
1344 }
-
1345 }