1use std::collections::HashMap;
10use std::io;
11use std::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV6, ToSocketAddrs};
12use std::time::{Duration, Instant};
13
14use crate::addr::normalize;
15use crate::error::{ConfigReason, LimitKind, NetError, TimeoutKind};
16use crate::sys::{self, AsSock};
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub struct UdpBudget {
27 pub datagrams_per_sec: u32,
29 pub bytes_per_sec: u32,
31 pub burst: u32,
33}
34
35impl UdpBudget {
36 pub const SOURCE_DEFAULT: UdpBudget = UdpBudget {
39 datagrams_per_sec: 1_000,
40 bytes_per_sec: 1_000_000,
41 burst: 100,
42 };
43}
44
45#[must_use]
55#[derive(Clone, Debug, PartialEq, Eq)]
56pub struct UdpOptions {
57 factor: u8,
58 window: Duration,
59 source: UdpBudget,
60 global: Option<UdpBudget>,
61 table: u32,
62 verified_for: Duration,
63 verified_table: u32,
64 ipv6_only: bool,
65 packet_info: bool,
66}
67
68impl Default for UdpOptions {
69 fn default() -> UdpOptions {
70 UdpOptions::new()
71 }
72}
73
74impl UdpOptions {
75 pub fn new() -> UdpOptions {
79 UdpOptions {
80 factor: 1,
81 window: Duration::from_secs(10),
82 source: UdpBudget::SOURCE_DEFAULT,
83 global: None,
84 table: 65_536,
85 verified_for: Duration::from_secs(60),
86 verified_table: 65_536,
87 ipv6_only: true,
88 packet_info: false,
89 }
90 }
91
92 pub fn amplification_factor(mut self, factor: u8) -> UdpOptions {
95 self.factor = factor;
96 self
97 }
98
99 pub fn amplification_window(mut self, window: Duration) -> UdpOptions {
103 self.window = window;
104 self
105 }
106
107 pub fn verification_lifetime(mut self, lifetime: Duration) -> UdpOptions {
112 self.verified_for = lifetime;
113 self
114 }
115
116 pub fn verified_table(mut self, entries: u32) -> UdpOptions {
121 self.verified_table = entries;
122 self
123 }
124
125 pub fn source_budget(mut self, budget: UdpBudget) -> UdpOptions {
127 self.source = budget;
128 self
129 }
130
131 pub fn global_budget(mut self, budget: UdpBudget) -> UdpOptions {
133 self.global = Some(budget);
134 self
135 }
136
137 pub fn source_table(mut self, entries: u32) -> UdpOptions {
139 self.table = entries;
140 self
141 }
142
143 pub fn packet_info(mut self, on: bool) -> UdpOptions {
150 self.packet_info = on;
151 self
152 }
153
154 pub fn ipv6_only(mut self, on: bool) -> UdpOptions {
156 self.ipv6_only = on;
157 self
158 }
159
160 fn validate(&self) -> Result<(), NetError> {
161 let invalid = |field, reason| Err(NetError::InvalidConfig { field, reason });
162 if self.factor == 0 {
163 return invalid("amplification_factor", ConfigReason::Zero);
164 }
165 if self.factor > 3 {
166 return invalid("amplification_factor", ConfigReason::TooLarge { max: 3 });
167 }
168 if self.window < Duration::from_secs(1) {
169 return invalid("amplification_window", ConfigReason::TooSmall { min: 1 });
170 }
171 if self.window > Duration::from_secs(MAX_WINDOW_SECS) {
172 return invalid(
173 "amplification_window",
174 ConfigReason::TooLarge {
175 max: MAX_WINDOW_SECS,
176 },
177 );
178 }
179 if self.verified_for < Duration::from_secs(1) {
180 return invalid("verification_lifetime", ConfigReason::TooSmall { min: 1 });
181 }
182 if self.verified_for > Duration::from_secs(MAX_VERIFIED_SECS) {
183 return invalid(
184 "verification_lifetime",
185 ConfigReason::TooLarge {
186 max: MAX_VERIFIED_SECS,
187 },
188 );
189 }
190 if self.table == 0 {
191 return invalid("source_table", ConfigReason::Zero);
192 }
193 if self.verified_table == 0 {
194 return invalid("verified_table", ConfigReason::Zero);
195 }
196 for (field, b) in [
197 ("source_budget", Some(self.source)),
198 ("global_budget", self.global),
199 ] {
200 if let Some(b) = b {
201 if b.datagrams_per_sec == 0 || b.bytes_per_sec == 0 || b.burst == 0 {
202 return invalid(field, ConfigReason::Zero);
203 }
204 }
205 }
206 Ok(())
207 }
208}
209
210#[derive(Clone, Copy, Debug, PartialEq, Eq)]
217pub struct Datagram {
218 pub len: usize,
221 pub from: SocketAddr,
223 pub truncated: bool,
225 pub destination: Option<IpAddr>,
227}
228
229#[non_exhaustive]
237#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
238pub struct UdpStats {
239 pub received: u64,
241 pub sent: u64,
243 pub dropped: u64,
245 pub refused: u64,
247 pub truncated: u64,
249 pub icmp_errors: u64,
251 pub overflow: u64,
253 pub sources: u32,
255}
256
257#[derive(Clone, Copy, Debug)]
259struct Bucket {
260 datagrams: u64,
261 bytes: u64,
262 at: Instant,
263}
264
265const MICRO: u64 = 1_000_000;
266
267impl Bucket {
268 fn full(budget: &UdpBudget, now: Instant) -> Bucket {
269 Bucket {
270 datagrams: u64::from(budget.burst) * MICRO,
271 bytes: u64::from(budget.bytes_per_sec) * MICRO,
272 at: now,
273 }
274 }
275
276 fn take(&mut self, budget: &UdpBudget, len: usize, now: Instant) -> bool {
278 let us = now
281 .saturating_duration_since(self.at)
282 .as_micros()
283 .min(1_000_000_000) as u64;
284 self.at = now;
285 let cap_d = u64::from(budget.burst) * MICRO;
286 let cap_b = u64::from(budget.bytes_per_sec) * MICRO;
287 self.datagrams = (self.datagrams + us * u64::from(budget.datagrams_per_sec)).min(cap_d);
288 self.bytes = (self.bytes + us * u64::from(budget.bytes_per_sec)).min(cap_b);
289 let need_b = (len as u64).saturating_mul(MICRO);
290 if self.datagrams >= MICRO && self.bytes >= need_b {
291 self.datagrams -= MICRO;
292 self.bytes -= need_b;
293 true
294 } else {
295 false
296 }
297 }
298}
299
300#[derive(Clone, Copy, Debug)]
302struct Entry {
303 ip: IpAddr,
304 bucket: Bucket,
305 received: [u64; 2],
306 sent: [u64; 2],
307 window_at: Instant,
308 referenced: bool,
310}
311
312impl Entry {
313 fn new(ip: IpAddr, budget: &UdpBudget, now: Instant) -> Entry {
314 Entry {
315 ip,
316 bucket: Bucket::full(budget, now),
317 received: [0; 2],
318 sent: [0; 2],
319 window_at: now,
320 referenced: false,
321 }
322 }
323
324 fn roll(&mut self, window: Duration, now: Instant) {
326 let gone = now.saturating_duration_since(self.window_at);
327 if gone >= window.saturating_mul(2) {
328 self.received = [0; 2];
329 self.sent = [0; 2];
330 self.window_at = now;
331 } else if gone >= window {
332 self.received = [0, self.received[0]];
333 self.sent = [0, self.sent[0]];
334 self.window_at = self.window_at.checked_add(window).unwrap_or(now);
335 }
336 }
337}
338
339#[derive(Clone, Copy, Debug)]
341struct Proof {
342 key: PeerKey,
343 until: Instant,
344 referenced: bool,
346}
347
348type PeerKey = (IpAddr, u16);
351
352fn peer_key(peer: SocketAddr) -> PeerKey {
353 (normalize(peer.ip()), peer.port())
354}
355
356const SWEEP: usize = 64;
359
360const TURN: usize = 2;
364
365const MAX_WINDOW_SECS: u64 = 3_600;
367
368const MAX_VERIFIED_SECS: u64 = 86_400;
370
371#[derive(Debug)]
374struct Guard {
375 index: HashMap<IpAddr, u32>,
376 slots: Vec<Entry>,
377 hand: usize,
378 proofs: HashMap<PeerKey, u32>,
379 proved: Vec<Proof>,
380 proof_hand: usize,
381 overflow: Bucket,
382 global: Option<Bucket>,
383 options: UdpOptions,
384}
385
386impl Guard {
387 fn new(options: UdpOptions, now: Instant) -> Guard {
388 Guard {
389 index: HashMap::new(),
390 slots: Vec::new(),
391 hand: 0,
392 proofs: HashMap::new(),
393 proved: Vec::new(),
394 proof_hand: 0,
395 overflow: Bucket::full(&options.source, now),
396 global: options.global.map(|g| Bucket::full(&g, now)),
397 options,
398 }
399 }
400
401 fn slot(&mut self, ip: IpAddr, now: Instant) -> Option<(usize, bool)> {
404 if let Some(&i) = self.index.get(&ip) {
405 return Some((i as usize, true));
406 }
407 let entry = Entry::new(ip, &self.options.source, now);
408 if self.slots.len() < self.options.table as usize {
409 self.slots.push(entry);
410 let i = self.slots.len() - 1;
411 self.index.insert(ip, i as u32);
412 return Some((i, false));
413 }
414 let n = self.slots.len();
415 for _ in 0..SWEEP.min(2 * n) {
416 let i = self.hand;
417 self.hand = (self.hand + 1) % n;
418 let e = &mut self.slots[i];
419 if e.referenced {
420 e.referenced = false;
421 continue;
422 }
423 self.index.remove(&e.ip);
424 *e = entry;
425 self.index.insert(ip, i as u32);
426 return Some((i, false));
427 }
428 None
429 }
430
431 fn turn(&mut self) {
434 let n = self.slots.len();
435 if n < self.options.table as usize || n == 0 {
436 return;
437 }
438 for _ in 0..TURN {
439 self.slots[self.hand].referenced = false;
440 self.hand = (self.hand + 1) % n;
441 }
442 }
443
444 fn admit(&mut self, ip: IpAddr, len: usize, now: Instant, overflow: &mut bool) -> bool {
448 let source = self.options.source;
449 let at = match self.slot(ip, now) {
450 Some((i, known)) => {
451 if known {
452 self.turn();
453 }
454 if !self.slots[i].bucket.take(&source, len, now) {
455 return false;
456 }
457 Some(i)
458 }
459 None => {
460 *overflow = true;
461 if !self.overflow.take(&source, len, now) {
462 return false;
463 }
464 None
465 }
466 };
467 if let (Some(bucket), Some(budget)) = (&mut self.global, &self.options.global) {
468 if !bucket.take(budget, len, now) {
469 return false;
470 }
471 }
472 if let Some(i) = at {
473 let window = self.options.window;
474 let e = &mut self.slots[i];
475 e.referenced = true;
476 e.roll(window, now);
477 e.received[0] = e.received[0].saturating_add(len as u64);
478 }
479 true
480 }
481
482 fn charge(&mut self, to: SocketAddr, len: usize, now: Instant) -> bool {
486 if self.is_verified(to, now) {
487 return true;
488 }
489 let Some(&i) = self.index.get(&normalize(to.ip())) else {
490 return len == 0;
491 };
492 let window = self.options.window;
493 let factor = u64::from(self.options.factor);
494 let e = &mut self.slots[i as usize];
495 e.roll(window, now);
496 let allowed = factor.saturating_mul(e.received[0].saturating_add(e.received[1]));
497 let total = e.sent[0]
498 .saturating_add(e.sent[1])
499 .saturating_add(len as u64);
500 if total > allowed {
501 return false;
502 }
503 e.sent[0] = e.sent[0].saturating_add(len as u64);
504 true
505 }
506
507 fn is_verified(&self, peer: SocketAddr, now: Instant) -> bool {
508 self.proofs
509 .get(&peer_key(peer))
510 .is_some_and(|&i| now < self.proved[i as usize].until)
511 }
512
513 fn verify(&mut self, peer: SocketAddr, now: Instant) {
517 let key = peer_key(peer);
518 let until = now.checked_add(self.options.verified_for).unwrap_or(now);
519 if let Some(&i) = self.proofs.get(&key) {
520 let p = &mut self.proved[i as usize];
521 p.until = until;
522 p.referenced = true;
523 return;
524 }
525 let proof = Proof {
526 key,
527 until,
528 referenced: true,
529 };
530 if self.proved.len() < self.options.verified_table as usize {
531 self.proved.push(proof);
532 self.proofs.insert(key, (self.proved.len() - 1) as u32);
533 return;
534 }
535 let n = self.proved.len();
536 let mut found = None;
537 for _ in 0..SWEEP.min(2 * n) {
538 let i = self.proof_hand;
539 self.proof_hand = (i + 1) % n;
540 let p = &mut self.proved[i];
541 if now >= p.until || !p.referenced {
542 found = Some(i);
543 break;
544 }
545 p.referenced = false;
546 }
547 let at = found.unwrap_or_else(|| {
548 let i = self.proof_hand;
549 self.proof_hand = (i + 1) % n;
550 i
551 });
552 let old = self.proved[at].key;
553 self.proofs.remove(&old);
554 self.proved[at] = proof;
555 self.proofs.insert(key, at as u32);
556 }
557
558 fn forget(&mut self, peer: SocketAddr, now: Instant) {
560 if let Some(&i) = self.proofs.get(&peer_key(peer)) {
561 let p = &mut self.proved[i as usize];
562 p.until = now;
563 p.referenced = false;
564 }
565 }
566}
567
568#[derive(Debug)]
584pub struct UdpSocket {
585 inner: std::net::UdpSocket,
586 guard: Guard,
587 read_timeout: Option<Duration>,
588 peer: Option<SocketAddr>,
589 v6: bool,
590 #[cfg_attr(windows, allow(dead_code))]
591 packet_info: bool,
592 stats: UdpStats,
593}
594
595#[derive(Debug)]
603pub struct DatagramBuffer<'a> {
604 pub buf: &'a mut [u8],
606 pub datagram: Option<Datagram>,
608}
609
610impl<'a> DatagramBuffer<'a> {
611 #[must_use]
613 pub fn new(buf: &'a mut [u8]) -> DatagramBuffer<'a> {
614 DatagramBuffer {
615 buf,
616 datagram: None,
617 }
618 }
619}
620
621#[derive(Clone, Copy, Debug)]
628pub struct OutgoingDatagram<'a> {
629 pub bytes: &'a [u8],
631 pub to: SocketAddr,
633}
634
635#[non_exhaustive]
642#[derive(Clone, Copy, Debug, PartialEq, Eq)]
643pub enum MulticastInterface {
644 Any,
646 V4(Ipv4Addr),
648 V6Index(u32),
650}
651
652impl UdpSocket {
653 pub fn bind<A: ToSocketAddrs>(addr: A) -> Result<UdpSocket, NetError> {
659 UdpSocket::bind_with(addr, UdpOptions::new())
660 }
661
662 pub fn bind_with<A: ToSocketAddrs>(
668 addr: A,
669 options: UdpOptions,
670 ) -> Result<UdpSocket, NetError> {
671 options.validate()?;
672 let addrs: Vec<SocketAddr> = addr
673 .to_socket_addrs()
674 .map_err(|e| NetError::Os {
675 op: "resolve",
676 source: e,
677 })?
678 .collect();
679 let mut last = NetError::NoAddresses;
680 if options.packet_info && !cfg!(unix) {
681 return Err(NetError::Unsupported {
682 feature: "UDP packet info",
683 platform: std::env::consts::OS,
684 });
685 }
686 let packet_info = options.packet_info;
687 for a in addrs {
688 match sys::udp_bind(a, options.ipv6_only) {
689 Ok(inner) => {
690 #[cfg(unix)]
691 if packet_info {
692 sys::udp_packet_info(inner.sock(), a.is_ipv6())
693 .map_err(|e| NetError::from_os("setsockopt", e))?;
694 }
695 return Ok(UdpSocket {
696 inner,
697 guard: Guard::new(options, Instant::now()),
698 read_timeout: None,
699 peer: None,
700 v6: a.is_ipv6(),
701 packet_info,
702 stats: UdpStats::default(),
703 });
704 }
705 Err(e) => last = crate::tcp::bind_error(a, e),
706 }
707 }
708 Err(last)
709 }
710
711 pub fn recv_from(&mut self, buf: &mut [u8]) -> Result<Datagram, NetError> {
719 let deadline = self
721 .read_timeout
722 .and_then(|t| Instant::now().checked_add(t));
723 loop {
724 let (len, from, truncated, destination) = match self.recv_one(buf) {
725 Ok(got) => got,
726 Err(e) => match e.kind() {
727 io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut => {
728 return Err(NetError::TimedOut {
729 kind: TimeoutKind::Read,
730 });
731 }
732 io::ErrorKind::Interrupted => continue,
733 io::ErrorKind::ConnectionRefused | io::ErrorKind::ConnectionReset => {
734 self.stats.icmp_errors += 1;
736 if past(deadline) {
737 return Err(NetError::TimedOut {
738 kind: TimeoutKind::Read,
739 });
740 }
741 continue;
742 }
743 _ => return Err(NetError::from_os("recvfrom", e)),
744 },
745 };
746 let from = crate::addr::normalize_socket(from);
747 if !self.admit(from, len, truncated) {
748 if past(deadline) {
749 return Err(NetError::TimedOut {
750 kind: TimeoutKind::Read,
751 });
752 }
753 continue;
754 }
755 return Ok(Datagram {
756 len,
757 from,
758 truncated,
759 destination,
760 });
761 }
762 }
763
764 fn recv_one(
765 &mut self,
766 buf: &mut [u8],
767 ) -> io::Result<(usize, SocketAddr, bool, Option<IpAddr>)> {
768 #[cfg(unix)]
769 if self.packet_info {
770 return sys::udp_recv_with_destination(self.inner.sock(), buf);
771 }
772 let (len, from, truncated) = sys::udp_recv_from(self.inner.sock(), buf)?;
773 Ok((len, from, truncated, None))
774 }
775
776 fn admit(&mut self, from: SocketAddr, len: usize, truncated: bool) -> bool {
778 let mut overflow = false;
779 let admitted = self
780 .guard
781 .admit(from.ip(), len, Instant::now(), &mut overflow);
782 if overflow {
783 self.stats.overflow += 1;
784 }
785 if !admitted {
786 self.stats.dropped += 1;
787 return false;
788 }
789 self.stats.received += 1;
790 if truncated {
791 self.stats.truncated += 1;
792 }
793 true
794 }
795
796 pub fn recv_batch(&mut self, slots: &mut [DatagramBuffer<'_>]) -> Result<usize, NetError> {
806 for slot in slots.iter_mut() {
807 slot.datagram = None;
808 }
809 if slots.is_empty() {
810 return Ok(0);
811 }
812 self.recv_many(slots)
813 }
814
815 #[cfg(target_os = "linux")]
816 fn recv_many(&mut self, slots: &mut [DatagramBuffer<'_>]) -> Result<usize, NetError> {
817 let count = slots.len().min(sys::BATCH_MAX);
818 let mut got = [None; sys::BATCH_MAX];
819 let n = loop {
820 let received = {
821 let mut bufs: [&mut [u8]; sys::BATCH_MAX] = std::array::from_fn(|_| &mut [][..]);
822 for (b, slot) in bufs.iter_mut().zip(slots.iter_mut()).take(count) {
823 *b = &mut *slot.buf;
824 }
825 sys::udp_recv_many(self.inner.sock(), &mut bufs[..count], &mut got)
826 };
827 match received {
828 Ok(n) => break n,
829 Err(e) => match e.kind() {
830 io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut => {
831 return Err(NetError::TimedOut {
832 kind: TimeoutKind::Read,
833 });
834 }
835 io::ErrorKind::Interrupted => {}
836 io::ErrorKind::ConnectionRefused | io::ErrorKind::ConnectionReset => {
837 self.stats.icmp_errors += 1;
838 }
839 _ => return Err(NetError::from_os("recvmmsg", e)),
840 },
841 }
842 };
843 let mut filled = 0;
844 for (slot, r) in slots.iter_mut().zip(got.iter()).take(n) {
845 let Some(r) = r else { continue };
846 let from = crate::addr::normalize_socket(r.from);
847 if self.admit(from, r.len, r.truncated) {
848 slot.datagram = Some(Datagram {
849 len: r.len,
850 from,
851 truncated: r.truncated,
852 destination: None,
853 });
854 filled += 1;
855 }
856 }
857 Ok(filled)
858 }
859
860 #[cfg(not(target_os = "linux"))]
861 fn recv_many(&mut self, slots: &mut [DatagramBuffer<'_>]) -> Result<usize, NetError> {
862 let (first, rest) = match slots.split_first_mut() {
863 Some(parts) => parts,
864 None => return Ok(0),
865 };
866 first.datagram = Some(self.recv_from(first.buf)?);
867 let mut filled = 1;
868 self.inner
869 .set_nonblocking(true)
870 .map_err(|e| NetError::from_os("ioctl", e))?;
871 for slot in rest.iter_mut().take(63) {
872 match self.recv_from(slot.buf) {
873 Ok(d) => {
874 slot.datagram = Some(d);
875 filled += 1;
876 }
877 Err(_) => break,
878 }
879 }
880 self.inner
881 .set_nonblocking(false)
882 .map_err(|e| NetError::from_os("ioctl", e))?;
883 Ok(filled)
884 }
885
886 pub fn send_batch(&mut self, datagrams: &[OutgoingDatagram<'_>]) -> Result<usize, NetError> {
894 let mut sent = 0;
895 while sent < datagrams.len() {
896 match self.send_some(&datagrams[sent..]) {
897 Ok(0) => break,
898 Ok(n) => sent += n,
899 Err(e) if sent == 0 => return Err(e),
900 Err(_) => break,
901 }
902 }
903 Ok(sent)
904 }
905
906 fn charge(&mut self, datagrams: &[OutgoingDatagram<'_>]) -> Result<usize, NetError> {
909 let now = Instant::now();
910 let mut allowed = 0;
911 for d in datagrams.iter().take(64) {
912 if !self.guard.charge(d.to, d.bytes.len(), now) {
913 self.stats.refused += 1;
914 break;
915 }
916 allowed += 1;
917 }
918 if allowed == 0 && !datagrams.is_empty() {
919 return Err(NetError::Limit {
920 which: LimitKind::Amplification,
921 });
922 }
923 Ok(allowed)
924 }
925
926 #[cfg(target_os = "linux")]
927 fn send_some(&mut self, datagrams: &[OutgoingDatagram<'_>]) -> Result<usize, NetError> {
928 let allowed = self.charge(datagrams)?;
929 let mut wire = [(&[][..], SocketAddr::from(([0, 0, 0, 0], 0))); sys::BATCH_MAX];
930 for (w, d) in wire.iter_mut().zip(datagrams.iter().take(allowed)) {
931 *w = (d.bytes, self.wire(d.to));
932 }
933 let n = sys::udp_send_many(self.inner.sock(), &wire[..allowed])
934 .map_err(|e| NetError::from_os("sendmmsg", e))?;
935 self.stats.sent += n as u64;
936 Ok(n)
937 }
938
939 #[cfg(not(target_os = "linux"))]
940 fn send_some(&mut self, datagrams: &[OutgoingDatagram<'_>]) -> Result<usize, NetError> {
941 let allowed = self.charge(datagrams)?;
942 let mut n = 0;
943 for d in &datagrams[..allowed] {
944 let wire = self.wire(d.to);
945 if let Err(e) = self.inner.send_to(d.bytes, wire) {
946 if n == 0 {
947 return Err(NetError::from_os("sendto", e));
948 }
949 break;
950 }
951 self.stats.sent += 1;
952 n += 1;
953 }
954 Ok(n)
955 }
956
957 pub fn join_multicast(
964 &self,
965 group: IpAddr,
966 interface: MulticastInterface,
967 ) -> Result<(), NetError> {
968 let result = match (group, interface) {
969 (IpAddr::V4(g), MulticastInterface::Any) => {
970 self.inner.join_multicast_v4(&g, &Ipv4Addr::UNSPECIFIED)
971 }
972 (IpAddr::V4(g), MulticastInterface::V4(i)) => self.inner.join_multicast_v4(&g, &i),
973 (IpAddr::V6(g), MulticastInterface::Any) => self.inner.join_multicast_v6(&g, 0),
974 (IpAddr::V6(g), MulticastInterface::V6Index(i)) => self.inner.join_multicast_v6(&g, i),
975 _ => {
976 return Err(NetError::InvalidConfig {
977 field: "interface",
978 reason: ConfigReason::Inconsistent,
979 });
980 }
981 };
982 result.map_err(|e| NetError::from_os("setsockopt", e))
983 }
984
985 pub fn recv(&mut self, buf: &mut [u8]) -> Result<Datagram, NetError> {
991 self.recv_from(buf)
992 }
993
994 pub fn send_to(&mut self, buf: &[u8], to: SocketAddr) -> Result<usize, NetError> {
1003 if !self.guard.charge(to, buf.len(), Instant::now()) {
1004 self.stats.refused += 1;
1005 return Err(NetError::Limit {
1006 which: LimitKind::Amplification,
1007 });
1008 }
1009 let wire = self.wire(to);
1010 let n = self
1011 .inner
1012 .send_to(buf, wire)
1013 .map_err(|e| NetError::from_os("sendto", e))?;
1014 self.stats.sent += 1;
1015 Ok(n)
1016 }
1017
1018 pub fn send(&mut self, buf: &[u8]) -> Result<usize, NetError> {
1024 let peer = self.peer.ok_or(NetError::Closed)?;
1025 if !self.guard.charge(peer, buf.len(), Instant::now()) {
1026 self.stats.refused += 1;
1027 return Err(NetError::Limit {
1028 which: LimitKind::Amplification,
1029 });
1030 }
1031 let n = self
1032 .inner
1033 .send(buf)
1034 .map_err(|e| NetError::from_os("send", e))?;
1035 self.stats.sent += 1;
1036 Ok(n)
1037 }
1038
1039 pub fn connect(&mut self, to: SocketAddr) -> Result<(), NetError> {
1046 self.inner
1047 .connect(self.wire(to))
1048 .map_err(|e| NetError::from_os("connect", e))?;
1049 self.peer = Some(to);
1050 Ok(())
1051 }
1052
1053 pub fn mark_verified(&mut self, peer: SocketAddr) {
1060 self.guard.verify(peer, Instant::now());
1061 }
1062
1063 pub fn forget_verified(&mut self, peer: SocketAddr) {
1066 self.guard.forget(peer, Instant::now());
1067 }
1068
1069 pub fn set_read_timeout(&mut self, timeout: Option<Duration>) -> Result<(), NetError> {
1075 if timeout == Some(Duration::ZERO) {
1076 return Err(NetError::InvalidConfig {
1077 field: "read_timeout",
1078 reason: ConfigReason::Zero,
1079 });
1080 }
1081 self.inner
1082 .set_read_timeout(timeout)
1083 .map_err(|e| NetError::from_os("setsockopt", e))?;
1084 self.read_timeout = timeout;
1085 Ok(())
1086 }
1087
1088 pub(crate) fn set_nonblocking(&self) -> Result<(), NetError> {
1090 self.inner
1091 .set_nonblocking(true)
1092 .map_err(|e| NetError::from_os("ioctl", e))
1093 }
1094
1095 pub(crate) fn raw_sock(&self) -> sys::Sock<'_> {
1096 self.inner.sock()
1097 }
1098
1099 pub fn local_addr(&self) -> Result<SocketAddr, NetError> {
1105 self.inner
1106 .local_addr()
1107 .map_err(|e| NetError::from_os("getsockname", e))
1108 }
1109
1110 #[must_use]
1112 pub fn stats(&self) -> UdpStats {
1113 UdpStats {
1114 sources: self.guard.slots.len() as u32,
1115 ..self.stats
1116 }
1117 }
1118
1119 fn wire(&self, to: SocketAddr) -> SocketAddr {
1121 match to {
1122 SocketAddr::V4(a) if self.v6 => {
1123 SocketAddr::V6(SocketAddrV6::new(a.ip().to_ipv6_mapped(), a.port(), 0, 0))
1124 }
1125 other => other,
1126 }
1127 }
1128}
1129
1130pub trait UdpSession: Send + 'static {
1145 fn on_datagram(&mut self, cx: &mut UdpContext<'_>, from: SocketAddr, bytes: &[u8]);
1147}
1148
1149#[derive(Debug)]
1151pub struct UdpContext<'a> {
1152 pub(crate) socket: &'a mut UdpSocket,
1153}
1154
1155impl UdpContext<'_> {
1156 pub fn send_to(&mut self, bytes: &[u8], to: SocketAddr) -> Result<usize, NetError> {
1162 self.socket.send_to(bytes, to)
1163 }
1164
1165 pub fn mark_verified(&mut self, peer: SocketAddr) {
1167 self.socket.mark_verified(peer);
1168 }
1169
1170 pub fn forget_verified(&mut self, peer: SocketAddr) {
1172 self.socket.forget_verified(peer);
1173 }
1174
1175 #[must_use]
1177 pub fn now(&self) -> Instant {
1178 Instant::now()
1179 }
1180}
1181
1182pub trait UdpSessionFactory: Send + Sync + 'static {
1185 fn open(&self, listener: &crate::tcp::ListenerInfo) -> Box<dyn UdpSession>;
1187}
1188
1189impl<F, S> UdpSessionFactory for F
1190where
1191 F: Fn(&crate::tcp::ListenerInfo) -> S + Send + Sync + 'static,
1192 S: UdpSession,
1193{
1194 fn open(&self, listener: &crate::tcp::ListenerInfo) -> Box<dyn UdpSession> {
1195 Box::new(self(listener))
1196 }
1197}
1198
1199fn past(deadline: Option<Instant>) -> bool {
1200 deadline.is_some_and(|d| Instant::now() >= d)
1201}
1202
1203#[cfg(unix)]
1204impl std::os::fd::AsFd for UdpSocket {
1205 fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
1206 self.inner.as_fd()
1207 }
1208}
1209
1210#[cfg(windows)]
1211impl std::os::windows::io::AsSocket for UdpSocket {
1212 fn as_socket(&self) -> std::os::windows::io::BorrowedSocket<'_> {
1213 self.inner.as_socket()
1214 }
1215}
1216
1217#[cfg(any(fuzzing, test))]
1224pub(crate) fn fuzz_udp(data: &[u8]) {
1225 let Some((head, ops)) = data.split_first_chunk::<5>() else {
1226 return;
1227 };
1228 let global = UdpBudget {
1229 datagrams_per_sec: u32::from(head[3]) + 1,
1230 bytes_per_sec: u32::from(head[3]) * 64 + 64,
1231 burst: u32::from(head[4] % 16) + 1,
1232 };
1233 let options = UdpOptions::new()
1234 .source_table(u32::from(head[0] % 16) + 1)
1235 .verified_table(u32::from(head[1] % 8) + 1)
1236 .amplification_factor(head[2] % 3 + 1)
1237 .amplification_window(Duration::from_secs(u64::from(head[2] >> 2) % 8 + 1))
1238 .verification_lifetime(Duration::from_secs(u64::from(head[4] >> 4) + 1))
1239 .source_budget(UdpBudget {
1240 datagrams_per_sec: 20,
1241 bytes_per_sec: 4_000,
1242 burst: 4,
1243 })
1244 .global_budget(global);
1245 if options.validate().is_err() {
1246 return;
1247 }
1248 let start = Instant::now();
1249 let mut now = start;
1250 let mut guard = Guard::new(options.clone(), now);
1251 let mut proven: HashMap<PeerKey, Instant> = HashMap::new();
1253 let mut admitted = 0u64;
1254 for op in ops.chunks(4) {
1255 let n = op.get(1).copied().unwrap_or(0);
1256 let host = match n % 3 {
1258 0 => IpAddr::from([10, 0, 0, n >> 2]),
1259 1 => IpAddr::V6(std::net::Ipv4Addr::new(10, 0, 0, n >> 2).to_ipv6_mapped()),
1260 _ => IpAddr::from([0xfd00, 0, 0, 0, 0, 0, 0, u16::from(n >> 2)]),
1261 };
1262 let peer = SocketAddr::new(host, u16::from(op.get(2).copied().unwrap_or(0) % 4));
1263 let arg = usize::from(op.get(3).copied().unwrap_or(0)) * 8;
1264 match op[0] % 6 {
1265 0 => {
1266 let mut overflow = false;
1267 let from = crate::addr::normalize_socket(peer);
1268 if guard.admit(from.ip(), arg, now, &mut overflow) {
1269 admitted += 1;
1270 }
1271 }
1272 1 => {
1273 let verified = guard.is_verified(peer, now);
1274 let sent = guard.charge(peer, arg, now);
1275 if sent && !verified && arg > 0 {
1276 let i = guard.index[&normalize(peer.ip())] as usize;
1277 let e = &guard.slots[i];
1278 let allowed = u64::from(options.factor)
1279 .saturating_mul(e.received[0].saturating_add(e.received[1]));
1280 assert!(
1281 e.sent[0].saturating_add(e.sent[1]) <= allowed,
1282 "sent past the factor"
1283 );
1284 }
1285 }
1286 2 => {
1287 guard.verify(peer, now);
1288 proven.insert(peer_key(peer), now + options.verified_for);
1289 }
1290 3 => {
1291 guard.forget(peer, now);
1292 proven.remove(&peer_key(peer));
1293 }
1294 4 => now += Duration::from_millis(arg as u64 * 13),
1295 _ => {
1296 let model = proven.get(&peer_key(peer)).is_some_and(|&t| now < t);
1297 assert!(
1298 model || !guard.is_verified(peer, now),
1299 "verified without a live proof"
1300 );
1301 }
1302 }
1303 assert_eq!(guard.index.len(), guard.slots.len());
1304 assert!(guard.slots.len() <= options.table as usize);
1305 for (ip, &i) in &guard.index {
1306 assert_eq!(guard.slots[i as usize].ip, *ip, "index points elsewhere");
1307 }
1308 assert_eq!(guard.proofs.len(), guard.proved.len());
1309 assert!(guard.proved.len() <= options.verified_table as usize);
1310 for (key, &i) in &guard.proofs {
1311 assert_eq!(guard.proved[i as usize].key, *key, "proof points elsewhere");
1312 }
1313 let elapsed = now.saturating_duration_since(start).as_secs_f64();
1314 let most = f64::from(global.burst) + f64::from(global.datagrams_per_sec) * elapsed + 1.0;
1315 assert!(
1316 admitted as f64 <= most,
1317 "{admitted} admitted, at most {most}"
1318 );
1319 }
1320}
1321
1322#[cfg(test)]
1323mod tests {
1324 use super::*;
1325
1326 fn ip(n: u8) -> IpAddr {
1327 IpAddr::from([10, 0, 0, n])
1328 }
1329
1330 #[test]
1333 fn test_guard_holds_under_random_operations() {
1334 let mut x = 0x9e37_79b9_7f4a_7c15u64;
1335 for _ in 0..2_000 {
1336 let len = 5 + (x % 400) as usize;
1337 let data: Vec<u8> = (0..len)
1338 .map(|_| {
1339 x ^= x << 13;
1340 x ^= x >> 7;
1341 x ^= x << 17;
1342 x as u8
1343 })
1344 .collect();
1345 fuzz_udp(&data);
1346 }
1347 }
1348
1349 #[test]
1350 fn test_bucket_refills_at_its_rate() {
1351 let b = UdpBudget {
1352 datagrams_per_sec: 10,
1353 bytes_per_sec: 1_000,
1354 burst: 2,
1355 };
1356 let t = Instant::now();
1357 let mut bucket = Bucket::full(&b, t);
1358 assert!(bucket.take(&b, 100, t));
1359 assert!(bucket.take(&b, 100, t));
1360 assert!(!bucket.take(&b, 100, t), "burst used up");
1361 assert!(bucket.take(&b, 100, t + Duration::from_millis(100)));
1363 assert!(!bucket.take(&b, 1_001, t + Duration::from_secs(5)));
1365 }
1366
1367 fn at(n: u8, port: u16) -> SocketAddr {
1368 SocketAddr::from(([10, 0, 0, n], port))
1369 }
1370
1371 #[test]
1372 fn test_amplification_factor_one_until_verified() {
1373 let t = Instant::now();
1375 let mut g = Guard::new(UdpOptions::new(), t);
1376 let mut o = false;
1377 let a = at(1, 1_000);
1378 assert!(!g.charge(a, 1, t), "never heard from");
1379 assert!(g.charge(a, 0, t));
1380 assert!(g.admit(ip(1), 1, t, &mut o));
1381 assert!(!g.charge(a, 2, t));
1382 assert!(g.charge(a, 1, t));
1383 assert!(!g.charge(a, 1, t), "the allowance is spent");
1384 g.verify(a, t);
1385 assert!(g.charge(a, 10_000, t));
1386 assert!(
1387 !g.charge(at(1, 2_000), 1, t),
1388 "another port is not verified, and the IP's allowance is spent"
1389 );
1390 }
1391
1392 #[test]
1393 fn test_amplification_factor_three_and_the_window() {
1394 let t = Instant::now();
1395 let w = Duration::from_secs(10);
1396 let mut g = Guard::new(UdpOptions::new().amplification_factor(3), t);
1397 let mut o = false;
1398 assert!(g.admit(ip(1), 100, t, &mut o));
1399 assert!(!g.charge(at(1, 9), 301, t));
1400 assert!(g.charge(at(1, 9), 300, t));
1401 assert!(!g.charge(at(1, 9), 1, t));
1402 assert!(g.admit(ip(2), 100, t, &mut o));
1404 assert!(g.charge(at(2, 9), 300, t + w + Duration::from_millis(1)));
1405 assert!(g.admit(ip(3), 100, t, &mut o));
1407 assert!(!g.charge(at(3, 9), 1, t + 3 * w));
1408 }
1409
1410 #[test]
1411 fn test_source_budget_drops_and_others_pass() {
1412 let t = Instant::now();
1413 let budget = UdpBudget {
1414 datagrams_per_sec: 1,
1415 bytes_per_sec: 10_000,
1416 burst: 3,
1417 };
1418 let mut g = Guard::new(UdpOptions::new().source_budget(budget), t);
1419 let mut o = false;
1420 let passed = (0..10).filter(|_| g.admit(ip(1), 10, t, &mut o)).count();
1421 assert_eq!(passed, 3);
1422 assert!(
1423 g.admit(ip(2), 10, t, &mut o),
1424 "another source has its own budget"
1425 );
1426 assert!(!o);
1427 }
1428
1429 #[test]
1430 fn test_global_budget_caps_every_source() {
1431 let t = Instant::now();
1432 let global = UdpBudget {
1433 datagrams_per_sec: 1,
1434 bytes_per_sec: 10_000,
1435 burst: 4,
1436 };
1437 let mut g = Guard::new(UdpOptions::new().global_budget(global), t);
1438 let mut o = false;
1439 let passed = (1..=10).filter(|&n| g.admit(ip(n), 10, t, &mut o)).count();
1440 assert_eq!(passed, 4);
1441 }
1442
1443 #[test]
1444 fn test_full_table_evicts_strangers() {
1445 let t = Instant::now();
1447 let mut g = Guard::new(UdpOptions::new().source_table(4), t);
1448 let mut o = false;
1449 for n in 1..=4 {
1450 assert!(g.admit(ip(n), 10, t, &mut o));
1451 }
1452 assert!(g.admit(ip(5), 10, t, &mut o));
1455 assert!(!o, "an entry was evicted");
1456 assert!(g.index.contains_key(&ip(5)));
1457 assert_eq!(g.slots.len(), 4);
1458 }
1459
1460 #[test]
1461 fn test_overflow_strangers_get_nothing_and_verified_peers_stay_answered() {
1462 let t = Instant::now();
1463 let mut g = Guard::new(UdpOptions::new().source_table(64), t);
1464 let mut o = false;
1465 let source = |n: u8| IpAddr::from([10, 0, 1, n]);
1466 for n in 0..64u8 {
1467 assert!(g.admit(source(n), 10, t, &mut o));
1468 }
1469 let peer = SocketAddr::from((source(0), 7));
1470 g.verify(peer, t);
1471 assert!(g.admit(ip(200), 10, t, &mut o));
1472 assert!(o, "no room: the overflow budget");
1473 assert!(
1474 !g.charge(at(200, 9), 1, t),
1475 "an overflow stranger gets no allowance"
1476 );
1477 assert!(g.charge(peer, 10_000, t), "verification needs no entry");
1478 }
1479
1480 #[test]
1483 fn test_verification_is_per_port_and_expires() {
1484 let t = Instant::now();
1485 let s = Duration::from_secs;
1486 let mut g = Guard::new(UdpOptions::new(), t);
1487 let a = at(1, 1_000);
1488 g.verify(a, t);
1489 assert!(g.charge(a, 10_000, t));
1490 assert!(!g.charge(at(1, 2_000), 1, t), "another port is a new path");
1491 assert!(g.charge(a, 10_000, t + s(59)));
1492 assert!(!g.charge(a, 1, t + s(61)), "the proof lapsed");
1493 g.verify(a, t + s(61));
1494 g.verify(a, t + s(100));
1495 assert!(
1496 g.charge(a, 10_000, t + s(159)),
1497 "a new proof starts it again"
1498 );
1499 g.forget(a, t + s(150));
1500 assert!(!g.charge(a, 1, t + s(151)));
1501 let mapped = SocketAddr::from((Ipv4Addr::new(10, 0, 0, 1).to_ipv6_mapped(), 3_000));
1503 g.verify(mapped, t);
1504 assert!(g.charge(at(1, 3_000), 10_000, t));
1505 }
1506
1507 #[test]
1510 fn test_verified_table_is_bounded() {
1511 let t = Instant::now();
1512 let s = Duration::from_secs;
1513 let mut g = Guard::new(UdpOptions::new().verified_table(2), t);
1514 g.verify(at(1, 1), t);
1515 g.verify(at(2, 1), t);
1516 g.verify(at(3, 1), t);
1517 assert_eq!(g.proved.len(), 2);
1518 assert!(!g.is_verified(at(1, 1), t));
1519 assert!(g.is_verified(at(2, 1), t) && g.is_verified(at(3, 1), t));
1520 let mut g = Guard::new(
1521 UdpOptions::new()
1522 .verified_table(2)
1523 .verification_lifetime(s(1)),
1524 t,
1525 );
1526 g.verify(at(1, 1), t);
1527 g.verify(at(2, 1), t + s(2));
1528 g.verify(at(3, 1), t + s(2));
1529 assert!(g.is_verified(at(2, 1), t + s(2)), "the lapsed one went");
1530 assert!(g.is_verified(at(3, 1), t + s(2)));
1531 }
1532
1533 #[test]
1535 fn test_verified_peers_leave_room_for_newcomers() {
1536 let t = Instant::now();
1537 let mut g = Guard::new(UdpOptions::new().source_table(4), t);
1538 let mut o = false;
1539 for n in 1..=4 {
1540 assert!(g.admit(ip(n), 10, t, &mut o));
1541 g.verify(at(n, 1), t);
1542 }
1543 let later = t + Duration::from_millis(10);
1544 assert!(g.admit(ip(9), 100, later, &mut o));
1545 assert!(!o, "a newcomer finds a slot");
1546 assert!(g.charge(at(9, 1), 100, later), "and its allowance");
1547 }
1548
1549 #[test]
1551 fn test_dropped_datagrams_do_not_keep_entries() {
1552 let t = Instant::now();
1553 let budget = UdpBudget {
1554 datagrams_per_sec: 1,
1555 bytes_per_sec: 10_000,
1556 burst: 1,
1557 };
1558 let options = UdpOptions::new().source_table(64).source_budget(budget);
1559 let mut g = Guard::new(options, t);
1560 let mut o = false;
1561 for n in 0..64u8 {
1562 assert!(g.admit(IpAddr::from([10, 0, 1, n]), 10, t, &mut o));
1563 }
1564 assert!(g.admit(ip(200), 10, t, &mut o));
1566 assert!(o);
1567 for n in 0..64u8 {
1569 assert!(!g.admit(IpAddr::from([10, 0, 1, n]), 10, t, &mut o));
1570 }
1571 let mut o = false;
1572 assert!(g.admit(ip(201), 10, t, &mut o));
1573 assert!(!o, "the dropped traffic did not keep the table full");
1574 }
1575
1576 #[test]
1579 fn test_full_table_traffic_turns_the_hand() {
1580 let t = Instant::now();
1581 let mut g = Guard::new(UdpOptions::new().source_table(64), t);
1582 let mut o = false;
1583 for n in 0..64u8 {
1584 assert!(g.admit(IpAddr::from([10, 0, 1, n]), 10, t, &mut o));
1585 }
1586 assert!(g.admit(ip(200), 10, t, &mut o));
1587 assert!(o, "every entry was recently used");
1588 let later = t + Duration::from_secs(1);
1590 for n in 0..64u8 {
1591 assert!(g.admit(IpAddr::from([10, 0, 1, n]), 10, later, &mut o));
1592 }
1593 let mut o = false;
1594 assert!(g.admit(ip(201), 10, later, &mut o));
1595 assert!(!o, "a newcomer finds a slot");
1596 }
1597
1598 #[test]
1601 fn test_huge_durations_never_panic() {
1602 for options in [
1603 UdpOptions::new().amplification_window(Duration::MAX),
1604 UdpOptions::new().amplification_window(Duration::from_secs(3_601)),
1605 UdpOptions::new().verification_lifetime(Duration::MAX),
1606 UdpOptions::new().verification_lifetime(Duration::from_millis(999)),
1607 UdpOptions::new().verified_table(0),
1608 ] {
1609 assert!(matches!(
1610 options.validate(),
1611 Err(NetError::InvalidConfig { .. })
1612 ));
1613 }
1614 let t = Instant::now();
1616 let options = UdpOptions::new()
1617 .amplification_window(Duration::MAX)
1618 .verification_lifetime(Duration::MAX);
1619 let mut g = Guard::new(options, t);
1620 let mut o = false;
1621 assert!(g.admit(ip(1), 10, t, &mut o));
1622 assert!(g.charge(at(1, 1), 10, t + Duration::from_secs(1)));
1623 g.verify(at(1, 1), t);
1624 let mut s = UdpSocket::bind("127.0.0.1:0").unwrap();
1625 s.set_read_timeout(Some(Duration::MAX)).unwrap();
1626 let c = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
1627 c.send_to(b"hi", s.local_addr().unwrap()).unwrap();
1628 let mut buf = [0u8; 8];
1629 assert_eq!(s.recv_from(&mut buf).unwrap().len, 2);
1630 }
1631
1632 #[test]
1635 fn test_verified_port_does_not_cover_the_ip() {
1636 let mut server = UdpSocket::bind("127.0.0.1:0").unwrap();
1637 server
1638 .set_read_timeout(Some(Duration::from_secs(5)))
1639 .unwrap();
1640 let a = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
1641 let b = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
1642 a.send_to(b"hello", server.local_addr().unwrap()).unwrap();
1643 let mut buf = [0u8; 16];
1644 let d = server.recv_from(&mut buf).unwrap();
1645 server.mark_verified(d.from);
1646 assert_eq!(server.send_to(&[1u8; 1_000], d.from).unwrap(), 1_000);
1647 assert!(matches!(
1648 server.send_to(&[1u8; 1_000], b.local_addr().unwrap()),
1649 Err(NetError::Limit {
1650 which: LimitKind::Amplification
1651 })
1652 ));
1653 server.forget_verified(d.from);
1654 assert!(server.send_to(&[1u8; 1_000], d.from).is_err());
1655 assert_eq!(server.send_to(&[1u8; 5], d.from).unwrap(), 5);
1656 }
1657
1658 #[test]
1659 fn test_options_validate() {
1660 let bad = |o: UdpOptions| matches!(o.validate(), Err(NetError::InvalidConfig { .. }));
1661 assert!(bad(UdpOptions::new().amplification_factor(0)));
1662 assert!(bad(UdpOptions::new().amplification_factor(4)));
1663 assert!(bad(
1664 UdpOptions::new().amplification_window(Duration::from_millis(500))
1665 ));
1666 assert!(bad(UdpOptions::new().source_table(0)));
1667 assert!(bad(UdpOptions::new().source_budget(UdpBudget {
1668 datagrams_per_sec: 0,
1669 bytes_per_sec: 1,
1670 burst: 1
1671 })));
1672 assert!(UdpOptions::new().validate().is_ok());
1673 assert_eq!(UdpOptions::default(), UdpOptions::new());
1674 }
1675
1676 #[test]
1677 fn test_echo_truncation_and_zero_length() {
1678 let mut s = UdpSocket::bind("127.0.0.1:0").unwrap();
1679 s.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
1680 let to = s.local_addr().unwrap();
1681 let c = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
1682 c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
1683 c.send_to(b"hello", to).unwrap();
1684 let mut buf = [0u8; 64];
1685 let d = s.recv_from(&mut buf).unwrap();
1686 assert_eq!(
1687 (d.len, d.truncated, d.from),
1688 (5, false, c.local_addr().unwrap())
1689 );
1690 assert_eq!(s.send_to(&buf[..5], d.from).unwrap(), 5);
1691 let mut back = [0u8; 8];
1692 assert_eq!(c.recv(&mut back).unwrap(), 5);
1693 assert!(matches!(
1694 s.send_to(b"x", d.from),
1695 Err(NetError::Limit {
1696 which: LimitKind::Amplification
1697 })
1698 ));
1699 c.send_to(&[7u8; 100], to).unwrap();
1701 let mut small = [0u8; 10];
1702 let d = s.recv_from(&mut small).unwrap();
1703 assert!(d.truncated);
1704 c.send_to(&[], to).unwrap();
1705 let d = s.recv_from(&mut buf).unwrap();
1706 assert_eq!((d.len, d.truncated), (0, false));
1707 let st = s.stats();
1708 assert_eq!(
1709 (st.received, st.sent, st.refused, st.truncated),
1710 (3, 1, 1, 1)
1711 );
1712 assert_eq!(st.sources, 1);
1713 }
1714
1715 #[test]
1716 fn test_icmp_reports_never_end_the_socket() {
1717 use crate::sys::shim::{Fault, Op, clear_here, program_here};
1719 let mut s = UdpSocket::bind("127.0.0.1:0").unwrap();
1720 s.set_read_timeout(Some(Duration::from_millis(300)))
1721 .unwrap();
1722 let closed = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
1723 let gone = closed.local_addr().unwrap();
1724 drop(closed);
1725 s.connect(gone).unwrap();
1726 s.mark_verified(gone);
1727 s.send(b"anyone?").unwrap();
1728 program_here(Op::Recv, 0, 1, Fault::Kind(io::ErrorKind::ConnectionReset));
1729 let mut buf = [0u8; 16];
1730 assert!(matches!(
1731 s.recv(&mut buf),
1732 Err(NetError::TimedOut {
1733 kind: TimeoutKind::Read
1734 })
1735 ));
1736 clear_here();
1737 assert!(s.stats().icmp_errors >= 1);
1738 let mut t = UdpSocket::bind("127.0.0.1:0").unwrap();
1740 t.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
1741 let c = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
1742 c.send_to(b"ok", t.local_addr().unwrap()).unwrap();
1743 assert_eq!(t.recv_from(&mut buf).unwrap().len, 2);
1744 }
1745
1746 #[test]
1747 fn test_dual_stack_replies_to_ipv4_sources() {
1748 let Ok(mut s) = UdpSocket::bind_with("[::]:0", UdpOptions::new().ipv6_only(false)) else {
1749 return; };
1751 s.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
1752 let port = s.local_addr().unwrap().port();
1753 let c = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
1754 c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
1755 c.send_to(b"v4", ("127.0.0.1", port)).unwrap();
1756 let mut buf = [0u8; 8];
1757 let d = s.recv_from(&mut buf).unwrap();
1758 assert!(d.from.is_ipv4(), "normalized: {}", d.from);
1759 s.send_to(b"ok", d.from).unwrap();
1760 assert_eq!(c.recv(&mut buf).unwrap(), 2);
1761 }
1762
1763 fn verified_pair() -> (UdpSocket, UdpSocket) {
1764 let mut a = UdpSocket::bind("127.0.0.1:0").unwrap();
1765 let mut b = UdpSocket::bind("127.0.0.1:0").unwrap();
1766 let (aa, ba) = (a.local_addr().unwrap(), b.local_addr().unwrap());
1767 a.mark_verified(ba);
1768 b.mark_verified(aa);
1769 a.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
1770 b.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
1771 (a, b)
1772 }
1773
1774 #[test]
1775 fn test_batches_cross_in_one_call_each() {
1776 let (mut a, mut b) = verified_pair();
1777 let to = b.local_addr().unwrap();
1778 let bodies: Vec<Vec<u8>> = (0..10u8).map(|i| vec![i; 1 + usize::from(i)]).collect();
1779 let out: Vec<_> = bodies
1780 .iter()
1781 .map(|b| OutgoingDatagram { bytes: b, to })
1782 .collect();
1783 assert_eq!(a.send_batch(&out).unwrap(), 10);
1784 std::thread::sleep(Duration::from_millis(50));
1785 let mut store = vec![[0u8; 64]; 16];
1786 let mut seen = 0;
1787 while seen < 10 {
1788 let mut slots: Vec<_> = store.iter_mut().map(|b| DatagramBuffer::new(b)).collect();
1789 let n = b.recv_batch(&mut slots).unwrap();
1790 assert!(n > 0);
1791 for slot in &slots {
1792 if let Some(d) = slot.datagram {
1793 assert_eq!(d.from, a.local_addr().unwrap());
1794 assert_eq!(&slot.buf[..d.len], &bodies[seen][..]);
1795 seen += 1;
1796 }
1797 }
1798 }
1799 assert_eq!(a.stats().sent, 10);
1800 assert_eq!(b.stats().received, 10);
1801 }
1802
1803 #[test]
1806 fn test_batch_send_stays_under_the_guard() {
1807 let mut server = UdpSocket::bind("127.0.0.1:0").unwrap();
1808 let client = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
1809 let to = client.local_addr().unwrap();
1810 client
1811 .send_to(&[0u8; 100], server.local_addr().unwrap())
1812 .unwrap();
1813 let mut buf = [0u8; 200];
1814 server.recv_from(&mut buf).unwrap();
1815 let big = [1u8; 40];
1816 let out = [OutgoingDatagram { bytes: &big, to }; 4];
1817 assert_eq!(
1818 server.send_batch(&out).unwrap(),
1819 2,
1820 "100 bytes of allowance"
1821 );
1822 assert!(matches!(
1823 server.send_batch(&out),
1824 Err(NetError::Limit {
1825 which: LimitKind::Amplification
1826 })
1827 ));
1828 }
1829
1830 #[cfg(unix)]
1831 #[test]
1832 fn test_packet_info_reports_the_destination() {
1833 let mut server =
1834 UdpSocket::bind_with("0.0.0.0:0", UdpOptions::new().packet_info(true)).unwrap();
1835 server
1836 .set_read_timeout(Some(Duration::from_secs(5)))
1837 .unwrap();
1838 let port = server.local_addr().unwrap().port();
1839 let client = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
1840 client.send_to(b"hi", ("127.0.0.1", port)).unwrap();
1841 let mut buf = [0u8; 16];
1842 let d = server.recv_from(&mut buf).unwrap();
1843 assert_eq!(d.len, 2);
1844 assert_eq!(d.destination, Some("127.0.0.1".parse().unwrap()));
1845 }
1846
1847 #[cfg(windows)]
1848 #[test]
1849 fn test_packet_info_is_refused_on_windows() {
1850 assert!(matches!(
1851 UdpSocket::bind_with("127.0.0.1:0", UdpOptions::new().packet_info(true)),
1852 Err(NetError::Unsupported { .. })
1853 ));
1854 }
1855
1856 #[test]
1857 fn test_multicast_join_checks_the_family() {
1858 let socket = UdpSocket::bind("0.0.0.0:0").unwrap();
1859 let group: IpAddr = "239.1.2.3".parse().unwrap();
1860 assert!(matches!(
1861 socket.join_multicast(group, MulticastInterface::V6Index(1)),
1862 Err(NetError::InvalidConfig { .. })
1863 ));
1864 let _ = socket.join_multicast(group, MulticastInterface::Any);
1866 }
1867}