blob: d0c920a1687ae21a01a54351ef1833b75407c55e [file] [log] [blame]
Alan Stokes9e2c5d52021-07-21 11:29:10 +01001/*
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
Victor Hsieh9ebf7ee2021-09-03 16:14:14 -070017//! A tool to start a standalone compsvc server that serves over RPC binder.
Alan Stokes9e2c5d52021-07-21 11:29:10 +010018
Victor Hsieh51789de2021-08-06 16:50:49 -070019mod compilation;
Victor Hsieha64194b2021-08-06 17:43:36 -070020mod compos_key_service;
Alan Stokes9e2c5d52021-07-21 11:29:10 +010021mod compsvc;
Victor Hsieh9ed27182021-08-25 15:52:42 -070022mod fsverity;
Alan Stokes7ec4e7f2021-07-21 11:29:10 +010023mod signer;
Alan Stokes9e2c5d52021-07-21 11:29:10 +010024
Alan Stokesb5c60b42021-09-09 14:44:13 +010025use android_system_virtualmachineservice::{
26 aidl::android::system::virtualmachineservice::IVirtualMachineService::{
27 IVirtualMachineService, VM_BINDER_SERVICE_PORT,
28 },
29 binder::Strong,
30};
31use anyhow::{anyhow, bail, Context, Result};
32use binder::{
33 unstable_api::{new_spibinder, AIBinder, AsNative},
34 FromIBinder,
35};
Alan Stokes17fd36a2021-09-06 17:22:37 +010036use compos_common::COMPOS_VSOCK_PORT;
Alan Stokesb5c60b42021-09-09 14:44:13 +010037use log::{debug, error};
38use nix::ioctl_read_bad;
39use std::fs::OpenOptions;
40use std::os::raw;
41use std::os::unix::io::AsRawFd;
42
43/// The CID representing the host VM
44const VMADDR_CID_HOST: u32 = 2;
Alan Stokes9e2c5d52021-07-21 11:29:10 +010045
Alan Stokese1b6e1c2021-10-01 12:44:49 +010046fn main() {
47 if let Err(e) = try_main() {
48 error!("failed with {:?}", e);
49 std::process::exit(1);
50 }
51}
52
53fn try_main() -> Result<()> {
Alan Stokesf03d81a2021-09-20 17:44:03 +010054 let args = clap::App::new("compsvc")
55 .arg(clap::Arg::with_name("log_to_stderr").long("log_to_stderr"))
56 .get_matches();
57 if args.is_present("log_to_stderr") {
58 env_logger::builder().filter_level(log::LevelFilter::Debug).init();
59 } else {
60 android_logger::init_once(
61 android_logger::Config::default().with_tag("compsvc").with_min_level(log::Level::Debug),
62 );
63 }
Alan Stokes9e2c5d52021-07-21 11:29:10 +010064
Victor Hsieh9ebf7ee2021-09-03 16:14:14 -070065 let mut service = compsvc::new_binder()?.as_binder();
66 debug!("compsvc is starting as a rpc service.");
Alan Stokesb5c60b42021-09-09 14:44:13 +010067
68 let mut ready_notifier = ReadyNotifier::new()?;
69
Victor Hsieh9ebf7ee2021-09-03 16:14:14 -070070 // SAFETY: Service ownership is transferring to the server and won't be valid afterward.
71 // Plus the binder objects are threadsafe.
Alan Stokesb5c60b42021-09-09 14:44:13 +010072 // RunRpcServerCallback does not retain a reference to ready_callback, and only ever
73 // calls it with the param we provide during the lifetime of ready_notifier.
Victor Hsieh9ebf7ee2021-09-03 16:14:14 -070074 let retval = unsafe {
Alan Stokesb5c60b42021-09-09 14:44:13 +010075 binder_rpc_unstable_bindgen::RunRpcServerCallback(
Victor Hsieh9ebf7ee2021-09-03 16:14:14 -070076 service.as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder,
Alan Stokes17fd36a2021-09-06 17:22:37 +010077 COMPOS_VSOCK_PORT,
Alan Stokesb5c60b42021-09-09 14:44:13 +010078 Some(ReadyNotifier::ready_callback),
79 ready_notifier.as_void_ptr(),
Victor Hsieh9ebf7ee2021-09-03 16:14:14 -070080 )
81 };
82 if retval {
83 debug!("RPC server has shut down gracefully");
84 Ok(())
Alan Stokes9e2c5d52021-07-21 11:29:10 +010085 } else {
Victor Hsieh9ebf7ee2021-09-03 16:14:14 -070086 bail!("Premature termination of RPC server");
Alan Stokes9e2c5d52021-07-21 11:29:10 +010087 }
88}
Alan Stokesb5c60b42021-09-09 14:44:13 +010089
90struct ReadyNotifier {
91 vm_service: Strong<dyn IVirtualMachineService>,
92 local_cid: u32,
93}
94
95impl ReadyNotifier {
96 fn new() -> Result<Self> {
97 Ok(Self { vm_service: Self::get_vm_service()?, local_cid: Self::get_local_cid()? })
98 }
99
100 fn notify(&self) {
101 if let Err(e) = self.vm_service.notifyPayloadReady(self.local_cid as i32) {
102 error!("Unable to notify ready: {}", e);
103 }
104 }
105
106 fn as_void_ptr(&mut self) -> *mut raw::c_void {
107 self as *mut _ as *mut raw::c_void
108 }
109
110 unsafe extern "C" fn ready_callback(param: *mut raw::c_void) {
111 // SAFETY: This is only ever called by RunRpcServerCallback, within the lifetime of the
112 // ReadyNotifier, with param taking the value returned by as_void_ptr (so a properly aligned
113 // non-null pointer to an initialized instance).
114 let ready_notifier = param as *mut Self;
115 ready_notifier.as_ref().unwrap().notify()
116 }
117
118 fn get_vm_service() -> Result<Strong<dyn IVirtualMachineService>> {
119 // SAFETY: AIBinder returned by RpcClient has correct reference count, and the ownership
120 // can be safely taken by new_spibinder.
121 let ibinder = unsafe {
122 new_spibinder(binder_rpc_unstable_bindgen::RpcClient(
123 VMADDR_CID_HOST,
124 VM_BINDER_SERVICE_PORT as u32,
125 ) as *mut AIBinder)
126 }
127 .ok_or_else(|| anyhow!("Failed to connect to IVirtualMachineService"))?;
128
129 FromIBinder::try_from(ibinder).context("Connecting to IVirtualMachineService")
130 }
131
132 // TODO(b/199259751): remove this after VS can check the peer addresses of binder clients
133 fn get_local_cid() -> Result<u32> {
134 let f = OpenOptions::new()
135 .read(true)
136 .write(false)
137 .open("/dev/vsock")
138 .context("Failed to open /dev/vsock")?;
139 let mut cid = 0;
140 // SAFETY: the kernel only modifies the given u32 integer.
141 unsafe { vm_sockets_get_local_cid(f.as_raw_fd(), &mut cid) }
142 .context("Failed to get local CID")?;
143 Ok(cid)
144 }
145}
146
147// TODO(b/199259751): remove this after VS can check the peer addresses of binder clients
148const IOCTL_VM_SOCKETS_GET_LOCAL_CID: usize = 0x7b9;
149ioctl_read_bad!(
150 /// Gets local cid from /dev/vsock
151 vm_sockets_get_local_cid,
152 IOCTL_VM_SOCKETS_GET_LOCAL_CID,
153 u32
154);