trifid/tfclient/src/apiworker.rs

75 lines
2.4 KiB
Rust
Raw Normal View History

use std::sync::mpsc::{Receiver, TryRecvError};
use log::{error, info};
2023-03-27 16:32:26 +00:00
use trifid_pki::ed25519_dalek::{SecretKey, SigningKey};
use trifid_pki::rand_core::OsRng;
use trifid_pki::x25519_dalek::StaticSecret;
use crate::config::{load_cdata, save_cdata, TFClientConfig};
2023-03-22 18:34:06 +00:00
use crate::daemon::ThreadMessageSender;
pub enum APIWorkerMessage {
Shutdown
2023-03-22 18:34:06 +00:00
}
2023-03-27 16:32:26 +00:00
pub fn apiworker_main(config: TFClientConfig, instance: String, _transmitters: ThreadMessageSender, rx: Receiver<APIWorkerMessage>) {
// Generate dhPubkey and edPubkey if it doesn't exist
// Load vardata
let mut vdata = match load_cdata(&instance) {
Ok(d) => d,
Err(e) => {
error!("Error loading vdata: {}", e);
error!("APIWorker exiting with error");
return;
}
};
if vdata.ed_privkey.is_none() {
info!("Generating ed25519 key");
let mut csprng = OsRng;
let key = SigningKey::generate(&mut csprng);
let ed_key_bytes = key.to_bytes().to_vec();
vdata.ed_privkey = Some(ed_key_bytes.try_into().unwrap());
}
if vdata.dh_privkey.is_none() {
info!("Generating ecdh key");
let mut csprng = OsRng;
let key = StaticSecret::new(&mut csprng);
let dh_key_bytes = key.to_bytes();
vdata.dh_privkey = Some(dh_key_bytes);
}
info!("Loading keys");
let ed_key = SigningKey::from_bytes(&SecretKey::from(vdata.ed_privkey.unwrap()));
let dh_key = StaticSecret::from(vdata.dh_privkey.unwrap());
info!("Keys loaded successfully");
// Save vardata
match save_cdata(&instance, vdata) {
Ok(_) => (),
Err(e) => {
error!("Error saving vdata: {}", e);
error!("APIWorker exiting with error");
return;
}
}
loop {
match rx.try_recv() {
Ok(msg) => {
match msg {
APIWorkerMessage::Shutdown => {
info!("recv on command socket: shutdown, stopping");
break;
}
}
},
Err(e) => {
match e {
TryRecvError::Empty => {}
TryRecvError::Disconnected => {
error!("apiworker command socket disconnected, shutting down to prevent orphaning");
break;
}
}
}
}
}
2023-03-22 18:34:06 +00:00
}