Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 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 | |
Victor Hsieh | 1a8cd04 | 2021-09-03 16:29:45 -0700 | [diff] [blame] | 17 | //! This program is a constrained file/FD server to serve file requests through a remote binder |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 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. |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 24 | |
Victor Hsieh | 4dc85c9 | 2021-03-15 11:01:23 -0700 | [diff] [blame] | 25 | mod fsverity; |
| 26 | |
Victor Hsieh | 1a8cd04 | 2021-09-03 16:29:45 -0700 | [diff] [blame] | 27 | use anyhow::{bail, Result}; |
Victor Hsieh | 50d75ac | 2021-09-03 14:46:55 -0700 | [diff] [blame] | 28 | use binder::unstable_api::AsNative; |
| 29 | use log::{debug, error}; |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 30 | use std::cmp::min; |
| 31 | use std::collections::BTreeMap; |
| 32 | use std::convert::TryInto; |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 33 | use std::fs::File; |
| 34 | use std::io; |
Alan Stokes | e1b6e1c | 2021-10-01 12:44:49 +0100 | [diff] [blame^] | 35 | use std::os::raw; |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 36 | use std::os::unix::fs::FileExt; |
Victor Hsieh | 4dc85c9 | 2021-03-15 11:01:23 -0700 | [diff] [blame] | 37 | use std::os::unix::io::{AsRawFd, FromRawFd}; |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 38 | |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 39 | use authfs_aidl_interface::aidl::com::android::virt::fs::IVirtFdService::{ |
Victor Hsieh | 50d75ac | 2021-09-03 14:46:55 -0700 | [diff] [blame] | 40 | BnVirtFdService, IVirtFdService, ERROR_FILE_TOO_LARGE, ERROR_IO, ERROR_UNKNOWN_FD, |
| 41 | MAX_REQUESTING_DATA, |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 42 | }; |
| 43 | use authfs_aidl_interface::binder::{ |
Victor Hsieh | 1a8cd04 | 2021-09-03 16:29:45 -0700 | [diff] [blame] | 44 | BinderFeatures, ExceptionCode, Interface, Result as BinderResult, Status, StatusCode, Strong, |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 45 | }; |
Alan Stokes | 3189af0 | 2021-09-30 17:51:19 +0100 | [diff] [blame] | 46 | use binder_common::new_binder_exception; |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 47 | |
Victor Hsieh | 2445e33 | 2021-06-04 16:44:53 -0700 | [diff] [blame] | 48 | const RPC_SERVICE_PORT: u32 = 3264; // TODO: support dynamic port for multiple fd_server instances |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 49 | |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 50 | fn validate_and_cast_offset(offset: i64) -> Result<u64, Status> { |
| 51 | offset.try_into().map_err(|_| { |
| 52 | new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, format!("Invalid offset: {}", offset)) |
| 53 | }) |
| 54 | } |
| 55 | |
| 56 | fn validate_and_cast_size(size: i32) -> Result<usize, Status> { |
| 57 | if size > MAX_REQUESTING_DATA { |
| 58 | Err(new_binder_exception( |
| 59 | ExceptionCode::ILLEGAL_ARGUMENT, |
| 60 | format!("Unexpectedly large size: {}", size), |
| 61 | )) |
| 62 | } else { |
| 63 | size.try_into().map_err(|_| { |
| 64 | new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, format!("Invalid size: {}", size)) |
| 65 | }) |
| 66 | } |
| 67 | } |
| 68 | |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 69 | /// Configuration of a file descriptor to be served/exposed/shared. |
| 70 | enum FdConfig { |
| 71 | /// A read-only file to serve by this server. The file is supposed to be verifiable with the |
| 72 | /// associated fs-verity metadata. |
| 73 | Readonly { |
| 74 | /// The file to read from. fs-verity metadata can be retrieved from this file's FD. |
| 75 | file: File, |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 76 | |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 77 | /// Alternative Merkle tree stored in another file. |
| 78 | alt_merkle_tree: Option<File>, |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 79 | |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 80 | /// Alternative signature stored in another file. |
| 81 | alt_signature: Option<File>, |
| 82 | }, |
| 83 | |
| 84 | /// A readable/writable file to serve by this server. This backing file should just be a |
| 85 | /// regular file and does not have any specific property. |
| 86 | ReadWrite(File), |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 87 | } |
| 88 | |
| 89 | struct FdService { |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 90 | /// A pool of opened files, may be readonly or read-writable. |
| 91 | fd_pool: BTreeMap<i32, FdConfig>, |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 92 | } |
| 93 | |
| 94 | impl FdService { |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 95 | pub fn new_binder(fd_pool: BTreeMap<i32, FdConfig>) -> Strong<dyn IVirtFdService> { |
Andrew Walbran | 4de2878 | 2021-04-13 14:51:43 +0000 | [diff] [blame] | 96 | BnVirtFdService::new_binder(FdService { fd_pool }, BinderFeatures::default()) |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 97 | } |
| 98 | |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 99 | fn get_file_config(&self, id: i32) -> BinderResult<&FdConfig> { |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 100 | self.fd_pool.get(&id).ok_or_else(|| Status::from(ERROR_UNKNOWN_FD)) |
| 101 | } |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 102 | } |
| 103 | |
| 104 | impl Interface for FdService {} |
| 105 | |
| 106 | impl IVirtFdService for FdService { |
| 107 | fn readFile(&self, id: i32, offset: i64, size: i32) -> BinderResult<Vec<u8>> { |
| 108 | let size: usize = validate_and_cast_size(size)?; |
| 109 | let offset: u64 = validate_and_cast_offset(offset)?; |
| 110 | |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 111 | match self.get_file_config(id)? { |
| 112 | FdConfig::Readonly { file, .. } | FdConfig::ReadWrite(file) => { |
Chris Wailes | 68c39f8 | 2021-07-27 16:03:44 -0700 | [diff] [blame] | 113 | read_into_buf(file, size, offset).map_err(|e| { |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 114 | error!("readFile: read error: {}", e); |
| 115 | Status::from(ERROR_IO) |
| 116 | }) |
| 117 | } |
| 118 | } |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 119 | } |
| 120 | |
| 121 | fn readFsverityMerkleTree(&self, id: i32, offset: i64, size: i32) -> BinderResult<Vec<u8>> { |
| 122 | let size: usize = validate_and_cast_size(size)?; |
| 123 | let offset: u64 = validate_and_cast_offset(offset)?; |
| 124 | |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 125 | match &self.get_file_config(id)? { |
Victor Hsieh | 4dc85c9 | 2021-03-15 11:01:23 -0700 | [diff] [blame] | 126 | FdConfig::Readonly { file, alt_merkle_tree, .. } => { |
| 127 | if let Some(tree_file) = &alt_merkle_tree { |
Chris Wailes | 68c39f8 | 2021-07-27 16:03:44 -0700 | [diff] [blame] | 128 | read_into_buf(tree_file, size, offset).map_err(|e| { |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 129 | error!("readFsverityMerkleTree: read error: {}", e); |
| 130 | Status::from(ERROR_IO) |
| 131 | }) |
| 132 | } else { |
Victor Hsieh | 4dc85c9 | 2021-03-15 11:01:23 -0700 | [diff] [blame] | 133 | let mut buf = vec![0; size]; |
| 134 | let s = fsverity::read_merkle_tree(file.as_raw_fd(), offset, &mut buf) |
| 135 | .map_err(|e| { |
| 136 | error!("readFsverityMerkleTree: failed to retrieve merkle tree: {}", e); |
| 137 | Status::from(e.raw_os_error().unwrap_or(ERROR_IO)) |
| 138 | })?; |
| 139 | debug_assert!(s <= buf.len(), "Shouldn't return more bytes than asked"); |
| 140 | buf.truncate(s); |
| 141 | Ok(buf) |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 142 | } |
| 143 | } |
| 144 | FdConfig::ReadWrite(_file) => { |
| 145 | // For a writable file, Merkle tree is not expected to be served since Auth FS |
| 146 | // doesn't trust it anyway. Auth FS may keep the Merkle tree privately for its own |
| 147 | // use. |
| 148 | Err(new_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION, "Unsupported")) |
| 149 | } |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 150 | } |
| 151 | } |
| 152 | |
| 153 | fn readFsveritySignature(&self, id: i32) -> BinderResult<Vec<u8>> { |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 154 | match &self.get_file_config(id)? { |
Victor Hsieh | 4dc85c9 | 2021-03-15 11:01:23 -0700 | [diff] [blame] | 155 | FdConfig::Readonly { file, alt_signature, .. } => { |
| 156 | if let Some(sig_file) = &alt_signature { |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 157 | // Supposedly big enough buffer size to store signature. |
| 158 | let size = MAX_REQUESTING_DATA as usize; |
Victor Hsieh | 4dc85c9 | 2021-03-15 11:01:23 -0700 | [diff] [blame] | 159 | let offset = 0; |
Chris Wailes | 68c39f8 | 2021-07-27 16:03:44 -0700 | [diff] [blame] | 160 | read_into_buf(sig_file, size, offset).map_err(|e| { |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 161 | error!("readFsveritySignature: read error: {}", e); |
| 162 | Status::from(ERROR_IO) |
| 163 | }) |
| 164 | } else { |
Victor Hsieh | 4dc85c9 | 2021-03-15 11:01:23 -0700 | [diff] [blame] | 165 | let mut buf = vec![0; MAX_REQUESTING_DATA as usize]; |
| 166 | let s = fsverity::read_signature(file.as_raw_fd(), &mut buf).map_err(|e| { |
| 167 | error!("readFsverityMerkleTree: failed to retrieve merkle tree: {}", e); |
| 168 | Status::from(e.raw_os_error().unwrap_or(ERROR_IO)) |
| 169 | })?; |
| 170 | debug_assert!(s <= buf.len(), "Shouldn't return more bytes than asked"); |
| 171 | buf.truncate(s); |
| 172 | Ok(buf) |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 173 | } |
| 174 | } |
| 175 | FdConfig::ReadWrite(_file) => { |
| 176 | // There is no signature for a writable file. |
| 177 | Err(new_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION, "Unsupported")) |
| 178 | } |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | fn writeFile(&self, id: i32, buf: &[u8], offset: i64) -> BinderResult<i32> { |
| 183 | match &self.get_file_config(id)? { |
| 184 | FdConfig::Readonly { .. } => Err(StatusCode::INVALID_OPERATION.into()), |
| 185 | FdConfig::ReadWrite(file) => { |
| 186 | let offset: u64 = offset.try_into().map_err(|_| { |
| 187 | new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, "Invalid offset") |
| 188 | })?; |
| 189 | // Check buffer size just to make `as i32` safe below. |
| 190 | if buf.len() > i32::MAX as usize { |
| 191 | return Err(new_binder_exception( |
| 192 | ExceptionCode::ILLEGAL_ARGUMENT, |
| 193 | "Buffer size is too big", |
| 194 | )); |
| 195 | } |
| 196 | Ok(file.write_at(buf, offset).map_err(|e| { |
| 197 | error!("writeFile: write error: {}", e); |
| 198 | Status::from(ERROR_IO) |
| 199 | })? as i32) |
| 200 | } |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 201 | } |
| 202 | } |
Victor Hsieh | 9d0ab62 | 2021-04-26 17:07:02 -0700 | [diff] [blame] | 203 | |
| 204 | fn resize(&self, id: i32, size: i64) -> BinderResult<()> { |
| 205 | match &self.get_file_config(id)? { |
| 206 | FdConfig::Readonly { .. } => Err(StatusCode::INVALID_OPERATION.into()), |
| 207 | FdConfig::ReadWrite(file) => { |
| 208 | if size < 0 { |
| 209 | return Err(new_binder_exception( |
| 210 | ExceptionCode::ILLEGAL_ARGUMENT, |
| 211 | "Invalid size to resize to", |
| 212 | )); |
| 213 | } |
| 214 | file.set_len(size as u64).map_err(|e| { |
| 215 | error!("resize: set_len error: {}", e); |
| 216 | Status::from(ERROR_IO) |
| 217 | }) |
| 218 | } |
| 219 | } |
| 220 | } |
Victor Hsieh | 50d75ac | 2021-09-03 14:46:55 -0700 | [diff] [blame] | 221 | |
| 222 | fn getFileSize(&self, id: i32) -> BinderResult<i64> { |
| 223 | match &self.get_file_config(id)? { |
| 224 | FdConfig::Readonly { file, .. } => { |
| 225 | let size = file |
| 226 | .metadata() |
| 227 | .map_err(|e| { |
| 228 | error!("getFileSize error: {}", e); |
| 229 | Status::from(ERROR_IO) |
| 230 | })? |
| 231 | .len(); |
| 232 | Ok(size.try_into().map_err(|e| { |
| 233 | error!("getFileSize: File too large: {}", e); |
| 234 | Status::from(ERROR_FILE_TOO_LARGE) |
| 235 | })?) |
| 236 | } |
| 237 | FdConfig::ReadWrite(_file) => { |
| 238 | // Content and metadata of a writable file needs to be tracked by authfs, since |
| 239 | // fd_server isn't considered trusted. So there is no point to support getFileSize |
| 240 | // for a writable file. |
| 241 | Err(new_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION, "Unsupported")) |
| 242 | } |
| 243 | } |
| 244 | } |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 245 | } |
| 246 | |
| 247 | fn read_into_buf(file: &File, max_size: usize, offset: u64) -> io::Result<Vec<u8>> { |
| 248 | let remaining = file.metadata()?.len().saturating_sub(offset); |
| 249 | let buf_size = min(remaining, max_size as u64) as usize; |
| 250 | let mut buf = vec![0; buf_size]; |
| 251 | file.read_exact_at(&mut buf, offset)?; |
| 252 | Ok(buf) |
| 253 | } |
| 254 | |
| 255 | fn is_fd_valid(fd: i32) -> bool { |
| 256 | // SAFETY: a query-only syscall |
| 257 | let retval = unsafe { libc::fcntl(fd, libc::F_GETFD) }; |
| 258 | retval >= 0 |
| 259 | } |
| 260 | |
| 261 | fn fd_to_file(fd: i32) -> Result<File> { |
| 262 | if !is_fd_valid(fd) { |
| 263 | bail!("Bad FD: {}", fd); |
| 264 | } |
| 265 | // SAFETY: The caller is supposed to provide valid FDs to this process. |
| 266 | Ok(unsafe { File::from_raw_fd(fd) }) |
| 267 | } |
| 268 | |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 269 | fn parse_arg_ro_fds(arg: &str) -> Result<(i32, FdConfig)> { |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 270 | let result: Result<Vec<i32>, _> = arg.split(':').map(|x| x.parse::<i32>()).collect(); |
| 271 | let fds = result?; |
| 272 | if fds.len() > 3 { |
| 273 | bail!("Too many options: {}", arg); |
| 274 | } |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 275 | Ok(( |
| 276 | fds[0], |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 277 | FdConfig::Readonly { |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 278 | file: fd_to_file(fds[0])?, |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 279 | // Alternative Merkle tree, if provided |
| 280 | alt_merkle_tree: fds.get(1).map(|fd| fd_to_file(*fd)).transpose()?, |
| 281 | // Alternative signature, if provided |
| 282 | alt_signature: fds.get(2).map(|fd| fd_to_file(*fd)).transpose()?, |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 283 | }, |
| 284 | )) |
| 285 | } |
| 286 | |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 287 | fn parse_arg_rw_fds(arg: &str) -> Result<(i32, FdConfig)> { |
| 288 | let fd = arg.parse::<i32>()?; |
| 289 | let file = fd_to_file(fd)?; |
| 290 | if file.metadata()?.len() > 0 { |
| 291 | bail!("File is expected to be empty"); |
| 292 | } |
| 293 | Ok((fd, FdConfig::ReadWrite(file))) |
| 294 | } |
| 295 | |
Alan Stokes | e1b6e1c | 2021-10-01 12:44:49 +0100 | [diff] [blame^] | 296 | struct Args { |
| 297 | fd_pool: BTreeMap<i32, FdConfig>, |
| 298 | ready_fd: Option<File>, |
| 299 | } |
| 300 | |
| 301 | fn parse_args() -> Result<Args> { |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 302 | #[rustfmt::skip] |
| 303 | let matches = clap::App::new("fd_server") |
| 304 | .arg(clap::Arg::with_name("ro-fds") |
| 305 | .long("ro-fds") |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 306 | .multiple(true) |
| 307 | .number_of_values(1)) |
| 308 | .arg(clap::Arg::with_name("rw-fds") |
| 309 | .long("rw-fds") |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 310 | .multiple(true) |
| 311 | .number_of_values(1)) |
Alan Stokes | e1b6e1c | 2021-10-01 12:44:49 +0100 | [diff] [blame^] | 312 | .arg(clap::Arg::with_name("ready-fd") |
| 313 | .long("ready-fd") |
| 314 | .takes_value(true)) |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 315 | .get_matches(); |
| 316 | |
| 317 | let mut fd_pool = BTreeMap::new(); |
| 318 | if let Some(args) = matches.values_of("ro-fds") { |
| 319 | for arg in args { |
| 320 | let (fd, config) = parse_arg_ro_fds(arg)?; |
| 321 | fd_pool.insert(fd, config); |
| 322 | } |
| 323 | } |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 324 | if let Some(args) = matches.values_of("rw-fds") { |
| 325 | for arg in args { |
| 326 | let (fd, config) = parse_arg_rw_fds(arg)?; |
| 327 | fd_pool.insert(fd, config); |
| 328 | } |
| 329 | } |
Alan Stokes | e1b6e1c | 2021-10-01 12:44:49 +0100 | [diff] [blame^] | 330 | let ready_fd = if let Some(arg) = matches.value_of("ready-fd") { |
| 331 | let fd = arg.parse::<i32>()?; |
| 332 | Some(fd_to_file(fd)?) |
| 333 | } else { |
| 334 | None |
| 335 | }; |
| 336 | Ok(Args { fd_pool, ready_fd }) |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 337 | } |
| 338 | |
| 339 | fn main() -> Result<()> { |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 340 | android_logger::init_once( |
| 341 | android_logger::Config::default().with_tag("fd_server").with_min_level(log::Level::Debug), |
| 342 | ); |
| 343 | |
Alan Stokes | e1b6e1c | 2021-10-01 12:44:49 +0100 | [diff] [blame^] | 344 | let args = parse_args()?; |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 345 | |
Alan Stokes | e1b6e1c | 2021-10-01 12:44:49 +0100 | [diff] [blame^] | 346 | let mut service = FdService::new_binder(args.fd_pool).as_binder(); |
| 347 | let mut ready_notifier = ReadyNotifier(args.ready_fd); |
| 348 | |
Victor Hsieh | 1a8cd04 | 2021-09-03 16:29:45 -0700 | [diff] [blame] | 349 | debug!("fd_server is starting as a rpc service."); |
| 350 | // SAFETY: Service ownership is transferring to the server and won't be valid afterward. |
| 351 | // Plus the binder objects are threadsafe. |
Alan Stokes | e1b6e1c | 2021-10-01 12:44:49 +0100 | [diff] [blame^] | 352 | // RunRpcServerCallback does not retain a reference to ready_callback, and only ever |
| 353 | // calls it with the param we provide during the lifetime of ready_notifier. |
Victor Hsieh | 1a8cd04 | 2021-09-03 16:29:45 -0700 | [diff] [blame] | 354 | let retval = unsafe { |
Alan Stokes | e1b6e1c | 2021-10-01 12:44:49 +0100 | [diff] [blame^] | 355 | binder_rpc_unstable_bindgen::RunRpcServerCallback( |
Victor Hsieh | 1a8cd04 | 2021-09-03 16:29:45 -0700 | [diff] [blame] | 356 | service.as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder, |
| 357 | RPC_SERVICE_PORT, |
Alan Stokes | e1b6e1c | 2021-10-01 12:44:49 +0100 | [diff] [blame^] | 358 | Some(ReadyNotifier::ready_callback), |
| 359 | ready_notifier.as_void_ptr(), |
Victor Hsieh | 1a8cd04 | 2021-09-03 16:29:45 -0700 | [diff] [blame] | 360 | ) |
| 361 | }; |
| 362 | if retval { |
| 363 | debug!("RPC server has shut down gracefully"); |
| 364 | Ok(()) |
Victor Hsieh | 2445e33 | 2021-06-04 16:44:53 -0700 | [diff] [blame] | 365 | } else { |
Victor Hsieh | 1a8cd04 | 2021-09-03 16:29:45 -0700 | [diff] [blame] | 366 | bail!("Premature termination of RPC server"); |
Victor Hsieh | 2445e33 | 2021-06-04 16:44:53 -0700 | [diff] [blame] | 367 | } |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 368 | } |
Alan Stokes | e1b6e1c | 2021-10-01 12:44:49 +0100 | [diff] [blame^] | 369 | |
| 370 | struct ReadyNotifier(Option<File>); |
| 371 | |
| 372 | impl ReadyNotifier { |
| 373 | fn notify(&mut self) { |
| 374 | debug!("fd_server is ready"); |
| 375 | // Close the ready-fd if we were given one to signal our readiness. |
| 376 | drop(self.0.take()); |
| 377 | } |
| 378 | |
| 379 | fn as_void_ptr(&mut self) -> *mut raw::c_void { |
| 380 | self as *mut _ as *mut raw::c_void |
| 381 | } |
| 382 | |
| 383 | unsafe extern "C" fn ready_callback(param: *mut raw::c_void) { |
| 384 | // SAFETY: This is only ever called by RunRpcServerCallback, within the lifetime of the |
| 385 | // ReadyNotifier, with param taking the value returned by as_void_ptr (so a properly aligned |
| 386 | // non-null pointer to an initialized instance). |
| 387 | let ready_notifier = param as *mut Self; |
| 388 | ready_notifier.as_mut().unwrap().notify() |
| 389 | } |
| 390 | } |