FWebSocketConnection.m 17 KB

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