File: CRURegistration.m

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (681 lines) | stat: -rw-r--r-- 23,992 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#if !defined(__has_feature) || !__has_feature(objc_arc)
#error "CRURegistration requires ARC support. Compile with `-fobjc-arc.`"
#endif

#import "CRURegistration.h"

#import <Foundation/Foundation.h>
#import <dispatch/dispatch.h>
#include <unistd.h>

#import "CRURegistration-Private.h"

#pragma mark - Constants

NSString* const CRURegistrationErrorDomain = @"org.chromium.CRURegistration";
NSString* const CRUReturnCodeErrorDomain = @"org.chromium.CRUReturnCode";
NSString* const CRURegistrationInternalErrorDomain =
    @"org.chromium.CRURegistrationInternal";

// Keys that may be present in NSError `userInfo` dictionaries.
NSString* const CRUErrnoKey = @"org.chromium.CRUErrno";
NSString* const CRUStdStreamNameKey = @"org.chromium.CRUStdStreamName";
NSString* const CRUStderrKey = @"org.chromium.CRUStderr";
NSString* const CRUStdoutKey = @"org.chromium.CRUStdout";
NSString* const CRUReturnCodeKey = @"org.chromium.CRUReturnCode";

#pragma mark - CRUAsyncTaskRunner

@implementation CRUAsyncTaskRunner {
  // These fields are written once during init and never again.
  dispatch_queue_t _parentQueue;
  dispatch_queue_t _privateQueue;
  NSTask* _task;

  // These fields are guarded by `_privateQueue`.
  BOOL _launched;
  NSMutableData* _taskStdoutData;
  NSMutableData* _taskStderrData;
  NSError* _taskManagementError;
  NSPipe* _taskStdoutPipe;
  NSPipe* _taskStderrPipe;
  dispatch_group_t _done_group;
}

- (instancetype)initWithTask:(NSTask*)task
                 targetQueue:(dispatch_queue_t)targetQueue {
  if (self = [super init]) {
    _task = task;
    _parentQueue = targetQueue;
    _privateQueue = dispatch_queue_create_with_target(
        "CRUAsyncTaskRunner", DISPATCH_QUEUE_SERIAL, targetQueue);
  }
  return self;
}

- (void)launchWithReply:(CRUTaskResultCallback)reply {
  dispatch_async(_privateQueue, ^{
    [self syncLaunchWithReply:reply];
  });
}

- (void)syncLaunchWithReply:(CRUTaskResultCallback)reply {
  if (_launched) {
    NSString* taskUrl = _task.executableURL.description;
    NSString* argList = [_task.arguments componentsJoinedByString:@"\n"];
    dispatch_async(_parentQueue, ^{
      reply(nil, nil,
            [NSError
                errorWithDomain:CRURegistrationInternalErrorDomain
                           code:CRURegistrationInternalErrorTaskAlreadyLaunched
                       userInfo:@{
                         NSFilePathErrorKey : taskUrl,
                         NSDebugDescriptionErrorKey : argList,
                       }]);
    });
    return;
  }

  _taskStdoutPipe = [NSPipe pipe];
  _taskStderrPipe = [NSPipe pipe];
  _task.standardOutput = _taskStdoutPipe;
  _task.standardError = _taskStderrPipe;
  _taskStdoutData = [NSMutableData data];
  _taskStderrData = [NSMutableData data];
  _taskManagementError = nil;

  _done_group = dispatch_group_create();
  // Enter for task configuration, to avoid invoking the handler block if the
  // task exits before we've gotten a chance to start processing its output.
  dispatch_group_enter(_done_group);

  dispatch_group_notify(_done_group, _privateQueue, ^{
    self->_task.terminationHandler = nil;
    if (self->_taskManagementError) {
      // The task never launched; touching task.terminationStatus would crash.
      dispatch_async(self->_parentQueue, ^{
        reply(nil, nil, self->_taskManagementError);
      });
      return;
    }

    NSError* returnCodeError = nil;
    if (self->_task.terminationStatus) {
      returnCodeError = [NSError errorWithDomain:CRUReturnCodeErrorDomain
                                            code:self->_task.terminationStatus
                                        userInfo:nil];
    }
    dispatch_async(self->_parentQueue, ^{
      reply([[NSString alloc] initWithData:self->_taskStdoutData
                                  encoding:NSUTF8StringEncoding],
            [[NSString alloc] initWithData:self->_taskStderrData
                                  encoding:NSUTF8StringEncoding],
            returnCodeError);
    });
  });

  // All fields are prepared and the result callback is armed. Hand off to
  // `syncFinishLaunching` so we can early-out on failure without specifically
  // balancing _done_group on each exit path.
  [self syncFinishLaunching];
  dispatch_group_leave(_done_group);
}

- (void)syncFinishLaunching {
  // Local reference to avoid referring to queue-protected fields of `_self`
  // without necessarily being on `_private_queue` -- there are no guarantees
  // about where an NSTask's termination handler is executed.
  dispatch_group_t done_group = _done_group;
  // Enter `_done_group` for task execution itself.
  dispatch_group_enter(done_group);
  _task.terminationHandler = ^(NSTask* unused) {
    dispatch_group_leave(done_group);
  };

  NSError* launchError = nil;
  if (![_task launchAndReturnError:&launchError]) {
    _taskManagementError = launchError;
    // Cancel the `enter`, since the termination handler will never run.
    dispatch_group_leave(done_group);
    return;
  }

  // Task is launched, kick off async I/O.

  [self syncSubscribeAsyncOnHandle:_taskStdoutPipe.fileHandleForReading
                              into:_taskStdoutData
                             named:@"stdout"];
  [self syncSubscribeAsyncOnHandle:_taskStderrPipe.fileHandleForReading
                              into:_taskStderrData
                             named:@"stderr"];
}

- (void)syncSubscribeAsyncOnHandle:(NSFileHandle*)readHandle
                              into:(NSMutableData*)dataOut
                             named:(NSString*)streamName {
  dispatch_group_enter(_done_group);
  dispatch_io_t stdoutIO = dispatch_io_create(
      DISPATCH_IO_STREAM, readHandle.fileDescriptor, _privateQueue,
      ^(int unused) {
        NSError* cleanupError = nil;
        NSAssert([readHandle closeAndReturnError:&cleanupError],
                 @"couldn't close task %@: %@", streamName, cleanupError);
      });
  dispatch_io_read(
      stdoutIO, 0, SIZE_MAX, _privateQueue,
      ^(bool done, dispatch_data_t chunk, int error) {
        if (chunk) {
          // dispatch_data_t may be cast to NSData in 64-bit software:
          // https://developer.apple.com/documentation/dispatch/dispatch_data_t?language=objc
          [dataOut appendData:(NSData*)chunk];
        }
        if (done || error) {
          dispatch_io_close(stdoutIO, 0);
          if (error && !self->_taskManagementError) {
            self->_taskManagementError = [NSError
                errorWithDomain:CRURegistrationErrorDomain
                           code:CRURegistrationErrorTaskStreamUnreadable
                       userInfo:@{
                         CRUErrnoKey : @(error),
                         CRUStdStreamNameKey : streamName,
                       }];
          }
          dispatch_group_leave(self->_done_group);
        }
      });
}

@end  // CRUAsyncTaskRunner

#pragma mark - CRURegistrationWorkItem

@implementation CRURegistrationWorkItem

@synthesize binPathCallback = _binPathCallback;
@synthesize args = _args;
@synthesize onDone = _onDone;
@synthesize resultCallback = _resultCallback;

@end

#pragma mark - CRURegistration

@implementation CRURegistration {
  // Immutable fields.
  NSString* _appId;
  NSString* _existenceCheckerPath;

  dispatch_queue_t _privateQueue;
  dispatch_queue_t _parentQueue;

  NSMutableArray<CRURegistrationWorkItem*>* _pendingWork;
  CRUAsyncTaskRunner* _currentWork;
}

- (instancetype)initWithAppId:(NSString*)appId
         existenceCheckerPath:(NSString*)xcPath
                  targetQueue:(dispatch_queue_t)targetQueue {
  if (self = [super init]) {
    _appId = appId;
    _existenceCheckerPath = xcPath;
    _parentQueue = targetQueue;
    _privateQueue = dispatch_queue_create_with_target(
        "CRURegistration", DISPATCH_QUEUE_SERIAL, targetQueue);
    _pendingWork = [NSMutableArray array];
  }
  return self;
}

- (instancetype)initWithAppId:(NSString*)appId
         existenceCheckerPath:(NSString*)xcPath
                          qos:(dispatch_qos_class_t)qos {
  return [self initWithAppId:appId
        existenceCheckerPath:xcPath
                 targetQueue:dispatch_get_global_queue(qos, 0)];
}

- (instancetype)initWithAppId:(NSString*)appId
         existenceCheckerPath:(NSString*)xcPath {
  return [self initWithAppId:appId
        existenceCheckerPath:xcPath
                         qos:QOS_CLASS_UTILITY];
}

/**
 * newKSAdminItem constructs a CRURegistrationWorkItem that will invoke ksadmin.
 */
- (CRURegistrationWorkItem*)newKSAdminItem {
  CRURegistrationWorkItem* ret = [[CRURegistrationWorkItem alloc] init];
  ret.binPathCallback = ^{
    return [self syncFindBestKSAdmin];
  };
  return ret;
}

- (void)fetchTagWithReply:(void (^)(NSString* _Nullable,
                                    NSError* _Nullable))reply {
  if (!reply) {
    return;
  }
  CRURegistrationWorkItem* fetchTagItem = [self newKSAdminItem];
  fetchTagItem.args = @[
    @"--print-tag",
    @"--productid",
    _appId,
    @"--xcpath",
    _existenceCheckerPath,
  ];
  fetchTagItem.resultCallback =
      ^(NSString* gotStdout, NSString* gotStderr, NSError* gotFailure) {
        if (gotFailure) {
          NSError* finalError = [self wrapError:gotFailure
                                     withStdout:gotStdout
                                      andStderr:gotStderr];
          dispatch_async(self->_parentQueue, ^{
            reply(nil, finalError);
          });
          return;
        }
        if (gotStdout.length) {
          // Trim off the trailing newline.
          NSString* tag = [gotStdout substringToIndex:gotStdout.length - 1];
          dispatch_async(self->_parentQueue, ^{
            reply(tag, nil);
          });
          return;
        }
        // Empty stdout implies "no tag".
        dispatch_async(self->_parentQueue, ^{
          reply(@"", nil);
        });
      };
  [self addWorkItems:@[ fetchTagItem ]];
}

- (void)registerVersion:(NSString*)version
                  reply:(void (^_Nullable)(NSError*))reply {
  NSAssert(version, @"nil version provided to registerVersion for app %@.",
           _appId);
  if (!version) {
    if (reply) {
      NSString* localAppId = _appId;
      dispatch_async(_parentQueue, ^{
        reply([NSError
            errorWithDomain:CRURegistrationErrorDomain
                       code:CRURegistrationErrorInvalidArgument
                   userInfo:@{
                     NSDebugDescriptionErrorKey :
                         [NSString stringWithFormat:
                                       @"CRURegistration's registerVersion for "
                                       @"app %@ was called with nil version.",
                                       localAppId],
                   }]);
      });
    }
    return;
  }

  CRURegistrationWorkItem* registerItem = [self newKSAdminItem];
  registerItem.args = @[
    @"--register",
    @"--productid",
    _appId,
    @"--version",
    version,
    @"--xcpath",
    _existenceCheckerPath,
  ];
  registerItem.resultCallback =
      ^(NSString* gotStdout, NSString* gotStderr, NSError* gotFailure) {
          if (reply) {
            dispatch_async(self->_parentQueue, ^{
              reply([self wrapError:gotFailure
                         withStdout:gotStdout
                          andStderr:gotStderr]);
            });
          }
      };

  [self addWorkItems:@[ registerItem ]];
}

- (void)installUpdaterWithReply:(void (^)(NSError* _Nullable))reply {
  // Build the "unzip and install" task chain on the private queue since
  // creating the temp dir is a synchronous file operation, which we need to
  // keep away from the calling thread since CRURegistration promises to do
  // all the expensive stuff asynchronously.
  dispatch_async(_privateQueue, ^{
    NSString* tempDir = [self syncNewTempDir];
    CRURegistrationWorkItem* unzipItem =
        [self workItemUnzippingInstallerToPath:tempDir];
    if (!unzipItem) {
      // We can't find anything to install. Fail immediately; we cannot create
      // the installation task.
      if (reply) {
        dispatch_async(self->_parentQueue, ^{
          NSString* expectedFilename =
              [CRUArchiveBasename stringByAppendingString:@".zip"];
          reply([NSError
              errorWithDomain:CRURegistrationErrorDomain
                         code:CRURegistrationErrorUpdaterArchiveNotFound
                     userInfo:@{NSFilePathErrorKey : expectedFilename}]);
        });
      }
      return;
    }
    CRURegistrationWorkItem* installItem =
        [self workItemInstallingFromDirectory:tempDir];
    unzipItem.onDone = ^CRURegistrationWorkItem*(
        CRURegistrationWorkItem* me, NSString* ignored, NSString* ignored2,
        NSError* error) {
      if (error) {
        me.resultCallback =
            ^(NSString* gotStdout, NSString* gotStderr, NSError* gotFailure) {
              if (reply) {
                dispatch_async(self->_parentQueue, ^{
                  reply([self wrapError:gotFailure
                             withStdout:gotStdout
                              andStderr:gotStderr]);
                });
              }
            };
        return nil;
      }
      return installItem;
    };
    installItem.resultCallback =
        ^(NSString* gotStdout, NSString* gotStderr, NSError* gotFailure) {
          dispatch_async(self->_privateQueue, ^{
            // Temp dir cleanup is best effort; we can't do anything useful with
            // the error here anyway.
            [[NSFileManager defaultManager] removeItemAtPath:tempDir error:nil];
          });
          if (reply) {
            dispatch_async(self->_parentQueue, ^{
              reply([self wrapError:gotFailure
                         withStdout:gotStdout
                          andStderr:gotStderr]);
            });
          }
        };
    // Don't re-dispatch to _privateQueue to avoid potentially reordering
    // this "install" request behind another operation that might have been
    // enqueued before we got around to running this setup work.
    [self->_pendingWork addObject:unzipItem];
    [self syncMaybeStartMoreWork];
  });
}

- (void)markActiveWithReply:(void (^)(NSError* _Nullable))reply {
  // "Mark active" doesn't use an external program, so it may run concurrently
  // with out-of-process tasks. It still uses _privateQueue so the SSD/HDD
  // access runs with the intended priority.
  dispatch_async(_privateQueue, ^{
    NSError* error;
    BOOL success = [self syncWriteActiveFileWithError:&error];
    if (!reply) {
      return;
    }
    dispatch_async(self->_parentQueue, ^{
      reply(success
                ? nil
                : [NSError errorWithDomain:CRURegistrationErrorDomain
                                      code:CRURegistrationErrorFilesystem
                                  userInfo:@{NSUnderlyingErrorKey : error}]);
    });
  });
}

#pragma mark - CRURegistration private methods

- (void)syncMaybeStartMoreWork {
  if (_currentWork || !_pendingWork.count) {
    return;
  }

  CRURegistrationWorkItem* nextItem = _pendingWork.firstObject;
  // NSMutableArray is actually a deque, so the obvious approach is performant.
  [_pendingWork removeObjectAtIndex:0];

  NSURL* taskURL = nextItem.binPathCallback();
  if (!taskURL) {
    NSError* error = [NSError errorWithDomain:CRURegistrationErrorDomain
                                         code:CRURegistrationErrorHelperNotFound
                                     userInfo:nil];
    if (nextItem.onDone) {
      CRURegistrationWorkItem* preempt =
          nextItem.onDone(nextItem, nil, nil, error);
      if (preempt) {
        [_pendingWork insertObject:preempt atIndex:0];
      }
    }
    self->_currentWork = nil;
    dispatch_async(_parentQueue, ^{
      nextItem.resultCallback(nil, nil, error);
    });
    [self syncMaybeStartMoreWork];
    return;
  }

  NSTask* task = [[NSTask alloc] init];
  task.executableURL = taskURL;
  task.arguments = nextItem.args;

  _currentWork = [[CRUAsyncTaskRunner alloc] initWithTask:task
                                              targetQueue:_privateQueue];
  [_currentWork
      launchWithReply:^(NSString* taskOut, NSString* taskErr, NSError* error) {
        if (nextItem.onDone) {
          CRURegistrationWorkItem* preempt =
              nextItem.onDone(nextItem, taskOut, taskErr, error);
          if (preempt) {
            [self->_pendingWork insertObject:preempt atIndex:0];
          }
        }
        self->_currentWork = nil;
        if (nextItem.resultCallback) {
          dispatch_async(self->_parentQueue, ^{
            nextItem.resultCallback(taskOut, taskErr, error);
          });
        }
        [self syncMaybeStartMoreWork];
      }];
}

- (NSString*)installerPathInDirectory:(NSString*)directory {
  NSString* helperPathInBundle =
      [NSString stringWithFormat:@"%1$@.app/Contents/MacOS/%1$@",
                                 CRUInstallerAppBasename];
  return [directory stringByAppendingPathComponent:helperPathInBundle];
}

/**
 * Writes an empty file to the path the updater uses as a "product was active"
 * sentinel for the provided app ID. Stomps on any file already at this path.
 * Does not validate the app ID; app IDs are assumed not to be under user
 * control, so a malicious string here could theoretically be some kind of
 * weird directory traversal attack.
 */
- (BOOL)syncWriteActiveFileWithError:(NSError**)error {
  NSFileManager* fm = [NSFileManager defaultManager];
  NSURL* library = [fm URLForDirectory:NSLibraryDirectory
                              inDomain:NSUserDomainMask
                     appropriateForURL:nil
                                create:NO
                                 error:error];
  if (!library) {
    return NO;
  }
  NSString* activesPathUnderLibrary =
      [NSString stringWithFormat:@"%s/%s/Actives", CRU_COMPANY_SHORTNAME_STRING,
                                 CRU_KEYSTONE_NAME];
  NSURL* activesPath =
      [library URLByAppendingPathComponent:activesPathUnderLibrary
                               isDirectory:YES];
  if (![fm createDirectoryAtURL:activesPath
          withIntermediateDirectories:YES
                           attributes:nil
                                error:error]) {
    return NO;
  }
  NSURL* target = [activesPath URLByAppendingPathComponent:_appId
                                               isDirectory:NO];
  return [@"" writeToFile:target.path
               atomically:NO
                 encoding:NSUTF8StringEncoding
                    error:error];
}

/**
 * syncNewTempDir uses mkdtemp to create a unique temp directory named after
 * the updater. It's marked as "sync" only because it performs synchronous
 * file I/O so should be kept off the caller's thread, which might be the
 * application's main thread.
 */
- (NSString*)syncNewTempDir {
  NSString* templateSuffix =
      [NSString stringWithFormat:@"%@_UpdaterInstaller_XXXXXX", _appId];
  NSString* template =
      [NSTemporaryDirectory() stringByAppendingPathComponent:templateSuffix];
  char* pathTemplateCString = strdup([template fileSystemRepresentation]);
  if (!pathTemplateCString) {
    return nil;
  }
  char* out = mkdtemp(pathTemplateCString);
  NSString* result = out ? [NSString stringWithUTF8String:out] : nil;
  free(pathTemplateCString);
  return result;
}

- (NSString*)syncInstallerArchivePath {
  return [NSBundle.mainBundle pathForResource:CRUArchiveBasename ofType:@"zip"];
}

- (CRURegistrationWorkItem*)workItemUnzippingInstallerToPath:(NSString*)path {
  NSString* archivePath = [self syncInstallerArchivePath];
  if (!archivePath) {
    return nil;
  }
  CRURegistrationWorkItem* unzipItem = [[CRURegistrationWorkItem alloc] init];
  unzipItem.binPathCallback = ^{
    return [NSURL fileURLWithPath:@"/usr/bin/tar" isDirectory:NO];
  };
  unzipItem.args = @[
    @"-x",
    @"-f",
    [self syncInstallerArchivePath],
    @"-C",
    path,
    @"--no-same-owner",
  ];
  return unzipItem;
}

- (CRURegistrationWorkItem*)workItemInstallingFromDirectory:(NSString*)path {
  CRURegistrationWorkItem* installItem = [[CRURegistrationWorkItem alloc] init];
  installItem.binPathCallback = ^{
    return [NSURL fileURLWithPath:[self installerPathInDirectory:path]
                      isDirectory:NO];
  };
  installItem.args = @[ @"--install" ];
  return installItem;
}
@end

#pragma mark - CRURegistration (VisibleForTesting)

@implementation CRURegistration (VisibleForTesting)

- (void)addWorkItems:(NSArray<CRURegistrationWorkItem*>*)items {
  dispatch_async(_privateQueue, ^{
    [self->_pendingWork addObjectsFromArray:items];
    [self syncMaybeStartMoreWork];
  });
}

- (NSURL*)syncFindBestKSAdmin {
  NSFileManager* fm = [NSFileManager defaultManager];
  NSArray<NSURL*>* libraries =
      [fm URLsForDirectory:NSLibraryDirectory
                 inDomains:NSUserDomainMask | NSLocalDomainMask];
  NSString* ksadminPathUnderLibrary =
      [NSString stringWithFormat:@"%s/%s/%s.bundle/Contents/Helpers/ksadmin",
                                 CRU_COMPANY_SHORTNAME_STRING,
                                 CRU_KEYSTONE_NAME, CRU_KEYSTONE_NAME];
  // URLsForDirectory returns paths in ascending order of domain mask values.
  // To match Keystone's behavior, we prefer local domain (machine install) over
  // user domain; local domain has the higher numerical value, so we test
  // these in reverse order.
  for (NSURL* library in libraries.reverseObjectEnumerator) {
    NSURL* candidate =
        [library URLByAppendingPathComponent:ksadminPathUnderLibrary
                                 isDirectory:NO];
    if ([fm isExecutableFileAtPath:candidate.path]) {
      return candidate;
    }
  }
  return nil;
}

- (NSError*)wrapError:(NSError*)error
           withStdout:(NSString*)gotStdout
            andStderr:(NSString*)gotStderr {
  if (!error) {
    return nil;
  }

  // Check for errors already ready for user presentation.
  if ([error.domain isEqual:CRURegistrationErrorDomain] ||
      [error.domain isEqual:CRURegistrationInternalErrorDomain]) {
    return error;
  }

  // We're going to need to wrap this error. Start with common error info.
  NSMutableDictionary* userInfo = [NSMutableDictionary
      dictionaryWithDictionary:@{NSUnderlyingErrorKey : error}];
  if (gotStdout) {
    userInfo[CRUStdoutKey] = gotStdout;
  }
  if (gotStderr) {
    userInfo[CRUStderrKey] = gotStderr;
  }
  id maybeFilePath = error.userInfo[NSFilePathErrorKey];
  if (maybeFilePath) {
    userInfo[NSFilePathErrorKey] = maybeFilePath;
  }
  id maybeURL = error.userInfo[NSURLErrorKey];
  if (maybeURL) {
    userInfo[NSURLErrorKey] = maybeURL;
  }

  // Check for helper task failure.
  if ([error.domain isEqual:CRUReturnCodeErrorDomain]) {
    userInfo[CRUReturnCodeKey] = @(error.code);
    return [NSError errorWithDomain:CRURegistrationErrorDomain
                               code:CRURegistrationErrorTaskFailed
                           userInfo:userInfo];
  }

  // Check for errors reported by NSTask if it cannot find the task, or the file
  // specified is not executable. NSTask returns the same error code for both.
  // This NSTask behavior was determined experimentally -- Apple does not
  // document the errors that NSTask can emit -- so promoting this to a
  // HelperNotFound error should be considered "best-efort".
  if ([error.domain isEqual:NSCocoaErrorDomain] &&
      error.code == NSFileNoSuchFileError) {
    return [NSError errorWithDomain:CRURegistrationErrorDomain
                               code:CRURegistrationErrorHelperNotFound
                           userInfo:userInfo];
  }

  // Unrecognized error.
  return [NSError errorWithDomain:CRURegistrationInternalErrorDomain
                             code:CRURegistrationInternalErrorUnrecognized
                         userInfo:userInfo];
}

@end