S025: own MTP/PTP client over nusb with replay transport

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-18 14:49:52 -06:00
commit c26c890ac4
14 changed files with 1973 additions and 11 deletions

63
Cargo.lock generated
View file

@ -842,6 +842,16 @@ dependencies = [
"libc",
]
[[package]]
name = "core-foundation"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "core-foundation-sys"
version = "0.8.7"
@ -855,7 +865,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081"
dependencies = [
"bitflags 1.3.2",
"core-foundation",
"core-foundation 0.9.4",
"core-graphics-types",
"foreign-types",
"libc",
@ -868,7 +878,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf"
dependencies = [
"bitflags 1.3.2",
"core-foundation",
"core-foundation 0.9.4",
"libc",
]
@ -911,7 +921,7 @@ dependencies = [
"jni",
"js-sys",
"libc",
"mach2",
"mach2 0.6.0",
"ndk",
"ndk-context",
"num-derive",
@ -2486,6 +2496,16 @@ version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36eee07d8e02bd95bf52b2e642cf13d33701b94c6e4b04fbf1d1fb07e9cb19e7"
[[package]]
name = "io-kit-sys"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06d3a048d09fbb6597dbf7c69f40d14df4a49487db1487191618c893fc3b1c26"
dependencies = [
"core-foundation-sys",
"mach2 0.5.0",
]
[[package]]
name = "io-lifetimes"
version = "1.0.11"
@ -2899,6 +2919,15 @@ dependencies = [
"num-traits",
]
[[package]]
name = "mach2"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a1b95cd5421ec55b445b5ae102f5ea0e768de1f82bd3001e11f426c269c3aea"
dependencies = [
"libc",
]
[[package]]
name = "mach2"
version = "0.6.0"
@ -3235,6 +3264,28 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "nusb"
version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1de8b6d15f559f50760dad6c1b56fde4041f99dc96a08e55c2b41f44c7417ad9"
dependencies = [
"core-foundation 0.10.1",
"core-foundation-sys",
"futures-core",
"io-kit-sys",
"js-sys",
"linux-raw-sys 0.12.1",
"log",
"once_cell",
"rustix 1.1.6",
"slab",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"windows-sys 0.61.2",
]
[[package]]
name = "objc-sys"
version = "0.3.5"
@ -5463,6 +5514,10 @@ dependencies = [
[[package]]
name = "tunal-devices"
version = "0.1.0"
dependencies = [
"jiff",
"nusb",
]
[[package]]
name = "tunal-dirmeta"
@ -6482,7 +6537,7 @@ dependencies = [
"calloop 0.13.0",
"cfg_aliases",
"concurrent-queue",
"core-foundation",
"core-foundation 0.9.4",
"core-graphics",
"cursor-icon",
"dpi",

View file

@ -29,3 +29,4 @@ symphonia = { version = "0.5", features = ["mp3", "aac", "isomp4"] }
cpal = "0.18"
rubato = "0.16"
rtrb = "0.4"
nusb = "0.2"

View file

@ -10,12 +10,12 @@ A pure-Rust MTP/PTP client (D-007) over a transport trait with an `nusb` impleme
docs/DECISIONS.md D-007; `nusb` docs in ~/.cargo/registry.
## Steps
- [ ] Transport trait (bulk in/out, interrupt in) and the nusb implementation: find the MTP interface (class 6/1/1 or vendor interface named 'MTP'), claim it.
- [ ] Containers: command/data/response/event encode/decode, transaction ids, packet boundaries and zero-length packets, PTP strings (UCS-2 with length) and dates.
- [ ] Session: OpenSession/CloseSession, GetDeviceInfo, GetStorageIDs, GetStorageInfo.
- [ ] Objects: GetObjectHandles, GetObjectInfo, GetObjectPropList when supported, GetObject/GetPartialObject64 streamed, SendObjectInfo + SendObject streamed, DeleteObject, MoveObject, CopyObject, rename via SetObjectPropValue(ObjectFileName); response codes → errors.
- [ ] Replay transport and an example running a scripted session against it.
- [ ] PROGRESS entry, INDEX line, commit `S025: …`
- [x] Transport trait (bulk in/out, interrupt in) and the nusb implementation: find the MTP interface (class 6/1/1 or vendor interface named 'MTP'), claim it.
- [x] Containers: command/data/response/event encode/decode, transaction ids, packet boundaries and zero-length packets, PTP strings (UCS-2 with length) and dates.
- [x] Session: OpenSession/CloseSession, GetDeviceInfo, GetStorageIDs, GetStorageInfo.
- [x] Objects: GetObjectHandles, GetObjectInfo, GetObjectPropList when supported, GetObject/GetPartialObject64 streamed, SendObjectInfo + SendObject streamed, DeleteObject, MoveObject, CopyObject, rename via SetObjectPropValue(ObjectFileName); response codes → errors.
- [x] Replay transport and an example running a scripted session against it.
- [x] PROGRESS entry, INDEX line, commit `S025: …`
## End criteria
- `cargo build --workspace`, `cargo clippy --workspace --all-targets -- -D warnings` and `cargo fmt --check` pass.

View file

@ -54,7 +54,7 @@ Tracker: https://claude.ai/artifact/4X8YCk3cQjUGyuyCqGuU7v
## 09 Devices
- [ ] [S024 — iOS devices over AFC](09%20Devices/S024-ios-afc.md) · Opus high
- [ ] [S025 — MTP protocol over nusb](09%20Devices/S025-mtp-protocol.md) · Opus high
- [x] [S025 — MTP protocol over nusb](09%20Devices/S025-mtp-protocol.md) · Opus high
- [ ] [S026 — Android devices over MTP](09%20Devices/S026-mtp-location.md) · Opus high
## 10 Network

View file

@ -4,3 +4,7 @@ version.workspace = true
edition.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
nusb.workspace = true
jiff.workspace = true

View file

@ -0,0 +1,436 @@
//! Smoke run of the MTP client against a scripted device:
//! `cargo run -p tunal-devices --example mtp_replay -- <scratch dir>`
//!
//! The script is written byte by byte here (not with the crate's encoder). It opens a
//! session, lists the top of a storage and a folder (property list), downloads a 512 KiB
//! object and a range of it, uploads a file, renames, moves, copies and deletes objects, and
//! checks one error response. Also prints the MTP devices on USB (usually none).
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use tunal_devices::mtp::{self, NewObject, ReplayTransport, Session, Step, code};
const PACKET: usize = 512;
const STORAGE: u32 = 0x0001_0001;
const CHUNK: usize = 256 * 1024;
fn main() {
let Some(dir) = std::env::args().nth(1).map(PathBuf::from) else {
eprintln!("usage: mtp_replay <scratch dir>");
std::process::exit(2);
};
std::fs::create_dir_all(&dir).expect("scratch dir");
match mtp::devices() {
Ok(list) => println!("USB MTP devices: {}", list.len()),
Err(e) => println!("USB MTP devices: {e}"),
}
// Object 3 is exactly two bulk chunks long, so its zero-length packet comes in a
// transfer of its own. The upload is packet-aligned, so the host must send one.
let song = pattern(2 * CHUNK - 12, 7);
let upload = pattern(600 * PACKET - 12, 13);
let upload_path = dir.join("upload.bin");
std::fs::write(&upload_path, &upload).expect("write upload");
let mut script = Vec::new();
let mut tid = 0;
let mut exchange = |op: u16,
params: &[u32],
out: Option<Vec<u8>>,
data: Option<(Vec<u8>, bool)>,
code: u16,
response: &[u32]| {
script.push(Step::Out(container(1, op, tid, &params_bytes(params))));
if let Some(out) = out {
script.push(Step::Out(container(2, op, tid, &out)));
}
if let Some((data, zlp)) = data {
script.push(Step::In {
data: container(2, op, tid, &data),
zlp,
});
}
script.push(Step::In {
data: container(3, code, tid, &params_bytes(response)),
zlp: true,
});
tid += 1;
};
let ok = code::OK;
exchange(code::OPEN_SESSION, &[1], None, None, ok, &[]);
exchange(
code::GET_DEVICE_INFO,
&[],
None,
Some((device_info(), true)),
ok,
&[],
);
exchange(
code::GET_STORAGE_IDS,
&[],
None,
Some((u32s(&[STORAGE]), true)),
ok,
&[],
);
exchange(
code::GET_STORAGE_INFO,
&[STORAGE],
None,
Some((storage_info(), true)),
ok,
&[],
);
exchange(
code::GET_OBJECT_HANDLES,
&[STORAGE, 0, code::ROOT],
None,
Some((u32s(&[1, 2]), true)),
ok,
&[],
);
exchange(
code::GET_OBJECT_INFO,
&[1],
None,
Some((object_info(0x3001, 0, 0, "Music", ""), true)),
ok,
&[],
);
exchange(
code::GET_OBJECT_INFO,
&[2],
None,
Some((
object_info(0x3000, 1234, 0, "notes.txt", "20260115T093000"),
true,
)),
ok,
&[],
);
exchange(
code::GET_OBJECT_HANDLES,
&[STORAGE, 0, 1],
None,
Some((u32s(&[3, 4]), true)),
ok,
&[],
);
// No zero-length packet after this aligned list: the response arrives in the same transfer.
exchange(
code::GET_OBJECT_PROP_LIST,
&[1, 0, code::ALL, 0, 1],
None,
Some((prop_list(song.len() as u64), false)),
ok,
&[],
);
exchange(
code::GET_OBJECT,
&[3],
None,
Some((song.clone(), true)),
ok,
&[],
);
exchange(
code::GET_PARTIAL_OBJECT_64,
&[3, 1000, 0, 100],
None,
Some((song[1000..1100].to_vec(), true)),
ok,
&[],
);
exchange(
code::SEND_OBJECT_INFO,
&[STORAGE, 1],
Some(new_object_info(upload.len() as u32)),
None,
ok,
&[STORAGE, 1, 5],
);
exchange(code::SEND_OBJECT, &[], Some(upload.clone()), None, ok, &[]);
exchange(
code::SET_OBJECT_PROP_VALUE,
&[5, 0xDC07],
Some(ptp_string("upload renamed.bin")),
None,
ok,
&[],
);
exchange(code::MOVE_OBJECT, &[2, STORAGE, 1], None, None, ok, &[]);
exchange(code::COPY_OBJECT, &[2, STORAGE, 0], None, None, ok, &[6]);
exchange(code::DELETE_OBJECT, &[99, 0], None, None, 0x2009, &[]);
exchange(code::DELETE_OBJECT, &[6, 0], None, None, ok, &[]);
exchange(code::CLOSE_SESSION, &[], None, None, ok, &[]);
let mut s = Session::new(ReplayTransport::new(PACKET, script));
let info = s.open(1).expect("open session").clone();
println!(
"device: {} {} {} serial {}, {} operations",
info.manufacturer,
info.model,
info.device_version,
info.serial,
info.operations.len()
);
let storages = s.storage_ids().expect("storage ids");
let storage = s.storage_info(storages[0]).expect("storage info");
println!(
"storage {:#010x}: {} ({}), {} of {} bytes free",
storages[0],
storage.description,
storage.volume_label,
storage.free_space,
storage.max_capacity
);
for o in s.list(STORAGE, code::ROOT).expect("list root") {
println!(
" /{}{} {} bytes modified {:?}",
o.name,
if o.is_folder() { "/" } else { "" },
o.size,
o.modified.map(mtp::format_date)
);
}
for o in s.list(STORAGE, 1).expect("list Music") {
println!(
" /Music/{} {} bytes modified {:?}",
o.name,
o.size,
o.modified.map(mtp::format_date)
);
}
let down_path = dir.join("song.mp3");
let mut down = File::create(&down_path).expect("create download");
s.get_object(3, &mut down).expect("download");
down.flush().expect("flush");
let got = std::fs::read(&down_path).expect("read download");
println!("downloaded {} bytes, matches: {}", got.len(), got == song);
let mut range = Vec::new();
let n = s
.get_partial_object(3, 1000, 100, &mut range)
.expect("partial");
println!(
"partial read: {n} bytes, matches: {}",
range == song[1000..1100]
);
let new = NewObject {
name: "upload.bin".into(),
size: upload.len() as u64,
modified: None,
folder: false,
};
let (st, parent, handle) = s
.send_object_info(STORAGE, 1, &new)
.expect("send object info");
let mut file = File::open(&upload_path).expect("open upload");
s.send_object(&mut file, upload.len() as u64)
.expect("send object");
println!(
"uploaded {} bytes as handle {handle} in {parent} of {st:#010x}",
upload.len()
);
s.rename(handle, "upload renamed.bin").expect("rename");
println!("renamed handle {handle}");
s.move_object(2, STORAGE, 1).expect("move");
let copy = s.copy_object(2, STORAGE, code::ROOT).expect("copy");
println!("moved 2 into Music, copied it to the top as {copy}");
match s.delete_object(99) {
Err(e) => println!("delete 99: {e}"),
Ok(()) => println!("delete 99: unexpectedly ok"),
}
s.delete_object(copy).expect("delete copy");
s.close().expect("close");
let finished = s.into_transport().finished();
println!("script finished: {finished}");
if !finished {
std::process::exit(1);
}
}
fn pattern(len: usize, seed: u32) -> Vec<u8> {
let mut x = seed;
(0..len)
.map(|_| {
x = x.wrapping_mul(1_103_515_245).wrapping_add(12_345);
(x >> 16) as u8
})
.collect()
}
fn container(kind: u16, code: u16, tid: u32, payload: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(&((12 + payload.len()) as u32).to_le_bytes());
out.extend_from_slice(&kind.to_le_bytes());
out.extend_from_slice(&code.to_le_bytes());
out.extend_from_slice(&tid.to_le_bytes());
out.extend_from_slice(payload);
out
}
fn params_bytes(params: &[u32]) -> Vec<u8> {
params.iter().flat_map(|p| p.to_le_bytes()).collect()
}
fn u32s(values: &[u32]) -> Vec<u8> {
let mut out = (values.len() as u32).to_le_bytes().to_vec();
out.extend(params_bytes(values));
out
}
fn u16s(values: &[u16]) -> Vec<u8> {
let mut out = (values.len() as u32).to_le_bytes().to_vec();
out.extend(values.iter().flat_map(|v| v.to_le_bytes()));
out
}
fn ptp_string(s: &str) -> Vec<u8> {
if s.is_empty() {
return vec![0];
}
let units: Vec<u16> = s.encode_utf16().chain([0]).collect();
let mut out = vec![units.len() as u8];
out.extend(units.iter().flat_map(|u| u.to_le_bytes()));
out
}
fn device_info() -> Vec<u8> {
let ops = [
0x1001, 0x1002, 0x1003, 0x1004, 0x1005, 0x1007, 0x1008, 0x1009, 0x100B, 0x100C, 0x100D,
0x1019, 0x101A, 0x101B, 0x9803, 0x9804, 0x9805, 0x95C1,
];
let mut d = Vec::new();
d.extend(100u16.to_le_bytes());
d.extend(6u32.to_le_bytes());
d.extend(100u16.to_le_bytes());
d.extend(ptp_string("microsoft.com: 1.0; android.com: 1.0;"));
d.extend(0u16.to_le_bytes());
d.extend(u16s(&ops));
d.extend(u16s(&[0x4002, 0x4003]));
d.extend(u16s(&[0xD401]));
d.extend(u16s(&[]));
d.extend(u16s(&[0x3000, 0x3001, 0x3009]));
for s in ["Example Phones", "Model X", "1.0", "SER123"] {
d.extend(ptp_string(s));
}
d
}
fn storage_info() -> Vec<u8> {
let mut d = Vec::new();
d.extend(3u16.to_le_bytes()); // fixed RAM
d.extend(2u16.to_le_bytes()); // hierarchical
d.extend(0u16.to_le_bytes());
d.extend(64_000_000_000u64.to_le_bytes());
d.extend(12_345_678_901u64.to_le_bytes());
d.extend(0xFFFF_FFFFu32.to_le_bytes());
d.extend(ptp_string("Internal shared storage"));
d.extend(ptp_string(""));
d
}
fn object_info(format: u16, size: u32, parent: u32, name: &str, modified: &str) -> Vec<u8> {
let mut d = Vec::new();
d.extend(STORAGE.to_le_bytes());
d.extend(format.to_le_bytes());
d.extend(0u16.to_le_bytes());
d.extend(size.to_le_bytes());
d.extend(0u16.to_le_bytes());
d.extend([0u8; 4 * 6]);
d.extend(parent.to_le_bytes());
d.extend((if format == 0x3001 { 1u16 } else { 0 }).to_le_bytes());
d.extend([0u8; 8]);
d.extend(ptp_string(name));
d.extend(ptp_string(""));
d.extend(ptp_string(modified));
d.extend(ptp_string(""));
d
}
/// Two children of folder 1, padded with an unknown property so the dataset fills whole
/// packets (the device then skips the zero-length packet).
fn prop_list(song_size: u64) -> Vec<u8> {
let mut entries: Vec<Vec<u8>> = Vec::new();
let prop = |entries: &mut Vec<Vec<u8>>, handle: u32, code: u16, ty: u16, value: Vec<u8>| {
let mut e = handle.to_le_bytes().to_vec();
e.extend(code.to_le_bytes());
e.extend(ty.to_le_bytes());
e.extend(value);
entries.push(e);
};
for (handle, name, size, modified) in [
(3, "song.mp3", song_size, "20251201T120000Z"),
(4, "cover.jpg", 48_213, "20251201T120500+0100"),
] {
prop(
&mut entries,
handle,
0xDC01,
0x0006,
STORAGE.to_le_bytes().to_vec(),
);
prop(
&mut entries,
handle,
0xDC02,
0x0004,
0x3009u16.to_le_bytes().to_vec(),
);
prop(
&mut entries,
handle,
0xDC04,
0x0008,
size.to_le_bytes().to_vec(),
);
prop(&mut entries, handle, 0xDC07, 0xFFFF, ptp_string(name));
prop(&mut entries, handle, 0xDC09, 0xFFFF, ptp_string(modified));
prop(
&mut entries,
handle,
0xDC0B,
0x0006,
1u32.to_le_bytes().to_vec(),
);
}
let used: usize = 12 + 4 + entries.iter().map(Vec::len).sum::<usize>();
// An array-of-u8 property (8 bytes of header + 4 count + n) pads to the packet size.
let pad = (PACKET - (used + 12) % PACKET) % PACKET;
let mut filler = (pad as u32).to_le_bytes().to_vec();
filler.extend(vec![0xAB; pad]);
prop(&mut entries, 3, 0xDC44, 0x4002, filler);
let mut d = (entries.len() as u32).to_le_bytes().to_vec();
for e in entries {
d.extend(e);
}
assert_eq!(
(12 + d.len()) % PACKET,
0,
"prop list must fill whole packets"
);
d
}
fn new_object_info(size: u32) -> Vec<u8> {
let mut d = Vec::new();
d.extend(STORAGE.to_le_bytes());
d.extend(0x3000u16.to_le_bytes());
d.extend(0u16.to_le_bytes());
d.extend(size.to_le_bytes());
d.extend(0u16.to_le_bytes());
d.extend([0u8; 4 * 6]);
d.extend(1u32.to_le_bytes());
d.extend(0u16.to_le_bytes());
d.extend([0u8; 8]);
d.extend(ptp_string("upload.bin"));
d.extend(ptp_string(""));
d.extend(ptp_string(""));
d.extend(ptp_string(""));
d
}

View file

@ -1 +1,3 @@
//! iOS and Android device locations.
pub mod mtp;

View file

@ -0,0 +1,342 @@
//! PTP/USB containers and the little-endian dataset encoding (integers, arrays, strings, dates).
use std::time::SystemTime;
use jiff::Timestamp;
use jiff::civil::DateTime;
use jiff::tz::{Offset, TimeZone};
use super::Error;
/// Bytes before a container's payload: length, type, code, transaction id.
pub const HEADER_LEN: usize = 12;
/// Container length of a data phase bigger than 4 GiB: read until the short packet.
pub const UNKNOWN_LEN: u32 = 0xFFFF_FFFF;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
Command = 1,
Data = 2,
Response = 3,
Event = 4,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Header {
/// Whole container length including the header, or [`UNKNOWN_LEN`].
pub len: u32,
pub kind: Kind,
pub code: u16,
pub tid: u32,
}
impl Header {
pub fn encode(&self) -> [u8; HEADER_LEN] {
let mut out = [0; HEADER_LEN];
out[0..4].copy_from_slice(&self.len.to_le_bytes());
out[4..6].copy_from_slice(&(self.kind as u16).to_le_bytes());
out[6..8].copy_from_slice(&self.code.to_le_bytes());
out[8..12].copy_from_slice(&self.tid.to_le_bytes());
out
}
pub fn decode(bytes: &[u8]) -> Result<Self, Error> {
if bytes.len() < HEADER_LEN {
return Err(Error::Protocol(format!(
"short container ({} bytes)",
bytes.len()
)));
}
let mut r = Reader::new(bytes);
let len = r.u32()?;
let kind = match r.u16()? {
1 => Kind::Command,
2 => Kind::Data,
3 => Kind::Response,
4 => Kind::Event,
k => return Err(Error::Protocol(format!("unknown container type {k}"))),
};
let header = Header {
len,
kind,
code: r.u16()?,
tid: r.u32()?,
};
if (len as usize) < HEADER_LEN {
return Err(Error::Protocol(format!("container length {len}")));
}
Ok(header)
}
}
/// A command, response or event: header plus up to five `u32` parameters.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Container {
pub kind: Kind,
pub code: u16,
pub tid: u32,
pub params: Vec<u32>,
}
impl Container {
pub fn encode(&self) -> Vec<u8> {
let len = HEADER_LEN + 4 * self.params.len();
let header = Header {
len: len as u32,
kind: self.kind,
code: self.code,
tid: self.tid,
};
let mut out = Vec::with_capacity(len);
out.extend_from_slice(&header.encode());
for p in &self.params {
out.extend_from_slice(&p.to_le_bytes());
}
out
}
/// Decodes one whole container; extra parameters past five are ignored.
pub fn decode(bytes: &[u8]) -> Result<Self, Error> {
let header = Header::decode(bytes)?;
let end = (header.len as usize).min(bytes.len());
let params = bytes[HEADER_LEN..end]
.as_chunks::<4>()
.0
.iter()
.take(5)
.map(|c| u32::from_le_bytes(*c))
.collect();
Ok(Container {
kind: header.kind,
code: header.code,
tid: header.tid,
params,
})
}
}
/// Builds a dataset.
#[derive(Default)]
pub struct Writer {
pub buf: Vec<u8>,
}
impl Writer {
pub fn new() -> Self {
Self::default()
}
pub fn u8(&mut self, v: u8) -> &mut Self {
self.buf.push(v);
self
}
pub fn u16(&mut self, v: u16) -> &mut Self {
self.buf.extend_from_slice(&v.to_le_bytes());
self
}
pub fn u32(&mut self, v: u32) -> &mut Self {
self.buf.extend_from_slice(&v.to_le_bytes());
self
}
pub fn u64(&mut self, v: u64) -> &mut Self {
self.buf.extend_from_slice(&v.to_le_bytes());
self
}
/// PTP string: a count of UTF-16 units including the terminating NUL, then the units;
/// the empty string is a single 0. Longer than 254 units is cut.
pub fn string(&mut self, s: &str) -> &mut Self {
let mut units: Vec<u16> = s.encode_utf16().take(254).collect();
if units.last().is_some_and(|u| (0xD800..0xDC00).contains(u)) {
units.pop(); // don't end on half a surrogate pair
}
if units.is_empty() {
return self.u8(0);
}
units.push(0);
self.u8(units.len() as u8);
for u in units {
self.u16(u);
}
self
}
/// PTP date string `YYYYMMDDThhmmss` in local time; `None` is the empty string.
pub fn date(&mut self, t: Option<SystemTime>) -> &mut Self {
let text = t.map(format_date).unwrap_or_default();
self.string(&text)
}
}
/// Reads a dataset; every read fails with `Protocol` at the end of the data.
pub struct Reader<'a> {
data: &'a [u8],
pos: usize,
}
impl<'a> Reader<'a> {
pub fn new(data: &'a [u8]) -> Self {
Reader { data, pos: 0 }
}
pub fn remaining(&self) -> usize {
self.data.len() - self.pos
}
pub fn bytes(&mut self, n: usize) -> Result<&'a [u8], Error> {
if self.remaining() < n {
return Err(Error::Protocol("dataset ends early".into()));
}
let out = &self.data[self.pos..self.pos + n];
self.pos += n;
Ok(out)
}
pub fn u8(&mut self) -> Result<u8, Error> {
Ok(self.bytes(1)?[0])
}
pub fn u16(&mut self) -> Result<u16, Error> {
let b = self.bytes(2)?;
Ok(u16::from_le_bytes([b[0], b[1]]))
}
pub fn u32(&mut self) -> Result<u32, Error> {
let b = self.bytes(4)?;
Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
}
pub fn u64(&mut self) -> Result<u64, Error> {
let b = self.bytes(8)?;
Ok(u64::from_le_bytes(b.try_into().expect("8 bytes")))
}
pub fn u16_array(&mut self) -> Result<Vec<u16>, Error> {
let n = self.u32()? as usize;
if n > self.remaining() / 2 {
return Err(Error::Protocol("array longer than dataset".into()));
}
(0..n).map(|_| self.u16()).collect()
}
pub fn u32_array(&mut self) -> Result<Vec<u32>, Error> {
let n = self.u32()? as usize;
if n > self.remaining() / 4 {
return Err(Error::Protocol("array longer than dataset".into()));
}
(0..n).map(|_| self.u32()).collect()
}
/// PTP string; unpaired surrogates become U+FFFD.
pub fn string(&mut self) -> Result<String, Error> {
let n = usize::from(self.u8()?);
let units: Vec<u16> = (0..n).map(|_| self.u16()).collect::<Result<_, _>>()?;
let end = units.iter().position(|&u| u == 0).unwrap_or(units.len());
Ok(String::from_utf16_lossy(&units[..end]))
}
/// PTP date string; empty or unparsable → `None`.
pub fn date(&mut self) -> Result<Option<SystemTime>, Error> {
Ok(parse_date(&self.string()?))
}
/// Reads one value of PTP data type `ty` (see [`Value`]).
pub fn value(&mut self, ty: u16) -> Result<Value, Error> {
let scalar = |r: &mut Self, ty: u16| -> Result<u128, Error> {
Ok(match ty {
0x0001 | 0x0002 => u128::from(r.u8()?),
0x0003 | 0x0004 => u128::from(r.u16()?),
0x0005 | 0x0006 => u128::from(r.u32()?),
0x0007 | 0x0008 => u128::from(r.u64()?),
0x0009 | 0x000A => u128::from_le_bytes(r.bytes(16)?.try_into().expect("16")),
t => return Err(Error::Protocol(format!("data type {t:#06x}"))),
})
};
match ty {
0xFFFF => Ok(Value::Str(self.string()?)),
t if t & 0x4000 != 0 => {
let n = self.u32()? as usize;
if n > self.remaining() {
return Err(Error::Protocol("array longer than dataset".into()));
}
let items = (0..n)
.map(|_| scalar(self, t & !0x4000))
.collect::<Result<_, _>>()?;
Ok(Value::Array(items))
}
t => Ok(Value::Int(scalar(self, t)?)),
}
}
}
/// A property value: integers of every width widen to `u128` (signed values keep their bits).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Value {
Int(u128),
Array(Vec<u128>),
Str(String),
}
impl Value {
pub fn int(&self) -> Option<u128> {
match self {
Value::Int(v) => Some(*v),
_ => None,
}
}
pub fn str(&self) -> Option<&str> {
match self {
Value::Str(s) => Some(s),
_ => None,
}
}
}
/// `YYYYMMDDThhmmss[.s][Z|±hhmm]`; without a zone the device's time is local time.
pub fn parse_date(s: &str) -> Option<SystemTime> {
let b = s.as_bytes();
if b.len() < 15 || b[8] != b'T' {
return None;
}
let num = |r: std::ops::Range<usize>| -> Option<i32> { s.get(r)?.parse().ok() };
let dt = DateTime::new(
num(0..4)? as i16,
num(4..6)? as i8,
num(6..8)? as i8,
num(9..11)? as i8,
num(11..13)? as i8,
num(13..15)?.min(59) as i8,
0,
)
.ok()?;
let mut rest = &s[15..];
if let Some(frac) = rest.strip_prefix('.') {
rest = frac.trim_start_matches(|c: char| c.is_ascii_digit());
}
let ts = match rest.as_bytes() {
[] => TimeZone::system().to_timestamp(dt).ok()?,
[b'Z'] => Offset::UTC.to_timestamp(dt).ok()?,
[sign @ (b'+' | b'-'), ..] if rest.len() == 5 => {
let h: i32 = rest.get(1..3)?.parse().ok()?;
let m: i32 = rest.get(3..5)?.parse().ok()?;
let secs = (h * 3600 + m * 60) * if *sign == b'-' { -1 } else { 1 };
Offset::from_seconds(secs).ok()?.to_timestamp(dt).ok()?
}
_ => return None,
};
Some(ts.into())
}
pub fn format_date(t: SystemTime) -> String {
let Ok(ts) = Timestamp::try_from(t) else {
return String::new();
};
TimeZone::system()
.to_datetime(ts)
.strftime("%Y%m%dT%H%M%S")
.to_string()
}

View file

@ -0,0 +1,137 @@
//! Own MTP/PTP client (D-007): containers, a session over a [`Transport`], and the object
//! operations Android phones offer. All calls block; run them off the UI thread.
mod container;
mod ops;
mod replay;
mod session;
mod transport;
use std::fmt;
pub use container::{Container, Header, Kind, Reader, Value, Writer, format_date, parse_date};
pub use ops::{DeviceInfo, NewObject, Object, ObjectInfo, StorageInfo};
pub use replay::{ReplayTransport, Step};
pub use session::Session;
pub use transport::{Transport, UsbTransport, devices, mtp_interface};
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Error {
/// The USB device has no usable MTP interface.
NoInterface,
Usb(String),
Disconnected,
Timeout,
/// The device sent something that isn't valid PTP.
Protocol(String),
/// The device answered with this response code (see [`code::response_name`]).
Response(u16),
/// Reading or writing the local side of a transfer failed.
Io(String),
}
impl Error {
pub fn is_response(&self, code: u16) -> bool {
*self == Error::Response(code)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::NoInterface => f.write_str("no MTP interface on this device"),
Error::Usb(e) => write!(f, "USB error: {e}"),
Error::Disconnected => f.write_str("device disconnected"),
Error::Timeout => f.write_str("device did not answer"),
Error::Protocol(e) => write!(f, "protocol error: {e}"),
Error::Response(c) => write!(f, "device error: {} ({c:#06x})", code::response_name(*c)),
Error::Io(e) => write!(f, "{e}"),
}
}
}
impl std::error::Error for Error {}
/// Operation, response, format and property codes (PTP 1.1, MTP 1.1, Android extensions).
pub mod code {
pub const GET_DEVICE_INFO: u16 = 0x1001;
pub const OPEN_SESSION: u16 = 0x1002;
pub const CLOSE_SESSION: u16 = 0x1003;
pub const GET_STORAGE_IDS: u16 = 0x1004;
pub const GET_STORAGE_INFO: u16 = 0x1005;
pub const GET_OBJECT_HANDLES: u16 = 0x1007;
pub const GET_OBJECT_INFO: u16 = 0x1008;
pub const GET_OBJECT: u16 = 0x1009;
pub const DELETE_OBJECT: u16 = 0x100B;
pub const SEND_OBJECT_INFO: u16 = 0x100C;
pub const SEND_OBJECT: u16 = 0x100D;
pub const MOVE_OBJECT: u16 = 0x1019;
pub const COPY_OBJECT: u16 = 0x101A;
pub const GET_PARTIAL_OBJECT: u16 = 0x101B;
pub const GET_OBJECT_PROP_VALUE: u16 = 0x9803;
pub const SET_OBJECT_PROP_VALUE: u16 = 0x9804;
pub const GET_OBJECT_PROP_LIST: u16 = 0x9805;
/// Android: 64-bit offset partial read.
pub const GET_PARTIAL_OBJECT_64: u16 = 0x95C1;
pub const OK: u16 = 0x2001;
pub const SESSION_ALREADY_OPEN: u16 = 0x201E;
pub const INVALID_OBJECT_HANDLE: u16 = 0x2009;
pub const OPERATION_NOT_SUPPORTED: u16 = 0x2005;
pub const FORMAT_UNDEFINED: u16 = 0x3000;
pub const FORMAT_ASSOCIATION: u16 = 0x3001;
pub const ASSOCIATION_FOLDER: u16 = 0x0001;
pub const PROP_STORAGE_ID: u16 = 0xDC01;
pub const PROP_OBJECT_FORMAT: u16 = 0xDC02;
pub const PROP_OBJECT_SIZE: u16 = 0xDC04;
pub const PROP_OBJECT_FILE_NAME: u16 = 0xDC07;
pub const PROP_DATE_MODIFIED: u16 = 0xDC09;
pub const PROP_PARENT_OBJECT: u16 = 0xDC0B;
/// Parent handle of objects at the top of a storage.
pub const ROOT: u32 = 0xFFFF_FFFF;
/// "All" for storage ids, formats and property codes in requests.
pub const ALL: u32 = 0xFFFF_FFFF;
pub fn response_name(code: u16) -> &'static str {
match code {
0x2001 => "OK",
0x2002 => "general error",
0x2003 => "session not open",
0x2004 => "invalid transaction id",
0x2005 => "operation not supported",
0x2006 => "parameter not supported",
0x2007 => "incomplete transfer",
0x2008 => "invalid storage id",
0x2009 => "invalid object handle",
0x200A => "device property not supported",
0x200B => "invalid object format",
0x200C => "storage full",
0x200D => "object write-protected",
0x200E => "storage read-only",
0x200F => "access denied",
0x2010 => "no thumbnail",
0x2012 => "partial deletion",
0x2013 => "storage not available",
0x2014 => "selection by format not supported",
0x2015 => "no valid object info",
0x2019 => "device busy",
0x201A => "invalid parent object",
0x201C => "invalid device property value",
0x201D => "invalid parameter",
0x201E => "session already open",
0x201F => "transaction cancelled",
0xA801 => "invalid object property code",
0xA802 => "invalid object property format",
0xA803 => "invalid object property value",
0xA804 => "invalid object reference",
0xA806 => "invalid dataset",
0xA808 => "selection by depth not supported",
0xA809 => "object too large",
0xA80A => "object property not supported",
_ => "unknown response",
}
}
}

View file

@ -0,0 +1,396 @@
//! Device, storage and object operations on an open [`Session`].
use std::collections::HashMap;
use std::io::{Read, Write};
use std::time::SystemTime;
use super::container::{Reader, Value, Writer};
use super::session::DataOut;
use super::{Error, Session, Transport, code};
#[derive(Clone, Debug, Default)]
pub struct DeviceInfo {
pub standard_version: u16,
pub vendor_extension_id: u32,
pub vendor_extension_version: u16,
pub vendor_extension: String,
pub functional_mode: u16,
pub operations: Vec<u16>,
pub events: Vec<u16>,
pub device_properties: Vec<u16>,
pub capture_formats: Vec<u16>,
pub playback_formats: Vec<u16>,
pub manufacturer: String,
pub model: String,
pub device_version: String,
pub serial: String,
}
#[derive(Clone, Debug, Default)]
pub struct StorageInfo {
pub storage_type: u16,
pub filesystem_type: u16,
/// 0 read-write, 1 read-only without delete, 2 read-only with delete.
pub access: u16,
pub max_capacity: u64,
pub free_space: u64,
pub free_objects: u32,
pub description: String,
pub volume_label: String,
}
/// The ObjectInfo dataset as sent by the device.
#[derive(Clone, Debug, Default)]
pub struct ObjectInfo {
pub storage_id: u32,
pub format: u16,
pub protection: u16,
/// 0xFFFF_FFFF for objects of 4 GiB and more (see [`Object::size`]).
pub compressed_size: u32,
pub parent: u32,
pub association_type: u16,
pub name: String,
pub created: Option<SystemTime>,
pub modified: Option<SystemTime>,
}
/// An object as a file manager needs it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Object {
pub handle: u32,
pub storage_id: u32,
/// [`code::ROOT`] at the top of a storage.
pub parent: u32,
pub format: u16,
pub name: String,
pub size: u64,
pub modified: Option<SystemTime>,
}
impl Object {
pub fn is_folder(&self) -> bool {
self.format == code::FORMAT_ASSOCIATION
}
}
/// What [`Session::send_object_info`] announces.
#[derive(Clone, Debug)]
pub struct NewObject {
pub name: String,
pub size: u64,
pub modified: Option<SystemTime>,
pub folder: bool,
}
impl<T: Transport> Session<T> {
pub fn device_info(&mut self) -> Result<DeviceInfo, Error> {
let (data, _) = self.request_data(code::GET_DEVICE_INFO, &[])?;
let mut r = Reader::new(&data);
Ok(DeviceInfo {
standard_version: r.u16()?,
vendor_extension_id: r.u32()?,
vendor_extension_version: r.u16()?,
vendor_extension: r.string()?,
functional_mode: r.u16()?,
operations: r.u16_array()?,
events: r.u16_array()?,
device_properties: r.u16_array()?,
capture_formats: r.u16_array()?,
playback_formats: r.u16_array()?,
manufacturer: r.string()?,
model: r.string()?,
device_version: r.string()?,
serial: r.string()?,
})
}
pub fn storage_ids(&mut self) -> Result<Vec<u32>, Error> {
let (data, _) = self.request_data(code::GET_STORAGE_IDS, &[])?;
Reader::new(&data).u32_array()
}
pub fn storage_info(&mut self, storage: u32) -> Result<StorageInfo, Error> {
let (data, _) = self.request_data(code::GET_STORAGE_INFO, &[storage])?;
let mut r = Reader::new(&data);
Ok(StorageInfo {
storage_type: r.u16()?,
filesystem_type: r.u16()?,
access: r.u16()?,
max_capacity: r.u64()?,
free_space: r.u64()?,
free_objects: r.u32()?,
description: r.string()?,
volume_label: r.string()?,
})
}
/// Handles of the objects in `parent` ([`code::ROOT`] for the top of `storage`).
pub fn object_handles(&mut self, storage: u32, parent: u32) -> Result<Vec<u32>, Error> {
let (data, _) = self.request_data(code::GET_OBJECT_HANDLES, &[storage, 0, parent])?;
Reader::new(&data).u32_array()
}
pub fn object_info(&mut self, handle: u32) -> Result<ObjectInfo, Error> {
let (data, _) = self.request_data(code::GET_OBJECT_INFO, &[handle])?;
let mut r = Reader::new(&data);
let storage_id = r.u32()?;
let format = r.u16()?;
let protection = r.u16()?;
let compressed_size = r.u32()?;
// Thumbnail format/size/width/height, image width/height/depth.
r.bytes(2 + 4 * 3 + 4 * 3)?;
let parent = r.u32()?;
let association_type = r.u16()?;
r.bytes(4 + 4)?; // association description, sequence number
Ok(ObjectInfo {
storage_id,
format,
protection,
compressed_size,
parent: if parent == 0 { code::ROOT } else { parent },
association_type,
name: r.string()?,
created: r.date()?,
modified: r.date()?,
})
}
/// One object as an [`Object`]; asks for the 64-bit size when the info has none.
pub fn object(&mut self, handle: u32) -> Result<Object, Error> {
let info = self.object_info(handle)?;
let size = if info.compressed_size == u32::MAX {
self.prop_value(handle, code::PROP_OBJECT_SIZE, 0x0008)?
.int()
.unwrap_or(u128::from(u32::MAX)) as u64
} else {
u64::from(info.compressed_size)
};
Ok(Object {
handle,
storage_id: info.storage_id,
parent: info.parent,
format: info.format,
name: info.name,
size,
modified: info.modified,
})
}
/// The objects in `parent`. Uses one GetObjectPropList for a folder when the device has
/// it, else (and at a storage's top, where depth-1 lists aren't portable) one
/// GetObjectInfo per object.
pub fn list(&mut self, storage: u32, parent: u32) -> Result<Vec<Object>, Error> {
let handles = self.object_handles(storage, parent)?;
let mut known = HashMap::new();
if parent != code::ROOT && self.supports(code::GET_OBJECT_PROP_LIST) && !handles.is_empty()
{
match self.object_prop_list(parent, code::ALL, 1) {
Ok(props) => known = objects_from_props(&props),
// Fall back on any refusal of the request.
Err(Error::Response(_)) => {}
Err(e) => return Err(e),
}
}
handles
.into_iter()
.map(|h| match known.remove(&h) {
Some(o) => Ok(o),
None => self.object(h),
})
.collect()
}
/// GetObjectPropList: `(handle, property, value)` for `handle` (`depth` 0) or its
/// children (`depth` 1); `prop` = [`code::ALL`] for every property.
pub fn object_prop_list(
&mut self,
handle: u32,
prop: u32,
depth: u32,
) -> Result<Vec<(u32, u16, Value)>, Error> {
let (data, _) =
self.request_data(code::GET_OBJECT_PROP_LIST, &[handle, 0, prop, 0, depth])?;
let mut r = Reader::new(&data);
let n = r.u32()?;
let mut out = Vec::with_capacity((n as usize).min(r.remaining() / 8));
for _ in 0..n {
let handle = r.u32()?;
let prop = r.u16()?;
let ty = r.u16()?;
out.push((handle, prop, r.value(ty)?));
}
Ok(out)
}
/// GetObjectPropValue; `ty` is the property's PTP data type.
pub fn prop_value(&mut self, handle: u32, prop: u16, ty: u16) -> Result<Value, Error> {
let (data, _) =
self.request_data(code::GET_OBJECT_PROP_VALUE, &[handle, u32::from(prop)])?;
Reader::new(&data).value(ty)
}
/// Streams the whole object into `out`.
pub fn get_object(&mut self, handle: u32, out: &mut dyn Write) -> Result<(), Error> {
let mut sink = |chunk: &[u8]| out.write_all(chunk).map_err(|e| Error::Io(e.to_string()));
self.transaction(code::GET_OBJECT, &[handle], DataOut::None, Some(&mut sink))?;
Ok(())
}
/// Streams up to `len` bytes from `offset` into `out`; returns the bytes sent. Uses the
/// 64-bit Android operation when present, else GetPartialObject (offsets below 4 GiB).
pub fn get_partial_object(
&mut self,
handle: u32,
offset: u64,
len: u32,
out: &mut dyn Write,
) -> Result<u64, Error> {
let mut sent = 0u64;
let mut sink = |chunk: &[u8]| {
sent += chunk.len() as u64;
out.write_all(chunk).map_err(|e| Error::Io(e.to_string()))
};
if self.supports(code::GET_PARTIAL_OBJECT_64) {
let params = [handle, offset as u32, (offset >> 32) as u32, len];
self.transaction(
code::GET_PARTIAL_OBJECT_64,
&params,
DataOut::None,
Some(&mut sink),
)?;
} else {
let offset = u32::try_from(offset)
.map_err(|_| Error::Response(code::OPERATION_NOT_SUPPORTED))?;
self.transaction(
code::GET_PARTIAL_OBJECT,
&[handle, offset, len],
DataOut::None,
Some(&mut sink),
)?;
}
Ok(sent)
}
/// SendObjectInfo into `parent` of `storage`; returns `(storage, parent, handle)` the
/// device chose. A file's bytes must follow with [`Session::send_object`] right away.
pub fn send_object_info(
&mut self,
storage: u32,
parent: u32,
object: &NewObject,
) -> Result<(u32, u32, u32), Error> {
let mut w = Writer::new();
let (format, association) = if object.folder {
(code::FORMAT_ASSOCIATION, code::ASSOCIATION_FOLDER)
} else {
(code::FORMAT_UNDEFINED, 0)
};
w.u32(storage)
.u16(format)
.u16(0) // protection
.u32(u32::try_from(object.size).unwrap_or(u32::MAX));
w.u16(0).u32(0).u32(0).u32(0); // thumbnail format, size, width, height
w.u32(0).u32(0).u32(0); // image width, height, bit depth
w.u32(if parent == code::ROOT { 0 } else { parent })
.u16(association)
.u32(0) // association description
.u32(0) // sequence number
.string(&object.name)
.date(object.modified) // capture date
.date(object.modified)
.string(""); // keywords
let params = [storage, parent];
let response = self.transaction(
code::SEND_OBJECT_INFO,
&params,
DataOut::Bytes(&w.buf),
None,
)?;
match response[..] {
[s, p, h, ..] => Ok((s, p, h)),
_ => Err(Error::Protocol(
"SendObjectInfo response without a handle".into(),
)),
}
}
/// SendObject: streams exactly `len` bytes from `data` (the size given to
/// [`Session::send_object_info`]).
pub fn send_object(&mut self, data: &mut dyn Read, len: u64) -> Result<(), Error> {
self.transaction(code::SEND_OBJECT, &[], DataOut::Stream(data, len), None)?;
Ok(())
}
pub fn delete_object(&mut self, handle: u32) -> Result<(), Error> {
self.request(code::DELETE_OBJECT, &[handle, 0])?;
Ok(())
}
/// Moves `handle` into `parent` of `storage`.
pub fn move_object(&mut self, handle: u32, storage: u32, parent: u32) -> Result<(), Error> {
self.request(code::MOVE_OBJECT, &[handle, storage, root_param(parent)])?;
Ok(())
}
/// Copies `handle` into `parent` of `storage`; returns the copy's handle.
pub fn copy_object(&mut self, handle: u32, storage: u32, parent: u32) -> Result<u32, Error> {
let response = self.request(code::COPY_OBJECT, &[handle, storage, root_param(parent)])?;
response
.first()
.copied()
.ok_or_else(|| Error::Protocol("CopyObject response without a handle".into()))
}
/// Renames through SetObjectPropValue(ObjectFileName).
pub fn rename(&mut self, handle: u32, name: &str) -> Result<(), Error> {
let mut w = Writer::new();
w.string(name);
let params = [handle, u32::from(code::PROP_OBJECT_FILE_NAME)];
self.transaction(
code::SET_OBJECT_PROP_VALUE,
&params,
DataOut::Bytes(&w.buf),
None,
)?;
Ok(())
}
}
/// Move/copy take 0 for "top of the storage".
fn root_param(parent: u32) -> u32 {
if parent == code::ROOT { 0 } else { parent }
}
/// Objects whose name came in a property list; the other fields default when missing.
fn objects_from_props(props: &[(u32, u16, Value)]) -> HashMap<u32, Object> {
let mut out: HashMap<u32, Object> = HashMap::new();
let mut named = Vec::new();
for (handle, prop, value) in props {
let o = out.entry(*handle).or_insert_with(|| Object {
handle: *handle,
storage_id: 0,
parent: code::ROOT,
format: code::FORMAT_UNDEFINED,
name: String::new(),
size: 0,
modified: None,
});
let int = value.int().unwrap_or(0);
match *prop {
code::PROP_STORAGE_ID => o.storage_id = int as u32,
code::PROP_OBJECT_FORMAT => o.format = int as u16,
code::PROP_OBJECT_SIZE => o.size = int as u64,
code::PROP_PARENT_OBJECT => o.parent = if int == 0 { code::ROOT } else { int as u32 },
code::PROP_OBJECT_FILE_NAME => {
o.name = value.str().unwrap_or_default().to_owned();
named.push(*handle);
}
code::PROP_DATE_MODIFIED => {
o.modified = value.str().and_then(super::container::parse_date)
}
_ => {}
}
}
out.retain(|h, _| named.contains(h));
out
}

View file

@ -0,0 +1,153 @@
//! A scripted transport: checks every container the host sends against the script and plays
//! back the device's containers with USB packet semantics (short packets end a transfer,
//! optional zero-length packets after packet-aligned containers).
use std::collections::VecDeque;
use std::time::Duration;
use super::{Error, Transport};
pub enum Step {
/// The host must send exactly this container, over any number of transfers.
Out(Vec<u8>),
/// The device sends this container. `zlp`: a packet-aligned container is followed by a
/// zero-length packet (devices that leave it out run into the next container).
In { data: Vec<u8>, zlp: bool },
}
pub struct ReplayTransport {
packet: usize,
steps: VecDeque<Step>,
step: usize,
sent: Vec<u8>,
expect_zlp: bool,
reading: Option<(Vec<u8>, usize, bool)>,
zlp_pending: bool,
}
impl ReplayTransport {
pub fn new(packet: usize, steps: Vec<Step>) -> Self {
ReplayTransport {
packet,
steps: steps.into(),
step: 0,
sent: Vec::new(),
expect_zlp: false,
reading: None,
zlp_pending: false,
}
}
/// True when every step was played and nothing is half sent or received.
pub fn finished(&self) -> bool {
self.steps.is_empty() && self.sent.is_empty() && self.reading.is_none() && !self.expect_zlp
}
fn fail(&self, what: String) -> Error {
Error::Protocol(format!("replay step {}: {what}", self.step + 1))
}
}
impl Transport for ReplayTransport {
fn max_packet_size(&self) -> usize {
self.packet
}
fn send(&mut self, data: &[u8]) -> Result<(), Error> {
if self.expect_zlp {
if !data.is_empty() {
return Err(self.fail("expected a zero-length packet".into()));
}
self.expect_zlp = false;
return Ok(());
}
if data.is_empty() {
return Err(self.fail("unexpected zero-length packet".into()));
}
self.sent.extend_from_slice(data);
if self.sent.len() < 4 {
return Ok(());
}
let len = u32::from_le_bytes(self.sent[..4].try_into().expect("4 bytes")) as usize;
if self.sent.len() < len {
return Ok(());
}
let Some(Step::Out(expected)) = self.steps.front() else {
return Err(self.fail("host sent a container where the device should talk".into()));
};
if self.sent != *expected {
let at = self
.sent
.iter()
.zip(expected)
.position(|(a, b)| a != b)
.unwrap_or(self.sent.len().min(expected.len()));
return Err(self.fail(format!(
"sent {} bytes, expected {}, first difference at byte {at}",
self.sent.len(),
expected.len()
)));
}
self.expect_zlp = len.is_multiple_of(self.packet);
self.sent.clear();
self.steps.pop_front();
self.step += 1;
Ok(())
}
fn receive(&mut self, max: usize) -> Result<Vec<u8>, Error> {
if max == 0 || !max.is_multiple_of(self.packet) {
return Err(self.fail(format!("read of {max} bytes is not whole packets")));
}
if self.expect_zlp || !self.sent.is_empty() {
return Err(self.fail("host reads before finishing its container".into()));
}
if self.zlp_pending {
self.zlp_pending = false;
return Ok(Vec::new());
}
let mut out = Vec::new();
while out.len() < max {
if self.reading.is_none() {
match self.steps.front() {
Some(Step::In { .. }) => {
let Some(Step::In { data, zlp }) = self.steps.pop_front() else {
unreachable!()
};
self.step += 1;
self.reading = Some((data, 0, zlp));
}
_ if out.is_empty() => {
return Err(
self.fail("host reads but the device has nothing to send".into())
);
}
_ => break,
}
}
let (data, pos, zlp) = self.reading.as_mut().expect("reading set");
let take = (max - out.len()).min(data.len() - *pos);
out.extend_from_slice(&data[*pos..*pos + take]);
*pos += take;
if *pos < data.len() {
break; // transfer full
}
let aligned = data.len().is_multiple_of(self.packet);
let zlp = *zlp;
self.reading = None;
if !aligned {
break; // short packet
}
if zlp {
// The zero-length packet ends this transfer, or the next one if this is full.
self.zlp_pending = out.len() == max;
break;
}
}
Ok(out)
}
fn event(&mut self, _timeout: Duration) -> Result<Option<Vec<u8>>, Error> {
Ok(None)
}
}

View file

@ -0,0 +1,289 @@
//! Transactions: command → optional data phase (either way) → response, with transaction ids,
//! streamed data and the zero-length packet rules of PTP over USB.
use std::io::Read;
use std::time::Duration;
use super::container::{Container, HEADER_LEN, Header, Kind, UNKNOWN_LEN};
use super::ops::DeviceInfo;
use super::{Error, Transport, code};
/// Bytes per bulk transfer (a multiple of every USB packet size).
const CHUNK: usize = 256 * 1024;
/// Zero-length transfers tolerated before a container.
const MAX_EMPTY: usize = 4;
/// Data sent to the device in a transaction's data phase.
pub enum DataOut<'a> {
None,
Bytes(&'a [u8]),
/// Exactly `len` bytes read from the reader, in chunks.
Stream(&'a mut dyn Read, u64),
}
/// Receives the data phase from the device, chunk by chunk.
pub type Sink<'a> = &'a mut dyn FnMut(&[u8]) -> Result<(), Error>;
/// An open (or not yet opened) MTP session on one device.
pub struct Session<T: Transport> {
transport: T,
session_id: u32,
tid: u32,
/// Bytes of the next container already received (devices that skip zero-length packets).
ahead: Vec<u8>,
pub(super) info: Option<DeviceInfo>,
}
impl<T: Transport> Session<T> {
/// A session over `transport`; call [`Session::open`] before object operations.
pub fn new(transport: T) -> Self {
Session {
transport,
session_id: 0,
tid: 0,
ahead: Vec::new(),
info: None,
}
}
pub fn is_open(&self) -> bool {
self.session_id != 0
}
/// OpenSession with `id` (non-zero), then reads and keeps the device info.
/// A session left open by an earlier client is taken over.
pub fn open(&mut self, id: u32) -> Result<&DeviceInfo, Error> {
self.tid = 0;
match self.request(code::OPEN_SESSION, &[id]) {
Ok(_) => {}
Err(e) if e.is_response(code::SESSION_ALREADY_OPEN) => {}
Err(e) => return Err(e),
}
self.session_id = id;
let info = self.device_info()?;
Ok(self.info.insert(info))
}
pub fn close(&mut self) -> Result<(), Error> {
if self.is_open() {
self.request(code::CLOSE_SESSION, &[])?;
self.session_id = 0;
}
Ok(())
}
pub fn into_transport(self) -> T {
self.transport
}
/// Device info from [`Session::open`].
pub fn info(&self) -> Option<&DeviceInfo> {
self.info.as_ref()
}
/// True when the device lists `op` among its operations.
pub fn supports(&self, op: u16) -> bool {
self.info
.as_ref()
.is_some_and(|i| i.operations.contains(&op))
}
/// Waits up to `timeout` for an event; returns its code and parameters.
pub fn event(&mut self, timeout: Duration) -> Result<Option<Container>, Error> {
match self.transport.event(timeout)? {
Some(bytes) => Ok(Some(Container::decode(&bytes)?)),
None => Ok(None),
}
}
/// A transaction without a data phase; returns the response parameters.
pub fn request(&mut self, op: u16, params: &[u32]) -> Result<Vec<u32>, Error> {
self.transaction(op, params, DataOut::None, None)
}
/// A transaction whose data phase comes from the device, collected in memory
/// (datasets; files go through [`Session::transaction`] with a sink).
pub fn request_data(&mut self, op: u16, params: &[u32]) -> Result<(Vec<u8>, Vec<u32>), Error> {
let mut data = Vec::new();
let mut sink = |chunk: &[u8]| {
data.extend_from_slice(chunk);
Ok(())
};
let response = self.transaction(op, params, DataOut::None, Some(&mut sink))?;
Ok((data, response))
}
/// One whole transaction. With `sink`, a data phase from the device is streamed into it;
/// if the sink fails, the rest of the phase is drained so the session stays in step,
/// and the sink's error is returned.
pub fn transaction(
&mut self,
op: u16,
params: &[u32],
data: DataOut,
mut sink: Option<Sink>,
) -> Result<Vec<u32>, Error> {
let tid = self.next_tid();
let command = Container {
kind: Kind::Command,
code: op,
tid,
params: params.to_vec(),
};
self.transport.send(&command.encode())?;
match data {
DataOut::None => {}
DataOut::Bytes(bytes) => {
self.send_data(op, tid, &mut &bytes[..], bytes.len() as u64)?
}
DataOut::Stream(reader, len) => self.send_data(op, tid, reader, len)?,
}
let mut sink_error = None;
let first = self.next_container()?;
let header = Header::decode(&first)?;
let response = if header.kind == Kind::Data {
check_tid(&header, tid)?;
let mut deliver = |chunk: &[u8]| -> Result<(), Error> {
if let (Some(sink), None) = (&mut sink, &sink_error) {
sink_error = sink(chunk).err();
}
Ok(())
};
self.receive_data(&header, &first[HEADER_LEN..], &mut deliver)?;
self.next_container()?
} else {
first
};
let response = Container::decode(&response)?;
if response.kind != Kind::Response {
return Err(Error::Protocol(format!(
"expected a response, got {:?}",
response.kind
)));
}
if response.tid != tid {
return Err(Error::Protocol(format!(
"response for transaction {} instead of {tid}",
response.tid
)));
}
if response.code != code::OK {
return Err(Error::Response(response.code));
}
match sink_error {
Some(e) => Err(e),
None => Ok(response.params),
}
}
fn next_tid(&mut self) -> u32 {
// OpenSession and anything outside a session use 0; inside, ids run from 1.
if self.session_id == 0 {
return 0;
}
self.tid = self.tid.wrapping_add(1).max(1);
self.tid
}
/// Data container: the header travels with the first chunk; a phase that ends on a packet
/// boundary gets a zero-length packet.
fn send_data(
&mut self,
op: u16,
tid: u32,
reader: &mut dyn Read,
len: u64,
) -> Result<(), Error> {
let total = len + HEADER_LEN as u64;
let header = Header {
len: u32::try_from(total).unwrap_or(UNKNOWN_LEN),
kind: Kind::Data,
code: op,
tid,
};
let mut buf = Vec::with_capacity(CHUNK);
buf.extend_from_slice(&header.encode());
let mut left = len;
loop {
let want = (CHUNK - buf.len()).min(usize::try_from(left).unwrap_or(usize::MAX));
let start = buf.len();
buf.resize(start + want, 0);
read_full(reader, &mut buf[start..])?;
left -= want as u64;
self.transport.send(&buf)?;
buf.clear();
if left == 0 {
break;
}
}
if total.is_multiple_of(self.transport.max_packet_size() as u64) {
self.transport.send(&[])?;
}
Ok(())
}
/// Streams the rest of a data container whose first transfer was `body`.
fn receive_data(&mut self, header: &Header, body: &[u8], deliver: Sink) -> Result<(), Error> {
if header.len == UNKNOWN_LEN {
// Over 4 GiB: the phase ends with the first short transfer.
deliver(body)?;
let mut last = body.len() + HEADER_LEN;
while last == CHUNK {
let chunk = self.transport.receive(CHUNK)?;
last = chunk.len();
deliver(&chunk)?;
}
return Ok(());
}
let mut left = header.len as usize - HEADER_LEN;
let mut chunk = body.to_vec();
loop {
let take = chunk.len().min(left);
deliver(&chunk[..take])?;
left -= take;
if left == 0 {
// Past the end: the next container, sent without a zero-length packet.
self.ahead = chunk.split_off(take);
return Ok(());
}
chunk = self.transport.receive(CHUNK)?;
if chunk.is_empty() {
return Err(Error::Protocol(format!(
"data phase ended {left} bytes early"
)));
}
}
}
/// The first transfer of the next container (zero-length packets before it are skipped).
fn next_container(&mut self) -> Result<Vec<u8>, Error> {
if !self.ahead.is_empty() {
return Ok(std::mem::take(&mut self.ahead));
}
for _ in 0..MAX_EMPTY {
let chunk = self.transport.receive(CHUNK)?;
if !chunk.is_empty() {
return Ok(chunk);
}
}
Err(Error::Protocol("device sent only empty packets".into()))
}
}
fn check_tid(header: &Header, tid: u32) -> Result<(), Error> {
if header.tid == tid {
Ok(())
} else {
Err(Error::Protocol(format!(
"data for transaction {} instead of {tid}",
header.tid
)))
}
}
fn read_full(reader: &mut dyn Read, buf: &mut [u8]) -> Result<(), Error> {
reader.read_exact(buf).map_err(|e| match e.kind() {
std::io::ErrorKind::UnexpectedEof => Error::Io("file ended before its size".into()),
_ => Error::Io(e.to_string()),
})
}

View file

@ -0,0 +1,138 @@
//! USB transfers under a session: a trait, and its `nusb` implementation.
use std::time::Duration;
use nusb::descriptors::TransferType;
use nusb::transfer::{Buffer, Bulk, Direction, In, Interrupt, Out, TransferError};
use nusb::{DeviceInfo, Endpoint, InterfaceInfo, MaybeFuture};
use super::Error;
/// Wait for one transfer before giving up.
const TIMEOUT: Duration = Duration::from_secs(10);
/// Bulk in/out and interrupt in, one USB transfer per call.
pub trait Transport: Send {
/// Bulk endpoint packet size; data phases that fill whole packets end with an empty one.
fn max_packet_size(&self) -> usize;
/// One bulk-out transfer; an empty `data` sends a zero-length packet.
fn send(&mut self, data: &[u8]) -> Result<(), Error>;
/// One bulk-in transfer of at most `max` bytes (a multiple of the packet size). It ends at
/// the first short packet, so it never spans two containers unless a device leaves out
/// the zero-length packet after a data phase.
fn receive(&mut self, max: usize) -> Result<Vec<u8>, Error>;
/// One interrupt-in transfer (an event container), `None` when nothing came in `timeout`.
fn event(&mut self, timeout: Duration) -> Result<Option<Vec<u8>>, Error>;
}
/// An MTP interface claimed on a USB device.
pub struct UsbTransport {
bulk_in: Endpoint<Bulk, In>,
bulk_out: Endpoint<Bulk, Out>,
interrupt: Option<Endpoint<Interrupt, In>>,
}
/// Connected devices that have an MTP interface.
pub fn devices() -> Result<Vec<DeviceInfo>, Error> {
let list = nusb::list_devices().wait().map_err(usb_error)?;
Ok(list.filter(|d| mtp_interface(d).is_some()).collect())
}
/// The MTP interface: still image class 6/1/1 (PTP, which MTP extends), or a vendor
/// interface named "MTP" (phones that also offer other vendor interfaces).
pub fn mtp_interface(device: &DeviceInfo) -> Option<u8> {
let is_mtp = |i: &&InterfaceInfo| {
(i.class(), i.subclass(), i.protocol()) == (6, 1, 1)
|| (i.class() == 0xFF && i.interface_string() == Some("MTP"))
};
device
.interfaces()
.find(is_mtp)
.map(|i| i.interface_number())
}
impl UsbTransport {
pub fn open(device: &DeviceInfo) -> Result<Self, Error> {
let number = mtp_interface(device).ok_or(Error::NoInterface)?;
let device = device.open().wait().map_err(usb_error)?;
let interface = device
.detach_and_claim_interface(number)
.wait()
.map_err(usb_error)?;
let descriptor = interface.descriptor().ok_or(Error::NoInterface)?;
let find = |ty: TransferType, dir: Direction| {
descriptor
.endpoints()
.find(|e| e.transfer_type() == ty && e.direction() == dir)
.map(|e| e.address())
};
let (Some(bulk_in), Some(bulk_out)) = (
find(TransferType::Bulk, Direction::In),
find(TransferType::Bulk, Direction::Out),
) else {
return Err(Error::NoInterface);
};
let interrupt = find(TransferType::Interrupt, Direction::In);
Ok(UsbTransport {
bulk_in: interface.endpoint(bulk_in).map_err(usb_error)?,
bulk_out: interface.endpoint(bulk_out).map_err(usb_error)?,
interrupt: match interrupt {
Some(a) => Some(interface.endpoint(a).map_err(usb_error)?),
None => None,
},
})
}
}
impl Transport for UsbTransport {
fn max_packet_size(&self) -> usize {
self.bulk_in.max_packet_size()
}
fn send(&mut self, data: &[u8]) -> Result<(), Error> {
let mut buf = Buffer::new(data.len());
buf.extend_from_slice(data);
let done = self.bulk_out.transfer_blocking(buf, TIMEOUT);
if done.status == Err(TransferError::Stall) {
let _ = self.bulk_out.clear_halt().wait();
}
done.status.map_err(transfer_error)
}
fn receive(&mut self, max: usize) -> Result<Vec<u8>, Error> {
let done = self.bulk_in.transfer_blocking(Buffer::new(max), TIMEOUT);
if done.status == Err(TransferError::Stall) {
let _ = self.bulk_in.clear_halt().wait();
}
done.status.map_err(transfer_error)?;
Ok(done.buffer.into_vec())
}
fn event(&mut self, timeout: Duration) -> Result<Option<Vec<u8>>, Error> {
let Some(ep) = &mut self.interrupt else {
std::thread::sleep(timeout);
return Ok(None);
};
let size = ep.max_packet_size().max(64);
match ep
.transfer_blocking(Buffer::new(size), timeout)
.into_result()
{
Ok(buf) => Ok(Some(buf.into_vec())),
Err(TransferError::Cancelled) => Ok(None),
Err(e) => Err(transfer_error(e)),
}
}
}
fn usb_error(e: nusb::Error) -> Error {
Error::Usb(e.to_string())
}
fn transfer_error(e: TransferError) -> Error {
match e {
TransferError::Cancelled => Error::Timeout,
TransferError::Disconnected => Error::Disconnected,
e => Error::Usb(e.to_string()),
}
}

View file

@ -99,5 +99,14 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done,
- Not done: mouse back/forward buttons not exercised (winit only; no live window). Tab and section motion not watched (software renderer ignores `transform-*`; screenshots are single frames). Completion list delivery needs the event loop (logic and list checked separately). A closed tab vanishes at once; the others slide over.
- Later: tab bar scrolling past the minimum width; drag-reorder bookmarks in the sidebar; per-place glyph on tabs (Music shows a plain folder); Backspace to go up.
## S025 — MTP protocol over nusb
- Done: `tunal_devices::mtp` (D-007, nusb 0.2, jiff for dates). `Transport` trait (`max_packet_size`, `send` one bulk-out transfer / empty = ZLP, `receive(max)` one bulk-in transfer, `event(timeout)`); `UsbTransport::open(&DeviceInfo)` (interface 6/1/1 or vendor 0xFF named "MTP", `detach_and_claim_interface`, clears halt on stall, 10 s per transfer), `devices()`, `mtp_interface()`. `Container`/`Header`/`Kind`, `Writer`/`Reader` (ints, arrays, PTP strings, dates, `Value` by data type), `parse_date` (local, `Z`, `±hhmm`) / `format_date` (local).
- `Session<T>`: `new`, `open(id) -> &DeviceInfo` (takes over SessionAlreadyOpen), `close`, `supports(op)`, `event`, `request`, `request_data`, `transaction(op, params, DataOut::{None, Bytes, Stream(reader, len)}, Option<sink>)` (tid 0 outside a session, 1.. inside; header travels with the first 256 KiB chunk; host ZLP after aligned data; skips empty transfers before a container; bytes past a data phase kept for the next container (devices without ZLP); >4 GiB `0xFFFFFFFF` length read to the short transfer; a failing sink drains the phase so the session stays in step).
- Ops: `device_info`, `storage_ids`, `storage_info`, `object_handles(storage, parent)`, `object_info`, `object(h)` (64-bit size via ObjectSize when needed), `list(storage, parent) -> Vec<Object { handle, storage_id, parent, format, name, size, modified }>` (one GetObjectPropList depth 1 for folders when supported, else ObjectInfo per handle; top of storage always ObjectInfo), `object_prop_list`, `prop_value`, `get_object(h, &mut Write)`, `get_partial_object(h, offset, len, &mut Write)` (0x95C1 if offered, else 32-bit), `send_object_info(storage, parent, &NewObject { name, size, modified, folder }) -> (storage, parent, handle)`, `send_object(&mut Read, len)`, `delete_object`, `move_object`, `copy_object`, `rename`. `code::*` constants, `Error::{NoInterface, Usb, Disconnected, Timeout, Protocol, Response(u16), Io}`, `code::response_name`. Parent `code::ROOT` = top of storage.
- `ReplayTransport::new(packet, Vec<Step::{Out(container), In { data, zlp }}>)` + `finished()`; example `mtp_replay <scratch dir>` (script bytes built by hand, not by the crate).
- Verified: workspace build; clippy -D warnings and fmt --check for `tunal-devices`; example: open, device/storage info, list root (ObjectInfo) and folder (prop list without ZLP, read-ahead path), 512 KiB download with its ZLP in a transfer of its own (bytes match), range read, packet-aligned 300 KB upload streamed from a file (host ZLP checked), rename, move, copy, error 0x2009 → `Response`, close, script finished; dates checked in local time (CST). `devices()` on this PC: 0.
- Not done: no real device (S036). Workspace-wide clippy/fmt currently fail only in S011's in-progress `crates/tunal/src/{smoke,actions,jobs_bridge}.rs`. Events only decoded, not acted on. I touched `crates/tunal-devices/src/lib.rs` (one `pub mod mtp;` line) and added `examples/`, outside `src/mtp/**`.
- Later: MTP class Cancel request (0x64) for aborting a running transfer; GetObjectPropsSupported checks; event-driven refresh (ObjectAdded/Removed) in S026.
## Later
-