-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModVerifier.cs
More file actions
311 lines (264 loc) · 10.8 KB
/
Copy pathModVerifier.cs
File metadata and controls
311 lines (264 loc) · 10.8 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
using System.IO.Compression;
using System.Net.Http;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
namespace ModManifestEditor;
public sealed class VerificationResult
{
public required ModEntry Entry { get; init; }
public bool Ok { get; init; }
public string? Error { get; init; }
}
/// <summary>
/// Identity read straight out of a compiled mod assembly.
/// </summary>
public sealed class AssemblyIdentity
{
public required string FileName { get; init; }
public Guid? Guid { get; init; }
public List<string> Versions { get; } = new();
}
public static class ModVerifier
{
private static readonly HttpClient Http = CreateClient();
private static HttpClient CreateClient()
{
var client = new HttpClient(new HttpClientHandler
{
AllowAutoRedirect = true
})
{
Timeout = TimeSpan.FromMinutes(5)
};
client.DefaultRequestHeaders.UserAgent.ParseAdd("ModManifestEditor/1.0");
return client;
}
public static async Task<VerificationResult> VerifyAsync(
ModEntry entry, IProgress<string>? progress, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(entry.URL))
return Fail(entry, "No download URL set.");
if (!Uri.TryCreate(entry.URL, UriKind.Absolute, out var uri))
return Fail(entry, $"URL is not valid: {entry.URL}");
if (!Guid.TryParse(entry.UUID, out var expectedGuid))
return Fail(entry, $"UUID is not a valid GUID: \"{entry.UUID}\"");
if (string.IsNullOrWhiteSpace(entry.ModNumber))
return Fail(entry, "No version set.");
var workDir = Path.Combine(Path.GetTempPath(), "ModManifestEditor", Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(workDir);
try
{
progress?.Report($"Downloading {entry.Name}...");
var archivePath = Path.Combine(workDir, "download.bin");
try
{
using var response = await Http.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, ct);
if (!response.IsSuccessStatusCode)
return Fail(entry, $"Download failed: HTTP {(int)response.StatusCode} {response.ReasonPhrase}");
await using var source = await response.Content.ReadAsStreamAsync(ct);
await using var target = File.Create(archivePath);
await source.CopyToAsync(target, ct);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
return Fail(entry, $"Download failed: {ex.Message}");
}
progress?.Report($"Unpacking {entry.Name}...");
var dllPaths = new List<string>();
if (IsZip(archivePath))
{
var extractDir = Path.Combine(workDir, "extracted");
Directory.CreateDirectory(extractDir);
try
{
ZipFile.ExtractToDirectory(archivePath, extractDir);
}
catch (Exception ex)
{
return Fail(entry, $"Could not unzip the download: {ex.Message}");
}
dllPaths.AddRange(Directory.EnumerateFiles(extractDir, "*.dll", SearchOption.AllDirectories));
}
else if (uri.AbsolutePath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
{
dllPaths.Add(archivePath);
}
else
{
return Fail(entry, "Download is neither a zip archive nor a .dll.");
}
if (dllPaths.Count == 0)
return Fail(entry, "The archive contains no .dll files.");
progress?.Report($"Checking {entry.Name}...");
var identities = new List<AssemblyIdentity>();
foreach (var dll in dllPaths)
{
ct.ThrowIfCancellationRequested();
var identity = ReadIdentity(dll);
if (identity != null) identities.Add(identity);
}
if (identities.Count == 0)
return Fail(entry, "None of the .dll files in the archive are .NET assemblies.");
var match = identities.FirstOrDefault(i => i.Guid == expectedGuid);
if (match == null)
{
var found = identities
.Where(i => i.Guid != null)
.Select(i => $" {i.FileName}: {i.Guid}")
.ToList();
var detail = found.Count > 0
? "Assemblies in the archive:\n" + string.Join("\n", found)
: "No assembly in the archive declares a GUID.";
return Fail(entry, $"GUID mismatch. Manifest says {expectedGuid}.\n{detail}");
}
if (!match.Versions.Any(v => VersionsMatch(v, entry.ModNumber)))
{
var found = match.Versions.Count > 0
? string.Join(", ", match.Versions.Distinct())
: "(none declared)";
return Fail(entry,
$"Version mismatch in {match.FileName}. Manifest says \"{entry.ModNumber}\", assembly says {found}.");
}
return new VerificationResult { Entry = entry, Ok = true };
}
finally
{
TryDelete(workDir);
}
}
private static VerificationResult Fail(ModEntry entry, string error) =>
new() { Entry = entry, Ok = false, Error = error };
private static bool IsZip(string path)
{
using var stream = File.OpenRead(path);
Span<byte> header = stackalloc byte[4];
if (stream.Read(header) != 4) return false;
return header[0] == 'P' && header[1] == 'K';
}
/// <summary>
/// Reads the GUID and every version string an assembly declares, without loading it.
/// </summary>
private static AssemblyIdentity? ReadIdentity(string path)
{
try
{
using var stream = File.OpenRead(path);
using var pe = new PEReader(stream);
if (!pe.HasMetadata) return null;
var reader = pe.GetMetadataReader();
if (!reader.IsAssembly) return null;
var assembly = reader.GetAssemblyDefinition();
Guid? guid = null;
var versions = new List<string> { assembly.Version.ToString() };
foreach (var handle in assembly.GetCustomAttributes())
{
var attribute = reader.GetCustomAttribute(handle);
var name = GetAttributeTypeName(reader, attribute);
if (name == null) continue;
switch (name)
{
case "GuidAttribute":
var raw = ReadFixedStrings(reader, attribute, 1).FirstOrDefault();
if (raw != null && Guid.TryParse(raw, out var parsed)) guid = parsed;
break;
case "AssemblyFileVersionAttribute":
case "AssemblyInformationalVersionAttribute":
var value = ReadFixedStrings(reader, attribute, 1).FirstOrDefault();
if (!string.IsNullOrWhiteSpace(value)) versions.Add(value);
break;
// MelonLoader: [MelonInfo(typeof(Mod), name, version, author, downloadLink)]
case "MelonInfoAttribute":
case "MelonModInfoAttribute":
var args = ReadFixedStrings(reader, attribute, 3);
if (args.Count == 3 && !string.IsNullOrWhiteSpace(args[2])) versions.Add(args[2]);
break;
}
}
var identity = new AssemblyIdentity { FileName = Path.GetFileName(path), Guid = guid };
identity.Versions.AddRange(versions);
return identity;
}
catch
{
return null;
}
}
private static string? GetAttributeTypeName(MetadataReader reader, CustomAttribute attribute)
{
try
{
switch (attribute.Constructor.Kind)
{
case HandleKind.MemberReference:
var member = reader.GetMemberReference((MemberReferenceHandle)attribute.Constructor);
if (member.Parent.Kind != HandleKind.TypeReference) return null;
var typeRef = reader.GetTypeReference((TypeReferenceHandle)member.Parent);
return reader.GetString(typeRef.Name);
case HandleKind.MethodDefinition:
var method = reader.GetMethodDefinition((MethodDefinitionHandle)attribute.Constructor);
var typeDef = reader.GetTypeDefinition(method.GetDeclaringType());
return reader.GetString(typeDef.Name);
default:
return null;
}
}
catch
{
return null;
}
}
/// <summary>
/// Pulls the leading fixed arguments off an attribute blob, assuming they are all
/// string- or Type-typed (both are encoded as SerString).
/// </summary>
private static List<string> ReadFixedStrings(MetadataReader reader, CustomAttribute attribute, int count)
{
var values = new List<string>();
try
{
var blob = reader.GetBlobReader(attribute.Value);
if (blob.Length < 2 || blob.ReadUInt16() != 1) return values;
for (var i = 0; i < count; i++)
{
var value = blob.ReadSerializedString();
if (value == null) return values;
values.Add(value);
}
}
catch
{
// Malformed or non-string arguments - keep whatever we managed to read.
}
return values;
}
/// <summary>
/// "0.4.0" and "0.4.0.0" are the same release; "v0.4.0" and build metadata are tolerated.
/// </summary>
private static bool VersionsMatch(string a, string b)
{
var left = Normalize(a);
var right = Normalize(b);
return left.Length > 0 && left == right;
static string Normalize(string value)
{
value = value.Trim();
if (value.StartsWith("v", StringComparison.OrdinalIgnoreCase)) value = value[1..];
var cut = value.IndexOfAny(new[] { '-', '+', ' ' });
if (cut >= 0) value = value[..cut];
var parts = value.Split('.').ToList();
while (parts.Count > 1 && parts[^1] == "0") parts.RemoveAt(parts.Count - 1);
return string.Join('.', parts);
}
}
private static void TryDelete(string directory)
{
try
{
if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true);
}
catch
{
// Temp dir cleanup is best-effort.
}
}
}