shellcanvas_filesystem_sdk/
lib.rs1use async_trait::async_trait;
5use serde::{Deserialize, Serialize};
6use std::{fmt, sync::Arc};
7pub mod bridge_control;
8pub mod wire;
9
10pub const MOUNT_IO_CHUNK: usize = 32 * 1024;
11
12#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
13pub enum FsErrorKind {
14 NotFound,
15 PermissionDenied,
16 AlreadyExists,
17 NotDirectory,
18 IsDirectory,
19 NotEmpty,
20 InvalidInput,
21 Unsupported,
22 ReadOnly,
23 Offline,
24 TimedOut,
25 Io,
26}
27#[derive(Clone, Debug, Serialize, Deserialize)]
28pub struct FsError {
29 pub kind: FsErrorKind,
30 pub message: String,
31}
32impl FsError {
33 pub fn new(kind: FsErrorKind, message: impl Into<String>) -> Self {
34 Self {
35 kind,
36 message: message.into(),
37 }
38 }
39}
40impl fmt::Display for FsError {
41 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42 f.write_str(&self.message)
43 }
44}
45impl std::error::Error for FsError {}
46pub type FsResult<T> = Result<T, FsError>;
47
48#[derive(Clone, Debug, Default, Eq, PartialEq, Hash, Serialize, Deserialize)]
52#[serde(try_from = "Vec<String>", into = "Vec<String>")]
53pub struct MountPath(Vec<String>);
54impl TryFrom<Vec<String>> for MountPath {
55 type Error = FsError;
56 fn try_from(names: Vec<String>) -> FsResult<Self> {
57 names
58 .iter()
59 .try_fold(Self::root(), |path, name| path.child(name))
60 }
61}
62impl From<MountPath> for Vec<String> {
63 fn from(path: MountPath) -> Self {
64 path.0
65 }
66}
67impl MountPath {
68 pub fn root() -> Self {
69 Self::default()
70 }
71 pub fn components(&self) -> &[String] {
72 &self.0
73 }
74 pub fn child(&self, name: &str) -> FsResult<Self> {
75 if name.is_empty() || matches!(name, "." | "..") || name.contains(['/', '\\', '\0', ':']) {
76 return Err(FsError::new(
77 FsErrorKind::InvalidInput,
78 "Invalid mounted filename",
79 ));
80 }
81 let mut path = self.0.clone();
82 path.push(name.into());
83 Ok(Self(path))
84 }
85 pub fn parent(&self) -> Option<Self> {
86 (!self.0.is_empty()).then(|| Self(self.0[..self.0.len() - 1].to_vec()))
87 }
88}
89
90#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
91pub enum FsKind {
92 File,
93 Directory,
94 Symlink,
95 Other,
96}
97#[derive(Clone, Debug, Serialize, Deserialize)]
98pub struct FsMetadata {
99 pub kind: FsKind,
100 pub size: u64,
101 pub accessed: Option<u64>,
103 pub modified: Option<u64>,
104 pub permissions: Option<u32>,
105}
106#[derive(Clone, Debug, Serialize, Deserialize)]
107pub struct FsDirectoryEntry {
108 pub name: String,
109 pub metadata: FsMetadata,
110}
111#[derive(Clone, Debug, Serialize, Deserialize)]
112pub struct FsSpace {
113 pub block_size: u64,
114 pub blocks: u64,
115 pub blocks_free: u64,
116 pub blocks_available: u64,
117 pub files: u64,
118 pub files_free: u64,
119 pub name_max: u64,
120}
121#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
122pub struct FsCapabilities {
123 pub writable: bool,
124 pub atomic_replace: bool,
125 pub durable_flush: bool,
126}
127#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
128pub enum FsCreate {
129 OpenExisting,
130 CreateNew,
131 OpenOrCreate,
132}
133#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
134pub struct FsOpenOptions {
135 pub read: bool,
136 pub write: bool,
137 pub create: FsCreate,
138 pub truncate: bool,
139}
140impl FsOpenOptions {
141 pub fn validate(self) -> FsResult<()> {
142 if !self.write && (!self.read || self.truncate || self.create != FsCreate::OpenExisting) {
143 return Err(FsError::new(
144 FsErrorKind::InvalidInput,
145 "Invalid file open options",
146 ));
147 }
148 Ok(())
149 }
150}
151#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize)]
152pub struct FsSetMetadata {
153 pub size: Option<u64>,
154 pub accessed: Option<u64>,
155 pub modified: Option<u64>,
156 pub permissions: Option<u32>,
157}
158
159#[async_trait]
163pub trait MountedFile: Send + Sync {
164 async fn metadata(&self) -> FsResult<FsMetadata>;
165 async fn read_at(&self, offset: u64, length: u32) -> FsResult<Vec<u8>>;
166 async fn write_at(&self, offset: u64, bytes: &[u8]) -> FsResult<()>;
167 async fn set_metadata(&self, metadata: FsSetMetadata) -> FsResult<()>;
170 async fn flush(&self) -> FsResult<()>;
172 async fn close(&self) -> FsResult<()>;
173}
174#[async_trait]
175pub trait MountedDirectory: Send {
176 async fn next(&mut self) -> FsResult<Vec<FsDirectoryEntry>>;
178 async fn close(&mut self) -> FsResult<()>;
179}
180#[async_trait]
181pub trait MountedFileSystem: Send + Sync {
182 fn check_available(&self) -> FsResult<()> {
184 Ok(())
185 }
186 fn capabilities(&self) -> FsCapabilities;
187 async fn space(&self, _path: &MountPath) -> FsResult<FsSpace> {
188 Err(FsError::new(
189 FsErrorKind::Unsupported,
190 "Remote capacity reporting is unavailable",
191 ))
192 }
193 async fn metadata(&self, path: &MountPath) -> FsResult<FsMetadata>;
194 async fn open(
195 &self,
196 path: &MountPath,
197 options: FsOpenOptions,
198 ) -> FsResult<Arc<dyn MountedFile>>;
199 async fn open_directory(&self, path: &MountPath) -> FsResult<Box<dyn MountedDirectory>>;
200 async fn set_metadata(&self, path: &MountPath, metadata: FsSetMetadata) -> FsResult<()>;
201 async fn mkdir(&self, path: &MountPath) -> FsResult<()>;
202 async fn remove(&self, path: &MountPath, directory: bool) -> FsResult<()>;
203 async fn rename(&self, from: &MountPath, to: &MountPath, replace: bool) -> FsResult<()>;
204}
205
206#[cfg(test)]
207mod tests {
208 use super::*;
209 #[test]
210 fn mount_paths_cannot_escape_or_inject_native_namespaces() {
211 for name in [
212 "",
213 ".",
214 "..",
215 "../outside",
216 "a/b",
217 "a\\b",
218 "C:",
219 "file:stream",
220 "nul\0",
221 ] {
222 assert!(MountPath::root().child(name).is_err(), "{name:?}");
223 }
224 let path = MountPath::root()
225 .child("資料")
226 .unwrap()
227 .child("hello world.txt")
228 .unwrap();
229 assert_eq!(path.components(), &["資料", "hello world.txt"]);
230 assert_eq!(path.parent().unwrap().parent().unwrap(), MountPath::root());
231 assert!(MountPath::root().parent().is_none());
232 }
233}