From 1dc8e50e22e8e3464f877b4ccc63e084c65ede7e Mon Sep 17 00:00:00 2001 From: Craig Edwards Date: Sat, 5 Oct 2024 12:28:39 +0000 Subject: [PATCH] refactor libdave naming --- src/dpp/dave/cipher_interface.cpp | 2 +- src/dpp/dave/cipher_interface.h | 2 +- src/dpp/dave/clock.h | 2 +- src/dpp/dave/codec_utils.cpp | 4 +- src/dpp/dave/common.h | 30 +++++------ src/dpp/dave/cryptor_manager.cpp | 20 +++---- src/dpp/dave/cryptor_manager.h | 28 +++++----- src/dpp/dave/decryptor.cpp | 74 +++++++++++++------------- src/dpp/dave/decryptor.h | 52 +++++++++--------- src/dpp/dave/encryptor.cpp | 12 ++--- src/dpp/dave/encryptor.h | 4 +- src/dpp/dave/frame_processors.cpp | 24 ++++----- src/dpp/dave/frame_processors.h | 6 +-- src/dpp/dave/key_ratchet.h | 2 +- src/dpp/dave/mls_key_ratchet.cpp | 2 +- src/dpp/dave/mls_key_ratchet.h | 2 +- src/dpp/dave/openssl_aead_cipher.cpp | 2 +- src/dpp/dave/openssl_aead_cipher.h | 2 +- src/dpp/dave/session.cpp | 22 ++++---- src/dpp/dave/session.h | 8 +-- src/dpp/voice/enabled/handle_frame.cpp | 4 +- src/dpp/voice/enabled/opus.cpp | 2 +- src/dpp/voice/enabled/read_ready.cpp | 3 +- 23 files changed, 153 insertions(+), 156 deletions(-) diff --git a/src/dpp/dave/cipher_interface.cpp b/src/dpp/dave/cipher_interface.cpp index d456449f53..2444cf4483 100755 --- a/src/dpp/dave/cipher_interface.cpp +++ b/src/dpp/dave/cipher_interface.cpp @@ -27,7 +27,7 @@ namespace dpp::dave { -std::unique_ptr create_cipher(const EncryptionKey& encryptionKey) +std::unique_ptr create_cipher(const encryption_key& encryptionKey) { auto cipher = std::make_unique(encryptionKey); return cipher->is_valid() ? std::move(cipher) : nullptr; diff --git a/src/dpp/dave/cipher_interface.h b/src/dpp/dave/cipher_interface.h index c998bd862d..725fb2a2e5 100755 --- a/src/dpp/dave/cipher_interface.h +++ b/src/dpp/dave/cipher_interface.h @@ -42,7 +42,7 @@ class cipher_interface { // NOLINT virtual bool decrypt(byte_view plaintextBufferOut, const_byte_view ciphertextBuffer, const_byte_view tagBuffer, const_byte_view nonceBuffer, const_byte_view additionalData) = 0; }; -std::unique_ptr create_cipher(const EncryptionKey& encryptionKey); +std::unique_ptr create_cipher(const encryption_key& encryptionKey); } // namespace dpp::dave diff --git a/src/dpp/dave/clock.h b/src/dpp/dave/clock.h index 1ed7331c47..13207b9bde 100755 --- a/src/dpp/dave/clock.h +++ b/src/dpp/dave/clock.h @@ -38,7 +38,7 @@ class clock_interface { virtual time_point now() const = 0; }; -class Clock : public clock_interface { +class clock : public clock_interface { public: time_point now() const override { return base_clock::now(); } }; diff --git a/src/dpp/dave/codec_utils.cpp b/src/dpp/dave/codec_utils.cpp index c547540e09..632f62ba3c 100755 --- a/src/dpp/dave/codec_utils.cpp +++ b/src/dpp/dave/codec_utils.cpp @@ -33,8 +33,8 @@ namespace dpp::dave::codec_utils { -UnencryptedFrameHeaderSize BytesCoveringH264PPS(const uint8_t* payload, - const uint64_t sizeRemaining) +unencrypted_frame_header_size BytesCoveringH264PPS(const uint8_t* payload, + const uint64_t sizeRemaining) { // the payload starts with three exponential golomb encoded values // (first_mb_in_slice, sps_id, pps_id) diff --git a/src/dpp/dave/common.h b/src/dpp/dave/common.h index 4a299cb5a8..35db54632f 100755 --- a/src/dpp/dave/common.h +++ b/src/dpp/dave/common.h @@ -40,12 +40,12 @@ namespace mlspp::bytes_ns { namespace dpp::dave { -using UnencryptedFrameHeaderSize = uint16_t; -using TruncatedSyncNonce = uint32_t; -using MagicMarker = uint16_t; -using EncryptionKey = ::mlspp::bytes_ns::bytes; -using TransitionId = uint16_t; -using SupplementalBytesSize = uint8_t; +using unencrypted_frame_header_size = uint16_t; +using truncated_sync_nonce = uint32_t; +using magic_marker = uint16_t; +using encryption_key = ::mlspp::bytes_ns::bytes; +using transition_id = uint16_t; +using supplemental_bytes_size = uint8_t; enum media_type : uint8_t { media_audio, media_video }; enum Codec : uint8_t { Unknown, Opus, VP8, VP9, H264, H265, AV1 }; @@ -59,25 +59,22 @@ struct ignored_t {}; // Map of ID-key pairs. // In ProcessCommit, this lists IDs whose keys have been added, changed, or removed; // an empty value value means a key was removed. -using RosterMap = std::map>; +using roster_map = std::map>; // Return type for functions producing RosterMap or hard or soft failures -using RosterVariant = std::variant; +using roster_variant = std::variant; -constexpr MagicMarker kMarkerBytes = 0xFAFA; +constexpr magic_marker kMarkerBytes = 0xFAFA; // Layout constants constexpr size_t kAesGcm128KeyBytes = 16; constexpr size_t kAesGcm128NonceBytes = 12; constexpr size_t kAesGcm128TruncatedSyncNonceBytes = 4; -constexpr size_t kAesGcm128TruncatedSyncNonceOffset = - kAesGcm128NonceBytes - kAesGcm128TruncatedSyncNonceBytes; +constexpr size_t kAesGcm128TruncatedSyncNonceOffset = kAesGcm128NonceBytes - kAesGcm128TruncatedSyncNonceBytes; constexpr size_t kAesGcm128TruncatedTagBytes = 8; constexpr size_t kRatchetGenerationBytes = 1; -constexpr size_t kRatchetGenerationShiftBits = - 8 * (kAesGcm128TruncatedSyncNonceBytes - kRatchetGenerationBytes); -constexpr size_t kSupplementalBytes = - kAesGcm128TruncatedTagBytes + sizeof(SupplementalBytesSize) + sizeof(MagicMarker); +constexpr size_t kRatchetGenerationShiftBits = 8 * (kAesGcm128TruncatedSyncNonceBytes - kRatchetGenerationBytes); +constexpr size_t kSupplementalBytes = kAesGcm128TruncatedTagBytes + sizeof(supplemental_bytes_size) + sizeof(magic_marker); constexpr size_t kTransformPaddingBytes = 64; // Timing constants @@ -94,8 +91,7 @@ constexpr auto kMaxFramesPerSecond = 50 + 2 * 60; // 50 audio frames + 2 * 60fps constexpr std::array kOpusSilencePacket = {0xF8, 0xFF, 0xFE}; // Utility routine for variant return types -template -inline std::optional GetOptional(V&& variant) +template inline std::optional get_optional(V&& variant) { if (auto map = std::get_if(&variant)) { if constexpr (std::is_rvalue_reference_v) { diff --git a/src/dpp/dave/cryptor_manager.cpp b/src/dpp/dave/cryptor_manager.cpp index f193c96d32..821bc24bf4 100755 --- a/src/dpp/dave/cryptor_manager.cpp +++ b/src/dpp/dave/cryptor_manager.cpp @@ -44,12 +44,12 @@ KeyGeneration compute_wrapped_generation(KeyGeneration oldest, KeyGeneration gen return factor * kGenerationWrap + generation; } -BigNonce compute_wrapped_big_nonce(KeyGeneration generation, TruncatedSyncNonce nonce) +big_nonce compute_wrapped_big_nonce(KeyGeneration generation, truncated_sync_nonce nonce) { // Remove the generation bits from the nonce auto maskedNonce = nonce & ((1 << kRatchetGenerationShiftBits) - 1); // Add the wrapped generation bits back in - return static_cast(generation) << kRatchetGenerationShiftBits | maskedNonce; + return static_cast(generation) << kRatchetGenerationShiftBits | maskedNonce; } aead_cipher_manager::aead_cipher_manager(const clock_interface& clock, std::unique_ptr keyRatchet) @@ -60,7 +60,7 @@ aead_cipher_manager::aead_cipher_manager(const clock_interface& clock, std::uniq { } -bool aead_cipher_manager::CanProcessNonce(KeyGeneration generation, TruncatedSyncNonce nonce) const +bool aead_cipher_manager::can_process_nonce(KeyGeneration generation, truncated_sync_nonce nonce) const { if (!newestProcessedNonce_) { return true; @@ -71,9 +71,9 @@ bool aead_cipher_manager::CanProcessNonce(KeyGeneration generation, TruncatedSyn std::find(missingNonces_.rbegin(), missingNonces_.rend(), bigNonce) != missingNonces_.rend(); } -cipher_interface* aead_cipher_manager::GetCryptor(KeyGeneration generation) +cipher_interface* aead_cipher_manager::get_cipher(KeyGeneration generation) { - CleanupExpiredCryptors(); + cleanup_expired_ciphers(); if (generation < oldestGeneration_) { DISCORD_LOG(LS_INFO) << "Received frame with old generation: " << generation @@ -102,7 +102,7 @@ cipher_interface* aead_cipher_manager::GetCryptor(KeyGeneration generation) auto it = cryptors_.find(generation); if (it == cryptors_.end()) { // We don't have a cryptor for this generation, create one - std::tie(it, std::ignore) = cryptors_.emplace(generation, MakeExpiringCryptor(generation)); + std::tie(it, std::ignore) = cryptors_.emplace(generation, make_expiring_cipher(generation)); } // Return a non-owning pointer to the cryptor @@ -110,7 +110,7 @@ cipher_interface* aead_cipher_manager::GetCryptor(KeyGeneration generation) return cryptor.get(); } -void aead_cipher_manager::ReportCryptorSuccess(KeyGeneration generation, TruncatedSyncNonce nonce) +void aead_cipher_manager::report_cipher_success(KeyGeneration generation, truncated_sync_nonce nonce) { auto bigNonce = compute_wrapped_big_nonce(generation, nonce); @@ -157,12 +157,12 @@ void aead_cipher_manager::ReportCryptorSuccess(KeyGeneration generation, Truncat } } -KeyGeneration aead_cipher_manager::ComputeWrappedGeneration(KeyGeneration generation) +KeyGeneration aead_cipher_manager::compute_wrapped_generation(KeyGeneration generation) { return ::dpp::dave::compute_wrapped_generation(oldestGeneration_, generation); } -aead_cipher_manager::ExpiringCryptor aead_cipher_manager::MakeExpiringCryptor(KeyGeneration generation) +aead_cipher_manager::expiring_cipher aead_cipher_manager::make_expiring_cipher(KeyGeneration generation) { // Get the new key from the ratchet auto encryptionKey = keyRatchet_->GetKey(generation); @@ -182,7 +182,7 @@ aead_cipher_manager::ExpiringCryptor aead_cipher_manager::MakeExpiringCryptor(Ke return {create_cipher(encryptionKey), expiryTime}; } -void aead_cipher_manager::CleanupExpiredCryptors() +void aead_cipher_manager::cleanup_expired_ciphers() { for (auto it = cryptors_.begin(); it != cryptors_.end();) { auto& [generation, cryptor] = *it; diff --git a/src/dpp/dave/cryptor_manager.h b/src/dpp/dave/cryptor_manager.h index d7bab473ea..4c950b852d 100755 --- a/src/dpp/dave/cryptor_manager.h +++ b/src/dpp/dave/cryptor_manager.h @@ -38,8 +38,8 @@ namespace dpp::dave { KeyGeneration compute_wrapped_generation(KeyGeneration oldest, KeyGeneration generation); -using BigNonce = uint64_t; -BigNonce compute_wrapped_big_nonce(KeyGeneration generation, TruncatedSyncNonce nonce); +using big_nonce = uint64_t; +big_nonce compute_wrapped_big_nonce(KeyGeneration generation, truncated_sync_nonce nonce); class aead_cipher_manager { public: @@ -47,35 +47,35 @@ class aead_cipher_manager { aead_cipher_manager(const clock_interface& clock, std::unique_ptr keyRatchet); - void UpdateExpiry(time_point expiry) { ratchetExpiry_ = expiry; } - bool IsExpired() const { return clock_.now() > ratchetExpiry_; } + void update_expiry(time_point expiry) { ratchetExpiry_ = expiry; } + bool is_expired() const { return clock_.now() > ratchetExpiry_; } - bool CanProcessNonce(KeyGeneration generation, TruncatedSyncNonce nonce) const; - KeyGeneration ComputeWrappedGeneration(KeyGeneration generation); + bool can_process_nonce(KeyGeneration generation, truncated_sync_nonce nonce) const; + KeyGeneration compute_wrapped_generation(KeyGeneration generation); - cipher_interface* GetCryptor(KeyGeneration generation); - void ReportCryptorSuccess(KeyGeneration generation, TruncatedSyncNonce nonce); + cipher_interface* get_cipher(KeyGeneration generation); + void report_cipher_success(KeyGeneration generation, truncated_sync_nonce nonce); private: - struct ExpiringCryptor { + struct expiring_cipher { std::unique_ptr cryptor; time_point expiry; }; - ExpiringCryptor MakeExpiringCryptor(KeyGeneration generation); - void CleanupExpiredCryptors(); + expiring_cipher make_expiring_cipher(KeyGeneration generation); + void cleanup_expired_ciphers(); const clock_interface& clock_; std::unique_ptr keyRatchet_; - std::unordered_map cryptors_; + std::unordered_map cryptors_; time_point ratchetCreation_; time_point ratchetExpiry_; KeyGeneration oldestGeneration_{0}; KeyGeneration newestGeneration_{0}; - std::optional newestProcessedNonce_; - std::deque missingNonces_; + std::optional newestProcessedNonce_; + std::deque missingNonces_; }; } // namespace dpp::dave diff --git a/src/dpp/dave/decryptor.cpp b/src/dpp/dave/decryptor.cpp index cc76e868c5..933b75dbe5 100755 --- a/src/dpp/dave/decryptor.cpp +++ b/src/dpp/dave/decryptor.cpp @@ -38,24 +38,24 @@ namespace dpp::dave { constexpr auto kStatsInterval = 10s; -void decryptor::TransitionToKeyRatchet(std::unique_ptr keyRatchet, - Duration transitionExpiry) +void decryptor::transition_to_key_ratchet(std::unique_ptr keyRatchet, + Duration transitionExpiry) { DISCORD_LOG(LS_INFO) << "Transitioning to new key ratchet: " << keyRatchet.get() << ", expiry: " << transitionExpiry.count(); // Update the expiry time for all existing cryptor managers - UpdateCryptorManagerExpiry(transitionExpiry); + update_cryptor_manager_expiry(transitionExpiry); if (keyRatchet) { cryptorManagers_.emplace_back(clock_, std::move(keyRatchet)); } } -void decryptor::TransitionToPassthroughMode(bool passthroughMode, Duration transitionExpiry) +void decryptor::transition_to_passthrough_mode(bool passthroughMode, Duration transitionExpiry) { if (passthroughMode) { - allowPassThroughUntil_ = TimePoint::max(); + allowPassThroughUntil_ = time_point::max(); } else { // Update the pass through mode expiry @@ -76,8 +76,8 @@ size_t decryptor::decrypt(media_type mediaType, auto start = clock_.now(); - auto localFrame = GetOrCreateFrameProcessor(); - ScopeExit cleanup([&] { ReturnFrameProcessor(std::move(localFrame)); }); + auto localFrame = get_or_create_frame_processor(); + ScopeExit cleanup([&] { return_frame_processor(std::move(localFrame)); }); // Skip decrypting for silence frames if (mediaType == media_audio && encryptedFrame.size() == kOpusSilencePacket.size() && @@ -90,7 +90,7 @@ size_t decryptor::decrypt(media_type mediaType, } // Remove any expired cryptor manager - CleanupExpiredCryptorManagers(); + cleanup_expired_cryptor_managers(); // Process the incoming frame // This will check whether it looks like a valid encrypted frame @@ -103,7 +103,7 @@ size_t decryptor::decrypt(media_type mediaType, if (encryptedFrame.data() != frame.data()) { std::memcpy(frame.data(), encryptedFrame.data(), encryptedFrame.size()); } - stats_[mediaType].passthroughCount++; + stats_[mediaType].passthroughs++; return encryptedFrame.size(); } @@ -111,7 +111,7 @@ size_t decryptor::decrypt(media_type mediaType, if (!localFrame->IsEncrypted()) { DISCORD_LOG(LS_INFO) << "decrypt failed, frame is not encrypted and pass through is disabled"; - stats_[mediaType].decryptFailureCount++; + stats_[mediaType].decrypt_failure++; return 0; } @@ -120,7 +120,7 @@ size_t decryptor::decrypt(media_type mediaType, bool success = false; for (auto it = cryptorManagers_.rbegin(); it != cryptorManagers_.rend(); ++it) { auto& cryptorManager = *it; - success = DecryptImpl(cryptorManager, mediaType, *localFrame, frame); + success = decrypt_impl(cryptorManager, mediaType, *localFrame, frame); if (success) { break; } @@ -128,11 +128,11 @@ size_t decryptor::decrypt(media_type mediaType, size_t bytesWritten = 0; if (success) { - stats_[mediaType].decryptSuccessCount++; + stats_[mediaType].decrypt_success++; bytesWritten = localFrame->ReconstructFrame(frame); } else { - stats_[mediaType].decryptFailureCount++; + stats_[mediaType].decrypt_failure++; DISCORD_LOG(LS_WARNING) << "decrypt failed, no valid cryptor found, type: " << (mediaType ? "video" : "audio") << ", encrypted frame size: " << encryptedFrame.size() @@ -144,21 +144,21 @@ size_t decryptor::decrypt(media_type mediaType, auto end = clock_.now(); if (end > lastStatsTime_ + kStatsInterval) { lastStatsTime_ = end; - DISCORD_LOG(LS_INFO) << "Decrypted audio: " << stats_[media_audio].decryptSuccessCount - << ", video: " << stats_[media_video].decryptSuccessCount - << ". Failed audio: " << stats_[media_audio].decryptFailureCount - << ", video: " << stats_[media_video].decryptFailureCount; + DISCORD_LOG(LS_INFO) << "Decrypted audio: " << stats_[media_audio].decrypt_success + << ", video: " << stats_[media_video].decrypt_success + << ". Failed audio: " << stats_[media_audio].decrypt_failure + << ", video: " << stats_[media_video].decrypt_failure; } - stats_[mediaType].decryptDuration += + stats_[mediaType].decrypt_duration += std::chrono::duration_cast(end - start).count(); return bytesWritten; } -bool decryptor::DecryptImpl(aead_cipher_manager& cryptorManager, - media_type mediaType, - InboundFrameProcessor& encryptedFrame, - array_view frame) +bool decryptor::decrypt_impl(aead_cipher_manager& cipher_manager, + media_type mediaType, + inbound_frame_processor& encryptedFrame, + array_view frame) { auto tag = encryptedFrame.GetTag(); auto truncatedNonce = encryptedFrame.GetTruncatedNonce(); @@ -176,65 +176,65 @@ bool decryptor::DecryptImpl(aead_cipher_manager& cryptorManager, auto nonceBufferView = make_array_view(nonceBuffer.data(), nonceBuffer.size()); auto generation = - cryptorManager.ComputeWrappedGeneration(truncatedNonce >> kRatchetGenerationShiftBits); + cipher_manager.compute_wrapped_generation(truncatedNonce >> kRatchetGenerationShiftBits); - if (!cryptorManager.CanProcessNonce(generation, truncatedNonce)) { + if (!cipher_manager.can_process_nonce(generation, truncatedNonce)) { DISCORD_LOG(LS_INFO) << "decrypt failed, cannot process nonce: " << truncatedNonce; return false; } // Get the cryptor for this generation - cipher_interface* cryptor = cryptorManager.GetCryptor(generation); + cipher_interface* cipher = cipher_manager.get_cipher(generation); - if (!cryptor) { + if (cipher == nullptr) { DISCORD_LOG(LS_INFO) << "decrypt failed, no cryptor found for generation: " << generation; return false; } // perform the decryption - bool success = cryptor->decrypt(plaintext, ciphertext, tag, nonceBufferView, authenticatedData); - stats_[mediaType].decryptAttempts++; + bool success = cipher->decrypt(plaintext, ciphertext, tag, nonceBufferView, authenticatedData); + stats_[mediaType].decrypt_attempts++; if (success) { - cryptorManager.ReportCryptorSuccess(generation, truncatedNonce); + cipher_manager.report_cipher_success(generation, truncatedNonce); } return success; } -size_t decryptor::GetMaxPlaintextByteSize(media_type mediaType, size_t encryptedFrameSize) +size_t decryptor::get_max_plaintext_byte_size(media_type mediaType, size_t encryptedFrameSize) { return encryptedFrameSize; } -void decryptor::UpdateCryptorManagerExpiry(Duration expiry) +void decryptor::update_cryptor_manager_expiry(Duration expiry) { auto maxExpiryTime = clock_.now() + expiry; for (auto& cryptorManager : cryptorManagers_) { - cryptorManager.UpdateExpiry(maxExpiryTime); + cryptorManager.update_expiry(maxExpiryTime); } } -void decryptor::CleanupExpiredCryptorManagers() +void decryptor::cleanup_expired_cryptor_managers() { - while (!cryptorManagers_.empty() && cryptorManagers_.front().IsExpired()) { + while (!cryptorManagers_.empty() && cryptorManagers_.front().is_expired()) { DISCORD_LOG(LS_INFO) << "Removing expired cryptor manager."; cryptorManagers_.pop_front(); } } -std::unique_ptr decryptor::GetOrCreateFrameProcessor() +std::unique_ptr decryptor::get_or_create_frame_processor() { std::lock_guard lock(frameProcessorsMutex_); if (frameProcessors_.empty()) { - return std::make_unique(); + return std::make_unique(); } auto frameProcessor = std::move(frameProcessors_.back()); frameProcessors_.pop_back(); return frameProcessor; } -void decryptor::ReturnFrameProcessor(std::unique_ptr frameProcessor) +void decryptor::return_frame_processor(std::unique_ptr frameProcessor) { std::lock_guard lock(frameProcessorsMutex_); frameProcessors_.push_back(std::move(frameProcessor)); diff --git a/src/dpp/dave/decryptor.h b/src/dpp/dave/decryptor.h index 0ae5a1b307..dab2ca3f1a 100755 --- a/src/dpp/dave/decryptor.h +++ b/src/dpp/dave/decryptor.h @@ -43,54 +43,54 @@ namespace dpp::dave { class IKeyRatchet; -struct DecryptorStats { - uint64_t passthroughCount = 0; - uint64_t decryptSuccessCount = 0; - uint64_t decryptFailureCount = 0; - uint64_t decryptDuration = 0; - uint64_t decryptAttempts = 0; +struct decryption_stats { + uint64_t passthroughs = 0; + uint64_t decrypt_success = 0; + uint64_t decrypt_failure = 0; + uint64_t decrypt_duration = 0; + uint64_t decrypt_attempts = 0; }; class decryptor { public: using Duration = std::chrono::seconds; - void TransitionToKeyRatchet(std::unique_ptr keyRatchet, - Duration transitionExpiry = kDefaultTransitionDuration); - void TransitionToPassthroughMode(bool passthroughMode, - Duration transitionExpiry = kDefaultTransitionDuration); + void transition_to_key_ratchet(std::unique_ptr keyRatchet, + Duration transitionExpiry = kDefaultTransitionDuration); + void transition_to_passthrough_mode(bool passthroughMode, + Duration transitionExpiry = kDefaultTransitionDuration); size_t decrypt(media_type mediaType, array_view encryptedFrame, array_view frame); - size_t GetMaxPlaintextByteSize(media_type mediaType, size_t encryptedFrameSize); - DecryptorStats GetStats(media_type mediaType) const { return stats_[mediaType]; } + size_t get_max_plaintext_byte_size(media_type mediaType, size_t encryptedFrameSize); + decryption_stats get_stats(media_type mediaType) const { return stats_[mediaType]; } private: - using TimePoint = clock_interface::time_point; + using time_point = clock_interface::time_point; - bool DecryptImpl(aead_cipher_manager& cryptor, - media_type mediaType, - InboundFrameProcessor& encryptedFrame, - array_view frame); + bool decrypt_impl(aead_cipher_manager& cipher_manager, + media_type mediaType, + inbound_frame_processor& encryptedFrame, + array_view frame); - void UpdateCryptorManagerExpiry(Duration expiry); - void CleanupExpiredCryptorManagers(); + void update_cryptor_manager_expiry(Duration expiry); + void cleanup_expired_cryptor_managers(); - std::unique_ptr GetOrCreateFrameProcessor(); - void ReturnFrameProcessor(std::unique_ptr frameProcessor); + std::unique_ptr get_or_create_frame_processor(); + void return_frame_processor(std::unique_ptr frameProcessor); - Clock clock_; + clock clock_; std::deque cryptorManagers_; std::mutex frameProcessorsMutex_; - std::vector> frameProcessors_; + std::vector> frameProcessors_; - TimePoint allowPassThroughUntil_{TimePoint::min()}; + time_point allowPassThroughUntil_{time_point::min()}; - TimePoint lastStatsTime_{TimePoint::min()}; - std::array stats_; + time_point lastStatsTime_{time_point::min()}; + std::array stats_; }; } // namespace dpp::dave diff --git a/src/dpp/dave/encryptor.cpp b/src/dpp/dave/encryptor.cpp index 91b030d88c..3981363b28 100755 --- a/src/dpp/dave/encryptor.cpp +++ b/src/dpp/dave/encryptor.cpp @@ -160,8 +160,8 @@ int encryptor::encrypt(media_type mediaType, auto unencryptedRangesBuffer = make_array_view(truncatedNonceBuffer.end(), unencryptedRangesSize); auto supplementalBytesBuffer = - make_array_view(unencryptedRangesBuffer.end(), sizeof(SupplementalBytesSize)); - auto markerBytesBuffer = make_array_view(supplementalBytesBuffer.end(), sizeof(MagicMarker)); + make_array_view(unencryptedRangesBuffer.end(), sizeof(supplemental_bytes_size)); + auto markerBytesBuffer = make_array_view(supplementalBytesBuffer.end(), sizeof(magic_marker)); // write the nonce auto res = WriteLeb128(truncatedNonce, truncatedNonceBuffer.begin()); @@ -181,15 +181,15 @@ int encryptor::encrypt(media_type mediaType, } // write the supplemental bytes size - SupplementalBytesSize supplementalBytes = + supplemental_bytes_size supplementalBytes = kSupplementalBytes + nonceSize + unencryptedRangesSize; - std::memcpy(supplementalBytesBuffer.data(), &supplementalBytes, sizeof(SupplementalBytesSize)); + std::memcpy(supplementalBytesBuffer.data(), &supplementalBytes, sizeof(supplemental_bytes_size)); // write the marker bytes, ends the frame - std::memcpy(markerBytesBuffer.data(), &kMarkerBytes, sizeof(MagicMarker)); + std::memcpy(markerBytesBuffer.data(), &kMarkerBytes, sizeof(magic_marker)); auto encryptedFrameBytes = reconstructedFrameSize + kAesGcm128TruncatedTagBytes + - nonceSize + unencryptedRangesSize + sizeof(SupplementalBytesSize) + sizeof(MagicMarker); + nonceSize + unencryptedRangesSize + sizeof(supplemental_bytes_size) + sizeof(magic_marker); if (codec_utils::validate_encrypted_frame( *frameProcessor, make_array_view(encryptedFrame.data(), encryptedFrameBytes))) { diff --git a/src/dpp/dave/encryptor.h b/src/dpp/dave/encryptor.h index 8f6f03b26e..3837f4e1ba 100755 --- a/src/dpp/dave/encryptor.h +++ b/src/dpp/dave/encryptor.h @@ -85,7 +85,7 @@ class encryptor { std::unique_ptr get_or_create_frame_processor(); void return_frame_processor(std::unique_ptr frameProcessor); - using cryptor_and_nonce = std::pair, TruncatedSyncNonce>; + using cryptor_and_nonce = std::pair, truncated_sync_nonce>; cryptor_and_nonce get_next_cryptor_and_nonce(); void update_current_protocol_version(ProtocolVersion version); @@ -96,7 +96,7 @@ class encryptor { std::unique_ptr keyRatchet_; std::shared_ptr cryptor_; KeyGeneration currentKeyGeneration_{0}; - TruncatedSyncNonce truncatedNonce_{0}; + truncated_sync_nonce truncatedNonce_{0}; std::mutex frameProcessorsMutex_; std::vector> frameProcessors_; diff --git a/src/dpp/dave/frame_processors.cpp b/src/dpp/dave/frame_processors.cpp index 8e05bf1708..e890c52698 100755 --- a/src/dpp/dave/frame_processors.cpp +++ b/src/dpp/dave/frame_processors.cpp @@ -183,40 +183,40 @@ size_t Reconstruct(Ranges ranges, return frameIndex; } -void InboundFrameProcessor::Clear() +void inbound_frame_processor::Clear() { isEncrypted_ = false; originalSize_ = 0; - truncatedNonce_ = std::numeric_limits::max(); + truncatedNonce_ = std::numeric_limits::max(); unencryptedRanges_.clear(); authenticated_.clear(); ciphertext_.clear(); plaintext_.clear(); } -void InboundFrameProcessor::ParseFrame(array_view frame) +void inbound_frame_processor::ParseFrame(array_view frame) { Clear(); constexpr auto MinSupplementalBytesSize = - kAesGcm128TruncatedTagBytes + sizeof(SupplementalBytesSize) + sizeof(MagicMarker); + kAesGcm128TruncatedTagBytes + sizeof(supplemental_bytes_size) + sizeof(magic_marker); if (frame.size() < MinSupplementalBytesSize) { DISCORD_LOG(LS_WARNING) << "Encrypted frame is too small to contain min supplemental bytes"; return; } // Check the frame ends with the magic marker - auto magicMarkerBuffer = frame.end() - sizeof(MagicMarker); - if (memcmp(magicMarkerBuffer, &kMarkerBytes, sizeof(MagicMarker)) != 0) { + auto magicMarkerBuffer = frame.end() - sizeof(magic_marker); + if (memcmp(magicMarkerBuffer, &kMarkerBytes, sizeof(magic_marker)) != 0) { return; } // Read the supplemental bytes size - SupplementalBytesSize supplementalBytesSize; - auto supplementalBytesSizeBuffer = magicMarkerBuffer - sizeof(SupplementalBytesSize); + supplemental_bytes_size supplementalBytesSize; + auto supplementalBytesSizeBuffer = magicMarkerBuffer - sizeof(supplemental_bytes_size); assert(frame.begin() <= supplementalBytesSizeBuffer && supplementalBytesSizeBuffer <= frame.end()); - memcpy(&supplementalBytesSize, supplementalBytesSizeBuffer, sizeof(SupplementalBytesSize)); + memcpy(&supplementalBytesSize, supplementalBytesSizeBuffer, sizeof(supplemental_bytes_size)); // Check the frame is large enough to contain the supplemental bytes if (frame.size() < supplementalBytesSize) { @@ -295,7 +295,7 @@ void InboundFrameProcessor::ParseFrame(array_view frame) isEncrypted_ = true; } -size_t InboundFrameProcessor::ReconstructFrame(array_view frame) const +size_t inbound_frame_processor::ReconstructFrame(array_view frame) const { if (!isEncrypted_) { DISCORD_LOG(LS_WARNING) << "Cannot reconstruct an invalid encrypted frame"; @@ -310,13 +310,13 @@ size_t InboundFrameProcessor::ReconstructFrame(array_view frame) const return Reconstruct(unencryptedRanges_, authenticated_, plaintext_, frame); } -void InboundFrameProcessor::AddAuthenticatedBytes(const uint8_t* data, size_t size) +void inbound_frame_processor::AddAuthenticatedBytes(const uint8_t* data, size_t size) { authenticated_.resize(authenticated_.size() + size); memcpy(authenticated_.data() + authenticated_.size() - size, data, size); } -void InboundFrameProcessor::AddCiphertextBytes(const uint8_t* data, size_t size) +void inbound_frame_processor::AddCiphertextBytes(const uint8_t* data, size_t size) { ciphertext_.resize(ciphertext_.size() + size); memcpy(ciphertext_.data() + ciphertext_.size() - size, data, size); diff --git a/src/dpp/dave/frame_processors.h b/src/dpp/dave/frame_processors.h index 7daf7481f8..d0fa8d829b 100755 --- a/src/dpp/dave/frame_processors.h +++ b/src/dpp/dave/frame_processors.h @@ -48,7 +48,7 @@ uint8_t DeserializeUnencryptedRanges(const uint8_t*& buffer, Ranges& unencryptedRanges); bool ValidateUnencryptedRanges(const Ranges& unencryptedRanges, size_t frameSize); -class InboundFrameProcessor { +class inbound_frame_processor { public: void ParseFrame(array_view frame); size_t ReconstructFrame(array_view frame) const; @@ -58,7 +58,7 @@ class InboundFrameProcessor { void Clear(); array_view GetTag() const { return tag_; } - TruncatedSyncNonce GetTruncatedNonce() const { return truncatedNonce_; } + truncated_sync_nonce GetTruncatedNonce() const { return truncatedNonce_; } array_view GetAuthenticatedData() const { return make_array_view(authenticated_.data(), authenticated_.size()); @@ -76,7 +76,7 @@ class InboundFrameProcessor { bool isEncrypted_{false}; size_t originalSize_{0}; array_view tag_; - TruncatedSyncNonce truncatedNonce_; + truncated_sync_nonce truncatedNonce_; Ranges unencryptedRanges_; std::vector authenticated_; std::vector ciphertext_; diff --git a/src/dpp/dave/key_ratchet.h b/src/dpp/dave/key_ratchet.h index 04262e88a1..1fd84d7d1a 100755 --- a/src/dpp/dave/key_ratchet.h +++ b/src/dpp/dave/key_ratchet.h @@ -34,7 +34,7 @@ using KeyGeneration = uint32_t; class IKeyRatchet { public: virtual ~IKeyRatchet() noexcept = default; - virtual EncryptionKey GetKey(KeyGeneration generation) noexcept = 0; + virtual encryption_key GetKey(KeyGeneration generation) noexcept = 0; virtual void DeleteKey(KeyGeneration generation) noexcept = 0; }; diff --git a/src/dpp/dave/mls_key_ratchet.cpp b/src/dpp/dave/mls_key_ratchet.cpp index 9ef5c4a8b9..3900b7e1eb 100755 --- a/src/dpp/dave/mls_key_ratchet.cpp +++ b/src/dpp/dave/mls_key_ratchet.cpp @@ -37,7 +37,7 @@ MlsKeyRatchet::MlsKeyRatchet(::mlspp::CipherSuite suite, bytes baseSecret) noexc MlsKeyRatchet::~MlsKeyRatchet() noexcept = default; -EncryptionKey MlsKeyRatchet::GetKey(KeyGeneration generation) noexcept +encryption_key MlsKeyRatchet::GetKey(KeyGeneration generation) noexcept { DISCORD_LOG(LS_INFO) << "Retrieving key for generation " << generation << " from HashRatchet"; diff --git a/src/dpp/dave/mls_key_ratchet.h b/src/dpp/dave/mls_key_ratchet.h index 84d583a728..74d8b4bde4 100755 --- a/src/dpp/dave/mls_key_ratchet.h +++ b/src/dpp/dave/mls_key_ratchet.h @@ -34,7 +34,7 @@ class MlsKeyRatchet : public IKeyRatchet { MlsKeyRatchet(::mlspp::CipherSuite suite, bytes baseSecret) noexcept; ~MlsKeyRatchet() noexcept override; - EncryptionKey GetKey(KeyGeneration generation) noexcept override; + encryption_key GetKey(KeyGeneration generation) noexcept override; void DeleteKey(KeyGeneration generation) noexcept override; private: diff --git a/src/dpp/dave/openssl_aead_cipher.cpp b/src/dpp/dave/openssl_aead_cipher.cpp index 0e32b3681f..94f921fb5f 100755 --- a/src/dpp/dave/openssl_aead_cipher.cpp +++ b/src/dpp/dave/openssl_aead_cipher.cpp @@ -39,7 +39,7 @@ void PrintSSLErrors() nullptr); } -openssl_aead_cipher::openssl_aead_cipher(const EncryptionKey& encryptionKey) : +openssl_aead_cipher::openssl_aead_cipher(const encryption_key& encryptionKey) : cipherCtx_(EVP_CIPHER_CTX_new()), key_(std::vector(encryptionKey.data(), encryptionKey.data() + encryptionKey.size())) { } diff --git a/src/dpp/dave/openssl_aead_cipher.h b/src/dpp/dave/openssl_aead_cipher.h index 27193c608b..9bf077d555 100755 --- a/src/dpp/dave/openssl_aead_cipher.h +++ b/src/dpp/dave/openssl_aead_cipher.h @@ -30,7 +30,7 @@ namespace dpp::dave { class openssl_aead_cipher : public cipher_interface { // NOLINT public: - openssl_aead_cipher(const EncryptionKey& encryptionKey); + openssl_aead_cipher(const encryption_key& encryptionKey); ~openssl_aead_cipher() override; diff --git a/src/dpp/dave/session.cpp b/src/dpp/dave/session.cpp index 5dd0f08924..a26896acdb 100755 --- a/src/dpp/dave/session.cpp +++ b/src/dpp/dave/session.cpp @@ -351,7 +351,7 @@ bool Session::CanProcessCommit(const ::mlspp::MLSMessage& commit) noexcept return true; } -RosterVariant Session::ProcessCommit(std::vector commit) noexcept +roster_variant Session::ProcessCommit(std::vector commit) noexcept try { DISCORD_LOG(LS_INFO) << "Processing commit"; DISCORD_LOG(LS_INFO) << "Commit: " << ::mlspp::bytes_ns::bytes(commit); @@ -380,7 +380,7 @@ try { DISCORD_LOG(LS_INFO) << "Successfully processed MLS commit, updating state; our leaf index is " << newState->index().val << "; current epoch is " << newState->epoch(); - RosterMap ret = ReplaceState(std::make_unique<::mlspp::State>(std::move(*newState))); + roster_map ret = ReplaceState(std::make_unique<::mlspp::State>(std::move(*newState))); // reset the outbound cached group since we handled the commit for this epoch outboundCachedGroupState_.reset(); @@ -395,7 +395,7 @@ catch (const std::exception& e) { return failed_t{}; } -std::optional Session::ProcessWelcome( +std::optional Session::ProcessWelcome( std::vector welcome, std::set const& recognizedUserIDs) noexcept try { @@ -440,7 +440,7 @@ try { << newState->index().val << "; current epoch is " << newState->epoch(); // make the verified state our new (and only) state - RosterMap ret = ReplaceState(std::move(newState)); + roster_map ret = ReplaceState(std::move(newState)); // clear out any pending state for creating/joining a group ClearPendingState(); @@ -453,9 +453,9 @@ catch (const std::exception& e) { return std::nullopt; } -RosterMap Session::ReplaceState(std::unique_ptr<::mlspp::State>&& state) +roster_map Session::ReplaceState(std::unique_ptr<::mlspp::State>&& state) { - RosterMap newRoster; + roster_map newRoster; for (const ::mlspp::LeafNode& node : state->roster()) { if (node.credential.type() != ::mlspp::CredentialType::basic) { continue; @@ -466,7 +466,7 @@ RosterMap Session::ReplaceState(std::unique_ptr<::mlspp::State>&& state) newRoster[FromBigEndianBytes(cred.identity)] = node.signature_key.data.as_vec(); } - RosterMap changeMap; + roster_map changeMap; std::set_difference(newRoster.begin(), newRoster.end(), @@ -475,11 +475,11 @@ RosterMap Session::ReplaceState(std::unique_ptr<::mlspp::State>&& state) std::inserter(changeMap, changeMap.end())); struct MissingItemWrapper { - RosterMap& changeMap_; + roster_map& changeMap_; - using iterator = RosterMap::iterator; - using const_iterator = RosterMap::const_iterator; - using value_type = RosterMap::value_type; + using iterator = roster_map::iterator; + using const_iterator = roster_map::const_iterator; + using value_type = roster_map::value_type; iterator insert(const_iterator it, const value_type& value) { diff --git a/src/dpp/dave/session.h b/src/dpp/dave/session.h index 542ccfc076..32c7410ac5 100755 --- a/src/dpp/dave/session.h +++ b/src/dpp/dave/session.h @@ -80,9 +80,9 @@ class Session { std::vector proposals, std::set const& recognizedUserIDs) noexcept; - RosterVariant ProcessCommit(std::vector commit) noexcept; + roster_variant ProcessCommit(std::vector commit) noexcept; - std::optional ProcessWelcome( + std::optional ProcessWelcome( std::vector welcome, std::set const& recognizedUserIDs) noexcept; @@ -115,7 +115,7 @@ class Session { bool CanProcessCommit(const ::mlspp::MLSMessage& commit) noexcept; - RosterMap ReplaceState(std::unique_ptr<::mlspp::State>&& state); + roster_map ReplaceState(std::unique_ptr<::mlspp::State>&& state); void ClearPendingState(); @@ -142,7 +142,7 @@ class Session { std::unique_ptr<::mlspp::State> outboundCachedGroupState_; std::unique_ptr<::mlspp::State> currentState_; - RosterMap roster_; + roster_map roster_; std::unique_ptr<::mlspp::State> stateWithProposals_; std::list proposalQueue_; diff --git a/src/dpp/voice/enabled/handle_frame.cpp b/src/dpp/voice/enabled/handle_frame.cpp index 1e35e12e41..720dd83dc3 100644 --- a/src/dpp/voice/enabled/handle_frame.cpp +++ b/src/dpp/voice/enabled/handle_frame.cpp @@ -70,7 +70,7 @@ bool discord_voice_client::handle_frame(const std::string &data, ws_opcode opcod log(ll_debug, "Setting decryptor key ratchet for user: " + user + ", protocol version: " + std::to_string(mls_state->dave_session->GetProtocolVersion())); dpp::snowflake u{user}; mls_state->decryptors.emplace(u, std::make_unique()); - mls_state->decryptors.find(u)->second->TransitionToKeyRatchet(mls_state->dave_session->GetKeyRatchet(user)); + mls_state->decryptors.find(u)->second->transition_to_key_ratchet(mls_state->dave_session->GetKeyRatchet(user)); } mls_state->encryptor->set_key_ratchet(mls_state->dave_session->GetKeyRatchet(creator->me.id.str())); @@ -100,7 +100,7 @@ bool discord_voice_client::handle_frame(const std::string &data, ws_opcode opcod log(ll_debug, "Setting decryptor key ratchet for user: " + user + ", protocol version: " + std::to_string(mls_state->dave_session->GetProtocolVersion())); dpp::snowflake u{user}; mls_state->decryptors.emplace(u, std::make_unique()); - mls_state->decryptors.find(u)->second->TransitionToKeyRatchet(mls_state->dave_session->GetKeyRatchet(user)); + mls_state->decryptors.find(u)->second->transition_to_key_ratchet(mls_state->dave_session->GetKeyRatchet(user)); } mls_state->encryptor->set_key_ratchet(mls_state->dave_session->GetKeyRatchet(creator->me.id.str())); } diff --git a/src/dpp/voice/enabled/opus.cpp b/src/dpp/voice/enabled/opus.cpp index 40ae142dbc..41a8e19064 100644 --- a/src/dpp/voice/enabled/opus.cpp +++ b/src/dpp/voice/enabled/opus.cpp @@ -91,7 +91,7 @@ discord_voice_client& discord_voice_client::send_audio_opus(uint8_t* opus_packet if (this->is_end_to_end_encrypted()) { - std::vector encrypted_buffer(encoded_audio.size() * 2); + std::vector encrypted_buffer(this->mls_state->encryptor->get_max_ciphertext_byte_size(dave::media_type::media_audio, length)); size_t out_size{0}; auto result = this->mls_state->encryptor->encrypt( diff --git a/src/dpp/voice/enabled/read_ready.cpp b/src/dpp/voice/enabled/read_ready.cpp index 72eaff52b7..22d0743bb5 100644 --- a/src/dpp/voice/enabled/read_ready.cpp +++ b/src/dpp/voice/enabled/read_ready.cpp @@ -146,10 +146,11 @@ void discord_voice_client::read_ready() /** * If DAVE is enabled, use the user's ratchet to decrypt the OPUS audio data */ - std::vector frame(opus_packet_len * 2); + std::vector frame; if (is_end_to_end_encrypted()) { auto decryptor = mls_state->decryptors.find(vp.vr->user_id); if (decryptor != mls_state->decryptors.end()) { + frame.resize(decryptor->second->get_max_plaintext_byte_size(dave::media_type::media_audio, opus_packet_len)); size_t enc_len = decryptor->second->decrypt( dave::media_type::media_audio, dave::make_array_view(opus_packet, opus_packet_len),