FWebSocketConnection.m 16 KB

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