Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of DwarvenDefender v0.1.0
plugins/DwarvenDefender.dll
Decompiled 2 days agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using DwarvenDefender.Core; using DwarvenDefender.Net; using HarmonyLib; using Microsoft.CodeAnalysis; using TMPro; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyCompany("DwarvenDefender")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.1.0.0")] [assembly: AssemblyInformationalVersion("0.1.0")] [assembly: AssemblyProduct("DwarvenDefender")] [assembly: AssemblyTitle("DwarvenDefender")] [assembly: AssemblyVersion("0.1.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace DwarvenDefender { [BepInPlugin("wubarrk.dwarvendefender", "DwarvenDefender", "0.1.0")] public class Plugin : BaseUnityPlugin { public const string ModGUID = "wubarrk.dwarvendefender"; public const string ModName = "DwarvenDefender"; public const string ModVersion = "0.1.0"; internal static Plugin Instance; internal static ManualLogSource Log; internal static ConfigEntry<bool> Enabled; internal static ConfigEntry<string> ListFolder; internal static ConfigEntry<bool> ExemptAdmins; internal static ConfigEntry<bool> CheckPatchers; internal static ConfigEntry<bool> KickOnListChange; internal static ConfigEntry<float> KickGraceSeconds; internal static ConfigEntry<bool> EnforceWhenHosting; internal static ConfigEntry<float> PollSeconds; internal static ConfigEntry<float> SettleSeconds; internal static ConfigEntry<bool> SaveReports; internal static string ListRoot; private readonly Harmony _harmony = new Harmony("wubarrk.dwarvendefender"); private void Awake() { //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Expected O, but got Unknown //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_014a: Expected O, but got Unknown //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Expected O, but got Unknown Instance = this; Log = ((BaseUnityPlugin)this).Logger; Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("1 - General", "Enabled", true, "Server: enforce the lists. Off = every client is let in (reports are still logged). No effect on a client."); ListFolder = ((BaseUnityPlugin)this).Config.Bind<string>("1 - General", "List folder", "DwarvenDefender", "Folder holding Whitelist/ and Greylist/. Relative paths are under BepInEx/config. Whitelist = every player MUST have every DLL in it; Greylist = a player MAY have them; any other DLL gets the player refused. Entries are compared by file contents (SHA-256), never by name."); ExemptAdmins = ((BaseUnityPlugin)this).Config.Bind<bool>("1 - General", "Exempt admins", true, "Players on the server's adminlist.txt are let in with any mods."); CheckPatchers = ((BaseUnityPlugin)this).Config.Bind<bool>("1 - General", "Check patchers", true, "Also hold DLLs under the client's BepInEx/patchers to the lists. Off = patchers are reported and logged but never refused."); EnforceWhenHosting = ((BaseUnityPlugin)this).Config.Bind<bool>("1 - General", "Enforce when hosting", false, "Also enforce when this game HOSTS a world from the main menu (Start with 'Community server'). Off = only a dedicated server enforces, so a player who hosts for friends is not suddenly checking them against empty lists."); KickOnListChange = ((BaseUnityPlugin)this).Config.Bind<bool>("2 - Hot reload", "Kick on list change", true, "When the lists change while the server runs, re-check every connected player and kick anyone who no longer matches."); KickGraceSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("2 - Hot reload", "Kick grace seconds", 30f, new ConfigDescription("After a list change, wait this long before kicking connected players, then judge them against the lists as they are THEN. Covers edits made in several steps (remove an entry, then copy its replacement in). New joins use the new lists at once. 0 = kick at once.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 600f), Array.Empty<object>())); PollSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("2 - Hot reload", "Poll seconds", 2f, new ConfigDescription("How often the list folders are checked for changes (a file watcher also wakes the check early).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 60f), Array.Empty<object>())); SettleSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("2 - Hot reload", "Settle seconds", 3f, new ConfigDescription("A change is applied only after the folders have stopped changing for this long, so half-copied files are never used.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 60f), Array.Empty<object>())); SaveReports = ((BaseUnityPlugin)this).Config.Bind<bool>("3 - Logging", "Save reports", true, "Server: write each joining player's full mod report to <List folder>/reports/<id>.txt (handy for building lists)."); ClientReporter.Begin(); _harmony.PatchAll(typeof(Plugin).Assembly); Commands.Register(); Log.LogInfo((object)"DwarvenDefender 0.1.0 loaded."); } internal static bool ShouldEnforce(ZNet znet) { if ((Object)(object)znet != (Object)null && znet.IsServer()) { if (!znet.IsDedicated()) { return EnforceWhenHosting.Value; } return true; } return false; } internal static void StartServer() { if (ServerGuard.Instance == null) { string text = ListFolder.Value.Trim(); ListRoot = Path.GetFullPath(Path.IsPathRooted(text) ? text : Path.Combine(Paths.ConfigPath, text)); ServerGuard.Create(ListRoot); } } internal static void StopServer() { ServerGuard.Instance?.Dispose(); } private void Update() { ServerGuard.Instance?.Tick(); } private void OnDestroy() { ServerGuard.Instance?.Dispose(); _harmony.UnpatchSelf(); } } } namespace DwarvenDefender.Net { internal static class ClientReporter { private static Task<ModReport> _report; internal static string LastReason; internal static void Begin() { _report = Task.Run(() => Build(null)); } private static ModReport Build(string[] extraLocations) { return ModReport.Gather(Paths.BepInExRootPath, Paths.PluginPath, Paths.PatcherPluginPath, extraLocations, "0.1.0", delegate(string msg) { Plugin.Log.LogWarning((object)msg); }); } internal static ModReport GetReport() { ModReport result; try { result = _report.Result; } catch (Exception arg) { Plugin.Log.LogError((object)$"Building the mod report failed, retrying: {arg}"); result = Build(null); } string[] array = (from p in Chainloader.PluginInfos.Values select p.Location into l where !string.IsNullOrEmpty(l) && !ModHashing.IsUnder(Paths.PluginPath, l) && !ModHashing.IsUnder(Paths.PatcherPluginPath, l) select l).Distinct<string>(StringComparer.OrdinalIgnoreCase).ToArray(); if (array.Length == 0) { return result; } return Build(array); } internal static void OnNewConnection(ZNetPeer peer) { LastReason = null; peer.m_rpc.Register<string>("DwarvenDefender_Verdict", (Action<ZRpc, string>)OnVerdict); ModReport report = GetReport(); ZPackageWriter zPackageWriter = new ZPackageWriter(); report.WriteTo(zPackageWriter); peer.m_rpc.Invoke("DwarvenDefender_Report", new object[1] { zPackageWriter.Pkg }); Plugin.Log.LogInfo((object)$"Sent mod report ({report.Files.Count} DLLs) to the server."); } private static void OnVerdict(ZRpc rpc, string reason) { LastReason = reason; Plugin.Log.LogWarning((object)("The server refused this game's mods:\n" + reason)); } } [HarmonyPatch] internal static class Commands { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static ConsoleEvent <>9__1_0; public static ConsoleEvent <>9__1_1; internal void <Register>b__1_0(ConsoleEventArgs args) { ServerGuard instance = ServerGuard.Instance; if (instance == null) { Reply("DwarvenDefender: not running as a server."); return; } instance.ForceReload(); Reply("DwarvenDefender: rescan requested; it applies once the folders have stopped changing (see the server log)."); } internal void <Register>b__1_1(ConsoleEventArgs args) { ServerGuard instance = ServerGuard.Instance; if (instance == null) { Reply("DwarvenDefender: not running as a server."); return; } string[] array = instance.Status().TrimEnd(new char[1] { '\n' }).Split(new char[1] { '\n' }); for (int i = 0; i < array.Length; i++) { Reply(array[i]); } } } private static ZRpc _caller; internal static void Register() { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown object obj = <>c.<>9__1_0; if (obj == null) { ConsoleEvent val = delegate { ServerGuard instance = ServerGuard.Instance; if (instance == null) { Reply("DwarvenDefender: not running as a server."); } else { instance.ForceReload(); Reply("DwarvenDefender: rescan requested; it applies once the folders have stopped changing (see the server log)."); } }; <>c.<>9__1_0 = val; obj = (object)val; } new ConsoleCommand("dd_reload", "[DwarvenDefender] Rescan the Whitelist/Greylist folders now.", (ConsoleEvent)obj, false, false, true, false, false, false, (ConsoleOptionsFetcher)null, false, true, false); object obj2 = <>c.<>9__1_1; if (obj2 == null) { ConsoleEvent val2 = delegate { ServerGuard instance = ServerGuard.Instance; if (instance == null) { Reply("DwarvenDefender: not running as a server."); } else { string[] array = instance.Status().TrimEnd(new char[1] { '\n' }).Split(new char[1] { '\n' }); for (int i = 0; i < array.Length; i++) { Reply(array[i]); } } }; <>c.<>9__1_1 = val2; obj2 = (object)val2; } new ConsoleCommand("dd_status", "[DwarvenDefender] Show the lists and every connected player's state.", (ConsoleEvent)obj2, false, false, true, false, false, false, (ConsoleOptionsFetcher)null, false, true, false); } private static void Reply(string text) { Plugin.Log.LogInfo((object)text); if (_caller != null && (Object)(object)ZNet.instance != (Object)null) { ZNet.instance.RemotePrint(_caller, text); return; } Console instance = Console.instance; if (instance != null) { instance.Print(text); } } [HarmonyPatch(typeof(ZNet), "InternalCommand")] [HarmonyPrefix] private static void InternalCommand_Prefix(ZRpc rpc) { _caller = rpc; } [HarmonyPatch(typeof(ZNet), "InternalCommand")] [HarmonyFinalizer] private static Exception InternalCommand_Finalizer(Exception __exception) { _caller = null; return __exception; } } [HarmonyPatch] internal static class Patches { [HarmonyPatch(typeof(ZNet), "Awake")] [HarmonyPostfix] private static void ZNet_Awake(ZNet __instance) { if (Plugin.ShouldEnforce(__instance)) { Plugin.StartServer(); } } [HarmonyPatch(typeof(ZNet), "OnDestroy")] [HarmonyPostfix] private static void ZNet_OnDestroy() { Plugin.StopServer(); } [HarmonyPatch(typeof(ZNet), "OnNewConnection", new Type[] { typeof(ZNetPeer) })] [HarmonyPostfix] private static void ZNet_OnNewConnection(ZNet __instance, ZNetPeer peer) { try { if (__instance.IsServer()) { if (ServerGuard.Instance == null && Plugin.ShouldEnforce(__instance)) { Plugin.StartServer(); } ServerGuard.Instance?.OnNewConnection(peer); } else { ClientReporter.OnNewConnection(peer); } } catch (Exception arg) { Plugin.Log.LogError((object)$"OnNewConnection: {arg}"); } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] [HarmonyPrefix] [HarmonyPriority(800)] private static bool ZNet_RPC_PeerInfo(ZNet __instance, ZRpc rpc, ZPackage pkg) { if (!Plugin.ShouldEnforce(__instance)) { return true; } try { if (ServerGuard.Instance == null) { Plugin.StartServer(); } return ServerGuard.Instance.OnPeerInfo(__instance, rpc, pkg); } catch (Exception arg) { Plugin.Log.LogError((object)$"Join check failed, refusing the connection: {arg}"); try { rpc.Invoke("Error", new object[1] { 5 }); } catch { } return false; } } [HarmonyPatch(typeof(ZNet), "Disconnect")] [HarmonyPrefix] private static void ZNet_Disconnect(ZNetPeer peer) { ServerGuard.Instance?.OnDisconnect(peer); } [HarmonyPatch(typeof(FejdStartup), "ShowConnectError")] [HarmonyPostfix] private static void FejdStartup_ShowConnectError(FejdStartup __instance) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Invalid comparison between Unknown and I4 //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Invalid comparison between Unknown and I4 //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Invalid comparison between Unknown and I4 //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Invalid comparison between Unknown and I4 //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_015b: Unknown result type (might be due to invalid IL or missing references) string lastReason = ClientReporter.LastReason; if (string.IsNullOrEmpty(lastReason)) { return; } try { if (!__instance.m_connectionFailedPanel.activeSelf) { return; } ConnectionStatus connectionStatus = ZNet.GetConnectionStatus(); if ((int)connectionStatus != 3 && (int)connectionStatus != 12 && (int)connectionStatus != 4 && (int)connectionStatus != 5) { return; } TMP_Text connectionFailedError = __instance.m_connectionFailedError; ClientReporter.LastReason = null; if (!connectionFailedError.text.Contains(lastReason)) { connectionFailedError.text = connectionFailedError.text + "\n\n" + lastReason; Transform obj = __instance.m_connectionFailedPanel.transform.Find("Image"); RectTransform val = ((obj != null) ? ((Component)obj).GetComponent<RectTransform>() : null); object obj2; if (val == null) { obj2 = null; } else { Transform obj3 = ((Component)val).transform.Find("ButtonOk"); obj2 = ((obj3 != null) ? ((Component)obj3).GetComponent<RectTransform>() : null); } RectTransform val2 = (RectTransform)obj2; if (!((Object)(object)val == (Object)null) && !((Object)(object)val2 == (Object)null)) { val.sizeDelta = new Vector2(Mathf.Max(val.sizeDelta.x, 675f), val.sizeDelta.y); connectionFailedError.ForceMeshUpdate(false, false); float num = connectionFailedError.renderedHeight + 105f; val2.anchoredPosition = new Vector2(val2.anchoredPosition.x, val2.anchoredPosition.y - (num - val.sizeDelta.y) / 2f); val.sizeDelta = new Vector2(val.sizeDelta.x, num); } } } catch (Exception ex) { Plugin.Log.LogWarning((object)("Could not show the refusal reason: " + ex.Message)); } } } internal sealed class ServerGuard : IDisposable { internal static ServerGuard Instance; private const float RefusedDisconnectDelay = 3f; private readonly ListWatcher _watcher; private readonly HashSet<string> _implicitlyAllowed = new HashSet<string>(StringComparer.Ordinal); private readonly Dictionary<ZRpc, ModReport> _reports = new Dictionary<ZRpc, ModReport>(); private readonly Dictionary<ZRpc, string> _names = new Dictionary<ZRpc, string>(); private readonly Dictionary<ZNetPeer, float> _refused = new Dictionary<ZNetPeer, float>(); private readonly HashSet<ZRpc> _refusedRpcs = new HashSet<ZRpc>(); private float _kickCheckAt = -1f; private const long RejectionLogMaxBytes = 5242880L; private readonly string _root; private float _nextPrune; private static readonly MethodInfo InternalKickPeer = AccessTools.Method(typeof(ZNet), "InternalKick", new Type[1] { typeof(ZNetPeer) }, (Type[])null); internal ListSnapshot Lists => _watcher.Current; private ServerGuard(string root) { _root = root; _watcher = new ListWatcher(root, delegate(string m) { Plugin.Log.LogInfo((object)m); }, delegate(string m) { Plugin.Log.LogWarning((object)m); }) { PollSeconds = Plugin.PollSeconds.Value, SettleSeconds = Plugin.SettleSeconds.Value }; try { string location = typeof(Plugin).Assembly.Location; if (!string.IsNullOrEmpty(location) && File.Exists(location)) { _implicitlyAllowed.Add(ModHashing.Sha256File(location)); } } catch (Exception ex) { Plugin.Log.LogWarning((object)("Could not hash DwarvenDefender's own DLL: " + ex.Message)); } } internal static void Create(string root) { ServerGuard serverGuard = new ServerGuard(root); Plugin.Log.LogInfo((object)("Server mode. Lists: " + root + (Plugin.Enabled.Value ? "" : " (ENFORCEMENT OFF: Enabled = false)"))); try { serverGuard._watcher.LoadInitial(); } catch (Exception arg) { Plugin.Log.LogError((object)$"Could not read the lists at start: {arg}. Every non-admin player will be refused until they load."); } serverGuard._watcher.Start(); Instance = serverGuard; } internal void ForceReload() { _watcher.ForceReload(); } internal void OnNewConnection(ZNetPeer peer) { peer.m_rpc.Register<ZPackage>("DwarvenDefender_Report", (Action<ZRpc, ZPackage>)OnReport); } private void OnReport(ZRpc rpc, ZPackage pkg) { if (_reports.ContainsKey(rpc)) { Plugin.Log.LogWarning((object)(Host(rpc) + " sent a second mod report; ignored (only the first counts).")); return; } ModReport value; try { value = ModReport.ReadFrom(new ZPackageReader(pkg)); } catch (Exception ex) { Plugin.Log.LogWarning((object)(Host(rpc) + " sent an unreadable mod report: " + ex.Message)); value = new ModReport { ProtocolVersion = -1 }; } _reports[rpc] = value; } internal bool OnPeerInfo(ZNet znet, ZRpc rpc, ZPackage pkg) { ZNetPeer val = ((IEnumerable<ZNetPeer>)znet.GetPeers()).FirstOrDefault((Func<ZNetPeer, bool>)((ZNetPeer p) => p.m_rpc == rpc)); if (val == null) { return true; } if (_refusedRpcs.Contains(rpc)) { _refused.Remove(val); znet.Disconnect(val); return false; } string text = Host(rpc); string text2 = PeekName(pkg); _names[rpc] = text2; _reports.TryGetValue(rpc, out var value); bool flag = IsAdmin(znet, text); Verdict verdict = Verifier.Check(value, Lists, _implicitlyAllowed, Plugin.CheckPatchers.Value); WriteReport(text, text2, value, verdict, flag); if (verdict.Allowed) { Plugin.Log.LogInfo((object)$"Allowed {text2} ({text}): {value.Files.Count} DLLs match the lists."); return true; } if (flag && Plugin.ExemptAdmins.Value) { Plugin.Log.LogInfo((object)("Allowed admin " + text2 + " (" + text + ") despite a mismatch (Exempt admins): " + verdict.LogLine())); return true; } if (!Plugin.Enabled.Value) { Plugin.Log.LogWarning((object)("Would refuse " + text2 + " (" + text + ") but enforcement is off: " + verdict.LogLine())); return true; } Refuse(val, rpc, text, text2, verdict, kicked: false); return false; } private void Refuse(ZNetPeer peer, ZRpc rpc, string host, string name, Verdict verdict, bool kicked) { string text = (kicked ? "Kicked" : "Refused"); Plugin.Log.LogWarning((object)(text + " " + name + " (" + host + "): " + verdict.LogLine())); AppendRejection(text + "\t" + name + "\t" + host + "\t" + verdict.LogLine()); try { rpc.Invoke("DwarvenDefender_Verdict", new object[1] { verdict.PlayerMessage() }); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Could not send the reason: " + ex.Message)); } if (kicked) { InternalKickPeer.Invoke(ZNet.instance, new object[1] { peer }); return; } rpc.Invoke("Error", new object[1] { 3 }); _refusedRpcs.Add(rpc); if (!_refused.ContainsKey(peer)) { _refused[peer] = Time.time + 3f; } } internal void Tick() { ListSnapshot listSnapshot = _watcher.TryTakeNew(); if (listSnapshot != null) { OnListsChanged(listSnapshot); } if (_kickCheckAt >= 0f && Time.time >= _kickCheckAt) { _kickCheckAt = -1f; RecheckConnected(Lists); } if (_refused.Count > 0 && (Object)(object)ZNet.instance != (Object)null) { foreach (KeyValuePair<ZNetPeer, float> item in _refused.Where((KeyValuePair<ZNetPeer, float> kv) => Time.time >= kv.Value).ToList()) { _refused.Remove(item.Key); if (ZNet.instance.GetPeers().Contains(item.Key) && !item.Key.IsReady()) { Plugin.Log.LogInfo((object)("Dropping refused connection " + Host(item.Key.m_rpc) + " (client did not close it).")); ZNet.instance.Disconnect(item.Key); } } } if (!(Time.time >= _nextPrune) || !((Object)(object)ZNet.instance != (Object)null)) { return; } _nextPrune = Time.time + 10f; HashSet<ZRpc> live = new HashSet<ZRpc>(from p in ZNet.instance.GetPeers() select p.m_rpc); foreach (ZRpc item2 in _reports.Keys.Where((ZRpc r) => !live.Contains(r)).ToList()) { Forget(item2); } } private void OnListsChanged(ListSnapshot lists) { if ((Object)(object)ZNet.instance == (Object)null) { return; } float value = Plugin.KickGraceSeconds.Value; if (value <= 0f || !Plugin.KickOnListChange.Value || !Plugin.Enabled.Value) { RecheckConnected(lists); return; } int num = ZNet.instance.GetPeers().Count((ZNetPeer p) => p.IsReady() && WouldKick(p, lists)); if (num != 0 || !(_kickCheckAt < 0f)) { _kickCheckAt = Time.time + value; Plugin.Log.LogWarning((object)($"Lists changed; {num} connected player(s) no longer match. Re-checking in {value:0} s (Kick grace seconds); " + "anyone still not matching then is kicked.")); } } private bool WouldKick(ZNetPeer peer, ListSnapshot lists) { if (Plugin.ExemptAdmins.Value && IsAdmin(ZNet.instance, Host(peer.m_rpc))) { return false; } _reports.TryGetValue(peer.m_rpc, out var value); return !Verifier.Check(value, lists, _implicitlyAllowed, Plugin.CheckPatchers.Value).Allowed; } private void RecheckConnected(ListSnapshot lists) { if ((Object)(object)ZNet.instance == (Object)null) { return; } List<ZNetPeer> list = (from p in ZNet.instance.GetPeers() where p.IsReady() select p).ToList(); if (list.Count == 0) { return; } if (!Plugin.KickOnListChange.Value || !Plugin.Enabled.Value) { Plugin.Log.LogInfo((object)$"Lists changed; {list.Count} connected player(s) not re-checked (Kick on list change / Enabled is off)."); return; } int num = 0; foreach (ZNetPeer item in list) { string host = Host(item.m_rpc); string name = (string.IsNullOrEmpty(item.m_playerName) ? Name(item.m_rpc) : ModReport.Clean(item.m_playerName, 64)); if (!Plugin.ExemptAdmins.Value || !IsAdmin(ZNet.instance, host)) { _reports.TryGetValue(item.m_rpc, out var value); Verdict verdict = Verifier.Check(value, lists, _implicitlyAllowed, Plugin.CheckPatchers.Value); if (!verdict.Allowed) { Refuse(item, item.m_rpc, host, name, verdict, kicked: true); num++; } } } Plugin.Log.LogInfo((object)$"Lists changed; re-checked {list.Count} connected player(s), kicked {num}."); } internal void Forget(ZRpc rpc) { _reports.Remove(rpc); _names.Remove(rpc); _refusedRpcs.Remove(rpc); } internal void OnDisconnect(ZNetPeer peer) { if (peer != null) { _refused.Remove(peer); if (peer.m_rpc != null) { Forget(peer.m_rpc); } } } internal string Status() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("DwarvenDefender 0.1.0: " + (Plugin.Enabled.Value ? "enforcing" : "OFF (log only)") + ", lists at " + _root + "\n"); stringBuilder.Append(Lists.Summary).Append($", loaded {Lists.LoadedUtc:u}\n"); if ((Object)(object)ZNet.instance == (Object)null) { return stringBuilder.ToString(); } foreach (ZNetPeer peer in ZNet.instance.GetPeers()) { string text = Host(peer.m_rpc); _reports.TryGetValue(peer.m_rpc, out var value); Verdict verdict = Verifier.Check(value, Lists, _implicitlyAllowed, Plugin.CheckPatchers.Value); string text2 = (string.IsNullOrEmpty(peer.m_playerName) ? Name(peer.m_rpc) : ModReport.Clean(peer.m_playerName, 64)); string text3 = (IsAdmin(ZNet.instance, text) ? " [admin]" : ""); stringBuilder.Append(" " + text2 + " (" + text + ")" + text3 + ": " + (verdict.Allowed ? "OK" : verdict.LogLine()) + "\n"); } return stringBuilder.ToString(); } private static bool IsAdmin(ZNet znet, string host) { try { return !string.IsNullOrEmpty(host) && znet.IsAdmin(host); } catch { return false; } } private static string Host(ZRpc rpc) { try { object obj; if (rpc == null) { obj = null; } else { ISocket socket = rpc.GetSocket(); obj = ((socket != null) ? socket.GetHostName() : null); } if (obj == null) { obj = "?"; } return (string)obj; } catch { return "?"; } } private string Name(ZRpc rpc) { if (rpc == null || !_names.TryGetValue(rpc, out var value)) { return "?"; } return value; } private static string PeekName(ZPackage pkg) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) int pos = pkg.GetPos(); try { pkg.ReadLong(); pkg.ReadString(); pkg.ReadUInt(); pkg.ReadVector3(); return ModReport.Clean(pkg.ReadString(), 64); } catch { return "?"; } finally { pkg.SetPos(pos); } } private void WriteReport(string host, string name, ModReport report, Verdict verdict, bool admin) { if (!Plugin.SaveReports.Value) { return; } try { string text = Path.Combine(_root, "reports"); Directory.CreateDirectory(text); string text2 = new string(host.Select((char c) => (!char.IsLetterOrDigit(c) && c != '_' && c != '-') ? '_' : c).ToArray()); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(string.Format("# {0:yyyy-MM-dd HH:mm:ss} {1} {2}{3}\n", DateTime.Now, name, host, admin ? " [admin]" : "")); stringBuilder.Append("# verdict: " + verdict.LogLine() + "\n"); if (report != null) { stringBuilder.Append($"# DwarvenDefender {report.DefenderVersion}, protocol {report.ProtocolVersion}, {report.Files.Count} DLLs\n"); foreach (ReportedFile file in report.Files) { string text3 = (Lists.Whitelist.ContainsKey(file.Hash) ? "WHITE" : (Lists.Greylist.ContainsKey(file.Hash) ? "GREY " : (_implicitlyAllowed.Contains(file.Hash) ? "SELF " : "NONE "))); stringBuilder.Append(text3 + " " + file.Hash + " " + file.Path + "\n"); } } File.WriteAllText(Path.Combine(text, text2 + ".txt"), stringBuilder.ToString()); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Could not save the report for " + host + ": " + ex.Message)); } } private void AppendRejection(string line) { try { string text = Path.Combine(_root, "rejections.log"); FileInfo fileInfo = new FileInfo(text); if (fileInfo.Exists && fileInfo.Length > 5242880) { string text2 = text + ".1"; if (File.Exists(text2)) { File.Delete(text2); } File.Move(text, text2); } File.AppendAllText(text, $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}\t{line.Replace('\r', ' ').Replace('\n', ' ')}\n"); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Could not write rejections.log: " + ex.Message)); } } public void Dispose() { _watcher.Dispose(); if (Instance == this) { Instance = null; } } } internal sealed class ZPackageWriter : ModReport.IWriter { public readonly ZPackage Pkg = new ZPackage(); public void Write(int v) { Pkg.Write(v); } public void Write(string s) { Pkg.Write(s); } } internal sealed class ZPackageReader : ModReport.IReader { private readonly ZPackage _pkg; public ZPackageReader(ZPackage pkg) { _pkg = pkg; } public int ReadInt() { return _pkg.ReadInt(); } public string ReadString() { return _pkg.ReadString(); } } internal static class Rpcs { public const string Report = "DwarvenDefender_Report"; public const string Verdict = "DwarvenDefender_Verdict"; } } namespace DwarvenDefender.Core { public sealed class ListWatcher : IDisposable { public readonly string Root; public double PollSeconds = 2.0; public double SettleSeconds = 3.0; private readonly Action<string> _info; private readonly Action<string> _warn; private volatile ListSnapshot _current; private ListSnapshot _pending; private readonly object _pendingLock = new object(); private readonly AutoResetEvent _wake = new AutoResetEvent(initialState: false); private volatile bool _stop; private volatile bool _force; private Thread _thread; private FileSystemWatcher _fsw; private string _refusedFingerprint; private const double FailedRetrySeconds = 30.0; public ListSnapshot Current => _current; public ListWatcher(string root, Action<string> info, Action<string> warn) { Root = root; _info = info ?? ((Action<string>)delegate { }); _warn = warn ?? ((Action<string>)delegate { }); _current = ListSnapshot.Empty; } public ListSnapshot LoadInitial() { Directory.CreateDirectory(Path.Combine(Root, "Whitelist")); Directory.CreateDirectory(Path.Combine(Root, "Greylist")); string fingerprint = ListLoader.Fingerprint(Root); ListSnapshot listSnapshot = (_current = ListLoader.Load(Root, fingerprint)); Report(listSnapshot, "Loaded"); return listSnapshot; } public void Start() { if (_thread != null) { return; } try { _fsw = new FileSystemWatcher(Root) { IncludeSubdirectories = true, NotifyFilter = (NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Size | NotifyFilters.LastWrite) }; FileSystemEventHandler value = delegate(object s, FileSystemEventArgs e) { if (Relevant(e.FullPath)) { _wake.Set(); } }; _fsw.Changed += value; _fsw.Created += value; _fsw.Deleted += value; _fsw.Renamed += delegate(object s, RenamedEventArgs e) { if (Relevant(e.FullPath) || Relevant(e.OldFullPath)) { _wake.Set(); } }; _fsw.Error += delegate { _wake.Set(); }; _fsw.EnableRaisingEvents = true; } catch (Exception ex) { _fsw = null; _warn($"File watcher unavailable ({ex.Message}); relying on polling every {PollSeconds}s."); } _thread = new Thread(Loop) { IsBackground = true, Name = "DwarvenDefender.ListWatcher" }; _thread.Start(); } public void ForceReload() { _force = true; _wake.Set(); } public ListSnapshot TryTakeNew() { lock (_pendingLock) { ListSnapshot pending = _pending; _pending = null; return pending; } } private bool Relevant(string path) { if (string.IsNullOrEmpty(path)) { return false; } string[] array = new string[2] { "Whitelist", "Greylist" }; foreach (string path2 in array) { string text = Path.Combine(Root, path2); if (string.Equals(path, text, StringComparison.OrdinalIgnoreCase) || ModHashing.IsUnder(text, path)) { return true; } } return false; } private void Loop() { string text = null; DateTime dateTime = DateTime.MinValue; string text2 = null; DateTime dateTime2 = DateTime.MinValue; while (!_stop) { _wake.WaitOne(TimeSpan.FromSeconds(Math.Max(0.25, PollSeconds))); if (_stop) { break; } string text3 = null; try { text3 = ListLoader.Fingerprint(Root); bool force = _force; if (!force && text3 == text2 && (DateTime.UtcNow - dateTime2).TotalSeconds < 30.0) { continue; } if (!force && text3 == _current.Fingerprint) { text = null; continue; } if (text3 != text) { text = text3; dateTime = DateTime.UtcNow; FinePoll(); continue; } if ((DateTime.UtcNow - dateTime).TotalSeconds < SettleSeconds) { FinePoll(); continue; } _force = false; if (RefuseVanishedList(text3)) { continue; } ListSnapshot listSnapshot = ListLoader.Load(Root, text3); string text4 = ListLoader.Fingerprint(Root); if (text4 != text3) { text = text4; dateTime = DateTime.UtcNow; FinePoll(); continue; } text = null; text2 = null; _refusedFingerprint = null; _current = listSnapshot; lock (_pendingLock) { _pending = listSnapshot; } Report(listSnapshot, force ? "Reloaded (forced)" : "Reloaded"); } catch (Exception ex) when (ex is FileNotFoundException || ex is DirectoryNotFoundException) { text = null; FinePoll(); } catch (Exception ex2) { if (text3 == null || text3 != text2) { _warn($"List reload failed, keeping the previous lists (retrying every {30.0:0}s until it reads): {ex2.Message}"); } text2 = text3; dateTime2 = DateTime.UtcNow; _force = false; } } } private void FinePoll() { Thread.Sleep(250); if (!_stop) { _wake.Set(); } } private bool RefuseVanishedList(string fp) { ListSnapshot current = _current; bool flag = fp.Contains("Whitelist:missing") && current.WhitelistFileCount > 0; bool flag2 = fp.Contains("Greylist:missing") && current.GreylistFileCount > 0; if (!flag && !flag2) { return false; } if (_refusedFingerprint != fp) { _refusedFingerprint = fp; _warn("The " + (flag ? "Whitelist" : "Greylist") + " folder under " + Root + " disappeared; keeping the previous lists. To clear a list, empty the folder instead of deleting it."); } return true; } private void Report(ListSnapshot snap, string verb) { _info(verb + ": " + snap.Summary); foreach (string warning in snap.Warnings) { _warn(warning); } } public void Dispose() { _stop = true; _wake.Set(); try { _fsw?.Dispose(); } catch { } _thread?.Join(2000); } } public static class ModHashing { public static string Sha256File(string path) { using SHA256 sHA = SHA256.Create(); using FileStream inputStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); return ToHex(sHA.ComputeHash(inputStream)); } public static string ToHex(byte[] bytes) { StringBuilder stringBuilder = new StringBuilder(bytes.Length * 2); foreach (byte b in bytes) { stringBuilder.Append(b.ToString("x2")); } return stringBuilder.ToString(); } public static bool IsDll(string path) { return string.Equals(Path.GetExtension(path), ".dll", StringComparison.OrdinalIgnoreCase); } public static List<string> FindDlls(string root) { List<string> list = new List<string>(); if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) { return list; } string[] files = Directory.GetFiles(root, "*", SearchOption.AllDirectories); foreach (string text in files) { if (IsDll(text)) { list.Add(text); } } list.Sort(StringComparer.Ordinal); return list; } public static string Relative(string root, string path) { string text = Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); char directorySeparatorChar = Path.DirectorySeparatorChar; string text2 = text + directorySeparatorChar; string fullPath = Path.GetFullPath(path); return (fullPath.StartsWith(text2, StringComparison.OrdinalIgnoreCase) ? fullPath.Substring(text2.Length) : Path.GetFileName(fullPath)).Replace('\\', '/'); } public static bool IsUnder(string root, string path) { if (string.IsNullOrEmpty(root) || string.IsNullOrEmpty(path)) { return false; } string text = Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); char directorySeparatorChar = Path.DirectorySeparatorChar; string value = text + directorySeparatorChar; return Path.GetFullPath(path).StartsWith(value, StringComparison.OrdinalIgnoreCase); } } public sealed class ListedFile { public string Hash; public string Entry; public string RelPath; public ListedFile(string hash, string entry, string relPath) { Hash = hash; Entry = entry; RelPath = relPath; } } public sealed class ListSnapshot { public readonly Dictionary<string, List<ListedFile>> Whitelist; public readonly Dictionary<string, List<ListedFile>> Greylist; public readonly int WhitelistFileCount; public readonly int GreylistFileCount; public readonly int WhitelistEntryCount; public readonly int GreylistEntryCount; public readonly string Fingerprint; public readonly DateTime LoadedUtc; public readonly List<string> Warnings; public static readonly ListSnapshot Empty = new ListSnapshot(new List<ListedFile>(), new List<ListedFile>(), "", new List<string>()); public string Summary => $"Whitelist {WhitelistEntryCount} entries / {WhitelistFileCount} DLLs ({Whitelist.Count} unique), " + $"Greylist {GreylistEntryCount} entries / {GreylistFileCount} DLLs ({Greylist.Count} unique)"; public ListSnapshot(List<ListedFile> white, List<ListedFile> grey, string fingerprint, List<string> warnings) { Whitelist = Index(white); Greylist = Index(grey); WhitelistFileCount = white.Count; GreylistFileCount = grey.Count; WhitelistEntryCount = white.Select((ListedFile f) => f.Entry).Distinct<string>(StringComparer.OrdinalIgnoreCase).Count(); GreylistEntryCount = grey.Select((ListedFile f) => f.Entry).Distinct<string>(StringComparer.OrdinalIgnoreCase).Count(); Fingerprint = fingerprint; LoadedUtc = DateTime.UtcNow; Warnings = warnings; } private static Dictionary<string, List<ListedFile>> Index(List<ListedFile> files) { Dictionary<string, List<ListedFile>> dictionary = new Dictionary<string, List<ListedFile>>(StringComparer.Ordinal); foreach (ListedFile file in files) { if (!dictionary.TryGetValue(file.Hash, out var value)) { value = (dictionary[file.Hash] = new List<ListedFile>()); } value.Add(file); } return dictionary; } } public static class ListLoader { public const string WhitelistDir = "Whitelist"; public const string GreylistDir = "Greylist"; public static string Fingerprint(string root) { StringBuilder stringBuilder = new StringBuilder(); string[] array = new string[2] { "Whitelist", "Greylist" }; foreach (string text in array) { string text2 = Path.Combine(root, text); bool flag = Directory.Exists(text2); stringBuilder.Append(text).Append(flag ? ":present\n" : ":missing\n"); if (!flag) { continue; } foreach (string item in ModHashing.FindDlls(text2)) { long length; long ticks; try { FileInfo fileInfo = new FileInfo(item); length = fileInfo.Length; ticks = fileInfo.LastWriteTimeUtc.Ticks; } catch (FileNotFoundException) { continue; } catch (DirectoryNotFoundException) { continue; } stringBuilder.Append(ModHashing.Relative(text2, item)).Append('|').Append(length) .Append('|') .Append(ticks) .Append('\n'); } } return stringBuilder.ToString(); } public static ListSnapshot Load(string root, string fingerprint) { List<string> list = new List<string>(); List<ListedFile> list2 = LoadOne(Path.Combine(root, "Whitelist"), list); List<ListedFile> list3 = LoadOne(Path.Combine(root, "Greylist"), list); HashSet<string> whiteHashes = new HashSet<string>(list2.Select((ListedFile f) => f.Hash), StringComparer.Ordinal); foreach (ListedFile item in list3.Where((ListedFile g) => whiteHashes.Contains(g.Hash))) { list.Add("Greylist/" + item.RelPath + " is also on the Whitelist (same contents); the Whitelist wins, so players MUST have it."); } foreach (ListedFile item2 in list2.Concat(list3)) { if (item2.RelPath.IndexOf('/') < 0) { list.Add(item2.RelPath + " sits loose in a list folder; it counts as its own entry. Put it in a <Owner>-<Name>-<version>/ folder."); } } return new ListSnapshot(list2, list3, fingerprint, list); } private static List<ListedFile> LoadOne(string dir, List<string> warnings) { List<ListedFile> list = new List<ListedFile>(); if (!Directory.Exists(dir)) { return list; } foreach (string item in ModHashing.FindDlls(dir)) { string text = ModHashing.Relative(dir, item); int num = text.IndexOf('/'); string entry = ((num < 0) ? text : text.Substring(0, num)); string hash; try { hash = ModHashing.Sha256File(item); } catch (FileNotFoundException) { throw; } catch (DirectoryNotFoundException) { throw; } catch (Exception ex3) { throw new IOException("cannot read " + Path.GetFileName(dir) + "/" + text + ": " + ex3.GetType().Name + ": " + ex3.Message, ex3); } list.Add(new ListedFile(hash, entry, text)); } return list; } } public enum FileKind { Plugin, Patcher } public sealed class ReportedFile { public string Hash; public string Path; public FileKind Kind; public ReportedFile(string hash, string path, FileKind kind) { Hash = hash; Path = path; Kind = kind; } public override string ToString() { return $"{Kind} {Hash} {Path}"; } } public sealed class ModReport { public interface IWriter { void Write(int v); void Write(string s); } public interface IReader { int ReadInt(); string ReadString(); } public const int Protocol = 1; public int ProtocolVersion = 1; public string DefenderVersion = ""; public List<ReportedFile> Files = new List<ReportedFile>(); public const int MaxFiles = 4096; public static ModReport Gather(string bepinexRoot, string pluginsDir, string patchersDir, IEnumerable<string> extraPluginLocations, string defenderVersion, Action<string> warn = null) { ModReport report = new ModReport { DefenderVersion = (defenderVersion ?? "") }; HashSet<string> seen = new HashSet<string>((Path.DirectorySeparatorChar == '\\') ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); foreach (string item in ModHashing.FindDlls(pluginsDir)) { Add(item, FileKind.Plugin); } foreach (string item2 in ModHashing.FindDlls(patchersDir)) { Add(item2, FileKind.Patcher); } if (extraPluginLocations != null) { foreach (string extraPluginLocation in extraPluginLocations) { if (!string.IsNullOrEmpty(extraPluginLocation) && File.Exists(extraPluginLocation)) { Add(extraPluginLocation, FileKind.Plugin); } } } report.Files.Sort((ReportedFile a, ReportedFile b) => string.CompareOrdinal(a.Path, b.Path)); return report; void Add(string file, FileKind kind) { string fullPath; try { fullPath = Path.GetFullPath(file); } catch { return; } if (!seen.Add(fullPath)) { return; } try { string path = (ModHashing.IsUnder(bepinexRoot, fullPath) ? ModHashing.Relative(bepinexRoot, fullPath) : ("external/" + Path.GetFileName(fullPath))); report.Files.Add(new ReportedFile(ModHashing.Sha256File(fullPath), path, kind)); } catch (Exception ex) { warn?.Invoke("Could not hash " + fullPath + ": " + ex.Message); report.Files.Add(new ReportedFile("unreadable:" + Path.GetFileName(fullPath), "unreadable/" + Path.GetFileName(fullPath), kind)); } } } public void WriteTo(IWriter w) { w.Write(ProtocolVersion); w.Write(DefenderVersion ?? ""); w.Write(Files.Count); foreach (ReportedFile file in Files) { w.Write((int)file.Kind); w.Write(file.Hash ?? ""); w.Write(file.Path ?? ""); } } public static ModReport ReadFrom(IReader r) { ModReport modReport = new ModReport { ProtocolVersion = r.ReadInt() }; if (modReport.ProtocolVersion != 1) { return modReport; } modReport.DefenderVersion = Clip(r.ReadString(), 64); int num = r.ReadInt(); if (num < 0 || num > 4096) { throw new InvalidDataException($"file count {num} out of range"); } for (int i = 0; i < num; i++) { int num2 = r.ReadInt(); if (num2 != 0 && num2 != 1) { throw new InvalidDataException($"bad file kind {num2}"); } string hash = Clip(r.ReadString(), 128).ToLowerInvariant(); string path = Clip(r.ReadString(), 260); modReport.Files.Add(new ReportedFile(hash, path, (FileKind)num2)); } return modReport; } private static string Clip(string s, int max) { return Clean(s, max); } public static string Clean(string s, int max) { if (string.IsNullOrEmpty(s)) { return ""; } StringBuilder stringBuilder = new StringBuilder(Math.Min(s.Length, max)); foreach (char c in s) { if (stringBuilder.Length >= max) { break; } stringBuilder.Append((char.IsControl(c) || c == '<' || c == '>') ? '_' : c); } return stringBuilder.ToString(); } } public sealed class Verdict { public bool Allowed; public bool ReportMissing; public string ProtocolProblem = ""; public List<string> Missing = new List<string>(); public List<string> Forbidden = new List<string>(); public static Verdict Ok() { return new Verdict { Allowed = true }; } public string PlayerMessage(int maxPerSection = 12) { if (Allowed) { return ""; } StringBuilder stringBuilder = new StringBuilder("<color=orange>DwarvenDefender: your mods do not match this server.</color>"); if (ReportMissing) { stringBuilder.Append('\n').Append(ProtocolProblem); return stringBuilder.ToString(); } AppendSection(stringBuilder, "Missing (required)", Missing, maxPerSection); AppendSection(stringBuilder, "Not allowed (remove)", Forbidden, maxPerSection); return stringBuilder.ToString(); } public string LogLine() { if (Allowed) { return "allowed"; } if (ReportMissing) { return ProtocolProblem; } return "missing [" + Capped(Missing) + "] forbidden [" + Capped(Forbidden) + "]"; } private static string Capped(List<string> items, int max = 20) { return string.Join(", ", items.Take(max)) + ((items.Count > max) ? $", ... +{items.Count - max} more" : ""); } private static void AppendSection(StringBuilder sb, string title, List<string> items, int max) { if (items.Count == 0) { return; } sb.Append("\n<color=yellow>").Append(title).Append(":</color>"); foreach (string item in items.Take(max)) { sb.Append("\n ").Append(item); } if (items.Count > max) { sb.Append($"\n ... and {items.Count - max} more"); } } } public static class Verifier { public static Verdict Check(ModReport report, ListSnapshot lists, ICollection<string> implicitlyAllowed, bool checkPatchers) { if (report == null) { return new Verdict { ReportMissing = true, ProtocolProblem = "DwarvenDefender is not installed (or did not report). Install the server's modpack." }; } if (report.ProtocolVersion != 1) { return new Verdict { ReportMissing = true, ProtocolProblem = $"DwarvenDefender version mismatch (yours speaks protocol {report.ProtocolVersion}, server {1}). Update the modpack." }; } Verdict verdict = new Verdict(); HashSet<string> hashSet = new HashSet<string>(report.Files.Select((ReportedFile f) => f.Hash), StringComparer.Ordinal); foreach (KeyValuePair<string, List<ListedFile>> item in lists.Whitelist.OrderBy<KeyValuePair<string, List<ListedFile>>, string>((KeyValuePair<string, List<ListedFile>> k) => k.Value[0].Entry, StringComparer.OrdinalIgnoreCase).ThenBy<KeyValuePair<string, List<ListedFile>>, string>((KeyValuePair<string, List<ListedFile>> k) => k.Value[0].RelPath, StringComparer.OrdinalIgnoreCase)) { if (!hashSet.Contains(item.Key)) { ListedFile listedFile = item.Value[0]; string text = listedFile.RelPath.Substring(listedFile.RelPath.LastIndexOf('/') + 1); verdict.Missing.Add((listedFile.RelPath.IndexOf('/') < 0) ? text : (listedFile.Entry + " (" + text + ")")); } } foreach (ReportedFile file in report.Files) { if ((checkPatchers || file.Kind != FileKind.Patcher) && !lists.Whitelist.ContainsKey(file.Hash) && !lists.Greylist.ContainsKey(file.Hash) && (implicitlyAllowed == null || !implicitlyAllowed.Contains(file.Hash))) { verdict.Forbidden.Add(file.Path); } } verdict.Allowed = verdict.Missing.Count == 0 && verdict.Forbidden.Count == 0; return verdict; } } }