fix: Cleans up core code (#1187)

**Only one functional change**
* Fixes a bug in LogFactory where `Warning` is being logged as `Information`

Non-functional changes:
* Updates/Fixes copyright headers
* Removes namespace scopes for core files.

View with [whitespace off](https://github.com/modernuo/ModernUO/pull/1187/files?w=1).
This commit is contained in:
Kamron Batman 2022-10-10 21:47:08 -07:00 committed by GitHub
parent 0138d40bda
commit f268d5d4e2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
262 changed files with 28527 additions and 28646 deletions

View file

@ -1,6 +1,6 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2020 - ModernUO Development Team *
* Copyright 2019-2022 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: TcpServer.cs *
* *
@ -21,188 +21,187 @@ using System.Net.NetworkInformation;
using System.Net.Sockets;
using Server.Logging;
namespace Server.Network
namespace Server.Network;
public static class TcpServer
{
public static class TcpServer
private static readonly ILogger logger = LogFactory.GetLogger(typeof(TcpServer));
private const int MaxConnectionsPerLoop = 250;
// Sanity. 256 * 1024 * 4096 = ~1.3GB of ram
public static int MaxConnections { get; set; } = 4096;
private const long _listenerErrorMessageDelay = 10000; // 10 seconds
private static long _nextMaximumSocketsReachedMessage;
// AccountLoginReject BadComm
private static readonly byte[] _socketRejected = { 0x82, 0xFF };
public static IPEndPoint[] ListeningAddresses { get; private set; }
public static Socket[] Listeners { get; private set; }
public static HashSet<NetState> Instances { get; } = new(2048);
private static readonly ConcurrentQueue<NetState> _connectedQueue = new();
public static void Configure()
{
private static readonly ILogger logger = LogFactory.GetLogger(typeof(TcpServer));
MaxConnections = ServerConfiguration.GetOrUpdateSetting("tcpServer.maxConnections", MaxConnections);
}
private const int MaxConnectionsPerLoop = 250;
public static void Start()
{
HashSet<IPEndPoint> listeningAddresses = new HashSet<IPEndPoint>();
List<Socket> listeners = new List<Socket>();
// Sanity. 256 * 1024 * 4096 = ~1.3GB of ram
public static int MaxConnections { get; set; } = 4096;
private const long _listenerErrorMessageDelay = 10000; // 10 seconds
private static long _nextMaximumSocketsReachedMessage;
// AccountLoginReject BadComm
private static readonly byte[] _socketRejected = { 0x82, 0xFF };
public static IPEndPoint[] ListeningAddresses { get; private set; }
public static Socket[] Listeners { get; private set; }
public static HashSet<NetState> Instances { get; } = new(2048);
private static readonly ConcurrentQueue<NetState> _connectedQueue = new();
public static void Configure()
foreach (var ipep in ServerConfiguration.Listeners)
{
MaxConnections = ServerConfiguration.GetOrUpdateSetting("tcpServer.maxConnections", MaxConnections);
}
public static void Start()
{
HashSet<IPEndPoint> listeningAddresses = new HashSet<IPEndPoint>();
List<Socket> listeners = new List<Socket>();
foreach (var ipep in ServerConfiguration.Listeners)
var listener = CreateListener(ipep);
if (listener == null)
{
var listener = CreateListener(ipep);
if (listener == null)
{
continue;
}
if (ipep.Address.Equals(IPAddress.Any) || ipep.Address.Equals(IPAddress.IPv6Any))
{
listeningAddresses.UnionWith(GetListeningAddresses(ipep));
}
else
{
listeningAddresses.Add(ipep);
}
listeners.Add(listener);
listener.BeginAcceptingSockets();
continue;
}
foreach (var ipep in listeningAddresses)
if (ipep.Address.Equals(IPAddress.Any) || ipep.Address.Equals(IPAddress.IPv6Any))
{
logger.Information("Listening: {Address}:{Port}", ipep.Address, ipep.Port);
listeningAddresses.UnionWith(GetListeningAddresses(ipep));
}
else
{
listeningAddresses.Add(ipep);
}
ListeningAddresses = listeningAddresses.ToArray();
Listeners = listeners.ToArray();
listeners.Add(listener);
listener.BeginAcceptingSockets();
}
public static void Shutdown()
foreach (var ipep in listeningAddresses)
{
foreach (var listener in Listeners)
logger.Information("Listening: {Address}:{Port}", ipep.Address, ipep.Port);
}
ListeningAddresses = listeningAddresses.ToArray();
Listeners = listeners.ToArray();
}
public static void Shutdown()
{
foreach (var listener in Listeners)
{
listener.Close();
}
}
public static IEnumerable<IPEndPoint> GetListeningAddresses(IPEndPoint ipep) =>
NetworkInterface.GetAllNetworkInterfaces().SelectMany(adapter =>
adapter.GetIPProperties().UnicastAddresses
.Where(uip => ipep.AddressFamily == uip.Address.AddressFamily)
.Select(uip => new IPEndPoint(uip.Address, ipep.Port))
);
public static Socket CreateListener(IPEndPoint ipep)
{
var listener = new Socket(ipep.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
{
LingerState = new LingerOption(false, 0),
ExclusiveAddressUse = true,
NoDelay = true
};
try
{
listener.Bind(ipep);
listener.Listen(32);
return listener;
}
catch (SocketException se)
{
// WSAEADDRINUSE
if (se.ErrorCode == 10048)
{
listener.Close();
logger.Warning("Listener: {Address}:{Port}: Failed (In Use)", ipep.Address, ipep.Port);
}
// WSAEADDRNOTAVAIL
else if (se.ErrorCode == 10049)
{
logger.Warning("Listener {Address}:{Port}: Failed (Unavailable)", ipep.Address, ipep.Port);
}
else
{
logger.Warning(se, "Listener Exception:");
}
}
public static IEnumerable<IPEndPoint> GetListeningAddresses(IPEndPoint ipep) =>
NetworkInterface.GetAllNetworkInterfaces().SelectMany(adapter =>
adapter.GetIPProperties().UnicastAddresses
.Where(uip => ipep.AddressFamily == uip.Address.AddressFamily)
.Select(uip => new IPEndPoint(uip.Address, ipep.Port))
);
return null;
}
public static Socket CreateListener(IPEndPoint ipep)
public static void Slice()
{
int count = 0;
while (++count <= MaxConnectionsPerLoop && _connectedQueue.TryDequeue(out var ns))
{
var listener = new Socket(ipep.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
{
LingerState = new LingerOption(false, 0),
ExclusiveAddressUse = true,
NoDelay = true
};
Instances.Add(ns);
ns.LogInfo($"Connected. [{Instances.Count} Online]");
}
}
private static async void BeginAcceptingSockets(this Socket listener)
{
while (true)
{
try
{
listener.Bind(ipep);
listener.Listen(32);
return listener;
}
catch (SocketException se)
{
// WSAEADDRINUSE
if (se.ErrorCode == 10048)
var socket = await listener.AcceptAsync();
var rejected = false;
if (Instances.Count >= MaxConnections)
{
logger.Warning("Listener: {Address}:{Port}: Failed (In Use)", ipep.Address, ipep.Port);
}
// WSAEADDRNOTAVAIL
else if (se.ErrorCode == 10049)
{
logger.Warning("Listener {Address}:{Port}: Failed (Unavailable)", ipep.Address, ipep.Port);
}
else
{
logger.Warning(se, "Listener Exception:");
}
}
rejected = true;
return null;
}
var ticks = Core.TickCount;
public static void Slice()
{
int count = 0;
while (++count <= MaxConnectionsPerLoop && _connectedQueue.TryDequeue(out var ns))
{
Instances.Add(ns);
ns.LogInfo($"Connected. [{Instances.Count} Online]");
}
}
private static async void BeginAcceptingSockets(this Socket listener)
{
while (true)
{
try
{
var socket = await listener.AcceptAsync();
var rejected = false;
if (Instances.Count >= MaxConnections)
if (_nextMaximumSocketsReachedMessage <= ticks)
{
rejected = true;
var ticks = Core.TickCount;
if (_nextMaximumSocketsReachedMessage <= ticks)
{
if (socket.RemoteEndPoint is IPEndPoint ipep)
{
var ip = ipep.Address.ToString();
logger.Warning("Listener {Address}: Failed (Maximum connections reached)", ip);
NetState.TraceDisconnect("Maximum connections reached.", ip);
}
_nextMaximumSocketsReachedMessage = ticks + _listenerErrorMessageDelay;
}
}
var args = new SocketConnectEventArgs(socket);
EventSink.InvokeSocketConnect(args);
if (!args.AllowConnection)
{
rejected = true;
if (socket.RemoteEndPoint is IPEndPoint ipep)
{
var ip = ipep.Address.ToString();
NetState.TraceDisconnect("Rejected by socket event handler", ip);
logger.Warning("Listener {Address}: Failed (Maximum connections reached)", ip);
NetState.TraceDisconnect("Maximum connections reached.", ip);
}
}
if (rejected)
{
socket.Send(_socketRejected, SocketFlags.None);
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
else
{
var ns = new NetState(socket);
_connectedQueue.Enqueue(ns);
_nextMaximumSocketsReachedMessage = ticks + _listenerErrorMessageDelay;
}
}
catch
var args = new SocketConnectEventArgs(socket);
EventSink.InvokeSocketConnect(args);
if (!args.AllowConnection)
{
// ignored
rejected = true;
if (socket.RemoteEndPoint is IPEndPoint ipep)
{
var ip = ipep.Address.ToString();
NetState.TraceDisconnect("Rejected by socket event handler", ip);
}
}
if (rejected)
{
socket.Send(_socketRejected, SocketFlags.None);
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
else
{
var ns = new NetState(socket);
_connectedQueue.Enqueue(ns);
}
}
catch
{
// ignored
}
}
}