blob: f91ebeceb4fc2ad6dcbcea477f688a788c2b0101 [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};
Victor Hsieh543d1992022-09-14 15:35:51 -070029use clap::Parser;
Victor Hsiehb0f5fc82021-10-15 17:24:19 -070030use log::debug;
Victor Hsiehbf944d72022-03-07 23:46:43 +000031use nix::sys::stat::{umask, Mode};
David Brazdil671e6142022-11-16 11:47:27 +000032use rpcbinder::RpcServer;
Victor Hsieh42cc7762021-01-25 16:44:19 -080033use std::collections::BTreeMap;
Victor Hsieh42cc7762021-01-25 16:44:19 -080034use std::fs::File;
Victor Hsieh543d1992022-09-14 15:35:51 -070035use std::os::unix::io::{FromRawFd, OwnedFd};
Victor Hsieh42cc7762021-01-25 16:44:19 -080036
Victor Hsiehb0f5fc82021-10-15 17:24:19 -070037use aidl::{FdConfig, FdService};
Inseob Kimc0886c22021-12-13 17:41:24 +090038use authfs_fsverity_metadata::parse_fsverity_metadata;
Victor Hsieh42cc7762021-01-25 16:44:19 -080039
David Brazdil3238da42022-11-18 10:04:51 +000040// TODO(b/259920193): support dynamic port for multiple fd_server instances
41const RPC_SERVICE_PORT: u32 = 3264;
Victor Hsieh42cc7762021-01-25 16:44:19 -080042
Victor Hsieh42cc7762021-01-25 16:44:19 -080043fn is_fd_valid(fd: i32) -> bool {
44 // SAFETY: a query-only syscall
45 let retval = unsafe { libc::fcntl(fd, libc::F_GETFD) };
46 retval >= 0
47}
48
Victor Hsiehbf944d72022-03-07 23:46:43 +000049fn fd_to_owned<T: FromRawFd>(fd: i32) -> Result<T> {
Victor Hsieh42cc7762021-01-25 16:44:19 -080050 if !is_fd_valid(fd) {
51 bail!("Bad FD: {}", fd);
52 }
53 // SAFETY: The caller is supposed to provide valid FDs to this process.
Victor Hsiehbf944d72022-03-07 23:46:43 +000054 Ok(unsafe { T::from_raw_fd(fd) })
Victor Hsieh42cc7762021-01-25 16:44:19 -080055}
56
Victor Hsieh60acfd32021-02-23 13:08:13 -080057fn parse_arg_ro_fds(arg: &str) -> Result<(i32, FdConfig)> {
Victor Hsieh42cc7762021-01-25 16:44:19 -080058 let result: Result<Vec<i32>, _> = arg.split(':').map(|x| x.parse::<i32>()).collect();
59 let fds = result?;
Inseob Kimc0886c22021-12-13 17:41:24 +090060 if fds.len() > 2 {
Victor Hsieh42cc7762021-01-25 16:44:19 -080061 bail!("Too many options: {}", arg);
62 }
Victor Hsieh42cc7762021-01-25 16:44:19 -080063 Ok((
64 fds[0],
Victor Hsieh60acfd32021-02-23 13:08:13 -080065 FdConfig::Readonly {
Victor Hsiehbf944d72022-03-07 23:46:43 +000066 file: fd_to_owned(fds[0])?,
Inseob Kimc0886c22021-12-13 17:41:24 +090067 // Alternative metadata source, if provided
68 alt_metadata: fds
69 .get(1)
Victor Hsiehbf944d72022-03-07 23:46:43 +000070 .map(|fd| fd_to_owned(*fd))
Inseob Kimc0886c22021-12-13 17:41:24 +090071 .transpose()?
72 .and_then(|f| parse_fsverity_metadata(f).ok()),
Victor Hsieh42cc7762021-01-25 16:44:19 -080073 },
74 ))
75}
76
Victor Hsieh543d1992022-09-14 15:35:51 -070077#[derive(Parser)]
Alan Stokese1b6e1c2021-10-01 12:44:49 +010078struct Args {
Victor Hsieh543d1992022-09-14 15:35:51 -070079 /// Read-only FD of file, with optional FD of corresponding .fsv_meta, joined with a ':'.
80 /// Example: "1:2", "3".
81 #[clap(long)]
82 ro_fds: Vec<String>,
83
84 /// Read-writable FD of file
85 #[clap(long)]
86 rw_fds: Vec<i32>,
87
88 /// Read-only FD of directory
89 #[clap(long)]
90 ro_dirs: Vec<i32>,
91
92 /// Read-writable FD of directory
93 #[clap(long)]
94 rw_dirs: Vec<i32>,
95
96 /// A pipe FD for signaling the other end once ready
97 #[clap(long)]
98 ready_fd: Option<i32>,
Alan Stokese1b6e1c2021-10-01 12:44:49 +010099}
100
Victor Hsieh543d1992022-09-14 15:35:51 -0700101/// Convert argument strings and integers to a form that is easier to use and handles ownership.
102fn convert_args(args: Args) -> Result<(BTreeMap<i32, FdConfig>, Option<OwnedFd>)> {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800103 let mut fd_pool = BTreeMap::new();
Victor Hsieh543d1992022-09-14 15:35:51 -0700104 for arg in args.ro_fds {
105 let (fd, config) = parse_arg_ro_fds(&arg)?;
106 fd_pool.insert(fd, config);
Victor Hsieh42cc7762021-01-25 16:44:19 -0800107 }
Victor Hsieh543d1992022-09-14 15:35:51 -0700108 for fd in args.rw_fds {
109 let file = fd_to_owned::<File>(fd)?;
110 if file.metadata()?.len() > 0 {
111 bail!("File is expected to be empty");
Victor Hsieh60acfd32021-02-23 13:08:13 -0800112 }
Victor Hsieh543d1992022-09-14 15:35:51 -0700113 fd_pool.insert(fd, FdConfig::ReadWrite(file));
Victor Hsieh60acfd32021-02-23 13:08:13 -0800114 }
Victor Hsieh543d1992022-09-14 15:35:51 -0700115 for fd in args.ro_dirs {
116 fd_pool.insert(fd, FdConfig::InputDir(fd_to_owned(fd)?));
Victor Hsieh559b9272021-11-08 15:15:14 -0800117 }
Victor Hsieh543d1992022-09-14 15:35:51 -0700118 for fd in args.rw_dirs {
119 fd_pool.insert(fd, FdConfig::OutputDir(fd_to_owned(fd)?));
Victor Hsieh45636232021-10-15 17:52:51 -0700120 }
Victor Hsieh543d1992022-09-14 15:35:51 -0700121 let ready_fd = args.ready_fd.map(fd_to_owned).transpose()?;
122 Ok((fd_pool, ready_fd))
Victor Hsieh42cc7762021-01-25 16:44:19 -0800123}
124
125fn main() -> Result<()> {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800126 android_logger::init_once(
127 android_logger::Config::default().with_tag("fd_server").with_min_level(log::Level::Debug),
128 );
129
Victor Hsieh543d1992022-09-14 15:35:51 -0700130 let args = Args::parse();
131 let (fd_pool, mut ready_fd) = convert_args(args)?;
Victor Hsieh8e285112021-12-10 11:17:26 -0800132
133 // Allow open/create/mkdir from authfs to create with expecting mode. It's possible to still
134 // use a custom mask on creation, then report the actual file mode back to authfs. But there
135 // is no demand now.
136 let old_umask = umask(Mode::empty());
137 debug!("Setting umask to 0 (old: {:03o})", old_umask.bits());
138
Victor Hsieh1a8cd042021-09-03 16:29:45 -0700139 debug!("fd_server is starting as a rpc service.");
David Brazdil671e6142022-11-16 11:47:27 +0000140 let service = FdService::new_binder(fd_pool).as_binder();
David Brazdil3238da42022-11-18 10:04:51 +0000141 // TODO(b/259920193): Only accept connections from the intended guest VM.
142 let server = RpcServer::new_vsock(service, libc::VMADDR_CID_ANY, RPC_SERVICE_PORT)?;
David Brazdil671e6142022-11-16 11:47:27 +0000143 debug!("fd_server is ready");
Alan Stokescd359bb2021-10-08 18:22:42 +0100144
David Brazdil671e6142022-11-16 11:47:27 +0000145 // Close the ready-fd if we were given one to signal our readiness.
146 drop(ready_fd.take());
147
148 server.join();
149 Ok(())
Victor Hsieh42cc7762021-01-25 16:44:19 -0800150}
Andrew Walbranda8786d2022-12-01 14:54:27 +0000151
152#[cfg(test)]
153mod tests {
154 use super::*;
155 use clap::CommandFactory;
156
157 #[test]
158 fn verify_args() {
159 // Check that the command parsing has been configured in a valid way.
160 Args::command().debug_assert();
161 }
162}