virtual_fs/
static_fs.rs

1use anyhow::anyhow;
2use futures::future::BoxFuture;
3use tokio::io::{AsyncRead, AsyncSeek, AsyncWrite};
4
5use std::convert::TryInto;
6use std::io::{self, Error as IoError, ErrorKind as IoErrorKind, SeekFrom};
7use std::path::Path;
8use std::path::PathBuf;
9use std::pin::Pin;
10use std::sync::Arc;
11use std::task::{Context, Poll};
12
13use crate::mem_fs::FileSystem as MemFileSystem;
14use crate::{
15    FileOpener, FileSystem, FsError, Metadata, OpenOptions, OpenOptionsConfig, ReadDir, VirtualFile,
16};
17use indexmap::IndexMap;
18use webc::v1::{FsEntry, FsEntryType, OwnedFsEntryFile};
19
20/// Custom file system wrapper to map requested file paths
21#[derive(Debug)]
22pub struct StaticFileSystem {
23    pub package: String,
24    pub volumes: Arc<IndexMap<String, webc::v1::Volume<'static>>>,
25    pub memory: Arc<MemFileSystem>,
26}
27
28impl StaticFileSystem {
29    pub fn init(bytes: &'static [u8], package: &str) -> Option<Self> {
30        let volumes = Arc::new(webc::v1::WebC::parse_volumes_from_fileblock(bytes).ok()?);
31        let fs = Self {
32            package: package.to_string(),
33            volumes: volumes.clone(),
34            memory: Arc::new(MemFileSystem::default()),
35        };
36        let volume_names = fs.volumes.keys().cloned().collect::<Vec<_>>();
37        for volume_name in volume_names {
38            let directories = volumes.get(&volume_name).unwrap().list_directories();
39            for directory in directories {
40                let _ = fs.create_dir(Path::new(&directory));
41            }
42        }
43        Some(fs)
44    }
45}
46
47/// Custom file opener, returns a WebCFile
48impl FileOpener for StaticFileSystem {
49    fn open(
50        &self,
51        path: &Path,
52        _conf: &OpenOptionsConfig,
53    ) -> Result<Box<dyn VirtualFile + Send + Sync>, FsError> {
54        match get_volume_name_opt(path) {
55            Some(volume) => {
56                let file = (*self.volumes)
57                    .get(&volume)
58                    .ok_or(FsError::EntryNotFound)?
59                    .get_file_entry(path.to_string_lossy().as_ref())
60                    .map_err(|_e| FsError::EntryNotFound)?;
61
62                Ok(Box::new(WebCFile {
63                    package: self.package.clone(),
64                    volume,
65                    volumes: self.volumes.clone(),
66                    path: path.to_path_buf(),
67                    entry: file,
68                    cursor: 0,
69                }))
70            }
71            None => {
72                for (volume, v) in self.volumes.iter() {
73                    let entry = match v.get_file_entry(path.to_string_lossy().as_ref()) {
74                        Ok(s) => s,
75                        Err(_) => continue, // error
76                    };
77
78                    return Ok(Box::new(WebCFile {
79                        package: self.package.clone(),
80                        volume: volume.clone(),
81                        volumes: self.volumes.clone(),
82                        path: path.to_path_buf(),
83                        entry,
84                        cursor: 0,
85                    }));
86                }
87                self.memory.new_open_options().open(path)
88            }
89        }
90    }
91}
92
93#[derive(Debug)]
94pub struct WebCFile {
95    pub volumes: Arc<IndexMap<String, webc::v1::Volume<'static>>>,
96    pub package: String,
97    pub volume: String,
98    pub path: PathBuf,
99    pub entry: OwnedFsEntryFile,
100    pub cursor: u64,
101}
102
103#[async_trait::async_trait]
104impl VirtualFile for WebCFile {
105    fn last_accessed(&self) -> u64 {
106        0
107    }
108    fn last_modified(&self) -> u64 {
109        0
110    }
111    fn created_time(&self) -> u64 {
112        0
113    }
114    fn size(&self) -> u64 {
115        self.entry.get_len()
116    }
117    fn set_len(&mut self, _new_size: u64) -> crate::Result<()> {
118        Ok(())
119    }
120    fn unlink(&mut self) -> Result<(), FsError> {
121        Ok(())
122    }
123    fn poll_read_ready(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<usize>> {
124        let remaining = self.entry.get_len() - self.cursor;
125        Poll::Ready(Ok(remaining as usize))
126    }
127    fn poll_write_ready(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<usize>> {
128        Poll::Ready(Ok(0))
129    }
130}
131
132impl AsyncRead for WebCFile {
133    fn poll_read(
134        self: Pin<&mut Self>,
135        _cx: &mut Context<'_>,
136        buf: &mut tokio::io::ReadBuf<'_>,
137    ) -> Poll<io::Result<()>> {
138        let bytes = self
139            .volumes
140            .get(&self.volume)
141            .ok_or_else(|| {
142                IoError::new(
143                    IoErrorKind::NotFound,
144                    anyhow!("Unknown volume {:?}", self.volume),
145                )
146            })?
147            .get_file_bytes(&self.entry)
148            .map_err(|e| IoError::new(IoErrorKind::NotFound, e))?;
149
150        let cursor: usize = self.cursor.try_into().unwrap_or(u32::MAX as usize);
151        let _start = cursor.min(bytes.len());
152        let bytes = &bytes[cursor..];
153
154        if bytes.len() > buf.remaining() {
155            let remaining = buf.remaining();
156            buf.put_slice(&bytes[..remaining]);
157        } else {
158            buf.put_slice(bytes);
159        }
160        Poll::Ready(Ok(()))
161    }
162}
163
164// WebC file is not writable, the FileOpener will return a MemoryFile for writing instead
165// This code should never be executed (since writes are redirected to memory instead).
166impl AsyncWrite for WebCFile {
167    fn poll_write(
168        self: Pin<&mut Self>,
169        _cx: &mut Context<'_>,
170        buf: &[u8],
171    ) -> Poll<io::Result<usize>> {
172        Poll::Ready(Ok(buf.len()))
173    }
174    fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
175        Poll::Ready(Ok(()))
176    }
177    fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
178        Poll::Ready(Ok(()))
179    }
180}
181
182impl AsyncSeek for WebCFile {
183    fn start_seek(mut self: Pin<&mut Self>, pos: io::SeekFrom) -> io::Result<()> {
184        let self_size = self.size();
185        match pos {
186            SeekFrom::Start(s) => {
187                self.cursor = s.min(self_size);
188            }
189            SeekFrom::End(e) => {
190                let self_size_i64 = self_size.try_into().unwrap_or(i64::MAX);
191                self.cursor = ((self_size_i64).saturating_add(e))
192                    .min(self_size_i64)
193                    .try_into()
194                    .unwrap_or(i64::MAX as u64);
195            }
196            SeekFrom::Current(c) => {
197                self.cursor = (self
198                    .cursor
199                    .saturating_add(c.try_into().unwrap_or(i64::MAX as u64)))
200                .min(self_size);
201            }
202        }
203        Ok(())
204    }
205    fn poll_complete(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<u64>> {
206        Poll::Ready(Ok(self.cursor))
207    }
208}
209
210fn get_volume_name_opt<P: AsRef<Path>>(path: P) -> Option<String> {
211    use std::path::Component::Normal;
212    if let Some(Normal(n)) = path.as_ref().components().next()
213        && let Some(s) = n.to_str()
214        && s.ends_with(':')
215    {
216        return Some(s.replace(':', ""));
217    }
218    None
219}
220
221fn transform_into_read_dir(path: &Path, fs_entries: &[FsEntry<'_>]) -> crate::ReadDir {
222    let entries = fs_entries
223        .iter()
224        .map(|e| crate::DirEntry {
225            path: path.join(&*e.text),
226            metadata: Ok(crate::Metadata {
227                ft: translate_file_type(e.fs_type),
228                accessed: 0,
229                created: 0,
230                modified: 0,
231                len: e.get_len(),
232            }),
233        })
234        .collect();
235
236    crate::ReadDir::new(entries)
237}
238
239impl FileSystem for StaticFileSystem {
240    fn readlink(&self, path: &Path) -> crate::Result<PathBuf> {
241        let path = normalizes_path(path);
242        if self
243            .volumes
244            .values()
245            .find_map(|v| v.get_file_entry(&path).ok())
246            .is_some()
247        {
248            Err(FsError::InvalidInput)
249        } else {
250            self.memory.readlink(Path::new(&path))
251        }
252    }
253
254    fn read_dir(&self, path: &Path) -> Result<ReadDir, FsError> {
255        let path = normalizes_path(path);
256        for volume in self.volumes.values() {
257            let read_dir_result = volume
258                .read_dir(&path)
259                .map(|o| transform_into_read_dir(Path::new(&path), o.as_ref()))
260                .map_err(|_| FsError::EntryNotFound);
261
262            match read_dir_result {
263                Ok(o) => {
264                    return Ok(o);
265                }
266                Err(_) => {
267                    continue;
268                }
269            }
270        }
271
272        self.memory.read_dir(Path::new(&path))
273    }
274    fn create_dir(&self, path: &Path) -> Result<(), FsError> {
275        let path = normalizes_path(path);
276        self.memory.create_dir(Path::new(&path))
277    }
278    fn remove_dir(&self, path: &Path) -> Result<(), FsError> {
279        let path = normalizes_path(path);
280        let result = self.memory.remove_dir(Path::new(&path));
281        if self
282            .volumes
283            .values()
284            .find_map(|v| v.get_file_entry(&path).ok())
285            .is_some()
286        {
287            Ok(())
288        } else {
289            result
290        }
291    }
292    fn rename<'a>(&'a self, from: &'a Path, to: &'a Path) -> BoxFuture<'a, Result<(), FsError>> {
293        Box::pin(async {
294            let from = normalizes_path(from);
295            let to = normalizes_path(to);
296            let result = self.memory.rename(Path::new(&from), Path::new(&to)).await;
297            if self
298                .volumes
299                .values()
300                .find_map(|v| v.get_file_entry(&from).ok())
301                .is_some()
302            {
303                Ok(())
304            } else {
305                result
306            }
307        })
308    }
309    fn metadata(&self, path: &Path) -> Result<Metadata, FsError> {
310        let path = normalizes_path(path);
311        if let Some(fs_entry) = self
312            .volumes
313            .values()
314            .find_map(|v| v.get_file_entry(&path).ok())
315        {
316            Ok(Metadata {
317                ft: translate_file_type(FsEntryType::File),
318                accessed: 0,
319                created: 0,
320                modified: 0,
321                len: fs_entry.get_len(),
322            })
323        } else if let Some(_fs) = self.volumes.values().find_map(|v| v.read_dir(&path).ok()) {
324            Ok(Metadata {
325                ft: translate_file_type(FsEntryType::Dir),
326                accessed: 0,
327                created: 0,
328                modified: 0,
329                len: 0,
330            })
331        } else {
332            self.memory.metadata(Path::new(&path))
333        }
334    }
335    fn remove_file(&self, path: &Path) -> Result<(), FsError> {
336        let path = normalizes_path(path);
337        let result = self.memory.remove_file(Path::new(&path));
338        if self
339            .volumes
340            .values()
341            .find_map(|v| v.get_file_entry(&path).ok())
342            .is_some()
343        {
344            Ok(())
345        } else {
346            result
347        }
348    }
349    fn new_open_options(&self) -> OpenOptions<'_> {
350        OpenOptions::new(self)
351    }
352    fn symlink_metadata(&self, path: &Path) -> Result<Metadata, FsError> {
353        let path = normalizes_path(path);
354        if let Some(fs_entry) = self
355            .volumes
356            .values()
357            .find_map(|v| v.get_file_entry(&path).ok())
358        {
359            Ok(Metadata {
360                ft: translate_file_type(FsEntryType::File),
361                accessed: 0,
362                created: 0,
363                modified: 0,
364                len: fs_entry.get_len(),
365            })
366        } else if self
367            .volumes
368            .values()
369            .find_map(|v| v.read_dir(&path).ok())
370            .is_some()
371        {
372            Ok(Metadata {
373                ft: translate_file_type(FsEntryType::Dir),
374                accessed: 0,
375                created: 0,
376                modified: 0,
377                len: 0,
378            })
379        } else {
380            self.memory.symlink_metadata(Path::new(&path))
381        }
382    }
383
384    fn mount(
385        &self,
386        _name: String,
387        _path: &Path,
388        _fs: Box<dyn FileSystem + Send + Sync>,
389    ) -> Result<(), FsError> {
390        Err(FsError::Unsupported)
391    }
392}
393
394fn normalizes_path(path: &Path) -> String {
395    let path = format!("{}", path.display());
396    if !path.starts_with('/') {
397        format!("/{path}")
398    } else {
399        path
400    }
401}
402
403fn translate_file_type(f: FsEntryType) -> crate::FileType {
404    crate::FileType {
405        dir: f == FsEntryType::Dir,
406        file: f == FsEntryType::File,
407        symlink: false,
408        char_device: false,
409        block_device: false,
410        socket: false,
411        fifo: false,
412    }
413}