work
This commit is contained in:
@@ -1,9 +1,7 @@
|
||||
use ed25519_dalek::SigningKey;
|
||||
use openworm::{
|
||||
net::LoginKey,
|
||||
rsc::{DataDir, DataRsc},
|
||||
};
|
||||
use rand::{TryRngCore, rngs::OsRng};
|
||||
|
||||
pub struct ClientData {
|
||||
pub dir: DataDir,
|
||||
@@ -26,16 +24,14 @@ impl ClientData {
|
||||
pub fn login_key(&self, user: &str) -> LoginKey {
|
||||
let entry = keyring::Entry::new("openworm", user).expect("failed to open keyring entry");
|
||||
if let Ok(secret) = entry.get_secret() {
|
||||
secret
|
||||
.try_into()
|
||||
.expect("failed to load key from secrets (invalid format)")
|
||||
LoginKey::from(secret)
|
||||
} else {
|
||||
LoginKey::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, bincode::Encode, bincode::Decode)]
|
||||
#[derive(Debug, Default, bitcode::Encode, bitcode::Decode)]
|
||||
pub struct Cache {
|
||||
pub ip: String,
|
||||
pub username: String,
|
||||
|
||||
@@ -1,31 +1,8 @@
|
||||
use crate::{Client, Rsc};
|
||||
use iris::core::UiRenderState;
|
||||
use openworm::net::NetServerMsg;
|
||||
|
||||
impl Client {
|
||||
pub fn debug(&mut self, _rsc: &mut Rsc, render: &mut UiRenderState) {
|
||||
render.debug_layers();
|
||||
// let mut file = std::fs::OpenOptions::new()
|
||||
// .write(true)
|
||||
// .create(true)
|
||||
// .truncate(true)
|
||||
// .open("./old_msgs")
|
||||
// .unwrap();
|
||||
// bincode::encode_into_std_write(
|
||||
// self.msgs.clone(),
|
||||
// &mut file,
|
||||
// openworm::net::BINCODE_CONFIG,
|
||||
// )
|
||||
// .unwrap();
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.open("/home/bryan/.local/share/openworm/old_msgs")
|
||||
.unwrap();
|
||||
let msgs: Vec<NetServerMsg> =
|
||||
bincode::decode_from_std_read(&mut file, openworm::net::BINCODE_CONFIG).unwrap();
|
||||
for msg in msgs {
|
||||
println!("{msg:?}");
|
||||
}
|
||||
// client.ui.debug_layers();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
#![feature(async_fn_traits)]
|
||||
#![windows_subsystem = "windows"]
|
||||
|
||||
use crate::{
|
||||
data::ClientData,
|
||||
state::{ClientState, LoggedIn},
|
||||
};
|
||||
use crate::{data::ClientData, state::ClientState};
|
||||
use iris::prelude::*;
|
||||
use openworm::net::{ClientMsg, ServerMsg, install_crypto_provider};
|
||||
use openworm::net::{ServerMsg, install_crypto_provider};
|
||||
use winit::{
|
||||
event::{ElementState, MouseButton, WindowEvent},
|
||||
window::WindowAttributes,
|
||||
@@ -83,44 +81,7 @@ impl DefaultAppState for Client {
|
||||
_render: &mut UiRenderState,
|
||||
) {
|
||||
match event {
|
||||
ClientEvent::ServerMsg(msg) => match msg {
|
||||
ServerMsg::SendMsg(msg) => {
|
||||
if let ClientState::LoggedIn(state) = &mut self.state
|
||||
&& let Some(msg_area) = state.channel
|
||||
{
|
||||
let msg = ui::msg_widget(&msg.user, &msg.content).add_strong(rsc);
|
||||
rsc[msg_area].children.push(msg);
|
||||
}
|
||||
}
|
||||
ServerMsg::LoadMsgs(msgs) => {
|
||||
if let ClientState::LoggedIn(state) = &mut self.state
|
||||
&& let Some(msg_area) = state.channel
|
||||
{
|
||||
for msg in msgs {
|
||||
state.msgs.push(msg.clone());
|
||||
let msg = ui::msg_widget(&msg.user, &msg.content).add_strong(rsc);
|
||||
rsc[msg_area].children.push(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
ServerMsg::Login { username } => {
|
||||
let ClientState::Login(state) = self.state.take() else {
|
||||
panic!("invalid state");
|
||||
};
|
||||
state.handle.send(ClientMsg::RequestMsgs);
|
||||
self.state = ClientState::LoggedIn(LoggedIn {
|
||||
network: state.handle,
|
||||
channel: None,
|
||||
msgs: Vec::new(),
|
||||
username,
|
||||
});
|
||||
ui::main_view(rsc).set_ptr(self.main_ui, rsc);
|
||||
}
|
||||
ServerMsg::Error(error) => {
|
||||
let msg = format!("{error:?}");
|
||||
rsc[self.notif].inner = Some(ui::werror(&msg, rsc));
|
||||
}
|
||||
},
|
||||
ClientEvent::ServerMsg(_) => {}
|
||||
ClientEvent::Err(msg) => {
|
||||
rsc[self.notif].inner = Some(ui::werror(&msg, rsc));
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
use crate::ClientEvent;
|
||||
use dashmap::DashMap;
|
||||
use openworm::net::{
|
||||
ClientMsg, RecvHandler, SERVER_NAME, ServerMsg, SkipServerVerification, recv_uni, send_uni,
|
||||
AccountCreated, ClientMsg, ClientMsgInst, CreateAccount, RecvHandler, RequestId, SERVER_NAME,
|
||||
ServerMsg, ServerRespMsg, SkipServerVerification, recv_uni, send_uni,
|
||||
};
|
||||
use quinn::{
|
||||
ClientConfig, Connection, Endpoint, IdleTimeout, TransportConfig,
|
||||
@@ -38,25 +40,53 @@ impl AppHandle {
|
||||
|
||||
type NetResult<T> = Result<T, String>;
|
||||
|
||||
pub trait ClientRequest {}
|
||||
|
||||
pub enum NetCtrlMsg {
|
||||
Exchange(ClientMsg, oneshot::Sender<>),
|
||||
Send(ClientMsg),
|
||||
Request(ClientMsg, oneshot::Sender<ServerMsg>),
|
||||
Exit,
|
||||
}
|
||||
|
||||
impl From<ClientMsg> for NetCtrlMsg {
|
||||
fn from(value: ClientMsg) -> Self {
|
||||
Self::Send(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl NetHandle {
|
||||
pub fn send(&self, msg: impl Into<NetCtrlMsg>) {
|
||||
self.send.send(msg.into());
|
||||
fn send_(&self, msg: NetCtrlMsg) {
|
||||
let _ = self.send.send(msg);
|
||||
}
|
||||
|
||||
pub fn send(&self, msg: impl Into<ClientMsg>) {
|
||||
self.send_(NetCtrlMsg::Send(msg.into()));
|
||||
}
|
||||
|
||||
pub async fn request<R: RequestMsg>(&self, msg: R) -> Result<R::Result, ()> {
|
||||
let (send, recv) = oneshot::channel();
|
||||
self.send_(NetCtrlMsg::Request(msg.into(), send));
|
||||
let Ok(recv) = recv.await else { todo!() };
|
||||
if let Some(res) = R::result(recv) {
|
||||
Ok(res)
|
||||
} else {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn exit(self) {
|
||||
self.send(NetCtrlMsg::Exit);
|
||||
self.send_(NetCtrlMsg::Exit);
|
||||
}
|
||||
}
|
||||
|
||||
pub trait RequestMsg: Into<ClientMsg> {
|
||||
type Result;
|
||||
fn result(msg: ServerMsg) -> Option<Self::Result>;
|
||||
}
|
||||
|
||||
impl RequestMsg for CreateAccount {
|
||||
type Result = AccountCreated;
|
||||
|
||||
fn result(msg: ServerMsg) -> Option<Self::Result> {
|
||||
if let ServerMsg::AccountCreated(res) = msg {
|
||||
Some(res)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,12 +159,25 @@ pub async fn connect(msg: impl MsgHandler, info: ConnectInfo) -> Result<NetHandl
|
||||
let (endpoint, conn) = connection_no_cert(addr).await?;
|
||||
let conn_ = conn.clone();
|
||||
|
||||
let recv = ServerRecv { msg };
|
||||
tokio::spawn(recv_uni(conn_, recv.into()));
|
||||
let mut req_id = RequestId::first();
|
||||
let recv = Arc::new(ServerRecv {
|
||||
msg,
|
||||
requests: DashMap::default(),
|
||||
});
|
||||
tokio::spawn(recv_uni(conn_, recv.clone()));
|
||||
tokio::spawn(async move {
|
||||
while let Some(msg) = ui_recv.recv().await {
|
||||
match msg {
|
||||
NetCtrlMsg::Send(msg) => {
|
||||
let msg = ClientMsgInst::from(msg);
|
||||
if send_uni(&conn, msg).await.is_err() {
|
||||
println!("disconnected from server");
|
||||
break;
|
||||
}
|
||||
}
|
||||
NetCtrlMsg::Request(msg, send) => {
|
||||
let msg = ClientMsgInst::from(msg);
|
||||
recv.requests.insert(req_id.next(), send);
|
||||
if send_uni(&conn, msg).await.is_err() {
|
||||
println!("disconnected from server");
|
||||
break;
|
||||
@@ -155,18 +198,29 @@ pub async fn connect(msg: impl MsgHandler, info: ConnectInfo) -> Result<NetHandl
|
||||
pub trait MsgHandler: Sync + Send + 'static {
|
||||
fn run(&self, msg: ServerMsg) -> impl Future<Output = ()> + Send;
|
||||
}
|
||||
impl<F: AsyncFn(ServerMsg) + Sync + Send + 'static> MsgHandler for F {
|
||||
impl<F: AsyncFn(ServerMsg) + Sync + Send + 'static> MsgHandler for F
|
||||
where
|
||||
for<'a> F::CallRefFuture<'a>: Send,
|
||||
{
|
||||
async fn run(&self, msg: ServerMsg) {
|
||||
self(msg);
|
||||
self(msg).await;
|
||||
}
|
||||
}
|
||||
|
||||
struct ServerRecv<F: MsgHandler> {
|
||||
requests: DashMap<RequestId, oneshot::Sender<ServerMsg>>,
|
||||
msg: F,
|
||||
}
|
||||
|
||||
impl<F: MsgHandler> RecvHandler<ServerMsg> for ServerRecv<F> {
|
||||
async fn msg(&self, msg: ServerMsg) {
|
||||
self.msg.run(msg).await;
|
||||
impl<F: MsgHandler> RecvHandler<ServerRespMsg> for ServerRecv<F> {
|
||||
async fn msg(&self, resp: ServerRespMsg) {
|
||||
let msg = resp.msg.into();
|
||||
if let Some(id) = resp.request_id
|
||||
&& let Some((_, send)) = self.requests.remove(&id)
|
||||
{
|
||||
send.send(msg);
|
||||
} else {
|
||||
self.msg.run(msg).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::net::NetHandle;
|
||||
use iris::prelude::*;
|
||||
use openworm::net::NetServerMsg;
|
||||
use openworm::net::LoadMsg;
|
||||
use std::thread::JoinHandle;
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -14,7 +14,7 @@ pub struct Login {
|
||||
|
||||
pub struct LoggedIn {
|
||||
pub network: NetHandle,
|
||||
pub msgs: Vec<NetServerMsg>,
|
||||
pub msgs: Vec<LoadMsg>,
|
||||
pub channel: Option<WeakWidget<Span>>,
|
||||
pub username: String,
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use openworm::net::CreateAccount;
|
||||
|
||||
use crate::net::{self, ConnectInfo};
|
||||
|
||||
use super::*;
|
||||
@@ -43,19 +45,39 @@ pub fn create_account(rsc: &mut Rsc) -> WeakWidget {
|
||||
|
||||
let create = Button::submit("create", rsc);
|
||||
rsc.events.register(create, Submit, move |ctx, rsc| {
|
||||
create.disable(rsc);
|
||||
let url = rsc[url].content();
|
||||
let user = rsc[username].content();
|
||||
let pwd = rsc[password].content();
|
||||
let key = ctx.state.data.login_key(&user);
|
||||
rsc.spawn_task(async |ctx| {
|
||||
let net = net::connect(
|
||||
let username = rsc[username].content();
|
||||
let password = rsc[password].content();
|
||||
let login_key = ctx.state.data.login_key(&username);
|
||||
rsc.spawn_task(async move |mut ctx| {
|
||||
let mut fail = move |reason| {
|
||||
ctx.update(move |ctx, rsc| {
|
||||
rsc[ctx.notif].inner = Some(werror(reason, rsc));
|
||||
create.enable(rsc);
|
||||
})
|
||||
};
|
||||
let Ok(net) = net::connect(
|
||||
async |msg| {
|
||||
println!("msg recv :joy:");
|
||||
},
|
||||
ConnectInfo { url },
|
||||
)
|
||||
.await
|
||||
.expect("failed to connect");
|
||||
else {
|
||||
return fail("failed to connect");
|
||||
};
|
||||
|
||||
let Ok(resp) = net
|
||||
.request(CreateAccount {
|
||||
username,
|
||||
password,
|
||||
login_key,
|
||||
})
|
||||
.await
|
||||
else {
|
||||
return fail("failed to create account");
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -84,6 +84,11 @@ impl Button {
|
||||
rsc[self.enabled] = false;
|
||||
rsc[self.rect].color = self.color.darker(0.8);
|
||||
}
|
||||
|
||||
pub fn enable(&self, rsc: &mut Rsc) {
|
||||
rsc[self.enabled] = true;
|
||||
rsc[self.rect].color = self.color;
|
||||
}
|
||||
}
|
||||
|
||||
widget_trait! {
|
||||
|
||||
@@ -4,9 +4,7 @@ use std::{
|
||||
path::Path,
|
||||
};
|
||||
|
||||
use bincode::{Decode, Encode};
|
||||
use openworm::net::BINCODE_CONFIG;
|
||||
use sled::Tree;
|
||||
use bitcode::{Decode, DecodeOwned, Encode};
|
||||
|
||||
pub const DB_VERSION: u64 = 0;
|
||||
|
||||
@@ -24,14 +22,14 @@ pub struct Msg {
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Db {
|
||||
pub db: sled::Db,
|
||||
pub db: fjall::Database,
|
||||
pub msgs: DbMap<u64, Msg>,
|
||||
pub users: DbMap<u64, User>,
|
||||
pub usernames: DbMap<String, u64>,
|
||||
}
|
||||
|
||||
pub struct DbMap<K, V> {
|
||||
tree: Tree,
|
||||
tree: fjall::Tree,
|
||||
_pd: PhantomData<(K, V)>,
|
||||
}
|
||||
|
||||
@@ -64,7 +62,7 @@ impl Key for u64 {
|
||||
}
|
||||
}
|
||||
|
||||
impl<K: Key, V: Encode + Decode<()>> DbMap<K, V> {
|
||||
impl<K: Key, V: Encode + DecodeOwned> DbMap<K, V> {
|
||||
pub fn insert(&self, k: &K, v: &V) {
|
||||
self.tree.insert_(k, v);
|
||||
}
|
||||
@@ -108,13 +106,13 @@ pub fn open_db(path: impl AsRef<Path>) -> Db {
|
||||
|
||||
trait DbUtil {
|
||||
fn insert_<V: Encode>(&self, k: &(impl Key + ?Sized), v: V);
|
||||
fn get_<V: Decode<()>>(&self, k: &(impl Key + ?Sized)) -> Option<V>;
|
||||
fn iter_all<V: Decode<()>>(&self) -> impl Iterator<Item = V>;
|
||||
fn get_<V: DecodeOwned>(&self, k: &(impl Key + ?Sized)) -> Option<V>;
|
||||
fn iter_all<V: DecodeOwned>(&self) -> impl Iterator<Item = V>;
|
||||
}
|
||||
|
||||
impl DbUtil for Tree {
|
||||
fn insert_<V: Encode>(&self, k: &(impl Key + ?Sized), v: V) {
|
||||
let bytes = bincode::encode_to_vec(v, BINCODE_CONFIG).unwrap();
|
||||
fn insert_<V: Encode>(&self, k: &(impl Key + ?Sized), v: &V) {
|
||||
let bytes = bitcode::encode(v);
|
||||
self.insert(k.bytes(), bytes).unwrap();
|
||||
}
|
||||
|
||||
|
||||
@@ -7,14 +7,14 @@ use clap::Parser;
|
||||
use net::{ClientSender, ConAccepter, listen};
|
||||
use openworm::{
|
||||
net::{
|
||||
ClientMsg, DisconnectReason, NetServerMsg, RecvHandler, ServerError, ServerMsg,
|
||||
install_crypto_provider,
|
||||
ClientMsg, ClientMsgInst, CreateAccount, DisconnectReason, LoadMsg, RecvHandler,
|
||||
ServerError, ServerMsg, install_crypto_provider,
|
||||
},
|
||||
rsc::DataDir,
|
||||
};
|
||||
use scrypt::{
|
||||
Scrypt,
|
||||
password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString, rand_core::OsRng},
|
||||
password_hash::{PasswordHasher, SaltString, rand_core::OsRng},
|
||||
};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
@@ -76,7 +76,7 @@ pub enum ClientState {
|
||||
}
|
||||
|
||||
impl ConAccepter for ServerListener {
|
||||
async fn accept(&self, send: ClientSender) -> impl RecvHandler<ClientMsg> {
|
||||
async fn accept(&self, send: ClientSender) -> impl RecvHandler<ClientMsgInst> {
|
||||
let id = self.count.fetch_add(1, Ordering::Release);
|
||||
self.senders.write().await.insert(id, send.clone());
|
||||
ClientHandler {
|
||||
@@ -97,11 +97,12 @@ struct ClientHandler {
|
||||
state: Arc<RwLock<ClientState>>,
|
||||
}
|
||||
|
||||
impl RecvHandler<ClientMsg> for ClientHandler {
|
||||
impl RecvHandler<ClientMsgInst> for ClientHandler {
|
||||
async fn connect(&self) -> () {
|
||||
println!("connected: {:?}", self.send.remote().ip());
|
||||
}
|
||||
async fn msg(&self, msg: ClientMsg) {
|
||||
async fn msg(&self, msg: ClientMsgInst) {
|
||||
let msg = ClientMsg::from(msg);
|
||||
match msg {
|
||||
ClientMsg::SendMsg(msg) => {
|
||||
let ClientState::Authed(uid) = &*self.state.read().await else {
|
||||
@@ -116,7 +117,7 @@ impl RecvHandler<ClientMsg> for ClientHandler {
|
||||
self.db.msgs.insert(&id, &msg);
|
||||
let mut handles = Vec::new();
|
||||
let user: User = self.db.users.get(uid).unwrap();
|
||||
let msg = NetServerMsg {
|
||||
let msg = LoadMsg {
|
||||
content: msg.content,
|
||||
user: user.username,
|
||||
};
|
||||
@@ -151,7 +152,7 @@ impl RecvHandler<ClientMsg> for ClientHandler {
|
||||
.get(&msg.user)
|
||||
.map(|user| user.username.to_string())
|
||||
.unwrap_or("deleted user".to_string());
|
||||
NetServerMsg {
|
||||
LoadMsg {
|
||||
content: msg.content,
|
||||
user,
|
||||
}
|
||||
@@ -159,8 +160,13 @@ impl RecvHandler<ClientMsg> for ClientHandler {
|
||||
.collect();
|
||||
let _ = self.send.send(ServerMsg::LoadMsgs(msgs)).await;
|
||||
}
|
||||
ClientMsg::CreateAccount { username, password } => {
|
||||
if !self.db.usernames.init_unique(&username) {
|
||||
ClientMsg::CreateAccount(info) => {
|
||||
let CreateAccount {
|
||||
username,
|
||||
password,
|
||||
login_key,
|
||||
} = &info;
|
||||
if !self.db.usernames.init_unique(username) {
|
||||
let _ = self.send.send(ServerError::UsernameTaken).await;
|
||||
return;
|
||||
}
|
||||
@@ -181,26 +187,25 @@ impl RecvHandler<ClientMsg> for ClientHandler {
|
||||
println!("account created: \"{username}\"");
|
||||
self.db.usernames.insert(&username, &id);
|
||||
*self.state.write().await = ClientState::Authed(id);
|
||||
let _ = self.send.send(ServerMsg::Login { username }).await;
|
||||
}
|
||||
ClientMsg::Login { username, password } => {
|
||||
let Some(id) = self.db.usernames.get(&username) else {
|
||||
let _ = self.send.send(ServerError::UnknownUsername).await;
|
||||
return;
|
||||
};
|
||||
let Some(user) = self.db.users.get(&id) else {
|
||||
panic!("invalid state! (should be a user)");
|
||||
};
|
||||
let hash = PasswordHash::new(&user.password_hash).unwrap();
|
||||
if Scrypt.verify_password(password.as_bytes(), &hash).is_err() {
|
||||
println!("invalid password: \"{username}\"");
|
||||
let _ = self.send.send(ServerError::InvalidPassword).await;
|
||||
return;
|
||||
}
|
||||
println!("login: \"{username}\"");
|
||||
*self.state.write().await = ClientState::Authed(id);
|
||||
let _ = self.send.send(ServerMsg::Login { username }).await;
|
||||
}
|
||||
// let _ = self.send.send(ServerMsg::Login()).await;
|
||||
} // ClientMsgType::Login { username, password } => {
|
||||
// let Some(id) = self.db.usernames.get(&username) else {
|
||||
// let _ = self.send.send(ServerError::UnknownUsername).await;
|
||||
// return;
|
||||
// };
|
||||
// let Some(user) = self.db.users.get(&id) else {
|
||||
// panic!("invalid state! (should be a user)");
|
||||
// };
|
||||
// let hash = PasswordHash::new(&user.password_hash).unwrap();
|
||||
// if Scrypt.verify_password(password.as_bytes(), &hash).is_err() {
|
||||
// println!("invalid password: \"{username}\"");
|
||||
// let _ = self.send.send(ServerError::InvalidPassword).await;
|
||||
// return;
|
||||
// }
|
||||
// println!("login: \"{username}\"");
|
||||
// *self.state.write().await = ClientState::Authed(id);
|
||||
// let _ = self.send.send(ServerMsgType::Login { username }).await;
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use openworm::net::{
|
||||
ClientMsg, RecvHandler, SERVER_NAME, SendResult, ServerMsg, recv_uni, send_uni,
|
||||
ClientMsg, ClientMsgInst, RecvHandler, SERVER_NAME, SendResult, ServerMsg, ServerMsgInst,
|
||||
recv_uni, send_uni,
|
||||
};
|
||||
use quinn::{
|
||||
Connection, Endpoint, ServerConfig,
|
||||
@@ -63,7 +64,7 @@ impl ClientSender {
|
||||
self.conn.remote_address()
|
||||
}
|
||||
pub async fn send(&self, msg: impl Into<ServerMsg>) -> SendResult {
|
||||
let msg = msg.into();
|
||||
let msg = ServerMsgInst::from(msg.into());
|
||||
send_uni(&self.conn, msg).await
|
||||
}
|
||||
}
|
||||
@@ -72,7 +73,7 @@ pub trait ConAccepter: Send + Sync + 'static {
|
||||
fn accept(
|
||||
&self,
|
||||
send: ClientSender,
|
||||
) -> impl Future<Output = impl RecvHandler<ClientMsg>> + Send;
|
||||
) -> impl Future<Output = impl RecvHandler<ClientMsgInst>> + Send;
|
||||
}
|
||||
|
||||
pub fn listen(
|
||||
|
||||
46
src/net/conversion.rs
Normal file
46
src/net/conversion.rs
Normal file
@@ -0,0 +1,46 @@
|
||||
use crate::net::{
|
||||
ClientMsg, ServerMsg,
|
||||
data::{ClientMsgInst, ServerMsgInst},
|
||||
};
|
||||
|
||||
impl From<ClientMsg> for ClientMsgInst {
|
||||
fn from(value: ClientMsg) -> Self {
|
||||
match value {
|
||||
ClientMsg::CreateAccount(v) => Self::CreateAccountV0(v),
|
||||
ClientMsg::RequestMsgs => Self::RequestMsgsV0,
|
||||
ClientMsg::SendMsg(v) => Self::SendMsgV0(v),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ClientMsgInst> for ClientMsg {
|
||||
fn from(value: ClientMsgInst) -> Self {
|
||||
match value {
|
||||
ClientMsgInst::CreateAccountV0(v) => Self::CreateAccount(v),
|
||||
ClientMsgInst::RequestMsgsV0 => Self::RequestMsgs,
|
||||
ClientMsgInst::SendMsgV0(v) => Self::SendMsg(v),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ServerMsg> for ServerMsgInst {
|
||||
fn from(value: ServerMsg) -> Self {
|
||||
match value {
|
||||
ServerMsg::AccountCreated(v) => Self::AccountCreatedV0(v),
|
||||
ServerMsg::LoadMsg(v) => Self::LoadMsgV0(v),
|
||||
ServerMsg::LoadMsgs(v) => Self::LoadMsgsV0(v),
|
||||
ServerMsg::ServerError(v) => Self::ServerErrorV0(v),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ServerMsgInst> for ServerMsg {
|
||||
fn from(value: ServerMsgInst) -> Self {
|
||||
match value {
|
||||
ServerMsgInst::AccountCreatedV0(v) => Self::AccountCreated(v),
|
||||
ServerMsgInst::LoadMsgV0(v) => Self::LoadMsg(v),
|
||||
ServerMsgInst::LoadMsgsV0(v) => Self::LoadMsgs(v),
|
||||
ServerMsgInst::ServerErrorV0(v) => Self::ServerError(v),
|
||||
}
|
||||
}
|
||||
}
|
||||
67
src/net/data.rs
Normal file
67
src/net/data.rs
Normal file
@@ -0,0 +1,67 @@
|
||||
use rand::TryRngCore;
|
||||
|
||||
#[repr(u32)]
|
||||
#[derive(Debug, bitcode::Encode, bitcode::Decode)]
|
||||
pub enum ClientMsgInst {
|
||||
CreateAccountV0(CreateAccountV0) = 0,
|
||||
RequestMsgsV0 = 1,
|
||||
SendMsgV0(SendMsgV0) = 2,
|
||||
}
|
||||
|
||||
#[repr(u32)]
|
||||
#[derive(Debug, bitcode::Encode, bitcode::Decode)]
|
||||
pub enum ServerMsgInst {
|
||||
AccountCreatedV0(AccountCreatedV0) = 0,
|
||||
LoadMsgV0(LoadMsgV0) = 1,
|
||||
LoadMsgsV0(Vec<LoadMsgV0>) = 2,
|
||||
ServerErrorV0(ServerErrorV0) = 3,
|
||||
}
|
||||
|
||||
#[derive(Debug, bitcode::Encode, bitcode::Decode)]
|
||||
pub struct CreateAccountV0 {
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
pub login_key: LoginKeyV0,
|
||||
}
|
||||
|
||||
#[derive(Debug, bitcode::Encode, bitcode::Decode)]
|
||||
pub struct AccountCreatedV0 {}
|
||||
|
||||
#[derive(Debug, bitcode::Encode, bitcode::Decode)]
|
||||
pub struct LoginKeyV0(Vec<u8>);
|
||||
impl LoginKeyV0 {
|
||||
pub const BIT_LEN: usize = 1024;
|
||||
pub const BYTE_LEN: usize = Self::BIT_LEN / 8;
|
||||
|
||||
pub fn new() -> Self {
|
||||
let mut key = [0u8; Self::BYTE_LEN];
|
||||
rand::rngs::OsRng
|
||||
.try_fill_bytes(&mut key)
|
||||
.expect("failed to generate random key");
|
||||
Self(key.to_vec())
|
||||
}
|
||||
}
|
||||
impl From<Vec<u8>> for LoginKeyV0 {
|
||||
fn from(value: Vec<u8>) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
|
||||
pub struct SendMsgV0 {
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
|
||||
pub struct LoadMsgV0 {
|
||||
pub content: String,
|
||||
pub user: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, bitcode::Encode, bitcode::Decode)]
|
||||
pub enum ServerErrorV0 {
|
||||
NotLoggedIn,
|
||||
UnknownUsername,
|
||||
InvalidPassword,
|
||||
UsernameTaken,
|
||||
}
|
||||
@@ -1,96 +1,22 @@
|
||||
use bincode::config::Configuration;
|
||||
|
||||
mod conversion;
|
||||
mod data;
|
||||
mod msg;
|
||||
mod no_cert;
|
||||
mod request;
|
||||
mod transfer;
|
||||
|
||||
pub use data::{ClientMsgInst, ServerMsgInst};
|
||||
pub use msg::*;
|
||||
pub use no_cert::*;
|
||||
use rand::{TryRngCore, rngs::OsRng};
|
||||
pub use request::*;
|
||||
pub use transfer::*;
|
||||
|
||||
pub const SERVER_NAME: &str = "openworm";
|
||||
pub const BINCODE_CONFIG: Configuration = bincode::config::standard();
|
||||
|
||||
#[derive(Debug, bincode::Encode, bincode::Decode)]
|
||||
pub enum ClientMsg {
|
||||
SendMsg(NetClientMsg),
|
||||
RequestMsgs,
|
||||
CreateAccount {
|
||||
username: String,
|
||||
password: String,
|
||||
device: LoginKey,
|
||||
},
|
||||
Login {
|
||||
username: String,
|
||||
password: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, bincode::Encode, bincode::Decode)]
|
||||
pub enum ServerMsg {
|
||||
SendMsg(NetServerMsg),
|
||||
LoadMsgs(Vec<NetServerMsg>),
|
||||
Login { username: String },
|
||||
Error(ServerError),
|
||||
}
|
||||
|
||||
#[derive(Debug, bincode::Encode, bincode::Decode)]
|
||||
pub enum ServerError {
|
||||
NotLoggedIn,
|
||||
UnknownUsername,
|
||||
InvalidPassword,
|
||||
UsernameTaken,
|
||||
}
|
||||
|
||||
impl From<ServerError> for ServerMsg {
|
||||
fn from(value: ServerError) -> Self {
|
||||
Self::Error(value)
|
||||
}
|
||||
}
|
||||
|
||||
pub type ServerResp<T> = Result<T, String>;
|
||||
|
||||
#[derive(Debug, Clone, bincode::Encode, bincode::Decode)]
|
||||
pub struct NetClientMsg {
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, bincode::Encode, bincode::Decode)]
|
||||
pub struct NetServerMsg {
|
||||
pub content: String,
|
||||
pub user: String,
|
||||
}
|
||||
|
||||
impl From<NetServerMsg> for ServerMsg {
|
||||
fn from(value: NetServerMsg) -> Self {
|
||||
Self::SendMsg(value)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn install_crypto_provider() {
|
||||
quinn::rustls::crypto::ring::default_provider()
|
||||
.install_default()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[derive(Debug, bincode::Encode, bincode::Decode)]
|
||||
pub struct LoginKey([u8; LoginKey::BYTE_LEN]);
|
||||
impl LoginKey {
|
||||
pub const BIT_LEN: usize = 1024;
|
||||
pub const BYTE_LEN: usize = Self::BIT_LEN / 8;
|
||||
|
||||
pub fn new() -> Self {
|
||||
let mut key = [0u8; Self::BYTE_LEN];
|
||||
OsRng
|
||||
.try_fill_bytes(&mut key)
|
||||
.expect("failed to generate random key");
|
||||
Self(key)
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<Vec<u8>> for LoginKey {
|
||||
type Error = ();
|
||||
|
||||
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
|
||||
Ok(Self(value.try_into().map_err(|_| ())?))
|
||||
}
|
||||
}
|
||||
|
||||
29
src/net/msg.rs
Normal file
29
src/net/msg.rs
Normal file
@@ -0,0 +1,29 @@
|
||||
use super::data::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ClientMsg {
|
||||
CreateAccount(CreateAccount),
|
||||
RequestMsgs,
|
||||
SendMsg(SendMsg),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ServerMsg {
|
||||
AccountCreated(AccountCreated),
|
||||
LoadMsg(LoadMsg),
|
||||
LoadMsgs(Vec<LoadMsg>),
|
||||
ServerError(ServerError),
|
||||
}
|
||||
|
||||
pub type LoginKey = LoginKeyV0;
|
||||
pub type SendMsg = SendMsgV0;
|
||||
pub type LoadMsg = LoadMsgV0;
|
||||
pub type ServerError = ServerErrorV0;
|
||||
pub type CreateAccount = CreateAccountV0;
|
||||
pub type AccountCreated = AccountCreatedV0;
|
||||
|
||||
impl From<CreateAccount> for ClientMsg {
|
||||
fn from(value: CreateAccount) -> Self {
|
||||
Self::CreateAccount(value)
|
||||
}
|
||||
}
|
||||
32
src/net/request.rs
Normal file
32
src/net/request.rs
Normal file
@@ -0,0 +1,32 @@
|
||||
use std::num::NonZeroU32;
|
||||
|
||||
use crate::net::{ClientMsgInst, ServerMsgInst};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, bitcode::Encode, bitcode::Decode)]
|
||||
pub struct RequestId(NonZeroU32);
|
||||
|
||||
impl RequestId {
|
||||
pub const fn first() -> Self {
|
||||
Self(NonZeroU32::MAX)
|
||||
}
|
||||
|
||||
pub const fn next(&mut self) -> Self {
|
||||
self.0 = match self.0.checked_add(1) {
|
||||
Some(v) => v,
|
||||
None => NonZeroU32::MIN,
|
||||
};
|
||||
*self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, bitcode::Encode, bitcode::Decode)]
|
||||
pub struct ClientRequestMsg {
|
||||
pub request_id: Option<RequestId>,
|
||||
pub msg: ClientMsgInst,
|
||||
}
|
||||
|
||||
#[derive(Debug, bitcode::Encode, bitcode::Decode)]
|
||||
pub struct ServerRespMsg {
|
||||
pub request_id: Option<RequestId>,
|
||||
pub msg: ServerMsgInst,
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::net::BINCODE_CONFIG;
|
||||
use quinn::Connection;
|
||||
use tokio::io::{AsyncReadExt as _, AsyncWriteExt};
|
||||
use tracing::Instrument as _;
|
||||
@@ -17,8 +16,8 @@ pub trait RecvHandler<M>: Send + Sync + 'static {
|
||||
}
|
||||
|
||||
pub type SendResult = Result<(), ()>;
|
||||
pub async fn send_uni<M: bincode::Encode>(conn: &Connection, msg: M) -> SendResult {
|
||||
let bytes = bincode::encode_to_vec(msg, BINCODE_CONFIG).unwrap();
|
||||
pub async fn send_uni<M: bitcode::Encode>(conn: &Connection, msg: M) -> SendResult {
|
||||
let bytes = bitcode::encode(&msg);
|
||||
let mut send = conn.open_uni().await.map_err(|_| ())?;
|
||||
|
||||
send.write_u64(bytes.len() as u64).await.map_err(|_| ())?;
|
||||
@@ -34,7 +33,7 @@ pub enum DisconnectReason {
|
||||
Other(String),
|
||||
}
|
||||
|
||||
pub async fn recv_uni<M: bincode::Decode<()>>(
|
||||
pub async fn recv_uni<M: bitcode::DecodeOwned>(
|
||||
conn: Connection,
|
||||
handler: Arc<impl RecvHandler<M>>,
|
||||
) -> DisconnectReason {
|
||||
@@ -58,7 +57,7 @@ pub async fn recv_uni<M: bincode::Decode<()>>(
|
||||
async move {
|
||||
let len = recv.read_u64().await.unwrap();
|
||||
let bytes = recv.read_to_end(len as usize).await.unwrap();
|
||||
let (msg, _) = bincode::decode_from_slice::<M, _>(&bytes, BINCODE_CONFIG).unwrap();
|
||||
let msg = bitcode::decode::<M>(&bytes).unwrap();
|
||||
handler.msg(msg).await;
|
||||
}
|
||||
.instrument(tracing::info_span!("request")),
|
||||
|
||||
16
src/rsc.rs
16
src/rsc.rs
@@ -1,12 +1,10 @@
|
||||
use std::{
|
||||
fs::{self, File},
|
||||
io::Write,
|
||||
path::Path,
|
||||
};
|
||||
|
||||
use directories_next::ProjectDirs;
|
||||
use ed25519_dalek::VerifyingKey;
|
||||
|
||||
use crate::net::BINCODE_CONFIG;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct DataDir {
|
||||
@@ -21,7 +19,7 @@ impl Default for DataDir {
|
||||
}
|
||||
}
|
||||
|
||||
pub trait DataRsc: bincode::Encode + bincode::Decode<()> + Default {
|
||||
pub trait DataRsc: bitcode::Encode + bitcode::DecodeOwned + Default {
|
||||
fn path() -> &'static str;
|
||||
}
|
||||
|
||||
@@ -33,8 +31,8 @@ impl DataDir {
|
||||
pub fn load<T: DataRsc>(&self) -> T {
|
||||
let path = self.get().join(T::path());
|
||||
match fs::read(path) {
|
||||
Ok(bytes) => match bincode::decode_from_slice(&bytes, BINCODE_CONFIG) {
|
||||
Ok((data, _)) => data,
|
||||
Ok(bytes) => match bitcode::decode(&bytes) {
|
||||
Ok(data) => data,
|
||||
Err(_) => todo!(),
|
||||
},
|
||||
Err(_) => T::default(),
|
||||
@@ -45,8 +43,8 @@ impl DataDir {
|
||||
let dir = self.get();
|
||||
fs::create_dir_all(dir).unwrap();
|
||||
let mut file = File::create(dir.join(T::path())).unwrap();
|
||||
bincode::encode_into_std_write(data, &mut file, BINCODE_CONFIG).unwrap();
|
||||
// TODO: used to use encode_into_std_write from bincode here
|
||||
let data = bitcode::encode(data);
|
||||
file.write_all(&data).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DevicePublicKey(VerifyingKey);
|
||||
|
||||
Reference in New Issue
Block a user