blob: f2638c2f746c7b1f854657afa497c0d02b0fcb4e [file] [log] [blame]
Victor Hsieh045f1e62021-08-03 12:04:34 -07001/*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use anyhow::{bail, Context, Result};
18use log::{debug, error, warn};
19use nix::mount::{umount2, MntFlags};
20use nix::sys::statfs::{statfs, FsType};
21use shared_child::SharedChild;
22use std::ffi::{OsStr, OsString};
23use std::fs::{remove_dir, OpenOptions};
24use std::path::PathBuf;
25use std::process::Command;
26use std::thread::sleep;
27use std::time::{Duration, Instant};
28
Victor Hsieh015bcb52021-11-17 17:28:01 -080029use authfs_aidl_interface::aidl::com::android::virt::fs::AuthFsConfig::{
30 AuthFsConfig, InputDirFdAnnotation::InputDirFdAnnotation, InputFdAnnotation::InputFdAnnotation,
31 OutputDirFdAnnotation::OutputDirFdAnnotation, OutputFdAnnotation::OutputFdAnnotation,
Victor Hsieh045f1e62021-08-03 12:04:34 -070032};
Victor Hsieh015bcb52021-11-17 17:28:01 -080033use authfs_aidl_interface::aidl::com::android::virt::fs::IAuthFs::{BnAuthFs, IAuthFs};
Alan Stokes0e82b502022-08-08 14:44:48 +010034use binder::{self, BinderFeatures, Interface, ParcelFileDescriptor, Status, Strong};
Victor Hsieh045f1e62021-08-03 12:04:34 -070035
36const AUTHFS_BIN: &str = "/system/bin/authfs";
37const AUTHFS_SETUP_POLL_INTERVAL_MS: Duration = Duration::from_millis(50);
38const AUTHFS_SETUP_TIMEOUT_SEC: Duration = Duration::from_secs(10);
39const FUSE_SUPER_MAGIC: FsType = FsType(0x65735546);
40
41/// An `AuthFs` instance is supposed to be backed by an `authfs` process. When the lifetime of the
42/// instance is over, it should leave no trace on the system: the process should be terminated, the
43/// FUSE should be unmounted, and the mount directory should be deleted.
44pub struct AuthFs {
45 mountpoint: OsString,
46 process: SharedChild,
47}
48
49impl Interface for AuthFs {}
50
51impl IAuthFs for AuthFs {
52 fn openFile(
53 &self,
Victor Hsiehebb1d902021-08-06 13:00:18 -070054 remote_fd_name: i32,
Victor Hsieh045f1e62021-08-03 12:04:34 -070055 writable: bool,
56 ) -> binder::Result<ParcelFileDescriptor> {
57 let mut path = PathBuf::from(&self.mountpoint);
58 path.push(remote_fd_name.to_string());
59 let file = OpenOptions::new().read(true).write(writable).open(&path).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +000060 Status::new_service_specific_error_str(
61 -1,
62 Some(format!("failed to open {:?} on authfs: {}", &path, e)),
Victor Hsieh045f1e62021-08-03 12:04:34 -070063 )
64 })?;
65 Ok(ParcelFileDescriptor::new(file))
66 }
Victor Hsiehf9968692021-11-18 11:34:39 -080067
68 fn getMountPoint(&self) -> binder::Result<String> {
69 if let Some(s) = self.mountpoint.to_str() {
70 Ok(s.to_string())
71 } else {
Andrew Walbrandcf9d582022-08-03 11:25:24 +000072 Err(Status::new_service_specific_error_str(-1, Some("Bad string encoding")))
Victor Hsiehf9968692021-11-18 11:34:39 -080073 }
74 }
Victor Hsieh045f1e62021-08-03 12:04:34 -070075}
76
77impl AuthFs {
78 /// Mount an authfs at `mountpoint` with specified FD annotations.
79 pub fn mount_and_wait(
80 mountpoint: OsString,
81 config: &AuthFsConfig,
82 debuggable: bool,
83 ) -> Result<Strong<dyn IAuthFs>> {
84 let child = run_authfs(
85 &mountpoint,
86 &config.inputFdAnnotations,
87 &config.outputFdAnnotations,
Victor Hsieh015bcb52021-11-17 17:28:01 -080088 &config.inputDirFdAnnotations,
89 &config.outputDirFdAnnotations,
Victor Hsieh045f1e62021-08-03 12:04:34 -070090 debuggable,
91 )?;
Chris Wailesa7ca8fa2024-09-05 14:49:10 -070092 wait_until_authfs_ready(&child, &mountpoint).inspect_err(|_| match child.wait() {
93 Ok(status) => debug!("Wait for authfs: {}", status),
94 Err(e) => warn!("Failed to wait for child: {}", e),
Victor Hsieh045f1e62021-08-03 12:04:34 -070095 })?;
96
97 let authfs = AuthFs { mountpoint, process: child };
98 Ok(BnAuthFs::new_binder(authfs, BinderFeatures::default()))
99 }
100}
101
102impl Drop for AuthFs {
103 /// On drop, try to erase all the traces for this authfs mount.
104 fn drop(&mut self) {
105 debug!("Dropping AuthFs instance at mountpoint {:?}", &self.mountpoint);
106 if let Err(e) = self.process.kill() {
107 error!("Failed to kill authfs: {}", e);
108 }
109 match self.process.wait() {
110 Ok(status) => debug!("authfs exit code: {}", status),
111 Err(e) => warn!("Failed to wait for authfs: {}", e),
112 }
113 // The client may still hold the file descriptors that refer to this filesystem. Use
114 // MNT_DETACH to detach the mountpoint, and automatically unmount when there is no more
115 // reference.
116 if let Err(e) = umount2(self.mountpoint.as_os_str(), MntFlags::MNT_DETACH) {
117 error!("Failed to umount authfs at {:?}: {}", &self.mountpoint, e)
118 }
119
120 if let Err(e) = remove_dir(&self.mountpoint) {
121 error!("Failed to clean up mount directory {:?}: {}", &self.mountpoint, e)
122 }
123 }
124}
125
126fn run_authfs(
127 mountpoint: &OsStr,
Victor Hsieh015bcb52021-11-17 17:28:01 -0800128 in_file_fds: &[InputFdAnnotation],
129 out_file_fds: &[OutputFdAnnotation],
130 in_dir_fds: &[InputDirFdAnnotation],
131 out_dir_fds: &[OutputDirFdAnnotation],
Victor Hsieh045f1e62021-08-03 12:04:34 -0700132 debuggable: bool,
133) -> Result<SharedChild> {
134 let mut args = vec![mountpoint.to_owned(), OsString::from("--cid=2")];
Victor Hsieh8bb67b62021-08-04 12:10:58 -0700135 args.push(OsString::from("-o"));
136 args.push(OsString::from("fscontext=u:object_r:authfs_fuse:s0"));
Victor Hsieh015bcb52021-11-17 17:28:01 -0800137 for conf in in_file_fds {
Victor Hsieh045f1e62021-08-03 12:04:34 -0700138 // TODO(b/185178698): Many input files need to be signed and verified.
139 // or can we use debug cert for now, which is better than nothing?
140 args.push(OsString::from("--remote-ro-file-unverified"));
Victor Hsiehb3588ce2021-11-02 15:02:32 -0700141 args.push(OsString::from(conf.fd.to_string()));
Victor Hsieh045f1e62021-08-03 12:04:34 -0700142 }
Victor Hsieh015bcb52021-11-17 17:28:01 -0800143 for conf in out_file_fds {
Victor Hsieh045f1e62021-08-03 12:04:34 -0700144 args.push(OsString::from("--remote-new-rw-file"));
Victor Hsiehb3588ce2021-11-02 15:02:32 -0700145 args.push(OsString::from(conf.fd.to_string()));
Victor Hsieh045f1e62021-08-03 12:04:34 -0700146 }
Victor Hsieh015bcb52021-11-17 17:28:01 -0800147 for conf in in_dir_fds {
148 args.push(OsString::from("--remote-ro-dir"));
Victor Hsieh015bcb52021-11-17 17:28:01 -0800149 args.push(OsString::from(format!("{}:{}:{}", conf.fd, conf.manifestPath, conf.prefix)));
150 }
151 for conf in out_dir_fds {
152 args.push(OsString::from("--remote-new-rw-dir"));
153 args.push(OsString::from(conf.fd.to_string()));
154 }
Victor Hsieh045f1e62021-08-03 12:04:34 -0700155 if debuggable {
156 args.push(OsString::from("--debug"));
157 }
158
159 let mut command = Command::new(AUTHFS_BIN);
160 command.args(&args);
Victor Hsieh015bcb52021-11-17 17:28:01 -0800161 debug!("Spawn authfs: {:?}", command);
Victor Hsieh045f1e62021-08-03 12:04:34 -0700162 SharedChild::spawn(&mut command).context("Spawn authfs")
163}
164
Alan Stokese1b6e1c2021-10-01 12:44:49 +0100165fn wait_until_authfs_ready(child: &SharedChild, mountpoint: &OsStr) -> Result<()> {
Victor Hsieh045f1e62021-08-03 12:04:34 -0700166 let start_time = Instant::now();
167 loop {
168 if is_fuse(mountpoint)? {
169 break;
170 }
Alan Stokese1b6e1c2021-10-01 12:44:49 +0100171 if let Some(exit_status) = child.try_wait()? {
172 // If the child has exited, we will never become ready.
173 bail!("Child has exited: {}", exit_status);
174 }
Victor Hsieh045f1e62021-08-03 12:04:34 -0700175 if start_time.elapsed() > AUTHFS_SETUP_TIMEOUT_SEC {
Dan Albert04e5dbd2023-05-08 22:49:40 +0000176 let _ignored = child.kill();
Victor Hsieh045f1e62021-08-03 12:04:34 -0700177 bail!("Time out mounting authfs");
178 }
179 sleep(AUTHFS_SETUP_POLL_INTERVAL_MS);
180 }
181 Ok(())
182}
183
184fn is_fuse(path: &OsStr) -> Result<bool> {
185 Ok(statfs(path)?.filesystem_type() == FUSE_SUPER_MAGIC)
186}