Skip to main content

rtci_interceptor/rtcp_session/
identity.rs

1//! The identity an endpoint has in RTCP: its CNAME (RFC 7022) and the SSRC it reports from
2//! when it sends no media (RFC 3550 8.1), and where the randomness for both comes from.
3
4/// The source of the random numbers the RTCP session uses: the variation of the report
5/// interval (RFC 3550 6.3.1), the dither of early feedback (RFC 4585 3.5.2), a reporting SSRC
6/// (RFC 3550 8.1) and the CNAME (RFC 7022 section 5).
7///
8/// The default draws from the operating system's CSPRNG through `rand`. A test supplies its
9/// own for a run that repeats exactly.
10pub trait RtcpRandom: Send + Sync {
11    /// 32 random bits.
12    fn next_u32(&mut self) -> u32;
13
14    /// A number uniformly distributed in [0, 1).
15    fn unit(&mut self) -> f64 {
16        f64::from(self.next_u32()) / 4_294_967_296.0
17    }
18}
19
20/// One [`RtcpRandom`] shared by the RTCP sessions of a peer connection
21/// ([`RtcpSessionBuilder::build_per_rtp_session`](super::RtcpSessionBuilder::build_per_rtp_session)).
22#[derive(Clone)]
23pub(crate) struct SharedRandom(pub(crate) std::sync::Arc<std::sync::Mutex<Box<dyn RtcpRandom>>>);
24
25impl RtcpRandom for SharedRandom {
26    fn next_u32(&mut self) -> u32 {
27        match self.0.lock() {
28            Ok(mut random) => random.next_u32(),
29            Err(poisoned) => poisoned.into_inner().next_u32(),
30        }
31    }
32}
33
34/// [`RtcpRandom`] from the thread's cryptographically secure generator.
35#[derive(Debug, Default, Clone, Copy)]
36pub(crate) struct ThreadRandom;
37
38impl RtcpRandom for ThreadRandom {
39    fn next_u32(&mut self) -> u32 {
40        rand::random::<u32>()
41    }
42}
43
44const BASE64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
45
46/// A short-term persistent RTCP CNAME as RFC 7022 section 4.2 defines it: 96 random bits
47/// (section 5 asks for at least that many, from a cryptographic generator), Base64 encoded
48/// into 16 characters, with no "user@" part and nothing that identifies the host or the user.
49pub(crate) fn generate_cname(random: &mut dyn RtcpRandom) -> String {
50    let mut octets = [0u8; 12];
51    for chunk in octets.chunks_mut(4) {
52        chunk.copy_from_slice(&random.next_u32().to_be_bytes());
53    }
54    let mut cname = String::with_capacity(16);
55    for triple in octets.chunks(3) {
56        let bits = u32::from(triple[0]) << 16 | u32::from(triple[1]) << 8 | u32::from(triple[2]);
57        for shift in [18, 12, 6, 0] {
58            cname.push(char::from(BASE64[((bits >> shift) & 0x3F) as usize]));
59        }
60    }
61    cname
62}
63
64/// A new RTCP CNAME for an endpoint, as RFC 7022 section 4.2 defines a short-term persistent
65/// one: 96 bits from the operating system's CSPRNG, Base64 encoded (16 characters). RFC 8834
66/// 4.9 asks for one per `RTCPeerConnection`, used by every SSRC it sends from.
67pub fn generate_rtcp_cname() -> String {
68    generate_cname(&mut ThreadRandom)
69}
70
71/// A new SSRC for this endpoint (RFC 3550 8.1): random, never zero, and not one `in_use`
72/// reports as taken by a source already in the session.
73pub(crate) fn choose_ssrc(random: &mut dyn RtcpRandom, in_use: impl Fn(u32) -> bool) -> u32 {
74    loop {
75        let candidate = random.next_u32();
76        if candidate != 0 && !in_use(candidate) {
77            return candidate;
78        }
79    }
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85
86    struct Counter(u32);
87
88    impl RtcpRandom for Counter {
89        fn next_u32(&mut self) -> u32 {
90            self.0 = self.0.wrapping_add(1);
91            self.0
92        }
93    }
94
95    /// RFC 7022 4.2: "at least the low 96 bits ... MUST be Base64 encoded" (16 characters).
96    #[test]
97    fn a_cname_is_96_random_bits_in_base64() {
98        let cname = generate_cname(&mut ThreadRandom);
99        assert_eq!(16, cname.len());
100        assert!(
101            cname
102                .bytes()
103                .all(|b| b.is_ascii_alphanumeric() || b == b'+' || b == b'/')
104        );
105        assert!(!cname.contains('@'));
106
107        // RFC 4648 section 10: BASE64("foobar") = "Zm9vYmFy"; twelve octets of it twice over.
108        struct Foobar(u32);
109        impl RtcpRandom for Foobar {
110            fn next_u32(&mut self) -> u32 {
111                let words = [
112                    u32::from_be_bytes(*b"foob"),
113                    u32::from_be_bytes(*b"arfo"),
114                    u32::from_be_bytes(*b"obar"),
115                ];
116                self.0 += 1;
117                words[(self.0 as usize - 1) % 3]
118            }
119        }
120        assert_eq!("Zm9vYmFyZm9vYmFy", generate_cname(&mut Foobar(0)));
121    }
122
123    /// RFC 7022 section 5: random, so two endpoints (and two sessions) do not share one.
124    #[test]
125    fn two_cnames_differ() {
126        assert_ne!(
127            generate_cname(&mut ThreadRandom),
128            generate_cname(&mut ThreadRandom)
129        );
130    }
131
132    /// RFC 3550 8.1: a candidate already in use is drawn again; zero is never chosen.
133    #[test]
134    fn a_chosen_ssrc_is_not_zero_and_not_in_use() {
135        // The counter yields 1, 2, 3, ...: 1 and 2 are taken.
136        assert_eq!(3, choose_ssrc(&mut Counter(0), |ssrc| ssrc < 3));
137        // It yields 0 first here.
138        assert_eq!(1, choose_ssrc(&mut Counter(u32::MAX), |_| false));
139    }
140
141    #[test]
142    fn unit_is_in_the_half_open_interval() {
143        struct Fixed(u32);
144        impl RtcpRandom for Fixed {
145            fn next_u32(&mut self) -> u32 {
146                self.0
147            }
148        }
149        assert_eq!(0.0, Fixed(0).unit());
150        assert!(Fixed(u32::MAX).unit() < 1.0);
151        assert_eq!(0.5, Fixed(1 << 31).unit());
152    }
153}