Decompiled source of ScrewThisGuy v1.0.0

ScrewThisGuy.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("LuniLC")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LuniLC")]
[assembly: AssemblyCopyright("Copyright ©  2026")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("96ea26a3-ef1b-4241-b306-606bd65802ba")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
[BepInPlugin("com.you.screwthisguy", "Screw this guy", "1.0.0")]
public class Plugin : BaseUnityPlugin
{
	private struct ParamMap
	{
		public int Sender;

		public int Reader;
	}

	private class Rate
	{
		public long WindowStart;

		public int Count;
	}

	private sealed class Wire
	{
		private readonly byte[] b;

		private int i;

		public int Left => b.Length - i;

		public Wire(byte[] data)
		{
			b = data;
		}

		private void Need(int n)
		{
			if (n < 0 || Left < n)
			{
				throw new FormatException();
			}
		}

		public byte U8()
		{
			Need(1);
			return b[i++];
		}

		public ushort U16()
		{
			Need(2);
			ushort result = (ushort)((b[i] << 8) | b[i + 1]);
			i += 2;
			return result;
		}

		public uint U32()
		{
			Need(4);
			uint result = (uint)((b[i] << 24) | (b[i + 1] << 16) | (b[i + 2] << 8) | b[i + 3]);
			i += 4;
			return result;
		}

		public string Str()
		{
			int num = U16();
			if (num == 0)
			{
				return null;
			}
			Need(num - 1);
			string result = Encoding.UTF8.GetString(b, i, num - 1);
			i += num - 1;
			return result;
		}

		public byte[] Bytes()
		{
			int num = U16();
			Need(num);
			byte[] array = new byte[num];
			Buffer.BlockCopy(b, i, array, 0, num);
			i += num;
			return array;
		}
	}

	public const string ModGuid = "com.you.screwthisguy";

	private const int MaxNameLength = 64;

	private const int MaxRoomNameLength = 128;

	private const int MaxRooms = 32;

	private const int MaxRelayTargets = 64;

	private const int MaxFrameSize = 5760;

	private const int MaxPacketsPerSecond = 200;

	private const ushort Magic = 35783;

	private static readonly int[] SampleRates = new int[5] { 8000, 12000, 16000, 24000, 48000 };

	internal static ManualLogSource L;

	private static Harmony harmony;

	private static int patched;

	private static bool loggedPrefixError;

	private float nextPatchTry;

	private static readonly HashSet<Assembly> scannedAssemblies = new HashSet<Assembly>();

	private static readonly Dictionary<MethodBase, ParamMap> paramMaps = new Dictionary<MethodBase, ParamMap>();

	private static readonly Dictionary<ulong, Rate> rates = new Dictionary<ulong, Rate>();

	private static readonly HashSet<string> logged = new HashSet<string>();

	private void Awake()
	{
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Expected O, but got Unknown
		((Object)((Component)this).gameObject).hideFlags = (HideFlags)61;
		L = ((BaseUnityPlugin)this).Logger;
		harmony = new Harmony("com.you.screwthisguy");
		TryPatch();
	}

	private void Update()
	{
		if (patched == 0 && Time.unscaledTime > nextPatchTry)
		{
			nextPatchTry = Time.unscaledTime + 3f;
			TryPatch();
		}
	}

	private void OnDestroy()
	{
		try
		{
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
		catch (Exception ex)
		{
			if (L != null)
			{
				L.LogWarning((object)("Unpatch failed: " + ex.Message));
			}
		}
	}

	private void TryPatch()
	{
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Expected O, but got Unknown
		HarmonyMethod val = new HarmonyMethod(typeof(Plugin).GetMethod("Prefix", BindingFlags.Static | BindingFlags.Public));
		Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
		foreach (Assembly assembly in assemblies)
		{
			if (scannedAssemblies.Contains(assembly))
			{
				continue;
			}
			Type[] array;
			try
			{
				array = assembly.GetTypes();
			}
			catch (ReflectionTypeLoadException ex)
			{
				array = ex.Types.Where((Type t) => t != null).ToArray();
			}
			catch
			{
				continue;
			}
			scannedAssemblies.Add(assembly);
			Type[] array2 = array;
			foreach (Type type in array2)
			{
				if (type.Namespace == null || !type.Namespace.StartsWith("Dissonance.Integrations.Unity_NFGO") || type.ContainsGenericParameters)
				{
					continue;
				}
				MethodInfo[] methods;
				try
				{
					methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				}
				catch
				{
					continue;
				}
				MethodInfo[] array3 = methods;
				foreach (MethodInfo methodInfo in array3)
				{
					if (!methodInfo.IsAbstract && !methodInfo.ContainsGenericParameters && IsCandidate(methodInfo))
					{
						try
						{
							harmony.Patch((MethodBase)methodInfo, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
							patched++;
							L.LogInfo((object)("Patched " + type.FullName + "." + methodInfo.Name));
						}
						catch (Exception ex2)
						{
							L.LogWarning((object)("Patch failed " + type.FullName + "." + methodInfo.Name + ": " + ex2.Message));
						}
					}
				}
			}
		}
	}

	private static bool IsCandidate(MethodBase m)
	{
		bool flag = false;
		bool flag2 = false;
		ParameterInfo[] parameters = m.GetParameters();
		foreach (ParameterInfo parameterInfo in parameters)
		{
			if (parameterInfo.ParameterType == typeof(FastBufferReader))
			{
				flag = true;
			}
			else if (parameterInfo.ParameterType == typeof(ulong) || parameterInfo.ParameterType == typeof(ushort))
			{
				flag2 = true;
			}
		}
		return flag && flag2;
	}

	private static ParamMap BuildParamMap(MethodBase m)
	{
		ParamMap result = new ParamMap
		{
			Sender = -1,
			Reader = -1
		};
		ParameterInfo[] parameters = m.GetParameters();
		for (int i = 0; i < parameters.Length; i++)
		{
			Type parameterType = parameters[i].ParameterType;
			if (result.Reader < 0 && parameterType == typeof(FastBufferReader))
			{
				result.Reader = i;
			}
			else
			{
				if (parameterType != typeof(ulong) && parameterType != typeof(ushort))
				{
					continue;
				}
				if (result.Sender < 0)
				{
					result.Sender = i;
					continue;
				}
				string text = (parameters[i].Name ?? string.Empty).ToLowerInvariant();
				if (text.Contains("sender") || text.Contains("client") || text.Contains("from"))
				{
					result.Sender = i;
				}
			}
		}
		return result;
	}

	public static bool Prefix(MethodBase __originalMethod, object[] __args)
	{
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			if (!paramMaps.TryGetValue(__originalMethod, out var value))
			{
				value = BuildParamMap(__originalMethod);
				paramMaps[__originalMethod] = value;
			}
			if (value.Sender < 0 || value.Reader < 0)
			{
				return true;
			}
			NetworkManager singleton = NetworkManager.Singleton;
			object obj = __args[value.Sender];
			ulong num = ((obj is ushort) ? ((ushort)obj) : ((ulong)obj));
			if ((Object)(object)singleton == (Object)null || num == singleton.LocalClientId)
			{
				return true;
			}
			FastBufferReader r = (FastBufferReader)__args[value.Reader];
			string text = Inspect(__originalMethod, r, num, singleton.IsServer);
			if (text == null)
			{
				return true;
			}
			LogDrop(num, text);
			return false;
		}
		catch (Exception ex)
		{
			if (!loggedPrefixError)
			{
				loggedPrefixError = true;
				L.LogWarning((object)("Prefix error (further errors suppressed): " + ex));
			}
			return true;
		}
	}

	private static string Inspect(MethodBase m, FastBufferReader r, ulong sender, bool isHost)
	{
		bool flag = m.Name == "NamedMessageHandler";
		if (flag && isHost && CountPacket(sender) > 200)
		{
			return "packet flood (over " + 200 + "/s)";
		}
		int position = ((FastBufferReader)(ref r)).Position;
		int length = ((FastBufferReader)(ref r)).Length;
		byte[] data;
		try
		{
			((FastBufferReader)(ref r)).Seek(position);
			if (flag)
			{
				if (length - position < 4)
				{
					return null;
				}
				byte b = default(byte);
				((FastBufferReader)(ref r)).ReadByteSafe(ref b);
				byte b2 = default(byte);
				((FastBufferReader)(ref r)).ReadByteSafe(ref b2);
				byte b3 = default(byte);
				((FastBufferReader)(ref r)).ReadByteSafe(ref b3);
				byte b4 = default(byte);
				((FastBufferReader)(ref r)).ReadByteSafe(ref b4);
				uint num = (uint)(b | (b2 << 8) | (b3 << 16) | (b4 << 24));
				int num2 = length - position - 4;
				if (num > (uint)num2)
				{
					return "fake length: declared " + num + ", actual " + num2;
				}
				data = new byte[num];
				if (num != 0)
				{
					((FastBufferReader)(ref r)).ReadBytesSafe(ref data, (int)num, 0);
				}
			}
			else
			{
				int num3 = length - position;
				if (num3 < 3)
				{
					return null;
				}
				data = new byte[num3];
				((FastBufferReader)(ref r)).ReadBytesSafe(ref data, num3, 0);
			}
		}
		catch
		{
			return null;
		}
		finally
		{
			try
			{
				((FastBufferReader)(ref r)).Seek(position);
			}
			catch
			{
			}
		}
		return Validate(data);
	}

	private static int CountPacket(ulong sender)
	{
		long num = Environment.TickCount;
		if (!rates.TryGetValue(sender, out var value))
		{
			value = new Rate
			{
				WindowStart = num
			};
			rates[sender] = value;
		}
		if (num - value.WindowStart >= 1000)
		{
			value.WindowStart = num;
			value.Count = 0;
		}
		return ++value.Count;
	}

	private static string Validate(byte[] data)
	{
		try
		{
			Wire wire = new Wire(data);
			if (wire.Left < 3 || wire.U16() != 35783)
			{
				return null;
			}
			switch (wire.U8())
			{
			case 1:
				return CheckClientState(wire);
			case 4:
				return CheckHandshake(wire);
			case 7:
			case 8:
				return CheckRelay(wire);
			case 9:
				return CheckDelta(wire);
			default:
				return null;
			}
		}
		catch (FormatException)
		{
			return "malformed packet";
		}
	}

	private static string CheckHandshake(Wire w)
	{
		string text = CheckCodec(w);
		if (text != null)
		{
			return text;
		}
		return CheckName(w.Str());
	}

	private static string CheckClientState(Wire w)
	{
		w.U32();
		string name = w.Str();
		w.U16();
		string text = CheckName(name);
		if (text != null)
		{
			return text;
		}
		text = CheckCodec(w);
		if (text != null)
		{
			return text;
		}
		int num = w.U16();
		if (num > 32)
		{
			return num + " rooms (limit " + 32 + ")";
		}
		for (int i = 0; i < num; i++)
		{
			string text2 = w.Str();
			if (text2 != null && text2.Length > 128)
			{
				return "room name is " + text2.Length + " characters";
			}
		}
		return null;
	}

	private static string CheckDelta(Wire w)
	{
		w.U32();
		w.U8();
		w.U16();
		string text = w.Str();
		if (text != null && text.Length > 128)
		{
			return "room name is " + text.Length + " characters";
		}
		return null;
	}

	private static string CheckRelay(Wire w)
	{
		w.U32();
		int num = w.U8();
		if (num > 64)
		{
			return num + " relay targets (limit " + 64 + ")";
		}
		for (int i = 0; i < num; i++)
		{
			w.U16();
		}
		Wire wire = new Wire(w.Bytes());
		if (wire.Left < 3 || wire.U16() != 35783)
		{
			return null;
		}
		byte b = wire.U8();
		if (b != 2 && b != 3 && b != 11)
		{
			return "packet type " + b + " not allowed inside a relay";
		}
		return null;
	}

	private static string CheckCodec(Wire w)
	{
		byte b = w.U8();
		uint num = w.U32();
		uint num2 = w.U32();
		if (b > 1)
		{
			return "unknown codec " + b;
		}
		if (num == 0 || num > 5760)
		{
			return "frame size " + num + " (limit " + 5760 + ")";
		}
		if (num2 > int.MaxValue || Array.IndexOf(SampleRates, (int)num2) < 0)
		{
			return "sample rate " + num2;
		}
		return null;
	}

	private static string CheckName(string name)
	{
		if (name == null)
		{
			return "name is null";
		}
		if (name.Length > 64)
		{
			return "name is " + name.Length + " characters (limit " + 64 + ")";
		}
		return null;
	}

	private static void LogDrop(ulong sender, string why)
	{
		if (logged.Count < 500 && logged.Add(sender + "|" + why))
		{
			L.LogWarning((object)("Dropped packet from " + sender + ": " + why));
		}
	}
}