-
Notifications
You must be signed in to change notification settings - Fork 742
Expand file tree
/
Copy pathIntegrityTester.cs
More file actions
147 lines (130 loc) · 4.38 KB
/
IntegrityTester.cs
File metadata and controls
147 lines (130 loc) · 4.38 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
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using UniGetUI.Core.Data;
using UniGetUI.Core.Logging;
namespace UniGetUI.Core.Tools;
public static class IntegrityTester
{
public class MismatchedHash
{
public string Got = string.Empty;
public string Expected = string.Empty;
}
public struct Result
{
public bool Passed;
public IReadOnlyList<string> MissingFiles;
public Dictionary<string, MismatchedHash> CorruptedFiles;
}
private static string GetSHA256(string fullPath, bool canRetry)
{
try
{
using (var sha256 = SHA256.Create())
{
using (var stream = File.OpenRead(fullPath))
{
var hashBytes = sha256.ComputeHash(stream);
return BitConverter.ToString(hashBytes).Replace("-", "");
}
}
}
catch (Exception ex)
{
if (canRetry)
{
Task.Delay(1000).GetAwaiter().GetResult();
return GetSHA256(fullPath, false);
}
return $"{ex.GetType()}: {ex.Message}";
}
}
public static Result CheckIntegrity(bool allowRetry = true)
{
string integrityTreePath = Path.Join(CoreData.UniGetUIExecutableDirectory, "IntegrityTree.json");
if (!File.Exists(integrityTreePath))
{
Logger.Error("/IntegrityTree.json does not exist, integrity check will not be performed!");
return new()
{
Passed = false,
MissingFiles = ["/IntegrityTree.json"],
CorruptedFiles = new Dictionary<string, MismatchedHash>(),
};
}
string rawData = File.ReadAllText(integrityTreePath);
Dictionary<string, string>? data = null;
try
{
data = JsonSerializer.Deserialize<Dictionary<string, string>>(rawData, SerializationHelpers.DefaultOptions);
}
catch (Exception ex)
{
Logger.Error("Failed to deserialize JSON object");
Logger.Error(ex);
}
if (data is null)
{
return new()
{
Passed = false,
MissingFiles = [],
CorruptedFiles = new()
{ {"", new MismatchedHash() {Got = rawData, Expected = "A valid JSON"} } },
};
}
Dictionary<string, MismatchedHash> mismatches = new();
List<string> misses = new();
foreach (var (file, expectedHash) in data)
{
var fullPath = Path.Join(CoreData.UniGetUIExecutableDirectory, file);
if (!File.Exists(fullPath))
{
misses.Add($"/{file}");
Logger.Error($"File {file} expected but did not exist");
continue;
}
var currentHash = GetSHA256(fullPath, allowRetry).ToLower();
if (currentHash != expectedHash.ToLower())
{
mismatches.Add($"/{file}", new() { Expected = expectedHash, Got = currentHash });
Logger.Error($"File {file} expected to have sha256 {expectedHash}, but had {currentHash} instead");
}
}
Result result = new()
{
Passed = !misses.Any() && !mismatches.Any(),
MissingFiles = misses,
CorruptedFiles = mismatches
};
if (result.Passed)
{
Logger.ImportantInfo("Integrity check passed successfully!");
}
return result;
}
public static string GetReadableReport(Result result)
{
var Builder = new StringBuilder();
if (result.Passed)
{
Builder.Append("No integrity violations were found.\n");
}
if (result.MissingFiles.Any())
{
Builder.Append("Missing files: ");
foreach (var file in result.MissingFiles)
Builder.Append($"\n - {file}");
Builder.Append('\n');
}
if (result.CorruptedFiles.Any())
{
Builder.Append("Corrupted files: ");
foreach (var (file, hashes) in result.CorruptedFiles)
Builder.Append($"\n - {file} (sha256 mismatch, got {hashes.Got} but expected {hashes.Expected} ");
Builder.Append('\n');
}
return Builder.ToString();
}
}