FIRMessagingAuthService.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. /*
  2. * Copyright 2019 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/Token/FIRMessagingAuthService.h"
  17. #import "FirebaseMessaging/Sources/FIRMessagingConstants.h"
  18. #import "FirebaseMessaging/Sources/FIRMessagingDefines.h"
  19. #import "FirebaseMessaging/Sources/FIRMessagingLogger.h"
  20. #import "FirebaseMessaging/Sources/NSError+FIRMessaging.h"
  21. #import "FirebaseMessaging/Sources/Token/FIRMessagingCheckinPreferences.h"
  22. #import "FirebaseMessaging/Sources/Token/FIRMessagingCheckinStore.h"
  23. // Max time interval between checkin retry in seconds.
  24. static const int64_t kMaxCheckinRetryIntervalInSeconds = 1 << 5;
  25. @interface FIRMessagingAuthService ()
  26. // Used to retrieve and cache the checkin info to disk and Keychain.
  27. @property(nonatomic, readwrite, strong) FIRMessagingCheckinStore *checkinStore;
  28. // Used to perform single checkin fetches.
  29. @property(nonatomic, readwrite, strong) FIRMessagingCheckinService *checkinService;
  30. // The current checkin info. It will be compared to what is retrieved to determine whether it is
  31. // different than what is in the cache.
  32. @property(nonatomic, readwrite, strong) FIRMessagingCheckinPreferences *checkinPreferences;
  33. // This array will track multiple handlers waiting for checkin to be performed. When a checkin
  34. // request completes, all the handlers will be notified.
  35. // Changes to the checkinHandlers array should happen in a thread-safe manner.
  36. @property(nonatomic, readonly, strong)
  37. NSMutableArray<FIRMessagingDeviceCheckinCompletion> *checkinHandlers;
  38. // This is set to true if there is a checkin request in-flight.
  39. @property(atomic, readwrite, assign) BOOL isCheckinInProgress;
  40. // This timer is used a perform checkin retries. It is cancellable.
  41. @property(atomic, readwrite, strong) NSTimer *scheduledCheckinTimer;
  42. // The number of times checkin has been retried during a scheduled checkin.
  43. @property(atomic, readwrite, assign) int checkinRetryCount;
  44. @end
  45. @implementation FIRMessagingAuthService
  46. - (instancetype)initWithCheckinStore:(FIRMessagingCheckinStore *)checkinStore {
  47. self = [super init];
  48. if (self) {
  49. _checkinStore = checkinStore;
  50. _checkinPreferences = [_checkinStore cachedCheckinPreferences];
  51. _checkinService = [[FIRMessagingCheckinService alloc] init];
  52. _checkinHandlers = [[NSMutableArray alloc] init];
  53. }
  54. return self;
  55. }
  56. - (void)dealloc {
  57. [_scheduledCheckinTimer invalidate];
  58. }
  59. #pragma mark - Schedule Checkin
  60. - (void)scheduleCheckin:(BOOL)immediately {
  61. // Checkin is still valid, so a remote checkin is not required.
  62. if ([self.checkinPreferences hasValidCheckinInfo]) {
  63. return;
  64. }
  65. // Checkin is already scheduled, so this (non-immediate) request can be ignored.
  66. if (!immediately && [self.scheduledCheckinTimer isValid]) {
  67. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeAuthService000,
  68. @"Checkin sync already scheduled. Will not schedule.");
  69. return;
  70. }
  71. if (immediately) {
  72. [self performScheduledCheckin];
  73. } else {
  74. int64_t checkinRetryDuration = [self calculateNextCheckinRetryIntervalInSeconds];
  75. [self startCheckinTimerWithDuration:(NSTimeInterval)checkinRetryDuration];
  76. }
  77. }
  78. - (void)startCheckinTimerWithDuration:(NSTimeInterval)timerDuration {
  79. self.scheduledCheckinTimer =
  80. [NSTimer scheduledTimerWithTimeInterval:timerDuration
  81. target:self
  82. selector:@selector(onScheduledCheckinTimerFired:)
  83. userInfo:nil
  84. repeats:NO];
  85. // Add some tolerance to the timer, to allow iOS to be more flexible with this timer
  86. self.scheduledCheckinTimer.tolerance = 0.5;
  87. }
  88. - (void)clearScheduledCheckinTimer {
  89. [self.scheduledCheckinTimer invalidate];
  90. self.scheduledCheckinTimer = nil;
  91. }
  92. - (void)onScheduledCheckinTimerFired:(NSTimer *)timer {
  93. [self performScheduledCheckin];
  94. }
  95. - (void)performScheduledCheckin {
  96. // No checkin scheduled as of now.
  97. [self clearScheduledCheckinTimer];
  98. // Checkin is still valid, so a remote checkin is not required.
  99. if ([self.checkinPreferences hasValidCheckinInfo]) {
  100. return;
  101. }
  102. FIRMessaging_WEAKIFY(self);
  103. [self fetchCheckinInfoWithHandler:^(FIRMessagingCheckinPreferences *_Nullable checkinPreferences,
  104. NSError *_Nullable error) {
  105. FIRMessaging_STRONGIFY(self);
  106. self.checkinRetryCount++;
  107. if (error) {
  108. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeAuthService001, @"Checkin error %@.", error);
  109. dispatch_async(dispatch_get_main_queue(), ^{
  110. // Schedule another checkin
  111. [self scheduleCheckin:NO];
  112. });
  113. } else {
  114. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeAuthService002, @"Checkin success.");
  115. }
  116. }];
  117. }
  118. - (int64_t)calculateNextCheckinRetryIntervalInSeconds {
  119. // persistent failures can lead to overflow prevent that.
  120. if (self.checkinRetryCount >= 10) {
  121. return kMaxCheckinRetryIntervalInSeconds;
  122. }
  123. return MIN(1 << self.checkinRetryCount, kMaxCheckinRetryIntervalInSeconds);
  124. }
  125. #pragma mark - Checkin Service
  126. - (BOOL)hasValidCheckinInfo {
  127. return [self.checkinPreferences hasValidCheckinInfo];
  128. }
  129. - (void)fetchCheckinInfoWithHandler:(nullable FIRMessagingDeviceCheckinCompletion)handler {
  130. // Perform any changes to self.checkinHandlers and _isCheckinInProgress in a thread-safe way.
  131. @synchronized(self) {
  132. [self.checkinHandlers addObject:[handler copy]];
  133. if (_isCheckinInProgress) {
  134. // Nothing more to do until our checkin request is done
  135. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeAuthServiceCheckinInProgress,
  136. @"Checkin is in progress\n");
  137. return;
  138. }
  139. }
  140. // Checkin is still valid, so a remote checkin is not required.
  141. if ([self.checkinPreferences hasValidCheckinInfo]) {
  142. [self notifyCheckinHandlersWithCheckin:self.checkinPreferences error:nil];
  143. return;
  144. }
  145. @synchronized(self) {
  146. _isCheckinInProgress = YES;
  147. }
  148. [self.checkinService
  149. checkinWithExistingCheckin:self.checkinPreferences
  150. completion:^(FIRMessagingCheckinPreferences *checkinPreferences,
  151. NSError *error) {
  152. @synchronized(self) {
  153. self->_isCheckinInProgress = NO;
  154. }
  155. if (error) {
  156. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeAuthService003,
  157. @"Failed to checkin device %@", error);
  158. [self notifyCheckinHandlersWithCheckin:nil error:error];
  159. return;
  160. }
  161. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeAuthService004,
  162. @"Successfully got checkin credentials");
  163. BOOL hasSameCachedPreferences =
  164. [self cachedCheckinMatchesCheckin:checkinPreferences];
  165. checkinPreferences.hasPreCachedAuthCredentials = hasSameCachedPreferences;
  166. // Update to the most recent checkin preferences
  167. self.checkinPreferences = checkinPreferences;
  168. // Save the checkin info to disk
  169. // Keychain might not be accessible, so confirm that checkin preferences can
  170. // be saved
  171. [self->_checkinStore
  172. saveCheckinPreferences:checkinPreferences
  173. handler:^(NSError *checkinSaveError) {
  174. if (checkinSaveError && !hasSameCachedPreferences) {
  175. // The checkin info was new, but it couldn't be
  176. // written to the Keychain. Delete any stuff that was
  177. // cached in memory. This doesn't delete any
  178. // previously persisted preferences.
  179. FIRMessagingLoggerError(
  180. kFIRMessagingMessageCodeService004,
  181. @"Unable to save checkin info, resetting "
  182. @"checkin preferences "
  183. "in memory.");
  184. [checkinPreferences reset];
  185. [self
  186. notifyCheckinHandlersWithCheckin:nil
  187. error:
  188. checkinSaveError];
  189. } else {
  190. // The checkin is either new, or it was the same (and
  191. // it couldn't be saved). Either way, report that the
  192. // checkin preferences were received successfully.
  193. [self notifyCheckinHandlersWithCheckin:
  194. checkinPreferences
  195. error:nil];
  196. if (!hasSameCachedPreferences) {
  197. // Checkin is new.
  198. // Notify any listeners that might be waiting for
  199. // checkin to be fetched, such as Firebase
  200. // Messaging (for its MCS connection).
  201. dispatch_async(dispatch_get_main_queue(), ^{
  202. [[NSNotificationCenter defaultCenter]
  203. postNotificationName:
  204. kFIRMessagingCheckinFetchedNotification
  205. object:nil];
  206. });
  207. }
  208. }
  209. }];
  210. }];
  211. }
  212. - (FIRMessagingCheckinPreferences *)checkinPreferences {
  213. return _checkinPreferences;
  214. }
  215. - (void)stopCheckinRequest {
  216. [self.checkinService stopFetching];
  217. }
  218. - (void)resetCheckinWithHandler:(void (^)(NSError *error))handler {
  219. [_checkinStore removeCheckinPreferencesWithHandler:^(NSError *error) {
  220. if (!error) {
  221. self.checkinPreferences = nil;
  222. }
  223. if (handler) {
  224. handler(error);
  225. }
  226. }];
  227. }
  228. #pragma mark - Private
  229. /**
  230. * Goes through the current list of checkin handlers and fires them with the same checkin and/or
  231. * error info. The checkin handlers will get cleared after.
  232. */
  233. - (void)notifyCheckinHandlersWithCheckin:(nullable FIRMessagingCheckinPreferences *)checkin
  234. error:(nullable NSError *)error {
  235. @synchronized(self) {
  236. for (FIRMessagingDeviceCheckinCompletion handler in self.checkinHandlers) {
  237. handler(checkin, error);
  238. }
  239. [self.checkinHandlers removeAllObjects];
  240. }
  241. }
  242. - (void)setCheckinHandlers:(NSMutableArray<FIRMessagingDeviceCheckinCompletion> *)checkinHandlers {
  243. NSLog(@"%lu", (unsigned long)self.checkinHandlers.count);
  244. }
  245. /**
  246. * Given a |checkin|, it will compare it to the current checkinPreferences to see if the
  247. * deviceID and secretToken are the same.
  248. */
  249. - (BOOL)cachedCheckinMatchesCheckin:(FIRMessagingCheckinPreferences *)checkin {
  250. if (self.checkinPreferences && checkin) {
  251. return ([self.checkinPreferences.deviceID isEqualToString:checkin.deviceID] &&
  252. [self.checkinPreferences.secretToken isEqualToString:checkin.secretToken]);
  253. }
  254. return NO;
  255. }
  256. @end