rustorb-rtps 0.4.0

DDSI-RTPS wire protocol (messages, discovery, writers and readers) for rustorb-dds
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
//! The UDPv4 transport and the default port numbers
//! (DDSI-RTPS 2.5, 8.5.3.4, 9.5 and 9.6.2).
//!
//! One RTPS message is the payload of one UDP datagram (9.5). A
//! [`UdpTransport`] opens the four sockets a participant needs (discovery
//! and user traffic, each unicast and multicast), receives on them with
//! one thread per socket, and hands the datagrams over a channel. It does
//! not depend on an async runtime.

use std::io;
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::mpsc;
use std::thread::JoinHandle;
use std::time::Duration;

use socket2::{Domain, Protocol, SockAddr, Socket, Type};

use crate::types::Locator;

/// The tunable parameters of the port number expressions
/// (9.6.2.3). [`Default`] gives the values required for out-of-the-box
/// interoperability.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PortMapping {
    /// PB, the port base number.
    pub port_base: u32,
    /// DG, the domain id gain.
    pub domain_id_gain: u32,
    /// PG, the participant id gain.
    pub participant_id_gain: u32,
    /// d0, offset of the discovery multicast port.
    pub d0: u32,
    /// d1, offset of the discovery unicast port.
    pub d1: u32,
    /// d2, offset of the user multicast port.
    pub d2: u32,
    /// d3, offset of the user unicast port.
    pub d3: u32,
}

impl Default for PortMapping {
    fn default() -> Self {
        PortMapping {
            port_base: 7400,
            domain_id_gain: 250,
            participant_id_gain: 2,
            d0: 0,
            d1: 10,
            d2: 1,
            d3: 11,
        }
    }
}

impl PortMapping {
    fn port(&self, domain_id: u32, offset: u32, participant_id: Option<u32>) -> Option<u16> {
        let mut p = u64::from(self.port_base)
            + u64::from(self.domain_id_gain) * u64::from(domain_id)
            + u64::from(offset);
        if let Some(pid) = participant_id {
            p += u64::from(self.participant_id_gain) * u64::from(pid);
        }
        u16::try_from(p).ok()
    }

    /// `SPDP_WELL_KNOWN_MULTICAST_PORT` = PB + DG * domainId + d0
    /// (Table 9.15). `None` if it does not fit in 16 bits.
    pub fn discovery_multicast_port(&self, domain_id: u32) -> Option<u16> {
        self.port(domain_id, self.d0, None)
    }

    /// `SPDP_WELL_KNOWN_UNICAST_PORT` = PB + DG * domainId + d1 + PG *
    /// participantId (Table 9.15).
    pub fn discovery_unicast_port(&self, domain_id: u32, participant_id: u32) -> Option<u16> {
        self.port(domain_id, self.d1, Some(participant_id))
    }

    /// The default user multicast port, PB + DG * domainId + d2
    /// (Table 9.16).
    pub fn user_multicast_port(&self, domain_id: u32) -> Option<u16> {
        self.port(domain_id, self.d2, None)
    }

    /// The default user unicast port, PB + DG * domainId + d3 + PG *
    /// participantId (Table 9.16).
    pub fn user_unicast_port(&self, domain_id: u32, participant_id: u32) -> Option<u16> {
        self.port(domain_id, self.d3, Some(participant_id))
    }
}

/// The multicast address every participant announces on and listens to
/// (9.6.2.4.1).
pub const DEFAULT_MULTICAST_ADDRESS: Ipv4Addr = Ipv4Addr::new(239, 255, 0, 1);

/// Settings of a [`UdpTransport`].
#[derive(Clone, Debug)]
pub struct UdpConfig {
    /// The DDS domain id.
    pub domain_id: u32,
    /// The participant id. `None` picks the lowest id, starting at 0,
    /// whose unicast ports are free (9.6.2.1).
    pub participant_id: Option<u32>,
    /// The highest participant id tried when `participant_id` is `None`.
    pub max_participant_id: u32,
    /// The port number parameters.
    pub ports: PortMapping,
    /// The interfaces to use, by their IPv4 address. Empty means the
    /// system's choice: multicast is joined on the default interface and
    /// the unicast locators use the address of the default route.
    pub interfaces: Vec<Ipv4Addr>,
    /// The multicast group.
    pub multicast_address: Ipv4Addr,
    /// The time-to-live of multicast datagrams sent.
    pub multicast_ttl: u32,
    /// Whether multicast datagrams sent are also delivered to this host,
    /// so that participants on the same host find each other.
    pub multicast_loopback: bool,
    /// The receive buffer to ask for on each socket that receives
    /// (`SO_RCVBUF`; the system may give less). A large sample comes as
    /// a burst of datagrams, which a small buffer drops. `None` keeps
    /// the system's default.
    pub receive_buffer_size: Option<usize>,
    /// The send buffer to ask for on each socket (`SO_SNDBUF`). On macOS
    /// it also bounds the largest datagram a socket can send, 9216
    /// octets by default, so it must be at least the largest message
    /// sent (up to 64 KiB, see `rustorb_rtps::frag`). `None` keeps the
    /// system's default.
    pub send_buffer_size: Option<usize>,
}

impl UdpConfig {
    /// The default settings for a domain.
    pub fn new(domain_id: u32) -> Self {
        UdpConfig {
            domain_id,
            participant_id: None,
            max_participant_id: 119,
            ports: PortMapping::default(),
            interfaces: Vec::new(),
            multicast_address: DEFAULT_MULTICAST_ADDRESS,
            multicast_ttl: 1,
            multicast_loopback: true,
            receive_buffer_size: Some(4 * 1024 * 1024),
            send_buffer_size: Some(1024 * 1024),
        }
    }
}

/// Which socket a datagram came in on.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Channel {
    /// Discovery traffic, multicast port (d0).
    DiscoveryMulticast,
    /// Discovery traffic, unicast port (d1).
    DiscoveryUnicast,
    /// User traffic, multicast port (d2).
    UserMulticast,
    /// User traffic, unicast port (d3).
    UserUnicast,
}

impl Channel {
    /// Whether it is a channel of user traffic.
    pub fn is_user(self) -> bool {
        matches!(self, Channel::UserMulticast | Channel::UserUnicast)
    }
}

/// One received datagram: one RTPS message.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Datagram {
    /// The socket it arrived on.
    pub channel: Channel,
    /// The sender.
    pub source: SocketAddr,
    /// The UDP payload.
    pub data: Vec<u8>,
}

/// The receiving end of a [`UdpTransport`].
///
/// It stops yielding datagrams once the transport is dropped.
#[derive(Debug)]
pub struct Incoming {
    rx: mpsc::Receiver<Datagram>,
    queued: Arc<AtomicUsize>,
}

impl Incoming {
    /// Waits for the next datagram. Returns `None` once the transport is
    /// closed.
    pub fn recv(&self) -> Option<Datagram> {
        self.rx.recv().ok()
    }

    /// Waits at most `timeout` for the next datagram.
    pub fn recv_timeout(&self, timeout: Duration) -> Option<Datagram> {
        self.rx.recv_timeout(timeout).ok()
    }

    /// Returns a datagram if one is waiting.
    pub fn try_recv(&self) -> Option<Datagram> {
        self.rx.try_recv().ok()
    }

    /// Says that `user` datagrams of user traffic taken from here have
    /// been handled. With a [`UserHandler`], user traffic goes to it only
    /// while none taken from here is still being handled, so that it is
    /// handled in the order it came.
    pub fn handled(&self, user: usize) {
        if user > 0 {
            self.queued.fetch_sub(user, Ordering::AcqRel);
        }
    }
}

/// The most datagrams received and not yet taken from [`Incoming`].
/// When it is full, the receive threads wait, the sockets' buffers fill
/// and the kernel drops what does not fit, as when a receiver is slower
/// than its senders: best-effort loses it, reliable repairs it. Without
/// a bound, a fast sender made the receiver's memory grow without end
/// (rustorb-dds#110). 1024 datagrams are at most 64 MiB.
pub const INCOMING_CAPACITY: usize = 1024;

/// Handles a datagram of user traffic on the thread that received it,
/// or gives it back to be queued on [`Incoming`] like the others.
pub type UserHandler = Arc<dyn Fn(Datagram) -> Option<Datagram> + Send + Sync>;

/// Where the receive threads put what they receive: on the queue of
/// [`Incoming`], or, for user traffic and with a [`UserHandler`], to
/// that handler on the receiving thread, which saves a hand-over
/// between threads for each message (rustorb-dds#111).
#[derive(Clone)]
pub struct Sink {
    tx: mpsc::SyncSender<Datagram>,
    user: Option<UserHandler>,
    /// The user datagrams queued and not yet [`Incoming::handled`].
    queued: Arc<AtomicUsize>,
}

impl std::fmt::Debug for Sink {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Sink")
            .field("user_handler", &self.user.is_some())
            .finish_non_exhaustive()
    }
}

impl From<mpsc::SyncSender<Datagram>> for Sink {
    fn from(tx: mpsc::SyncSender<Datagram>) -> Self {
        Sink {
            tx,
            user: None,
            queued: Arc::new(AtomicUsize::new(0)),
        }
    }
}

impl Sink {
    /// Puts a datagram where it goes. `alone` says that no other has
    /// come with it: user traffic goes to the handler only then (a
    /// burst is queued, for the participant's thread to handle while
    /// this one receives), and only while no user datagram queued
    /// earlier is still to be handled. Returns `false` once the
    /// receiving side is gone.
    pub fn deliver(&self, d: Datagram, alone: bool) -> bool {
        let user = d.channel.is_user();
        let d = match &self.user {
            Some(h) if user && alone && self.queued.load(Ordering::Acquire) == 0 => match h(d) {
                Some(d) => d,
                None => return true,
            },
            _ => d,
        };
        if user {
            self.queued.fetch_add(1, Ordering::AcqRel);
        }
        if self.tx.send(d).is_ok() {
            true
        } else {
            if user {
                self.queued.fetch_sub(1, Ordering::AcqRel);
            }
            false
        }
    }
}

/// How often the receive threads look at the stop flag.
const POLL: Duration = Duration::from_millis(100);
/// The largest UDP payload.
const MAX_DATAGRAM: usize = 65_536;

/// The UDPv4 sockets of one participant.
#[derive(Debug)]
pub struct UdpTransport {
    domain_id: u32,
    participant_id: u32,
    ports: PortMapping,
    multicast_address: Ipv4Addr,
    unicast_addresses: Vec<Ipv4Addr>,
    /// Sends unicast; this is the user unicast socket.
    unicast_sender: Arc<UdpSocket>,
    /// Sends multicast, one socket per interface.
    multicast_senders: Vec<UdpSocket>,
    stop: Arc<AtomicBool>,
    threads: Vec<JoinHandle<()>>,
    /// For other transports to deliver to the same [`Incoming`].
    sink: Sink,
}

impl UdpTransport {
    /// Opens the sockets, joins the multicast group and starts receiving.
    pub fn open(config: &UdpConfig) -> io::Result<(UdpTransport, Incoming)> {
        Self::open_with(config, None)
    }

    /// Like [`Self::open`], with user traffic given to `user` on the
    /// receiving threads (see [`Sink`]).
    pub fn open_with(
        config: &UdpConfig,
        user: Option<UserHandler>,
    ) -> io::Result<(UdpTransport, Incoming)> {
        let ports = config.ports;
        let domain_id = config.domain_id;
        let port_err = || io::Error::new(io::ErrorKind::InvalidInput, "port number out of range");

        let disc_mc_port = ports
            .discovery_multicast_port(domain_id)
            .ok_or_else(port_err)?;
        let user_mc_port = ports.user_multicast_port(domain_id).ok_or_else(port_err)?;
        let disc_mc = multicast_socket(config, disc_mc_port)?;
        let user_mc = if user_mc_port == disc_mc_port {
            None
        } else {
            Some(multicast_socket(config, user_mc_port)?)
        };

        let (participant_id, disc_uc, user_uc) = bind_unicast(config)?;

        let multicast_senders = if config.interfaces.is_empty() {
            vec![multicast_sender(config, None)?]
        } else {
            config
                .interfaces
                .iter()
                .map(|i| multicast_sender(config, Some(*i)))
                .collect::<io::Result<_>>()?
        };

        let unicast_addresses = if config.interfaces.is_empty() {
            vec![default_address(config.multicast_address)]
        } else {
            config.interfaces.clone()
        };

        let user_uc = Arc::new(user_uc);
        let stop = Arc::new(AtomicBool::new(false));
        let (tx, rx) = mpsc::sync_channel(INCOMING_CAPACITY);
        let queued = Arc::new(AtomicUsize::new(0));
        let sink = Sink {
            tx,
            user,
            queued: queued.clone(),
        };
        let mut threads = Vec::new();
        let mut spawn = |socket: Arc<UdpSocket>, channel: Channel| -> io::Result<()> {
            socket.set_read_timeout(Some(POLL))?;
            let stop = stop.clone();
            let sink = sink.clone();
            let handle = std::thread::Builder::new()
                .name(format!("rtps-udp-{channel:?}"))
                .spawn(move || receive_loop(&socket, channel, &stop, &sink))?;
            threads.push(handle);
            Ok(())
        };
        spawn(Arc::new(disc_mc), Channel::DiscoveryMulticast)?;
        if let Some(s) = user_mc {
            spawn(Arc::new(s), Channel::UserMulticast)?;
        }
        spawn(Arc::new(disc_uc), Channel::DiscoveryUnicast)?;
        spawn(user_uc.clone(), Channel::UserUnicast)?;

        Ok((
            UdpTransport {
                domain_id,
                participant_id,
                ports,
                multicast_address: config.multicast_address,
                unicast_addresses,
                unicast_sender: user_uc,
                multicast_senders,
                stop,
                threads,
                sink,
            },
            Incoming { rx, queued },
        ))
    }

    /// A sender of datagrams to this transport's [`Incoming`], for
    /// another transport (shared memory) to deliver there too.
    pub fn injector(&self) -> Sink {
        self.sink.clone()
    }

    /// The domain id.
    pub fn domain_id(&self) -> u32 {
        self.domain_id
    }

    /// The participant id that was chosen.
    pub fn participant_id(&self) -> u32 {
        self.participant_id
    }

    /// Where other participants reach this one's built-in endpoints by
    /// unicast (`metatrafficUnicastLocatorList`).
    pub fn discovery_unicast_locators(&self) -> Vec<Locator> {
        let port = self
            .ports
            .discovery_unicast_port(self.domain_id, self.participant_id)
            .expect("checked when opened");
        self.unicast_locators(port)
    }

    /// `metatrafficMulticastLocatorList`: the group on the discovery
    /// multicast port.
    pub fn discovery_multicast_locators(&self) -> Vec<Locator> {
        let port = self
            .ports
            .discovery_multicast_port(self.domain_id)
            .expect("checked when opened");
        vec![Locator::udpv4(SocketAddrV4::new(
            self.multicast_address,
            port,
        ))]
    }

    /// `defaultUnicastLocatorList`: where user endpoints are reached by
    /// unicast.
    pub fn user_unicast_locators(&self) -> Vec<Locator> {
        let port = self
            .ports
            .user_unicast_port(self.domain_id, self.participant_id)
            .expect("checked when opened");
        self.unicast_locators(port)
    }

    /// `defaultMulticastLocatorList`: the group on the user multicast
    /// port.
    pub fn user_multicast_locators(&self) -> Vec<Locator> {
        let port = self
            .ports
            .user_multicast_port(self.domain_id)
            .expect("checked when opened");
        vec![Locator::udpv4(SocketAddrV4::new(
            self.multicast_address,
            port,
        ))]
    }

    fn unicast_locators(&self, port: u16) -> Vec<Locator> {
        self.unicast_addresses
            .iter()
            .map(|a| Locator::udpv4(SocketAddrV4::new(*a, port)))
            .collect()
    }

    /// The IPv4 addresses this transport's unicast locators carry.
    pub fn unicast_addresses(&self) -> &[Ipv4Addr] {
        &self.unicast_addresses
    }

    /// Sends one message to a locator. Multicast destinations are sent on
    /// every configured interface.
    ///
    /// Locators that are not UDPv4 are refused with
    /// [`io::ErrorKind::Unsupported`].
    pub fn send(&self, data: &[u8], to: &Locator) -> io::Result<()> {
        let addr = match (to.kind, to.to_socket_addr()) {
            (Locator::KIND_UDPV4, Some(SocketAddr::V4(a))) => a,
            _ => {
                return Err(io::Error::new(
                    io::ErrorKind::Unsupported,
                    "only UDPv4 locators are supported",
                ));
            }
        };
        if addr.ip().is_multicast() {
            let mut result = Ok(());
            for s in &self.multicast_senders {
                if let Err(e) = s.send_to(data, addr) {
                    result = Err(e);
                }
            }
            result
        } else {
            self.unicast_sender.send_to(data, addr).map(|_| ())
        }
    }
}

impl Drop for UdpTransport {
    fn drop(&mut self) {
        self.stop.store(true, Ordering::Relaxed);
        for t in self.threads.drain(..) {
            let _ = t.join();
        }
    }
}

fn receive_loop(socket: &UdpSocket, channel: Channel, stop: &AtomicBool, sink: &Sink) {
    let mut buf = vec![0u8; MAX_DATAGRAM];
    // The size of the datagram known to wait first, when the system
    // tells it: received straight into a buffer of its size rather than
    // copied out of `buf` (#112).
    let mut next = 0;
    while !stop.load(Ordering::Relaxed) {
        let got = if next > 0 {
            receive_sized(socket, next)
        } else {
            socket
                .recv_from(&mut buf)
                .map(|(n, source)| (buf[..n].to_vec(), source))
        };
        match got {
            Ok((data, source)) => {
                let large = data.len() >= INLINE_SIZE;
                let d = Datagram {
                    channel,
                    source,
                    data,
                };
                // Alone when no other waits behind it: a burst goes to
                // the participant's thread while this one receives. A
                // large datagram (fragments of a large sample) is handled
                // here even in a burst: its handling is mostly the copy
                // into the sample, and handing it over costs a thread
                // wake-up (#112).
                let waiting = pending(socket);
                next = if EXACT_PENDING { waiting } else { 0 };
                if !sink.deliver(d, waiting == 0 || large) {
                    return;
                }
            }
            Err(e) => {
                next = 0;
                match e.kind() {
                    io::ErrorKind::WouldBlock
                    | io::ErrorKind::TimedOut
                    | io::ErrorKind::Interrupted => {}
                    // On Windows a previous send to a closed port shows up
                    // here as ConnectionReset; it says nothing about this
                    // socket.
                    io::ErrorKind::ConnectionReset => {}
                    _ => std::thread::sleep(POLL),
                }
            }
        }
    }
}

/// Receives a datagram of `size` octets into a buffer of that size.
fn receive_sized(socket: &UdpSocket, size: usize) -> io::Result<(Vec<u8>, SocketAddr)> {
    let mut data = Vec::with_capacity(size);
    let (n, source) = socket2::SockRef::from(socket).recv_from(data.spare_capacity_mut())?;
    // SAFETY: the system wrote the first `n` octets, `n` <= capacity.
    unsafe { data.set_len(n) };
    let source = source
        .as_socket()
        .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidData))?;
    Ok((data, source))
}

/// The size from which a user datagram is handled on the receive thread
/// even when others wait behind it.
const INLINE_SIZE: usize = 8192;

/// Whether [`pending`] tells the size of the first datagram waiting, as
/// Linux does for a UDP socket, rather than of all of them.
const EXACT_PENDING: bool = cfg!(target_os = "linux");

/// How many octets wait on `socket`: on Linux the size of the first
/// datagram. 0 when none waits, or for an empty datagram.
#[cfg(unix)]
fn pending(socket: &UdpSocket) -> usize {
    use std::os::fd::AsRawFd;
    let mut n: libc::c_int = 0;
    // SAFETY: FIONREAD writes one c_int, to `n`, for an open socket.
    let r = unsafe { libc::ioctl(socket.as_raw_fd(), libc::FIONREAD, &mut n) };
    if r == 0 { n.max(0) as usize } else { 0 }
}

/// How many octets wait on `socket`: unknown here, so none.
#[cfg(not(unix))]
fn pending(_socket: &UdpSocket) -> usize {
    0
}

fn new_udp_socket() -> io::Result<Socket> {
    Socket::new(Domain::IPV4, Type::DGRAM, Some(Protocol::UDP))
}

/// A socket with the buffers asked for. Failing to get them is not an
/// error: the socket works with what it has.
fn new_configured_socket(config: &UdpConfig) -> io::Result<Socket> {
    let s = new_udp_socket()?;
    if let Some(size) = config.receive_buffer_size {
        let _ = s.set_recv_buffer_size(size);
    }
    if let Some(size) = config.send_buffer_size {
        let _ = s.set_send_buffer_size(size);
    }
    Ok(s)
}

/// A socket on a multicast port. All participants of a domain on a host
/// share the port, so the address is marked reusable.
fn multicast_socket(config: &UdpConfig, port: u16) -> io::Result<UdpSocket> {
    let s = new_configured_socket(config)?;
    s.set_reuse_address(true)?;
    #[cfg(all(unix, not(any(target_os = "solaris", target_os = "illumos"))))]
    s.set_reuse_port(true)?;
    s.bind(&SockAddr::from(SocketAddrV4::new(
        Ipv4Addr::UNSPECIFIED,
        port,
    )))?;
    if config.interfaces.is_empty() {
        s.join_multicast_v4(&config.multicast_address, &Ipv4Addr::UNSPECIFIED)?;
    } else {
        for i in &config.interfaces {
            s.join_multicast_v4(&config.multicast_address, i)?;
        }
    }
    Ok(s.into())
}

fn multicast_sender(config: &UdpConfig, interface: Option<Ipv4Addr>) -> io::Result<UdpSocket> {
    let s = new_configured_socket(config)?;
    s.set_multicast_ttl_v4(config.multicast_ttl)?;
    s.set_multicast_loop_v4(config.multicast_loopback)?;
    if let Some(i) = interface {
        s.set_multicast_if_v4(&i)?;
    }
    s.bind(&SockAddr::from(SocketAddrV4::new(
        interface.unwrap_or(Ipv4Addr::UNSPECIFIED),
        0,
    )))?;
    Ok(s.into())
}

/// A socket on a unicast port, not shared with anyone.
fn unicast_socket(config: &UdpConfig, port: u16) -> io::Result<UdpSocket> {
    let s = new_configured_socket(config)?;
    // On Windows, SO_EXCLUSIVEADDRUSE would be needed to stop others
    // from taking the port; without SO_REUSEADDR the bind at least fails
    // when the port is already taken.
    s.bind(&SockAddr::from(SocketAddrV4::new(
        Ipv4Addr::UNSPECIFIED,
        port,
    )))?;
    Ok(s.into())
}

/// Picks the participant id and binds its discovery and user unicast
/// ports (9.6.2.1).
fn bind_unicast(config: &UdpConfig) -> io::Result<(u32, UdpSocket, UdpSocket)> {
    let ports = &config.ports;
    let range = match config.participant_id {
        Some(id) => id..=id,
        None => 0..=config.max_participant_id,
    };
    let mut last_err = None;
    for pid in range {
        let (Some(disc), Some(user)) = (
            ports.discovery_unicast_port(config.domain_id, pid),
            ports.user_unicast_port(config.domain_id, pid),
        ) else {
            break;
        };
        match (unicast_socket(config, disc), unicast_socket(config, user)) {
            (Ok(d), Ok(u)) => return Ok((pid, d, u)),
            (Err(e), _) | (_, Err(e)) => last_err = Some(e),
        }
    }
    Err(last_err
        .unwrap_or_else(|| io::Error::new(io::ErrorKind::AddrInUse, "no free participant id")))
}

/// The local address of the route towards `toward`, found by connecting a
/// UDP socket (no datagram is sent). Falls back to the loopback address.
fn default_address(toward: Ipv4Addr) -> Ipv4Addr {
    let found = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).and_then(|s| {
        s.connect((toward, 7400))?;
        s.local_addr()
    });
    match found {
        Ok(SocketAddr::V4(a)) if !a.ip().is_unspecified() => *a.ip(),
        _ => Ipv4Addr::LOCALHOST,
    }
}

/// The unicast locators of a remote endpoint to send its messages to, of
/// all it gives, so that each message reaches it once (rustorb-dds#108:
/// RustDDS gives 127.0.0.1 besides its interface addresses, and a copy
/// sent to each wastes the bandwidth and confused its reassembly).
///
/// `local` are this participant's own unicast addresses. Locators that
/// are not UDPv4 are kept as they are. Of the UDPv4 ones:
///
/// * when one of them is an address in `local`, the endpoint is on this
///   host: its first loopback locator, or else that one;
/// * when this participant is on loopback only, the loopback ones;
/// * else those that are not loopback (a loopback address of another
///   host is this host), or all when there are none.
pub fn select_unicast(remote: &[Locator], local: &[Ipv4Addr]) -> Vec<Locator> {
    let v4 = |l: &Locator| match (l.kind, l.to_socket_addr()) {
        (Locator::KIND_UDPV4, Some(SocketAddr::V4(a))) => Some(*a.ip()),
        _ => None,
    };
    let (udp, mut out): (Vec<Locator>, Vec<Locator>) = remote.iter().partition(|l| v4(l).is_some());
    if udp.len() <= 1 {
        return remote.to_vec();
    }
    let loopback = |l: &&Locator| v4(l).is_some_and(|a| a.is_loopback());
    let chosen: Vec<Locator> = if let Some(same) = udp
        .iter()
        .find(|l| v4(l).is_some_and(|a| !a.is_loopback() && local.contains(&a)))
    {
        vec![*udp.iter().find(loopback).unwrap_or(same)]
    } else if !local.is_empty() && local.iter().all(|a| a.is_loopback()) {
        let lo: Vec<Locator> = udp.iter().filter(loopback).copied().collect();
        if lo.is_empty() { udp.clone() } else { lo }
    } else {
        let other: Vec<Locator> = udp.iter().filter(|l| !loopback(l)).copied().collect();
        if other.is_empty() { udp.clone() } else { other }
    };
    // In the order they were given.
    out.extend(chosen);
    let mut ordered: Vec<Locator> = remote.iter().filter(|l| out.contains(l)).copied().collect();
    ordered.dedup();
    ordered
}

#[cfg(test)]
mod tests {
    fn v4(s: &str) -> Locator {
        Locator::udpv4(s.parse().unwrap())
    }

    #[test]
    fn a_peer_on_this_host_is_sent_to_once_on_loopback() {
        let local = [Ipv4Addr::new(192, 0, 2, 2)];
        let remote = [v4("192.0.2.2:7411"), v4("127.0.0.1:7411")];
        assert_eq!(select_unicast(&remote, &local), vec![v4("127.0.0.1:7411")]);
        // Without a loopback locator: the one of this host's address.
        let remote = [v4("10.0.0.1:7411"), v4("192.0.2.2:7411")];
        assert_eq!(select_unicast(&remote, &local), vec![v4("192.0.2.2:7411")]);
    }

    #[test]
    fn a_peer_on_another_host_is_not_sent_to_on_loopback() {
        let local = [Ipv4Addr::new(192, 0, 2, 2)];
        let remote = [
            v4("127.0.0.1:7411"),
            v4("192.0.2.9:7411"),
            v4("10.0.0.9:7411"),
        ];
        assert_eq!(
            select_unicast(&remote, &local),
            vec![v4("192.0.2.9:7411"), v4("10.0.0.9:7411")]
        );
        let remote = [v4("127.0.0.1:7411"), v4("127.0.0.2:7411")];
        assert_eq!(select_unicast(&remote, &local), remote.to_vec());
    }

    #[test]
    fn a_loopback_only_participant_sends_on_loopback() {
        let local = [Ipv4Addr::LOCALHOST];
        let remote = [v4("192.0.2.9:7411"), v4("127.0.0.1:7411")];
        assert_eq!(select_unicast(&remote, &local), vec![v4("127.0.0.1:7411")]);
    }

    #[test]
    fn other_locators_and_a_single_one_are_kept() {
        let local = [Ipv4Addr::new(192, 0, 2, 2)];
        let mut shm = v4("0.0.0.0:1");
        shm.kind = 0x0100_0000;
        let remote = [v4("192.0.2.9:7411")];
        assert_eq!(select_unicast(&remote, &local), remote.to_vec());
        let remote = [shm, v4("192.0.2.2:7411"), v4("127.0.0.1:7411")];
        assert_eq!(
            select_unicast(&remote, &local),
            vec![shm, v4("127.0.0.1:7411")]
        );
    }

    use super::*;

    #[test]
    fn default_ports() {
        let p = PortMapping::default();
        assert_eq!(p.discovery_multicast_port(0), Some(7400));
        assert_eq!(p.discovery_unicast_port(0, 0), Some(7410));
        assert_eq!(p.user_multicast_port(0), Some(7401));
        assert_eq!(p.user_unicast_port(0, 0), Some(7411));
        assert_eq!(p.discovery_unicast_port(0, 1), Some(7412));
        assert_eq!(p.user_unicast_port(0, 1), Some(7413));
        assert_eq!(p.discovery_multicast_port(1), Some(7650));
        assert_eq!(p.user_unicast_port(2, 3), Some(7400 + 500 + 11 + 6));
        // 7400 + 250 * 233 = 65650 does not fit.
        assert_eq!(p.discovery_multicast_port(233), None);
        assert_eq!(p.discovery_multicast_port(232), Some(65400));
        assert_eq!(p.user_unicast_port(232, 62), Some(65535));
        assert_eq!(p.user_unicast_port(232, 63), None);
    }
}