FWebSocketConnection.m 17 KB

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