webrtc_srtp/context/
srtcp.rs

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