Skip to main content

rustorb_rtps/
message.rs

1//! RTPS messages: the header followed by submessages
2//! (DDSI-RTPS 2.5, 8.3.3, 8.3.4.1, 9.4.1, 9.4.4 and 9.4.5.1).
3
4use crate::error::{DecodeError, EncodeError};
5use crate::submessage::{Submessage, submessage_id};
6use crate::types::{GuidPrefix, ProtocolVersion, VendorId};
7use crate::wire::{Endianness, Reader, Writer};
8
9/// `PROTOCOL_RTPS`.
10pub const PROTOCOL_RTPS: [u8; 4] = *b"RTPS";
11
12/// The fixed 20-octet header at the start of every message (9.4.4).
13#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
14pub struct Header {
15    /// The protocol version of the sender.
16    pub version: ProtocolVersion,
17    /// The vendor of the sender.
18    pub vendor_id: VendorId,
19    /// The participant of the sender; the default prefix for the GUIDs in
20    /// the message.
21    pub guid_prefix: GuidPrefix,
22}
23
24impl Header {
25    /// The size of the header on the wire.
26    pub const SIZE: usize = 20;
27
28    /// A header for this crate's protocol version (2.5).
29    pub fn new(vendor_id: VendorId, guid_prefix: GuidPrefix) -> Self {
30        Header {
31            version: ProtocolVersion::CURRENT,
32            vendor_id,
33            guid_prefix,
34        }
35    }
36
37    /// Reads a header from the start of `bytes`.
38    ///
39    /// Fails if the input is shorter than 20 octets, does not start with
40    /// `RTPS`, or has a major version above 2 (8.3.6.3).
41    pub fn decode(bytes: &[u8]) -> Result<Header, DecodeError> {
42        // The header has no multi-octet integers, so the byte order does
43        // not matter.
44        let mut r = Reader::new(bytes, Endianness::Big);
45        let protocol: [u8; 4] = r.array()?;
46        if protocol != PROTOCOL_RTPS {
47            return Err(DecodeError::NotRtps(protocol));
48        }
49        let version = ProtocolVersion::read(&mut r)?;
50        if version.major > ProtocolVersion::CURRENT.major {
51            return Err(DecodeError::UnsupportedVersion(version));
52        }
53        Ok(Header {
54            version,
55            vendor_id: VendorId::read(&mut r)?,
56            guid_prefix: GuidPrefix::read(&mut r)?,
57        })
58    }
59
60    fn write(&self, w: &mut Writer<'_>) {
61        w.bytes(&PROTOCOL_RTPS);
62        self.version.write(w);
63        self.vendor_id.write(w);
64        self.guid_prefix.write(w);
65    }
66}
67
68/// A whole RTPS message, as carried in one UDP datagram (9.5).
69#[derive(Clone, Debug, PartialEq, Eq)]
70pub struct Message {
71    /// The header.
72    pub header: Header,
73    /// The submessages, in order.
74    pub submessages: Vec<Submessage>,
75}
76
77impl Message {
78    /// A message with no submessages yet.
79    pub fn new(header: Header) -> Self {
80        Message {
81            header,
82            submessages: Vec::new(),
83        }
84    }
85
86    /// Reads a whole message and fails on the first problem.
87    ///
88    /// The receive rules of 8.3.4.1 say that the submessages before an
89    /// invalid one are still valid. To act on those, use
90    /// [`Message::parse`] instead.
91    pub fn decode(bytes: &[u8]) -> Result<Message, DecodeError> {
92        let (header, submessages) = Message::parse(bytes)?;
93        Ok(Message {
94            header,
95            submessages: submessages.collect::<Result<_, _>>()?,
96        })
97    }
98
99    /// Reads the header and returns an iterator over the submessages.
100    ///
101    /// The iterator follows 8.3.4.1: unknown submessage ids and unknown
102    /// flags are skipped (unknown ids come out as
103    /// [`Submessage::Unknown`]), and after the first error it yields that
104    /// error and then stops, as the rest of the message is invalid.
105    pub fn parse(bytes: &[u8]) -> Result<(Header, Submessages<'_>), DecodeError> {
106        let header = Header::decode(bytes)?;
107        Ok((
108            header,
109            Submessages {
110                bytes,
111                pos: Header::SIZE,
112                index: 0,
113                done: false,
114                base: None,
115            },
116        ))
117    }
118
119    /// Like [`Message::parse`], with the payloads of DATA and DATA_FRAG
120    /// as slices of `bytes` instead of copies.
121    pub fn parse_shared(bytes: &crate::Octets) -> Result<(Header, Submessages<'_>), DecodeError> {
122        let (header, mut subs) = Message::parse(bytes)?;
123        subs.base = Some(bytes);
124        Ok((header, subs))
125    }
126
127    /// Writes the message with every submessage in byte order
128    /// `endianness`.
129    ///
130    /// Each submessage but the last is padded with zeros so that the next
131    /// one starts on a 4-octet boundary (9.4.1). The last one may be
132    /// longer than 65535 octets; its `octetsToNextHeader` is then 0
133    /// (9.4.5.1.3).
134    pub fn encode(&self, endianness: Endianness) -> Result<Vec<u8>, EncodeError> {
135        let mut out = Vec::new();
136        self.encode_into(&mut out, endianness)?;
137        Ok(out)
138    }
139
140    /// Like [`Message::encode`], appending to `out`.
141    pub fn encode_into(
142        &self,
143        out: &mut Vec<u8>,
144        endianness: Endianness,
145    ) -> Result<(), EncodeError> {
146        let mut w = Writer::new(out, endianness);
147        self.header.write(&mut w);
148        let last = self.submessages.len().saturating_sub(1);
149        for (index, sub) in self.submessages.iter().enumerate() {
150            let id = sub.id();
151            if id == submessage_id::RTPS_HE && index != 0 {
152                return Err(EncodeError::MisplacedHeaderExtension { index });
153            }
154            let header_at = w.len();
155            w.zeros(4);
156            let flags = sub.write_body(&mut w)?;
157            if index != last {
158                w.align4();
159            }
160            let body_len = w.len() - header_at - 4;
161            let length = if body_len == 0 {
162                let zero_means_empty = matches!(id, submessage_id::PAD | submessage_id::INFO_TS);
163                if !zero_means_empty && index != last {
164                    return Err(EncodeError::EmptySubmessage { index });
165                }
166                0
167            } else {
168                match u16::try_from(body_len) {
169                    Ok(n) => n,
170                    Err(_) if index == last && id != submessage_id::PAD => 0,
171                    Err(_) => return Err(EncodeError::SubmessageTooLong { index }),
172                }
173            };
174            // The length is in the byte order of the submessage, which for
175            // an unknown submessage is the one it was received in.
176            let len_bytes = match Endianness::from_flags(flags) {
177                Endianness::Big => length.to_be_bytes(),
178                Endianness::Little => length.to_le_bytes(),
179            };
180            w.patch(header_at, &[id, flags, len_bytes[0], len_bytes[1]]);
181        }
182        Ok(())
183    }
184}
185
186/// Iterator over the submessages of a message; see [`Message::parse`].
187#[derive(Debug)]
188pub struct Submessages<'a> {
189    bytes: &'a [u8],
190    base: Option<&'a crate::Octets>,
191    pos: usize,
192    index: usize,
193    done: bool,
194}
195
196impl Submessages<'_> {
197    fn next_inner(&mut self) -> Result<Submessage, DecodeError> {
198        let offset = self.pos;
199        let rest = &self.bytes[offset..];
200        // 8.3.4.1 rule 1.
201        if rest.len() < 4 {
202            return Err(DecodeError::BadSubmessageLength { offset });
203        }
204        let id = rest[0];
205        let flags = rest[1];
206        let raw = [rest[2], rest[3]];
207        let length = match Endianness::from_flags(flags) {
208            Endianness::Big => u16::from_be_bytes(raw),
209            Endianness::Little => u16::from_le_bytes(raw),
210        } as usize;
211        let after_header = &rest[4..];
212        // 9.4.5.1.3: 0 means "to the end of the message", except for PAD
213        // and INFO_TS where it means an empty body.
214        let body = if length == 0 {
215            if matches!(id, submessage_id::PAD | submessage_id::INFO_TS) {
216                &after_header[..0]
217            } else {
218                after_header
219            }
220        } else if length <= after_header.len() {
221            &after_header[..length]
222        } else {
223            // 8.3.4.1 rule 2.
224            return Err(DecodeError::BadSubmessageLength { offset });
225        };
226        self.pos = offset + 4 + body.len();
227        // 8.3.7.3: a HeaderExtension must come right after the Header.
228        if id == submessage_id::RTPS_HE && self.index != 0 {
229            return Err(DecodeError::InvalidSubmessage {
230                id,
231                reason: "HeaderExtension does not follow the Header",
232            });
233        }
234        self.index += 1;
235        Submessage::decode_body(id, flags, body, self.base)
236    }
237}
238
239impl Iterator for Submessages<'_> {
240    type Item = Result<Submessage, DecodeError>;
241
242    fn next(&mut self) -> Option<Self::Item> {
243        if self.done || self.pos >= self.bytes.len() {
244            return None;
245        }
246        let item = self.next_inner();
247        if item.is_err() {
248            self.done = true;
249        }
250        Some(item)
251    }
252}
253
254impl std::iter::FusedIterator for Submessages<'_> {}