Repository navigation
Expand file tree
/
Copy pathDriverUpdateService.cs
More file actions
1467 lines (1358 loc) · 70 KB
/
Copy pathDriverUpdateService.cs
File metadata and controls
1467 lines (1358 loc) · 70 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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Buffers;
using System.IO.Compression;
using System.Globalization;
using System.Management;
using System.Net;
using System.Net.Http.Json;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text.Json;
using System.Text.RegularExpressions;
using Microsoft.Win32;
namespace HonorPCHelper;
internal sealed record DriverComponent(
int Id,
string Name,
string DisplayName,
string CurrentVersion,
string PackageType,
string? DeviceName = null,
string? AppName = null);
internal sealed record DriverUpdate(
DriverComponent Component,
string Version,
string VersionId,
string DownloadBaseUrl,
long Size,
string? Sha256,
string? ReleaseDate = null,
bool IsUpdate = true,
string? PackageTitle = null);
internal sealed record DriverCheckResult(
IReadOnlyList<DriverComponent> Components,
IReadOnlyList<DriverUpdate> Updates,
IReadOnlyDictionary<int, string> AvailableVersions,
bool IsComplete = true);
internal sealed partial class DriverUpdateService
{
private const string CheckUrl =
"https://update.platform.hihonorcloud.com/hid_and_common/v2/CheckEx.action?latest=true&verType=true&defenceHijack=true";
private const string LaptopProductId = "CMCG10000120";
private const int SupportRequestConcurrency = 6;
// Driver endpoints must not inherit a stale local WinINET proxy. A number
// of VPN/proxy clients leave 127.0.0.1 configured after they stop, which
// otherwise turns every update check into a timeout.
private static readonly HttpClient Http = new(new SocketsHttpHandler
{
UseProxy = false,
// Каталоги HONOR отдают объёмный JSON, а между запросами проходят
// секунды: сжатие и переиспользование соединений заметно сокращают
// время проверки.
AutomaticDecompression = DecompressionMethods.All,
PooledConnectionLifetime = TimeSpan.FromMinutes(2)
})
{
Timeout = TimeSpan.FromMinutes(10)
};
internal async Task<DriverCheckResult> CheckAsync(
CancellationToken cancellationToken = default)
{
var installedComponents = await ReadInstalledComponentsAsync(cancellationToken);
return await CheckAsync(installedComponents, cancellationToken);
}
internal async Task<IReadOnlyList<DriverComponent>> ReadInstalledComponentsAsync(
CancellationToken cancellationToken = default)
=> await Task.Run(ReadInstalledComponents, cancellationToken);
internal async Task<IReadOnlyList<DriverComponent>> BuildDeviceListAsync(
CancellationToken cancellationToken = default)
=> AddMissingCatalogComponents(await ReadInstalledComponentsAsync(cancellationToken));
internal async Task<DriverCheckResult> CheckAsync(
IReadOnlyList<DriverComponent> installedComponents,
CancellationToken cancellationToken = default)
{
var requestComponents = AddMissingCatalogComponents(installedComponents);
var serverRequestComponents = requestComponents.Where(component => component.Id > 0).ToList();
var machine = ReadMachineIdentity();
var dashboard = string.Join(';', serverRequestComponents.Select(component => $"{component.Name}:{component.CurrentVersion}")) + ";";
var helperVersion = Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? string.Empty;
var request = new
{
components = serverRequestComponents.Select(component => new
{
AppName = component.AppName ?? component.Name,
PackageName = component.Name,
PackageType = component.PackageType,
PackageVersionCode = component.CurrentVersion,
PackageVersionName = helperVersion,
componentID = component.Id.ToString()
}),
rules = new
{
C_version = machine.CVersion,
Dashboard = dashboard,
DashboardFlash = string.Empty,
DeviceName = machine.DeviceName,
FirmWare = string.Empty,
Language = System.Globalization.CultureInfo.CurrentUICulture.Name,
OS = Environment.OSVersion.VersionString,
deviceId = string.Empty,
udid = string.Empty
}
};
AppLog.Info($"Checking HONOR driver updates for {machine.DeviceName}/{machine.CVersion}; "
+ $"{installedComponents.Count} detected, {serverRequestComponents.Count} requested");
AppLog.Info($"Installed component versions: {dashboard}");
var (apiUpdates, apiVersions) = await CheckPlatformAsync(
request, serverRequestComponents, cancellationToken);
var availableApiUpdates = await FilterAvailableDownloadsAsync(apiUpdates, cancellationToken);
var platformHasMissingDownloads = availableApiUpdates.Count < apiUpdates.Count;
var (siteComponents, siteUpdates, siteVersions, siteCheckComplete) = !platformHasMissingDownloads
&& (availableApiUpdates.Count > 0 || apiVersions.Count > 0)
? (Array.Empty<DriverComponent>(), Array.Empty<DriverUpdate>(),
(IReadOnlyDictionary<int, string>)new Dictionary<int, string>(), true)
: await CheckSupportSiteAsync(machine, serverRequestComponents, cancellationToken);
var availableSiteUpdates = await FilterAvailableDownloadsAsync(siteUpdates, cancellationToken);
// When several packages map to the same component, prefer one whose version
// can be compared with the installed driver at all: a build-date package
// sorts above the real driver version but says nothing about it.
var updates = availableApiUpdates.Concat(availableSiteUpdates)
.GroupBy(update => update.Component.Id)
.Select(group => group
.OrderByDescending(update =>
IsComparableVersion(update.Version, update.Component.CurrentVersion))
.ThenByDescending(update => VersionParts(update.Version), VersionPartComparer.Instance)
.First())
.ToList();
var availableVersions = apiVersions.ToDictionary(item => item.Key, item => item.Value);
foreach (var item in siteVersions)
{
if (!availableVersions.TryGetValue(item.Key, out var version)
|| CompareVersions(item.Value, version) > 0)
availableVersions[item.Key] = item.Value;
}
// Keep missing catalog entries visible even when HONOR has no compatible
// package for this particular model. Previously those entries were used
// in the request and then discarded unless the server returned a version,
// which made devices without a detected driver disappear from the UI.
var components = requestComponents.Concat(siteComponents)
.GroupBy(component => component.Id)
.Select(group => group.First())
.ToList();
foreach (var update in updates.Where(update => update.IsUpdate))
{
AppLog.Info($"Update available for {update.Component.Name}: "
+ $"{update.Component.CurrentVersion} -> {update.Version}");
}
AppLog.Info($"HONOR driver update check completed; "
+ $"{updates.Count(update => update.IsUpdate)} update(s), "
+ $"{updates.Count} package(s)");
return new DriverCheckResult(components, updates, availableVersions, siteCheckComplete);
}
private static async Task<IReadOnlyList<DriverUpdate>> FilterAvailableDownloadsAsync(
IEnumerable<DriverUpdate> updates,
CancellationToken cancellationToken)
{
var groups = updates.GroupBy(update => GetDownloadUrl(update.DownloadBaseUrl))
.Select(group => (Url: group.Key, Updates: group.ToArray()))
.ToArray();
using var requestSlots = new SemaphoreSlim(SupportRequestConcurrency);
var checks = groups.Select(async group =>
{
await requestSlots.WaitAsync(cancellationToken);
try
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(10));
using var request = new HttpRequestMessage(HttpMethod.Head, group.Url);
using var response = await Http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeout.Token);
if (response.StatusCode is HttpStatusCode.NotFound or HttpStatusCode.Gone)
{
AppLog.Info($"Ignoring missing driver package: {group.Updates[0].Component.Name} "
+ $"{group.Updates[0].Version} returned {(int)response.StatusCode}");
return Array.Empty<DriverUpdate>();
}
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
AppLog.Info($"Driver package availability check timed out for {group.Url.Host}");
}
catch (Exception exception)
{
AppLog.Error($"Driver package availability check failed for {group.Url.Host}", exception);
}
finally
{
requestSlots.Release();
}
return group.Updates;
});
return (await Task.WhenAll(checks)).SelectMany(group => group).ToArray();
}
private static async Task<(
IReadOnlyList<DriverUpdate> Updates,
IReadOnlyDictionary<int, string> AvailableVersions)> CheckPlatformAsync(
object request,
IReadOnlyList<DriverComponent> components,
CancellationToken cancellationToken)
{
try
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
// This endpoint is only the fast path. Waiting half a minute here
// makes the window look hung before the support catalog is even
// tried, and the catalog contains the same packages.
timeout.CancelAfter(TimeSpan.FromSeconds(10));
using var response = await Http.PostAsJsonAsync(CheckUrl, request, timeout.Token);
response.EnsureSuccessStatusCode();
await using var stream = await response.Content.ReadAsStreamAsync(timeout.Token);
using var document = await JsonDocument.ParseAsync(stream, cancellationToken: timeout.Token);
return ParseUpdates(document.RootElement, components);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
AppLog.Info("HONOR update platform request timed out; using support catalog");
return ([], new Dictionary<int, string>());
}
catch (Exception exception)
{
AppLog.Error("HONOR update platform request failed; using support catalog", exception);
return ([], new Dictionary<int, string>());
}
}
internal async Task DownloadAsync(
DriverUpdate update,
IProgress<int>? progress = null,
CancellationToken cancellationToken = default)
{
var safeVersion = SafeFileName(update.Version);
var packageDirectory = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"HonorPCHelper", "DriverUpdates", $"{update.Component.Id}_{safeVersion}");
var downloadUrl = GetDownloadUrl(update.DownloadBaseUrl);
var originalPackageName = GetOriginalPackageName(downloadUrl)
?? SafeFileName(update.PackageTitle ?? update.Component.DisplayName);
var extension = Path.GetExtension(downloadUrl.AbsolutePath);
if (string.IsNullOrWhiteSpace(extension) || extension.Length > 8)
extension = ".download";
var saveExtension = extension.Equals(".zip", StringComparison.OrdinalIgnoreCase)
|| extension.Equals(".download", StringComparison.OrdinalIgnoreCase)
? ".exe"
: extension;
using var dialog = new SaveFileDialog
{
Title = L.T("Сохранить драйвер", "Save driver", "保存驱动程序"),
FileName = Path.ChangeExtension(originalPackageName, saveExtension),
Filter = $"{L.T("Файл драйвера", "Driver file", "驱动程序文件")} (*{saveExtension})|*{saveExtension}",
AddExtension = true,
DefaultExt = saveExtension.TrimStart('.'),
OverwritePrompt = true
};
if (dialog.ShowDialog() != DialogResult.OK)
throw new OperationCanceledException(cancellationToken);
Directory.CreateDirectory(packageDirectory);
var packagePath = Path.Combine(packageDirectory, "package" + extension);
var extractDirectory = Path.Combine(packageDirectory, "package");
if (Directory.Exists(extractDirectory))
Directory.Delete(extractDirectory, recursive: true);
AppLog.Info($"Downloading driver {update.Component.Name} {update.Version} from {downloadUrl.Host}");
using (var response = await Http.GetAsync(
downloadUrl, HttpCompletionOption.ResponseHeadersRead, cancellationToken))
{
if (response.StatusCode is HttpStatusCode.NotFound or HttpStatusCode.Gone)
throw new HttpRequestException(L.T(
"Файл драйвера больше недоступен на сервере HONOR. Обновите список драйверов.",
"The driver file is no longer available on the HONOR server. Refresh the driver list.",
"该驱动程序文件已无法从 HONOR 服务器获取。请刷新驱动程序列表。"),
null, response.StatusCode);
response.EnsureSuccessStatusCode();
var total = response.Content.Headers.ContentLength;
await using var source = await response.Content.ReadAsStreamAsync(cancellationToken);
await using var destination = new FileStream(packagePath, FileMode.Create, FileAccess.Write, FileShare.None, 81920, true);
var buffer = new byte[81920];
long written = 0;
int read;
while ((read = await source.ReadAsync(buffer, cancellationToken)) > 0)
{
await destination.WriteAsync(buffer.AsMemory(0, read), cancellationToken);
written += read;
if (total > 0)
progress?.Report((int)Math.Clamp(written * 100 / total.Value, 0, 100));
}
}
if (!string.IsNullOrWhiteSpace(update.Sha256))
{
await using var package = File.OpenRead(packagePath);
var actualHash = Convert.ToHexString(await SHA256.HashDataAsync(package, cancellationToken));
if (!actualHash.Equals(update.Sha256, StringComparison.OrdinalIgnoreCase))
throw new InvalidDataException(L.T(
"Контрольная сумма пакета драйвера не совпадает.",
"The driver package checksum does not match.",
"驱动程序包校验和不匹配。"));
}
var fileToSave = packagePath;
if (IsZipPackage(packagePath))
{
Directory.CreateDirectory(extractDirectory);
ExtractSafely(packagePath, extractDirectory);
ExtractNestedArchivesSafely(extractDirectory);
var installer = Directory.GetFiles(extractDirectory, "*.exe", SearchOption.AllDirectories)
.OrderByDescending(path => new FileInfo(path).Length)
.FirstOrDefault();
if (installer is not null)
fileToSave = installer;
}
var fromOfficialSupport = downloadUrl.Host.EndsWith("service.hihonor.com", StringComparison.OrdinalIgnoreCase)
|| downloadUrl.Host.EndsWith("honor.com", StringComparison.OrdinalIgnoreCase)
|| downloadUrl.Host.EndsWith("hihonorcloud.com", StringComparison.OrdinalIgnoreCase);
if (Path.GetExtension(fileToSave).Equals(".exe", StringComparison.OrdinalIgnoreCase))
VerifyInstallerSignature(fileToSave, requireHonorPublisher: !fromOfficialSupport);
else if (!fromOfficialSupport && string.IsNullOrWhiteSpace(update.Sha256))
throw new InvalidDataException(L.T(
"Не удалось проверить целостность пакета драйвера.",
"The driver package integrity could not be verified.",
"无法验证驱动程序包的完整性。"));
var destinationPath = Path.ChangeExtension(dialog.FileName, Path.GetExtension(fileToSave));
if (!destinationPath.Equals(dialog.FileName, StringComparison.OrdinalIgnoreCase)
&& File.Exists(destinationPath)
&& MessageBox.Show(
L.T($"Файл {Path.GetFileName(destinationPath)} уже существует. Заменить его?",
$"The file {Path.GetFileName(destinationPath)} already exists. Replace it?",
$"文件 {Path.GetFileName(destinationPath)} 已存在。是否替换?"),
dialog.Title, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes)
throw new OperationCanceledException(cancellationToken);
File.Copy(fileToSave, destinationPath, overwrite: true);
AppLog.Info($"Saved verified driver package to {destinationPath}");
}
private static bool IsZipPackage(string path)
{
Span<byte> signature = stackalloc byte[4];
using var stream = File.OpenRead(path);
return stream.Read(signature) == signature.Length
&& signature[0] == (byte)'P' && signature[1] == (byte)'K';
}
private static readonly SearchValues<char> InvalidFileNameChars =
SearchValues.Create(Path.GetInvalidFileNameChars());
private static string SafeFileName(string value)
{
var name = string.Create(value.Length, value, (span, source) =>
{
for (var index = 0; index < source.Length; index++)
span[index] = InvalidFileNameChars.Contains(source[index]) ? '_' : source[index];
}).Trim();
return string.IsNullOrWhiteSpace(name) ? "HONOR-driver" : name;
}
private static string? GetOriginalPackageName(Uri downloadUrl)
{
var pathName = Uri.UnescapeDataString(Path.GetFileName(downloadUrl.AbsolutePath));
var encoded = Path.GetFileNameWithoutExtension(pathName);
if (encoded.Length is > 0 and <= 8192)
{
try
{
var base64 = encoded.Replace('-', '+').Replace('_', '/');
base64 += new string('=', (4 - base64.Length % 4) % 4);
using var compressed = new MemoryStream(Convert.FromBase64String(base64));
using var gzip = new GZipStream(compressed, CompressionMode.Decompress);
using var document = JsonDocument.Parse(gzip);
var fileName = Text(document.RootElement, "fileName");
if (!string.IsNullOrWhiteSpace(fileName))
return SafeFileName(Path.GetFileName(fileName));
}
catch (Exception exception) when (exception is FormatException
or InvalidDataException or JsonException)
{
// Some support links use a regular file path instead of an encoded descriptor.
}
}
return string.IsNullOrWhiteSpace(Path.GetExtension(pathName)) ? null : SafeFileName(pathName);
}
private static List<DriverComponent> ReadInstalledComponents()
{
// Win32_PnPSignedDriver - самый медленный запрос всей проверки.
// Однопроходное перечисление отдаёт объекты по мере готовности
// и не держит весь результат в памяти.
using var searcher = new ManagementObjectSearcher(
"SELECT DeviceName, DeviceID, DeviceClass, DriverVersion, DriverProviderName "
+ "FROM Win32_PnPSignedDriver")
{
Options = ForwardOnly()
};
using var results = searcher.Get();
var driverList = new List<PnpDriver>();
foreach (var item in results)
{
using var driver = item;
var version = Convert.ToString(driver["DriverVersion"]) ?? string.Empty;
if (string.IsNullOrWhiteSpace(version))
continue;
driverList.Add(new PnpDriver(
Convert.ToString(driver["DeviceName"]) ?? string.Empty,
Convert.ToString(driver["DeviceID"]) ?? string.Empty,
version,
Convert.ToString(driver["DriverProviderName"]) ?? string.Empty,
Convert.ToString(driver["DeviceClass"]) ?? string.Empty));
}
var drivers = driverList.ToArray();
var components = new List<DriverComponent>();
Add(components, drivers, 87, "VDisplay", "Virtual Display", d => Has(d, "virtual display"));
Add(components, drivers, 88, "VHID", "Virtual HID", d => Has(d, "virtual hid"));
Add(components, drivers, 12, "WDT", "Watchdog", d => Has(d, "wdtdevice") || IdHas(d, "WDT0001"));
Add(components, drivers, 1, "Chipset", "Chipset", d =>
Has(d, "lpc") || Has(d, "espi") || Has(d, "smbus") || Has(d, "chipset"));
Add(components, drivers, 2, "ME", "Intel Management Engine", d => Has(d, "management engine interface"));
// Display adapters are matched by hardware vendor and device class instead
// of by name: Windows localises adapter names and they differ between Arc,
// Iris, UHD and Radeon parts. The integrated GPU is preferred because that
// is the one HONOR ships a package for.
Add(components, drivers, 3, "Graphics", "Graphics",
[
d => IsDisplayAdapter(d, "VEN_8086"),
d => IsDisplayAdapter(d, "VEN_1002"),
d => IsDisplayAdapter(d, "VEN_10DE")
]);
Add(components, drivers, 4, "SerialIO", "Serial IO", d => Has(d, "serial io"));
Add(components, drivers, 6, "DPTF", "Platform framework", d =>
Has(d, "innovation platform framework manager")
|| Has(d, "dynamic platform and thermal framework"));
Add(components, drivers, 14, "Audio", "Audio", d =>
IdHas(d, "FUNC_01") && Has(d, "audio"));
Add(components, drivers, 15, "WiFi", "Wi-Fi", d =>
ClassIs(d, "NET")
&& (d.DeviceId.StartsWith("PCI\\", StringComparison.OrdinalIgnoreCase)
|| d.DeviceId.StartsWith("USB\\", StringComparison.OrdinalIgnoreCase))
&& (Has(d, "wi-fi") || Has(d, "wifi") || Has(d, "wireless") || Has(d, "wlan"))
&& !Has(d, "virtual")
&& !IsGenericProvider(d));
Add(components, drivers, 16, "BT", "Bluetooth", d =>
(ClassIs(d, "BLUETOOTH") || Has(d, "bluetooth")) && !IsGenericProvider(d));
Add(components, drivers, 18, "EgisFingerPrint", "Fingerprint", d =>
ClassIs(d, "BIOMETRIC") || Has(d, "fingerprint"), FingerprintPackageType);
Add(components, drivers, 41, "Monitor", "Monitor", d =>
(ClassIs(d, "MONITOR")
|| d.DeviceId.StartsWith("DISPLAY\\", StringComparison.OrdinalIgnoreCase)
|| d.DeviceId.StartsWith("MONITOR\\", StringComparison.OrdinalIgnoreCase))
&& !IsGenericProvider(d));
Add(components, drivers, 52, "NFC", "NFC", d => Has(d, "nfc") || IdHas(d, "NTAG"));
Add(components, drivers, 55, "PPM", "Intel PPM", d => Has(d, "ppm provisioning"));
Add(components, drivers, 56, "TXT", "Intel TXT", d => Has(d, "txt authenticated"));
// Windows localises most Smart Sound endpoint names, so match the part of
// the product name that stays in English and let the shared package version
// of the matched devices win.
Add(components, drivers, 65, "ISST", "Intel Smart Sound", d => Has(d, "smart sound"));
Add(components, drivers, 73, "iPMT", "Intel PMT", d => Has(d, "platform monitoring technology"));
// The Gaussian & Neural Accelerator of pre-Meteor Lake platforms shares the
// ComputeAccelerator class with the NPU but is versioned separately, so
// reporting it as the NPU would invent an update on every such machine.
Add(components, drivers, 74, "NPU", "Intel NPU", d =>
!Has(d, "gaussian") && !Has(d, "gna")
&& (ClassIs(d, "COMPUTEACCELERATOR") || ClassIs(d, "NEURALPROCESSOR")
|| Has(d, "npu") || Has(d, "neural processor") || Has(d, "ai boost")));
Add(components, drivers, 76, "LuxvisionsCameraDrv", "Camera", d =>
(ClassIs(d, "CAMERA") || ClassIs(d, "IMAGE") || Has(d, "camera")) && !IsGenericProvider(d),
appName: "HonorCamera");
Add(components, drivers, 78, "MEP", "Windows Studio Effects", d =>
IdHas(d, "MEP_") && (Has(d, "windows camera effects") || Has(d, "windows studio effects")));
using var biosSearcher = new ManagementObjectSearcher("SELECT SMBIOSBIOSVersion FROM Win32_BIOS");
using var biosResults = biosSearcher.Get();
var biosVersion = biosResults.Cast<ManagementObject>()
.Select(item => Convert.ToString(item["SMBIOSBIOSVersion"]))
.FirstOrDefault(value => !string.IsNullOrWhiteSpace(value));
var biosPackageType = Convert.ToString(
Registry.GetValue(@"HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\BIOS", "SystemProductName", string.Empty));
if (!string.IsNullOrWhiteSpace(biosVersion))
components.Add(new DriverComponent(23, "BIOS", "BIOS", biosVersion, biosPackageType ?? string.Empty));
using var missingSearcher = new ManagementObjectSearcher(
"SELECT Name, DeviceID, PNPClass FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 28")
{
Options = ForwardOnly()
};
using var missingResults = missingSearcher.Get();
// Однонаправленная выборка освобождает строку при переходе к следующей,
// поэтому значения копируются во время обхода, а сортируются копии:
// OrderBy по живой выборке читал уже освобождённые объекты.
var missingDevices = new List<(string? Name, string? DeviceId, string? PnpClass)>();
foreach (var item in missingResults)
{
using var device = item;
missingDevices.Add((
Convert.ToString(device["Name"]),
Convert.ToString(device["DeviceID"]),
Convert.ToString(device["PNPClass"])));
}
var missingDeviceId = -1;
foreach (var (name, deviceId, pnpClass) in missingDevices
.OrderBy(device => device.DeviceId, StringComparer.OrdinalIgnoreCase))
{
components.Add(new DriverComponent(
missingDeviceId--,
"MissingDevice",
string.IsNullOrWhiteSpace(name)
? L.T("Неизвестное устройство", "Unknown device", "未知设备")
: name,
"0",
pnpClass ?? string.Empty,
deviceId));
}
return components.GroupBy(component => component.Id).Select(group => group.First()).ToList();
}
private static List<DriverComponent> AddMissingCatalogComponents(IReadOnlyCollection<DriverComponent> installed)
{
var result = installed.ToList();
var installedIds = installed.Select(component => component.Id).ToHashSet();
foreach (var item in ComponentCatalog)
{
if (!installedIds.Contains(item.Id))
result.Add(new DriverComponent(
item.Id, item.Name, item.DisplayName, "0", string.Empty, AppName: item.AppName));
}
return result;
}
private static void Add(
ICollection<DriverComponent> components,
IEnumerable<PnpDriver> drivers,
int id,
string name,
string displayName,
Func<PnpDriver, bool> predicate,
Func<PnpDriver, string>? packageType = null,
string? appName = null)
=> Add(components, drivers, id, name, displayName, [predicate], packageType, appName);
// Records the installed version of one HONOR component. The predicates are
// tried in order and the first one matching any device wins, so a precise rule
// can be stated ahead of a broader fallback.
private static void Add(
ICollection<DriverComponent> components,
IEnumerable<PnpDriver> drivers,
int id,
string name,
string displayName,
Func<PnpDriver, bool>[] predicates,
Func<PnpDriver, string>? packageType = null,
string? appName = null)
{
foreach (var predicate in predicates)
{
var match = SelectRepresentative(drivers.Where(predicate).ToArray());
if (match is null)
continue;
components.Add(new DriverComponent(id, name, displayName, match.Version,
packageType?.Invoke(match) ?? string.Empty, match.DeviceName, appName));
return;
}
}
// Picks the device whose driver version stands for the installed package. A
// HONOR package installs the same version on every device it covers, so the
// version shared by most of the matched devices is the reliable answer; taking
// the highest one instead used to pick an unrelated device that merely shared a
// keyword, which made the component look out of date.
private static PnpDriver? SelectRepresentative(IReadOnlyCollection<PnpDriver> matches)
{
if (matches.Count == 0)
return null;
var vendorMatches = matches.Where(driver => !IsGenericProvider(driver)).ToArray();
var candidates = vendorMatches.Length > 0 ? vendorMatches : matches;
return candidates
.GroupBy(driver => driver.Version, StringComparer.OrdinalIgnoreCase)
.OrderByDescending(group => group.Count())
.ThenByDescending(group => VersionParts(group.Key), VersionPartComparer.Instance)
.First()
.OrderBy(driver => driver.DeviceName, StringComparer.OrdinalIgnoreCase)
.First();
}
private static (
IReadOnlyList<DriverUpdate> Updates,
IReadOnlyDictionary<int, string> AvailableVersions) ParseUpdates(
JsonElement root,
IReadOnlyList<DriverComponent> components)
{
var result = new List<DriverUpdate>();
var availableVersions = new Dictionary<int, string>();
if (!root.TryGetProperty("status", out var status) || status.GetString() != "0"
|| !root.TryGetProperty("components", out var serverComponents))
return (result, availableVersions);
var byId = components.ToDictionary(component => component.Id);
foreach (var item in serverComponents.EnumerateArray())
{
if (!TryInt(item, "componentID", out var id) || !byId.TryGetValue(id, out var component))
continue;
var version = Text(item, "version") ?? Text(item, "name") ?? string.Empty;
if (!string.IsNullOrWhiteSpace(version)
&& (!availableVersions.TryGetValue(id, out var availableVersion)
|| CompareVersions(version, availableVersion) > 0))
availableVersions[id] = version;
var url = Text(item, "url") ?? string.Empty;
if (string.IsNullOrWhiteSpace(version) || string.IsNullOrWhiteSpace(url))
continue;
_ = long.TryParse(Text(item, "size"), out var size);
result.Add(new DriverUpdate(component, version, Text(item, "versionID") ?? string.Empty,
url, size, Text(item, "sha256") ?? Text(item, "hash"),
NormalizeReleaseDate(Text(item, "releaseDate") ?? Text(item, "updateTime") ?? Text(item, "date")),
IsNewerVersion(version, component.CurrentVersion)));
}
return (result, availableVersions);
}
private static async Task<(
IReadOnlyList<DriverComponent> Components,
IReadOnlyList<DriverUpdate> Updates,
IReadOnlyDictionary<int, string> AvailableVersions,
bool IsComplete)> CheckSupportSiteAsync(
MachineIdentity machine,
IReadOnlyList<DriverComponent> components,
CancellationToken cancellationToken)
{
var hadFailure = false;
var knownOfferings = KnownSupportOfferings(machine);
// ReadSupportPackagesAsync uses the same canonical catalog/package
// endpoints for a known offering, so retrying it once per regional
// product-tree endpoint only repeats an identical request.
var endpoints = knownOfferings.Count > 0 ? SupportEndpoints.Take(1) : SupportEndpoints;
// Сервер каталога иногда подвисает на минуту-другую. С одним сервером
// запасного нет, поэтому сорвавшийся запрос повторяется один раз;
// при нескольких запасным служит следующий регион.
var attempts = knownOfferings.Count > 0 ? 2 : 1;
foreach (var endpoint in endpoints)
{
for (var attempt = 1; attempt <= attempts; attempt++)
{
var last = attempt == attempts;
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(30));
try
{
// HONOR's product-tree lookup is by far the slowest part of the
// check and occasionally stalls. Prefer a verified model to
// offering mapping when one is available; package metadata is
// still fetched live from the official catalog.
var offerings = knownOfferings.Count > 0
? knownOfferings
: await ResolveSupportOfferingsAsync(endpoint, machine, timeout.Token);
if (offerings.Count == 0)
break;
var result = await ReadSupportPackagesAsync(
endpoint, offerings, components, timeout.Token);
if (result.Updates.Count > 0)
{
AppLog.Info($"Official HONOR support matched {string.Join(',', offerings)}; "
+ $"{result.Updates.Count} package(s)");
return (result.Components, result.Updates, result.AvailableVersions, true);
}
break;
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
AppLog.Info($"HONOR support catalog {endpoint.CountryCode} timed out"
+ (last ? string.Empty : "; retrying"));
hadFailure |= last;
}
catch (Exception exception) when (!last && exception is HttpRequestException or IOException)
{
AppLog.Info($"HONOR support catalog {endpoint.CountryCode} failed; retrying: {exception.Message}");
}
catch (Exception exception)
{
AppLog.Error($"HONOR support catalog {endpoint.CountryCode} failed", exception);
hadFailure = true;
break;
}
}
}
AppLog.Info($"Official HONOR support has no catalog match for {machine.DeviceName}/{machine.CVersion}");
return ([], [], new Dictionary<int, string>(), !hadFailure);
}
// A verified model to offering shortcut for the machine this project is
// developed on: HONOR MagicBook Pro 14 2026 Ultra X7-358H (ZQC-P / ZhuqueC),
// which the support catalog knows only by its offering code.
//
// The match names the model and its processor, and deliberately ignores the
// CVersion platform code: C233 covers ZhuqueC, XuanwuC and JiguangC alike, so
// keying on it handed a MagicBook 16 2026 (JGC-N, offering OFFE00421315) the
// Pro 14 catalog - an Audio package from another codec that never raised the
// installed version, and a BIOS 1.10 that belongs to a different board.
// Every other machine resolves its own offering from the product tree.
private static IReadOnlyList<string> KnownSupportOfferings(MachineIdentity machine)
{
var identifiers = machine.Identifiers
.Append(machine.DeviceName)
.Select(NormalizeIdentity)
.ToHashSet(StringComparer.Ordinal);
return (identifiers.Contains("ZQCP") || identifiers.Contains("ZHUQUEC"))
&& ProcessorIdentityTokens(machine.ProcessorName).Contains("358H")
? ["OFFE00461151"]
: [];
}
private static async Task<IReadOnlyList<string>> ResolveSupportOfferingsAsync(
SupportEndpoint endpoint,
MachineIdentity machine,
CancellationToken cancellationToken)
{
using var seriesDocument = await GetSupportJsonAsync(endpoint,
"/ccpc/queryNewCommodityList/1000",
new Dictionary<string, string>
{
["productLevel"] = "lv3",
["productId"] = LaptopProductId
}, cancellationToken);
if (!TryProductList(seriesDocument.RootElement, out var series))
return [];
var productIds = series.EnumerateArray()
.Select(item => Text(item, "productId"))
.Where(id => !string.IsNullOrWhiteSpace(id))
.Cast<string>()
.ToList();
using var requestSlots = new SemaphoreSlim(SupportRequestConcurrency);
var productTasks = productIds.Select(async productId =>
{
await requestSlots.WaitAsync(cancellationToken);
try
{
using var productsDocument = await GetSupportJsonAsync(endpoint,
"/ccpc/queryNewCommodityList/1000",
new Dictionary<string, string>
{
["productLevel"] = "lv5",
["productId"] = productId
}, cancellationToken);
if (!TryProductList(productsDocument.RootElement, out var productList))
return Array.Empty<SupportProduct>();
return productList.EnumerateArray()
.Select(item => new SupportProduct(
Text(item, "offeringCode") ?? Text(item, "productId") ?? string.Empty,
string.Join(' ', new[]
{
Text(item, "displayName"), Text(item, "productName"),
Text(item, "backName"), Text(item, "keyword")
}.Where(value => !string.IsNullOrWhiteSpace(value)))))
.Where(product => !string.IsNullOrWhiteSpace(product.OfferingCode))
.ToArray();
}
finally
{
requestSlots.Release();
}
});
var products = (await Task.WhenAll(productTasks)).SelectMany(items => items).ToList();
var scored = products.Select(product => (Product: product, Score: ScoreProduct(product, machine)))
.Where(item => item.Score >= 100)
.OrderByDescending(item => item.Score)
.ToList();
if (scored.Count == 0)
return [];
var bestScore = scored[0].Score;
if (bestScore < 130 && scored.Count(item => item.Score == bestScore) > 1
&& ProcessorIdentityTokens(machine.ProcessorName).Count > 0)
return [];
return scored.Where(item => item.Score == bestScore)
.Select(item => item.Product.OfferingCode)
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
}
private static int ScoreProduct(SupportProduct product, MachineIdentity machine)
{
var productText = NormalizeIdentity(product.Description);
var score = 0;
foreach (var identifier in machine.Identifiers)
{
var normalized = NormalizeIdentity(identifier);
if (normalized.Length >= 4 && productText.Contains(normalized, StringComparison.Ordinal))
{
var hardwareCode = !identifier.Any(char.IsWhiteSpace)
&& (identifier.Contains('-') || identifier.Any(char.IsDigit));
score = Math.Max(score, (hardwareCode ? 100 : 70) + Math.Min(normalized.Length, 20));
}
}
if (score < 70)
return 0;
foreach (var token in ProcessorIdentityTokens(machine.ProcessorName))
{
if (productText.Contains(token, StringComparison.Ordinal))
score += 30;
}
if (machine.MemoryGb > 0
&& Regex.IsMatch(product.Description, $@"\b{machine.MemoryGb}\s*GB\b", RegexOptions.IgnoreCase))
score += 5;
return score;
}
private static string NormalizeIdentity(string value)
=> NonAlphanumericPattern().Replace(value, string.Empty).ToUpperInvariant();
private static IReadOnlyList<string> ProcessorIdentityTokens(string value)
=> ProcessorTokenPattern().Matches(value)
.Select(match => NormalizeIdentity(match.Value))
.Where(token => token.Length >= 4 && token.Any(char.IsLetter) && token.Any(char.IsDigit))
.Distinct(StringComparer.Ordinal)
.ToList();
private static async Task<(
IReadOnlyList<DriverComponent> Components,
IReadOnlyList<DriverUpdate> Updates,
IReadOnlyDictionary<int, string> AvailableVersions)> ReadSupportPackagesAsync(
SupportEndpoint endpoint,
IReadOnlyList<string> offeringCodes,
IReadOnlyList<DriverComponent> installedComponents,
CancellationToken cancellationToken)
{
var catalogEndpoint = SupportEndpoints[0];
var packageEndpoint = ChinesePackageEndpoint;
var byId = installedComponents.ToDictionary(component => component.Id);
var discovered = new Dictionary<int, DriverComponent>();
var updates = new List<DriverUpdate>();
var versions = new Dictionary<int, string>();
foreach (var offeringCode in offeringCodes)
{
using var catalogDocument = await GetSupportJsonAsync(catalogEndpoint,
"/knowledgeBase/getKnowCatalog/1000",
new Dictionary<string, string>
{
["knowTypeId"] = "63",
["orderType"] = "1",
["page"] = "1",
["pageSize"] = "100",
["offeringCode"] = offeringCode,
["cflag"] = "1"
}, cancellationToken);
if (!catalogDocument.RootElement.TryGetProperty("responseData", out var catalogData)
|| !catalogData.TryGetProperty("catalogList", out var catalogList))
continue;
var categories = catalogList.EnumerateArray()
.Select(category => new SupportCategory(
Text(category, "knowTypeId") ?? string.Empty,
Text(category, "knowTypeName") ?? string.Empty))
.Where(category => !string.IsNullOrWhiteSpace(category.Id))
.ToList();
using var requestSlots = new SemaphoreSlim(SupportRequestConcurrency);
var packageTasks = categories.Select(async category =>
{
await requestSlots.WaitAsync(cancellationToken);
try
{
using var policyDocument = await GetSupportJsonAsync(packageEndpoint,
"/knowledgeBase/getServicePolicy/1000",
new Dictionary<string, string>
{
["knowTypeId"] = category.Id,
["orderType"] = "1",
["page"] = "1",
["pageSize"] = "999",
["offeringCode"] = offeringCode,
["driverDown"] = "true",
["cflag"] = "1"
}, cancellationToken);
if (!policyDocument.RootElement.TryGetProperty("responseData", out var data)
|| !data.TryGetProperty("detailList", out var details))
return Array.Empty<SupportPackage>();
return details.EnumerateArray()
.Select(item => new SupportPackage(
Text(item, "resourceTitle") ?? category.Name,
NormalizeSupportVersion(Text(item, "versionNumber") ?? string.Empty),
Text(item, "downloadUrl") ?? string.Empty,
Text(item, "updateTime"), category.Id, category.Name))
.Where(package => !string.IsNullOrWhiteSpace(package.Version)
&& !string.IsNullOrWhiteSpace(package.Url))
.ToArray();
}
finally
{
requestSlots.Release();
}
});
foreach (var package in (await Task.WhenAll(packageTasks)).SelectMany(items => items))
{
var id = SupportComponentId(package.Title, package.CategoryId, package.CategoryName);
DriverComponent component;
if (id > 0 && byId.TryGetValue(id, out var installed))
component = installed;
else
{
if (id <= 0)
id = StableSupportComponentId(package.CategoryId + "|" + package.Title);
var catalogItem = ComponentCatalog.FirstOrDefault(entry => entry.Id == id);
component = new DriverComponent(id, catalogItem?.Name ?? package.Title,
catalogItem?.DisplayName ?? package.CategoryName, "0", string.Empty,
NormalizeSupportTitle(package.Title, package.Version), catalogItem?.AppName);
discovered.TryAdd(id, component);
}
if (!versions.TryGetValue(id, out var known) || CompareVersions(package.Version, known) > 0)
versions[id] = package.Version;
updates.Add(new DriverUpdate(component, package.Version, string.Empty, package.Url, 0, null,
NormalizeReleaseDate(package.UpdateTime),
IsNewerVersion(package.Version, component.CurrentVersion),
NormalizeSupportTitle(package.Title, package.Version)));
}
}
return (discovered.Values.ToList(), updates, versions);
}
private static async Task<JsonDocument> GetSupportJsonAsync(
SupportEndpoint endpoint,
string path,
IReadOnlyDictionary<string, string> parameters,
CancellationToken cancellationToken)
{
var allParameters = parameters.ToDictionary(item => item.Key, item => item.Value);
allParameters["areaCode"] = endpoint.CountryCode;
allParameters["langCode"] = endpoint.Language;
if (!endpoint.MinimalParameters)
{
allParameters["channelCode"] = "HONOR";
allParameters["countryCode"] = endpoint.CountryCode;
allParameters["country"] = endpoint.CountryCode;
allParameters["language"] = endpoint.Language;
allParameters["siteCode"] = endpoint.SiteCode;
}
allParameters["jsonp"] = "callback";
var query = string.Join('&', allParameters.Select(item =>
$"{Uri.EscapeDataString(item.Key)}={Uri.EscapeDataString(item.Value)}"));
var jsonp = await Http.GetStringAsync($"{endpoint.ApiUrl}{path}?{query}", cancellationToken);
var start = jsonp.IndexOf('(');
var end = jsonp.LastIndexOf(')');
if (start < 0 || end <= start)
throw new InvalidDataException("HONOR support returned invalid JSONP.");
return JsonDocument.Parse(jsonp[(start + 1)..end]);
}
private static bool TryProductList(JsonElement root, out JsonElement productList)
{
productList = default;
return Text(root, "responseCode") == "200"
&& root.TryGetProperty("responseData", out var data)
&& data.TryGetProperty("productList", out productList);
}
private static int StableSupportComponentId(string value)
{
uint hash = 2166136261;
foreach (var character in value)
hash = (hash ^ char.ToUpperInvariant(character)) * 16777619;
return 1000 + (int)(hash % 1_000_000);
}
private static int SupportComponentId(string title, string category, string categoryName)
{
var text = title + " " + categoryName;
if (text.Contains("Camera", StringComparison.OrdinalIgnoreCase)) return 76;
if (text.Contains("ISST", StringComparison.OrdinalIgnoreCase)) return 65;
if (text.Contains("IntelME", StringComparison.OrdinalIgnoreCase)) return 2;
if (text.Contains("Monitor", StringComparison.OrdinalIgnoreCase)) return 41;
if (text.Contains("MEP", StringComparison.OrdinalIgnoreCase)) return 78;
if (text.Contains("SerialIO", StringComparison.OrdinalIgnoreCase)) return 4;
if (text.Contains("VHID", StringComparison.OrdinalIgnoreCase)) return 88;
if (text.Contains("DPTF", StringComparison.OrdinalIgnoreCase)) return 6;
if (text.Contains("PPM", StringComparison.OrdinalIgnoreCase)) return 55;
if (text.Contains("TXT", StringComparison.OrdinalIgnoreCase)) return 56;
if (text.Contains("NPU", StringComparison.OrdinalIgnoreCase)) return 74;
if (text.Contains("NFC", StringComparison.OrdinalIgnoreCase)) return 52;
if (text.Contains("iPMT", StringComparison.OrdinalIgnoreCase)) return 73;
if (text.Contains("VDisplay", StringComparison.OrdinalIgnoreCase)) return 87;
if (text.Contains("WDT", StringComparison.OrdinalIgnoreCase)) return 12;
if (category == "631") return 1;
if (category == "633") return 3;
if (category == "634") return 15;