Skip to main content

net_io/
udp.rs

1//! UDP: a bound socket that reports truncated datagrams, budgets sources, and
2//! never amplifies (FR-49 to FR-51).
3//!
4//! UDP source addresses are trivially spoofed, so the guard sits between the
5//! socket and the caller: every datagram is charged to its source's budget
6//! (and the global one) before it is returned, and every send to a source that
7//! has not proved it can receive is limited to `factor` times what it sent us.
8//! Budgets are kept per source prefix (an IPv6 host usually owns a whole /64);
9//! the send allowance is kept per exact address, since that is what a reply hits.
10
11use std::collections::HashMap;
12use std::hash::Hash;
13use std::io;
14use std::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV6, ToSocketAddrs};
15use std::sync::atomic::{AtomicBool, Ordering};
16use std::time::{Duration, Instant};
17
18use crate::addr::{PrefixKey, PrefixPolicy, normalize};
19use crate::error::{ConfigReason, LimitKind, NetError, TimeoutKind};
20use crate::sys::{self, AsSock};
21
22/// Rates for one budget: datagrams and bytes per second, and how many datagrams
23/// may arrive at once. The byte bucket holds one second of bytes.
24///
25/// ```
26/// let budget = net_io::UdpBudget { datagrams_per_sec: 100, bytes_per_sec: 150_000, burst: 20 };
27/// # let _ = budget;
28/// ```
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub struct UdpBudget {
31    /// Datagrams per second, sustained.
32    pub datagrams_per_sec: u32,
33    /// Bytes per second, sustained.
34    pub bytes_per_sec: u32,
35    /// Datagrams that may arrive at once (the datagram bucket's depth).
36    pub burst: u32,
37}
38
39impl UdpBudget {
40    /// The default per-source budget: 1,000 datagrams and 1 MB per second,
41    /// bursts of 100.
42    pub const SOURCE_DEFAULT: UdpBudget = UdpBudget {
43        datagrams_per_sec: 1_000,
44        bytes_per_sec: 1_000_000,
45        burst: 100,
46    };
47
48    /// The default budget of a whole socket: 100,000 datagrams and 150 MB per
49    /// second (100,000 full-size 1,500-byte datagrams, 1.2 Gbit/s), bursts of
50    /// 10,000 (a tenth of a second). One listener is one thread, which handles
51    /// on the order of 100,000 datagrams a second once its session does any work
52    /// (an estimate, not a measurement), so a server below that never meets this
53    /// budget; one that expects more sets its own with
54    /// [`UdpOptions::global_budget`].
55    pub const GLOBAL_DEFAULT: UdpBudget = UdpBudget {
56        datagrams_per_sec: 100_000,
57        bytes_per_sec: 150_000_000,
58        burst: 10_000,
59    };
60}
61
62/// Options for [`UdpSocket::bind_with`].
63///
64/// ```
65/// use net_io::{UdpBudget, UdpOptions};
66/// let options = UdpOptions::new()
67///     .amplification_factor(3) // a QUIC handshake (RFC 9000)
68///     .global_budget(UdpBudget { datagrams_per_sec: 50_000, bytes_per_sec: 60_000_000, burst: 5_000 });
69/// # let _ = options;
70/// ```
71#[must_use]
72#[derive(Clone, Debug, PartialEq, Eq)]
73pub struct UdpOptions {
74    factor: u8,
75    window: Duration,
76    source: UdpBudget,
77    first: u32,
78    prefix: PrefixPolicy,
79    global: UdpBudget,
80    table: u32,
81    verified_for: Duration,
82    verified_table: u32,
83    ipv6_only: bool,
84    packet_info: bool,
85}
86
87impl Default for UdpOptions {
88    fn default() -> UdpOptions {
89        UdpOptions::new()
90    }
91}
92
93impl UdpOptions {
94    /// Factor 1, a 10 s window, [`UdpBudget::SOURCE_DEFAULT`] per source prefix
95    /// (/32 for IPv4, /64 for IPv6) with a first burst of 16,
96    /// [`UdpBudget::GLOBAL_DEFAULT`] for the socket, 65,536 sources, verification
97    /// for 60 s and up to 65,536 verified peers, IPv6-only for IPv6 addresses.
98    pub fn new() -> UdpOptions {
99        UdpOptions {
100            factor: 1,
101            window: Duration::from_secs(10),
102            source: UdpBudget::SOURCE_DEFAULT,
103            first: 16,
104            prefix: PrefixPolicy::DEFAULT,
105            global: UdpBudget::GLOBAL_DEFAULT,
106            table: 65_536,
107            verified_for: Duration::from_secs(60),
108            verified_table: 65_536,
109            ipv6_only: true,
110            packet_info: false,
111        }
112    }
113
114    /// How many times the bytes received from an unverified source may be sent
115    /// back to it (1 by default, at most 3; decision D-034).
116    pub fn amplification_factor(mut self, factor: u8) -> UdpOptions {
117        self.factor = factor;
118        self
119    }
120
121    /// How long received bytes count toward a source's send allowance (10 s by
122    /// default, at least 1 s, at most 1 hour). The allowance spans the current and
123    /// the previous window, so a reply just after a window boundary is not refused.
124    pub fn amplification_window(mut self, window: Duration) -> UdpOptions {
125        self.window = window;
126        self
127    }
128
129    /// How long one [`UdpSocket::mark_verified`] lasts (60 s by default, at least
130    /// 1 s, at most 1 day). Each call starts it again, so a protocol that proves
131    /// its peer on every authenticated datagram never sees it lapse; a peer that
132    /// went away stops being an unlimited target once it does.
133    pub fn verification_lifetime(mut self, lifetime: Duration) -> UdpOptions {
134        self.verified_for = lifetime;
135        self
136    }
137
138    /// How many verified peers (address and port) are held (65,536 by default,
139    /// about 100 bytes each). Past that, a new verification takes the place of
140    /// one that lapsed or was least recently verified; that peer is limited
141    /// again until it is verified again.
142    pub fn verified_table(mut self, entries: u32) -> UdpOptions {
143        self.verified_table = entries;
144        self
145    }
146
147    /// The budget of each source (each prefix of [`UdpOptions::source_prefix`]).
148    pub fn source_budget(mut self, budget: UdpBudget) -> UdpOptions {
149        self.source = budget;
150        self
151    }
152
153    /// How addresses are grouped into sources for the budgets
154    /// ([`PrefixPolicy::DEFAULT`]: /32 for IPv4 and /64 for IPv6, as the TCP
155    /// per-source cap groups them; [`PrefixPolicy::HOST`] budgets every address
156    /// on its own). An IPv6 host usually owns a whole /64 and can send from any
157    /// address in it, so a budget per address would give it millions. The send
158    /// allowance and verification stay per address whatever the policy.
159    pub fn source_prefix(mut self, policy: PrefixPolicy) -> UdpOptions {
160        self.prefix = policy;
161        self
162    }
163
164    /// How many datagrams a source not in the table may send at once (16 by
165    /// default, never more than the source budget's burst). Its bucket then fills
166    /// to the full burst at the budget's rate, so a source that keeps sending sees
167    /// no difference after a moment, while a spoofer that rotates sources, or
168    /// pushes its own entry out of a full table, gets this much per entry instead
169    /// of a full burst.
170    pub fn new_source_burst(mut self, datagrams: u32) -> UdpOptions {
171        self.first = datagrams;
172        self
173    }
174
175    /// The budget of the whole socket ([`UdpBudget::GLOBAL_DEFAULT`] by
176    /// default): what all sources together may send, so a flood from many
177    /// sources, spoofed or not, reaches the caller at this rate at most.
178    pub fn global_budget(mut self, budget: UdpBudget) -> UdpOptions {
179        self.global = budget;
180        self
181    }
182
183    /// How many sources are tracked (65,536 by default): budgets per source
184    /// prefix and send allowances per address, each table bounded by this,
185    /// about 200 bytes per source in all (12.5 MiB for a full default table).
186    pub fn source_table(mut self, entries: u32) -> UdpOptions {
187        self.table = entries;
188        self
189    }
190
191    /// `IPV6_V6ONLY` for an IPv6 address (on by default). Off, an IPv6 socket also
192    /// receives IPv4; sources are reported as IPv4 and replies to them work.
193    /// Reports each datagram's destination address in [`Datagram::destination`], for a
194    /// socket bound to a wildcard that must answer from the address it was asked on.
195    /// One `recvmsg` per datagram instead of `recvfrom`. Unix only: `bind_with` fails
196    /// with `Unsupported` on Windows, and `recv_batch` does not fill it.
197    pub fn packet_info(mut self, on: bool) -> UdpOptions {
198        self.packet_info = on;
199        self
200    }
201
202    /// `IPV6_V6ONLY` for IPv6 addresses (on by default).
203    pub fn ipv6_only(mut self, on: bool) -> UdpOptions {
204        self.ipv6_only = on;
205        self
206    }
207
208    fn validate(&self) -> Result<(), NetError> {
209        let invalid = |field, reason| Err(NetError::InvalidConfig { field, reason });
210        if self.factor == 0 {
211            return invalid("amplification_factor", ConfigReason::Zero);
212        }
213        if self.factor > 3 {
214            return invalid("amplification_factor", ConfigReason::TooLarge { max: 3 });
215        }
216        if self.window < Duration::from_secs(1) {
217            return invalid("amplification_window", ConfigReason::TooSmall { min: 1 });
218        }
219        if self.window > Duration::from_secs(MAX_WINDOW_SECS) {
220            return invalid(
221                "amplification_window",
222                ConfigReason::TooLarge {
223                    max: MAX_WINDOW_SECS,
224                },
225            );
226        }
227        if self.verified_for < Duration::from_secs(1) {
228            return invalid("verification_lifetime", ConfigReason::TooSmall { min: 1 });
229        }
230        if self.verified_for > Duration::from_secs(MAX_VERIFIED_SECS) {
231            return invalid(
232                "verification_lifetime",
233                ConfigReason::TooLarge {
234                    max: MAX_VERIFIED_SECS,
235                },
236            );
237        }
238        if self.table == 0 {
239            return invalid("source_table", ConfigReason::Zero);
240        }
241        if self.verified_table == 0 {
242            return invalid("verified_table", ConfigReason::Zero);
243        }
244        if self.first == 0 {
245            return invalid("new_source_burst", ConfigReason::Zero);
246        }
247        for (field, b) in [
248            ("source_budget", self.source),
249            ("global_budget", self.global),
250        ] {
251            if b.datagrams_per_sec == 0 || b.bytes_per_sec == 0 || b.burst == 0 {
252                return invalid(field, ConfigReason::Zero);
253            }
254        }
255        Ok(())
256    }
257}
258
259/// One received datagram.
260///
261/// ```
262/// let d = net_io::Datagram { len: 3, from: "127.0.0.1:9".parse().unwrap(), truncated: false, destination: None };
263/// assert!(!d.truncated);
264/// ```
265#[derive(Clone, Copy, Debug, PartialEq, Eq)]
266pub struct Datagram {
267    /// Its length. When `truncated`: the real length on Linux, the bytes copied
268    /// (the buffer's length) elsewhere; never index the buffer with it then.
269    pub len: usize,
270    /// Its source, normalized.
271    pub from: SocketAddr,
272    /// It did not fit the buffer and was cut.
273    pub truncated: bool,
274    /// The local address it was sent to (packet info, `0.6.0`; always `None` before).
275    pub destination: Option<IpAddr>,
276}
277
278/// Counters of one socket since it was bound.
279///
280/// ```
281/// let s = net_io::UdpSocket::bind("127.0.0.1:0")?.stats();
282/// assert_eq!(s.received, 0);
283/// # Ok::<(), net_io::NetError>(())
284/// ```
285#[non_exhaustive]
286#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
287pub struct UdpStats {
288    /// Datagrams returned to the caller.
289    pub received: u64,
290    /// Datagrams sent.
291    pub sent: u64,
292    /// Datagrams read and dropped because their source or the socket was over budget.
293    pub dropped: u64,
294    /// Sends refused by the amplification guard.
295    pub refused: u64,
296    /// Datagrams returned truncated.
297    pub truncated: u64,
298    /// ICMP error reports read from the socket and ignored.
299    pub icmp_errors: u64,
300    /// Datagrams from sources that found the table full (the shared overflow budget).
301    pub overflow: u64,
302    /// Sources (prefixes of [`UdpOptions::source_prefix`]) with a budget now.
303    pub sources: u32,
304}
305
306/// A token bucket in micro-tokens: one token per datagram, one per byte.
307#[derive(Clone, Copy, Debug)]
308struct Bucket {
309    datagrams: u64,
310    bytes: u64,
311    at: Instant,
312}
313
314const MICRO: u64 = 1_000_000;
315
316impl Bucket {
317    fn full(budget: &UdpBudget, now: Instant) -> Bucket {
318        Bucket {
319            datagrams: u64::from(budget.burst) * MICRO,
320            bytes: u64::from(budget.bytes_per_sec) * MICRO,
321            at: now,
322        }
323    }
324
325    /// A bucket for a source new to the table: `first` datagrams (at most the
326    /// burst) and the same share of the byte bucket.
327    fn starting(budget: &UdpBudget, first: u32, now: Instant) -> Bucket {
328        let burst = u64::from(budget.burst.max(1));
329        let first = u64::from(first.min(budget.burst));
330        Bucket {
331            datagrams: first * MICRO,
332            bytes: u64::from(budget.bytes_per_sec) * first / burst * MICRO,
333            at: now,
334        }
335    }
336
337    /// Refills for the time passed and takes one datagram of `len` bytes.
338    fn take(&mut self, budget: &UdpBudget, len: usize, now: Instant) -> bool {
339        // Micro-tokens per microsecond equal tokens per second; a gap of more
340        // than 1,000 s refills the buckets completely anyway.
341        let us = now
342            .saturating_duration_since(self.at)
343            .as_micros()
344            .min(1_000_000_000) as u64;
345        self.at = now;
346        let cap_d = u64::from(budget.burst) * MICRO;
347        let cap_b = u64::from(budget.bytes_per_sec) * MICRO;
348        self.datagrams = (self.datagrams + us * u64::from(budget.datagrams_per_sec)).min(cap_d);
349        self.bytes = (self.bytes + us * u64::from(budget.bytes_per_sec)).min(cap_b);
350        let need_b = (len as u64).saturating_mul(MICRO);
351        if self.datagrams >= MICRO && self.bytes >= need_b {
352            self.datagrams -= MICRO;
353            self.bytes -= need_b;
354            true
355        } else {
356            false
357        }
358    }
359}
360
361/// The send allowance of one source address: bytes received from it and sent to
362/// it, over the current and the previous window.
363#[derive(Clone, Copy, Debug)]
364struct Allowance {
365    received: [u64; 2],
366    sent: [u64; 2],
367    window_at: Instant,
368}
369
370impl Allowance {
371    fn new(now: Instant) -> Allowance {
372        Allowance {
373            received: [0; 2],
374            sent: [0; 2],
375            window_at: now,
376        }
377    }
378
379    /// Index 0 is the current window, 1 the previous one.
380    fn roll(&mut self, window: Duration, now: Instant) {
381        let gone = now.saturating_duration_since(self.window_at);
382        if gone >= window.saturating_mul(2) {
383            self.received = [0; 2];
384            self.sent = [0; 2];
385            self.window_at = now;
386        } else if gone >= window {
387            self.received = [0, self.received[0]];
388            self.sent = [0, self.sent[0]];
389            self.window_at = self.window_at.checked_add(window).unwrap_or(now);
390        }
391    }
392}
393
394/// A peer the application verified: its address and port, until a deadline.
395#[derive(Clone, Copy, Debug)]
396struct Proof {
397    key: PeerKey,
398    until: Instant,
399    /// Set by a verification, cleared by the hand.
400    referenced: bool,
401}
402
403/// A verified peer: the normalized IP and the port. Flow label and scope are not
404/// part of it.
405type PeerKey = (IpAddr, u16);
406
407fn peer_key(peer: SocketAddr) -> PeerKey {
408    (normalize(peer.ip()), peer.port())
409}
410
411/// How many entries one insertion may look at before it gives up and uses the
412/// overflow budget.
413const SWEEP: usize = 64;
414
415/// How far the hand moves for each datagram from a source already in a full
416/// table. Above 1, so a spoofer that touches each of its entries once per
417/// revolution cannot keep them all recently used.
418const TURN: usize = 2;
419
420/// The longest amplification window (1 hour).
421const MAX_WINDOW_SECS: u64 = 3_600;
422
423/// The longest verification lifetime (1 day).
424const MAX_VERIFIED_SECS: u64 = 86_400;
425
426/// A bounded map with CLOCK eviction: a hash index over a slab, a hand, and a
427/// recently-used bit per entry.
428#[derive(Debug)]
429struct Clock<K, V> {
430    index: HashMap<K, u32>,
431    slots: Vec<Slot<K, V>>,
432    hand: usize,
433    cap: usize,
434}
435
436#[derive(Clone, Copy, Debug)]
437struct Slot<K, V> {
438    key: K,
439    value: V,
440    /// Set by an admitted datagram, cleared by the hand.
441    referenced: bool,
442}
443
444impl<K: Copy + Eq + Hash, V> Clock<K, V> {
445    fn new(cap: u32) -> Clock<K, V> {
446        Clock {
447            index: HashMap::new(),
448            slots: Vec::new(),
449            hand: 0,
450            cap: cap as usize,
451        }
452    }
453
454    fn get(&self, key: &K) -> Option<usize> {
455        self.index.get(key).map(|&i| i as usize)
456    }
457
458    /// Finds `key`, or makes room for it holding `value`; the flag says it was
459    /// already there. A newcomer takes the first entry the hand finds not
460    /// recently used, within [`SWEEP`] looks; `None` when there is none.
461    fn find_or_insert(&mut self, key: K, value: V) -> Option<(usize, bool)> {
462        if let Some(i) = self.get(&key) {
463            return Some((i, true));
464        }
465        if self.slots.len() < self.cap {
466            self.slots.push(Slot {
467                key,
468                value,
469                referenced: false,
470            });
471            let i = self.slots.len() - 1;
472            self.index.insert(key, i as u32);
473            return Some((i, false));
474        }
475        let n = self.slots.len();
476        for _ in 0..SWEEP.min(2 * n) {
477            let i = self.hand;
478            self.hand = (self.hand + 1) % n;
479            let s = &mut self.slots[i];
480            if s.referenced {
481                s.referenced = false;
482                continue;
483            }
484            self.index.remove(&s.key);
485            *s = Slot {
486                key,
487                value,
488                referenced: false,
489            };
490            self.index.insert(key, i as u32);
491            return Some((i, false));
492        }
493        None
494    }
495
496    /// While the table is full, moves the hand [`TURN`] entries: the sources'
497    /// own traffic ages the table, not only newcomers.
498    fn turn(&mut self) {
499        let n = self.slots.len();
500        if n < self.cap || n == 0 {
501            return;
502        }
503        for _ in 0..TURN {
504            self.slots[self.hand].referenced = false;
505            self.hand = (self.hand + 1) % n;
506        }
507    }
508}
509
510/// The budgets of source prefixes and the send allowances of source addresses,
511/// both bounded maps with CLOCK eviction, and the table of verified peers,
512/// bounded the same way.
513#[derive(Debug)]
514struct Guard {
515    budgets: Clock<PrefixKey, Bucket>,
516    allowances: Clock<IpAddr, Allowance>,
517    proofs: HashMap<PeerKey, u32>,
518    proved: Vec<Proof>,
519    proof_hand: usize,
520    overflow: Bucket,
521    global: Bucket,
522    options: UdpOptions,
523}
524
525impl Guard {
526    fn new(options: UdpOptions, now: Instant) -> Guard {
527        Guard {
528            budgets: Clock::new(options.table),
529            allowances: Clock::new(options.table),
530            proofs: HashMap::new(),
531            proved: Vec::new(),
532            proof_hand: 0,
533            overflow: Bucket::full(&options.source, now),
534            global: Bucket::full(&options.global, now),
535            options,
536        }
537    }
538
539    /// Charges a received datagram from `ip` (normalized); `false` drops it.
540    /// `overflow` is set when its prefix found no room in the table. Only an
541    /// admitted datagram marks its entries recently used and counts toward the
542    /// send allowance of its address.
543    fn admit(&mut self, ip: IpAddr, len: usize, now: Instant, overflow: &mut bool) -> bool {
544        let source = self.options.source;
545        let key = PrefixKey::of(ip, self.options.prefix);
546        let fresh = Bucket::starting(&source, self.options.first, now);
547        let at = match self.budgets.find_or_insert(key, fresh) {
548            Some((i, known)) => {
549                if known {
550                    self.budgets.turn();
551                }
552                if !self.budgets.slots[i].value.take(&source, len, now) {
553                    return false;
554                }
555                Some(i)
556            }
557            None => {
558                *overflow = true;
559                if !self.overflow.take(&source, len, now) {
560                    return false;
561                }
562                None
563            }
564        };
565        if !self.global.take(&self.options.global, len, now) {
566            return false;
567        }
568        // A prefix with no room shares the overflow budget, and its addresses get
569        // no send allowance: strangers in a full table could otherwise pool one.
570        let Some(i) = at else { return true };
571        self.budgets.slots[i].referenced = true;
572        if let Some((j, known)) = self.allowances.find_or_insert(ip, Allowance::new(now)) {
573            if known {
574                self.allowances.turn();
575            }
576            let window = self.options.window;
577            let s = &mut self.allowances.slots[j];
578            s.referenced = true;
579            s.value.roll(window, now);
580            s.value.received[0] = s.value.received[0].saturating_add(len as u64);
581        }
582        true
583    }
584
585    /// Whether `len` bytes may go to `to` now. A verified peer is not limited; to
586    /// anyone else the bytes are charged against the allowance of its IP, so a
587    /// short send leaves it smaller, never larger.
588    fn charge(&mut self, to: SocketAddr, len: usize, now: Instant) -> bool {
589        if self.is_verified(to, now) {
590            return true;
591        }
592        let Some(i) = self.allowances.get(&normalize(to.ip())) else {
593            return len == 0;
594        };
595        let window = self.options.window;
596        let factor = u64::from(self.options.factor);
597        let e = &mut self.allowances.slots[i].value;
598        e.roll(window, now);
599        let allowed = factor.saturating_mul(e.received[0].saturating_add(e.received[1]));
600        let total = e.sent[0]
601            .saturating_add(e.sent[1])
602            .saturating_add(len as u64);
603        if total > allowed {
604            return false;
605        }
606        e.sent[0] = e.sent[0].saturating_add(len as u64);
607        true
608    }
609
610    fn is_verified(&self, peer: SocketAddr, now: Instant) -> bool {
611        self.proofs
612            .get(&peer_key(peer))
613            .is_some_and(|&i| now < self.proved[i as usize].until)
614    }
615
616    /// Verifies `peer` for the lifetime from `now`. A full table gives the place
617    /// of a lapsed or not recently verified peer, or failing that within one
618    /// sweep, of the peer under the hand: a verification always lands.
619    fn verify(&mut self, peer: SocketAddr, now: Instant) {
620        let key = peer_key(peer);
621        let until = now.checked_add(self.options.verified_for).unwrap_or(now);
622        if let Some(&i) = self.proofs.get(&key) {
623            let p = &mut self.proved[i as usize];
624            p.until = until;
625            p.referenced = true;
626            return;
627        }
628        let proof = Proof {
629            key,
630            until,
631            referenced: true,
632        };
633        if self.proved.len() < self.options.verified_table as usize {
634            self.proved.push(proof);
635            self.proofs.insert(key, (self.proved.len() - 1) as u32);
636            return;
637        }
638        let n = self.proved.len();
639        let mut found = None;
640        for _ in 0..SWEEP.min(2 * n) {
641            let i = self.proof_hand;
642            self.proof_hand = (i + 1) % n;
643            let p = &mut self.proved[i];
644            if now >= p.until || !p.referenced {
645                found = Some(i);
646                break;
647            }
648            p.referenced = false;
649        }
650        let at = found.unwrap_or_else(|| {
651            let i = self.proof_hand;
652            self.proof_hand = (i + 1) % n;
653            i
654        });
655        let old = self.proved[at].key;
656        self.proofs.remove(&old);
657        self.proved[at] = proof;
658        self.proofs.insert(key, at as u32);
659    }
660
661    /// Ends `peer`'s verification now.
662    fn forget(&mut self, peer: SocketAddr, now: Instant) {
663        if let Some(&i) = self.proofs.get(&peer_key(peer)) {
664            let p = &mut self.proved[i as usize];
665            p.until = now;
666            p.referenced = false;
667        }
668    }
669}
670
671/// A UDP socket with the guard in front of it.
672///
673/// ```no_run
674/// let mut socket = net_io::UdpSocket::bind("0.0.0.0:5353")?;
675/// let mut buf = [0u8; 1500];
676/// loop {
677///     let datagram = socket.recv_from(&mut buf)?;
678///     if datagram.truncated {
679///         continue; // larger than we accept
680///     }
681///     // Replies are limited to the size of what the peer sent until it is verified.
682///     socket.send_to(&buf[..datagram.len], datagram.from)?;
683/// }
684/// # Ok::<(), net_io::NetError>(())
685/// ```
686#[derive(Debug)]
687pub struct UdpSocket {
688    inner: std::net::UdpSocket,
689    guard: Guard,
690    read_timeout: Option<Duration>,
691    /// Set by the server's loop: receives never wait, and one gives up after
692    /// [`DROP_TURN`] datagrams it dropped. Atomic only so that setting it takes
693    /// `&self`; one thread owns the socket.
694    nonblocking: AtomicBool,
695    peer: Option<SocketAddr>,
696    v6: bool,
697    #[cfg_attr(windows, allow(dead_code))]
698    packet_info: bool,
699    stats: UdpStats,
700}
701
702/// A receive buffer of a batch; [`UdpSocket::recv_batch`] fills `datagram`.
703///
704/// ```
705/// let mut bytes = [0u8; 1500];
706/// let slot = net_io::DatagramBuffer::new(&mut bytes);
707/// assert!(slot.datagram.is_none());
708/// ```
709#[derive(Debug)]
710pub struct DatagramBuffer<'a> {
711    /// Where the bytes land.
712    pub buf: &'a mut [u8],
713    /// What arrived; `None` for a slot not filled, or dropped over budget.
714    pub datagram: Option<Datagram>,
715}
716
717impl<'a> DatagramBuffer<'a> {
718    /// An empty slot over `buf`.
719    #[must_use]
720    pub fn new(buf: &'a mut [u8]) -> DatagramBuffer<'a> {
721        DatagramBuffer {
722            buf,
723            datagram: None,
724        }
725    }
726}
727
728/// One datagram of a batch to send.
729///
730/// ```
731/// let d = net_io::OutgoingDatagram { bytes: b"hi", to: "127.0.0.1:9".parse().unwrap() };
732/// assert_eq!(d.bytes.len(), 2);
733/// ```
734#[derive(Clone, Copy, Debug)]
735pub struct OutgoingDatagram<'a> {
736    /// The bytes.
737    pub bytes: &'a [u8],
738    /// The destination.
739    pub to: SocketAddr,
740}
741
742/// Which interface joins a multicast group.
743///
744/// ```
745/// let any = net_io::MulticastInterface::Any;
746/// # let _ = any;
747/// ```
748#[non_exhaustive]
749#[derive(Clone, Copy, Debug, PartialEq, Eq)]
750pub enum MulticastInterface {
751    /// The one the OS picks.
752    Any,
753    /// The IPv4 interface with this address.
754    V4(Ipv4Addr),
755    /// The IPv6 interface with this index.
756    V6Index(u32),
757}
758
759impl UdpSocket {
760    /// Binds with [`UdpOptions::new`]. The first resolved address that binds wins.
761    ///
762    /// # Errors
763    ///
764    /// `AddrInUse`, `AddrNotAvailable`, `PermissionDenied`, `NoAddresses`, `Bind`.
765    pub fn bind<A: ToSocketAddrs>(addr: A) -> Result<UdpSocket, NetError> {
766        UdpSocket::bind_with(addr, UdpOptions::new())
767    }
768
769    /// Binds with `options`.
770    ///
771    /// # Errors
772    ///
773    /// As [`UdpSocket::bind`]; `InvalidConfig` for an option out of range.
774    pub fn bind_with<A: ToSocketAddrs>(
775        addr: A,
776        options: UdpOptions,
777    ) -> Result<UdpSocket, NetError> {
778        options.validate()?;
779        let addrs: Vec<SocketAddr> = addr
780            .to_socket_addrs()
781            .map_err(|e| NetError::Os {
782                op: "resolve",
783                source: e,
784            })?
785            .collect();
786        let mut last = NetError::NoAddresses;
787        if options.packet_info && !cfg!(unix) {
788            return Err(NetError::Unsupported {
789                feature: "UDP packet info",
790                platform: std::env::consts::OS,
791            });
792        }
793        let packet_info = options.packet_info;
794        for a in addrs {
795            match sys::udp_bind(a, options.ipv6_only) {
796                Ok(inner) => {
797                    #[cfg(unix)]
798                    if packet_info {
799                        sys::udp_packet_info(inner.sock(), a.is_ipv6())
800                            .map_err(|e| NetError::from_os("setsockopt", e))?;
801                    }
802                    return Ok(UdpSocket {
803                        inner,
804                        guard: Guard::new(options, Instant::now()),
805                        read_timeout: None,
806                        nonblocking: AtomicBool::new(false),
807                        peer: None,
808                        v6: a.is_ipv6(),
809                        packet_info,
810                        stats: UdpStats::default(),
811                    });
812                }
813                Err(e) => last = crate::tcp::bind_error(a, e),
814            }
815        }
816        Err(last)
817    }
818
819    /// Receives one datagram within the budgets. Datagrams over budget are read,
820    /// dropped, and counted; ICMP error reports about earlier sends (port, host,
821    /// or network unreachable, time exceeded, a parameter problem) are counted and
822    /// never end the socket. Under a flood the call returns within twice the read
823    /// timeout.
824    ///
825    /// # Errors
826    ///
827    /// `TimedOut { kind: Read }` (only with a read timeout), `Os`.
828    pub fn recv_from(&mut self, buf: &mut [u8]) -> Result<Datagram, NetError> {
829        let bounded = self.nonblocking.load(Ordering::Relaxed);
830        self.recv_bounded(buf, bounded)
831    }
832
833    /// As [`UdpSocket::recv_from`]; `bounded` (a socket that never waits) also
834    /// returns `TimedOut` after [`DROP_TURN`] datagrams dropped or reports skipped,
835    /// as if nothing were ready, so a flood over budget cannot hold the caller's
836    /// loop away from its other checks.
837    fn recv_bounded(&mut self, buf: &mut [u8], bounded: bool) -> Result<Datagram, NetError> {
838        let timed_out = || {
839            Err(NetError::TimedOut {
840                kind: TimeoutKind::Read,
841            })
842        };
843        // A timeout past the clock's range has no deadline.
844        let deadline = self
845            .read_timeout
846            .and_then(|t| Instant::now().checked_add(t));
847        let mut skipped = 0u32;
848        loop {
849            let (len, from, truncated, destination) = match self.recv_one(buf) {
850                Ok(got) => got,
851                Err(e) => match e.kind() {
852                    io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut => return timed_out(),
853                    io::ErrorKind::Interrupted => continue,
854                    _ if icmp_report(&e) => {
855                        // About an earlier send: never fatal (edge case 92).
856                        self.stats.icmp_errors += 1;
857                        skipped += 1;
858                        if past(deadline) || (bounded && skipped >= DROP_TURN) {
859                            return timed_out();
860                        }
861                        continue;
862                    }
863                    _ => return Err(NetError::from_os("recvfrom", e)),
864                },
865            };
866            let from = crate::addr::normalize_socket(from);
867            if !self.admit(from, len, truncated) {
868                skipped += 1;
869                if past(deadline) || (bounded && skipped >= DROP_TURN) {
870                    return timed_out();
871                }
872                continue;
873            }
874            return Ok(Datagram {
875                len,
876                from,
877                truncated,
878                destination,
879            });
880        }
881    }
882
883    fn recv_one(
884        &mut self,
885        buf: &mut [u8],
886    ) -> io::Result<(usize, SocketAddr, bool, Option<IpAddr>)> {
887        #[cfg(unix)]
888        if self.packet_info {
889            return sys::udp_recv_with_destination(self.inner.sock(), buf);
890        }
891        let (len, from, truncated) = sys::udp_recv_from(self.inner.sock(), buf)?;
892        Ok((len, from, truncated, None))
893    }
894
895    /// Charges a datagram to its source and counts it.
896    fn admit(&mut self, from: SocketAddr, len: usize, truncated: bool) -> bool {
897        let mut overflow = false;
898        let admitted = self
899            .guard
900            .admit(from.ip(), len, Instant::now(), &mut overflow);
901        if overflow {
902            self.stats.overflow += 1;
903        }
904        if !admitted {
905            self.stats.dropped += 1;
906            return false;
907        }
908        self.stats.received += 1;
909        if truncated {
910            self.stats.truncated += 1;
911        }
912        true
913    }
914
915    /// Waits for a datagram, then takes what else is ready, up to `slots.len()`
916    /// (64 at most). Each datagram passes the budgets as in [`UdpSocket::recv_from`]:
917    /// one that does not leaves its slot's `datagram` at `None`, so walk every slot.
918    /// One system call on Linux (`recvmmsg`), a loop elsewhere. Returns how many
919    /// slots hold a datagram. Packet info is not reported here.
920    ///
921    /// # Errors
922    ///
923    /// As [`UdpSocket::recv_from`].
924    pub fn recv_batch(&mut self, slots: &mut [DatagramBuffer<'_>]) -> Result<usize, NetError> {
925        for slot in slots.iter_mut() {
926            slot.datagram = None;
927        }
928        if slots.is_empty() {
929            return Ok(0);
930        }
931        self.recv_many(slots)
932    }
933
934    #[cfg(target_os = "linux")]
935    fn recv_many(&mut self, slots: &mut [DatagramBuffer<'_>]) -> Result<usize, NetError> {
936        let count = slots.len().min(sys::BATCH_MAX);
937        let mut got = [None; sys::BATCH_MAX];
938        let n = loop {
939            let received = {
940                let mut bufs: [&mut [u8]; sys::BATCH_MAX] = std::array::from_fn(|_| &mut [][..]);
941                for (b, slot) in bufs.iter_mut().zip(slots.iter_mut()).take(count) {
942                    *b = &mut *slot.buf;
943                }
944                sys::udp_recv_many(self.inner.sock(), &mut bufs[..count], &mut got)
945            };
946            match received {
947                Ok(n) => break n,
948                Err(e) => match e.kind() {
949                    io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut => {
950                        return Err(NetError::TimedOut {
951                            kind: TimeoutKind::Read,
952                        });
953                    }
954                    io::ErrorKind::Interrupted => {}
955                    _ if icmp_report(&e) => self.stats.icmp_errors += 1,
956                    _ => return Err(NetError::from_os("recvmmsg", e)),
957                },
958            }
959        };
960        let mut filled = 0;
961        for (slot, r) in slots.iter_mut().zip(got.iter()).take(n) {
962            let Some(r) = r else { continue };
963            let from = crate::addr::normalize_socket(r.from);
964            if self.admit(from, r.len, r.truncated) {
965                slot.datagram = Some(Datagram {
966                    len: r.len,
967                    from,
968                    truncated: r.truncated,
969                    destination: None,
970                });
971                filled += 1;
972            }
973        }
974        Ok(filled)
975    }
976
977    #[cfg(not(target_os = "linux"))]
978    fn recv_many(&mut self, slots: &mut [DatagramBuffer<'_>]) -> Result<usize, NetError> {
979        let (first, rest) = match slots.split_first_mut() {
980            Some(parts) => parts,
981            None => return Ok(0),
982        };
983        first.datagram = Some(self.recv_from(first.buf)?);
984        let mut filled = 1;
985        // The rest is what is ready now: the socket stops waiting for them, and
986        // goes back to the mode it was in.
987        let waits = !self.nonblocking.load(Ordering::Relaxed);
988        if waits {
989            self.inner
990                .set_nonblocking(true)
991                .map_err(|e| NetError::from_os("ioctl", e))?;
992        }
993        for slot in rest.iter_mut().take(63) {
994            match self.recv_bounded(slot.buf, true) {
995                Ok(d) => {
996                    slot.datagram = Some(d);
997                    filled += 1;
998                }
999                Err(_) => break,
1000            }
1001        }
1002        if waits {
1003            self.inner
1004                .set_nonblocking(false)
1005                .map_err(|e| NetError::from_os("ioctl", e))?;
1006        }
1007        Ok(filled)
1008    }
1009
1010    /// Sends from the front of `datagrams`, each under the guard of
1011    /// [`UdpSocket::send_to`], until one is refused or the OS takes no more. One system
1012    /// call per 64 on Linux (`sendmmsg`), a loop elsewhere. Returns how many went.
1013    ///
1014    /// # Errors
1015    ///
1016    /// `Limit { which: Amplification }` when the first is refused, `Os`.
1017    pub fn send_batch(&mut self, datagrams: &[OutgoingDatagram<'_>]) -> Result<usize, NetError> {
1018        let mut sent = 0;
1019        while sent < datagrams.len() {
1020            match self.send_some(&datagrams[sent..]) {
1021                Ok(0) => break,
1022                Ok(n) => sent += n,
1023                Err(e) if sent == 0 => return Err(e),
1024                Err(_) => break,
1025            }
1026        }
1027        Ok(sent)
1028    }
1029
1030    /// The guard's prefix of `datagrams`. Charged before the send, so a short send
1031    /// leaves the peer's allowance smaller, never larger.
1032    fn charge(&mut self, datagrams: &[OutgoingDatagram<'_>]) -> Result<usize, NetError> {
1033        let now = Instant::now();
1034        let mut allowed = 0;
1035        for d in datagrams.iter().take(64) {
1036            if !self.guard.charge(d.to, d.bytes.len(), now) {
1037                self.stats.refused += 1;
1038                break;
1039            }
1040            allowed += 1;
1041        }
1042        if allowed == 0 && !datagrams.is_empty() {
1043            return Err(NetError::Limit {
1044                which: LimitKind::Amplification,
1045            });
1046        }
1047        Ok(allowed)
1048    }
1049
1050    #[cfg(target_os = "linux")]
1051    fn send_some(&mut self, datagrams: &[OutgoingDatagram<'_>]) -> Result<usize, NetError> {
1052        let allowed = self.charge(datagrams)?;
1053        let mut wire = [(&[][..], SocketAddr::from(([0, 0, 0, 0], 0))); sys::BATCH_MAX];
1054        for (w, d) in wire.iter_mut().zip(datagrams.iter().take(allowed)) {
1055            *w = (d.bytes, self.wire(d.to));
1056        }
1057        let n = sys::udp_send_many(self.inner.sock(), &wire[..allowed])
1058            .map_err(|e| NetError::from_os("sendmmsg", e))?;
1059        self.stats.sent += n as u64;
1060        Ok(n)
1061    }
1062
1063    #[cfg(not(target_os = "linux"))]
1064    fn send_some(&mut self, datagrams: &[OutgoingDatagram<'_>]) -> Result<usize, NetError> {
1065        let allowed = self.charge(datagrams)?;
1066        let mut n = 0;
1067        for d in &datagrams[..allowed] {
1068            let wire = self.wire(d.to);
1069            if let Err(e) = self.inner.send_to(d.bytes, wire) {
1070                if n == 0 {
1071                    return Err(NetError::from_os("sendto", e));
1072                }
1073                break;
1074            }
1075            self.stats.sent += 1;
1076            n += 1;
1077        }
1078        Ok(n)
1079    }
1080
1081    /// Joins a multicast group. Datagrams to the group then pass the same budgets as
1082    /// any other; a reply to a group member is still under the amplification guard.
1083    ///
1084    /// # Errors
1085    ///
1086    /// `InvalidConfig` when the interface's family is not the group's, `Os`.
1087    pub fn join_multicast(
1088        &self,
1089        group: IpAddr,
1090        interface: MulticastInterface,
1091    ) -> Result<(), NetError> {
1092        let result = match (group, interface) {
1093            (IpAddr::V4(g), MulticastInterface::Any) => {
1094                self.inner.join_multicast_v4(&g, &Ipv4Addr::UNSPECIFIED)
1095            }
1096            (IpAddr::V4(g), MulticastInterface::V4(i)) => self.inner.join_multicast_v4(&g, &i),
1097            (IpAddr::V6(g), MulticastInterface::Any) => self.inner.join_multicast_v6(&g, 0),
1098            (IpAddr::V6(g), MulticastInterface::V6Index(i)) => self.inner.join_multicast_v6(&g, i),
1099            _ => {
1100                return Err(NetError::InvalidConfig {
1101                    field: "interface",
1102                    reason: ConfigReason::Inconsistent,
1103                });
1104            }
1105        };
1106        result.map_err(|e| NetError::from_os("setsockopt", e))
1107    }
1108
1109    /// Receives from the connected peer (see [`UdpSocket::connect`]).
1110    ///
1111    /// # Errors
1112    ///
1113    /// As [`UdpSocket::recv_from`].
1114    pub fn recv(&mut self, buf: &mut [u8]) -> Result<Datagram, NetError> {
1115        self.recv_from(buf)
1116    }
1117
1118    /// Sends one datagram. To an address and port not marked verified, the bytes
1119    /// sent within the window never exceed `factor` times the bytes received
1120    /// from its IP; a source never heard from gets nothing (an empty datagram
1121    /// aside). The bytes are charged before the send.
1122    ///
1123    /// # Errors
1124    ///
1125    /// `Limit { which: Amplification }` (nothing was sent), `Os`.
1126    pub fn send_to(&mut self, buf: &[u8], to: SocketAddr) -> Result<usize, NetError> {
1127        if !self.guard.charge(to, buf.len(), Instant::now()) {
1128            self.stats.refused += 1;
1129            return Err(NetError::Limit {
1130                which: LimitKind::Amplification,
1131            });
1132        }
1133        let wire = self.wire(to);
1134        let n = self
1135            .inner
1136            .send_to(buf, wire)
1137            .map_err(|e| NetError::from_os("sendto", e))?;
1138        self.stats.sent += 1;
1139        Ok(n)
1140    }
1141
1142    /// Sends to the connected peer, under the same guard as [`UdpSocket::send_to`].
1143    ///
1144    /// # Errors
1145    ///
1146    /// `Closed` when not connected; as [`UdpSocket::send_to`].
1147    pub fn send(&mut self, buf: &[u8]) -> Result<usize, NetError> {
1148        let peer = self.peer.ok_or(NetError::Closed)?;
1149        if !self.guard.charge(peer, buf.len(), Instant::now()) {
1150            self.stats.refused += 1;
1151            return Err(NetError::Limit {
1152                which: LimitKind::Amplification,
1153            });
1154        }
1155        let n = self
1156            .inner
1157            .send(buf)
1158            .map_err(|e| NetError::from_os("send", e))?;
1159        self.stats.sent += 1;
1160        Ok(n)
1161    }
1162
1163    /// Fixes the peer: the kernel drops datagrams from other sources, and
1164    /// [`UdpSocket::send`] goes to it.
1165    ///
1166    /// # Errors
1167    ///
1168    /// `Os`.
1169    pub fn connect(&mut self, to: SocketAddr) -> Result<(), NetError> {
1170        self.inner
1171            .connect(self.wire(to))
1172            .map_err(|e| NetError::from_os("connect", e))?;
1173        self.peer = Some(to);
1174        Ok(())
1175    }
1176
1177    /// The protocol proved `peer` can receive at this address and port (a cookie,
1178    /// a handshake, an authenticated datagram): the guard does not limit sends to
1179    /// it for the verification lifetime (60 s by default), counted from the latest
1180    /// call. Call it again each time the protocol proves the peer again; a raw
1181    /// datagram from the address never extends it, since anyone can forge one.
1182    /// Other ports of the same IP stay limited: a new port is a new path.
1183    pub fn mark_verified(&mut self, peer: SocketAddr) {
1184        self.guard.verify(peer, Instant::now());
1185    }
1186
1187    /// The protocol is done with `peer` (its connection closed): sends to it are
1188    /// limited again from now, without waiting for the lifetime to run out.
1189    pub fn forget_verified(&mut self, peer: SocketAddr) {
1190        self.guard.forget(peer, Instant::now());
1191    }
1192
1193    /// How long a receive waits (`None`: forever, the default).
1194    ///
1195    /// # Errors
1196    ///
1197    /// `InvalidConfig` for a zero duration, `Os`.
1198    pub fn set_read_timeout(&mut self, timeout: Option<Duration>) -> Result<(), NetError> {
1199        if timeout == Some(Duration::ZERO) {
1200            return Err(NetError::InvalidConfig {
1201                field: "read_timeout",
1202                reason: ConfigReason::Zero,
1203            });
1204        }
1205        self.inner
1206            .set_read_timeout(timeout)
1207            .map_err(|e| NetError::from_os("setsockopt", e))?;
1208        self.read_timeout = timeout;
1209        Ok(())
1210    }
1211
1212    /// Receives never wait: a server's thread waits in `poll` with its wake channel.
1213    pub(crate) fn set_nonblocking(&self) -> Result<(), NetError> {
1214        self.inner
1215            .set_nonblocking(true)
1216            .map_err(|e| NetError::from_os("ioctl", e))?;
1217        self.nonblocking.store(true, Ordering::Relaxed);
1218        Ok(())
1219    }
1220
1221    pub(crate) fn raw_sock(&self) -> sys::Sock<'_> {
1222        self.inner.sock()
1223    }
1224
1225    /// The bound address.
1226    ///
1227    /// # Errors
1228    ///
1229    /// `Os` when `getsockname` fails.
1230    pub fn local_addr(&self) -> Result<SocketAddr, NetError> {
1231        self.inner
1232            .local_addr()
1233            .map_err(|e| NetError::from_os("getsockname", e))
1234    }
1235
1236    /// Counters since the socket was bound.
1237    #[must_use]
1238    pub fn stats(&self) -> UdpStats {
1239        UdpStats {
1240            sources: self.guard.budgets.slots.len() as u32,
1241            ..self.stats
1242        }
1243    }
1244
1245    /// An IPv4 destination on an IPv6 socket goes out as its IPv4-mapped form.
1246    fn wire(&self, to: SocketAddr) -> SocketAddr {
1247        match to {
1248            SocketAddr::V4(a) if self.v6 => {
1249                SocketAddr::V6(SocketAddrV6::new(a.ip().to_ipv6_mapped(), a.port(), 0, 0))
1250            }
1251            other => other,
1252        }
1253    }
1254}
1255
1256/// A datagram protocol run by a server: one per UDP listener, called on that listener's
1257/// thread, so it needs no locks of its own. Budgets and the amplification guard apply
1258/// before it sees a datagram and on every reply.
1259///
1260/// ```
1261/// use std::net::SocketAddr;
1262/// use net_io::{UdpContext, UdpSession};
1263/// struct Echo;
1264/// impl UdpSession for Echo {
1265///     fn on_datagram(&mut self, cx: &mut UdpContext<'_>, from: SocketAddr, bytes: &[u8]) {
1266///         let _ = cx.send_to(bytes, from);
1267///     }
1268/// }
1269/// ```
1270pub trait UdpSession: Send + 'static {
1271    /// One datagram that passed its budgets.
1272    fn on_datagram(&mut self, cx: &mut UdpContext<'_>, from: SocketAddr, bytes: &[u8]);
1273}
1274
1275/// What a [`UdpSession`] may do during a call.
1276#[derive(Debug)]
1277pub struct UdpContext<'a> {
1278    pub(crate) socket: &'a mut UdpSocket,
1279}
1280
1281impl UdpContext<'_> {
1282    /// Sends a datagram under the guard of [`UdpSocket::send_to`].
1283    ///
1284    /// # Errors
1285    ///
1286    /// As [`UdpSocket::send_to`].
1287    pub fn send_to(&mut self, bytes: &[u8], to: SocketAddr) -> Result<usize, NetError> {
1288        self.socket.send_to(bytes, to)
1289    }
1290
1291    /// As [`UdpSocket::mark_verified`].
1292    pub fn mark_verified(&mut self, peer: SocketAddr) {
1293        self.socket.mark_verified(peer);
1294    }
1295
1296    /// As [`UdpSocket::forget_verified`].
1297    pub fn forget_verified(&mut self, peer: SocketAddr) {
1298        self.socket.forget_verified(peer);
1299    }
1300
1301    /// The time.
1302    #[must_use]
1303    pub fn now(&self) -> Instant {
1304        Instant::now()
1305    }
1306}
1307
1308/// Makes the [`UdpSession`] of each UDP listener; any
1309/// `Fn(&ListenerInfo) -> impl UdpSession` is one.
1310pub trait UdpSessionFactory: Send + Sync + 'static {
1311    /// The session for this listener.
1312    fn open(&self, listener: &crate::tcp::ListenerInfo) -> Box<dyn UdpSession>;
1313}
1314
1315impl<F, S> UdpSessionFactory for F
1316where
1317    F: Fn(&crate::tcp::ListenerInfo) -> S + Send + Sync + 'static,
1318    S: UdpSession,
1319{
1320    fn open(&self, listener: &crate::tcp::ListenerInfo) -> Box<dyn UdpSession> {
1321        Box::new(self(listener))
1322    }
1323}
1324
1325fn past(deadline: Option<Instant>) -> bool {
1326    deadline.is_some_and(|d| Instant::now() >= d)
1327}
1328
1329/// Datagrams a receive that never waits drops over budget (or ICMP reports it
1330/// skips) before it reports nothing ready. The server's loop then waits in `poll`
1331/// again, which returns at once while datagrams are queued: under a flood that is
1332/// one more system call per 64 dropped (an estimated 2% of the cost of reading
1333/// them), and the loop reaches its stop and drain checks in between.
1334const DROP_TURN: u32 = 64;
1335
1336/// Whether a receive error is an ICMP report about an earlier send rather than a
1337/// fault of this socket: port, host, or network unreachable, and on some systems
1338/// host down, protocol unreachable, a parameter problem, or (Windows) time
1339/// exceeded. Only numbers a receive gives for no other reason are here, so a
1340/// lasting fault is never skipped as a report.
1341fn icmp_report(e: &io::Error) -> bool {
1342    use io::ErrorKind as K;
1343    if matches!(
1344        e.kind(),
1345        K::ConnectionRefused | K::ConnectionReset | K::HostUnreachable | K::NetworkUnreachable
1346    ) {
1347        return true;
1348    }
1349    #[cfg(unix)]
1350    {
1351        // EMSGSIZE: an ICMP "fragmentation needed" on a connected socket. A receive
1352        // reports a datagram too large for its buffer as truncated, never so.
1353        use sys::errno::{EHOSTDOWN, EMSGSIZE, ENONET, ENOPROTOOPT, EPROTO};
1354        matches!(
1355            e.raw_os_error(),
1356            Some(EHOSTDOWN | EMSGSIZE | ENONET | ENOPROTOOPT | EPROTO)
1357        )
1358    }
1359    #[cfg(windows)]
1360    {
1361        e.raw_os_error() == Some(sys::errno::WSAENETRESET)
1362    }
1363}
1364
1365#[cfg(unix)]
1366impl std::os::fd::AsFd for UdpSocket {
1367    fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
1368        self.inner.as_fd()
1369    }
1370}
1371
1372#[cfg(windows)]
1373impl std::os::windows::io::AsSocket for UdpSocket {
1374    fn as_socket(&self) -> std::os::windows::io::BorrowedSocket<'_> {
1375        self.inner.as_socket()
1376    }
1377}
1378
1379/// The fuzz target `udp`: arbitrary datagrams, sends, verifications, and clock
1380/// steps against the guard, under three prefix policies. It checks that the
1381/// tables stay consistent and within their bounds, that an allowance has its
1382/// prefix's budget beside it unless the budget table is full, that no peer is verified that a model says is not, that an
1383/// unverified peer is never sent more than the factor times what the guard holds
1384/// as received from it, and that the global budget admits no more than its burst
1385/// plus its rate.
1386#[cfg(any(fuzzing, test))]
1387pub(crate) fn fuzz_udp(data: &[u8]) {
1388    let Some((head, ops)) = data.split_first_chunk::<5>() else {
1389        return;
1390    };
1391    let global = UdpBudget {
1392        datagrams_per_sec: u32::from(head[3]) + 1,
1393        bytes_per_sec: u32::from(head[3]) * 64 + 64,
1394        burst: u32::from(head[4] % 16) + 1,
1395    };
1396    let options = UdpOptions::new()
1397        .source_table(u32::from(head[0] % 16) + 1)
1398        .verified_table(u32::from(head[1] % 8) + 1)
1399        .amplification_factor(head[2] % 3 + 1)
1400        .amplification_window(Duration::from_secs(u64::from(head[2] >> 2) % 8 + 1))
1401        .verification_lifetime(Duration::from_secs(u64::from(head[4] >> 4) + 1))
1402        .source_budget(UdpBudget {
1403            datagrams_per_sec: 20,
1404            bytes_per_sec: 4_000,
1405            burst: 4,
1406        })
1407        .new_source_burst(u32::from(head[2] >> 5) + 1)
1408        .source_prefix(match (head[1] >> 3) & 3 {
1409            1 => PrefixPolicy::HOST,
1410            2 => PrefixPolicy::new(24, 48).unwrap_or(PrefixPolicy::DEFAULT),
1411            _ => PrefixPolicy::DEFAULT,
1412        })
1413        .global_budget(global);
1414    if options.validate().is_err() {
1415        return;
1416    }
1417    let start = Instant::now();
1418    let mut now = start;
1419    let mut guard = Guard::new(options.clone(), now);
1420    // The model: when each peer's verification ends, if it is verified.
1421    let mut proven: HashMap<PeerKey, Instant> = HashMap::new();
1422    let mut admitted = 0u64;
1423    for op in ops.chunks(4) {
1424        let n = op.get(1).copied().unwrap_or(0);
1425        // Mapped and plain forms of the same IPv4 address, and IPv6 addresses.
1426        let host = match n % 3 {
1427            0 => IpAddr::from([10, 0, 0, n >> 2]),
1428            1 => IpAddr::V6(std::net::Ipv4Addr::new(10, 0, 0, n >> 2).to_ipv6_mapped()),
1429            _ => IpAddr::from([0xfd00, 0, 0, 0, 0, 0, 0, u16::from(n >> 2)]),
1430        };
1431        let peer = SocketAddr::new(host, u16::from(op.get(2).copied().unwrap_or(0) % 4));
1432        let arg = usize::from(op.get(3).copied().unwrap_or(0)) * 8;
1433        match op[0] % 6 {
1434            0 => {
1435                let mut overflow = false;
1436                let from = crate::addr::normalize_socket(peer);
1437                if guard.admit(from.ip(), arg, now, &mut overflow) {
1438                    admitted += 1;
1439                }
1440            }
1441            1 => {
1442                let verified = guard.is_verified(peer, now);
1443                let sent = guard.charge(peer, arg, now);
1444                if sent && !verified && arg > 0 {
1445                    let i = guard.allowances.index[&normalize(peer.ip())] as usize;
1446                    let e = &guard.allowances.slots[i].value;
1447                    let allowed = u64::from(options.factor)
1448                        .saturating_mul(e.received[0].saturating_add(e.received[1]));
1449                    assert!(
1450                        e.sent[0].saturating_add(e.sent[1]) <= allowed,
1451                        "sent past the factor"
1452                    );
1453                }
1454            }
1455            2 => {
1456                guard.verify(peer, now);
1457                proven.insert(peer_key(peer), now + options.verified_for);
1458            }
1459            3 => {
1460                guard.forget(peer, now);
1461                proven.remove(&peer_key(peer));
1462            }
1463            4 => now += Duration::from_millis(arg as u64 * 13),
1464            _ => {
1465                let model = proven.get(&peer_key(peer)).is_some_and(|&t| now < t);
1466                assert!(
1467                    model || !guard.is_verified(peer, now),
1468                    "verified without a live proof"
1469                );
1470            }
1471        }
1472        assert_eq!(guard.budgets.index.len(), guard.budgets.slots.len());
1473        assert!(guard.budgets.slots.len() <= options.table as usize);
1474        for (key, &i) in &guard.budgets.index {
1475            assert_eq!(
1476                guard.budgets.slots[i as usize].key, *key,
1477                "index points elsewhere"
1478            );
1479        }
1480        assert_eq!(guard.allowances.index.len(), guard.allowances.slots.len());
1481        assert!(guard.allowances.slots.len() <= options.table as usize);
1482        for (ip, &i) in &guard.allowances.index {
1483            assert_eq!(
1484                guard.allowances.slots[i as usize].key, *ip,
1485                "index points elsewhere"
1486            );
1487            assert!(
1488                guard
1489                    .budgets
1490                    .index
1491                    .contains_key(&PrefixKey::of(*ip, options.prefix))
1492                    || guard.budgets.slots.len() == options.table as usize,
1493                "an allowance with no budget in a table with room"
1494            );
1495        }
1496        assert_eq!(guard.proofs.len(), guard.proved.len());
1497        assert!(guard.proved.len() <= options.verified_table as usize);
1498        for (key, &i) in &guard.proofs {
1499            assert_eq!(guard.proved[i as usize].key, *key, "proof points elsewhere");
1500        }
1501        let elapsed = now.saturating_duration_since(start).as_secs_f64();
1502        let most = f64::from(global.burst) + f64::from(global.datagrams_per_sec) * elapsed + 1.0;
1503        assert!(
1504            admitted as f64 <= most,
1505            "{admitted} admitted, at most {most}"
1506        );
1507    }
1508}
1509
1510#[cfg(test)]
1511mod tests {
1512    use super::*;
1513    use std::net::Ipv6Addr;
1514
1515    fn ip(n: u8) -> IpAddr {
1516        IpAddr::from([10, 0, 0, n])
1517    }
1518
1519    /// The fuzz target's checks on pseudo-random input, so they run in every test
1520    /// build and not only under cargo-fuzz.
1521    #[test]
1522    fn test_guard_holds_under_random_operations() {
1523        let mut x = 0x9e37_79b9_7f4a_7c15u64;
1524        for _ in 0..2_000 {
1525            let len = 5 + (x % 400) as usize;
1526            let data: Vec<u8> = (0..len)
1527                .map(|_| {
1528                    x ^= x << 13;
1529                    x ^= x >> 7;
1530                    x ^= x << 17;
1531                    x as u8
1532                })
1533                .collect();
1534            fuzz_udp(&data);
1535        }
1536    }
1537
1538    #[test]
1539    fn test_bucket_refills_at_its_rate() {
1540        let b = UdpBudget {
1541            datagrams_per_sec: 10,
1542            bytes_per_sec: 1_000,
1543            burst: 2,
1544        };
1545        let t = Instant::now();
1546        let mut bucket = Bucket::full(&b, t);
1547        assert!(bucket.take(&b, 100, t));
1548        assert!(bucket.take(&b, 100, t));
1549        assert!(!bucket.take(&b, 100, t), "burst used up");
1550        // 100 ms refills one datagram.
1551        assert!(bucket.take(&b, 100, t + Duration::from_millis(100)));
1552        // Bytes: the bucket holds one second; 1,001 bytes never pass.
1553        assert!(!bucket.take(&b, 1_001, t + Duration::from_secs(5)));
1554    }
1555
1556    fn at(n: u8, port: u16) -> SocketAddr {
1557        SocketAddr::from(([10, 0, 0, n], port))
1558    }
1559
1560    #[test]
1561    fn test_amplification_factor_one_until_verified() {
1562        // Edge case 94: a 1-byte request, a 2-byte reply refused until verified.
1563        let t = Instant::now();
1564        let mut g = Guard::new(UdpOptions::new(), t);
1565        let mut o = false;
1566        let a = at(1, 1_000);
1567        assert!(!g.charge(a, 1, t), "never heard from");
1568        assert!(g.charge(a, 0, t));
1569        assert!(g.admit(ip(1), 1, t, &mut o));
1570        assert!(!g.charge(a, 2, t));
1571        assert!(g.charge(a, 1, t));
1572        assert!(!g.charge(a, 1, t), "the allowance is spent");
1573        g.verify(a, t);
1574        assert!(g.charge(a, 10_000, t));
1575        assert!(
1576            !g.charge(at(1, 2_000), 1, t),
1577            "another port is not verified, and the IP's allowance is spent"
1578        );
1579    }
1580
1581    #[test]
1582    fn test_amplification_factor_three_and_the_window() {
1583        let t = Instant::now();
1584        let w = Duration::from_secs(10);
1585        let mut g = Guard::new(UdpOptions::new().amplification_factor(3), t);
1586        let mut o = false;
1587        assert!(g.admit(ip(1), 100, t, &mut o));
1588        assert!(!g.charge(at(1, 9), 301, t));
1589        assert!(g.charge(at(1, 9), 300, t));
1590        assert!(!g.charge(at(1, 9), 1, t));
1591        // Just after the window edge the previous window still counts.
1592        assert!(g.admit(ip(2), 100, t, &mut o));
1593        assert!(g.charge(at(2, 9), 300, t + w + Duration::from_millis(1)));
1594        // Two windows later it is gone.
1595        assert!(g.admit(ip(3), 100, t, &mut o));
1596        assert!(!g.charge(at(3, 9), 1, t + 3 * w));
1597    }
1598
1599    #[test]
1600    fn test_source_budget_drops_and_others_pass() {
1601        let t = Instant::now();
1602        let budget = UdpBudget {
1603            datagrams_per_sec: 1,
1604            bytes_per_sec: 10_000,
1605            burst: 3,
1606        };
1607        let mut g = Guard::new(UdpOptions::new().source_budget(budget), t);
1608        let mut o = false;
1609        let passed = (0..10).filter(|_| g.admit(ip(1), 10, t, &mut o)).count();
1610        assert_eq!(passed, 3);
1611        assert!(
1612            g.admit(ip(2), 10, t, &mut o),
1613            "another source has its own budget"
1614        );
1615        assert!(!o);
1616    }
1617
1618    #[test]
1619    fn test_global_budget_caps_every_source() {
1620        let t = Instant::now();
1621        let global = UdpBudget {
1622            datagrams_per_sec: 1,
1623            bytes_per_sec: 10_000,
1624            burst: 4,
1625        };
1626        let mut g = Guard::new(UdpOptions::new().global_budget(global), t);
1627        let mut o = false;
1628        let passed = (1..=10).filter(|&n| g.admit(ip(n), 10, t, &mut o)).count();
1629        assert_eq!(passed, 4);
1630    }
1631
1632    #[test]
1633    fn test_full_table_evicts_strangers() {
1634        // Edge case 93.
1635        let t = Instant::now();
1636        let mut g = Guard::new(UdpOptions::new().source_table(4), t);
1637        let mut o = false;
1638        for n in 1..=4 {
1639            assert!(g.admit(ip(n), 10, t, &mut o));
1640        }
1641        // Recently used entries survive one pass of the hand; the newcomer takes
1642        // the first entry it then finds.
1643        assert!(g.admit(ip(5), 10, t, &mut o));
1644        assert!(!o, "an entry was evicted");
1645        assert!(g.budgets.index.contains_key(&PrefixKey::exact(ip(5))));
1646        assert_eq!(g.budgets.slots.len(), 4);
1647    }
1648
1649    #[test]
1650    fn test_overflow_strangers_get_nothing_and_verified_peers_stay_answered() {
1651        let t = Instant::now();
1652        let mut g = Guard::new(UdpOptions::new().source_table(64), t);
1653        let mut o = false;
1654        let source = |n: u8| IpAddr::from([10, 0, 1, n]);
1655        for n in 0..64u8 {
1656            assert!(g.admit(source(n), 10, t, &mut o));
1657        }
1658        let peer = SocketAddr::from((source(0), 7));
1659        g.verify(peer, t);
1660        assert!(g.admit(ip(200), 10, t, &mut o));
1661        assert!(o, "no room: the overflow budget");
1662        assert!(
1663            !g.charge(at(200, 9), 1, t),
1664            "an overflow stranger gets no allowance"
1665        );
1666        assert!(g.charge(peer, 10_000, t), "verification needs no entry");
1667    }
1668
1669    /// Verification proves one address and port, for its lifetime from the
1670    /// latest proof, and ends early when the application says so.
1671    #[test]
1672    fn test_verification_is_per_port_and_expires() {
1673        let t = Instant::now();
1674        let s = Duration::from_secs;
1675        let mut g = Guard::new(UdpOptions::new(), t);
1676        let a = at(1, 1_000);
1677        g.verify(a, t);
1678        assert!(g.charge(a, 10_000, t));
1679        assert!(!g.charge(at(1, 2_000), 1, t), "another port is a new path");
1680        assert!(g.charge(a, 10_000, t + s(59)));
1681        assert!(!g.charge(a, 1, t + s(61)), "the proof lapsed");
1682        g.verify(a, t + s(61));
1683        g.verify(a, t + s(100));
1684        assert!(
1685            g.charge(a, 10_000, t + s(159)),
1686            "a new proof starts it again"
1687        );
1688        g.forget(a, t + s(150));
1689        assert!(!g.charge(a, 1, t + s(151)));
1690        // IPv4-mapped and plain IPv4 are one peer.
1691        let mapped = SocketAddr::from((Ipv4Addr::new(10, 0, 0, 1).to_ipv6_mapped(), 3_000));
1692        g.verify(mapped, t);
1693        assert!(g.charge(at(1, 3_000), 10_000, t));
1694    }
1695
1696    /// The verified table is bounded; a full one gives up a lapsed peer first,
1697    /// then one not recently verified.
1698    #[test]
1699    fn test_verified_table_is_bounded() {
1700        let t = Instant::now();
1701        let s = Duration::from_secs;
1702        let mut g = Guard::new(UdpOptions::new().verified_table(2), t);
1703        g.verify(at(1, 1), t);
1704        g.verify(at(2, 1), t);
1705        g.verify(at(3, 1), t);
1706        assert_eq!(g.proved.len(), 2);
1707        assert!(!g.is_verified(at(1, 1), t));
1708        assert!(g.is_verified(at(2, 1), t) && g.is_verified(at(3, 1), t));
1709        let mut g = Guard::new(
1710            UdpOptions::new()
1711                .verified_table(2)
1712                .verification_lifetime(s(1)),
1713            t,
1714        );
1715        g.verify(at(1, 1), t);
1716        g.verify(at(2, 1), t + s(2));
1717        g.verify(at(3, 1), t + s(2));
1718        assert!(g.is_verified(at(2, 1), t + s(2)), "the lapsed one went");
1719        assert!(g.is_verified(at(3, 1), t + s(2)));
1720    }
1721
1722    /// Verified peers never lock newcomers out of the table.
1723    #[test]
1724    fn test_verified_peers_leave_room_for_newcomers() {
1725        let t = Instant::now();
1726        let mut g = Guard::new(UdpOptions::new().source_table(4), t);
1727        let mut o = false;
1728        for n in 1..=4 {
1729            assert!(g.admit(ip(n), 10, t, &mut o));
1730            g.verify(at(n, 1), t);
1731        }
1732        let later = t + Duration::from_millis(10);
1733        assert!(g.admit(ip(9), 100, later, &mut o));
1734        assert!(!o, "a newcomer finds a slot");
1735        assert!(g.charge(at(9, 1), 100, later), "and its allowance");
1736    }
1737
1738    /// A datagram dropped over budget does not keep its entry recently used.
1739    #[test]
1740    fn test_dropped_datagrams_do_not_keep_entries() {
1741        let t = Instant::now();
1742        let budget = UdpBudget {
1743            datagrams_per_sec: 1,
1744            bytes_per_sec: 10_000,
1745            burst: 1,
1746        };
1747        let options = UdpOptions::new().source_table(64).source_budget(budget);
1748        let mut g = Guard::new(options, t);
1749        let mut o = false;
1750        for n in 0..64u8 {
1751            assert!(g.admit(IpAddr::from([10, 0, 1, n]), 10, t, &mut o));
1752        }
1753        // A newcomer's sweep clears every bit and finds nothing.
1754        assert!(g.admit(ip(200), 10, t, &mut o));
1755        assert!(o);
1756        // Every source sends again at once and is dropped over its budget.
1757        for n in 0..64u8 {
1758            assert!(!g.admit(IpAddr::from([10, 0, 1, n]), 10, t, &mut o));
1759        }
1760        let mut o = false;
1761        assert!(g.admit(ip(201), 10, t, &mut o));
1762        assert!(!o, "the dropped traffic did not keep the table full");
1763    }
1764
1765    /// A full table's own traffic turns the hand, so a spoofer touching every
1766    /// entry once per revolution cannot hold every slot.
1767    #[test]
1768    fn test_full_table_traffic_turns_the_hand() {
1769        let t = Instant::now();
1770        let mut g = Guard::new(UdpOptions::new().source_table(64), t);
1771        let mut o = false;
1772        for n in 0..64u8 {
1773            assert!(g.admit(IpAddr::from([10, 0, 1, n]), 10, t, &mut o));
1774        }
1775        assert!(g.admit(ip(200), 10, t, &mut o));
1776        assert!(o, "every entry was recently used");
1777        // The spoofer touches each entry once, admitted.
1778        let later = t + Duration::from_secs(1);
1779        for n in 0..64u8 {
1780            assert!(g.admit(IpAddr::from([10, 0, 1, n]), 10, later, &mut o));
1781        }
1782        let mut o = false;
1783        assert!(g.admit(ip(201), 10, later, &mut o));
1784        assert!(!o, "a newcomer finds a slot");
1785    }
1786
1787    /// A window, lifetime, or read timeout too large for the clock is refused or
1788    /// clamped, never a panic.
1789    #[test]
1790    fn test_huge_durations_never_panic() {
1791        for options in [
1792            UdpOptions::new().amplification_window(Duration::MAX),
1793            UdpOptions::new().amplification_window(Duration::from_secs(3_601)),
1794            UdpOptions::new().verification_lifetime(Duration::MAX),
1795            UdpOptions::new().verification_lifetime(Duration::from_millis(999)),
1796            UdpOptions::new().verified_table(0),
1797        ] {
1798            assert!(matches!(
1799                options.validate(),
1800                Err(NetError::InvalidConfig { .. })
1801            ));
1802        }
1803        // The guard itself saturates, validated or not.
1804        let t = Instant::now();
1805        let options = UdpOptions::new()
1806            .amplification_window(Duration::MAX)
1807            .verification_lifetime(Duration::MAX);
1808        let mut g = Guard::new(options, t);
1809        let mut o = false;
1810        assert!(g.admit(ip(1), 10, t, &mut o));
1811        assert!(g.charge(at(1, 1), 10, t + Duration::from_secs(1)));
1812        g.verify(at(1, 1), t);
1813        let mut s = UdpSocket::bind("127.0.0.1:0").unwrap();
1814        s.set_read_timeout(Some(Duration::MAX)).unwrap();
1815        let c = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
1816        c.send_to(b"hi", s.local_addr().unwrap()).unwrap();
1817        let mut buf = [0u8; 8];
1818        assert_eq!(s.recv_from(&mut buf).unwrap().len, 2);
1819    }
1820
1821    /// A verified address does not verify another port of the same IP, through
1822    /// the socket.
1823    #[test]
1824    fn test_verified_port_does_not_cover_the_ip() {
1825        let mut server = UdpSocket::bind("127.0.0.1:0").unwrap();
1826        server
1827            .set_read_timeout(Some(Duration::from_secs(5)))
1828            .unwrap();
1829        let a = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
1830        let b = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
1831        a.send_to(b"hello", server.local_addr().unwrap()).unwrap();
1832        let mut buf = [0u8; 16];
1833        let d = server.recv_from(&mut buf).unwrap();
1834        server.mark_verified(d.from);
1835        assert_eq!(server.send_to(&[1u8; 1_000], d.from).unwrap(), 1_000);
1836        assert!(matches!(
1837            server.send_to(&[1u8; 1_000], b.local_addr().unwrap()),
1838            Err(NetError::Limit {
1839                which: LimitKind::Amplification
1840            })
1841        ));
1842        server.forget_verified(d.from);
1843        assert!(server.send_to(&[1u8; 1_000], d.from).is_err());
1844        assert_eq!(server.send_to(&[1u8; 5], d.from).unwrap(), 5);
1845    }
1846
1847    #[test]
1848    fn test_options_validate() {
1849        let bad = |o: UdpOptions| matches!(o.validate(), Err(NetError::InvalidConfig { .. }));
1850        assert!(bad(UdpOptions::new().amplification_factor(0)));
1851        assert!(bad(UdpOptions::new().amplification_factor(4)));
1852        assert!(bad(
1853            UdpOptions::new().amplification_window(Duration::from_millis(500))
1854        ));
1855        assert!(bad(UdpOptions::new().source_table(0)));
1856        assert!(bad(UdpOptions::new().source_budget(UdpBudget {
1857            datagrams_per_sec: 0,
1858            bytes_per_sec: 1,
1859            burst: 1
1860        })));
1861        assert!(bad(UdpOptions::new().new_source_burst(0)));
1862        assert!(bad(UdpOptions::new().global_budget(UdpBudget {
1863            datagrams_per_sec: 1,
1864            bytes_per_sec: 1,
1865            burst: 0
1866        })));
1867        assert!(UdpOptions::new().validate().is_ok());
1868        assert_eq!(UdpOptions::default(), UdpOptions::new());
1869    }
1870
1871    #[test]
1872    fn test_echo_truncation_and_zero_length() {
1873        let mut s = UdpSocket::bind("127.0.0.1:0").unwrap();
1874        s.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
1875        let to = s.local_addr().unwrap();
1876        let c = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
1877        c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
1878        c.send_to(b"hello", to).unwrap();
1879        let mut buf = [0u8; 64];
1880        let d = s.recv_from(&mut buf).unwrap();
1881        assert_eq!(
1882            (d.len, d.truncated, d.from),
1883            (5, false, c.local_addr().unwrap())
1884        );
1885        assert_eq!(s.send_to(&buf[..5], d.from).unwrap(), 5);
1886        let mut back = [0u8; 8];
1887        assert_eq!(c.recv(&mut back).unwrap(), 5);
1888        assert!(matches!(
1889            s.send_to(b"x", d.from),
1890            Err(NetError::Limit {
1891                which: LimitKind::Amplification
1892            })
1893        ));
1894        // Edge cases 90 and 91.
1895        c.send_to(&[7u8; 100], to).unwrap();
1896        let mut small = [0u8; 10];
1897        let d = s.recv_from(&mut small).unwrap();
1898        assert!(d.truncated);
1899        c.send_to(&[], to).unwrap();
1900        let d = s.recv_from(&mut buf).unwrap();
1901        assert_eq!((d.len, d.truncated), (0, false));
1902        let st = s.stats();
1903        assert_eq!(
1904            (st.received, st.sent, st.refused, st.truncated),
1905            (3, 1, 1, 1)
1906        );
1907        assert_eq!(st.sources, 1);
1908    }
1909
1910    #[test]
1911    fn test_icmp_reports_never_end_the_socket() {
1912        // Edge case 92: an injected "connection reset" and a real port-unreachable.
1913        use crate::sys::shim::{Fault, Op, clear_here, program_here};
1914        let mut s = UdpSocket::bind("127.0.0.1:0").unwrap();
1915        s.set_read_timeout(Some(Duration::from_millis(300)))
1916            .unwrap();
1917        let closed = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
1918        let gone = closed.local_addr().unwrap();
1919        drop(closed);
1920        s.connect(gone).unwrap();
1921        s.mark_verified(gone);
1922        s.send(b"anyone?").unwrap();
1923        program_here(Op::Recv, 0, 1, Fault::Kind(io::ErrorKind::ConnectionReset));
1924        let mut buf = [0u8; 16];
1925        assert!(matches!(
1926            s.recv(&mut buf),
1927            Err(NetError::TimedOut {
1928                kind: TimeoutKind::Read
1929            })
1930        ));
1931        clear_here();
1932        assert!(s.stats().icmp_errors >= 1);
1933        // Still usable.
1934        let mut t = UdpSocket::bind("127.0.0.1:0").unwrap();
1935        t.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
1936        let c = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
1937        c.send_to(b"ok", t.local_addr().unwrap()).unwrap();
1938        assert_eq!(t.recv_from(&mut buf).unwrap().len, 2);
1939    }
1940
1941    #[test]
1942    fn test_dual_stack_replies_to_ipv4_sources() {
1943        let Ok(mut s) = UdpSocket::bind_with("[::]:0", UdpOptions::new().ipv6_only(false)) else {
1944            return; // no IPv6 on this host
1945        };
1946        s.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
1947        let port = s.local_addr().unwrap().port();
1948        let c = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
1949        c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
1950        c.send_to(b"v4", ("127.0.0.1", port)).unwrap();
1951        let mut buf = [0u8; 8];
1952        let d = s.recv_from(&mut buf).unwrap();
1953        assert!(d.from.is_ipv4(), "normalized: {}", d.from);
1954        s.send_to(b"ok", d.from).unwrap();
1955        assert_eq!(c.recv(&mut buf).unwrap(), 2);
1956    }
1957
1958    fn verified_pair() -> (UdpSocket, UdpSocket) {
1959        let mut a = UdpSocket::bind("127.0.0.1:0").unwrap();
1960        let mut b = UdpSocket::bind("127.0.0.1:0").unwrap();
1961        let (aa, ba) = (a.local_addr().unwrap(), b.local_addr().unwrap());
1962        a.mark_verified(ba);
1963        b.mark_verified(aa);
1964        a.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
1965        b.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
1966        (a, b)
1967    }
1968
1969    #[test]
1970    fn test_batches_cross_in_one_call_each() {
1971        let (mut a, mut b) = verified_pair();
1972        let to = b.local_addr().unwrap();
1973        let bodies: Vec<Vec<u8>> = (0..10u8).map(|i| vec![i; 1 + usize::from(i)]).collect();
1974        let out: Vec<_> = bodies
1975            .iter()
1976            .map(|b| OutgoingDatagram { bytes: b, to })
1977            .collect();
1978        assert_eq!(a.send_batch(&out).unwrap(), 10);
1979        std::thread::sleep(Duration::from_millis(50));
1980        let mut store = vec![[0u8; 64]; 16];
1981        let mut seen = 0;
1982        while seen < 10 {
1983            let mut slots: Vec<_> = store.iter_mut().map(|b| DatagramBuffer::new(b)).collect();
1984            let n = b.recv_batch(&mut slots).unwrap();
1985            assert!(n > 0);
1986            for slot in &slots {
1987                if let Some(d) = slot.datagram {
1988                    assert_eq!(d.from, a.local_addr().unwrap());
1989                    assert_eq!(&slot.buf[..d.len], &bodies[seen][..]);
1990                    seen += 1;
1991                }
1992            }
1993        }
1994        assert_eq!(a.stats().sent, 10);
1995        assert_eq!(b.stats().received, 10);
1996    }
1997
1998    /// An unverified peer's allowance holds across a batch: what got through is what
1999    /// the guard allows, and a batch cannot spend it twice.
2000    #[test]
2001    fn test_batch_send_stays_under_the_guard() {
2002        let mut server = UdpSocket::bind("127.0.0.1:0").unwrap();
2003        let client = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
2004        let to = client.local_addr().unwrap();
2005        client
2006            .send_to(&[0u8; 100], server.local_addr().unwrap())
2007            .unwrap();
2008        let mut buf = [0u8; 200];
2009        server.recv_from(&mut buf).unwrap();
2010        let big = [1u8; 40];
2011        let out = [OutgoingDatagram { bytes: &big, to }; 4];
2012        assert_eq!(
2013            server.send_batch(&out).unwrap(),
2014            2,
2015            "100 bytes of allowance"
2016        );
2017        assert!(matches!(
2018            server.send_batch(&out),
2019            Err(NetError::Limit {
2020                which: LimitKind::Amplification
2021            })
2022        ));
2023    }
2024
2025    #[cfg(unix)]
2026    #[test]
2027    fn test_packet_info_reports_the_destination() {
2028        let mut server =
2029            UdpSocket::bind_with("0.0.0.0:0", UdpOptions::new().packet_info(true)).unwrap();
2030        server
2031            .set_read_timeout(Some(Duration::from_secs(5)))
2032            .unwrap();
2033        let port = server.local_addr().unwrap().port();
2034        let client = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
2035        client.send_to(b"hi", ("127.0.0.1", port)).unwrap();
2036        let mut buf = [0u8; 16];
2037        let d = server.recv_from(&mut buf).unwrap();
2038        assert_eq!(d.len, 2);
2039        assert_eq!(d.destination, Some("127.0.0.1".parse().unwrap()));
2040    }
2041
2042    #[cfg(windows)]
2043    #[test]
2044    fn test_packet_info_is_refused_on_windows() {
2045        assert!(matches!(
2046            UdpSocket::bind_with("127.0.0.1:0", UdpOptions::new().packet_info(true)),
2047            Err(NetError::Unsupported { .. })
2048        ));
2049    }
2050
2051    /// One IPv6 /64 is one source by default: a host that rotates its interface
2052    /// id gets no budget per address, and another /64 keeps its own.
2053    #[test]
2054    fn test_one_slash64_shares_one_budget() {
2055        let t = Instant::now();
2056        let budget = UdpBudget {
2057            datagrams_per_sec: 1,
2058            bytes_per_sec: 1_000_000,
2059            burst: 3,
2060        };
2061        let mut g = Guard::new(UdpOptions::new().source_budget(budget), t);
2062        let mut o = false;
2063        let mut admitted = 0;
2064        for host in 0..1_000u16 {
2065            let ip = IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 1, 2, 0, 0, 0, host + 1));
2066            for _ in 0..10 {
2067                if g.admit(ip, 100, t, &mut o) {
2068                    admitted += 1;
2069                }
2070            }
2071        }
2072        assert!(admitted <= 3, "{admitted} admitted from one /64");
2073        let other = IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 1, 3, 0, 0, 0, 1));
2074        assert!(g.admit(other, 100, t, &mut o), "another /64 has its own");
2075        assert!(!o);
2076    }
2077
2078    /// `PrefixPolicy::HOST` budgets every address on its own, and a first burst
2079    /// larger than the budget's burst is cut to it.
2080    #[test]
2081    fn test_source_prefix_and_first_burst_are_options() {
2082        let t = Instant::now();
2083        let budget = UdpBudget {
2084            datagrams_per_sec: 1,
2085            bytes_per_sec: 1_000_000,
2086            burst: 3,
2087        };
2088        let options = UdpOptions::new()
2089            .source_budget(budget)
2090            .source_prefix(PrefixPolicy::HOST)
2091            .new_source_burst(50);
2092        let mut g = Guard::new(options, t);
2093        let mut o = false;
2094        let mut admitted = 0;
2095        for host in 1..=10u16 {
2096            let ip = IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 1, 2, 0, 0, 0, host));
2097            admitted += (0..10).filter(|_| g.admit(ip, 100, t, &mut o)).count();
2098        }
2099        assert_eq!(admitted, 30, "three per address");
2100        let wide = PrefixPolicy::new(24, 48).unwrap();
2101        let mut g = Guard::new(UdpOptions::new().source_prefix(wide).new_source_burst(2), t);
2102        let n = (1..=20u8)
2103            .filter(|&n| g.admit(IpAddr::from([192, 0, 2, n]), 10, t, &mut o))
2104            .count();
2105        assert_eq!(n, 2, "one /24, a first burst of two");
2106    }
2107
2108    /// The send allowance stays with the exact address that sent, even when its
2109    /// budget is shared with the rest of its /64.
2110    #[test]
2111    fn test_send_allowance_stays_per_address_within_a_prefix() {
2112        let t = Instant::now();
2113        let mut g = Guard::new(UdpOptions::new(), t);
2114        let mut o = false;
2115        let a = IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1));
2116        let b = IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 2));
2117        assert!(g.admit(a, 100, t, &mut o));
2118        assert!(
2119            !g.charge(SocketAddr::new(b, 9), 1, t),
2120            "a neighbour in the /64 never sent"
2121        );
2122        assert!(g.charge(SocketAddr::new(a, 9), 100, t));
2123        assert!(!g.charge(SocketAddr::new(a, 9), 1, t));
2124    }
2125
2126    /// With the default options a flood of new sources at one instant reaches the
2127    /// caller only up to the default global burst.
2128    #[test]
2129    fn test_default_options_cap_a_flood_of_new_sources() {
2130        let t = Instant::now();
2131        let mut g = Guard::new(UdpOptions::new(), t);
2132        let mut o = false;
2133        let admitted = (0..300_000u32)
2134            .filter(|n| {
2135                let ip = IpAddr::from((0x0A00_0000u32 + n).to_be_bytes());
2136                g.admit(ip, 512, t, &mut o)
2137            })
2138            .count();
2139        assert!(admitted <= 10_000, "{admitted} of 300,000 admitted");
2140    }
2141
2142    /// A source new to the table starts with a small burst, and its bucket fills
2143    /// to the full burst at its rate.
2144    #[test]
2145    fn test_a_new_source_starts_with_a_small_burst() {
2146        let t = Instant::now();
2147        let mut g = Guard::new(UdpOptions::new(), t);
2148        let mut o = false;
2149        let first = (0..200).filter(|_| g.admit(ip(1), 10, t, &mut o)).count();
2150        assert_eq!(first, 16);
2151        let later = t + Duration::from_secs(1);
2152        let then = (0..200)
2153            .filter(|_| g.admit(ip(1), 10, later, &mut o))
2154            .count();
2155        assert_eq!(then, 100, "the full burst after a second");
2156    }
2157
2158    /// A non-blocking receive (the server's loop) returns after a bounded number
2159    /// of datagrams dropped over budget instead of reading the whole queue.
2160    #[test]
2161    fn test_a_non_blocking_receive_returns_after_a_bounded_number_of_drops() {
2162        let budget = UdpBudget {
2163            datagrams_per_sec: 1,
2164            bytes_per_sec: 1_000_000,
2165            burst: 1,
2166        };
2167        let mut s =
2168            UdpSocket::bind_with("127.0.0.1:0", UdpOptions::new().source_budget(budget)).unwrap();
2169        let to = s.local_addr().unwrap();
2170        let c = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
2171        for _ in 0..200 {
2172            c.send_to(b"x", to).unwrap();
2173        }
2174        std::thread::sleep(Duration::from_millis(100));
2175        s.set_nonblocking().unwrap();
2176        let mut buf = [0u8; 8];
2177        assert!(s.recv_from(&mut buf).is_ok(), "the burst");
2178        assert!(matches!(
2179            s.recv_from(&mut buf),
2180            Err(NetError::TimedOut {
2181                kind: TimeoutKind::Read
2182            })
2183        ));
2184        assert_eq!(s.stats().dropped, 64, "one call read the whole queue");
2185        assert!(s.recv_from(&mut buf).is_err());
2186        assert!(s.stats().dropped > 64, "the next call goes on");
2187    }
2188
2189    /// Unreachable reports and the other errors an ICMP message leaves on a
2190    /// socket are counted and skipped like a refused port.
2191    #[test]
2192    fn test_other_icmp_reports_never_end_the_socket() {
2193        use crate::sys::shim::{Fault, Op, clear_here, program_here};
2194        let mut s = UdpSocket::bind("127.0.0.1:0").unwrap();
2195        s.set_read_timeout(Some(Duration::from_millis(100)))
2196            .unwrap();
2197        let mut faults = vec![
2198            Fault::Kind(io::ErrorKind::HostUnreachable),
2199            Fault::Kind(io::ErrorKind::NetworkUnreachable),
2200        ];
2201        #[cfg(unix)]
2202        faults.extend([
2203            Fault::Os(sys::errno::EHOSTDOWN),
2204            Fault::Os(sys::errno::ENOPROTOOPT),
2205            Fault::Os(sys::errno::EPROTO),
2206            Fault::Os(sys::errno::EMSGSIZE),
2207        ]);
2208        // WSAENETRESET: a "time exceeded" report.
2209        #[cfg(windows)]
2210        faults.push(Fault::Os(sys::errno::WSAENETRESET));
2211        let n = faults.len() as u64;
2212        let mut buf = [0u8; 16];
2213        for fault in faults {
2214            program_here(Op::Recv, 0, 1, fault);
2215            let got = s.recv_from(&mut buf);
2216            clear_here();
2217            assert!(
2218                matches!(
2219                    got,
2220                    Err(NetError::TimedOut {
2221                        kind: TimeoutKind::Read
2222                    })
2223                ),
2224                "{got:?}"
2225            );
2226        }
2227        assert_eq!(s.stats().icmp_errors, n);
2228    }
2229
2230    /// A batch receive leaves a non-blocking socket non-blocking.
2231    #[test]
2232    fn test_a_batch_receive_keeps_the_socket_mode() {
2233        let (mut a, mut b) = verified_pair();
2234        b.set_read_timeout(Some(Duration::from_secs(2))).unwrap();
2235        b.set_nonblocking().unwrap();
2236        a.send_to(b"one", b.local_addr().unwrap()).unwrap();
2237        std::thread::sleep(Duration::from_millis(50));
2238        let mut store = [[0u8; 16]; 4];
2239        let mut slots: Vec<_> = store.iter_mut().map(|b| DatagramBuffer::new(b)).collect();
2240        assert_eq!(b.recv_batch(&mut slots).unwrap(), 1);
2241        let started = Instant::now();
2242        let mut buf = [0u8; 16];
2243        assert!(b.recv_from(&mut buf).is_err());
2244        assert!(
2245            started.elapsed() < Duration::from_millis(500),
2246            "the receive waited {:?}: the batch left the socket blocking",
2247            started.elapsed()
2248        );
2249    }
2250
2251    #[test]
2252    fn test_multicast_join_checks_the_family() {
2253        let socket = UdpSocket::bind("0.0.0.0:0").unwrap();
2254        let group: IpAddr = "239.1.2.3".parse().unwrap();
2255        assert!(matches!(
2256            socket.join_multicast(group, MulticastInterface::V6Index(1)),
2257            Err(NetError::InvalidConfig { .. })
2258        ));
2259        // A host without a multicast route refuses; a broken family check would not.
2260        let _ = socket.join_multicast(group, MulticastInterface::Any);
2261    }
2262}