1use crate::{
2 Status,
3 registry::{self, Handle},
4};
5use alloc::string::String;
6use core::{ffi::c_char, slice, str};
7use file_system::PathOwned;
8use virtual_file_system::VirtualFileSystem;
9
10pub const XILA_RIGHT_READ: u32 = 1;
11pub const XILA_RIGHT_WRITE: u32 = 2;
12
13pub struct Directory {
15 pub(crate) vfs: &'static VirtualFileSystem,
16 pub(crate) task: task::TaskIdentifier,
17 pub(crate) path: PathOwned,
18 pub(crate) rights: u8,
19}
20impl Directory {
21 pub fn new(
23 vfs: &'static VirtualFileSystem,
24 task: task::TaskIdentifier,
25 path: &str,
26 rights: u32,
27 ) -> Result<Self, Status> {
28 validate_rights(rights)?;
29 if !path.starts_with('/') {
30 return Err(Status::InvalidArgument);
31 }
32 let path = canonical("/", &path[1..], false)?;
33 Self::validated(vfs, task, path, rights as u8)
34 }
35 fn validated(
36 vfs: &'static VirtualFileSystem,
37 task: task::TaskIdentifier,
38 path: PathOwned,
39 rights: u8,
40 ) -> Result<Self, Status> {
41 let path = crate::suspend_on_cancellable(async move {
45 virtual_file_system::Directory::open(vfs, task, &path)
46 .await?
47 .close(vfs)
48 .await
49 .map(|()| path)
50 })
51 .map_err(Status::from)?;
52 Ok(Self::granted(vfs, task, path, rights))
53 }
54 pub(crate) fn granted(
57 vfs: &'static VirtualFileSystem,
58 task: task::TaskIdentifier,
59 path: PathOwned,
60 rights: u8,
61 ) -> Self {
62 Self {
63 vfs,
64 task,
65 path,
66 rights,
67 }
68 }
69 pub fn into_raw(self) -> *mut Self {
72 registry::register(self)
73 }
74 pub unsafe fn from_raw(raw: *mut Self) -> Self {
78 unsafe { registry::reclaim(raw) }
79 }
80}
81
82impl Handle for Directory {
83 unsafe fn close(raw: *mut Self) {
84 let _ = unsafe { xila_directory_close(raw) };
86 }
87}
88#[inline]
89pub(crate) fn validate_rights(rights: u32) -> Result<(), Status> {
90 if rights & !3 != 0 {
91 Err(Status::InvalidArgument)
92 } else {
93 Ok(())
94 }
95}
96pub(crate) fn canonical(base: &str, path: &str, entry: bool) -> Result<PathOwned, Status> {
100 if path.starts_with('/')
101 || path.contains('\0')
102 || path.split('/').any(|part| part == "..")
103 || (entry && path.split('/').all(|part| part.is_empty() || part == "."))
104 {
105 return Err(Status::InvalidArgument);
106 }
107 let mut joined = String::with_capacity(base.len() + path.len() + 1);
108 joined.push_str(base);
109 for part in path
110 .split('/')
111 .filter(|part| !part.is_empty() && *part != ".")
112 {
113 if !joined.ends_with('/') {
114 joined.push('/');
115 }
116 joined.push_str(part);
117 }
118 PathOwned::new(joined).ok_or(Status::InvalidArgument)
119}
120#[inline]
121pub(crate) unsafe fn path_input<'a>(path: *const c_char, length: usize) -> Result<&'a str, Status> {
122 if path.is_null() || length > isize::MAX as usize {
123 return Err(Status::InvalidArgument);
124 }
125 str::from_utf8(unsafe { slice::from_raw_parts(path.cast(), length) })
126 .map_err(|_| Status::InvalidArgument)
127}
128
129pub unsafe extern "C" fn xila_directory_open(
134 parent: *const Directory,
135 path: *const c_char,
136 path_length: usize,
137 rights: u32,
138 directory: *mut *mut Directory,
139) -> Status {
140 if parent.is_null() || directory.is_null() {
141 return Status::InvalidArgument;
142 }
143 let parent = unsafe { &*parent };
145 let result = (|| {
146 validate_rights(rights)?;
147 if rights & !(parent.rights as u32) != 0 {
148 return Err(Status::PermissionDenied);
149 }
150 let path = canonical(
151 parent.path.as_str(),
152 unsafe { path_input(path, path_length)? },
153 false,
154 )?;
155 Directory::validated(parent.vfs, parent.task, path, rights as u8)
156 })();
157 match result {
158 Ok(value) => {
159 unsafe { directory.write(value.into_raw()) };
160 Status::Ok
161 }
162 Err(error) => error,
163 }
164}
165pub unsafe extern "C" fn xila_directory_close(directory: *mut Directory) -> Status {
169 if !directory.is_null() {
170 drop(unsafe { Directory::from_raw(directory) });
171 }
172 Status::Ok
173}
174
175impl Directory {
176 pub(crate) unsafe fn resolve(
177 &self,
178 path: *const c_char,
179 length: usize,
180 right: u32,
181 nonempty: bool,
182 ) -> Result<PathOwned, Status> {
183 if path.is_null() {
184 return Err(Status::InvalidArgument);
185 }
186 if u32::from(self.rights) & right == 0 {
187 return Err(Status::PermissionDenied);
188 }
189 canonical(
190 self.path.as_str(),
191 unsafe { path_input(path, length)? },
192 nonempty,
193 )
194 }
195}
196
197pub unsafe extern "C" fn xila_directory_create(
201 directory: *const Directory,
202 path: *const c_char,
203 length: usize,
204) -> Status {
205 if directory.is_null() {
206 return Status::InvalidArgument;
207 }
208 let directory = unsafe { &*directory };
210 let result = (|| {
211 let path = unsafe { directory.resolve(path, length, XILA_RIGHT_WRITE, true)? };
212 let (vfs, task) = (directory.vfs, directory.task);
213 crate::suspend_on_cancellable(async move { vfs.create_directory(task, &path).await })
214 .map_err(Status::from)
215 })();
216 result.map_or_else(|error| error, |()| Status::Ok)
217}
218
219pub const XILA_REMOVE_DIRECTORY: u32 = 1;
221
222pub unsafe extern "C" fn xila_directory_remove(
226 directory: *const Directory,
227 path: *const c_char,
228 length: usize,
229 flags: u32,
230) -> Status {
231 if directory.is_null() || flags & !XILA_REMOVE_DIRECTORY != 0 {
232 return Status::InvalidArgument;
233 }
234 let directory = unsafe { &*directory };
236 let result = (|| {
237 let path = unsafe { directory.resolve(path, length, XILA_RIGHT_WRITE, true)? };
238 let (vfs, task) = (directory.vfs, directory.task);
239 crate::suspend_on_cancellable(async move {
240 if flags & XILA_REMOVE_DIRECTORY == 0
243 && vfs.get_link_statistics_for_task(task, &path).await?.kind
244 == file_system::Kind::Directory
245 {
246 return Err(Status::IsADirectory);
247 }
248 vfs.remove(task, &path).await.map_err(Status::from)
249 })
250 })();
251 result.map_or_else(|error| error, |()| Status::Ok)
252}
253
254pub unsafe extern "C" fn xila_directory_rename(
259 from: *const Directory,
260 from_path: *const c_char,
261 from_length: usize,
262 to: *const Directory,
263 to_path: *const c_char,
264 to_length: usize,
265) -> Status {
266 if from.is_null() || to.is_null() {
267 return Status::InvalidArgument;
268 }
269 let (from, to) = unsafe { (&*from, &*to) };
271 let result = (|| {
272 let from_path = unsafe { from.resolve(from_path, from_length, XILA_RIGHT_WRITE, true)? };
273 let to_path = unsafe { to.resolve(to_path, to_length, XILA_RIGHT_WRITE, true)? };
274 if !core::ptr::eq(from.vfs, to.vfs) || from.task != to.task {
275 return Err(Status::InvalidArgument);
276 }
277 let (vfs, task) = (from.vfs, from.task);
278 crate::suspend_on_cancellable(async move { vfs.rename(task, &from_path, &to_path).await })
279 .map_err(Status::from)
280 })();
281 result.map_or_else(|error| error, |()| Status::Ok)
282}