Merge branch 'dev' into push-notifications

This commit is contained in:
gmbnt 2020-03-27 11:56:37 +11:00
commit 9f2df6d560
10 changed files with 71 additions and 31 deletions

View File

@ -4294,7 +4294,7 @@
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
CODE_SIGN_STYLE = Automatic;
COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 64;
CURRENT_PROJECT_VERSION = 65;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = SUQ8J2PCT7;
FRAMEWORK_SEARCH_PATHS = "$(inherited)";
@ -4356,7 +4356,7 @@
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
CODE_SIGN_STYLE = Automatic;
COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 64;
CURRENT_PROJECT_VERSION = 65;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEVELOPMENT_TEAM = SUQ8J2PCT7;
ENABLE_NS_ASSERTIONS = NO;
@ -4410,7 +4410,7 @@
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
CODE_SIGN_STYLE = Automatic;
COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 64;
CURRENT_PROJECT_VERSION = 65;
DEBUG_INFORMATION_FORMAT = dwarf;
DEFINES_MODULE = YES;
DEVELOPMENT_TEAM = SUQ8J2PCT7;
@ -4479,7 +4479,7 @@
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
CODE_SIGN_STYLE = Automatic;
COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 64;
CURRENT_PROJECT_VERSION = 65;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEFINES_MODULE = YES;
DEVELOPMENT_TEAM = SUQ8J2PCT7;
@ -4688,7 +4688,7 @@
CODE_SIGN_ENTITLEMENTS = Signal/Signal.entitlements;
CODE_SIGN_IDENTITY = "iPhone Developer";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
CURRENT_PROJECT_VERSION = 64;
CURRENT_PROJECT_VERSION = 65;
DEVELOPMENT_TEAM = SUQ8J2PCT7;
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
@ -4755,7 +4755,7 @@
CODE_SIGN_ENTITLEMENTS = Signal/Signal.entitlements;
CODE_SIGN_IDENTITY = "iPhone Developer";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
CURRENT_PROJECT_VERSION = 64;
CURRENT_PROJECT_VERSION = 65;
DEVELOPMENT_TEAM = SUQ8J2PCT7;
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",

View File

@ -15,7 +15,7 @@ class BaseVC : UIViewController {
@objc private func handleUnexpectedDeviceLinkRequestReceivedNotification() {
guard DeviceLinkingUtilities.shouldShowUnexpectedDeviceLinkRequestReceivedAlert else { return }
DispatchQueue.main.async {
let alert = UIAlertController(title: "Device Link Request Received", message: "Open the device link screen by going to \"Settings\"> \"Devices\" > \"Link a Device\" to link your devices.", preferredStyle: .alert)
let alert = UIAlertController(title: "Device Link Request Received", message: "Open the device link screen by going to \"Settings\" > \"Devices\" > \"Link a Device\" to link your devices.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}

View File

@ -219,12 +219,12 @@ private extension DeviceLinksVC {
stackView.axis = .vertical
stackView.distribution = .equalCentering
stackView.spacing = Values.verySmallSpacing
stackView.set(.height, to: 36)
stackView.set(.height, to: 44)
contentView.addSubview(stackView)
stackView.pin(.leading, to: .leading, of: contentView, withInset: Values.largeSpacing)
stackView.pin(.top, to: .top, of: contentView, withInset: Values.mediumSpacing)
stackView.pin(.top, to: .top, of: contentView, withInset: 12)
contentView.pin(.trailing, to: .trailing, of: stackView, withInset: Values.largeSpacing)
contentView.pin(.bottom, to: .bottom, of: stackView, withInset: Values.mediumSpacing)
contentView.pin(.bottom, to: .bottom, of: stackView, withInset: 12)
stackView.set(.width, to: UIScreen.main.bounds.width - 2 * Values.largeSpacing)
}

View File

@ -5488,7 +5488,7 @@ typedef enum : NSUInteger {
{
if (!LKDeviceLinkingUtilities.shouldShowUnexpectedDeviceLinkRequestReceivedAlert) { return; }
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Device Link Request Received" message:@"Open the device link screen by going to \"Settings\"> \"Devices\" > \"Link a Device\" to link your devices." preferredStyle:UIAlertControllerStyleAlert];
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Device Link Request Received" message:@"Open the device link screen by going to \"Settings\" > \"Devices\" > \"Link a Device\" to link your devices." preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
[self presentViewController:alert animated:YES completion:nil];
});

View File

@ -352,7 +352,7 @@ public class SystemContactsFetcher: NSObject {
guard let contacts = fetchedContacts else {
owsFailDebug("contacts was unexpectedly not set.")
completion(nil)
return completion(nil)
}
Logger.info("fetched \(contacts.count) contacts.")

View File

@ -1,14 +1,14 @@
import PromiseKit
public extension LokiAPI {
private static var snodeVersion: [LokiAPITarget:String] = [:]
/// Only ever accessed from `LokiAPI.errorHandlingQueue` to avoid race conditions.
fileprivate static var failureCount: [LokiAPITarget:UInt] = [:]
// MARK: Settings
private static let minimumSnodeCount = 2
private static let targetSnodeCount = 3
private static let maxRandomSnodePoolSize = 1024
fileprivate static let failureThreshold = 2
// MARK: Caching
@ -37,10 +37,9 @@ public extension LokiAPI {
let target = seedNodePool.randomElement()!
let url = URL(string: "\(target)/json_rpc")!
let request = TSRequest(url: url, method: "POST", parameters: [
"method" : "get_n_service_nodes",
"method" : "get_service_nodes",
"params" : [
"active_only" : true,
"limit" : maxRandomSnodePoolSize,
"fields" : [
"public_ip" : true,
"storage_port" : true,
@ -49,7 +48,7 @@ public extension LokiAPI {
]
]
])
print("[Loki] Invoking get_n_service_nodes on \(target).")
print("[Loki] Invoking get_service_nodes on \(target).")
return TSNetworkManager.shared().perform(request, withCompletionQueue: DispatchQueue.global()).map(on: DispatchQueue.global()) { intermediate in
let rawResponse = intermediate.responseObject
guard let json = rawResponse as? JSON, let intermediate = json["result"] as? JSON, let rawTargets = intermediate["service_node_states"] as? [JSON] else { throw LokiAPIError.randomSnodePoolUpdatingFailed }
@ -84,11 +83,47 @@ public extension LokiAPI {
}
}
// MARK: Public API
internal static func getTargetSnodes(for hexEncodedPublicKey: String) -> Promise<[LokiAPITarget]> {
// shuffled() uses the system's default random generator, which is cryptographically secure
return getSwarm(for: hexEncodedPublicKey).map { Array($0.shuffled().prefix(targetSnodeCount)) }
}
internal static func getFileServerProxy() -> Promise<LokiAPITarget> {
// All of this has to happen on DispatchQueue.global() due to the way OWSMessageManager works
let (promise, seal) = Promise<LokiAPITarget>.pending()
func getVersion(for snode: LokiAPITarget) -> Promise<String> {
if let version = snodeVersion[snode] {
return Promise { $0.fulfill(version) }
} else {
let url = URL(string: "\(snode.address):\(snode.port)/get_stats/v1")!
let request = TSRequest(url: url)
return TSNetworkManager.shared().perform(request, withCompletionQueue: DispatchQueue.global()).map(on: DispatchQueue.global()) { intermediate in
let rawResponse = intermediate.responseObject
guard let json = rawResponse as? JSON, let version = json["version"] as? String else { throw LokiAPIError.missingSnodeVersion }
snodeVersion[snode] = version
return version
}
}
}
getRandomSnode().then(on: DispatchQueue.global()) { snode -> Promise<LokiAPITarget> in
return getVersion(for: snode).then(on: DispatchQueue.global()) { version -> Promise<LokiAPITarget> in
if version >= "2.0.2" {
print("[Loki] Using file server proxy with version number \(version).")
return Promise { $0.fulfill(snode) }
} else {
print("[Loki] Rejecting file server proxy with version number \(version).")
return getFileServerProxy()
}
}.recover(on: DispatchQueue.global()) { error in
return getFileServerProxy()
}
}.done(on: DispatchQueue.global()) { snode in
seal.fulfill(snode)
}.catch(on: DispatchQueue.global()) { error in
seal.reject(error)
}
return promise
}
// MARK: Parsing
private static func parseTargets(from rawResponse: Any) -> [LokiAPITarget] {

View File

@ -2,10 +2,12 @@ import PromiseKit
@objc(LKAPI)
public final class LokiAPI : NSObject {
private static let stateQueue = DispatchQueue(label: "stateQueue")
/// Only ever modified from the message processing queue (`OWSBatchMessageProcessor.processingQueue`).
private static var syncMessageTimestamps: [String:Set<UInt64>] = [:]
public static var _lastDeviceLinkUpdate: [String:Date] = [:]
private static var _lastDeviceLinkUpdate: [String:Date] = [:]
/// A mapping from hex encoded public key to date updated.
public static var lastDeviceLinkUpdate: [String:Date] {
get { stateQueue.sync { _lastDeviceLinkUpdate } }
@ -19,8 +21,6 @@ public final class LokiAPI : NSObject {
set { stateQueue.sync { _userHexEncodedPublicKeyCache = newValue } }
}
private static let stateQueue = DispatchQueue(label: "stateQueue")
/// All service node related errors must be handled on this queue to avoid race conditions maintaining e.g. failure counts.
public static let errorHandlingQueue = DispatchQueue(label: "errorHandlingQueue")
@ -47,6 +47,7 @@ public final class LokiAPI : NSObject {
@objc public static let messageConversionFailed = LokiAPIError(domain: "LokiAPIErrorDomain", code: 2, userInfo: [ NSLocalizedDescriptionKey : "Failed to construct message." ])
@objc public static let clockOutOfSync = LokiAPIError(domain: "LokiAPIErrorDomain", code: 3, userInfo: [ NSLocalizedDescriptionKey : "Your clock is out of sync with the service node network." ])
@objc public static let randomSnodePoolUpdatingFailed = LokiAPIError(domain: "LokiAPIErrorDomain", code: 4, userInfo: [ NSLocalizedDescriptionKey : "Failed to update random service node pool." ])
@objc public static let missingSnodeVersion = LokiAPIError(domain: "LokiAPIErrorDomain", code: 5, userInfo: [ NSLocalizedDescriptionKey : "Missing service node version." ])
}
@objc(LKDestination)

View File

@ -50,7 +50,7 @@ internal class LokiFileServerProxy : LokiHTTPClient {
DispatchQueue.global().async {
let uncheckedSymmetricKey = try? Curve25519.generateSharedSecret(fromPublicKey: LokiFileServerProxy.fileServerPublicKey, privateKey: keyPair.privateKey)
guard let symmetricKey = uncheckedSymmetricKey else { return seal.reject(Error.symmetricKeyGenerationFailed) }
LokiAPI.getRandomSnode().then(on: DispatchQueue.global()) { proxy -> Promise<Any> in
LokiAPI.getFileServerProxy().then(on: DispatchQueue.global()) { proxy -> Promise<Any> in
let url = "\(proxy.address):\(proxy.port)/file_proxy"
guard let urlAsString = request.url?.absoluteString, let serverURLEndIndex = urlAsString.range(of: server)?.upperBound,
serverURLEndIndex < urlAsString.endIndex else { throw Error.endpointParsingFailed }

View File

@ -9,7 +9,6 @@ public final class LokiPoller : NSObject {
private var usedSnodes = Set<LokiAPITarget>()
// MARK: Settings
private static let pollInterval: TimeInterval = 1
private static let retryInterval: TimeInterval = 4
// MARK: Initialization
@ -24,7 +23,7 @@ public final class LokiPoller : NSObject {
print("[Loki] Started polling.")
hasStarted = true
hasStopped = false
openConnections()
setUpPolling()
}
@objc public func stopIfNeeded() {
@ -36,7 +35,7 @@ public final class LokiPoller : NSObject {
}
// MARK: Private API
private func openConnections() {
private func setUpPolling() {
guard !hasStopped else { return }
LokiAPI.getSwarm(for: getUserHexEncodedPublicKey()).then { [weak self] _ -> Promise<Void> in
guard let strongSelf = self else { return Promise { $0.fulfill(()) } }
@ -45,10 +44,10 @@ public final class LokiPoller : NSObject {
strongSelf.pollNextSnode(seal: seal)
return promise
}.ensure { [weak self] in
guard let strongSelf = self else { return }
guard let strongSelf = self, !strongSelf.hasStopped else { return }
Timer.scheduledTimer(withTimeInterval: LokiPoller.retryInterval, repeats: false) { _ in
guard let strongSelf = self else { return }
strongSelf.openConnections()
strongSelf.setUpPolling()
}
}
}
@ -62,7 +61,9 @@ public final class LokiPoller : NSObject {
let nextSnode = unusedSnodes.randomElement()!
usedSnodes.insert(nextSnode)
print("[Loki] Polling \(nextSnode).")
poll(nextSnode, seal: seal).catch(on: LokiAPI.errorHandlingQueue) { [weak self] error in
poll(nextSnode, seal: seal).done(on: DispatchQueue.global()) {
seal.fulfill(())
}.catch(on: LokiAPI.errorHandlingQueue) { [weak self] error in
print("[Loki] Polling \(nextSnode) failed; dropping it and switching to next snode.")
LokiAPI.dropIfNeeded(nextSnode, hexEncodedPublicKey: userHexEncodedPublicKey)
self?.pollNextSnode(seal: seal)
@ -72,12 +73,12 @@ public final class LokiPoller : NSObject {
}
}
private func poll(_ target: LokiAPITarget, seal: Resolver<Void>) -> Promise<Void> {
private func poll(_ target: LokiAPITarget, seal longTermSeal: Resolver<Void>) -> Promise<Void> {
return LokiAPI.getRawMessages(from: target, usingLongPolling: false).then(on: DispatchQueue.global()) { [weak self] rawResponse -> Promise<Void> in
guard let strongSelf = self, !strongSelf.hasStopped else { return Promise.value(()) }
guard let strongSelf = self, !strongSelf.hasStopped else { return Promise { $0.fulfill(()) } }
let messages = LokiAPI.parseRawMessagesResponse(rawResponse, from: target)
strongSelf.onMessagesReceived(messages)
return strongSelf.poll(target, seal: seal)
return strongSelf.poll(target, seal: longTermSeal)
}
}
}

View File

@ -194,6 +194,9 @@ NSString *const kNSNotificationName_IsCensorshipCircumventionActiveDidChange =
sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
sessionManager.requestSerializer.HTTPShouldHandleCookies = NO;
sessionManager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
NSMutableSet<NSString *> *acceptableContentTypes = sessionManager.responseSerializer.acceptableContentTypes.mutableCopy;
[acceptableContentTypes addObject:@"text/plain"];
sessionManager.responseSerializer.acceptableContentTypes = acceptableContentTypes;
return sessionManager;
}