Inital Commit
This commit is contained in:
@@ -1,108 +1,98 @@
|
||||
#region References
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
#endregion
|
||||
|
||||
namespace Server.Network
|
||||
{
|
||||
public class BufferPool
|
||||
{
|
||||
public static List<BufferPool> Pools { get; private set; }
|
||||
public class BufferPool
|
||||
{
|
||||
private static readonly ConcurrentDictionary<BufferPool, string> m_Pools = new ConcurrentDictionary<BufferPool, string>();
|
||||
|
||||
static BufferPool()
|
||||
{
|
||||
Pools = new List<BufferPool>();
|
||||
}
|
||||
public static ReadOnlyCollection<BufferPool> Pools => (ReadOnlyCollection<BufferPool>)m_Pools.Keys;
|
||||
|
||||
private readonly string m_Name;
|
||||
private readonly string m_Name;
|
||||
|
||||
private readonly int m_InitialCapacity;
|
||||
private readonly int m_BufferSize;
|
||||
private readonly int m_InitialCapacity;
|
||||
private readonly int m_BufferSize;
|
||||
|
||||
private int m_Misses;
|
||||
private volatile int m_Misses;
|
||||
|
||||
private readonly Queue<byte[]> m_FreeBuffers;
|
||||
private readonly ConcurrentQueue<byte[]> m_FreeBuffers = new ConcurrentQueue<byte[]>();
|
||||
|
||||
public int Count
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (this)
|
||||
return m_FreeBuffers.Count;
|
||||
}
|
||||
}
|
||||
public int Count
|
||||
{
|
||||
get
|
||||
{
|
||||
return m_FreeBuffers.Count;
|
||||
}
|
||||
}
|
||||
|
||||
public void GetInfo(
|
||||
out string name,
|
||||
out int freeCount,
|
||||
out int initialCapacity,
|
||||
out int currentCapacity,
|
||||
out int bufferSize,
|
||||
out int misses)
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
name = m_Name;
|
||||
freeCount = m_FreeBuffers.Count;
|
||||
initialCapacity = m_InitialCapacity;
|
||||
currentCapacity = m_InitialCapacity * (1 + m_Misses);
|
||||
bufferSize = m_BufferSize;
|
||||
misses = m_Misses;
|
||||
}
|
||||
}
|
||||
public void GetInfo(
|
||||
out string name,
|
||||
out int freeCount,
|
||||
out int initialCapacity,
|
||||
out int currentCapacity,
|
||||
out int bufferSize,
|
||||
out int misses)
|
||||
{
|
||||
name = m_Name;
|
||||
freeCount = m_FreeBuffers.Count;
|
||||
initialCapacity = m_InitialCapacity;
|
||||
currentCapacity = m_InitialCapacity * (1 + m_Misses);
|
||||
bufferSize = m_BufferSize;
|
||||
misses = m_Misses;
|
||||
}
|
||||
|
||||
public BufferPool(string name, int initialCapacity, int bufferSize)
|
||||
{
|
||||
m_Name = name;
|
||||
public BufferPool(string name, int initialCapacity, int bufferSize)
|
||||
{
|
||||
m_Name = name;
|
||||
|
||||
m_InitialCapacity = initialCapacity;
|
||||
m_BufferSize = bufferSize;
|
||||
m_InitialCapacity = initialCapacity;
|
||||
m_BufferSize = bufferSize;
|
||||
|
||||
m_FreeBuffers = new Queue<byte[]>(initialCapacity);
|
||||
while (m_FreeBuffers.Count < initialCapacity)
|
||||
{
|
||||
m_FreeBuffers.Enqueue(new byte[bufferSize]);
|
||||
}
|
||||
|
||||
for (int i = 0; i < initialCapacity; ++i)
|
||||
{
|
||||
m_FreeBuffers.Enqueue(new byte[bufferSize]);
|
||||
}
|
||||
m_Pools[this] = name;
|
||||
}
|
||||
|
||||
lock (Pools)
|
||||
Pools.Add(this);
|
||||
}
|
||||
public byte[] AcquireBuffer()
|
||||
{
|
||||
if (m_FreeBuffers.TryDequeue(out var buffer))
|
||||
{
|
||||
return buffer;
|
||||
}
|
||||
|
||||
public byte[] AcquireBuffer()
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
if (m_FreeBuffers.Count > 0)
|
||||
{
|
||||
return m_FreeBuffers.Dequeue();
|
||||
}
|
||||
++m_Misses;
|
||||
|
||||
++m_Misses;
|
||||
while (m_FreeBuffers.Count < m_InitialCapacity - 1)
|
||||
{
|
||||
m_FreeBuffers.Enqueue(new byte[m_BufferSize]);
|
||||
}
|
||||
|
||||
for (int i = 0; i < m_InitialCapacity; ++i)
|
||||
{
|
||||
m_FreeBuffers.Enqueue(new byte[m_BufferSize]);
|
||||
}
|
||||
return new byte[m_BufferSize];
|
||||
}
|
||||
|
||||
return m_FreeBuffers.Dequeue();
|
||||
}
|
||||
}
|
||||
public void ReleaseBuffer(byte[] buffer)
|
||||
{
|
||||
if (buffer == null || buffer.Length != m_BufferSize)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
public void ReleaseBuffer(byte[] buffer)
|
||||
{
|
||||
if (buffer == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
Array.Clear(buffer, 0, buffer.Length);
|
||||
|
||||
lock (this)
|
||||
m_FreeBuffers.Enqueue(buffer);
|
||||
}
|
||||
m_FreeBuffers.Enqueue(buffer);
|
||||
}
|
||||
|
||||
public void Free()
|
||||
{
|
||||
lock (Pools)
|
||||
Pools.Remove(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
public void Free()
|
||||
{
|
||||
m_Pools.TryRemove(this, out _);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+515
-249
@@ -1,280 +1,546 @@
|
||||
#region References
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
#endregion
|
||||
|
||||
namespace Server.Network
|
||||
{
|
||||
public class Listener : IDisposable
|
||||
{
|
||||
private Socket m_Listener;
|
||||
private PingListener _PingListener;
|
||||
public class Listener : IDisposable
|
||||
{
|
||||
private static readonly byte[][] m_HttpFilters =
|
||||
{
|
||||
Encoding.UTF8.GetBytes("GET"),
|
||||
Encoding.UTF8.GetBytes("POST"),
|
||||
Encoding.UTF8.GetBytes("PUT"),
|
||||
Encoding.UTF8.GetBytes("DELETE"),
|
||||
Encoding.UTF8.GetBytes("HEAD"),
|
||||
Encoding.UTF8.GetBytes("OPTIONS"),
|
||||
Encoding.UTF8.GetBytes("PATCH"),
|
||||
Encoding.UTF8.GetBytes("CONNECT"),
|
||||
Encoding.UTF8.GetBytes("TRACE"),
|
||||
};
|
||||
|
||||
private readonly Queue<Socket> m_Accepted;
|
||||
private readonly object m_AcceptedSyncRoot;
|
||||
private static readonly BufferPool m_ByteBufferPool = new BufferPool("Login Byte", 1024, 1);
|
||||
private static readonly BufferPool m_PeekBufferPool = new BufferPool("Login Peek", 1024, 4);
|
||||
private static readonly BufferPool m_SeedBufferPool = new BufferPool("Login Seed [0xEF]", 1024, PacketHandlers.LoginSeedLength);
|
||||
|
||||
private readonly AsyncCallback m_OnAccept;
|
||||
public static IPAddress Address => Config.Get("Server.Listen", IPAddress.Any);
|
||||
|
||||
private static readonly Socket[] m_EmptySockets = new Socket[0];
|
||||
public static int Port => Config.Get("Server.Port", 2593);
|
||||
|
||||
public static IPEndPoint[] EndPoints { get; set; }
|
||||
public static IPEndPoint[] EndPoints { get; set; } =
|
||||
{
|
||||
new IPEndPoint(Address, Port)
|
||||
};
|
||||
|
||||
public Listener(IPEndPoint ipep)
|
||||
{
|
||||
m_Accepted = new Queue<Socket>();
|
||||
m_AcceptedSyncRoot = ((ICollection)m_Accepted).SyncRoot;
|
||||
private long m_SliceTime, m_SliceCounter;
|
||||
|
||||
m_Listener = Bind(ipep);
|
||||
private long m_Counter, m_AcceptsPerSecond;
|
||||
|
||||
if (m_Listener == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
public long AcceptsPerSecond => m_AcceptsPerSecond;
|
||||
|
||||
DisplayListener();
|
||||
_PingListener = new PingListener(ipep);
|
||||
private Socket m_Listener;
|
||||
|
||||
m_OnAccept = OnAccept;
|
||||
try
|
||||
{
|
||||
IAsyncResult res = m_Listener.BeginAccept(m_OnAccept, m_Listener);
|
||||
}
|
||||
catch (SocketException ex)
|
||||
{
|
||||
NetState.TraceException(ex);
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{ }
|
||||
}
|
||||
private readonly ConcurrentQueue<SocketState> m_Accepted = new ConcurrentQueue<SocketState>();
|
||||
|
||||
private Socket Bind(IPEndPoint ipep)
|
||||
{
|
||||
Socket s = new Socket(ipep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
|
||||
private readonly AutoResetEvent m_AcceptLimiter = new AutoResetEvent(true);
|
||||
|
||||
try
|
||||
{
|
||||
s.LingerState.Enabled = false;
|
||||
|
||||
// Default is 'false' starting Windows Vista and Server 2008. Source: https://msdn.microsoft.com/en-us/library/system.net.sockets.socket.exclusiveaddressuse(v=vs.110).aspx?f=255&MSPPError=-2147217396
|
||||
s.ExclusiveAddressUse = false;
|
||||
private readonly Thread m_AcceptThread;
|
||||
|
||||
s.Bind(ipep);
|
||||
s.Listen(8);
|
||||
private SocketAsyncEventArgs m_AcceptArgs;
|
||||
|
||||
return s;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
if (e is SocketException)
|
||||
{
|
||||
SocketException se = (SocketException)e;
|
||||
public Listener(IPEndPoint ipep)
|
||||
{
|
||||
m_Listener = Bind(ipep);
|
||||
|
||||
if (se.ErrorCode == 10048)
|
||||
{
|
||||
// WSAEADDRINUSE
|
||||
Utility.PushColor(ConsoleColor.Red);
|
||||
Console.WriteLine("Listener Failed: {0}:{1} (In Use)", ipep.Address, ipep.Port);
|
||||
Utility.PopColor();
|
||||
}
|
||||
else if (se.ErrorCode == 10049)
|
||||
{
|
||||
// WSAEADDRNOTAVAIL
|
||||
Utility.PushColor(ConsoleColor.Red);
|
||||
Console.WriteLine("Listener Failed: {0}:{1} (Unavailable)", ipep.Address, ipep.Port);
|
||||
Utility.PopColor();
|
||||
}
|
||||
else
|
||||
{
|
||||
Utility.PushColor(ConsoleColor.Red);
|
||||
Console.WriteLine("Listener Exception:");
|
||||
Console.WriteLine(e);
|
||||
Utility.PopColor();
|
||||
}
|
||||
}
|
||||
m_SliceTime = Core.TickCount;
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void DisplayListener()
|
||||
{
|
||||
IPEndPoint ipep = m_Listener.LocalEndPoint as IPEndPoint;
|
||||
|
||||
if (ipep == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (ipep.Address.Equals(IPAddress.Any) || ipep.Address.Equals(IPAddress.IPv6Any))
|
||||
{
|
||||
var adapters = NetworkInterface.GetAllNetworkInterfaces();
|
||||
foreach (NetworkInterface adapter in adapters)
|
||||
{
|
||||
IPInterfaceProperties properties = adapter.GetIPProperties();
|
||||
foreach (IPAddressInformation unicast in properties.UnicastAddresses)
|
||||
{
|
||||
if (ipep.AddressFamily == unicast.Address.AddressFamily)
|
||||
{
|
||||
Utility.PushColor(ConsoleColor.Green);
|
||||
Console.WriteLine("Listening: {0}:{1}", unicast.Address, ipep.Port);
|
||||
Utility.PopColor();
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
try {
|
||||
Console.WriteLine( "Listening: {0}:{1}", IPAddress.Loopback, ipep.Port );
|
||||
IPHostEntry iphe = Dns.GetHostEntry( Dns.GetHostName() );
|
||||
IPAddress[] ip = iphe.AddressList;
|
||||
for ( int i = 0; i < ip.Length; ++i )
|
||||
Console.WriteLine( "Listening: {0}:{1}", ip[i], ipep.Port );
|
||||
}
|
||||
catch { }
|
||||
*/
|
||||
}
|
||||
else
|
||||
{
|
||||
Utility.PushColor(ConsoleColor.Green);
|
||||
Console.WriteLine("Listening: {0}:{1}", ipep.Address, ipep.Port);
|
||||
Utility.PopColor();
|
||||
}
|
||||
|
||||
Utility.PushColor(ConsoleColor.DarkGreen);
|
||||
Console.WriteLine(@"----------------------------------------------------------------------");
|
||||
Utility.PopColor();
|
||||
}
|
||||
|
||||
private void OnAccept(IAsyncResult asyncResult)
|
||||
{
|
||||
Socket listener = (Socket)asyncResult.AsyncState;
|
||||
|
||||
Socket accepted = null;
|
||||
|
||||
try
|
||||
{
|
||||
accepted = listener.EndAccept(asyncResult);
|
||||
}
|
||||
catch (SocketException ex)
|
||||
{
|
||||
NetState.TraceException(ex);
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (accepted != null)
|
||||
{
|
||||
if (VerifySocket(accepted))
|
||||
{
|
||||
Enqueue(accepted);
|
||||
}
|
||||
else
|
||||
{
|
||||
Release(accepted);
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
listener.BeginAccept(m_OnAccept, listener);
|
||||
}
|
||||
catch (SocketException ex)
|
||||
{
|
||||
NetState.TraceException(ex);
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{ }
|
||||
}
|
||||
|
||||
private bool VerifySocket(Socket socket)
|
||||
{
|
||||
try
|
||||
{
|
||||
SocketConnectEventArgs args = new SocketConnectEventArgs(socket);
|
||||
|
||||
EventSink.InvokeSocketConnect(args);
|
||||
|
||||
return args.AllowConnection;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
NetState.TraceException(ex);
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void Enqueue(Socket socket)
|
||||
{
|
||||
lock (m_AcceptedSyncRoot)
|
||||
{
|
||||
m_Accepted.Enqueue(socket);
|
||||
}
|
||||
|
||||
Core.Set();
|
||||
}
|
||||
|
||||
private void Release(Socket socket)
|
||||
{
|
||||
try
|
||||
{
|
||||
socket.Shutdown(SocketShutdown.Both);
|
||||
}
|
||||
catch (SocketException ex)
|
||||
{
|
||||
NetState.TraceException(ex);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
socket.Close();
|
||||
}
|
||||
catch (SocketException ex)
|
||||
{
|
||||
NetState.TraceException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public Socket[] Slice()
|
||||
{
|
||||
Socket[] array;
|
||||
|
||||
lock (m_AcceptedSyncRoot)
|
||||
{
|
||||
if (m_Accepted.Count == 0)
|
||||
{
|
||||
return m_EmptySockets;
|
||||
}
|
||||
|
||||
array = m_Accepted.ToArray();
|
||||
m_Accepted.Clear();
|
||||
}
|
||||
|
||||
return array;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Socket socket = Interlocked.Exchange(ref m_Listener, null);
|
||||
|
||||
if (socket != null)
|
||||
{
|
||||
socket.Close();
|
||||
}
|
||||
|
||||
if (_PingListener == null)
|
||||
if (m_Listener == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_PingListener.Dispose();
|
||||
_PingListener = null;
|
||||
DisplayListener();
|
||||
|
||||
m_AcceptThread = new Thread(AcceptLoop)
|
||||
{
|
||||
Name = $"Login Accept Processor",
|
||||
Priority = ThreadPriority.AboveNormal,
|
||||
};
|
||||
|
||||
m_AcceptThread.Start();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Socket Bind(IPEndPoint ipep)
|
||||
{
|
||||
Socket s = new Socket(ipep.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
|
||||
{
|
||||
SendTimeout = 1000,
|
||||
ReceiveTimeout = 1000,
|
||||
ExclusiveAddressUse = false,
|
||||
UseOnlyOverlappedIO = false,
|
||||
NoDelay = true,
|
||||
LingerState =
|
||||
{
|
||||
Enabled = true,
|
||||
LingerTime = 0,
|
||||
},
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
s.Bind(ipep);
|
||||
s.Listen(1000);
|
||||
|
||||
return s;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
if (e is SocketException se)
|
||||
{
|
||||
if (se.ErrorCode == 10048)
|
||||
{
|
||||
// WSAEADDRINUSE
|
||||
Utility.PushColor(ConsoleColor.Red);
|
||||
Console.WriteLine("Listener Failed: {0}:{1} (In Use)", ipep.Address, ipep.Port);
|
||||
Utility.PopColor();
|
||||
}
|
||||
else if (se.ErrorCode == 10049)
|
||||
{
|
||||
// WSAEADDRNOTAVAIL
|
||||
Utility.PushColor(ConsoleColor.Red);
|
||||
Console.WriteLine("Listener Failed: {0}:{1} (Unavailable)", ipep.Address, ipep.Port);
|
||||
Utility.PopColor();
|
||||
}
|
||||
else
|
||||
{
|
||||
Utility.PushColor(ConsoleColor.Red);
|
||||
Console.WriteLine("Listener Exception:");
|
||||
Console.WriteLine(e);
|
||||
Utility.PopColor();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void DisplayListener()
|
||||
{
|
||||
if (!(m_Listener.LocalEndPoint is IPEndPoint ipep))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (ipep.Address.Equals(IPAddress.Any) || ipep.Address.Equals(IPAddress.IPv6Any))
|
||||
{
|
||||
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
|
||||
|
||||
foreach (NetworkInterface adapter in adapters)
|
||||
{
|
||||
IPInterfaceProperties properties = adapter.GetIPProperties();
|
||||
|
||||
foreach (IPAddressInformation unicast in properties.UnicastAddresses)
|
||||
{
|
||||
if (ipep.AddressFamily == unicast.Address.AddressFamily)
|
||||
{
|
||||
Utility.PushColor(ConsoleColor.Green);
|
||||
Console.WriteLine("Listening: {0}:{1}", unicast.Address, ipep.Port);
|
||||
Utility.PopColor();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Utility.PushColor(ConsoleColor.Green);
|
||||
Console.WriteLine("Listening: {0}:{1}", ipep.Address, ipep.Port);
|
||||
Utility.PopColor();
|
||||
}
|
||||
|
||||
Utility.PushColor(ConsoleColor.DarkGreen);
|
||||
Console.WriteLine(@"----------------------------------------------------------------------");
|
||||
Utility.PopColor();
|
||||
}
|
||||
|
||||
private SocketAsyncEventArgs Reset(ref SocketAsyncEventArgs e)
|
||||
{
|
||||
if (e == null)
|
||||
{
|
||||
e = new SocketAsyncEventArgs();
|
||||
|
||||
e.Completed += OnAccept;
|
||||
}
|
||||
|
||||
e.UserToken = this;
|
||||
e.AcceptSocket = null;
|
||||
e.RemoteEndPoint = null;
|
||||
|
||||
e.SocketFlags = 0;
|
||||
e.SocketError = 0;
|
||||
|
||||
e.DisconnectReuseSocket = true;
|
||||
|
||||
return e;
|
||||
}
|
||||
|
||||
[STAThread]
|
||||
private void AcceptLoop()
|
||||
{
|
||||
while (m_Listener != null)
|
||||
{
|
||||
Accept();
|
||||
}
|
||||
}
|
||||
|
||||
private void Accept()
|
||||
{
|
||||
if (!m_AcceptLimiter.WaitOne(10))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (m_Listener == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
SocketAsyncEventArgs e = Reset(ref m_AcceptArgs);
|
||||
|
||||
bool iocp;
|
||||
|
||||
try
|
||||
{
|
||||
iocp = m_Listener.AcceptAsync(e);
|
||||
}
|
||||
catch
|
||||
{
|
||||
iocp = false;
|
||||
}
|
||||
|
||||
if (!iocp)
|
||||
{
|
||||
OnAccept(e);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnAccept(object sender, SocketAsyncEventArgs e)
|
||||
{
|
||||
OnAccept(e);
|
||||
}
|
||||
|
||||
private void OnAccept(SocketAsyncEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
Socket accepted = e.AcceptSocket;
|
||||
SocketError error = e.SocketError;
|
||||
|
||||
m_AcceptArgs = Reset(ref e);
|
||||
|
||||
if (accepted == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Interlocked.Increment(ref m_Counter);
|
||||
|
||||
accepted.NoDelay = true;
|
||||
|
||||
if (error != 0)
|
||||
{
|
||||
Release(false, ref accepted);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
accepted.SendTimeout = 1000;
|
||||
accepted.ReceiveTimeout = 1000;
|
||||
|
||||
_ = ThreadPool.QueueUserWorkItem(o =>
|
||||
{
|
||||
Socket s = (Socket)o;
|
||||
|
||||
if (ValidateSequence(s, out byte[] seed))
|
||||
{
|
||||
Enqueue(s, seed);
|
||||
}
|
||||
else
|
||||
{
|
||||
Release(false, ref s);
|
||||
}
|
||||
}, accepted);
|
||||
}
|
||||
catch
|
||||
{
|
||||
Release(false, ref accepted);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
m_AcceptLimiter.Set();
|
||||
}
|
||||
}
|
||||
|
||||
private bool ValidateSequence(Socket socket, out byte[] buffer)
|
||||
{
|
||||
buffer = null;
|
||||
|
||||
byte[] peek;
|
||||
|
||||
try
|
||||
{
|
||||
peek = m_PeekBufferPool.AcquireBuffer();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
int recv = socket.Receive(peek, peek.Length, SocketFlags.None);
|
||||
|
||||
if (recv < peek.Length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
bool allow = false;
|
||||
|
||||
int index = 0;
|
||||
|
||||
byte packetID = peek[index++];
|
||||
|
||||
if (packetID == 0xEF)
|
||||
{
|
||||
byte[] packet = m_SeedBufferPool.AcquireBuffer();
|
||||
|
||||
try
|
||||
{
|
||||
var diff = packet.Length - peek.Length;
|
||||
|
||||
recv = socket.Receive(packet, peek.Length, diff, SocketFlags.None);
|
||||
|
||||
if (recv == diff)
|
||||
{
|
||||
Buffer.BlockCopy(peek, 0, packet, 0, peek.Length);
|
||||
|
||||
uint seed = readU32(packet, ref index);
|
||||
|
||||
if (seed != 0)
|
||||
{
|
||||
uint clientMaj = readU32(packet, ref index);
|
||||
uint clientMin = readU32(packet, ref index);
|
||||
uint clientRev = readU32(packet, ref index);
|
||||
uint clientPat = readU32(packet, ref index);
|
||||
|
||||
uint version = (clientMaj << 24) | (clientMin << 16) | (clientRev << 8) | clientPat;
|
||||
|
||||
if (version != 0)
|
||||
{
|
||||
allow = true;
|
||||
|
||||
buffer = packet.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
m_SeedBufferPool.ReleaseBuffer(packet);
|
||||
}
|
||||
}
|
||||
else if (!Match(peek))
|
||||
{
|
||||
index = packetID = 0;
|
||||
|
||||
uint seed = readU32(peek, ref index);
|
||||
|
||||
if (seed != 0)
|
||||
{
|
||||
var one = m_ByteBufferPool.AcquireBuffer();
|
||||
|
||||
try
|
||||
{
|
||||
recv = socket.Receive(one, 0, one.Length, SocketFlags.None);
|
||||
|
||||
if (recv == one.Length)
|
||||
{
|
||||
packetID = one[0];
|
||||
|
||||
if (!MessagePump.CheckEncrypted(packetID))
|
||||
{
|
||||
allow = true;
|
||||
|
||||
buffer = new byte[peek.Length + one.Length];
|
||||
|
||||
Buffer.BlockCopy(peek, 0, buffer, 0, peek.Length);
|
||||
Buffer.BlockCopy(one, 0, buffer, peek.Length, one.Length);
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
m_ByteBufferPool.ReleaseBuffer(one);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return allow;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
m_PeekBufferPool.ReleaseBuffer(peek);
|
||||
}
|
||||
|
||||
uint readU32(byte[] b, ref int i)
|
||||
{
|
||||
return (uint)((b[i++] << 24) | (b[i++] << 16) | (b[i++] << 8) | b[i++]);
|
||||
}
|
||||
}
|
||||
|
||||
private bool Match(byte[] buffer)
|
||||
{
|
||||
for (int i = 0; i < m_HttpFilters.Length; i++)
|
||||
{
|
||||
byte[] filter = m_HttpFilters[i];
|
||||
|
||||
if (filter?.Length > 0)
|
||||
{
|
||||
IEnumerable<byte> fseq = filter;
|
||||
IEnumerable<byte> pseq = buffer;
|
||||
|
||||
if (filter.Length > buffer.Length)
|
||||
{
|
||||
fseq = fseq.Take(buffer.Length);
|
||||
}
|
||||
else if (buffer.Length > filter.Length)
|
||||
{
|
||||
pseq = pseq.Take(filter.Length);
|
||||
}
|
||||
|
||||
if (Enumerable.SequenceEqual(fseq, pseq))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void Enqueue(Socket socket, byte[] seed)
|
||||
{
|
||||
m_Accepted.Enqueue(new SocketState(socket, seed));
|
||||
|
||||
Core.Set();
|
||||
}
|
||||
|
||||
private void Release(bool graceful, ref Socket socket)
|
||||
{
|
||||
if (socket != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (graceful)
|
||||
{
|
||||
try
|
||||
{
|
||||
socket.Shutdown(SocketShutdown.Both);
|
||||
}
|
||||
catch (SocketException ex)
|
||||
{
|
||||
NetState.TraceException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
if (socket.LingerState != null)
|
||||
{
|
||||
socket.LingerState.Enabled = true;
|
||||
socket.LingerState.LingerTime = graceful ? 1 : 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
socket.LingerState = new LingerOption(true, graceful ? 1 : 0);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
finally
|
||||
{
|
||||
socket.Close();
|
||||
|
||||
socket = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerable<SocketState> Slice()
|
||||
{
|
||||
long now = Core.TickCount;
|
||||
|
||||
if (now - m_SliceTime >= 1000)
|
||||
{
|
||||
var count = m_Counter;
|
||||
|
||||
Interlocked.Exchange(ref m_SliceTime, now);
|
||||
Interlocked.Exchange(ref m_AcceptsPerSecond, count - m_SliceCounter);
|
||||
Interlocked.Exchange(ref m_SliceCounter, count);
|
||||
}
|
||||
|
||||
int limit = Math.Min(m_Accepted.Count, 100);
|
||||
|
||||
while (--limit >= 0 && m_Accepted.TryDequeue(out SocketState accepted))
|
||||
{
|
||||
Socket socket = accepted.Socket;
|
||||
|
||||
SocketConnectEventArgs args = new SocketConnectEventArgs(socket);
|
||||
|
||||
EventSink.InvokeSocketConnect(args);
|
||||
|
||||
if (args.AllowConnection)
|
||||
{
|
||||
yield return accepted;
|
||||
}
|
||||
else
|
||||
{
|
||||
Release(true, ref socket);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Socket socket = Interlocked.Exchange(ref m_Listener, null);
|
||||
|
||||
socket?.Close();
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct SocketState
|
||||
{
|
||||
public readonly Socket Socket;
|
||||
public readonly byte[] Seed;
|
||||
|
||||
public SocketState(Socket socket, byte[] seed)
|
||||
{
|
||||
Socket = socket;
|
||||
Seed = seed;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#region References
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Sockets;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
|
||||
using Server.Diagnostics;
|
||||
@@ -9,15 +9,17 @@ using Server.Diagnostics;
|
||||
|
||||
namespace Server.Network
|
||||
{
|
||||
public class MessagePump
|
||||
public static class MessagePump
|
||||
{
|
||||
private Queue<NetState> m_Queue;
|
||||
private Queue<NetState> m_WorkingQueue;
|
||||
private readonly Queue<NetState> m_Throttled;
|
||||
private static readonly ConcurrentQueue<NetState> m_Queue = new ConcurrentQueue<NetState>();
|
||||
|
||||
public Listener[] Listeners { get; set; }
|
||||
|
||||
public MessagePump()
|
||||
private static readonly ConcurrentQueue<NetState> m_Throttled = new ConcurrentQueue<NetState>();
|
||||
|
||||
public static Listener[] Listeners { get; private set; }
|
||||
|
||||
public static long AcceptsPerSecond => Listeners.Sum(l => l.AcceptsPerSecond);
|
||||
|
||||
public static void Start()
|
||||
{
|
||||
var ipep = Listener.EndPoints;
|
||||
|
||||
@@ -44,13 +46,9 @@ namespace Server.Network
|
||||
}
|
||||
}
|
||||
while (!success);
|
||||
|
||||
m_Queue = new Queue<NetState>();
|
||||
m_WorkingQueue = new Queue<NetState>();
|
||||
m_Throttled = new Queue<NetState>();
|
||||
}
|
||||
|
||||
public void AddListener(Listener l)
|
||||
public static void AddListener(Listener l)
|
||||
{
|
||||
var old = Listeners;
|
||||
|
||||
@@ -64,15 +62,13 @@ namespace Server.Network
|
||||
Listeners[old.Length] = l;
|
||||
}
|
||||
|
||||
private void CheckListener()
|
||||
private static void CheckListener()
|
||||
{
|
||||
foreach (Listener l in Listeners)
|
||||
{
|
||||
var accepted = l.Slice();
|
||||
|
||||
foreach (Socket s in accepted)
|
||||
foreach (SocketState state in l.Slice())
|
||||
{
|
||||
NetState ns = new NetState(s, this);
|
||||
NetState ns = new NetState(state);
|
||||
|
||||
ns.Start();
|
||||
|
||||
@@ -104,50 +100,41 @@ namespace Server.Network
|
||||
|
||||
private static string[] _NoDisplay =
|
||||
{
|
||||
"192.99.10.155",
|
||||
"192.99.69.21",
|
||||
"54.39.99.106",
|
||||
};
|
||||
|
||||
public void OnReceive(NetState ns)
|
||||
public static void OnReceive(NetState ns)
|
||||
{
|
||||
lock (this)
|
||||
m_Queue.Enqueue(ns);
|
||||
m_Queue.Enqueue(ns);
|
||||
|
||||
Core.Set();
|
||||
}
|
||||
|
||||
public void Slice()
|
||||
{
|
||||
CheckListener();
|
||||
public static void Slice()
|
||||
{
|
||||
CheckListener();
|
||||
|
||||
lock (this)
|
||||
{
|
||||
var temp = m_WorkingQueue;
|
||||
m_WorkingQueue = m_Queue;
|
||||
m_Queue = temp;
|
||||
}
|
||||
var limit = m_Queue.Count;
|
||||
|
||||
while (m_WorkingQueue.Count > 0)
|
||||
{
|
||||
NetState ns = m_WorkingQueue.Dequeue();
|
||||
while (--limit >= 0 && m_Queue.TryDequeue(out NetState ns))
|
||||
{
|
||||
if (ns.Running)
|
||||
{
|
||||
HandleReceive(ns);
|
||||
}
|
||||
}
|
||||
|
||||
if (ns.Running)
|
||||
{
|
||||
HandleReceive(ns);
|
||||
}
|
||||
}
|
||||
|
||||
lock (this)
|
||||
{
|
||||
while (m_Throttled.Count > 0)
|
||||
{
|
||||
m_Queue.Enqueue(m_Throttled.Dequeue());
|
||||
}
|
||||
}
|
||||
}
|
||||
while (m_Throttled.TryDequeue(out NetState ns))
|
||||
{
|
||||
if (ns.Running)
|
||||
{
|
||||
m_Queue.Enqueue(ns);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private const int BufferSize = 4096;
|
||||
private readonly BufferPool m_Buffers = new BufferPool("Processor", 4, BufferSize);
|
||||
private static readonly BufferPool m_Buffers = new BufferPool("Processor", 4, BufferSize);
|
||||
|
||||
public static bool HandleSeed(NetState ns, ByteQueue buffer)
|
||||
{
|
||||
@@ -187,24 +174,36 @@ namespace Server.Network
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool CheckEncrypted(NetState ns, int packetID)
|
||||
{
|
||||
if (!ns.SentFirstPacket && packetID != 0xF0 && packetID != 0xF1 && packetID != 0xCF && packetID != 0x80 &&
|
||||
packetID != 0x91 && packetID != 0xA4 && packetID != 0xEF && packetID != 0xE4 && packetID != 0xFF)
|
||||
{
|
||||
Utility.PushColor(ConsoleColor.Red);
|
||||
Console.WriteLine("Client: {0}: Encrypted Client Unsupported", ns);
|
||||
Utility.PopColor();
|
||||
|
||||
ns.Dispose();
|
||||
public static bool CheckEncrypted(NetState ns, int packetID)
|
||||
{
|
||||
if (ns.SentFirstPacket || !CheckEncrypted(packetID))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
Utility.PushColor(ConsoleColor.Red);
|
||||
Console.WriteLine("Client: {0}: Encrypted Client Unsupported", ns);
|
||||
Utility.PopColor();
|
||||
|
||||
return false;
|
||||
ns.Dispose();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool CheckEncrypted(int packetID)
|
||||
{
|
||||
return packetID != 0xF0
|
||||
&& packetID != 0xF1
|
||||
&& packetID != 0xCF
|
||||
&& packetID != 0x80
|
||||
&& packetID != 0x91
|
||||
&& packetID != 0xA4
|
||||
&& packetID != 0xEF
|
||||
&& packetID != 0xE4
|
||||
&& packetID != 0xFF;
|
||||
}
|
||||
|
||||
public void HandleReceive(NetState ns)
|
||||
public static void HandleReceive(NetState ns)
|
||||
{
|
||||
ByteQueue buffer = ns.Buffer;
|
||||
|
||||
|
||||
+1108
-1102
File diff suppressed because it is too large
Load Diff
@@ -48,9 +48,11 @@ namespace Server.Network
|
||||
private static readonly EncodedPacketHandler[] m_EncodedHandlersLow;
|
||||
private static readonly Dictionary<int, EncodedPacketHandler> m_EncodedHandlersHigh;
|
||||
|
||||
public static PacketHandler[] Handlers { get { return m_Handlers; } }
|
||||
public static PacketHandler[] Handlers { get { return m_Handlers; } }
|
||||
|
||||
static PacketHandlers()
|
||||
public static int LoginSeedLength => Handlers[0xEF]?.Length ?? -1;
|
||||
|
||||
static PacketHandlers()
|
||||
{
|
||||
m_Handlers = new PacketHandler[0x100];
|
||||
m_6017Handlers = new PacketHandler[0x100];
|
||||
|
||||
+76
-103
@@ -1,6 +1,7 @@
|
||||
#region References
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Threading;
|
||||
#endregion
|
||||
|
||||
namespace Server.Network
|
||||
@@ -9,29 +10,20 @@ namespace Server.Network
|
||||
{
|
||||
public class Gram
|
||||
{
|
||||
private static readonly Stack<Gram> _pool = new Stack<Gram>();
|
||||
private static readonly ConcurrentQueue<Gram> _pool = new ConcurrentQueue<Gram>();
|
||||
|
||||
public static Gram Acquire()
|
||||
{
|
||||
lock (_pool)
|
||||
{
|
||||
Gram gram;
|
||||
public static Gram Acquire()
|
||||
{
|
||||
if (!_pool.TryDequeue(out Gram gram))
|
||||
{
|
||||
gram = new Gram();
|
||||
}
|
||||
|
||||
if (_pool.Count > 0)
|
||||
{
|
||||
gram = _pool.Pop();
|
||||
}
|
||||
else
|
||||
{
|
||||
gram = new Gram();
|
||||
}
|
||||
gram._buffer = AcquireBuffer();
|
||||
gram._length = 0;
|
||||
|
||||
gram._buffer = AcquireBuffer();
|
||||
gram._length = 0;
|
||||
|
||||
return gram;
|
||||
}
|
||||
}
|
||||
return gram;
|
||||
}
|
||||
|
||||
private byte[] _buffer;
|
||||
private int _length;
|
||||
@@ -58,14 +50,12 @@ namespace Server.Network
|
||||
return write;
|
||||
}
|
||||
|
||||
public void Release()
|
||||
{
|
||||
lock (_pool)
|
||||
{
|
||||
_pool.Push(this);
|
||||
ReleaseBuffer(_buffer);
|
||||
}
|
||||
}
|
||||
public void Release()
|
||||
{
|
||||
_pool.Enqueue(this);
|
||||
|
||||
ReleaseBuffer(_buffer);
|
||||
}
|
||||
}
|
||||
|
||||
private static int m_CoalesceBufferSize = 512;
|
||||
@@ -74,77 +64,60 @@ namespace Server.Network
|
||||
public static int CoalesceBufferSize
|
||||
{
|
||||
get { return m_CoalesceBufferSize; }
|
||||
set
|
||||
{
|
||||
if (m_CoalesceBufferSize == value)
|
||||
{
|
||||
return;
|
||||
}
|
||||
set
|
||||
{
|
||||
if (m_CoalesceBufferSize == value)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
BufferPool old = m_UnusedBuffers;
|
||||
m_UnusedBuffers?.Free();
|
||||
|
||||
lock (old)
|
||||
{
|
||||
if (m_UnusedBuffers != null)
|
||||
{
|
||||
m_UnusedBuffers.Free();
|
||||
}
|
||||
|
||||
m_CoalesceBufferSize = value;
|
||||
m_UnusedBuffers = new BufferPool("Coalesced", 2048, m_CoalesceBufferSize);
|
||||
}
|
||||
}
|
||||
m_CoalesceBufferSize = value;
|
||||
m_UnusedBuffers = new BufferPool("Coalesced", 2048, m_CoalesceBufferSize);
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] AcquireBuffer()
|
||||
{
|
||||
lock (m_UnusedBuffers)
|
||||
return m_UnusedBuffers.AcquireBuffer();
|
||||
return m_UnusedBuffers.AcquireBuffer();
|
||||
}
|
||||
|
||||
public static void ReleaseBuffer(byte[] buffer)
|
||||
{
|
||||
lock (m_UnusedBuffers)
|
||||
if (buffer != null && buffer.Length == m_CoalesceBufferSize)
|
||||
{
|
||||
m_UnusedBuffers.ReleaseBuffer(buffer);
|
||||
}
|
||||
}
|
||||
public static void ReleaseBuffer(byte[] buffer)
|
||||
{
|
||||
if (buffer != null && buffer.Length == m_CoalesceBufferSize)
|
||||
{
|
||||
m_UnusedBuffers.ReleaseBuffer(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
private readonly Queue<Gram> _pending;
|
||||
private readonly ConcurrentQueue<Gram> _pending = new ConcurrentQueue<Gram>();
|
||||
|
||||
private Gram _buffered;
|
||||
private volatile Gram _buffered;
|
||||
|
||||
public bool IsFlushReady { get { return (_pending.Count == 0 && _buffered != null); } }
|
||||
|
||||
public bool IsEmpty { get { return (_pending.Count == 0 && _buffered == null); } }
|
||||
|
||||
public SendQueue()
|
||||
{
|
||||
_pending = new Queue<Gram>();
|
||||
}
|
||||
|
||||
public Gram CheckFlushReady()
|
||||
{
|
||||
Gram gram = _buffered;
|
||||
_pending.Enqueue(_buffered);
|
||||
_buffered = null;
|
||||
Gram gram = Interlocked.Exchange(ref _buffered, null);
|
||||
|
||||
_pending.Enqueue(gram);
|
||||
|
||||
return gram;
|
||||
}
|
||||
|
||||
public Gram Dequeue()
|
||||
{
|
||||
Gram gram = null;
|
||||
if (_pending.TryDequeue(out Gram gram))
|
||||
{
|
||||
gram?.Release();
|
||||
gram = null;
|
||||
|
||||
if (_pending.Count > 0)
|
||||
{
|
||||
_pending.Dequeue().Release();
|
||||
|
||||
if (_pending.Count > 0)
|
||||
{
|
||||
gram = _pending.Peek();
|
||||
}
|
||||
}
|
||||
if (_pending.TryPeek(out Gram peek))
|
||||
gram = peek;
|
||||
}
|
||||
|
||||
return gram;
|
||||
}
|
||||
@@ -177,41 +150,41 @@ namespace Server.Network
|
||||
throw new ArgumentException("Offset and length do not point to a valid segment within the buffer.");
|
||||
}
|
||||
|
||||
int existingBytes = (_pending.Count * m_CoalesceBufferSize) + (_buffered == null ? 0 : _buffered.Length);
|
||||
int existingBytes = (_pending.Count * m_CoalesceBufferSize) + (_buffered?.Length ?? 0);
|
||||
|
||||
if ((existingBytes + length) > PendingCap)
|
||||
{
|
||||
throw new CapacityExceededException();
|
||||
}
|
||||
|
||||
Gram gram = null;
|
||||
Gram gram = null;
|
||||
|
||||
while (length > 0)
|
||||
{
|
||||
if (_buffered == null)
|
||||
{
|
||||
// nothing yet buffered
|
||||
_buffered = Gram.Acquire();
|
||||
}
|
||||
while (length > 0)
|
||||
{
|
||||
if (_buffered == null)
|
||||
{
|
||||
// nothing yet buffered
|
||||
_buffered = Gram.Acquire();
|
||||
}
|
||||
|
||||
int bytesWritten = _buffered.Write(buffer, offset, length);
|
||||
int bytesWritten = _buffered.Write(buffer, offset, length);
|
||||
|
||||
offset += bytesWritten;
|
||||
length -= bytesWritten;
|
||||
offset += bytesWritten;
|
||||
length -= bytesWritten;
|
||||
|
||||
if (_buffered.IsFull)
|
||||
{
|
||||
if (_pending.Count == 0)
|
||||
{
|
||||
gram = _buffered;
|
||||
}
|
||||
if (_buffered.IsFull)
|
||||
{
|
||||
if (_pending.Count == 0)
|
||||
{
|
||||
gram = _buffered;
|
||||
}
|
||||
|
||||
_pending.Enqueue(_buffered);
|
||||
_buffered = null;
|
||||
}
|
||||
}
|
||||
_pending.Enqueue(_buffered);
|
||||
_buffered = null;
|
||||
}
|
||||
}
|
||||
|
||||
return gram;
|
||||
return gram;
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
@@ -222,9 +195,9 @@ namespace Server.Network
|
||||
_buffered = null;
|
||||
}
|
||||
|
||||
while (_pending.Count > 0)
|
||||
while (_pending.TryDequeue(out Gram gram))
|
||||
{
|
||||
_pending.Dequeue().Release();
|
||||
gram?.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -236,4 +209,4 @@ namespace Server.Network
|
||||
: base("Too much data pending.")
|
||||
{ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user