2 * Copyright (c) 2017 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
24 #import <Foundation/Foundation.h>
28 #import <dispatch/dispatch.h>
30 #import "keychain/ckks/CKKSZoneChangeFetcher.h"
31 #import "keychain/ckks/CKKSFetchAllRecordZoneChangesOperation.h"
32 #import "keychain/ckks/CKKSKeychainView.h"
33 #import "keychain/ckks/CKKSNearFutureScheduler.h"
34 #import "keychain/ckks/CloudKitCategories.h"
35 #import "keychain/ckks/CKKSReachabilityTracker.h"
36 #import "keychain/categories/NSError+UsefulConstructors.h"
37 #import "keychain/analytics/SecEventMetric.h"
38 #import "keychain/analytics/SecMetrics.h"
39 #import "keychain/ot/ObjCImprovements.h"
41 CKKSFetchBecause* const CKKSFetchBecauseAPNS = (CKKSFetchBecause*) @"apns";
42 CKKSFetchBecause* const CKKSFetchBecauseAPIFetchRequest = (CKKSFetchBecause*) @"api";
43 CKKSFetchBecause* const CKKSFetchBecauseCurrentItemFetchRequest = (CKKSFetchBecause*) @"currentitemcheck";
44 CKKSFetchBecause* const CKKSFetchBecauseInitialStart = (CKKSFetchBecause*) @"initialfetch";
45 CKKSFetchBecause* const CKKSFetchBecauseSecuritydRestart = (CKKSFetchBecause*) @"restart";
46 CKKSFetchBecause* const CKKSFetchBecausePreviousFetchFailed = (CKKSFetchBecause*) @"fetchfailed";
47 CKKSFetchBecause* const CKKSFetchBecauseNetwork = (CKKSFetchBecause*) @"network";
48 CKKSFetchBecause* const CKKSFetchBecauseKeyHierarchy = (CKKSFetchBecause*) @"keyhierarchy";
49 CKKSFetchBecause* const CKKSFetchBecauseTesting = (CKKSFetchBecause*) @"testing";
50 CKKSFetchBecause* const CKKSFetchBecauseResync = (CKKSFetchBecause*) @"resync";
51 CKKSFetchBecause* const CKKSFetchBecauseMoreComing = (CKKSFetchBecause*) @"more-coming";
53 #pragma mark - CKKSZoneChangeFetchDependencyOperation
54 @interface CKKSZoneChangeFetchDependencyOperation : CKKSResultOperation
55 @property (weak) CKKSZoneChangeFetcher* owner;
56 @property NSMutableArray<CKKSZoneChangeFetchDependencyOperation*>* chainDependents;
57 - (void)chainDependency:(CKKSZoneChangeFetchDependencyOperation*)newDependency;
60 @implementation CKKSZoneChangeFetchDependencyOperation
61 - (instancetype)init {
62 if((self = [super init])) {
63 _chainDependents = [NSMutableArray array];
68 - (NSError* _Nullable)descriptionError {
69 return [NSError errorWithDomain:CKKSResultDescriptionErrorDomain
70 code:CKKSResultDescriptionPendingSuccessfulFetch
71 description:@"Fetch failed"
72 underlying:self.owner.lastCKFetchError];
75 - (void)chainDependency:(CKKSZoneChangeFetchDependencyOperation*)newDependency {
76 [self addSuccessDependency:newDependency];
78 // There's no need to build a chain more than two links long. Move all our children up to depend on the new dependency.
79 for(CKKSZoneChangeFetchDependencyOperation* op in self.chainDependents) {
80 [newDependency.chainDependents addObject:op];
81 [op addSuccessDependency:newDependency];
82 [op removeDependency:self];
84 [self.chainDependents removeAllObjects];
88 #pragma mark - CKKSZoneChangeFetcher
90 @interface CKKSZoneChangeFetcher ()
91 @property NSString* name;
92 @property NSOperationQueue* operationQueue;
93 @property dispatch_queue_t queue;
95 @property NSError* lastCKFetchError;
97 @property NSMapTable<CKRecordZoneID*, id<CKKSChangeFetcherClient>>* clientMap;
99 @property CKKSFetchAllRecordZoneChangesOperation* currentFetch;
100 @property CKKSResultOperation* currentProcessResult;
102 @property NSMutableSet<CKKSFetchBecause*>* currentFetchReasons;
103 @property NSMutableSet<CKRecordZoneNotification*>* apnsPushes;
104 @property bool newRequests; // true if there's someone pending on successfulFetchDependency
105 @property CKKSZoneChangeFetchDependencyOperation* successfulFetchDependency;
107 @property (nullable) CKKSZoneChangeFetchDependencyOperation* inflightFetchDependency;
109 @property CKKSResultOperation* holdOperation;
112 @implementation CKKSZoneChangeFetcher
114 - (instancetype)initWithContainer:(CKContainer*)container
115 fetchClass:(Class<CKKSFetchRecordZoneChangesOperation>)fetchRecordZoneChangesOperationClass
116 reachabilityTracker:(CKKSReachabilityTracker *)reachabilityTracker
118 if((self = [super init])) {
119 _container = container;
120 _fetchRecordZoneChangesOperationClass = fetchRecordZoneChangesOperationClass;
121 _reachabilityTracker = reachabilityTracker;
123 _currentFetchReasons = [[NSMutableSet alloc] init];
124 _apnsPushes = [[NSMutableSet alloc] init];
126 _clientMap = [NSMapTable strongToWeakObjectsMapTable];
128 _name = @"zone-change-fetcher";
129 _queue = dispatch_queue_create([_name UTF8String], DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL);
130 _operationQueue = [[NSOperationQueue alloc] init];
131 _successfulFetchDependency = [self createSuccesfulFetchDependency];
132 _inflightFetchDependency = nil;
134 _newRequests = false;
136 // If we're testing, for the initial delay, use 0.5 second. Otherwise, 2s.
137 dispatch_time_t initialDelay = (SecCKKSReduceRateLimiting() ? 500 * NSEC_PER_MSEC : 2 * NSEC_PER_SEC);
139 // If we're testing, for the maximum delay, use 6 second. Otherwise, 2m.
140 dispatch_time_t maximumDelay = (SecCKKSReduceRateLimiting() ? 6 * NSEC_PER_SEC : 120 * NSEC_PER_SEC);
143 _fetchScheduler = [[CKKSNearFutureScheduler alloc] initWithName:@"zone-change-fetch-scheduler"
144 initialDelay:initialDelay
146 maximumDelay:maximumDelay
147 keepProcessAlive:false
148 dependencyDescriptionCode:CKKSResultDescriptionPendingZoneChangeFetchScheduling
151 [self maybeCreateNewFetch];
157 - (NSString*)description {
158 NSDate* nextFetchAt = self.fetchScheduler.nextFireTime;
160 NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
161 [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
162 return [NSString stringWithFormat: @"<CKKSZoneChangeFetcher(%@): next fetch at %@", self.name, [dateFormatter stringFromDate: nextFetchAt]];
164 return [NSString stringWithFormat: @"<CKKSZoneChangeFetcher(%@): no pending fetches", self.name];
168 - (void)registerClient:(id<CKKSChangeFetcherClient>)client
170 @synchronized(self.clientMap) {
171 [self.clientMap setObject:client forKey:client.zoneID];
175 - (NSArray<id<CKKSChangeFetcherClient>>*)clients {
176 NSMutableArray<id<CKKSChangeFetcherClient>> *clients = [NSMutableArray array];
177 @synchronized (self.clientMap) {
178 for(id<CKKSChangeFetcherClient> client in [self.clientMap objectEnumerator]) {
180 [clients addObject:client];
187 - (CKKSResultOperation*)requestSuccessfulFetch:(CKKSFetchBecause*)why {
188 return [self requestSuccessfulFetchForManyReasons:[NSSet setWithObject:why]];
191 - (void)notifyZoneChange:(CKRecordZoneNotification* _Nullable)notification
193 ckksnotice_global("ckkspush", "received a zone change notification for %@ %@", self, notification);
194 [self requestFetchDueToAPNS:notification];
197 - (CKKSResultOperation*)requestFetchDueToAPNS:(CKRecordZoneNotification*)notification
199 __block BOOL notReady = YES;
201 // make sure we don't hold the self.queue when we call out to clients since that will lead
202 // to lock inversions
204 NSArray<id<CKKSChangeFetcherClient>> *clients = [self clients];
206 for(id<CKKSChangeFetcherClient> client in clients) {
207 if([client zoneIsReadyForFetching]) {
213 dispatch_sync(self.queue, ^{
216 [self.apnsPushes addObject:notification];
217 if(notification.ckksPushTracingEnabled) {
218 // Report that we saw this notification before doing anything else
219 ckksnotice_global("ckksfetch", "Submitting initial CKEventMetric due to notification %@", notification);
221 CKEventMetric *metric = [[CKEventMetric alloc] initWithEventName:@"APNSPushMetrics"];
222 metric.isPushTriggerFired = true;
223 metric[@"push_token_uuid"] = notification.ckksPushTracingUUID;
224 metric[@"push_received_date"] = notification.ckksPushReceivedDate;
225 metric[@"push_event_name"] = @"CKKS APNS Push Received";
226 metric[@"zones_status"] = notReady ? @"not-ready" : @"ready";
228 [self.container submitEventMetric:metric];
230 SecEventMetric *metric2 = [[SecEventMetric alloc] initWithEventName:@"APNSPushMetrics"];
231 metric2[@"push_token_uuid"] = notification.ckksPushTracingUUID;
232 metric2[@"push_received_date"] = notification.ckksPushReceivedDate;
233 metric2[@"push_event_name"] = @"CKKS APNS Push Received-webtunnel";
234 metric[@"zones_status"] = notReady ? @"not-ready" : @"ready";
236 [[SecMetrics managerObject] submitEvent:metric2];
243 ckksnotice_global("ckksfetch", "Skipping fetching size no zone is ready");
247 return [self requestSuccessfulFetchForManyReasons:[NSSet setWithObject:CKKSFetchBecauseAPNS]];
250 - (CKKSResultOperation*)requestSuccessfulFetchForManyReasons:(NSSet<CKKSFetchBecause*>*)why
252 __block CKKSResultOperation* dependency = nil;
253 dispatch_sync(self.queue, ^{
254 dependency = self.successfulFetchDependency;
255 self.newRequests = true;
256 [self.currentFetchReasons unionSet:why];
258 [self.fetchScheduler trigger];
264 - (CKKSResultOperation* _Nullable)inflightFetch
266 __block CKKSResultOperation* dependency = nil;
267 dispatch_sync(self.queue, ^{
269 // If we'll have a new fetch in the future, return its status.
270 if(self.newRequests || self.inflightFetchDependency == nil) {
271 dependency = self.successfulFetchDependency;
273 // Otherwise, return the last triggered fetch
274 dependency = self.inflightFetchDependency;
281 -(void)maybeCreateNewFetchOnQueue {
282 dispatch_assert_queue(self.queue);
283 if(self.newRequests &&
284 (self.currentFetch == nil || [self.currentFetch isFinished]) &&
285 (self.currentProcessResult == nil || [self.currentProcessResult isFinished])) {
286 [self _onqueueCreateNewFetch];
290 -(void)maybeCreateNewFetch {
291 dispatch_sync(self.queue, ^{
292 [self maybeCreateNewFetchOnQueue];
296 -(void)_onqueueCreateNewFetch {
297 dispatch_assert_queue(self.queue);
301 CKKSZoneChangeFetchDependencyOperation* dependency = self.successfulFetchDependency;
302 self.inflightFetchDependency = dependency;
304 NSMutableSet<CKKSFetchBecause*>* lastFetchReasons = self.currentFetchReasons;
305 self.currentFetchReasons = [[NSMutableSet alloc] init];
307 NSString *reasonsString = [[lastFetchReasons sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES]]] componentsJoinedByString:@","];
309 ckksnotice_global("ckksfetcher", "Starting a new fetch, reasons: %@", reasonsString);
311 NSMutableSet<CKRecordZoneNotification*>* lastAPNSPushes = self.apnsPushes;
312 self.apnsPushes = [[NSMutableSet alloc] init];
314 CKOperationGroup* operationGroup = [CKOperationGroup CKKSGroupWithName: reasonsString];
316 NSArray<id<CKKSChangeFetcherClient>> *clients = [self clients];
318 if(clients.count == 0u) {
319 ckksnotice_global("ckksfetcher", "No clients");
320 // Nothing to do, really.
323 CKKSFetchAllRecordZoneChangesOperation* fetchAllChanges = [[CKKSFetchAllRecordZoneChangesOperation alloc] initWithContainer:self.container
324 fetchClass:self.fetchRecordZoneChangesOperationClass
326 fetchReasons:lastFetchReasons
327 apnsPushes:lastAPNSPushes
329 ckoperationGroup:operationGroup];
331 if ([lastFetchReasons containsObject:CKKSFetchBecauseNetwork]) {
332 ckksnotice_global("ckksfetcher", "blocking fetch on network reachability");
333 [fetchAllChanges addNullableDependency: self.reachabilityTracker.reachabilityDependency]; // wait on network, if its unavailable
335 [fetchAllChanges addNullableDependency: self.holdOperation];
337 self.currentProcessResult = [CKKSResultOperation operationWithBlock: ^{
340 ckkserror_global("ckksfetcher", "Received a null self pointer; strange.");
344 bool attemptAnotherFetch = false;
345 if(fetchAllChanges.error != nil) {
346 ckkserror_global("ckksfetcher", "Interrogating clients about fetch error: %@", fetchAllChanges.error);
348 // Check in with clients: should we keep fetching for them?
349 @synchronized(self.clientMap) {
350 for(CKRecordZoneID* zoneID in fetchAllChanges.fetchedZoneIDs) {
351 id<CKKSChangeFetcherClient> client = [self.clientMap objectForKey:zoneID];
353 attemptAnotherFetch |= [client shouldRetryAfterFetchError:fetchAllChanges.error];
359 dispatch_sync(self.queue, ^{
360 self.lastCKFetchError = fetchAllChanges.error;
362 if(fetchAllChanges.error == nil) {
363 // success! notify the listeners.
364 [self.operationQueue addOperation: dependency];
365 self.currentFetch = nil;
367 // Did new people show up and want another fetch?
368 if(self.newRequests) {
369 [self.fetchScheduler trigger];
372 // The operation errored. Chain the dependency on the current one...
373 [dependency chainDependency:self.successfulFetchDependency];
374 [self.operationQueue addOperation: dependency];
376 if(!attemptAnotherFetch) {
377 ckkserror_global("ckksfetcher", "All clients thought %@ is a fatal error. Not restarting fetch.", fetchAllChanges.error);
381 // And in a bit, try the fetch again.
382 NSTimeInterval delay = CKRetryAfterSecondsForError(fetchAllChanges.error);
384 ckksnotice_global("ckksfetcher", "Fetch failed with rate-limiting error, restarting in %.1f seconds: %@", delay, fetchAllChanges.error);
385 [self.fetchScheduler waitUntil:NSEC_PER_SEC * delay];
387 ckksnotice_global("ckksfetcher", "Fetch failed with error, restarting soon: %@", fetchAllChanges.error);
390 // Add the failed fetch reasons to the new fetch reasons
391 [self.currentFetchReasons unionSet:lastFetchReasons];
392 [self.apnsPushes unionSet:lastAPNSPushes];
394 // If its a network error, make next try depend on network availability
395 if ([self.reachabilityTracker isNetworkError:fetchAllChanges.error]) {
396 [self.currentFetchReasons addObject:CKKSFetchBecauseNetwork];
398 [self.currentFetchReasons addObject:CKKSFetchBecausePreviousFetchFailed];
400 self.newRequests = true;
401 [self.fetchScheduler trigger];
406 // creata a new fetch dependency, for all those who come in while this operation is executing
407 self.newRequests = false;
408 self.successfulFetchDependency = [self createSuccesfulFetchDependency];
410 // now let new new fetch go and process it's results
411 self.currentProcessResult.name = @"zone-change-fetcher-worker";
412 [self.currentProcessResult addDependency: fetchAllChanges];
414 [self.operationQueue addOperation:self.currentProcessResult];
416 self.currentFetch = fetchAllChanges;
417 [self.operationQueue addOperation:self.currentFetch];
420 -(CKKSZoneChangeFetchDependencyOperation*)createSuccesfulFetchDependency {
421 CKKSZoneChangeFetchDependencyOperation* dep = [[CKKSZoneChangeFetchDependencyOperation alloc] init];
423 dep.name = @"successful-fetch-dependency";
424 dep.descriptionErrorCode = CKKSResultDescriptionPendingSuccessfulFetch;
430 - (void)holdFetchesUntil:(CKKSResultOperation*)holdOperation {
431 self.holdOperation = holdOperation;
435 [self.fetchScheduler cancel];