Do not crash when receiving invalid message.

This commit is contained in:
Felix Ableitner 2015-01-29 17:46:57 +01:00
parent 5a460c9527
commit 2f08ec0124
2 changed files with 28 additions and 18 deletions

View file

@ -5,6 +5,7 @@ import java.io._
import android.bluetooth.BluetoothSocket
import android.util.Log
import com.nutomic.ensichat.protocol._
import com.nutomic.ensichat.protocol.messages.Message.ReadMessageException
import com.nutomic.ensichat.protocol.messages.{ConnectionInfo, Message, MessageHeader}
/**
@ -54,8 +55,8 @@ class TransferThread(device: Device, socket: BluetoothSocket, Handler: Bluetooth
onReceive(msg, device.Id)
}
} catch {
case e: RuntimeException =>
Log.i(Tag, "Received invalid message", e)
case e: ReadMessageException =>
Log.i(Tag, "Failed to read message", e)
case e: IOException =>
Log.w(Tag, "Failed to read incoming message", e)
close()

View file

@ -1,6 +1,7 @@
package com.nutomic.ensichat.protocol.messages
import java.io.InputStream
import java.security.spec.InvalidKeySpecException
object Message {
@ -16,7 +17,11 @@ object Message {
val Charset = "UTF-8"
class ReadMessageException(throwable: Throwable)
extends RuntimeException(throwable)
def read(stream: InputStream): Message = {
try {
val headerBytes = new Array[Byte](MessageHeader.Length)
stream.read(headerBytes, 0, MessageHeader.Length)
val header = MessageHeader.read(headerBytes)
@ -37,6 +42,10 @@ object Message {
}
new Message(header, crypto, body)
} catch {
case e @ (_ : OutOfMemoryError | _ : InvalidKeySpecException) =>
throw new ReadMessageException(e)
}
}
}