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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
//! ADB sync protocol — file operations (stat, list, push, pull).
//!
//! The sync protocol operates over a `sync:\0` channel and provides
//! file-system access on the device.  Each message uses an 8-byte
//! header: `[id: 4 ASCII bytes, arg: u32 LE]`, optionally followed
//! by a variable-length payload.
//!
//! This module supports both legacy (v1) and extended (v2) variants:
//!
//! | Operation | v1 | v2 | Feature |
//! |-----------|----|----|---------|
//! | Stat | `STAT` | `STA2` | `stat_v2` |
//! | List dir | `LIST`→`DENT` | `LIS2` | `ls_v2` |
//! | Pull file | `RECV` | `RCV2` | `sendrecv_v2` |
//! | Push file | `SEND` | `SND2` | `sendrecv_v2` |
//!
//! Each of the [`SyncFlags`] `RCV2` and `SND2` carry needs a feature of
//! its own on top of `sendrecv_v2`.
//!
//! # Paths
//!
//! adbd keeps a path in a C string, so a NUL would end it early. `SND2`
//! and the requests that only read would act on the file named before
//! the NUL, with no error. `SEND` would lose the mode that follows the
//! path: adbd fails with `missing , in ID_SEND_V1` and ends the service,
//! unless a comma comes before the NUL, which it then takes for the one
//! before the mode.
//!
//! So every call that takes a path fails with
//! [`SyncError::InvalidPath`] on a NUL, before anything is sent and
//! before it looks at what the device advertises. The session stays
//! usable.
//!
//! # A push the device fails
//!
//! adbd answers some pushes with `FAIL` and ends the sync service
//! before it has read them through, a path over 1024 bytes for one. A
//! push call that then finds the channel closed fails with the
//! [`SyncError::Failed`] the device sent, and with
//! [`Error::ChannelClosed`] only if it sent none. Either way it waits
//! for nothing more from the device.
//!
//! # Buffer sizing
//!
//! [`SyncSession`] uses a caller-provided byte slice as its receive
//! buffer.  The minimum useful size depends on the operation:
//!
//! * **stat / stat_v2**: 72 bytes.
//! * **list / list_v2**: 76 bytes + longest file name.
//! * **recv / send**: [`HEADER_SIZE`] + [`SYNC_DATA_MAX`] = 65 544
//!   bytes to fit the largest `DATA` chunk the device may send.
//!
//! Passing a buffer that is too small yields
//! [`Error::ReceiveBufferFull`] — except for a `FAIL` body, which is
//! truncated to the buffer instead so the device's error is never
//! masked by a buffer complaint.
//!
//! # Examples
//!
//! ```ignore
//! let mut buf = [0u8; 66_000];
//! let mut sync = sync::open(&mut conn, &mut buf).await?;
//!
//! // stat
//! let st = sync.stat_v2("/sdcard/DCIM").await?;
//!
//! // list
//! for entry in sync.list_v2("/sdcard/DCIM").await? {
//!     println!("{}", core::str::from_utf8(&entry.name).unwrap());
//! }
//!
//! // pull (small file)
//! let data = sync.recv("/sdcard/file.txt").await?;
//!
//! // push
//! sync.send("/sdcard/upload.txt", FileMode(0o100644), 0, b"hello").await?;
//!
//! sync.quit().await?;
//! ```

mod error;
mod format;
#[cfg(test)]
mod tests;

pub use error::SyncError;
pub use format::*;

use alloc::vec::Vec;

use crate::base::channel::Channel;
use crate::base::decimal::format_u32;
use crate::base::protocol::features::Feature;
use crate::base::recv_buf::RecvBuf;
use crate::base::session::Session;
use crate::error::Error;
use format::{u32_at, SyncId, DENT_V1_SIZE, DENT_V2_SIZE, STAT_V1_SIZE};

const FLAG_FEATURES: [(SyncFlags, Feature); 4] = [
    (SyncFlags::BROTLI, Feature::SendrecvV2Brotli),
    (SyncFlags::LZ4, Feature::SendrecvV2Lz4),
    (SyncFlags::ZSTD, Feature::SendrecvV2Zstd),
    (SyncFlags::DRY_RUN, Feature::SendrecvV2DryRunSend),
];

const COMPRESSION: [SyncFlags; 3] = [SyncFlags::BROTLI, SyncFlags::LZ4, SyncFlags::ZSTD];

fn check_path(path: &str) -> Result<(), SyncError> {
    if path.contains('\0') {
        return Err(SyncError::InvalidPath);
    }
    Ok(())
}

/// A sync session over an open `sync:\0` channel.
///
/// Provides stat, list, push and pull operations.  Created by [`open`].
/// Multiple operations can be performed on the same session before
/// calling [`quit`](Self::quit).
pub struct SyncSession<'a, 'b, S> {
    channel: Channel<'a, S>,
    rx: RecvBuf<'b>,
}

impl<'a, 'b, S: Session> SyncSession<'a, 'b, S> {
    /// Wrap an already-opened `sync:\0` channel.
    ///
    /// # Panics
    ///
    /// Panics if `buf.len() < HEADER_SIZE`.
    pub fn new(channel: Channel<'a, S>, buf: &'b mut [u8]) -> Self {
        assert!(
            buf.len() >= HEADER_SIZE,
            "SyncSession buffer must be at least {} bytes",
            HEADER_SIZE,
        );
        Self {
            channel,
            rx: RecvBuf::new(buf),
        }
    }

    fn require_sendrecv_v2(&self, flags: SyncFlags) -> Result<(), Error<S::IoError>> {
        if COMPRESSION.iter().filter(|&&c| flags.contains(c)).count() > 1 {
            return Err(SyncError::InvalidFlags(flags).into());
        }
        self.channel.session.require_feature(Feature::SendrecvV2)?;
        for (flag, feature) in FLAG_FEATURES {
            if flags.contains(flag) {
                self.channel.session.require_feature(feature)?;
            }
        }
        Ok(())
    }

    fn peek_id(&self) -> [u8; 4] {
        self.rx.peek(4).try_into().expect("peeked four bytes")
    }

    fn peek_u32(&self, offset: usize) -> u32 {
        u32_at(self.rx.peek(offset + 4), offset)
    }

    async fn write_header(&mut self, id: SyncId, arg: u32) -> Result<(), Error<S::IoError>> {
        let mut hdr = [0u8; HEADER_SIZE];
        hdr[..4].copy_from_slice(&id.as_bytes());
        hdr[4..8].copy_from_slice(&arg.to_le_bytes());
        self.channel.write(&hdr).await
    }

    async fn write_request(
        &mut self,
        id: SyncId,
        parts: &[&[u8]],
    ) -> Result<(), Error<S::IoError>> {
        let arg_len: usize = parts.iter().map(|p| p.len()).sum();
        self.write_message(id, arg_len as u32, parts).await
    }

    async fn write_message(
        &mut self,
        id: SyncId,
        arg: u32,
        parts: &[&[u8]],
    ) -> Result<(), Error<S::IoError>> {
        let total = HEADER_SIZE + parts.iter().map(|p| p.len()).sum::<usize>();

        self.rx.compact();
        let window = self.rx.window();

        if total <= window.len() {
            window[..4].copy_from_slice(&id.as_bytes());
            window[4..8].copy_from_slice(&arg.to_le_bytes());
            let mut off = HEADER_SIZE;
            for p in parts {
                window[off..off + p.len()].copy_from_slice(p);
                off += p.len();
            }
            self.channel.write(&window[..total]).await
        } else {
            self.write_header(id, arg).await?;
            for p in parts {
                if !p.is_empty() {
                    self.channel.write(p).await?;
                }
            }
            Ok(())
        }
    }

    async fn read_next_id(&mut self, allowed: &[SyncId]) -> Result<SyncId, Error<S::IoError>> {
        self.rx
            .fill_at_least(&mut self.channel, HEADER_SIZE)
            .await?;
        let raw = self.peek_id();
        match SyncId::from_bytes(raw) {
            Some(SyncId::Fail) => {
                let msg = self.read_fail_body().await?;
                Err(SyncError::Failed(msg).into())
            }
            Some(id) if allowed.contains(&id) => Ok(id),
            _ => Err(SyncError::UnexpectedId(raw).into()),
        }
    }

    async fn pushed(
        &mut self,
        sent: Result<(), Error<S::IoError>>,
    ) -> Result<(), Error<S::IoError>> {
        match sent {
            Err(Error::ChannelClosed) => match self.read_next_id(&[]).await {
                Err(failed @ Error::Sync(SyncError::Failed(_))) => Err(failed),
                _ => Err(Error::ChannelClosed),
            },
            sent => sent,
        }
    }

    async fn read_fail_body(&mut self) -> Result<Vec<u8>, Error<S::IoError>> {
        let msg_len = self.peek_u32(4) as usize;
        self.rx.advance(HEADER_SIZE);
        let kept = msg_len.min(self.rx.capacity());
        if kept > 0 {
            self.rx.fill_at_least(&mut self.channel, kept).await?;
        }
        let msg = self.rx.take(kept).to_vec();
        let mut left = msg_len - kept;
        while left > 0 {
            let chunk = left.min(self.rx.capacity());
            self.rx.fill_at_least(&mut self.channel, chunk).await?;
            self.rx.advance(chunk);
            left -= chunk;
        }
        Ok(msg)
    }

    /// Stat a file (v1).
    ///
    /// Returns zeroed fields when the path does not exist (v1 has no
    /// error code).
    pub async fn stat(&mut self, path: &str) -> Result<StatV1, Error<S::IoError>> {
        check_path(path)?;
        self.rx.compact();
        self.write_request(SyncId::Stat, &[path.as_bytes()]).await?;
        self.read_next_id(&[SyncId::Stat]).await?;

        self.rx
            .fill_at_least(&mut self.channel, STAT_V1_SIZE)
            .await?;
        let mode = FileMode(self.peek_u32(4));
        let size = self.peek_u32(8);
        let mtime = self.peek_u32(12);
        self.rx.advance(STAT_V1_SIZE);
        Ok(StatV1 { mode, size, mtime })
    }

    /// Stat a file (v2).
    ///
    /// Returns full metadata including uid/gid and 64-bit size.
    /// Requires the device to advertise `stat_v2`: one whose banner
    /// does not fails with [`Error::MissingFeature`] before anything is
    /// sent.
    ///
    /// Returns [`SyncError::RemoteErrno`] when the device reports a
    /// non-zero error code (e.g. `ENOENT`).
    pub async fn stat_v2(&mut self, path: &str) -> Result<StatV2, Error<S::IoError>> {
        check_path(path)?;
        self.channel.session.require_feature(Feature::StatV2)?;
        self.rx.compact();
        self.write_request(SyncId::Sta2, &[path.as_bytes()]).await?;
        self.read_next_id(&[SyncId::Sta2]).await?;

        self.rx
            .fill_at_least(&mut self.channel, STAT_V2_SIZE)
            .await?;
        let body = &self.rx.peek(STAT_V2_SIZE)[4..];
        let stat = parse_stat_v2_body(body.try_into().expect("checked STAT_V2_SIZE bytes"));
        self.rx.advance(STAT_V2_SIZE);

        if stat.error != 0 {
            return Err(SyncError::RemoteErrno(stat.error).into());
        }
        Ok(stat)
    }

    /// List a directory (v1).
    pub async fn list(&mut self, path: &str) -> Result<Vec<DirEntry>, Error<S::IoError>> {
        check_path(path)?;
        self.rx.compact();
        self.write_request(SyncId::List, &[path.as_bytes()]).await?;

        let mut entries = Vec::new();
        loop {
            if self.read_next_id(&[SyncId::Dent, SyncId::Done]).await? == SyncId::Done {
                self.rx
                    .fill_at_least(&mut self.channel, DENT_V1_SIZE)
                    .await?;
                self.rx.advance(DENT_V1_SIZE);
                return Ok(entries);
            }

            self.rx
                .fill_at_least(&mut self.channel, DENT_V1_SIZE)
                .await?;
            let mode = FileMode(self.peek_u32(4));
            let size = self.peek_u32(8);
            let mtime = self.peek_u32(12);
            let namelen = self.peek_u32(16) as usize;
            self.rx.advance(DENT_V1_SIZE);

            self.rx.fill_at_least(&mut self.channel, namelen).await?;
            let name = self.rx.take(namelen).to_vec();

            entries.push(DirEntry {
                name,
                mode,
                size,
                mtime,
            });
        }
    }

    /// List a directory (v2).
    ///
    /// Requires the device to advertise `ls_v2`, failing with
    /// [`Error::MissingFeature`] before anything is sent otherwise.
    /// Entries whose stat failed on the device have a non-zero
    /// `stat.error` field but are still included in the result.
    pub async fn list_v2(&mut self, path: &str) -> Result<Vec<DirEntryV2>, Error<S::IoError>> {
        check_path(path)?;
        self.channel.session.require_feature(Feature::LsV2)?;
        self.rx.compact();
        self.write_request(SyncId::Lis2, &[path.as_bytes()]).await?;

        let mut entries = Vec::new();
        loop {
            if self.read_next_id(&[SyncId::Dnt2, SyncId::Done]).await? == SyncId::Done {
                self.rx
                    .fill_at_least(&mut self.channel, DENT_V2_SIZE)
                    .await?;
                self.rx.advance(DENT_V2_SIZE);
                return Ok(entries);
            }

            self.rx
                .fill_at_least(&mut self.channel, DENT_V2_SIZE)
                .await?;
            let body = &self.rx.peek(STAT_V2_SIZE)[4..];
            let stat = parse_stat_v2_body(body.try_into().expect("checked STAT_V2_SIZE bytes"));
            let namelen = self.peek_u32(72) as usize;
            self.rx.advance(DENT_V2_SIZE);

            self.rx.fill_at_least(&mut self.channel, namelen).await?;
            let name = self.rx.take(namelen).to_vec();

            entries.push(DirEntryV2 { name, stat });
        }
    }

    /// Begin a `RECV` (v1) pull.
    pub async fn recv_start(&mut self, path: &str) -> Result<(), Error<S::IoError>> {
        check_path(path)?;
        self.rx.compact();
        self.write_request(SyncId::Recv, &[path.as_bytes()]).await
    }

    /// Begin a `RCV2` (v2) pull.
    ///
    /// `flags` combines [`SyncFlags`]; [`SyncFlags::NONE`] pulls
    /// uncompressed. Requires the device to advertise `sendrecv_v2` and
    /// the feature of each flag, failing with [`Error::MissingFeature`]
    /// otherwise. adbd has no dry-run pull and takes one compression flag
    /// at most, so [`SyncFlags::DRY_RUN`] or two compression flags fail
    /// with [`SyncError::InvalidFlags`] whatever the device advertises.
    /// Either way nothing is sent and the session stays usable.
    pub async fn recv_v2_start(
        &mut self,
        path: &str,
        flags: SyncFlags,
    ) -> Result<(), Error<S::IoError>> {
        check_path(path)?;
        if flags.contains(SyncFlags::DRY_RUN) {
            return Err(SyncError::InvalidFlags(flags).into());
        }
        self.require_sendrecv_v2(flags)?;
        let path_bytes = path.as_bytes();
        self.write_message(
            SyncId::Rcv2,
            path_bytes.len() as u32,
            &[
                path_bytes,
                &SyncId::Rcv2.as_bytes(),
                &flags.bits().to_le_bytes(),
            ],
        )
        .await
    }

    /// Read the next `DATA` chunk from an in-progress recv.
    ///
    /// Returns `Ok(Some(data))` for each chunk and `Ok(None)` when the
    /// device signals `DONE`.  The returned slice references the
    /// internal buffer and is valid until the next method call.
    ///
    /// Must be called after [`recv_start`](Self::recv_start) or
    /// [`recv_v2_start`](Self::recv_v2_start). A chunk that does not
    /// fit the buffer together with its header is
    /// [`Error::ReceiveBufferFull`].
    pub async fn recv_next(&mut self) -> Result<Option<&[u8]>, Error<S::IoError>> {
        self.rx.compact();
        if self.read_next_id(&[SyncId::Data, SyncId::Done]).await? == SyncId::Done {
            self.rx.advance(HEADER_SIZE);
            return Ok(None);
        }

        let data_len = self.peek_u32(4) as usize;
        let chunk_len = HEADER_SIZE
            .checked_add(data_len)
            .ok_or(Error::ReceiveBufferFull)?;
        self.rx.fill_at_least(&mut self.channel, chunk_len).await?;
        self.rx.advance(HEADER_SIZE);
        Ok(Some(self.rx.take(data_len)))
    }

    /// Pull a file into memory (v1 `RECV`).
    ///
    /// Convenience wrapper around [`recv_start`](Self::recv_start) +
    /// [`recv_next`](Self::recv_next).  For large files prefer the
    /// streaming API.
    pub async fn recv(&mut self, path: &str) -> Result<Vec<u8>, Error<S::IoError>> {
        self.recv_start(path).await?;
        let mut data = Vec::new();
        while let Some(chunk) = self.recv_next().await? {
            data.extend_from_slice(chunk);
        }
        Ok(data)
    }

    /// Pull a file into memory (v2 `RCV2`), with `flags` as in
    /// [`recv_v2_start`](Self::recv_v2_start): one the device does not
    /// take fails with [`Error::MissingFeature`] or
    /// [`SyncError::InvalidFlags`] before anything is sent.
    pub async fn recv_v2(
        &mut self,
        path: &str,
        flags: SyncFlags,
    ) -> Result<Vec<u8>, Error<S::IoError>> {
        self.recv_v2_start(path, flags).await?;
        let mut data = Vec::new();
        while let Some(chunk) = self.recv_next().await? {
            data.extend_from_slice(chunk);
        }
        Ok(data)
    }

    /// Begin a `SEND` (v1) push.
    ///
    /// `mode` is what the device creates the file from, e.g.
    /// `FileMode(0o100644)`. adbd copies the owner's permission bits to
    /// the group and to others, so that one lands as `0o100666`.
    ///
    /// On a channel the device closed it fails with the device's `FAIL`,
    /// if it sent one: see
    /// [A push the device fails](crate::sync#a-push-the-device-fails).
    pub async fn send_start(
        &mut self,
        path: &str,
        mode: FileMode,
    ) -> Result<(), Error<S::IoError>> {
        check_path(path)?;
        let mut mode_dec = [0u8; 10];
        let mode_str = format_u32(mode.0, &mut mode_dec);
        let sent = self
            .write_request(SyncId::Send, &[path.as_bytes(), b",", mode_str])
            .await;
        self.pushed(sent).await
    }

    /// Begin a `SND2` (v2) push.
    ///
    /// `mode` is as in [`send_start`](Self::send_start). `flags`
    /// combines [`SyncFlags`]; [`SyncFlags::NONE`] pushes uncompressed.
    /// Requires the device to advertise `sendrecv_v2` and the feature of
    /// each flag, failing with [`Error::MissingFeature`] otherwise. adbd
    /// takes one compression flag at most, so two fail with
    /// [`SyncError::InvalidFlags`] whatever the device advertises.
    /// Either way nothing is sent and the session stays usable.
    ///
    /// On a channel the device closed it fails with the device's `FAIL`,
    /// if it sent one: see
    /// [A push the device fails](crate::sync#a-push-the-device-fails).
    pub async fn send_v2_start(
        &mut self,
        path: &str,
        mode: FileMode,
        flags: SyncFlags,
    ) -> Result<(), Error<S::IoError>> {
        check_path(path)?;
        self.require_sendrecv_v2(flags)?;
        let path_bytes = path.as_bytes();
        let sent = self
            .write_message(
                SyncId::Snd2,
                path_bytes.len() as u32,
                &[
                    path_bytes,
                    &SyncId::Snd2.as_bytes(),
                    &mode.0.to_le_bytes(),
                    &flags.bits().to_le_bytes(),
                ],
            )
            .await;
        self.pushed(sent).await
    }

    /// Send one or more `DATA` chunks.
    ///
    /// `data` is automatically split into [`SYNC_DATA_MAX`]-sized
    /// chunks.  Must be called between a `send*_start` and
    /// [`send_done`](Self::send_done).
    ///
    /// On a channel the device closed it fails with the device's `FAIL`,
    /// if it sent one: see
    /// [A push the device fails](crate::sync#a-push-the-device-fails).
    pub async fn send_data(&mut self, data: &[u8]) -> Result<(), Error<S::IoError>> {
        for chunk in data.chunks(SYNC_DATA_MAX) {
            let sent = self.write_request(SyncId::Data, &[chunk]).await;
            self.pushed(sent).await?;
        }
        Ok(())
    }

    /// Finish a push, providing the file modification time in Unix
    /// seconds: unsigned and 32-bit for v1 and v2 alike, since `DONE`
    /// has no wider field.
    ///
    /// Sends `DONE` and reads the device response (`OKAY` or `FAIL`).
    /// On a channel the device closed it fails with the device's `FAIL`,
    /// if it sent one: see
    /// [A push the device fails](crate::sync#a-push-the-device-fails).
    pub async fn send_done(&mut self, mtime: u32) -> Result<(), Error<S::IoError>> {
        let sent = self.write_header(SyncId::Done, mtime).await;
        self.pushed(sent).await?;
        self.rx.compact();
        self.read_next_id(&[SyncId::Okay]).await?;
        self.rx.advance(HEADER_SIZE);
        Ok(())
    }

    /// Push a file to the device (v1 `SEND`).
    ///
    /// Convenience wrapper around [`send_start`](Self::send_start) +
    /// [`send_data`](Self::send_data) + [`send_done`](Self::send_done).
    pub async fn send(
        &mut self,
        path: &str,
        mode: FileMode,
        mtime: u32,
        data: &[u8],
    ) -> Result<(), Error<S::IoError>> {
        self.send_start(path, mode).await?;
        self.send_data(data).await?;
        self.send_done(mtime).await
    }

    /// Push a file to the device (v2 `SND2`), with `flags` as in
    /// [`send_v2_start`](Self::send_v2_start): one the device does not
    /// take fails with [`Error::MissingFeature`] or
    /// [`SyncError::InvalidFlags`] before anything is sent.
    pub async fn send_v2(
        &mut self,
        path: &str,
        mode: FileMode,
        mtime: u32,
        flags: SyncFlags,
        data: &[u8],
    ) -> Result<(), Error<S::IoError>> {
        self.send_v2_start(path, mode, flags).await?;
        self.send_data(data).await?;
        self.send_done(mtime).await
    }

    /// Send `QUIT` and close the underlying channel. The close goes on
    /// every way out, since nothing else frees the slot ([`Channel`] has
    /// no `Drop`).
    ///
    /// A channel the device has already closed is not a failure: a
    /// transfer that fails ends the sync service on the device, so after
    /// one there is nothing left to quit. A channel a fault closed fails
    /// all the same, with that fault's error, such as
    /// [`Error::ChannelRxOverflow`].
    pub async fn quit(mut self) -> Result<(), Error<S::IoError>> {
        let sent = match self.write_header(SyncId::Quit, 0).await {
            Err(Error::ChannelClosed) => Ok(()),
            sent => sent,
        };
        let closed = self.channel.close().await;
        sent.and(closed)
    }
}

/// Open a `sync:\0` channel and return a [`SyncSession`].
///
/// `buf` is the caller-owned receive buffer — see the
/// [module docs](self) for sizing guidance.
pub async fn open<'a, 'b, S: Session>(
    session: &'a mut S,
    buf: &'b mut [u8],
) -> Result<SyncSession<'a, 'b, S>, Error<S::IoError>> {
    let channel = session.open(b"sync:\0").await?;
    Ok(SyncSession::new(channel, buf))
}