Decompiled source of Aerolt v4.0.10
Aerolt.dll
Decompiled 6 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Aerolt.Buttons; using Aerolt.Classes; using Aerolt.Enums; using Aerolt.Helpers; using Aerolt.Managers; using Aerolt.Messages; using Aerolt.Overrides; using Aerolt.Social; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HG; using HarmonyLib; using JetBrains.Annotations; using KinematicCharacterController; using Microsoft.CodeAnalysis; using RiskOfOptions; using RiskOfOptions.Components.Panel; using RiskOfOptions.Options; using RoR2; using RoR2.CharacterAI; using RoR2.ContentManagement; using RoR2.Networking; using RoR2.UI; using TMPro; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.Networking; using UnityEngine.Serialization; using UnityEngine.UI; using UnityEngine.UIElements; using WebSocketSharp; using Zio; using ZioConfigFile; using ZioRiskOfOptions; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Aerolt")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("Aerolt")] [assembly: AssemblyTitle("Aerolt")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace Aerolt { [BepInPlugin("com.Lodington.Aerolt", "Aerolt", "4.0.10")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Load : BaseUnityPlugin { public const string Name = "Aerolt"; public const string Guid = "com.Lodington.Aerolt"; public const string Version = "4.0.10"; public static ManualLogSource Log; public static GameObject Co; public static AssetBundle Assets; public static Load Instance; public static Dictionary<ButtonNames, ZioConfigEntry<KeyboardShortcut>> KeyBinds = new Dictionary<ButtonNames, ZioConfigEntry<KeyboardShortcut>>(); public static Dictionary<NetworkUser, GameObject> AeroltUIs = new Dictionary<NetworkUser, GameObject>(); private static GameObject _settingsUI; public static ZioConfigFile ConfigFile; public static NetworkUser TempViewer; public static HUD TempHud; public static string Path; public void Awake() { Instance = this; Log = ((BaseUnityPlugin)this).Logger; Path = System.IO.Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location); Assets = AssetBundle.LoadFromFile(System.IO.Path.Combine(Path, "aeroltbundle")); Tools.Log(LogLevel.Information, "Loaded AssetBundle"); Co = Assets.LoadAsset<GameObject>("PlayerCanvas"); Assets.LoadAsset<GameObject>("AeroltUI"); NetworkManager.Initialize(); } public void Start() { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Expected O, but got Unknown RoR2Application.onLoad = (Action)Delegate.Combine(RoR2Application.onLoad, new Action(GameLoad)); HUD.shouldHudDisplay += new ShouldHudDisplayDelegate(CreateHud); } private void OnDestroy() { WebSocketClient.DisconnectClient(); } public void OnGUI() { if (Object.op_Implicit((Object)(object)Esp.Instance)) { Esp.Draw(); } } public static bool GetKeyPressed(ZioConfigEntry<KeyboardShortcut> entry) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) KeyboardShortcut value = entry.Value; foreach (KeyCode modifier in ((KeyboardShortcut)(ref value)).Modifiers) { if (!Input.GetKey(modifier)) { return false; } } value = entry.Value; return Input.GetKeyDown(((KeyboardShortcut)(ref value)).MainKey); } private void GameLoad() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Expected O, but got Unknown //IL_004a: Unknown result type (might be due to invalid IL or missing references) ConfigFile = new ZioConfigFile(RoR2Application.cloudStorage, UPath.op_Implicit("/Aerolt/Settings.cfg"), true, (BepInPlugin)null); CreateKeyBindSettings(); Colors.InitColors(); Harmony val = new Harmony(((BaseUnityPlugin)this).Info.Metadata.GUID); new PatchClassProcessor(val, typeof(Hooks)).Patch(); } private void CreateKeyBindSettings() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) KeyBinds.Add(ButtonNames.OpenMenu, ConfigFile.Bind<KeyboardShortcut>("Keybinds", "OpenMenu", new KeyboardShortcut((KeyCode)282, Array.Empty<KeyCode>()), (ConfigDescription)null)); if (Chainloader.PluginInfos.ContainsKey("bubbet.zioriskofoptions")) { MakeRiskOfOptions(); } } private void MakeRiskOfOptions() { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected O, but got Unknown foreach (ZioConfigEntry<KeyboardShortcut> value in KeyBinds.Values) { ModSettingsManager.AddOption((BaseOption)new ZioKeyBindOption(value)); } } public static void CreateHud(HUD hud, ref bool shoulddisplay) { if (!Object.op_Implicit((Object)(object)hud.cameraRigController)) { return; } NetworkUser viewer = hud.cameraRigController.viewer; if (!AeroltUIs.ContainsKey(viewer)) { if (Object.op_Implicit((Object)(object)_settingsUI) && _settingsUI.activeSelf) { _settingsUI.SetActive(false); } TempViewer = viewer; TempHud = hud; GameObject val = Object.Instantiate<GameObject>(Co); val.GetComponent<MPEventSystemProvider>().eventSystem = hud.eventSystemProvider.eventSystem; TempViewer = null; TempHud = null; AeroltUIs.Add(viewer, val); Tools.Log(LogLevel.Information, "Created UI"); } } } } namespace Aerolt.Social { public class GetWebSocketClientData : MonoBehaviour { public TMP_InputField inputField; public TMP_Text chatWindowText; public TMP_Text userWindowText; public Button sendButton; public TMP_Text userCount; public TMP_Text WelcomeText; private bool isTextDirty; private ScrollRect scrollRect; private bool setToBottom; public void Awake() { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown WebSocketClient.Bind(MarkTextDirty); ((UnityEvent)sendButton.onClick).AddListener(new UnityAction(SendMessage)); scrollRect = ((Component)chatWindowText).gameObject.GetComponentInParent<ScrollRect>(); } public void InsertLobbyID() { TMP_InputField obj = inputField; obj.text = obj.text + "#" + PlatformSystems.lobbyManager.GetLobbyID(); } private void Update() { if (setToBottom && scrollRect.verticalScrollbar.value > 0f) { scrollRect.verticalScrollbar.value = 0f; setToBottom = false; } if (isTextDirty) { UpdateChatWindow(); isTextDirty = false; } if (Input.GetKeyDown((KeyCode)13)) { SendMessage(); } } private void OnEnable() { WebSocketClient.TryConnect(); UpdateChatWindow(); } private void OnDestroy() { WebSocketClient.UnBind(MarkTextDirty); } private void SendMessage() { if (!string.IsNullOrEmpty(inputField.text)) { WebSocketClient.Message.Send(inputField.text); inputField.text = string.Empty; } } private void MarkTextDirty(object sender, MessageEventArgs e) { isTextDirty = true; } private void UpdateChatWindow() { bool flag = scrollRect.verticalScrollbar.value < 0.05f; chatWindowText.text = WebSocketClient.MessageText; userWindowText.text = WebSocketClient.UsernameText; string text = "0"; if (!string.IsNullOrEmpty(WebSocketClient.UsernameText)) { userCount.text = "Users Online : " + text; } if (flag) { setToBottom = true; } } } public class WebSocketClient { public static string UsernameText; public static string MessageText; public static string ip; public static string port; public static readonly WebSocket Connect; public static WebSocket Message; public static readonly WebSocket AssetBundle; private static ZioConfigEntry<string> _authUuid; public static float DownloadProgress; public static Action DownloadComplete; private static bool _isRetying; public static string AuthUuid { get { return _authUuid.Value; } set { _authUuid.Value = value; } } public static string GetUsername() { _authUuid = Load.ConfigFile.Bind<string>("UserAuth", "UUID", "", ""); return Utility.IsNullOrWhiteSpace(AuthUuid) ? RoR2Application.GetBestUserName() : AuthUuid; } static WebSocketClient() { //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Expected O, but got Unknown //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Expected O, but got Unknown //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Expected O, but got Unknown ip = "localhost"; port = "5001"; Connect = new WebSocket("ws://" + ip + ":" + port + "/Connect", Array.Empty<string>()); Message = new WebSocket("ws://" + ip + ":" + port + "/Message", Array.Empty<string>()); AssetBundle = new WebSocket("ws://" + ip + ":" + port + "/AssetBundle", Array.Empty<string>()); Connect.OnMessage += delegate(object _, MessageEventArgs e) { AuthUuid = (Guid.TryParse(e.Data, out var result) ? e.Data : ""); if (AuthUuid != null) { Connect.guid = result; Message.guid = result; Connect.Close(); ConnectToAssetBundle(); } }; Message.OnMessage += delegate(object _, MessageEventArgs e) { MessageText = MessageText + e.Data + "\n"; }; Message.OnError += delegate(object sender, ErrorEventArgs args) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Invalid comparison between Unknown and I4 bool flag = args.Message == "An exception has occurred while receiving a message."; Tools.Log(LogLevel.Error, args.Message); WebSocket val = (WebSocket)sender; if ((int)val.ReadyState == 1 && !flag) { Task.Run((Action)ConnectClient); } }; Message.OnClose += HandleClose("Message"); AssetBundle.OnMessage += delegate(object sender, MessageEventArgs e) { GetAssetBundle(e.Data); AssetBundle.Close(); }; } private static EventHandler<CloseEventArgs> HandleClose(string url) { return delegate { Tools.Log(LogLevel.Warning, "Lost Connection to server."); ReconnectSocket("ws://" + ip + ":" + port + "/" + url); }; } private static void GetAssetBundle(string obj) { using WebClient webClient = new WebClient(); webClient.DownloadProgressChanged += wc_DownloadProgressChanged; webClient.DownloadFileCompleted += DoneDownloading; webClient.DownloadFileAsync(new Uri(obj), webClient.QueryString["File"]); } private static void DoneDownloading(object sender, AsyncCompletedEventArgs e) { DownloadComplete?.Invoke(); } private static void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { DownloadProgress = e.ProgressPercentage; } private static void ConnectToAssetBundle() { AssetBundle.Connect(); AssetBundle.Send(GetUsername()); } public static void Bind(EventHandler<MessageEventArgs> action) { Message.OnMessage += action; Connect.OnMessage += action; } public static void UnBind(EventHandler<MessageEventArgs> action) { Message.OnMessage -= action; Connect.OnMessage -= action; } public static void TryConnect() { if (!_isRetying) { Task.Run((Action)ConnectClient); } } public static void ConnectClient() { if (_isRetying) { return; } _isRetying = true; string username = GetUsername(); int num = 10; int num2 = 1; while (num2 < num) { Connect.Connect(); Message.Connect(); if (Connect.IsAlive && Message.IsAlive) { Connect.Send(username); _isRetying = false; break; } Tools.Log(LogLevel.Error, $"Couldnt Connect to Server. Retrying {num - num2} times."); num2++; Task.Delay(5000); } } private static WebSocket ReconnectSocket(string ipaddress) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown return new WebSocket(ipaddress, Array.Empty<string>()); } public static void DisconnectClient() { Connect.Close(); Message.Close(); } } } namespace Aerolt.Overrides { [HarmonyPatch] public class Hooks { } public class IconSwap : MonoBehaviour { public Image discord; public Sprite imageToSwapTo; public void Awake() { int num = Random.Range(0, 99); if (num < 20) { SwapThisImage(); } } public void SwapThisImage() { discord.sprite = imageToSwapTo; } } } namespace Aerolt.Messages { public class BodyStatMessage : AeroltMessageBase { private string fieldName; private CharacterBody TargetBody; private float value; public BodyStatMessage() { } public BodyStatMessage(CharacterBody targetBody, string fieldName, float result) { this.fieldName = fieldName; TargetBody = targetBody; value = result; } public override void Handle() { base.Handle(); FieldInfo field = typeof(CharacterBody).GetField(fieldName, BindingFlags.Instance | BindingFlags.Public); field.SetValue(TargetBody, value); TargetBody.statsDirty = true; } public override void Deserialize(NetworkReader reader) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) ((MessageBase)this).Deserialize(reader); GameObject val = Util.FindNetworkObject(reader.ReadNetworkId()); if (Object.op_Implicit((Object)(object)val)) { TargetBody = val.GetComponent<CharacterBody>(); } fieldName = reader.ReadString(); value = reader.ReadSingle(); } public override void Serialize(NetworkWriter writer) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) ((MessageBase)this).Serialize(writer); writer.Write(((NetworkBehaviour)TargetBody).netId); writer.Write(fieldName); writer.Write(value); } } public class CurrencyMessage : AeroltMessageBase { private CurrencyType _type; private uint amount; private CharacterMaster master; public CurrencyMessage() { } public CurrencyMessage(CharacterMaster master, CurrencyType type, uint amount) { _type = type; this.amount = amount; this.master = master; } public override void Handle() { //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) base.Handle(); switch (_type) { case CurrencyType.Money: master.GiveMoney(amount - master.money); break; case CurrencyType.Lunar: { NetworkUser networkUser = master.playerCharacterMasterController.networkUser; long num = (int)amount - networkUser.NetworknetLunarCoins; if (num < 0) { networkUser.DeductLunarCoins((uint)Math.Abs(num)); } else { networkUser.AwardLunarCoins((uint)num); } break; } case CurrencyType.Void: master.GiveVoidCoins(amount - master.voidCoins); break; case CurrencyType.Experience: TeamManager.instance.SetTeamExperience(master.teamIndex, (ulong)amount); break; case CurrencyType.Level: TeamManager.instance.SetTeamLevel(master.teamIndex, amount); break; default: throw new ArgumentOutOfRangeException(); } } public override void Deserialize(NetworkReader reader) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) ((MessageBase)this).Deserialize(reader); GameObject val = Util.FindNetworkObject(reader.ReadNetworkId()); if (Object.op_Implicit((Object)(object)val)) { master = val.GetComponent<CharacterMaster>(); } _type = (CurrencyType)reader.ReadPackedUInt32(); amount = reader.ReadPackedUInt32(); } public override void Serialize(NetworkWriter writer) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) ((MessageBase)this).Serialize(writer); writer.Write(((NetworkBehaviour)master).netId); writer.WritePackedUInt32((uint)_type); writer.WritePackedUInt32(amount); } } public enum CurrencyType { Money, Lunar, Void, Experience, Level } public class GodModeMessage : AeroltMessageBase { private bool enabled; private CharacterMaster master; public GodModeMessage() { } public GodModeMessage(CharacterMaster master, bool enable) { this.master = master; enabled = enable; } public override void Handle() { base.Handle(); master.godMode = enabled; master.UpdateBodyGodMode(); } public override void Deserialize(NetworkReader reader) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) ((MessageBase)this).Deserialize(reader); GameObject val = Util.FindNetworkObject(reader.ReadNetworkId()); if (Object.op_Implicit((Object)(object)val)) { master = val.GetComponent<CharacterMaster>(); } enabled = reader.ReadBoolean(); } public override void Serialize(NetworkWriter writer) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) ((MessageBase)this).Serialize(writer); writer.Write(((NetworkBehaviour)master).netId); writer.Write(enabled); } } public class InteractableSpawnMessage : AeroltMessageBase { private uint index; private Vector3 position; public InteractableSpawnMessage() { } public InteractableSpawnMessage(uint index, Vector3 position) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) this.index = index; this.position = position; } public override void Serialize(NetworkWriter writer) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) ((MessageBase)this).Serialize(writer); writer.WritePackedUInt32(index); writer.Write(position); } public override void Deserialize(NetworkReader reader) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) ((MessageBase)this).Deserialize(reader); index = reader.ReadPackedUInt32(); position = reader.ReadVector3(); } public override void Handle() { //IL_000f: Unknown result type (might be due to invalid IL or missing references) base.Handle(); InteractableManager.Spawn(index, position); } } public class KillAllTeamMessage : AeroltMessageBase { private TeamIndex team; public KillAllTeamMessage() { } public KillAllTeamMessage(TeamIndex allExcept) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) team = allExcept; } public override void Handle() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) base.Handle(); TeamMask mask = TeamMask.AllExcept(team); CharacterMaster[] array = CharacterMaster.instancesList.Where((CharacterMaster x) => ((TeamMask)(ref mask)).HasTeam(x.teamIndex)).ToArray(); CharacterMaster[] array2 = array; foreach (CharacterMaster val in array2) { CharacterBody body = val.GetBody(); if (Object.op_Implicit((Object)(object)body)) { Chat.AddMessage("<color=yellow>Killed " + body.GetDisplayName() + " </color>"); } val.TrueKill(); } } public override void Deserialize(NetworkReader reader) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) ((MessageBase)this).Deserialize(reader); team = NetworkExtensions.ReadTeamIndex(reader); } public override void Serialize(NetworkWriter writer) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) ((MessageBase)this).Serialize(writer); NetworkExtensions.Write(writer, team); } } public class KillMessage : AeroltMessageBase { private CharacterMaster master; public KillMessage() { } public KillMessage(CharacterMaster master) { this.master = master; } public override void Handle() { base.Handle(); master.TrueKill(); } public override void Deserialize(NetworkReader reader) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) ((MessageBase)this).Deserialize(reader); GameObject val = Util.FindNetworkObject(reader.ReadNetworkId()); if (Object.op_Implicit((Object)(object)val)) { master = val.GetComponent<CharacterMaster>(); } } public override void Serialize(NetworkWriter writer) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) ((MessageBase)this).Serialize(writer); writer.Write(((NetworkBehaviour)master).netId); } } public class MonsterSpawnMessage : AeroltMessageBase { private string bodyName; private bool brainDead; private EquipmentIndex eliteIndex; private Dictionary<ItemDef, uint> itemCounts; private Vector3 location; private string masterName; private TeamIndex teamIndex; public MonsterSpawnMessage() { } public MonsterSpawnMessage(string masterName, string bodyName, Vector3 vector3, TeamIndex teamIndex1, EquipmentIndex equipmentIndex, bool brainDead, Dictionary<ItemDef, uint> toDictionary) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) this.masterName = masterName; this.bodyName = bodyName; location = vector3; teamIndex = teamIndex1; eliteIndex = equipmentIndex; this.brainDead = brainDead; itemCounts = toDictionary; } public override void Handle() { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Invalid comparison between Unknown and I4 //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) base.Handle(); GameObject val = MasterCatalog.FindMasterPrefab(masterName); GameObject val2 = Object.Instantiate<GameObject>(val.gameObject, location, Quaternion.identity); CharacterMaster component = val2.GetComponent<CharacterMaster>(); component.teamIndex = teamIndex; foreach (var (val4, num2) in itemCounts) { component.inventory.GiveItem(val4, (int)num2); } if ((int)eliteIndex != -1) { component.inventory.SetEquipmentIndex(eliteIndex); } if (brainDead) { BaseAI[] aiComponents = component.aiComponents; foreach (BaseAI val5 in aiComponents) { Object.Destroy((Object)(object)val5); } } NetworkServer.Spawn(val2); component.bodyPrefab = BodyCatalog.FindBodyPrefab(bodyName); component.SpawnBody(location, Quaternion.identity); } public override void Deserialize(NetworkReader reader) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) ((MessageBase)this).Deserialize(reader); masterName = reader.ReadString(); bodyName = reader.ReadString(); location = reader.ReadVector3(); teamIndex = NetworkExtensions.ReadTeamIndex(reader); eliteIndex = NetworkExtensions.ReadEquipmentIndex(reader); brainDead = reader.ReadBoolean(); itemCounts = reader.ReadItemAmounts(); } public override void Serialize(NetworkWriter writer) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) ((MessageBase)this).Serialize(writer); writer.Write(masterName); writer.Write(bodyName); writer.Write(location); NetworkExtensions.Write(writer, teamIndex); NetworkExtensions.Write(writer, eliteIndex); writer.Write(brainDead); writer.Write(itemCounts); } } public class PortalSpawnMessage : AeroltMessageBase { private string portal; public PortalSpawnMessage(string portal) { this.portal = portal; } public override void Handle() { //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Expected O, but got Unknown //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_01da: Expected O, but got Unknown base.Handle(); switch (portal) { case "gold": TeleporterInteraction.instance.shouldAttemptToSpawnGoldshoresPortal = true; break; case "newt": TeleporterInteraction.instance.shouldAttemptToSpawnShopPortal = true; break; case "blue": TeleporterInteraction.instance.shouldAttemptToSpawnMSPortal = true; break; case "void": { PortalSpawner val2 = ((IEnumerable<PortalSpawner>)TeleporterInteraction.instance.portalSpawners).FirstOrDefault((Func<PortalSpawner, bool>)((PortalSpawner x) => x.spawnMessageToken == "PORTAL_VOID_OPEN")); if ((Object)(object)val2 != (Object)null && Run.instance.IsExpansionEnabled(val2.requiredExpansion)) { val2.NetworkwillSpawn = true; if (!string.IsNullOrEmpty(val2.spawnPreviewMessageToken)) { Chat.SendBroadcastChat((ChatMessageBase)new SimpleChatMessage { baseToken = val2.spawnPreviewMessageToken }); } if (Object.op_Implicit((Object)(object)val2.previewChild)) { val2.previewChild.SetActive(true); } } break; } case "all": { Chat.AddMessage("<color=red>Spawned All Portal</color>"); TeleporterInteraction.instance.shouldAttemptToSpawnGoldshoresPortal = true; TeleporterInteraction.instance.shouldAttemptToSpawnShopPortal = true; TeleporterInteraction.instance.shouldAttemptToSpawnMSPortal = true; PortalSpawner[] portalSpawners = TeleporterInteraction.instance.portalSpawners; foreach (PortalSpawner val in portalSpawners) { if (Run.instance.IsExpansionEnabled(val.requiredExpansion)) { val.NetworkwillSpawn = true; if (!string.IsNullOrEmpty(val.spawnPreviewMessageToken)) { Chat.SendBroadcastChat((ChatMessageBase)new SimpleChatMessage { baseToken = val.spawnPreviewMessageToken }); } if (Object.op_Implicit((Object)(object)val.previewChild)) { val.previewChild.SetActive(true); } } } break; } } } public override void Deserialize(NetworkReader reader) { ((MessageBase)this).Deserialize(reader); portal = reader.ReadString(); } public override void Serialize(NetworkWriter writer) { ((MessageBase)this).Serialize(writer); writer.Write(portal); } } public class SceneChangeMessage : AeroltMessageBase { private bool isSet; private SceneIndex target; public SceneChangeMessage() { } public SceneChangeMessage(SceneIndex sceneIndex) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) isSet = true; target = sceneIndex; } public override void Handle() { //IL_0009: Unknown result type (might be due to invalid IL or missing references) base.Handle(); SceneDef sceneDef = SceneCatalog.GetSceneDef(target); if (isSet && Object.op_Implicit((Object)(object)sceneDef)) { Run.instance.AdvanceStage(sceneDef); Run instance = Run.instance; instance.stageClearCount--; } else { Run.instance.AdvanceStage(Run.instance.nextStageScene); } } public override void Deserialize(NetworkReader reader) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) ((MessageBase)this).Deserialize(reader); isSet = reader.ReadBoolean(); target = (SceneIndex)reader.ReadInt32(); } public override void Serialize(NetworkWriter writer) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected I4, but got Unknown ((MessageBase)this).Serialize(writer); writer.Write(isSet); writer.Write((int)target); } } public class SetBodyMessage : AeroltMessageBase { private string newBody; private NetworkUser user; public SetBodyMessage() { } public SetBodyMessage(NetworkUser user, CharacterBody newBody) : this(user) { this.newBody = ((Object)newBody).name; } public SetBodyMessage(NetworkUser networkUser) { user = networkUser; newBody = ""; } public override void Handle() { base.Handle(); GameOverController val = Object.FindObjectOfType<GameOverController>(); if (Object.op_Implicit((Object)(object)val)) { foreach (KeyValuePair<HUD, GameEndReportPanelController> reportPanel in val.reportPanels) { Object.Destroy((Object)(object)((Component)reportPanel.Value).gameObject); } Object.Destroy((Object)(object)((Component)val).gameObject); } if (NetworkServer.active) { bool usePod = false; if (Object.op_Implicit((Object)(object)Stage.instance)) { usePod = Stage.instance.usePod; Stage.instance.usePod = false; } user.master.preventRespawnUntilNextStageServer = false; user.master.CmdRespawn(newBody); if (Object.op_Implicit((Object)(object)Stage.instance)) { Stage.instance.usePod = usePod; } } } public override void Deserialize(NetworkReader reader) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) ((MessageBase)this).Deserialize(reader); GameObject val = Util.FindNetworkObject(reader.ReadNetworkId()); if (Object.op_Implicit((Object)(object)val)) { user = val.GetComponent<NetworkUser>(); } newBody = reader.ReadString(); } public override void Serialize(NetworkWriter writer) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) ((MessageBase)this).Serialize(writer); writer.Write(((NetworkBehaviour)user).netId); writer.Write(newBody); } } public class SetBuffCountMessage : AeroltMessageBase { public CharacterBody body; public Dictionary<BuffIndex, uint> buffCounts; public SetBuffCountMessage() { } public SetBuffCountMessage(CharacterBody bodyIn, Dictionary<BuffIndex, uint> buffCountsIn) { body = bodyIn; buffCounts = buffCountsIn; } public override void Handle() { //IL_0027: Unknown result type (might be due to invalid IL or missing references) base.Handle(); foreach (KeyValuePair<BuffIndex, uint> buffCount in buffCounts) { body.SetBuffCount(buffCount.Key, (int)buffCount.Value); } } public override void Deserialize(NetworkReader reader) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) ((MessageBase)this).Deserialize(reader); GameObject val = Util.FindNetworkObject(reader.ReadNetworkId()); if (Object.op_Implicit((Object)(object)val)) { body = val.GetComponent<CharacterBody>(); } uint num = reader.ReadPackedUInt32(); buffCounts = new Dictionary<BuffIndex, uint>(); for (int i = 0; i < num; i++) { buffCounts.Add((BuffIndex)reader.ReadPackedUInt32(), reader.ReadPackedUInt32()); } } public override void Serialize(NetworkWriter writer) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Expected I4, but got Unknown ((MessageBase)this).Serialize(writer); writer.Write(((NetworkBehaviour)body).netId); writer.WritePackedUInt32((uint)buffCounts.Count); foreach (var (val2, num2) in buffCounts) { writer.WritePackedUInt32((uint)(int)val2); writer.WritePackedUInt32(num2); } } } public class SetEquipmentMessage : AeroltMessageBase { private Dictionary<EquipmentDef, int> equipmentCounts; private Inventory inventory; public SetEquipmentMessage() { } public SetEquipmentMessage(Inventory inventory, Dictionary<EquipmentDef, int> equipmentCounts) { this.inventory = inventory; this.equipmentCounts = equipmentCounts; } public override void Serialize(NetworkWriter writer) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Expected I4, but got Unknown ((MessageBase)this).Serialize(writer); writer.Write(((NetworkBehaviour)inventory).netId); writer.WritePackedUInt32((uint)equipmentCounts.Count); foreach (var (val2, num2) in equipmentCounts) { writer.WritePackedUInt32((uint)(int)val2.equipmentIndex); writer.WritePackedUInt32((uint)num2); } } public override void Deserialize(NetworkReader reader) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) ((MessageBase)this).Deserialize(reader); GameObject obj = Util.FindNetworkObject(reader.ReadNetworkId()); inventory = ((obj != null) ? obj.GetComponent<Inventory>() : null); equipmentCounts = new Dictionary<EquipmentDef, int>(); uint num = reader.ReadPackedUInt32(); for (int i = 0; i < num; i++) { EquipmentDef equipmentDef = EquipmentCatalog.GetEquipmentDef((EquipmentIndex)reader.ReadPackedUInt32()); equipmentCounts.Add(equipmentDef, (int)reader.ReadPackedUInt32()); } } public override void Handle() { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0042->IL0042: Incompatible stack types: O vs I4 //IL_0036->IL0042: Incompatible stack types: I4 vs O //IL_0036->IL0042: Incompatible stack types: O vs I4 base.Handle(); foreach (KeyValuePair<EquipmentDef, int> equipmentCount in equipmentCounts) { object obj = inventory; int num; if (!Object.op_Implicit((Object)(object)equipmentCount.Key)) { num = -1; obj = num; num = (int)obj; } else { obj = equipmentCount.Key.equipmentIndex; num = (int)obj; } ((Inventory)num).SetEquipmentIndex((EquipmentIndex)obj); } } } public class SetItemCountMessage : AeroltMessageBase { private Inventory inventory; private Dictionary<ItemDef, uint> itemCounts; public SetItemCountMessage() { } public SetItemCountMessage(Inventory inventory, Dictionary<ItemDef, int> itemCounts) { this.inventory = inventory; this.itemCounts = itemCounts.ToDictionary((KeyValuePair<ItemDef, int> x) => x.Key, (KeyValuePair<ItemDef, int> x) => (uint)x.Value); } public override void Serialize(NetworkWriter writer) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) ((MessageBase)this).Serialize(writer); writer.Write(((NetworkBehaviour)inventory).netId); writer.Write(itemCounts); } public override void Deserialize(NetworkReader reader) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) ((MessageBase)this).Deserialize(reader); GameObject obj = Util.FindNetworkObject(reader.ReadNetworkId()); inventory = ((obj != null) ? obj.GetComponent<Inventory>() : null); itemCounts = reader.ReadItemAmounts(); } public override void Handle() { base.Handle(); foreach (KeyValuePair<ItemDef, uint> itemCount in itemCounts) { inventory.GiveItem(itemCount.Key, (int)itemCount.Value - inventory.GetItemCount(itemCount.Key)); } } } public class TeamSwitchMessage : AeroltMessageBase { private TeamIndex newTeam; private CharacterMaster target; public TeamSwitchMessage() { } public TeamSwitchMessage(CharacterMaster who, TeamIndex team) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) target = who; newTeam = team; } public override void Handle() { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) base.Handle(); target.teamIndex = newTeam; CharacterBody body = target.GetBody(); if (Object.op_Implicit((Object)(object)body)) { body.teamComponent.teamIndex = newTeam; } } public override void Deserialize(NetworkReader reader) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) ((MessageBase)this).Deserialize(reader); GameObject val = Util.FindNetworkObject(reader.ReadNetworkId()); if (Object.op_Implicit((Object)(object)val)) { target = val.GetComponent<CharacterMaster>(); } newTeam = (TeamIndex)(sbyte)reader.ReadInt32(); } public override void Serialize(NetworkWriter writer) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected I4, but got Unknown ((MessageBase)this).Serialize(writer); writer.Write(((NetworkBehaviour)target).netId); writer.Write((int)newTeam); } } public class TeleporterChargeMessage : AeroltMessageBase { public override void Handle() { base.Handle(); if (Object.op_Implicit((Object)(object)TeleporterInteraction.instance) && Object.op_Implicit((Object)(object)TeleporterInteraction.instance.holdoutZoneController)) { TeleporterInteraction.instance.holdoutZoneController.charge = 1f; } } } public class TeleportMessage : AeroltMessageBase { private Vector3 targetPosition; private CharacterBody teleportedBody; public TeleportMessage() { } public TeleportMessage(CharacterBody teleportedBody, Vector3 targetPosition) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) this.teleportedBody = teleportedBody; this.targetPosition = targetPosition; } public override void Handle() { //IL_003d: Unknown result type (might be due to invalid IL or missing references) base.Handle(); if (Object.op_Implicit((Object)(object)teleportedBody) && Object.op_Implicit((Object)(object)teleportedBody.characterMotor)) { ((BaseCharacterController)teleportedBody.characterMotor).Motor.MoveCharacter(targetPosition); } } public override void Deserialize(NetworkReader reader) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) ((MessageBase)this).Deserialize(reader); GameObject val = Util.FindNetworkObject(reader.ReadNetworkId()); if (Object.op_Implicit((Object)(object)val)) { teleportedBody = val.GetComponent<CharacterBody>(); } targetPosition = reader.ReadVector3(); } public override void Serialize(NetworkWriter writer) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) ((MessageBase)this).Serialize(writer); writer.Write(((NetworkBehaviour)teleportedBody).netId); writer.Write(targetPosition); } } } namespace Aerolt.Managers { public static class EspHelper { public static void DrawESPLabel(Vector3 worldpos, Color textcolor, Color outlinecolor, string text, string outlinetext = null) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0184: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_019f: Unknown result type (might be due to invalid IL or missing references) //IL_01a5: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Unknown result type (might be due to invalid IL or missing references) GUIContent val = new GUIContent(text); if (outlinetext == null) { outlinetext = text; } GUIContent val2 = new GUIContent(outlinetext); GUIStyle label = GUI.skin.label; label.alignment = (TextAnchor)4; Vector2 val3 = label.CalcSize(val); Vector3 val4 = Camera.main.WorldToScreenPoint(worldpos); val4.y = (float)Screen.height - val4.y; if (val4.z >= 0f) { GUI.color = Color.black; GUI.Label(new Rect(val4.x - val3.x / 2f + 1f, val4.y + 1f, val3.x, val3.y), val2); GUI.Label(new Rect(val4.x - val3.x / 2f - 1f, val4.y - 1f, val3.x, val3.y), val2); GUI.Label(new Rect(val4.x - val3.x / 2f + 1f, val4.y - 1f, val3.x, val3.y), val2); GUI.Label(new Rect(val4.x - val3.x / 2f - 1f, val4.y + 1f, val3.x, val3.y), val2); GUI.color = textcolor; GUI.Label(new Rect(val4.x - val3.x / 2f, val4.y, val3.x, val3.y), val); GUI.color = Color.black; } } public static void DrawRarityESPLabel(Vector3 worldpos, Color textcolor, Color outlinecolor, string text, Color itemColor, string itemName = "", string outlinetext = null) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0184: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_019f: Unknown result type (might be due to invalid IL or missing references) //IL_01a5: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: Unknown result type (might be due to invalid IL or missing references) //IL_0365: Unknown result type (might be due to invalid IL or missing references) //IL_01cd: Unknown result type (might be due to invalid IL or missing references) //IL_01d4: Expected O, but got Unknown //IL_01da: Unknown result type (might be due to invalid IL or missing references) //IL_01e1: Expected O, but got Unknown //IL_01e4: Unknown result type (might be due to invalid IL or missing references) //IL_01e9: Unknown result type (might be due to invalid IL or missing references) //IL_01eb: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: Unknown result type (might be due to invalid IL or missing references) //IL_01fd: Unknown result type (might be due to invalid IL or missing references) //IL_0211: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0225: Unknown result type (might be due to invalid IL or missing references) //IL_022c: Unknown result type (might be due to invalid IL or missing references) //IL_0233: Unknown result type (might be due to invalid IL or missing references) //IL_0240: Unknown result type (might be due to invalid IL or missing references) //IL_0247: Unknown result type (might be due to invalid IL or missing references) //IL_025b: Unknown result type (might be due to invalid IL or missing references) //IL_0268: Unknown result type (might be due to invalid IL or missing references) //IL_026f: Unknown result type (might be due to invalid IL or missing references) //IL_0276: Unknown result type (might be due to invalid IL or missing references) //IL_027d: Unknown result type (might be due to invalid IL or missing references) //IL_028a: Unknown result type (might be due to invalid IL or missing references) //IL_0291: Unknown result type (might be due to invalid IL or missing references) //IL_02a5: Unknown result type (might be due to invalid IL or missing references) //IL_02b2: Unknown result type (might be due to invalid IL or missing references) //IL_02b9: Unknown result type (might be due to invalid IL or missing references) //IL_02c0: Unknown result type (might be due to invalid IL or missing references) //IL_02c7: Unknown result type (might be due to invalid IL or missing references) //IL_02d4: Unknown result type (might be due to invalid IL or missing references) //IL_02db: Unknown result type (might be due to invalid IL or missing references) //IL_02ef: Unknown result type (might be due to invalid IL or missing references) //IL_02fc: Unknown result type (might be due to invalid IL or missing references) //IL_0303: Unknown result type (might be due to invalid IL or missing references) //IL_030a: Unknown result type (might be due to invalid IL or missing references) //IL_0311: Unknown result type (might be due to invalid IL or missing references) //IL_031e: Unknown result type (might be due to invalid IL or missing references) //IL_0326: Unknown result type (might be due to invalid IL or missing references) //IL_032d: Unknown result type (might be due to invalid IL or missing references) //IL_033b: Unknown result type (might be due to invalid IL or missing references) //IL_0342: Unknown result type (might be due to invalid IL or missing references) //IL_0349: Unknown result type (might be due to invalid IL or missing references) //IL_0350: Unknown result type (might be due to invalid IL or missing references) //IL_0357: Unknown result type (might be due to invalid IL or missing references) GUIContent val = new GUIContent(text); if (outlinetext == null) { outlinetext = text; } GUIContent val2 = new GUIContent(outlinetext); GUIStyle label = GUI.skin.label; label.alignment = (TextAnchor)4; Vector2 val3 = label.CalcSize(val); Vector3 val4 = Camera.main.WorldToScreenPoint(worldpos); val4.y = (float)Screen.height - val4.y; if (val4.z >= 0f) { GUI.color = Color.black; GUI.Label(new Rect(val4.x - val3.x / 2f + 1f, val4.y + 1f, val3.x, val3.y), val2); GUI.Label(new Rect(val4.x - val3.x / 2f - 1f, val4.y - 1f, val3.x, val3.y), val2); GUI.Label(new Rect(val4.x - val3.x / 2f + 1f, val4.y - 1f, val3.x, val3.y), val2); GUI.Label(new Rect(val4.x - val3.x / 2f - 1f, val4.y + 1f, val3.x, val3.y), val2); GUI.color = textcolor; GUI.Label(new Rect(val4.x - val3.x / 2f, val4.y, val3.x, val3.y), val); if (!string.IsNullOrEmpty(itemName)) { GUIContent val5 = new GUIContent(itemName); GUIContent val6 = new GUIContent(itemName); Vector2 val7 = label.CalcSize(val5); GUI.color = Color.black; GUI.Label(new Rect(val4.x - val7.x / 2f + 1f, val4.y + 1f + val3.y, val7.x, val7.y), val6); GUI.Label(new Rect(val4.x - val7.x / 2f - 1f, val4.y - 1f + val3.y, val7.x, val7.y), val6); GUI.Label(new Rect(val4.x - val7.x / 2f + 1f, val4.y - 1f + val3.y, val7.x, val7.y), val6); GUI.Label(new Rect(val4.x - val7.x / 2f - 1f, val4.y + 1f + val3.y, val7.x, val7.y), val6); GUI.color = itemColor; GUI.Label(new Rect(val4.x - val7.x / 2f, val4.y + val3.y, val7.x, val7.y), val5); } GUI.color = Color.black; } } public static void DrawMultiShopRarityESPLabel(Vector3 worldpos, Color textcolor, Color outlinecolor, string text, List<Color> itemColors, List<string> itemNames, string outlinetext = null) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0184: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_019f: Unknown result type (might be due to invalid IL or missing references) //IL_01a5: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: Unknown result type (might be due to invalid IL or missing references) //IL_03db: 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_01e8: Unknown result type (might be due to invalid IL or missing references) //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_01f3: Expected O, but got Unknown //IL_01f9: Unknown result type (might be due to invalid IL or missing references) //IL_0200: Expected O, but got Unknown //IL_0203: Unknown result type (might be due to invalid IL or missing references) //IL_0208: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_0215: Unknown result type (might be due to invalid IL or missing references) //IL_021c: Unknown result type (might be due to invalid IL or missing references) //IL_0230: Unknown result type (might be due to invalid IL or missing references) //IL_023d: Unknown result type (might be due to invalid IL or missing references) //IL_0247: Unknown result type (might be due to invalid IL or missing references) //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Unknown result type (might be due to invalid IL or missing references) //IL_025e: Unknown result type (might be due to invalid IL or missing references) //IL_026b: Unknown result type (might be due to invalid IL or missing references) //IL_0272: Unknown result type (might be due to invalid IL or missing references) //IL_0286: Unknown result type (might be due to invalid IL or missing references) //IL_0293: Unknown result type (might be due to invalid IL or missing references) //IL_029d: Unknown result type (might be due to invalid IL or missing references) //IL_02a6: Unknown result type (might be due to invalid IL or missing references) //IL_02ad: Unknown result type (might be due to invalid IL or missing references) //IL_02b4: Unknown result type (might be due to invalid IL or missing references) //IL_02c1: Unknown result type (might be due to invalid IL or missing references) //IL_02c8: Unknown result type (might be due to invalid IL or missing references) //IL_02dc: Unknown result type (might be due to invalid IL or missing references) //IL_02e9: Unknown result type (might be due to invalid IL or missing references) //IL_02f3: Unknown result type (might be due to invalid IL or missing references) //IL_02fc: Unknown result type (might be due to invalid IL or missing references) //IL_0303: Unknown result type (might be due to invalid IL or missing references) //IL_030a: Unknown result type (might be due to invalid IL or missing references) //IL_0317: Unknown result type (might be due to invalid IL or missing references) //IL_031e: Unknown result type (might be due to invalid IL or missing references) //IL_0332: Unknown result type (might be due to invalid IL or missing references) //IL_033f: Unknown result type (might be due to invalid IL or missing references) //IL_0349: Unknown result type (might be due to invalid IL or missing references) //IL_0352: Unknown result type (might be due to invalid IL or missing references) //IL_0359: Unknown result type (might be due to invalid IL or missing references) //IL_0360: Unknown result type (might be due to invalid IL or missing references) //IL_036d: Unknown result type (might be due to invalid IL or missing references) //IL_0375: Unknown result type (might be due to invalid IL or missing references) //IL_037c: Unknown result type (might be due to invalid IL or missing references) //IL_038a: Unknown result type (might be due to invalid IL or missing references) //IL_0391: Unknown result type (might be due to invalid IL or missing references) //IL_039b: Unknown result type (might be due to invalid IL or missing references) //IL_03a4: Unknown result type (might be due to invalid IL or missing references) //IL_03ab: Unknown result type (might be due to invalid IL or missing references) //IL_03b2: Unknown result type (might be due to invalid IL or missing references) GUIContent val = new GUIContent(text); if (outlinetext == null) { outlinetext = text; } GUIContent val2 = new GUIContent(outlinetext); GUIStyle label = GUI.skin.label; label.alignment = (TextAnchor)4; Vector2 val3 = label.CalcSize(val); Vector3 val4 = Camera.main.WorldToScreenPoint(worldpos); val4.y = (float)Screen.height - val4.y; if (!(val4.z >= 0f)) { return; } GUI.color = Color.black; GUI.Label(new Rect(val4.x - val3.x / 2f + 1f, val4.y + 1f, val3.x, val3.y), val2); GUI.Label(new Rect(val4.x - val3.x / 2f - 1f, val4.y - 1f, val3.x, val3.y), val2); GUI.Label(new Rect(val4.x - val3.x / 2f + 1f, val4.y - 1f, val3.x, val3.y), val2); GUI.Label(new Rect(val4.x - val3.x / 2f - 1f, val4.y + 1f, val3.x, val3.y), val2); GUI.color = textcolor; GUI.Label(new Rect(val4.x - val3.x / 2f, val4.y, val3.x, val3.y), val); for (int i = 0; i < itemNames.Count; i++) { string text2 = itemNames[i]; if (!string.IsNullOrEmpty(text2)) { Color color = itemColors[i]; GUIContent val5 = new GUIContent(text2); string text3 = text2; GUIContent val6 = new GUIContent(text3); Vector2 val7 = label.CalcSize(val5); GUI.color = Color.black; GUI.Label(new Rect(val4.x - val7.x / 2f + 1f, val4.y + 1f + val3.y + (float)i * val7.y, val7.x, val7.y), val6); GUI.Label(new Rect(val4.x - val7.x / 2f - 1f, val4.y - 1f + val3.y + (float)i * val7.y, val7.x, val7.y), val6); GUI.Label(new Rect(val4.x - val7.x / 2f + 1f, val4.y - 1f + val3.y + (float)i * val7.y, val7.x, val7.y), val6); GUI.Label(new Rect(val4.x - val7.x / 2f - 1f, val4.y + 1f + val3.y + (float)i * val7.y, val7.x, val7.y), val6); GUI.color = color; GUI.Label(new Rect(val4.x - val7.x / 2f, val4.y + val3.y + (float)i * val7.y, val7.x, val7.y), val5); } } GUI.color = Color.black; } public static Vector3 WorldToScreen(Vector3 worldpos) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) Vector3 val = Camera.main.WorldToScreenPoint(worldpos); val.y = (float)Screen.height - val.y; return new Vector3(val.x, val.y); } } public class BodyManager : MonoBehaviour { public GameObject buttonPrefab; public GameObject buttonParent; public TMP_InputField searchFilter; private GameObject _newBody; private readonly Dictionary<CharacterBody, CustomButton> bodyDefRef = new Dictionary<CharacterBody, CustomButton>(); private NetworkUser target; private void Awake() { //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Expected O, but got Unknown //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Expected O, but got Unknown foreach (CharacterBody body in BodyCatalog.allBodyPrefabBodyBodyComponents.OrderBy((CharacterBody x) => Language.GetString(x.baseNameToken))) { GameObject val = Object.Instantiate<GameObject>(buttonPrefab, buttonParent.transform); CustomButton component = val.GetComponent<CustomButton>(); component.buttonText.text = Language.GetString(body.baseNameToken); component.image.sprite = Sprite.Create((Texture2D)body.portraitIcon, new Rect(0f, 0f, (float)body.portraitIcon.width, (float)body.portraitIcon.height), new Vector2(0.5f, 0.5f)); ((UnityEvent)component.button.onClick).AddListener((UnityAction)delegate { SetBodyDef(body); }); bodyDefRef[body] = component; } if (Object.op_Implicit((Object)(object)searchFilter)) { ((UnityEvent<string>)(object)searchFilter.onValueChanged).AddListener((UnityAction<string>)FilterUpdated); } } public void SpawnAsBody() { new SetBodyMessage(target, _newBody.GetComponent<CharacterBody>()).SendToServer(); } public void SetBodyDef(CharacterBody body) { _newBody = BodyCatalog.FindBodyPrefab(body); SpawnAsBody(); ((Component)this).GetComponentInParent<LobbyPlayerPageManager>().SwapViewState(); } public void Initialize(NetworkUser currentUser) { target = currentUser; } private void FilterUpdated(string text) { if (Utility.IsNullOrWhiteSpace(text)) { foreach (KeyValuePair<CharacterBody, CustomButton> item in bodyDefRef) { ((Component)item.Value).gameObject.SetActive(true); } return; } CustomButton[] array = bodyDefRef.Values.ToArray(); CustomButton[] source = Tools.FindMatches(array, (CustomButton x) => x.buttonText.text, text); CustomButton[] array2 = array; foreach (CustomButton customButton in array2) { ((Component)customButton).gameObject.SetActive(source.Contains(customButton)); } } } public class ConnectionManager : MonoBehaviour { public Button yesButton; public Button noButton; public GameObject loadingScreen; public static AssetBundle Assets; public static string Path; public static GameObject ChatWindow; public void DontConnectToServer() { Tools.Log(LogLevel.Warning, "Aerolt will not connect to the server."); } public void StartConnectToServer() { WebSocketClient.TryConnect(); WebSocketClient.DownloadComplete = (Action)Delegate.Combine(WebSocketClient.DownloadComplete, new Action(SetUpAssetBundle)); } private void SetUpAssetBundle() { Assets = AssetBundle.LoadFromFile(System.IO.Path.Combine(Load.Path, WebSocketClient.AuthUuid)); Tools.Log(LogLevel.Information, "Loaded AssetBundle"); ChatWindow = Assets.LoadAsset<GameObject>("ChatWindowV2"); Component component = ChatWindow.GetComponent(typeof(RectTransform)); RectTransform source = (RectTransform)(object)((component is RectTransform) ? component : null); source.SetSize(746f, 480f); Object.Instantiate<GameObject>(loadingScreen, ((Component)this).transform); } } public class InteractableManager : MonoBehaviour, IModuleStartup { [CanBeNull] public static SpawnCard[] _spawnCards; public GameObject buttonPrefab; public GameObject buttonParent; public TMP_InputField searchFilter; private MenuInfo _info; private readonly Dictionary<SpawnCard, CustomButton> cardDefRef = new Dictionary<SpawnCard, CustomButton>(); private static bool isScalingInteractablePricesConstantly; public static Dictionary<SpawnCard, int> startOfRoundScaledInteractableCosts; public static SpawnCard[] cards => _spawnCards ?? (_spawnCards = (from x in (from x in (from x in ClassicStageInfo.instance.interactableDccsPool.GenerateWeightedSelection().choices where !((object)x).Equals((object?)null) && Object.op_Implicit((Object)(object)x.value) select x.value into x where !((object)x).Equals((object?)null) && x.categories != null select x.categories).SelectMany((Category[] x) => x) where !((object)(Category)(ref x)).Equals((object?)null) && !x.cards.Equals(null) select x.cards).SelectMany((DirectorCard[] x) => x) select x.spawnCard).Union(from x in Object.FindObjectOfType<SceneDirector>().GenerateInteractableCardSelection().choices where x.value != null && (Object)(object)x.value.spawnCard != (Object)null select x.value.spawnCard).ToArray()); static InteractableManager() { isScalingInteractablePricesConstantly = false; startOfRoundScaledInteractableCosts = new Dictionary<SpawnCard, int>(); Run.onRunStartGlobal += delegate { _spawnCards = null; }; } public void ModuleStart() { //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Expected O, but got Unknown //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Invalid comparison between Unknown and I4 _info = ((Component)this).GetComponentInParent<MenuInfo>(); startOfRoundScaledInteractableCosts.Clear(); foreach (SpawnCard card in cards.OrderBy((SpawnCard x) => (x.prefab.GetComponentInChildren<IDisplayNameProvider>() != null) ? x.prefab.GetComponentInChildren<IDisplayNameProvider>().GetDisplayName() : ((Object)x).name)) { if (!((object)card).Equals((object?)null) && !((object)card).Equals((object?)null)) { GameObject val = Object.Instantiate<GameObject>(buttonPrefab, buttonParent.transform); IDisplayNameProvider componentInChildren = card.prefab.GetComponentInChildren<IDisplayNameProvider>(); CustomButton component = val.GetComponent<CustomButton>(); component.buttonText.text = ((componentInChildren != null) ? componentInChildren.GetDisplayName() : ((Object)card).name); component.image.sprite = PingIndicator.GetInteractableIcon(card.prefab); ((UnityEvent)component.button.onClick).AddListener((UnityAction)delegate { SpawnInteractable(card); }); cardDefRef[card] = component; GameObject prefab = card.prefab; PurchaseInteraction component2 = prefab.GetComponent<PurchaseInteraction>(); if (Object.op_Implicit((Object)(object)component2) && (int)component2.costType == 1) { int difficultyScaledCost = Run.instance.GetDifficultyScaledCost(component2.cost); startOfRoundScaledInteractableCosts.Add(card, difficultyScaledCost); } } } if (Object.op_Implicit((Object)(object)searchFilter)) { ((UnityEvent<string>)(object)searchFilter.onValueChanged).AddListener((UnityAction<string>)FilterUpdated); } } public void SpawnInteractable(SpawnCard card) { //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)_info.Master)) { Tools.Log(LogLevel.Error, "Cant Spawn Interactable Localuser Master is null"); return; } CharacterBody body = _info.Body; if (!Object.op_Implicit((Object)(object)body)) { Tools.Log(LogLevel.Error, "Cant Spawn Interactable Localuser Body is null"); return; } Vector3 position = body.transform.position; Ray aimRay = body.inputBank.GetAimRay(); Vector3 val = ((Ray)(ref aimRay)).direction * 1.6f; if (NetworkServer.active) { Spawn((uint)Array.IndexOf(cards, card), position + val); } else { ClientScene.readyConnection.SendAerolt(new InteractableSpawnMessage((uint)Array.IndexOf(cards, card), position + val)); } } public static void Spawn(uint index, Vector3 position) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Expected O, but got Unknown //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Invalid comparison between Unknown and I4 SpawnCard val = cards[index]; DirectorPlacementRule val2 = new DirectorPlacementRule { placementMode = (PlacementMode)3, maxDistance = 30f, minDistance = 10f, position = position, preventOverhead = true }; DirectorSpawnRequest val3 = new DirectorSpawnRequest(val, val2, RoR2Application.rng); GameObject val4 = DirectorCore.instance.TrySpawnObject(val3); if (Object.op_Implicit((Object)(object)val4)) { PurchaseInteraction component = val4.GetComponent<PurchaseInteraction>(); if (Object.op_Implicit((Object)(object)component) && (int)component.costType == 1) { component.Networkcost = (isScalingInteractablePricesConstantly ? Run.instance.GetDifficultyScaledCost(component.cost) : startOfRoundScaledInteractableCosts[val]); } } } private void FilterUpdated(string text) { if (Utility.IsNullOrWhiteSpace(text)) { foreach (KeyValuePair<SpawnCard, CustomButton> item in cardDefRef) { ((Component)item.Value).gameObject.SetActive(true); } return; } CustomButton[] array = cardDefRef.Values.ToArray(); CustomButton[] source = Tools.FindMatches(array, (CustomButton x) => x.buttonText.text, text); CustomButton[] array2 = array; foreach (CustomButton customButton in array2) { ((Component)customButton).gameObject.SetActive(source.Contains(customButton)); } } } [RequireComponent(typeof(ToggleGroup))] public class LobbyPlayerManager : MonoBehaviour, IModuleStartup { public GameObject playerEntryPrefab; public Transform playerEntryParent; public readonly Dictionary<NetworkUser, PlayerConfigBinding> users = new Dictionary<NetworkUser, PlayerConfigBinding>(); private LobbyPlayerPageManager _pageManager; private MenuInfo info; private NetworkUser selectedUser; private ToggleGroup toggleGroup; private void OnEnable() { foreach (NetworkUser key in users.Keys) { UpdateUserLobbyButton(key); } } public void ModuleStart() { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown NetworkUser.onPostNetworkUserStart += new NetworkUserGenericDelegate(UserAdded); NetworkUser.onNetworkUserLost += new NetworkUserGenericDelegate(UserLost); info = ((Component)this).GetComponentInParent<MenuInfo>(); toggleGroup = ((Component)this).GetComponent<ToggleGroup>(); _pageManager = ((Component)this).GetComponent<LobbyPlayerPageManager>(); foreach (NetworkUser instances in NetworkUser.instancesList) { UserAdded(instances); } } void IModuleStartup.ModuleEnd() { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown NetworkUser.onPostNetworkUserStart -= new NetworkUserGenericDelegate(UserAdded); NetworkUser.onNetworkUserDiscovered -= new NetworkUserGenericDelegate(UserAdded); NetworkUser.onNetworkUserLost -= new NetworkUserGenericDelegate(UserLost); foreach (var (_, playerConfigBinding2) in users) { playerConfigBinding2.OnDestroy(); } } private void UpdateUserLobbyButton(NetworkUser user) { CustomButton customButton = users[user].customButton; customButton.buttonText.text = user.userName; if (Object.op_Implicit((Object)(object)user.master) && Object.op_Implicit((Object)(object)user.master.bodyPrefab)) { customButton.rawImage.texture = user.master.bodyPrefab.GetComponent<CharacterBody>().portraitIcon; } } private void UserAdded(NetworkUser user) { if (users.ContainsKey(user)) { return; } CustomButton component = Object.Instantiate<GameObject>(playerEntryPrefab, playerEntryParent, false).GetComponent<CustomButton>(); users[user] = new PlayerConfigBinding(user, component); Toggle component2 = ((Component)component).GetComponent<Toggle>(); component2.group = toggleGroup; ((UnityEvent<bool>)(object)component2.onValueChanged).AddListener((UnityAction<bool>)delegate(bool val) { if (val) { SetUser(user); } }); if ((Object)(object)user == (Object)(object)info.Owner) { component2.Set(true, true); } if (Object.op_Implicit((Object)(object)user.master)) { if (NetworkServer.active) { BodyStart(user.master.GetBody()); } user.master.onBodyStart += BodyStart; } } private void BodyStart(CharacterBody body) { if (Object.op_Implicit((Object)(object)body)) { NetworkUser networkUser = body.master.playerCharacterMasterController.networkUser; users[networkUser].Sync(); } } private void UserLost(NetworkUser user) { if (users.ContainsKey(user)) { Object.Destroy((Object)(object)((Component)users[user].customButton).gameObject); users[user].OnDestroy(); users.Remove(user); if ((Object)(object)selectedUser == (Object)(object)user && users.Any()) { SetUser(users.Keys.Last()); } if (Object.op_Implicit((Object)(object)user.master)) { user.master.onBodyStart -= BodyStart; } } } private void SetUser(NetworkUser user) { selectedUser = user; _pageManager.SetUser(user); } } public class LobbyPlayerPageManager : MonoBehaviour, IModuleStartup { [CanBeNull] private static PickupDropTable _chest1DropTable; public PlayerValuesGenerator bodyStats; [Header("Inventory Display")] public ItemInventoryDisplay inventoryDisplay; public EquipmentIcon equipmentIcon; public BuffDisplay buffDisplay; [Header("Toggles")] public Toggle aimbotToggle; public Toggle noclipToggle; public Toggle godToggle; public Toggle infiniteSkillsToggle; public Toggle alwaysSprintToggle; public Toggle disableMobSpawnToggle; [Header("Sliders")] public Slider aimbotWeightSlider; public Slider xpSlider; [Header("DropDowns")] public TMP_Dropdown teamDropdown; [Header("InputFields")] public TMP_InputField moneyInputField; public TMP_InputField lunarCoinsInputField; public TMP_InputField voidMarkersInputField; public TMP_InputField xpToGiveInputField; [Header("Content Display")] public GameObject mainContent; public EditPlayerItemButton itemContent; public EquipmentButtonGenerator equipmentContent; public BodyManager bodyContent; public EditPlayerBuffButton buffContent; public TMP_Text LevelLabel; private PlayerConfigBinding _playerConfig; private ViewState _state = ViewState.Main; private CharacterBody body; [Header("Character Info")] private NetworkUser currentUser; private ValueWrapper<bool> disableMobSpawns; private MenuInfo info; private CharacterMaster master; private bool ownerIsSelected; private LobbyPlayerManager playerManager; private static List<ItemDef> _giveAllFilteredItems; public static PickupDropTable Chest1DropTable => _chest1DropTable ?? (_chest1DropTable = LegacyResourcesAPI.Load<PickupDropTable>("DropTables/dtSmallChest")); public static List<ItemDef> GiveAllFilteredItems { get { object obj = _giveAllFilteredItems; if (obj == null) { obj = new List<ItemDef> { Items.DroneWeaponsBoost, Items.HealthDecay, Items.LunarPrimaryReplacement, Items.LunarSecondaryReplacement, Items.LunarUtilityReplacement, Items.LunarSpecialReplacement }; _giveAllFilteredItems = (List<ItemDef>)obj; } return (List<ItemDef>)obj; } } private PlayerConfigBinding PlayerConfig { get { return _playerConfig; } set { if (_playerConfig != null && _playerConfig != value) { _playerConfig.UnBind(UpdateCheckboxValues); } _playerConfig = value; _playerConfig.Bind(UpdateCheckboxValues); UpdateCheckboxValues(); } } public void Kick() { new KickBanMessage(currentUser, kick: true).SendToServer(); } public void Ban() { new KickBanMessage(currentUser, kick: false, ban: true).SendToServer(); } public void Goto() { //IL_003b: Unknown result type (might be due to invalid IL or missing references) if (Object.op_Implicit((Object)(object)info.Body) && Object.op_Implicit((Object)(object)body)) { new TeleportMessage(info.Body, body.transform.position).SendToAuthority(info.Body); } } public void Bring() { //IL_003b: Unknown result type (might be due to invalid IL or missing references) if (Object.op_Implicit((Object)(object)info.Body) && Object.op_Implicit((Object)(object)body)) { new TeleportMessage(body, info.Body.transform.position).SendToAuthority(body); } } public void Kill() { if (Object.op_Implicit((Object)(object)master)) { new KillMessage(master).SendToServer(); } } public void Revive() { SetBodyMessage setBodyMessage = new SetBodyMessage(currentUser); if (!NetworkServer.active) { setBodyMessage.Handle(); } setBodyMessage.SendToServer(); } public void GiveAllItems() { if (Object.op_Implicit((Object)(object)master)) { Dictionary<ItemDef, int> itemCounts = ContentManager.itemDefs.Except(GiveAllFilteredItems).ToDictionary((ItemDef x) => x, (ItemDef def) => master.inventory.GetItemCount(def) + 1); new SetItemCountMessage(master.inventory, itemCounts).SendToServer(); } } public void GiveRandomItems() { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)master)) { return; } Dictionary<ItemDef, int> dictionary = new Dictionary<ItemDef, int>(); for (int i = 0; i < Random.Range(0, 100); i++) { PickupIndex val = Chest1DropTable.GenerateDrop(RoR2Application.rng); PickupDef pickupDef = PickupCatalog.GetPickupDef(val); ItemDef itemDef = ItemCatalog.GetItemDef((ItemIndex)((pickupDef == null) ? (-1) : ((int)pickupDef.itemIndex))); if (!((Object)(object)itemDef == (Object)null)) { if (!dictionary.ContainsKey(itemDef)) { dictionary[itemDef] = master.inventory.GetItemCount(itemDef); } dictionary[itemDef] += Random.Range(0, 100); } } new SetItemCountMessage(master.inventory, dictionary).SendToServer(); } public void ClearInventory() { Dictionary<ItemDef, int> itemCounts = ContentManager.itemDefs.ToDictionary((ItemDef x) => x, (ItemDef _) => 0); new SetItemCountMessage(master.inventory, itemCounts).SendToServer(); } public void OpenInventory() { SwapViewState(ViewState.Inventory); } public void OpenBuffs() { SwapViewState(ViewState.Buff); } public void OpenEquipment() { SwapViewState(ViewState.Equipment); } public void OpenSpawnAs() { SwapViewState(ViewState.Body); } public void Update() { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) if (Object.op_Implicit((Object)(object)currentUser) && Object.op_Implicit((Object)(object)master)) { ((TMP_Text)(TextMeshProUGUI)moneyInputField.placeholder).text = master.money.ToString(); ((TMP_Text)(TextMeshProUGUI)voidMarkersInputField.placeholder).text = master.voidCoins.ToString(); ((TMP_Text)(TextMeshProUGUI)lunarCoinsInputField.placeholder).text = currentUser.lunarCoins.ToString(); } } private void OnEnable() { UpdateLevelValues(); } public void ModuleStart() { info = ((Component)this).GetComponentInParent<MenuInfo>(); playerManager = ((Component)this).GetComponent<LobbyPlayerManager>(); bodyStats.Setup(); GlobalEventManager.onTeamLevelUp += OnTeamLevelUp; teamDropdown.options.Clear(); teamDropdown.AddOptions((from x in Enum.GetNames(typeof(TeamIndex)) where x != "None" select x).ToList()); ((UnityEvent<bool>)(object)godToggle.onValueChanged).AddListener((UnityAction<bool>)delegate(bool val) { PlayerConfig.GodMode.Value = val; }); ((UnityEvent<bool>)(object)aimbotToggle.onValueChanged).AddListener((UnityAction<bool>)delegate(bool val) { PlayerConfig.Aimbot.Value = val; }); ((UnityEvent<float>)(object)aimbotWeightSlider.onValueChanged).AddListener((UnityAction<float>)delegate(float val) { PlayerConfig.AimbotWeight.Value = val; }); ((UnityEvent<bool>)(object)noclipToggle.onValueChanged).AddListener((UnityAction<bool>)delegate(bool val) { PlayerConfig.Noclip.Value = val; }); ((UnityEvent<bool>)(object)infiniteSkillsToggle.onValueChanged).AddListener((UnityAction<bool>)delegate(bool val) { PlayerConfig.InfiniteSkills.Value = val; }); ((UnityEvent<bool>)(object)alwaysSprintToggle.onValueChanged).AddListener((UnityAction<bool>)delegate(bool val) { PlayerConfig.AlwaysSprint.Value = val; }); ((UnityEvent<string>)(object)moneyInputField.onEndEdit).AddListener((UnityAction<string>)delegate(string amt) { SetCurrency(CurrencyType.Money, amt); moneyInputField.SetTextWithoutNotify(""); }); ((UnityEvent<string>)(object)lunarCoinsInputField.onEndEdit).AddListener((UnityAction<string>)delegate(string amt) { SetCurrency(CurrencyType.Lunar, amt); lunarCoinsInputField.SetTextWithoutNotify(""); }); ((UnityEvent<string>)(object)voidMarkersInputField.onEndEdit).AddListener((UnityAction<string>)delegate(string amt) { SetCurrency(CurrencyType.Void, amt); lunarCoinsInputField.SetTextWithoutNotify(""); }); ((UnityEvent<string>)(object)xpToGiveInputField.onEndEdit).AddListener((UnityAction<string>)delegate(string amt) { SetCurrency(CurrencyType.Level, amt); UpdateLevelValues(); xpToGiveInputField.SetTextWithoutNotify(""); }); ((UnityEvent<int>)(object)teamDropdown.onValueChanged).AddListener((UnityAction<int>)TeamChanged); TeamComponent.onJoinTeamGlobal += TeamJoined; disableMobSpawns = ValueWrapper.Get("PlayerMenu", "DisableMobSpawns", defaultValue: false, ""); disableMobSpawns.settingChanged += MobSpawnsChanged; ((UnityEvent<bool>)(object)disableMobSpawnToggle.onValueChanged).AddListener((UnityAction<bool>)delegate(bool val) { disableMobSpawns.Value = val; }); disableMobSpawns.Sync(); } void IModuleStartup.ModuleEnd() { disableMobSpawns.settingChanged -= MobSpawnsChanged; } private void UpdateCheckboxValues() { godToggle.SetIsOnWithoutNotify(PlayerConfig.GodMode.Value); aimbotToggle.SetIsOnWithoutNotify(PlayerConfig.Aimbot.Value); noclipToggle.SetIsOnWithoutNotify(PlayerConfig.Noclip.Value); infiniteSkillsToggle.SetIsOnWithoutNotify(PlayerConfig.InfiniteSkills.Value); alwaysSprintToggle.SetIsOnWithoutNotify(PlayerConfig.AlwaysSprint.Value); aimbotWeightSlider.SetValueWithoutNotify(PlayerConfig.AimbotWeight.Value); } public void SetUser(NetworkUser user) { if ((Object)(object)currentUser != (Object)null && Object.op_Implicit((Object)(object)currentUser.master)) { currentUser.master.onBodyStart -= SetBody; } currentUser = user; PlayerConfig = playerManager.users[currentUser]; SwapViewState(); ownerIsSelected = (Object)(object)currentUser == (Object)(object)info.Owner; bodyStats.SetTogglesActive(ownerIsSelected); master = currentUser.master; UpdateLevelValues(); if (Object.op_Implicit((Object)(object)master)) { Inventory inventory = master.inventory; equipmentIcon.targetInventory = inventory; master.onBodyStart += SetBody; CharacterBody val = master.GetBody(); if (Object.op_Implicit((Object)(object)val)) { SetBody(val); } } } private void SetBody(CharacterBody bodyIn) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Expected I4, but got Unknown body = bodyIn; if (!ownerIsSelected) { bodyStats.ProfileSelected(0, applyValuesToBody: false); } buffDisplay.source = body; bodyStats.TargetBody = body; teamDropdown.SetValueWithoutNotify((int)body.teamComponent.teamIndex); } private void MobSpawnsChanged() { disableMobSpawnToggle.SetIsOnWithoutNotify(disableMobSpawns.Value); if (!NetworkServer.active) { return; } foreach (CombatDirector instances in CombatDirector.instancesList) { instances.monsterSpawnTimer = (disableMobSpawns.Value ? float.PositiveInfinity : 0f); } } private void TeamJoined(TeamComponent who, TeamIndex team) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected I4, but got Unknown if ((Object)(object)who.body == (Object)(object)body) { teamDropdown.SetValueWithoutNotify((int)team); } } public void SetCurrency(CurrencyType currencyType, string strAmount) { if (uint.TryParse(strAmount, out var result)) { new CurrencyMessage(master, currencyType, result).SendToServer(); } } public void SetXp() { SetCurrency(CurrencyType.Experience, Mathf.RoundToInt(xpSlider.value).ToString()); UpdateLevelValues(); } private void OnTeamLevelUp(TeamIndex obj) { xpSlider.value = TeamManager.instance.GetTeamCurrentLevelExperience((TeamIndex)(sbyte)teamDropdown.value); LevelLabel.text = $"Lv : {TeamManager.instance.GetTeamLevel((TeamIndex)(sbyte)teamDropdown.value)}"; } private void UpdateLevelValues() { LevelLabel.text = $"Lv : {TeamManager.instance.GetTeamLevel((TeamIndex)(sbyte)teamDropdown.value)}"; xpSlider.minValue = TeamManager.instance.GetTeamCurrentLevelExperience((TeamIndex)(sbyte)teamDropdown.value); xpSlider.maxValue = TeamManager.instance.GetTeamNextLevelExperience((TeamIndex)(sbyte)teamDropdown.value); xpSlider.value = TeamManager.instance.GetTeamExperience((TeamIndex)(sbyte)teamDropdown.value); } public void TeamChanged(int team) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) if (Object.op_Implicit((Object)(object)master)) { TeamIndex team2 = (TeamIndex)(sbyte)team; new TeamSwitchMessage(master, team2).SendToServer(); UpdateLevelValues(); } } public void SwapViewState(ViewState newState) { switch (_state) { case ViewState.Main: mainContent.SetActive(false); break; case ViewState.Inventory: ((Component)itemContent).gameObject.SetActive(false); break; case ViewState.Equipment: ((Component)equipmentContent).gameObject.SetActive(false); break; case ViewState.Body: ((Component)bodyContent).gameObject.SetActive(false); break; case ViewState.Buff: ((Component)buffContent).gameObject.SetActive(false); break; default: throw new ArgumentOutOfRangeException(); } switch (newState) { case ViewState.Main: mainContent.SetActive(true); break; case ViewState.Inventory: ((Component)itemContent).gameObject.SetActive(true); itemContent.Initialize(currentUser); break; case ViewState.Equipment: ((Component)equipmentContent).gameObject.SetActive(true); equipmentContent.Initialize(currentUser); break; case ViewState.Body: ((Component)bodyContent).gameObject.SetActive(true); bodyContent.Initialize(currentUser); break; case ViewState.Buff: ((Component)buffContent).gameObject.SetActive(true); buffContent.Initialize(currentUser); break; default: throw new ArgumentOutOfRangeException("newState", newState, null); } _state = newState; } public void KillAllMobs() { new KillAllTeamMessage((TeamIndex)1).SendToServer(); } public void SwapViewState() { SwapViewState(ViewState.Main); } } public static class NetworkManager { public static Type[] RegisteredMessages; public static void Initialize() { NetworkManagerSystem.onStartServerGlobal += RegisterMessages; NetworkManagerSystem.onStartClientGlobal += RegisterMessages; RegisteredMessages = (from x in typeof(AeroltMessageBase).Assembly.GetTypes() where typeof(AeroltMessageBase).IsAssignableFrom(x) && x != typeof(AeroltMessageBase) select x).ToArray(); } private static void RegisterMessages() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown NetworkServer.RegisterHandler((short)2004, new NetworkMessageDelegate(HandleMessage)); } public static void RegisterMessages(NetworkClient client) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown client.RegisterHandler((short)2004, new NetworkMessageDelegate(HandleMessage)); } private static void HandleMessage(NetworkMessage netmsg) { AeroltMessage aeroltMessage = netmsg.ReadMessage<AeroltMessage>(); if (aeroltMessage.message is BroadcastMessage broadcastMessage) { broadcastMessage.fromConnection = netmsg.conn; } aeroltMessage.message.Handle(); } public static void SendAerolt<T>(this NetworkConnection connection, T message) where T : AeroltMessageBase { AeroltMessage aeroltMessage = new AeroltMessage(message); connection.Send((short)2004, (MessageBase)(object)aeroltMessage); } } public class AeroltMessageBase : MessageBase { public virtual void Handle() { } public void SendToServer() { if (!NetworkServer.active) { ClientScene.readyConnection.SendAerolt(this); } else { Handle(); } } public void SendToEveryone() { Handle(); new BroadcastMessage(this).SendToServer(); } public void SendToAuthority(NetworkIdentity identity) { if (!Util.HasEffectiveAuthority(identity) && NetworkServer.active) { identity.clientAuthorityOwner.SendAerolt(this); } else if (!NetworkServer.active) { new NewAuthMessage(identity, this).SendToServer(); } else { Handle(); } } public void SendToAuthority(NetworkUser user) { SendToAuthority(((NetworkBehaviour)user).netIdentity); } public void SendToAuthority(CharacterMaster master) { SendToAuthority(master.networkIdentity); } public void SendToAuthority(CharacterBody body) { SendToAuthority(body.netwo
websocket-sharp.dll
Decompiled 6 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security.Authentication; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Permissions; using System.Security.Principal; using System.Text; using System.Threading; using System.Timers; using WebSocketSharp.Net; using WebSocketSharp.Net.WebSockets; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("websocket-sharp")] [assembly: AssemblyDescription("A C# implementation of the WebSocket protocol client and server")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("websocket-sharp.dll")] [assembly: AssemblyCopyright("sta.blockhead")] [assembly: AssemblyTrademark("")] [assembly: AssemblyVersion("1.0.2.30259")] namespace WebSocketSharp { public static class Ext { private static readonly byte[] _last = new byte[1]; private static readonly int _maxRetry = 5; private const string _tspecials = "()<>@,;:\\\"/[]?={} \t"; private static byte[] compress(this byte[] data) { if (data.LongLength == 0) { return data; } using MemoryStream stream = new MemoryStream(data); return stream.compressToArray(); } private static MemoryStream compress(this Stream stream) { MemoryStream memoryStream = new MemoryStream(); if (stream.Length == 0) { return memoryStream; } stream.Position = 0L; CompressionMode mode = CompressionMode.Compress; using DeflateStream deflateStream = new DeflateStream(memoryStream, mode, leaveOpen: true); CopyTo(stream, deflateStream, 1024); deflateStream.Close(); memoryStream.Write(_last, 0, 1); memoryStream.Position = 0L; return memoryStream; } private static byte[] compressToArray(this Stream stream) { using MemoryStream memoryStream = stream.compress(); memoryStream.Close(); return memoryStream.ToArray(); } private static byte[] decompress(this byte[] data) { if (data.LongLength == 0) { return data; } using MemoryStream stream = new MemoryStream(data); return stream.decompressToArray(); } private static MemoryStream decompress(this Stream stream) { MemoryStream memoryStream = new MemoryStream(); if (stream.Length == 0) { return memoryStream; } stream.Position = 0L; CompressionMode mode = CompressionMode.Decompress; using DeflateStream sourceStream = new DeflateStream(stream, mode, leaveOpen: true); CopyTo(sourceStream, memoryStream, 1024); memoryStream.Position = 0L; return memoryStream; } private static byte[] decompressToArray(this Stream stream) { using MemoryStream memoryStream = stream.decompress(); memoryStream.Close(); return memoryStream.ToArray(); } private static bool isPredefinedScheme(this string value) { switch (value[0]) { case 'h': return value == "http" || value == "https"; case 'w': return value == "ws" || value == "wss"; case 'f': return value == "file" || value == "ftp"; case 'g': return value == "gopher"; case 'm': return value == "mailto"; case 'n': { char c = value[1]; return (c != 'e') ? (value == "nntp") : (value == "news" || value == "net.pipe" || value == "net.tcp"); } default: return false; } } internal static byte[] Append(this ushort code, string reason) { byte[] array = code.ToByteArray(ByteOrder.Big); if (reason == null || reason.Length == 0) { return array; } List<byte> list = new List<byte>(array); byte[] bytes = Encoding.UTF8.GetBytes(reason); list.AddRange(bytes); return list.ToArray(); } internal static byte[] Compress(this byte[] data, CompressionMethod method) { return (method == CompressionMethod.Deflate) ? data.compress() : data; } internal static Stream Compress(this Stream stream, CompressionMethod method) { return (method == CompressionMethod.Deflate) ? stream.compress() : stream; } internal static bool Contains(this string value, params char[] anyOf) { return anyOf != null && anyOf.Length != 0 && value.IndexOfAny(anyOf) > -1; } internal static bool Contains(this NameValueCollection collection, string name) { return collection[name] != null; } internal static bool Contains(this NameValueCollection collection, string name, string value, StringComparison comparisonTypeForValue) { string text = collection[name]; if (text == null) { return false; } string[] array = text.Split(new char[1] { ',' }); foreach (string text2 in array) { if (text2.Trim().Equals(value, comparisonTypeForValue)) { return true; } } return false; } internal static bool Contains<T>(this IEnumerable<T> source, Func<T, bool> condition) { foreach (T item in source) { if (condition(item)) { return true; } } return false; } internal static bool ContainsTwice(this string[] values) { int len = values.Length; int end = len - 1; Func<int, bool> seek = null; seek = delegate(int idx) { if (idx == end) { return false; } string text = values[idx]; for (int i = idx + 1; i < len; i++) { if (values[i] == text) { return true; } } return seek(++idx); }; return seek(0); } internal static T[] Copy<T>(this T[] sourceArray, int length) { T[] array = new T[length]; Array.Copy(sourceArray, 0, array, 0, length); return array; } internal static T[] Copy<T>(this T[] sourceArray, long length) { T[] array = new T[length]; Array.Copy(sourceArray, 0L, array, 0L, length); return array; } internal static void CopyTo(this Stream sourceStream, Stream destinationStream, int bufferLength) { byte[] buffer = new byte[bufferLength]; while (true) { int num = sourceStream.Read(buffer, 0, bufferLength); if (num <= 0) { break; } destinationStream.Write(buffer, 0, num); } } internal static void CopyToAsync(this Stream sourceStream, Stream destinationStream, int bufferLength, Action completed, Action<Exception> error) { byte[] buff = new byte[bufferLength]; AsyncCallback callback = null; callback = delegate(IAsyncResult ar) { try { int num = sourceStream.EndRead(ar); if (num <= 0) { if (completed != null) { completed(); } } else { destinationStream.Write(buff, 0, num); sourceStream.BeginRead(buff, 0, bufferLength, callback, null); } } catch (Exception obj2) { if (error != null) { error(obj2); } } }; try { sourceStream.BeginRead(buff, 0, bufferLength, callback, null); } catch (Exception obj) { if (error != null) { error(obj); } } } internal static byte[] Decompress(this byte[] data, CompressionMethod method) { return (method == CompressionMethod.Deflate) ? data.decompress() : data; } internal static Stream Decompress(this Stream stream, CompressionMethod method) { return (method == CompressionMethod.Deflate) ? stream.decompress() : stream; } internal static byte[] DecompressToArray(this Stream stream, CompressionMethod method) { return (method == CompressionMethod.Deflate) ? stream.decompressToArray() : stream.ToByteArray(); } internal static void Emit(this EventHandler eventHandler, object sender, EventArgs e) { eventHandler?.Invoke(sender, e); } internal static void Emit<TEventArgs>(this EventHandler<TEventArgs> eventHandler, object sender, TEventArgs e) where TEventArgs : EventArgs { eventHandler?.Invoke(sender, e); } internal static string GetAbsolutePath(this Uri uri) { if (uri.IsAbsoluteUri) { return uri.AbsolutePath; } string originalString = uri.OriginalString; if (originalString[0] != '/') { return null; } int num = originalString.IndexOfAny(new char[2] { '?', '#' }); return (num > 0) ? originalString.Substring(0, num) : originalString; } internal static WebSocketSharp.Net.CookieCollection GetCookies(this NameValueCollection headers, bool response) { string text = headers[response ? "Set-Cookie" : "Cookie"]; return (text != null) ? WebSocketSharp.Net.CookieCollection.Parse(text, response) : new WebSocketSharp.Net.CookieCollection(); } internal static string GetDnsSafeHost(this Uri uri, bool bracketIPv6) { return (bracketIPv6 && uri.HostNameType == UriHostNameType.IPv6) ? uri.Host : uri.DnsSafeHost; } internal static string GetMessage(this CloseStatusCode code) { return code switch { CloseStatusCode.ProtocolError => "A protocol error has occurred.", CloseStatusCode.UnsupportedData => "Unsupported data has been received.", CloseStatusCode.Abnormal => "An abnormal error has occurred.", CloseStatusCode.InvalidData => "Invalid data has been received.", CloseStatusCode.PolicyViolation => "A policy violation has occurred.", CloseStatusCode.TooBig => "A too big message has been received.", CloseStatusCode.MandatoryExtension => "The client did not receive expected extension(s).", CloseStatusCode.ServerError => "The server got an internal error.", CloseStatusCode.TlsHandshakeFailure => "An error has occurred during a TLS handshake.", _ => string.Empty, }; } internal static string GetName(this string nameAndValue, char separator) { int num = nameAndValue.IndexOf(separator); return (num > 0) ? nameAndValue.Substring(0, num).Trim() : null; } internal static string GetUTF8DecodedString(this byte[] bytes) { return Encoding.UTF8.GetString(bytes); } internal static byte[] GetUTF8EncodedBytes(this string s) { return Encoding.UTF8.GetBytes(s); } internal static string GetValue(this string nameAndValue, char separator) { return nameAndValue.GetValue(separator, unquote: false); } internal static string GetValue(this string nameAndValue, char separator, bool unquote) { int num = nameAndValue.IndexOf(separator); if (num < 0 || num == nameAndValue.Length - 1) { return null; } string text = nameAndValue.Substring(num + 1).Trim(); return unquote ? text.Unquote() : text; } internal static bool IsCompressionExtension(this string value, CompressionMethod method) { string value2 = method.ToExtensionString(); StringComparison comparisonType = StringComparison.Ordinal; return value.StartsWith(value2, comparisonType); } internal static bool IsControl(this byte opcode) { return opcode > 7 && opcode < 16; } internal static bool IsControl(this Opcode opcode) { return (int)opcode >= 8; } internal static bool IsData(this byte opcode) { return opcode == 1 || opcode == 2; } internal static bool IsData(this Opcode opcode) { return opcode == Opcode.Text || opcode == Opcode.Binary; } internal static bool IsEqualTo(this int value, char c, Action<int> beforeComparing) { beforeComparing(value); return value == c; } internal static bool IsHttpMethod(this string value) { int result; switch (value) { default: result = ((value == "TRACE") ? 1 : 0); break; case "GET": case "HEAD": case "POST": case "PUT": case "DELETE": case "CONNECT": case "OPTIONS": result = 1; break; } return (byte)result != 0; } internal static bool IsPortNumber(this int value) { return value > 0 && value < 65536; } internal static bool IsReserved(this ushort code) { return code == 1004 || code == 1005 || code == 1006 || code == 1015; } internal static bool IsReserved(this CloseStatusCode code) { return code == CloseStatusCode.Undefined || code == CloseStatusCode.NoStatus || code == CloseStatusCode.Abnormal || code == CloseStatusCode.TlsHandshakeFailure; } internal static bool IsSupported(this byte opcode) { return Enum.IsDefined(typeof(Opcode), opcode); } internal static bool IsText(this string value) { int length = value.Length; for (int i = 0; i < length; i++) { char c = value[i]; if (c < ' ') { if ("\r\n\t".IndexOf(c) == -1) { return false; } if (c == '\n') { i++; if (i == length) { break; } c = value[i]; if (" \t".IndexOf(c) == -1) { return false; } } } else if (c == '\u007f') { return false; } } return true; } internal static bool IsToken(this string value) { foreach (char c in value) { if (c < ' ') { return false; } if (c > '~') { return false; } if ("()<>@,;:\\\"/[]?={} \t".IndexOf(c) > -1) { return false; } } return true; } internal static bool KeepsAlive(this NameValueCollection headers, Version version) { StringComparison comparisonTypeForValue = StringComparison.OrdinalIgnoreCase; return (version < WebSocketSharp.Net.HttpVersion.Version11) ? headers.Contains("Connection", "keep-alive", comparisonTypeForValue) : (!headers.Contains("Connection", "close", comparisonTypeForValue)); } internal static bool MaybeUri(this string value) { int num = value.IndexOf(':'); if (num < 2 || num > 9) { return false; } string value2 = value.Substring(0, num); return value2.isPredefinedScheme(); } internal static string Quote(this string value) { string format = "\"{0}\""; string arg = value.Replace("\"", "\\\""); return string.Format(format, arg); } internal static byte[] ReadBytes(this Stream stream, int length) { byte[] array = new byte[length]; int num = 0; int num2 = 0; while (length > 0) { int num3 = stream.Read(array, num, length); if (num3 <= 0) { if (num2 >= _maxRetry) { return array.SubArray(0, num); } num2++; } else { num2 = 0; num += num3; length -= num3; } } return array; } internal static byte[] ReadBytes(this Stream stream, long length, int bufferLength) { using MemoryStream memoryStream = new MemoryStream(); byte[] buffer = new byte[bufferLength]; int num = 0; while (length > 0) { if (length < bufferLength) { bufferLength = (int)length; } int num2 = stream.Read(buffer, 0, bufferLength); if (num2 <= 0) { if (num >= _maxRetry) { break; } num++; } else { num = 0; memoryStream.Write(buffer, 0, num2); length -= num2; } } memoryStream.Close(); return memoryStream.ToArray(); } internal static void ReadBytesAsync(this Stream stream, int length, Action<byte[]> completed, Action<Exception> error) { byte[] ret = new byte[length]; int offset = 0; int retry = 0; AsyncCallback callback = null; callback = delegate(IAsyncResult ar) { try { int num = stream.EndRead(ar); if (num <= 0) { if (retry < _maxRetry) { retry++; stream.BeginRead(ret, offset, length, callback, null); } else if (completed != null) { completed(ret.SubArray(0, offset)); } } else if (num == length) { if (completed != null) { completed(ret); } } else { retry = 0; offset += num; length -= num; stream.BeginRead(ret, offset, length, callback, null); } } catch (Exception obj2) { if (error != null) { error(obj2); } } }; try { stream.BeginRead(ret, offset, length, callback, null); } catch (Exception obj) { if (error != null) { error(obj); } } } internal static void ReadBytesAsync(this Stream stream, long length, int bufferLength, Action<byte[]> completed, Action<Exception> error) { MemoryStream dest = new MemoryStream(); byte[] buff = new byte[bufferLength]; int retry = 0; Action<long> read = null; read = delegate(long len) { if (len < bufferLength) { bufferLength = (int)len; } stream.BeginRead(buff, 0, bufferLength, delegate(IAsyncResult ar) { try { int num = stream.EndRead(ar); if (num <= 0) { if (retry < _maxRetry) { int num2 = retry; retry = num2 + 1; read(len); } else { if (completed != null) { dest.Close(); byte[] obj2 = dest.ToArray(); completed(obj2); } dest.Dispose(); } } else { dest.Write(buff, 0, num); if (num == len) { if (completed != null) { dest.Close(); byte[] obj3 = dest.ToArray(); completed(obj3); } dest.Dispose(); } else { retry = 0; read(len - num); } } } catch (Exception obj4) { dest.Dispose(); if (error != null) { error(obj4); } } }, null); }; try { read(length); } catch (Exception obj) { dest.Dispose(); if (error != null) { error(obj); } } } internal static T[] Reverse<T>(this T[] array) { long num = array.LongLength; T[] array2 = new T[num]; long num2 = num - 1; for (long num3 = 0L; num3 <= num2; num3++) { array2[num3] = array[num2 - num3]; } return array2; } internal static IEnumerable<string> SplitHeaderValue(this string value, params char[] separators) { int len = value.Length; int end = len - 1; StringBuilder buff = new StringBuilder(32); bool escaped = false; bool quoted = false; for (int i = 0; i <= end; i++) { char c = value[i]; buff.Append(c); switch (c) { case '"': if (escaped) { escaped = false; } else { quoted = !quoted; } continue; case '\\': if (i == end) { break; } if (value[i + 1] == '"') { escaped = true; } continue; default: if (Array.IndexOf(separators, c) > -1 && !quoted) { buff.Length--; yield return buff.ToString(); buff.Length = 0; } continue; } break; } yield return buff.ToString(); } internal static byte[] ToByteArray(this Stream stream) { stream.Position = 0L; using MemoryStream memoryStream = new MemoryStream(); CopyTo(stream, memoryStream, 1024); memoryStream.Close(); return memoryStream.ToArray(); } internal static byte[] ToByteArray(this ushort value, ByteOrder order) { byte[] bytes = BitConverter.GetBytes(value); if (!order.IsHostOrder()) { Array.Reverse((Array)bytes); } return bytes; } internal static byte[] ToByteArray(this ulong value, ByteOrder order) { byte[] bytes = BitConverter.GetBytes(value); if (!order.IsHostOrder()) { Array.Reverse((Array)bytes); } return bytes; } internal static CompressionMethod ToCompressionMethod(this string value) { Array values = Enum.GetValues(typeof(CompressionMethod)); foreach (CompressionMethod item in values) { if (item.ToExtensionString() == value) { return item; } } return CompressionMethod.None; } internal static string ToExtensionString(this CompressionMethod method, params string[] parameters) { if (method == CompressionMethod.None) { return string.Empty; } string arg = method.ToString().ToLower(); string text = $"permessage-{arg}"; if (parameters == null || parameters.Length == 0) { return text; } string arg2 = parameters.ToString("; "); return $"{text}; {arg2}"; } internal static int ToInt32(this string numericString) { return int.Parse(numericString); } internal static IPAddress ToIPAddress(this string value) { if (value == null || value.Length == 0) { return null; } if (IPAddress.TryParse(value, out IPAddress address)) { return address; } try { IPAddress[] hostAddresses = Dns.GetHostAddresses(value); return hostAddresses[0]; } catch { return null; } } internal static List<TSource> ToList<TSource>(this IEnumerable<TSource> source) { return new List<TSource>(source); } internal static string ToString(this IPAddress address, bool bracketIPv6) { return (bracketIPv6 && address.AddressFamily == AddressFamily.InterNetworkV6) ? $"[{address}]" : address.ToString(); } internal static ushort ToUInt16(this byte[] source, ByteOrder sourceOrder) { byte[] value = source.ToHostOrder(sourceOrder); return BitConverter.ToUInt16(value, 0); } internal static ulong ToUInt64(this byte[] source, ByteOrder sourceOrder) { byte[] value = source.ToHostOrder(sourceOrder); return BitConverter.ToUInt64(value, 0); } internal static Version ToVersion(this string versionString) { return new Version(versionString); } internal static IEnumerable<string> TrimEach(this IEnumerable<string> source) { foreach (string elm in source) { yield return elm.Trim(); } } internal static string TrimSlashFromEnd(this string value) { string text = value.TrimEnd(new char[1] { '/' }); return (text.Length > 0) ? text : "/"; } internal static string TrimSlashOrBackslashFromEnd(this string value) { string text = value.TrimEnd('/', '\\'); return (text.Length > 0) ? text : value[0].ToString(); } internal static bool TryCreateVersion(this string versionString, out Version result) { result = null; try { result = new Version(versionString); } catch { return false; } return true; } internal static bool TryCreateWebSocketUri(this string uriString, out Uri result, out string message) { result = null; message = null; Uri uri = uriString.ToUri(); if (uri == null) { message = "An invalid URI string."; return false; } if (!uri.IsAbsoluteUri) { message = "A relative URI."; return false; } string scheme = uri.Scheme; if (!(scheme == "ws") && !(scheme == "wss")) { message = "The scheme part is not 'ws' or 'wss'."; return false; } int port = uri.Port; if (port == 0) { message = "The port part is zero."; return false; } if (uri.Fragment.Length > 0) { message = "It includes the fragment component."; return false; } if (port == -1) { port = ((scheme == "ws") ? 80 : 443); uriString = $"{scheme}://{uri.Host}:{port}{uri.PathAndQuery}"; result = new Uri(uriString); } else { result = uri; } return true; } internal static bool TryGetUTF8DecodedString(this byte[] bytes, out string s) { s = null; try { s = Encoding.UTF8.GetString(bytes); } catch { return false; } return true; } internal static bool TryGetUTF8EncodedBytes(this string s, out byte[] bytes) { bytes = null; try { bytes = Encoding.UTF8.GetBytes(s); } catch { return false; } return true; } internal static bool TryOpenRead(this FileInfo fileInfo, out FileStream fileStream) { fileStream = null; try { fileStream = fileInfo.OpenRead(); } catch { return false; } return true; } internal static string Unquote(this string value) { int num = value.IndexOf('"'); if (num == -1) { return value; } int num2 = value.LastIndexOf('"'); if (num2 == num) { return value; } int num3 = num2 - num - 1; return (num3 > 0) ? value.Substring(num + 1, num3).Replace("\\\"", "\"") : string.Empty; } internal static bool Upgrades(this NameValueCollection headers, string protocol) { StringComparison comparisonTypeForValue = StringComparison.OrdinalIgnoreCase; return headers.Contains("Upgrade", protocol, comparisonTypeForValue) && headers.Contains("Connection", "Upgrade", comparisonTypeForValue); } internal static string UrlDecode(this string value, Encoding encoding) { return (value.IndexOfAny(new char[2] { '%', '+' }) > -1) ? HttpUtility.UrlDecode(value, encoding) : value; } internal static string UrlEncode(this string value, Encoding encoding) { return HttpUtility.UrlEncode(value, encoding); } internal static void WriteBytes(this Stream stream, byte[] bytes, int bufferLength) { using MemoryStream sourceStream = new MemoryStream(bytes); CopyTo(sourceStream, stream, bufferLength); } internal static void WriteBytesAsync(this Stream stream, byte[] bytes, int bufferLength, Action completed, Action<Exception> error) { MemoryStream src = new MemoryStream(bytes); src.CopyToAsync(stream, bufferLength, delegate { if (completed != null) { completed(); } src.Dispose(); }, delegate(Exception ex) { src.Dispose(); if (error != null) { error(ex); } }); } public static string GetDescription(this WebSocketSharp.Net.HttpStatusCode code) { return ((int)code).GetStatusDescription(); } public static string GetStatusDescription(this int code) { return code switch { 100 => "Continue", 101 => "Switching Protocols", 102 => "Processing", 200 => "OK", 201 => "Created", 202 => "Accepted", 203 => "Non-Authoritative Information", 204 => "No Content", 205 => "Reset Content", 206 => "Partial Content", 207 => "Multi-Status", 300 => "Multiple Choices", 301 => "Moved Permanently", 302 => "Found", 303 => "See Other", 304 => "Not Modified", 305 => "Use Proxy", 307 => "Temporary Redirect", 400 => "Bad Request", 401 => "Unauthorized", 402 => "Payment Required", 403 => "Forbidden", 404 => "Not Found", 405 => "Method Not Allowed", 406 => "Not Acceptable", 407 => "Proxy Authentication Required", 408 => "Request Timeout", 409 => "Conflict", 410 => "Gone", 411 => "Length Required", 412 => "Precondition Failed", 413 => "Request Entity Too Large", 414 => "Request-Uri Too Long", 415 => "Unsupported Media Type", 416 => "Requested Range Not Satisfiable", 417 => "Expectation Failed", 422 => "Unprocessable Entity", 423 => "Locked", 424 => "Failed Dependency", 500 => "Internal Server Error", 501 => "Not Implemented", 502 => "Bad Gateway", 503 => "Service Unavailable", 504 => "Gateway Timeout", 505 => "Http Version Not Supported", 507 => "Insufficient Storage", _ => string.Empty, }; } public static bool IsCloseStatusCode(this ushort value) { return value > 999 && value < 5000; } public static bool IsEnclosedIn(this string value, char c) { if (value == null) { return false; } int length = value.Length; return length > 1 && value[0] == c && value[length - 1] == c; } public static bool IsHostOrder(this ByteOrder order) { return BitConverter.IsLittleEndian == (order == ByteOrder.Little); } public static bool IsLocal(this IPAddress address) { if (address == null) { throw new ArgumentNullException("address"); } if (address.Equals(IPAddress.Any)) { return true; } if (address.Equals(IPAddress.Loopback)) { return true; } if (Socket.OSSupportsIPv6) { if (address.Equals(IPAddress.IPv6Any)) { return true; } if (address.Equals(IPAddress.IPv6Loopback)) { return true; } } string hostName = Dns.GetHostName(); IPAddress[] hostAddresses = Dns.GetHostAddresses(hostName); IPAddress[] array = hostAddresses; foreach (IPAddress obj in array) { if (address.Equals(obj)) { return true; } } return false; } public static bool IsNullOrEmpty(this string value) { return value == null || value.Length == 0; } public static T[] SubArray<T>(this T[] array, int startIndex, int length) { if (array == null) { throw new ArgumentNullException("array"); } int num = array.Length; if (num == 0) { if (startIndex != 0) { throw new ArgumentOutOfRangeException("startIndex"); } if (length != 0) { throw new ArgumentOutOfRangeException("length"); } return array; } if (startIndex < 0 || startIndex >= num) { throw new ArgumentOutOfRangeException("startIndex"); } if (length < 0 || length > num - startIndex) { throw new ArgumentOutOfRangeException("length"); } if (length == 0) { return new T[0]; } if (length == num) { return array; } T[] array2 = new T[length]; Array.Copy(array, startIndex, array2, 0, length); return array2; } public static T[] SubArray<T>(this T[] array, long startIndex, long length) { if (array == null) { throw new ArgumentNullException("array"); } long num = array.LongLength; if (num == 0) { if (startIndex != 0) { throw new ArgumentOutOfRangeException("startIndex"); } if (length != 0) { throw new ArgumentOutOfRangeException("length"); } return array; } if (startIndex < 0 || startIndex >= num) { throw new ArgumentOutOfRangeException("startIndex"); } if (length < 0 || length > num - startIndex) { throw new ArgumentOutOfRangeException("length"); } if (length == 0) { return new T[0]; } if (length == num) { return array; } T[] array2 = new T[length]; Array.Copy(array, startIndex, array2, 0L, length); return array2; } public static void Times(this int n, Action<int> action) { if (n > 0 && action != null) { for (int i = 0; i < n; i++) { action(i); } } } public static void Times(this long n, Action<long> action) { if (n > 0 && action != null) { for (long num = 0L; num < n; num++) { action(num); } } } public static byte[] ToHostOrder(this byte[] source, ByteOrder sourceOrder) { if (source == null) { throw new ArgumentNullException("source"); } if (source.Length < 2) { return source; } if (sourceOrder.IsHostOrder()) { return source; } return source.Reverse(); } public static string ToString<T>(this T[] array, string separator) { if (array == null) { throw new ArgumentNullException("array"); } int num = array.Length; if (num == 0) { return string.Empty; } StringBuilder stringBuilder = new StringBuilder(64); int num2 = num - 1; for (int i = 0; i < num2; i++) { stringBuilder.AppendFormat("{0}{1}", array[i], separator); } stringBuilder.AppendFormat("{0}", array[num2]); return stringBuilder.ToString(); } public static Uri ToUri(this string value) { if (value == null || value.Length == 0) { return null; } UriKind uriKind = (value.MaybeUri() ? UriKind.Absolute : UriKind.Relative); Uri.TryCreate(value, uriKind, out Uri result); return result; } } public class MessageEventArgs : EventArgs { private string _data; private bool _dataSet; private Opcode _opcode; private byte[] _rawData; internal Opcode Opcode => _opcode; public string Data { get { setData(); return _data; } } public bool IsBinary => _opcode == Opcode.Binary; public bool IsPing => _opcode == Opcode.Ping; public bool IsText => _opcode == Opcode.Text; public byte[] RawData { get { setData(); return _rawData; } } internal MessageEventArgs(WebSocketFrame frame) { _opcode = frame.Opcode; _rawData = frame.PayloadData.ApplicationData; } internal MessageEventArgs(Opcode opcode, byte[] rawData) { if ((ulong)rawData.LongLength > PayloadData.MaxLength) { throw new WebSocketException(CloseStatusCode.TooBig); } _opcode = opcode; _rawData = rawData; } private void setData() { if (_dataSet) { return; } if (_opcode == Opcode.Binary) { _dataSet = true; return; } if (_rawData.TryGetUTF8DecodedString(out var s)) { _data = s; } _dataSet = true; } } public class CloseEventArgs : EventArgs { private bool _clean; private PayloadData _payloadData; public ushort Code => _payloadData.Code; public string Reason => _payloadData.Reason; public bool WasClean => _clean; internal CloseEventArgs(PayloadData payloadData, bool clean) { _payloadData = payloadData; _clean = clean; } internal CloseEventArgs(ushort code, string reason, bool clean) { _payloadData = new PayloadData(code, reason); _clean = clean; } } public enum ByteOrder { Little, Big } public class ErrorEventArgs : EventArgs { private Exception _exception; private string _message; public Exception Exception => _exception; public string Message => _message; internal ErrorEventArgs(string message) : this(message, null) { } internal ErrorEventArgs(string message, Exception exception) { _message = message; _exception = exception; } } public class WebSocket : IDisposable { private AuthenticationChallenge _authChallenge; private string _base64Key; private bool _client; private Action _closeContext; private CompressionMethod _compression; private WebSocketContext _context; private WebSocketSharp.Net.CookieCollection _cookies; private WebSocketSharp.Net.NetworkCredential _credentials; private bool _emitOnPing; private bool _enableRedirection; private string _extensions; private bool _extensionsRequested; private object _forMessageEventQueue; private object _forPing; private object _forSend; private object _forState; private MemoryStream _fragmentsBuffer; private bool _fragmentsCompressed; private Opcode _fragmentsOpcode; private const string _guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; private Func<WebSocketContext, string> _handshakeRequestChecker; private bool _ignoreExtensions; private bool _inContinuation; private volatile bool _inMessage; private volatile Logger _logger; private static readonly int _maxRetryCountForConnect; private Action<MessageEventArgs> _message; private Queue<MessageEventArgs> _messageEventQueue; private uint _nonceCount; private string _origin; private ManualResetEvent _pongReceived; private bool _preAuth; private string _protocol; private string[] _protocols; private bool _protocolsRequested; private WebSocketSharp.Net.NetworkCredential _proxyCredentials; private Uri _proxyUri; private volatile WebSocketState _readyState; private ManualResetEvent _receivingExited; private int _retryCountForConnect; private bool _secure; private ClientSslConfiguration _sslConfig; private Stream _stream; private TcpClient _tcpClient; private Uri _uri; private const string _version = "13"; private TimeSpan _waitTime; internal static readonly byte[] EmptyBytes; internal static readonly int FragmentLength; internal static readonly RandomNumberGenerator RandomNumber; internal WebSocketSharp.Net.CookieCollection CookieCollection => _cookies; internal Func<WebSocketContext, string> CustomHandshakeRequestChecker { get { return _handshakeRequestChecker; } set { _handshakeRequestChecker = value; } } internal bool HasMessage { get { lock (_forMessageEventQueue) { return _messageEventQueue.Count > 0; } } } internal bool IgnoreExtensions { get { return _ignoreExtensions; } set { _ignoreExtensions = value; } } internal bool IsConnected => _readyState == WebSocketState.Open || _readyState == WebSocketState.Closing; public CompressionMethod Compression { get { return _compression; } set { string text = null; if (!_client) { text = "This instance is not a client."; throw new InvalidOperationException(text); } if (!canSet(out text)) { _logger.Warn(text); return; } lock (_forState) { if (!canSet(out text)) { _logger.Warn(text); } else { _compression = value; } } } } public IEnumerable<WebSocketSharp.Net.Cookie> Cookies { get { lock (_cookies.SyncRoot) { foreach (WebSocketSharp.Net.Cookie cookie in _cookies) { yield return cookie; } } } } public WebSocketSharp.Net.NetworkCredential Credentials => _credentials; public bool EmitOnPing { get { return _emitOnPing; } set { _emitOnPing = value; } } public bool EnableRedirection { get { return _enableRedirection; } set { string text = null; if (!_client) { text = "This instance is not a client."; throw new InvalidOperationException(text); } if (!canSet(out text)) { _logger.Warn(text); return; } lock (_forState) { if (!canSet(out text)) { _logger.Warn(text); } else { _enableRedirection = value; } } } } public string Extensions => _extensions ?? string.Empty; public bool IsAlive => ping(EmptyBytes); public bool IsSecure => _secure; public Logger Log { get { return _logger; } internal set { _logger = value; } } public string Origin { get { return _origin; } set { string text = null; if (!_client) { text = "This instance is not a client."; throw new InvalidOperationException(text); } if (!value.IsNullOrEmpty()) { if (!Uri.TryCreate(value, UriKind.Absolute, out Uri result)) { text = "Not an absolute URI string."; throw new ArgumentException(text, "value"); } if (result.Segments.Length > 1) { text = "It includes the path segments."; throw new ArgumentException(text, "value"); } } if (!canSet(out text)) { _logger.Warn(text); return; } lock (_forState) { if (!canSet(out text)) { _logger.Warn(text); return; } _origin = ((!value.IsNullOrEmpty()) ? value.TrimEnd(new char[1] { '/' }) : value); } } } public string Protocol { get { return _protocol ?? string.Empty; } internal set { _protocol = value; } } public WebSocketState ReadyState => _readyState; public ClientSslConfiguration SslConfiguration { get { if (!_client) { string text = "This instance is not a client."; throw new InvalidOperationException(text); } if (!_secure) { string text2 = "This instance does not use a secure connection."; throw new InvalidOperationException(text2); } return getSslConfiguration(); } } public Uri Url => _client ? _uri : _context.RequestUri; public TimeSpan WaitTime { get { return _waitTime; } set { if (value <= TimeSpan.Zero) { throw new ArgumentOutOfRangeException("value", "Zero or less."); } if (!canSet(out var text)) { _logger.Warn(text); return; } lock (_forState) { if (!canSet(out text)) { _logger.Warn(text); } else { _waitTime = value; } } } } public event EventHandler<CloseEventArgs> OnClose; public event EventHandler<ErrorEventArgs> OnError; public event EventHandler<MessageEventArgs> OnMessage; public event EventHandler OnOpen; static WebSocket() { _maxRetryCountForConnect = 10; EmptyBytes = new byte[0]; FragmentLength = 1016; RandomNumber = new RNGCryptoServiceProvider(); } internal WebSocket(HttpListenerWebSocketContext context, string protocol) { _context = context; _protocol = protocol; _closeContext = context.Close; _logger = context.Log; _message = messages; _secure = context.IsSecureConnection; _stream = context.Stream; _waitTime = TimeSpan.FromSeconds(1.0); init(); } internal WebSocket(TcpListenerWebSocketContext context, string protocol) { _context = context; _protocol = protocol; _closeContext = context.Close; _logger = context.Log; _message = messages; _secure = context.IsSecureConnection; _stream = context.Stream; _waitTime = TimeSpan.FromSeconds(1.0); init(); } public WebSocket(string url, params string[] protocols) { if (url == null) { throw new ArgumentNullException("url"); } if (url.Length == 0) { throw new ArgumentException("An empty string.", "url"); } if (!url.TryCreateWebSocketUri(out _uri, out var text)) { throw new ArgumentException(text, "url"); } if (protocols != null && protocols.Length != 0) { if (!checkProtocols(protocols, out text)) { throw new ArgumentException(text, "protocols"); } _protocols = protocols; } _base64Key = CreateBase64Key(); _client = true; _logger = new Logger(); _message = messagec; _secure = _uri.Scheme == "wss"; _waitTime = TimeSpan.FromSeconds(5.0); init(); } private bool accept() { if (_readyState == WebSocketState.Open) { string text = "The handshake request has already been accepted."; _logger.Warn(text); return false; } lock (_forState) { if (_readyState == WebSocketState.Open) { string text2 = "The handshake request has already been accepted."; _logger.Warn(text2); return false; } if (_readyState == WebSocketState.Closing) { string text3 = "The close process has set in."; _logger.Error(text3); text3 = "An interruption has occurred while attempting to accept."; error(text3, null); return false; } if (_readyState == WebSocketState.Closed) { string text4 = "The connection has been closed."; _logger.Error(text4); text4 = "An interruption has occurred while attempting to accept."; error(text4, null); return false; } try { if (!acceptHandshake()) { return false; } } catch (Exception ex) { _logger.Fatal(ex.Message); _logger.Debug(ex.ToString()); string text5 = "An exception has occurred while attempting to accept."; fatal(text5, ex); return false; } _readyState = WebSocketState.Open; return true; } } private bool acceptHandshake() { string format = "A handshake request from {0}:\n{1}"; string text = string.Format(format, _context.UserEndPoint, _context); _logger.Debug(text); if (!checkHandshakeRequest(_context, out text)) { _logger.Error(text); string reason = "A handshake error has occurred while attempting to accept."; refuseHandshake(CloseStatusCode.ProtocolError, reason); return false; } if (!customCheckHandshakeRequest(_context, out text)) { _logger.Error(text); string reason2 = "A handshake error has occurred while attempting to accept."; refuseHandshake(CloseStatusCode.PolicyViolation, reason2); return false; } _base64Key = _context.Headers["Sec-WebSocket-Key"]; if (_protocol != null) { IEnumerable<string> secWebSocketProtocols = _context.SecWebSocketProtocols; processSecWebSocketProtocolClientHeader(secWebSocketProtocols); } if (!_ignoreExtensions) { string value = _context.Headers["Sec-WebSocket-Extensions"]; processSecWebSocketExtensionsClientHeader(value); } HttpResponse response = createHandshakeResponse(); return sendHttpResponse(response); } private bool canSet(out string message) { message = null; if (_readyState == WebSocketState.Open) { message = "The connection has already been established."; return false; } if (_readyState == WebSocketState.Closing) { message = "The connection is closing."; return false; } return true; } private bool checkHandshakeRequest(WebSocketContext context, out string message) { message = null; if (!context.IsWebSocketRequest) { message = "Not a WebSocket handshake request."; return false; } if (context.RequestUri == null) { message = "The Request-URI is invalid."; return false; } NameValueCollection headers = context.Headers; string text = headers["Sec-WebSocket-Key"]; if (text == null) { message = "The Sec-WebSocket-Key header is non-existent."; return false; } if (text.Length == 0) { message = "The Sec-WebSocket-Key header is invalid."; return false; } string text2 = headers["Sec-WebSocket-Version"]; if (text2 == null) { message = "The Sec-WebSocket-Version header is non-existent."; return false; } if (text2 != "13") { message = "The Sec-WebSocket-Version header is invalid."; return false; } string text3 = headers["Sec-WebSocket-Protocol"]; if (text3 != null && text3.Length == 0) { message = "The Sec-WebSocket-Protocol header is invalid."; return false; } if (!_ignoreExtensions) { string text4 = headers["Sec-WebSocket-Extensions"]; if (text4 != null && text4.Length == 0) { message = "The Sec-WebSocket-Extensions header is invalid."; return false; } } return true; } private bool checkHandshakeResponse(HttpResponse response, out string message) { message = null; if (response.IsRedirect) { message = "The redirection is indicated."; return false; } if (response.IsUnauthorized) { message = "The authentication is required."; return false; } if (!response.IsWebSocketResponse) { message = "Not a WebSocket handshake response."; return false; } NameValueCollection headers = response.Headers; string text = headers["Sec-WebSocket-Accept"]; if (text == null) { message = "The Sec-WebSocket-Accept header is non-existent."; return false; } if (text != CreateResponseKey(_base64Key)) { message = "The Sec-WebSocket-Accept header is invalid."; return false; } string text2 = headers["Sec-WebSocket-Version"]; if (text2 != null && text2 != "13") { message = "The Sec-WebSocket-Version header is invalid."; return false; } string subp = headers["Sec-WebSocket-Protocol"]; if (subp == null) { if (_protocolsRequested) { message = "The Sec-WebSocket-Protocol header is non-existent."; return false; } } else if (subp.Length <= 0 || !_protocolsRequested || !_protocols.Contains((string p) => p == subp)) { message = "The Sec-WebSocket-Protocol header is invalid."; return false; } string value = headers["Sec-WebSocket-Extensions"]; if (!validateSecWebSocketExtensionsServerHeader(value)) { message = "The Sec-WebSocket-Extensions header is invalid."; return false; } return true; } private static bool checkProtocols(string[] protocols, out string message) { message = null; Func<string, bool> condition = (string protocol) => protocol.IsNullOrEmpty() || !protocol.IsToken(); if (protocols.Contains(condition)) { message = "It contains a value that is not a token."; return false; } if (protocols.ContainsTwice()) { message = "It contains a value twice."; return false; } return true; } private bool checkReceivedFrame(WebSocketFrame frame, out string message) { message = null; bool isMasked = frame.IsMasked; if (_client && isMasked) { message = "A frame from the server is masked."; return false; } if (!_client && !isMasked) { message = "A frame from a client is not masked."; return false; } if (_inContinuation && frame.IsData) { message = "A data frame has been received while receiving continuation frames."; return false; } if (frame.IsCompressed && _compression == CompressionMethod.None) { message = "A compressed frame has been received without any agreement for it."; return false; } if (frame.Rsv2 == Rsv.On) { message = "The RSV2 of a frame is non-zero without any negotiation for it."; return false; } if (frame.Rsv3 == Rsv.On) { message = "The RSV3 of a frame is non-zero without any negotiation for it."; return false; } return true; } private void close(ushort code, string reason) { if (_readyState == WebSocketState.Closing) { _logger.Info("The closing is already in progress."); return; } if (_readyState == WebSocketState.Closed) { _logger.Info("The connection has already been closed."); return; } if (code == 1005) { close(PayloadData.Empty, send: true, receive: true, received: false); return; } bool receive = !code.IsReserved(); close(new PayloadData(code, reason), receive, receive, received: false); } private void close(PayloadData payloadData, bool send, bool receive, bool received) { lock (_forState) { if (_readyState == WebSocketState.Closing) { _logger.Info("The closing is already in progress."); return; } if (_readyState == WebSocketState.Closed) { _logger.Info("The connection has already been closed."); return; } send = send && _readyState == WebSocketState.Open; receive = send && receive; _readyState = WebSocketState.Closing; } _logger.Trace("Begin closing the connection."); bool clean = closeHandshake(payloadData, send, receive, received); releaseResources(); _logger.Trace("End closing the connection."); _readyState = WebSocketState.Closed; CloseEventArgs e = new CloseEventArgs(payloadData, clean); try { this.OnClose.Emit(this, e); } catch (Exception ex) { _logger.Error(ex.Message); _logger.Debug(ex.ToString()); } } private void closeAsync(ushort code, string reason) { if (_readyState == WebSocketState.Closing) { _logger.Info("The closing is already in progress."); return; } if (_readyState == WebSocketState.Closed) { _logger.Info("The connection has already been closed."); return; } if (code == 1005) { closeAsync(PayloadData.Empty, send: true, receive: true, received: false); return; } bool receive = !code.IsReserved(); closeAsync(new PayloadData(code, reason), receive, receive, received: false); } private void closeAsync(PayloadData payloadData, bool send, bool receive, bool received) { Action<PayloadData, bool, bool, bool> closer = close; closer.BeginInvoke(payloadData, send, receive, received, delegate(IAsyncResult ar) { closer.EndInvoke(ar); }, null); } private bool closeHandshake(byte[] frameAsBytes, bool receive, bool received) { bool flag = frameAsBytes != null && sendBytes(frameAsBytes); if (!received && flag && receive && _receivingExited != null) { received = _receivingExited.WaitOne(_waitTime); } bool flag2 = flag && received; _logger.Debug($"Was clean?: {flag2}\n sent: {flag}\n received: {received}"); return flag2; } private bool closeHandshake(PayloadData payloadData, bool send, bool receive, bool received) { bool flag = false; if (send) { WebSocketFrame webSocketFrame = WebSocketFrame.CreateCloseFrame(payloadData, _client); flag = sendBytes(webSocketFrame.ToArray()); if (_client) { webSocketFrame.Unmask(); } } if (!received && flag && receive && _receivingExited != null) { received = _receivingExited.WaitOne(_waitTime); } bool flag2 = flag && received; _logger.Debug($"Was clean?: {flag2}\n sent: {flag}\n received: {received}"); return flag2; } private bool connect() { if (_readyState == WebSocketState.Open) { string text = "The connection has already been established."; _logger.Warn(text); return false; } lock (_forState) { if (_readyState == WebSocketState.Open) { string text2 = "The connection has already been established."; _logger.Warn(text2); return false; } if (_readyState == WebSocketState.Closing) { string text3 = "The close process has set in."; _logger.Error(text3); text3 = "An interruption has occurred while attempting to connect."; error(text3, null); return false; } if (_retryCountForConnect > _maxRetryCountForConnect) { string text4 = "An opportunity for reconnecting has been lost."; _logger.Error(text4); text4 = "An interruption has occurred while attempting to connect."; error(text4, null); return false; } _readyState = WebSocketState.Connecting; try { doHandshake(); } catch (Exception ex) { _retryCountForConnect++; _logger.Fatal(ex.Message); _logger.Debug(ex.ToString()); string text5 = "An exception has occurred while attempting to connect."; fatal(text5, ex); return false; } _retryCountForConnect = 1; _readyState = WebSocketState.Open; return true; } } private AuthenticationResponse createAuthenticationResponse() { if (_credentials == null) { return null; } if (_authChallenge != null) { AuthenticationResponse authenticationResponse = new AuthenticationResponse(_authChallenge, _credentials, _nonceCount); _nonceCount = authenticationResponse.NonceCount; return authenticationResponse; } return _preAuth ? new AuthenticationResponse(_credentials) : null; } private string createExtensions() { StringBuilder stringBuilder = new StringBuilder(80); if (_compression != 0) { string arg = _compression.ToExtensionString("server_no_context_takeover", "client_no_context_takeover"); stringBuilder.AppendFormat("{0}, ", arg); } int length = stringBuilder.Length; if (length <= 2) { return null; } stringBuilder.Length = length - 2; return stringBuilder.ToString(); } private HttpResponse createHandshakeFailureResponse(WebSocketSharp.Net.HttpStatusCode code) { HttpResponse httpResponse = HttpResponse.CreateCloseResponse(code); httpResponse.Headers["Sec-WebSocket-Version"] = "13"; return httpResponse; } private HttpRequest createHandshakeRequest() { HttpRequest httpRequest = HttpRequest.CreateWebSocketHandshakeRequest(_uri); NameValueCollection headers = httpRequest.Headers; headers["Sec-WebSocket-Key"] = _base64Key; headers["Sec-WebSocket-Version"] = "13"; if (!_origin.IsNullOrEmpty()) { headers["Origin"] = _origin; } if (_protocols != null) { headers["Sec-WebSocket-Protocol"] = _protocols.ToString(", "); _protocolsRequested = true; } string text = createExtensions(); if (text != null) { headers["Sec-WebSocket-Extensions"] = text; _extensionsRequested = true; } AuthenticationResponse authenticationResponse = createAuthenticationResponse(); if (authenticationResponse != null) { headers["Authorization"] = authenticationResponse.ToString(); } if (_cookies.Count > 0) { httpRequest.SetCookies(_cookies); } return httpRequest; } private HttpResponse createHandshakeResponse() { HttpResponse httpResponse = HttpResponse.CreateWebSocketHandshakeResponse(); NameValueCollection headers = httpResponse.Headers; headers["Sec-WebSocket-Accept"] = CreateResponseKey(_base64Key); if (_protocol != null) { headers["Sec-WebSocket-Protocol"] = _protocol; } if (_extensions != null) { headers["Sec-WebSocket-Extensions"] = _extensions; } if (_cookies.Count > 0) { httpResponse.SetCookies(_cookies); } return httpResponse; } private bool customCheckHandshakeRequest(WebSocketContext context, out string message) { message = null; if (_handshakeRequestChecker == null) { return true; } message = _handshakeRequestChecker(context); return message == null; } private MessageEventArgs dequeueFromMessageEventQueue() { lock (_forMessageEventQueue) { return (_messageEventQueue.Count > 0) ? _messageEventQueue.Dequeue() : null; } } private void doHandshake() { setClientStream(); HttpResponse httpResponse = sendHandshakeRequest(); if (!checkHandshakeResponse(httpResponse, out var text)) { throw new WebSocketException(CloseStatusCode.ProtocolError, text); } if (_protocolsRequested) { _protocol = httpResponse.Headers["Sec-WebSocket-Protocol"]; } if (_extensionsRequested) { string value = httpResponse.Headers["Sec-WebSocket-Extensions"]; processSecWebSocketExtensionsServerHeader(value); } processCookies(httpResponse.Cookies); } private void enqueueToMessageEventQueue(MessageEventArgs e) { lock (_forMessageEventQueue) { _messageEventQueue.Enqueue(e); } } private void error(string message, Exception exception) { try { this.OnError.Emit(this, new ErrorEventArgs(message, exception)); } catch (Exception ex) { _logger.Error(ex.Message); _logger.Debug(ex.ToString()); } } private void fatal(string message, Exception exception) { CloseStatusCode code = ((exception is WebSocketException) ? ((WebSocketException)exception).Code : CloseStatusCode.Abnormal); fatal(message, (ushort)code); } private void fatal(string message, ushort code) { PayloadData payloadData = new PayloadData(code, message); close(payloadData, !code.IsReserved(), receive: false, received: false); } private void fatal(string message, CloseStatusCode code) { fatal(message, (ushort)code); } private ClientSslConfiguration getSslConfiguration() { if (_sslConfig == null) { _sslConfig = new ClientSslConfiguration(_uri.DnsSafeHost); } return _sslConfig; } private void init() { _compression = CompressionMethod.None; _cookies = new WebSocketSharp.Net.CookieCollection(); _forPing = new object(); _forSend = new object(); _forState = new object(); _messageEventQueue = new Queue<MessageEventArgs>(); _forMessageEventQueue = ((ICollection)_messageEventQueue).SyncRoot; _readyState = WebSocketState.Connecting; } private void message() { MessageEventArgs obj = null; lock (_forMessageEventQueue) { if (_inMessage || _messageEventQueue.Count == 0 || _readyState != WebSocketState.Open) { return; } _inMessage = true; obj = _messageEventQueue.Dequeue(); } _message(obj); } private void messagec(MessageEventArgs e) { while (true) { try { this.OnMessage.Emit(this, e); } catch (Exception ex) { _logger.Error(ex.ToString()); error("An error has occurred during an OnMessage event.", ex); } lock (_forMessageEventQueue) { if (_messageEventQueue.Count == 0 || _readyState != WebSocketState.Open) { _inMessage = false; break; } e = _messageEventQueue.Dequeue(); } bool flag = true; } } private void messages(MessageEventArgs e) { try { this.OnMessage.Emit(this, e); } catch (Exception ex) { _logger.Error(ex.ToString()); error("An error has occurred during an OnMessage event.", ex); } lock (_forMessageEventQueue) { if (_messageEventQueue.Count == 0 || _readyState != WebSocketState.Open) { _inMessage = false; return; } e = _messageEventQueue.Dequeue(); } ThreadPool.QueueUserWorkItem(delegate { messages(e); }); } private void open() { _inMessage = true; startReceiving(); try { this.OnOpen.Emit(this, EventArgs.Empty); } catch (Exception ex) { _logger.Error(ex.ToString()); error("An error has occurred during the OnOpen event.", ex); } MessageEventArgs obj = null; lock (_forMessageEventQueue) { if (_messageEventQueue.Count == 0 || _readyState != WebSocketState.Open) { _inMessage = false; return; } obj = _messageEventQueue.Dequeue(); } _message.BeginInvoke(obj, delegate(IAsyncResult ar) { _message.EndInvoke(ar); }, null); } private bool ping(byte[] data) { if (_readyState != WebSocketState.Open) { return false; } ManualResetEvent pongReceived = _pongReceived; if (pongReceived == null) { return false; } lock (_forPing) { try { pongReceived.Reset(); if (!send(Fin.Final, Opcode.Ping, data, compressed: false)) { return false; } return pongReceived.WaitOne(_waitTime); } catch (ObjectDisposedException) { return false; } } } private bool processCloseFrame(WebSocketFrame frame) { PayloadData payloadData = frame.PayloadData; close(payloadData, !payloadData.HasReservedCode, receive: false, received: true); return false; } private void processCookies(WebSocketSharp.Net.CookieCollection cookies) { if (cookies.Count != 0) { _cookies.SetOrRemove(cookies); } } private bool processDataFrame(WebSocketFrame frame) { enqueueToMessageEventQueue(frame.IsCompressed ? new MessageEventArgs(frame.Opcode, frame.PayloadData.ApplicationData.Decompress(_compression)) : new MessageEventArgs(frame)); return true; } private bool processFragmentFrame(WebSocketFrame frame) { if (!_inContinuation) { if (frame.IsContinuation) { return true; } _fragmentsOpcode = frame.Opcode; _fragmentsCompressed = frame.IsCompressed; _fragmentsBuffer = new MemoryStream(); _inContinuation = true; } _fragmentsBuffer.WriteBytes(frame.PayloadData.ApplicationData, 1024); if (frame.IsFinal) { using (_fragmentsBuffer) { byte[] rawData = (_fragmentsCompressed ? _fragmentsBuffer.DecompressToArray(_compression) : _fragmentsBuffer.ToArray()); enqueueToMessageEventQueue(new MessageEventArgs(_fragmentsOpcode, rawData)); } _fragmentsBuffer = null; _inContinuation = false; } return true; } private bool processPingFrame(WebSocketFrame frame) { _logger.Trace("A ping was received."); WebSocketFrame webSocketFrame = WebSocketFrame.CreatePongFrame(frame.PayloadData, _client); lock (_forState) { if (_readyState != WebSocketState.Open) { _logger.Error("The connection is closing."); return true; } if (!sendBytes(webSocketFrame.ToArray())) { return false; } } _logger.Trace("A pong to this ping has been sent."); if (_emitOnPing) { if (_client) { webSocketFrame.Unmask(); } enqueueToMessageEventQueue(new MessageEventArgs(frame)); } return true; } private bool processPongFrame(WebSocketFrame frame) { _logger.Trace("A pong was received."); try { _pongReceived.Set(); } catch (NullReferenceException ex) { _logger.Error(ex.Message); _logger.Debug(ex.ToString()); return false; } catch (ObjectDisposedException ex2) { _logger.Error(ex2.Message); _logger.Debug(ex2.ToString()); return false; } _logger.Trace("It has been signaled."); return true; } private bool processReceivedFrame(WebSocketFrame frame) { if (!checkReceivedFrame(frame, out var text)) { throw new WebSocketException(CloseStatusCode.ProtocolError, text); } frame.Unmask(); return frame.IsFragment ? processFragmentFrame(frame) : (frame.IsData ? processDataFrame(frame) : (frame.IsPing ? processPingFrame(frame) : (frame.IsPong ? processPongFrame(frame) : (frame.IsClose ? processCloseFrame(frame) : processUnsupportedFrame(frame))))); } private void processSecWebSocketExtensionsClientHeader(string value) { if (value == null) { return; } StringBuilder stringBuilder = new StringBuilder(80); bool flag = false; foreach (string item in value.SplitHeaderValue(',')) { string text = item.Trim(); if (text.Length != 0 && !flag && text.IsCompressionExtension(CompressionMethod.Deflate)) { _compression = CompressionMethod.Deflate; string arg = _compression.ToExtensionString("client_no_context_takeover", "server_no_context_takeover"); stringBuilder.AppendFormat("{0}, ", arg); flag = true; } } int length = stringBuilder.Length; if (length > 2) { stringBuilder.Length = length - 2; _extensions = stringBuilder.ToString(); } } private void processSecWebSocketExtensionsServerHeader(string value) { if (value == null) { _compression = CompressionMethod.None; } else { _extensions = value; } } private void processSecWebSocketProtocolClientHeader(IEnumerable<string> values) { if (!values.Contains((string val) => val == _protocol)) { _protocol = null; } } private bool processUnsupportedFrame(WebSocketFrame frame) { _logger.Fatal("An unsupported frame:" + frame.PrintToString(dumped: false)); fatal("There is no way to handle it.", CloseStatusCode.PolicyViolation); return false; } private void refuseHandshake(CloseStatusCode code, string reason) { _readyState = WebSocketState.Closing; HttpResponse response = createHandshakeFailureResponse(WebSocketSharp.Net.HttpStatusCode.BadRequest); sendHttpResponse(response); releaseServerResources(); _readyState = WebSocketState.Closed; CloseEventArgs e = new CloseEventArgs((ushort)code, reason, clean: false); try { this.OnClose.Emit(this, e); } catch (Exception ex) { _logger.Error(ex.Message); _logger.Debug(ex.ToString()); } } private void releaseClientResources() { if (_stream != null) { _stream.Dispose(); _stream = null; } if (_tcpClient != null) { _tcpClient.Close(); _tcpClient = null; } } private void releaseCommonResources() { if (_fragmentsBuffer != null) { _fragmentsBuffer.Dispose(); _fragmentsBuffer = null; _inContinuation = false; } if (_pongReceived != null) { _pongReceived.Close(); _pongReceived = null; } if (_receivingExited != null) { _receivingExited.Close(); _receivingExited = null; } } private void releaseResources() { if (_client) { releaseClientResources(); } else { releaseServerResources(); } releaseCommonResources(); } private void releaseServerResources() { if (_closeContext != null) { _closeContext(); _closeContext = null; _stream = null; _context = null; } } private bool send(Opcode opcode, Stream stream) { lock (_forSend) { Stream stream2 = stream; bool flag = false; bool flag2 = false; try { if (_compression != 0) { stream = stream.Compress(_compression); flag = true; } flag2 = send(opcode, stream, flag); if (!flag2) { error("A send has been interrupted.", null); } } catch (Exception ex) { _logger.Error(ex.ToString()); error("An error has occurred during a send.", ex); } finally { if (flag) { stream.Dispose(); } stream2.Dispose(); } return flag2; } } private bool send(Opcode opcode, Stream stream, bool compressed) { long length = stream.Length; if (length == 0) { return send(Fin.Final, opcode, EmptyBytes, compressed: false); } long num = length / FragmentLength; int num2 = (int)(length % FragmentLength); byte[] array = null; switch (num) { case 0L: array = new byte[num2]; return stream.Read(array, 0, num2) == num2 && send(Fin.Final, opcode, array, compressed); case 1L: if (num2 == 0) { array = new byte[FragmentLength]; return stream.Read(array, 0, FragmentLength) == FragmentLength && send(Fin.Final, opcode, array, compressed); } break; } array = new byte[FragmentLength]; if (stream.Read(array, 0, FragmentLength) != FragmentLength || !send(Fin.More, opcode, array, compressed)) { return false; } long num3 = ((num2 == 0) ? (num - 2) : (num - 1)); for (long num4 = 0L; num4 < num3; num4++) { if (stream.Read(array, 0, FragmentLength) != FragmentLength || !send(Fin.More, Opcode.Cont, array, compressed: false)) { return false; } } if (num2 == 0) { num2 = FragmentLength; } else { array = new byte[num2]; } return stream.Read(array, 0, num2) == num2 && send(Fin.Final, Opcode.Cont, array, compressed: false); } private bool send(Fin fin, Opcode opcode, byte[] data, bool compressed) { lock (_forState) { if (_readyState != WebSocketState.Open) { _logger.Error("The connection is closing."); return false; } WebSocketFrame webSocketFrame = new WebSocketFrame(fin, opcode, data, compressed, _client); return sendBytes(webSocketFrame.ToArray()); } } private void sendAsync(Opcode opcode, Stream stream, Action<bool> completed) { Func<Opcode, Stream, bool> sender = send; sender.BeginInvoke(opcode, stream, delegate(IAsyncResult ar) { try { bool obj = sender.EndInvoke(ar); if (completed != null) { completed(obj); } } catch (Exception ex) { _logger.Error(ex.ToString()); error("An error has occurred during the callback for an async send.", ex); } }, null); } private bool sendBytes(byte[] bytes) { try { _stream.Write(bytes, 0, bytes.Length); } catch (Exception ex) { _logger.Error(ex.Message); _logger.Debug(ex.ToString()); return false; } return true; } private HttpResponse sendHandshakeRequest() { HttpRequest httpRequest = createHandshakeRequest(); HttpResponse httpResponse = sendHttpRequest(httpRequest, 90000); if (httpResponse.IsUnauthorized) { if (_credentials == null) { _logger.Error("No credential is specified."); return httpResponse; } string value = httpResponse.Headers["WWW-Authenticate"]; if (value.IsNullOrEmpty()) { _logger.Error("No authentication challenge is specified."); return httpResponse; } AuthenticationChallenge authenticationChallenge = AuthenticationChallenge.Parse(value); if (authenticationChallenge == null) { _logger.Error("An invalid authentication challenge is specified."); return httpResponse; } _authChallenge = authenticationChallenge; if (_preAuth && _authChallenge.Scheme == WebSocketSharp.Net.AuthenticationSchemes.Basic) { _logger.Error("The authentication has failed."); return httpResponse; } AuthenticationResponse authenticationResponse = new AuthenticationResponse(_authChallenge, _credentials, _nonceCount); _nonceCount = authenticationResponse.NonceCount; httpRequest.Headers["Authorization"] = authenticationResponse.ToString(); if (httpResponse.CloseConnection) { releaseClientResources(); setClientStream(); } httpResponse = sendHttpRequest(httpRequest, 15000); } if (httpResponse.IsRedirect) { if (!_enableRedirection) { return httpResponse; } string text = httpResponse.Headers["Location"]; if (text.IsNullOrEmpty()) { _logger.Error("No url to redirect is located."); return httpResponse; } if (!text.TryCreateWebSocketUri(out var result, out var _)) { _logger.Error("An invalid url to redirect is located."); return httpResponse; } releaseClientResources(); _uri = result; _secure = result.Scheme == "wss"; setClientStream(); return sendHandshakeRequest(); } return httpResponse; } private HttpResponse sendHttpRequest(HttpRequest request, int millisecondsTimeout) { string text = "An HTTP request to the server:\n" + request.ToString(); _logger.Debug(text); HttpResponse response = request.GetResponse(_stream, millisecondsTimeout); text = "An HTTP response from the server:\n" + response.ToString(); _logger.Debug(text); return response; } private bool sendHttpResponse(HttpResponse response) { string format = "An HTTP response to {0}:\n{1}"; string text = string.Format(format, _context.UserEndPoint, response); _logger.Debug(text); byte[] bytes = response.ToByteArray(); return sendBytes(bytes); } private void sendProxyConnectRequest() { HttpRequest httpRequest = HttpRequest.CreateConnectRequest(_uri); HttpResponse httpResponse = sendHttpRequest(httpRequest, 90000); if (httpResponse.IsProxyAuthenticationRequired) { if (_proxyCredentials == null) { string text = "No credential for the proxy is specified."; throw new WebSocketException(text); } string value = httpResponse.Headers["Proxy-Authenticate"]; if (value.IsNullOrEmpty()) { string text2 = "No proxy authentication challenge is specified."; throw new WebSocketException(text2); } AuthenticationChallenge authenticationChallenge = AuthenticationChallenge.Parse(value); if (authenticationChallenge == null) { string text3 = "An invalid proxy authentication challenge is specified."; throw new WebSocketException(text3); } AuthenticationResponse authenticationResponse = new AuthenticationResponse(authenticationChallenge, _proxyCredentials, 0u); httpRequest.Headers["Proxy-Authorization"] = authenticationResponse.ToString(); if (httpResponse.CloseConnection) { releaseClientResources(); _tcpClient = new TcpClient(_proxyUri.DnsSafeHost, _proxyUri.Port); _stream = _tcpClient.GetStream(); } httpResponse = sendHttpRequest(httpRequest, 15000); if (httpResponse.IsProxyAuthenticationRequired) { string text4 = "The proxy authentication has failed."; throw new WebSocketException(text4); } } if (!httpResponse.IsSuccess) { string text5 = "The proxy has failed a connection to the requested URL."; throw new WebSocketException(text5); } } private void setClientStream() { if (_proxyUri != null) { _tcpClient = new TcpClient(_proxyUri.DnsSafeHost, _proxyUri.Port); _stream = _tcpClient.GetStream(); sendProxyConnectRequest(); } else { _tcpClient = new TcpClient(_uri.DnsSafeHost, _uri.Port); _stream = _tcpClient.GetStream(); } if (_secure) { ClientSslConfiguration sslConfiguration = getSslConfiguration(); string targetHost = sslConfiguration.TargetHost; if (targetHost != _uri.DnsSafeHost) { string text = "An invalid host name is specified."; throw new WebSocketException(CloseStatusCode.TlsHandshakeFailure, text); } try { SslStream sslStream = new SslStream(_stream, leaveInnerStreamOpen: false, sslConfiguration.ServerCertificateValidationCallback, sslConfiguration.ClientCertificateSelectionCallback); sslStream.AuthenticateAsClient(targetHost, sslConfiguration.ClientCertificates, sslConfiguration.EnabledSslProtocols, sslConfiguration.CheckCertificateRevocation); _stream = sslStream; } catch (Exception innerException) { throw new WebSocketException(CloseStatusCode.TlsHandshakeFailure, innerException); } } } private void startReceiving() { if (_messageEventQueue.Count > 0) { _messageEventQueue.Clear(); } _pongReceived = new ManualResetEvent(initialState: false); _receivingExited = new ManualResetEvent(initialState: false); Action receive = null; receive = delegate { WebSocketFrame.ReadFrameAsync(_stream, unmask: false, delegate(WebSocketFrame frame) { if (!processReceivedFrame(frame) || _readyState == WebSocketState.Closed) { _receivingExited?.Set(); } else { receive(); if (!_inMessage && HasMessage && _readyState == WebSocketState.Open) { message(); } } }, delegate(Exception ex) { _logger.Fatal(ex.ToString()); fatal("An exception has occurred while receiving.", ex); }); }; receive(); } private bool validateSecWebSocketExtensionsServerHeader(string value) { if (value == null) { return true; } if (value.Length == 0) { return false; } if (!_extensionsRequested) { return false; } bool flag = _compression != CompressionMethod.None; foreach (string item in value.SplitHeaderValue(',')) { string text = item.Trim(); if (flag && text.IsCompressionExtension(_compression)) { string param1 = "server_no_context_takeover"; string param2 = "client_no_context_takeover"; if (!text.Contains(param1)) { string format = "The server did not send back '{0}'."; string text2 = string.Format(format, param1); _logger.Error(text2); return false; } string name = _compression.ToExtensionString(); if (text.SplitHeaderValue(';').Contains(delegate(string t) { t = t.Trim(); bool flag2 = t == name || t == param1 || t == param2; return !flag2; })) { return false; } flag = false; continue; } return false; } return true; } internal void Close(HttpResponse response) { _readyState = WebSocketState.Closing; sendHttpResponse(response); releaseServerResources(); _readyState = WebSocketState.Closed; } internal void Close(WebSocketSharp.Net.HttpStatusCode code) { Close(createHandshakeFailureResponse(code)); } internal void Close(PayloadData payloadData, byte[] frameAsBytes) { lock (_forState) { if (_readyState == WebSocketState.Closing) { _logger.Info("The closing is already in progress."); return; } if (_readyState == WebSocketState.Closed) { _logger.Info("The connection has already been closed."); return; } _readyState = WebSocketState.Closing; } _logger.Trace("Begin closing the connection."); bool flag = frameAsBytes != null && sendBytes(frameAsBytes); bool flag2 = flag && _receivingExited != null && _receivingExited.WaitOne(_waitTime); bool flag3 = flag && flag2; _logger.Debug($"Was clean?: {flag3}\n sent: {flag}\n received: {flag2}"); releaseServerResources(); releaseCommonResources(); _logger.Trace("End closing the connection."); _readyState = WebSocketState.Closed; CloseEventArgs e = new CloseEventArgs(payloadData, flag3); try { this.OnClose.Emit(this, e); } catch (Exception ex) { _logger.Error(ex.Message); _logger.Debug(ex.ToString()); } } internal static string CreateBase64Key() { byte[] array = new byte[16]; RandomNumber.GetBytes(array); return Convert.ToBase64String(array); } internal static string CreateResponseKey(string base64Key) { StringBuilder stringBuilder = new StringBuilder(base64Key, 64); stringBuilder.Append("258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); SHA1 sHA = new SHA1CryptoServiceProvider(); byte[] inArray = sHA.ComputeHash(stringBuilder.ToString().GetUTF8EncodedBytes()); return Convert.ToBase64String(inArray); } internal void InternalAccept() { try { if (!acceptHandshake()) { return; } } catch (Exception ex) { _logger.Fatal(ex.Message); _logger.Debug(ex.ToString()); string text = "An exception has occurred while attempting to accept."; fatal(text, ex); return; } _readyState = WebSocketState.Open; open(); } internal bool Ping(byte[] frameAsBytes, TimeSpan timeout) { if (_readyState != WebSocketState.Open) { return false; } ManualResetEvent pongReceived = _pongReceived; if (pongReceived == null) { return false; } lock (_forPing) { try { pongReceived.Reset(); lock (_forState) { if (_readyState != WebSocketState.Open) { return false; } if (!sendBytes(frameAsBytes)) { return false; } } return pongReceived.WaitOne(timeout); } catch (ObjectDisposedException) { return false; } } } internal void Send(Opcode opcode, byte[] data, Dictionary<CompressionMethod, byte[]> cache) { lock (_forSend) { lock (_forState) { if (_readyState != WebSocketState.Open) { _logger.Error("The connection is closing."); return; } if (!cache.TryGetValue(_compression, out var value)) { value = new WebSocketFrame(Fin.Final, opcode, data.Compress(_compression), _compression != CompressionMethod.None, mask: false).ToArray(); cache.Add(_compression, value); } sendBytes(value); } } } internal void Send(Opcode opcode, Stream stream, Dictionary<CompressionMethod, Stream> cache) { lock (_forSend) { if (!cache.TryGetValue(_compression, out var value)) { value = stream.Compress(_compression); cache.Add(_compression, value); } else { value.Position = 0L; } send(opcode, value, _compression != CompressionMethod.None); } } public void Accept() { if (_client) { string text = "This instance is a client."; throw new InvalidOperationException(text); } if (_readyState == WebSocketState.Closing) { string text2 = "The close process is in progress."; throw new InvalidOperationException(text2); } if (_readyState == WebSocketState.Closed) { string text3 = "The connection has already been closed."; throw new InvalidOperationException(text3); } if (accept()) { open(); } } public void AcceptAsync() { if (_client) { string text = "This instance is a client."; throw new InvalidOperationException(text); } if (_readyState == WebSocketState.Closing) { string text2 = "The close process is in progress."; throw new InvalidOperationException(text2); } if (_readyState == WebSocketState.Closed) { string text3 = "The connection has already been closed."; throw new InvalidOperationException(text3); } Func<bool> acceptor = accept; acceptor.BeginInvoke(delegate(IAsyncResult ar) { if (acceptor.EndInvoke(ar)) { open(); } }, null); } public void Close() { close(1005, string.Empty); } public void Close(ushort code) { if (!code.IsCloseStatusCode()) { string text = "Less than 1000 or greater than 4999."; throw new ArgumentOutOfRangeException("code", text); } if (_client && code == 1011) { string text2 = "1011 cannot be used."; throw new ArgumentException(text2, "code"); } if (!_client && code == 1010) { string text3 = "1010 cannot be used."; throw new ArgumentException(text3, "code"); } close(code, string.Empty); } public void Close(CloseStatusCode code) { if (_client && code == CloseStatusCode.ServerError) { string text = "ServerError cannot be used."; throw new ArgumentException(text, "code"); } if (!_client && code == CloseStatusCode.MandatoryExtension) { string text2 = "MandatoryExtension cannot be used."; throw new ArgumentException(text2, "code"); } close((ushort)code, string.Empty); } public void Close(ushort code, string reason) { if (!code.IsCloseStatusCode()) { string text = "Less than 1000 or greater than 4999."; throw new ArgumentOutOfRangeException("code", text); } if (_client && code == 1011) { string text2 = "1011 cannot be used."; throw new ArgumentException(text2, "code"); } if (!_client && code == 1010) { string text3 = "1010 cannot be used."; throw new ArgumentException(text3, "code"); } if (reason.IsNullOrEmpty()) { close(code, string.Empty); return; } if (code == 1005) { string text4 = "1005 cannot be used."; throw new ArgumentException(text4, "code"); } if (!reason.TryGetUTF8EncodedBytes(out var bytes)) { string text5 = "It could not be UTF-8-encoded."; throw new ArgumentException(text5, "reason"); } if (bytes.Length > 123) { string text6 = "Its size is greater than 123 bytes."; throw new ArgumentOutOfRangeException("reason", text6); } close(code, reason); } public void Close(CloseStatusCode code, string reason) { if (_client && code == CloseStatusCode.ServerError) { string text = "ServerError cannot be used."; throw new ArgumentException(text, "code"); } if (!_client && code == CloseStatusCode.MandatoryExtension) { string text2 = "MandatoryExtension cannot be used."; throw new ArgumentException(text2, "code"); } if (reason.IsNullOrEmpty()) { close((ushort)code, string.Empty); return; } if (code == CloseStatusCode.NoStatus) { string text3 = "NoStatus cannot be used."; throw new ArgumentException(text3, "code"); } if (!reason.TryGetUTF8EncodedBytes(out var bytes)) { string text4 = "It could not be UTF-8-encoded."; throw new ArgumentException(text4, "reason"); } if (bytes.Length > 123) { string text5 = "Its size is greater than 123 bytes."; throw new ArgumentOutOfRangeException("reason", text5); } close((ushort)code, reason); } public void CloseAsync() { closeAsync(1005, string.Empty); } public void CloseAsync(ushort code) { if (!code.IsCloseStatusCode()) { string text = "Less than 1000 or greater than 4999."; throw new ArgumentOutOfRangeException("code", text); } if (_client && code == 1011) { string text2 = "1011 cannot be used."; throw new ArgumentException(text2, "code"); } if (!_client && code == 1010) { string text3 = "1010 cannot be used."; throw new ArgumentException(text3, "code"); } closeAsync(code, string.Empty); } public void CloseAsync(CloseStatusCode code) { if (_client && code == CloseStatusCode.ServerError) { string text = "ServerError cannot be used."; throw new ArgumentException(text, "code"); } if (!_client && code == CloseStatusCode.MandatoryExtension) { string text2 = "MandatoryExtension cannot be used."; throw new ArgumentException(text2, "code"); } closeAsync((ushort)code, string.Empty); } public void CloseAsync(ushort code, string reason) { if (!code.IsCloseStatusCode()) { string text = "Less than 1000 or greater than 4999."; throw new ArgumentOutOfRangeException("code", text); } if (_client && code == 1011) { string text2 = "1011 cannot be used."; throw new ArgumentException(text2, "code"); } if (!_client && code == 1010) { string text3 = "1010 cannot be used."; throw new ArgumentException(text3, "code"); } if (reason.IsNullOrEmpty()) { closeAsync(code, string.Empty); return; } if (code == 1005) { string text4 = "1005 cannot be used."; throw new ArgumentException(text4, "code"); } if (!reason.TryGetUTF8EncodedBytes(out var bytes)) { string text5 = "It could not be UTF-8-encoded."; throw new ArgumentException(text5, "reason"); } if (bytes.Length > 123) { string text6 = "Its size is greater than 123 bytes."; throw new ArgumentOutOfRangeException("reason", text6); } closeAsync(code, reason); } public void CloseAsync(CloseStatusCode code, string reason) { if (_client && code == CloseStatusCode.ServerError) { string text = "ServerError cannot be used."; throw new ArgumentException(text, "code"); } if (!_client && code == CloseStatusCode.MandatoryExtension) { string text2 = "MandatoryExtension cannot be used."; throw new ArgumentException(text2, "code"); } if (reason.IsNullOrEmpty()) { closeAsync((ushort)code, string.Empty); return; } if (code == CloseStatusCode.NoStatus) { string text3 = "NoStatus cannot be used."; throw new ArgumentException(text3, "code"); } if (!reason.TryGetUTF8EncodedBytes(out var bytes)) { string text4 = "It could not be UTF-8-encoded."; throw new ArgumentException(text4, "reason"); } if (bytes.Length > 123) { string text5 = "Its size is greater than 123 bytes."; throw new ArgumentOutOfRangeException("reason", text5); } closeAsync((ushort)code, reason); } public void Connect() { if (!_client) { string text = "This instance is not a client."; throw new InvalidOperationException(text); } if (_readyState == WebSocketState.Closing) { string text2 = "The close process is in progress."; throw new InvalidOperationException(text2); } if (_retryCountForConnect > _maxRetryCountForConnect) { string text3 = "A series of reconnecting has failed."; throw new InvalidOperationException(text3); } if (connect()) { open(); } } public void ConnectAsync() { if (!_client) { string text = "This instance is not a client."; throw new InvalidOperationException(text); } if (_readyState == WebSocketState.Closing) { string text2 = "The close process is in progress."; throw new InvalidOperationException(text2); } if (_retryCountForConnect > _maxRetryCountForConnect) { string text3 = "A series of reconnecting has failed."; throw new InvalidOperationException(text3); } Func<bool> connector = connect; connector.BeginInvoke(delegate(IAsyncResult ar) { if (connector.EndInvoke(ar)) { open(); } }, null); } public bool Ping() { return ping(EmptyBytes); } public bool Ping(string message) { if (message.IsNullOrEmpty()) { return ping(EmptyBytes); } if (!message.TryGetUTF8EncodedBytes(out var bytes)) { string text = "It could not be UTF-8-encoded."; throw new ArgumentException(text, "message"); } if (bytes.Length > 125) { string text2 = "Its size is greater than 125 bytes."; throw new ArgumentOutOfRangeException("message", text2); } return ping(bytes); } public void Send(byte[] data) { if (_readyState != WebSocketState.Open) { string text = "The current state of the connection is not Open."; throw new InvalidOperationException(text); } if (data == null) { throw new ArgumentNullException("data"); } send(Opcode.Binary, new MemoryStream(data)); } public void Send(FileInfo fileInfo) { if (_readyState != WebSocketState.Open) { string text = "The current state of the connection is not Open."; throw new InvalidOperationException(text); } if (fileInfo == null) { throw new ArgumentNullException("fileInfo"); } if (!fileInfo.Exists) { string text2 = "The file does not exist."; throw new ArgumentException(text2, "fileInfo"); } if (!fileInfo.TryOpenRead(out var fileStream)) { string text3 = "The file could not be opened."; throw new ArgumentException(text3, "fileInfo"); } send(Opcode.Binary, fileStream); } public void Send(string data) { if (_readyState != WebSocketState.Open) { string text = "The current state of the connection is not Open."; throw new InvalidOperationException(text); } if (data == null) { throw new ArgumentNullException("data"); } if (!data.TryGetUTF8EncodedBytes(out var bytes)) { string text2 = "It could not be UTF-8-encoded."; throw new ArgumentException(text2, "data"); } send(Opcode.Text, new MemoryStream(bytes)); } public void Send(Stream stream, int length) { if (_readyState != WebSocketState.Open) { string text = "The current state of the connection is not Open."; throw new InvalidOperationException(text); } if (stream == null) { throw new ArgumentNullException("stream"); } if (!stream.CanRead) { string text2 = "It cannot be read."; throw new ArgumentException(text2, "stream"); } if (length < 1) { string text3 = "Less than 1."; throw new ArgumentException(text3, "length"); } byte[] array = stream.ReadBytes(length); int num = array.Length; if (num == 0) { string text4 = "No data could be read from it."; throw new ArgumentException(text4, "stream"); } if (num < length) { _logger.Warn($"Only {num} byte(s) of data could be read from the stream."); } send(Opcode.Binary, new MemoryStream(array)); } public void SendAsync(byte[] data, Action<bool> completed) { if (_readyState != WebSocketState.Open) { string text = "The current state of the connection is not Open."; throw new InvalidOperationException(text); } if (data == null) { throw new ArgumentNullException("data"); } sendAsync(Opcode.Binary, new MemoryStream(data), completed); } public void SendAsync(FileInfo fileInfo, Action<bool> completed) { if (_readyState != WebSocketState.Open) { string text = "The current state of the connection is not Open."; throw new InvalidOperationException(text); } if (fileInfo == null) { throw new ArgumentNullException("fileInfo"); } if (!fileInfo.Exists) { string text2 = "The file does not exist."; throw new ArgumentException(text2, "fileInfo"); } if (!fileInfo.TryOpenRead(out var fileStream)) { string text3 = "The file could not be opened."; throw new ArgumentException(text3, "fileInfo"); } sendAsync(Opcode.Binary, fileStream, completed); } public void SendAsync(string data, Action<bool> completed) { if (_readyState != WebSocketState.Open) { string text = "The current state of the connection is not Open."; throw new InvalidOperationException(text); } if (data == null) { throw new ArgumentNullException("data"); } if (!data.TryGetUTF8EncodedBytes(out var bytes)) { string text2 = "It could not be UTF-8-encoded."; throw new ArgumentException(text2, "data"); } sendAsync(Opcode.Text, new MemoryStream(bytes), completed); } public void SendAsync(Stream stream, int length, Action<bool> completed) { if (_readyState != WebSocketState.Open) { string text = "The current state of the connection is not Open."; throw new InvalidOperationException(text); } if (stream == null) { throw new ArgumentNullException("stream"); } if (!stream.CanRead) { string text2 = "It cannot be read."; throw new ArgumentException(text2, "stream"); } if (length < 1) { string text3 = "Less than 1."; throw new ArgumentException(text3, "length"); } byte[] array = stream.ReadBytes(length); int num = array.Length; if (num == 0) { string text4 = "No data could be read from it."; throw new ArgumentException(text4, "stream"); } if (num < length) { _logger.Warn($"Only {num} byte(s) of data could be read from the stream."); } sendAsync(Opcode.Binary, new MemoryStream(array), completed); } public void SetCookie(WebSocketSharp.Net.Cookie cookie) { string text = null; if (!_client) { text = "This instance is not a client."; throw new InvalidOperationException(text); } if (cookie == null) { throw new ArgumentNullException("cookie"); } if (!canSet(out text)) { _logger.Warn(text); return; } lock (_forState) { if (!canSet(out text)) { _logger.Warn(text); return; } lock (_cookies.SyncRoot) { _cookies.SetOrRemove(cookie); } } } public void SetCredentials(string username, string password, bool preAuth) { string text = null; if (!_client) { text = "This instance is not a client."; throw new InvalidOperationException(text); } if (!username.IsNullOrEmpty() && (Ext.Contains(username, ':') || !username.IsText())) { text = "It contains an invalid character."; throw new ArgumentException(text, "username"); } if (!password.IsNullOrEmpty() && !password.IsText()) { text = "It contains an invalid character."; throw new ArgumentException(text, "password"); } if (!canSet(out text)) { _logger.Warn(text); return; } lock (_forState) { if (!canSet(out text)) { _logger.Warn(text); } else if (username.IsNullOrEmpty()) { _credentials = null; _preAuth = false; } else { _credentials = new WebSocketSharp.Net.NetworkCredential(username, password, _uri.PathAndQuery); _preAuth = preAuth; } } } public void SetProxy(string url, string username, string password) { string text = null; if (!_client) { text = "This instance is not a client."; throw new InvalidOperationException(text); } Uri result = null; if (!url.IsNullOrEmpty()) { if (!Uri.TryCreate(url, UriKind.Absolute, out result)) { text = "Not an absolute URI string."; throw new ArgumentException(text, "url"); } if (result.Scheme != "http") { text = "The scheme part is not http."; throw new ArgumentException(text, "url"); } if (result.Segments.Length > 1) { text = "It includes the path segments."; throw new ArgumentException(text, "url"); } } if (!username.IsNullOrEmpty() && (Ext.Contains(username, ':') || !username.IsText())) { text = "It contains an invalid character."; throw new ArgumentException(text, "username"); } if (!password.IsNullOrEmpty() && !password.IsText()) { text = "It contains an invalid character."; throw new ArgumentException(text, "password"); } if (!canSet(out text)) { _logger.Warn(text); return; } lock (_forState) { if (!canSet(out text)) { _logger.Warn(text); } else if (url.IsNullOrEmpty()) { _proxyUri = null; _proxyCredentials = null; } else { _proxyUri = result; _proxyCredentials = ((!username.IsNullOrEmpty()) ? new WebSocketSharp.Net.NetworkCredential(username, password, $"{_uri.DnsSafeHost}:{_uri.Port}") : null); } } } void IDisposable.Dispose() { close(1001, string.Empty); } } public enum CloseStatusCode : ushort { Normal = 1000, Away = 1001, ProtocolError = 1002, UnsupportedData = 1003, Undefined = 1004, NoStatus = 1005, Abnormal = 1006, InvalidData = 1007, PolicyViolation = 1008, TooBig = 1009, MandatoryExtension = 1010, ServerError = 1011, TlsHandshakeFailure = 1015 } internal enum Fin : byte { More, Final } internal enum Mask : byte { Off, On } internal enum Opcode : byte { Cont = 0, Text = 1, Binary = 2, Close = 8, Ping = 9, Pong = 10 } internal class PayloadData : IEnumerable<byte>, IEnumerable { private byte[] _data; private long _extDataLength; private long _length; public static readonly PayloadData Empty; public static readonly ulong MaxLength; internal ushort Code => (ushort)((_length >= 2) ? _data.SubArray(0, 2).ToUInt16(ByteOrder.Big) : 1005); internal long ExtensionDataLength { get { return _extDataLength; } set { _extDataLength = value; } } internal bool HasReservedCode => _length >= 2 && Code.IsReserved(); internal string Reason { get { if (_length <= 2) { return string.Empty; } byte[] bytes = _data.SubArray(2L, _length - 2); string s; return bytes.TryGetUTF8DecodedString(out s) ? s : string.Empty; } } public byte[] ApplicationData => (_extDataLength > 0) ? _data.SubArray(_extDataLength, _length - _extDataLength) : _data; public byte[] ExtensionData => (_extDataLength > 0) ? _data.SubArray(0L, _extDataLength) : WebSocket.EmptyBytes; public ulong Length => (ulong)_length; static PayloadData() { Empty = new PayloadData(WebSocket.EmptyBytes, 0L); MaxLength = 9223372036854775807uL; } internal PayloadData(byte[] data) : this(data, data.LongLength) { } internal PayloadData(byte[] data, long length) { _data = data; _length = length; } internal PayloadData(ushort code, string reason) { _data = code.Append(reason); _length = _data.LongLength; } internal void Mask(byte[] key) { for (long num = 0L; num < _length; num++) { _data[num] ^= key[num % 4]; } } public IEnumerator<byte> GetEnumerator() { byte[] data = _data; for (int i = 0; i < data.Length; i++) { yield return data[i]; } } public byte[] ToArray() { return _data; } public override string ToString() { return BitConverter.ToString(_data); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal enum Rsv : byte { Off, On } public enum CompressionMethod : byte { None, Deflate } public class WebSocketException : Exception { private CloseStatusCode _code; public CloseStatusCode Code => _code; internal WebSocketException() : this(CloseStatusCode.Abnormal, null, null) { } internal WebSocketException(Exception innerException) : this(CloseStatusCode.Abnormal, null, innerException) { } internal WebSocketException(string message) : this(CloseStatusCode.Abnormal, message, null) { } internal WebSocketException(CloseStatusCode code) : this(code, null, null) { } internal WebSocketException(string message, Exception innerException) : this(CloseStatusCode.Abnormal, message, innerException) { } internal WebSocketException(CloseStatusCode code, Exception inne