1use crate::directory::FatDirectory;
6use crate::filesystem::FatFilesystem;
7use crate::node::Node;
8use crate::refs::FatfsFileRef;
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 fragile::Fragile;
15use std::cell::{Ref, RefCell, RefMut};
16use std::fmt::Debug;
17use std::io::{Read, Seek, Write};
18use std::ops::Deref;
19use std::rc::Rc;
20use std::sync::Arc;
21use vfs::attributes;
22use vfs::directory::entry::EntryInfo;
23use vfs::file::{File as VfsFile, FileIo as VfsFileIo, FileOptions, SyncMode};
24use zx::{self as zx, Status};
25
26fn extend(file: &mut File<'_>, mut current: u64, target: u64) -> Result<(), Status> {
27 let zeros = vec![0; 8192];
28 while current < target {
29 let to_do = (std::cmp::min(target, (current + 8192) / 8192 * 8192) - current) as usize;
30 let written = file.write(&zeros[..to_do]).map_err(fatfs_error_to_status)? as u64;
31 if written == 0 {
32 return Err(Status::NO_SPACE);
33 }
34 current += written;
35 }
36 Ok(())
37}
38
39fn seek_for_write(file: &mut File<'_>, offset: u64) -> Result<(), Status> {
40 if offset > fatfs::MAX_FILE_SIZE as u64 {
41 return Err(Status::INVALID_ARGS);
42 }
43 let real_offset = file.seek(std::io::SeekFrom::Start(offset)).map_err(fatfs_error_to_status)?;
44 if real_offset == offset {
45 return Ok(());
46 }
47 assert!(real_offset < offset);
48 let result = extend(file, real_offset, offset);
49 if let Err(e) = result {
50 file.seek(std::io::SeekFrom::Start(real_offset)).map_err(fatfs_error_to_status)?;
52 file.truncate().map_err(fatfs_error_to_status)?;
53 return Err(e);
54 }
55 Ok(())
56}
57
58struct FatFileData {
59 name: String,
60 parent: Option<Arc<FatDirectory>>,
61}
62
63pub struct FatFile(Fragile<FatFileInner>);
65
66pub struct FatFileInner {
67 file: FatfsFileRef,
68 data: RefCell<FatFileData>,
69}
70
71impl FatFileInner {
72 pub(crate) fn fs(&self) -> &Rc<FatFilesystem> {
73 self.file.filesystem()
74 }
75}
76
77impl Deref for FatFile {
78 type Target = FatFileInner;
79
80 fn deref(&self) -> &Self::Target {
81 self.0.get()
82 }
83}
84
85impl FatFile {
86 pub(crate) fn new(file: FatfsFileRef, parent: Arc<FatDirectory>, name: String) -> Arc<Self> {
88 Arc::new(FatFile(Fragile::new(FatFileInner {
89 file,
90 data: RefCell::new(FatFileData { parent: Some(parent), name }),
91 })))
92 }
93
94 pub(crate) fn borrow_file_mut<'a>(&'a self) -> Option<RefMut<'a, File<'a>>> {
95 self.file.get_mut()
96 }
97
98 pub fn borrow_file<'a>(&'a self) -> Result<Ref<'a, File<'a>>, Status> {
99 self.file.get().ok_or(Status::BAD_HANDLE)
100 }
101
102 fn write_or_append(&self, offset: Option<u64>, content: &[u8]) -> Result<(u64, u64), Status> {
103 let mut file = self.borrow_file_mut().ok_or(Status::BAD_HANDLE)?;
104 let mut file_offset = match offset {
105 Some(offset) => {
106 seek_for_write(&mut *file, offset)?;
107 offset
108 }
109 None => file.seek(std::io::SeekFrom::End(0)).map_err(fatfs_error_to_status)?,
110 };
111 let mut total_written = 0;
112 while total_written < content.len() {
113 let written = file.write(&content[total_written..]).map_err(fatfs_error_to_status)?;
114 if written == 0 {
115 break;
116 }
117 total_written += written;
118 file_offset += written as u64;
119 let result = file.write(&content[total_written..]).map_err(fatfs_error_to_status);
120 match result {
121 Ok(0) => break,
122 Ok(written) => {
123 total_written += written;
124 file_offset += written as u64;
125 }
126 Err(e) => {
127 if total_written > 0 {
128 break;
129 }
130 return Err(e);
131 }
132 }
133 }
134 self.fs().mark_dirty();
135 Ok((total_written as u64, file_offset))
136 }
137}
138
139impl Node for FatFile {
140 fn detach(&self) {
143 self.file.clear();
144 }
145
146 fn attach(&self, new_parent: Arc<FatDirectory>, name: &str) -> Result<(), Status> {
148 let mut data = self.data.borrow_mut();
149 data.name = name.to_owned();
150 self.file.maybe_reopen(&new_parent, name)?;
152 data.parent.replace(new_parent);
153 Ok(())
154 }
155
156 fn did_delete(&self) {
157 self.data.borrow_mut().parent.take();
158 }
159
160 fn open_ref(&self) -> Result<(), Status> {
161 let data = self.data.borrow();
162 self.file.open(data.parent.as_deref(), &data.name)
163 }
164
165 fn shut_down(&self) -> Result<(), Status> {
167 self.file.clear();
168 Ok(())
169 }
170
171 fn flush_dir_entry(&self) -> Result<(), Status> {
172 if let Some(mut file) = self.borrow_file_mut() {
173 file.flush_dir_entry().map_err(fatfs_error_to_status)?
174 }
175 Ok(())
176 }
177
178 fn close_ref(&self) {
179 self.file.close();
180 }
181}
182
183impl vfs::node::Node for FatFile {
184 async fn get_attributes(
185 &self,
186 requested_attributes: fio::NodeAttributesQuery,
187 ) -> Result<fio::NodeAttributes2, Status> {
188 let file = self.borrow_file()?;
189 let content_size = file.len() as u64;
190 let creation_time = dos_to_unix_time(file.created());
191 let modification_time = dos_to_unix_time(file.modified());
192 let access_time = dos_date_to_unix_time(file.accessed());
193
194 let cluster_size = self.fs().cluster_size() as u64;
197 let storage_size = ((content_size + cluster_size - 1) / cluster_size) * cluster_size;
198
199 Ok(attributes!(
200 requested_attributes,
201 Mutable {
202 creation_time: creation_time,
203 modification_time: modification_time,
204 access_time: access_time
205 },
206 Immutable {
207 protocols: fio::NodeProtocolKinds::FILE,
208 abilities: fio::Operations::GET_ATTRIBUTES
209 | fio::Operations::UPDATE_ATTRIBUTES
210 | fio::Operations::READ_BYTES
211 | fio::Operations::WRITE_BYTES,
212 content_size: content_size,
213 storage_size: storage_size,
214 link_count: 1, }
216 ))
217 }
218
219 fn close(self: Arc<Self>) {
220 self.close_ref();
221 }
222
223 fn query_filesystem(&self) -> Result<fio::FilesystemInfo, Status> {
224 self.fs().query_filesystem()
225 }
226
227 fn will_clone(&self) {
228 self.open_ref().unwrap();
229 }
230}
231
232impl Debug for FatFile {
233 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
234 f.debug_struct("FatFile").field("name", &self.data.borrow().name).finish_non_exhaustive()
235 }
236}
237
238impl VfsFile for FatFile {
239 fn writable(&self) -> bool {
240 return true;
241 }
242
243 async fn open_file(&self, _options: &FileOptions) -> Result<(), Status> {
244 Ok(())
245 }
246
247 async fn truncate(&self, length: u64) -> Result<(), Status> {
248 let mut file = self.borrow_file_mut().ok_or(Status::BAD_HANDLE)?;
249 seek_for_write(&mut *file, length)?;
250 file.truncate().map_err(fatfs_error_to_status)?;
251 self.fs().mark_dirty();
252 Ok(())
253 }
254
255 #[allow(deprecated)]
260 async fn update_attributes(
261 &self,
262 attributes: fio::MutableNodeAttributes,
263 ) -> Result<(), Status> {
264 const SUPPORTED_MUTABLE_ATTRIBUTES: fio::NodeAttributesQuery =
265 fio::NodeAttributesQuery::CREATION_TIME
266 .union(fio::NodeAttributesQuery::MODIFICATION_TIME);
267
268 if !SUPPORTED_MUTABLE_ATTRIBUTES
269 .contains(vfs::common::mutable_node_attributes_to_query(&attributes))
270 {
271 return Err(Status::NOT_SUPPORTED);
272 }
273
274 let mut file = self.borrow_file_mut().ok_or(Status::BAD_HANDLE)?;
275 let mut needs_flush = false;
276 if let Some(creation_time) = attributes.creation_time {
277 file.set_created(unix_to_dos_time(creation_time));
278 needs_flush = true;
279 }
280 if let Some(modification_time) = attributes.modification_time {
281 file.set_modified(unix_to_dos_time(modification_time));
282 needs_flush = true;
283 }
284
285 if needs_flush {
286 file.flush().map_err(fatfs_error_to_status)?;
287 self.fs().mark_dirty();
288 }
289 Ok(())
290 }
291
292 async fn get_size(&self) -> Result<u64, Status> {
293 let file = self.borrow_file()?;
294 Ok(file.len() as u64)
295 }
296
297 async fn sync(&self, _mode: SyncMode) -> Result<(), Status> {
298 let mut file = self.borrow_file_mut().ok_or(Status::BAD_HANDLE)?;
299
300 file.flush().map_err(fatfs_error_to_status)?;
301 Ok(())
302 }
303}
304
305impl VfsFileIo for FatFile {
306 async fn read_at(&self, offset: u64, buffer: &mut [u8]) -> Result<u64, Status> {
307 let mut file = self.borrow_file_mut().ok_or(Status::BAD_HANDLE)?;
308
309 let real_offset =
310 file.seek(std::io::SeekFrom::Start(offset)).map_err(fatfs_error_to_status)?;
311 if real_offset != offset {
314 return Ok(0);
315 }
316 let mut total_read = 0;
317 while total_read < buffer.len() {
318 let read = file.read(&mut buffer[total_read..]).map_err(fatfs_error_to_status)?;
319 if read == 0 {
320 break;
321 }
322 total_read += read;
323 }
324 Ok(total_read as u64)
325 }
326
327 async fn write_at(&self, offset: u64, content: &[u8]) -> Result<u64, Status> {
328 self.write_or_append(Some(offset), content).map(|r| r.0)
329 }
330
331 async fn append(&self, content: &[u8]) -> Result<(u64, u64), Status> {
332 self.write_or_append(None, content)
333 }
334}
335
336impl vfs::directory::entry::GetEntryInfo for FatFile {
337 fn entry_info(&self) -> EntryInfo {
338 EntryInfo::new(fio::INO_UNKNOWN, fio::DirentType::File)
339 }
340}
341
342#[cfg(test)]
343mod tests {
344 use super::*;
346 use crate::node::{Closer, FatNode};
347 use crate::tests::{TestDiskContents, TestFatDisk};
348
349 const TEST_DISK_SIZE: u64 = 2048 << 10; const TEST_FILE_CONTENT: &str = "test file contents";
351
352 struct TestFile(Arc<FatFile>);
353
354 impl TestFile {
355 fn new() -> Self {
356 let disk = TestFatDisk::empty_disk(TEST_DISK_SIZE);
357 let structure =
358 TestDiskContents::dir().add_child("test_file", TEST_FILE_CONTENT.into());
359 structure.create(&disk.root_dir());
360
361 let fs = disk.into_fatfs();
362 let dir = fs.get_fatfs_root();
363 let mut closer = Closer::new();
364 dir.open_ref().expect("open_ref failed");
365 closer.add(FatNode::Dir(dir.clone()));
366 let file = match dir
367 .open_child("test_file", fio::OpenFlags::empty(), &mut closer)
368 .expect("Open to succeed")
369 {
370 FatNode::File(f) => f,
371 val => panic!("Unexpected value {:?}", val),
372 };
373 file.open_ref().expect("open_ref failed");
374 TestFile(file)
375 }
376 }
377
378 impl Drop for TestFile {
379 fn drop(&mut self) {
380 self.0.close_ref();
381 }
382 }
383
384 impl std::ops::Deref for TestFile {
385 type Target = Arc<FatFile>;
386
387 fn deref(&self) -> &Self::Target {
388 &self.0
389 }
390 }
391
392 #[fuchsia::test]
393 async fn test_read_at() {
394 let file = TestFile::new();
395 let mut buffer = [0u8; 512];
401 let err = file.read_at(u64::MAX - 30, &mut buffer).await.expect_err("Read fails");
402 assert_eq!(err, Status::INVALID_ARGS);
403 }
404
405 #[fuchsia::test]
406 async fn test_get_attributes() {
407 let file = TestFile::new();
408 let fio::NodeAttributes2 { mutable_attributes, immutable_attributes } =
409 vfs::node::Node::get_attributes(&**file, fio::NodeAttributesQuery::all())
410 .await
411 .unwrap();
412 assert_eq!(immutable_attributes.content_size.unwrap(), TEST_FILE_CONTENT.len() as u64);
413 assert!(immutable_attributes.storage_size.unwrap() > TEST_FILE_CONTENT.len() as u64);
414 assert_eq!(immutable_attributes.protocols.unwrap(), fio::NodeProtocolKinds::FILE);
415 assert_eq!(
416 immutable_attributes.abilities.unwrap(),
417 fio::Abilities::GET_ATTRIBUTES
418 | fio::Abilities::UPDATE_ATTRIBUTES
419 | fio::Abilities::READ_BYTES
420 | fio::Abilities::WRITE_BYTES
421 );
422 assert!(mutable_attributes.creation_time.is_some());
423 assert!(mutable_attributes.modification_time.is_some());
424 }
425
426 #[fuchsia::test]
427 async fn test_update_attributes() {
428 let file = TestFile::new();
429
430 let new_time = std::time::SystemTime::now()
431 .duration_since(std::time::SystemTime::UNIX_EPOCH)
432 .expect("SystemTime before UNIX EPOCH")
433 .as_nanos();
434 let new_attrs = fio::MutableNodeAttributes {
435 creation_time: Some(new_time.try_into().unwrap()),
436 ..Default::default()
437 };
438 file.update_attributes(new_attrs).await.expect("update attributes failed");
439 }
440}