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