-
Notifications
You must be signed in to change notification settings - Fork 5
/
ProgramUtils.cs
382 lines (357 loc) · 14.9 KB
/
ProgramUtils.cs
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
// Copyright Bastian Eicher et al.
// Licensed under the GNU Lesser Public License
using System.Diagnostics;
using System.Reflection;
using System.Security;
using NanoByte.Common.Native;
using NanoByte.Common.Net;
using NanoByte.Common.Streams;
using NanoByte.Common.Values;
using ZeroInstall.Commands.Desktop;
using ZeroInstall.DesktopIntegration;
using ZeroInstall.Services.Executors;
using ZeroInstall.Services.Solvers;
using ZeroInstall.Store.Implementations;
using ZeroInstall.Store.Trust;
namespace ZeroInstall.Commands;
/// <summary>
/// Provides utility methods for application entry points.
/// </summary>
public static class ProgramUtils
{
/// <summary>
/// The current UI language; <c>null</c> to use system default.
/// </summary>
/// <remarks>This value is only used on Windows and is stored in the Registry. For non-Windows platforms use the <c>LC_*</c> environment variables instead.</remarks>
public static CultureInfo? UILanguage
{
get
{
if (!WindowsUtils.IsWindows) return null;
string? language = RegistryUtils.GetSoftwareString("Zero Install", "Language", machineWide: false)
?? RegistryUtils.GetSoftwareString("Zero Install", "Language", machineWide: true);
if (string.IsNullOrEmpty(language)) return null;
try
{
return Languages.FromString(language);
}
catch (ArgumentException ex)
{
Log.Warn($"Failed to parse '{language}' as an ISO language code", ex);
return null;
}
}
set
{
if (WindowsUtils.IsWindows)
RegistryUtils.SetSoftwareString("Zero Install", "Language", value?.ToString() ?? "");
}
}
/// <summary>
/// Common initialization code to be called by every Zero Install executable right after startup.
/// </summary>
public static void Init()
{
AppMutex.Create(ZeroInstallEnvironment.MutexName());
AppMutex.Create(ZeroInstallEnvironment.LegacyMutexName());
if (AppMutex.Probe(ZeroInstallEnvironment.UpdateMutexName()) || AppMutex.Probe(ZeroInstallEnvironment.LegacyUpdateMutexName())) Environment.Exit(999);
ReplaceMissingRuntimeConfig();
if (UILanguage != null) Languages.SetUI(UILanguage);
ProcessUtils.SanitizeEnvironmentVariables();
NetUtils.ApplyProxy();
ServicePointManager.DefaultConnectionLimit = 16;
}
[Conditional("NETFRAMEWORK")]
private static void ReplaceMissingRuntimeConfig()
{
string path = Assembly.GetEntryAssembly()!.Location + ".config";
if (File.Exists(path)) return;
Log.Info($"Replacing missing runtime config file: {path}");
try
{
typeof(ProgramUtils).CopyEmbeddedToFile("0install.exe.config", path);
}
#region Error handling
catch (Exception ex)
{
Log.Error("Failed to replace missing runtime config file", ex);
}
#endregion
}
/// <summary>
/// Creates a <see cref="ProcessStartInfo"/> for launching an instance of the 0install command-line interface.
/// </summary>
public static ProcessStartInfo? CliStartInfo(params string[] arguments)
{
try
{
return ProcessUtils.Assembly("0install", arguments);
}
catch (FileNotFoundException)
{
return null;
}
}
/// <summary>
/// Creates a <see cref="ProcessStartInfo"/> for launching an instance of the 0install graphical interface.
/// </summary>
public static ProcessStartInfo? GuiStartInfo(params string[] arguments)
{
try
{
return WindowsUtils.IsWindows && WindowsUtils.IsGuiSession
? ProcessUtils.Assembly("0install-win", arguments)
: null;
}
catch (FileNotFoundException)
{
return null;
}
}
private const string
RegKeyFSPolicyMachine = @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem",
RegKeyFSPolicyUser = @"HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy Objects\{B0D05113-7B6B-4D69-81E2-8E8836775C9C}Machine\System\CurrentControlSet\Control\FileSystem",
RegValueNameLongPaths = "LongPathsEnabled";
/// <summary>A command-line argument used to indicate that the program was relaunched with admin rights.</summary>
private const string AsAdminIndicatorArg = "--as-admin";
/// <summary>A command-line argument used to indicate that the program was relaunched as a freshly deployed instance.</summary>
private const string DeployedIndicatorArg = "--deployed";
/// <summary>
/// Parses command-line arguments and performs the indicated action. Performs error handling.
/// </summary>
/// <param name="exeName">The name of the executable to use as a reference in help messages and self-invocation.</param>
/// <param name="args">The arguments to be processed.</param>
/// <param name="handler">A callback object used when the user needs to be asked questions or informed about download and IO tasks.</param>
/// <returns>The exit status code to end the process with. Cast to <see cref="int"/> to return from a Main method.</returns>
public static ExitCode Run(string exeName, string[] args, ICommandHandler handler)
{
#region Sanity checks
if (string.IsNullOrEmpty(exeName)) throw new ArgumentNullException(nameof(exeName));
if (args == null) throw new ArgumentNullException(nameof(args));
if (handler == null) throw new ArgumentNullException(nameof(handler));
#endregion
if (args is [AsAdminIndicatorArg or DeployedIndicatorArg, ..])
args = args.Skip(1).ToArray();
try
{
var command = CliCommand.CreateAndParse(args, handler);
return command.Execute();
}
#region Error handling
catch (OperationCanceledException)
{
return ExitCode.UserCanceled;
}
catch (NeedsGuiException) when (GuiStartInfo(args) is {} startInfo)
{
Log.Info("Switching to GUI");
handler.DisableUI();
try
{
return (ExitCode)startInfo.Run();
}
catch (IOException ex2)
{
handler.Error(ex2);
return ExitCode.IOError;
}
catch (NotAdminException ex2)
{
handler.Error(ex2);
return ExitCode.AccessDenied;
}
}
catch (NotAdminException) when (WindowsUtils.HasUac
&& args.FirstOrDefault() != AsAdminIndicatorArg
&& GuiStartInfo([AsAdminIndicatorArg, ..args]) is {} startInfo)
{
Log.Info("Elevating to admin");
handler.DisableUI();
try
{
return (ExitCode)startInfo.AsAdmin().Run();
}
catch (IOException ex2)
{
handler.Error(ex2);
return ExitCode.IOError;
}
catch (OperationCanceledException)
{
return ExitCode.UserCanceled;
}
}
catch (ConflictException ex)
{
handler.Error(ex);
return ExitCode.Conflict;
}
catch (UnsuitableInstallBaseException ex) when (WindowsUtils.IsWindows && args.FirstOrDefault() != DeployedIndicatorArg)
{
Log.Info(ex.Message, ex);
try
{
return TryRunOtherInstance(exeName, args, handler, ex.NeedsMachineWide)
?? DeployAndRunOtherInstance(exeName, args, handler, ex.NeedsMachineWide);
}
catch (OperationCanceledException)
{
return ExitCode.UserCanceled;
}
catch (IOException ex2)
{
handler.Error(ex2);
return ExitCode.IOError;
}
catch (NotAdminException ex2)
{
handler.Error(ex2);
return ExitCode.AccessDenied;
}
}
catch (OptionException ex)
{
string message = ex.Message + Environment.NewLine + string.Format(Resources.TryHelp, $"{exeName} --help");
if (!string.IsNullOrEmpty(ex.OptionName)) message = ex.OptionName + ": " + message;
handler.Error(new OptionException(message, ex.OptionName));
return ExitCode.InvalidArguments;
}
catch (FormatException ex)
{
handler.Error(ex);
return ExitCode.InvalidArguments;
}
catch (WebException ex)
{
handler.Error(ex);
return ExitCode.WebError;
}
catch (NotSupportedException ex)
{
handler.Error(ex);
return ExitCode.NotSupported;
}
catch (PathTooLongException ex) when (
WindowsUtils.IsWindows10Redstone &&
RegistryUtils.GetDword(RegKeyFSPolicyUser, RegValueNameLongPaths, defaultValue: RegistryUtils.GetDword(RegKeyFSPolicyMachine, RegValueNameLongPaths)) != 1)
{
Debug.Assert(WindowsUtils.IsWindows);
try
{
string message = ex.Message + @" " + Resources.SuggestLongPath;
if (handler.Ask(message + @" " + Resources.AskTryNow, defaultAnswer: false, alternateMessage: message))
{
RegistryUtils.SetDword(WindowsUtils.IsAdministrator ? RegKeyFSPolicyMachine : RegKeyFSPolicyUser, RegValueNameLongPaths, 1);
return (ExitCode)ProcessUtils.Assembly(exeName, args).Run();
}
else
{
handler.Error(ex);
return ExitCode.IOError;
}
}
catch (OperationCanceledException)
{
return ExitCode.UserCanceled;
}
catch (PlatformNotSupportedException ex2)
{
handler.Error(ex2);
return ExitCode.NotSupported;
}
catch (IOException ex2)
{
handler.Error(ex2);
return ExitCode.IOError;
}
catch (NotAdminException ex2)
{
handler.Error(ex2);
return ExitCode.AccessDenied;
}
}
catch (IOException ex)
{
handler.Error(ex);
return ExitCode.IOError;
}
catch (Exception ex) when (ex is UnauthorizedAccessException or SecurityException)
{
handler.Error(ex);
return ExitCode.AccessDenied;
}
catch (InvalidDataException ex)
{
handler.Error(ex);
return ExitCode.InvalidData;
}
catch (SignatureException ex)
{
handler.Error(ex);
return ExitCode.InvalidSignature;
}
catch (DigestMismatchException ex)
{
Log.Info(ex.LongMessage);
handler.Error(ex);
return ExitCode.DigestMismatch;
}
catch (SolverException ex)
{
handler.Error(ex);
return ExitCode.SolverError;
}
catch (ExecutorException ex)
{
handler.Error(ex);
return ExitCode.ExecutorError;
}
#endregion
finally
{
handler.CloseUI();
}
}
/// <summary>
/// Tries to run a command in another instance of Zero Install deployed on this system.
/// </summary>
/// <param name="exeName">The name of the executable to call in the target instance.</param>
/// <param name="args">The arguments to pass to the target instance.</param>
/// <param name="handler">A callback object used when the user needs to be asked questions or informed about download and IO tasks.</param>
/// <param name="needsMachineWide"><c>true</c> if a machine-wide install location is required; <c>false</c> if a user-specific location will also do.</param>
/// <returns>The exit code returned by the other instance; <c>null</c> if no other instance could be found.</returns>
/// <exception cref="IOException">There was a problem launching the target instance.</exception>
/// <exception cref="NotAdminException">The target process requires elevation.</exception>
private static ExitCode? TryRunOtherInstance(string exeName, string[] args, ICommandHandler handler, bool needsMachineWide)
{
if (ZeroInstallDeployment.FindOther(needsMachineWide) is {} installLocation)
{
Log.Info($"Redirecting to Zero Install instance at: {installLocation}");
handler.DisableUI();
return (ExitCode)ProcessUtils.Assembly(Path.Combine(installLocation, exeName), args).Run();
}
else return null;
}
/// <summary>
/// Deploys a new instance of Zero Install instance and runs a command in it.
/// </summary>
/// <param name="exeName">The name of the executable to call in the target instance.</param>
/// <param name="args">The arguments to pass to the target instance.</param>
/// <param name="handler">A callback object used when the user needs to be asked questions or informed about download and IO tasks.</param>
/// <param name="machineWide"><c>true</c> to deploy to a machine-wide location; <c>false</c> to deploy to a user-specific location.</param>
/// <returns>The exit code returned by the other instance; <c>null</c> if no other instance could be found.</returns>
/// <exception cref="IOException">There was a problem launching the target instance.</exception>
/// <exception cref="NotAdminException">The target process requires elevation.</exception>
private static ExitCode DeployAndRunOtherInstance(string exeName, string[] args, ICommandHandler handler, bool machineWide)
{
Log.Info("Deploying new Zero Install instance to redirect to");
var deployResult = Run(exeName,
machineWide
? [Self.Name, Self.Deploy.Name, "--library", "--machine"]
: [Self.Name, Self.Deploy.Name, "--library"],
handler);
if (deployResult != ExitCode.OK) return deployResult;
return TryRunOtherInstance(exeName, [DeployedIndicatorArg, ..args], handler, machineWide)
?? throw new IOException("Unable to find newly deployed Zero Install instance.");
}
}