4 #import "keychain/ot/OctagonStateMachine.h"
5 #import "keychain/ot/OctagonStateMachineObservers.h"
6 #import "keychain/ot/ObjCImprovements.h"
7 #import "keychain/ckks/CKKSNearFutureScheduler.h"
8 #import "keychain/ckks/CKKS.h"
9 #import "keychain/ot/OTStates.h"
10 #import "utilities/debugging.h"
12 #define statemachinelog(scope, format, ...) \
14 os_log(secLogObjForCFScope((__bridge CFStringRef)[NSString stringWithFormat:@"%@-%@", self.name, @(scope)]), \
19 @interface OctagonStateMachine ()
21 OctagonState* _currentState;
24 @property (weak) id<OctagonStateMachineEngine> stateEngine;
26 @property dispatch_queue_t queue;
27 @property NSOperationQueue* operationQueue;
29 @property NSString* name;
32 @property CKKSCondition* paused;
33 @property OctagonState* currentState;
34 @property OctagonFlags* currentFlags;
36 // Set this to an operation to pause the state machine in-flight
37 @property NSOperation* holdStateMachineOperation;
39 @property (nullable) CKKSResultOperation* nextStateMachineCycleOperation;
41 @property NSMutableArray<OctagonStateTransitionRequest<CKKSResultOperation<OctagonStateTransitionOperationProtocol>*>*>* stateMachineRequests;
42 @property NSMutableArray<OctagonStateTransitionWatcher*>* stateMachineWatchers;
44 @property BOOL halted;
45 @property bool allowPendingFlags;
46 @property NSMutableDictionary<OctagonFlag*, OctagonPendingFlag*>* pendingFlags;
47 @property CKKSNearFutureScheduler* pendingFlagsScheduler;
49 @property OctagonPendingConditions conditionChecksInFlight;
50 @property OctagonPendingConditions currentConditions;
51 @property NSOperation* checkUnlockOperation;
54 @implementation OctagonStateMachine
56 - (instancetype)initWithName:(NSString*)name
57 states:(NSSet<OctagonState*>*)possibleStates
58 flags:(NSSet<OctagonFlag*>*)possibleFlags
59 initialState:(OctagonState*)initialState
60 queue:(dispatch_queue_t)queue
61 stateEngine:(id<OctagonStateMachineEngine>)stateEngine
62 lockStateTracker:(CKKSLockStateTracker*)lockStateTracker
64 if ((self = [super init])) {
67 _lockStateTracker = lockStateTracker;
68 _conditionChecksInFlight = 0;
69 _currentConditions = 0;
71 // Every state machine starts in OctagonStateMachineNotStarted, so help them out a bit.
72 _allowableStates = [possibleStates setByAddingObjectsFromArray:@[OctagonStateMachineNotStarted, OctagonStateMachineHalted]];
75 _operationQueue = [[NSOperationQueue alloc] init];
76 _currentFlags = [[OctagonFlags alloc] initWithQueue:queue flags:possibleFlags];
78 _stateEngine = stateEngine;
80 _holdStateMachineOperation = [NSBlockOperation blockOperationWithBlock:^{}];
83 _stateConditions = [[NSMutableDictionary alloc] init];
84 [possibleStates enumerateObjectsUsingBlock:^(OctagonState * _Nonnull obj, BOOL * _Nonnull stop) {
85 self.stateConditions[obj] = [[CKKSCondition alloc] init];
88 // Use the setter method to set the condition variables
89 self.currentState = OctagonStateMachineNotStarted;
91 _stateMachineRequests = [NSMutableArray array];
92 _stateMachineWatchers = [NSMutableArray array];
95 _allowPendingFlags = true;
96 _pendingFlags = [NSMutableDictionary dictionary];
97 _pendingFlagsScheduler = [[CKKSNearFutureScheduler alloc] initWithName:[NSString stringWithFormat:@"%@-pending-flag", name]
98 delay:100*NSEC_PER_MSEC
99 keepProcessAlive:false
100 dependencyDescriptionCode:CKKSResultDescriptionPendingFlag
103 dispatch_sync(self.queue, ^{
104 [self _onqueueSendAnyPendingFlags];
108 OctagonStateTransitionOperation* initializeOp = [OctagonStateTransitionOperation named:@"initialize"
109 entering:initialState];
110 [initializeOp addDependency:_holdStateMachineOperation];
111 [_operationQueue addOperation:initializeOp];
113 _paused = [[CKKSCondition alloc] init];
115 _nextStateMachineCycleOperation = [self createOperationToFinishAttempt:initializeOp];
116 [_operationQueue addOperation:_nextStateMachineCycleOperation];
121 - (NSString*)pendingFlagsString
123 return [self.pendingFlags.allValues componentsJoinedByString:@","];
126 - (NSString*)description
128 NSString* pendingFlags = @"";
129 if(self.pendingFlags.count != 0) {
130 pendingFlags = [NSString stringWithFormat:@" (pending: %@)", [self pendingFlagsString]];
132 return [NSString stringWithFormat:@"<OctagonStateMachine(%@,%@,%@)>", self.name, self.currentState, pendingFlags];
135 #pragma mark - Bookkeeping
137 - (id<OctagonFlagSetter>)flags {
138 return self.currentFlags;
141 - (OctagonState* _Nonnull)currentState {
142 return _currentState;
145 - (void)setCurrentState:(OctagonState* _Nonnull)state {
146 if((state == nil && _currentState == nil) || ([state isEqualToString:_currentState])) {
147 // No change, do nothing.
149 // Fixup the condition variables as part of setting this state
151 self.stateConditions[_currentState] = [[CKKSCondition alloc] init];
154 NSAssert([self.allowableStates containsObject:state], @"state machine tried to enter unknown state %@", state);
155 _currentState = state;
158 [self.stateConditions[state] fulfill];
163 - (OctagonState* _Nonnull)waitForState:(OctagonState* _Nonnull)wantedState wait:(uint64_t)timeout {
164 if ([self.stateConditions[wantedState] wait:timeout]) {
165 return _currentState;
171 #pragma mark - Machinery
173 - (CKKSResultOperation<OctagonStateTransitionOperationProtocol>* _Nullable)_onqueueNextStateMachineTransition
175 dispatch_assert_queue(self.queue);
178 if([self.currentState isEqualToString:OctagonStateMachineHalted]) {
181 return [OctagonStateTransitionOperation named:@"halt"
182 entering:OctagonStateMachineHalted];
186 // Check requests: do any of them want to come from this state?
187 for(OctagonStateTransitionRequest<OctagonStateTransitionOperation*>* request in self.stateMachineRequests) {
188 if([request.sourceStates containsObject:self.currentState]) {
189 OctagonStateTransitionOperation* attempt = [request _onqueueStart];
192 statemachinelog("state", "Running state machine request %@ (from %@)", request, self.currentState);
198 // Ask the stateEngine what it would like to do
199 return [self.stateEngine _onqueueNextStateMachineTransition:self.currentState
200 flags:self.currentFlags
204 - (void)_onqueueStartNextStateMachineOperation:(bool)immediatelyAfterPreviousOp {
205 dispatch_assert_queue(self.queue);
207 // early-exit if there's an existing operation. That operation will call this function after it's done
208 if(self.nextStateMachineCycleOperation) {
212 CKKSResultOperation<OctagonStateTransitionOperationProtocol>* nextOp = [self _onqueueNextStateMachineTransition];
214 statemachinelog("state", "Beginning state transition attempt %@", nextOp);
216 self.nextStateMachineCycleOperation = [self createOperationToFinishAttempt:nextOp];
217 [self.operationQueue addOperation:self.nextStateMachineCycleOperation];
219 [nextOp addNullableDependency:self.holdStateMachineOperation];
220 nextOp.qualityOfService = NSQualityOfServiceUserInitiated;
221 [self.operationQueue addOperation:nextOp];
223 if(!immediatelyAfterPreviousOp) {
224 self.paused = [[CKKSCondition alloc] init];
227 statemachinelog("state", "State machine rests (%@, f:[%@] p:[%@])", self.currentState, [self.currentFlags contentsAsString], [self pendingFlagsString]);
228 [self.paused fulfill];
233 - (CKKSResultOperation*)createOperationToFinishAttempt:(CKKSResultOperation<OctagonStateTransitionOperationProtocol>*)op
237 CKKSResultOperation* followUp = [CKKSResultOperation named:@"octagon-state-follow-up" withBlock:^{
240 dispatch_sync(self.queue, ^{
241 statemachinelog("state", "Finishing state transition attempt (ending in %@, intended: %@, f:[%@], p:[%@]): %@ %@",
244 [self.currentFlags contentsAsString],
245 [self pendingFlagsString],
247 op.error ?: @"(no error)");
249 for(OctagonStateTransitionWatcher* watcher in self.stateMachineWatchers) {
250 statemachinelog("state", "notifying watcher: %@", watcher);
251 [watcher onqueueHandleTransition:op];
254 // finished watchers can be removed from the list. Use a reversed for loop to enable removal
255 for (NSInteger i = self.stateMachineWatchers.count - 1; i >= 0; i--) {
256 if([self.stateMachineWatchers[i].result isFinished]) {
257 [self.stateMachineWatchers removeObjectAtIndex:i];
261 self.currentState = op.nextState;
262 self.nextStateMachineCycleOperation = nil;
264 [self _onqueueStartNextStateMachineOperation:true];
267 [followUp addNullableDependency:self.holdStateMachineOperation];
268 [followUp addNullableDependency:op];
269 followUp.qualityOfService = NSQualityOfServiceUserInitiated;
273 - (void)pokeStateMachine
275 dispatch_sync(self.queue, ^{
276 [self _onqueuePokeStateMachine];
280 - (void)_onqueuePokeStateMachine
282 dispatch_assert_queue(self.queue);
283 [self _onqueueStartNextStateMachineOperation:false];
286 - (void)handleFlag:(OctagonFlag*)flag
288 dispatch_sync(self.queue, ^{
289 [self.currentFlags _onqueueSetFlag:flag];
290 [self _onqueuePokeStateMachine];
294 - (void)handlePendingFlag:(OctagonPendingFlag *)pendingFlag {
295 dispatch_sync(self.queue, ^{
296 [self _onqueueHandlePendingFlag:pendingFlag];
300 - (void)_onqueueHandlePendingFlag:(OctagonPendingFlag*)pendingFlag {
301 dispatch_assert_queue(self.queue);
303 // Overwrite any existing pending flag!
304 self.pendingFlags[pendingFlag.flag] = pendingFlag;
306 // Do we need to recheck any conditions? Anything which is currently the state of the world needs checking
307 OctagonPendingConditions recheck = pendingFlag.conditions & self.currentConditions;
309 // Technically don't need this if, but it adds readability
310 self.currentConditions &= ~recheck;
313 [self _onqueueRecheckConditions];
314 [self _onqueueSendAnyPendingFlags];
317 - (void)disablePendingFlags {
318 dispatch_sync(self.queue, ^{
319 self.allowPendingFlags = false;
323 - (NSDictionary<NSString*, NSString*>*)dumpPendingFlags
325 __block NSMutableDictionary<NSString*, NSString*>* d = [NSMutableDictionary dictionary];
326 dispatch_sync(self.queue, ^{
327 for(OctagonFlag* flag in [self.pendingFlags allKeys]) {
328 d[flag] = [self.pendingFlags[flag] description];
335 - (NSArray<OctagonFlag*>*)possiblePendingFlags
337 return [self.pendingFlags allKeys];
340 - (void)_onqueueRecheckConditions
342 dispatch_assert_queue(self.queue);
344 if(!self.allowPendingFlags) {
348 NSArray<OctagonPendingFlag*>* flags = [self.pendingFlags.allValues copy];
349 OctagonPendingConditions allConditions = 0;
350 for(OctagonPendingFlag* flag in flags) {
351 allConditions |= flag.conditions;
353 if(allConditions == 0x0) {
354 // No conditions? Don't bother.
358 // We need to recheck everything that is not currently the state of the world
359 OctagonPendingConditions pendingConditions = allConditions & ~(self.currentConditions);
361 // But we don't need to recheck anything that's currently being checked
362 OctagonPendingConditions conditionsToCheck = pendingConditions & ~(self.conditionChecksInFlight);
366 if(conditionsToCheck & OctagonPendingConditionsDeviceUnlocked) {
367 statemachinelog("conditions", "Waiting for unlock");
368 self.checkUnlockOperation = [NSBlockOperation blockOperationWithBlock:^{
370 dispatch_sync(self.queue, ^{
371 statemachinelog("pending-flag", "Unlock occurred");
372 self.currentConditions |= OctagonPendingConditionsDeviceUnlocked;
373 self.conditionChecksInFlight &= ~OctagonPendingConditionsDeviceUnlocked;
374 [self _onqueueSendAnyPendingFlags];
377 self.conditionChecksInFlight |= OctagonPendingConditionsDeviceUnlocked;
379 [self.checkUnlockOperation addNullableDependency:self.lockStateTracker.unlockDependency];
380 [self.operationQueue addOperation:self.checkUnlockOperation];
384 - (void)_onqueueSendAnyPendingFlags
386 dispatch_assert_queue(self.queue);
388 if(!self.allowPendingFlags) {
392 // Copy pending flags so we can edit the list
393 NSArray<OctagonPendingFlag*>* flags = [self.pendingFlags.allValues copy];
394 bool setFlag = false;
396 NSDate* now = [NSDate date];
397 NSDate* earliestDeadline = nil;
398 for(OctagonPendingFlag* pendingFlag in flags) {
401 if(pendingFlag.fireTime) {
402 if([pendingFlag.fireTime compare:now] == NSOrderedAscending) {
403 statemachinelog("pending-flag", "Delay has ended for pending flag %@", pendingFlag.flag);
406 earliestDeadline = earliestDeadline == nil ?
407 pendingFlag.fireTime :
408 [earliestDeadline earlierDate:pendingFlag.fireTime];
412 if(pendingFlag.conditions != 0x0) {
413 // Also, send the flag if the conditions are right
414 if((pendingFlag.conditions & self.currentConditions) == pendingFlag.conditions) {
416 statemachinelog("pending-flag", "Conditions are right for %@", pendingFlag.flag);
423 [self.currentFlags _onqueueSetFlag:pendingFlag.flag];
424 self.pendingFlags[pendingFlag.flag] = nil;
429 if(earliestDeadline != nil) {
430 NSTimeInterval delay = [earliestDeadline timeIntervalSinceDate:now];
431 uint64_t delayNanoseconds = delay * NSEC_PER_SEC;
433 [self.pendingFlagsScheduler triggerAt:delayNanoseconds];
437 [self _onqueuePokeStateMachine];
441 #pragma mark - Client Services
445 __block BOOL ret = false;
446 dispatch_sync(self.queue, ^{
447 ret = self.nextStateMachineCycleOperation == nil;
453 - (void)startOperation {
454 dispatch_sync(self.queue, ^{
455 if(self.holdStateMachineOperation) {
456 [self.operationQueue addOperation: self.holdStateMachineOperation];
457 self.holdStateMachineOperation = nil;
462 - (void)haltOperation
464 dispatch_sync(self.queue, ^{
465 if(self.holdStateMachineOperation) {
466 [self.operationQueue addOperation:self.holdStateMachineOperation];
467 self.holdStateMachineOperation = nil;
471 self.allowPendingFlags = false;
473 // Ask the state machine to halt itself
474 [self _onqueuePokeStateMachine];
477 [self.nextStateMachineCycleOperation waitUntilFinished];
480 - (void)handleExternalRequest:(OctagonStateTransitionRequest<CKKSResultOperation<OctagonStateTransitionOperationProtocol>*>*)request
482 dispatch_sync(self.queue, ^{
483 [self.stateMachineRequests addObject:request];
484 [self _onqueuePokeStateMachine];
488 - (void)registerStateTransitionWatcher:(OctagonStateTransitionWatcher*)watcher
490 dispatch_sync(self.queue, ^{
491 [self.stateMachineWatchers addObject: watcher];
492 [self _onqueuePokeStateMachine];
496 #pragma mark - RPC Helpers
498 - (void)doSimpleStateMachineRPC:(NSString*)name
499 op:(CKKSResultOperation<OctagonStateTransitionOperationProtocol>*)op
500 sourceStates:(NSSet<OctagonState*>*)sourceStates
501 reply:(nonnull void (^)(NSError * _Nullable))reply
503 statemachinelog("state-rpc", "Beginning a '%@' rpc", name);
505 OctagonStateTransitionRequest* request = [[OctagonStateTransitionRequest alloc] init:name
506 sourceStates:sourceStates
507 serialQueue:self.queue
508 timeout:10*NSEC_PER_SEC
510 [self handleExternalRequest:request];
513 CKKSResultOperation* callback = [CKKSResultOperation named:[NSString stringWithFormat: @"%@-callback", name]
516 statemachinelog("state-rpc", "Returning '%@' result: %@", name, op.error ?: @"no error");
519 [callback addDependency:op];
520 [self.operationQueue addOperation: callback];
523 - (void)setWatcherTimeout:(uint64_t)timeout
525 self.timeout = timeout;
528 - (void)doWatchedStateMachineRPC:(NSString*)name
529 sourceStates:(NSSet<OctagonState*>*)sourceStates
530 path:(OctagonStateTransitionPath*)path
531 reply:(nonnull void (^)(NSError *error))reply
533 statemachinelog("state-rpc", "Beginning a '%@' rpc", name);
535 CKKSResultOperation<OctagonStateTransitionOperationProtocol>* initialTransitionOp
536 = [OctagonStateTransitionOperation named:[NSString stringWithFormat:@"intial-transition-%@", name]
537 entering:path.initialState];
539 // Note that this has an initial timeout of 10s, and isn't configurable.
540 OctagonStateTransitionRequest* request = [[OctagonStateTransitionRequest alloc] init:name
541 sourceStates:sourceStates
542 serialQueue:self.queue
543 timeout:10 * NSEC_PER_SEC
544 transitionOp:initialTransitionOp];
546 OctagonStateTransitionWatcher* watcher = [[OctagonStateTransitionWatcher alloc] initNamed:[NSString stringWithFormat:@"watcher-%@", name]
547 serialQueue:self.queue
549 initialRequest:request];
550 [watcher timeout:self.timeout?:120*NSEC_PER_SEC];
552 [self registerStateTransitionWatcher:watcher];
555 CKKSResultOperation* replyOp = [CKKSResultOperation named:[NSString stringWithFormat: @"%@-callback", name]
558 statemachinelog("state-rpc", "Returning '%@' result: %@", name, watcher.result.error ?: @"no error");
559 reply(watcher.result.error);
561 [replyOp addDependency:watcher.result];
562 [self.operationQueue addOperation:replyOp];
565 [self handleExternalRequest:request];