Skip to content

Commit

Permalink
use only config dir where all configs and relevant files are stored
Browse files Browse the repository at this point in the history
  • Loading branch information
beac0n committed Jul 7, 2024
1 parent abc464b commit b34ac75
Show file tree
Hide file tree
Showing 12 changed files with 104 additions and 62 deletions.
2 changes: 1 addition & 1 deletion config/config.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
address = "127.0.0.1:8080"
pem_path = "/etc/ruroco/ruroco_public.pem"
config_dir = "/etc/ruroco/"

[commands]
2 changes: 1 addition & 1 deletion src/bin/commander.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@ fn main() -> Result<(), String> {
.map_err(|e| format!("Could not read {config_path:?}: {e}"))?;
let config: Config = toml::from_str(&config_str)
.map_err(|e| format!("Could not create TOML from {config_path:?}: {e}"))?;
Commander::create(config.commands, config.socket_user, config.socket_group, config.socket_path)
Commander::create(config.commands, config.socket_user, config.socket_group, config.config_dir)
.run()
}
2 changes: 1 addition & 1 deletion src/bin/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,5 @@ fn main() -> Result<(), String> {
.map_err(|e| format!("Could not read {config_path:?}: {e}"))?;
let config: Config = toml::from_str(&config_str)
.map_err(|e| format!("Could not create TOML from {config_path:?}: {e}"))?;
Server::create(config.pem_path, config.address, config.socket_path)?.run()
Server::create(config.config_dir, config.address)?.run()
}
6 changes: 4 additions & 2 deletions src/commander.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ use std::process::Command;
use log::{error, info, warn};
use users::{get_group_by_name, get_user_by_name};

use crate::common::get_socket_path;

pub struct Commander {
config: HashMap<String, String>,
socket_group: String,
Expand All @@ -22,13 +24,13 @@ impl Commander {
config: HashMap<String, String>,
socket_user: String,
socket_group: String,
socket_path: PathBuf,
config_dir: PathBuf,
) -> Commander {
Commander {
config,
socket_user,
socket_group,
socket_path,
socket_path: get_socket_path(config_dir),
}
}

Expand Down
7 changes: 7 additions & 0 deletions src/common.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::path::PathBuf;
use std::time::SystemTime;

use openssl::rsa::Padding;
Expand All @@ -15,3 +16,9 @@ pub fn time() -> Result<u128, String> {
.map_err(|e| format!("Could not get duration since: {e}"))?;
Ok(duration.as_nanos())
}

pub fn get_socket_path(config_dir: PathBuf) -> PathBuf {
let mut config_dir_clone = config_dir.clone();
config_dir_clone.push("ruroco.socket");
config_dir_clone
}
14 changes: 4 additions & 10 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,12 @@ pub struct Config {
pub commands: HashMap<String, String>,
#[serde(default = "default_address")]
pub address: String,
#[serde(default = "default_pem_path")]
pub pem_path: PathBuf, // TODO: add pem directory instead of path, so that multiple PEMs can be used
#[serde(default = "default_config_path")]
pub config_dir: PathBuf,
#[serde(default = "default_socket_user")]
pub socket_user: String,
#[serde(default = "default_socket_group")]
pub socket_group: String,
#[serde(default = "default_socket_path")]
pub socket_path: PathBuf,
}

fn default_socket_user() -> String {
Expand All @@ -38,10 +36,6 @@ fn default_address() -> String {
String::from("127.0.0.1:8080")
}

fn default_pem_path() -> PathBuf {
PathBuf::from("ruroco_public.pem")
}

fn default_socket_path() -> PathBuf {
PathBuf::from("/etc/ruroco/ruroco.socket")
fn default_config_path() -> PathBuf {
PathBuf::from("/etc/ruroco")
}
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
pub mod common;
pub mod server;
pub mod client;
pub mod commander;
pub mod common;
pub mod config;
pub mod server;
60 changes: 52 additions & 8 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use openssl::pkey::Public;
use openssl::rsa::Rsa;
use openssl::version::version;

use crate::common::{RSA_PADDING, time};
use crate::common::{get_socket_path, RSA_PADDING, time};

pub struct Server {
rsa: Rsa<Public>,
Expand All @@ -29,11 +29,8 @@ struct DecodedData {
}

impl Server {
pub fn create(
pem_path: PathBuf,
address: String,
socket_file_path: PathBuf,
) -> Result<Server, String> {
pub fn create(config_dir: PathBuf, address: String) -> Result<Server, String> {
let pem_path = Self::get_pem_path(&config_dir)?;
info!("Creating server, loading public PEM from {pem_path:?}, using {} ...", version());

let pem_data =
Expand Down Expand Up @@ -71,10 +68,47 @@ impl Server {
socket,
decrypted_data,
encrypted_data,
socket_path: socket_file_path,
socket_path: get_socket_path(config_dir),
})
}

fn get_pem_path(config_dir: &PathBuf) -> Result<PathBuf, String> {
let pem_files = Self::get_pem_files(&config_dir);

return match pem_files.len() {
0 => Err(format!("Could not find any .pem files in {config_dir:?}").into()),
1 => Ok(pem_files.first().unwrap().clone()),
other => Err(format!(
"Only one public PEM is supported at this point in time, found {other}"
)
.into()),
};
}

fn get_pem_files(config_dir: &PathBuf) -> Vec<PathBuf> {
let mut pem_paths = vec![];
match fs::read_dir(config_dir) {
Ok(entries) => {
for entry in entries {
match entry {
Ok(entry) => {
let path = entry.path();
match path.extension() {
Some(extension) if path.is_file() && extension == "pem" => {
pem_paths.push(path)
}
_ => {}
}
}
Err(e) => error!("Error reading entry: {e}"),
}
}
}
Err(e) => error!("Error reading directory: {e}"),
}
pem_paths
}

pub fn run(&mut self) -> Result<(), String> {
info!("Running server on udp://{}", self.address);
let rsa_size = self.rsa.size() as usize;
Expand Down Expand Up @@ -120,12 +154,22 @@ impl Server {
);
// TODO: blacklist data.deadline_ns until data.deadline_ns == data.now_ns
// TODO: remove all blacklisted timestamps that are now too old in the next validate call
self.send_command(&data.command_name)
self.send_command(&data.command_name);
self.clean_block_list();
self.add_to_block_list(data);
}
Err(e) => error!("Could not decode data: {e}"),
};
}

fn clean_block_list(&self) {
// TODO: implement
}

fn add_to_block_list(&self, data: DecodedData) {
// TODO: implement
}

fn send_command(&self, command_name: &str) {
match self.write_to_socket(command_name) {
Ok(_) => info!("Successfully sent data to commander"),
Expand Down
9 changes: 3 additions & 6 deletions tests/client_gen_test.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::fs;
use std::path::PathBuf;

use ruroco::client::gen;

#[cfg(test)]
Expand Down Expand Up @@ -27,9 +28,7 @@ mod tests {

assert_eq!(
result.unwrap_err().to_string(),
format!(
"Could not read PEM file: {private_file_name} does not end with .pem"
)
format!("Could not read PEM file: {private_file_name} does not end with .pem")
);
}

Expand All @@ -45,9 +44,7 @@ mod tests {

assert_eq!(
result.unwrap_err().to_string(),
format!(
"Could not read PEM file: {public_file_name} does not end with .pem"
)
format!("Could not read PEM file: {public_file_name} does not end with .pem")
);
}

Expand Down
11 changes: 4 additions & 7 deletions tests/commander_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,9 @@ mod tests {
#[test]
fn test_run() {
init_logger();
let socket_file_path = "/tmp/ruroco/ruroco.socket";
let socket_file_path = Path::new("/tmp/ruroco/ruroco.socket");
let _ = fs::remove_file(socket_file_path);

println!("{}", socket_file_path);

assert!(!Path::new(socket_file_path).exists());
assert!(!socket_file_path.exists());

let mut config = HashMap::new();
config.insert(String::from("default"), format!("touch {}", gen_file_name(".test")));
Expand All @@ -32,14 +29,14 @@ mod tests {
config,
String::from(""),
String::from(""),
PathBuf::from(socket_file_path),
PathBuf::from("/tmp/ruroco"),
)
.run()
.expect("commander terminated")
});

thread::sleep(Duration::from_secs(1));

assert!(Path::new(socket_file_path).exists());
assert!(socket_file_path.exists());
}
}
2 changes: 1 addition & 1 deletion tests/config.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
address = "127.0.0.1:8080"
pem_path = "/etc/ruroco/ruroco_public.pem"
config_dir = "/etc/ruroco/"

[commands]
default = "touch /tmp/ruroco_test/start.test /tmp/ruroco_test/stop.test"
47 changes: 24 additions & 23 deletions tests/integration_test.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#[cfg(test)]
mod tests {
use std::{fs, thread};
use std::{env, fs, thread};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::Duration;
Expand All @@ -10,7 +10,7 @@ mod tests {

use ruroco::client::{gen, send};
use ruroco::commander::Commander;
use ruroco::common::init_logger;
use ruroco::common::{get_socket_path, init_logger};
use ruroco::server::Server;

fn gen_file_name(suffix: &str) -> String {
Expand Down Expand Up @@ -44,25 +44,21 @@ mod tests {
let server_address = format!("127.0.0.1:{}", rand::thread_rng().gen_range(1024..65535));

let test_filename = gen_file_name(".test");
let socket_path = get_socket_path(env::current_dir().unwrap());
let public_pem_path = PathBuf::from(gen_file_name(".pem"));
let mut private_pem_path = env::current_dir().unwrap();
private_pem_path.push("tests");
private_pem_path.push(gen_file_name(".pem"));

let private_file = gen_file_name(".pem");
let public_file = gen_file_name(".pem");

let priv_pem_path = PathBuf::from(&private_file);
let pub_pem_path = PathBuf::from(&public_file);
gen(priv_pem_path.clone(), pub_pem_path.clone(), key_size).unwrap();
gen(private_pem_path.clone(), public_pem_path.clone(), key_size).unwrap();

let server_address_for_server = server_address.clone();

thread::spawn(move || {
Server::create(
pub_pem_path,
server_address_for_server,
PathBuf::from("/tmp/ruroco/ruroco.socket"),
)
.expect("could not create server")
.run()
.expect("server terminated")
Server::create(env::current_dir().unwrap(), server_address_for_server)
.expect("could not create server")
.run()
.expect("server terminated")
});

let mut config = HashMap::new();
Expand All @@ -73,30 +69,35 @@ mod tests {
config,
String::from(""),
String::from(""),
PathBuf::from("/tmp/ruroco/ruroco.socket"),
env::current_dir().unwrap(),
)
.run()
.expect("commander terminated")
});

send(priv_pem_path.clone(), server_address.to_string(), String::from("default"), 5).unwrap();
send(private_pem_path.clone(), server_address.to_string(), String::from("default"), 5)
.unwrap();
thread::sleep(Duration::from_secs(1)); // wait for commands to be executed

let _ = fs::remove_file(&test_filename);

send(priv_pem_path.clone(), server_address.to_string(), String::from("default"), 5).unwrap();
send(private_pem_path.clone(), server_address.to_string(), String::from("default"), 5)
.unwrap();
thread::sleep(Duration::from_secs(1)); // wait for commands to be executed

let start_test_exists = Path::new(&test_filename).exists();
let private_exists = Path::new(&private_file).exists();
let public_exists = Path::new(&public_file).exists();
let private_exists = private_pem_path.exists();
let public_exists = public_pem_path.exists();
let socket_exists = socket_path.exists();

let _ = fs::remove_file(&test_filename);
let _ = fs::remove_file(&private_file);
let _ = fs::remove_file(&public_file);
let _ = fs::remove_file(&private_pem_path);
let _ = fs::remove_file(&public_pem_path);
let _ = fs::remove_file(socket_path);

assert!(start_test_exists);
assert!(private_exists);
assert!(public_exists);
assert!(socket_exists);
}
}

0 comments on commit b34ac75

Please sign in to comment.