Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat!: add service management cli commands #11

Merged
merged 1 commit into from
May 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 85 additions & 3 deletions src/bin/main.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use std::fs::File;
use std::io::Read;

use clap::Parser;
use clap::{Parser, Subcommand};

use onionpipe::{config, OnionPipe, Result};
use onionpipe::{config, OnionPipe, PipeError, Result};

#[derive(Parser)]
#[command(name = "onionpipe")]
Expand All @@ -12,13 +12,36 @@ struct Cli {
#[arg(long)]
config: Option<std::path::PathBuf>,

#[clap(subcommand)]
commands: Option<Commands>,

forwards: Vec<String>,
}

#[derive(Subcommand)]
enum Commands {
#[clap(subcommand)]
Service(ServiceCommands),
}

#[derive(Subcommand)]
enum ServiceCommands {
Add { name: String },
Delete { name: String },
List,
}

#[tokio::main]
async fn main() {
let cli = Cli::parse();
let rc = match run(cli).await {

let result = match &cli.commands {
Some(Commands::Service(ServiceCommands::Add { ref name })) => add_service(name).await,
Some(Commands::Service(ServiceCommands::Delete { ref name })) => delete_service(name).await,
Some(Commands::Service(ServiceCommands::List)) => list_services().await,
None => run(cli).await,
};
let rc = match result {
Ok(_) => 0,
Err(e) => {
eprintln!("{}", e);
Expand All @@ -28,6 +51,65 @@ async fn main() {
std::process::exit(rc)
}

async fn add_service(name: &str) -> Result<()> {
let config_dir = match dirs::config_dir() {
Some(dir) => dir,
None => {
return Err(PipeError::CLI("failed to locate config dir".to_string()));
}
};
let secrets_dir = config_dir.join("onionpipe");
let mut secret_store = onionpipe::secrets::SecretStore::new(secrets_dir.to_str().unwrap());
let key_bytes = secret_store.ensure_service(name)?;
let onion_addr = torut::onion::TorSecretKeyV3::from(key_bytes)
.public()
.get_onion_address()
.to_string();
println!("{}\t{}", name, onion_addr);
Ok(())
}

async fn delete_service(name: &str) -> Result<()> {
let config_dir = match dirs::config_dir() {
Some(dir) => dir,
None => {
return Err(PipeError::CLI("failed to locate config dir".to_string()));
}
};
let secrets_dir = config_dir.join("onionpipe");
let mut secret_store = onionpipe::secrets::SecretStore::new(secrets_dir.to_str().unwrap());
match secret_store.delete_service(name)? {
Some(()) => {
println!("service {} deleted", name);
Ok(())
}
None => Err(PipeError::CLI(
format!("{}: service not found", name).to_string(),
)),
}
}

async fn list_services() -> Result<()> {
let config_dir = match dirs::config_dir() {
Some(dir) => dir,
None => {
return Err(PipeError::CLI("failed to locate config dir".to_string()));
}
};
let secrets_dir = config_dir.join("onionpipe");
let secret_store = onionpipe::secrets::SecretStore::new(secrets_dir.to_str().unwrap());
let services = secret_store.list_services()?;
for service_name in services {
let key_bytes = secret_store.get_service(&service_name)?.unwrap();
let onion_addr = torut::onion::TorSecretKeyV3::from(key_bytes)
.public()
.get_onion_address()
.to_string();
println!("{}\t{}", service_name, onion_addr);
}
Ok(())
}

async fn run(cli: Cli) -> Result<()> {
unsafe {
libc::umask(0o077);
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ pub enum PipeError {
Join(#[from] tokio::task::JoinError),
#[error("invalid socket address: {0}")]
ParseAddr(#[from] net::AddrParseError),
#[error("command failed: {0}")]
CLI(String),
#[error("invalid config: {0}")]
Config(String),
#[error("config parse error: {0}")]
Expand Down
17 changes: 17 additions & 0 deletions src/secrets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,23 @@ impl SecretStore {
}
}

pub fn get_service(&self, name: &str) -> Result<Option<[u8; 64]>> {
let service_dir = path::PathBuf::from(&self.secrets_dir).join(SERVICES_DIR);
if !service_dir.exists() {
Ok(None)
} else {
let service_file = service_dir.join(name);
if !service_file.exists() {
Ok(None)
} else {
let contents = fs::read(&service_file)?;
let mut key = [0; 64];
key.copy_from_slice(&contents);
Ok(Some(key))
}
}
}

pub fn ensure_service(&mut self, name: &str) -> Result<[u8; 64]> {
let service_dir = path::PathBuf::from(&self.secrets_dir).join(SERVICES_DIR);
if !service_dir.exists() {
Expand Down