diff --git a/FirClient/.vsconfig b/FirClient/.vsconfig new file mode 100644 index 00000000..1586a483 --- /dev/null +++ b/FirClient/.vsconfig @@ -0,0 +1,6 @@ +{ + "version": "1.0", + "components": [ + "Microsoft.VisualStudio.Workload.ManagedGame" + ] +} diff --git a/FirClient/Assets/Libraries/LiteNetLib.meta b/FirClient/Assets/Libraries/LiteNetLib.meta deleted file mode 100644 index 0e42ca91..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: d4e4bd3508c768e4f9b97c9b2b0fc1fe -folderAsset: yes -timeCreated: 1510492067 -licenseType: Pro -DefaultImporter: - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/BaseChannel.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/BaseChannel.cs.meta deleted file mode 100644 index 70a50f85..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/BaseChannel.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d85e425fcb28148499d58b0296c0b72e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/ConnectionRequest.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/ConnectionRequest.cs.meta deleted file mode 100644 index f2e948a1..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/ConnectionRequest.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 8ea8e8aa7337511479ea11a93a6ccdbe -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/INetEventListener.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/INetEventListener.cs.meta deleted file mode 100644 index 228bb240..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/INetEventListener.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 621f11c193a0efd46ab4427300a277f7 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/Layers/Crc32cLayer.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/Layers/Crc32cLayer.cs.meta deleted file mode 100644 index ad8bfb80..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/Layers/Crc32cLayer.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 266b6f3fa1e455149b07a13f2669665e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/Layers/PacketLayerBase.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/Layers/PacketLayerBase.cs.meta deleted file mode 100644 index 50685a02..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/Layers/PacketLayerBase.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: bcbadb92fd2b56848a8b220cc97a8eff -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/Layers/XorEncryptLayer.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/Layers/XorEncryptLayer.cs.meta deleted file mode 100644 index 4da89b9b..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/Layers/XorEncryptLayer.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 8ac6fbfd6cff6e14b9cb09284bd5b9d6 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/LiteNetLib.csproj b/FirClient/Assets/Libraries/LiteNetLib/LiteNetLib.csproj deleted file mode 100644 index e6f1782c..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/LiteNetLib.csproj +++ /dev/null @@ -1,30 +0,0 @@ - - - - LiteNetLib - LiteNetLib - 4 - netcoreapp2.1;netcoreapp3.0;netstandard2.0 - net35;netstandard2.0;netcoreapp2.1;netcoreapp3.0 - - - - TRACE;DEBUG - 1701;1702;1705;1591 - 4 - - - - TRACE - bin\Release\net35\LiteNetLib.xml - 1701;1702;1705;1591 - - - - - - - - - - \ No newline at end of file diff --git a/FirClient/Assets/Libraries/LiteNetLib/NatPunchModule.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/NatPunchModule.cs.meta deleted file mode 100644 index 63749594..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/NatPunchModule.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: aea42f9d45be292469e2356ccec1bb95 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/NetConstants.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/NetConstants.cs.meta deleted file mode 100644 index f19c3954..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/NetConstants.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d847fbb5d3a526d4cb22393bae357aeb -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/NetDebug.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/NetDebug.cs.meta deleted file mode 100644 index 6a77913a..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/NetDebug.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 32de28292e31ab14bb629a83f289de6b -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/NetManager.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/NetManager.cs.meta deleted file mode 100644 index d982b6ff..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/NetManager.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: bea4e27bf3024094d9310ea27c1bf37f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/NetPacket.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/NetPacket.cs.meta deleted file mode 100644 index 82af8cd6..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/NetPacket.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2e00d89f03190bc47917e99cfb24c351 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/NetPacketPool.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/NetPacketPool.cs.meta deleted file mode 100644 index 9bda2e86..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/NetPacketPool.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 63b9adafac99bdf43b6f27920ae9c4ad -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/NetPeer.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/NetPeer.cs.meta deleted file mode 100644 index 385bc0ac..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/NetPeer.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 503b9e2a355ff73419495a8a83cd25c0 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/NetSocket.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/NetSocket.cs.meta deleted file mode 100644 index 90aae79a..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/NetSocket.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 32cc23d01eae065498adfa24865f7513 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/NetStatistics.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/NetStatistics.cs.meta deleted file mode 100644 index 6e2d821b..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/NetStatistics.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d8c6b5e6a72f95048947c090519f6ecd -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/NetUtils.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/NetUtils.cs.meta deleted file mode 100644 index 2b630d24..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/NetUtils.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 71c0119029f19f047be62052dbaa9958 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/ReliableChannel.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/ReliableChannel.cs.meta deleted file mode 100644 index afa4b053..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/ReliableChannel.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 972570e8b63db6646ba26deec34ff1ce -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/SequencedChannel.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/SequencedChannel.cs.meta deleted file mode 100644 index c5f401e7..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/SequencedChannel.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 34a3f88bc946ee047a18fe8e59fa1d1d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/Utils/CRC32C.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/Utils/CRC32C.cs.meta deleted file mode 100644 index 51b91464..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/Utils/CRC32C.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 3cf67d1f78235fd4e93b0327f7a85636 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/Utils/FastBitConverter.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/Utils/FastBitConverter.cs.meta deleted file mode 100644 index 461cd21b..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/Utils/FastBitConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2fc9c024028e941499c3d3c2cdbfd84e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/Utils/INetSerializable.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/Utils/INetSerializable.cs.meta deleted file mode 100644 index 4437551f..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/Utils/INetSerializable.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: cb0dbed46ed06884e97c4e3ae694b0c1 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/Utils/NetDataReader.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/Utils/NetDataReader.cs.meta deleted file mode 100644 index b30808b7..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/Utils/NetDataReader.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: fae8eaaf72539f94c98207806da9f65b -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/Utils/NetDataWriter.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/Utils/NetDataWriter.cs.meta deleted file mode 100644 index 3ac4c53d..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/Utils/NetDataWriter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 99c52be6b8f1bcb43b2ac498bfec1959 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/Utils/NetPacketProcessor.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/Utils/NetPacketProcessor.cs.meta deleted file mode 100644 index 75067c1b..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/Utils/NetPacketProcessor.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 93e9979f146a9674686e2b7c8fbf9fa8 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/Utils/NetSerializer.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/Utils/NetSerializer.cs.meta deleted file mode 100644 index fec096d0..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/Utils/NetSerializer.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 391dd95b70c1d4248811aa405085a770 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/Utils/NtpPacket.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/Utils/NtpPacket.cs.meta deleted file mode 100644 index 8ba1f807..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/Utils/NtpPacket.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 284614af82ff83b4f8fc6c81e63b4e51 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/LiteNetLib/Utils/NtpRequest.cs.meta b/FirClient/Assets/Libraries/LiteNetLib/Utils/NtpRequest.cs.meta deleted file mode 100644 index 675d449b..00000000 --- a/FirClient/Assets/Libraries/LiteNetLib/Utils/NtpRequest.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 46650741d263d9042b6353b56a15aa54 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/FirClient/Assets/Libraries/Mono.Xml.meta b/FirClient/Assets/Libraries/Mono.Xml.meta deleted file mode 100644 index 7593c0c5..00000000 --- a/FirClient/Assets/Libraries/Mono.Xml.meta +++ /dev/null @@ -1,5 +0,0 @@ -fileFormatVersion: 2 -guid: a74fd14c68e12734590d60f85698a0f2 -folderAsset: yes -DefaultImporter: - userData: diff --git a/FirClient/Assets/Libraries/Mono.Xml/ChangeLog b/FirClient/Assets/Libraries/Mono.Xml/ChangeLog deleted file mode 100644 index 2fbc0ef5..00000000 --- a/FirClient/Assets/Libraries/Mono.Xml/ChangeLog +++ /dev/null @@ -1,28 +0,0 @@ -2005-06-15 Atsushi Enomoto - - * SmallXmlParser.cs, SecurityParser.cs : they can be CLSCompliant now. - -2005-05-12 Atsushi Enomoto - - * SmallXmlParser.cs, - SecurityParser.cs : Use new SmallXmlParser.cs instead of MiniParser. - -2004-09-16 Sebastien Pouliot - - * MiniParser.cs: Fixed warning (l4) for unused variables. Removed - duplicate (and identical) license. - -2004-05-14 Marek Safar - - * MiniParser.cs, SecurityParser.cs: [CLSCompliant (false)] - only for public mode. - -2003-07-05 Sebastien Pouliot - - * SecurityParser.cs: Parse an XML string and convert it to a - SecurityElement object. - -2003-02-08 Sebastien Pouliot - - * MiniParser.cs: Renamed namespace to match new location. - diff --git a/FirClient/Assets/Libraries/Mono.Xml/ChangeLog.meta b/FirClient/Assets/Libraries/Mono.Xml/ChangeLog.meta deleted file mode 100644 index a14b1ea5..00000000 --- a/FirClient/Assets/Libraries/Mono.Xml/ChangeLog.meta +++ /dev/null @@ -1,4 +0,0 @@ -fileFormatVersion: 2 -guid: fa290f0e10bb2c549a1ef66875042d74 -DefaultImporter: - userData: diff --git a/FirClient/Assets/Libraries/Mono.Xml/MiniParser.cs b/FirClient/Assets/Libraries/Mono.Xml/MiniParser.cs deleted file mode 100644 index 4c3da2d4..00000000 --- a/FirClient/Assets/Libraries/Mono.Xml/MiniParser.cs +++ /dev/null @@ -1,621 +0,0 @@ -// -// System.Security.Cryptography.MiniParser: Internal XML parser implementation -// -// Authors: -// Sergey Chaban -// -// Copyright (c) 2001, 2002 Wild West Software -// Copyright (c) 2002 Sergey Chaban -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -using System; -using System.Text; -using System.Collections; -using System.Globalization; - -namespace Mono.Xml { - - internal class MiniParser { - - public interface IReader { - int Read(); - } - - public interface IAttrList { - int Length {get;} - bool IsEmpty {get;} - string GetName(int i); - string GetValue(int i); - string GetValue(string name); - void ChangeValue(string name, string newValue); - string[] Names {get;} - string[] Values {get;} - } - - public interface IMutableAttrList : IAttrList { - void Clear(); - void Add(string name, string value); - void CopyFrom(IAttrList attrs); - void Remove(int i); - void Remove(string name); - } - - public interface IHandler { - void OnStartParsing(MiniParser parser); - void OnStartElement(string name, IAttrList attrs); - void OnEndElement(string name); - void OnChars(string ch); - void OnEndParsing(MiniParser parser); - } - - public class HandlerAdapter : IHandler { - public HandlerAdapter() {} - public void OnStartParsing(MiniParser parser) {} - public void OnStartElement(string name, IAttrList attrs) {} - public void OnEndElement(string name) {} - public void OnChars(string ch) {} - public void OnEndParsing(MiniParser parser) {} - } - - private enum CharKind : byte { - LEFT_BR = 0, - RIGHT_BR = 1, - SLASH = 2, - PI_MARK = 3, - EQ = 4, - AMP = 5, - SQUOTE = 6, - DQUOTE = 7, - BANG = 8, - LEFT_SQBR = 9, - SPACE = 0xA, - RIGHT_SQBR = 0xB, - TAB = 0xC, - CR = 0xD, - EOL = 0xE, - CHARS = 0xF, - UNKNOWN = 0x1F - } - - private enum ActionCode : byte { - START_ELEM = 0, - END_ELEM = 1, - END_NAME = 2, - SET_ATTR_NAME = 3, - SET_ATTR_VAL = 4, - SEND_CHARS = 5, - START_CDATA = 6, - END_CDATA = 7, - ERROR = 8, - STATE_CHANGE = 9, - FLUSH_CHARS_STATE_CHANGE = 0xA, - ACC_CHARS_STATE_CHANGE = 0xB, - ACC_CDATA = 0xC, - PROC_CHAR_REF = 0xD, - UNKNOWN = 0xF - } - - public class AttrListImpl : IMutableAttrList { - protected ArrayList names; - protected ArrayList values; - - public AttrListImpl() : this(0) {} - - public AttrListImpl(int initialCapacity) { - if (initialCapacity <= 0) { - names = new ArrayList(); - values = new ArrayList(); - } else { - names = new ArrayList(initialCapacity); - values = new ArrayList(initialCapacity); - } - } - - public AttrListImpl(IAttrList attrs) - : this(attrs != null ? attrs.Length : 0) { - if (attrs != null) this.CopyFrom(attrs); - } - - public int Length { - get {return names.Count;} - } - - public bool IsEmpty { - get {return this.Length != 0;} - } - - public string GetName(int i) { - string res = null; - if (i >= 0 && i < this.Length) { - res = names[i] as string; - } - return res; - } - - public string GetValue(int i) { - string res = null; - if (i >= 0 && i < this.Length) { - res = values[i] as string; - } - return res; - } - - public string GetValue(string name) { - return this.GetValue(names.IndexOf(name)); - } - - public void ChangeValue(string name, string newValue) { - int i = names.IndexOf(name); - if (i >= 0 && i < this.Length) { - values[i] = newValue; - } - } - - public string[] Names { - get {return names.ToArray(typeof(string)) as string[];} - } - - public string[] Values { - get {return values.ToArray(typeof(string)) as string[];} - } - - public void Clear() { - names.Clear(); - values.Clear(); - } - - public void Add(string name, string value) { - names.Add(name); - values.Add(value); - } - - public void Remove(int i) { - if (i >= 0) { - names.RemoveAt(i); - values.RemoveAt(i); - } - } - - public void Remove(string name) { - this.Remove(names.IndexOf(name)); - } - - public void CopyFrom(IAttrList attrs) { - if (attrs != null && ((object)this == (object)attrs)) { - this.Clear(); - int n = attrs.Length; - for (int i = 0; i < n; i++) { - this.Add(attrs.GetName(i), attrs.GetValue(i)); - } - } - } - } - - public class XMLError : Exception { - protected string descr; - protected int line, column; - public XMLError() : this("Unknown") {} - public XMLError(string descr) : this(descr, -1, -1) {} - public XMLError(string descr, int line, int column) - : base(descr) { - this.descr = descr; - this.line = line; - this.column = column; - } - public int Line {get {return line;}} - public int Column {get {return column;}} - public override string ToString() { - return (String.Format("{0} @ (line = {1}, col = {2})", descr, line, column)); - } - } - - private static readonly int INPUT_RANGE = 13; - private static readonly ushort[] tbl = { - (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 1), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 0), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ERROR << 8) | 128), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.ERROR << 8) | 128), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 128), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ERROR << 8) | 128), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ERROR << 8) | 128), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ERROR << 8) | 128), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 128), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ERROR << 8) | 128), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 128), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 128), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 128), - (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 2), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 133), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 16), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.FLUSH_CHARS_STATE_CHANGE << 8) | 4), - (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.END_ELEM << 8) | 0), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 2), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 2), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), - (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 5), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), - (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 4), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.END_NAME << 8) | 6), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.END_NAME << 8) | 7), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.END_NAME << 8) | 8), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), - (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 0), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), - (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 0), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ERROR << 8) | 129), - (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.FLUSH_CHARS_STATE_CHANGE << 8) | 1), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.PROC_CHAR_REF << 8) | 10), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 7), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), - (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 9), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.START_ELEM << 8) | 6), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.START_ELEM << 8) | 7), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 8), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), - (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 9), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.SET_ATTR_NAME << 8) | 11), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 12), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 130), - (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 13), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.PROC_CHAR_REF << 8) | 10), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), - (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 14), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 15), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 11), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 132), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.ERROR << 8) | 132), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 132), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ERROR << 8) | 132), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ERROR << 8) | 132), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ERROR << 8) | 132), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ERROR << 8) | 132), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 132), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 132), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ERROR << 8) | 132), - (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.SET_ATTR_NAME << 8) | 11), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 12), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ERROR << 8) | 130), - (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.SEND_CHARS << 8) | 2), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 16), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 134), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 134), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ERROR << 8) | 134), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ERROR << 8) | 134), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ERROR << 8) | 134), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 134), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 134), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.ERROR << 8) | 134), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 134), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 134), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ERROR << 8) | 134), - (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.SET_ATTR_VAL << 8) | 17), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.PROC_CHAR_REF << 8) | 14), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 14), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 14), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 14), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 14), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 14), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 14), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 14), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 14), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 14), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 14), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 14), - (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.SET_ATTR_VAL << 8) | 17), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.PROC_CHAR_REF << 8) | 15), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 15), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 15), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 15), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 15), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 15), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 15), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 15), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 15), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 15), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 15), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 15), - (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.START_CDATA << 8) | 18), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 0), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.START_CDATA << 8) | 19), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.START_CDATA << 8) | 19), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.START_CDATA << 8) | 19), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.START_CDATA << 8) | 19), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.START_CDATA << 8) | 19), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.START_CDATA << 8) | 19), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.START_CDATA << 8) | 19), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.START_CDATA << 8) | 19), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.START_CDATA << 8) | 19), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.START_CDATA << 8) | 19), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.START_CDATA << 8) | 19), - (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.START_ELEM << 8) | 6), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.START_ELEM << 8) | 7), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 17), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 9), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), - (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.END_CDATA << 8) | 10), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 18), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 18), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 18), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 18), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 18), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 18), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 18), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 18), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 18), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 18), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 18), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 18), - (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), - (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.UNKNOWN << 8) | 255), - 0xFFFF - }; - - protected static string[] errors = { - /* 0 */ "Expected element", - /* 1 */ "Invalid character in tag", - /* 2 */ "No '='", - /* 3 */ "Invalid character entity", - /* 4 */ "Invalid attr value", - /* 5 */ "Empty tag", - /* 6 */ "No end tag", - /* 7 */ "Bad entity ref" - }; - - protected int line; - protected int col; - protected int[] twoCharBuff; - protected bool splitCData; - - public MiniParser() { - twoCharBuff = new int[2]; - splitCData = false; - Reset(); - } - - public void Reset() { - line = 0; - col = 0; - } - - protected static bool StrEquals(string str, StringBuilder sb, int sbStart, int len) { - if (len != str.Length) return false; - for (int i = 0; i < len; i++) { - if (str[i] != sb[sbStart + i]) return false; - } - return true; - } - - protected void FatalErr(string descr) { - throw new XMLError(descr, this.line, this.col); - } - - protected static int Xlat(int charCode, int state) { - int p = state * INPUT_RANGE; - int n = System.Math.Min(tbl.Length - p, INPUT_RANGE); - for (;--n >= 0;) { - ushort code = tbl[p]; - if (charCode == (code >> 12)) return (code & 0xFFF); - p++; - } - return 0xFFF; - } - - public void Parse(IReader reader, IHandler handler) { - if (reader == null) throw new ArgumentNullException("reader"); - if (handler == null) handler = new HandlerAdapter(); - - AttrListImpl attrList = new AttrListImpl(); - string lastAttrName = null; - Stack tagStack = new Stack(); - string elementName = null; - line = 1; - col = 0; - int currCh = 0; - int stateCode = 0; - StringBuilder sbChars = new StringBuilder(); - bool seenCData = false; - bool isComment = false; - bool isDTD = false; - int bracketSwitch = 0; - - handler.OnStartParsing(this); - - while (true) { - ++this.col; - - currCh = reader.Read(); - - if (currCh == -1) { - if (stateCode != 0) { - FatalErr("Unexpected EOF"); - } - break; - } - - int charCode = "<>/?=&'\"![ ]\t\r\n".IndexOf((char)currCh) & 0xF; - if (charCode == (int)CharKind.CR) continue; // ignore - // whitepace ::= (#x20 | #x9 | #xd | #xa)+ - if (charCode == (int)CharKind.TAB) charCode = (int)CharKind.SPACE; // tab == space - if (charCode == (int)CharKind.EOL) { - this.col = 0; - this.line++; - charCode = (int)CharKind.SPACE; - } - - int actionCode = MiniParser.Xlat(charCode, stateCode); - stateCode = actionCode & 0xFF; - // Ignore newline inside attribute value. - if (currCh == '\n' && (stateCode == 0xE || stateCode == 0xF)) continue; - actionCode >>= 8; - - if (stateCode >= 0x80) { - if (stateCode == 0xFF) { - FatalErr("State dispatch error."); - } else { - FatalErr(errors[stateCode ^ 0x80]); - } - } - - switch (actionCode) { - case (int)ActionCode.START_ELEM: - handler.OnStartElement(elementName, attrList); - if (currCh != '/') { - tagStack.Push(elementName); - } else { - handler.OnEndElement(elementName); - } - attrList.Clear(); - break; - - case (int)ActionCode.END_ELEM: - elementName = sbChars.ToString(); - sbChars = new StringBuilder(); - string endName = null; - if (tagStack.Count == 0 || - elementName != (endName = tagStack.Pop() as string)) { - if (endName == null) { - FatalErr("Tag stack underflow"); - } else { - FatalErr(String.Format("Expected end tag '{0}' but found '{1}'", elementName, endName)); - } - } - handler.OnEndElement(elementName); - break; - - case (int)ActionCode.END_NAME: - elementName = sbChars.ToString(); - sbChars = new StringBuilder(); - if (currCh != '/' && currCh != '>') break; - goto case (int)ActionCode.START_ELEM; - - case (int)ActionCode.SET_ATTR_NAME: - lastAttrName = sbChars.ToString(); - sbChars = new StringBuilder(); - break; - - case (int)ActionCode.SET_ATTR_VAL: - if (lastAttrName == null) FatalErr("Internal error."); - attrList.Add(lastAttrName, sbChars.ToString()); - sbChars = new StringBuilder(); - lastAttrName = null; - break; - - case (int)ActionCode.SEND_CHARS: - handler.OnChars(sbChars.ToString()); - sbChars = new StringBuilder(); - break; - - case (int)ActionCode.START_CDATA: - string cdata = "CDATA["; - isComment = false; - isDTD = false; - - if (currCh == '-') { - currCh = reader.Read(); - - if (currCh != '-') FatalErr("Invalid comment"); - - this.col++; - isComment = true; - twoCharBuff[0] = -1; - twoCharBuff[1] = -1; - } else { - if (currCh != '[') { - isDTD = true; - bracketSwitch = 0; - break; - } - - for (int i = 0; i < cdata.Length; i++) { - if (reader.Read() != cdata[i]) { - this.col += i+1; - break; - } - } - this.col += cdata.Length; - seenCData = true; - } - break; - - case (int)ActionCode.END_CDATA: - int n = 0; - currCh = ']'; - - while (currCh == ']') { - currCh = reader.Read(); - n++; - } - - if (currCh != '>') { - for (int i = 0; i < n; i++) sbChars.Append(']'); - sbChars.Append((char)currCh); - stateCode = 0x12; - } else { - for (int i = 0; i < n-2; i++) sbChars.Append(']'); - seenCData = false; - } - - this.col += n; - break; - - case (int)ActionCode.ERROR: - FatalErr(String.Format("Error {0}", stateCode)); - break; - - case (int)ActionCode.STATE_CHANGE: - break; - - case (int)ActionCode.FLUSH_CHARS_STATE_CHANGE: - sbChars = new StringBuilder(); - if (currCh != '<') goto case (int)ActionCode.ACC_CHARS_STATE_CHANGE; - break; - - case (int)ActionCode.ACC_CHARS_STATE_CHANGE: - sbChars.Append((char)currCh); - break; - - case (int)ActionCode.ACC_CDATA: - if (isComment) { - if (currCh == '>' - && twoCharBuff[0] == '-' - && twoCharBuff[1] == '-') { - isComment = false; - stateCode = 0; - } else { - twoCharBuff[0] = twoCharBuff[1]; - twoCharBuff[1] = currCh; - } - } else if (isDTD) { - if (currCh == '<' || currCh == '>') bracketSwitch ^= 1; - if (currCh == '>' && bracketSwitch != 0) { - isDTD = false; - stateCode = 0; - } - } else { - if (this.splitCData - && sbChars.Length > 0 - && seenCData) { - handler.OnChars(sbChars.ToString()); - sbChars = new StringBuilder(); - } - seenCData = false; - sbChars.Append((char)currCh); - } - break; - - case (int)ActionCode.PROC_CHAR_REF: - currCh = reader.Read(); - int cl = this.col + 1; - if (currCh == '#') { // character reference - int r = 10; - int chCode = 0; - int nDigits = 0; - currCh = reader.Read(); - cl++; - - if (currCh == 'x') { - currCh = reader.Read(); - cl++; - r=16; - } - - NumberStyles style = r == 16 ? NumberStyles.HexNumber : NumberStyles.Integer; - - while (true) { - int x = -1; - if (Char.IsNumber((char)currCh) || "abcdef".IndexOf(Char.ToLower((char)currCh)) != -1) { - try { - x = Int32.Parse(new string((char)currCh, 1), style); - } catch (FormatException) {x = -1;} - } - if (x == -1) break; - chCode *= r; - chCode += x; - nDigits++; - currCh = reader.Read(); - cl++; - } - - if (currCh == ';' && nDigits > 0) { - sbChars.Append((char)chCode); - } else { - FatalErr("Bad char ref"); - } - } else { - // entity reference - string entityRefChars = "aglmopqstu"; // amp | apos | quot | gt | lt - string entities = "&'\"><"; - - int pos = 0; - int entIdx = 0xF; - int predShift = 0; - - int sbLen = sbChars.Length; - - while (true) { - if (pos != 0xF) pos = entityRefChars.IndexOf((char)currCh) & 0xF; - if (pos == 0xF) FatalErr(errors[7]); - sbChars.Append((char)currCh); - - int path = "\uFF35\u3F8F\u4F8F\u0F5F\uFF78\uE1F4\u2299\uEEFF\uEEFF\uFF4F"[pos]; - int lBr = (path >> 4) & 0xF; - int rBr = path & 0xF; - int lPred = path >> 12; - int rPred = (path >> 8) & 0xF; - currCh = reader.Read(); - cl++; - pos = 0xF; - if (lBr != 0xF && currCh == entityRefChars[lBr]) { - if (lPred < 0xE) entIdx = lPred; -// pred = lPred; - predShift = 12; // left - } else if (rBr != 0xF && currCh == entityRefChars[rBr]) { - if (rPred < 0xE) entIdx = rPred; -// pred = rPred; - predShift = 8; // right - } else if (currCh == ';') { - if (entIdx != 0xF - && predShift != 0 - && ((path >> predShift) & 0xF) == 0xE) break; - continue; // pos == 0xF - } - - pos=0; - - } - - int l = cl - this.col - 1; - - if ((l > 0 && l < 5) - &&(StrEquals("amp", sbChars, sbLen, l) - || StrEquals("apos", sbChars, sbLen, l) - || StrEquals("quot", sbChars, sbLen, l) - || StrEquals("lt", sbChars, sbLen, l) - || StrEquals("gt", sbChars, sbLen, l)) - ) { - sbChars.Length = sbLen; - sbChars.Append(entities[entIdx]); - } else FatalErr(errors[7]); - } - - this.col = cl; - break; - - default: - FatalErr(String.Format("Unexpected action code - {0}.", actionCode)); - break; - } - } // while (true) - - handler.OnEndParsing(this); - - } // Parse - - } - -} diff --git a/FirClient/Assets/Libraries/Mono.Xml/MiniParser.cs.meta b/FirClient/Assets/Libraries/Mono.Xml/MiniParser.cs.meta deleted file mode 100644 index bbc12f50..00000000 --- a/FirClient/Assets/Libraries/Mono.Xml/MiniParser.cs.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 728a134ff25ce624789cb4e887a61b31 -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: diff --git a/FirClient/Assets/Libraries/Mono.Xml/SecurityParser.cs b/FirClient/Assets/Libraries/Mono.Xml/SecurityParser.cs deleted file mode 100644 index ec538308..00000000 --- a/FirClient/Assets/Libraries/Mono.Xml/SecurityParser.cs +++ /dev/null @@ -1,109 +0,0 @@ -// -// Mono.Xml.SecurityParser.cs class implementation -// -// Author: -// Sebastien Pouliot (spouliot@motus.com) -// -// (C) 2003 Motus Technologies Inc. (http://www.motus.com) -// - -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -using System; -using System.Collections; -using System.IO; -using System.Security; - -namespace Mono.Xml { - - // convert an XML document into SecurityElement objects - internal class SecurityParser : SmallXmlParser, SmallXmlParser.IContentHandler { - - private SecurityElement root; - - public SecurityParser () : base () - { - stack = new Stack (); - } - - public void LoadXml (string xml) - { - root = null; -#if CF_1_0 - stack = new Stack (); -#else - stack.Clear (); -#endif - Parse (new StringReader (xml), this); - } - - public SecurityElement ToXml () - { - return root; - } - - // IContentHandler - - private SecurityElement current; - private Stack stack; - - public void OnStartParsing (SmallXmlParser parser) {} - - public void OnProcessingInstruction (string name, string text) {} - - public void OnIgnorableWhitespace (string s) {} - - public void OnStartElement (string name, SmallXmlParser.IAttrList attrs) - { - SecurityElement newel = new SecurityElement (name); - if (root == null) { - root = newel; - current = newel; - } - else { - SecurityElement parent = (SecurityElement) stack.Peek (); - parent.AddChild (newel); - } - stack.Push (newel); - current = newel; - // attributes - int n = attrs.Length; - for (int i=0; i < n; i++) - current.AddAttribute (attrs.GetName (i), attrs.GetValue (i)); - } - - public void OnEndElement (string name) - { - current = (SecurityElement) stack.Pop (); - } - - public void OnChars (string ch) - { - current.Text = ch; - } - - public void OnEndParsing (SmallXmlParser parser) {} - } -} - diff --git a/FirClient/Assets/Libraries/Mono.Xml/SecurityParser.cs.meta b/FirClient/Assets/Libraries/Mono.Xml/SecurityParser.cs.meta deleted file mode 100644 index b30dde41..00000000 --- a/FirClient/Assets/Libraries/Mono.Xml/SecurityParser.cs.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: da5d6a0d68618aa4395966a66aac6141 -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: diff --git a/FirClient/Assets/Libraries/Mono.Xml/SmallXmlParser.cs b/FirClient/Assets/Libraries/Mono.Xml/SmallXmlParser.cs deleted file mode 100644 index 4a492ef5..00000000 --- a/FirClient/Assets/Libraries/Mono.Xml/SmallXmlParser.cs +++ /dev/null @@ -1,637 +0,0 @@ -// -// SmallXmlParser.cs -// -// Author: -// Atsushi Enomoto -// -// Copyright (C) 2005 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -// -// small xml parser that is mostly compatible with -// - -using System; -using System.Collections; -using System.Globalization; -using System.IO; -using System.Text; - -namespace Mono.Xml -{ - internal class DefaultHandler : SmallXmlParser.IContentHandler - { - public void OnStartParsing (SmallXmlParser parser) - { - } - - public void OnEndParsing (SmallXmlParser parser) - { - } - - public void OnStartElement (string name, SmallXmlParser.IAttrList attrs) - { - } - - public void OnEndElement (string name) - { - } - - public void OnChars (string s) - { - } - - public void OnIgnorableWhitespace (string s) - { - } - - public void OnProcessingInstruction (string name, string text) - { - } - } - - internal class SmallXmlParser - { - public interface IContentHandler - { - void OnStartParsing (SmallXmlParser parser); - void OnEndParsing (SmallXmlParser parser); - void OnStartElement (string name, IAttrList attrs); - void OnEndElement (string name); - void OnProcessingInstruction (string name, string text); - void OnChars (string text); - void OnIgnorableWhitespace (string text); - } - - public interface IAttrList - { - int Length { get; } - bool IsEmpty { get; } - string GetName (int i); - string GetValue (int i); - string GetValue (string name); - string [] Names { get; } - string [] Values { get; } - } - - class AttrListImpl : IAttrList - { - public int Length { - get { return attrNames.Count; } - } - public bool IsEmpty { - get { return attrNames.Count == 0; } - } - public string GetName (int i) - { - return (string) attrNames [i]; - } - public string GetValue (int i) - { - return (string) attrValues [i]; - } - public string GetValue (string name) - { - for (int i = 0; i < attrNames.Count; i++) - if ((string) attrNames [i] == name) - return (string) attrValues [i]; - return null; - } - public string [] Names { - get { return (string []) attrNames.ToArray (typeof (string)); } - } - public string [] Values { - get { return (string []) attrValues.ToArray (typeof (string)); } - } - - ArrayList attrNames = new ArrayList (); - ArrayList attrValues = new ArrayList (); - - internal void Clear () - { - attrNames.Clear (); - attrValues.Clear (); - } - - internal void Add (string name, string value) - { - attrNames.Add (name); - attrValues.Add (value); - } - } - - IContentHandler handler; - TextReader reader; - Stack elementNames = new Stack (); - Stack xmlSpaces = new Stack (); - string xmlSpace; - StringBuilder buffer = new StringBuilder (200); - char [] nameBuffer = new char [30]; - bool isWhitespace; - - AttrListImpl attributes = new AttrListImpl (); - int line = 1, column; - bool resetColumn; - - public SmallXmlParser () - { - } - - private Exception Error (string msg) - { - return new SmallXmlParserException (msg, line, column); - } - - private Exception UnexpectedEndError () - { - string [] arr = new string [elementNames.Count]; - // COMPACT FRAMEWORK NOTE: CopyTo is not visible through the Stack class - (elementNames as ICollection).CopyTo (arr, 0); - return Error (String.Format ( - "Unexpected end of stream. Element stack content is {0}", String.Join (",", arr))); - } - - - private bool IsNameChar (char c, bool start) - { - switch (c) { - case ':': - case '_': - return true; - case '-': - case '.': - return !start; - } - if (c > 0x100) { // optional condition for optimization - switch (c) { - case '\u0559': - case '\u06E5': - case '\u06E6': - return true; - } - if ('\u02BB' <= c && c <= '\u02C1') - return true; - } - switch (Char.GetUnicodeCategory (c)) { - case UnicodeCategory.LowercaseLetter: - case UnicodeCategory.UppercaseLetter: - case UnicodeCategory.OtherLetter: - case UnicodeCategory.TitlecaseLetter: - case UnicodeCategory.LetterNumber: - return true; - case UnicodeCategory.SpacingCombiningMark: - case UnicodeCategory.EnclosingMark: - case UnicodeCategory.NonSpacingMark: - case UnicodeCategory.ModifierLetter: - case UnicodeCategory.DecimalDigitNumber: - return !start; - default: - return false; - } - } - - private bool IsWhitespace (int c) - { - switch (c) { - case ' ': - case '\r': - case '\t': - case '\n': - return true; - default: - return false; - } - } - - - public void SkipWhitespaces () - { - SkipWhitespaces (false); - } - - private void HandleWhitespaces () - { - while (IsWhitespace (Peek ())) - buffer.Append ((char) Read ()); - if (Peek () != '<' && Peek () >= 0) - isWhitespace = false; - } - - public void SkipWhitespaces (bool expected) - { - while (true) { - switch (Peek ()) { - case ' ': - case '\r': - case '\t': - case '\n': - Read (); - if (expected) - expected = false; - continue; - } - if (expected) - throw Error ("Whitespace is expected."); - return; - } - } - - - private int Peek () - { - return reader.Peek (); - } - - private int Read () - { - int i = reader.Read (); - if (i == '\n') - resetColumn = true; - if (resetColumn) { - line++; - resetColumn = false; - column = 1; - } - else - column++; - return i; - } - - public void Expect (int c) - { - int p = Read (); - if (p < 0) - throw UnexpectedEndError (); - else if (p != c) - throw Error (String.Format ("Expected '{0}' but got {1}", (char) c, (char) p)); - } - - private string ReadUntil (char until, bool handleReferences) - { - while (true) { - if (Peek () < 0) - throw UnexpectedEndError (); - char c = (char) Read (); - if (c == until) - break; - else if (handleReferences && c == '&') - ReadReference (); - else - buffer.Append (c); - } - string ret = buffer.ToString (); - buffer.Length = 0; - return ret; - } - - public string ReadName () - { - int idx = 0; - if (Peek () < 0 || !IsNameChar ((char) Peek (), true)) - throw Error ("XML name start character is expected."); - for (int i = Peek (); i >= 0; i = Peek ()) { - char c = (char) i; - if (!IsNameChar (c, false)) - break; - if (idx == nameBuffer.Length) { - char [] tmp = new char [idx * 2]; - // COMPACT FRAMEWORK NOTE: Array.Copy(sourceArray, destinationArray, count) is not available. - Array.Copy (nameBuffer, 0, tmp, 0, idx); - nameBuffer = tmp; - } - nameBuffer [idx++] = c; - Read (); - } - if (idx == 0) - throw Error ("Valid XML name is expected."); - return new string (nameBuffer, 0, idx); - } - - - public void Parse (TextReader input, IContentHandler handler) - { - this.reader = input; - this.handler = handler; - - handler.OnStartParsing (this); - - while (Peek () >= 0) - ReadContent (); - HandleBufferedContent (); - if (elementNames.Count > 0) - throw Error (String.Format ("Insufficient close tag: {0}", elementNames.Peek ())); - - handler.OnEndParsing (this); - - Cleanup (); - } - - private void Cleanup () - { - line = 1; - column = 0; - handler = null; - reader = null; -#if CF_1_0 - elementNames = new Stack (); - xmlSpaces = new Stack (); -#else - elementNames.Clear (); - xmlSpaces.Clear (); -#endif - attributes.Clear (); - buffer.Length = 0; - xmlSpace = null; - isWhitespace = false; - } - - public void ReadContent () - { - string name; - if (IsWhitespace (Peek ())) { - if (buffer.Length == 0) - isWhitespace = true; - HandleWhitespaces (); - } - if (Peek () == '<') { - Read (); - switch (Peek ()) { - case '!': // declarations - Read (); - if (Peek () == '[') { - Read (); - if (ReadName () != "CDATA") - throw Error ("Invalid declaration markup"); - Expect ('['); - ReadCDATASection (); - return; - } - else if (Peek () == '-') { - ReadComment (); - return; - } - else if (ReadName () != "DOCTYPE") - throw Error ("Invalid declaration markup."); - else - throw Error ("This parser does not support document type."); - case '?': // PIs - HandleBufferedContent (); - Read (); - name = ReadName (); - SkipWhitespaces (); - string text = String.Empty; - if (Peek () != '?') { - while (true) { - text += ReadUntil ('?', false); - if (Peek () == '>') - break; - text += "?"; - } - } - handler.OnProcessingInstruction ( - name, text); - Expect ('>'); - return; - case '/': // end tags - HandleBufferedContent (); - if (elementNames.Count == 0) - throw UnexpectedEndError (); - Read (); - name = ReadName (); - SkipWhitespaces (); - string expected = (string) elementNames.Pop (); - xmlSpaces.Pop (); - if (xmlSpaces.Count > 0) - xmlSpace = (string) xmlSpaces.Peek (); - else - xmlSpace = null; - if (name != expected) - throw Error (String.Format ("End tag mismatch: expected {0} but found {1}", expected, name)); - handler.OnEndElement (name); - Expect ('>'); - return; - default: // start tags (including empty tags) - HandleBufferedContent (); - name = ReadName (); - while (Peek () != '>' && Peek () != '/') - ReadAttribute (attributes); - handler.OnStartElement (name, attributes); - attributes.Clear (); - SkipWhitespaces (); - if (Peek () == '/') { - Read (); - handler.OnEndElement (name); - } - else { - elementNames.Push (name); - xmlSpaces.Push (xmlSpace); - } - Expect ('>'); - return; - } - } - else - ReadCharacters (); - } - - private void HandleBufferedContent () - { - if (buffer.Length == 0) - return; - if (isWhitespace) - handler.OnIgnorableWhitespace (buffer.ToString ()); - else - handler.OnChars (buffer.ToString ()); - buffer.Length = 0; - isWhitespace = false; - } - - private void ReadCharacters () - { - isWhitespace = false; - while (true) { - int i = Peek (); - switch (i) { - case -1: - return; - case '<': - return; - case '&': - Read (); - ReadReference (); - continue; - default: - buffer.Append ((char) Read ()); - continue; - } - } - } - - private void ReadReference () - { - if (Peek () == '#') { - // character reference - Read (); - ReadCharacterReference (); - } else { - string name = ReadName (); - Expect (';'); - switch (name) { - case "amp": - buffer.Append ('&'); - break; - case "quot": - buffer.Append ('"'); - break; - case "apos": - buffer.Append ('\''); - break; - case "lt": - buffer.Append ('<'); - break; - case "gt": - buffer.Append ('>'); - break; - default: - throw Error ("General non-predefined entity reference is not supported in this parser."); - } - } - } - - private int ReadCharacterReference () - { - int n = 0; - if (Peek () == 'x') { // hex - Read (); - for (int i = Peek (); i >= 0; i = Peek ()) { - if ('0' <= i && i <= '9') - n = n << 4 + i - '0'; - else if ('A' <= i && i <='F') - n = n << 4 + i - 'A' + 10; - else if ('a' <= i && i <='f') - n = n << 4 + i - 'a' + 10; - else - break; - Read (); - } - } else { - for (int i = Peek (); i >= 0; i = Peek ()) { - if ('0' <= i && i <= '9') - n = n << 4 + i - '0'; - else - break; - Read (); - } - } - return n; - } - - private void ReadAttribute (AttrListImpl a) - { - SkipWhitespaces (true); - if (Peek () == '/' || Peek () == '>') - // came here just to spend trailing whitespaces - return; - - string name = ReadName (); - string value; - SkipWhitespaces (); - Expect ('='); - SkipWhitespaces (); - switch (Read ()) { - case '\'': - value = ReadUntil ('\'', true); - break; - case '"': - value = ReadUntil ('"', true); - break; - default: - throw Error ("Invalid attribute value markup."); - } - if (name == "xml:space") - xmlSpace = value; - a.Add (name, value); - } - - private void ReadCDATASection () - { - int nBracket = 0; - while (true) { - if (Peek () < 0) - throw UnexpectedEndError (); - char c = (char) Read (); - if (c == ']') - nBracket++; - else if (c == '>' && nBracket > 1) { - for (int i = nBracket; i > 2; i--) - buffer.Append (']'); - break; - } - else { - for (int i = 0; i < nBracket; i++) - buffer.Append (']'); - nBracket = 0; - buffer.Append (c); - } - } - } - - private void ReadComment () - { - Expect ('-'); - Expect ('-'); - while (true) { - if (Read () != '-') - continue; - if (Read () != '-') - continue; - if (Read () != '>') - throw Error ("'--' is not allowed inside comment markup."); - break; - } - } - } - - internal class SmallXmlParserException : SystemException - { - int line; - int column; - - public SmallXmlParserException (string msg, int line, int column) - : base (String.Format ("{0}. At ({1},{2})", msg, line, column)) - { - this.line = line; - this.column = column; - } - - public int Line { - get { return line; } - } - - public int Column { - get { return column; } - } - } -} - - - diff --git a/FirClient/Assets/Libraries/Mono.Xml/SmallXmlParser.cs.meta b/FirClient/Assets/Libraries/Mono.Xml/SmallXmlParser.cs.meta deleted file mode 100644 index f9344d8c..00000000 --- a/FirClient/Assets/Libraries/Mono.Xml/SmallXmlParser.cs.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: c2efb2fb46eb19240bfbaa917fe090ca -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: diff --git a/FirClient/Assets/Plugins/FirCommon.dll b/FirClient/Assets/Plugins/FirCommon.dll index c49f8583..96e85250 100644 Binary files a/FirClient/Assets/Plugins/FirCommon.dll and b/FirClient/Assets/Plugins/FirCommon.dll differ diff --git a/FirClient/Assets/Scripts/Handler/BaseDispatcher.cs b/FirClient/Assets/Scripts/Handler/BaseDispatcher.cs index cb16fa83..0cb28a01 100644 --- a/FirClient/Assets/Scripts/Handler/BaseDispatcher.cs +++ b/FirClient/Assets/Scripts/Handler/BaseDispatcher.cs @@ -1,18 +1,7 @@ -using LiteNetLib; -using LiteNetLib.Utils; - namespace FirClient.Manager { public abstract class BaseDispatcher : BaseBehaviour { - public abstract void OnMessage(NetPeer peer, NetDataReader reader); - - protected void ParseProtoBytes(NetDataReader reader, ref string protoName, ref byte[] bytes) - { - protoName = reader.GetString(); - var count = reader.GetInt(); - bytes = new byte[count]; - reader.GetBytes(bytes, count); - } + public abstract void OnMessage(string protoName, byte[] bytes); } } \ No newline at end of file diff --git a/FirClient/Assets/Scripts/Handler/BaseHandler.cs b/FirClient/Assets/Scripts/Handler/BaseHandler.cs index 45fe77b1..7f19c9bd 100644 --- a/FirClient/Assets/Scripts/Handler/BaseHandler.cs +++ b/FirClient/Assets/Scripts/Handler/BaseHandler.cs @@ -5,15 +5,6 @@ namespace FirClient.Handler public abstract class BaseHandler : BaseBehaviour { public abstract void OnMessage(byte[] bytes); - - //protected T DeSerialize(byte[] bytes) - //{ - // using (MemoryStream ms = new MemoryStream(bytes)) - // { - // T t = Serializer.Deserialize(ms); - // return t; - // } - //} } } diff --git a/FirClient/Assets/Scripts/Handler/CSMsgDispatcher.cs b/FirClient/Assets/Scripts/Handler/CSMsgDispatcher.cs index f1fdf0a4..3fa90981 100644 --- a/FirClient/Assets/Scripts/Handler/CSMsgDispatcher.cs +++ b/FirClient/Assets/Scripts/Handler/CSMsgDispatcher.cs @@ -1,7 +1,5 @@ -using FirClient.Define; using FirClient.Handler; -using LiteNetLib; -using LiteNetLib.Utils; +using FirCommon.Define; using System.Collections.Generic; namespace FirClient.Manager @@ -13,14 +11,9 @@ internal class CSMsgDispatcher : BaseDispatcher { Protocal.Default, new DefaultHandler() }, }; - public override void OnMessage(NetPeer peer, NetDataReader reader) + public override void OnMessage(string protoName, byte[] bytes) { - byte[] bytes = null; - string protoName = null; - ParseProtoBytes(reader, ref protoName, ref bytes); - - BaseHandler handler = null; - if (mHandlers.TryGetValue(protoName, out handler)) + if (mHandlers.TryGetValue(protoName, out BaseHandler handler)) { if (handler != null) { diff --git a/FirClient/Assets/Scripts/Handler/LuaMsgDispatcher.cs b/FirClient/Assets/Scripts/Handler/LuaMsgDispatcher.cs index 9a31b833..b0fefe16 100644 --- a/FirClient/Assets/Scripts/Handler/LuaMsgDispatcher.cs +++ b/FirClient/Assets/Scripts/Handler/LuaMsgDispatcher.cs @@ -1,17 +1,12 @@ using FirClient.Utility; -using LiteNetLib; -using LiteNetLib.Utils; using LuaInterface; namespace FirClient.Manager { internal class LuaMsgDispatcher : BaseDispatcher { - public override void OnMessage(NetPeer peer, NetDataReader reader) + public override void OnMessage(string protoName, byte[] bytes) { - byte[] bytes = null; - string protoName = null; - ParseProtoBytes(reader, ref protoName, ref bytes); if (bytes != null) { var buffer = new LuaByteBuffer(bytes); diff --git a/FirClient/Assets/Libraries/LiteNetLib/Layers.meta b/FirClient/Assets/Scripts/Lua/3rd/event.meta similarity index 77% rename from FirClient/Assets/Libraries/LiteNetLib/Layers.meta rename to FirClient/Assets/Scripts/Lua/3rd/event.meta index 24a987c3..19d50965 100644 --- a/FirClient/Assets/Libraries/LiteNetLib/Layers.meta +++ b/FirClient/Assets/Scripts/Lua/3rd/event.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: fb6d5578bee113f48a9d9c91a5f7895c +guid: 5ddd6b56ca24a8949988c6696b0a408f folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/FirClient/Assets/Libraries/LiteNetLib/LiteNetLib.csproj.meta b/FirClient/Assets/Scripts/Lua/3rd/event/eventlib.lua.meta similarity index 74% rename from FirClient/Assets/Libraries/LiteNetLib/LiteNetLib.csproj.meta rename to FirClient/Assets/Scripts/Lua/3rd/event/eventlib.lua.meta index f3b3a718..d26eb05a 100644 --- a/FirClient/Assets/Libraries/LiteNetLib/LiteNetLib.csproj.meta +++ b/FirClient/Assets/Scripts/Lua/3rd/event/eventlib.lua.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: d0b58bceccc11b34c9c8535fa4c3cb4c +guid: 4555fca152c4d9b4ead4adbf24581a10 DefaultImporter: externalObjects: {} userData: diff --git a/FirClient/Assets/Libraries/LiteNetLib/Utils.meta b/FirClient/Assets/Scripts/Lua/3rd/event/events.lua.meta similarity index 67% rename from FirClient/Assets/Libraries/LiteNetLib/Utils.meta rename to FirClient/Assets/Scripts/Lua/3rd/event/events.lua.meta index dca0f5bd..bfdffd78 100644 --- a/FirClient/Assets/Libraries/LiteNetLib/Utils.meta +++ b/FirClient/Assets/Scripts/Lua/3rd/event/events.lua.meta @@ -1,6 +1,5 @@ fileFormatVersion: 2 -guid: 04b0926cb8c74594e83f5e28988e33ef -folderAsset: yes +guid: f69d7494ca51d5f479417fd6a14a1df7 DefaultImporter: externalObjects: {} userData: diff --git a/FirClient/Assets/Scripts/Lua/Adapter/LoginAdapter.lua b/FirClient/Assets/Scripts/Lua/Adapter/LoginAdapter.lua index cf60bbf9..400f19cb 100644 --- a/FirClient/Assets/Scripts/Lua/Adapter/LoginAdapter.lua +++ b/FirClient/Assets/Scripts/Lua/Adapter/LoginAdapter.lua @@ -16,7 +16,7 @@ function LoginAdapter:ConnectServer() if self.netMgr ~= nil then local ip = AppConst.SocketAddress local port = tointeger(AppConst.SocketPort) - self.netMgr:Connect(ip, port, self, self.OnConnectOK) + self.netMgr:Connect(ip, port, self, self.OnConnectOK, self.OnDisconnected) end end @@ -36,6 +36,10 @@ function LoginAdapter:OnConnectOK(disReason) end end +function LoginAdapter:OnDisconnected(disReason) + logError('server disconnected!!! reason:', disReason) +end + function LoginAdapter:OnLeaveLevel(execOK) if execOK ~= nil then execAction(execOK) diff --git a/FirClient/Assets/Scripts/Lua/Manager/NetworkManager.lua b/FirClient/Assets/Scripts/Lua/Manager/NetworkManager.lua index 9767471c..bc2b4ad9 100644 --- a/FirClient/Assets/Scripts/Lua/Manager/NetworkManager.lua +++ b/FirClient/Assets/Scripts/Lua/Manager/NetworkManager.lua @@ -81,9 +81,9 @@ function NetworkManager:OnReceived(name, bytes) end end -function NetworkManager:Connect(ip, port, caller, func) +function NetworkManager:Connect(ip, port, caller, onConnected, onDisconnected) if self.socket then - self.socket:Connect(ip, port, caller, func) + self.socket:Connect(ip, port, caller, onConnected, onConnected) log("Connect Server [ip]:"..ip.." [port]:"..port) end end diff --git a/FirClient/Assets/Scripts/Manager/NetworkManager.cs b/FirClient/Assets/Scripts/Manager/NetworkManager.cs index 7928d3a5..9229d212 100644 --- a/FirClient/Assets/Scripts/Manager/NetworkManager.cs +++ b/FirClient/Assets/Scripts/Manager/NetworkManager.cs @@ -13,7 +13,8 @@ namespace FirClient.Manager struct ConnectParam { public LuaTable luaClass; - public LuaFunction callFunc; + public LuaFunction connFunc; + public LuaFunction disconnFunc; } public partial class NetworkManager : BaseManager @@ -56,10 +57,11 @@ public override void OnUpdate(float deltaTime) } } - public void Connect(string addr, int port, LuaTable luaClass, LuaFunction connectOK) + public void Connect(string addr, int port, LuaTable luaClass, LuaFunction connectOK, LuaFunction disconnFunc) { connParams.luaClass = luaClass; - connParams.callFunc = connectOK; + connParams.connFunc = connectOK; + connParams.disconnFunc = disconnFunc; mClient.Connect(addr, port, AppConst.AppName); Debug.LogWarning("Connect Server Address:" + addr + " Port:" + port); @@ -68,16 +70,16 @@ public void Connect(string addr, int port, LuaTable luaClass, LuaFunction connec [NoToLua] public void OnConnected(NetPeer peer, string disReason = null) { - if (connParams.callFunc != null) + if (connParams.connFunc != null) { var self = connParams.luaClass; - connParams.callFunc.Call(self, disReason); + connParams.connFunc.Call(self, disReason); - connParams.luaClass.Dispose(); - connParams.luaClass = null; + //connParams.luaClass.Dispose(); + //connParams.luaClass = null; - connParams.callFunc.Dispose(); - connParams.callFunc = null; + connParams.connFunc.Dispose(); + connParams.connFunc = null; } } @@ -120,17 +122,36 @@ private void SendDataInternal(ProtoType protocal, string protoName, byte[] buffe [NoToLua] public void OnReceived(NetPeer peer, NetDataReader reader) { - BaseDispatcher dispatcher = null; var key = reader.GetByte(); - if (mDispatchers.TryGetValue(key, out dispatcher)) + if (mDispatchers.TryGetValue(key, out BaseDispatcher dispatcher)) { if (dispatcher != null) { - dispatcher.OnMessage(peer, reader); + var protoName = reader.GetString(); + var count = reader.GetInt(); + var bytes = new byte[count]; + reader.GetBytes(bytes, count); + dispatcher.OnMessage(protoName, bytes); } } } + [NoToLua] + public void OnDisconnected(NetPeer peer, string disReason) + { + if (connParams.connFunc != null) + { + var self = connParams.luaClass; + connParams.disconnFunc.Call(self, disReason); + + connParams.luaClass.Dispose(); + connParams.luaClass = null; + + connParams.disconnFunc.Dispose(); + connParams.disconnFunc = null; + } + } + [NoToLua] public override void OnDispose() { diff --git a/FirClient/Assets/Scripts/Network/ClientListener.cs b/FirClient/Assets/Scripts/Network/ClientListener.cs index 4169017f..2c45a509 100644 --- a/FirClient/Assets/Scripts/Network/ClientListener.cs +++ b/FirClient/Assets/Scripts/Network/ClientListener.cs @@ -61,7 +61,7 @@ public void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo) { if (netMgr != null) { - netMgr.OnConnected(peer, disconnectInfo.Reason.ToString()); + netMgr.OnDisconnected(peer, disconnectInfo.Reason.ToString()); } Debug.Log("[CLIENT] We disconnected because " + disconnectInfo.Reason); } diff --git a/FirCommon.dll b/FirCommon.dll index c49f8583..96e85250 100644 Binary files a/FirCommon.dll and b/FirCommon.dll differ diff --git a/FirCommon/Define/CommonClass.cs b/FirCommon/Define/CommonClass.cs index e01b06c0..b69143c3 100644 --- a/FirCommon/Define/CommonClass.cs +++ b/FirCommon/Define/CommonClass.cs @@ -1,5 +1,7 @@ -using System; +using LiteNetLib; +using System; using System.IO; +using System.Net; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using UnityEngine; @@ -130,4 +132,24 @@ public static T Deserialize(string fullPath) where T : class } } } + + public class ClientPeer + { + public NetPeer peer; + + public int Id + { + get { return peer.Id; } + } + + public IPEndPoint EndPoint + { + get { return peer.EndPoint; } + } + + public ClientPeer(NetPeer peer) + { + this.peer = peer; + } + } } \ No newline at end of file diff --git a/FirClient/Assets/Libraries/LiteNetLib/BaseChannel.cs b/FirCommon/Libraries/LiteNetLib/BaseChannel.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/BaseChannel.cs rename to FirCommon/Libraries/LiteNetLib/BaseChannel.cs diff --git a/FirClient/Assets/Libraries/LiteNetLib/ConnectionRequest.cs b/FirCommon/Libraries/LiteNetLib/ConnectionRequest.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/ConnectionRequest.cs rename to FirCommon/Libraries/LiteNetLib/ConnectionRequest.cs diff --git a/FirClient/Assets/Libraries/LiteNetLib/INetEventListener.cs b/FirCommon/Libraries/LiteNetLib/INetEventListener.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/INetEventListener.cs rename to FirCommon/Libraries/LiteNetLib/INetEventListener.cs diff --git a/FirClient/Assets/Libraries/LiteNetLib/Layers/Crc32cLayer.cs b/FirCommon/Libraries/LiteNetLib/Layers/Crc32cLayer.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/Layers/Crc32cLayer.cs rename to FirCommon/Libraries/LiteNetLib/Layers/Crc32cLayer.cs diff --git a/FirClient/Assets/Libraries/LiteNetLib/Layers/PacketLayerBase.cs b/FirCommon/Libraries/LiteNetLib/Layers/PacketLayerBase.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/Layers/PacketLayerBase.cs rename to FirCommon/Libraries/LiteNetLib/Layers/PacketLayerBase.cs diff --git a/FirClient/Assets/Libraries/LiteNetLib/Layers/XorEncryptLayer.cs b/FirCommon/Libraries/LiteNetLib/Layers/XorEncryptLayer.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/Layers/XorEncryptLayer.cs rename to FirCommon/Libraries/LiteNetLib/Layers/XorEncryptLayer.cs diff --git a/FirServer/Libraries/LiteNetLib/LiteNetLib.csproj b/FirCommon/Libraries/LiteNetLib/LiteNetLib.csproj similarity index 100% rename from FirServer/Libraries/LiteNetLib/LiteNetLib.csproj rename to FirCommon/Libraries/LiteNetLib/LiteNetLib.csproj diff --git a/FirClient/Assets/Libraries/LiteNetLib/NatPunchModule.cs b/FirCommon/Libraries/LiteNetLib/NatPunchModule.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/NatPunchModule.cs rename to FirCommon/Libraries/LiteNetLib/NatPunchModule.cs diff --git a/FirClient/Assets/Libraries/LiteNetLib/NetConstants.cs b/FirCommon/Libraries/LiteNetLib/NetConstants.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/NetConstants.cs rename to FirCommon/Libraries/LiteNetLib/NetConstants.cs diff --git a/FirClient/Assets/Libraries/LiteNetLib/NetDebug.cs b/FirCommon/Libraries/LiteNetLib/NetDebug.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/NetDebug.cs rename to FirCommon/Libraries/LiteNetLib/NetDebug.cs diff --git a/FirClient/Assets/Libraries/LiteNetLib/NetManager.cs b/FirCommon/Libraries/LiteNetLib/NetManager.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/NetManager.cs rename to FirCommon/Libraries/LiteNetLib/NetManager.cs diff --git a/FirClient/Assets/Libraries/LiteNetLib/NetPacket.cs b/FirCommon/Libraries/LiteNetLib/NetPacket.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/NetPacket.cs rename to FirCommon/Libraries/LiteNetLib/NetPacket.cs diff --git a/FirClient/Assets/Libraries/LiteNetLib/NetPacketPool.cs b/FirCommon/Libraries/LiteNetLib/NetPacketPool.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/NetPacketPool.cs rename to FirCommon/Libraries/LiteNetLib/NetPacketPool.cs diff --git a/FirClient/Assets/Libraries/LiteNetLib/NetPeer.cs b/FirCommon/Libraries/LiteNetLib/NetPeer.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/NetPeer.cs rename to FirCommon/Libraries/LiteNetLib/NetPeer.cs diff --git a/FirClient/Assets/Libraries/LiteNetLib/NetSocket.cs b/FirCommon/Libraries/LiteNetLib/NetSocket.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/NetSocket.cs rename to FirCommon/Libraries/LiteNetLib/NetSocket.cs diff --git a/FirClient/Assets/Libraries/LiteNetLib/NetStatistics.cs b/FirCommon/Libraries/LiteNetLib/NetStatistics.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/NetStatistics.cs rename to FirCommon/Libraries/LiteNetLib/NetStatistics.cs diff --git a/FirClient/Assets/Libraries/LiteNetLib/NetUtils.cs b/FirCommon/Libraries/LiteNetLib/NetUtils.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/NetUtils.cs rename to FirCommon/Libraries/LiteNetLib/NetUtils.cs diff --git a/FirClient/Assets/Libraries/LiteNetLib/ReliableChannel.cs b/FirCommon/Libraries/LiteNetLib/ReliableChannel.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/ReliableChannel.cs rename to FirCommon/Libraries/LiteNetLib/ReliableChannel.cs diff --git a/FirClient/Assets/Libraries/LiteNetLib/SequencedChannel.cs b/FirCommon/Libraries/LiteNetLib/SequencedChannel.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/SequencedChannel.cs rename to FirCommon/Libraries/LiteNetLib/SequencedChannel.cs diff --git a/FirClient/Assets/Libraries/LiteNetLib/Utils/CRC32C.cs b/FirCommon/Libraries/LiteNetLib/Utils/CRC32C.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/Utils/CRC32C.cs rename to FirCommon/Libraries/LiteNetLib/Utils/CRC32C.cs diff --git a/FirClient/Assets/Libraries/LiteNetLib/Utils/FastBitConverter.cs b/FirCommon/Libraries/LiteNetLib/Utils/FastBitConverter.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/Utils/FastBitConverter.cs rename to FirCommon/Libraries/LiteNetLib/Utils/FastBitConverter.cs diff --git a/FirClient/Assets/Libraries/LiteNetLib/Utils/INetSerializable.cs b/FirCommon/Libraries/LiteNetLib/Utils/INetSerializable.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/Utils/INetSerializable.cs rename to FirCommon/Libraries/LiteNetLib/Utils/INetSerializable.cs diff --git a/FirClient/Assets/Libraries/LiteNetLib/Utils/NetDataReader.cs b/FirCommon/Libraries/LiteNetLib/Utils/NetDataReader.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/Utils/NetDataReader.cs rename to FirCommon/Libraries/LiteNetLib/Utils/NetDataReader.cs diff --git a/FirClient/Assets/Libraries/LiteNetLib/Utils/NetDataWriter.cs b/FirCommon/Libraries/LiteNetLib/Utils/NetDataWriter.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/Utils/NetDataWriter.cs rename to FirCommon/Libraries/LiteNetLib/Utils/NetDataWriter.cs diff --git a/FirClient/Assets/Libraries/LiteNetLib/Utils/NetPacketProcessor.cs b/FirCommon/Libraries/LiteNetLib/Utils/NetPacketProcessor.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/Utils/NetPacketProcessor.cs rename to FirCommon/Libraries/LiteNetLib/Utils/NetPacketProcessor.cs diff --git a/FirClient/Assets/Libraries/LiteNetLib/Utils/NetSerializer.cs b/FirCommon/Libraries/LiteNetLib/Utils/NetSerializer.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/Utils/NetSerializer.cs rename to FirCommon/Libraries/LiteNetLib/Utils/NetSerializer.cs diff --git a/FirClient/Assets/Libraries/LiteNetLib/Utils/NtpPacket.cs b/FirCommon/Libraries/LiteNetLib/Utils/NtpPacket.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/Utils/NtpPacket.cs rename to FirCommon/Libraries/LiteNetLib/Utils/NtpPacket.cs diff --git a/FirClient/Assets/Libraries/LiteNetLib/Utils/NtpRequest.cs b/FirCommon/Libraries/LiteNetLib/Utils/NtpRequest.cs similarity index 100% rename from FirClient/Assets/Libraries/LiteNetLib/Utils/NtpRequest.cs rename to FirCommon/Libraries/LiteNetLib/Utils/NtpRequest.cs diff --git a/FirServer/FirSango/GameWorld.cs b/FirServer/FirSango/GameWorld.cs index d161eced..c1d1bb96 100644 --- a/FirServer/FirSango/GameWorld.cs +++ b/FirServer/FirSango/GameWorld.cs @@ -1,7 +1,6 @@ using FirCommon.Define; using FirCommon.Utility; using FirServer; -using FirServer.Define; using FirServer.Interface; using GameLibs.FirSango.Defines; using GameLibs.FirSango.Handlers; diff --git a/FirServer/FirSango/Handlers/ConnectedHandler.cs b/FirServer/FirSango/Handlers/ConnectedHandler.cs index 3e4e2180..7640cde9 100644 --- a/FirServer/FirSango/Handlers/ConnectedHandler.cs +++ b/FirServer/FirSango/Handlers/ConnectedHandler.cs @@ -1,6 +1,6 @@ -using FirServer; +using FirCommon.Data; +using FirServer; using FirServer.Handler; -using LiteNetLib; using log4net; namespace GameLibs.FirSango.Handlers @@ -9,7 +9,7 @@ public class ConnectedHandler : BaseHandler { private static readonly ILog logger = LogManager.GetLogger(AppServer.repository.Name, typeof(ConnectedHandler)); - public override void OnMessage(NetPeer peer, byte[] bytes) + public override void OnMessage(ClientPeer peer, byte[] bytes) { logger.Info(peer.EndPoint + " OnConnected!!"); } diff --git a/FirServer/FirSango/Handlers/DefaultHandler.cs b/FirServer/FirSango/Handlers/DefaultHandler.cs index 80692864..3a64287d 100644 --- a/FirServer/FirSango/Handlers/DefaultHandler.cs +++ b/FirServer/FirSango/Handlers/DefaultHandler.cs @@ -1,6 +1,6 @@ -using FirServer; +using FirCommon.Data; +using FirServer; using FirServer.Handler; -using LiteNetLib; using log4net; using System; @@ -10,7 +10,7 @@ public class DefaultHandler : BaseHandler { private static readonly ILog logger = LogManager.GetLogger(AppServer.repository.Name, typeof(DefaultHandler)); - public override void OnMessage(NetPeer peer, byte[] bytes) + public override void OnMessage(ClientPeer peer, byte[] bytes) { throw new NotImplementedException(); } diff --git a/FirServer/FirSango/Handlers/DisconnectHandler.cs b/FirServer/FirSango/Handlers/DisconnectHandler.cs index 22f5fcfd..3d314bb6 100644 --- a/FirServer/FirSango/Handlers/DisconnectHandler.cs +++ b/FirServer/FirSango/Handlers/DisconnectHandler.cs @@ -1,6 +1,6 @@ -using FirServer; +using FirCommon.Data; +using FirServer; using FirServer.Handler; -using LiteNetLib; using log4net; namespace GameLibs.FirSango.Handlers @@ -10,7 +10,7 @@ public class DisconnectHandler : BaseHandler { private static readonly ILog logger = LogManager.GetLogger(AppServer.repository.Name, typeof(DisconnectHandler)); - public override void OnMessage(NetPeer peer, byte[] bytes) + public override void OnMessage(ClientPeer peer, byte[] bytes) { logger.Warn("connid:>" + peer.Id); } diff --git a/FirServer/FirSango/Handlers/LoginHandler.cs b/FirServer/FirSango/Handlers/LoginHandler.cs index 16905e70..58bda006 100644 --- a/FirServer/FirSango/Handlers/LoginHandler.cs +++ b/FirServer/FirSango/Handlers/LoginHandler.cs @@ -1,6 +1,4 @@ using log4net; -using FirServer.Define; -using LiteNetLib; using FirServer.Handler; using FirServer; using GameLibs.FirSango.Defines; @@ -8,6 +6,7 @@ using PbUser; using FirCommon.Utility; using FirCommon.Define; +using FirCommon.Data; namespace GameLibs.FirSango.Handlers { @@ -15,7 +14,7 @@ public class LoginHandler : BaseHandler { private static readonly ILog logger = LogManager.GetLogger(AppServer.repository.Name, typeof(LoginHandler)); - public override void OnMessage(NetPeer peer, byte[] bytes) + public override void OnMessage(ClientPeer peer, byte[] bytes) { var person = ReqLogin.Parser.ParseFrom(bytes); diff --git a/FirServer/FirServer.sln b/FirServer/FirServer.sln index 249eed53..a1e0075f 100644 --- a/FirServer/FirServer.sln +++ b/FirServer/FirServer.sln @@ -7,10 +7,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FirServer", "FirServer\FirS EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FirSango", "FirSango\FirSango.csproj", "{1CCD87BF-3A04-4175-9198-EA1734ED0001}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LiteNetLib", "Libraries\LiteNetLib\LiteNetLib.csproj", "{AF53701E-27F1-49E8-9511-1C4AD836622A}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mono.Xml", "Libraries\Mono.Xml\Mono.Xml.csproj", "{E4B95495-61E4-4BA1-9564-2FF3E9127007}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -25,14 +21,6 @@ Global {1CCD87BF-3A04-4175-9198-EA1734ED0001}.Debug|Any CPU.Build.0 = Debug|Any CPU {1CCD87BF-3A04-4175-9198-EA1734ED0001}.Release|Any CPU.ActiveCfg = Release|Any CPU {1CCD87BF-3A04-4175-9198-EA1734ED0001}.Release|Any CPU.Build.0 = Release|Any CPU - {AF53701E-27F1-49E8-9511-1C4AD836622A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {AF53701E-27F1-49E8-9511-1C4AD836622A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {AF53701E-27F1-49E8-9511-1C4AD836622A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {AF53701E-27F1-49E8-9511-1C4AD836622A}.Release|Any CPU.Build.0 = Release|Any CPU - {E4B95495-61E4-4BA1-9564-2FF3E9127007}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E4B95495-61E4-4BA1-9564-2FF3E9127007}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E4B95495-61E4-4BA1-9564-2FF3E9127007}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E4B95495-61E4-4BA1-9564-2FF3E9127007}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/FirServer/FirServer/Common/BaseBehaviour.cs b/FirServer/FirServer/Common/BaseBehaviour.cs index b6158731..f71f736f 100644 --- a/FirServer/FirServer/Common/BaseBehaviour.cs +++ b/FirServer/FirServer/Common/BaseBehaviour.cs @@ -108,5 +108,18 @@ protected static HandlerManager handlerMgr return _handlerMgr; } } + + private static ClientPeerManager _clientPeerMgr = null; + protected static ClientPeerManager clientPeerMgr + { + get + { + if (_clientPeerMgr == null) + { + _clientPeerMgr = ManagementCenter.GetManager(); + } + return _clientPeerMgr; + } + } } } diff --git a/FirServer/FirServer/Common/ManagementCenter.cs b/FirServer/FirServer/Common/ManagementCenter.cs index 00c73134..b9687699 100644 --- a/FirServer/FirServer/Common/ManagementCenter.cs +++ b/FirServer/FirServer/Common/ManagementCenter.cs @@ -24,6 +24,7 @@ public static void Initialize() AddManager(); AddManager(); AddManager(); + AddManager(); var mgrCount = mManagers.Count; var currMgrs = new List(mManagers.Values); diff --git a/FirServer/FirServer/FirServer.csproj b/FirServer/FirServer/FirServer.csproj index c60f12f1..03bf9087 100644 --- a/FirServer/FirServer/FirServer.csproj +++ b/FirServer/FirServer/FirServer.csproj @@ -23,7 +23,6 @@ - diff --git a/FirServer/FirServer/Handler/BaseHandler.cs b/FirServer/FirServer/Handler/BaseHandler.cs index a51475c7..ddac7e3f 100644 --- a/FirServer/FirServer/Handler/BaseHandler.cs +++ b/FirServer/FirServer/Handler/BaseHandler.cs @@ -1,20 +1,10 @@ -using FirServer.Interface; -using LiteNetLib; -using System.IO; +using FirCommon.Data; +using FirServer.Interface; namespace FirServer.Handler { public abstract class BaseHandler : BaseBehaviour, IHandler { - public abstract void OnMessage(NetPeer peer, byte[] bytes); - - //public T DeSerialize(byte[] bytes) - //{ - // using (MemoryStream ms = new MemoryStream(bytes)) - // { - // T t = Serializer.Deserialize(ms); - // return t; - // } - //} + public abstract void OnMessage(ClientPeer peer, byte[] bytes); } } diff --git a/FirServer/FirServer/Handler/DefaultHandler.cs b/FirServer/FirServer/Handler/DefaultHandler.cs index 00bb3e59..d89ab9d7 100644 --- a/FirServer/FirServer/Handler/DefaultHandler.cs +++ b/FirServer/FirServer/Handler/DefaultHandler.cs @@ -1,12 +1,11 @@ -using LiteNetLib; +using FirCommon.Data; namespace FirServer.Handler { class DefaultHandler : BaseHandler { - public override void OnMessage(NetPeer peer, byte[] bytes) + public override void OnMessage(ClientPeer peer, byte[] bytes) { - //netMgr.DeSerialize(bytes); } } } diff --git a/FirServer/FirServer/Handler/DisconnectHandler.cs b/FirServer/FirServer/Handler/DisconnectHandler.cs index 2d11b979..45b3ee20 100644 --- a/FirServer/FirServer/Handler/DisconnectHandler.cs +++ b/FirServer/FirServer/Handler/DisconnectHandler.cs @@ -1,10 +1,10 @@ -using LiteNetLib; +using FirCommon.Data; namespace FirServer.Handler { class DisconnectHandler : BaseHandler { - public override void OnMessage(NetPeer peer, byte[] bytes) + public override void OnMessage(ClientPeer peer, byte[] bytes) { } } diff --git a/FirServer/FirServer/Interface/IHandler.cs b/FirServer/FirServer/Interface/IHandler.cs index 18be453f..b5a858bc 100644 --- a/FirServer/FirServer/Interface/IHandler.cs +++ b/FirServer/FirServer/Interface/IHandler.cs @@ -1,9 +1,9 @@ -using LiteNetLib; +using FirCommon.Data; namespace FirServer.Interface { public interface IHandler : IObject { - void OnMessage(NetPeer peer, byte[] bytes); + void OnMessage(ClientPeer peer, byte[] bytes); } } diff --git a/FirServer/FirServer/Manager/ClientPeerManager.cs b/FirServer/FirServer/Manager/ClientPeerManager.cs new file mode 100644 index 00000000..b9f12f59 --- /dev/null +++ b/FirServer/FirServer/Manager/ClientPeerManager.cs @@ -0,0 +1,39 @@ +using FirCommon.Data; +using LiteNetLib; +using System.Collections.Generic; + +namespace FirServer.Manager +{ + public class ClientPeerManager : BaseManager + { + Dictionary mClientPeers = new Dictionary(); + + public override void Initialize() + { + } + + public ClientPeer GetClientPeer(NetPeer peer) + { + mClientPeers.TryGetValue(peer, out ClientPeer clientPeer); + if (clientPeer == null) + { + clientPeer = new ClientPeer(peer); + mClientPeers.Add(peer, clientPeer); + } + return clientPeer; + } + + public void RemoveClientPeer(NetPeer peer) + { + mClientPeers.Remove(peer); + } + + public void RemoveClientPeer(ClientPeer clientPeer) + { + if (clientPeer != null) + { + RemoveClientPeer(clientPeer.peer); + } + } + } +} diff --git a/FirServer/FirServer/Manager/HandlerManager.cs b/FirServer/FirServer/Manager/HandlerManager.cs index 4002a58d..b8c3a57b 100644 --- a/FirServer/FirServer/Manager/HandlerManager.cs +++ b/FirServer/FirServer/Manager/HandlerManager.cs @@ -1,8 +1,6 @@ using System.Collections.Generic; using log4net; -using FirServer.Handler; using FirServer.Interface; -using FirServer.Define; using LiteNetLib; using System; using FirCommon.Define; @@ -14,9 +12,6 @@ public class HandlerManager : BaseManager static readonly ILog logger = LogManager.GetLogger(AppServer.repository.Name, typeof(HandlerManager)); Dictionary mHandlers = new Dictionary(); - /// - /// 初始化消息处理器映射 - /// public override void Initialize() { } @@ -78,7 +73,8 @@ public void OnRecvData(NetPeer peer, NetPacketReader reader) { if (handler != null) { - handler.OnMessage(peer, bytes); + var clientPeer = clientPeerMgr.GetClientPeer(peer); + handler.OnMessage(clientPeer, bytes); } } catch (Exception ex) diff --git a/FirServer/FirServer/Manager/NetworkManager.cs b/FirServer/FirServer/Manager/NetworkManager.cs index 558af8d9..93d2ae09 100644 --- a/FirServer/FirServer/Manager/NetworkManager.cs +++ b/FirServer/FirServer/Manager/NetworkManager.cs @@ -1,6 +1,6 @@ -using FirCommon.Define; +using FirCommon.Data; +using FirCommon.Define; using FirCommon.Utility; -using FirServer.Define; using Google.Protobuf; using LiteNetLib; using LiteNetLib.Utils; @@ -21,24 +21,20 @@ internal void OnConnected(NetPeer peer) var handler = handlerMgr.GetHandler(Protocal.Connected); if (handler != null) { - handler.OnMessage(peer, null); + var clientPeer = clientPeerMgr.GetClientPeer(peer); + handler.OnMessage(clientPeer, null); } } - public void SendData(NetPeer peer, ProtoType protoType, string protoName, IMessage msg) + public void SendData(ClientPeer clientPeer, ProtoType protoType, string protoName, IMessage msg) { var buffer = msg.Serialize(); - SendDataInternal(peer, protoType, protoName, buffer); - } - - private void SendDataInternal(NetPeer peer, ProtoType protoType, string protoName, byte[] buffer) - { var writer = new NetDataWriter(); writer.Put((byte)protoType); writer.Put(protoName); writer.Put(buffer.Length); writer.Put(buffer); - peer.Send(writer, DeliveryMethod.ReliableOrdered); + clientPeer.peer.Send(writer, DeliveryMethod.ReliableOrdered); } public void OnRecvData(NetPeer peer, NetPacketReader reader) @@ -51,7 +47,8 @@ public void OnDisconnect(NetPeer peer) var handler = handlerMgr.GetHandler(Protocal.Disconnect); if (handler != null) { - handler.OnMessage(peer, null); + var clientPeer = clientPeerMgr.GetClientPeer(peer); + handler.OnMessage(clientPeer, null); } logger.Error("ConnectId:>" + peer.Id + " Disconnected!"); } diff --git a/FirServer/Libraries/FirCommon.dll b/FirServer/Libraries/FirCommon.dll index c49f8583..96e85250 100644 Binary files a/FirServer/Libraries/FirCommon.dll and b/FirServer/Libraries/FirCommon.dll differ diff --git a/FirServer/Libraries/LiteNetLib/BaseChannel.cs b/FirServer/Libraries/LiteNetLib/BaseChannel.cs deleted file mode 100644 index c734413f..00000000 --- a/FirServer/Libraries/LiteNetLib/BaseChannel.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System.Collections.Generic; - -namespace LiteNetLib -{ - internal abstract class BaseChannel - { - public BaseChannel Next; - protected readonly NetPeer Peer; - protected readonly Queue OutgoingQueue; - - protected BaseChannel(NetPeer peer) - { - Peer = peer; - OutgoingQueue = new Queue(64); - } - - public int PacketsInQueue - { - get { return OutgoingQueue.Count; } - } - - public void AddToQueue(NetPacket packet) - { - lock (OutgoingQueue) - OutgoingQueue.Enqueue(packet); - } - - public abstract void SendNextPackets(); - public abstract bool ProcessPacket(NetPacket packet); - } -} diff --git a/FirServer/Libraries/LiteNetLib/ConnectionRequest.cs b/FirServer/Libraries/LiteNetLib/ConnectionRequest.cs deleted file mode 100644 index f087f0eb..00000000 --- a/FirServer/Libraries/LiteNetLib/ConnectionRequest.cs +++ /dev/null @@ -1,137 +0,0 @@ -using System.Net; -using System.Threading; -using LiteNetLib.Utils; - -namespace LiteNetLib -{ - internal enum ConnectionRequestResult - { - None, - Accept, - Reject, - RejectForce - } - - public class ConnectionRequest - { - private readonly NetManager _listener; - private int _used; - - public readonly NetDataReader Data; - - internal ConnectionRequestResult Result { get; private set; } - internal long ConnectionTime; - internal byte ConnectionNumber; - public readonly IPEndPoint RemoteEndPoint; - - private bool TryActivate() - { - return Interlocked.CompareExchange(ref _used, 1, 0) == 0; - } - - internal void UpdateRequest(NetConnectRequestPacket connRequest) - { - if (connRequest.ConnectionTime >= ConnectionTime) - { - ConnectionTime = connRequest.ConnectionTime; - ConnectionNumber = connRequest.ConnectionNumber; - } - } - - internal ConnectionRequest( - long connectionId, - byte connectionNumber, - NetDataReader netDataReader, - IPEndPoint endPoint, - NetManager listener) - { - ConnectionTime = connectionId; - ConnectionNumber = connectionNumber; - RemoteEndPoint = endPoint; - Data = netDataReader; - _listener = listener; - } - - public NetPeer AcceptIfKey(string key) - { - if (!TryActivate()) - return null; - try - { - if (Data.GetString() == key) - Result = ConnectionRequestResult.Accept; - } - catch - { - NetDebug.WriteError("[AC] Invalid incoming data"); - } - if (Result == ConnectionRequestResult.Accept) - return _listener.OnConnectionSolved(this, null, 0, 0); - - Result = ConnectionRequestResult.Reject; - _listener.OnConnectionSolved(this, null, 0, 0); - return null; - } - - /// - /// Accept connection and get new NetPeer as result - /// - /// Connected NetPeer - public NetPeer Accept() - { - if (!TryActivate()) - return null; - Result = ConnectionRequestResult.Accept; - return _listener.OnConnectionSolved(this, null, 0, 0); - } - - public void Reject(byte[] rejectData, int start, int length, bool force) - { - if (!TryActivate()) - return; - Result = force ? ConnectionRequestResult.RejectForce : ConnectionRequestResult.Reject; - _listener.OnConnectionSolved(this, rejectData, start, length); - } - - public void Reject(byte[] rejectData, int start, int length) - { - Reject(rejectData, start, length, false); - } - - - public void RejectForce(byte[] rejectData, int start, int length) - { - Reject(rejectData, start, length, true); - } - - public void RejectForce() - { - Reject(null, 0, 0, true); - } - - public void RejectForce(byte[] rejectData) - { - Reject(rejectData, 0, rejectData.Length, true); - } - - public void RejectForce(NetDataWriter rejectData) - { - Reject(rejectData.Data, 0, rejectData.Length, true); - } - - public void Reject() - { - Reject(null, 0, 0, false); - } - - public void Reject(byte[] rejectData) - { - Reject(rejectData, 0, rejectData.Length, false); - } - - public void Reject(NetDataWriter rejectData) - { - Reject(rejectData.Data, 0, rejectData.Length, false); - } - } -} diff --git a/FirServer/Libraries/LiteNetLib/INetEventListener.cs b/FirServer/Libraries/LiteNetLib/INetEventListener.cs deleted file mode 100644 index c4fec6ca..00000000 --- a/FirServer/Libraries/LiteNetLib/INetEventListener.cs +++ /dev/null @@ -1,224 +0,0 @@ -using System.Net; -using System.Net.Sockets; - -namespace LiteNetLib -{ - /// - /// Type of message that you receive in OnNetworkReceiveUnconnected event - /// - public enum UnconnectedMessageType - { - BasicMessage, - Broadcast - } - - /// - /// Disconnect reason that you receive in OnPeerDisconnected event - /// - public enum DisconnectReason - { - ConnectionFailed, - Timeout, - HostUnreachable, - NetworkUnreachable, - RemoteConnectionClose, - DisconnectPeerCalled, - ConnectionRejected, - InvalidProtocol, - UnknownHost, - Reconnect, - PeerToPeerConnection - } - - /// - /// Additional information about disconnection - /// - public struct DisconnectInfo - { - /// - /// Additional info why peer disconnected - /// - public DisconnectReason Reason; - - /// - /// Error code (if reason is SocketSendError or SocketReceiveError) - /// - public SocketError SocketErrorCode; - - /// - /// Additional data that can be accessed (only if reason is RemoteConnectionClose) - /// - public NetPacketReader AdditionalData; - } - - public interface INetEventListener - { - /// - /// New remote peer connected to host, or client connected to remote host - /// - /// Connected peer object - void OnPeerConnected(NetPeer peer); - - /// - /// Peer disconnected - /// - /// disconnected peer - /// additional info about reason, errorCode or data received with disconnect message - void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo); - - /// - /// Network error (on send or receive) - /// - /// From endPoint (can be null) - /// Socket error - void OnNetworkError(IPEndPoint endPoint, SocketError socketError); - - /// - /// Received some data - /// - /// From peer - /// DataReader containing all received data - /// Type of received packet - void OnNetworkReceive(NetPeer peer, NetPacketReader reader, DeliveryMethod deliveryMethod); - - /// - /// Received unconnected message - /// - /// From address (IP and Port) - /// Message data - /// Message type (simple, discovery request or response) - void OnNetworkReceiveUnconnected(IPEndPoint remoteEndPoint, NetPacketReader reader, UnconnectedMessageType messageType); - - /// - /// Latency information updated - /// - /// Peer with updated latency - /// latency value in milliseconds - void OnNetworkLatencyUpdate(NetPeer peer, int latency); - - /// - /// On peer connection requested - /// - /// Request information (EndPoint, internal id, additional data) - void OnConnectionRequest(ConnectionRequest request); - } - - public interface IDeliveryEventListener - { - /// - /// On reliable message delivered - /// - /// - /// - void OnMessageDelivered(NetPeer peer, object userData); - } - - public class EventBasedNetListener : INetEventListener, IDeliveryEventListener - { - public delegate void OnPeerConnected(NetPeer peer); - public delegate void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo); - public delegate void OnNetworkError(IPEndPoint endPoint, SocketError socketError); - public delegate void OnNetworkReceive(NetPeer peer, NetPacketReader reader, DeliveryMethod deliveryMethod); - public delegate void OnNetworkReceiveUnconnected(IPEndPoint remoteEndPoint, NetPacketReader reader, UnconnectedMessageType messageType); - public delegate void OnNetworkLatencyUpdate(NetPeer peer, int latency); - public delegate void OnConnectionRequest(ConnectionRequest request); - public delegate void OnDeliveryEvent(NetPeer peer, object userData); - - public event OnPeerConnected PeerConnectedEvent; - public event OnPeerDisconnected PeerDisconnectedEvent; - public event OnNetworkError NetworkErrorEvent; - public event OnNetworkReceive NetworkReceiveEvent; - public event OnNetworkReceiveUnconnected NetworkReceiveUnconnectedEvent; - public event OnNetworkLatencyUpdate NetworkLatencyUpdateEvent; - public event OnConnectionRequest ConnectionRequestEvent; - public event OnDeliveryEvent DeliveryEvent; - - public void ClearPeerConnectedEvent() - { - PeerConnectedEvent = null; - } - - public void ClearPeerDisconnectedEvent() - { - PeerDisconnectedEvent = null; - } - - public void ClearNetworkErrorEvent() - { - NetworkErrorEvent = null; - } - - public void ClearNetworkReceiveEvent() - { - NetworkReceiveEvent = null; - } - - public void ClearNetworkReceiveUnconnectedEvent() - { - NetworkReceiveUnconnectedEvent = null; - } - - public void ClearNetworkLatencyUpdateEvent() - { - NetworkLatencyUpdateEvent = null; - } - - public void ClearConnectionRequestEvent() - { - ConnectionRequestEvent = null; - } - - public void ClearDeliveryEvent() - { - DeliveryEvent = null; - } - - void INetEventListener.OnPeerConnected(NetPeer peer) - { - if (PeerConnectedEvent != null) - PeerConnectedEvent(peer); - } - - void INetEventListener.OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo) - { - if (PeerDisconnectedEvent != null) - PeerDisconnectedEvent(peer, disconnectInfo); - } - - void INetEventListener.OnNetworkError(IPEndPoint endPoint, SocketError socketErrorCode) - { - if (NetworkErrorEvent != null) - NetworkErrorEvent(endPoint, socketErrorCode); - } - - void INetEventListener.OnNetworkReceive(NetPeer peer, NetPacketReader reader, DeliveryMethod deliveryMethod) - { - if (NetworkReceiveEvent != null) - NetworkReceiveEvent(peer, reader, deliveryMethod); - } - - void INetEventListener.OnNetworkReceiveUnconnected(IPEndPoint remoteEndPoint, NetPacketReader reader, UnconnectedMessageType messageType) - { - if (NetworkReceiveUnconnectedEvent != null) - NetworkReceiveUnconnectedEvent(remoteEndPoint, reader, messageType); - } - - void INetEventListener.OnNetworkLatencyUpdate(NetPeer peer, int latency) - { - if (NetworkLatencyUpdateEvent != null) - NetworkLatencyUpdateEvent(peer, latency); - } - - void INetEventListener.OnConnectionRequest(ConnectionRequest request) - { - if (ConnectionRequestEvent != null) - ConnectionRequestEvent(request); - } - - void IDeliveryEventListener.OnMessageDelivered(NetPeer peer, object userData) - { - if (DeliveryEvent != null) - DeliveryEvent(peer, userData); - } - } -} diff --git a/FirServer/Libraries/LiteNetLib/Layers/Crc32cLayer.cs b/FirServer/Libraries/LiteNetLib/Layers/Crc32cLayer.cs deleted file mode 100644 index 716c4b50..00000000 --- a/FirServer/Libraries/LiteNetLib/Layers/Crc32cLayer.cs +++ /dev/null @@ -1,36 +0,0 @@ -using LiteNetLib.Utils; -using System; - -namespace LiteNetLib.Layers -{ - public sealed class Crc32cLayer : PacketLayerBase - { - public Crc32cLayer() : base(CRC32C.ChecksumSize) - { - - } - - public override void ProcessInboundPacket(ref byte[] data, ref int length) - { - if (length < NetConstants.HeaderSize + CRC32C.ChecksumSize) - { - NetDebug.WriteError("[NM] DataReceived size: bad!"); - return; - } - - int checksumPoint = length - CRC32C.ChecksumSize; - if (CRC32C.Compute(data, 0, checksumPoint) != BitConverter.ToUInt32(data, checksumPoint)) - { - NetDebug.Write("[NM] DataReceived checksum: bad!"); - return; - } - length -= CRC32C.ChecksumSize; - } - - public override void ProcessOutBoundPacket(ref byte[] data, ref int offset, ref int length) - { - FastBitConverter.GetBytes(data, length, CRC32C.Compute(data, offset, length)); - length += CRC32C.ChecksumSize; - } - } -} diff --git a/FirServer/Libraries/LiteNetLib/Layers/PacketLayerBase.cs b/FirServer/Libraries/LiteNetLib/Layers/PacketLayerBase.cs deleted file mode 100644 index 264a4185..00000000 --- a/FirServer/Libraries/LiteNetLib/Layers/PacketLayerBase.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace LiteNetLib.Layers -{ - public abstract class PacketLayerBase - { - public readonly int ExtraPacketSizeForLayer; - - protected PacketLayerBase(int extraPacketSizeForLayer) - { - ExtraPacketSizeForLayer = extraPacketSizeForLayer; - } - - public abstract void ProcessInboundPacket(ref byte[] data, ref int length); - public abstract void ProcessOutBoundPacket(ref byte[] data, ref int offset, ref int length); - } -} diff --git a/FirServer/Libraries/LiteNetLib/Layers/XorEncryptLayer.cs b/FirServer/Libraries/LiteNetLib/Layers/XorEncryptLayer.cs deleted file mode 100644 index 82ac9a4b..00000000 --- a/FirServer/Libraries/LiteNetLib/Layers/XorEncryptLayer.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System; -using System.Text; - -namespace LiteNetLib.Layers -{ - public class XorEncryptLayer : PacketLayerBase - { - private byte[] _byteKey; - - public XorEncryptLayer() : base(0) - { - - } - - public XorEncryptLayer(byte[] key) : this() - { - SetKey(key); - } - - public XorEncryptLayer(string key) : this() - { - SetKey(key); - } - - public void SetKey(string key) - { - _byteKey = Encoding.UTF8.GetBytes(key); - } - - public void SetKey(byte[] key) - { - if (_byteKey == null || _byteKey.Length != key.Length) - _byteKey = new byte[key.Length]; - Buffer.BlockCopy(key, 0, _byteKey, 0, key.Length); - } - - public override void ProcessInboundPacket(ref byte[] data, ref int length) - { - if (_byteKey == null) - return; - for (var i = 0; i < length; i++) - { - var offset = i % _byteKey.Length; - data[i] = (byte)(data[i] ^ _byteKey[offset]); - } - } - - public override void ProcessOutBoundPacket(ref byte[] data, ref int offset, ref int length) - { - if (_byteKey == null) - return; - var cur = offset; - for (var i = 0; i < length; i++, cur++) - { - data[cur] = (byte)(data[cur] ^ _byteKey[i % _byteKey.Length]); - } - } - } -} diff --git a/FirServer/Libraries/LiteNetLib/NatPunchModule.cs b/FirServer/Libraries/LiteNetLib/NatPunchModule.cs deleted file mode 100644 index a15f8bc3..00000000 --- a/FirServer/Libraries/LiteNetLib/NatPunchModule.cs +++ /dev/null @@ -1,245 +0,0 @@ -using System.Collections.Generic; -using System.Net; -using System.Net.Sockets; -using LiteNetLib.Utils; - -namespace LiteNetLib -{ - public enum NatAddressType - { - Internal, - External - } - - public interface INatPunchListener - { - void OnNatIntroductionRequest(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint, string token); - void OnNatIntroductionSuccess(IPEndPoint targetEndPoint, NatAddressType type, string token); - } - - public class EventBasedNatPunchListener : INatPunchListener - { - public delegate void OnNatIntroductionRequest(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint, string token); - public delegate void OnNatIntroductionSuccess(IPEndPoint targetEndPoint, NatAddressType type, string token); - - public event OnNatIntroductionRequest NatIntroductionRequest; - public event OnNatIntroductionSuccess NatIntroductionSuccess; - - void INatPunchListener.OnNatIntroductionRequest(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint, string token) - { - if(NatIntroductionRequest != null) - NatIntroductionRequest(localEndPoint, remoteEndPoint, token); - } - - void INatPunchListener.OnNatIntroductionSuccess(IPEndPoint targetEndPoint, NatAddressType type, string token) - { - if (NatIntroductionSuccess != null) - NatIntroductionSuccess(targetEndPoint, type, token); - } - } - - /// - /// Module for UDP NAT Hole punching operations. Can be accessed from NetManager - /// - public sealed class NatPunchModule - { - struct RequestEventData - { - public IPEndPoint LocalEndPoint; - public IPEndPoint RemoteEndPoint; - public string Token; - } - - struct SuccessEventData - { - public IPEndPoint TargetEndPoint; - public NatAddressType Type; - public string Token; - } - - class NatIntroduceRequestPacket - { - public IPEndPoint Internal { get; set; } - public string Token { get; set; } - } - - class NatIntroduceResponsePacket - { - public IPEndPoint Internal { get; set; } - public IPEndPoint External { get; set; } - public string Token { get; set; } - } - - class NatPunchPacket - { - public string Token { get; set; } - public bool IsExternal { get; set; } - } - - private readonly NetSocket _socket; - private readonly Queue _requestEvents = new Queue(); - private readonly Queue _successEvents = new Queue(); - private readonly NetDataReader _cacheReader = new NetDataReader(); - private readonly NetDataWriter _cacheWriter = new NetDataWriter(); - private readonly NetPacketProcessor _netPacketProcessor = new NetPacketProcessor(MaxTokenLength); - private INatPunchListener _natPunchListener; - public const int MaxTokenLength = 256; - - internal NatPunchModule(NetSocket socket) - { - _socket = socket; - _netPacketProcessor.SubscribeReusable(OnNatIntroductionResponse); - _netPacketProcessor.SubscribeReusable(OnNatIntroductionRequest); - _netPacketProcessor.SubscribeReusable(OnNatPunch); - } - - internal void ProcessMessage(IPEndPoint senderEndPoint, NetPacket packet) - { - lock (_cacheReader) - { - _cacheReader.SetSource(packet.RawData, NetConstants.HeaderSize, packet.Size); - _netPacketProcessor.ReadAllPackets(_cacheReader, senderEndPoint); - } - } - - public void Init(INatPunchListener listener) - { - _natPunchListener = listener; - } - - private void Send(T packet, IPEndPoint target) where T : class, new() - { - SocketError errorCode = 0; - _cacheWriter.Reset(); - _cacheWriter.Put((byte)PacketProperty.NatMessage); - _netPacketProcessor.Write(_cacheWriter, packet); - _socket.SendTo(_cacheWriter.Data, 0, _cacheWriter.Length, target, ref errorCode); - } - - public void NatIntroduce( - IPEndPoint hostInternal, - IPEndPoint hostExternal, - IPEndPoint clientInternal, - IPEndPoint clientExternal, - string additionalInfo) - { - var req = new NatIntroduceResponsePacket - { - Token = additionalInfo - }; - - //First packet (server) send to client - req.Internal = hostInternal; - req.External = hostExternal; - Send(req, clientExternal); - - //Second packet (client) send to server - req.Internal = clientInternal; - req.External = clientExternal; - Send(req, hostExternal); - } - - public void PollEvents() - { - if (_natPunchListener == null || (_successEvents.Count == 0 && _requestEvents.Count == 0)) - return; - lock (_successEvents) - { - while (_successEvents.Count > 0) - { - var evt = _successEvents.Dequeue(); - _natPunchListener.OnNatIntroductionSuccess( - evt.TargetEndPoint, - evt.Type, - evt.Token); - } - } - lock (_requestEvents) - { - while (_requestEvents.Count > 0) - { - var evt = _requestEvents.Dequeue(); - _natPunchListener.OnNatIntroductionRequest(evt.LocalEndPoint, evt.RemoteEndPoint, evt.Token); - } - } - } - - public void SendNatIntroduceRequest(string host, int port, string additionalInfo) - { - SendNatIntroduceRequest(NetUtils.MakeEndPoint(host, port), additionalInfo); - } - - public void SendNatIntroduceRequest(IPEndPoint masterServerEndPoint, string additionalInfo) - { - //prepare outgoing data - string networkIp = NetUtils.GetLocalIp(LocalAddrType.IPv4); - if (string.IsNullOrEmpty(networkIp)) - { - networkIp = NetUtils.GetLocalIp(LocalAddrType.IPv6); - } - - Send( - new NatIntroduceRequestPacket - { - Internal = NetUtils.MakeEndPoint(networkIp, _socket.LocalPort), - Token = additionalInfo - }, - masterServerEndPoint); - } - - //We got request and must introduce - private void OnNatIntroductionRequest(NatIntroduceRequestPacket req, IPEndPoint senderEndPoint) - { - lock (_requestEvents) - { - _requestEvents.Enqueue(new RequestEventData - { - LocalEndPoint = req.Internal, - RemoteEndPoint = senderEndPoint, - Token = req.Token - }); - } - } - - //We got introduce and must punch - private void OnNatIntroductionResponse(NatIntroduceResponsePacket req) - { - NetDebug.Write(NetLogLevel.Trace, "[NAT] introduction received"); - - // send internal punch - var punchPacket = new NatPunchPacket {Token = req.Token}; - Send(punchPacket, req.Internal); - NetDebug.Write(NetLogLevel.Trace, "[NAT] internal punch sent to " + req.Internal); - - // hack for some routers - SocketError errorCode = 0; - _socket.Ttl = 2; - _socket.SendTo(new[] { (byte)PacketProperty.Empty }, 0, 1, req.External, ref errorCode); - - // send external punch - _socket.Ttl = NetConstants.SocketTTL; - punchPacket.IsExternal = true; - Send(punchPacket, req.External); - NetDebug.Write(NetLogLevel.Trace, "[NAT] external punch sent to " + req.External); - } - - //We got punch and can connect - private void OnNatPunch(NatPunchPacket req, IPEndPoint senderEndPoint) - { - //Read info - NetDebug.Write(NetLogLevel.Trace, "[NAT] punch received from {0} - additional info: {1}", - senderEndPoint, req.Token); - - //Release punch success to client; enabling him to Connect() to Sender if token is ok - lock (_successEvents) - { - _successEvents.Enqueue(new SuccessEventData - { - TargetEndPoint = senderEndPoint, - Type = req.IsExternal ? NatAddressType.External : NatAddressType.Internal, - Token = req.Token - }); - } - } - } -} diff --git a/FirServer/Libraries/LiteNetLib/NetConstants.cs b/FirServer/Libraries/LiteNetLib/NetConstants.cs deleted file mode 100644 index 5032c6cd..00000000 --- a/FirServer/Libraries/LiteNetLib/NetConstants.cs +++ /dev/null @@ -1,72 +0,0 @@ -namespace LiteNetLib -{ - /// - /// Sending method type - /// - public enum DeliveryMethod : byte - { - /// - /// Unreliable. Packets can be dropped, can be duplicated, can arrive without order. - /// - Unreliable = 4, - - /// - /// Reliable. Packets won't be dropped, won't be duplicated, can arrive without order. - /// - ReliableUnordered = 0, - - /// - /// Unreliable. Packets can be dropped, won't be duplicated, will arrive in order. - /// - Sequenced = 1, - - /// - /// Reliable and ordered. Packets won't be dropped, won't be duplicated, will arrive in order. - /// - ReliableOrdered = 2, - - /// - /// Reliable only last packet. Packets can be dropped (except the last one), won't be duplicated, will arrive in order. - /// - ReliableSequenced = 3 - } - - /// - /// Network constants. Can be tuned from sources for your purposes. - /// - public static class NetConstants - { - //can be tuned - public const int DefaultWindowSize = 64; - public const int SocketBufferSize = 1024 * 1024; //1mb - public const int SocketTTL = 255; - - public const int HeaderSize = 1; - public const int ChanneledHeaderSize = 4; - public const int FragmentHeaderSize = 6; - public const int FragmentedHeaderTotalSize = ChanneledHeaderSize + FragmentHeaderSize; - public const ushort MaxSequence = 32768; - public const ushort HalfMaxSequence = MaxSequence / 2; - - //protocol - internal const int ProtocolId = 11; - internal const int MaxUdpHeaderSize = 68; - - internal static readonly int[] PossibleMtu = - { - 576 - MaxUdpHeaderSize, //minimal - 1232 - MaxUdpHeaderSize, - 1460 - MaxUdpHeaderSize, //google cloud - 1472 - MaxUdpHeaderSize, //VPN - 1492 - MaxUdpHeaderSize, //Ethernet with LLC and SNAP, PPPoE (RFC 1042) - 1500 - MaxUdpHeaderSize //Ethernet II (RFC 1191) - }; - - internal static readonly int MaxPacketSize = PossibleMtu[PossibleMtu.Length - 1]; - - //peer specific - public const byte MaxConnectionNumber = 4; - - public const int PacketPoolSize = 1000; - } -} diff --git a/FirServer/Libraries/LiteNetLib/NetDebug.cs b/FirServer/Libraries/LiteNetLib/NetDebug.cs deleted file mode 100644 index ab92dfbe..00000000 --- a/FirServer/Libraries/LiteNetLib/NetDebug.cs +++ /dev/null @@ -1,92 +0,0 @@ -using System; -using System.Diagnostics; - -namespace LiteNetLib -{ - public class InvalidPacketException : ArgumentException - { - public InvalidPacketException(string message) : base(message) - { - } - } - - public class TooBigPacketException : InvalidPacketException - { - public TooBigPacketException(string message) : base(message) - { - } - } - - public enum NetLogLevel - { - Warning, - Error, - Trace, - Info - } - - /// - /// Interface to implement for your own logger - /// - public interface INetLogger - { - void WriteNet(NetLogLevel level, string str, params object[] args); - } - - /// - /// Static class for defining your own LiteNetLib logger instead of Console.WriteLine - /// or Debug.Log if compiled with UNITY flag - /// - public static class NetDebug - { - public static INetLogger Logger = null; - private static readonly object DebugLogLock = new object(); - private static void WriteLogic(NetLogLevel logLevel, string str, params object[] args) - { - lock (DebugLogLock) - { - if (Logger == null) - { -#if UNITY_4 || UNITY_5 || UNITY_5_3_OR_NEWER - UnityEngine.Debug.Log(string.Format(str, args)); -#else - Console.WriteLine(str, args); -#endif - } - else - { - Logger.WriteNet(logLevel, str, args); - } - } - } - - [Conditional("DEBUG_MESSAGES")] - internal static void Write(string str, params object[] args) - { - WriteLogic(NetLogLevel.Trace, str, args); - } - - [Conditional("DEBUG_MESSAGES")] - internal static void Write(NetLogLevel level, string str, params object[] args) - { - WriteLogic(level, str, args); - } - - [Conditional("DEBUG_MESSAGES"), Conditional("DEBUG")] - internal static void WriteForce(string str, params object[] args) - { - WriteLogic(NetLogLevel.Trace, str, args); - } - - [Conditional("DEBUG_MESSAGES"), Conditional("DEBUG")] - internal static void WriteForce(NetLogLevel level, string str, params object[] args) - { - WriteLogic(level, str, args); - } - - internal static void WriteError(string str, params object[] args) - { - WriteLogic(NetLogLevel.Error, str, args); - } - } -} diff --git a/FirServer/Libraries/LiteNetLib/NetManager.cs b/FirServer/Libraries/LiteNetLib/NetManager.cs deleted file mode 100644 index fcf4b899..00000000 --- a/FirServer/Libraries/LiteNetLib/NetManager.cs +++ /dev/null @@ -1,1622 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; -using System.Net; -using System.Net.Sockets; -using System.Threading; -using LiteNetLib.Layers; -using LiteNetLib.Utils; - -namespace LiteNetLib -{ - public enum IPv6Mode - { - Disabled, - SeparateSocket, - DualMode - } - - public sealed class NetPacketReader : NetDataReader - { - private NetPacket _packet; - private readonly NetManager _manager; - private readonly NetEvent _evt; - - internal NetPacketReader(NetManager manager, NetEvent evt) - { - _manager = manager; - _evt = evt; - } - - internal void SetSource(NetPacket packet) - { - if (packet == null) - return; - _packet = packet; - SetSource(packet.RawData, packet.GetHeaderSize(), packet.Size); - } - - internal void RecycleInternal() - { - Clear(); - if (_packet != null) - _manager.NetPacketPool.Recycle(_packet); - _packet = null; - _manager.RecycleEvent(_evt); - } - - public void Recycle() - { - if(_manager.AutoRecycle) - throw new Exception("Recycle called with AutoRecycle enabled"); - RecycleInternal(); - } - } - - internal sealed class NetEvent - { - public enum EType - { - Connect, - Disconnect, - Receive, - ReceiveUnconnected, - Error, - ConnectionLatencyUpdated, - Broadcast, - ConnectionRequest, - MessageDelivered - } - public EType Type; - - public NetPeer Peer; - public IPEndPoint RemoteEndPoint; - public object UserData; - public int Latency; - public SocketError ErrorCode; - public DisconnectReason DisconnectReason; - public ConnectionRequest ConnectionRequest; - public DeliveryMethod DeliveryMethod; - public readonly NetPacketReader DataReader; - - public NetEvent(NetManager manager) - { - DataReader = new NetPacketReader(manager, this); - } - } - - /// - /// Main class for all network operations. Can be used as client and/or server. - /// - public class NetManager : INetSocketListener, IEnumerable - { - private class IPEndPointComparer : IEqualityComparer - { - public bool Equals(IPEndPoint x, IPEndPoint y) - { - return x.Address.Equals(y.Address) && x.Port == y.Port; - } - - public int GetHashCode(IPEndPoint obj) - { - return obj.GetHashCode(); - } - } - - public struct NetPeerEnumerator : IEnumerator - { - private readonly NetPeer _initialPeer; - private NetPeer _p; - - public NetPeerEnumerator(NetPeer p) - { - _initialPeer = p; - _p = null; - } - - public void Dispose() - { - - } - - public bool MoveNext() - { - _p = _p == null ? _initialPeer : _p.NextPeer; - return _p != null; - } - - public void Reset() - { - throw new NotSupportedException(); - } - - public NetPeer Current - { - get { return _p; } - } - - object IEnumerator.Current - { - get { return _p; } - } - } - -#if DEBUG - private struct IncomingData - { - public byte[] Data; - public IPEndPoint EndPoint; - public DateTime TimeWhenGet; - } - private readonly List _pingSimulationList = new List(); - private readonly Random _randomGenerator = new Random(); - private const int MinLatencyThreshold = 5; -#endif - - private readonly NetSocket _socket; - private Thread _logicThread; - - private readonly Queue _netEventsQueue; - private readonly Stack _netEventsPool; - private readonly INetEventListener _netEventListener; - private readonly IDeliveryEventListener _deliveryEventListener; - - private readonly Dictionary _peersDict; - private readonly Dictionary _requestsDict; - private readonly ReaderWriterLockSlim _peersLock; - private volatile NetPeer _headPeer; - private volatile int _connectedPeersCount; - private readonly List _connectedPeerListCache; - private NetPeer[] _peersArray; - private readonly PacketLayerBase _extraPacketLayer; - private int _lastPeerId; - private readonly Queue _peerIds; - private byte _channelsCount = 1; - - internal readonly NetPacketPool NetPacketPool; - - //config section - /// - /// Enable messages receiving without connection. (with SendUnconnectedMessage method) - /// - public bool UnconnectedMessagesEnabled = false; - - /// - /// Enable nat punch messages - /// - public bool NatPunchEnabled = false; - - /// - /// Library logic update and send period in milliseconds - /// - public int UpdateTime = 15; - - /// - /// Interval for latency detection and checking connection - /// - public int PingInterval = 1000; - - /// - /// If NetManager doesn't receive any packet from remote peer during this time then connection will be closed - /// (including library internal keepalive packets) - /// - public int DisconnectTimeout = 5000; - - /// - /// Simulate packet loss by dropping random amount of packets. (Works only in DEBUG mode) - /// - public bool SimulatePacketLoss = false; - - /// - /// Simulate latency by holding packets for random time. (Works only in DEBUG mode) - /// - public bool SimulateLatency = false; - - /// - /// Chance of packet loss when simulation enabled. value in percents (1 - 100). - /// - public int SimulationPacketLossChance = 10; - - /// - /// Minimum simulated latency - /// - public int SimulationMinLatency = 30; - - /// - /// Maximum simulated latency - /// - public int SimulationMaxLatency = 100; - - /// - /// Experimental feature. Events automatically will be called without PollEvents method from another thread - /// - public bool UnsyncedEvents = false; - - /// - /// If true - delivery event will be called from "receive" thread otherwise on PollEvents call - /// - public bool UnsyncedDeliveryEvent = false; - - /// - /// Allows receive broadcast packets - /// - public bool BroadcastReceiveEnabled = false; - - /// - /// Delay between initial connection attempts - /// - public int ReconnectDelay = 500; - - /// - /// Maximum connection attempts before client stops and call disconnect event. - /// - public int MaxConnectAttempts = 10; - - /// - /// Enables socket option "ReuseAddress" for specific purposes - /// - public bool ReuseAddress = false; - - /// - /// Statistics of all connections - /// - public readonly NetStatistics Statistics; - - /// - /// Toggles the collection of network statistics for the instance and all known peers - /// - public bool EnableStatistics = false; - - /// - /// NatPunchModule for NAT hole punching operations - /// - public readonly NatPunchModule NatPunchModule; - - /// - /// Returns true if socket listening and update thread is running - /// - public bool IsRunning { get { return _socket.IsRunning; } } - - /// - /// Local EndPoint (host and port) - /// - public int LocalPort { get { return _socket.LocalPort; } } - - /// - /// Automatically recycle NetPacketReader after OnReceive event - /// - public bool AutoRecycle; - - /// - /// IPv6 support - /// - public IPv6Mode IPv6Enabled = IPv6Mode.SeparateSocket; - - /// - /// First peer. Useful for Client mode - /// - public NetPeer FirstPeer - { - get { return _headPeer; } - } - - /// - /// QoS channel count per message type (value must be between 1 and 64 channels) - /// - public byte ChannelsCount - { - get { return _channelsCount; } - set - { - if (value < 1 || value > 64) - throw new ArgumentException("Channels count must be between 1 and 64"); - _channelsCount = value; - } - } - - /// - /// Returns connected peers list (with internal cached list) - /// - public List ConnectedPeerList - { - get - { - GetPeersNonAlloc(_connectedPeerListCache, ConnectionState.Connected); - return _connectedPeerListCache; - } - } - - /// - /// Gets peer by peer id - /// - /// id of peer - /// Peer if peer with id exist, otherwise null - public NetPeer GetPeerById(int id) - { - return _peersArray[id]; - } - - /// - /// Returns connected peers count - /// - public int ConnectedPeersCount { get { return _connectedPeersCount; } } - - public int ExtraPacketSizeForLayer - { - get { return _extraPacketLayer != null ? _extraPacketLayer.ExtraPacketSizeForLayer : 0; } - } - - private bool TryGetPeer(IPEndPoint endPoint, out NetPeer peer) - { - _peersLock.EnterReadLock(); - bool result = _peersDict.TryGetValue(endPoint, out peer); - _peersLock.ExitReadLock(); - return result; - } - - private void AddPeer(NetPeer peer) - { - _peersLock.EnterWriteLock(); - if (_headPeer != null) - { - peer.NextPeer = _headPeer; - _headPeer.PrevPeer = peer; - } - _headPeer = peer; - _peersDict.Add(peer.EndPoint, peer); - if (peer.Id >= _peersArray.Length) - { - int newSize = _peersArray.Length * 2; - while (peer.Id >= newSize) - newSize *= 2; - Array.Resize(ref _peersArray, newSize); - } - _peersArray[peer.Id] = peer; - _peersLock.ExitWriteLock(); - } - - private void RemovePeer(NetPeer peer) - { - _peersLock.EnterWriteLock(); - RemovePeerInternal(peer); - _peersLock.ExitWriteLock(); - } - - private void RemovePeerInternal(NetPeer peer) - { - if (!_peersDict.Remove(peer.EndPoint)) - return; - if (peer == _headPeer) - _headPeer = peer.NextPeer; - - if (peer.PrevPeer != null) - peer.PrevPeer.NextPeer = peer.NextPeer; - if (peer.NextPeer != null) - peer.NextPeer.PrevPeer = peer.PrevPeer; - peer.PrevPeer = null; - - _peersArray[peer.Id] = null; - lock (_peerIds) - _peerIds.Enqueue(peer.Id); - } - - /// - /// NetManager constructor - /// - /// Network events listener (also can implement IDeliveryEventListener) - /// Extra processing of packages, like CRC checksum or encryption. All connected NetManagers must have same layer. - public NetManager(INetEventListener listener, PacketLayerBase extraPacketLayer = null) - { - _socket = new NetSocket(this); - _netEventListener = listener; - _deliveryEventListener = listener as IDeliveryEventListener; - _netEventsQueue = new Queue(); - _netEventsPool = new Stack(); - NetPacketPool = new NetPacketPool(); - NatPunchModule = new NatPunchModule(_socket); - Statistics = new NetStatistics(); - _connectedPeerListCache = new List(); - _peersDict = new Dictionary(new IPEndPointComparer()); - _requestsDict = new Dictionary(new IPEndPointComparer()); - _peersLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); - _peerIds = new Queue(); - _peersArray = new NetPeer[32]; - _extraPacketLayer = extraPacketLayer; - } - - internal void ConnectionLatencyUpdated(NetPeer fromPeer, int latency) - { - CreateEvent(NetEvent.EType.ConnectionLatencyUpdated, fromPeer, latency: latency); - } - - internal void MessageDelivered(NetPeer fromPeer, object userData) - { - if(_deliveryEventListener != null) - CreateEvent(NetEvent.EType.MessageDelivered, fromPeer, userData: userData); - } - - internal int SendRawAndRecycle(NetPacket packet, IPEndPoint remoteEndPoint) - { - var result = SendRaw(packet.RawData, 0, packet.Size, remoteEndPoint); - NetPacketPool.Recycle(packet); - return result; - } - - internal int SendRaw(NetPacket packet, IPEndPoint remoteEndPoint) - { - return SendRaw(packet.RawData, 0, packet.Size, remoteEndPoint); - } - - internal int SendRaw(byte[] message, int start, int length, IPEndPoint remoteEndPoint) - { - if (!_socket.IsRunning) - return 0; - - SocketError errorCode = 0; - int result; - if (_extraPacketLayer != null) - { - var expandedPacket = NetPacketPool.GetPacket(length + _extraPacketLayer.ExtraPacketSizeForLayer); - Buffer.BlockCopy(message, start, expandedPacket.RawData, 0, length); - int newStart = 0; - _extraPacketLayer.ProcessOutBoundPacket(ref expandedPacket.RawData, ref newStart, ref length); - result = _socket.SendTo(expandedPacket.RawData, newStart, length, remoteEndPoint, ref errorCode); - NetPacketPool.Recycle(expandedPacket); - } - else - { - result = _socket.SendTo(message, start, length, remoteEndPoint, ref errorCode); - } - - NetPeer fromPeer; - switch (errorCode) - { - case SocketError.MessageSize: - NetDebug.Write(NetLogLevel.Trace, "[SRD] 10040, datalen: {0}", length); - return -1; - case SocketError.HostUnreachable: - if (TryGetPeer(remoteEndPoint, out fromPeer)) - DisconnectPeerForce(fromPeer, DisconnectReason.HostUnreachable, errorCode, null); - CreateEvent(NetEvent.EType.Error, remoteEndPoint: remoteEndPoint, errorCode: errorCode); - return -1; - case SocketError.NetworkUnreachable: - if (TryGetPeer(remoteEndPoint, out fromPeer)) - DisconnectPeerForce(fromPeer, DisconnectReason.NetworkUnreachable, errorCode, null); - CreateEvent(NetEvent.EType.Error, remoteEndPoint: remoteEndPoint, errorCode: errorCode); - return -1; - } - if (result <= 0) - return 0; - - if (EnableStatistics) - { - Statistics.PacketsSent++; - Statistics.BytesSent += (uint)length; - } - - return result; - } - - internal void DisconnectPeerForce(NetPeer peer, - DisconnectReason reason, - SocketError socketErrorCode, - NetPacket eventData) - { - DisconnectPeer(peer, reason, socketErrorCode, true, null, 0, 0, eventData); - } - - private void DisconnectPeer( - NetPeer peer, - DisconnectReason reason, - SocketError socketErrorCode, - bool force, - byte[] data, - int start, - int count, - NetPacket eventData) - { - var shutdownResult = peer.Shutdown(data, start, count, force); - if (shutdownResult == ShutdownResult.None) - return; - if(shutdownResult == ShutdownResult.WasConnected) - _connectedPeersCount--; - CreateEvent( - NetEvent.EType.Disconnect, - peer, - errorCode: socketErrorCode, - disconnectReason: reason, - readerSource: eventData); - } - - private void CreateEvent( - NetEvent.EType type, - NetPeer peer = null, - IPEndPoint remoteEndPoint = null, - SocketError errorCode = 0, - int latency = 0, - DisconnectReason disconnectReason = DisconnectReason.ConnectionFailed, - ConnectionRequest connectionRequest = null, - DeliveryMethod deliveryMethod = DeliveryMethod.Unreliable, - NetPacket readerSource = null, - object userData = null) - { - NetEvent evt; - bool unsyncEvent = UnsyncedEvents; - - if (type == NetEvent.EType.Connect) - _connectedPeersCount++; - else if (type == NetEvent.EType.MessageDelivered) - unsyncEvent = UnsyncedDeliveryEvent; - - lock (_netEventsPool) - { - evt = _netEventsPool.Count > 0 ? _netEventsPool.Pop() : new NetEvent(this); - } - evt.Type = type; - evt.DataReader.SetSource(readerSource); - evt.Peer = peer; - evt.RemoteEndPoint = remoteEndPoint; - evt.Latency = latency; - evt.ErrorCode = errorCode; - evt.DisconnectReason = disconnectReason; - evt.ConnectionRequest = connectionRequest; - evt.DeliveryMethod = deliveryMethod; - evt.UserData = userData; - - if (unsyncEvent) - { - ProcessEvent(evt); - } - else - { - lock (_netEventsQueue) - _netEventsQueue.Enqueue(evt); - } - } - - private void ProcessEvent(NetEvent evt) - { - NetDebug.Write("[NM] Processing event: " + evt.Type); - bool emptyData = evt.DataReader.IsNull; - switch (evt.Type) - { - case NetEvent.EType.Connect: - _netEventListener.OnPeerConnected(evt.Peer); - break; - case NetEvent.EType.Disconnect: - var info = new DisconnectInfo - { - Reason = evt.DisconnectReason, - AdditionalData = evt.DataReader, - SocketErrorCode = evt.ErrorCode - }; - _netEventListener.OnPeerDisconnected(evt.Peer, info); - break; - case NetEvent.EType.Receive: - _netEventListener.OnNetworkReceive(evt.Peer, evt.DataReader, evt.DeliveryMethod); - break; - case NetEvent.EType.ReceiveUnconnected: - _netEventListener.OnNetworkReceiveUnconnected(evt.RemoteEndPoint, evt.DataReader, UnconnectedMessageType.BasicMessage); - break; - case NetEvent.EType.Broadcast: - _netEventListener.OnNetworkReceiveUnconnected(evt.RemoteEndPoint, evt.DataReader, UnconnectedMessageType.Broadcast); - break; - case NetEvent.EType.Error: - _netEventListener.OnNetworkError(evt.RemoteEndPoint, evt.ErrorCode); - break; - case NetEvent.EType.ConnectionLatencyUpdated: - _netEventListener.OnNetworkLatencyUpdate(evt.Peer, evt.Latency); - break; - case NetEvent.EType.ConnectionRequest: - _netEventListener.OnConnectionRequest(evt.ConnectionRequest); - break; - case NetEvent.EType.MessageDelivered: - _deliveryEventListener.OnMessageDelivered(evt.Peer, evt.UserData); - break; - } - //Recycle if not message - if (emptyData) - RecycleEvent(evt); - else if (AutoRecycle) - evt.DataReader.RecycleInternal(); - } - - internal void RecycleEvent(NetEvent evt) - { - evt.Peer = null; - evt.ErrorCode = 0; - evt.RemoteEndPoint = null; - evt.ConnectionRequest = null; - lock (_netEventsPool) - _netEventsPool.Push(evt); - } - - //Update function - private void UpdateLogic() - { - var peersToRemove = new List(); - var stopwatch = new Stopwatch(); - stopwatch.Start(); - - while (_socket.IsRunning) - { -#if DEBUG - if (SimulateLatency) - { - var time = DateTime.UtcNow; - lock (_pingSimulationList) - { - for (int i = 0; i < _pingSimulationList.Count; i++) - { - var incomingData = _pingSimulationList[i]; - if (incomingData.TimeWhenGet <= time) - { - DataReceived(incomingData.Data, incomingData.Data.Length, incomingData.EndPoint); - _pingSimulationList.RemoveAt(i); - i--; - } - } - } - } -#endif - - ulong totalPacketLoss = 0; - - int elapsed = (int)stopwatch.ElapsedMilliseconds; - elapsed = elapsed <= 0 ? 1 : elapsed; - stopwatch.Reset(); - stopwatch.Start(); - - for (var netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) - { - if (netPeer.ConnectionState == ConnectionState.Disconnected && netPeer.TimeSinceLastPacket > DisconnectTimeout) - { - peersToRemove.Add(netPeer); - } - else - { - netPeer.Update(elapsed); - - if (EnableStatistics) - { - totalPacketLoss += netPeer.Statistics.PacketLoss; - } - } - } - if (peersToRemove.Count > 0) - { - _peersLock.EnterWriteLock(); - for (int i = 0; i < peersToRemove.Count; i++) - RemovePeerInternal(peersToRemove[i]); - _peersLock.ExitWriteLock(); - peersToRemove.Clear(); - } - - if (EnableStatistics) - { - Statistics.PacketLoss = totalPacketLoss; - } - - int sleepTime = UpdateTime - (int)stopwatch.ElapsedMilliseconds; - if (sleepTime > 0) - Thread.Sleep(sleepTime); - } - stopwatch.Stop(); - } - - void INetSocketListener.OnMessageReceived(byte[] data, int length, SocketError errorCode, IPEndPoint remoteEndPoint) - { - if (errorCode != 0) - { - CreateEvent(NetEvent.EType.Error, errorCode: errorCode); - NetDebug.WriteError("[NM] Receive error: {0}", errorCode); - return; - } -#if DEBUG - if (SimulatePacketLoss && _randomGenerator.NextDouble() * 100 < SimulationPacketLossChance) - { - //drop packet - return; - } - if (SimulateLatency) - { - int latency = _randomGenerator.Next(SimulationMinLatency, SimulationMaxLatency); - if (latency > MinLatencyThreshold) - { - byte[] holdedData = new byte[length]; - Buffer.BlockCopy(data, 0, holdedData, 0, length); - - lock (_pingSimulationList) - { - _pingSimulationList.Add(new IncomingData - { - Data = holdedData, - EndPoint = remoteEndPoint, - TimeWhenGet = DateTime.UtcNow.AddMilliseconds(latency) - }); - } - //hold packet - return; - } - } -#endif - try - { - //ProcessEvents - DataReceived(data, length, remoteEndPoint); - } - catch(Exception e) - { - //protects socket receive thread - NetDebug.WriteError("[NM] SocketReceiveThread error: " + e ); - } - } - - internal NetPeer OnConnectionSolved(ConnectionRequest request, byte[] rejectData, int start, int length) - { - NetPeer netPeer = null; - - if (request.Result == ConnectionRequestResult.RejectForce) - { - NetDebug.Write(NetLogLevel.Trace, "[NM] Peer connect reject force."); - if (rejectData != null && length > 0) - { - var shutdownPacket = NetPacketPool.GetWithProperty(PacketProperty.Disconnect, length); - shutdownPacket.ConnectionNumber = request.ConnectionNumber; - FastBitConverter.GetBytes(shutdownPacket.RawData, 1, request.ConnectionTime); - if (shutdownPacket.Size >= NetConstants.PossibleMtu[0]) - NetDebug.WriteError("[Peer] Disconnect additional data size more than MTU!"); - else - Buffer.BlockCopy(rejectData, start, shutdownPacket.RawData, 9, length); - SendRawAndRecycle(shutdownPacket, request.RemoteEndPoint); - } - } - else - { - _peersLock.EnterUpgradeableReadLock(); - if (_peersDict.TryGetValue(request.RemoteEndPoint, out netPeer)) - { - //already have peer - _peersLock.ExitUpgradeableReadLock(); - } - else if (request.Result == ConnectionRequestResult.Reject) - { - netPeer = new NetPeer(this, request.RemoteEndPoint, GetNextPeerId()); - netPeer.Reject(request.ConnectionTime, request.ConnectionNumber, rejectData, start, length); - AddPeer(netPeer); - _peersLock.ExitUpgradeableReadLock(); - NetDebug.Write(NetLogLevel.Trace, "[NM] Peer connect reject."); - } - else //Accept - { - netPeer = new NetPeer(this, request.RemoteEndPoint, GetNextPeerId(), request.ConnectionTime, request.ConnectionNumber); - AddPeer(netPeer); - _peersLock.ExitUpgradeableReadLock(); - CreateEvent(NetEvent.EType.Connect, netPeer); - NetDebug.Write(NetLogLevel.Trace, "[NM] Received peer connection Id: {0}, EP: {1}", - netPeer.ConnectTime, netPeer.EndPoint); - } - } - - lock(_requestsDict) - _requestsDict.Remove(request.RemoteEndPoint); - - return netPeer; - } - - private int GetNextPeerId() - { - lock (_peerIds) - return _peerIds.Count == 0 ? _lastPeerId++ : _peerIds.Dequeue(); - } - - private void ProcessConnectRequest( - IPEndPoint remoteEndPoint, - NetPeer netPeer, - NetConnectRequestPacket connRequest) - { - byte connectionNumber = connRequest.ConnectionNumber; - ConnectionRequest req; - - //if we have peer - if (netPeer != null) - { - var processResult = netPeer.ProcessConnectRequest(connRequest); - NetDebug.Write("ConnectRequest LastId: {0}, NewId: {1}, EP: {2}, Result: {3}", - netPeer.ConnectTime, - connRequest.ConnectionTime, - remoteEndPoint, - processResult); - - switch (processResult) - { - case ConnectRequestResult.Reconnection: - DisconnectPeerForce(netPeer, DisconnectReason.Reconnect, 0, null); - RemovePeer(netPeer); - //go to new connection - break; - case ConnectRequestResult.NewConnection: - RemovePeer(netPeer); - //go to new connection - break; - case ConnectRequestResult.P2PLose: - DisconnectPeerForce(netPeer, DisconnectReason.PeerToPeerConnection, 0, null); - RemovePeer(netPeer); - //go to new connection - break; - default: - //no operations needed - return; - } - //ConnectRequestResult.NewConnection - //Set next connection number - if(processResult != ConnectRequestResult.P2PLose) - connectionNumber = (byte)((netPeer.ConnectionNum + 1) % NetConstants.MaxConnectionNumber); - //To reconnect peer - } - else - { - NetDebug.Write("ConnectRequest Id: {0}, EP: {1}", connRequest.ConnectionTime, remoteEndPoint); - } - - lock (_requestsDict) - { - if (_requestsDict.TryGetValue(remoteEndPoint, out req)) - { - req.UpdateRequest(connRequest); - return; - } - req = new ConnectionRequest( - connRequest.ConnectionTime, - connectionNumber, - connRequest.Data, - remoteEndPoint, - this); - _requestsDict.Add(remoteEndPoint, req); - } - NetDebug.Write("[NM] Creating request event: " + connRequest.ConnectionTime); - CreateEvent(NetEvent.EType.ConnectionRequest, connectionRequest: req); - } - - private void DataReceived(byte[] reusableBuffer, int count, IPEndPoint remoteEndPoint) - { - if (EnableStatistics) - { - Statistics.PacketsReceived++; - Statistics.BytesReceived += (uint)count; - } - - if (_extraPacketLayer != null) - { - _extraPacketLayer.ProcessInboundPacket(ref reusableBuffer, ref count); - if (count == 0) - return; - } - - //empty packet - if (reusableBuffer[0] == (byte) PacketProperty.Empty) - return; - - //Try read packet - NetPacket packet = NetPacketPool.GetPacket(count); - if (!packet.FromBytes(reusableBuffer, 0, count)) - { - NetPacketPool.Recycle(packet); - NetDebug.WriteError("[NM] DataReceived: bad!"); - return; - } - - switch (packet.Property) - { - //special case connect request - case PacketProperty.ConnectRequest: - if (NetConnectRequestPacket.GetProtocolId(packet) != NetConstants.ProtocolId) - { - SendRawAndRecycle(NetPacketPool.GetWithProperty(PacketProperty.InvalidProtocol), remoteEndPoint); - return; - } - break; - //unconnected messages - case PacketProperty.Broadcast: - if (!BroadcastReceiveEnabled) - return; - CreateEvent(NetEvent.EType.Broadcast, remoteEndPoint: remoteEndPoint, readerSource: packet); - return; - case PacketProperty.UnconnectedMessage: - if (!UnconnectedMessagesEnabled) - return; - CreateEvent(NetEvent.EType.ReceiveUnconnected, remoteEndPoint: remoteEndPoint, readerSource: packet); - return; - case PacketProperty.NatMessage: - if (NatPunchEnabled) - NatPunchModule.ProcessMessage(remoteEndPoint, packet); - return; - } - - //Check normal packets - NetPeer netPeer; - _peersLock.EnterReadLock(); - bool peerFound = _peersDict.TryGetValue(remoteEndPoint, out netPeer); - _peersLock.ExitReadLock(); - - switch (packet.Property) - { - case PacketProperty.ConnectRequest: - var connRequest = NetConnectRequestPacket.FromData(packet); - if (connRequest != null) - ProcessConnectRequest(remoteEndPoint, netPeer, connRequest); - break; - case PacketProperty.PeerNotFound: - if (peerFound) - { - if (netPeer.ConnectionState != ConnectionState.Connected) - return; - if (packet.Size == 1) - { - //first reply - var p = NetPacketPool.GetWithProperty(PacketProperty.PeerNotFound, 9); - p.RawData[1] = 0; - FastBitConverter.GetBytes(p.RawData, 2, netPeer.ConnectTime); - SendRawAndRecycle(p, remoteEndPoint); - NetDebug.Write("PeerNotFound sending connectTime: {0}", netPeer.ConnectTime); - } - else if (packet.Size == 10 && packet.RawData[1] == 1 && BitConverter.ToInt64(packet.RawData, 2) == netPeer.ConnectTime) - { - //second reply - NetDebug.Write("PeerNotFound received our connectTime: {0}", netPeer.ConnectTime); - DisconnectPeerForce(netPeer, DisconnectReason.RemoteConnectionClose, 0, null); - } - } - else if (packet.Size == 10 && packet.RawData[1] == 0) - { - //send reply back - packet.RawData[1] = 1; - SendRawAndRecycle(packet, remoteEndPoint); - } - break; - case PacketProperty.InvalidProtocol: - if (peerFound && netPeer.ConnectionState == ConnectionState.Outgoing) - DisconnectPeerForce(netPeer, DisconnectReason.InvalidProtocol, 0, null); - break; - case PacketProperty.Disconnect: - if (peerFound) - { - var disconnectResult = netPeer.ProcessDisconnect(packet); - if (disconnectResult == DisconnectResult.None) - { - NetPacketPool.Recycle(packet); - return; - } - DisconnectPeerForce( - netPeer, - disconnectResult == DisconnectResult.Disconnect - ? DisconnectReason.RemoteConnectionClose - : DisconnectReason.ConnectionRejected, - 0, packet); - } - else - { - NetPacketPool.Recycle(packet); - } - //Send shutdown - SendRawAndRecycle(NetPacketPool.GetWithProperty(PacketProperty.ShutdownOk), remoteEndPoint); - break; - case PacketProperty.ConnectAccept: - if (!peerFound) - return; - var connAccept = NetConnectAcceptPacket.FromData(packet); - if (connAccept != null && netPeer.ProcessConnectAccept(connAccept)) - CreateEvent(NetEvent.EType.Connect, netPeer); - break; - default: - if(peerFound) - netPeer.ProcessPacket(packet); - else - SendRawAndRecycle(NetPacketPool.GetWithProperty(PacketProperty.PeerNotFound), remoteEndPoint); - break; - } - } - - internal void CreateReceiveEvent(NetPacket packet, DeliveryMethod method, NetPeer fromPeer) - { - NetEvent evt; - lock (_netEventsPool) - { - evt = _netEventsPool.Count > 0 ? _netEventsPool.Pop() : new NetEvent(this); - } - evt.Type = NetEvent.EType.Receive; - evt.DataReader.SetSource(packet); - evt.Peer = fromPeer; - evt.DeliveryMethod = method; - if (UnsyncedEvents) - { - ProcessEvent(evt); - } - else - { - lock (_netEventsQueue) - _netEventsQueue.Enqueue(evt); - } - } - - /// - /// Send data to all connected peers (channel - 0) - /// - /// DataWriter with data - /// Send options (reliable, unreliable, etc.) - public void SendToAll(NetDataWriter writer, DeliveryMethod options) - { - SendToAll(writer.Data, 0, writer.Length, options); - } - - /// - /// Send data to all connected peers (channel - 0) - /// - /// Data - /// Send options (reliable, unreliable, etc.) - public void SendToAll(byte[] data, DeliveryMethod options) - { - SendToAll(data, 0, data.Length, options); - } - - /// - /// Send data to all connected peers (channel - 0) - /// - /// Data - /// Start of data - /// Length of data - /// Send options (reliable, unreliable, etc.) - public void SendToAll(byte[] data, int start, int length, DeliveryMethod options) - { - SendToAll(data, start, length, 0, options); - } - - /// - /// Send data to all connected peers - /// - /// DataWriter with data - /// Number of channel (from 0 to channelsCount - 1) - /// Send options (reliable, unreliable, etc.) - public void SendToAll(NetDataWriter writer, byte channelNumber, DeliveryMethod options) - { - SendToAll(writer.Data, 0, writer.Length, channelNumber, options); - } - - /// - /// Send data to all connected peers - /// - /// Data - /// Number of channel (from 0 to channelsCount - 1) - /// Send options (reliable, unreliable, etc.) - public void SendToAll(byte[] data, byte channelNumber, DeliveryMethod options) - { - SendToAll(data, 0, data.Length, channelNumber, options); - } - - /// - /// Send data to all connected peers - /// - /// Data - /// Start of data - /// Length of data - /// Number of channel (from 0 to channelsCount - 1) - /// Send options (reliable, unreliable, etc.) - public void SendToAll(byte[] data, int start, int length, byte channelNumber, DeliveryMethod options) - { - try - { - _peersLock.EnterReadLock(); - for (var netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) - netPeer.Send(data, start, length, channelNumber, options); - } - finally - { - _peersLock.ExitReadLock(); - } - } - - /// - /// Send data to all connected peers (channel - 0) - /// - /// DataWriter with data - /// Send options (reliable, unreliable, etc.) - /// Excluded peer - public void SendToAll(NetDataWriter writer, DeliveryMethod options, NetPeer excludePeer) - { - SendToAll(writer.Data, 0, writer.Length, 0, options, excludePeer); - } - - /// - /// Send data to all connected peers (channel - 0) - /// - /// Data - /// Send options (reliable, unreliable, etc.) - /// Excluded peer - public void SendToAll(byte[] data, DeliveryMethod options, NetPeer excludePeer) - { - SendToAll(data, 0, data.Length, 0, options, excludePeer); - } - - /// - /// Send data to all connected peers (channel - 0) - /// - /// Data - /// Start of data - /// Length of data - /// Send options (reliable, unreliable, etc.) - /// Excluded peer - public void SendToAll(byte[] data, int start, int length, DeliveryMethod options, NetPeer excludePeer) - { - SendToAll(data, start, length, 0, options, excludePeer); - } - - /// - /// Send data to all connected peers - /// - /// DataWriter with data - /// Number of channel (from 0 to channelsCount - 1) - /// Send options (reliable, unreliable, etc.) - /// Excluded peer - public void SendToAll(NetDataWriter writer, byte channelNumber, DeliveryMethod options, NetPeer excludePeer) - { - SendToAll(writer.Data, 0, writer.Length, channelNumber, options, excludePeer); - } - - /// - /// Send data to all connected peers - /// - /// Data - /// Number of channel (from 0 to channelsCount - 1) - /// Send options (reliable, unreliable, etc.) - /// Excluded peer - public void SendToAll(byte[] data, byte channelNumber, DeliveryMethod options, NetPeer excludePeer) - { - SendToAll(data, 0, data.Length, channelNumber, options, excludePeer); - } - - - /// - /// Send data to all connected peers - /// - /// Data - /// Start of data - /// Length of data - /// Number of channel (from 0 to channelsCount - 1) - /// Send options (reliable, unreliable, etc.) - /// Excluded peer - public void SendToAll(byte[] data, int start, int length, byte channelNumber, DeliveryMethod options, NetPeer excludePeer) - { - try - { - _peersLock.EnterReadLock(); - for (var netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) - { - if (netPeer != excludePeer) - netPeer.Send(data, start, length, channelNumber, options); - } - } - finally - { - _peersLock.ExitReadLock(); - } - } - - /// - /// Start logic thread and listening on available port - /// - public bool Start() - { - return Start(0); - } - - /// - /// Start logic thread and listening on selected port - /// - /// bind to specific ipv4 address - /// bind to specific ipv6 address - /// port to listen - public bool Start(IPAddress addressIPv4, IPAddress addressIPv6, int port) - { - if (!_socket.Bind(addressIPv4, addressIPv6, port, ReuseAddress, IPv6Enabled)) - return false; - _logicThread = new Thread(UpdateLogic) { Name = "LogicThread", IsBackground = true }; - _logicThread.Start(); - return true; - } - - /// - /// Start logic thread and listening on selected port - /// - /// bind to specific ipv4 address - /// bind to specific ipv6 address - /// port to listen - public bool Start(string addressIPv4, string addressIPv6, int port) - { - IPAddress ipv4 = NetUtils.ResolveAddress(addressIPv4); - IPAddress ipv6 = NetUtils.ResolveAddress(addressIPv6); - return Start(ipv4, ipv6, port); - } - - /// - /// Start logic thread and listening on selected port - /// - /// port to listen - public bool Start(int port) - { - return Start(IPAddress.Any, IPAddress.IPv6Any, port); - } - - /// - /// Send message without connection - /// - /// Raw data - /// Packet destination - /// Operation result - public bool SendUnconnectedMessage(byte[] message, IPEndPoint remoteEndPoint) - { - return SendUnconnectedMessage(message, 0, message.Length, remoteEndPoint); - } - - /// - /// Send message without connection - /// - /// Data serializer - /// Packet destination - /// Operation result - public bool SendUnconnectedMessage(NetDataWriter writer, IPEndPoint remoteEndPoint) - { - return SendUnconnectedMessage(writer.Data, 0, writer.Length, remoteEndPoint); - } - - /// - /// Send message without connection - /// - /// Raw data - /// data start - /// data length - /// Packet destination - /// Operation result - public bool SendUnconnectedMessage(byte[] message, int start, int length, IPEndPoint remoteEndPoint) - { - //No need for CRC here, SendRaw does that - NetPacket packet = NetPacketPool.GetWithData(PacketProperty.UnconnectedMessage, message, start, length); - return SendRawAndRecycle(packet, remoteEndPoint) > 0; - } - - public bool SendBroadcast(NetDataWriter writer, int port) - { - return SendBroadcast(writer.Data, 0, writer.Length, port); - } - - public bool SendBroadcast(byte[] data, int port) - { - return SendBroadcast(data, 0, data.Length, port); - } - - public bool SendBroadcast(byte[] data, int start, int length, int port) - { - NetPacket packet; - if (_extraPacketLayer != null) - { - var headerSize = NetPacket.GetHeaderSize(PacketProperty.Broadcast); - packet = NetPacketPool.GetPacket(headerSize + length + _extraPacketLayer.ExtraPacketSizeForLayer); - packet.Property = PacketProperty.Broadcast; - Buffer.BlockCopy(data, start, packet.RawData, headerSize, length); - var checksumComputeStart = 0; - int preCrcLength = length + headerSize; - _extraPacketLayer.ProcessOutBoundPacket(ref packet.RawData, ref checksumComputeStart, ref preCrcLength); - } - else - { - packet = NetPacketPool.GetWithData(PacketProperty.Broadcast, data, start, length); - } - - bool result = _socket.SendBroadcast(packet.RawData, 0, packet.Size, port); - NetPacketPool.Recycle(packet); - return result; - } - - /// - /// Flush all queued packets of all peers - /// - public void Flush() - { - for (var netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) - netPeer.Flush(); - } - - /// - /// Receive all pending events. Call this in game update code - /// - public void PollEvents() - { - if (UnsyncedEvents) - return; - int eventsCount = _netEventsQueue.Count; - for(int i = 0; i < eventsCount; i++) - { - NetEvent evt; - lock (_netEventsQueue) - evt = _netEventsQueue.Dequeue(); - ProcessEvent(evt); - } - } - - /// - /// Connect to remote host - /// - /// Server IP or hostname - /// Server Port - /// Connection key - /// New NetPeer if new connection, Old NetPeer if already connected - /// Manager is not running. Call - public NetPeer Connect(string address, int port, string key) - { - return Connect(address, port, NetDataWriter.FromString(key)); - } - - /// - /// Connect to remote host - /// - /// Server IP or hostname - /// Server Port - /// Additional data for remote peer - /// New NetPeer if new connection, Old NetPeer if already connected - /// Manager is not running. Call - public NetPeer Connect(string address, int port, NetDataWriter connectionData) - { - IPEndPoint ep; - try - { - ep = NetUtils.MakeEndPoint(address, port); - } - catch - { - CreateEvent(NetEvent.EType.Disconnect, disconnectReason: DisconnectReason.UnknownHost); - return null; - } - return Connect(ep, connectionData); - } - - /// - /// Connect to remote host - /// - /// Server end point (ip and port) - /// Connection key - /// New NetPeer if new connection, Old NetPeer if already connected - /// Manager is not running. Call - public NetPeer Connect(IPEndPoint target, string key) - { - return Connect(target, NetDataWriter.FromString(key)); - } - - /// - /// Connect to remote host - /// - /// Server end point (ip and port) - /// Additional data for remote peer - /// New NetPeer if new connection, Old NetPeer if already connected, null peer if there is ConnectionRequest awaiting - /// Manager is not running. Call - public NetPeer Connect(IPEndPoint target, NetDataWriter connectionData) - { - if (!_socket.IsRunning) - throw new InvalidOperationException("Client is not running"); - - NetPeer peer; - byte connectionNumber = 0; - - if (_requestsDict.ContainsKey(target)) - return null; - - _peersLock.EnterUpgradeableReadLock(); - if (_peersDict.TryGetValue(target, out peer)) - { - switch (peer.ConnectionState) - { - //just return already connected peer - case ConnectionState.Connected: - case ConnectionState.Outgoing: - _peersLock.ExitUpgradeableReadLock(); - return peer; - } - //else reconnect - connectionNumber = (byte)((peer.ConnectionNum + 1) % NetConstants.MaxConnectionNumber); - RemovePeer(peer); - } - - //Create reliable connection - //And send connection request - peer = new NetPeer(this, target, GetNextPeerId(), connectionNumber, connectionData); - AddPeer(peer); - _peersLock.ExitUpgradeableReadLock(); - - return peer; - } - - /// - /// Force closes connection and stop all threads. - /// - public void Stop() - { - Stop(true); - } - - /// - /// Force closes connection and stop all threads. - /// - /// Send disconnect messages - public void Stop(bool sendDisconnectMessages) - { - if (!_socket.IsRunning) - return; - NetDebug.Write("[NM] Stop"); - - //Send last disconnect - for(var netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) - netPeer.Shutdown(null, 0, 0, !sendDisconnectMessages); - - //Stop - _socket.Close(false); - _logicThread.Join(); - _logicThread = null; - - //clear peers - _peersLock.EnterWriteLock(); - _headPeer = null; - _peersDict.Clear(); - _peersArray = new NetPeer[32]; - _peersLock.ExitWriteLock(); - lock(_peerIds) - _peerIds.Clear(); -#if DEBUG - lock (_pingSimulationList) - _pingSimulationList.Clear(); -#endif - _connectedPeersCount = 0; - lock(_netEventsQueue) - _netEventsQueue.Clear(); - } - - /// - /// Return peers count with connection state - /// - /// peer connection state (you can use as bit flags) - /// peers count - public int GetPeersCount(ConnectionState peerState) - { - int count = 0; - _peersLock.EnterReadLock(); - for (var netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) - { - if ((netPeer.ConnectionState & peerState) != 0) - count++; - } - _peersLock.ExitReadLock(); - return count; - } - - /// - /// Get copy of peers (without allocations) - /// - /// List that will contain result - /// State of peers - public void GetPeersNonAlloc(List peers, ConnectionState peerState) - { - peers.Clear(); - _peersLock.EnterReadLock(); - for (var netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) - { - if ((netPeer.ConnectionState & peerState) != 0) - peers.Add(netPeer); - } - _peersLock.ExitReadLock(); - } - - /// - /// Disconnect all peers without any additional data - /// - public void DisconnectAll() - { - DisconnectAll(null, 0, 0); - } - - /// - /// Disconnect all peers with shutdown message - /// - /// Data to send (must be less or equal MTU) - /// Data start - /// Data count - public void DisconnectAll(byte[] data, int start, int count) - { - //Send disconnect packets - _peersLock.EnterReadLock(); - for (var netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) - { - DisconnectPeer( - netPeer, - DisconnectReason.DisconnectPeerCalled, - 0, - false, - data, - start, - count, - null); - } - _peersLock.ExitReadLock(); - } - - /// - /// Immediately disconnect peer from server without additional data - /// - /// peer to disconnect - public void DisconnectPeerForce(NetPeer peer) - { - DisconnectPeerForce(peer, DisconnectReason.DisconnectPeerCalled, 0, null); - } - - /// - /// Disconnect peer from server - /// - /// peer to disconnect - public void DisconnectPeer(NetPeer peer) - { - DisconnectPeer(peer, null, 0, 0); - } - - /// - /// Disconnect peer from server and send additional data (Size must be less or equal MTU - 8) - /// - /// peer to disconnect - /// additional data - public void DisconnectPeer(NetPeer peer, byte[] data) - { - DisconnectPeer(peer, data, 0, data.Length); - } - - /// - /// Disconnect peer from server and send additional data (Size must be less or equal MTU - 8) - /// - /// peer to disconnect - /// additional data - public void DisconnectPeer(NetPeer peer, NetDataWriter writer) - { - DisconnectPeer(peer, writer.Data, 0, writer.Length); - } - - /// - /// Disconnect peer from server and send additional data (Size must be less or equal MTU - 8) - /// - /// peer to disconnect - /// additional data - /// data start - /// data length - public void DisconnectPeer(NetPeer peer, byte[] data, int start, int count) - { - DisconnectPeer( - peer, - DisconnectReason.DisconnectPeerCalled, - 0, - false, - data, - start, - count, - null); - } - - public NetPeerEnumerator GetEnumerator() - { - return new NetPeerEnumerator(_headPeer); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return new NetPeerEnumerator(_headPeer); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return new NetPeerEnumerator(_headPeer); - } - } -} diff --git a/FirServer/Libraries/LiteNetLib/NetPacket.cs b/FirServer/Libraries/LiteNetLib/NetPacket.cs deleted file mode 100644 index c5569a95..00000000 --- a/FirServer/Libraries/LiteNetLib/NetPacket.cs +++ /dev/null @@ -1,255 +0,0 @@ -using System; -using System.Net; -using LiteNetLib.Utils; - -namespace LiteNetLib -{ - internal enum PacketProperty : byte - { - Unreliable, - Channeled, - Ack, - Ping, - Pong, - ConnectRequest, - ConnectAccept, - Disconnect, - UnconnectedMessage, - MtuCheck, - MtuOk, - Broadcast, - Merged, - ShutdownOk, - PeerNotFound, - InvalidProtocol, - NatMessage, - Empty, - } - - internal sealed class NetPacket - { - private static readonly int LastProperty = Enum.GetValues(typeof(PacketProperty)).Length; - //Header - public PacketProperty Property - { - get { return (PacketProperty)(RawData[0] & 0x1F); } - set { RawData[0] = (byte)((RawData[0] & 0xE0) | (byte)value); } - } - - public byte ConnectionNumber - { - get { return (byte)((RawData[0] & 0x60) >> 5); } - set { RawData[0] = (byte) ((RawData[0] & 0x9F) | (value << 5)); } - } - - public ushort Sequence - { - get { return BitConverter.ToUInt16(RawData, 1); } - set { FastBitConverter.GetBytes(RawData, 1, value); } - } - - public bool IsFragmented - { - get { return (RawData[0] & 0x80) != 0; } - } - - public void MarkFragmented() - { - RawData[0] |= 0x80; //set first bit - } - - public byte ChannelId - { - get { return RawData[3]; } - set { RawData[3] = value; } - } - - public ushort FragmentId - { - get { return BitConverter.ToUInt16(RawData, 4); } - set { FastBitConverter.GetBytes(RawData, 4, value); } - } - - public ushort FragmentPart - { - get { return BitConverter.ToUInt16(RawData, 6); } - set { FastBitConverter.GetBytes(RawData, 6, value); } - } - - public ushort FragmentsTotal - { - get { return BitConverter.ToUInt16(RawData, 8); } - set { FastBitConverter.GetBytes(RawData, 8, value); } - } - - //Data - public byte[] RawData; - public int Size; - - //Delivery - public object UserData; - - public NetPacket(int size) - { - RawData = new byte[size]; - Size = size; - } - - public NetPacket(PacketProperty property, int size) - { - size += GetHeaderSize(property); - RawData = new byte[size]; - Property = property; - Size = size; - } - - public static int GetHeaderSize(PacketProperty property) - { - switch (property) - { - case PacketProperty.Channeled: - case PacketProperty.Ack: - return NetConstants.ChanneledHeaderSize; - case PacketProperty.Ping: - return NetConstants.HeaderSize + 2; - case PacketProperty.ConnectRequest: - return NetConnectRequestPacket.HeaderSize; - case PacketProperty.ConnectAccept: - return NetConnectAcceptPacket.Size; - case PacketProperty.Disconnect: - return NetConstants.HeaderSize + 8; - case PacketProperty.Pong: - return NetConstants.HeaderSize + 10; - default: - return NetConstants.HeaderSize; - } - } - - public int GetHeaderSize() - { - return GetHeaderSize(Property); - } - - //Packet constructor from byte array - public bool FromBytes(byte[] data, int start, int packetSize) - { - //Reading property - byte property = (byte)(data[start] & 0x1F); - bool fragmented = (data[start] & 0x80) != 0; - int headerSize = GetHeaderSize((PacketProperty) property); - - if (property > LastProperty || packetSize < headerSize || - (fragmented && packetSize < headerSize + NetConstants.FragmentHeaderSize) || - data.Length < start + packetSize) - { - return false; - } - - Buffer.BlockCopy(data, start, RawData, 0, packetSize); - Size = (ushort)packetSize; - return true; - } - } - - internal sealed class NetConnectRequestPacket - { - public const int HeaderSize = 14; - public readonly long ConnectionTime; - public readonly byte ConnectionNumber; - public readonly byte[] TargetAddress; - public readonly NetDataReader Data; - - private NetConnectRequestPacket(long connectionTime, byte connectionNumber, byte[] targetAddress, NetDataReader data) - { - ConnectionTime = connectionTime; - ConnectionNumber = connectionNumber; - TargetAddress = targetAddress; - Data = data; - } - - public static int GetProtocolId(NetPacket packet) - { - return BitConverter.ToInt32(packet.RawData, 1); - } - - public static NetConnectRequestPacket FromData(NetPacket packet) - { - if (packet.ConnectionNumber >= NetConstants.MaxConnectionNumber) - return null; - - //Getting new id for peer - long connectionId = BitConverter.ToInt64(packet.RawData, 5); - - //Get target address - int addrSize = packet.RawData[13]; - if (addrSize != 16 && addrSize != 28) - return null; - byte[] addressBytes = new byte[addrSize]; - Buffer.BlockCopy(packet.RawData, 14, addressBytes, 0, addrSize); - - // Read data and create request - var reader = new NetDataReader(null, 0, 0); - if (packet.Size > HeaderSize+addrSize) - reader.SetSource(packet.RawData, HeaderSize + addrSize, packet.Size); - - return new NetConnectRequestPacket(connectionId, packet.ConnectionNumber, addressBytes, reader); - } - - public static NetPacket Make(NetDataWriter connectData, SocketAddress addressBytes, long connectId) - { - //Make initial packet - var packet = new NetPacket(PacketProperty.ConnectRequest, connectData.Length+addressBytes.Size); - - //Add data - FastBitConverter.GetBytes(packet.RawData, 1, NetConstants.ProtocolId); - FastBitConverter.GetBytes(packet.RawData, 5, connectId); - packet.RawData[13] = (byte)addressBytes.Size; - for (int i = 0; i < addressBytes.Size; i++) - packet.RawData[14+i] = addressBytes[i]; - Buffer.BlockCopy(connectData.Data, 0, packet.RawData, 14+addressBytes.Size, connectData.Length); - return packet; - } - } - - internal sealed class NetConnectAcceptPacket - { - public const int Size = 11; - public readonly long ConnectionId; - public readonly byte ConnectionNumber; - public readonly bool IsReusedPeer; - - private NetConnectAcceptPacket(long connectionId, byte connectionNumber, bool isReusedPeer) - { - ConnectionId = connectionId; - ConnectionNumber = connectionNumber; - IsReusedPeer = isReusedPeer; - } - - public static NetConnectAcceptPacket FromData(NetPacket packet) - { - if (packet.Size > Size) - return null; - - long connectionId = BitConverter.ToInt64(packet.RawData, 1); - //check connect num - byte connectionNumber = packet.RawData[9]; - if (connectionNumber >= NetConstants.MaxConnectionNumber) - return null; - //check reused flag - byte isReused = packet.RawData[10]; - if (isReused > 1) - return null; - - return new NetConnectAcceptPacket(connectionId, connectionNumber, isReused == 1); - } - - public static NetPacket Make(long connectId, byte connectNum, bool reusedPeer) - { - var packet = new NetPacket(PacketProperty.ConnectAccept, 0); - FastBitConverter.GetBytes(packet.RawData, 1, connectId); - packet.RawData[9] = connectNum; - packet.RawData[10] = (byte)(reusedPeer ? 1 : 0); - return packet; - } - } -} diff --git a/FirServer/Libraries/LiteNetLib/NetPacketPool.cs b/FirServer/Libraries/LiteNetLib/NetPacketPool.cs deleted file mode 100644 index cd951703..00000000 --- a/FirServer/Libraries/LiteNetLib/NetPacketPool.cs +++ /dev/null @@ -1,86 +0,0 @@ -using System; -using System.Threading; - -namespace LiteNetLib -{ - internal sealed class NetPacketPool - { - private readonly NetPacket[] _pool = new NetPacket[NetConstants.PacketPoolSize]; - private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); - private int _count; - - public NetPacket GetWithData(PacketProperty property, byte[] data, int start, int length) - { - int headerSize = NetPacket.GetHeaderSize(property); - NetPacket packet = GetPacket(length + headerSize); - packet.Property = property; - Buffer.BlockCopy(data, start, packet.RawData, headerSize, length); - return packet; - } - - //Get packet with size - public NetPacket GetWithProperty(PacketProperty property, int size) - { - NetPacket packet = GetPacket(size + NetPacket.GetHeaderSize(property)); - packet.Property = property; - return packet; - } - - public NetPacket GetWithProperty(PacketProperty property) - { - NetPacket packet = GetPacket(NetPacket.GetHeaderSize(property)); - packet.Property = property; - return packet; - } - - public NetPacket GetPacket(int size) - { - if (size <= NetConstants.MaxPacketSize) - { - NetPacket packet = null; - _lock.EnterUpgradeableReadLock(); - if (_count > 0) - { - _lock.EnterWriteLock(); - _count--; - packet = _pool[_count]; - _pool[_count] = null; - _lock.ExitWriteLock(); - } - _lock.ExitUpgradeableReadLock(); - if (packet != null) - { - packet.Size = size; - if (packet.RawData.Length < size) - packet.RawData = new byte[size]; - return packet; - } - } - return new NetPacket(size); - } - - public void Recycle(NetPacket packet) - { - if (packet.RawData.Length > NetConstants.MaxPacketSize) - { - //Don't pool big packets. Save memory - return; - } - - //Clean fragmented flag - packet.RawData[0] = 0; - - _lock.EnterUpgradeableReadLock(); - if (_count == NetConstants.PacketPoolSize) - { - _lock.ExitUpgradeableReadLock(); - return; - } - _lock.EnterWriteLock(); - _pool[_count] = packet; - _count++; - _lock.ExitWriteLock(); - _lock.ExitUpgradeableReadLock(); - } - } -} diff --git a/FirServer/Libraries/LiteNetLib/NetPeer.cs b/FirServer/Libraries/LiteNetLib/NetPeer.cs deleted file mode 100644 index 277ff02f..00000000 --- a/FirServer/Libraries/LiteNetLib/NetPeer.cs +++ /dev/null @@ -1,1175 +0,0 @@ -#if DEBUG -#define STATS_ENABLED -#endif -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Net; -using System.Threading; -using LiteNetLib.Utils; - -namespace LiteNetLib -{ - /// - /// Peer connection state - /// - [Flags] - public enum ConnectionState : byte - { - Outgoing = 1 << 1, - Connected = 1 << 2, - ShutdownRequested = 1 << 3, - Disconnected = 1 << 4, - Any = Outgoing | Connected | ShutdownRequested - } - - internal enum ConnectRequestResult - { - None, - P2PLose, //when peer connecting - Reconnection, //when peer was connected - NewConnection //when peer was disconnected - } - - internal enum DisconnectResult - { - None, - Reject, - Disconnect - } - - internal enum ShutdownResult - { - None, - Success, - WasConnected - } - - /// - /// Network peer. Main purpose is sending messages to specific peer. - /// - public class NetPeer - { - //Ping and RTT - private int _rtt; - private int _avgRtt; - private int _rttCount; - private double _resendDelay = 27.0; - private int _pingSendTimer; - private int _rttResetTimer; - private readonly Stopwatch _pingTimer = new Stopwatch(); - private int _timeSinceLastPacket; - private long _remoteDelta; - - //Common - private readonly NetPacketPool _packetPool; - private readonly object _flushLock = new object(); - private readonly object _sendLock = new object(); - private readonly object _shutdownLock = new object(); - - internal volatile NetPeer NextPeer; - internal NetPeer PrevPeer; - - internal byte ConnectionNum - { - get { return _connectNum; } - private set - { - _connectNum = value; - _mergeData.ConnectionNumber = value; - _pingPacket.ConnectionNumber = value; - _pongPacket.ConnectionNumber = value; - } - } - - //Channels - private readonly Queue _unreliableChannel; - private readonly BaseChannel[] _channels; - private BaseChannel _headChannel; - - //MTU - private int _mtu; - private int _mtuIdx; - private bool _finishMtu; - private int _mtuCheckTimer; - private int _mtuCheckAttempts; - private const int MtuCheckDelay = 1000; - private const int MaxMtuCheckAttempts = 4; - private readonly object _mtuMutex = new object(); - - //Fragment - private class IncomingFragments - { - public NetPacket[] Fragments; - public int ReceivedCount; - public int TotalSize; - public byte ChannelId; - } - private ushort _fragmentId; - private readonly Dictionary _holdedFragments; - private readonly Dictionary _deliveredFramgnets; - - //Merging - private readonly NetPacket _mergeData; - private int _mergePos; - private int _mergeCount; - - //Connection - private int _connectAttempts; - private int _connectTimer; - private long _connectTime; - private byte _connectNum; - private ConnectionState _connectionState; - private NetPacket _shutdownPacket; - private const int ShutdownDelay = 300; - private int _shutdownTimer; - private readonly NetPacket _pingPacket; - private readonly NetPacket _pongPacket; - private readonly NetPacket _connectRequestPacket; - private readonly NetPacket _connectAcceptPacket; - - /// - /// Peer ip address and port - /// - public readonly IPEndPoint EndPoint; - - /// - /// Peer parent NetManager - /// - public readonly NetManager NetManager; - - /// - /// Current connection state - /// - public ConnectionState ConnectionState { get { return _connectionState; } } - - /// - /// Connection time for internal purposes - /// - internal long ConnectTime { get { return _connectTime; } } - - /// - /// Peer id can be used as key in your dictionary of peers - /// - public readonly int Id; - - /// - /// Current ping in milliseconds - /// - public int Ping { get { return _avgRtt/2; } } - - /// - /// Current MTU - Maximum Transfer Unit ( maximum udp packet size without fragmentation ) - /// - public int Mtu { get { return _mtu; } } - - /// - /// Delta with remote time in ticks (not accurate) - /// positive - remote time > our time - /// - public long RemoteTimeDelta - { - get { return _remoteDelta; } - } - - /// - /// Remote UTC time (not accurate) - /// - public DateTime RemoteUtcTime - { - get { return new DateTime(DateTime.UtcNow.Ticks + _remoteDelta); } - } - - /// - /// Time since last packet received (including internal library packets) - /// - public int TimeSinceLastPacket { get { return _timeSinceLastPacket; } } - - internal double ResendDelay { get { return _resendDelay; } } - - /// - /// Application defined object containing data about the connection - /// - public object Tag; - - /// - /// Statistics of peer connection - /// - public readonly NetStatistics Statistics; - - //incoming connection constructor - internal NetPeer(NetManager netManager, IPEndPoint remoteEndPoint, int id) - { - Id = id; - Statistics = new NetStatistics(); - _packetPool = netManager.NetPacketPool; - NetManager = netManager; - SetMtu(0); - - EndPoint = remoteEndPoint; - _connectionState = ConnectionState.Connected; - _mergeData = new NetPacket(PacketProperty.Merged, NetConstants.MaxPacketSize); - _pongPacket = new NetPacket(PacketProperty.Pong, 0); - _pingPacket = new NetPacket(PacketProperty.Ping, 0) {Sequence = 1}; - - _unreliableChannel = new Queue(64); - _headChannel = null; - _holdedFragments = new Dictionary(); - _deliveredFramgnets = new Dictionary(); - - _channels = new BaseChannel[netManager.ChannelsCount * 4]; - } - - private void SetMtu(int mtuIdx) - { - _mtu = NetConstants.PossibleMtu[mtuIdx] - NetManager.ExtraPacketSizeForLayer; - } - - /// - /// Returns packets count in queue for reliable channel - /// - /// number of channel 0-63 - /// type of channel ReliableOrdered or ReliableUnordered - /// packets count in channel queue - public int GetPacketsCountInReliableQueue(byte channelNumber, bool ordered) - { - int idx = channelNumber * 4 + - (byte) (ordered ? DeliveryMethod.ReliableOrdered : DeliveryMethod.ReliableUnordered); - var channel = _channels[idx]; - return channel != null ? ((ReliableChannel)channel).PacketsInQueue : 0; - } - - private BaseChannel CreateChannel(byte idx) - { - BaseChannel newChannel = _channels[idx]; - if (newChannel != null) - return newChannel; - switch ((DeliveryMethod)(idx % 4)) - { - case DeliveryMethod.ReliableUnordered: - newChannel = new ReliableChannel(this, false, idx); - break; - case DeliveryMethod.Sequenced: - newChannel = new SequencedChannel(this, false, idx); - break; - case DeliveryMethod.ReliableOrdered: - newChannel = new ReliableChannel(this, true, idx); - break; - case DeliveryMethod.ReliableSequenced: - newChannel = new SequencedChannel(this, true, idx); - break; - } - _channels[idx] = newChannel; - newChannel.Next = _headChannel; - _headChannel = newChannel; - return newChannel; - } - - //"Connect to" constructor - internal NetPeer(NetManager netManager, IPEndPoint remoteEndPoint, int id, byte connectNum, NetDataWriter connectData) - : this(netManager, remoteEndPoint, id) - { - _connectTime = DateTime.UtcNow.Ticks; - _connectionState = ConnectionState.Outgoing; - ConnectionNum = connectNum; - - //Make initial packet - _connectRequestPacket = NetConnectRequestPacket.Make(connectData, remoteEndPoint.Serialize(), _connectTime); - _connectRequestPacket.ConnectionNumber = connectNum; - - //Send request - NetManager.SendRaw(_connectRequestPacket, EndPoint); - - NetDebug.Write(NetLogLevel.Trace, "[CC] ConnectId: {0}, ConnectNum: {1}", _connectTime, connectNum); - } - - //"Accept" incoming constructor - internal NetPeer(NetManager netManager, IPEndPoint remoteEndPoint, int id, long connectId, byte connectNum) - : this(netManager, remoteEndPoint, id) - { - _connectTime = connectId; - _connectionState = ConnectionState.Connected; - ConnectionNum = connectNum; - - //Make initial packet - _connectAcceptPacket = NetConnectAcceptPacket.Make(_connectTime, connectNum, false); - //Send - NetManager.SendRaw(_connectAcceptPacket, EndPoint); - - NetDebug.Write(NetLogLevel.Trace, "[CC] ConnectId: {0}", _connectTime); - } - - //Reject - internal void Reject(long connectionId, byte connectionNumber, byte[] data, int start, int length) - { - _connectTime = connectionId; - _connectNum = connectionNumber; - Shutdown(data, start, length, false); - } - - internal bool ProcessConnectAccept(NetConnectAcceptPacket packet) - { - if (_connectionState != ConnectionState.Outgoing) - return false; - - //check connection id - if (packet.ConnectionId != _connectTime) - { - NetDebug.Write(NetLogLevel.Trace, "[NC] Invalid connectId: {0}", _connectTime); - return false; - } - //check connect num - ConnectionNum = packet.ConnectionNumber; - - NetDebug.Write(NetLogLevel.Trace, "[NC] Received connection accept"); - Interlocked.Exchange(ref _timeSinceLastPacket, 0); - _connectionState = ConnectionState.Connected; - return true; - } - - /// - /// Gets maximum size of packet that will be not fragmented. - /// - /// Type of packet that you want send - /// size in bytes - public int GetMaxSinglePacketSize(DeliveryMethod options) - { - return _mtu - NetPacket.GetHeaderSize(options == DeliveryMethod.Unreliable ? PacketProperty.Unreliable : PacketProperty.Channeled); - } - - /// - /// Send data to peer with delivery event called - /// - /// Data - /// Number of channel (from 0 to channelsCount - 1) - /// Delivery method (reliable, unreliable, etc.) - /// User data that will be received in DeliveryEvent - /// - /// If you trying to send unreliable packet type - /// - public void SendWithDeliveryEvent(byte[] data, byte channelNumber, DeliveryMethod deliveryMethod, object userData) - { - if (deliveryMethod != DeliveryMethod.ReliableOrdered && deliveryMethod != DeliveryMethod.ReliableUnordered) - throw new ArgumentException("Delivery event will work only for ReliableOrdered/Unordered packets"); - SendInternal(data, 0, data.Length, channelNumber, deliveryMethod, userData); - } - - /// - /// Send data to peer with delivery event called - /// - /// Data - /// Start of data - /// Length of data - /// Number of channel (from 0 to channelsCount - 1) - /// Delivery method (reliable, unreliable, etc.) - /// User data that will be received in DeliveryEvent - /// - /// If you trying to send unreliable packet type - /// - public void SendWithDeliveryEvent(byte[] data, int start, int length, byte channelNumber, DeliveryMethod deliveryMethod, object userData) - { - if (deliveryMethod != DeliveryMethod.ReliableOrdered && deliveryMethod != DeliveryMethod.ReliableUnordered) - throw new ArgumentException("Delivery event will work only for ReliableOrdered/Unordered packets"); - SendInternal(data, start, length, channelNumber, deliveryMethod, userData); - } - - /// - /// Send data to peer with delivery event called - /// - /// Data - /// Number of channel (from 0 to channelsCount - 1) - /// Delivery method (reliable, unreliable, etc.) - /// User data that will be received in DeliveryEvent - /// - /// If you trying to send unreliable packet type - /// - public void SendWithDeliveryEvent(NetDataWriter dataWriter, byte channelNumber, DeliveryMethod deliveryMethod, object userData) - { - if (deliveryMethod != DeliveryMethod.ReliableOrdered && deliveryMethod != DeliveryMethod.ReliableUnordered) - throw new ArgumentException("Delivery event will work only for ReliableOrdered/Unordered packets"); - SendInternal(dataWriter.Data, 0, dataWriter.Length, channelNumber, deliveryMethod, userData); - } - - /// - /// Send data to peer (channel - 0) - /// - /// Data - /// Send options (reliable, unreliable, etc.) - /// - /// If size exceeds maximum limit: - /// MTU - headerSize bytes for Unreliable - /// Fragment count exceeded ushort.MaxValue - /// - public void Send(byte[] data, DeliveryMethod deliveryMethod) - { - SendInternal(data, 0, data.Length, 0, deliveryMethod, null); - } - - /// - /// Send data to peer (channel - 0) - /// - /// DataWriter with data - /// Send options (reliable, unreliable, etc.) - /// - /// If size exceeds maximum limit: - /// MTU - headerSize bytes for Unreliable - /// Fragment count exceeded ushort.MaxValue - /// - public void Send(NetDataWriter dataWriter, DeliveryMethod deliveryMethod) - { - SendInternal(dataWriter.Data, 0, dataWriter.Length, 0, deliveryMethod, null); - } - - /// - /// Send data to peer (channel - 0) - /// - /// Data - /// Start of data - /// Length of data - /// Send options (reliable, unreliable, etc.) - /// - /// If size exceeds maximum limit: - /// MTU - headerSize bytes for Unreliable - /// Fragment count exceeded ushort.MaxValue - /// - public void Send(byte[] data, int start, int length, DeliveryMethod options) - { - SendInternal(data, start, length, 0, options, null); - } - - /// - /// Send data to peer - /// - /// Data - /// Number of channel (from 0 to channelsCount - 1) - /// Send options (reliable, unreliable, etc.) - /// - /// If size exceeds maximum limit: - /// MTU - headerSize bytes for Unreliable - /// Fragment count exceeded ushort.MaxValue - /// - public void Send(byte[] data, byte channelNumber, DeliveryMethod deliveryMethod) - { - SendInternal(data, 0, data.Length, channelNumber, deliveryMethod, null); - } - - /// - /// Send data to peer - /// - /// DataWriter with data - /// Number of channel (from 0 to channelsCount - 1) - /// Send options (reliable, unreliable, etc.) - /// - /// If size exceeds maximum limit: - /// MTU - headerSize bytes for Unreliable - /// Fragment count exceeded ushort.MaxValue - /// - public void Send(NetDataWriter dataWriter, byte channelNumber, DeliveryMethod deliveryMethod) - { - SendInternal(dataWriter.Data, 0, dataWriter.Length, channelNumber, deliveryMethod, null); - } - - /// - /// Send data to peer - /// - /// Data - /// Start of data - /// Length of data - /// Number of channel (from 0 to channelsCount - 1) - /// Delivery method (reliable, unreliable, etc.) - /// - /// If size exceeds maximum limit: - /// MTU - headerSize bytes for Unreliable - /// Fragment count exceeded ushort.MaxValue - /// - public void Send(byte[] data, int start, int length, byte channelNumber, DeliveryMethod deliveryMethod) - { - SendInternal(data, start, length, channelNumber, deliveryMethod, null); - } - - private void SendInternal( - byte[] data, - int start, - int length, - byte channelNumber, - DeliveryMethod deliveryMethod, - object userData) - { - if (_connectionState != ConnectionState.Connected || channelNumber >= _channels.Length) - return; - - //Select channel - PacketProperty property; - BaseChannel channel = null; - - if (deliveryMethod == DeliveryMethod.Unreliable) - { - property = PacketProperty.Unreliable; - } - else - { - property = PacketProperty.Channeled; - channel = CreateChannel((byte)(channelNumber*4 + (byte)deliveryMethod)); - } - - //Prepare - NetDebug.Write("[RS]Packet: " + property); - - //Check fragmentation - int headerSize = NetPacket.GetHeaderSize(property); - //Save mtu for multithread - int mtu = _mtu; - if (length + headerSize > mtu) - { - //if cannot be fragmented - if (deliveryMethod != DeliveryMethod.ReliableOrdered && deliveryMethod != DeliveryMethod.ReliableUnordered) - throw new TooBigPacketException("Unreliable packet size exceeded maximum of " + (mtu - headerSize) + " bytes"); - - int packetFullSize = mtu - headerSize; - int packetDataSize = packetFullSize - NetConstants.FragmentHeaderSize; - int totalPackets = length / packetDataSize + (length % packetDataSize == 0 ? 0 : 1); - - NetDebug.Write("FragmentSend:\n" + - " MTU: {0}\n" + - " headerSize: {1}\n" + - " packetFullSize: {2}\n" + - " packetDataSize: {3}\n" + - " totalPackets: {4}", - mtu, headerSize, packetFullSize, packetDataSize, totalPackets); - - if (totalPackets > ushort.MaxValue) - throw new TooBigPacketException("Data was split in " + totalPackets + " fragments, which exceeds " + ushort.MaxValue); - - ushort currentFramentId; - lock (_sendLock) - { - currentFramentId = _fragmentId; - _fragmentId++; - } - - for(ushort partIdx = 0; partIdx < totalPackets; partIdx++) - { - int sendLength = length > packetDataSize ? packetDataSize : length; - - NetPacket p = _packetPool.GetPacket(headerSize + sendLength + NetConstants.FragmentHeaderSize); - p.Property = property; - p.UserData = userData; - p.FragmentId = currentFramentId; - p.FragmentPart = partIdx; - p.FragmentsTotal = (ushort)totalPackets; - p.MarkFragmented(); - - Buffer.BlockCopy(data, partIdx * packetDataSize, p.RawData, NetConstants.FragmentedHeaderTotalSize, sendLength); - channel.AddToQueue(p); - - length -= sendLength; - } - return; - } - - //Else just send - NetPacket packet = _packetPool.GetPacket(headerSize + length); - packet.Property = property; - Buffer.BlockCopy(data, start, packet.RawData, headerSize, length); - packet.UserData = userData; - - if (channel == null) //unreliable - { - lock(_unreliableChannel) - _unreliableChannel.Enqueue(packet); - } - else - { - channel.AddToQueue(packet); - } - } - - public void Disconnect(byte[] data) - { - NetManager.DisconnectPeer(this, data); - } - - public void Disconnect(NetDataWriter writer) - { - NetManager.DisconnectPeer(this, writer); - } - - public void Disconnect(byte[] data, int start, int count) - { - NetManager.DisconnectPeer(this, data, start, count); - } - - public void Disconnect() - { - NetManager.DisconnectPeer(this); - } - - internal DisconnectResult ProcessDisconnect(NetPacket packet) - { - if ((_connectionState == ConnectionState.Connected || _connectionState == ConnectionState.Outgoing) && - packet.Size >= 9 && - BitConverter.ToInt64(packet.RawData, 1) == _connectTime && - packet.ConnectionNumber == _connectNum) - { - return _connectionState == ConnectionState.Connected - ? DisconnectResult.Disconnect - : DisconnectResult.Reject; - } - return DisconnectResult.None; - } - - internal ShutdownResult Shutdown(byte[] data, int start, int length, bool force) - { - lock (_shutdownLock) - { - //trying to shutdown already disconnected - if (_connectionState == ConnectionState.Disconnected || - _connectionState == ConnectionState.ShutdownRequested) - { - return ShutdownResult.None; - } - - var result = _connectionState == ConnectionState.Connected - ? ShutdownResult.WasConnected - : ShutdownResult.Success; - - //don't send anything - if (force) - { - _connectionState = ConnectionState.Disconnected; - return result; - } - - //reset time for reconnect protection - Interlocked.Exchange(ref _timeSinceLastPacket, 0); - - //send shutdown packet - _shutdownPacket = new NetPacket(PacketProperty.Disconnect, length) {ConnectionNumber = _connectNum}; - FastBitConverter.GetBytes(_shutdownPacket.RawData, 1, _connectTime); - if (_shutdownPacket.Size >= _mtu) - { - //Drop additional data - NetDebug.WriteError("[Peer] Disconnect additional data size more than MTU - 8!"); - } - else if (data != null && length > 0) - { - Buffer.BlockCopy(data, start, _shutdownPacket.RawData, 9, length); - } - _connectionState = ConnectionState.ShutdownRequested; - NetDebug.Write("[Peer] Send disconnect"); - NetManager.SendRaw(_shutdownPacket, EndPoint); - return result; - } - } - - private void UpdateRoundTripTime(int roundTripTime) - { - _rtt += roundTripTime; - _rttCount++; - _avgRtt = _rtt/_rttCount; - _resendDelay = 25.0 + _avgRtt * 2.1; // 25 ms + double rtt - } - - internal void AddReliablePacket(DeliveryMethod method, NetPacket p) - { - if (p.IsFragmented) - { - NetDebug.Write("Fragment. Id: {0}, Part: {1}, Total: {2}", p.FragmentId, p.FragmentPart, p.FragmentsTotal); - //Get needed array from dictionary - ushort packetFragId = p.FragmentId; - IncomingFragments incomingFragments; - if (!_holdedFragments.TryGetValue(packetFragId, out incomingFragments)) - { - incomingFragments = new IncomingFragments - { - Fragments = new NetPacket[p.FragmentsTotal], - ChannelId = p.ChannelId - }; - _holdedFragments.Add(packetFragId, incomingFragments); - } - - //Cache - var fragments = incomingFragments.Fragments; - - //Error check - if (p.FragmentPart >= fragments.Length || - fragments[p.FragmentPart] != null || - p.ChannelId != incomingFragments.ChannelId) - { - _packetPool.Recycle(p); - NetDebug.WriteError("Invalid fragment packet"); - return; - } - //Fill array - fragments[p.FragmentPart] = p; - - //Increase received fragments count - incomingFragments.ReceivedCount++; - - //Increase total size - incomingFragments.TotalSize += p.Size - NetConstants.FragmentedHeaderTotalSize; - - //Check for finish - if (incomingFragments.ReceivedCount != fragments.Length) - return; - - //unreliable to save header space - NetPacket resultingPacket = _packetPool.GetWithProperty( - PacketProperty.Unreliable, - incomingFragments.TotalSize); - - int firstFragmentSize = fragments[0].Size - NetConstants.FragmentedHeaderTotalSize; - for (int i = 0; i < incomingFragments.ReceivedCount; i++) - { - var fragment = fragments[i]; - //Create resulting big packet - Buffer.BlockCopy( - fragment.RawData, - NetConstants.FragmentedHeaderTotalSize, - resultingPacket.RawData, - NetConstants.HeaderSize + firstFragmentSize * i, - fragment.Size - NetConstants.FragmentedHeaderTotalSize); - - //Free memory - _packetPool.Recycle(fragment); - } - Array.Clear(fragments, 0, incomingFragments.ReceivedCount); - - //Send to process - NetManager.CreateReceiveEvent(resultingPacket, method, this); - - //Clear memory - _holdedFragments.Remove(packetFragId); - } - else //Just simple packet - { - NetManager.CreateReceiveEvent(p, method, this); - } - } - - private void ProcessMtuPacket(NetPacket packet) - { - //header + int - if (packet.Size < NetConstants.PossibleMtu[0]) - return; - - //first stage check (mtu check and mtu ok) - int receivedMtu = BitConverter.ToInt32(packet.RawData, 1); - int endMtuCheck = BitConverter.ToInt32(packet.RawData, packet.Size - 4); - if (receivedMtu != packet.Size || receivedMtu != endMtuCheck || receivedMtu > NetConstants.MaxPacketSize) - { - NetDebug.WriteError("[MTU] Broken packet. RMTU {0}, EMTU {1}, PSIZE {2}", receivedMtu, endMtuCheck, packet.Size); - return; - } - - if (packet.Property == PacketProperty.MtuCheck) - { - _mtuCheckAttempts = 0; - NetDebug.Write("[MTU] check. send back: " + receivedMtu); - packet.Property = PacketProperty.MtuOk; - NetManager.SendRawAndRecycle(packet, EndPoint); - } - else if(receivedMtu > _mtu && !_finishMtu) //MtuOk - { - //invalid packet - if (receivedMtu != NetConstants.PossibleMtu[_mtuIdx + 1]) - return; - - lock (_mtuMutex) - { - _mtuIdx++; - SetMtu(_mtuIdx); - } - //if maxed - finish. - if (_mtuIdx == NetConstants.PossibleMtu.Length - 1) - _finishMtu = true; - - NetDebug.Write("[MTU] ok. Increase to: " + _mtu); - } - } - - private void UpdateMtuLogic(int deltaTime) - { - if (_finishMtu) - return; - - _mtuCheckTimer += deltaTime; - if (_mtuCheckTimer < MtuCheckDelay) - return; - - _mtuCheckTimer = 0; - _mtuCheckAttempts++; - if (_mtuCheckAttempts >= MaxMtuCheckAttempts) - { - _finishMtu = true; - return; - } - - lock (_mtuMutex) - { - if (_mtuIdx >= NetConstants.PossibleMtu.Length - 1) - return; - - //Send increased packet - int newMtu = NetConstants.PossibleMtu[_mtuIdx + 1]; - var p = _packetPool.GetPacket(newMtu); - p.Property = PacketProperty.MtuCheck; - FastBitConverter.GetBytes(p.RawData, 1, newMtu); //place into start - FastBitConverter.GetBytes(p.RawData, p.Size - 4, newMtu);//and end of packet - - //Must check result for MTU fix - if (NetManager.SendRawAndRecycle(p, EndPoint) <= 0) - _finishMtu = true; - } - } - - internal ConnectRequestResult ProcessConnectRequest(NetConnectRequestPacket connRequest) - { - //current or new request - switch (_connectionState) - { - //P2P case - case ConnectionState.Outgoing: - //fast check - if (connRequest.ConnectionTime < _connectTime) - { - return ConnectRequestResult.P2PLose; - } - //slow rare case check - else if (connRequest.ConnectionTime == _connectTime) - { - var remoteBytes = EndPoint.Serialize(); - var localBytes = connRequest.TargetAddress; - for (int i = remoteBytes.Size-1; i >= 0; i--) - { - byte rb = remoteBytes[i]; - if (rb == localBytes[i]) - continue; - if (rb < localBytes[i]) - return ConnectRequestResult.P2PLose; - } - } - break; - - case ConnectionState.Connected: - //Old connect request - if (connRequest.ConnectionTime == _connectTime) - { - //just reply accept - NetManager.SendRaw(_connectAcceptPacket, EndPoint); - } - //New connect request - else if (connRequest.ConnectionTime > _connectTime) - { - return ConnectRequestResult.Reconnection; - } - break; - - case ConnectionState.Disconnected: - case ConnectionState.ShutdownRequested: - if (connRequest.ConnectionTime >= _connectTime) - return ConnectRequestResult.NewConnection; - break; - } - return ConnectRequestResult.None; - } - - //Process incoming packet - internal void ProcessPacket(NetPacket packet) - { - //not initialized - if (_connectionState == ConnectionState.Outgoing) - { - _packetPool.Recycle(packet); - return; - } - if (packet.ConnectionNumber != _connectNum && packet.Property != PacketProperty.ShutdownOk) //without connectionNum - { - NetDebug.Write(NetLogLevel.Trace, "[RR]Old packet"); - _packetPool.Recycle(packet); - return; - } - Interlocked.Exchange(ref _timeSinceLastPacket, 0); - - NetDebug.Write("[RR]PacketProperty: {0}", packet.Property); - switch (packet.Property) - { - case PacketProperty.Merged: - int pos = NetConstants.HeaderSize; - while (pos < packet.Size) - { - ushort size = BitConverter.ToUInt16(packet.RawData, pos); - pos += 2; - NetPacket mergedPacket = _packetPool.GetPacket(size); - if (!mergedPacket.FromBytes(packet.RawData, pos, size)) - { - _packetPool.Recycle(packet); - break; - } - pos += size; - ProcessPacket(mergedPacket); - } - break; - //If we get ping, send pong - case PacketProperty.Ping: - if (NetUtils.RelativeSequenceNumber(packet.Sequence, _pongPacket.Sequence) > 0) - { - NetDebug.Write("[PP]Ping receive, send pong"); - FastBitConverter.GetBytes(_pongPacket.RawData, 3, DateTime.UtcNow.Ticks); - _pongPacket.Sequence = packet.Sequence; - NetManager.SendRaw(_pongPacket, EndPoint); - } - _packetPool.Recycle(packet); - break; - - //If we get pong, calculate ping time and rtt - case PacketProperty.Pong: - if (packet.Sequence == _pingPacket.Sequence) - { - _pingTimer.Stop(); - int elapsedMs = (int)_pingTimer.ElapsedMilliseconds; - _remoteDelta = BitConverter.ToInt64(packet.RawData, 3) + (elapsedMs * TimeSpan.TicksPerMillisecond ) / 2 - DateTime.UtcNow.Ticks; - UpdateRoundTripTime(elapsedMs); - NetManager.ConnectionLatencyUpdated(this, elapsedMs / 2); - NetDebug.Write("[PP]Ping: {0} - {1} - {2}", packet.Sequence, elapsedMs, _remoteDelta); - } - _packetPool.Recycle(packet); - break; - - case PacketProperty.Ack: - case PacketProperty.Channeled: - if (packet.ChannelId > _channels.Length) - { - _packetPool.Recycle(packet); - break; - } - var channel = _channels[packet.ChannelId] ?? (packet.Property == PacketProperty.Ack ? null : CreateChannel(packet.ChannelId)); - if (channel != null) - { - if (!channel.ProcessPacket(packet)) - _packetPool.Recycle(packet); - } - break; - - //Simple packet without acks - case PacketProperty.Unreliable: - NetManager.CreateReceiveEvent(packet, DeliveryMethod.Unreliable, this); - return; - - case PacketProperty.MtuCheck: - case PacketProperty.MtuOk: - ProcessMtuPacket(packet); - break; - - case PacketProperty.ShutdownOk: - if(_connectionState == ConnectionState.ShutdownRequested) - _connectionState = ConnectionState.Disconnected; - _packetPool.Recycle(packet); - break; - - default: - NetDebug.WriteError("Error! Unexpected packet type: " + packet.Property); - break; - } - } - - private void SendMerged() - { - if (_mergeCount == 0) - return; - int bytesSent; - if (_mergeCount > 1) - { - NetDebug.Write("[P]Send merged: " + _mergePos + ", count: " + _mergeCount); - bytesSent = NetManager.SendRaw(_mergeData.RawData, 0, NetConstants.HeaderSize + _mergePos, EndPoint); - } - else - { - //Send without length information and merging - bytesSent = NetManager.SendRaw(_mergeData.RawData, NetConstants.HeaderSize + 2, _mergePos - 2, EndPoint); - } - - if (NetManager.EnableStatistics) - { - Statistics.PacketsSent++; - Statistics.BytesSent += (ulong)bytesSent; - } - - _mergePos = 0; - _mergeCount = 0; - } - - internal void SendUserData(NetPacket packet) - { - packet.ConnectionNumber = _connectNum; - int mergedPacketSize = NetConstants.HeaderSize + packet.Size + 2; - const int sizeTreshold = 20; - if (mergedPacketSize + sizeTreshold >= _mtu) - { - NetDebug.Write(NetLogLevel.Trace, "[P]SendingPacket: " + packet.Property); - int bytesSent = NetManager.SendRaw(packet, EndPoint); - - if (NetManager.EnableStatistics) - { - Statistics.PacketsSent++; - Statistics.BytesSent += (ulong)bytesSent; - } - - return; - } - if (_mergePos + mergedPacketSize > _mtu) - SendMerged(); - - FastBitConverter.GetBytes(_mergeData.RawData, _mergePos + NetConstants.HeaderSize, (ushort)packet.Size); - Buffer.BlockCopy(packet.RawData, 0, _mergeData.RawData, _mergePos + NetConstants.HeaderSize + 2, packet.Size); - _mergePos += packet.Size + 2; - _mergeCount++; - //DebugWriteForce("Merged: " + _mergePos + "/" + (_mtu - 2) + ", count: " + _mergeCount); - } - - /// - /// Flush all queued packets - /// - public void Flush() - { - if (_connectionState != ConnectionState.Connected) - return; - lock (_flushLock) - { - BaseChannel currentChannel = _headChannel; - while (currentChannel != null) - { - currentChannel.SendNextPackets(); - currentChannel = currentChannel.Next; - } - - lock (_unreliableChannel) - { - while (_unreliableChannel.Count > 0) - { - NetPacket packet = _unreliableChannel.Dequeue(); - SendUserData(packet); - NetManager.NetPacketPool.Recycle(packet); - } - } - - SendMerged(); - } - } - - internal void Update(int deltaTime) - { - Interlocked.Add(ref _timeSinceLastPacket, deltaTime); - switch (_connectionState) - { - case ConnectionState.Connected: - if (_timeSinceLastPacket > NetManager.DisconnectTimeout) - { - NetDebug.Write( - "[UPDATE] Disconnect by timeout: {0} > {1}", - _timeSinceLastPacket, - NetManager.DisconnectTimeout); - NetManager.DisconnectPeerForce(this, DisconnectReason.Timeout, 0, null); - return; - } - break; - - case ConnectionState.ShutdownRequested: - if (_timeSinceLastPacket > NetManager.DisconnectTimeout) - { - _connectionState = ConnectionState.Disconnected; - } - else - { - _shutdownTimer += deltaTime; - if (_shutdownTimer >= ShutdownDelay) - { - _shutdownTimer = 0; - NetManager.SendRaw(_shutdownPacket, EndPoint); - } - } - return; - - case ConnectionState.Outgoing: - _connectTimer += deltaTime; - if (_connectTimer > NetManager.ReconnectDelay) - { - _connectTimer = 0; - _connectAttempts++; - if (_connectAttempts > NetManager.MaxConnectAttempts) - { - NetManager.DisconnectPeerForce(this, DisconnectReason.ConnectionFailed, 0, null); - return; - } - - //else send connect again - NetManager.SendRaw(_connectRequestPacket, EndPoint); - } - return; - - case ConnectionState.Disconnected: - return; - } - - //Send ping - _pingSendTimer += deltaTime; - if (_pingSendTimer >= NetManager.PingInterval) - { - NetDebug.Write("[PP] Send ping..."); - //reset timer - _pingSendTimer = 0; - //send ping - _pingPacket.Sequence++; - //ping timeout - if (_pingTimer.IsRunning) - UpdateRoundTripTime((int)_pingTimer.ElapsedMilliseconds); - _pingTimer.Reset(); - _pingTimer.Start(); - NetManager.SendRaw(_pingPacket, EndPoint); - } - - //RTT - round trip time - _rttResetTimer += deltaTime; - if (_rttResetTimer >= NetManager.PingInterval * 3) - { - _rttResetTimer = 0; - _rtt = _avgRtt; - _rttCount = 1; - } - - UpdateMtuLogic(deltaTime); - - //Pending send - Flush(); - } - - //For reliable channel - internal void RecycleAndDeliver(NetPacket packet) - { - if (packet.UserData != null) - { - if (packet.IsFragmented) - { - ushort fragCount; - _deliveredFramgnets.TryGetValue(packet.FragmentId, out fragCount); - fragCount++; - if (fragCount == packet.FragmentsTotal) - { - NetManager.MessageDelivered(this, packet.UserData); - _deliveredFramgnets.Remove(packet.FragmentId); - } - else - { - _deliveredFramgnets[packet.FragmentId] = fragCount; - } - } - else - { - NetManager.MessageDelivered(this, packet.UserData); - } - packet.UserData = null; - } - _packetPool.Recycle(packet); - } - } -} diff --git a/FirServer/Libraries/LiteNetLib/NetSocket.cs b/FirServer/Libraries/LiteNetLib/NetSocket.cs deleted file mode 100644 index ca686a30..00000000 --- a/FirServer/Libraries/LiteNetLib/NetSocket.cs +++ /dev/null @@ -1,483 +0,0 @@ -#if UNITY_5_3_OR_NEWER -#define UNITY -#if UNITY_IOS && !UNITY_EDITOR -using UnityEngine; -#endif -#endif -#if NETSTANDARD || NETCOREAPP -using System.Runtime.InteropServices; -#endif - -using System; -using System.Net; -using System.Net.Sockets; -using System.Threading; - -namespace LiteNetLib -{ -#if UNITY_IOS && !UNITY_EDITOR - public class UnitySocketFix : MonoBehaviour - { - internal IPAddress BindAddrIPv4; - internal IPAddress BindAddrIPv6; - internal bool Reuse; - internal IPv6Mode IPv6; - internal int Port; - internal bool Paused; - internal NetSocket Socket; - - private void Update() - { - if (Socket == null) - Destroy(gameObject); - } - - private void OnApplicationPause(bool pause) - { - if (Socket == null) - return; - if (pause) - { - Paused = true; - Socket.Close(true); - } - else if (Paused) - { - if (!Socket.Bind(BindAddrIPv4, BindAddrIPv6, Port, Reuse, IPv6)) - { - NetDebug.WriteError("[S] Cannot restore connection \"{0}\",\"{1}\" port {2}", BindAddrIPv4, BindAddrIPv6, Port); - Socket.OnErrorRestore(); - } - } - } - } -#endif - - internal interface INetSocketListener - { - void OnMessageReceived(byte[] data, int length, SocketError errorCode, IPEndPoint remoteEndPoint); - } - - internal sealed class NetSocket - { - public const int ReceivePollingTime = 500000; //0.5 second - private Socket _udpSocketv4; - private Socket _udpSocketv6; - private Thread _threadv4; - private Thread _threadv6; - private readonly INetSocketListener _listener; - private const int SioUdpConnreset = -1744830452; //SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12 - private static readonly IPAddress MulticastAddressV6 = IPAddress.Parse("ff02::1"); - internal static readonly bool IPv6Support; -#if UNITY_IOS && !UNITY_EDITOR - private UnitySocketFix _unitySocketFix; - - public void OnErrorRestore() - { - Close(false); - _listener.OnMessageReceived(null, 0, SocketError.NotConnected, new IPEndPoint(0,0)); - } -#endif - public int LocalPort { get; private set; } - public volatile bool IsRunning; - - public short Ttl - { - get - { -#if UNITY_SWITCH - return 0; -#else - if (_udpSocketv4.AddressFamily == AddressFamily.InterNetworkV6) - return (short)_udpSocketv4.GetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.HopLimit); - return _udpSocketv4.Ttl; -#endif - } - set - { -#if !UNITY_SWITCH - if (_udpSocketv4.AddressFamily == AddressFamily.InterNetworkV6) - _udpSocketv4.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.HopLimit, value); - else - _udpSocketv4.Ttl = value; -#endif - } - } - - static NetSocket() - { -#if DISABLE_IPV6 || (!UNITY_EDITOR && ENABLE_IL2CPP && !UNITY_2018_3_OR_NEWER) - IPv6Support = false; -#elif !UNITY_2019_1_OR_NEWER && !UNITY_2018_4_OR_NEWER && (!UNITY_EDITOR && ENABLE_IL2CPP && UNITY_2018_3_OR_NEWER) - string version = UnityEngine.Application.unityVersion; - IPv6Support = Socket.OSSupportsIPv6 && int.Parse(version.Remove(version.IndexOf('f')).Split('.')[2]) >= 6; -#elif UNITY_2018_2_OR_NEWER - IPv6Support = Socket.OSSupportsIPv6; -#elif UNITY -#pragma warning disable 618 - IPv6Support = Socket.SupportsIPv6; -#pragma warning restore 618 -#else - IPv6Support = Socket.OSSupportsIPv6; -#endif - } - - public NetSocket(INetSocketListener listener) - { - _listener = listener; - } - - private bool IsActive() - { -#if UNITY_IOS && !UNITY_EDITOR - var unitySocketFix = _unitySocketFix; //save for multithread - if (unitySocketFix != null && unitySocketFix.Paused) - return false; -#endif - return IsRunning; - } - - private void ReceiveLogic(object state) - { - Socket socket = (Socket)state; - EndPoint bufferEndPoint = new IPEndPoint(socket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0); - byte[] receiveBuffer = new byte[NetConstants.MaxPacketSize]; - - while (IsActive()) - { - int result; - - //Reading data - try - { - if (socket.Available == 0 && !socket.Poll(ReceivePollingTime, SelectMode.SelectRead)) - continue; - result = socket.ReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, - ref bufferEndPoint); - } - catch (SocketException ex) - { - switch (ex.SocketErrorCode) - { -#if UNITY_IOS && !UNITY_EDITOR - case SocketError.NotConnected: -#endif - case SocketError.Interrupted: - case SocketError.NotSocket: - return; - case SocketError.ConnectionReset: - case SocketError.MessageSize: - case SocketError.TimedOut: - NetDebug.Write(NetLogLevel.Trace, "[R]Ignored error: {0} - {1}", - (int)ex.SocketErrorCode, ex.ToString()); - break; - default: - NetDebug.WriteError("[R]Error code: {0} - {1}", (int)ex.SocketErrorCode, - ex.ToString()); - _listener.OnMessageReceived(null, 0, ex.SocketErrorCode, (IPEndPoint)bufferEndPoint); - break; - } - continue; - } - catch (ObjectDisposedException) - { - return; - } - - //All ok! - NetDebug.Write(NetLogLevel.Trace, "[R]Received data from {0}, result: {1}", bufferEndPoint.ToString(), result); - _listener.OnMessageReceived(receiveBuffer, result, 0, (IPEndPoint)bufferEndPoint); - } - } - - public bool Bind(IPAddress addressIPv4, IPAddress addressIPv6, int port, bool reuseAddress, IPv6Mode ipv6Mode) - { - if (IsActive()) - return false; - bool dualMode = ipv6Mode == IPv6Mode.DualMode && IPv6Support; - - _udpSocketv4 = new Socket( - dualMode ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork, - SocketType.Dgram, - ProtocolType.Udp); - - if (!BindSocket(_udpSocketv4, new IPEndPoint(dualMode ? addressIPv6 : addressIPv4, port), reuseAddress, ipv6Mode)) - return false; - - LocalPort = ((IPEndPoint) _udpSocketv4.LocalEndPoint).Port; - -#if UNITY_IOS && !UNITY_EDITOR - if (_unitySocketFix == null) - { - var unityFixObj = new GameObject("LiteNetLib_UnitySocketFix"); - GameObject.DontDestroyOnLoad(unityFixObj); - _unitySocketFix = unityFixObj.AddComponent(); - _unitySocketFix.Socket = this; - _unitySocketFix.BindAddrIPv4 = addressIPv4; - _unitySocketFix.BindAddrIPv6 = addressIPv6; - _unitySocketFix.Reuse = reuseAddress; - _unitySocketFix.Port = LocalPort; - _unitySocketFix.IPv6 = ipv6Mode; - } - else - { - _unitySocketFix.Paused = false; - } -#endif - if (dualMode) - _udpSocketv6 = _udpSocketv4; - - IsRunning = true; - _threadv4 = new Thread(ReceiveLogic) - { - Name = "SocketThreadv4(" + LocalPort + ")", - IsBackground = true - }; - _threadv4.Start(_udpSocketv4); - - //Check IPv6 support - if (!IPv6Support || ipv6Mode != IPv6Mode.SeparateSocket) - return true; - - _udpSocketv6 = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp); - //Use one port for two sockets - if (BindSocket(_udpSocketv6, new IPEndPoint(addressIPv6, LocalPort), reuseAddress, ipv6Mode)) - { - _threadv6 = new Thread(ReceiveLogic) - { - Name = "SocketThreadv6(" + LocalPort + ")", - IsBackground = true - }; - _threadv6.Start(_udpSocketv6); - } - - return true; - } - - private bool BindSocket(Socket socket, IPEndPoint ep, bool reuseAddress, IPv6Mode ipv6Mode) - { - //Setup socket - socket.ReceiveTimeout = 500; - socket.SendTimeout = 500; - socket.ReceiveBufferSize = NetConstants.SocketBufferSize; - socket.SendBufferSize = NetConstants.SocketBufferSize; -#if !UNITY || UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN -#if NETSTANDARD || NETCOREAPP - if(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) -#endif - try - { - socket.IOControl(SioUdpConnreset, new byte[] { 0 }, null); - } - catch - { - //ignored - } -#endif - - try - { - socket.ExclusiveAddressUse = !reuseAddress; - socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, reuseAddress); - } - catch - { - //Unity with IL2CPP throws an exception here, it doesn't matter in most cases so just ignore it - } - if (socket.AddressFamily == AddressFamily.InterNetwork) - { - Ttl = NetConstants.SocketTTL; - -#if NETSTANDARD || NETCOREAPP - if(!RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) -#endif - try { socket.DontFragment = true; } - catch (SocketException e) - { - NetDebug.WriteError("[B]DontFragment error: {0}", e.SocketErrorCode); - } - - try { socket.EnableBroadcast = true; } - catch (SocketException e) - { - NetDebug.WriteError("[B]Broadcast error: {0}", e.SocketErrorCode); - } - } - else //IPv6 specific - { - if (ipv6Mode == IPv6Mode.DualMode) - { - try - { - //Disable IPv6 only mode - socket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, false); - } - catch(Exception e) - { - NetDebug.WriteError("[B]Bind exception (dualmode setting): {0}", e.ToString()); - } - } - } - - //Bind - try - { - socket.Bind(ep); - NetDebug.Write(NetLogLevel.Trace, "[B]Successfully binded to port: {0}", ((IPEndPoint)socket.LocalEndPoint).Port); - - //join multicast - if (socket.AddressFamily == AddressFamily.InterNetworkV6) - { - try - { -#if !UNITY - socket.SetSocketOption( - SocketOptionLevel.IPv6, - SocketOptionName.AddMembership, - new IPv6MulticastOption(MulticastAddressV6)); -#endif - } - catch (Exception) - { - // Unity3d throws exception - ignored - } - } - } - catch (SocketException bindException) - { - switch (bindException.SocketErrorCode) - { - //IPv6 bind fix - case SocketError.AddressAlreadyInUse: - if (socket.AddressFamily == AddressFamily.InterNetworkV6 && ipv6Mode != IPv6Mode.DualMode) - { - try - { - //Set IPv6Only - socket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, true); - socket.Bind(ep); - } -#if UNITY_2018_3_OR_NEWER - catch (SocketException ex) - { - - //because its fixed in 2018_3 - NetDebug.WriteError("[B]Bind exception: {0}, errorCode: {1}", ex.ToString(), ex.SocketErrorCode); -#else - catch(SocketException) - { -#endif - return false; - } - return true; - } - break; - //hack for iOS (Unity3D) - case SocketError.AddressFamilyNotSupported: - return true; - } - NetDebug.WriteError("[B]Bind exception: {0}, errorCode: {1}", bindException.ToString(), bindException.SocketErrorCode); - return false; - } - return true; - } - - public bool SendBroadcast(byte[] data, int offset, int size, int port) - { - if (!IsActive()) - return false; - bool broadcastSuccess = false; - bool multicastSuccess = false; - try - { - broadcastSuccess = _udpSocketv4.SendTo( - data, - offset, - size, - SocketFlags.None, - new IPEndPoint(IPAddress.Broadcast, port)) > 0; - - if (_udpSocketv6 != null) - { - multicastSuccess = _udpSocketv6.SendTo( - data, - offset, - size, - SocketFlags.None, - new IPEndPoint(MulticastAddressV6, port)) > 0; - } - } - catch (Exception ex) - { - NetDebug.WriteError("[S][MCAST]" + ex); - return broadcastSuccess; - } - return broadcastSuccess || multicastSuccess; - } - - public int SendTo(byte[] data, int offset, int size, IPEndPoint remoteEndPoint, ref SocketError errorCode) - { - if (!IsActive()) - return 0; - try - { - var socket = _udpSocketv4; - if (remoteEndPoint.AddressFamily == AddressFamily.InterNetworkV6 && IPv6Support) - socket = _udpSocketv6; - int result = socket.SendTo(data, offset, size, SocketFlags.None, remoteEndPoint); - NetDebug.Write(NetLogLevel.Trace, "[S]Send packet to {0}, result: {1}", remoteEndPoint, result); - return result; - } - catch (SocketException ex) - { - switch (ex.SocketErrorCode) - { - case SocketError.NoBufferSpaceAvailable: - case SocketError.Interrupted: - return 0; - case SocketError.MessageSize: //do nothing - break; - default: - NetDebug.WriteError("[S]" + ex); - break; - } - errorCode = ex.SocketErrorCode; - return -1; - } - catch (Exception ex) - { - NetDebug.WriteError("[S]" + ex); - return -1; - } - } - - public void Close(bool suspend) - { - if (!suspend) - { - IsRunning = false; -#if UNITY_IOS && !UNITY_EDITOR - _unitySocketFix.Socket = null; - _unitySocketFix = null; -#endif - } - //cleanup dual mode - if (_udpSocketv4 == _udpSocketv6) - _udpSocketv6 = null; - - if (_udpSocketv4 != null) - _udpSocketv4.Close(); - if (_udpSocketv6 != null) - _udpSocketv6.Close(); - _udpSocketv4 = null; - _udpSocketv6 = null; - - if (_threadv4 != null && _threadv4 != Thread.CurrentThread) - _threadv4.Join(); - if (_threadv6 != null && _threadv6 != Thread.CurrentThread) - _threadv6.Join(); - _threadv4 = null; - _threadv6 = null; - } - } -} diff --git a/FirServer/Libraries/LiteNetLib/NetStatistics.cs b/FirServer/Libraries/LiteNetLib/NetStatistics.cs deleted file mode 100644 index e763e7ad..00000000 --- a/FirServer/Libraries/LiteNetLib/NetStatistics.cs +++ /dev/null @@ -1,39 +0,0 @@ -namespace LiteNetLib -{ - public sealed class NetStatistics - { - public ulong PacketsSent; - public ulong PacketsReceived; - public ulong BytesSent; - public ulong BytesReceived; - public ulong PacketLoss; - public ulong PacketLossPercent - { - get { return PacketsSent == 0 ? 0 : PacketLoss * 100 / PacketsSent; } - } - - public ulong SequencedPacketLoss; - - public void Reset() - { - PacketsSent = 0; - PacketsReceived = 0; - BytesSent = 0; - BytesReceived = 0; - PacketLoss = 0; - } - - public override string ToString() - { - return - string.Format( - "BytesReceived: {0}\nPacketsReceived: {1}\nBytesSent: {2}\nPacketsSent: {3}\nPacketLoss: {4}\nPacketLossPercent: {5}\n", - BytesReceived, - PacketsReceived, - BytesSent, - PacketsSent, - PacketLoss, - PacketLossPercent); - } - } -} diff --git a/FirServer/Libraries/LiteNetLib/NetUtils.cs b/FirServer/Libraries/LiteNetLib/NetUtils.cs deleted file mode 100644 index a74ab113..00000000 --- a/FirServer/Libraries/LiteNetLib/NetUtils.cs +++ /dev/null @@ -1,197 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net; -using System.Net.Sockets; -using System.Net.NetworkInformation; - -namespace LiteNetLib -{ - /// - /// Address type that you want to receive from NetUtils.GetLocalIp method - /// - [Flags] - public enum LocalAddrType - { - IPv4 = 1, - IPv6 = 2, - All = IPv4 | IPv6 - } - - /// - /// Some specific network utilities - /// - public static class NetUtils - { - public static IPEndPoint MakeEndPoint(string hostStr, int port) - { - return new IPEndPoint(ResolveAddress(hostStr), port); - } - - public static IPAddress ResolveAddress(string hostStr) - { - if(hostStr == "localhost") - return IPAddress.Loopback; - - IPAddress ipAddress; - if (!IPAddress.TryParse(hostStr, out ipAddress)) - { - if (NetSocket.IPv6Support) - ipAddress = ResolveAddress(hostStr, AddressFamily.InterNetworkV6); - if (ipAddress == null) - ipAddress = ResolveAddress(hostStr, AddressFamily.InterNetwork); - } - if (ipAddress == null) - throw new ArgumentException("Invalid address: " + hostStr); - - return ipAddress; - } - - private static IPAddress ResolveAddress(string hostStr, AddressFamily addressFamily) - { - IPAddress[] addresses = ResolveAddresses(hostStr); - foreach (IPAddress ip in addresses) - { - if (ip.AddressFamily == addressFamily) - { - return ip; - } - } - return null; - } - - private static IPAddress[] ResolveAddresses(string hostStr) - { -#if NETSTANDARD || NETCOREAPP - var hostTask = Dns.GetHostEntryAsync(hostStr); - hostTask.GetAwaiter().GetResult(); - var host = hostTask.Result; -#else - var host = Dns.GetHostEntry(hostStr); -#endif - return host.AddressList; - } - - /// - /// Get all local ip addresses - /// - /// type of address (IPv4, IPv6 or both) - /// List with all local ip addresses - public static List GetLocalIpList(LocalAddrType addrType) - { - List targetList = new List(); - GetLocalIpList(targetList, addrType); - return targetList; - } - - /// - /// Get all local ip addresses (non alloc version) - /// - /// result list - /// type of address (IPv4, IPv6 or both) - public static void GetLocalIpList(IList targetList, LocalAddrType addrType) - { - bool ipv4 = (addrType & LocalAddrType.IPv4) == LocalAddrType.IPv4; - bool ipv6 = (addrType & LocalAddrType.IPv6) == LocalAddrType.IPv6; - try - { - foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) - { - //Skip loopback and disabled network interfaces - if (ni.NetworkInterfaceType == NetworkInterfaceType.Loopback || - ni.OperationalStatus != OperationalStatus.Up) - continue; - - var ipProps = ni.GetIPProperties(); - - //Skip address without gateway - if (ipProps.GatewayAddresses.Count == 0) - continue; - - foreach (UnicastIPAddressInformation ip in ipProps.UnicastAddresses) - { - var address = ip.Address; - if ((ipv4 && address.AddressFamily == AddressFamily.InterNetwork) || - (ipv6 && address.AddressFamily == AddressFamily.InterNetworkV6)) - targetList.Add(address.ToString()); - } - } - } - catch - { - //ignored - } - - //Fallback mode (unity android) - if (targetList.Count == 0) - { - IPAddress[] addresses = ResolveAddresses(Dns.GetHostName()); - foreach (IPAddress ip in addresses) - { - if((ipv4 && ip.AddressFamily == AddressFamily.InterNetwork) || - (ipv6 && ip.AddressFamily == AddressFamily.InterNetworkV6)) - targetList.Add(ip.ToString()); - } - } - if (targetList.Count == 0) - { - if(ipv4) - targetList.Add("127.0.0.1"); - if(ipv6) - targetList.Add("::1"); - } - } - - private static readonly List IpList = new List(); - /// - /// Get first detected local ip address - /// - /// type of address (IPv4, IPv6 or both) - /// IP address if available. Else - string.Empty - public static string GetLocalIp(LocalAddrType addrType) - { - lock (IpList) - { - IpList.Clear(); - GetLocalIpList(IpList, addrType); - return IpList.Count == 0 ? string.Empty : IpList[0]; - } - } - - // =========================================== - // Internal and debug log related stuff - // =========================================== - internal static void PrintInterfaceInfos() - { - NetDebug.WriteForce(NetLogLevel.Info, "IPv6Support: {0}", NetSocket.IPv6Support); - try - { - foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) - { - foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses) - { - if (ip.Address.AddressFamily == AddressFamily.InterNetwork || - ip.Address.AddressFamily == AddressFamily.InterNetworkV6) - { - NetDebug.WriteForce( - NetLogLevel.Info, - "Interface: {0}, Type: {1}, Ip: {2}, OpStatus: {3}", - ni.Name, - ni.NetworkInterfaceType.ToString(), - ip.Address.ToString(), - ni.OperationalStatus.ToString()); - } - } - } - } - catch (Exception e) - { - NetDebug.WriteForce(NetLogLevel.Info, "Error while getting interface infos: {0}", e.ToString()); - } - } - - internal static int RelativeSequenceNumber(int number, int expected) - { - return (number - expected + NetConstants.MaxSequence + NetConstants.HalfMaxSequence) % NetConstants.MaxSequence - NetConstants.HalfMaxSequence; - } - } -} diff --git a/FirServer/Libraries/LiteNetLib/ReliableChannel.cs b/FirServer/Libraries/LiteNetLib/ReliableChannel.cs deleted file mode 100644 index 68e98cce..00000000 --- a/FirServer/Libraries/LiteNetLib/ReliableChannel.cs +++ /dev/null @@ -1,323 +0,0 @@ -using System; - -namespace LiteNetLib -{ - internal sealed class ReliableChannel : BaseChannel - { - private struct PendingPacket - { - private NetPacket _packet; - private long _timeStamp; - private bool _isSent; - - public override string ToString() - { - return _packet == null ? "Empty" : _packet.Sequence.ToString(); - } - - public void Init(NetPacket packet) - { - _packet = packet; - _isSent = false; - } - - public void TrySend(long currentTime, NetPeer peer) - { - if (_packet == null) - return; - if (_isSent) //check send time - { - double resendDelay = peer.ResendDelay * TimeSpan.TicksPerMillisecond; - double packetHoldTime = currentTime - _timeStamp; - if (packetHoldTime < resendDelay) - return; - NetDebug.Write("[RC]Resend: {0} > {1}", (int)packetHoldTime, resendDelay); - } - _timeStamp = currentTime; - _isSent = true; - peer.SendUserData(_packet); - } - - public bool Clear(NetPeer peer) - { - if (_packet != null) - { - peer.RecycleAndDeliver(_packet); - _packet = null; - return true; - } - return false; - } - } - - private readonly NetPacket _outgoingAcks; //for send acks - private readonly PendingPacket[] _pendingPackets; //for unacked packets and duplicates - private readonly NetPacket[] _receivedPackets; //for order - private readonly bool[] _earlyReceived; //for unordered - - private int _localSeqence; - private int _remoteSequence; - private int _localWindowStart; - private int _remoteWindowStart; - - private bool _mustSendAcks; - - private readonly DeliveryMethod _deliveryMethod; - private readonly bool _ordered; - private readonly int _windowSize; - private const int BitsInByte = 8; - private readonly byte _id; - - public ReliableChannel(NetPeer peer, bool ordered, byte id) : base(peer) - { - _id = id; - _windowSize = NetConstants.DefaultWindowSize; - _ordered = ordered; - _pendingPackets = new PendingPacket[_windowSize]; - for (int i = 0; i < _pendingPackets.Length; i++) - _pendingPackets[i] = new PendingPacket(); - - if (_ordered) - { - _deliveryMethod = DeliveryMethod.ReliableOrdered; - _receivedPackets = new NetPacket[_windowSize]; - } - else - { - _deliveryMethod = DeliveryMethod.ReliableUnordered; - _earlyReceived = new bool[_windowSize]; - } - - _localWindowStart = 0; - _localSeqence = 0; - _remoteSequence = 0; - _remoteWindowStart = 0; - _outgoingAcks = new NetPacket(PacketProperty.Ack, (_windowSize - 1) / BitsInByte + 2) {ChannelId = id}; - } - - //ProcessAck in packet - private void ProcessAck(NetPacket packet) - { - if (packet.Size != _outgoingAcks.Size) - { - NetDebug.Write("[PA]Invalid acks packet size"); - return; - } - - ushort ackWindowStart = packet.Sequence; - int windowRel = NetUtils.RelativeSequenceNumber(_localWindowStart, ackWindowStart); - if (ackWindowStart >= NetConstants.MaxSequence || windowRel < 0) - { - NetDebug.Write("[PA]Bad window start"); - return; - } - - //check relevance - if (windowRel >= _windowSize) - { - NetDebug.Write("[PA]Old acks"); - return; - } - - byte[] acksData = packet.RawData; - lock (_pendingPackets) - { - for (int pendingSeq = _localWindowStart; - pendingSeq != _localSeqence; - pendingSeq = (pendingSeq + 1) % NetConstants.MaxSequence) - { - int rel = NetUtils.RelativeSequenceNumber(pendingSeq, ackWindowStart); - if (rel >= _windowSize) - { - NetDebug.Write("[PA]REL: " + rel); - break; - } - - int pendingIdx = pendingSeq % _windowSize; - int currentByte = NetConstants.ChanneledHeaderSize + pendingIdx / BitsInByte; - int currentBit = pendingIdx % BitsInByte; - if ((acksData[currentByte] & (1 << currentBit)) == 0) - { -#if DEBUG - Peer.Statistics.PacketLoss++; -#else - if (Peer.NetManager.EnableStatistics) - { - Peer.Statistics.PacketLoss++; - } -#endif - - //Skip false ack - NetDebug.Write("[PA]False ack: {0}", pendingSeq); - continue; - } - - if (pendingSeq == _localWindowStart) - { - //Move window - _localWindowStart = (_localWindowStart + 1) % NetConstants.MaxSequence; - } - - //clear packet - if (_pendingPackets[pendingIdx].Clear(Peer)) - NetDebug.Write("[PA]Removing reliableInOrder ack: {0} - true", pendingSeq); - } - } - } - - public override void SendNextPackets() - { - if (_mustSendAcks) - { - _mustSendAcks = false; - NetDebug.Write("[RR]SendAcks"); - lock(_outgoingAcks) - Peer.SendUserData(_outgoingAcks); - } - - long currentTime = DateTime.UtcNow.Ticks; - lock (_pendingPackets) - { - //get packets from queue - lock (OutgoingQueue) - { - while (OutgoingQueue.Count > 0) - { - int relate = NetUtils.RelativeSequenceNumber(_localSeqence, _localWindowStart); - if (relate >= _windowSize) - break; - - var netPacket = OutgoingQueue.Dequeue(); - netPacket.Sequence = (ushort) _localSeqence; - netPacket.ChannelId = _id; - _pendingPackets[_localSeqence % _windowSize].Init(netPacket); - _localSeqence = (_localSeqence + 1) % NetConstants.MaxSequence; - } - } - //send - for (int pendingSeq = _localWindowStart; pendingSeq != _localSeqence; pendingSeq = (pendingSeq + 1) % NetConstants.MaxSequence) - _pendingPackets[pendingSeq % _windowSize].TrySend(currentTime, Peer); - } - } - - //Process incoming packet - public override bool ProcessPacket(NetPacket packet) - { - if (packet.Property == PacketProperty.Ack) - { - ProcessAck(packet); - return false; - } - int seq = packet.Sequence; - if (seq >= NetConstants.MaxSequence) - { - NetDebug.Write("[RR]Bad sequence"); - return false; - } - - int relate = NetUtils.RelativeSequenceNumber(seq, _remoteWindowStart); - int relateSeq = NetUtils.RelativeSequenceNumber(seq, _remoteSequence); - - if (relateSeq > _windowSize) - { - NetDebug.Write("[RR]Bad sequence"); - return false; - } - - //Drop bad packets - if (relate < 0) - { - //Too old packet doesn't ack - NetDebug.Write("[RR]ReliableInOrder too old"); - return false; - } - if (relate >= _windowSize * 2) - { - //Some very new packet - NetDebug.Write("[RR]ReliableInOrder too new"); - return false; - } - - //If very new - move window - int ackIdx; - int ackByte; - int ackBit; - lock (_outgoingAcks) - { - if (relate >= _windowSize) - { - //New window position - int newWindowStart = (_remoteWindowStart + relate - _windowSize + 1) % NetConstants.MaxSequence; - _outgoingAcks.Sequence = (ushort) newWindowStart; - - //Clean old data - while (_remoteWindowStart != newWindowStart) - { - ackIdx = _remoteWindowStart % _windowSize; - ackByte = NetConstants.ChanneledHeaderSize + ackIdx / BitsInByte; - ackBit = ackIdx % BitsInByte; - _outgoingAcks.RawData[ackByte] &= (byte) ~(1 << ackBit); - _remoteWindowStart = (_remoteWindowStart + 1) % NetConstants.MaxSequence; - } - } - - //Final stage - process valid packet - //trigger acks send - _mustSendAcks = true; - ackIdx = seq % _windowSize; - ackByte = NetConstants.ChanneledHeaderSize + ackIdx / BitsInByte; - ackBit = ackIdx % BitsInByte; - if ((_outgoingAcks.RawData[ackByte] & (1 << ackBit)) != 0) - { - NetDebug.Write("[RR]ReliableInOrder duplicate"); - return false; - } - - //save ack - _outgoingAcks.RawData[ackByte] |= (byte) (1 << ackBit); - } - - //detailed check - if (seq == _remoteSequence) - { - NetDebug.Write("[RR]ReliableInOrder packet succes"); - Peer.AddReliablePacket(_deliveryMethod, packet); - _remoteSequence = (_remoteSequence + 1) % NetConstants.MaxSequence; - - if (_ordered) - { - NetPacket p; - while ((p = _receivedPackets[_remoteSequence % _windowSize]) != null) - { - //process holden packet - _receivedPackets[_remoteSequence % _windowSize] = null; - Peer.AddReliablePacket(_deliveryMethod, p); - _remoteSequence = (_remoteSequence + 1) % NetConstants.MaxSequence; - } - } - else - { - while (_earlyReceived[_remoteSequence % _windowSize]) - { - //process early packet - _earlyReceived[_remoteSequence % _windowSize] = false; - _remoteSequence = (_remoteSequence + 1) % NetConstants.MaxSequence; - } - } - return true; - } - - //holden packet - if (_ordered) - { - _receivedPackets[ackIdx] = packet; - } - else - { - _earlyReceived[ackIdx] = true; - Peer.AddReliablePacket(_deliveryMethod, packet); - } - return true; - } - } -} \ No newline at end of file diff --git a/FirServer/Libraries/LiteNetLib/SequencedChannel.cs b/FirServer/Libraries/LiteNetLib/SequencedChannel.cs deleted file mode 100644 index c5e38976..00000000 --- a/FirServer/Libraries/LiteNetLib/SequencedChannel.cs +++ /dev/null @@ -1,98 +0,0 @@ -using System; - -namespace LiteNetLib -{ - internal sealed class SequencedChannel : BaseChannel - { - private int _localSequence; - private ushort _remoteSequence; - private readonly bool _reliable; - private NetPacket _lastPacket; - private readonly NetPacket _ackPacket; - private bool _mustSendAck; - private readonly byte _id; - private long _lastPacketSendTime; - - public SequencedChannel(NetPeer peer, bool reliable, byte id) : base(peer) - { - _id = id; - _reliable = reliable; - if (_reliable) - _ackPacket = new NetPacket(PacketProperty.Ack, 0) {ChannelId = id}; - } - - public override void SendNextPackets() - { - if (_reliable && OutgoingQueue.Count == 0) - { - long currentTime = DateTime.UtcNow.Ticks; - long packetHoldTime = currentTime - _lastPacketSendTime; - if (packetHoldTime < Peer.ResendDelay * TimeSpan.TicksPerMillisecond) - return; - var packet = _lastPacket; - if (packet != null) - { - _lastPacketSendTime = currentTime; - Peer.SendUserData(packet); - } - } - else - { - lock (OutgoingQueue) - { - while (OutgoingQueue.Count > 0) - { - NetPacket packet = OutgoingQueue.Dequeue(); - _localSequence = (_localSequence + 1) % NetConstants.MaxSequence; - packet.Sequence = (ushort)_localSequence; - packet.ChannelId = _id; - Peer.SendUserData(packet); - - if (_reliable && OutgoingQueue.Count == 0) - { - _lastPacketSendTime = DateTime.UtcNow.Ticks; - _lastPacket = packet; - } - else - { - Peer.NetManager.NetPacketPool.Recycle(packet); - } - } - } - } - - if (_reliable && _mustSendAck) - { - _mustSendAck = false; - _ackPacket.Sequence = _remoteSequence; - Peer.SendUserData(_ackPacket); - } - } - - public override bool ProcessPacket(NetPacket packet) - { - if (packet.IsFragmented) - return false; - if (packet.Property == PacketProperty.Ack) - { - if (_reliable && _lastPacket != null && packet.Sequence == _lastPacket.Sequence) - _lastPacket = null; - return false; - } - int relative = NetUtils.RelativeSequenceNumber(packet.Sequence, _remoteSequence); - bool packetProcessed = false; - if (packet.Sequence < NetConstants.MaxSequence && relative > 0) - { - Peer.Statistics.PacketLoss += (ulong)(relative - 1); - _remoteSequence = packet.Sequence; - Peer.NetManager.CreateReceiveEvent( - packet, - _reliable ? DeliveryMethod.ReliableSequenced : DeliveryMethod.Sequenced, - Peer); - packetProcessed = true; - } - _mustSendAck = true; - return packetProcessed; - } - } -} diff --git a/FirServer/Libraries/LiteNetLib/Utils/CRC32C.cs b/FirServer/Libraries/LiteNetLib/Utils/CRC32C.cs deleted file mode 100644 index 0d993eb3..00000000 --- a/FirServer/Libraries/LiteNetLib/Utils/CRC32C.cs +++ /dev/null @@ -1,96 +0,0 @@ -#if NETCOREAPP3_0 -using System; -using System.Runtime.Intrinsics.X86; -#endif - -namespace LiteNetLib.Utils -{ - //Implementation from Crc32.NET - public static class CRC32C - { - public const int ChecksumSize = 4; - private const uint Poly = 0x82F63B78u; - private static readonly uint[] Table; - - static CRC32C() - { -#if NETCOREAPP3_0 - if(Sse42.IsSupported) - return; -#endif - Table = new uint[16 * 256]; - for (uint i = 0; i < 256; i++) - { - uint res = i; - for (int t = 0; t < 16; t++) - { - for (int k = 0; k < 8; k++) - res = (res & 1) == 1 ? Poly ^ (res >> 1) : (res >> 1); - Table[t * 256 + i] = res; - } - } - } - - /// - /// Compute CRC32C for data - /// - /// input data - /// offset - /// length - /// CRC32C checksum - public static uint Compute(byte[] input, int offset, int length) - { - uint crcLocal = uint.MaxValue; -#if NETCOREAPP3_0 - if(Sse42.IsSupported) - { - if (Sse42.X64.IsSupported) - { - while (length >= 8) - { - crcLocal = (uint)Sse42.X64.Crc32(crcLocal, BitConverter.ToUInt64(input, offset)); - offset += 8; - length -= 8; - } - } - while (length > 0) - { - crcLocal = Sse42.Crc32(crcLocal, input[offset]); - offset++; - length--; - } - return crcLocal ^ uint.MaxValue; - } -#endif - while (length >= 16) - { - var a = Table[(3 * 256) + input[offset + 12]] - ^ Table[(2 * 256) + input[offset + 13]] - ^ Table[(1 * 256) + input[offset + 14]] - ^ Table[(0 * 256) + input[offset + 15]]; - - var b = Table[(7 * 256) + input[offset + 8]] - ^ Table[(6 * 256) + input[offset + 9]] - ^ Table[(5 * 256) + input[offset + 10]] - ^ Table[(4 * 256) + input[offset + 11]]; - - var c = Table[(11 * 256) + input[offset + 4]] - ^ Table[(10 * 256) + input[offset + 5]] - ^ Table[(9 * 256) + input[offset + 6]] - ^ Table[(8 * 256) + input[offset + 7]]; - - var d = Table[(15 * 256) + ((byte)crcLocal ^ input[offset])] - ^ Table[(14 * 256) + ((byte)(crcLocal >> 8) ^ input[offset + 1])] - ^ Table[(13 * 256) + ((byte)(crcLocal >> 16) ^ input[offset + 2])] - ^ Table[(12 * 256) + ((crcLocal >> 24) ^ input[offset + 3])]; - - crcLocal = d ^ c ^ b ^ a; - offset += 16; - length -= 16; - } - while (--length >= 0) - crcLocal = Table[(byte)(crcLocal ^ input[offset++])] ^ crcLocal >> 8; - return crcLocal ^ uint.MaxValue; - } - } -} diff --git a/FirServer/Libraries/LiteNetLib/Utils/FastBitConverter.cs b/FirServer/Libraries/LiteNetLib/Utils/FastBitConverter.cs deleted file mode 100644 index 3693a027..00000000 --- a/FirServer/Libraries/LiteNetLib/Utils/FastBitConverter.cs +++ /dev/null @@ -1,118 +0,0 @@ -using System.Runtime.InteropServices; - -namespace LiteNetLib.Utils -{ - public static class FastBitConverter - { - [StructLayout(LayoutKind.Explicit)] - private struct ConverterHelperDouble - { - [FieldOffset(0)] - public ulong Along; - - [FieldOffset(0)] - public double Adouble; - } - - [StructLayout(LayoutKind.Explicit)] - private struct ConverterHelperFloat - { - [FieldOffset(0)] - public int Aint; - - [FieldOffset(0)] - public float Afloat; - } - - private static void WriteLittleEndian(byte[] buffer, int offset, ulong data) - { -#if BIGENDIAN - buffer[offset + 7] = (byte)(data); - buffer[offset + 6] = (byte)(data >> 8); - buffer[offset + 5] = (byte)(data >> 16); - buffer[offset + 4] = (byte)(data >> 24); - buffer[offset + 3] = (byte)(data >> 32); - buffer[offset + 2] = (byte)(data >> 40); - buffer[offset + 1] = (byte)(data >> 48); - buffer[offset ] = (byte)(data >> 56); -#else - buffer[offset] = (byte)(data); - buffer[offset + 1] = (byte)(data >> 8); - buffer[offset + 2] = (byte)(data >> 16); - buffer[offset + 3] = (byte)(data >> 24); - buffer[offset + 4] = (byte)(data >> 32); - buffer[offset + 5] = (byte)(data >> 40); - buffer[offset + 6] = (byte)(data >> 48); - buffer[offset + 7] = (byte)(data >> 56); -#endif - } - - private static void WriteLittleEndian(byte[] buffer, int offset, int data) - { -#if BIGENDIAN - buffer[offset + 3] = (byte)(data); - buffer[offset + 2] = (byte)(data >> 8); - buffer[offset + 1] = (byte)(data >> 16); - buffer[offset ] = (byte)(data >> 24); -#else - buffer[offset] = (byte)(data); - buffer[offset + 1] = (byte)(data >> 8); - buffer[offset + 2] = (byte)(data >> 16); - buffer[offset + 3] = (byte)(data >> 24); -#endif - } - - public static void WriteLittleEndian(byte[] buffer, int offset, short data) - { -#if BIGENDIAN - buffer[offset + 1] = (byte)(data); - buffer[offset ] = (byte)(data >> 8); -#else - buffer[offset] = (byte)(data); - buffer[offset + 1] = (byte)(data >> 8); -#endif - } - - public static void GetBytes(byte[] bytes, int startIndex, double value) - { - ConverterHelperDouble ch = new ConverterHelperDouble { Adouble = value }; - WriteLittleEndian(bytes, startIndex, ch.Along); - } - - public static void GetBytes(byte[] bytes, int startIndex, float value) - { - ConverterHelperFloat ch = new ConverterHelperFloat { Afloat = value }; - WriteLittleEndian(bytes, startIndex, ch.Aint); - } - - public static void GetBytes(byte[] bytes, int startIndex, short value) - { - WriteLittleEndian(bytes, startIndex, value); - } - - public static void GetBytes(byte[] bytes, int startIndex, ushort value) - { - WriteLittleEndian(bytes, startIndex, (short)value); - } - - public static void GetBytes(byte[] bytes, int startIndex, int value) - { - WriteLittleEndian(bytes, startIndex, value); - } - - public static void GetBytes(byte[] bytes, int startIndex, uint value) - { - WriteLittleEndian(bytes, startIndex, (int)value); - } - - public static void GetBytes(byte[] bytes, int startIndex, long value) - { - WriteLittleEndian(bytes, startIndex, (ulong)value); - } - - public static void GetBytes(byte[] bytes, int startIndex, ulong value) - { - WriteLittleEndian(bytes, startIndex, value); - } - } -} diff --git a/FirServer/Libraries/LiteNetLib/Utils/INetSerializable.cs b/FirServer/Libraries/LiteNetLib/Utils/INetSerializable.cs deleted file mode 100644 index 92f14bee..00000000 --- a/FirServer/Libraries/LiteNetLib/Utils/INetSerializable.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace LiteNetLib.Utils -{ - public interface INetSerializable - { - void Serialize(NetDataWriter writer); - void Deserialize(NetDataReader reader); - } -} diff --git a/FirServer/Libraries/LiteNetLib/Utils/NetDataReader.cs b/FirServer/Libraries/LiteNetLib/Utils/NetDataReader.cs deleted file mode 100644 index 60c29f19..00000000 --- a/FirServer/Libraries/LiteNetLib/Utils/NetDataReader.cs +++ /dev/null @@ -1,694 +0,0 @@ -using System; -using System.Net; -using System.Text; - -namespace LiteNetLib.Utils -{ - public class NetDataReader - { - protected byte[] _data; - protected int _position; - protected int _dataSize; - private int _offset; - - public byte[] RawData - { - get { return _data; } - } - - public int RawDataSize - { - get { return _dataSize; } - } - - public int UserDataOffset - { - get { return _offset; } - } - - public int UserDataSize - { - get { return _dataSize - _offset; } - } - - public bool IsNull - { - get { return _data == null; } - } - - public int Position - { - get { return _position; } - } - - public bool EndOfData - { - get { return _position == _dataSize; } - } - - public int AvailableBytes - { - get { return _dataSize - _position; } - } - - public void SkipBytes(int count) - { - _position += count; - } - - public void SetSource(NetDataWriter dataWriter) - { - _data = dataWriter.Data; - _position = 0; - _offset = 0; - _dataSize = dataWriter.Length; - } - - public void SetSource(byte[] source) - { - _data = source; - _position = 0; - _offset = 0; - _dataSize = source.Length; - } - - public void SetSource(byte[] source, int offset) - { - _data = source; - _position = offset; - _offset = offset; - _dataSize = source.Length; - } - - public void SetSource(byte[] source, int offset, int maxSize) - { - _data = source; - _position = offset; - _offset = offset; - _dataSize = maxSize; - } - - public NetDataReader() - { - - } - - public NetDataReader(NetDataWriter writer) - { - SetSource(writer); - } - - public NetDataReader(byte[] source) - { - SetSource(source); - } - - public NetDataReader(byte[] source, int offset) - { - SetSource(source, offset); - } - - public NetDataReader(byte[] source, int offset, int maxSize) - { - SetSource(source, offset, maxSize); - } - - #region GetMethods - public IPEndPoint GetNetEndPoint() - { - string host = GetString(1000); - int port = GetInt(); - return NetUtils.MakeEndPoint(host, port); - } - - public byte GetByte() - { - byte res = _data[_position]; - _position += 1; - return res; - } - - public sbyte GetSByte() - { - var b = (sbyte)_data[_position]; - _position++; - return b; - } - - public bool[] GetBoolArray() - { - ushort size = BitConverter.ToUInt16(_data, _position); - _position += 2; - var arr = new bool[size]; - Buffer.BlockCopy(_data, _position, arr, 0, size); - _position += size; - return arr; - } - - public ushort[] GetUShortArray() - { - ushort size = BitConverter.ToUInt16(_data, _position); - _position += 2; - var arr = new ushort[size]; - Buffer.BlockCopy(_data, _position, arr, 0, size * 2); - _position += size * 2; - return arr; - } - - public short[] GetShortArray() - { - ushort size = BitConverter.ToUInt16(_data, _position); - _position += 2; - var arr = new short[size]; - Buffer.BlockCopy(_data, _position, arr, 0, size * 2); - _position += size * 2; - return arr; - } - - public long[] GetLongArray() - { - ushort size = BitConverter.ToUInt16(_data, _position); - _position += 2; - var arr = new long[size]; - Buffer.BlockCopy(_data, _position, arr, 0, size * 8); - _position += size * 8; - return arr; - } - - public ulong[] GetULongArray() - { - ushort size = BitConverter.ToUInt16(_data, _position); - _position += 2; - var arr = new ulong[size]; - Buffer.BlockCopy(_data, _position, arr, 0, size * 8); - _position += size * 8; - return arr; - } - - public int[] GetIntArray() - { - ushort size = BitConverter.ToUInt16(_data, _position); - _position += 2; - var arr = new int[size]; - Buffer.BlockCopy(_data, _position, arr, 0, size * 4); - _position += size * 4; - return arr; - } - - public uint[] GetUIntArray() - { - ushort size = BitConverter.ToUInt16(_data, _position); - _position += 2; - var arr = new uint[size]; - Buffer.BlockCopy(_data, _position, arr, 0, size * 4); - _position += size * 4; - return arr; - } - - public float[] GetFloatArray() - { - ushort size = BitConverter.ToUInt16(_data, _position); - _position += 2; - var arr = new float[size]; - Buffer.BlockCopy(_data, _position, arr, 0, size * 4); - _position += size * 4; - return arr; - } - - public double[] GetDoubleArray() - { - ushort size = BitConverter.ToUInt16(_data, _position); - _position += 2; - var arr = new double[size]; - Buffer.BlockCopy(_data, _position, arr, 0, size * 8); - _position += size * 8; - return arr; - } - - public string[] GetStringArray() - { - ushort size = BitConverter.ToUInt16(_data, _position); - _position += 2; - var arr = new string[size]; - for (int i = 0; i < size; i++) - { - arr[i] = GetString(); - } - return arr; - } - - public string[] GetStringArray(int maxStringLength) - { - ushort size = BitConverter.ToUInt16(_data, _position); - _position += 2; - var arr = new string[size]; - for (int i = 0; i < size; i++) - { - arr[i] = GetString(maxStringLength); - } - return arr; - } - - public bool GetBool() - { - bool res = _data[_position] > 0; - _position += 1; - return res; - } - - public char GetChar() - { - char result = BitConverter.ToChar(_data, _position); - _position += 2; - return result; - } - - public ushort GetUShort() - { - ushort result = BitConverter.ToUInt16(_data, _position); - _position += 2; - return result; - } - - public short GetShort() - { - short result = BitConverter.ToInt16(_data, _position); - _position += 2; - return result; - } - - public long GetLong() - { - long result = BitConverter.ToInt64(_data, _position); - _position += 8; - return result; - } - - public ulong GetULong() - { - ulong result = BitConverter.ToUInt64(_data, _position); - _position += 8; - return result; - } - - public int GetInt() - { - int result = BitConverter.ToInt32(_data, _position); - _position += 4; - return result; - } - - public uint GetUInt() - { - uint result = BitConverter.ToUInt32(_data, _position); - _position += 4; - return result; - } - - public float GetFloat() - { - float result = BitConverter.ToSingle(_data, _position); - _position += 4; - return result; - } - - public double GetDouble() - { - double result = BitConverter.ToDouble(_data, _position); - _position += 8; - return result; - } - - public string GetString(int maxLength) - { - int bytesCount = GetInt(); - if (bytesCount <= 0 || bytesCount > maxLength*2) - { - return string.Empty; - } - - int charCount = Encoding.UTF8.GetCharCount(_data, _position, bytesCount); - if (charCount > maxLength) - { - return string.Empty; - } - - string result = Encoding.UTF8.GetString(_data, _position, bytesCount); - _position += bytesCount; - return result; - } - - public string GetString() - { - int bytesCount = GetInt(); - if (bytesCount <= 0) - { - return string.Empty; - } - - string result = Encoding.UTF8.GetString(_data, _position, bytesCount); - _position += bytesCount; - return result; - } - - public ArraySegment GetRemainingBytesSegment() - { - ArraySegment segment = new ArraySegment(_data, _position, AvailableBytes); - _position = _data.Length; - return segment; - } - - public T Get() where T : INetSerializable, new() - { - var obj = new T(); - obj.Deserialize(this); - return obj; - } - - public byte[] GetRemainingBytes() - { - byte[] outgoingData = new byte[AvailableBytes]; - Buffer.BlockCopy(_data, _position, outgoingData, 0, AvailableBytes); - _position = _data.Length; - return outgoingData; - } - - public void GetBytes(byte[] destination, int start, int count) - { - Buffer.BlockCopy(_data, _position, destination, start, count); - _position += count; - } - - public void GetBytes(byte[] destination, int count) - { - Buffer.BlockCopy(_data, _position, destination, 0, count); - _position += count; - } - - public sbyte[] GetSBytesWithLength() - { - int length = GetInt(); - sbyte[] outgoingData = new sbyte[length]; - Buffer.BlockCopy(_data, _position, outgoingData, 0, length); - _position += length; - return outgoingData; - } - - public byte[] GetBytesWithLength() - { - int length = GetInt(); - byte[] outgoingData = new byte[length]; - Buffer.BlockCopy(_data, _position, outgoingData, 0, length); - _position += length; - return outgoingData; - } - #endregion - - #region PeekMethods - - public byte PeekByte() - { - return _data[_position]; - } - - public sbyte PeekSByte() - { - return (sbyte)_data[_position]; - } - - public bool PeekBool() - { - return _data[_position] > 0; - } - - public char PeekChar() - { - return BitConverter.ToChar(_data, _position); - } - - public ushort PeekUShort() - { - return BitConverter.ToUInt16(_data, _position); - } - - public short PeekShort() - { - return BitConverter.ToInt16(_data, _position); - } - - public long PeekLong() - { - return BitConverter.ToInt64(_data, _position); - } - - public ulong PeekULong() - { - return BitConverter.ToUInt64(_data, _position); - } - - public int PeekInt() - { - return BitConverter.ToInt32(_data, _position); - } - - public uint PeekUInt() - { - return BitConverter.ToUInt32(_data, _position); - } - - public float PeekFloat() - { - return BitConverter.ToSingle(_data, _position); - } - - public double PeekDouble() - { - return BitConverter.ToDouble(_data, _position); - } - - public string PeekString(int maxLength) - { - int bytesCount = BitConverter.ToInt32(_data, _position); - if (bytesCount <= 0 || bytesCount > maxLength * 2) - { - return string.Empty; - } - - int charCount = Encoding.UTF8.GetCharCount(_data, _position + 4, bytesCount); - if (charCount > maxLength) - { - return string.Empty; - } - - string result = Encoding.UTF8.GetString(_data, _position + 4, bytesCount); - return result; - } - - public string PeekString() - { - int bytesCount = BitConverter.ToInt32(_data, _position); - if (bytesCount <= 0) - { - return string.Empty; - } - - string result = Encoding.UTF8.GetString(_data, _position + 4, bytesCount); - return result; - } - #endregion - - #region TryGetMethods - public bool TryGetByte(out byte result) - { - if (AvailableBytes >= 1) - { - result = GetByte(); - return true; - } - result = 0; - return false; - } - - public bool TryGetSByte(out sbyte result) - { - if (AvailableBytes >= 1) - { - result = GetSByte(); - return true; - } - result = 0; - return false; - } - - public bool TryGetBool(out bool result) - { - if (AvailableBytes >= 1) - { - result = GetBool(); - return true; - } - result = false; - return false; - } - - public bool TryGetChar(out char result) - { - if (AvailableBytes >= 2) - { - result = GetChar(); - return true; - } - result = '\0'; - return false; - } - - public bool TryGetShort(out short result) - { - if (AvailableBytes >= 2) - { - result = GetShort(); - return true; - } - result = 0; - return false; - } - - public bool TryGetUShort(out ushort result) - { - if (AvailableBytes >= 2) - { - result = GetUShort(); - return true; - } - result = 0; - return false; - } - - public bool TryGetInt(out int result) - { - if (AvailableBytes >= 4) - { - result = GetInt(); - return true; - } - result = 0; - return false; - } - - public bool TryGetUInt(out uint result) - { - if (AvailableBytes >= 4) - { - result = GetUInt(); - return true; - } - result = 0; - return false; - } - - public bool TryGetLong(out long result) - { - if (AvailableBytes >= 8) - { - result = GetLong(); - return true; - } - result = 0; - return false; - } - - public bool TryGetULong(out ulong result) - { - if (AvailableBytes >= 8) - { - result = GetULong(); - return true; - } - result = 0; - return false; - } - - public bool TryGetFloat(out float result) - { - if (AvailableBytes >= 4) - { - result = GetFloat(); - return true; - } - result = 0; - return false; - } - - public bool TryGetDouble(out double result) - { - if (AvailableBytes >= 8) - { - result = GetDouble(); - return true; - } - result = 0; - return false; - } - - public bool TryGetString(out string result) - { - if (AvailableBytes >= 4) - { - var bytesCount = PeekInt(); - if (AvailableBytes >= bytesCount + 4) - { - result = GetString(); - return true; - } - } - result = null; - return false; - } - - public bool TryGetStringArray(out string[] result) - { - ushort size; - if (!TryGetUShort(out size)) - { - result = null; - return false; - } - - result = new string[size]; - for (int i = 0; i < size; i++) - { - if (!TryGetString(out result[i])) - { - result = null; - return false; - } - } - - return true; - } - - public bool TryGetBytesWithLength(out byte[] result) - { - if (AvailableBytes >= 4) - { - var length = PeekInt(); - if (length >= 0 && AvailableBytes >= length + 4) - { - result = GetBytesWithLength(); - return true; - } - } - result = null; - return false; - } - #endregion - - public void Clear() - { - _position = 0; - _dataSize = 0; - _data = null; - } - } -} - diff --git a/FirServer/Libraries/LiteNetLib/Utils/NetDataWriter.cs b/FirServer/Libraries/LiteNetLib/Utils/NetDataWriter.cs deleted file mode 100644 index 4f4f855f..00000000 --- a/FirServer/Libraries/LiteNetLib/Utils/NetDataWriter.cs +++ /dev/null @@ -1,382 +0,0 @@ -using System; -using System.Net; -using System.Text; - -namespace LiteNetLib.Utils -{ - public class NetDataWriter - { - protected byte[] _data; - protected int _position; - private const int InitialSize = 64; - private readonly bool _autoResize; - - public int Capacity - { - get { return _data.Length; } - } - - public NetDataWriter() : this(true, InitialSize) - { - } - - public NetDataWriter(bool autoResize) : this(autoResize, InitialSize) - { - } - - public NetDataWriter(bool autoResize, int initialSize) - { - _data = new byte[initialSize]; - _autoResize = autoResize; - } - - /// - /// Creates NetDataWriter from existing ByteArray - /// - /// Source byte array - /// Copy array to new location or use existing - public static NetDataWriter FromBytes(byte[] bytes, bool copy) - { - if (copy) - { - var netDataWriter = new NetDataWriter(true, bytes.Length); - netDataWriter.Put(bytes); - return netDataWriter; - } - return new NetDataWriter(true, 0) {_data = bytes}; - } - - /// - /// Creates NetDataWriter from existing ByteArray (always copied data) - /// - /// Source byte array - /// Offset of array - /// Length of array - public static NetDataWriter FromBytes(byte[] bytes, int offset, int length) - { - var netDataWriter = new NetDataWriter(true, bytes.Length); - netDataWriter.Put(bytes, offset, length); - return netDataWriter; - } - - public static NetDataWriter FromString(string value) - { - var netDataWriter = new NetDataWriter(); - netDataWriter.Put(value); - return netDataWriter; - } - - public void ResizeIfNeed(int newSize) - { - int len = _data.Length; - if (len < newSize) - { - while (len < newSize) - len *= 2; - Array.Resize(ref _data, len); - } - } - - public void Reset(int size) - { - ResizeIfNeed(size); - _position = 0; - } - - public void Reset() - { - _position = 0; - } - - public byte[] CopyData() - { - byte[] resultData = new byte[_position]; - Buffer.BlockCopy(_data, 0, resultData, 0, _position); - return resultData; - } - - public byte[] Data - { - get { return _data; } - } - - public int Length - { - get { return _position; } - } - - public void Put(float value) - { - if (_autoResize) - ResizeIfNeed(_position + 4); - FastBitConverter.GetBytes(_data, _position, value); - _position += 4; - } - - public void Put(double value) - { - if (_autoResize) - ResizeIfNeed(_position + 8); - FastBitConverter.GetBytes(_data, _position, value); - _position += 8; - } - - public void Put(long value) - { - if (_autoResize) - ResizeIfNeed(_position + 8); - FastBitConverter.GetBytes(_data, _position, value); - _position += 8; - } - - public void Put(ulong value) - { - if (_autoResize) - ResizeIfNeed(_position + 8); - FastBitConverter.GetBytes(_data, _position, value); - _position += 8; - } - - public void Put(int value) - { - if (_autoResize) - ResizeIfNeed(_position + 4); - FastBitConverter.GetBytes(_data, _position, value); - _position += 4; - } - - public void Put(uint value) - { - if (_autoResize) - ResizeIfNeed(_position + 4); - FastBitConverter.GetBytes(_data, _position, value); - _position += 4; - } - - public void Put(char value) - { - if (_autoResize) - ResizeIfNeed(_position + 2); - FastBitConverter.GetBytes(_data, _position, value); - _position += 2; - } - - public void Put(ushort value) - { - if (_autoResize) - ResizeIfNeed(_position + 2); - FastBitConverter.GetBytes(_data, _position, value); - _position += 2; - } - - public void Put(short value) - { - if (_autoResize) - ResizeIfNeed(_position + 2); - FastBitConverter.GetBytes(_data, _position, value); - _position += 2; - } - - public void Put(sbyte value) - { - if (_autoResize) - ResizeIfNeed(_position + 1); - _data[_position] = (byte)value; - _position++; - } - - public void Put(byte value) - { - if (_autoResize) - ResizeIfNeed(_position + 1); - _data[_position] = value; - _position++; - } - - public void Put(byte[] data, int offset, int length) - { - if (_autoResize) - ResizeIfNeed(_position + length); - Buffer.BlockCopy(data, offset, _data, _position, length); - _position += length; - } - - public void Put(byte[] data) - { - if (_autoResize) - ResizeIfNeed(_position + data.Length); - Buffer.BlockCopy(data, 0, _data, _position, data.Length); - _position += data.Length; - } - - public void PutSBytesWithLength(sbyte[] data, int offset, int length) - { - if (_autoResize) - ResizeIfNeed(_position + length + 4); - FastBitConverter.GetBytes(_data, _position, length); - Buffer.BlockCopy(data, offset, _data, _position + 4, length); - _position += length + 4; - } - - public void PutSBytesWithLength(sbyte[] data) - { - if (_autoResize) - ResizeIfNeed(_position + data.Length + 4); - FastBitConverter.GetBytes(_data, _position, data.Length); - Buffer.BlockCopy(data, 0, _data, _position + 4, data.Length); - _position += data.Length + 4; - } - - public void PutBytesWithLength(byte[] data, int offset, int length) - { - if (_autoResize) - ResizeIfNeed(_position + length + 4); - FastBitConverter.GetBytes(_data, _position, length); - Buffer.BlockCopy(data, offset, _data, _position + 4, length); - _position += length + 4; - } - - public void PutBytesWithLength(byte[] data) - { - if (_autoResize) - ResizeIfNeed(_position + data.Length + 4); - FastBitConverter.GetBytes(_data, _position, data.Length); - Buffer.BlockCopy(data, 0, _data, _position + 4, data.Length); - _position += data.Length + 4; - } - - public void Put(bool value) - { - if (_autoResize) - ResizeIfNeed(_position + 1); - _data[_position] = (byte)(value ? 1 : 0); - _position++; - } - - private void PutArray(Array arr, int sz) - { - ushort length = arr == null ? (ushort) 0 : (ushort)arr.Length; - sz *= length; - if (_autoResize) - ResizeIfNeed(_position + sz + 2); - FastBitConverter.GetBytes(_data, _position, length); - if (arr != null) - Buffer.BlockCopy(arr, 0, _data, _position + 2, sz); - _position += sz + 2; - } - - public void PutArray(float[] value) - { - PutArray(value, 4); - } - - public void PutArray(double[] value) - { - PutArray(value, 8); - } - - public void PutArray(long[] value) - { - PutArray(value, 8); - } - - public void PutArray(ulong[] value) - { - PutArray(value, 8); - } - - public void PutArray(int[] value) - { - PutArray(value, 4); - } - - public void PutArray(uint[] value) - { - PutArray(value, 4); - } - - public void PutArray(ushort[] value) - { - PutArray(value, 2); - } - - public void PutArray(short[] value) - { - PutArray(value, 2); - } - - public void PutArray(bool[] value) - { - PutArray(value, 1); - } - - public void PutArray(string[] value) - { - ushort len = value == null ? (ushort)0 : (ushort)value.Length; - Put(len); - for (int i = 0; i < len; i++) - Put(value[i]); - } - - public void PutArray(string[] value, int maxLength) - { - ushort len = value == null ? (ushort)0 : (ushort)value.Length; - Put(len); - for (int i = 0; i < len; i++) - Put(value[i], maxLength); - } - - public void Put(IPEndPoint endPoint) - { - Put(endPoint.Address.ToString()); - Put(endPoint.Port); - } - - public void Put(string value) - { - if (string.IsNullOrEmpty(value)) - { - Put(0); - return; - } - - //put bytes count - int bytesCount = Encoding.UTF8.GetByteCount(value); - if (_autoResize) - ResizeIfNeed(_position + bytesCount + 4); - Put(bytesCount); - - //put string - Encoding.UTF8.GetBytes(value, 0, value.Length, _data, _position); - _position += bytesCount; - } - - public void Put(string value, int maxLength) - { - if (string.IsNullOrEmpty(value)) - { - Put(0); - return; - } - - int length = value.Length > maxLength ? maxLength : value.Length; - //calculate max count - int bytesCount = Encoding.UTF8.GetByteCount(value); - if (_autoResize) - ResizeIfNeed(_position + bytesCount + 4); - - //put bytes count - Put(bytesCount); - - //put string - Encoding.UTF8.GetBytes(value, 0, length, _data, _position); - - _position += bytesCount; - } - - public void Put(T obj) where T : INetSerializable - { - obj.Serialize(this); - } - } -} diff --git a/FirServer/Libraries/LiteNetLib/Utils/NetPacketProcessor.cs b/FirServer/Libraries/LiteNetLib/Utils/NetPacketProcessor.cs deleted file mode 100644 index f77015ed..00000000 --- a/FirServer/Libraries/LiteNetLib/Utils/NetPacketProcessor.cs +++ /dev/null @@ -1,314 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace LiteNetLib.Utils -{ - public class NetPacketProcessor - { - private static class HashCache - { - public static bool Initialized; - public static ulong Id; - } - - protected delegate void SubscribeDelegate(NetDataReader reader, object userData); - private readonly NetSerializer _netSerializer; - private readonly Dictionary _callbacks = new Dictionary(); - private readonly NetDataWriter _netDataWriter = new NetDataWriter(); - - public NetPacketProcessor() - { - _netSerializer = new NetSerializer(); - } - - public NetPacketProcessor(int maxStringLength) - { - _netSerializer = new NetSerializer(maxStringLength); - } - - //FNV-1 64 bit hash - protected virtual ulong GetHash() - { - if(HashCache.Initialized) - return HashCache.Id; - - ulong hash = 14695981039346656037UL; //offset - string typeName = typeof(T).FullName; - for (var i = 0; i < typeName.Length; i++) - { - hash = hash ^ typeName[i]; - hash *= 1099511628211UL; //prime - } - HashCache.Initialized = true; - HashCache.Id = hash; - return hash; - } - - protected virtual SubscribeDelegate GetCallbackFromData(NetDataReader reader) - { - var hash = reader.GetULong(); - SubscribeDelegate action; - if (!_callbacks.TryGetValue(hash, out action)) - { - throw new ParseException("Undefined packet in NetDataReader"); - } - return action; - } - - protected virtual void WriteHash(NetDataWriter writer) - { - writer.Put(GetHash()); - } - - /// - /// Register nested property type - /// - /// INetSerializable structure - public void RegisterNestedType() where T : struct, INetSerializable - { - _netSerializer.RegisterNestedType(); - } - - /// - /// Register nested property type - /// - /// - /// - public void RegisterNestedType(Action writeDelegate, Func readDelegate) - { - _netSerializer.RegisterNestedType(writeDelegate, readDelegate); - } - - /// - /// Register nested property type - /// - /// INetSerializable class - public void RegisterNestedType(Func constructor) where T : class, INetSerializable - { - _netSerializer.RegisterNestedType(constructor); - } - - /// - /// Reads all available data from NetDataReader and calls OnReceive delegates - /// - /// NetDataReader with packets data - public void ReadAllPackets(NetDataReader reader) - { - while (reader.AvailableBytes > 0) - ReadPacket(reader); - } - - /// - /// Reads all available data from NetDataReader and calls OnReceive delegates - /// - /// NetDataReader with packets data - /// Argument that passed to OnReceivedEvent - /// Malformed packet - public void ReadAllPackets(NetDataReader reader, object userData) - { - while (reader.AvailableBytes > 0) - ReadPacket(reader, userData); - } - - /// - /// Reads one packet from NetDataReader and calls OnReceive delegate - /// - /// NetDataReader with packet - /// Malformed packet - public void ReadPacket(NetDataReader reader) - { - ReadPacket(reader, null); - } - - public void Send(NetPeer peer, T packet, DeliveryMethod options) where T : class, new() - { - _netDataWriter.Reset(); - Write(_netDataWriter, packet); - peer.Send(_netDataWriter, options); - } - - public void SendNetSerializable(NetPeer peer, T packet, DeliveryMethod options) where T : INetSerializable - { - _netDataWriter.Reset(); - WriteNetSerializable(_netDataWriter, packet); - peer.Send(_netDataWriter, options); - } - - public void Send(NetManager manager, T packet, DeliveryMethod options) where T : class, new() - { - _netDataWriter.Reset(); - Write(_netDataWriter, packet); - manager.SendToAll(_netDataWriter, options); - } - - public void SendNetSerializable(NetManager manager, T packet, DeliveryMethod options) where T : INetSerializable - { - _netDataWriter.Reset(); - WriteNetSerializable(_netDataWriter, packet); - manager.SendToAll(_netDataWriter, options); - } - - public void Write(NetDataWriter writer, T packet) where T : class, new() - { - WriteHash(writer); - _netSerializer.Serialize(writer, packet); - } - - public void WriteNetSerializable(NetDataWriter writer, T packet) where T : INetSerializable - { - WriteHash(writer); - packet.Serialize(writer); - } - - public byte[] Write(T packet) where T : class, new() - { - _netDataWriter.Reset(); - WriteHash(_netDataWriter); - _netSerializer.Serialize(_netDataWriter, packet); - return _netDataWriter.CopyData(); - } - - public byte[] WriteNetSerializable(T packet) where T : INetSerializable - { - _netDataWriter.Reset(); - WriteHash(_netDataWriter); - packet.Serialize(_netDataWriter); - return _netDataWriter.CopyData(); - } - - /// - /// Reads one packet from NetDataReader and calls OnReceive delegate - /// - /// NetDataReader with packet - /// Argument that passed to OnReceivedEvent - /// Malformed packet - public void ReadPacket(NetDataReader reader, object userData) - { - GetCallbackFromData(reader)(reader, userData); - } - - /// - /// Register and subscribe to packet receive event - /// - /// event that will be called when packet deserialized with ReadPacket method - /// Method that constructs packet instead of slow Activator.CreateInstance - /// 's fields are not supported, or it has no fields - public void Subscribe(Action onReceive, Func packetConstructor) where T : class, new() - { - _netSerializer.Register(); - _callbacks[GetHash()] = (reader, userData) => - { - var reference = packetConstructor(); - _netSerializer.Deserialize(reader, reference); - onReceive(reference); - }; - } - - /// - /// Register and subscribe to packet receive event (with userData) - /// - /// event that will be called when packet deserialized with ReadPacket method - /// Method that constructs packet instead of slow Activator.CreateInstance - /// 's fields are not supported, or it has no fields - public void Subscribe(Action onReceive, Func packetConstructor) where T : class, new() - { - _netSerializer.Register(); - _callbacks[GetHash()] = (reader, userData) => - { - var reference = packetConstructor(); - _netSerializer.Deserialize(reader, reference); - onReceive(reference, (TUserData)userData); - }; - } - - /// - /// Register and subscribe to packet receive event - /// This method will overwrite last received packet class on receive (less garbage) - /// - /// event that will be called when packet deserialized with ReadPacket method - /// 's fields are not supported, or it has no fields - public void SubscribeReusable(Action onReceive) where T : class, new() - { - _netSerializer.Register(); - var reference = new T(); - _callbacks[GetHash()] = (reader, userData) => - { - _netSerializer.Deserialize(reader, reference); - onReceive(reference); - }; - } - - /// - /// Register and subscribe to packet receive event - /// This method will overwrite last received packet class on receive (less garbage) - /// - /// event that will be called when packet deserialized with ReadPacket method - /// 's fields are not supported, or it has no fields - public void SubscribeReusable(Action onReceive) where T : class, new() - { - _netSerializer.Register(); - var reference = new T(); - _callbacks[GetHash()] = (reader, userData) => - { - _netSerializer.Deserialize(reader, reference); - onReceive(reference, (TUserData)userData); - }; - } - - public void SubscribeNetSerializable( - Action onReceive, - Func packetConstructor) where T : INetSerializable - { - _callbacks[GetHash()] = (reader, userData) => - { - var pkt = packetConstructor(); - pkt.Deserialize(reader); - onReceive(pkt, (TUserData)userData); - }; - } - - public void SubscribeNetSerializable( - Action onReceive, - Func packetConstructor) where T : INetSerializable - { - _callbacks[GetHash()] = (reader, userData) => - { - var pkt = packetConstructor(); - pkt.Deserialize(reader); - onReceive(pkt); - }; - } - - public void SubscribeNetSerializable( - Action onReceive) where T : INetSerializable, new() - { - var reference = new T(); - _callbacks[GetHash()] = (reader, userData) => - { - reference.Deserialize(reader); - onReceive(reference, (TUserData)userData); - }; - } - - public void SubscribeNetSerializable( - Action onReceive) where T : INetSerializable, new() - { - var reference = new T(); - _callbacks[GetHash()] = (reader, userData) => - { - reference.Deserialize(reader); - onReceive(reference); - }; - } - - /// - /// Remove any subscriptions by type - /// - /// Packet type - /// true if remove is success - public bool RemoveSubscription() - { - return _callbacks.Remove(GetHash()); - } - } -} diff --git a/FirServer/Libraries/LiteNetLib/Utils/NetSerializer.cs b/FirServer/Libraries/LiteNetLib/Utils/NetSerializer.cs deleted file mode 100644 index 7609248c..00000000 --- a/FirServer/Libraries/LiteNetLib/Utils/NetSerializer.cs +++ /dev/null @@ -1,752 +0,0 @@ -using System; -using System.Reflection; -using System.Collections.Generic; -using System.Net; - -namespace LiteNetLib.Utils -{ - public class InvalidTypeException : ArgumentException - { - public InvalidTypeException(string message) : base(message) { } - } - - public class ParseException : Exception - { - public ParseException(string message) : base(message) { } - } - - public class NetSerializer - { - private enum CallType - { - Basic, - Array, - List - } - - private abstract class FastCall - { - public CallType Type; - public virtual void Init(MethodInfo getMethod, MethodInfo setMethod, CallType type) { Type = type; } - public abstract void Read(T inf, NetDataReader r); - public abstract void Write(T inf, NetDataWriter w); - public abstract void ReadArray(T inf, NetDataReader r); - public abstract void WriteArray(T inf, NetDataWriter w); - public abstract void ReadList(T inf, NetDataReader r); - public abstract void WriteList(T inf, NetDataWriter w); - } - - private abstract class FastCallSpecific : FastCall - { - protected Func Getter; - protected Action Setter; - protected Func GetterArr; - protected Action SetterArr; - protected Func> GetterList; - protected Action> SetterList; - - public override void ReadArray(TClass inf, NetDataReader r) { throw new InvalidTypeException("Unsupported type: " + typeof(TProperty) + "[]"); } - public override void WriteArray(TClass inf, NetDataWriter w) { throw new InvalidTypeException("Unsupported type: " + typeof(TProperty) + "[]"); } - public override void ReadList(TClass inf, NetDataReader r) { throw new InvalidTypeException("Unsupported type: List<" + typeof(TProperty) + ">"); } - public override void WriteList(TClass inf, NetDataWriter w) { throw new InvalidTypeException("Unsupported type: List<" + typeof(TProperty) + ">"); } - - protected TProperty[] ReadArrayHelper(TClass inf, NetDataReader r) - { - ushort count = r.GetUShort(); - var arr = GetterArr(inf); - arr = arr == null || arr.Length != count ? new TProperty[count] : arr; - SetterArr(inf, arr); - return arr; - } - - protected TProperty[] WriteArrayHelper(TClass inf, NetDataWriter w) - { - var arr = GetterArr(inf); - w.Put((ushort)arr.Length); - return arr; - } - - protected List ReadListHelper(TClass inf, NetDataReader r, out int len) - { - len = r.GetUShort(); - var list = GetterList(inf); - if (list == null) - { - list = new List(len); - SetterList(inf, list); - } - return list; - } - - protected List WriteListHelper(TClass inf, NetDataWriter w, out int len) - { - var list = GetterList(inf); - if (list == null) - { - len = 0; - w.Put(0); - return null; - } - len = list.Count; - w.Put((ushort)len); - return list; - } - - public override void Init(MethodInfo getMethod, MethodInfo setMethod, CallType type) - { - base.Init(getMethod, setMethod, type); - switch (type) - { - case CallType.Array: - GetterArr = (Func)Delegate.CreateDelegate(typeof(Func), getMethod); - SetterArr = (Action)Delegate.CreateDelegate(typeof(Action), setMethod); - break; - case CallType.List: - GetterList = (Func>)Delegate.CreateDelegate(typeof(Func>), getMethod); - SetterList = (Action>)Delegate.CreateDelegate(typeof(Action>), setMethod); - break; - default: - Getter = (Func)Delegate.CreateDelegate(typeof(Func), getMethod); - Setter = (Action)Delegate.CreateDelegate(typeof(Action), setMethod); - break; - } - } - } - - private abstract class FastCallSpecificAuto : FastCallSpecific - { - protected abstract void ElementRead(NetDataReader r, out TProperty prop); - protected abstract void ElementWrite(NetDataWriter w, ref TProperty prop); - - public override void Read(TClass inf, NetDataReader r) - { - TProperty elem; - ElementRead(r, out elem); - Setter(inf, elem); - } - - public override void Write(TClass inf, NetDataWriter w) - { - var elem = Getter(inf); - ElementWrite(w, ref elem); - } - - public override void ReadArray(TClass inf, NetDataReader r) - { - var arr = ReadArrayHelper(inf, r); - for (int i = 0; i < arr.Length; i++) - ElementRead(r, out arr[i]); - } - - public override void WriteArray(TClass inf, NetDataWriter w) - { - var arr = WriteArrayHelper(inf, w); - for (int i = 0; i < arr.Length; i++) - ElementWrite(w, ref arr[i]); - } - } - - private sealed class FastCallStatic : FastCallSpecific - { - private readonly Action _writer; - private readonly Func _reader; - - public FastCallStatic(Action write, Func read) - { - _writer = write; - _reader = read; - } - - public override void Read(TClass inf, NetDataReader r) { Setter(inf, _reader(r)); } - public override void Write(TClass inf, NetDataWriter w) { _writer(w, Getter(inf)); } - - public override void ReadList(TClass inf, NetDataReader r) - { - int len; - var list = ReadListHelper(inf, r, out len); - int listCount = list.Count; - if (len > listCount) - { - for (int i = 0; i < listCount; i++) - list[i] = _reader(r); - for (int i = listCount; i < len; i++) - list.Add(_reader(r)); - return; - } - if (len < listCount) - list.RemoveRange(len, listCount - len); - for (int i = 0; i < len; i++) - list[i] = _reader(r); - } - - public override void WriteList(TClass inf, NetDataWriter w) - { - int len; - var list = WriteListHelper(inf, w, out len); - for (int i = 0; i < len; i++) - _writer(w, list[i]); - } - - public override void ReadArray(TClass inf, NetDataReader r) - { - var arr = ReadArrayHelper(inf, r); - int len = arr.Length; - for (int i = 0; i < len; i++) - arr[i] = _reader(r); - } - - public override void WriteArray(TClass inf, NetDataWriter w) - { - var arr = WriteArrayHelper(inf, w); - int len = arr.Length; - for (int i = 0; i < len; i++) - _writer(w, arr[i]); - } - } - - private sealed class FastCallStruct : FastCallSpecific where TProperty : struct, INetSerializable - { - private TProperty _p; - - public override void Read(TClass inf, NetDataReader r) - { - _p.Deserialize(r); - Setter(inf, _p); - } - - public override void Write(TClass inf, NetDataWriter w) - { - _p = Getter(inf); - _p.Serialize(w); - } - - public override void ReadList(TClass inf, NetDataReader r) - { - int len; - var list = ReadListHelper(inf, r, out len); - int listCount = list.Count; - if (len > listCount) - { - for (int i = 0; i < listCount; i++) - list[i].Deserialize(r); - for (int i = listCount; i < len; i++) - { - var itm = default(TProperty); - itm.Deserialize(r); - list.Add(itm); - } - return; - } - if(len < listCount) - list.RemoveRange(len, listCount - len); - for (int i = 0; i < len; i++) - list[i].Deserialize(r); - } - - public override void WriteList(TClass inf, NetDataWriter w) - { - int len; - var list = WriteListHelper(inf, w, out len); - for (int i = 0; i < len; i++) - list[i].Serialize(w); - } - - public override void ReadArray(TClass inf, NetDataReader r) - { - var arr = ReadArrayHelper(inf, r); - int len = arr.Length; - for (int i = 0; i < len; i++) - arr[i].Deserialize(r); - } - - public override void WriteArray(TClass inf, NetDataWriter w) - { - var arr = WriteArrayHelper(inf, w); - int len = arr.Length; - for (int i = 0; i < len; i++) - arr[i].Serialize(w); - } - } - - private sealed class FastCallClass : FastCallSpecific where TProperty : class, INetSerializable - { - private readonly Func _constructor; - public FastCallClass(Func constructor) { _constructor = constructor; } - - public override void Read(TClass inf, NetDataReader r) - { - var p = _constructor(); - p.Deserialize(r); - Setter(inf, p); - } - - public override void Write(TClass inf, NetDataWriter w) - { - var p = Getter(inf); - if(p != null) - p.Serialize(w); - } - - public override void ReadList(TClass inf, NetDataReader r) - { - int len; - var list = ReadListHelper(inf, r, out len); - int listCount = list.Count; - if (len > listCount) - { - for (int i = 0; i < listCount; i++) - list[i].Deserialize(r); - for (int i = listCount; i < len; i++) - { - var itm = _constructor(); - itm.Deserialize(r); - list.Add(itm); - } - return; - } - if (len < listCount) - list.RemoveRange(len, listCount - len); - for (int i = 0; i < len; i++) - list[i].Deserialize(r); - } - - public override void WriteList(TClass inf, NetDataWriter w) - { - int len; - var list = WriteListHelper(inf, w, out len); - for (int i = 0; i < len; i++) - list[i].Serialize(w); - } - - public override void ReadArray(TClass inf, NetDataReader r) - { - var arr = ReadArrayHelper(inf, r); - int len = arr.Length; - for (int i = 0; i < len; i++) - { - arr[i] = _constructor(); - arr[i].Deserialize(r); - } - } - - public override void WriteArray(TClass inf, NetDataWriter w) - { - var arr = WriteArrayHelper(inf, w); - int len = arr.Length; - for (int i = 0; i < len; i++) - arr[i].Serialize(w); - } - } - - private class IntSerializer : FastCallSpecific - { - public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetInt()); } - public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } - public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetIntArray()); } - public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } - } - - private class UIntSerializer : FastCallSpecific - { - public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetUInt()); } - public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } - public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetUIntArray()); } - public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } - } - - private class ShortSerializer : FastCallSpecific - { - public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetShort()); } - public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } - public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetShortArray()); } - public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } - } - - private class UShortSerializer : FastCallSpecific - { - public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetUShort()); } - public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } - public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetUShortArray()); } - public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } - } - - private class LongSerializer : FastCallSpecific - { - public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetLong()); } - public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } - public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetLongArray()); } - public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } - } - - private class ULongSerializer : FastCallSpecific - { - public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetULong()); } - public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } - public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetULongArray()); } - public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } - } - - private class ByteSerializer : FastCallSpecific - { - public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetByte()); } - public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } - public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetBytesWithLength()); } - public override void WriteArray(T inf, NetDataWriter w) { w.PutBytesWithLength(GetterArr(inf)); } - } - - private class SByteSerializer : FastCallSpecific - { - public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetSByte()); } - public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } - public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetSBytesWithLength()); } - public override void WriteArray(T inf, NetDataWriter w) { w.PutSBytesWithLength(GetterArr(inf)); } - } - - private class FloatSerializer : FastCallSpecific - { - public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetFloat()); } - public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } - public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetFloatArray()); } - public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } - } - - private class DoubleSerializer : FastCallSpecific - { - public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetDouble()); } - public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } - public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetDoubleArray()); } - public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } - } - - private class BoolSerializer : FastCallSpecific - { - public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetBool()); } - public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } - public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetBoolArray()); } - public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } - } - - private class CharSerializer : FastCallSpecificAuto - { - protected override void ElementWrite(NetDataWriter w, ref char prop) { w.Put(prop); } - protected override void ElementRead(NetDataReader r, out char prop) { prop = r.GetChar(); } - } - - private class IPEndPointSerializer : FastCallSpecificAuto - { - protected override void ElementWrite(NetDataWriter w, ref IPEndPoint prop) { w.Put(prop); } - protected override void ElementRead(NetDataReader r, out IPEndPoint prop) { prop = r.GetNetEndPoint(); } - } - - private class StringSerializer : FastCallSpecific - { - private readonly int _maxLength; - public StringSerializer(int maxLength) { _maxLength = maxLength > 0 ? maxLength : short.MaxValue; } - public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetString(_maxLength)); } - public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf), _maxLength); } - public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetStringArray(_maxLength)); } - public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf), _maxLength); } - } - - private class EnumByteSerializer : FastCall - { - protected readonly PropertyInfo Property; - protected readonly Type PropertyType; - public EnumByteSerializer(PropertyInfo property, Type propertyType) - { - Property = property; - PropertyType = propertyType; - } - public override void Read(T inf, NetDataReader r) { Property.SetValue(inf, Enum.ToObject(PropertyType, r.GetByte()), null); } - public override void Write(T inf, NetDataWriter w) { w.Put((byte)Property.GetValue(inf, null)); } - public override void ReadArray(T inf, NetDataReader r) { throw new InvalidTypeException("Unsupported type: Enum[]"); } - public override void WriteArray(T inf, NetDataWriter w) { throw new InvalidTypeException("Unsupported type: Enum[]"); } - public override void ReadList(T inf, NetDataReader r) { throw new InvalidTypeException("Unsupported type: List"); } - public override void WriteList(T inf, NetDataWriter w) { throw new InvalidTypeException("Unsupported type: List"); } - } - - private class EnumIntSerializer : EnumByteSerializer - { - public EnumIntSerializer(PropertyInfo property, Type propertyType) : base(property, propertyType) { } - public override void Read(T inf, NetDataReader r) { Property.SetValue(inf, Enum.ToObject(PropertyType, r.GetInt()), null); } - public override void Write(T inf, NetDataWriter w) { w.Put((int)Property.GetValue(inf, null)); } - } - - private sealed class ClassInfo - { - public static ClassInfo Instance; - private readonly FastCall[] _serializers; - private readonly int _membersCount; - - public ClassInfo(List> serializers) - { - _membersCount = serializers.Count; - _serializers = serializers.ToArray(); - } - - public void Write(T obj, NetDataWriter writer) - { - for (int i = 0; i < _membersCount; i++) - { - var s = _serializers[i]; - if (s.Type == CallType.Basic) - s.Write(obj, writer); - else if (s.Type == CallType.Array) - s.WriteArray(obj, writer); - else - s.WriteList(obj, writer); - } - } - - public void Read(T obj, NetDataReader reader) - { - for (int i = 0; i < _membersCount; i++) - { - var s = _serializers[i]; - if (s.Type == CallType.Basic) - s.Read(obj, reader); - else if(s.Type == CallType.Array) - s.ReadArray(obj, reader); - else - s.ReadList(obj, reader); - } - } - } - - private abstract class CustomType - { - public abstract FastCall Get(); - } - - private sealed class CustomTypeStruct : CustomType where TProperty : struct, INetSerializable - { - public override FastCall Get() { return new FastCallStruct(); } - } - - private sealed class CustomTypeClass : CustomType where TProperty : class, INetSerializable - { - private readonly Func _constructor; - public CustomTypeClass(Func constructor) { _constructor = constructor; } - public override FastCall Get() { return new FastCallClass(_constructor); } - } - - private sealed class CustomTypeStatic : CustomType - { - private readonly Action _writer; - private readonly Func _reader; - public CustomTypeStatic(Action writer, Func reader) - { - _writer = writer; - _reader = reader; - } - public override FastCall Get() { return new FastCallStatic(_writer, _reader); } - } - - /// - /// Register custom property type - /// - /// INetSerializable structure - public void RegisterNestedType() where T : struct, INetSerializable - { - _registeredTypes.Add(typeof(T), new CustomTypeStruct()); - } - - /// - /// Register custom property type - /// - /// INetSerializable class - public void RegisterNestedType(Func constructor) where T : class, INetSerializable - { - _registeredTypes.Add(typeof(T), new CustomTypeClass(constructor)); - } - - /// - /// Register custom property type - /// - /// Any packet - /// custom type writer - /// custom type reader - public void RegisterNestedType(Action writer, Func reader) - { - _registeredTypes.Add(typeof(T), new CustomTypeStatic(writer, reader)); - } - - private NetDataWriter _writer; - private readonly int _maxStringLength; - private readonly Dictionary _registeredTypes = new Dictionary(); - - public NetSerializer() : this(0) - { - } - - public NetSerializer(int maxStringLength) - { - _maxStringLength = maxStringLength; - } - - private ClassInfo RegisterInternal() - { - if (ClassInfo.Instance != null) - return ClassInfo.Instance; - - Type t = typeof(T); - var props = t.GetProperties( - BindingFlags.Instance | - BindingFlags.Public | - BindingFlags.GetProperty | - BindingFlags.SetProperty); - var serializers = new List>(); - for (int i = 0; i < props.Length; i++) - { - var property = props[i]; - var propertyType = property.PropertyType; - - var elementType = propertyType.IsArray ? propertyType.GetElementType() : propertyType; - var callType = propertyType.IsArray ? CallType.Array : CallType.Basic; - - if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(List<>)) - { - elementType = propertyType.GetGenericArguments()[0]; - callType = CallType.List; - } - - var getMethod = property.GetGetMethod(); - var setMethod = property.GetSetMethod(); - if (getMethod == null || setMethod == null) - continue; - - FastCall serialzer = null; - if (propertyType.IsEnum) - { - var underlyingType = Enum.GetUnderlyingType(propertyType); - if (underlyingType == typeof(byte)) - serialzer = new EnumByteSerializer(property, propertyType); - else if (underlyingType == typeof(int)) - serialzer = new EnumIntSerializer(property, propertyType); - else - throw new InvalidTypeException("Not supported enum underlying type: " + underlyingType.Name); - } - else if (elementType == typeof(string)) - serialzer = new StringSerializer(_maxStringLength); - else if (elementType == typeof(bool)) - serialzer = new BoolSerializer(); - else if (elementType == typeof(byte)) - serialzer = new ByteSerializer(); - else if (elementType == typeof(sbyte)) - serialzer = new SByteSerializer(); - else if (elementType == typeof(short)) - serialzer = new ShortSerializer(); - else if (elementType == typeof(ushort)) - serialzer = new UShortSerializer(); - else if (elementType == typeof(int)) - serialzer = new IntSerializer(); - else if (elementType == typeof(uint)) - serialzer = new UIntSerializer(); - else if (elementType == typeof(long)) - serialzer = new LongSerializer(); - else if (elementType == typeof(ulong)) - serialzer = new ULongSerializer(); - else if (elementType == typeof(float)) - serialzer = new FloatSerializer(); - else if (elementType == typeof(double)) - serialzer = new DoubleSerializer(); - else if (elementType == typeof(char)) - serialzer = new CharSerializer(); - else if (elementType == typeof(IPEndPoint)) - serialzer = new IPEndPointSerializer(); - else - { - CustomType customType; - _registeredTypes.TryGetValue(elementType, out customType); - if (customType != null) - serialzer = customType.Get(); - } - - if (serialzer != null) - { - serialzer.Init(getMethod, setMethod, callType); - serializers.Add(serialzer); - } - else - { - throw new InvalidTypeException("Unknown property type: " + propertyType.FullName); - } - } - ClassInfo.Instance = new ClassInfo(serializers); - return ClassInfo.Instance; - } - - /// 's fields are not supported, or it has no fields - public void Register() - { - RegisterInternal(); - } - - /// - /// Reads packet with known type - /// - /// NetDataReader with packet - /// Returns packet if packet in reader is matched type - /// 's fields are not supported, or it has no fields - public T Deserialize(NetDataReader reader) where T : class, new() - { - var info = RegisterInternal(); - var result = new T(); - try - { - info.Read(result, reader); - } - catch - { - return null; - } - return result; - } - - /// - /// Reads packet with known type (non alloc variant) - /// - /// NetDataReader with packet - /// Deserialization target - /// Returns true if packet in reader is matched type - /// 's fields are not supported, or it has no fields - public bool Deserialize(NetDataReader reader, T target) where T : class, new() - { - var info = RegisterInternal(); - try - { - info.Read(target, reader); - } - catch - { - return false; - } - return true; - } - - /// - /// Serialize object to NetDataWriter (fast) - /// - /// Serialization target NetDataWriter - /// Object to serialize - /// 's fields are not supported, or it has no fields - public void Serialize(NetDataWriter writer, T obj) where T : class, new() - { - RegisterInternal().Write(obj, writer); - } - - /// - /// Serialize object to byte array - /// - /// Object to serialize - /// byte array with serialized data - public byte[] Serialize(T obj) where T : class, new() - { - if (_writer == null) - _writer = new NetDataWriter(); - _writer.Reset(); - Serialize(_writer, obj); - return _writer.CopyData(); - } - } -} diff --git a/FirServer/Libraries/LiteNetLib/Utils/NtpPacket.cs b/FirServer/Libraries/LiteNetLib/Utils/NtpPacket.cs deleted file mode 100644 index 86db7685..00000000 --- a/FirServer/Libraries/LiteNetLib/Utils/NtpPacket.cs +++ /dev/null @@ -1,426 +0,0 @@ -using System; - -namespace LiteNetLib.Utils -{ - /// - /// Represents RFC4330 SNTP packet used for communication to and from a network time server. - /// - /// - /// - /// Most applications should just use the property. - /// - /// - /// The same data structure represents both request and reply packets. - /// Request and reply differ in which properties are set and to what values. - /// - /// - /// The only real property is . - /// All other properties read from and write to the underlying byte array - /// with the exception of , - /// which is not part of the packet on network and it is instead set locally after receiving the packet. - /// - /// - /// Copied from GuerrillaNtp project - /// with permission from Robert Vazan (@robertvazan) under MIT license, see https://github.com/RevenantX/LiteNetLib/pull/236 - /// - /// - public class NtpPacket - { - private static readonly DateTime Epoch = new DateTime(1900, 1, 1); - - /// - /// Gets RFC4330-encoded SNTP packet. - /// - /// - /// Byte array containing RFC4330-encoded SNTP packet. It is at least 48 bytes long. - /// - /// - /// This is the only real property. All other properties except - /// read from or write to this byte array. - /// - public byte[] Bytes { get; private set; } - - /// - /// Gets the leap second indicator. - /// - /// - /// Leap second warning, if any. Special value - /// indicates unsynchronized server clock. - /// Default is . - /// - /// - /// Only servers fill in this property. Clients can consult this property for possible leap second warning. - /// - public NtpLeapIndicator LeapIndicator - { - get { return (NtpLeapIndicator)((Bytes[0] & 0xC0) >> 6); } - } - - /// - /// Gets or sets protocol version number. - /// - /// - /// SNTP protocol version. Default is 4, which is the latest version at the time of this writing. - /// - /// - /// In request packets, clients should leave this property at default value 4. - /// Servers usually reply with the same protocol version. - /// - public int VersionNumber - { - get { return (Bytes[0] & 0x38) >> 3; } - private set { Bytes[0] = (byte)((Bytes[0] & ~0x38) | value << 3); } - } - - /// - /// Gets or sets SNTP packet mode, i.e. whether this is client or server packet. - /// - /// - /// SNTP packet mode. Default is in newly created packets. - /// Server reply should have this property set to . - /// - public NtpMode Mode - { - get { return (NtpMode)(Bytes[0] & 0x07); } - private set { Bytes[0] = (byte)((Bytes[0] & ~0x07) | (int)value); } - } - - /// - /// Gets server's distance from the reference clock. - /// - /// - /// - /// Distance from the reference clock. This property is set only in server reply packets. - /// Servers connected directly to reference clock hardware set this property to 1. - /// Statum number is incremented by 1 on every hop down the NTP server hierarchy. - /// - /// - /// Special value 0 indicates that this packet is a Kiss-o'-Death message - /// with kiss code stored in . - /// - /// - public int Stratum { get { return Bytes[1]; } } - - /// - /// Gets server's preferred polling interval. - /// - /// - /// Polling interval in log2 seconds, e.g. 4 stands for 16s and 17 means 131,072s. - /// - public int Poll { get { return Bytes[2]; } } - - /// - /// Gets the precision of server clock. - /// - /// - /// Clock precision in log2 seconds, e.g. -20 for microsecond precision. - /// - public int Precision { get { return (sbyte)Bytes[3]; } } - - /// - /// Gets the total round-trip delay from the server to the reference clock. - /// - /// - /// Round-trip delay to the reference clock. Normally a positive value smaller than one second. - /// - public TimeSpan RootDelay { get { return GetTimeSpan32(4); } } - - /// - /// Gets the estimated error in time reported by the server. - /// - /// - /// Estimated error in time reported by the server. Normally a positive value smaller than one second. - /// - public TimeSpan RootDispersion { get { return GetTimeSpan32(8); } } - - /// - /// Gets the ID of the time source used by the server or Kiss-o'-Death code sent by the server. - /// - /// - /// - /// ID of server's time source or Kiss-o'-Death code. - /// Purpose of this property depends on value of property. - /// - /// - /// Stratum 1 servers write here one of several special values that describe the kind of hardware clock they use. - /// - /// - /// Stratum 2 and lower servers set this property to IPv4 address of their upstream server. - /// If upstream server has IPv6 address, the address is hashed, because it doesn't fit in this property. - /// - /// - /// When server sets to special value 0, - /// this property contains so called kiss code that instructs the client to stop querying the server. - /// - /// - public uint ReferenceId { get { return GetUInt32BE(12); } } - - /// - /// Gets or sets the time when the server clock was last set or corrected. - /// - /// - /// Time when the server clock was last set or corrected or null when not specified. - /// - /// - /// This Property is usually set only by servers. It usually lags server's current time by several minutes, - /// so don't use this property for time synchronization. - /// - public DateTime? ReferenceTimestamp { get { return GetDateTime64(16); } } - - /// - /// Gets or sets the time when the client sent its request. - /// - /// - /// This property is null in request packets. - /// In reply packets, it is the time when the client sent its request. - /// Servers copy this value from - /// that they find in received request packet. - /// - /// - /// - public DateTime? OriginTimestamp { get { return GetDateTime64(24); } } - - /// - /// Gets or sets the time when the request was received by the server. - /// - /// - /// This property is null in request packets. - /// In reply packets, it is the time when the server received client request. - /// - /// - /// - public DateTime? ReceiveTimestamp { get { return GetDateTime64(32); } } - - /// - /// Gets or sets the time when the packet was sent. - /// - /// - /// Time when the packet was sent. It should never be null. - /// Default value is . - /// - /// - /// This property must be set by both clients and servers. - /// - /// - /// - public DateTime? TransmitTimestamp { get { return GetDateTime64(40); } private set { SetDateTime64(40, value); } } - - /// - /// Gets or sets the time of reception of response SNTP packet on the client. - /// - /// - /// Time of reception of response SNTP packet on the client. It is null in request packets. - /// - /// - /// This property is not part of the protocol and has to be set when reply packet is received. - /// - /// - /// - public DateTime? DestinationTimestamp { get; private set; } - - /// - /// Gets the round-trip time to the server. - /// - /// - /// Time the request spent traveling to the server plus the time the reply spent traveling back. - /// This is calculated from timestamps in the packet as (t1 - t0) + (t3 - t2) - /// where t0 is , - /// t1 is , - /// t2 is , - /// and t3 is . - /// This property throws an exception in request packets. - /// - public TimeSpan RoundTripTime - { - get - { - CheckTimestamps(); - return (ReceiveTimestamp.Value - OriginTimestamp.Value) + (DestinationTimestamp.Value - TransmitTimestamp.Value); - } - } - - /// - /// Gets the offset that should be added to local time to synchronize it with server time. - /// - /// - /// Time difference between server and client. It should be added to local time to get server time. - /// It is calculated from timestamps in the packet as 0.5 * ((t1 - t0) - (t3 - t2)) - /// where t0 is , - /// t1 is , - /// t2 is , - /// and t3 is . - /// This property throws an exception in request packets. - /// - public TimeSpan CorrectionOffset - { - get - { - CheckTimestamps(); - return TimeSpan.FromTicks(((ReceiveTimestamp.Value - OriginTimestamp.Value) - (DestinationTimestamp.Value - TransmitTimestamp.Value)).Ticks / 2); - } - } - - /// - /// Initializes default request packet. - /// - /// - /// Properties and - /// are set appropriately for request packet. Property - /// is set to . - /// - public NtpPacket() : this(new byte[48]) - { - Mode = NtpMode.Client; - VersionNumber = 4; - TransmitTimestamp = DateTime.UtcNow; - } - - /// - /// Initializes packet from received data. - /// - internal NtpPacket(byte[] bytes) - { - if (bytes.Length < 48) - throw new ArgumentException("SNTP reply packet must be at least 48 bytes long.", "bytes"); - Bytes = bytes; - } - - /// - /// Initializes packet from data received from a server. - /// - /// Data received from the server. - /// Utc time of reception of response SNTP packet on the client. - /// - public static NtpPacket FromServerResponse(byte[] bytes, DateTime destinationTimestamp) - { - return new NtpPacket(bytes) { DestinationTimestamp = destinationTimestamp }; - } - - internal void ValidateRequest() - { - if (Mode != NtpMode.Client) - throw new InvalidOperationException("This is not a request SNTP packet."); - if (VersionNumber == 0) - throw new InvalidOperationException("Protocol version of the request is not specified."); - if (TransmitTimestamp == null) - throw new InvalidOperationException("TransmitTimestamp must be set in request packet."); - } - - internal void ValidateReply() - { - if (Mode != NtpMode.Server) - throw new InvalidOperationException("This is not a reply SNTP packet."); - if (VersionNumber == 0) - throw new InvalidOperationException("Protocol version of the reply is not specified."); - if (Stratum == 0) - throw new InvalidOperationException(string.Format("Received Kiss-o'-Death SNTP packet with code 0x{0:x}.", ReferenceId)); - if (LeapIndicator == NtpLeapIndicator.AlarmCondition) - throw new InvalidOperationException("SNTP server has unsynchronized clock."); - CheckTimestamps(); - } - - private void CheckTimestamps() - { - if (OriginTimestamp == null) - throw new InvalidOperationException("Origin timestamp is missing."); - if (ReceiveTimestamp == null) - throw new InvalidOperationException("Receive timestamp is missing."); - if (TransmitTimestamp == null) - throw new InvalidOperationException("Transmit timestamp is missing."); - if (DestinationTimestamp == null) - throw new InvalidOperationException("Destination timestamp is missing."); - } - - private DateTime? GetDateTime64(int offset) - { - var field = GetUInt64BE(offset); - if (field == 0) - return null; - return new DateTime(Epoch.Ticks + Convert.ToInt64(field * (1.0 / (1L << 32) * 10000000.0))); - } - - private void SetDateTime64(int offset, DateTime? value) - { - SetUInt64BE(offset, value == null ? 0 : Convert.ToUInt64((value.Value.Ticks - Epoch.Ticks) * (0.0000001 * (1L << 32)))); - } - - private TimeSpan GetTimeSpan32(int offset) - { - return TimeSpan.FromSeconds(GetInt32BE(offset) / (double)(1 << 16)); - } - - private ulong GetUInt64BE(int offset) - { - return SwapEndianness(BitConverter.ToUInt64(Bytes, offset)); - } - - private void SetUInt64BE(int offset, ulong value) - { - FastBitConverter.GetBytes(Bytes, offset, SwapEndianness(value)); - } - - private int GetInt32BE(int offset) - { - return (int)GetUInt32BE(offset); - } - - private uint GetUInt32BE(int offset) - { - return SwapEndianness(BitConverter.ToUInt32(Bytes, offset)); - } - - private static uint SwapEndianness(uint x) - { - return ((x & 0xff) << 24) | ((x & 0xff00) << 8) | ((x & 0xff0000) >> 8) | ((x & 0xff000000) >> 24); - } - - private static ulong SwapEndianness(ulong x) - { - return ((ulong)SwapEndianness((uint)x) << 32) | SwapEndianness((uint)(x >> 32)); - } - } - - /// - /// Represents leap second warning from the server that instructs the client to add or remove leap second. - /// - /// - public enum NtpLeapIndicator - { - /// - /// No leap second warning. No action required. - /// - NoWarning, - - /// - /// Warns the client that the last minute of the current day has 61 seconds. - /// - LastMinuteHas61Seconds, - - /// - /// Warns the client that the last minute of the current day has 59 seconds. - /// - LastMinuteHas59Seconds, - - /// - /// Special value indicating that the server clock is unsynchronized and the returned time is unreliable. - /// - AlarmCondition - } - - /// - /// Describes SNTP packet mode, i.e. client or server. - /// - /// - public enum NtpMode - { - /// - /// Identifies client-to-server SNTP packet. - /// - Client = 3, - - /// - /// Identifies server-to-client SNTP packet. - /// - Server = 4, - } -} \ No newline at end of file diff --git a/FirServer/Libraries/LiteNetLib/Utils/NtpRequest.cs b/FirServer/Libraries/LiteNetLib/Utils/NtpRequest.cs deleted file mode 100644 index 8c0e2ae9..00000000 --- a/FirServer/Libraries/LiteNetLib/Utils/NtpRequest.cs +++ /dev/null @@ -1,146 +0,0 @@ -using System; -using System.Net; -using System.Net.Sockets; - -namespace LiteNetLib.Utils -{ - /// - /// Make NTP request. - /// - /// 1. Create the object by method. - /// - /// - /// 2. Use method to send requests. - /// - /// - /// 3. Call to release the socket AFTER you have received the response or some timeout. - /// If you close the socket too early, you may miss the response. - /// - /// - public sealed class NtpRequest : INetSocketListener - { - public const int DefaultPort = 123; - - private readonly NetSocket _socket; - private readonly Action _onRequestComplete; - private readonly IPEndPoint _ntpEndPoint; - - /// - /// Initialize object, open socket. - /// - /// NTP Server endpoint - /// callback (called from other thread!) - private NtpRequest(IPEndPoint endPoint, Action onRequestComplete) - { - _ntpEndPoint = endPoint; - _onRequestComplete = onRequestComplete; - - // Create and start socket - _socket = new NetSocket(this); - _socket.Bind( - IPAddress.Any, - IPAddress.IPv6Any, - 0, - false, - endPoint.AddressFamily == AddressFamily.InterNetworkV6 ? IPv6Mode.SeparateSocket : IPv6Mode.Disabled); - } - - /// - /// Create the requests for NTP server, open socket. - /// - /// NTP Server address. - /// callback (called from other thread!) - public static NtpRequest Create(IPEndPoint endPoint, Action onRequestComplete) - { - return new NtpRequest(endPoint, onRequestComplete); - } - - /// - /// Create the requests for NTP server (default port), open socket. - /// - /// NTP Server address. - /// callback (called from other thread!) - public static NtpRequest Create(IPAddress ipAddress, Action onRequestComplete) - { - IPEndPoint endPoint = new IPEndPoint(ipAddress, DefaultPort); - return Create(endPoint, onRequestComplete); - } - - /// - /// Create the requests for NTP server, open socket. - /// - /// NTP Server address. - /// port - /// callback (called from other thread!) - public static NtpRequest Create(string ntpServerAddress, int port, Action onRequestComplete) - { - IPEndPoint endPoint = NetUtils.MakeEndPoint(ntpServerAddress, port); - return Create(endPoint, onRequestComplete); - } - - /// - /// Create the requests for NTP server (default port), open socket. - /// - /// NTP Server address. - /// callback (called from other thread!) - public static NtpRequest Create(string ntpServerAddress, Action onRequestComplete) - { - IPEndPoint endPoint = NetUtils.MakeEndPoint(ntpServerAddress, DefaultPort); - return Create(endPoint, onRequestComplete); - } - - /// - /// Send request to the NTP server calls callback (if success). - /// In case of error the callback is called with null param. - /// - public void Send() - { - SocketError errorCode = 0; - var packet = new NtpPacket(); - packet.ValidateRequest(); // not necessary - byte[] sendData = packet.Bytes; - var sendCount = _socket.SendTo(sendData, 0, sendData.Length, _ntpEndPoint, ref errorCode); - if (errorCode != 0 || sendCount != sendData.Length) - { - _onRequestComplete(null); - } - } - - /// - /// Close socket. - /// - public void Close() - { - _socket.Close(false); - } - - /// - /// Handle received data: transform bytes to NtpPacket, close socket and call the callback. - /// - void INetSocketListener.OnMessageReceived(byte[] data, int length, SocketError errorCode, IPEndPoint remoteEndPoint) - { - DateTime destinationTimestamp = DateTime.UtcNow; - if (!remoteEndPoint.Equals(_ntpEndPoint)) - return; - - if (length < 48) - { - NetDebug.Write(NetLogLevel.Trace, "NTP response too short: {}", length); - _onRequestComplete(null); - return; - } - - NtpPacket packet = NtpPacket.FromServerResponse(data, destinationTimestamp); - try - { - packet.ValidateReply(); - } - catch (InvalidOperationException ex) - { - NetDebug.Write(NetLogLevel.Trace, "NTP response error: {}", ex.Message); - packet = null; - } - _onRequestComplete(packet); - } - } -} diff --git a/FirServer/Libraries/Mono.Xml/ChangeLog b/FirServer/Libraries/Mono.Xml/ChangeLog deleted file mode 100644 index 2fbc0ef5..00000000 --- a/FirServer/Libraries/Mono.Xml/ChangeLog +++ /dev/null @@ -1,28 +0,0 @@ -2005-06-15 Atsushi Enomoto - - * SmallXmlParser.cs, SecurityParser.cs : they can be CLSCompliant now. - -2005-05-12 Atsushi Enomoto - - * SmallXmlParser.cs, - SecurityParser.cs : Use new SmallXmlParser.cs instead of MiniParser. - -2004-09-16 Sebastien Pouliot - - * MiniParser.cs: Fixed warning (l4) for unused variables. Removed - duplicate (and identical) license. - -2004-05-14 Marek Safar - - * MiniParser.cs, SecurityParser.cs: [CLSCompliant (false)] - only for public mode. - -2003-07-05 Sebastien Pouliot - - * SecurityParser.cs: Parse an XML string and convert it to a - SecurityElement object. - -2003-02-08 Sebastien Pouliot - - * MiniParser.cs: Renamed namespace to match new location. - diff --git a/FirServer/Libraries/Mono.Xml/MiniParser.cs b/FirServer/Libraries/Mono.Xml/MiniParser.cs deleted file mode 100644 index 4c3da2d4..00000000 --- a/FirServer/Libraries/Mono.Xml/MiniParser.cs +++ /dev/null @@ -1,621 +0,0 @@ -// -// System.Security.Cryptography.MiniParser: Internal XML parser implementation -// -// Authors: -// Sergey Chaban -// -// Copyright (c) 2001, 2002 Wild West Software -// Copyright (c) 2002 Sergey Chaban -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -using System; -using System.Text; -using System.Collections; -using System.Globalization; - -namespace Mono.Xml { - - internal class MiniParser { - - public interface IReader { - int Read(); - } - - public interface IAttrList { - int Length {get;} - bool IsEmpty {get;} - string GetName(int i); - string GetValue(int i); - string GetValue(string name); - void ChangeValue(string name, string newValue); - string[] Names {get;} - string[] Values {get;} - } - - public interface IMutableAttrList : IAttrList { - void Clear(); - void Add(string name, string value); - void CopyFrom(IAttrList attrs); - void Remove(int i); - void Remove(string name); - } - - public interface IHandler { - void OnStartParsing(MiniParser parser); - void OnStartElement(string name, IAttrList attrs); - void OnEndElement(string name); - void OnChars(string ch); - void OnEndParsing(MiniParser parser); - } - - public class HandlerAdapter : IHandler { - public HandlerAdapter() {} - public void OnStartParsing(MiniParser parser) {} - public void OnStartElement(string name, IAttrList attrs) {} - public void OnEndElement(string name) {} - public void OnChars(string ch) {} - public void OnEndParsing(MiniParser parser) {} - } - - private enum CharKind : byte { - LEFT_BR = 0, - RIGHT_BR = 1, - SLASH = 2, - PI_MARK = 3, - EQ = 4, - AMP = 5, - SQUOTE = 6, - DQUOTE = 7, - BANG = 8, - LEFT_SQBR = 9, - SPACE = 0xA, - RIGHT_SQBR = 0xB, - TAB = 0xC, - CR = 0xD, - EOL = 0xE, - CHARS = 0xF, - UNKNOWN = 0x1F - } - - private enum ActionCode : byte { - START_ELEM = 0, - END_ELEM = 1, - END_NAME = 2, - SET_ATTR_NAME = 3, - SET_ATTR_VAL = 4, - SEND_CHARS = 5, - START_CDATA = 6, - END_CDATA = 7, - ERROR = 8, - STATE_CHANGE = 9, - FLUSH_CHARS_STATE_CHANGE = 0xA, - ACC_CHARS_STATE_CHANGE = 0xB, - ACC_CDATA = 0xC, - PROC_CHAR_REF = 0xD, - UNKNOWN = 0xF - } - - public class AttrListImpl : IMutableAttrList { - protected ArrayList names; - protected ArrayList values; - - public AttrListImpl() : this(0) {} - - public AttrListImpl(int initialCapacity) { - if (initialCapacity <= 0) { - names = new ArrayList(); - values = new ArrayList(); - } else { - names = new ArrayList(initialCapacity); - values = new ArrayList(initialCapacity); - } - } - - public AttrListImpl(IAttrList attrs) - : this(attrs != null ? attrs.Length : 0) { - if (attrs != null) this.CopyFrom(attrs); - } - - public int Length { - get {return names.Count;} - } - - public bool IsEmpty { - get {return this.Length != 0;} - } - - public string GetName(int i) { - string res = null; - if (i >= 0 && i < this.Length) { - res = names[i] as string; - } - return res; - } - - public string GetValue(int i) { - string res = null; - if (i >= 0 && i < this.Length) { - res = values[i] as string; - } - return res; - } - - public string GetValue(string name) { - return this.GetValue(names.IndexOf(name)); - } - - public void ChangeValue(string name, string newValue) { - int i = names.IndexOf(name); - if (i >= 0 && i < this.Length) { - values[i] = newValue; - } - } - - public string[] Names { - get {return names.ToArray(typeof(string)) as string[];} - } - - public string[] Values { - get {return values.ToArray(typeof(string)) as string[];} - } - - public void Clear() { - names.Clear(); - values.Clear(); - } - - public void Add(string name, string value) { - names.Add(name); - values.Add(value); - } - - public void Remove(int i) { - if (i >= 0) { - names.RemoveAt(i); - values.RemoveAt(i); - } - } - - public void Remove(string name) { - this.Remove(names.IndexOf(name)); - } - - public void CopyFrom(IAttrList attrs) { - if (attrs != null && ((object)this == (object)attrs)) { - this.Clear(); - int n = attrs.Length; - for (int i = 0; i < n; i++) { - this.Add(attrs.GetName(i), attrs.GetValue(i)); - } - } - } - } - - public class XMLError : Exception { - protected string descr; - protected int line, column; - public XMLError() : this("Unknown") {} - public XMLError(string descr) : this(descr, -1, -1) {} - public XMLError(string descr, int line, int column) - : base(descr) { - this.descr = descr; - this.line = line; - this.column = column; - } - public int Line {get {return line;}} - public int Column {get {return column;}} - public override string ToString() { - return (String.Format("{0} @ (line = {1}, col = {2})", descr, line, column)); - } - } - - private static readonly int INPUT_RANGE = 13; - private static readonly ushort[] tbl = { - (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 1), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 0), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ERROR << 8) | 128), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.ERROR << 8) | 128), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 128), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ERROR << 8) | 128), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ERROR << 8) | 128), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ERROR << 8) | 128), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 128), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ERROR << 8) | 128), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 128), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 128), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 128), - (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 2), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 133), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 16), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.FLUSH_CHARS_STATE_CHANGE << 8) | 4), - (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.END_ELEM << 8) | 0), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 2), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 2), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), - (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 5), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), - (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 4), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.END_NAME << 8) | 6), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.END_NAME << 8) | 7), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.END_NAME << 8) | 8), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), - (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 0), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 3), - (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 0), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ERROR << 8) | 129), - (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.FLUSH_CHARS_STATE_CHANGE << 8) | 1), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.PROC_CHAR_REF << 8) | 10), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 7), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), - (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 9), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.START_ELEM << 8) | 6), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.START_ELEM << 8) | 7), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 8), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), - (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 9), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.SET_ATTR_NAME << 8) | 11), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 12), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 130), - (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 13), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.PROC_CHAR_REF << 8) | 10), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 10), - (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 14), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 15), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 11), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 132), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.ERROR << 8) | 132), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 132), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ERROR << 8) | 132), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ERROR << 8) | 132), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ERROR << 8) | 132), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ERROR << 8) | 132), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 132), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 132), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ERROR << 8) | 132), - (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.SET_ATTR_NAME << 8) | 11), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 12), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 130), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ERROR << 8) | 130), - (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.SEND_CHARS << 8) | 2), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 16), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 134), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 134), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ERROR << 8) | 134), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ERROR << 8) | 134), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ERROR << 8) | 134), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 134), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 134), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.ERROR << 8) | 134), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 134), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 134), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ERROR << 8) | 134), - (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.SET_ATTR_VAL << 8) | 17), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.PROC_CHAR_REF << 8) | 14), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 14), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 14), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 14), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 14), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 14), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 14), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 14), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 14), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 14), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 14), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 14), - (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.SET_ATTR_VAL << 8) | 17), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.PROC_CHAR_REF << 8) | 15), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 15), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 15), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 15), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 15), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 15), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 15), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 15), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 15), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 15), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 15), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 15), - (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.START_CDATA << 8) | 18), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 0), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.START_CDATA << 8) | 19), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.START_CDATA << 8) | 19), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.START_CDATA << 8) | 19), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.START_CDATA << 8) | 19), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.START_CDATA << 8) | 19), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.START_CDATA << 8) | 19), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.START_CDATA << 8) | 19), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.START_CDATA << 8) | 19), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.START_CDATA << 8) | 19), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.START_CDATA << 8) | 19), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.START_CDATA << 8) | 19), - (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.START_ELEM << 8) | 6), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.START_ELEM << 8) | 7), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.STATE_CHANGE << 8) | 17), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ACC_CHARS_STATE_CHANGE << 8) | 9), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ERROR << 8) | 129), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ERROR << 8) | 129), - (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.END_CDATA << 8) | 10), (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 18), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 18), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 18), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 18), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 18), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 18), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 18), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 18), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 18), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 18), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 18), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 18), - (ushort)(((ushort)CharKind.LEFT_BR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), (ushort)(((ushort)CharKind.SLASH << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), (ushort)(((ushort)CharKind.RIGHT_BR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), (ushort)(((ushort)CharKind.PI_MARK << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), (ushort)(((ushort)CharKind.EQ << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), (ushort)(((ushort)CharKind.AMP << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), (ushort)(((ushort)CharKind.SQUOTE << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), (ushort)(((ushort)CharKind.BANG << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), (ushort)(((ushort)CharKind.LEFT_SQBR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), (ushort)(((ushort)CharKind.SPACE << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), (ushort)(((ushort)CharKind.RIGHT_SQBR << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), (ushort)(((ushort)CharKind.DQUOTE << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.ACC_CDATA << 8) | 19), - (ushort)(((ushort)CharKind.CHARS << 12) | ((ushort)ActionCode.UNKNOWN << 8) | 255), - 0xFFFF - }; - - protected static string[] errors = { - /* 0 */ "Expected element", - /* 1 */ "Invalid character in tag", - /* 2 */ "No '='", - /* 3 */ "Invalid character entity", - /* 4 */ "Invalid attr value", - /* 5 */ "Empty tag", - /* 6 */ "No end tag", - /* 7 */ "Bad entity ref" - }; - - protected int line; - protected int col; - protected int[] twoCharBuff; - protected bool splitCData; - - public MiniParser() { - twoCharBuff = new int[2]; - splitCData = false; - Reset(); - } - - public void Reset() { - line = 0; - col = 0; - } - - protected static bool StrEquals(string str, StringBuilder sb, int sbStart, int len) { - if (len != str.Length) return false; - for (int i = 0; i < len; i++) { - if (str[i] != sb[sbStart + i]) return false; - } - return true; - } - - protected void FatalErr(string descr) { - throw new XMLError(descr, this.line, this.col); - } - - protected static int Xlat(int charCode, int state) { - int p = state * INPUT_RANGE; - int n = System.Math.Min(tbl.Length - p, INPUT_RANGE); - for (;--n >= 0;) { - ushort code = tbl[p]; - if (charCode == (code >> 12)) return (code & 0xFFF); - p++; - } - return 0xFFF; - } - - public void Parse(IReader reader, IHandler handler) { - if (reader == null) throw new ArgumentNullException("reader"); - if (handler == null) handler = new HandlerAdapter(); - - AttrListImpl attrList = new AttrListImpl(); - string lastAttrName = null; - Stack tagStack = new Stack(); - string elementName = null; - line = 1; - col = 0; - int currCh = 0; - int stateCode = 0; - StringBuilder sbChars = new StringBuilder(); - bool seenCData = false; - bool isComment = false; - bool isDTD = false; - int bracketSwitch = 0; - - handler.OnStartParsing(this); - - while (true) { - ++this.col; - - currCh = reader.Read(); - - if (currCh == -1) { - if (stateCode != 0) { - FatalErr("Unexpected EOF"); - } - break; - } - - int charCode = "<>/?=&'\"![ ]\t\r\n".IndexOf((char)currCh) & 0xF; - if (charCode == (int)CharKind.CR) continue; // ignore - // whitepace ::= (#x20 | #x9 | #xd | #xa)+ - if (charCode == (int)CharKind.TAB) charCode = (int)CharKind.SPACE; // tab == space - if (charCode == (int)CharKind.EOL) { - this.col = 0; - this.line++; - charCode = (int)CharKind.SPACE; - } - - int actionCode = MiniParser.Xlat(charCode, stateCode); - stateCode = actionCode & 0xFF; - // Ignore newline inside attribute value. - if (currCh == '\n' && (stateCode == 0xE || stateCode == 0xF)) continue; - actionCode >>= 8; - - if (stateCode >= 0x80) { - if (stateCode == 0xFF) { - FatalErr("State dispatch error."); - } else { - FatalErr(errors[stateCode ^ 0x80]); - } - } - - switch (actionCode) { - case (int)ActionCode.START_ELEM: - handler.OnStartElement(elementName, attrList); - if (currCh != '/') { - tagStack.Push(elementName); - } else { - handler.OnEndElement(elementName); - } - attrList.Clear(); - break; - - case (int)ActionCode.END_ELEM: - elementName = sbChars.ToString(); - sbChars = new StringBuilder(); - string endName = null; - if (tagStack.Count == 0 || - elementName != (endName = tagStack.Pop() as string)) { - if (endName == null) { - FatalErr("Tag stack underflow"); - } else { - FatalErr(String.Format("Expected end tag '{0}' but found '{1}'", elementName, endName)); - } - } - handler.OnEndElement(elementName); - break; - - case (int)ActionCode.END_NAME: - elementName = sbChars.ToString(); - sbChars = new StringBuilder(); - if (currCh != '/' && currCh != '>') break; - goto case (int)ActionCode.START_ELEM; - - case (int)ActionCode.SET_ATTR_NAME: - lastAttrName = sbChars.ToString(); - sbChars = new StringBuilder(); - break; - - case (int)ActionCode.SET_ATTR_VAL: - if (lastAttrName == null) FatalErr("Internal error."); - attrList.Add(lastAttrName, sbChars.ToString()); - sbChars = new StringBuilder(); - lastAttrName = null; - break; - - case (int)ActionCode.SEND_CHARS: - handler.OnChars(sbChars.ToString()); - sbChars = new StringBuilder(); - break; - - case (int)ActionCode.START_CDATA: - string cdata = "CDATA["; - isComment = false; - isDTD = false; - - if (currCh == '-') { - currCh = reader.Read(); - - if (currCh != '-') FatalErr("Invalid comment"); - - this.col++; - isComment = true; - twoCharBuff[0] = -1; - twoCharBuff[1] = -1; - } else { - if (currCh != '[') { - isDTD = true; - bracketSwitch = 0; - break; - } - - for (int i = 0; i < cdata.Length; i++) { - if (reader.Read() != cdata[i]) { - this.col += i+1; - break; - } - } - this.col += cdata.Length; - seenCData = true; - } - break; - - case (int)ActionCode.END_CDATA: - int n = 0; - currCh = ']'; - - while (currCh == ']') { - currCh = reader.Read(); - n++; - } - - if (currCh != '>') { - for (int i = 0; i < n; i++) sbChars.Append(']'); - sbChars.Append((char)currCh); - stateCode = 0x12; - } else { - for (int i = 0; i < n-2; i++) sbChars.Append(']'); - seenCData = false; - } - - this.col += n; - break; - - case (int)ActionCode.ERROR: - FatalErr(String.Format("Error {0}", stateCode)); - break; - - case (int)ActionCode.STATE_CHANGE: - break; - - case (int)ActionCode.FLUSH_CHARS_STATE_CHANGE: - sbChars = new StringBuilder(); - if (currCh != '<') goto case (int)ActionCode.ACC_CHARS_STATE_CHANGE; - break; - - case (int)ActionCode.ACC_CHARS_STATE_CHANGE: - sbChars.Append((char)currCh); - break; - - case (int)ActionCode.ACC_CDATA: - if (isComment) { - if (currCh == '>' - && twoCharBuff[0] == '-' - && twoCharBuff[1] == '-') { - isComment = false; - stateCode = 0; - } else { - twoCharBuff[0] = twoCharBuff[1]; - twoCharBuff[1] = currCh; - } - } else if (isDTD) { - if (currCh == '<' || currCh == '>') bracketSwitch ^= 1; - if (currCh == '>' && bracketSwitch != 0) { - isDTD = false; - stateCode = 0; - } - } else { - if (this.splitCData - && sbChars.Length > 0 - && seenCData) { - handler.OnChars(sbChars.ToString()); - sbChars = new StringBuilder(); - } - seenCData = false; - sbChars.Append((char)currCh); - } - break; - - case (int)ActionCode.PROC_CHAR_REF: - currCh = reader.Read(); - int cl = this.col + 1; - if (currCh == '#') { // character reference - int r = 10; - int chCode = 0; - int nDigits = 0; - currCh = reader.Read(); - cl++; - - if (currCh == 'x') { - currCh = reader.Read(); - cl++; - r=16; - } - - NumberStyles style = r == 16 ? NumberStyles.HexNumber : NumberStyles.Integer; - - while (true) { - int x = -1; - if (Char.IsNumber((char)currCh) || "abcdef".IndexOf(Char.ToLower((char)currCh)) != -1) { - try { - x = Int32.Parse(new string((char)currCh, 1), style); - } catch (FormatException) {x = -1;} - } - if (x == -1) break; - chCode *= r; - chCode += x; - nDigits++; - currCh = reader.Read(); - cl++; - } - - if (currCh == ';' && nDigits > 0) { - sbChars.Append((char)chCode); - } else { - FatalErr("Bad char ref"); - } - } else { - // entity reference - string entityRefChars = "aglmopqstu"; // amp | apos | quot | gt | lt - string entities = "&'\"><"; - - int pos = 0; - int entIdx = 0xF; - int predShift = 0; - - int sbLen = sbChars.Length; - - while (true) { - if (pos != 0xF) pos = entityRefChars.IndexOf((char)currCh) & 0xF; - if (pos == 0xF) FatalErr(errors[7]); - sbChars.Append((char)currCh); - - int path = "\uFF35\u3F8F\u4F8F\u0F5F\uFF78\uE1F4\u2299\uEEFF\uEEFF\uFF4F"[pos]; - int lBr = (path >> 4) & 0xF; - int rBr = path & 0xF; - int lPred = path >> 12; - int rPred = (path >> 8) & 0xF; - currCh = reader.Read(); - cl++; - pos = 0xF; - if (lBr != 0xF && currCh == entityRefChars[lBr]) { - if (lPred < 0xE) entIdx = lPred; -// pred = lPred; - predShift = 12; // left - } else if (rBr != 0xF && currCh == entityRefChars[rBr]) { - if (rPred < 0xE) entIdx = rPred; -// pred = rPred; - predShift = 8; // right - } else if (currCh == ';') { - if (entIdx != 0xF - && predShift != 0 - && ((path >> predShift) & 0xF) == 0xE) break; - continue; // pos == 0xF - } - - pos=0; - - } - - int l = cl - this.col - 1; - - if ((l > 0 && l < 5) - &&(StrEquals("amp", sbChars, sbLen, l) - || StrEquals("apos", sbChars, sbLen, l) - || StrEquals("quot", sbChars, sbLen, l) - || StrEquals("lt", sbChars, sbLen, l) - || StrEquals("gt", sbChars, sbLen, l)) - ) { - sbChars.Length = sbLen; - sbChars.Append(entities[entIdx]); - } else FatalErr(errors[7]); - } - - this.col = cl; - break; - - default: - FatalErr(String.Format("Unexpected action code - {0}.", actionCode)); - break; - } - } // while (true) - - handler.OnEndParsing(this); - - } // Parse - - } - -} diff --git a/FirServer/Libraries/Mono.Xml/Mono.Xml.csproj b/FirServer/Libraries/Mono.Xml/Mono.Xml.csproj deleted file mode 100644 index cb631906..00000000 --- a/FirServer/Libraries/Mono.Xml/Mono.Xml.csproj +++ /dev/null @@ -1,7 +0,0 @@ - - - - netcoreapp3.1 - - - diff --git a/FirServer/Libraries/Mono.Xml/SecurityParser.cs b/FirServer/Libraries/Mono.Xml/SecurityParser.cs deleted file mode 100644 index e686e7b1..00000000 --- a/FirServer/Libraries/Mono.Xml/SecurityParser.cs +++ /dev/null @@ -1,109 +0,0 @@ -// -// Mono.Xml.SecurityParser.cs class implementation -// -// Author: -// Sebastien Pouliot (spouliot@motus.com) -// -// (C) 2003 Motus Technologies Inc. (http://www.motus.com) -// - -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -using System; -using System.Collections; -using System.IO; -using System.Security; - -namespace Mono.Xml { - - // convert an XML document into SecurityElement objects - public class SecurityParser : SmallXmlParser, SmallXmlParser.IContentHandler { - - private SecurityElement root; - - public SecurityParser () : base () - { - stack = new Stack (); - } - - public void LoadXml (string xml) - { - root = null; -#if CF_1_0 - stack = new Stack (); -#else - stack.Clear (); -#endif - Parse (new StringReader (xml), this); - } - - public SecurityElement ToXml () - { - return root; - } - - // IContentHandler - - private SecurityElement current; - private Stack stack; - - public void OnStartParsing (SmallXmlParser parser) {} - - public void OnProcessingInstruction (string name, string text) {} - - public void OnIgnorableWhitespace (string s) {} - - public void OnStartElement (string name, SmallXmlParser.IAttrList attrs) - { - SecurityElement newel = new SecurityElement (name); - if (root == null) { - root = newel; - current = newel; - } - else { - SecurityElement parent = (SecurityElement) stack.Peek (); - parent.AddChild (newel); - } - stack.Push (newel); - current = newel; - // attributes - int n = attrs.Length; - for (int i=0; i < n; i++) - current.AddAttribute (attrs.GetName (i), attrs.GetValue (i)); - } - - public void OnEndElement (string name) - { - current = (SecurityElement) stack.Pop (); - } - - public void OnChars (string ch) - { - current.Text = ch; - } - - public void OnEndParsing (SmallXmlParser parser) {} - } -} - diff --git a/FirServer/Libraries/Mono.Xml/SmallXmlParser.cs b/FirServer/Libraries/Mono.Xml/SmallXmlParser.cs deleted file mode 100644 index 4b59f048..00000000 --- a/FirServer/Libraries/Mono.Xml/SmallXmlParser.cs +++ /dev/null @@ -1,637 +0,0 @@ -// -// SmallXmlParser.cs -// -// Author: -// Atsushi Enomoto -// -// Copyright (C) 2005 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -// -// small xml parser that is mostly compatible with -// - -using System; -using System.Collections; -using System.Globalization; -using System.IO; -using System.Text; - -namespace Mono.Xml -{ - internal class DefaultHandler : SmallXmlParser.IContentHandler - { - public void OnStartParsing (SmallXmlParser parser) - { - } - - public void OnEndParsing (SmallXmlParser parser) - { - } - - public void OnStartElement (string name, SmallXmlParser.IAttrList attrs) - { - } - - public void OnEndElement (string name) - { - } - - public void OnChars (string s) - { - } - - public void OnIgnorableWhitespace (string s) - { - } - - public void OnProcessingInstruction (string name, string text) - { - } - } - - public class SmallXmlParser - { - public interface IContentHandler - { - void OnStartParsing (SmallXmlParser parser); - void OnEndParsing (SmallXmlParser parser); - void OnStartElement (string name, IAttrList attrs); - void OnEndElement (string name); - void OnProcessingInstruction (string name, string text); - void OnChars (string text); - void OnIgnorableWhitespace (string text); - } - - public interface IAttrList - { - int Length { get; } - bool IsEmpty { get; } - string GetName (int i); - string GetValue (int i); - string GetValue (string name); - string [] Names { get; } - string [] Values { get; } - } - - class AttrListImpl : IAttrList - { - public int Length { - get { return attrNames.Count; } - } - public bool IsEmpty { - get { return attrNames.Count == 0; } - } - public string GetName (int i) - { - return (string) attrNames [i]; - } - public string GetValue (int i) - { - return (string) attrValues [i]; - } - public string GetValue (string name) - { - for (int i = 0; i < attrNames.Count; i++) - if ((string) attrNames [i] == name) - return (string) attrValues [i]; - return null; - } - public string [] Names { - get { return (string []) attrNames.ToArray (typeof (string)); } - } - public string [] Values { - get { return (string []) attrValues.ToArray (typeof (string)); } - } - - ArrayList attrNames = new ArrayList (); - ArrayList attrValues = new ArrayList (); - - internal void Clear () - { - attrNames.Clear (); - attrValues.Clear (); - } - - internal void Add (string name, string value) - { - attrNames.Add (name); - attrValues.Add (value); - } - } - - IContentHandler handler; - TextReader reader; - Stack elementNames = new Stack (); - Stack xmlSpaces = new Stack (); - string xmlSpace; - StringBuilder buffer = new StringBuilder (200); - char [] nameBuffer = new char [30]; - bool isWhitespace; - - AttrListImpl attributes = new AttrListImpl (); - int line = 1, column; - bool resetColumn; - - public SmallXmlParser () - { - } - - private Exception Error (string msg) - { - return new SmallXmlParserException (msg, line, column); - } - - private Exception UnexpectedEndError () - { - string [] arr = new string [elementNames.Count]; - // COMPACT FRAMEWORK NOTE: CopyTo is not visible through the Stack class - (elementNames as ICollection).CopyTo (arr, 0); - return Error (String.Format ( - "Unexpected end of stream. Element stack content is {0}", String.Join (",", arr))); - } - - - private bool IsNameChar (char c, bool start) - { - switch (c) { - case ':': - case '_': - return true; - case '-': - case '.': - return !start; - } - if (c > 0x100) { // optional condition for optimization - switch (c) { - case '\u0559': - case '\u06E5': - case '\u06E6': - return true; - } - if ('\u02BB' <= c && c <= '\u02C1') - return true; - } - switch (Char.GetUnicodeCategory (c)) { - case UnicodeCategory.LowercaseLetter: - case UnicodeCategory.UppercaseLetter: - case UnicodeCategory.OtherLetter: - case UnicodeCategory.TitlecaseLetter: - case UnicodeCategory.LetterNumber: - return true; - case UnicodeCategory.SpacingCombiningMark: - case UnicodeCategory.EnclosingMark: - case UnicodeCategory.NonSpacingMark: - case UnicodeCategory.ModifierLetter: - case UnicodeCategory.DecimalDigitNumber: - return !start; - default: - return false; - } - } - - private bool IsWhitespace (int c) - { - switch (c) { - case ' ': - case '\r': - case '\t': - case '\n': - return true; - default: - return false; - } - } - - - public void SkipWhitespaces () - { - SkipWhitespaces (false); - } - - private void HandleWhitespaces () - { - while (IsWhitespace (Peek ())) - buffer.Append ((char) Read ()); - if (Peek () != '<' && Peek () >= 0) - isWhitespace = false; - } - - public void SkipWhitespaces (bool expected) - { - while (true) { - switch (Peek ()) { - case ' ': - case '\r': - case '\t': - case '\n': - Read (); - if (expected) - expected = false; - continue; - } - if (expected) - throw Error ("Whitespace is expected."); - return; - } - } - - - private int Peek () - { - return reader.Peek (); - } - - private int Read () - { - int i = reader.Read (); - if (i == '\n') - resetColumn = true; - if (resetColumn) { - line++; - resetColumn = false; - column = 1; - } - else - column++; - return i; - } - - public void Expect (int c) - { - int p = Read (); - if (p < 0) - throw UnexpectedEndError (); - else if (p != c) - throw Error (String.Format ("Expected '{0}' but got {1}", (char) c, (char) p)); - } - - private string ReadUntil (char until, bool handleReferences) - { - while (true) { - if (Peek () < 0) - throw UnexpectedEndError (); - char c = (char) Read (); - if (c == until) - break; - else if (handleReferences && c == '&') - ReadReference (); - else - buffer.Append (c); - } - string ret = buffer.ToString (); - buffer.Length = 0; - return ret; - } - - public string ReadName () - { - int idx = 0; - if (Peek () < 0 || !IsNameChar ((char) Peek (), true)) - throw Error ("XML name start character is expected."); - for (int i = Peek (); i >= 0; i = Peek ()) { - char c = (char) i; - if (!IsNameChar (c, false)) - break; - if (idx == nameBuffer.Length) { - char [] tmp = new char [idx * 2]; - // COMPACT FRAMEWORK NOTE: Array.Copy(sourceArray, destinationArray, count) is not available. - Array.Copy (nameBuffer, 0, tmp, 0, idx); - nameBuffer = tmp; - } - nameBuffer [idx++] = c; - Read (); - } - if (idx == 0) - throw Error ("Valid XML name is expected."); - return new string (nameBuffer, 0, idx); - } - - - public void Parse (TextReader input, IContentHandler handler) - { - this.reader = input; - this.handler = handler; - - handler.OnStartParsing (this); - - while (Peek () >= 0) - ReadContent (); - HandleBufferedContent (); - if (elementNames.Count > 0) - throw Error (String.Format ("Insufficient close tag: {0}", elementNames.Peek ())); - - handler.OnEndParsing (this); - - Cleanup (); - } - - private void Cleanup () - { - line = 1; - column = 0; - handler = null; - reader = null; -#if CF_1_0 - elementNames = new Stack (); - xmlSpaces = new Stack (); -#else - elementNames.Clear (); - xmlSpaces.Clear (); -#endif - attributes.Clear (); - buffer.Length = 0; - xmlSpace = null; - isWhitespace = false; - } - - public void ReadContent () - { - string name; - if (IsWhitespace (Peek ())) { - if (buffer.Length == 0) - isWhitespace = true; - HandleWhitespaces (); - } - if (Peek () == '<') { - Read (); - switch (Peek ()) { - case '!': // declarations - Read (); - if (Peek () == '[') { - Read (); - if (ReadName () != "CDATA") - throw Error ("Invalid declaration markup"); - Expect ('['); - ReadCDATASection (); - return; - } - else if (Peek () == '-') { - ReadComment (); - return; - } - else if (ReadName () != "DOCTYPE") - throw Error ("Invalid declaration markup."); - else - throw Error ("This parser does not support document type."); - case '?': // PIs - HandleBufferedContent (); - Read (); - name = ReadName (); - SkipWhitespaces (); - string text = String.Empty; - if (Peek () != '?') { - while (true) { - text += ReadUntil ('?', false); - if (Peek () == '>') - break; - text += "?"; - } - } - handler.OnProcessingInstruction ( - name, text); - Expect ('>'); - return; - case '/': // end tags - HandleBufferedContent (); - if (elementNames.Count == 0) - throw UnexpectedEndError (); - Read (); - name = ReadName (); - SkipWhitespaces (); - string expected = (string) elementNames.Pop (); - xmlSpaces.Pop (); - if (xmlSpaces.Count > 0) - xmlSpace = (string) xmlSpaces.Peek (); - else - xmlSpace = null; - if (name != expected) - throw Error (String.Format ("End tag mismatch: expected {0} but found {1}", expected, name)); - handler.OnEndElement (name); - Expect ('>'); - return; - default: // start tags (including empty tags) - HandleBufferedContent (); - name = ReadName (); - while (Peek () != '>' && Peek () != '/') - ReadAttribute (attributes); - handler.OnStartElement (name, attributes); - attributes.Clear (); - SkipWhitespaces (); - if (Peek () == '/') { - Read (); - handler.OnEndElement (name); - } - else { - elementNames.Push (name); - xmlSpaces.Push (xmlSpace); - } - Expect ('>'); - return; - } - } - else - ReadCharacters (); - } - - private void HandleBufferedContent () - { - if (buffer.Length == 0) - return; - if (isWhitespace) - handler.OnIgnorableWhitespace (buffer.ToString ()); - else - handler.OnChars (buffer.ToString ()); - buffer.Length = 0; - isWhitespace = false; - } - - private void ReadCharacters () - { - isWhitespace = false; - while (true) { - int i = Peek (); - switch (i) { - case -1: - return; - case '<': - return; - case '&': - Read (); - ReadReference (); - continue; - default: - buffer.Append ((char) Read ()); - continue; - } - } - } - - private void ReadReference () - { - if (Peek () == '#') { - // character reference - Read (); - ReadCharacterReference (); - } else { - string name = ReadName (); - Expect (';'); - switch (name) { - case "amp": - buffer.Append ('&'); - break; - case "quot": - buffer.Append ('"'); - break; - case "apos": - buffer.Append ('\''); - break; - case "lt": - buffer.Append ('<'); - break; - case "gt": - buffer.Append ('>'); - break; - default: - throw Error ("General non-predefined entity reference is not supported in this parser."); - } - } - } - - private int ReadCharacterReference () - { - int n = 0; - if (Peek () == 'x') { // hex - Read (); - for (int i = Peek (); i >= 0; i = Peek ()) { - if ('0' <= i && i <= '9') - n = n << 4 + i - '0'; - else if ('A' <= i && i <='F') - n = n << 4 + i - 'A' + 10; - else if ('a' <= i && i <='f') - n = n << 4 + i - 'a' + 10; - else - break; - Read (); - } - } else { - for (int i = Peek (); i >= 0; i = Peek ()) { - if ('0' <= i && i <= '9') - n = n << 4 + i - '0'; - else - break; - Read (); - } - } - return n; - } - - private void ReadAttribute (AttrListImpl a) - { - SkipWhitespaces (true); - if (Peek () == '/' || Peek () == '>') - // came here just to spend trailing whitespaces - return; - - string name = ReadName (); - string value; - SkipWhitespaces (); - Expect ('='); - SkipWhitespaces (); - switch (Read ()) { - case '\'': - value = ReadUntil ('\'', true); - break; - case '"': - value = ReadUntil ('"', true); - break; - default: - throw Error ("Invalid attribute value markup."); - } - if (name == "xml:space") - xmlSpace = value; - a.Add (name, value); - } - - private void ReadCDATASection () - { - int nBracket = 0; - while (true) { - if (Peek () < 0) - throw UnexpectedEndError (); - char c = (char) Read (); - if (c == ']') - nBracket++; - else if (c == '>' && nBracket > 1) { - for (int i = nBracket; i > 2; i--) - buffer.Append (']'); - break; - } - else { - for (int i = 0; i < nBracket; i++) - buffer.Append (']'); - nBracket = 0; - buffer.Append (c); - } - } - } - - private void ReadComment () - { - Expect ('-'); - Expect ('-'); - while (true) { - if (Read () != '-') - continue; - if (Read () != '-') - continue; - if (Read () != '>') - throw Error ("'--' is not allowed inside comment markup."); - break; - } - } - } - - internal class SmallXmlParserException : SystemException - { - int line; - int column; - - public SmallXmlParserException (string msg, int line, int column) - : base (String.Format ("{0}. At ({1},{2})", msg, line, column)) - { - this.line = line; - this.column = column; - } - - public int Line { - get { return line; } - } - - public int Column { - get { return column; } - } - } -} - - - diff --git a/FirToolkit/Libraries/FirCommon.dll b/FirToolkit/Libraries/FirCommon.dll index c49f8583..96e85250 100644 Binary files a/FirToolkit/Libraries/FirCommon.dll and b/FirToolkit/Libraries/FirCommon.dll differ