Skip to content

Commit

Permalink
Add ResolveAssembly and IPv6DualStack
Browse files Browse the repository at this point in the history
  • Loading branch information
sgkoishi committed Feb 20, 2024
1 parent 5e41b34 commit 221da80
Show file tree
Hide file tree
Showing 9 changed files with 110 additions and 21 deletions.
10 changes: 10 additions & 0 deletions Core/Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,16 @@ public record class EnhancementsSettings
/// </summary>
public Optional<bool> BanPattern = Optional.Default(true, true);

/// <summary>
/// Try to resolve references from loaded assemblies.
/// </summary>
public Optional<bool> ResolveAssembly = Optional.Default(true);

/// <summary>
/// IPv6 Dual Stack Support
/// </summary>
public Optional<bool> IPv6DualStack = Optional.Default(true);

public enum UpdateOptions
{
Silent,
Expand Down
17 changes: 17 additions & 0 deletions Core/Enhancements.cs
Original file line number Diff line number Diff line change
Expand Up @@ -175,4 +175,21 @@ private void RefreshLocalizedCommandAliases()
}
}
}

private void Detour_Socket_StartDualMode(Action<System.Net.Sockets.TcpListener, int> orig, System.Net.Sockets.TcpListener listener, int backlog)
{
if (this.config.Enhancements.Value.IPv6DualStack)
{
try
{
listener.Server.DualMode = true;
TShockAPI.TShock.Log.ConsoleInfo("Dual stack enabled.");
}
catch (Exception e)
{
Utils.ShowError($"Failed to enable dual stack on {listener.LocalEndpoint}: {e}");
}
}
orig(listener, backlog);
}
}
2 changes: 1 addition & 1 deletion Core/FirstChance.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ private void FirstChanceExceptionHandler(object? sender, FirstChanceExceptionEve
try
{
this.inFirstChance.Value++;
var v = args.Exception.ToString();
var v = $"{args.Exception.Message} @ {args.Exception.StackTrace}";
if (this.exceptions.Add(v))
{
Utils.ShowError($"New First Chance: {v}");
Expand Down
32 changes: 32 additions & 0 deletions Core/Plugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ public partial class Plugin : TerrariaPlugin

public Plugin(Main game) : base(game)
{
Utils.AssemblyMutex(this);
AppDomain.CurrentDomain.AssemblyResolve += this.AssemblyResolveHandler;
AppDomain.CurrentDomain.FirstChanceException += this.FirstChanceExceptionHandler;
this.Order = int.MinValue;
this.LoadConfig(Utils.ConsolePlayer.Instance);
Expand Down Expand Up @@ -119,6 +121,32 @@ public Plugin(Main game) : base(game)
.GetMethod("HandleSyncLoadout", _bfany),
this.Detour_Mitigation_HandleSyncLoadout
);
this.Detour(
nameof(this.Detour_Socket_StartDualMode),
typeof(System.Net.Sockets.TcpListener)
.GetMethod(nameof(System.Net.Sockets.TcpListener.Start), [typeof(int)]),
this.Detour_Socket_StartDualMode
);
}

private Assembly? AssemblyResolveHandler(object? sender, ResolveEventArgs args)
{
var an = new AssemblyName(args.Name);
if (an.Name == Assembly.GetExecutingAssembly().GetName().Name)
{
return Assembly.GetExecutingAssembly();
}
if (this.config.Enhancements.Value.ResolveAssembly)
{
foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
{
if (a.GetName().Name == an.Name && a.GetName().Version >= an.Version)
{
return a;
}
}
}
return null;
}

public event Action<Plugin, Config>? OnConfigLoad;
Expand Down Expand Up @@ -341,5 +369,9 @@ private void PostTShockInitialize()
OTAPI.Hooks.Netplay.CreateTcpListener += this.OTHook_Socket_OnCreate;
this.InitCommands();
this.OnReload(new ReloadEventArgs(TSPlayer.Server));
if (this.config.Enhancements.Value.IPv6DualStack)
{
Terraria.Program.LaunchParameters.Add("-ip", System.Net.IPAddress.IPv6Any.ToString());
}
}
}
2 changes: 2 additions & 0 deletions Core/Plugin.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@
<AssemblyName>Chireiden.TShock.Omni</AssemblyName>
<RootNamespace>Chireiden.TShock.Omni</RootNamespace>
<Deterministic>true</Deterministic>
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
<LangVersion>preview</LangVersion>
</PropertyGroup>

<PropertyGroup>
<Authors>Chireiden</Authors>
<Description>Yet another misc plugin for TShock</Description>
<PackageProjectUrl>https://github.com/sgkoishi/yaaiomni</PackageProjectUrl>
<AssemblyTitle>$(PackageProjectUrl)</AssemblyTitle>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageType>TShockPlugin</PackageType>
Expand Down
26 changes: 26 additions & 0 deletions Core/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,32 @@ public static void OnceFlag(string key, Action action)
}
}

public static void AssemblyMutex(TerrariaApi.Server.TerrariaPlugin plugin)
{
var asm = plugin.GetType().Assembly;
foreach (var ld in AppDomain.CurrentDomain.GetAssemblies())
{
if (ld.GetName().Name == asm.GetName().Name && ld != asm)
{
var dict = ((Dictionary<string, System.Reflection.Assembly>) typeof(TerrariaApi.Server.ServerApi)
.GetField("loadedAssemblies", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)!
.GetValue(null)!)
.ToDictionary(kvp => kvp.Value, kvp => kvp.Key)!;
var em = $"Duplicate {plugin.Name} loaded:";
if (dict.TryGetValue(ld, out var fileNameWithoutExtension))
{
em += Environment.NewLine + $" --> Loaded: {fileNameWithoutExtension} (v{ld.GetName().Version})";
}
if (dict.TryGetValue(asm, out fileNameWithoutExtension))
{
em += Environment.NewLine + $" --> Current: {fileNameWithoutExtension} (v{asm.GetName().Version})";
}
TerrariaApi.Server.ServerApi.LogWriter.PluginWriteLine(plugin, em, System.Diagnostics.TraceLevel.Error);
throw new OperationCanceledException($"{asm.GetName().Name} already loaded.");
}
}
}

public class ConsolePlayer : TSPlayer
{
public static ConsolePlayer Instance = new ConsolePlayer("Console");
Expand Down
13 changes: 10 additions & 3 deletions Misc/Commands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,15 @@ private void Command_WhereIs(CommandArgs args)

foreach (var command in c)
{
var aliases = string.Join(", ", command.Names.Skip(1).Select(x => TShockAPI.Commands.Specifier + x));
args.Player.SendSuccessMessage($"{TShockAPI.Commands.Specifier}{command.Name} ({aliases}) :");
if (command.Names.Count == 1)
{
args.Player.SendSuccessMessage($"{TShockAPI.Commands.Specifier}{command.Name} :");
}
else
{
var aliases = string.Join(", ", command.Names.Skip(1).Select(x => TShockAPI.Commands.Specifier + x));
args.Player.SendSuccessMessage($"{TShockAPI.Commands.Specifier}{command.Name} ({aliases}) :");
}
var method = command.CommandDelegate.Method;
var sig = $"{method.DeclaringType?.FullName}.{method.Name}";
args.Player.SendInfoMessage($" Signature: {sig}");
Expand Down Expand Up @@ -179,7 +186,7 @@ private void Command_TicksPerSec(CommandArgs args)
}
}

private void Detour_UpdateConnectedClients(Action orig)
private void Detour_UpdateConnectedClients(On.Terraria.Netplay.orig_UpdateConnectedClients orig)
{
orig();
if (!Terraria.Netplay.HasClients)
Expand Down
2 changes: 2 additions & 0 deletions Misc/Misc.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@
<AssemblyName>Chireiden.TShock.Omni.Misc</AssemblyName>
<RootNamespace>Chireiden.TShock.Omni</RootNamespace>
<Deterministic>true</Deterministic>
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
<LangVersion>preview</LangVersion>
</PropertyGroup>

<PropertyGroup>
<Authors>Chireiden</Authors>
<Description>Yet another misc plugin for TShock - the miscellaneous part</Description>
<PackageProjectUrl>https://github.com/sgkoishi/yaaiomni</PackageProjectUrl>
<AssemblyTitle>$(PackageProjectUrl)</AssemblyTitle>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageType>TShockPlugin</PackageType>
Expand Down
27 changes: 10 additions & 17 deletions Misc/Plugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,30 +18,17 @@ public partial class Plugin : TerrariaPlugin

public string ConfigPath = Path.Combine(TShockAPI.TShock.SavePath, "chireiden.omni.misc.json");
private const BindingFlags _bfany = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
public Config config;
public Config config = null!;

public Plugin(Main game) : base(game)
{
this.config = new Config();
this.LoadConfig(Utils.ConsolePlayer.Instance);
this.Detour(
nameof(this.Detour_Lava_HitEffect),
typeof(NPC)
.GetMethod(nameof(NPC.HitEffect), _bfany),
this.Detour_Lava_HitEffect);
this.Detour(
nameof(this.Detour_Lava_KillTile),
typeof(WorldGen)
.GetMethod(nameof(WorldGen.KillTile), _bfany),
this.Detour_Lava_KillTile);
this.Detour(
nameof(this.Detour_UpdateConnectedClients),
typeof(Terraria.Netplay).GetMethod(nameof(Terraria.Netplay.UpdateConnectedClients), _bfany),
this.Detour_UpdateConnectedClients);
}

public override void Initialize()
{
Utils.AssemblyMutex(this);
this.config = new Config();
this.LoadConfig(Utils.ConsolePlayer.Instance);
var core = ServerApi.Plugins.Get<Omni.Plugin>() ?? throw new Exception("Core Omni is null.");
Utils.OnceFlag("chireiden.omni.misc.preset.lock", () =>
{
Expand Down Expand Up @@ -100,7 +87,10 @@ public override void Initialize()

this.InitCommands();

On.Terraria.NPC.HitEffect += this.Detour_Lava_HitEffect;
On.Terraria.MessageBuffer.GetData += this.MMHook_PatchVersion_GetData;
On.Terraria.WorldGen.KillTile += this.Detour_Lava_KillTile;
On.Terraria.Netplay.UpdateConnectedClients += this.Detour_UpdateConnectedClients;
OTAPI.Hooks.MessageBuffer.GetData += this.OTHook_Permission_SyncLoadout;
OTAPI.Hooks.MessageBuffer.GetData += this.OTHook_Permission_SummonBoss;
TShockAPI.GetDataHandlers.TogglePvp.Register(this.GDHook_Permission_TogglePvp);
Expand Down Expand Up @@ -144,7 +134,10 @@ protected override void Dispose(bool disposing)
{
if (disposing)
{
On.Terraria.NPC.HitEffect -= this.Detour_Lava_HitEffect;
On.Terraria.MessageBuffer.GetData -= this.MMHook_PatchVersion_GetData;
On.Terraria.WorldGen.KillTile -= this.Detour_Lava_KillTile;
On.Terraria.Netplay.UpdateConnectedClients -= this.Detour_UpdateConnectedClients;
OTAPI.Hooks.MessageBuffer.GetData -= this.OTHook_Permission_SyncLoadout;
OTAPI.Hooks.MessageBuffer.GetData -= this.OTHook_Permission_SummonBoss;
TShockAPI.GetDataHandlers.TogglePvp.UnRegister(this.GDHook_Permission_TogglePvp);
Expand Down

0 comments on commit 221da80

Please sign in to comment.