use alloc::vec::Vec;
use core::fmt;
use crate::base::channel::{Capped, ChannelId, ReadToEnd};
use crate::base::session::ServiceChannel;
use crate::error::{Error, ProtocolError};
const REPLY_CAP: usize = 64 * 1024;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ReverseError {
Failed(Vec<u8>),
UnexpectedReply,
}
impl fmt::Display for ReverseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Failed(msg) => {
write!(f, "reverse service failed: ")?;
match core::str::from_utf8(msg) {
Ok(m) => f.write_str(m),
Err(_) => write!(f, "{msg:?}"),
}
}
Self::UnexpectedReply => f.write_str("unexpected reverse service reply"),
}
}
}
impl core::error::Error for ReverseError {}
impl<E> From<ReverseError> for Error<E> {
fn from(e: ReverseError) -> Self {
Self::Reverse(e)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReverseRule {
pub serial: Vec<u8>,
pub remote: Vec<u8>,
pub local: Vec<u8>,
}
pub async fn establish<C: ServiceChannel>(
conn: &mut C,
device_spec: &str,
host_spec: &str,
) -> Result<Option<u32>, Error<C::IoError>> {
check_specs(&[device_spec, host_spec])?;
let mut dest = Vec::with_capacity(18 + device_spec.len() + host_spec.len());
dest.extend_from_slice(b"reverse:forward:");
dest.extend_from_slice(device_spec.as_bytes());
dest.push(b';');
dest.extend_from_slice(host_spec.as_bytes());
dest.push(0);
let reply = exchange(conn, &dest).await?;
let data = parse_status(&reply).map_err(Error::Reverse)?;
parse_port(&data).map_err(Error::Reverse)
}
pub async fn remove<C: ServiceChannel>(
conn: &mut C,
device_spec: &str,
) -> Result<(), Error<C::IoError>> {
check_specs(&[device_spec])?;
let mut dest = Vec::with_capacity(21 + device_spec.len());
dest.extend_from_slice(b"reverse:killforward:");
dest.extend_from_slice(device_spec.as_bytes());
dest.push(0);
let reply = exchange(conn, &dest).await?;
parse_status(&reply).map_err(Error::Reverse)?;
Ok(())
}
pub async fn remove_all<C: ServiceChannel>(conn: &mut C) -> Result<(), Error<C::IoError>> {
let reply = exchange(conn, b"reverse:killforward-all\0").await?;
parse_status(&reply).map_err(Error::Reverse)?;
Ok(())
}
pub async fn list<C: ServiceChannel>(conn: &mut C) -> Result<Vec<ReverseRule>, Error<C::IoError>> {
let listing = list_raw(conn).await?;
parse_listing(&listing).map_err(Error::Reverse)
}
pub async fn list_raw<C: ServiceChannel>(conn: &mut C) -> Result<Vec<u8>, Error<C::IoError>> {
let reply = exchange(conn, b"reverse:list-forward\0").await?;
if reply.starts_with(b"FAIL") {
return Err(Error::Reverse(fail_message(&reply[4..])));
}
hex4_block(&reply).ok_or(Error::Reverse(ReverseError::UnexpectedReply))
}
fn check_specs<E>(specs: &[&str]) -> Result<(), Error<E>> {
if specs.iter().any(|s| s.contains('\0')) {
return Err(Error::Protocol(ProtocolError::InvalidDestination));
}
Ok(())
}
async fn exchange<C: ServiceChannel>(
conn: &mut C,
dest: &[u8],
) -> Result<Vec<u8>, Error<C::IoError>> {
let ch = conn.open_service_channel(dest).await?;
let mut buf = [0u8; 512];
OpenedChannel { conn, ch }
.read_to_vec(&mut buf, REPLY_CAP)
.await?
.map_err(|Capped| Error::Reverse(ReverseError::UnexpectedReply))
}
struct OpenedChannel<'c, C> {
conn: &'c mut C,
ch: ChannelId,
}
impl<C: ServiceChannel> ReadToEnd for OpenedChannel<'_, C> {
type IoError = C::IoError;
async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error<C::IoError>> {
self.conn.read_service_channel(self.ch, buf).await
}
async fn close(self) -> Result<(), Error<C::IoError>> {
self.conn.close_service_channel(self.ch).await
}
}
fn parse_status(reply: &[u8]) -> Result<Vec<u8>, ReverseError> {
match reply.get(..4) {
Some(b"OKAY") => {
let rest = &reply[4..];
if rest.is_empty() {
Ok(Vec::new())
} else {
hex4_block(rest).ok_or(ReverseError::UnexpectedReply)
}
}
Some(b"FAIL") => Err(fail_message(&reply[4..])),
_ => Err(ReverseError::UnexpectedReply),
}
}
fn parse_port(data: &[u8]) -> Result<Option<u32>, ReverseError> {
if data.is_empty() {
return Ok(None);
}
let digits = data.strip_prefix(b"-").unwrap_or(data);
if !digits.iter().all(u8::is_ascii_digit) {
return Err(ReverseError::UnexpectedReply);
}
core::str::from_utf8(data)
.ok()
.and_then(|text| {
if text.starts_with('-') {
text.parse::<i32>().ok().map(|port| port as u32)
} else {
text.parse().ok()
}
})
.map(Some)
.ok_or(ReverseError::UnexpectedReply)
}
fn parse_listing(block: &[u8]) -> Result<Vec<ReverseRule>, ReverseError> {
if block.is_empty() {
return Ok(Vec::new());
}
let lines = block.strip_suffix(b"\n").unwrap_or(block);
lines
.split(|&b| b == b'\n')
.map(|line| {
let mut fields = line.splitn(3, |&b| b == b' ');
match (fields.next(), fields.next(), fields.next()) {
(Some(serial), Some(remote), Some(local)) => Ok(ReverseRule {
serial: serial.to_vec(),
remote: remote.to_vec(),
local: local.to_vec(),
}),
_ => Err(ReverseError::UnexpectedReply),
}
})
.collect()
}
fn fail_message(rest: &[u8]) -> ReverseError {
ReverseError::Failed(hex4_block(rest).unwrap_or_else(|| rest.to_vec()))
}
fn hex4_block(b: &[u8]) -> Option<Vec<u8>> {
let prefix = b.get(..4)?;
if !prefix.iter().all(u8::is_ascii_hexdigit) {
return None;
}
let digits = core::str::from_utf8(prefix).ok()?;
let len = usize::from_str_radix(digits, 16).ok()?;
let body = b.get(4..)?;
if body.len() != len {
return None;
}
Some(body.to_vec())
}
#[cfg(test)]
mod tests {
use core::convert::Infallible;
use super::*;
use crate::base::mock::now;
struct FullReads;
impl ServiceChannel for FullReads {
type IoError = Infallible;
async fn open_service_channel(&mut self, _: &[u8]) -> Result<ChannelId, Error<Infallible>> {
Ok(ChannelId::from_raw(0, 1))
}
async fn read_service_channel(
&mut self,
_: ChannelId,
_: &mut [u8],
) -> Result<usize, Error<Infallible>> {
Err(Error::ReceiveBufferFull)
}
async fn close_service_channel(&mut self, _: ChannelId) -> Result<(), Error<Infallible>> {
Ok(())
}
}
#[test]
fn a_full_receive_buffer_is_not_taken_for_the_reply_cap() {
let err = now(list(&mut FullReads)).unwrap_err();
assert!(matches!(err, Error::ReceiveBufferFull), "got {err:?}");
}
#[test]
fn statuses_parse_as_probed_on_a_real_device() {
assert_eq!(parse_status(b"OKAY00046100").unwrap(), b"6100");
assert_eq!(parse_status(b"OKAY").unwrap(), b"");
assert_eq!(
parse_status(b"FAIL0014bad forward: garbage").unwrap_err(),
ReverseError::Failed(b"bad forward: garbage".to_vec())
);
assert_eq!(
parse_status(b"MEOW").unwrap_err(),
ReverseError::UnexpectedReply
);
assert_eq!(
parse_status(b"OKAY000461").unwrap_err(),
ReverseError::UnexpectedReply
);
assert_eq!(hex4_block(b"0000").unwrap(), b"");
assert_eq!(
hex4_block(b"001ahost-19 tcp:6100 tcp:6100\n").unwrap(),
b"host-19 tcp:6100 tcp:6100\n"
);
assert_eq!(hex4_block(b"+0011"), None);
assert_eq!(
parse_status(b"OKAY+0011").unwrap_err(),
ReverseError::UnexpectedReply
);
}
fn rule(serial: &[u8], remote: &[u8], local: &[u8]) -> ReverseRule {
ReverseRule {
serial: serial.to_vec(),
remote: remote.to_vec(),
local: local.to_vec(),
}
}
#[test]
fn a_listing_parses_one_rule_per_line() {
let listing = b"host-19 tcp:6100 tcp:6100\nhost-19 localabstract:a tcp:7\n";
assert_eq!(
parse_listing(listing).unwrap(),
[
rule(b"host-19", b"tcp:6100", b"tcp:6100"),
rule(b"host-19", b"localabstract:a", b"tcp:7"),
]
);
assert_eq!(parse_listing(b"").unwrap(), []);
assert_eq!(
parse_listing(b"host-19 tcp:1 tcp:1").unwrap(),
[rule(b"host-19", b"tcp:1", b"tcp:1")],
"a last line without its newline"
);
}
#[test]
fn a_space_in_the_last_field_stays_in_it() {
assert_eq!(
parse_listing(b"host-19 tcp:1 localabstract:a b\n").unwrap(),
[rule(b"host-19", b"tcp:1", b"localabstract:a b")]
);
}
#[test]
fn a_spec_that_is_not_utf8_comes_back_as_its_bytes() {
assert_eq!(
parse_listing(b"host-19 tcp:1 localabstract:\xff\nhost-19 tcp:2 tcp:2\n").unwrap(),
[
rule(b"host-19", b"tcp:1", b"localabstract:\xff"),
rule(b"host-19", b"tcp:2", b"tcp:2"),
]
);
}
#[test]
fn a_listing_that_is_not_rules_is_an_unexpected_reply() {
for listing in [
&b"host-19 tcp:1\n"[..],
b"\n",
b"host-19 tcp:1 tcp:1\n\nhost-19 tcp:2 tcp:2\n",
] {
assert_eq!(
parse_listing(listing),
Err(ReverseError::UnexpectedReply),
"{listing:?}"
);
}
}
#[test]
fn a_bound_port_parses_as_decimal() {
assert_eq!(parse_port(b"6100"), Ok(Some(6100)));
assert_eq!(parse_port(b"65535"), Ok(Some(65535)));
assert_eq!(parse_port(b"100000"), Ok(Some(100_000)), "past u16");
assert_eq!(parse_port(b"4294967295"), Ok(Some(u32::MAX)));
assert_eq!(parse_port(b""), Ok(None), "adbd reported no port");
}
#[test]
fn a_negative_port_is_one_past_i32_max() {
assert_eq!(parse_port(b"-1294967296"), Ok(Some(3_000_000_000)));
assert_eq!(parse_port(b"-2147483648"), Ok(Some(1 << 31)), "the first");
assert_eq!(parse_port(b"-1"), Ok(Some(u32::MAX)), "the last");
}
#[test]
fn a_port_that_is_not_one_is_an_unexpected_reply() {
for data in [
&b"+5"[..],
b"-",
b"-+5",
b"--5",
b"x",
b"4294967296",
b"-2147483649",
b"61 00",
b"port",
b"\xff",
] {
assert_eq!(
parse_port(data),
Err(ReverseError::UnexpectedReply),
"{data:?}"
);
}
}
}