Skip to content

Commit

Permalink
Merge pull request zeskeertwee#84 from sokorototo/main
Browse files Browse the repository at this point in the history
Added a new CLI subcommand `pipe`
  • Loading branch information
zeskeertwee authored Mar 16, 2024
2 parents 94dc085 + 9514dd9 commit a69f263
Show file tree
Hide file tree
Showing 13 changed files with 135 additions and 87 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ perf.data
perf.data.old
workspace.code-workspace
.cargo/config.toml
**.vach
45 changes: 7 additions & 38 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 4 additions & 6 deletions vach-cli/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "vach-cli"
version = "0.5.5"
version = "0.5.6"
edition = "2021"
authors = [
"Jasper Fortuin <[email protected]>",
Expand All @@ -21,10 +21,8 @@ path = "src/main.rs"
[dependencies]
vach = { version = "0.5.5", features = ["all"] }
clap = "3.1.15"
indicatif = "0.17.6"
anyhow = "1.0.57"
indicatif = "0.17.8"
anyhow = "1.0.81"
tabled = "0.15.0"
log = "0.4.17"
walkdir = "2.3.2"
pretty_env_logger = "0.5.0"
walkdir = "2.5.0"
term_size = "0.3.2"
11 changes: 11 additions & 0 deletions vach-cli/src/app/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,17 @@ pub fn build_app<'a>(key_map: HashMap<&'static str, Arg<'a>>) -> Command<'a> {
.arg(key_map.get(key_names::PUBLIC_KEY).unwrap())
.arg(key_map.get(key_names::TRUNCATE).unwrap()),
)
.subcommand(
Command::new("pipe")
.author(AUTHORS)
.version(commands::pipe::VERSION)
.about("Pipes the contents of a .vach archive to stdout")
.arg(key_map.get(key_names::INPUT).unwrap())
.arg(key_map.get(key_names::MAGIC).unwrap())
.arg(key_map.get(key_names::PUBLIC_KEY).unwrap())
.arg(key_map.get(key_names::RESOURCE).unwrap())
.arg(key_map.get(key_names::KEYPAIR).unwrap()),
)
.subcommand(
Command::new("pack")
.author(AUTHORS)
Expand Down
6 changes: 3 additions & 3 deletions vach-cli/src/commands/keypair.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,13 @@ impl CommandTrait for Evaluator {
pk_path.push_str(".pk");

utils::create_and_write_to_file(&sk_path, &kp.to_bytes())?;
log::info!("Secret Key successfully generated and saved in: {}", sk_path);
println!("Secret Key successfully generated and saved in: {}", sk_path);

utils::create_and_write_to_file(&pk_path, &kp.verifying_key().to_bytes())?;
log::info!("Public Key successfully generated and saved in: {}", pk_path);
println!("Public Key successfully generated and saved in: {}", pk_path);
} else {
utils::create_and_write_to_file(&output_path, &kp.to_keypair_bytes())?;
log::info!("KeyPair successfully generated and saved in: {}", output_path);
println!("KeyPair successfully generated and saved in: {}", output_path);
}

Ok(())
Expand Down
2 changes: 2 additions & 0 deletions vach-cli/src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ pub trait CommandTrait: Sync {
pub mod keypair;
pub mod list;
pub mod pack;
pub mod pipe;
pub mod split;
pub mod unpack;
pub mod verify;
Expand All @@ -28,6 +29,7 @@ pub fn build_commands() -> HashMap<&'static str, Box<dyn CommandTrait>> {
map.insert("list", Box::new(list::Evaluator));
map.insert("unpack", Box::new(unpack::Evaluator));
map.insert("pack", Box::new(pack::Evaluator));
map.insert("pipe", Box::new(pipe::Evaluator));

map
}
8 changes: 4 additions & 4 deletions vach-cli/src/commands/pack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ impl CommandTrait for Evaluator {
match path.canonicalize() {
Ok(path) => Some(path),
Err(err) => {
log::warn!(
eprintln!(
"Failed to evaluate: {}. Skipping due to error: {}",
path.to_string_lossy(),
err
Expand All @@ -113,7 +113,7 @@ impl CommandTrait for Evaluator {
let path_filter = |path: &PathBuf| match path.canonicalize() {
Ok(canonical) => !excludes.contains(&canonical) && canonical.is_file(),
Err(err) => {
log::warn!(
eprintln!(
"Failed to evaluate: {}. Skipping due to error: {}",
path.to_string_lossy(),
err
Expand Down Expand Up @@ -183,7 +183,7 @@ impl CommandTrait for Evaluator {

let mut file = File::create("keypair.kp")?;
file.write_all(&generated.to_keypair_bytes())?;
log::info!("Generated a new keypair @ keypair.kp");
println!("Generated a new keypair @ keypair.kp");

kp = Some(generated);
}
Expand Down Expand Up @@ -247,7 +247,7 @@ impl CommandTrait for Evaluator {
.trim_start_matches("./")
.trim_start_matches(".\\")
.to_string();
log::info!("Preparing {} for packaging", id);
println!("Preparing {} for packaging", id);
builder.add(wrapper, &id)?;
}

Expand Down
79 changes: 79 additions & 0 deletions vach-cli/src/commands/pipe.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
use std::{
fs::File,
io::{self, BufReader, Write},
};
use vach::{crypto_utils, prelude::*};

use super::CommandTrait;
use crate::keys::key_names;

pub const VERSION: &str = "0.1.0";

pub struct Evaluator;

impl CommandTrait for Evaluator {
fn evaluate(&self, args: &clap::ArgMatches) -> anyhow::Result<()> {
let input_path = match args.value_of(key_names::INPUT) {
Some(path) => path,
None => anyhow::bail!("Please provide an input path using the -i or --input key"),
};

let resource = match args.value_of(key_names::RESOURCE) {
Some(resource) => resource,
None => anyhow::bail!("Please provide a resource to extract using the -r or --resource key"),
};

let magic: [u8; vach::MAGIC_LENGTH] = match args.value_of(key_names::MAGIC) {
Some(magic) => magic.as_bytes().try_into()?,
None => *vach::DEFAULT_MAGIC,
};

// Attempting to extract a public key from a -p or -k input
let public_key = match args.value_of(key_names::KEYPAIR) {
Some(path) => {
let file = match File::open(path) {
Ok(it) => it,
Err(err) => anyhow::bail!("IOError: {} @ {}", err, path),
};

Some(crypto_utils::read_keypair(file)?.verifying_key())
},
None => match args.value_of(key_names::PUBLIC_KEY) {
Some(path) => {
let file = File::open(path)?;
Some(crypto_utils::read_public_key(file)?)
},
None => None,
},
};

let input_file = match File::open(input_path) {
Ok(it) => BufReader::new(it),
Err(err) => anyhow::bail!("IOError: {} @ {}", err, input_path),
};

// Generate ArchiveConfig using given magic and public key
let header_config = ArchiveConfig::new(magic, public_key);

// Parse then extract archive
let mut archive = match Archive::with_config(input_file, &header_config) {
Ok(archive) => archive,
Err(err) => match err {
InternalError::NoKeypairError => anyhow::bail!(
"Please provide a public key or a keypair for use in decryption or signature verification"
),
InternalError::MalformedArchiveSource(_) => anyhow::bail!("Unable to validate the archive: {}", err),
err => anyhow::bail!("Encountered an error: {}", err.to_string()),
},
};

let stdout = io::stdout();
{
let mut handle = stdout.lock();
let resource = archive.fetch_mut(resource)?;
handle.write_all(&resource.data)?;
}

Ok(())
}
}
6 changes: 2 additions & 4 deletions vach-cli/src/commands/split.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,9 @@ impl CommandTrait for Evaluator {
utils::create_and_write_to_file(&pk_path, &kp.verifying_key().to_bytes())?;
utils::create_and_write_to_file(&sk_path, &kp.to_bytes())?;

log::info!(
println!(
"Successfully split keypair: {} -> into {} and {}",
input_path,
pk_path,
sk_path
input_path, pk_path, sk_path
);

Ok(())
Expand Down
10 changes: 5 additions & 5 deletions vach-cli/src/commands/unpack.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::fs::{self, File};
use std::str::FromStr;
use std::io::{Read, Seek, Write};
use std::io::{BufReader, Read, Seek, Write};
use std::path::PathBuf;
use std::time::Instant;

Expand All @@ -12,7 +12,7 @@ use indicatif::{ProgressBar, ProgressStyle};
use super::CommandTrait;
use crate::keys::key_names;

pub const VERSION: &str = "0.1.0";
pub const VERSION: &str = "0.1.1";

/// This command extracts an archive into the specified output folder
pub struct Evaluator;
Expand Down Expand Up @@ -61,7 +61,7 @@ impl CommandTrait for Evaluator {
let truncate = args.is_present(key_names::TRUNCATE);

let input_file = match File::open(input_path) {
Ok(it) => it,
Ok(it) => BufReader::new(it),
Err(err) => anyhow::bail!("IOError: {} @ {}", err, input_path),
};

Expand All @@ -84,7 +84,7 @@ impl CommandTrait for Evaluator {

// Delete original archive
if truncate {
log::info!("Truncating original archive @ {}", &input_path);
println!("Truncating original archive @ {}", &input_path);
std::fs::remove_file(input_path)?;
};

Expand Down Expand Up @@ -141,7 +141,7 @@ fn extract_archive<T: Read + Seek + Send + Sync>(archive: &Archive<T>, target_fo

// Finished extracting
pbar.finish();
log::info!(
println!(
"Extracted {} files in {}s",
archive.entries().len(),
time.elapsed().as_secs_f64()
Expand Down
14 changes: 14 additions & 0 deletions vach-cli/src/keys/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::collections::HashMap;
pub mod key_names {
pub(crate) const OUTPUT: &str = "OUTPUT";
pub(crate) const INPUT: &str = "INPUT";
pub(crate) const RESOURCE: &str = "RESOURCE";

pub(crate) const DIR_INPUT: &str = "DIR_INPUT";
pub(crate) const DIR_INPUT_REC: &str = "DIR_INPUT_REC";
Expand Down Expand Up @@ -45,6 +46,19 @@ pub fn build_keys<'a>() -> HashMap<&'static str, Arg<'a>> {
.number_of_values(1),
);

// A resource to focus on and extract
map.insert(
key_names::RESOURCE,
Arg::new(key_names::RESOURCE)
.short('r')
.long("resource")
.value_name(key_names::RESOURCE)
.help("An exact resource to extract from the archive")
.required(false)
.takes_value(true)
.number_of_values(1),
);

// A general input source
map.insert(
key_names::INPUT,
Expand Down
Loading

0 comments on commit a69f263

Please sign in to comment.