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 ValheimDeathBan v1.3.0
ValheimDeathBan.dll
Decompiled a month agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Net.Http; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("ValheimDeathBan")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ValheimDeathBan")] [assembly: AssemblyCopyright("Copyright © 2026")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("F05960A1-C2AA-4AEB-BA68-6DC9426B2BC0")] [assembly: AssemblyFileVersion("1.3.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.3.0.0")] namespace ValheimDeathBan; internal sealed class DeathAnnouncementUi : IDisposable { private readonly Queue<string> _messages = new Queue<string>(); private readonly ManualLogSource _log; private Component _label; private float _until; private float _retryAt; private bool _fontWarning; internal DeathAnnouncementUi(ManualLogSource log) { _log = log; } internal void Enqueue(string text) { if (_messages.Count >= 100) { _messages.Dequeue(); } _messages.Enqueue(text); } internal void Tick(float seconds, float fontSize) { //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_label != (Object)null && Time.realtimeSinceStartup < _until) { return; } if ((Object)(object)_label != (Object)null) { _label.gameObject.SetActive(false); } if (_messages.Count == 0 || Time.realtimeSinceStartup < _retryAt) { return; } try { if ((Object)(object)_label == (Object)null && !CreateLabel()) { _retryAt = Time.realtimeSinceStartup + 1f; return; } fontSize = Mathf.Clamp(fontSize, 16f, 120f); Set("fontSizeMin", fontSize * 0.5f); Set("fontSizeMax", fontSize); Set("fontSize", fontSize); RectTransform component = _label.GetComponent<RectTransform>(); if ((Object)(object)component != (Object)null) { component.sizeDelta = new Vector2(0f, Mathf.Max(180f, fontSize * 3f)); } Set("text", _messages.Peek()); _messages.Dequeue(); _label.gameObject.SetActive(true); Component component2 = _label.GetComponent("CanvasRenderer"); ((object)component2)?.GetType().GetMethod("SetColor", new Type[1] { typeof(Color) })?.Invoke(component2, new object[1] { Color.white }); _label.transform.SetAsLastSibling(); _until = Time.realtimeSinceStartup + seconds; } catch (Exception ex) { _retryAt = Time.realtimeSinceStartup + 10f; _log.LogWarning((object)("Death banner UI failed: " + ex.GetType().Name)); } } private bool CreateLabel() { //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)MessageHud.instance == (Object)null) { return false; } object? obj = typeof(MessageHud).GetField("m_messageCenterText", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(MessageHud.instance); Component val = (Component)((obj is Component) ? obj : null); if ((Object)(object)val == (Object)null) { return false; } Transform parent = val.transform.parent; while ((Object)(object)parent != (Object)null && (Object)(object)((Component)parent).GetComponent("Canvas") == (Object)null) { parent = parent.parent; } if ((Object)(object)parent == (Object)null) { return false; } GameObject val2 = Object.Instantiate<GameObject>(val.gameObject, parent, false); ((Object)val2).name = "ValheimDeathBanAnnouncement"; _label = val2.GetComponent(((object)val).GetType()); RectTransform component = val2.GetComponent<RectTransform>(); component.anchorMin = new Vector2(0.05f, 1f); component.anchorMax = new Vector2(0.95f, 1f); component.pivot = new Vector2(0.5f, 1f); component.sizeDelta = new Vector2(0f, 180f); component.anchoredPosition = new Vector2(0f, -60f); ((Transform)component).localScale = Vector3.one; Set("richText", false); Set("raycastTarget", false); Set("enableAutoSizing", true); Set("fontSizeMin", 30f); Set("fontSizeMax", 60f); Set("fontSize", 60f); Set("color", (object)new Color(1f, 0.12f, 0.12f, 1f)); Set("alpha", 1f); Set("outlineColor", Color.black); Set("outlineWidth", 0.18f); PropertyInfo property = ((object)_label).GetType().GetProperty("alignment"); if (property != null) { property.SetValue(_label, Enum.Parse(property.PropertyType, "Center"), null); } PropertyInfo property2 = ((object)_label).GetType().GetProperty("font"); Object val3 = null; if (property2 != null) { Object[] array = Resources.FindObjectsOfTypeAll(property2.PropertyType); foreach (Object val4 in array) { if (val4.name.Equals("Valheim-Norsebold", StringComparison.OrdinalIgnoreCase)) { val3 = val4; break; } } } if (val3 != (Object)null) { property2.SetValue(_label, val3, null); } PropertyInfo property3 = ((object)_label).GetType().GetProperty("fontStyle"); if (property3 != null) { property3.SetValue(_label, Enum.Parse(property3.PropertyType, "Bold"), null); } if (val3 == (Object)null && !_fontWarning) { _fontWarning = true; _log.LogWarning((object)"Norse font asset not found; death banner uses the game's message font."); } val2.SetActive(false); return true; } private void Set(string property, object value) { PropertyInfo property2 = ((object)_label).GetType().GetProperty(property); if (property2 != null && property2.CanWrite) { property2.SetValue(_label, value, null); } } public void Dispose() { _messages.Clear(); if ((Object)(object)_label != (Object)null) { Object.Destroy((Object)(object)_label.gameObject); } _label = null; } } internal static class DeathMessageFormatter { private static readonly Dictionary<string, string> Names = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); private static bool _loaded; private static float _nextLoad; private static bool _warned; private static readonly Dictionary<string, string> EnglishNames = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); internal static void InitializeRussianNames() { if (!_loaded && !(Time.realtimeSinceStartup < _nextLoad)) { _nextLoad = Time.realtimeSinceStartup + 10f; LoadRussianTables(); } } internal static bool UsesRussianNames() { try { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { Type type = assemblies[i].GetType("Localization"); if (!(type == null)) { object obj = type.GetField("m_instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(null); MethodInfo method = type.GetMethod("GetSelectedLanguage", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); return obj != null && string.Equals(method?.Invoke(obj, null) as string, "Russian", StringComparison.OrdinalIgnoreCase); } } } catch { } return false; } internal static string Format(string player, string reason) { return Format(player, reason, UsesRussianNames()); } internal static string Format(string player, string reason, bool russian) { reason = reason ?? ""; int num = reason.IndexOf('['); int num2 = reason.IndexOf(']'); string text = ((num >= 0 && num2 > num) ? reason.Substring(num + 1, num2 - num - 1) : ""); switch (text) { case "PlayerHit": { int num4 = reason.IndexOf("; attacker=", StringComparison.Ordinal); string text2 = ((num4 >= 0) ? reason.Substring(num4 + 11).Trim() : ""); if (!string.IsNullOrWhiteSpace(text2)) { return Safe("Игрок " + text2 + " убил игрока " + player); } return Safe("Неизвестный игрок убил игрока " + player); } case "EnemyHit": { int num3 = reason.IndexOf("; attacker=", StringComparison.Ordinal); return Safe(((num3 >= 0) ? CreatureName(reason.Substring(num3 + 11).Trim(), russian) : (russian ? "Неизвестное существо" : "Unknown creature")) + " убивает " + player); } default: switch (text.Length) { case 8: switch (text[0]) { case 'F': if (!(text == "Freezing")) { break; } return Safe(player + " замёрз"); case 'P': if (!(text == "Poisoned")) { break; } return Safe(player + " отравился"); case 'D': if (!(text == "Drowning")) { break; } return Safe(player + " утонул"); } break; case 4: switch (text[0]) { case 'F': if (!(text == "Fall")) { break; } return Safe(player + " разбился"); case 'T': if (!(text == "Tree")) { break; } return Safe("Дерево придавило " + player); } break; case 7: if (!(text == "Burning")) { break; } goto IL_01e6; case 10: { if (!(text == "CinderFire")) { break; } goto IL_01e6; } IL_01e6: return Safe(player + " сгорел"); } break; case null: break; } return Safe(player + " усоп"); } private static string CreatureName(string value, bool russian) { InitializeRussianNames(); if ((russian ? Names : EnglishNames).TryGetValue(value.TrimStart(new char[1] { '$' }), out var value2)) { return value2; } string text; if (!russian) { if (!value.StartsWith("$", StringComparison.Ordinal) && !value.StartsWith("enemy_", StringComparison.OrdinalIgnoreCase)) { bool flag = false; text = value; foreach (char c in text) { if (c >= 'Ѐ' && c <= 'ӿ') { flag = true; } } if (!flag) { return value; } } return "Unknown creature"; } text = value; foreach (char c2 in text) { if (c2 >= 'Ѐ' && c2 <= 'ӿ') { return value; } } return "Неизвестное существо"; } private static void LoadRussianTables() { if (_loaded) { return; } try { Type type = null; Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { type = assemblies[i].GetType("Localization"); if (type != null) { break; } } if (type == null) { return; } FieldInfo field = type.GetField("m_instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (field != null && field.GetValue(null) == null) { return; } object obj = type.GetField("m_localizationSettings", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(null); if (obj == null) { return; } if (!(obj.GetType().GetProperty("Localizations", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(obj, null) is IEnumerable enumerable)) { throw new MissingMemberException("LocalizationSettings.Localizations"); } MethodInfo method = type.GetMethod("LoadCSV", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[2] { typeof(TextAsset), typeof(string) }, null); FieldInfo field2 = type.GetField("m_translations", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (method == null || field2 == null) { throw new MissingMemberException("Localization.LoadCSV/m_translations"); } object uninitializedObject = FormatterServices.GetUninitializedObject(type); field2.SetValue(uninitializedObject, new Dictionary<string, string>()); int num = 0; foreach (object item in enumerable) { TextAsset val = (TextAsset)((item is TextAsset) ? item : null); if (!((Object)(object)val == (Object)null) && (bool)method.Invoke(uninitializedObject, new object[2] { val, "Russian" })) { num++; } } if (num == 0) { throw new InvalidOperationException("No Russian localization files available"); } Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); for (int i = 0; i < fields.Length; i++) { if (!(fields[i].GetValue(uninitializedObject) is IDictionary dictionary2)) { continue; } foreach (DictionaryEntry item2 in dictionary2) { string text = item2.Key as string; string text2 = item2.Value as string; if (text == null || string.IsNullOrWhiteSpace(text2)) { continue; } text = text.TrimStart(new char[1] { '$' }); if (!text.StartsWith("enemy_", StringComparison.OrdinalIgnoreCase)) { continue; } bool flag = false; string text3 = text2; foreach (char c in text3) { if (c >= 'Ѐ' && c <= 'ӿ') { flag = true; break; } } if (flag) { dictionary[text] = text2; } } } if (dictionary.Count == 0) { throw new InvalidOperationException("Russian creature translation table is not ready"); } foreach (KeyValuePair<string, string> item3 in dictionary) { Names[item3.Key] = item3.Value; } object uninitializedObject2 = FormatterServices.GetUninitializedObject(type); field2.SetValue(uninitializedObject2, new Dictionary<string, string>()); foreach (object item4 in enumerable) { TextAsset val2 = (TextAsset)((item4 is TextAsset) ? item4 : null); if ((Object)(object)val2 != (Object)null) { method.Invoke(uninitializedObject2, new object[2] { val2, "English" }); } } IDictionary obj2 = field2.GetValue(uninitializedObject2) as IDictionary; int num2 = 0; foreach (DictionaryEntry item5 in obj2) { string text4 = item5.Key as string; string text5 = item5.Value as string; if (text4 == null || string.IsNullOrWhiteSpace(text5)) { continue; } text4 = text4.TrimStart(new char[1] { '$' }); if (text4.StartsWith("enemy_", StringComparison.OrdinalIgnoreCase)) { EnglishNames[text4] = text5; EnglishNames[text5] = text5; if (Names.TryGetValue(text4, out var value)) { Names[text5] = value; EnglishNames[value] = text5; } num2++; } } if (num2 == 0) { throw new InvalidOperationException("English creature translation table is not ready"); } _loaded = true; ValheimDeathBanPlugin.Log.LogInfo((object)("Loaded " + dictionary.Count + " Russian and " + num2 + " English creature names from game localization.")); } catch (Exception ex) { if (!_warned) { _warned = true; ValheimDeathBanPlugin.Log.LogWarning((object)("Russian creature names not loaded yet; using unknown-creature labels and retrying: " + ex.GetType().Name)); } } } internal static List<List<string>> ParseCsv(string csv) { List<List<string>> list = new List<List<string>>(); List<string> list2 = new List<string>(); StringBuilder stringBuilder = new StringBuilder(); bool flag = false; for (int i = 0; i < csv.Length; i++) { char c = csv[i]; if (c == '"') { if (flag && i + 1 < csv.Length && csv[i + 1] == '"') { stringBuilder.Append('"'); i++; } else { flag = !flag; } } else if (!flag && (c == ',' || c == '\n' || c == '\r')) { list2.Add(stringBuilder.ToString()); stringBuilder.Clear(); if (c != ',') { list.Add(list2); list2 = new List<string>(); if (c == '\r' && i + 1 < csv.Length && csv[i + 1] == '\n') { i++; } } } else { stringBuilder.Append(c); } } if (stringBuilder.Length > 0 || list2.Count > 0) { list2.Add(stringBuilder.ToString()); list.Add(list2); } return list; } private static string Safe(string text) { return text.Replace('\r', ' ').Replace('\n', ' ').Replace('<', '<') .Replace('>', '>'); } } internal sealed class DiscordDeathNotifier : IDisposable { private sealed class Message { internal Uri Url; internal string Json; } private readonly Queue<Message> _queue = new Queue<Message>(); private readonly object _gate = new object(); private readonly CancellationTokenSource _stop = new CancellationTokenSource(); private readonly HttpClient _http; private readonly ManualLogSource _log; private bool _running; private bool _disposed; internal DiscordDeathNotifier(ManualLogSource log) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Expected O, but got Unknown _log = log; _http = new HttpClient((HttpMessageHandler)new HttpClientHandler { AllowAutoRedirect = false }); _http.Timeout = TimeSpan.FromSeconds(10.0); } internal void Enqueue(string webhook, string player, string id, string reason, string status, DateTimeOffset time) { if (string.IsNullOrWhiteSpace(webhook)) { return; } if (!Uri.TryCreate(webhook.Trim(), UriKind.Absolute, out Uri result) || result.Scheme != "https" || !result.IsDefaultPort || (!(result.Host == "discord.com") && !(result.Host == "discordapp.com") && !(result.Host == "canary.discord.com") && !(result.Host == "ptb.discord.com")) || !Regex.IsMatch(result.AbsolutePath, "^/api/(?:v\\d+/)?webhooks/\\d+/[A-Za-z0-9_-]+/?$") || !string.IsNullOrEmpty(result.UserInfo)) { _log.LogWarning((object)"Discord: invalid webhook URL. Use the HTTPS URL copied from Discord."); return; } UriBuilder uriBuilder = new UriBuilder(result); string input = uriBuilder.Query.TrimStart(new char[1] { '?' }); input = Regex.Replace(input, "(^|&)wait=[^&]*", "").Trim(new char[1] { '&' }); uriBuilder.Query = ((input.Length == 0) ? "" : (input + "&")) + "wait=true"; string value = DeathMessageFormatter.Format(Limit(player, 256), Limit(reason, 512)) + "\nID: " + Limit(id, 128) + "\nВремя: " + time.ToString("yyyy-MM-dd HH:mm:ss zzz", CultureInfo.InvariantCulture) + "\nСтатус: " + Limit(status, 256); Message item = new Message { Url = uriBuilder.Uri, Json = "{\"content\":" + Quote(value) + ",\"allowed_mentions\":{\"parse\":[]}}" }; lock (_gate) { if (_disposed) { return; } if (_queue.Count >= 256) { _log.LogWarning((object)"Discord: notification queue full; this notification was dropped."); return; } _queue.Enqueue(item); if (!_running) { _running = true; Task.Run((Func<Task?>)DrainAsync); } } } private async Task DrainAsync() { _ = 1; try { while (true) { Message message; lock (_gate) { if (_disposed || _queue.Count == 0) { break; } message = _queue.Dequeue(); } await SendAsync(message).ConfigureAwait(continueOnCapturedContext: false); await Task.Delay(500, _stop.Token).ConfigureAwait(continueOnCapturedContext: false); } } catch (OperationCanceledException) { } catch (Exception) { _log.LogWarning((object)"Discord: notification worker stopped unexpectedly."); } finally { lock (_gate) { _running = false; if (_disposed) { ((HttpMessageInvoker)_http).Dispose(); } else if (_queue.Count > 0) { _running = true; Task.Run((Func<Task?>)DrainAsync); } } } } private async Task SendAsync(Message message) { _ = 2; try { for (int attempt = 0; attempt < 3; attempt++) { StringContent body = new StringContent(message.Json, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await _http.PostAsync(message.Url, (HttpContent)(object)body, _stop.Token).ConfigureAwait(continueOnCapturedContext: false); try { if (response.IsSuccessStatusCode) { break; } if (response.StatusCode == HttpStatusCode.TooManyRequests && attempt < 2) { Match match = Regex.Match(await response.Content.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext: false), "\"retry_after\"\\s*:\\s*([0-9]+(?:\\.[0-9]+)?)"); if (!match.Success || !double.TryParse(match.Groups[1].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { result = 2.0; } if (result > 60.0) { _log.LogWarning((object)"Discord: long rate limit; notification dropped."); break; } await Task.Delay(TimeSpan.FromSeconds(Math.Max(0.5, result) + 0.25), _stop.Token).ConfigureAwait(continueOnCapturedContext: false); continue; } _log.LogWarning((object)("Discord: HTTP " + (int)response.StatusCode + "; notification not delivered.")); break; } finally { ((IDisposable)response)?.Dispose(); } } finally { ((IDisposable)body)?.Dispose(); } } } catch (OperationCanceledException) { if (!_stop.IsCancellationRequested) { _log.LogWarning((object)"Discord: request timed out; notification not delivered."); } } catch (Exception) { if (!_stop.IsCancellationRequested) { _log.LogWarning((object)"Discord: network/TLS error; notification not delivered."); } } } private static string Limit(string value, int length) { value = (value ?? "unknown").Replace('\r', ' ').Replace('\n', ' '); if (value.Length <= length) { return value; } return value.Substring(0, length); } internal static string Quote(string value) { StringBuilder stringBuilder = new StringBuilder("\""); foreach (char c in value) { if (c == '"' || c == '\\') { stringBuilder.Append('\\').Append(c); } else if (c < ' ' || char.IsSurrogate(c)) { StringBuilder stringBuilder2 = stringBuilder.Append("\\u"); int num = c; stringBuilder2.Append(num.ToString("x4")); } else { stringBuilder.Append(c); } } return stringBuilder.Append('"').ToString(); } public void Dispose() { lock (_gate) { if (!_disposed) { _disposed = true; _queue.Clear(); _stop.Cancel(); if (!_running) { ((HttpMessageInvoker)_http).Dispose(); } } } } } internal static class EnforcerWhitelist { private static ConfigEntry<bool> integration; private static ConfigEntry<bool> whitelist; private static ConfigEntry<bool> exemptAdmins; private static bool warnedMissing; internal static void Initialize(ConfigFile config) { integration = config.Bind<bool>("Enforcer", "IntegrationEnabled", false, "Enable integration with the loaded ValheimEnforcer plugin. Required for the whitelist."); whitelist = config.Bind<bool>("Enforcer", "WhitelistEnabled", false, "Only allow Steam accounts already present in Enforcer's character database. Requires IntegrationEnabled and a loaded Enforcer. An empty database denies all remote accounts."); exemptAdmins = config.Bind<bool>("Enforcer", "WhitelistExemptAdmins", true, "Exempt accounts in the native adminlist.txt from the Enforcer whitelist. Does not bypass native bans or Enforcer's own checks."); } private static Type ResolveDatabase() { foreach (PluginInfo value in Chainloader.PluginInfos.Values) { if ((Object)(object)value.Instance == (Object)null) { continue; } Assembly assembly = ((object)value.Instance).GetType().Assembly; if (string.Equals(assembly.GetName().Name, "ValheimEnforcer", StringComparison.Ordinal)) { Type? type = assembly.GetType("ValheimEnforcer.modules.character.CharacterSaves"); if (type == null) { throw new MissingMemberException("Enforcer CharacterSaves API unavailable"); } return type; } } return null; } private static string SteamAccount(string value) { if (value == null) { return null; } value = value.Trim(); if (value.StartsWith("Steam_", StringComparison.OrdinalIgnoreCase)) { value = value.Substring(6); } if (value.Length != 17) { return null; } string text = value; foreach (char c in text) { if (c < '0' || c > '9') { return null; } } return value; } internal static bool Allow(string host, string name) { if (integration == null || !integration.Value || !whitelist.Value || (Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer()) { return true; } try { if (exemptAdmins.Value && DeathBanUtil.IsAdmin(host)) { return true; } Type type = ResolveDatabase(); if (type == null) { if (!warnedMissing) { warnedMissing = true; ValheimDeathBanPlugin.Log.LogWarning((object)"Enforcer whitelist inactive: ValheimEnforcer is not loaded."); } return true; } warnedMissing = false; MethodInfo? method = type.GetMethod("Accounts", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null); if (method == null) { throw new MissingMethodException("CharacterSaves.Accounts()"); } IEnumerable obj = (method.Invoke(null, null) as IEnumerable) ?? throw new InvalidOperationException("Enforcer returned no account collection"); string text = SteamAccount(host); bool flag = false; foreach (object item in obj) { if (text != null && string.Equals(text, SteamAccount(item as string), StringComparison.Ordinal)) { flag = true; } } if (flag) { return true; } Journal(host, name, (text == null) ? "unsupported or invalid Steam account" : "account absent from Enforcer database"); return false; } catch (Exception ex) { ValheimDeathBanPlugin.Log.LogError((object)("Enforcer whitelist database check failed: " + ex)); Journal(host, name, "Enforcer database unavailable; entry rejected"); return false; } } private static string Clean(string value) { value = (value ?? "unknown").Replace('\r', ' ').Replace('\n', ' ').Replace('\t', ' '); if (value.Length <= 512) { return value; } return value.Substring(0, 512); } private static void Journal(string host, string name, string reason) { string text = $"{DateTimeOffset.Now:yyyy-MM-dd HH:mm:ss zzz} | player={Clean(name)} | id={Clean(host)} | rejected={reason}"; ValheimDeathBanPlugin.Log.LogWarning((object)("Enforcer whitelist: " + text)); try { string text2 = Path.Combine(Paths.ConfigPath, "ValheimDeathBan"); Directory.CreateDirectory(text2); File.AppendAllText(Path.Combine(text2, "whitelist_rejections.txt"), text + Environment.NewLine, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); } catch (Exception ex) { ValheimDeathBanPlugin.Log.LogError((object)("Could not write whitelist rejection journal: " + ex)); } } } [HarmonyPatch(typeof(ZNet), "IsAllowed", new Type[] { typeof(string), typeof(string) })] internal static class EnforcerWhitelistJoinPatch { [HarmonyPriority(800)] private static bool Prefix(string __0, string __1, ref bool __result) { if (EnforcerWhitelist.Allow(__0, __1)) { return true; } __result = false; return false; } } internal sealed class BanRecoveryRequiredException : IOException { internal BanRecoveryRequiredException(string message, Exception inner = null) : base(message, inner) { } } internal static class NativeAccountBan { private static readonly HashSet<string> RecoveryRequired = new HashSet<string>(StringComparer.Ordinal); private const BindingFlags Flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; private static readonly FieldInfo BanListField = typeof(ZNet).GetField("m_bannedList", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); private static readonly FieldInfo LocationField = typeof(SyncedList).GetField("m_fileLocation", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); private static readonly FieldInfo EntriesField = typeof(SyncedList).GetField("m_list", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); private static readonly FieldInfo CommentsField = typeof(SyncedList).GetField("m_comments", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); private static readonly FieldInfo DateField = typeof(SyncedList).GetField("m_lastLoadDate", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); private static readonly MethodInfo SaveMethod = typeof(SyncedList).GetMethod("Save", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null); private static readonly MethodInfo KickPeerMethod = typeof(ZNet).GetMethod("InternalKick", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(ZNetPeer) }, null); internal static void Apply(string host) { //IL_034d: Unknown result type (might be due to invalid IL or missing references) //IL_0381: Unknown result type (might be due to invalid IL or missing references) //IL_0323: Unknown result type (might be due to invalid IL or missing references) //IL_0325: Unknown result type (might be due to invalid IL or missing references) //IL_032b: Unknown result type (might be due to invalid IL or missing references) //IL_03c3: Unknown result type (might be due to invalid IL or missing references) //IL_03ca: Unknown result type (might be due to invalid IL or missing references) //IL_03cc: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_01bc: Unknown result type (might be due to invalid IL or missing references) //IL_01e6: Unknown result type (might be due to invalid IL or missing references) //IL_01e7: Unknown result type (might be due to invalid IL or missing references) //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_023d: Unknown result type (might be due to invalid IL or missing references) //IL_0291: Unknown result type (might be due to invalid IL or missing references) //IL_02aa: Unknown result type (might be due to invalid IL or missing references) //IL_02ab: Unknown result type (might be due to invalid IL or missing references) //IL_02b1: Invalid comparison between Unknown and I4 //IL_02d4: Unknown result type (might be due to invalid IL or missing references) //IL_02d5: Unknown result type (might be due to invalid IL or missing references) //IL_02dc: Unknown result type (might be due to invalid IL or missing references) //IL_02b3: Unknown result type (might be due to invalid IL or missing references) //IL_02ba: Unknown result type (might be due to invalid IL or missing references) //IL_02c0: Unknown result type (might be due to invalid IL or missing references) //IL_02f7: Unknown result type (might be due to invalid IL or missing references) //IL_02f9: Unknown result type (might be due to invalid IL or missing references) //IL_02ff: Unknown result type (might be due to invalid IL or missing references) ZNet instance = ZNet.instance; if ((Object)(object)instance == (Object)null || !instance.IsServer()) { throw new InvalidOperationException("Account bans require the server."); } if (string.IsNullOrWhiteSpace(host) || host.IndexOfAny(new char[2] { '\r', '\n' }) >= 0) { throw new ArgumentException("Invalid account ID.", "host"); } if (BanListField == null || LocationField == null || EntriesField == null || CommentsField == null || DateField == null || SaveMethod == null) { throw new MissingMemberException("Native ban list persistence API unavailable."); } object? value = BanListField.GetValue(instance); SyncedList val = (SyncedList)((value is SyncedList) ? value : null); if (val == null) { throw new InvalidOperationException("Native ban list unavailable."); } FileLocation val2 = (FileLocation)LocationField.GetValue(val); if (RecoveryRequired.Contains(val2.m_path)) { throw new BanRecoveryRequiredException("Ban-list storage requires recovery from .deathban-backup and a restart."); } string text = Read(val2); List<string> list = new List<string>(); List<string> list2 = new List<string>(); using (StringReader stringReader = new StringReader(text)) { string text2; while ((text2 = stringReader.ReadLine()) != null) { if (text2.Length > 0) { if (text2.StartsWith("//", StringComparison.Ordinal)) { list2.Add(text2); } else { list.Add(text2); } } } } if (list.Contains(host)) { EntriesField.SetValue(val, list); CommentsField.SetValue(val, list2); return; } list.Add(host); object value2 = EntriesField.GetValue(val); object value3 = CommentsField.GetValue(val); object value4 = DateField.GetValue(val); FileLocation val3 = default(FileLocation); ((FileLocation)(ref val3))..ctor(val2.m_fileSource, val2.m_path + ".deathban-new-" + Guid.NewGuid().ToString("N")); FileLocation val4 = default(FileLocation); ((FileLocation)(ref val4))..ctor(val2.m_fileSource, val2.m_path + ".deathban-backup"); bool flag = false; try { LocationField.SetValue(val, val3); EntriesField.SetValue(val, list); CommentsField.SetValue(val, list2); SaveMethod.Invoke(val, null); string text3 = Read(val3); List<string> list3 = new List<string>(list2); list3.AddRange(list); if (text3.Replace("\r\n", "\n") != string.Join("\n", list3) + "\n") { throw new IOException("Staged ban list could not be verified."); } if (Read(val2) != text) { throw new IOException("Ban list changed during save; retry required."); } if ((int)val2.m_fileSource == 2) { File.Replace(val3.m_path, val2.m_path, val4.m_path); flag = true; return; } CopyCloud(val2, val4); if (Read(val4) != text) { throw new IOException("Cloud backup could not be verified."); } try { CopyCloud(val3, val2); if (Read(val2) != text3) { throw new IOException("Cloud ban list could not be verified."); } flag = true; } catch (Exception ex) { try { CopyCloud(val4, val2); if (Read(val2) != text) { throw new IOException("Cloud rollback could not be verified."); } } catch (Exception ex2) { RecoveryRequired.Add(val2.m_path); throw new BanRecoveryRequiredException("Cloud rollback failed; recover .deathban-backup and restart. Further death-ban writes are stopped.", new AggregateException(ex, ex2)); } throw; } } finally { LocationField.SetValue(val, val2); DateField.SetValue(val, value4); EntriesField.SetValue(val, flag ? list : value2); CommentsField.SetValue(val, flag ? list2 : value3); try { FileHelpers.Delete(val3.m_path, val3.m_fileSource); } catch { } } } private static string Read(FileLocation location) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Expected O, but got Unknown FileReader val = new FileReader(location.m_path, location.m_fileSource, (FileHelperType)1); try { return val.m_stream.ReadToEnd(); } finally { val.Dispose(); } } private static void CopyCloud(FileLocation source, FileLocation destination) { //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) MethodInfo[] methods = typeof(FileHelpers).GetMethods(BindingFlags.Static | BindingFlags.Public); foreach (MethodInfo methodInfo in methods) { ParameterInfo[] parameters = methodInfo.GetParameters(); if (!(methodInfo.Name != "Copy") && parameters.Length == 5 && !(parameters[1].ParameterType != typeof(FileSource))) { object obj = Enum.Parse(parameters[3].ParameterType, "SameFileEnding"); if (!(bool)methodInfo.Invoke(null, new object[5] { source.m_path, source.m_fileSource, destination.m_path, obj, destination.m_fileSource })) { throw new IOException("Cloud ban-list copy failed."); } return; } } throw new MissingMethodException("FileHelpers.Copy"); } internal static void Kick(string host) { ZNet instance = ZNet.instance; if ((Object)(object)instance == (Object)null || !instance.IsServer()) { return; } if (KickPeerMethod == null) { throw new MissingMethodException("ZNet.InternalKick(ZNetPeer)"); } ZNetPeer[] array = instance.GetPeers().ToArray(); foreach (ZNetPeer val in array) { if (string.Equals(DeathBanUtil.GetPeerHost(val), host, StringComparison.Ordinal)) { KickPeerMethod.Invoke(instance, new object[1] { val }); } } } } [BepInPlugin("com.xtasy.ValheimDeathBan", "Valheim Death Ban", "1.3.0")] public sealed class ValheimDeathBanPlugin : BaseUnityPlugin { private sealed class CharacterWatch { internal long Sender; internal string PlayerName; internal string Host; internal float LastSeen; internal bool DeathRegistered; internal bool ReasonClosed; } private sealed class ReasonReport { internal string Host; internal string Reason; internal float ReceivedAt; } public const string GUID = "com.xtasy.ValheimDeathBan"; public const string NAME = "Valheim Death Ban"; public const string VERSION = "1.3.0"; internal static ManualLogSource Log; internal static ValheimDeathBanPlugin Instance; internal static ConfigEntry<bool> Enabled; internal static ConfigEntry<bool> BanOnDeath; internal static ConfigEntry<float> KickDelaySeconds; internal static ConfigEntry<bool> BanAdmins; private ConfigEntry<float> _scanIntervalSeconds; private Harmony _harmony; private ConfigEntry<bool> _discordEnabled; private ConfigEntry<string> _webhookUrl; private DiscordDeathNotifier _discord; private ConfigEntry<bool> _announceChat; private ConfigEntry<bool> _announceBanner; private ConfigEntry<float> _bannerSeconds; private ConfigEntry<float> _bannerFontSize; private DeathAnnouncementUi _announcementUi; private const string AnnouncementRpc = "xtasy_DeathBan_Announcement_ru_direct_v3"; private const string EnglishAnnouncementRpc = "xtasy_DeathBan_Announcement_en_direct_v3"; private ZNet _registeredNet; private float _nextRpcCheck; private readonly HashSet<ZRpc> _registeredPeers = new HashSet<ZRpc>(); private const string ReasonRpc = "xtasy_DeathBan_Reason_direct_v2"; private readonly Dictionary<ZDOID, ReasonReport> _reports = new Dictionary<ZDOID, ReasonReport>(); private long _banGeneration; private readonly HashSet<string> _pendingBans = new HashSet<string>(StringComparer.Ordinal); private readonly Dictionary<ZDOID, CharacterWatch> _characters = new Dictionary<ZDOID, CharacterWatch>(); private float _nextScan; private float _nextErrorLog; private ConfigEntry<bool> _diagnosticsEnabled; private ConfigEntry<float> _diagnosticsIntervalMinutes; private float _nextDiagnostics; private long _diagnosticScans; private long _diagnosticFailures; private long _scanTotalTicks; private long _scanMaxTicks; private long _scanLastTicks; private long _peerTotalTicks; private long _peerMaxTicks; private long _peerLastTicks; private long _lookupTotalTicks; private long _lookupMaxTicks; private long _lookupLastTicks; private long _totalPeers; private long _totalZdoLookups; private long _totalDeadReads; private int _lastPeers; private int _lastZdoLookups; private int _lastDeadReads; private int _lastMissingZdos; private float _nextConfigCheck; private float _configStableAt; private DateTime _configCandidateWrite; private long _configCandidateLength = -1L; private bool _configPending; private void AnnounceDeath(string playerName, string reason) { if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer()) { return; } string text = DeathMessageFormatter.Format(Clean(playerName), Clean(reason), russian: true); string text2 = DeathMessageFormatter.Format(Clean(playerName), Clean(reason), russian: false); try { if (!_announceChat.Value && !_announceBanner.Value) { return; } DisplayAnnouncement(DeathMessageFormatter.UsesRussianNames() ? text : text2, _announceChat.Value, _announceBanner.Value); foreach (ZNetPeer peer in ZNet.instance.GetPeers()) { if (peer.IsReady() && peer.m_rpc != null) { peer.m_rpc.Invoke("xtasy_DeathBan_Announcement_ru_direct_v3", new object[3] { text, _announceChat.Value, _announceBanner.Value }); peer.m_rpc.Invoke("xtasy_DeathBan_Announcement_en_direct_v3", new object[3] { text2, _announceChat.Value, _announceBanner.Value }); } } } catch (Exception ex) { Log.LogWarning((object)("Death announcement failed: " + ex.GetType().Name)); } } private void ReceiveAnnouncement(ZRpc rpc, string text, bool chat, bool banner) { if (DeathBanUtil.IsServerConnection(rpc)) { DisplayAnnouncement(text, chat, banner); } } private void DisplayAnnouncement(string text, bool chat, bool banner) { text = Clean(text).Replace('<', '<').Replace('>', '>'); if (chat && (Object)(object)Chat.instance != (Object)null) { try { MethodInfo? method = typeof(Terminal).GetMethod("AddString", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[4] { typeof(string), typeof(string), typeof(Type), typeof(bool) }, null); if (method == null) { throw new MissingMethodException("Terminal.AddString"); } method.Invoke(Chat.instance, new object[4] { "Death Ban", text, (object)(Type)2, false }); typeof(Chat).GetField("m_hideTimer", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.SetValue(Chat.instance, 0f); } catch (Exception ex) { Log.LogWarning((object)("Death chat display failed: " + ex.GetType().Name)); } } if (banner) { if (_announcementUi == null) { _announcementUi = new DeathAnnouncementUi(Log); } _announcementUi.Enqueue(text); } } private void NotifyDeath(string playerName, string host, string reason, string status, DateTimeOffset diedAt) { try { if (_discordEnabled.Value && _discord != null && (Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer()) { _discord.Enqueue(_webhookUrl.Value, playerName, host, reason, status, diedAt); } } catch (Exception) { Log.LogWarning((object)"Discord notification could not be queued. Ban and journal are unaffected."); } } private void ResetDiagnostics(float now) { _nextDiagnostics = now + _diagnosticsIntervalMinutes.Value * 60f; _diagnosticScans = (_diagnosticFailures = 0L); _scanTotalTicks = (_scanMaxTicks = (_scanLastTicks = 0L)); _peerTotalTicks = (_peerMaxTicks = (_peerLastTicks = 0L)); _lookupTotalTicks = (_lookupMaxTicks = (_lookupLastTicks = 0L)); _totalPeers = (_totalZdoLookups = (_totalDeadReads = 0L)); } private static double Milliseconds(long ticks) { return (double)ticks * (1000.0 / (double)Stopwatch.Frequency); } private void RecordScanDiagnostics(float now, long ticks, bool failed) { _diagnosticScans++; if (failed) { _diagnosticFailures++; } _scanLastTicks = ticks; _scanTotalTicks += ticks; _scanMaxTicks = Math.Max(_scanMaxTicks, ticks); _peerTotalTicks += _peerLastTicks; _peerMaxTicks = Math.Max(_peerMaxTicks, _peerLastTicks); _lookupTotalTicks += _lookupLastTicks; _lookupMaxTicks = Math.Max(_lookupMaxTicks, _lookupLastTicks); _totalPeers += _lastPeers; _totalZdoLookups += _lastZdoLookups; _totalDeadReads += _lastDeadReads; if (!(now < _nextDiagnostics)) { Log.LogInfo((object)string.Format(CultureInfo.InvariantCulture, "Death scan diagnostics ({19:F2} min): scans={0}, failed={1}; peers last/avg={2}/{3:F1}, tracked={4}; full scan ms last/avg/max={5:F4}/{6:F4}/{7:F4}; peer loop ms last/avg/max={8:F4}/{9:F4}/{10:F4}; ZDO lookup + dead flag ms last/avg/max={11:F4}/{12:F4}/{13:F4}; ZDO lookups last/total={14}/{15}, dead flag reads last/total={16}/{17}, missing ZDO last={18}.", _diagnosticScans, _diagnosticFailures, _lastPeers, (double)_totalPeers / (double)_diagnosticScans, _characters.Count, Milliseconds(_scanLastTicks), Milliseconds(_scanTotalTicks) / (double)_diagnosticScans, Milliseconds(_scanMaxTicks), Milliseconds(_peerLastTicks), Milliseconds(_peerTotalTicks) / (double)_diagnosticScans, Milliseconds(_peerMaxTicks), Milliseconds(_lookupLastTicks), Milliseconds(_lookupTotalTicks) / (double)_diagnosticScans, Milliseconds(_lookupMaxTicks), _lastZdoLookups, _totalZdoLookups, _lastDeadReads, _totalDeadReads, _lastMissingZdos, _diagnosticsIntervalMinutes.Value)); ResetDiagnostics(now); } } private void CheckConfigChanges() { float realtimeSinceStartup = Time.realtimeSinceStartup; if (realtimeSinceStartup < _nextConfigCheck) { return; } _nextConfigCheck = realtimeSinceStartup + 1f; try { FileInfo fileInfo = new FileInfo(((BaseUnityPlugin)this).Config.ConfigFilePath); if (!fileInfo.Exists) { return; } if (fileInfo.LastWriteTimeUtc != _configCandidateWrite || fileInfo.Length != _configCandidateLength) { _configCandidateWrite = fileInfo.LastWriteTimeUtc; _configCandidateLength = fileInfo.Length; _configStableAt = realtimeSinceStartup + 0.5f; _configPending = true; } else if (_configPending && !(realtimeSinceStartup < _configStableAt)) { bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet; try { ((BaseUnityPlugin)this).Config.SaveOnConfigSet = false; ((BaseUnityPlugin)this).Config.Reload(); } finally { ((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet; } _configPending = false; Log.LogInfo((object)"Configuration reloaded after file change."); } } catch (Exception ex) { _configStableAt = realtimeSinceStartup + 10f; _nextConfigCheck = realtimeSinceStartup + 10f; Log.LogWarning((object)("Configuration reload/check failed; will retry: " + ex.GetType().Name)); } } private void RememberConfigFile() { try { FileInfo fileInfo = new FileInfo(((BaseUnityPlugin)this).Config.ConfigFilePath); if (fileInfo.Exists) { _configCandidateWrite = fileInfo.LastWriteTimeUtc; _configCandidateLength = fileInfo.Length; } } catch { } } private void Update() { CheckConfigChanges(); DeathMessageFormatter.InitializeRussianNames(); EnsurePeerRpcs(); _announcementUi?.Tick(DeathBanUtil.BannerDuration(_bannerSeconds.Value), _bannerFontSize.Value); if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || ZDOMan.instance == null || !Enabled.Value) { return; } float realtimeSinceStartup = Time.realtimeSinceStartup; if (realtimeSinceStartup < _nextScan) { return; } _nextScan = realtimeSinceStartup + DeathBanUtil.ScanInterval(_scanIntervalSeconds.Value); _lastPeers = (_lastZdoLookups = (_lastDeadReads = (_lastMissingZdos = 0))); _peerLastTicks = (_lookupLastTicks = 0L); bool value = _diagnosticsEnabled.Value; long num = (value ? Stopwatch.GetTimestamp() : 0); bool failed = false; try { ScanCharacters(realtimeSinceStartup); } catch (Exception ex) { failed = true; if (realtimeSinceStartup >= _nextErrorLog) { _nextErrorLog = realtimeSinceStartup + 10f; Log.LogError((object)("Server death scan failed: " + ex)); } } finally { if (value) { long ticks = Stopwatch.GetTimestamp() - num; RecordScanDiagnostics(realtimeSinceStartup, ticks, failed); } } } private void ScanCharacters(float now) { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_02d3: Unknown result type (might be due to invalid IL or missing references) //IL_02d8: Unknown result type (might be due to invalid IL or missing references) //IL_02e0: Unknown result type (might be due to invalid IL or missing references) //IL_0181: Unknown result type (might be due to invalid IL or missing references) //IL_0337: Unknown result type (might be due to invalid IL or missing references) //IL_0264: Unknown result type (might be due to invalid IL or missing references) //IL_0287: Unknown result type (might be due to invalid IL or missing references) //IL_0366: Unknown result type (might be due to invalid IL or missing references) //IL_036b: Unknown result type (might be due to invalid IL or missing references) //IL_0373: Unknown result type (might be due to invalid IL or missing references) bool value = _diagnosticsEnabled.Value; long num = (value ? Stopwatch.GetTimestamp() : 0); try { foreach (ZNetPeer peer in ZNet.instance.GetPeers()) { _lastPeers++; if (peer.m_characterID == ZDOID.None) { continue; } string peerHost = DeathBanUtil.GetPeerHost(peer); if (!string.IsNullOrWhiteSpace(peerHost)) { if (!_characters.TryGetValue(peer.m_characterID, out var value2)) { value2 = new CharacterWatch { Sender = peer.m_uid, PlayerName = DeathBanUtil.GetPeerName(peer), Host = peerHost }; _characters.Add(peer.m_characterID, value2); } if (!(value2.Host != peerHost)) { value2.LastSeen = now; } } } } finally { if (value) { _peerLastTicks = Stopwatch.GetTimestamp() - num; } } List<ZDOID> list = new List<ZDOID>(); foreach (KeyValuePair<ZDOID, CharacterWatch> character in _characters) { CharacterWatch value3 = character.Value; if (now - value3.LastSeen > 30f) { list.Add(character.Key); } else { if (value3.DeathRegistered) { continue; } bool flag = false; long num2 = (value ? Stopwatch.GetTimestamp() : 0); try { _lastZdoLookups++; ZDO zDO = ZDOMan.instance.GetZDO(character.Key); if (zDO == null) { _lastMissingZdos++; } else { _lastDeadReads++; flag = zDO.GetBool(DeathBanUtil.DeadKey, false); } } finally { if (value) { _lookupLastTicks += Stopwatch.GetTimestamp() - num2; } } if (flag) { bool flag2 = !BanAdmins.Value && DeathBanUtil.IsAdmin(value3.Host); bool value4 = BanOnDeath.Value; value3.DeathRegistered = true; bool ownsBan = !flag2 && value4 && _pendingBans.Add(value3.Host); Log.LogInfo((object)$"Server death confirmed: player='{Clean(value3.PlayerName)}', id='{Clean(value3.Host)}', character={character.Key}, admin_exempt={flag2}."); ((MonoBehaviour)this).StartCoroutine(ProcessDeath(character.Key, value3.PlayerName, value3.Host, flag2, value4, ownsBan)); } } } foreach (ZDOID item in list) { _characters.Remove(item); } List<ZDOID> list2 = new List<ZDOID>(); foreach (KeyValuePair<ZDOID, ReasonReport> report in _reports) { if (now - report.Value.ReceivedAt > 15f) { list2.Add(report.Key); } } foreach (ZDOID item2 in list2) { _reports.Remove(item2); } } internal void EnsurePeerRpcs() { ZNet instance = ZNet.instance; if (instance != _registeredNet) { ((MonoBehaviour)this).StopAllCoroutines(); UnregisterPeerRpcs(); _announcementUi?.Dispose(); _announcementUi = null; _characters.Clear(); _pendingBans.Clear(); _reports.Clear(); _nextScan = (_nextRpcCheck = 0f); ResetDiagnostics(Time.realtimeSinceStartup); _registeredNet = instance; } if ((Object)(object)instance == (Object)null || Time.realtimeSinceStartup < _nextRpcCheck) { return; } _nextRpcCheck = Time.realtimeSinceStartup + 1f; HashSet<ZRpc> active = new HashSet<ZRpc>(); foreach (ZNetPeer peer in instance.GetPeers()) { if (peer.m_rpc != null) { active.Add(peer.m_rpc); RegisterPeerRpc(peer); } } _registeredPeers.RemoveWhere((ZRpc rpc) => !active.Contains(rpc)); } internal void RegisterPeerRpc(ZNetPeer peer) { if (peer?.m_rpc == null || _registeredPeers.Contains(peer.m_rpc)) { return; } peer.m_rpc.Register<ZDOID, string>("xtasy_DeathBan_Reason_direct_v2", (Action<ZRpc, ZDOID, string>)ReceiveReason); peer.m_rpc.Register<string, bool, bool>("xtasy_DeathBan_Announcement_ru_direct_v3", (Action<ZRpc, string, bool, bool>)delegate(ZRpc rpc, string text, bool chat, bool banner) { if (DeathMessageFormatter.UsesRussianNames()) { ReceiveAnnouncement(rpc, text, chat, banner); } }); peer.m_rpc.Register<string, bool, bool>("xtasy_DeathBan_Announcement_en_direct_v3", (Action<ZRpc, string, bool, bool>)delegate(ZRpc rpc, string text, bool chat, bool banner) { if (!DeathMessageFormatter.UsesRussianNames()) { ReceiveAnnouncement(rpc, text, chat, banner); } }); _registeredPeers.Add(peer.m_rpc); } private void UnregisterPeerRpcs() { foreach (ZRpc registeredPeer in _registeredPeers) { registeredPeer.Unregister("xtasy_DeathBan_Reason_direct_v2"); registeredPeer.Unregister("xtasy_DeathBan_Announcement_ru_direct_v3"); registeredPeer.Unregister("xtasy_DeathBan_Announcement_en_direct_v3"); } _registeredPeers.Clear(); } private void ReceiveReason(ZRpc rpc, ZDOID characterId, string reason) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || !Enabled.Value) { return; } try { ZNetPeer val = DeathBanUtil.FindPeer(rpc); if (val == null || !val.IsReady() || characterId == ZDOID.None) { return; } string peerHost = DeathBanUtil.GetPeerHost(val); if (string.IsNullOrWhiteSpace(peerHost)) { return; } if (_characters.TryGetValue(characterId, out var value)) { if (value.Host != peerHost || value.Sender != val.m_uid || value.ReasonClosed || Time.realtimeSinceStartup - value.LastSeen > 30f) { return; } } else if (val.m_characterID != characterId) { return; } if (!_reports.ContainsKey(characterId) && _reports.Count < 1024) { _reports[characterId] = new ReasonReport { Host = peerHost, Reason = Clean(reason), ReceivedAt = Time.realtimeSinceStartup }; Log.LogInfo((object)$"Death reason received: character={characterId}; awaiting server ZDO confirmation."); } } catch (Exception ex) { Log.LogError((object)("Death report processing failed: " + ex)); } } internal void ReportLocalDeath(Player player) { //IL_00e1: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)ZNet.instance == (Object)null || (Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)Player.m_localPlayer) { return; } try { if (ZNet.instance.IsServer()) { if (Enabled.Value) { string reason = DeathBanUtil.DescribeLastHit(player); WriteDeath(player.GetPlayerName(), "local-host", reason, "local host (ban exempt)", exempt: true); AnnounceDeath(player.GetPlayerName(), reason); NotifyDeath(player.GetPlayerName(), "local-host", reason, "Хозяин локального мира — освобождён от бана", DateTimeOffset.Now); } return; } Log.LogInfo((object)("Client death detected: " + Clean(player.GetPlayerName()))); EnsurePeerRpcs(); ZRpc serverRPC = ZNet.instance.GetServerRPC(); if (!DeathBanUtil.IsServerConnection(serverRPC)) { Log.LogWarning((object)"Death report not sent: server connection unavailable."); return; } serverRPC.Invoke("xtasy_DeathBan_Reason_direct_v2", new object[2] { ((Character)player).GetZDOID(), DeathBanUtil.DescribeLastHit(player) }); Log.LogInfo((object)"Death report sent on the server connection."); } catch (Exception ex) { Log.LogWarning((object)("Could not report death reason: " + ex.Message)); } } internal IEnumerator ProcessDeath(ZDOID characterId, string playerName, string host, bool exempt, bool banOnDeath, bool ownsBan) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) ZNet deathNet = ZNet.instance; long generation = _banGeneration; try { float start = Time.realtimeSinceStartup; DateTimeOffset diedAt = DateTimeOffset.Now; float delay = DeathBanUtil.KickDelay(KickDelaySeconds.Value); float num = Math.Min(1f, delay); if (num > 0f) { yield return (object)new WaitForSecondsRealtime(num); } if (ZNet.instance != deathNet || (Object)(object)deathNet == (Object)null || !deathNet.IsServer()) { yield break; } string reason = "неизвестна (клиент не передал данные)"; string source = "server ZDO; reason=unavailable"; if (_reports.TryGetValue(characterId, out var value) && value.Host == host && Time.realtimeSinceStartup - value.ReceivedAt <= 15f) { reason = value.Reason; source = "server ZDO; reason=client report"; } _reports.Remove(characterId); if (_characters.TryGetValue(characterId, out var value2)) { value2.ReasonClosed = true; } WriteDeath(playerName, host, reason, source, exempt); AnnounceDeath(playerName, reason); if (exempt) { NotifyDeath(playerName, host, reason, "Администратор — освобождён от бана", diedAt); yield break; } if (!Enabled.Value) { NotifyDeath(playerName, host, reason, "Бан не применён: мод отключён", diedAt); yield break; } if (!banOnDeath || !BanOnDeath.Value || generation != _banGeneration) { NotifyDeath(playerName, host, reason, "Бан не применён: BanOnDeath отключён", diedAt); yield break; } if (!ownsBan) { NotifyDeath(playerName, host, reason, "Бан уже ожидается после предыдущей смерти", diedAt); yield break; } float num2 = delay - (Time.realtimeSinceStartup - start); if (num2 > 0f) { yield return (object)new WaitForSecondsRealtime(num2); } for (int attempt = 0; attempt < 5; attempt++) { if (ZNet.instance != deathNet) { break; } if ((Object)(object)deathNet == (Object)null) { break; } if (!deathNet.IsServer()) { break; } if (!Enabled.Value) { NotifyDeath(playerName, host, reason, "Бан не применён: мод отключён", diedAt); break; } if (!BanOnDeath.Value || generation != _banGeneration) { NotifyDeath(playerName, host, reason, "Бан не применён: BanOnDeath отключён", diedAt); break; } bool flag = false; bool flag2 = false; try { if (!BanAdmins.Value && DeathBanUtil.IsAdmin(host)) { NotifyDeath(playerName, host, reason, "Администратор — освобождён от бана", diedAt); break; } NativeAccountBan.Apply(host); flag = true; } catch (Exception ex) { flag2 = ex is BanRecoveryRequiredException; Log.LogError((object)$"Failed to death-ban '{Clean(playerName)}' ({Clean(host)}), attempt {attempt + 1}/5: {ex}"); } if (flag2) { NotifyDeath(playerName, host, reason, "Состояние бана не подтверждено: требуется восстановление списка банов и перезапуск сервера", diedAt); break; } if (!flag) { if (attempt < 4) { yield return (object)new WaitForSecondsRealtime(2f * (float)(1 << attempt)); continue; } NotifyDeath(playerName, host, reason, "Ошибка применения бана после 5 попыток — проверьте лог сервера", diedAt); break; } NotifyDeath(playerName, host, reason, "Забанен", diedAt); try { NativeAccountBan.Kick(host); } catch (Exception ex2) { Log.LogWarning((object)("Death-ban applied, but fallback kick failed: " + ex2.GetType().Name)); } Log.LogWarning((object)("Death-ban applied and saved: player='" + Clean(playerName) + "', id='" + Clean(host) + "'.")); break; } } finally { ValheimDeathBanPlugin valheimDeathBanPlugin = this; if (ownsBan && generation == valheimDeathBanPlugin._banGeneration) { valheimDeathBanPlugin._pendingBans.Remove(host); } } } private static string Clean(string text) { if (text == null) { return "unknown"; } text = text.Replace('\r', ' ').Replace('\n', ' ').Replace('\t', ' '); if (text.Length <= 512) { return text; } return text.Substring(0, 512); } private static void WriteDeath(string name, string host, string reason, string source, bool exempt) { try { string text = Path.Combine(Paths.ConfigPath, "ValheimDeathBan"); Directory.CreateDirectory(text); string text2 = $"{DateTimeOffset.Now:yyyy-MM-dd HH:mm:ss zzz} | player={Clean(name)} | id={Clean(host)} | reason={Clean(reason)} | source={source} | admin_exempt={exempt}"; File.AppendAllText(Path.Combine(text, "deaths.txt"), text2 + Environment.NewLine, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); Log.LogInfo((object)text2); } catch (Exception ex) { Log.LogError((object)("Failed to write death journal: " + ex)); } } private void Awake() { //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Expected O, but got Unknown //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Expected O, but got Unknown //IL_02a5: Unknown result type (might be due to invalid IL or missing references) //IL_02af: Expected O, but got Unknown //IL_02c0: Unknown result type (might be due to invalid IL or missing references) //IL_02ca: Expected O, but got Unknown Instance = this; Log = ((BaseUnityPlugin)this).Logger; EnforcerWhitelist.Initialize(((BaseUnityPlugin)this).Config); Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Enable server death processing, the death journal and announcements. BanOnDeath controls account bans."); BanOnDeath = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "BanOnDeath", true, "Ban and disconnect accounts after confirmed deaths. If false, keep the journal, announcements and Discord notifications without banning or kicking. Server setting; existing bans are not removed."); Enabled.SettingChanged += OnBanSettingChanged; BanOnDeath.SettingChanged += OnBanSettingChanged; KickDelaySeconds = ((BaseUnityPlugin)this).Config.Bind<float>("General", "KickDelaySeconds", 3f, "Seconds to wait after death before disconnecting the player."); BanAdmins = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "BanAdmins", false, "If false, players present in adminlist.txt are exempt from death bans."); _scanIntervalSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("General", "ScanIntervalSeconds", 0.25f, new ConfigDescription("Seconds between server player/death scans. Range: 0.05-1 second to sample before normal respawn removes the dead ZDO. Older larger values are clamped.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.05f, 1f), Array.Empty<object>())); _scanIntervalSeconds.SettingChanged += OnScanIntervalChanged; _diagnosticsEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Diagnostics", "Enabled", true, "Enable server death-scan timing and periodic diagnostic logs."); _diagnosticsIntervalMinutes = ((BaseUnityPlugin)this).Config.Bind<float>("Diagnostics", "LogIntervalMinutes", 15f, new ConfigDescription("Minutes between server scan diagnostic logs. Range: 0.1-1440 minutes.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 1440f), Array.Empty<object>())); _diagnosticsEnabled.SettingChanged += OnDiagnosticsChanged; _diagnosticsIntervalMinutes.SettingChanged += OnDiagnosticsChanged; ResetDiagnostics(Time.realtimeSinceStartup); _discordEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Discord", "Enabled", false, "Send death notifications to Discord from the server. Sends names and account IDs."); _webhookUrl = ((BaseUnityPlugin)this).Config.Bind<string>("Discord", "WebhookUrl", "", "Discord webhook URL. Server-only secret; never synced to clients. Empty disables sending."); _discord = new DiscordDeathNotifier(Log); _announceChat = ((BaseUnityPlugin)this).Config.Bind<bool>("Announcements", "Chat", true, "Announce all confirmed deaths in shout-style chat (/s). Clients need Death Ban 1.2.7 or newer."); _announceBanner = ((BaseUnityPlugin)this).Config.Bind<bool>("Announcements", "Banner", true, "Broadcast a large red Norse death banner. Clients need Death Ban 1.2.7 or newer."); _bannerSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Announcements", "BannerSeconds", 8f, "Client banner duration in seconds, clamped to 1-60. Multiple deaths are queued."); _bannerFontSize = ((BaseUnityPlugin)this).Config.Bind<float>("Announcements", "BannerFontSize", 60f, new ConfigDescription("Client banner font size. Long messages may shrink to half this size to fit. Range: 16-120. Default: 60.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(16f, 120f), Array.Empty<object>())); RememberConfigFile(); _harmony = new Harmony("com.xtasy.ValheimDeathBan"); _harmony.PatchAll(); Log.LogInfo((object)"Valheim Death Ban 1.3.0 loaded. Server ZDO death monitoring; client reports provide reasons only."); } private void OnBanSettingChanged(object sender, EventArgs args) { if (!Enabled.Value || !BanOnDeath.Value) { _banGeneration++; _pendingBans.Clear(); } } private void OnDiagnosticsChanged(object sender, EventArgs args) { ResetDiagnostics(Time.realtimeSinceStartup); } private void OnScanIntervalChanged(object sender, EventArgs args) { _nextScan = 0f; } private void OnDestroy() { if (Enabled != null) { Enabled.SettingChanged -= OnBanSettingChanged; } if (BanOnDeath != null) { BanOnDeath.SettingChanged -= OnBanSettingChanged; } if (_scanIntervalSeconds != null) { _scanIntervalSeconds.SettingChanged -= OnScanIntervalChanged; } if (_diagnosticsEnabled != null) { _diagnosticsEnabled.SettingChanged -= OnDiagnosticsChanged; } if (_diagnosticsIntervalMinutes != null) { _diagnosticsIntervalMinutes.SettingChanged -= OnDiagnosticsChanged; } _announcementUi?.Dispose(); _discord?.Dispose(); UnregisterPeerRpcs(); Instance = null; Harmony harmony = _harmony; if (harmony != null) { harmony.UnpatchSelf(); } } } internal static class DeathBanUtil { private const BindingFlags AnyInstance = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; internal static readonly int DeadKey = ZDOVars.s_dead; internal static float BannerDuration(float value) { if (!float.IsNaN(value) && !float.IsInfinity(value)) { return Mathf.Clamp(value, 1f, 60f); } return 8f; } internal static float ScanInterval(float value) { if (!float.IsNaN(value) && !float.IsInfinity(value)) { return Mathf.Clamp(value, 0.05f, 1f); } return 0.25f; } internal static float KickDelay(float value) { if (!float.IsNaN(value) && !float.IsInfinity(value)) { return Mathf.Max(0f, value); } return 3f; } internal static string DescribeLastHit(Player player) { object? obj = typeof(Character).GetField("m_lastHit", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(player); HitData val = (HitData)((obj is HitData) ? obj : null); if (val == null) { return "неизвестна (нет последнего удара)"; } string text = ((object)Unsafe.As<HitType, HitType>(ref val.m_hitType)/*cast due to .constrained prefix*/).ToString(); string text2 = text switch { "EnemyHit" => "атака существа", "PlayerHit" => "атака игрока", "Fall" => "падение", "Drowning" => "утопление", "Burning" => "горение", "Freezing" => "замерзание", "Poisoned" => "отравление", "Water" => "урон от воды", "Smoke" => "дым", "EdgeOfWorld" => "край мира", "Impact" => "удар объектом", "Cart" => "телега", "Tree" => "дерево", "Self" => "урон себе", "Structural" => "строительная конструкция", "Turret" => "баллиста", "Boat" => "корабль", "Stalagtite" => "сталактит", "Catapult" => "катапульта", "CinderFire" => "пепельный огонь", "AshlandsOcean" => "кипящий океан Пепельных земель", "AshlandsLava" => "лава", "Incinerator" => "уничтожитель предметов", "DrawBridge" => "подъёмный мост", _ => "неизвестная причина", }; Character attacker = val.GetAttacker(); Player val2 = (Player)(object)((attacker is Player) ? attacker : null); string text3 = ((val2 != null) ? val2.GetPlayerName() : (((Object)(object)attacker != (Object)null) ? attacker.m_name : null)); return text2 + " [" + text + "]" + (string.IsNullOrEmpty(text3) ? "" : ("; attacker=" + text3)); } internal static ZNetPeer FindPeer(ZRpc rpc) { if ((Object)(object)ZNet.instance == (Object)null || rpc == null) { return null; } foreach (ZNetPeer peer in ZNet.instance.GetPeers()) { if (peer.m_rpc == rpc) { return peer; } } return null; } internal static bool IsServerConnection(ZRpc rpc) { ZNet instance = ZNet.instance; if ((Object)(object)instance == (Object)null || instance.IsServer() || rpc == null || instance.GetServerRPC() != rpc) { return false; } ZNetPeer val = FindPeer(rpc); if (val != null && val.m_server) { return val.IsReady(); } return false; } internal static string GetPeerName(ZNetPeer peer) { return typeof(ZNetPeer).GetField("m_playerName", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(peer)?.ToString() ?? "unknown"; } internal static string GetPeerHost(ZNetPeer peer) { if (peer == null) { return null; } object obj = typeof(ZNetPeer).GetField("m_socket", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(peer); return obj?.GetType().GetMethod("GetHostName", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null)?.Invoke(obj, null)?.ToString(); } internal static bool IsAdmin(string host) { if ((Object)(object)ZNet.instance == (Object)null || string.IsNullOrWhiteSpace(host)) { return false; } return ZNet.instance.IsAdmin(host); } } [HarmonyPatch(typeof(Player), "OnDeath")] internal static class PlayerLocalDeathPatch { private static void Prefix(Player __instance) { ValheimDeathBanPlugin.Instance?.ReportLocalDeath(__instance); } } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] internal static class DeathBanPeerConnectionPatch { private static void Postfix(ZNetPeer peer) { ValheimDeathBanPlugin instance = ValheimDeathBanPlugin.Instance; if (!((Object)(object)instance == (Object)null)) { instance.EnsurePeerRpcs(); instance.RegisterPeerRpc(peer); } } }