Decompiled source of BirdHeimBypassPlugin v1.2.2

BirdHeimBypassPlugin.dll

Decompiled 11 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("BirdHeimBypassPlugin")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("BirdHeimBypassPlugin")]
[assembly: AssemblyTitle("BirdHeimBypassPlugin")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[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 BirdHeimBypassPlugin
{
	[BepInPlugin("pabloss.valheim.birdheimbypassplugin", "BirdHeimBypassPlugin", "1.2.2")]
	public class BirdHeimBypassPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "pabloss.valheim.birdheimbypassplugin";

		public const string PluginName = "BirdHeimBypassPlugin";

		public const string PluginVersion = "1.2.2";

		private const string RpcSyncWhitelist = "BHBP_SyncWhitelist";

		private static string _configDir = "";

		private static string _jsonPath = "";

		private static FileSystemWatcher? _watcher;

		private static HashSet<string> _whitelistedGuids = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private static readonly object _lock = new object();

		private static string _currentRawJson = "{\"BypassGuidList\":[]}";

		private static DateTime _lastReload = DateTime.MinValue;

		private static bool _rpcRegistered;

		private static bool _initialSynced;

		private static bool _loadingGuardPatched;

		public static ConfigEntry<bool> LockConfiguration = null;

		public static ConfigEntry<bool> DisableFlightSafeguard = null;

		private Harmony? _harmony;

		private void Awake()
		{
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Expected O, but got Unknown
			_configDir = Path.Combine(Paths.ConfigPath, "BirdHeimBypassPlugin");
			_jsonPath = Path.Combine(_configDir, "whitelist.json");
			Directory.CreateDirectory(_configDir);
			LockConfiguration = ((BaseUnityPlugin)this).Config.Bind<bool>("ServerSync", "LockConfiguration", true, "Gdy włączone na serwerze, lista whitelist.json z serwera nadpisuje lokalną listę u graczy w trakcie sesji.");
			DisableFlightSafeguard = ((BaseUnityPlugin)this).Config.Bind<bool>("BirdheimBypass", "DisableFlightSafeguard", true, "Wyłącza w Birdheim (LoadingGuard) ograniczenie lotu do 100 m w jednym obszarze przy wykryciu innych hooków.");
			LoadLocalWhitelist();
			SetupWatcher();
			_harmony = new Harmony("pabloss.valheim.birdheimbypassplugin");
			PatchConfigSyncInstances(_harmony);
			TryPatchLoadingGuard(_harmony);
		}

		private void Update()
		{
			if (!_loadingGuardPatched && _harmony != null)
			{
				TryPatchLoadingGuard(_harmony);
			}
			if (!_rpcRegistered && ZRoutedRpc.instance != null)
			{
				ZRoutedRpc.instance.Register<bool, string>("BHBP_SyncWhitelist", (Action<long, bool, string>)OnReceiveServerSync);
				_rpcRegistered = true;
			}
			if (_rpcRegistered && !_initialSynced && (Object)(object)ZNet.instance != (Object)null && (Object)(object)Player.m_localPlayer != (Object)null)
			{
				_initialSynced = true;
				if (IsServerAuthoritative())
				{
					BroadcastWhitelistToClients();
				}
			}
			if (_initialSynced && (Object)(object)ZNet.instance == (Object)null)
			{
				_initialSynced = false;
				LoadLocalWhitelist();
			}
		}

		private void OnDestroy()
		{
			_watcher?.Dispose();
			Harmony? harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		private static bool IsServerAuthoritative()
		{
			if (!((Object)(object)ZNet.instance == (Object)null))
			{
				return ZNet.instance.IsServer();
			}
			return true;
		}

		private static void OnReceiveServerSync(long sender, bool serverLocked, string serverJson)
		{
			if (!IsServerAuthoritative())
			{
				if (!serverLocked)
				{
					Debug.Log((object)"[BirdHeimBypassPlugin] Serwer ma wyłączone LockConfiguration – używam lokalnej whitelist.json.");
					LoadLocalWhitelist();
				}
				else if (!string.IsNullOrWhiteSpace(serverJson))
				{
					ApplyWhitelistJson(serverJson, "ServerSync");
				}
			}
		}

		private static void BroadcastWhitelistToClients()
		{
			if (ZRoutedRpc.instance != null && !((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer())
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(0L, "BHBP_SyncWhitelist", new object[2] { LockConfiguration.Value, _currentRawJson });
				Debug.Log((object)string.Format("[{0}] Wysłano whitelist.json przez ServerSync (Lock={1}).", "BirdHeimBypassPlugin", LockConfiguration.Value));
			}
		}

		private static void LoadLocalWhitelist()
		{
			lock (_lock)
			{
				if (!File.Exists(_jsonPath))
				{
					string contents = JsonUtility.ToJson((object)new WhitelistConfig
					{
						BypassGuidList = new List<string> { "pabloss.valheim.custommobnames", "expdare.meadworks.core.runtimeprefabs" }
					}, true);
					File.WriteAllText(_jsonPath, contents, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
				}
				try
				{
					ApplyWhitelistJson(_currentRawJson = File.ReadAllText(_jsonPath, Encoding.UTF8), "plik lokalny");
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)("[BirdHeimBypassPlugin] Błąd odczytu whitelist.json: " + ex.Message));
				}
			}
		}

		private static void ApplyWhitelistJson(string rawJson, string source)
		{
			try
			{
				WhitelistConfig whitelistConfig = JsonUtility.FromJson<WhitelistConfig>(rawJson);
				lock (_lock)
				{
					_whitelistedGuids = ((whitelistConfig?.BypassGuidList != null) ? new HashSet<string>(whitelistConfig.BypassGuidList, StringComparer.OrdinalIgnoreCase) : new HashSet<string>(StringComparer.OrdinalIgnoreCase));
				}
				Debug.Log((object)string.Format("[{0}] Załadowano {1} GUID-ów ({2}).", "BirdHeimBypassPlugin", _whitelistedGuids.Count, source));
			}
			catch (Exception ex)
			{
				Debug.LogWarning((object)("[BirdHeimBypassPlugin] Błąd parsowania JSON (" + source + "): " + ex.Message));
			}
		}

		private static void SetupWatcher()
		{
			_watcher = new FileSystemWatcher(_configDir, "whitelist.json")
			{
				NotifyFilter = (NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite),
				EnableRaisingEvents = true
			};
			FileSystemEventHandler value = delegate
			{
				if (!((DateTime.UtcNow - _lastReload).TotalMilliseconds < 250.0))
				{
					_lastReload = DateTime.UtcNow;
					Thread.Sleep(80);
					LoadLocalWhitelist();
					if (IsServerAuthoritative())
					{
						BroadcastWhitelistToClients();
					}
				}
			};
			_watcher.Changed += value;
			_watcher.Created += value;
		}

		public static bool IsModWhitelisted(string modGuid)
		{
			if (string.IsNullOrWhiteSpace(modGuid))
			{
				return false;
			}
			lock (_lock)
			{
				return _whitelistedGuids.Contains(modGuid.Trim());
			}
		}

		private static Type? FindLoadingGuardType()
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				if (assembly.GetName().Name.Equals("Birdheim", StringComparison.OrdinalIgnoreCase))
				{
					Type type = assembly.GetType("Birdheim.LoadingGuard");
					if (type != null)
					{
						return type;
					}
				}
			}
			return null;
		}

		private static void TryPatchLoadingGuard(Harmony harmony)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Expected O, but got Unknown
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Expected O, but got Unknown
			if (_loadingGuardPatched)
			{
				return;
			}
			Type type = FindLoadingGuardType();
			if (!(type == null))
			{
				MethodInfo method = type.GetMethod("Check", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				MethodInfo method2 = typeof(BirdHeimBypassPlugin).GetMethod("LoadingGuardCheckPostfix", BindingFlags.Static | BindingFlags.NonPublic);
				if (method != null && method2 != null)
				{
					harmony.Patch((MethodBase)method, (HarmonyMethod)null, new HarmonyMethod(method2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				MethodInfo method3 = type.GetMethod("get_SingleArea", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				MethodInfo method4 = typeof(BirdHeimBypassPlugin).GetMethod("SingleAreaPostfix", BindingFlags.Static | BindingFlags.NonPublic);
				if (method3 != null && method4 != null)
				{
					harmony.Patch((MethodBase)method3, (HarmonyMethod)null, new HarmonyMethod(method4), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				_loadingGuardPatched = true;
				Debug.Log((object)"[BirdHeimBypassPlugin] Podpięto patche pod Birdheim.LoadingGuard.");
			}
		}

		private static void SingleAreaPostfix(ref bool __result)
		{
			try
			{
				if (DisableFlightSafeguard.Value)
				{
					__result = false;
				}
			}
			catch
			{
			}
		}

		private static void LoadingGuardCheckPostfix()
		{
			try
			{
				if (!DisableFlightSafeguard.Value)
				{
					return;
				}
				Type type = FindLoadingGuardType();
				if (!(type == null))
				{
					FieldInfo field = type.GetField("s_single", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
					if (field != null && !field.IsLiteral && field.FieldType == typeof(bool))
					{
						field.SetValue(null, false);
					}
					FieldInfo field2 = type.GetField("s_told", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
					if (field2 != null && !field2.IsLiteral && field2.FieldType == typeof(bool))
					{
						field2.SetValue(null, true);
					}
					FieldInfo field3 = type.GetField("s_why", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
					if (field3 != null && !field3.IsLiteral && field3.FieldType == typeof(string))
					{
						field3.SetValue(null, string.Empty);
					}
				}
			}
			catch (Exception ex)
			{
				Debug.LogWarning((object)("[BirdHeimBypassPlugin] LoadingGuardCheckPostfix pominięty: " + ex.Message));
			}
		}

		private static void PatchConfigSyncInstances(Harmony harmony)
		{
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Expected O, but got Unknown
			MethodInfo method = typeof(BirdHeimBypassPlugin).GetMethod("SyncMethodPrefix", BindingFlags.Static | BindingFlags.NonPublic);
			if (method == null)
			{
				return;
			}
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				Type[] array;
				try
				{
					array = assembly.GetTypes();
				}
				catch (ReflectionTypeLoadException ex)
				{
					array = Array.FindAll(ex.Types, (Type t) => t != null);
				}
				Type[] array2 = array;
				foreach (Type type in array2)
				{
					if (type.Name != "ConfigSync")
					{
						continue;
					}
					string[] array3 = new string[2] { "RPC_FromServerConfigSync", "FromServerConfigSync" };
					foreach (string name in array3)
					{
						MethodInfo method2 = type.GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
						if (method2 != null)
						{
							harmony.Patch((MethodBase)method2, new HarmonyMethod(method), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
						}
					}
				}
			}
		}

		private static bool SyncMethodPrefix(object? __instance)
		{
			if (__instance == null)
			{
				return true;
			}
			string text = ExtractModGuid(__instance);
			if (!string.IsNullOrEmpty(text) && IsModWhitelisted(text))
			{
				return false;
			}
			return true;
		}

		private static string ExtractModGuid(object configSyncInstance)
		{
			Type type = configSyncInstance.GetType();
			if (type.GetField("Name", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(configSyncInstance) is string text && !string.IsNullOrWhiteSpace(text))
			{
				return text;
			}
			if (type.GetProperty("Name", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(configSyncInstance) is string text2 && !string.IsNullOrWhiteSpace(text2))
			{
				return text2;
			}
			return "";
		}
	}
	[Serializable]
	public class WhitelistConfig
	{
		public List<string> BypassGuidList = new List<string>();
	}
}