FWebSocketConnection.m 10 KB

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