FWebSocketConnection.m 17 KB

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