Remove CryptoAsyncHelper and use only coroutine

This commit is contained in:
Benoit Marty 2019-06-14 13:43:37 +02:00
parent 907a1d1a4b
commit 659ba34fb3
12 changed files with 530 additions and 541 deletions

View File

@ -1,61 +0,0 @@
/*
*
* * Copyright 2019 New Vector Ltd
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/

package im.vector.matrix.android.internal.crypto

import android.os.Handler
import android.os.HandlerThread
import android.os.Looper

private const val THREAD_CRYPTO_NAME = "Crypto_Thread"

// TODO Remove and replace by Task
internal object CryptoAsyncHelper {

private var uiHandler: Handler? = null
private var cryptoBackgroundHandler: Handler? = null

fun getUiHandler(): Handler {
return uiHandler
?: Handler(Looper.getMainLooper())
.also { uiHandler = it }
}


fun getDecryptBackgroundHandler(): Handler {
return getCryptoBackgroundHandler()
}

fun getEncryptBackgroundHandler(): Handler {
return getCryptoBackgroundHandler()
}

private fun getCryptoBackgroundHandler(): Handler {
return cryptoBackgroundHandler
?: createCryptoBackgroundHandler()
.also { cryptoBackgroundHandler = it }
}

private fun createCryptoBackgroundHandler(): Handler {
val handlerThread = HandlerThread(THREAD_CRYPTO_NAME)
handlerThread.start()
return Handler(handlerThread.looper)
}


}

View File

@ -19,6 +19,8 @@
package im.vector.matrix.android.internal.crypto package im.vector.matrix.android.internal.crypto


import android.content.Context import android.content.Context
import android.os.Handler
import android.os.Looper
import android.text.TextUtils import android.text.TextUtils
import arrow.core.Try import arrow.core.Try
import com.zhuinden.monarchy.Monarchy import com.zhuinden.monarchy.Monarchy
@ -138,6 +140,8 @@ internal class CryptoManager(
private val taskExecutor: TaskExecutor private val taskExecutor: TaskExecutor
) : CryptoService { ) : CryptoService {


private val uiHandler = Handler(Looper.getMainLooper())

// MXEncrypting instance for each room. // MXEncrypting instance for each room.
private val roomEncryptors: MutableMap<String, IMXEncrypting> = HashMap() private val roomEncryptors: MutableMap<String, IMXEncrypting> = HashMap()
private val isStarting = AtomicBoolean(false) private val isStarting = AtomicBoolean(false)
@ -825,18 +829,13 @@ internal class CryptoManager(
password: String, password: String,
progressListener: ProgressListener?, progressListener: ProgressListener?,
callback: MatrixCallback<ImportRoomKeysResult>) { callback: MatrixCallback<ImportRoomKeysResult>) {
// TODO Use coroutines GlobalScope.launch(coroutineDispatchers.main) {
withContext(coroutineDispatchers.crypto) {
Try {
Timber.v("## importRoomKeys starts") Timber.v("## importRoomKeys starts")


val t0 = System.currentTimeMillis() val t0 = System.currentTimeMillis()
val roomKeys: String val roomKeys: String = MXMegolmExportEncryption.decryptMegolmKeyFile(roomKeysAsArray, password)

try {
roomKeys = MXMegolmExportEncryption.decryptMegolmKeyFile(roomKeysAsArray, password)
} catch (e: Exception) {
callback.onFailure(e)
return
}


val importedSessions: List<MegolmSessionData> val importedSessions: List<MegolmSessionData>


@ -844,22 +843,19 @@ internal class CryptoManager(


Timber.v("## importRoomKeys : decryptMegolmKeyFile done in " + (t1 - t0) + " ms") Timber.v("## importRoomKeys : decryptMegolmKeyFile done in " + (t1 - t0) + " ms")


try {
val list = MoshiProvider.providesMoshi() val list = MoshiProvider.providesMoshi()
.adapter(List::class.java) .adapter(List::class.java)
.fromJson(roomKeys) .fromJson(roomKeys)
importedSessions = list as List<MegolmSessionData> importedSessions = list as List<MegolmSessionData>
} catch (e: Exception) {
Timber.e(e, "## importRoomKeys failed")
callback.onFailure(e)
return
}


val t2 = System.currentTimeMillis() val t2 = System.currentTimeMillis()


Timber.v("## importRoomKeys : JSON parsing " + (t2 - t1) + " ms") Timber.v("## importRoomKeys : JSON parsing " + (t2 - t1) + " ms")


megolmSessionDataImporter.handle(importedSessions, true, progressListener, callback) megolmSessionDataImporter.handle(importedSessions, true, uiHandler, progressListener)
}
}.foldToCallback(callback)
}
} }


/** /**

View File

@ -277,6 +277,7 @@ internal class CryptoModule {
// Task // Task
get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(),
// Task executor // Task executor
get(),
get()) get())
} }



View File

@ -16,9 +16,9 @@


package im.vector.matrix.android.internal.crypto.actions package im.vector.matrix.android.internal.crypto.actions


import im.vector.matrix.android.api.MatrixCallback import android.os.Handler
import androidx.annotation.WorkerThread
import im.vector.matrix.android.api.listeners.ProgressListener import im.vector.matrix.android.api.listeners.ProgressListener
import im.vector.matrix.android.internal.crypto.CryptoAsyncHelper
import im.vector.matrix.android.internal.crypto.MXOlmDevice import im.vector.matrix.android.internal.crypto.MXOlmDevice
import im.vector.matrix.android.internal.crypto.MegolmSessionData import im.vector.matrix.android.internal.crypto.MegolmSessionData
import im.vector.matrix.android.internal.crypto.OutgoingRoomKeyRequestManager import im.vector.matrix.android.internal.crypto.OutgoingRoomKeyRequestManager
@ -35,34 +35,32 @@ internal class MegolmSessionDataImporter(private val olmDevice: MXOlmDevice,


/** /**
* Import a list of megolm session keys. * Import a list of megolm session keys.
* Must be call on the crypto coroutine thread
* *
* @param megolmSessionsData megolm sessions. * @param megolmSessionsData megolm sessions.
* @param backUpKeys true to back up them to the homeserver. * @param backUpKeys true to back up them to the homeserver.
* @param progressListener the progress listener * @param progressListener the progress listener
* @param callback * @return import room keys result
*/ */
@WorkerThread
fun handle(megolmSessionsData: List<MegolmSessionData>, fun handle(megolmSessionsData: List<MegolmSessionData>,
fromBackup: Boolean, fromBackup: Boolean,
progressListener: ProgressListener?, uiHandler: Handler,
callback: MatrixCallback<ImportRoomKeysResult>) { progressListener: ProgressListener?): ImportRoomKeysResult {
val t0 = System.currentTimeMillis() val t0 = System.currentTimeMillis()


val totalNumbersOfKeys = megolmSessionsData.size val totalNumbersOfKeys = megolmSessionsData.size
var cpt = 0
var lastProgress = 0 var lastProgress = 0
var totalNumbersOfImportedKeys = 0 var totalNumbersOfImportedKeys = 0


if (progressListener != null) { if (progressListener != null) {
CryptoAsyncHelper.getUiHandler().post { uiHandler.post {
progressListener.onProgress(0, 100) progressListener.onProgress(0, 100)
} }
} }
val olmInboundGroupSessionWrappers = olmDevice.importInboundGroupSessions(megolmSessionsData) val olmInboundGroupSessionWrappers = olmDevice.importInboundGroupSessions(megolmSessionsData)


for (megolmSessionData in megolmSessionsData) { megolmSessionsData.forEachIndexed { cpt, megolmSessionData ->
cpt++


val decrypting = roomDecryptorProvider.getOrCreateRoomDecryptor(megolmSessionData.roomId, megolmSessionData.algorithm) val decrypting = roomDecryptorProvider.getOrCreateRoomDecryptor(megolmSessionData.roomId, megolmSessionData.algorithm)


if (null != decrypting) { if (null != decrypting) {
@ -90,7 +88,7 @@ internal class MegolmSessionDataImporter(private val olmDevice: MXOlmDevice,
} }


if (progressListener != null) { if (progressListener != null) {
CryptoAsyncHelper.getUiHandler().post { uiHandler.post {
val progress = 100 * cpt / totalNumbersOfKeys val progress = 100 * cpt / totalNumbersOfKeys


if (lastProgress != progress) { if (lastProgress != progress) {
@ -111,10 +109,6 @@ internal class MegolmSessionDataImporter(private val olmDevice: MXOlmDevice,


Timber.v("## importMegolmSessionsData : sessions import " + (t1 - t0) + " ms (" + megolmSessionsData.size + " sessions)") Timber.v("## importMegolmSessionsData : sessions import " + (t1 - t0) + " ms (" + megolmSessionsData.size + " sessions)")


val finalTotalNumbersOfImportedKeys = totalNumbersOfImportedKeys return ImportRoomKeysResult(totalNumbersOfKeys, totalNumbersOfImportedKeys)

CryptoAsyncHelper.getUiHandler().post {
callback.onSuccess(ImportRoomKeysResult(totalNumbersOfKeys, finalTotalNumbersOfImportedKeys))
}
} }
} }

View File

@ -31,7 +31,10 @@ import im.vector.matrix.android.api.listeners.StepProgressListener
import im.vector.matrix.android.api.session.crypto.keysbackup.KeysBackupService import im.vector.matrix.android.api.session.crypto.keysbackup.KeysBackupService
import im.vector.matrix.android.api.session.crypto.keysbackup.KeysBackupState import im.vector.matrix.android.api.session.crypto.keysbackup.KeysBackupState
import im.vector.matrix.android.api.session.crypto.keysbackup.KeysBackupStateListener import im.vector.matrix.android.api.session.crypto.keysbackup.KeysBackupStateListener
import im.vector.matrix.android.internal.crypto.* import im.vector.matrix.android.internal.crypto.MXCRYPTO_ALGORITHM_MEGOLM_BACKUP
import im.vector.matrix.android.internal.crypto.MXOlmDevice
import im.vector.matrix.android.internal.crypto.MegolmSessionData
import im.vector.matrix.android.internal.crypto.ObjectSigner
import im.vector.matrix.android.internal.crypto.actions.MegolmSessionDataImporter import im.vector.matrix.android.internal.crypto.actions.MegolmSessionDataImporter
import im.vector.matrix.android.internal.crypto.keysbackup.model.KeysBackupVersionTrust import im.vector.matrix.android.internal.crypto.keysbackup.model.KeysBackupVersionTrust
import im.vector.matrix.android.internal.crypto.keysbackup.model.KeysBackupVersionTrustSignature import im.vector.matrix.android.internal.crypto.keysbackup.model.KeysBackupVersionTrustSignature
@ -47,10 +50,15 @@ import im.vector.matrix.android.internal.crypto.model.OlmInboundGroupSessionWrap
import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore
import im.vector.matrix.android.internal.crypto.store.db.model.KeysBackupDataEntity import im.vector.matrix.android.internal.crypto.store.db.model.KeysBackupDataEntity
import im.vector.matrix.android.internal.di.MoshiProvider import im.vector.matrix.android.internal.di.MoshiProvider
import im.vector.matrix.android.internal.extensions.foldToCallback
import im.vector.matrix.android.internal.task.Task import im.vector.matrix.android.internal.task.Task
import im.vector.matrix.android.internal.task.TaskExecutor import im.vector.matrix.android.internal.task.TaskExecutor
import im.vector.matrix.android.internal.task.TaskThread import im.vector.matrix.android.internal.task.TaskThread
import im.vector.matrix.android.internal.task.configureWith import im.vector.matrix.android.internal.task.configureWith
import im.vector.matrix.android.internal.util.MatrixCoroutineDispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.matrix.olm.OlmException import org.matrix.olm.OlmException
import org.matrix.olm.OlmPkDecryption import org.matrix.olm.OlmPkDecryption
import org.matrix.olm.OlmPkEncryption import org.matrix.olm.OlmPkEncryption
@ -87,7 +95,8 @@ internal class KeysBackup(
private val storeSessionDataTask: StoreSessionsDataTask, private val storeSessionDataTask: StoreSessionsDataTask,
private val updateKeysBackupVersionTask: UpdateKeysBackupVersionTask, private val updateKeysBackupVersionTask: UpdateKeysBackupVersionTask,
// Task executor // Task executor
private val taskExecutor: TaskExecutor private val taskExecutor: TaskExecutor,
private val coroutineDispatchers: MatrixCoroutineDispatchers
) : KeysBackupService { ) : KeysBackupService {


private val uiHandler = Handler(Looper.getMainLooper()) private val uiHandler = Handler(Looper.getMainLooper())
@ -130,8 +139,9 @@ internal class KeysBackup(
override fun prepareKeysBackupVersion(password: String?, override fun prepareKeysBackupVersion(password: String?,
progressListener: ProgressListener?, progressListener: ProgressListener?,
callback: MatrixCallback<MegolmBackupCreationInfo>) { callback: MatrixCallback<MegolmBackupCreationInfo>) {
CryptoAsyncHelper.getDecryptBackgroundHandler().post { GlobalScope.launch(coroutineDispatchers.main) {
try { withContext(coroutineDispatchers.crypto) {
Try {
val olmPkDecryption = OlmPkDecryption() val olmPkDecryption = OlmPkDecryption()
val megolmBackupAuthData = MegolmBackupAuthData() val megolmBackupAuthData = MegolmBackupAuthData()


@ -173,12 +183,9 @@ internal class KeysBackup(
megolmBackupCreationInfo.authData = megolmBackupAuthData megolmBackupCreationInfo.authData = megolmBackupAuthData
megolmBackupCreationInfo.recoveryKey = computeRecoveryKey(olmPkDecryption.privateKey()) megolmBackupCreationInfo.recoveryKey = computeRecoveryKey(olmPkDecryption.privateKey())


uiHandler.post { callback.onSuccess(megolmBackupCreationInfo) } megolmBackupCreationInfo
} catch (e: OlmException) {
Timber.e(e, "OlmException")

uiHandler.post { callback.onFailure(e) }
} }
}.foldToCallback(callback)
} }
} }


@ -221,7 +228,8 @@ internal class KeysBackup(
} }


override fun deleteBackup(version: String, callback: MatrixCallback<Unit>?) { override fun deleteBackup(version: String, callback: MatrixCallback<Unit>?) {
CryptoAsyncHelper.getDecryptBackgroundHandler().post { GlobalScope.launch(coroutineDispatchers.main) {
withContext(coroutineDispatchers.crypto) {
// If we're currently backing up to this backup... stop. // If we're currently backing up to this backup... stop.
// (We start using it automatically in createKeysBackupVersion so this is symmetrical). // (We start using it automatically in createKeysBackupVersion so this is symmetrical).
if (keysBackupVersion != null && version == keysBackupVersion!!.version) { if (keysBackupVersion != null && version == keysBackupVersion!!.version) {
@ -254,6 +262,7 @@ internal class KeysBackup(
.executeBy(taskExecutor) .executeBy(taskExecutor)
} }
} }
}


override fun canRestoreKeys(): Boolean { override fun canRestoreKeys(): Boolean {
// Server contains more keys than locally // Server contains more keys than locally
@ -426,21 +435,17 @@ internal class KeysBackup(
callback: MatrixCallback<Unit>) { callback: MatrixCallback<Unit>) {
Timber.v("trustKeyBackupVersion: $trust, version ${keysBackupVersion.version}") Timber.v("trustKeyBackupVersion: $trust, version ${keysBackupVersion.version}")


CryptoAsyncHelper.getDecryptBackgroundHandler().post {
val myUserId = credentials.userId

// Get auth data to update it // Get auth data to update it
val authData = getMegolmBackupAuthData(keysBackupVersion) val authData = getMegolmBackupAuthData(keysBackupVersion)


if (authData == null) { if (authData == null) {
Timber.w("trustKeyBackupVersion:trust: Key backup is missing required data") Timber.w("trustKeyBackupVersion:trust: Key backup is missing required data")


uiHandler.post {
callback.onFailure(IllegalArgumentException("Missing element")) callback.onFailure(IllegalArgumentException("Missing element"))
} } else {

GlobalScope.launch(coroutineDispatchers.main) {
return@post val updateKeysBackupVersionBody = withContext(coroutineDispatchers.crypto) {
} val myUserId = credentials.userId


// Get current signatures, or create an empty set // Get current signatures, or create an empty set
val myUserSignatures = (authData.signatures!![myUserId]?.toMutableMap() ?: HashMap()) val myUserSignatures = (authData.signatures!![myUserId]?.toMutableMap() ?: HashMap())
@ -474,9 +479,11 @@ internal class KeysBackup(
val moshi = MoshiProvider.providesMoshi() val moshi = MoshiProvider.providesMoshi()
val adapter = moshi.adapter(Map::class.java) val adapter = moshi.adapter(Map::class.java)



updateKeysBackupVersionBody.authData = adapter.fromJson(newMegolmBackupAuthData.toJsonString()) as Map<String, Any>? updateKeysBackupVersionBody.authData = adapter.fromJson(newMegolmBackupAuthData.toJsonString()) as Map<String, Any>?


updateKeysBackupVersionBody
}

// And send it to the homeserver // And send it to the homeserver
updateKeysBackupVersionTask updateKeysBackupVersionTask
.configureWith(UpdateKeysBackupVersionTask.Params(keysBackupVersion.version!!, updateKeysBackupVersionBody)) .configureWith(UpdateKeysBackupVersionTask.Params(keysBackupVersion.version!!, updateKeysBackupVersionBody))
@ -493,62 +500,58 @@ internal class KeysBackup(


checkAndStartWithKeysBackupVersion(newKeysBackupVersion) checkAndStartWithKeysBackupVersion(newKeysBackupVersion)


uiHandler.post {
callback.onSuccess(data) callback.onSuccess(data)
} }
}


override fun onFailure(failure: Throwable) { override fun onFailure(failure: Throwable) {
uiHandler.post {
callback.onFailure(failure) callback.onFailure(failure)
} }
}
}) })
.executeBy(taskExecutor) .executeBy(taskExecutor)
} }
} }
}


override fun trustKeysBackupVersionWithRecoveryKey(keysBackupVersion: KeysVersionResult, override fun trustKeysBackupVersionWithRecoveryKey(keysBackupVersion: KeysVersionResult,
recoveryKey: String, recoveryKey: String,
callback: MatrixCallback<Unit>) { callback: MatrixCallback<Unit>) {
Timber.v("trustKeysBackupVersionWithRecoveryKey: version ${keysBackupVersion.version}") Timber.v("trustKeysBackupVersionWithRecoveryKey: version ${keysBackupVersion.version}")


CryptoAsyncHelper.getDecryptBackgroundHandler().post { GlobalScope.launch(coroutineDispatchers.main) {
if (!isValidRecoveryKeyForKeysBackupVersion(recoveryKey, keysBackupVersion)) { val isValid = withContext(coroutineDispatchers.crypto) {
isValidRecoveryKeyForKeysBackupVersion(recoveryKey, keysBackupVersion)
}

if (!isValid) {
Timber.w("trustKeyBackupVersionWithRecoveryKey: Invalid recovery key.") Timber.w("trustKeyBackupVersionWithRecoveryKey: Invalid recovery key.")


uiHandler.post {
callback.onFailure(IllegalArgumentException("Invalid recovery key or password")) callback.onFailure(IllegalArgumentException("Invalid recovery key or password"))
} } else {
return@post
}

trustKeysBackupVersion(keysBackupVersion, true, callback) trustKeysBackupVersion(keysBackupVersion, true, callback)
} }
} }
}


override fun trustKeysBackupVersionWithPassphrase(keysBackupVersion: KeysVersionResult, override fun trustKeysBackupVersionWithPassphrase(keysBackupVersion: KeysVersionResult,
password: String, password: String,
callback: MatrixCallback<Unit>) { callback: MatrixCallback<Unit>) {
Timber.v("trustKeysBackupVersionWithPassphrase: version ${keysBackupVersion.version}") Timber.v("trustKeysBackupVersionWithPassphrase: version ${keysBackupVersion.version}")


CryptoAsyncHelper.getDecryptBackgroundHandler().post { GlobalScope.launch(coroutineDispatchers.main) {
val recoveryKey = recoveryKeyFromPassword(password, keysBackupVersion, null) val recoveryKey = withContext(coroutineDispatchers.crypto) {
recoveryKeyFromPassword(password, keysBackupVersion, null)
}


if (recoveryKey == null) { if (recoveryKey == null) {
Timber.w("trustKeysBackupVersionWithPassphrase: Key backup is missing required data") Timber.w("trustKeysBackupVersionWithPassphrase: Key backup is missing required data")


uiHandler.post {
callback.onFailure(IllegalArgumentException("Missing element")) callback.onFailure(IllegalArgumentException("Missing element"))
} } else {

return@post
}

// Check trust using the recovery key // Check trust using the recovery key
trustKeysBackupVersionWithRecoveryKey(keysBackupVersion, recoveryKey, callback) trustKeysBackupVersionWithRecoveryKey(keysBackupVersion, recoveryKey, callback)
} }
} }
}


/** /**
* Get public key from a Recovery key * Get public key from a Recovery key
@ -591,12 +594,10 @@ internal class KeysBackup(
} }


override fun getBackupProgress(progressListener: ProgressListener) { override fun getBackupProgress(progressListener: ProgressListener) {
CryptoAsyncHelper.getDecryptBackgroundHandler().post {
val backedUpKeys = cryptoStore.inboundGroupSessionsCount(true) val backedUpKeys = cryptoStore.inboundGroupSessionsCount(true)
val total = cryptoStore.inboundGroupSessionsCount(false) val total = cryptoStore.inboundGroupSessionsCount(false)


uiHandler.post { progressListener.onProgress(backedUpKeys, total) } progressListener.onProgress(backedUpKeys, total)
}
} }


override fun restoreKeysWithRecoveryKey(keysVersionResult: KeysVersionResult, override fun restoreKeysWithRecoveryKey(keysVersionResult: KeysVersionResult,
@ -607,12 +608,13 @@ internal class KeysBackup(
callback: MatrixCallback<ImportRoomKeysResult>) { callback: MatrixCallback<ImportRoomKeysResult>) {
Timber.v("restoreKeysWithRecoveryKey: From backup version: ${keysVersionResult.version}") Timber.v("restoreKeysWithRecoveryKey: From backup version: ${keysVersionResult.version}")


CryptoAsyncHelper.getDecryptBackgroundHandler().post(Runnable { GlobalScope.launch(coroutineDispatchers.main) {
withContext(coroutineDispatchers.crypto) {
Try {
// Check if the recovery is valid before going any further // Check if the recovery is valid before going any further
if (!isValidRecoveryKeyForKeysBackupVersion(recoveryKey, keysVersionResult)) { if (!isValidRecoveryKeyForKeysBackupVersion(recoveryKey, keysVersionResult)) {
Timber.e("restoreKeysWithRecoveryKey: Invalid recovery key for this keys version") Timber.e("restoreKeysWithRecoveryKey: Invalid recovery key for this keys version")
uiHandler.post { callback.onFailure(InvalidParameterException("Invalid recovery key")) } throw InvalidParameterException("Invalid recovery key")
return@Runnable
} }


// Get a PK decryption instance // Get a PK decryption instance
@ -620,17 +622,23 @@ internal class KeysBackup(
if (decryption == null) { if (decryption == null) {
// This should not happen anymore // This should not happen anymore
Timber.e("restoreKeysWithRecoveryKey: Invalid recovery key. Error") Timber.e("restoreKeysWithRecoveryKey: Invalid recovery key. Error")
uiHandler.post { callback.onFailure(InvalidParameterException("Invalid recovery key")) } throw InvalidParameterException("Invalid recovery key")
return@Runnable
} }


if (stepProgressListener != null) { decryption!!
uiHandler.post { stepProgressListener.onStepProgress(StepProgressListener.Step.DownloadingKey) }
} }
}.fold(
{
callback.onFailure(it)
},
{ decryption ->
stepProgressListener?.onStepProgress(StepProgressListener.Step.DownloadingKey)


// Get backed up keys from the homeserver // Get backed up keys from the homeserver
getKeys(sessionId, roomId, keysVersionResult.version!!, object : MatrixCallback<KeysBackupData> { getKeys(sessionId, roomId, keysVersionResult.version!!, object : MatrixCallback<KeysBackupData> {
override fun onSuccess(data: KeysBackupData) { override fun onSuccess(data: KeysBackupData) {
GlobalScope.launch(coroutineDispatchers.main) {
val importRoomKeysResult = withContext(coroutineDispatchers.crypto) {
val sessionsData = ArrayList<MegolmSessionData>() val sessionsData = ArrayList<MegolmSessionData>()
// Restore that data // Restore that data
var sessionsFromHsCount = 0 var sessionsFromHsCount = 0
@ -668,14 +676,18 @@ internal class KeysBackup(
null null
} }


megolmSessionDataImporter.handle(sessionsData, !backUp, progressListener, object : MatrixCallback<ImportRoomKeysResult> { val result = megolmSessionDataImporter.handle(sessionsData, !backUp, uiHandler, progressListener)
override fun onSuccess(data: ImportRoomKeysResult) {
// Do not back up the key if it comes from a backup recovery // Do not back up the key if it comes from a backup recovery
if (backUp) { if (backUp) {
maybeBackupKeys() maybeBackupKeys()
} }


callback.onSuccess(data) result
}

callback.onSuccess(importRoomKeysResult)
}
} }


override fun onFailure(failure: Throwable) { override fun onFailure(failure: Throwable) {
@ -683,12 +695,8 @@ internal class KeysBackup(
} }
}) })
} }

)
override fun onFailure(failure: Throwable) {
uiHandler.post { callback.onFailure(failure) }
} }
})
})
} }


override fun restoreKeyBackupWithPassword(keysBackupVersion: KeysVersionResult, override fun restoreKeyBackupWithPassword(keysBackupVersion: KeysVersionResult,
@ -699,7 +707,8 @@ internal class KeysBackup(
callback: MatrixCallback<ImportRoomKeysResult>) { callback: MatrixCallback<ImportRoomKeysResult>) {
Timber.v("[MXKeyBackup] restoreKeyBackup with password: From backup version: ${keysBackupVersion.version}") Timber.v("[MXKeyBackup] restoreKeyBackup with password: From backup version: ${keysBackupVersion.version}")


CryptoAsyncHelper.getDecryptBackgroundHandler().post { GlobalScope.launch(coroutineDispatchers.main) {
withContext(coroutineDispatchers.crypto) {
val progressListener = if (stepProgressListener != null) { val progressListener = if (stepProgressListener != null) {
object : ProgressListener { object : ProgressListener {
override fun onProgress(progress: Int, total: Int) { override fun onProgress(progress: Int, total: Int) {
@ -712,20 +721,24 @@ internal class KeysBackup(
null null
} }


val recoveryKey = recoveryKeyFromPassword(password, keysBackupVersion, progressListener) Try {

recoveryKeyFromPassword(password, keysBackupVersion, progressListener)
}
}.fold(
{
callback.onFailure(it)
},
{ recoveryKey ->
if (recoveryKey == null) { if (recoveryKey == null) {
uiHandler.post {
Timber.v("backupKeys: Invalid configuration") Timber.v("backupKeys: Invalid configuration")
callback.onFailure(IllegalStateException("Invalid configuration")) callback.onFailure(IllegalStateException("Invalid configuration"))
} } else {

return@post
}

restoreKeysWithRecoveryKey(keysBackupVersion, recoveryKey, roomId, sessionId, stepProgressListener, callback) restoreKeysWithRecoveryKey(keysBackupVersion, recoveryKey, roomId, sessionId, stepProgressListener, callback)
} }
} }
)
}
}


/** /**
* Same method as [RoomKeysRestClient.getRoomKey] except that it accepts nullable * Same method as [RoomKeysRestClient.getRoomKey] except that it accepts nullable
@ -1190,7 +1203,8 @@ internal class KeysBackup(


keysBackupStateManager.state = KeysBackupState.BackingUp keysBackupStateManager.state = KeysBackupState.BackingUp


CryptoAsyncHelper.getEncryptBackgroundHandler().post { GlobalScope.launch(coroutineDispatchers.main) {
withContext(coroutineDispatchers.crypto) {
Timber.v("backupKeys: 2 - Encrypting keys") Timber.v("backupKeys: 2 - Encrypting keys")


// Gather data to send to the homeserver // Gather data to send to the homeserver
@ -1280,6 +1294,7 @@ internal class KeysBackup(
.executeBy(taskExecutor) .executeBy(taskExecutor)
} }
} }
}


@VisibleForTesting @VisibleForTesting
@WorkerThread @WorkerThread

View File

@ -27,17 +27,12 @@ import im.vector.matrix.android.api.session.crypto.sas.safeValueOf
import im.vector.matrix.android.api.session.events.model.Event import im.vector.matrix.android.api.session.events.model.Event
import im.vector.matrix.android.api.session.events.model.EventType import im.vector.matrix.android.api.session.events.model.EventType
import im.vector.matrix.android.api.session.events.model.toModel import im.vector.matrix.android.api.session.events.model.toModel
import im.vector.matrix.android.internal.crypto.CryptoAsyncHelper
import im.vector.matrix.android.internal.crypto.DeviceListManager import im.vector.matrix.android.internal.crypto.DeviceListManager
import im.vector.matrix.android.internal.crypto.MyDeviceInfoHolder import im.vector.matrix.android.internal.crypto.MyDeviceInfoHolder
import im.vector.matrix.android.internal.crypto.actions.SetDeviceVerificationAction import im.vector.matrix.android.internal.crypto.actions.SetDeviceVerificationAction
import im.vector.matrix.android.internal.crypto.model.MXDeviceInfo import im.vector.matrix.android.internal.crypto.model.MXDeviceInfo
import im.vector.matrix.android.internal.crypto.model.MXUsersDevicesMap import im.vector.matrix.android.internal.crypto.model.MXUsersDevicesMap
import im.vector.matrix.android.internal.crypto.model.rest.KeyVerificationAccept import im.vector.matrix.android.internal.crypto.model.rest.*
import im.vector.matrix.android.internal.crypto.model.rest.KeyVerificationCancel
import im.vector.matrix.android.internal.crypto.model.rest.KeyVerificationKey
import im.vector.matrix.android.internal.crypto.model.rest.KeyVerificationMac
import im.vector.matrix.android.internal.crypto.model.rest.KeyVerificationStart
import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore
import im.vector.matrix.android.internal.crypto.tasks.SendToDeviceTask import im.vector.matrix.android.internal.crypto.tasks.SendToDeviceTask
import im.vector.matrix.android.internal.task.TaskExecutor import im.vector.matrix.android.internal.task.TaskExecutor
@ -372,9 +367,8 @@ internal class DefaultSasVerificationService(private val credentials: Credential
userId, userId,
deviceID) deviceID)
addTransaction(tx) addTransaction(tx)
CryptoAsyncHelper.getDecryptBackgroundHandler().post {
tx.start() tx.start()
}
return txID return txID
} else { } else {
throw IllegalArgumentException("Unknown verification method") throw IllegalArgumentException("Unknown verification method")

View File

@ -22,13 +22,12 @@ import im.vector.matrix.android.api.session.crypto.sas.IncomingSasVerificationTr
import im.vector.matrix.android.api.session.crypto.sas.SasMode import im.vector.matrix.android.api.session.crypto.sas.SasMode
import im.vector.matrix.android.api.session.crypto.sas.SasVerificationTxState import im.vector.matrix.android.api.session.crypto.sas.SasVerificationTxState
import im.vector.matrix.android.api.session.events.model.EventType import im.vector.matrix.android.api.session.events.model.EventType
import im.vector.matrix.android.internal.crypto.CryptoAsyncHelper
import im.vector.matrix.android.internal.crypto.actions.SetDeviceVerificationAction import im.vector.matrix.android.internal.crypto.actions.SetDeviceVerificationAction
import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore
import im.vector.matrix.android.internal.crypto.model.rest.KeyVerificationAccept import im.vector.matrix.android.internal.crypto.model.rest.KeyVerificationAccept
import im.vector.matrix.android.internal.crypto.model.rest.KeyVerificationKey import im.vector.matrix.android.internal.crypto.model.rest.KeyVerificationKey
import im.vector.matrix.android.internal.crypto.model.rest.KeyVerificationMac import im.vector.matrix.android.internal.crypto.model.rest.KeyVerificationMac
import im.vector.matrix.android.internal.crypto.model.rest.KeyVerificationStart import im.vector.matrix.android.internal.crypto.model.rest.KeyVerificationStart
import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore
import im.vector.matrix.android.internal.crypto.tasks.SendToDeviceTask import im.vector.matrix.android.internal.crypto.tasks.SendToDeviceTask
import im.vector.matrix.android.internal.di.MoshiProvider import im.vector.matrix.android.internal.di.MoshiProvider
import im.vector.matrix.android.internal.task.TaskExecutor import im.vector.matrix.android.internal.task.TaskExecutor
@ -125,9 +124,7 @@ internal class IncomingSASVerificationTransaction(
//TODO force download keys!! //TODO force download keys!!
//would be probably better to download the keys //would be probably better to download the keys
//for now I cancel //for now I cancel
CryptoAsyncHelper.getDecryptBackgroundHandler().post {
cancel(CancelCode.User) cancel(CancelCode.User)
}
} else { } else {
// val otherKey = info.identityKey() // val otherKey = info.identityKey()
//need to jump back to correct thread //need to jump back to correct thread
@ -139,11 +136,9 @@ internal class IncomingSASVerificationTransaction(
shortAuthenticationStrings = agreedShortCode, shortAuthenticationStrings = agreedShortCode,
commitment = Base64.encodeToString("temporary commitment".toByteArray(), Base64.DEFAULT) commitment = Base64.encodeToString("temporary commitment".toByteArray(), Base64.DEFAULT)
) )
CryptoAsyncHelper.getDecryptBackgroundHandler().post {
doAccept(accept) doAccept(accept)
} }
} }
}




private fun doAccept(accept: KeyVerificationAccept) { private fun doAccept(accept: KeyVerificationAccept) {

View File

@ -86,7 +86,6 @@ internal class OutgoingSASVerificationRequest(
} }


fun start() { fun start() {

if (state != SasVerificationTxState.None) { if (state != SasVerificationTxState.None) {
Timber.e("## start verification from invalid state") Timber.e("## start verification from invalid state")
//should I cancel?? //should I cancel??

View File

@ -23,7 +23,6 @@ import im.vector.matrix.android.api.session.crypto.sas.EmojiRepresentation
import im.vector.matrix.android.api.session.crypto.sas.SasMode import im.vector.matrix.android.api.session.crypto.sas.SasMode
import im.vector.matrix.android.api.session.crypto.sas.SasVerificationTxState import im.vector.matrix.android.api.session.crypto.sas.SasVerificationTxState
import im.vector.matrix.android.api.session.events.model.EventType import im.vector.matrix.android.api.session.events.model.EventType
import im.vector.matrix.android.internal.crypto.CryptoAsyncHelper
import im.vector.matrix.android.internal.crypto.actions.SetDeviceVerificationAction import im.vector.matrix.android.internal.crypto.actions.SetDeviceVerificationAction
import im.vector.matrix.android.internal.crypto.model.MXDeviceInfo import im.vector.matrix.android.internal.crypto.model.MXDeviceInfo
import im.vector.matrix.android.internal.crypto.model.MXKey import im.vector.matrix.android.internal.crypto.model.MXKey
@ -278,22 +277,18 @@ internal abstract class SASVerificationTransaction(
.dispatchTo(object : MatrixCallback<Unit> { .dispatchTo(object : MatrixCallback<Unit> {
override fun onSuccess(data: Unit) { override fun onSuccess(data: Unit) {
Timber.v("## SAS verification [$transactionId] toDevice type '$type' success.") Timber.v("## SAS verification [$transactionId] toDevice type '$type' success.")
CryptoAsyncHelper.getDecryptBackgroundHandler().post {
if (onDone != null) { if (onDone != null) {
onDone() onDone()
} else { } else {
state = nextState state = nextState
} }
} }
}


override fun onFailure(failure: Throwable) { override fun onFailure(failure: Throwable) {
Timber.e("## SAS verification [$transactionId] failed to send toDevice in state : $state") Timber.e("## SAS verification [$transactionId] failed to send toDevice in state : $state")


CryptoAsyncHelper.getDecryptBackgroundHandler().post {
cancel(onErrorReason) cancel(onErrorReason)
} }
}
}) })
.executeBy(taskExecutor) .executeBy(taskExecutor)
} }

View File

@ -17,7 +17,8 @@
package im.vector.matrix.android.internal.di package im.vector.matrix.android.internal.di


import android.content.Context import android.content.Context
import im.vector.matrix.android.internal.crypto.CryptoAsyncHelper import android.os.Handler
import android.os.HandlerThread
import im.vector.matrix.android.internal.task.TaskExecutor import im.vector.matrix.android.internal.task.TaskExecutor
import im.vector.matrix.android.internal.util.BackgroundDetectionObserver import im.vector.matrix.android.internal.util.BackgroundDetectionObserver
import im.vector.matrix.android.internal.util.MatrixCoroutineDispatchers import im.vector.matrix.android.internal.util.MatrixCoroutineDispatchers
@ -36,11 +37,14 @@ class MatrixModule(private val context: Context) {
} }


single { single {
val cryptoHandler = CryptoAsyncHelper.getDecryptBackgroundHandler() val THREAD_CRYPTO_NAME = "Crypto_Thread"
val handlerThread = HandlerThread(THREAD_CRYPTO_NAME)
handlerThread.start()

MatrixCoroutineDispatchers(io = Dispatchers.IO, MatrixCoroutineDispatchers(io = Dispatchers.IO,
computation = Dispatchers.IO, computation = Dispatchers.IO,
main = Dispatchers.Main, main = Dispatchers.Main,
crypto = cryptoHandler.asCoroutineDispatcher("crypto") crypto = Handler(handlerThread.looper).asCoroutineDispatcher("crypto")
) )
} }



View File

@ -0,0 +1,83 @@
/*
* Copyright 2019 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package im.vector.riotredesign.features.crypto.keys

import android.content.Context
import android.net.Uri
import arrow.core.Try
import im.vector.matrix.android.api.MatrixCallback
import im.vector.matrix.android.api.session.Session
import im.vector.matrix.android.internal.crypto.model.ImportRoomKeysResult
import im.vector.riotredesign.core.intent.getMimeTypeFromUri
import im.vector.riotredesign.core.resources.openResource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import timber.log.Timber

class KeysImporter(private val session: Session) {

/**
* Export keys and return the file path with the callback
*/
fun import(context: Context,
uri: Uri,
mimetype: String?,
password: String,
callback: MatrixCallback<ImportRoomKeysResult>) {
GlobalScope.launch(Dispatchers.Main) {
withContext(Dispatchers.IO) {
Try {
val resource = openResource(context, uri, mimetype ?: getMimeTypeFromUri(context, uri))

if (resource?.mContentStream == null) {
throw Exception("Error")
}

val data: ByteArray
try {
data = ByteArray(resource.mContentStream!!.available())
resource.mContentStream!!.read(data)
resource.mContentStream!!.close()

data
} catch (e: Exception) {
try {
resource.mContentStream!!.close()
} catch (e2: Exception) {
Timber.e(e2, "## importKeys()")
}

throw e
}
}
}
.fold(
{
callback.onFailure(it)
},
{ byteArray ->
session.importRoomKeys(byteArray,
password,
null,
callback)
}
)
}
}
}

View File

@ -59,18 +59,17 @@ import im.vector.riotredesign.core.extensions.withArgs
import im.vector.riotredesign.core.intent.ExternalIntentData import im.vector.riotredesign.core.intent.ExternalIntentData
import im.vector.riotredesign.core.intent.analyseIntent import im.vector.riotredesign.core.intent.analyseIntent
import im.vector.riotredesign.core.intent.getFilenameFromUri import im.vector.riotredesign.core.intent.getFilenameFromUri
import im.vector.riotredesign.core.intent.getMimeTypeFromUri
import im.vector.riotredesign.core.platform.SimpleTextWatcher import im.vector.riotredesign.core.platform.SimpleTextWatcher
import im.vector.riotredesign.core.platform.VectorPreferenceFragment import im.vector.riotredesign.core.platform.VectorPreferenceFragment
import im.vector.riotredesign.core.preference.BingRule import im.vector.riotredesign.core.preference.BingRule
import im.vector.riotredesign.core.preference.ProgressBarPreference import im.vector.riotredesign.core.preference.ProgressBarPreference
import im.vector.riotredesign.core.preference.UserAvatarPreference import im.vector.riotredesign.core.preference.UserAvatarPreference
import im.vector.riotredesign.core.preference.VectorPreference import im.vector.riotredesign.core.preference.VectorPreference
import im.vector.riotredesign.core.resources.openResource
import im.vector.riotredesign.core.utils.* import im.vector.riotredesign.core.utils.*
import im.vector.riotredesign.features.MainActivity import im.vector.riotredesign.features.MainActivity
import im.vector.riotredesign.features.configuration.VectorConfiguration import im.vector.riotredesign.features.configuration.VectorConfiguration
import im.vector.riotredesign.features.crypto.keys.KeysExporter import im.vector.riotredesign.features.crypto.keys.KeysExporter
import im.vector.riotredesign.features.crypto.keys.KeysImporter
import im.vector.riotredesign.features.crypto.keysbackup.settings.KeysBackupManageActivity import im.vector.riotredesign.features.crypto.keysbackup.settings.KeysBackupManageActivity
import im.vector.riotredesign.features.themes.ThemeUtils import im.vector.riotredesign.features.themes.ThemeUtils
import org.koin.android.ext.android.inject import org.koin.android.ext.android.inject
@ -2702,37 +2701,12 @@ class VectorSettingsPreferencesFragment : VectorPreferenceFragment(), SharedPref


importButton.setOnClickListener(View.OnClickListener { importButton.setOnClickListener(View.OnClickListener {
val password = passPhraseEditText.text.toString() val password = passPhraseEditText.text.toString()
val resource = openResource(appContext, uri, mimetype ?: getMimeTypeFromUri(appContext, uri))


if (resource?.mContentStream == null) { KeysImporter(mSession)
appContext.toast("Error") .import(requireContext(),

uri,
return@OnClickListener mimetype,
}

val data: ByteArray
// TODO BG
try {
data = ByteArray(resource.mContentStream!!.available())
resource.mContentStream!!.read(data)
resource.mContentStream!!.close()
} catch (e: Exception) {
try {
resource.mContentStream!!.close()
} catch (e2: Exception) {
Timber.e(e2, "## importKeys()")
}

appContext.toast(e.localizedMessage)

return@OnClickListener
}

displayLoadingView()

mSession.importRoomKeys(data,
password, password,
null,
object : MatrixCallback<ImportRoomKeysResult> { object : MatrixCallback<ImportRoomKeysResult> {
override fun onSuccess(data: ImportRoomKeysResult) { override fun onSuccess(data: ImportRoomKeysResult) {
if (!isAdded) { if (!isAdded) {