FWebSocketConnection.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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 "FConstants.h"
  20. #import "FIRDatabaseReference.h"
  21. #import "FIRDatabase_Private.h"
  22. #import "FStringUtilities.h"
  23. #import "FWebSocketConnection.h"
  24. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  25. #if TARGET_OS_IOS || TARGET_OS_TV
  26. #import <UIKit/UIKit.h>
  27. #endif
  28. @interface FWebSocketConnection () {
  29. NSMutableString *frame;
  30. BOOL everConnected;
  31. BOOL isClosed;
  32. NSTimer *keepAlive;
  33. }
  34. - (void)shutdown;
  35. - (void)onClosed;
  36. - (void)closeIfNeverConnected;
  37. @property(nonatomic, strong) FSRWebSocket *webSocket;
  38. @property(nonatomic, strong) NSNumber *connectionId;
  39. @property(nonatomic, readwrite) int totalFrames;
  40. @property(nonatomic, readonly) BOOL buffering;
  41. @property(nonatomic, readonly) NSString *userAgent;
  42. @property(nonatomic) dispatch_queue_t dispatchQueue;
  43. - (void)nop:(NSTimer *)timer;
  44. @end
  45. @implementation FWebSocketConnection
  46. @synthesize delegate;
  47. @synthesize webSocket;
  48. @synthesize connectionId;
  49. - (id)initWith:(FRepoInfo *)repoInfo
  50. andQueue:(dispatch_queue_t)queue
  51. googleAppID:(NSString *)googleAppID
  52. lastSessionID:(NSString *)lastSessionID {
  53. self = [super init];
  54. if (self) {
  55. everConnected = NO;
  56. isClosed = NO;
  57. self.connectionId = [FUtilities LUIDGenerator];
  58. self.totalFrames = 0;
  59. self.dispatchQueue = queue;
  60. frame = nil;
  61. NSString *connectionUrl =
  62. [repoInfo connectionURLWithLastSessionID:lastSessionID];
  63. NSString *ua = [self userAgent];
  64. FFLog(@"I-RDB083001", @"(wsc:%@) Connecting to: %@ as %@",
  65. self.connectionId, connectionUrl, ua);
  66. NSURLRequest *req = [[NSURLRequest alloc]
  67. initWithURL:[[NSURL alloc] initWithString:connectionUrl]];
  68. self.webSocket = [[FSRWebSocket alloc] initWithURLRequest:req
  69. queue:queue
  70. googleAppID:googleAppID
  71. andUserAgent:ua];
  72. [self.webSocket setDelegateDispatchQueue:queue];
  73. self.webSocket.delegate = self;
  74. }
  75. return self;
  76. }
  77. - (NSString *)userAgent {
  78. NSString *systemVersion;
  79. NSString *deviceName;
  80. BOOL hasUiDeviceClass = NO;
  81. // Targetted compilation is ONLY for testing. UIKit is weak-linked in actual
  82. // release build.
  83. #if TARGET_OS_IOS || TARGET_OS_TV
  84. Class uiDeviceClass = NSClassFromString(@"UIDevice");
  85. if (uiDeviceClass) {
  86. systemVersion = [uiDeviceClass currentDevice].systemVersion;
  87. deviceName = [uiDeviceClass currentDevice].model;
  88. hasUiDeviceClass = YES;
  89. }
  90. #endif
  91. if (!hasUiDeviceClass) {
  92. NSDictionary *systemVersionDictionary = [NSDictionary
  93. dictionaryWithContentsOfFile:
  94. @"/System/Library/CoreServices/SystemVersion.plist"];
  95. systemVersion =
  96. [systemVersionDictionary objectForKey:@"ProductVersion"];
  97. deviceName = [systemVersionDictionary objectForKey:@"ProductName"];
  98. }
  99. NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
  100. // Sanitize '/'s in deviceName and bundleIdentifier for stats
  101. deviceName = [FStringUtilities sanitizedForUserAgent:deviceName];
  102. bundleIdentifier =
  103. [FStringUtilities sanitizedForUserAgent:bundleIdentifier];
  104. // Firebase/5/<semver>_<build date>_<git hash>/<os version>/{device model /
  105. // os (Mac OS X, iPhone, etc.}_<bundle id>
  106. NSString *ua = [NSString
  107. stringWithFormat:@"Firebase/%@/%@/%@/%@_%@", kWebsocketProtocolVersion,
  108. [FIRDatabase buildVersion], systemVersion, deviceName,
  109. bundleIdentifier];
  110. return ua;
  111. }
  112. - (BOOL)buffering {
  113. return frame != nil;
  114. }
  115. #pragma mark -
  116. #pragma mark Public FWebSocketConnection methods
  117. - (void)open {
  118. FFLog(@"I-RDB083002", @"(wsc:%@) FWebSocketConnection open.",
  119. self.connectionId);
  120. assert(delegate);
  121. everConnected = NO;
  122. // TODO Assert url
  123. [self.webSocket open];
  124. dispatch_time_t when = dispatch_time(
  125. DISPATCH_TIME_NOW, kWebsocketConnectTimeout * NSEC_PER_SEC);
  126. dispatch_after(when, self.dispatchQueue, ^{
  127. [self closeIfNeverConnected];
  128. });
  129. }
  130. - (void)close {
  131. FFLog(@"I-RDB083003", @"(wsc:%@) FWebSocketConnection is being closed.",
  132. self.connectionId);
  133. isClosed = YES;
  134. [self.webSocket close];
  135. }
  136. - (void)start {
  137. // Start is a no-op for websockets.
  138. }
  139. - (void)send:(NSDictionary *)dictionary {
  140. [self resetKeepAlive];
  141. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary
  142. options:kNilOptions
  143. error:nil];
  144. NSString *data = [[NSString alloc] initWithData:jsonData
  145. encoding:NSUTF8StringEncoding];
  146. NSArray *dataSegs = [FUtilities splitString:data
  147. intoMaxSize:kWebsocketMaxFrameSize];
  148. // First send the header so the server knows how many segments are
  149. // forthcoming
  150. if (dataSegs.count > 1) {
  151. [self.webSocket
  152. send:[NSString
  153. stringWithFormat:@"%u", (unsigned int)dataSegs.count]];
  154. }
  155. // Then, actually send the segments.
  156. for (NSString *segment in dataSegs) {
  157. [self.webSocket send:segment];
  158. }
  159. }
  160. - (void)nop:(NSTimer *)timer {
  161. if (!isClosed) {
  162. FFLog(@"I-RDB083004", @"(wsc:%@) nop", self.connectionId);
  163. [self.webSocket send:@"0"];
  164. } else {
  165. FFLog(@"I-RDB083005",
  166. @"(wsc:%@) No more websocket; invalidating nop timer.",
  167. self.connectionId);
  168. [timer invalidate];
  169. }
  170. }
  171. - (void)handleNewFrameCount:(int)numFrames {
  172. self.totalFrames = numFrames;
  173. frame = [[NSMutableString alloc] initWithString:@""];
  174. FFLog(@"I-RDB083006", @"(wsc:%@) handleNewFrameCount: %d",
  175. self.connectionId, self.totalFrames);
  176. }
  177. - (NSString *)extractFrameCount:(NSString *)message {
  178. if ([message length] <= 4) {
  179. int frameCount = [message intValue];
  180. if (frameCount > 0) {
  181. [self handleNewFrameCount:frameCount];
  182. return nil;
  183. }
  184. }
  185. [self handleNewFrameCount:1];
  186. return message;
  187. }
  188. - (void)appendFrame:(NSString *)message {
  189. [frame appendString:message];
  190. self.totalFrames = self.totalFrames - 1;
  191. if (self.totalFrames == 0) {
  192. // Call delegate and pass an immutable version of the frame
  193. NSDictionary *json = [NSJSONSerialization
  194. JSONObjectWithData:[frame dataUsingEncoding:NSUTF8StringEncoding]
  195. options:kNilOptions
  196. error:nil];
  197. frame = nil;
  198. FFLog(@"I-RDB083007",
  199. @"(wsc:%@) handleIncomingFrame sending complete frame: %d",
  200. self.connectionId, self.totalFrames);
  201. @autoreleasepool {
  202. [self.delegate onMessage:self withMessage:json];
  203. }
  204. }
  205. }
  206. - (void)handleIncomingFrame:(NSString *)message {
  207. [self resetKeepAlive];
  208. if (self.buffering) {
  209. [self appendFrame:message];
  210. } else {
  211. NSString *remaining = [self extractFrameCount:message];
  212. if (remaining) {
  213. [self appendFrame:remaining];
  214. }
  215. }
  216. }
  217. #pragma mark -
  218. #pragma mark SRWebSocketDelegate implementation
  219. - (void)webSocket:(FSRWebSocket *)webSocket didReceiveMessage:(id)message {
  220. [self handleIncomingFrame:message];
  221. }
  222. - (void)webSocketDidOpen:(FSRWebSocket *)webSocket {
  223. FFLog(@"I-RDB083008", @"(wsc:%@) webSocketDidOpen", self.connectionId);
  224. everConnected = YES;
  225. dispatch_async(dispatch_get_main_queue(), ^{
  226. self->keepAlive =
  227. [NSTimer scheduledTimerWithTimeInterval:kWebsocketKeepaliveInterval
  228. target:self
  229. selector:@selector(nop:)
  230. userInfo:nil
  231. repeats:YES];
  232. FFLog(@"I-RDB083009", @"(wsc:%@) nop timer kicked off",
  233. self.connectionId);
  234. });
  235. }
  236. - (void)webSocket:(FSRWebSocket *)webSocket didFailWithError:(NSError *)error {
  237. FFLog(@"I-RDB083010", @"(wsc:%@) didFailWithError didFailWithError: %@",
  238. self.connectionId, [error description]);
  239. [self onClosed];
  240. }
  241. - (void)webSocket:(FSRWebSocket *)webSocket
  242. didCloseWithCode:(NSInteger)code
  243. reason:(NSString *)reason
  244. wasClean:(BOOL)wasClean {
  245. FFLog(@"I-RDB083011", @"(wsc:%@) didCloseWithCode: %ld %@",
  246. self.connectionId, (long)code, reason);
  247. [self onClosed];
  248. }
  249. #pragma mark -
  250. #pragma mark Private methods
  251. /**
  252. * Note that the close / onClosed / shutdown cycle here is a little different
  253. * from the javascript client. In order to properly handle deallocation, no
  254. * close-related action is taken at a higher level until we have received
  255. * notification from the websocket itself that it is closed. Otherwise, we end
  256. * up deallocating this class and the FConnection class before the websocket has
  257. * a change to call some of its delegate methods. So, since close is the
  258. * external close handler, we just set a flag saying not to call our own
  259. * delegate method and close the websocket. That will trigger a callback into
  260. * this class that can then do things like clean up the keepalive timer.
  261. */
  262. - (void)closeIfNeverConnected {
  263. if (!everConnected) {
  264. FFLog(@"I-RDB083012", @"(wsc:%@) Websocket timed out on connect",
  265. self.connectionId);
  266. [self.webSocket close];
  267. }
  268. }
  269. - (void)shutdown {
  270. isClosed = YES;
  271. // Call delegate methods
  272. [self.delegate onDisconnect:self wasEverConnected:everConnected];
  273. }
  274. - (void)onClosed {
  275. if (!isClosed) {
  276. FFLog(@"I-RDB083013", @"Websocket is closing itself");
  277. [self shutdown];
  278. }
  279. self.webSocket = nil;
  280. if (keepAlive.isValid) {
  281. [keepAlive invalidate];
  282. }
  283. }
  284. - (void)resetKeepAlive {
  285. NSDate *newTime =
  286. [NSDate dateWithTimeIntervalSinceNow:kWebsocketKeepaliveInterval];
  287. // Calling setFireDate is actually kinda' expensive, so wait at least 5
  288. // seconds before updating it.
  289. if ([newTime timeIntervalSinceDate:keepAlive.fireDate] > 5) {
  290. FFLog(@"I-RDB083014", @"(wsc:%@) resetting keepalive, to %@ ; old: %@",
  291. self.connectionId, newTime, [keepAlive fireDate]);
  292. [keepAlive setFireDate:newTime];
  293. }
  294. }
  295. @end