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 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 CKKSResultOperation* holdOperation;
110 @implementation CKKSZoneChangeFetcher
112 - (instancetype)initWithContainer:(CKContainer*)container
113 fetchClass:(Class<CKKSFetchRecordZoneChangesOperation>)fetchRecordZoneChangesOperationClass
114 reachabilityTracker:(CKKSReachabilityTracker *)reachabilityTracker
116 if((self = [super init])) {
117 _container = container;
118 _fetchRecordZoneChangesOperationClass = fetchRecordZoneChangesOperationClass;
119 _reachabilityTracker = reachabilityTracker;
121 _currentFetchReasons = [[NSMutableSet alloc] init];
122 _apnsPushes = [[NSMutableSet alloc] init];
124 _clientMap = [NSMapTable strongToWeakObjectsMapTable];
126 _name = @"zone-change-fetcher";
127 _queue = dispatch_queue_create([_name UTF8String], DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL);
128 _operationQueue = [[NSOperationQueue alloc] init];
129 _successfulFetchDependency = [self createSuccesfulFetchDependency];
131 _newRequests = false;
133 // If we're testing, for the initial delay, use 0.2 second. Otherwise, 2s.
134 dispatch_time_t initialDelay = (SecCKKSReduceRateLimiting() ? 200 * NSEC_PER_MSEC : 2 * NSEC_PER_SEC);
136 // If we're testing, for the continuing delay, use 2 second. Otherwise, 30s.
137 dispatch_time_t continuingDelay = (SecCKKSReduceRateLimiting() ? 2 * NSEC_PER_SEC : 30 * NSEC_PER_SEC);
140 _fetchScheduler = [[CKKSNearFutureScheduler alloc] initWithName:@"zone-change-fetch-scheduler"
141 initialDelay:initialDelay
142 continuingDelay:continuingDelay
143 keepProcessAlive:false
144 dependencyDescriptionCode:CKKSResultDescriptionPendingZoneChangeFetchScheduling
147 [self maybeCreateNewFetch];
153 - (NSString*)description {
154 NSDate* nextFetchAt = self.fetchScheduler.nextFireTime;
156 NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
157 [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
158 return [NSString stringWithFormat: @"<CKKSZoneChangeFetcher(%@): next fetch at %@", self.name, [dateFormatter stringFromDate: nextFetchAt]];
160 return [NSString stringWithFormat: @"<CKKSZoneChangeFetcher(%@): no pending fetches", self.name];
164 - (void)registerClient:(id<CKKSChangeFetcherClient>)client
166 @synchronized(self.clientMap) {
167 [self.clientMap setObject:client forKey:client.zoneID];
172 - (CKKSResultOperation*)requestSuccessfulFetch:(CKKSFetchBecause*)why {
173 return [self requestSuccessfulFetchForManyReasons:[NSSet setWithObject:why]];
176 - (CKKSResultOperation*)requestSuccessfulFetchForManyReasons:(NSSet<CKKSFetchBecause*>*)why
178 return [self requestSuccessfulFetchForManyReasons:why apns:nil];
181 - (CKKSResultOperation*)requestSuccessfulFetchDueToAPNS:(CKRecordZoneNotification*)notification
183 return [self requestSuccessfulFetchForManyReasons:[NSSet setWithObject:CKKSFetchBecauseAPNS] apns:notification];
186 - (CKKSResultOperation*)requestSuccessfulFetchForManyReasons:(NSSet<CKKSFetchBecause*>*)why apns:(CKRecordZoneNotification*)notification
188 __block CKKSResultOperation* dependency = nil;
189 dispatch_sync(self.queue, ^{
190 dependency = self.successfulFetchDependency;
191 self.newRequests = true;
192 [self.currentFetchReasons unionSet:why];
194 [self.apnsPushes addObject:notification];
196 if(notification.ckksPushTracingEnabled) {
197 // Report that we saw this notification before doing anything else
198 secnotice("ckksfetch", "Submitting initial CKEventMetric due to notification %@", notification);
200 CKEventMetric *metric = [[CKEventMetric alloc] initWithEventName:@"APNSPushMetrics"];
201 metric.isPushTriggerFired = true;
202 metric[@"push_token_uuid"] = notification.ckksPushTracingUUID;
203 metric[@"push_received_date"] = notification.ckksPushReceivedDate;
204 metric[@"push_event_name"] = @"CKKS APNS Push Received";
206 [self.container submitEventMetric:metric];
208 SecEventMetric *metric2 = [[SecEventMetric alloc] initWithEventName:@"APNSPushMetrics"];
209 metric2[@"push_token_uuid"] = notification.ckksPushTracingUUID;
210 metric2[@"push_received_date"] = notification.ckksPushReceivedDate;
211 metric2[@"push_event_name"] = @"CKKS APNS Push Received-webtunnel";
213 [[SecMetrics managerObject] submitEvent:metric2];
219 [self.fetchScheduler trigger];
225 -(void)maybeCreateNewFetchOnQueue {
226 dispatch_assert_queue(self.queue);
227 if(self.newRequests &&
228 (self.currentFetch == nil || [self.currentFetch isFinished]) &&
229 (self.currentProcessResult == nil || [self.currentProcessResult isFinished])) {
230 [self _onqueueCreateNewFetch];
234 -(void)maybeCreateNewFetch {
235 dispatch_sync(self.queue, ^{
236 [self maybeCreateNewFetchOnQueue];
240 -(void)_onqueueCreateNewFetch {
241 dispatch_assert_queue(self.queue);
245 CKKSZoneChangeFetchDependencyOperation* dependency = self.successfulFetchDependency;
246 NSMutableSet<CKKSFetchBecause*>* lastFetchReasons = self.currentFetchReasons;
247 self.currentFetchReasons = [[NSMutableSet alloc] init];
249 NSString *reasonsString = [[lastFetchReasons sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES]]] componentsJoinedByString:@","];
251 secnotice("ckksfetcher", "Starting a new fetch, reasons: %@", reasonsString);
253 NSMutableSet<CKRecordZoneNotification*>* lastAPNSPushes = self.apnsPushes;
254 self.apnsPushes = [[NSMutableSet alloc] init];
256 CKOperationGroup* operationGroup = [CKOperationGroup CKKSGroupWithName: reasonsString];
258 NSMutableArray<id<CKKSChangeFetcherClient>>* clients = [NSMutableArray array];
259 @synchronized(self.clientMap) {
260 for(id<CKKSChangeFetcherClient> client in [self.clientMap objectEnumerator]) {
262 [clients addObject:client];
267 if(clients.count == 0u) {
268 secnotice("ckksfetcher", "No clients");
269 // Nothing to do, really.
272 CKKSFetchAllRecordZoneChangesOperation* fetchAllChanges = [[CKKSFetchAllRecordZoneChangesOperation alloc] initWithContainer:self.container
273 fetchClass:self.fetchRecordZoneChangesOperationClass
275 fetchReasons:lastFetchReasons
276 apnsPushes:lastAPNSPushes
278 ckoperationGroup:operationGroup];
280 if ([lastFetchReasons containsObject:CKKSFetchBecauseNetwork]) {
281 secnotice("ckksfetcher", "blocking fetch on network reachability");
282 [fetchAllChanges addNullableDependency: self.reachabilityTracker.reachabilityDependency]; // wait on network, if its unavailable
284 [fetchAllChanges addNullableDependency: self.holdOperation];
286 self.currentProcessResult = [CKKSResultOperation operationWithBlock: ^{
289 secerror("ckksfetcher: Received a null self pointer; strange.");
293 bool attemptAnotherFetch = false;
294 if(fetchAllChanges.error != nil) {
295 secerror("ckksfetcher: Interrogating clients about fetch error: %@", fetchAllChanges.error);
297 // Check in with clients: should we keep fetching for them?
298 @synchronized(self.clientMap) {
299 for(CKRecordZoneID* zoneID in fetchAllChanges.fetchedZoneIDs) {
300 id<CKKSChangeFetcherClient> client = [self.clientMap objectForKey:zoneID];
302 attemptAnotherFetch |= [client shouldRetryAfterFetchError:fetchAllChanges.error];
308 dispatch_sync(self.queue, ^{
309 self.lastCKFetchError = fetchAllChanges.error;
311 if(!fetchAllChanges.error) {
312 if (attemptAnotherFetch) {
313 [dependency chainDependency:self.successfulFetchDependency];
314 [self.operationQueue addOperation: dependency];
316 [self.currentFetchReasons unionSet:lastFetchReasons];
317 [self.apnsPushes unionSet:lastAPNSPushes];
319 self.newRequests = true;
320 [self.fetchScheduler trigger];
322 // success! notify the listeners.
323 [self.operationQueue addOperation: dependency];
324 self.currentFetch = nil;
326 // Did new people show up and want another fetch?
327 if(self.newRequests) {
328 [self.fetchScheduler trigger];
332 // The operation errored. Chain the dependency on the current one...
333 [dependency chainDependency:self.successfulFetchDependency];
334 [self.operationQueue addOperation: dependency];
336 if(!attemptAnotherFetch) {
337 secerror("ckksfetcher: All clients thought %@ is a fatal error. Not restarting fetch.", fetchAllChanges.error);
341 // And in a bit, try the fetch again.
342 NSTimeInterval delay = CKRetryAfterSecondsForError(fetchAllChanges.error);
344 secnotice("ckksfetcher", "Fetch failed with rate-limiting error, restarting in %.1f seconds: %@", delay, fetchAllChanges.error);
345 [self.fetchScheduler waitUntil:NSEC_PER_SEC * delay];
347 secnotice("ckksfetcher", "Fetch failed with error, restarting soon: %@", fetchAllChanges.error);
350 // Add the failed fetch reasons to the new fetch reasons
351 [self.currentFetchReasons unionSet:lastFetchReasons];
352 [self.apnsPushes unionSet:lastAPNSPushes];
354 // If its a network error, make next try depend on network availability
355 if ([self.reachabilityTracker isNetworkError:fetchAllChanges.error]) {
356 [self.currentFetchReasons addObject:CKKSFetchBecauseNetwork];
358 [self.currentFetchReasons addObject:CKKSFetchBecausePreviousFetchFailed];
360 self.newRequests = true;
361 [self.fetchScheduler trigger];
366 // creata a new fetch dependency, for all those who come in while this operation is executing
367 self.newRequests = false;
368 self.successfulFetchDependency = [self createSuccesfulFetchDependency];
370 // now let new new fetch go and process it's results
371 self.currentProcessResult.name = @"zone-change-fetcher-worker";
372 [self.currentProcessResult addDependency: fetchAllChanges];
374 [self.operationQueue addOperation:self.currentProcessResult];
376 self.currentFetch = fetchAllChanges;
377 [self.operationQueue addOperation:self.currentFetch];
380 -(CKKSZoneChangeFetchDependencyOperation*)createSuccesfulFetchDependency {
381 CKKSZoneChangeFetchDependencyOperation* dep = [[CKKSZoneChangeFetchDependencyOperation alloc] init];
383 dep.name = @"successful-fetch-dependency";
384 dep.descriptionErrorCode = CKKSResultDescriptionPendingSuccessfulFetch;
390 - (void)holdFetchesUntil:(CKKSResultOperation*)holdOperation {
391 self.holdOperation = holdOperation;
395 [self.fetchScheduler cancel];