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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
use aes::{Aes128, BlockDecrypt, BlockEncrypt};
use alloc::{collections::VecDeque, vec::Vec};
use core::mem;
use syscall::error::{Error, Result, EIO, EKEYREJECTED, ENOENT, ENOKEY, ENOSPC};

use crate::{
    AllocEntry, AllocList, Allocator, BlockAddr, BlockData, BlockLevel, BlockTrait, Disk, Header,
    Key, KeySlot, Node, Salt, Transaction, TreeList, BLOCK_SIZE, HEADER_RING,
};

/// A file system
pub struct FileSystem<D: Disk> {
    //TODO: make private
    pub disk: D,
    //TODO: make private
    pub block: u64,
    //TODO: make private
    pub header: Header,
    pub(crate) allocator: Allocator,
    pub(crate) aes_opt: Option<Aes128>,
    aes_blocks: Vec<aes::Block>,
}

impl<D: Disk> FileSystem<D> {
    /// Open a file system on a disk
    pub fn open(
        mut disk: D,
        password_opt: Option<&[u8]>,
        block_opt: Option<u64>,
        squash: bool,
    ) -> Result<Self> {
        for ring_block in block_opt.map_or(0..65536, |x| x..x + 1) {
            let mut header = Header::default();
            unsafe { disk.read_at(ring_block, &mut header)? };

            // Skip invalid headers
            if !header.valid() {
                continue;
            }

            let block = ring_block - (header.generation() % HEADER_RING);
            for i in 0..HEADER_RING {
                let mut other_header = Header::default();
                unsafe { disk.read_at(block + i, &mut other_header)? };

                // Skip invalid headers
                if !other_header.valid() {
                    continue;
                }

                // If this is a newer header, use it
                if other_header.generation() > header.generation() {
                    header = other_header;
                }
            }

            let aes_opt = match password_opt {
                Some(password) => {
                    if !header.encrypted() {
                        // Header not encrypted but password provided
                        return Err(Error::new(EKEYREJECTED));
                    }
                    match header.aes(password) {
                        Some(aes) => Some(aes),
                        None => {
                            // Header encrypted with a different password
                            return Err(Error::new(ENOKEY));
                        }
                    }
                }
                None => {
                    if header.encrypted() {
                        // Header encrypted but no password provided
                        return Err(Error::new(ENOKEY));
                    }
                    None
                }
            };

            let mut fs = FileSystem {
                disk,
                block,
                header,
                allocator: Allocator::default(),
                aes_opt,
                aes_blocks: Vec::with_capacity(BLOCK_SIZE as usize / aes::BLOCK_SIZE),
            };

            unsafe { fs.reset_allocator()? };

            // Squash allocations and sync
            Transaction::new(&mut fs).commit(squash)?;

            return Ok(fs);
        }

        Err(Error::new(ENOENT))
    }

    /// Create a file system on a disk
    #[cfg(feature = "std")]
    pub fn create(
        disk: D,
        password_opt: Option<&[u8]>,
        ctime: u64,
        ctime_nsec: u32,
    ) -> Result<Self> {
        Self::create_reserved(disk, password_opt, &[], ctime, ctime_nsec)
    }

    /// Create a file system on a disk, with reserved data at the beginning
    /// Reserved data will be zero padded up to the nearest block
    /// We need to pass ctime and ctime_nsec in order to initialize the unix timestamps
    #[cfg(feature = "std")]
    pub fn create_reserved(
        mut disk: D,
        password_opt: Option<&[u8]>,
        reserved: &[u8],
        ctime: u64,
        ctime_nsec: u32,
    ) -> Result<Self> {
        let size = disk.size()?;
        let block_offset = (reserved.len() as u64 + BLOCK_SIZE - 1) / BLOCK_SIZE;

        if size >= (block_offset + HEADER_RING + 4) * BLOCK_SIZE {
            for block in 0..block_offset as usize {
                let mut data = [0; BLOCK_SIZE as usize];

                let mut i = 0;
                while i < data.len() && block * BLOCK_SIZE as usize + i < reserved.len() {
                    data[i] = reserved[block * BLOCK_SIZE as usize + i];
                    i += 1;
                }

                unsafe {
                    disk.write_at(block as u64, &data)?;
                }
            }

            let mut header = Header::new(size);

            let aes_opt = match password_opt {
                Some(password) => {
                    //TODO: handle errors
                    header.key_slots[0] =
                        KeySlot::new(password, Salt::new().unwrap(), Key::new().unwrap()).unwrap();
                    Some(header.key_slots[0].key(password).unwrap().into_aes())
                }
                None => None,
            };

            let mut fs = FileSystem {
                disk,
                block: block_offset,
                header,
                allocator: Allocator::default(),
                aes_opt,
                aes_blocks: Vec::with_capacity(BLOCK_SIZE as usize / aes::BLOCK_SIZE),
            };

            // Write header generation zero
            let count = unsafe { fs.disk.write_at(fs.block, &fs.header)? };
            if count != mem::size_of_val(&fs.header) {
                // Wrote wrong number of bytes
                #[cfg(feature = "log")]
                log::error!("CREATE: WRONG NUMBER OF BYTES");
                return Err(Error::new(EIO));
            }

            // Set tree and alloc pointers and write header generation one
            fs.tx(|tx| unsafe {
                let tree = BlockData::new(
                    BlockAddr::new(HEADER_RING + 1, BlockLevel::default()),
                    TreeList::empty(BlockLevel::default()).unwrap(),
                );

                let mut alloc = BlockData::new(
                    BlockAddr::new(HEADER_RING + 2, BlockLevel::default()),
                    AllocList::empty(BlockLevel::default()).unwrap(),
                );
                let alloc_free = size / BLOCK_SIZE - (block_offset + HEADER_RING + 4);
                alloc.data_mut().entries[0] = AllocEntry::new(HEADER_RING + 4, alloc_free as i64);

                tx.header.tree = tx.write_block(tree)?;
                tx.header.alloc = tx.write_block(alloc)?;
                tx.header_changed = true;

                Ok(())
            })?;

            unsafe {
                fs.reset_allocator()?;
            }

            fs.tx(|tx| unsafe {
                let mut root = BlockData::new(
                    BlockAddr::new(HEADER_RING + 3, BlockLevel::default()),
                    Node::new(Node::MODE_DIR | 0o755, 0, 0, ctime, ctime_nsec),
                );
                root.data_mut().set_links(1);
                let root_ptr = tx.write_block(root)?;
                assert_eq!(tx.insert_tree(root_ptr)?.id(), 1);
                Ok(())
            })?;

            // Make sure everything is synced and squash allocations
            Transaction::new(&mut fs).commit(true)?;

            Ok(fs)
        } else {
            Err(Error::new(ENOSPC))
        }
    }

    /// start a filesystem transaction, required for making any changes
    pub fn tx<F: FnOnce(&mut Transaction<D>) -> Result<T>, T>(&mut self, f: F) -> Result<T> {
        let mut tx = Transaction::new(self);
        let t = f(&mut tx)?;
        tx.commit(false)?;
        Ok(t)
    }

    pub fn allocator(&self) -> &Allocator {
        &self.allocator
    }

    /// Reset allocator to state stored on disk
    ///
    /// # Safety
    /// Unsafe, it must only be called when openning the filesystem
    unsafe fn reset_allocator(&mut self) -> Result<()> {
        self.allocator = Allocator::default();

        // To avoid having to update all prior alloc blocks, there is only a previous pointer
        // This means we need to roll back all allocations. Currently we do this by reading the
        // alloc log into a buffer to reverse it.
        let mut allocs = VecDeque::new();
        self.tx(|tx| {
            let mut alloc_ptr = tx.header.alloc;
            while !alloc_ptr.is_null() {
                let alloc = tx.read_block(alloc_ptr)?;
                alloc_ptr = alloc.data().prev;
                allocs.push_front(alloc);
            }
            Ok(())
        })?;

        for alloc in allocs {
            for entry in alloc.data().entries.iter() {
                let index = entry.index();
                let count = entry.count();
                if count < 0 {
                    for i in 0..-count {
                        //TODO: replace assert with error?
                        let addr = BlockAddr::new(index + i as u64, BlockLevel::default());
                        assert_eq!(self.allocator.allocate_exact(addr), Some(addr));
                    }
                } else {
                    for i in 0..count {
                        let addr = BlockAddr::new(index + i as u64, BlockLevel::default());
                        self.allocator.deallocate(addr);
                    }
                }
            }
        }

        Ok(())
    }

    pub(crate) fn decrypt(&mut self, data: &mut [u8]) -> bool {
        if let Some(ref aes) = self.aes_opt {
            assert_eq!(data.len() % aes::BLOCK_SIZE, 0);

            self.aes_blocks.clear();
            for i in 0..data.len() / aes::BLOCK_SIZE {
                self.aes_blocks.push(aes::Block::clone_from_slice(
                    &data[i * aes::BLOCK_SIZE..(i + 1) * aes::BLOCK_SIZE],
                ));
            }

            aes.decrypt_blocks(&mut self.aes_blocks);

            for i in 0..data.len() / aes::BLOCK_SIZE {
                data[i * aes::BLOCK_SIZE..(i + 1) * aes::BLOCK_SIZE]
                    .copy_from_slice(&self.aes_blocks[i]);
            }
            self.aes_blocks.clear();

            true
        } else {
            false
        }
    }

    pub(crate) fn encrypt(&mut self, data: &mut [u8]) -> bool {
        if let Some(ref aes) = self.aes_opt {
            assert_eq!(data.len() % aes::BLOCK_SIZE, 0);

            self.aes_blocks.clear();
            for i in 0..data.len() / aes::BLOCK_SIZE {
                self.aes_blocks.push(aes::Block::clone_from_slice(
                    &data[i * aes::BLOCK_SIZE..(i + 1) * aes::BLOCK_SIZE],
                ));
            }

            aes.encrypt_blocks(&mut self.aes_blocks);

            for i in 0..data.len() / aes::BLOCK_SIZE {
                data[i * aes::BLOCK_SIZE..(i + 1) * aes::BLOCK_SIZE]
                    .copy_from_slice(&self.aes_blocks[i]);
            }
            self.aes_blocks.clear();

            true
        } else {
            false
        }
    }
}