1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
// Copyright (c) 2016 est31 <MTest31@outlook.com>
// and contributors. All rights reserved.
// Licensed under MIT license, or Apache 2 license,
// at your option. Please see the LICENSE file
// attached to this source distribution for details.

#![forbid(unsafe_code)]
#![cfg_attr(test, deny(warnings))]

/*!
Download test assets, managing them outside of git.

This library downloads test assets using http(s),
and ensures integrity by comparing those assets to a hash.

By managing the download separately, you can keep them
out of VCS and don't make them bloat your repository.

Usage example:

```
#[test]
fn some_awesome_test() {
	let asset_defs = [
		TestAssetDef {
			filename : format!("file_a.png"),
			hash : format!("<sha256 here>"),
			url : format!("https://url/to/a.png"),
		},
		TestAssetDef {
			filename : format!("file_b.png"),
			hash : format!("<sha256 here>"),
			url : format!("https://url/to/a.png"),
		},
	];
	test_assets::download_test_files(&asset_defs,
		"test-assets", true).unwrap();
	// use your files here
	// with path under test-assets/file_a.png and test-assets/file_b.png
}
```

If you have run the test once, it will re-use the files
instead of re-downloading them.
*/

extern crate sha2;
extern crate curl;

mod hash_list;

use std::io;
use curl::easy::Easy;
use sha2::sha2::Sha256;
use sha2::digest::Digest;
use hash_list::HashList;
use std::fs::create_dir_all;


/// Definition for a test file
///
///
pub struct TestAssetDef {
	/// Name of the file on disk. This should be unique for the file.
	pub filename :String,
	/// Sha256 hash of the file's data in hexadecimal lowercase representation
	pub hash :String,
	/// The url the test file can be obtained from
	pub url :String,
}

/// A type for a Sha256 hash value
///
/// Provides conversion functionality to hex representation and back
#[derive(PartialEq, Eq, Hash, Clone)]
pub struct Sha256Hash([u8; 32]);

impl Sha256Hash {

	pub fn from_digest(sha :&mut Sha256) -> Self {
		let mut res = Sha256Hash([0; 32]);
		sha.result(&mut res.0);
		return res;
	}

	/// Converts the hexadecimal string to a hash value
	pub fn from_hex(s :&str) -> Result<Self, ()> {
		let mut res = Sha256Hash([0; 32]);
		let mut idx = 0;
		let mut iter = s.chars();
		loop {
			let upper = match iter.next().and_then(|c| c.to_digit(16)) {
				Some(v) => v as u8,
				None => try!(Err(())),
			};
			let lower = match iter.next().and_then(|c| c.to_digit(16)) {
				Some(v) => v as u8,
				None => try!(Err(())),
			};
			res.0[idx] = (upper << 4) | lower;
			idx += 1;
			if idx == 32 {
				break;
			}
		}
		return Ok(res);
	}
	/// Converts the hash value to hexadecimal
	pub fn to_hex(&self) -> String {
		let mut res = String::with_capacity(64);
		for v in self.0.iter() {
			use std::char::from_digit;
			res.push(from_digit(*v as u32 >> 4, 16).unwrap());
			res.push(from_digit(*v as u32 & 15, 16).unwrap());
		}
		return res;
	}
}

#[derive(Debug)]
pub enum TaError {
	Io(io::Error),
	Curl(curl::Error),
	DownloadFailed(u32),
	BadHashFormat,
}

impl From<io::Error> for TaError {
	fn from(err :io::Error) -> TaError {
		TaError::Io(err)
	}
}

impl From<curl::Error> for TaError {
	fn from(err :curl::Error) -> TaError {
		TaError::Curl(err)
	}
}

enum DownloadOutcome {
	WithHash(Sha256Hash),
	DownloadFailed(u32),
}

fn download_test_file(client :&mut Easy,
		tfile :&TestAssetDef, dir :&str) -> Result<DownloadOutcome, TaError> {
	use std::io::Write;
	use std::fs::File;
	try!(client.url(&tfile.url));
	let mut content = Vec::new();

	{
		let mut transfer = client.transfer();
		try!(transfer.write_function(|data| {
			content.extend_from_slice(data);
			Ok(data.len())
		}));
		try!(transfer.perform());
	}

	let mut hasher = Sha256::new();
	let mut file = try!(File::create(format!("{}/{}", dir, tfile.filename)));
	try!(file.write_all(&content));
	hasher.input(&content);

	let response_code = try!(client.response_code());
	if response_code < 200 || response_code > 399 {
		return Ok(DownloadOutcome::DownloadFailed(response_code));
	}
	return Ok(DownloadOutcome::WithHash(Sha256Hash::from_digest(&mut hasher)));
}

/// Downloads the test files into the passed directory.
pub fn download_test_files(defs :&[TestAssetDef],
		dir :&str, verbose :bool) -> Result<(), TaError> {
	let mut client = Easy::new();
	try!(client.follow_location(true));

	use std::io::ErrorKind;

	let hash_list_path = format!("{}/hash_list", dir);
	let mut hash_list = match HashList::from_file(&hash_list_path) {
		Ok(l) => l,
		Err(TaError::Io(ref e)) if e.kind() == ErrorKind::NotFound => HashList::new(),
		e => { try!(e); unreachable!() },
	};
	try!(create_dir_all(dir));
	for tfile in defs.iter() {
		let tfile_hash = try!(Sha256Hash::from_hex(&tfile.hash).map_err(|_| TaError::BadHashFormat));
		if hash_list.get_hash(&tfile.filename).map(|h| h == &tfile_hash)
				.unwrap_or(false) {
			// Hash match
			if verbose {
				println!("File {} has matching hash inside hash list, skipping download", tfile.filename);
			}
			continue;
		}
		if verbose {
			print!("Fetching file {} ...", tfile.filename);
		}
		let outcome = try!(download_test_file(&mut client, tfile, dir));
		use self::DownloadOutcome::*;
		match &outcome {
			&DownloadFailed(code) => return Err(TaError::DownloadFailed(code)),
			&WithHash(ref hash) => hash_list.add_entry(&tfile.filename, hash),
		}
		if verbose {
			print!("  => ");
			match &outcome {
				&DownloadFailed(code) => println!("Download failed with code {}", code),
				&WithHash(ref found_hash) => {
					if found_hash == &tfile_hash {
						println!("Success")
					} else {
						println!("Hash mismatch: found {}, expected {}",
							found_hash.to_hex(), tfile.hash)
					}
				 },
			}
		}
	}
	try!(hash_list.to_file(&hash_list_path));
	Ok(())
}