blob: d7e256ba7d038e5be1f30ec8696b4410cd45e49f [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;
Andrew Scull6f3e5fe2021-07-02 12:38:21 +000022use log::{error, info, warn};
Jooyung Han634e2d72021-06-10 16:27:38 +090023use microdroid_payload_config::{Task, TaskType, VmPayloadConfig};
Joel Galenson482704c2021-07-29 15:53:53 -070024use rustutils::system_properties::PropertyWatcher;
Jiyong Park8611a6c2021-07-09 18:17:44 +090025use std::fs::{self, File};
26use std::os::unix::io::{FromRawFd, IntoRawFd};
Jooyung Hanf48ceb42021-06-01 18:00:04 +090027use std::path::Path;
Jiyong Park8611a6c2021-07-09 18:17:44 +090028use std::process::{Command, Stdio};
29use std::str;
Jooyung Han634e2d72021-06-10 16:27:38 +090030use std::time::Duration;
Jiyong Park8611a6c2021-07-09 18:17:44 +090031use vsock::VsockStream;
Jooyung Han634e2d72021-06-10 16:27:38 +090032
33const WAIT_TIMEOUT: Duration = Duration::from_secs(10);
Jooyung Han19c1d6c2021-08-06 14:08:16 +090034const DM_MOUNTED_APK_PATH: &str = "/dev/block/mapper/microdroid-apk";
Jooyung Han347d9f22021-05-28 00:05:14 +090035
Jooyung Han634e2d72021-06-10 16:27:38 +090036fn main() -> Result<()> {
Jiyong Park79b88012021-06-25 13:06:25 +090037 kernlog::init()?;
Jooyung Han347d9f22021-05-28 00:05:14 +090038 info!("started.");
39
Jooyung Han74573482021-06-08 17:10:21 +090040 let metadata = metadata::load()?;
Jooyung Han19c1d6c2021-08-06 14:08:16 +090041
42 if let Err(err) = verify_payloads() {
Jooyung Hand4e035e2021-08-18 21:19:41 +090043 error!("failed to verify payload: {:#?}", err);
44 return Err(err);
Jooyung Han19c1d6c2021-08-06 14:08:16 +090045 }
46
Jooyung Han74573482021-06-08 17:10:21 +090047 if !metadata.payload_config_path.is_empty() {
Jooyung Han634e2d72021-06-10 16:27:38 +090048 let config = load_config(Path::new(&metadata.payload_config_path))?;
49
Andrew Scull6f3e5fe2021-07-02 12:38:21 +000050 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 -070051 if let Err(err) = rustutils::system_properties::write("ro.vmsecret.keymint", fake_secret) {
Andrew Scull6f3e5fe2021-07-02 12:38:21 +000052 warn!("failed to set ro.vmsecret.keymint: {}", err);
53 }
54
Jooyung Han634e2d72021-06-10 16:27:38 +090055 // TODO(jooyung): wait until sys.boot_completed?
Jooyung Han347d9f22021-05-28 00:05:14 +090056 if let Some(main_task) = &config.task {
Jiyong Park8611a6c2021-07-09 18:17:44 +090057 exec_task(main_task).map_err(|e| {
58 error!("failed to execute task: {}", e);
59 e
60 })?;
Jooyung Han347d9f22021-05-28 00:05:14 +090061 }
62 }
63
64 Ok(())
65}
66
Jooyung Han19c1d6c2021-08-06 14:08:16 +090067// TODO(jooyung): v2/v3 full verification can be slow. Consider multithreading.
68fn verify_payloads() -> Result<()> {
69 // We don't verify APEXes since apexd does.
70
71 // should wait APK to be dm-verity mounted by apkdmverity
72 ioutil::wait_for_file(DM_MOUNTED_APK_PATH, WAIT_TIMEOUT)?;
73 verify(DM_MOUNTED_APK_PATH).context(format!("failed to verify {}", DM_MOUNTED_APK_PATH))?;
74
75 info!("payload verification succeeded.");
76 // TODO(jooyung): collect public keys and store them in instance.img
77 Ok(())
78}
79
Jooyung Han634e2d72021-06-10 16:27:38 +090080fn load_config(path: &Path) -> Result<VmPayloadConfig> {
81 info!("loading config from {:?}...", path);
82 let file = ioutil::wait_for_file(path, WAIT_TIMEOUT)?;
83 Ok(serde_json::from_reader(file)?)
84}
85
Jiyong Park8611a6c2021-07-09 18:17:44 +090086/// Executes the given task. Stdout of the task is piped into the vsock stream to the
87/// virtualizationservice in the host side.
Jooyung Han634e2d72021-06-10 16:27:38 +090088fn exec_task(task: &Task) -> Result<()> {
Jiyong Park8611a6c2021-07-09 18:17:44 +090089 const VMADDR_CID_HOST: u32 = 2;
90 const PORT_VIRT_SVC: u32 = 3000;
91 let stdout = match VsockStream::connect_with_cid_port(VMADDR_CID_HOST, PORT_VIRT_SVC) {
92 Ok(stream) => {
93 // SAFETY: the ownership of the underlying file descriptor is transferred from stream
94 // to the file object, and then into the Command object. When the command is finished,
95 // the file descriptor is closed.
96 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
97 Stdio::from(f)
Jiyong Park038b73e2021-06-16 01:57:02 +090098 }
Jiyong Park8611a6c2021-07-09 18:17:44 +090099 Err(e) => {
100 error!("failed to connect to virtualization service: {}", e);
101 // Don't fail hard here. Even if we failed to connect to the virtualizationservice,
102 // we keep executing the task. This can happen if the owner of the VM doesn't register
103 // callback to accept the stream. Use /dev/null as the stdout so that the task can
104 // make progress without waiting for someone to consume the output.
105 Stdio::null()
106 }
107 };
108 info!("executing main task {:?}...", task);
109 // TODO(jiyong): consider piping the stream into stdio (and probably stderr) as well.
110 let mut child = build_command(task)?.stdout(stdout).spawn()?;
111 match child.wait()?.code() {
112 Some(0) => {
113 info!("task successfully finished");
114 Ok(())
115 }
116 Some(code) => bail!("task exited with exit code: {}", code),
117 None => bail!("task terminated by signal"),
Jiyong Park038b73e2021-06-16 01:57:02 +0900118 }
Jooyung Han347d9f22021-05-28 00:05:14 +0900119}
Jooyung Han634e2d72021-06-10 16:27:38 +0900120
121fn build_command(task: &Task) -> Result<Command> {
122 Ok(match task.type_ {
123 TaskType::Executable => {
124 let mut command = Command::new(&task.command);
125 command.args(&task.args);
126 command
127 }
128 TaskType::MicrodroidLauncher => {
129 let mut command = Command::new("/system/bin/microdroid_launcher");
130 command.arg(find_library_path(&task.command)?).args(&task.args);
131 command
132 }
133 })
134}
135
136fn find_library_path(name: &str) -> Result<String> {
137 let mut watcher = PropertyWatcher::new("ro.product.cpu.abilist")?;
138 let value = watcher.read(|_name, value| Ok(value.trim().to_string()))?;
139 let abi = value.split(',').next().ok_or_else(|| anyhow!("no abilist"))?;
140 let path = format!("/mnt/apk/lib/{}/{}", abi, name);
141
142 let metadata = fs::metadata(&path)?;
143 if !metadata.is_file() {
144 bail!("{} is not a file", &path);
145 }
146
147 Ok(path)
148}