From 0a7fbe580d90d31c3f9b6c4b7975f37a0a2318a5 Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 18 Nov 2026 23:55:31 -0600 Subject: [PATCH] S024: iPhones over usbmuxd and AFC as ios:// locations Hotplug via usbmuxd Listen (hidden when the socket is missing), pairing with a Trust prompt, AFC list/stat/stream/mkdir/rename/delete, Devices entries merged with MTP, Eject in the place menu, ios_location example. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 501 +++++++++++++++++- Cargo.toml | 2 + Plans/09 Devices/S024-ios-afc.md | 12 +- Plans/INDEX.md | 2 +- crates/tunal-devices/Cargo.toml | 2 + crates/tunal-devices/examples/ios_location.rs | 40 ++ crates/tunal-devices/src/ios/location.rs | 268 ++++++++++ crates/tunal-devices/src/ios/mod.rs | 304 +++++++++++ crates/tunal-devices/src/lib.rs | 10 + crates/tunal-devices/src/mtp/location.rs | 9 +- crates/tunal/src/devices_bridge.rs | 110 +++- crates/tunal/src/shell/mod.rs | 16 + docs/PROGRESS.md | 10 + 13 files changed, 1236 insertions(+), 50 deletions(-) create mode 100644 crates/tunal-devices/examples/ios_location.rs create mode 100644 crates/tunal-devices/src/ios/location.rs create mode 100644 crates/tunal-devices/src/ios/mod.rs diff --git a/Cargo.lock b/Cargo.lock index 73caba9..0b1b7b3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -466,12 +466,24 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "base64" version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bincode" version = "2.0.1" @@ -528,6 +540,15 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "block-buffer" version = "0.12.1" @@ -720,6 +741,17 @@ dependencies = [ "libc", ] +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + [[package]] name = "chrono" version = "0.4.45" @@ -729,6 +761,7 @@ dependencies = [ "iana-time-zone", "js-sys", "num-traits", + "serde", "wasm-bindgen", "windows-link", ] @@ -823,6 +856,12 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "const-oid" version = "0.10.3" @@ -944,6 +983,15 @@ dependencies = [ "windows-core", ] +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + [[package]] name = "cpufeatures" version = "0.3.1" @@ -1017,6 +1065,16 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "crypto-common" version = "0.2.2" @@ -1068,6 +1126,36 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "der_derive", + "flagset", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "der_derive" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + [[package]] name = "derive_more" version = "2.1.1" @@ -1091,15 +1179,26 @@ dependencies = [ "unicode-xid", ] +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "const-oid 0.9.6", + "crypto-common 0.1.7", +] + [[package]] name = "digest" version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ - "block-buffer", - "const-oid", - "crypto-common", + "block-buffer 0.12.1", + "const-oid 0.10.3", + "crypto-common 0.2.2", "ctutils", ] @@ -1389,6 +1488,12 @@ dependencies = [ "writeable", ] +[[package]] +name = "flagset" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe" + [[package]] name = "flate2" version = "1.1.11" @@ -1630,6 +1735,16 @@ dependencies = [ "libc", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "gethostname" version = "1.1.0" @@ -1672,6 +1787,7 @@ dependencies = [ "cfg-if", "libc", "r-efi 6.0.0", + "rand_core 0.10.1", ] [[package]] @@ -1886,7 +2002,7 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" dependencies = [ - "digest", + "digest 0.11.3", ] [[package]] @@ -2419,6 +2535,31 @@ version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "913a7d294ad056474749152107309fdee3ec17d2482d1ab70fdc61a81c64b9a3" +[[package]] +name = "idevice" +version = "0.1.68" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5d7799c8497cef60ddfd38f7d92e267b9fa5d0b18e7691d31041453007400ca" +dependencies = [ + "base64 0.22.1", + "chrono", + "futures", + "libc", + "plist", + "plist-macro", + "rand 0.10.4", + "rsa", + "rustls", + "serde", + "sha2", + "thiserror 2.0.21", + "tokio", + "tokio-rustls", + "tracing", + "web-time", + "x509-cert", +] + [[package]] name = "idna" version = "1.1.0" @@ -2770,6 +2911,9 @@ name = "lazy_static" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +dependencies = [ + "spin", +] [[package]] name = "libc" @@ -2986,7 +3130,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" dependencies = [ "cfg-if", - "digest", + "digest 0.11.3", ] [[package]] @@ -3237,6 +3381,22 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.8", + "smallvec", + "zeroize", +] + [[package]] name = "num-complex" version = "0.4.6" @@ -3246,6 +3406,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + [[package]] name = "num-derive" version = "0.4.2" @@ -3266,6 +3432,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -3862,6 +4038,15 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -3966,6 +4151,27 @@ dependencies = [ "futures-io", ] +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "pkg-config" version = "0.3.34" @@ -3978,6 +4184,28 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" +[[package]] +name = "plist" +version = "1.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d86a77b7d9cdebd9643c180c158748db7d894b24a3935ed4b5843e698ae086eb" +dependencies = [ + "base64 0.23.1", + "indexmap", + "quick-xml 0.42.0", + "serde", + "time", +] + +[[package]] +name = "plist-macro" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82c39e020f2d8d361e91a434cfe26bc7c3e21ae54414379816d0110f3f7ca121" +dependencies = [ + "plist", +] + [[package]] name = "png" version = "0.18.1" @@ -4043,6 +4271,21 @@ dependencies = [ "zerovec", ] +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + [[package]] name = "presser" version = "0.3.1" @@ -4124,6 +4367,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "memchr", +] + [[package]] name = "quote" version = "1.0.47" @@ -4145,6 +4397,52 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "rand_chacha", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + [[package]] name = "range-alloc" version = "0.1.5" @@ -4372,6 +4670,27 @@ dependencies = [ "memchr", ] +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid 0.9.6", + "digest 0.10.7", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "sha2", + "signature", + "spki", + "subtle", + "zeroize", +] + [[package]] name = "rspolib" version = "0.1.2" @@ -4614,6 +4933,17 @@ dependencies = [ "serde_core", ] +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + [[package]] name = "sha1" version = "0.11.0" @@ -4621,8 +4951,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" dependencies = [ "cfg-if", - "cpufeatures", - "digest", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", ] [[package]] @@ -4641,6 +4982,16 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest 0.10.7", + "rand_core 0.6.4", +] + [[package]] name = "simd-adler32" version = "0.3.10" @@ -4899,6 +5250,16 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "softbuffer" version = "0.4.8" @@ -4930,6 +5291,12 @@ dependencies = [ "x11rb", ] +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" + [[package]] name = "spin_on" version = "0.1.1" @@ -4948,6 +5315,16 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -5343,6 +5720,36 @@ dependencies = [ "zune-jpeg", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tiny-skia" version = "0.11.4" @@ -5424,13 +5831,49 @@ version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" +[[package]] +name = "tls_codec" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b" +dependencies = [ + "tls_codec_derive", + "zeroize", +] + +[[package]] +name = "tls_codec_derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "tokio" version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ + "bytes", + "libc", + "mio", "pin-project-lite", + "socket2", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", ] [[package]] @@ -5568,8 +6011,10 @@ name = "tunal-devices" version = "0.1.0" dependencies = [ "futures-lite", + "idevice", "jiff", "nusb", + "tokio", "tunal-core", ] @@ -5590,9 +6035,9 @@ dependencies = [ name = "tunal-net" version = "0.1.0" dependencies = [ - "base64", + "base64 0.23.1", "hmac", - "sha1", + "sha1 0.11.0", ] [[package]] @@ -5746,7 +6191,7 @@ version = "3.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ac5cecf619ca81f66a96482db09687c9f7465af65f4300a8c30cca05bd5a59d" dependencies = [ - "base64", + "base64 0.23.1", "flate2", "log", "percent-encoding", @@ -5763,7 +6208,7 @@ version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" dependencies = [ - "base64", + "base64 0.23.1", "http", "httparse", "log", @@ -5787,7 +6232,7 @@ version = "0.49.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d09b73ee83641d390ad7ffd9000f347b16eb128e437675b6ff277ea5c7fcf22c" dependencies = [ - "base64", + "base64 0.23.1", "data-url", "flate2", "fontdb", @@ -5815,7 +6260,7 @@ version = "0.50.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bdb896f04730b97805bbc3191fc57e4bf03face0f14577dd42e783c4d8c98802" dependencies = [ - "base64", + "base64 0.23.1", "data-url", "flate2", "fontdb", @@ -6097,7 +6542,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" dependencies = [ "proc-macro2", - "quick-xml", + "quick-xml 0.41.0", "quote", ] @@ -6704,6 +7149,20 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" +[[package]] +name = "x509-cert" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94" +dependencies = [ + "const-oid 0.9.6", + "der", + "sha1 0.10.7", + "signature", + "spki", + "tls_codec", +] + [[package]] name = "xattr" version = "1.7.0" @@ -6960,6 +7419,20 @@ name = "zeroize" version = "1.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] [[package]] name = "zerotrie" diff --git a/Cargo.toml b/Cargo.toml index 445bcf4..eae3d15 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,3 +34,5 @@ base64 = "0.23" hmac = "0.13" sha1 = "0.11" futures-lite = "2" +idevice = { version = "0.1.68", default-features = false, features = ["ring", "usbmuxd", "afc", "pair"] } +tokio = { version = "1", features = ["rt-multi-thread", "net", "time"] } diff --git a/Plans/09 Devices/S024-ios-afc.md b/Plans/09 Devices/S024-ios-afc.md index 9bbc842..232b993 100644 --- a/Plans/09 Devices/S024-ios-afc.md +++ b/Plans/09 Devices/S024-ios-afc.md @@ -10,12 +10,12 @@ Browse and transfer files on iPhones as an `ios://` location through the `idevic docs/DECISIONS.md D-006, D-016; `idevice` crate docs in ~/.cargo/registry (check the real API first); crates/tunal-core trait; places API from S010. ## Steps -- [ ] usbmuxd connection, device list and attach/detach listening; usbmuxd missing → iOS support hidden, no error. -- [ ] Lockdown with the pair record from usbmuxd; unpaired → start pairing and show 'Unlock the iPhone and tap Trust'. -- [ ] AFC service: list, stat, read/write streaming, mkdir, rename, delete (permanent, with confirm) as the `ios:///` `Location`. -- [ ] Device entries in the places Devices section (name, eject = close), opening a tab at its root. -- [ ] Smoke without a device: discovery returns nothing, no panic, app runs. -- [ ] PROGRESS entry, INDEX line, commit `S024: …` +- [x] usbmuxd connection, device list and attach/detach listening; usbmuxd missing → iOS support hidden, no error. +- [x] Lockdown with the pair record from usbmuxd; unpaired → start pairing and show 'Unlock the iPhone and tap Trust'. +- [x] AFC service: list, stat, read/write streaming, mkdir, rename, delete (permanent, with confirm) as the `ios:///` `Location`. +- [x] Device entries in the places Devices section (name, eject = close), opening a tab at its root. +- [x] Smoke without a device: discovery returns nothing, no panic, app runs. +- [x] PROGRESS entry, INDEX line, commit `S024: …` ## End criteria - `cargo build --workspace`, `cargo clippy --workspace --all-targets -- -D warnings` and `cargo fmt --check` pass. diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 6338194..70193d4 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -55,7 +55,7 @@ Tracker: https://claude.ai/artifact/4X8YCk3cQjUGyuyCqGuU7v ## 09 Devices -- [ ] [S024 — iOS devices over AFC](09%20Devices/S024-ios-afc.md) · Opus high +- [x] [S024 — iOS devices over AFC](09%20Devices/S024-ios-afc.md) · Opus high - [x] [S025 — MTP protocol over nusb](09%20Devices/S025-mtp-protocol.md) · Opus high - [x] [S026 — Android devices over MTP](09%20Devices/S026-mtp-location.md) · Opus high diff --git a/crates/tunal-devices/Cargo.toml b/crates/tunal-devices/Cargo.toml index fb5c439..304a192 100644 --- a/crates/tunal-devices/Cargo.toml +++ b/crates/tunal-devices/Cargo.toml @@ -10,3 +10,5 @@ nusb.workspace = true jiff.workspace = true tunal-core = { path = "../tunal-core" } futures-lite.workspace = true +idevice.workspace = true +tokio.workspace = true diff --git a/crates/tunal-devices/examples/ios_location.rs b/crates/tunal-devices/examples/ios_location.rs new file mode 100644 index 0000000..0938a71 --- /dev/null +++ b/crates/tunal-devices/examples/ios_location.rs @@ -0,0 +1,40 @@ +//! Smoke run of the `ios://` location with no iPhone: +//! `cargo run -p tunal-devices --example ios_location` +//! (`USBMUXD_SOCKET_ADDRESS=/nonexistent` simulates a missing usbmuxd). +//! +//! Discovery runs for a few seconds; it must find nothing, print no error and not panic, +//! and an unknown device must answer `NotFound`. + +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Duration; + +use tunal_core::{Error, Location, Uri}; +use tunal_devices::ios::{self, IosLocation}; + +fn main() { + let location = Arc::new(IosLocation::new().expect("runtime")); + let changes = Arc::new(AtomicUsize::new(0)); + let seen = changes.clone(); + ios::watch(location.clone(), move || { + seen.fetch_add(1, Ordering::Relaxed); + }) + .expect("watch thread"); + // Two usbmuxd polls. + std::thread::sleep(Duration::from_secs(7)); + + let places = location.places(); + println!( + "devices: {}, changes: {}", + places.len(), + changes.load(Ordering::Relaxed) + ); + assert!(places.is_empty(), "no device is attached"); + + let uri = Uri::parse("ios://00008030-000000000000002E/DCIM").expect("uri"); + let listed = location.list(&uri, &mut |_| std::ops::ControlFlow::Continue(())); + assert_eq!(listed, Err(Error::NotFound)); + assert_eq!(location.stat(&uri).err(), Some(Error::NotFound)); + location.eject(&uri); + println!("ok"); +} diff --git a/crates/tunal-devices/src/ios/location.rs b/crates/tunal-devices/src/ios/location.rs new file mode 100644 index 0000000..4ac4a3d --- /dev/null +++ b/crates/tunal-devices/src/ios/location.rs @@ -0,0 +1,268 @@ +//! The `Location` side of [`IosLocation`]: AFC calls on the device's shared client; file +//! streams get an AFC connection of their own so listing goes on during a transfer. + +use std::collections::HashMap; +use std::io::{self, Read, Write}; +use std::sync::Arc; +use std::time::{Duration, SystemTime}; + +use idevice::IdeviceError; +use idevice::IdeviceService; +use idevice::afc::AfcClient; +use idevice::afc::errors::AfcError; +use idevice::afc::file::OwnedFileDescriptor; +use idevice::afc::opcode::AfcFopenMode; +use tokio::runtime::Handle; +use tunal_core::{ + Capabilities, Entry, Error as CoreError, Kind, ListSink, Location, Result, Uri, WriteMode, + display_name, mime, +}; + +use super::{Device, IosLocation, SCHEME, lock}; + +/// Bytes per AFC read while streaming a file from the device. +const READ_CHUNK: usize = 1 << 20; +/// Entries per listing chunk handed to the view. +const LIST_CHUNK: usize = 256; + +impl IosLocation { + fn device(&self, uri: &Uri) -> Result> { + lock(&self.devices) + .get(uri.authority()) + .cloned() + .ok_or(CoreError::NotFound) + } + + /// Runs `op` on the device's AFC client with the AFC path of `uri`. + fn run( + &self, + uri: &Uri, + op: impl AsyncFnOnce(&mut AfcClient, String) -> std::result::Result, + ) -> Result { + let d = self.device(uri)?; + let path = afc_path(uri)?; + let mut guard = lock(&d.afc); + let Some(afc) = guard.as_mut() else { + return Err(problem_error(&d)); + }; + let result = self.rt.block_on(op(afc, path)); + if let Err(IdeviceError::Socket(_)) = result { + // Lost the connection: the device is going away, or will need a replug. + guard.take(); + d.set_problem(Some("Lost the connection to the iPhone".into())); + } + result.map_err(core_error) + } + + /// Opens `uri` on a fresh AFC connection. + fn open(&self, uri: &Uri, mode: AfcFopenMode) -> Result { + let d = self.device(uri)?; + let path = afc_path(uri)?; + if lock(&d.afc).is_none() { + return Err(problem_error(&d)); + } + self.rt + .block_on(async { + let afc = AfcClient::connect(&d.provider).await?; + afc.open_owned(path, mode).await + }) + .map_err(core_error) + } + + fn exists(&self, uri: &Uri) -> Result { + match self.run(uri, async |afc, path| afc.get_file_info_raw(path).await) { + Ok(_) => Ok(true), + Err(CoreError::NotFound) => Ok(false), + Err(e) => Err(e), + } + } +} + +impl Location for IosLocation { + fn scheme(&self) -> &str { + SCHEME + } + + fn capabilities(&self) -> Capabilities { + Capabilities { + write: true, + ..Capabilities::default() + } + } + + fn list(&self, dir: &Uri, sink: &mut ListSink<'_>) -> Result<()> { + let names = self.run(dir, async |afc, path| afc.list_dir(path).await)?; + let mut chunk = Vec::new(); + for name in names { + if name == "." || name == ".." { + continue; + } + let child = dir.join(name.as_bytes()); + // Gone between the listing and the stat: skip it. + let Ok(info) = self.run(&child, async |afc, path| afc.get_file_info_raw(path).await) + else { + continue; + }; + chunk.push(to_entry(name.into_bytes(), &info)); + if chunk.len() == LIST_CHUNK && sink(std::mem::take(&mut chunk)).is_break() { + return Err(CoreError::Cancelled); + } + } + if !chunk.is_empty() && sink(chunk).is_break() { + return Err(CoreError::Cancelled); + } + Ok(()) + } + + fn stat(&self, uri: &Uri) -> Result { + let info = self.run(uri, async |afc, path| afc.get_file_info_raw(path).await)?; + Ok(to_entry(uri.file_name().unwrap_or(b"").to_vec(), &info)) + } + + fn open_read(&self, uri: &Uri) -> Result> { + if self.stat(uri)?.kind.is_dir() { + return Err(CoreError::Io("not a file".into())); + } + let fd = self.open(uri, AfcFopenMode::RdOnly)?; + Ok(Box::new(Download { + rt: self.rt.handle().clone(), + fd, + })) + } + + fn open_write(&self, uri: &Uri, mode: WriteMode) -> Result> { + match self.stat(uri) { + Ok(_) if mode == WriteMode::CreateNew => return Err(CoreError::Exists), + Ok(e) if e.kind == Kind::Dir => return Err(CoreError::Exists), + Ok(_) | Err(CoreError::NotFound) => {} + Err(e) => return Err(e), + } + let fd = self.open(uri, AfcFopenMode::WrOnly)?; + Ok(Box::new(Upload { + rt: self.rt.handle().clone(), + fd: Some(fd), + })) + } + + fn mkdir(&self, uri: &Uri) -> Result<()> { + if self.exists(uri)? { + return Err(CoreError::Exists); + } + self.run(uri, async |afc, path| afc.mk_dir(path).await) + } + + fn rename(&self, from: &Uri, to: &Uri) -> Result<()> { + if from.authority() != to.authority() { + return Err(CoreError::Unsupported); + } + if self.exists(to)? { + return Err(CoreError::Exists); + } + let target = afc_path(to)?; + self.run(from, async |afc, path| afc.rename(path, target).await) + } + + fn delete(&self, uri: &Uri) -> Result<()> { + self.run(uri, async |afc, path| afc.remove(path).await) + } +} + +/// Streams a file from the device; AFC reads return nothing at the end. +struct Download { + rt: Handle, + fd: OwnedFileDescriptor, +} + +impl Read for Download { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let want = buf.len().min(READ_CHUNK); + let bytes = self.rt.block_on(self.fd.read_n(want)).map_err(io_error)?; + let n = bytes.len().min(want); + buf[..n].copy_from_slice(&bytes[..n]); + Ok(n) + } +} + +/// Streams a file to the device; dropping it closes the file there. +struct Upload { + rt: Handle, + fd: Option, +} + +impl Write for Upload { + fn write(&mut self, buf: &[u8]) -> io::Result { + let fd = self.fd.as_mut().ok_or(io::ErrorKind::BrokenPipe)?; + self.rt.block_on(fd.write_entire(buf)).map_err(io_error)?; + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl Drop for Upload { + fn drop(&mut self) { + if let Some(fd) = self.fd.take() { + let _ = self.rt.block_on(fd.close()); + } + } +} + +/// AFC paths are UTF-8, rooted at the media folder. +fn afc_path(uri: &Uri) -> Result { + let path = String::from_utf8(uri.path().to_vec()).map_err(|_| CoreError::NotFound)?; + Ok(if path.is_empty() { "/".into() } else { path }) +} + +fn to_entry(name: Vec, info: &HashMap) -> Entry { + let kind = match info.get("st_ifmt").map(String::as_str) { + Some("S_IFDIR") => Kind::Dir, + // Targets aren't followed (rare in the media folder): shown as links of unknown type. + Some("S_IFLNK") => Kind::Symlink { + target: info + .get("st_link_target") + .cloned() + .unwrap_or_default() + .into_bytes(), + target_type: None, + }, + _ => Kind::File, + }; + let number = |key: &str| info.get(key).and_then(|v| v.parse::().ok()); + Entry { + display_name: display_name(&name), + hidden: name.first() == Some(&b'.'), + mime: mime::mime_type(&name, &kind), + name, + kind, + size: number("st_size").unwrap_or(0), + mtime: number("st_mtime").map(|ns| SystemTime::UNIX_EPOCH + Duration::from_nanos(ns)), + mode: 0, + uid: 0, + gid: 0, + } +} + +fn problem_error(d: &Device) -> CoreError { + CoreError::Remote( + lock(&d.problem) + .clone() + .unwrap_or_else(|| "The iPhone isn't connected".into()), + ) +} + +fn core_error(e: IdeviceError) -> CoreError { + match e { + IdeviceError::Afc(AfcError::ObjectNotFound) => CoreError::NotFound, + IdeviceError::Afc(AfcError::PermDenied) => CoreError::PermissionDenied, + IdeviceError::Afc(AfcError::ObjectExists) => CoreError::Exists, + IdeviceError::Afc(AfcError::DirNotEmpty) => CoreError::NotEmpty, + IdeviceError::Afc(AfcError::NoSpaceLeft) => CoreError::Remote("The iPhone is full".into()), + e => CoreError::Remote(e.to_string()), + } +} + +fn io_error(e: IdeviceError) -> io::Error { + io::Error::other(e.to_string()) +} diff --git a/crates/tunal-devices/src/ios/mod.rs b/crates/tunal-devices/src/ios/mod.rs new file mode 100644 index 0000000..e06d126 --- /dev/null +++ b/crates/tunal-devices/src/ios/mod.rs @@ -0,0 +1,304 @@ +//! iPhones and iPads through the system usbmuxd (D-006): each trusted device is an +//! `ios:///` location on its AFC media folder. All calls block; run them off the +//! UI thread. No usbmuxd socket means no devices, never an error. + +mod location; + +use std::collections::{HashMap, HashSet}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::Duration; + +use futures_lite::StreamExt; +use idevice::afc::AfcClient; +use idevice::lockdown::LockdownClient; +use idevice::provider::{IdeviceProvider, UsbmuxdProvider}; +use idevice::usbmuxd::{Connection, UsbmuxdAddr, UsbmuxdDevice, UsbmuxdListenEvent}; +use idevice::{IdeviceError, IdeviceService}; +use tokio::runtime::Runtime; +use tunal_core::Uri; + +use crate::DevicePlace; + +pub const SCHEME: &str = "ios"; +/// Our name towards usbmuxd and lockdown. +const LABEL: &str = "Tunal"; +const TRUST: &str = "Unlock the iPhone and tap Trust"; +const CONNECTING: &str = "Connecting to the iPhone…"; +/// Between pairing or connection attempts. +const RETRY: Duration = Duration::from_secs(2); +/// Between looks for the usbmuxd socket (udev starts usbmuxd when an iPhone is plugged in). +const MUXD_POLL: Duration = Duration::from_secs(3); + +type OnChange = Arc; + +/// Every attached iOS device, by UDID. +pub struct IosLocation { + rt: Runtime, + addr: UsbmuxdAddr, + devices: Mutex>>, + /// Ejected devices stay hidden until they are unplugged. + ejected: Mutex>, + on_change: Mutex>, +} + +struct Device { + udid: String, + mux_id: u32, + provider: UsbmuxdProvider, + name: Mutex, + afc: Mutex>, + /// Shown instead of the files until the device is ready (trust, connecting, failure). + problem: Mutex>, + gone: AtomicBool, +} + +impl IosLocation { + /// The usbmuxd socket comes from `USBMUXD_SOCKET_ADDRESS` (a path, or host:port), else + /// the system default. + pub fn new() -> std::io::Result { + let rt = tokio::runtime::Builder::new_multi_thread() + .worker_threads(1) + .thread_name("tunal-ios") + .enable_all() + .build()?; + Ok(Self { + rt, + addr: UsbmuxdAddr::from_env_var().unwrap_or_default(), + devices: Mutex::default(), + ejected: Mutex::default(), + on_change: Mutex::default(), + }) + } + + /// Sidebar entries, devices by name. + pub fn places(&self) -> Vec { + let mut out: Vec = lock(&self.devices) + .values() + .map(|d| DevicePlace { + name: lock(&d.name).clone(), + uri: Uri::new(SCHEME, &d.udid, "/"), + }) + .collect(); + out.sort_by(|a, b| { + a.name + .cmp(&b.name) + .then(a.uri.authority().cmp(b.uri.authority())) + }); + out + } + + /// Closes the device at `uri` and hides it until it is plugged in again. + pub fn eject(&self, uri: &Uri) { + let removed = lock(&self.devices).remove(uri.authority()); + if let Some(d) = removed { + lock(&self.ejected).insert(d.udid.clone()); + d.close(); + self.changed(); + } + } + + fn changed(&self) { + let f = lock(&self.on_change).clone(); + if let Some(f) = f { + f(); + } + } + + /// Follows attach and detach events until usbmuxd goes away. + async fn listen(self: &Arc) -> Result<(), IdeviceError> { + let mut conn = self.addr.connect(0).await?; + let mut events = conn.listen().await?; + while let Some(event) = events.next().await { + match event? { + // Wi-Fi sync shows the same device a second time. + UsbmuxdListenEvent::Connected(dev) if dev.connection_type == Connection::Usb => { + self.attach(dev) + } + UsbmuxdListenEvent::Connected(_) => {} + UsbmuxdListenEvent::Disconnected(id) => self.detach(id), + } + } + Ok(()) + } + + fn attach(self: &Arc, dev: UsbmuxdDevice) { + if lock(&self.ejected).contains(&dev.udid) { + return; + } + let device = Arc::new(Device { + udid: dev.udid.clone(), + mux_id: dev.device_id, + provider: dev.to_provider(self.addr.clone(), LABEL), + name: Mutex::new("iPhone".into()), + afc: Mutex::new(None), + problem: Mutex::new(Some(CONNECTING.into())), + gone: AtomicBool::new(false), + }); + if let Some(old) = lock(&self.devices).insert(dev.udid, device.clone()) { + old.close(); + } + self.changed(); + let me = self.clone(); + std::thread::Builder::new() + .name("tunal-ios-setup".into()) + .spawn(move || me.setup(&device)) + .ok(); + } + + fn detach(&self, mux_id: u32) { + let removed: Vec> = { + let mut devices = lock(&self.devices); + let keys: Vec = devices + .values() + .filter(|d| d.mux_id == mux_id) + .map(|d| d.udid.clone()) + .collect(); + keys.iter().filter_map(|k| devices.remove(k)).collect() + }; + // An ejected device shows again once it is replugged; its mux id is gone with it. + lock(&self.ejected).clear(); + if !removed.is_empty() { + removed.iter().for_each(|d| d.close()); + self.changed(); + } + } + + fn clear(&self) { + let removed: Vec> = lock(&self.devices).drain().map(|(_, d)| d).collect(); + lock(&self.ejected).clear(); + if !removed.is_empty() { + removed.iter().for_each(|d| d.close()); + self.changed(); + } + } + + /// Pairs if needed and opens AFC, retrying until it works or the device goes away. + fn setup(&self, device: &Device) { + while !device.gone.load(Ordering::Relaxed) { + let result = self.rt.block_on(self.connect(device)); + let problem = match &result { + Ok(()) => None, + Err( + IdeviceError::PairingDialogResponsePending | IdeviceError::PasswordProtected, + ) => Some(TRUST.to_owned()), + Err(IdeviceError::UserDeniedPairing) => Some( + "This computer isn't trusted. Unplug the iPhone and plug it in again to \ + be asked once more" + .to_owned(), + ), + Err(e) => Some(format!("Can't talk to this iPhone: {e}")), + }; + if device.set_problem(problem) { + self.changed(); + } + if !retry_later(&result) { + return; + } + std::thread::sleep(RETRY); + } + } + + async fn connect(&self, device: &Device) -> Result<(), IdeviceError> { + let mut mux = self.addr.connect(0).await?; + if mux.get_pair_record(&device.udid).await.is_err() { + if device.set_problem(Some(TRUST.into())) { + self.changed(); + } + let mut lockdown = LockdownClient::connect(&device.provider).await?; + let buid = mux.get_buid().await?; + // Waits while the Trust dialog is up; a locked device answers at once. + let record = lockdown.pair(host_id()?, buid, Some(LABEL)).await?; + mux.save_pair_record(&device.udid, record.serialize()?) + .await?; + } + let pairing = device.provider.get_pairing_file().await?; + let mut lockdown = LockdownClient::connect(&device.provider).await?; + match lockdown.start_session(&pairing).await { + Ok(_) => {} + // The device forgot us: drop the stale record so the next attempt pairs again. + Err(IdeviceError::InvalidHostID) => { + mux.delete_pair_record(&device.udid).await?; + return Err(IdeviceError::PairingDialogResponsePending); + } + Err(e) => return Err(e), + } + if let Ok(value) = lockdown.get_value(Some("DeviceName"), None).await + && let Some(name) = value.as_string() + { + *lock(&device.name) = name.to_owned(); + } + let afc = AfcClient::connect(&device.provider).await?; + if !device.gone.load(Ordering::Relaxed) { + *lock(&device.afc) = Some(afc); + } + Ok(()) + } +} + +impl Device { + /// True when the text changed. + fn set_problem(&self, problem: Option) -> bool { + let mut p = lock(&self.problem); + let changed = *p != problem; + *p = problem; + changed + } + + fn close(&self) { + self.gone.store(true, Ordering::Relaxed); + lock(&self.afc).take(); + } +} + +/// Adds the attached devices, then follows plugs and unplugs on a thread of its own; +/// `on_change` runs on that thread (or a device's setup thread) after every change. +pub fn watch( + location: Arc, + on_change: impl Fn() + Send + Sync + 'static, +) -> std::io::Result<()> { + *lock(&location.on_change) = Some(Arc::new(on_change)); + std::thread::Builder::new() + .name("tunal-ios-hotplug".into()) + .spawn(move || { + loop { + // Err: no usbmuxd (not installed, or not started yet). Look again later. + let _ = location.rt.block_on(location.listen()); + location.clear(); + std::thread::sleep(MUXD_POLL); + } + })?; + Ok(()) +} + +/// Lockdown errors worth another attempt; the rest wait for a replug. +fn retry_later(result: &Result<(), IdeviceError>) -> bool { + matches!( + result, + Err(IdeviceError::Socket(_) + | IdeviceError::PairingDialogResponsePending + | IdeviceError::PasswordProtected) + ) +} + +/// A random UUID for our side of a new pair record. +fn host_id() -> Result { + use std::io::Read; + let mut b = [0u8; 16]; + std::fs::File::open("/dev/urandom")?.read_exact(&mut b)?; + b[6] = (b[6] & 0x0f) | 0x40; + b[8] = (b[8] & 0x3f) | 0x80; + let hex: String = b.iter().map(|x| format!("{x:02X}")).collect(); + Ok(format!( + "{}-{}-{}-{}-{}", + &hex[..8], + &hex[8..12], + &hex[12..16], + &hex[16..20], + &hex[20..] + )) +} + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} diff --git a/crates/tunal-devices/src/lib.rs b/crates/tunal-devices/src/lib.rs index b4d4eb9..bcd3ceb 100644 --- a/crates/tunal-devices/src/lib.rs +++ b/crates/tunal-devices/src/lib.rs @@ -1,3 +1,13 @@ //! iOS and Android device locations. +pub mod ios; pub mod mtp; + +use tunal_core::Uri; + +/// A sidebar entry for a device (or one of its storages), shared by every device backend. +#[derive(Clone, Debug)] +pub struct DevicePlace { + pub name: String, + pub uri: Uri, +} diff --git a/crates/tunal-devices/src/mtp/location.rs b/crates/tunal-devices/src/mtp/location.rs index 21ab0dc..0156e93 100644 --- a/crates/tunal-devices/src/mtp/location.rs +++ b/crates/tunal-devices/src/mtp/location.rs @@ -14,6 +14,8 @@ use tunal_core::{ WatchCallback, WatchEvent, WriteMode, display_name, mime, }; +pub use crate::DevicePlace; + use super::{Container, Error, Events, NewObject, Object, Session, StorageInfo, Transport, code}; pub const SCHEME: &str = "mtp"; @@ -25,13 +27,6 @@ const EVENT_WAIT: Duration = Duration::from_secs(5); type OnChange = Arc; type Phone = Session>; -/// A sidebar entry: one per storage, or one for the device while it has a problem. -#[derive(Clone, Debug)] -pub struct DevicePlace { - pub name: String, - pub uri: Uri, -} - /// Every connected MTP device, by URI authority. #[derive(Default)] pub struct MtpLocation { diff --git a/crates/tunal/src/devices_bridge.rs b/crates/tunal/src/devices_bridge.rs index 1ab2ab8..8b341fe 100644 --- a/crates/tunal/src/devices_bridge.rs +++ b/crates/tunal/src/devices_bridge.rs @@ -1,10 +1,13 @@ -//! Phones in the sidebar: the `mtp://` backend and its hotplug watch, adapted to the shell. +//! Phones in the sidebar: the `mtp://` and `ios://` backends and their hotplug watches, +//! adapted to the shell. use std::cell::RefCell; use std::rc::{Rc, Weak}; -use std::sync::Arc; +use std::sync::{Arc, Mutex}; -use tunal_core::Locations; +use tunal_core::{Locations, Uri}; +use tunal_devices::DevicePlace; +use tunal_devices::ios::{self, IosLocation}; use tunal_devices::mtp::{self, MtpLocation}; use crate::shell::Shell; @@ -15,37 +18,100 @@ const PHONE: &str = "\u{e32c}"; thread_local! { static SHELL: RefCell> = const { RefCell::new(Weak::new()) }; + static IOS: RefCell>> = const { RefCell::new(None) }; } -/// Adds the `mtp://` backend to `locations`. -pub fn register(locations: &mut Locations) -> Arc { +/// Each backend's latest entries; the sidebar shows them together. +#[derive(Default)] +struct Lists { + mtp: Vec, + ios: Vec, +} + +pub struct Backends { + mtp: Arc, + ios: Option>, +} + +/// Adds the device backends to `locations`. +pub fn register(locations: &mut Locations) -> Backends { let mtp = Arc::new(MtpLocation::new()); locations.register(mtp.clone()); - mtp + // No async runtime (out of threads): iPhones just don't show up. + let ios = match IosLocation::new() { + Ok(l) => Some(Arc::new(l)), + Err(e) => { + eprintln!("tunal: iPhones: {e}"); + None + } + }; + if let Some(ios) = &ios { + locations.register(ios.clone()); + } + Backends { mtp, ios } } /// Fills the Devices section now and on every plug, unplug or storage change. -pub fn attach(shell: &Rc, mtp: Arc) { +pub fn attach(shell: &Rc, backends: Backends) { SHELL.with(|s| *s.borrow_mut() = Rc::downgrade(shell)); - let source = mtp.clone(); - let watched = mtp::watch(mtp, move || { + IOS.with(|i| *i.borrow_mut() = backends.ios.clone()); + let lists = Arc::new(Mutex::new(Lists::default())); + + let source = backends.mtp.clone(); + let mtp_lists = lists.clone(); + let watched = mtp::watch(backends.mtp, move || { let places = source.places(); - let _ = slint::invoke_from_event_loop(move || { - let items = places - .into_iter() - .map(|p| Place { - name: p.name, - glyph: PHONE, - uri: p.uri, - }) - .collect(); - if let Some(shell) = SHELL.with(|s| s.borrow().upgrade()) { - shell.set_devices(items); - } - }); + show(&mtp_lists, |l| l.mtp = places); }); // No hotplug (no udev netlink in a sandbox): phones just don't show up. if let Err(e) = watched { eprintln!("tunal: phones: {e}"); } + + if let Some(location) = backends.ios { + let source = location.clone(); + if let Err(e) = ios::watch(location, move || { + let places = source.places(); + show(&lists, |l| l.ios = places); + }) { + eprintln!("tunal: iPhones: {e}"); + } + } +} + +/// True for sidebar entries that can be ejected. +pub fn can_eject(uri: &Uri) -> bool { + uri.scheme() == ios::SCHEME +} + +/// Closes the device at `uri`; it shows again once replugged. +pub fn eject(uri: &Uri) { + let ios = IOS.with(|i| i.borrow().clone()); + if let Some(ios) = ios.filter(|_| can_eject(uri)) { + // Closing talks to no one, but the device lock may wait on a transfer. + let uri = uri.clone(); + std::thread::spawn(move || ios.eject(&uri)); + } +} + +/// Updates one backend's list (on a device thread) and shows all of them. +fn show(lists: &Mutex, update: impl FnOnce(&mut Lists)) { + let places: Vec = { + let mut l = lists.lock().unwrap_or_else(|e| e.into_inner()); + update(&mut l); + l.mtp.iter().chain(&l.ios).cloned().collect() + }; + let _ = slint::invoke_from_event_loop(move || { + let items = places + .into_iter() + .map(|p| Place { + name: p.name, + glyph: PHONE, + uri: p.uri, + }) + .collect(); + if let Some(shell) = SHELL.with(|s| s.borrow().upgrade()) { + shell.set_devices(items); + } + }); } diff --git a/crates/tunal/src/shell/mod.rs b/crates/tunal/src/shell/mod.rs index 5208f74..6723ac4 100644 --- a/crates/tunal/src/shell/mod.rs +++ b/crates/tunal/src/shell/mod.rs @@ -619,15 +619,31 @@ impl Shell { items.push(item("Move down", "\u{e5db}", index >= last)); items.push(item("Remove", "\u{e872}", false)); } + if self.ejectable(section, index).is_some() { + items.push(item("Eject", "\u{e8fb}", false)); + } items } + /// The URI of a device entry that can be ejected. + fn ejectable(&self, section: Section, index: usize) -> Option { + let places = self.places.borrow(); + let place = places.get(section, index)?; + (section == Section::Devices && crate::devices_bridge::can_eject(&place.uri)) + .then(|| place.uri.clone()) + } + fn place_menu_activated(&self, choice: usize) { let Some(MenuTarget { section, index }) = self.menu_target.get() else { return; }; match choice { 0 => self.open_place(section, index, true), + 1 if section == Section::Devices => { + if let Some(uri) = self.ejectable(section, index) { + crate::devices_bridge::eject(&uri); + } + } 1 => { let name = self .places diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 95123a1..bf21037 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -200,6 +200,16 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, - Not done: no live window (typing, drop, clicks, progress bar motion, scrolling); no file chooser for the cover (path field or drop); a mixed field can't be cleared on purpose (only set); lookup apply doesn't offer per-field choice; offline/busy messages not seen live. - Later: file chooser; per-field "clear" for mixed values; recording search by title when no album; lookup for one file with no album tag uses the file name. +## S024 — iOS devices over AFC +- Done: `tunal_devices::ios::IosLocation` (`Location`, scheme `ios`): `ios:///` on the AFC media folder; list (+ stat per entry, chunks of 256), stat, open_read (own AFC connection, 1 MiB reads), open_write (own connection, streamed, closed on drop; CreateNew/dir → Exists), mkdir, rename (Exists check), delete (permanent; trash Unsupported so the UI confirms). AFC errors → NotFound/PermissionDenied/Exists/NotEmpty; lost socket drops the client. +- `ios::watch(location, on_change)`: usbmuxd Listen on a 1-worker tokio runtime; USB devices only (Wi-Fi duplicates skipped); no socket → retry every 3 s silently (udev starts usbmuxd on plug). Socket from `USBMUXD_SOCKET_ADDRESS`, else `/var/run/usbmuxd`. +- Setup thread per device: pair record from usbmuxd, else lockdown `pair` (problem "Unlock the iPhone and tap Trust", retries while locked/pending), record saved to usbmuxd; stale record (InvalidHostID) deleted and re-paired; DeviceName from lockdown. Problems show as the folder error. +- **Shared device API**: `tunal_devices::DevicePlace {name, uri}` (moved from mtp, re-exported there). `devices_bridge::register` now returns `Backends` (MTP + iOS); Devices section merges both lists. Place menu on an `ios://` entry: "Eject" (closes the connection, hidden until replugged) via `devices_bridge::{can_eject, eject}`. +- Deps: `idevice` 0.1.68 (no default features; `ring`, `usbmuxd`, `afc`, `pair` — no aws-lc, D-019), `tokio` (rt-multi-thread, net, time). +- Verified: workspace build, clippy -D warnings, fmt --check; `cargo run -p tunal-devices --example ios_location` (new) with the real usbmuxd and with `USBMUXD_SOCKET_ADDRESS=/nonexistent/usbmuxd`: 0 devices, no error, unknown udid → NotFound; app screenshot both ways: Devices "No phones connected", no stderr. +- Not done: no iPhone (D-009, S036): pairing, Trust prompt, AFC ops, eject, names all unchecked live. Symlinks shown with unknown target type. main.rs still names the backends `mtp` (left to avoid S021's file). +- Later: eject for MTP phones; device name in breadcrumb; free space via AFC device info; a "Connecting…" entry shows the default name "iPhone" until lockdown answers. + ## Later - (orchestrator) Breadcrumb: a long path is hard-clipped at the bar's left edge with no elision mark, and the root crumb elides at 960 px — for S034. -