Добавлено логирование типов с атрибутом HarmonyPatch и улучшена обработка ошибок в системе патчей; удалены неиспользуемые зависимости из систем блокировки IP

This commit is contained in:
Vigers Ray 2026-01-05 06:21:36 +01:00
parent c567e2d111
commit 7fbbd51d23
4 changed files with 52 additions and 47 deletions

View file

@ -1,4 +1,4 @@
using System;
using System.Linq;
using System.Reflection;
using HarmonyLib;
@ -29,6 +29,21 @@ public sealed class PatchManager
var patchedCount = 0;
var failedCount = 0;
// Логируем все типы с атрибутом HarmonyPatch для диагностики
var allPatchTypes = new List<Type>();
foreach (var type in types)
{
if (type.Assembly == assembly)
{
var hasHarmonyPatch = type.GetCustomAttributes(typeof(HarmonyPatch), false).Length > 0;
if (hasHarmonyPatch)
{
allPatchTypes.Add(type);
}
}
}
sawmill.Info($"Found {allPatchTypes.Count} patch types: {string.Join(", ", allPatchTypes.Select(t => t.FullName))}");
foreach (var type in types)
{
try
@ -37,14 +52,37 @@ public sealed class PatchManager
if (type.Assembly != assembly)
continue;
// Проверяем, есть ли атрибут HarmonyPatch
var hasHarmonyPatch = type.GetCustomAttributes(typeof(HarmonyPatch), false).Length > 0;
if (!hasHarmonyPatch)
continue;
sawmill.Info($"Applying patch to type: {type.FullName}");
// Применяем патчи к типу
harmony.CreateClassProcessor(type).Patch();
var processor = harmony.CreateClassProcessor(type);
var patchInfo = processor.Patch();
if (patchInfo != null)
{
sawmill.Info($"Successfully patched type: {type.FullName}");
}
else
{
sawmill.Warning($"Patch returned null for type: {type.FullName}");
}
patchedCount++;
}
catch (Exception ex)
{
// Логируем ошибку, но продолжаем применять патчи к другим типам
sawmill.Warning($"Failed to patch type {type.FullName}: {ex.Message}");
sawmill.Warning($"Failed to patch type {type.FullName}: {ex.GetType().Name}: {ex.Message}");
if (ex.InnerException != null)
{
sawmill.Warning($"Inner exception: {ex.InnerException.GetType().Name}: {ex.InnerException.Message}");
}
sawmill.Warning($"Stack trace: {ex.StackTrace}");
failedCount++;
}
}

View file

@ -6,8 +6,6 @@ using System.Runtime.InteropServices;
using Content.Server.Administration.Managers;
using Content.Server.Chat.Managers;
using Content.Server.Connection.IPIntel;
using Content.Server.Connection.IPBlocking;
using Content.Shared.Connection.IPBlocking;
using Content.Server.Database;
using Content.Server.GameTicking;
using Content.Server.Preferences.Managers;
@ -61,7 +59,6 @@ namespace Content.Server.Connection
private readonly Dictionary<NetUserId, TimeSpan> _temporaryBypasses = [];
private readonly Dictionary<NetUserId, DateTime> _temporaryConnectionAllowed = [];
private IPIntel.IPIntel _ipintel = default!;
private IPBlockingSystem _ipBlockingSystem = default!;
public event EventHandler<PlayerConnectingWithBanEvent>? PlayerConnectingWithBan;
@ -76,14 +73,6 @@ namespace Content.Server.Connection
_ipintel = new IPIntel.IPIntel(new IPIntelApi(_http, _cfg), _db, _cfg, _logManager, _chatManager, _gameTiming);
// Инициализация системы блокировки IP
_ipBlockingSystem = new IPBlockingSystem();
IoCManager.Instance!.InjectDependencies(_ipBlockingSystem);
_ipBlockingSystem.Initialize();
// Регистрация в IoC для использования в других системах
IoCManager.Instance.RegisterInstance<IIPBlockingSystem>(_ipBlockingSystem, true);
IoCManager.Instance!.TryResolveType(out _sponsorsMgr);
_netMgr.Connecting += NetMgrOnConnecting;
_netMgr.AssignUserIdCallback = AssignUserIdCallback;
@ -135,16 +124,6 @@ namespace Content.Server.Connection
{
_sawmill.Error("IPIntel update failed:" + e);
}
// Периодическая очистка истекших блокировок IP
try
{
_ipBlockingSystem.Update();
}
catch (Exception e)
{
_sawmill.Error("IPBlockingSystem update failed:" + e);
}
}
private async Task NetMgrOnConnecting(NetConnectingArgs e)

View file

@ -1,11 +1,7 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net;
using Content.Shared.CCVar;
using Robust.Shared.Configuration;
using Robust.Shared.IoC;
using Robust.Shared.Log;
using Robust.Shared.Timing;
using Content.Shared.Connection.IPBlocking;
@ -19,7 +15,6 @@ public sealed class IPBlockingSystem : IIPBlockingSystem
{
[Dependency] private readonly IConfigurationManager _cfg = default!;
[Dependency] private readonly ILogManager _logManager = default!;
[Dependency] private readonly IGameTiming _gameTiming = default!;
private readonly ConcurrentDictionary<IPAddress, DateTime> _blockedIPs = new();
private ISawmill _sawmill = default!;
@ -88,12 +83,16 @@ public sealed class IPBlockingSystem : IIPBlockingSystem
public bool CheckAndBlockSuspiciousLength(IPAddress ip, int length, string context)
{
if (!_enabled)
{
_sawmill.Debug($"IP blocking is disabled, skipping block for {ip}");
return false;
}
// Проверяем на отрицательные или слишком большие значения
if (length < 0 || length > _maxResponseLength)
{
var reason = $"Подозрительная длина ответа: {length} байт (контекст: {context})";
_sawmill.Info($"Blocking IP {ip} for suspicious length {length} in context {context}");
BlockIP(ip, reason);
return true;
}
@ -101,14 +100,6 @@ public sealed class IPBlockingSystem : IIPBlockingSystem
return false;
}
/// <summary>
/// Получает максимально допустимую длину ответа.
/// </summary>
public int GetMaxResponseLength()
{
return _maxResponseLength;
}
/// <summary>
/// Очищает истекшие блокировки. Должен вызываться периодически.
/// </summary>
@ -144,13 +135,5 @@ public sealed class IPBlockingSystem : IIPBlockingSystem
_sawmill.Info($"IP {ip} разблокирован вручную");
}
}
/// <summary>
/// Получает количество заблокированных IP-адресов.
/// </summary>
public int GetBlockedCount()
{
return _blockedIPs.Count;
}
}

View file

@ -7,6 +7,11 @@ namespace Content.Shared.Connection.IPBlocking;
/// </summary>
public interface IIPBlockingSystem
{
/// <summary>
/// Инициализирует систему блокировки IP.
/// </summary>
void Initialize();
/// <summary>
/// Проверяет, заблокирован ли указанный IP-адрес.
/// </summary>
@ -19,8 +24,8 @@ public interface IIPBlockingSystem
bool CheckAndBlockSuspiciousLength(IPAddress ip, int length, string context);
/// <summary>
/// Получает максимально допустимую длину ответа.
/// Очищает истекшие блокировки. Должен вызываться периодически.
/// </summary>
int GetMaxResponseLength();
void Update();
}