blob: 10d50dde9e6640bfefd67bf33123ce03ab6deb85 [file] [log] [blame]
Janis Danisevskisaaba4af2021-11-18 14:25:07 -08001// Copyright 2021, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use android_hardware_security_dice::aidl::android::hardware::security::dice::ResponseCode::ResponseCode;
16use anyhow::Result;
17use binder::public_api::{
18 ExceptionCode, Result as BinderResult, Status as BinderStatus, StatusCode,
19};
20use std::ffi::CString;
21
22/// This is the error type for DICE HAL implementations. It wraps
23/// `android::hardware::security::dice::ResponseCode` generated
24/// from AIDL in the `Rc` variant and Binder and BinderTransaction errors in the respective
25/// variants.
26#[allow(dead_code)] // Binder error forwarding will be needed when proxy nodes are implemented.
27#[derive(Debug, thiserror::Error, Eq, PartialEq, Clone)]
28pub enum Error {
29 /// Wraps a dice `ResponseCode` as defined by the Keystore AIDL interface specification.
30 #[error("Error::Rc({0:?})")]
31 Rc(ResponseCode),
32 /// Wraps a Binder exception code other than a service specific exception.
33 #[error("Binder exception code {0:?}, {1:?}")]
34 Binder(ExceptionCode, i32),
35 /// Wraps a Binder status code.
36 #[error("Binder transaction error {0:?}")]
37 BinderTransaction(StatusCode),
38}
39
40/// This function should be used by dice service calls to translate error conditions
41/// into service specific exceptions.
42///
43/// All error conditions get logged by this function.
44///
45/// All `Error::Rc(x)` variants get mapped onto a service specific error code of x.
46/// `selinux::Error::PermissionDenied` is mapped on `ResponseCode::PERMISSION_DENIED`.
47///
48/// All non `Error` error conditions and the Error::Binder variant get mapped onto
49/// ResponseCode::SYSTEM_ERROR`.
50///
51/// `handle_ok` will be called if `result` is `Ok(value)` where `value` will be passed
52/// as argument to `handle_ok`. `handle_ok` must generate a `BinderResult<T>`, but it
53/// typically returns Ok(value).
54///
55/// # Examples
56///
57/// ```
58/// fn do_something() -> anyhow::Result<Vec<u8>> {
59/// Err(anyhow!(Error::Rc(ResponseCode::NOT_IMPLEMENTED)))
60/// }
61///
62/// map_or_log_err(do_something(), Ok)
63/// ```
64pub fn map_or_log_err<T, U, F>(result: Result<U>, handle_ok: F) -> BinderResult<T>
65where
66 F: FnOnce(U) -> BinderResult<T>,
67{
68 map_err_with(
69 result,
70 |e| {
71 log::error!("{:?}", e);
72 e
73 },
74 handle_ok,
75 )
76}
77
78/// This function behaves similar to map_or_log_error, but it does not log the errors, instead
79/// it calls map_err on the error before mapping it to a binder result allowing callers to
80/// log or transform the error before mapping it.
81fn map_err_with<T, U, F1, F2>(result: Result<U>, map_err: F1, handle_ok: F2) -> BinderResult<T>
82where
83 F1: FnOnce(anyhow::Error) -> anyhow::Error,
84 F2: FnOnce(U) -> BinderResult<T>,
85{
86 result.map_or_else(
87 |e| {
88 let e = map_err(e);
89 let msg = match CString::new(format!("{:?}", e)) {
90 Ok(msg) => Some(msg),
91 Err(_) => {
92 log::warn!(
93 "Cannot convert error message to CStr. It contained a nul byte.
94 Omitting message from service specific error."
95 );
96 None
97 }
98 };
99 let rc = get_error_code(&e);
100 Err(BinderStatus::new_service_specific_error(rc, msg.as_deref()))
101 },
102 handle_ok,
103 )
104}
105
106/// Extracts the error code from an `anyhow::Error` mapping any error that does not have a
107/// root cause of `Error::Rc` onto `ResponseCode::SYSTEM_ERROR` and to `e` with `Error::Rc(e)`
108/// otherwise.
109fn get_error_code(e: &anyhow::Error) -> i32 {
110 let root_cause = e.root_cause();
111 match root_cause.downcast_ref::<Error>() {
112 Some(Error::Rc(rcode)) => rcode.0,
113 // If an Error::Binder reaches this stage we report a system error.
114 // The exception code and possible service specific error will be
115 // printed in the error log above.
116 Some(Error::Binder(_, _)) | Some(Error::BinderTransaction(_)) => {
117 ResponseCode::SYSTEM_ERROR.0
118 }
119 None => ResponseCode::SYSTEM_ERROR.0,
120 }
121}