binary refactor
This commit is contained in:
@@ -1,144 +0,0 @@
|
||||
use crate::{
|
||||
client::{AppHandle, ClientEvent},
|
||||
net::{
|
||||
ClientMsg, SERVER_NAME, ServerMsg,
|
||||
no_cert::SkipServerVerification,
|
||||
transfer::{RecvHandler, recv_uni, send_uni},
|
||||
},
|
||||
};
|
||||
use quinn::{
|
||||
ClientConfig, Connection, Endpoint, IdleTimeout, TransportConfig,
|
||||
crypto::rustls::QuicClientConfig,
|
||||
};
|
||||
use std::{
|
||||
net::{Ipv6Addr, SocketAddr, SocketAddrV6, ToSocketAddrs},
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::sync::mpsc::UnboundedSender;
|
||||
|
||||
pub const CLIENT_SOCKET: SocketAddr =
|
||||
SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, 0, 0, 0));
|
||||
|
||||
pub struct ConnectInfo {
|
||||
pub ip: String,
|
||||
pub username: String,
|
||||
}
|
||||
|
||||
pub fn connect(handle: AppHandle, info: ConnectInfo) {
|
||||
std::thread::spawn(move || {
|
||||
if let Err(msg) = connect_the(handle.clone(), info) {
|
||||
handle.send(ClientEvent::Err(msg));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
type NetResult<T> = Result<T, String>;
|
||||
|
||||
type MsgPayload = ClientMsg;
|
||||
pub struct NetSender {
|
||||
send: UnboundedSender<MsgPayload>,
|
||||
}
|
||||
|
||||
impl NetSender {
|
||||
pub fn send(&self, msg: ClientMsg) {
|
||||
let _ = self.send.send(msg);
|
||||
}
|
||||
}
|
||||
|
||||
// async fn connection_cert(addr: SocketAddr) -> NetResult<Connection> {
|
||||
// let dirs = directories_next::ProjectDirs::from("", "", "openworm").unwrap();
|
||||
// let mut roots = quinn::rustls::RootCertStore::empty();
|
||||
// match fs::read(dirs.data_local_dir().join("cert.der")) {
|
||||
// Ok(cert) => {
|
||||
// roots.add(CertificateDer::from(cert))?;
|
||||
// }
|
||||
// Err(ref e) if e.kind() == ErrorKind::NotFound => {
|
||||
// eprintln!("local server certificate not found");
|
||||
// }
|
||||
// Err(e) => {
|
||||
// eprintln!("failed to open local server certificate: {}", e);
|
||||
// }
|
||||
// }
|
||||
// let client_crypto = quinn::rustls::ClientConfig::builder()
|
||||
// .with_root_certificates(roots)
|
||||
// .with_no_client_auth();
|
||||
// let client_config = ClientConfig::new(Arc::new(QuicClientConfig::try_from(client_crypto)?));
|
||||
// let mut endpoint = quinn::Endpoint::client(SocketAddr::from_str("[::]:0").unwrap())?;
|
||||
// endpoint.set_default_client_config(client_config);
|
||||
// endpoint
|
||||
// .connect(addr, SERVER_NAME)?
|
||||
// .await
|
||||
// .map_err(|e| format!("failed to connect: {}", e))
|
||||
// }
|
||||
|
||||
async fn connection_no_cert(addr: SocketAddr) -> NetResult<Connection> {
|
||||
let mut endpoint = Endpoint::client(CLIENT_SOCKET).map_err(|e| e.to_string())?;
|
||||
|
||||
let quic = QuicClientConfig::try_from(
|
||||
quinn::rustls::ClientConfig::builder()
|
||||
.dangerous()
|
||||
.with_custom_certificate_verifier(SkipServerVerification::new())
|
||||
.with_no_client_auth(),
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let mut config = ClientConfig::new(Arc::new(quic));
|
||||
|
||||
let mut transport = TransportConfig::default();
|
||||
transport.keep_alive_interval(Some(Duration::from_secs(5)));
|
||||
transport.max_idle_timeout(Some(
|
||||
IdleTimeout::try_from(Duration::from_secs(10)).unwrap(),
|
||||
));
|
||||
config.transport_config(transport.into());
|
||||
|
||||
endpoint.set_default_client_config(config);
|
||||
|
||||
// connect to server
|
||||
endpoint
|
||||
.connect(addr, SERVER_NAME)
|
||||
.map_err(|e| e.to_string())?
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn connect_the(handle: AppHandle, info: ConnectInfo) -> NetResult<()> {
|
||||
let (send, mut ui_recv) = tokio::sync::mpsc::unbounded_channel::<MsgPayload>();
|
||||
|
||||
let addr = info
|
||||
.ip
|
||||
.to_socket_addrs()
|
||||
.map_err(|e| e.to_string())?
|
||||
.next()
|
||||
.ok_or("no addresses found".to_string())?;
|
||||
let conn = connection_no_cert(addr).await?;
|
||||
let conn_ = conn.clone();
|
||||
|
||||
handle.send(ClientEvent::Connect {
|
||||
username: info.username,
|
||||
send: NetSender { send },
|
||||
});
|
||||
|
||||
let recv = ServerRecv { handle };
|
||||
tokio::spawn(recv_uni(conn_, recv.into()));
|
||||
|
||||
while let Some(msg) = ui_recv.recv().await {
|
||||
if send_uni(&conn, msg).await.is_err() {
|
||||
println!("disconnected from server");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct ServerRecv {
|
||||
handle: AppHandle,
|
||||
}
|
||||
|
||||
impl RecvHandler<ServerMsg> for ServerRecv {
|
||||
async fn msg(&self, msg: ServerMsg) {
|
||||
self.handle.send(ClientEvent::ServerMsg(msg));
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
use bincode::config::Configuration;
|
||||
|
||||
pub mod client;
|
||||
mod no_cert;
|
||||
pub mod server;
|
||||
pub mod transfer;
|
||||
mod transfer;
|
||||
|
||||
pub use no_cert::*;
|
||||
pub use transfer::*;
|
||||
|
||||
pub const SERVER_NAME: &str = "openworm";
|
||||
pub const BINCODE_CONFIG: Configuration = bincode::config::standard();
|
||||
|
||||
@@ -1,114 +0,0 @@
|
||||
use crate::net::{
|
||||
ClientMsg, SERVER_NAME, ServerMsg,
|
||||
transfer::{RecvHandler, SendResult, recv_uni, send_uni},
|
||||
};
|
||||
use quinn::{
|
||||
Connection, Endpoint, ServerConfig,
|
||||
rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer},
|
||||
};
|
||||
use std::{fs, path::Path};
|
||||
use std::{
|
||||
net::{Ipv6Addr, SocketAddr, SocketAddrV6},
|
||||
sync::Arc,
|
||||
};
|
||||
use tracing::Instrument;
|
||||
|
||||
pub const DEFAULT_PORT: u16 = 16839;
|
||||
pub const SERVER_HOST: Ipv6Addr = Ipv6Addr::UNSPECIFIED;
|
||||
pub const SERVER_SOCKET: SocketAddr =
|
||||
SocketAddr::V6(SocketAddrV6::new(SERVER_HOST, DEFAULT_PORT, 0, 0));
|
||||
|
||||
pub fn init_endpoint(data_path: &Path) -> Endpoint {
|
||||
let cert_path = data_path.join("cert.der");
|
||||
let key_path = data_path.join("key.der");
|
||||
let (cert, key) = match fs::read(&cert_path).and_then(|x| Ok((x, fs::read(&key_path)?))) {
|
||||
Ok((cert, key)) => (
|
||||
CertificateDer::from(cert),
|
||||
PrivateKeyDer::try_from(key).unwrap(),
|
||||
),
|
||||
Err(ref e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
let cert = rcgen::generate_simple_self_signed([SERVER_NAME.into()]).unwrap();
|
||||
let key = PrivatePkcs8KeyDer::from(cert.signing_key.serialize_der());
|
||||
let cert = cert.cert.into();
|
||||
fs::create_dir_all(data_path).expect("failed to create certificate directory");
|
||||
fs::write(&cert_path, &cert).expect("failed to write certificate");
|
||||
fs::write(&key_path, key.secret_pkcs8_der()).expect("failed to write private key");
|
||||
(cert, key.into())
|
||||
}
|
||||
Err(e) => {
|
||||
panic!("failed to read certificate: {}", e);
|
||||
}
|
||||
};
|
||||
// let server_crypto = quinn::rustls::ServerConfig::builder()
|
||||
// .with_no_client_auth()
|
||||
// .with_single_cert(vec![cert], key)
|
||||
// .unwrap();
|
||||
//
|
||||
// let server_config = quinn::ServerConfig::with_crypto(Arc::new(
|
||||
// QuicServerConfig::try_from(server_crypto).unwrap(),
|
||||
// ));
|
||||
|
||||
let server_config = ServerConfig::with_single_cert(vec![cert], key).unwrap();
|
||||
// let transport_config = Arc::get_mut(&mut server_config.transport).unwrap();
|
||||
// transport_config.max_concurrent_uni_streams(0_u8.into());
|
||||
|
||||
quinn::Endpoint::server(server_config, SERVER_SOCKET).unwrap()
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ClientSender {
|
||||
conn: Connection,
|
||||
}
|
||||
|
||||
impl ClientSender {
|
||||
pub async fn send(&self, msg: ServerMsg) -> SendResult {
|
||||
send_uni(&self.conn, msg).await
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ConAccepter: Send + Sync + 'static {
|
||||
fn accept(
|
||||
&self,
|
||||
send: ClientSender,
|
||||
) -> impl Future<Output = impl RecvHandler<ClientMsg>> + Send;
|
||||
}
|
||||
|
||||
pub async fn listen(data_path: &Path, accepter: impl ConAccepter) {
|
||||
let accepter = Arc::new(accepter);
|
||||
let endpoint = init_endpoint(data_path);
|
||||
println!("listening on {}", endpoint.local_addr().unwrap());
|
||||
|
||||
while let Some(conn) = endpoint.accept().await {
|
||||
let fut = handle_connection(conn, accepter.clone());
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = fut.await {
|
||||
eprintln!("connection failed: {reason}", reason = e)
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_connection(
|
||||
conn: quinn::Incoming,
|
||||
accepter: Arc<impl ConAccepter>,
|
||||
) -> std::io::Result<()> {
|
||||
let conn = conn.await?;
|
||||
let handler = Arc::new(accepter.accept(ClientSender { conn: conn.clone() }).await);
|
||||
let span = tracing::info_span!(
|
||||
"connection",
|
||||
remote = %conn.remote_address(),
|
||||
protocol = %conn
|
||||
.handshake_data()
|
||||
.unwrap()
|
||||
.downcast::<quinn::crypto::rustls::HandshakeData>().unwrap()
|
||||
.protocol
|
||||
.map_or_else(|| "<none>".into(), |x| String::from_utf8_lossy(&x).into_owned())
|
||||
);
|
||||
async {
|
||||
let res = recv_uni(conn, handler.clone()).await;
|
||||
handler.disconnect(res).await;
|
||||
}
|
||||
.instrument(span)
|
||||
.await;
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user