blob: cbd77127d913b510815c1c612a993b786d34014a [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
17//! This program is a constrained file/FD server to serve file requests through a remote[1] 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//! [1] Since the remote binder is not ready, this currently implementation uses local binder
26//! first.
27
28use std::cmp::min;
29use std::collections::BTreeMap;
30use std::convert::TryInto;
31use std::ffi::CString;
32use std::fs::File;
33use std::io;
34use std::os::unix::fs::FileExt;
35use std::os::unix::io::FromRawFd;
36
37use anyhow::{bail, Context, Result};
38use binder::IBinder; // TODO(178852354): remove once set_requesting_sid is exposed in the API.
39use log::{debug, error};
40
41use authfs_aidl_interface::aidl::com::android::virt::fs::IVirtFdService::{
42 BnVirtFdService, IVirtFdService, ERROR_IO, ERROR_UNKNOWN_FD, MAX_REQUESTING_DATA,
43};
44use authfs_aidl_interface::binder::{
45 add_service, ExceptionCode, Interface, ProcessState, Result as BinderResult, Status, Strong,
46};
47
48const SERVICE_NAME: &str = "authfs_fd_server";
49
50fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status {
51 Status::new_exception(exception, CString::new(message.as_ref()).as_deref().ok())
52}
53
54fn validate_and_cast_offset(offset: i64) -> Result<u64, Status> {
55 offset.try_into().map_err(|_| {
56 new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, format!("Invalid offset: {}", offset))
57 })
58}
59
60fn validate_and_cast_size(size: i32) -> Result<usize, Status> {
61 if size > MAX_REQUESTING_DATA {
62 Err(new_binder_exception(
63 ExceptionCode::ILLEGAL_ARGUMENT,
64 format!("Unexpectedly large size: {}", size),
65 ))
66 } else {
67 size.try_into().map_err(|_| {
68 new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, format!("Invalid size: {}", size))
69 })
70 }
71}
72
73/// Configuration of a read-only file to serve by this server. The file is supposed to be verifiable
74/// with the associated fs-verity metadata.
75struct ReadonlyFdConfig {
76 /// The file to read from. fs-verity metadata can be retrieved from this file's FD.
77 file: File,
78
79 /// Alternative Merkle tree stored in another file.
80 alt_merkle_file: Option<File>,
81
82 /// Alternative signature stored in another file.
83 alt_signature_file: Option<File>,
84}
85
86struct FdService {
87 /// A pool of read-only files
88 fd_pool: BTreeMap<i32, ReadonlyFdConfig>,
89}
90
91impl FdService {
92 pub fn new_binder(fd_pool: BTreeMap<i32, ReadonlyFdConfig>) -> Strong<dyn IVirtFdService> {
93 let result = BnVirtFdService::new_binder(FdService { fd_pool });
94 result.as_binder().set_requesting_sid(false);
95 result
96 }
97
98 fn get_file_config(&self, id: i32) -> BinderResult<&ReadonlyFdConfig> {
99 self.fd_pool.get(&id).ok_or_else(|| Status::from(ERROR_UNKNOWN_FD))
100 }
101
102 fn get_file(&self, id: i32) -> BinderResult<&File> {
103 Ok(&self.get_file_config(id)?.file)
104 }
105}
106
107impl Interface for FdService {}
108
109impl IVirtFdService for FdService {
110 fn readFile(&self, id: i32, offset: i64, size: i32) -> BinderResult<Vec<u8>> {
111 let size: usize = validate_and_cast_size(size)?;
112 let offset: u64 = validate_and_cast_offset(offset)?;
113
114 read_into_buf(self.get_file(id)?, size, offset).map_err(|e| {
115 error!("readFile: read error: {}", e);
116 Status::from(ERROR_IO)
117 })
118 }
119
120 fn readFsverityMerkleTree(&self, id: i32, offset: i64, size: i32) -> BinderResult<Vec<u8>> {
121 let size: usize = validate_and_cast_size(size)?;
122 let offset: u64 = validate_and_cast_offset(offset)?;
123
124 if let Some(file) = &self.get_file_config(id)?.alt_merkle_file {
125 read_into_buf(&file, size, offset).map_err(|e| {
126 error!("readFsverityMerkleTree: read error: {}", e);
127 Status::from(ERROR_IO)
128 })
129 } else {
130 // TODO(victorhsieh) retrieve from the fd when the new ioctl is ready
131 Err(new_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION, "Not implemented yet"))
132 }
133 }
134
135 fn readFsveritySignature(&self, id: i32) -> BinderResult<Vec<u8>> {
136 if let Some(file) = &self.get_file_config(id)?.alt_signature_file {
137 // Supposedly big enough buffer size to store signature.
138 let size = MAX_REQUESTING_DATA as usize;
139 read_into_buf(&file, size, 0).map_err(|e| {
140 error!("readFsveritySignature: read error: {}", e);
141 Status::from(ERROR_IO)
142 })
143 } else {
144 // TODO(victorhsieh) retrieve from the fd when the new ioctl is ready
145 Err(new_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION, "Not implemented yet"))
146 }
147 }
148}
149
150fn read_into_buf(file: &File, max_size: usize, offset: u64) -> io::Result<Vec<u8>> {
151 let remaining = file.metadata()?.len().saturating_sub(offset);
152 let buf_size = min(remaining, max_size as u64) as usize;
153 let mut buf = vec![0; buf_size];
154 file.read_exact_at(&mut buf, offset)?;
155 Ok(buf)
156}
157
158fn is_fd_valid(fd: i32) -> bool {
159 // SAFETY: a query-only syscall
160 let retval = unsafe { libc::fcntl(fd, libc::F_GETFD) };
161 retval >= 0
162}
163
164fn fd_to_file(fd: i32) -> Result<File> {
165 if !is_fd_valid(fd) {
166 bail!("Bad FD: {}", fd);
167 }
168 // SAFETY: The caller is supposed to provide valid FDs to this process.
169 Ok(unsafe { File::from_raw_fd(fd) })
170}
171
172fn parse_arg_ro_fds(arg: &str) -> Result<(i32, ReadonlyFdConfig)> {
173 let result: Result<Vec<i32>, _> = arg.split(':').map(|x| x.parse::<i32>()).collect();
174 let fds = result?;
175 if fds.len() > 3 {
176 bail!("Too many options: {}", arg);
177 }
178
179 Ok((
180 fds[0],
181 ReadonlyFdConfig {
182 file: fd_to_file(fds[0])?,
183 alt_merkle_file: fds.get(1).map(|fd| fd_to_file(*fd)).transpose()?,
184 alt_signature_file: fds.get(2).map(|fd| fd_to_file(*fd)).transpose()?,
185 },
186 ))
187}
188
189fn parse_args() -> Result<BTreeMap<i32, ReadonlyFdConfig>> {
190 #[rustfmt::skip]
191 let matches = clap::App::new("fd_server")
192 .arg(clap::Arg::with_name("ro-fds")
193 .long("ro-fds")
194 .required(true)
195 .multiple(true)
196 .number_of_values(1))
197 .get_matches();
198
199 let mut fd_pool = BTreeMap::new();
200 if let Some(args) = matches.values_of("ro-fds") {
201 for arg in args {
202 let (fd, config) = parse_arg_ro_fds(arg)?;
203 fd_pool.insert(fd, config);
204 }
205 }
206 Ok(fd_pool)
207}
208
209fn main() -> Result<()> {
210 let fd_pool = parse_args()?;
211
212 ProcessState::start_thread_pool();
213
214 add_service(SERVICE_NAME, FdService::new_binder(fd_pool).as_binder())
215 .with_context(|| format!("Failed to register service {}", SERVICE_NAME))?;
216 debug!("fd_server is running.");
217
218 ProcessState::join_thread_pool();
219 bail!("Unexpected exit after join_thread_pool")
220}