1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub struct UdpBudget {
31 pub datagrams_per_sec: u32,
33 pub bytes_per_sec: u32,
35 pub burst: u32,
37}
38
39impl UdpBudget {
40 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 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#[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 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 pub fn amplification_factor(mut self, factor: u8) -> UdpOptions {
117 self.factor = factor;
118 self
119 }
120
121 pub fn amplification_window(mut self, window: Duration) -> UdpOptions {
125 self.window = window;
126 self
127 }
128
129 pub fn verification_lifetime(mut self, lifetime: Duration) -> UdpOptions {
134 self.verified_for = lifetime;
135 self
136 }
137
138 pub fn verified_table(mut self, entries: u32) -> UdpOptions {
143 self.verified_table = entries;
144 self
145 }
146
147 pub fn source_budget(mut self, budget: UdpBudget) -> UdpOptions {
149 self.source = budget;
150 self
151 }
152
153 pub fn source_prefix(mut self, policy: PrefixPolicy) -> UdpOptions {
160 self.prefix = policy;
161 self
162 }
163
164 pub fn new_source_burst(mut self, datagrams: u32) -> UdpOptions {
171 self.first = datagrams;
172 self
173 }
174
175 pub fn global_budget(mut self, budget: UdpBudget) -> UdpOptions {
179 self.global = budget;
180 self
181 }
182
183 pub fn source_table(mut self, entries: u32) -> UdpOptions {
187 self.table = entries;
188 self
189 }
190
191 pub fn packet_info(mut self, on: bool) -> UdpOptions {
198 self.packet_info = on;
199 self
200 }
201
202 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
266pub struct Datagram {
267 pub len: usize,
270 pub from: SocketAddr,
272 pub truncated: bool,
274 pub destination: Option<IpAddr>,
276}
277
278#[non_exhaustive]
286#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
287pub struct UdpStats {
288 pub received: u64,
290 pub sent: u64,
292 pub dropped: u64,
294 pub refused: u64,
296 pub truncated: u64,
298 pub icmp_errors: u64,
300 pub overflow: u64,
302 pub sources: u32,
304}
305
306#[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 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 fn take(&mut self, budget: &UdpBudget, len: usize, now: Instant) -> bool {
339 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#[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 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#[derive(Clone, Copy, Debug)]
396struct Proof {
397 key: PeerKey,
398 until: Instant,
399 referenced: bool,
401}
402
403type PeerKey = (IpAddr, u16);
406
407fn peer_key(peer: SocketAddr) -> PeerKey {
408 (normalize(peer.ip()), peer.port())
409}
410
411const SWEEP: usize = 64;
414
415const TURN: usize = 2;
419
420const MAX_WINDOW_SECS: u64 = 3_600;
422
423const MAX_VERIFIED_SECS: u64 = 86_400;
425
426#[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 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 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 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#[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 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 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 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 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 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#[derive(Debug)]
687pub struct UdpSocket {
688 inner: std::net::UdpSocket,
689 guard: Guard,
690 read_timeout: Option<Duration>,
691 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#[derive(Debug)]
710pub struct DatagramBuffer<'a> {
711 pub buf: &'a mut [u8],
713 pub datagram: Option<Datagram>,
715}
716
717impl<'a> DatagramBuffer<'a> {
718 #[must_use]
720 pub fn new(buf: &'a mut [u8]) -> DatagramBuffer<'a> {
721 DatagramBuffer {
722 buf,
723 datagram: None,
724 }
725 }
726}
727
728#[derive(Clone, Copy, Debug)]
735pub struct OutgoingDatagram<'a> {
736 pub bytes: &'a [u8],
738 pub to: SocketAddr,
740}
741
742#[non_exhaustive]
749#[derive(Clone, Copy, Debug, PartialEq, Eq)]
750pub enum MulticastInterface {
751 Any,
753 V4(Ipv4Addr),
755 V6Index(u32),
757}
758
759impl UdpSocket {
760 pub fn bind<A: ToSocketAddrs>(addr: A) -> Result<UdpSocket, NetError> {
766 UdpSocket::bind_with(addr, UdpOptions::new())
767 }
768
769 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 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 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 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 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 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 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 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 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 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 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 pub fn recv(&mut self, buf: &mut [u8]) -> Result<Datagram, NetError> {
1115 self.recv_from(buf)
1116 }
1117
1118 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 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 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 pub fn mark_verified(&mut self, peer: SocketAddr) {
1184 self.guard.verify(peer, Instant::now());
1185 }
1186
1187 pub fn forget_verified(&mut self, peer: SocketAddr) {
1190 self.guard.forget(peer, Instant::now());
1191 }
1192
1193 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 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 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 #[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 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
1256pub trait UdpSession: Send + 'static {
1271 fn on_datagram(&mut self, cx: &mut UdpContext<'_>, from: SocketAddr, bytes: &[u8]);
1273}
1274
1275#[derive(Debug)]
1277pub struct UdpContext<'a> {
1278 pub(crate) socket: &'a mut UdpSocket,
1279}
1280
1281impl UdpContext<'_> {
1282 pub fn send_to(&mut self, bytes: &[u8], to: SocketAddr) -> Result<usize, NetError> {
1288 self.socket.send_to(bytes, to)
1289 }
1290
1291 pub fn mark_verified(&mut self, peer: SocketAddr) {
1293 self.socket.mark_verified(peer);
1294 }
1295
1296 pub fn forget_verified(&mut self, peer: SocketAddr) {
1298 self.socket.forget_verified(peer);
1299 }
1300
1301 #[must_use]
1303 pub fn now(&self) -> Instant {
1304 Instant::now()
1305 }
1306}
1307
1308pub trait UdpSessionFactory: Send + Sync + 'static {
1311 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
1329const DROP_TURN: u32 = 64;
1335
1336fn 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 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#[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 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 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 #[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 assert!(bucket.take(&b, 100, t + Duration::from_millis(100)));
1552 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 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 assert!(g.admit(ip(2), 100, t, &mut o));
1593 assert!(g.charge(at(2, 9), 300, t + w + Duration::from_millis(1)));
1594 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 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 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 #[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 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 #[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 #[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 #[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 assert!(g.admit(ip(200), 10, t, &mut o));
1755 assert!(o);
1756 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 #[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 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 #[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 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 #[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 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 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 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; };
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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 let _ = socket.join_multicast(group, MulticastInterface::Any);
2261 }
2262}