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, 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
164/// One received datagram: one RTPS message.
165#[derive(Clone, Debug, PartialEq, Eq)]
166pub struct Datagram {
167    /// The socket it arrived on.
168    pub channel: Channel,
169    /// The sender.
170    pub source: SocketAddr,
171    /// The UDP payload.
172    pub data: Vec<u8>,
173}
174
175/// The receiving end of a [`UdpTransport`].
176///
177/// It stops yielding datagrams once the transport is dropped.
178#[derive(Debug)]
179pub struct Incoming {
180    rx: mpsc::Receiver<Datagram>,
181}
182
183impl Incoming {
184    /// Waits for the next datagram. Returns `None` once the transport is
185    /// closed.
186    pub fn recv(&self) -> Option<Datagram> {
187        self.rx.recv().ok()
188    }
189
190    /// Waits at most `timeout` for the next datagram.
191    pub fn recv_timeout(&self, timeout: Duration) -> Option<Datagram> {
192        self.rx.recv_timeout(timeout).ok()
193    }
194
195    /// Returns a datagram if one is waiting.
196    pub fn try_recv(&self) -> Option<Datagram> {
197        self.rx.try_recv().ok()
198    }
199}
200
201/// How often the receive threads look at the stop flag.
202const POLL: Duration = Duration::from_millis(100);
203/// The largest UDP payload.
204const MAX_DATAGRAM: usize = 65_536;
205
206/// The UDPv4 sockets of one participant.
207#[derive(Debug)]
208pub struct UdpTransport {
209    domain_id: u32,
210    participant_id: u32,
211    ports: PortMapping,
212    multicast_address: Ipv4Addr,
213    unicast_addresses: Vec<Ipv4Addr>,
214    /// Sends unicast; this is the user unicast socket.
215    unicast_sender: Arc<UdpSocket>,
216    /// Sends multicast, one socket per interface.
217    multicast_senders: Vec<UdpSocket>,
218    stop: Arc<AtomicBool>,
219    threads: Vec<JoinHandle<()>>,
220    /// For other transports to deliver to the same [`Incoming`].
221    tx: mpsc::Sender<Datagram>,
222}
223
224impl UdpTransport {
225    /// Opens the sockets, joins the multicast group and starts receiving.
226    pub fn open(config: &UdpConfig) -> io::Result<(UdpTransport, Incoming)> {
227        let ports = config.ports;
228        let domain_id = config.domain_id;
229        let port_err = || io::Error::new(io::ErrorKind::InvalidInput, "port number out of range");
230
231        let disc_mc_port = ports
232            .discovery_multicast_port(domain_id)
233            .ok_or_else(port_err)?;
234        let user_mc_port = ports.user_multicast_port(domain_id).ok_or_else(port_err)?;
235        let disc_mc = multicast_socket(config, disc_mc_port)?;
236        let user_mc = if user_mc_port == disc_mc_port {
237            None
238        } else {
239            Some(multicast_socket(config, user_mc_port)?)
240        };
241
242        let (participant_id, disc_uc, user_uc) = bind_unicast(config)?;
243
244        let multicast_senders = if config.interfaces.is_empty() {
245            vec![multicast_sender(config, None)?]
246        } else {
247            config
248                .interfaces
249                .iter()
250                .map(|i| multicast_sender(config, Some(*i)))
251                .collect::<io::Result<_>>()?
252        };
253
254        let unicast_addresses = if config.interfaces.is_empty() {
255            vec![default_address(config.multicast_address)]
256        } else {
257            config.interfaces.clone()
258        };
259
260        let user_uc = Arc::new(user_uc);
261        let stop = Arc::new(AtomicBool::new(false));
262        let (tx, rx) = mpsc::channel();
263        let mut threads = Vec::new();
264        let mut spawn = |socket: Arc<UdpSocket>, channel: Channel| -> io::Result<()> {
265            socket.set_read_timeout(Some(POLL))?;
266            let stop = stop.clone();
267            let tx = tx.clone();
268            let handle = std::thread::Builder::new()
269                .name(format!("rtps-udp-{channel:?}"))
270                .spawn(move || receive_loop(&socket, channel, &stop, &tx))?;
271            threads.push(handle);
272            Ok(())
273        };
274        spawn(Arc::new(disc_mc), Channel::DiscoveryMulticast)?;
275        if let Some(s) = user_mc {
276            spawn(Arc::new(s), Channel::UserMulticast)?;
277        }
278        spawn(Arc::new(disc_uc), Channel::DiscoveryUnicast)?;
279        spawn(user_uc.clone(), Channel::UserUnicast)?;
280
281        Ok((
282            UdpTransport {
283                domain_id,
284                participant_id,
285                ports,
286                multicast_address: config.multicast_address,
287                unicast_addresses,
288                unicast_sender: user_uc,
289                multicast_senders,
290                stop,
291                threads,
292                tx,
293            },
294            Incoming { rx },
295        ))
296    }
297
298    /// A sender of datagrams to this transport's [`Incoming`], for
299    /// another transport (shared memory) to deliver there too.
300    pub fn injector(&self) -> mpsc::Sender<Datagram> {
301        self.tx.clone()
302    }
303
304    /// The domain id.
305    pub fn domain_id(&self) -> u32 {
306        self.domain_id
307    }
308
309    /// The participant id that was chosen.
310    pub fn participant_id(&self) -> u32 {
311        self.participant_id
312    }
313
314    /// Where other participants reach this one's built-in endpoints by
315    /// unicast (`metatrafficUnicastLocatorList`).
316    pub fn discovery_unicast_locators(&self) -> Vec<Locator> {
317        let port = self
318            .ports
319            .discovery_unicast_port(self.domain_id, self.participant_id)
320            .expect("checked when opened");
321        self.unicast_locators(port)
322    }
323
324    /// `metatrafficMulticastLocatorList`: the group on the discovery
325    /// multicast port.
326    pub fn discovery_multicast_locators(&self) -> Vec<Locator> {
327        let port = self
328            .ports
329            .discovery_multicast_port(self.domain_id)
330            .expect("checked when opened");
331        vec![Locator::udpv4(SocketAddrV4::new(
332            self.multicast_address,
333            port,
334        ))]
335    }
336
337    /// `defaultUnicastLocatorList`: where user endpoints are reached by
338    /// unicast.
339    pub fn user_unicast_locators(&self) -> Vec<Locator> {
340        let port = self
341            .ports
342            .user_unicast_port(self.domain_id, self.participant_id)
343            .expect("checked when opened");
344        self.unicast_locators(port)
345    }
346
347    /// `defaultMulticastLocatorList`: the group on the user multicast
348    /// port.
349    pub fn user_multicast_locators(&self) -> Vec<Locator> {
350        let port = self
351            .ports
352            .user_multicast_port(self.domain_id)
353            .expect("checked when opened");
354        vec![Locator::udpv4(SocketAddrV4::new(
355            self.multicast_address,
356            port,
357        ))]
358    }
359
360    fn unicast_locators(&self, port: u16) -> Vec<Locator> {
361        self.unicast_addresses
362            .iter()
363            .map(|a| Locator::udpv4(SocketAddrV4::new(*a, port)))
364            .collect()
365    }
366
367    /// Sends one message to a locator. Multicast destinations are sent on
368    /// every configured interface.
369    ///
370    /// Locators that are not UDPv4 are refused with
371    /// [`io::ErrorKind::Unsupported`].
372    pub fn send(&self, data: &[u8], to: &Locator) -> io::Result<()> {
373        let addr = match (to.kind, to.to_socket_addr()) {
374            (Locator::KIND_UDPV4, Some(SocketAddr::V4(a))) => a,
375            _ => {
376                return Err(io::Error::new(
377                    io::ErrorKind::Unsupported,
378                    "only UDPv4 locators are supported",
379                ));
380            }
381        };
382        if addr.ip().is_multicast() {
383            let mut result = Ok(());
384            for s in &self.multicast_senders {
385                if let Err(e) = s.send_to(data, addr) {
386                    result = Err(e);
387                }
388            }
389            result
390        } else {
391            self.unicast_sender.send_to(data, addr).map(|_| ())
392        }
393    }
394}
395
396impl Drop for UdpTransport {
397    fn drop(&mut self) {
398        self.stop.store(true, Ordering::Relaxed);
399        for t in self.threads.drain(..) {
400            let _ = t.join();
401        }
402    }
403}
404
405fn receive_loop(
406    socket: &UdpSocket,
407    channel: Channel,
408    stop: &AtomicBool,
409    tx: &mpsc::Sender<Datagram>,
410) {
411    let mut buf = vec![0u8; MAX_DATAGRAM];
412    while !stop.load(Ordering::Relaxed) {
413        match socket.recv_from(&mut buf) {
414            Ok((n, source)) => {
415                let d = Datagram {
416                    channel,
417                    source,
418                    data: buf[..n].to_vec(),
419                };
420                if tx.send(d).is_err() {
421                    return;
422                }
423            }
424            Err(e)
425                if matches!(
426                    e.kind(),
427                    io::ErrorKind::WouldBlock
428                        | io::ErrorKind::TimedOut
429                        | io::ErrorKind::Interrupted
430                ) => {}
431            // On Windows a previous send to a closed port shows up here as
432            // ConnectionReset; it says nothing about this socket.
433            Err(e) if e.kind() == io::ErrorKind::ConnectionReset => {}
434            Err(_) => std::thread::sleep(POLL),
435        }
436    }
437}
438
439fn new_udp_socket() -> io::Result<Socket> {
440    Socket::new(Domain::IPV4, Type::DGRAM, Some(Protocol::UDP))
441}
442
443/// A socket with the buffers asked for. Failing to get them is not an
444/// error: the socket works with what it has.
445fn new_configured_socket(config: &UdpConfig) -> io::Result<Socket> {
446    let s = new_udp_socket()?;
447    if let Some(size) = config.receive_buffer_size {
448        let _ = s.set_recv_buffer_size(size);
449    }
450    if let Some(size) = config.send_buffer_size {
451        let _ = s.set_send_buffer_size(size);
452    }
453    Ok(s)
454}
455
456/// A socket on a multicast port. All participants of a domain on a host
457/// share the port, so the address is marked reusable.
458fn multicast_socket(config: &UdpConfig, port: u16) -> io::Result<UdpSocket> {
459    let s = new_configured_socket(config)?;
460    s.set_reuse_address(true)?;
461    #[cfg(all(unix, not(any(target_os = "solaris", target_os = "illumos"))))]
462    s.set_reuse_port(true)?;
463    s.bind(&SockAddr::from(SocketAddrV4::new(
464        Ipv4Addr::UNSPECIFIED,
465        port,
466    )))?;
467    if config.interfaces.is_empty() {
468        s.join_multicast_v4(&config.multicast_address, &Ipv4Addr::UNSPECIFIED)?;
469    } else {
470        for i in &config.interfaces {
471            s.join_multicast_v4(&config.multicast_address, i)?;
472        }
473    }
474    Ok(s.into())
475}
476
477fn multicast_sender(config: &UdpConfig, interface: Option<Ipv4Addr>) -> io::Result<UdpSocket> {
478    let s = new_configured_socket(config)?;
479    s.set_multicast_ttl_v4(config.multicast_ttl)?;
480    s.set_multicast_loop_v4(config.multicast_loopback)?;
481    if let Some(i) = interface {
482        s.set_multicast_if_v4(&i)?;
483    }
484    s.bind(&SockAddr::from(SocketAddrV4::new(
485        interface.unwrap_or(Ipv4Addr::UNSPECIFIED),
486        0,
487    )))?;
488    Ok(s.into())
489}
490
491/// A socket on a unicast port, not shared with anyone.
492fn unicast_socket(config: &UdpConfig, port: u16) -> io::Result<UdpSocket> {
493    let s = new_configured_socket(config)?;
494    // On Windows, SO_EXCLUSIVEADDRUSE would be needed to stop others
495    // from taking the port; without SO_REUSEADDR the bind at least fails
496    // when the port is already taken.
497    s.bind(&SockAddr::from(SocketAddrV4::new(
498        Ipv4Addr::UNSPECIFIED,
499        port,
500    )))?;
501    Ok(s.into())
502}
503
504/// Picks the participant id and binds its discovery and user unicast
505/// ports (9.6.2.1).
506fn bind_unicast(config: &UdpConfig) -> io::Result<(u32, UdpSocket, UdpSocket)> {
507    let ports = &config.ports;
508    let range = match config.participant_id {
509        Some(id) => id..=id,
510        None => 0..=config.max_participant_id,
511    };
512    let mut last_err = None;
513    for pid in range {
514        let (Some(disc), Some(user)) = (
515            ports.discovery_unicast_port(config.domain_id, pid),
516            ports.user_unicast_port(config.domain_id, pid),
517        ) else {
518            break;
519        };
520        match (unicast_socket(config, disc), unicast_socket(config, user)) {
521            (Ok(d), Ok(u)) => return Ok((pid, d, u)),
522            (Err(e), _) | (_, Err(e)) => last_err = Some(e),
523        }
524    }
525    Err(last_err
526        .unwrap_or_else(|| io::Error::new(io::ErrorKind::AddrInUse, "no free participant id")))
527}
528
529/// The local address of the route towards `toward`, found by connecting a
530/// UDP socket (no datagram is sent). Falls back to the loopback address.
531fn default_address(toward: Ipv4Addr) -> Ipv4Addr {
532    let found = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).and_then(|s| {
533        s.connect((toward, 7400))?;
534        s.local_addr()
535    });
536    match found {
537        Ok(SocketAddr::V4(a)) if !a.ip().is_unspecified() => *a.ip(),
538        _ => Ipv4Addr::LOCALHOST,
539    }
540}
541
542#[cfg(test)]
543mod tests {
544    use super::*;
545
546    #[test]
547    fn default_ports() {
548        let p = PortMapping::default();
549        assert_eq!(p.discovery_multicast_port(0), Some(7400));
550        assert_eq!(p.discovery_unicast_port(0, 0), Some(7410));
551        assert_eq!(p.user_multicast_port(0), Some(7401));
552        assert_eq!(p.user_unicast_port(0, 0), Some(7411));
553        assert_eq!(p.discovery_unicast_port(0, 1), Some(7412));
554        assert_eq!(p.user_unicast_port(0, 1), Some(7413));
555        assert_eq!(p.discovery_multicast_port(1), Some(7650));
556        assert_eq!(p.user_unicast_port(2, 3), Some(7400 + 500 + 11 + 6));
557        // 7400 + 250 * 233 = 65650 does not fit.
558        assert_eq!(p.discovery_multicast_port(233), None);
559        assert_eq!(p.discovery_multicast_port(232), Some(65400));
560        assert_eq!(p.user_unicast_port(232, 62), Some(65535));
561        assert_eq!(p.user_unicast_port(232, 63), None);
562    }
563}