From df0d358ad09abae56a87b9f4f47eaec279d2b0b6 Mon Sep 17 00:00:00 2001
From: Nicolas Werner <nicolas.werner@hotmail.de>
Date: Tue, 20 Apr 2021 14:27:40 +0200
Subject: [PATCH] Allow exporting sessions at a specific index

---
 include/mtxclient/crypto/client.hpp | 6 ++++--
 lib/crypto/client.cpp               | 7 ++++---
 tests/e2ee.cpp                      | 2 +-
 3 files changed, 9 insertions(+), 6 deletions(-)

diff --git a/include/mtxclient/crypto/client.hpp b/include/mtxclient/crypto/client.hpp
index 0d62329ab..5ca5ec1b3 100644
--- a/include/mtxclient/crypto/client.hpp
+++ b/include/mtxclient/crypto/client.hpp
@@ -347,9 +347,11 @@ session_id(OlmOutboundGroupSession *s);
 std::string
 session_key(OlmOutboundGroupSession *s);
 
-//! Retrieve the session key from an *inbound* megolm session.
+// @brief Retrieve the session key from an *inbound* megolm session with a specific minimum index.
+//
+// Use -1 to use the smallest index possible
 std::string
-export_session(OlmInboundGroupSession *s);
+export_session(OlmInboundGroupSession *s, uint32_t at_index);
 
 //! Create an *inbound* megolm session from an exported session key.
 InboundGroupSessionPtr
diff --git a/lib/crypto/client.cpp b/lib/crypto/client.cpp
index 73e3ea78d..95cfb35e4 100644
--- a/lib/crypto/client.cpp
+++ b/lib/crypto/client.cpp
@@ -659,10 +659,11 @@ mtx::crypto::session_key(OlmOutboundGroupSession *s)
 }
 
 std::string
-mtx::crypto::export_session(OlmInboundGroupSession *s)
+mtx::crypto::export_session(OlmInboundGroupSession *s, uint32_t at_index)
 {
-        const size_t len     = olm_export_inbound_group_session_length(s);
-        const uint32_t index = olm_inbound_group_session_first_known_index(s);
+        const size_t len = olm_export_inbound_group_session_length(s);
+        const uint32_t index =
+          at_index == uint32_t(-1) ? olm_inbound_group_session_first_known_index(s) : at_index;
 
         auto session_key = create_buffer(len);
         const std::size_t ret =
diff --git a/tests/e2ee.cpp b/tests/e2ee.cpp
index 20b0e3399..fd8a424c7 100644
--- a/tests/e2ee.cpp
+++ b/tests/e2ee.cpp
@@ -1270,7 +1270,7 @@ TEST(ExportSessions, InboundMegolmSessions)
 
         // ==================== SESSION IMPORT/EXPORT =================== //
 
-        auto exported_session_key     = export_session(inbound_megolm_session.get());
+        auto exported_session_key     = export_session(inbound_megolm_session.get(), -1);
         auto restored_inbound_session = import_session(exported_session_key);
 
         // Decrypt message again.
-- 
GitLab