binary refactor

This commit is contained in:
2025-11-18 02:32:10 -05:00
parent 626614a2cf
commit db15f43610
14 changed files with 37 additions and 51 deletions

113
src/bin/server/net.rs Normal file
View File

@@ -0,0 +1,113 @@
use openworm::net::{
ClientMsg, RecvHandler, SERVER_NAME, SendResult, ServerMsg, 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(())
}