FWebSocketConnection.m 10 KB

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