use alloc::format;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use core::ffi::c_void;
use core::future::Future;
use libadb::base::auth::Authenticator;
use libadb::keys::rsa::rand_core::OsRng;
use libadb::keys::AdbKey;
#[cfg(feature = "tls")]
use libadb::tls::{TlsClientConfig, TlsIdentity};
use crate::error::AdbStatus;
pub(crate) struct FfiAuthenticator {
key: AdbKey,
public_key: Vec<u8>,
}
impl FfiAuthenticator {
pub(crate) fn from_pkcs8_pem(priv_pem: &str, pub_key: &[u8]) -> Result<Self, String> {
let key = AdbKey::from_pkcs8_pem(priv_pem, &mut OsRng, "")
.map_err(|e| format!("parse private key: {e}"))?;
Ok(Self {
key,
public_key: normalize_public_key(pub_key),
})
}
#[cfg(feature = "tls")]
pub(crate) fn tls_config(&self) -> Result<TlsClientConfig, String> {
tls_config_for(&self.key)
}
}
#[cfg(feature = "tls")]
pub(crate) fn tls_config_for(key: &AdbKey) -> Result<TlsClientConfig, String> {
let identity = TlsIdentity::from_key(key, &mut OsRng).map_err(|e| format!("tls: {e}"))?;
TlsClientConfig::adb(&identity).map_err(|e| format!("tls: {e}"))
}
impl Authenticator for FfiAuthenticator {
type Error = String;
async fn sign(&mut self, token: &[u8]) -> Result<Vec<u8>, String> {
self.key.sign(token).await.map_err(|e| format!("sign: {e}"))
}
fn public_key(&self) -> &[u8] {
&self.public_key
}
}
fn normalize_public_key(pub_key: &[u8]) -> Vec<u8> {
let mut v = pub_key.to_vec();
if !v.ends_with(b"\0") {
v.push(0);
}
v
}
pub type AdbSignFn = unsafe extern "C" fn(
user_data: *mut c_void,
token: *const u8,
token_len: usize,
out_signature: *mut u8,
out_capacity: usize,
out_length: *mut usize,
) -> AdbStatus;
#[repr(C)]
#[allow(non_camel_case_types)]
pub struct adb_authenticator_t {
pub public_key: *const u8,
pub public_key_len: usize,
pub sign: Option<AdbSignFn>,
pub user_data: *mut c_void,
}
const MAX_SIGNATURE_LEN: usize = 1024;
const ADB_AUTH_TOKEN_LEN: usize = 20;
pub(crate) struct CallbackAuthenticator {
public_key: Vec<u8>,
sign_fn: AdbSignFn,
user_data: *mut c_void,
}
impl CallbackAuthenticator {
pub(crate) unsafe fn from_ffi(a: &adb_authenticator_t) -> Result<Self, &'static str> {
let Some(sign_fn) = a.sign else {
return Err("sign callback is null");
};
if a.public_key.is_null() && a.public_key_len > 0 {
return Err("public_key is null but public_key_len > 0");
}
let pub_key_bytes = if a.public_key_len > 0 {
core::slice::from_raw_parts(a.public_key, a.public_key_len)
} else {
&[]
};
Ok(Self {
public_key: normalize_public_key(pub_key_bytes),
sign_fn,
user_data: a.user_data,
})
}
}
impl Authenticator for CallbackAuthenticator {
type Error = String;
fn sign(&mut self, token: &[u8]) -> impl Future<Output = Result<Vec<u8>, Self::Error>> {
if token.len() != ADB_AUTH_TOKEN_LEN {
return core::future::ready(Err(format!(
"expected {ADB_AUTH_TOKEN_LEN}-byte SHA-1 prehash token, got {}",
token.len()
)));
}
let mut buf = vec![0u8; MAX_SIGNATURE_LEN];
let mut out_len: usize = 0;
let status = unsafe {
(self.sign_fn)(
self.user_data,
token.as_ptr(),
token.len(),
buf.as_mut_ptr(),
buf.len(),
&mut out_len,
)
};
let res = match status {
AdbStatus::Ok if out_len == 0 => {
Err(String::from("sign callback returned empty signature"))
}
AdbStatus::Ok if out_len <= buf.len() => {
buf.truncate(out_len);
Ok(buf)
}
AdbStatus::Ok => Err(format!(
"sign callback wrote {out_len} bytes, exceeds capacity {}",
buf.len()
)),
other => Err(format!("sign callback returned status {}", other as i32)),
};
core::future::ready(res)
}
fn public_key(&self) -> &[u8] {
&self.public_key
}
}