session-android/libsession/src/main/java/org/session/libsession/messaging/sending_receiving/MessageReceiver.kt

131 lines
7.2 KiB
Kotlin
Raw Normal View History

2020-12-02 06:39:33 +01:00
package org.session.libsession.messaging.sending_receiving
2020-11-25 02:06:41 +01:00
2021-04-26 03:14:45 +02:00
import org.session.libsession.messaging.MessagingModuleConfiguration
import org.session.libsession.messaging.messages.Message
import org.session.libsession.messaging.messages.control.*
import org.session.libsession.messaging.messages.visible.VisibleMessage
2021-05-18 01:50:16 +02:00
import org.session.libsignal.crypto.PushTransportDetails
2021-05-18 01:44:06 +02:00
import org.session.libsignal.protos.SignalServiceProtos
2020-11-25 02:06:41 +01:00
object MessageReceiver {
internal sealed class Error(message: String) : Exception(message) {
object DuplicateMessage: Error("Duplicate message.")
2020-12-02 06:39:33 +01:00
object InvalidMessage: Error("Invalid message.")
object UnknownMessage: Error("Unknown message type.")
object UnknownEnvelopeType: Error("Unknown envelope type.")
object DecryptionFailed : Exception("Couldn't decrypt message.")
object InvalidSignature: Error("Invalid message signature.")
2020-12-02 06:39:33 +01:00
object NoData: Error("Received an empty envelope.")
object SenderBlocked: Error("Received a message from a blocked user.")
object NoThread: Error("Couldn't find thread for message.")
object SelfSend: Error("Message addressed at self.")
object InvalidGroupPublicKey: Error("Invalid group public key.")
2021-01-14 01:42:26 +01:00
object NoGroupKeyPair: Error("Missing group key pair.")
2020-12-02 06:39:33 +01:00
internal val isRetryable: Boolean = when (this) {
is DuplicateMessage, is InvalidMessage, is UnknownMessage,
is UnknownEnvelopeType, is InvalidSignature, is NoData,
is SenderBlocked, is SelfSend -> false
2020-12-02 06:39:33 +01:00
else -> true
}
}
internal fun parse(data: ByteArray, openGroupServerID: Long?): Pair<Message, SignalServiceProtos.Content> {
2021-04-26 03:14:45 +02:00
val storage = MessagingModuleConfiguration.shared.storage
val userPublicKey = storage.getUserPublicKey()
val isOpenGroupMessage = (openGroupServerID != null)
// Parse the envelope
val envelope = SignalServiceProtos.Envelope.parseFrom(data)
// Decrypt the contents
2021-01-14 01:42:26 +01:00
val ciphertext = envelope.content ?: throw Error.NoData
var plaintext: ByteArray? = null
var sender: String? = null
var groupPublicKey: String? = null
if (isOpenGroupMessage) {
plaintext = envelope.content.toByteArray()
sender = envelope.source
} else {
when (envelope.type) {
2021-04-26 03:23:09 +02:00
SignalServiceProtos.Envelope.Type.SESSION_MESSAGE -> {
2021-04-26 03:14:45 +02:00
val userX25519KeyPair = MessagingModuleConfiguration.shared.storage.getUserX25519KeyPair()
val decryptionResult = MessageDecrypter.decrypt(ciphertext.toByteArray(), userX25519KeyPair)
plaintext = decryptionResult.first
sender = decryptionResult.second
}
2021-04-26 03:23:09 +02:00
SignalServiceProtos.Envelope.Type.CLOSED_GROUP_MESSAGE -> {
2021-01-14 01:42:26 +01:00
val hexEncodedGroupPublicKey = envelope.source
2021-04-26 03:14:45 +02:00
if (hexEncodedGroupPublicKey == null || !MessagingModuleConfiguration.shared.storage.isClosedGroup(hexEncodedGroupPublicKey)) {
2021-01-14 01:42:26 +01:00
throw Error.InvalidGroupPublicKey
}
2021-04-26 03:14:45 +02:00
val encryptionKeyPairs = MessagingModuleConfiguration.shared.storage.getClosedGroupEncryptionKeyPairs(hexEncodedGroupPublicKey)
2021-01-14 01:42:26 +01:00
if (encryptionKeyPairs.isEmpty()) { throw Error.NoGroupKeyPair }
// Loop through all known group key pairs in reverse order (i.e. try the latest key pair first (which'll more than
// likely be the one we want) but try older ones in case that didn't work)
var encryptionKeyPair = encryptionKeyPairs.removeLast()
fun decrypt() {
try {
val decryptionResult = MessageDecrypter.decrypt(ciphertext.toByteArray(), encryptionKeyPair)
2021-01-14 01:42:26 +01:00
plaintext = decryptionResult.first
sender = decryptionResult.second
} catch (e: Exception) {
if (encryptionKeyPairs.isNotEmpty()) {
encryptionKeyPair = encryptionKeyPairs.removeLast()
decrypt()
} else {
throw e
}
}
}
groupPublicKey = envelope.source
2021-02-11 06:57:43 +01:00
decrypt()
}
else -> throw Error.UnknownEnvelopeType
}
}
// Don't process the envelope any further if the sender is blocked
if (isBlocked(sender!!)) throw Error.SenderBlocked
// Parse the proto
val proto = SignalServiceProtos.Content.parseFrom(PushTransportDetails.getStrippedPaddingMessageBody(plaintext))
// Parse the message
val message: Message = ReadReceipt.fromProto(proto) ?:
2021-04-26 03:23:09 +02:00
TypingIndicator.fromProto(proto) ?:
ClosedGroupControlMessage.fromProto(proto) ?:
DataExtractionNotification.fromProto(proto) ?:
ExpirationTimerUpdate.fromProto(proto) ?:
ConfigurationMessage.fromProto(proto) ?:
UnsendRequest.fromProto(proto) ?:
MessageRequestResponse.fromProto(proto) ?:
2021-04-26 03:23:09 +02:00
VisibleMessage.fromProto(proto) ?: throw Error.UnknownMessage
// Ignore self send if needed
if (!message.isSelfSendValid && sender == userPublicKey) throw Error.SelfSend
// Guard against control messages in open groups
if (isOpenGroupMessage && message !is VisibleMessage) throw Error.InvalidMessage
// Finish parsing
message.sender = sender
message.recipient = userPublicKey
message.sentTimestamp = envelope.timestamp
message.receivedTimestamp = if (envelope.hasServerTimestamp()) envelope.serverTimestamp else System.currentTimeMillis()
message.groupPublicKey = groupPublicKey
message.openGroupServerMessageID = openGroupServerID
// Validate
var isValid = message.isValid()
if (message is VisibleMessage && !isValid && proto.dataMessage.attachmentsCount != 0) { isValid = true }
if (!isValid) { throw Error.InvalidMessage }
2021-05-19 00:56:44 +02:00
// If the message failed to process the first time around we retry it later (if the error is retryable). In this case the timestamp
// will already be in the database but we don't want to treat the message as a duplicate. The isRetry flag is a simple workaround
// for this issue.
if (message is ClosedGroupControlMessage && message.kind is ClosedGroupControlMessage.Kind.New) {
// Allow duplicates in this case to avoid the following situation:
// • The app performed a background poll or received a push notification
// • This method was invoked and the received message timestamps table was updated
// • Processing wasn't finished
// • The user doesn't see the new closed group
} else {
if (storage.isDuplicateMessage(envelope.timestamp)) { throw Error.DuplicateMessage }
storage.addReceivedMessageTimestamp(envelope.timestamp)
}
// Return
return Pair(message, proto)
}
2020-11-25 02:06:41 +01:00
}