]> git.saurik.com Git - apple/security.git/blob - keychain/ckks/CKKSNearFutureScheduler.m
Security-58286.60.28.tar.gz
[apple/security.git] / keychain / ckks / CKKSNearFutureScheduler.m
1 /*
2 * Copyright (c) 2017 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
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
11 * file.
12 *
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.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 #if OCTAGON
25
26 #import "CKKSNearFutureScheduler.h"
27 #import "CKKSCondition.h"
28 #import "keychain/ckks/NSOperationCategories.h"
29 #import "keychain/ckks/CKKSResultOperation.h"
30 #include <os/transaction_private.h>
31
32 @interface CKKSNearFutureScheduler ()
33 @property NSString* name;
34 @property dispatch_time_t initialDelay;
35 @property dispatch_time_t continuingDelay;
36
37 @property NSInteger operationDependencyDescriptionCode;
38 @property CKKSResultOperation* operationDependency;
39 @property (nonnull) NSOperationQueue* operationQueue;
40
41 @property NSDate* predictedNextFireTime;
42 @property bool liveRequest;
43 @property CKKSCondition* liveRequestReceived; // Triggered when liveRequest goes to true.
44
45 @property dispatch_source_t timer;
46 @property dispatch_queue_t queue;
47
48 @property bool keepProcessAlive;
49 @property os_transaction_t transaction;
50 @end
51
52 @implementation CKKSNearFutureScheduler
53
54 -(instancetype)initWithName:(NSString*)name
55 delay:(dispatch_time_t)ns
56 keepProcessAlive:(bool)keepProcessAlive
57 dependencyDescriptionCode:(NSInteger)code
58 block:(void (^)(void))futureBlock
59 {
60 return [self initWithName:name
61 initialDelay:ns
62 continuingDelay:ns
63 keepProcessAlive:keepProcessAlive
64 dependencyDescriptionCode:code
65 block:futureBlock];
66 }
67
68 -(instancetype)initWithName:(NSString*)name
69 initialDelay:(dispatch_time_t)initialDelay
70 continuingDelay:(dispatch_time_t)continuingDelay
71 keepProcessAlive:(bool)keepProcessAlive
72 dependencyDescriptionCode:(NSInteger)code
73 block:(void (^)(void))futureBlock
74 {
75 if((self = [super init])) {
76 _name = name;
77
78 _queue = dispatch_queue_create([[NSString stringWithFormat:@"near-future-scheduler-%@",name] UTF8String], DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL);
79 _initialDelay = initialDelay;
80 _continuingDelay = continuingDelay;
81 _futureBlock = futureBlock;
82
83 _liveRequest = false;
84 _liveRequestReceived = [[CKKSCondition alloc] init];
85 _predictedNextFireTime = nil;
86
87 _keepProcessAlive = keepProcessAlive;
88
89 _operationQueue = [[NSOperationQueue alloc] init];
90 _operationDependencyDescriptionCode = code;
91 _operationDependency = [self makeOperationDependency];
92 }
93 return self;
94 }
95
96 - (CKKSResultOperation*)makeOperationDependency {
97 CKKSResultOperation* op = [CKKSResultOperation named:[NSString stringWithFormat:@"nfs-%@", self.name] withBlock:^{}];
98 op.descriptionErrorCode = self.operationDependencyDescriptionCode;
99 return op;
100 }
101
102 -(NSString*)description {
103 NSDate* nextAt = self.nextFireTime;
104 if(nextAt) {
105 NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
106 [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
107 return [NSString stringWithFormat: @"<CKKSNearFutureScheduler(%@): next at %@", self.name, [dateFormatter stringFromDate: nextAt]];
108 } else {
109 return [NSString stringWithFormat: @"<CKKSNearFutureScheduler(%@): no pending attempts", self.name];
110 }
111 }
112
113 - (NSDate*)nextFireTime {
114 // If we have a live request, send the next fire time back. Otherwise, wait a tiny tiny bit to see if we receive a request.
115 if(self.liveRequest) {
116 return self.predictedNextFireTime;
117 } else if([self.liveRequestReceived wait:50*NSEC_PER_USEC] == 0) {
118 return self.predictedNextFireTime;
119 }
120
121 return nil;
122 }
123
124 -(void)waitUntil:(uint64_t)delay {
125 dispatch_sync(self.queue, ^{
126 [self _onqueueTrigger:delay];
127 });
128 }
129
130 -(void)_onqueueTimerTick {
131 dispatch_assert_queue(self.queue);
132
133 if(self.liveRequest) {
134 // Put a new dependency in place, and save the old one for execution
135 NSOperation* dependency = self.operationDependency;
136 self.operationDependency = [self makeOperationDependency];
137
138 self.futureBlock();
139 self.liveRequest = false;
140 self.liveRequestReceived = [[CKKSCondition alloc] init];
141 self.transaction = nil;
142
143 [self.operationQueue addOperation: dependency];
144
145 self.predictedNextFireTime = [NSDate dateWithTimeIntervalSinceNow: (NSTimeInterval) ((double) self.continuingDelay) / (double) NSEC_PER_SEC];
146 } else {
147 // The timer has fired with no requests to call the block. Cancel it.
148 dispatch_source_cancel(self.timer);
149 self.predictedNextFireTime = nil;
150 }
151 }
152
153 -(void)trigger {
154 __weak __typeof(self) weakSelf = self;
155 dispatch_async(self.queue, ^{
156 // The timer tick should call the block!
157 self.liveRequest = true;
158 [self.liveRequestReceived fulfill];
159
160 [weakSelf _onqueueTrigger:DISPATCH_TIME_NOW];
161 });
162 }
163
164 -(void)_onqueueTrigger:(dispatch_time_t)requestedDelay {
165 dispatch_assert_queue(self.queue);
166 __weak __typeof(self) weakSelf = self;
167
168 // If we don't have one already, set up an os_transaction
169 if(self.keepProcessAlive && self.transaction == nil) {
170 self.transaction = os_transaction_create([[NSString stringWithFormat:@"com.apple.securityd.%@",self.name] UTF8String]);
171 }
172
173 if(requestedDelay != DISPATCH_TIME_NOW) {
174 NSDate* delayTime = [NSDate dateWithTimeIntervalSinceNow: (NSTimeInterval) ((double) requestedDelay) / (double) NSEC_PER_SEC];
175 if([delayTime compare:self.predictedNextFireTime] != NSOrderedDescending) {
176 // The next fire time is after this delay. Do nothing with the request.
177 } else {
178 // Need to cancel the timer and reset it below.
179 dispatch_source_cancel(self.timer);
180 self.predictedNextFireTime = nil;
181 }
182 }
183
184 // Check if the timer is alive
185 if(self.timer != nil && 0 == dispatch_source_testcancel(self.timer)) {
186 // timer is alive, do nothing
187 } else {
188 // start the timer
189 self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,
190 0,
191 (dispatch_source_timer_flags_t)0,
192 self.queue);
193 dispatch_source_set_event_handler(self.timer, ^{
194 [weakSelf _onqueueTimerTick];
195 });
196
197 dispatch_time_t actualDelay = self.initialDelay > requestedDelay ? self.initialDelay : requestedDelay;
198
199 dispatch_source_set_timer(self.timer,
200 dispatch_walltime(NULL, actualDelay),
201 self.continuingDelay,
202 50 * NSEC_PER_MSEC);
203 dispatch_resume(self.timer);
204
205 self.predictedNextFireTime = [NSDate dateWithTimeIntervalSinceNow: (NSTimeInterval) ((double) actualDelay) / (double) NSEC_PER_SEC];
206 };
207 }
208
209 -(void)cancel {
210 dispatch_sync(self.queue, ^{
211 if(self.timer != nil && 0 == dispatch_source_testcancel(self.timer)) {
212 dispatch_source_cancel(self.timer);
213 }
214 });
215 }
216
217 @end
218
219 #endif // OCTAGON