5 #import <Foundation/Foundation.h>
6 #import <Foundation/NSXPCConnection_Private.h>
7 #import <Security/Security.h>
8 #import <Security/SecItemPriv.h>
12 #import "keychain/ckks/CKKS.h"
13 #import "keychain/ckks/CKKSControl.h"
15 #include "lib/SecArgParse.h"
17 static void nsprintf(NSString *fmt, ...) NS_FORMAT_FUNCTION(1, 2);
18 static void print_result(NSDictionary *dict, bool json_flag);
19 static void print_dict(NSDictionary *dict, int ind);
20 static void print_array(NSArray *array, int ind);
21 static void print_entry(id k, id v, int ind);
23 static void nsprintf(NSString *fmt, ...)
27 NSString *str = [[NSString alloc] initWithFormat:fmt arguments:ap];
30 puts([str UTF8String]);
31 #if !__has_feature(objc_arc)
36 static NSDictionary* flattenNSErrorsInDictionary(NSDictionary* dict) {
40 NSMutableDictionary* mutDict = [dict mutableCopy];
41 for(id key in mutDict.allKeys) {
42 id obj = mutDict[key];
43 if([obj isKindOfClass:[NSError class]]) {
44 NSError* obje = (NSError*) obj;
45 NSMutableDictionary* newErrorDict = [@{@"code": @(obje.code), @"domain": obje.domain} mutableCopy];
46 newErrorDict[@"userInfo"] = flattenNSErrorsInDictionary(obje.userInfo);
47 mutDict[key] = newErrorDict;
48 } else if(![NSJSONSerialization isValidJSONObject:obj]) {
49 mutDict[key] = [obj description];
55 static void print_result(NSDictionary *dict, bool json_flag)
60 // NSErrors don't know how to JSON-ify themselves, for some reason
61 // This will flatten a single layer of them
62 if(![NSJSONSerialization isValidJSONObject:dict]) {
63 dict = flattenNSErrorsInDictionary(dict);
66 if(![NSJSONSerialization isValidJSONObject:dict]) {
67 printf("Still unsure how to JSONify the following object:\n");
71 NSData *json = [NSJSONSerialization dataWithJSONObject:dict
72 options:(NSJSONWritingPrettyPrinted | NSJSONWritingSortedKeys)
75 NSLog(@"error: %@", err.localizedDescription);
77 printf("%s", [[[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding] UTF8String]);
84 static void print_dict(NSDictionary *dict, int ind)
86 NSArray *sortedKeys = [[dict allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
87 for (id k in sortedKeys) {
89 print_entry(k, v, ind);
93 static void print_array(NSArray *array, int ind)
95 [array enumerateObjectsUsingBlock:^(id v, NSUInteger i, BOOL *stop __unused) {
96 print_entry(@(i), v, ind);
100 static void print_entry(id k, id v, int ind)
102 if ([v isKindOfClass:[NSDictionary class]]) {
104 nsprintf(@"\n%*s%@ -", ind * 4, "", k);
105 nsprintf(@"%*s========================", ind * 4, "");
106 } else if (ind == 1) {
107 nsprintf(@"\n%*s%@ -", ind * 4, "", k);
108 nsprintf(@"%*s------------------------", ind * 4, "");
110 nsprintf(@"%*s%@ -", ind * 4, "", k);
113 print_dict(v, ind + 1);
114 } else if ([v isKindOfClass:[NSArray class]]) {
115 nsprintf(@"%*s%@ -", ind * 4, "", k);
116 print_array(v, ind + 1);
118 nsprintf(@"%*s%@: %@", ind * 4, "", k, v);
122 @interface CKKSControlCLI : NSObject
123 @property CKKSControl* control;
126 @implementation CKKSControlCLI
128 - (instancetype) initWithCKKSControl:(CKKSControl*)control {
129 if ((self = [super init])) {
136 - (NSDictionary<NSString *, id> *)fetchPerformanceCounters
138 NSMutableDictionary *perfDict = [[NSMutableDictionary alloc] init];
140 dispatch_semaphore_t sema = dispatch_semaphore_create(0);
142 [self.control rpcPerformanceCounters:^(NSDictionary<NSString *,NSNumber *> * counters, NSError * error) {
144 perfDict[@"error"] = [error description];
147 [counters enumerateKeysAndObjectsUsingBlock:^(NSString * key, NSNumber * obj, BOOL *stop) {
151 dispatch_semaphore_signal(sema);
154 if(dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 60)) != 0) {
155 perfDict[@"error"] = @"timed out waiting for response";
162 - (long)resetLocal:(NSString*)view {
163 __block long ret = 0;
165 printf("Beginning local reset for %s...\n", view ? [[view description] UTF8String] : "all zones");
166 dispatch_semaphore_t sema = dispatch_semaphore_create(0);
168 [self.control rpcResetLocal:view
169 reply:^(NSError *error) {
171 printf("reset complete.\n");
174 nsprintf(@"reset error: %@\n", error);
177 dispatch_semaphore_signal(sema);
180 if(dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 60 * 2)) != 0) {
181 printf("\n\nError: timed out waiting for response\n");
188 - (long)resetCloudKit:(NSString*)view {
189 __block long ret = 0;
191 printf("Beginning CloudKit reset for %s...\n", view ? [[view description] UTF8String] : "all zones");
192 dispatch_semaphore_t sema = dispatch_semaphore_create(0);
194 [self.control rpcResetCloudKit:view reason:@"ckksctl" reply:^(NSError* error){
196 printf("CloudKit Reset complete.\n");
199 nsprintf(@"Reset error: %@\n", error);
202 dispatch_semaphore_signal(sema);
205 if(dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 60 * 5)) != 0) {
206 printf("\n\nError: timed out waiting for response\n");
213 - (long)resync:(NSString*)view {
214 __block long ret = 0;
216 printf("Beginning resync for %s...\n", view ? [[view description] UTF8String] : "all zones");
217 dispatch_semaphore_t sema = dispatch_semaphore_create(0);
219 [self.control rpcResync:view reply:^(NSError* error){
221 printf("resync success.\n");
224 nsprintf(@"resync errored: %@\n", error);
227 dispatch_semaphore_signal(sema);
230 if(dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 60 * 2)) != 0) {
231 printf("\n\nError: timed out waiting for response\n");
238 - (NSDictionary<NSString *, id> *)fetchStatus: (NSString*) view {
239 NSMutableDictionary *status = [[NSMutableDictionary alloc] init];
241 dispatch_semaphore_t sema = dispatch_semaphore_create(0);
243 [self.control rpcStatus: view reply: ^(NSArray<NSDictionary*>* result, NSError* error) {
245 status[@"error"] = [error description];
248 if(result.count <= 1u) {
249 printf("No CKKS views are active.\n");
253 for(NSDictionary* viewStatus in result) {
254 status[viewStatus[@"view"]] = viewStatus;
256 dispatch_semaphore_signal(sema);
259 if(dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 30)) != 0) {
260 status[@"error"] = @"timed out";
266 - (void)printHumanReadableStatus: (NSString*) view {
268 dispatch_semaphore_t sema = dispatch_semaphore_create(0);
270 [self.control rpcStatus: view reply: ^(NSArray<NSDictionary*>* result, NSError* error) {
272 printf("ERROR FETCHING STATUS: %s\n", [[error description] UTF8String]);
275 #define pop(d, key) ({ id x = d[key]; d[key] = nil; x; })
277 // First result is always global state
278 // Ideally, this would come in another parameter, but we can't change the protocol until
279 // <rdar://problem/33583242> CKKS: remove PCS's use of CKKSControlProtocol
280 NSMutableDictionary* global = [result[0] mutableCopy];
282 NSString* selfPeers = pop(global, @"selfPeers");
283 NSString* selfPeersError = pop(global, @"selfPeersError");
284 NSArray* trustedPeers = pop(global, @"trustedPeers");
285 NSString* trustedPeersError = pop(global, @"trustedPeersError");
286 NSString* reachability = pop(global, @"reachability");
287 NSString* ckdeviceID = pop(global, @"ckdeviceID");
288 NSString* ckdeviceIDError = pop(global, @"ckdeviceIDError");
290 printf("================================================================================\n\n");
291 printf("Global state:\n\n");
292 printf("Current self: %s\n", [[selfPeers description] UTF8String]);
293 if(![selfPeersError isEqual: [NSNull null]]) {
294 printf("Self Peers Error: %s\n", [[selfPeersError description] UTF8String]);
296 printf("Trusted peers: %s\n", [[trustedPeers description] UTF8String]);
297 if(![trustedPeersError isEqual: [NSNull null]]) {
298 printf("Trusted Peers Error: %s\n", [[trustedPeersError description] UTF8String]);
300 printf("Reachability: %s\n", [[reachability description] UTF8String]);
301 printf("CK DeviceID: %s\n", [[ckdeviceID description] UTF8String]);
302 printf("CK DeviceID Error: %s\n", [[ckdeviceIDError description] UTF8String]);
307 NSArray* remainingViews = result.count > 1 ? [result subarrayWithRange:NSMakeRange(1, result.count-1)] : @[];
309 if(remainingViews.count == 0u) {
310 printf("No CKKS views are active.\n");
313 for(NSDictionary* viewStatus in remainingViews) {
314 NSMutableDictionary* status = [viewStatus mutableCopy];
316 NSString* viewName = pop(status,@"view");
317 NSString* accountStatus = pop(status,@"ckaccountstatus");
318 NSString* lockStateTracker = pop(status,@"lockstatetracker");
319 NSString* accountTracker = pop(status,@"accounttracker");
320 NSString* fetcher = pop(status,@"fetcher");
321 NSString* zoneCreated = pop(status,@"zoneCreated");
322 NSString* zoneCreatedError = pop(status,@"zoneCreatedError");
323 NSString* zoneSubscribed = pop(status,@"zoneSubscribed");
324 NSString* zoneSubscribedError = pop(status,@"zoneSubscribedError");
325 NSString* zoneInitializeScheduler = pop(status,@"zoneInitializeScheduler");
326 NSString* keystate = pop(status,@"keystate");
327 NSString* keyStateError = pop(status,@"keyStateError");
328 NSString* statusError = pop(status,@"statusError");
329 NSString* currentTLK = pop(status,@"currentTLK");
330 NSString* currentClassA = pop(status,@"currentClassA");
331 NSString* currentClassC = pop(status,@"currentClassC");
332 NSString* currentTLKPtr = pop(status,@"currentTLKPtr");
333 NSString* currentClassAPtr = pop(status,@"currentClassAPtr");
334 NSString* currentClassCPtr = pop(status,@"currentClassCPtr");
335 NSString* currentManifestGeneration = pop(status,@"currentManifestGen");
337 NSDictionary* oqe = pop(status,@"oqe");
338 NSDictionary* iqe = pop(status,@"iqe");
339 NSDictionary* keys = pop(status,@"keys");
340 NSDictionary* ckmirror = pop(status,@"ckmirror");
341 NSArray* devicestates = pop(status, @"devicestates");
342 NSArray* tlkshares = pop(status, @"tlkshares");
345 NSString* zoneSetupOperation = pop(status,@"zoneSetupOperation");
346 NSString* keyStateOperation = pop(status,@"keyStateOperation");
347 NSString* lastIncomingQueueOperation = pop(status,@"lastIncomingQueueOperation");
348 NSString* lastNewTLKOperation = pop(status,@"lastNewTLKOperation");
349 NSString* lastOutgoingQueueOperation = pop(status,@"lastOutgoingQueueOperation");
350 NSString* lastProcessReceivedKeysOperation = pop(status,@"lastProcessReceivedKeysOperation");
351 NSString* lastReencryptOutgoingItemsOperation = pop(status,@"lastReencryptOutgoingItemsOperation");
352 NSString* lastScanLocalItemsOperation = pop(status,@"lastScanLocalItemsOperation");
354 printf("================================================================================\n\n");
356 printf("View: %s\n\n", [viewName UTF8String]);
358 if(![statusError isEqual: [NSNull null]]) {
359 printf("ERROR FETCHING STATUS: %s\n\n", [statusError UTF8String]);
362 printf("CloudKit account: %s\n", [accountStatus UTF8String]);
363 printf("Account tracker: %s\n", [accountTracker UTF8String]);
365 if(!([zoneCreated isEqualToString:@"yes"] && [zoneSubscribed isEqualToString:@"yes"])) {
366 printf("CK Zone Created: %s\n", [[zoneCreated description] UTF8String]);
367 printf("CK Zone Created error: %s\n", [[zoneCreatedError description] UTF8String]);
369 printf("CK Zone Subscribed: %s\n", [[zoneSubscribed description] UTF8String]);
370 printf("CK Zone Subscription error: %s\n", [[zoneSubscribedError description] UTF8String]);
371 printf("CK Zone initialize retry: %s\n", [[zoneInitializeScheduler description] UTF8String]);
375 printf("Key state: %s\n", [keystate UTF8String]);
376 if(![keyStateError isEqual: [NSNull null]]) {
377 printf("Key State Error: %s\n", [keyStateError UTF8String]);
379 printf("Lock state: %s\n", [lockStateTracker UTF8String]);
381 printf("Current TLK: %s\n", ![currentTLK isEqual: [NSNull null]]
382 ? [currentTLK UTF8String]
383 : [[NSString stringWithFormat:@"missing; pointer is %@", currentTLKPtr] UTF8String]);
384 printf("Current ClassA: %s\n", ![currentClassA isEqual: [NSNull null]]
385 ? [currentClassA UTF8String]
386 : [[NSString stringWithFormat:@"missing; pointer is %@", currentClassAPtr] UTF8String]);
387 printf("Current ClassC: %s\n", ![currentClassC isEqual: [NSNull null]]
388 ? [currentClassC UTF8String]
389 : [[NSString stringWithFormat:@"missing; pointer is %@", currentClassCPtr] UTF8String]);
391 printf("TLK shares: %s\n", [[tlkshares description] UTF8String]);
393 printf("Outgoing Queue counts: %s\n", [[oqe description] UTF8String]);
394 printf("Incoming Queue counts: %s\n", [[iqe description] UTF8String]);
395 printf("Key counts: %s\n", [[keys description] UTF8String]);
396 printf("latest manifest generation: %s\n", [currentManifestGeneration isEqual:[NSNull null]] ? "null" : currentManifestGeneration.UTF8String);
398 printf("Item counts (by key): %s\n", [[ckmirror description] UTF8String]);
399 printf("Peer states: %s\n", [[devicestates description] UTF8String]);
401 printf("zone change fetcher: %s\n", [[fetcher description] UTF8String]);
402 printf("zoneSetupOperation: %s\n", [zoneSetupOperation isEqual: [NSNull null]] ? "never" : [zoneSetupOperation UTF8String]);
403 printf("keyStateOperation: %s\n", [keyStateOperation isEqual: [NSNull null]] ? "never" : [keyStateOperation UTF8String]);
404 printf("lastIncomingQueueOperation: %s\n", [lastIncomingQueueOperation isEqual: [NSNull null]] ? "never" : [lastIncomingQueueOperation UTF8String]);
405 printf("lastNewTLKOperation: %s\n", [lastNewTLKOperation isEqual: [NSNull null]] ? "never" : [lastNewTLKOperation UTF8String]);
406 printf("lastOutgoingQueueOperation: %s\n", [lastOutgoingQueueOperation isEqual: [NSNull null]] ? "never" : [lastOutgoingQueueOperation UTF8String]);
407 printf("lastProcessReceivedKeysOperation: %s\n", [lastProcessReceivedKeysOperation isEqual: [NSNull null]] ? "never" : [lastProcessReceivedKeysOperation UTF8String]);
408 printf("lastReencryptOutgoingItemsOperation: %s\n", [lastReencryptOutgoingItemsOperation isEqual: [NSNull null]] ? "never" : [lastReencryptOutgoingItemsOperation UTF8String]);
409 printf("lastScanLocalItemsOperation: %s\n", [lastScanLocalItemsOperation isEqual: [NSNull null]] ? "never" : [lastScanLocalItemsOperation UTF8String]);
411 if(status.allKeys.count > 0u) {
412 printf("\nExtra information: %s\n", [[status description] UTF8String]);
416 dispatch_semaphore_signal(sema);
419 if(dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 30)) != 0) {
420 printf("\n\nError: timed out waiting for response\n");
425 - (long)fetch:(NSString*)view {
426 __block long ret = 0;
428 dispatch_semaphore_t sema = dispatch_semaphore_create(0);
430 [self.control rpcFetchAndProcessChanges:view reply:^(NSError* error) {
432 printf("Error fetching: %s\n", [[error description] UTF8String]);
433 ret = (error.code == 0 ? -1 : error.code);
435 printf("Complete.\n");
439 dispatch_semaphore_signal(sema);
442 if(dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 65)) != 0) {
443 printf("\n\nError: timed out waiting for response\n");
450 - (long)push:(NSString*)view {
451 __block long ret = 0;
453 dispatch_semaphore_t sema = dispatch_semaphore_create(0);
455 [self.control rpcPushOutgoingChanges:view reply:^(NSError* error) {
457 printf("Error pushing: %s\n", [[error description] UTF8String]);
458 ret = (error.code == 0 ? -1 : error.code);
460 printf("Complete.\n");
464 dispatch_semaphore_signal(sema);
467 if(dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 65)) != 0) {
468 printf("\n\nError: timed out waiting for response\n");
478 static int perfCounters = false;
479 static int status = false;
480 static int resync = false;
481 static int reset = false;
482 static int resetCloudKit = false;
483 static int fetch = false;
484 static int push = false;
485 static int json = false;
487 static char* viewArg = NULL;
489 int main(int argc, char **argv)
491 static struct argument options[] = {
492 { .shortname='p', .longname="perfcounters", .flag=&perfCounters, .flagval=true, .description="Print CKKS performance counters"},
493 { .shortname='j', .longname="json", .flag=&json, .flagval=true, .description="Output in JSON format"},
494 { .shortname='v', .longname="view", .argument=&viewArg, .description="Operate on a single view"},
496 { .command="status", .flag=&status, .flagval=true, .description="Report status on CKKS views"},
497 { .command="fetch", .flag=&fetch, .flagval=true, .description="Fetch all new changes in CloudKit and attempt to process them"},
498 { .command="push", .flag=&push, .flagval=true, .description="Push all pending local changes to CloudKit"},
499 { .command="resync", .flag=&resync, .flagval=true, .description="Resync all data with what's in CloudKit"},
500 { .command="reset", .flag=&reset, .flagval=true, .description="All local data will be wiped, and data refetched from CloudKit"},
501 { .command="reset-cloudkit", .flag=&resetCloudKit, .flagval=true, .description="All data in CloudKit will be removed and replaced with what's local"},
505 static struct arguments args = {
506 .programname="ckksctl",
507 .description="Control and report on CKKS",
508 .arguments = options,
511 if(!options_parse(argc, argv, &args)) {
518 NSError* error = nil;
520 CKKSControl* rpc = [CKKSControl controlObject:&error];
522 errx(1, "no CKKSControl failed: %s", [[error description] UTF8String]);
525 CKKSControlCLI* ctl = [[CKKSControlCLI alloc] initWithCKKSControl:rpc];
527 NSString* view = viewArg ? [NSString stringWithCString: viewArg encoding: NSUTF8StringEncoding] : nil;
530 // Complicated logic, but you can choose any combination of (json, perfcounters) that you like.
531 NSMutableDictionary *statusDict = [[NSMutableDictionary alloc] init];
533 statusDict[@"performance"] = [ctl fetchPerformanceCounters];
536 statusDict[@"status"] = [ctl fetchStatus:view];
538 if(json || perfCounters) {
539 print_result(statusDict, true);
544 [ctl printHumanReadableStatus:view];
547 } else if(perfCounters) {
548 NSMutableDictionary *statusDict = [[NSMutableDictionary alloc] init];
549 statusDict[@"performance"] = [ctl fetchPerformanceCounters];
550 print_result(statusDict, false);
553 return (int)[ctl fetch:view];
555 return (int)[ctl push:view];
557 return (int)[ctl resetLocal:view];
558 } else if(resetCloudKit) {
559 return (int)[ctl resetCloudKit:view];
561 return (int)[ctl resync:view];