use std::fs; use std::sync::mpsc::{Receiver, TryRecvError}; use base64::Engine; use chrono::Local; use log::{error, info, warn}; use url::Url; use dnapi_rs::client_blocking::Client; use trifid_pki::cert::{serialize_ed25519_public, serialize_x25519_public}; 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}; use crate::daemon::ThreadMessageSender; use crate::dirs::get_nebulaconfig_file; pub enum APIWorkerMessage { Shutdown, Enroll { code: String }, Timer } pub fn apiworker_main(config: TFClientConfig, instance: String, url: String, _transmitters: ThreadMessageSender, rx: Receiver) { let server = Url::parse(&url).unwrap(); let client = Client::new(format!("tfclient/{}", env!("CARGO_PKG_VERSION")), server).unwrap(); loop { match rx.try_recv() { Ok(msg) => { match msg { APIWorkerMessage::Shutdown => { info!("recv on command socket: shutdown, stopping"); break; }, APIWorkerMessage::Timer => { info!("updating config"); let mut cdata = match load_cdata(&instance) { Ok(c) => c, Err(e) => { error!("error in api worker thread: {}", e); error!("APIWorker exiting with error"); return; } }; if cdata.creds.is_none() { info!("not enrolled, cannot perform config update"); continue; } }, APIWorkerMessage::Enroll { code } => { info!("recv on command socket: enroll {}", code); let mut cdata = match load_cdata(&instance) { Ok(c) => c, Err(e) => { error!("error in api worker thread: {}", e); error!("APIWorker exiting with error"); return; } }; if cdata.creds.is_some() { warn!("enrollment failed: already enrolled"); continue; } let (config, dh_privkey, creds, meta) = match client.enroll(&code) { Ok(resp) => resp, Err(e) => { error!("error with enrollment request: {}", e); continue; } }; match fs::write(get_nebulaconfig_file(&instance).expect("Unable to determine nebula config file location"), config) { Ok(_) => (), Err(e) => { error!("unable to save nebula config: {}", e); continue; } } cdata.creds = Some(creds); cdata.dh_privkey = Some(dh_privkey.try_into().expect("32 != 32")); cdata.meta = Some(meta); // Save vardata match save_cdata(&instance, cdata) { Ok(_) => (), Err(e) => { error!("Error saving cdata: {}", e); error!("APIWorker exiting with error"); return; } } info!("Configuration updated. Sending signal to Nebula worker thread"); } } }, Err(e) => { match e { TryRecvError::Empty => {} TryRecvError::Disconnected => { error!("apiworker command socket disconnected, shutting down to prevent orphaning"); break; } } } } } }