Decompiled source of ServerSideSave v0.1.0

ServerSideSave.dll

Decompiled a week ago
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using ServerSync;
using TMPro;
using UnityEngine;

[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: Guid("A2F1E7C4-6B3D-4E9A-9C2F-1D8B5E4A7F00")]
[assembly: ComVisible(false)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright © 2026")]
[assembly: AssemblyProduct("ServerSideSave")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyDescription("Server-side character save, load, and backup for Valheim")]
[assembly: AssemblyTitle("ServerSideSave")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.0.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<10feb7ed-e60f-4c88-95a3-1099a174f0c2>Embedded]
	internal sealed class <10feb7ed-e60f-4c88-95a3-1099a174f0c2>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[<10feb7ed-e60f-4c88-95a3-1099a174f0c2>Embedded]
	internal sealed class <f2a06230-3221-409a-8322-fa18508eeb85>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <f2a06230-3221-409a-8322-fa18508eeb85>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <f2a06230-3221-409a-8322-fa18508eeb85>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[<10feb7ed-e60f-4c88-95a3-1099a174f0c2>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	internal sealed class <802b2a64-2d28-45f3-90a5-d554b5f02235>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <802b2a64-2d28-45f3-90a5-d554b5f02235>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace ServerSideSave
{
	[<802b2a64-2d28-45f3-90a5-d554b5f02235>NullableContext(1)]
	[<f2a06230-3221-409a-8322-fa18508eeb85>Nullable(0)]
	internal static class CharacterBaseline
	{
		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		[<802b2a64-2d28-45f3-90a5-d554b5f02235>NullableContext(0)]
		private static class SendStoredProfileOnPeerInfo
		{
			[<802b2a64-2d28-45f3-90a5-d554b5f02235>NullableContext(1)]
			private static void Postfix(ZNet __instance, ZRpc rpc)
			{
				if (!__instance.IsServer())
				{
					return;
				}
				ZNetPeer peer = __instance.GetPeer(rpc);
				if (peer != null && !string.IsNullOrEmpty(peer.m_playerName))
				{
					string hostName = rpc.GetSocket().GetHostName();
					string path = OwnSavePath(hostName, peer.m_playerName);
					byte[] array2;
					if (File.Exists(path))
					{
						byte[] array = File.ReadAllBytes(path);
						array2 = new byte[array.Length + 1];
						array2[0] = 1;
						Buffer.BlockCopy(array, 0, array2, 1, array.Length);
						Plugin.Log.LogInfo((object)$"[Server] sending stored save ({array.Length} bytes) to {peer.m_playerName}");
					}
					else if (Plugin.ForceFreshCharacter.Value && SingleCharacterModePatch.FindEstablishedCharacterName(hostName) == null)
					{
						array2 = new byte[1] { 2 };
						Plugin.Log.LogInfo((object)("[Server] " + peer.m_playerName + " (" + hostName + ") has never connected to this server before, forcing a fresh character"));
					}
					else
					{
						array2 = new byte[1];
						Plugin.Log.LogInfo((object)("[Server] no stored save for " + peer.m_playerName + " (" + hostName + "), letting local data stand"));
					}
					ProfileTransfer.Send(rpc, "SSS_ServerProfile", array2);
				}
			}
		}

		internal const byte TagNoData = 0;

		internal const byte TagApplyData = 1;

		internal const byte TagForceFreshCharacter = 2;

		private static string OwnSavePath(string steamId, string charName)
		{
			return Path.Combine(SaveSystem.GetCharacterFolderPath((FileSource)2), "Steam_" + steamId + "_" + charName.ToLowerInvariant() + ".sss");
		}

		internal static void HandleClientProfile(ZRpc rpc, byte[] data)
		{
			ZNetPeer peer = ZNet.instance.GetPeer(rpc);
			if (peer != null && !string.IsNullOrEmpty(peer.m_playerName))
			{
				string hostName = rpc.GetSocket().GetHostName();
				string path = OwnSavePath(hostName, peer.m_playerName);
				if (File.Exists(path))
				{
					BackupExistingFile(path);
				}
				AtomicWrite(path, data);
				Plugin.Log.LogInfo((object)$"[Server] stored {data.Length} bytes for {peer.m_playerName} ({hostName})");
			}
		}

		private static void BackupExistingFile(string path)
		{
			string? directoryName = Path.GetDirectoryName(path);
			string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(path);
			string extension = Path.GetExtension(path);
			string text = DateTime.Now.ToString("yyyyMMdd-HHmmss");
			string destFileName = Path.Combine(directoryName, fileNameWithoutExtension + "_backup_auto-" + text + extension);
			File.Copy(path, destFileName, overwrite: true);
			PruneOldBackups(directoryName, fileNameWithoutExtension, extension);
		}

		private static void PruneOldBackups(string dir, string baseName, string ext)
		{
			foreach (string item in (from f in Directory.GetFiles(dir, baseName + "_backup_auto-*" + ext)
				orderby f descending
				select f).ToList().Skip(Plugin.MaxBackups.Value))
			{
				File.Delete(item);
			}
		}

		private static void AtomicWrite(string path, byte[] data)
		{
			string text = path + ".tmp";
			File.WriteAllBytes(text, data);
			if (File.Exists(path))
			{
				File.Delete(path);
			}
			File.Move(text, path);
		}
	}
	[<802b2a64-2d28-45f3-90a5-d554b5f02235>NullableContext(1)]
	[<f2a06230-3221-409a-8322-fa18508eeb85>Nullable(0)]
	internal static class Rpc
	{
		internal const string ServerProfileName = "SSS_ServerProfile";

		internal const string ClientProfileName = "SSS_ClientProfile";

		internal const string KickReasonName = "SSS_KickReason";
	}
	[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
	internal static class ShowKickReasonPatch
	{
		[<f2a06230-3221-409a-8322-fa18508eeb85>Nullable(2)]
		internal static string PendingReason;

		[<802b2a64-2d28-45f3-90a5-d554b5f02235>NullableContext(1)]
		private static void Postfix(FejdStartup __instance)
		{
			if (PendingReason != null && __instance.m_connectionFailedPanel.activeSelf)
			{
				TMP_Text connectionFailedError = __instance.m_connectionFailedError;
				connectionFailedError.text = connectionFailedError.text + "\n" + PendingReason;
				PendingReason = null;
			}
		}
	}
	[<802b2a64-2d28-45f3-90a5-d554b5f02235>NullableContext(1)]
	[<f2a06230-3221-409a-8322-fa18508eeb85>Nullable(0)]
	[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
	internal static class OnNewConnectionPatch
	{
		private static void Postfix(ZNet __instance, ZNetPeer peer)
		{
			if (__instance.IsServer())
			{
				peer.m_rpc.Register<ZPackage>("SSS_ClientProfile", (Action<ZRpc, ZPackage>)([<802b2a64-2d28-45f3-90a5-d554b5f02235>NullableContext(0)] (ZRpc rpc, [<f2a06230-3221-409a-8322-fa18508eeb85>Nullable(1)] ZPackage pkg) =>
				{
					ProfileTransfer.HandleIncoming(rpc, pkg, CharacterBaseline.HandleClientProfile);
				}));
				return;
			}
			peer.m_rpc.Register<ZPackage>("SSS_ServerProfile", (Action<ZRpc, ZPackage>)([<802b2a64-2d28-45f3-90a5-d554b5f02235>NullableContext(0)] (ZRpc rpc, [<f2a06230-3221-409a-8322-fa18508eeb85>Nullable(1)] ZPackage pkg) =>
			{
				ProfileTransfer.HandleIncoming(rpc, pkg, OnServerProfileReceived);
			}));
			peer.m_rpc.Register<string>("SSS_KickReason", (Action<ZRpc, string>)([<802b2a64-2d28-45f3-90a5-d554b5f02235>NullableContext(0)] (ZRpc _, [<f2a06230-3221-409a-8322-fa18508eeb85>Nullable(1)] string reason) =>
			{
				ShowKickReasonPatch.PendingReason = reason;
			}));
			ServerProfileGate.BeginWaiting();
		}

		private static void OnServerProfileReceived(ZRpc rpc, byte[] payload)
		{
			switch ((byte)((payload.Length != 0) ? payload[0] : 0))
			{
			case 1:
			{
				byte[] array = new byte[payload.Length - 1];
				Buffer.BlockCopy(payload, 1, array, 0, array.Length);
				Plugin.Log.LogInfo((object)$"[Client] received authoritative save ({array.Length} bytes) from server, applying before spawn");
				Game.instance.GetPlayerProfile().m_playerData = array;
				break;
			}
			case 2:
				Plugin.Log.LogInfo((object)"[Client] this server requires a fresh character on first connect; discarding local save data");
				Game.instance.GetPlayerProfile().m_playerData = null;
				break;
			default:
				Plugin.Log.LogInfo((object)"[Client] server has no stored save for this character, using local data");
				break;
			}
			ServerProfileGate.MarkReady();
		}
	}
	[HarmonyPatch(typeof(PlayerProfile), "SavePlayerToDisk")]
	internal static class SendProfileOnSavePatch
	{
		[<802b2a64-2d28-45f3-90a5-d554b5f02235>NullableContext(1)]
		private static void Postfix(PlayerProfile __instance, bool __result)
		{
			if (!__result || (Object)(object)ZNet.instance == (Object)null || ZNet.instance.IsServer())
			{
				return;
			}
			ZNetPeer serverPeer = ZNet.instance.GetServerPeer();
			if (serverPeer != null)
			{
				byte[] playerData = __instance.m_playerData;
				if (playerData != null && playerData.Length != 0)
				{
					Plugin.Log.LogInfo((object)$"[Client] profile saved locally, forwarding {playerData.Length} bytes to server");
					ProfileTransfer.Send(serverPeer.m_rpc, "SSS_ClientProfile", playerData);
				}
			}
		}
	}
	[<f2a06230-3221-409a-8322-fa18508eeb85>Nullable(0)]
	[BepInPlugin("ServerSideSave", "ServerSideSave", "0.1.0")]
	[<802b2a64-2d28-45f3-90a5-d554b5f02235>NullableContext(1)]
	public class Plugin : BaseUnityPlugin
	{
		public const string ModGUID = "ServerSideSave";

		public const string ModName = "ServerSideSave";

		public const string ModVersion = "0.1.0";

		internal static readonly ManualLogSource Log = Logger.CreateLogSource("ServerSideSave");

		private readonly Harmony harmony = new Harmony("ServerSideSave");

		internal static readonly ConfigSync ConfigSync = new ConfigSync("ServerSideSave")
		{
			DisplayName = "ServerSideSave",
			CurrentVersion = "0.1.0",
			MinimumRequiredVersion = "0.1.0",
			ModRequired = true
		};

		internal static ConfigEntry<bool> SingleCharacterMode = null;

		internal static ConfigEntry<int> MaxBackups = null;

		internal static ConfigEntry<bool> ForceFreshCharacter = null;

		internal static Plugin Instance = null;

		private void Awake()
		{
			Instance = this;
			SingleCharacterMode = ((BaseUnityPlugin)this).Config.Bind<bool>("Server", "SingleCharacterMode", true, "If true, each Steam ID may only join with the one character name it first connected with.");
			ConfigSync.AddConfigEntry<bool>(SingleCharacterMode);
			MaxBackups = ((BaseUnityPlugin)this).Config.Bind<int>("Server", "MaxBackups", 10, "Number of rotating timestamped backups to keep per character save.");
			ForceFreshCharacter = ((BaseUnityPlugin)this).Config.Bind<bool>("Server", "ForceFreshCharacter", true, "If true, a Steam ID that has never connected to this server before (no existing character file and no stored save) is forced to spawn with a brand-new default character, ignoring whatever local character data they connected with. Steam IDs that already had a character on this server before this setting existed are unaffected.");
			harmony.PatchAll(Assembly.GetExecutingAssembly());
			Log.LogInfo((object)"ServerSideSave 0.1.0 loaded");
		}

		private void OnDestroy()
		{
			harmony.UnpatchSelf();
		}
	}
	[<802b2a64-2d28-45f3-90a5-d554b5f02235>NullableContext(1)]
	[<f2a06230-3221-409a-8322-fa18508eeb85>Nullable(0)]
	internal static class ProfileTransfer
	{
		[<802b2a64-2d28-45f3-90a5-d554b5f02235>NullableContext(0)]
		private class ReassemblyState
		{
			[<f2a06230-3221-409a-8322-fa18508eeb85>Nullable(1)]
			public readonly Dictionary<int, byte[]> Fragments = new Dictionary<int, byte[]>();

			public int TotalFragments;
		}

		private const int ChunkSize = 200000;

		private const byte FlagSingle = 0;

		private const byte FlagFragment = 1;

		private static long nextTransferId;

		private static readonly ConditionalWeakTable<ZRpc, Dictionary<long, ReassemblyState>> reassemblyByPeer = new ConditionalWeakTable<ZRpc, Dictionary<long, ReassemblyState>>();

		internal static void Send(ZRpc rpc, string rpcName, byte[] rawData)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Expected O, but got Unknown
			byte[] array = Compress(rawData);
			if (array.Length <= 200000)
			{
				ZPackage val = new ZPackage();
				val.Write((byte)0);
				val.Write(array);
				rpc.Invoke(rpcName, new object[1] { val });
				return;
			}
			long num = Interlocked.Increment(ref nextTransferId);
			int num2 = (array.Length + 200000 - 1) / 200000;
			for (int i = 0; i < num2; i++)
			{
				int num3 = i * 200000;
				int num4 = Math.Min(200000, array.Length - num3);
				byte[] array2 = new byte[num4];
				Buffer.BlockCopy(array, num3, array2, 0, num4);
				ZPackage val2 = new ZPackage();
				val2.Write((byte)1);
				val2.Write(num);
				val2.Write(i);
				val2.Write(num2);
				val2.Write(array2);
				rpc.Invoke(rpcName, new object[1] { val2 });
			}
		}

		internal static void HandleIncoming(ZRpc rpc, ZPackage package, Action<ZRpc, byte[]> onComplete)
		{
			if (package.ReadByte() == 0)
			{
				onComplete(rpc, Decompress(package.ReadByteArray()));
				return;
			}
			long key = package.ReadLong();
			int key2 = package.ReadInt();
			int totalFragments = package.ReadInt();
			byte[] value = package.ReadByteArray();
			Dictionary<long, ReassemblyState> orCreateValue = reassemblyByPeer.GetOrCreateValue(rpc);
			if (!orCreateValue.TryGetValue(key, out var value2))
			{
				value2 = (orCreateValue[key] = new ReassemblyState
				{
					TotalFragments = totalFragments
				});
			}
			value2.Fragments[key2] = value;
			if (value2.Fragments.Count < value2.TotalFragments)
			{
				return;
			}
			orCreateValue.Remove(key);
			using MemoryStream memoryStream = new MemoryStream();
			for (int i = 0; i < value2.TotalFragments; i++)
			{
				memoryStream.Write(value2.Fragments[i], 0, value2.Fragments[i].Length);
			}
			onComplete(rpc, Decompress(memoryStream.ToArray()));
		}

		private static byte[] Compress(byte[] data)
		{
			using MemoryStream memoryStream = new MemoryStream();
			using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionLevel.Optimal, leaveOpen: true))
			{
				deflateStream.Write(data, 0, data.Length);
			}
			return memoryStream.ToArray();
		}

		private static byte[] Decompress(byte[] data)
		{
			using MemoryStream stream = new MemoryStream(data);
			using MemoryStream memoryStream = new MemoryStream();
			using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
			{
				deflateStream.CopyTo(memoryStream);
			}
			return memoryStream.ToArray();
		}
	}
	[HarmonyPatch(typeof(ZNet), "RPC_CharacterID")]
	[<802b2a64-2d28-45f3-90a5-d554b5f02235>NullableContext(1)]
	[<f2a06230-3221-409a-8322-fa18508eeb85>Nullable(0)]
	internal static class SingleCharacterModePatch
	{
		private const string BackupMarker = "_backup_auto-";

		private static void Postfix(ZNet __instance, ZRpc rpc)
		{
			if (!__instance.IsServer() || !Plugin.SingleCharacterMode.Value)
			{
				return;
			}
			ZNetPeer peer = __instance.GetPeer(rpc);
			if (peer != null && !string.IsNullOrEmpty(peer.m_playerName))
			{
				string hostName = rpc.GetSocket().GetHostName();
				string text = FindEstablishedCharacterName(hostName);
				if (text != null && !string.Equals(text, peer.m_playerName, StringComparison.OrdinalIgnoreCase))
				{
					Plugin.Log.LogWarning((object)("Rejecting connection: Steam ID " + hostName + " already has an established character \"" + text + "\" on this server, tried to join as \"" + peer.m_playerName + "\""));
					rpc.Invoke("SSS_KickReason", new object[1] { "One character only. You already have \"" + text + "\" on this server." });
					rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)12 });
					__instance.Disconnect(peer);
				}
			}
		}

		[return: <f2a06230-3221-409a-8322-fa18508eeb85>Nullable(2)]
		internal static string FindEstablishedCharacterName(string steamId)
		{
			string characterFolderPath = SaveSystem.GetCharacterFolderPath((FileSource)2);
			if (!Directory.Exists(characterFolderPath))
			{
				return null;
			}
			string prefix = "Steam_" + steamId + "_";
			return (from name in Directory.EnumerateFiles(characterFolderPath, prefix + "*.fch").Select(Path.GetFileNameWithoutExtension)
				where name != null && !name.Contains("_backup_auto-")
				select name.Substring(prefix.Length)).FirstOrDefault();
		}
	}
	internal static class ServerProfileGate
	{
		private const float TimeoutSeconds = 10f;

		private static float deadline;

		private static bool hasGatedSpawn;

		private static bool isReady;

		internal static void BeginWaiting()
		{
			isReady = false;
			hasGatedSpawn = false;
			deadline = Time.time + 10f;
		}

		internal static void MarkReady()
		{
			isReady = true;
		}

		internal static bool ShouldLetSpawnProceed()
		{
			if (hasGatedSpawn || isReady)
			{
				hasGatedSpawn = true;
				return true;
			}
			if (Time.time >= deadline)
			{
				hasGatedSpawn = true;
				Plugin.Log.LogWarning((object)"[Client] Timed out waiting for the server profile; spawning with local save data");
				return true;
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(Game), "_RequestRespawn")]
	internal static class GateInitialSpawnPatch
	{
		[<802b2a64-2d28-45f3-90a5-d554b5f02235>NullableContext(1)]
		private static bool Prefix(Game __instance)
		{
			if ((Object)(object)ZNet.instance == (Object)null || ZNet.instance.IsServer())
			{
				return true;
			}
			if (ServerProfileGate.ShouldLetSpawnProceed())
			{
				return true;
			}
			((MonoBehaviour)__instance).Invoke("_RequestRespawn", 0.2f);
			return false;
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[Embedded]
	[CompilerGenerated]
	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;
		}
	}
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	[Embedded]
	[CompilerGenerated]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ServerSync
{
	[PublicAPI]
	internal abstract class OwnConfigEntryBase
	{
		public object? LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	[PublicAPI]
	internal class SyncedConfigEntry<T>(ConfigEntry<T> sourceConfig) : OwnConfigEntryBase()
	{
		public readonly ConfigEntry<T> SourceConfig = sourceConfig;

		public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig;

		public T Value
		{
			get
			{
				return SourceConfig.Value;
			}
			set
			{
				SourceConfig.Value = value;
			}
		}

		public void AssignLocalValue(T value)
		{
			if (LocalBaseValue == null)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal abstract class CustomSyncedValueBase
	{
		public object? LocalBaseValue;

		public readonly string Identifier;

		public readonly Type Type;

		private object? boxedValue;

		protected bool localIsOwner;

		public readonly int Priority;

		public object? BoxedValue
		{
			get
			{
				return boxedValue;
			}
			set
			{
				boxedValue = value;
				this.ValueChanged?.Invoke();
			}
		}

		public event Action? ValueChanged;

		protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority)
		{
			Priority = priority;
			Identifier = identifier;
			Type = type;
			configSync.AddCustomValue(this);
			localIsOwner = configSync.IsSourceOfTruth;
			configSync.SourceOfTruthChanged += delegate(bool truth)
			{
				localIsOwner = truth;
			};
		}
	}
	[PublicAPI]
	internal sealed class CustomSyncedValue<T> : CustomSyncedValueBase
	{
		public T Value
		{
			get
			{
				return (T)base.BoxedValue;
			}
			set
			{
				base.BoxedValue = value;
			}
		}

		public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0)
			: base(configSync, identifier, typeof(T), priority)
		{
			Value = value;
		}

		public void AssignLocalValue(T value)
		{
			if (localIsOwner)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal class ConfigurationManagerAttributes
	{
		[UsedImplicitly]
		public bool? ReadOnly = false;
	}
	[PublicAPI]
	internal class ConfigSync
	{
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		private static class SnatchCurrentlyHandlingRPC
		{
			public static ZRpc? currentRpc;

			[HarmonyPrefix]
			private static void Prefix(ZRpc __instance)
			{
				currentRpc = __instance;
			}
		}

		[HarmonyPatch(typeof(ZNet), "Awake")]
		internal static class RegisterRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance)
			{
				isServer = __instance.IsServer();
				foreach (ConfigSync configSync2 in configSyncs)
				{
					ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync);
					if (isServer)
					{
						configSync2.InitialSyncDone = true;
						Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"));
					}
				}
				if (isServer)
				{
					((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges());
				}
				static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
				{
					ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1]
					{
						new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = isAdmin
						}
					});
					ConfigSync configSync = configSyncs.First();
					if (configSync != null)
					{
						((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package));
					}
				}
				static IEnumerator WatchAdminListChanges()
				{
					MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
					SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					List<string> CurrentList = new List<string>(adminList.GetList());
					while (true)
					{
						yield return (object)new WaitForSeconds(30f);
						if (!adminList.GetList().SequenceEqual(CurrentList))
						{
							CurrentList = new List<string>(adminList.GetList());
							List<ZNetPeer> list = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p)
							{
								string hostName = p.m_rpc.GetSocket().GetHostName();
								return ((object)listContainsId != null) ? ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })) : adminList.Contains(hostName);
							}).ToList();
							SendAdmin(ZNet.instance.GetPeers().Except(list).ToList(), isAdmin: false);
							SendAdmin(list, isAdmin: true);
						}
					}
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static class RegisterClientRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (__instance.IsServer())
				{
					return;
				}
				foreach (ConfigSync configSync in configSyncs)
				{
					peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync);
				}
			}
		}

		private class ParsedConfigs
		{
			public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>();

			public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>();
		}

		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		private class ResetConfigsOnShutdown
		{
			[HarmonyPostfix]
			private static void Postfix()
			{
				ProcessingServerUpdate = true;
				foreach (ConfigSync configSync in configSyncs)
				{
					configSync.resetConfigsFromServer();
					configSync.IsSourceOfTruth = true;
					configSync.InitialSyncDone = false;
				}
				ProcessingServerUpdate = false;
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private class SendConfigsAfterLogin
		{
			private class BufferingSocket : ZPlayFabSocket, ISocket
			{
				public volatile bool finished;

				public volatile int versionMatchQueued = -1;

				public readonly List<ZPackage> Package = new List<ZPackage>();

				public readonly ISocket Original;

				public BufferingSocket(ISocket original)
				{
					Original = original;
					((ZPlayFabSocket)this)..ctor();
				}

				public bool IsConnected()
				{
					return Original.IsConnected();
				}

				public ZPackage Recv()
				{
					return Original.Recv();
				}

				public int GetSendQueueSize()
				{
					return Original.GetSendQueueSize();
				}

				public int GetCurrentSendRate()
				{
					return Original.GetCurrentSendRate();
				}

				public bool IsHost()
				{
					return Original.IsHost();
				}

				public void Dispose()
				{
					Original.Dispose();
				}

				public bool GotNewData()
				{
					return Original.GotNewData();
				}

				public void Close()
				{
					Original.Close();
				}

				public string GetEndPointString()
				{
					return Original.GetEndPointString();
				}

				public void GetAndResetStats(out int totalSent, out int totalRecv)
				{
					Original.GetAndResetStats(ref totalSent, ref totalRecv);
				}

				public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec)
				{
					Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec);
				}

				public ISocket Accept()
				{
					return Original.Accept();
				}

				public int GetHostPort()
				{
					return Original.GetHostPort();
				}

				public bool Flush()
				{
					return Original.Flush();
				}

				public string GetHostName()
				{
					return Original.GetHostName();
				}

				public void VersionMatch()
				{
					if (finished)
					{
						Original.VersionMatch();
					}
					else
					{
						versionMatchQueued = Package.Count;
					}
				}

				public void Send(ZPackage pkg)
				{
					//IL_004c: Unknown result type (might be due to invalid IL or missing references)
					//IL_0052: Expected O, but got Unknown
					int pos = pkg.GetPos();
					pkg.SetPos(0);
					int num = pkg.ReadInt();
					if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished)
					{
						ZPackage val = new ZPackage(pkg.GetArray());
						val.SetPos(pos);
						Package.Add(val);
					}
					else
					{
						pkg.SetPos(pos);
						Original.Send(pkg);
					}
				}
			}

			[HarmonyPrefix]
			[HarmonyPriority(800)]
			private static void Prefix(ref Dictionary<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0073: Unknown result type (might be due to invalid IL or missing references)
				if (!__instance.IsServer())
				{
					return;
				}
				BufferingSocket bufferingSocket = new BufferingSocket(rpc.GetSocket());
				AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket);
				object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
				ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
				if (val != null && (int)ZNet.m_onlineBackend != 0)
				{
					FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket");
					object? value = fieldInfo.GetValue(val);
					ZPlayFabSocket val2 = (ZPlayFabSocket)((value is ZPlayFabSocket) ? value : null);
					if (val2 != null)
					{
						typeof(ZPlayFabSocket).GetField("m_remotePlayerId").SetValue(bufferingSocket, val2.m_remotePlayerId);
					}
					fieldInfo.SetValue(val, bufferingSocket);
				}
				if (__state == null)
				{
					__state = new Dictionary<Assembly, BufferingSocket>();
				}
				__state[Assembly.GetExecutingAssembly()] = bufferingSocket;
			}

			[HarmonyPostfix]
			private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				ZNetPeer peer;
				if (__instance.IsServer())
				{
					object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (peer == null)
					{
						SendBufferedData();
					}
					else
					{
						((MonoBehaviour)__instance).StartCoroutine(sendAsync());
					}
				}
				void SendBufferedData()
				{
					if (rpc.GetSocket() is BufferingSocket bufferingSocket)
					{
						AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original);
						object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
						ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null);
						if (val != null)
						{
							AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original);
						}
					}
					BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()];
					bufferingSocket2.finished = true;
					for (int i = 0; i < bufferingSocket2.Package.Count; i++)
					{
						if (i == bufferingSocket2.versionMatchQueued)
						{
							bufferingSocket2.Original.VersionMatch();
						}
						bufferingSocket2.Original.Send(bufferingSocket2.Package[i]);
					}
					if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued)
					{
						bufferingSocket2.Original.VersionMatch();
					}
				}
				IEnumerator sendAsync()
				{
					foreach (ConfigSync configSync in configSyncs)
					{
						List<PackageEntry> list = new List<PackageEntry>();
						if (configSync.CurrentVersion != null)
						{
							list.Add(new PackageEntry
							{
								section = "Internal",
								key = "serverversion",
								type = typeof(string),
								value = configSync.CurrentVersion
							});
						}
						MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						list.Add(new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = (((object)methodInfo == null) ? ((object)val.Contains(rpc.GetSocket().GetHostName())) : methodInfo.Invoke(ZNet.instance, new object[2]
							{
								val,
								rpc.GetSocket().GetHostName()
							}))
						});
						ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, list, partial: false);
						yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
					}
					SendBufferedData();
				}
			}
		}

		private class PackageEntry
		{
			public string section;

			public string key;

			public Type type;

			public object? value;
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")]
		private static class PreventSavingServerInfo
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, ref string __result)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase))
				{
					return true;
				}
				__result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType);
				return false;
			}
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")]
		private static class PreventConfigRereadChangingValues
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, string value)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null)
				{
					return true;
				}
				try
				{
					ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
				}
				return false;
			}
		}

		private class InvalidDeserializationTypeException : Exception
		{
			public string expected;

			public string received;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		public string? DisplayName;

		public string? CurrentVersion;

		public string? MinimumRequiredVersion;

		public bool ModRequired;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

		private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>();

		private HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>();

		private static bool isServer;

		private static bool lockExempt;

		private OwnConfigEntryBase? lockedConfig;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

		private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>();

		private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>();

		private static long packageCounter;

		public bool IsLocked
		{
			get
			{
				bool? flag = forceConfigLocking;
				bool num;
				if (!flag.HasValue)
				{
					if (lockedConfig == null)
					{
						goto IL_0051;
					}
					num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0;
				}
				else
				{
					num = flag == true;
				}
				if (num)
				{
					return !lockExempt;
				}
				goto IL_0051;
				IL_0051:
				return false;
			}
			set
			{
				forceConfigLocking = value;
			}
		}

		public bool IsAdmin
		{
			get
			{
				if (!lockExempt)
				{
					return isSourceOfTruth;
				}
				return true;
			}
		}

		public bool IsSourceOfTruth
		{
			get
			{
				return isSourceOfTruth;
			}
			private set
			{
				if (value != isSourceOfTruth)
				{
					isSourceOfTruth = value;
					this.SourceOfTruthChanged?.Invoke(value);
				}
			}
		}

		public bool InitialSyncDone { get; private set; }

		public event Action<bool>? SourceOfTruthChanged;

		private event Action? lockedConfigChanged;

		static ConfigSync()
		{
			ProcessingServerUpdate = false;
			configSyncs = new HashSet<ConfigSync>();
			lockExempt = false;
			packageCounter = 0L;
			RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle);
		}

		public ConfigSync(string name)
		{
			Name = name;
			configSyncs.Add(this);
			new VersionCheck(this);
		}

		public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry)
		{
			OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry);
			SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>;
			if (syncedEntry == null)
			{
				syncedEntry = new SyncedConfigEntry<T>(configEntry);
				AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1]
				{
					new ConfigurationManagerAttributes()
				}.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray());
				configEntry.SettingChanged += delegate
				{
					if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
					{
						Broadcast(0L, (ConfigEntryBase)configEntry);
					}
				};
				allConfigs.Add(syncedEntry);
			}
			return syncedEntry;
		}

		public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible
		{
			if (lockedConfig != null)
			{
				throw new Exception("Cannot initialize locking ConfigEntry twice");
			}
			lockedConfig = AddConfigEntry<T>(lockingConfig);
			lockingConfig.SettingChanged += delegate
			{
				this.lockedConfigChanged?.Invoke();
			};
			return (SyncedConfigEntry<T>)lockedConfig;
		}

		internal void AddCustomValue(CustomSyncedValueBase customValue)
		{
			if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier))
			{
				throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)");
			}
			allCustomValues.Add(customValue);
			allCustomValues = new HashSet<CustomSyncedValueBase>(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority));
			customValue.ValueChanged += delegate
			{
				if (!ProcessingServerUpdate)
				{
					Broadcast(0L, customValue);
				}
			};
		}

		private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package)
		{
			lockedConfigChanged += serverLockedSettingChanged;
			IsSourceOfTruth = false;
			if (HandleConfigSyncRPC(0L, package, clientUpdate: false))
			{
				InitialSyncDone = true;
			}
		}

		private void RPC_FromOtherClientConfigSync(long sender, ZPackage package)
		{
			HandleConfigSyncRPC(sender, package, clientUpdate: true);
		}

		private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate)
		{
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Expected O, but got Unknown
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Expected O, but got Unknown
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			try
			{
				if (isServer && IsLocked)
				{
					ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc;
					object obj;
					if (currentRpc == null)
					{
						obj = null;
					}
					else
					{
						ISocket socket = currentRpc.GetSocket();
						obj = ((socket != null) ? socket.GetHostName() : null);
					}
					string text = (string)obj;
					if (text != null)
					{
						MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text }))))
						{
							return false;
						}
					}
				}
				cacheExpirations.RemoveAll(delegate(KeyValuePair<long, string> kv)
				{
					if (kv.Key < DateTimeOffset.Now.Ticks)
					{
						configValueCache.Remove(kv.Value);
						return true;
					}
					return false;
				});
				byte b = package.ReadByte();
				if ((b & 2) != 0)
				{
					long num = package.ReadLong();
					string text2 = sender.ToString() + num;
					if (!configValueCache.TryGetValue(text2, out SortedDictionary<int, byte[]> value))
					{
						value = new SortedDictionary<int, byte[]>();
						configValueCache[text2] = value;
						cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2));
					}
					int key = package.ReadInt();
					int num2 = package.ReadInt();
					value.Add(key, package.ReadByteArray());
					if (value.Count < num2)
					{
						return false;
					}
					configValueCache.Remove(text2);
					package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray());
					b = package.ReadByte();
				}
				ProcessingServerUpdate = true;
				if ((b & 4) != 0)
				{
					MemoryStream stream = new MemoryStream(package.ReadByteArray());
					MemoryStream memoryStream = new MemoryStream();
					using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
					{
						deflateStream.CopyTo(memoryStream);
					}
					package = new ZPackage(memoryStream.ToArray());
					b = package.ReadByte();
				}
				if ((b & 1) == 0)
				{
					resetConfigsFromServer();
				}
				ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package);
				ConfigFile val2 = null;
				bool saveOnConfigSet = false;
				foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues)
				{
					if (!isServer && configValue.Key.LocalBaseValue == null)
					{
						configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue;
					}
					if (val2 == null)
					{
						val2 = configValue.Key.BaseConfig.ConfigFile;
						saveOnConfigSet = val2.SaveOnConfigSet;
						val2.SaveOnConfigSet = false;
					}
					configValue.Key.BaseConfig.BoxedValue = configValue.Value;
				}
				if (val2 != null)
				{
					val2.SaveOnConfigSet = saveOnConfigSet;
					val2.Save();
				}
				foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues)
				{
					if (!isServer)
					{
						CustomSyncedValueBase key2 = customValue.Key;
						if (key2.LocalBaseValue == null)
						{
							key2.LocalBaseValue = customValue.Key.BoxedValue;
						}
					}
					customValue.Key.BoxedValue = customValue.Value;
				}
				Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name));
				if (!isServer)
				{
					serverLockedSettingChanged();
				}
				return true;
			}
			finally
			{
				ProcessingServerUpdate = false;
			}
		}

		private ParsedConfigs ReadConfigsFromPackage(ZPackage package)
		{
			ParsedConfigs parsedConfigs = new ParsedConfigs();
			Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c);
			Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c);
			int num = package.ReadInt();
			for (int num2 = 0; num2 < num; num2++)
			{
				string text = package.ReadString();
				string text2 = package.ReadString();
				string text3 = package.ReadString();
				Type type = Type.GetType(text3);
				if (text3 == "" || type != null)
				{
					object obj;
					try
					{
						obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type));
					}
					catch (InvalidDeserializationTypeException ex)
					{
						Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected));
						continue;
					}
					OwnConfigEntryBase value2;
					if (text == "Internal")
					{
						CustomSyncedValueBase value;
						if (text2 == "serverversion")
						{
							if (obj?.ToString() != CurrentVersion)
							{
								Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")));
							}
						}
						else if (text2 == "lockexempt")
						{
							if (obj is bool flag)
							{
								lockExempt = flag;
							}
						}
						else if (dictionary2.TryGetValue(text2, out value))
						{
							if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3)
							{
								parsedConfigs.customValues[value] = obj;
								continue;
							}
							Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName));
						}
					}
					else if (dictionary.TryGetValue(text + "_" + text2, out value2))
					{
						Type type2 = configType(value2.BaseConfig);
						if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3)
						{
							parsedConfigs.configValues[value2] = obj;
							continue;
						}
						Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName));
					}
					else
					{
						Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."));
					}
					continue;
				}
				Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs"));
				return new ParsedConfigs();
			}
			return parsedConfigs;
		}

		private static bool isWritableConfig(OwnConfigEntryBase config)
		{
			ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config));
			if (configSync == null)
			{
				return true;
			}
			if (!configSync.IsSourceOfTruth && config.SynchronizedConfig && config.LocalBaseValue != null)
			{
				if (!configSync.IsLocked)
				{
					if (config == configSync.lockedConfig)
					{
						return lockExempt;
					}
					return true;
				}
				return false;
			}
			return true;
		}

		private void serverLockedSettingChanged()
		{
			foreach (OwnConfigEntryBase allConfig in allConfigs)
			{
				configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig);
			}
		}

		private void resetConfigsFromServer()
		{
			ConfigFile val = null;
			bool saveOnConfigSet = false;
			foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null))
			{
				if (val == null)
				{
					val = item.BaseConfig.ConfigFile;
					saveOnConfigSet = val.SaveOnConfigSet;
					val.SaveOnConfigSet = false;
				}
				item.BaseConfig.BoxedValue = item.LocalBaseValue;
				item.LocalBaseValue = null;
			}
			if (val != null)
			{
				val.SaveOnConfigSet = saveOnConfigSet;
			}
			foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null))
			{
				item2.BoxedValue = item2.LocalBaseValue;
				item2.LocalBaseValue = null;
			}
			lockedConfigChanged -= serverLockedSettingChanged;
			serverLockedSettingChanged();
		}

		private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
		{
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc == null)
			{
				yield break;
			}
			byte[] data = package.GetArray();
			if (data != null && data.LongLength > 250000)
			{
				int fragments = (int)(1 + (data.LongLength - 1) / 250000);
				long packageIdentifier = ++packageCounter;
				int fragment = 0;
				while (fragment < fragments)
				{
					foreach (bool item in waitForQueue())
					{
						yield return item;
					}
					if (peer.m_socket.IsConnected())
					{
						ZPackage val = new ZPackage();
						val.Write((byte)2);
						val.Write(packageIdentifier);
						val.Write(fragment);
						val.Write(fragments);
						val.Write(data.Skip(250000 * fragment).Take(250000).ToArray());
						SendPackage(val);
						if (fragment != fragments - 1)
						{
							yield return true;
						}
						int num = fragment + 1;
						fragment = num;
						continue;
					}
					break;
				}
				yield break;
			}
			foreach (bool item2 in waitForQueue())
			{
				yield return item2;
			}
			SendPackage(package);
			void SendPackage(ZPackage pkg)
			{
				string text = Name + " ConfigSync";
				if (isServer)
				{
					peer.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg });
				}
			}
			IEnumerable<bool> waitForQueue()
			{
				float timeout = Time.time + 30f;
				while (peer.m_socket.GetSendQueueSize() > 20000)
				{
					if (Time.time > timeout)
					{
						Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout");
						peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 });
						ZNet.instance.Disconnect(peer);
						break;
					}
					yield return false;
				}
			}
		}

		private IEnumerator sendZPackage(long target, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				return Enumerable.Empty<object>().GetEnumerator();
			}
			List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance);
			if (target != 0L)
			{
				list = list.Where((ZNetPeer p) => p.m_uid == target).ToList();
			}
			return sendZPackage(list, package);
		}

		private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] array = package.GetArray();
			if (array != null && array.LongLength > 10000)
			{
				ZPackage val = new ZPackage();
				val.Write((byte)4);
				MemoryStream memoryStream = new MemoryStream();
				using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionLevel.Optimal))
				{
					deflateStream.Write(array, 0, array.Length);
				}
				val.Write(memoryStream.ToArray());
				package = val;
			}
			List<IEnumerator<bool>> writers = (from p in peers
				where p.IsReady()
				select distributeConfigToPeers(p, package)).ToList();
			writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			while (writers.Count > 0)
			{
				yield return null;
				writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			}
		}

		private void Broadcast(long target, params ConfigEntryBase[] configs)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(configs);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private void Broadcast(long target, params CustomSyncedValueBase[] customValues)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(null, customValues);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private static OwnConfigEntryBase? configData(ConfigEntryBase config)
		{
			return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault();
		}

		public static SyncedConfigEntry<T>? ConfigData<T>(ConfigEntry<T> config)
		{
			return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault();
		}

		private static T configAttribute<T>(ConfigEntryBase config)
		{
			return config.Description.Tags.OfType<T>().First();
		}

		private static Type configType(ConfigEntryBase config)
		{
			return configType(config.SettingType);
		}

		private static Type configType(Type type)
		{
			if (!type.IsEnum)
			{
				return type;
			}
			return Enum.GetUnderlyingType(type);
		}

		private static ZPackage ConfigsToPackage(IEnumerable<ConfigEntryBase>? configs = null, IEnumerable<CustomSyncedValueBase>? customValues = null, IEnumerable<PackageEntry>? packageEntries = null, bool partial = true)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			List<ConfigEntryBase> list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>();
			List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>();
			ZPackage val = new ZPackage();
			val.Write(partial ? ((byte)1) : ((byte)0));
			val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0));
			foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>())
			{
				AddEntryToPackage(val, item);
			}
			foreach (CustomSyncedValueBase item2 in list2)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = "Internal",
					key = item2.Identifier,
					type = item2.Type,
					value = item2.BoxedValue
				});
			}
			foreach (ConfigEntryBase item3 in list)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = item3.Definition.Section,
					key = item3.Definition.Key,
					type = configType(item3),
					value = item3.BoxedValue
				});
			}
			return val;
		}

		private static void AddEntryToPackage(ZPackage package, PackageEntry entry)
		{
			package.Write(entry.section);
			package.Write(entry.key);
			package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type));
			AddValueToZPackage(package, entry.value);
		}

		private static string GetZPackageTypeString(Type type)
		{
			return type.AssemblyQualifiedName;
		}

		private static void AddValueToZPackage(ZPackage package, object? value)
		{
			Type type = value?.GetType();
			if (value is Enum)
			{
				value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture);
			}
			else
			{
				if (value is ICollection collection)
				{
					package.Write(collection.Count);
					{
						foreach (object item in collection)
						{
							AddValueToZPackage(package, item);
						}
						return;
					}
				}
				if ((object)type != null && type.IsValueType && !type.IsPrimitive)
				{
					FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					package.Write(fields.Length);
					FieldInfo[] array = fields;
					foreach (FieldInfo fieldInfo in array)
					{
						package.Write(GetZPackageTypeString(fieldInfo.FieldType));
						AddValueToZPackage(package, fieldInfo.GetValue(value));
					}
					return;
				}
			}
			ZRpc.Serialize(new object[1] { value }, ref package);
		}

		private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type)
		{
			if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum)
			{
				FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				int num = package.ReadInt();
				if (num != fields.Length)
				{
					throw new InvalidDeserializationTypeException
					{
						received = $"(field count: {num})",
						expected = $"(field count: {fields.Length})"
					};
				}
				object uninitializedObject = FormatterServices.GetUninitializedObject(type);
				FieldInfo[] array = fields;
				foreach (FieldInfo fieldInfo in array)
				{
					string text = package.ReadString();
					if (text != GetZPackageTypeString(fieldInfo.FieldType))
					{
						throw new InvalidDeserializationTypeException
						{
							received = text,
							expected = GetZPackageTypeString(fieldInfo.FieldType),
							field = fieldInfo.Name
						};
					}
					fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType));
				}
				return uninitializedObject;
			}
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >))
			{
				int num2 = package.ReadInt();
				IDictionary dictionary = (IDictionary)Activator.CreateInstance(type);
				Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments);
				FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic);
				FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic);
				for (int j = 0; j < num2; j++)
				{
					object obj = ReadValueWithTypeFromZPackage(package, type2);
					dictionary.Add(field.GetValue(obj), field2.GetValue(obj));
				}
				return dictionary;
			}
			if (type != typeof(List<string>) && type.IsGenericType)
			{
				Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]);
				if ((object)type3 != null && type3.IsAssignableFrom(type))
				{
					int num3 = package.ReadInt();
					object obj2 = Activator.CreateInstance(type);
					MethodInfo method = type3.GetMethod("Add");
					for (int k = 0; k < num3; k++)
					{
						method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) });
					}
					return obj2;
				}
			}
			ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo));
			AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type);
			List<object> source = new List<object>();
			ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source);
			return source.First();
		}
	}
	[PublicAPI]
	[HarmonyPatch]
	internal class VersionCheck
	{
		private static readonly HashSet<VersionCheck> versionChecks;

		private static readonly Dictionary<string, string> notProcessedNames;

		public string Name;

		private string? displayName;

		private string? currentVersion;

		private string? minimumRequiredVersion;

		public bool ModRequired = true;

		private string? ReceivedCurrentVersion;

		private string? ReceivedMinimumRequiredVersion;

		private readonly List<ZRpc> ValidatedClients = new List<ZRpc>();

		private ConfigSync? ConfigSync;

		public string DisplayName
		{
			get
			{
				return displayName ?? Name;
			}
			set
			{
				displayName = value;
			}
		}

		public string CurrentVersion
		{
			get
			{
				return currentVersion ?? "0.0.0";
			}
			set
			{
				currentVersion = value;
			}
		}

		public string MinimumRequiredVersion
		{
			get
			{
				string text = minimumRequiredVersion;
				if (text == null)
				{
					if (!ModRequired)
					{
						return "0.0.0";
					}
					text = CurrentVersion;
				}
				return text;
			}
			set
			{
				minimumRequiredVersion = value;
			}
		}

		private static void PatchServerSync()
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null));
			if (patchInfo != null && patchInfo.Postfixes.Count((Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0)
			{
				return;
			}
			Harmony val = new Harmony("org.bepinex.helpers.ServerSync");
			foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) })
				where t.IsClass
				select t)
			{
				val.PatchAll(item);
			}
		}

		static VersionCheck()
		{
			versionChecks = new HashSet<VersionCheck>();
			notProcessedNames = new Dictionary<string, string>();
			typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1]
			{
				new Action(PatchServerSync)
			});
		}

		public VersionCheck(string name)
		{
			Name = name;
			ModRequired = true;
			versionChecks.Add(this);
		}

		public VersionCheck(ConfigSync configSync)
		{
			ConfigSync = configSync;
			Name = ConfigSync.Name;
			versionChecks.Add(this);
		}

		public void Initialize()
		{
			ReceivedCurrentVersion = null;
			ReceivedMinimumRequiredVersion = null;
			if (ConfigSync != null)
			{
				Name = ConfigSync.Name;
				DisplayName = ConfigSync.DisplayName;
				CurrentVersion = ConfigSync.CurrentVersion;
				MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion;
				ModRequired = ConfigSync.ModRequired;
			}
		}

		private bool IsVersionOk()
		{
			if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null)
			{
				return !ModRequired;
			}
			bool num = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion);
			bool flag = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion);
			return num && flag;
		}

		private string ErrorClient()
		{
			if (ReceivedMinimumRequiredVersion == null)
			{
				return DisplayName + " is not installed on the server.";
			}
			if (!(new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)))
			{
				return DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". You have version " + CurrentVersion + ".";
			}
			return DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + ".";
		}

		private string ErrorServer(ZRpc rpc)
		{
			return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion;
		}

		private string Error(ZRpc? rpc = null)
		{
			if (rpc != null)
			{
				return ErrorServer(rpc);
			}
			return ErrorClient();
		}

		private static VersionCheck[] GetFailedClient()
		{
			return versionChecks.Where((VersionCheck check) => !check.IsVersionOk()).ToArray();
		}

		private static VersionCheck[] GetFailedServer(ZRpc rpc)
		{
			return versionChecks.Where((VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc)).ToArray();
		}

		private static void Logout()
		{
			Game.instance.Logout(true, true);
			AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3);
		}

		private static void DisconnectClient(ZRpc rpc)
		{
			rpc.Invoke("Error", new object[1] { 3 });
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg)
		{
			CheckVersion(rpc, pkg, null);
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg, Action<ZRpc, ZPackage>? original)
		{
			string text = pkg.ReadString();
			string text2 = pkg.ReadString();
			string text3 = pkg.ReadString();
			bool flag = false;
			foreach (VersionCheck versionCheck in versionChecks)
			{
				if (!(text != versionCheck.Name))
				{
					Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + "."));
					versionCheck.ReceivedMinimumRequiredVersion = text2;
					versionCheck.ReceivedCurrentVersion = text3;
					if (ZNet.instance.IsServer() && versionCheck.IsVersionOk())
					{
						versionCheck.ValidatedClients.Add(rpc);
					}
					flag = true;
				}
			}
			if (flag)
			{
				return;
			}
			pkg.SetPos(0);
			if (original != null)
			{
				original(rpc, pkg);
				if (pkg.GetPos() == 0)
				{
					notProcessedNames.Add(text, text3);
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		[HarmonyPrefix]
		private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance)
		{
			VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient());
			if (array.Length == 0)
			{
				return true;
			}
			VersionCheck[] array2 = array;
			for (int i = 0; i < array2.Length; i++)
			{
				Debug.LogWarning((object)array2[i].Error(rpc));
			}
			if (__instance.IsServer())
			{
				DisconnectClient(rpc);
			}
			else
			{
				Logout();
			}
			return false;
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		[HarmonyPrefix]
		private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance)
		{
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Expected O, but got Unknown
			notProcessedNames.Clear();
			IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc);
			if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")))
			{
				object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")];
				Action<ZRpc, ZPackage> action = (Action<ZRpc, ZPackage>)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj);
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)delegate(ZRpc rpc, ZPackage pkg)
				{
					CheckVersion(rpc, pkg, action);
				});
			}
			else
			{
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)CheckVersion);
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.Initialize();
				if (versionCheck.ModRequired || __instance.IsServer())
				{
					Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + "."));
					ZPackage val = new ZPackage();
					val.Write(versionCheck.Name);
					val.Write(versionCheck.MinimumRequiredVersion);
					val.Write(versionCheck.CurrentVersion);
					peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val });
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ZNet), "Disconnect")]
		private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance)
		{
			if (!__instance.IsServer())
			{
				return;
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.ValidatedClients.Remove(peer.m_rpc);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
		private static void ShowConnectionError(FejdStartup __instance)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Invalid comparison between Unknown and I4
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3)
			{
				return;
			}
			bool flag = false;
			VersionCheck[] failedClient = GetFailedClient();
			if (failedClient.Length != 0)
			{
				string text = string.Join("\n", failedClient.Select((VersionCheck check) => check.Error()));
				TMP_Text connectionFailedError = __instance.m_connectionFailedError;
				connectionFailedError.text = connectionFailedError.text + "\n" + text;
				flag = true;
			}
			foreach (KeyValuePair<string, string> item in notProcessedNames.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> kv) => kv.Key))
			{
				if (!__instance.m_connectionFailedError.text.Contains(item.Key))
				{
					TMP_Text connectionFailedError2 = __instance.m_connectionFailedError;
					connectionFailedError2.text = connectionFailedError2.text + "\nServer expects you to have " + item.Key + " (Version: " + item.Value + ") installed.";
					flag = true;
				}
			}
			if (flag)
			{
				RectTransform component = ((Component)__instance.m_connectionFailedPanel.transform.Find("Image")).GetComponent<RectTransform>();
				Vector2 sizeDelta = component.sizeDelta;
				sizeDelta.x = 675f;
				component.sizeDelta = sizeDelta;
				__instance.m_connectionFailedError.ForceMeshUpdate(false, false);
				float num = __instance.m_connectionFailedError.renderedHeight + 105f;
				RectTransform component2 = ((Component)((Component)component).transform.Find("ButtonOk")).GetComponent<RectTransform>();
				component2.anchoredPosition = new Vector2(component2.anchoredPosition.x, component2.anchoredPosition.y - (num - component.sizeDelta.y) / 2f);
				sizeDelta = component.sizeDelta;
				sizeDelta.y = num;
				component.sizeDelta = sizeDelta;
			}
		}
	}
}
namespace System.IO.Compression
{
	internal static class Crc32Helper
	{
		private static readonly uint[] crcTable = new uint[256]
		{
			0u, 1996959894u, 3993919788u, 2567524794u, 124634137u, 1886057615u, 3915621685u, 2657392035u, 249268274u, 2044508324u,
			3772115230u, 2547177864u, 162941995u, 2125561021u, 3887607047u, 2428444049u, 498536548u, 1789927666u, 4089016648u, 2227061214u,
			450548861u, 1843258603u, 4107580753u, 2211677639u, 325883990u, 1684777152u, 4251122042u, 2321926636u, 335633487u, 1661365465u,
			4195302755u, 2366115317u, 997073096u, 1281953886u, 3579855332u, 2724688242u, 1006888145u, 1258607687u, 3524101629u, 2768942443u,
			901097722u, 1119000684u, 3686517206u, 2898065728u, 853044451u, 1172266101u, 3705015759u, 2882616665u, 651767980u, 1373503546u,
			3369554304u, 3218104598u, 565507253u, 1454621731u, 3485111705u, 3099436303u, 671266974u, 1594198024u, 3322730930u, 2970347812u,
			795835527u, 1483230225u, 3244367275u, 3060149565u, 1994146192u, 31158534u, 2563907772u, 4023717930u, 1907459465u, 112637215u,
			2680153253u, 3904427059u, 2013776290u, 251722036u, 2517215374u, 3775830040u, 2137656763u, 141376813u, 2439277719u, 3865271297u,
			1802195444u, 476864866u, 2238001368u, 4066508878u, 1812370925u, 453092731u, 2181625025u, 4111451223u, 1706088902u, 314042704u,
			2344532202u, 4240017532u, 1658658271u, 366619977u, 2362670323u, 4224994405u, 1303535960u, 984961486u, 2747007092u, 3569037538u,
			1256170817u, 1037604311u, 2765210733u, 3554079995u, 1131014506u, 879679996u, 2909243462u, 3663771856u, 1141124467u, 855842277u,
			2852801631u, 3708648649u, 1342533948u, 654459306u, 3188396048u, 3373015174u, 1466479909u, 544179635u, 3110523913u, 3462522015u,
			1591671054u, 702138776u, 2966460450u, 3352799412u, 1504918807u, 783551873u, 3082640443u, 3233442989u, 3988292384u, 2596254646u,
			62317068u, 1957810842u, 3939845945u, 2647816111u, 81470997u, 1943803523u, 3814918930u, 2489596804u, 225274430u, 2053790376u,
			3826175755u, 2466906013u, 167816743u, 2097651377u, 4027552580u, 2265490386u, 503444072u, 1762050814u, 4150417245u, 2154129355u,
			426522225u, 1852507879u, 4275313526u, 2312317920u, 282753626u, 1742555852u, 4189708143u, 2394877945u, 397917763u, 1622183637u,
			3604390888u, 2714866558u, 953729732u, 1340076626u, 3518719985u, 2797360999u, 1068828381u, 1219638859u, 3624741850u, 2936675148u,
			906185462u, 1090812512u, 3747672003u, 2825379669u, 829329135u, 1181335161u, 3412177804u, 3160834842u, 628085408u, 1382605366u,
			3423369109u, 3138078467u, 570562233u, 1426400815u, 3317316542u, 2998733608u, 733239954u, 1555261956u, 3268935591u, 3050360625u,
			752459403u, 1541320221u, 2607071920u, 3965973030u, 1969922972u, 40735498u, 2617837225u, 3943577151u, 1913087877u, 83908371u,
			2512341634u, 3803740692u, 2075208622u, 213261112u, 2463272603u, 3855990285u, 2094854071u, 198958881u, 2262029012u, 4057260610u,
			1759359992u, 534414190u, 2176718541u, 4139329115u, 1873836001u, 414664567u, 2282248934u, 4279200368u, 1711684554u, 285281116u,
			2405801727u, 4167216745u, 1634467795u, 376229701u, 2685067896u, 3608007406u, 1308918612u, 956543938u, 2808555105u, 3495958263u,
			1231636301u, 1047427035u, 2932959818u, 3654703836u, 1088359270u, 936918000u, 2847714899u, 3736837829u, 1202900863u, 817233897u,
			3183342108u, 3401237130u, 1404277552u, 615818150u, 3134207493u, 3453421203u, 1423857449u, 601450431u, 3009837614u, 3294710456u,
			1567103746u, 711928724u, 3020668471u, 3272380065u, 1510334235u, 755167117u
		};

		public static uint UpdateCrc32(uint crc32, byte[] buffer, int offset, int length)
		{
			crc32 ^= 0xFFFFFFFFu;
			while (--length >= 0)
			{
				crc32 = crcTable[(crc32 ^ buffer[offset++]) & 0xFF] ^ (crc32 >> 8);
			}
			crc32 ^= 0xFFFFFFFFu;
			return crc32;
		}
	}
	internal class WrappedStream : Stream
	{
		private readonly Stream _baseStream;

		private readonly EventHandler _onClosed;

		private bool _canRead;

		private bool _canWrite;

		private bool _canSeek;

		private bool _isDisposed;

		private readonly bool _closeBaseStream;

		public override long Length
		{
			get
			{
				ThrowIfDisposed();
				return _baseStream.Length;
			}
		}

		public override long Position
		{
			get
			{
				ThrowIfDisposed();
				return _baseStream.Position;
			}
			set
			{
				ThrowIfDisposed();
				ThrowIfCantSeek();
				_baseStream.Position = value;
			}
		}

		public override bool CanRead
		{
			get
			{
				if (_canRead)
				{
					return _baseStream.CanRead;
				}
				return false;
			}
		}

		public override bool CanSeek
		{
			get
			{
				if (_canSeek)
				{
					return _baseStream.CanSeek;
				}
				return false;
			}
		}

		public override bool CanWrite
		{
			get
			{
				if (_canWrite)
				{
					return _baseStream.CanWrite;
				}
				return false;
			}
		}

		internal WrappedStream(Stream baseStream, bool canRead, bool canWrite, bool canSeek, EventHandler onClosed)
			: this(baseStream, canRead, canWrite, canSeek, closeBaseStream: false, onClosed)
		{
		}

		internal WrappedStream(Stream baseStream, bool canRead, bool canWrite, bool canSeek, bool closeBaseStream, EventHandler onClosed)
		{
			_baseStream = baseStream;
			_onClosed = onClosed;
			_canRead = canRead;
			_canSeek = canSeek;
			_canWrite = canWrite;
			_isDisposed = false;
			_closeBaseStream = closeBaseStream;
		}

		internal WrappedStream(Stream baseStream, EventHandler onClosed)
			: this(baseStream, canRead: true, canWrite: true, canSeek: true, onClosed)
		{
		}

		private void ThrowIfDisposed()
		{
			if (_isDisposed)
			{
				throw new ObjectDisposedException(GetType().Name, Messages.HiddenStreamName);
			}
		}

		private void ThrowIfCantRead()
		{
			if (!CanWrite)
			{
				throw new NotSupportedException(Messages.WritingNotSupported);
			}
		}

		private void ThrowIfCantWrite()
		{
			if (!CanWrite)
			{
				throw new NotSupportedException(Messages.WritingNotSupported);
			}
		}

		private void ThrowIfCantSeek()
		{
			if (!CanSeek)
			{
				throw new NotSupportedException(Messages.SeekingNotSupported);
			}
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			ThrowIfDisposed();
			ThrowIfCantRead();
			return _baseStream.Read(buffer, offset, count);
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			ThrowIfDisposed();
			ThrowIfCantSeek();
			return _baseStream.Seek(offset, origin);
		}

		public override void SetLength(long value)
		{
			ThrowIfDisposed();
			ThrowIfCantSeek();
			ThrowIfCantWrite();
			_baseStream.SetLength(value);
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
			ThrowIfDisposed();
			ThrowIfCantWrite();
			_baseStream.Write(buffer, offset, count);
		}

		public override void Flush()
		{
			ThrowIfDisposed();
			ThrowIfCantWrite();
			_baseStream.Flush();
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing && !_isDisposed)
			{
				if (_onClosed != null)
				{
					_onClosed(this, null);
				}
				if (_closeBaseStream)
				{
					_baseStream.Dispose();
				}
				_canRead = false;
				_canWrite = false;
				_canSeek = false;
				_isDisposed = true;
			}
			base.Dispose(disposing);
		}
	}
	internal class SubReadStream : Stream
	{
		private readonly long _startInSuperStream;

		private long _positionInSuperStream;

		private readonly long _endInSuperStream;

		private readonly Stream _superStream;

		private bool _canRead;

		private bool _isDisposed;

		public override long Length
		{
			get
			{
				ThrowIfDisposed();
				return _endInSuperStream - _startInSuperStream;
			}
		}

		public override long Position
		{
			get
			{
				ThrowIfDisposed();
				return _positionInSuperStream - _startInSuperStream;
			}
			set
			{
				ThrowIfDisposed();
				throw new NotSupportedException(Messages.SeekingNotSupported);
			}
		}

		public override bool CanRead
		{
			get
			{
				if (_superStream.CanRead)
				{
					return _canRead;
				}
				return false;
			}
		}

		public override bool CanSeek => false;

		public override bool CanWrite => false;

		public SubReadStream(Stream superStream, long startPosition, long maxLength)
		{
			_startInSuperStream = startPosition;
			_positionInSuperStream = startPosition;
			_endInSuperStream = startPosition + maxLength;
			_superStream = superStream;
			_canRead = true;
			_isDisposed = false;
		}

		private void ThrowIfDisposed()
		{
			if (_isDisposed)
			{
				throw new ObjectDisposedException(GetType().Name, Messages.HiddenStreamName);
			}
		}

		private void ThrowIfCantRead()
		{
			if (!CanRead)
			{
				throw new NotSupportedException(Messages.ReadingNotSupported);
			}
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			int num = count;
			ThrowIfDisposed();
			ThrowIfCantRead();
			if (_superStream.Position != _positionInSuperStream)
			{
				_superStream.Seek(_positionInSuperStream, SeekOrigin.Begin);
			}
			if (_positionInSuperStream + count > _endInSuperStream)
			{
				count = (int)(_endInSuperStream - _positionInSuperStream);
			}
			int num2 = _superStream.Read(buffer, offset, count);
			_positionInSuperStream += num2;
			return num2;
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			ThrowIfDisposed();
			throw new NotSupportedException(Messages.SeekingNotSupported);
		}

		public override void SetLength(long value)
		{
			ThrowIfDisposed();
			throw new NotSupportedException(Messages.SetLengthRequiresSeekingAndWriting);
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
			ThrowIfDisposed();
			throw new NotSupportedException(Messages.WritingNotSupported);
		}

		public override void Flush()
		{
			ThrowIfDisposed();
			throw new NotSupportedException(Messages.WritingNotSupported);
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing && !_isDisposed)
			{
				_canRead = false;
				_isDisposed = true;
			}
			base.Dispose(disposing);
		}
	}
	internal class CheckSumAndSizeWriteStream : Stream
	{
		private readonly Stream _baseStream;

		private readonly Stream _baseBaseStream;

		private long _position;

		private uint _checksum;

		private readonly bool _leaveOpenOnClose;

		private bool _canWrite;

		private bool _isDisposed;

		private bool _everWritten;

		private long _initialPosition;

		private readonly Action<long, long, uint> _saveCrcAndSizes;

		public override long Length
		{
			get
			{
				ThrowIfDisposed();
				throw new NotSupportedException(Messages.SeekingNotSupported);
			}
		}

		public override long Position
		{
			get
			{
				ThrowIfDisposed();
				return _position;
			}
			set
			{
				ThrowIfDisposed();
				throw new NotSupportedException(Messages.SeekingNotSupported);
			}
		}

		public override bool CanRead => false;

		public override bool CanSeek => false;

		public override bool CanWrite => _canWrite;

		public CheckSumAndSizeWriteStream(Stream baseStream, Stream baseBaseStream, bool leaveOpenOnClose, Action<long, long, uint> saveCrcAndSizes)
		{
			_baseStream = baseStream;
			_baseBaseStream = baseBaseStream;
			_position = 0L;
			_checksum = 0u;
			_leaveOpenOnClose = leaveOpenOnClose;
			_canWrite = true;
			_isDisposed = false;
			_initialPosition = 0L;
			_saveCrcAndSizes = saveCrcAndSizes;
		}

		private void ThrowIfDisposed()
		{
			if (_isDisposed)
			{
				throw new ObjectDisposedException(GetType().Name, Messages.HiddenStreamName);
			}
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			ThrowIfDisposed();
			throw new NotSupportedException(Messages.ReadingNotSupported);
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			ThrowIfDisposed();
			throw new NotSupportedException(Messages.SeekingNotSupported);
		}

		public override void SetLength(long value)
		{
			ThrowIfDisposed();
			throw new NotSupportedException(Messages.SetLengthRequiresSeekingAndWriting);
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
			if (buffer == null)
			{
				throw new ArgumentNullException("buffer");
			}
			if (offset < 0)
			{
				throw new ArgumentOutOfRangeException("offset", Messages.ArgumentNeedNonNegative);
			}
			if (count < 0)
			{
				throw new ArgumentOutOfRangeException("count", Messages.ArgumentNeedNonNegative);
			}
			if (buffer.Length - offset < count)
			{
				throw new ArgumentException(Messages.OffsetLengthInvalid);
			}
			ThrowIfDisposed();
			if (count != 0)
			{
				if (!_everWritten)
				{
					_initialPosition = _baseBaseStream.Position;
					_everWritten = true;
				}
				_checksum = System.IO.Compression.Crc32Helper.UpdateCrc32(_checksum, buffer, offset, count);
				_baseStream.Write(buffer, offset, count);
				_position += count;
			}
		}

		public override void Flush()
		{
			ThrowIfDisposed();
			_baseStream.Flush();
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing && !_isDisposed)
			{
				if (!_everWritten)
				{
					_initialPosition = _baseBaseStream.Position;
				}
				if (!_leaveOpenOnClose)
				{
					_baseStream.Close();
				}
				if (_saveCrcAndSizes != null)
				{
					_saveCrcAndSizes(_initialPosition, Position, _checksum);
				}
				_isDisposed = true;
			}
			base.Dispose(disposing);
		}
	}
	[__DynamicallyInvokable]
	internal class ZipArchive : IDisposable
	{
		private Stream _archiveStream;

		private ZipArchiveEntry _archiveStreamOwner;

		private BinaryReader _archiveReader;

		private ZipArchiveMode _mode;

		private List<ZipArchiveEntry> _entries;

		private ReadOnlyCollection<ZipArchiveEntry> _entriesCollection;

		private Dictionary<string, ZipArchiveEntry> _entriesDictionary;

		private bool _readEntries;

		private bool _leaveOpen;

		private long _centralDirectoryStart;

		private bool _isDisposed;

		private uint _numberOfThisDisk;

		private long _expectedNumberOfEntries;

		private Stream _backingStream;

		private byte[] _archiveComment;

		private Encoding _entryNameEncoding;

		[__DynamicallyInvokable]
		public ReadOnlyCollection<ZipArchiveEntry> Entries
		{
			[__DynamicallyInvokable]
			get
			{
				if (_mode == ZipArchiveMode.Create)
				{
					throw new NotSupportedException(Messages.EntriesInCreateMode);
				}
				ThrowIfDisposed();
				EnsureCentralDirectoryRead();
				return _entriesCollection;
			}
		}

		[__DynamicallyInvokable]
		public ZipArchiveMode Mode
		{
			[__DynamicallyInvokable]
			get
			{
				return _mode;
			}
		}

		internal BinaryReader ArchiveReader => _archiveReader;

		internal Stream ArchiveStream => _archiveStream;

		internal uint NumberOfThisDisk => _numberOfThisDisk;

		internal Encoding EntryNameEncoding
		{
			get
			{
				return _entryNameEncoding;
			}
			private set
			{
				if (value != null && (value.Equals(Encoding.BigEndianUnicode) || value.Equals(Encoding.Unicode) || value.Equals(Encoding.UTF32) || value.Equals(Encoding.UTF7)))
				{
					throw new ArgumentException(Messages.EntryNameEncodingNotSupported, "entryNameEncoding");
				}
				_entryNameEncoding = value;
			}
		}

		[__DynamicallyInvokable]
		public ZipArchive(Stream stream)
			: this(stream, ZipArchiveMode.Read, leaveOpen: false, null)
		{
		}

		[__DynamicallyInvokable]
		public ZipArchive(Stream stream, ZipArchiveMode mode)
			: this(stream, mode, leaveOpen: false, null)
		{
		}

		[__DynamicallyInvokable]
		public ZipArchive(Stream stream, ZipArchiveMode mode, bool leaveOpen)
			: this(stream, mode, leaveOpen, null)
		{
		}

		[__DynamicallyInvokable]
		public ZipArchive(Stream stream, ZipArchiveMode mode, bool leaveOpen, Encoding entryNameEncoding)
		{
			if (stream == null)
			{
				throw new ArgumentNullException("stream");
			}
			EntryNameEncoding = entryNameEncoding;
			Init(stream, mode, leaveOpen);
		}

		[__DynamicallyInvokable]
		public ZipArchiveEntry CreateEntry(string entryName)
		{
			return DoCreateEntry(entryName, null);
		}

		[__DynamicallyInvokable]
		public ZipArchiveEntry CreateEntry(string entryName, CompressionLevel compressionLevel)
		{
			return DoCreateEntry(entryName, compressionLevel);
		}

		[__DynamicallyInvokable]
		protected virtual void Dispose(bool disposing)
		{
			if (!disposing || _isDisposed)
			{
				return;
			}
			ZipArchiveMode mode = _mode;
			if (mode != ZipArchiveMode.Read)
			{
				_ = mode - 1;
				_ = 1;
				try
				{
					WriteFile();
				}
				catch (InvalidDataException)
				{
					CloseStreams();
					_isDisposed = true;
					throw;
				}
			}
			CloseStreams();
			_isDisposed = true;
		}

		[__DynamicallyInvokable]
		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		[__DynamicallyInvokable]
		public ZipArchiveEntry GetEntry(string entryName)
		{
			if (entryName == null)
			{
				throw new ArgumentNullException("entryName");
			}
			if (_mode == ZipArchiveMode.Create)
			{
				throw new NotSupportedException(Messages.EntriesInCreateMode);
			}
			EnsureCentralDirectoryRead();
			_entriesDictionary.TryGetValue(entryName, out var value);
			return value;
		}

		private ZipArchiveEntry DoCreateEntry(string entryName, CompressionLevel? compressionLevel)
		{
			if (entryName == null)
			{
				throw new ArgumentNullException("entryName");
			}
			if (string.IsNullOrEmpty(entryName))
			{
				throw new ArgumentException(Messages.CannotBeEmpty, "entryName");
			}
			if (_mode == ZipArchiveMode.Read)
			{
				throw new NotSupportedException(Messages.CreateInReadMode);
			}
			ThrowIfDisposed();
			ZipArchiveEntry zipArchiveEntry = (compressionLevel.HasValue ? new ZipArchiveEntry(this, entryName, compressionLevel.Value) : new ZipArchiveEntry(this, entryName));
			AddEntry(zipArchiveEntry);
			return zipArchiveEntry;
		}

		internal void AcquireArchiveStream(ZipArchiveEntry entry)
		{
			if (_archiveStreamOwner != null)
			{
				if (_archiveStreamOwner.EverOpenedForWrite)
				{
					throw new IOException(Messages.CreateModeCreateEntryWhileOpen);
				}
				_archiveStreamOwner.WriteAndFinishLocalEntry();
			}
			_archiveStreamOwner = entry;
		}

		private void AddEntry(ZipArchiveEntry entry)
		{
			_entries.Add(entry);
			string fullName = entry.FullName;
			if (!_entriesDictionary.ContainsKey(fullName))
			{
				_entriesDictionary.Add(fullName, entry);
			}
		}

		internal bool IsStillArchiveStreamOwner(ZipArchiveEntry entry)
		{
			return _archiveStreamOwner == entry;
		}

		internal void ReleaseArchiveStream(ZipArchiveEntry entry)
		{
			_archiveStreamOwner = null;
		}

		internal void RemoveEntry(ZipArchiveEntry entry)
		{
			_entries.Remove(entry);
			_entriesDictionary.Remove(entry.FullName);
		}

		internal void ThrowIfDisposed()
		{
			if (_isDisposed)
			{
				throw new ObjectDisposedException(GetType().Name);
			}
		}

		private void CloseStreams()
		{
			if (!_leaveOpen)
			{
				_archiveStream.Close();
				if (_backingStream != null)
				{
					_backingStream.Close();
				}
				if (_archiveReader != null)
				{
					_archiveReader.Close();
				}
			}
			else if (_backingStream != null)
			{
				_archiveStream.Close();
			}
		}

		private void EnsureCentralDirectoryRead()
		{
			if (!_readEntries)
			{
				ReadCentralDirectory();
				_readEntries = true;
			}
		}

		private void Init(Stream stream, ZipArchiveMode mode, bool leaveOpen)
		{
			Stream stream2 = null;
			try
			{
				_backingStream = null;
				switch (mode)
				{
				case ZipArchiveMode.Create:
					if (!stream.CanWrite)
					{
						throw new ArgumentException(Messages.CreateModeCapabilities);
					}
					break;
				case ZipArchiveMode.Read:
					if (!stream.CanRead)
					{
						throw new ArgumentException(Messages.ReadModeCapabilities);
					}
					if (!stream.CanSeek)
					{
						_backingStream = stream;
						stream2 = (stream = new MemoryStream());
						_backingStream.CopyTo(stream);
						stream.Seek(0L, SeekOrigin.Begin);
					}
					break;
				case ZipArchiveMode.Update:
					if (!stream.CanRead || !stream.CanWrite || !stream.CanSeek)
					{
						throw new ArgumentException(Messages.UpdateModeCapabilities);
					}
					break;
				default:
					throw new ArgumentOutOfRangeException("mode");
				}
				_mode = mode;
				_archiveStream = stream;
				_archiveStreamOwner = null;
				if (mode == ZipArchiveMode.Create)
				{
					_archiveReader = null;
				}
				else
				{
					_archiveReader = new BinaryReader(stream);
				}
				_entries = new List<ZipArchiveEntry>();
				_entriesCollection = new ReadOnlyCollection<ZipArchiveEntry>(_entries);
				_entriesDictionary = new Dictionary<string, ZipArchiveEntry>();
				_readEntries = false;
				_leaveOpen = leaveOpen;
				_centralDirectoryStart = 0L;
				_isDisposed = false;
				_numberOfThisDisk = 0u;
				_archiveComment = null;
				switch (mode)
				{
				case ZipArchiveMode.Create:
					_readEntries = true;
					return;
				case ZipArchiveMode.Read:
					ReadEndOfCentralDirectory();
					return;
				}
				if (_archiveStream.Length == 0L)
				{
					_readEntries = true;
					return;
				}
				ReadEndOfCentralDirectory();
				EnsureCentralDirectoryRead();
				foreach (ZipArchiveEntry entry in _entries)
				{
					entry.ThrowIfNotOpenable(needToUncompress: false, needToLoadIntoMemory: true);
				}
			}
			catch
			{
				stream2?.Close();
				throw;
			}
		}

		private void ReadCentralDirectory()
		{
			try
			{
				_archiveStream.Seek(_centralDirectoryStart, SeekOrigin.Begin);
				long num = 0L;
				bool saveExtraFieldsAndComments = Mode == ZipArchiveMode.Update;
				System.IO.Compression.ZipCentralDirectoryFileHeader header;
				while (System.IO.Compression.ZipCentralDirectoryFileHeader.TryReadBlock(_archiveReader, saveExtraFieldsAndComments, out header))
				{
					AddEntry(new ZipArchiveEntry(this, header));
					num++;
				}
				if (num != _expectedNumberOfEntries)
				{
					throw new InvalidDataException(Messages.NumEntriesWrong);
				}
			}
			catch (EndOfStreamException innerException)
			{
				throw new InvalidDataException(Messages.CentralDirectoryInvalid, innerException);
			}
		}

		private void ReadEndOfCentralDirectory()
		{
			try
			{
				_archiveStream.Seek(-18L, SeekOrigin.End);
				if (!System.IO.Compression.ZipHelper.SeekBackwardsToSignature(_archiveStream, 101010256u))
				{
					throw new InvalidDataException(Messages.EOCDNotFound);
				}
				long position = _archiveStream.Position;
				System.IO.Compression.ZipEndOfCentralDirectoryBlock eocdBlock;
				bool flag = System.IO.Compression.ZipEndOfCentralDirectoryBlock.TryReadBlock(_archiveReader, out eocdBlock);
				if (eocdBlock.NumberOfThisDisk != eocdBlock.NumberOfTheDiskWithTheStartOfTheCentralDirectory)
				{
					throw new InvalidDataException(Messages.SplitSpanned);
				}
				_numberOfThisDisk = eocdBlock.NumberOfThisDisk;
				_centralDirectoryStart = eocdBlock.OffsetOfStartOfCentralDirectoryWithRespectToTheStartingDiskNumber;
				if (eocdBlock.NumberOfEntriesInTheCentralDirectory != eocdBlock.NumberOfEntriesInTheCentralDirectoryOnThisDisk)
				{
					throw new InvalidDataException(Messages.SplitSpanned);
				}
				_expectedNumberOfEntries = eocdBlock.NumberOfEntriesInTheCentralDirectory;
				if (_mode == ZipArchiveMode.Update)
				{
					_archiveComment = eocdBlock.ArchiveComment;
				}
				if (eocdBlock.NumberOfThisDisk == ushort.MaxValue || eocdBlock.OffsetOfStartOfCentralDirectoryWithRespectToTheStartingDiskNumber == uint.MaxValue || eocdBlock.NumberOfEntriesInTheCentralDirectory == ushort.MaxValue)
				{
					_archiveStream.Seek(position - 16, SeekOrigin.Begin);
					if (System.IO.Compression.ZipHelper.SeekBackwardsToSignature(_archiveStream, 117853008u))
					{
						System.IO.Compression.Zip64EndOfCentralDirectoryLocator zip64EOCDLocator;
						bool flag2 = System.IO.Compression.Zip64EndOfCentralDirectoryLocator.TryReadBlock(_archiveReader, out zip64EOCDLocator);
						if (zip64EOCDLocator.OffsetOfZip64EOCD > long.MaxValue)
						{
							throw new InvalidDataException(Messages.FieldTooBigOffsetToZip64EOCD);
						}
						long offsetOfZip64EOCD = (long)zip64EOCDLocator.OffsetOfZip64EOCD;
						_archiveStream.Seek(offsetOfZip64EOCD, SeekOrigin.Begin);
						if (!System.IO.Compression.Zip64EndOfCentralDirectoryRecord.TryReadBlock(_archiveReader, out var zip64EOCDRecord))
						{
							throw new InvalidDataException(Messages.Zip64EOCDNotWhereExpected);
						}
						_numberOfThisDisk = zip64EOCDRecord.NumberOfThisDisk;
						if (zip64EOCDRecord.NumberOfEntriesTotal > long.MaxValue)
						{
							throw new InvalidDataException(Messages.FieldTooBigNumEntries);
						}
						if (zip64EOCDRecord.OffsetOfCentralDirectory > long.MaxValue)
						{
							throw new InvalidDataException(Messages.FieldTooBigOffsetToCD);
						}
						if (zip64EOCDRecord.NumberOfEntriesTotal != zip64EOCDRecord.NumberOfEntriesOnThisDisk)
						{
							throw new InvalidDataException(Messages.SplitSpanned);
						}
						_expectedNumberOfEntries = (long)zip64EOCDRecord.NumberOfEntriesTotal;
						_centralDirectoryStart = (long)zip64EOCDRecord.OffsetOfCentralDirectory;
					}
				}
				if (_centralDirectoryStart > _archiveStream.Length)
				{
					throw new InvalidDataException(Messages.FieldTooBigOffsetToCD);
				}
			}
			catch (EndOfStreamException innerException)
			{
				throw new InvalidDataException(Messages.CDCorrupt, innerException);
			}
			catch (IOException innerException2)
			{
				throw new InvalidDataException(Messages.CDCorrupt, innerException2);
			}
		}

		private void WriteFile()
		{
			if (_mode == ZipArchiveMode.Update)
			{
				List<ZipArchiveEntry> list = new List<ZipArchiveEntry>();
				foreach (ZipArchiveEntry entry in _entries)
				{
					if (!entry.LoadLocalHeaderExtraFieldAndCompressedBytesIfNeeded())
					{
						list.Add(entry);
					}
				}
				foreach (ZipArchiveEntry item in list)
				{
					item.Delete();
				}
				_archiveStream.Seek(0L, SeekOrigin.Begin);
				_archiveStream.SetLength(0L);
			}
			foreach (ZipArchiveEntry entry2 in _entries)
			{
				entry2.WriteAndFinishLocalEntry();
			}
			long position = _archiveStream.Position;
			foreach (ZipArchiveEntry entry3 in _entries)
			{
				entry3.WriteCentralDirectoryFileHeader();
			}
			long sizeOfCentralDirectory = _archiveStream.Position - position;
			WriteArchiveEpilogue(position, sizeOfCentralDirectory);
		}

		private void WriteArchiveEpilogue(long startOfCentralDirectory, long sizeOfCentralDirectory)
		{
			bool flag = false;
			if (startOfCentralDirectory >= uint.MaxValue || sizeOfCentralDirectory >= uint.MaxValue || _entries.Count >= 65535)
			{
				flag = true;
			}
			if (flag)
			{
				long position = _archiveStream.Position;
				System.IO.Compression.Zip64EndOfCentralDirectoryRecord.WriteBlock(_archiveStream, _entries.Count, startOfCentralDirectory, sizeOfCentralDirectory);
				System.IO.Compression.Zip64EndOfCentralDirectoryLocator.WriteBlock(_archiveStream, position);
			}
			System.IO.Compression.ZipEndOfCentralDirectoryBlock.WriteBlock(_archiveStream, _entries.Count, startOfCentralDirectory, sizeOfCentralDirectory, _archiveComment);
		}
	}
	[__DynamicallyInvokable]
	internal class ZipArchiveEntry
	{
		private class DirectToArchiveWriterStream : Stream
		{
			private long _position;

			private System.IO.Compression.CheckSumAndSizeWriteStream _crcSizeStream;

			private bool _everWritten;

			private bool _isDisposed;

			private ZipArchiveEntry _entry;

			private bool _usedZip64inLH;

			private bool _canWrite;

			public override long Length
			{
				get
				{
					ThrowIfDisposed();
					throw new NotSupportedException(Messages.SeekingNotSupported);
				}
			}

			public override long Position
			{
				get
				{
					ThrowIfDisposed();
					return _position;
				}
				set
				{
					ThrowIfDisposed();
					throw new NotSupportedException(Messages.SeekingNotSupported);
				}
			}

			public override bool CanRead => false;

			public override bool CanSeek => false;

			public override bool CanWrite => _canWrite;

			public DirectToArchiveWriterStream(System.IO.Compression.CheckSumAndSizeWriteStream crcSizeStream, ZipArchiveEntry entry)
			{
				_position = 0L;
				_crcSizeStream = crcSizeStream;
				_everWritten = false;
				_isDisposed = false;
				_entry = entry;
				_usedZip64inLH = false;
				_canWrite = true;
			}

			private void ThrowIfDisposed()
			{
				if (_isDisposed)
				{
					throw new ObjectDisposedException(GetType().Name, Messages.HiddenStreamName);
				}
			}

			public override int Read(byte[] buffer, int offset, int count)
			{
				ThrowIfDisposed();
				throw new NotSupportedException(Messages.ReadingNotSupported);
			}

			public override long Seek(long offset, SeekOrigin origin)
			{
				ThrowIfDisposed();
				throw new NotSupportedException(Messages.SeekingNotSupported);
			}

			public override void SetLength(long value)
			{
				ThrowIfDisposed();
				throw new NotSupportedException(Messages.SetLengthRequiresSeekingAndWriting);
			}

			public override void Write(byte[] buffer, int offset, int count)
			{
				if (buffer == null)
				{
					throw new ArgumentNullException("buffer");
				}
				if (offset < 0)
				{
					throw new ArgumentOutOfRangeException("offset", Messages.ArgumentNeedNonNegative);
				}
				if (count < 0)
				{
					throw new ArgumentOutOfRangeException("count", Messages.ArgumentNeedNonNegative);
				}
				if (buffer.Length - offset < count)
				{
					throw new ArgumentException(Messages.OffsetLengthInvalid);
				}
				ThrowIfDisposed();
				if (count != 0)
				{
					if (!_everWritten)
					{
						_everWritten = true;
						_usedZip64inLH = _entry.WriteLocalFileHeader(isEmptyFile: false);
					}
					_crcSizeStream.Write(buffer, offset, count);
					_position += count;
				}
			}

			public override void Flush()
			{
				ThrowIfDisposed();
				_crcSizeStream.Flush();
			}

			protected override void Dispose(bool disposing)
			{
				if (disposing && !_isDisposed)
				{
					_crcSizeStream.Close();
					if (!_everWritten)
					{
						_entry.WriteLocalFileHeader(isEmptyFile: true);
					}
					else if (_entry._archive.ArchiveStream.CanSeek)
					{
						_entry.WriteCrcAndSizesInLocalHeader(_usedZip64inLH);
					}
					else
					{
						_entry.WriteDataDescriptor();
					}
					_canWrite = false;
					_isDisposed = true;
				}
				base.Dispose(disposing);
			}
		}

		[Flags]
		private enum BitFlagValues : ushort
		{
			DataDescriptor = 8,
			UnicodeFileName = 0x800
		}

		private enum CompressionMethodValues : ushort
		{
			Stored = 0,
			Deflate = 8
		}

		private enum OpenableValues
		{
			Openable,
			FileNonExistent,
			FileTooLarge
		}

		private const ushort DefaultVersionToExtract = 10;

		private ZipArchive _archive;

		private readonly bool _originallyInArchive;

		private readonly int _diskNumberStart;

		private System.IO.Compression.ZipVersionNeededValues _versionToExtract;

		private BitFlagValues _generalPurposeBitFlag;

		private CompressionMethodValues _storedCompressionMethod;

		private DateTimeOffset _lastModified;

		private long _compressedSize;

		private long _uncompressedSize;

		private long _offsetOfLocalHeader;

		private long? _storedOffsetOfCompressedData;

		private uint _crc32;

		private byte[] _compressedBytes;

		private MemoryStream _storedUncompressedData;

		private bool _currentlyOpenForWrite;

		private bool _everOpenedForWrite;

		private Stream _outstandingWriteStream;

		private uint _externalFileAttr;

		private string _storedEntryName;

		private byte[] _storedEntryNameBytes;

		private List<System.IO.Compression.ZipGenericExtraField> _cdUnknownExtraFields;

		private List<System.IO.Compression.ZipGenericExtraField> _lhUnknownExtraFields;

		private byte[] _fileComment;

		private CompressionLevel? _compressionLevel;

		[__DynamicallyInvokable]
		public ZipArchive Archive
		{
			[__DynamicallyInvokable]
			get
			{
				return _archive;
			}
		}

		[__DynamicallyInvokable]
		public long CompressedLength
		{
			[__DynamicallyInvokable]
			get
			{
				if (_everOpenedForWrite)
				{
					throw new InvalidOperationException(Messages.LengthAfterWrite);
				}
				return _compressedSize;
			}
		}

		public int ExternalAttributes
		{
			get