FIRMessagingClient.m 20 KB

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