blob: cfd57667e03d21912725e749238106c8dffa699c [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 )?;
Alan Stokese1b6e1c2021-10-01 12:44:49 +010092 wait_until_authfs_ready(&child, &mountpoint).map_err(|e| {
93 match child.wait() {
94 Ok(status) => debug!("Wait for authfs: {}", status),
95 Err(e) => warn!("Failed to wait for child: {}", e),
96 }
Victor Hsieh045f1e62021-08-03 12:04:34 -070097 e
98 })?;
99
100 let authfs = AuthFs { mountpoint, process: child };
101 Ok(BnAuthFs::new_binder(authfs, BinderFeatures::default()))
102 }
103}
104
105impl Drop for AuthFs {
106 /// On drop, try to erase all the traces for this authfs mount.
107 fn drop(&mut self) {
108 debug!("Dropping AuthFs instance at mountpoint {:?}", &self.mountpoint);
109 if let Err(e) = self.process.kill() {
110 error!("Failed to kill authfs: {}", e);
111 }
112 match self.process.wait() {
113 Ok(status) => debug!("authfs exit code: {}", status),
114 Err(e) => warn!("Failed to wait for authfs: {}", e),
115 }
116 // The client may still hold the file descriptors that refer to this filesystem. Use
117 // MNT_DETACH to detach the mountpoint, and automatically unmount when there is no more
118 // reference.
119 if let Err(e) = umount2(self.mountpoint.as_os_str(), MntFlags::MNT_DETACH) {
120 error!("Failed to umount authfs at {:?}: {}", &self.mountpoint, e)
121 }
122
123 if let Err(e) = remove_dir(&self.mountpoint) {
124 error!("Failed to clean up mount directory {:?}: {}", &self.mountpoint, e)
125 }
126 }
127}
128
129fn run_authfs(
130 mountpoint: &OsStr,
Victor Hsieh015bcb52021-11-17 17:28:01 -0800131 in_file_fds: &[InputFdAnnotation],
132 out_file_fds: &[OutputFdAnnotation],
133 in_dir_fds: &[InputDirFdAnnotation],
134 out_dir_fds: &[OutputDirFdAnnotation],
Victor Hsieh045f1e62021-08-03 12:04:34 -0700135 debuggable: bool,
136) -> Result<SharedChild> {
137 let mut args = vec![mountpoint.to_owned(), OsString::from("--cid=2")];
Victor Hsieh8bb67b62021-08-04 12:10:58 -0700138 args.push(OsString::from("-o"));
139 args.push(OsString::from("fscontext=u:object_r:authfs_fuse:s0"));
Victor Hsieh015bcb52021-11-17 17:28:01 -0800140 for conf in in_file_fds {
Victor Hsieh045f1e62021-08-03 12:04:34 -0700141 // TODO(b/185178698): Many input files need to be signed and verified.
142 // or can we use debug cert for now, which is better than nothing?
143 args.push(OsString::from("--remote-ro-file-unverified"));
Victor Hsiehb3588ce2021-11-02 15:02:32 -0700144 args.push(OsString::from(conf.fd.to_string()));
Victor Hsieh045f1e62021-08-03 12:04:34 -0700145 }
Victor Hsieh015bcb52021-11-17 17:28:01 -0800146 for conf in out_file_fds {
Victor Hsieh045f1e62021-08-03 12:04:34 -0700147 args.push(OsString::from("--remote-new-rw-file"));
Victor Hsiehb3588ce2021-11-02 15:02:32 -0700148 args.push(OsString::from(conf.fd.to_string()));
Victor Hsieh045f1e62021-08-03 12:04:34 -0700149 }
Victor Hsieh015bcb52021-11-17 17:28:01 -0800150 for conf in in_dir_fds {
151 args.push(OsString::from("--remote-ro-dir"));
Victor Hsieh015bcb52021-11-17 17:28:01 -0800152 args.push(OsString::from(format!("{}:{}:{}", conf.fd, conf.manifestPath, conf.prefix)));
153 }
154 for conf in out_dir_fds {
155 args.push(OsString::from("--remote-new-rw-dir"));
156 args.push(OsString::from(conf.fd.to_string()));
157 }
Victor Hsieh045f1e62021-08-03 12:04:34 -0700158 if debuggable {
159 args.push(OsString::from("--debug"));
160 }
161
162 let mut command = Command::new(AUTHFS_BIN);
163 command.args(&args);
Victor Hsieh015bcb52021-11-17 17:28:01 -0800164 debug!("Spawn authfs: {:?}", command);
Victor Hsieh045f1e62021-08-03 12:04:34 -0700165 SharedChild::spawn(&mut command).context("Spawn authfs")
166}
167
Alan Stokese1b6e1c2021-10-01 12:44:49 +0100168fn wait_until_authfs_ready(child: &SharedChild, mountpoint: &OsStr) -> Result<()> {
Victor Hsieh045f1e62021-08-03 12:04:34 -0700169 let start_time = Instant::now();
170 loop {
171 if is_fuse(mountpoint)? {
172 break;
173 }
Alan Stokese1b6e1c2021-10-01 12:44:49 +0100174 if let Some(exit_status) = child.try_wait()? {
175 // If the child has exited, we will never become ready.
176 bail!("Child has exited: {}", exit_status);
177 }
Victor Hsieh045f1e62021-08-03 12:04:34 -0700178 if start_time.elapsed() > AUTHFS_SETUP_TIMEOUT_SEC {
Dan Albert04e5dbd2023-05-08 22:49:40 +0000179 let _ignored = child.kill();
Victor Hsieh045f1e62021-08-03 12:04:34 -0700180 bail!("Time out mounting authfs");
181 }
182 sleep(AUTHFS_SETUP_POLL_INTERVAL_MS);
183 }
184 Ok(())
185}
186
187fn is_fuse(path: &OsStr) -> Result<bool> {
188 Ok(statfs(path)?.filesystem_type() == FUSE_SUPER_MAGIC)
189}