Merge pull request #27 from loki-project/clearnet

Clearnet Changes
pull/33/head
gamabuntan 6 years ago committed by GitHub
commit a7e3a2b534
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -332,13 +332,13 @@ static NSTimeInterval launchStartedAt;
if ([serverURLDescription hasSuffix:@"/"]) {
serverURLDescription = [serverURLDescription substringToIndex:serverURLDescription.length - 1];
}
OWSLogInfo(@"[Loki] Started server at %@.", serverURLDescription);
NSLog(@"[Loki] Started server at %@.", serverURLDescription);
break;
}
}
if (!self.lokiP2PServer.isRunning) {
OWSLogWarn(@"[Loki] Failed to start P2P server.");
NSLog(@"[Loki] Failed to start P2P server.");
}
return YES;
@ -1416,7 +1416,7 @@ static NSTimeInterval launchStartedAt;
- (void)handleNewMessagesReceived:(NSNotification *)notification
{
NSArray *messages = (NSArray *)notification.userInfo[@"messages"];
OWSLogInfo(@"[Loki] Received %lu messages through long polling.", messages.count);
NSLog(@"[Loki] Received %lu messages through long polling.", messages.count);
for (SSKProtoEnvelope *envelope in messages) {
NSData *envelopeData = envelope.serializedDataIgnoringErrors;

@ -147,7 +147,7 @@ public class SessionResetOperation: OWSOperation, DurableOperation {
message.save(with: transaction)
// Loki: We have initiated a session reset
Logger.debug("[Loki] Session reset initiated.")
print("[Loki] Session reset initiated.")
self.contactThread.sessionResetState = .initiated
self.contactThread.save(with: transaction)
}

@ -25,7 +25,7 @@ private extension GCDWebServerDataRequest {
let object = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
return object as? JSON
} catch let error {
Logger.debug("[Loki] Failed to serialize JSON: \(error).")
print("[Loki] Failed to serialize JSON: \(error).")
}
return nil

@ -451,6 +451,7 @@ NS_ASSUME_NONNULL_BEGIN
return sectionIndex;
};
/** Loki: Original code
contents.sectionIndexTitlesForTableViewBlock = ^NSArray<NSString *> *_Nonnull
{
typeof(self) strongSelf = weakSelf;
@ -460,6 +461,7 @@ NS_ASSUME_NONNULL_BEGIN
return strongSelf.collation.sectionTitles;
};
*/
}
self.tableViewController.contents = contents;

@ -40,9 +40,11 @@ static double const STALLED_PROGRESS = 0.9;
_socketStatusView.progress = 0.0f;
_socketStatusView.progressTintColor = [UIColor ows_fadedBlueColor];
/** Loki: Original code
if (![_socketStatusView superview]) {
[self.navigationBar addSubview:_socketStatusView];
}
*/
}
- (void)dealloc

@ -36,7 +36,7 @@ public class CreatePreKeysOperation: OWSOperation {
self.primaryStorage.storeSignedPreKey(signedPreKeyRecord.id, signedPreKeyRecord: signedPreKeyRecord)
self.primaryStorage.setCurrentSignedPrekeyId(signedPreKeyRecord.id)
Logger.debug("[CreatePreKeysOperation] done")
print("[Loki] Create pre keys operation done.")
self.reportSuccess()
/* Loki: Original code

@ -52,7 +52,7 @@ public class RefreshPreKeysOperation: OWSOperation {
TSPreKeyManager.clearPreKeyUpdateFailureCount()
TSPreKeyManager.clearSignedPreKeyRecords()
Logger.debug("[PreKeyRefreshOperation] done")
print("[Loki] Pre key refresh operation done.")
self.reportSuccess()
}

@ -37,7 +37,7 @@ public class RotateSignedPreKeyOperation: OWSOperation {
TSPreKeyManager.clearPreKeyUpdateFailureCount()
TSPreKeyManager.clearSignedPreKeyRecords()
Logger.debug("[RotateSignedKeyOperation] done")
print("[Loki] Rotate signed pre key operation done.")
self.reportSuccess()
}

@ -768,7 +768,7 @@ ConversationColorName const kConversationColorName_Default = ConversationColorNa
- (void)saveFriendRequestStatus:(LKThreadFriendRequestStatus)friendRequestStatus withTransaction:(YapDatabaseReadWriteTransaction *_Nullable)transaction
{
self.friendRequestStatus = friendRequestStatus;
OWSLogInfo(@"[Loki] Setting thread friend request status to %@.", self.friendRequestStatusDescription);
NSLog(@"[Loki] Setting thread friend request status to %@.", self.friendRequestStatusDescription);
void (^postNotification)() = ^() {
[NSNotificationCenter.defaultCenter postNotificationName:NSNotification.threadFriendRequestStatusChanged object:self.uniqueId];
};

@ -15,7 +15,7 @@ public extension LokiAPI {
isLongPolling = true
shouldStopPolling = false
Logger.info("[Loki] Started long polling.")
print("[Loki] Started long polling.")
longPoll()
}
@ -27,7 +27,7 @@ public extension LokiAPI {
usedSnodes.removeAll()
cancelAllPromises()
Logger.info("[Loki] Stopped long polling.")
print("[Loki] Stopped long polling.")
}
/// The long polling loop

@ -1,10 +1,12 @@
import PromiseKit
extension String : Error { }
public extension LokiAPI {
// MARK: Settings
private static let minimumSnodeCount = 2 // TODO: For debugging purposes
private static let targetSnodeCount = 3 // TODO: For debugging purposes
private static let minimumSnodeCount = 2
private static let targetSnodeCount = 3
private static let defaultSnodePort: UInt16 = 8080
// MARK: Caching
@ -34,10 +36,28 @@ public extension LokiAPI {
}
}
// MARK: Clearnet Setup
private static var randomSnodePool: Set<LokiAPITarget> = []
// MARK: Internal API
private static func getRandomSnode() -> Promise<LokiAPITarget> {
return Promise<LokiAPITarget> { seal in
seal.fulfill(LokiAPITarget(address: "http://13.236.173.190", port: defaultSnodePort)) // TODO: For debugging purposes
if randomSnodePool.isEmpty {
let url = URL(string: "http://3.104.19.14:22023/json_rpc")!
let request = TSRequest(url: url, method: "POST", parameters: [ "method" : "get_service_nodes" ])
print("[Loki] Invoking get_service_nodes on http://3.104.19.14:22023.")
return TSNetworkManager.shared().makePromise(request: request).map { 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 "Failed to update random snode pool from: \(rawResponse)." }
randomSnodePool = try Set(rawTargets.flatMap { rawTarget in
guard let address = rawTarget["public_ip"] as? String, let port = rawTarget["storage_port"] as? Int else { throw "Failed to update random snode pool from: \(rawTarget)." }
return LokiAPITarget(address: "https://\(address)", port: UInt16(port))
})
return randomSnodePool.randomElement()!
}
} else {
return Promise<LokiAPITarget> { seal in
seal.fulfill(randomSnodePool.randomElement()!)
}
}
}
@ -58,16 +78,17 @@ public extension LokiAPI {
// MARK: Parsing
private static func parseTargets(from rawResponse: Any) -> [LokiAPITarget] {
// TODO: For debugging purposes
// ========
let target = LokiAPITarget(address: "http://13.236.173.190", port: defaultSnodePort)
return Array(repeating: target, count: 3)
// ========
// guard let json = rawResponse as? JSON, let addresses = json["snodes"] as? [String] else {
// Logger.warn("[Loki] Failed to parse targets from: \(rawResponse).")
// return []
// }
// return addresses.map { Target(address: $0, port: defaultSnodePort) }
guard let json = rawResponse as? JSON, let rawSnodes = json["snodes"] as? [JSON] else {
print("[Loki] Failed to parse targets from: \(rawResponse).")
return []
}
return rawSnodes.flatMap { rawSnode in
guard let address = rawSnode["ip"] as? String, let portAsString = rawSnode["port"] as? String, let port = UInt16(portAsString) else {
print("[Loki] Failed to parse target from: \(rawSnode).")
return nil
}
return LokiAPITarget(address: "https://\(address)", port: port)
}
}
}
@ -80,10 +101,10 @@ internal extension Promise {
switch error.statusCode {
case 0:
// The snode is unreachable; usually a problem with LokiNet
Logger.warn("[Loki] Couldn't reach snode at: \(target.address):\(target.port).")
print("[Loki] Couldn't reach snode at: \(target.address):\(target.port).")
case 421:
// The snode isn't associated with the given public key anymore
Logger.warn("[Loki] Invalidating swarm for: \(hexEncodedPublicKey).")
print("[Loki] Invalidating swarm for: \(hexEncodedPublicKey).")
LokiAPI.dropIfNeeded(target, hexEncodedPublicKey: hexEncodedPublicKey)
default: break
}

@ -9,6 +9,7 @@ public final class LokiAPI : NSObject {
// MARK: Settings
private static let version = "v1"
private static let maxRetryCount: UInt = 3
private static let defaultTimeout: TimeInterval = 20
private static let longPollingTimeout: TimeInterval = 40
public static let defaultMessageTTL: UInt64 = 24 * 60 * 60 * 1000
@ -40,7 +41,16 @@ public final class LokiAPI : NSObject {
let url = URL(string: "\(target.address):\(target.port)/\(version)/storage_rpc")!
let request = TSRequest(url: url, method: "POST", parameters: [ "method" : method.rawValue, "params" : parameters ])
if let headers = headers { request.allHTTPHeaderFields = headers }
if let timeout = timeout { request.timeoutInterval = timeout }
if let timeout = timeout { request.timeoutInterval = timeout ?? defaultTimeout }
let headers = request.allHTTPHeaderFields ?? [:]
let headersDescription = headers.isEmpty ? "no custom headers specified" : headers.description
let parametersDescription = "[ " + parameters.map { key, value in
let valueDescription = String(describing: value)
let maxLength = 20
let truncatedValueDescription = valueDescription.count > maxLength ? valueDescription.prefix(maxLength) + "..." : valueDescription
return key + " : " + truncatedValueDescription
}.joined(separator: ", ") + " ]"
print("[Loki] Invoking \(method.rawValue) on \(target) with \(parametersDescription) (\(headersDescription)).")
return TSNetworkManager.shared().makePromise(request: request).map { $0.responseObject }
.handlingSwarmSpecificErrorsIfNeeded(for: target, associatedWith: hexEncodedPublicKey).recoveringNetworkErrorsIfNeeded()
}
@ -82,7 +92,7 @@ public final class LokiAPI : NSObject {
}.recover { error -> Promise<Set<RawResponsePromise>> in
LokiP2PAPI.markOffline(destination)
if lokiMessage.isPing {
Logger.warn("[Loki] Failed to ping \(destination); marking contact as offline.")
print("[Loki] Failed to ping \(destination); marking contact as offline.")
if let error = error as? NSError {
error.isRetryable = false
throw error
@ -119,7 +129,7 @@ public final class LokiAPI : NSObject {
if let lastMessage = rawMessages.last, let hashValue = lastMessage["hash"] as? String, let expirationDate = lastMessage["expiration"] as? Int {
setLastMessageHashValue(for: target, hashValue: hashValue, expirationDate: UInt64(expirationDate))
} else if (!rawMessages.isEmpty) {
Logger.warn("[Loki] Failed to update last message hash value from: \(rawMessages).")
print("[Loki] Failed to update last message hash value from: \(rawMessages).")
}
}
@ -127,7 +137,7 @@ public final class LokiAPI : NSObject {
var receivedMessageHashValues = getReceivedMessageHashValues() ?? []
return rawMessages.filter { rawMessage in
guard let hashValue = rawMessage["hash"] as? String else {
Logger.warn("[Loki] Missing hash value for message: \(rawMessage).")
print("[Loki] Missing hash value for message: \(rawMessage).")
return false
}
let isDuplicate = receivedMessageHashValues.contains(hashValue)
@ -140,11 +150,11 @@ public final class LokiAPI : NSObject {
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 {
Logger.warn("[Loki] Failed to decode data for message: \(rawMessage).")
print("[Loki] Failed to decode data for message: \(rawMessage).")
return nil
}
guard let envelope = try? LokiMessageWrapper.unwrap(data: data) else {
Logger.warn("[Loki] Failed to unwrap data for message: \(rawMessage).")
print("[Loki] Failed to unwrap data for message: \(rawMessage).")
return nil
}
return envelope

@ -29,4 +29,7 @@ internal final class LokiAPITarget : NSObject, NSCoding {
coder.encode(address, forKey: "address")
coder.encode(port, forKey: "port")
}
// MARK: Description
override var description: String { return "https://\(address):\(port)" }
}

@ -39,7 +39,7 @@ public struct LokiMessage {
let isPing = signalMessage.isPing
return LokiMessage(destination: destination, data: data, ttl: ttl, isPing: isPing)
} catch let error {
Logger.debug("[Loki] Failed to convert Signal message to Loki message: \(signalMessage).")
print("[Loki] Failed to convert Signal message to Loki message: \(signalMessage).")
return nil
}
}

@ -48,12 +48,12 @@ public class LokiP2PAPI : NSObject {
}
guard let thread = contactThread else {
Logger.warn("[Loki] Failed to fetch thread when attempting to ping: \(pubKey).")
print("[Loki] Failed to fetch thread when attempting to ping: \(pubKey).")
return
}
guard let message = createLokiAddressMessage(for: thread, isPing: true) else {
Logger.warn("[Loki] Failed to build ping message for \(pubKey).")
print("[Loki] Failed to build ping message for \(pubKey).")
return
}
@ -75,11 +75,11 @@ public class LokiP2PAPI : NSObject {
public static func handleReceivedMessage(base64EncodedData: String) {
guard let data = Data(base64Encoded: base64EncodedData) else {
Logger.warn("[Loki] Failed to decode data for P2P message.")
print("[Loki] Failed to decode data for P2P message.")
return
}
guard let envelope = try? LokiMessageWrapper.unwrap(data: data) else {
Logger.warn("[Loki] Failed to unwrap data for P2P message.")
print("[Loki] Failed to unwrap data for P2P message.")
return
}
// We need to set the P2P field on the envelope
@ -91,7 +91,7 @@ public class LokiP2PAPI : NSObject {
let envelopeData = try newEnvelope.serializedData()
messageReceiver.handleReceivedEnvelopeData(envelopeData)
} catch let error {
Logger.warn("[Loki] Something went wrong during proto conversion: \(error).")
print("[Loki] Something went wrong during proto conversion: \(error).")
}
}
@ -198,7 +198,7 @@ public class LokiP2PAPI : NSObject {
AssertIsOnMainThread()
guard let message = onlineBroadcastMessage(forThread: thread) else {
Logger.warn("[Loki] P2P address not set.")
print("[Loki] P2P address not set.")
return
}
@ -222,7 +222,7 @@ public class LokiP2PAPI : NSObject {
private static func createLokiAddressMessage(for thread: TSThread, isPing: Bool) -> LokiAddressMessage? {
guard let ourAddress = ourP2PAddress else {
Logger.warn("[Loki] P2P address not set.")
print("[Loki] P2P address not set.")
return nil
}

@ -62,7 +62,7 @@
@try {
return [self throws_loadPreKey:preKeyId];
} @catch (NSException *exception) {
OWSLogWarn(@"[Loki] New prekey generated for %@.", pubKey);
NSLog(@"[Loki] New prekey generated for %@.", pubKey);
return [self generateAndStorePreKeyForContact:pubKey];
}
}

@ -140,7 +140,7 @@ public final class FriendRequestExpirationJob : NSObject {
private func timerDidFire(isMainTimer: Bool) {
guard CurrentAppContext().isMainAppAndActive else {
let infoString = isMainTimer ? "Main timer fired while main app is inactive." : "Ignoring fallback timer for app which is not main and active."
Logger.info("[Loki] Friend request expiration job running: \(infoString).")
print("[Loki] Friend request expiration job running: \(infoString).")
return
}

@ -40,7 +40,7 @@ public enum LokiMessageWrapper {
}
return try builder.build()
} catch let error {
Logger.warn("[Loki] Failed to wrap message in envelope: \(error).")
print("[Loki] Failed to wrap message in envelope: \(error).")
throw WrappingError.failedToWrapMessageInEnvelope
}
}
@ -53,7 +53,7 @@ public enum LokiMessageWrapper {
messageBuilder.setRequest(try requestBuilder.build())
return try messageBuilder.build()
} catch let error {
Logger.warn("[Loki] Failed to wrap envelope in web socket message: \(error).")
print("[Loki] Failed to wrap envelope in web socket message: \(error).")
throw WrappingError.failedToWrapEnvelopeInWebSocketMessage
}
}
@ -65,7 +65,7 @@ public enum LokiMessageWrapper {
let envelope = webSocketMessage.request!.body!
return try SSKProtoEnvelope.parseData(envelope)
} catch let error {
Logger.warn("[Loki] Failed to unwrap data: \(error).")
print("[Loki] Failed to unwrap data: \(error).")
throw WrappingError.failedToUnwrapData
}
}

@ -445,7 +445,7 @@ static const NSUInteger OWSMessageSchemaVersion = 4;
- (void)saveFriendRequestStatus:(LKMessageFriendRequestStatus)friendRequestStatus withTransaction:(YapDatabaseReadWriteTransaction *_Nullable)transaction
{
self.friendRequestStatus = friendRequestStatus;
OWSLogInfo(@"[Loki] Setting message friend request status to %@.", self.friendRequestStatusDescription);
NSLog(@"[Loki] Setting message friend request status to %@.", self.friendRequestStatusDescription);
void (^postNotification)() = ^() {
[NSNotificationCenter.defaultCenter postNotificationName:NSNotification.messageFriendRequestStatusChanged object:self.uniqueId];
};

@ -220,11 +220,11 @@ NSError *EnsureDecryptError(NSError *_Nullable error, NSString *fallbackErrorDes
[self decryptFriendRequestMessage:envelope
envelopeData:envelopeData
successBlock:^(OWSMessageDecryptResult *result) {
OWSLogDebug(@"decrypted friend request message.");
OWSLogDebug(@"Decrypted friend request message.");
successBlock(result, transaction);
}
failureBlock:^(NSError * _Nullable error) {
OWSLogError(@"decrypting friend request message from address: %@ failed with error: %@",
OWSLogError(@"Decrypting friend request message from address: %@ failed with error: %@.",
envelopeAddress(envelope),
error);
failureBlock();
@ -333,7 +333,7 @@ NSError *EnsureDecryptError(NSError *_Nullable error, NSString *fallbackErrorDes
NSData *encryptedData = envelope.content;
if (!encryptedData) {
OWSProdFail([OWSAnalyticsEvents messageManagerErrorMessageEnvelopeHasNoContent]);
NSError *error = OWSErrorWithCodeDescription(OWSErrorCodeFailedToDecryptMessage, @"Envelope has no content");
NSError *error = OWSErrorWithCodeDescription(OWSErrorCodeFailedToDecryptMessage, @"Envelope has no content.");
return failureBlock(error);
}
@ -342,7 +342,7 @@ NSError *EnsureDecryptError(NSError *_Nullable error, NSString *fallbackErrorDes
NSData *_Nullable plaintextData = [[cipher decryptWithMessage:encryptedData] removePadding];
if (!plaintextData) {
NSString *errorString = [NSString stringWithFormat:@"Failed to decrypt friend request message for %@", recipientId];
NSString *errorString = [NSString stringWithFormat:@"Failed to decrypt friend request message for: %@.", recipientId];
NSError *error = OWSErrorWithCodeDescription(OWSErrorCodeFailedToDecryptMessage, errorString);
return failureBlock(error);
}

@ -423,12 +423,12 @@ NS_ASSUME_NONNULL_BEGIN
}
OWSLogInfo(@"handling content: <Content: %@>", [self descriptionForContent:contentProto]);
// Loki: Handle PreKeyBundle message
// Loki: Handle pre key bundle message
if (contentProto.prekeyBundleMessage) {
OWSLogInfo(@"Received a prekey bundle message from: %@", envelope.source);
OWSLogInfo(@"Received a pre key bundle message from: %@.", envelope.source);
PreKeyBundle *_Nullable bundle = [contentProto.prekeyBundleMessage createPreKeyBundleWithTransaction:transaction];
if (!bundle) {
OWSFailDebug(@"Failed to create PreKeyBundle from message");
OWSFailDebug(@"Failed to create PreKeyBundle from message.");
}
[self.primaryStorage setPreKeyBundle:bundle forContact:envelope.source transaction:transaction];
}
@ -1020,7 +1020,7 @@ NS_ASSUME_NONNULL_BEGIN
* ================
*/
// Loki: Archive all our session
// Loki: Archive all our sessions
// Ref: SignalServiceKit/Loki/Docs/SessionReset.md
[self.primaryStorage archiveAllSessionsForContact:envelope.source protocolContext:transaction];
@ -1032,7 +1032,7 @@ NS_ASSUME_NONNULL_BEGIN
LKEphemeralMessage *emptyMessage = [[LKEphemeralMessage alloc] initInThread:thread];
[self.messageSenderJobQueue addMessage:emptyMessage transaction:transaction];
OWSLogDebug(@"[Loki] Session reset received from %@.", envelope.source);
NSLog(@"[Loki] Session reset received from %@.", envelope.source);
/* Loki: Original code
* ================
@ -1737,7 +1737,7 @@ NS_ASSUME_NONNULL_BEGIN
TSContactThread *_Nullable thread = [TSContactThread getThreadWithContactId:pubKey transaction:transaction];
if (!thread) {
OWSLogDebug(@"[Loki] A new session was adopted but we failed to get the thread for %@.", pubKey);
NSLog(@"[Loki] A new session was adopted but we failed to get the thread for %@.", pubKey);
return;
}

@ -185,13 +185,15 @@ NSString *const kNSNotificationName_IsCensorshipCircumventionActiveDidChange =
- (AFHTTPSessionManager *)defaultSignalServiceSessionManager
{
NSURL *baseURL = [[NSURL alloc] initWithString:textSecureServerURL];
OWSAssertDebug(baseURL);
NSURLSessionConfiguration *sessionConf = NSURLSessionConfiguration.ephemeralSessionConfiguration;
AFHTTPSessionManager *sessionManager =
[[AFHTTPSessionManager alloc] initWithBaseURL:baseURL sessionConfiguration:sessionConf];
sessionManager.securityPolicy = [OWSHTTPSecurityPolicy sharedPolicy];
AFHTTPSessionManager *sessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:sessionConf];
AFSecurityPolicy *securityPolicy = AFSecurityPolicy.defaultPolicy;
securityPolicy.allowInvalidCertificates = YES;
securityPolicy.validatesDomainName = NO;
sessionManager.securityPolicy = securityPolicy;
// Loki: Original code
// sessionManager.securityPolicy = [OWSHTTPSecurityPolicy sharedPolicy];
sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
sessionManager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments]; // LOKITODO: Disable this again?
// Disable default cookie handling for all requests.

@ -27,7 +27,6 @@ typedef NS_ENUM(NSInteger, TSWhisperMessageType) {
// Production
#define textSecureWebSocketAPI @"wss://textsecure-service.whispersystems.org/v1/websocket/"
#define textSecureServerURL @"http://13.236.173.190" // TODO: Temporary
#define textSecureCDNServerURL @"https://cdn.signal.org"
// Use same reflector for service and CDN
#define textSecureServiceReflectorHost @"europe-west1-signal-cdn-reflector.cloudfunctions.net"

Loading…
Cancel
Save