oscall 0.1.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
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
//! Name resolution: `net::resolve`, `net::reverse` and `net::dns`.
//!
//! Nothing here leaves the machine. The DNS client is tested against a
//! name server the test runs itself on a loopback address, which answers
//! by the name it is asked (see `zone`); the system's resolver is only
//! asked for `localhost` and for addresses.

use core::net::{IpAddr, Ipv4Addr, SocketAddr};

use oscall::ErrorKind;
use oscall::net::{self, IpVersion};

const NO_ADDR: SocketAddr = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0);

/// An address written as text.
fn ip(text: &str) -> IpAddr {
    text.parse().unwrap()
}

#[test]
fn literals() {
    let mut addrs = [NO_ADDR; 4];
    for (host, version) in [
        ("127.0.0.1", IpVersion::Any),
        ("192.0.2.200", IpVersion::V4),
        ("::1", IpVersion::Any),
        ("2001:db8::7", IpVersion::V6),
        ("::ffff:192.0.2.1", IpVersion::V6),
    ] {
        let count = net::resolve(host, 8080, version, &mut addrs).unwrap();
        assert_eq!(count, 1, "{host}");
        assert_eq!(addrs[0], SocketAddr::new(ip(host), 8080));
        #[cfg(feature = "alloc")]
        assert_eq!(
            net::resolve_vec(host, 8080, version).unwrap(),
            [SocketAddr::new(ip(host), 8080)]
        );
    }
    // An address of the other kind is not converted.
    for (host, version) in [("127.0.0.1", IpVersion::V6), ("::1", IpVersion::V4)] {
        let error = net::resolve(host, 1, version, &mut addrs).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::NotFound, "{host}");
    }
    // Nowhere to write it.
    assert_eq!(net::resolve("127.0.0.1", 1, IpVersion::Any, &mut []), Ok(0));
    assert_eq!(IpVersion::default(), IpVersion::Any);
}

#[test]
fn names_that_are_not() {
    let mut addrs = [NO_ADDR; 4];
    let long_label = format!("{}.example", "a".repeat(64));
    let long_name = format!("{}example", "abcdefg.".repeat(31));
    assert_eq!(long_name.len(), 255);
    for host in [
        "",
        ".",
        " ",
        "a b",
        "exa mple.com",
        "a..b",
        ".example.com",
        "example.com..",
        "h\u{e9}llo.example",
        "\u{4e16}\u{754c}",
        "a/b",
        "user@example.com",
        "example.com:80",
        "fe80::1%eth0",
        "[::1]",
        "a\0b",
        "a\nb",
        &long_label,
        &long_name,
    ] {
        let error = net::resolve(host, 80, IpVersion::Any, &mut addrs).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{host:?}");
        #[cfg(feature = "alloc")]
        assert_eq!(
            net::resolve_vec(host, 80, IpVersion::Any)
                .unwrap_err()
                .kind(),
            ErrorKind::InvalidInput
        );
    }
}

/// `localhost` is this machine on every system, whoever answers for it.
#[test]
#[cfg(not(target_family = "wasm"))]
fn localhost() {
    let mut addrs = [NO_ADDR; 8];
    for (version, v4, v6) in [
        (IpVersion::Any, true, true),
        (IpVersion::V4, true, false),
        (IpVersion::V6, false, true),
    ] {
        for host in ["localhost", "LOCALHOST"] {
            let count = net::resolve(host, 4321, version, &mut addrs).unwrap();
            assert!(count >= 1, "{host} {version:?}");
            for addr in &addrs[..count] {
                assert!(addr.ip().is_loopback(), "{host} {version:?}: {addr}");
                assert_eq!(addr.port(), 4321);
                assert!(if addr.is_ipv4() { v4 } else { v6 }, "{version:?}: {addr}");
            }
            #[cfg(feature = "alloc")]
            assert_eq!(
                net::resolve_vec(host, 4321, version).unwrap(),
                &addrs[..count]
            );
        }
    }
    // One address at most is asked for: one is given.
    let count = net::resolve("localhost", 1, IpVersion::Any, &mut addrs[..1]).unwrap();
    assert_eq!(count, 1);
    // The address the system prefers is one this machine answers on,
    // where the machine has that kind of address at all.
    let listener = match addrs[0] {
        SocketAddr::V4(_) => std::net::TcpListener::bind("127.0.0.1:0"),
        SocketAddr::V6(_) => std::net::TcpListener::bind("[::1]:0"),
    };
    if let Ok(listener) = listener {
        let port = listener.local_addr().unwrap().port();
        net::resolve("localhost", port, IpVersion::Any, &mut addrs[..1]).unwrap();
        std::net::TcpStream::connect(addrs[0]).unwrap();
    }
}

/// The name of the loopback address is the system's business; it has one
/// or it does not, and what comes back is a name.
#[test]
#[cfg(not(target_family = "wasm"))]
fn reverse_of_loopback() {
    use core::net::Ipv6Addr;

    let mut buf = [0u8; 256];
    #[cfg_attr(
        not(any(target_os = "linux", target_os = "fullrust")),
        allow(unused_mut)
    )]
    let mut loopbacks = vec![
        IpAddr::V4(Ipv4Addr::LOCALHOST),
        IpAddr::V6(Ipv6Addr::LOCALHOST),
    ];
    // On Linux an address `/etc/hosts` does not have is asked of the name
    // servers, which are not this test's to count on.
    #[cfg(any(target_os = "linux", target_os = "fullrust"))]
    {
        let hosts = std::fs::read_to_string("/etc/hosts").unwrap_or_default();
        loopbacks.retain(|addr| {
            hosts.lines().any(|line| {
                let line = line.split('#').next().unwrap();
                let mut words = line.split_ascii_whitespace();
                words.next().and_then(|word| word.parse().ok()) == Some(*addr)
                    && words.next().is_some()
            })
        });
    }
    for addr in loopbacks {
        match net::reverse(addr, &mut buf) {
            Ok(name) => {
                assert!(!name.is_empty() && !name.ends_with('.'), "{name:?}");
                assert!(
                    name.bytes()
                        .all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b)),
                    "{name:?}"
                );
                let len = name.len();
                // A buffer that is too small says so.
                let error = net::reverse(addr, &mut buf[..len - 1]).unwrap_err();
                assert_eq!(error.kind(), ErrorKind::BufferTooSmall, "{addr}");
            }
            // Windows names the address after the computer, when the
            // computer has a name that is a host name.
            Err(error) => {
                if !cfg!(windows) {
                    panic!("{addr}: {error}");
                }
                assert_eq!(error.kind(), ErrorKind::NotFound, "{addr}: {error}");
            }
        }
    }
    // Where there is an `/etc/hosts`, it is read: the first name of the
    // line of 127.0.0.1.
    #[cfg(any(target_os = "linux", target_os = "fullrust"))]
    if let Ok(hosts) = std::fs::read_to_string("/etc/hosts") {
        let expected = hosts.lines().find_map(|line| {
            let line = line.split('#').next().unwrap();
            let mut words = line.split_ascii_whitespace();
            (words.next() == Some("127.0.0.1"))
                .then(|| words.next())
                .flatten()
        });
        if let Some(expected) = expected {
            assert_eq!(
                net::reverse(IpAddr::V4(Ipv4Addr::LOCALHOST), &mut buf),
                Ok(expected.trim_end_matches('.'))
            );
        }
    }
}

/// What `/etc/resolv.conf` says is what the system's configuration is.
#[test]
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
fn linux_dns_config() {
    let config = net::linux::dns_config().unwrap();
    assert!(!config.servers().is_empty());
    assert!(config.servers().len() <= net::dns::MAX_SERVERS);
    match std::fs::read("/etc/resolv.conf") {
        Ok(text) => {
            let expected = net::dns::Config::from_resolv_conf(&text);
            assert_eq!(config.servers(), expected.servers());
            assert!(config.search().eq(expected.search()));
            assert_eq!(config.ndots(), expected.ndots());
            assert_eq!(config.timeout(), expected.timeout());
            assert_eq!(config.attempts(), expected.attempts());
        }
        Err(_) => assert_eq!(config.servers(), ["127.0.0.1:53".parse().unwrap()]),
    }
}

/// WebAssembly has no resolver and no sockets to ask a server with.
#[test]
#[cfg(target_family = "wasm")]
fn unsupported() {
    let mut addrs = [NO_ADDR; 2];
    let error = net::resolve("localhost", 80, IpVersion::Any, &mut addrs).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::Unsupported);
    let mut buf = [0u8; 64];
    let error = net::reverse(ip("127.0.0.1"), &mut buf).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::Unsupported);
    let config = net::dns::Config::new(&["127.0.0.1:53".parse().unwrap()]).unwrap();
    let error = config
        .resolve("example.com", 80, IpVersion::Any, &mut addrs)
        .unwrap_err();
    assert_eq!(error.kind(), ErrorKind::Unsupported);
    // An address needs nobody.
    assert_eq!(config.resolve("::1", 80, IpVersion::Any, &mut addrs), Ok(1));
}

/// The client, against a server of the test's own.
#[cfg(not(target_family = "wasm"))]
mod client {
    use std::io::{Read, Write};
    use std::net::{TcpListener, UdpSocket};
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::{Arc, Mutex};
    use std::time::{Duration, Instant};

    use core::net::Ipv6Addr;

    use oscall::net::dns::Config;

    use super::*;

    const A: u16 = 1;
    const CNAME: u16 = 5;
    const PTR: u16 = 12;
    const AAAA: u16 = 28;

    const OK: u16 = 0;
    const SERVER_FAILURE: u16 = 2;
    const NAME_ERROR: u16 = 3;
    const TRUNCATED: u16 = 0x0200;

    /// A name as it travels.
    fn wire(name: &str) -> Vec<u8> {
        let mut out = Vec::new();
        for label in name.split('.').filter(|label| !label.is_empty()) {
            out.push(label.len() as u8);
            out.extend_from_slice(label.as_bytes());
        }
        out.push(0);
        out
    }

    /// A response to `query`: its identifier and its question, `flags`
    /// (the response code, and `TRUNCATED`), and `records`, each a name,
    /// a type and data.
    fn response(
        query: &[u8],
        question_len: usize,
        flags: u16,
        records: &[(Vec<u8>, u16, Vec<u8>)],
    ) -> Vec<u8> {
        let mut msg = Vec::new();
        msg.extend_from_slice(&query[..2]);
        msg.extend_from_slice(&(0x8180 | flags).to_be_bytes());
        msg.extend_from_slice(&1u16.to_be_bytes());
        msg.extend_from_slice(&(records.len() as u16).to_be_bytes());
        msg.extend_from_slice(&[0; 4]);
        msg.extend_from_slice(&query[12..12 + question_len]);
        for (name, rtype, data) in records {
            msg.extend_from_slice(name);
            msg.extend_from_slice(&rtype.to_be_bytes());
            msg.extend_from_slice(&1u16.to_be_bytes());
            msg.extend_from_slice(&60u32.to_be_bytes());
            msg.extend_from_slice(&(data.len() as u16).to_be_bytes());
            msg.extend_from_slice(data);
        }
        msg
    }

    /// What the server sends for a question: over UDP every message of
    /// the list, over TCP the last one; an empty list is silence.
    fn zone(query: &[u8], tcp: bool, log: &Mutex<Vec<(String, u16, bool)>>) -> Vec<Vec<u8>> {
        // The question: labels, then a type and a class.
        let mut name = String::new();
        let mut at = 12;
        while let Some(&len) = query.get(at) {
            if len == 0 {
                break;
            }
            let label = &query[at + 1..at + 1 + usize::from(len)];
            name.push_str(&String::from_utf8_lossy(label).to_ascii_lowercase());
            name.push('.');
            at += 1 + usize::from(len);
        }
        let question_len = at + 1 + 4 - 12;
        let qtype = u16::from_be_bytes([query[at + 1], query[at + 2]]);
        log.lock().unwrap().push((name.clone(), qtype, tcp));

        // The name of a record: a pointer to the question's.
        let same = vec![0xc0, 12];
        let v4 = |last: u8| (same.clone(), A, vec![192, 0, 2, last]);
        let v6 = |last: u8| {
            let mut addr = Ipv6Addr::from([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]).octets();
            addr[15] = last;
            (same.clone(), AAAA, addr.to_vec())
        };
        let reply = |flags: u16, records: &[(Vec<u8>, u16, Vec<u8>)]| {
            vec![response(query, question_len, flags, records)]
        };
        let many = |count: u16| -> Vec<(Vec<u8>, u16, Vec<u8>)> {
            (0..count)
                .map(|i| (same.clone(), A, vec![198, 51, (i >> 8) as u8, i as u8]))
                .collect()
        };
        match (name.as_str(), qtype) {
            ("host.test.", A) => reply(OK, &[v4(1), v4(2)]),
            ("host.test.", AAAA) => reply(OK, &[v6(1)]),
            ("v4only.test.", A) => reply(OK, &[v4(4)]),
            ("v4only.test.", AAAA) => reply(OK, &[]),
            ("v6only.test.", A) => reply(OK, &[]),
            ("v6only.test.", AAAA) => reply(OK, &[v6(6)]),
            ("alias.test.", A) => reply(
                OK,
                &[
                    (same.clone(), CNAME, wire("middle.test")),
                    (wire("middle.test"), CNAME, wire("target.test")),
                    (wire("target.test"), A, vec![192, 0, 2, 7]),
                    (wire("elsewhere.test"), A, vec![192, 0, 2, 66]),
                ],
            ),
            ("alias.test.", AAAA) => reply(OK, &[(same.clone(), CNAME, wire("middle.test"))]),
            ("short.sub.test.", A) => reply(OK, &[v4(9)]),
            ("short.sub.test.", AAAA) => reply(OK, &[]),
            ("dotted.name.sub.test.", A) => reply(OK, &[v4(10)]),
            ("dotted.name.sub.test.", AAAA) => reply(OK, &[]),
            ("second.other.test.", A) => reply(OK, &[v4(11)]),
            ("second.other.test.", AAAA) => reply(OK, &[]),
            // More than a datagram holds: cut over UDP, whole over TCP.
            ("big.test.", A) if tcp => reply(OK, &many(40)),
            ("big.test.", A) => reply(TRUNCATED, &[]),
            ("big.test.", AAAA) => reply(OK, &[]),
            // More than the client reads without allocating.
            ("huge.test.", A) if tcp => reply(OK, &many(600)),
            ("huge.test.", A) => reply(TRUNCATED, &[]),
            ("huge.test.", AAAA) => reply(OK, &[]),
            // Cut over UDP, and nothing over TCP: the connection closes.
            ("nostream.test.", _) if tcp => Vec::new(),
            ("nostream.test.", _) => reply(TRUNCATED, &[]),
            ("failure.test.", _) => reply(SERVER_FAILURE, &[]),
            ("silent.test.", _) => Vec::new(),
            // Noise before the answer: bytes that mean nothing, the
            // answer to another identifier, to another question, a query.
            ("noisy.test.", A) => {
                let good = response(query, question_len, OK, &[v4(42)]);
                let mut other_id = good.clone();
                other_id[1] ^= 0xff;
                other_id[good.len() - 1] = 13;
                let mut other_name = good.clone();
                other_name[13] ^= 1;
                other_name[good.len() - 1] = 14;
                let mut a_query = good.clone();
                a_query[2] &= 0x7f;
                a_query[good.len() - 1] = 15;
                vec![
                    vec![0xff; 5],
                    Vec::new(),
                    vec![0; 600],
                    other_id,
                    other_name,
                    a_query,
                    good,
                ]
            }
            ("noisy.test.", AAAA) => reply(OK, &[]),
            // An answer that ends in the middle of a record.
            ("broken.test.", _) => {
                let mut msg = response(query, question_len, OK, &[v4(1), v4(2)]);
                msg.truncate(msg.len() - 3);
                vec![msg]
            }
            // One record that is not an address, in an answer that is
            // well formed.
            ("badlength.test.", A) => reply(OK, &[(same.clone(), A, vec![1, 2, 3])]),
            ("badlength.test.", AAAA) => reply(OK, &[]),
            ("1.2.0.192.in-addr.arpa.", PTR) => reply(
                OK,
                &[
                    (same.clone(), PTR, wire("host.test")),
                    (same.clone(), PTR, wire("other.test")),
                ],
            ),
            ("9.2.0.192.in-addr.arpa.", PTR) => {
                reply(OK, &[(same.clone(), PTR, wire("not a name.test"))])
            }
            ("8.2.0.192.in-addr.arpa.", PTR) => reply(OK, &[]),
            ("1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa.", PTR) => {
                reply(OK, &[(same.clone(), PTR, wire("six.test"))])
            }
            _ => reply(NAME_ERROR, &[]),
        }
    }

    /// A name server on a loopback address, on the same port for UDP and
    /// TCP, for as long as the value lives.
    struct Server {
        addr: SocketAddr,
        /// The questions it was asked: the name, the type, and whether
        /// over TCP.
        log: Arc<Mutex<Vec<(String, u16, bool)>>>,
        stop: Arc<AtomicBool>,
        threads: Vec<std::thread::JoinHandle<()>>,
    }

    impl Server {
        /// `None` where the machine has no such address (IPv6 in some
        /// containers).
        fn start(ip: IpAddr) -> Option<Self> {
            // A port that is free for both: the system picks one for TCP,
            // and UDP nearly always has it free too.
            let (listener, udp) = (0..50).find_map(|_| {
                let listener = TcpListener::bind(SocketAddr::new(ip, 0)).ok()?;
                let udp = UdpSocket::bind(listener.local_addr().ok()?).ok()?;
                Some((listener, udp))
            })?;
            let addr = listener.local_addr().unwrap();
            let log = Arc::new(Mutex::new(Vec::new()));
            let stop = Arc::new(AtomicBool::new(false));
            // Not a receive with a timeout: Windows documents the state of
            // a socket as indeterminate after one that timed out, and a
            // datagram that arrived then was seen to be lost (one question
            // of two never reached this server, on the arm64 runner).
            udp.set_nonblocking(true).unwrap();
            listener.set_nonblocking(true).unwrap();

            let datagrams = {
                let (log, stop) = (log.clone(), stop.clone());
                std::thread::spawn(move || {
                    let mut buf = [0u8; 1500];
                    while !stop.load(Ordering::Acquire) {
                        let Ok((len, from)) = udp.recv_from(&mut buf) else {
                            std::thread::sleep(Duration::from_millis(1));
                            continue;
                        };
                        if len < 17 {
                            continue;
                        }
                        for msg in zone(&buf[..len], false, &log) {
                            let _ = udp.send_to(&msg, from);
                        }
                    }
                })
            };
            let streams = {
                let (log, stop) = (log.clone(), stop.clone());
                std::thread::spawn(move || {
                    while !stop.load(Ordering::Acquire) {
                        let Ok((mut stream, _)) = listener.accept() else {
                            std::thread::sleep(Duration::from_millis(2));
                            continue;
                        };
                        stream.set_nonblocking(false).unwrap();
                        stream
                            .set_read_timeout(Some(Duration::from_secs(5)))
                            .unwrap();
                        let mut prefix = [0u8; 2];
                        if stream.read_exact(&mut prefix).is_err() {
                            continue;
                        }
                        let mut query = vec![0u8; usize::from(u16::from_be_bytes(prefix))];
                        if stream.read_exact(&mut query).is_err() || query.len() < 17 {
                            continue;
                        }
                        if let Some(msg) = zone(&query, true, &log).pop() {
                            // In two writes, so that the client reads it
                            // in pieces.
                            let mut framed = (msg.len() as u16).to_be_bytes().to_vec();
                            framed.extend_from_slice(&msg);
                            let _ = stream.write_all(&framed[..3]);
                            let _ = stream.flush();
                            std::thread::sleep(Duration::from_millis(5));
                            let _ = stream.write_all(&framed[3..]);
                        }
                    }
                })
            };
            Some(Self {
                addr,
                log,
                stop,
                threads: vec![datagrams, streams],
            })
        }

        /// A configuration that asks this server, and gives it time: the
        /// tests run on loaded machines and under emulators.
        fn config(&self) -> Config {
            Config::new(&[self.addr])
                .unwrap()
                .with_timeout(Duration::from_secs(20))
        }

        /// The questions asked since the last call.
        fn asked(&self) -> Vec<(String, u16, bool)> {
            std::mem::take(&mut *self.log.lock().unwrap())
        }
    }

    impl Drop for Server {
        fn drop(&mut self) {
            self.stop.store(true, Ordering::Release);
            for thread in self.threads.drain(..) {
                let _ = thread.join();
            }
        }
    }

    fn server() -> Server {
        Server::start(IpAddr::V4(Ipv4Addr::LOCALHOST)).expect("no server on 127.0.0.1")
    }

    fn lookup(config: &Config, host: &str, version: IpVersion) -> oscall::Result<Vec<IpAddr>> {
        let mut addrs = [NO_ADDR; 64];
        let count = config.resolve(host, 853, version, &mut addrs)?;
        assert!(addrs[..count].iter().all(|addr| addr.port() == 853));
        Ok(addrs[..count].iter().map(SocketAddr::ip).collect())
    }

    fn kind(result: oscall::Result<Vec<IpAddr>>) -> ErrorKind {
        result.unwrap_err().kind()
    }

    /// The names of the questions, in order, without their types.
    fn names(asked: &[(String, u16, bool)]) -> Vec<&str> {
        let mut names: Vec<&str> = asked.iter().map(|(name, _, _)| name.as_str()).collect();
        names.dedup();
        names
    }

    #[test]
    fn addresses() {
        let server = server();
        let config = server.config();
        // IPv6 first, each kind in the server's order.
        assert_eq!(
            lookup(&config, "host.test", IpVersion::Any).unwrap(),
            [ip("2001:db8::1"), ip("192.0.2.1"), ip("192.0.2.2")]
        );
        let mut asked = server.asked();
        asked.sort();
        assert_eq!(
            asked,
            [
                ("host.test.".to_owned(), A, false),
                ("host.test.".to_owned(), AAAA, false)
            ]
        );
        // One kind is one question.
        assert_eq!(
            lookup(&config, "host.test", IpVersion::V4).unwrap(),
            [ip("192.0.2.1"), ip("192.0.2.2")]
        );
        assert_eq!(server.asked(), [("host.test.".to_owned(), A, false)]);
        assert_eq!(
            lookup(&config, "HOST.Test.", IpVersion::V6).unwrap(),
            [ip("2001:db8::1")]
        );
        assert_eq!(server.asked(), [("host.test.".to_owned(), AAAA, false)]);

        // A name with addresses of one kind.
        assert_eq!(
            lookup(&config, "v4only.test", IpVersion::Any).unwrap(),
            [ip("192.0.2.4")]
        );
        assert_eq!(
            lookup(&config, "v6only.test", IpVersion::Any).unwrap(),
            [ip("2001:db8::6")]
        );
        assert_eq!(
            kind(lookup(&config, "v4only.test", IpVersion::V6)),
            ErrorKind::NotFound
        );
        assert_eq!(
            kind(lookup(&config, "v6only.test", IpVersion::V4)),
            ErrorKind::NotFound
        );
        // A name that does not exist.
        assert_eq!(
            kind(lookup(&config, "missing.test", IpVersion::Any)),
            ErrorKind::NotFound
        );

        // Fewer places than addresses: the first ones.
        let mut addrs = [NO_ADDR; 2];
        let count = config
            .resolve("host.test", 1, IpVersion::Any, &mut addrs)
            .unwrap();
        assert_eq!(count, 2);
        // Nowhere to write is not "no such name".
        assert_eq!(
            config.resolve("host.test", 1, IpVersion::Any, &mut []),
            Ok(0)
        );
        let error = config
            .resolve("missing.test", 1, IpVersion::Any, &mut [])
            .unwrap_err();
        assert_eq!(error.kind(), ErrorKind::NotFound);

        // An address is nobody's question.
        server.asked();
        assert_eq!(
            lookup(&config, "192.0.2.77", IpVersion::Any).unwrap(),
            [ip("192.0.2.77")]
        );
        assert_eq!(
            kind(lookup(&config, "not a name", IpVersion::Any)),
            ErrorKind::InvalidInput
        );
        assert!(server.asked().is_empty());
    }

    #[test]
    fn aliases() {
        let server = server();
        let config = server.config();
        // The chain is followed, and what it does not lead to is left.
        assert_eq!(
            lookup(&config, "alias.test", IpVersion::V4).unwrap(),
            [ip("192.0.2.7")]
        );
        // An alias with nothing at its end is a name without addresses.
        assert_eq!(
            kind(lookup(&config, "alias.test", IpVersion::V6)),
            ErrorKind::NotFound
        );
        assert_eq!(
            lookup(&config, "alias.test", IpVersion::Any).unwrap(),
            [ip("192.0.2.7")]
        );
    }

    #[test]
    fn search_list() {
        let server = server();
        let config = server
            .config()
            .with_search(&["sub.test", "other.test"])
            .unwrap();
        // Fewer dots than `ndots`: the list first, and the first domain
        // that knows the name ends the search.
        assert_eq!(
            lookup(&config, "short", IpVersion::Any).unwrap(),
            [ip("192.0.2.9")]
        );
        assert_eq!(names(&server.asked()), ["short.sub.test."]);
        assert_eq!(
            lookup(&config, "second", IpVersion::Any).unwrap(),
            [ip("192.0.2.11")]
        );
        assert_eq!(
            names(&server.asked()),
            ["second.sub.test.", "second.other.test."]
        );
        // As many dots: alone first, then the list.
        assert_eq!(
            lookup(&config, "dotted.name", IpVersion::Any).unwrap(),
            [ip("192.0.2.10")]
        );
        assert_eq!(
            names(&server.asked()),
            ["dotted.name.", "dotted.name.sub.test."]
        );
        assert_eq!(
            lookup(&config, "host.test", IpVersion::V4).unwrap().len(),
            2
        );
        assert_eq!(names(&server.asked()), ["host.test."]);
        // A last dot: alone, and that is all.
        assert_eq!(
            kind(lookup(&config, "short.", IpVersion::Any)),
            ErrorKind::NotFound
        );
        assert_eq!(names(&server.asked()), ["short."]);
        // Nowhere: everything was tried, the name alone last.
        assert_eq!(
            kind(lookup(&config, "nowhere", IpVersion::V4)),
            ErrorKind::NotFound
        );
        assert_eq!(
            names(&server.asked()),
            ["nowhere.sub.test.", "nowhere.other.test.", "nowhere."]
        );
        // More dots are wanted: a name with one is completed first.
        let config = config.with_ndots(2);
        assert_eq!(
            lookup(&config, "dotted.name", IpVersion::Any).unwrap(),
            [ip("192.0.2.10")]
        );
        assert_eq!(names(&server.asked()), ["dotted.name.sub.test."]);
        // A domain that would make the name too long is not asked for.
        let long = ["abcdefgh"; 28].join(".");
        assert_eq!(
            kind(lookup(&config, &long, IpVersion::V4)),
            ErrorKind::NotFound
        );
        assert_eq!(names(&server.asked()), [format!("{long}.")]);
    }

    /// A response too long for a datagram comes over TCP.
    #[test]
    fn truncated() {
        let server = server();
        let config = server.config();
        let found = lookup(&config, "big.test", IpVersion::V4).unwrap();
        let expected: Vec<IpAddr> = (0..40u8).map(|i| IpAddr::from([198, 51, 0, i])).collect();
        assert_eq!(found, expected);
        assert_eq!(
            server.asked(),
            [
                ("big.test.".to_owned(), A, false),
                ("big.test.".to_owned(), A, true)
            ]
        );
        assert_eq!(
            lookup(&config, "big.test", IpVersion::Any).unwrap(),
            expected
        );

        // More than the client holds on its stack: with the heap it is
        // read all the same, and the caller's buffer is what cuts it.
        let huge = lookup(&config, "huge.test", IpVersion::V4);
        if cfg!(feature = "alloc") {
            let huge = huge.unwrap();
            assert_eq!(huge.len(), 64);
            assert_eq!(huge[63], IpAddr::from([198, 51, 0, 63]));
        } else {
            assert_eq!(kind(huge), ErrorKind::MessageTooLong);
        }

        // A server that cuts its answer and then has nothing to say over
        // TCP has not answered.
        let config = config.with_attempts(1);
        assert_eq!(
            kind(lookup(&config, "nostream.test", IpVersion::V4)),
            ErrorKind::Other
        );
    }

    /// What is not the answer is not taken for it.
    #[test]
    fn noise_and_lies() {
        let server = server();
        let config = server.config().with_attempts(1);
        assert_eq!(
            lookup(&config, "noisy.test", IpVersion::Any).unwrap(),
            [ip("192.0.2.42")]
        );
        // A server that fails, or answers nonsense, is no answer.
        for name in ["failure.test", "broken.test", "badlength.test"] {
            assert_eq!(
                kind(lookup(&config, name, IpVersion::V4)),
                ErrorKind::Other,
                "{name}"
            );
        }
        // It was asked once: one attempt, one server.
        server.asked();
        let _ = lookup(&config, "failure.test", IpVersion::V4);
        assert_eq!(server.asked().len(), 1);
        let config = config.with_attempts(3);
        let _ = lookup(&config, "failure.test", IpVersion::V4);
        assert_eq!(server.asked().len(), 3);
    }

    /// A server that says nothing is waited for, for the time set, and
    /// asked again as many times as set.
    #[test]
    fn silence() {
        let server = server();
        let timeout = Duration::from_millis(150);
        let config = server.config().with_timeout(timeout).with_attempts(2);
        let start = Instant::now();
        assert_eq!(
            kind(lookup(&config, "silent.test", IpVersion::V4)),
            ErrorKind::TimedOut
        );
        let elapsed = start.elapsed();
        assert!(elapsed >= 2 * timeout, "{elapsed:?}");
        assert!(elapsed < Duration::from_secs(30), "{elapsed:?}");
        assert_eq!(server.asked().len(), 2);
        // The search list is not gone through for a name nobody answers
        // for.
        let config = config.with_search(&["sub.test"]).unwrap();
        assert_eq!(
            kind(lookup(&config, "silent.test", IpVersion::V4)),
            ErrorKind::TimedOut
        );
        assert_eq!(names(&server.asked()), ["silent.test."]);
    }

    /// The servers are asked in turn: one that is not there, or says
    /// nothing, or fails, gives way to the next.
    #[test]
    fn several_servers() {
        let good = server();
        let quiet = server();
        // A port nobody listens on: it was just closed.
        let closed = UdpSocket::bind("127.0.0.1:0")
            .unwrap()
            .local_addr()
            .unwrap();

        let config = Config::new(&[closed, good.addr])
            .unwrap()
            .with_timeout(Duration::from_millis(500));
        assert_eq!(
            lookup(&config, "v4only.test", IpVersion::Any).unwrap(),
            [ip("192.0.2.4")]
        );

        assert_eq!(good.asked().len(), 2);

        // Two that say nothing cost their time each, each time round.
        let config = Config::new(&[quiet.addr, good.addr])
            .unwrap()
            .with_timeout(Duration::from_millis(500));
        let start = Instant::now();
        assert_eq!(
            kind(lookup(&config, "silent.test", IpVersion::V4)),
            ErrorKind::TimedOut
        );
        assert!(start.elapsed() >= Duration::from_millis(4 * 500));
        assert_eq!((quiet.asked().len(), good.asked().len()), (2, 2));

        // A server that fails, then one that does too: the second was
        // asked.
        let config = Config::new(&[quiet.addr, good.addr]).unwrap();
        assert_eq!(
            kind(lookup(&config, "failure.test", IpVersion::V4)),
            ErrorKind::Other
        );
        assert_eq!((quiet.asked().len(), good.asked().len()), (2, 2));

        // Nobody at all: what the system said of it, or silence where it
        // says nothing.
        let config = Config::new(&[closed])
            .unwrap()
            .with_timeout(Duration::from_millis(300))
            .with_attempts(1);
        let error = kind(lookup(&config, "host.test", IpVersion::V4));
        assert!(
            matches!(
                error,
                ErrorKind::ConnectionRefused | ErrorKind::ConnectionReset | ErrorKind::TimedOut
            ),
            "{error:?}"
        );
    }

    #[test]
    fn reverse() {
        let server = server();
        let config = server.config();
        let mut buf = [0u8; 64];
        assert_eq!(config.reverse(ip("192.0.2.1"), &mut buf), Ok("host.test"));
        assert_eq!(
            server.asked(),
            [("1.2.0.192.in-addr.arpa.".to_owned(), PTR, false)]
        );
        assert_eq!(config.reverse(ip("2001:db8::1"), &mut buf), Ok("six.test"));
        let error = config.reverse(ip("192.0.2.1"), &mut buf[..8]).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::BufferTooSmall);
        assert_eq!(
            config.reverse(ip("192.0.2.1"), &mut buf[..9]),
            Ok("host.test")
        );
        // No name, no such address, and a name that is not a host's.
        for addr in ["192.0.2.8", "192.0.2.250", "192.0.2.9", "2001:db8::2"] {
            let error = config.reverse(ip(addr), &mut buf).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::NotFound, "{addr}");
        }
    }

    /// A server reached over IPv6, where the machine has it.
    #[test]
    fn server_on_ipv6() {
        let Some(server) = Server::start(IpAddr::V6(Ipv6Addr::LOCALHOST)) else {
            eprintln!("no IPv6 loopback here: not tested");
            return;
        };
        let config = server.config();
        assert_eq!(
            lookup(&config, "host.test", IpVersion::Any).unwrap(),
            [ip("2001:db8::1"), ip("192.0.2.1"), ip("192.0.2.2")]
        );
        assert_eq!(
            lookup(&config, "big.test", IpVersion::V4).unwrap().len(),
            40
        );
    }

    /// Several lookups at once share nothing.
    #[test]
    fn concurrent() {
        let server = server();
        let config = server.config();
        std::thread::scope(|scope| {
            for i in 0..8 {
                let config = &config;
                scope.spawn(move || {
                    for _ in 0..10 {
                        if i % 2 == 0 {
                            assert_eq!(
                                lookup(config, "host.test", IpVersion::Any).unwrap().len(),
                                3
                            );
                        } else {
                            assert_eq!(
                                lookup(config, "big.test", IpVersion::V4).unwrap().len(),
                                40
                            );
                        }
                    }
                });
            }
        });
    }
}