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, RemoteNode};
6use crate::task::dynamic_thread_spawner::SpawnRequestBuilder;
7use crate::task::{CurrentTask, LockedAndTask};
8use crate::vfs::{
9    CacheConfig, CacheMode, FileSystem, FileSystemHandle, FileSystemOps, FileSystemOptions,
10    FsNodeHandle, FsStr,
11};
12use fidl::endpoints::{DiscoverableProtocolMarker, SynchronousProxy, create_sync_proxy};
13use fidl_fuchsia_fshost::StarnixVolumeProviderMarker;
14use fidl_fuchsia_fxfs::CryptMarker;
15use fidl_fuchsia_io as fio;
16use starnix_crypt::CryptService;
17use starnix_logging::{log_error, log_info};
18use starnix_sync::{FileOpsCore, Locked, Unlocked};
19use starnix_uapi::errors::Errno;
20use starnix_uapi::{errno, from_status_like_fdio, statfs};
21use std::sync::Arc;
22use syncio::{Zxio, zxio_node_attr_has_t, zxio_node_attributes_t};
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 {
30    remotefs: RemoteFs,
31    exposed_dir_proxy: fio::DirectorySynchronousProxy,
32    crypt_service: Arc<CryptService>,
33}
34
35impl RemoteVolume {
36    pub fn remotefs(&self) -> &RemoteFs {
37        &self.remotefs
38    }
39}
40
41impl FileSystemOps for RemoteVolume {
42    fn statfs(
43        &self,
44        locked: &mut Locked<FileOpsCore>,
45        fs: &FileSystem,
46        current_task: &CurrentTask,
47    ) -> Result<statfs, Errno> {
48        self.remotefs.statfs(locked, fs, current_task)
49    }
50
51    fn name(&self) -> &'static FsStr {
52        "remotevol".into()
53    }
54
55    fn uses_external_node_ids(&self) -> bool {
56        self.remotefs.uses_external_node_ids()
57    }
58
59    fn rename(
60        &self,
61        locked: &mut Locked<FileOpsCore>,
62        fs: &FileSystem,
63        current_task: &CurrentTask,
64        old_parent: &FsNodeHandle,
65        old_name: &FsStr,
66        new_parent: &FsNodeHandle,
67        new_name: &FsStr,
68        renamed: &FsNodeHandle,
69        replaced: Option<&FsNodeHandle>,
70    ) -> Result<(), Errno> {
71        self.remotefs.rename(
72            locked,
73            fs,
74            current_task,
75            old_parent,
76            old_name,
77            new_parent,
78            new_name,
79            renamed,
80            replaced,
81        )
82    }
83
84    fn unmount(&self) {
85        let (proxy, server_end) = create_sync_proxy::<fidl_fuchsia_fs::AdminMarker>();
86        if let Err(e) = fdio::service_connect_at(
87            self.exposed_dir_proxy.as_channel(),
88            &format!("svc/{}", fidl_fuchsia_fs::AdminMarker::PROTOCOL_NAME),
89            server_end.into(),
90        ) {
91            log_error!(e:%; "StarnixVolumeProvider.Unmount failed to connect to fuchsia.fs.Admin");
92            return;
93        }
94
95        if let Err(e) = proxy.shutdown(zx::MonotonicInstant::INFINITE) {
96            log_error!(e:%; "StarnixVolumeProvider.Unmount failed at FIDL layer");
97        }
98    }
99
100    fn crypt_service(&self) -> Option<Arc<CryptService>> {
101        Some(self.crypt_service.clone())
102    }
103}
104
105// Key file
106// ========
107//
108// Version 1:
109//
110//   +------- 32 -------+------- 32 -------+
111//   |   metadata key   |     data key     |
112//   +------------------+------------------+
113//
114// Version 2:
115//
116//   +-2-+------- 32 -------+------- 32 -------+
117//   | V |   metadata key   |     data key     |
118//   +---+------------------+------------------+
119//
120// Version 2 includes a 16 bit version which indicates the version of the key file.  The key
121// identifiers used for version 2 key files will use the lblk32 algorithm for derivation which
122// differs from version 1, which uses a, deprecated, Fuchsia specific derivation.
123
124struct VolumeKeys {
125    metadata: [u8; 32],
126    data: [u8; 32],
127    use_lblk32_identifiers: bool,
128}
129
130impl VolumeKeys {
131    // `KEYS_SIZE` is the size of the two keys (the metadata key, and the data key) stored in the
132    // key file.
133    const KEYS_SIZE: usize = 64;
134
135    // Version 1 does not include a version.
136    const V1_FILE_SIZE: usize = Self::KEYS_SIZE;
137
138    // Includes 2 bytes for the version.
139    const FILE_SIZE: usize = 2 + Self::KEYS_SIZE;
140
141    const LATEST_VERSION: u16 = 2;
142
143    /// Returns (keys, did_create).
144    fn get_or_create(
145        data: &fio::DirectorySynchronousProxy,
146        key_path: &str,
147    ) -> Result<(Self, bool), Errno> {
148        if let Some(keys) = Self::get(data, key_path)? {
149            Ok((keys, false))
150        } else {
151            log_info!("Creating key file at {key_path}");
152            Ok((Self::create(data, key_path)?, true))
153        }
154    }
155
156    /// Returns None rather than an error if the key file does not exist or is corrupt,
157    /// but returns all other errors (e.g. if the connection to `data` is closed).
158    fn get(data: &fio::DirectorySynchronousProxy, key_path: &str) -> Result<Option<Self>, Errno> {
159        match syncio::directory_read_file(data, key_path, zx::MonotonicInstant::INFINITE) {
160            Ok(bytes) => {
161                if bytes.len() == Self::FILE_SIZE {
162                    // Version 2
163                    if u16::from_le_bytes(bytes[0..2].try_into().unwrap()) != Self::LATEST_VERSION {
164                        return Ok(None);
165                    }
166                    Ok(Some(Self {
167                        metadata: bytes[2..34].try_into().unwrap(),
168                        data: bytes[34..66].try_into().unwrap(),
169                        use_lblk32_identifiers: true,
170                    }))
171                } else if bytes.len() == Self::V1_FILE_SIZE {
172                    // Version 1
173                    Ok(Some(Self {
174                        metadata: bytes[..32].try_into().unwrap(),
175                        data: bytes[32..].try_into().unwrap(),
176                        use_lblk32_identifiers: false,
177                    }))
178                } else {
179                    Ok(None)
180                }
181            }
182            Err(zx::Status::NOT_FOUND) => Ok(None),
183            Err(status) => {
184                log_error!("Failed to read key file: {status:?}");
185                Err(from_status_like_fdio!(status))
186            }
187        }
188    }
189
190    /// Creates a new key file at the latest version, with new random metadata and data keys.
191    fn create(data: &fio::DirectorySynchronousProxy, key_path: &str) -> Result<Self, Errno> {
192        let mut bytes = [0; Self::FILE_SIZE];
193        bytes[..2].copy_from_slice(&Self::LATEST_VERSION.to_le_bytes());
194        zx::cprng_draw(&mut bytes[2..]);
195        let tmp_file = syncio::directory_create_tmp_file(
196            data,
197            fio::PERM_READABLE,
198            zx::MonotonicInstant::INFINITE,
199        )
200        .map_err(|e| {
201            let err = from_status_like_fdio!(e);
202            log_error!("Failed to create tmp file with error: {:?}", err);
203            err
204        })?;
205        tmp_file
206            .write(&bytes, zx::MonotonicInstant::INFINITE)
207            .map_err(|e| {
208                log_error!("FIDL transport error on File.Write {:?}", e);
209                errno!(ENOENT)
210            })?
211            .map_err(|e| {
212                let err = from_status_like_fdio!(zx::Status::from_raw(e));
213                log_error!("File.Write failed with {:?}", err);
214                err
215            })?;
216        tmp_file
217            .sync(zx::MonotonicInstant::INFINITE)
218            .map_err(|e| {
219                log_error!("FIDL transport error on File.Sync {:?}", e);
220                errno!(ENOENT)
221            })?
222            .map_err(|e| {
223                let err = from_status_like_fdio!(zx::Status::from_raw(e));
224                log_error!("File.Sync failed with {:?}", err);
225                err
226            })?;
227        let (status, token) = data.get_token(zx::MonotonicInstant::INFINITE).map_err(|e| {
228            log_error!("transport error on get_token for the data directory, error: {:?}", e);
229            errno!(ENOENT)
230        })?;
231        zx::Status::ok(status).map_err(|e| {
232            let err = from_status_like_fdio!(e);
233            log_error!("Failed to get_token for the data directory, error: {:?}", err);
234            err
235        })?;
236
237        tmp_file
238            .link_into(
239                zx::Event::from(token.ok_or_else(|| errno!(ENOENT))?),
240                key_path,
241                zx::MonotonicInstant::INFINITE,
242            )
243            .map_err(|e| {
244                log_error!("FIDL transport error on File.LinkInto {:?}", e);
245                errno!(EIO)
246            })?
247            .map_err(|e| {
248                let err = from_status_like_fdio!(zx::Status::from_raw(e));
249                log_error!("File.LinkInto failed with {:?}", err);
250                err
251            })?;
252        Ok(Self {
253            metadata: bytes[2..34].try_into().unwrap(),
254            data: bytes[34..].try_into().unwrap(),
255            use_lblk32_identifiers: true,
256        })
257    }
258}
259
260pub fn new_remote_vol(
261    locked: &mut Locked<Unlocked>,
262    current_task: &CurrentTask,
263    options: FileSystemOptions,
264) -> Result<FileSystemHandle, Errno> {
265    let kernel = current_task.kernel();
266    let volume_provider = current_task
267        .kernel()
268        .connect_to_protocol_at_container_svc::<StarnixVolumeProviderMarker>()
269        .map_err(|_| errno!(ENOENT))?
270        .into_sync_proxy();
271
272    let (crypt_client_end, crypt_proxy) = fidl::endpoints::create_endpoints::<CryptMarker>();
273
274    let data = match kernel.container_namespace.get_namespace_channel("/data") {
275        Ok(channel) => fio::DirectorySynchronousProxy::new(channel),
276        Err(err) => {
277            log_error!("Unable to find a channel for /data. Received error: {}", err);
278            return Err(errno!(ENOENT));
279        }
280    };
281
282    let (keys, created_key_file) = VolumeKeys::get_or_create(&data, KEY_FILE_PATH)?;
283
284    let crypt_service =
285        Arc::new(CryptService::new(&keys.metadata, &keys.data, keys.use_lblk32_identifiers, None));
286
287    let (exposed_dir_client_end, exposed_dir_server) =
288        fidl::endpoints::create_endpoints::<fio::DirectoryMarker>();
289
290    {
291        let crypt_service = Arc::clone(&crypt_service);
292        let closure = async move |_: LockedAndTask<'_>| {
293            if let Err(e) = crypt_service.handle_connection(crypt_proxy.into_stream()).await {
294                log_error!("Error while handling a Crypt request {e}");
295            }
296        };
297        let req = SpawnRequestBuilder::new()
298            .with_debug_name("remote-volume-crypt")
299            .with_role(CRYPT_THREAD_ROLE)
300            .with_async_closure(closure)
301            .build();
302        kernel.kthreads.spawner().spawn_from_request(req);
303    }
304
305    let mode = if created_key_file {
306        fidl_fuchsia_fshost::MountMode::AlwaysCreate
307    } else {
308        fidl_fuchsia_fshost::MountMode::MaybeCreate
309    };
310    let guid = volume_provider
311        .mount(crypt_client_end, mode, exposed_dir_server, zx::MonotonicInstant::INFINITE)
312        .map_err(|e| {
313            log_error!("FIDL transport error on StarnixVolumeProvider.Mount {:?}", e);
314            errno!(ENOENT)
315        })?
316        .map_err(|e| {
317            let error = from_status_like_fdio!(zx::Status::from_raw(e));
318            log_error!(error:?; "StarnixVolumeProvider.Mount failed");
319            error
320        })?;
321
322    crypt_service.set_uuid(guid);
323
324    let exposed_dir_proxy = exposed_dir_client_end.into_sync_proxy();
325
326    let root = syncio::directory_open_directory_async(
327        &exposed_dir_proxy,
328        "root",
329        fio::PERM_READABLE | fio::PERM_WRITABLE,
330    )
331    .map_err(|e| errno!(EIO, format!("Failed to open root: {e}")))?;
332
333    let rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
334
335    let (client_end, server_end) = zx::Channel::create();
336    let remotefs = RemoteFs::new(root.into_channel(), server_end)?;
337    let mut attrs = zxio_node_attributes_t {
338        has: zxio_node_attr_has_t { id: true, ..Default::default() },
339        ..Default::default()
340    };
341    let (remote_node, node_id) =
342        match Zxio::create_with_on_representation(client_end.into(), Some(&mut attrs)) {
343            Err(status) => return Err(from_status_like_fdio!(status)),
344            Ok(zxio) => (RemoteNode::new(zxio, rights), attrs.id),
345        };
346
347    let use_remote_ids = remotefs.use_remote_ids();
348    let remotevol = RemoteVolume { remotefs, exposed_dir_proxy, crypt_service };
349    let fs = FileSystem::new(
350        locked,
351        kernel,
352        CacheMode::Cached(CacheConfig::default()),
353        remotevol,
354        options,
355    )?;
356    if use_remote_ids {
357        fs.create_root(node_id, remote_node);
358    } else {
359        let root_ino = fs.allocate_ino();
360        fs.create_root(root_ino, remote_node);
361    }
362    Ok(fs)
363}