FWebSocketConnection.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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 || \
  145. (defined(TARGET_OS_VISION) && TARGET_OS_VISION)
  146. Class uiDeviceClass = NSClassFromString(@"UIDevice");
  147. if (uiDeviceClass) {
  148. systemVersion = [uiDeviceClass currentDevice].systemVersion;
  149. deviceName = [uiDeviceClass currentDevice].model;
  150. hasUiDeviceClass = YES;
  151. }
  152. #endif // TARGET_OS_IOS || TARGET_OS_TV || (defined(TARGET_OS_VISION) &&
  153. // TARGET_OS_VISION)
  154. if (!hasUiDeviceClass) {
  155. NSDictionary *systemVersionDictionary = [NSDictionary
  156. dictionaryWithContentsOfFile:
  157. @"/System/Library/CoreServices/SystemVersion.plist"];
  158. systemVersion =
  159. [systemVersionDictionary objectForKey:@"ProductVersion"];
  160. deviceName = [systemVersionDictionary objectForKey:@"ProductName"];
  161. }
  162. NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
  163. // Sanitize '/'s in deviceName and bundleIdentifier for stats
  164. deviceName = [FStringUtilities sanitizedForUserAgent:deviceName];
  165. bundleIdentifier =
  166. [FStringUtilities sanitizedForUserAgent:bundleIdentifier];
  167. // Firebase/5/<semver>_<build date>_<git hash>/<os version>/{device model /
  168. // os (Mac OS X, iPhone, etc.}_<bundle id>
  169. NSString *ua = [NSString
  170. stringWithFormat:@"Firebase/%@/%@/%@/%@_%@", kWebsocketProtocolVersion,
  171. [FIRDatabase buildVersion], systemVersion, deviceName,
  172. bundleIdentifier];
  173. return ua;
  174. }
  175. - (BOOL)buffering {
  176. return frame != nil;
  177. }
  178. #pragma mark -
  179. #pragma mark Public FWebSocketConnection methods
  180. - (void)open {
  181. FFLog(@"I-RDB083002", @"(wsc:%@) FWebSocketConnection open.",
  182. self.connectionId);
  183. assert(delegate);
  184. everConnected = NO;
  185. // TODO Assert url
  186. if (@available(iOS 13.0, macOS 10.15, macCatalyst 13.1, tvOS 13.0,
  187. watchOS 6.0, *)) {
  188. [self.webSocketTask resume];
  189. // We need to request data from the web socket in order for it to start
  190. // sending data.
  191. [self receiveWebSocketData];
  192. }
  193. #if !TARGET_OS_WATCH
  194. else {
  195. [self.webSocket open];
  196. }
  197. #endif // TARGET_OS_WATCH
  198. dispatch_time_t when = dispatch_time(
  199. DISPATCH_TIME_NOW, kWebsocketConnectTimeout * NSEC_PER_SEC);
  200. dispatch_after(when, self.dispatchQueue, ^{
  201. [self closeIfNeverConnected];
  202. });
  203. }
  204. - (void)close {
  205. FFLog(@"I-RDB083003", @"(wsc:%@) FWebSocketConnection is being closed.",
  206. self.connectionId);
  207. isClosed = YES;
  208. if (@available(iOS 13.0, macOS 10.15, macCatalyst 13.1, tvOS 13.0,
  209. watchOS 6.0, *)) {
  210. [self.webSocketTask
  211. cancelWithCloseCode:NSURLSessionWebSocketCloseCodeNormalClosure
  212. reason:nil];
  213. }
  214. #if !TARGET_OS_WATCH
  215. else {
  216. [self.webSocket close];
  217. }
  218. #endif // TARGET_OS_WATCH
  219. }
  220. - (void)start {
  221. // Start is a no-op for websockets.
  222. }
  223. - (void)send:(NSDictionary *)dictionary {
  224. [self resetKeepAlive];
  225. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary
  226. options:kNilOptions
  227. error:nil];
  228. NSString *data = [[NSString alloc] initWithData:jsonData
  229. encoding:NSUTF8StringEncoding];
  230. NSArray *dataSegs = [FUtilities splitString:data
  231. intoMaxSize:kWebsocketMaxFrameSize];
  232. // First send the header so the server knows how many segments are
  233. // forthcoming
  234. if (dataSegs.count > 1) {
  235. NSString *formattedData =
  236. [NSString stringWithFormat:@"%u", (unsigned int)dataSegs.count];
  237. [self sendStringToWebSocket:formattedData];
  238. }
  239. // Then, actually send the segments.
  240. for (NSString *segment in dataSegs) {
  241. [self sendStringToWebSocket:segment];
  242. }
  243. }
  244. - (void)nop:(NSTimer *)timer {
  245. if (!isClosed) {
  246. FFLog(@"I-RDB083004", @"(wsc:%@) nop", self.connectionId);
  247. // Note: the backend is expecting a string "0" here, not any special
  248. // ping/pong from build in websocket APIs.
  249. [self sendStringToWebSocket:@"0"];
  250. } else {
  251. FFLog(@"I-RDB083005",
  252. @"(wsc:%@) No more websocket; invalidating nop timer.",
  253. self.connectionId);
  254. [timer invalidate];
  255. }
  256. }
  257. - (void)handleNewFrameCount:(int)numFrames {
  258. self.totalFrames = numFrames;
  259. frame = [[NSMutableString alloc] initWithString:@""];
  260. FFLog(@"I-RDB083006", @"(wsc:%@) handleNewFrameCount: %d",
  261. self.connectionId, self.totalFrames);
  262. }
  263. - (NSString *)extractFrameCount:(NSString *)message {
  264. if ([message length] <= 4) {
  265. int frameCount = [message intValue];
  266. if (frameCount > 0) {
  267. [self handleNewFrameCount:frameCount];
  268. return nil;
  269. }
  270. }
  271. [self handleNewFrameCount:1];
  272. return message;
  273. }
  274. - (void)appendFrame:(NSString *)message {
  275. [frame appendString:message];
  276. self.totalFrames = self.totalFrames - 1;
  277. if (self.totalFrames == 0) {
  278. // Call delegate and pass an immutable version of the frame
  279. NSDictionary *json = [NSJSONSerialization
  280. JSONObjectWithData:[frame dataUsingEncoding:NSUTF8StringEncoding]
  281. options:kNilOptions
  282. error:nil];
  283. frame = nil;
  284. FFLog(@"I-RDB083007",
  285. @"(wsc:%@) handleIncomingFrame sending complete frame: %d",
  286. self.connectionId, self.totalFrames);
  287. @autoreleasepool {
  288. [self.delegate onMessage:self withMessage:json];
  289. }
  290. }
  291. }
  292. - (void)handleIncomingFrame:(NSString *)message {
  293. [self resetKeepAlive];
  294. if (self.buffering) {
  295. [self appendFrame:message];
  296. } else {
  297. NSString *remaining = [self extractFrameCount:message];
  298. if (remaining) {
  299. [self appendFrame:remaining];
  300. }
  301. }
  302. }
  303. #pragma mark -
  304. #pragma mark URLSessionWebSocketDelegate implementation
  305. - (void)URLSession:(NSURLSession *)session
  306. webSocketTask:(NSURLSessionWebSocketTask *)webSocketTask
  307. didOpenWithProtocol:(NSString *)protocol
  308. API_AVAILABLE(macos(10.15), ios(13.0), watchos(6.0), tvos(13.0)) {
  309. [self webSocketDidOpen];
  310. }
  311. - (void)URLSession:(NSURLSession *)session
  312. webSocketTask:(NSURLSessionWebSocketTask *)webSocketTask
  313. didCloseWithCode:(NSURLSessionWebSocketCloseCode)closeCode
  314. reason:(NSData *)reason
  315. API_AVAILABLE(macos(10.15), ios(13.0), watchos(6.0), tvos(13.0)) {
  316. FFLog(@"I-RDB083011", @"(wsc:%@) didCloseWithCode: %ld %@",
  317. self.connectionId, (long)closeCode, reason);
  318. [self onClosed];
  319. }
  320. - (void)receiveWebSocketData API_AVAILABLE(macos(10.15), ios(13.0),
  321. watchos(6.0), tvos(13.0)) {
  322. __weak __auto_type weakSelf = self;
  323. [self.webSocketTask receiveMessageWithCompletionHandler:^(
  324. NSURLSessionWebSocketMessage *_Nullable message,
  325. NSError *_Nullable error) {
  326. __auto_type strongSelf = weakSelf;
  327. if (strongSelf == nil) {
  328. return;
  329. }
  330. if (message) {
  331. [strongSelf handleIncomingFrame:message.string];
  332. } else if (error && !strongSelf->isClosed) {
  333. FFWarn(@"I-RDB083020",
  334. @"Error received from web socket, closing the connection. %@",
  335. error);
  336. [strongSelf shutdown];
  337. return;
  338. }
  339. [strongSelf receiveWebSocketData];
  340. }];
  341. }
  342. #if !TARGET_OS_WATCH
  343. #pragma mark SRWebSocketDelegate implementation
  344. - (void)webSocket:(FSRWebSocket *)webSocket didReceiveMessage:(id)message {
  345. [self handleIncomingFrame:message];
  346. }
  347. - (void)webSocket:(FSRWebSocket *)webSocket didFailWithError:(NSError *)error {
  348. FFLog(@"I-RDB083010", @"(wsc:%@) didFailWithError didFailWithError: %@",
  349. self.connectionId, [error description]);
  350. [self onClosed];
  351. }
  352. - (void)webSocket:(FSRWebSocket *)webSocket
  353. didCloseWithCode:(NSInteger)code
  354. reason:(NSString *)reason
  355. wasClean:(BOOL)wasClean {
  356. FFLog(@"I-RDB083011", @"(wsc:%@) didCloseWithCode: %ld %@",
  357. self.connectionId, (long)code, reason);
  358. [self onClosed];
  359. }
  360. #endif // !TARGET_OS_WATCH
  361. // Common to both SRWebSocketDelegate and URLSessionWebSocketDelegate.
  362. - (void)webSocketDidOpen {
  363. FFLog(@"I-RDB083008", @"(wsc:%@) webSocketDidOpen", self.connectionId);
  364. everConnected = YES;
  365. dispatch_async(dispatch_get_main_queue(), ^{
  366. self->keepAlive =
  367. [NSTimer scheduledTimerWithTimeInterval:kWebsocketKeepaliveInterval
  368. target:self
  369. selector:@selector(nop:)
  370. userInfo:nil
  371. repeats:YES];
  372. FFLog(@"I-RDB083009", @"(wsc:%@) nop timer kicked off",
  373. self.connectionId);
  374. });
  375. }
  376. #pragma mark -
  377. #pragma mark Private methods
  378. /** Sends a string through the open web socket. */
  379. - (void)sendStringToWebSocket:(NSString *)string {
  380. if (@available(iOS 13.0, macOS 10.15, macCatalyst 13.1, tvOS 13.0,
  381. watchOS 6.0, *)) {
  382. // Use built-in URLSessionWebSocket functionality.
  383. [self.webSocketTask
  384. sendMessage:[[NSURLSessionWebSocketMessage alloc]
  385. initWithString:string]
  386. completionHandler:^(NSError *_Nullable error) {
  387. if (error) {
  388. FFWarn(@"I-RDB083016", @"Error sending web socket data: %@.",
  389. error);
  390. return;
  391. }
  392. }];
  393. }
  394. #if !TARGET_OS_WATCH
  395. else {
  396. // Use existing SocketRocket implementation.
  397. [self.webSocket send:string];
  398. }
  399. #endif // !TARGET_OS_WATCH
  400. }
  401. /**
  402. * Note that the close / onClosed / shutdown cycle here is a little different
  403. * from the javascript client. In order to properly handle deallocation, no
  404. * close-related action is taken at a higher level until we have received
  405. * notification from the websocket itself that it is closed. Otherwise, we end
  406. * up deallocating this class and the FConnection class before the websocket has
  407. * a change to call some of its delegate methods. So, since close is the
  408. * external close handler, we just set a flag saying not to call our own
  409. * delegate method and close the websocket. That will trigger a callback into
  410. * this class that can then do things like clean up the keepalive timer.
  411. */
  412. - (void)closeIfNeverConnected {
  413. if (!everConnected) {
  414. FFLog(@"I-RDB083012", @"(wsc:%@) Websocket timed out on connect",
  415. self.connectionId);
  416. if (@available(iOS 13.0, macOS 10.15, macCatalyst 13.1, tvOS 13.0,
  417. watchOS 6.0, *)) {
  418. [self.webSocketTask
  419. cancelWithCloseCode:
  420. NSURLSessionWebSocketCloseCodeNoStatusReceived
  421. reason:nil];
  422. }
  423. #if !TARGET_OS_WATCH
  424. else {
  425. [self.webSocket close];
  426. }
  427. #endif // TARGET_OS_WATCH
  428. }
  429. }
  430. - (void)shutdown {
  431. isClosed = YES;
  432. // Call delegate methods
  433. [self.delegate onDisconnect:self wasEverConnected:everConnected];
  434. }
  435. - (void)onClosed {
  436. if (!isClosed) {
  437. FFLog(@"I-RDB083013", @"Websocket is closing itself");
  438. [self shutdown];
  439. }
  440. if (@available(iOS 13.0, macOS 10.15, macCatalyst 13.1, tvOS 13.0,
  441. watchOS 6.0, *)) {
  442. self.webSocketTask = nil;
  443. }
  444. #if !TARGET_OS_WATCH
  445. self.webSocket = nil;
  446. #endif // TARGET_OS_WATCH
  447. if (keepAlive.isValid) {
  448. [keepAlive invalidate];
  449. }
  450. }
  451. - (void)resetKeepAlive {
  452. NSDate *newTime =
  453. [NSDate dateWithTimeIntervalSinceNow:kWebsocketKeepaliveInterval];
  454. // Calling setFireDate is actually kinda' expensive, so wait at least 5
  455. // seconds before updating it.
  456. if ([newTime timeIntervalSinceDate:keepAlive.fireDate] > 5) {
  457. FFLog(@"I-RDB083014", @"(wsc:%@) resetting keepalive, to %@ ; old: %@",
  458. self.connectionId, newTime, [keepAlive fireDate]);
  459. [keepAlive setFireDate:newTime];
  460. }
  461. }
  462. + (NSURLRequest *)createRequestWithURL:(NSString *)connectionURL
  463. userAgent:(NSString *)userAgent
  464. googleAppID:(NSString *)googleAppID
  465. appCheckToken:(nullable NSString *)appCheckToken {
  466. NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
  467. initWithURL:[[NSURL alloc] initWithString:connectionURL]];
  468. [request setValue:appCheckToken forHTTPHeaderField:kAppCheckTokenHeader];
  469. [request setValue:userAgent forHTTPHeaderField:kUserAgentHeader];
  470. [request setValue:googleAppID forHTTPHeaderField:kGoogleAppIDHeader];
  471. return [request copy];
  472. }
  473. @end