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}; |
| 20 | use android_system_virtmanager::aidl::android::system::virtmanager::IVirtManager::IVirtManager; |
| 21 | use android_system_virtmanager::aidl::android::system::virtmanager::IVirtualMachine::{ |
| 22 | BnVirtualMachine, IVirtualMachine, |
| 23 | }; |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 24 | use android_system_virtmanager::aidl::android::system::virtmanager::VirtualMachineDebugInfo::VirtualMachineDebugInfo; |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 25 | use android_system_virtmanager::binder::{ |
| 26 | self, Interface, ParcelFileDescriptor, StatusCode, Strong, ThreadState, |
| 27 | }; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 28 | use log::error; |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 29 | use std::ffi::CStr; |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 30 | use std::fs::File; |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 31 | use std::sync::{Arc, Mutex, Weak}; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 32 | |
| 33 | pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtmanager"; |
| 34 | |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 35 | // TODO(qwandor): Use PermissionController once it is available to Rust. |
| 36 | /// Only processes running with one of these UIDs are allowed to call debug methods. |
| 37 | const DEBUG_ALLOWED_UIDS: [u32; 2] = [0, 2000]; |
| 38 | |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 39 | /// Implementation of `IVirtManager`, the entry point of the AIDL service. |
| 40 | #[derive(Debug, Default)] |
| 41 | pub struct VirtManager { |
Andrew Walbran | 9c01baa | 2021-03-08 18:23:50 +0000 | [diff] [blame] | 42 | state: Mutex<State>, |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 43 | } |
| 44 | |
| 45 | impl Interface for VirtManager {} |
| 46 | |
| 47 | impl IVirtManager for VirtManager { |
| 48 | /// Create and start a new VM with the given configuration, assigning it the next available CID. |
| 49 | /// |
| 50 | /// 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] | 51 | fn startVm( |
| 52 | &self, |
Andrew Walbran | 06b5f5c | 2021-03-31 12:34:13 +0000 | [diff] [blame] | 53 | config_fd: &ParcelFileDescriptor, |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 54 | log_fd: Option<&ParcelFileDescriptor>, |
| 55 | ) -> binder::Result<Strong<dyn IVirtualMachine>> { |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 56 | let state = &mut *self.state.lock().unwrap(); |
| 57 | let cid = state.next_cid; |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 58 | let log_fd = log_fd |
| 59 | .map(|fd| fd.as_ref().try_clone().map_err(|_| StatusCode::UNKNOWN_ERROR)) |
| 60 | .transpose()?; |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 61 | let requester_uid = ThreadState::get_calling_uid(); |
| 62 | let requester_sid = ThreadState::with_calling_sid(|sid| { |
| 63 | sid.and_then(|sid: &CStr| match sid.to_str() { |
| 64 | Ok(s) => Some(s.to_owned()), |
| 65 | Err(e) => { |
| 66 | error!("SID was not valid UTF-8: {:?}", e); |
| 67 | None |
| 68 | } |
| 69 | }) |
| 70 | }); |
| 71 | let requester_pid = ThreadState::get_calling_pid(); |
| 72 | let instance = Arc::new(start_vm( |
| 73 | config_fd.as_ref(), |
| 74 | cid, |
| 75 | log_fd, |
| 76 | requester_uid, |
| 77 | requester_sid, |
| 78 | requester_pid, |
| 79 | )?); |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 80 | // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them. |
| 81 | 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] | 82 | state.add_vm(Arc::downgrade(&instance)); |
| 83 | Ok(VirtualMachine::create(instance)) |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 84 | } |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 85 | |
| 86 | /// Get a list of all currently running VMs. This method is only intended for debug purposes, |
| 87 | /// and as such is only permitted from the shell user. |
| 88 | fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> { |
| 89 | if !debug_access_allowed() { |
| 90 | return Err(StatusCode::PERMISSION_DENIED.into()); |
| 91 | } |
| 92 | |
| 93 | let state = &mut *self.state.lock().unwrap(); |
| 94 | let vms = state.vms(); |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 95 | let cids = vms |
| 96 | .into_iter() |
| 97 | .map(|vm| VirtualMachineDebugInfo { |
| 98 | cid: vm.cid as i32, |
| 99 | requester_uid: vm.requester_uid as i32, |
| 100 | requester_sid: vm.requester_sid.clone(), |
| 101 | requester_pid: vm.requester_pid, |
| 102 | }) |
| 103 | .collect(); |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 104 | Ok(cids) |
| 105 | } |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 106 | |
| 107 | /// Hold a strong reference to a VM in Virt Manager. This method is only intended for debug |
| 108 | /// purposes, and as such is only permitted from the shell user. |
Andrei Homescu | 1415c13 | 2021-03-24 02:39:55 +0000 | [diff] [blame^] | 109 | fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> { |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 110 | if !debug_access_allowed() { |
| 111 | return Err(StatusCode::PERMISSION_DENIED.into()); |
| 112 | } |
| 113 | |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 114 | let state = &mut *self.state.lock().unwrap(); |
Andrei Homescu | 1415c13 | 2021-03-24 02:39:55 +0000 | [diff] [blame^] | 115 | state.debug_hold_vm(vmref.clone()); |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 116 | Ok(()) |
| 117 | } |
| 118 | |
| 119 | /// Drop reference to a VM that is being held by Virt Manager. Returns the reference if VM was |
| 120 | /// found and None otherwise. This method is only intended for debug purposes, and as such is |
| 121 | /// only permitted from the shell user. |
| 122 | fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> { |
| 123 | if !debug_access_allowed() { |
| 124 | return Err(StatusCode::PERMISSION_DENIED.into()); |
| 125 | } |
| 126 | |
| 127 | let state = &mut *self.state.lock().unwrap(); |
| 128 | Ok(state.debug_drop_vm(cid)) |
| 129 | } |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 130 | } |
| 131 | |
| 132 | /// Check whether the caller of the current Binder method is allowed to call debug methods. |
| 133 | fn debug_access_allowed() -> bool { |
| 134 | let uid = ThreadState::get_calling_uid(); |
| 135 | log::trace!("Debug method call from UID {}.", uid); |
| 136 | DEBUG_ALLOWED_UIDS.contains(&uid) |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 137 | } |
| 138 | |
| 139 | /// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM. |
| 140 | #[derive(Debug)] |
| 141 | struct VirtualMachine { |
| 142 | instance: Arc<VmInstance>, |
| 143 | } |
| 144 | |
| 145 | impl VirtualMachine { |
| 146 | fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> { |
| 147 | let binder = VirtualMachine { instance }; |
| 148 | BnVirtualMachine::new_binder(binder) |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | impl Interface for VirtualMachine {} |
| 153 | |
| 154 | impl IVirtualMachine for VirtualMachine { |
| 155 | fn getCid(&self) -> binder::Result<i32> { |
| 156 | Ok(self.instance.cid as i32) |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | /// The mutable state of the Virt Manager. There should only be one instance of this struct. |
| 161 | #[derive(Debug)] |
| 162 | struct State { |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 163 | /// The next available unused CID. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 164 | next_cid: Cid, |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 165 | |
| 166 | /// The VMs which have been started. When VMs are started a weak reference is added to this list |
| 167 | /// while a strong reference is returned to the caller over Binder. Once all copies of the |
| 168 | /// Binder client are dropped the weak reference here will become invalid, and will be removed |
| 169 | /// from the list opportunistically the next time `add_vm` is called. |
| 170 | vms: Vec<Weak<VmInstance>>, |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 171 | |
| 172 | /// Vector of strong VM references held on behalf of users that cannot hold them themselves. |
| 173 | /// This is only used for debugging purposes. |
| 174 | debug_held_vms: Vec<Strong<dyn IVirtualMachine>>, |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 175 | } |
| 176 | |
| 177 | impl State { |
| 178 | /// Get a list of VMs which are currently running. |
| 179 | fn vms(&self) -> Vec<Arc<VmInstance>> { |
| 180 | // Attempt to upgrade the weak pointers to strong pointers. |
| 181 | self.vms.iter().filter_map(Weak::upgrade).collect() |
| 182 | } |
| 183 | |
| 184 | /// Add a new VM to the list. |
| 185 | fn add_vm(&mut self, vm: Weak<VmInstance>) { |
| 186 | // Garbage collect any entries from the stored list which no longer exist. |
| 187 | self.vms.retain(|vm| vm.strong_count() > 0); |
| 188 | |
| 189 | // Actually add the new VM. |
| 190 | self.vms.push(vm); |
| 191 | } |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 192 | |
| 193 | /// Store a strong VM reference. |
| 194 | fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) { |
| 195 | self.debug_held_vms.push(vm); |
| 196 | } |
| 197 | |
| 198 | /// Retrieve and remove a strong VM reference. |
| 199 | fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> { |
| 200 | let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?; |
| 201 | Some(self.debug_held_vms.swap_remove(pos)) |
| 202 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 203 | } |
| 204 | |
| 205 | impl Default for State { |
| 206 | fn default() -> Self { |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 207 | State { next_cid: FIRST_GUEST_CID, vms: vec![], debug_held_vms: vec![] } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 208 | } |
| 209 | } |
| 210 | |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 211 | /// 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] | 212 | /// running. |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 213 | fn start_vm( |
| 214 | config_file: &File, |
| 215 | cid: Cid, |
| 216 | log_fd: Option<File>, |
| 217 | requester_uid: u32, |
| 218 | requester_sid: Option<String>, |
| 219 | requester_pid: i32, |
| 220 | ) -> binder::Result<VmInstance> { |
Andrew Walbran | 06b5f5c | 2021-03-31 12:34:13 +0000 | [diff] [blame] | 221 | let config = VmConfig::load(config_file).map_err(|e| { |
| 222 | error!("Failed to load VM config from {:?}: {:?}", config_file, e); |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 223 | StatusCode::BAD_VALUE |
| 224 | })?; |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 225 | Ok(VmInstance::start(&config, cid, log_fd, requester_uid, requester_sid, requester_pid) |
| 226 | .map_err(|e| { |
| 227 | error!("Failed to start VM from {:?}: {:?}", config_file, e); |
| 228 | StatusCode::UNKNOWN_ERROR |
| 229 | })?) |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 230 | } |