Skip to main content

rtci_shared/
util.rs

1//! Shared helpers: packet demultiplexing and random strings.
2//!
3//! WebRTC multiplexes STUN, DTLS and SRTP onto one port, so the first byte of a datagram decides
4//! which layer receives it ([RFC 7983]). The `match_*` predicates implement those ranges, and
5//! [`is_rtcp`](crate::util::is_rtcp) separates RTCP from RTP once a packet is known to be one of the two.
6//!
7//! [RFC 7983]: https://datatracker.ietf.org/doc/html/rfc7983
8use crate::error::{Error, Result};
9use rand::{RngExt, rng};
10use std::net::{SocketAddr, ToSocketAddrs};
11
12// match_range is a MatchFunc that accepts packets with the first byte in [lower..upper]
13fn match_range(lower: u8, upper: u8) -> impl Fn(&[u8]) -> bool {
14    move |buf: &[u8]| -> bool {
15        if buf.is_empty() {
16            return false;
17        }
18        let b = buf[0];
19        b >= lower && b <= upper
20    }
21}
22
23/// MatchFuncs as described in RFC7983
24/// <https://tools.ietf.org/html/rfc7983>
25///              +----------------+
26///              |        [0..3] -+--> forward to STUN
27///              |                |
28///              |      [16..19] -+--> forward to ZRTP
29///              |                |
30///  packet -->  |      [20..63] -+--> forward to DTLS
31///              |                |
32///              |      [64..79] -+--> forward to TURN Channel
33///              |                |
34///              |    [128..191] -+--> forward to RTP/RTCP
35///              +----------------+
36/// match_dtls is a MatchFunc that accepts packets with the first byte in [20..63]
37/// as defied in RFC7983
38pub fn match_dtls(b: &[u8]) -> bool {
39    match_range(20, 63)(b)
40}
41
42/// Returns `true` if `b` looks like SRTP or SRTCP: its first byte is in `[128, 191]`.
43///
44/// One of the demultiplexing predicates from [RFC 7983], which is how a single port can carry
45/// STUN, DTLS and SRTP at once.
46///
47/// [RFC 7983]: https://datatracker.ietf.org/doc/html/rfc7983
48pub fn match_srtp_or_srtcp(b: &[u8]) -> bool {
49    match_range(128, 191)(b)
50}
51
52/// Returns `true` if `buf` is RTCP rather than RTP.
53///
54/// Distinguished by the second octet, as [RFC 5761] ยง4 has it: an RTCP packet carries its
55/// packet type there, and the types RTCP uses next to RTP are `[192, 223]`. An RTP packet
56/// carries the marker bit and its 7-bit payload type there, so the octet is in that range only
57/// for payload types 64 to 95 sent with the marker bit set, which is why RFC 5761 forbids
58/// those payload types when RTP and RTCP share a port. The same payload types without the
59/// marker bit (second octet 64 to 95) are RTP like any other.
60///
61/// Returns `false` for buffers too short to tell.
62///
63/// [RFC 5761]: https://datatracker.ietf.org/doc/html/rfc5761#section-4
64pub fn is_rtcp(buf: &[u8]) -> bool {
65    // Not long enough to determine RTP/RTCP
66    if buf.len() < 4 {
67        return false;
68    }
69
70    let rtcp_packet_type = buf[1];
71    (192..=223).contains(&rtcp_packet_type)
72}
73
74/// match_srtp is a MatchFunc that only matches SRTP and not SRTCP
75pub fn match_srtp(buf: &[u8]) -> bool {
76    match_srtp_or_srtcp(buf) && !is_rtcp(buf)
77}
78
79/// match_srtcp is a MatchFunc that only matches SRTCP and not SRTP
80pub fn match_srtcp(buf: &[u8]) -> bool {
81    match_srtp_or_srtcp(buf) && is_rtcp(buf)
82}
83
84/// lookup host to SocketAddr
85pub fn lookup_host<T>(use_ipv4: bool, host: T) -> Result<SocketAddr>
86where
87    T: ToSocketAddrs,
88{
89    for remote_addr in host.to_socket_addrs()? {
90        if (use_ipv4 && remote_addr.is_ipv4()) || (!use_ipv4 && remote_addr.is_ipv6()) {
91            return Ok(remote_addr);
92        }
93    }
94
95    Err(Error::ErrAddressParseFailed)
96}
97
98const RUNES_ALPHA: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
99const RUNES_ALPHA_NUMBER: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
100
101/// math_rand_alpha generates a mathematical random alphabet sequence of the requested length.
102pub fn math_rand_alpha(n: usize) -> String {
103    generate_crypto_random_string(n, RUNES_ALPHA)
104}
105
106/// math_rand_alpha generates a mathematical random alphabet and number sequence of the requested length.
107pub fn math_rand_alpha_number(n: usize) -> String {
108    generate_crypto_random_string(n, RUNES_ALPHA_NUMBER)
109}
110
111//TODO: generates a random string for cryptographic usage.
112/// Generates a random `n`-character string drawn from `runes`.
113///
114/// Used for values that must be unguessable, such as ICE credentials and SDP identifiers.
115pub fn generate_crypto_random_string(n: usize, runes: &[u8]) -> String {
116    let mut rng = rng();
117
118    let rand_string: String = (0..n)
119        .map(|_| {
120            let idx = rng.random_range(0..runes.len());
121            runes[idx] as char
122        })
123        .collect();
124
125    rand_string
126}
127
128#[cfg(test)]
129mod rtp_rtcp_demux_test {
130    use super::*;
131
132    fn packet(first: u8, second: u8) -> [u8; 12] {
133        let mut p = [0u8; 12];
134        p[0] = first;
135        p[1] = second;
136        p
137    }
138
139    // RFC 5761 4: "RTCP packet types in the ranges 1-191 and 224-254 SHOULD only be used when
140    // other values have been exhausted", and the demultiplexing is on 192 to 223.
141    #[test]
142    fn the_second_octet_192_to_223_is_rtcp_and_nothing_else_is() {
143        for second in 0..=u8::MAX {
144            let want = (192..=223).contains(&second);
145            assert_eq!(
146                want,
147                is_rtcp(&packet(0x80, second)),
148                "second octet {second}"
149            );
150            assert_eq!(
151                want,
152                match_srtcp(&packet(0x80, second)),
153                "second octet {second}"
154            );
155            assert_eq!(
156                !want,
157                match_srtp(&packet(0x80, second)),
158                "second octet {second}"
159            );
160        }
161    }
162
163    // RFC 5761 4: payload types 64 to 95 collide with RTCP only when the marker bit is set
164    // (second octet 192 to 223). Without it they are RTP: the test is on the whole octet, not
165    // on the payload type with the marker bit masked away.
166    #[test]
167    fn payload_types_64_to_95_are_rtcp_only_with_the_marker_bit() {
168        for payload_type in 64..=95u8 {
169            assert!(
170                !is_rtcp(&packet(0x80, payload_type)),
171                "PT {payload_type}, M=0"
172            );
173            assert!(
174                is_rtcp(&packet(0x80, 0x80 | payload_type)),
175                "PT {payload_type}, M=1"
176            );
177        }
178        // The payload types WebRTC uses, with and without the marker bit.
179        for payload_type in (0..=63u8).chain(96..=127) {
180            assert!(
181                !is_rtcp(&packet(0x80, payload_type)),
182                "PT {payload_type}, M=0"
183            );
184            assert!(
185                !is_rtcp(&packet(0x80, 0x80 | payload_type)),
186                "PT {payload_type}, M=1"
187            );
188        }
189    }
190
191    // The RTCP packet types in use, each with the counts and formats they come with.
192    #[test]
193    fn every_rtcp_packet_type_in_use_is_rtcp() {
194        for (first, packet_type) in [
195            (0x80, 200), // SR
196            (0x81, 201), // RR
197            (0x81, 202), // SDES
198            (0x81, 203), // BYE
199            (0x80, 204), // APP
200            (0x81, 205), // RTPFB, generic NACK
201            (0x8f, 205), // RTPFB, transport-wide feedback
202            (0x81, 206), // PSFB, PLI
203            (0xaf, 206), // PSFB, REMB, padded
204            (0x80, 207), // XR
205        ] {
206            assert!(is_rtcp(&packet(first, packet_type)), "PT {packet_type}");
207        }
208    }
209
210    // RFC 7983 7: the first octet picks the protocol; 128 to 191 is RTP or RTCP. `is_rtcp`
211    // only tells those two apart, so `match_srtcp` asks for both.
212    #[test]
213    fn only_a_first_octet_of_128_to_191_is_rtp_or_rtcp() {
214        for first in 0..=u8::MAX {
215            let rtp_or_rtcp = (128..=191).contains(&first);
216            assert_eq!(
217                rtp_or_rtcp,
218                match_srtcp(&packet(first, 200)),
219                "first octet {first}"
220            );
221            assert_eq!(
222                rtp_or_rtcp,
223                match_srtp(&packet(first, 96)),
224                "first octet {first}"
225            );
226            assert!(!match_srtp(&packet(first, 200)));
227            assert!(!match_srtcp(&packet(first, 96)));
228        }
229    }
230
231    // Shorter than an RTCP header there is nothing to classify.
232    #[test]
233    fn a_buffer_shorter_than_an_rtcp_header_is_not_rtcp() {
234        assert!(!is_rtcp(&[]));
235        assert!(!is_rtcp(&[0x80]));
236        assert!(!is_rtcp(&[0x80, 200]));
237        assert!(!is_rtcp(&[0x80, 200, 0]));
238        assert!(is_rtcp(&[0x80, 200, 0, 0]));
239    }
240}