Skip to content

Commit

Permalink
Refactor code aesthetics
Browse files Browse the repository at this point in the history
  • Loading branch information
danielpclark committed Dec 20, 2017
1 parent d95a761 commit d863418
Show file tree
Hide file tree
Showing 10 changed files with 175 additions and 112 deletions.
5 changes: 3 additions & 2 deletions src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
// copied, modified, or distributed except according to those terms.

use digits::Digits;
use ::model::work_load::WorkLoad;
use ::model::cli_reporter::CliReporter;
use std::io::{Read};
use std::process::{Command, Output};
use rayon::prelude::*;
Expand All @@ -16,9 +18,8 @@ use resume::{ResumeKey,ResumeFile};
use self::tempdir::TempDir;
use std::{fs,path,env};
use std::time::{Duration, Instant};
use ::{WorkLoad,ITERATIONS,SUCCESS};
use ::{ITERATIONS,SUCCESS};
use std::sync::{Arc, Mutex};
use reporter::CliReporter;
use std::sync::atomic::Ordering;

fn has_five_minutes_passed(t: Instant) -> bool {
Expand Down
86 changes: 55 additions & 31 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,50 +10,49 @@
extern crate digits;
extern crate rayon;
use digits::Digits;
use std::io::{self, Write};
mod web;
mod model;
use model::report_data::ReportData;
use model::work_load::WorkLoad;
mod resume;
mod result;
use result::Error;
use std::error::Error as StdError;
mod reporter;
mod process_input;
use process_input::*;
mod validators;
use validators::*;
mod core;
use core::*;
use std::io::{self, Write};
use result::Error;
use std::error::Error as StdError;
#[macro_use]
extern crate clap;
use clap::{Arg, App};
use std::sync::atomic::{AtomicUsize, AtomicBool, ATOMIC_USIZE_INIT, ATOMIC_BOOL_INIT};
extern crate serde_json;
use std::time::SystemTime;
use std::sync::{Arc, Mutex};
extern crate num_cpus;
extern crate tiny_http;
mod web;
use web::ReportData;

use std::thread;
use reporter::CliReporter;
extern crate libc;
use libc::pthread_cancel;
use std::os::unix::thread::{RawPthread,JoinHandleExt};
use std::os::unix::thread::{
RawPthread,
JoinHandleExt
};

use std::sync::atomic::{
AtomicUsize,
AtomicBool,
ATOMIC_USIZE_INIT,
ATOMIC_BOOL_INIT
};

static ITERATIONS: AtomicUsize = ATOMIC_USIZE_INIT;
static SUCCESS: AtomicBool = ATOMIC_BOOL_INIT;

pub struct WorkLoad(
pub String, // characters: String,
pub usize, // max: usize,
pub Digits, // mut sequencer: Digits,
pub String, // target: String,
pub Option<String>, // adj: Option<String>
pub Option<String>, // chunk: Option<String>
pub Option<usize>, // cluster_step: Option<(usize,usize)>
pub ReportData, // cloned ReportData for web JSON results and other reporters
pub CliReporter, // cli Reporter chosen
);

fn run_app() -> Result<(), Error> {
let matches = App::new("abrute - AES Brute Force File Decryptor").
version(&format!("v{}", crate_version!())[..]).
Expand Down Expand Up @@ -140,13 +139,20 @@ USE OF THIS BINARY FALLS UNDER THE MIT LICENSE (c) 2017").
validate_aescrpyt_executable()?;
}

let (min, max) = derive_min_max(matches.value_of("RANGE").unwrap())?;
let (min, max) = derive_min_max(
matches.value_of("RANGE").unwrap()
)?;

validate_start_string(&matches, max)?;

let mapping = derive_character_base(matches.value_of("CHARACTERS").unwrap());
let mapping = derive_character_base(
matches.value_of("CHARACTERS").unwrap()
);
let resume_key_chars = mapping_to_characters(&mapping);
let mut sequencer = Digits::new(mapping, matches.value_of("start").unwrap_or("").to_string());
let mut sequencer = Digits::new(
mapping,
matches.value_of("start").unwrap_or("").to_string()
);
sequencer.zero_fill(min as usize);

let target = matches.value_of("TARGET").unwrap_or("");
Expand All @@ -162,7 +168,9 @@ USE OF THIS BINARY FALLS UNDER THE MIT LICENSE (c) 2017").

let mut cluster_step: Option<usize> = None;
if matches.is_present("cluster") {
let (offset, step) = derive_cluster(matches.value_of("cluster").unwrap())?;
let (offset, step) = derive_cluster(
matches.value_of("cluster").unwrap()
)?;
cluster_step = Some(step);
let additive = sequencer.gen(offset as u64).pred_till_zero();
sequencer.mut_add(additive);
Expand Down Expand Up @@ -199,22 +207,33 @@ USE OF THIS BINARY FALLS UNDER THE MIT LICENSE (c) 2017").
// DATA for JSON web end point
let reporter_handler = ReportData {
cores: num_cpus::get() as u8,
chunk: chunk.clone().unwrap_or("").parse::<usize>().unwrap_or(32),
chunk: chunk.
clone().
unwrap_or("").
parse::<usize>().
unwrap_or(32),
cluster: {
if matches.is_present("cluster") {
Some(derive_cluster(matches.value_of("cluster").unwrap()).ok().unwrap())
Some(
derive_cluster(
matches.value_of("cluster").unwrap()
).ok().unwrap()
)
} else { None }
},
character_set: resume_key_chars.clone(),
start_time: SystemTime::now(),
start_at: sequencer.to_s(),
adjacent_limit: adjacent.map(|ref s| u8::from_str_radix(&s,10).ok().unwrap()),
five_min_progress: Arc::new(Mutex::new((0, "".to_string()))),
adjacent_limit: adjacent.map(|ref s|
u8::from_str_radix(&s,10).ok().unwrap()
),
five_min_progress: Arc::new(
Mutex::new((0, "".to_string()))
),
};

let web_reporter = reporter_handler.clone();

let web_runner: thread::JoinHandle<_> = thread::spawn(move || {
let web_runner = thread::spawn(move || {
web::host_data(&web_reporter)
});

Expand All @@ -241,8 +260,13 @@ USE OF THIS BINARY FALLS UNDER THE MIT LICENSE (c) 2017").
});

let wr: RawPthread = web_runner.as_pthread_t();

let cr = crypt_runner.join().unwrap();
unsafe { pthread_cancel(wr); }

unsafe {
pthread_cancel(wr);
}

cr
}

Expand Down
16 changes: 16 additions & 0 deletions src/model/cli_reporter.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
use ::Digits;

pub enum CliReporter {
TickerTape,
Spinner,
}

impl CliReporter {
#[inline]
pub fn report(&self, data: &Digits) {
match *self {
ref _thingy @ CliReporter::TickerTape => ::reporter::ticker_tape::report(data),
ref _thingy @ CliReporter::Spinner => ::reporter::spinner::report(data),
}
}
}
3 changes: 3 additions & 0 deletions src/model/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pub mod report_data;
pub mod cli_reporter;
pub mod work_load;
52 changes: 52 additions & 0 deletions src/model/report_data.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
use std::time::SystemTime;
extern crate serde;
use self::serde::ser::{Serialize, Serializer, SerializeStruct};
use std::sync::{Arc, Mutex};
use ::{ITERATIONS,SUCCESS};
use std::sync::atomic::Ordering;
use std::ops::Deref;

#[derive(Clone)]
pub struct ReportData {
pub cores: u8,
pub chunk: usize,
pub cluster: Option<(usize,usize)>,
pub character_set: String,
pub start_time: SystemTime,
pub start_at: String,
pub adjacent_limit: Option<u8>,
pub five_min_progress: Arc<Mutex<(usize, String)>>
}

impl Serialize for ReportData {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer {

let mut struct_fields = 9;
if self.cluster.is_some() { struct_fields += 2; }
if self.adjacent_limit.is_some() { struct_fields += 1; }

let mut state = serializer.serialize_struct("ReportData", struct_fields)?;
state.serialize_field("cores", &self.cores)?;
state.serialize_field("chunk", &self.chunk)?;
if let Some((node, cluster_size)) = self.cluster {
state.serialize_field("cluster_node", &node)?;
state.serialize_field("cluster_size", &cluster_size)?;
}
state.serialize_field("character_set", &self.character_set)?;
state.serialize_field("start_time", &self.start_time)?;
state.serialize_field("start_at", &self.start_at)?;
if let Some(adj) = self.adjacent_limit {
state.serialize_field("adjacent_limit", &adj)?;
}
state.serialize_field("iterations", &ITERATIONS.load(Ordering::SeqCst))?;
let getter = self.five_min_progress.lock().unwrap();
let &(five_min_iters, ref last_string) = getter.deref();
state.serialize_field("last_five_minute_iterations", &five_min_iters)?;
state.serialize_field("last_attempt", &last_string)?;
state.serialize_field("success", &SUCCESS.load(Ordering::SeqCst))?;
state.end()
}
}


15 changes: 15 additions & 0 deletions src/model/work_load.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
use ::Digits;
use ::model::report_data::ReportData;
use ::model::cli_reporter::CliReporter;

pub struct WorkLoad(
pub String, // characters: String,
pub usize, // max: usize,
pub Digits, // mut sequencer: Digits,
pub String, // target: String,
pub Option<String>, // adj: Option<String>
pub Option<String>, // chunk: Option<String>
pub Option<usize>, // cluster_step: Option<(usize,usize)>
pub ReportData, // cloned ReportData for web JSON results and other reporters
pub CliReporter, // cli Reporter chosen
);
19 changes: 14 additions & 5 deletions src/process_input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,22 @@

use digits::BaseCustom;
use super::result::Error;
use reporter::CliReporter;
use ::model::cli_reporter::CliReporter;

pub fn verify_reporter_name(rn: String) -> CliReporter {
match &rn[..] {
"spinner" => CliReporter::Spinner,
"ticker" => CliReporter::TickerTape,
_ => CliReporter::TickerTape,
}
}

pub fn derive_min_max(range: &str) -> Result<(usize, usize), Error> {
let rvals = range.split(':').collect::<Vec<&str>>();
for item in &rvals { if item.parse::<u8>().is_err() { return Err(Error::InvalidRange); } }
for item in &rvals {
if item.parse::<u8>().is_err() {
return Err(Error::InvalidRange);
}
}
let mut rivals = rvals.iter();
let min = rivals.next().unwrap();
let max = rivals.next();
Expand All @@ -36,13 +39,19 @@ pub fn derive_min_max(range: &str) -> Result<(usize, usize), Error> {
pub fn derive_cluster(range: &str) -> Result<(usize, usize), Error> {
let rvals = range.split(':').collect::<Vec<&str>>();
if rvals.len() != 2 { return Err(Error::InvalidRange); }
for item in &rvals { if item.parse::<usize>().is_err() { return Err(Error::InvalidRange); } }
for item in &rvals {
if item.parse::<usize>().is_err() {
return Err(Error::InvalidRange);
}
}
let mut rivals = rvals.iter();
let offset = rivals.next().unwrap();
let cluster_size = rivals.next().unwrap();
let offset = offset.parse::<usize>().unwrap();
let cluster_size = cluster_size.parse::<usize>().unwrap();
if offset > cluster_size || offset == 0 { return Err(Error::InvalidRange); }
if offset > cluster_size || offset == 0 {
return Err(Error::InvalidRange);
}
Ok((offset, cluster_size))
}

Expand Down
17 changes: 0 additions & 17 deletions src/reporter/mod.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,2 @@
pub mod ticker_tape;
pub mod spinner;
use ::Digits;

#[derive(Debug)]
pub enum CliReporter {
TickerTape,
Spinner,
}

impl CliReporter {
#[inline]
pub fn report(&self, data: &Digits) {
match *self {
ref _thingy @ CliReporter::TickerTape => ticker_tape::report(data),
ref _thingy @ CliReporter::Spinner => spinner::report(data),
}
}
}
20 changes: 15 additions & 5 deletions src/validators.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,22 @@ pub fn validate_chunk_input(v: &str) -> Result<(), Error> {

pub fn validate_start_string(matches: &clap::ArgMatches, max: usize) -> Result<(), Error> {
if let Some(s) = matches.value_of("start") {
if s.len() > max { return Err(Error::InvalidStringLength); }

let chrctrs: Vec<char> = matches.value_of("CHARACTERS").unwrap().chars().collect();
if s.len() > max {
return Err(Error::InvalidStringLength);
}

let chrctrs: Vec<char> = matches.
value_of("CHARACTERS").
unwrap().
chars().
collect();
let mut itr = s.chars();
loop {
match itr.next() {
Some(ref c) => {
if !chrctrs.contains(c) { return Err(Error::InvalidCharacterSet); }
if !chrctrs.contains(c) {
return Err(Error::InvalidCharacterSet);
}
},
_ => break,
}
Expand All @@ -50,7 +58,9 @@ pub fn validate_and_prep_sequencer_adjacent<'a>(
if let &Some(num) = &adjacent {
validate_adjacent_input(num.to_string())?;
if seq_base > 3 {
sequencer.prep_non_adjacent(num.parse::<usize>().unwrap());
sequencer.prep_non_adjacent(
num.parse::<usize>().unwrap()
);
}
}

Expand Down
Loading

0 comments on commit d863418

Please sign in to comment.