FIRMessagingClient.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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 "FIRMessagingClient.h"
  17. #import <FirebaseCore/FIRReachabilityChecker.h>
  18. #import "FIRMessagingConnection.h"
  19. #import "FIRMessagingConstants.h"
  20. #import "FIRMessagingDataMessageManager.h"
  21. #import "FIRMessagingDefines.h"
  22. #import "FIRMessagingLogger.h"
  23. #import "FIRMessagingRegistrar.h"
  24. #import "FIRMessagingRmqManager.h"
  25. #import "FIRMessagingTopicsCommon.h"
  26. #import "FIRMessagingUtilities.h"
  27. #import "NSError+FIRMessaging.h"
  28. static const NSTimeInterval kConnectTimeoutInterval = 40.0;
  29. static const NSTimeInterval kReconnectDelayInSeconds = 2 * 60; // 2 minutes
  30. static const NSUInteger kMaxRetryExponent = 10; // 2^10 = 1024 seconds ~= 17 minutes
  31. static NSString *const kFIRMessagingMCSServerHost = @"mtalk.google.com";
  32. static NSUInteger const kFIRMessagingMCSServerPort = 5228;
  33. // register device with checkin
  34. typedef void(^FIRMessagingRegisterDeviceHandler)(NSError *error);
  35. static NSString *FIRMessagingServerHost() {
  36. static NSString *serverHost = nil;
  37. static dispatch_once_t onceToken;
  38. dispatch_once(&onceToken, ^{
  39. NSDictionary *environment = [[NSProcessInfo processInfo] environment];
  40. NSString *customServerHostAndPort = environment[@"FCM_MCS_HOST"];
  41. NSString *host = [customServerHostAndPort componentsSeparatedByString:@":"].firstObject;
  42. if (host) {
  43. serverHost = host;
  44. } else {
  45. serverHost = kFIRMessagingMCSServerHost;
  46. }
  47. });
  48. return serverHost;
  49. }
  50. static NSUInteger FIRMessagingServerPort() {
  51. static NSUInteger serverPort = kFIRMessagingMCSServerPort;
  52. static dispatch_once_t onceToken;
  53. dispatch_once(&onceToken, ^{
  54. NSDictionary *environment = [[NSProcessInfo processInfo] environment];
  55. NSString *customServerHostAndPort = environment[@"FCM_MCS_HOST"];
  56. NSArray<NSString *> *components = [customServerHostAndPort componentsSeparatedByString:@":"];
  57. NSUInteger port = (NSUInteger)[components.lastObject integerValue];
  58. if (port != 0) {
  59. serverPort = port;
  60. }
  61. });
  62. return serverPort;
  63. }
  64. @interface FIRMessagingClient () <FIRMessagingConnectionDelegate>
  65. @property(nonatomic, readwrite, weak) id<FIRMessagingClientDelegate> clientDelegate;
  66. @property(nonatomic, readwrite, strong) FIRMessagingConnection *connection;
  67. @property(nonatomic, readwrite, strong) FIRMessagingRegistrar *registrar;
  68. @property(nonatomic, readwrite, strong) NSString *senderId;
  69. // FIRMessagingService owns these instances
  70. @property(nonatomic, readwrite, weak) FIRMessagingRmqManager *rmq2Manager;
  71. @property(nonatomic, readwrite, weak) FIRReachabilityChecker *reachability;
  72. @property(nonatomic, readwrite, assign) int64_t lastConnectedTimestamp;
  73. @property(nonatomic, readwrite, assign) int64_t lastDisconnectedTimestamp;
  74. @property(nonatomic, readwrite, assign) NSUInteger connectRetryCount;
  75. // Should we stay connected to MCS or not. Should be YES throughout the lifetime
  76. // of a MCS connection. If set to NO it signifies that an existing MCS connection
  77. // should be disconnected.
  78. @property(nonatomic, readwrite, assign) BOOL stayConnected;
  79. @property(nonatomic, readwrite, assign) NSTimeInterval connectionTimeoutInterval;
  80. // Used if the MCS connection suddenly breaksdown in the middle and we want to reconnect
  81. // with some permissible delay we schedule a reconnect and set it to YES and when it's
  82. // scheduled this will be set back to NO.
  83. @property(nonatomic, readwrite, assign) BOOL didScheduleReconnect;
  84. // handlers
  85. @property(nonatomic, readwrite, copy) FIRMessagingConnectCompletionHandler connectHandler;
  86. @end
  87. @implementation FIRMessagingClient
  88. - (instancetype)init {
  89. FIRMessagingInvalidateInitializer();
  90. }
  91. - (instancetype)initWithDelegate:(id<FIRMessagingClientDelegate>)delegate
  92. reachability:(FIRReachabilityChecker *)reachability
  93. rmq2Manager:(FIRMessagingRmqManager *)rmq2Manager {
  94. self = [super init];
  95. if (self) {
  96. _reachability = reachability;
  97. _clientDelegate = delegate;
  98. _rmq2Manager = rmq2Manager;
  99. _registrar = [[FIRMessagingRegistrar alloc] init];
  100. _connectionTimeoutInterval = kConnectTimeoutInterval;
  101. // Listen for checkin fetch notifications, as connecting to MCS may have failed due to
  102. // missing checkin info (while it was being fetched).
  103. [[NSNotificationCenter defaultCenter] addObserver:self
  104. selector:@selector(checkinFetched:)
  105. name:kFIRMessagingCheckinFetchedNotification
  106. object:nil];
  107. }
  108. return self;
  109. }
  110. - (void)teardown {
  111. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient000, @"");
  112. self.stayConnected = NO;
  113. // Clear all the handlers
  114. self.connectHandler = nil;
  115. [self.connection teardown];
  116. // Stop all subscription requests
  117. [self.registrar cancelAllRequests];
  118. _FIRMessagingDevAssert(self.connection.state == kFIRMessagingConnectionNotConnected, @"Did not disconnect");
  119. [NSObject cancelPreviousPerformRequestsWithTarget:self];
  120. [[NSNotificationCenter defaultCenter] removeObserver:self];
  121. }
  122. - (void)cancelAllRequests {
  123. // Stop any checkin requests or any subscription requests
  124. [self.registrar cancelAllRequests];
  125. // Stop any future connection requests to MCS
  126. if (self.stayConnected && self.isConnected && !self.isConnectionActive) {
  127. self.stayConnected = NO;
  128. [NSObject cancelPreviousPerformRequestsWithTarget:self];
  129. }
  130. }
  131. #pragma mark - FIRMessaging subscribe
  132. - (void)updateSubscriptionWithToken:(NSString *)token
  133. topic:(NSString *)topic
  134. options:(NSDictionary *)options
  135. shouldDelete:(BOOL)shouldDelete
  136. handler:(FIRMessagingTopicOperationCompletion)handler {
  137. _FIRMessagingDevAssert(handler != nil, @"Invalid handler to FIRMessaging subscribe");
  138. FIRMessagingTopicOperationCompletion completion =
  139. ^void(FIRMessagingTopicOperationResult result, NSError * error) {
  140. if (error) {
  141. FIRMessagingLoggerError(kFIRMessagingMessageCodeClient001, @"Failed to subscribe to topic %@",
  142. error);
  143. } else {
  144. if (shouldDelete) {
  145. FIRMessagingLoggerInfo(kFIRMessagingMessageCodeClient002,
  146. @"Successfully unsubscribed from topic %@", topic);
  147. } else {
  148. FIRMessagingLoggerInfo(kFIRMessagingMessageCodeClient003,
  149. @"Successfully subscribed to topic %@", topic);
  150. }
  151. }
  152. handler(result, error);
  153. };
  154. [self.registrar tryToLoadValidCheckinInfo];
  155. [self.registrar updateSubscriptionToTopic:topic
  156. withToken:token
  157. options:options
  158. shouldDelete:shouldDelete
  159. handler:completion];
  160. }
  161. #pragma mark - MCS Connection
  162. - (BOOL)isConnected {
  163. return self.stayConnected && self.connection.state != kFIRMessagingConnectionNotConnected;
  164. }
  165. - (BOOL)isConnectionActive {
  166. return self.stayConnected && self.connection.state == kFIRMessagingConnectionSignedIn;
  167. }
  168. - (BOOL)shouldStayConnected {
  169. return self.stayConnected;
  170. }
  171. - (void)retryConnectionImmediately:(BOOL)immediately {
  172. // Do not connect to an invalid host or an invalid port
  173. if (!self.stayConnected || !self.connection.host || self.connection.port == 0) {
  174. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient004,
  175. @"FIRMessaging connection will not reconnect to MCS. "
  176. @"Stay connected: %d",
  177. self.stayConnected);
  178. return;
  179. }
  180. if (self.isConnectionActive) {
  181. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient005,
  182. @"FIRMessaging Connection skip retry, active");
  183. // already connected and logged in.
  184. // Heartbeat alarm is set and will force close the connection
  185. return;
  186. }
  187. if (self.isConnected) {
  188. // already connected and logged in.
  189. // Heartbeat alarm is set and will force close the connection
  190. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient006,
  191. @"FIRMessaging Connection skip retry, connected");
  192. return;
  193. }
  194. if (immediately) {
  195. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient007,
  196. @"Try to connect to MCS immediately");
  197. [self tryToConnect];
  198. } else {
  199. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient008, @"Try to connect to MCS lazily");
  200. // Avoid all the other logic that we have in other clients, since this would always happen
  201. // when the app is in the foreground and since the FIRMessaging connection isn't shared with any other
  202. // app we can be more aggressive in reconnections
  203. if (!self.didScheduleReconnect) {
  204. FIRMessaging_WEAKIFY(self);
  205. dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
  206. (int64_t)(kReconnectDelayInSeconds * NSEC_PER_SEC)),
  207. dispatch_get_main_queue(), ^{
  208. FIRMessaging_STRONGIFY(self);
  209. self.didScheduleReconnect = NO;
  210. [self tryToConnect];
  211. });
  212. self.didScheduleReconnect = YES;
  213. }
  214. }
  215. }
  216. - (void)connectWithHandler:(FIRMessagingConnectCompletionHandler)handler {
  217. if (self.isConnected) {
  218. NSError *error = [NSError fcm_errorWithCode:kFIRMessagingErrorCodeAlreadyConnected
  219. userInfo:@{
  220. NSLocalizedFailureReasonErrorKey: @"FIRMessaging is already connected",
  221. }];
  222. handler(error);
  223. return;
  224. }
  225. self.lastDisconnectedTimestamp = FIRMessagingCurrentTimestampInMilliseconds();
  226. self.connectHandler = handler;
  227. [self.registrar tryToLoadValidCheckinInfo];
  228. [self connect];
  229. }
  230. - (void)connect {
  231. // reset retry counts
  232. self.connectRetryCount = 0;
  233. if (self.isConnected) {
  234. return;
  235. }
  236. self.stayConnected = YES;
  237. BOOL isRegistrationComplete = [self.registrar hasValidCheckinInfo];
  238. if (!isRegistrationComplete) {
  239. if (![self.registrar tryToLoadValidCheckinInfo]) {
  240. // Checkin info is not available. This may be due to the checkin still being fetched.
  241. if (self.connectHandler) {
  242. NSError *error = [NSError errorWithFCMErrorCode:kFIRMessagingErrorCodeMissingDeviceID];
  243. self.connectHandler(error);
  244. }
  245. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient009,
  246. @"Failed to connect to MCS. No deviceID and secret found.");
  247. // Return for now. If checkin is, in fact, retrieved, the
  248. // |kFIRMessagingCheckinFetchedNotification| will be fired.
  249. return;
  250. }
  251. }
  252. [self setupConnectionAndConnect];
  253. }
  254. - (void)disconnect {
  255. // user called disconnect
  256. // We don't want to connect later even if no network is available.
  257. [self disconnectWithTryToConnectLater:NO];
  258. }
  259. /**
  260. * Disconnect the current client connection. Also explicitly stop and connction retries.
  261. *
  262. * @param tryToConnectLater If YES will try to connect later when sending upstream messages
  263. * else if NO do not connect again until user explicitly calls
  264. * connect.
  265. */
  266. - (void)disconnectWithTryToConnectLater:(BOOL)tryToConnectLater {
  267. self.stayConnected = tryToConnectLater;
  268. [self.connection signOut];
  269. _FIRMessagingDevAssert(self.connection.state == kFIRMessagingConnectionNotConnected,
  270. @"FIRMessaging connection did not disconnect");
  271. // since we can disconnect while still trying to establish the connection it's required to
  272. // cancel all performSelectors else the object might be retained
  273. [NSObject cancelPreviousPerformRequestsWithTarget:self
  274. selector:@selector(tryToConnect)
  275. object:nil];
  276. [NSObject cancelPreviousPerformRequestsWithTarget:self
  277. selector:@selector(didConnectTimeout)
  278. object:nil];
  279. self.connectHandler = nil;
  280. }
  281. #pragma mark - Checkin Notification
  282. - (void)checkinFetched:(NSNotification *)notification {
  283. // A failed checkin may have been the reason for the connection failure. Attempt a connection
  284. // if the checkin fetched notification is fired.
  285. if (self.stayConnected && !self.isConnected) {
  286. [self connect];
  287. }
  288. }
  289. #pragma mark - Messages
  290. - (void)sendMessage:(GPBMessage *)message {
  291. [self.connection sendProto:message];
  292. }
  293. - (void)sendOnConnectOrDrop:(GPBMessage *)message {
  294. [self.connection sendOnConnectOrDrop:message];
  295. }
  296. #pragma mark - FIRMessagingConnectionDelegate
  297. - (void)connection:(FIRMessagingConnection *)fcmConnection
  298. didCloseForReason:(FIRMessagingConnectionCloseReason)reason {
  299. self.lastDisconnectedTimestamp = FIRMessagingCurrentTimestampInMilliseconds();
  300. if (reason == kFIRMessagingConnectionCloseReasonSocketDisconnected) {
  301. // Cancel the not-yet-triggered timeout task before rescheduling, in case the previous sign in
  302. // failed, due to a connection error caused by bad network.
  303. [NSObject cancelPreviousPerformRequestsWithTarget:self
  304. selector:@selector(didConnectTimeout)
  305. object:nil];
  306. }
  307. if (self.stayConnected) {
  308. [self scheduleConnectRetry];
  309. }
  310. }
  311. - (void)didLoginWithConnection:(FIRMessagingConnection *)fcmConnection {
  312. // Cancel the not-yet-triggered timeout task.
  313. [NSObject cancelPreviousPerformRequestsWithTarget:self
  314. selector:@selector(didConnectTimeout)
  315. object:nil];
  316. self.connectRetryCount = 0;
  317. self.lastConnectedTimestamp = FIRMessagingCurrentTimestampInMilliseconds();
  318. [self.dataMessageManager setDeviceAuthID:self.registrar.deviceAuthID
  319. secretToken:self.registrar.secretToken];
  320. if (self.connectHandler) {
  321. self.connectHandler(nil);
  322. // notified the third party app with the registrationId.
  323. // we don't want them to know about the connection status and how it changes
  324. // so remove this handler
  325. self.connectHandler = nil;
  326. }
  327. }
  328. - (void)connectionDidRecieveMessage:(GtalkDataMessageStanza *)message {
  329. NSDictionary *parsedMessage = [self.dataMessageManager processPacket:message];
  330. if ([parsedMessage count]) {
  331. [self.dataMessageManager didReceiveParsedMessage:parsedMessage];
  332. }
  333. }
  334. - (int)connectionDidReceiveAckForRmqIds:(NSArray *)rmqIds {
  335. NSSet *rmqIDSet = [NSSet setWithArray:rmqIds];
  336. NSMutableArray *messagesSent = [NSMutableArray arrayWithCapacity:rmqIds.count];
  337. [self.rmq2Manager scanWithRmqMessageHandler:nil
  338. dataMessageHandler:^(int64_t rmqId, GtalkDataMessageStanza *stanza) {
  339. NSString *rmqIdString = [NSString stringWithFormat:@"%lld", rmqId];
  340. if ([rmqIDSet containsObject:rmqIdString]) {
  341. [messagesSent addObject:stanza];
  342. }
  343. }];
  344. for (GtalkDataMessageStanza *message in messagesSent) {
  345. [self.dataMessageManager didSendDataMessageStanza:message];
  346. }
  347. return [self.rmq2Manager removeRmqMessagesWithRmqIds:rmqIds];
  348. }
  349. #pragma mark - Private
  350. - (void)setupConnectionAndConnect {
  351. [self setupConnection];
  352. [self tryToConnect];
  353. }
  354. - (void)setupConnection {
  355. NSString *host = FIRMessagingServerHost();
  356. NSUInteger port = FIRMessagingServerPort();
  357. _FIRMessagingDevAssert([host length] > 0 && port != 0, @"Invalid port or host");
  358. if (self.connection != nil) {
  359. // if there is an old connection, explicitly sign it off.
  360. [self.connection signOut];
  361. self.connection.delegate = nil;
  362. }
  363. self.connection = [[FIRMessagingConnection alloc] initWithAuthID:self.registrar.deviceAuthID
  364. token:self.registrar.secretToken
  365. host:host
  366. port:port
  367. runLoop:[NSRunLoop mainRunLoop]
  368. rmq2Manager:self.rmq2Manager
  369. fcmManager:self.dataMessageManager];
  370. self.connection.delegate = self;
  371. }
  372. - (void)tryToConnect {
  373. if (!self.stayConnected) {
  374. return;
  375. }
  376. // Cancel any other pending signin requests.
  377. [NSObject cancelPreviousPerformRequestsWithTarget:self
  378. selector:@selector(tryToConnect)
  379. object:nil];
  380. // Do not re-sign in if there is already a connection in progress.
  381. if (self.connection.state != kFIRMessagingConnectionNotConnected) {
  382. return;
  383. }
  384. _FIRMessagingDevAssert(self.registrar.deviceAuthID.length > 0 &&
  385. self.registrar.secretToken.length > 0 &&
  386. self.connection != nil,
  387. @"Invalid state cannot connect");
  388. self.connectRetryCount = MIN(kMaxRetryExponent, self.connectRetryCount + 1);
  389. [self performSelector:@selector(didConnectTimeout)
  390. withObject:nil
  391. afterDelay:self.connectionTimeoutInterval];
  392. [self.connection signIn];
  393. }
  394. - (void)didConnectTimeout {
  395. _FIRMessagingDevAssert(self.connection.state != kFIRMessagingConnectionSignedIn,
  396. @"Invalid state for MCS connection");
  397. if (self.stayConnected) {
  398. [self.connection signOut];
  399. [self scheduleConnectRetry];
  400. }
  401. }
  402. #pragma mark - Schedulers
  403. - (void)scheduleConnectRetry {
  404. FIRReachabilityStatus status = self.reachability.reachabilityStatus;
  405. BOOL isReachable = (status == kFIRReachabilityViaWifi || status == kFIRReachabilityViaCellular);
  406. if (!isReachable) {
  407. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient010,
  408. @"Internet not reachable when signing into MCS during a retry");
  409. FIRMessagingConnectCompletionHandler handler = [self.connectHandler copy];
  410. // disconnect before issuing a callback
  411. [self disconnectWithTryToConnectLater:YES];
  412. NSError *error =
  413. [NSError errorWithDomain:@"No internet available, cannot connect to FIRMessaging"
  414. code:kFIRMessagingErrorCodeNetwork
  415. userInfo:nil];
  416. if (handler) {
  417. handler(error);
  418. self.connectHandler = nil;
  419. }
  420. return;
  421. }
  422. NSUInteger retryInterval = [self nextRetryInterval];
  423. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient011,
  424. @"Failed to sign in to MCS, retry in %lu seconds",
  425. _FIRMessaging_UL(retryInterval));
  426. [self performSelector:@selector(tryToConnect) withObject:nil afterDelay:retryInterval];
  427. }
  428. - (NSUInteger)nextRetryInterval {
  429. return 1u << self.connectRetryCount;
  430. }
  431. @end