FPersistentConnection.m 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  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/Sources/Private/FirebaseCoreInternal.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. googleAppID:self.config.googleAppID
  459. lastSessionID:self.lastSessionID];
  460. self.realtime.delegate = self;
  461. [self.realtime open];
  462. }
  463. static void reachabilityCallback(SCNetworkReachabilityRef ref,
  464. SCNetworkReachabilityFlags flags, void *info) {
  465. if (flags & kSCNetworkReachabilityFlagsReachable) {
  466. FFLog(@"I-RDB034014",
  467. @"Network became reachable. Trigger a connection attempt");
  468. FPersistentConnection *self = (__bridge FPersistentConnection *)info;
  469. // Reset reconnect delay
  470. [self.retryHelper signalSuccess];
  471. if (self->connectionState == ConnectionStateDisconnected) {
  472. [self tryScheduleReconnect];
  473. }
  474. } else {
  475. FFLog(@"I-RDB034015", @"Network is not reachable");
  476. }
  477. }
  478. - (void)enteringForeground {
  479. dispatch_async(self.dispatchQueue, ^{
  480. // Reset reconnect delay
  481. [self.retryHelper signalSuccess];
  482. if (self->connectionState == ConnectionStateDisconnected) {
  483. [self tryScheduleReconnect];
  484. }
  485. });
  486. }
  487. - (void)setupNotifications {
  488. NSString *const *foregroundConstant = (NSString *const *)dlsym(
  489. RTLD_DEFAULT, "UIApplicationWillEnterForegroundNotification");
  490. if (foregroundConstant) {
  491. [[NSNotificationCenter defaultCenter]
  492. addObserver:self
  493. selector:@selector(enteringForeground)
  494. name:*foregroundConstant
  495. object:nil];
  496. }
  497. // An empty address is interpreted a generic internet access
  498. struct sockaddr_in zeroAddress;
  499. bzero(&zeroAddress, sizeof(zeroAddress));
  500. zeroAddress.sin_len = sizeof(zeroAddress);
  501. zeroAddress.sin_family = AF_INET;
  502. reachability = SCNetworkReachabilityCreateWithAddress(
  503. kCFAllocatorDefault, (const struct sockaddr *)&zeroAddress);
  504. SCNetworkReachabilityContext ctx = {0, (__bridge void *)(self), NULL, NULL,
  505. NULL};
  506. if (SCNetworkReachabilitySetCallback(reachability, reachabilityCallback,
  507. &ctx)) {
  508. SCNetworkReachabilitySetDispatchQueue(reachability, self.dispatchQueue);
  509. } else {
  510. FFLog(@"I-RDB034016",
  511. @"Failed to set up network reachability monitoring");
  512. CFRelease(reachability);
  513. reachability = NULL;
  514. }
  515. }
  516. - (void)sendAuthAndRestoreStateAfterComplete:(BOOL)restoreStateAfterComplete {
  517. NSAssert([self connected], @"Must be connected to send auth");
  518. NSAssert(self.authToken != nil,
  519. @"Can't send auth if there is no credential");
  520. NSDictionary *requestData = @{kFWPRequestCredential : self.authToken};
  521. [self sendAction:kFWPRequestActionAuth
  522. body:requestData
  523. sensitive:YES
  524. callback:^(NSDictionary *data) {
  525. self->connectionState = ConnectionStateConnected;
  526. NSString *status =
  527. [data objectForKey:kFWPResponseForActionStatus];
  528. id responseData = [data objectForKey:kFWPResponseForActionData];
  529. if (responseData == nil) {
  530. responseData = @"error";
  531. }
  532. BOOL statusOk =
  533. [status isEqualToString:kFWPResponseForActionStatusOk];
  534. if (statusOk) {
  535. if (restoreStateAfterComplete) {
  536. [self restoreState];
  537. }
  538. } else {
  539. self.authToken = nil;
  540. self.forceAuthTokenRefresh = YES;
  541. if ([status isEqualToString:@"expired_token"]) {
  542. FFLog(@"I-RDB034017", @"Authentication failed: %@ (%@)",
  543. status, responseData);
  544. } else {
  545. FFWarn(@"I-RDB034018", @"Authentication failed: %@ (%@)",
  546. status, responseData);
  547. }
  548. [self.realtime close];
  549. }
  550. }];
  551. }
  552. - (void)sendUnauth {
  553. [self sendAction:kFWPRequestActionUnauth
  554. body:@{}
  555. sensitive:NO
  556. callback:nil];
  557. }
  558. - (void)onAuthRevokedWithStatus:(NSString *)status
  559. andReason:(NSString *)reason {
  560. // This might be for an earlier token than we just recently sent. But since
  561. // we need to close the connection anyways, we can set it to null here and
  562. // we will refresh the token later on reconnect
  563. if ([status isEqualToString:@"expired_token"]) {
  564. FFLog(@"I-RDB034019", @"Auth token revoked: %@ (%@)", status, reason);
  565. } else {
  566. FFWarn(@"I-RDB034020", @"Auth token revoked: %@ (%@)", status, reason);
  567. }
  568. self.authToken = nil;
  569. self.forceAuthTokenRefresh = YES;
  570. // Try reconnecting on auth revocation
  571. [self.realtime close];
  572. }
  573. - (void)onListenRevoked:(FPath *)path {
  574. NSArray *queries = [self removeAllListensAtPath:path];
  575. for (FOutstandingQuery *query in queries) {
  576. query.onComplete(@"permission_denied");
  577. }
  578. }
  579. - (void)sendOnDisconnectAction:(NSString *)action
  580. forPath:(NSString *)pathString
  581. withData:(id)data
  582. andCallback:(fbt_void_nsstring_nsstring)callback {
  583. NSDictionary *request =
  584. @{kFWPRequestPath : pathString, kFWPRequestData : data};
  585. FFLog(@"I-RDB034021", @"onDisconnect %@: %@", action, request);
  586. [self sendAction:action
  587. body:request
  588. sensitive:NO
  589. callback:^(NSDictionary *data) {
  590. NSString *status =
  591. [data objectForKey:kFWPResponseForActionStatus];
  592. NSString *errorReason =
  593. [data objectForKey:kFWPResponseForActionData];
  594. callback(status, errorReason);
  595. }];
  596. }
  597. - (void)sendPut:(NSNumber *)index {
  598. NSAssert([self canSendWrites],
  599. @"sendPut called when not able to send writes");
  600. FOutstandingPut *put = self.outstandingPuts[index];
  601. assert(put != nil);
  602. fbt_void_nsstring_nsstring onComplete = put.onCompleteBlock;
  603. // Do not async this block; copying the block insinde sendAction: doesn't
  604. // happen in time (or something) so coredumps
  605. put.sent = YES;
  606. [self sendAction:put.action
  607. body:put.request
  608. sensitive:NO
  609. callback:^(NSDictionary *data) {
  610. FOutstandingPut *currentPut = self.outstandingPuts[index];
  611. if (currentPut == put) {
  612. [self.outstandingPuts removeObjectForKey:index];
  613. if (onComplete != nil) {
  614. NSString *status =
  615. [data objectForKey:kFWPResponseForActionStatus];
  616. NSString *errorReason =
  617. [data objectForKey:kFWPResponseForActionData];
  618. if (self.unackedListensCount == 0) {
  619. onComplete(status, errorReason);
  620. } else {
  621. FTupleCallbackStatus *putToAck =
  622. [[FTupleCallbackStatus alloc] init];
  623. putToAck.block = onComplete;
  624. putToAck.status = status;
  625. putToAck.errorReason = errorReason;
  626. [self.putsToAck addObject:putToAck];
  627. }
  628. }
  629. } else {
  630. FFLog(@"I-RDB034022",
  631. @"Ignoring on complete for put %@ because it was "
  632. @"already removed",
  633. index);
  634. }
  635. }];
  636. }
  637. - (void)sendUnlisten:(FPath *)path
  638. queryParams:(FQueryParams *)queryParams
  639. tagId:(NSNumber *)tagId {
  640. FFLog(@"I-RDB034023", @"Unlisten on %@ for %@", path, queryParams);
  641. NSMutableDictionary *request = [NSMutableDictionary
  642. dictionaryWithObjectsAndKeys:[path toString], kFWPRequestPath, nil];
  643. if (tagId != nil) {
  644. [request setObject:queryParams.wireProtocolParams
  645. forKey:kFWPRequestQueries];
  646. [request setObject:tagId forKey:kFWPRequestTag];
  647. }
  648. [self sendAction:kFWPRequestActionTaggedUnlisten
  649. body:request
  650. sensitive:NO
  651. callback:nil];
  652. }
  653. - (void)putInternal:(id)data
  654. forAction:(NSString *)action
  655. forPath:(NSString *)pathString
  656. withHash:(NSString *)hash
  657. withCallback:(fbt_void_nsstring_nsstring)onComplete {
  658. NSMutableDictionary *request = [NSMutableDictionary
  659. dictionaryWithObjectsAndKeys:pathString, kFWPRequestPath, data,
  660. kFWPRequestData, nil];
  661. if (hash) {
  662. [request setObject:hash forKey:kFWPRequestHash];
  663. }
  664. FOutstandingPut *put = [[FOutstandingPut alloc] init];
  665. put.action = action;
  666. put.request = request;
  667. put.onCompleteBlock = onComplete;
  668. put.sent = NO;
  669. NSNumber *index = [self.putCounter getAndIncrement];
  670. self.outstandingPuts[index] = put;
  671. if ([self canSendWrites]) {
  672. FFLog(@"I-RDB034024", @"Was connected, and added as index: %@", index);
  673. [self sendPut:index];
  674. } else {
  675. FFLog(@"I-RDB034025",
  676. @"Wasn't connected or writes paused, so added to outstanding "
  677. @"puts only. Path: %@",
  678. pathString);
  679. }
  680. }
  681. - (void)sendListen:(FOutstandingQuery *)listenSpec {
  682. FQuerySpec *query = listenSpec.query;
  683. FFLog(@"I-RDB034026", @"Listen for %@", query);
  684. NSMutableDictionary *request =
  685. [NSMutableDictionary dictionaryWithObject:[query.path toString]
  686. forKey:kFWPRequestPath];
  687. // Only bother to send query if it's non-default
  688. if (listenSpec.tagId != nil) {
  689. [request setObject:[query.params wireProtocolParams]
  690. forKey:kFWPRequestQueries];
  691. [request setObject:listenSpec.tagId forKey:kFWPRequestTag];
  692. }
  693. [request setObject:[listenSpec.syncTreeHash simpleHash]
  694. forKey:kFWPRequestHash];
  695. if ([listenSpec.syncTreeHash includeCompoundHash]) {
  696. FCompoundHash *compoundHash = [listenSpec.syncTreeHash compoundHash];
  697. NSMutableArray *posts = [NSMutableArray array];
  698. for (FPath *path in compoundHash.posts) {
  699. [posts addObject:path.wireFormat];
  700. }
  701. request[kFWPRequestCompoundHash] = @{
  702. kFWPRequestCompoundHashHashes : compoundHash.hashes,
  703. kFWPRequestCompoundHashPaths : posts
  704. };
  705. }
  706. fbt_void_nsdictionary onResponse = ^(NSDictionary *response) {
  707. FFLog(@"I-RDB034027", @"Listen response %@", response);
  708. // warn in any case, even if the listener was removed
  709. [self warnOnListenWarningsForQuery:query
  710. payload:response[kFWPResponseForActionData]];
  711. FOutstandingQuery *currentListenSpec = self.listens[query];
  712. // only trigger actions if the listen hasn't been removed (and maybe
  713. // readded)
  714. if (currentListenSpec == listenSpec) {
  715. NSString *status = [response objectForKey:kFWPRequestStatus];
  716. if (![status isEqualToString:@"ok"]) {
  717. [self removeListen:query];
  718. }
  719. if (listenSpec.onComplete) {
  720. listenSpec.onComplete(status);
  721. }
  722. }
  723. self.unackedListensCount--;
  724. NSAssert(self.unackedListensCount >= 0,
  725. @"unackedListensCount decremented to be negative.");
  726. if (self.unackedListensCount == 0) {
  727. [self ackPuts];
  728. }
  729. };
  730. [self sendAction:kFWPRequestActionTaggedListen
  731. body:request
  732. sensitive:NO
  733. callback:onResponse];
  734. self.unackedListensCount++;
  735. }
  736. - (void)warnOnListenWarningsForQuery:(FQuerySpec *)query payload:(id)payload {
  737. if (payload != nil && [payload isKindOfClass:[NSDictionary class]]) {
  738. NSDictionary *payloadDict = payload;
  739. id warnings = payloadDict[kFWPResponseDataWarnings];
  740. if (warnings != nil && [warnings isKindOfClass:[NSArray class]]) {
  741. NSArray *warningsArr = warnings;
  742. if ([warningsArr containsObject:@"no_index"]) {
  743. NSString *indexSpec = [NSString
  744. stringWithFormat:@"\".indexOn\": \"%@\"",
  745. [query.params.index queryDefinition]];
  746. NSString *indexPath = [query.path description];
  747. FFWarn(@"I-RDB034028",
  748. @"Using an unspecified index. Your data will be "
  749. @"downloaded and filtered on the client. "
  750. "Consider adding %@ at %@ to your security rules for "
  751. "better performance",
  752. indexSpec, indexPath);
  753. }
  754. }
  755. }
  756. }
  757. - (int)getNextRequestNumber {
  758. return [[self.requestNumber getAndIncrement] intValue];
  759. }
  760. - (void)sendAction:(NSString *)action
  761. body:(NSDictionary *)message
  762. sensitive:(BOOL)sensitive
  763. callback:(void (^)(NSDictionary *data))onMessage {
  764. // Hold onto the onMessage callback for this request before firing it off
  765. NSNumber *rn = [NSNumber numberWithInt:[self getNextRequestNumber]];
  766. NSDictionary *msg = [NSDictionary
  767. dictionaryWithObjectsAndKeys:rn, kFWPRequestNumber, action,
  768. kFWPRequestAction, message,
  769. kFWPRequestPayloadBody, nil];
  770. [self.realtime sendRequest:msg sensitive:sensitive];
  771. if (onMessage) {
  772. // Debug message without a callback; bump the rn, but don't hold onto
  773. // the cb
  774. [self.requestCBHash setObject:[onMessage copy] forKey:rn];
  775. }
  776. }
  777. - (void)cancelSentTransactions {
  778. NSMutableDictionary<NSNumber *, FOutstandingPut *>
  779. *cancelledOutstandingPuts = [[NSMutableDictionary alloc] init];
  780. for (NSNumber *index in self.outstandingPuts) {
  781. FOutstandingPut *put = self.outstandingPuts[index];
  782. if (put.request[kFWPRequestHash] && put.sent) {
  783. // This is a sent transaction put.
  784. cancelledOutstandingPuts[index] = put;
  785. }
  786. }
  787. [cancelledOutstandingPuts
  788. enumerateKeysAndObjectsUsingBlock:^(
  789. NSNumber *index, FOutstandingPut *outstandingPut, BOOL *stop) {
  790. // `onCompleteBlock:` may invoke `rerunTransactionsForPath:` and
  791. // enqueue new writes. We defer calling it until we have finished
  792. // enumerating all existing writes.
  793. outstandingPut.onCompleteBlock(
  794. kFTransactionDisconnect,
  795. @"Client was disconnected while running a transaction");
  796. [self.outstandingPuts removeObjectForKey:index];
  797. }];
  798. }
  799. - (void)onDataPushWithAction:(NSString *)action andBody:(NSDictionary *)body {
  800. FFLog(@"I-RDB034029", @"handleServerMessage: %@, %@", action, body);
  801. id<FPersistentConnectionDelegate> delegate = self.delegate;
  802. if ([action isEqualToString:kFWPAsyncServerDataUpdate] ||
  803. [action isEqualToString:kFWPAsyncServerDataMerge]) {
  804. BOOL isMerge = [action isEqualToString:kFWPAsyncServerDataMerge];
  805. if ([body objectForKey:kFWPAsyncServerDataUpdateBodyPath] &&
  806. [body objectForKey:kFWPAsyncServerDataUpdateBodyData]) {
  807. NSString *path =
  808. [body objectForKey:kFWPAsyncServerDataUpdateBodyPath];
  809. id payloadData =
  810. [body objectForKey:kFWPAsyncServerDataUpdateBodyData];
  811. if (isMerge && [payloadData isKindOfClass:[NSDictionary class]] &&
  812. [payloadData count] == 0) {
  813. // ignore empty merge
  814. } else {
  815. [delegate
  816. onDataUpdate:self
  817. forPath:path
  818. message:payloadData
  819. isMerge:isMerge
  820. tagId:[body objectForKey:
  821. kFWPAsyncServerDataUpdateBodyTag]];
  822. }
  823. } else {
  824. FFLog(
  825. @"I-RDB034030",
  826. @"Malformed data response from server missing path or data: %@",
  827. body);
  828. }
  829. } else if ([action isEqualToString:kFWPAsyncServerDataRangeMerge]) {
  830. NSString *path = body[kFWPAsyncServerDataUpdateBodyPath];
  831. NSArray *ranges = body[kFWPAsyncServerDataUpdateBodyData];
  832. NSNumber *tag = body[kFWPAsyncServerDataUpdateBodyTag];
  833. NSMutableArray *rangeMerges = [NSMutableArray array];
  834. for (NSDictionary *range in ranges) {
  835. NSString *startString = range[kFWPAsyncServerDataUpdateStartPath];
  836. NSString *endString = range[kFWPAsyncServerDataUpdateEndPath];
  837. id updateData = range[kFWPAsyncServerDataUpdateRangeMerge];
  838. id<FNode> updates = [FSnapshotUtilities nodeFrom:updateData];
  839. FPath *start = (startString != nil)
  840. ? [[FPath alloc] initWith:startString]
  841. : nil;
  842. FPath *end =
  843. (endString != nil) ? [[FPath alloc] initWith:endString] : nil;
  844. FRangeMerge *merge = [[FRangeMerge alloc] initWithStart:start
  845. end:end
  846. updates:updates];
  847. [rangeMerges addObject:merge];
  848. }
  849. [delegate onRangeMerge:rangeMerges forPath:path tagId:tag];
  850. } else if ([action isEqualToString:kFWPAsyncServerAuthRevoked]) {
  851. NSString *status = [body objectForKey:kFWPResponseForActionStatus];
  852. NSString *reason = [body objectForKey:kFWPResponseForActionData];
  853. [self onAuthRevokedWithStatus:status andReason:reason];
  854. } else if ([action isEqualToString:kFWPASyncServerListenCancelled]) {
  855. NSString *pathString =
  856. [body objectForKey:kFWPAsyncServerDataUpdateBodyPath];
  857. [self onListenRevoked:[[FPath alloc] initWith:pathString]];
  858. } else if ([action isEqualToString:kFWPAsyncServerSecurityDebug]) {
  859. NSString *msg = [body objectForKey:@"msg"];
  860. if (msg != nil) {
  861. NSArray *msgs = [msg componentsSeparatedByString:@"\n"];
  862. for (NSString *m in msgs) {
  863. FFWarn(@"I-RDB034031", @"%@", m);
  864. }
  865. }
  866. } else {
  867. // TODO: revoke listens, auth, security debug
  868. FFLog(@"I-RDB034032", @"Unsupported action from server: %@", action);
  869. }
  870. }
  871. - (void)restoreAuth {
  872. FFLog(@"I-RDB034033", @"Calling restore state");
  873. NSAssert(self->connectionState == ConnectionStateConnecting,
  874. @"Wanted to restore auth, but was in wrong state: %d",
  875. self->connectionState);
  876. if (self.authToken == nil) {
  877. FFLog(@"I-RDB034034", @"Not restoring auth because token is nil");
  878. self->connectionState = ConnectionStateConnected;
  879. [self restoreState];
  880. } else {
  881. FFLog(@"I-RDB034035", @"Restoring auth");
  882. self->connectionState = ConnectionStateAuthenticating;
  883. [self sendAuthAndRestoreStateAfterComplete:YES];
  884. }
  885. }
  886. - (void)restoreState {
  887. NSAssert(self->connectionState == ConnectionStateConnected,
  888. @"Should be connected if we're restoring state, but we are: %d",
  889. self->connectionState);
  890. [self.listens enumerateKeysAndObjectsUsingBlock:^(
  891. FQuerySpec *query, FOutstandingQuery *outstandingListen,
  892. BOOL *stop) {
  893. FFLog(@"I-RDB034036", @"Restoring listen for %@", query);
  894. [self sendListen:outstandingListen];
  895. }];
  896. NSArray *keys = [[self.outstandingPuts allKeys]
  897. sortedArrayUsingSelector:@selector(compare:)];
  898. for (int i = 0; i < [keys count]; i++) {
  899. if ([self.outstandingPuts objectForKey:[keys objectAtIndex:i]] != nil) {
  900. FFLog(@"I-RDB034037", @"Restoring put: %d", i);
  901. [self sendPut:[keys objectAtIndex:i]];
  902. } else {
  903. FFLog(@"I-RDB034038", @"Restoring put: skipped nil: %d", i);
  904. }
  905. }
  906. for (FTupleOnDisconnect *tuple in self.onDisconnectQueue) {
  907. [self sendOnDisconnectAction:tuple.action
  908. forPath:tuple.pathString
  909. withData:tuple.data
  910. andCallback:tuple.onComplete];
  911. }
  912. [self.onDisconnectQueue removeAllObjects];
  913. }
  914. - (NSArray *)removeListen:(FQuerySpec *)query {
  915. NSAssert(query.isDefault || !query.loadsAllData,
  916. @"removeListen called for non-default but complete query");
  917. FOutstandingQuery *outstanding = self.listens[query];
  918. if (!outstanding) {
  919. FFLog(@"I-RDB034039",
  920. @"Trying to remove listener for query %@ but no listener exists",
  921. query);
  922. return @[];
  923. } else {
  924. [self.listens removeObjectForKey:query];
  925. return @[ outstanding ];
  926. }
  927. }
  928. - (NSArray *)removeAllListensAtPath:(FPath *)path {
  929. FFLog(@"I-RDB034040", @"Removing all listens at path %@", path);
  930. NSMutableArray *removed = [NSMutableArray array];
  931. NSMutableArray *toRemove = [NSMutableArray array];
  932. [self.listens
  933. enumerateKeysAndObjectsUsingBlock:^(
  934. FQuerySpec *spec, FOutstandingQuery *outstanding, BOOL *stop) {
  935. if ([spec.path isEqual:path]) {
  936. [removed addObject:outstanding];
  937. [toRemove addObject:spec];
  938. }
  939. }];
  940. [self.listens removeObjectsForKeys:toRemove];
  941. return removed;
  942. }
  943. - (void)purgeOutstandingWrites {
  944. // We might have unacked puts in our queue that we need to ack now before we
  945. // send out any cancels...
  946. [self ackPuts];
  947. // Cancel in order
  948. NSArray *keys = [[self.outstandingPuts allKeys]
  949. sortedArrayUsingSelector:@selector(compare:)];
  950. for (NSNumber *key in keys) {
  951. FOutstandingPut *put = self.outstandingPuts[key];
  952. if (put.onCompleteBlock != nil) {
  953. put.onCompleteBlock(kFErrorWriteCanceled, nil);
  954. }
  955. }
  956. for (FTupleOnDisconnect *onDisconnect in self.onDisconnectQueue) {
  957. if (onDisconnect.onComplete != nil) {
  958. onDisconnect.onComplete(kFErrorWriteCanceled, nil);
  959. }
  960. }
  961. [self.outstandingPuts removeAllObjects];
  962. [self.onDisconnectQueue removeAllObjects];
  963. }
  964. - (void)ackPuts {
  965. for (FTupleCallbackStatus *put in self.putsToAck) {
  966. put.block(put.status, put.errorReason);
  967. }
  968. [self.putsToAck removeAllObjects];
  969. }
  970. - (void)handleTimestamp:(NSNumber *)timestamp {
  971. FFLog(@"I-RDB034041", @"Handling timestamp: %@", timestamp);
  972. double timestampDeltaMs = [timestamp doubleValue] -
  973. ([[NSDate date] timeIntervalSince1970] * 1000);
  974. [self.delegate onServerInfoUpdate:self
  975. updates:@{
  976. kDotInfoServerTimeOffset : [NSNumber
  977. numberWithDouble:timestampDeltaMs]
  978. }];
  979. }
  980. - (void)sendStats:(NSDictionary *)stats {
  981. if ([stats count] > 0) {
  982. NSDictionary *request = @{kFWPRequestCounters : stats};
  983. [self sendAction:kFWPRequestActionStats
  984. body:request
  985. sensitive:NO
  986. callback:^(NSDictionary *data) {
  987. NSString *status =
  988. [data objectForKey:kFWPResponseForActionStatus];
  989. NSString *errorReason =
  990. [data objectForKey:kFWPResponseForActionData];
  991. BOOL statusOk =
  992. [status isEqualToString:kFWPResponseForActionStatusOk];
  993. if (!statusOk) {
  994. FFLog(@"I-RDB034042", @"Failed to send stats: %@",
  995. errorReason);
  996. }
  997. }];
  998. } else {
  999. FFLog(@"I-RDB034043", @"Not sending stats because stats are empty");
  1000. }
  1001. }
  1002. - (void)sendConnectStats {
  1003. NSMutableDictionary *stats = [NSMutableDictionary dictionary];
  1004. #if TARGET_OS_IOS || TARGET_OS_TV
  1005. if (self.config.persistenceEnabled) {
  1006. stats[@"persistence.ios.enabled"] = @1;
  1007. }
  1008. #elif TARGET_OS_OSX
  1009. if (self.config.persistenceEnabled) {
  1010. stats[@"persistence.osx.enabled"] = @1;
  1011. }
  1012. #endif
  1013. NSString *sdkVersion =
  1014. [[FIRDatabase sdkVersion] stringByReplacingOccurrencesOfString:@"."
  1015. withString:@"-"];
  1016. NSString *sdkStatName =
  1017. [NSString stringWithFormat:@"sdk.objc.%@", sdkVersion];
  1018. stats[sdkStatName] = @1;
  1019. FFLog(@"I-RDB034044", @"Sending first connection stats");
  1020. [self sendStats:stats];
  1021. }
  1022. - (NSDictionary *)dumpListens {
  1023. return self.listens;
  1024. }
  1025. @end