-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.xaml.cs
More file actions
255 lines (233 loc) · 9.88 KB
/
Copy pathApp.xaml.cs
File metadata and controls
255 lines (233 loc) · 9.88 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
using System;
using System.IO;
using System.Diagnostics;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Libertix.Helpers;
using Libertix.Installation;
using Libertix.Models;
namespace Libertix
{
public partial class App : Application
{
private Mutex _singleInstanceMutex;
private bool _ownsSingleInstanceMutex;
public InstallationState InstallationState { get; } = new InstallationState();
public StartupOptions RuntimeOptions { get; private set; } = new StartupOptions();
public ApplicationBuild Build { get; } = ApplicationBuild.Current;
public FilepoolConfig Filepool { get; private set; } =
FilepoolConfig.ForBuild(ApplicationBuild.Current);
protected override async void OnStartup(StartupEventArgs e)
{
_singleInstanceMutex = new Mutex(
initiallyOwned: true,
name: @"Global\Libertix.Installation",
createdNew: out bool createdNew);
_ownsSingleInstanceMutex = createdNew;
if (!createdNew)
{
_singleInstanceMutex.Dispose();
_singleInstanceMutex = null;
MessageBox.Show(
Localization.GetBootstrapString(
"SingleInstanceRequired",
"Another Libertix instance is already running."),
"Libertix",
MessageBoxButton.OK,
MessageBoxImage.Warning);
Shutdown(3);
return;
}
ApplicationLogger.Initialize();
ApplicationLogger.Write("Libertix.exe startup.");
RegisterApplicationErrorLogging();
if (!TryConfigureStartupOptions(e.Args))
return;
if (!IsRunningAsAdministrator())
{
ApplicationLogger.Write("Startup refused: administrator privileges are missing.");
// This runs before the language dictionary is merged, so the
// message is resolved from the Windows UI language directly.
MessageBox.Show(
AdministratorRequiredMessage(),
"Libertix",
MessageBoxButton.OK,
MessageBoxImage.Error);
Shutdown(1);
return;
}
string recoveryStatePath = TryGetUefiRecoveryStatePath(RuntimeOptions);
if (!string.IsNullOrWhiteSpace(recoveryStatePath))
InstallationState.UefiRecoveryStatePath = recoveryStatePath;
if (!await ValidatePublishedVersionAsync())
return;
base.OnStartup(e);
}
private bool TryConfigureStartupOptions(string[] args)
{
if (!StartupOptions.TryParse(args, out StartupOptions options, out string error))
{
RejectInvalidStartupOptions(error);
return false;
}
FilepoolConfig filepool = FilepoolConfig.ForBuild(Build);
if (!string.IsNullOrWhiteSpace(options.FilepoolBaseUrlOverride) &&
!FilepoolConfig.TryCreate(
options.FilepoolBaseUrlOverride,
out filepool,
out error))
{
RejectInvalidStartupOptions(error);
return false;
}
Filepool = filepool;
RuntimeOptions = options;
ApplicationLogger.Write($"Filepool base URL: {Filepool.BaseUrl}");
ApplicationLogger.Write($"Build version: {Build.Version}; channel={Build.Channel}.");
if (!string.IsNullOrEmpty(options.DevelopmentSshStaticIpv4Address))
{
ApplicationLogger.Write(
"Development SSH/static network enabled for " +
options.DevelopmentSshStaticIpv4Address + "/" +
options.DevelopmentSshStaticIpv4PrefixLength + ".");
}
return true;
}
private async Task<bool> ValidatePublishedVersionAsync()
{
ReleaseCheckResult result = await ReleaseMetadataClient.CheckAsync(Build, Filepool);
if (result.IsCurrent)
return true;
if (!string.IsNullOrWhiteSpace(result.Error))
{
ApplicationLogger.Write("Published version check failed: " + result.Error);
MessageBox.Show(
string.Format(
Localization.GetBootstrapString(
"ReleaseCheckFailedMessage",
"Libertix could not verify the current published version: {0}"),
result.Error),
Localization.GetBootstrapString(
"ReleaseCheckFailedTitle",
"Libertix - version verification failed"),
MessageBoxButton.OK,
MessageBoxImage.Error);
Shutdown(4);
return false;
}
ApplicationLogger.Write(
$"Startup refused: build {Build.Version} is older than {result.LatestVersion}.");
MessageBoxResult response = MessageBox.Show(
string.Format(
Localization.GetBootstrapString(
"ReleaseUpdateRequiredMessage",
"This Libertix version ({0}) is no longer current. The latest version is {1}. " +
"Download the current release before continuing. Open the download page now?"),
Build.Version,
result.LatestVersion),
Localization.GetBootstrapString(
"ReleaseUpdateRequiredTitle",
"Libertix - update required"),
MessageBoxButton.YesNo,
MessageBoxImage.Warning);
if (response == MessageBoxResult.Yes)
{
try
{
Process.Start(result.ReleaseUrl);
}
catch (Exception exception) when (
exception is InvalidOperationException ||
exception is System.ComponentModel.Win32Exception)
{
ApplicationLogger.WriteException(
"The current release URL could not be opened.",
exception);
}
}
Shutdown(5);
return false;
}
private static void RejectInvalidStartupOptions(string error)
{
ApplicationLogger.Write("Startup refused: " + error);
MessageBox.Show(
string.Format(
Localization.GetBootstrapString(
"InvalidStartupOptionsMessage",
"Invalid startup option: {0}"),
error),
Localization.GetBootstrapString(
"InvalidStartupOptionsTitle",
"Libertix - invalid startup option"),
MessageBoxButton.OK,
MessageBoxImage.Error);
Current.Shutdown(2);
}
protected override void OnExit(ExitEventArgs e)
{
ApplicationLogger.Write($"Libertix.exe exit, code={e.ApplicationExitCode}.");
if (_singleInstanceMutex != null)
{
if (_ownsSingleInstanceMutex)
_singleInstanceMutex.ReleaseMutex();
_singleInstanceMutex.Dispose();
_singleInstanceMutex = null;
_ownsSingleInstanceMutex = false;
}
base.OnExit(e);
}
private void RegisterApplicationErrorLogging()
{
DispatcherUnhandledException += (_, args) =>
ApplicationLogger.WriteException("Unhandled WPF dispatcher exception.", args.Exception);
AppDomain.CurrentDomain.UnhandledException += (_, args) =>
ApplicationLogger.Write(
"Unhandled AppDomain exception." + Environment.NewLine +
(args.ExceptionObject?.ToString() ?? "No exception details."));
TaskScheduler.UnobservedTaskException += (_, args) =>
ApplicationLogger.WriteException("Unobserved task exception.", args.Exception);
}
private static string TryGetUefiRecoveryStatePath(StartupOptions options)
{
if (options == null ||
!options.UefiBootNextFailed ||
string.IsNullOrWhiteSpace(options.UefiRecoveryStatePath))
{
return null;
}
try
{
string path = Path.GetFullPath(options.UefiRecoveryStatePath);
string root = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
"Libertix",
"UefiRecovery") + Path.DirectorySeparatorChar;
if (path.StartsWith(root, StringComparison.OrdinalIgnoreCase) && File.Exists(path))
return path;
}
catch
{
// Invalid or inaccessible command-line paths are rejected like
// paths outside the protected recovery directory.
}
return null;
}
private static string AdministratorRequiredMessage()
{
return Localization.GetBootstrapString(
"AdministratorRequired",
"Libertix must be run as administrator.");
}
private static bool IsRunningAsAdministrator()
{
using (var identity = WindowsIdentity.GetCurrent())
{
var principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
}
}
}