FIRMessagingClient.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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 "Firebase/Messaging/Protos/GtalkCore.pbobjc.h"
  18. #import <FirebaseInstanceID/FIRInstanceID_Private.h>
  19. #import <FirebaseMessaging/FIRMessaging.h>
  20. #import <GoogleUtilities/GULReachabilityChecker.h>
  21. #import "Firebase/Messaging/FIRMessagingConnection.h"
  22. #import "Firebase/Messaging/FIRMessagingConstants.h"
  23. #import "Firebase/Messaging/FIRMessagingDataMessageManager.h"
  24. #import "Firebase/Messaging/FIRMessagingDefines.h"
  25. #import "Firebase/Messaging/FIRMessagingLogger.h"
  26. #import "Firebase/Messaging/FIRMessagingPubSubRegistrar.h"
  27. #import "Firebase/Messaging/FIRMessagingRmqManager.h"
  28. #import "Firebase/Messaging/FIRMessagingTopicsCommon.h"
  29. #import "Firebase/Messaging/FIRMessagingUtilities.h"
  30. #import "Firebase/Messaging/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. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeRegistrar000,
  167. @"Device check in error, no auth credentials found");
  168. NSError *error = [NSError errorWithFCMErrorCode:kFIRMessagingErrorCodeMissingDeviceID];
  169. handler(error);
  170. }
  171. }
  172. #pragma mark - MCS Connection
  173. - (BOOL)isConnected {
  174. return self.stayConnected && self.connection.state != kFIRMessagingConnectionNotConnected;
  175. }
  176. - (BOOL)isConnectionActive {
  177. return self.stayConnected && self.connection.state == kFIRMessagingConnectionSignedIn;
  178. }
  179. - (BOOL)shouldStayConnected {
  180. return self.stayConnected;
  181. }
  182. - (void)retryConnectionImmediately:(BOOL)immediately {
  183. // Do not connect to an invalid host or an invalid port
  184. if (!self.stayConnected || !self.connection.host || self.connection.port == 0) {
  185. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient004,
  186. @"FIRMessaging connection will not reconnect to MCS. "
  187. @"Stay connected: %d",
  188. self.stayConnected);
  189. return;
  190. }
  191. if (self.isConnectionActive) {
  192. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient005,
  193. @"FIRMessaging Connection skip retry, active");
  194. // already connected and logged in.
  195. // Heartbeat alarm is set and will force close the connection
  196. return;
  197. }
  198. if (self.isConnected) {
  199. // already connected and logged in.
  200. // Heartbeat alarm is set and will force close the connection
  201. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient006,
  202. @"FIRMessaging Connection skip retry, connected");
  203. return;
  204. }
  205. if (immediately) {
  206. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient007,
  207. @"Try to connect to MCS immediately");
  208. [self tryToConnect];
  209. } else {
  210. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient008, @"Try to connect to MCS lazily");
  211. // Avoid all the other logic that we have in other clients, since this would always happen
  212. // when the app is in the foreground and since the FIRMessaging connection isn't shared with any
  213. // other app we can be more aggressive in reconnections
  214. if (!self.didScheduleReconnect) {
  215. FIRMessaging_WEAKIFY(self);
  216. dispatch_after(
  217. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kReconnectDelayInSeconds * NSEC_PER_SEC)),
  218. dispatch_get_main_queue(), ^{
  219. FIRMessaging_STRONGIFY(self);
  220. self.didScheduleReconnect = NO;
  221. [self tryToConnect];
  222. });
  223. self.didScheduleReconnect = YES;
  224. }
  225. }
  226. }
  227. - (void)connectWithHandler:(FIRMessagingConnectCompletionHandler)handler {
  228. if (self.isConnected) {
  229. NSError *error =
  230. [NSError fcm_errorWithCode:kFIRMessagingErrorCodeAlreadyConnected
  231. userInfo:@{
  232. NSLocalizedFailureReasonErrorKey : @"FIRMessaging is already connected",
  233. }];
  234. handler(error);
  235. return;
  236. }
  237. self.lastDisconnectedTimestamp = FIRMessagingCurrentTimestampInMilliseconds();
  238. self.connectHandler = handler;
  239. [self connect];
  240. }
  241. - (void)connect {
  242. // reset retry counts
  243. self.connectRetryCount = 0;
  244. if (self.isConnected) {
  245. return;
  246. }
  247. self.stayConnected = YES;
  248. if (![[FIRInstanceID instanceID] tryToLoadValidCheckinInfo]) {
  249. // Checkin info is not available. This may be due to the checkin still being fetched.
  250. if (self.connectHandler) {
  251. NSError *error = [NSError errorWithFCMErrorCode:kFIRMessagingErrorCodeMissingDeviceID];
  252. self.connectHandler(error);
  253. }
  254. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient009,
  255. @"Failed to connect to MCS. No deviceID and secret found.");
  256. // Return for now. If checkin is, in fact, retrieved, the
  257. // |kFIRMessagingCheckinFetchedNotification| will be fired.
  258. return;
  259. }
  260. [self setupConnectionAndConnect];
  261. }
  262. - (void)disconnect {
  263. // user called disconnect
  264. // We don't want to connect later even if no network is available.
  265. [self disconnectWithTryToConnectLater:NO];
  266. }
  267. /**
  268. * Disconnect the current client connection. Also explicitly stop and connction retries.
  269. *
  270. * @param tryToConnectLater If YES will try to connect later when sending upstream messages
  271. * else if NO do not connect again until user explicitly calls
  272. * connect.
  273. */
  274. - (void)disconnectWithTryToConnectLater:(BOOL)tryToConnectLater {
  275. self.stayConnected = tryToConnectLater;
  276. [self.connection signOut];
  277. // since we can disconnect while still trying to establish the connection it's required to
  278. // cancel all performSelectors else the object might be retained
  279. [NSObject cancelPreviousPerformRequestsWithTarget:self
  280. selector:@selector(tryToConnect)
  281. object:nil];
  282. [NSObject cancelPreviousPerformRequestsWithTarget:self
  283. selector:@selector(didConnectTimeout)
  284. object:nil];
  285. self.connectHandler = nil;
  286. }
  287. #pragma mark - Checkin Notification
  288. - (void)checkinFetched:(NSNotification *)notification {
  289. // A failed checkin may have been the reason for the connection failure. Attempt a connection
  290. // if the checkin fetched notification is fired.
  291. if (self.stayConnected && !self.isConnected) {
  292. [self connect];
  293. }
  294. }
  295. #pragma mark - Messages
  296. - (void)sendMessage:(GPBMessage *)message {
  297. [self.connection sendProto:message];
  298. }
  299. - (void)sendOnConnectOrDrop:(GPBMessage *)message {
  300. [self.connection sendOnConnectOrDrop:message];
  301. }
  302. #pragma mark - FIRMessagingConnectionDelegate
  303. - (void)connection:(FIRMessagingConnection *)fcmConnection
  304. didCloseForReason:(FIRMessagingConnectionCloseReason)reason {
  305. self.lastDisconnectedTimestamp = FIRMessagingCurrentTimestampInMilliseconds();
  306. if (reason == kFIRMessagingConnectionCloseReasonSocketDisconnected) {
  307. // Cancel the not-yet-triggered timeout task before rescheduling, in case the previous sign in
  308. // failed, due to a connection error caused by bad network.
  309. [NSObject cancelPreviousPerformRequestsWithTarget:self
  310. selector:@selector(didConnectTimeout)
  311. object:nil];
  312. }
  313. if (self.stayConnected) {
  314. [self scheduleConnectRetry];
  315. }
  316. }
  317. - (void)didLoginWithConnection:(FIRMessagingConnection *)fcmConnection {
  318. // Cancel the not-yet-triggered timeout task.
  319. [NSObject cancelPreviousPerformRequestsWithTarget:self
  320. selector:@selector(didConnectTimeout)
  321. object:nil];
  322. self.connectRetryCount = 0;
  323. self.lastConnectedTimestamp = FIRMessagingCurrentTimestampInMilliseconds();
  324. [self.dataMessageManager setDeviceAuthID:[FIRInstanceID instanceID].deviceAuthID
  325. secretToken:[FIRInstanceID instanceID].secretToken];
  326. if (self.connectHandler) {
  327. self.connectHandler(nil);
  328. // notified the third party app with the registrationId.
  329. // we don't want them to know about the connection status and how it changes
  330. // so remove this handler
  331. self.connectHandler = nil;
  332. }
  333. }
  334. - (void)connectionDidRecieveMessage:(GtalkDataMessageStanza *)message {
  335. NSDictionary *parsedMessage = [self.dataMessageManager processPacket:message];
  336. if ([parsedMessage count]) {
  337. [self.dataMessageManager didReceiveParsedMessage:parsedMessage];
  338. }
  339. }
  340. - (void)connectionDidReceiveAckForRmqIds:(NSArray *)rmqIds {
  341. NSSet *rmqIDSet = [NSSet setWithArray:rmqIds];
  342. NSMutableArray *messagesSent = [NSMutableArray arrayWithCapacity:rmqIds.count];
  343. [self.rmq2Manager scanWithRmqMessageHandler:^(NSDictionary *messages) {
  344. for (NSString *rmqID in messages) {
  345. GPBMessage *proto = messages[rmqID];
  346. GtalkDataMessageStanza *stanza = (GtalkDataMessageStanza *)proto;
  347. if ([rmqIDSet containsObject:rmqID]) {
  348. [messagesSent addObject:stanza];
  349. }
  350. }
  351. }];
  352. for (GtalkDataMessageStanza *message in messagesSent) {
  353. [self.dataMessageManager didSendDataMessageStanza:message];
  354. }
  355. [self.rmq2Manager removeRmqMessagesWithRmqIds:rmqIds];
  356. }
  357. #pragma mark - Private
  358. - (void)setupConnectionAndConnect {
  359. [self setupConnection];
  360. [self tryToConnect];
  361. }
  362. - (void)setupConnection {
  363. NSString *host = FIRMessagingServerHost();
  364. NSUInteger port = FIRMessagingServerPort();
  365. if (self.connection != nil) {
  366. // if there is an old connection, explicitly sign it off.
  367. [self.connection signOut];
  368. self.connection.delegate = nil;
  369. }
  370. self.connection =
  371. [[FIRMessagingConnection alloc] initWithAuthID:[FIRInstanceID instanceID].deviceAuthID
  372. token:[FIRInstanceID instanceID].secretToken
  373. host:host
  374. port:port
  375. runLoop:[NSRunLoop mainRunLoop]
  376. rmq2Manager:self.rmq2Manager
  377. fcmManager:self.dataMessageManager];
  378. self.connection.delegate = self;
  379. }
  380. - (void)tryToConnect {
  381. if (!self.stayConnected) {
  382. return;
  383. }
  384. // Cancel any other pending signin requests.
  385. [NSObject cancelPreviousPerformRequestsWithTarget:self
  386. selector:@selector(tryToConnect)
  387. object:nil];
  388. NSString *deviceAuthID = [FIRInstanceID instanceID].deviceAuthID;
  389. NSString *secretToken = [FIRInstanceID instanceID].secretToken;
  390. if (deviceAuthID.length == 0 || secretToken.length == 0 || !self.connection) {
  391. FIRMessagingLoggerWarn(
  392. kFIRMessagingMessageCodeClientInvalidState,
  393. @"Invalid state to connect, deviceAuthID: %@, secretToken: %@, connection state: %ld",
  394. deviceAuthID, secretToken, (long)self.connection.state);
  395. return;
  396. }
  397. // Do not re-sign in if there is already a connection in progress.
  398. if (self.connection.state != kFIRMessagingConnectionNotConnected) {
  399. return;
  400. }
  401. self.connectRetryCount = MIN(kMaxRetryExponent, self.connectRetryCount + 1);
  402. [self performSelector:@selector(didConnectTimeout)
  403. withObject:nil
  404. afterDelay:self.connectionTimeoutInterval];
  405. [self.connection signIn];
  406. }
  407. - (void)didConnectTimeout {
  408. if (self.connection.state == kFIRMessagingConnectionSignedIn) {
  409. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeClientInvalidStateTimeout,
  410. @"Invalid state for connection timeout.");
  411. }
  412. if (self.stayConnected) {
  413. [self.connection signOut];
  414. [self scheduleConnectRetry];
  415. }
  416. }
  417. #pragma mark - Schedulers
  418. - (void)scheduleConnectRetry {
  419. GULReachabilityStatus status = self.reachability.reachabilityStatus;
  420. BOOL isReachable = (status == kGULReachabilityViaWifi || status == kGULReachabilityViaCellular);
  421. if (!isReachable) {
  422. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient010,
  423. @"Internet not reachable when signing into MCS during a retry");
  424. FIRMessagingConnectCompletionHandler handler = [self.connectHandler copy];
  425. // disconnect before issuing a callback
  426. [self disconnectWithTryToConnectLater:YES];
  427. NSError *error =
  428. [NSError errorWithDomain:@"No internet available, cannot connect to FIRMessaging"
  429. code:kFIRMessagingErrorCodeNetwork
  430. userInfo:nil];
  431. if (handler) {
  432. handler(error);
  433. self.connectHandler = nil;
  434. }
  435. return;
  436. }
  437. NSUInteger retryInterval = [self nextRetryInterval];
  438. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient011,
  439. @"Failed to sign in to MCS, retry in %lu seconds",
  440. _FIRMessaging_UL(retryInterval));
  441. [self performSelector:@selector(tryToConnect) withObject:nil afterDelay:retryInterval];
  442. }
  443. - (NSUInteger)nextRetryInterval {
  444. return 1u << self.connectRetryCount;
  445. }
  446. @end