FPersistentConnection.m 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141
  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. #import <Foundation/Foundation.h>
  17. #import "FAtomicNumber.h"
  18. #import "FAuthTokenProvider.h"
  19. #import "FCompoundHash.h"
  20. #import "FConstants.h"
  21. #import "FIRDatabaseConfig.h"
  22. #import "FIRDatabaseConfig_Private.h"
  23. #import "FIRDatabaseReference.h"
  24. #import "FIRRetryHelper.h"
  25. #import "FIndex.h"
  26. #import "FPersistentConnection.h"
  27. #import "FQueryParams.h"
  28. #import "FQuerySpec.h"
  29. #import "FRangeMerge.h"
  30. #import "FSnapshotUtilities.h"
  31. #import "FSyncTree.h"
  32. #import "FTupleCallbackStatus.h"
  33. #import "FTupleOnDisconnect.h"
  34. #import "FUtilities.h"
  35. #import <FirebaseCore/FIRLogger.h>
  36. #import <SystemConfiguration/SystemConfiguration.h>
  37. #import <dlfcn.h>
  38. #import <netinet/in.h>
  39. @interface FOutstandingQuery : NSObject
  40. @property(nonatomic, strong) FQuerySpec *query;
  41. @property(nonatomic, strong) NSNumber *tagId;
  42. @property(nonatomic, strong) id<FSyncTreeHash> syncTreeHash;
  43. @property(nonatomic, copy) fbt_void_nsstring onComplete;
  44. @end
  45. @implementation FOutstandingQuery
  46. @end
  47. @interface FOutstandingPut : NSObject
  48. @property(nonatomic, strong) NSString *action;
  49. @property(nonatomic, strong) NSDictionary *request;
  50. @property(nonatomic, copy) fbt_void_nsstring_nsstring onCompleteBlock;
  51. @property(nonatomic) BOOL sent;
  52. @end
  53. @implementation FOutstandingPut
  54. @end
  55. typedef enum {
  56. ConnectionStateDisconnected,
  57. ConnectionStateGettingToken,
  58. ConnectionStateConnecting,
  59. ConnectionStateAuthenticating,
  60. ConnectionStateConnected
  61. } ConnectionState;
  62. @interface FPersistentConnection () {
  63. ConnectionState connectionState;
  64. BOOL firstConnection;
  65. NSTimeInterval reconnectDelay;
  66. NSTimeInterval lastConnectionAttemptTime;
  67. NSTimeInterval lastConnectionEstablishedTime;
  68. SCNetworkReachabilityRef reachability;
  69. }
  70. - (int)getNextRequestNumber;
  71. - (void)onDataPushWithAction:(NSString *)action andBody:(NSDictionary *)body;
  72. - (void)handleTimestamp:(NSNumber *)timestamp;
  73. - (void)sendOnDisconnectAction:(NSString *)action
  74. forPath:(NSString *)pathString
  75. withData:(id)data
  76. andCallback:(fbt_void_nsstring_nsstring)callback;
  77. @property(nonatomic, strong) FConnection *realtime;
  78. @property(nonatomic, strong) NSMutableDictionary *listens;
  79. @property(nonatomic, strong) NSMutableDictionary *outstandingPuts;
  80. @property(nonatomic, strong) NSMutableArray *onDisconnectQueue;
  81. @property(nonatomic, strong) FRepoInfo *repoInfo;
  82. @property(nonatomic, strong) FAtomicNumber *putCounter;
  83. @property(nonatomic, strong) FAtomicNumber *requestNumber;
  84. @property(nonatomic, strong) NSMutableDictionary *requestCBHash;
  85. @property(nonatomic, strong) FIRDatabaseConfig *config;
  86. @property(nonatomic) NSUInteger unackedListensCount;
  87. @property(nonatomic, strong) NSMutableArray *putsToAck;
  88. @property(nonatomic, strong) dispatch_queue_t dispatchQueue;
  89. @property(nonatomic, strong) NSString *lastSessionID;
  90. @property(nonatomic, strong) NSMutableSet *interruptReasons;
  91. @property(nonatomic, strong) FIRRetryHelper *retryHelper;
  92. @property(nonatomic, strong) id<FAuthTokenProvider> authTokenProvider;
  93. @property(nonatomic, strong) NSString *authToken;
  94. @property(nonatomic) BOOL forceAuthTokenRefresh;
  95. @property(nonatomic) NSUInteger currentFetchTokenAttempt;
  96. @end
  97. @implementation FPersistentConnection
  98. - (id)initWithRepoInfo:(FRepoInfo *)repoInfo
  99. dispatchQueue:(dispatch_queue_t)dispatchQueue
  100. config:(FIRDatabaseConfig *)config {
  101. self = [super init];
  102. if (self) {
  103. self->_config = config;
  104. self->_repoInfo = repoInfo;
  105. self->_dispatchQueue = dispatchQueue;
  106. self->_authTokenProvider = config.authTokenProvider;
  107. NSAssert(self->_authTokenProvider != nil,
  108. @"Expected auth token provider");
  109. self.interruptReasons = [NSMutableSet set];
  110. self.listens = [[NSMutableDictionary alloc] init];
  111. self.outstandingPuts = [[NSMutableDictionary alloc] init];
  112. self.onDisconnectQueue = [[NSMutableArray alloc] init];
  113. self.putCounter = [[FAtomicNumber alloc] init];
  114. self.requestNumber = [[FAtomicNumber alloc] init];
  115. self.requestCBHash = [[NSMutableDictionary alloc] init];
  116. self.unackedListensCount = 0;
  117. self.putsToAck = [NSMutableArray array];
  118. connectionState = ConnectionStateDisconnected;
  119. firstConnection = YES;
  120. reconnectDelay = kPersistentConnReconnectMinDelay;
  121. self->_retryHelper = [[FIRRetryHelper alloc]
  122. initWithDispatchQueue:dispatchQueue
  123. minRetryDelayAfterFailure:kPersistentConnReconnectMinDelay
  124. maxRetryDelay:kPersistentConnReconnectMaxDelay
  125. retryExponent:kPersistentConnReconnectMultiplier
  126. jitterFactor:0.7];
  127. [self setupNotifications];
  128. // Make sure we don't actually connect until open is called
  129. [self interruptForReason:kFInterruptReasonWaitingForOpen];
  130. }
  131. // nb: The reason establishConnection isn't called here like the JS version
  132. // is because callers need to set the delegate first. The ctor can be
  133. // modified to accept the delegate but that deviates from normal ios
  134. // conventions. After the delegate has been set, the caller is responsible
  135. // for calling establishConnection:
  136. return self;
  137. }
  138. - (void)dealloc {
  139. if (reachability) {
  140. // Unschedule the notifications
  141. SCNetworkReachabilitySetDispatchQueue(reachability, NULL);
  142. CFRelease(reachability);
  143. }
  144. }
  145. #pragma mark -
  146. #pragma mark Public methods
  147. - (void)open {
  148. [self resumeForReason:kFInterruptReasonWaitingForOpen];
  149. }
  150. /**
  151. * Note that the listens dictionary has a type of Map[String (pathString),
  152. * Map[FQueryParams, FOutstandingQuery]]
  153. *
  154. * This means, for each path we care about, there are sets of queryParams that
  155. * correspond to an FOutstandingQuery object. There can be multiple sets at a
  156. * path since we overlap listens for a short time while adding or removing a
  157. * query from a location in the tree.
  158. */
  159. - (void)listen:(FQuerySpec *)query
  160. tagId:(NSNumber *)tagId
  161. hash:(id<FSyncTreeHash>)hash
  162. onComplete:(fbt_void_nsstring)onComplete {
  163. FFLog(@"I-RDB034001", @"Listen called for %@", query);
  164. NSAssert(self.listens[query] == nil,
  165. @"listen() called twice for the same query");
  166. NSAssert(query.isDefault || !query.loadsAllData,
  167. @"listen called for non-default but complete query");
  168. FOutstandingQuery *outstanding = [[FOutstandingQuery alloc] init];
  169. outstanding.query = query;
  170. outstanding.tagId = tagId;
  171. outstanding.syncTreeHash = hash;
  172. outstanding.onComplete = onComplete;
  173. [self.listens setObject:outstanding forKey:query];
  174. if ([self connected]) {
  175. [self sendListen:outstanding];
  176. }
  177. }
  178. - (void)putData:(id)data
  179. forPath:(NSString *)pathString
  180. withHash:(NSString *)hash
  181. withCallback:(fbt_void_nsstring_nsstring)onComplete {
  182. [self putInternal:data
  183. forAction:kFWPRequestActionPut
  184. forPath:pathString
  185. withHash:hash
  186. withCallback:onComplete];
  187. }
  188. - (void)mergeData:(id)data
  189. forPath:(NSString *)pathString
  190. withCallback:(fbt_void_nsstring_nsstring)onComplete {
  191. [self putInternal:data
  192. forAction:kFWPRequestActionMerge
  193. forPath:pathString
  194. withHash:nil
  195. withCallback:onComplete];
  196. }
  197. - (void)onDisconnectPutData:(id)data
  198. forPath:(FPath *)path
  199. withCallback:(fbt_void_nsstring_nsstring)callback {
  200. if ([self canSendWrites]) {
  201. [self sendOnDisconnectAction:kFWPRequestActionDisconnectPut
  202. forPath:[path description]
  203. withData:data
  204. andCallback:callback];
  205. } else {
  206. FTupleOnDisconnect *tuple = [[FTupleOnDisconnect alloc] init];
  207. tuple.pathString = [path description];
  208. tuple.action = kFWPRequestActionDisconnectPut;
  209. tuple.data = data;
  210. tuple.onComplete = callback;
  211. [self.onDisconnectQueue addObject:tuple];
  212. }
  213. }
  214. - (void)onDisconnectMergeData:(id)data
  215. forPath:(FPath *)path
  216. withCallback:(fbt_void_nsstring_nsstring)callback {
  217. if ([self canSendWrites]) {
  218. [self sendOnDisconnectAction:kFWPRequestActionDisconnectMerge
  219. forPath:[path description]
  220. withData:data
  221. andCallback:callback];
  222. } else {
  223. FTupleOnDisconnect *tuple = [[FTupleOnDisconnect alloc] init];
  224. tuple.pathString = [path description];
  225. tuple.action = kFWPRequestActionDisconnectMerge;
  226. tuple.data = data;
  227. tuple.onComplete = callback;
  228. [self.onDisconnectQueue addObject:tuple];
  229. }
  230. }
  231. - (void)onDisconnectCancelPath:(FPath *)path
  232. withCallback:(fbt_void_nsstring_nsstring)callback {
  233. if ([self canSendWrites]) {
  234. [self sendOnDisconnectAction:kFWPRequestActionDisconnectCancel
  235. forPath:[path description]
  236. withData:[NSNull null]
  237. andCallback:callback];
  238. } else {
  239. FTupleOnDisconnect *tuple = [[FTupleOnDisconnect alloc] init];
  240. tuple.pathString = [path description];
  241. tuple.action = kFWPRequestActionDisconnectCancel;
  242. tuple.data = [NSNull null];
  243. tuple.onComplete = callback;
  244. [self.onDisconnectQueue addObject:tuple];
  245. }
  246. }
  247. - (void)unlisten:(FQuerySpec *)query tagId:(NSNumber *)tagId {
  248. FPath *path = query.path;
  249. FFLog(@"I-RDB034002", @"Unlistening for %@", query);
  250. NSArray *outstanding = [self removeListen:query];
  251. if (outstanding.count > 0 && [self connected]) {
  252. [self sendUnlisten:path queryParams:query.params tagId:tagId];
  253. }
  254. }
  255. - (void)refreshAuthToken:(NSString *)token {
  256. self.authToken = token;
  257. if ([self connected]) {
  258. if (token != nil) {
  259. [self sendAuthAndRestoreStateAfterComplete:NO];
  260. } else {
  261. [self sendUnauth];
  262. }
  263. }
  264. }
  265. #pragma mark -
  266. #pragma mark Connection status
  267. - (BOOL)connected {
  268. return self->connectionState == ConnectionStateAuthenticating ||
  269. self->connectionState == ConnectionStateConnected;
  270. }
  271. - (BOOL)canSendWrites {
  272. return self->connectionState == ConnectionStateConnected;
  273. }
  274. #pragma mark -
  275. #pragma mark FConnection delegate methods
  276. - (void)onReady:(FConnection *)fconnection
  277. atTime:(NSNumber *)timestamp
  278. sessionID:(NSString *)sessionID {
  279. FFLog(@"I-RDB034003", @"On ready");
  280. lastConnectionEstablishedTime = [[NSDate date] timeIntervalSince1970];
  281. [self handleTimestamp:timestamp];
  282. if (firstConnection) {
  283. [self sendConnectStats];
  284. }
  285. [self restoreAuth];
  286. firstConnection = NO;
  287. self.lastSessionID = sessionID;
  288. dispatch_async(self.dispatchQueue, ^{
  289. [self.delegate onConnect:self];
  290. });
  291. }
  292. - (void)onDataMessage:(FConnection *)fconnection
  293. withMessage:(NSDictionary *)message {
  294. if (message[kFWPRequestNumber] != nil) {
  295. // this is a response to a request we sent
  296. NSNumber *rn = [NSNumber
  297. numberWithInt:[[message objectForKey:kFWPRequestNumber] intValue]];
  298. if ([self.requestCBHash objectForKey:rn]) {
  299. void (^callback)(NSDictionary *) =
  300. [self.requestCBHash objectForKey:rn];
  301. [self.requestCBHash removeObjectForKey:rn];
  302. if (callback) {
  303. // dispatch_async(self.dispatchQueue, ^{
  304. callback([message objectForKey:kFWPResponseForRNData]);
  305. //});
  306. }
  307. }
  308. } else if (message[kFWPRequestError] != nil) {
  309. NSString *error = [message objectForKey:kFWPRequestError];
  310. @throw [[NSException alloc] initWithName:@"FirebaseDatabaseServerError"
  311. reason:error
  312. userInfo:nil];
  313. } else if (message[kFWPAsyncServerAction] != nil) {
  314. // this is a server push of some sort
  315. NSString *action = [message objectForKey:kFWPAsyncServerAction];
  316. NSDictionary *body = [message objectForKey:kFWPAsyncServerPayloadBody];
  317. [self onDataPushWithAction:action andBody:body];
  318. }
  319. }
  320. - (void)onDisconnect:(FConnection *)fconnection
  321. withReason:(FDisconnectReason)reason {
  322. FFLog(@"I-RDB034004", @"Got on disconnect due to %s",
  323. (reason == DISCONNECT_REASON_SERVER_RESET) ? "server_reset"
  324. : "other");
  325. connectionState = ConnectionStateDisconnected;
  326. // Drop the realtime connection
  327. self.realtime = nil;
  328. [self cancelSentTransactions];
  329. [self.requestCBHash removeAllObjects];
  330. self.unackedListensCount = 0;
  331. if ([self shouldReconnect]) {
  332. NSTimeInterval timeSinceLastConnectSucceeded =
  333. [[NSDate date] timeIntervalSince1970] -
  334. lastConnectionEstablishedTime;
  335. BOOL lastConnectionWasSuccessful;
  336. if (lastConnectionEstablishedTime > 0) {
  337. lastConnectionWasSuccessful =
  338. timeSinceLastConnectSucceeded >
  339. kPersistentConnSuccessfulConnectionEstablishedDelay;
  340. } else {
  341. lastConnectionWasSuccessful = NO;
  342. }
  343. if (reason == DISCONNECT_REASON_SERVER_RESET ||
  344. lastConnectionWasSuccessful) {
  345. [self.retryHelper signalSuccess];
  346. }
  347. [self tryScheduleReconnect];
  348. }
  349. lastConnectionEstablishedTime = 0;
  350. [self.delegate onDisconnect:self];
  351. }
  352. - (void)onKill:(FConnection *)fconnection withReason:(NSString *)reason {
  353. FFWarn(@"I-RDB034005",
  354. @"Firebase Database connection was forcefully killed by the server. "
  355. @" Will not attempt reconnect. Reason: %@",
  356. reason);
  357. [self interruptForReason:kFInterruptReasonServerKill];
  358. }
  359. #pragma mark -
  360. #pragma mark Connection handling methods
  361. - (void)interruptForReason:(NSString *)reason {
  362. FFLog(@"I-RDB034006", @"Connection interrupted for: %@", reason);
  363. [self.interruptReasons addObject:reason];
  364. if (self.realtime) {
  365. // Will call onDisconnect and set the connection state to Disconnected
  366. [self.realtime close];
  367. self.realtime = nil;
  368. } else {
  369. [self.retryHelper cancel];
  370. self->connectionState = ConnectionStateDisconnected;
  371. }
  372. // Reset timeouts
  373. [self.retryHelper signalSuccess];
  374. }
  375. - (void)resumeForReason:(NSString *)reason {
  376. FFLog(@"I-RDB034007", @"Connection no longer interrupted for: %@", reason);
  377. [self.interruptReasons removeObject:reason];
  378. if ([self shouldReconnect] &&
  379. connectionState == ConnectionStateDisconnected) {
  380. [self tryScheduleReconnect];
  381. }
  382. }
  383. - (BOOL)shouldReconnect {
  384. return self.interruptReasons.count == 0;
  385. }
  386. - (BOOL)isInterruptedForReason:(NSString *)reason {
  387. return [self.interruptReasons containsObject:reason];
  388. }
  389. #pragma mark -
  390. #pragma mark Private methods
  391. - (void)tryScheduleReconnect {
  392. if ([self shouldReconnect]) {
  393. NSAssert(self->connectionState == ConnectionStateDisconnected,
  394. @"Not in disconnected state: %d", self->connectionState);
  395. BOOL forceRefresh = self.forceAuthTokenRefresh;
  396. self.forceAuthTokenRefresh = NO;
  397. FFLog(@"I-RDB034008", @"Scheduling connection attempt");
  398. [self.retryHelper retry:^{
  399. FFLog(@"I-RDB034009", @"Trying to fetch auth token");
  400. NSAssert(self->connectionState == ConnectionStateDisconnected,
  401. @"Not in disconnected state: %d", self->connectionState);
  402. self->connectionState = ConnectionStateGettingToken;
  403. self.currentFetchTokenAttempt++;
  404. NSUInteger thisFetchTokenAttempt = self.currentFetchTokenAttempt;
  405. [self.authTokenProvider
  406. fetchTokenForcingRefresh:forceRefresh
  407. withCallback:^(NSString *token, NSError *error) {
  408. if (thisFetchTokenAttempt ==
  409. self.currentFetchTokenAttempt) {
  410. if (error != nil) {
  411. self->connectionState =
  412. ConnectionStateDisconnected;
  413. FFLog(@"I-RDB034010",
  414. @"Error fetching token: %@", error);
  415. [self tryScheduleReconnect];
  416. } else {
  417. // Someone could have interrupted us while
  418. // fetching the token, marking the
  419. // connection as Disconnected
  420. if (self->connectionState ==
  421. ConnectionStateGettingToken) {
  422. FFLog(@"I-RDB034011",
  423. @"Successfully fetched token, "
  424. @"opening connection");
  425. [self openNetworkConnectionWithToken:
  426. token];
  427. } else {
  428. NSAssert(
  429. self->connectionState ==
  430. ConnectionStateDisconnected,
  431. @"Expected connection state "
  432. @"disconnected, but got %d",
  433. self->connectionState);
  434. FFLog(@"I-RDB034012",
  435. @"Not opening connection after "
  436. @"token refresh, because "
  437. @"connection was set to "
  438. @"disconnected.");
  439. }
  440. }
  441. } else {
  442. FFLog(@"I-RDB034013",
  443. @"Ignoring fetch token result, because "
  444. @"this was not the latest attempt.");
  445. }
  446. }];
  447. }];
  448. }
  449. }
  450. - (void)openNetworkConnectionWithToken:(NSString *)token {
  451. NSAssert(self->connectionState == ConnectionStateGettingToken,
  452. @"Trying to open network connection while in wrong state: %d",
  453. self->connectionState);
  454. self.authToken = token;
  455. self->connectionState = ConnectionStateConnecting;
  456. self.realtime = [[FConnection alloc] initWith:self.repoInfo
  457. andDispatchQueue:self.dispatchQueue
  458. lastSessionID:self.lastSessionID];
  459. self.realtime.delegate = self;
  460. [self.realtime open];
  461. }
  462. static void reachabilityCallback(SCNetworkReachabilityRef ref,
  463. SCNetworkReachabilityFlags flags, void *info) {
  464. if (flags & kSCNetworkReachabilityFlagsReachable) {
  465. FFLog(@"I-RDB034014",
  466. @"Network became reachable. Trigger a connection attempt");
  467. FPersistentConnection *self = (__bridge FPersistentConnection *)info;
  468. // Reset reconnect delay
  469. [self.retryHelper signalSuccess];
  470. if (self->connectionState == ConnectionStateDisconnected) {
  471. [self tryScheduleReconnect];
  472. }
  473. } else {
  474. FFLog(@"I-RDB034015", @"Network is not reachable");
  475. }
  476. }
  477. - (void)enteringForeground {
  478. dispatch_async(self.dispatchQueue, ^{
  479. // Reset reconnect delay
  480. [self.retryHelper signalSuccess];
  481. if (self->connectionState == ConnectionStateDisconnected) {
  482. [self tryScheduleReconnect];
  483. }
  484. });
  485. }
  486. - (void)setupNotifications {
  487. NSString *const *foregroundConstant = (NSString *const *)dlsym(
  488. RTLD_DEFAULT, "UIApplicationWillEnterForegroundNotification");
  489. if (foregroundConstant) {
  490. [[NSNotificationCenter defaultCenter]
  491. addObserver:self
  492. selector:@selector(enteringForeground)
  493. name:*foregroundConstant
  494. object:nil];
  495. }
  496. // An empty address is interpreted a generic internet access
  497. struct sockaddr_in zeroAddress;
  498. bzero(&zeroAddress, sizeof(zeroAddress));
  499. zeroAddress.sin_len = sizeof(zeroAddress);
  500. zeroAddress.sin_family = AF_INET;
  501. reachability = SCNetworkReachabilityCreateWithAddress(
  502. kCFAllocatorDefault, (const struct sockaddr *)&zeroAddress);
  503. SCNetworkReachabilityContext ctx = {0, (__bridge void *)(self), NULL, NULL,
  504. NULL};
  505. if (SCNetworkReachabilitySetCallback(reachability, reachabilityCallback,
  506. &ctx)) {
  507. SCNetworkReachabilitySetDispatchQueue(reachability, self.dispatchQueue);
  508. } else {
  509. FFLog(@"I-RDB034016",
  510. @"Failed to set up network reachability monitoring");
  511. CFRelease(reachability);
  512. reachability = NULL;
  513. }
  514. }
  515. - (void)sendAuthAndRestoreStateAfterComplete:(BOOL)restoreStateAfterComplete {
  516. NSAssert([self connected], @"Must be connected to send auth");
  517. NSAssert(self.authToken != nil,
  518. @"Can't send auth if there is no credential");
  519. NSDictionary *requestData = @{kFWPRequestCredential : self.authToken};
  520. [self sendAction:kFWPRequestActionAuth
  521. body:requestData
  522. sensitive:YES
  523. callback:^(NSDictionary *data) {
  524. self->connectionState = ConnectionStateConnected;
  525. NSString *status =
  526. [data objectForKey:kFWPResponseForActionStatus];
  527. id responseData = [data objectForKey:kFWPResponseForActionData];
  528. if (responseData == nil) {
  529. responseData = @"error";
  530. }
  531. BOOL statusOk =
  532. [status isEqualToString:kFWPResponseForActionStatusOk];
  533. if (statusOk) {
  534. if (restoreStateAfterComplete) {
  535. [self restoreState];
  536. }
  537. } else {
  538. self.authToken = nil;
  539. self.forceAuthTokenRefresh = YES;
  540. if ([status isEqualToString:@"expired_token"]) {
  541. FFLog(@"I-RDB034017", @"Authentication failed: %@ (%@)",
  542. status, responseData);
  543. } else {
  544. FFWarn(@"I-RDB034018", @"Authentication failed: %@ (%@)",
  545. status, responseData);
  546. }
  547. [self.realtime close];
  548. }
  549. }];
  550. }
  551. - (void)sendUnauth {
  552. [self sendAction:kFWPRequestActionUnauth
  553. body:@{}
  554. sensitive:NO
  555. callback:nil];
  556. }
  557. - (void)onAuthRevokedWithStatus:(NSString *)status
  558. andReason:(NSString *)reason {
  559. // This might be for an earlier token than we just recently sent. But since
  560. // we need to close the connection anyways, we can set it to null here and
  561. // we will refresh the token later on reconnect
  562. if ([status isEqualToString:@"expired_token"]) {
  563. FFLog(@"I-RDB034019", @"Auth token revoked: %@ (%@)", status, reason);
  564. } else {
  565. FFWarn(@"I-RDB034020", @"Auth token revoked: %@ (%@)", status, reason);
  566. }
  567. self.authToken = nil;
  568. self.forceAuthTokenRefresh = YES;
  569. // Try reconnecting on auth revocation
  570. [self.realtime close];
  571. }
  572. - (void)onListenRevoked:(FPath *)path {
  573. NSArray *queries = [self removeAllListensAtPath:path];
  574. for (FOutstandingQuery *query in queries) {
  575. query.onComplete(@"permission_denied");
  576. }
  577. }
  578. - (void)sendOnDisconnectAction:(NSString *)action
  579. forPath:(NSString *)pathString
  580. withData:(id)data
  581. andCallback:(fbt_void_nsstring_nsstring)callback {
  582. NSDictionary *request =
  583. @{kFWPRequestPath : pathString, kFWPRequestData : data};
  584. FFLog(@"I-RDB034021", @"onDisconnect %@: %@", action, request);
  585. [self sendAction:action
  586. body:request
  587. sensitive:NO
  588. callback:^(NSDictionary *data) {
  589. NSString *status =
  590. [data objectForKey:kFWPResponseForActionStatus];
  591. NSString *errorReason =
  592. [data objectForKey:kFWPResponseForActionData];
  593. callback(status, errorReason);
  594. }];
  595. }
  596. - (void)sendPut:(NSNumber *)index {
  597. NSAssert([self canSendWrites],
  598. @"sendPut called when not able to send writes");
  599. FOutstandingPut *put = self.outstandingPuts[index];
  600. assert(put != nil);
  601. fbt_void_nsstring_nsstring onComplete = put.onCompleteBlock;
  602. // Do not async this block; copying the block insinde sendAction: doesn't
  603. // happen in time (or something) so coredumps
  604. put.sent = YES;
  605. [self sendAction:put.action
  606. body:put.request
  607. sensitive:NO
  608. callback:^(NSDictionary *data) {
  609. FOutstandingPut *currentPut = self.outstandingPuts[index];
  610. if (currentPut == put) {
  611. [self.outstandingPuts removeObjectForKey:index];
  612. if (onComplete != nil) {
  613. NSString *status =
  614. [data objectForKey:kFWPResponseForActionStatus];
  615. NSString *errorReason =
  616. [data objectForKey:kFWPResponseForActionData];
  617. if (self.unackedListensCount == 0) {
  618. onComplete(status, errorReason);
  619. } else {
  620. FTupleCallbackStatus *putToAck =
  621. [[FTupleCallbackStatus alloc] init];
  622. putToAck.block = onComplete;
  623. putToAck.status = status;
  624. putToAck.errorReason = errorReason;
  625. [self.putsToAck addObject:putToAck];
  626. }
  627. }
  628. } else {
  629. FFLog(@"I-RDB034022",
  630. @"Ignoring on complete for put %@ because it was "
  631. @"already removed",
  632. index);
  633. }
  634. }];
  635. }
  636. - (void)sendUnlisten:(FPath *)path
  637. queryParams:(FQueryParams *)queryParams
  638. tagId:(NSNumber *)tagId {
  639. FFLog(@"I-RDB034023", @"Unlisten on %@ for %@", path, queryParams);
  640. NSMutableDictionary *request = [NSMutableDictionary
  641. dictionaryWithObjectsAndKeys:[path toString], kFWPRequestPath, nil];
  642. if (tagId != nil) {
  643. [request setObject:queryParams.wireProtocolParams
  644. forKey:kFWPRequestQueries];
  645. [request setObject:tagId forKey:kFWPRequestTag];
  646. }
  647. [self sendAction:kFWPRequestActionTaggedUnlisten
  648. body:request
  649. sensitive:NO
  650. callback:nil];
  651. }
  652. - (void)putInternal:(id)data
  653. forAction:(NSString *)action
  654. forPath:(NSString *)pathString
  655. withHash:(NSString *)hash
  656. withCallback:(fbt_void_nsstring_nsstring)onComplete {
  657. NSMutableDictionary *request = [NSMutableDictionary
  658. dictionaryWithObjectsAndKeys:pathString, kFWPRequestPath, data,
  659. kFWPRequestData, nil];
  660. if (hash) {
  661. [request setObject:hash forKey:kFWPRequestHash];
  662. }
  663. FOutstandingPut *put = [[FOutstandingPut alloc] init];
  664. put.action = action;
  665. put.request = request;
  666. put.onCompleteBlock = onComplete;
  667. put.sent = NO;
  668. NSNumber *index = [self.putCounter getAndIncrement];
  669. self.outstandingPuts[index] = put;
  670. if ([self canSendWrites]) {
  671. FFLog(@"I-RDB034024", @"Was connected, and added as index: %@", index);
  672. [self sendPut:index];
  673. } else {
  674. FFLog(@"I-RDB034025",
  675. @"Wasn't connected or writes paused, so added to outstanding "
  676. @"puts only. Path: %@",
  677. pathString);
  678. }
  679. }
  680. - (void)sendListen:(FOutstandingQuery *)listenSpec {
  681. FQuerySpec *query = listenSpec.query;
  682. FFLog(@"I-RDB034026", @"Listen for %@", query);
  683. NSMutableDictionary *request =
  684. [NSMutableDictionary dictionaryWithObject:[query.path toString]
  685. forKey:kFWPRequestPath];
  686. // Only bother to send query if it's non-default
  687. if (listenSpec.tagId != nil) {
  688. [request setObject:[query.params wireProtocolParams]
  689. forKey:kFWPRequestQueries];
  690. [request setObject:listenSpec.tagId forKey:kFWPRequestTag];
  691. }
  692. [request setObject:[listenSpec.syncTreeHash simpleHash]
  693. forKey:kFWPRequestHash];
  694. if ([listenSpec.syncTreeHash includeCompoundHash]) {
  695. FCompoundHash *compoundHash = [listenSpec.syncTreeHash compoundHash];
  696. NSMutableArray *posts = [NSMutableArray array];
  697. for (FPath *path in compoundHash.posts) {
  698. [posts addObject:path.wireFormat];
  699. }
  700. request[kFWPRequestCompoundHash] = @{
  701. kFWPRequestCompoundHashHashes : compoundHash.hashes,
  702. kFWPRequestCompoundHashPaths : posts
  703. };
  704. }
  705. fbt_void_nsdictionary onResponse = ^(NSDictionary *response) {
  706. FFLog(@"I-RDB034027", @"Listen response %@", response);
  707. // warn in any case, even if the listener was removed
  708. [self warnOnListenWarningsForQuery:query
  709. payload:response[kFWPResponseForActionData]];
  710. FOutstandingQuery *currentListenSpec = self.listens[query];
  711. // only trigger actions if the listen hasn't been removed (and maybe
  712. // readded)
  713. if (currentListenSpec == listenSpec) {
  714. NSString *status = [response objectForKey:kFWPRequestStatus];
  715. if (![status isEqualToString:@"ok"]) {
  716. [self removeListen:query];
  717. }
  718. if (listenSpec.onComplete) {
  719. listenSpec.onComplete(status);
  720. }
  721. }
  722. self.unackedListensCount--;
  723. NSAssert(self.unackedListensCount >= 0,
  724. @"unackedListensCount decremented to be negative.");
  725. if (self.unackedListensCount == 0) {
  726. [self ackPuts];
  727. }
  728. };
  729. [self sendAction:kFWPRequestActionTaggedListen
  730. body:request
  731. sensitive:NO
  732. callback:onResponse];
  733. self.unackedListensCount++;
  734. }
  735. - (void)warnOnListenWarningsForQuery:(FQuerySpec *)query payload:(id)payload {
  736. if (payload != nil && [payload isKindOfClass:[NSDictionary class]]) {
  737. NSDictionary *payloadDict = payload;
  738. id warnings = payloadDict[kFWPResponseDataWarnings];
  739. if (warnings != nil && [warnings isKindOfClass:[NSArray class]]) {
  740. NSArray *warningsArr = warnings;
  741. if ([warningsArr containsObject:@"no_index"]) {
  742. NSString *indexSpec = [NSString
  743. stringWithFormat:@"\".indexOn\": \"%@\"",
  744. [query.params.index queryDefinition]];
  745. NSString *indexPath = [query.path description];
  746. FFWarn(@"I-RDB034028",
  747. @"Using an unspecified index. Your data will be "
  748. @"downloaded and filtered on the client. "
  749. "Consider adding %@ at %@ to your security rules for "
  750. "better performance",
  751. indexSpec, indexPath);
  752. }
  753. }
  754. }
  755. }
  756. - (int)getNextRequestNumber {
  757. return [[self.requestNumber getAndIncrement] intValue];
  758. }
  759. - (void)sendAction:(NSString *)action
  760. body:(NSDictionary *)message
  761. sensitive:(BOOL)sensitive
  762. callback:(void (^)(NSDictionary *data))onMessage {
  763. // Hold onto the onMessage callback for this request before firing it off
  764. NSNumber *rn = [NSNumber numberWithInt:[self getNextRequestNumber]];
  765. NSDictionary *msg = [NSDictionary
  766. dictionaryWithObjectsAndKeys:rn, kFWPRequestNumber, action,
  767. kFWPRequestAction, message,
  768. kFWPRequestPayloadBody, nil];
  769. [self.realtime sendRequest:msg sensitive:sensitive];
  770. if (onMessage) {
  771. // Debug message without a callback; bump the rn, but don't hold onto
  772. // the cb
  773. [self.requestCBHash setObject:[onMessage copy] forKey:rn];
  774. }
  775. }
  776. - (void)cancelSentTransactions {
  777. NSMutableDictionary<NSNumber *, FOutstandingPut *>
  778. *cancelledOutstandingPuts = [[NSMutableDictionary alloc] init];
  779. for (NSNumber *index in self.outstandingPuts) {
  780. FOutstandingPut *put = self.outstandingPuts[index];
  781. if (put.request[kFWPRequestHash] && put.sent) {
  782. // This is a sent transaction put.
  783. cancelledOutstandingPuts[index] = put;
  784. }
  785. }
  786. [cancelledOutstandingPuts
  787. enumerateKeysAndObjectsUsingBlock:^(
  788. NSNumber *index, FOutstandingPut *outstandingPut, BOOL *stop) {
  789. // `onCompleteBlock:` may invoke `rerunTransactionsForPath:` and
  790. // enqueue new writes. We defer calling it until we have finished
  791. // enumerating all existing writes.
  792. outstandingPut.onCompleteBlock(
  793. kFTransactionDisconnect,
  794. @"Client was disconnected while running a transaction");
  795. [self.outstandingPuts removeObjectForKey:index];
  796. }];
  797. }
  798. - (void)onDataPushWithAction:(NSString *)action andBody:(NSDictionary *)body {
  799. FFLog(@"I-RDB034029", @"handleServerMessage: %@, %@", action, body);
  800. id<FPersistentConnectionDelegate> delegate = self.delegate;
  801. if ([action isEqualToString:kFWPAsyncServerDataUpdate] ||
  802. [action isEqualToString:kFWPAsyncServerDataMerge]) {
  803. BOOL isMerge = [action isEqualToString:kFWPAsyncServerDataMerge];
  804. if ([body objectForKey:kFWPAsyncServerDataUpdateBodyPath] &&
  805. [body objectForKey:kFWPAsyncServerDataUpdateBodyData]) {
  806. NSString *path =
  807. [body objectForKey:kFWPAsyncServerDataUpdateBodyPath];
  808. id payloadData =
  809. [body objectForKey:kFWPAsyncServerDataUpdateBodyData];
  810. if (isMerge && [payloadData isKindOfClass:[NSDictionary class]] &&
  811. [payloadData count] == 0) {
  812. // ignore empty merge
  813. } else {
  814. [delegate
  815. onDataUpdate:self
  816. forPath:path
  817. message:payloadData
  818. isMerge:isMerge
  819. tagId:[body objectForKey:
  820. kFWPAsyncServerDataUpdateBodyTag]];
  821. }
  822. } else {
  823. FFLog(
  824. @"I-RDB034030",
  825. @"Malformed data response from server missing path or data: %@",
  826. body);
  827. }
  828. } else if ([action isEqualToString:kFWPAsyncServerDataRangeMerge]) {
  829. NSString *path = body[kFWPAsyncServerDataUpdateBodyPath];
  830. NSArray *ranges = body[kFWPAsyncServerDataUpdateBodyData];
  831. NSNumber *tag = body[kFWPAsyncServerDataUpdateBodyTag];
  832. NSMutableArray *rangeMerges = [NSMutableArray array];
  833. for (NSDictionary *range in ranges) {
  834. NSString *startString = range[kFWPAsyncServerDataUpdateStartPath];
  835. NSString *endString = range[kFWPAsyncServerDataUpdateEndPath];
  836. id updateData = range[kFWPAsyncServerDataUpdateRangeMerge];
  837. id<FNode> updates = [FSnapshotUtilities nodeFrom:updateData];
  838. FPath *start = (startString != nil)
  839. ? [[FPath alloc] initWith:startString]
  840. : nil;
  841. FPath *end =
  842. (endString != nil) ? [[FPath alloc] initWith:endString] : nil;
  843. FRangeMerge *merge = [[FRangeMerge alloc] initWithStart:start
  844. end:end
  845. updates:updates];
  846. [rangeMerges addObject:merge];
  847. }
  848. [delegate onRangeMerge:rangeMerges forPath:path tagId:tag];
  849. } else if ([action isEqualToString:kFWPAsyncServerAuthRevoked]) {
  850. NSString *status = [body objectForKey:kFWPResponseForActionStatus];
  851. NSString *reason = [body objectForKey:kFWPResponseForActionData];
  852. [self onAuthRevokedWithStatus:status andReason:reason];
  853. } else if ([action isEqualToString:kFWPASyncServerListenCancelled]) {
  854. NSString *pathString =
  855. [body objectForKey:kFWPAsyncServerDataUpdateBodyPath];
  856. [self onListenRevoked:[[FPath alloc] initWith:pathString]];
  857. } else if ([action isEqualToString:kFWPAsyncServerSecurityDebug]) {
  858. NSString *msg = [body objectForKey:@"msg"];
  859. if (msg != nil) {
  860. NSArray *msgs = [msg componentsSeparatedByString:@"\n"];
  861. for (NSString *m in msgs) {
  862. FFWarn(@"I-RDB034031", @"%@", m);
  863. }
  864. }
  865. } else {
  866. // TODO: revoke listens, auth, security debug
  867. FFLog(@"I-RDB034032", @"Unsupported action from server: %@", action);
  868. }
  869. }
  870. - (void)restoreAuth {
  871. FFLog(@"I-RDB034033", @"Calling restore state");
  872. NSAssert(self->connectionState == ConnectionStateConnecting,
  873. @"Wanted to restore auth, but was in wrong state: %d",
  874. self->connectionState);
  875. if (self.authToken == nil) {
  876. FFLog(@"I-RDB034034", @"Not restoring auth because token is nil");
  877. self->connectionState = ConnectionStateConnected;
  878. [self restoreState];
  879. } else {
  880. FFLog(@"I-RDB034035", @"Restoring auth");
  881. self->connectionState = ConnectionStateAuthenticating;
  882. [self sendAuthAndRestoreStateAfterComplete:YES];
  883. }
  884. }
  885. - (void)restoreState {
  886. NSAssert(self->connectionState == ConnectionStateConnected,
  887. @"Should be connected if we're restoring state, but we are: %d",
  888. self->connectionState);
  889. [self.listens enumerateKeysAndObjectsUsingBlock:^(
  890. FQuerySpec *query, FOutstandingQuery *outstandingListen,
  891. BOOL *stop) {
  892. FFLog(@"I-RDB034036", @"Restoring listen for %@", query);
  893. [self sendListen:outstandingListen];
  894. }];
  895. NSArray *keys = [[self.outstandingPuts allKeys]
  896. sortedArrayUsingSelector:@selector(compare:)];
  897. for (int i = 0; i < [keys count]; i++) {
  898. if ([self.outstandingPuts objectForKey:[keys objectAtIndex:i]] != nil) {
  899. FFLog(@"I-RDB034037", @"Restoring put: %d", i);
  900. [self sendPut:[keys objectAtIndex:i]];
  901. } else {
  902. FFLog(@"I-RDB034038", @"Restoring put: skipped nil: %d", i);
  903. }
  904. }
  905. for (FTupleOnDisconnect *tuple in self.onDisconnectQueue) {
  906. [self sendOnDisconnectAction:tuple.action
  907. forPath:tuple.pathString
  908. withData:tuple.data
  909. andCallback:tuple.onComplete];
  910. }
  911. [self.onDisconnectQueue removeAllObjects];
  912. }
  913. - (NSArray *)removeListen:(FQuerySpec *)query {
  914. NSAssert(query.isDefault || !query.loadsAllData,
  915. @"removeListen called for non-default but complete query");
  916. FOutstandingQuery *outstanding = self.listens[query];
  917. if (!outstanding) {
  918. FFLog(@"I-RDB034039",
  919. @"Trying to remove listener for query %@ but no listener exists",
  920. query);
  921. return @[];
  922. } else {
  923. [self.listens removeObjectForKey:query];
  924. return @[ outstanding ];
  925. }
  926. }
  927. - (NSArray *)removeAllListensAtPath:(FPath *)path {
  928. FFLog(@"I-RDB034040", @"Removing all listens at path %@", path);
  929. NSMutableArray *removed = [NSMutableArray array];
  930. NSMutableArray *toRemove = [NSMutableArray array];
  931. [self.listens
  932. enumerateKeysAndObjectsUsingBlock:^(
  933. FQuerySpec *spec, FOutstandingQuery *outstanding, BOOL *stop) {
  934. if ([spec.path isEqual:path]) {
  935. [removed addObject:outstanding];
  936. [toRemove addObject:spec];
  937. }
  938. }];
  939. [self.listens removeObjectsForKeys:toRemove];
  940. return removed;
  941. }
  942. - (void)purgeOutstandingWrites {
  943. // We might have unacked puts in our queue that we need to ack now before we
  944. // send out any cancels...
  945. [self ackPuts];
  946. // Cancel in order
  947. NSArray *keys = [[self.outstandingPuts allKeys]
  948. sortedArrayUsingSelector:@selector(compare:)];
  949. for (NSNumber *key in keys) {
  950. FOutstandingPut *put = self.outstandingPuts[key];
  951. if (put.onCompleteBlock != nil) {
  952. put.onCompleteBlock(kFErrorWriteCanceled, nil);
  953. }
  954. }
  955. for (FTupleOnDisconnect *onDisconnect in self.onDisconnectQueue) {
  956. if (onDisconnect.onComplete != nil) {
  957. onDisconnect.onComplete(kFErrorWriteCanceled, nil);
  958. }
  959. }
  960. [self.outstandingPuts removeAllObjects];
  961. [self.onDisconnectQueue removeAllObjects];
  962. }
  963. - (void)ackPuts {
  964. for (FTupleCallbackStatus *put in self.putsToAck) {
  965. put.block(put.status, put.errorReason);
  966. }
  967. [self.putsToAck removeAllObjects];
  968. }
  969. - (void)handleTimestamp:(NSNumber *)timestamp {
  970. FFLog(@"I-RDB034041", @"Handling timestamp: %@", timestamp);
  971. double timestampDeltaMs = [timestamp doubleValue] -
  972. ([[NSDate date] timeIntervalSince1970] * 1000);
  973. [self.delegate onServerInfoUpdate:self
  974. updates:@{
  975. kDotInfoServerTimeOffset : [NSNumber
  976. numberWithDouble:timestampDeltaMs]
  977. }];
  978. }
  979. - (void)sendStats:(NSDictionary *)stats {
  980. if ([stats count] > 0) {
  981. NSDictionary *request = @{kFWPRequestCounters : stats};
  982. [self sendAction:kFWPRequestActionStats
  983. body:request
  984. sensitive:NO
  985. callback:^(NSDictionary *data) {
  986. NSString *status =
  987. [data objectForKey:kFWPResponseForActionStatus];
  988. NSString *errorReason =
  989. [data objectForKey:kFWPResponseForActionData];
  990. BOOL statusOk =
  991. [status isEqualToString:kFWPResponseForActionStatusOk];
  992. if (!statusOk) {
  993. FFLog(@"I-RDB034042", @"Failed to send stats: %@",
  994. errorReason);
  995. }
  996. }];
  997. } else {
  998. FFLog(@"I-RDB034043", @"Not sending stats because stats are empty");
  999. }
  1000. }
  1001. - (void)sendConnectStats {
  1002. NSMutableDictionary *stats = [NSMutableDictionary dictionary];
  1003. #if TARGET_OS_IOS || TARGET_OS_TV
  1004. if (self.config.persistenceEnabled) {
  1005. stats[@"persistence.ios.enabled"] = @1;
  1006. }
  1007. #elif TARGET_OS_OSX
  1008. if (self.config.persistenceEnabled) {
  1009. stats[@"persistence.osx.enabled"] = @1;
  1010. }
  1011. #endif
  1012. NSString *sdkVersion =
  1013. [[FIRDatabase sdkVersion] stringByReplacingOccurrencesOfString:@"."
  1014. withString:@"-"];
  1015. NSString *sdkStatName =
  1016. [NSString stringWithFormat:@"sdk.objc.%@", sdkVersion];
  1017. stats[sdkStatName] = @1;
  1018. FFLog(@"I-RDB034044", @"Sending first connection stats");
  1019. [self sendStats:stats];
  1020. }
  1021. - (NSDictionary *)dumpListens {
  1022. return self.listens;
  1023. }
  1024. @end