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
//! A DNS client: asking name servers for the addresses of a name, and for
//! the name of an address.
//!
//! This is the same code on every system, written on the sockets of this
//! crate: what it does on one it does on all. A [`Config`] says which
//! servers to ask and how; [`Config::resolve`] and [`Config::reverse`]
//! ask them. Nothing is read from the system here: a `Config` is made
//! from addresses ([`Config::new`]) or from the text of a `resolv.conf`
//! ([`Config::from_resolv_conf`]), and [`resolve`](super::resolve) is the
//! function that asks the way the system is set up to.
//!
//! ```no_run
//! use core::net::SocketAddr;
//! use oscall::net::{IpVersion, dns};
//!
//! # fn main() -> oscall::Result<()> {
//! let server: SocketAddr = "192.0.2.53:53".parse().unwrap();
//! let config = dns::Config::new(&[server])?;
//! let mut addrs = [SocketAddr::from(([0, 0, 0, 0], 0)); 8];
//! let count = config.resolve("www.example.com", 443, IpVersion::Any, &mut addrs)?;
//! for addr in &addrs[..count] {
//!     // connect...
//! #   let _ = addr;
//! }
//! # Ok(())
//! # }
//! ```
//!
//! # What it does
//!
//! - It is a *stub* resolver: it asks servers that do the work (recursive
//!   ones), with one question per message, and believes what they say.
//! - A question goes out as a datagram (UDP), from a socket of its own and
//!   so from a port the system picked, with an identifier from the
//!   system's random generator. An answer is taken only from the address
//!   that was asked, with that identifier and that question.
//! - A response the server had to cut to fit a datagram is asked again
//!   over TCP, of the same server.
//! - For [`IpVersion::Any`] the two questions (`AAAA` and `A`) are sent
//!   together and their answers awaited together.
//! - The servers are asked in turn, each for [`Config::timeout`]; a server
//!   that does not answer, answers that it failed (`SERVFAIL`, `REFUSED`
//!   and the like), or sends something malformed, gives its turn to the
//!   next, and the list is gone through [`Config::attempts`] times.
//! - A name is completed from the search list as the C libraries do: a
//!   name with fewer dots than [`Config::ndots`] is tried with each domain
//!   of the list first and alone last, one with as many is tried alone
//!   first, and one that ends with a dot is tried alone and that is all.
//!   The first that has addresses wins. A lookup that fails for want of an
//!   answer is not continued with the next domain.
//! - Aliases (`CNAME`) are followed within the response, which is where a
//!   recursive server puts the whole chain.
//! - No memory is allocated. A response is read into 4 KiB on the stack,
//!   which is all UDP can bring; over TCP a longer one is read into
//!   memory from the heap with the `alloc` feature, and fails with
//!   [`MessageTooLong`](ErrorKind::MessageTooLong) without it.
//!
//! # What it does not do
//!
//! - **Validate** (DNSSEC): it believes the server, as every stub does.
//!   What protects an answer is the unpredictable port and identifier,
//!   and the path to the server.
//! - **Encrypt**: no DNS over TLS or HTTPS.
//! - **EDNS**: a response is at most 512 bytes over UDP, and longer ones
//!   come over TCP.
//! - **Internationalised names** (IDNA): a name is letters, digits, `-`
//!   and `_` between dots. Converting a name in another script to its
//!   `xn--` form is the caller's business.
//! - **Cache**: every call asks.
//! - **Other name services**: multicast DNS (`.local`), LLMNR, NetBIOS.
//!   See [`resolve`](super::resolve) for what that means on Linux.
//! - Of `resolv.conf`: the options other than `ndots`, `timeout` and
//!   `attempts` (`rotate`, `edns0`, `use-vc`, `single-request`...), the
//!   `sortlist` line, the variables `LOCALDOMAIN` and `RES_OPTIONS`, and
//!   name servers given with the name of an interface (`fe80::1%eth0`; a
//!   number, `fe80::1%2`, is taken).
//!
//! # Errors
//!
//! - [`NotFound`](ErrorKind::NotFound): a server answered, and the name
//!   does not exist or has no record of the kind asked for.
//! - [`TimedOut`](ErrorKind::TimedOut): no server answered in time.
//! - The system's own error when no server could be reached and that is
//!   why ([`NetworkUnreachable`](ErrorKind::NetworkUnreachable),
//!   [`ConnectionRefused`](ErrorKind::ConnectionRefused) for a port
//!   nothing listens on...).
//! - [`Other`](ErrorKind::Other): the servers answered, all with a
//!   failure or with something that is not an answer.
//! - [`InvalidInput`](ErrorKind::InvalidInput): the name is not one.
//! - [`Unsupported`](ErrorKind::Unsupported) on WebAssembly, which cannot
//!   create a socket.

pub(crate) mod conf;
pub(crate) mod message;

use core::net::{IpAddr, SocketAddr};
use core::time::Duration;

use self::message::{Answer, Header, MAX_UDP, Name, TYPE_A, TYPE_AAAA, TYPE_PTR};
use super::{Family, IpVersion, OwnedSocket, Protocol, RecvFlags, SendFlags, Type};
use crate::event::{Interest, PollEntry};
use crate::time::Clock;
use crate::{Error, ErrorKind, Result};

/// The most name servers a [`Config`] holds: what the C libraries read of
/// a `resolv.conf`.
pub const MAX_SERVERS: usize = 3;
/// The most domains of a search list, and the room for their text.
const MAX_SEARCH: usize = 6;
const SEARCH_TEXT: usize = 256;
/// What is read on the stack.
const BUFFER: usize = 4096;

const DEFAULT_TIMEOUT: Duration = Duration::from_secs(5);
const MAX_TIMEOUT: Duration = Duration::from_secs(30);
const DEFAULT_ATTEMPTS: u8 = 2;
const MAX_ATTEMPTS: u8 = 5;
const DEFAULT_NDOTS: u8 = 1;
const MAX_NDOTS: u8 = 15;

/// Which name servers to ask, and how: see [the module](self).
#[derive(Clone)]
pub struct Config {
    servers: [SocketAddr; MAX_SERVERS],
    server_count: u8,
    /// The domains of the search list, each followed by a NUL.
    search: [u8; SEARCH_TEXT],
    search_len: u16,
    ndots: u8,
    attempts: u8,
    timeout: Duration,
}

impl Config {
    /// No server, no search list, and the defaults.
    pub(crate) fn empty() -> Self {
        Self {
            servers: [SocketAddr::new(IpAddr::V4(core::net::Ipv4Addr::LOCALHOST), 53); MAX_SERVERS],
            server_count: 0,
            search: [0; SEARCH_TEXT],
            search_len: 0,
            ndots: DEFAULT_NDOTS,
            attempts: DEFAULT_ATTEMPTS,
            timeout: DEFAULT_TIMEOUT,
        }
    }

    /// A configuration that asks `servers`, in that order: one to
    /// [`MAX_SERVERS`] addresses, each with its port (53 is where name
    /// servers listen). No search list, and the defaults a `resolv.conf`
    /// has: 5 seconds for each server, the list gone through twice, one
    /// dot.
    ///
    /// Fails with [`InvalidInput`](ErrorKind::InvalidInput) for no server
    /// or too many.
    pub fn new(servers: &[SocketAddr]) -> Result<Self> {
        if servers.is_empty() || servers.len() > MAX_SERVERS {
            return Err(ErrorKind::InvalidInput.into());
        }
        let mut config = Self::empty();
        config.servers[..servers.len()].copy_from_slice(servers);
        config.server_count = servers.len() as u8;
        Ok(config)
    }

    /// The configuration the text of a `resolv.conf` describes, as
    /// `resolv.conf(5)` has it: its `nameserver` lines (the first three,
    /// on port 53), its last `search` or `domain` line (six domains and
    /// 255 characters at most; what is beyond is left out), and of its
    /// `options` lines `ndots` (15 at most), `timeout` (30 at most) and
    /// `attempts` (5 at most). Anything else is ignored, as is a line
    /// that cannot be read.
    ///
    /// A text that names no server gives one that asks `127.0.0.1`, which
    /// is what the C libraries do with a file that is empty or missing.
    #[must_use]
    pub fn from_resolv_conf(text: &[u8]) -> Self {
        let mut config = Self::empty();
        for line in text.split(|&byte| byte == b'\n') {
            conf::resolv_line(line, &mut config);
        }
        config.or_local()
    }

    /// With the server every C library falls back on, if there is none.
    pub(crate) fn or_local(mut self) -> Self {
        if self.server_count == 0 {
            self.server_count = 1;
        }
        self
    }

    /// Adds a server, if there is room.
    pub(crate) fn push_server(&mut self, server: SocketAddr) {
        if let Some(slot) = self.servers.get_mut(usize::from(self.server_count)) {
            *slot = server;
            self.server_count += 1;
        }
    }

    /// Replaces the search list by `domains`, as far as they fit and are
    /// names.
    pub(crate) fn replace_search<'a>(&mut self, domains: impl Iterator<Item = &'a [u8]>) {
        self.search_len = 0;
        for domain in domains.take(MAX_SEARCH) {
            let domain = domain.strip_suffix(b".").unwrap_or(domain);
            if Name::from_text(domain).is_none() {
                continue;
            }
            let start = usize::from(self.search_len);
            let end = start + domain.len();
            // The last byte stays out: 255 characters, as glibc counts.
            let Some(slot) = self.search.get_mut(start..end + 1) else {
                break;
            };
            slot[..domain.len()].copy_from_slice(domain);
            slot[domain.len()] = 0;
            self.search_len = (end + 1) as u16;
        }
    }

    /// The servers, in the order they are asked.
    #[must_use]
    pub fn servers(&self) -> &[SocketAddr] {
        &self.servers[..usize::from(self.server_count)]
    }

    /// The domains a name is completed with, in order.
    pub fn search(&self) -> impl Iterator<Item = &str> {
        self.search[..usize::from(self.search_len)]
            .split(|&byte| byte == 0)
            .filter(|domain| !domain.is_empty())
            // What `replace_search` stored was checked to be a name, which
            // is ASCII.
            .filter_map(|domain| core::str::from_utf8(domain).ok())
    }

    /// Sets the search list: six domains at most, and 255 characters in
    /// all with one between two domains.
    ///
    /// Fails with [`InvalidInput`](ErrorKind::InvalidInput) if there are
    /// more, or if one is not a name.
    pub fn with_search(mut self, domains: &[&str]) -> Result<Self> {
        let room = domains.iter().map(|domain| domain.len() + 1).sum::<usize>();
        let named = domains
            .iter()
            .all(|domain| Name::from_text(domain.as_bytes()).is_some());
        if domains.len() > MAX_SEARCH || room > SEARCH_TEXT || !named {
            return Err(ErrorKind::InvalidInput.into());
        }
        self.replace_search(domains.iter().map(|domain| domain.as_bytes()));
        Ok(self)
    }

    /// How many dots make a name one to try as it is before the search
    /// list is tried: 1 unless set.
    #[must_use]
    pub fn ndots(&self) -> u8 {
        self.ndots
    }

    /// Sets [`ndots`](Self::ndots): 15 at most, as in `resolv.conf`.
    #[must_use]
    pub fn with_ndots(mut self, ndots: u8) -> Self {
        self.ndots = ndots.min(MAX_NDOTS);
        self
    }

    /// How long one server is waited for: 5 seconds unless set.
    #[must_use]
    pub fn timeout(&self) -> Duration {
        self.timeout
    }

    /// Sets [`timeout`](Self::timeout): from a millisecond to 30 seconds.
    /// (`resolv.conf` counts in seconds; a program that asks a server it
    /// knows to be near may want less.)
    #[must_use]
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout.clamp(Duration::from_millis(1), MAX_TIMEOUT);
        self
    }

    /// How many times the list of servers is gone through before a lookup
    /// gives up: twice unless set.
    #[must_use]
    pub fn attempts(&self) -> u8 {
        self.attempts
    }

    /// Sets [`attempts`](Self::attempts): from 1 to 5.
    #[must_use]
    pub fn with_attempts(mut self, attempts: u8) -> Self {
        self.attempts = attempts.clamp(1, MAX_ATTEMPTS);
        self
    }

    /// Asks the servers for the addresses of `host`, writes them to
    /// `addrs` with `port`, and returns how many were written: those of
    /// IPv6 first, each kind in the order the server gave. Addresses
    /// that do not fit in `addrs` are left out.
    ///
    /// A `host` that is an address already (`192.0.2.1`, `2001:db8::1`)
    /// is returned as it is, and no server is asked. Otherwise it must be
    /// a name: labels of letters, digits, `-` and `_`, 63 characters at
    /// most each, with dots between them, 253 characters in all; a last
    /// dot says the name is complete and keeps the search list away.
    /// Anything else fails with [`InvalidInput`](ErrorKind::InvalidInput).
    ///
    /// See [the module](self) for the errors, and for what is and is not
    /// done.
    pub fn resolve(
        &self,
        host: &str,
        port: u16,
        version: IpVersion,
        addrs: &mut [SocketAddr],
    ) -> Result<usize> {
        if let Some(count) = literal(host, port, version, addrs)? {
            return Ok(count);
        }
        let host = host.as_bytes();
        let alone = Name::from_text(host).ok_or(ErrorKind::InvalidInput)?;
        let complete = host.ends_with(b".");
        let dots = host.iter().filter(|&&byte| byte == b'.').count() - usize::from(complete);
        let alone_first = complete || dots >= usize::from(self.ndots);

        // How many addresses were written, or `None` when the name has
        // none: with nowhere to write, a name that has some is `Some(0)`.
        let ask = |name: &Name, addrs: &mut [SocketAddr]| -> Result<Option<usize>> {
            let mut questions = [Question::new(TYPE_AAAA), Question::new(TYPE_A)];
            let questions = match version {
                IpVersion::Any => &mut questions[..],
                IpVersion::V6 => &mut questions[..1],
                IpVersion::V4 => &mut questions[1..],
            };
            let (mut count, mut found) = (0, false);
            self.lookup(name, questions, &mut |qtype, msg, header| {
                let before = count;
                let answer = message::addresses(msg, header, name, qtype, |addr| {
                    if let Some(slot) = addrs.get_mut(count) {
                        *slot = SocketAddr::new(addr, port);
                        count += 1;
                    }
                });
                match answer {
                    Some(Answer::Found(_)) => found = true,
                    Some(Answer::Nothing) => {}
                    // What a malformed response gave before it went wrong
                    // is not kept.
                    None => count = before,
                }
                answer
            })?;
            v6_first(addrs.get_mut(..count).ok_or(ErrorKind::Other)?);
            Ok(found.then_some(count))
        };

        if alone_first && let Some(count) = ask(&alone, addrs)? {
            return Ok(count);
        }
        if !complete {
            for domain in self.search() {
                let mut name = alone.clone();
                // A name the domain makes too long is not asked for.
                if name.push_text(domain.as_bytes()).is_none() {
                    continue;
                }
                if let Some(count) = ask(&name, addrs)? {
                    return Ok(count);
                }
            }
        }
        if !alone_first && let Some(count) = ask(&alone, addrs)? {
            return Ok(count);
        }
        Err(ErrorKind::NotFound.into())
    }

    /// Asks the servers for the name of `addr` (its `PTR` record, under
    /// `in-addr.arpa` or `ip6.arpa`), writes it to `buf` without a last
    /// dot, and returns it. An address may have several names: this is
    /// the first the server gave.
    ///
    /// A name that is not a host name (see [`resolve`](Self::resolve) for
    /// what is) is not returned: the call fails with
    /// [`NotFound`](ErrorKind::NotFound), as it does for an address with
    /// no name. If `buf` is too small for the name it fails with
    /// [`BufferTooSmall`](ErrorKind::BufferTooSmall); 253 bytes hold any.
    ///
    /// Nothing says the name leads back to the address: whoever runs the
    /// servers for the address writes what they like there.
    pub fn reverse<'a>(&self, addr: IpAddr, buf: &'a mut [u8]) -> Result<&'a str> {
        let name = Name::reverse(addr);
        let mut found = None;
        self.lookup(
            &name,
            &mut [Question::new(TYPE_PTR)],
            &mut |_, msg, header| {
                let pointer = message::pointer(msg, header, &name)?;
                Some(match pointer {
                    Some(pointer) => {
                        found = Some(pointer);
                        Answer::Found(1)
                    }
                    None => Answer::Nothing,
                })
            },
        )?;
        let found = found.ok_or(ErrorKind::NotFound)?;
        let mut text = [0u8; message::MAX_NAME];
        let len = found.to_text(&mut text).ok_or(ErrorKind::NotFound)?;
        let out = buf.get_mut(..len).ok_or(ErrorKind::BufferTooSmall)?;
        out.copy_from_slice(&text[..len]);
        core::str::from_utf8(out).map_err(|_| ErrorKind::Other.into())
    }

    /// Gets every question answered, by whichever server will, and gives
    /// each response to `handle`, which says what it found in it (`None`
    /// for a response that is malformed).
    fn lookup(
        &self,
        name: &Name,
        questions: &mut [Question],
        handle: &mut Handle<'_>,
    ) -> Result<()> {
        // What went wrong last: a system error, or a server that answered
        // without an answer.
        let mut error = None;
        let mut failed = false;
        for _ in 0..self.attempts {
            for server in self.servers() {
                match ask(server, self.timeout, name, questions, handle) {
                    Ok(Asked::Answered) => return Ok(()),
                    Ok(Asked::Silent) => {}
                    Ok(Asked::Failed) => failed = true,
                    Err(e) if e.kind() == ErrorKind::Unsupported => return Err(e),
                    Err(e) => error = Some(e),
                }
            }
        }
        Err(match (error, failed) {
            (Some(error), _) => error,
            (None, true) => ErrorKind::Other.into(),
            (None, false) => ErrorKind::TimedOut.into(),
        })
    }
}

impl core::fmt::Debug for Config {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        struct Search<'a>(&'a Config);
        impl core::fmt::Debug for Search<'_> {
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                f.debug_list().entries(self.0.search()).finish()
            }
        }
        f.debug_struct("Config")
            .field("servers", &self.servers())
            .field("search", &Search(self))
            .field("ndots", &self.ndots)
            .field("timeout", &self.timeout)
            .field("attempts", &self.attempts)
            .finish()
    }
}

/// What a response is given to: the type of the question, the message and
/// its header.
type Handle<'a> = dyn FnMut(u16, &[u8], &Header) -> Option<Answer> + 'a;

/// The answer for a `host` that is an address already. `None` if it is
/// not one.
pub(crate) fn literal(
    host: &str,
    port: u16,
    version: IpVersion,
    addrs: &mut [SocketAddr],
) -> Result<Option<usize>> {
    let Ok(addr) = host.parse::<IpAddr>() else {
        return Ok(None);
    };
    let wanted = match version {
        IpVersion::Any => true,
        IpVersion::V4 => addr.is_ipv4(),
        IpVersion::V6 => addr.is_ipv6(),
    };
    if !wanted {
        return Err(ErrorKind::NotFound.into());
    }
    Ok(Some(match addrs.first_mut() {
        Some(slot) => {
            *slot = SocketAddr::new(addr, port);
            1
        }
        None => 0,
    }))
}

/// Whether `host` is a name as [`Config::resolve`] takes one.
pub(crate) fn is_name(host: &str) -> bool {
    Name::from_text(host.as_bytes()).is_some()
}

/// Puts the IPv6 addresses before the others, each kind in its order.
pub(crate) fn v6_first(addrs: &mut [SocketAddr]) {
    partition(addrs, SocketAddr::is_ipv6);
}

/// Puts the addresses `first` holds for before the others, each group in
/// the order it had. The lists are short: this is an insertion.
pub(crate) fn partition(addrs: &mut [SocketAddr], mut first: impl FnMut(&SocketAddr) -> bool) {
    let mut front = 0;
    for i in 0..addrs.len() {
        if first(&addrs[i]) {
            addrs[front..=i].rotate_right(1);
            front += 1;
        }
    }
}

/// One question of a lookup.
struct Question {
    qtype: u16,
    id: u16,
    answered: bool,
}

impl Question {
    fn new(qtype: u16) -> Self {
        Self {
            qtype,
            id: 0,
            answered: false,
        }
    }
}

/// How asking one server went.
enum Asked {
    /// Every question has its answer.
    Answered,
    /// The time passed.
    Silent,
    /// The server answered that it could not, or not in DNS.
    Failed,
}

fn now() -> Result<Duration> {
    Clock::Monotonic.now()
}

/// Waits until `socket` is ready for `interest` or `deadline` passes, and
/// says whether it is ready.
fn wait(socket: &OwnedSocket, interest: Interest, deadline: Duration) -> Result<bool> {
    loop {
        let left = deadline.saturating_sub(now()?);
        if left.is_zero() {
            return Ok(false);
        }
        let mut entry = [PollEntry::new(socket, interest)];
        match crate::event::poll(&mut entry, Some(left)) {
            Ok(0) => return Ok(false),
            Ok(_) => return Ok(true),
            // A signal handler ran: the deadline has not moved.
            Err(error) if error.kind() == ErrorKind::Interrupted => {}
            Err(error) => return Err(error),
        }
    }
}

fn socket_for(server: &SocketAddr, ty: Type) -> Result<OwnedSocket> {
    let family = if server.is_ipv4() {
        Family::Ipv4
    } else {
        Family::Ipv6
    };
    super::socket(family, ty, Protocol::Default)
}

/// Whether a failed call on a socket only means "not now".
fn retry(error: Error) -> bool {
    matches!(
        error.kind(),
        ErrorKind::WouldBlock | ErrorKind::Interrupted | ErrorKind::TimedOut
    )
}

/// Asks `server` the questions that have no answer yet, and waits
/// `timeout` for it.
fn ask(
    server: &SocketAddr,
    timeout: Duration,
    name: &Name,
    questions: &mut [Question],
    handle: &mut Handle<'_>,
) -> Result<Asked> {
    // A socket for this server and this time: its port is one the system
    // picks, and being connected it takes datagrams from that server
    // alone.
    let socket = socket_for(server, Type::Datagram)?;
    super::connect(&socket, &(*server).into())?;

    let mut ids = [0u8; 2];
    let mut used = None;
    for question in questions.iter_mut().filter(|question| !question.answered) {
        // An identifier nobody can guess, and not the other question's.
        loop {
            crate::rand::fill(&mut ids)?;
            question.id = u16::from_ne_bytes(ids);
            if used != Some(question.id) {
                break;
            }
        }
        used = Some(question.id);
        let mut query = [0u8; MAX_UDP];
        let len = message::write_query(&mut query, question.id, name, question.qtype);
        super::send(&socket, &query[..len], SendFlags::empty())?;
    }

    let deadline = now()?.saturating_add(timeout);
    let mut buf = [0u8; BUFFER];
    loop {
        if questions.iter().all(|question| question.answered) {
            return Ok(Asked::Answered);
        }
        if !wait(&socket, Interest::READABLE, deadline)? {
            return Ok(Asked::Silent);
        }
        let len = match super::recv(&socket, &mut buf, RecvFlags::empty()) {
            Ok(len) => len,
            Err(error) if retry(error) => continue,
            Err(error) => return Err(error),
        };
        // Whose answer is it? Anything else is noise, or an attack.
        let asked = questions
            .iter_mut()
            .filter(|question| !question.answered)
            .find_map(|question| {
                let header = message::parse_header(&buf[..len], question.id, name, question.qtype)?;
                Some((question, header))
            });
        let Some((question, header)) = asked else {
            continue;
        };
        let answer = match header.rcode {
            message::RCODE_NAME_ERROR => Some(Answer::Nothing),
            message::RCODE_OK if header.truncated => {
                // The whole of it is to be had over TCP.
                match tcp(server, timeout, name, question, &mut buf, handle) {
                    Ok(answer) => answer,
                    // A server that does not speak TCP has not answered.
                    Err(error) if error.kind() == ErrorKind::MessageTooLong => return Err(error),
                    Err(_) => return Ok(Asked::Failed),
                }
            }
            message::RCODE_OK => handle(question.qtype, &buf[..len], &header),
            _ => None,
        };
        match answer {
            Some(_) => question.answered = true,
            None => return Ok(Asked::Failed),
        }
    }
}

/// Asks `server` one question over TCP, where a message travels after
/// its length, and gives the response to `handle`. `Ok(None)` for a
/// response that is not an answer.
fn tcp(
    server: &SocketAddr,
    timeout: Duration,
    name: &Name,
    question: &Question,
    buf: &mut [u8; BUFFER],
    handle: &mut Handle<'_>,
) -> Result<Option<Answer>> {
    let deadline = now()?.saturating_add(timeout);
    let socket = socket_for(server, Type::Stream)?;
    // Not blocking: a connection that nobody answers would take minutes.
    super::set_nonblocking(&socket, true)?;
    match super::connect(&socket, &(*server).into()) {
        Ok(()) => {}
        Err(error) if matches!(error.kind(), ErrorKind::InProgress | ErrorKind::WouldBlock) => {
            if !wait(&socket, Interest::WRITABLE, deadline)? {
                return Err(ErrorKind::TimedOut.into());
            }
            if let Some(error) = super::take_error(&socket)? {
                return Err(error);
            }
        }
        Err(error) => return Err(error),
    }

    let mut query = [0u8; 2 + MAX_UDP];
    let (prefix, body) = query.split_at_mut(2);
    let body: &mut [u8; MAX_UDP] = body.try_into().map_err(|_| ErrorKind::Other)?;
    let len = message::write_query(body, question.id, name, question.qtype);
    prefix.copy_from_slice(&(len as u16).to_be_bytes());
    let mut rest = &query[..2 + len];
    while !rest.is_empty() {
        if !wait(&socket, Interest::WRITABLE, deadline)? {
            return Err(ErrorKind::TimedOut.into());
        }
        match super::send(&socket, rest, SendFlags::empty()) {
            Ok(sent) => rest = rest.get(sent..).ok_or(ErrorKind::Other)?,
            Err(error) if retry(error) => {}
            Err(error) => return Err(error),
        }
    }

    let read = |to: &mut [u8]| -> Result<()> {
        let mut filled = 0;
        while filled < to.len() {
            if !wait(&socket, Interest::READABLE, deadline)? {
                return Err(ErrorKind::TimedOut.into());
            }
            match super::recv(&socket, &mut to[filled..], RecvFlags::empty()) {
                // The server closed before the end of what it announced.
                Ok(0) => return Err(ErrorKind::ConnectionReset.into()),
                Ok(received) => filled += received,
                Err(error) if retry(error) => {}
                Err(error) => return Err(error),
            }
        }
        Ok(())
    };
    let mut prefix = [0u8; 2];
    read(&mut prefix)?;
    let len = usize::from(u16::from_be_bytes(prefix));

    #[cfg(feature = "alloc")]
    let mut large = alloc::vec::Vec::new();
    let msg = match buf.get_mut(..len) {
        Some(msg) => msg,
        #[cfg(feature = "alloc")]
        None => {
            large
                .try_reserve_exact(len)
                .map_err(|_| ErrorKind::OutOfMemory)?;
            large.resize(len, 0);
            &mut large[..]
        }
        #[cfg(not(feature = "alloc"))]
        None => return Err(ErrorKind::MessageTooLong.into()),
    };
    read(msg)?;
    let Some(header) = message::parse_header(msg, question.id, name, question.qtype) else {
        return Ok(None);
    };
    Ok(match header.rcode {
        message::RCODE_NAME_ERROR => Some(Answer::Nothing),
        // Cut again, over TCP: there is no third way to ask.
        message::RCODE_OK if !header.truncated => handle(question.qtype, msg, &header),
        _ => None,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn partitions() {
        let addr = |text: &str| -> SocketAddr { text.parse().unwrap() };
        let mut addrs = [
            addr("192.0.2.1:1"),
            addr("[2001:db8::1]:2"),
            addr("192.0.2.2:3"),
            addr("[2001:db8::2]:4"),
            addr("[2001:db8::3]:5"),
        ];
        v6_first(&mut addrs);
        assert_eq!(
            addrs,
            [
                addr("[2001:db8::1]:2"),
                addr("[2001:db8::2]:4"),
                addr("[2001:db8::3]:5"),
                addr("192.0.2.1:1"),
                addr("192.0.2.2:3"),
            ]
        );
        v6_first(&mut addrs[..0]);
    }

    #[test]
    fn literals() {
        let mut addrs = [SocketAddr::from(([0, 0, 0, 0], 0)); 2];
        assert_eq!(
            literal("192.0.2.7", 80, IpVersion::Any, &mut addrs),
            Ok(Some(1))
        );
        assert_eq!(addrs[0], "192.0.2.7:80".parse().unwrap());
        assert_eq!(literal("::1", 443, IpVersion::V6, &mut addrs), Ok(Some(1)));
        assert_eq!(addrs[0], "[::1]:443".parse().unwrap());
        assert_eq!(literal("::1", 443, IpVersion::Any, &mut []), Ok(Some(0)));
        for (host, version) in [("::1", IpVersion::V4), ("192.0.2.7", IpVersion::V6)] {
            let error = literal(host, 1, version, &mut addrs).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::NotFound);
        }
        for name in [
            "localhost",
            "192.0.2",
            "192.0.2.256",
            "1.2.3.4.5",
            "::g",
            "",
        ] {
            assert_eq!(
                literal(name, 1, IpVersion::Any, &mut addrs),
                Ok(None),
                "{name}"
            );
        }
        assert!(is_name("192.0.2.256"));
        assert!(!is_name("::g"));
    }
}