]>
code.octet-stream.net Git - hashgood/blob - src/main.rs
2 use std
::path
::PathBuf
;
4 use structopt
::StructOpt
;
6 /// Calculate digests for given input data
9 /// Display output nicely in the terminal
12 /// Collect candidate hashes based on options and match them against a calculated hash
16 #[structopt(name = "hashgood")]
18 /// Read the hash from the clipboard
19 #[cfg(feature = "paste")]
20 #[structopt(short = "p", long = "paste")]
23 /// Disable ANSI colours in output
24 #[structopt(short = "C", long = "no-colour")]
27 /// A file containing the hash to verify. It can either be a raw hash or a SHASUMS-style listing. Use `-` for standard input.
28 #[structopt(short = "c", long = "check", parse(from_os_str))]
29 hash_file
: Option
<PathBuf
>,
31 /// The file to be verified or `-` for standard input
32 #[structopt(name = "input", parse(from_os_str))]
35 /// A hash to verify, supplied directly on the command line
36 #[structopt(name = "hash")]
41 fn get_paste(&self) -> bool
{
42 #[cfg(feature = "paste")]
46 #[cfg(not(feature = "paste"))]
53 /// Types of supported digest algorithm
54 #[derive(Debug, PartialEq, Copy, Clone)]
62 /// Assume a hash type from the binary length. Fortunately the typical 3 algorithms we care about are different lengths.
63 pub fn from_len(len
: usize) -> Result
<Algorithm
, String
> {
65 16 => Ok(Algorithm
::Md5
),
66 20 => Ok(Algorithm
::Sha1
),
67 32 => Ok(Algorithm
::Sha256
),
68 _
=> Err(format
!("Unrecognised hash length: {} bytes", len
)),
73 /// The method by which one or more hashes were supplied to verify the calculated digest
74 pub enum VerificationSource
{
81 /// A complete standalone hash result
89 pub fn new(alg
: Algorithm
, bytes
: Vec
<u8>, path
: &PathBuf
) -> Self {
90 // Taking the filename component should always work?
91 // If not, just fall back to the full path
92 let filename
= match path
.file
_name
() {
93 Some(filename
) => filename
.to_string_lossy(),
94 None
=> path
.to_string_lossy(),
99 filename
: filename
.to_string(),
104 /// A possible hash to match against. The algorithm is assumed.
105 pub struct CandidateHash
{
107 filename
: Option
<String
>,
110 /// A list of candidate hashes that our input could potentially match. At this point it is
111 /// assumed that we will be verifying a digest of a particular, single algorithm.
112 pub struct CandidateHashes
{
114 hashes
: Vec
<CandidateHash
>,
115 source
: VerificationSource
,
118 /// Summary of an atetmpt to match the calculated digest against candidates
119 pub enum MatchLevel
{
125 /// The severity of any informational messages to be printed before the final result
126 pub enum MessageLevel
{
132 /// Overall details of an attempt to match the calculated digest against candidates
133 pub struct Verification
<'a
> {
134 match_level
: MatchLevel
,
135 comparison_hash
: Option
<&'a CandidateHash
>,
136 messages
: Vec
<(MessageLevel
, String
)>,
139 /// Entry point - run the program and handle errors ourselves cleanly.
141 /// At the moment there aren't really any errors that can be handled by the application. Therefore
142 /// stringly-typed errors are used and they are all captured here, where the problem is printed
143 /// and the application terminates with a non-zero return code.
145 hashgood().unwrap
_or
_else
(|e
| {
146 eprintln
!("Error: {}", e
);
151 /// Main application logic
152 fn hashgood() -> Result
<(), Box
<dyn Error
>> {
153 let opt
= get_verified_options()?
;
154 let candidates
= verify
::get_candidate_hashes(&opt
)?
;
155 let input
= calculate
::get_input_reader(&opt
.inp
ut
)?
;
156 if let Some(c
) = candidates
{
157 // If we have a candidate hash of a particular type, use that specific algorithm
158 let hashes
= calculate
::create_digests(&[c
.alg
], input
)?
;
159 for (alg
, bytes
) in hashes
{
160 // Should always be true
162 let hash
= Hash
::new(alg
, bytes
, &opt
.inp
ut
);
163 let verification
= verify
::verify_hash(&hash
, &c
);
166 verification
.comparison_hash
,
170 display
::print_messages(verification
.messages
, opt
.no_colour
)?
;
171 display
::print_match_level(verification
.match_level
, opt
.no_colour
)?
;
175 // If no candidate, calculate all three common digest types for output
176 let hashes
= calculate
::create_digests(
177 &[Algorithm
::Md5
, Algorithm
::Sha1
, Algorithm
::Sha256
],
180 for (alg
, bytes
) in hashes
{
184 filename
: opt
.inp
ut
.file
_name
().unwrap
().to_string_lossy().to_string(),
186 display
::print_hash(&hash
, None
, None
, opt
.no_colour
)?
;
192 /// Parse the command line options and check for ambiguous or inconsistent settings
193 fn get_verified_options() -> Result
<Opt
, String
> {
194 let opt
= Opt
::from_args();
196 opt
.hash
.is
_some
() as i32 + opt
.get_paste() as i32 + opt
.hash_file
.is
_some
() as i32;
197 if hash_methods
> 1 {
198 if opt
.hash
.is
_some
() {
199 eprintln
!("* specified as command line argument");
202 eprintln
!("* paste from clipboard (-p)")
204 if opt
.hash_file
.is
_some
() {
205 eprintln
!("* check hash from file (-c)")
207 return Err("Error: Hashes were provided by multiple methods. Use only one.".to_owned());
209 if opt
.inp
ut
.to_str() == Some("-")
210 && opt
.hash_file
.as_ref().and_then(|h
| h
.to_str()) == Some("-")
212 return Err("Error: Cannot use use stdin for both hash file and input data".to_owned());