FWebSocketConnection.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. // Targetted compilation is ONLY for testing. UIKit is weak-linked in actual
  17. // release build.
  18. #import <Foundation/Foundation.h>
  19. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  20. #import "FirebaseDatabase/Sources/Api/Private/FIRDatabase_Private.h"
  21. #import "FirebaseDatabase/Sources/Constants/FConstants.h"
  22. #import "FirebaseDatabase/Sources/Public/FirebaseDatabase/FIRDatabaseReference.h"
  23. #import "FirebaseDatabase/Sources/Realtime/FWebSocketConnection.h"
  24. #import "FirebaseDatabase/Sources/Utilities/FStringUtilities.h"
  25. #if TARGET_OS_IOS || TARGET_OS_TV
  26. #import <UIKit/UIKit.h>
  27. #endif // TARGET_OS_IOS || TARGET_OS_TV
  28. #if TARGET_OS_WATCH
  29. #import <Network/Network.h>
  30. #import <WatchKit/WatchKit.h>
  31. #endif // TARGET_OS_WATCH
  32. @interface FWebSocketConnection () {
  33. NSMutableString *frame;
  34. BOOL everConnected;
  35. BOOL isClosed;
  36. NSTimer *keepAlive;
  37. }
  38. - (void)shutdown;
  39. - (void)onClosed;
  40. - (void)closeIfNeverConnected;
  41. #if TARGET_OS_WATCH
  42. @property(nonatomic, strong) NSURLSessionWebSocketTask *webSocketTask;
  43. #else
  44. @property(nonatomic, strong) FSRWebSocket *webSocket;
  45. #endif // TARGET_OS_WATCH
  46. @property(nonatomic, strong) NSNumber *connectionId;
  47. @property(nonatomic, readwrite) int totalFrames;
  48. @property(nonatomic, readonly) BOOL buffering;
  49. @property(nonatomic, readonly) NSString *userAgent;
  50. @property(nonatomic) dispatch_queue_t dispatchQueue;
  51. - (void)nop:(NSTimer *)timer;
  52. @end
  53. @implementation FWebSocketConnection
  54. @synthesize delegate;
  55. #if !TARGET_OS_WATCH
  56. @synthesize webSocket;
  57. #endif // !TARGET_OS_WATCH
  58. @synthesize connectionId;
  59. - (id)initWith:(FRepoInfo *)repoInfo
  60. andQueue:(dispatch_queue_t)queue
  61. googleAppID:(NSString *)googleAppID
  62. lastSessionID:(NSString *)lastSessionID {
  63. self = [super init];
  64. if (self) {
  65. everConnected = NO;
  66. isClosed = NO;
  67. self.connectionId = [FUtilities LUIDGenerator];
  68. self.totalFrames = 0;
  69. self.dispatchQueue = queue;
  70. frame = nil;
  71. NSString *connectionUrl =
  72. [repoInfo connectionURLWithLastSessionID:lastSessionID];
  73. NSString *ua = [self userAgent];
  74. FFLog(@"I-RDB083001", @"(wsc:%@) Connecting to: %@ as %@",
  75. self.connectionId, connectionUrl, ua);
  76. NSURLRequest *req = [[NSURLRequest alloc]
  77. initWithURL:[[NSURL alloc] initWithString:connectionUrl]];
  78. #if TARGET_OS_WATCH
  79. // Regular NSURLSession websocket.
  80. NSOperationQueue *opQueue = [[NSOperationQueue alloc] init];
  81. opQueue.underlyingQueue = queue;
  82. NSURLSession *session = [NSURLSession
  83. sessionWithConfiguration:[NSURLSessionConfiguration
  84. defaultSessionConfiguration]
  85. delegate:self
  86. delegateQueue:opQueue];
  87. NSURLSessionWebSocketTask *task =
  88. [session webSocketTaskWithRequest:req];
  89. self.webSocketTask = task;
  90. if (@available(watchOS 7.0, *)) {
  91. [[NSNotificationCenter defaultCenter]
  92. addObserverForName:WKApplicationWillResignActiveNotification
  93. object:nil
  94. queue:opQueue
  95. usingBlock:^(NSNotification *_Nonnull note) {
  96. FFLog(@"I-RDB083015",
  97. @"Received watchOS background notification, "
  98. @"closing web socket.");
  99. [self onClosed];
  100. }];
  101. }
  102. #else
  103. self.webSocket = [[FSRWebSocket alloc] initWithURLRequest:req
  104. queue:queue
  105. googleAppID:googleAppID
  106. andUserAgent:ua];
  107. [self.webSocket setDelegateDispatchQueue:queue];
  108. self.webSocket.delegate = self;
  109. #endif // TARGET_OS_WATCH
  110. }
  111. return self;
  112. }
  113. - (NSString *)userAgent {
  114. NSString *systemVersion;
  115. NSString *deviceName;
  116. BOOL hasUiDeviceClass = NO;
  117. // Targetted compilation is ONLY for testing. UIKit is weak-linked in actual
  118. // release build.
  119. #if TARGET_OS_IOS || TARGET_OS_TV
  120. Class uiDeviceClass = NSClassFromString(@"UIDevice");
  121. if (uiDeviceClass) {
  122. systemVersion = [uiDeviceClass currentDevice].systemVersion;
  123. deviceName = [uiDeviceClass currentDevice].model;
  124. hasUiDeviceClass = YES;
  125. }
  126. #endif // TARGET_OS_IOS || TARGET_OS_TV
  127. if (!hasUiDeviceClass) {
  128. NSDictionary *systemVersionDictionary = [NSDictionary
  129. dictionaryWithContentsOfFile:
  130. @"/System/Library/CoreServices/SystemVersion.plist"];
  131. systemVersion =
  132. [systemVersionDictionary objectForKey:@"ProductVersion"];
  133. deviceName = [systemVersionDictionary objectForKey:@"ProductName"];
  134. }
  135. NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
  136. // Sanitize '/'s in deviceName and bundleIdentifier for stats
  137. deviceName = [FStringUtilities sanitizedForUserAgent:deviceName];
  138. bundleIdentifier =
  139. [FStringUtilities sanitizedForUserAgent:bundleIdentifier];
  140. // Firebase/5/<semver>_<build date>_<git hash>/<os version>/{device model /
  141. // os (Mac OS X, iPhone, etc.}_<bundle id>
  142. NSString *ua = [NSString
  143. stringWithFormat:@"Firebase/%@/%@/%@/%@_%@", kWebsocketProtocolVersion,
  144. [FIRDatabase buildVersion], systemVersion, deviceName,
  145. bundleIdentifier];
  146. return ua;
  147. }
  148. - (BOOL)buffering {
  149. return frame != nil;
  150. }
  151. #pragma mark -
  152. #pragma mark Public FWebSocketConnection methods
  153. - (void)open {
  154. FFLog(@"I-RDB083002", @"(wsc:%@) FWebSocketConnection open.",
  155. self.connectionId);
  156. assert(delegate);
  157. everConnected = NO;
  158. // TODO Assert url
  159. #if TARGET_OS_WATCH
  160. [self.webSocketTask resume];
  161. // We need to request data from the web socket in order for it to start
  162. // sending data.
  163. [self receiveWebSocketData];
  164. #else
  165. [self.webSocket open];
  166. #endif // TARGET_OS_WATCH
  167. dispatch_time_t when = dispatch_time(
  168. DISPATCH_TIME_NOW, kWebsocketConnectTimeout * NSEC_PER_SEC);
  169. dispatch_after(when, self.dispatchQueue, ^{
  170. [self closeIfNeverConnected];
  171. });
  172. }
  173. - (void)close {
  174. FFLog(@"I-RDB083003", @"(wsc:%@) FWebSocketConnection is being closed.",
  175. self.connectionId);
  176. isClosed = YES;
  177. #if TARGET_OS_WATCH
  178. [self.webSocketTask
  179. cancelWithCloseCode:NSURLSessionWebSocketCloseCodeNormalClosure
  180. reason:nil];
  181. #else
  182. [self.webSocket close];
  183. #endif // TARGET_OS_WATCH
  184. }
  185. - (void)start {
  186. // Start is a no-op for websockets.
  187. }
  188. - (void)send:(NSDictionary *)dictionary {
  189. [self resetKeepAlive];
  190. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary
  191. options:kNilOptions
  192. error:nil];
  193. NSString *data = [[NSString alloc] initWithData:jsonData
  194. encoding:NSUTF8StringEncoding];
  195. NSArray *dataSegs = [FUtilities splitString:data
  196. intoMaxSize:kWebsocketMaxFrameSize];
  197. // First send the header so the server knows how many segments are
  198. // forthcoming
  199. if (dataSegs.count > 1) {
  200. NSString *formattedData =
  201. [NSString stringWithFormat:@"%u", (unsigned int)dataSegs.count];
  202. [self sendStringToWebSocket:formattedData];
  203. }
  204. // Then, actually send the segments.
  205. for (NSString *segment in dataSegs) {
  206. [self sendStringToWebSocket:segment];
  207. }
  208. }
  209. - (void)nop:(NSTimer *)timer {
  210. if (!isClosed) {
  211. FFLog(@"I-RDB083004", @"(wsc:%@) nop", self.connectionId);
  212. // Note: the backend is expecting a string "0" here, not any special
  213. // ping/pong from build in websocket APIs.
  214. [self sendStringToWebSocket:@"0"];
  215. } else {
  216. FFLog(@"I-RDB083005",
  217. @"(wsc:%@) No more websocket; invalidating nop timer.",
  218. self.connectionId);
  219. [timer invalidate];
  220. }
  221. }
  222. - (void)handleNewFrameCount:(int)numFrames {
  223. self.totalFrames = numFrames;
  224. frame = [[NSMutableString alloc] initWithString:@""];
  225. FFLog(@"I-RDB083006", @"(wsc:%@) handleNewFrameCount: %d",
  226. self.connectionId, self.totalFrames);
  227. }
  228. - (NSString *)extractFrameCount:(NSString *)message {
  229. if ([message length] <= 4) {
  230. int frameCount = [message intValue];
  231. if (frameCount > 0) {
  232. [self handleNewFrameCount:frameCount];
  233. return nil;
  234. }
  235. }
  236. [self handleNewFrameCount:1];
  237. return message;
  238. }
  239. - (void)appendFrame:(NSString *)message {
  240. [frame appendString:message];
  241. self.totalFrames = self.totalFrames - 1;
  242. if (self.totalFrames == 0) {
  243. // Call delegate and pass an immutable version of the frame
  244. NSDictionary *json = [NSJSONSerialization
  245. JSONObjectWithData:[frame dataUsingEncoding:NSUTF8StringEncoding]
  246. options:kNilOptions
  247. error:nil];
  248. frame = nil;
  249. FFLog(@"I-RDB083007",
  250. @"(wsc:%@) handleIncomingFrame sending complete frame: %d",
  251. self.connectionId, self.totalFrames);
  252. @autoreleasepool {
  253. [self.delegate onMessage:self withMessage:json];
  254. }
  255. }
  256. }
  257. - (void)handleIncomingFrame:(NSString *)message {
  258. [self resetKeepAlive];
  259. if (self.buffering) {
  260. [self appendFrame:message];
  261. } else {
  262. NSString *remaining = [self extractFrameCount:message];
  263. if (remaining) {
  264. [self appendFrame:remaining];
  265. }
  266. }
  267. }
  268. #pragma mark -
  269. #pragma mark URLSessionWebSocketDelegate watchOS implementation
  270. #if TARGET_OS_WATCH
  271. - (void)URLSession:(NSURLSession *)session
  272. webSocketTask:(NSURLSessionWebSocketTask *)webSocketTask
  273. didOpenWithProtocol:(NSString *)protocol {
  274. [self webSocketDidOpen];
  275. }
  276. - (void)URLSession:(NSURLSession *)session
  277. webSocketTask:(NSURLSessionWebSocketTask *)webSocketTask
  278. didCloseWithCode:(NSURLSessionWebSocketCloseCode)closeCode
  279. reason:(NSData *)reason {
  280. FFLog(@"I-RDB083011", @"(wsc:%@) didCloseWithCode: %ld %@",
  281. self.connectionId, (long)closeCode, reason);
  282. [self onClosed];
  283. }
  284. - (void)receiveWebSocketData {
  285. __weak __auto_type weakSelf = self;
  286. [self.webSocketTask receiveMessageWithCompletionHandler:^(
  287. NSURLSessionWebSocketMessage *_Nullable message,
  288. NSError *_Nullable error) {
  289. __auto_type strongSelf = weakSelf;
  290. if (strongSelf == nil) {
  291. return;
  292. }
  293. if (message) {
  294. [strongSelf handleIncomingFrame:message.string];
  295. } else if (error && !strongSelf->isClosed) {
  296. FFWarn(@"I-RDB083020",
  297. @"Error received from web socket, closing the connection. %@",
  298. error);
  299. [strongSelf shutdown];
  300. return;
  301. }
  302. [strongSelf receiveWebSocketData];
  303. }];
  304. }
  305. #else
  306. #pragma mark SRWebSocketDelegate implementation
  307. - (void)webSocket:(FSRWebSocket *)webSocket didReceiveMessage:(id)message {
  308. [self handleIncomingFrame:message];
  309. }
  310. - (void)webSocket:(FSRWebSocket *)webSocket didFailWithError:(NSError *)error {
  311. FFLog(@"I-RDB083010", @"(wsc:%@) didFailWithError didFailWithError: %@",
  312. self.connectionId, [error description]);
  313. [self onClosed];
  314. }
  315. - (void)webSocket:(FSRWebSocket *)webSocket
  316. didCloseWithCode:(NSInteger)code
  317. reason:(NSString *)reason
  318. wasClean:(BOOL)wasClean {
  319. FFLog(@"I-RDB083011", @"(wsc:%@) didCloseWithCode: %ld %@",
  320. self.connectionId, (long)code, reason);
  321. [self onClosed];
  322. }
  323. #endif // TARGET_OS_WATCH
  324. // Common to both SRWebSocketDelegate and URLSessionWebSocketDelegate.
  325. - (void)webSocketDidOpen {
  326. FFLog(@"I-RDB083008", @"(wsc:%@) webSocketDidOpen", self.connectionId);
  327. everConnected = YES;
  328. dispatch_async(dispatch_get_main_queue(), ^{
  329. self->keepAlive =
  330. [NSTimer scheduledTimerWithTimeInterval:kWebsocketKeepaliveInterval
  331. target:self
  332. selector:@selector(nop:)
  333. userInfo:nil
  334. repeats:YES];
  335. FFLog(@"I-RDB083009", @"(wsc:%@) nop timer kicked off",
  336. self.connectionId);
  337. });
  338. }
  339. #pragma mark -
  340. #pragma mark Private methods
  341. /** Sends a string through the open web socket. */
  342. - (void)sendStringToWebSocket:(NSString *)string {
  343. #if TARGET_OS_WATCH
  344. // Use built-in URLSessionWebSocket functionality.
  345. [self.webSocketTask sendMessage:[[NSURLSessionWebSocketMessage alloc]
  346. initWithString:string]
  347. completionHandler:^(NSError *_Nullable error) {
  348. if (error) {
  349. FFWarn(@"I-RDB083016",
  350. @"Error sending web socket data: %@.", error);
  351. return;
  352. }
  353. }];
  354. #else
  355. // Use existing SocketRocket implementation.
  356. [self.webSocket send:string];
  357. #endif // TARGET_OS_WATCH
  358. }
  359. /**
  360. * Note that the close / onClosed / shutdown cycle here is a little different
  361. * from the javascript client. In order to properly handle deallocation, no
  362. * close-related action is taken at a higher level until we have received
  363. * notification from the websocket itself that it is closed. Otherwise, we end
  364. * up deallocating this class and the FConnection class before the websocket has
  365. * a change to call some of its delegate methods. So, since close is the
  366. * external close handler, we just set a flag saying not to call our own
  367. * delegate method and close the websocket. That will trigger a callback into
  368. * this class that can then do things like clean up the keepalive timer.
  369. */
  370. - (void)closeIfNeverConnected {
  371. if (!everConnected) {
  372. FFLog(@"I-RDB083012", @"(wsc:%@) Websocket timed out on connect",
  373. self.connectionId);
  374. #if TARGET_OS_WATCH
  375. [self.webSocketTask
  376. cancelWithCloseCode:NSURLSessionWebSocketCloseCodeNoStatusReceived
  377. reason:nil];
  378. #else
  379. [self.webSocket close];
  380. #endif // TARGET_OS_WATCH
  381. }
  382. }
  383. - (void)shutdown {
  384. isClosed = YES;
  385. // Call delegate methods
  386. [self.delegate onDisconnect:self wasEverConnected:everConnected];
  387. }
  388. - (void)onClosed {
  389. if (!isClosed) {
  390. FFLog(@"I-RDB083013", @"Websocket is closing itself");
  391. [self shutdown];
  392. }
  393. #if TARGET_OS_WATCH
  394. self.webSocketTask = nil;
  395. #else
  396. self.webSocket = nil;
  397. #endif // TARGET_OS_WATCH
  398. if (keepAlive.isValid) {
  399. [keepAlive invalidate];
  400. }
  401. }
  402. - (void)resetKeepAlive {
  403. NSDate *newTime =
  404. [NSDate dateWithTimeIntervalSinceNow:kWebsocketKeepaliveInterval];
  405. // Calling setFireDate is actually kinda' expensive, so wait at least 5
  406. // seconds before updating it.
  407. if ([newTime timeIntervalSinceDate:keepAlive.fireDate] > 5) {
  408. FFLog(@"I-RDB083014", @"(wsc:%@) resetting keepalive, to %@ ; old: %@",
  409. self.connectionId, newTime, [keepAlive fireDate]);
  410. [keepAlive setFireDate:newTime];
  411. }
  412. }
  413. @end