Adds style cop (#109)

This commit is contained in:
Kamron Batman 2020-04-26 00:16:02 -07:00 committed by GitHub
parent 3e715bcb60
commit 556a17aba8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
1725 changed files with 33831 additions and 38046 deletions

View file

@ -31,10 +31,10 @@ namespace Server.Network
OnReceive = onReceive;
}
public int PacketID{ get; }
public int PacketID { get; }
public OnEncodedPacketReceive OnReceive{ get; }
public OnEncodedPacketReceive OnReceive { get; }
public bool Ingame{ get; }
public bool Ingame { get; }
}
}

View file

@ -33,13 +33,14 @@ namespace Server.Network
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 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 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());
public string ReadUnicodeString() =>
m_Reader.ReadByte() != 2 ? string.Empty : m_Reader.ReadUnicodeString(m_Reader.ReadUInt16());
}
}

View file

@ -1,6 +1,6 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019 - ModernUO Development Team *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: MessagePumpService.cs *
* Created: 2020/04/12 - Updated: 2020/04/12 *
@ -42,10 +42,10 @@ namespace Server.Network
public void DoWork()
{
int count = 0;
var count = 0;
while (!m_WorkQueue.IsEmpty && count++ < 250)
{
if (!m_WorkQueue.TryDequeue(out Work work))
if (!m_WorkQueue.TryDequeue(out var work))
break;
work.OnReceive(work.State, new PacketReader(new ReadOnlySequence<byte>(work.MemoryOwner.Memory)));
@ -56,6 +56,7 @@ namespace Server.Network
private class Work
{
public readonly NetState State;
// TODO: Force dispose?
public readonly IMemoryOwner<byte> MemoryOwner;
public readonly OnPacketReceive OnReceive;

View file

@ -22,7 +22,6 @@ using System;
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;
@ -202,11 +201,11 @@ namespace Server.Network
public void ValidateAllTrades()
{
for (int i = Trades.Count - 1; i >= 0; --i)
for (var i = Trades.Count - 1; i >= 0; --i)
{
if (i >= Trades.Count) continue;
SecureTrade trade = Trades[i];
var 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) ||
@ -216,7 +215,7 @@ namespace Server.Network
public void CancelAllTrades()
{
for (int i = Trades.Count - 1; i >= 0; --i)
for (var i = Trades.Count - 1; i >= 0; --i)
if (i < Trades.Count)
Trades[i].Cancel();
}
@ -228,9 +227,9 @@ namespace Server.Network
public SecureTrade FindTrade(Mobile m)
{
for (int i = 0; i < Trades.Count; ++i)
for (var i = 0; i < Trades.Count; ++i)
{
SecureTrade trade = Trades[i];
var trade = Trades[i];
if (trade.From.Mobile == m || trade.To.Mobile == m) return trade;
}
@ -240,12 +239,12 @@ namespace Server.Network
public SecureTradeContainer FindTradeContainer(Mobile m)
{
for (int i = 0; i < Trades.Count; ++i)
for (var i = 0; i < Trades.Count; ++i)
{
SecureTrade trade = Trades[i];
var trade = Trades[i];
SecureTradeInfo from = trade.From;
SecureTradeInfo to = trade.To;
var from = trade.From;
var to = trade.To;
if (from.Mobile == Mobile && to.Mobile == m) return from.Container;
@ -257,7 +256,7 @@ namespace Server.Network
public SecureTradeContainer AddTrade(NetState state)
{
SecureTrade newTrade = new SecureTrade(Mobile, state.Mobile);
var newTrade = new SecureTrade(Mobile, state.Mobile);
Trades.Add(newTrade);
state.Trades.Add(newTrade);
@ -300,7 +299,9 @@ namespace Server.Network
Menus ??= new List<IMenu>();
if (Menus.Count < MenuCap)
{
Menus.Add(menu);
}
else
{
WriteConsole("Exceeded menu cap, disconnecting...");
@ -328,7 +329,9 @@ namespace Server.Network
HuePickers ??= new List<HuePicker>();
if (HuePickers.Count < HuePickerCap)
{
HuePickers.Add(huePicker);
}
else
{
WriteConsole("Exceeded hue picker cap, disconnecting...");
@ -356,7 +359,9 @@ namespace Server.Network
Gumps ??= new List<Gump>();
if (Gumps.Count < GumpCap)
{
Gumps.Add(gump);
}
else
{
WriteConsole("Exceeded gump cap, disconnecting...");
@ -394,8 +399,8 @@ namespace Server.Network
public IAccount Account { get; set; }
public override string ToString() => m_ToString;
public NetState(ConnectionContext connection)
public NetState(ConnectionContext connection)
{
Connection = connection;
Seeded = false;
@ -443,13 +448,13 @@ namespace Server.Network
try
{
//TODO: Rented memory
ReadOnlyMemory<byte> buffer = p.Compile(CompressionEnabled, out int length);
// TODO: Rented memory
ReadOnlyMemory<byte> buffer = p.Compile(CompressionEnabled, out var length);
if (buffer.Length > 0 && length > 0)
try
{
FlushResult result = await outPipe.WriteAsync(buffer.Slice(0, length));
var result = await outPipe.WriteAsync(buffer.Slice(0, length));
if (result.IsCanceled || result.IsCompleted)
{
@ -491,8 +496,7 @@ namespace Server.Network
}
public PacketHandler GetHandler(int packetID) =>
ContainerGridLines ? PacketHandlers.Get6017Handler(packetID) :
PacketHandlers.GetHandler(packetID);
ContainerGridLines ? PacketHandlers.Get6017Handler(packetID) : PacketHandlers.GetHandler(packetID);
public static void TraceException(Exception ex)
{
@ -501,7 +505,7 @@ namespace Server.Network
try
{
using StreamWriter op = new StreamWriter("network-errors.log", true);
using var op = new StreamWriter("network-errors.log", true);
op.WriteLine("# {0}", DateTime.UtcNow);
op.WriteLine(ex);
@ -523,7 +527,7 @@ namespace Server.Network
public virtual void Dispose()
{
int disposing = Interlocked.Exchange(ref m_Disposing, 1);
var disposing = Interlocked.Exchange(ref m_Disposing, 1);
if (disposing == 1)
return;
@ -545,15 +549,15 @@ namespace Server.Network
public static void ProcessDisposedQueue()
{
int breakout = 0;
var breakout = 0;
while (breakout++ < 200)
{
if (!m_Disposed.TryDequeue(out NetState ns))
if (!m_Disposed.TryDequeue(out var ns))
break;
Mobile m = ns.Mobile;
IAccount a = ns.Account;
var m = ns.Mobile;
var a = ns.Account;
if (m != null)
{
@ -579,11 +583,11 @@ namespace Server.Network
{
get
{
for (int i = ExpansionInfo.Table.Length - 1; i >= 0; i--)
for (var i = ExpansionInfo.Table.Length - 1; i >= 0; i--)
{
ExpansionInfo info = ExpansionInfo.Table[i];
var info = ExpansionInfo.Table[i];
if (info.RequiredClient != null && Version >= info.RequiredClient || (Flags & info.ClientFlags) != 0)
if ((info.RequiredClient != null && Version >= info.RequiredClient) || (Flags & info.ClientFlags) != 0)
return info;
}
@ -597,13 +601,14 @@ namespace Server.Network
public bool SupportsExpansion(ExpansionInfo info, bool checkCoreExpansion = true)
{
if (info == null || checkCoreExpansion && (int)Core.Expansion < info.ID)
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) => SupportsExpansion(ExpansionInfo.GetInfo(ex), checkCoreExpansion);
public bool SupportsExpansion(Expansion ex, bool checkCoreExpansion = true) =>
SupportsExpansion(ExpansionInfo.GetInfo(ex), checkCoreExpansion);
public int CompareTo(NetState other) => other == null ? 1 : m_ToString.CompareTo(other.m_ToString);
}

View file

@ -27,7 +27,7 @@ namespace Server.Network
/// <summary>
/// Handles outgoing packet compression for the network.
/// </summary>
public static class Compression
public static class NetworkCompression
{
private const int CountIndex = 0;
private const int ValueIndex = 1;
@ -48,7 +48,8 @@ namespace Server.Network
// If our input exceeds this length, we may potentially overflow the buffer
private const int PossibleOverflow = (BufferSize * 8 - TerminalCodeLength) / MaximalCodeLength;
private static readonly int[] _huffmanTable = {
private static readonly 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,
@ -86,7 +87,7 @@ namespace Server.Network
public static readonly ICompressor Compressor;
static Compression()
static NetworkCompression()
{
if (Core.Unix)
Compressor = new UnixCompressor();
@ -100,14 +101,14 @@ namespace Server.Network
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();
if (input.Length - offset < count) throw new ArgumentOutOfRangeException(nameof(offset));
length = 0;
if (count > DefiniteOverflow) return;
int bitCount = 0;
int bitValue = 0;
var bitCount = 0;
var bitValue = 0;
fixed (int* pTable = _huffmanTable)
{
@ -185,10 +186,11 @@ namespace Server.Network
public static unsafe ZLibError Pack(Span<byte> dest, ref int destLength, ReadOnlySpan<byte> source, int sourceLength)
{
ulong destLengthLong = (ulong)destLength;
var destLengthLong = (ulong)destLength;
fixed (byte* dPtr = &MemoryMarshal.GetReference(dest), sPtr = &MemoryMarshal.GetReference(source))
{
ZLibError e = Compressor.Compress(Unsafe.AsRef<int>(dPtr), ref destLengthLong, Unsafe.AsRef<int>(sPtr), (ulong)sourceLength);
var e = Compressor.Compress(Unsafe.AsRef<int>(dPtr), ref destLengthLong, Unsafe.AsRef<int>(sPtr),
(ulong)sourceLength);
destLength = (int)destLengthLong;
return e;
}
@ -196,21 +198,24 @@ namespace Server.Network
public static unsafe ZLibError Pack(Span<byte> dest, ref int destLength, ReadOnlySpan<byte> source, ZLibQuality quality)
{
ulong destLengthLong = (ulong)destLength;
var destLengthLong = (ulong)destLength;
fixed (byte* dPtr = &MemoryMarshal.GetReference(dest), sPtr = &MemoryMarshal.GetReference(source))
{
ZLibError e = Compressor.Compress(Unsafe.AsRef<int>(dPtr), ref destLengthLong, Unsafe.AsRef<int>(sPtr), (ulong)source.Length, quality);
var e = Compressor.Compress(Unsafe.AsRef<int>(dPtr), ref destLengthLong, Unsafe.AsRef<int>(sPtr),
(ulong)source.Length, quality);
destLength = (int)destLengthLong;
return e;
}
}
public static unsafe ZLibError Pack(Span<byte> dest, ref int destLength, ReadOnlySpan<byte> source, int sourceLength, ZLibQuality quality)
public static unsafe ZLibError Pack(Span<byte> dest, ref int destLength, ReadOnlySpan<byte> source, int sourceLength,
ZLibQuality quality)
{
ulong destLengthLong = (ulong)destLength;
var destLengthLong = (ulong)destLength;
fixed (byte* dPtr = &MemoryMarshal.GetReference(dest), sPtr = &MemoryMarshal.GetReference(source))
{
ZLibError e = Compressor.Compress(Unsafe.AsRef<int>(dPtr), ref destLengthLong, Unsafe.AsRef<int>(sPtr), (ulong)sourceLength, quality);
var e = Compressor.Compress(Unsafe.AsRef<int>(dPtr), ref destLengthLong, Unsafe.AsRef<int>(sPtr),
(ulong)sourceLength, quality);
destLength = (int)destLengthLong;
return e;
}
@ -218,10 +223,11 @@ namespace Server.Network
public static unsafe ZLibError Unpack(Span<byte> dest, ref int destLength, ReadOnlySpan<byte> source, int sourceLength)
{
ulong destLengthLong = (ulong)destLength;
var destLengthLong = (ulong)destLength;
fixed (byte* dPtr = &MemoryMarshal.GetReference(dest), sPtr = &MemoryMarshal.GetReference(source))
{
ZLibError e = Compressor.Decompress(Unsafe.AsRef<int>(dPtr), ref destLengthLong, Unsafe.AsRef<int>(sPtr), (ulong)sourceLength);
var e = Compressor.Decompress(Unsafe.AsRef<int>(dPtr), ref destLengthLong, Unsafe.AsRef<int>(sPtr),
(ulong)sourceLength);
destLength = (int)destLengthLong;
return e;
}
@ -231,26 +237,38 @@ namespace Server.Network
public static unsafe ZLibError Pack(Span<byte> dest, ref ulong destLength, ReadOnlySpan<byte> source, ulong sourceLength)
{
fixed(byte* dPtr = &MemoryMarshal.GetReference(dest), sPtr = &MemoryMarshal.GetReference(source))
fixed (byte* dPtr = &MemoryMarshal.GetReference(dest), sPtr = &MemoryMarshal.GetReference(source))
{
return Compressor.Compress(Unsafe.AsRef<int>(dPtr), ref destLength, Unsafe.AsRef<int>(sPtr), sourceLength);
}
}
public static unsafe ZLibError Pack(Span<byte> dest, ref ulong destLength, ReadOnlySpan<byte> source, ZLibQuality quality)
public static unsafe ZLibError Pack(Span<byte> dest, ref ulong destLength, ReadOnlySpan<byte> source,
ZLibQuality quality)
{
fixed(byte* dPtr = &MemoryMarshal.GetReference(dest), sPtr = &MemoryMarshal.GetReference(source))
return Compressor.Compress(Unsafe.AsRef<int>(dPtr), ref destLength, Unsafe.AsRef<int>(sPtr), (ulong)source.Length, quality);
fixed (byte* dPtr = &MemoryMarshal.GetReference(dest), sPtr = &MemoryMarshal.GetReference(source))
{
return Compressor.Compress(Unsafe.AsRef<int>(dPtr), ref destLength, Unsafe.AsRef<int>(sPtr), (ulong)source.Length,
quality);
}
}
public static unsafe ZLibError Pack(Span<byte> dest, ref ulong destLength, ReadOnlySpan<byte> source, ulong sourceLength, ZLibQuality quality)
public static unsafe ZLibError Pack(Span<byte> dest, ref ulong destLength, ReadOnlySpan<byte> source, ulong sourceLength,
ZLibQuality quality)
{
fixed(byte* dPtr = &MemoryMarshal.GetReference(dest), sPtr = &MemoryMarshal.GetReference(source))
fixed (byte* dPtr = &MemoryMarshal.GetReference(dest), sPtr = &MemoryMarshal.GetReference(source))
{
return Compressor.Compress(Unsafe.AsRef<int>(dPtr), ref destLength, Unsafe.AsRef<int>(sPtr), sourceLength, quality);
}
}
public static unsafe ZLibError Unpack(Span<byte> dest, ref ulong destLength, ReadOnlySpan<byte> source, ulong sourceLength)
public static unsafe ZLibError Unpack(Span<byte> dest, ref ulong destLength, ReadOnlySpan<byte> source,
ulong sourceLength)
{
fixed(byte* dPtr = &MemoryMarshal.GetReference(dest), sPtr = &MemoryMarshal.GetReference(source))
fixed (byte* dPtr = &MemoryMarshal.GetReference(dest), sPtr = &MemoryMarshal.GetReference(source))
{
return Compressor.Decompress(Unsafe.AsRef<int>(dPtr), ref destLength, Unsafe.AsRef<int>(sPtr), sourceLength);
}
}
}
@ -265,66 +283,72 @@ namespace Server.Network
public class Compressor : ICompressor
{
public string Version => zlibVersion();
public string Version => SafeNativeMethods.zlibVersion();
public ZLibError Compress(in int dest, ref ulong destLength, in int source, ulong sourceLength) =>
compress(dest, ref destLength, source, sourceLength);
SafeNativeMethods.compress(dest, ref destLength, source, sourceLength);
public ZLibError Compress(in int dest, ref ulong destLength, in int source, ulong sourceLength,
ZLibQuality quality) => compress2(dest, ref destLength, source, sourceLength, quality);
ZLibQuality quality) => SafeNativeMethods.compress2(dest, ref destLength, source, sourceLength, quality);
public ZLibError Decompress(in int dest, ref ulong destLength, in int source, ulong sourceLength) =>
uncompress(dest, ref destLength, source, sourceLength);
SafeNativeMethods.uncompress(dest, ref destLength, source, sourceLength);
public ulong CompressBound(ulong sourceLength) => compressBound(sourceLength);
public ulong CompressBound(ulong sourceLength) => SafeNativeMethods.compressBound(sourceLength);
[DllImport("zlib")]
private static extern string zlibVersion();
private static class SafeNativeMethods
{
[DllImport("zlib", CharSet = CharSet.Unicode)]
internal static extern string zlibVersion();
[DllImport("zlib")]
private static extern ZLibError compress(in int dest, ref ulong destLength, in int source, ulong sourceLength);
[DllImport("zlib")]
internal static extern ZLibError compress(in int dest, ref ulong destLength, in int source, ulong sourceLength);
[DllImport("zlib")]
private static extern ZLibError compress2(in int dest, ref ulong destLength, in int source, ulong sourceLength,
ZLibQuality quality);
[DllImport("zlib")]
internal static extern ZLibError compress2(in int dest, ref ulong destLength, in int source, ulong sourceLength,
ZLibQuality quality);
[DllImport("zlib")]
private static extern ZLibError uncompress(in int dest, ref ulong destLength, in int source, ulong sourceLength);
[DllImport("zlib")]
internal static extern ZLibError uncompress(in int dest, ref ulong destLength, in int source, ulong sourceLength);
[DllImport("zlib")]
private static extern ulong compressBound(ulong sourceLen);
[DllImport("zlib")]
internal static extern ulong compressBound(ulong sourceLen);
}
}
public class UnixCompressor : ICompressor
{
public string Version => zlibVersion();
public string Version => SafeNativeMethods.zlibVersion();
public ZLibError Compress(in int dest, ref ulong destLength, in int source, ulong sourceLength) =>
compress(dest, ref destLength, source, sourceLength);
SafeNativeMethods.compress(dest, ref destLength, source, sourceLength);
public ZLibError Compress(in int dest, ref ulong destLength, in int source, ulong sourceLength,
ZLibQuality quality) => compress2(dest, ref destLength, source, sourceLength, quality);
ZLibQuality quality) => SafeNativeMethods.compress2(dest, ref destLength, source, sourceLength, quality);
public ZLibError Decompress(in int dest, ref ulong destLength, in int source, ulong sourceLength) =>
uncompress(dest, ref destLength, source, sourceLength);
SafeNativeMethods.uncompress(dest, ref destLength, source, sourceLength);
public ulong CompressBound(ulong sourceLength) => compressBound(sourceLength);
public ulong CompressBound(ulong sourceLength) => SafeNativeMethods.compressBound(sourceLength);
[DllImport("libz")]
private static extern string zlibVersion();
internal static class SafeNativeMethods
{
[DllImport("libz", CharSet = CharSet.Unicode)]
internal static extern string zlibVersion();
[DllImport("libz")]
private static extern ZLibError compress(in int dest, ref ulong destLength, in int source, ulong sourceLength);
[DllImport("libz")]
internal static extern ZLibError compress(in int dest, ref ulong destLength, in int source, ulong sourceLength);
[DllImport("libz")]
private static extern ZLibError compress2(in int dest, ref ulong destLength, in int source, ulong sourceLength,
ZLibQuality quality);
[DllImport("libz")]
internal static extern ZLibError compress2(in int dest, ref ulong destLength, in int source, ulong sourceLength,
ZLibQuality quality);
[DllImport("libz")]
private static extern ZLibError uncompress(in int dest, ref ulong destLength, in int source, ulong sourceLength);
[DllImport("libz")]
internal static extern ZLibError uncompress(in int dest, ref ulong destLength, in int source, ulong sourceLength);
[DllImport("libz")]
private static extern ulong compressBound(ulong sourceLen);
[DllImport("libz")]
internal static extern ulong compressBound(ulong sourceLen);
}
}
public enum ZLibError

View file

@ -18,11 +18,11 @@
*
***************************************************************************/
using Server.Diagnostics;
using System;
using System.Buffers;
using System.Diagnostics;
using System.IO;
using Server.Diagnostics;
namespace Server.Network
{
@ -37,15 +37,13 @@ namespace Server.Network
private readonly 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());
var prof = PacketSendProfile.Acquire(GetType());
prof.Increment();
}
}
@ -55,25 +53,25 @@ namespace Server.Network
PacketID = packetID;
m_Length = length;
m_Stream = PacketWriter.CreateInstance(length); // new PacketWriter( length );
m_Stream.Write((byte)packetID);
Stream = PacketWriter.CreateInstance(length); // new PacketWriter( length );
Stream.Write((byte)packetID);
if (Core.Profiling)
{
PacketSendProfile prof = PacketSendProfile.Acquire(GetType());
var prof = PacketSendProfile.Acquire(GetType());
prof.Increment();
}
}
public int PacketID { get; }
public PacketWriter UnderlyingStream => m_Stream;
public PacketWriter Stream { get; protected set; }
public void EnsureCapacity(int length)
{
m_Stream = PacketWriter.CreateInstance(length); // new PacketWriter( length );
m_Stream.Write((byte)PacketID);
m_Stream.Write((short)0);
Stream = PacketWriter.CreateInstance(length); // new PacketWriter( length );
Stream.Write((byte)PacketID);
Stream.Write((short)0);
}
public static Packet SetStatic(Packet p)
@ -154,7 +152,7 @@ namespace Server.Network
try
{
using StreamWriter op = new StreamWriter("net_opt.log", true);
using var op = new StreamWriter("net_opt.log", true);
op.WriteLine("Redundant compile for packet {0}, use Acquire() and Release()", GetType());
op.WriteLine(new StackTrace());
}
@ -164,7 +162,7 @@ namespace Server.Network
}
}
m_CompiledBuffer = new byte[0];
m_CompiledBuffer = Array.Empty<byte>();
m_CompiledLength = 0;
length = m_CompiledLength;
@ -183,35 +181,35 @@ namespace Server.Network
{
if (m_Length == 0)
{
long streamLen = m_Stream.Length;
var streamLen = Stream.Length;
m_Stream.Seek(1, SeekOrigin.Begin);
m_Stream.Write((ushort)streamLen);
Stream.Seek(1, SeekOrigin.Begin);
Stream.Write((ushort)streamLen);
}
else if (m_Stream.Length != m_Length)
else if (Stream.Length != m_Length)
{
int diff = (int)m_Stream.Length - m_Length;
var diff = (int)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;
var ms = Stream.UnderlyingStream;
m_CompiledBuffer = ms.GetBuffer();
int length = (int)ms.Length;
var length = (int)ms.Length;
if (compress)
{
byte[] buffer = ArrayPool<byte>.Shared.Rent(CompressorBufferSize);
var buffer = ArrayPool<byte>.Shared.Rent(CompressorBufferSize);
Compression.Compress(m_CompiledBuffer, 0, length, buffer, out length);
NetworkCompression.Compress(m_CompiledBuffer, 0, length, buffer, out 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);
using var 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());
@ -235,11 +233,13 @@ namespace Server.Network
}
else if (length > 0)
{
byte[] old = m_CompiledBuffer;
var 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);
@ -249,8 +249,8 @@ namespace Server.Network
Buffer.BlockCopy(old, 0, m_CompiledBuffer, 0, length);
}
PacketWriter.ReleaseInstance(m_Stream);
m_Stream = null;
PacketWriter.ReleaseInstance(Stream);
Stream = null;
}
[Flags]

View file

@ -36,14 +36,14 @@ namespace Server.Network
OnReceive = onReceive;
}
public int PacketID{ get; }
public int PacketID { get; }
public int Length{ get; }
public int Length { get; }
public OnPacketReceive OnReceive{ get; }
public OnPacketReceive OnReceive { get; }
public ThrottlePacketCallback ThrottleCallback{ get; set; }
public ThrottlePacketCallback ThrottleCallback { get; set; }
public bool Ingame{ get; }
public bool Ingame { get; }
}
}

File diff suppressed because it is too large Load diff

View file

@ -36,19 +36,19 @@ namespace Server.Network
public PacketReader(ReadOnlySequence<byte> seq) => m_Reader = new SequenceReader<byte>(seq);
public byte Peek() => m_Reader.TryPeek(out byte value) ? value : (byte)0;
public byte Peek() => m_Reader.TryPeek(out var value) ? value : (byte)0;
public void Trace(NetState state)
{
try
{
using StreamWriter sw = new StreamWriter("Packets.log", true);
byte[] buffer = m_Reader.Sequence.ToArray();
using var sw = new StreamWriter("Packets.log", true);
var 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))
using (var ms = new MemoryStream(buffer))
{
Utility.FormatBuffer(sw, ms, buffer.Length);
}
@ -79,7 +79,7 @@ namespace Server.Network
m_Reader.Advance(Math.Min(m_Reader.Remaining, offset));
break;
case SeekOrigin.End:
long count = m_Reader.Remaining - offset;
var count = m_Reader.Remaining - offset;
if (count < 0)
m_Reader.Rewind(count * -1);
else if (count > 0)
@ -96,7 +96,7 @@ namespace Server.Network
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 byte ReadByte() => m_Reader.TryRead(out var value) ? value : (byte)0;
public uint ReadUInt32() => (uint)ReadInt32();
@ -108,7 +108,7 @@ namespace Server.Network
public string ReadUnicodeStringLE()
{
StringBuilder sb = new StringBuilder();
var sb = new StringBuilder();
while (m_Reader.TryReadLittleEndian(out short c) && c != 0)
sb.Append((char)c);
@ -118,7 +118,7 @@ namespace Server.Network
public string ReadUnicodeStringLE(int fixedLength)
{
StringBuilder sb = new StringBuilder();
var sb = new StringBuilder();
while (fixedLength-- > 0 && m_Reader.TryReadLittleEndian(out short c) && c != 0)
sb.Append((char)c);
@ -131,7 +131,7 @@ namespace Server.Network
public string ReadUnicodeStringLESafe(int fixedLength)
{
StringBuilder sb = new StringBuilder();
var sb = new StringBuilder();
while (fixedLength-- > 0 && m_Reader.TryReadLittleEndian(out short c) && c != 0)
if (IsSafeChar(c))
@ -145,7 +145,7 @@ namespace Server.Network
public string ReadUnicodeStringLESafe()
{
StringBuilder sb = new StringBuilder();
var sb = new StringBuilder();
while (m_Reader.TryReadLittleEndian(out short c) && c != 0)
if (IsSafeChar(c))
@ -156,7 +156,7 @@ namespace Server.Network
public string ReadUnicodeStringSafe()
{
StringBuilder sb = new StringBuilder();
var sb = new StringBuilder();
while (m_Reader.TryReadBigEndian(out short c) && c != 0)
if (IsSafeChar(c))
@ -167,7 +167,7 @@ namespace Server.Network
public string ReadUnicodeString()
{
StringBuilder sb = new StringBuilder();
var sb = new StringBuilder();
while (m_Reader.TryReadBigEndian(out short c) && c != 0)
sb.Append((char)c);
@ -182,17 +182,19 @@ namespace Server.Network
string s;
if (m_Reader.TryReadTo(out ReadOnlySpan<byte> span, (byte)'\0'))
{
s = Utility.UTF8.GetString(span.Length > fixedLength ? span.Slice(0, fixedLength) : span);
}
else
{
long size = Math.Min(m_Reader.Remaining, fixedLength);
var 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);
var sb = new StringBuilder(s.Length);
for (int i = 0; i < s.Length; ++i)
for (var i = 0; i < s.Length; ++i)
if (IsSafeChar(s[i]))
sb.Append(s[i]);
@ -204,16 +206,18 @@ namespace Server.Network
string s;
if (m_Reader.TryReadTo(out ReadOnlySpan<byte> span, (byte)'\0'))
{
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);
var sb = new StringBuilder(s.Length);
for (int i = 0; i < s.Length; ++i)
for (var i = 0; i < s.Length; ++i)
if (IsSafeChar(s[i]))
sb.Append(s[i]);
@ -222,15 +226,15 @@ namespace Server.Network
public string ReadUTF8String() =>
Utility.UTF8.GetString(
m_Reader.TryReadTo(out ReadOnlySpan<byte> span, (byte)'\0') ? span :
m_Reader.Sequence.Slice(m_Reader.Position, m_Reader.Remaining).ToArray()
);
m_Reader.TryReadTo(out ReadOnlySpan<byte> span, (byte)'\0')
? span
: m_Reader.Sequence.Slice(m_Reader.Position, m_Reader.Remaining).ToArray());
public string ReadString()
{
StringBuilder sb = new StringBuilder();
var sb = new StringBuilder();
while (m_Reader.TryRead(out byte c))
while (m_Reader.TryRead(out var c))
sb.Append((char)c);
return sb.ToString();
@ -238,9 +242,9 @@ namespace Server.Network
public string ReadStringSafe()
{
StringBuilder sb = new StringBuilder();
var sb = new StringBuilder();
while (m_Reader.TryRead(out byte c))
while (m_Reader.TryRead(out var c))
if (IsSafeChar(c))
sb.Append((char)c);
@ -249,7 +253,7 @@ namespace Server.Network
public string ReadUnicodeStringSafe(int fixedLength)
{
StringBuilder sb = new StringBuilder();
var sb = new StringBuilder();
while (fixedLength-- > 0 && m_Reader.TryReadBigEndian(out short c) && c != 0)
if (IsSafeChar(c))
@ -263,7 +267,7 @@ namespace Server.Network
public string ReadUnicodeString(int fixedLength)
{
StringBuilder sb = new StringBuilder();
var sb = new StringBuilder();
while (fixedLength-- > 0 && m_Reader.TryReadBigEndian(out short c) && c != 0)
sb.Append((char)c);
@ -276,9 +280,9 @@ namespace Server.Network
public string ReadStringSafe(int fixedLength)
{
StringBuilder sb = new StringBuilder();
var sb = new StringBuilder();
while (fixedLength-- > 0 && m_Reader.TryRead(out byte c) && c != 0)
while (fixedLength-- > 0 && m_Reader.TryRead(out var c) && c != 0)
if (IsSafeChar(c))
sb.Append((char)c);
@ -290,9 +294,9 @@ namespace Server.Network
public string ReadString(int fixedLength)
{
StringBuilder sb = new StringBuilder();
var sb = new StringBuilder();
while (fixedLength-- > 0 && m_Reader.TryRead(out byte c) && c != 0)
while (fixedLength-- > 0 && m_Reader.TryRead(out var c) && c != 0)
sb.Append((char)c);
if (fixedLength > 0)

View file

@ -70,7 +70,7 @@ namespace Server.Network
public static PacketWriter CreateInstance(int capacity = 32)
{
if (m_Pool.TryDequeue(out PacketWriter pw))
if (m_Pool.TryDequeue(out var pw))
{
pw.m_Capacity = capacity;
pw.UnderlyingStream.SetLength(0);
@ -177,7 +177,7 @@ namespace Server.Network
value = string.Empty;
}
int length = value.Length;
var length = value.Length;
UnderlyingStream.SetLength(UnderlyingStream.Length + size);
@ -204,7 +204,7 @@ namespace Server.Network
value = string.Empty;
}
int length = value.Length;
var length = value.Length;
UnderlyingStream.SetLength(UnderlyingStream.Length + length + 1);
@ -223,11 +223,12 @@ namespace Server.Network
value = string.Empty;
}
int length = value.Length;
var 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 +=
Encoding.Unicode.GetBytes(value, 0, length, UnderlyingStream.GetBuffer(), (int)UnderlyingStream.Position);
UnderlyingStream.Position += 2;
}
@ -243,7 +244,7 @@ namespace Server.Network
value = string.Empty;
}
int length = value.Length;
var length = value.Length;
size *= 2;
UnderlyingStream.SetLength(UnderlyingStream.Length + size);
@ -271,7 +272,7 @@ namespace Server.Network
value = string.Empty;
}
int length = value.Length;
var length = value.Length;
UnderlyingStream.SetLength(UnderlyingStream.Length + (length + 1) * 2);
@ -292,15 +293,16 @@ namespace Server.Network
value = string.Empty;
}
int length = value.Length;
var length = value.Length;
size *= 2;
UnderlyingStream.SetLength(UnderlyingStream.Length + size);
if (length * 2 >= size )
if (length * 2 >= size)
{
UnderlyingStream.Position +=
Encoding.BigEndianUnicode.GetBytes(value, 0, size / 2, UnderlyingStream.GetBuffer(), (int)UnderlyingStream.Position);
Encoding.BigEndianUnicode.GetBytes(value, 0, size / 2, UnderlyingStream.GetBuffer(),
(int)UnderlyingStream.Position);
}
else
{

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019 - ModernUO Development Team *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: ServerConnectionHandler.cs *
* Created: 2020/04/12 - Updated: 2020/04/12 *
@ -20,8 +20,6 @@
*************************************************************************/
using System;
using System.Buffers;
using System.IO.Pipelines;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
using Microsoft.Extensions.Logging;
@ -35,8 +33,7 @@ namespace Server.Network
public ServerConnectionHandler(
IMessagePumpService messagePumpService,
ILogger<ServerConnectionHandler> logger
)
ILogger<ServerConnectionHandler> logger)
{
_messagePumpService = messagePumpService;
_logger = logger;
@ -50,13 +47,13 @@ namespace Server.Network
return;
}
NetState ns = new NetState(connection);
var ns = new NetState(connection);
TcpServer.Instances.Add(ns);
_logger.LogInformation($"Client: {ns}: Connected. [{TcpServer.Instances.Count} Online]");
connection.ConnectionClosed.Register(() => { TcpServer.Instances.Remove(ns); });
await ProcessIncoming(ns);
await ProcessIncoming(ns).ConfigureAwait(false);
}
private async Task ProcessIncoming(NetState ns)
@ -70,16 +67,16 @@ namespace Server.Network
try
{
ReadResult result = await inPipe.ReadAsync();
var result = await inPipe.ReadAsync();
if (result.IsCanceled || result.IsCompleted)
return;
ReadOnlySequence<byte> seq = result.Buffer;
var seq = result.Buffer;
if (seq.IsEmpty)
break;
int pos = PacketHandlers.ProcessPacket(_messagePumpService, ns, seq);
var pos = PacketHandlers.ProcessPacket(_messagePumpService, ns, seq);
if (pos <= 0)
break;
@ -99,7 +96,7 @@ namespace Server.Network
{
try
{
SocketConnectEventArgs args = new SocketConnectEventArgs(connection);
var args = new SocketConnectEventArgs(connection);
EventSink.InvokeSocketConnect(args);

View file

@ -1,6 +1,6 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019 - ModernUO Development Team *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: ServerStartup.cs *
* Created: 2020/04/12 - Updated: 2020/04/12 *

View file

@ -1,6 +1,6 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019 - ModernUO Development Team *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: StaticPacketHandlers.cs *
* Created: 2019/03/15 - Updated: 2019/12/24 *
@ -25,18 +25,26 @@ namespace Server.Network
{
public static class StaticPacketHandlers
{
private static readonly ConcurrentDictionary<IPropertyListObject,OPLInfo> OPLInfoPackets = new ConcurrentDictionary<IPropertyListObject,OPLInfo>();
private static readonly ConcurrentDictionary<IEntity,RemoveEntity> RemoveEntityPackets = new ConcurrentDictionary<IEntity,RemoveEntity>();
private static readonly ConcurrentDictionary<IPropertyListObject, OPLInfo> OPLInfoPackets =
new ConcurrentDictionary<IPropertyListObject, OPLInfo>();
private static readonly ConcurrentDictionary<Item,WorldItem> WorldItemPackets = new ConcurrentDictionary<Item,WorldItem>();
private static readonly ConcurrentDictionary<Item,WorldItemSA> WorldItemSAPackets = new ConcurrentDictionary<Item,WorldItemSA>();
private static readonly ConcurrentDictionary<Item,WorldItemHS> WorldItemHSPackets = new ConcurrentDictionary<Item,WorldItemHS>();
private static readonly ConcurrentDictionary<IEntity, RemoveEntity> RemoveEntityPackets =
new ConcurrentDictionary<IEntity, RemoveEntity>();
private static readonly ConcurrentDictionary<Item, WorldItem> WorldItemPackets =
new ConcurrentDictionary<Item, WorldItem>();
private static readonly ConcurrentDictionary<Item, WorldItemSA> WorldItemSAPackets =
new ConcurrentDictionary<Item, WorldItemSA>();
private static readonly 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.Entity.Serial, value.PropertyList.Hash);
var packet = new OPLInfo(value.PropertyList.Entity.Serial, value.PropertyList.Hash);
packet.SetStatic();
return packet;
});
@ -44,7 +52,7 @@ namespace Server.Network
public static OPLInfo FreeOPLInfoPacket(IPropertyListObject obj)
{
if (OPLInfoPackets.TryRemove(obj, out OPLInfo p))
if (OPLInfoPackets.TryRemove(obj, out var p))
Packet.Release(p);
return p;
@ -54,7 +62,7 @@ namespace Server.Network
{
return RemoveEntityPackets.GetOrAdd(entity, value =>
{
RemoveEntity packet = new RemoveEntity(value);
var packet = new RemoveEntity(value);
packet.SetStatic();
return packet;
});
@ -62,7 +70,7 @@ namespace Server.Network
public static void FreeRemoveItemPacket(IEntity entity)
{
if (RemoveEntityPackets.TryRemove(entity, out RemoveEntity p))
if (RemoveEntityPackets.TryRemove(entity, out var p))
Packet.Release(p);
}
@ -70,7 +78,7 @@ namespace Server.Network
{
return WorldItemPackets.GetOrAdd(item, value =>
{
WorldItem packet = new WorldItem(value);
var packet = new WorldItem(value);
packet.SetStatic();
return packet;
});
@ -80,7 +88,7 @@ namespace Server.Network
{
return WorldItemSAPackets.GetOrAdd(item, value =>
{
WorldItemSA packet = new WorldItemSA(value);
var packet = new WorldItemSA(value);
packet.SetStatic();
return packet;
});
@ -90,7 +98,7 @@ namespace Server.Network
{
return WorldItemHSPackets.GetOrAdd(item, value =>
{
WorldItemHS packet = new WorldItemHS(value);
var packet = new WorldItemHS(value);
packet.SetStatic();
return packet;
});
@ -98,13 +106,13 @@ namespace Server.Network
public static void FreeWorldItemPackets(Item item)
{
if (WorldItemPackets.TryRemove(item, out WorldItem wi))
if (WorldItemPackets.TryRemove(item, out var wi))
Packet.Release(wi);
if (WorldItemSAPackets.TryRemove(item, out WorldItemSA wisa))
if (WorldItemSAPackets.TryRemove(item, out var wisa))
Packet.Release(wisa);
if (WorldItemHSPackets.TryRemove(item, out WorldItemHS wihs))
if (WorldItemHSPackets.TryRemove(item, out var wihs))
Packet.Release(wihs);
}
}

View file

@ -1,6 +1,6 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019 - ModernUO Development Team *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: TcpServer.cs *
* Created: 2020/04/12 - Updated: 2020/04/12 *
@ -30,19 +30,17 @@ using Microsoft.Extensions.DependencyInjection;
namespace Server.Network
{
public class TcpServer
public static class TcpServer
{
public static List<IPEndPoint> Listeners { get; } = new List<IPEndPoint>();
// Make this thread safe
public static List<NetState> Instances { get; } = new List<NetState>();
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
public static IWebHostBuilder CreateWebHostBuilder(string[] args = null) =>
WebHost.CreateDefaultBuilder(args)
.UseSetting(WebHostDefaults.SuppressStatusMessagesKey, "True")
.ConfigureServices(services =>
{
services.AddSingleton<IMessagePumpService>(new MessagePumpService());
})
.ConfigureServices(services => { services.AddSingleton<IMessagePumpService>(new MessagePumpService()); })
.UseKestrel(options =>
{
foreach (var ipep in Listeners)
@ -60,17 +58,19 @@ namespace Server.Network
{
if (ipep.Address.Equals(IPAddress.Any) || ipep.Address.Equals(IPAddress.IPv6Any))
{
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in adapters)
var adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (var adapter in adapters)
{
IPInterfaceProperties properties = adapter.GetIPProperties();
foreach (UnicastIPAddressInformation unicast in properties.UnicastAddresses)
var properties = adapter.GetIPProperties();
foreach (var 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);
}
}
}
}