Skip to main content

abi_application/
directory.rs

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
13/// Opaque path capability. Native callers must serialize access and preserve ownership.
14pub 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    /// Validate an absolute directory and retain its canonical path and authority.
22    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        // Open and close in one suspension: the listing and the path exist only inside the
42        // future, which a cancellation drops in place, so neither sits in the program's
43        // frames. The future gives the path back once the directory is validated.
44        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    /// A capability a process was granted for a directory the granter holds already,
55    /// bound to the process's own task. The granter validated it, so this does not.
56    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    /// Hand the capability to a program as an owned pointer. Inside a native process it is
70    /// also registered, so the host frees it if the process ends without doing so.
71    pub fn into_raw(self) -> *mut Self {
72        registry::register(self)
73    }
74    /// Reclaim an owned capability.
75    /// # Safety
76    /// `raw` must be a live pointer returned by `into_raw`, reclaimed exactly once.
77    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        // SAFETY: the registry holds only live capabilities that came from `into_raw`.
85        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}
96/// Join `path` below `base`. With `entry`, the path must name an entry below the
97/// capability, never the capability itself (`""`, `"."`, `"./"`), so that it cannot
98/// be opened as a file, removed or renamed.
99pub(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
129/// Open a relative directory; requested rights must be a subset of the parent's.
130/// # Safety
131/// Non-null objects must be live. Path must be readable for its length and output
132/// writable and aligned. Outputs must not overlap inputs. Calls must be serialized.
133pub 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    // SAFETY: checked non-null above; the caller guarantees the object is live.
144    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}
165/// Release a directory capability. Null is a no-op.
166/// # Safety
167/// Non-null pointer must be owned, live, and released exactly once; no concurrent calls.
168pub 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
197/// Create a relative directory with the WRITE right.
198/// # Safety
199/// Directory must be live; path readable for length. Calls must be serialized.
200pub 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    // SAFETY: checked non-null above; the caller guarantees the object is live.
209    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
219/// Allow removing directories as well as files. Removal never follows the final link.
220pub const XILA_REMOVE_DIRECTORY: u32 = 1;
221
222/// Remove a relative entry; XILA_REMOVE_DIRECTORY permits directory removal.
223/// # Safety
224/// Directory must be live; path readable for length. Calls must be serialized.
225pub 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    // SAFETY: checked non-null above; the caller guarantees the object is live.
235    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            // The VFS has a single remove primitive. A caller must explicitly permit
241            // directories.
242            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
254/// Rename an entry using two WRITE capabilities with the same VFS and task.
255/// Existing destinations follow the underlying filesystem's replacement semantics.
256/// # Safety
257/// Objects must be live and paths readable for their lengths. Calls must be serialized.
258pub 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    // SAFETY: checked non-null above; the caller guarantees the objects are live.
270    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}