Skip to main content

rustorb_rtps/
udp.rs

1//! The UDPv4 transport and the default port numbers
2//! (DDSI-RTPS 2.5, 8.5.3.4, 9.5 and 9.6.2).
3//!
4//! One RTPS message is the payload of one UDP datagram (9.5). A
5//! [`UdpTransport`] opens the four sockets a participant needs (discovery
6//! and user traffic, each unicast and multicast), receives on them with
7//! one thread per socket, and hands the datagrams over a channel. It does
8//! not depend on an async runtime.
9
10use std::io;
11use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};
12use std::sync::Arc;
13use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
14use std::sync::mpsc;
15use std::thread::JoinHandle;
16use std::time::Duration;
17
18use socket2::{Domain, Protocol, SockAddr, Socket, Type};
19
20use crate::types::Locator;
21
22/// The tunable parameters of the port number expressions
23/// (9.6.2.3). [`Default`] gives the values required for out-of-the-box
24/// interoperability.
25#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
26pub struct PortMapping {
27    /// PB, the port base number.
28    pub port_base: u32,
29    /// DG, the domain id gain.
30    pub domain_id_gain: u32,
31    /// PG, the participant id gain.
32    pub participant_id_gain: u32,
33    /// d0, offset of the discovery multicast port.
34    pub d0: u32,
35    /// d1, offset of the discovery unicast port.
36    pub d1: u32,
37    /// d2, offset of the user multicast port.
38    pub d2: u32,
39    /// d3, offset of the user unicast port.
40    pub d3: u32,
41}
42
43impl Default for PortMapping {
44    fn default() -> Self {
45        PortMapping {
46            port_base: 7400,
47            domain_id_gain: 250,
48            participant_id_gain: 2,
49            d0: 0,
50            d1: 10,
51            d2: 1,
52            d3: 11,
53        }
54    }
55}
56
57impl PortMapping {
58    fn port(&self, domain_id: u32, offset: u32, participant_id: Option<u32>) -> Option<u16> {
59        let mut p = u64::from(self.port_base)
60            + u64::from(self.domain_id_gain) * u64::from(domain_id)
61            + u64::from(offset);
62        if let Some(pid) = participant_id {
63            p += u64::from(self.participant_id_gain) * u64::from(pid);
64        }
65        u16::try_from(p).ok()
66    }
67
68    /// `SPDP_WELL_KNOWN_MULTICAST_PORT` = PB + DG * domainId + d0
69    /// (Table 9.15). `None` if it does not fit in 16 bits.
70    pub fn discovery_multicast_port(&self, domain_id: u32) -> Option<u16> {
71        self.port(domain_id, self.d0, None)
72    }
73
74    /// `SPDP_WELL_KNOWN_UNICAST_PORT` = PB + DG * domainId + d1 + PG *
75    /// participantId (Table 9.15).
76    pub fn discovery_unicast_port(&self, domain_id: u32, participant_id: u32) -> Option<u16> {
77        self.port(domain_id, self.d1, Some(participant_id))
78    }
79
80    /// The default user multicast port, PB + DG * domainId + d2
81    /// (Table 9.16).
82    pub fn user_multicast_port(&self, domain_id: u32) -> Option<u16> {
83        self.port(domain_id, self.d2, None)
84    }
85
86    /// The default user unicast port, PB + DG * domainId + d3 + PG *
87    /// participantId (Table 9.16).
88    pub fn user_unicast_port(&self, domain_id: u32, participant_id: u32) -> Option<u16> {
89        self.port(domain_id, self.d3, Some(participant_id))
90    }
91}
92
93/// The multicast address every participant announces on and listens to
94/// (9.6.2.4.1).
95pub const DEFAULT_MULTICAST_ADDRESS: Ipv4Addr = Ipv4Addr::new(239, 255, 0, 1);
96
97/// Settings of a [`UdpTransport`].
98#[derive(Clone, Debug)]
99pub struct UdpConfig {
100    /// The DDS domain id.
101    pub domain_id: u32,
102    /// The participant id. `None` picks the lowest id, starting at 0,
103    /// whose unicast ports are free (9.6.2.1).
104    pub participant_id: Option<u32>,
105    /// The highest participant id tried when `participant_id` is `None`.
106    pub max_participant_id: u32,
107    /// The port number parameters.
108    pub ports: PortMapping,
109    /// The interfaces to use, by their IPv4 address. Empty means the
110    /// system's choice: multicast is joined on the default interface and
111    /// the unicast locators use the address of the default route.
112    pub interfaces: Vec<Ipv4Addr>,
113    /// The multicast group.
114    pub multicast_address: Ipv4Addr,
115    /// The time-to-live of multicast datagrams sent.
116    pub multicast_ttl: u32,
117    /// Whether multicast datagrams sent are also delivered to this host,
118    /// so that participants on the same host find each other.
119    pub multicast_loopback: bool,
120    /// The receive buffer to ask for on each socket that receives
121    /// (`SO_RCVBUF`; the system may give less). A large sample comes as
122    /// a burst of datagrams, which a small buffer drops. `None` keeps
123    /// the system's default.
124    pub receive_buffer_size: Option<usize>,
125    /// The send buffer to ask for on each socket (`SO_SNDBUF`). On macOS
126    /// it also bounds the largest datagram a socket can send, 9216
127    /// octets by default, so it must be at least the largest message
128    /// sent (up to 64 KiB, see `rustorb_rtps::frag`). `None` keeps the
129    /// system's default.
130    pub send_buffer_size: Option<usize>,
131}
132
133impl UdpConfig {
134    /// The default settings for a domain.
135    pub fn new(domain_id: u32) -> Self {
136        UdpConfig {
137            domain_id,
138            participant_id: None,
139            max_participant_id: 119,
140            ports: PortMapping::default(),
141            interfaces: Vec::new(),
142            multicast_address: DEFAULT_MULTICAST_ADDRESS,
143            multicast_ttl: 1,
144            multicast_loopback: true,
145            receive_buffer_size: Some(4 * 1024 * 1024),
146            send_buffer_size: Some(1024 * 1024),
147        }
148    }
149}
150
151/// Which socket a datagram came in on.
152#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
153pub enum Channel {
154    /// Discovery traffic, multicast port (d0).
155    DiscoveryMulticast,
156    /// Discovery traffic, unicast port (d1).
157    DiscoveryUnicast,
158    /// User traffic, multicast port (d2).
159    UserMulticast,
160    /// User traffic, unicast port (d3).
161    UserUnicast,
162}
163
164impl Channel {
165    /// Whether it is a channel of user traffic.
166    pub fn is_user(self) -> bool {
167        matches!(self, Channel::UserMulticast | Channel::UserUnicast)
168    }
169}
170
171/// One received datagram: one RTPS message.
172#[derive(Clone, Debug, PartialEq, Eq)]
173pub struct Datagram {
174    /// The socket it arrived on.
175    pub channel: Channel,
176    /// The sender.
177    pub source: SocketAddr,
178    /// The UDP payload.
179    pub data: Vec<u8>,
180}
181
182/// The receiving end of a [`UdpTransport`].
183///
184/// It stops yielding datagrams once the transport is dropped.
185#[derive(Debug)]
186pub struct Incoming {
187    rx: mpsc::Receiver<Datagram>,
188    queued: Arc<AtomicUsize>,
189}
190
191impl Incoming {
192    /// Waits for the next datagram. Returns `None` once the transport is
193    /// closed.
194    pub fn recv(&self) -> Option<Datagram> {
195        self.rx.recv().ok()
196    }
197
198    /// Waits at most `timeout` for the next datagram.
199    pub fn recv_timeout(&self, timeout: Duration) -> Option<Datagram> {
200        self.rx.recv_timeout(timeout).ok()
201    }
202
203    /// Returns a datagram if one is waiting.
204    pub fn try_recv(&self) -> Option<Datagram> {
205        self.rx.try_recv().ok()
206    }
207
208    /// Says that `user` datagrams of user traffic taken from here have
209    /// been handled. With a [`UserHandler`], user traffic goes to it only
210    /// while none taken from here is still being handled, so that it is
211    /// handled in the order it came.
212    pub fn handled(&self, user: usize) {
213        if user > 0 {
214            self.queued.fetch_sub(user, Ordering::AcqRel);
215        }
216    }
217}
218
219/// The most datagrams received and not yet taken from [`Incoming`].
220/// When it is full, the receive threads wait, the sockets' buffers fill
221/// and the kernel drops what does not fit, as when a receiver is slower
222/// than its senders: best-effort loses it, reliable repairs it. Without
223/// a bound, a fast sender made the receiver's memory grow without end
224/// (rustorb-dds#110). 1024 datagrams are at most 64 MiB.
225pub const INCOMING_CAPACITY: usize = 1024;
226
227/// Handles a datagram of user traffic on the thread that received it,
228/// or gives it back to be queued on [`Incoming`] like the others.
229pub type UserHandler = Arc<dyn Fn(Datagram) -> Option<Datagram> + Send + Sync>;
230
231/// Where the receive threads put what they receive: on the queue of
232/// [`Incoming`], or, for user traffic and with a [`UserHandler`], to
233/// that handler on the receiving thread, which saves a hand-over
234/// between threads for each message (rustorb-dds#111).
235#[derive(Clone)]
236pub struct Sink {
237    tx: mpsc::SyncSender<Datagram>,
238    user: Option<UserHandler>,
239    /// The user datagrams queued and not yet [`Incoming::handled`].
240    queued: Arc<AtomicUsize>,
241}
242
243impl std::fmt::Debug for Sink {
244    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
245        f.debug_struct("Sink")
246            .field("user_handler", &self.user.is_some())
247            .finish_non_exhaustive()
248    }
249}
250
251impl From<mpsc::SyncSender<Datagram>> for Sink {
252    fn from(tx: mpsc::SyncSender<Datagram>) -> Self {
253        Sink {
254            tx,
255            user: None,
256            queued: Arc::new(AtomicUsize::new(0)),
257        }
258    }
259}
260
261impl Sink {
262    /// Puts a datagram where it goes. `alone` says that no other has
263    /// come with it: user traffic goes to the handler only then (a
264    /// burst is queued, for the participant's thread to handle while
265    /// this one receives), and only while no user datagram queued
266    /// earlier is still to be handled. Returns `false` once the
267    /// receiving side is gone.
268    pub fn deliver(&self, d: Datagram, alone: bool) -> bool {
269        let user = d.channel.is_user();
270        let d = match &self.user {
271            Some(h) if user && alone && self.queued.load(Ordering::Acquire) == 0 => match h(d) {
272                Some(d) => d,
273                None => return true,
274            },
275            _ => d,
276        };
277        if user {
278            self.queued.fetch_add(1, Ordering::AcqRel);
279        }
280        if self.tx.send(d).is_ok() {
281            true
282        } else {
283            if user {
284                self.queued.fetch_sub(1, Ordering::AcqRel);
285            }
286            false
287        }
288    }
289}
290
291/// How often the receive threads look at the stop flag.
292const POLL: Duration = Duration::from_millis(100);
293/// The largest UDP payload.
294const MAX_DATAGRAM: usize = 65_536;
295
296/// The UDPv4 sockets of one participant.
297#[derive(Debug)]
298pub struct UdpTransport {
299    domain_id: u32,
300    participant_id: u32,
301    ports: PortMapping,
302    multicast_address: Ipv4Addr,
303    unicast_addresses: Vec<Ipv4Addr>,
304    /// Sends unicast; this is the user unicast socket.
305    unicast_sender: Arc<UdpSocket>,
306    /// Sends multicast, one socket per interface.
307    multicast_senders: Vec<UdpSocket>,
308    stop: Arc<AtomicBool>,
309    threads: Vec<JoinHandle<()>>,
310    /// For other transports to deliver to the same [`Incoming`].
311    sink: Sink,
312}
313
314impl UdpTransport {
315    /// Opens the sockets, joins the multicast group and starts receiving.
316    pub fn open(config: &UdpConfig) -> io::Result<(UdpTransport, Incoming)> {
317        Self::open_with(config, None)
318    }
319
320    /// Like [`Self::open`], with user traffic given to `user` on the
321    /// receiving threads (see [`Sink`]).
322    pub fn open_with(
323        config: &UdpConfig,
324        user: Option<UserHandler>,
325    ) -> io::Result<(UdpTransport, Incoming)> {
326        let ports = config.ports;
327        let domain_id = config.domain_id;
328        let port_err = || io::Error::new(io::ErrorKind::InvalidInput, "port number out of range");
329
330        let disc_mc_port = ports
331            .discovery_multicast_port(domain_id)
332            .ok_or_else(port_err)?;
333        let user_mc_port = ports.user_multicast_port(domain_id).ok_or_else(port_err)?;
334        let disc_mc = multicast_socket(config, disc_mc_port)?;
335        let user_mc = if user_mc_port == disc_mc_port {
336            None
337        } else {
338            Some(multicast_socket(config, user_mc_port)?)
339        };
340
341        let (participant_id, disc_uc, user_uc) = bind_unicast(config)?;
342
343        let multicast_senders = if config.interfaces.is_empty() {
344            vec![multicast_sender(config, None)?]
345        } else {
346            config
347                .interfaces
348                .iter()
349                .map(|i| multicast_sender(config, Some(*i)))
350                .collect::<io::Result<_>>()?
351        };
352
353        let unicast_addresses = if config.interfaces.is_empty() {
354            vec![default_address(config.multicast_address)]
355        } else {
356            config.interfaces.clone()
357        };
358
359        let user_uc = Arc::new(user_uc);
360        let stop = Arc::new(AtomicBool::new(false));
361        let (tx, rx) = mpsc::sync_channel(INCOMING_CAPACITY);
362        let queued = Arc::new(AtomicUsize::new(0));
363        let sink = Sink {
364            tx,
365            user,
366            queued: queued.clone(),
367        };
368        let mut threads = Vec::new();
369        let mut spawn = |socket: Arc<UdpSocket>, channel: Channel| -> io::Result<()> {
370            socket.set_read_timeout(Some(POLL))?;
371            let stop = stop.clone();
372            let sink = sink.clone();
373            let handle = std::thread::Builder::new()
374                .name(format!("rtps-udp-{channel:?}"))
375                .spawn(move || receive_loop(&socket, channel, &stop, &sink))?;
376            threads.push(handle);
377            Ok(())
378        };
379        spawn(Arc::new(disc_mc), Channel::DiscoveryMulticast)?;
380        if let Some(s) = user_mc {
381            spawn(Arc::new(s), Channel::UserMulticast)?;
382        }
383        spawn(Arc::new(disc_uc), Channel::DiscoveryUnicast)?;
384        spawn(user_uc.clone(), Channel::UserUnicast)?;
385
386        Ok((
387            UdpTransport {
388                domain_id,
389                participant_id,
390                ports,
391                multicast_address: config.multicast_address,
392                unicast_addresses,
393                unicast_sender: user_uc,
394                multicast_senders,
395                stop,
396                threads,
397                sink,
398            },
399            Incoming { rx, queued },
400        ))
401    }
402
403    /// A sender of datagrams to this transport's [`Incoming`], for
404    /// another transport (shared memory) to deliver there too.
405    pub fn injector(&self) -> Sink {
406        self.sink.clone()
407    }
408
409    /// The domain id.
410    pub fn domain_id(&self) -> u32 {
411        self.domain_id
412    }
413
414    /// The participant id that was chosen.
415    pub fn participant_id(&self) -> u32 {
416        self.participant_id
417    }
418
419    /// Where other participants reach this one's built-in endpoints by
420    /// unicast (`metatrafficUnicastLocatorList`).
421    pub fn discovery_unicast_locators(&self) -> Vec<Locator> {
422        let port = self
423            .ports
424            .discovery_unicast_port(self.domain_id, self.participant_id)
425            .expect("checked when opened");
426        self.unicast_locators(port)
427    }
428
429    /// `metatrafficMulticastLocatorList`: the group on the discovery
430    /// multicast port.
431    pub fn discovery_multicast_locators(&self) -> Vec<Locator> {
432        let port = self
433            .ports
434            .discovery_multicast_port(self.domain_id)
435            .expect("checked when opened");
436        vec![Locator::udpv4(SocketAddrV4::new(
437            self.multicast_address,
438            port,
439        ))]
440    }
441
442    /// `defaultUnicastLocatorList`: where user endpoints are reached by
443    /// unicast.
444    pub fn user_unicast_locators(&self) -> Vec<Locator> {
445        let port = self
446            .ports
447            .user_unicast_port(self.domain_id, self.participant_id)
448            .expect("checked when opened");
449        self.unicast_locators(port)
450    }
451
452    /// `defaultMulticastLocatorList`: the group on the user multicast
453    /// port.
454    pub fn user_multicast_locators(&self) -> Vec<Locator> {
455        let port = self
456            .ports
457            .user_multicast_port(self.domain_id)
458            .expect("checked when opened");
459        vec![Locator::udpv4(SocketAddrV4::new(
460            self.multicast_address,
461            port,
462        ))]
463    }
464
465    fn unicast_locators(&self, port: u16) -> Vec<Locator> {
466        self.unicast_addresses
467            .iter()
468            .map(|a| Locator::udpv4(SocketAddrV4::new(*a, port)))
469            .collect()
470    }
471
472    /// The IPv4 addresses this transport's unicast locators carry.
473    pub fn unicast_addresses(&self) -> &[Ipv4Addr] {
474        &self.unicast_addresses
475    }
476
477    /// Sends one message to a locator. Multicast destinations are sent on
478    /// every configured interface.
479    ///
480    /// Locators that are not UDPv4 are refused with
481    /// [`io::ErrorKind::Unsupported`].
482    pub fn send(&self, data: &[u8], to: &Locator) -> io::Result<()> {
483        let addr = match (to.kind, to.to_socket_addr()) {
484            (Locator::KIND_UDPV4, Some(SocketAddr::V4(a))) => a,
485            _ => {
486                return Err(io::Error::new(
487                    io::ErrorKind::Unsupported,
488                    "only UDPv4 locators are supported",
489                ));
490            }
491        };
492        if addr.ip().is_multicast() {
493            let mut result = Ok(());
494            for s in &self.multicast_senders {
495                if let Err(e) = s.send_to(data, addr) {
496                    result = Err(e);
497                }
498            }
499            result
500        } else {
501            self.unicast_sender.send_to(data, addr).map(|_| ())
502        }
503    }
504}
505
506impl Drop for UdpTransport {
507    fn drop(&mut self) {
508        self.stop.store(true, Ordering::Relaxed);
509        for t in self.threads.drain(..) {
510            let _ = t.join();
511        }
512    }
513}
514
515fn receive_loop(socket: &UdpSocket, channel: Channel, stop: &AtomicBool, sink: &Sink) {
516    let mut buf = vec![0u8; MAX_DATAGRAM];
517    // The size of the datagram known to wait first, when the system
518    // tells it: received straight into a buffer of its size rather than
519    // copied out of `buf` (#112).
520    let mut next = 0;
521    while !stop.load(Ordering::Relaxed) {
522        let got = if next > 0 {
523            receive_sized(socket, next)
524        } else {
525            socket
526                .recv_from(&mut buf)
527                .map(|(n, source)| (buf[..n].to_vec(), source))
528        };
529        match got {
530            Ok((data, source)) => {
531                let large = data.len() >= INLINE_SIZE;
532                let d = Datagram {
533                    channel,
534                    source,
535                    data,
536                };
537                // Alone when no other waits behind it: a burst goes to
538                // the participant's thread while this one receives. A
539                // large datagram (fragments of a large sample) is handled
540                // here even in a burst: its handling is mostly the copy
541                // into the sample, and handing it over costs a thread
542                // wake-up (#112).
543                let waiting = pending(socket);
544                next = if EXACT_PENDING { waiting } else { 0 };
545                if !sink.deliver(d, waiting == 0 || large) {
546                    return;
547                }
548            }
549            Err(e) => {
550                next = 0;
551                match e.kind() {
552                    io::ErrorKind::WouldBlock
553                    | io::ErrorKind::TimedOut
554                    | io::ErrorKind::Interrupted => {}
555                    // On Windows a previous send to a closed port shows up
556                    // here as ConnectionReset; it says nothing about this
557                    // socket.
558                    io::ErrorKind::ConnectionReset => {}
559                    _ => std::thread::sleep(POLL),
560                }
561            }
562        }
563    }
564}
565
566/// Receives a datagram of `size` octets into a buffer of that size.
567fn receive_sized(socket: &UdpSocket, size: usize) -> io::Result<(Vec<u8>, SocketAddr)> {
568    let mut data = Vec::with_capacity(size);
569    let (n, source) = socket2::SockRef::from(socket).recv_from(data.spare_capacity_mut())?;
570    // SAFETY: the system wrote the first `n` octets, `n` <= capacity.
571    unsafe { data.set_len(n) };
572    let source = source
573        .as_socket()
574        .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidData))?;
575    Ok((data, source))
576}
577
578/// The size from which a user datagram is handled on the receive thread
579/// even when others wait behind it.
580const INLINE_SIZE: usize = 8192;
581
582/// Whether [`pending`] tells the size of the first datagram waiting, as
583/// Linux does for a UDP socket, rather than of all of them.
584const EXACT_PENDING: bool = cfg!(target_os = "linux");
585
586/// How many octets wait on `socket`: on Linux the size of the first
587/// datagram. 0 when none waits, or for an empty datagram.
588#[cfg(unix)]
589fn pending(socket: &UdpSocket) -> usize {
590    use std::os::fd::AsRawFd;
591    let mut n: libc::c_int = 0;
592    // SAFETY: FIONREAD writes one c_int, to `n`, for an open socket.
593    let r = unsafe { libc::ioctl(socket.as_raw_fd(), libc::FIONREAD, &mut n) };
594    if r == 0 { n.max(0) as usize } else { 0 }
595}
596
597/// How many octets wait on `socket`: unknown here, so none.
598#[cfg(not(unix))]
599fn pending(_socket: &UdpSocket) -> usize {
600    0
601}
602
603fn new_udp_socket() -> io::Result<Socket> {
604    Socket::new(Domain::IPV4, Type::DGRAM, Some(Protocol::UDP))
605}
606
607/// A socket with the buffers asked for. Failing to get them is not an
608/// error: the socket works with what it has.
609fn new_configured_socket(config: &UdpConfig) -> io::Result<Socket> {
610    let s = new_udp_socket()?;
611    if let Some(size) = config.receive_buffer_size {
612        let _ = s.set_recv_buffer_size(size);
613    }
614    if let Some(size) = config.send_buffer_size {
615        let _ = s.set_send_buffer_size(size);
616    }
617    Ok(s)
618}
619
620/// A socket on a multicast port. All participants of a domain on a host
621/// share the port, so the address is marked reusable.
622fn multicast_socket(config: &UdpConfig, port: u16) -> io::Result<UdpSocket> {
623    let s = new_configured_socket(config)?;
624    s.set_reuse_address(true)?;
625    #[cfg(all(unix, not(any(target_os = "solaris", target_os = "illumos"))))]
626    s.set_reuse_port(true)?;
627    s.bind(&SockAddr::from(SocketAddrV4::new(
628        Ipv4Addr::UNSPECIFIED,
629        port,
630    )))?;
631    if config.interfaces.is_empty() {
632        s.join_multicast_v4(&config.multicast_address, &Ipv4Addr::UNSPECIFIED)?;
633    } else {
634        for i in &config.interfaces {
635            s.join_multicast_v4(&config.multicast_address, i)?;
636        }
637    }
638    Ok(s.into())
639}
640
641fn multicast_sender(config: &UdpConfig, interface: Option<Ipv4Addr>) -> io::Result<UdpSocket> {
642    let s = new_configured_socket(config)?;
643    s.set_multicast_ttl_v4(config.multicast_ttl)?;
644    s.set_multicast_loop_v4(config.multicast_loopback)?;
645    if let Some(i) = interface {
646        s.set_multicast_if_v4(&i)?;
647    }
648    s.bind(&SockAddr::from(SocketAddrV4::new(
649        interface.unwrap_or(Ipv4Addr::UNSPECIFIED),
650        0,
651    )))?;
652    Ok(s.into())
653}
654
655/// A socket on a unicast port, not shared with anyone.
656fn unicast_socket(config: &UdpConfig, port: u16) -> io::Result<UdpSocket> {
657    let s = new_configured_socket(config)?;
658    // On Windows, SO_EXCLUSIVEADDRUSE would be needed to stop others
659    // from taking the port; without SO_REUSEADDR the bind at least fails
660    // when the port is already taken.
661    s.bind(&SockAddr::from(SocketAddrV4::new(
662        Ipv4Addr::UNSPECIFIED,
663        port,
664    )))?;
665    Ok(s.into())
666}
667
668/// Picks the participant id and binds its discovery and user unicast
669/// ports (9.6.2.1).
670fn bind_unicast(config: &UdpConfig) -> io::Result<(u32, UdpSocket, UdpSocket)> {
671    let ports = &config.ports;
672    let range = match config.participant_id {
673        Some(id) => id..=id,
674        None => 0..=config.max_participant_id,
675    };
676    let mut last_err = None;
677    for pid in range {
678        let (Some(disc), Some(user)) = (
679            ports.discovery_unicast_port(config.domain_id, pid),
680            ports.user_unicast_port(config.domain_id, pid),
681        ) else {
682            break;
683        };
684        match (unicast_socket(config, disc), unicast_socket(config, user)) {
685            (Ok(d), Ok(u)) => return Ok((pid, d, u)),
686            (Err(e), _) | (_, Err(e)) => last_err = Some(e),
687        }
688    }
689    Err(last_err
690        .unwrap_or_else(|| io::Error::new(io::ErrorKind::AddrInUse, "no free participant id")))
691}
692
693/// The local address of the route towards `toward`, found by connecting a
694/// UDP socket (no datagram is sent). Falls back to the loopback address.
695fn default_address(toward: Ipv4Addr) -> Ipv4Addr {
696    let found = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).and_then(|s| {
697        s.connect((toward, 7400))?;
698        s.local_addr()
699    });
700    match found {
701        Ok(SocketAddr::V4(a)) if !a.ip().is_unspecified() => *a.ip(),
702        _ => Ipv4Addr::LOCALHOST,
703    }
704}
705
706/// The unicast locators of a remote endpoint to send its messages to, of
707/// all it gives, so that each message reaches it once (rustorb-dds#108:
708/// RustDDS gives 127.0.0.1 besides its interface addresses, and a copy
709/// sent to each wastes the bandwidth and confused its reassembly).
710///
711/// `local` are this participant's own unicast addresses. Locators that
712/// are not UDPv4 are kept as they are. Of the UDPv4 ones:
713///
714/// * when one of them is an address in `local`, the endpoint is on this
715///   host: its first loopback locator, or else that one;
716/// * when this participant is on loopback only, the loopback ones;
717/// * else those that are not loopback (a loopback address of another
718///   host is this host), or all when there are none.
719pub fn select_unicast(remote: &[Locator], local: &[Ipv4Addr]) -> Vec<Locator> {
720    let v4 = |l: &Locator| match (l.kind, l.to_socket_addr()) {
721        (Locator::KIND_UDPV4, Some(SocketAddr::V4(a))) => Some(*a.ip()),
722        _ => None,
723    };
724    let (udp, mut out): (Vec<Locator>, Vec<Locator>) = remote.iter().partition(|l| v4(l).is_some());
725    if udp.len() <= 1 {
726        return remote.to_vec();
727    }
728    let loopback = |l: &&Locator| v4(l).is_some_and(|a| a.is_loopback());
729    let chosen: Vec<Locator> = if let Some(same) = udp
730        .iter()
731        .find(|l| v4(l).is_some_and(|a| !a.is_loopback() && local.contains(&a)))
732    {
733        vec![*udp.iter().find(loopback).unwrap_or(same)]
734    } else if !local.is_empty() && local.iter().all(|a| a.is_loopback()) {
735        let lo: Vec<Locator> = udp.iter().filter(loopback).copied().collect();
736        if lo.is_empty() { udp.clone() } else { lo }
737    } else {
738        let other: Vec<Locator> = udp.iter().filter(|l| !loopback(l)).copied().collect();
739        if other.is_empty() { udp.clone() } else { other }
740    };
741    // In the order they were given.
742    out.extend(chosen);
743    let mut ordered: Vec<Locator> = remote.iter().filter(|l| out.contains(l)).copied().collect();
744    ordered.dedup();
745    ordered
746}
747
748#[cfg(test)]
749mod tests {
750    fn v4(s: &str) -> Locator {
751        Locator::udpv4(s.parse().unwrap())
752    }
753
754    #[test]
755    fn a_peer_on_this_host_is_sent_to_once_on_loopback() {
756        let local = [Ipv4Addr::new(192, 0, 2, 2)];
757        let remote = [v4("192.0.2.2:7411"), v4("127.0.0.1:7411")];
758        assert_eq!(select_unicast(&remote, &local), vec![v4("127.0.0.1:7411")]);
759        // Without a loopback locator: the one of this host's address.
760        let remote = [v4("10.0.0.1:7411"), v4("192.0.2.2:7411")];
761        assert_eq!(select_unicast(&remote, &local), vec![v4("192.0.2.2:7411")]);
762    }
763
764    #[test]
765    fn a_peer_on_another_host_is_not_sent_to_on_loopback() {
766        let local = [Ipv4Addr::new(192, 0, 2, 2)];
767        let remote = [
768            v4("127.0.0.1:7411"),
769            v4("192.0.2.9:7411"),
770            v4("10.0.0.9:7411"),
771        ];
772        assert_eq!(
773            select_unicast(&remote, &local),
774            vec![v4("192.0.2.9:7411"), v4("10.0.0.9:7411")]
775        );
776        let remote = [v4("127.0.0.1:7411"), v4("127.0.0.2:7411")];
777        assert_eq!(select_unicast(&remote, &local), remote.to_vec());
778    }
779
780    #[test]
781    fn a_loopback_only_participant_sends_on_loopback() {
782        let local = [Ipv4Addr::LOCALHOST];
783        let remote = [v4("192.0.2.9:7411"), v4("127.0.0.1:7411")];
784        assert_eq!(select_unicast(&remote, &local), vec![v4("127.0.0.1:7411")]);
785    }
786
787    #[test]
788    fn other_locators_and_a_single_one_are_kept() {
789        let local = [Ipv4Addr::new(192, 0, 2, 2)];
790        let mut shm = v4("0.0.0.0:1");
791        shm.kind = 0x0100_0000;
792        let remote = [v4("192.0.2.9:7411")];
793        assert_eq!(select_unicast(&remote, &local), remote.to_vec());
794        let remote = [shm, v4("192.0.2.2:7411"), v4("127.0.0.1:7411")];
795        assert_eq!(
796            select_unicast(&remote, &local),
797            vec![shm, v4("127.0.0.1:7411")]
798        );
799    }
800
801    use super::*;
802
803    #[test]
804    fn default_ports() {
805        let p = PortMapping::default();
806        assert_eq!(p.discovery_multicast_port(0), Some(7400));
807        assert_eq!(p.discovery_unicast_port(0, 0), Some(7410));
808        assert_eq!(p.user_multicast_port(0), Some(7401));
809        assert_eq!(p.user_unicast_port(0, 0), Some(7411));
810        assert_eq!(p.discovery_unicast_port(0, 1), Some(7412));
811        assert_eq!(p.user_unicast_port(0, 1), Some(7413));
812        assert_eq!(p.discovery_multicast_port(1), Some(7650));
813        assert_eq!(p.user_unicast_port(2, 3), Some(7400 + 500 + 11 + 6));
814        // 7400 + 250 * 233 = 65650 does not fit.
815        assert_eq!(p.discovery_multicast_port(233), None);
816        assert_eq!(p.discovery_multicast_port(232), Some(65400));
817        assert_eq!(p.user_unicast_port(232, 62), Some(65535));
818        assert_eq!(p.user_unicast_port(232, 63), None);
819    }
820}