FIRMessagingAuthService.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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)init {
  47. self = [super init];
  48. if (self) {
  49. _checkinStore = [[FIRMessagingCheckinStore alloc] init];
  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. - (BOOL)hasCheckinPlist {
  61. return [_checkinStore hasCheckinPlist];
  62. }
  63. - (void)scheduleCheckin:(BOOL)immediately {
  64. // Checkin is still valid, so a remote checkin is not required.
  65. if ([self.checkinPreferences hasValidCheckinInfo]) {
  66. return;
  67. }
  68. // Checkin is already scheduled, so this (non-immediate) request can be ignored.
  69. if (!immediately && [self.scheduledCheckinTimer isValid]) {
  70. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeAuthService000,
  71. @"Checkin sync already scheduled. Will not schedule.");
  72. return;
  73. }
  74. if (immediately) {
  75. [self performScheduledCheckin];
  76. } else {
  77. int64_t checkinRetryDuration = [self calculateNextCheckinRetryIntervalInSeconds];
  78. [self startCheckinTimerWithDuration:(NSTimeInterval)checkinRetryDuration];
  79. }
  80. }
  81. - (void)startCheckinTimerWithDuration:(NSTimeInterval)timerDuration {
  82. self.scheduledCheckinTimer =
  83. [NSTimer scheduledTimerWithTimeInterval:timerDuration
  84. target:self
  85. selector:@selector(onScheduledCheckinTimerFired:)
  86. userInfo:nil
  87. repeats:NO];
  88. // Add some tolerance to the timer, to allow iOS to be more flexible with this timer
  89. self.scheduledCheckinTimer.tolerance = 0.5;
  90. }
  91. - (void)clearScheduledCheckinTimer {
  92. [self.scheduledCheckinTimer invalidate];
  93. self.scheduledCheckinTimer = nil;
  94. }
  95. - (void)onScheduledCheckinTimerFired:(NSTimer *)timer {
  96. [self performScheduledCheckin];
  97. }
  98. - (void)performScheduledCheckin {
  99. // No checkin scheduled as of now.
  100. [self clearScheduledCheckinTimer];
  101. // Checkin is still valid, so a remote checkin is not required.
  102. if ([self.checkinPreferences hasValidCheckinInfo]) {
  103. return;
  104. }
  105. FIRMessaging_WEAKIFY(self);
  106. [self fetchCheckinInfoWithHandler:^(FIRMessagingCheckinPreferences *_Nullable checkinPreferences,
  107. NSError *_Nullable error) {
  108. FIRMessaging_STRONGIFY(self);
  109. self.checkinRetryCount++;
  110. if (error) {
  111. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeAuthService001, @"Checkin error %@.", error);
  112. dispatch_async(dispatch_get_main_queue(), ^{
  113. // Schedule another checkin
  114. [self scheduleCheckin:NO];
  115. });
  116. } else {
  117. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeAuthService002, @"Checkin success.");
  118. }
  119. }];
  120. }
  121. - (int64_t)calculateNextCheckinRetryIntervalInSeconds {
  122. // persistent failures can lead to overflow prevent that.
  123. if (self.checkinRetryCount >= 10) {
  124. return kMaxCheckinRetryIntervalInSeconds;
  125. }
  126. return MIN(1 << self.checkinRetryCount, kMaxCheckinRetryIntervalInSeconds);
  127. }
  128. #pragma mark - Checkin Service
  129. - (BOOL)hasValidCheckinInfo {
  130. return [self.checkinPreferences hasValidCheckinInfo];
  131. }
  132. - (void)fetchCheckinInfoWithHandler:(nullable FIRMessagingDeviceCheckinCompletion)handler {
  133. // Perform any changes to self.checkinHandlers and _isCheckinInProgress in a thread-safe way.
  134. @synchronized(self) {
  135. [self.checkinHandlers addObject:[handler copy]];
  136. if (_isCheckinInProgress) {
  137. // Nothing more to do until our checkin request is done
  138. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeAuthServiceCheckinInProgress,
  139. @"Checkin is in progress\n");
  140. return;
  141. }
  142. }
  143. // Checkin is still valid, so a remote checkin is not required.
  144. if ([self.checkinPreferences hasValidCheckinInfo]) {
  145. [self notifyCheckinHandlersWithCheckin:self.checkinPreferences error:nil];
  146. return;
  147. }
  148. @synchronized(self) {
  149. _isCheckinInProgress = YES;
  150. }
  151. [self.checkinService
  152. checkinWithExistingCheckin:self.checkinPreferences
  153. completion:^(FIRMessagingCheckinPreferences *checkinPreferences,
  154. NSError *error) {
  155. @synchronized(self) {
  156. self->_isCheckinInProgress = NO;
  157. }
  158. if (error) {
  159. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeAuthService003,
  160. @"Failed to checkin device %@", error);
  161. [self notifyCheckinHandlersWithCheckin:nil error:error];
  162. return;
  163. }
  164. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeAuthService004,
  165. @"Successfully got checkin credentials");
  166. BOOL hasSameCachedPreferences =
  167. [self cachedCheckinMatchesCheckin:checkinPreferences];
  168. checkinPreferences.hasPreCachedAuthCredentials = hasSameCachedPreferences;
  169. // Update to the most recent checkin preferences
  170. self.checkinPreferences = checkinPreferences;
  171. // Save the checkin info to disk
  172. // Keychain might not be accessible, so confirm that checkin preferences can
  173. // be saved
  174. [self->_checkinStore
  175. saveCheckinPreferences:checkinPreferences
  176. handler:^(NSError *checkinSaveError) {
  177. if (checkinSaveError && !hasSameCachedPreferences) {
  178. // The checkin info was new, but it couldn't be
  179. // written to the Keychain. Delete any stuff that was
  180. // cached in memory. This doesn't delete any
  181. // previously persisted preferences.
  182. FIRMessagingLoggerError(
  183. kFIRMessagingMessageCodeService004,
  184. @"Unable to save checkin info, resetting "
  185. @"checkin preferences "
  186. "in memory.");
  187. [checkinPreferences reset];
  188. [self
  189. notifyCheckinHandlersWithCheckin:nil
  190. error:
  191. checkinSaveError];
  192. } else {
  193. // The checkin is either new, or it was the same (and
  194. // it couldn't be saved). Either way, report that the
  195. // checkin preferences were received successfully.
  196. [self notifyCheckinHandlersWithCheckin:
  197. checkinPreferences
  198. error:nil];
  199. if (!hasSameCachedPreferences) {
  200. // Checkin is new.
  201. // Notify any listeners that might be waiting for
  202. // checkin to be fetched, such as Firebase
  203. // Messaging (for its MCS connection).
  204. dispatch_async(dispatch_get_main_queue(), ^{
  205. [[NSNotificationCenter defaultCenter]
  206. postNotificationName:
  207. kFIRMessagingCheckinFetchedNotification
  208. object:nil];
  209. });
  210. }
  211. }
  212. }];
  213. }];
  214. }
  215. - (FIRMessagingCheckinPreferences *)checkinPreferences {
  216. return _checkinPreferences;
  217. }
  218. - (void)stopCheckinRequest {
  219. [self.checkinService stopFetching];
  220. }
  221. - (void)resetCheckinWithHandler:(void (^)(NSError *error))handler {
  222. [_checkinStore removeCheckinPreferencesWithHandler:^(NSError *error) {
  223. if (!error) {
  224. self.checkinPreferences = nil;
  225. }
  226. if (handler) {
  227. handler(error);
  228. }
  229. }];
  230. }
  231. #pragma mark - Private
  232. /**
  233. * Goes through the current list of checkin handlers and fires them with the same checkin and/or
  234. * error info. The checkin handlers will get cleared after.
  235. */
  236. - (void)notifyCheckinHandlersWithCheckin:(nullable FIRMessagingCheckinPreferences *)checkin
  237. error:(nullable NSError *)error {
  238. @synchronized(self) {
  239. for (FIRMessagingDeviceCheckinCompletion handler in self.checkinHandlers) {
  240. handler(checkin, error);
  241. }
  242. [self.checkinHandlers removeAllObjects];
  243. }
  244. }
  245. - (void)setCheckinHandlers:(NSMutableArray<FIRMessagingDeviceCheckinCompletion> *)checkinHandlers {
  246. NSLog(@"%lu", (unsigned long)self.checkinHandlers.count);
  247. }
  248. /**
  249. * Given a |checkin|, it will compare it to the current checkinPreferences to see if the
  250. * deviceID and secretToken are the same.
  251. */
  252. - (BOOL)cachedCheckinMatchesCheckin:(FIRMessagingCheckinPreferences *)checkin {
  253. if (self.checkinPreferences && checkin) {
  254. return ([self.checkinPreferences.deviceID isEqualToString:checkin.deviceID] &&
  255. [self.checkinPreferences.secretToken isEqualToString:checkin.secretToken]);
  256. }
  257. return NO;
  258. }
  259. @end