diff --git a/peach-lib/debug/.cargo/config b/peach-lib/debug/.cargo/config deleted file mode 100644 index 4b6f460..0000000 --- a/peach-lib/debug/.cargo/config +++ /dev/null @@ -1,4 +0,0 @@ -[target.aarch64-unknown-linux-gnu] -linker = "aarch64-linux-gnu-gcc" -objcopy = { path ="aarch64-linux-gnu-objcopy" } -strip = { path ="aarch64-linux-gnu-strip" } diff --git a/peach-lib/debug/Cargo.toml b/peach-lib/debug/Cargo.toml deleted file mode 100644 index 2c9f53e..0000000 --- a/peach-lib/debug/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "debug" -version = "0.1.0" -authors = ["notplants "] -edition = "2018" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -peach-lib = { path = "../" } -env_logger = "0.6" -chrono = "0.4.19" \ No newline at end of file diff --git a/peach-lib/debug/src/main.rs b/peach-lib/debug/src/main.rs deleted file mode 100644 index 19de0b3..0000000 --- a/peach-lib/debug/src/main.rs +++ /dev/null @@ -1,65 +0,0 @@ -use peach_lib::dyndns_client::{dyndns_update_ip, register_domain, is_dns_updater_online, log_successful_nsupdate, get_num_seconds_since_successful_dns_update }; -use peach_lib::password_utils::{verify_password, set_new_password, verify_temporary_password, set_new_temporary_password, send_password_reset}; -use peach_lib::config_manager::{add_ssb_admin_id, delete_ssb_admin_id}; -use peach_lib::sbot_client; -use std::process; -use chrono::prelude::*; - - -fn main() { - // initalize the logger - env_logger::init(); -// -// println!("Hello, world its debug!"); -// let result = set_new_password("password3"); -// println!("result: {:?}", result); -// -// let result = verify_password("password1"); -// println!("result should be error: {:?}", result); -// -// let result = verify_password("password3"); -// println!("result should be ok: {:?}", result); -// -// -// println!("Testing temporary passwords"); -// let result = set_new_temporary_password("abcd"); -// println!("result: {:?}", result); -// -// let result = verify_temporary_password("password1"); -// println!("result should be error: {:?}", result); -// -// let result = verify_temporary_password("abcd"); -// println!("result should be ok: {:?}", result); -// - let result = send_password_reset(); - println!("send password reset result should be ok: {:?}", result); - -// sbot_client::post("hi cat"); -// let result = sbot_client::whoami(); -// let result = sbot_client::create_invite(50); -// let result = sbot_client::post("is this working"); -// println!("result: {:?}", result); -// let result = sbot_client::post("nice we have contact"); -// let result = sbot_client::update_pub_name("vermont-pub"); -// let result = sbot_client::private_message("this is a private message", "@LZx+HP6/fcjUm7vef2eaBKAQ9gAKfzmrMVGzzdJiQtA=.ed25519"); -// println!("result: {:?}", result); - -// let result = send_password_reset(); -// let result = add_ssb_admin_id("xyzdab"); -// println!("result: {:?}", result); -// let result = delete_ssb_admin_id("xyzdab"); -// println!("result: {:?}", result); -// let result = delete_ssb_admin_id("ab"); -// println!("result: {:?}", result); - -//// let result = log_successful_nsupdate(); -//// let result = get_num_seconds_since_successful_dns_update(); -// let is_online = is_dns_updater_online(); -// println!("is online: {:?}", is_online); -// -//// let result = get_last_successful_dns_update(); -//// println!("result: {:?}", result); -//// register_domain("newquarter299.dyn.peachcloud.org"); -// let result = dyndns_update_ip(); -// println!("result: {:?}", result); -} diff --git a/peach-lib/examples/config.rs b/peach-lib/examples/config.rs new file mode 100644 index 0000000..2580150 --- /dev/null +++ b/peach-lib/examples/config.rs @@ -0,0 +1,11 @@ +use peach_lib::config_manager::{get_config_value, save_config_value}; + +fn main() { + println!("Running example of PeachCloud configuration management"); + let v = get_config_value("ADDR").unwrap(); + println!("ADDR: {}", v); + + save_config_value("ADDR", "1.1.1.1".to_string()); + let v = get_config_value("ADDR").unwrap(); + println!("ADDR: {}", v); +} diff --git a/peach-lib/src/config_manager.rs b/peach-lib/src/config_manager.rs index 343c8b6..abcb19f 100644 --- a/peach-lib/src/config_manager.rs +++ b/peach-lib/src/config_manager.rs @@ -11,11 +11,12 @@ //! The configuration file is located at: "/var/lib/peachcloud/config.yml" //! unless its path is configured by setting PEACH_CONFIG_PATH env variable. +use std::collections::{BTreeMap, HashMap}; use std::{env, fs}; -use std::collections::HashMap; use fslock::LockFile; use lazy_static::lazy_static; +use log::debug; use crate::error::PeachError; @@ -37,31 +38,6 @@ lazy_static! { static ref LOCK_FILE_PATH: String = format!("{}.lock", *CONFIG_PATH); } -// primary interface for getting config values -pub fn get_config_value(key: &str) -> Result { - // first check if it is an environmental variable - if let Ok(val) = env::var(key) { - Ok(val) - } else { - // then check disc - let peach_config_on_disc = load_peach_config_from_disc()?; - let val = peach_config_on_disc.get(key); - // then check defaults - match val { - Some(v) => Ok(v.to_string()), - None => { - match get_peach_config_defaults().get(key) { - Some(v) => Ok(v.to_string()), - None => { - Err(PeachError::InvalidKey { msg: format!("No default config value set for key: {}", key) }) - } - } - } - } - } -} - - // Default values for PeachCloud configs which are used for any key which is not set // via an environment variable or in a saved configuration file. pub fn get_peach_config_defaults() -> HashMap { @@ -72,36 +48,95 @@ pub fn get_peach_config_defaults() -> HashMap { ("PORT".to_string(), "8000".to_string()), ("EXTERNAL_DOMAIN".to_string(), "".to_string()), ("DYN_DOMAIN".to_string(), "".to_string()), - ("DYN_DNS_SERVER_ADDRESS".to_string(), "http://dynserver.dyn.peachcloud.org".to_string()), + ( + "DYN_DNS_SERVER_ADDRESS".to_string(), + "http://dynserver.dyn.peachcloud.org".to_string(), + ), ("DYN_USE_CUSTOM_SERVER".to_string(), "true".to_string()), ("DYN_TSIG_KEY_PATH".to_string(), "".to_string()), - ("DYN_NAMESERVER".to_string(), "ns.peachcloud.org".to_string()), + ( + "DYN_NAMESERVER".to_string(), + "ns.peachcloud.org".to_string(), + ), ("DYN_ENABLED".to_string(), "false".to_string()), - ("SSB_ADMIN_IDS".to_string(), "[]".to_string()), + ("SSB_ADMIN_IDS".to_string(), "".to_string()), ("ADMIN_PASSWORD_HASH".to_string(), "146".to_string()), ("TEMPORARY_PASSWORD_HASH".to_string(), "".to_string()), ("GO_SBOT_DATADIR".to_string(), "".to_string()), - ("PEACH_CONFIGDIR".to_string(), "/var/lib/peachcloud".to_string()), + ( + "PEACH_CONFIGDIR".to_string(), + "/var/lib/peachcloud".to_string(), + ), ]); peach_config_defaults } - -// helper function to load PeachCloud configuration files saved to disc -pub fn load_peach_config_from_disc() -> Result, PeachError> { - let peach_config : HashMap = HashMap::new(); - // TODO: implement - Ok(peach_config) +// primary interface for getting config values +// Config values are looked up from three locations in this order by key name: +// 1. from environmental variables +// 2. from a configuration file +// 3. from default values +pub fn get_config_value(key: &str) -> Result { + // first check if there is an environmental variable set + if let Ok(val) = env::var(key) { + Ok(val) + } else { + // then check if a value is set in the config file + let peach_config_on_disc = load_peach_config_from_disc()?; + let val = peach_config_on_disc.get(key); + // if no value is found in the config file, then get the default value + match val { + // return config value + Some(v) => Ok(v.to_string()), + // get default value + None => { + match get_peach_config_defaults().get(key) { + Some(v) => Ok(v.to_string()), + // if this key was not found in the defaults, then it was an invalid key + None => Err(PeachError::InvalidKey { + key: key.to_string(), + }), + } + } + } + } } -pub fn save_peach_config_to_disc(peach_config: HashMap) -> Result, PeachError> { +// helper function to load PeachCloud configuration file saved to disc +pub fn load_peach_config_from_disc() -> Result, PeachError> { + let peach_config_exists = std::path::Path::new(CONFIG_PATH.as_str()).exists(); + // if config file does not exist, return an emtpy HashMap + if !peach_config_exists { + let peach_config: HashMap = HashMap::new(); + Ok(peach_config) + } + // otherwise we load peach config from disk + else { + debug!("Loading peach config: {} exists", CONFIG_PATH.as_str()); + let contents = + fs::read_to_string(CONFIG_PATH.as_str()).map_err(|source| PeachError::Read { + source, + path: CONFIG_PATH.to_string(), + })?; + let peach_config: HashMap = serde_yaml::from_str(&contents)?; + Ok(peach_config) + } +} +// helper function to save PeachCloud configuration file to disc +// takes in a Hashmap and saves the whole HashMap as a yaml file +// with the keys in alphabetical order +pub fn save_peach_config_to_disc( + peach_config: HashMap, +) -> Result, PeachError> { // use a file lock to avoid race conditions while saving config let mut lock = LockFile::open(&*LOCK_FILE_PATH)?; lock.lock()?; - // convert HashMap to yaml - let yaml_str = serde_yaml::to_string(&peach_config)?; + // first convert Hashmap to BTreeMap (so that keys are saved in deterministic alphabetical order) + let ordered: BTreeMap<_, _> = peach_config.iter().collect(); + // then serialize BTreeMap as yaml + let yaml_str = serde_yaml::to_string(&ordered)?; // write yaml to file fs::write(CONFIG_PATH.as_str(), yaml_str).map_err(|source| PeachError::Write { @@ -116,9 +151,8 @@ pub fn save_peach_config_to_disc(peach_config: HashMap) -> Resul Ok(peach_config) } -// helper functions for serializing and deserializing PeachConfig from disc -pub fn save_peach_config_value(key: &str, value: String) -> Result, PeachError> { - +// helper functions for serializing and deserializing PeachConfig values from disc +pub fn save_config_value(key: &str, value: String) -> Result, PeachError> { // get current config from disc let mut peach_config = load_peach_config_from_disc()?; @@ -129,7 +163,6 @@ pub fn save_peach_config_value(key: &str, value: String) -> Result "true", - false => "false" + false => "false", }; peach_config.insert("DYN_DOMAIN".to_string(), dyn_domain.to_string()); - peach_config.insert("DYN_DNS_SERVER_ADDRESS".to_string(), dyn_dns_server_address.to_string()); - peach_config.insert("DYN_TSIG_KEY_PATH".to_string(), dyn_tsig_key_path.to_string()); + peach_config.insert( + "DYN_DNS_SERVER_ADDRESS".to_string(), + dyn_dns_server_address.to_string(), + ); + peach_config.insert( + "DYN_TSIG_KEY_PATH".to_string(), + dyn_tsig_key_path.to_string(), + ); peach_config.insert("DYN_ENABLED".to_string(), dyn_enabled_str.to_string()); save_peach_config_to_disc(peach_config) } -pub fn set_external_domain(new_external_domain: &str) -> Result, PeachError> { - save_peach_config_value("EXTERNAL_DOMAIN", new_external_domain.to_string()) +pub fn set_external_domain( + new_external_domain: &str, +) -> Result, PeachError> { + save_config_value("EXTERNAL_DOMAIN", new_external_domain.to_string()) } pub fn get_peachcloud_domain() -> Result, PeachError> { let external_domain = get_config_value("EXTERNAL_DOMAIN")?; let dyn_domain = get_config_value("DYN_DOMAIN")?; if !external_domain.is_empty() { - Ok(Some(external_domain.to_string())) + Ok(Some(external_domain)) } else if !dyn_domain.is_empty() { - Ok(Some(dyn_domain.to_string())) + Ok(Some(dyn_domain)) } else { Ok(None) } @@ -169,24 +210,59 @@ pub fn get_dyndns_server_address() -> Result { get_config_value("DYN_DNS_SERVER_ADDRESS") } -pub fn set_dyndns_enabled_value(enabled_value: bool) -> Result, PeachError> { +pub fn set_dyndns_enabled_value( + enabled_value: bool, +) -> Result, PeachError> { match enabled_value { - true => save_peach_config_value("DYN_ENABLED", "true".to_string()), - false => save_peach_config_value("DYN_ENABLED", "false".to_string()) + true => save_config_value("DYN_ENABLED", "true".to_string()), + false => save_config_value("DYN_ENABLED", "false".to_string()), } } pub fn get_dyndns_enabled_value() -> Result { let val = get_config_value("DYN_ENABLED")?; - return Ok(val == "true") + Ok(val == "true") } +pub fn set_admin_password_hash( + password_hash: String, +) -> Result, PeachError> { + save_config_value("ADMIN_PASSWORD_HASH", password_hash) +} + +pub fn get_admin_password_hash() -> Result { + let admin_password_hash = get_config_value("ADMIN_PASSWORD_HASH")?; + if !admin_password_hash.is_empty() { + Ok(admin_password_hash) + } else { + Err(PeachError::PasswordNotSet) + } +} + +pub fn set_temporary_password_hash( + password_hash: String, +) -> Result, PeachError> { + save_config_value("TEMPORARY_PASSWORD_HASH", password_hash) +} + +pub fn get_temporary_password_hash() -> Result { + let admin_password_hash = get_config_value("TEMPORARY_PASSWORD_HASH")?; + if !admin_password_hash.is_empty() { + Ok(admin_password_hash) + } else { + Err(PeachError::PasswordNotSet) + } +} + +// add ssb_id to vector of admin ids and save new value for SSB_ADMIN_IDS pub fn add_ssb_admin_id(ssb_id: &str) -> Result, PeachError> { let mut ssb_admin_ids = get_ssb_admin_ids()?; ssb_admin_ids.push(ssb_id.to_string()); save_ssb_admin_ids(ssb_admin_ids) } +// remove ssb_id from vector of admin ids if found and save new value for SSB_ADMIN_IDS +// if value is not found then return an error pub fn delete_ssb_admin_id(ssb_id: &str) -> Result, PeachError> { let mut ssb_admin_ids = get_ssb_admin_ids()?; let index_result = ssb_admin_ids.iter().position(|x| *x == ssb_id); @@ -201,39 +277,16 @@ pub fn delete_ssb_admin_id(ssb_id: &str) -> Result, PeachError> { } } -pub fn save_ssb_admin_ids(ssb_admin_ids: Vec) -> Result, PeachError> { - // save_peach_config_value("SSB_ADMIN_IDS", ssb_admin_ids.to_string()) - // TODO: implement - Ok(ssb_admin_ids) -} - -pub fn set_admin_password_hash(password_hash: String) -> Result, PeachError> { - save_peach_config_value("ADMIN_PASSWORD_HASH", password_hash) -} - -pub fn get_admin_password_hash() -> Result { - let admin_password_hash = get_config_value("ADMIN_PASSWORD_HASH")?; - if !admin_password_hash.is_empty() { - Ok(admin_password_hash.to_string()) - } else { - Err(PeachError::PasswordNotSet) - } -} - -pub fn set_temporary_password_hash(password_hash: String) -> Result, PeachError> { - save_peach_config_value("TEMPORARY_PASSWORD_HASH", password_hash) -} - -pub fn get_temporary_password_hash() -> Result { - let admin_password_hash = get_config_value("TEMPORARY_PASSWORD_HASH")?; - if !admin_password_hash.is_empty() { - Ok(admin_password_hash.to_string()) - } else { - Err(PeachError::PasswordNotSet) - } -} - +// looks up the String value for SSB_ADMIN_IDS and converts it into a Vec pub fn get_ssb_admin_ids() -> Result, PeachError> { - let mut ssb_admin_ids = vec!["x".to_string(), "y".to_string(), "z".to_string()]; + let ssb_admin_ids_str = get_config_value("SSB_ADMIN_IDS")?; + let ssb_admin_ids: Vec = serde_json::from_str(&ssb_admin_ids_str)?; + Ok(ssb_admin_ids) +} + +// takes in a Vec and saves SSB_ADMIN_IDS as a json string representation of this vec +pub fn save_ssb_admin_ids(ssb_admin_ids: Vec) -> Result, PeachError> { + let ssb_admin_ids_as_json_str = serde_json::to_string(&ssb_admin_ids)?; + save_config_value("SSB_ADMIN_IDS", ssb_admin_ids_as_json_str)?; Ok(ssb_admin_ids) } diff --git a/peach-lib/src/dyndns_client.rs b/peach-lib/src/dyndns_client.rs index a169d25..cfa8acf 100644 --- a/peach-lib/src/dyndns_client.rs +++ b/peach-lib/src/dyndns_client.rs @@ -18,7 +18,9 @@ use jsonrpc_client_http::HttpTransport; use log::{debug, info}; use regex::Regex; -use crate::config_manager::{get_dyndns_server_address, get_config_value, get_dyndns_enabled_value}; +use crate::config_manager::{ + get_config_value, get_dyndns_enabled_value, get_dyndns_server_address, +}; use crate::{config_manager, error::PeachError}; /// constants for dyndns configuration @@ -120,11 +122,7 @@ pub fn dyndns_update_ip() -> Result { dyn_enabled: {:?} dyn_nameserver: {:?} ", - dyn_tsig_key_path, - dyn_domain, - dyn_dns_server_address, - dyn_enabled, - dyn_nameserver, + dyn_tsig_key_path, dyn_domain, dyn_dns_server_address, dyn_enabled, dyn_nameserver, ); if !dyn_enabled { info!("dyndns is not enabled, not updating"); @@ -132,10 +130,7 @@ pub fn dyndns_update_ip() -> Result { } else { // call nsupdate passing appropriate configs let mut nsupdate_command = Command::new("nsupdate"); - nsupdate_command - .arg("-k") - .arg(&dyn_tsig_key_path) - .arg("-v"); + nsupdate_command.arg("-k").arg(&dyn_tsig_key_path).arg("-v"); // pass nsupdate commands via stdin let public_ip_address = get_public_ip_address()?; info!("found public ip address: {}", public_ip_address); diff --git a/peach-lib/src/error.rs b/peach-lib/src/error.rs index 7d49111..42a4993 100644 --- a/peach-lib/src/error.rs +++ b/peach-lib/src/error.rs @@ -9,7 +9,8 @@ use std::{io, str, string}; pub enum PeachError { /// Represents looking up a Config value with a non-existent key InvalidKey { - msg: String, + /// the key value which was invalid + key: String, }, /// Represents a failure to determine the path of the user's home directory. @@ -107,7 +108,7 @@ impl std::error::Error for PeachError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match *self { PeachError::HomeDir => None, - PeachError::InvalidKey{ .. } => None, + PeachError::InvalidKey { .. } => None, PeachError::Io(_) => None, PeachError::JsonRpcClientCore(_) => None, PeachError::JsonRpcCore(_) => None, @@ -136,8 +137,8 @@ impl std::error::Error for PeachError { impl std::fmt::Display for PeachError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match *self { - PeachError::InvalidKey { ref msg} => { - write!(f, "Invalid key in config lookup: {}", msg) + PeachError::InvalidKey { ref key } => { + write!(f, "Invalid key in config lookup for key: {}", key) } PeachError::HomeDir => { write!( diff --git a/peach-lib/src/sbot.rs b/peach-lib/src/sbot.rs index 0c0d816..ee9434f 100644 --- a/peach-lib/src/sbot.rs +++ b/peach-lib/src/sbot.rs @@ -5,7 +5,6 @@ use std::{fs, fs::File, io, io::Write, path::PathBuf, process::Command, str}; use serde::{Deserialize, Serialize}; use crate::error::PeachError; -use crate::config_manager::get_config_value; /* HELPER FUNCTIONS */