Skip to main content

rustorb_rtps/
spdp_secure.rs

1//! The DCPSParticipantsSecure builtin topic (DDS Security 1.2, 7.5.1.6).
2//!
3//! A participant with protected discovery announces itself on SPDP as
4//! usual, to bootstrap authentication, and once a remote participant is
5//! authenticated also sends it its `ParticipantBuiltinTopicDataSecure`
6//! through the SPDPbuiltinParticipantsSecureWriter: the SPDP data, with
7//! an optional `identity_status_token`. Changes to the data and the
8//! deletion of the participant go there too. The endpoints have the QoS
9//! of the secure SEDP endpoints: RELIABLE and TRANSIENT_LOCAL, with one
10//! instance, the participant, kept KEEP_LAST 1.
11//!
12//! [`SpdpSecure`] holds the two endpoints without doing any I/O, like
13//! [`crate::wlp::Wlp`]; DDS Security protects what they send. Their
14//! entity ids are in 7.5.8 and their bits of `availableBuiltinEndpoints`
15//! in 7.4.1.6.
16
17use std::time::Instant;
18
19use crate::error::DecodeError;
20use crate::parameter::{Parameter, ParameterList};
21use crate::pl::{PlBuilder, decode_pl_payload, encode_pl_payload, pid};
22use crate::receiver::receive;
23use crate::reliable::{
24    MatchedReader, Outgoing, ReaderConfig, ReliableReader, ReliableWriter, WriterConfig,
25};
26use crate::spdp::ParticipantData;
27use crate::submessage::{PayloadKind, SerializedPayload, Submessage};
28use crate::types::{BuiltinEndpointSet, EntityId, Guid, GuidPrefix, SequenceNumber, VendorId};
29use crate::wire::Endianness;
30
31/// `StatusInfo_t` flags (DDSI-RTPS 2.5, 9.6.4.9).
32const STATUS_DISPOSED: u8 = 0x01;
33const STATUS_UNREGISTERED: u8 = 0x02;
34
35/// What a remote participant sent on DCPSParticipantsSecure.
36#[derive(Clone, Debug, PartialEq, Eq)]
37pub enum SecureParticipantEvent {
38    /// Its current data.
39    Data(Box<ParticipantData>),
40    /// It is going away (disposed or unregistered).
41    Disposed(GuidPrefix),
42}
43
44/// The SPDPbuiltinParticipantsSecureWriter and Reader of one participant.
45#[derive(Debug)]
46pub struct SpdpSecure {
47    prefix: GuidPrefix,
48    writer: ReliableWriter,
49    reader: ReliableReader,
50    /// The change with the local data (KEEP_LAST 1).
51    last: Option<SequenceNumber>,
52}
53
54impl SpdpSecure {
55    /// The bits of `availableBuiltinEndpoints` for the endpoints provided
56    /// here.
57    pub const BUILTIN_ENDPOINTS: u32 = BuiltinEndpointSet::PARTICIPANT_SECURE_WRITER
58        | BuiltinEndpointSet::PARTICIPANT_SECURE_READER;
59
60    /// The endpoints of the participant `prefix`.
61    pub fn new(
62        prefix: GuidPrefix,
63        vendor_id: VendorId,
64        writer: WriterConfig,
65        reader: ReaderConfig,
66    ) -> Self {
67        SpdpSecure {
68            prefix,
69            writer: ReliableWriter::new(
70                Guid::new(
71                    prefix,
72                    EntityId::SPDP_RELIABLE_BUILTIN_PARTICIPANT_SECURE_WRITER,
73                ),
74                vendor_id,
75                writer,
76            ),
77            reader: ReliableReader::new(
78                Guid::new(
79                    prefix,
80                    EntityId::SPDP_RELIABLE_BUILTIN_PARTICIPANT_SECURE_READER,
81                ),
82                vendor_id,
83                reader,
84            ),
85            last: None,
86        }
87    }
88
89    /// Connects with the endpoints of an authenticated participant, as
90    /// far as its `availableBuiltinEndpoints` says it has them. The local
91    /// participant is ignored.
92    pub fn add_participant(&mut self, p: &ParticipantData, now: Instant) {
93        if p.guid_prefix == self.prefix {
94            return;
95        }
96        let set = p.available_builtin_endpoints;
97        let uc = p.metatraffic_unicast_locators.clone();
98        let mc = p.metatraffic_multicast_locators.clone();
99        if set.contains(BuiltinEndpointSet::PARTICIPANT_SECURE_READER) {
100            self.writer.add_matched_reader(
101                Guid::new(
102                    p.guid_prefix,
103                    EntityId::SPDP_RELIABLE_BUILTIN_PARTICIPANT_SECURE_READER,
104                ),
105                MatchedReader {
106                    unicast: uc.clone(),
107                    multicast: mc.clone(),
108                    reliable: true,
109                    history: true,
110                },
111            );
112        }
113        if set.contains(BuiltinEndpointSet::PARTICIPANT_SECURE_WRITER) {
114            self.reader.add_writer(
115                Guid::new(
116                    p.guid_prefix,
117                    EntityId::SPDP_RELIABLE_BUILTIN_PARTICIPANT_SECURE_WRITER,
118                ),
119                uc,
120                mc,
121                now,
122            );
123        }
124    }
125
126    /// Disconnects from a participant that is gone.
127    pub fn remove_participant(&mut self, prefix: &GuidPrefix) {
128        self.writer.remove_readers_of(prefix);
129        self.reader.remove_writers_of(prefix);
130    }
131
132    /// Writes the local participant's data, replacing what was written
133    /// before. It is sent at the next [`Self::poll`].
134    pub fn write(&mut self, data: &ParticipantData) {
135        let mut qos = ParameterList::new();
136        qos.push(Parameter::new(pid::KEY_HASH, data.guid().to_bytes()));
137        let sn = self.writer.add_change(
138            Some(qos),
139            Some(SerializedPayload {
140                kind: PayloadKind::Data,
141                bytes: data.to_payload(Endianness::NATIVE).into(),
142            }),
143        );
144        if let Some(old) = self.last.replace(sn) {
145            self.writer.remove_change(old);
146        }
147    }
148
149    /// Writes that the local participant is going away: disposed and
150    /// unregistered, with the key, `PID_PARTICIPANT_GUID`, as the
151    /// payload, as on SPDP (DDSI-RTPS 2.5, 9.6.3.2). Returns its sequence
152    /// number, for [`Self::is_acked_by_all`].
153    pub fn dispose(&mut self) -> SequenceNumber {
154        let e = Endianness::NATIVE;
155        let guid = Guid::new(self.prefix, EntityId::PARTICIPANT);
156        let mut qos = ParameterList::new();
157        qos.push(Parameter::new(pid::KEY_HASH, guid.to_bytes()));
158        qos.push(Parameter::new(
159            pid::STATUS_INFO,
160            [0, 0, 0, STATUS_DISPOSED | STATUS_UNREGISTERED],
161        ));
162        let mut key = ParameterList::new();
163        key.push(PlBuilder::new(e).guid(pid::PARTICIPANT_GUID, guid));
164        let sn = self.writer.add_change(
165            Some(qos),
166            Some(SerializedPayload {
167                kind: PayloadKind::Key,
168                bytes: encode_pl_payload(&key, e).into(),
169            }),
170        );
171        if let Some(old) = self.last.replace(sn) {
172            self.writer.remove_change(old);
173        }
174        sn
175    }
176
177    /// Whether every matched reader acknowledged the change `sn`.
178    pub fn is_acked_by_all(&self, sn: SequenceNumber) -> bool {
179        self.writer.is_acked_by_all(sn)
180    }
181
182    /// Processes one received RTPS message, decoded by DDS Security:
183    /// returns what other participants sent. The data and disposes are
184    /// taken as the writer's participant's own, whatever they say.
185    pub fn handle_message(&mut self, bytes: &[u8], now: Instant) -> Vec<SecureParticipantEvent> {
186        let mut out = Vec::new();
187        let Some((_, received)) = receive(bytes, self.prefix) else {
188            return out;
189        };
190        let w = EntityId::SPDP_RELIABLE_BUILTIN_PARTICIPANT_SECURE_WRITER;
191        for r in received {
192            let src = r.source_prefix;
193            let changes = match r.submessage {
194                Submessage::Data(d) if d.writer_id == w => {
195                    self.reader
196                        .handle_data(Guid::new(src, d.writer_id), &d, r.timestamp)
197                }
198                Submessage::DataFrag(d) if d.writer_id == w => {
199                    self.reader
200                        .handle_data_frag(Guid::new(src, d.writer_id), &d, r.timestamp)
201                }
202                Submessage::Gap(g) if g.writer_id == w => {
203                    self.reader.handle_gap(Guid::new(src, g.writer_id), &g)
204                }
205                Submessage::Heartbeat(h) if h.writer_id == w => {
206                    self.reader
207                        .handle_heartbeat(Guid::new(src, h.writer_id), &h, now)
208                }
209                Submessage::HeartbeatFrag(h) if h.writer_id == w => {
210                    self.reader
211                        .handle_heartbeat_frag(Guid::new(src, h.writer_id), &h, now);
212                    Vec::new()
213                }
214                Submessage::AckNack(a) if a.writer_id == w => {
215                    self.writer
216                        .handle_acknack(Guid::new(src, a.reader_id), &a, now);
217                    Vec::new()
218                }
219                Submessage::NackFrag(n) if n.writer_id == w => {
220                    self.writer
221                        .handle_nackfrag(Guid::new(src, n.reader_id), &n, now);
222                    Vec::new()
223                }
224                _ => Vec::new(),
225            };
226            for c in changes {
227                let from = c.writer.prefix;
228                let status = c
229                    .inline_qos
230                    .as_ref()
231                    .and_then(|q| q.get(pid::STATUS_INFO))
232                    .and_then(|p| p.value.get(3).copied())
233                    .unwrap_or(0);
234                if status & (STATUS_DISPOSED | STATUS_UNREGISTERED) != 0 {
235                    out.push(SecureParticipantEvent::Disposed(from));
236                    continue;
237                }
238                let Some(p) = c.payload.filter(|p| p.kind == PayloadKind::Data) else {
239                    continue;
240                };
241                if let Ok(d) = Self::data_from_payload(&p.bytes)
242                    && d.guid_prefix == from
243                {
244                    out.push(SecureParticipantEvent::Data(Box::new(d)));
245                }
246            }
247        }
248        out
249    }
250
251    /// Reads `ParticipantBuiltinTopicDataSecure`: the SPDP data, the
252    /// `identity_status_token` being skipped.
253    fn data_from_payload(bytes: &[u8]) -> Result<ParticipantData, DecodeError> {
254        let (mut list, e) = decode_pl_payload(bytes)?;
255        list.parameters
256            .retain(|p| p.id != pid::IDENTITY_STATUS_TOKEN);
257        ParticipantData::from_parameter_list(&list, e)
258    }
259
260    /// The datagrams due at `now`.
261    pub fn poll(&mut self, now: Instant) -> Vec<Outgoing> {
262        let mut out = self.writer.poll(now);
263        out.extend(self.reader.poll(now));
264        out
265    }
266
267    /// When [`Self::poll`] next has something to do, if no message comes
268    /// in before.
269    pub fn next_deadline(&self) -> Option<Instant> {
270        [self.writer.next_deadline(), self.reader.next_deadline()]
271            .into_iter()
272            .flatten()
273            .min()
274    }
275}
276
277#[cfg(test)]
278mod tests {
279    use super::*;
280    use crate::types::Locator;
281    use std::time::Duration;
282
283    fn prefix(n: u8) -> GuidPrefix {
284        GuidPrefix([n; 12])
285    }
286
287    fn participant(n: u8) -> ParticipantData {
288        let mut p = ParticipantData::new(prefix(n), VendorId::UNKNOWN);
289        p.available_builtin_endpoints.0 |= SpdpSecure::BUILTIN_ENDPOINTS;
290        p.metatraffic_unicast_locators = vec![Locator::udpv4(std::net::SocketAddrV4::new(
291            std::net::Ipv4Addr::LOCALHOST,
292            7400 + n as u16,
293        ))];
294        p
295    }
296
297    fn secure(n: u8) -> SpdpSecure {
298        SpdpSecure::new(
299            prefix(n),
300            VendorId::UNKNOWN,
301            WriterConfig::default(),
302            ReaderConfig::default(),
303        )
304    }
305
306    fn pump(
307        a: &mut SpdpSecure,
308        b: &mut SpdpSecure,
309        t: Instant,
310    ) -> (Vec<SecureParticipantEvent>, Vec<SecureParticipantEvent>) {
311        let (mut got_a, mut got_b) = (Vec::new(), Vec::new());
312        for _ in 0..10 {
313            let out_a = a.poll(t);
314            let out_b = b.poll(t);
315            if out_a.is_empty() && out_b.is_empty() {
316                break;
317            }
318            for o in out_a {
319                got_b.extend(b.handle_message(&o.bytes, t));
320            }
321            for o in out_b {
322                got_a.extend(a.handle_message(&o.bytes, t));
323            }
324        }
325        (got_a, got_b)
326    }
327
328    #[test]
329    fn data_changes_and_deletion_reach_the_other_participant() {
330        let t = Instant::now();
331        let mut a = secure(1);
332        let mut b = secure(2);
333        let mut data = participant(1);
334        // Written before the other side is known: it is kept for it.
335        a.write(&data);
336        a.add_participant(&participant(2), t);
337        b.add_participant(&data, t);
338        let (_, got) = pump(&mut a, &mut b, t);
339        assert_eq!(got, [SecureParticipantEvent::Data(Box::new(data.clone()))]);
340        // A change replaces the data (KEEP_LAST 1).
341        data.user_data = vec![1, 2, 3];
342        a.write(&data);
343        assert_eq!(a.writer.len(), 1);
344        let (_, got) = pump(&mut a, &mut b, t + Duration::from_millis(10));
345        assert_eq!(got, [SecureParticipantEvent::Data(Box::new(data.clone()))]);
346        let sn = a.dispose();
347        let (_, got) = pump(&mut a, &mut b, t + Duration::from_millis(20));
348        assert_eq!(got, [SecureParticipantEvent::Disposed(prefix(1))]);
349        assert!(a.is_acked_by_all(sn));
350    }
351
352    #[test]
353    fn data_of_another_participant_is_ignored() {
354        let t = Instant::now();
355        let mut a = secure(1);
356        let mut b = secure(2);
357        // Participant 1 writes data that claims to be participant 3's.
358        a.write(&participant(3));
359        a.add_participant(&participant(2), t);
360        b.add_participant(&participant(1), t);
361        let (_, got) = pump(&mut a, &mut b, t);
362        assert!(got.is_empty());
363    }
364
365    #[test]
366    fn the_identity_status_token_is_skipped() {
367        let d = participant(4);
368        let e = Endianness::Little;
369        let mut list = d.to_parameter_list(e);
370        list.push(Parameter::new(pid::IDENTITY_STATUS_TOKEN, vec![0u8; 8]));
371        let bytes = encode_pl_payload(&list, e);
372        assert_eq!(SpdpSecure::data_from_payload(&bytes).unwrap(), d);
373    }
374}