blob: 98af714a380dd8c51639f03ddfa25a8d15684c4e [file] [log] [blame]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001// 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//! Implementation of the AIDL interface of the Virt Manager.
16
Andrew Walbrana2f8c232021-03-11 11:46:53 +000017use crate::config::VmConfig;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000018use crate::crosvm::VmInstance;
19use crate::{Cid, FIRST_GUEST_CID};
David Brazdil3c2ddef2021-03-18 13:09:57 +000020use ::binder::FromIBinder; // TODO(dbrazdil): remove once b/182890877 is fixed
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000021use android_system_virtmanager::aidl::android::system::virtmanager::IVirtManager::IVirtManager;
22use android_system_virtmanager::aidl::android::system::virtmanager::IVirtualMachine::{
23 BnVirtualMachine, IVirtualMachine,
24};
Andrew Walbran320b5602021-03-04 16:11:12 +000025use android_system_virtmanager::aidl::android::system::virtmanager::VirtualMachineDebugInfo::VirtualMachineDebugInfo;
Andrew Walbrana89fc132021-03-17 17:08:36 +000026use android_system_virtmanager::binder::{
27 self, Interface, ParcelFileDescriptor, StatusCode, Strong, ThreadState,
28};
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000029use log::error;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000030use std::ffi::CStr;
Andrew Walbrana89fc132021-03-17 17:08:36 +000031use std::fs::File;
Andrew Walbran320b5602021-03-04 16:11:12 +000032use std::sync::{Arc, Mutex, Weak};
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000033
34pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtmanager";
35
Andrew Walbran320b5602021-03-04 16:11:12 +000036// TODO(qwandor): Use PermissionController once it is available to Rust.
37/// Only processes running with one of these UIDs are allowed to call debug methods.
38const DEBUG_ALLOWED_UIDS: [u32; 2] = [0, 2000];
39
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000040/// Implementation of `IVirtManager`, the entry point of the AIDL service.
41#[derive(Debug, Default)]
42pub struct VirtManager {
Andrew Walbran9c01baa2021-03-08 18:23:50 +000043 state: Mutex<State>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000044}
45
46impl Interface for VirtManager {}
47
48impl IVirtManager for VirtManager {
49 /// Create and start a new VM with the given configuration, assigning it the next available CID.
50 ///
51 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbrana89fc132021-03-17 17:08:36 +000052 fn startVm(
53 &self,
Andrew Walbran06b5f5c2021-03-31 12:34:13 +000054 config_fd: &ParcelFileDescriptor,
Andrew Walbrana89fc132021-03-17 17:08:36 +000055 log_fd: Option<&ParcelFileDescriptor>,
56 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000057 let state = &mut *self.state.lock().unwrap();
58 let cid = state.next_cid;
Andrew Walbrana89fc132021-03-17 17:08:36 +000059 let log_fd = log_fd
60 .map(|fd| fd.as_ref().try_clone().map_err(|_| StatusCode::UNKNOWN_ERROR))
61 .transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000062 let requester_uid = ThreadState::get_calling_uid();
63 let requester_sid = ThreadState::with_calling_sid(|sid| {
64 sid.and_then(|sid: &CStr| match sid.to_str() {
65 Ok(s) => Some(s.to_owned()),
66 Err(e) => {
67 error!("SID was not valid UTF-8: {:?}", e);
68 None
69 }
70 })
71 });
72 let requester_pid = ThreadState::get_calling_pid();
73 let instance = Arc::new(start_vm(
74 config_fd.as_ref(),
75 cid,
76 log_fd,
77 requester_uid,
78 requester_sid,
79 requester_pid,
80 )?);
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000081 // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them.
82 state.next_cid = state.next_cid.checked_add(1).ok_or(StatusCode::UNKNOWN_ERROR)?;
Andrew Walbran320b5602021-03-04 16:11:12 +000083 state.add_vm(Arc::downgrade(&instance));
84 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000085 }
Andrew Walbran320b5602021-03-04 16:11:12 +000086
87 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
88 /// and as such is only permitted from the shell user.
89 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
90 if !debug_access_allowed() {
91 return Err(StatusCode::PERMISSION_DENIED.into());
92 }
93
94 let state = &mut *self.state.lock().unwrap();
95 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000096 let cids = vms
97 .into_iter()
98 .map(|vm| VirtualMachineDebugInfo {
99 cid: vm.cid as i32,
100 requester_uid: vm.requester_uid as i32,
101 requester_sid: vm.requester_sid.clone(),
102 requester_pid: vm.requester_pid,
103 })
104 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000105 Ok(cids)
106 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000107
108 /// Hold a strong reference to a VM in Virt Manager. This method is only intended for debug
109 /// purposes, and as such is only permitted from the shell user.
110 fn debugHoldVmRef(&self, vmref: &dyn IVirtualMachine) -> binder::Result<()> {
111 if !debug_access_allowed() {
112 return Err(StatusCode::PERMISSION_DENIED.into());
113 }
114
115 // Workaround for b/182890877.
116 let vm: Strong<dyn IVirtualMachine> = FromIBinder::try_from(vmref.as_binder()).unwrap();
117
118 let state = &mut *self.state.lock().unwrap();
119 state.debug_hold_vm(vm);
120 Ok(())
121 }
122
123 /// Drop reference to a VM that is being held by Virt Manager. Returns the reference if VM was
124 /// found and None otherwise. This method is only intended for debug purposes, and as such is
125 /// only permitted from the shell user.
126 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
127 if !debug_access_allowed() {
128 return Err(StatusCode::PERMISSION_DENIED.into());
129 }
130
131 let state = &mut *self.state.lock().unwrap();
132 Ok(state.debug_drop_vm(cid))
133 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000134}
135
136/// Check whether the caller of the current Binder method is allowed to call debug methods.
137fn debug_access_allowed() -> bool {
138 let uid = ThreadState::get_calling_uid();
139 log::trace!("Debug method call from UID {}.", uid);
140 DEBUG_ALLOWED_UIDS.contains(&uid)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000141}
142
143/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
144#[derive(Debug)]
145struct VirtualMachine {
146 instance: Arc<VmInstance>,
147}
148
149impl VirtualMachine {
150 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
151 let binder = VirtualMachine { instance };
152 BnVirtualMachine::new_binder(binder)
153 }
154}
155
156impl Interface for VirtualMachine {}
157
158impl IVirtualMachine for VirtualMachine {
159 fn getCid(&self) -> binder::Result<i32> {
160 Ok(self.instance.cid as i32)
161 }
162}
163
164/// The mutable state of the Virt Manager. There should only be one instance of this struct.
165#[derive(Debug)]
166struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000167 /// The next available unused CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000168 next_cid: Cid,
Andrew Walbran320b5602021-03-04 16:11:12 +0000169
170 /// The VMs which have been started. When VMs are started a weak reference is added to this list
171 /// while a strong reference is returned to the caller over Binder. Once all copies of the
172 /// Binder client are dropped the weak reference here will become invalid, and will be removed
173 /// from the list opportunistically the next time `add_vm` is called.
174 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000175
176 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
177 /// This is only used for debugging purposes.
178 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000179}
180
181impl State {
182 /// Get a list of VMs which are currently running.
183 fn vms(&self) -> Vec<Arc<VmInstance>> {
184 // Attempt to upgrade the weak pointers to strong pointers.
185 self.vms.iter().filter_map(Weak::upgrade).collect()
186 }
187
188 /// Add a new VM to the list.
189 fn add_vm(&mut self, vm: Weak<VmInstance>) {
190 // Garbage collect any entries from the stored list which no longer exist.
191 self.vms.retain(|vm| vm.strong_count() > 0);
192
193 // Actually add the new VM.
194 self.vms.push(vm);
195 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000196
197 /// Store a strong VM reference.
198 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
199 self.debug_held_vms.push(vm);
200 }
201
202 /// Retrieve and remove a strong VM reference.
203 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
204 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
205 Some(self.debug_held_vms.swap_remove(pos))
206 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000207}
208
209impl Default for State {
210 fn default() -> Self {
David Brazdil3c2ddef2021-03-18 13:09:57 +0000211 State { next_cid: FIRST_GUEST_CID, vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000212 }
213}
214
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000215/// Start a new VM instance from the given VM config file. This assumes the VM is not already
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000216/// running.
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000217fn start_vm(
218 config_file: &File,
219 cid: Cid,
220 log_fd: Option<File>,
221 requester_uid: u32,
222 requester_sid: Option<String>,
223 requester_pid: i32,
224) -> binder::Result<VmInstance> {
Andrew Walbran06b5f5c2021-03-31 12:34:13 +0000225 let config = VmConfig::load(config_file).map_err(|e| {
226 error!("Failed to load VM config from {:?}: {:?}", config_file, e);
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000227 StatusCode::BAD_VALUE
228 })?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000229 Ok(VmInstance::start(&config, cid, log_fd, requester_uid, requester_sid, requester_pid)
230 .map_err(|e| {
231 error!("Failed to start VM from {:?}: {:?}", config_file, e);
232 StatusCode::UNKNOWN_ERROR
233 })?)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000234}