fuchsia_fatfs/
file.rs

1// Copyright 2020 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::directory::FatDirectory;
6use crate::filesystem::{FatFilesystem, FatFilesystemInner};
7use crate::node::Node;
8use crate::refs::{FatfsFileRef, Guard, GuardMut, Wrapper};
9use crate::types::File;
10use crate::util::{
11    dos_date_to_unix_time, dos_to_unix_time, fatfs_error_to_status, unix_to_dos_time,
12};
13use fidl_fuchsia_io as fio;
14use fuchsia_sync::RwLock;
15use std::cell::RefCell;
16use std::fmt::Debug;
17use std::io::{Read, Seek, Write};
18use std::pin::Pin;
19use std::sync::Arc;
20use vfs::attributes;
21use vfs::directory::entry::EntryInfo;
22use vfs::file::{File as VfsFile, FileIo as VfsFileIo, FileOptions, SyncMode};
23use zx::{self as zx, Status};
24
25fn extend(file: &mut File<'_>, mut current: u64, target: u64) -> Result<(), Status> {
26    let zeros = vec![0; 8192];
27    while current < target {
28        let to_do = (std::cmp::min(target, (current + 8192) / 8192 * 8192) - current) as usize;
29        let written = file.write(&zeros[..to_do]).map_err(fatfs_error_to_status)? as u64;
30        if written == 0 {
31            return Err(Status::NO_SPACE);
32        }
33        current += written;
34    }
35    Ok(())
36}
37
38fn seek_for_write(file: &mut File<'_>, offset: u64) -> Result<(), Status> {
39    if offset > fatfs::MAX_FILE_SIZE as u64 {
40        return Err(Status::INVALID_ARGS);
41    }
42    let real_offset = file.seek(std::io::SeekFrom::Start(offset)).map_err(fatfs_error_to_status)?;
43    if real_offset == offset {
44        return Ok(());
45    }
46    assert!(real_offset < offset);
47    let result = extend(file, real_offset, offset);
48    if let Err(e) = result {
49        // Return the file to its original size.
50        file.seek(std::io::SeekFrom::Start(real_offset)).map_err(fatfs_error_to_status)?;
51        file.truncate().map_err(fatfs_error_to_status)?;
52        return Err(e);
53    }
54    Ok(())
55}
56
57struct FatFileData {
58    name: String,
59    parent: Option<Arc<FatDirectory>>,
60}
61
62/// Represents a single file on the disk.
63pub struct FatFile {
64    file: RefCell<FatfsFileRef>,
65    filesystem: Pin<Arc<FatFilesystem>>,
66    data: RwLock<FatFileData>,
67}
68
69// The only member that isn't `Sync + Send` is the `file` member.
70// `file` is protected by the lock on `filesystem`, so we can safely
71// implement Sync + Send for FatFile.
72unsafe impl Sync for FatFile {}
73unsafe impl Send for FatFile {}
74
75impl FatFile {
76    /// Create a new FatFile.
77    pub(crate) fn new(
78        file: FatfsFileRef,
79        parent: Arc<FatDirectory>,
80        filesystem: Pin<Arc<FatFilesystem>>,
81        name: String,
82    ) -> Arc<Self> {
83        Arc::new(FatFile {
84            file: RefCell::new(file),
85            filesystem,
86            data: RwLock::new(FatFileData { parent: Some(parent), name }),
87        })
88    }
89
90    /// Borrow the underlying Fatfs File mutably.
91    pub(crate) fn borrow_file_mut<'a>(
92        &'a self,
93        fs: &'a FatFilesystemInner,
94    ) -> Option<GuardMut<'a, FatfsFileRef>> {
95        let mut file = self.file.borrow_mut();
96        if file.get_mut(fs).is_none() { None } else { Some(GuardMut::new(fs, file)) }
97    }
98
99    pub fn borrow_file<'a>(
100        &'a self,
101        fs: &'a FatFilesystemInner,
102    ) -> Result<Guard<'a, FatfsFileRef>, Status> {
103        let file = self.file.borrow();
104        if file.get(fs).is_none() { Err(Status::BAD_HANDLE) } else { Ok(Guard::new(fs, file)) }
105    }
106
107    async fn write_or_append(
108        &self,
109        offset: Option<u64>,
110        content: &[u8],
111    ) -> Result<(u64, u64), Status> {
112        let fs_lock = self.filesystem.lock();
113        let mut file = self.borrow_file_mut(&fs_lock).ok_or(Status::BAD_HANDLE)?;
114        let mut file_offset = match offset {
115            Some(offset) => {
116                seek_for_write(&mut *file, offset)?;
117                offset
118            }
119            None => file.seek(std::io::SeekFrom::End(0)).map_err(fatfs_error_to_status)?,
120        };
121        let mut total_written = 0;
122        while total_written < content.len() {
123            let written = file.write(&content[total_written..]).map_err(fatfs_error_to_status)?;
124            if written == 0 {
125                break;
126            }
127            total_written += written;
128            file_offset += written as u64;
129            let result = file.write(&content[total_written..]).map_err(fatfs_error_to_status);
130            match result {
131                Ok(0) => break,
132                Ok(written) => {
133                    total_written += written;
134                    file_offset += written as u64;
135                }
136                Err(e) => {
137                    if total_written > 0 {
138                        break;
139                    }
140                    return Err(e);
141                }
142            }
143        }
144        self.filesystem.mark_dirty();
145        Ok((total_written as u64, file_offset))
146    }
147}
148
149impl Node for FatFile {
150    /// Flush to disk and invalidate the reference that's contained within this FatFile.
151    /// Any operations on the file will return Status::BAD_HANDLE until it is re-attached.
152    fn detach(&self, fs: &FatFilesystemInner) {
153        self.file.borrow_mut().take(fs);
154    }
155
156    /// Attach to the given parent and re-open the underlying `FatfsFileRef` this file represents.
157    fn attach(
158        &self,
159        new_parent: Arc<FatDirectory>,
160        name: &str,
161        fs: &FatFilesystemInner,
162    ) -> Result<(), Status> {
163        let mut data = self.data.write();
164        data.name = name.to_owned();
165        // Safe because we hold the fs lock.
166        let mut file = self.file.borrow_mut();
167        // Safe because we have a reference to the FatFilesystem.
168        unsafe { file.maybe_reopen(fs, &new_parent, name)? };
169        data.parent.replace(new_parent);
170        Ok(())
171    }
172
173    fn did_delete(&self) {
174        self.data.write().parent.take();
175    }
176
177    fn open_ref(&self, fs_lock: &FatFilesystemInner) -> Result<(), Status> {
178        let data = self.data.read();
179        let mut file_ref = self.file.borrow_mut();
180        unsafe { file_ref.open(&fs_lock, data.parent.as_deref(), &data.name) }
181    }
182
183    /// Close the underlying FatfsFileRef, regardless of the number of open connections.
184    fn shut_down(&self, fs: &FatFilesystemInner) -> Result<(), Status> {
185        self.file.borrow_mut().take(fs);
186        Ok(())
187    }
188
189    fn flush_dir_entry(&self, fs: &FatFilesystemInner) -> Result<(), Status> {
190        if let Some(mut file) = self.borrow_file_mut(fs) {
191            file.flush_dir_entry().map_err(fatfs_error_to_status)?
192        }
193        Ok(())
194    }
195
196    fn close_ref(&self, fs: &FatFilesystemInner) {
197        self.file.borrow_mut().close(fs);
198    }
199}
200
201impl vfs::node::Node for FatFile {
202    async fn get_attributes(
203        &self,
204        requested_attributes: fio::NodeAttributesQuery,
205    ) -> Result<fio::NodeAttributes2, Status> {
206        let fs_lock = self.filesystem.lock();
207        let file = self.borrow_file(&fs_lock)?;
208        let content_size = file.len() as u64;
209        let creation_time = dos_to_unix_time(file.created());
210        let modification_time = dos_to_unix_time(file.modified());
211        let access_time = dos_date_to_unix_time(file.accessed());
212
213        // Figure out the storage size by rounding content_size up to the nearest
214        // multiple of cluster_size.
215        let cluster_size = fs_lock.cluster_size() as u64;
216        let storage_size = ((content_size + cluster_size - 1) / cluster_size) * cluster_size;
217
218        Ok(attributes!(
219            requested_attributes,
220            Mutable {
221                creation_time: creation_time,
222                modification_time: modification_time,
223                access_time: access_time
224            },
225            Immutable {
226                protocols: fio::NodeProtocolKinds::FILE,
227                abilities: fio::Operations::GET_ATTRIBUTES
228                    | fio::Operations::UPDATE_ATTRIBUTES
229                    | fio::Operations::READ_BYTES
230                    | fio::Operations::WRITE_BYTES,
231                content_size: content_size,
232                storage_size: storage_size,
233                link_count: 1, // FAT does not support hard links, so there is always 1 "link".
234            }
235        ))
236    }
237
238    fn close(self: Arc<Self>) {
239        self.close_ref(&self.filesystem.lock());
240    }
241
242    fn query_filesystem(&self) -> Result<fio::FilesystemInfo, Status> {
243        self.filesystem.query_filesystem()
244    }
245
246    fn will_clone(&self) {
247        self.open_ref(&self.filesystem.lock()).unwrap();
248    }
249}
250
251impl Debug for FatFile {
252    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
253        f.debug_struct("FatFile").field("name", &self.data.read().name).finish()
254    }
255}
256
257impl VfsFile for FatFile {
258    fn writable(&self) -> bool {
259        return true;
260    }
261
262    async fn open_file(&self, _options: &FileOptions) -> Result<(), Status> {
263        Ok(())
264    }
265
266    async fn truncate(&self, length: u64) -> Result<(), Status> {
267        let fs_lock = self.filesystem.lock();
268        let mut file = self.borrow_file_mut(&fs_lock).ok_or(Status::BAD_HANDLE)?;
269        seek_for_write(&mut *file, length)?;
270        file.truncate().map_err(fatfs_error_to_status)?;
271        self.filesystem.mark_dirty();
272        Ok(())
273    }
274
275    // Unfortunately, fatfs has deprecated the "set_created" and "set_modified" methods,
276    // saying that a TimeProvider should be used instead. There doesn't seem to be a good way to
277    // use a TimeProvider to change the creation/modification time of a file after the fact,
278    // so we need to use the deprecated methods.
279    #[allow(deprecated)]
280    async fn update_attributes(
281        &self,
282        attributes: fio::MutableNodeAttributes,
283    ) -> Result<(), Status> {
284        const SUPPORTED_MUTABLE_ATTRIBUTES: fio::NodeAttributesQuery =
285            fio::NodeAttributesQuery::CREATION_TIME
286                .union(fio::NodeAttributesQuery::MODIFICATION_TIME);
287
288        if !SUPPORTED_MUTABLE_ATTRIBUTES
289            .contains(vfs::common::mutable_node_attributes_to_query(&attributes))
290        {
291            return Err(Status::NOT_SUPPORTED);
292        }
293
294        let fs_lock = self.filesystem.lock();
295        let mut file = self.borrow_file_mut(&fs_lock).ok_or(Status::BAD_HANDLE)?;
296        let mut needs_flush = false;
297        if let Some(creation_time) = attributes.creation_time {
298            file.set_created(unix_to_dos_time(creation_time));
299            needs_flush = true;
300        }
301        if let Some(modification_time) = attributes.modification_time {
302            file.set_modified(unix_to_dos_time(modification_time));
303            needs_flush = true;
304        }
305
306        if needs_flush {
307            file.flush().map_err(fatfs_error_to_status)?;
308            self.filesystem.mark_dirty();
309        }
310        Ok(())
311    }
312
313    async fn get_size(&self) -> Result<u64, Status> {
314        let fs_lock = self.filesystem.lock();
315        let file = self.borrow_file(&fs_lock)?;
316        Ok(file.len() as u64)
317    }
318
319    async fn sync(&self, _mode: SyncMode) -> Result<(), Status> {
320        let fs_lock = self.filesystem.lock();
321        let mut file = self.borrow_file_mut(&fs_lock).ok_or(Status::BAD_HANDLE)?;
322
323        file.flush().map_err(fatfs_error_to_status)?;
324        Ok(())
325    }
326}
327
328impl VfsFileIo for FatFile {
329    async fn read_at(&self, offset: u64, buffer: &mut [u8]) -> Result<u64, Status> {
330        let fs_lock = self.filesystem.lock();
331        let mut file = self.borrow_file_mut(&fs_lock).ok_or(Status::BAD_HANDLE)?;
332
333        let real_offset =
334            file.seek(std::io::SeekFrom::Start(offset)).map_err(fatfs_error_to_status)?;
335        // Technically, we don't need to do this because the read should return zero bytes later,
336        // but it's better to be explicit.
337        if real_offset != offset {
338            return Ok(0);
339        }
340        let mut total_read = 0;
341        while total_read < buffer.len() {
342            let read = file.read(&mut buffer[total_read..]).map_err(fatfs_error_to_status)?;
343            if read == 0 {
344                break;
345            }
346            total_read += read;
347        }
348        Ok(total_read as u64)
349    }
350
351    async fn write_at(&self, offset: u64, content: &[u8]) -> Result<u64, Status> {
352        self.write_or_append(Some(offset), content).await.map(|r| r.0)
353    }
354
355    async fn append(&self, content: &[u8]) -> Result<(u64, u64), Status> {
356        self.write_or_append(None, content).await
357    }
358}
359
360impl vfs::directory::entry::GetEntryInfo for FatFile {
361    fn entry_info(&self) -> EntryInfo {
362        EntryInfo::new(fio::INO_UNKNOWN, fio::DirentType::File)
363    }
364}
365
366#[cfg(test)]
367mod tests {
368    // We only test things here that aren't covered by fs_tests.
369    use super::*;
370    use crate::node::{Closer, FatNode};
371    use crate::tests::{TestDiskContents, TestFatDisk};
372
373    const TEST_DISK_SIZE: u64 = 2048 << 10; // 2048K
374    const TEST_FILE_CONTENT: &str = "test file contents";
375
376    struct TestFile(Arc<FatFile>);
377
378    impl TestFile {
379        fn new() -> Self {
380            let disk = TestFatDisk::empty_disk(TEST_DISK_SIZE);
381            let structure =
382                TestDiskContents::dir().add_child("test_file", TEST_FILE_CONTENT.into());
383            structure.create(&disk.root_dir());
384
385            let fs = disk.into_fatfs();
386            let dir = fs.get_fatfs_root();
387            let mut closer = Closer::new(&fs.filesystem());
388            dir.open_ref(&fs.filesystem().lock()).expect("open_ref failed");
389            closer.add(FatNode::Dir(dir.clone()));
390            let file = match dir
391                .open_child("test_file", fio::OpenFlags::empty(), &mut closer)
392                .expect("Open to succeed")
393            {
394                FatNode::File(f) => f,
395                val => panic!("Unexpected value {:?}", val),
396            };
397            file.open_ref(&fs.filesystem().lock()).expect("open_ref failed");
398            TestFile(file)
399        }
400    }
401
402    impl Drop for TestFile {
403        fn drop(&mut self) {
404            self.0.close_ref(&self.0.filesystem.lock());
405        }
406    }
407
408    impl std::ops::Deref for TestFile {
409        type Target = Arc<FatFile>;
410
411        fn deref(&self) -> &Self::Target {
412            &self.0
413        }
414    }
415
416    #[fuchsia::test]
417    async fn test_read_at() {
418        let file = TestFile::new();
419        // Note: fatfs incorrectly casts u64 to i64, which causes this value to wrap
420        // around and become negative, which causes seek() in read_at() to fail.
421        // The error is not particularly important, because fat has a maximum 32-bit file size.
422        // An error like this will only happen if an application deliberately seeks to a (very)
423        // out-of-range position or reads at a nonsensical offset.
424        let mut buffer = [0u8; 512];
425        let err = file.read_at(u64::MAX - 30, &mut buffer).await.expect_err("Read fails");
426        assert_eq!(err, Status::INVALID_ARGS);
427    }
428
429    #[fuchsia::test]
430    async fn test_get_attributes() {
431        let file = TestFile::new();
432        let fio::NodeAttributes2 { mutable_attributes, immutable_attributes } =
433            vfs::node::Node::get_attributes(&**file, fio::NodeAttributesQuery::all())
434                .await
435                .unwrap();
436        assert_eq!(immutable_attributes.content_size.unwrap(), TEST_FILE_CONTENT.len() as u64);
437        assert!(immutable_attributes.storage_size.unwrap() > TEST_FILE_CONTENT.len() as u64);
438        assert_eq!(immutable_attributes.protocols.unwrap(), fio::NodeProtocolKinds::FILE);
439        assert_eq!(
440            immutable_attributes.abilities.unwrap(),
441            fio::Abilities::GET_ATTRIBUTES
442                | fio::Abilities::UPDATE_ATTRIBUTES
443                | fio::Abilities::READ_BYTES
444                | fio::Abilities::WRITE_BYTES
445        );
446        assert!(mutable_attributes.creation_time.is_some());
447        assert!(mutable_attributes.modification_time.is_some());
448    }
449
450    #[fuchsia::test]
451    async fn test_update_attributes() {
452        let file = TestFile::new();
453
454        let new_time = std::time::SystemTime::now()
455            .duration_since(std::time::SystemTime::UNIX_EPOCH)
456            .expect("SystemTime before UNIX EPOCH")
457            .as_nanos();
458        let new_attrs = fio::MutableNodeAttributes {
459            creation_time: Some(new_time.try_into().unwrap()),
460            ..Default::default()
461        };
462        file.update_attributes(new_attrs).await.expect("update attributes failed");
463    }
464}