blob: 3413ce6d0a7009856fe09bd160b459bd2ca2c58e [file] [log] [blame]
Victor Hsieh42cc7762021-01-25 16:44:19 -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
Victor Hsieh1a8cd042021-09-03 16:29:45 -070017//! This program is a constrained file/FD server to serve file requests through a remote binder
Victor Hsieh42cc7762021-01-25 16:44:19 -080018//! service. The file server is not designed to serve arbitrary file paths in the filesystem. On
19//! the contrary, the server should be configured to start with already opened FDs, and serve the
20//! client's request against the FDs
21//!
22//! For example, `exec 9</path/to/file fd_server --ro-fds 9` starts the binder service. A client
23//! client can then request the content of file 9 by offset and size.
Victor Hsieh42cc7762021-01-25 16:44:19 -080024
Victor Hsiehb0f5fc82021-10-15 17:24:19 -070025mod aidl;
Victor Hsieh4dc85c92021-03-15 11:01:23 -070026mod fsverity;
27
Victor Hsieh1a8cd042021-09-03 16:29:45 -070028use anyhow::{bail, Result};
Alan Stokescd359bb2021-10-08 18:22:42 +010029use binder_common::rpc_server::run_rpc_server;
Victor Hsiehb0f5fc82021-10-15 17:24:19 -070030use log::debug;
Victor Hsieh42cc7762021-01-25 16:44:19 -080031use std::collections::BTreeMap;
Victor Hsieh42cc7762021-01-25 16:44:19 -080032use std::fs::File;
Victor Hsiehb0f5fc82021-10-15 17:24:19 -070033use std::os::unix::io::FromRawFd;
Victor Hsieh42cc7762021-01-25 16:44:19 -080034
Victor Hsiehb0f5fc82021-10-15 17:24:19 -070035use aidl::{FdConfig, FdService};
Victor Hsieh42cc7762021-01-25 16:44:19 -080036
Victor Hsieh2445e332021-06-04 16:44:53 -070037const RPC_SERVICE_PORT: u32 = 3264; // TODO: support dynamic port for multiple fd_server instances
Victor Hsieh42cc7762021-01-25 16:44:19 -080038
Victor Hsieh42cc7762021-01-25 16:44:19 -080039fn is_fd_valid(fd: i32) -> bool {
40 // SAFETY: a query-only syscall
41 let retval = unsafe { libc::fcntl(fd, libc::F_GETFD) };
42 retval >= 0
43}
44
45fn fd_to_file(fd: i32) -> Result<File> {
46 if !is_fd_valid(fd) {
47 bail!("Bad FD: {}", fd);
48 }
49 // SAFETY: The caller is supposed to provide valid FDs to this process.
50 Ok(unsafe { File::from_raw_fd(fd) })
51}
52
Victor Hsieh60acfd32021-02-23 13:08:13 -080053fn parse_arg_ro_fds(arg: &str) -> Result<(i32, FdConfig)> {
Victor Hsieh42cc7762021-01-25 16:44:19 -080054 let result: Result<Vec<i32>, _> = arg.split(':').map(|x| x.parse::<i32>()).collect();
55 let fds = result?;
56 if fds.len() > 3 {
57 bail!("Too many options: {}", arg);
58 }
Victor Hsieh42cc7762021-01-25 16:44:19 -080059 Ok((
60 fds[0],
Victor Hsieh60acfd32021-02-23 13:08:13 -080061 FdConfig::Readonly {
Victor Hsieh42cc7762021-01-25 16:44:19 -080062 file: fd_to_file(fds[0])?,
Victor Hsieh60acfd32021-02-23 13:08:13 -080063 // Alternative Merkle tree, if provided
64 alt_merkle_tree: fds.get(1).map(|fd| fd_to_file(*fd)).transpose()?,
65 // Alternative signature, if provided
66 alt_signature: fds.get(2).map(|fd| fd_to_file(*fd)).transpose()?,
Victor Hsieh42cc7762021-01-25 16:44:19 -080067 },
68 ))
69}
70
Victor Hsieh60acfd32021-02-23 13:08:13 -080071fn parse_arg_rw_fds(arg: &str) -> Result<(i32, FdConfig)> {
72 let fd = arg.parse::<i32>()?;
73 let file = fd_to_file(fd)?;
74 if file.metadata()?.len() > 0 {
75 bail!("File is expected to be empty");
76 }
77 Ok((fd, FdConfig::ReadWrite(file)))
78}
79
Alan Stokese1b6e1c2021-10-01 12:44:49 +010080struct Args {
81 fd_pool: BTreeMap<i32, FdConfig>,
82 ready_fd: Option<File>,
83}
84
85fn parse_args() -> Result<Args> {
Victor Hsieh42cc7762021-01-25 16:44:19 -080086 #[rustfmt::skip]
87 let matches = clap::App::new("fd_server")
88 .arg(clap::Arg::with_name("ro-fds")
89 .long("ro-fds")
Victor Hsieh60acfd32021-02-23 13:08:13 -080090 .multiple(true)
91 .number_of_values(1))
92 .arg(clap::Arg::with_name("rw-fds")
93 .long("rw-fds")
Victor Hsieh42cc7762021-01-25 16:44:19 -080094 .multiple(true)
95 .number_of_values(1))
Alan Stokese1b6e1c2021-10-01 12:44:49 +010096 .arg(clap::Arg::with_name("ready-fd")
97 .long("ready-fd")
98 .takes_value(true))
Victor Hsieh42cc7762021-01-25 16:44:19 -080099 .get_matches();
100
101 let mut fd_pool = BTreeMap::new();
102 if let Some(args) = matches.values_of("ro-fds") {
103 for arg in args {
104 let (fd, config) = parse_arg_ro_fds(arg)?;
105 fd_pool.insert(fd, config);
106 }
107 }
Victor Hsieh60acfd32021-02-23 13:08:13 -0800108 if let Some(args) = matches.values_of("rw-fds") {
109 for arg in args {
110 let (fd, config) = parse_arg_rw_fds(arg)?;
111 fd_pool.insert(fd, config);
112 }
113 }
Alan Stokese1b6e1c2021-10-01 12:44:49 +0100114 let ready_fd = if let Some(arg) = matches.value_of("ready-fd") {
115 let fd = arg.parse::<i32>()?;
116 Some(fd_to_file(fd)?)
117 } else {
118 None
119 };
120 Ok(Args { fd_pool, ready_fd })
Victor Hsieh42cc7762021-01-25 16:44:19 -0800121}
122
123fn main() -> Result<()> {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800124 android_logger::init_once(
125 android_logger::Config::default().with_tag("fd_server").with_min_level(log::Level::Debug),
126 );
127
Alan Stokese1b6e1c2021-10-01 12:44:49 +0100128 let args = parse_args()?;
Alan Stokescd359bb2021-10-08 18:22:42 +0100129 let service = FdService::new_binder(args.fd_pool).as_binder();
Alan Stokese1b6e1c2021-10-01 12:44:49 +0100130
Victor Hsieh1a8cd042021-09-03 16:29:45 -0700131 debug!("fd_server is starting as a rpc service.");
Alan Stokescd359bb2021-10-08 18:22:42 +0100132
133 let mut ready_fd = args.ready_fd;
134 let retval = run_rpc_server(service, RPC_SERVICE_PORT, || {
135 debug!("fd_server is ready");
136 // Close the ready-fd if we were given one to signal our readiness.
137 drop(ready_fd.take());
138 });
139
Victor Hsieh1a8cd042021-09-03 16:29:45 -0700140 if retval {
141 debug!("RPC server has shut down gracefully");
142 Ok(())
Victor Hsieh2445e332021-06-04 16:44:53 -0700143 } else {
Victor Hsieh1a8cd042021-09-03 16:29:45 -0700144 bail!("Premature termination of RPC server");
Victor Hsieh2445e332021-06-04 16:44:53 -0700145 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800146}