1 /*
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 //! This program is a constrained file/FD server to serve file requests through a remote binder
18 //! 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.
24
25 mod aidl;
26
27 use anyhow::{bail, Result};
28 use clap::Parser;
29 use log::debug;
30 use nix::sys::stat::{umask, Mode};
31 use rpcbinder::RpcServer;
32 use rustutils::inherited_fd::take_fd_ownership;
33 use std::collections::BTreeMap;
34 use std::fs::File;
35 use std::os::unix::io::OwnedFd;
36
37 use aidl::{FdConfig, FdService};
38 use authfs_fsverity_metadata::parse_fsverity_metadata;
39
40 // TODO(b/259920193): support dynamic port for multiple fd_server instances
41 const RPC_SERVICE_PORT: u32 = 3264;
42
parse_arg_ro_fds(arg: &str) -> Result<(i32, FdConfig)>43 fn parse_arg_ro_fds(arg: &str) -> Result<(i32, FdConfig)> {
44 let result: Result<Vec<i32>, _> = arg.split(':').map(|x| x.parse::<i32>()).collect();
45 let fds = result?;
46 if fds.len() > 2 {
47 bail!("Too many options: {}", arg);
48 }
49 Ok((
50 fds[0],
51 FdConfig::Readonly {
52 file: take_fd_ownership(fds[0])?.into(),
53 // Alternative metadata source, if provided
54 alt_metadata: fds
55 .get(1)
56 .map(|fd| take_fd_ownership(*fd))
57 .transpose()?
58 .and_then(|f| parse_fsverity_metadata(f.into()).ok()),
59 },
60 ))
61 }
62
63 #[derive(Parser)]
64 struct Args {
65 /// Read-only FD of file, with optional FD of corresponding .fsv_meta, joined with a ':'.
66 /// Example: "1:2", "3".
67 #[clap(long)]
68 ro_fds: Vec<String>,
69
70 /// Read-writable FD of file
71 #[clap(long)]
72 rw_fds: Vec<i32>,
73
74 /// Read-only FD of directory
75 #[clap(long)]
76 ro_dirs: Vec<i32>,
77
78 /// Read-writable FD of directory
79 #[clap(long)]
80 rw_dirs: Vec<i32>,
81
82 /// A pipe FD for signaling the other end once ready
83 #[clap(long)]
84 ready_fd: Option<i32>,
85 }
86
87 /// Convert argument strings and integers to a form that is easier to use and handles ownership.
convert_args(args: Args) -> Result<(BTreeMap<i32, FdConfig>, Option<OwnedFd>)>88 fn convert_args(args: Args) -> Result<(BTreeMap<i32, FdConfig>, Option<OwnedFd>)> {
89 let mut fd_pool = BTreeMap::new();
90 for arg in args.ro_fds {
91 let (fd, config) = parse_arg_ro_fds(&arg)?;
92 fd_pool.insert(fd, config);
93 }
94 for fd in args.rw_fds {
95 let file: File = take_fd_ownership(fd)?.into();
96 if file.metadata()?.len() > 0 {
97 bail!("File is expected to be empty");
98 }
99 fd_pool.insert(fd, FdConfig::ReadWrite(file));
100 }
101 for fd in args.ro_dirs {
102 fd_pool.insert(fd, FdConfig::InputDir(take_fd_ownership(fd)?));
103 }
104 for fd in args.rw_dirs {
105 fd_pool.insert(fd, FdConfig::OutputDir(take_fd_ownership(fd)?));
106 }
107 let ready_fd = args.ready_fd.map(take_fd_ownership).transpose()?;
108 Ok((fd_pool, ready_fd))
109 }
110
main() -> Result<()>111 fn main() -> Result<()> {
112 // SAFETY: This is very early in the process. Nobody has taken ownership of the inherited FDs
113 // yet.
114 unsafe { rustutils::inherited_fd::init_once()? };
115
116 android_logger::init_once(
117 android_logger::Config::default()
118 .with_tag("fd_server")
119 .with_max_level(log::LevelFilter::Debug),
120 );
121
122 let args = Args::parse();
123 let (fd_pool, mut ready_fd) = convert_args(args)?;
124
125 // Allow open/create/mkdir from authfs to create with expecting mode. It's possible to still
126 // use a custom mask on creation, then report the actual file mode back to authfs. But there
127 // is no demand now.
128 let old_umask = umask(Mode::empty());
129 debug!("Setting umask to 0 (old: {:03o})", old_umask.bits());
130
131 debug!("fd_server is starting as a rpc service.");
132 let service = FdService::new_binder(fd_pool).as_binder();
133 // TODO(b/259920193): Only accept connections from the intended guest VM.
134 let (server, _) = RpcServer::new_vsock(service, libc::VMADDR_CID_ANY, RPC_SERVICE_PORT)?;
135 debug!("fd_server is ready");
136
137 // Close the ready-fd if we were given one to signal our readiness.
138 drop(ready_fd.take());
139
140 server.join();
141 Ok(())
142 }
143
144 #[cfg(test)]
145 mod tests {
146 use super::*;
147 use clap::CommandFactory;
148
149 #[test]
verify_args()150 fn verify_args() {
151 // Check that the command parsing has been configured in a valid way.
152 Args::command().debug_assert();
153 }
154 }
155