blob: 3f0b64bc983df29575c19347b13048f19d84f395 [file] [log] [blame]
David Brazdil1f530702022-10-03 12:18:10 +01001// Copyright 2022, 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//! Android Virtualization Manager
16
17mod aidl;
18mod atom;
19mod composite;
20mod crosvm;
21mod payload;
22mod selinux;
23
David Brazdil4b4c5102022-12-19 22:56:20 +000024use crate::aidl::{GLOBAL_SERVICE, VirtualizationService};
David Brazdil1f530702022-10-03 12:18:10 +010025use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualizationService::BnVirtualizationService;
Alan Stokesc4d5def2023-02-14 17:01:59 +000026use anyhow::{bail, Context, Result};
David Brazdil4b4c5102022-12-19 22:56:20 +000027use binder::{BinderFeatures, ProcessState};
David Brazdil1f530702022-10-03 12:18:10 +010028use lazy_static::lazy_static;
29use log::{info, Level};
30use rpcbinder::{FileDescriptorTransportMode, RpcServer};
31use std::os::unix::io::{FromRawFd, OwnedFd, RawFd};
32use clap::Parser;
David Brazdil161ddda2023-01-06 20:29:19 +000033use nix::fcntl::{fcntl, F_GETFD, F_SETFD, FdFlag};
David Brazdil1f530702022-10-03 12:18:10 +010034use nix::unistd::{Pid, Uid};
35use std::os::unix::raw::{pid_t, uid_t};
36
37const LOG_TAG: &str = "virtmgr";
38
39lazy_static! {
40 static ref PID_PARENT: Pid = Pid::parent();
41 static ref UID_CURRENT: Uid = Uid::current();
42}
43
44fn get_calling_pid() -> pid_t {
45 // The caller is the parent of this process.
46 PID_PARENT.as_raw()
47}
48
49fn get_calling_uid() -> uid_t {
50 // The caller and this process share the same UID.
51 UID_CURRENT.as_raw()
52}
53
54#[derive(Parser)]
55struct Args {
56 /// File descriptor inherited from the caller to run RpcBinder server on.
57 /// This should be one end of a socketpair() compatible with RpcBinder's
58 /// UDS bootstrap transport.
59 #[clap(long)]
60 rpc_server_fd: RawFd,
61 /// File descriptor inherited from the caller to signal RpcBinder server
62 /// readiness. This should be one end of pipe() and the caller should be
63 /// waiting for HUP on the other end.
64 #[clap(long)]
65 ready_fd: RawFd,
66}
67
68fn take_fd_ownership(raw_fd: RawFd, owned_fds: &mut Vec<RawFd>) -> Result<OwnedFd, anyhow::Error> {
69 // Basic check that the integer value does correspond to a file descriptor.
David Brazdil161ddda2023-01-06 20:29:19 +000070 fcntl(raw_fd, F_GETFD).with_context(|| format!("Invalid file descriptor {raw_fd}"))?;
71
72 // The file descriptor had CLOEXEC disabled to be inherited from the parent.
73 // Re-enable it to make sure it is not accidentally inherited further.
74 fcntl(raw_fd, F_SETFD(FdFlag::FD_CLOEXEC))
75 .with_context(|| format!("Could not set CLOEXEC on file descriptor {raw_fd}"))?;
David Brazdil1f530702022-10-03 12:18:10 +010076
77 // Creating OwnedFd for stdio FDs is not safe.
78 if [libc::STDIN_FILENO, libc::STDOUT_FILENO, libc::STDERR_FILENO].contains(&raw_fd) {
79 bail!("File descriptor {raw_fd} is standard I/O descriptor");
80 }
81
82 // Reject RawFds that already have a corresponding OwnedFd.
83 if owned_fds.contains(&raw_fd) {
84 bail!("File descriptor {raw_fd} already owned");
85 }
86 owned_fds.push(raw_fd);
87
88 // SAFETY - Initializing OwnedFd for a RawFd provided in cmdline arguments.
89 // We checked that the integer value corresponds to a valid FD and that this
90 // is the first argument to claim its ownership.
91 Ok(unsafe { OwnedFd::from_raw_fd(raw_fd) })
92}
93
Alan Stokesc4d5def2023-02-14 17:01:59 +000094fn check_vm_support() -> Result<()> {
95 if hypervisor_props::is_any_vm_supported()? {
96 Ok(())
97 } else {
98 // This should never happen, it indicates a misconfigured device where the virt APEX
99 // is present but VMs are not supported. If it does happen, fail fast to avoid wasting
100 // resources trying.
101 bail!("Device doesn't support protected or non-protected VMs")
102 }
Alan Stokes8d39a9b2023-01-10 15:01:00 +0000103}
104
David Brazdil1f530702022-10-03 12:18:10 +0100105fn main() {
106 android_logger::init_once(
107 android_logger::Config::default()
108 .with_tag(LOG_TAG)
109 .with_min_level(Level::Info)
110 .with_log_id(android_logger::LogId::System),
111 );
112
Alan Stokesc4d5def2023-02-14 17:01:59 +0000113 check_vm_support().unwrap();
Alan Stokes8d39a9b2023-01-10 15:01:00 +0000114
David Brazdil1f530702022-10-03 12:18:10 +0100115 let args = Args::parse();
116
117 let mut owned_fds = vec![];
118 let rpc_server_fd = take_fd_ownership(args.rpc_server_fd, &mut owned_fds)
119 .expect("Failed to take ownership of rpc_server_fd");
120 let ready_fd = take_fd_ownership(args.ready_fd, &mut owned_fds)
121 .expect("Failed to take ownership of ready_fd");
122
David Brazdil4b4c5102022-12-19 22:56:20 +0000123 // Start thread pool for kernel Binder connection to VirtualizationServiceInternal.
124 ProcessState::start_thread_pool();
125
126 GLOBAL_SERVICE.removeMemlockRlimit().expect("Failed to remove memlock rlimit");
127
David Brazdil1f530702022-10-03 12:18:10 +0100128 let service = VirtualizationService::init();
129 let service =
130 BnVirtualizationService::new_binder(service, BinderFeatures::default()).as_binder();
131
132 let server = RpcServer::new_unix_domain_bootstrap(service, rpc_server_fd)
133 .expect("Failed to start RpcServer");
134 server.set_supported_file_descriptor_transport_modes(&[FileDescriptorTransportMode::Unix]);
135
136 info!("Started VirtualizationService RpcServer. Ready to accept connections");
137
138 // Signal readiness to the caller by closing our end of the pipe.
139 drop(ready_fd);
140
141 server.join();
142 info!("Shutting down VirtualizationService RpcServer");
143}