Some fixes and security updates
This commit is contained in:
parent
43acf366af
commit
68e6fa2353
22 changed files with 1114 additions and 58 deletions
80
src/GsDChat.Server/Services/ConnectionLimiterService.cs
Normal file
80
src/GsDChat.Server/Services/ConnectionLimiterService.cs
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GsDChat.Server.Services;
|
||||
|
||||
public class ConnectionLimiterService
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, int> _ipConnections = new();
|
||||
private readonly int _maxConnectionsPerIp;
|
||||
private readonly int _maxGlobalConnections;
|
||||
private int _globalConnectionCount;
|
||||
|
||||
public ConnectionLimiterService(int maxConnectionsPerIp = 10, int maxGlobalConnections = 100)
|
||||
{
|
||||
_maxConnectionsPerIp = maxConnectionsPerIp;
|
||||
_maxGlobalConnections = maxGlobalConnections;
|
||||
}
|
||||
|
||||
public bool TryAddConnection(string ipAddress)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(ipAddress))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
lock (this)
|
||||
{
|
||||
if (_globalConnectionCount >= _maxGlobalConnections)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var currentIpCount = _ipConnections.GetOrAdd(ipAddress, 0);
|
||||
if (currentIpCount >= _maxConnectionsPerIp)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_ipConnections.AddOrUpdate(ipAddress, 1, (_, existing) => existing + 1);
|
||||
_globalConnectionCount++;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public void RemoveConnection(string ipAddress)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(ipAddress))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
lock (this)
|
||||
{
|
||||
if (_ipConnections.TryGetValue(ipAddress, out var count))
|
||||
{
|
||||
if (count <= 1)
|
||||
{
|
||||
_ipConnections.TryRemove(ipAddress, out _);
|
||||
}
|
||||
else
|
||||
{
|
||||
_ipConnections.AddOrUpdate(ipAddress, 0, (_, existing) => existing - 1);
|
||||
}
|
||||
_globalConnectionCount = Math.Max(0, _globalConnectionCount - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int GetConnectionCount(string ipAddress)
|
||||
{
|
||||
return _ipConnections.TryGetValue(ipAddress, out var count) ? count : 0;
|
||||
}
|
||||
|
||||
public int GetGlobalConnectionCount()
|
||||
{
|
||||
return _globalConnectionCount;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue