Split into modules

This commit is contained in:
Andrey Golovizin 2023-04-09 22:12:15 +02:00
parent 72ed117cb0
commit f663a4f8b4
4 changed files with 158 additions and 137 deletions

67
src/keys.rs Normal file
View file

@ -0,0 +1,67 @@
use gethostname::gethostname;
use log::debug;
use std::io::Write;
use std::path::PathBuf;
use std::process;
use crate::dirs::get_data_dir;
#[derive(Debug)]
pub(crate) struct WireguardKeyPair {
pub public_key: String,
pub private_key: String,
}
pub(crate) fn get_keys(machine: Option<&PathBuf>) -> Result<WireguardKeyPair, anyhow::Error> {
let hostname: PathBuf;
let machine_subdir: &PathBuf = if let Some(machine) = machine {
machine
} else {
hostname = PathBuf::from(gethostname());
&hostname
};
let key_path = get_data_dir().join("keys").join(machine_subdir);
debug!("key path = {:?}", &key_path);
std::fs::create_dir_all(&key_path)?;
let private_key_path = key_path.join("key");
let private_key = if private_key_path.is_file() {
std::fs::read_to_string(private_key_path)?
} else {
let key = generate_private_key()?;
std::fs::write(private_key_path, key.as_bytes())?;
key
};
let public_key_path = key_path.join("pubkey");
let public_key = if public_key_path.is_file() {
std::fs::read_to_string(public_key_path)?
} else {
let key = generate_public_key(&private_key)?;
std::fs::write(public_key_path, key.as_bytes())?;
key
};
Ok(WireguardKeyPair {
private_key,
public_key,
})
}
fn generate_private_key() -> anyhow::Result<String> {
let privkey = process::Command::new("wg").arg("genkey").output()?.stdout;
Ok(String::from_utf8(privkey)?.trim_end().to_string())
}
fn generate_public_key(private_key: &str) -> anyhow::Result<String> {
let mut pubkey_cmd = process::Command::new("wg")
.arg("pubkey")
.stdin(process::Stdio::piped())
.stdout(process::Stdio::piped())
.spawn()?;
pubkey_cmd
.stdin
.as_mut()
.expect("no stdin")
.write_all(private_key.as_bytes())?;
let pubkey = pubkey_cmd.wait_with_output()?.stdout;
Ok(String::from_utf8(pubkey)?.trim_end().to_string())
}