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::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        if let Some(replay_detector) = &mut self.get_srtcp_ssrc_state(ssrc).replay_detector
16            && !replay_detector.check(index as u64)
17        {
18            return Err(Error::SrtcpSsrcDuplicated(ssrc, index));
19        }
20
21        let dst = self.cipher.decrypt_rtcp(encrypted, index, ssrc)?;
22
23        if let Some(replay_detector) = &mut self.get_srtcp_ssrc_state(ssrc).replay_detector {
24            replay_detector.accept();
25        }
26
27        Ok(dst)
28    }
29
30    /// EncryptRTCP marshals and encrypts an RTCP packet, writing to the dst buffer provided.
31    /// If the dst buffer does not have the capacity to hold `len(plaintext) + 14` bytes, a new one will be allocated and returned.
32    pub fn encrypt_rtcp(&mut self, decrypted: &[u8]) -> Result<BytesMut> {
33        if decrypted.len() < 8 {
34            return Err(Error::ErrTooShortRtcp);
35        }
36
37        let mut buf = decrypted;
38        rtcp::Header::unmarshal(&mut buf)?;
39
40        let ssrc = u32::from_be_bytes([decrypted[4], decrypted[5], decrypted[6], decrypted[7]]);
41
42        let index = {
43            let state = self.get_srtcp_ssrc_state(ssrc);
44            state.srtcp_index += 1;
45            if state.srtcp_index > MAX_SRTCP_INDEX {
46                state.srtcp_index = 0;
47            }
48            state.srtcp_index
49        };
50
51        self.cipher.encrypt_rtcp(decrypted, index, ssrc)
52    }
53}