Formatting fixes

This commit is contained in:
Felix Ableitner 2016-08-27 03:08:20 +02:00
parent 8bec10efb6
commit 127e4c9ff2
2 changed files with 50 additions and 49 deletions

View file

@ -4,9 +4,10 @@ import java.security.InvalidKeyException
import com.nutomic.ensichat.core.interfaces._
import com.nutomic.ensichat.core.internet.InternetInterface
import com.nutomic.ensichat.core.messages.Message
import com.nutomic.ensichat.core.messages.body._
import com.nutomic.ensichat.core.messages.header.{AbstractHeader, ContentHeader}
import com.nutomic.ensichat.core.routing.{MessageBuffer, Router}
import com.nutomic.ensichat.core.messages.header.{MessageHeader, AbstractHeader, ContentHeader}
import com.nutomic.ensichat.core.routing._
import com.nutomic.ensichat.core.util._
import com.typesafe.scalalogging.Logger
import org.joda.time.{DateTime, Duration}
@ -31,15 +32,15 @@ final class ConnectionHandler(settings: SettingsInterface, database: Database,
private lazy val seqNumGenerator = new SeqNumGenerator(settings)
private val localRoutesInfo = new routing.LocalRoutesInfo(connections)
private val localRoutesInfo = new LocalRoutesInfo(connections)
private val routeMessageInfo = new routing.RouteMessageInfo()
private val routeMessageInfo = new RouteMessageInfo()
private lazy val router = new Router(localRoutesInfo,
(a, m) => transmissionInterfaces.foreach(_.send(a, m)),
noRouteFound)
private lazy val messageBuffer = new routing.MessageBuffer(crypto.localAddress, requestRoute)
private lazy val messageBuffer = new MessageBuffer(crypto.localAddress, requestRoute)
/**
* Holds all known users.
@ -81,7 +82,7 @@ final class ConnectionHandler(settings: SettingsInterface, database: Database,
/**
* Sends a new message to the given target address.
*/
def sendTo(target: routing.Address, body: MessageBody): Unit = {
def sendTo(target: Address, body: MessageBody): Unit = {
assert(body.contentType != -1)
FutureHelper {
val messageId = settings.get("message_id", 0L)
@ -89,7 +90,7 @@ final class ConnectionHandler(settings: SettingsInterface, database: Database,
body.contentType, Some(messageId), Some(DateTime.now), AbstractHeader.InitialForwardingTokens)
settings.put("message_id", messageId + 1)
val msg = new messages.Message(header, body)
val msg = new Message(header, body)
val encrypted = crypto.encryptAndSign(msg)
router.forwardMessage(encrypted)
forwardMessageToRelays(encrypted)
@ -97,34 +98,34 @@ final class ConnectionHandler(settings: SettingsInterface, database: Database,
}
}
private def requestRoute(target: routing.Address): Unit = {
private def requestRoute(target: Address): Unit = {
assert(localRoutesInfo.getRoute(target).isEmpty)
val seqNum = seqNumGenerator.next()
val targetSeqNum = localRoutesInfo.getRoute(target).map(_.seqNum).getOrElse(-1)
val body = new RouteRequest(target, seqNum, targetSeqNum, 0)
val header = new messages.header.MessageHeader(body.protocolType, crypto.localAddress, routing.Address.Broadcast, seqNum, 0)
val header = new MessageHeader(body.protocolType, crypto.localAddress, Address.Broadcast, seqNum, 0)
val signed = crypto.sign(new messages.Message(header, body))
val signed = crypto.sign(new Message(header, body))
router.forwardMessage(signed)
}
private def replyRoute(target: routing.Address, replyTo: routing.Address): Unit = {
private def replyRoute(target: Address, replyTo: Address): Unit = {
val seqNum = seqNumGenerator.next()
val body = new RouteReply(seqNum, 0)
val header = new messages.header.MessageHeader(body.protocolType, crypto.localAddress, replyTo, seqNum, 0)
val header = new MessageHeader(body.protocolType, crypto.localAddress, replyTo, seqNum, 0)
val signed = crypto.sign(new messages.Message(header, body))
val signed = crypto.sign(new Message(header, body))
router.forwardMessage(signed)
}
private def routeError(address: routing.Address, packetSource: Option[routing.Address]): Unit = {
val destination = packetSource.getOrElse(routing.Address.Broadcast)
val header = new messages.header.MessageHeader(RouteError.Type, crypto.localAddress, destination,
private def routeError(address: Address, packetSource: Option[Address]): Unit = {
val destination = packetSource.getOrElse(Address.Broadcast)
val header = new MessageHeader(RouteError.Type, crypto.localAddress, destination,
seqNumGenerator.next(), 0)
val seqNum = localRoutesInfo.getRoute(address).map(_.seqNum).getOrElse(-1)
val body = new RouteError(address, seqNum)
val signed = crypto.sign(new messages.Message(header, body))
val signed = crypto.sign(new Message(header, body))
router.forwardMessage(signed)
}
@ -143,7 +144,7 @@ final class ConnectionHandler(settings: SettingsInterface, database: Database,
/**
* Decrypts and verifies incoming messages, forwards valid ones to [[onNewMessage()]].
*/
def onMessageReceived(msg: messages.Message, previousHop: routing.Address): Unit = {
def onMessageReceived(msg: Message, previousHop: Address): Unit = {
if (router.isMessageSeen(msg)) {
logger.trace("Ignoring message from " + msg.header.origin + " that we already received")
return
@ -165,10 +166,10 @@ final class ConnectionHandler(settings: SettingsInterface, database: Database,
else {
val body = rreq.copy(originMetric = rreq.originMetric + 1)
val forwardMsg = crypto.sign(new messages.Message(msg.header, body))
val forwardMsg = crypto.sign(new Message(msg.header, body))
localRoutesInfo.getRoute(rreq.requested) match {
case Some(route) => router.forwardMessage(forwardMsg, Option(route.nextHop))
case None => router.forwardMessage(forwardMsg, Option(routing.Address.Broadcast))
case None => router.forwardMessage(forwardMsg, Option(Address.Broadcast))
}
}
return
@ -186,7 +187,7 @@ final class ConnectionHandler(settings: SettingsInterface, database: Database,
return
val existingRoute = localRoutesInfo.getRoute(msg.header.target)
val states = Set(routing.LocalRoutesInfo.RouteStates.Active, routing.LocalRoutesInfo.RouteStates.Idle)
val states = Set(LocalRoutesInfo.RouteStates.Active, LocalRoutesInfo.RouteStates.Idle)
if (existingRoute.isEmpty || !states.contains(existingRoute.get.state)) {
routeError(msg.header.target, Option(msg.header.origin))
return
@ -194,7 +195,7 @@ final class ConnectionHandler(settings: SettingsInterface, database: Database,
val body = rrep.copy(originMetric = rrep.originMetric + 1)
val forwardMsg = crypto.sign(new messages.Message(msg.header, body))
val forwardMsg = crypto.sign(new Message(msg.header, body))
router.forwardMessage(forwardMsg)
return
case rerr: RouteError =>
@ -246,7 +247,7 @@ final class ConnectionHandler(settings: SettingsInterface, database: Database,
onNewMessage(plainMsg)
}
private def forwardMessageToRelays(message: messages.Message): Unit = {
private def forwardMessageToRelays(message: Message): Unit = {
var tokens = message.header.tokens
val relays = database.pickLongestConnectionDevice(connections())
var index = 0
@ -269,7 +270,7 @@ final class ConnectionHandler(settings: SettingsInterface, database: Database,
.foreach(router.forwardMessage(_))
}
private def noRouteFound(message: messages.Message): Unit = {
private def noRouteFound(message: Message): Unit = {
messageBuffer.addMessage(message)
requestRoute(message.header.target)
}
@ -277,7 +278,7 @@ final class ConnectionHandler(settings: SettingsInterface, database: Database,
/**
* Handles all (locally and remotely sent) new messages.
*/
private def onNewMessage(msg: messages.Message): Unit = msg.body match {
private def onNewMessage(msg: Message): Unit = msg.body match {
case ui: UserInfo =>
val contact = new util.User(msg.header.origin, ui.name, ui.status)
knownUsers += contact
@ -305,7 +306,7 @@ final class ConnectionHandler(settings: SettingsInterface, database: Database,
* @param msg The message containing [[messages.body.ConnectionInfo]] to open the connection.
* @return True if the connection is valid
*/
def onConnectionOpened(msg: messages.Message): Boolean = {
def onConnectionOpened(msg: Message): Boolean = {
val maxConnections = settings.get(SettingsInterface.KeyMaxConnections,
SettingsInterface.DefaultMaxConnections.toString).toInt
if (connections().size == maxConnections) {
@ -315,7 +316,7 @@ final class ConnectionHandler(settings: SettingsInterface, database: Database,
val info = msg.body.asInstanceOf[messages.body.ConnectionInfo]
val sender = crypto.calculateAddress(info.key)
if (sender == routing.Address.Broadcast || sender == routing.Address.Null) {
if (sender == Address.Broadcast || sender == Address.Null) {
logger.info("Ignoring ConnectionInfo message with invalid sender " + sender)
return false
}
@ -354,21 +355,21 @@ final class ConnectionHandler(settings: SettingsInterface, database: Database,
* @param address The address of the connected device.
* @param duration The time that we were connected to the device.
*/
def onConnectionClosed(address: routing.Address, duration: Duration): Unit = {
def onConnectionClosed(address: Address, duration: Duration): Unit = {
localRoutesInfo.connectionClosed(address)
.foreach(routeError(_, None))
callbacks.onConnectionsChanged()
database.insertOrUpdateKnownDevice(address, duration)
}
def connections(): Set[routing.Address] = transmissionInterfaces.flatMap(_.getConnections)
def connections(): Set[Address] = transmissionInterfaces.flatMap(_.getConnections)
private def allKnownUsers() = database.getContacts ++ knownUsers
/**
* Returns [[util.User]] object containing the user's name (if we know it).
*/
def getUser(address: routing.Address) =
def getUser(address: Address) =
allKnownUsers()
.find(_.address == address)
.getOrElse(new util.User(address, address.toString(), ""))

View file

@ -6,9 +6,9 @@ import java.security.spec.{PKCS8EncodedKeySpec, X509EncodedKeySpec}
import javax.crypto.spec.SecretKeySpec
import javax.crypto.{Cipher, CipherOutputStream, KeyGenerator, SecretKey}
import com.nutomic.ensichat.core._
import com.nutomic.ensichat.core.interfaces.SettingsInterface
import com.nutomic.ensichat.core.messages.body.{CryptoData, EncryptedBody, Text, UserInfo}
import com.nutomic.ensichat.core.messages.Message
import com.nutomic.ensichat.core.messages.body._
import com.nutomic.ensichat.core.messages.header.{ContentHeader, MessageHeader}
import com.nutomic.ensichat.core.routing.Address
import com.nutomic.ensichat.core.util.Crypto._
@ -91,7 +91,7 @@ class Crypto(settings: SettingsInterface, keyFolder: File) {
if (localKeysExist)
return
var address: routing.Address = null
var address: Address = null
var keyPair: KeyPair = null
do {
val keyGen = KeyPairGenerator.getInstance(PublicKeyAlgorithm)
@ -101,7 +101,7 @@ class Crypto(settings: SettingsInterface, keyFolder: File) {
address = calculateAddress(keyPair.getPublic)
// Never generate an invalid address.
} while(address == routing.Address.Broadcast || address == routing.Address.Null)
} while(address == Address.Broadcast || address == Address.Null)
settings.put(LocalAddressKey, address.toString)
@ -113,7 +113,7 @@ class Crypto(settings: SettingsInterface, keyFolder: File) {
/**
* Returns true if we have a public key stored for the given device.
*/
private[core] def havePublicKey(address: routing.Address) = new File(keyFolder, address.toString).exists()
private[core] def havePublicKey(address: Address) = new File(keyFolder, address.toString).exists()
/**
* Returns the public key for the given device.
@ -121,7 +121,7 @@ class Crypto(settings: SettingsInterface, keyFolder: File) {
* @throws RuntimeException If the key does not exist.
*/
@throws[RuntimeException]
def getPublicKey(address: routing.Address): PublicKey = {
def getPublicKey(address: Address): PublicKey = {
loadKey(address.toString, classOf[PublicKey])
}
@ -131,7 +131,7 @@ class Crypto(settings: SettingsInterface, keyFolder: File) {
* @throws RuntimeException If a key already exists for this address.
*/
@throws[RuntimeException]
def addPublicKey(address: routing.Address, key: PublicKey): Unit = {
def addPublicKey(address: Address, key: PublicKey): Unit = {
if (havePublicKey(address))
throw new RuntimeException("Already have key for " + address + ", not overwriting")
@ -141,7 +141,7 @@ class Crypto(settings: SettingsInterface, keyFolder: File) {
/**
* Prepares message header and body so that they can be signed/verified.
*/
private def messageForSigning(msg: messages.Message): Array[Byte] = {
private def messageForSigning(msg: Message): Array[Byte] = {
val header = msg.header match {
case ch: ContentHeader => ch.copy(tokens = 0, hopCount = 0)
case mh: MessageHeader => mh.copy(tokens = 0, hopCount = 0)
@ -149,16 +149,16 @@ class Crypto(settings: SettingsInterface, keyFolder: File) {
header.write(msg.body.length) ++ msg.body.write
}
def sign(msg: messages.Message): messages.Message = {
def sign(msg: Message): Message = {
val sig = Signature.getInstance(SigningAlgorithm)
val key = loadKey(PrivateKeyAlias, classOf[PrivateKey])
sig.initSign(key)
sig.update(messageForSigning(msg))
new messages.Message(msg.header, new CryptoData(Option(sig.sign), msg.crypto.key), msg.body)
new Message(msg.header, new CryptoData(Option(sig.sign), msg.crypto.key), msg.body)
}
@throws[InvalidKeyException]
private[core] def verify(msg: messages.Message, key: Option[PublicKey] = None): Boolean = {
private[core] def verify(msg: Message, key: Option[PublicKey] = None): Boolean = {
val sig = Signature.getInstance(SigningAlgorithm)
lazy val defaultKey = loadKey(msg.header.origin.toString, classOf[PublicKey])
sig.initVerify(key.getOrElse(defaultKey))
@ -241,11 +241,11 @@ class Crypto(settings: SettingsInterface, keyFolder: File) {
}
}
private[core] def encryptAndSign(msg: messages.Message, key: Option[PublicKey] = None): messages.Message = {
private[core] def encryptAndSign(msg: Message, key: Option[PublicKey] = None): Message = {
sign(encrypt(msg, key))
}
private def encrypt(msg: messages.Message, key: Option[PublicKey] = None): messages.Message = {
private def encrypt(msg: Message, key: Option[PublicKey] = None): Message = {
// Symmetric encryption of data
val secretKey = makeSecretKey()
val symmetricCipher = Cipher.getInstance(SymmetricKeyAlgorithm)
@ -257,12 +257,12 @@ class Crypto(settings: SettingsInterface, keyFolder: File) {
lazy val defaultKey = loadKey(msg.header.target.toString, classOf[PublicKey])
asymmetricCipher.init(Cipher.WRAP_MODE, key.getOrElse(defaultKey))
new messages.Message(msg.header,
new Message(msg.header,
new CryptoData(None, Option(asymmetricCipher.wrap(secretKey))), encrypted)
}
@throws[InvalidKeyException]
def decrypt(msg: messages.Message): messages.Message = {
def decrypt(msg: Message): Message = {
// Asymmetric decryption of secret key
val asymmetricCipher = Cipher.getInstance(CipherAlgorithm)
asymmetricCipher.init(Cipher.UNWRAP_MODE, loadKey(PrivateKeyAlias, classOf[PrivateKey]))
@ -275,9 +275,9 @@ class Crypto(settings: SettingsInterface, keyFolder: File) {
val body = msg.header.asInstanceOf[ContentHeader].contentType match {
case Text.Type => Text.read(decrypted)
case UserInfo.Type => UserInfo.read(decrypted)
case messages.body.MessageReceived.Type => messages.body.MessageReceived.read(decrypted)
case MessageReceived.Type => MessageReceived.read(decrypted)
}
new messages.Message(msg.header, msg.crypto, body)
new Message(msg.header, msg.crypto, body)
}
/**
@ -315,10 +315,10 @@ class Crypto(settings: SettingsInterface, keyFolder: File) {
/**
* Generates the address by hashing the given public key with [[KeyHashAlgorithm]].
*/
def calculateAddress(key: PublicKey): routing.Address = {
def calculateAddress(key: PublicKey): Address = {
val md = MessageDigest.getInstance(KeyHashAlgorithm)
val hash = md.digest(key.getEncoded)
new routing.Address(hash)
new Address(hash)
}
/**