Skip to main content

starnix_core/fs/fuchsia/
remote_volume.rs

1// Copyright 2025 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::fs::fuchsia::RemoteFs;
6use crate::task::CurrentTask;
7use crate::task::dynamic_thread_spawner::SpawnRequestBuilder;
8use crate::vfs::{
9    CacheMode, FileSystem, FileSystemHandle, FileSystemOps, FileSystemOptions, FsStr, RenameContext,
10};
11use fidl::endpoints::{DiscoverableProtocolMarker, SynchronousProxy, create_sync_proxy};
12use fidl_fuchsia_fshost::StarnixVolumeProviderMarker;
13use fidl_fuchsia_fxfs::{CryptMarker, DebugMarker};
14use fidl_fuchsia_hardware_inlineencryption::DeviceMarker as InlineEncryptionDeviceMarker;
15use fidl_fuchsia_io as fio;
16use starnix_crypt::CryptService;
17use starnix_logging::{Level, log, log_error};
18use starnix_uapi::errors::Errno;
19use starnix_uapi::{errno, error, from_status_like_fdio, statfs};
20use std::sync::Arc;
21use sync_io_client::SyncIo;
22use thiserror::Error;
23
24const CRYPT_THREAD_ROLE: &str = "fuchsia.starnix.remotevol.crypt";
25// `KEY_FILE_PATH` determines where the volume-wide keys for the Starnix volume will live in the
26// container's data storage capability.
27const KEY_FILE_PATH: &str = "key_file";
28
29pub struct RemoteVolume<I> {
30    remotefs: RemoteFs<I>,
31    exposed_dir_proxy: fio::DirectorySynchronousProxy,
32    crypt_service: Arc<CryptService>,
33}
34
35impl<I> RemoteVolume<I> {
36    pub fn remotefs(&self) -> &RemoteFs<I> {
37        &self.remotefs
38    }
39}
40
41impl<I: SyncIo> FileSystemOps for RemoteVolume<I> {
42    fn statfs(&self, fs: &FileSystem, current_task: &CurrentTask) -> Result<statfs, Errno> {
43        self.remotefs.statfs(fs, current_task)
44    }
45
46    fn name(&self) -> &'static FsStr {
47        "remotevol".into()
48    }
49
50    fn uses_external_node_ids(&self) -> bool {
51        self.remotefs.uses_external_node_ids()
52    }
53
54    fn has_casefold_support(&self) -> bool {
55        self.remotefs.has_casefold_support()
56    }
57
58    fn rename(
59        &self,
60        fs: &FileSystem,
61        current_task: &CurrentTask,
62        context: &mut RenameContext<'_>,
63        old_name: &FsStr,
64        new_name: &FsStr,
65    ) -> Result<(), Errno> {
66        self.remotefs.rename(fs, current_task, context, old_name, new_name)
67    }
68
69    fn sync(&self, fs: &FileSystem, current_task: &CurrentTask) -> Result<(), Errno> {
70        self.remotefs.sync(fs, current_task)
71    }
72
73    fn unmount(&self) {
74        let (proxy, server_end) = create_sync_proxy::<fidl_fuchsia_fs::AdminMarker>();
75        if let Err(e) = fdio::service_connect_at(
76            self.exposed_dir_proxy.as_channel(),
77            &format!("svc/{}", fidl_fuchsia_fs::AdminMarker::PROTOCOL_NAME),
78            server_end.into(),
79        ) {
80            log_error!(e:%; "StarnixVolumeProvider.Unmount failed to connect to fuchsia.fs.Admin");
81            return;
82        }
83
84        if let Err(e) = proxy.shutdown(zx::MonotonicInstant::INFINITE) {
85            log_error!(e:%; "StarnixVolumeProvider.Unmount failed at FIDL layer");
86        }
87    }
88
89    fn crypt_service(&self) -> Option<Arc<CryptService>> {
90        Some(self.crypt_service.clone())
91    }
92
93    fn drop_caches(&self, _fs: &FileSystem) -> Result<(), Errno> {
94        let (proxy, server_end) = create_sync_proxy::<DebugMarker>();
95        if let Err(e) = fdio::service_connect_at(
96            self.exposed_dir_proxy.as_channel(),
97            &format!("svc/{}", DebugMarker::PROTOCOL_NAME),
98            server_end.into(),
99        ) {
100            log_error!(e:%; "RemoteVolume.drop_caches failed to connect to fuchsia.fxfs.Debug");
101            return error!(EIO);
102        }
103
104        match proxy.clear_caches(zx::MonotonicInstant::INFINITE) {
105            Ok(Ok(())) => Ok(()),
106            Ok(Err(status)) => {
107                let err = from_status_like_fdio!(zx::Status::err_from_raw(status));
108                log_error!(err:?; "RemoteVolume.drop_caches failed");
109                Err(err)
110            }
111            Err(e) => {
112                log_error!(e:%; "RemoteVolume.drop_caches failed at FIDL layer");
113                error!(EIO)
114            }
115        }
116    }
117}
118
119// Key file
120// ========
121//
122// Version 1: No longer supported.
123// Version 2:
124//
125//   +-2-+------- 32 -------+------- 32 -------+
126//   | V |   metadata key   |     data key     |
127//   +---+------------------+------------------+
128//
129// Version 2 includes a 16 bit version which indicates the version of the key file.  The key
130// identifiers used for version 2 key files will use the lblk32 algorithm.
131
132struct VolumeKeys {
133    metadata: [u8; 32],
134    data: [u8; 32],
135}
136
137#[derive(Error, Debug, Eq, PartialEq)]
138enum KeyFileError {
139    #[error("key file not found")]
140    NotFound,
141    #[error("failed to read key file")]
142    ReadError(#[from] zx::Status),
143    #[error("unsupported key file version")]
144    UnsupportedVersion,
145    #[error("unexpected content")]
146    UnexpectedContent,
147}
148
149impl VolumeKeys {
150    // `KEYS_SIZE` is the size of the two keys (the metadata key, and the data key) stored in the
151    // key file.
152    const KEYS_SIZE: usize = 64;
153
154    // Includes 2 bytes for the version.
155    const FILE_SIZE: usize = 2 + Self::KEYS_SIZE;
156
157    const LATEST_VERSION: u16 = 2;
158
159    /// Returns (keys, did_create).
160    fn get_or_create(
161        data: &fio::DirectorySynchronousProxy,
162        key_path: &str,
163    ) -> Result<(Self, bool), Errno> {
164        match Self::get(data, key_path) {
165            Ok(keys) => Ok((keys, false)),
166            Err(KeyFileError::ReadError(status)) => {
167                // If there's a read error, we just return the error rather than try and create a
168                // key file.  Chances are that if we are unable to read the file, we'll be unable to
169                // create the file too.  A missing key file is handled differently.
170                Err(from_status_like_fdio!(status))
171            }
172            Err(e) => {
173                log!(
174                    if e == KeyFileError::NotFound { Level::Info } else { Level::Warn },
175                    "Creating key file at {key_path} (reason={e:?}) which will \
176                     cause existing data to be *wiped* if it exists."
177                );
178                Ok((Self::create(data, key_path)?, true))
179            }
180        }
181    }
182
183    /// Returns None rather than an error if the key file does not exist or is corrupt,
184    /// but returns all other errors (e.g. if the connection to `data` is closed).
185    fn get(data: &fio::DirectorySynchronousProxy, key_path: &str) -> Result<Self, KeyFileError> {
186        match syncio::directory_read_file(data, key_path, zx::MonotonicInstant::INFINITE) {
187            Ok(bytes) => {
188                if bytes.len() == Self::FILE_SIZE {
189                    if u16::from_le_bytes(bytes[0..2].try_into().unwrap()) != Self::LATEST_VERSION {
190                        Err(KeyFileError::UnsupportedVersion)
191                    } else {
192                        Ok(Self {
193                            metadata: bytes[2..34].try_into().unwrap(),
194                            data: bytes[34..66].try_into().unwrap(),
195                        })
196                    }
197                } else {
198                    Err(KeyFileError::UnexpectedContent)
199                }
200            }
201            Err(zx::Status::NOT_FOUND) => {
202                // This is expected after an FDR or clean install.
203                Err(KeyFileError::NotFound)
204            }
205            Err(status) => {
206                log_error!(status:?; "Failed to read key file");
207                Err(status.into())
208            }
209        }
210    }
211
212    /// Creates a new key file at the latest version, with new random metadata and data keys.
213    fn create(data: &fio::DirectorySynchronousProxy, key_path: &str) -> Result<Self, Errno> {
214        let mut bytes = [0; Self::FILE_SIZE];
215        bytes[..2].copy_from_slice(&Self::LATEST_VERSION.to_le_bytes());
216        starnix_crypto::cprng_draw(&mut bytes[2..]);
217        let tmp_file = syncio::directory_create_tmp_file(
218            data,
219            fio::PERM_READABLE,
220            zx::MonotonicInstant::INFINITE,
221        )
222        .map_err(|e| {
223            let err = from_status_like_fdio!(e);
224            log_error!("Failed to create tmp file with error: {:?}", err);
225            err
226        })?;
227        tmp_file
228            .write(&bytes, zx::MonotonicInstant::INFINITE)
229            .map_err(|e| {
230                log_error!("FIDL transport error on File.Write {:?}", e);
231                errno!(ENOENT)
232            })?
233            .map_err(|e| {
234                let err = from_status_like_fdio!(zx::Status::err_from_raw(e));
235                log_error!("File.Write failed with {:?}", err);
236                err
237            })?;
238        tmp_file
239            .sync(zx::MonotonicInstant::INFINITE)
240            .map_err(|e| {
241                log_error!("FIDL transport error on File.Sync {:?}", e);
242                errno!(ENOENT)
243            })?
244            .map_err(|e| {
245                let err = from_status_like_fdio!(zx::Status::err_from_raw(e));
246                log_error!("File.Sync failed with {:?}", err);
247                err
248            })?;
249        let token = data
250            .get_token(zx::MonotonicInstant::INFINITE)
251            .map_err(|e| {
252                log_error!("transport error on get_token for the data directory, error: {:?}", e);
253                errno!(ENOENT)
254            })?
255            .map_err(|status| {
256                let err = from_status_like_fdio!(zx::Status::err_from_raw(status));
257                log_error!("Failed to get_token for the data directory, error: {:?}", err);
258                err
259            })?;
260
261        tmp_file
262            .link_into(token, key_path, zx::MonotonicInstant::INFINITE)
263            .map_err(|e| {
264                log_error!("FIDL transport error on File.LinkInto {:?}", e);
265                errno!(EIO)
266            })?
267            .map_err(|e| {
268                let err = from_status_like_fdio!(zx::Status::err_from_raw(e));
269                log_error!("File.LinkInto failed with {:?}", err);
270                err
271            })?;
272        Ok(Self {
273            metadata: bytes[2..34].try_into().unwrap(),
274            data: bytes[34..].try_into().unwrap(),
275        })
276    }
277}
278
279pub fn new_remote_vol(
280    current_task: &CurrentTask,
281    options: FileSystemOptions,
282) -> Result<FileSystemHandle, Errno> {
283    let kernel = current_task.kernel();
284    if kernel.features.remotevol_in_process {
285        // TODO(https://fxbug.dev/570047887): In process volume implementation is in progress.
286        log_error!("TODO(b/570047887): remotevol_in_process is not yet implemented");
287        return Err(errno!(ENOTSUP));
288    }
289    // TODO(https://fxbug.dev/460156877): Starnix cannot handle multiple volumes.
290    let volume_provider = current_task
291        .kernel()
292        .connect_to_protocol_at_container_svc::<StarnixVolumeProviderMarker>()
293        .map_err(|_| errno!(ENOENT))?
294        .into_sync_proxy();
295
296    // We need one crypt instance for fsck, the other for mounting.
297    let (crypt_client_end, crypt_proxy) = fidl::endpoints::create_endpoints::<CryptMarker>();
298    let (crypt2_client_end, crypt2_proxy) = fidl::endpoints::create_endpoints::<CryptMarker>();
299
300    let key_location = match options.params.get(FsStr::new(b"keylocation")) {
301        Some(path) => str::from_utf8(path.as_bytes()).map_err(|_| errno!(EINVAL))?,
302        None => {
303            // TODO(https://fxbug.dev/460156877): Starnix cannot handle unencrypted volumes.
304            log_error!(
305                "TODO(b/460156877): Starnix is unable to mount remote volumes without encryption. \
306                Encrypted volumes should specify a keylocation in the mount flags."
307            );
308            return Err(errno!(EINVAL));
309        }
310    };
311
312    let open_flags =
313        fio::PERM_READABLE | fio::Flags::FLAG_MAYBE_CREATE | fio::Flags::PROTOCOL_DIRECTORY;
314    let (root, subdir) = kernel.open_ns_dir(key_location, open_flags)?;
315
316    let open_rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
317    let subdir = if subdir.is_empty() { ".".to_string() } else { subdir };
318    let key_location_proxy = syncio::directory_open_directory_async(&root, &subdir, open_rights)
319        .map_err(|e| errno!(EIO, format!("Failed to open proxy for keylocation: {e}")))?;
320
321    let (keys, created_key_file) = VolumeKeys::get_or_create(&key_location_proxy, KEY_FILE_PATH)?;
322
323    // Attempt to connect to the inline encryption device if mount options specify inline crypt
324    let inline_encryption_provider = if options.params.get(FsStr::new(b"inlinecrypt")).is_some() {
325        match current_task
326            .kernel()
327            .connect_to_protocol_at_container_svc::<InlineEncryptionDeviceMarker>()
328        {
329            Ok(client_end) => Some(client_end.into_sync_proxy()),
330            Err(error) => {
331                log_error!(error:?; "Error connecting to inline encryption device");
332                return Err(error);
333            }
334        }
335    } else {
336        None
337    };
338    let crypt_service =
339        Arc::new(CryptService::new(&keys.metadata, &keys.data, inline_encryption_provider));
340
341    let (exposed_dir_client_end, exposed_dir_server) =
342        fidl::endpoints::create_endpoints::<fio::DirectoryMarker>();
343
344    let crypt_service_clone = Arc::clone(&crypt_service);
345    let closure = async move |_: &CurrentTask| {
346        let (r1, r2) = futures::join!(
347            crypt_service_clone.handle_connection(crypt_proxy.into_stream()),
348            crypt_service_clone.handle_connection(crypt2_proxy.into_stream())
349        );
350        match (r1, r2) {
351            (Err(e1), Err(e2)) => {
352                log_error!("Error while handling Crypt connections: {e1:?}, {e2:?}")
353            }
354            (Err(e), Ok(())) => log_error!("Error while handling Crypt connection: {e:?}"),
355            (Ok(()), Err(e)) => log_error!("Error while handling Crypt2 connection: {e:?}"),
356            (Ok(()), Ok(())) => {}
357        }
358    };
359    let req = SpawnRequestBuilder::new()
360        .with_debug_name("remote-volume-crypt")
361        .with_role(CRYPT_THREAD_ROLE)
362        .with_async_closure(closure)
363        .build();
364    kernel.kthreads.spawner().spawn_from_request(req);
365
366    let mode = if created_key_file {
367        fidl_fuchsia_fshost::MountMode::AlwaysCreate
368    } else {
369        // If fsck fails, return an error.  This might trigger a reboot, which is OK -- the device
370        // should eventually land back into recovery mode.
371        volume_provider
372            .check(crypt2_client_end, zx::MonotonicInstant::INFINITE)
373            .map_err(|e| {
374                log_error!("FIDL transport error on StarnixVolumeProvider.Check {:?}", e);
375                errno!(ENOENT)
376            })?
377            .map_err(|e| {
378                let error = from_status_like_fdio!(zx::Status::err_from_raw(e));
379                log_error!(
380                    error:?;
381                    "Volume check failed. The filesystem might be corrupt!");
382                error
383            })?;
384        fidl_fuchsia_fshost::MountMode::MaybeCreate
385    };
386    let guid = volume_provider
387        .mount(crypt_client_end, mode, exposed_dir_server, zx::MonotonicInstant::INFINITE)
388        .map_err(|e| {
389            log_error!("FIDL transport error on StarnixVolumeProvider.Mount {:?}", e);
390            errno!(ENOENT)
391        })?
392        .map_err(|e| {
393            let error = from_status_like_fdio!(zx::Status::err_from_raw(e));
394            log_error!(error:?; "StarnixVolumeProvider.Mount failed");
395            error
396        })?;
397
398    crypt_service.set_uuid(guid);
399
400    let exposed_dir_proxy = exposed_dir_client_end.into_sync_proxy();
401
402    let root = syncio::directory_open_directory_async(
403        &exposed_dir_proxy,
404        "root",
405        fio::PERM_READABLE | fio::PERM_WRITABLE,
406    )
407    .map_err(|e| errno!(EIO, format!("Failed to open root: {e}")))?;
408
409    let rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
410
411    let (remotefs, root_node, info, node_id) =
412        RemoteFs::new(root.into_channel(), rights, "remotevol")?;
413
414    let use_remote_ids = remotefs.use_remote_ids();
415    let remotevol = RemoteVolume { remotefs, exposed_dir_proxy, crypt_service };
416    let fs =
417        FileSystem::new(kernel, CacheMode::Cached(kernel.fs_cache_config()), remotevol, options)?;
418
419    if use_remote_ids {
420        fs.create_root_with_info(node_id, root_node, info);
421    } else {
422        let root_ino = fs.allocate_ino();
423        fs.create_root_with_info(root_ino, root_node, info);
424    }
425
426    Ok(fs)
427}
428
429#[cfg(test)]
430mod test {
431    use super::*;
432    use crate::testing::spawn_kernel_and_run;
433    use crate::vfs::Namespace;
434    use crate::vfs::buffers::VecInputBuffer;
435    use fxfs_testing::TestFixture;
436    use starnix_uapi::device_id::DeviceId;
437    use starnix_uapi::file_mode::mode;
438    use starnix_uapi::open_flags::OpenFlags;
439
440    #[::fuchsia::test(threads = 2)]
441    async fn test_sync_flushes_open_file() {
442        let fixture = TestFixture::new().await;
443        let (server, client) = zx::Channel::create();
444        fixture.root().clone(server.into()).expect("clone failed");
445        let device = fixture.fs().device();
446
447        let crashed_device = spawn_kernel_and_run(async move |current_task| {
448            let (remotefs, root_node, info, node_id) =
449                RemoteFs::new(client, fio::PERM_READABLE | fio::PERM_WRITABLE, "remotevol")
450                    .expect("RemoteFs::new failed");
451            let remotevol = RemoteVolume {
452                remotefs,
453                exposed_dir_proxy: fio::DirectorySynchronousProxy::new(zx::Channel::create().0),
454                crypt_service: Arc::new(CryptService::new(&[0; 32], &[1; 32], None)),
455            };
456            let fs = FileSystem::new(
457                current_task.kernel(),
458                CacheMode::Uncached,
459                remotevol,
460                Default::default(),
461            )
462            .expect("FileSystem::new failed");
463            fs.create_root_with_info(node_id, root_node, info);
464            let ns = Namespace::new(fs.clone());
465            let file = ns
466                .root()
467                .create_node(&current_task, "file".into(), mode!(IFREG, 0o666), DeviceId::NONE)
468                .expect("create_node failed")
469                .open(&current_task, OpenFlags::RDWR)
470                .expect("open failed");
471            file.write(&current_task, &mut VecInputBuffer::new(b"hello")).expect("write failed");
472
473            // Sync without closing or fsyncing the file, then simulate a crash.
474            fs.sync(&current_task).expect("sync failed");
475            device.snapshot().expect("snapshot failed")
476        })
477        .await;
478        fixture.close().await;
479
480        let fixture = TestFixture::new_with_device(crashed_device).await;
481        assert_eq!(
482            fuchsia_fs::directory::read_file(fixture.root(), "file")
483                .await
484                .expect("read_file failed"),
485            b"hello"
486        );
487        fixture.close().await;
488    }
489}