connection things

This commit is contained in:
Ferdinand Schober
2024-09-06 13:21:44 +02:00
parent 28e4895418
commit e4a7f0b4fc
4 changed files with 125 additions and 45 deletions

View File

@@ -1,6 +1,9 @@
use std::{io, net::SocketAddr, sync::Arc};
use crate::server::Server;
use lan_mouse_ipc::{ClientHandle, DEFAULT_PORT};
use lan_mouse_proto::{ProtoEvent, MAX_EVENT_SIZE};
use std::{collections::HashMap, io, net::SocketAddr, sync::Arc};
use thiserror::Error;
use tokio::net::UdpSocket;
use tokio::{net::UdpSocket, task::JoinSet};
use webrtc_dtls::{
config::{Config, ExtendedMasterSecretType},
conn::DTLSConn,
@@ -14,6 +17,10 @@ pub(crate) enum LanMouseConnectionError {
Bind(#[from] io::Error),
#[error(transparent)]
Dtls(#[from] webrtc_dtls::Error),
#[error(transparent)]
Webrtc(#[from] webrtc_util::Error),
#[error("no ips associated with the client")]
NoIps,
}
pub(crate) struct LanMouseConnection {}
@@ -36,4 +43,62 @@ impl LanMouseConnection {
Arc::new(DTLSConn::new(conn, config, true, None).await?);
Ok(dtls_conn)
}
pub(crate) async fn connect_any(
addrs: &[SocketAddr],
) -> Result<Arc<dyn Conn + Send + Sync>, LanMouseConnectionError> {
let mut joinset = JoinSet::new();
for &addr in addrs {
joinset.spawn_local(Self::connect(addr));
}
let conn = joinset.join_next().await;
conn.expect("no addrs to connect").expect("failed to join")
}
}
struct ConnectionProxy {
server: Server,
conns: HashMap<SocketAddr, Arc<dyn Conn + Send + Sync>>,
}
impl ConnectionProxy {
fn find_conn(&self, addrs: &[SocketAddr]) -> Vec<Arc<dyn Conn + Send + Sync>> {
let mut conns = vec![];
for addr in addrs {
if let Some(conn) = self.conns.get(&addr) {
conns.push(conn.clone());
}
}
conns
}
async fn send(
&self,
event: ProtoEvent,
handle: ClientHandle,
) -> Result<(), LanMouseConnectionError> {
let (buf, len): ([u8; MAX_EVENT_SIZE], usize) = event.into();
let buf = &buf[..len];
if let Some(addr) = self.server.active_addr(handle) {
if let Some(conn) = self.conns.get(&addr) {
if let Ok(_) = conn.send(buf).await {
return Ok(());
}
}
}
// sending did not work, figure out active conn.
if let Some(addrs) = self.server.get_ips(handle) {
let port = self.server.get_port(handle).unwrap_or(DEFAULT_PORT);
let addrs = addrs
.into_iter()
.map(|a| SocketAddr::new(a, port))
.collect::<Vec<_>>();
let conn = LanMouseConnection::connect_any(&addrs).await?;
let addr = conn.remote_addr().expect("no remote addr");
self.server.set_active_addr(handle, addr);
conn.send(buf).await?;
return Ok(());
}
Err(LanMouseConnectionError::NoIps)
}
}