feat: add checksum validation for models

Also truncate new model zips before writing, fixing a long-standing issue.
This commit is contained in:
Anna 2021-04-25 11:42:50 -04:00
parent 2f1bc76dc2
commit 9c2471ff1f
2 changed files with 32 additions and 0 deletions

View File

@ -1,9 +1,13 @@
using System;
namespace NoSoliciting.Ml {
[Serializable]
public class Manifest {
public uint Version { get; set; }
public Uri ModelUrl { get; set; }
public string ModelHash { get; set; }
public Uri ReportUrl { get; set; }
public byte[] Hash() => Convert.FromBase64String(this.ModelHash);
}
}

View File

@ -1,7 +1,9 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Dalamud.Plugin;
@ -89,6 +91,32 @@ namespace NoSoliciting.Ml {
return null;
}
// validate checksum
var retries = 0;
const int maxRetries = 3;
var correctHash = manifest!.Value.manifest!.Hash();
using (var sha = SHA256.Create()) {
var hash = sha.ComputeHash(data);
while (!hash.SequenceEqual(correctHash) && retries < maxRetries) {
PluginLog.Warning($"Model checksum did not match. Redownloading (attempt {retries + 1}/{maxRetries})");
retries += 1;
data = await DownloadModel(manifest!.Value.manifest!.ModelUrl);
if (data != null) {
hash = sha.ComputeHash(data);
}
}
}
// give up if we couldn't get any data at this point
if (data == null) {
plugin.MlStatus = MlFilterStatus.Uninitialised;
return null;
}
plugin.MlStatus = MlFilterStatus.Initialising;
// if there is source for the manifest