-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathMacPlatform.cs
More file actions
692 lines (593 loc) · 26.6 KB
/
MacPlatform.cs
File metadata and controls
692 lines (593 loc) · 26.6 KB
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
682
683
684
685
686
687
688
689
690
691
692
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace sttz.InstallUnity
{
/// <summary>
/// Platform-specific installer code for macOS.
/// </summary>
public class MacPlatform : IInstallerPlatform
{
/// <summary>
/// Bundle ID of Unity editors (applies for 5+, even 2018).
/// </summary>
const string BUNDLE_ID = "com.unity3d.UnityEditor5.x";
/// <summary>
/// Volume where the packages will be installed to.
/// </summary>
const string INSTALL_VOLUME = "/";
/// <summary>
/// Default installation path.
/// </summary>
const string INSTALL_PATH = "/Applications/Unity";
/// <summary>
/// Path used to temporarily move existing installation out of the way.
/// </summary>
const string INSTALL_PATH_TMP = "/Applications/Unity (Moved by " + UnityInstaller.PRODUCT_NAME + ")";
/// <summary>
/// Match the mount point from hdiutil's output, e.g.:
/// /dev/disk4s2 Apple_HFS /private/tmp/dmg.0bDM7Q
/// </summary>
static Regex MOUNT_POINT_REGEX = new Regex(@"^(?:\/dev\/\w+)[\t ]+(?:\w+)[\t ]+(\/.*)$", RegexOptions.Multiline);
// -------- IInstallerPlatform --------
public async Task<CachePlatform> GetCurrentPlatform()
{
var result = await Command.Run("uname", "-a");
if (result.exitCode != 0) {
throw new Exception($"ERROR: {result.error}");
}
if (result.output.Contains("_ARM64_")) {
return CachePlatform.macOSArm;
} else if (result.output.Contains("x86_64")) {
return CachePlatform.macOSIntel;
}
throw new Exception($"Unknown runtime architecture: '{result.output.Trim()}'");
}
public async Task<IEnumerable<CachePlatform>> GetInstallablePlatforms()
{
var platform = await GetCurrentPlatform();
if (platform == CachePlatform.macOSIntel) {
return new CachePlatform[] {
CachePlatform.macOSIntel
};
} else {
return new CachePlatform[] {
CachePlatform.macOSIntel,
CachePlatform.macOSArm
};
}
}
string GetUserLibraryDirectory()
{
var home = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
return Path.Combine(home, "Library");
}
string GetUserApplicationSupportDirectory()
{
return Path.Combine(Path.Combine(GetUserLibraryDirectory(), "Application Support"), UnityInstaller.PRODUCT_NAME);
}
public string GetConfigurationDirectory()
{
return GetUserApplicationSupportDirectory();
}
public string GetCacheDirectory()
{
return GetUserApplicationSupportDirectory();
}
public string GetDownloadDirectory()
{
return Path.Combine(Path.GetTempPath(), UnityInstaller.PRODUCT_NAME);
}
public Task<bool> IsAdmin(CancellationToken cancellation = default)
{
return CheckIsRoot(false, cancellation);
}
public async Task<bool> PromptForPasswordIfNecessary(CancellationToken cancellation = default)
{
if (await CheckIsRoot(false, cancellation)) return true;
Console.WriteLine();
var attempts = 3;
while (true) {
if (pwd == null) {
Console.Write($"{UnityInstaller.PRODUCT_NAME} requires your admin password: ");
pwd = Helpers.ReadPassword();
}
if (await CheckIsRoot(true, cancellation)) {
return true;
} else if (--attempts > 0) {
Console.WriteLine("Sorry, try again.");
pwd = null;
} else {
pwd = null;
return false;
}
}
}
public async Task<IEnumerable<Installation>> FindInstallations(CancellationToken cancellation = default)
{
var findResult = await Command.Run("/usr/bin/mdfind", $"kMDItemCFBundleIdentifier = '{BUNDLE_ID}'", null, cancellation);
if (findResult.exitCode != 0) {
throw new Exception($"ERROR: {findResult.error}");
}
var lines = findResult.output.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
var installations = new List<Installation>(lines.Length);
foreach (var appPath in lines) {
if (!Directory.Exists(appPath)) {
Logger.LogWarning($"Could not find Unity installation at path: {appPath}");
continue;
}
var installRoot = Path.GetDirectoryName(appPath);
// Cursory check if the user has moved the Unity.app somewhere else
var bugReporterPath = Path.Combine(installRoot, "Unity Bug Reporter.app");
if (!Directory.Exists(bugReporterPath)) {
Logger.LogWarning("Unity.app appears to be in a non-standard Unity folder: " + appPath);
continue;
}
var versionResult = await Command.Run("/usr/bin/defaults", $"read \"{appPath}/Contents/Info\" CFBundleVersion", null, cancellation);
if (versionResult.exitCode != 0) {
throw new Exception($"ERROR: {versionResult.error}");
}
var version = new UnityVersion(versionResult.output.Trim());
if (!version.IsFullVersion) {
Logger.LogWarning($"Could not determine Unity version at path '{appPath}': {versionResult.output.Trim()}");
continue;
}
var hashResult = await Command.Run("/usr/bin/defaults", $"read \"{appPath}/Contents/Info\" UnityBuildNumber", null, cancellation);
if (hashResult.exitCode != 0) {
throw new Exception($"ERROR: {hashResult.error}");
}
version.hash = hashResult.output.Trim();
var executable = ExecutableFromAppPath(appPath);
if (executable == null) continue;
Logger.LogDebug($"Found Unity {version} at path: {appPath}");
installations.Add(new Installation() {
path = installRoot,
executable = executable,
version = version
});
}
return installations;
}
public async Task PrepareInstall(UnityInstaller.Queue queue, string installationPaths, CancellationToken cancellation = default)
{
if (installing.version.IsValid)
throw new InvalidOperationException($"Already installing another version: {installing.version}");
installing = queue.metadata;
this.installationPaths = installationPaths;
installedEditor = false;
// Move existing installation out of the way
movedExisting = false;
if (Directory.Exists(INSTALL_PATH)) {
if (Directory.Exists(INSTALL_PATH_TMP)) {
throw new InvalidOperationException($"Fallback installation path '{INSTALL_PATH_TMP}' already exists.");
}
Logger.LogInformation("Temporarily moving existing installation at default install path: " + INSTALL_PATH);
await Move(INSTALL_PATH, INSTALL_PATH_TMP, cancellation);
movedExisting = true;
}
// Check for upgrading installation
upgradeOriginalPath = null;
if (!queue.items.Any(i => i.package.name == PackageMetadata.EDITOR_PACKAGE_NAME)) {
var installs = await FindInstallations(cancellation);
var existingInstall = installs.Where(i => i.version == queue.metadata.version).FirstOrDefault();
if (existingInstall == null) {
throw new InvalidOperationException($"Not installing editor but version {queue.metadata.version} not already installed.");
}
upgradeOriginalPath = existingInstall.path;
Logger.LogInformation($"Temporarily moving installation to upgrade from '{existingInstall}' to default install path");
await Move(existingInstall.path, INSTALL_PATH, cancellation);
}
}
public async Task Install(UnityInstaller.Queue queue, UnityInstaller.QueueItem item, CancellationToken cancellation = default)
{
if (item.package.name != PackageMetadata.EDITOR_PACKAGE_NAME && !installedEditor && upgradeOriginalPath == null) {
throw new InvalidOperationException("Cannot install package without installing editor first.");
}
var extentsion = Path.GetExtension(item.filePath).ToLower();
if (extentsion == ".pkg") {
await InstallPkg(item.filePath, cancellation);
} else if (extentsion == ".dmg") {
await InstallDmg(item.filePath, cancellation);
} else if (extentsion == ".zip") {
await InstallZip(item.filePath, item.package.destination, item.package.renameFrom, item.package.renameTo, cancellation);
} else if (extentsion == ".po") {
await InstallFile(item.filePath, item.package.destination, cancellation);
} else {
throw new Exception("Cannot install package of type: " + extentsion);
}
if (item.package.name == PackageMetadata.EDITOR_PACKAGE_NAME) {
installedEditor = true;
}
}
public async Task<Installation> CompleteInstall(bool aborted, CancellationToken cancellation = default)
{
if (!installing.version.IsValid)
throw new InvalidOperationException("Not installing any version to complete");
string destination = null;
if (upgradeOriginalPath != null) {
// Move back installation
destination = upgradeOriginalPath;
Logger.LogInformation("Moving back upgraded installation to: " + destination);
await Move(INSTALL_PATH, destination, cancellation);
} else if (!aborted) {
// Move new installations to "Unity VERSION"
destination = GetUniqueInstallationPath(installing.version, installationPaths);
Logger.LogInformation("Moving newly installed version to: " + destination);
await Move(INSTALL_PATH, destination, cancellation);
} else if (aborted) {
// Clean up partial installation
Logger.LogInformation("Deleting aborted installation at path: " + INSTALL_PATH);
await Delete(INSTALL_PATH, cancellation);
}
// Move back original Unity folder
if (movedExisting) {
Logger.LogInformation("Moving back installation that was at default installation path");
await Move(INSTALL_PATH_TMP, INSTALL_PATH, cancellation);
}
if (!aborted) {
var executable = ExecutableFromAppPath(Path.Combine(destination, "Unity.app"));
if (executable == null) return default;
var installation = new Installation() {
version = installing.version,
executable = executable,
path = destination
};
installing = default;
movedExisting = false;
upgradeOriginalPath = null;
return installation;
} else {
return default;
}
}
public async Task MoveInstallation(Installation installation, string newPath, CancellationToken cancellation = default)
{
if (Directory.Exists(newPath) || File.Exists(newPath))
throw new ArgumentException("Destination path already exists: " + newPath);
await Move(installation.path, newPath, cancellation);
installation.path = newPath;
}
public async Task Uninstall(Installation installation, CancellationToken cancellation = default)
{
await Delete(installation.path, cancellation);
}
public async Task Run(Installation installation, IEnumerable<string> arguments, bool child)
{
if (!child) {
var cmd = new System.Diagnostics.Process();
cmd.StartInfo.FileName = "/usr/bin/open";
cmd.StartInfo.Arguments = $"-a \"{installation.executable}\" -n --args {string.Join(" ", arguments)}";
Logger.LogInformation($"$ {cmd.StartInfo.FileName} {cmd.StartInfo.Arguments}");
cmd.Start();
await cmd.WaitForExitAsync();
} else {
if (!arguments.Contains("-logFile")) {
arguments = arguments.Append("-logFile").Append("-");
}
var cmd = new System.Diagnostics.Process();
cmd.StartInfo.FileName = installation.executable;
cmd.StartInfo.Arguments = string.Join(" ", arguments);
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.RedirectStandardError = true;
cmd.EnableRaisingEvents = true;
cmd.OutputDataReceived += (s, a) => {
if (a.Data == null) return;
Logger.LogInformation(a.Data);
};
cmd.ErrorDataReceived += (s, a) => {
if (a.Data == null) return;
Logger.LogError(a.Data);
};
cmd.Start();
cmd.BeginOutputReadLine();
cmd.BeginErrorReadLine();
await cmd.WaitForExitAsync(); // Let stdout and stderr flush
Logger.LogInformation($"Unity exited with code {cmd.ExitCode}");
Environment.Exit(cmd.ExitCode);
}
}
// -------- Helpers --------
ILogger Logger = UnityInstaller.CreateLogger<MacPlatform>();
bool? isRoot;
string pwd;
VersionMetadata installing;
string installationPaths;
string upgradeOriginalPath;
bool movedExisting;
bool installedEditor;
/// <summary>
/// Get the path to the Unity executable inside the App bundle.
/// </summary>
string ExecutableFromAppPath(string appPath)
{
var executable = Path.Combine(appPath, "Contents", "MacOS", "Unity");
if (!File.Exists(executable)) {
Logger.LogError("Could not find Unity executable at path: " + executable);
return null;
}
return executable;
}
/// <summary>
/// Install a PKG package using the `installer` command.
/// </summary>
async Task InstallPkg(string filePath, CancellationToken cancellation = default)
{
var platform = await GetCurrentPlatform();
if (platform == CachePlatform.macOSIntel) {
var result = await Sudo("/usr/sbin/installer", $"-pkg \"{filePath}\" -target \"{INSTALL_VOLUME}\" -verbose", cancellation);
if (result.exitCode != 0) {
throw new Exception($"ERROR: {result.error}");
}
} else {
// Make sure we run the arm64 version of the installer
// Otherwise the install script will fail with
// "Unity for Apple silicon can't be installed on this computer"
var result = await Sudo("/usr/bin/arch", $"-arm64 /usr/sbin/installer -pkg \"{filePath}\" -target \"{INSTALL_VOLUME}\" -verbose", cancellation);
if (result.exitCode != 0) {
throw new Exception($"ERROR: {result.error}");
}
}
}
/// <summary>
/// Install a DMG package by mounting it and copying the app bundle.
/// </summary>
async Task InstallDmg(string filePath, CancellationToken cancellation = default)
{
// Mount DMG
var result = await Command.Run("/usr/bin/hdiutil", $"attach -nobrowse -mountrandom /tmp \"{filePath}\"", cancellation: cancellation);
if (result.exitCode != 0) {
throw new Exception($"ERROR: {result.error}");
}
var matches = MOUNT_POINT_REGEX.Matches(result.output);
if (matches.Count == 0) {
throw new Exception($"Failed to find mountpoint in hdiutil output: {result.output} / {result.error}");
} else if (matches.Count > 1) {
throw new Exception("Ambiguous mount points in hdiutil output (DMG contains multiple volumes?)");
}
var mountPoint = matches[0].Groups[1].Value;
if (!Directory.Exists(mountPoint)) {
throw new Exception("Mount point does not exist: " + mountPoint);
}
try {
// Find and copy app bundle
var apps = Directory.GetDirectories(mountPoint, "*.app");
if (apps.Length == 0) {
throw new Exception("No app bundles found in DMG.");
}
var targetDir = Path.Combine(INSTALL_VOLUME, "Applications");
foreach (var app in apps) {
var dst = Path.Combine(targetDir, Path.GetFileName(app));
if (Directory.Exists(dst) || File.Exists(dst)) {
await Delete(dst, cancellation);
}
await Copy(app, dst, cancellation);
}
} finally {
// Unmount dmg
result = await Command.Run("/usr/bin/hdiutil", $"detach \"{mountPoint}\"", cancellation: cancellation);
if (result.exitCode != 0) {
Logger.LogError($"ERROR: {result.error}");
}
}
}
/// <summary>
/// Copy a file without doing anything with it.
/// </summary>
async Task InstallFile(string filePath, string destination, CancellationToken cancellation = default)
{
if (string.IsNullOrEmpty(destination)) {
throw new Exception($"Cannot install {filePath}: File packages must have a destination set.");
}
var targetDir = destination.Replace("{UNITY_PATH}", INSTALL_PATH);
var dst = Path.Combine(targetDir, Path.GetFileName(filePath));
await Copy(filePath, dst, cancellation);
}
/// <summary>
/// Unpack a Zip file to the given destination.
/// </summary>
async Task InstallZip(string filePath, string destination, string renameFrom, string renameTo, CancellationToken cancellation = default)
{
if (string.IsNullOrEmpty(destination)) {
throw new Exception($"Cannot install {filePath}: Zip packages must have a destination set.");
}
var target = destination.Replace("{UNITY_PATH}", INSTALL_PATH);
var retryWithRoot = false;
(int exitCode, string output, string error) result;
try {
if (!Directory.Exists(target)) {
Directory.CreateDirectory(target);
}
result = await Command.Run("/usr/bin/unzip", $"-o -d \"{target}\" \"{filePath}\"", cancellation: cancellation);
if (result.exitCode != 0) {
throw new Exception($"ERROR: {result.error}");
}
} catch (Exception e) {
Logger.LogInformation($"Unzip as user failed, trying as root... ({e.Message})");
retryWithRoot = true;
}
if (retryWithRoot) {
result = await Sudo("/bin/mkdir", $"-p \"{target}\"", cancellation);
if (result.exitCode != 0) {
throw new Exception($"ERROR: {result.error}");
}
result = await Sudo("/usr/bin/unzip", $"-o -d \"{target}\" \"{filePath}\"", cancellation);
if (result.exitCode != 0) {
throw new Exception($"ERROR: {result.error}");
}
}
// Fix permissions, some files are not readable if installed with root
await Sudo("/bin/chmod", $"-R o+rX \"{target}\"", cancellation);
if (!string.IsNullOrEmpty(renameFrom) && !string.IsNullOrEmpty(renameTo)) {
var from = renameFrom.Replace("{UNITY_PATH}", INSTALL_PATH);
var to = renameTo.Replace("{UNITY_PATH}", INSTALL_PATH);
if (!Directory.Exists(from) && !File.Exists(from)) {
throw new Exception($"{filePath}: renameFrom path does not exist: {from}");
}
await Move(from, to, cancellation);
}
}
/// <summary>
/// Find a unique path for a new installation.
/// Tries paths in installationPaths until one is unused, falls back to adding
/// increasing numbers to the the last path in installationPaths or using the
/// default installation path.
/// </summary>
/// <param name="version">Unity version being installed</param>
/// <param name="installationPaths">Paths string (see <see cref="Configuration.installPathMac"/></param>
string GetUniqueInstallationPath(UnityVersion version, string installationPaths)
{
string expanded = null;
if (!string.IsNullOrEmpty(installationPaths)) {
var comparison = StringComparison.OrdinalIgnoreCase;
var paths = installationPaths.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var path in paths) {
expanded = path.Trim();
expanded = Helpers.Replace(expanded, "{major}", version.major.ToString(), comparison);
expanded = Helpers.Replace(expanded, "{minor}", version.minor.ToString(), comparison);
expanded = Helpers.Replace(expanded, "{patch}", version.patch.ToString(), comparison);
expanded = Helpers.Replace(expanded, "{type}", ((char)version.type).ToString(), comparison);
expanded = Helpers.Replace(expanded, "{build}", version.build.ToString(), comparison);
expanded = Helpers.Replace(expanded, "{hash}", version.hash, comparison);
if (!Directory.Exists(expanded)) {
return expanded;
}
}
}
if (expanded != null) {
return Helpers.GenerateUniqueFileName(expanded);
} else {
return Helpers.GenerateUniqueFileName(INSTALL_PATH);
}
}
/// <summary>
/// Move a directory, first trying directly and falling back to `sudo mv` if that fails.
/// </summary>
async Task Move(string sourcePath, string newPath, CancellationToken cancellation)
{
var baseDst = Path.GetDirectoryName(newPath);
try {
if (!Directory.Exists(baseDst)) {
Directory.CreateDirectory(baseDst);
}
Directory.Move(sourcePath, newPath);
return;
} catch (Exception e) {
Logger.LogInformation($"Move as user failed, trying as root... ({e.Message})");
}
// Try again with admin privileges
var result = await Sudo("/bin/mkdir", $"-p \"{baseDst}\"", cancellation);
if (result.exitCode != 0) {
throw new Exception($"ERROR: {result.error}");
}
result = await Sudo("/bin/mv", $"\"{sourcePath}\" \"{newPath}\"", cancellation);
if (result.exitCode != 0) {
throw new Exception($"ERROR: {result.error}");
}
}
/// <summary>
/// Copy a directory, first trying as the current user and using sudo if that fails.
/// </summary>
async Task Copy(string sourcePath, string newPath, CancellationToken cancellation)
{
var baseDst = Path.GetDirectoryName(newPath);
(int exitCode, string output, string error) result;
try {
result = await Command.Run("/bin/mkdir", $"-p \"{baseDst}\"", cancellation: cancellation);
if (result.exitCode != 0) {
throw new Exception($"ERROR: {result.error}");
}
result = await Command.Run("/bin/cp", $"-R \"{sourcePath}\" \"{newPath}\"", cancellation: cancellation);
if (result.exitCode != 0) {
throw new Exception($"ERROR: {result.error}");
}
return;
} catch (Exception e) {
Logger.LogInformation($"Copy as user failed, trying as root... ({e.Message})");
}
// Try again with admin privileges
result = await Sudo("/bin/mkdir", $"-p \"{baseDst}\"", cancellation);
if (result.exitCode != 0) {
throw new Exception($"ERROR: {result.error}");
}
result = await Sudo("/bin/mv", $"\"{sourcePath}\" \"{newPath}\"", cancellation);
if (result.exitCode != 0) {
throw new Exception($"ERROR: {result.error}");
}
}
/// <summary>
/// Delete a directory, first trying directly and falling back to `sudo rm` if that fails.
/// </summary>
async Task Delete(string deletePath, CancellationToken cancellation = default)
{
// First try deleting the installation directly
try {
Directory.Delete(deletePath, true);
return;
} catch (Exception e) {
Logger.LogInformation($"Deleting as user failed, trying as root... ({e.Message})");
}
// Try again with admin privileges
var result = await Sudo("/bin/rm", $"-rf \"{deletePath}\"", cancellation);
if (result.exitCode != 0) {
throw new Exception($"ERROR: {result.error}");
}
}
/// <summary>
/// Check if the program is running as root.
/// </summary>
async Task<bool> CheckIsRoot(bool withSudo, CancellationToken cancellation)
{
var command = "/usr/bin/id";
var arguments = "-u";
(int exitCode, string output, string error) result;
if (withSudo) {
result = await Sudo(command, arguments, cancellation: cancellation);
if (result.exitCode != 0) {
if (result.exitCode == 1 && result.error.Contains("Sorry, try again.")) {
return false;
} else {
throw new Exception($"ERROR: {result.error}");
}
}
} else {
result = await Command.Run(command, arguments, cancellation: cancellation);
if (result.exitCode != 0) {
throw new Exception($"ERROR: {result.error}");
}
}
int id;
if (!int.TryParse(result.output, out id)) {
throw new Exception($"ERROR: failed to run id, cannot parse output: {result.output} / {result.error}");
}
return (id == 0);
}
/// <summary>
/// Run a command as root using sudo.
/// This will prompt the user for the password the first time it's run.
/// If the user is already root, this is equivalent to calling the command directly.
/// </summary>
async Task<(int exitCode, string output, string error)> Sudo(string command, string arguments, CancellationToken cancellation)
{
if (isRoot == null) {
isRoot = await CheckIsRoot(false, cancellation);
}
if (isRoot == true) {
// Run the command directly if we already are root
return await Command.Run(command, arguments, cancellation: cancellation);
} else {
if (pwd == null) {
await PromptForPasswordIfNecessary(cancellation);
}
// Run command using sudo
return await Command.Run("sudo", "-Sk " + command + " " + arguments, pwd + "\n", cancellation);
}
}
}
}