tvpipe 0.2.0

Stream a program's frames and sound, files, web pages or the screen to Apple TVs, Chromecasts and browser tabs with low latency, in process
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
//! `tvpipe pair` / `unpair` (PLAN ยง4) and [`connect`], the
//! authenticated control connection the mirroring sink (W7) starts from.
//!
//! `connect` opens the control port, pair-verifies with stored
//! credentials (or does transient pair-setup when the receiver allows
//! it), and switches the connection to the encrypted channel. The
//! returned [`Control`] carries the RTSP client and the shared secret.

use std::net::{IpAddr, SocketAddr, TcpStream};
use std::time::Duration;

use crate::airplay::credentials::{Identity, Query, Receiver, Store};
use crate::airplay::info::get_info;
use crate::airplay::pairing::{self, Shared};
use crate::airplay::secure::SecureStream;
use crate::ctx::Ctx;
use crate::error::{Error, ErrorKind, Result};
use crate::events::{Event, Paired, PinRequest, Unpaired};
use crate::net::device::Device;
use crate::net::discover;
use crate::net::http::Conn;
use crate::net::rtsp::RtspClient;

/// The AirPlay control port when only an address is given.
pub const DEFAULT_PORT: u16 = 7000;
const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
const IO_TIMEOUT: Duration = Duration::from_secs(15);
const DISCOVER_TIMEOUT: Duration = Duration::from_secs(4);

/// The encrypted control connection.
pub type SecureClient = RtspClient<SecureStream<TcpStream>>;

/// How [`connect`] authenticated.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Auth {
    /// Pair-verify with stored credentials.
    Verified(Receiver),
    /// Transient pair-setup (no stored credentials needed).
    Transient,
}

/// An authenticated, encrypted control connection.
pub struct Control {
    pub client: SecureClient,
    /// The pairing's shared secret (W7 derives stream keys from it).
    pub shared: Shared,
    pub addr: SocketAddr,
    pub auth: Auth,
}

impl std::fmt::Debug for Control {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Control")
            .field("addr", &self.addr)
            .field("auth", &self.auth)
            .finish_non_exhaustive()
    }
}

/// A resolved `NAME|ADDR`.
#[derive(Debug, Clone)]
pub struct Target {
    pub addr: SocketAddr,
    /// The discovered device, unless an address was given.
    pub device: Option<Device>,
}

impl Target {
    /// The device's display name, else the address.
    pub fn label(&self) -> String {
        self.device
            .as_ref()
            .map(|d| d.name.clone())
            .unwrap_or_else(|| self.addr.to_string())
    }

    /// A credentials query from what discovery knows.
    pub fn query(&self) -> Query<'_> {
        let mut q = Query::default();
        if let Some(d) = &self.device {
            let txt = d.airplay.as_ref().or(d.raop.as_ref()).map(|a| &a.txt);
            q.public_key = txt.and_then(|t| t.pk.as_deref());
            q.device_id = txt.and_then(|t| t.deviceid.as_deref());
            q.names = d.names();
        }
        q
    }
}

/// Parses `ip` or `ip:port` (IPv6 as `[addr]:port`).
fn parse_addr(s: &str) -> Option<SocketAddr> {
    if let Ok(ip) = s.parse::<IpAddr>() {
        return Some(SocketAddr::new(ip, DEFAULT_PORT));
    }
    s.parse::<SocketAddr>().ok()
}

/// Resolves `NAME|ADDR` to the AirPlay control address.
pub fn resolve(target: &str) -> Result<Target> {
    if let Some(addr) = parse_addr(target) {
        return Ok(Target { addr, device: None });
    }
    let device = discover::resolve(target, DISCOVER_TIMEOUT, &[])?
        .ok_or_else(|| Error::not_found(format!("no receiver named {target:?}")))?;
    let ep = device
        .airplay
        .as_ref()
        .or(device.raop.as_ref())
        .map(|a| &a.endpoint)
        .ok_or_else(|| Error::unsupported(format!("{} does not speak AirPlay", device.name)))?;
    let addr = SocketAddr::new(ep.addr(), ep.port);
    debug!("resolved {target:?} to {} at {addr}", device.name);
    Ok(Target {
        addr,
        device: Some(device),
    })
}

/// Opens a plain control connection with timeouts set.
pub fn open(addr: SocketAddr) -> Result<RtspClient<TcpStream>> {
    let stream = TcpStream::connect_timeout(&addr, CONNECT_TIMEOUT)
        .map_err(|e| Error::io(format!("airplay: connect to {addr}"), e))?;
    stream
        .set_read_timeout(Some(IO_TIMEOUT))
        .and_then(|()| stream.set_write_timeout(Some(IO_TIMEOUT)))
        .and_then(|()| stream.set_nodelay(true))
        .map_err(|e| Error::io("airplay: socket options", e))?;
    Ok(RtspClient::new(stream))
}

/// Switches a plain connection to the encrypted channel keyed by `shared`.
pub fn encrypt(mut client: RtspClient<TcpStream>, shared: &Shared) -> Result<SecureClient> {
    if !client.conn().buffered().is_empty() {
        return Err(Error::protocol(
            "airplay: receiver sent data before the encrypted channel started",
        ));
    }
    let stream = client
        .conn()
        .get_ref()
        .try_clone()
        .map_err(|e| Error::io("airplay: clone socket", e))?;
    let secure = SecureStream::new(stream, &shared.control_keys()?);
    Ok(client.replace_conn(Conn::new(secure)))
}

/// Connects and authenticates: pair-verify with `receiver`, else
/// transient pair-setup.
pub fn connect_with(addr: SocketAddr, identity: &Identity, auth: Auth) -> Result<Control> {
    connect_auth(addr, identity, auth, false)
}

/// Whether discovery says the receiver prefers legacy pairing (no
/// CoreUtils pairing bit, or bit 26/51): its transient pair-setup starts
/// with `X-Apple-HKP: 3` (W7, spec `airplay-mirroring.md` Appendix A).
fn legacy_preferring(target: &Target) -> bool {
    target
        .device
        .as_ref()
        .and_then(|d| d.airplay.as_ref().or(d.raop.as_ref()))
        .and_then(|a| a.txt.features)
        .is_some_and(crate::airplay::legacy_pair::is_candidate)
}

fn connect_auth(
    addr: SocketAddr,
    identity: &Identity,
    auth: Auth,
    legacy_preferring: bool,
) -> Result<Control> {
    let mut client = open(addr)?;
    let shared = match &auth {
        Auth::Verified(r) => {
            debug!("pair-verify with {} at {addr}", r.name);
            pairing::pair_verify(&mut client, identity, &r.id, &r.public_key)?
        }
        Auth::Transient => {
            debug!("transient pair-setup with {addr}");
            pairing::pair_setup_transient_for(&mut client, legacy_preferring)?
        }
    };
    let client = encrypt(client, &shared)?;
    Ok(Control {
        client,
        shared,
        addr,
        auth,
    })
}

/// Connects to a resolved target with the credentials in `store`: stored
/// pairing first, transient pair-setup otherwise.
pub fn connect(target: &Target, store: &Store) -> Result<Control> {
    let found = store.find(&target.query()).or_else(|| {
        let ip = target.addr.ip().to_string();
        store.find(&Query {
            addr: Some(&ip),
            ..Query::default()
        })
    });
    // Legacy raw pairings are verified by `airplay::legacy_pair` (W7).
    match found.filter(|r| !r.raw) {
        Some(r) => connect_with(target.addr, &store.identity, Auth::Verified(r.clone())),
        None => connect_auth(
            target.addr,
            &store.identity,
            Auth::Transient,
            legacy_preferring(target),
        )
        .map_err(|e| {
            if e.kind() == ErrorKind::Auth {
                Error::auth(format!(
                    "{} requires pairing: run `tvpipe pair {:?}` ({})",
                    target.label(),
                    target.label(),
                    e.message()
                ))
                .with_code("pairing-required")
                .with_device(target.label())
            } else {
                e
            }
        }),
    }
}

/// Pairs with `target` and stores the credentials in `store`. With `pin`
/// given, the receiver is assumed to have a fixed PIN and
/// `/pair-pin-start` is skipped; without it, the TV shows a PIN and
/// `get_pin` is asked for it.
pub fn pair_with(
    target: &Target,
    store: &mut Store,
    pin: Option<&str>,
    get_pin: impl FnOnce() -> Result<String>,
) -> Result<Receiver> {
    let mut client = open(target.addr)?;
    let plain_info = get_info(&mut client)
        .map_err(|e| debug!("pair: plain /info failed: {e}"))
        .ok();
    let receiver = match pin {
        Some(pin) => {
            let pin = pin.to_owned();
            pairing::pair_setup_pin(&mut client, &store.identity, false, move || Ok(pin))?
        }
        None => pairing::pair_setup_pin(&mut client, &store.identity, true, get_pin)?,
    };
    drop(client);
    if let Some(pk) = plain_info.as_ref().and_then(|i| i.pk.as_deref()) {
        if pk != receiver.public_key {
            debug!("pair: /info pk differs from the pair-setup key");
        }
    }
    let name = target
        .device
        .as_ref()
        .map(|d| d.name.clone())
        .or_else(|| plain_info.as_ref().and_then(|i| i.name.clone()))
        .unwrap_or_else(|| target.addr.ip().to_string());
    let device_id = target
        .device
        .as_ref()
        .and_then(|d| d.airplay.as_ref().or(d.raop.as_ref()))
        .and_then(|a| a.txt.deviceid.clone())
        .or_else(|| plain_info.as_ref().and_then(|i| i.device_id.clone()));
    let record = Receiver {
        id: receiver.id,
        public_key: receiver.public_key,
        name,
        device_id,
        addr: Some(target.addr.to_string()),
        raw: false,
    };
    store.upsert(record.clone());
    store.save()?;
    Ok(record)
}

/// The `pair` command body. `get_pin` is asked for the PIN the TV shows,
/// after a `pin-required` event.
pub fn pair(
    target: &str,
    pin: Option<&str>,
    ctx: &Ctx,
    get_pin: &mut dyn FnMut(&PinRequest) -> Result<String>,
) -> Result<Paired> {
    let target = resolve(target)?;
    let mut store = Store::open(&ctx.storage)?;
    let label = target.label();
    info!("pairing with {label} at {}", target.addr);
    let record = pair_with(&target, &mut store, pin, || {
        let req = PinRequest {
            name: label.clone(),
            address: target.addr.to_string(),
        };
        ctx.events.emit(Event::PinRequired(req.clone()));
        get_pin(&req)
    })?;
    info!(
        "paired with {} (receiver id {}); credentials in {}",
        record.name,
        record.id_display(),
        store.location()
    );
    // Prove the pairing works: verify on a fresh connection and fetch the
    // full /info over the encrypted channel.
    let mut control = connect_with(target.addr, &store.identity, Auth::Verified(record))?;
    let info = get_info(&mut control.client)?;
    let paired = Paired {
        name: label,
        model: info.model.clone(),
        file: store.file().map(|f| f.display().to_string()),
    };
    ctx.events.emit(Event::Paired(paired.clone()));
    Ok(paired)
}

/// The `unpair` command body: forgets the stored pairing.
pub fn unpair(target: &str, ctx: &Ctx) -> Result<Vec<Unpaired>> {
    let mut store = Store::open(&ctx.storage)?;
    let removed = forget(&mut store, target, resolve)?;
    let mut out = Vec::new();
    for r in &removed {
        let u = Unpaired {
            name: r.name.clone(),
            id: r.id_display(),
        };
        ctx.events.emit(Event::Unpaired(u.clone()));
        out.push(u);
    }
    Ok(out)
}

/// Removes the pairings for `target` from `store` and saves it. Looks the
/// target up by name or address first and only calls `resolve` (which
/// browses) when that finds nothing.
pub fn forget(
    store: &mut Store,
    target: &str,
    resolve: impl FnOnce(&str) -> Result<Target>,
) -> Result<Vec<Receiver>> {
    let addr = parse_addr(target).map(|a| a.ip().to_string());
    let local = Query {
        names: if addr.is_none() { vec![target] } else { vec![] },
        addr: addr.as_deref(),
        ..Query::default()
    };
    let mut removed = store.remove(&local);
    if removed.is_empty() && addr.is_none() {
        match resolve(target) {
            Ok(t) => removed = store.remove(&t.query()),
            Err(e) => debug!("unpair: cannot resolve {target:?}: {e}"),
        }
    }
    if removed.is_empty() {
        return Err(Error::not_found(format!(
            "no stored pairing for {target:?}"
        )));
    }
    store.save()?;
    Ok(removed)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::airplay::credentials::tests::temp_dir;
    use crate::airplay::pairing::fake::{Config, FakeReceiver};
    use crate::storage::Storage;

    fn target(fake: &FakeReceiver) -> Target {
        Target {
            addr: fake.addr,
            device: None,
        }
    }

    #[test]
    fn pin_pair_then_verify_after_restart() {
        let fake = FakeReceiver::start(Config {
            allow_transient: false,
            ..Config::default()
        });
        let path = Storage::dir(temp_dir("pair-pin"));
        let mut store = Store::open(&path).unwrap();
        let record = pair_with(&target(&fake), &mut store, None, || Ok("1234".into())).unwrap();
        assert_eq!(record.id, fake.config.id);
        assert_eq!(record.public_key, fake.public_key());
        assert_eq!(record.name, "Fake TV");
        assert_eq!(record.device_id.as_deref(), Some("AA:BB:CC:00:00:0A"));
        assert_eq!(fake.state.lock().unwrap().pin_starts, 1);
        drop(store);

        // A later run: credentials come from disk.
        let store = Store::open(&path).unwrap();
        assert_eq!(store.receivers.len(), 1);
        let mut control = connect(&target(&fake), &store).unwrap();
        assert!(matches!(control.auth, Auth::Verified(_)));
        assert_eq!(control.shared.secret().len(), 32);
        let info = get_info(&mut control.client).unwrap();
        let caps = info.capabilities();
        assert_eq!((caps.max_width, caps.max_height), (3840, 2160));
        assert_eq!(caps.max_fps.num, 60);
        // A second request on the same encrypted connection.
        let resp = control.client.request("OPTIONS", "*", &[], None).unwrap();
        assert_eq!(resp.status, 404);
        let log = fake.log();
        assert!(log.contains(&"secure GET /info".to_string()), "{log:?}");
        assert!(log.contains(&"secure OPTIONS *".to_string()), "{log:?}");
    }

    #[test]
    fn fixed_pin_skips_pin_start() {
        let fake = FakeReceiver::start(Config::default());
        let path = Storage::dir(temp_dir("pair-fixed-pin"));
        let mut store = Store::open(&path).unwrap();
        pair_with(&target(&fake), &mut store, Some("1234"), || {
            panic!("not asked")
        })
        .unwrap();
        assert_eq!(fake.state.lock().unwrap().pin_starts, 0);
    }

    #[test]
    fn wrong_pin_is_auth_error() {
        let fake = FakeReceiver::start(Config::default());
        let path = Storage::dir(temp_dir("pair-wrong-pin"));
        let mut store = Store::open(&path).unwrap();
        let err = pair_with(&target(&fake), &mut store, None, || Ok("9999".into())).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Auth, "{err}");
        assert!(store.receivers.is_empty());
    }

    #[test]
    fn transient_when_unpaired() {
        let fake = FakeReceiver::start(Config::default());
        let path = Storage::dir(temp_dir("pair-transient"));
        let store = Store::open(&path).unwrap();
        let mut control = connect(&target(&fake), &store).unwrap();
        assert_eq!(control.auth, Auth::Transient);
        assert_eq!(control.shared.secret().len(), 64);
        let info = get_info(&mut control.client).unwrap();
        assert_eq!(info.displays.len(), 1);
        assert_eq!(
            fake.log(),
            [
                "plain POST /pair-setup",
                "plain POST /pair-setup",
                "secure GET /info"
            ]
        );
    }

    fn setups(fake: &FakeReceiver) -> usize {
        fake.log()
            .iter()
            .filter(|l| *l == "plain POST /pair-setup")
            .count()
    }

    /// W7: transient HKP by receiver family, with one retry each for the
    /// HKP value and the SRP password (spec airplay-mirroring Appendix A).
    #[test]
    fn transient_hkp_and_password_retries() {
        let lg = || {
            FakeReceiver::start(Config {
                transient_hkp: "3".into(),
                ..Config::default()
            })
        };
        // Legacy-preferring receiver, HKP 3 first: the plain exchange.
        let fake = lg();
        let mut c = connect_auth(
            fake.addr,
            &Identity::generate().unwrap(),
            Auth::Transient,
            true,
        )
        .unwrap();
        get_info(&mut c.client).unwrap();
        assert_eq!(setups(&fake), 2);
        // Apple order against it: HKP 4 is rejected at M1, HKP 3 works.
        let fake = lg();
        let mut c =
            connect_with(fake.addr, &Identity::generate().unwrap(), Auth::Transient).unwrap();
        get_info(&mut c.client).unwrap();
        assert_eq!(setups(&fake), 3);
        // Empty transient password: 3939 fails at M4, the retry works.
        let fake = FakeReceiver::start(Config {
            transient_pin: String::new(),
            ..Config::default()
        });
        let mut c =
            connect_with(fake.addr, &Identity::generate().unwrap(), Auth::Transient).unwrap();
        get_info(&mut c.client).unwrap();
        assert_eq!(setups(&fake), 4);
        // Neither HKP accepted: an error after two M1 tries.
        let fake = FakeReceiver::start(Config {
            transient_hkp: "9".into(),
            ..Config::default()
        });
        let err =
            connect_with(fake.addr, &Identity::generate().unwrap(), Auth::Transient).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Auth, "{err}");
        assert_eq!(setups(&fake), 2);
    }

    /// `connect` picks HKP 3 first from the discovered features.
    #[test]
    fn connect_uses_discovered_family() {
        let fake = FakeReceiver::start(Config {
            transient_hkp: "3".into(),
            ..Config::default()
        });
        let mut dev = crate::net::device::tests::lan_devices()
            .into_iter()
            .find(|d| d.airplay.is_some())
            .unwrap();
        dev.airplay.as_mut().unwrap().txt.features = Some(1 << 7 | 1 << 26 | 1 << 48);
        let t = Target {
            addr: fake.addr,
            device: Some(dev),
        };
        let path = Storage::dir(temp_dir("pair-family"));
        let store = Store::open(&path).unwrap();
        assert!(legacy_preferring(&t));
        connect(&t, &store).unwrap();
        assert_eq!(setups(&fake), 2);
        assert!(!legacy_preferring(&target(&fake)));
    }

    #[test]
    fn unpaired_and_no_transient_says_pair() {
        let fake = FakeReceiver::start(Config {
            allow_transient: false,
            ..Config::default()
        });
        let path = Storage::dir(temp_dir("pair-required"));
        let store = Store::open(&path).unwrap();
        let err = connect(&target(&fake), &store).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Auth);
        assert!(err.message().contains("tvpipe pair"), "{err}");
    }

    #[test]
    fn forget_by_name_address_or_discovery() {
        let fake = FakeReceiver::start(Config::default());
        let path = Storage::dir(temp_dir("pair-forget"));
        let mut store = Store::open(&path).unwrap();
        pair_with(&target(&fake), &mut store, None, || Ok("1234".into())).unwrap();
        let no_browse = |_: &str| -> Result<Target> { panic!("should not browse") };
        let removed = forget(&mut store, "fake tv", no_browse).unwrap();
        assert_eq!(removed.len(), 1);
        assert!(Store::open(&path).unwrap().receivers.is_empty());

        pair_with(&target(&fake), &mut store, None, || Ok("1234".into())).unwrap();
        let ip = fake.addr.ip().to_string();
        assert_eq!(forget(&mut store, &ip, no_browse).unwrap().len(), 1);

        // Unknown name: falls back to discovery, then reports not found.
        let err = forget(&mut store, "Other", |_| Err(Error::not_found("x"))).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::NotFound);
    }

    #[test]
    fn repeated_verify_and_repair() {
        let fake = FakeReceiver::start(Config::default());
        let path = Storage::dir(temp_dir("pair-repeat"));
        let mut store = Store::open(&path).unwrap();
        pair_with(&target(&fake), &mut store, None, || Ok("1234".into())).unwrap();
        let mut secrets = Vec::new();
        for _ in 0..3 {
            let mut c = connect(&target(&fake), &store).unwrap();
            assert!(matches!(c.auth, Auth::Verified(_)));
            get_info(&mut c.client).unwrap();
            secrets.push(c.shared.secret().to_vec());
        }
        // Fresh ephemeral keys every time.
        assert_ne!(secrets[0], secrets[1]);
        // Pairing again replaces the record instead of adding one.
        pair_with(&target(&fake), &mut store, None, || Ok("1234".into())).unwrap();
        assert_eq!(Store::open(&path).unwrap().receivers.len(), 1);
    }

    #[test]
    fn verify_fails_when_receiver_forgot_us() {
        let fake = FakeReceiver::start(Config::default());
        let path = Storage::dir(temp_dir("pair-forgotten"));
        let mut store = Store::open(&path).unwrap();
        pair_with(&target(&fake), &mut store, None, || Ok("1234".into())).unwrap();
        fake.state.lock().unwrap().pairings.clear();
        let err = connect(&target(&fake), &store).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Auth, "{err}");
        assert!(err.message().contains("re-pair"), "{err}");

        // A stored key that does not match the receiver fails in M2.
        store.receivers[0].public_key = [1; 32];
        let err = connect(&target(&fake), &store).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Auth, "{err}");
    }
}

/// Hardware checks against a real receiver, run by hand (they use the
/// real credential store, like the CLI):
///
/// ```text
/// TVPIPE_ATV=192.168.1.34 cargo test hardware_pair -- --ignored --nocapture
/// TVPIPE_ATV=192.168.1.34 cargo test hardware_verify -- --ignored --nocapture
/// ```
#[cfg(test)]
mod hardware {
    use super::*;

    fn atv() -> Option<Target> {
        let addr = parse_addr(&std::env::var("TVPIPE_ATV").ok()?)?;
        crate::log::to_stderr(crate::log::Level::Trace);
        Some(Target { addr, device: None })
    }

    #[test]
    #[ignore]
    fn hardware_plain_info() {
        let Some(t) = atv() else { return };
        let mut c = open(t.addr).unwrap();
        let info = get_info(&mut c).unwrap();
        eprintln!("{info:#?}");
    }

    /// Interactive: reads the PIN shown on the TV from stdin.
    #[test]
    #[ignore]
    fn hardware_pair() {
        let Some(t) = atv() else { return };
        let mut store = Store::open(&crate::storage::Storage::cli()).unwrap();
        let r = pair_with(&t, &mut store, None, || {
            eprint!("PIN: ");
            let mut line = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            Ok(line.trim().to_owned())
        })
        .unwrap();
        eprintln!("paired: {} ({})", r.name, r.id_display());
    }

    /// Pair-verify with the stored credentials, then `/info` over the
    /// encrypted channel; saves the body to `target/appletv-info-verified.bplist`
    /// (scrub it with `tests/fixtures/airplay/scrub_info.py` before committing).
    #[test]
    #[ignore]
    fn hardware_verify() {
        let Some(t) = atv() else { return };
        let store = Store::open(&crate::storage::Storage::cli()).unwrap();
        let mut control = connect(&t, &store).unwrap();
        eprintln!(
            "verified with {} at {}",
            match &control.auth {
                Auth::Verified(r) => r.name.as_str(),
                Auth::Transient => "(transient)",
            },
            control.addr
        );
        let resp = control.client.request("GET", "/info", &[], None).unwrap();
        let out = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("target")
            .join("appletv-info-verified.bplist");
        std::fs::write(&out, &resp.body).unwrap();
        let info = crate::airplay::info::Info::parse(&resp.body).unwrap();
        eprintln!("{:#?}", info.capabilities());
        eprintln!("saved {}", out.display());
    }
}