second-brain-sync 0.13.0

Bidirectional sync for second-brain: SSH transport, JSONL change log, conflict resolution
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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
use std::collections::BTreeMap;
use std::io::ErrorKind;
use std::net::{IpAddr, Ipv4Addr, SocketAddr, UdpSocket};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

use anyhow::{Context, Result};
use rand_core::{OsRng, RngCore};

#[cfg(target_os = "macos")]
mod dnssd;
#[cfg(not(target_os = "macos"))]
mod lan;
#[cfg(target_os = "macos")]
use dnssd as lan;
#[cfg(any(target_os = "macos", test))]
mod system;

/// Every device with an sshd advertises this, its machine id and ssh login
/// in the TXT record and its sshd port in the SRV record.
pub const SERVICE: &str = "_second-brain._tcp";
/// An open `sb pair` listener, its port in the SRV record.
pub const PAIR_SERVICE: &str = "_second-brain-pair._tcp";
pub const TXT_ID: &str = "id";
pub const TXT_LOGIN: &str = "login";
/// How long a lookup collects answers; responders on a LAN answer within
/// milliseconds, and the query is sent twice in case one is lost.
pub const LOOKUP_WINDOW: Duration = Duration::from_millis(1500);

#[cfg(any(not(target_os = "macos"), test))]
const GROUP: Ipv4Addr = Ipv4Addr::new(224, 0, 0, 251);
const MDNS_PORT: u16 = 5353;
/// Every SRV target is a host name under this prefix, so it never claims a
/// name avahi or mDNSResponder publishes for the host itself.
const HOST_PREFIX: &str = "second-brain-";
const TYPE_A: u16 = 1;
const TYPE_PTR: u16 = 12;
const TYPE_TXT: u16 = 16;
const TYPE_SRV: u16 = 33;
const TYPE_ANY: u16 = 255;
const CLASS_IN: u16 = 1;
const CLASS_MASK: u16 = 0x7fff;
const CACHE_FLUSH: u16 = 0x8000;
const UNICAST_RESPONSE: u16 = 0x8000;
const FLAG_RESPONSE: u16 = 0x8000;
const FLAG_AUTHORITATIVE: u16 = 0x0400;
/// RFC 6762 6.7: answers to a legacy unicast query carry a TTL of at most
/// 10 seconds.
const UNICAST_TTL: u32 = 10;
const MULTICAST_TTL: u32 = 120;
const MAX_LABEL: usize = 63;
const MAX_NAME: usize = 255;
const MAX_JUMPS: usize = 16;
const MAX_PACKET: usize = 9000;
const POLL: Duration = Duration::from_millis(200);
const RESEND_AFTER: Duration = Duration::from_millis(500);

/// Where lookups are sent and where a responder listens.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Net {
    /// mDNS on the local network. On macOS the system's DNS-SD service
    /// registers and browses, and nothing here binds port 5353. Elsewhere
    /// queries go to the 224.0.0.251:5353 group from a port other than 5353,
    /// so responders answer the asking socket directly.
    Lan,
    /// One responder at this address, reached by plain unicast; on a
    /// loopback address nothing leaves the host.
    Unicast(SocketAddr),
}

/// One service instance a responder answers for.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Advert {
    pub service: &'static str,
    pub instance: String,
    /// The SRV target's first label, answered with the address this host
    /// sends its reply from; on macOS the system's DNS-SD service targets
    /// the host's own name instead.
    pub host: String,
    pub port: u16,
    pub txt: Vec<(String, String)>,
}

/// One instance a lookup found. `address` is where its answer came from,
/// which on a LAN is the address the device is reachable at.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Found {
    pub instance: String,
    pub address: IpAddr,
    pub port: u16,
    pub txt: BTreeMap<String, String>,
}

impl Found {
    pub fn get(&self, key: &str) -> Option<&str> {
        self.txt.get(key).map(String::as_str)
    }
}

pub fn device_advert(machine_id: &str, login: &str, ssh_port: u16) -> Advert {
    Advert {
        service: SERVICE,
        instance: label(machine_id),
        host: host_label(machine_id),
        port: ssh_port,
        txt: vec![
            (TXT_ID.to_string(), machine_id.to_string()),
            (TXT_LOGIN.to_string(), login.to_string()),
        ],
    }
}

pub fn pairing_advert(name: &str, machine_id: &str, port: u16) -> Advert {
    Advert {
        service: PAIR_SERVICE,
        instance: label(if name.is_empty() { machine_id } else { name }),
        host: host_label(machine_id),
        port,
        txt: vec![(TXT_ID.to_string(), machine_id.to_string())],
    }
}

fn host_label(machine_id: &str) -> String {
    label(&format!("{HOST_PREFIX}{machine_id}"))
}

/// The first 63 bytes, cut at a character boundary.
fn label(text: &str) -> String {
    let mut end = text.len().min(MAX_LABEL);
    while !text.is_char_boundary(end) {
        end -= 1;
    }
    text[..end].to_string()
}

/// Read on every query that names one of our services, instances or hosts,
/// or each second on macOS, where the system's DNS-SD service answers, so
/// adverts stay current without being pushed.
pub type Adverts = Arc<dyn Fn() -> Vec<Advert> + Send + Sync>;

/// Answers queries for `Adverts` until dropped.
pub struct Responder {
    local: SocketAddr,
    stop: Arc<AtomicBool>,
    thread: Option<JoinHandle<()>>,
}

impl Responder {
    pub fn spawn(net: &Net, adverts: Adverts) -> Result<Self> {
        match net {
            Net::Lan => lan::responder(adverts),
            Net::Unicast(address) => Self::answering(
                UdpSocket::bind(address)
                    .with_context(|| format!("binding the mDNS responder to {address}"))?,
                None,
                adverts,
            ),
        }
    }

    /// The address its socket is bound to; unspecified with port 0 when the
    /// system's DNS-SD service answers in its place.
    pub fn local_addr(&self) -> SocketAddr {
        self.local
    }

    fn answering(socket: UdpSocket, group: Option<SocketAddr>, adverts: Adverts) -> Result<Self> {
        socket.set_read_timeout(Some(POLL))?;
        let local = socket.local_addr()?;
        Self::running(local, move |stop| {
            serve(&socket, group, stop, adverts.as_ref())
        })
    }

    fn running(local: SocketAddr, work: impl FnOnce(&AtomicBool) + Send + 'static) -> Result<Self> {
        let stop = Arc::new(AtomicBool::new(false));
        let thread = std::thread::Builder::new()
            .name("mdns-responder".to_string())
            .spawn({
                let stop = stop.clone();
                move || work(&stop)
            })
            .context("spawning the mDNS responder")?;
        Ok(Self {
            local,
            stop,
            thread: Some(thread),
        })
    }
}

impl Drop for Responder {
    fn drop(&mut self) {
        self.stop.store(true, Ordering::SeqCst);
        if let Some(thread) = self.thread.take()
            && thread.join().is_err()
        {
            tracing::warn!("the mDNS responder panicked");
        }
    }
}

fn serve(
    socket: &UdpSocket,
    group: Option<SocketAddr>,
    stop: &AtomicBool,
    adverts: &(dyn Fn() -> Vec<Advert> + Send + Sync),
) {
    let mut buf = vec![0u8; MAX_PACKET];
    while !stop.load(Ordering::SeqCst) {
        let (len, from) = match socket.recv_from(&mut buf) {
            Ok(received) => received,
            Err(e) if is_timeout(&e) || e.kind() == ErrorKind::ConnectionRefused => continue,
            Err(e) => {
                tracing::warn!("the mDNS responder cannot read: {e}");
                std::thread::sleep(POLL);
                continue;
            }
        };
        let Some((reply, to)) = answer(&buf[..len], from, group, adverts) else {
            continue;
        };
        if let Err(e) = socket.send_to(&reply, to) {
            tracing::debug!("cannot answer an mDNS query from {from}: {e}");
        }
    }
}

fn on_local_network(ip: IpAddr) -> bool {
    match ip {
        IpAddr::V4(v4) => v4.is_private() || v4.is_link_local() || v4.is_loopback(),
        IpAddr::V6(_) => false,
    }
}

fn is_timeout(e: &std::io::Error) -> bool {
    matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut)
}

/// The reply to `packet` and where it goes, when it asks for a service,
/// instance or host name `adverts` holds. A query from a port other than
/// 5353 is a legacy unicast query, answered to its sender with its id and
/// first answered question; one from 5353 is answered to the group unless
/// that question asks for a unicast reply. An A record carries the address
/// the reply leaves from, and a host question goes unanswered without one.
/// Only queries from a private, link-local or loopback address are
/// answered, so a host reachable from the internet is no amplifier for a
/// spoofed sender; a LAN numbered from public or shared address space is
/// not served.
fn answer(
    packet: &[u8],
    from: SocketAddr,
    group: Option<SocketAddr>,
    adverts: &(dyn Fn() -> Vec<Advert> + Send + Sync),
) -> Option<(Vec<u8>, SocketAddr)> {
    answer_routed(packet, from, group, adverts, &route_toward)
}

fn answer_routed(
    packet: &[u8],
    from: SocketAddr,
    group: Option<SocketAddr>,
    adverts: &(dyn Fn() -> Vec<Advert> + Send + Sync),
    route: &dyn Fn(IpAddr) -> Option<Ipv4Addr>,
) -> Option<(Vec<u8>, SocketAddr)> {
    if !on_local_network(from.ip()) {
        return None;
    }
    let message = Message::parse(packet)?;
    if message.flags & FLAG_RESPONSE != 0 {
        return None;
    }
    let asked: Vec<&Question> = message
        .questions
        .iter()
        .filter(|q| q.qclass & CLASS_MASK == CLASS_IN && may_be_ours(q))
        .collect();
    if asked.is_empty() {
        return None;
    }
    let held = adverts();
    let mut reply = Reply::default();
    let mut matched = Vec::new();
    for question in &asked {
        let mut records = false;
        let mut host = false;
        for advert in &held {
            let (named, hosted) = reply.answer(question, advert);
            records |= named;
            host |= hosted;
        }
        matched.push((*question, records, host));
    }
    let legacy = from.port() != MDNS_PORT;
    let destination = |question: &Question| match group {
        Some(group) if !legacy && question.qclass & UNICAST_RESPONSE == 0 => group,
        _ => from,
    };
    let mut first = matched
        .iter()
        .find(|(_, records, host)| *records || *host)?
        .0;
    let mut to = destination(first);
    let mut address = route(to.ip());
    if address.is_none() {
        first = matched.iter().find(|(_, records, _)| *records)?.0;
        to = destination(first);
        address = route(to.ip());
    }
    reply.complete(address);
    let reply = if legacy {
        reply.write(message.id, Some(first), UNICAST_TTL, false)
    } else {
        reply.write(0, None, MULTICAST_TTL, true)
    };
    Some((reply, to))
}

/// Whether `question` names one of our services, an instance of one, or a
/// host under `HOST_PREFIX`, checked before any advert is read.
fn may_be_ours(question: &Question) -> bool {
    let name = &question.name;
    let ours = |labels: &[String]| {
        [SERVICE, PAIR_SERVICE]
            .iter()
            .any(|service| same_labels(labels, &service_name(service)))
    };
    match question.qtype {
        TYPE_PTR => ours(name),
        TYPE_SRV | TYPE_TXT => name.len() > 1 && ours(&name[1..]),
        TYPE_A => is_our_host(name),
        TYPE_ANY => ours(name) || (name.len() > 1 && ours(&name[1..])) || is_our_host(name),
        _ => false,
    }
}

fn is_our_host(name: &[String]) -> bool {
    name.len() == 2
        && name[1].eq_ignore_ascii_case("local")
        && name[0]
            .get(..HOST_PREFIX.len())
            .is_some_and(|prefix| prefix.eq_ignore_ascii_case(HOST_PREFIX))
}

/// The IPv4 address this host sends from toward `to`, the group included;
/// connecting a UDP socket sends nothing.
fn route_toward(to: IpAddr) -> Option<Ipv4Addr> {
    let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).ok()?;
    socket.connect((to, 9)).ok()?;
    match socket.local_addr().ok()?.ip() {
        IpAddr::V4(address) if !address.is_unspecified() => Some(address),
        _ => None,
    }
}

#[derive(PartialEq)]
enum Answer<'a> {
    Ptr(&'a Advert),
    Srv(&'a Advert),
    Txt(&'a Advert),
    Host(&'a str, Ipv4Addr),
}

#[derive(Default)]
struct Reply<'a> {
    answers: Vec<Answer<'a>>,
    additional: Vec<Answer<'a>>,
    hosts_asked: Vec<&'a str>,
}

impl<'a> Reply<'a> {
    /// Whether `question` names `advert`'s service or instance, and whether
    /// it names its host, which `complete` answers once the reply's address
    /// is known.
    fn answer(&mut self, question: &Question, advert: &'a Advert) -> (bool, bool) {
        let any = question.qtype == TYPE_ANY;
        let name = &question.name;
        let mut records = Vec::new();
        if (any || question.qtype == TYPE_PTR) && same_labels(name, &service_name(advert.service)) {
            records.push(Answer::Ptr(advert));
        }
        if same_labels(name, &instance_name(advert)) {
            if any || question.qtype == TYPE_SRV {
                records.push(Answer::Srv(advert));
            }
            if any || question.qtype == TYPE_TXT {
                records.push(Answer::Txt(advert));
            }
        }
        let host = (any || question.qtype == TYPE_A) && same_labels(name, &host_name(advert));
        if host && !self.hosts_asked.contains(&advert.host.as_str()) {
            self.hosts_asked.push(&advert.host);
        }
        let named = !records.is_empty();
        for record in records {
            if !self.answers.contains(&record) {
                self.answers.push(record);
            }
        }
        (named, host)
    }

    /// RFC 6763 12: a PTR answer brings its SRV and TXT records, and an SRV
    /// record the address of its target. Without an address no A record is
    /// written, and a question only for one goes unanswered.
    fn complete(&mut self, address: Option<Ipv4Addr>) {
        if let Some(address) = address {
            for host in std::mem::take(&mut self.hosts_asked) {
                let record = Answer::Host(host, address);
                if !self.answers.contains(&record) {
                    self.answers.push(record);
                }
            }
        }
        let pointed: Vec<&'a Advert> = self
            .answers
            .iter()
            .filter_map(|record| match record {
                Answer::Ptr(advert) => Some(*advert),
                _ => None,
            })
            .collect();
        for advert in pointed {
            self.add(Answer::Srv(advert));
            self.add(Answer::Txt(advert));
        }
        let targets: Vec<&'a str> = self
            .answers
            .iter()
            .chain(&self.additional)
            .filter_map(|record| match record {
                Answer::Srv(advert) => Some(advert.host.as_str()),
                _ => None,
            })
            .collect();
        if let Some(address) = address {
            for host in targets {
                self.add(Answer::Host(host, address));
            }
        }
    }

    fn add(&mut self, record: Answer<'a>) {
        if !self.answers.contains(&record) && !self.additional.contains(&record) {
            self.additional.push(record);
        }
    }

    fn write(&self, id: u16, question: Option<&Question>, ttl: u32, flush: bool) -> Vec<u8> {
        let mut out = Vec::with_capacity(512);
        put_header(
            &mut out,
            id,
            FLAG_RESPONSE | FLAG_AUTHORITATIVE,
            u16::from(question.is_some()),
            self.answers.len() as u16,
            self.additional.len() as u16,
        );
        if let Some(question) = question {
            put_name(&mut out, &question.name);
            put_u16(&mut out, question.qtype);
            put_u16(&mut out, CLASS_IN);
        }
        let unique = if flush {
            CLASS_IN | CACHE_FLUSH
        } else {
            CLASS_IN
        };
        for record in self.answers.iter().chain(&self.additional) {
            match record {
                Answer::Ptr(advert) => {
                    let mut rdata = Vec::new();
                    put_name(&mut rdata, &instance_name(advert));
                    let name = service_name(advert.service);
                    put_record(&mut out, &name, TYPE_PTR, CLASS_IN, ttl, &rdata);
                }
                Answer::Srv(advert) => {
                    let mut srv = Vec::new();
                    put_u16(&mut srv, 0);
                    put_u16(&mut srv, 0);
                    put_u16(&mut srv, advert.port);
                    put_name(&mut srv, &host_name(advert));
                    let name = instance_name(advert);
                    put_record(&mut out, &name, TYPE_SRV, unique, ttl, &srv);
                }
                Answer::Txt(advert) => {
                    let name = instance_name(advert);
                    put_record(&mut out, &name, TYPE_TXT, unique, ttl, &txt_record(advert));
                }
                Answer::Host(host, address) => {
                    let name = [host.to_string(), "local".to_string()];
                    put_record(&mut out, &name, TYPE_A, unique, ttl, &address.octets());
                }
            }
        }
        out
    }
}

/// The instances of `service` found within `window`, each at an address
/// on the local network.
pub fn browse(net: &Net, service: &str, window: Duration) -> Result<Vec<Found>> {
    match net {
        Net::Lan => lan::browse(service, window),
        Net::Unicast(address) => {
            let socket =
                UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).context("opening an mDNS socket")?;
            ask(&socket, *address, service, window)
        }
    }
}

/// Sends a query for `service` to `to` and collects the instances that
/// answer within `window`. A legacy unicast reply echoes the query's id, so
/// a reply with another id, or from outside the local network, is dropped.
fn ask(socket: &UdpSocket, to: SocketAddr, service: &str, window: Duration) -> Result<Vec<Found>> {
    let id = OsRng.next_u32() as u16;
    let query = query(id, service);
    socket
        .send_to(&query, to)
        .with_context(|| format!("sending an mDNS query to {to}"))?;
    let start = Instant::now();
    let mut resent = false;
    let mut found: Vec<Found> = Vec::new();
    let mut buf = vec![0u8; MAX_PACKET];
    loop {
        let elapsed = start.elapsed();
        if elapsed >= window {
            break;
        }
        if !resent && elapsed >= RESEND_AFTER {
            resent = true;
            if let Err(e) = socket.send_to(&query, to) {
                tracing::debug!("cannot resend an mDNS query to {to}: {e}");
            }
        }
        let until = if resent {
            window
        } else {
            window.min(RESEND_AFTER)
        };
        let wait = until.saturating_sub(elapsed);
        socket.set_read_timeout(Some(wait.max(Duration::from_millis(1))))?;
        let (len, from) = match socket.recv_from(&mut buf) {
            Ok(received) => received,
            Err(e) if is_timeout(&e) || e.kind() == ErrorKind::ConnectionRefused => continue,
            Err(e) => return Err(e).context("reading mDNS answers"),
        };
        if !on_local_network(from.ip()) || Message::id_of(&buf[..len]) != Some(id) {
            continue;
        }
        for instance in found_in(&buf[..len], from, service) {
            if !found.contains(&instance) {
                found.push(instance);
            }
        }
    }
    Ok(found)
}

/// The instances of `service` a response names, each with its SRV port and
/// TXT strings; an instance without an SRV record is left out.
fn found_in(packet: &[u8], from: SocketAddr, service: &str) -> Vec<Found> {
    let Some(message) = Message::parse(packet) else {
        return Vec::new();
    };
    if message.flags & FLAG_RESPONSE == 0 {
        return Vec::new();
    }
    let wanted = service_name(service);
    let mut out = Vec::new();
    for record in &message.records {
        let Rdata::Ptr(instance) = &record.rdata else {
            continue;
        };
        if !same_labels(&record.name, &wanted) || instance.is_empty() {
            continue;
        }
        let port = message.records.iter().find_map(|r| match &r.rdata {
            Rdata::Srv { port } if same_labels(&r.name, instance) => Some(*port),
            _ => None,
        });
        let Some(port) = port else {
            continue;
        };
        let strings: Vec<Vec<u8>> = message
            .records
            .iter()
            .filter_map(|r| match &r.rdata {
                Rdata::Txt(strings) if same_labels(&r.name, instance) => Some(strings.clone()),
                _ => None,
            })
            .flatten()
            .collect();
        let txt = txt_map(&strings);
        let found = Found {
            instance: instance[0].clone(),
            address: from.ip(),
            port,
            txt,
        };
        if !out.contains(&found) {
            out.push(found);
        }
    }
    out
}

/// TXT strings as `key=value` pairs, keys lowercased and the first of a
/// repeated key kept, as RFC 6763 6.4 reads them.
fn txt_map(strings: &[Vec<u8>]) -> BTreeMap<String, String> {
    let mut txt = BTreeMap::new();
    for string in strings {
        let text = String::from_utf8_lossy(string);
        let (key, value) = text.split_once('=').unwrap_or((&text, ""));
        if key.is_empty() {
            continue;
        }
        txt.entry(key.to_ascii_lowercase())
            .or_insert_with(|| value.to_string());
    }
    txt
}

/// An advert's TXT record data, one length-prefixed string per pair; a
/// pair too long for one string is left out.
fn txt_record(advert: &Advert) -> Vec<u8> {
    let mut txt = Vec::new();
    for (key, value) in &advert.txt {
        let string = format!("{key}={value}");
        if string.len() <= 255 {
            txt.push(string.len() as u8);
            txt.extend_from_slice(string.as_bytes());
        }
    }
    if txt.is_empty() {
        txt.push(0);
    }
    txt
}

fn service_name(service: &str) -> Vec<String> {
    service
        .split('.')
        .chain(["local"])
        .map(str::to_string)
        .collect()
}

fn same_labels(a: &[String], b: &[String]) -> bool {
    a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.eq_ignore_ascii_case(y))
}

fn query(id: u16, service: &str) -> Vec<u8> {
    let mut out = Vec::with_capacity(64);
    put_header(&mut out, id, 0, 1, 0, 0);
    put_name(&mut out, &service_name(service));
    put_u16(&mut out, TYPE_PTR);
    put_u16(&mut out, CLASS_IN);
    out
}

fn instance_name(advert: &Advert) -> Vec<String> {
    let mut name = vec![label(&advert.instance)];
    name.extend(service_name(advert.service));
    name
}

fn host_name(advert: &Advert) -> Vec<String> {
    vec![label(&advert.host), "local".to_string()]
}

fn put_header(out: &mut Vec<u8>, id: u16, flags: u16, questions: u16, answers: u16, extra: u16) {
    for value in [id, flags, questions, answers, 0, extra] {
        put_u16(out, value);
    }
}

fn put_record(out: &mut Vec<u8>, name: &[String], rtype: u16, class: u16, ttl: u32, rdata: &[u8]) {
    put_name(out, name);
    put_u16(out, rtype);
    put_u16(out, class);
    out.extend_from_slice(&ttl.to_be_bytes());
    put_u16(out, rdata.len() as u16);
    out.extend_from_slice(rdata);
}

fn put_name(out: &mut Vec<u8>, labels: &[String]) {
    for label in labels {
        let label = &label.as_bytes()[..label.len().min(MAX_LABEL)];
        out.push(label.len() as u8);
        out.extend_from_slice(label);
    }
    out.push(0);
}

fn put_u16(out: &mut Vec<u8>, value: u16) {
    out.extend_from_slice(&value.to_be_bytes());
}

struct Question {
    name: Vec<String>,
    qtype: u16,
    qclass: u16,
}

struct Record {
    name: Vec<String>,
    rdata: Rdata,
}

enum Rdata {
    Ptr(Vec<String>),
    Srv { port: u16 },
    Txt(Vec<Vec<u8>>),
    Other,
}

/// A DNS message, read whole or not at all.
struct Message {
    id: u16,
    flags: u16,
    questions: Vec<Question>,
    records: Vec<Record>,
}

impl Message {
    fn id_of(packet: &[u8]) -> Option<u16> {
        Some(u16::from_be_bytes([*packet.first()?, *packet.get(1)?]))
    }

    fn parse(packet: &[u8]) -> Option<Self> {
        let mut at = 0;
        let mut header = [0u16; 6];
        for value in &mut header {
            *value = read_u16(packet, &mut at)?;
        }
        let [id, flags, questions, answers, authority, additional] = header;
        let mut message = Message {
            id,
            flags,
            questions: Vec::new(),
            records: Vec::new(),
        };
        for _ in 0..questions {
            let name = read_name(packet, &mut at)?;
            let qtype = read_u16(packet, &mut at)?;
            let qclass = read_u16(packet, &mut at)?;
            message.questions.push(Question {
                name,
                qtype,
                qclass,
            });
        }
        let records = u32::from(answers) + u32::from(authority) + u32::from(additional);
        for _ in 0..records {
            let name = read_name(packet, &mut at)?;
            let rtype = read_u16(packet, &mut at)?;
            let _class = read_u16(packet, &mut at)?;
            at = at.checked_add(4)?;
            let len = usize::from(read_u16(packet, &mut at)?);
            let end = at.checked_add(len)?;
            let rdata = packet.get(at..end)?;
            let rdata = match rtype {
                TYPE_PTR => {
                    let mut inner = at;
                    let target = read_name(packet, &mut inner)?;
                    if inner > end {
                        return None;
                    }
                    Rdata::Ptr(target)
                }
                TYPE_SRV => {
                    let port = u16::from_be_bytes([*rdata.get(4)?, *rdata.get(5)?]);
                    Rdata::Srv { port }
                }
                TYPE_TXT => Rdata::Txt(read_strings(rdata)?),
                _ => Rdata::Other,
            };
            message.records.push(Record { name, rdata });
            at = end;
        }
        Some(message)
    }
}

fn read_u16(packet: &[u8], at: &mut usize) -> Option<u16> {
    let bytes = packet.get(*at..at.checked_add(2)?)?;
    *at += 2;
    Some(u16::from_be_bytes([bytes[0], bytes[1]]))
}

/// Follows compression pointers, at most `MAX_JUMPS` of them, so a pointer
/// loop ends; `at` moves past the name where it first appears.
fn read_name(packet: &[u8], at: &mut usize) -> Option<Vec<String>> {
    let mut labels = Vec::new();
    let mut total = 0;
    let mut pos = *at;
    let mut jumps = 0;
    let mut after: Option<usize> = None;
    loop {
        let len = *packet.get(pos)?;
        match len & 0xC0 {
            0xC0 => {
                let low = *packet.get(pos + 1)?;
                after.get_or_insert(pos + 2);
                jumps += 1;
                if jumps > MAX_JUMPS {
                    return None;
                }
                pos = usize::from(u16::from_be_bytes([len & 0x3F, low]));
            }
            0x00 if len == 0 => {
                after.get_or_insert(pos + 1);
                break;
            }
            0x00 => {
                let len = usize::from(len);
                let bytes = packet.get(pos + 1..pos + 1 + len)?;
                total += len + 1;
                if total > MAX_NAME {
                    return None;
                }
                labels.push(String::from_utf8(bytes.to_vec()).ok()?);
                pos += 1 + len;
            }
            _ => return None,
        }
    }
    *at = after?;
    Some(labels)
}

fn read_strings(rdata: &[u8]) -> Option<Vec<Vec<u8>>> {
    let mut strings = Vec::new();
    let mut at = 0;
    while at < rdata.len() {
        let len = usize::from(rdata[at]);
        let string = rdata.get(at + 1..at + 1 + len)?;
        if !string.is_empty() {
            strings.push(string.to_vec());
        }
        at += 1 + len;
    }
    Some(strings)
}

#[cfg(test)]
mod tests {
    use std::net::{Ipv4Addr, UdpSocket};
    use std::sync::Mutex;
    use std::sync::atomic::{AtomicUsize, Ordering};

    use super::*;

    /// Long enough for a loaded host to schedule the responder thread.
    const FOUND_WINDOW: Duration = Duration::from_secs(3);
    const NONE_WINDOW: Duration = Duration::from_millis(400);

    fn loopback_responder(adverts: Adverts) -> Responder {
        Responder::spawn(
            &Net::Unicast(SocketAddr::from((Ipv4Addr::LOCALHOST, 0))),
            adverts,
        )
        .unwrap()
    }

    fn fixed(adverts: Vec<Advert>) -> Adverts {
        Arc::new(move || adverts.clone())
    }

    fn browse_at(responder: &Responder, service: &str, window: Duration) -> Vec<Found> {
        browse(&Net::Unicast(responder.local_addr()), service, window).unwrap()
    }

    #[test]
    fn a_browse_finds_each_advert_of_its_service_at_the_responders_address() {
        let responder = loopback_responder(fixed(vec![
            device_advert("peer-1", "me", 2222),
            pairing_advert("desk", "peer-1", 7201),
        ]));
        let found = browse_at(&responder, SERVICE, FOUND_WINDOW);
        assert_eq!(found.len(), 1, "{found:?}");
        assert_eq!(found[0].address, IpAddr::V4(Ipv4Addr::LOCALHOST));
        assert_eq!(found[0].port, 2222);
        assert_eq!(found[0].get(TXT_ID), Some("peer-1"));
        assert_eq!(found[0].get(TXT_LOGIN), Some("me"));

        let pairing = browse_at(&responder, PAIR_SERVICE, FOUND_WINDOW);
        assert_eq!(pairing.len(), 1, "{pairing:?}");
        assert_eq!(pairing[0].port, 7201);
        assert_eq!(pairing[0].instance, "desk");
        assert_eq!(pairing[0].get(TXT_ID), Some("peer-1"));
        assert_eq!(pairing[0].get(TXT_LOGIN), None);
    }

    #[test]
    fn an_advert_withdrawn_is_no_longer_found() {
        let held = Arc::new(Mutex::new(vec![device_advert("peer-1", "me", 22)]));
        let responder = loopback_responder({
            let held = held.clone();
            Arc::new(move || held.lock().unwrap().clone())
        });
        assert_eq!(browse_at(&responder, SERVICE, FOUND_WINDOW).len(), 1);
        held.lock().unwrap().clear();
        assert_eq!(
            browse_at(&responder, SERVICE, NONE_WINDOW),
            Vec::<Found>::new()
        );
    }

    #[test]
    fn a_query_for_another_name_is_not_answered_and_reads_no_adverts() {
        let reads = Arc::new(AtomicUsize::new(0));
        let responder = loopback_responder({
            let reads = reads.clone();
            Arc::new(move || {
                reads.fetch_add(1, Ordering::SeqCst);
                vec![device_advert("peer-1", "me", 22)]
            })
        });
        assert_eq!(
            browse_at(&responder, "_other._tcp", NONE_WINDOW),
            Vec::<Found>::new()
        );
        let socket = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
        socket.send_to(b"not dns", responder.local_addr()).unwrap();
        socket
            .set_read_timeout(Some(Duration::from_millis(200)))
            .unwrap();
        assert!(socket.recv_from(&mut [0u8; 512]).is_err());
        assert_eq!(reads.load(Ordering::SeqCst), 0);
    }

    #[test]
    fn only_a_query_from_a_local_network_is_answered() {
        let adverts = || vec![device_advert("peer-1", "me", 22)];
        let asked = query(7, SERVICE);
        let at = |ip: [u8; 4], port: u16| SocketAddr::from((Ipv4Addr::from(ip), port));
        let group = Some(SocketAddr::from((GROUP, MDNS_PORT)));
        for local in [
            [192, 168, 1, 5],
            [10, 0, 0, 2],
            [169, 254, 3, 4],
            [127, 0, 0, 1],
        ] {
            let (reply, to) = answer(&asked, at(local, 40000), group, &adverts)
                .unwrap_or_else(|| panic!("{local:?} was not answered"));
            assert_eq!(to, at(local, 40000), "a legacy query is answered directly");
            assert_eq!(Message::id_of(&reply), Some(7));
            assert_eq!(found_in(&reply, at(local, MDNS_PORT), SERVICE).len(), 1);
        }
        let (_, to) = answer(&asked, at([192, 168, 1, 5], MDNS_PORT), group, &adverts).unwrap();
        assert_eq!(
            Some(to),
            group,
            "a query from 5353 is answered to the group"
        );
        for remote in [[198, 51, 100, 7], [8, 8, 8, 8], [100, 64, 0, 1]] {
            assert!(answer(&asked, at(remote, 40000), group, &adverts).is_none());
        }
    }

    /// A responder that answers one query with `id`, or with the query's own
    /// id when None.
    fn replying_with_id(id: Option<u16>) -> (SocketAddr, std::thread::JoinHandle<()>) {
        let socket = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
        socket
            .set_read_timeout(Some(Duration::from_secs(10)))
            .unwrap();
        let at = socket.local_addr().unwrap();
        let thread = std::thread::spawn(move || {
            let mut buf = [0u8; 512];
            let Ok((len, from)) = socket.recv_from(&mut buf) else {
                return;
            };
            let id = id.unwrap_or_else(|| Message::id_of(&buf[..len]).unwrap());
            let advert = device_advert("peer-1", "me", 22);
            let reply = Reply {
                answers: vec![Answer::Ptr(&advert)],
                additional: vec![Answer::Srv(&advert), Answer::Txt(&advert)],
                ..Reply::default()
            }
            .write(id, None, UNICAST_TTL, false);
            socket.send_to(&reply, from).unwrap();
        });
        (at, thread)
    }

    #[test]
    fn a_reply_without_the_querys_id_is_dropped() {
        let (at, thread) = replying_with_id(None);
        assert_eq!(
            browse(&Net::Unicast(at), SERVICE, FOUND_WINDOW)
                .unwrap()
                .len(),
            1
        );
        thread.join().unwrap();
        let (at, thread) = replying_with_id(Some(0));
        assert_eq!(
            browse(&Net::Unicast(at), SERVICE, NONE_WINDOW).unwrap(),
            Vec::<Found>::new()
        );
        thread.join().unwrap();
    }

    #[test]
    fn a_machine_id_longer_than_a_label_is_found_whole() {
        let id = "m".repeat(128);
        let responder = loopback_responder(fixed(vec![device_advert(&id, "me", 22)]));
        let found = browse_at(&responder, SERVICE, FOUND_WINDOW);
        assert_eq!(found.len(), 1, "{found:?}");
        assert_eq!(found[0].get(TXT_ID), Some(id.as_str()));
        assert_eq!(found[0].instance.len(), 63);
    }

    #[test]
    fn a_responder_is_stopped_by_dropping_it() {
        let responder = loopback_responder(fixed(vec![device_advert("peer-1", "me", 22)]));
        let net = Net::Unicast(responder.local_addr());
        drop(responder);
        assert_eq!(
            browse(&net, SERVICE, NONE_WINDOW).unwrap(),
            Vec::<Found>::new()
        );
    }

    fn asking(id: u16, questions: &[(Vec<String>, u16, u16)]) -> Vec<u8> {
        let mut out = Vec::new();
        put_header(&mut out, id, 0, questions.len() as u16, 0, 0);
        for (name, qtype, qclass) in questions {
            put_name(&mut out, name);
            put_u16(&mut out, *qtype);
            put_u16(&mut out, *qclass);
        }
        out
    }

    fn host_of(advert: &Advert) -> Vec<String> {
        vec![advert.host.clone(), "local".to_string()]
    }

    struct Decoded {
        answer: bool,
        name: Vec<String>,
        rtype: u16,
        class: u16,
        rdata: std::ops::Range<usize>,
    }

    /// Every record of a reply with its section, type and class, which
    /// `Message::parse` does not keep.
    fn decoded(packet: &[u8]) -> Vec<Decoded> {
        let mut at = 0;
        let mut header = [0u16; 6];
        for value in &mut header {
            *value = read_u16(packet, &mut at).unwrap();
        }
        for _ in 0..header[2] {
            read_name(packet, &mut at).unwrap();
            at += 4;
        }
        let mut out = Vec::new();
        for index in 0..header[3] + header[4] + header[5] {
            let name = read_name(packet, &mut at).unwrap();
            let rtype = read_u16(packet, &mut at).unwrap();
            let class = read_u16(packet, &mut at).unwrap();
            at += 4;
            let len = usize::from(read_u16(packet, &mut at).unwrap());
            out.push(Decoded {
                answer: index < header[3],
                name,
                rtype,
                class,
                rdata: at..at + len,
            });
            at += len;
        }
        assert_eq!(at, packet.len());
        out
    }

    fn srv_targets(packet: &[u8]) -> Vec<Vec<String>> {
        decoded(packet)
            .into_iter()
            .filter(|r| r.rtype == TYPE_SRV)
            .map(|r| read_name(packet, &mut (r.rdata.start + 6)).unwrap())
            .collect()
    }

    fn addresses_of(packet: &[u8], host: &[String]) -> Vec<Ipv4Addr> {
        decoded(packet)
            .into_iter()
            .filter(|r| r.rtype == TYPE_A && same_labels(&r.name, host))
            .map(|r| <[u8; 4]>::try_from(&packet[r.rdata]).unwrap().into())
            .collect()
    }

    fn types_in(packet: &[u8], answer: bool) -> Vec<u16> {
        decoded(packet)
            .into_iter()
            .filter(|r| r.answer == answer)
            .map(|r| r.rtype)
            .collect()
    }

    /// mDNSResponder browses with a PTR query from port 5353, then asks for
    /// whichever SRV, TXT or A record its cache lacks; a unicast-response
    /// question keeps the replies on loopback here.
    #[test]
    fn a_mac_shaped_lookup_gets_the_srv_txt_and_address_of_the_srv_target() {
        let advert = device_advert("peer-1", "me", 2222);
        let adverts = {
            let advert = advert.clone();
            move || vec![advert.clone()]
        };
        let group = Some(SocketAddr::from((GROUP, MDNS_PORT)));
        let from = SocketAddr::from((Ipv4Addr::LOCALHOST, MDNS_PORT));
        let host = host_of(&advert);
        let ask = |name: Vec<String>, qtype: u16| {
            let query = asking(0, &[(name, qtype, CLASS_IN | UNICAST_RESPONSE)]);
            let (reply, to) = answer(&query, from, group, &adverts)
                .unwrap_or_else(|| panic!("type {qtype} was not answered"));
            assert_eq!(to, from);
            for record in decoded(&reply) {
                let shared = record.rtype == TYPE_PTR;
                assert_eq!(
                    record.class,
                    if shared {
                        CLASS_IN
                    } else {
                        CLASS_IN | CACHE_FLUSH
                    },
                    "type {}",
                    record.rtype
                );
            }
            reply
        };

        let browsed = ask(service_name(SERVICE), TYPE_PTR);
        assert_eq!(found_in(&browsed, from, SERVICE).len(), 1);
        assert_eq!(types_in(&browsed, true), [TYPE_PTR]);
        assert_eq!(types_in(&browsed, false), [TYPE_SRV, TYPE_TXT, TYPE_A]);
        assert_eq!(srv_targets(&browsed), std::slice::from_ref(&host));
        assert_eq!(addresses_of(&browsed, &host), [Ipv4Addr::LOCALHOST]);

        let srv = ask(instance_name(&advert), TYPE_SRV);
        assert_eq!(types_in(&srv, true), [TYPE_SRV]);
        assert_eq!(types_in(&srv, false), [TYPE_A]);
        assert_eq!(addresses_of(&srv, &host), [Ipv4Addr::LOCALHOST]);

        let txt = ask(instance_name(&advert), TYPE_TXT);
        assert_eq!(types_in(&txt, true), [TYPE_TXT]);
        let record = decoded(&txt).remove(0);
        let strings = read_strings(&txt[record.rdata]).unwrap();
        assert_eq!(
            txt_map(&strings).get(TXT_ID).map(String::as_str),
            Some("peer-1")
        );

        let any = ask(instance_name(&advert), TYPE_ANY);
        assert_eq!(types_in(&any, true), [TYPE_SRV, TYPE_TXT]);
        assert_eq!(types_in(&any, false), [TYPE_A]);

        let address = ask(host.clone(), TYPE_A);
        assert_eq!(types_in(&address, true), [TYPE_A]);
        assert_eq!(addresses_of(&address, &host), [Ipv4Addr::LOCALHOST]);
    }

    #[test]
    fn a_reply_to_the_group_carries_the_address_it_leaves_from() {
        let advert = device_advert("peer-1", "me", 22);
        let adverts = {
            let advert = advert.clone();
            move || vec![advert.clone()]
        };
        let group = SocketAddr::from((GROUP, MDNS_PORT));
        let from = SocketAddr::from((Ipv4Addr::LOCALHOST, MDNS_PORT));
        let query = asking(0, &[(instance_name(&advert), TYPE_SRV, CLASS_IN)]);
        let (reply, to) = answer(&query, from, Some(group), &adverts).unwrap();
        assert_eq!(to, group);
        let toward_group: Vec<Ipv4Addr> = route_toward(group.ip()).into_iter().collect();
        assert_eq!(addresses_of(&reply, &host_of(&advert)), toward_group);
        assert!(!toward_group.contains(&Ipv4Addr::LOCALHOST));
    }

    #[test]
    fn a_reply_without_an_address_writes_no_a_record() {
        let advert = device_advert("peer-1", "me", 22);
        let mut reply = Reply::default();
        let host = Question {
            name: host_of(&advert),
            qtype: TYPE_A,
            qclass: CLASS_IN,
        };
        assert_eq!(reply.answer(&host, &advert), (false, true));
        let browse = Question {
            name: service_name(SERVICE),
            qtype: TYPE_PTR,
            qclass: CLASS_IN,
        };
        assert_eq!(reply.answer(&browse, &advert), (true, false));
        reply.complete(None);
        let written = reply.write(0, None, MULTICAST_TTL, true);
        assert_eq!(types_in(&written, true), [TYPE_PTR]);
        assert_eq!(types_in(&written, false), [TYPE_SRV, TYPE_TXT]);

        let mut host_only = Reply::default();
        host_only.answer(&host, &advert);
        host_only.complete(None);
        assert!(host_only.answers.is_empty());
    }

    #[test]
    fn without_a_route_a_host_question_is_neither_echoed_nor_answered() {
        let advert = device_advert("peer-1", "me", 22);
        let adverts = {
            let advert = advert.clone();
            move || vec![advert.clone()]
        };
        let no_route = |_: IpAddr| None;
        let from = SocketAddr::from((Ipv4Addr::LOCALHOST, 40000));
        let host = (host_of(&advert), TYPE_A, CLASS_IN);
        let browse = (service_name(SERVICE), TYPE_PTR, CLASS_IN);

        let query = asking(9, &[host.clone(), browse]);
        let (reply, to) = answer_routed(&query, from, None, &adverts, &no_route).unwrap();
        assert_eq!(to, from);
        let message = Message::parse(&reply).unwrap();
        assert!(same_labels(
            &message.questions[0].name,
            &service_name(SERVICE)
        ));
        assert_eq!(types_in(&reply, true), [TYPE_PTR]);
        assert_eq!(types_in(&reply, false), [TYPE_SRV, TYPE_TXT]);

        let query = asking(9, &[host]);
        assert!(answer_routed(&query, from, None, &adverts, &no_route).is_none());
    }

    #[test]
    fn a_legacy_query_echoes_its_first_answered_question() {
        let advert = device_advert("peer-1", "me", 22);
        let adverts = {
            let advert = advert.clone();
            move || vec![advert.clone()]
        };
        let from = SocketAddr::from((Ipv4Addr::LOCALHOST, 40000));
        let other = device_advert("peer-2", "me", 22);
        let query = asking(
            9,
            &[
                (instance_name(&other), TYPE_SRV, CLASS_IN),
                (instance_name(&advert), TYPE_SRV, CLASS_IN),
            ],
        );
        let (reply, to) = answer(&query, from, None, &adverts).unwrap();
        assert_eq!(to, from);
        let message = Message::parse(&reply).unwrap();
        assert_eq!(message.id, 9);
        assert_eq!(message.questions.len(), 1);
        assert!(same_labels(
            &message.questions[0].name,
            &instance_name(&advert)
        ));
        assert_eq!(types_in(&reply, true), [TYPE_SRV]);
        assert!(decoded(&reply).iter().all(|r| r.class == CLASS_IN));
    }

    #[test]
    fn no_srv_target_is_a_machine_name_another_responder_may_own() {
        let pairing = pairing_advert("desk", "peer-1", 7201);
        let device = device_advert("peer-1", "me", 22);
        assert_eq!(pairing.host, device.host);
        assert!(pairing.host.starts_with(HOST_PREFIX), "{}", pairing.host);
        assert!(device_advert(&"m".repeat(128), "me", 22).host.len() <= MAX_LABEL);
    }

    #[test]
    fn a_query_for_a_host_name_not_ours_is_not_answered_and_reads_no_adverts() {
        let reads = AtomicUsize::new(0);
        let adverts = || {
            reads.fetch_add(1, Ordering::SeqCst);
            vec![pairing_advert("desk", "peer-1", 7201)]
        };
        let from = SocketAddr::from((Ipv4Addr::LOCALHOST, MDNS_PORT));
        for name in [
            vec!["desk".to_string(), "local".to_string()],
            vec!["peer-1".to_string(), "local".to_string()],
            vec![
                "desk".to_string(),
                "_other._tcp".to_string(),
                "local".to_string(),
            ],
        ] {
            for qtype in [TYPE_A, TYPE_SRV, TYPE_TXT, TYPE_ANY] {
                let query = asking(0, &[(name.clone(), qtype, CLASS_IN)]);
                assert!(answer(&query, from, None, &adverts).is_none());
            }
        }
        assert_eq!(reads.load(Ordering::SeqCst), 0);
    }

    fn from() -> SocketAddr {
        SocketAddr::from((Ipv4Addr::new(192, 0, 2, 7), 5353))
    }

    fn put_labels(out: &mut Vec<u8>, labels: &[&str]) {
        for label in labels {
            out.push(label.len() as u8);
            out.extend_from_slice(label.as_bytes());
        }
    }

    fn record_header(out: &mut Vec<u8>, rtype: u16, rdata_len: usize) {
        out.extend_from_slice(&rtype.to_be_bytes());
        out.extend_from_slice(&0x8001u16.to_be_bytes());
        out.extend_from_slice(&120u32.to_be_bytes());
        out.extend_from_slice(&(rdata_len as u16).to_be_bytes());
    }

    /// A response the way other responders write it: names compressed
    /// against earlier ones, and the SRV and TXT in the answer section.
    fn compressed_response() -> Vec<u8> {
        let mut out = vec![0, 0, 0x84, 0, 0, 0, 0, 3, 0, 0, 0, 0];
        let service_at = out.len() as u16;
        put_labels(&mut out, &["_second-brain", "_tcp", "local"]);
        out.push(0);
        let service_ptr = [0xC0 | (service_at >> 8) as u8, service_at as u8];
        record_header(&mut out, 12, 1 + 4 + 2);
        let instance_at = out.len() as u16;
        put_labels(&mut out, &["peer"]);
        out.extend_from_slice(&service_ptr);
        let instance_ptr = [0xC0 | (instance_at >> 8) as u8, instance_at as u8];

        out.extend_from_slice(&instance_ptr);
        let target = {
            let mut t = Vec::new();
            put_labels(&mut t, &["peer"]);
            t.extend_from_slice(&[0xC0, 12 + 1 + 13 + 1 + 4]);
            t
        };
        record_header(&mut out, 33, 6 + target.len());
        out.extend_from_slice(&[0, 0, 0, 0]);
        out.extend_from_slice(&2222u16.to_be_bytes());
        out.extend_from_slice(&target);

        out.extend_from_slice(&instance_ptr);
        let txt: &[&[u8]] = &[b"id=peer", b"login=me", b"id=shadowed", b"flag"];
        record_header(&mut out, 16, txt.iter().map(|s| s.len() + 1).sum());
        for string in txt {
            out.push(string.len() as u8);
            out.extend_from_slice(string);
        }
        out
    }

    #[test]
    fn a_response_with_compressed_names_is_read() {
        let found = found_in(&compressed_response(), from(), SERVICE);
        assert_eq!(found.len(), 1, "{found:?}");
        assert_eq!(found[0].instance, "peer");
        assert_eq!(found[0].address, from().ip());
        assert_eq!(found[0].port, 2222);
        assert_eq!(found[0].get(TXT_ID), Some("peer"));
        assert_eq!(found[0].get(TXT_LOGIN), Some("me"));
        assert_eq!(found[0].get("flag"), Some(""));
        assert!(found_in(&compressed_response(), from(), PAIR_SERVICE).is_empty());
    }

    #[test]
    fn a_truncated_or_looping_packet_yields_nothing() {
        let whole = compressed_response();
        for end in 0..whole.len() {
            assert!(
                found_in(&whole[..end], from(), SERVICE).is_empty(),
                "a response cut at {end} bytes was read"
            );
        }
        let mut looping = vec![0, 0, 0x84, 0, 0, 0, 0, 1, 0, 0, 0, 0];
        looping.extend_from_slice(&[0xC0, 12]);
        record_header(&mut looping, 12, 2);
        looping.extend_from_slice(&[0xC0, 12]);
        assert!(found_in(&looping, from(), SERVICE).is_empty());
        let mut query = compressed_response();
        query[2] = 0;
        assert!(found_in(&query, from(), SERVICE).is_empty());
    }
}