FWebSocketConnection.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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. [self.webSocketTask receiveMessageWithCompletionHandler:^(
  286. NSURLSessionWebSocketMessage *_Nullable message,
  287. NSError *_Nullable error) {
  288. if (message) {
  289. [self handleIncomingFrame:message.string];
  290. } else if (error && !isClosed) {
  291. FFWarn(@"I-RDB083020",
  292. @"Error received from web socket, closing the connection. %@",
  293. error);
  294. [self shutdown];
  295. return;
  296. }
  297. [self receiveWebSocketData];
  298. }];
  299. }
  300. #else
  301. #pragma mark SRWebSocketDelegate implementation
  302. - (void)webSocket:(FSRWebSocket *)webSocket didReceiveMessage:(id)message {
  303. [self handleIncomingFrame:message];
  304. }
  305. - (void)webSocket:(FSRWebSocket *)webSocket didFailWithError:(NSError *)error {
  306. FFLog(@"I-RDB083010", @"(wsc:%@) didFailWithError didFailWithError: %@",
  307. self.connectionId, [error description]);
  308. [self onClosed];
  309. }
  310. - (void)webSocket:(FSRWebSocket *)webSocket
  311. didCloseWithCode:(NSInteger)code
  312. reason:(NSString *)reason
  313. wasClean:(BOOL)wasClean {
  314. FFLog(@"I-RDB083011", @"(wsc:%@) didCloseWithCode: %ld %@",
  315. self.connectionId, (long)code, reason);
  316. [self onClosed];
  317. }
  318. #endif // TARGET_OS_WATCH
  319. // Common to both SRWebSocketDelegate and URLSessionWebSocketDelegate.
  320. - (void)webSocketDidOpen {
  321. FFLog(@"I-RDB083008", @"(wsc:%@) webSocketDidOpen", self.connectionId);
  322. everConnected = YES;
  323. dispatch_async(dispatch_get_main_queue(), ^{
  324. self->keepAlive =
  325. [NSTimer scheduledTimerWithTimeInterval:kWebsocketKeepaliveInterval
  326. target:self
  327. selector:@selector(nop:)
  328. userInfo:nil
  329. repeats:YES];
  330. FFLog(@"I-RDB083009", @"(wsc:%@) nop timer kicked off",
  331. self.connectionId);
  332. });
  333. }
  334. #pragma mark -
  335. #pragma mark Private methods
  336. /** Sends a string through the open web socket. */
  337. - (void)sendStringToWebSocket:(NSString *)string {
  338. #if TARGET_OS_WATCH
  339. // Use built-in URLSessionWebSocket functionality.
  340. [self.webSocketTask sendMessage:[[NSURLSessionWebSocketMessage alloc]
  341. initWithString:string]
  342. completionHandler:^(NSError *_Nullable error) {
  343. if (error) {
  344. FFWarn(@"I-RDB083016",
  345. @"Error sending web socket data: %@.", error);
  346. return;
  347. }
  348. }];
  349. #else
  350. // Use existing SocketRocket implementation.
  351. [self.webSocket send:string];
  352. #endif // TARGET_OS_WATCH
  353. }
  354. /**
  355. * Note that the close / onClosed / shutdown cycle here is a little different
  356. * from the javascript client. In order to properly handle deallocation, no
  357. * close-related action is taken at a higher level until we have received
  358. * notification from the websocket itself that it is closed. Otherwise, we end
  359. * up deallocating this class and the FConnection class before the websocket has
  360. * a change to call some of its delegate methods. So, since close is the
  361. * external close handler, we just set a flag saying not to call our own
  362. * delegate method and close the websocket. That will trigger a callback into
  363. * this class that can then do things like clean up the keepalive timer.
  364. */
  365. - (void)closeIfNeverConnected {
  366. if (!everConnected) {
  367. FFLog(@"I-RDB083012", @"(wsc:%@) Websocket timed out on connect",
  368. self.connectionId);
  369. #if TARGET_OS_WATCH
  370. [self.webSocketTask
  371. cancelWithCloseCode:NSURLSessionWebSocketCloseCodeNoStatusReceived
  372. reason:nil];
  373. #else
  374. [self.webSocket close];
  375. #endif // TARGET_OS_WATCH
  376. }
  377. }
  378. - (void)shutdown {
  379. isClosed = YES;
  380. // Call delegate methods
  381. [self.delegate onDisconnect:self wasEverConnected:everConnected];
  382. }
  383. - (void)onClosed {
  384. if (!isClosed) {
  385. FFLog(@"I-RDB083013", @"Websocket is closing itself");
  386. [self shutdown];
  387. }
  388. #if TARGET_OS_WATCH
  389. self.webSocketTask = nil;
  390. #else
  391. self.webSocket = nil;
  392. #endif // TARGET_OS_WATCH
  393. if (keepAlive.isValid) {
  394. [keepAlive invalidate];
  395. }
  396. }
  397. - (void)resetKeepAlive {
  398. NSDate *newTime =
  399. [NSDate dateWithTimeIntervalSinceNow:kWebsocketKeepaliveInterval];
  400. // Calling setFireDate is actually kinda' expensive, so wait at least 5
  401. // seconds before updating it.
  402. if ([newTime timeIntervalSinceDate:keepAlive.fireDate] > 5) {
  403. FFLog(@"I-RDB083014", @"(wsc:%@) resetting keepalive, to %@ ; old: %@",
  404. self.connectionId, newTime, [keepAlive fireDate]);
  405. [keepAlive setFireDate:newTime];
  406. }
  407. }
  408. @end