rtc_srtp/context/
srtcp.rs

1use super::*;
2use shared::{error::Result, marshal::Unmarshal};
3
4use bytes::BytesMut;
5
6impl Context {
7    /// DecryptRTCP decrypts a RTCP packet with an encrypted payload
8    pub fn decrypt_rtcp(&mut self, encrypted: &[u8]) -> Result<BytesMut> {
9        let mut buf = encrypted;
10        rtcp::header::Header::unmarshal(&mut buf)?;
11
12        let index = self.cipher.get_rtcp_index(encrypted);
13        let ssrc = u32::from_be_bytes([encrypted[4], encrypted[5], encrypted[6], encrypted[7]]);
14
15        {
16            if let Some(state) = self.get_srtcp_ssrc_state(ssrc) {
17                if let Some(replay_detector) = &mut state.replay_detector {
18                    if !replay_detector.check(index as u64) {
19                        return Err(Error::SrtcpSsrcDuplicated(ssrc, index));
20                    }
21                }
22            } else {
23                return Err(Error::SsrcMissingFromSrtcp(ssrc));
24            }
25        }
26
27        let dst = self.cipher.decrypt_rtcp(encrypted, index, ssrc)?;
28
29        {
30            if let Some(state) = self.get_srtcp_ssrc_state(ssrc) {
31                if let Some(replay_detector) = &mut state.replay_detector {
32                    replay_detector.accept();
33                }
34            }
35        }
36
37        Ok(dst)
38    }
39
40    /// EncryptRTCP marshals and encrypts an RTCP packet, writing to the dst buffer provided.
41    /// If the dst buffer does not have the capacity to hold `len(plaintext) + 14` bytes, a new one will be allocated and returned.
42    pub fn encrypt_rtcp(&mut self, decrypted: &[u8]) -> Result<BytesMut> {
43        let mut buf = decrypted;
44        rtcp::header::Header::unmarshal(&mut buf)?;
45
46        let ssrc = u32::from_be_bytes([decrypted[4], decrypted[5], decrypted[6], decrypted[7]]);
47
48        let index;
49        {
50            if let Some(state) = self.get_srtcp_ssrc_state(ssrc) {
51                state.srtcp_index += 1;
52                if state.srtcp_index > MAX_SRTCP_INDEX {
53                    state.srtcp_index = 0;
54                }
55                index = state.srtcp_index;
56            } else {
57                return Err(Error::SsrcMissingFromSrtcp(ssrc));
58            }
59        }
60
61        self.cipher.encrypt_rtcp(decrypted, index, ssrc)
62    }
63}