• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 //! AuthFsService facilitates authfs mounting (which is a privileged operation) for the client. The
18 //! client will provide an `AuthFsConfig` which includes the backend address (only port for now) and
19 //! the filesystem configuration. It is up to the client to ensure the backend server is running. On
20 //! a successful mount, the client receives an `IAuthFs`, and through the binder object, the client
21 //! is able to retrieve "remote file descriptors".
22 
23 mod authfs;
24 
25 use anyhow::{bail, Result};
26 use log::*;
27 use rpcbinder::RpcServer;
28 use std::ffi::OsString;
29 use std::fs::{create_dir, read_dir, remove_dir_all, remove_file};
30 use std::sync::atomic::{AtomicUsize, Ordering};
31 
32 use authfs_aidl_interface::aidl::com::android::virt::fs::AuthFsConfig::AuthFsConfig;
33 use authfs_aidl_interface::aidl::com::android::virt::fs::IAuthFs::IAuthFs;
34 use authfs_aidl_interface::aidl::com::android::virt::fs::IAuthFsService::{
35     BnAuthFsService, IAuthFsService, AUTHFS_SERVICE_SOCKET_NAME,
36 };
37 use binder::{self, BinderFeatures, ExceptionCode, Interface, Status, Strong};
38 
39 const SERVICE_ROOT: &str = "/data/misc/authfs";
40 
41 /// Implementation of `IAuthFsService`.
42 pub struct AuthFsService {
43     serial_number: AtomicUsize,
44     debuggable: bool,
45 }
46 
47 impl Interface for AuthFsService {}
48 
49 impl IAuthFsService for AuthFsService {
mount(&self, config: &AuthFsConfig) -> binder::Result<Strong<dyn IAuthFs>>50     fn mount(&self, config: &AuthFsConfig) -> binder::Result<Strong<dyn IAuthFs>> {
51         self.validate(config)?;
52 
53         let mountpoint = self.get_next_mount_point();
54 
55         // The directory is supposed to be deleted when `AuthFs` is dropped.
56         create_dir(&mountpoint).map_err(|e| {
57             Status::new_service_specific_error_str(
58                 -1,
59                 Some(format!("Cannot create mount directory {:?}: {:?}", &mountpoint, e)),
60             )
61         })?;
62 
63         authfs::AuthFs::mount_and_wait(mountpoint, config, self.debuggable).map_err(|e| {
64             Status::new_service_specific_error_str(
65                 -1,
66                 Some(format!("mount_and_wait failed: {:?}", e)),
67             )
68         })
69     }
70 }
71 
72 impl AuthFsService {
new_binder(debuggable: bool) -> Strong<dyn IAuthFsService>73     fn new_binder(debuggable: bool) -> Strong<dyn IAuthFsService> {
74         let service = AuthFsService { serial_number: AtomicUsize::new(1), debuggable };
75         BnAuthFsService::new_binder(service, BinderFeatures::default())
76     }
77 
validate(&self, config: &AuthFsConfig) -> binder::Result<()>78     fn validate(&self, config: &AuthFsConfig) -> binder::Result<()> {
79         if config.port < 0 {
80             return Err(Status::new_exception_str(
81                 ExceptionCode::ILLEGAL_ARGUMENT,
82                 Some(format!("Invalid port: {}", config.port)),
83             ));
84         }
85         Ok(())
86     }
87 
get_next_mount_point(&self) -> OsString88     fn get_next_mount_point(&self) -> OsString {
89         let previous = self.serial_number.fetch_add(1, Ordering::Relaxed);
90         OsString::from(format!("{}/{}", SERVICE_ROOT, previous))
91     }
92 }
93 
clean_up_working_directory() -> Result<()>94 fn clean_up_working_directory() -> Result<()> {
95     for entry in read_dir(SERVICE_ROOT)? {
96         let entry = entry?;
97         let path = entry.path();
98         if path.is_dir() {
99             remove_dir_all(path)?;
100         } else if path.is_file() {
101             remove_file(path)?;
102         } else {
103             bail!("Unrecognized path type: {:?}", path);
104         }
105     }
106     Ok(())
107 }
108 
try_main() -> Result<()>109 fn try_main() -> Result<()> {
110     let debuggable = env!("TARGET_BUILD_VARIANT") != "user";
111     let log_level = if debuggable { log::Level::Trace } else { log::Level::Info };
112     android_logger::init_once(
113         android_logger::Config::default().with_tag("authfs_service").with_min_level(log_level),
114     );
115 
116     clean_up_working_directory()?;
117 
118     let service = AuthFsService::new_binder(debuggable).as_binder();
119     debug!("{} is starting as a rpc service.", AUTHFS_SERVICE_SOCKET_NAME);
120     let server = RpcServer::new_init_unix_domain(service, AUTHFS_SERVICE_SOCKET_NAME)?;
121     info!("The RPC server '{}' is running.", AUTHFS_SERVICE_SOCKET_NAME);
122     server.join();
123     info!("The RPC server at '{}' has shut down gracefully.", AUTHFS_SERVICE_SOCKET_NAME);
124     Ok(())
125 }
126 
main()127 fn main() {
128     if let Err(e) = try_main() {
129         error!("failed with {:?}", e);
130         std::process::exit(1);
131     }
132 }
133