///|
#derive(Eq, Debug)
pub(all) suberror SrtpError {
  InvalidKey
  InvalidPacket
  AuthFailed
  Replay
}

///|
pub impl Show for SrtpError with fn output(self, logger) {
  match self {
    InvalidKey => logger.write_string("InvalidKey")
    InvalidPacket => logger.write_string("InvalidPacket")
    AuthFailed => logger.write_string("AuthFailed")
    Replay => logger.write_string("Replay")
  }
}

///|
/// RFC 3711 ยง4.3.1 AES-CM key derivation PRF (with `kdr = 0`).
pub fn derive_key(
  master_key : BytesView,
  master_salt : BytesView,
  label : Byte,
  out_len : Int32,
) -> Bytes raise SrtpError {
  if master_salt.length() < 12 {
    raise InvalidKey
  }
  let iv_arr : Array[Byte] = []
  for i = 0; i < 16; i = i + 1 {
    iv_arr.push(if i < master_salt.length() { master_salt[i] } else { b'\x00' })
  }
  // 112-bit master salt (14 bytes); label sits at byte index 7 (bit 48 from LSB of 14 bytes).
  iv_arr[7] = (iv_arr[7].to_int() ^ label.to_int()).to_byte()
  iv_arr[14] = b'\x00'
  iv_arr[15] = b'\x00'
  let cipher = try @aes.Cipher::new(master_key) catch {
    _ => raise InvalidKey
  } noraise {
    c => c
  }
  let ctr = try @mode.Ctr::new(cipher, Bytes::from_array(iv_arr)) catch {
    _ => raise InvalidKey
  } noraise {
    c => c
  }
  let zeros = Bytes::make(out_len, b'\x00')
  ctr.apply(zeros)
}

///|
#derive(Eq, Debug)
pub struct SessionKeys {
  cipher_key : Bytes
  auth_key : Bytes
  cipher_salt : Bytes
}

///|
pub fn derive_session_keys(
  profile : @moontls_srtp.Profile,
  master_key : BytesView,
  master_salt : BytesView,
  is_srtcp~ : Bool = false,
) -> SessionKeys raise SrtpError {
  let k_len = profile.key_size()
  let s_len = profile.salt_size()
  let a_len = match profile {
    Aes128CmSha1Tag80 | Aes128CmSha1Tag32 | NullSha1Tag80 | NullSha1Tag32 => 20
    Aead128Gcm | Aead256Gcm => 0
  }
  let (l_enc, l_auth, l_salt) = if is_srtcp {
    (b'\x03', b'\x04', b'\x05')
  } else {
    (b'\x00', b'\x01', b'\x02')
  }
  let cipher_key = derive_key(master_key, master_salt, l_enc, k_len)
  let auth_key = if a_len > 0 {
    derive_key(master_key, master_salt, l_auth, a_len)
  } else {
    b""
  }
  let cipher_salt = derive_key(master_key, master_salt, l_salt, s_len)
  { cipher_key, auth_key, cipher_salt, }
}

///|
fn put_u32_be(out : Array[Byte], v : UInt32) -> Unit {
  out.push(((v >> 24) & 0xffU).to_byte())
  out.push(((v >> 16) & 0xffU).to_byte())
  out.push(((v >> 8) & 0xffU).to_byte())
  out.push((v & 0xffU).to_byte())
}

///|
fn get_u32_be(b : BytesView, off : Int32) -> UInt32 {
  (b[off].to_uint() << 24) |
  (b[off + 1].to_uint() << 16) |
  (b[off + 2].to_uint() << 8) |
  b[off + 3].to_uint()
}

///|
fn srtp_ctr_iv(salt : Bytes, ssrc : UInt32, index : UInt64) -> Bytes {
  let iv : Array[Byte] = []
  for i = 0; i < 14; i = i + 1 {
    iv.push(if i < salt.length() { salt[i] } else { b'\x00' })
  }
  iv.push(b'\x00')
  iv.push(b'\x00')
  // XOR ssrc into bytes 4..8, index (48-bit) into bytes 8..14
  iv[4] = (iv[4].to_int() ^ ((ssrc >> 24) & 0xffU).reinterpret_as_int()).to_byte()
  iv[5] = (iv[5].to_int() ^ ((ssrc >> 16) & 0xffU).reinterpret_as_int()).to_byte()
  iv[6] = (iv[6].to_int() ^ ((ssrc >> 8) & 0xffU).reinterpret_as_int()).to_byte()
  iv[7] = (iv[7].to_int() ^ (ssrc & 0xffU).reinterpret_as_int()).to_byte()
  for i = 0; i < 6; i = i + 1 {
    let shift = (5 - i) * 8
    iv[8 + i] = (iv[8 + i].to_int() ^ ((index >> shift) & 0xffUL).to_int()).to_byte()
  }
  Bytes::from_array(iv)
}

///|
fn srtp_gcm_nonce(salt : Bytes, ssrc : UInt32, index : UInt64) -> Bytes {
  let n : Array[Byte] = []
  for i = 0; i < 12; i = i + 1 {
    n.push(if i < salt.length() { salt[i] } else { b'\x00' })
  }
  n[2] = (n[2].to_int() ^ ((ssrc >> 24) & 0xffU).reinterpret_as_int()).to_byte()
  n[3] = (n[3].to_int() ^ ((ssrc >> 16) & 0xffU).reinterpret_as_int()).to_byte()
  n[4] = (n[4].to_int() ^ ((ssrc >> 8) & 0xffU).reinterpret_as_int()).to_byte()
  n[5] = (n[5].to_int() ^ (ssrc & 0xffU).reinterpret_as_int()).to_byte()
  for i = 0; i < 6; i = i + 1 {
    let shift = (5 - i) * 8
    n[6 + i] = (n[6 + i].to_int() ^ ((index >> shift) & 0xffUL).to_int()).to_byte()
  }
  Bytes::from_array(n)
}

///|
fn const_time_eq(a : BytesView, b : BytesView) -> Bool {
  if a.length() != b.length() {
    return false
  }
  let mut diff = 0
  for i = 0; i < a.length(); i = i + 1 {
    diff = diff | (a[i].to_int() ^ b[i].to_int())
  }
  diff == 0
}

///|
pub struct Context {
  profile : @moontls_srtp.Profile
  rtp_keys : SessionKeys
  rtcp_keys : SessionKeys
  tracker : @rtp.SeqTracker
  mut srtcp_index : UInt32
}

///|
pub fn Context::new(
  profile : @moontls_srtp.Profile,
  master_key : BytesView,
  master_salt : BytesView,
) -> Context raise SrtpError {
  {
    profile,
    rtp_keys: derive_session_keys(
      profile,
      master_key,
      master_salt,
      is_srtcp=false,
    ),
    rtcp_keys: derive_session_keys(
      profile,
      master_key,
      master_salt,
      is_srtcp=true,
    ),
    tracker: @rtp.SeqTracker::new(),
    srtcp_index: 0U,
  }
}

///|
pub fn Context::from_dtls_keys(
  profile : @moontls_srtp.Profile,
  keys : @moontls_srtp.Keys,
  is_sender_client : Bool,
) -> Context raise SrtpError {
  if is_sender_client {
    Context::new(profile, keys.client_key, keys.client_salt)
  } else {
    Context::new(profile, keys.server_key, keys.server_salt)
  }
}

///|
fn auth_tag_len(profile : @moontls_srtp.Profile) -> Int32 {
  match profile {
    Aes128CmSha1Tag80 | NullSha1Tag80 => 10
    Aes128CmSha1Tag32 | NullSha1Tag32 => 4
    Aead128Gcm | Aead256Gcm => 16
  }
}

///|
/// Protect an RTP packet into SRTP.
pub fn Context::protect_rtp(
  self : Context,
  rtp_packet : BytesView,
) -> Bytes raise SrtpError {
  let hlen = try @rtp.header_len(rtp_packet) catch {
    _ => raise InvalidPacket
  } noraise {
    h => h
  }
  let seq = (rtp_packet[2].to_int() << 8) | rtp_packet[3].to_int()
  let ssrc = get_u32_be(rtp_packet, 8)
  let idx = self.tracker.update(seq)
  let roc = (idx >> 16).to_uint()
  let header = rtp_packet[:hlen]
  let payload = rtp_packet[hlen:]

  match self.profile {
    Aead128Gcm | Aead256Gcm => {
      let cipher = try @aes.Cipher::new(self.rtp_keys.cipher_key) catch {
        _ => raise InvalidKey
      } noraise {
        c => c
      }
      let gcm = try @gcm.Gcm::new(cipher, tag=16) catch {
        _ => raise InvalidKey
      } noraise {
        g => g
      }
      let nonce = srtp_gcm_nonce(self.rtp_keys.cipher_salt, ssrc, idx)
      let sealed_pkt = gcm.seal(nonce~, plain=payload, aad=header)
      let out : Array[Byte] = []
      for b in header {
        out.push(b)
      }
      for b in sealed_pkt {
        out.push(b)
      }
      Bytes::from_array(out)
    }
    _ => {
      let enc_payload : Bytes = match self.profile {
        NullSha1Tag80 | NullSha1Tag32 => payload.to_owned()
        _ => {
          let cipher = try @aes.Cipher::new(self.rtp_keys.cipher_key) catch {
            _ => raise InvalidKey
          } noraise {
            c => c
          }
          let iv = srtp_ctr_iv(self.rtp_keys.cipher_salt, ssrc, idx)
          let ctr = try @mode.Ctr::new(cipher, iv) catch {
            _ => raise InvalidKey
          } noraise {
            c => c
          }
          ctr.apply(payload)
        }
      }
      let auth_input : Array[Byte] = []
      for b in header {
        auth_input.push(b)
      }
      for b in enc_payload {
        auth_input.push(b)
      }
      let roc_pos = auth_input.length()
      put_u32_be(auth_input, roc)
      let full_mac = @hmac.mac(
        self.rtp_keys.auth_key,
        Bytes::from_array(auth_input),
        () => @sha1.Hasher::new(),
      )
      let tlen = auth_tag_len(self.profile)
      let out : Array[Byte] = []
      for i = 0; i < roc_pos; i = i + 1 {
        out.push(auth_input[i])
      }
      for i = 0; i < tlen; i = i + 1 {
        out.push(full_mac[i])
      }
      Bytes::from_array(out)
    }
  }
}

///|
/// Verify and unprotect an SRTP packet back to plaintext RTP.
pub fn Context::unprotect_rtp(
  self : Context,
  srtp_packet : BytesView,
) -> Bytes raise SrtpError {
  let tlen = auth_tag_len(self.profile)
  if srtp_packet.length() < 12 + tlen {
    raise InvalidPacket
  }
  let hlen = try
    @rtp.header_len(srtp_packet[:srtp_packet.length() - tlen])
  catch {
    _ => raise InvalidPacket
  } noraise {
    h => h
  }
  let seq = (srtp_packet[2].to_int() << 8) | srtp_packet[3].to_int()
  let ssrc = get_u32_be(srtp_packet, 8)
  let idx = self.tracker.estimate_index(seq)
  let roc = (idx >> 16).to_uint()
  let header = srtp_packet[:hlen]

  match self.profile {
    Aead128Gcm | Aead256Gcm => {
      let cipher = try @aes.Cipher::new(self.rtp_keys.cipher_key) catch {
        _ => raise InvalidKey
      } noraise {
        c => c
      }
      let gcm = try @gcm.Gcm::new(cipher, tag=16) catch {
        _ => raise InvalidKey
      } noraise {
        g => g
      }
      let nonce = srtp_gcm_nonce(self.rtp_keys.cipher_salt, ssrc, idx)
      let plain = try
        gcm.open(nonce~, cipher=srtp_packet[hlen:], aad=header)
      catch {
        _ => raise AuthFailed
      } noraise {
        p => p
      }
      let _ = self.tracker.update(seq)
      let out : Array[Byte] = []
      for b in header {
        out.push(b)
      }
      for b in plain {
        out.push(b)
      }
      Bytes::from_array(out)
    }
    _ => {
      let body_end = srtp_packet.length() - tlen
      let auth_input : Array[Byte] = []
      for i = 0; i < body_end; i = i + 1 {
        auth_input.push(srtp_packet[i])
      }
      put_u32_be(auth_input, roc)
      let full_mac = @hmac.mac(
        self.rtp_keys.auth_key,
        Bytes::from_array(auth_input),
        () => @sha1.Hasher::new(),
      )
      if !const_time_eq(full_mac[:tlen], srtp_packet[body_end:]) {
        raise AuthFailed
      }
      let _ = self.tracker.update(seq)
      let enc_payload = srtp_packet[hlen:body_end]
      let plain_payload : Bytes = match self.profile {
        NullSha1Tag80 | NullSha1Tag32 => enc_payload.to_owned()
        _ => {
          let cipher = try @aes.Cipher::new(self.rtp_keys.cipher_key) catch {
            _ => raise InvalidKey
          } noraise {
            c => c
          }
          let iv = srtp_ctr_iv(self.rtp_keys.cipher_salt, ssrc, idx)
          let ctr = try @mode.Ctr::new(cipher, iv) catch {
            _ => raise InvalidKey
          } noraise {
            c => c
          }
          ctr.apply(enc_payload)
        }
      }
      let out : Array[Byte] = []
      for b in header {
        out.push(b)
      }
      for b in plain_payload {
        out.push(b)
      }
      Bytes::from_array(out)
    }
  }
}

///|
/// Protect an RTCP packet into SRTCP (always encrypted with E-flag set).
pub fn Context::protect_rtcp(
  self : Context,
  rtcp_packet : BytesView,
) -> Bytes raise SrtpError {
  if rtcp_packet.length() < 8 {
    raise InvalidPacket
  }
  let ssrc = get_u32_be(rtcp_packet, 4)
  let idx = self.srtcp_index
  self.srtcp_index += 1U
  let e_idx = 0x80000000U | idx
  let header = rtcp_packet[:8]
  let body = rtcp_packet[8:]

  match self.profile {
    Aead128Gcm | Aead256Gcm => {
      let cipher = try @aes.Cipher::new(self.rtcp_keys.cipher_key) catch {
        _ => raise InvalidKey
      } noraise {
        c => c
      }
      let gcm = try @gcm.Gcm::new(cipher, tag=16) catch {
        _ => raise InvalidKey
      } noraise {
        g => g
      }
      let nonce = srtp_gcm_nonce(
        self.rtcp_keys.cipher_salt,
        ssrc,
        idx.to_uint64(),
      )
      let aad : Array[Byte] = []
      for b in header {
        aad.push(b)
      }
      put_u32_be(aad, e_idx)
      let sealed_pkt = gcm.seal(nonce~, plain=body, aad=Bytes::from_array(aad))
      let out : Array[Byte] = []
      for b in header {
        out.push(b)
      }
      for b in sealed_pkt {
        out.push(b)
      }
      put_u32_be(out, e_idx)
      Bytes::from_array(out)
    }
    _ => {
      let enc_body : Bytes = match self.profile {
        NullSha1Tag80 | NullSha1Tag32 => body.to_owned()
        _ => {
          let cipher = try @aes.Cipher::new(self.rtcp_keys.cipher_key) catch {
            _ => raise InvalidKey
          } noraise {
            c => c
          }
          let iv = srtp_ctr_iv(
            self.rtcp_keys.cipher_salt,
            ssrc,
            idx.to_uint64(),
          )
          let ctr = try @mode.Ctr::new(cipher, iv) catch {
            _ => raise InvalidKey
          } noraise {
            c => c
          }
          ctr.apply(body)
        }
      }
      let out : Array[Byte] = []
      for b in header {
        out.push(b)
      }
      for b in enc_body {
        out.push(b)
      }
      put_u32_be(out, e_idx)
      let full_mac = @hmac.mac(
        self.rtcp_keys.auth_key,
        Bytes::from_array(out),
        () => @sha1.Hasher::new(),
      )
      let tlen = auth_tag_len(self.profile)
      for i = 0; i < tlen; i = i + 1 {
        out.push(full_mac[i])
      }
      Bytes::from_array(out)
    }
  }
}

///|
/// Verify and unprotect an SRTCP packet back to plaintext RTCP.
pub fn Context::unprotect_rtcp(
  self : Context,
  srtcp_packet : BytesView,
) -> Bytes raise SrtpError {
  let tlen = auth_tag_len(self.profile)
  if srtcp_packet.length() < 12 + tlen {
    raise InvalidPacket
  }
  let ssrc = get_u32_be(srtcp_packet, 4)
  match self.profile {
    Aead128Gcm | Aead256Gcm => {
      let idx_off = srtcp_packet.length() - 4
      let e_idx = get_u32_be(srtcp_packet, idx_off)
      let idx = e_idx & 0x7fffffffU
      let header = srtcp_packet[:8]
      let aad : Array[Byte] = []
      for b in header {
        aad.push(b)
      }
      put_u32_be(aad, e_idx)
      let cipher = try @aes.Cipher::new(self.rtcp_keys.cipher_key) catch {
        _ => raise InvalidKey
      } noraise {
        c => c
      }
      let gcm = try @gcm.Gcm::new(cipher, tag=16) catch {
        _ => raise InvalidKey
      } noraise {
        g => g
      }
      let nonce = srtp_gcm_nonce(
        self.rtcp_keys.cipher_salt,
        ssrc,
        idx.to_uint64(),
      )
      let plain = try
        gcm.open(
          nonce~,
          cipher=srtcp_packet[8:idx_off],
          aad=Bytes::from_array(aad),
        )
      catch {
        _ => raise AuthFailed
      } noraise {
        p => p
      }
      let out : Array[Byte] = []
      for b in header {
        out.push(b)
      }
      for b in plain {
        out.push(b)
      }
      Bytes::from_array(out)
    }
    _ => {
      let body_end = srtcp_packet.length() - tlen
      let full_mac = @hmac.mac(
        self.rtcp_keys.auth_key,
        srtcp_packet[:body_end],
        () => @sha1.Hasher::new(),
      )
      if !const_time_eq(full_mac[:tlen], srtcp_packet[body_end:]) {
        raise AuthFailed
      }
      let idx_off = body_end - 4
      let e_idx = get_u32_be(srtcp_packet, idx_off)
      let encrypted = (e_idx & 0x80000000U) != 0U
      let idx = e_idx & 0x7fffffffU
      let enc_body = srtcp_packet[8:idx_off]
      let plain_body : Bytes = if !encrypted {
        enc_body.to_owned()
      } else {
        match self.profile {
          NullSha1Tag80 | NullSha1Tag32 => enc_body.to_owned()
          _ => {
            let cipher = try @aes.Cipher::new(self.rtcp_keys.cipher_key) catch {
              _ => raise InvalidKey
            } noraise {
              c => c
            }
            let iv = srtp_ctr_iv(
              self.rtcp_keys.cipher_salt,
              ssrc,
              idx.to_uint64(),
            )
            let ctr = try @mode.Ctr::new(cipher, iv) catch {
              _ => raise InvalidKey
            } noraise {
              c => c
            }
            ctr.apply(enc_body)
          }
        }
      }
      let out : Array[Byte] = []
      for i = 0; i < 8; i = i + 1 {
        out.push(srtcp_packet[i])
      }
      for b in plain_body {
        out.push(b)
      }
      Bytes::from_array(out)
    }
  }
}