This repository has been archived by the owner on Feb 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 68
/
TSSocketManager.m
365 lines (293 loc) · 13 KB
/
TSSocketManager.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
//
// TSSocketManager.m
// TextSecureiOS
//
// Created by Frederic Jacobs on 17/05/14.
// Copyright (c) 2014 Open Whisper Systems. All rights reserved.
//
#import "SubProtocol.pb.h"
#import "TSAccountManager.h"
#import "TSConstants.h"
#import "TSMessagesManager.h"
#import "TSSocketManager.h"
#import "TSStorageManager+keyingMaterial.h"
#import "OWSWebsocketSecurityPolicy.h"
#import "Cryptography.h"
#define kWebSocketHeartBeat 30
#define kWebSocketReconnectTry 5
#define kBackgroundConnectTimer 25
#define kBackgroundConnectKeepAlive 15
NSString *const SocketOpenedNotification = @"SocketOpenedNotification";
NSString *const SocketClosedNotification = @"SocketClosedNotification";
NSString *const SocketConnectingNotification = @"SocketConnectingNotification";
@interface TSSocketManager ()
@property (nonatomic, retain) NSTimer *pingTimer;
@property (nonatomic, retain) NSTimer *reconnectTimer;
@property (nonatomic, retain) SRWebSocket *websocket;
@property (nonatomic) SocketStatus status;
@property (nonatomic) UIBackgroundTaskIdentifier fetchingTaskIdentifier;
@property BOOL didConnectBg;
@property BOOL didRetreiveMessageBg;
@property BOOL shouldDownloadMessage;
@property (nonatomic, retain) NSTimer *backgroundKeepAliveTimer;
@property (nonatomic, retain) NSTimer *backgroundConnectTimer;
@end
@implementation TSSocketManager
- (instancetype)init {
self = [super init];
if (self) {
self.websocket = nil;
[self addObserver:self forKeyPath:@"status" options:0 context:kSocketStatusObservationContext];
}
return self;
}
+ (instancetype)sharedManager {
static TSSocketManager *sharedMyManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedMyManager = [[self alloc] init];
sharedMyManager.fetchingTaskIdentifier = UIBackgroundTaskInvalid;
sharedMyManager.didConnectBg = NO;
sharedMyManager.shouldDownloadMessage = NO;
sharedMyManager.didRetreiveMessageBg = NO;
});
return sharedMyManager;
}
#pragma mark - Manage Socket
+ (void)becomeActive {
TSSocketManager *sharedInstance = [self sharedManager];
SRWebSocket *socket = [sharedInstance websocket];
if (socket) {
switch ([socket readyState]) {
case SR_OPEN:
DDLogVerbose(@"WebSocket already open on connection request");
sharedInstance.status = kSocketStatusOpen;
return;
case SR_CONNECTING:
DDLogVerbose(@"WebSocket is already connecting");
sharedInstance.status = kSocketStatusConnecting;
return;
default:
[socket close];
sharedInstance.status = kSocketStatusClosed;
socket.delegate = nil;
socket = nil;
break;
}
}
NSString *webSocketConnect =
[textSecureWebSocketAPI stringByAppendingString:[[self sharedManager] webSocketAuthenticationString]];
NSURL *webSocketConnectURL = [NSURL URLWithString:webSocketConnect];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:webSocketConnectURL];
socket = [[SRWebSocket alloc] initWithURLRequest:request securityPolicy:[OWSWebsocketSecurityPolicy sharedPolicy]];
socket.delegate = [self sharedManager];
[[self sharedManager] setWebsocket:socket];
[socket open];
}
+ (void)resignActivity {
SRWebSocket *socket = [[self sharedManager] websocket];
[socket close];
}
#pragma mark - Delegate methods
- (void)webSocketDidOpen:(SRWebSocket *)webSocket {
self.pingTimer = [NSTimer timerWithTimeInterval:kWebSocketHeartBeat
target:self
selector:@selector(webSocketHeartBeat)
userInfo:nil
repeats:YES];
// Additionally, we want the ping timer to work in the background too.
[[NSRunLoop mainRunLoop] addTimer:self.pingTimer forMode:NSDefaultRunLoopMode];
self.status = kSocketStatusOpen;
[self.reconnectTimer invalidate];
self.reconnectTimer = nil;
self.didConnectBg = YES;
}
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error {
DDLogError(@"Error connecting to socket %@", error);
[self.pingTimer invalidate];
self.status = kSocketStatusClosed;
[self scheduleRetry];
}
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(NSData *)data {
WebSocketMessage *wsMessage = [WebSocketMessage parseFromData:data];
self.didRetreiveMessageBg = YES;
if (wsMessage.type == WebSocketMessageTypeRequest) {
[self processWebSocketRequestMessage:wsMessage.request];
} else if (wsMessage.type == WebSocketMessageTypeResponse) {
[self processWebSocketResponseMessage:wsMessage.response];
} else {
DDLogWarn(@"Got a WebSocketMessage of unknown type");
}
}
- (void)processWebSocketRequestMessage:(WebSocketRequestMessage *)message {
DDLogInfo(@"Got message with verb: %@ and path: %@", message.verb, message.path);
[self sendWebSocketMessageAcknowledgement:message];
[self keepAliveBackground];
if ([message.path isEqualToString:@"/api/v1/message"] && [message.verb isEqualToString:@"PUT"]) {
NSData *decryptedPayload =
[Cryptography decryptAppleMessagePayload:message.body withSignalingKey:TSStorageManager.signalingKey];
if (!decryptedPayload) {
DDLogWarn(@"Failed to decrypt incoming payload or bad HMAC");
return;
}
IncomingPushMessageSignal *messageSignal = [IncomingPushMessageSignal parseFromData:decryptedPayload];
[[TSMessagesManager sharedManager] handleMessageSignal:messageSignal];
} else {
DDLogWarn(@"Unsupported WebSocket Request");
}
}
- (void)keepAliveBackground {
[self.backgroundConnectTimer invalidate];
if (self.fetchingTaskIdentifier) {
[self.backgroundKeepAliveTimer invalidate];
self.backgroundKeepAliveTimer = [NSTimer timerWithTimeInterval:kBackgroundConnectKeepAlive
target:self
selector:@selector(backgroundTimeExpired)
userInfo:nil
repeats:NO];
// Additionally, we want the reconnect timer to work in the background too.
[[NSRunLoop mainRunLoop] addTimer:self.backgroundKeepAliveTimer forMode:NSDefaultRunLoopMode];
}
}
- (void)processWebSocketResponseMessage:(WebSocketResponseMessage *)message {
DDLogWarn(@"Client should not receive WebSocket Respond messages");
}
- (void)sendWebSocketMessageAcknowledgement:(WebSocketRequestMessage *)request {
WebSocketResponseMessageBuilder *response = [WebSocketResponseMessage builder];
[response setStatus:200];
[response setMessage:@"OK"];
[response setId:request.id];
WebSocketMessageBuilder *message = [WebSocketMessage builder];
[message setResponse:response.build];
[message setType:WebSocketMessageTypeResponse];
@try {
[self.websocket send:message.build.data];
} @catch (NSException *exception) {
DDLogWarn(@"Caught exception while trying to write on the socket %@", exception.debugDescription);
}
}
- (void)webSocket:(SRWebSocket *)webSocket
didCloseWithCode:(NSInteger)code
reason:(NSString *)reason
wasClean:(BOOL)wasClean {
[self.pingTimer invalidate];
self.status = kSocketStatusClosed;
if (!wasClean && [UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
[self scheduleRetry];
}
}
- (void)webSocketHeartBeat {
NSError *error;
[self.websocket sendPing:nil error:&error];
if (error) {
DDLogWarn(@"Error in websocket heartbeat: %@", error.localizedDescription);
}
}
- (NSString *)webSocketAuthenticationString {
return [NSString
stringWithFormat:@"?login=%@&password=%@",
[[TSStorageManager localNumber] stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"],
[TSStorageManager serverAuthToken]];
}
- (void)scheduleRetry {
if (![self.reconnectTimer isValid]) {
self.reconnectTimer = [NSTimer timerWithTimeInterval:kWebSocketReconnectTry
target:[self class]
selector:@selector(becomeActive)
userInfo:nil
repeats:YES];
// Additionally, we want the reconnect timer to work in the background too.
[[NSRunLoop mainRunLoop] addTimer:self.reconnectTimer forMode:NSDefaultRunLoopMode];
} else {
DDLogWarn(@"Not scheduling retry, valid timer");
}
}
#pragma mark - Background Connect
+ (void)becomeActiveFromForeground {
TSSocketManager *sharedInstance = [self sharedManager];
if (sharedInstance.fetchingTaskIdentifier != UIBackgroundTaskInvalid) {
[sharedInstance closeBackgroundTask];
}
[self becomeActive];
}
+ (void)becomeActiveFromBackgroundExpectMessage:(BOOL)expected {
TSSocketManager *sharedInstance = [TSSocketManager sharedManager];
if (sharedInstance.fetchingTaskIdentifier == UIBackgroundTaskInvalid) {
sharedInstance.backgroundConnectTimer = [NSTimer timerWithTimeInterval:kBackgroundConnectTimer
target:sharedInstance
selector:@selector(backgroundConnectTimerExpired)
userInfo:nil
repeats:NO];
NSRunLoop *loop = [NSRunLoop mainRunLoop];
[loop addTimer:[TSSocketManager sharedManager].backgroundConnectTimer forMode:NSDefaultRunLoopMode];
[sharedInstance.backgroundKeepAliveTimer invalidate];
sharedInstance.didConnectBg = NO;
sharedInstance.didRetreiveMessageBg = NO;
sharedInstance.shouldDownloadMessage = expected;
sharedInstance.fetchingTaskIdentifier =
[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[TSSocketManager resignActivity];
[[TSSocketManager sharedManager] closeBackgroundTask];
}];
[self becomeActive];
} else {
DDLogWarn(@"Got called to become active in the background but there was already a background task running.");
}
}
- (void)backgroundConnectTimerExpired {
[self backgroundTimeExpired];
}
- (void)backgroundTimeExpired {
[[self class] resignActivity];
[self closeBackgroundTask];
}
- (void)closeBackgroundTask {
[self.backgroundKeepAliveTimer invalidate];
[self.backgroundConnectTimer invalidate];
/*
If VOIP Push worked, we should just have to check if message was retreived and if not, alert the user.
But we have to rely on the server for the fallback in failed cases since background push is unreliable.
https://devforums.apple.com/message/1135227
if ((self.shouldDownloadMessage && !self.didRetreiveMessageBg) || !self.didConnectBg) {
[self backgroundConnectTimedOut];
}
*/
[[UIApplication sharedApplication] endBackgroundTask:self.fetchingTaskIdentifier];
self.fetchingTaskIdentifier = UIBackgroundTaskInvalid;
}
- (void)backgroundConnectTimedOut {
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.alertBody = NSLocalizedString(@"APN_FETCHED_FAILED", nil);
notification.soundName = @"NewMessage.aifc";
[[UIApplication sharedApplication] presentLocalNotificationNow:notification];
}
#pragma mark UI Delegates
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
if (context == kSocketStatusObservationContext) {
[self notifyStatusChange];
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
- (void)notifyStatusChange {
switch (self.status) {
case kSocketStatusOpen:
[[NSNotificationCenter defaultCenter] postNotificationName:SocketOpenedNotification object:self];
break;
case kSocketStatusClosed:
[[NSNotificationCenter defaultCenter] postNotificationName:SocketClosedNotification object:self];
break;
case kSocketStatusConnecting:
[[NSNotificationCenter defaultCenter] postNotificationName:SocketConnectingNotification object:self];
break;
default:
break;
}
}
+ (void)sendNotification {
[[self sharedManager] notifyStatusChange];
}
@end