blob: e1d820ad4a74ecbd5a58a87bce2e0794f044bb52 [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};
Victor Hsieh045f1e62021-08-03 12:04:34 -070034use authfs_aidl_interface::binder::{
35 self, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor, Strong,
36};
Alan Stokes3189af02021-09-30 17:51:19 +010037use binder_common::new_binder_exception;
Victor Hsieh045f1e62021-08-03 12:04:34 -070038
39const AUTHFS_BIN: &str = "/system/bin/authfs";
40const AUTHFS_SETUP_POLL_INTERVAL_MS: Duration = Duration::from_millis(50);
41const AUTHFS_SETUP_TIMEOUT_SEC: Duration = Duration::from_secs(10);
42const FUSE_SUPER_MAGIC: FsType = FsType(0x65735546);
43
44/// An `AuthFs` instance is supposed to be backed by an `authfs` process. When the lifetime of the
45/// instance is over, it should leave no trace on the system: the process should be terminated, the
46/// FUSE should be unmounted, and the mount directory should be deleted.
47pub struct AuthFs {
48 mountpoint: OsString,
49 process: SharedChild,
50}
51
52impl Interface for AuthFs {}
53
54impl IAuthFs for AuthFs {
55 fn openFile(
56 &self,
Victor Hsiehebb1d902021-08-06 13:00:18 -070057 remote_fd_name: i32,
Victor Hsieh045f1e62021-08-03 12:04:34 -070058 writable: bool,
59 ) -> binder::Result<ParcelFileDescriptor> {
60 let mut path = PathBuf::from(&self.mountpoint);
61 path.push(remote_fd_name.to_string());
62 let file = OpenOptions::new().read(true).write(writable).open(&path).map_err(|e| {
63 new_binder_exception(
64 ExceptionCode::SERVICE_SPECIFIC,
65 format!("failed to open {:?} on authfs: {}", &path, e),
66 )
67 })?;
68 Ok(ParcelFileDescriptor::new(file))
69 }
Victor Hsiehf9968692021-11-18 11:34:39 -080070
71 fn getMountPoint(&self) -> binder::Result<String> {
72 if let Some(s) = self.mountpoint.to_str() {
73 Ok(s.to_string())
74 } else {
75 Err(new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, "Bad string encoding"))
76 }
77 }
Victor Hsieh045f1e62021-08-03 12:04:34 -070078}
79
80impl AuthFs {
81 /// Mount an authfs at `mountpoint` with specified FD annotations.
82 pub fn mount_and_wait(
83 mountpoint: OsString,
84 config: &AuthFsConfig,
85 debuggable: bool,
86 ) -> Result<Strong<dyn IAuthFs>> {
87 let child = run_authfs(
88 &mountpoint,
89 &config.inputFdAnnotations,
90 &config.outputFdAnnotations,
Victor Hsieh015bcb52021-11-17 17:28:01 -080091 &config.inputDirFdAnnotations,
92 &config.outputDirFdAnnotations,
Victor Hsieh045f1e62021-08-03 12:04:34 -070093 debuggable,
94 )?;
Alan Stokese1b6e1c2021-10-01 12:44:49 +010095 wait_until_authfs_ready(&child, &mountpoint).map_err(|e| {
96 match child.wait() {
97 Ok(status) => debug!("Wait for authfs: {}", status),
98 Err(e) => warn!("Failed to wait for child: {}", e),
99 }
Victor Hsieh045f1e62021-08-03 12:04:34 -0700100 e
101 })?;
102
103 let authfs = AuthFs { mountpoint, process: child };
104 Ok(BnAuthFs::new_binder(authfs, BinderFeatures::default()))
105 }
106}
107
108impl Drop for AuthFs {
109 /// On drop, try to erase all the traces for this authfs mount.
110 fn drop(&mut self) {
111 debug!("Dropping AuthFs instance at mountpoint {:?}", &self.mountpoint);
112 if let Err(e) = self.process.kill() {
113 error!("Failed to kill authfs: {}", e);
114 }
115 match self.process.wait() {
116 Ok(status) => debug!("authfs exit code: {}", status),
117 Err(e) => warn!("Failed to wait for authfs: {}", e),
118 }
119 // The client may still hold the file descriptors that refer to this filesystem. Use
120 // MNT_DETACH to detach the mountpoint, and automatically unmount when there is no more
121 // reference.
122 if let Err(e) = umount2(self.mountpoint.as_os_str(), MntFlags::MNT_DETACH) {
123 error!("Failed to umount authfs at {:?}: {}", &self.mountpoint, e)
124 }
125
126 if let Err(e) = remove_dir(&self.mountpoint) {
127 error!("Failed to clean up mount directory {:?}: {}", &self.mountpoint, e)
128 }
129 }
130}
131
132fn run_authfs(
133 mountpoint: &OsStr,
Victor Hsieh015bcb52021-11-17 17:28:01 -0800134 in_file_fds: &[InputFdAnnotation],
135 out_file_fds: &[OutputFdAnnotation],
136 in_dir_fds: &[InputDirFdAnnotation],
137 out_dir_fds: &[OutputDirFdAnnotation],
Victor Hsieh045f1e62021-08-03 12:04:34 -0700138 debuggable: bool,
139) -> Result<SharedChild> {
140 let mut args = vec![mountpoint.to_owned(), OsString::from("--cid=2")];
Victor Hsieh8bb67b62021-08-04 12:10:58 -0700141 args.push(OsString::from("-o"));
142 args.push(OsString::from("fscontext=u:object_r:authfs_fuse:s0"));
Victor Hsieh015bcb52021-11-17 17:28:01 -0800143 for conf in in_file_fds {
Victor Hsieh045f1e62021-08-03 12:04:34 -0700144 // TODO(b/185178698): Many input files need to be signed and verified.
145 // or can we use debug cert for now, which is better than nothing?
146 args.push(OsString::from("--remote-ro-file-unverified"));
Victor Hsiehb3588ce2021-11-02 15:02:32 -0700147 args.push(OsString::from(conf.fd.to_string()));
Victor Hsieh045f1e62021-08-03 12:04:34 -0700148 }
Victor Hsieh015bcb52021-11-17 17:28:01 -0800149 for conf in out_file_fds {
Victor Hsieh045f1e62021-08-03 12:04:34 -0700150 args.push(OsString::from("--remote-new-rw-file"));
Victor Hsiehb3588ce2021-11-02 15:02:32 -0700151 args.push(OsString::from(conf.fd.to_string()));
Victor Hsieh045f1e62021-08-03 12:04:34 -0700152 }
Victor Hsieh015bcb52021-11-17 17:28:01 -0800153 for conf in in_dir_fds {
154 args.push(OsString::from("--remote-ro-dir"));
155 // TODO(206869687): Replace /dev/null with the real path when possible.
156 args.push(OsString::from(format!("{}:{}:{}", conf.fd, conf.manifestPath, conf.prefix)));
157 }
158 for conf in out_dir_fds {
159 args.push(OsString::from("--remote-new-rw-dir"));
160 args.push(OsString::from(conf.fd.to_string()));
161 }
Victor Hsieh045f1e62021-08-03 12:04:34 -0700162 if debuggable {
163 args.push(OsString::from("--debug"));
164 }
165
166 let mut command = Command::new(AUTHFS_BIN);
167 command.args(&args);
Victor Hsieh015bcb52021-11-17 17:28:01 -0800168 debug!("Spawn authfs: {:?}", command);
Victor Hsieh045f1e62021-08-03 12:04:34 -0700169 SharedChild::spawn(&mut command).context("Spawn authfs")
170}
171
Alan Stokese1b6e1c2021-10-01 12:44:49 +0100172fn wait_until_authfs_ready(child: &SharedChild, mountpoint: &OsStr) -> Result<()> {
Victor Hsieh045f1e62021-08-03 12:04:34 -0700173 let start_time = Instant::now();
174 loop {
175 if is_fuse(mountpoint)? {
176 break;
177 }
Alan Stokese1b6e1c2021-10-01 12:44:49 +0100178 if let Some(exit_status) = child.try_wait()? {
179 // If the child has exited, we will never become ready.
180 bail!("Child has exited: {}", exit_status);
181 }
Victor Hsieh045f1e62021-08-03 12:04:34 -0700182 if start_time.elapsed() > AUTHFS_SETUP_TIMEOUT_SEC {
Alan Stokese1b6e1c2021-10-01 12:44:49 +0100183 let _ = child.kill();
Victor Hsieh045f1e62021-08-03 12:04:34 -0700184 bail!("Time out mounting authfs");
185 }
186 sleep(AUTHFS_SETUP_POLL_INTERVAL_MS);
187 }
188 Ok(())
189}
190
191fn is_fuse(path: &OsStr) -> Result<bool> {
192 Ok(statfs(path)?.filesystem_type() == FUSE_SUPER_MAGIC)
193}