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
|
use std::error::Error;
use std::ffi::OsStr;
use std::fmt::{Display, Formatter};
use std::io::ErrorKind;
use std::path::{Component, Path, PathBuf, Prefix};
use log::debug;
use sha1_smol::{Digest, Sha1};
use tokio::fs::File;
use tokio::io::AsyncReadExt;
use crate::util;
#[derive(Debug)]
pub enum IntegrityError {
SizeMismatch{ expect: usize, actual: usize },
Sha1Mismatch{ expect: Digest, actual: Digest }
}
impl Display for IntegrityError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
IntegrityError::SizeMismatch{ expect, actual } =>
write!(f, "size mismatch (expect {expect} bytes, got {actual} bytes)"),
IntegrityError::Sha1Mismatch {expect, actual} =>
write!(f, "sha1 mismatch (expect {expect}, got {actual})")
}
}
}
impl Error for IntegrityError {}
pub fn verify_sha1(expect: Digest, s: &str) -> Result<(), Digest> {
let dig = Sha1::from(s).digest();
if dig == expect {
return Ok(());
}
Err(dig)
}
#[derive(Debug)]
pub enum FileVerifyError {
Integrity(PathBuf, IntegrityError),
Open(PathBuf, tokio::io::Error),
Read(PathBuf, tokio::io::Error),
}
impl Display for FileVerifyError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
FileVerifyError::Integrity(path, e) => write!(f, "file integrity error {}: {}", path.display(), e),
FileVerifyError::Open(path, e) => write!(f, "error opening file {}: {}", path.display(), e),
FileVerifyError::Read(path, e) => write!(f, "error reading file {}: {}", path.display(), e)
}
}
}
impl Error for FileVerifyError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
FileVerifyError::Integrity(_, e) => Some(e),
FileVerifyError::Open(_, e) => Some(e),
FileVerifyError::Read(_, e) => Some(e)
}
}
}
pub async fn verify_file(path: impl AsRef<Path>, expect_size: Option<usize>, expect_sha1: Option<Digest>) -> Result<(), FileVerifyError> {
let path = path.as_ref();
if expect_size.is_none() && expect_sha1.is_none() {
debug!("No size or sha1 for {}, have to assume it's good.", path.display());
return Ok(());
}
let mut file = File::open(path).await.map_err(|e| FileVerifyError::Open(path.to_owned(), e))?;
let mut tally = 0usize;
let mut st = Sha1::new();
let mut buf = [0u8; 4096];
loop {
let n = match file.read(&mut buf).await {
Ok(n) => n,
Err(e) => match e.kind() {
ErrorKind::Interrupted => continue,
_ => return Err(FileVerifyError::Read(path.to_owned(), e))
}
};
if n == 0 {
break;
}
st.update(&buf[..n]);
tally += n;
}
let dig = st.digest();
if expect_size.is_some_and(|sz| sz != tally) {
return Err(FileVerifyError::Integrity(path.to_owned(), IntegrityError::SizeMismatch {
expect: expect_size.unwrap(),
actual: tally
}));
} else if expect_sha1.is_some_and(|exp_dig| exp_dig != dig) {
return Err(FileVerifyError::Integrity(path.to_owned(), IntegrityError::Sha1Mismatch {
expect: expect_sha1.unwrap(),
actual: dig
}));
}
Ok(())
}
pub fn check_path(name: &str) -> Result<&Path, &'static str> {
let entry_path: &Path = Path::new(name);
let mut depth = 0usize;
for component in entry_path.components() {
depth = match component {
Component::Prefix(_) | Component::RootDir =>
return Err("root path component in entry"),
Component::ParentDir => depth.checked_sub(1)
.map_or_else(|| Err("entry path escapes"), |s| Ok(s))?,
Component::Normal(_) => depth + 1,
_ => depth
}
}
Ok(entry_path)
}
#[cfg(windows)]
pub fn strip_verbatim(path: &Path) -> &Path {
let Some(Component::Prefix(p)) = path.components().next() else {
return path;
};
match p.kind() {
Prefix::VerbatimDisk(_) =>
Path::new(unsafe { OsStr::from_encoded_bytes_unchecked(&path.as_os_str().as_encoded_bytes()[4..]) }),
_ => path
}
}
#[cfg(not(windows))]
pub fn strip_verbatim(path: &Path) -> &Path {
path
}
pub trait AsJavaPath {
fn as_java_path(&self) -> &Path;
}
impl AsJavaPath for Path {
fn as_java_path(&self) -> &Path {
strip_verbatim(self)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[cfg(windows)]
fn test_strip_verbatim() {
let path = Path::new(r"\\?\C:\Some\Verbatim\Path");
match path.components().next().unwrap() {
Component::Prefix(p) => assert!(matches!(p.kind(), Prefix::VerbatimDisk(_)), "(TEST BUG) path does not start with verbatim disk"),
_ => panic!("(TEST BUG) path does not start with prefix")
}
let path2 = path.as_java_path();
match path2.components().next().unwrap() {
Component::Prefix(p) => assert!(matches!(p.kind(), Prefix::Disk(_))),
_ => panic!("path does not begin with prefix")
}
}
}
|