1use device::hash::{self, HashAlgorithm, SET_ALGORITHM};
2use file_system::{
3 BaseOperations, CharacterDevice, Context, ControlCommand, ControlCommandIdentifier,
4 IoErrorKind, MountOperations, Result, Size,
5};
6use sha2::{Digest, Sha224, Sha256, Sha384, Sha512, Sha512_224, Sha512_256, digest::DynDigest};
7use shared::AnyByLayout;
8
9#[derive(Clone)]
10struct HashDeviceContext {
11 hasher: Box<dyn DynDigest>,
12}
13
14unsafe impl Send for HashDeviceContext {}
15unsafe impl Sync for HashDeviceContext {}
16
17impl HashDeviceContext {
18 fn new(algorithm: HashAlgorithm) -> Result<Self> {
19 let hasher: Box<dyn DynDigest> = match algorithm {
20 HashAlgorithm::Sha224 => Box::new(Sha224::new()),
21 HashAlgorithm::Sha256 => Box::new(Sha256::new()),
22 HashAlgorithm::Sha384 => Box::new(Sha384::new()),
23 HashAlgorithm::Sha512 => Box::new(Sha512::new()),
24 HashAlgorithm::Sha512_224 => Box::new(Sha512_224::new()),
25 HashAlgorithm::Sha512_256 => Box::new(Sha512_256::new()),
26 _ => return Err(IoErrorKind::InvalidArgument),
27 };
28
29 Ok(Self { hasher })
30 }
31}
32
33pub struct HashDevice;
34
35impl BaseOperations for HashDevice {
36 fn open(&self, context: &mut Context) -> Result<()> {
37 context.set_private_data(Box::new(HashDeviceContext::new(HashAlgorithm::Sha256)?));
38 Ok(())
39 }
40
41 fn close(&self, context: &mut Context) -> Result<()> {
42 context.take_private_data_of_type::<HashDeviceContext>();
43 Ok(())
44 }
45
46 fn read(
47 &self,
48 context: &mut Context,
49 _cx: &mut core::task::Context<'_>,
50 buffer: &mut [u8],
51 _: Size,
52 ) -> core::task::Poll<Result<usize>> {
53 file_system::ready(|| {
54 let hash_context = context
55 .get_private_data_mutable_of_type::<HashDeviceContext>()
56 .ok_or(file_system::IoErrorKind::InvalidArgument)?;
57
58 if buffer.len() < hash_context.hasher.output_size() {
59 return Err(IoErrorKind::InvalidArgument);
60 }
61
62 let result = hash_context.hasher.clone().finalize();
63 let length = result.len();
64 buffer[..length].copy_from_slice(&result);
65 Ok(length)
66 })
67 }
68
69 fn write(
70 &self,
71 context: &mut Context,
72 _cx: &mut core::task::Context<'_>,
73 buffer: &[u8],
74 _: Size,
75 ) -> core::task::Poll<Result<usize>> {
76 file_system::ready(|| {
77 let hash_context = context
78 .get_private_data_mutable_of_type::<HashDeviceContext>()
79 .ok_or(file_system::IoErrorKind::InvalidArgument)?;
80
81 hash_context.hasher.update(buffer);
82 Ok(buffer.len())
83 })
84 }
85
86 fn control(
87 &self,
88 context: &mut Context,
89 _cx: &mut core::task::Context<'_>,
90 command: ControlCommandIdentifier,
91 input: &AnyByLayout,
92 _: &mut AnyByLayout,
93 ) -> core::task::Poll<Result<()>> {
94 file_system::ready(|| {
95 let hash_context = context
96 .get_private_data_mutable_of_type::<HashDeviceContext>()
97 .ok_or(file_system::IoErrorKind::InvalidArgument)?;
98
99 match command {
100 hash::RESET::IDENTIFIER => {
101 hash_context.hasher.reset();
102 Ok(())
103 }
104 hash::SET_ALGORITHM::IDENTIFIER => {
105 let algorithm = HashAlgorithm::try_from(*SET_ALGORITHM::cast_input(input)?)?;
106
107 *hash_context = HashDeviceContext::new(algorithm)?;
108 Ok(())
109 }
110 _ => Err(file_system::IoErrorKind::Unsupported),
111 }
112 })
113 }
114
115 fn clone_context(&self, context: &Context) -> Result<Context> {
116 let hash_context = context
117 .get_private_data_of_type::<HashDeviceContext>()
118 .ok_or(file_system::IoErrorKind::InvalidArgument)?;
119
120 Ok(Context::new(Some(hash_context.clone())))
121 }
122}
123
124impl MountOperations for HashDevice {}
125
126impl CharacterDevice for HashDevice {}
127
128#[cfg(test)]
129mod tests {
130 use super::*;
131 use core::task::{Poll, Waker};
132 use file_system::{BaseOperations, ControlCommand};
133 use shared::AnyByLayout;
134
135 #[test]
136 fn set_algorithm_rejects_an_invalid_payload_byte() {
137 let device = HashDevice;
138 let mut context = Context::new_empty();
139 device.open(&mut context).unwrap();
140 let mut cx = core::task::Context::from_waker(Waker::noop());
141
142 let invalid = 200u8;
143 assert_eq!(
144 device.control(
145 &mut context,
146 &mut cx,
147 SET_ALGORITHM::IDENTIFIER,
148 AnyByLayout::from(&invalid),
149 AnyByLayout::NONE,
150 ),
151 Poll::Ready(Err(IoErrorKind::InvalidArgument))
152 );
153
154 let valid = HashAlgorithm::Sha384 as u8;
155 assert_eq!(
156 device.control(
157 &mut context,
158 &mut cx,
159 SET_ALGORITHM::IDENTIFIER,
160 AnyByLayout::from(&valid),
161 AnyByLayout::NONE,
162 ),
163 Poll::Ready(Ok(()))
164 );
165 }
166}