libadb 0.7.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
use super::super::error::ProtocolError;
use super::{
    constant::{AUTH_RSAPUBLICKEY, AUTH_SIGNATURE, MAX_PAYLOAD},
    Checksumable, Command, Message, MESSAGE_SIZE,
};
use bytes::{Buf, Bytes, BytesMut};

#[cfg(test)]
use super::Checksum;
#[cfg(test)]
use bytes::BufMut;

/// An ADB packet: a 24-byte message header and its payload.
///
/// What the two argument fields mean depends on the command — channel
/// ids for `OPEN`/`WRTE`/`OKAY`/`CLSE`, protocol version and maximum
/// payload for `CNXN`. See [`Command`].
///
/// [`decode`](Self::decode) is the entry point for reading packets off
/// a stream; there is no matching whole-buffer encoder, because a
/// packet has to leave as a separate header write and payload write —
/// adbd reads the header with an exact-size read.
#[derive(Debug, Clone, PartialEq)]
pub struct Packet {
    /// What the packet asks for.
    pub command: Command,
    /// First argument; meaning depends on `command`.
    pub arg0: u32,
    /// Second argument; meaning depends on `command`.
    pub arg1: u32,
    /// Payload, empty for commands that carry none.
    pub data: Bytes,
}

impl Checksumable for Bytes {
    type Checksum = u32;

    fn calculate_checksum(&self) -> u32 {
        let mut sum = 0u32;
        for &b in self.as_ref() {
            sum = sum.wrapping_add(b as u32);
        }
        sum
    }
}

impl Checksumable for Packet {
    type Checksum = u32;

    fn calculate_checksum(&self) -> u32 {
        self.data.calculate_checksum()
    }
}

impl Packet {
    pub fn new(command: Command, arg0: u32, arg1: u32, payload: impl Into<Bytes>) -> Self {
        let data = payload.into();
        Self {
            command,
            arg0,
            arg1,
            data,
        }
    }

    pub fn close(local_id: u32, remote_id: u32) -> Self {
        Self::new(Command::Close, local_id, remote_id, Bytes::new())
    }

    pub fn auth_signature(signature: impl Into<Bytes>) -> Self {
        Self::new(Command::Auth, AUTH_SIGNATURE, 0, signature)
    }

    pub fn auth_public_key(key: impl Into<Bytes>) -> Self {
        Self::new(Command::Auth, AUTH_RSAPUBLICKEY, 0, key)
    }
}

impl Packet {
    /// Returns `Ok(None)` until a whole packet is buffered. The size
    /// check happens before the payload is awaited, so an oversized
    /// announcement fails instead of growing `buf` to fit it.
    pub fn decode(buf: &mut BytesMut, max_payload: u32) -> Result<Option<Self>, ProtocolError> {
        if buf.len() < MESSAGE_SIZE {
            return Ok(None);
        }

        let mut h = &buf[..MESSAGE_SIZE];
        let message = Message {
            command: h.get_u32_le(),
            arg0: h.get_u32_le(),
            arg1: h.get_u32_le(),
            data_length: h.get_u32_le(),
            data_check: h.get_u32_le(),
            magic: h.get_u32_le(),
        };

        let command = Command::try_from(message.command)
            .map_err(|_| ProtocolError::InvalidCommand(message.command))?;

        if message.magic != command.magic() {
            return Err(ProtocolError::InvalidMagic);
        }

        if message.data_length > max_payload.min(MAX_PAYLOAD) {
            return Err(ProtocolError::PayloadTooLarge);
        }

        let payload_len = message.data_length as usize;
        let total_len = MESSAGE_SIZE + payload_len;

        if buf.len() < total_len {
            return Ok(None);
        }

        let packet_buf = buf.split_to(total_len).freeze();
        let data = packet_buf.slice(MESSAGE_SIZE..);

        if message.data_check != 0 && data.calculate_checksum() != message.data_check {
            return Err(ProtocolError::InvalidChecksum);
        }

        Ok(Some(Self {
            command,
            arg0: message.arg0,
            arg1: message.arg1,
            data,
        }))
    }

    /// Bytes still missing before [`decode`](Self::decode) can produce a
    /// packet: the rest of the header, or the rest of the payload it
    /// announces. Only meaningful after `decode` returned `Ok(None)`,
    /// which is also what bounds the announced length.
    pub fn missing(buf: &[u8]) -> usize {
        if buf.len() < MESSAGE_SIZE {
            return MESSAGE_SIZE - buf.len();
        }
        let data_length = u32::from_le_bytes([buf[12], buf[13], buf[14], buf[15]]) as usize;
        (MESSAGE_SIZE + data_length).saturating_sub(buf.len())
    }

    /// `checksum` decides whether `data_check` carries the payload sum
    /// or stays zero — see [`Checksum`].
    /// Serialize into one contiguous buffer. Test-only: on the wire a
    /// packet must go out as a separate header write and payload write
    /// (see [`send_pkt`](crate::base::wire::send_pkt)), which is what
    /// adbd's exact-size header read requires.
    #[cfg(test)]
    pub fn encode(&self, dst: &mut BytesMut, checksum: Checksum) -> Result<(), ProtocolError> {
        let message = self.to_message(checksum)?;
        dst.reserve(MESSAGE_SIZE + self.data.len());
        dst.put_u32_le(message.command);
        dst.put_u32_le(message.arg0);
        dst.put_u32_le(message.arg1);
        dst.put_u32_le(message.data_length);
        dst.put_u32_le(message.data_check);
        dst.put_u32_le(message.magic);
        dst.put_slice(&self.data);
        Ok(())
    }

    #[cfg(test)]
    fn to_message(&self, checksum: Checksum) -> Result<Message, ProtocolError> {
        if self.data.len() > MAX_PAYLOAD as usize {
            return Err(ProtocolError::PayloadTooLarge);
        }
        Ok(Message {
            command: self.command.into(),
            arg0: self.arg0,
            arg1: self.arg1,
            data_length: self.data.len() as u32,
            data_check: checksum.of(&self.data),
            magic: self.command.magic(),
        })
    }
}

#[cfg(test)]
mod tests {
    extern crate std;

    use super::super::super::error::ProtocolError;
    use super::super::{constant::MAX_PAYLOAD, packet::Packet, Checksum, Command, MESSAGE_SIZE};
    use bytes::{BufMut, Bytes, BytesMut};

    /// Decode with the library-wide limit; tests that care about a
    /// custom cap call `Packet::decode` directly.
    fn decode(buf: &mut BytesMut) -> Result<Option<Packet>, ProtocolError> {
        Packet::decode(buf, MAX_PAYLOAD)
    }

    fn checksum(data: &[u8]) -> u32 {
        data.iter().map(|&b| b as u32).sum()
    }

    fn magic(command: u32) -> u32 {
        command ^ 0xFFFF_FFFF
    }

    fn encode_header(
        command: u32,
        arg0: u32,
        arg1: u32,
        data_length: u32,
        data_check: u32,
        magic: u32,
    ) -> BytesMut {
        let mut buf = BytesMut::with_capacity(MESSAGE_SIZE);
        buf.put_u32_le(command);
        buf.put_u32_le(arg0);
        buf.put_u32_le(arg1);
        buf.put_u32_le(data_length);
        buf.put_u32_le(data_check);
        buf.put_u32_le(magic);
        buf
    }

    #[test]
    fn decode_command_without_payload() {
        let command: u32 = Command::Ready.into();
        let arg0 = 10;
        let arg1 = 20;

        let mut buf = BytesMut::new();
        buf.put_u32_le(command);

        assert_eq!(
            decode(&mut buf),
            Ok(None),
            "buffer smaller than header must yield None"
        );

        buf.put_u32_le(arg0);
        buf.put_u32_le(arg1);
        buf.put_u32_le(0);
        buf.put_u32_le(0);
        buf.put_u32_le(magic(command));

        assert_eq!(
            decode(&mut buf),
            Ok(Some(Packet::new(Command::Ready, arg0, arg1, Bytes::new()))),
            "full header must decode into a ready packet"
        );
    }

    #[test]
    fn decode_command_with_payload() {
        let command: u32 = Command::Open.into();
        let arg0 = 10;
        let arg1 = 0;
        let data = b"shell_v2\0";

        let mut buf = BytesMut::new();
        buf.put_u32_le(command);

        assert_eq!(decode(&mut buf), Ok(None));

        buf.put_u32_le(arg0);
        buf.put_u32_le(arg1);
        buf.put_u32_le(data.len() as u32);
        buf.put_u32_le(checksum(data));
        buf.put_u32_le(magic(command));

        assert_eq!(
            decode(&mut buf),
            Ok(None),
            "header-only buffer must wait for the payload"
        );

        buf.put_slice(b"shel");
        assert_eq!(
            decode(&mut buf),
            Ok(None),
            "partial payload must wait for the rest"
        );

        buf.put_slice(b"l_v2\0");
        assert_eq!(
            decode(&mut buf),
            Ok(Some(Packet::new(
                Command::Open,
                arg0,
                0,
                &b"shell_v2\0"[..]
            )))
        );
    }

    #[test]
    fn encode_then_decode_reproduces_packet_without_payload() {
        let original = Packet::new(Command::Ready, 7, 42, Bytes::new());
        let mut buf = BytesMut::new();
        original.encode(&mut buf, Checksum::Compute).unwrap();
        assert_eq!(buf.len(), MESSAGE_SIZE);
        assert_eq!(decode(&mut buf), Ok(Some(original)));
    }

    #[test]
    fn encode_then_decode_reproduces_packet_with_payload() {
        let original = Packet::new(Command::Write, 1, 2, Bytes::from_static(b"hello, device"));
        let mut buf = BytesMut::new();
        original.encode(&mut buf, Checksum::Compute).unwrap();
        assert_eq!(buf.len(), MESSAGE_SIZE + b"hello, device".len());
        assert_eq!(decode(&mut buf), Ok(Some(original)));
    }

    #[test]
    fn encode_refuses_payload_exceeding_max_payload() {
        let oversized = alloc::vec![0u8; MAX_PAYLOAD as usize + 1];
        let packet = Packet::new(Command::Write, 0, 0, Bytes::from(oversized));
        let mut buf = BytesMut::new();
        assert_eq!(
            packet.encode(&mut buf, Checksum::Compute),
            Err(ProtocolError::PayloadTooLarge)
        );
    }

    #[test]
    fn decode_rejects_bad_magic() {
        let command: u32 = Command::Ready.into();
        let mut buf = encode_header(command, 0, 0, 0, 0, magic(command) ^ 0x1);
        assert_eq!(decode(&mut buf), Err(ProtocolError::InvalidMagic));
    }

    #[test]
    fn decode_rejects_unknown_command() {
        let unknown: u32 = 0xDEAD_BEEF;
        let mut buf = encode_header(unknown, 0, 0, 0, 0, magic(unknown));
        assert_eq!(
            decode(&mut buf),
            Err(ProtocolError::InvalidCommand(unknown))
        );
    }

    #[test]
    fn decode_rejects_bad_checksum_when_nonzero() {
        let command: u32 = Command::Write.into();
        let data = b"payload";
        let wrong_checksum = checksum(data).wrapping_add(1);

        let mut buf = encode_header(
            command,
            1,
            2,
            data.len() as u32,
            wrong_checksum,
            magic(command),
        );
        buf.put_slice(data);

        assert_eq!(decode(&mut buf), Err(ProtocolError::InvalidChecksum));
    }

    #[test]
    fn decode_accepts_zero_checksum_as_unchecked() {
        let command: u32 = Command::Write.into();
        let data = b"payload";

        let mut buf = encode_header(command, 1, 2, data.len() as u32, 0, magic(command));
        buf.put_slice(data);

        assert_eq!(
            decode(&mut buf),
            Ok(Some(Packet::new(
                Command::Write,
                1,
                2,
                Bytes::from_static(data)
            )))
        );
    }

    #[test]
    fn decode_rejects_payload_length_above_max_payload() {
        let command: u32 = Command::Write.into();
        let mut buf = encode_header(command, 0, 0, MAX_PAYLOAD + 1, 0, magic(command));
        assert_eq!(decode(&mut buf), Err(ProtocolError::PayloadTooLarge));
    }

    fn data_check_of(buf: &BytesMut) -> u32 {
        u32::from_le_bytes(buf[16..20].try_into().unwrap())
    }

    #[test]
    fn encode_writes_the_sum_when_asked_to_compute() {
        let packet = Packet::new(Command::Write, 1, 2, Bytes::from_static(b"abc"));
        let mut buf = BytesMut::new();
        packet.encode(&mut buf, Checksum::Compute).unwrap();
        assert_eq!(data_check_of(&buf), 294);
    }

    #[test]
    fn encode_zeroes_data_check_when_skipping() {
        let packet = Packet::new(Command::Write, 1, 2, Bytes::from_static(b"abc"));
        let mut buf = BytesMut::new();
        packet.encode(&mut buf, Checksum::Skip).unwrap();
        assert_eq!(data_check_of(&buf), 0);
        // Everything else is byte-identical to the checksummed form.
        let mut checked = BytesMut::new();
        packet.encode(&mut checked, Checksum::Compute).unwrap();
        assert_eq!(buf[..16], checked[..16]);
        assert_eq!(buf[20..], checked[20..]);
    }

    #[test]
    fn a_skipped_checksum_still_decodes() {
        let original = Packet::new(Command::Write, 1, 2, Bytes::from_static(b"payload"));
        let mut buf = BytesMut::new();
        original.encode(&mut buf, Checksum::Skip).unwrap();
        assert_eq!(decode(&mut buf), Ok(Some(original)));
    }
}