-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
456 lines (407 loc) · 18.2 KB
/
Program.cs
File metadata and controls
456 lines (407 loc) · 18.2 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
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Spectre.Console;
using System.Diagnostics;
using System.Security.Principal;
using System.Text;
using System.Text.Json;
using ZapretCLI.Core.Interfaces;
using ZapretCLI.Core.Logging;
using ZapretCLI.Core.Managers;
using ZapretCLI.Core.Services;
using ZapretCLI.Models;
using ZapretCLI.UI;
namespace ZapretCLI
{
class Program
{
public static ServiceProvider ServiceProvider;
private static System.Timers.Timer _statusTimer;
private static ILoggerService _logger;
private static CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
static async Task Main(string[] args)
{
try
{
if (IsAdministrator())
{
ConfigureMinimalLogger();
AppDomain.CurrentDomain.UnhandledException += (s, e) =>
{
var exception = e.ExceptionObject as Exception;
Log.Fatal(exception, "Unhandled exception occurred");
};
TaskScheduler.UnobservedTaskException += (s, e) =>
{
Log.Error(e.Exception, "Unobserved task exception");
e.SetObserved();
};
}
// OS and administrator rights checks
if (!await InitializeApplicationAsync(args))
return;
// Setting up a DI container
ServiceProvider = ConfigureServices();
await RunApplicationAsync(args);
}
finally
{
DisposeResources();
}
}
private static void ConfigureMinimalLogger()
{
var appPath = AppDomain.CurrentDomain.BaseDirectory;
var logsPath = Path.Combine(appPath, "logs");
Directory.CreateDirectory(logsPath);
var logPath = Path.Combine(logsPath, $"zapret_{DateTime.Now:yyyyMMdd}.log");
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.File(
path: logPath,
formatter: new CustomLogFormatter(),
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 7)
.CreateLogger();
}
private static void DisposeResources()
{
try
{
MainMenu.Shutdown();
var updateService = ServiceProvider.GetRequiredService<IUpdateService>();
var profileService = ServiceProvider.GetRequiredService<IProfileService>();
var processService = ServiceProvider.GetRequiredService<IProcessService>();
var localizationService = ServiceProvider.GetRequiredService<ILocalizationService>();
var configService = ServiceProvider.GetRequiredService<IConfigService>();
updateService.Dispose();
profileService.Dispose();
processService.Dispose();
localizationService.Dispose();
configService.Dispose();
_statusTimer?.Stop();
_statusTimer?.Dispose();
_cancellationTokenSource.Cancel();
_cancellationTokenSource.Dispose();
ServiceProvider?.Dispose();
Log.CloseAndFlush();
}
catch
{
//
}
}
private static ServiceProvider ConfigureServices()
{
var services = new ServiceCollection();
var appPath = AppDomain.CurrentDomain.BaseDirectory;
// Registration of services
services = SetupLogger(services);
services.AddSingleton<IFileSystemService, FileSystemService>();
services.AddSingleton<AppConfig>();
services.AddSingleton<IConfigService, ConfigService>(sp => new ConfigService(appPath, sp.GetRequiredService<ILoggerService>()));
services.AddSingleton<ILocalizationService, LocalizationService>(sp =>
new LocalizationService(
sp.GetRequiredService<IConfigService>(),
sp.GetRequiredService<IFileSystemService>(),
sp.GetRequiredService<ILoggerService>(),
appPath
));
// HttpClient
services.AddHttpClient();
// Basic services
services.AddSingleton<IProcessService, ProcessService>(sp =>
{
var fileSystem = sp.GetRequiredService<IFileSystemService>();
var configuration = sp.GetRequiredService<IConfigService>().GetConfig();
var logger = sp.GetRequiredService<ILoggerService>();
return new ProcessService(fileSystem, configuration, appPath, logger);
});
services.AddSingleton<IStatusService, StatusService>(sp =>
{
var localizationService = sp.GetRequiredService<ILocalizationService>();
var logger = sp.GetRequiredService<ILoggerService>();
return new StatusService(appPath, localizationService, logger);
});
services.AddSingleton<IProfileService, ProfileService>(sp =>
{
var localizationService = sp.GetRequiredService<ILocalizationService>();
var logger = sp.GetRequiredService<ILoggerService>();
return new ProfileService(appPath, localizationService, logger);
});
services.AddSingleton<ITestService>(sp =>
{
return new TestService(
sp.GetRequiredService<IZapretManager>(),
sp.GetRequiredService<ILocalizationService>(),
sp.GetRequiredService<ILoggerService>(),
sp.GetRequiredService<IHttpClientFactory>(),
sp.GetRequiredService<IProfileService>()
);
});
services.AddSingleton<IZapretManager, ZapretManager>(sp =>
{
var processService = sp.GetRequiredService<IProcessService>();
var statusService = sp.GetRequiredService<IStatusService>();
var profileService = sp.GetRequiredService<IProfileService>();
var localizationService = sp.GetRequiredService<ILocalizationService>();
var configService = sp.GetRequiredService<IConfigService>();
var logger = sp.GetRequiredService<ILoggerService>();
return new ZapretManager(appPath, processService, statusService, profileService, localizationService, configService, logger);
});
services.AddSingleton<IUpdateService, UpdateService>(sp =>
{
return new UpdateService(appPath, sp.GetRequiredService<IProfileService>(), sp.GetRequiredService<IZapretManager>(), sp.GetRequiredService<ILocalizationService>(), sp.GetRequiredService<ILoggerService>());
});
services.AddSingleton<IDiagnosticsService, DiagnosticsService>(sp =>
{
return new DiagnosticsService(
sp.GetRequiredService<ILocalizationService>(),
sp.GetRequiredService<ILoggerService>(),
sp.GetRequiredService<IFileSystemService>(),
appPath
);
});
services.AddSingleton<IExportService, ExportService>(sp =>
{
var fileSystemService = sp.GetRequiredService<IFileSystemService>();
var statusService = sp.GetRequiredService<IStatusService>();
var profileService = sp.GetRequiredService<IProfileService>();
var configService = sp.GetRequiredService<IConfigService>();
var zapretManager = sp.GetRequiredService<IZapretManager>();
var localizationService = sp.GetRequiredService<ILocalizationService>();
var logger = sp.GetRequiredService<ILoggerService>();
return new ExportService(appPath, fileSystemService, statusService, profileService, configService, zapretManager, localizationService, logger);
});
return services.BuildServiceProvider();
}
private static ServiceCollection SetupLogger(ServiceCollection services)
{
var appPath = AppDomain.CurrentDomain.BaseDirectory;
var logsPath = Path.Combine(appPath, "logs");
Directory.CreateDirectory(logsPath);
var logPath = Path.Combine(logsPath, $"zapret_{DateTime.Now:yyyyMMdd}.log");
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.File(
path: logPath,
formatter: new CustomLogFormatter(),
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 7)
.CreateLogger();
services.AddLogging(loggingBuilder =>
{
loggingBuilder.ClearProviders();
loggingBuilder.AddSerilog(Log.Logger, dispose: true);
});
services.AddSingleton<ILoggerService, LoggerService>();
return services;
}
private static async Task<bool> InitializeApplicationAsync(string[] args)
{
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
{
AnsiConsole.MarkupLine($"[{ConsoleUI.redName}]Unfortunately, it currently only works on Windows...[/] [{ConsoleUI.greyName}]:([/]");
return false;
}
if (!IsAdministrator())
{
AnsiConsole.MarkupLine($"[{ConsoleUI.redName}]Administrator rights are required! Restarting...[/]");
await Task.Delay(250);
RestartAsAdmin(args);
return false;
}
Console.OutputEncoding = Encoding.UTF8;
// Kill existing processes
KillProcessByName("winws.exe");
return true;
}
private static void InitializeListFiles()
{
var listsPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "lists");
Directory.CreateDirectory(listsPath);
var requiredFiles = new[]
{
"list-general.txt",
"list-general-user.txt",
"list-exclude.txt",
"list-exclude-user.txt",
"ipset-exclude.txt",
"ipset-exclude-user.txt"
};
foreach (var fileName in requiredFiles)
{
var filePath = Path.Combine(listsPath, fileName);
if (!File.Exists(filePath))
{
try
{
File.WriteAllText(filePath, string.Empty);
_logger.LogInformation($"Created empty list file: {fileName}");
}
catch (Exception ex)
{
_logger.LogError($"Failed to create list file {fileName}", ex);
}
}
}
}
private static async Task RunApplicationAsync(string[] args)
{
Stopwatch sp = Stopwatch.StartNew();
// Initialization
Console.Title = $"Zapret CLI - v.{MainMenu.version}";
_logger = ServiceProvider.GetRequiredService<ILoggerService>();
_logger.LogInformation($"========================================");
_logger.LogInformation($"Zapret CLI - v.{MainMenu.version}");
var runId = Guid.NewGuid().ToString("N");
_logger.LogInformation($"Session: {runId}");
_logger.LogInformation($"Process ID: {Environment.ProcessId}, Thread ID: {Thread.CurrentThread.ManagedThreadId}");
_logger.LogInformation($"Launch arguments: {JsonSerializer.Serialize(args)}");
_logger.LogInformation($"Working directory: {Environment.CurrentDirectory}");
_logger.LogInformation($"OS: {System.Runtime.InteropServices.RuntimeInformation.OSDescription}");
_logger.LogInformation($"Host: {Environment.MachineName}, User: {Environment.UserName}");
_logger.LogInformation($".NET runtime: {Environment.Version}");
_logger.LogInformation($"Initializing...");
InitializeListFiles();
var zapretManager = ServiceProvider.GetRequiredService<IZapretManager>();
var updateService = ServiceProvider.GetRequiredService<IUpdateService>();
AnsiConsole.MarkupLine($"[{ConsoleUI.greenName}]{ServiceProvider.GetRequiredService<ILocalizationService>().GetString("checking_for_updates")}[/]");
_logger.LogInformation($"Initializing ZapretManager...");
await zapretManager.InitializeAsync();
// Run update checks
try
{
_logger.LogInformation($"Checking for CLI and Zapret updates...");
await Task.Run(async () =>
{
await updateService.CheckForUpdatesAsync();
await updateService.CheckForCliUpdatesAsync();
}, _cancellationTokenSource.Token);
}
catch (OperationCanceledException)
{
_logger.LogWarning("Update checks were canceled");
}
catch (Exception ex)
{
_logger.LogError("Update checks failed", ex);
}
// Title timers setup
_statusTimer = new System.Timers.Timer(1000);
_statusTimer.Elapsed += async (sender, e) => await UpdateConsoleTitle(zapretManager);
_statusTimer.Start();
// Show main menu
sp.Stop();
_logger.LogInformation($"Initialization completed! ({sp.ElapsedMilliseconds}ms)");
await MainMenu.ShowAsync(ServiceProvider);
}
public static async Task UpdateProfiles()
{
await ServiceProvider.GetRequiredService<IUpdateService>().DownloadLatestReleaseAsync();
}
private static async Task UpdateConsoleTitle(IZapretManager zapretManager)
{
var localization = ServiceProvider.GetRequiredService<ILocalizationService>();
var isRunning = zapretManager.IsRunning();
var status = isRunning ? localization.GetString("running") : localization.GetString("stopped");
var stats = await zapretManager.GetStatusStatsAsync();
var hostsCount = stats.TotalHosts;
var ipsCount = stats.TotalIPs;
Console.Title = $"Zapret CLI - {status} • {localization.GetString("hosts")}: {hostsCount} • {localization.GetString("ips")}: {ipsCount}";
}
private static bool IsAdministrator()
{
try
{
using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
{
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
}
catch
{
return false;
}
}
private static void RestartAsAdmin(string[] args = null)
{
try
{
var currentProcess = Process.GetCurrentProcess();
var processStartInfo = new ProcessStartInfo
{
FileName = currentProcess.MainModule.FileName,
Verb = "runas",
UseShellExecute = true
};
// Correctly add arguments using ArgumentList
if (args != null)
{
foreach (var arg in args)
{
processStartInfo.ArgumentList.Add(arg);
}
}
Process.Start(processStartInfo);
Environment.Exit(0);
}
catch (Exception ex)
{
// Fallback to minimal logging if ServiceProvider is not available
try
{
if (ServiceProvider != null)
{
var localization = ServiceProvider?.GetRequiredService<ILocalizationService>();
AnsiConsole.MarkupLine($"[{ConsoleUI.redName}]{localization?.GetString("restart_as_admin_fail") ?? "Failed to restart as administrator"}: {ex.Message}[/]");
}
else
{
throw;
}
}
catch
{
AnsiConsole.MarkupLine($"[{ConsoleUI.redName}]Failed to restart as administrator: {ex.Message}[/]");
}
throw;
}
}
private static void KillProcessByName(string processName)
{
try
{
var processes = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(processName));
if (processes.Length == 0)
{
return;
}
foreach (var process in processes)
{
try
{
process.Kill();
process.WaitForExit(5000);
}
catch (Exception ex)
{
_logger.LogError($"Terminate process {processName} failed", ex);
AnsiConsole.MarkupLine($"[{ConsoleUI.redName}]Failed to terminate process {{0}}: {{1}}[/]", processName, ex.Message);
}
finally
{
process.Dispose();
}
}
}
catch (Exception ex)
{
_logger.LogError("Processes check failed", ex);
AnsiConsole.MarkupLine($"[{ConsoleUI.redName}]Error checking processes: {{0}}[/]", ex.Message);
}
}
}
}