ic_host_artifacts/artifact/
mod.rs1use sha2::{Digest, Sha256};
9use std::{
10 fmt,
11 io::{self, Read},
12 str::FromStr,
13};
14
15mod chunks;
16mod copy;
17#[cfg(feature = "gzip")]
18mod gzip;
19mod hashing;
20mod matching;
21#[cfg(test)]
22mod tests;
23mod writer;
24
25pub use chunks::{ChunkDigestError, chunk_digests};
26pub use copy::{CopyError, copy_reader};
27#[cfg(feature = "gzip")]
28pub use gzip::{GzipError, decode_gzip, encode_gzip, gzip_matches, hash_gzip, hash_gzip_or_raw};
29pub use hashing::HashingWriter;
30pub use matching::MatchingWriter;
31pub use writer::{BoundedWriter, WriterError};
32
33#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
35pub struct Sha256Digest([u8; 32]);
36
37impl Sha256Digest {
38 #[must_use]
40 pub const fn from_bytes(bytes: [u8; 32]) -> Self {
41 Self(bytes)
42 }
43
44 #[must_use]
46 pub const fn as_bytes(&self) -> &[u8; 32] {
47 &self.0
48 }
49
50 #[must_use]
52 pub fn compute(bytes: &[u8]) -> Self {
53 Self(Sha256::digest(bytes).into())
54 }
55}
56
57impl fmt::Display for Sha256Digest {
58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 for byte in self.0 {
60 write!(f, "{byte:02x}")?;
61 }
62 Ok(())
63 }
64}
65
66#[derive(Clone, Copy, Debug, Eq, PartialEq)]
68pub enum DigestParseError {
69 Length {
71 actual: usize,
73 },
74 Digit {
76 offset: usize,
78 },
79}
80
81impl fmt::Display for DigestParseError {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 match self {
84 Self::Length { actual } => {
85 write!(f, "SHA-256 requires 64 hex bytes, received {actual}")
86 }
87 Self::Digit { offset } => write!(f, "invalid lowercase SHA-256 digit at byte {offset}"),
88 }
89 }
90}
91impl std::error::Error for DigestParseError {}
92
93impl FromStr for Sha256Digest {
94 type Err = DigestParseError;
95
96 fn from_str(text: &str) -> Result<Self, Self::Err> {
97 if text.len() != 64 {
98 return Err(DigestParseError::Length { actual: text.len() });
99 }
100 let mut bytes = [0; 32];
101 for (offset, digit) in text.bytes().enumerate() {
102 let nibble = match digit {
103 b'0'..=b'9' => digit - b'0',
104 b'a'..=b'f' => digit - b'a' + 10,
105 _ => return Err(DigestParseError::Digit { offset }),
106 };
107 bytes[offset / 2] |= nibble << if offset % 2 == 0 { 4 } else { 0 };
108 }
109 Ok(Self(bytes))
110 }
111}
112
113#[derive(Clone, Copy, Debug, Eq, PartialEq)]
115pub struct ArtifactIdentity {
116 pub bytes: u64,
118 pub sha256: Sha256Digest,
120}
121
122#[derive(Debug)]
124pub enum ArtifactError {
125 Io(io::Error),
127 NotRegularFile,
129 LimitExceeded {
131 limit: u64,
133 },
134 DigestMismatch {
136 expected: Sha256Digest,
138 actual: ArtifactIdentity,
140 },
141 Allocation(std::collections::TryReserveError),
143}
144
145impl fmt::Display for ArtifactError {
146 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147 match self {
148 Self::Io(source) => write!(f, "artifact read failed: {source}"),
149 Self::NotRegularFile => f.write_str("artifact path is not a regular file"),
150 Self::LimitExceeded { limit } => write!(f, "artifact exceeds {limit} bytes"),
151 Self::DigestMismatch { expected, actual } => write!(
152 f,
153 "artifact SHA-256 is {}, expected {expected}",
154 actual.sha256
155 ),
156 Self::Allocation(source) => write!(f, "artifact allocation failed: {source}"),
157 }
158 }
159}
160impl std::error::Error for ArtifactError {
161 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
162 match self {
163 Self::Io(source) => Some(source),
164 Self::Allocation(source) => Some(source),
165 _ => None,
166 }
167 }
168}
169impl From<io::Error> for ArtifactError {
170 fn from(source: io::Error) -> Self {
171 Self::Io(source)
172 }
173}
174
175impl From<ArtifactError> for io::Error {
177 fn from(error: ArtifactError) -> Self {
178 match error {
179 ArtifactError::Io(source) => source,
180 other => Self::other(other),
181 }
182 }
183}
184
185pub fn hash_reader(
195 mut reader: impl Read,
196 max_bytes: u64,
197) -> Result<ArtifactIdentity, ArtifactError> {
198 let mut hasher = Sha256::new();
199 let bytes = visit_reader::<ArtifactError>(&mut reader, max_bytes, |chunk| {
200 hasher.update(chunk);
201 Ok(())
202 })?;
203 Ok(ArtifactIdentity {
204 bytes,
205 sha256: Sha256Digest(hasher.finalize().into()),
206 })
207}
208
209pub fn verify_reader(
214 reader: impl Read,
215 max_bytes: u64,
216 expected: Sha256Digest,
217) -> Result<ArtifactIdentity, ArtifactError> {
218 let actual = hash_reader(reader, max_bytes)?;
219 if actual.sha256 != expected {
220 return Err(ArtifactError::DigestMismatch { expected, actual });
221 }
222 Ok(actual)
223}
224
225pub fn read_reader(mut reader: impl Read, max_bytes: usize) -> Result<Vec<u8>, ArtifactError> {
234 let mut bytes = Vec::new();
235 visit_reader::<ArtifactError>(&mut reader, max_bytes as u64, |chunk| {
236 reserve_bounded(&mut bytes, chunk.len(), max_bytes).map_err(ArtifactError::Allocation)?;
237 bytes.extend_from_slice(chunk);
238 Ok(())
239 })?;
240 Ok(bytes)
241}
242
243fn reserve_bounded<T>(
246 items: &mut Vec<T>,
247 additional: usize,
248 limit: usize,
249) -> Result<(), std::collections::TryReserveError> {
250 let required = items.len() + additional;
251 if required > items.capacity() {
252 let capacity = items.capacity().saturating_mul(2).max(required).min(limit);
253 items.try_reserve_exact(capacity - items.len())?;
254 }
255 Ok(())
256}
257
258fn visit_reader<E: From<ArtifactError>>(
259 reader: &mut impl Read,
260 limit: u64,
261 mut visit: impl FnMut(&[u8]) -> Result<(), E>,
262) -> Result<u64, E> {
263 let mut bytes = 0_u64;
264 let mut buffer = [0_u8; 16 * 1024];
265 loop {
266 let remaining = usize::try_from(limit - bytes).unwrap_or(usize::MAX);
267 let allowance = remaining.saturating_add(1).min(buffer.len());
268 let count = match reader.read(&mut buffer[..allowance]) {
269 Ok(count) => count,
270 Err(source) if source.kind() == io::ErrorKind::Interrupted => continue,
271 Err(source) => return Err(ArtifactError::Io(source).into()),
272 };
273 if count > allowance {
274 return Err(ArtifactError::Io(io::Error::new(
275 io::ErrorKind::InvalidData,
276 "reader returned more bytes than its buffer can hold",
277 ))
278 .into());
279 }
280 if count == 0 {
281 return Ok(bytes);
282 }
283 if count as u64 > limit - bytes {
284 return Err(ArtifactError::LimitExceeded { limit }.into());
285 }
286 visit(&buffer[..count])?;
287 bytes += count as u64;
288 }
289}