blob: 16c35106ca86d740df2c14d594a025ed3c7427e3 [file] [log] [blame]
Victor Hsieh272aa242021-02-01 14:19:20 -08001/*
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
17//! compsvc is a service to run computational tasks in a PVM upon request. It is able to set up
18//! file descriptors backed by fd_server and pass the file descriptors to the actual tasks for
19//! read/write. The service also attempts to sandbox the execution so that one task cannot leak or
20//! impact future tasks.
21//!
22//! Example:
23//! $ compsvc /system/bin/sleep
24//!
25//! The current architecture / process hierarchy looks like:
26//! - compsvc (handle requests)
27//! - compsvc_worker (for environment setup)
28//! - authfs (fd translation)
29//! - actual task
30
31use anyhow::{bail, Context, Result};
Victor Hsieha7d37862021-06-04 17:14:20 -070032use binder::unstable_api::AsNative;
33use log::{debug, error};
Victor Hsieh272aa242021-02-01 14:19:20 -080034use minijail::{self, Minijail};
35use std::path::PathBuf;
36
37use compos_aidl_interface::aidl::com::android::compos::ICompService::{
38 BnCompService, ICompService,
39};
40use compos_aidl_interface::aidl::com::android::compos::Metadata::Metadata;
41use compos_aidl_interface::binder::{
42 add_service, BinderFeatures, Interface, ProcessState, Result as BinderResult, Status,
43 StatusCode, Strong,
44};
45
Victor Hsieha7d37862021-06-04 17:14:20 -070046mod common;
47use common::{SERVICE_NAME, VSOCK_PORT};
48
Victor Hsiehb5f465a2021-05-11 13:45:15 -070049const WORKER_BIN: &str = "/apex/com.android.compos/bin/compsvc_worker";
Victor Hsieh272aa242021-02-01 14:19:20 -080050// TODO: Replace with a valid directory setup in the VM.
51const AUTHFS_MOUNTPOINT: &str = "/data/local/tmp/authfs_mnt";
52
53struct CompService {
54 worker_bin: PathBuf,
55 task_bin: String,
Victor Hsieha7d37862021-06-04 17:14:20 -070056 rpc_binder: bool,
Victor Hsieh272aa242021-02-01 14:19:20 -080057 debuggable: bool,
58}
59
60impl CompService {
61 pub fn new_binder(service: CompService) -> Strong<dyn ICompService> {
62 BnCompService::new_binder(service, BinderFeatures::default())
63 }
64
65 fn run_worker_in_jail_and_wait(&self, args: &[String]) -> Result<(), minijail::Error> {
66 let mut jail = Minijail::new()?;
67
68 // TODO(b/185175567): New user and uid namespace when supported. Run as nobody.
69 // New mount namespace to isolate the FUSE mount.
70 jail.namespace_vfs();
71
72 let inheritable_fds = if self.debuggable {
73 vec![1, 2] // inherit/redirect stdout/stderr for debugging
74 } else {
75 vec![]
76 };
77 let _pid = jail.run(&self.worker_bin, &inheritable_fds, &args)?;
78 jail.wait()
79 }
80
81 fn build_worker_args(&self, args: &[String], metadata: &Metadata) -> Vec<String> {
82 let mut worker_args = vec![
83 WORKER_BIN.to_string(),
84 "--authfs-root".to_string(),
85 AUTHFS_MOUNTPOINT.to_string(),
86 ];
87 for annotation in &metadata.input_fd_annotations {
88 worker_args.push("--in-fd".to_string());
89 worker_args.push(format!("{}:{}", annotation.fd, annotation.file_size));
90 }
91 for annotation in &metadata.output_fd_annotations {
92 worker_args.push("--out-fd".to_string());
93 worker_args.push(annotation.fd.to_string());
94 }
95 if self.debuggable {
96 worker_args.push("--debug".to_string());
97 }
98 worker_args.push("--".to_string());
99
100 // Do not accept arbitrary code execution. We want to execute some specific task of this
101 // service. Use the associated executable.
102 worker_args.push(self.task_bin.clone());
103 worker_args.extend_from_slice(&args[1..]);
104 worker_args
105 }
106}
107
108impl Interface for CompService {}
109
110impl ICompService for CompService {
111 fn execute(&self, args: &[String], metadata: &Metadata) -> BinderResult<i8> {
112 let worker_args = self.build_worker_args(args, metadata);
113
114 match self.run_worker_in_jail_and_wait(&worker_args) {
115 Ok(_) => Ok(0), // TODO(b/161471326): Sign the output on succeed.
116 Err(minijail::Error::ReturnCode(exit_code)) => {
117 error!("Task failed with exit code {}", exit_code);
118 Err(Status::from(StatusCode::FAILED_TRANSACTION))
119 }
120 Err(e) => {
121 error!("Unexpected error: {}", e);
122 Err(Status::from(StatusCode::UNKNOWN_ERROR))
123 }
124 }
125 }
126}
127
128fn parse_args() -> Result<CompService> {
129 #[rustfmt::skip]
130 let matches = clap::App::new("compsvc")
131 .arg(clap::Arg::with_name("debug")
132 .long("debug"))
133 .arg(clap::Arg::with_name("task_bin")
134 .required(true))
Victor Hsieha7d37862021-06-04 17:14:20 -0700135 .arg(clap::Arg::with_name("rpc_binder")
136 .long("rpc-binder"))
Victor Hsieh272aa242021-02-01 14:19:20 -0800137 .get_matches();
138
139 Ok(CompService {
140 task_bin: matches.value_of("task_bin").unwrap().to_string(),
141 worker_bin: PathBuf::from(WORKER_BIN),
Victor Hsieha7d37862021-06-04 17:14:20 -0700142 rpc_binder: matches.is_present("rpc_binder"),
Victor Hsieh272aa242021-02-01 14:19:20 -0800143 debuggable: matches.is_present("debug"),
144 })
145}
146
147fn main() -> Result<()> {
148 android_logger::init_once(
149 android_logger::Config::default().with_tag("compsvc").with_min_level(log::Level::Debug),
150 );
151
152 let service = parse_args()?;
153
Victor Hsieha7d37862021-06-04 17:14:20 -0700154 if service.rpc_binder {
155 let mut service = CompService::new_binder(service).as_binder();
156 debug!("compsvc is starting as a rpc service.");
157 // SAFETY: Service ownership is transferring to the server and won't be valid afterward.
158 // Plus the binder objects are threadsafe.
159 let retval = unsafe {
160 binder_rpc_unstable_bindgen::RunRpcServer(
161 service.as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder,
162 VSOCK_PORT,
163 )
164 };
165 if retval {
166 debug!("RPC server has shut down gracefully");
167 Ok(())
168 } else {
169 bail!("Premature termination of RPC server");
170 }
171 } else {
172 ProcessState::start_thread_pool();
173 debug!("compsvc is starting as a local service.");
174 add_service(SERVICE_NAME, CompService::new_binder(service).as_binder())
175 .with_context(|| format!("Failed to register service {}", SERVICE_NAME))?;
176 ProcessState::join_thread_pool();
177 bail!("Unexpected exit after join_thread_pool")
178 }
Victor Hsieh272aa242021-02-01 14:19:20 -0800179}