blob: 2fb7fdd980cf864fd92d4b667c725c53c39cd12c [file] [log] [blame]
Jooyung Han347d9f22021-05-28 00:05:14 +09001// Copyright 2021, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Microdroid Manager
16
Jooyung Hanf48ceb42021-06-01 18:00:04 +090017mod ioutil;
Jooyung Han74573482021-06-08 17:10:21 +090018mod metadata;
Jooyung Han347d9f22021-05-28 00:05:14 +090019
Jooyung Han19c1d6c2021-08-06 14:08:16 +090020use anyhow::{anyhow, bail, Context, Result};
21use apkverify::verify;
Inseob Kim1b95f2e2021-08-19 13:17:40 +090022use binder::unstable_api::{new_spibinder, AIBinder};
23use binder::{FromIBinder, Strong};
Andrew Scull6f3e5fe2021-07-02 12:38:21 +000024use log::{error, info, warn};
Jooyung Han634e2d72021-06-10 16:27:38 +090025use microdroid_payload_config::{Task, TaskType, VmPayloadConfig};
Joel Galenson482704c2021-07-29 15:53:53 -070026use rustutils::system_properties::PropertyWatcher;
Jiyong Park8611a6c2021-07-09 18:17:44 +090027use std::fs::{self, File};
28use std::os::unix::io::{FromRawFd, IntoRawFd};
Jooyung Hanf48ceb42021-06-01 18:00:04 +090029use std::path::Path;
Jiyong Park8611a6c2021-07-09 18:17:44 +090030use std::process::{Command, Stdio};
31use std::str;
Jooyung Han634e2d72021-06-10 16:27:38 +090032use std::time::Duration;
Jiyong Park8611a6c2021-07-09 18:17:44 +090033use vsock::VsockStream;
Jooyung Han634e2d72021-06-10 16:27:38 +090034
Inseob Kim1b95f2e2021-08-19 13:17:40 +090035use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::IVirtualMachineService;
36
Jooyung Han634e2d72021-06-10 16:27:38 +090037const WAIT_TIMEOUT: Duration = Duration::from_secs(10);
Jooyung Han19c1d6c2021-08-06 14:08:16 +090038const DM_MOUNTED_APK_PATH: &str = "/dev/block/mapper/microdroid-apk";
Jooyung Han347d9f22021-05-28 00:05:14 +090039
Inseob Kim1b95f2e2021-08-19 13:17:40 +090040/// The CID representing the host VM
41const VMADDR_CID_HOST: u32 = 2;
42
43/// Port number that virtualizationservice listens on connections from the guest VMs for the
44/// VirtualMachineService binder service
45/// Sync with virtualizationservice/src/aidl.rs
46const PORT_VM_BINDER_SERVICE: u32 = 5000;
47
48fn get_vms_rpc_binder() -> Result<Strong<dyn IVirtualMachineService>> {
49 // SAFETY: AIBinder returned by RpcClient has correct reference count, and the ownership can be
50 // safely taken by new_spibinder.
51 let ibinder = unsafe {
52 new_spibinder(binder_rpc_unstable_bindgen::RpcClient(
53 VMADDR_CID_HOST,
54 PORT_VM_BINDER_SERVICE,
55 ) as *mut AIBinder)
56 };
57 if let Some(ibinder) = ibinder {
58 <dyn IVirtualMachineService>::try_from(ibinder).context("Cannot connect to RPC service")
59 } else {
60 bail!("Invalid raw AIBinder")
61 }
62}
63
Jooyung Han634e2d72021-06-10 16:27:38 +090064fn main() -> Result<()> {
Jiyong Park79b88012021-06-25 13:06:25 +090065 kernlog::init()?;
Jooyung Han347d9f22021-05-28 00:05:14 +090066 info!("started.");
67
Jooyung Han74573482021-06-08 17:10:21 +090068 let metadata = metadata::load()?;
Jooyung Han19c1d6c2021-08-06 14:08:16 +090069
70 if let Err(err) = verify_payloads() {
Jooyung Hand4e035e2021-08-18 21:19:41 +090071 error!("failed to verify payload: {:#?}", err);
72 return Err(err);
Jooyung Han19c1d6c2021-08-06 14:08:16 +090073 }
74
Inseob Kim1b95f2e2021-08-19 13:17:40 +090075 // TODO(b/191845268): microdroid_manager should use this binder to communicate with the host
76 if let Err(err) = get_vms_rpc_binder() {
77 error!("cannot connect to VirtualMachineService: {}", err);
78 }
79
Jooyung Han74573482021-06-08 17:10:21 +090080 if !metadata.payload_config_path.is_empty() {
Jooyung Han634e2d72021-06-10 16:27:38 +090081 let config = load_config(Path::new(&metadata.payload_config_path))?;
82
Andrew Scull6f3e5fe2021-07-02 12:38:21 +000083 let fake_secret = "This is a placeholder for a value that is derived from the images that are loaded in the VM.";
Joel Galenson482704c2021-07-29 15:53:53 -070084 if let Err(err) = rustutils::system_properties::write("ro.vmsecret.keymint", fake_secret) {
Andrew Scull6f3e5fe2021-07-02 12:38:21 +000085 warn!("failed to set ro.vmsecret.keymint: {}", err);
86 }
87
Jooyung Han634e2d72021-06-10 16:27:38 +090088 // TODO(jooyung): wait until sys.boot_completed?
Jooyung Han347d9f22021-05-28 00:05:14 +090089 if let Some(main_task) = &config.task {
Jiyong Park8611a6c2021-07-09 18:17:44 +090090 exec_task(main_task).map_err(|e| {
91 error!("failed to execute task: {}", e);
92 e
93 })?;
Jooyung Han347d9f22021-05-28 00:05:14 +090094 }
95 }
96
97 Ok(())
98}
99
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900100// TODO(jooyung): v2/v3 full verification can be slow. Consider multithreading.
101fn verify_payloads() -> Result<()> {
102 // We don't verify APEXes since apexd does.
103
104 // should wait APK to be dm-verity mounted by apkdmverity
105 ioutil::wait_for_file(DM_MOUNTED_APK_PATH, WAIT_TIMEOUT)?;
106 verify(DM_MOUNTED_APK_PATH).context(format!("failed to verify {}", DM_MOUNTED_APK_PATH))?;
107
108 info!("payload verification succeeded.");
109 // TODO(jooyung): collect public keys and store them in instance.img
110 Ok(())
111}
112
Jooyung Han634e2d72021-06-10 16:27:38 +0900113fn load_config(path: &Path) -> Result<VmPayloadConfig> {
114 info!("loading config from {:?}...", path);
115 let file = ioutil::wait_for_file(path, WAIT_TIMEOUT)?;
116 Ok(serde_json::from_reader(file)?)
117}
118
Jiyong Park8611a6c2021-07-09 18:17:44 +0900119/// Executes the given task. Stdout of the task is piped into the vsock stream to the
120/// virtualizationservice in the host side.
Jooyung Han634e2d72021-06-10 16:27:38 +0900121fn exec_task(task: &Task) -> Result<()> {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900122 const VMADDR_CID_HOST: u32 = 2;
123 const PORT_VIRT_SVC: u32 = 3000;
124 let stdout = match VsockStream::connect_with_cid_port(VMADDR_CID_HOST, PORT_VIRT_SVC) {
125 Ok(stream) => {
126 // SAFETY: the ownership of the underlying file descriptor is transferred from stream
127 // to the file object, and then into the Command object. When the command is finished,
128 // the file descriptor is closed.
129 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
130 Stdio::from(f)
Jiyong Park038b73e2021-06-16 01:57:02 +0900131 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900132 Err(e) => {
133 error!("failed to connect to virtualization service: {}", e);
134 // Don't fail hard here. Even if we failed to connect to the virtualizationservice,
135 // we keep executing the task. This can happen if the owner of the VM doesn't register
136 // callback to accept the stream. Use /dev/null as the stdout so that the task can
137 // make progress without waiting for someone to consume the output.
138 Stdio::null()
139 }
140 };
141 info!("executing main task {:?}...", task);
142 // TODO(jiyong): consider piping the stream into stdio (and probably stderr) as well.
143 let mut child = build_command(task)?.stdout(stdout).spawn()?;
144 match child.wait()?.code() {
145 Some(0) => {
146 info!("task successfully finished");
147 Ok(())
148 }
149 Some(code) => bail!("task exited with exit code: {}", code),
150 None => bail!("task terminated by signal"),
Jiyong Park038b73e2021-06-16 01:57:02 +0900151 }
Jooyung Han347d9f22021-05-28 00:05:14 +0900152}
Jooyung Han634e2d72021-06-10 16:27:38 +0900153
154fn build_command(task: &Task) -> Result<Command> {
155 Ok(match task.type_ {
156 TaskType::Executable => {
157 let mut command = Command::new(&task.command);
158 command.args(&task.args);
159 command
160 }
161 TaskType::MicrodroidLauncher => {
162 let mut command = Command::new("/system/bin/microdroid_launcher");
163 command.arg(find_library_path(&task.command)?).args(&task.args);
164 command
165 }
166 })
167}
168
169fn find_library_path(name: &str) -> Result<String> {
170 let mut watcher = PropertyWatcher::new("ro.product.cpu.abilist")?;
171 let value = watcher.read(|_name, value| Ok(value.trim().to_string()))?;
172 let abi = value.split(',').next().ok_or_else(|| anyhow!("no abilist"))?;
173 let path = format!("/mnt/apk/lib/{}/{}", abi, name);
174
175 let metadata = fs::metadata(&path)?;
176 if !metadata.is_file() {
177 bail!("{} is not a file", &path);
178 }
179
180 Ok(path)
181}