No Description

FIRInstanceIDAuthService.m 12KB

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