FWebSocketConnection.m 19 KB

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