Reorganizes Project (#41)

This commit is contained in:
Kamron Batman 2019-08-02 18:13:40 -07:00 committed by GitHub
parent 08bf44af9a
commit 3614a66aee
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3499 changed files with 79 additions and 55 deletions

View file

@ -0,0 +1,398 @@
/***************************************************************************
* Compression.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;
using System.Runtime.InteropServices;
namespace Server.Network
{
/// <summary>
/// Handles outgoing packet compression for the network.
/// </summary>
public static class Compression
{
private const int CountIndex = 0;
private const int ValueIndex = 1;
// UO packets may not exceed 64kb in length
private const int BufferSize = 0x10000;
// Optimal compression ratio is 2 / 8; worst compression ratio is 11 / 8
private const int MinimalCodeLength = 2;
private const int MaximalCodeLength = 11;
// Fixed overhead, in bits, per compression call
private const int TerminalCodeLength = 4;
// If our input exceeds this length, we cannot possibly compress it within the buffer
private const int DefiniteOverflow = (BufferSize * 8 - TerminalCodeLength) / MinimalCodeLength;
// If our input exceeds this length, we may potentially overflow the buffer
private const int PossibleOverflow = (BufferSize * 8 - TerminalCodeLength) / MaximalCodeLength;
private static int[] _huffmanTable = {
0x2, 0x000, 0x5, 0x01F, 0x6, 0x022, 0x7, 0x034, 0x7, 0x075, 0x6, 0x028, 0x6, 0x03B, 0x7, 0x032,
0x8, 0x0E0, 0x8, 0x062, 0x7, 0x056, 0x8, 0x079, 0x9, 0x19D, 0x8, 0x097, 0x6, 0x02A, 0x7, 0x057,
0x8, 0x071, 0x8, 0x05B, 0x9, 0x1CC, 0x8, 0x0A7, 0x7, 0x025, 0x7, 0x04F, 0x8, 0x066, 0x8, 0x07D,
0x9, 0x191, 0x9, 0x1CE, 0x7, 0x03F, 0x9, 0x090, 0x8, 0x059, 0x8, 0x07B, 0x8, 0x091, 0x8, 0x0C6,
0x6, 0x02D, 0x9, 0x186, 0x8, 0x06F, 0x9, 0x093, 0xA, 0x1CC, 0x8, 0x05A, 0xA, 0x1AE, 0xA, 0x1C0,
0x9, 0x148, 0x9, 0x14A, 0x9, 0x082, 0xA, 0x19F, 0x9, 0x171, 0x9, 0x120, 0x9, 0x0E7, 0xA, 0x1F3,
0x9, 0x14B, 0x9, 0x100, 0x9, 0x190, 0x6, 0x013, 0x9, 0x161, 0x9, 0x125, 0x9, 0x133, 0x9, 0x195,
0x9, 0x173, 0x9, 0x1CA, 0x9, 0x086, 0x9, 0x1E9, 0x9, 0x0DB, 0x9, 0x1EC, 0x9, 0x08B, 0x9, 0x085,
0x5, 0x00A, 0x8, 0x096, 0x8, 0x09C, 0x9, 0x1C3, 0x9, 0x19C, 0x9, 0x08F, 0x9, 0x18F, 0x9, 0x091,
0x9, 0x087, 0x9, 0x0C6, 0x9, 0x177, 0x9, 0x089, 0x9, 0x0D6, 0x9, 0x08C, 0x9, 0x1EE, 0x9, 0x1EB,
0x9, 0x084, 0x9, 0x164, 0x9, 0x175, 0x9, 0x1CD, 0x8, 0x05E, 0x9, 0x088, 0x9, 0x12B, 0x9, 0x172,
0x9, 0x10A, 0x9, 0x08D, 0x9, 0x13A, 0x9, 0x11C, 0xA, 0x1E1, 0xA, 0x1E0, 0x9, 0x187, 0xA, 0x1DC,
0xA, 0x1DF, 0x7, 0x074, 0x9, 0x19F, 0x8, 0x08D, 0x8, 0x0E4, 0x7, 0x079, 0x9, 0x0EA, 0x9, 0x0E1,
0x8, 0x040, 0x7, 0x041, 0x9, 0x10B, 0x9, 0x0B0, 0x8, 0x06A, 0x8, 0x0C1, 0x7, 0x071, 0x7, 0x078,
0x8, 0x0B1, 0x9, 0x14C, 0x7, 0x043, 0x8, 0x076, 0x7, 0x066, 0x7, 0x04D, 0x9, 0x08A, 0x6, 0x02F,
0x8, 0x0C9, 0x9, 0x0CE, 0x9, 0x149, 0x9, 0x160, 0xA, 0x1BA, 0xA, 0x19E, 0xA, 0x39F, 0x9, 0x0E5,
0x9, 0x194, 0x9, 0x184, 0x9, 0x126, 0x7, 0x030, 0x8, 0x06C, 0x9, 0x121, 0x9, 0x1E8, 0xA, 0x1C1,
0xA, 0x11D, 0xA, 0x163, 0xA, 0x385, 0xA, 0x3DB, 0xA, 0x17D, 0xA, 0x106, 0xA, 0x397, 0xA, 0x24E,
0x7, 0x02E, 0x8, 0x098, 0xA, 0x33C, 0xA, 0x32E, 0xA, 0x1E9, 0x9, 0x0BF, 0xA, 0x3DF, 0xA, 0x1DD,
0xA, 0x32D, 0xA, 0x2ED, 0xA, 0x30B, 0xA, 0x107, 0xA, 0x2E8, 0xA, 0x3DE, 0xA, 0x125, 0xA, 0x1E8,
0x9, 0x0E9, 0xA, 0x1CD, 0xA, 0x1B5, 0x9, 0x165, 0xA, 0x232, 0xA, 0x2E1, 0xB, 0x3AE, 0xB, 0x3C6,
0xB, 0x3E2, 0xA, 0x205, 0xA, 0x29A, 0xA, 0x248, 0xA, 0x2CD, 0xA, 0x23B, 0xB, 0x3C5, 0xA, 0x251,
0xA, 0x2E9, 0xA, 0x252, 0x9, 0x1EA, 0xB, 0x3A0, 0xB, 0x391, 0xA, 0x23C, 0xB, 0x392, 0xB, 0x3D5,
0xA, 0x233, 0xA, 0x2CC, 0xB, 0x390, 0xA, 0x1BB, 0xB, 0x3A1, 0xB, 0x3C4, 0xA, 0x211, 0xA, 0x203,
0x9, 0x12A, 0xA, 0x231, 0xB, 0x3E0, 0xA, 0x29B, 0xB, 0x3D7, 0xA, 0x202, 0xB, 0x3AD, 0xA, 0x213,
0xA, 0x253, 0xA, 0x32C, 0xA, 0x23D, 0xA, 0x23F, 0xA, 0x32F, 0xA, 0x11C, 0xA, 0x384, 0xA, 0x31C,
0xA, 0x17C, 0xA, 0x30A, 0xA, 0x2E0, 0xA, 0x276, 0xA, 0x250, 0xB, 0x3E3, 0xA, 0x396, 0xA, 0x18F,
0xA, 0x204, 0xA, 0x206, 0xA, 0x230, 0xA, 0x265, 0xA, 0x212, 0xA, 0x23E, 0xB, 0x3AC, 0xB, 0x393,
0xB, 0x3E1, 0xA, 0x1DE, 0xB, 0x3D6, 0xA, 0x31D, 0xB, 0x3E5, 0xB, 0x3E4, 0xA, 0x207, 0xB, 0x3C7,
0xA, 0x277, 0xB, 0x3D4, 0x8, 0x0C0, 0xA, 0x162, 0xA, 0x3DA, 0xA, 0x124, 0xA, 0x1B4, 0xA, 0x264,
0xA, 0x33D, 0xA, 0x1D1, 0xA, 0x1AF, 0xA, 0x39E, 0xA, 0x24F, 0xB, 0x373, 0xA, 0x249, 0xB, 0x372,
0x9, 0x167, 0xA, 0x210, 0xA, 0x23A, 0xA, 0x1B8, 0xB, 0x3AF, 0xA, 0x18E, 0xA, 0x2EC, 0x7, 0x062,
0x4, 0x00D
};
public static readonly ICompressor Compressor;
static Compression()
{
if (Core.Unix)
{
if (Core.Is64Bit)
Compressor = new CompressorUnix64();
else
Compressor = new CompressorUnix32();
}
else if (Core.Is64Bit)
{
Compressor = new Compressor64();
}
else
{
Compressor = new Compressor32();
}
}
public static unsafe void Compress(byte[] input, int offset, int count, byte[] output, ref int length)
{
if (input == null) throw new ArgumentNullException(nameof(input));
if (offset < 0 || offset >= input.Length) throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > input.Length) throw new ArgumentOutOfRangeException(nameof(count));
if (input.Length - offset < count) throw new ArgumentException();
length = 0;
if (count > DefiniteOverflow) return;
int bitCount = 0;
int bitValue = 0;
fixed (int* pTable = _huffmanTable)
{
int* pEntry;
fixed (byte* pInputBuffer = input)
{
byte* pInput = pInputBuffer + offset, pInputEnd = pInput + count;
fixed (byte* pOutputBuffer = output)
{
byte* pOutput = pOutputBuffer, pOutputEnd = pOutput + BufferSize;
while (pInput < pInputEnd)
{
pEntry = &pTable[*pInput++ << 1];
bitCount += pEntry[CountIndex];
bitValue <<= pEntry[CountIndex];
bitValue |= pEntry[ValueIndex];
while (bitCount >= 8)
{
bitCount -= 8;
if (pOutput < pOutputEnd)
{
*pOutput++ = (byte)(bitValue >> bitCount);
}
else
{
length = 0;
return;
}
}
}
// terminal code
pEntry = &pTable[0x200];
bitCount += pEntry[CountIndex];
bitValue <<= pEntry[CountIndex];
bitValue |= pEntry[ValueIndex];
// align on byte boundary
if ((bitCount & 7) != 0)
{
bitValue <<= 8 - (bitCount & 7);
bitCount += 8 - (bitCount & 7);
}
while (bitCount >= 8)
{
bitCount -= 8;
if (pOutput < pOutputEnd)
{
*pOutput++ = (byte)(bitValue >> bitCount);
}
else
{
length = 0;
return;
}
}
length = (int)(pOutput - pOutputBuffer);
}
}
}
}
public static ZLibError Pack(byte[] dest, ref int destLength, byte[] source, int sourceLength)
{
return Compressor.Compress(dest, ref destLength, source, sourceLength);
}
public static ZLibError Pack(byte[] dest, ref int destLength, byte[] source, int sourceLength, ZLibQuality quality)
{
return Compressor.Compress(dest, ref destLength, source, sourceLength, quality);
}
public static ZLibError Unpack(byte[] dest, ref int destLength, byte[] source, int sourceLength)
{
return Compressor.Decompress(dest, ref destLength, source, sourceLength);
}
}
public interface ICompressor
{
string Version{ get; }
ZLibError Compress(byte[] dest, ref int destLength, byte[] source, int sourceLength);
ZLibError Compress(byte[] dest, ref int destLength, byte[] source, int sourceLength, ZLibQuality quality);
ZLibError Decompress(byte[] dest, ref int destLength, byte[] source, int sourceLength);
}
public sealed class Compressor32 : ICompressor
{
public string Version => SafeNativeMethods.zlibVersion();
public ZLibError Compress(byte[] dest, ref int destLength, byte[] source, int sourceLength)
{
return SafeNativeMethods.compress(dest, ref destLength, source, sourceLength);
}
public ZLibError Compress(byte[] dest, ref int destLength, byte[] source, int sourceLength, ZLibQuality quality)
{
return SafeNativeMethods.compress2(dest, ref destLength, source, sourceLength, quality);
}
public ZLibError Decompress(byte[] dest, ref int destLength, byte[] source, int sourceLength)
{
return SafeNativeMethods.uncompress(dest, ref destLength, source, sourceLength);
}
internal class SafeNativeMethods
{
[DllImport("zlib32")]
internal static extern string zlibVersion();
[DllImport("zlib32")]
internal static extern ZLibError compress(byte[] dest, ref int destLength, byte[] source, int sourceLength);
[DllImport("zlib32")]
internal static extern ZLibError compress2(byte[] dest, ref int destLength, byte[] source, int sourceLength,
ZLibQuality quality);
[DllImport("zlib32")]
internal static extern ZLibError uncompress(byte[] dest, ref int destLen, byte[] source, int sourceLen);
}
}
public sealed class Compressor64 : ICompressor
{
public string Version => SafeNativeMethods.zlibVersion();
public ZLibError Compress(byte[] dest, ref int destLength, byte[] source, int sourceLength)
{
return SafeNativeMethods.compress(dest, ref destLength, source, sourceLength);
}
public ZLibError Compress(byte[] dest, ref int destLength, byte[] source, int sourceLength, ZLibQuality quality)
{
return SafeNativeMethods.compress2(dest, ref destLength, source, sourceLength, quality);
}
public ZLibError Decompress(byte[] dest, ref int destLength, byte[] source, int sourceLength)
{
return SafeNativeMethods.uncompress(dest, ref destLength, source, sourceLength);
}
internal class SafeNativeMethods
{
[DllImport("zlib64")]
internal static extern string zlibVersion();
[DllImport("zlib64")]
internal static extern ZLibError compress(byte[] dest, ref int destLength, byte[] source, int sourceLength);
[DllImport("zlib64")]
internal static extern ZLibError compress2(byte[] dest, ref int destLength, byte[] source, int sourceLength,
ZLibQuality quality);
[DllImport("zlib64")]
internal static extern ZLibError uncompress(byte[] dest, ref int destLen, byte[] source, int sourceLen);
}
}
public sealed class CompressorUnix32 : ICompressor
{
public string Version => SafeNativeMethods.zlibVersion();
public ZLibError Compress(byte[] dest, ref int destLength, byte[] source, int sourceLength)
{
return SafeNativeMethods.compress(dest, ref destLength, source, sourceLength);
}
public ZLibError Compress(byte[] dest, ref int destLength, byte[] source, int sourceLength, ZLibQuality quality)
{
return SafeNativeMethods.compress2(dest, ref destLength, source, sourceLength, quality);
}
public ZLibError Decompress(byte[] dest, ref int destLength, byte[] source, int sourceLength)
{
return SafeNativeMethods.uncompress(dest, ref destLength, source, sourceLength);
}
internal class SafeNativeMethods
{
[DllImport("libz")]
internal static extern string zlibVersion();
[DllImport("libz")]
internal static extern ZLibError compress(byte[] dest, ref int destLength, byte[] source, int sourceLength);
[DllImport("libz")]
internal static extern ZLibError compress2(byte[] dest, ref int destLength, byte[] source, int sourceLength,
ZLibQuality quality);
[DllImport("libz")]
internal static extern ZLibError uncompress(byte[] dest, ref int destLen, byte[] source, int sourceLen);
}
}
public sealed class CompressorUnix64 : ICompressor
{
public string Version => SafeNativeMethods.zlibVersion();
public ZLibError Compress(byte[] dest, ref int destLength, byte[] source, int sourceLength)
{
ulong destLengthLong = (ulong)destLength;
ZLibError z = SafeNativeMethods.compress(dest, ref destLengthLong, source, sourceLength);
destLength = (int)destLengthLong;
return z;
}
public ZLibError Compress(byte[] dest, ref int destLength, byte[] source, int sourceLength, ZLibQuality quality)
{
ulong destLengthLong = (ulong)destLength;
ZLibError z = SafeNativeMethods.compress2(dest, ref destLengthLong, source, sourceLength, quality);
destLength = (int)destLengthLong;
return z;
}
public ZLibError Decompress(byte[] dest, ref int destLength, byte[] source, int sourceLength)
{
ulong destLengthLong = (ulong)destLength;
ZLibError z = SafeNativeMethods.uncompress(dest, ref destLengthLong, source, sourceLength);
destLength = (int)destLengthLong;
return z;
}
internal class SafeNativeMethods
{
[DllImport("libz")]
internal static extern string zlibVersion();
[DllImport("libz")]
internal static extern ZLibError compress(byte[] dest, ref ulong destLength, byte[] source, int sourceLength);
[DllImport("libz")]
internal static extern ZLibError compress2(byte[] dest, ref ulong destLength, byte[] source, int sourceLength,
ZLibQuality quality);
[DllImport("libz")]
internal static extern ZLibError uncompress(byte[] dest, ref ulong destLen, byte[] source, int sourceLen);
}
}
public enum ZLibError
{
VersionError = -6,
BufferError = -5,
MemoryError = -4,
DataError = -3,
StreamError = -2,
FileError = -1,
Okay = 0,
StreamEnd = 1,
NeedDictionary = 2
}
public enum ZLibQuality
{
Default = -1,
None = 0,
Speed = 1,
Size = 9
}
}

View file

@ -0,0 +1,40 @@
/***************************************************************************
* EncodedPacketHandler.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.
*
***************************************************************************/
namespace Server.Network
{
public delegate void OnEncodedPacketReceive(NetState state, IEntity ent, EncodedReader pvSrc);
public class EncodedPacketHandler
{
public EncodedPacketHandler(int packetID, bool ingame, OnEncodedPacketReceive onReceive)
{
PacketID = packetID;
Ingame = ingame;
OnReceive = onReceive;
}
public int PacketID{ get; }
public OnEncodedPacketReceive OnReceive{ get; }
public bool Ingame{ get; }
}
}

View file

@ -0,0 +1,48 @@
/***************************************************************************
* EncodedReader.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.
*
***************************************************************************/
namespace Server.Network
{
public ref struct EncodedReader
{
private PacketReader m_Reader;
public EncodedReader(PacketReader reader)
{
m_Reader = reader;
}
public void Trace(NetState state)
{
m_Reader.Trace(state);
}
public int ReadInt32() => m_Reader.ReadByte() != 0 ? 0 : m_Reader.ReadInt32();
public Point3D ReadPoint3D() => m_Reader.ReadByte() != 3 ? Point3D.Zero :
new Point3D(m_Reader.ReadInt16(), m_Reader.ReadInt16(), m_Reader.ReadByte());
public string ReadUnicodeStringSafe() => m_Reader.ReadByte() != 2 ? string.Empty :
m_Reader.ReadUnicodeStringSafe(m_Reader.ReadUInt16());
public string ReadUnicodeString() => m_Reader.ReadByte() != 2 ? string.Empty :
m_Reader.ReadUnicodeString(m_Reader.ReadUInt16());
}
}

View file

@ -0,0 +1,175 @@
/***************************************************************************
* Listener.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;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace Server.Network
{
public class Listener
{
private Socket m_Socket;
private IPEndPoint m_EndPoint;
public Listener(IPEndPoint ipep)
{
#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_Socket.LingerState.Enabled = false;
m_Socket.ExclusiveAddressUse = false;
m_EndPoint = ipep;
}
public virtual async Task Start(MessagePump pump)
{
try
{
m_Socket.Bind(m_EndPoint);
m_Socket.Listen(8);
}
catch (Exception e)
{
if (e is SocketException se)
{
if (se.ErrorCode == 10048)
{
// WSAEADDRINUSE
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)", m_EndPoint.Address, m_EndPoint.Port);
}
else
{
Console.WriteLine("Listener Exception:");
Console.WriteLine(e);
}
}
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_Socket.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 (UnicastIPAddressInformation unicast in properties.UnicastAddresses)
if (ipep.AddressFamily == unicast.Address.AddressFamily)
Console.WriteLine("Listening: {0}:{1}", unicast.Address, ipep.Port);
}
}
else
{
Console.WriteLine("Listening: {0}:{1}", ipep.Address, ipep.Port);
}
}
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 Release(Socket socket)
{
try
{
socket.Shutdown(SocketShutdown.Both);
}
catch (SocketException ex)
{
NetState.TraceException(ex);
}
try
{
socket.Close();
}
catch (SocketException ex)
{
NetState.TraceException(ex);
}
try
{
socket.Dispose();
}
catch (SocketException ex)
{
NetState.TraceException(ex);
}
}
public void Dispose()
{
Interlocked.Exchange<Socket>(ref m_Socket, null)?.Close();
GC.SuppressFinalize(this);
}
}
}

View file

@ -0,0 +1,77 @@
/***************************************************************************
* MessagePump.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;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net;
namespace Server.Network
{
public class MessagePump
{
private ConcurrentQueue<Work> m_WorkQueue = new ConcurrentQueue<Work>();
public Listener[] Listeners => new Listener[0];
public void AddListener(IPEndPoint ipep)
{
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 void QueueWork(NetState ns, in ReadOnlySequence<byte> seq, OnPacketReceive onReceive)
{
m_WorkQueue.Enqueue(new Work(ns, seq, onReceive));
Core.Set();
}
public void DoWork()
{
int count = m_WorkQueue.Count;
while (count-- > 0)
{
if (!m_WorkQueue.TryDequeue(out Work work))
break;
work.OnReceive(work.State, new PacketReader(work.Sequence));
}
}
// TODO: Optimize this with a pool
private class Work
{
public NetState State;
public ReadOnlySequence<byte> Sequence;
public OnPacketReceive OnReceive;
public Work(NetState ns, in ReadOnlySequence<byte> seq, OnPacketReceive onReceive)
{
State = ns;
Sequence = seq;
OnReceive = onReceive;
}
}
}
}

View file

@ -0,0 +1,764 @@
/***************************************************************************
* NetState.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;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipelines;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Server.Accounting;
using Server.Diagnostics;
using Server.Gumps;
using Server.HuePickers;
using Server.Items;
using Server.Menus;
namespace Server.Network
{
public interface IPacketEncoder
{
void EncodeOutgoingPacket(NetState to, ref Memory<byte> seq);
void DecodeIncomingPacket(NetState from, ref Memory<byte> seq);
}
public delegate void NetStateCreatedCallback(NetState ns);
[Flags]
public enum ProtocolChanges
{
NewSpellbook = 0x00000001,
DamagePacket = 0x00000002,
Unpack = 0x00000004,
BuffIcon = 0x00000008,
NewHaven = 0x00000010,
ContainerGridLines = 0x00000020,
ExtendedSupportedFeatures = 0x00000040,
StygianAbyss = 0x00000080,
HighSeas = 0x00000100,
NewCharacterList = 0x00000200,
NewCharacterCreation = 0x00000400,
ExtendedStatus = 0x00000800,
NewMobileIncoming = 0x00001000,
NewSecureTrading = 0x00002000,
UltimaStore = 0x00004000,
EndlessJourney = 0x00008000,
Version400a = NewSpellbook,
Version407a = Version400a | DamagePacket,
Version500a = Version407a | Unpack,
Version502b = Version500a | BuffIcon,
Version6000 = Version502b | NewHaven,
Version6017 = Version6000 | ContainerGridLines,
Version60142 = Version6017 | ExtendedSupportedFeatures,
Version7000 = Version60142 | StygianAbyss,
Version7090 = Version7000 | HighSeas,
Version70130 = Version7090 | NewCharacterList,
Version70160 = Version70130 | NewCharacterCreation,
Version70300 = Version70160 | ExtendedStatus,
Version70331 = Version70300 | NewMobileIncoming,
Version704565 = Version70331 | NewSecureTrading,
Version70500 = Version704565 | UltimaStore,
Version70610 = Version70500 | EndlessJourney
}
public class AsyncState
{
public bool Paused { get; set; }
public AsyncState(bool paused)
{
Paused = paused;
}
}
public class NetState : IComparable<NetState>
{
private string m_ToString;
private ClientVersion m_Version;
private SendQueue<Packet> m_SendQueue = new SendQueue<Packet>();
public DateTime ConnectedOn { get; }
public TimeSpan ConnectedFor => DateTime.UtcNow - ConnectedOn;
public DateTime ThrottledUntil { get; set; }
internal int m_Seed;
internal int m_AuthID;
public IPAddress Address { get; }
private static AsyncState m_PauseState = new AsyncState(true);
private static AsyncState m_ResumeState = new AsyncState(false);
private static AsyncState m_AsyncState = m_ResumeState;
public IPacketEncoder PacketEncoder { get; set; }
public static NetStateCreatedCallback CreatedCallback { get; set; }
public bool SentFirstPacket { get; set; }
public bool BlockAllPackets { get; set; }
public ClientFlags Flags { get; set; }
public ClientVersion Version
{
get => m_Version;
set
{
m_Version = value;
if (value >= m_Version70610)
ProtocolChanges = ProtocolChanges.Version70610;
if (value >= m_Version70500)
ProtocolChanges = ProtocolChanges.Version70500;
if (value >= m_Version704565)
ProtocolChanges = ProtocolChanges.Version704565;
else if (value >= m_Version70331)
ProtocolChanges = ProtocolChanges.Version70331;
else if (value >= m_Version70300)
ProtocolChanges = ProtocolChanges.Version70300;
else if (value >= m_Version70160)
ProtocolChanges = ProtocolChanges.Version70160;
else if (value >= m_Version70130)
ProtocolChanges = ProtocolChanges.Version70130;
else if (value >= m_Version7090)
ProtocolChanges = ProtocolChanges.Version7090;
else if (value >= m_Version7000)
ProtocolChanges = ProtocolChanges.Version7000;
else if (value >= m_Version60142)
ProtocolChanges = ProtocolChanges.Version60142;
else if (value >= m_Version6017)
ProtocolChanges = ProtocolChanges.Version6017;
else if (value >= m_Version6000)
ProtocolChanges = ProtocolChanges.Version6000;
else if (value >= m_Version502b)
ProtocolChanges = ProtocolChanges.Version502b;
else if (value >= m_Version500a)
ProtocolChanges = ProtocolChanges.Version500a;
else if (value >= m_Version407a)
ProtocolChanges = ProtocolChanges.Version407a;
else if (value >= m_Version400a) ProtocolChanges = ProtocolChanges.Version400a;
}
}
private static readonly ClientVersion m_Version400a = new ClientVersion("4.0.0a");
private static readonly ClientVersion m_Version407a = new ClientVersion("4.0.7a");
private static readonly ClientVersion m_Version500a = new ClientVersion("5.0.0a");
private static readonly ClientVersion m_Version502b = new ClientVersion("5.0.2b");
private static readonly ClientVersion m_Version6000 = new ClientVersion("6.0.0.0");
private static readonly ClientVersion m_Version6017 = new ClientVersion("6.0.1.7");
private static readonly ClientVersion m_Version60142 = new ClientVersion("6.0.14.2");
private static readonly ClientVersion m_Version7000 = new ClientVersion("7.0.0.0");
private static readonly ClientVersion m_Version7090 = new ClientVersion("7.0.9.0");
private static readonly ClientVersion m_Version70130 = new ClientVersion("7.0.13.0");
private static readonly ClientVersion m_Version70160 = new ClientVersion("7.0.16.0");
private static readonly ClientVersion m_Version70300 = new ClientVersion("7.0.30.0");
private static readonly ClientVersion m_Version70331 = new ClientVersion("7.0.33.1");
private static readonly ClientVersion m_Version704565 = new ClientVersion("7.0.45.65");
private static readonly ClientVersion m_Version70500 = new ClientVersion("7.0.50.0");
private static readonly ClientVersion m_Version70610 = new ClientVersion("7.0.61.0");
public bool NewSpellbook => (ProtocolChanges & ProtocolChanges.NewSpellbook) != 0;
public bool DamagePacket => (ProtocolChanges & ProtocolChanges.DamagePacket) != 0;
public bool Unpack => (ProtocolChanges & ProtocolChanges.Unpack) != 0;
public bool BuffIcon => (ProtocolChanges & ProtocolChanges.BuffIcon) != 0;
public bool NewHaven => (ProtocolChanges & ProtocolChanges.NewHaven) != 0;
public bool ContainerGridLines => (ProtocolChanges & ProtocolChanges.ContainerGridLines) != 0;
public bool ExtendedSupportedFeatures => (ProtocolChanges & ProtocolChanges.ExtendedSupportedFeatures) != 0;
public bool StygianAbyss => (ProtocolChanges & ProtocolChanges.StygianAbyss) != 0;
public bool HighSeas => (ProtocolChanges & ProtocolChanges.HighSeas) != 0;
public bool NewCharacterList => (ProtocolChanges & ProtocolChanges.NewCharacterList) != 0;
public bool NewCharacterCreation => (ProtocolChanges & ProtocolChanges.NewCharacterCreation) != 0;
public bool ExtendedStatus => (ProtocolChanges & ProtocolChanges.ExtendedStatus) != 0;
public bool NewMobileIncoming => (ProtocolChanges & ProtocolChanges.NewMobileIncoming) != 0;
public bool NewSecureTrading => (ProtocolChanges & ProtocolChanges.NewSecureTrading) != 0;
public bool IsUOTDClient =>
(Flags & ClientFlags.UOTD) != 0 || m_Version?.Type == ClientType.UOTD;
public bool IsSAClient => m_Version?.Type == ClientType.SA;
public List<SecureTrade> Trades { get; }
public void ValidateAllTrades()
{
for (int i = Trades.Count - 1; i >= 0; --i)
{
if (i >= Trades.Count) continue;
SecureTrade trade = Trades[i];
if (trade.From.Mobile.Deleted || trade.To.Mobile.Deleted || !trade.From.Mobile.Alive ||
!trade.To.Mobile.Alive || !trade.From.Mobile.InRange(trade.To.Mobile, 2) ||
trade.From.Mobile.Map != trade.To.Mobile.Map) trade.Cancel();
}
}
public void CancelAllTrades()
{
for (int i = Trades.Count - 1; i >= 0; --i)
if (i < Trades.Count)
Trades[i].Cancel();
}
public void RemoveTrade(SecureTrade trade)
{
Trades.Remove(trade);
}
public SecureTrade FindTrade(Mobile m)
{
for (int i = 0; i < Trades.Count; ++i)
{
SecureTrade trade = Trades[i];
if (trade.From.Mobile == m || trade.To.Mobile == m) return trade;
}
return null;
}
public SecureTradeContainer FindTradeContainer(Mobile m)
{
for (int i = 0; i < Trades.Count; ++i)
{
SecureTrade trade = Trades[i];
SecureTradeInfo from = trade.From;
SecureTradeInfo to = trade.To;
if (from.Mobile == Mobile && to.Mobile == m) return from.Container;
if (from.Mobile == m && to.Mobile == Mobile) return to.Container;
}
return null;
}
public SecureTradeContainer AddTrade(NetState state)
{
SecureTrade newTrade = new SecureTrade(Mobile, state.Mobile);
Trades.Add(newTrade);
state.Trades.Add(newTrade);
return newTrade.From.Container;
}
public bool Running { get; private set; }
public bool Seeded { get; set; }
public Socket Socket { get; private set; }
public bool CompressionEnabled { get; set; }
public int Sequence { get; set; }
public List<Gump> Gumps { get; private set; }
public List<HuePicker> HuePickers { get; private set; }
public List<IMenu> Menus { get; private set; }
public static int GumpCap { get; set; } = 512;
public static int HuePickerCap { get; set; } = 512;
public static int MenuCap { get; set; } = 512;
public void WriteConsole(string text)
{
Console.WriteLine("Client: {0}: {1}", this, text);
}
public void WriteConsole(string format, params object[] args)
{
WriteConsole(string.Format(format, args));
}
public void AddMenu(IMenu menu)
{
if (Menus == null)
Menus = new List<IMenu>();
if (Menus.Count < MenuCap)
Menus.Add(menu);
else
{
WriteConsole("Exceeded menu cap, disconnecting...");
Dispose();
}
}
public void RemoveMenu(IMenu menu)
{
Menus?.Remove(menu);
}
public void RemoveMenu(int index)
{
Menus?.RemoveAt(index);
}
public void ClearMenus()
{
Menus?.Clear();
}
public void AddHuePicker(HuePicker huePicker)
{
if (HuePickers == null)
HuePickers = new List<HuePicker>();
if (HuePickers.Count < HuePickerCap)
HuePickers.Add(huePicker);
else
{
WriteConsole("Exceeded hue picker cap, disconnecting...");
Dispose();
}
}
public void RemoveHuePicker(HuePicker huePicker)
{
HuePickers?.Remove(huePicker);
}
public void RemoveHuePicker(int index)
{
HuePickers?.RemoveAt(index);
}
public void ClearHuePickers()
{
HuePickers?.Clear();
}
public void AddGump(Gump gump)
{
if (Gumps == null)
Gumps = new List<Gump>();
if (Gumps.Count < GumpCap)
Gumps.Add(gump);
else
{
WriteConsole("Exceeded gump cap, disconnecting...");
Dispose();
}
}
public void RemoveGump(Gump gump)
{
Gumps?.Remove(gump);
}
public void RemoveGump(int index)
{
Gumps?.RemoveAt(index);
}
public void ClearGumps()
{
Gumps?.Clear();
}
public void LaunchBrowser(string url)
{
Send(new MessageLocalized(Serial.MinusOne, -1, MessageType.Label, 0x35, 3, 501231, "", ""));
Send(new LaunchBrowser(url));
}
public CityInfo[] CityInfo { get; set; }
public Mobile Mobile { get; set; }
public ServerInfo[] ServerInfo { get; set; }
public IAccount Account { get; set; }
public override string ToString()
{
return m_ToString;
}
public static List<NetState> Instances { get; } = new List<NetState>();
public NetState(Socket socket, MessagePump pump)
{
Socket = socket;
Seeded = false;
Running = false;
Gumps = new List<Gump>();
HuePickers = new List<HuePicker>();
Menus = new List<IMenu>();
Trades = new List<SecureTrade>();
m_NextCheckActivity = Core.TickCount + 30000;
Instances.Add(this);
try
{
Address = Utility.Intern(((IPEndPoint)Socket.RemoteEndPoint).Address);
m_ToString = Address.ToString();
}
catch (Exception ex)
{
TraceException(ex);
Address = IPAddress.None;
m_ToString = "(error)";
}
ConnectedOn = DateTime.UtcNow;
_ = Start(pump);
CreatedCallback?.Invoke(this);
Console.WriteLine("Client: {0}: Connected. [{1} Online]", this, NetState.Instances.Count);
}
public static void Pause()
{
m_AsyncState = Interlocked.Exchange(ref m_AsyncState, m_PauseState);
}
public static void Resume()
{
m_AsyncState = Interlocked.Exchange(ref m_AsyncState, m_ResumeState);
}
public virtual void Send(Packet p)
{
if (Socket == null || BlockAllPackets)
{
p.OnSend();
return;
}
m_SendQueue.Enqueue(p);
}
public bool CheckEncrypted(int packetID)
{
if (!SentFirstPacket && packetID != 0xF0 && packetID != 0xF1 && packetID != 0xCF && packetID != 0x80 &&
packetID != 0x91 && packetID != 0xA4 && packetID != 0xEF)
{
Console.WriteLine("Client: {0}: Encrypted client detected, disconnecting", this);
Dispose();
return true;
}
return false;
}
private Pipe m_RecvdPipe;
private async Task Start(MessagePump pump)
{
m_RecvdPipe = new Pipe();
Running = true;
await Task.WhenAll(ProcessSends(), ProcessRecvs(), HandlePackets(pump)).ConfigureAwait(false);
}
private async Task ProcessRecvs()
{
PipeWriter w = m_RecvdPipe.Writer;
while (true)
{
if (m_AsyncState.Paused)
{
await Timer.Pause(50).ConfigureAwait(false);
continue;
}
try
{
Memory<byte> memory = w.GetMemory();
int bytesRead = await Socket.ReceiveAsync(memory, SocketFlags.None).ConfigureAwait(false);
if (bytesRead == 0)
break;
Interlocked.Exchange(ref m_NextCheckActivity, Core.TickCount + 90000);
w.Advance(bytesRead);
FlushResult result = await w.FlushAsync().ConfigureAwait(false);
if (result.IsCompleted || result.IsCanceled)
break;
}
catch
{
break;
}
}
w.Complete();
Dispose();
}
private async Task ProcessSends()
{
while (true)
{
try
{
Packet p = await m_SendQueue?.DequeueAsync() ?? null;
if (p == null)
break;
ReadOnlyMemory<byte> buffer = p.Compile(CompressionEnabled, out int length);
if (buffer.Length <= 0 || length <= 0)
{
p.OnSend();
return;
}
buffer = buffer.Slice(0, length);
PacketSendProfile prof = null;
if (Core.Profiling)
prof = PacketSendProfile.Acquire(p.GetType());
prof?.Start();
await Socket.SendAsync(buffer, SocketFlags.None).ConfigureAwait(false);
p.OnSend();
prof?.Finish(length);
}
catch (SocketException ex)
{
Console.WriteLine(ex);
TraceException(ex);
Dispose();
break;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
private async Task HandlePackets(MessagePump pump)
{
PipeReader pr = m_RecvdPipe.Reader;
while (true)
{
ReadResult result = await pr.ReadAsync();
ReadOnlySequence<byte> seq = result.Buffer;
if (seq.Length == 0)
break;
long pos = PacketHandlers.ProcessPacket(pump, this, seq);
if (pos <= 0)
break;
pr.AdvanceTo(seq.GetPosition(pos, seq.Start));
if (result.IsCompleted || result.IsCanceled)
break;
}
pr.Complete();
}
public PacketHandler GetHandler(int packetID)
{
return ContainerGridLines ? PacketHandlers.Get6017Handler(packetID) :
PacketHandlers.GetHandler(packetID);
}
private long m_NextCheckActivity;
public void CheckAlive(long curTicks)
{
if (Socket == null || m_NextCheckActivity - curTicks >= 0)
return;
Console.WriteLine("Client: {0}: Disconnecting due to inactivity...", this);
Dispose();
}
public static void TraceException(Exception ex)
{
if (!Core.Debug)
return;
try
{
using (StreamWriter op = new StreamWriter("network-errors.log", true))
{
op.WriteLine("# {0}", DateTime.UtcNow);
op.WriteLine(ex);
op.WriteLine();
op.WriteLine();
}
}
catch
{
// ignored
}
Console.WriteLine(ex);
}
private int m_Disposing;
public bool IsDisposing { get { return m_Disposing != 0; } private set { m_Disposing = value ? 1 : 0; } }
public virtual void Dispose()
{
int disposing = Interlocked.Exchange(ref m_Disposing, 1);
if (disposing == 1)
return;
Task.Run(async () =>
{
m_RecvdPipe.Reader.CancelPendingRead();
m_RecvdPipe.Reader.Complete();
await m_RecvdPipe.Writer.FlushAsync().ConfigureAwait(false);
m_RecvdPipe.Writer.Complete();
try { Socket.Shutdown(SocketShutdown.Both); } catch (Exception ex) { TraceException(ex); }
try { Socket.Close(); } catch (Exception ex) { TraceException(ex); }
Socket = null;
m_RecvdPipe = null;
m_SendQueue = null;
m_Disposed.Enqueue(this);
});
}
public static void Initialize()
{
Timer.DelayCall(TimeSpan.FromMinutes(1.0), TimeSpan.FromMinutes(1.5), CheckAllAlive);
}
public static void CheckAllAlive()
{
try
{
long curTicks = Core.TickCount;
if (Instances.Count >= 1024)
Parallel.ForEach(Instances, ns => ns.CheckAlive(curTicks));
else
for (int i = 0; i < Instances.Count; ++i)
Instances[i].CheckAlive(curTicks);
}
catch (Exception ex)
{
TraceException(ex);
}
}
private static ConcurrentQueue<NetState> m_Disposed = new ConcurrentQueue<NetState>();
public static void ProcessDisposedQueue()
{
int breakout = 0;
while (breakout++ < 200)
{
if (!m_Disposed.TryDequeue(out NetState ns))
break;
Mobile m = ns.Mobile;
IAccount a = ns.Account;
if (m != null)
{
m.NetState = null;
ns.Mobile = null;
}
ns.Gumps.Clear();
ns.Menus.Clear();
ns.HuePickers.Clear();
ns.Account = null;
ns.ServerInfo = null;
ns.CityInfo = null;
Instances.Remove(ns);
if (a != null)
ns.WriteConsole("Disconnected. [{0} Online] [{1}]", Instances.Count, a);
else
ns.WriteConsole("Disconnected. [{0} Online]", Instances.Count);
}
}
public ExpansionInfo ExpansionInfo
{
get
{
for (int i = ExpansionInfo.Table.Length - 1; i >= 0; i--)
{
ExpansionInfo info = ExpansionInfo.Table[i];
if (info.RequiredClient != null && Version >= info.RequiredClient || (Flags & info.ClientFlags) != 0)
return info;
}
return ExpansionInfo.GetInfo(Expansion.None);
}
}
public Expansion Expansion => (Expansion)ExpansionInfo.ID;
public ProtocolChanges ProtocolChanges { get; set; }
public bool SupportsExpansion(ExpansionInfo info, bool checkCoreExpansion = true)
{
if (info == null || checkCoreExpansion && (int)Core.Expansion < info.ID)
return false;
return info.RequiredClient != null ? Version >= info.RequiredClient : (Flags & info.ClientFlags) != 0;
}
public bool SupportsExpansion(Expansion ex, bool checkCoreExpansion = true)
{
return SupportsExpansion(ExpansionInfo.GetInfo(ex), checkCoreExpansion);
}
public int CompareTo(NetState other)
{
return other == null ? 1 : m_ToString.CompareTo(other.m_ToString);
}
}
}

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

@ -0,0 +1,49 @@
/***************************************************************************
* PacketHandler.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 delegate void OnPacketReceive(NetState state, PacketReader pvSrc);
public delegate TimeSpan ThrottlePacketCallback(NetState state);
public class PacketHandler
{
public PacketHandler(int packetID, long length, bool ingame, OnPacketReceive onReceive)
{
PacketID = packetID;
Length = length;
Ingame = ingame;
OnReceive = onReceive;
}
public int PacketID{ get; }
public long Length{ get; }
public OnPacketReceive OnReceive{ get; }
public ThrottlePacketCallback ThrottleCallback{ get; set; }
public bool Ingame{ get; }
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,315 @@
/***************************************************************************
* PacketReader.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;
using System.Buffers;
using System.IO;
using System.IO.Pipelines;
using System.Text;
namespace Server.Network
{
public ref struct PacketReader
{
private SequenceReader<byte> m_Reader;
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)
{
m_Reader = new SequenceReader<byte>(seq);
}
public byte Peek() => m_Reader.TryPeek(out byte value) ? value : (byte)0;
public void Trace(NetState state)
{
try
{
using (StreamWriter sw = new StreamWriter("Packets.log", true))
{
byte[] buffer = m_Reader.Sequence.ToArray();
if (buffer.Length > 0)
sw.WriteLine("Client: {0}: Unhandled packet 0x{1:X2}", state, buffer[0]);
using (MemoryStream ms = new MemoryStream(buffer))
{
Utility.FormatBuffer(sw, ms, buffer.Length);
}
sw.WriteLine();
sw.WriteLine();
}
}
catch
{
// ignored
}
}
public SequencePosition Seek(long offset, SeekOrigin origin)
{
switch (origin)
{
case SeekOrigin.Begin:
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:
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:
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_Reader.Position;
}
public bool TryReadByte(out byte value) => m_Reader.TryRead(out value);
public int ReadInt32() => m_Reader.TryReadBigEndian(out int value) ? value : 0;
public short ReadInt16() => m_Reader.TryReadBigEndian(out short value) ? value : (short)0;
public byte ReadByte() => m_Reader.TryRead(out byte value) ? value : (byte)0;
public uint ReadUInt32() => (uint)ReadInt32();
public ushort ReadUInt16() => (ushort)ReadInt16();
public sbyte ReadSByte() => (sbyte)ReadByte();
public bool ReadBoolean() => ReadByte() > 0;
public string ReadUnicodeStringLE()
{
StringBuilder sb = new StringBuilder();
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)
{
StringBuilder sb = new StringBuilder();
while (fixedLength-- > 0 && m_Reader.TryReadLittleEndian(out short c) && c != 0)
if (IsSafeChar(c))
sb.Append((char)c);
if (fixedLength > 0)
m_Reader.Advance(fixedLength * 2);
return sb.ToString();
}
public string ReadUnicodeStringLESafe()
{
StringBuilder sb = new StringBuilder();
while (m_Reader.TryReadLittleEndian(out short c) && c != 0)
if (IsSafeChar(c))
sb.Append((char)c);
return sb.ToString();
}
public string ReadUnicodeStringSafe()
{
StringBuilder sb = new StringBuilder();
while (m_Reader.TryReadBigEndian(out short c) && c != 0)
if (IsSafeChar(c))
sb.Append((char)c);
return sb.ToString();
}
public string ReadUnicodeString()
{
StringBuilder sb = new StringBuilder();
while (m_Reader.TryReadBigEndian(out short c) && c != 0)
sb.Append((char)c);
return sb.ToString();
}
public bool IsSafeChar(int c)
{
return c >= 0x20 && c < 0xFFFE;
}
public string ReadUTF8StringSafe(int fixedLength)
{
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
{
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);
}
StringBuilder sb = new StringBuilder(s.Length);
for (int i = 0; i < s.Length; ++i)
if (IsSafeChar(s[i]))
sb.Append(s[i]);
return sb.ToString();
}
public string ReadUTF8StringSafe()
{
string 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);
for (int i = 0; i < s.Length; ++i)
if (IsSafeChar(s[i]))
sb.Append(s[i]);
return sb.ToString();
}
public string ReadUTF8String()
{
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();
while (m_Reader.TryRead(out byte c))
sb.Append((char)c);
return sb.ToString();
}
public string ReadStringSafe()
{
StringBuilder sb = new StringBuilder();
while (m_Reader.TryRead(out byte c))
if (IsSafeChar(c))
sb.Append((char)c);
return sb.ToString();
}
public string ReadUnicodeStringSafe(int fixedLength)
{
StringBuilder sb = new StringBuilder();
while (fixedLength-- > 0 && m_Reader.TryReadBigEndian(out short c) && c != 0)
if (IsSafeChar(c))
sb.Append((char)c);
if (fixedLength > 0)
m_Reader.Advance(fixedLength * 2);
return sb.ToString();
}
public string ReadUnicodeString(int fixedLength)
{
StringBuilder sb = new StringBuilder();
while (fixedLength-- > 0 && m_Reader.TryReadBigEndian(out short c) && c != 0)
sb.Append((char)c);
if (fixedLength > 0)
m_Reader.Advance(fixedLength * 2);
return sb.ToString();
}
public string ReadStringSafe(int fixedLength)
{
StringBuilder sb = new StringBuilder();
while (fixedLength-- > 0 && m_Reader.TryRead(out byte c) && c != 0)
if (IsSafeChar(c))
sb.Append((char)c);
if (fixedLength > 0)
m_Reader.Advance(fixedLength);
return sb.ToString();
}
public string ReadString(int fixedLength)
{
StringBuilder sb = new StringBuilder();
while (fixedLength-- > 0 && m_Reader.TryRead(out byte c) && c != 0)
sb.Append((char)c);
if (fixedLength > 0)
m_Reader.Advance(fixedLength);
return sb.ToString();
}
}
}

View file

@ -0,0 +1,346 @@
/***************************************************************************
* PacketWriter.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;
using System.Collections.Concurrent;
using System.IO;
using System.Text;
namespace Server.Network
{
/// <summary>
/// Provides functionality for writing primitive binary data.
/// </summary>
public class PacketWriter
{
private static ConcurrentQueue<PacketWriter> m_Pool = new ConcurrentQueue<PacketWriter>();
/// <summary>
/// Internal format buffer.
/// </summary>
private byte[] m_Buffer = new byte[4];
private int m_Capacity;
/// <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)
{
UnderlyingStream = new MemoryStream(capacity);
m_Capacity = capacity;
}
/// <summary>
/// Gets the total stream length.
/// </summary>
public long Length => UnderlyingStream.Length;
/// <summary>
/// Gets or sets the current stream position.
/// </summary>
public long Position
{
get => UnderlyingStream.Position;
set => UnderlyingStream.Position = value;
}
/// <summary>
/// The internal stream used by this PacketWriter instance.
/// </summary>
public MemoryStream UnderlyingStream { get; private set; }
public static PacketWriter CreateInstance(int capacity = 32)
{
if (m_Pool.TryDequeue(out PacketWriter pw))
{
pw.m_Capacity = capacity;
pw.UnderlyingStream.SetLength(0);
return pw;
}
return new PacketWriter(capacity);
}
public static void ReleaseInstance(PacketWriter pw)
{
m_Pool.Enqueue(pw);
}
/// <summary>
/// Writes a 1-byte boolean value to the underlying stream. False is represented by 0, true by 1.
/// </summary>
public void Write(bool value)
{
UnderlyingStream.WriteByte((byte)(value ? 1 : 0));
}
/// <summary>
/// Writes a 1-byte unsigned integer value to the underlying stream.
/// </summary>
public void Write(byte value)
{
UnderlyingStream.WriteByte(value);
}
/// <summary>
/// Writes a 1-byte signed integer value to the underlying stream.
/// </summary>
public void Write(sbyte value)
{
UnderlyingStream.WriteByte((byte)value);
}
/// <summary>
/// Writes a 2-byte signed integer value to the underlying stream.
/// </summary>
public void Write(short value)
{
m_Buffer[0] = (byte)(value >> 8);
m_Buffer[1] = (byte)value;
UnderlyingStream.Write(m_Buffer, 0, 2);
}
/// <summary>
/// Writes a 2-byte unsigned integer value to the underlying stream.
/// </summary>
public void Write(ushort value)
{
m_Buffer[0] = (byte)(value >> 8);
m_Buffer[1] = (byte)value;
UnderlyingStream.Write(m_Buffer, 0, 2);
}
/// <summary>
/// Writes a 4-byte signed integer value to the underlying stream.
/// </summary>
public void Write(int value)
{
m_Buffer[0] = (byte)(value >> 24);
m_Buffer[1] = (byte)(value >> 16);
m_Buffer[2] = (byte)(value >> 8);
m_Buffer[3] = (byte)value;
UnderlyingStream.Write(m_Buffer, 0, 4);
}
/// <summary>
/// Writes a 4-byte unsigned integer value to the underlying stream.
/// </summary>
public void Write(uint value)
{
m_Buffer[0] = (byte)(value >> 24);
m_Buffer[1] = (byte)(value >> 16);
m_Buffer[2] = (byte)(value >> 8);
m_Buffer[3] = (byte)value;
UnderlyingStream.Write(m_Buffer, 0, 4);
}
/// <summary>
/// Writes a sequence of bytes to the underlying stream
/// </summary>
public void Write(byte[] buffer, int offset, int size)
{
UnderlyingStream.Write(buffer, offset, size);
}
/// <summary>
/// Writes a fixed-length ASCII-encoded string value to the underlying stream. To fit (size), the string content is either
/// truncated or padded with null characters.
/// </summary>
public void WriteAsciiFixed(string value, int size)
{
if (value == null)
{
Console.WriteLine("Network: Attempted to WriteAsciiFixed() with null value");
value = string.Empty;
}
int length = value.Length;
UnderlyingStream.SetLength(UnderlyingStream.Length + size);
if (length >= size)
{
UnderlyingStream.Position +=
Encoding.ASCII.GetBytes(value, 0, size, UnderlyingStream.GetBuffer(), (int)UnderlyingStream.Position);
}
else
{
Encoding.ASCII.GetBytes(value, 0, length, UnderlyingStream.GetBuffer(), (int)UnderlyingStream.Position);
UnderlyingStream.Position += size;
}
}
/// <summary>
/// Writes a dynamic-length ASCII-encoded string value to the underlying stream, followed by a 1-byte null character.
/// </summary>
public void WriteAsciiNull(string value)
{
if (value == null)
{
Console.WriteLine("Network: Attempted to WriteAsciiNull() with null value");
value = string.Empty;
}
int length = value.Length;
UnderlyingStream.SetLength(UnderlyingStream.Length + length + 1);
Encoding.ASCII.GetBytes(value, 0, length, UnderlyingStream.GetBuffer(), (int)UnderlyingStream.Position);
UnderlyingStream.Position += length + 1;
}
/// <summary>
/// Writes a dynamic-length little-endian unicode string value to the underlying stream, followed by a 2-byte null character.
/// </summary>
public void WriteLittleUniNull(string value)
{
if (value == null)
{
Console.WriteLine("Network: Attempted to WriteLittleUniNull() with null value");
value = string.Empty;
}
int length = value.Length;
UnderlyingStream.SetLength(UnderlyingStream.Length + (length + 1) * 2);
UnderlyingStream.Position += Encoding.Unicode.GetBytes(value, 0, length, UnderlyingStream.GetBuffer(), (int)UnderlyingStream.Position);
UnderlyingStream.Position += 2;
}
/// <summary>
/// Writes a fixed-length little-endian unicode string value to the underlying stream. To fit (size), the string content is
/// either truncated or padded with null characters.
/// </summary>
public void WriteLittleUniFixed(string value, int size)
{
if (value == null)
{
Console.WriteLine("Network: Attempted to WriteLittleUniFixed() with null value");
value = string.Empty;
}
int length = value.Length;
size *= 2;
UnderlyingStream.SetLength(UnderlyingStream.Length + size);
if (length * 2 >= size)
{
UnderlyingStream.Position +=
Encoding.Unicode.GetBytes(value, 0, size, UnderlyingStream.GetBuffer(), (int)UnderlyingStream.Position);
}
else
{
Encoding.Unicode.GetBytes(value, 0, length, UnderlyingStream.GetBuffer(), (int)UnderlyingStream.Position);
UnderlyingStream.Position += size;
}
}
/// <summary>
/// Writes a dynamic-length big-endian unicode string value to the underlying stream, followed by a 2-byte null character.
/// </summary>
public void WriteBigUniNull(string value)
{
if (value == null)
{
Console.WriteLine("Network: Attempted to WriteBigUniNull() with null value");
value = string.Empty;
}
int length = value.Length;
UnderlyingStream.SetLength(UnderlyingStream.Length + (length + 1) * 2);
UnderlyingStream.Position +=
Encoding.BigEndianUnicode.GetBytes(value, 0, length, UnderlyingStream.GetBuffer(), (int)UnderlyingStream.Position);
UnderlyingStream.Position += 2;
}
/// <summary>
/// Writes a fixed-length big-endian unicode string value to the underlying stream. To fit (size), the string content is
/// either truncated or padded with null characters.
/// </summary>
public void WriteBigUniFixed(string value, int size)
{
if (value == null)
{
Console.WriteLine("Network: Attempted to WriteBigUniFixed() with null value");
value = string.Empty;
}
int length = value.Length;
size *= 2;
UnderlyingStream.SetLength(UnderlyingStream.Length + size);
if (length * 2 >= size )
{
UnderlyingStream.Position +=
Encoding.BigEndianUnicode.GetBytes(value, 0, size, UnderlyingStream.GetBuffer(), (int)UnderlyingStream.Position);
}
else
{
Encoding.BigEndianUnicode.GetBytes(value, 0, length, UnderlyingStream.GetBuffer(), (int)UnderlyingStream.Position);
UnderlyingStream.Position += size;
}
}
/// <summary>
/// Fills the stream from the current position up to (capacity) with 0x00's
/// </summary>
public void Fill()
{
Fill(m_Capacity - UnderlyingStream.Length);
}
/// <summary>
/// Writes a number of 0x00 byte values to the underlying stream.
/// </summary>
public void Fill(long length)
{
if (UnderlyingStream.Position == UnderlyingStream.Length)
{
UnderlyingStream.SetLength(UnderlyingStream.Length + length);
UnderlyingStream.Seek(0, SeekOrigin.End);
}
else
{
UnderlyingStream.Write(new byte[length], 0, (int)length);
}
}
/// <summary>
/// Offsets the current position from an origin.
/// </summary>
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() => UnderlyingStream.ToArray();
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,51 @@
/***************************************************************************
* SendQueue.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.Concurrent;
using System.Threading.Tasks;
namespace Server.Network
{
public class SendQueue<T>
{
private BlockingCollection<T> m_Queue = new BlockingCollection<T>(new ConcurrentQueue<T>());
public SendQueue()
{
}
public void Enqueue(T t)
{
m_Queue.Add(t);
}
public Task<T> DequeueAsync()
{
TaskCompletionSource<T> taskCompletion = new TaskCompletionSource<T>();
Task.Run(() => taskCompletion.SetResult(Dequeue()));
return taskCompletion.Task;
}
public T Dequeue()
{
return m_Queue.Take();
}
}
}

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

@ -0,0 +1,135 @@
/***************************************************************************
* 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
{
public static class StaticPacketHandlers
{
private static ConcurrentDictionary<IPropertyListObject,OPLInfo> OPLInfoPackets = new ConcurrentDictionary<IPropertyListObject,OPLInfo>();
private static ConcurrentDictionary<IPropertyListObject,ObjectPropertyList> ObjectPropertyListPackets = new ConcurrentDictionary<IPropertyListObject,ObjectPropertyList>();
private static ConcurrentDictionary<IEntity,RemoveEntity> RemoveEntityPackets = new ConcurrentDictionary<IEntity,RemoveEntity>();
private static ConcurrentDictionary<Item,WorldItem> WorldItemPackets = new ConcurrentDictionary<Item,WorldItem>();
private static ConcurrentDictionary<Item,WorldItemSA> WorldItemSAPackets = new ConcurrentDictionary<Item,WorldItemSA>();
private static ConcurrentDictionary<Item,WorldItemHS> WorldItemHSPackets = new ConcurrentDictionary<Item,WorldItemHS>();
public static OPLInfo GetOPLInfoPacket(IPropertyListObject obj)
{
return OPLInfoPackets.GetOrAdd(obj, value =>
{
OPLInfo packet = new OPLInfo(value.PropertyList);
packet.SetStatic();
return packet;
});
}
public static OPLInfo FreeOPLInfoPacket(IPropertyListObject obj)
{
if (OPLInfoPackets.TryRemove(obj, out OPLInfo p))
Packet.Release(p);
return p;
}
public static ObjectPropertyList GetOPLPacket(IPropertyListObject obj)
{
return ObjectPropertyListPackets.GetOrAdd(obj, value =>
{
ObjectPropertyList list = new ObjectPropertyList(value);
value.GetProperties(list);
if (value is Item item)
item.AppendChildProperties(list);
list.Terminate();
list.SetStatic();
return list;
});
}
public static ObjectPropertyList FreeOPLPacket(IPropertyListObject obj)
{
if (ObjectPropertyListPackets.TryRemove(obj, out ObjectPropertyList list))
Packet.Release(list);
return list;
}
public static RemoveEntity GetRemoveEntityPacket(IEntity entity)
{
return RemoveEntityPackets.GetOrAdd(entity, value =>
{
RemoveEntity packet = new RemoveEntity(value);
packet.SetStatic();
return packet;
});
}
public static void FreeRemoveItemPacket(IEntity entity)
{
if (RemoveEntityPackets.TryRemove(entity, out RemoveEntity p))
Packet.Release(p);
}
public static WorldItem GetWorldItemPacket(Item item)
{
return WorldItemPackets.GetOrAdd(item, value =>
{
WorldItem packet = new WorldItem(value);
packet.SetStatic();
return packet;
});
}
public static WorldItemSA GetWorldItemSAPacket(Item item)
{
return WorldItemSAPackets.GetOrAdd(item, value =>
{
WorldItemSA packet = new WorldItemSA(value);
packet.SetStatic();
return packet;
});
}
public static WorldItemHS GetWorldItemHSPacket(Item item)
{
return WorldItemHSPackets.GetOrAdd(item, value =>
{
WorldItemHS packet = new WorldItemHS(value);
packet.SetStatic();
return packet;
});
}
public static void FreeWorldItemPackets(Item item)
{
if (WorldItemPackets.TryRemove(item, out WorldItem wi))
Packet.Release(wi);
if (WorldItemSAPackets.TryRemove(item, out WorldItemSA wisa))
Packet.Release(wisa);
if (WorldItemHSPackets.TryRemove(item, out WorldItemHS wihs))
Packet.Release(wihs);
}
}
}