FWebSocketConnection.m 11 KB

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