blob: 2fb7fdd980cf864fd92d4b667c725c53c39cd12c [file] [log] [blame]
// Copyright 2021, The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Microdroid Manager
mod ioutil;
mod metadata;
use anyhow::{anyhow, bail, Context, Result};
use apkverify::verify;
use binder::unstable_api::{new_spibinder, AIBinder};
use binder::{FromIBinder, Strong};
use log::{error, info, warn};
use microdroid_payload_config::{Task, TaskType, VmPayloadConfig};
use rustutils::system_properties::PropertyWatcher;
use std::fs::{self, File};
use std::os::unix::io::{FromRawFd, IntoRawFd};
use std::path::Path;
use std::process::{Command, Stdio};
use std::str;
use std::time::Duration;
use vsock::VsockStream;
use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::IVirtualMachineService;
const WAIT_TIMEOUT: Duration = Duration::from_secs(10);
const DM_MOUNTED_APK_PATH: &str = "/dev/block/mapper/microdroid-apk";
/// The CID representing the host VM
const VMADDR_CID_HOST: u32 = 2;
/// Port number that virtualizationservice listens on connections from the guest VMs for the
/// VirtualMachineService binder service
/// Sync with virtualizationservice/src/aidl.rs
const PORT_VM_BINDER_SERVICE: u32 = 5000;
fn get_vms_rpc_binder() -> Result<Strong<dyn IVirtualMachineService>> {
// SAFETY: AIBinder returned by RpcClient has correct reference count, and the ownership can be
// safely taken by new_spibinder.
let ibinder = unsafe {
new_spibinder(binder_rpc_unstable_bindgen::RpcClient(
VMADDR_CID_HOST,
PORT_VM_BINDER_SERVICE,
) as *mut AIBinder)
};
if let Some(ibinder) = ibinder {
<dyn IVirtualMachineService>::try_from(ibinder).context("Cannot connect to RPC service")
} else {
bail!("Invalid raw AIBinder")
}
}
fn main() -> Result<()> {
kernlog::init()?;
info!("started.");
let metadata = metadata::load()?;
if let Err(err) = verify_payloads() {
error!("failed to verify payload: {:#?}", err);
return Err(err);
}
// TODO(b/191845268): microdroid_manager should use this binder to communicate with the host
if let Err(err) = get_vms_rpc_binder() {
error!("cannot connect to VirtualMachineService: {}", err);
}
if !metadata.payload_config_path.is_empty() {
let config = load_config(Path::new(&metadata.payload_config_path))?;
let fake_secret = "This is a placeholder for a value that is derived from the images that are loaded in the VM.";
if let Err(err) = rustutils::system_properties::write("ro.vmsecret.keymint", fake_secret) {
warn!("failed to set ro.vmsecret.keymint: {}", err);
}
// TODO(jooyung): wait until sys.boot_completed?
if let Some(main_task) = &config.task {
exec_task(main_task).map_err(|e| {
error!("failed to execute task: {}", e);
e
})?;
}
}
Ok(())
}
// TODO(jooyung): v2/v3 full verification can be slow. Consider multithreading.
fn verify_payloads() -> Result<()> {
// We don't verify APEXes since apexd does.
// should wait APK to be dm-verity mounted by apkdmverity
ioutil::wait_for_file(DM_MOUNTED_APK_PATH, WAIT_TIMEOUT)?;
verify(DM_MOUNTED_APK_PATH).context(format!("failed to verify {}", DM_MOUNTED_APK_PATH))?;
info!("payload verification succeeded.");
// TODO(jooyung): collect public keys and store them in instance.img
Ok(())
}
fn load_config(path: &Path) -> Result<VmPayloadConfig> {
info!("loading config from {:?}...", path);
let file = ioutil::wait_for_file(path, WAIT_TIMEOUT)?;
Ok(serde_json::from_reader(file)?)
}
/// Executes the given task. Stdout of the task is piped into the vsock stream to the
/// virtualizationservice in the host side.
fn exec_task(task: &Task) -> Result<()> {
const VMADDR_CID_HOST: u32 = 2;
const PORT_VIRT_SVC: u32 = 3000;
let stdout = match VsockStream::connect_with_cid_port(VMADDR_CID_HOST, PORT_VIRT_SVC) {
Ok(stream) => {
// SAFETY: the ownership of the underlying file descriptor is transferred from stream
// to the file object, and then into the Command object. When the command is finished,
// the file descriptor is closed.
let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
Stdio::from(f)
}
Err(e) => {
error!("failed to connect to virtualization service: {}", e);
// Don't fail hard here. Even if we failed to connect to the virtualizationservice,
// we keep executing the task. This can happen if the owner of the VM doesn't register
// callback to accept the stream. Use /dev/null as the stdout so that the task can
// make progress without waiting for someone to consume the output.
Stdio::null()
}
};
info!("executing main task {:?}...", task);
// TODO(jiyong): consider piping the stream into stdio (and probably stderr) as well.
let mut child = build_command(task)?.stdout(stdout).spawn()?;
match child.wait()?.code() {
Some(0) => {
info!("task successfully finished");
Ok(())
}
Some(code) => bail!("task exited with exit code: {}", code),
None => bail!("task terminated by signal"),
}
}
fn build_command(task: &Task) -> Result<Command> {
Ok(match task.type_ {
TaskType::Executable => {
let mut command = Command::new(&task.command);
command.args(&task.args);
command
}
TaskType::MicrodroidLauncher => {
let mut command = Command::new("/system/bin/microdroid_launcher");
command.arg(find_library_path(&task.command)?).args(&task.args);
command
}
})
}
fn find_library_path(name: &str) -> Result<String> {
let mut watcher = PropertyWatcher::new("ro.product.cpu.abilist")?;
let value = watcher.read(|_name, value| Ok(value.trim().to_string()))?;
let abi = value.split(',').next().ok_or_else(|| anyhow!("no abilist"))?;
let path = format!("/mnt/apk/lib/{}/{}", abi, name);
let metadata = fs::metadata(&path)?;
if !metadata.is_file() {
bail!("{} is not a file", &path);
}
Ok(path)
}