Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 1 | // 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 Walbran | a2f8c23 | 2021-03-11 11:46:53 +0000 | [diff] [blame] | 17 | use crate::config::VmConfig; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 18 | use crate::crosvm::VmInstance; |
| 19 | use crate::{Cid, FIRST_GUEST_CID}; |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 20 | use ::binder::FromIBinder; // TODO(dbrazdil): remove once b/182890877 is fixed |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 21 | use android_system_virtmanager::aidl::android::system::virtmanager::IVirtManager::IVirtManager; |
| 22 | use android_system_virtmanager::aidl::android::system::virtmanager::IVirtualMachine::{ |
| 23 | BnVirtualMachine, IVirtualMachine, |
| 24 | }; |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 25 | use android_system_virtmanager::aidl::android::system::virtmanager::VirtualMachineDebugInfo::VirtualMachineDebugInfo; |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 26 | use android_system_virtmanager::binder::{ |
| 27 | self, Interface, ParcelFileDescriptor, StatusCode, Strong, ThreadState, |
| 28 | }; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 29 | use log::error; |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame^] | 30 | use std::ffi::CStr; |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 31 | use std::fs::File; |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 32 | use std::sync::{Arc, Mutex, Weak}; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 33 | |
| 34 | pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtmanager"; |
| 35 | |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 36 | // 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. |
| 38 | const DEBUG_ALLOWED_UIDS: [u32; 2] = [0, 2000]; |
| 39 | |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 40 | /// Implementation of `IVirtManager`, the entry point of the AIDL service. |
| 41 | #[derive(Debug, Default)] |
| 42 | pub struct VirtManager { |
Andrew Walbran | 9c01baa | 2021-03-08 18:23:50 +0000 | [diff] [blame] | 43 | state: Mutex<State>, |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 44 | } |
| 45 | |
| 46 | impl Interface for VirtManager {} |
| 47 | |
| 48 | impl 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 Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 52 | fn startVm( |
| 53 | &self, |
Andrew Walbran | 06b5f5c | 2021-03-31 12:34:13 +0000 | [diff] [blame] | 54 | config_fd: &ParcelFileDescriptor, |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 55 | log_fd: Option<&ParcelFileDescriptor>, |
| 56 | ) -> binder::Result<Strong<dyn IVirtualMachine>> { |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 57 | let state = &mut *self.state.lock().unwrap(); |
| 58 | let cid = state.next_cid; |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 59 | let log_fd = log_fd |
| 60 | .map(|fd| fd.as_ref().try_clone().map_err(|_| StatusCode::UNKNOWN_ERROR)) |
| 61 | .transpose()?; |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame^] | 62 | 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 Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 81 | // 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 Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 83 | state.add_vm(Arc::downgrade(&instance)); |
| 84 | Ok(VirtualMachine::create(instance)) |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 85 | } |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 86 | |
| 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 Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame^] | 96 | 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 Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 105 | Ok(cids) |
| 106 | } |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 107 | |
| 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 Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 134 | } |
| 135 | |
| 136 | /// Check whether the caller of the current Binder method is allowed to call debug methods. |
| 137 | fn 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 Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 141 | } |
| 142 | |
| 143 | /// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM. |
| 144 | #[derive(Debug)] |
| 145 | struct VirtualMachine { |
| 146 | instance: Arc<VmInstance>, |
| 147 | } |
| 148 | |
| 149 | impl VirtualMachine { |
| 150 | fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> { |
| 151 | let binder = VirtualMachine { instance }; |
| 152 | BnVirtualMachine::new_binder(binder) |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | impl Interface for VirtualMachine {} |
| 157 | |
| 158 | impl 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)] |
| 166 | struct State { |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 167 | /// The next available unused CID. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 168 | next_cid: Cid, |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 169 | |
| 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 Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 175 | |
| 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 Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 179 | } |
| 180 | |
| 181 | impl 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 Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 196 | |
| 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 Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 207 | } |
| 208 | |
| 209 | impl Default for State { |
| 210 | fn default() -> Self { |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 211 | State { next_cid: FIRST_GUEST_CID, vms: vec![], debug_held_vms: vec![] } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 212 | } |
| 213 | } |
| 214 | |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame^] | 215 | /// Start a new VM instance from the given VM config file. This assumes the VM is not already |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 216 | /// running. |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame^] | 217 | fn 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 Walbran | 06b5f5c | 2021-03-31 12:34:13 +0000 | [diff] [blame] | 225 | let config = VmConfig::load(config_file).map_err(|e| { |
| 226 | error!("Failed to load VM config from {:?}: {:?}", config_file, e); |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 227 | StatusCode::BAD_VALUE |
| 228 | })?; |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame^] | 229 | 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 Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 234 | } |