-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathKmsServer.xaml.cs
527 lines (449 loc) · 19.9 KB
/
KmsServer.xaml.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
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
using HGM.Hotbird64.LicenseManager.Extensions;
using HGM.Hotbird64.Vlmcs;
using LicenseManager.Annotations;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace HGM.Hotbird64.LicenseManager
{
public struct ActivationInterval
{
public uint Interval;
public static bool TryParse(string intervalString, out uint interval)
{
interval = 0;
if (string.IsNullOrWhiteSpace(intervalString))
{
return false;
}
if (uint.TryParse(intervalString, NumberStyles.AllowThousands | NumberStyles.AllowTrailingSign, CultureInfo.CurrentCulture, out interval))
{
return true;
}
char multiplierChar = intervalString.ToUpperInvariant().Last();
string numberString = intervalString.Substring(0, intervalString.Length - 1);
if (!uint.TryParse(numberString, NumberStyles.AllowThousands | NumberStyles.AllowTrailingSign, CultureInfo.CurrentCulture, out uint rawValue))
{
return false;
}
switch (multiplierChar)
{
case 'S':
interval = (rawValue + 30) / 60;
break;
case 'M':
interval = rawValue;
break;
case 'H':
interval = rawValue * 60;
break;
case 'D':
interval = rawValue * 60 * 24;
break;
case 'W':
interval = rawValue * 60 * 24 * 7;
break;
default:
return false;
}
return true;
}
public static explicit operator uint(ActivationInterval activationInterval) => activationInterval.Interval;
public static explicit operator ActivationInterval(uint uInt) => new ActivationInterval { Interval = uInt };
}
public partial class KmsServer : INotifyPropertyChanged
{
private static readonly string nl = Environment.NewLine;
public static Random Rand = new Random(unchecked((int)DateTime.UtcNow.Ticks));
public ushort Port { get; private set; }
public static int Lcid = 1033; //1033 is EN-US (locale)
private static ObservableCollection<CsvlkItem> csvlks = new ObservableCollection<CsvlkItem>(KmsLists.CsvlkItemList.Where(c => c.Export).OrderBy(c => c.VlmcsdIndex));
public ObservableCollection<CsvlkItem> Csvlks
{
get => csvlks;
set
{
csvlks = value;
NotifyOfPropertyChange();
}
}
public IKmsProductCollection<AppItem> AppItems => KmsLists.AppItemList;
private static bool isRunning;
public bool IsRunning
{
get { return isRunning; }
private set
{
isRunning = value;
Dispatcher.InvokeAsync(() =>
{
ButtonStartStop.Content = (value ? "Stop" : "Start") + " Server";
TextBoxPort.IsEnabled = !value;
CheckBoxPreCharge.IsEnabled = !value;
if (!string.IsNullOrEmpty(TextBoxInfoText.Text))
{
TextBoxInfoText.AppendText(nl);
}
string statusText = value ? "started" : "stopped";
TextBoxInfoText.AppendText($"vlmcsd {Kms.EmulatorVersion}, API level {Kms.ApiVersion.Major}.{Kms.ApiVersion.Minor} has been {statusText}.");
TextBoxInfoText.ScrollToEnd();
if (value)
{
UseTap.IsEnabled = false;
try
{
if (!UseTap.IsChecked.Value)
{
return;
}
Version version = TapMirror.Start(TextBoxTapIp.Text, ((TapMirror.TapDevice)ComboBoxTap.Items[ComboBoxTap.SelectedIndex]).Name);
ComboBoxTap.IsEnabled = false;
TextBoxInfoText.AppendText($"{nl}TAP {version} device \"{ComboBoxTap.SelectionBoxItem}\" has been started.");
}
catch (Exception ex)
{
TextBoxInfoText.AppendText($"{nl}TAP device \"{ComboBoxTap.SelectionBoxItem}\" could not be started: {ex.Message}");
try
{
Kms.StopServer();
}
catch
{
/**/
}
}
}
else
{
TapMirror.Stop();
UseTap.IsEnabled = TapMirror.GetTapDevices().Any();
ComboBoxTap.IsEnabled = true;
foreach (AppItem appItem in KmsLists.AppItemList)
{
appItem.Reset();
}
}
});
}
}
public KmsServer(MainWindow parentWindow) : base(parentWindow)
{
InitializeComponent();
DataContext = this;
TopElement.LayoutTransform = Scaler;
TapMirror.TapDevice[] tapList = TapMirror.GetTapDevices().ToArray();
UseTap.IsChecked = UseTap.IsEnabled = tapList.Any();
ComboBoxTap.Visibility = UseTap.IsEnabled ? Visibility.Visible : Visibility.Collapsed;
if (UseTap.IsEnabled)
{
ComboBoxTap.ItemsSource = tapList;
ComboBoxTap.SelectedIndex = 0;
}
ProtocolVersion dllVersion = Kms.ApiVersion;
if (dllVersion < Kms.RequiredDllVersion)
{
MessageBox.Show
(
this,
$"libkms32.dll version {Kms.RequiredDllVersion} or greater required. You have version {dllVersion}.",
"Incorrect DLL version",
MessageBoxButton.OK, MessageBoxImage.Error
);
Loaded += (s, e) => Close();
return;
}
Title = $" KMS Server Powered By vlmcsd {Kms.EmulatorVersion}";
Closed += (s, e) =>
{
TapMirror.Stop();
try
{
Kms.StopServer();
}
catch (KmsException)
{
}
foreach (CsvlkItem csvlkItem in Csvlks)
{
csvlkItem.PropertyChanged -= CsvlkItem_PropertyChanged;
}
};
Loaded += (s, e) =>
{
Icon = this.GenerateImage(new Icons.KmsServerIcon(), 16, 16);
foreach (CsvlkItem csvlkItem in Csvlks)
{
csvlkItem.PropertyChanged += CsvlkItem_PropertyChanged;
}
};
}
private void CsvlkItem_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (!(sender is CsvlkItem csvlkItem))
{
return;
}
switch (e.PropertyName)
{
case nameof(csvlkItem.IsRandom):
if (csvlkItem.IsRandom)
{
KmsLists.GetRandomEPid(csvlkItem);
}
break;
}
}
[SuppressMessage("ReSharper", "PossibleInvalidOperationException")]
public int ProcessKmsRequest(IntPtr requestPtr, IntPtr responsePtr, IntPtr hwIdPtr, IntPtr clientIpAddressPtr)
{
KmsRequest request = (KmsRequest)Marshal.PtrToStructure(requestPtr, typeof(KmsRequest));
string clientIpAddress = Marshal.PtrToStringAnsi(clientIpAddressPtr);
KmsResponse response = new KmsResponse();
HwId hwId;
int result = 0;
CsvlkItem csvlkItem = Csvlks.SingleOrDefault(c => c.Activates.Select(a => a.Guid).Contains(request.KmsID)) ?? Csvlks[KmsLists.AppItemList[request.ID]?.VlmcsdIndex ?? 0];
AppItem appItem = KmsLists.AppItemList[request.ApplicationID] ?? KmsLists.AppItemList.SingleOrDefault(a => a.VlmcsdIndex == 0) ?? KmsLists.AppItemList.First();
Dispatcher.Invoke(() =>
{
try
{
hwId.Text = TextBoxHwId.Text;
}
catch (Exception ex)
{
TextBoxInfoText.AppendText(nl + ex.Message);
}
});
response.ClientMachineID = request.ClientMachineID;
response.TimeStamp = request.TimeStamp;
response.Version = request.Version;
bool allowUnknownProducts = false;
bool allowRetailAndBetaProducts = false;
bool checkTime = false;
Dispatcher.Invoke(() =>
{
response.KmsPid.Text = csvlkItem.EPid;
response.KmsPIDLen = (uint)(response.KmsPid.Text.Length + 1) << 1;
if (!ActivationInterval.TryParse(TextBoxVlActivation.Text, out response.VLActivationInterval))
{
response.VLActivationInterval = 120;
}
if (!ActivationInterval.TryParse(TextBoxVlRenewal.Text, out response.VLRenewalInterval))
{
response.VLRenewalInterval = 7 * 24 * 60;
}
allowUnknownProducts = CheckBoxAllowUnknownProducts.IsChecked.Value;
checkTime = CheckBoxCheckTime.IsChecked.Value;
allowRetailAndBetaProducts = CheckBoxAllowNonVl.IsChecked.Value;
});
try
{
KmsData.Lock.AcquireReaderLock(500);
try
{
string product = KmsLists.SkuItemList[request.ID]?.ToString() ??
KmsLists.KmsItemList[request.KmsID]?.ToString() ??
KmsLists.AppItemList[request.ApplicationID]?.ToString() ??
"Unknown";
KmsItem kmsItem = KmsLists.KmsItemList[request.KmsID];
if (!allowRetailAndBetaProducts && kmsItem != null && (kmsItem.IsPreview || kmsItem.IsRetail))
{
Dispatcher.InvokeAsync(() =>
{
TextBoxInfoText.AppendText($"{nl}V{request.Version} request from {clientIpAddress} for {product} declined: ");
TextBoxInfoText.AppendText($"{(kmsItem.IsRetail ? "Retail" : "Beta")} product \"{product}\" not allowed.");
});
result = unchecked((int)0xc004f042);
return result;
}
if (!allowUnknownProducts &&
(KmsLists.KmsItemList[request.KmsID] == null ||
KmsLists.KmsItemList[request.KmsID].App.Guid != request.ApplicationID))
{
Dispatcher.InvokeAsync(() =>
{
TextBoxInfoText.AppendText($"{nl}V{request.Version} request from {clientIpAddress} for {product} declined: ");
TextBoxInfoText.AppendText(KmsLists.KmsItemList[request.KmsID] == null ? $"Unknown KMS ID {request.KmsID}." : $"Incorrect App ID {request.ApplicationID}.");
});
result = unchecked((int)0xc004f042);
return result;
}
if (request.RequiredClientCount > 1000)
{
Dispatcher.InvokeAsync(() => TextBoxInfoText.AppendText($"{nl}V{request.Version} request from {clientIpAddress} for {product} declined: Required clients > 1000."));
result = unchecked((int)0x8007000d);
return result;
}
DateTime clientDate = DateTime.FromFileTime(request.TimeStamp).ToUniversalTime();
if (checkTime && Math.Abs((clientDate - DateTime.UtcNow).TotalHours) > 4.0)
{
Dispatcher.InvokeAsync(
() =>
TextBoxInfoText.AppendText(
$"{nl}V{request.Version} request from {clientIpAddress} for {product} declined: Client time \"{clientDate.ToLocalTime()} {KmsClientWindow.CurrentTimeZone}\" > ± 4 hours from server time \"{DateTime.Now} {KmsClientWindow.CurrentTimeZone}\"."));
result = unchecked((int)0xc004f06c);
return result;
}
appItem.MaxActiveClients = Math.Max((int)request.RequiredClientCount << 1, appItem.MaxActiveClients);
appItem.AddClient(request.ClientMachineID);
response.KMSCurrentCount = (uint)appItem.Queue.Count;
if (response.KMSCurrentCount > 671)
{
Dispatcher.InvokeAsync(() => TextBoxInfoText.AppendText($"{nl}V{request.Version} request from {clientIpAddress} for {product} declined: > 671 clients."));
result = unchecked((int)0xc004d104);
return result;
}
Dispatcher.InvokeAsync(() =>
{
TextBoxInfoText.AppendText($"{nl}V{response.Version.Major}.{response.Version.Minor} response for {product} sent to {request.WorkstationName.Text} ({clientIpAddress}).");
});
}
finally
{
KmsData.Lock.ReleaseReaderLock();
Dispatcher.InvokeAsync(() =>
{
if (result != 0)
{
TextBoxInfoText.AppendText($" Error 0x{unchecked((uint)result):X8}: {Kms.StatusMessage(unchecked((uint)result))}");
}
TextBoxInfoText.ScrollToEnd();
});
}
}
catch (Exception ex)
{
Dispatcher.InvokeAsync(() =>
{
TextBoxInfoText.AppendText($"{nl}Request not logged: {ex.Message}");
TextBoxInfoText.ScrollToEnd();
});
}
Marshal.StructureToPtr(response, responsePtr, true);
if (request.Version.Major > 5 && hwIdPtr != IntPtr.Zero)
{
Marshal.StructureToPtr(hwId, hwIdPtr, true);
}
return 0;
}
private void KmsServerThread()
{
try
{
Kms.StartServer(Port, ProcessKmsRequest);
IsRunning = false;
}
catch (KmsException ex)
{
IsRunning = false;
Dispatcher.Invoke(() => MessageBox.Show(this, ex.Message, "KMS server error", MessageBoxButton.OK, MessageBoxImage.Error));
}
}
private void Button_StartStop_Click(object sender, RoutedEventArgs e)
{
if (!IsRunning)
{
if (TextBoxPort.Background.Equals(Brushes.OrangeRed))
{
MessageBox.Show(TextBoxPort.ToolTip.ToString(), "Incorrect TCP-Port", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
Port = ushort.Parse(TextBoxPort.Text, NumberStyles.None, CultureInfo.CurrentCulture);
if (TextBoxTapIp.Background.Equals(Brushes.OrangeRed))
{
MessageBox.Show("TAP IPv4/CIDR is invalid", null, MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
IsRunning = true;
KmsLists.LoadDatabase();
foreach (AppItem appItem in KmsLists.AppItemList)
{
appItem.PreCharge(CheckBoxPreCharge.IsChecked.Value);
}
new Thread(KmsServerThread).Start();
}
else
{
Kms.StopServer();
}
}
private void ActivationInterval_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
TextBox parsedTextBox = ((Grid)textBox.Parent).Children.OfType<TextBox>().FirstOrDefault(uiElement => uiElement.Name == textBox.Name + "Parsed");
bool isValidInterval = ActivationInterval.TryParse(textBox.Text, out uint validationInterval);
if (!isValidInterval)
{
textBox.Background = Brushes.OrangeRed;
if (parsedTextBox != null)
{
validationInterval = parsedTextBox.Name == nameof(TextBoxVlRenewalParsed) ? 10080U : 120U;
}
}
else
{
textBox.Background = Brushes.LightGreen;
}
TimeSpan timeSpan = TimeSpan.FromMinutes(validationInterval);
if (parsedTextBox != null)
{
parsedTextBox.Text = $"{timeSpan.Days} days, {timeSpan.Hours} hours, {timeSpan.Minutes} minutes";
}
}
private void UseTap_Click(object sender, RoutedEventArgs e)
{
CheckBox checkBox = (CheckBox)sender;
TextBoxTapIp.Visibility = ComboBoxTap.Visibility = checkBox.IsChecked.Value ? Visibility.Visible : Visibility.Collapsed;
}
private void TextBoxTapIp_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
bool isValid = TapMirror.IsValidSubnet(textBox.Text, out string errorReason);
textBox.ToolTip = errorReason;
textBox.Background = isValid ? Brushes.LightGreen : Brushes.OrangeRed;
}
private void TextBoxHwId_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
HwId hwid;
try
{
hwid.Text = textBox.Text;
textBox.Background = Brushes.LightGreen;
textBox.ToolTip = null;
}
catch (Exception ex)
{
textBox.Background = Brushes.OrangeRed;
textBox.ToolTip = ex.Message;
}
}
private void TextBoxPort_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
if (!ushort.TryParse(textBox.Text, NumberStyles.None, CultureInfo.CurrentCulture, out ushort port) || port == 0)
{
textBox.Background = Brushes.OrangeRed;
textBox.ToolTip = "Port must be an integer number between 1 and 65535";
return;
}
textBox.Background = Brushes.LightGreen;
textBox.ToolTip = null;
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void NotifyOfPropertyChange([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}