session-ios/SignalServiceKit/src/Loki/API/LokiAPI.swift

337 lines
17 KiB
Swift
Raw Normal View History

2019-04-30 06:27:39 +02:00
import PromiseKit
@objc(LKAPI)
public final class LokiAPI : NSObject {
private static var lastDeviceLinkUpdate: [String:Date] = [:] // Hex encoded public key to date
2019-10-09 01:37:44 +02:00
@objc static var userIDCache: [String:Set<String>] = [:] // Thread ID to set of user hex encoded public keys
2019-04-30 06:27:39 +02:00
2019-09-17 01:56:47 +02:00
// MARK: Convenience
2019-09-26 03:32:47 +02:00
internal static let storage = OWSPrimaryStorage.shared()
internal static let userHexEncodedPublicKey = OWSIdentityManager.shared().identityKeyPair()!.hexEncodedPublicKey
2019-06-12 06:44:28 +02:00
2019-05-21 05:44:46 +02:00
// MARK: Settings
2019-05-08 01:29:07 +02:00
private static let version = "v1"
2019-09-18 08:59:11 +02:00
private static let maxRetryCount: UInt = 8
2019-06-18 08:01:53 +02:00
private static let defaultTimeout: TimeInterval = 20
2019-06-12 06:23:01 +02:00
private static let longPollingTimeout: TimeInterval = 40
private static let deviceLinkUpdateInterval: TimeInterval = 8 * 60
2019-10-09 01:37:44 +02:00
private static let receivedMessageHashValuesKey = "receivedMessageHashValuesKey"
private static let receivedMessageHashValuesCollection = "receivedMessageHashValuesCollection"
private static var userIDScanLimit: UInt = 4096
2019-10-04 06:52:59 +02:00
internal static var powDifficulty: UInt = 4
2019-10-09 01:37:44 +02:00
public static let defaultMessageTTL: UInt64 = 24 * 60 * 60 * 1000
2019-04-30 06:27:39 +02:00
// MARK: Types
2019-05-07 05:53:31 +02:00
public typealias RawResponse = Any
2019-04-30 06:27:39 +02:00
2019-05-07 02:10:15 +02:00
public enum Error : LocalizedError {
2019-05-22 08:04:51 +02:00
/// Only applicable to snode targets as proof of work isn't required for P2P messaging.
2019-05-07 02:10:15 +02:00
case proofOfWorkCalculationFailed
2019-05-27 04:26:37 +02:00
case messageConversionFailed
2019-05-07 02:10:15 +02:00
public var errorDescription: String? {
switch self {
case .proofOfWorkCalculationFailed: return NSLocalizedString("Failed to calculate proof of work.", comment: "")
2019-05-27 04:26:37 +02:00
case .messageConversionFailed: return "Failed to convert Signal message to Loki message."
2019-05-07 02:10:15 +02:00
}
}
}
2019-09-30 04:08:55 +02:00
@objc(LKDestination)
public final class Destination : NSObject {
@objc public let hexEncodedPublicKey: String
@objc(kind)
public let objc_kind: String
public var kind: Kind {
return Kind(rawValue: objc_kind)!
}
2019-09-30 04:08:55 +02:00
public enum Kind : String { case master, slave }
public init(hexEncodedPublicKey: String, kind: Kind) {
self.hexEncodedPublicKey = hexEncodedPublicKey
self.objc_kind = kind.rawValue
}
@objc public init(hexEncodedPublicKey: String, kind: String) {
self.hexEncodedPublicKey = hexEncodedPublicKey
self.objc_kind = kind
}
2019-10-03 08:46:08 +02:00
override public func isEqual(_ other: Any?) -> Bool {
guard let other = other as? Destination else { return false }
return hexEncodedPublicKey == other.hexEncodedPublicKey && kind == other.kind
}
override public var hash: Int { // Override NSObject.hash and not Hashable.hashValue or Hashable.hash(into:)
return hexEncodedPublicKey.hashValue ^ kind.hashValue
}
override public var description: String { return "\(kind.rawValue)(\(hexEncodedPublicKey))" }
}
2019-05-28 01:57:54 +02:00
public typealias MessageListPromise = Promise<[SSKProtoEnvelope]>
public typealias RawResponsePromise = Promise<RawResponse>
2019-05-27 02:27:49 +02:00
2019-04-30 06:27:39 +02:00
// MARK: Lifecycle
2019-05-06 08:13:32 +02:00
override private init() { }
2019-04-30 06:27:39 +02:00
2019-05-21 05:26:51 +02:00
// MARK: Internal API
2019-06-12 06:23:01 +02:00
internal static func invoke(_ method: LokiAPITarget.Method, on target: LokiAPITarget, associatedWith hexEncodedPublicKey: String,
parameters: [String:Any], headers: [String:String]? = nil, timeout: TimeInterval? = nil) -> RawResponsePromise {
2019-06-26 07:09:03 +02:00
let url = URL(string: "\(target.address):\(target.port)/storage_rpc/\(version)")!
2019-06-12 06:23:01 +02:00
let request = TSRequest(url: url, method: "POST", parameters: [ "method" : method.rawValue, "params" : parameters ])
if let headers = headers { request.allHTTPHeaderFields = headers }
2019-06-18 03:27:19 +02:00
request.timeoutInterval = timeout ?? defaultTimeout
2019-06-13 06:34:19 +02:00
let headers = request.allHTTPHeaderFields ?? [:]
let headersDescription = headers.isEmpty ? "no custom headers specified" : headers.prettifiedDescription
print("[Loki] Invoking \(method.rawValue) on \(target) with \(parameters.prettifiedDescription) (\(headersDescription)).")
2019-06-12 06:23:01 +02:00
return TSNetworkManager.shared().makePromise(request: request).map { $0.responseObject }
.handlingSwarmSpecificErrorsIfNeeded(for: target, associatedWith: hexEncodedPublicKey).recoveringNetworkErrorsIfNeeded()
2019-06-12 04:36:34 +02:00
}
2019-06-12 06:44:28 +02:00
internal static func getRawMessages(from target: LokiAPITarget, usingLongPolling useLongPolling: Bool) -> RawResponsePromise {
2019-06-11 08:22:35 +02:00
let lastHashValue = getLastMessageHashValue(for: target) ?? ""
2019-07-25 05:09:22 +02:00
let parameters = [ "pubKey" : userHexEncodedPublicKey, "lastHash" : lastHashValue ]
2019-06-12 06:23:01 +02:00
let headers: [String:String]? = useLongPolling ? [ "X-Loki-Long-Poll" : "true" ] : nil
let timeout: TimeInterval? = useLongPolling ? longPollingTimeout : nil
2019-07-25 05:09:22 +02:00
return invoke(.getMessages, on: target, associatedWith: userHexEncodedPublicKey, parameters: parameters, headers: headers, timeout: timeout)
}
2019-09-30 04:08:55 +02:00
// MARK: Public API
public static func getMessages() -> Promise<Set<MessageListPromise>> {
return getTargetSnodes(for: userHexEncodedPublicKey).mapValues { targetSnode in
return getRawMessages(from: targetSnode, usingLongPolling: false).map { parseRawMessagesResponse($0, from: targetSnode) }
}.map { Set($0) }.retryingIfNeeded(maxRetryCount: maxRetryCount)
}
public static func getDestinations(for hexEncodedPublicKey: String) -> Promise<[Destination]> {
let (promise, seal) = Promise<[Destination]>.pending()
func getDestinations() {
storage.dbReadConnection.read { transaction in
var destinations: [Destination] = []
let masterHexEncodedPublicKey = storage.getMasterHexEncodedPublicKey(for: hexEncodedPublicKey, in: transaction) ?? hexEncodedPublicKey
let masterDestination = Destination(hexEncodedPublicKey: masterHexEncodedPublicKey, kind: .master)
destinations.append(masterDestination)
let deviceLinks = storage.getDeviceLinks(for: masterHexEncodedPublicKey, in: transaction)
let slaveDestinations = deviceLinks.map { Destination(hexEncodedPublicKey: $0.slave.hexEncodedPublicKey, kind: .slave) }
destinations.append(contentsOf: slaveDestinations)
destinations = destinations.filter { $0.hexEncodedPublicKey != userHexEncodedPublicKey }
seal.fulfill(destinations)
}
}
let timeSinceLastUpdate: TimeInterval
if let lastDeviceLinkUpdate = lastDeviceLinkUpdate[hexEncodedPublicKey] {
timeSinceLastUpdate = Date().timeIntervalSince(lastDeviceLinkUpdate)
} else {
timeSinceLastUpdate = .infinity
}
if timeSinceLastUpdate > deviceLinkUpdateInterval {
storage.dbReadConnection.read { transaction in
let masterHexEncodedPublicKey = storage.getMasterHexEncodedPublicKey(for: hexEncodedPublicKey, in: transaction) ?? hexEncodedPublicKey
2019-10-08 01:48:12 +02:00
LokiStorageAPI.getDeviceLinks(associatedWith: masterHexEncodedPublicKey).done { _ in
getDestinations()
lastDeviceLinkUpdate[hexEncodedPublicKey] = Date()
}.catch { error in
if case LokiDotNetAPI.Error.parsingFailed = error {
2019-10-08 03:22:11 +02:00
// Don't immediately re-fetch in case of failure due to a parsing error
2019-10-08 01:48:12 +02:00
lastDeviceLinkUpdate[hexEncodedPublicKey] = Date()
2019-10-08 03:22:11 +02:00
getDestinations()
2019-10-08 01:48:12 +02:00
} else {
seal.reject(error)
}
}
2019-09-30 04:08:55 +02:00
}
} else {
getDestinations()
}
return promise
}
public static func sendSignalMessage(_ signalMessage: SignalMessage, onP2PSuccess: @escaping () -> Void) -> Promise<Set<RawResponsePromise>> {
2019-06-12 06:44:28 +02:00
guard let lokiMessage = LokiMessage.from(signalMessage: signalMessage) else { return Promise(error: Error.messageConversionFailed) }
2019-05-27 04:26:37 +02:00
let destination = lokiMessage.destination
2019-06-12 06:44:28 +02:00
func sendLokiMessage(_ lokiMessage: LokiMessage, to target: LokiAPITarget) -> RawResponsePromise {
2019-05-27 04:26:37 +02:00
let parameters = lokiMessage.toJSON()
2019-05-27 04:50:30 +02:00
return invoke(.sendMessage, on: target, associatedWith: destination, parameters: parameters)
}
func sendLokiMessageUsingSwarmAPI() -> Promise<Set<RawResponsePromise>> {
2019-08-02 01:28:04 +02:00
return lokiMessage.calculatePoW().then { lokiMessageWithPoW in
return getTargetSnodes(for: destination).map { swarm in
return Set(swarm.map { target in
sendLokiMessage(lokiMessageWithPoW, to: target).map { rawResponse in
if let json = rawResponse as? JSON, let powDifficulty = json["difficulty"] as? Int {
guard powDifficulty != LokiAPI.powDifficulty else { return rawResponse }
print("[Loki] Setting proof of work difficulty to \(powDifficulty).")
LokiAPI.powDifficulty = UInt(powDifficulty)
} else {
print("[Loki] Failed to update proof of work difficulty from: \(rawResponse).")
}
return rawResponse
2019-06-14 02:04:07 +02:00
}
2019-08-02 01:28:04 +02:00
})
}.retryingIfNeeded(maxRetryCount: maxRetryCount)
}
}
if let peer = LokiP2PAPI.getInfo(for: destination), (lokiMessage.isPing || peer.isOnline) {
2019-06-12 03:55:01 +02:00
let target = LokiAPITarget(address: peer.address, port: peer.port)
2019-05-27 05:50:22 +02:00
return Promise.value([ target ]).mapValues { sendLokiMessage(lokiMessage, to: $0) }.map { Set($0) }.retryingIfNeeded(maxRetryCount: maxRetryCount).get { _ in
LokiP2PAPI.markOnline(destination)
2019-05-27 07:06:54 +02:00
onP2PSuccess()
}.recover { error -> Promise<Set<RawResponsePromise>> in
LokiP2PAPI.markOffline(destination)
2019-05-27 04:26:37 +02:00
if lokiMessage.isPing {
2019-06-13 06:34:19 +02:00
print("[Loki] Failed to ping \(destination); marking contact as offline.")
2019-05-27 08:30:28 +02:00
if let error = error as? NSError {
error.isRetryable = false
throw error
2019-05-27 04:26:37 +02:00
} else {
throw error
}
2019-05-24 08:07:00 +02:00
}
2019-05-27 07:06:54 +02:00
return sendLokiMessageUsingSwarmAPI()
2019-05-24 08:07:00 +02:00
}
2019-05-27 04:26:37 +02:00
} else {
2019-05-27 07:06:54 +02:00
return sendLokiMessageUsingSwarmAPI()
}
2019-05-22 08:04:51 +02:00
}
2019-09-30 04:08:55 +02:00
// MARK: Public API (Obj-C)
@objc(getDestinationsFor:)
public static func objc_getDestinations(for hexEncodedPublicKey: String) -> AnyPromise {
let promise = getDestinations(for: hexEncodedPublicKey)
return AnyPromise.from(promise)
}
@objc(sendSignalMessage:onP2PSuccess:)
public static func objc_sendSignalMessage(_ signalMessage: SignalMessage, onP2PSuccess: @escaping () -> Void) -> AnyPromise {
let promise = sendSignalMessage(signalMessage, onP2PSuccess: onP2PSuccess).mapValues { AnyPromise.from($0) }.map { Set($0) }
2019-05-27 04:26:37 +02:00
return AnyPromise.from(promise)
2019-05-08 02:04:19 +02:00
}
// MARK: Parsing
// The parsing utilities below use a best attempt approach to parsing; they warn for parsing failures but don't throw exceptions.
2019-06-12 06:23:01 +02:00
internal static func parseRawMessagesResponse(_ rawResponse: Any, from target: LokiAPITarget) -> [SSKProtoEnvelope] {
guard let json = rawResponse as? JSON, let rawMessages = json["messages"] as? [JSON] else { return [] }
updateLastMessageHashValueIfPossible(for: target, from: rawMessages)
let newRawMessages = removeDuplicates(from: rawMessages)
2019-07-25 05:09:22 +02:00
let newMessages = parseProtoEnvelopes(from: newRawMessages)
let newMessageCount = newMessages.count
if newMessageCount == 1 {
print("[Loki] Retrieved 1 new message.")
} else if (newMessageCount != 0) {
print("[Loki] Retrieved \(newMessageCount) new messages.")
}
return newMessages
2019-06-12 06:23:01 +02:00
}
2019-06-12 03:55:01 +02:00
private static func updateLastMessageHashValueIfPossible(for target: LokiAPITarget, from rawMessages: [JSON]) {
2019-06-12 06:23:01 +02:00
if let lastMessage = rawMessages.last, let hashValue = lastMessage["hash"] as? String, let expirationDate = lastMessage["expiration"] as? Int {
2019-06-12 06:44:28 +02:00
setLastMessageHashValue(for: target, hashValue: hashValue, expirationDate: UInt64(expirationDate))
2019-06-12 06:23:01 +02:00
} else if (!rawMessages.isEmpty) {
2019-06-13 06:34:19 +02:00
print("[Loki] Failed to update last message hash value from: \(rawMessages).")
2019-05-21 07:21:51 +02:00
}
}
private static func removeDuplicates(from rawMessages: [JSON]) -> [JSON] {
var receivedMessageHashValues = getReceivedMessageHashValues() ?? []
return rawMessages.filter { rawMessage in
guard let hashValue = rawMessage["hash"] as? String else {
2019-06-13 06:34:19 +02:00
print("[Loki] Missing hash value for message: \(rawMessage).")
return false
}
let isDuplicate = receivedMessageHashValues.contains(hashValue)
receivedMessageHashValues.insert(hashValue)
setReceivedMessageHashValues(to: receivedMessageHashValues)
return !isDuplicate
}
2019-05-21 07:21:51 +02:00
}
private static func parseProtoEnvelopes(from rawMessages: [JSON]) -> [SSKProtoEnvelope] {
return rawMessages.compactMap { rawMessage in
guard let base64EncodedData = rawMessage["data"] as? String, let data = Data(base64Encoded: base64EncodedData) else {
2019-06-13 06:34:19 +02:00
print("[Loki] Failed to decode data for message: \(rawMessage).")
2019-05-21 05:26:51 +02:00
return nil
}
guard let envelope = try? LokiMessageWrapper.unwrap(data: data) else {
2019-06-13 06:34:19 +02:00
print("[Loki] Failed to unwrap data for message: \(rawMessage).")
2019-05-21 05:26:51 +02:00
return nil
}
return envelope
}
}
2019-08-29 07:52:51 +02:00
2019-10-09 01:37:44 +02:00
// MARK: Message Hash Caching
2019-08-29 07:52:51 +02:00
private static func getLastMessageHashValue(for target: LokiAPITarget) -> String? {
var result: String? = nil
// Uses a read/write connection because getting the last message hash value also removes expired messages as needed
// TODO: This shouldn't be the case; a getter shouldn't have an unexpected side effect
storage.dbReadWriteConnection.readWrite { transaction in
result = storage.getLastMessageHash(forServiceNode: target.address, transaction: transaction)
}
return result
}
private static func setLastMessageHashValue(for target: LokiAPITarget, hashValue: String, expirationDate: UInt64) {
storage.dbReadWriteConnection.readWrite { transaction in
storage.setLastMessageHash(forServiceNode: target.address, hash: hashValue, expiresAt: expirationDate, transaction: transaction)
}
}
private static func getReceivedMessageHashValues() -> Set<String>? {
var result: Set<String>? = nil
storage.dbReadConnection.read { transaction in
result = transaction.object(forKey: receivedMessageHashValuesKey, inCollection: receivedMessageHashValuesCollection) as! Set<String>?
}
return result
}
private static func setReceivedMessageHashValues(to receivedMessageHashValues: Set<String>) {
storage.dbReadWriteConnection.readWrite { transaction in
transaction.setObject(receivedMessageHashValues, forKey: receivedMessageHashValuesKey, inCollection: receivedMessageHashValuesCollection)
}
}
2019-10-08 06:02:03 +02:00
// MARK: User ID Caching
2019-10-09 01:37:44 +02:00
@objc public static func cache(_ userHexEncodedPublicKey: String, for threadID: String) {
if let cache = userIDCache[threadID] {
2019-10-08 06:02:03 +02:00
var mutableCache = cache
mutableCache.insert(userHexEncodedPublicKey)
2019-10-09 01:37:44 +02:00
userIDCache[threadID] = mutableCache
2019-10-08 06:02:03 +02:00
} else {
2019-10-09 01:37:44 +02:00
userIDCache[threadID] = [ userHexEncodedPublicKey ]
}
}
@objc public static func populateUserIDCacheIfNeeded(for threadID: String) {
guard userIDCache[threadID] == nil else { return }
var result: Set<String> = []
storage.dbReadWriteConnection.readWrite { transaction in
guard let thread = TSThread.fetch(uniqueId: threadID, transaction: transaction) else { return }
let interactions = transaction.ext(TSMessageDatabaseViewExtensionName) as! YapDatabaseViewTransaction
interactions.enumerateKeysAndObjects(inGroup: threadID) { _, _, object, index, _ in
guard let message = object as? TSIncomingMessage, index < userIDScanLimit else { return }
result.insert(message.authorId)
}
2019-10-08 06:02:03 +02:00
}
2019-10-09 01:37:44 +02:00
result.insert(userHexEncodedPublicKey)
userIDCache[threadID] = result
2019-10-08 06:02:03 +02:00
}
2019-08-29 07:52:51 +02:00
}
// MARK: Error Handling
private extension Promise {
fileprivate func recoveringNetworkErrorsIfNeeded() -> Promise<T> {
return recover() { error -> Promise<T> in
switch error {
case NetworkManagerError.taskError(_, let underlyingError): throw underlyingError
default: throw error
}
}
}
2019-05-08 08:02:53 +02:00
}