Targets .NET Core 3.0 (#39)

This commit is contained in:
Kamron Batman 2019-08-02 17:53:18 -07:00 • committed by GitHub
parent 0993c03b70
commit 08bf44af9a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
125 changed files with 1473 additions and 14244 deletions

View file

@ -1,106 +0,0 @@
/***************************************************************************
* BufferPool.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System.Collections.Generic;
namespace Server.Network
{
public class BufferPool
{
private int m_BufferSize;
private Queue<byte[]> m_FreeBuffers;
private int m_InitialCapacity;
private int m_Misses;
private string m_Name;
public BufferPool(string name, int initialCapacity, int bufferSize)
{
m_Name = name;
m_InitialCapacity = initialCapacity;
m_BufferSize = bufferSize;
m_FreeBuffers = new Queue<byte[]>(initialCapacity);
for (int i = 0; i < initialCapacity; ++i)
m_FreeBuffers.Enqueue(new byte[bufferSize]);
lock (Pools)
{
Pools.Add(this);
}
}
public static List<BufferPool> Pools{ get; set; } = new List<BufferPool>();
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 byte[] AcquireBuffer()
{
lock (this)
{
if (m_FreeBuffers.Count > 0)
return m_FreeBuffers.Dequeue();
++m_Misses;
for (int i = 0; i < m_InitialCapacity; ++i)
m_FreeBuffers.Enqueue(new byte[m_BufferSize]);
return m_FreeBuffers.Dequeue();
}
}
public void ReleaseBuffer(byte[] buffer)
{
if (buffer == null)
return;
lock (this)
{
m_FreeBuffers.Enqueue(buffer);
}
}
public void Free()
{
lock (Pools)
{
Pools.Remove(this);
}
}
}
}

View file

@ -1,150 +0,0 @@
/***************************************************************************
* ByteQueue.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
namespace Server.Network
{
public class ByteQueue
{
private byte[] m_Buffer;
private int m_Head;
private int m_Tail;
public ByteQueue()
{
m_Buffer = new byte[2048];
}
public int Length{ get; private set; }
public void Clear()
{
m_Head = 0;
m_Tail = 0;
Length = 0;
}
private void SetCapacity(int capacity)
{
byte[] newBuffer = new byte[capacity];
if (Length > 0)
{
if (m_Head < m_Tail)
{
Buffer.BlockCopy(m_Buffer, m_Head, newBuffer, 0, Length);
}
else
{
Buffer.BlockCopy(m_Buffer, m_Head, newBuffer, 0, m_Buffer.Length - m_Head);
Buffer.BlockCopy(m_Buffer, 0, newBuffer, m_Buffer.Length - m_Head, m_Tail);
}
}
m_Head = 0;
m_Tail = Length;
m_Buffer = newBuffer;
}
public byte GetPacketID()
{
if (Length >= 1)
return m_Buffer[m_Head];
return 0xFF;
}
public int GetPacketLength()
{
if (Length >= 3)
return (m_Buffer[(m_Head + 1) % m_Buffer.Length] << 8) | m_Buffer[(m_Head + 2) % m_Buffer.Length];
return 0;
}
public int Dequeue(byte[] buffer, int offset, int size)
{
if (size > Length)
size = Length;
if (size == 0)
return 0;
if (m_Head < m_Tail)
{
Buffer.BlockCopy(m_Buffer, m_Head, buffer, offset, size);
}
else
{
int rightLength = m_Buffer.Length - m_Head;
if (rightLength >= size)
{
Buffer.BlockCopy(m_Buffer, m_Head, buffer, offset, size);
}
else
{
Buffer.BlockCopy(m_Buffer, m_Head, buffer, offset, rightLength);
Buffer.BlockCopy(m_Buffer, 0, buffer, offset + rightLength, size - rightLength);
}
}
m_Head = (m_Head + size) % m_Buffer.Length;
Length -= size;
if (Length == 0)
{
m_Head = 0;
m_Tail = 0;
}
return size;
}
public void Enqueue(byte[] buffer, int offset, int size)
{
if (Length + size > m_Buffer.Length)
SetCapacity((Length + size + 2047) & ~2047);
if (m_Head < m_Tail)
{
int rightLength = m_Buffer.Length - m_Tail;
if (rightLength >= size)
{
Buffer.BlockCopy(buffer, offset, m_Buffer, m_Tail, size);
}
else
{
Buffer.BlockCopy(buffer, offset, m_Buffer, m_Tail, rightLength);
Buffer.BlockCopy(buffer, offset + rightLength, m_Buffer, 0, size - rightLength);
}
}
else
{
Buffer.BlockCopy(buffer, offset, m_Buffer, m_Tail, size);
}
m_Tail = (m_Tail + size) % m_Buffer.Length;
Length += size;
}
}
}

View file

@ -37,4 +37,4 @@ namespace Server.Network
public bool Ingame{ get; }
}
}
}

View file

@ -20,7 +20,7 @@
namespace Server.Network
{
public class EncodedReader
public ref struct EncodedReader
{
private PacketReader m_Reader;
@ -29,47 +29,20 @@ namespace Server.Network
m_Reader = reader;
}
public byte[] Buffer => m_Reader.Buffer;
public void Trace(NetState state)
{
m_Reader.Trace(state);
}
public int ReadInt32()
{
if (m_Reader.ReadByte() != 0)
return 0;
public int ReadInt32() => m_Reader.ReadByte() != 0 ? 0 : m_Reader.ReadInt32();
return m_Reader.ReadInt32();
}
public Point3D ReadPoint3D() => m_Reader.ReadByte() != 3 ? Point3D.Zero :
new Point3D(m_Reader.ReadInt16(), m_Reader.ReadInt16(), m_Reader.ReadByte());
public Point3D ReadPoint3D()
{
if (m_Reader.ReadByte() != 3)
return Point3D.Zero;
public string ReadUnicodeStringSafe() => m_Reader.ReadByte() != 2 ? string.Empty :
m_Reader.ReadUnicodeStringSafe(m_Reader.ReadUInt16());
return new Point3D(m_Reader.ReadInt16(), m_Reader.ReadInt16(), m_Reader.ReadByte());
}
public string ReadUnicodeStringSafe()
{
if (m_Reader.ReadByte() != 2)
return "";
int length = m_Reader.ReadUInt16();
return m_Reader.ReadUnicodeStringSafe(length);
}
public string ReadUnicodeString()
{
if (m_Reader.ReadByte() != 2)
return "";
int length = m_Reader.ReadUInt16();
return m_Reader.ReadUnicodeString(length);
}
public string ReadUnicodeString() => m_Reader.ReadByte() != 2 ? string.Empty :
m_Reader.ReadUnicodeString(m_Reader.ReadUInt16());
}
}
}

View file

@ -19,58 +19,35 @@
***************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace Server.Network
{
public class Listener : IDisposable
public class Listener
{
private Socket m_Listener;
private Queue<Socket> m_Accepted;
private object m_AcceptedSyncRoot;
private SocketAsyncEventArgs m_EventArgs;
private static Socket[] m_EmptySockets = new Socket[0];
public static IPEndPoint[] EndPoints{ get; set; }
private Socket m_Socket;
private IPEndPoint m_EndPoint;
public Listener(IPEndPoint ipep)
{
m_Accepted = new Queue<Socket>();
m_AcceptedSyncRoot = ((ICollection)m_Accepted).SyncRoot;
#pragma warning disable IDE0068 // Use recommended dispose pattern
m_Socket = new Socket(ipep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
#pragma warning restore IDE0068 // Use recommended dispose pattern
m_Listener = Bind(ipep);
if (m_Listener == null)
return;
DisplayListener();
m_EventArgs = new SocketAsyncEventArgs();
m_EventArgs.Completed += Accept_Completion;
Accept_Start();
m_Socket.LingerState.Enabled = false;
m_Socket.ExclusiveAddressUse = false;
m_EndPoint = ipep;
}
private Socket Bind(IPEndPoint ipep)
public virtual async Task Start(MessagePump pump)
{
Socket s = new Socket(ipep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
s.LingerState.Enabled = false;
s.ExclusiveAddressUse = false;
s.Bind(ipep);
s.Listen(8);
return s;
m_Socket.Bind(m_EndPoint);
m_Socket.Listen(8);
}
catch (Exception e)
{
@ -79,12 +56,12 @@ namespace Server.Network
if (se.ErrorCode == 10048)
{
// WSAEADDRINUSE
Console.WriteLine("Listener Failed: {0}:{1} (In Use)", ipep.Address, ipep.Port);
Console.WriteLine("Listener Failed: {0}:{1} (In Use)", m_EndPoint.Address, m_EndPoint.Port);
}
else if (se.ErrorCode == 10049)
{
// WSAEADDRNOTAVAIL
Console.WriteLine("Listener Failed: {0}:{1} (Unavailable)", ipep.Address, ipep.Port);
Console.WriteLine("Listener Failed: {0}:{1} (Unavailable)", m_EndPoint.Address, m_EndPoint.Port);
}
else
{
@ -93,13 +70,35 @@ namespace Server.Network
}
}
return null;
m_Socket = null;
return;
}
DisplayListener();
while (true)
{
Socket s;
try
{
s = await m_Socket.AcceptAsync().ConfigureAwait(false);
}
catch (SocketException ex)
{
NetState.TraceException(ex);
continue;
}
if (VerifySocket(s))
_ = new NetState(s, pump);
else
Release(s);
}
}
private void DisplayListener()
{
if (!(m_Listener.LocalEndPoint is IPEndPoint ipep))
if (!(m_Socket.LocalEndPoint is IPEndPoint ipep))
return;
if (ipep.Address.Equals(IPAddress.Any) || ipep.Address.Equals(IPAddress.IPv6Any))
@ -112,17 +111,6 @@ namespace Server.Network
if (ipep.AddressFamily == unicast.Address.AddressFamily)
Console.WriteLine("Listening: {0}:{1}", unicast.Address, ipep.Port);
}
/*
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
{
@ -130,49 +118,6 @@ namespace Server.Network
}
}
private void Accept_Start()
{
bool result;
do
{
try
{
result = !m_Listener.AcceptAsync(m_EventArgs);
}
catch (SocketException ex)
{
NetState.TraceException(ex);
break;
}
catch (ObjectDisposedException)
{
break;
}
if (result)
Accept_Process(m_EventArgs);
} while (result);
}
private void Accept_Completion(object sender, SocketAsyncEventArgs e)
{
Accept_Process(e);
Accept_Start();
}
private void Accept_Process(SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success && VerifySocket(e.AcceptSocket))
Enqueue(e.AcceptSocket);
else
Release(e.AcceptSocket);
e.AcceptSocket = null;
}
private bool VerifySocket(Socket socket)
{
try
@ -191,16 +136,6 @@ namespace Server.Network
}
}
private void Enqueue(Socket socket)
{
lock (m_AcceptedSyncRoot)
{
m_Accepted.Enqueue(socket);
}
Core.Set();
}
private void Release(Socket socket)
{
try
@ -220,37 +155,20 @@ namespace Server.Network
{
NetState.TraceException(ex);
}
}
public Socket[] Slice()
{
Socket[] array;
lock (m_AcceptedSyncRoot)
try
{
if (m_Accepted.Count == 0)
return m_EmptySockets;
array = m_Accepted.ToArray();
m_Accepted.Clear();
socket.Dispose();
}
return array;
}
public void Dispose(bool disposing)
{
if (disposing)
catch (SocketException ex)
{
Socket socket = Interlocked.Exchange(ref m_Listener, null);
socket?.Close();
NetState.TraceException(ex);
}
}
public void Dispose()
{
Dispose(true);
Interlocked.Exchange<Socket>(ref m_Socket, null)?.Close();
GC.SuppressFinalize(this);
}
}

View file

@ -1,3 +1,4 @@
/***************************************************************************
* MessagePump.cs
* -------------------
@ -19,271 +20,57 @@
***************************************************************************/
using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Server.Diagnostics;
namespace Server.Network
{
public class MessagePump
{
private const int BufferSize = 4096;
private BufferPool m_Buffers = new BufferPool("Processor", 4, BufferSize);
private Queue<NetState> m_Queue;
private Queue<NetState> m_Throttled;
private Queue<NetState> m_WorkingQueue;
private ConcurrentQueue<Work> m_WorkQueue = new ConcurrentQueue<Work>();
public Listener[] Listeners => new Listener[0];
public MessagePump()
public void AddListener(IPEndPoint ipep)
{
IPEndPoint[] ipep = Listener.EndPoints;
Listeners = new Listener[ipep.Length];
bool success = false;
do
{
for (int i = 0; i < ipep.Length; i++)
{
Listener l = new Listener(ipep[i]);
if (!success)
success = true;
Listeners[i] = l;
}
if (!success)
{
Console.WriteLine("Retrying...");
Thread.Sleep(10000);
}
} while (!success);
m_Queue = new Queue<NetState>();
m_WorkingQueue = new Queue<NetState>();
m_Throttled = new Queue<NetState>();
Listener[] listeners = new Listener[Listeners.Length + 1];
Array.Copy(Listeners, listeners, Listeners.Length);
Listener listener = new Listener(ipep);
_ = listener.Start(this);
listeners[Listeners.Length] = listener;
}
public Listener[] Listeners{ get; set; }
public void AddListener(Listener l)
public void QueueWork(NetState ns, in ReadOnlySequence<byte> seq, OnPacketReceive onReceive)
{
Listener[] old = Listeners;
Listeners = new Listener[old.Length + 1];
for (int i = 0; i < old.Length; ++i)
Listeners[i] = old[i];
Listeners[old.Length] = l;
}
private void CheckListener()
{
for (int j = 0; j < Listeners.Length; ++j)
{
Socket[] accepted = Listeners[j].Slice();
for (int i = 0; i < accepted.Length; ++i)
{
NetState ns = new NetState(accepted[i], this);
ns.Start();
if (ns.Running)
Console.WriteLine("Client: {0}: Connected. [{1} Online]", ns, NetState.Instances.Count);
}
}
}
public void OnReceive(NetState ns)
{
lock (this)
{
m_Queue.Enqueue(ns);
}
m_WorkQueue.Enqueue(new Work(ns, seq, onReceive));
Core.Set();
}
public void Slice()
public void DoWork()
{
CheckListener();
lock (this)
int count = m_WorkQueue.Count;
while (count-- > 0)
{
Queue<NetState> temp = m_WorkingQueue;
m_WorkingQueue = m_Queue;
m_Queue = temp;
}
if (!m_WorkQueue.TryDequeue(out Work work))
break;
while (m_WorkingQueue.Count > 0)
{
NetState ns = m_WorkingQueue.Dequeue();
if (ns.Running)
HandleReceive(ns);
}
lock (this)
{
while (m_Throttled.Count > 0)
m_Queue.Enqueue(m_Throttled.Dequeue());
work.OnReceive(work.State, new PacketReader(work.Sequence));
}
}
private bool HandleSeed(NetState ns, ByteQueue buffer)
// TODO: Optimize this with a pool
private class Work
{
if (buffer.GetPacketID() == 0xEF)
public NetState State;
public ReadOnlySequence<byte> Sequence;
public OnPacketReceive OnReceive;
public Work(NetState ns, in ReadOnlySequence<byte> seq, OnPacketReceive onReceive)
{
// new packet in client 6.0.5.0 replaces the traditional seed method with a seed packet
// 0xEF = 239 = multicast IP, so this should never appear in a normal seed. So this is backwards compatible with older clients.
ns.Seeded = true;
return true;
}
if (buffer.Length >= 4)
{
byte[] m_Peek = new byte[4];
buffer.Dequeue(m_Peek, 0, 4);
int seed = (m_Peek[0] << 24) | (m_Peek[1] << 16) | (m_Peek[2] << 8) | m_Peek[3];
if (seed == 0)
{
Console.WriteLine("Login: {0}: Invalid client detected, disconnecting", ns);
ns.Dispose();
return false;
}
ns.m_Seed = seed;
ns.Seeded = true;
return true;
}
return false;
}
private bool CheckEncrypted(NetState ns, int packetID)
{
if (!ns.SentFirstPacket && packetID != 0xF0 && packetID != 0xF1 && packetID != 0xCF && packetID != 0x80 &&
packetID != 0x91 && packetID != 0xA4 && packetID != 0xEF)
{
Console.WriteLine("Client: {0}: Encrypted client detected, disconnecting", ns);
ns.Dispose();
return true;
}
return false;
}
public void HandleReceive(NetState ns)
{
ByteQueue buffer = ns.Buffer;
if (buffer == null || buffer.Length <= 0)
return;
lock (buffer)
{
if (!ns.Seeded)
if (!HandleSeed(ns, buffer))
return;
int length = buffer.Length;
while (length > 0 && ns.Running)
{
int packetID = buffer.GetPacketID();
if (CheckEncrypted(ns, packetID))
break;
PacketHandler handler = ns.GetHandler(packetID);
if (handler == null)
{
byte[] data = new byte[length];
length = buffer.Dequeue(data, 0, length);
new PacketReader(data, length, false).Trace(ns);
break;
}
int packetLength = handler.Length;
if (packetLength <= 0)
{
if (length >= 3)
{
packetLength = buffer.GetPacketLength();
if (packetLength < 3)
{
ns.Dispose();
break;
}
}
else
{
break;
}
}
if (length >= packetLength)
{
if (handler.Ingame)
{
if (ns.Mobile == null)
{
Console.WriteLine(
"Client: {0}: Sent ingame packet (0x{1:X2}) before having been attached to a mobile", ns,
packetID);
ns.Dispose();
break;
}
if (ns.Mobile.Deleted)
{
ns.Dispose();
break;
}
}
ThrottlePacketCallback throttler = handler.ThrottleCallback;
if (throttler?.Invoke(ns) == false)
{
m_Throttled.Enqueue(ns);
return;
}
PacketReceiveProfile prof = null;
if (Core.Profiling)
prof = PacketReceiveProfile.Acquire(packetID);
prof?.Start();
byte[] packetBuffer = BufferSize >= packetLength ? m_Buffers.AcquireBuffer() : new byte[packetLength];
packetLength = buffer.Dequeue(packetBuffer, 0, packetLength);
PacketReader r = new PacketReader(packetBuffer, packetLength, handler.Length != 0);
handler.OnReceive(ns, r);
length = buffer.Length;
if (BufferSize >= packetLength)
m_Buffers.ReleaseBuffer(packetBuffer);
prof?.Finish(packetLength);
}
else
{
break;
}
}
State = ns;
Sequence = seq;
OnReceive = onReceive;
}
}
}

File diff suppressed because it is too large Load diff

273
Server/Network/Packet.cs Normal file
View file

@ -0,0 +1,273 @@
/***************************************************************************
* Packet.cs
* -------------------
* begin : August 2, 2019
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Diagnostics;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace Server.Network
{
public abstract class Packet
{
private const int CompressorBufferSize = 0x10000;
private const int BufferSize = 4096;
private byte[] m_CompiledBuffer;
private int m_CompiledLength;
private int m_Length;
private State m_State;
protected PacketWriter m_Stream;
protected Packet(int packetID)
{
PacketID = packetID;
if (Core.Profiling)
{
PacketSendProfile prof = PacketSendProfile.Acquire(GetType());
prof.Increment();
}
}
protected Packet(int packetID, int length)
{
PacketID = packetID;
m_Length = length;
m_Stream = PacketWriter.CreateInstance(length); // new PacketWriter( length );
m_Stream.Write((byte)packetID);
if (Core.Profiling)
{
PacketSendProfile prof = PacketSendProfile.Acquire(GetType());
prof.Increment();
}
}
public int PacketID { get; }
public PacketWriter UnderlyingStream => m_Stream;
public void EnsureCapacity(int length)
{
m_Stream = PacketWriter.CreateInstance(length); // new PacketWriter( length );
m_Stream.Write((byte)PacketID);
m_Stream.Write((short)0);
}
public static Packet SetStatic(Packet p)
{
p.SetStatic();
return p;
}
public static Packet Acquire(Packet p)
{
p.Acquire();
return p;
}
public static void Release(ref Packet p)
{
p?.Release();
p = null;
}
public static void Release(Packet p)
{
p?.Release();
}
public void SetStatic()
{
m_State |= State.Static | State.Acquired;
}
public void Acquire()
{
m_State |= State.Acquired;
}
public void OnSend()
{
Core.Set(); // Is this still needed if this is done async?
if ((m_State & (State.Acquired | State.Static)) == 0)
Free();
}
private void Free()
{
if (m_CompiledBuffer == null)
return;
if ((m_State & State.Buffered) != 0)
ArrayPool<byte>.Shared.Return(m_CompiledBuffer);
m_State &= ~(State.Static | State.Acquired | State.Buffered);
m_CompiledBuffer = null;
}
public void Release()
{
if ((m_State & State.Acquired) != 0)
Free();
}
public byte[] Compile(bool compress, out int length)
{
lock (this)
{
if (m_CompiledBuffer == null)
{
if ((m_State & State.Accessed) == 0)
{
m_State |= State.Accessed;
}
else
{
if ((m_State & State.Warned) == 0)
{
m_State |= State.Warned;
try
{
using (StreamWriter op = new StreamWriter("net_opt.log", true))
{
op.WriteLine("Redundant compile for packet {0}, use Acquire() and Release()", GetType());
op.WriteLine(new StackTrace());
}
}
catch
{
// ignored
}
}
m_CompiledBuffer = new byte[0];
m_CompiledLength = 0;
length = m_CompiledLength;
return m_CompiledBuffer;
}
InternalCompile(compress);
}
length = m_CompiledLength;
return m_CompiledBuffer;
}
}
private void InternalCompile(bool compress)
{
if (m_Length == 0)
{
long streamLen = m_Stream.Length;
m_Stream.Seek(1, SeekOrigin.Begin);
m_Stream.Write((ushort)streamLen);
}
else if (m_Stream.Length != m_Length)
{
int diff = (int)m_Stream.Length - m_Length;
Console.WriteLine("Packet: 0x{0:X2}: Bad packet length! ({1}{2} bytes)", PacketID, diff >= 0 ? "+" : "",
diff);
}
MemoryStream ms = m_Stream.UnderlyingStream;
m_CompiledBuffer = ms.GetBuffer();
int length = (int)ms.Length;
if (compress)
{
byte[] buffer = ArrayPool<byte>.Shared.Rent(CompressorBufferSize);
Compression.Compress(m_CompiledBuffer, 0, length, buffer, ref length);
if (length <= 0)
{
Console.WriteLine("Warning: Compression buffer overflowed on packet 0x{0:X2} ('{1}') (length={2})",
PacketID, GetType().Name, length);
using (StreamWriter op = new StreamWriter("compression_overflow.log", true))
{
op.WriteLine("{0} Warning: Compression buffer overflowed on packet 0x{1:X2} ('{2}') (length={3})",
DateTime.UtcNow, PacketID, GetType().Name, length);
op.WriteLine(new StackTrace());
}
}
else
{
m_CompiledLength = length;
if ((m_State & State.Static) != 0)
{
m_CompiledBuffer = new byte[length];
Buffer.BlockCopy(buffer, 0, m_CompiledBuffer, 0, length);
ArrayPool<byte>.Shared.Return(buffer);
}
else
{
m_CompiledBuffer = buffer;
m_State |= State.Buffered;
}
}
}
else if (length > 0)
{
byte[] old = m_CompiledBuffer;
m_CompiledLength = length;
if ((m_State & State.Static) != 0)
m_CompiledBuffer = new byte[length];
else
{
m_CompiledBuffer = ArrayPool<byte>.Shared.Rent(length);
m_State |= State.Buffered;
}
Buffer.BlockCopy(old, 0, m_CompiledBuffer, 0, length);
}
PacketWriter.ReleaseInstance(m_Stream);
m_Stream = null;
}
[Flags]
private enum State
{
Inactive = 0x00,
Static = 0x01,
Acquired = 0x02,
Accessed = 0x04,
Buffered = 0x08,
Warned = 0x10
}
}
}

View file

@ -18,15 +18,17 @@
*
***************************************************************************/
using System;
namespace Server.Network
{
public delegate void OnPacketReceive(NetState state, PacketReader pvSrc);
public delegate bool ThrottlePacketCallback(NetState state);
public delegate TimeSpan ThrottlePacketCallback(NetState state);
public class PacketHandler
{
public PacketHandler(int packetID, int length, bool ingame, OnPacketReceive onReceive)
public PacketHandler(int packetID, long length, bool ingame, OnPacketReceive onReceive)
{
PacketID = packetID;
Length = length;
@ -36,7 +38,7 @@ namespace Server.Network
public int PacketID{ get; }
public int Length{ get; }
public long Length{ get; }
public OnPacketReceive OnReceive{ get; }
@ -44,4 +46,4 @@ namespace Server.Network
public bool Ingame{ get; }
}
}
}

View file

@ -19,8 +19,10 @@
***************************************************************************/
using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipelines;
using Server.Accounting;
using Server.ContextMenus;
using Server.Diagnostics;
@ -304,6 +306,102 @@ namespace Server.Network
ph.ThrottleCallback = t;
}
public static long ProcessPacket(MessagePump pump, NetState ns, in ReadOnlySequence<byte> seq)
{
PacketReader r = new PacketReader(seq);
if (!r.TryReadByte(out byte packetId))
{
ns.Dispose();
return -1;
}
if (!ns.Seeded)
{
if (packetId == 0xEF)
{
// new packet in client 6.0.5.0 replaces the traditional seed method with a seed packet
// 0xEF = 239 = multicast IP, so this should never appear in a normal seed. So this is backwards compatible with older clients.
ns.Seeded = true;
}
else
{
int seed = (packetId << 24) | (r.ReadByte() << 16) | (r.ReadByte() << 8) | r.ReadByte();
if (seed == 0)
{
Console.WriteLine("Login: {0}: Invalid client detected, disconnecting", ns);
ns.Dispose();
return -1;
}
ns.m_Seed = seed;
ns.Seeded = true;
return 4;
}
}
if (ns.CheckEncrypted(packetId))
{
ns.Dispose();
return -1;
}
// Get Handlers
PacketHandler handler = ns.GetHandler(packetId);
if (handler == null)
{
r.Trace(ns);
return -1;
}
long packetLength = handler.Length;
if (handler.Length <= 0 && r.Length >= 3)
{
packetLength = r.ReadUInt16();
if (packetLength < 3)
{
ns.Dispose();
return -1;
}
}
if (r.Length < packetLength)
return 0;
if (handler.Ingame && ns.Mobile?.Deleted != false)
{
Console.WriteLine(
"Client: {0}: Sent ingame packet (0x{1:X2}) without being attached to a valid mobile.",
ns,
packetId
);
ns.Dispose();
return -1;
}
ThrottlePacketCallback throttler = handler.ThrottleCallback;
TimeSpan throttled = handler.ThrottleCallback?.Invoke(ns) ?? TimeSpan.Zero;
if (throttled > TimeSpan.Zero)
ns.ThrottledUntil = DateTime.UtcNow + throttled;
PacketReceiveProfile prof = null;
if (Core.Profiling)
prof = PacketReceiveProfile.Acquire(packetId);
prof?.Start();
pump.QueueWork(ns, seq.Slice(r.Position), handler.OnReceive);
prof?.Finish(packetLength);
return packetLength;
}
private static void UnhandledBF(NetState state, PacketReader pvSrc)
{
}
@ -450,7 +548,8 @@ namespace Server.Network
Mobile vendor = World.FindMobile(pvSrc.ReadUInt32());
byte flag = pvSrc.ReadByte();
if (vendor == null) return;
if (vendor == null)
return;
if (vendor.Deleted || !Utility.RangeCheck(vendor.Location, state.Mobile.Location, 10))
{
@ -499,7 +598,7 @@ namespace Server.Network
}
int count = pvSrc.ReadUInt16();
if (count < 100 && pvSrc.Size == 1 + 2 + 4 + 2 + count * 6)
if (count < 100 && pvSrc.Length == 1 + 2 + 4 + 2 + count * 6)
{
List<SellItemResponse> sellList = new List<SellItemResponse>(count);
@ -888,7 +987,8 @@ namespace Server.Network
public static void GodModeRequest(NetState state, PacketReader pvSrc)
{
if (VerifyGC(state)) state.Send(new GodModeReply(pvSrc.ReadBoolean()));
if (VerifyGC(state))
state.Send(new GodModeReply(pvSrc.ReadBoolean()));
}
public static void AsciiPromptResponse(NetState state, PacketReader pvSrc)
@ -1603,6 +1703,7 @@ namespace Server.Network
{
int packetID = pvSrc.ReadUInt16();
Console.WriteLine("Extended Packet: {0:X}", packetID);
PacketHandler ph = GetExtendedHandler(packetID);
if (ph == null)
@ -1681,12 +1782,12 @@ namespace Server.Network
Mobile from = state.Mobile;
int length = pvSrc.Size - 3;
long length = pvSrc.Length - 3;
if (length < 0 || length % 4 != 0)
return;
int count = length / 4;
long count = length / 4;
for (int i = 0; i < count; ++i)
{
@ -2010,7 +2111,7 @@ namespace Server.Network
pvSrc.Seek(2, SeekOrigin.Current);
int flags = pvSrc.ReadInt32();
if (FeatureProtection.DisabledFeatures != 0 && ThirdPartyAuthCallback != null)
/* if (FeatureProtection.DisabledFeatures != 0 && ThirdPartyAuthCallback != null)
{
bool authOK = false;
@ -2031,18 +2132,18 @@ namespace Server.Network
}
ThirdPartyAuthCallback(state, authOK);
}
else
{
}*/
/* else
{*/
pvSrc.Seek(24, SeekOrigin.Current);
}
/* }*/
if (ThirdPartyHackedCallback != null)
/* if (ThirdPartyHackedCallback != null)
{
pvSrc.Seek(-2, SeekOrigin.Current);
if (pvSrc.ReadUInt16() == 0xDEAD)
ThirdPartyHackedCallback(state, true);
}
}*/
if (!state.Running)
return;
@ -2053,9 +2154,7 @@ namespace Server.Network
IAccount a = state.Account;
if (a == null || charSlot < 0 || charSlot >= a.Length)
{
state.Dispose();
}
else
{
Mobile m = a[charSlot];
@ -2079,7 +2178,6 @@ namespace Server.Network
return;
}
m.NetState?.Dispose();
// TODO: Make this wait one tick so we don't have to call it unnecessarily
@ -2206,8 +2304,6 @@ namespace Server.Network
int prof = pvSrc.ReadByte();
pvSrc.Seek(15, SeekOrigin.Current);
//bool female = pvSrc.ReadBoolean();
int genderRace = pvSrc.ReadByte();
int str = pvSrc.ReadByte();
@ -2645,8 +2741,7 @@ namespace Server.Network
if (e.Rejected)
{
state.Account = null;
state.Send(new AccountLoginRej(ALRReason.BadComm));
state.Dispose();
AccountLogin_ReplyRej(state, ALRReason.BadComm);
}
else
{

View file

@ -18,25 +18,29 @@
*
***************************************************************************/
using System;
using System.Buffers;
using System.IO;
using System.IO.Pipelines;
using System.Text;
namespace Server.Network
{
public class PacketReader
public ref struct PacketReader
{
private int m_Index;
private SequenceReader<byte> m_Reader;
public PacketReader(byte[] data, int size, bool fixedSize)
public SequencePosition Position => m_Reader.Position;
public long Length => m_Reader.Length;
public long Consumed => m_Reader.Consumed;
public long Remaining => m_Reader.Remaining;
public PacketReader(ReadOnlySequence<byte> seq)
{
Buffer = data;
Size = size;
m_Index = fixedSize ? 1 : 3;
m_Reader = new SequenceReader<byte>(seq);
}
public byte[] Buffer{ get; }
public int Size{ get; }
public byte Peek() => m_Reader.TryPeek(out byte value) ? value : (byte)0;
public void Trace(NetState state)
{
@ -44,7 +48,7 @@ namespace Server.Network
{
using (StreamWriter sw = new StreamWriter("Packets.log", true))
{
byte[] buffer = Buffer;
byte[] buffer = m_Reader.Sequence.ToArray();
if (buffer.Length > 0)
sw.WriteLine("Client: {0}: Unhandled packet 0x{1:X2}", state, buffer[0]);
@ -64,113 +68,83 @@ namespace Server.Network
}
}
public int Seek(int offset, SeekOrigin origin)
public SequencePosition Seek(long offset, SeekOrigin origin)
{
switch (origin)
{
case SeekOrigin.Begin:
m_Index = offset;
if (offset < m_Reader.Consumed)
m_Reader.Rewind(m_Reader.Consumed - Math.Max(offset, 0L));
else
m_Reader.Advance(offset - m_Reader.Consumed);
break;
case SeekOrigin.Current:
m_Index += offset;
if (offset < 0)
m_Reader.Rewind(Math.Min(m_Reader.Consumed, offset * -1));
else
m_Reader.Advance(Math.Min(m_Reader.Remaining, offset));
break;
case SeekOrigin.End:
m_Index = Size - offset;
long count = m_Reader.Remaining - offset;
if (count < 0)
m_Reader.Rewind(count * -1);
else if (count > 0)
m_Reader.Advance(count);
break;
}
return m_Index;
return m_Reader.Position;
}
public int ReadInt32()
{
if (m_Index + 4 > Size)
return 0;
public bool TryReadByte(out byte value) => m_Reader.TryRead(out value);
return (Buffer[m_Index++] << 24)
| (Buffer[m_Index++] << 16)
| (Buffer[m_Index++] << 8)
| Buffer[m_Index++];
}
public int ReadInt32() => m_Reader.TryReadBigEndian(out int value) ? value : 0;
public short ReadInt16()
{
if (m_Index + 2 > Size)
return 0;
public short ReadInt16() => m_Reader.TryReadBigEndian(out short value) ? value : (short)0;
return (short)((Buffer[m_Index++] << 8) | Buffer[m_Index++]);
}
public byte ReadByte() => m_Reader.TryRead(out byte value) ? value : (byte)0;
public byte ReadByte()
{
if (m_Index + 1 > Size)
return 0;
public uint ReadUInt32() => (uint)ReadInt32();
return Buffer[m_Index++];
}
public ushort ReadUInt16() => (ushort)ReadInt16();
public uint ReadUInt32()
{
if (m_Index + 4 > Size)
return 0;
public sbyte ReadSByte() => (sbyte)ReadByte();
return (uint)((Buffer[m_Index++] << 24) | (Buffer[m_Index++] << 16) | (Buffer[m_Index++] << 8) |
Buffer[m_Index++]);
}
public ushort ReadUInt16()
{
if (m_Index + 2 > Size)
return 0;
return (ushort)((Buffer[m_Index++] << 8) | Buffer[m_Index++]);
}
public sbyte ReadSByte()
{
if (m_Index + 1 > Size)
return 0;
return (sbyte)Buffer[m_Index++];
}
public bool ReadBoolean()
{
if (m_Index + 1 > Size)
return false;
return Buffer[m_Index++] != 0;
}
public bool ReadBoolean() => ReadByte() > 0;
public string ReadUnicodeStringLE()
{
StringBuilder sb = new StringBuilder();
int c;
while (m_Index + 1 < Size && (c = Buffer[m_Index++] | (Buffer[m_Index++] << 8)) != 0)
while (m_Reader.TryReadLittleEndian(out short c) && c != 0)
sb.Append((char)c);
return sb.ToString();
}
public string ReadUnicodeStringLE(int fixedLength)
{
StringBuilder sb = new StringBuilder();
while (fixedLength-- > 0 && m_Reader.TryReadLittleEndian(out short c) && c != 0)
sb.Append((char)c);
if (fixedLength > 0)
m_Reader.Advance(fixedLength);
return sb.ToString();
}
public string ReadUnicodeStringLESafe(int fixedLength)
{
int bound = m_Index + (fixedLength << 1);
int end = bound;
if (bound > Size)
bound = Size;
StringBuilder sb = new StringBuilder();
int c;
while (m_Index + 1 < bound && (c = Buffer[m_Index++] | (Buffer[m_Index++] << 8)) != 0)
while (fixedLength-- > 0 && m_Reader.TryReadLittleEndian(out short c) && c != 0)
if (IsSafeChar(c))
sb.Append((char)c);
m_Index = end;
if (fixedLength > 0)
m_Reader.Advance(fixedLength * 2);
return sb.ToString();
}
@ -179,9 +153,7 @@ namespace Server.Network
{
StringBuilder sb = new StringBuilder();
int c;
while (m_Index + 1 < Size && (c = Buffer[m_Index++] | (Buffer[m_Index++] << 8)) != 0)
while (m_Reader.TryReadLittleEndian(out short c) && c != 0)
if (IsSafeChar(c))
sb.Append((char)c);
@ -192,9 +164,7 @@ namespace Server.Network
{
StringBuilder sb = new StringBuilder();
int c;
while (m_Index + 1 < Size && (c = (Buffer[m_Index++] << 8) | Buffer[m_Index++]) != 0)
while (m_Reader.TryReadBigEndian(out short c) && c != 0)
if (IsSafeChar(c))
sb.Append((char)c);
@ -205,9 +175,7 @@ namespace Server.Network
{
StringBuilder sb = new StringBuilder();
int c;
while (m_Index + 1 < Size && (c = (Buffer[m_Index++] << 8) | Buffer[m_Index++]) != 0)
while (m_Reader.TryReadBigEndian(out short c) && c != 0)
sb.Append((char)c);
return sb.ToString();
@ -220,45 +188,17 @@ namespace Server.Network
public string ReadUTF8StringSafe(int fixedLength)
{
if (m_Index >= Size)
string s;
if (m_Reader.TryReadTo(out ReadOnlySpan<byte> span, (byte)'\0', true))
s = Utility.UTF8.GetString(span.Length > fixedLength ? span.Slice(0, fixedLength) : span);
else
{
m_Index += fixedLength;
return string.Empty;
long size = Math.Min(m_Reader.Remaining, fixedLength);
s = Utility.UTF8.GetString(m_Reader.Sequence.Slice(m_Reader.Position, size).ToArray());
m_Reader.Advance(size);
}
int bound = m_Index + fixedLength;
//int end = bound;
if (bound > Size)
bound = Size;
int count = 0;
int index = m_Index;
int start = m_Index;
while (index < bound && Buffer[index++] != 0)
++count;
index = 0;
byte[] buffer = new byte[count];
int value = 0;
while (m_Index < bound && (value = Buffer[m_Index++]) != 0)
buffer[index++] = (byte)value;
string s = Utility.UTF8.GetString(buffer);
bool isSafe = true;
for (int i = 0; isSafe && i < s.Length; ++i)
isSafe = IsSafeChar(s[i]);
m_Index = start + fixedLength;
if (isSafe)
return s;
StringBuilder sb = new StringBuilder(s.Length);
for (int i = 0; i < s.Length; ++i)
@ -270,32 +210,15 @@ namespace Server.Network
public string ReadUTF8StringSafe()
{
if (m_Index >= Size)
return string.Empty;
string s;
int count = 0;
int index = m_Index;
while (index < Size && Buffer[index++] != 0)
++count;
index = 0;
byte[] buffer = new byte[count];
int value = 0;
while (m_Index < Size && (value = Buffer[m_Index++]) != 0)
buffer[index++] = (byte)value;
string s = Utility.UTF8.GetString(buffer);
bool isSafe = true;
for (int i = 0; isSafe && i < s.Length; ++i)
isSafe = IsSafeChar(s[i]);
if (isSafe)
return s;
if (m_Reader.TryReadTo(out ReadOnlySpan<byte> span, (byte)'\0', true))
s = Utility.UTF8.GetString(span);
else
{
s = Utility.UTF8.GetString(m_Reader.Sequence.Slice(m_Reader.Position, m_Reader.Remaining).ToArray());
m_Reader.Advance(m_Reader.Remaining);
}
StringBuilder sb = new StringBuilder(s.Length);
@ -308,33 +231,17 @@ namespace Server.Network
public string ReadUTF8String()
{
if (m_Index >= Size)
return string.Empty;
int count = 0;
int index = m_Index;
while (index < Size && Buffer[index++] != 0)
++count;
index = 0;
byte[] buffer = new byte[count];
int value = 0;
while (m_Index < Size && (value = Buffer[m_Index++]) != 0)
buffer[index++] = (byte)value;
return Utility.UTF8.GetString(buffer);
return Utility.UTF8.GetString(
m_Reader.TryReadTo(out ReadOnlySpan<byte> span, (byte)'\0', true) ? span :
m_Reader.Sequence.Slice(m_Reader.Position, m_Reader.Remaining).ToArray()
);
}
public string ReadString()
{
StringBuilder sb = new StringBuilder();
int c;
while (m_Index < Size && (c = Buffer[m_Index++]) != 0)
while (m_Reader.TryRead(out byte c))
sb.Append((char)c);
return sb.ToString();
@ -344,9 +251,7 @@ namespace Server.Network
{
StringBuilder sb = new StringBuilder();
int c;
while (m_Index < Size && (c = Buffer[m_Index++]) != 0)
while (m_Reader.TryRead(out byte c))
if (IsSafeChar(c))
sb.Append((char)c);
@ -355,84 +260,56 @@ namespace Server.Network
public string ReadUnicodeStringSafe(int fixedLength)
{
int bound = m_Index + (fixedLength << 1);
int end = bound;
if (bound > Size)
bound = Size;
StringBuilder sb = new StringBuilder();
int c;
while (m_Index + 1 < bound && (c = (Buffer[m_Index++] << 8) | Buffer[m_Index++]) != 0)
while (fixedLength-- > 0 && m_Reader.TryReadBigEndian(out short c) && c != 0)
if (IsSafeChar(c))
sb.Append((char)c);
m_Index = end;
if (fixedLength > 0)
m_Reader.Advance(fixedLength * 2);
return sb.ToString();
}
public string ReadUnicodeString(int fixedLength)
{
int bound = m_Index + (fixedLength << 1);
int end = bound;
if (bound > Size)
bound = Size;
StringBuilder sb = new StringBuilder();
int c;
while (m_Index + 1 < bound && (c = (Buffer[m_Index++] << 8) | Buffer[m_Index++]) != 0)
while (fixedLength-- > 0 && m_Reader.TryReadBigEndian(out short c) && c != 0)
sb.Append((char)c);
m_Index = end;
if (fixedLength > 0)
m_Reader.Advance(fixedLength * 2);
return sb.ToString();
}
public string ReadStringSafe(int fixedLength)
{
int bound = m_Index + fixedLength;
int end = bound;
if (bound > Size)
bound = Size;
StringBuilder sb = new StringBuilder();
int c;
while (m_Index < bound && (c = Buffer[m_Index++]) != 0)
while (fixedLength-- > 0 && m_Reader.TryRead(out byte c) && c != 0)
if (IsSafeChar(c))
sb.Append((char)c);
m_Index = end;
if (fixedLength > 0)
m_Reader.Advance(fixedLength);
return sb.ToString();
}
public string ReadString(int fixedLength)
{
int bound = m_Index + fixedLength;
int end = bound;
if (bound > Size)
bound = Size;
StringBuilder sb = new StringBuilder();
int c;
while (m_Index < bound && (c = Buffer[m_Index++]) != 0)
while (fixedLength-- > 0 && m_Reader.TryRead(out byte c) && c != 0)
sb.Append((char)c);
m_Index = end;
if (fixedLength > 0)
m_Reader.Advance(fixedLength);
return sb.ToString();
}
}
}
}

View file

@ -19,7 +19,7 @@
***************************************************************************/
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.IO;
using System.Text;
@ -30,7 +30,7 @@ namespace Server.Network
/// </summary>
public class PacketWriter
{
private static Stack<PacketWriter> m_Pool = new Stack<PacketWriter>();
private static ConcurrentQueue<PacketWriter> m_Pool = new ConcurrentQueue<PacketWriter>();
/// <summary>
/// Internal format buffer.
@ -39,85 +39,50 @@ namespace Server.Network
private int m_Capacity;
/// <summary>
/// Internal stream which holds the entire packet.
/// </summary>
private MemoryStream m_Stream;
/// <summary>
/// Instantiates a new PacketWriter instance with a given capacity.
/// </summary>
/// <param name="capacity">Initial capacity for the internal stream.</param>
public PacketWriter(int capacity = 32)
{
m_Stream = new MemoryStream(capacity);
UnderlyingStream = new MemoryStream(capacity);
m_Capacity = capacity;
}
/// <summary>
/// Gets the total stream length.
/// </summary>
public long Length => m_Stream.Length;
public long Length => UnderlyingStream.Length;
/// <summary>
/// Gets or sets the current stream position.
/// </summary>
public long Position
{
get => m_Stream.Position;
set => m_Stream.Position = value;
get => UnderlyingStream.Position;
set => UnderlyingStream.Position = value;
}
/// <summary>
/// The internal stream used by this PacketWriter instance.
/// </summary>
public MemoryStream UnderlyingStream => m_Stream;
public MemoryStream UnderlyingStream { get; private set; }
public static PacketWriter CreateInstance()
public static PacketWriter CreateInstance(int capacity = 32)
{
return CreateInstance(32);
}
public static PacketWriter CreateInstance(int capacity)
{
PacketWriter pw = null;
lock (m_Pool)
if (m_Pool.TryDequeue(out PacketWriter pw))
{
if (m_Pool.Count > 0)
{
pw = m_Pool.Pop();
if (pw != null)
{
pw.m_Capacity = capacity;
pw.m_Stream.SetLength(0);
}
}
pw.m_Capacity = capacity;
pw.UnderlyingStream.SetLength(0);
return pw;
}
return pw ?? new PacketWriter(capacity);
return new PacketWriter(capacity);
}
public static void ReleaseInstance(PacketWriter pw)
{
lock (m_Pool)
{
if (!m_Pool.Contains(pw))
m_Pool.Push(pw);
else
try
{
using (StreamWriter op = new StreamWriter("neterr.log"))
{
op.WriteLine("{0}\tInstance pool contains writer", DateTime.UtcNow);
}
}
catch
{
Console.WriteLine("net error");
}
}
m_Pool.Enqueue(pw);
}
/// <summary>
@ -125,7 +90,7 @@ namespace Server.Network
/// </summary>
public void Write(bool value)
{
m_Stream.WriteByte((byte)(value ? 1 : 0));
UnderlyingStream.WriteByte((byte)(value ? 1 : 0));
}
/// <summary>
@ -133,7 +98,7 @@ namespace Server.Network
/// </summary>
public void Write(byte value)
{
m_Stream.WriteByte(value);
UnderlyingStream.WriteByte(value);
}
/// <summary>
@ -141,7 +106,7 @@ namespace Server.Network
/// </summary>
public void Write(sbyte value)
{
m_Stream.WriteByte((byte)value);
UnderlyingStream.WriteByte((byte)value);
}
/// <summary>
@ -152,7 +117,7 @@ namespace Server.Network
m_Buffer[0] = (byte)(value >> 8);
m_Buffer[1] = (byte)value;
m_Stream.Write(m_Buffer, 0, 2);
UnderlyingStream.Write(m_Buffer, 0, 2);
}
/// <summary>
@ -163,7 +128,7 @@ namespace Server.Network
m_Buffer[0] = (byte)(value >> 8);
m_Buffer[1] = (byte)value;
m_Stream.Write(m_Buffer, 0, 2);
UnderlyingStream.Write(m_Buffer, 0, 2);
}
/// <summary>
@ -176,7 +141,7 @@ namespace Server.Network
m_Buffer[2] = (byte)(value >> 8);
m_Buffer[3] = (byte)value;
m_Stream.Write(m_Buffer, 0, 4);
UnderlyingStream.Write(m_Buffer, 0, 4);
}
/// <summary>
@ -189,7 +154,7 @@ namespace Server.Network
m_Buffer[2] = (byte)(value >> 8);
m_Buffer[3] = (byte)value;
m_Stream.Write(m_Buffer, 0, 4);
UnderlyingStream.Write(m_Buffer, 0, 4);
}
/// <summary>
@ -197,7 +162,7 @@ namespace Server.Network
/// </summary>
public void Write(byte[] buffer, int offset, int size)
{
m_Stream.Write(buffer, offset, size);
UnderlyingStream.Write(buffer, offset, size);
}
/// <summary>
@ -214,29 +179,18 @@ namespace Server.Network
int length = value.Length;
m_Stream.SetLength(m_Stream.Length + size);
UnderlyingStream.SetLength(UnderlyingStream.Length + size);
if (length >= size)
{
m_Stream.Position += Encoding.ASCII.GetBytes(value, 0, size, m_Stream.GetBuffer(), (int)m_Stream.Position);
UnderlyingStream.Position +=
Encoding.ASCII.GetBytes(value, 0, size, UnderlyingStream.GetBuffer(), (int)UnderlyingStream.Position);
}
else
{
Encoding.ASCII.GetBytes(value, 0, length, m_Stream.GetBuffer(), (int)m_Stream.Position);
m_Stream.Position += size;
Encoding.ASCII.GetBytes(value, 0, length, UnderlyingStream.GetBuffer(), (int)UnderlyingStream.Position);
UnderlyingStream.Position += size;
}
/*byte[] buffer = Encoding.ASCII.GetBytes( value );
if ( buffer.Length >= size )
{
m_Stream.Write( buffer, 0, size );
}
else
{
m_Stream.Write( buffer, 0, buffer.Length );
Fill( size - buffer.Length );
}*/
}
/// <summary>
@ -252,15 +206,10 @@ namespace Server.Network
int length = value.Length;
m_Stream.SetLength(m_Stream.Length + length + 1);
UnderlyingStream.SetLength(UnderlyingStream.Length + length + 1);
Encoding.ASCII.GetBytes(value, 0, length, m_Stream.GetBuffer(), (int)m_Stream.Position);
m_Stream.Position += length + 1;
/*byte[] buffer = Encoding.ASCII.GetBytes( value );
m_Stream.Write( buffer, 0, buffer.Length );
m_Stream.WriteByte( 0 );*/
Encoding.ASCII.GetBytes(value, 0, length, UnderlyingStream.GetBuffer(), (int)UnderlyingStream.Position);
UnderlyingStream.Position += length + 1;
}
/// <summary>
@ -276,18 +225,10 @@ namespace Server.Network
int length = value.Length;
m_Stream.SetLength(m_Stream.Length + (length + 1) * 2);
UnderlyingStream.SetLength(UnderlyingStream.Length + (length + 1) * 2);
m_Stream.Position += Encoding.Unicode.GetBytes(value, 0, length, m_Stream.GetBuffer(), (int)m_Stream.Position);
m_Stream.Position += 2;
/*byte[] buffer = Encoding.Unicode.GetBytes( value );
m_Stream.Write( buffer, 0, buffer.Length );
m_Buffer[0] = 0;
m_Buffer[1] = 0;
m_Stream.Write( m_Buffer, 0, 2 );*/
UnderlyingStream.Position += Encoding.Unicode.GetBytes(value, 0, length, UnderlyingStream.GetBuffer(), (int)UnderlyingStream.Position);
UnderlyingStream.Position += 2;
}
/// <summary>
@ -302,36 +243,21 @@ namespace Server.Network
value = string.Empty;
}
int length = value.Length;
size *= 2;
int length = value.Length;
m_Stream.SetLength(m_Stream.Length + size);
UnderlyingStream.SetLength(UnderlyingStream.Length + size);
if (length * 2 >= size)
{
m_Stream.Position +=
Encoding.Unicode.GetBytes(value, 0, length, m_Stream.GetBuffer(), (int)m_Stream.Position);
UnderlyingStream.Position +=
Encoding.Unicode.GetBytes(value, 0, size, UnderlyingStream.GetBuffer(), (int)UnderlyingStream.Position);
}
else
{
Encoding.Unicode.GetBytes(value, 0, length, m_Stream.GetBuffer(), (int)m_Stream.Position);
m_Stream.Position += size;
Encoding.Unicode.GetBytes(value, 0, length, UnderlyingStream.GetBuffer(), (int)UnderlyingStream.Position);
UnderlyingStream.Position += size;
}
/*size *= 2;
byte[] buffer = Encoding.Unicode.GetBytes( value );
if ( buffer.Length >= size )
{
m_Stream.Write( buffer, 0, size );
}
else
{
m_Stream.Write( buffer, 0, buffer.Length );
Fill( size - buffer.Length );
}*/
}
/// <summary>
@ -347,19 +273,11 @@ namespace Server.Network
int length = value.Length;
m_Stream.SetLength(m_Stream.Length + (length + 1) * 2);
UnderlyingStream.SetLength(UnderlyingStream.Length + (length + 1) * 2);
m_Stream.Position +=
Encoding.BigEndianUnicode.GetBytes(value, 0, length, m_Stream.GetBuffer(), (int)m_Stream.Position);
m_Stream.Position += 2;
/*byte[] buffer = Encoding.BigEndianUnicode.GetBytes( value );
m_Stream.Write( buffer, 0, buffer.Length );
m_Buffer[0] = 0;
m_Buffer[1] = 0;
m_Stream.Write( m_Buffer, 0, 2 );*/
UnderlyingStream.Position +=
Encoding.BigEndianUnicode.GetBytes(value, 0, length, UnderlyingStream.GetBuffer(), (int)UnderlyingStream.Position);
UnderlyingStream.Position += 2;
}
/// <summary>
@ -374,36 +292,21 @@ namespace Server.Network
value = string.Empty;
}
int length = value.Length;
size *= 2;
int length = value.Length;
UnderlyingStream.SetLength(UnderlyingStream.Length + size);
m_Stream.SetLength(m_Stream.Length + size);
if (length * 2 >= size)
if (length * 2 >= size )
{
m_Stream.Position +=
Encoding.BigEndianUnicode.GetBytes(value, 0, length, m_Stream.GetBuffer(), (int)m_Stream.Position);
UnderlyingStream.Position +=
Encoding.BigEndianUnicode.GetBytes(value, 0, size, UnderlyingStream.GetBuffer(), (int)UnderlyingStream.Position);
}
else
{
Encoding.BigEndianUnicode.GetBytes(value, 0, length, m_Stream.GetBuffer(), (int)m_Stream.Position);
m_Stream.Position += size;
Encoding.BigEndianUnicode.GetBytes(value, 0, length, UnderlyingStream.GetBuffer(), (int)UnderlyingStream.Position);
UnderlyingStream.Position += size;
}
/*size *= 2;
byte[] buffer = Encoding.BigEndianUnicode.GetBytes( value );
if ( buffer.Length >= size )
{
m_Stream.Write( buffer, 0, size );
}
else
{
m_Stream.Write( buffer, 0, buffer.Length );
Fill( size - buffer.Length );
}*/
}
/// <summary>
@ -411,39 +314,33 @@ namespace Server.Network
/// </summary>
public void Fill()
{
Fill((int)(m_Capacity - m_Stream.Length));
Fill(m_Capacity - UnderlyingStream.Length);
}
/// <summary>
/// Writes a number of 0x00 byte values to the underlying stream.
/// </summary>
public void Fill(int length)
public void Fill(long length)
{
if (m_Stream.Position == m_Stream.Length)
if (UnderlyingStream.Position == UnderlyingStream.Length)
{
m_Stream.SetLength(m_Stream.Length + length);
m_Stream.Seek(0, SeekOrigin.End);
UnderlyingStream.SetLength(UnderlyingStream.Length + length);
UnderlyingStream.Seek(0, SeekOrigin.End);
}
else
{
m_Stream.Write(new byte[length], 0, length);
UnderlyingStream.Write(new byte[length], 0, (int)length);
}
}
/// <summary>
/// Offsets the current position from an origin.
/// </summary>
public long Seek(long offset, SeekOrigin origin)
{
return m_Stream.Seek(offset, origin);
}
public long Seek(long offset, SeekOrigin origin) => UnderlyingStream.Seek(offset, origin);
/// <summary>
/// Gets the entire stream content as a byte array.
/// </summary>
public byte[] ToArray()
{
return m_Stream.ToArray();
}
public byte[] ToArray() => UnderlyingStream.ToArray();
}
}

View file

@ -19,6 +19,7 @@
***************************************************************************/
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
@ -2336,8 +2337,6 @@ namespace Server.Network
public sealed class DisplayGumpPacked : Packet, IGumpWriter
{
private const int GumpBufferSize = 0x5000;
private static byte[] m_True = Gump.StringToBuffer(" 1");
private static byte[] m_False = Gump.StringToBuffer(" 0");
@ -2345,7 +2344,6 @@ namespace Server.Network
private static byte[] m_EndTextSeparator = Gump.StringToBuffer("@");
private static byte[] m_Buffer = new byte[48];
private static BufferPool m_PackBuffers = new BufferPool("Gump", 4, GumpBufferSize);
private Gump m_Gump;
@ -2465,30 +2463,17 @@ namespace Server.Network
wantLength += 4095;
wantLength &= ~4095;
byte[] m_PackBuffer;
lock (m_PackBuffers)
{
m_PackBuffer = m_PackBuffers.AcquireBuffer();
}
byte[] packBuffer = ArrayPool<byte>.Shared.Rent(wantLength);
if (m_PackBuffer.Length < wantLength)
{
Console.WriteLine("Notice: DisplayGumpPacked creating new {0} byte buffer", wantLength);
m_PackBuffer = new byte[wantLength];
}
int packLength = wantLength;
int packLength = m_PackBuffer.Length;
Compression.Pack(m_PackBuffer, ref packLength, buffer, length, ZLibQuality.Default);
Compression.Pack(packBuffer, ref packLength, buffer, length, ZLibQuality.Default);
m_Stream.Write(4 + packLength);
m_Stream.Write(length);
m_Stream.Write(m_PackBuffer, 0, packLength);
m_Stream.Write(packBuffer, 0, packLength);
lock (m_PackBuffers)
{
m_PackBuffers.ReleaseBuffer(m_PackBuffer);
}
ArrayPool<byte>.Shared.Return(packBuffer);
}
}
@ -3954,7 +3939,7 @@ namespace Server.Network
public sealed class CharacterList : Packet
{
private static MD5CryptoServiceProvider m_MD5Provider;
//private static MD5CryptoServiceProvider m_MD5Provider;
public CharacterList(IAccount a, CityInfo[] info) : base(0xA9)
{
@ -4013,7 +3998,7 @@ namespace Server.Network
m_Stream.Write((short)-1);
ThirdPartyFeature disabled = FeatureProtection.DisabledFeatures;
/*ThirdPartyFeature disabled = FeatureProtection.DisabledFeatures;
if (disabled != 0)
{
@ -4040,7 +4025,7 @@ namespace Server.Network
m_Stream.Seek(95, SeekOrigin.Begin);
m_Stream.Write(hashCode, 0, hashCode.Length);
}
}*/
}
public static CharacterListFlags AdditionalFlags{ get; set; }
@ -4048,7 +4033,7 @@ namespace Server.Network
public sealed class CharacterListOld : Packet
{
private static MD5CryptoServiceProvider m_MD5Provider;
// private static MD5CryptoServiceProvider m_MD5Provider;
public CharacterListOld(IAccount a, CityInfo[] info) : base(0xA9)
{
@ -4099,7 +4084,7 @@ namespace Server.Network
m_Stream.Write((int)(flags | CharacterList.AdditionalFlags)); // Additional Flags
ThirdPartyFeature disabled = FeatureProtection.DisabledFeatures;
/* ThirdPartyFeature disabled = FeatureProtection.DisabledFeatures;
if (disabled != 0)
{
@ -4126,7 +4111,7 @@ namespace Server.Network
m_Stream.Seek(95, SeekOrigin.Begin);
m_Stream.Write(hashCode, 0, hashCode.Length);
}
}*/
}
}
@ -4197,7 +4182,7 @@ namespace Server.Network
public sealed class ServerInfo
{
public ServerInfo(string name, int fullPercent, TimeZone tz, IPEndPoint address)
public ServerInfo(string name, int fullPercent, TimeZoneInfo tz, IPEndPoint address)
{
Name = name;
FullPercent = fullPercent;
@ -4289,271 +4274,4 @@ namespace Server.Network
m_Stream.Write(m_AuthID);
}
}
public abstract class Packet
{
private const int CompressorBufferSize = 0x10000;
private const int BufferSize = 4096;
private static BufferPool m_CompressorBuffers = new BufferPool("Compressor", 4, CompressorBufferSize);
private static BufferPool m_Buffers = new BufferPool("Compressed", 16, BufferSize);
private byte[] m_CompiledBuffer;
private int m_CompiledLength;
private int m_Length;
private State m_State;
protected PacketWriter m_Stream;
protected Packet(int packetID)
{
PacketID = packetID;
if (Core.Profiling)
{
PacketSendProfile prof = PacketSendProfile.Acquire(GetType());
prof.Increment();
}
}
protected Packet(int packetID, int length)
{
PacketID = packetID;
m_Length = length;
m_Stream = PacketWriter.CreateInstance(length); // new PacketWriter( length );
m_Stream.Write((byte)packetID);
if (Core.Profiling)
{
PacketSendProfile prof = PacketSendProfile.Acquire(GetType());
prof.Increment();
}
}
public int PacketID{ get; }
public PacketWriter UnderlyingStream => m_Stream;
public void EnsureCapacity(int length)
{
m_Stream = PacketWriter.CreateInstance(length); // new PacketWriter( length );
m_Stream.Write((byte)PacketID);
m_Stream.Write((short)0);
}
public static Packet SetStatic(Packet p)
{
p.SetStatic();
return p;
}
public static Packet Acquire(Packet p)
{
p.Acquire();
return p;
}
public static void Release(ref Packet p)
{
p?.Release();
p = null;
}
public static void Release(Packet p)
{
p?.Release();
}
public void SetStatic()
{
m_State |= State.Static | State.Acquired;
}
public void Acquire()
{
m_State |= State.Acquired;
}
public void OnSend()
{
Core.Set();
lock (this)
{
if ((m_State & (State.Acquired | State.Static)) == 0)
Free();
}
}
private void Free()
{
if (m_CompiledBuffer == null)
return;
if ((m_State & State.Buffered) != 0)
m_Buffers.ReleaseBuffer(m_CompiledBuffer);
m_State &= ~(State.Static | State.Acquired | State.Buffered);
m_CompiledBuffer = null;
}
public void Release()
{
if ((m_State & State.Acquired) != 0)
Free();
}
public byte[] Compile(bool compress, out int length)
{
lock (this)
{
if (m_CompiledBuffer == null)
{
if ((m_State & State.Accessed) == 0)
{
m_State |= State.Accessed;
}
else
{
if ((m_State & State.Warned) == 0)
{
m_State |= State.Warned;
try
{
using (StreamWriter op = new StreamWriter("net_opt.log", true))
{
op.WriteLine("Redundant compile for packet {0}, use Acquire() and Release()", GetType());
op.WriteLine(new StackTrace());
}
}
catch
{
// ignored
}
}
m_CompiledBuffer = new byte[0];
m_CompiledLength = 0;
length = m_CompiledLength;
return m_CompiledBuffer;
}
InternalCompile(compress);
}
length = m_CompiledLength;
return m_CompiledBuffer;
}
}
private void InternalCompile(bool compress)
{
if (m_Length == 0)
{
long streamLen = m_Stream.Length;
m_Stream.Seek(1, SeekOrigin.Begin);
m_Stream.Write((ushort)streamLen);
}
else if (m_Stream.Length != m_Length)
{
int diff = (int)m_Stream.Length - m_Length;
Console.WriteLine("Packet: 0x{0:X2}: Bad packet length! ({1}{2} bytes)", PacketID, diff >= 0 ? "+" : "",
diff);
}
MemoryStream ms = m_Stream.UnderlyingStream;
m_CompiledBuffer = ms.GetBuffer();
int length = (int)ms.Length;
if (compress)
{
byte[] buffer;
lock (m_CompressorBuffers)
{
buffer = m_CompressorBuffers.AcquireBuffer();
}
Compression.Compress(m_CompiledBuffer, 0, length, buffer, ref length);
if (length <= 0)
{
Console.WriteLine("Warning: Compression buffer overflowed on packet 0x{0:X2} ('{1}') (length={2})",
PacketID, GetType().Name, length);
using (StreamWriter op = new StreamWriter("compression_overflow.log", true))
{
op.WriteLine("{0} Warning: Compression buffer overflowed on packet 0x{1:X2} ('{2}') (length={3})",
DateTime.UtcNow, PacketID, GetType().Name, length);
op.WriteLine(new StackTrace());
}
}
else
{
m_CompiledLength = length;
if (length > BufferSize || (m_State & State.Static) != 0)
{
m_CompiledBuffer = new byte[length];
}
else
{
lock (m_Buffers)
{
m_CompiledBuffer = m_Buffers.AcquireBuffer();
}
m_State |= State.Buffered;
}
Buffer.BlockCopy(buffer, 0, m_CompiledBuffer, 0, length);
lock (m_CompressorBuffers)
{
m_CompressorBuffers.ReleaseBuffer(buffer);
}
}
}
else if (length > 0)
{
byte[] old = m_CompiledBuffer;
m_CompiledLength = length;
if (length > BufferSize || (m_State & State.Static) != 0)
{
m_CompiledBuffer = new byte[length];
}
else
{
lock (m_Buffers)
{
m_CompiledBuffer = m_Buffers.AcquireBuffer();
}
m_State |= State.Buffered;
}
Buffer.BlockCopy(old, 0, m_CompiledBuffer, 0, length);
}
PacketWriter.ReleaseInstance(m_Stream);
m_Stream = null;
}
[Flags]
private enum State
{
Inactive = 0x00,
Static = 0x01,
Acquired = 0x02,
Accessed = 0x04,
Buffered = 0x08,
Warned = 0x10
}
}
}

View file

@ -18,208 +18,34 @@
*
***************************************************************************/
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace Server.Network
{
public class SendQueue
public class SendQueue<T>
{
private const int PendingCap = 256 * 1024;
private static int m_CoalesceBufferSize = 512;
private static BufferPool m_UnusedBuffers = new BufferPool("Coalesced", 2048, m_CoalesceBufferSize);
private Gram _buffered;
private Queue<Gram> _pending;
private BlockingCollection<T> m_Queue = new BlockingCollection<T>(new ConcurrentQueue<T>());
public SendQueue()
{
_pending = new Queue<Gram>();
}
public static int CoalesceBufferSize
public void Enqueue(T t)
{
get => m_CoalesceBufferSize;
set
{
if (m_CoalesceBufferSize == value)
return;
BufferPool old = m_UnusedBuffers;
lock (old)
{
m_UnusedBuffers?.Free();
m_CoalesceBufferSize = value;
m_UnusedBuffers = new BufferPool("Coalesced", 2048, m_CoalesceBufferSize);
}
}
m_Queue.Add(t);
}
public bool IsFlushReady => _pending.Count == 0 && _buffered != null;
public bool IsEmpty => _pending.Count == 0 && _buffered == null;
public static byte[] AcquireBuffer()
public Task<T> DequeueAsync()
{
lock (m_UnusedBuffers)
{
return m_UnusedBuffers.AcquireBuffer();
}
TaskCompletionSource<T> taskCompletion = new TaskCompletionSource<T>();
Task.Run(() => taskCompletion.SetResult(Dequeue()));
return taskCompletion.Task;
}
public static void ReleaseBuffer(byte[] buffer)
public T Dequeue()
{
lock (m_UnusedBuffers)
{
if (buffer != null && buffer.Length == m_CoalesceBufferSize)
m_UnusedBuffers.ReleaseBuffer(buffer);
}
}
public Gram CheckFlushReady()
{
Gram gram = _buffered;
_pending.Enqueue(_buffered);
_buffered = null;
return gram;
}
public Gram Dequeue()
{
Gram gram = null;
if (_pending.Count > 0)
{
_pending.Dequeue().Release();
if (_pending.Count > 0) gram = _pending.Peek();
}
return gram;
}
public Gram Enqueue(byte[] buffer, int length)
{
return Enqueue(buffer, 0, length);
}
public Gram Enqueue(byte[] buffer, int offset, int length)
{
if (buffer == null) throw new ArgumentNullException("buffer");
if (!(offset >= 0 && offset < buffer.Length))
throw new ArgumentOutOfRangeException("offset", offset,
"Offset must be greater than or equal to zero and less than the size of the buffer.");
if (length < 0 || length > buffer.Length)
throw new ArgumentOutOfRangeException("length", length,
"Length cannot be less than zero or greater than the size of the buffer.");
if (buffer.Length - offset < length)
throw new ArgumentException("Offset and length do not point to a valid segment within the buffer.");
int existingBytes = _pending.Count * m_CoalesceBufferSize + (_buffered?.Length ?? 0);
if (existingBytes + length > PendingCap) throw new CapacityExceededException();
Gram gram = null;
while (length > 0)
{
if (_buffered == null) _buffered = Gram.Acquire();
int bytesWritten = _buffered.Write(buffer, offset, length);
offset += bytesWritten;
length -= bytesWritten;
if (_buffered.IsFull)
{
if (_pending.Count == 0) gram = _buffered;
_pending.Enqueue(_buffered);
_buffered = null;
}
}
return gram;
}
public void Clear()
{
if (_buffered != null)
{
_buffered.Release();
_buffered = null;
}
while (_pending.Count > 0) _pending.Dequeue().Release();
}
public class Gram
{
private static Stack<Gram> _pool = new Stack<Gram>();
private Gram()
{
}
public byte[] Buffer{ get; private set; }
public int Length{ get; private set; }
public int Available => Buffer.Length - Length;
public bool IsFull => Length == Buffer.Length;
public static Gram Acquire()
{
lock (_pool)
{
Gram gram;
if (_pool.Count > 0)
gram = _pool.Pop();
else
gram = new Gram();
gram.Buffer = AcquireBuffer();
gram.Length = 0;
return gram;
}
}
public int Write(byte[] buffer, int offset, int length)
{
int write = Math.Min(length, Available);
System.Buffer.BlockCopy(buffer, offset, Buffer, Length, write);
Length += write;
return write;
}
public void Release()
{
lock (_pool)
{
_pool.Push(this);
ReleaseBuffer(Buffer);
}
}
return m_Queue.Take();
}
}
[Serializable]
public sealed class CapacityExceededException : Exception
{
public CapacityExceededException()
: base("Too much data pending.")
{
}
}
}
}

View file

@ -0,0 +1,57 @@
/***************************************************************************
* SocketExtensions.cs
* -------------------
* begin : August 2, 2019
* copyright : (C) The ModernUO Team
* email : hi@modernuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.Buffers;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace Server.Network
{
public static class SocketExtensions
{
public static Task<int> ReceiveAsync(this Socket socket, Memory<byte> memory, SocketFlags socketFlags)
{
return SocketTaskExtensions.ReceiveAsync(socket, GetArray(memory), socketFlags);
}
public static ArraySegment<byte> GetArray(this Memory<byte> memory)
{
return ((ReadOnlyMemory<byte>)memory).GetArray();
}
public static ArraySegment<byte> GetArray(this ReadOnlyMemory<byte> memory)
{
if (MemoryMarshal.TryGetArray(memory, out var result))
return result;
throw new InvalidOperationException("Buffer backed by array was expected");
}
public static ArraySegment<byte> GetArray(this ReadOnlySequence<byte> memory)
{
if (SequenceMarshal.TryGetArray(memory, out var result))
return result;
throw new InvalidOperationException("Buffer backed by array was expected");
}
}
}

View file

@ -1,3 +1,23 @@
/***************************************************************************
* StaticPacketHandlers.cs
* -------------------
* begin : March 15, 2019
* copyright : (C) The ModernUO Team
* email : hi@modernuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System.Collections.Concurrent;
namespace Server.Network