This commit is contained in:
2026-01-26 13:53:51 -05:00
parent e1eff49be9
commit 53ed4775ae
19 changed files with 565 additions and 350 deletions

View File

@@ -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();
}

View File

@@ -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;
// }
}
}

View File

@@ -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(