FWebSocketConnection.m 10 KB

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