libadb 0.9.0

Low-level ADB protocol library for direct TCP and USB communication
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! Reverse forwards (`adb reverse`): rules that make the device listen
//! on its side and open channels toward the host.
//!
//! A rule lives on the connection that established it: adbd drops it
//! when that connection goes away. Every connection the device then
//! accepts arrives there as a device-initiated OPEN whose destination is
//! the rule's `<local>` spec: receive them with
//! [`Connection::accept_incoming`](crate::Connection::accept_incoming)
//! (or `Reader::accept_incoming` on a split connection, and an
//! `IncomingListener` from `Writer::listen_incoming` while
//! `Reader::run` dispatches; without one, `run` refuses them).
//!
//! The list of rules is the device's, shared by all its connections:
//! [`list`] shows every rule on it, and [`remove`] and [`remove_all`]
//! take rules off it whichever connection established them.
//!
//! Specs are passed through verbatim, e.g. `tcp:8080` or
//! `localabstract:name`. On the device, adbd binds `tcp:` listeners on
//! its wildcard address — connecting locally over IPv6 (`::1`) is what
//! works in practice.
//!
//! Wire format, verified against a real adbd:
//!
//! * `reverse:forward:<remote>;<local>` → `OKAY` + `%04x` + the port in
//!   decimal, or a bare `OKAY` when adbd reports none: [`establish`]
//!   says when;
//! * `reverse:killforward:<remote>`, `reverse:killforward-all` →
//!   bare `OKAY`;
//! * `reverse:list-forward` → no `OKAY`, just `%04x` + lines of
//!   `<serial> <remote> <local>\n`;
//! * any failure → `FAIL` + `%04x` + message.

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;

/// What the `reverse:` rule service answered.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ReverseError {
    /// The device returned `FAIL`. The message is adbd's own text,
    /// e.g. `bad forward: …` or `listener '…' not found`.
    Failed(Vec<u8>),
    /// The reply matched neither `OKAY` nor `FAIL`, or a *successful*
    /// reply's length prefix disagreed with what arrived. A `FAIL` is
    /// reported as [`Failed`](Self::Failed) even when its own length
    /// prefix is mangled — the device's message matters more than its
    /// framing.
    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)
    }
}

/// One rule in the device's listing, as [`list`] reads it.
///
/// The fields are the bytes the device sent: adbd prints its specs as
/// they were given, and nothing makes them UTF-8.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReverseRule {
    /// The name adbd files the rule under, e.g. `host-19`: the
    /// connection that established it, as the device sees it.
    pub serial: Vec<u8>,
    /// The spec the device listens on, e.g. `tcp:6100`.
    pub remote: Vec<u8>,
    /// The spec each connection is opened toward on the host, e.g.
    /// `tcp:6100`.
    pub local: Vec<u8>,
}

/// Ask the device to listen on `device_spec` and forward every
/// connection to a channel opened toward the host with `host_spec` as
/// its destination.
///
/// Returns the port adbd reports. Going by adbd's sources, that depends
/// on the spec and on whether it bound anything:
///
/// * a newly bound `tcp:0` reports the port adbd picked;
/// * a fixed `tcp:<port>` reports it from Android 10 on, not on
///   Android 9;
/// * a `vsock:` listener reports its port;
/// * a rule that already exists, and any other spec, answer a bare
///   `OKAY`, which is `None`.
///
/// The type is 32 bits wide because vsock ports are; a `tcp:` port
/// always fits a `u16`. A reply that is not a 32-bit decimal port is
/// [`ReverseError::UnexpectedReply`].
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)
}

/// Remove the rule listening on `device_spec`, whichever connection
/// established it.
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(())
}

/// Remove every rule on the device, whichever connection established it.
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(())
}

/// The device's current rules, whichever connection established them.
///
/// adbd prints each rule as a `<serial> <remote> <local>` line and
/// separates the fields with a bare space, so a space inside `local`
/// survives and one inside `remote` does not. The fields are kept as
/// bytes, so a spec that is not UTF-8 comes back like any other; a
/// line with fewer than three fields is
/// [`ReverseError::UnexpectedReply`].
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)
}

/// The device's current rules as it sent them: the
/// `<serial> <remote> <local>\n` lines [`list`] parses, without the
/// reply's length prefix and unparsed, for a caller that passes the
/// listing on as text.
///
/// A `FAIL` is [`ReverseError::Failed`], and a reply that is not one
/// length-prefixed block is [`ReverseError::UnexpectedReply`]; the
/// lines themselves are not checked.
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;

    /// A [`ServiceChannel`] whose every read fails with
    /// [`Error::ReceiveBufferFull`].
    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"
        );
        // A signed prefix is not four hex digits, however happily
        // `from_str_radix` would take it.
        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() {
        // One such rule used to fail the whole listing.
        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() {
        // What adbd's `%d` prints for a port held in an `int`.
        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:?}"
            );
        }
    }
}