blob: 1b0574994b69ce9b6204f14988fb4d1b0a454d73 [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 Hsieh045f1e62021-08-03 12:04:34 -070029use authfs_aidl_interface::aidl::com::android::virt::fs::IAuthFs::{BnAuthFs, IAuthFs};
30use authfs_aidl_interface::aidl::com::android::virt::fs::{
31 AuthFsConfig::AuthFsConfig, InputFdAnnotation::InputFdAnnotation,
32 OutputFdAnnotation::OutputFdAnnotation,
33};
34use 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 }
70}
71
72impl AuthFs {
73 /// Mount an authfs at `mountpoint` with specified FD annotations.
74 pub fn mount_and_wait(
75 mountpoint: OsString,
76 config: &AuthFsConfig,
77 debuggable: bool,
78 ) -> Result<Strong<dyn IAuthFs>> {
79 let child = run_authfs(
80 &mountpoint,
81 &config.inputFdAnnotations,
82 &config.outputFdAnnotations,
83 debuggable,
84 )?;
Alan Stokese1b6e1c2021-10-01 12:44:49 +010085 wait_until_authfs_ready(&child, &mountpoint).map_err(|e| {
86 match child.wait() {
87 Ok(status) => debug!("Wait for authfs: {}", status),
88 Err(e) => warn!("Failed to wait for child: {}", e),
89 }
Victor Hsieh045f1e62021-08-03 12:04:34 -070090 e
91 })?;
92
93 let authfs = AuthFs { mountpoint, process: child };
94 Ok(BnAuthFs::new_binder(authfs, BinderFeatures::default()))
95 }
96}
97
98impl Drop for AuthFs {
99 /// On drop, try to erase all the traces for this authfs mount.
100 fn drop(&mut self) {
101 debug!("Dropping AuthFs instance at mountpoint {:?}", &self.mountpoint);
102 if let Err(e) = self.process.kill() {
103 error!("Failed to kill authfs: {}", e);
104 }
105 match self.process.wait() {
106 Ok(status) => debug!("authfs exit code: {}", status),
107 Err(e) => warn!("Failed to wait for authfs: {}", e),
108 }
109 // The client may still hold the file descriptors that refer to this filesystem. Use
110 // MNT_DETACH to detach the mountpoint, and automatically unmount when there is no more
111 // reference.
112 if let Err(e) = umount2(self.mountpoint.as_os_str(), MntFlags::MNT_DETACH) {
113 error!("Failed to umount authfs at {:?}: {}", &self.mountpoint, e)
114 }
115
116 if let Err(e) = remove_dir(&self.mountpoint) {
117 error!("Failed to clean up mount directory {:?}: {}", &self.mountpoint, e)
118 }
119 }
120}
121
122fn run_authfs(
123 mountpoint: &OsStr,
124 in_fds: &[InputFdAnnotation],
125 out_fds: &[OutputFdAnnotation],
126 debuggable: bool,
127) -> Result<SharedChild> {
128 let mut args = vec![mountpoint.to_owned(), OsString::from("--cid=2")];
Victor Hsieh8bb67b62021-08-04 12:10:58 -0700129 args.push(OsString::from("-o"));
130 args.push(OsString::from("fscontext=u:object_r:authfs_fuse:s0"));
Victor Hsieh045f1e62021-08-03 12:04:34 -0700131 for conf in in_fds {
132 // TODO(b/185178698): Many input files need to be signed and verified.
133 // or can we use debug cert for now, which is better than nothing?
134 args.push(OsString::from("--remote-ro-file-unverified"));
Victor Hsiehb3588ce2021-11-02 15:02:32 -0700135 args.push(OsString::from(conf.fd.to_string()));
Victor Hsieh045f1e62021-08-03 12:04:34 -0700136 }
137 for conf in out_fds {
138 args.push(OsString::from("--remote-new-rw-file"));
Victor Hsiehb3588ce2021-11-02 15:02:32 -0700139 args.push(OsString::from(conf.fd.to_string()));
Victor Hsieh045f1e62021-08-03 12:04:34 -0700140 }
141 if debuggable {
142 args.push(OsString::from("--debug"));
143 }
144
145 let mut command = Command::new(AUTHFS_BIN);
146 command.args(&args);
147 SharedChild::spawn(&mut command).context("Spawn authfs")
148}
149
Alan Stokese1b6e1c2021-10-01 12:44:49 +0100150fn wait_until_authfs_ready(child: &SharedChild, mountpoint: &OsStr) -> Result<()> {
Victor Hsieh045f1e62021-08-03 12:04:34 -0700151 let start_time = Instant::now();
152 loop {
153 if is_fuse(mountpoint)? {
154 break;
155 }
Alan Stokese1b6e1c2021-10-01 12:44:49 +0100156 if let Some(exit_status) = child.try_wait()? {
157 // If the child has exited, we will never become ready.
158 bail!("Child has exited: {}", exit_status);
159 }
Victor Hsieh045f1e62021-08-03 12:04:34 -0700160 if start_time.elapsed() > AUTHFS_SETUP_TIMEOUT_SEC {
Alan Stokese1b6e1c2021-10-01 12:44:49 +0100161 let _ = child.kill();
Victor Hsieh045f1e62021-08-03 12:04:34 -0700162 bail!("Time out mounting authfs");
163 }
164 sleep(AUTHFS_SETUP_POLL_INTERVAL_MS);
165 }
166 Ok(())
167}
168
169fn is_fuse(path: &OsStr) -> Result<bool> {
170 Ok(statfs(path)?.filesystem_type() == FUSE_SUPER_MAGIC)
171}