rtci-mdns 0.5.0

Sans-I/O mDNS (RFC 6762) querier and responder, as used for WebRTC mDNS ICE candidates
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
//! The resolver: query series, which responses resolve, and the cache (RFC 6762 sections 5,
//! 6, 6.1, 7.3, 10, 11, 16 to 18; draft-ietf-mmusic-mdns-ice-candidates sections 3.2.1, 3.2.2).

use super::testkit::*;
use super::wire::{CLASS_IN, CLASS_TOP_BIT, TYPE_A, TYPE_AAAA, TYPE_NSEC};
use super::*;
use sansio::Protocol;

/// The host that owns `UUID_1`, as address and as mDNS source.
const OWNER: &str = "192.168.1.50";
const OWNER_SRC: &str = "192.168.1.50:5353";

/// A resolver with a query for `UUID_1` sent at `base`, its packet taken off the queue.
fn asking(base: Instant, config: MdnsConfig) -> (Mdns, QueryId) {
    let mut conn = Mdns::new(base, config);
    let id = conn.query_now(base, UUID_1);
    assert_eq!(query_rounds(&sent(&mut conn, base)), vec![ms(0)]);
    (conn, id)
}

/// Whether `bytes` from `from`, received on the multicast group, resolves a query for
/// `UUID_1` to `OWNER`.
fn resolves(bytes: &[u8], from: &str) -> bool {
    let base = Instant::now();
    let (mut conn, id) = asking(base, config());
    deliver(&mut conn, base, from, bytes);
    let answered = answered(&mut conn);
    if answered.is_empty() {
        assert!(conn.is_query_pending(id), "an ignored answer ends nothing");
        return false;
    }
    assert_eq!(answered, vec![(id, ip(OWNER))]);
    assert!(!conn.is_query_pending(id));
    true
}

fn query_times(packets: &[Sent]) -> Vec<Duration> {
    query_rounds(packets)
}

// RFC 6762 section 5.2: one second between the first two queries, then at least double each
// time. Retries used to come every second for the life of the query.
#[test]
fn test_query_intervals_double() {
    let base = Instant::now();
    let mut conn = Mdns::new(base, config().without_query_timeout());
    let id = conn.query_now(base, UUID_1);
    let out = run(&mut conn, base, ms(0), ms(130_000));
    let seconds: Vec<u64> = query_times(&out).iter().map(|t| t.as_secs()).collect();
    assert_eq!(seconds, vec![0, 1, 3, 7, 15, 31, 63, 127]);
    assert!(conn.is_query_pending(id));
}

// RFC 6762 section 5.2: the interval may stop growing at 60 minutes.
#[test]
fn test_query_interval_stops_growing_at_an_hour() {
    let base = Instant::now();
    let mut conn = Mdns::new(
        base,
        config()
            .without_query_timeout()
            .with_query_interval(Duration::from_secs(40 * 60)),
    );
    conn.query_now(base, UUID_1);
    let out = run(&mut conn, base, ms(0), Duration::from_secs(4 * 3600));
    let minutes: Vec<u64> = query_times(&out).iter().map(|t| t.as_secs() / 60).collect();
    assert_eq!(minutes, vec![0, 40, 100, 160, 220]);
}

// RFC 6762 section 5.2: at least one second between the first two queries, whatever is asked
// for.
#[test]
fn test_first_retry_is_no_sooner_than_a_second() {
    let base = Instant::now();
    let mut conn = Mdns::new(base, config().with_query_interval(ms(100)));
    conn.query_now(base, UUID_1);
    assert_eq!(query_rounds(&sent(&mut conn, base)), vec![ms(0)]);
    assert_eq!(conn.poll_timeout(), Some(base + ms(1000)));
    let out = run(&mut conn, base, ms(0), ms(1000));
    assert_eq!(query_times(&out), vec![ms(1000)]);
}

// A query nobody answers ends by itself: it used to be retried for ever unless a timeout was
// configured.
#[test]
fn test_unanswered_query_ends_after_thirty_seconds_by_default() {
    let base = Instant::now();
    let mut conn = Mdns::new(base, config());
    let id = conn.query_now(base, UUID_1);
    let out = run(&mut conn, base, ms(0), ms(29_999));
    assert_eq!(
        query_rounds(&out),
        vec![ms(0), ms(1000), ms(3000), ms(7000), ms(15000)],
        "sent at 0, 1, 3, 7 and 15 s"
    );
    assert!(conn.is_query_pending(id));
    assert_eq!(conn.poll_timeout(), Some(base + ms(30_000)));

    let out = run(&mut conn, base, ms(29_999), ms(600_000));
    assert!(out.is_empty(), "nothing is sent for a query that ended");
    assert_eq!(ended(&mut conn), vec![id]);
    assert!(!conn.is_query_pending(id));
    assert!(conn.poll_timeout().is_none());
}

// RFC 6762 section 5.2: the first query of a series waits a random 20 to 120 ms, when the
// connection is configured to (the default sends it from the `handle_timeout` that starts it).
#[test]
fn test_scheduled_query_first_goes_out_after_20_to_120_ms() {
    let base = Instant::now();
    let mut waits = std::collections::HashSet::new();
    for seed in 0..20 {
        let delayed = MdnsConfig::default()
            .with_jitter_seed(seed)
            .with_first_query_delay(true);
        let mut conn = Mdns::new(base, delayed);
        let id = conn.schedule_query(UUID_1);
        assert!(conn.is_query_pending(id));
        assert_eq!(
            conn.poll_timeout(),
            Some(base),
            "the caller is asked for the time"
        );
        let out = run(&mut conn, base, ms(0), ms(500));
        let rounds = query_rounds(&out);
        assert_eq!(rounds.len(), 1, "{rounds:?}");
        assert!((ms(20)..=ms(120)).contains(&rounds[0]), "{:?}", rounds[0]);
        // The retry is a second after the query, not after it was scheduled.
        assert_eq!(conn.poll_timeout(), Some(base + rounds[0] + ms(1000)));
        waits.insert(rounds[0]);
    }
    assert!(waits.len() > 10, "the wait is random: {waits:?}");

    let mut conn = Mdns::new(base, config());
    conn.schedule_query(UUID_1);
    assert!(
        sent(&mut conn, base).is_empty(),
        "not before the caller gives the time"
    );
    conn.handle_timeout(base).unwrap();
    assert_eq!(
        query_rounds(&sent(&mut conn, base)),
        vec![ms(0)],
        "without the delay: at once"
    );
}

// RFC 6762 sections 5.2, 5.3, 18: a query leaves from port 5353 for the group, with ID, flags
// and record counts zero, asking for A and then AAAA, one question a message, and without the
// unicast-response bit.
#[test]
fn test_query_message_format() {
    let base = Instant::now();
    let mut conn = Mdns::new(base, config());
    conn.query_now(base, UUID_1);
    let out = run(&mut conn, base, ms(0), ms(1000));
    assert_eq!(
        out.len(),
        4,
        "the query and its first retry, two messages each"
    );
    let mut asked: Vec<(u16, u16, bool)> = Vec::new();
    for packet in &out {
        assert_eq!(packet.from, "0.0.0.0:5353".parse().unwrap());
        assert_eq!(packet.to, MDNS_DEST_ADDR);
        // ID 0; QR, OPCODE, AA, TC, RD, RA, Z, AD, CD, RCODE all 0; one question, no records.
        assert_eq!(&packet.raw[..12], &[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0]);
        assert_eq!(packet.msg.questions.len(), 1);
        let q = &packet.msg.questions[0];
        assert_eq!(q.name, format!("{UUID_1}."));
        asked.push((q.typ, q.class, q.unicast));
    }
    let round = [(TYPE_A, CLASS_IN, false), (TYPE_AAAA, CLASS_IN, false)];
    assert_eq!(asked, [round, round].concat());
    assert_eq!(query_rounds(&out), vec![ms(0), ms(1000)]);
}

// draft-ietf-mmusic-mdns-ice-candidates section 3.2.1, RFC 6762 section 5.4: when asked to,
// the first query of a series sets the unicast-response bit; a retry never does.
#[test]
fn test_unicast_response_bit_is_set_on_the_first_query_only() {
    let base = Instant::now();
    let mut conn = Mdns::new(base, config().with_unicast_response(true));
    conn.query_now(base, UUID_1);
    let out = run(&mut conn, base, ms(0), ms(3000));
    assert_eq!(query_rounds(&out), vec![ms(0), ms(1000), ms(3000)]);
    let unicast: Vec<Vec<bool>> = out
        .iter()
        .map(|p| p.msg.questions.iter().map(|q| q.unicast).collect())
        .collect();
    assert_eq!(
        unicast,
        vec![
            vec![true],
            vec![true],
            vec![false],
            vec![false],
            vec![false],
            vec![false]
        ],
        "both questions of the first round, each in its message"
    );
    // The bit is the top bit of the class field, which stays IN.
    for packet in &out[..2] {
        assert_eq!(&packet.raw[packet.raw.len() - 2..], &[0x80, 0x01]);
    }
}

// RFC 6762 section 6: a unicast response is taken only for a question that asked for one
// within the last two seconds.
#[test]
fn test_unicast_response_is_taken_only_for_a_recent_unicast_question() {
    let base = Instant::now();
    let own: SocketAddr = "192.168.1.30:5353".parse().unwrap();
    let answer = response(&[addr(UUID_1, OWNER)]);

    let (mut conn, id) = asking(base, config().with_unicast_response(true));
    deliver_to(&mut conn, base + ms(500), OWNER_SRC, own, &answer);
    assert_eq!(answered(&mut conn), vec![(id, ip(OWNER))]);

    // More than two seconds after the question that asked for it.
    let (mut conn, id) = asking(base, config().with_unicast_response(true));
    run(&mut conn, base, ms(0), ms(2500));
    deliver_to(&mut conn, base + ms(2500), OWNER_SRC, own, &answer);
    assert!(answered(&mut conn).is_empty());
    assert!(conn.is_query_pending(id));
    // The same response on the group is taken.
    deliver(&mut conn, base + ms(2500), OWNER_SRC, &answer);
    assert_eq!(answered(&mut conn), vec![(id, ip(OWNER))]);

    // A caller that does not report destinations has every datagram taken as a multicast
    // arrival, whatever `local_addr` says (a socket's bound address, usually).
    let (mut conn, id) = asking(base, MdnsConfig::default());
    deliver_to(&mut conn, base + ms(500), OWNER_SRC, own, &answer);
    assert_eq!(answered(&mut conn), vec![(id, ip(OWNER))]);

    // A question that did not ask for a unicast response does not get one.
    let (mut conn, id) = asking(base, config());
    deliver_to(&mut conn, base + ms(500), OWNER_SRC, own, &answer);
    assert!(answered(&mut conn).is_empty());
    assert!(conn.is_query_pending(id));
    // Nor is what it carried kept for later.
    conn.cancel_query(id);
    let again = conn.query_now(base + ms(600), UUID_1);
    assert!(conn.is_query_pending(again));
}

// RFC 6762 section 6: a response from another source port is ignored.
#[test]
fn test_response_from_another_port_does_not_resolve() {
    let answer = response(&[addr(UUID_1, OWNER)]);
    assert!(resolves(&answer, OWNER_SRC));
    assert!(!resolves(&answer, "192.168.1.50:40000"));
}

// RFC 6762 sections 18.3, 18.11: a response with another OPCODE, or an RCODE, is ignored.
#[test]
fn test_response_with_another_opcode_or_an_rcode_does_not_resolve() {
    let with_flags = |flags: u16| message(0, flags, &[], &[addr(UUID_1, OWNER)], &[], &[]);
    assert!(resolves(&with_flags(RESPONSE), OWNER_SRC));
    assert!(
        !resolves(&with_flags(RESPONSE | 0x0003), OWNER_SRC),
        "RCODE 3"
    );
    assert!(
        !resolves(&with_flags(RESPONSE | 0x2800), OWNER_SRC),
        "OPCODE 5"
    );
    // The bits a receiver must ignore (AA clear; TC, RD, RA, Z, AD, CD set) change nothing,
    // and neither does the ID.
    assert!(resolves(&with_flags(0x8000 | 0x03F0), OWNER_SRC));
    let with_id = message(0xBEEF, RESPONSE, &[], &[addr(UUID_1, OWNER)], &[], &[]);
    assert!(resolves(&with_id, OWNER_SRC));
}

// RFC 6762 section 6.1: a record that is not understood must not hide the rest of the
// message. A TXT or NSEC record ahead of the address record used to end the scan.
#[test]
fn test_address_record_after_records_of_other_types_resolves() {
    let answer = response(&[
        other(UUID_1, TYPE_TXT, b"\x03abc"),
        // An NSEC record that is not in the restricted form.
        other(UUID_1, TYPE_NSEC, &[0xff, 0xff, 0xff]),
        // An unknown type.
        other(UUID_1, 65, &[1, 2, 3, 4]),
        addr(UUID_1, OWNER),
    ]);
    assert!(resolves(&answer, OWNER_SRC));
}

// RFC 6762 sections 6.4, 18.1: a responder aggregates. Only the first four Answer records used
// to be read, and the Additional section never.
#[test]
fn test_address_record_beyond_the_fourth_and_in_the_additional_section_resolves() {
    let mut answers: Vec<Rec> = (1..=9)
        .map(|i| addr(&format!("other-{i}.local"), OWNER))
        .collect();
    answers.push(addr(UUID_1, OWNER));
    assert!(resolves(&response(&answers), OWNER_SRC));

    let additional = message(
        0,
        RESPONSE,
        &[],
        &[addr("other.local", OWNER)],
        &[],
        &[addr(UUID_1, OWNER)],
    );
    assert!(resolves(&additional, OWNER_SRC));
    // The Authority section of a response answers nothing.
    let authority = message(0, RESPONSE, &[], &[], &[addr(UUID_1, OWNER)], &[]);
    assert!(!resolves(&authority, OWNER_SRC));
}

// RFC 6762 section 16, RFC 1035 section 2.3.3: a responder answers in its own spelling.
#[test]
fn test_answer_in_another_case_resolves() {
    let base = Instant::now();
    let mut conn = Mdns::new(base, config());
    let id = conn.query_now(base, &UUID_1.to_ascii_uppercase());
    deliver(
        &mut conn,
        base,
        OWNER_SRC,
        &response(&[addr(UUID_1, OWNER)]),
    );
    assert_eq!(answered(&mut conn), vec![(id, ip(OWNER))]);
}

// RFC 6762 section 16: names are UTF-8. A record whose name is not is stepped over, and what
// follows it is read.
#[test]
fn test_record_with_a_name_that_is_not_utf8_is_stepped_over() {
    let mut bytes = message(0, RESPONSE, &[], &[addr("xx.local", OWNER)], &[], &[]);
    // The first label of the first record: two bytes that are not UTF-8.
    assert_eq!(&bytes[12..15], &[2, b'x', b'x']);
    bytes[13] = 0xff;
    bytes[14] = 0xfe;
    let rest = message(0, RESPONSE, &[], &[addr(UUID_1, OWNER)], &[], &[]);
    bytes.extend_from_slice(&rest[12..]);
    bytes[7] = 2;
    assert!(resolves(&bytes, OWNER_SRC));
}

// RFC 6762 section 17: no mDNS message is over 9000 bytes.
#[test]
fn test_datagram_over_9000_bytes_is_ignored() {
    let mut answer = response(&[addr(UUID_1, OWNER)]);
    answer.resize(9000, 0);
    assert!(resolves(&answer, OWNER_SRC));
    answer.resize(9001, 0);
    assert!(!resolves(&answer, OWNER_SRC));
}

// draft-ietf-mmusic-mdns-ice-candidates section 3.2.2: a name with more than one address is
// not resolved. The first record used to win.
#[test]
fn test_name_with_two_addresses_does_not_resolve() {
    let base = Instant::now();
    let both = response(&[addr(UUID_1, OWNER), addr(UUID_1, "fe80::50")]);

    let (mut conn, id) = asking(base, config());
    deliver(&mut conn, base, OWNER_SRC, &both);
    let events = events(&mut conn);
    assert!(
        matches!(&events[..], [MdnsEvent::QueryTimeout(ended)] if *ended == id),
        "{events:?}"
    );
    assert!(!conn.is_query_pending(id));
    assert!(conn.poll_timeout().is_none(), "the query is over");

    // The same address twice is one address.
    let (mut conn, id) = asking(base, config());
    let twice = response(&[addr(UUID_1, OWNER), addr(UUID_1, OWNER)]);
    deliver(&mut conn, base, OWNER_SRC, &twice);
    assert_eq!(answered(&mut conn), vec![(id, ip(OWNER))]);

    // A resolver that is not an ICE agent's may take the first.
    let (mut conn, id) = asking(base, config().with_multiple_addresses(true));
    deliver(&mut conn, base, OWNER_SRC, &both);
    assert_eq!(answered(&mut conn), vec![(id, ip(OWNER))]);
}

// RFC 6762 section 6.1: the restricted-form NSEC record is read. A name whose owner says it
// has neither an A nor an AAAA record resolves to nothing, at once.
#[test]
fn test_nsec_saying_the_name_has_no_address_ends_the_query() {
    let base = Instant::now();
    let nsec = |bitmap: &[u8]| {
        let mut rdata = wire_name(UUID_1);
        rdata.push(0);
        rdata.push(bitmap.len() as u8);
        rdata.extend_from_slice(bitmap);
        response(&[other(UUID_1, TYPE_NSEC, &rdata)])
    };

    // Only a TXT record (type 16) exists.
    let (mut conn, id) = asking(base, config());
    deliver(&mut conn, base, OWNER_SRC, &nsec(&[0, 0, 0x80]));
    assert_eq!(ended(&mut conn), vec![id]);
    assert!(!conn.is_query_pending(id));

    // An A record exists (and no AAAA): the query waits for it.
    let (mut conn, id) = asking(base, config());
    deliver(&mut conn, base, OWNER_SRC, &nsec(&[0x40]));
    assert!(events(&mut conn).is_empty());
    assert!(conn.is_query_pending(id));

    // Not from off the link (the destination unknown, so the source's scope decides; one that
    // arrived at the group is on the link whatever its source, RFC 6762 section 11).
    let (mut conn, id) = asking(base, config());
    deliver_to(
        &mut conn,
        base,
        "203.0.113.9:5353",
        UNKNOWN,
        &nsec(&[0, 0, 0x80]),
    );
    assert!(conn.is_query_pending(id));
}

/// A datagram's destination the driver does not know (a socket bound to the unspecified
/// address): the on-link test is then the source's (RFC 6762 section 11's second test).
const UNKNOWN: SocketAddr = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), MDNS_PORT);

// RFC 6762 section 11: with the link's subnets configured, they decide who is on the link
// (for a response whose destination is not the group: one that arrived there is on the link
// whatever its source).
#[test]
fn test_configured_subnets_decide_who_is_on_the_link() {
    let base = Instant::now();
    let subnets = vec![(ip("203.0.113.0"), 24), (ip("fe80::"), 10)];
    let public = response(&[addr(UUID_1, "203.0.113.9")]);

    let (mut conn, id) = asking(base, config().with_on_link_subnets(subnets.clone()));
    deliver(&mut conn, base, "203.0.113.9:5353", &public);
    assert_eq!(answered(&mut conn), vec![(id, ip("203.0.113.9"))]);

    // A private address that is not in a configured subnet is not on this link.
    let (mut conn, id) = asking(base, config().with_on_link_subnets(subnets.clone()));
    deliver_to(
        &mut conn,
        base,
        OWNER_SRC,
        UNKNOWN,
        &response(&[addr(UUID_1, OWNER)]),
    );
    assert!(answered(&mut conn).is_empty());
    let aaaa = response(&[addr(UUID_1, "2001:db8::7")]);
    deliver_to(&mut conn, base, OWNER_SRC, UNKNOWN, &aaaa);
    assert!(answered(&mut conn).is_empty());
    deliver_to(&mut conn, base, "[fe80::7]:5353", UNKNOWN, &aaaa);
    assert_eq!(answered(&mut conn), vec![(id, ip("2001:db8::7"))]);

    // Without subnets, the address scope decides: a public IPv4 sender is refused.
    let (mut conn, id) = asking(base, config());
    deliver_to(&mut conn, base, "203.0.113.9:5353", UNKNOWN, &public);
    assert!(conn.is_query_pending(id));
}

// RFC 6762 sections 5.2, 18.1: an address heard in a response is cached, so a name announced
// by its owner, or resolved before, answers without a query.
#[test]
fn test_announced_name_resolves_from_the_cache_without_a_query() {
    let base = Instant::now();
    let mut conn = Mdns::new(base, config());
    deliver(
        &mut conn,
        base,
        OWNER_SRC,
        &response(&[addr(UUID_1, OWNER)]),
    );
    assert!(events(&mut conn).is_empty());

    let id = conn.query_now(base + ms(5000), UUID_1);
    assert_eq!(answered(&mut conn), vec![(id, ip(OWNER))]);
    assert!(!conn.is_query_pending(id));
    assert!(sent(&mut conn, base).is_empty(), "no query goes out");

    let id = conn.schedule_query(&UUID_1.to_ascii_uppercase());
    let out = run(&mut conn, base, ms(6000), ms(7000));
    assert!(out.is_empty());
    assert_eq!(answered(&mut conn), vec![(id, ip(OWNER))]);
}

// RFC 6762 section 5.2: a cached record is gone when its TTL is over.
#[test]
fn test_cached_address_expires_at_its_ttl() {
    let base = Instant::now();
    let mut conn = Mdns::new(base, config());
    deliver(
        &mut conn,
        base,
        OWNER_SRC,
        &response(&[addr(UUID_1, OWNER).ttl(120)]),
    );
    // Nobody asks for the name: the record is not kept alive with queries of our own.
    assert!(conn.poll_timeout().is_none());
    let id = conn.query_now(base + ms(119_999), UUID_1);
    assert_eq!(answered(&mut conn), vec![(id, ip(OWNER))]);

    let id = conn.query_now(base + ms(120_000), UUID_1);
    assert!(conn.is_query_pending(id), "the record has expired");
    assert_eq!(
        query_rounds(&sent(&mut conn, base)),
        vec![ms(120_000)],
        "so the name is asked for"
    );
}

// RFC 6762 section 10.1: a goodbye is acted on a second later, not at once; and it resolves
// nothing.
#[test]
fn test_goodbye_leaves_the_cache_a_second_later() {
    let base = Instant::now();
    let mut conn = Mdns::new(base, config());
    deliver(
        &mut conn,
        base,
        OWNER_SRC,
        &response(&[addr(UUID_1, OWNER)]),
    );
    let goodbye = response(&[addr(UUID_1, OWNER).ttl(0)]);
    deliver(&mut conn, base + ms(10_000), OWNER_SRC, &goodbye);

    let id = conn.query_now(base + ms(10_900), UUID_1);
    assert_eq!(answered(&mut conn), vec![(id, ip(OWNER))], "still there");
    let id = conn.query_now(base + ms(11_000), UUID_1);
    assert!(conn.is_query_pending(id), "gone a second after the goodbye");
    deliver(&mut conn, base + ms(11_000), OWNER_SRC, &goodbye);
    assert!(conn.is_query_pending(id));
    assert!(events(&mut conn).is_empty());
}

// RFC 6762 section 10.2: a record with the cache-flush bit replaces what was heard for its
// name and type more than a second ago; one without it is added.
#[test]
fn test_cache_flush_record_replaces_older_addresses() {
    let base = Instant::now();
    let newer = addr(UUID_1, "192.168.1.60");

    let mut conn = Mdns::new(base, config());
    deliver(
        &mut conn,
        base,
        OWNER_SRC,
        &response(&[addr(UUID_1, OWNER)]),
    );
    deliver(
        &mut conn,
        base + ms(5000),
        "192.168.1.60:5353",
        &response(std::slice::from_ref(&newer)),
    );
    let id = conn.query_now(base + ms(6001), UUID_1);
    assert_eq!(answered(&mut conn), vec![(id, ip("192.168.1.60"))]);

    // Without the bit both stay, and a name with two addresses does not resolve.
    let mut conn = Mdns::new(base, config());
    deliver(
        &mut conn,
        base,
        OWNER_SRC,
        &response(&[addr(UUID_1, OWNER)]),
    );
    deliver(
        &mut conn,
        base + ms(5000),
        "192.168.1.60:5353",
        &response(&[newer.class(CLASS_IN)]),
    );
    let id = conn.query_now(base + ms(6001), UUID_1);
    assert_eq!(ended(&mut conn), vec![id]);
}

// Flood control: any host on the link can offer records, so the cache has a fixed size.
#[test]
fn test_cache_is_bounded() {
    let base = Instant::now();
    let mut conn = Mdns::new(base, config());
    for batch in 0..10 {
        let records: Vec<Rec> = (0..50)
            .map(|i| addr(&format!("flood-{batch}-{i}.local"), "fe80::bad").ttl(100))
            .collect();
        deliver(&mut conn, base, "192.168.1.66:5353", &response(&records));
    }
    assert_eq!(conn.cache.len(), MAX_CACHED_ADDRESSES);

    // A record that lives longer than the one nearest its expiry takes its place; one that
    // does not is not taken.
    deliver(
        &mut conn,
        base,
        OWNER_SRC,
        &response(&[addr("short.local", OWNER).ttl(50)]),
    );
    deliver(
        &mut conn,
        base,
        OWNER_SRC,
        &response(&[addr(UUID_1, OWNER)]),
    );
    assert_eq!(conn.cache.len(), MAX_CACHED_ADDRESSES);
    let id = conn.query_now(base, "short.local");
    assert!(conn.is_query_pending(id));
    let id = conn.query_now(base, UUID_1);
    assert_eq!(answered(&mut conn), vec![(id, ip(OWNER))]);

    // Expired entries make room.
    conn.handle_timeout(base + Duration::from_secs(200))
        .unwrap();
    assert!(conn.cache.is_empty());
}

// RFC 6762 section 7.1: the Known-Answer section of another host's query is not cached.
#[test]
fn test_known_answers_of_a_query_are_not_cached() {
    let base = Instant::now();
    let mut conn = Mdns::new(base, config());
    let query = message(
        0,
        QUERY,
        &[(UUID_1, TYPE_A, CLASS_IN)],
        &[addr(UUID_1, OWNER)],
        &[],
        &[],
    );
    deliver(&mut conn, base, OWNER_SRC, &query);
    let id = conn.query_now(base, UUID_1);
    assert!(conn.is_query_pending(id));
    assert_eq!(query_rounds(&sent(&mut conn, base)), vec![ms(0)]);
}

// RFC 6762 section 7.3: the same question, multicast by another host, counts as ours sent.
#[test]
fn test_question_seen_from_another_host_counts_as_sent() {
    let base = Instant::now();
    let (mut conn, id) = asking(base, config().without_query_timeout());
    deliver(
        &mut conn,
        base + ms(500),
        "192.168.1.31:5353",
        &query_for(UUID_1),
    );
    assert!(sent(&mut conn, base).is_empty(), "we do not own the name");
    let out = run(&mut conn, base, ms(500), ms(6499));
    assert_eq!(
        query_times(&out),
        vec![ms(2500)],
        "the retry due at 1 s is not sent; the next comes two seconds after the question seen"
    );
    assert!(conn.is_query_pending(id));
}

#[test]
fn test_question_that_does_not_stand_for_ours_changes_nothing() {
    let base = Instant::now();
    let other_host = "192.168.1.31:5353";
    let retry_at = |bytes: &[u8], from: &str, after: Duration, config: MdnsConfig| {
        let (mut conn, _) = asking(base, config.without_query_timeout());
        deliver(&mut conn, base + after, from, bytes);
        let out = run(&mut conn, base, after, ms(1500));
        query_times(&out)
    };
    let on_time = vec![ms(1000)];

    // One that asks for a unicast response: its answer goes to the asker alone.
    let qu = message(
        0,
        QUERY,
        &[
            (UUID_1, TYPE_A, CLASS_IN | CLASS_TOP_BIT),
            (UUID_1, TYPE_AAAA, CLASS_IN | CLASS_TOP_BIT),
        ],
        &[],
        &[],
        &[],
    );
    assert_eq!(retry_at(&qu, other_host, ms(500), config()), on_time);

    // One whose known answers would keep the answer from us.
    let knowing = message(
        0,
        QUERY,
        &[(UUID_1, TYPE_A, CLASS_IN), (UUID_1, TYPE_AAAA, CLASS_IN)],
        &[addr(UUID_1, OWNER).class(CLASS_IN)],
        &[],
        &[],
    );
    assert_eq!(retry_at(&knowing, other_host, ms(500), config()), on_time);

    // One from off the link.
    assert_eq!(
        retry_at(&query_for(UUID_1), "203.0.113.5:5353", ms(500), config()),
        on_time
    );

    // Half of ours.
    let only_a = message(0, QUERY, &[(UUID_1, TYPE_A, CLASS_IN)], &[], &[], &[]);
    assert_eq!(retry_at(&only_a, other_host, ms(500), config()), on_time);

    // Our own, handed back by the link right after it went out, or coming from an address
    // of ours.
    let ours = query_for(UUID_1);
    assert_eq!(retry_at(&ours, other_host, ms(50), config()), on_time);
    let with_address = config()
        .with_local_names(vec![UUID_2.to_owned()])
        .with_local_ip(ip("192.168.1.31"));
    let out = retry_at(&ours, other_host, ms(500), with_address);
    assert!(out.contains(&ms(1000)), "{out:?}");
}

// RFC 6762 section 10.3: what was learned on another link is not carried over.
#[test]
fn test_network_change_empties_the_cache() {
    let base = Instant::now();
    let mut conn = Mdns::new(base, config());
    deliver(
        &mut conn,
        base,
        OWNER_SRC,
        &response(&[addr(UUID_1, OWNER)]),
    );
    conn.network_changed();
    let id = conn.query_now(base, UUID_1);
    assert!(conn.is_query_pending(id));
    assert_eq!(query_rounds(&sent(&mut conn, base)), vec![ms(0)]);
}

/// One query for `UUID_1` between two hosts in virtual time, a millisecond at a time: this
/// host's resolver (QU bit `qu`) and the owner of the name, a responder that answers a question
/// about its unique name at once, by unicast when the question asks for it and the record was
/// multicast within a quarter of its TTL (RFC 6762 sections 5.4, 6), as `Mdns` does with the
/// multi-question delay off. Multicast reaches both sockets; a unicast datagram to this host's
/// port 5353 reaches this resolver only when its socket is the `first` bound to the port,
/// else another responder of the host takes it (RFC 6762 section 15.1). Returns the time from
/// the first query on the wire to the answer.
fn resolution_time(qu: bool, first: bool) -> Duration {
    let base = Instant::now();
    let own = "192.168.1.30";
    let own_src = "192.168.1.30:5353";
    let mut owner = Mdns::new(
        base,
        MdnsConfig::default()
            .with_jitter_seed(2)
            .with_multi_question_delay(false),
    );
    assert!(owner.add_local_name(UUID_1, ip(OWNER)));
    // The owner probes for nothing (a random name) and announces at 0 s and 1 s.
    let _ = run(&mut owner, base, ms(0), ms(5_000));
    let mut resolver = Mdns::new(base, config().with_unicast_response(qu));
    let start = base + ms(5_000);
    let id = resolver.query_now(start, UUID_1);
    let datagram = |now: Instant, from: &str, bytes: BytesMut| TaggedBytesMut {
        now,
        transport: TransportContext {
            local_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), MDNS_PORT),
            peer_addr: from.parse().unwrap(),
            transport_protocol: TransportProtocol::UDP,
            ecn: None,
        },
        message: bytes,
    };
    let mut first_query = None;
    let mut unicast_lost = 0;
    let mut unicast_delivered = 0;
    for step in 0..3_000u64 {
        let now = start + ms(step);
        resolver.handle_timeout(now).unwrap();
        owner.handle_timeout(now).unwrap();
        while let Some(packet) = resolver.poll_write() {
            assert_eq!(
                packet.transport.peer_addr, MDNS_DEST_ADDR,
                "queries go to the group"
            );
            first_query.get_or_insert(now);
            owner
                .handle_datagram(datagram(now, own_src, packet.message), ip("224.0.0.251"))
                .unwrap();
        }
        while let Some(packet) = owner.poll_write() {
            if packet.transport.peer_addr == MDNS_DEST_ADDR {
                resolver
                    .handle_datagram(datagram(now, OWNER_SRC, packet.message), ip("224.0.0.251"))
                    .unwrap();
            } else if first {
                assert_eq!(packet.transport.peer_addr, own_src.parse().unwrap());
                unicast_delivered += 1;
                resolver
                    .handle_datagram(datagram(now, OWNER_SRC, packet.message), ip(own))
                    .unwrap();
            } else {
                unicast_lost += 1;
            }
        }
        if answered(&mut resolver)
            .iter()
            .any(|(q, a)| *q == id && *a == ip(OWNER))
        {
            let first_query = first_query.expect("a query went out");
            assert_eq!(
                unicast_lost > 0,
                qu && !first,
                "a unicast answer is lost exactly when QU is asked beside another socket"
            );
            assert_eq!(
                unicast_delivered > 0,
                qu && first,
                "the owner answers by unicast exactly when QU is asked"
            );
            return now - first_query;
        }
    }
    panic!("not resolved in 3 s (qu {qu}, first {first})");
}

/// RFC 6762 section 15.1, measured: "'QU' responses and other packets sent via unicast will be
/// received only by the first Multicast DNS responder and/or querier on a system". With the QU
/// bit (draft-ietf-mmusic-mdns-ice-candidates 3.2.1, `with_unicast_response(true)`) and another
/// responder holding port 5353 first, the owner's unicast answer goes to that responder and the
/// name resolves at the first retry, a second later (retries never ask QU); without the bit
/// the multicast answer resolves it at once; with the bit and this socket first, at once too.
#[test]
fn the_unicast_response_bit_costs_a_second_when_another_socket_holds_the_port() {
    let qu_beside_another = resolution_time(true, false);
    let qm = resolution_time(false, false);
    let qu_first = resolution_time(true, true);
    println!(
        "MEASURED mdns-qu: QU beside another responder {qu_beside_another:?}, QM {qm:?}, QU with the socket first {qu_first:?}"
    );
    assert!(qm <= ms(5), "QM resolves at once: {qm:?}");
    assert!(
        qu_first <= ms(5),
        "QU with the socket first resolves at once: {qu_first:?}"
    );
    assert!(
        (ms(1_000)..=ms(1_100)).contains(&qu_beside_another),
        "QU beside another responder waits for the retry: {qu_beside_another:?}"
    );
}

/// The query packets for `name` among `packets`: (when, type, class with its top bit).
fn questions_for(packets: &[Sent], name: &str) -> Vec<(Duration, u16, u16)> {
    let name = format!("{name}.");
    packets
        .iter()
        .filter(|p| !p.is_response())
        .flat_map(|p| {
            p.msg.questions.iter().filter(|q| q.name == name).map(|q| {
                let top = if q.unicast { CLASS_TOP_BIT } else { 0 };
                (p.at, q.typ, q.class | top)
            })
        })
        .collect()
}

// RFC 6762 section 5.3: several questions in one message mean no more than one message per
// question, and Chromium's mDNS responder drops a query whose QDCOUNT is not 1 (chromium/src
// net/dns/dns_query.cc `DnsQuery::Parse`). Every query message carries one question: the A and
// the AAAA question of a name go in messages of their own, on the first round and on every
// retry, for one name and for several due together (the retries used to share a message).
#[test]
fn test_every_query_message_carries_one_question_for_one_name_and_for_several() {
    let base = Instant::now();
    for unicast in [false, true] {
        let mut conn = Mdns::new(
            base,
            config()
                .without_query_timeout()
                .with_unicast_response(unicast),
        );
        let names = [UUID_1, UUID_2, "aaaaaaaa-0000-4000-8000-000000000003.local"];
        for name in names {
            conn.schedule_query(name);
        }
        let out = run(&mut conn, base, ms(0), ms(7_000));
        assert!(!out.is_empty(), "the queries went out");
        for packet in &out {
            assert!(!packet.is_response());
            assert_eq!(packet.msg.questions.len(), 1, "one question a message");
            assert_eq!(&packet.raw[4..6], &[0, 1], "QDCOUNT 1");
        }
        let rounds = [ms(0), ms(1_000), ms(3_000), ms(7_000)];
        assert_eq!(
            query_rounds(&out),
            rounds.iter().flat_map(|&t| [t; 3]).collect::<Vec<_>>(),
            "three names, a round each at 0, 1, 3 and 7 s"
        );
        let qu = CLASS_IN | CLASS_TOP_BIT;
        for name in names {
            let mut expected = Vec::new();
            for (i, &at) in rounds.iter().enumerate() {
                // The first round asks for a unicast response when configured to; a retry
                // never does (RFC 6762 section 5.4).
                let class = if unicast && i == 0 { qu } else { CLASS_IN };
                expected.push((at, TYPE_A, class));
                expected.push((at, TYPE_AAAA, class));
            }
            assert_eq!(questions_for(&out, name), expected, "{name}, QU {unicast}");
        }
    }
}

// The message budget may let the A question of a round go and hold its AAAA question: the
// AAAA question goes out as soon as the budget allows, the A question is not asked twice, and
// the series (RFC 6762 section 5.2) moves on from the round's last message.
#[test]
fn test_an_aaaa_question_the_budget_holds_back_goes_out_before_the_series_moves_on() {
    let base = Instant::now();
    let limit = MdnsRateLimit::new(1, 1);
    let mut conn = Mdns::new(
        base,
        config().without_query_timeout().with_rate_limit(limit),
    );
    conn.query_now(base, UUID_1);
    let first = sent(&mut conn, base);
    assert_eq!(
        questions_for(&first, UUID_1),
        vec![(ms(0), TYPE_A, CLASS_IN)]
    );
    assert_eq!(
        conn.poll_timeout(),
        Some(base + ms(1_000)),
        "waits for the budget"
    );
    let out = run(&mut conn, base, ms(0), ms(4_500));
    assert!(out.iter().all(|p| p.msg.questions.len() == 1));
    assert_eq!(
        questions_for(&out, UUID_1),
        vec![
            (ms(1_000), TYPE_AAAA, CLASS_IN),
            (ms(2_000), TYPE_A, CLASS_IN),
            (ms(3_000), TYPE_AAAA, CLASS_IN),
        ],
        "the round of 0 s ends at 1 s, its retry is due a second later and ends at 3 s"
    );
    assert_eq!(
        conn.poll_timeout(),
        Some(base + ms(5_000)),
        "then two seconds"
    );
}

/// Whether a responder that parses a query as Chromium's does would take `message`
/// (chromium/src 8dafa8bc `services/network/mdns_responder.cc` passes every datagram to
/// `DnsQuery::Parse`, which in `net/dns/dns_query.cc` refuses a QDCOUNT other than 1 and a
/// QCLASS other than IN, so a set unicast-response bit too).
fn chromium_takes(message: &[u8]) -> bool {
    let Some(msg) = wire::parse(message) else {
        return false;
    };
    message.get(4..6) == Some(&[0, 1][..])
        && msg.questions.len() == 1
        && msg.questions[0].class == CLASS_IN
        && !msg.questions[0].unicast
}

/// What a resolver with `config`, asking for each of `names`, saw from a responder that owns
/// them at `OWNER` and takes queries as [`chromium_takes`] says, answering by multicast only
/// (as Chromium's does). The responder hears nothing before `deaf_until`.
struct AgainstChromium {
    /// When each name resolved, from the resolver's first `handle_timeout`.
    resolved: Vec<Option<Duration>>,
    /// Query messages the responder refused by the Chromium rule.
    refused: usize,
    /// Query messages it took.
    taken: usize,
}

fn against_chromium_like_responder(
    config: MdnsConfig,
    names: &[&str],
    deaf_until: Duration,
) -> AgainstChromium {
    let base = Instant::now();
    let own_src = "192.168.1.30:5353";
    let mut owner = Mdns::new(
        base,
        MdnsConfig::default()
            .with_jitter_seed(2)
            .with_unicast_replies(false),
    );
    for name in names {
        assert!(owner.add_local_name(name, ip(OWNER)));
    }
    // The owner announces at 0 s and 1 s, which the resolver does not hear.
    let _ = run(&mut owner, base, ms(0), ms(5_000));
    let start = base + ms(5_000);
    let mut resolver = Mdns::new(base, config);
    let ids: Vec<QueryId> = names.iter().map(|n| resolver.schedule_query(n)).collect();
    let datagram = |now: Instant, from: &str, bytes: BytesMut| TaggedBytesMut {
        now,
        transport: TransportContext {
            local_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), MDNS_PORT),
            peer_addr: from.parse().unwrap(),
            transport_protocol: TransportProtocol::UDP,
            ecn: None,
        },
        message: bytes,
    };
    let mut seen = AgainstChromium {
        resolved: vec![None; names.len()],
        refused: 0,
        taken: 0,
    };
    for step in 0..3_000u64 {
        let now = start + ms(step);
        resolver.handle_timeout(now).unwrap();
        owner.handle_timeout(now).unwrap();
        while let Some(packet) = resolver.poll_write() {
            assert_eq!(packet.transport.peer_addr, MDNS_DEST_ADDR);
            if ms(step) < deaf_until {
                continue;
            }
            if !chromium_takes(&packet.message) {
                seen.refused += 1;
                continue;
            }
            seen.taken += 1;
            owner
                .handle_datagram(datagram(now, own_src, packet.message), ip("224.0.0.251"))
                .unwrap();
        }
        while let Some(packet) = owner.poll_write() {
            assert_eq!(
                packet.transport.peer_addr, MDNS_DEST_ADDR,
                "answered by multicast"
            );
            resolver
                .handle_datagram(datagram(now, OWNER_SRC, packet.message), ip("224.0.0.251"))
                .unwrap();
        }
        for (id, addr) in answered(&mut resolver) {
            assert_eq!(addr, ip(OWNER));
            if let Some(i) = ids.iter().position(|&q| q == id) {
                seen.resolved[i].get_or_insert(ms(step));
            }
        }
        if seen.resolved.iter().all(Option::is_some) {
            break;
        }
    }
    seen
}

// Interop with Chromium's mDNS responder, the one that answers for the `.local` names in
// Chrome's ICE candidates: it drops a query of more than one question. The resolver's names
// resolve through a responder that takes only one-question QM queries: at once on the first
// round, and through the retry round when the responder missed the first, with two names due
// together. A packed query (A and AAAA in one message, as this crate sent until mdns-2) is
// refused by it, so a resolver that packed never resolved such a name by query.
#[test]
fn test_names_resolve_through_a_responder_that_takes_one_question_a_query_only() {
    // The simulated responder is the Chromium rule: a packed query and a QU question are
    // refused, a one-question QM query is taken.
    assert!(!chromium_takes(&query_for(UUID_1)));
    assert!(chromium_takes(&message(
        0,
        QUERY,
        &[(UUID_1, TYPE_A, CLASS_IN)],
        &[],
        &[],
        &[]
    )));
    assert!(!chromium_takes(&message(
        0,
        QUERY,
        &[(UUID_1, TYPE_A, CLASS_IN | CLASS_TOP_BIT)],
        &[],
        &[],
        &[]
    )));

    let names = [UUID_1, UUID_2];
    let at_once = against_chromium_like_responder(config(), &names, ms(0));
    assert_eq!(at_once.refused, 0, "no query is refused");
    assert!(at_once.taken >= 2, "{} taken", at_once.taken);
    for resolved in &at_once.resolved {
        let resolved = resolved.expect("resolved by query");
        assert!(resolved <= ms(5), "on the first round: {resolved:?}");
    }

    let on_retry = against_chromium_like_responder(config(), &names, ms(500));
    assert_eq!(on_retry.refused, 0, "no retry is refused");
    for resolved in &on_retry.resolved {
        let resolved = resolved.expect("resolved by query");
        assert!(
            (ms(1_000)..=ms(1_005)).contains(&resolved),
            "on the retry round: {resolved:?}"
        );
    }
}

// With the unicast-response setting on (MDNSICE-3.2.1-4), Chromium's responder refuses the QU
// first round (its QCLASS is not IN) and the name resolves on the first retry, which never asks
// QU: the setting costs a second against Chrome.
#[test]
fn test_against_a_chromium_like_responder_the_unicast_response_bit_costs_a_second() {
    let seen =
        against_chromium_like_responder(config().with_unicast_response(true), &[UUID_1], ms(0));
    assert_eq!(seen.refused, 2, "the A and AAAA questions of the QU round");
    let resolved = seen.resolved[0].expect("resolved on the retry");
    assert!(
        (ms(1_000)..=ms(1_005)).contains(&resolved),
        "on the retry round: {resolved:?}"
    );
}