From 74830eea0c0a05c85a8649d08a195e84946bceec Mon Sep 17 00:00:00 2001 From: ahmed Date: Thu, 2 Apr 2026 19:42:54 +0300 Subject: [PATCH] WIP --- .../Program.cs | 9 +- Esiur/Data/BinaryList.cs | 2 +- Esiur/Data/Codec.cs | 54 +- Esiur/Data/DataConverter.cs | 4 +- Esiur/Data/DataDeserializer.cs | 322 ++-- Esiur/Data/DataSerializer.cs | 276 +-- Esiur/Data/ParsedTDU.cs | 50 +- Esiur/Data/TDU.cs | 26 +- Esiur/Data/TDUClass.cs | 2 +- Esiur/Data/TDUIdentifier.cs | 2 +- Esiur/Data/TRU.cs | 284 +-- Esiur/Data/TRUIdentifier.cs | 2 +- Esiur/Data/Types/ArgumentDef.cs | 4 +- Esiur/Data/Types/ConstantDef.cs | 6 +- Esiur/Data/Types/EventDef.cs | 6 +- Esiur/Data/Types/FunctionDef.cs | 18 +- Esiur/Data/Types/PropertyDef.cs | 8 +- Esiur/Data/Types/TypeDef.cs | 12 +- Esiur/Data/UUID.cs | 12 +- Esiur/Esiur.csproj | 9 + Esiur/Net/HTTP/HTTPConnection.cs | 42 +- Esiur/Net/HTTP/HTTPFilter.cs | 10 +- Esiur/Net/HTTP/HTTPServer.cs | 54 +- Esiur/Net/HTTP/HTTPSession.cs | 10 +- Esiur/Net/Http/{EPoHTTP.cs => EpOverHttp.cs} | 6 +- .../Http/{EPoWS.cs => EpOvwerWebsocket.cs} | 6 +- Esiur/Net/Packets/EpAuthPacket.cs | 362 +--- Esiur/Net/Packets/EpAuthPacketAcknowledge.cs | 26 - .../Packets/EpAuthPacketAcknowledgement.cs | 18 + Esiur/Net/Packets/EpAuthPacketAction.cs | 31 +- Esiur/Net/Packets/EpAuthPacketAuthMode.cs | 32 + Esiur/Net/Packets/EpAuthPacketCommand.cs | 1 - .../Net/Packets/EpAuthPacketEncryptionMode.cs | 13 + .../Net/Packets/EpAuthPacketHashAlgorithm.cs | 12 - Esiur/Net/Packets/EpAuthPacketHeader.cs | 33 +- Esiur/Net/Packets/EpAuthPacketInitialize.cs | 26 - .../Packets/EpAuthPacketPublicKeyAlgorithm.cs | 12 - Esiur/Net/Packets/EpPacket.cs | 14 +- Esiur/Net/Packets/EpPacketAttachInfo.cs | 4 +- Esiur/Net/Packets/HTTP/HTTPComposeOption.cs | 4 +- Esiur/Net/Packets/HTTP/HTTPCookie.cs | 8 +- Esiur/Net/Packets/HTTP/HTTPMethod.cs | 4 +- Esiur/Net/Packets/HTTP/HTTPRequestPacket.cs | 28 +- Esiur/Net/Packets/HTTP/HTTPResponseCode.cs | 4 +- Esiur/Net/Packets/HTTP/HTTPResponsePacket.cs | 24 +- Esiur/Net/Ppap/DeterministicGenerator.cs | 249 +++ Esiur/Net/Ppap/KeyGenerator.cs | 61 + Esiur/Net/Ppap/RandomGenerator.cs | 247 +++ Esiur/Net/TCP/TCPConnection.cs | 6 +- Esiur/Net/TCP/TCPFilter.cs | 10 +- Esiur/Net/TCP/TCPServer.cs | 20 +- Esiur/Net/TCP/TCPSession.cs | 4 +- Esiur/Net/UDP/UDPFilter.cs | 2 +- Esiur/Net/UDP/UDPServer.cs | 8 +- .../HashAnonymousAuthenticator.cs | 20 + Esiur/Protocol/EpConnection.cs | 1710 +++++++++-------- Esiur/Protocol/EpConnectionProtocol.cs | 84 +- Esiur/Protocol/EpServer.cs | 22 +- Esiur/Protocol/EpSession.cs | 37 - Esiur/Proxy/TypeDefGenerator.cs | 64 +- Esiur/Resource/Storable.cs | 6 +- Esiur/Resource/TypeIdAttribute.cs | 4 +- Esiur/Resource/Warehouse.cs | 12 +- .../Security/Authority/AlienAuthentication.cs | 40 - Esiur/Security/Authority/Authentication.cs | 6 +- .../Authority/AuthenticationMethod.cs | 11 +- ...nticationType.cs => AuthenticationMode.cs} | 10 +- .../Authority/AuthenticationResult.cs | 28 + .../Authority/AuthenticationRuling.cs | 13 + Esiur/Security/Authority/CACertificate.cs | 201 -- Esiur/Security/Authority/Certificate.cs | 221 --- Esiur/Security/Authority/CertificateType.cs | 41 - .../Authority/ClientAuthentication.cs | 70 - .../Authority/CoHostAuthentication.cs | 40 - Esiur/Security/Authority/DomainCertificate.cs | 249 --- .../Security/Authority/HostAuthentication.cs | 41 - .../Authority/IAuthenticationHandler.cs | 18 + .../Authority/IAuthenticationInitiator.cs | 13 + .../Authority/IAuthenticationResponder.cs | 12 + Esiur/Security/Authority/Session.cs | 17 +- Esiur/Security/Cryptography/EncryptionMode.cs | 14 + Tests/Distribution/Program.cs | 6 +- 82 files changed, 2501 insertions(+), 3008 deletions(-) rename Esiur/Net/Http/{EPoHTTP.cs => EpOverHttp.cs} (85%) rename Esiur/Net/Http/{EPoWS.cs => EpOvwerWebsocket.cs} (94%) delete mode 100644 Esiur/Net/Packets/EpAuthPacketAcknowledge.cs create mode 100644 Esiur/Net/Packets/EpAuthPacketAcknowledgement.cs create mode 100644 Esiur/Net/Packets/EpAuthPacketAuthMode.cs create mode 100644 Esiur/Net/Packets/EpAuthPacketEncryptionMode.cs delete mode 100644 Esiur/Net/Packets/EpAuthPacketHashAlgorithm.cs delete mode 100644 Esiur/Net/Packets/EpAuthPacketInitialize.cs delete mode 100644 Esiur/Net/Packets/EpAuthPacketPublicKeyAlgorithm.cs create mode 100644 Esiur/Net/Ppap/DeterministicGenerator.cs create mode 100644 Esiur/Net/Ppap/KeyGenerator.cs create mode 100644 Esiur/Net/Ppap/RandomGenerator.cs create mode 100644 Esiur/Protocol/Authentication/HashAnonymousAuthenticator.cs delete mode 100644 Esiur/Protocol/EpSession.cs delete mode 100644 Esiur/Security/Authority/AlienAuthentication.cs rename Esiur/Security/Authority/{AuthenticationType.cs => AuthenticationMode.cs} (90%) create mode 100644 Esiur/Security/Authority/AuthenticationResult.cs create mode 100644 Esiur/Security/Authority/AuthenticationRuling.cs delete mode 100644 Esiur/Security/Authority/CACertificate.cs delete mode 100644 Esiur/Security/Authority/Certificate.cs delete mode 100644 Esiur/Security/Authority/CertificateType.cs delete mode 100644 Esiur/Security/Authority/ClientAuthentication.cs delete mode 100644 Esiur/Security/Authority/CoHostAuthentication.cs delete mode 100644 Esiur/Security/Authority/DomainCertificate.cs delete mode 100644 Esiur/Security/Authority/HostAuthentication.cs create mode 100644 Esiur/Security/Authority/IAuthenticationHandler.cs create mode 100644 Esiur/Security/Authority/IAuthenticationInitiator.cs create mode 100644 Esiur/Security/Authority/IAuthenticationResponder.cs create mode 100644 Esiur/Security/Cryptography/EncryptionMode.cs diff --git a/Esiur.Examples.StandaloneWebServerDemo/Program.cs b/Esiur.Examples.StandaloneWebServerDemo/Program.cs index 3a86c72..5f75230 100644 --- a/Esiur.Examples.StandaloneWebServerDemo/Program.cs +++ b/Esiur.Examples.StandaloneWebServerDemo/Program.cs @@ -1,6 +1,7 @@  using Esiur.Examples.StandaloneWebServerDemo; -using Esiur.Net.HTTP; +using Esiur.Net.Http; +using Esiur.Net.Packets.Http; using Esiur.Protocol; using Esiur.Resource; using Esiur.Stores; @@ -22,10 +23,10 @@ internal class Program // Add your object to the store var service = await wh.Put("sys/demo", new Demo()); - var http = await wh.Put("sys/http", new HTTPServer() { Port = 8888 }); + var http = await wh.Put("sys/http", new HttpServer() { Port = 8888 }); - http.MapGet("{url}", (string url, HTTPConnection sender) => + http.MapGet("{url}", (string url, HttpConnection sender) => { var fn = "Web/" + (sender.Request.Filename == "/" ? "/index.html" : sender.Request.Filename); @@ -42,7 +43,7 @@ internal class Program } else { - sender.Response.Number = Esiur.Net.Packets.HTTP.HTTPResponseCode.NotFound; + sender.Response.Number = HttpResponseCode.NotFound; sender.Send("`" + fn + "` Not Found"); sender.Close(); } diff --git a/Esiur/Data/BinaryList.cs b/Esiur/Data/BinaryList.cs index 397df1a..2f79a4b 100644 --- a/Esiur/Data/BinaryList.cs +++ b/Esiur/Data/BinaryList.cs @@ -64,7 +64,7 @@ public class BinaryList } - public BinaryList AddUUID(UUID value) + public BinaryList AddUUID(Uuid value) { list.AddRange(value.Data); return this; diff --git a/Esiur/Data/Codec.cs b/Esiur/Data/Codec.cs index 147b7e0..913082e 100644 --- a/Esiur/Data/Codec.cs +++ b/Esiur/Data/Codec.cs @@ -41,8 +41,8 @@ public static class Codec //delegate AsyncReply AsyncParser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence); - delegate object AsyncParser(ParsedTDU tdu, EpConnection connection, uint[] requestSequence); - delegate object SyncParser(ParsedTDU tdu, Warehouse warehouse); + delegate object AsyncParser(ParsedTdu tdu, EpConnection connection, uint[] requestSequence); + delegate object SyncParser(ParsedTdu tdu, Warehouse warehouse); static AsyncParser[][] FixedAsyncParsers = new AsyncParser[][] { @@ -195,20 +195,20 @@ public static class Codec public static (uint, object) ParseAsync(byte[] data, uint offset, EpConnection connection, uint[] requestSequence) { - var tdu = ParsedTDU.Parse(data, offset, (uint)data.Length); + var tdu = ParsedTdu.Parse(data, offset, (uint)data.Length); - if (tdu.Class == TDUClass.Invalid) + if (tdu.Class == TduClass.Invalid) throw new NullReferenceException("DataType can't be parsed."); - if (tdu.Class == TDUClass.Fixed) + if (tdu.Class == TduClass.Fixed) { return ((uint)tdu.TotalLength, FixedAsyncParsers[tdu.Exponent][tdu.Index](tdu, connection, requestSequence)); } - else if (tdu.Class == TDUClass.Dynamic) + else if (tdu.Class == TduClass.Dynamic) { return ((uint)tdu.TotalLength, DynamicAsyncParsers[tdu.Index](tdu, connection, requestSequence)); } - else if (tdu.Class == TDUClass.Typed) + else if (tdu.Class == TduClass.Typed) { return ((uint)tdu.TotalLength, TypedAsyncParsers[tdu.Index](tdu, connection, requestSequence)); } @@ -219,20 +219,20 @@ public static class Codec } } - public static (uint, object) ParseAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static (uint, object) ParseAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { - if (tdu.Class == TDUClass.Invalid) + if (tdu.Class == TduClass.Invalid) throw new NullReferenceException("DataType can't be parsed."); - if (tdu.Class == TDUClass.Fixed) + if (tdu.Class == TduClass.Fixed) { return ((uint)tdu.TotalLength, FixedAsyncParsers[tdu.Exponent][tdu.Index](tdu, connection, requestSequence)); } - else if (tdu.Class == TDUClass.Dynamic) + else if (tdu.Class == TduClass.Dynamic) { return ((uint)tdu.TotalLength, DynamicAsyncParsers[tdu.Index](tdu, connection, requestSequence)); } - else if (tdu.Class == TDUClass.Typed) + else if (tdu.Class == TduClass.Typed) { return ((uint)tdu.TotalLength, TypedAsyncParsers[tdu.Index](tdu, connection, requestSequence)); } @@ -243,17 +243,17 @@ public static class Codec } } - public static (uint, object) ParseSync(ParsedTDU tdu, Warehouse warehouse) + public static (uint, object) ParseSync(ParsedTdu tdu, Warehouse warehouse) { - if (tdu.Class == TDUClass.Fixed) + if (tdu.Class == TduClass.Fixed) { return ((uint)tdu.TotalLength, FixedParsers[tdu.Exponent][tdu.Index](tdu, warehouse)); } - else if (tdu.Class == TDUClass.Dynamic) + else if (tdu.Class == TduClass.Dynamic) { return ((uint)tdu.TotalLength, DynamicParsers[tdu.Index](tdu, warehouse)); } - else if (tdu.Class == TDUClass.Typed) + else if (tdu.Class == TduClass.Typed) { return ((uint)tdu.TotalLength, TypedParsers[tdu.Index](tdu, warehouse)); } @@ -266,21 +266,21 @@ public static class Codec public static (uint, object) ParseSync(byte[] data, uint offset, Warehouse warehouse) { - var tdu = ParsedTDU.Parse(data, offset, (uint)data.Length); + var tdu = ParsedTdu.Parse(data, offset, (uint)data.Length); - if (tdu.Class == TDUClass.Invalid) + if (tdu.Class == TduClass.Invalid) throw new NullReferenceException("DataType can't be parsed."); - if (tdu.Class == TDUClass.Fixed) + if (tdu.Class == TduClass.Fixed) { return ((uint)tdu.TotalLength, FixedParsers[tdu.Exponent][tdu.Index](tdu, warehouse)); } - else if (tdu.Class == TDUClass.Dynamic) + else if (tdu.Class == TduClass.Dynamic) { return ((uint)tdu.TotalLength, DynamicParsers[tdu.Index](tdu, warehouse)); } - else if (tdu.Class == TDUClass.Typed) + else if (tdu.Class == TduClass.Typed) { return ((uint)tdu.TotalLength, TypedParsers[tdu.Index](tdu, warehouse)); } @@ -307,7 +307,7 @@ public static class Codec return false; } - public delegate TDU Composer(object value, Warehouse warehouse, EpConnection connection); + public delegate Tdu Composer(object value, Warehouse warehouse, EpConnection connection); public static Dictionary Composers = new Dictionary() { @@ -347,7 +347,7 @@ public static class Codec //[typeof(List)] = DataSerializer.RawDataComposerFromList, [typeof(string)] = DataSerializer.StringComposer, [typeof(ResourceLink)] = DataSerializer.ResourceLinkComposer, - [typeof(UUID)] = DataSerializer.UUIDComposer, + [typeof(Uuid)] = DataSerializer.UUIDComposer, // Special [typeof(object[])] = DataSerializer.ListComposer, [typeof(List)] = DataSerializer.ListComposer, @@ -381,11 +381,11 @@ public static class Codec }; - internal static TDU + internal static Tdu ComposeInternal(object valueOrSource, Warehouse warehouse, EpConnection connection) { if (valueOrSource == null) - return new TDU(TDUIdentifier.Null, null, 0); + return new Tdu(TduIdentifier.Null, null, 0); var type = valueOrSource.GetType(); @@ -412,7 +412,7 @@ public static class Codec valueOrSource = ((IUserType)valueOrSource).Get(); if (valueOrSource == null) - return new TDU(TDUIdentifier.Null, null, 0); + return new Tdu(TduIdentifier.Null, null, 0); type = valueOrSource.GetType(); @@ -488,7 +488,7 @@ public static class Codec } - return new TDU(TDUIdentifier.Null, null, 0); + return new Tdu(TduIdentifier.Null, null, 0); } diff --git a/Esiur/Data/DataConverter.cs b/Esiur/Data/DataConverter.cs index efdac8e..67fbb82 100644 --- a/Esiur/Data/DataConverter.cs +++ b/Esiur/Data/DataConverter.cs @@ -813,9 +813,9 @@ public static class DC // Data Converter return ar.ToArray(); } - public static UUID GetUUID(this byte[] data, uint offset) + public static Uuid GetUUID(this byte[] data, uint offset) { - return new UUID(data, offset); + return new Uuid(data, offset); } //public static Guid GetGuid(this byte[] data, uint offset) diff --git a/Esiur/Data/DataDeserializer.cs b/Esiur/Data/DataDeserializer.cs index 79c5ab5..f410c2a 100644 --- a/Esiur/Data/DataDeserializer.cs +++ b/Esiur/Data/DataDeserializer.cs @@ -17,246 +17,246 @@ namespace Esiur.Data; public static class DataDeserializer { - public static object NullParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static object NullParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { return null; } - public static object NullParser(ParsedTDU tdu, Warehouse warehouse) + public static object NullParser(ParsedTdu tdu, Warehouse warehouse) { return null; } - public static object BooleanTrueParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static object BooleanTrueParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { return true; } - public static object BooleanTrueParser(ParsedTDU tdu, Warehouse warehouse) + public static object BooleanTrueParser(ParsedTdu tdu, Warehouse warehouse) { return true; } - public static object BooleanFalseParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static object BooleanFalseParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { return false; } - public static object BooleanFalseParser(ParsedTDU tdu, Warehouse warehouse) + public static object BooleanFalseParser(ParsedTdu tdu, Warehouse warehouse) { return false; } - public static object NotModifiedParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static object NotModifiedParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { return NotModified.Default; } - public static object NotModifiedParser(ParsedTDU tdu, Warehouse warehouse) + public static object NotModifiedParser(ParsedTdu tdu, Warehouse warehouse) { return NotModified.Default; } - public static object UInt8ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static object UInt8ParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { return tdu.Data[tdu.Offset]; } - public static object UInt8Parser(ParsedTDU tdu, Warehouse warehouse) + public static object UInt8Parser(ParsedTdu tdu, Warehouse warehouse) { return tdu.Data[tdu.Offset]; } - public static object Int8ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static object Int8ParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { return (sbyte)tdu.Data[tdu.Offset]; } - public static object Int8Parser(ParsedTDU tdu, Warehouse warehouse) + public static object Int8Parser(ParsedTdu tdu, Warehouse warehouse) { return (sbyte)tdu.Data[tdu.Offset]; } - public static unsafe object Char16ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static unsafe object Char16ParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(char*)ptr; } - public static unsafe object Char16Parser(ParsedTDU tdu, Warehouse warehouse) + public static unsafe object Char16Parser(ParsedTdu tdu, Warehouse warehouse) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(char*)ptr; } - public static object Char8ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static object Char8ParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { return (char)tdu.Data[tdu.Offset]; } - public static object Char8Parser(ParsedTDU tdu, Warehouse warehouse) + public static object Char8Parser(ParsedTdu tdu, Warehouse warehouse) { return (char)tdu.Data[tdu.Offset]; } - public static unsafe object Int16ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static unsafe object Int16ParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(short*)ptr; } - public static unsafe object Int16Parser(ParsedTDU tdu, Warehouse warehouse) + public static unsafe object Int16Parser(ParsedTdu tdu, Warehouse warehouse) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(short*)ptr; } - public static unsafe object UInt16ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static unsafe object UInt16ParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(ushort*)ptr; } - public static unsafe object UInt16Parser(ParsedTDU tdu, Warehouse warehouse) + public static unsafe object UInt16Parser(ParsedTdu tdu, Warehouse warehouse) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(ushort*)ptr; } - public static unsafe object Int32ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static unsafe object Int32ParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(int*)ptr; } - public static unsafe object Int32Parser(ParsedTDU tdu, Warehouse warehouse) + public static unsafe object Int32Parser(ParsedTdu tdu, Warehouse warehouse) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(int*)ptr; } - public static unsafe object UInt32ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static unsafe object UInt32ParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(uint*)ptr; } - public static unsafe object UInt32Parser(ParsedTDU tdu, Warehouse warehouse) + public static unsafe object UInt32Parser(ParsedTdu tdu, Warehouse warehouse) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(uint*)ptr; } - public static unsafe object Float32ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static unsafe object Float32ParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(float*)ptr; } - public static unsafe object Float32Parser(ParsedTDU tdu, Warehouse warehouse) + public static unsafe object Float32Parser(ParsedTdu tdu, Warehouse warehouse) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(float*)ptr; } - public static unsafe object Float64ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static unsafe object Float64ParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(double*)ptr; } - public static unsafe object Float64Parser(ParsedTDU tdu, Warehouse warehouse) + public static unsafe object Float64Parser(ParsedTdu tdu, Warehouse warehouse) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(double*)ptr; } - public static unsafe object Decimal128ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static unsafe object Decimal128ParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(decimal*)ptr; } - public static unsafe object Decimal128Parser(ParsedTDU tdu, Warehouse warehouse) + public static unsafe object Decimal128Parser(ParsedTdu tdu, Warehouse warehouse) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(decimal*)ptr; } - public static unsafe object UUIDParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static unsafe object UUIDParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { - return new UUID(tdu.Data, tdu.Offset); + return new Uuid(tdu.Data, tdu.Offset); } - public static unsafe object UUIDParser(ParsedTDU tdu, Warehouse warehouse) + public static unsafe object UUIDParser(ParsedTdu tdu, Warehouse warehouse) { - return new UUID(tdu.Data, tdu.Offset); + return new Uuid(tdu.Data, tdu.Offset); } - public static unsafe object Int128ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static unsafe object Int128ParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr1 = &tdu.Data[tdu.Offset]) fixed (byte* ptr2 = &tdu.Data[tdu.Offset + 8]) return new Int128(*(ulong*)ptr1, *(ulong*)ptr2); } - public static unsafe object Int128Parser(ParsedTDU tdu, Warehouse warehouse) + public static unsafe object Int128Parser(ParsedTdu tdu, Warehouse warehouse) { fixed (byte* ptr1 = &tdu.Data[tdu.Offset]) fixed (byte* ptr2 = &tdu.Data[tdu.Offset + 8]) return new Int128(*(ulong*)ptr1, *(ulong*)ptr2); } - public static unsafe object UInt128ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static unsafe object UInt128ParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr1 = &tdu.Data[tdu.Offset]) fixed (byte* ptr2 = &tdu.Data[tdu.Offset + 8]) return new UInt128(*(ulong*)ptr1, *(ulong*)ptr2); } - public static unsafe object UInt128Parser(ParsedTDU tdu, Warehouse warehouse) + public static unsafe object UInt128Parser(ParsedTdu tdu, Warehouse warehouse) { fixed (byte* ptr1 = &tdu.Data[tdu.Offset]) fixed (byte* ptr2 = &tdu.Data[tdu.Offset + 8]) return new UInt128(*(ulong*)ptr1, *(ulong*)ptr2); } - public static unsafe object Int64ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static unsafe object Int64ParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(long*)ptr; } - public static unsafe object Int64Parser(ParsedTDU tdu, Warehouse warehouse) + public static unsafe object Int64Parser(ParsedTdu tdu, Warehouse warehouse) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(long*)ptr; } - public static unsafe object UInt64ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static unsafe object UInt64ParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(ulong*)ptr; } - public static unsafe object UInt64Parser(ParsedTDU tdu, Warehouse warehouse) + public static unsafe object UInt64Parser(ParsedTdu tdu, Warehouse warehouse) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(ulong*)ptr; } - public static unsafe object DateTimeParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static unsafe object DateTimeParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return new DateTime(*(long*)ptr, DateTimeKind.Utc); } - public static unsafe object DateTimeParser(ParsedTDU tdu, Warehouse warehouse) + public static unsafe object DateTimeParser(ParsedTdu tdu, Warehouse warehouse) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return new DateTime(*(long*)ptr, DateTimeKind.Utc); @@ -264,7 +264,7 @@ public static class DataDeserializer } - public static object ResourceLinkParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static object ResourceLinkParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { var link = tdu.Data.GetString(tdu.Offset, (uint)tdu.ContentLength); if (connection == null) @@ -277,13 +277,13 @@ public static class DataDeserializer } } - public static object ResourceLinkParser(ParsedTDU tdu, Warehouse warehouse) + public static object ResourceLinkParser(ParsedTdu tdu, Warehouse warehouse) { var link = tdu.Data.GetString(tdu.Offset, (uint)tdu.ContentLength); return new ResourceLink(link); } - public static unsafe object ResourceParser8Async(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static unsafe object ResourceParser8Async(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { if (connection == null) return new ResourceId(false, tdu.Data[tdu.Offset]); @@ -291,12 +291,12 @@ public static class DataDeserializer return connection.Fetch(tdu.Data[tdu.Offset], requestSequence); } - public static unsafe object ResourceParser8(ParsedTDU tdu, Warehouse warehouse) + public static unsafe object ResourceParser8(ParsedTdu tdu, Warehouse warehouse) { return new ResourceId(false, tdu.Data[tdu.Offset]); } - public static unsafe object LocalResourceParser8Async(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static unsafe object LocalResourceParser8Async(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { if (connection == null) return new ResourceId(true, tdu.Data[tdu.Offset]); @@ -304,12 +304,12 @@ public static class DataDeserializer return connection.Instance.Warehouse.GetById(tdu.Data[tdu.Offset]); } - public static unsafe object LocalResourceParser8(ParsedTDU tdu, Warehouse warehouse) + public static unsafe object LocalResourceParser8(ParsedTdu tdu, Warehouse warehouse) { return new ResourceId(true, tdu.Data[tdu.Offset]); } - public static unsafe object ResourceParser16Async(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static unsafe object ResourceParser16Async(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) if (connection == null) @@ -318,14 +318,14 @@ public static class DataDeserializer return connection.Fetch(*(ushort*)ptr, requestSequence); } - public static unsafe object ResourceParser16(ParsedTDU tdu, Warehouse warehouse) + public static unsafe object ResourceParser16(ParsedTdu tdu, Warehouse warehouse) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return new ResourceId(false, *(ushort*)ptr); } - public static unsafe object LocalResourceParser16Async(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static unsafe object LocalResourceParser16Async(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) if (connection == null) @@ -334,13 +334,13 @@ public static class DataDeserializer return connection.Instance.Warehouse.GetById(*(ushort*)ptr); } - public static unsafe object LocalResourceParser16(ParsedTDU tdu, Warehouse warehouse) + public static unsafe object LocalResourceParser16(ParsedTdu tdu, Warehouse warehouse) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return new ResourceId(true, *(ushort*)ptr); } - public static unsafe object ResourceParser32Async(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static unsafe object ResourceParser32Async(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) if (connection == null) @@ -349,14 +349,14 @@ public static class DataDeserializer return connection.Fetch(*(uint*)ptr, requestSequence); } - public static unsafe object ResourceParser32(ParsedTDU tdu, Warehouse warehouse) + public static unsafe object ResourceParser32(ParsedTdu tdu, Warehouse warehouse) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return new ResourceId(false, *(uint*)ptr); } - public static unsafe object LocalResourceParser32Async(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static unsafe object LocalResourceParser32Async(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) if (connection == null) @@ -365,35 +365,35 @@ public static class DataDeserializer return connection.Instance.Warehouse.GetById(*(uint*)ptr); } - public static unsafe object LocalResourceParser32(ParsedTDU tdu, Warehouse warehouse) + public static unsafe object LocalResourceParser32(ParsedTdu tdu, Warehouse warehouse) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return new ResourceId(true, *(uint*)ptr); } - public static unsafe object RawDataParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static unsafe object RawDataParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { return tdu.Data.Clip(tdu.Offset, (uint)tdu.ContentLength); } - public static unsafe object RawDataParser(ParsedTDU tdu, Warehouse warehouse) + public static unsafe object RawDataParser(ParsedTdu tdu, Warehouse warehouse) { return tdu.Data.Clip(tdu.Offset, (uint)tdu.ContentLength); } - public static unsafe object StringParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static unsafe object StringParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { return tdu.Data.GetString(tdu.Offset, (uint)tdu.ContentLength); } - public static unsafe object StringParser(ParsedTDU tdu, Warehouse warehouse) + public static unsafe object StringParser(ParsedTdu tdu, Warehouse warehouse) { return tdu.Data.GetString(tdu.Offset, (uint)tdu.ContentLength); } - public static unsafe object RecordParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static unsafe object RecordParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { var typeId = tdu.Metadata.GetUUID(0); var typeDef = connection.Instance.Warehouse.GetTypeDefById(typeId, @@ -403,8 +403,8 @@ public static class DataDeserializer var list = new AsyncBag(); - ParsedTDU current; - ParsedTDU? previous = null; + ParsedTdu current; + ParsedTdu? previous = null; var offset = tdu.Offset; var length = tdu.ContentLength; @@ -414,22 +414,22 @@ public static class DataDeserializer { for (var i = 0; i < typeDef.Properties.Length; i++) { - current = ParsedTDU.Parse(tdu.Data, offset, ends); + current = ParsedTdu.Parse(tdu.Data, offset, ends); - if (current.Class == TDUClass.Invalid) + if (current.Class == TduClass.Invalid) throw new Exception("Unknown type."); - if (current.Identifier == TDUIdentifier.TypeContinuation) + if (current.Identifier == TduIdentifier.TypeContinuation) { current.Class = previous.Value.Class; current.Identifier = previous.Value.Identifier; current.Metadata = previous.Value.Metadata; } - else if (current.Identifier == TDUIdentifier.TypeOfTarget) + else if (current.Identifier == TduIdentifier.TypeOfTarget) { var (idf, mt) = typeDef.Properties[i].ValueType.GetMetadata(); - current.Class = TDUClass.Typed; + current.Class = TduClass.Typed; current.Identifier = idf; current.Metadata = mt; current.Index = (int)idf & 0x7; @@ -515,7 +515,7 @@ public static class DataDeserializer } - public static unsafe object RecordParser(ParsedTDU tdu, Warehouse warehouse) + public static unsafe object RecordParser(ParsedTdu tdu, Warehouse warehouse) { var typeId = tdu.Metadata.GetUUID(0); var typeDef = warehouse.GetTypeDefById(typeId, TypeDefKind.Record); @@ -529,8 +529,8 @@ public static class DataDeserializer var list = new List(); - ParsedTDU current; - ParsedTDU? previous = null; + ParsedTdu current; + ParsedTdu? previous = null; var offset = tdu.Offset; var length = tdu.ContentLength; @@ -539,22 +539,22 @@ public static class DataDeserializer for (var i = 0; i < typeDef.Properties.Length; i++) { - current = ParsedTDU.Parse(tdu.Data, offset, ends); + current = ParsedTdu.Parse(tdu.Data, offset, ends); - if (current.Class == TDUClass.Invalid) + if (current.Class == TduClass.Invalid) throw new Exception("Unknown type."); - if (current.Identifier == TDUIdentifier.TypeContinuation) + if (current.Identifier == TduIdentifier.TypeContinuation) { current.Class = previous.Value.Class; current.Identifier = previous.Value.Identifier; current.Metadata = previous.Value.Metadata; } - else if (current.Identifier == TDUIdentifier.TypeOfTarget) + else if (current.Identifier == TduIdentifier.TypeOfTarget) { var (idf, mt) = typeDef.Properties[i].ValueType.GetMetadata(); - current.Class = TDUClass.Typed; + current.Class = TduClass.Typed; current.Identifier = idf; current.Metadata = mt; current.Index = (int)idf & 0x7; @@ -605,17 +605,17 @@ public static class DataDeserializer } } - public static unsafe object ConstantParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static unsafe object ConstantParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { throw new NotImplementedException(); } - public static unsafe object ConstantParser(ParsedTDU tdu, Warehouse warehouse) + public static unsafe object ConstantParser(ParsedTdu tdu, Warehouse warehouse) { throw new NotImplementedException(); } - public static unsafe AsyncReply EnumParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static unsafe AsyncReply EnumParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { var typeId = tdu.Metadata.GetUUID(0); @@ -643,7 +643,7 @@ public static class DataDeserializer } } - public static unsafe object EnumParser(ParsedTDU tdu, Warehouse warehouse) + public static unsafe object EnumParser(ParsedTdu tdu, Warehouse warehouse) { var typeId = tdu.Metadata.GetUUID(0); @@ -664,7 +664,7 @@ public static class DataDeserializer } - public static AsyncReply RecordListParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static AsyncReply RecordListParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { var rt = new AsyncBag(); @@ -691,7 +691,7 @@ public static class DataDeserializer return rt; } - public static object RecordListParser(ParsedTDU tdu, Warehouse warehouse) + public static object RecordListParser(ParsedTdu tdu, Warehouse warehouse) { var rt = new List(); @@ -717,7 +717,7 @@ public static class DataDeserializer return rt.ToArray(); } - public static AsyncReply ResourceListParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static AsyncReply ResourceListParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { var rt = new AsyncBag(); @@ -745,7 +745,7 @@ public static class DataDeserializer } - public static object ResourceListParser(ParsedTDU tdu, Warehouse warehouse) + public static object ResourceListParser(ParsedTdu tdu, Warehouse warehouse) { var rt = new List(); @@ -771,7 +771,7 @@ public static class DataDeserializer return rt.ToArray(); } - public static AsyncBag ListParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static AsyncBag ListParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { //var rt = new AsyncBag(); @@ -806,8 +806,8 @@ public static class DataDeserializer //var list = new List(); - ParsedTDU current; - ParsedTDU? previous = null; + ParsedTdu current; + ParsedTdu? previous = null; var offset = tdu.Offset; var length = tdu.ContentLength; @@ -815,13 +815,13 @@ public static class DataDeserializer while (length > 0) { - current = ParsedTDU.Parse(tdu.Data, offset, ends); + current = ParsedTdu.Parse(tdu.Data, offset, ends); - if (current.Class == TDUClass.Invalid) + if (current.Class == TduClass.Invalid) throw new Exception("Unknown type."); - if (current.Identifier == TDUIdentifier.TypeContinuation) + if (current.Identifier == TduIdentifier.TypeContinuation) { current.Class = previous.Value.Class; current.Identifier = previous.Value.Identifier; @@ -850,12 +850,12 @@ public static class DataDeserializer } - public static object ListParser(ParsedTDU tdu, Warehouse warehouse) + public static object ListParser(ParsedTdu tdu, Warehouse warehouse) { var list = new List(); - ParsedTDU current; - ParsedTDU? previous = null; + ParsedTdu current; + ParsedTdu? previous = null; var offset = tdu.Offset; var length = tdu.ContentLength; @@ -863,13 +863,13 @@ public static class DataDeserializer while (length > 0) { - current = ParsedTDU.Parse(tdu.Data, offset, ends); + current = ParsedTdu.Parse(tdu.Data, offset, ends); - if (current.Class == TDUClass.Invalid) + if (current.Class == TduClass.Invalid) throw new Exception("Unknown type."); - if (current.Identifier == TDUIdentifier.TypeContinuation) + if (current.Identifier == TduIdentifier.TypeContinuation) { current.Class = previous.Value.Class; current.Identifier = previous.Value.Identifier; @@ -923,25 +923,25 @@ public static class DataDeserializer } - public static AsyncReply TypedMapParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static AsyncReply TypedMapParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { var rt = new AsyncReply(); // get key type - var (keyCs, keysTru) = TRU.Parse(tdu.Metadata, 0); - var (valueCs, valuesTru) = TRU.Parse(tdu.Metadata, keyCs); + var (keyCs, keysTru) = Tru.Parse(tdu.Metadata, 0); + var (valueCs, valuesTru) = Tru.Parse(tdu.Metadata, keyCs); var map = (IMap)Activator.CreateInstance(typeof(Map<,>).MakeGenericType( keysTru.GetRuntimeType(connection.Instance.Warehouse), valuesTru.GetRuntimeType(connection.Instance.Warehouse))); - var keysTdu = ParsedTDU.Parse(tdu.Data, tdu.Offset, + var keysTdu = ParsedTdu.Parse(tdu.Data, tdu.Offset, (uint)(tdu.Offset + tdu.ContentLength)); - var valuesTdu = ParsedTDU.Parse(tdu.Data, + var valuesTdu = ParsedTdu.Parse(tdu.Data, (uint)(keysTdu.Offset + keysTdu.ContentLength), tdu.Ends); @@ -1011,29 +1011,29 @@ public static class DataDeserializer } - public static Array TypedArrayParser(ParsedTDU tdu, TRU tru, Warehouse warehouse) + public static Array TypedArrayParser(ParsedTdu tdu, Tru tru, Warehouse warehouse) { switch (tru.Identifier) { - case TRUIdentifier.Int32: + case TruIdentifier.Int32: return GroupInt32Codec.Decode(tdu.Data.AsSpan( (int)tdu.Offset, (int)tdu.ContentLength)); - case TRUIdentifier.Int64: + case TruIdentifier.Int64: return GroupInt64Codec.Decode(tdu.Data.AsSpan( (int)tdu.Offset, (int)tdu.ContentLength)); - case TRUIdentifier.Int16: + case TruIdentifier.Int16: return GroupInt16Codec.Decode(tdu.Data.AsSpan( (int)tdu.Offset, (int)tdu.ContentLength)); - case TRUIdentifier.UInt32: + case TruIdentifier.UInt32: return GroupUInt32Codec.Decode(tdu.Data.AsSpan( (int)tdu.Offset, (int)tdu.ContentLength)); - case TRUIdentifier.UInt64: + case TruIdentifier.UInt64: return GroupUInt64Codec.Decode(tdu.Data.AsSpan( (int)tdu.Offset, (int)tdu.ContentLength)); - case TRUIdentifier.UInt16: + case TruIdentifier.UInt16: return GroupUInt16Codec.Decode(tdu.Data.AsSpan( (int)tdu.Offset, (int)tdu.ContentLength)); - case TRUIdentifier.Enum: + case TruIdentifier.Enum: var enumType = tru.GetRuntimeType(warehouse); @@ -1053,8 +1053,8 @@ public static class DataDeserializer var list = new List(); - ParsedTDU current; - ParsedTDU? previous = null; + ParsedTdu current; + ParsedTdu? previous = null; var offset = tdu.Offset; var length = tdu.ContentLength; @@ -1062,22 +1062,22 @@ public static class DataDeserializer while (length > 0) { - current = ParsedTDU.Parse(tdu.Data, offset, ends); + current = ParsedTdu.Parse(tdu.Data, offset, ends); - if (current.Class == TDUClass.Invalid) + if (current.Class == TduClass.Invalid) throw new Exception("Unknown type."); - if (current.Identifier == TDUIdentifier.TypeContinuation) + if (current.Identifier == TduIdentifier.TypeContinuation) { current.Class = previous.Value.Class; current.Identifier = previous.Value.Identifier; current.Metadata = previous.Value.Metadata; } - else if (current.Identifier == TDUIdentifier.TypeOfTarget) + else if (current.Identifier == TduIdentifier.TypeOfTarget) { var (idf, mt) = tru.GetMetadata(); - current.Class = TDUClass.Typed; + current.Class = TduClass.Typed; current.Identifier = idf; current.Metadata = mt; current.Index = (int)idf & 0x7; @@ -1107,21 +1107,21 @@ public static class DataDeserializer } - public static object TypedMapParser(ParsedTDU tdu, Warehouse warehouse) + public static object TypedMapParser(ParsedTdu tdu, Warehouse warehouse) { // get key type - var (keyCs, keysTru) = TRU.Parse(tdu.Metadata, 0); - var (valueCs, valuesTru) = TRU.Parse(tdu.Metadata, keyCs); + var (keyCs, keysTru) = Tru.Parse(tdu.Metadata, 0); + var (valueCs, valuesTru) = Tru.Parse(tdu.Metadata, keyCs); var map = (IMap)Activator.CreateInstance(typeof(Map<,>).MakeGenericType(keysTru.GetRuntimeType(warehouse), valuesTru.GetRuntimeType(warehouse))); - var keysTdu = ParsedTDU.Parse(tdu.Data, tdu.Offset, + var keysTdu = ParsedTdu.Parse(tdu.Data, tdu.Offset, (uint)(tdu.Offset + tdu.ContentLength)); - var valuesTdu = ParsedTDU.Parse(tdu.Data, + var valuesTdu = ParsedTdu.Parse(tdu.Data, (uint)(keysTdu.Offset + keysTdu.ContentLength), tdu.Ends); @@ -1135,20 +1135,20 @@ public static class DataDeserializer } - public static AsyncReply TupleParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static AsyncReply TupleParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { var rt = new AsyncReply(); // var tupleSize = tdu.Metadata[0]; - var trus = new List(); + var trus = new List(); uint mtOffset = 0; while (mtOffset < tdu.Metadata.Length) { - var (cs, tru) = TRU.Parse(tdu.Metadata, mtOffset); + var (cs, tru) = Tru.Parse(tdu.Metadata, mtOffset); trus.Add(tru); mtOffset += cs; } @@ -1156,8 +1156,8 @@ public static class DataDeserializer var results = new AsyncBag(); var types = trus.Select(x => x.GetRuntimeType(connection.Instance.Warehouse)).ToArray(); - ParsedTDU current; - ParsedTDU? previous = null; + ParsedTdu current; + ParsedTdu? previous = null; var offset = tdu.Offset; var length = tdu.ContentLength; @@ -1166,15 +1166,15 @@ public static class DataDeserializer for (var i = 0; i < trus.Count; i++) { - current = ParsedTDU.Parse(tdu.Data, offset, ends); + current = ParsedTdu.Parse(tdu.Data, offset, ends); - if (current.Class == TDUClass.Invalid) + if (current.Class == TduClass.Invalid) throw new Exception("Unknown type."); - if (current.Identifier == TDUIdentifier.TypeOfTarget) + if (current.Identifier == TduIdentifier.TypeOfTarget) { var (idf, mt) = trus[i].GetMetadata(); - current.Class = TDUClass.Typed; + current.Class = TduClass.Typed; current.Identifier = idf; current.Metadata = mt; current.Index = (int)idf & 0x7; @@ -1234,16 +1234,16 @@ public static class DataDeserializer return rt; } - public static object TupleParser(ParsedTDU tdu, Warehouse warehouse) + public static object TupleParser(ParsedTdu tdu, Warehouse warehouse) { var tupleSize = tdu.Metadata[0]; - var trus = new List(); + var trus = new List(); uint mtOffset = 1; for (var i = 0; i < tupleSize; i++) { - var (cs, tru) = TRU.Parse(tdu.Metadata, mtOffset); + var (cs, tru) = Tru.Parse(tdu.Metadata, mtOffset); trus.Add(tru); mtOffset += cs; } @@ -1251,8 +1251,8 @@ public static class DataDeserializer var results = new List(); var types = trus.Select(x => x.GetRuntimeType(warehouse)).ToArray(); - ParsedTDU current; - ParsedTDU? previous = null; + ParsedTdu current; + ParsedTdu? previous = null; var offset = tdu.Offset; var length = tdu.ContentLength; @@ -1261,15 +1261,15 @@ public static class DataDeserializer for (var i = 0; i < tupleSize; i++) { - current = ParsedTDU.Parse(tdu.Data, offset, ends); + current = ParsedTdu.Parse(tdu.Data, offset, ends); - if (current.Class == TDUClass.Invalid) + if (current.Class == TduClass.Invalid) throw new Exception("Unknown type."); - if (current.Identifier == TDUIdentifier.TypeOfTarget) + if (current.Identifier == TduIdentifier.TypeOfTarget) { var (idf, mt) = trus[i].GetMetadata(); - current.Class = TDUClass.Typed; + current.Class = TduClass.Typed; current.Identifier = idf; current.Metadata = mt; current.Index = (int)idf & 0x7; @@ -1325,30 +1325,30 @@ public static class DataDeserializer } - public static AsyncReply TypedArrayParserAsync(ParsedTDU tdu, TRU tru, EpConnection connection, uint[] requestSequence) + public static AsyncReply TypedArrayParserAsync(ParsedTdu tdu, Tru tru, EpConnection connection, uint[] requestSequence) { switch (tru.Identifier) { - case TRUIdentifier.Int32: + case TruIdentifier.Int32: return new AsyncReply(GroupInt32Codec.Decode(tdu.Data.AsSpan( (int)tdu.Offset, (int)tdu.ContentLength))); - case TRUIdentifier.Int64: + case TruIdentifier.Int64: return new AsyncReply(GroupInt64Codec.Decode(tdu.Data.AsSpan( (int)tdu.Offset, (int)tdu.ContentLength))); - case TRUIdentifier.Int16: + case TruIdentifier.Int16: return new AsyncReply(GroupInt16Codec.Decode(tdu.Data.AsSpan( (int)tdu.Offset, (int)tdu.ContentLength))); - case TRUIdentifier.UInt32: + case TruIdentifier.UInt32: return new AsyncReply(GroupUInt32Codec.Decode(tdu.Data.AsSpan( (int)tdu.Offset, (int)tdu.ContentLength))); - case TRUIdentifier.UInt64: + case TruIdentifier.UInt64: return new AsyncReply(GroupUInt64Codec.Decode(tdu.Data.AsSpan( (int)tdu.Offset, (int)tdu.ContentLength))); - case TRUIdentifier.UInt16: + case TruIdentifier.UInt16: return new AsyncReply(GroupUInt16Codec.Decode(tdu.Data.AsSpan( (int)tdu.Offset, (int)tdu.ContentLength))); - case TRUIdentifier.Enum: + case TruIdentifier.Enum: var enumType = tru.GetRuntimeType(connection.Instance.Warehouse); var rt = Array.CreateInstance(enumType, (int)tdu.ContentLength); @@ -1370,8 +1370,8 @@ public static class DataDeserializer list.ArrayType = tru.GetRuntimeType(connection.Instance.Warehouse); - ParsedTDU current; - ParsedTDU? previous = null; + ParsedTdu current; + ParsedTdu? previous = null; var offset = tdu.Offset; var length = tdu.ContentLength; @@ -1379,22 +1379,22 @@ public static class DataDeserializer while (length > 0) { - current = ParsedTDU.Parse(tdu.Data, offset, ends); + current = ParsedTdu.Parse(tdu.Data, offset, ends); - if (current.Class == TDUClass.Invalid) + if (current.Class == TduClass.Invalid) throw new Exception("Unknown type."); - if (current.Identifier == TDUIdentifier.TypeContinuation) + if (current.Identifier == TduIdentifier.TypeContinuation) { current.Class = previous.Value.Class; current.Identifier = previous.Value.Identifier; current.Metadata = previous.Value.Metadata; } - else if (current.Identifier == TDUIdentifier.TypeOfTarget) + else if (current.Identifier == TduIdentifier.TypeOfTarget) { var (idf, mt) = tru.GetMetadata(); - current.Class = TDUClass.Typed; + current.Class = TduClass.Typed; current.Identifier = idf; current.Metadata = mt; current.Index = (int)idf & 0x7; @@ -1421,10 +1421,10 @@ public static class DataDeserializer } - public static AsyncReply TypedListParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) + public static AsyncReply TypedListParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { // get the type - var (hdrCs, tru) = TRU.Parse(tdu.Metadata, 0); + var (hdrCs, tru) = Tru.Parse(tdu.Metadata, 0); return TypedArrayParserAsync(tdu, tru, connection, requestSequence); @@ -1498,10 +1498,10 @@ public static class DataDeserializer //} } - public static object TypedListParser(ParsedTDU tdu, Warehouse warehouse) + public static object TypedListParser(ParsedTdu tdu, Warehouse warehouse) { // get the type - var (hdrCs, tru) = TRU.Parse(tdu.Metadata, 0); + var (hdrCs, tru) = Tru.Parse(tdu.Metadata, 0); return TypedArrayParser(tdu, tru, warehouse); } @@ -1511,7 +1511,7 @@ public static class DataDeserializer var rt = new AsyncBag(); - ListParserAsync(new ParsedTDU() { Data = data, Offset = offset, ContentLength = length } + ListParserAsync(new ParsedTdu() { Data = data, Offset = offset, ContentLength = length } , connection, requestSequence).Then(x => { diff --git a/Esiur/Data/DataSerializer.cs b/Esiur/Data/DataSerializer.cs index e2c6a97..8a09d0b 100644 --- a/Esiur/Data/DataSerializer.cs +++ b/Esiur/Data/DataSerializer.cs @@ -17,13 +17,13 @@ public static class DataSerializer { public delegate byte[] Serializer(object value); - public static unsafe TDU Int32Composer(object value, Warehouse warehouse, EpConnection connection) + public static unsafe Tdu Int32Composer(object value, Warehouse warehouse, EpConnection connection) { var v = (int)value; if (v >= sbyte.MinValue && v <= sbyte.MaxValue) { - return new TDU(TDUIdentifier.Int8, new byte[] { (byte)(sbyte)v }, 1); + return new Tdu(TduIdentifier.Int8, new byte[] { (byte)(sbyte)v }, 1); } else if (v >= short.MinValue && v <= short.MaxValue) { @@ -32,7 +32,7 @@ public static class DataSerializer fixed (byte* ptr = rt) *((short*)ptr) = (short)v; - return new TDU(TDUIdentifier.Int16, rt, 2); + return new Tdu(TduIdentifier.Int16, rt, 2); } else { @@ -40,18 +40,18 @@ public static class DataSerializer var rt = new byte[4]; fixed (byte* ptr = rt) *((int*)ptr) = v; - return new TDU(TDUIdentifier.Int32, rt, 4); + return new Tdu(TduIdentifier.Int32, rt, 4); } } - public static unsafe TDU UInt32Composer(object value, Warehouse warehouse, EpConnection connection) + public static unsafe Tdu UInt32Composer(object value, Warehouse warehouse, EpConnection connection) { var v = (uint)value; if (v <= byte.MaxValue) { // Fits in 1 byte - return new TDU(TDUIdentifier.UInt8, new byte[] { (byte)v }, 1); + return new Tdu(TduIdentifier.UInt8, new byte[] { (byte)v }, 1); } else if (v <= ushort.MaxValue) { @@ -60,7 +60,7 @@ public static class DataSerializer fixed (byte* ptr = rt) *((ushort*)ptr) = (ushort)v; - return new TDU(TDUIdentifier.UInt16, rt, 2); + return new Tdu(TduIdentifier.UInt16, rt, 2); } else { @@ -69,18 +69,18 @@ public static class DataSerializer fixed (byte* ptr = rt) *((uint*)ptr) = v; - return new TDU(TDUIdentifier.UInt32, rt, 4); + return new Tdu(TduIdentifier.UInt32, rt, 4); } } - public static unsafe TDU Int16Composer(object value, Warehouse warehouse, EpConnection connection) + public static unsafe Tdu Int16Composer(object value, Warehouse warehouse, EpConnection connection) { var v = (short)value; if (v >= sbyte.MinValue && v <= sbyte.MaxValue) { // Fits in 1 byte - return new TDU(TDUIdentifier.Int8, new byte[] { (byte)(sbyte)v }, 1); + return new Tdu(TduIdentifier.Int8, new byte[] { (byte)(sbyte)v }, 1); } else { @@ -89,18 +89,18 @@ public static class DataSerializer fixed (byte* ptr = rt) *((short*)ptr) = v; - return new TDU(TDUIdentifier.Int16, rt, 2); + return new Tdu(TduIdentifier.Int16, rt, 2); } } - public static unsafe TDU UInt16Composer(object value, Warehouse warehouse, EpConnection connection) + public static unsafe Tdu UInt16Composer(object value, Warehouse warehouse, EpConnection connection) { var v = (ushort)value; if (v <= byte.MaxValue) { // Fits in 1 byte - return new TDU(TDUIdentifier.UInt8, new byte[] { (byte)v }, 1); + return new Tdu(TduIdentifier.UInt8, new byte[] { (byte)v }, 1); } else { @@ -109,19 +109,19 @@ public static class DataSerializer fixed (byte* ptr = rt) *((ushort*)ptr) = v; - return new TDU(TDUIdentifier.UInt16, rt, 2); + return new Tdu(TduIdentifier.UInt16, rt, 2); } } - public static unsafe TDU Float32Composer(object value, Warehouse warehouse, EpConnection connection) + public static unsafe Tdu Float32Composer(object value, Warehouse warehouse, EpConnection connection) { float v = (float)value; // Special IEEE-754 values if (float.IsNaN(v) || float.IsInfinity(v)) { - return new TDU(TDUIdentifier.Infinity, new byte[0], 0); + return new Tdu(TduIdentifier.Infinity, new byte[0], 0); } // If v is an exact integer, prefer smallest signed width up to Int32 @@ -130,7 +130,7 @@ public static class DataSerializer // Note: casts are safe because we check bounds first. if (v >= sbyte.MinValue && v <= sbyte.MaxValue) { - return new TDU(TDUIdentifier.Int8, new byte[] { (byte)(sbyte)v }, 1); + return new Tdu(TduIdentifier.Int8, new byte[] { (byte)(sbyte)v }, 1); } if (v >= short.MinValue && v <= short.MaxValue) @@ -138,7 +138,7 @@ public static class DataSerializer var rt = new byte[2]; fixed (byte* ptr = rt) *((short*)ptr) = (short)v; - return new TDU(TDUIdentifier.Int16, rt, 2); + return new Tdu(TduIdentifier.Int16, rt, 2); } } @@ -147,26 +147,26 @@ public static class DataSerializer var rt = new byte[4]; fixed (byte* ptr = rt) *((float*)ptr) = v; - return new TDU(TDUIdentifier.Float32, rt, 4); + return new Tdu(TduIdentifier.Float32, rt, 4); } } - public unsafe static TDU Float64Composer(object value, Warehouse warehouse, EpConnection connection) + public unsafe static Tdu Float64Composer(object value, Warehouse warehouse, EpConnection connection) { double v = (double)value; // Special IEEE-754 values if (double.IsNaN(v) || double.IsInfinity(v)) { - return new TDU(TDUIdentifier.Infinity, new byte[0], 0); + return new Tdu(TduIdentifier.Infinity, new byte[0], 0); } // If v is an exact integer, choose the smallest signed width if (v == Math.Truncate(v)) { if (v >= sbyte.MinValue && v <= sbyte.MaxValue) - return new TDU(TDUIdentifier.Int8, new byte[] { (byte)(sbyte)v }, 1); + return new Tdu(TduIdentifier.Int8, new byte[] { (byte)(sbyte)v }, 1); if (v >= short.MinValue && v <= short.MaxValue) { @@ -175,7 +175,7 @@ public static class DataSerializer fixed (byte* ptr = rt) *((short*)ptr) = (short)v; - return new TDU(TDUIdentifier.Int16, rt, 2); + return new Tdu(TduIdentifier.Int16, rt, 2); } if (v >= int.MinValue && v <= int.MaxValue) @@ -185,7 +185,7 @@ public static class DataSerializer fixed (byte* ptr = rt) *((int*)ptr) = (int)v; - return new TDU(TDUIdentifier.Int32, rt, 4); + return new Tdu(TduIdentifier.Int32, rt, 4); } // If it's integral but outside Int64 range, fall through to Float64. @@ -200,7 +200,7 @@ public static class DataSerializer fixed (byte* ptr = rt) *((float*)ptr) = f; - return new TDU(TDUIdentifier.Float32, rt, 4); + return new Tdu(TduIdentifier.Float32, rt, 4); } // Default: Float64 @@ -208,17 +208,17 @@ public static class DataSerializer var rt = new byte[8]; fixed (byte* ptr = rt) *((double*)ptr) = v; - return new TDU(TDUIdentifier.Float64, rt, 8); + return new Tdu(TduIdentifier.Float64, rt, 8); } } - public static unsafe TDU Int64Composer(object value, Warehouse warehouse, EpConnection connection) + public static unsafe Tdu Int64Composer(object value, Warehouse warehouse, EpConnection connection) { var v = (long)value; if (v >= sbyte.MinValue && v <= sbyte.MaxValue) { // Fits in 1 byte - return new TDU(TDUIdentifier.Int8, new byte[] { (byte)(sbyte)v }, 1); + return new Tdu(TduIdentifier.Int8, new byte[] { (byte)(sbyte)v }, 1); } else if (v >= short.MinValue && v <= short.MaxValue) { @@ -227,7 +227,7 @@ public static class DataSerializer fixed (byte* ptr = rt) *((short*)ptr) = (short)v; - return new TDU(TDUIdentifier.Int16, rt, 2); + return new Tdu(TduIdentifier.Int16, rt, 2); } else if (v >= int.MinValue && v <= int.MaxValue) { @@ -236,7 +236,7 @@ public static class DataSerializer fixed (byte* ptr = rt) *((int*)ptr) = (int)v; - return new TDU(TDUIdentifier.Int32, rt, 4); + return new Tdu(TduIdentifier.Int32, rt, 4); } else { @@ -245,18 +245,18 @@ public static class DataSerializer fixed (byte* ptr = rt) *((long*)ptr) = v; - return new TDU(TDUIdentifier.Int64, rt, 8); + return new Tdu(TduIdentifier.Int64, rt, 8); } } - public static unsafe TDU UInt64Composer(object value, Warehouse warehouse, EpConnection connection) + public static unsafe Tdu UInt64Composer(object value, Warehouse warehouse, EpConnection connection) { var v = (ulong)value; if (v <= byte.MaxValue) { // Fits in 1 byte - return new TDU(TDUIdentifier.UInt8, new byte[] { (byte)v }, 1); + return new Tdu(TduIdentifier.UInt8, new byte[] { (byte)v }, 1); } else if (v <= ushort.MaxValue) { @@ -265,7 +265,7 @@ public static class DataSerializer fixed (byte* ptr = rt) *((ushort*)ptr) = (ushort)v; - return new TDU(TDUIdentifier.UInt16, rt, 2); + return new Tdu(TduIdentifier.UInt16, rt, 2); } else if (v <= uint.MaxValue) { @@ -274,7 +274,7 @@ public static class DataSerializer fixed (byte* ptr = rt) *((uint*)ptr) = (uint)v; - return new TDU(TDUIdentifier.UInt32, rt, 4); + return new Tdu(TduIdentifier.UInt32, rt, 4); } else { @@ -283,19 +283,19 @@ public static class DataSerializer fixed (byte* ptr = rt) *((ulong*)ptr) = v; - return new TDU(TDUIdentifier.UInt64, rt, 8); + return new Tdu(TduIdentifier.UInt64, rt, 8); } } - public static unsafe TDU DateTimeComposer(object value, Warehouse warehouse, EpConnection connection) + public static unsafe Tdu DateTimeComposer(object value, Warehouse warehouse, EpConnection connection) { var v = ((DateTime)value).ToUniversalTime().Ticks; var rt = new byte[8]; fixed (byte* ptr = rt) *((long*)ptr) = v; - return new TDU(TDUIdentifier.DateTime, rt, 8); + return new Tdu(TduIdentifier.DateTime, rt, 8); } //public static unsafe TDU Decimal128Composer(object value, Warehouse warehouse, EpConnection connection) @@ -308,7 +308,7 @@ public static class DataSerializer // return new TDU(TDUIdentifier.Decimal128, rt, 16); //} - public static unsafe TDU Decimal128Composer(object value, Warehouse warehouse, EpConnection connection) + public static unsafe Tdu Decimal128Composer(object value, Warehouse warehouse, EpConnection connection) { var v = (decimal)value; @@ -320,27 +320,27 @@ public static class DataSerializer if (scale == 0) { if (v >= sbyte.MinValue && v <= sbyte.MaxValue) - return new TDU(TDUIdentifier.Int8, new byte[] { (byte)(sbyte)v }, 1); + return new Tdu(TduIdentifier.Int8, new byte[] { (byte)(sbyte)v }, 1); if (v >= short.MinValue && v <= short.MaxValue) { var b = new byte[2]; BinaryPrimitives.WriteInt16LittleEndian(b, (short)v); - return new TDU(TDUIdentifier.Int16, b, 2); + return new Tdu(TduIdentifier.Int16, b, 2); } if (v >= int.MinValue && v <= int.MaxValue) { var b = new byte[4]; BinaryPrimitives.WriteInt32LittleEndian(b, (int)v); - return new TDU(TDUIdentifier.Int32, b, 4); + return new Tdu(TduIdentifier.Int32, b, 4); } if (v >= long.MinValue && v <= long.MaxValue) { var b = new byte[8]; BinaryPrimitives.WriteInt64LittleEndian(b, (long)v); - return new TDU(TDUIdentifier.Int64, b, 8); + return new Tdu(TduIdentifier.Int64, b, 8); } // else fall through (needs 96+ bits) } @@ -355,7 +355,7 @@ public static class DataSerializer fixed (byte* ptr = rt) *((float*)ptr) = f; - return new TDU(TDUIdentifier.Float32, rt, 4); + return new Tdu(TduIdentifier.Float32, rt, 4); } // Try exact Float64 (8 bytes) @@ -367,7 +367,7 @@ public static class DataSerializer fixed (byte* ptr = rt) *((double*)ptr) = d; - return new TDU(TDUIdentifier.Float64, rt, 8); + return new Tdu(TduIdentifier.Float64, rt, 8); } { @@ -377,29 +377,29 @@ public static class DataSerializer fixed (byte* ptr = rt) *((decimal*)ptr) = v; - return new TDU(TDUIdentifier.Decimal128, rt, 16); + return new Tdu(TduIdentifier.Decimal128, rt, 16); } } - public static TDU StringComposer(object value, Warehouse warehouse, EpConnection connection) + public static Tdu StringComposer(object value, Warehouse warehouse, EpConnection connection) { var b = Encoding.UTF8.GetBytes((string)value); - return new TDU(TDUIdentifier.String, b, (uint)b.Length); + return new Tdu(TduIdentifier.String, b, (uint)b.Length); } - public static TDU ResourceLinkComposer(object value, Warehouse warehouse, EpConnection connection) + public static Tdu ResourceLinkComposer(object value, Warehouse warehouse, EpConnection connection) { var b = Encoding.UTF8.GetBytes((ResourceLink)value); - return new TDU(TDUIdentifier.ResourceLink, b, (uint)b.Length); + return new Tdu(TduIdentifier.ResourceLink, b, (uint)b.Length); } - public static TDU EnumComposer(object value, Warehouse warehouse, EpConnection connection) + public static Tdu EnumComposer(object value, Warehouse warehouse, EpConnection connection) { if (value == null) - return new TDU(TDUIdentifier.Null, null, 0); + return new Tdu(TduIdentifier.Null, null, 0); //var warehouse = connection?.Instance?.Warehouse ?? connection?.Server?.Instance?.Warehouse; @@ -413,71 +413,71 @@ public static class DataSerializer var ct = typeDef.Constants.FirstOrDefault(x => x.Value.Equals(intVal)); if (ct == null) - return new TDU(TDUIdentifier.Null, null, 0); + return new Tdu(TduIdentifier.Null, null, 0); //return Codec.ComposeInternal(intVal, warehouse, connection); - return new TDU(TDUIdentifier.TypedEnum, + return new Tdu(TduIdentifier.TypedEnum, new byte[] { ct.Index }, 1, typeDef.Id.Data); } - public static TDU UInt8Composer(object value, Warehouse warehouse, EpConnection connection) + public static Tdu UInt8Composer(object value, Warehouse warehouse, EpConnection connection) { - return new TDU(TDUIdentifier.UInt8, + return new Tdu(TduIdentifier.UInt8, new byte[] { (byte)value }, 1); } - public static TDU Int8Composer(object value, Warehouse warehouse, EpConnection connection) + public static Tdu Int8Composer(object value, Warehouse warehouse, EpConnection connection) { - return new TDU(TDUIdentifier.Int8, + return new Tdu(TduIdentifier.Int8, new byte[] { (byte)(sbyte)value }, 1); } - public static TDU Char8Composer(object value, Warehouse warehouse, EpConnection connection) + public static Tdu Char8Composer(object value, Warehouse warehouse, EpConnection connection) { - return new TDU(TDUIdentifier.Int8, + return new Tdu(TduIdentifier.Int8, new byte[] { (byte)(char)value }, 1); } - public static unsafe TDU Char16Composer(object value, Warehouse warehouse, EpConnection connection) + public static unsafe Tdu Char16Composer(object value, Warehouse warehouse, EpConnection connection) { var v = (char)value; var rt = new byte[2]; fixed (byte* ptr = rt) *((char*)ptr) = v; - return new TDU(TDUIdentifier.Char16, rt, 2); + return new Tdu(TduIdentifier.Char16, rt, 2); } - public static TDU BoolComposer(object value, Warehouse warehouse, EpConnection connection) + public static Tdu BoolComposer(object value, Warehouse warehouse, EpConnection connection) { if ((bool)value) { - return new TDU(TDUIdentifier.True, null, 0); + return new Tdu(TduIdentifier.True, null, 0); } else { - return new TDU(TDUIdentifier.False, null, 0); + return new Tdu(TduIdentifier.False, null, 0); } } - public static TDU NotModifiedComposer(object value, Warehouse warehouse, EpConnection connection) + public static Tdu NotModifiedComposer(object value, Warehouse warehouse, EpConnection connection) { - return new TDU(TDUIdentifier.NotModified, null, 0); + return new Tdu(TduIdentifier.NotModified, null, 0); } - public static TDU RawDataComposerFromArray(object value, Warehouse warehouse, EpConnection connection) + public static Tdu RawDataComposerFromArray(object value, Warehouse warehouse, EpConnection connection) { var b = (byte[])value; - return new TDU(TDUIdentifier.RawData, b, (uint)b.Length); + return new Tdu(TduIdentifier.RawData, b, (uint)b.Length); } - public static TDU RawDataComposerFromList(dynamic value, Warehouse warehouse, EpConnection connection) + public static Tdu RawDataComposerFromList(dynamic value, Warehouse warehouse, EpConnection connection) { var b = value as List; - return new TDU(TDUIdentifier.RawData, b.ToArray(), (uint)b.Count); + return new Tdu(TduIdentifier.RawData, b.ToArray(), (uint)b.Count); } //public static (TDUIdentifier, byte[]) ListComposerFromArray(dynamic value, EpConnection connection) @@ -491,16 +491,16 @@ public static class DataSerializer // return (TDUIdentifier.List, rt.ToArray()); //} - public static TDU ListComposer(object value, Warehouse warehouse, EpConnection connection) + public static Tdu ListComposer(object value, Warehouse warehouse, EpConnection connection) { var composed = DynamicArrayComposer((IEnumerable)value, warehouse, connection); if (composed == null) - return new TDU(TDUIdentifier.Null, new byte[0], 0); + return new Tdu(TduIdentifier.Null, new byte[0], 0); else { - return new TDU(TDUIdentifier.List, composed, (uint)composed.Length); + return new Tdu(TduIdentifier.List, composed, (uint)composed.Length); } //if (value == null) @@ -534,7 +534,7 @@ public static class DataSerializer //return new TDU(TDUIdentifier.List, rt.ToArray(), (uint)rt.Count); } - public static byte[] TypedArrayComposer(IEnumerable value, TRU tru, Warehouse warehouse, EpConnection connection) + public static byte[] TypedArrayComposer(IEnumerable value, Tru tru, Warehouse warehouse, EpConnection connection) { byte[] composed; @@ -542,31 +542,31 @@ public static class DataSerializer return null; - if (tru.Identifier == TRUIdentifier.Int32) + if (tru.Identifier == TruIdentifier.Int32) { composed = GroupInt32Codec.Encode((IList)value); } - else if (tru.Identifier == TRUIdentifier.Int64) + else if (tru.Identifier == TruIdentifier.Int64) { composed = GroupInt64Codec.Encode((IList)value); } - else if (tru.Identifier == TRUIdentifier.Int16) + else if (tru.Identifier == TruIdentifier.Int16) { composed = GroupInt16Codec.Encode((IList)value); } - else if (tru.Identifier == TRUIdentifier.UInt32) + else if (tru.Identifier == TruIdentifier.UInt32) { composed = GroupUInt32Codec.Encode((IList)value); } - else if (tru.Identifier == TRUIdentifier.UInt64) + else if (tru.Identifier == TruIdentifier.UInt64) { composed = GroupUInt64Codec.Encode((IList)value); } - else if (tru.Identifier == TRUIdentifier.UInt16) + else if (tru.Identifier == TruIdentifier.UInt16) { composed = GroupUInt16Codec.Encode((IList)value); } - else if (tru.Identifier == TRUIdentifier.Enum) + else if (tru.Identifier == TruIdentifier.Enum) { var rt = new List(); @@ -587,21 +587,21 @@ public static class DataSerializer { var rt = new List(); - TDU? previous = null; + Tdu? previous = null; var isTyped = tru.IsTyped(); foreach (var i in value) { var tdu = Codec.ComposeInternal(i, warehouse, connection); - var currentTru = TRU.FromType(i?.GetType()); + var currentTru = Tru.FromType(i?.GetType()); if (isTyped && tru.Match(currentTru)) { var d = tdu.Composed.Clip(tdu.ContentOffset, (uint)tdu.Composed.Length - tdu.ContentOffset); - var ntd = new TDU(TDUIdentifier.TypeOfTarget, d, (ulong)d.Length); + var ntd = new Tdu(TduIdentifier.TypeOfTarget, d, (ulong)d.Length); rt.AddRange(ntd.Composed); } else @@ -611,7 +611,7 @@ public static class DataSerializer var d = tdu.Composed.Clip(tdu.ContentOffset, (uint)tdu.Composed.Length - tdu.ContentOffset); - var ntd = new TDU(TDUIdentifier.TypeContinuation, d, (ulong)d.Length); + var ntd = new Tdu(TduIdentifier.TypeContinuation, d, (ulong)d.Length); rt.AddRange(ntd.Composed); } else @@ -630,18 +630,18 @@ public static class DataSerializer } - public static TDU TypedListComposer(IEnumerable value, Type type, Warehouse warehouse, EpConnection connection) + public static Tdu TypedListComposer(IEnumerable value, Type type, Warehouse warehouse, EpConnection connection) { - var tru = TRU.FromType(type); + var tru = Tru.FromType(type); byte[] composed = TypedArrayComposer(value, tru, warehouse, connection); if (composed == null) - return new TDU(TDUIdentifier.Null, new byte[0], 0); + return new Tdu(TduIdentifier.Null, new byte[0], 0); var metadata = tru.Compose(); - return new TDU(TDUIdentifier.TypedList, composed, (uint)composed.Length, metadata); + return new Tdu(TduIdentifier.TypedList, composed, (uint)composed.Length, metadata); } //public static byte[] PropertyValueComposer(PropertyValue propertyValue, EpConnection connection)//, bool includeAge = true) @@ -655,10 +655,10 @@ public static class DataSerializer // .ToArray(); //} - public static TDU PropertyValueArrayComposer(object value, Warehouse warehouse, EpConnection connection) + public static Tdu PropertyValueArrayComposer(object value, Warehouse warehouse, EpConnection connection) { if (value == null) - return new TDU(TDUIdentifier.Null, new byte[0], 0); + return new Tdu(TduIdentifier.Null, new byte[0], 0); var rt = new List(); var ar = value as PropertyValue[]; @@ -670,17 +670,17 @@ public static class DataSerializer rt.AddRange(Codec.Compose(pv.Value, warehouse, connection)); } - return new TDU(TDUIdentifier.RawData, rt.ToArray(), + return new Tdu(TduIdentifier.RawData, rt.ToArray(), (uint)rt.Count); } - public static TDU TypedMapComposer(object value, Type keyType, Type valueType, Warehouse warehouse, EpConnection connection) + public static Tdu TypedMapComposer(object value, Type keyType, Type valueType, Warehouse warehouse, EpConnection connection) { if (value == null) - return new TDU(TDUIdentifier.Null, new byte[0], 0); + return new Tdu(TduIdentifier.Null, new byte[0], 0); - var kt = TRU.FromType(keyType); - var vt = TRU.FromType(valueType); + var kt = Tru.FromType(keyType); + var vt = Tru.FromType(valueType); //var rt = new List(); @@ -700,26 +700,26 @@ public static class DataSerializer //foreach (var el in map.Serialize()) // rt.AddRange(Codec.Compose(el, warehouse, connection)); - var keysTdu = new TDU(TDUIdentifier.TypeOfTarget, compsedKeys, (uint)compsedKeys.Length).Composed; - var valuesTdu = new TDU(TDUIdentifier.TypeOfTarget, compsedValues, (uint)compsedValues.Length).Composed; + var keysTdu = new Tdu(TduIdentifier.TypeOfTarget, compsedKeys, (uint)compsedKeys.Length).Composed; + var valuesTdu = new Tdu(TduIdentifier.TypeOfTarget, compsedValues, (uint)compsedValues.Length).Composed; var all = DC.Combine(keysTdu, 0, (uint)keysTdu.Length, valuesTdu, 0, (uint)valuesTdu.Length); - return new TDU(TDUIdentifier.TypedMap, all, (uint)all.Length, metadata); + return new Tdu(TduIdentifier.TypedMap, all, (uint)all.Length, metadata); //return new TDU(TDUIdentifier.TypedMap, rt.ToArray(), (uint)rt.Count, // ); } - public static TDU TypedDictionaryComposer(object value, Type keyType, Type valueType, Warehouse warehouse, EpConnection connection) + public static Tdu TypedDictionaryComposer(object value, Type keyType, Type valueType, Warehouse warehouse, EpConnection connection) { if (value == null) - return new TDU(TDUIdentifier.Null, new byte[0], 0); + return new Tdu(TduIdentifier.Null, new byte[0], 0); - var kt = TRU.FromType(keyType); - var vt = TRU.FromType(valueType); + var kt = Tru.FromType(keyType); + var vt = Tru.FromType(valueType); //var rt = new List(); @@ -739,12 +739,12 @@ public static class DataSerializer //foreach (var el in map.Serialize()) // rt.AddRange(Codec.Compose(el, warehouse, connection)); - var keysTdu = new TDU(TDUIdentifier.TypeOfTarget, compsedKeys, (uint)compsedKeys.Length).Composed; - var valuesTdu = new TDU(TDUIdentifier.TypeOfTarget, compsedValues, (uint)compsedValues.Length).Composed; + var keysTdu = new Tdu(TduIdentifier.TypeOfTarget, compsedKeys, (uint)compsedKeys.Length).Composed; + var valuesTdu = new Tdu(TduIdentifier.TypeOfTarget, compsedValues, (uint)compsedValues.Length).Composed; var all = DC.Combine(keysTdu, 0, (uint)keysTdu.Length, valuesTdu, 0, (uint)valuesTdu.Length); - return new TDU(TDUIdentifier.TypedMap, all, (uint)all.Length, metadata); + return new Tdu(TduIdentifier.TypedMap, all, (uint)all.Length, metadata); //if (value == null) @@ -782,7 +782,7 @@ public static class DataSerializer var rt = new List(); - TDU? previous = null; + Tdu? previous = null; foreach (var i in value) { @@ -792,7 +792,7 @@ public static class DataSerializer var d = tdu.Composed.Clip(tdu.ContentOffset, (uint)tdu.Composed.Length - tdu.ContentOffset); - var ntd = new TDU(TDUIdentifier.TypeContinuation, d, (ulong)d.Length); + var ntd = new Tdu(TduIdentifier.TypeContinuation, d, (ulong)d.Length); rt.AddRange(ntd.Composed); } else @@ -806,36 +806,36 @@ public static class DataSerializer return rt.ToArray(); } - public static TDU ResourceListComposer(object value, Warehouse warehouse, EpConnection connection) + public static Tdu ResourceListComposer(object value, Warehouse warehouse, EpConnection connection) { if (value == null) - return new TDU(TDUIdentifier.Null, new byte[0], 0); + return new Tdu(TduIdentifier.Null, new byte[0], 0); var composed = DynamicArrayComposer((IEnumerable)value, warehouse, connection); - return new TDU(TDUIdentifier.ResourceList, composed, + return new Tdu(TduIdentifier.ResourceList, composed, (uint)composed.Length); } - public static TDU RecordListComposer(object value, Warehouse warehouse, EpConnection connection) + public static Tdu RecordListComposer(object value, Warehouse warehouse, EpConnection connection) { if (value == null) - return new TDU(TDUIdentifier.Null, new byte[0], 0); + return new Tdu(TduIdentifier.Null, new byte[0], 0); var composed = DynamicArrayComposer((IEnumerable)value, warehouse, connection); - return new TDU(TDUIdentifier.RecordList, + return new Tdu(TduIdentifier.RecordList, composed, (uint)composed.Length); } - public static unsafe TDU ResourceComposer(object value, Warehouse warehouse, EpConnection connection) + public static unsafe Tdu ResourceComposer(object value, Warehouse warehouse, EpConnection connection) { var resource = (IResource)value; if (resource.Instance == null || resource.Instance.IsDestroyed) { - return new TDU(TDUIdentifier.Null, null, 0); + return new Tdu(TduIdentifier.Null, null, 0); } if (Codec.IsLocalResource(resource, connection)) @@ -843,21 +843,21 @@ public static class DataSerializer var rid = (resource as EpResource).DistributedResourceInstanceId; if (rid <= 0xFF) - return new TDU(TDUIdentifier.LocalResource8, new byte[] { (byte)rid }, 1); + return new Tdu(TduIdentifier.LocalResource8, new byte[] { (byte)rid }, 1); else if (rid <= 0xFFFF) { var rt = new byte[2]; fixed (byte* ptr = rt) *((ushort*)ptr) = (ushort)rid; - return new TDU(TDUIdentifier.LocalResource16, rt, 2); + return new Tdu(TduIdentifier.LocalResource16, rt, 2); } else { var rt = new byte[4]; fixed (byte* ptr = rt) *((uint*)ptr) = rid; - return new TDU(TDUIdentifier.LocalResource32, rt, 4); + return new Tdu(TduIdentifier.LocalResource32, rt, 4); } } else @@ -868,29 +868,29 @@ public static class DataSerializer var rid = resource.Instance.Id; if (rid <= 0xFF) - return new TDU(TDUIdentifier.RemoteResource8, new byte[] { (byte)rid }, 1); + return new Tdu(TduIdentifier.RemoteResource8, new byte[] { (byte)rid }, 1); else if (rid <= 0xFFFF) { var rt = new byte[2]; fixed (byte* ptr = rt) *((ushort*)ptr) = (ushort)rid; - return new TDU(TDUIdentifier.RemoteResource16, rt, 2); + return new Tdu(TduIdentifier.RemoteResource16, rt, 2); } else { var rt = new byte[4]; fixed (byte* ptr = rt) *((uint*)ptr) = rid; - return new TDU(TDUIdentifier.RemoteResource32, rt, 4); + return new Tdu(TduIdentifier.RemoteResource32, rt, 4); } } } - public static unsafe TDU MapComposer(object value, Warehouse warehouse, EpConnection connection) + public static unsafe Tdu MapComposer(object value, Warehouse warehouse, EpConnection connection) { if (value == null) - return new TDU(TDUIdentifier.Null, new byte[0], 1); + return new Tdu(TduIdentifier.Null, new byte[0], 1); var rt = new List(); var map = (IMap)value; @@ -898,16 +898,16 @@ public static class DataSerializer foreach (var el in map.Serialize()) rt.AddRange(Codec.Compose(el, warehouse, connection)); - return new TDU(TDUIdentifier.Map, rt.ToArray(), (uint)rt.Count); + return new Tdu(TduIdentifier.Map, rt.ToArray(), (uint)rt.Count); } - public static unsafe TDU UUIDComposer(object value, Warehouse warehouse, EpConnection connection) + public static unsafe Tdu UUIDComposer(object value, Warehouse warehouse, EpConnection connection) { - return new TDU(TDUIdentifier.UUID, ((UUID)value).Data, 16); + return new Tdu(TduIdentifier.UUID, ((Uuid)value).Data, 16); } - public static unsafe TDU RecordComposer(object value, Warehouse warehouse, EpConnection connection) + public static unsafe Tdu RecordComposer(object value, Warehouse warehouse, EpConnection connection) { var rt = new List(); var record = (IRecord)value; @@ -921,7 +921,7 @@ public static class DataSerializer //if (propValue == null) // return TDU(TDUIdentifier.Null, null, 0); - var tru = TRU.FromType(propValue?.GetType()); + var tru = Tru.FromType(propValue?.GetType()); var tdu = Codec.ComposeInternal(propValue, warehouse, connection); @@ -930,14 +930,14 @@ public static class DataSerializer { // strip metadata var len = (uint)tdu.Composed.Length - tdu.ContentOffset; - tdu = new TDU(TDUIdentifier.TypeOfTarget, + tdu = new Tdu(TduIdentifier.TypeOfTarget, tdu.Composed.Clip(tdu.ContentOffset, len), len); } rt.AddRange(tdu.Composed); } - return new TDU(TDUIdentifier.Record, rt.ToArray(), + return new Tdu(TduIdentifier.Record, rt.ToArray(), (uint)rt.Count, typeDef.Id.Data); } @@ -958,14 +958,14 @@ public static class DataSerializer return rt.ToArray(); } - public static TDU TupleComposer(object value, Warehouse warehouse, EpConnection connection) + public static Tdu TupleComposer(object value, Warehouse warehouse, EpConnection connection) { if (value == null) - return new TDU(TDUIdentifier.Null, new byte[0], 0); + return new Tdu(TduIdentifier.Null, new byte[0], 0); var fields = value.GetType().GetFields(); var list = fields.Select(x => x.GetValue(value)).ToArray(); - var trus = fields.Select(x => TRU.FromType(x.FieldType)).ToArray(); + var trus = fields.Select(x => Tru.FromType(x.FieldType)).ToArray(); var metadata = new List(); @@ -982,21 +982,21 @@ public static class DataSerializer var tdu = Codec.ComposeInternal(tupleValue, warehouse, connection); - var valueTru = TRU.FromType(tupleValue?.GetType()); + var valueTru = Tru.FromType(tupleValue?.GetType()); if (targetTru.IsTyped() && targetTru.Match(valueTru)) { // strip metadata var len = (uint)tdu.Composed.Length - tdu.ContentOffset; - tdu = new TDU(TDUIdentifier.TypeOfTarget, + tdu = new Tdu(TduIdentifier.TypeOfTarget, tdu.Composed.Clip(tdu.ContentOffset, len), len); } rt.AddRange(tdu.Composed); } - return new TDU(TDUIdentifier.TypedTuple, rt.ToArray(), + return new Tdu(TduIdentifier.TypedTuple, rt.ToArray(), (uint)rt.Count, metadata.ToArray()); } diff --git a/Esiur/Data/ParsedTDU.cs b/Esiur/Data/ParsedTDU.cs index 2eec2f9..8c1c1e7 100644 --- a/Esiur/Data/ParsedTDU.cs +++ b/Esiur/Data/ParsedTDU.cs @@ -4,11 +4,11 @@ using System.Text; namespace Esiur.Data { - public struct ParsedTDU + public struct ParsedTdu { - public TDUIdentifier Identifier; + public TduIdentifier Identifier; public int Index; - public TDUClass Class; + public TduClass Class; public uint Offset; public ulong ContentLength; public byte[] Data; @@ -17,21 +17,21 @@ namespace Esiur.Data public byte[] Metadata; public uint Ends; - public static ParsedTDU Parse(byte[] data, uint offset, uint ends) + public static ParsedTdu Parse(byte[] data, uint offset, uint ends) { var h = data[offset++]; - var cls = (TDUClass)(h >> 6); + var cls = (TduClass)(h >> 6); - if (cls == TDUClass.Fixed) + if (cls == TduClass.Fixed) { var exp = (h & 0x38) >> 3; if (exp == 0) - return new ParsedTDU() + return new ParsedTdu() { - Identifier = (TDUIdentifier)h, + Identifier = (TduIdentifier)h, Data = data, Offset = offset, Class = cls, @@ -45,17 +45,17 @@ namespace Esiur.Data ulong cl = (ulong)(1 << (exp - 1)); if (ends - offset < cl) - return new ParsedTDU() + return new ParsedTdu() { - Class = TDUClass.Invalid, + Class = TduClass.Invalid, TotalLength = (cl - (ends - offset)) }; //offset += (uint)cl; - return new ParsedTDU() + return new ParsedTdu() { - Identifier = (TDUIdentifier)h, + Identifier = (TduIdentifier)h, Data = data, Offset = offset, Class = cls, @@ -66,14 +66,14 @@ namespace Esiur.Data Ends = ends }; } - else if (cls == TDUClass.Typed) + else if (cls == TduClass.Typed) { ulong cll = (ulong)(h >> 3) & 0x7; if (ends - offset < cll) - return new ParsedTDU() + return new ParsedTdu() { - Class = TDUClass.Invalid, + Class = TduClass.Invalid, TotalLength = (cll - (ends - offset)) }; @@ -83,19 +83,19 @@ namespace Esiur.Data cl = cl << 8 | data[offset++]; if (ends - offset < cl) - return new ParsedTDU() + return new ParsedTdu() { TotalLength = (cl - (ends - offset)), - Class = TDUClass.Invalid, + Class = TduClass.Invalid, }; var metaData = DC.Clip(data, offset + 1, data[offset]); offset += data[offset] + (uint)1; - return new ParsedTDU() + return new ParsedTdu() { - Identifier = (TDUIdentifier)(h & 0xC7), + Identifier = (TduIdentifier)(h & 0xC7), Data = data, Offset = offset, Class = cls, @@ -111,9 +111,9 @@ namespace Esiur.Data ulong cll = (ulong)(h >> 3) & 0x7; if (ends - offset < cll) - return new ParsedTDU() + return new ParsedTdu() { - Class = TDUClass.Invalid, + Class = TduClass.Invalid, TotalLength = (cll - (ends - offset)) }; @@ -123,17 +123,17 @@ namespace Esiur.Data cl = cl << 8 | data[offset++]; if (ends - offset < cl) - return new ParsedTDU() + return new ParsedTdu() { - Class = TDUClass.Invalid, + Class = TduClass.Invalid, TotalLength = (cl - (ends - offset)) }; return - new ParsedTDU() + new ParsedTdu() { - Identifier = (TDUIdentifier)(h & 0xC7), + Identifier = (TduIdentifier)(h & 0xC7), Data = data, Offset = offset, Class = cls, diff --git a/Esiur/Data/TDU.cs b/Esiur/Data/TDU.cs index abc0e3a..1ffffe6 100644 --- a/Esiur/Data/TDU.cs +++ b/Esiur/Data/TDU.cs @@ -8,11 +8,11 @@ using static Esiur.Data.Codec; namespace Esiur.Data; // Transmission Data Unit -public struct TDU +public struct Tdu { - public TDUIdentifier Identifier; + public TduIdentifier Identifier; //public int Index; - public TDUClass Class; + public TduClass Class; //public ulong ContentLength; public byte[] Composed; @@ -52,35 +52,35 @@ public struct TDU //private ulong TotalSize; - public TDU() + public Tdu() { } - public TDU(TDUIdentifier identifier) + public Tdu(TduIdentifier identifier) { Identifier = identifier; Composed = new byte[0]; } - public TDU(TDUIdentifier identifier, + public Tdu(TduIdentifier identifier, byte[] data, ulong length, byte[] metadata = null) { Identifier = identifier; //Index = (byte)identifier & 0x7; - Class = (TDUClass)((byte)identifier >> 6); + Class = (TduClass)((byte)identifier >> 6); Metadata = metadata; - if (Class == TDUClass.Fixed) + if (Class == TduClass.Fixed) { if (length == 0) Composed = new byte[1] { (byte)identifier }; else Composed = DC.Combine(new byte[] { (byte)Identifier }, 0, 1, data, 0, (uint)length); } - else if (Class == TDUClass.Dynamic - || Class == TDUClass.Extension) + else if (Class == TduClass.Dynamic + || Class == TduClass.Extension) { if (length == 0) @@ -169,7 +169,7 @@ public struct TDU Buffer.BlockCopy(data, 0, Composed, 8, (int)length); } } - else if (Class == TDUClass.Typed) + else if (Class == TduClass.Typed) { if (metadata == null) throw new Exception("Metadata must be provided for types."); @@ -297,12 +297,12 @@ public struct TDU } - public bool MatchType(TDU with) + public bool MatchType(Tdu with) { if (Identifier != with.Identifier) return false; - if (Class != TDUClass.Typed || with.Class != TDUClass.Typed) + if (Class != TduClass.Typed || with.Class != TduClass.Typed) return false; if (!Metadata.SequenceEqual(with.Metadata)) diff --git a/Esiur/Data/TDUClass.cs b/Esiur/Data/TDUClass.cs index 2922031..51a5b29 100644 --- a/Esiur/Data/TDUClass.cs +++ b/Esiur/Data/TDUClass.cs @@ -4,7 +4,7 @@ using System.Text; namespace Esiur.Data { - public enum TDUClass + public enum TduClass { Fixed = 0x0, Dynamic = 0x1, diff --git a/Esiur/Data/TDUIdentifier.cs b/Esiur/Data/TDUIdentifier.cs index 4ea38d9..e202823 100644 --- a/Esiur/Data/TDUIdentifier.cs +++ b/Esiur/Data/TDUIdentifier.cs @@ -4,7 +4,7 @@ using System.Text; namespace Esiur.Data { - public enum TDUIdentifier + public enum TduIdentifier { Null = 0x0, False = 0x1, diff --git a/Esiur/Data/TRU.cs b/Esiur/Data/TRU.cs index c932193..bef089c 100644 --- a/Esiur/Data/TRU.cs +++ b/Esiur/Data/TRU.cs @@ -14,54 +14,54 @@ using System.Text; namespace Esiur.Data { - public class TRU + public class Tru { - static TRUIdentifier[] refTypes = new TRUIdentifier[] + static TruIdentifier[] refTypes = new TruIdentifier[] { - TRUIdentifier.Dynamic, - TRUIdentifier.RawData, - TRUIdentifier.String, - TRUIdentifier.Resource, - TRUIdentifier.Record, - TRUIdentifier.Map, - TRUIdentifier.List, - TRUIdentifier.TypedList, - TRUIdentifier.TypedMap, - TRUIdentifier.Tuple2, - TRUIdentifier.Tuple3, - TRUIdentifier.Tuple4, - TRUIdentifier.Tuple5, - TRUIdentifier.Tuple6, - TRUIdentifier.Tuple7, - TRUIdentifier.TypedRecord, - TRUIdentifier.TypedResource + TruIdentifier.Dynamic, + TruIdentifier.RawData, + TruIdentifier.String, + TruIdentifier.Resource, + TruIdentifier.Record, + TruIdentifier.Map, + TruIdentifier.List, + TruIdentifier.TypedList, + TruIdentifier.TypedMap, + TruIdentifier.Tuple2, + TruIdentifier.Tuple3, + TruIdentifier.Tuple4, + TruIdentifier.Tuple5, + TruIdentifier.Tuple6, + TruIdentifier.Tuple7, + TruIdentifier.TypedRecord, + TruIdentifier.TypedResource }; - static Map typesMap = new Map() + static Map typesMap = new Map() { - [TDUIdentifier.UInt8] = TRUIdentifier.UInt8, - [TDUIdentifier.Int8] = TRUIdentifier.Int8, - [TDUIdentifier.UInt16] = TRUIdentifier.UInt16, - [TDUIdentifier.Int16] = TRUIdentifier.Int16, - [TDUIdentifier.UInt32] = TRUIdentifier.UInt32, - [TDUIdentifier.Int32] = TRUIdentifier.Int32, - [TDUIdentifier.UInt64] = TRUIdentifier.UInt64, - [TDUIdentifier.Int64] = TRUIdentifier.Int64, - [TDUIdentifier.UInt128] = TRUIdentifier.UInt128, - [TDUIdentifier.Int128] = TRUIdentifier.Int128, - [TDUIdentifier.Char8] = TRUIdentifier.Char, - [TDUIdentifier.DateTime] = TRUIdentifier.DateTime, - [TDUIdentifier.Float32] = TRUIdentifier.Float32, - [TDUIdentifier.Float64] = TRUIdentifier.Float64, - [TDUIdentifier.Decimal128] = TRUIdentifier.Decimal, - [TDUIdentifier.False] = TRUIdentifier.Bool, - [TDUIdentifier.True] = TRUIdentifier.Bool, - [TDUIdentifier.Map] = TRUIdentifier.Map, - [TDUIdentifier.List] = TRUIdentifier.List, - [TDUIdentifier.RawData] = TRUIdentifier.RawData, - [TDUIdentifier.Record] = TRUIdentifier.Record, - [TDUIdentifier.String] = TRUIdentifier.String, + [TduIdentifier.UInt8] = TruIdentifier.UInt8, + [TduIdentifier.Int8] = TruIdentifier.Int8, + [TduIdentifier.UInt16] = TruIdentifier.UInt16, + [TduIdentifier.Int16] = TruIdentifier.Int16, + [TduIdentifier.UInt32] = TruIdentifier.UInt32, + [TduIdentifier.Int32] = TruIdentifier.Int32, + [TduIdentifier.UInt64] = TruIdentifier.UInt64, + [TduIdentifier.Int64] = TruIdentifier.Int64, + [TduIdentifier.UInt128] = TruIdentifier.UInt128, + [TduIdentifier.Int128] = TruIdentifier.Int128, + [TduIdentifier.Char8] = TruIdentifier.Char, + [TduIdentifier.DateTime] = TruIdentifier.DateTime, + [TduIdentifier.Float32] = TruIdentifier.Float32, + [TduIdentifier.Float64] = TruIdentifier.Float64, + [TduIdentifier.Decimal128] = TruIdentifier.Decimal, + [TduIdentifier.False] = TruIdentifier.Bool, + [TduIdentifier.True] = TruIdentifier.Bool, + [TduIdentifier.Map] = TruIdentifier.Map, + [TduIdentifier.List] = TruIdentifier.List, + [TduIdentifier.RawData] = TruIdentifier.RawData, + [TduIdentifier.Record] = TruIdentifier.Record, + [TduIdentifier.String] = TruIdentifier.String, }; @@ -129,7 +129,7 @@ namespace Esiur.Data public Type? GetRuntimeType(Warehouse warehouse) { - if (Identifier == TRUIdentifier.TypedList) + if (Identifier == TruIdentifier.TypedList) { var sub = SubTypes?[0].GetRuntimeType(warehouse); if (sub == null) @@ -139,7 +139,7 @@ namespace Esiur.Data return rt; } - else if (Identifier == TRUIdentifier.TypedMap) + else if (Identifier == TruIdentifier.TypedMap) { var subs = SubTypes.Select(x => x.GetRuntimeType(warehouse)).ToArray(); var rt = typeof(Map<,>).MakeGenericType(subs); @@ -148,59 +148,59 @@ namespace Esiur.Data return Identifier switch { - (TRUIdentifier.Void) => typeof(void), - (TRUIdentifier.Dynamic) => typeof(object), - (TRUIdentifier.Bool) => Nullable ? typeof(bool?) : typeof(bool), - (TRUIdentifier.Char) => Nullable ? typeof(char?) : typeof(char), - (TRUIdentifier.UInt8) => Nullable ? typeof(byte?) : typeof(byte), - (TRUIdentifier.Int8) => Nullable ? typeof(sbyte?) : typeof(sbyte), - (TRUIdentifier.Int16) => Nullable ? typeof(short?) : typeof(short), - (TRUIdentifier.UInt16) => Nullable ? typeof(ushort?) : typeof(ushort), - (TRUIdentifier.Int32) => Nullable ? typeof(int?) : typeof(int), - (TRUIdentifier.UInt32) => Nullable ? typeof(uint?) : typeof(uint), - (TRUIdentifier.Int64) => Nullable ? typeof(ulong?) : typeof(long), - (TRUIdentifier.UInt64) => Nullable ? typeof(ulong?) : typeof(ulong), - (TRUIdentifier.Float32) => Nullable ? typeof(float?) : typeof(float), - (TRUIdentifier.Float64) => Nullable ? typeof(double?) : typeof(double), - (TRUIdentifier.Decimal) => Nullable ? typeof(decimal?) : typeof(decimal), - (TRUIdentifier.String) => typeof(string), - (TRUIdentifier.DateTime) => Nullable ? typeof(DateTime?) : typeof(DateTime), - (TRUIdentifier.Resource) => typeof(IResource), - (TRUIdentifier.Record) => typeof(IRecord), - (TRUIdentifier.TypedRecord) => warehouse.GetTypeDefById((UUID)UUID!, TypeDefKind.Record)?.DefinedType, - (TRUIdentifier.TypedResource) => warehouse.GetTypeDefById((UUID)UUID!, TypeDefKind.Resource)?.DefinedType, - (TRUIdentifier.Enum) => warehouse.GetTypeDefById((UUID)UUID!, TypeDefKind.Enum)?.DefinedType, + (TruIdentifier.Void) => typeof(void), + (TruIdentifier.Dynamic) => typeof(object), + (TruIdentifier.Bool) => Nullable ? typeof(bool?) : typeof(bool), + (TruIdentifier.Char) => Nullable ? typeof(char?) : typeof(char), + (TruIdentifier.UInt8) => Nullable ? typeof(byte?) : typeof(byte), + (TruIdentifier.Int8) => Nullable ? typeof(sbyte?) : typeof(sbyte), + (TruIdentifier.Int16) => Nullable ? typeof(short?) : typeof(short), + (TruIdentifier.UInt16) => Nullable ? typeof(ushort?) : typeof(ushort), + (TruIdentifier.Int32) => Nullable ? typeof(int?) : typeof(int), + (TruIdentifier.UInt32) => Nullable ? typeof(uint?) : typeof(uint), + (TruIdentifier.Int64) => Nullable ? typeof(ulong?) : typeof(long), + (TruIdentifier.UInt64) => Nullable ? typeof(ulong?) : typeof(ulong), + (TruIdentifier.Float32) => Nullable ? typeof(float?) : typeof(float), + (TruIdentifier.Float64) => Nullable ? typeof(double?) : typeof(double), + (TruIdentifier.Decimal) => Nullable ? typeof(decimal?) : typeof(decimal), + (TruIdentifier.String) => typeof(string), + (TruIdentifier.DateTime) => Nullable ? typeof(DateTime?) : typeof(DateTime), + (TruIdentifier.Resource) => typeof(IResource), + (TruIdentifier.Record) => typeof(IRecord), + (TruIdentifier.TypedRecord) => warehouse.GetTypeDefById((Uuid)UUID!, TypeDefKind.Record)?.DefinedType, + (TruIdentifier.TypedResource) => warehouse.GetTypeDefById((Uuid)UUID!, TypeDefKind.Resource)?.DefinedType, + (TruIdentifier.Enum) => warehouse.GetTypeDefById((Uuid)UUID!, TypeDefKind.Enum)?.DefinedType, _ => null }; } - public TRUIdentifier Identifier; + public TruIdentifier Identifier; public bool Nullable; - public UUID? UUID; + public Uuid? UUID; //public RepresentationType? SubType1; // List + Map //public RepresentationType? SubType2; // Map //public RepresentationType? SubType3; // No types yet - public TRU[]? SubTypes = null; + public Tru[]? SubTypes = null; - public TRU ToNullable() + public Tru ToNullable() { - return new TRU(Identifier, true, UUID, SubTypes); + return new Tru(Identifier, true, UUID, SubTypes); } public bool IsTyped() { - if (Identifier == TRUIdentifier.TypedList && SubTypes[0].Identifier == TRUIdentifier.UInt8) + if (Identifier == TruIdentifier.TypedList && SubTypes[0].Identifier == TruIdentifier.UInt8) return false; - if (Identifier == TRUIdentifier.TypedResource) + if (Identifier == TruIdentifier.TypedResource) return false; return (UUID != null) || (SubTypes != null && SubTypes.Length > 0); } - public bool Match(TRU other) + public bool Match(Tru other) { //if (UUID == null && (SubTypes == null || SubTypes.Length == 0)) // return false; @@ -224,19 +224,19 @@ namespace Esiur.Data } - public (TDUIdentifier, byte[]) GetMetadata() + public (TduIdentifier, byte[]) GetMetadata() { switch (Identifier) { - case TRUIdentifier.TypedList: - return (TDUIdentifier.TypedList, SubTypes[0].Compose()); - case TRUIdentifier.TypedRecord: - return (TDUIdentifier.Record, UUID?.Data); - case TRUIdentifier.TypedMap: - return (TDUIdentifier.TypedMap, + case TruIdentifier.TypedList: + return (TduIdentifier.TypedList, SubTypes[0].Compose()); + case TruIdentifier.TypedRecord: + return (TduIdentifier.Record, UUID?.Data); + case TruIdentifier.TypedMap: + return (TduIdentifier.TypedMap, SubTypes[0].Compose().Concat(SubTypes[1].Compose()).ToArray()); - case TRUIdentifier.Enum: - return (TDUIdentifier.TypedEnum, UUID?.Data); + case TruIdentifier.Enum: + return (TduIdentifier.TypedEnum, UUID?.Data); default: @@ -267,12 +267,12 @@ namespace Esiur.Data // case TRUIdentifier. } //} - private static Dictionary _cache = new Dictionary(); + private static Dictionary _cache = new Dictionary(); - public static TRU? FromType(Type type) + public static Tru? FromType(Type type) { if (type == null) - return new TRU(TRUIdentifier.Void, true); + return new Tru(TruIdentifier.Void, true); if (_cache.ContainsKey(type)) return _cache[type]; @@ -287,33 +287,33 @@ namespace Esiur.Data nullable = true; } - TRU? tru = null; + Tru? tru = null; if (type == typeof(IResource)) { - return new TRU(TRUIdentifier.Resource, nullable); + return new Tru(TruIdentifier.Resource, nullable); } else if (type == typeof(IRecord) || type == typeof(Record)) { - return new TRU(TRUIdentifier.Record, nullable); + return new Tru(TruIdentifier.Record, nullable); } else if (type == typeof(Map) || type == typeof(Dictionary)) { - return new TRU(TRUIdentifier.Map, nullable); + return new Tru(TruIdentifier.Map, nullable); } else if (Codec.ImplementsInterface(type, typeof(IResource))) { - tru = new TRU( - TRUIdentifier.TypedResource, + tru = new Tru( + TruIdentifier.TypedResource, nullable, TypeDef.GetTypeUUID(type) ); } else if (Codec.ImplementsInterface(type, typeof(IRecord))) { - tru = new TRU( - TRUIdentifier.TypedRecord, + tru = new Tru( + TruIdentifier.TypedRecord, nullable, TypeDef.GetTypeUUID(type) ); @@ -329,7 +329,7 @@ namespace Esiur.Data var args = type.GetGenericArguments(); if (args[0] == typeof(object)) { - tru = new TRU(TRUIdentifier.List, nullable); + tru = new Tru(TruIdentifier.List, nullable); } else { @@ -338,8 +338,8 @@ namespace Esiur.Data return null; - tru = new TRU(TRUIdentifier.TypedList, nullable, null, - new TRU[] { subType }); + tru = new Tru(TruIdentifier.TypedList, nullable, null, + new Tru[] { subType }); } } @@ -349,7 +349,7 @@ namespace Esiur.Data var args = type.GetGenericArguments(); if (args[0] == typeof(object) && args[1] == typeof(object)) { - tru = new TRU(TRUIdentifier.Map, nullable); + tru = new Tru(TruIdentifier.Map, nullable); } else { @@ -361,8 +361,8 @@ namespace Esiur.Data if (subType2 == null) return null; - tru = new TRU(TRUIdentifier.TypedMap, nullable, null, - new TRU[] { subType1, subType2 }); + tru = new Tru(TruIdentifier.TypedMap, nullable, null, + new Tru[] { subType1, subType2 }); } } @@ -375,7 +375,7 @@ namespace Esiur.Data else if (genericType == typeof(ValueTuple<,>)) { var args = type.GetGenericArguments(); - var subTypes = new TRU[args.Length]; + var subTypes = new Tru[args.Length]; for (var i = 0; i < args.Length; i++) { var t = FromType(args[i]); @@ -385,13 +385,13 @@ namespace Esiur.Data } - tru = new TRU(TRUIdentifier.Tuple2, nullable, null, subTypes); + tru = new Tru(TruIdentifier.Tuple2, nullable, null, subTypes); } else if (genericType == typeof(ValueTuple<,,>)) { var args = type.GetGenericArguments(); - var subTypes = new TRU[args.Length]; + var subTypes = new Tru[args.Length]; for (var i = 0; i < args.Length; i++) { var t = FromType(args[i]); @@ -400,14 +400,14 @@ namespace Esiur.Data subTypes[i] = t; } - tru = new TRU(TRUIdentifier.Tuple3, nullable, null, subTypes); + tru = new Tru(TruIdentifier.Tuple3, nullable, null, subTypes); } else if (genericType == typeof(ValueTuple<,,,>)) { var args = type.GetGenericArguments(); - var subTypes = new TRU[args.Length]; + var subTypes = new Tru[args.Length]; for (var i = 0; i < args.Length; i++) { var t = FromType(args[i]); @@ -416,12 +416,12 @@ namespace Esiur.Data subTypes[i] = t; } - tru = new TRU(TRUIdentifier.Tuple4, nullable, null, subTypes); + tru = new Tru(TruIdentifier.Tuple4, nullable, null, subTypes); } else if (genericType == typeof(ValueTuple<,,,,>)) { var args = type.GetGenericArguments(); - var subTypes = new TRU[args.Length]; + var subTypes = new Tru[args.Length]; for (var i = 0; i < args.Length; i++) { var t = FromType(args[i]); @@ -430,12 +430,12 @@ namespace Esiur.Data subTypes[i] = t; } - tru = new TRU(TRUIdentifier.Tuple5, nullable, null, subTypes); + tru = new Tru(TruIdentifier.Tuple5, nullable, null, subTypes); } else if (genericType == typeof(ValueTuple<,,,,,>)) { var args = type.GetGenericArguments(); - var subTypes = new TRU[args.Length]; + var subTypes = new Tru[args.Length]; for (var i = 0; i < args.Length; i++) { var t = FromType(args[i]); @@ -444,12 +444,12 @@ namespace Esiur.Data subTypes[i] = t; } - tru = new TRU(TRUIdentifier.Tuple6, nullable, null, subTypes); + tru = new Tru(TruIdentifier.Tuple6, nullable, null, subTypes); } else if (genericType == typeof(ValueTuple<,,,,,,>)) { var args = type.GetGenericArguments(); - var subTypes = new TRU[args.Length]; + var subTypes = new Tru[args.Length]; for (var i = 0; i < args.Length; i++) { var t = FromType(args[i]); @@ -458,7 +458,7 @@ namespace Esiur.Data subTypes[i] = t; } - tru = new TRU(TRUIdentifier.Tuple7, nullable, null, subTypes); + tru = new Tru(TruIdentifier.Tuple7, nullable, null, subTypes); } else return null; @@ -467,7 +467,7 @@ namespace Esiur.Data { var elementType = type.GetElementType(); if (elementType == typeof(object)) - tru = new TRU(TRUIdentifier.List, nullable); + tru = new Tru(TruIdentifier.List, nullable); else { var subType = FromType(elementType); @@ -475,14 +475,14 @@ namespace Esiur.Data if (subType == null) return null; - tru = new TRU(TRUIdentifier.TypedList, nullable, null, - new TRU[] { subType }); + tru = new Tru(TruIdentifier.TypedList, nullable, null, + new Tru[] { subType }); } } else if (type.IsEnum) { - tru = new TRU(TRUIdentifier.Enum, nullable, TypeDef.GetTypeUUID(type)); + tru = new Tru(TruIdentifier.Enum, nullable, TypeDef.GetTypeUUID(type)); } else if (type.IsInterface) { @@ -503,30 +503,30 @@ namespace Esiur.Data // last check return type switch { - _ when type == typeof(void) => new TRU(TRUIdentifier.Void, nullable), - _ when type == typeof(object) => new TRU(TRUIdentifier.Dynamic, nullable), - _ when type == typeof(bool) => new TRU(TRUIdentifier.Bool, nullable), - _ when type == typeof(char) => new TRU(TRUIdentifier.Char, nullable), - _ when type == typeof(byte) => new TRU(TRUIdentifier.UInt8, nullable), - _ when type == typeof(sbyte) => new TRU(TRUIdentifier.Int8, nullable), - _ when type == typeof(short) => new TRU(TRUIdentifier.Int16, nullable), - _ when type == typeof(ushort) => new TRU(TRUIdentifier.UInt16, nullable), - _ when type == typeof(int) => new TRU(TRUIdentifier.Int32, nullable), - _ when type == typeof(uint) => new TRU(TRUIdentifier.UInt32, nullable), - _ when type == typeof(long) => new TRU(TRUIdentifier.Int64, nullable), - _ when type == typeof(ulong) => new TRU(TRUIdentifier.UInt64, nullable), - _ when type == typeof(float) => new TRU(TRUIdentifier.Float32, nullable), - _ when type == typeof(double) => new TRU(TRUIdentifier.Float64, nullable), - _ when type == typeof(decimal) => new TRU(TRUIdentifier.Decimal, nullable), - _ when type == typeof(string) => new TRU(TRUIdentifier.String, nullable), - _ when type == typeof(DateTime) => new TRU(TRUIdentifier.DateTime, nullable), - _ when type == typeof(ResourceLink) => new TRU(TRUIdentifier.Resource, nullable), + _ when type == typeof(void) => new Tru(TruIdentifier.Void, nullable), + _ when type == typeof(object) => new Tru(TruIdentifier.Dynamic, nullable), + _ when type == typeof(bool) => new Tru(TruIdentifier.Bool, nullable), + _ when type == typeof(char) => new Tru(TruIdentifier.Char, nullable), + _ when type == typeof(byte) => new Tru(TruIdentifier.UInt8, nullable), + _ when type == typeof(sbyte) => new Tru(TruIdentifier.Int8, nullable), + _ when type == typeof(short) => new Tru(TruIdentifier.Int16, nullable), + _ when type == typeof(ushort) => new Tru(TruIdentifier.UInt16, nullable), + _ when type == typeof(int) => new Tru(TruIdentifier.Int32, nullable), + _ when type == typeof(uint) => new Tru(TruIdentifier.UInt32, nullable), + _ when type == typeof(long) => new Tru(TruIdentifier.Int64, nullable), + _ when type == typeof(ulong) => new Tru(TruIdentifier.UInt64, nullable), + _ when type == typeof(float) => new Tru(TruIdentifier.Float32, nullable), + _ when type == typeof(double) => new Tru(TruIdentifier.Float64, nullable), + _ when type == typeof(decimal) => new Tru(TruIdentifier.Decimal, nullable), + _ when type == typeof(string) => new Tru(TruIdentifier.String, nullable), + _ when type == typeof(DateTime) => new Tru(TruIdentifier.DateTime, nullable), + _ when type == typeof(ResourceLink) => new Tru(TruIdentifier.Resource, nullable), _ => null }; } - public TRU(TRUIdentifier identifier, bool nullable, UUID? uuid = null, TRU[]? subTypes = null) + public Tru(TruIdentifier identifier, bool nullable, Uuid? uuid = null, Tru[]? subTypes = null) { Nullable = nullable; Identifier = identifier; @@ -553,13 +553,13 @@ namespace Esiur.Data return rt.ToArray(); } - public static (uint, TRU) Parse(byte[] data, uint offset) + public static (uint, Tru) Parse(byte[] data, uint offset) { var oOffset = offset; var header = data[offset++]; bool nullable = (header & 0x80) > 0; - var identifier = (TRUIdentifier)(header & 0x7F); + var identifier = (TruIdentifier)(header & 0x7F); if ((header & 0x40) > 0) @@ -568,7 +568,7 @@ namespace Esiur.Data var hasUUID = (header & 0x4) > 0; var subsCount = (header >> 3) & 0x7; - UUID? uuid = null; + Uuid? uuid = null; if (hasUUID) { @@ -576,19 +576,19 @@ namespace Esiur.Data offset += 16; } - var subs = new TRU[subsCount]; + var subs = new Tru[subsCount]; for (var i = 0; i < subsCount; i++) { - (var len, subs[i]) = TRU.Parse(data, offset); + (var len, subs[i]) = Tru.Parse(data, offset); offset += len; } - return (offset - oOffset, new TRU(identifier, nullable, uuid, subs)); + return (offset - oOffset, new Tru(identifier, nullable, uuid, subs)); } else { - return (1, new TRU(identifier, nullable)); + return (1, new Tru(identifier, nullable)); } } diff --git a/Esiur/Data/TRUIdentifier.cs b/Esiur/Data/TRUIdentifier.cs index 588629f..874c560 100644 --- a/Esiur/Data/TRUIdentifier.cs +++ b/Esiur/Data/TRUIdentifier.cs @@ -4,7 +4,7 @@ using System.Text; namespace Esiur.Data { - public enum TRUIdentifier + public enum TruIdentifier { Void = 0x0, Dynamic = 0x1, diff --git a/Esiur/Data/Types/ArgumentDef.cs b/Esiur/Data/Types/ArgumentDef.cs index 8b4d21f..d34021d 100644 --- a/Esiur/Data/Types/ArgumentDef.cs +++ b/Esiur/Data/Types/ArgumentDef.cs @@ -12,7 +12,7 @@ public class ArgumentDef public bool Optional { get; set; } - public TRU Type { get; set; } + public Tru Type { get; set; } public ParameterInfo ParameterInfo { get; set; } @@ -28,7 +28,7 @@ public class ArgumentDef var cs = (uint)data[offset++]; var name = data.GetString(offset, cs); offset += cs; - var (size, type) = TRU.Parse(data, offset); + var (size, type) = Tru.Parse(data, offset); offset += size; diff --git a/Esiur/Data/Types/ConstantDef.cs b/Esiur/Data/Types/ConstantDef.cs index 44f05ef..4bf7be7 100644 --- a/Esiur/Data/Types/ConstantDef.cs +++ b/Esiur/Data/Types/ConstantDef.cs @@ -13,7 +13,7 @@ public class ConstantDef : MemberDef public object Value { get; set; } public Map Annotations { get; set; } - public TRU ValueType { get; set; } + public Tru ValueType { get; set; } public FieldInfo FieldInfo { get; set; } @@ -27,7 +27,7 @@ public class ConstantDef : MemberDef var name = data.GetString(offset + 1, data[offset]); offset += (uint)data[offset] + 1; - var (dts, valueType) = TRU.Parse(data, offset); + var (dts, valueType) = Tru.Parse(data, offset); offset += dts; @@ -100,7 +100,7 @@ public class ConstantDef : MemberDef { var annotationAttrs = ci.GetCustomAttributes(true); - var valueType = TRU.FromType(ci.FieldType); + var valueType = Tru.FromType(ci.FieldType); if (valueType == null) throw new Exception($"Unsupported type `{ci.FieldType}` in constant `{type.Name}.{ci.Name}`"); diff --git a/Esiur/Data/Types/EventDef.cs b/Esiur/Data/Types/EventDef.cs index e1eb0a6..5a5f0dc 100644 --- a/Esiur/Data/Types/EventDef.cs +++ b/Esiur/Data/Types/EventDef.cs @@ -29,7 +29,7 @@ public class EventDef : MemberDef public EventInfo EventInfo { get; set; } - public TRU ArgumentType { get; set; } + public Tru ArgumentType { get; set; } public static (uint, EventDef) Parse(byte[] data, uint offset, byte index, bool inherited) @@ -42,7 +42,7 @@ public class EventDef : MemberDef var name = data.GetString(offset + 1, data[offset]); offset += (uint)data[offset] + 1; - var (dts, argType) = TRU.Parse(data, offset); + var (dts, argType) = Tru.Parse(data, offset); offset += dts; @@ -116,7 +116,7 @@ public class EventDef : MemberDef var argType = ei.EventHandlerType.GenericTypeArguments[0]; - var evtType = TRU.FromType(argType); + var evtType = Tru.FromType(argType); if (evtType == null) throw new Exception($"Unsupported type `{argType}` in event `{type.Name}.{ei.Name}`"); diff --git a/Esiur/Data/Types/FunctionDef.cs b/Esiur/Data/Types/FunctionDef.cs index 0837a53..251034d 100644 --- a/Esiur/Data/Types/FunctionDef.cs +++ b/Esiur/Data/Types/FunctionDef.cs @@ -27,7 +27,7 @@ public class FunctionDef : MemberDef // set; //} - public TRU ReturnType { get; set; } + public Tru ReturnType { get; set; } public bool IsStatic { get; set; } @@ -52,7 +52,7 @@ public class FunctionDef : MemberDef offset += (uint)data[offset] + 1; // return type - var (rts, returnType) = TRU.Parse(data, offset); + var (rts, returnType) = Tru.Parse(data, offset); offset += rts; // arguments count @@ -124,27 +124,27 @@ public class FunctionDef : MemberDef var genericRtType = mi.ReturnType.IsGenericType ? mi.ReturnType.GetGenericTypeDefinition() : null; - TRU rtType; + Tru rtType; if (genericRtType == typeof(AsyncReply<>)) { - rtType = TRU.FromType(mi.ReturnType.GetGenericArguments()[0]); + rtType = Tru.FromType(mi.ReturnType.GetGenericArguments()[0]); } else if (genericRtType == typeof(Task<>)) { - rtType = TRU.FromType(mi.ReturnType.GetGenericArguments()[0]); + rtType = Tru.FromType(mi.ReturnType.GetGenericArguments()[0]); } else if (genericRtType == typeof(IEnumerable<>) || genericRtType == typeof(IAsyncEnumerable<>)) { // get export - rtType = TRU.FromType(mi.ReturnType.GetGenericArguments()[0]); + rtType = Tru.FromType(mi.ReturnType.GetGenericArguments()[0]); } else { if (mi.ReturnType == typeof(Task)) - rtType = TRU.FromType(null); + rtType = Tru.FromType(null); else - rtType = TRU.FromType(mi.ReturnType); + rtType = Tru.FromType(mi.ReturnType); } if (rtType == null) @@ -214,7 +214,7 @@ public class FunctionDef : MemberDef var arguments = args.Select(x => { - var argType = TRU.FromType(x.ParameterType); + var argType = Tru.FromType(x.ParameterType); if (argType == null) throw new Exception($"Unsupported type `{x.ParameterType}` in method `{type.Name}.{mi.Name}` parameter `{x.Name}`"); diff --git a/Esiur/Data/Types/PropertyDef.cs b/Esiur/Data/Types/PropertyDef.cs index 2a3dd0f..aad4796 100644 --- a/Esiur/Data/Types/PropertyDef.cs +++ b/Esiur/Data/Types/PropertyDef.cs @@ -24,7 +24,7 @@ public class PropertyDef : MemberDef set; } - public TRU ValueType { get; set; } + public Tru ValueType { get; set; } /* @@ -93,7 +93,7 @@ public class PropertyDef : MemberDef offset += (uint)data[offset] + 1; - var (dts, valueType) = TRU.Parse(data, offset); + var (dts, valueType) = Tru.Parse(data, offset); offset += dts; @@ -200,8 +200,8 @@ public class PropertyDef : MemberDef var genericPropType = pi.PropertyType.IsGenericType ? pi.PropertyType.GetGenericTypeDefinition() : null; var propType = genericPropType == typeof(PropertyContext<>) ? - TRU.FromType(pi.PropertyType.GetGenericArguments()[0]) : - TRU.FromType(pi.PropertyType); + Tru.FromType(pi.PropertyType.GetGenericArguments()[0]) : + Tru.FromType(pi.PropertyType); if (propType == null) throw new Exception($"Unsupported type `{pi.PropertyType}` in property `{type.Name}.{pi.Name}`"); diff --git a/Esiur/Data/Types/TypeDef.cs b/Esiur/Data/Types/TypeDef.cs index 5d4f71c..f8eb566 100644 --- a/Esiur/Data/Types/TypeDef.cs +++ b/Esiur/Data/Types/TypeDef.cs @@ -18,8 +18,8 @@ namespace Esiur.Data.Types; public class TypeDef { - protected UUID typeId; - protected UUID? parentId; + protected Uuid typeId; + protected Uuid? parentId; public Map Annotations { get; set; } @@ -41,7 +41,7 @@ public class TypeDef protected byte[] content; - public UUID? ParentId => parentId; + public Uuid? ParentId => parentId; public byte[] Content { @@ -110,7 +110,7 @@ public class TypeDef return null; } - public UUID Id + public Uuid Id { get { return typeId; } } @@ -142,7 +142,7 @@ public class TypeDef } - public static UUID GetTypeUUID(Type type) + public static Uuid GetTypeUUID(Type type) { var attr = type.GetCustomAttribute(); if (attr != null) @@ -153,7 +153,7 @@ public class TypeDef hash[6] = (byte)((hash[6] & 0xF) | 0x80); hash[8] = (byte)((hash[8] & 0xF) | 0x80); - var rt = new UUID(hash); + var rt = new Uuid(hash); return rt; } diff --git a/Esiur/Data/UUID.cs b/Esiur/Data/UUID.cs index f3ffbee..9f72165 100644 --- a/Esiur/Data/UUID.cs +++ b/Esiur/Data/UUID.cs @@ -9,7 +9,7 @@ using System.Text; namespace Esiur.Data { //[StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct UUID + public struct Uuid { //4e7db2d8-a785-1b99-1854-4b4018bc5677 //byte a1; @@ -32,7 +32,7 @@ namespace Esiur.Data public byte[] Data { get; private set; } - public UUID(byte[] data, uint offset) + public Uuid(byte[] data, uint offset) { if (offset + 16 > data.Length) throw new Exception("UUID data size must be at least 16 bytes"); @@ -74,7 +74,7 @@ namespace Esiur.Data } - public UUID(byte[] data) { + public Uuid(byte[] data) { if (data.Length != 16) throw new Exception("UUID data size must be 16 bytes"); @@ -107,13 +107,13 @@ namespace Esiur.Data public override bool Equals(object obj) { - if (obj is UUID b) + if (obj is Uuid b) return Data.SequenceEqual(b.Data); return false; } - public static bool operator == (UUID a, UUID b) + public static bool operator == (Uuid a, Uuid b) { return a.Data.SequenceEqual(b.Data); @@ -135,7 +135,7 @@ namespace Esiur.Data // && a.e6 == b.e6; } - public static bool operator !=(UUID a, UUID b) + public static bool operator !=(Uuid a, Uuid b) { return !(a == b); } diff --git a/Esiur/Esiur.csproj b/Esiur/Esiur.csproj index 61c43ed..50d2f13 100644 --- a/Esiur/Esiur.csproj +++ b/Esiur/Esiur.csproj @@ -39,6 +39,7 @@ + @@ -60,6 +61,10 @@ + + + + @@ -69,7 +74,11 @@ + + + + diff --git a/Esiur/Net/HTTP/HTTPConnection.cs b/Esiur/Net/HTTP/HTTPConnection.cs index 796f984..3cb08f2 100644 --- a/Esiur/Net/HTTP/HTTPConnection.cs +++ b/Esiur/Net/HTTP/HTTPConnection.cs @@ -37,22 +37,22 @@ using Esiur.Misc; using System.Security.Cryptography; using Esiur.Core; using Esiur.Net.Packets.WebSocket; -using Esiur.Net.Packets.HTTP; +using Esiur.Net.Packets.Http; -namespace Esiur.Net.HTTP; -public class HTTPConnection : NetworkConnection +namespace Esiur.Net.Http; +public class HttpConnection : NetworkConnection { public bool WSMode { get; internal set; } - public HTTPServer Server { get; internal set; } + public HttpServer Server { get; internal set; } public WebsocketPacket WSRequest { get; set; } - public HTTPRequestPacket Request { get; set; } - public HTTPResponsePacket Response { get; } = new HTTPResponsePacket(); + public HttpRequestPacket Request { get; set; } + public HttpResponsePacket Response { get; } = new HttpResponsePacket(); - HTTPSession session; + HttpSession session; public KeyList Variables { get; } = new KeyList(); @@ -80,7 +80,7 @@ public class HTTPConnection : NetworkConnection } else { - var rp = new HTTPRequestPacket(); + var rp = new HttpRequestPacket(); var pSize = rp.Parse(data, 0, (uint)data.Length); if (pSize > 0) { @@ -115,7 +115,7 @@ public class HTTPConnection : NetworkConnection return ok; } - public static bool Upgrade(HTTPRequestPacket request, HTTPResponsePacket response) + public static bool Upgrade(HttpRequestPacket request, HttpResponsePacket response) { if (IsWebsocketRequest(request)) { @@ -132,7 +132,7 @@ public class HTTPConnection : NetworkConnection response.Headers["Sec-WebSocket-Protocol"] = request.Headers["Sec-WebSocket-Protocol"]; - response.Number = HTTPResponseCode.Switching; + response.Number = HttpResponseCode.Switching; response.Text = "Switching Protocols"; return true; @@ -141,7 +141,7 @@ public class HTTPConnection : NetworkConnection return false; } - public HTTPServer Parent + public HttpServer Parent { get { @@ -173,7 +173,7 @@ public class HTTPConnection : NetworkConnection Send(); } - public void Send(HTTPComposeOption Options = HTTPComposeOption.AllCalculateLength) + public void Send(HttpComposeOption Options = HttpComposeOption.AllCalculateLength) { if (Response.Handled) return; @@ -211,7 +211,7 @@ public class HTTPConnection : NetworkConnection // Create a new one session = Server.CreateSession(Global.GenerateCode(12), 60 * 20); - HTTPCookie cookie = new HTTPCookie("SID", session.Id); + HttpCookie cookie = new HttpCookie("SID", session.Id); cookie.Expires = DateTime.MaxValue; cookie.Path = "/"; cookie.HttpOnly = true; @@ -226,7 +226,7 @@ public class HTTPConnection : NetworkConnection return IsWebsocketRequest(this.Request); } - public static bool IsWebsocketRequest(HTTPRequestPacket request) + public static bool IsWebsocketRequest(HttpRequestPacket request) { if (request.Headers.ContainsKey("connection") && request.Headers["connection"].ToLower().Contains("upgrade") @@ -254,7 +254,7 @@ public class HTTPConnection : NetworkConnection if (BL == 0) { - if (Request.Method == HTTPMethod.UNKNOWN) + if (Request.Method == Packets.Http.HttpMethod.UNKNOWN) { Close(); return; @@ -313,7 +313,7 @@ public class HTTPConnection : NetworkConnection { if (!Server.Execute(this)) { - Response.Number = HTTPResponseCode.InternalServerError; + Response.Number = HttpResponseCode.InternalServerError; Send("Bad Request"); Close(); } @@ -362,7 +362,7 @@ public class HTTPConnection : NetworkConnection if (!File.Exists(filename)) { - Response.Number = HTTPResponseCode.NotFound; + Response.Number = HttpResponseCode.NotFound; Send("File Not Found"); return true; } @@ -376,10 +376,10 @@ public class HTTPConnection : NetworkConnection var ims = DateTime.Parse(Request.Headers["if-modified-since"]); if ((fileEditTime - ims).TotalSeconds < 2) { - Response.Number = HTTPResponseCode.NotModified; + Response.Number = HttpResponseCode.NotModified; Response.Headers.Clear(); //Response.Text = "Not Modified"; - Send(HTTPComposeOption.SpecifiedHeadersOnly); + Send(HttpComposeOption.SpecifiedHeadersOnly); return true; } } @@ -391,12 +391,12 @@ public class HTTPConnection : NetworkConnection - Response.Number = HTTPResponseCode.OK; + Response.Number = HttpResponseCode.OK; // Fri, 30 Oct 2007 14:19:41 GMT Response.Headers["Last-Modified"] = fileEditTime.ToString("ddd, dd MMM yyyy HH:mm:ss"); FileInfo fi = new FileInfo(filename); Response.Headers["Content-Length"] = fi.Length.ToString(); - Send(HTTPComposeOption.SpecifiedHeadersOnly); + Send(HttpComposeOption.SpecifiedHeadersOnly); //var fd = File.ReadAllBytes(filename); diff --git a/Esiur/Net/HTTP/HTTPFilter.cs b/Esiur/Net/HTTP/HTTPFilter.cs index 3270b16..8cfcc74 100644 --- a/Esiur/Net/HTTP/HTTPFilter.cs +++ b/Esiur/Net/HTTP/HTTPFilter.cs @@ -35,9 +35,9 @@ using Esiur.Data; using Esiur.Core; using Esiur.Resource; -namespace Esiur.Net.HTTP; +namespace Esiur.Net.Http; -public abstract class HTTPFilter : IResource +public abstract class HttpFilter : IResource { public Instance Instance { @@ -60,14 +60,14 @@ public abstract class HTTPFilter : IResource } */ - public abstract AsyncReply Execute(HTTPConnection sender); + public abstract AsyncReply Execute(HttpConnection sender); - public virtual void ClientConnected(HTTPConnection HTTP) + public virtual void ClientConnected(HttpConnection HTTP) { //return false; } - public virtual void ClientDisconnected(HTTPConnection HTTP) + public virtual void ClientDisconnected(HttpConnection HTTP) { //return false; } diff --git a/Esiur/Net/HTTP/HTTPServer.cs b/Esiur/Net/HTTP/HTTPServer.cs index f33bdc0..5f6453b 100644 --- a/Esiur/Net/HTTP/HTTPServer.cs +++ b/Esiur/Net/HTTP/HTTPServer.cs @@ -40,25 +40,25 @@ using Esiur.Resource; using System.Text.RegularExpressions; using System.Linq; using System.Reflection; -using Esiur.Net.Packets.HTTP; +using Esiur.Net.Packets.Http; -namespace Esiur.Net.HTTP; -public class HTTPServer : NetworkServer, IResource +namespace Esiur.Net.Http; +public class HttpServer : NetworkServer, IResource { - Dictionary sessions = new Dictionary(); - HTTPFilter[] filters = new HTTPFilter[0]; + Dictionary sessions = new Dictionary(); + HttpFilter[] filters = new HttpFilter[0]; - Dictionary> routes = new() + Dictionary> routes = new() { - [HTTPMethod.GET] = new List(), - [HTTPMethod.POST] = new List(), - [HTTPMethod.HEAD] = new List(), - [HTTPMethod.OPTIONS] = new List(), - [HTTPMethod.UNKNOWN] = new List(), - [HTTPMethod.DELETE] = new List(), - [HTTPMethod.TRACE] = new List(), - [HTTPMethod.CONNECT] = new List(), - [HTTPMethod.PUT] = new List() + [Packets.Http.HttpMethod.GET] = new List(), + [Packets.Http.HttpMethod.POST] = new List(), + [Packets.Http.HttpMethod.HEAD] = new List(), + [Packets.Http.HttpMethod.OPTIONS] = new List(), + [Packets.Http.HttpMethod.UNKNOWN] = new List(), + [Packets.Http.HttpMethod.DELETE] = new List(), + [Packets.Http.HttpMethod.TRACE] = new List(), + [Packets.Http.HttpMethod.CONNECT] = new List(), + [Packets.Http.HttpMethod.PUT] = new List() }; //List GetRoutes = new List(); @@ -86,7 +86,7 @@ public class HTTPServer : NetworkServer, IResource var last = ps.LastOrDefault(); - if (last != null && last.ParameterType == typeof(HTTPConnection)) + if (last != null && last.ParameterType == typeof(HttpConnection)) { SenderIndex = ps.Length - 1; @@ -101,7 +101,7 @@ public class HTTPServer : NetworkServer, IResource } - public bool Invoke(HTTPConnection sender) + public bool Invoke(HttpConnection sender) { var match = Pattern.Match(sender.Request.URL); @@ -176,9 +176,9 @@ public class HTTPServer : NetworkServer, IResource } - public HTTPSession CreateSession(string id, int timeout) + public HttpSession CreateSession(string id, int timeout) { - var s = new HTTPSession(); + var s = new HttpSession(); s.Set(id, timeout); @@ -214,7 +214,7 @@ public class HTTPServer : NetworkServer, IResource return Cookie; } - protected override void ClientDisconnected(HTTPConnection connection) + protected override void ClientDisconnected(HttpConnection connection) { foreach (var filter in filters) filter.ClientDisconnected(connection); @@ -222,7 +222,7 @@ public class HTTPServer : NetworkServer, IResource - internal bool Execute(HTTPConnection sender) + internal bool Execute(HttpConnection sender) { if (!sender.WSMode) foreach (var route in routes[sender.Request.Method]) @@ -243,14 +243,14 @@ public class HTTPServer : NetworkServer, IResource public void MapGet(string pattern, Delegate handler) { var regex = Global.GetRouteRegex(pattern); - var list = routes[HTTPMethod.GET]; + var list = routes[Packets.Http.HttpMethod.GET]; list.Add(new RouteInfo(handler, regex)); } public void MapPost(string pattern, Delegate handler) { var regex = Global.GetRouteRegex(pattern); - var list = routes[HTTPMethod.POST]; + var list = routes[Packets.Http.HttpMethod.POST]; list.Add(new RouteInfo(handler, regex)); } @@ -329,7 +329,7 @@ public class HTTPServer : NetworkServer, IResource } else if (trigger == ResourceTrigger.SystemInitialized) { - filters = await Instance.Children(); + filters = await Instance.Children(); } return true; @@ -337,19 +337,19 @@ public class HTTPServer : NetworkServer, IResource } - public override void Add(HTTPConnection connection) + public override void Add(HttpConnection connection) { connection.Server = this; base.Add(connection); } - public override void Remove(HTTPConnection connection) + public override void Remove(HttpConnection connection) { connection.Server = null; base.Remove(connection); } - protected override void ClientConnected(HTTPConnection connection) + protected override void ClientConnected(HttpConnection connection) { //if (filters.Length == 0 && routes.) //{ diff --git a/Esiur/Net/HTTP/HTTPSession.cs b/Esiur/Net/HTTP/HTTPSession.cs index d97166f..58d59bd 100644 --- a/Esiur/Net/HTTP/HTTPSession.cs +++ b/Esiur/Net/HTTP/HTTPSession.cs @@ -35,11 +35,11 @@ using Esiur.Data; using Esiur.Misc; using Esiur.Core; -namespace Esiur.Net.HTTP; -public class HTTPSession : IDestructible // where T : TClient +namespace Esiur.Net.Http; +public class HttpSession : IDestructible // where T : TClient { - public delegate void SessionModifiedEvent(HTTPSession session, string key, object oldValue, object newValue); - public delegate void SessionEndedEvent(HTTPSession session); + public delegate void SessionModifiedEvent(HttpSession session, string key, object oldValue, object newValue); + public delegate void SessionEndedEvent(HttpSession session); private string id; private Timer timer; @@ -58,7 +58,7 @@ public class HTTPSession : IDestructible // where T : TClient get { return variables; } } - public HTTPSession() + public HttpSession() { variables = new KeyList(); variables.OnModified += new KeyList.Modified(VariablesModified); diff --git a/Esiur/Net/Http/EPoHTTP.cs b/Esiur/Net/Http/EpOverHttp.cs similarity index 85% rename from Esiur/Net/Http/EPoHTTP.cs rename to Esiur/Net/Http/EpOverHttp.cs index 9e84986..4afa8f5 100644 --- a/Esiur/Net/Http/EPoHTTP.cs +++ b/Esiur/Net/Http/EpOverHttp.cs @@ -6,13 +6,13 @@ using System; using System.Collections.Generic; using System.Text; -namespace Esiur.Net.HTTP; -public class EPoHTTP : HTTPFilter +namespace Esiur.Net.Http; +public class EpOverHttp : HttpFilter { [Attribute] EntryPoint EntryPoint { get; set; } - public override AsyncReply Execute(HTTPConnection sender) + public override AsyncReply Execute(HttpConnection sender) { if (sender.Request.URL != "EP") return new AsyncReply(false); diff --git a/Esiur/Net/Http/EPoWS.cs b/Esiur/Net/Http/EpOvwerWebsocket.cs similarity index 94% rename from Esiur/Net/Http/EPoWS.cs rename to Esiur/Net/Http/EpOvwerWebsocket.cs index 2da2cbd..6470628 100644 --- a/Esiur/Net/Http/EPoWS.cs +++ b/Esiur/Net/Http/EpOvwerWebsocket.cs @@ -32,8 +32,8 @@ using Esiur.Net.Sockets; using Esiur.Core; using Esiur.Protocol; -namespace Esiur.Net.HTTP; -public class EPoWS : HTTPFilter +namespace Esiur.Net.Http; +public class EpOvwerWebsocket : HttpFilter { [Attribute] public EpServer Server @@ -42,7 +42,7 @@ public class EPoWS : HTTPFilter set; } - public override AsyncReply Execute(HTTPConnection sender) + public override AsyncReply Execute(HttpConnection sender) { if (sender.IsWebsocketRequest()) diff --git a/Esiur/Net/Packets/EpAuthPacket.cs b/Esiur/Net/Packets/EpAuthPacket.cs index 5a84e55..3bb70d3 100644 --- a/Esiur/Net/Packets/EpAuthPacket.cs +++ b/Esiur/Net/Packets/EpAuthPacket.cs @@ -1,6 +1,6 @@ /* -Copyright (c) 2017 Ahmed Kh. Zamil +Copyright (c) 2017-2026 Ahmed Kh. Zamil Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -37,23 +37,11 @@ namespace Esiur.Net.Packets; public class EpAuthPacket : Packet { - public EpAuthPacketCommand Command { get; set; } - public EpAuthPacketInitialize Initialization - { - get; - set; - } - - public EpAuthPacketAcknowledge Acknowledgement - { - get; - set; - } public EpAuthPacketAction Action { @@ -67,18 +55,32 @@ public class EpAuthPacket : Packet set; } - public AuthenticationMethod LocalMethod + public EpAuthPacketAcknowledgement Acknowledgement { get; set; } - public AuthenticationMethod RemoteMethod + + public EpAuthPacketAuthMode AuthMode { get; set; } + public EpAuthPacketEncryptionMode EncryptionMode + { + get; + set; + } + + //public AuthenticationMethod AuthenticationMethod + //{ + // get; + // set; + //} + + public byte ErrorCode { get; @@ -91,52 +93,14 @@ public class EpAuthPacket : Packet set; } - - public EpAuthPacketPublicKeyAlgorithm PublicKeyAlgorithm - { - get; - set; - } - - public EpAuthPacketHashAlgorithm HashAlgorithm - { - get; - set; - } - - - public byte[] Certificate - { - get; - set; - } - - public byte[] Challenge - { - get; - set; - } - - public byte[] AsymetricEncryptionKey - { - get; - set; - } - - public byte[] SessionId { get; set; } - public byte[] AccountId - { - get; - set; - } - public ParsedTDU? DataType + public ParsedTdu? Tdu { get; set; @@ -177,284 +141,46 @@ public class EpAuthPacket : Packet return -dataLengthNeeded; Command = (EpAuthPacketCommand)(data[offset] >> 6); + var hasTdu = (data[offset] & 0x20) != 0; if (Command == EpAuthPacketCommand.Initialize) { - LocalMethod = (AuthenticationMethod)(data[offset] >> 4 & 0x3); - RemoteMethod = (AuthenticationMethod)(data[offset] >> 2 & 0x3); - - Initialization = (EpAuthPacketInitialize)(data[offset++] & 0xFC); // remove last two reserved LSBs - - if (NotEnough(offset, ends, 1)) - return -dataLengthNeeded; - - DataType = ParsedTDU.Parse(data, offset, ends); - - if (DataType.Value.Class == TDUClass.Invalid) - return -(int)DataType.Value.TotalLength; - - - offset += (uint)DataType.Value.TotalLength; - + AuthMode = (EpAuthPacketAuthMode)(data[offset] >> 3 & 0x7); + EncryptionMode = (EpAuthPacketEncryptionMode)(data[offset++] & 0x7); } else if (Command == EpAuthPacketCommand.Acknowledge) { - - LocalMethod = (AuthenticationMethod)(data[offset] >> 4 & 0x3); - RemoteMethod = (AuthenticationMethod)(data[offset] >> 2 & 0x3); - - Acknowledgement = (EpAuthPacketAcknowledge)(data[offset++] & 0xFC); // remove last two reserved LSBs - - if (NotEnough(offset, ends, 1)) - return -dataLengthNeeded; - - DataType = ParsedTDU.Parse(data, offset, ends); - - if (DataType.Value.Class == TDUClass.Invalid) - return -(int)DataType.Value.TotalLength; - - - offset += (uint)DataType.Value.TotalLength; + // remove last two reserved LSBs + Acknowledgement = (EpAuthPacketAcknowledgement)(data[offset++]);// & 0xFC); } else if (Command == EpAuthPacketCommand.Action) { - Action = (EpAuthPacketAction)data[offset++]; // (EPAuthPacketAction)(data[offset++] & 0x3f); - - if (Action == EpAuthPacketAction.AuthenticateHash - || Action == EpAuthPacketAction.AuthenticatePublicHash - || Action == EpAuthPacketAction.AuthenticatePrivateHash - || Action == EpAuthPacketAction.AuthenticatePublicPrivateHash) - { - if (NotEnough(offset, ends, 3)) - return -dataLengthNeeded; - - HashAlgorithm = (EpAuthPacketHashAlgorithm)data[offset++]; - - var hashLength = data.GetUInt16(offset, Endian.Little); - offset += 2; - - - if (NotEnough(offset, ends, hashLength)) - return -dataLengthNeeded; - - Challenge = data.Clip(offset, hashLength); - offset += hashLength; - - } - else if (Action == EpAuthPacketAction.AuthenticatePrivateHashCert - || Action == EpAuthPacketAction.AuthenticatePublicPrivateHashCert) - { - if (NotEnough(offset, ends, 3)) - return -dataLengthNeeded; - - HashAlgorithm = (EpAuthPacketHashAlgorithm)data[offset++]; - - var hashLength = data.GetUInt16(offset, Endian.Little); - offset += 2; - - - if (NotEnough(offset, ends, hashLength)) - return -dataLengthNeeded; - - Challenge = data.Clip(offset, hashLength); - offset += hashLength; - - if (NotEnough(offset, ends, 2)) - return -dataLengthNeeded; - - var certLength = data.GetUInt16(offset, Endian.Little); - offset += 2; - - if (NotEnough(offset, ends, certLength)) - return -dataLengthNeeded; - - Certificate = data.Clip(offset, certLength); - - offset += certLength; - } - else if (Action == EpAuthPacketAction.IAuthPlain) - { - if (NotEnough(offset, ends, 5)) - return -dataLengthNeeded; - - Reference = data.GetUInt32(offset, Endian.Little); - offset += 4; - - DataType = ParsedTDU.Parse(data, offset, ends); - - if (DataType.Value.Class == TDUClass.Invalid) - return -(int)DataType.Value.TotalLength; - - offset += (uint)DataType.Value.TotalLength; - - } - else if (Action == EpAuthPacketAction.IAuthHashed) - { - if (NotEnough(offset, ends, 7)) - return -dataLengthNeeded; - - Reference = data.GetUInt32(offset, Endian.Little); - offset += 4; - - HashAlgorithm = (EpAuthPacketHashAlgorithm)data[offset++]; - - var cl = data.GetUInt16(offset, Endian.Little); - offset += 2; - - if (NotEnough(offset, ends, cl)) - return -dataLengthNeeded; - - Challenge = data.Clip(offset, cl); - - offset += cl; - - } - else if (Action == EpAuthPacketAction.IAuthEncrypted) - { - if (NotEnough(offset, ends, 7)) - return -dataLengthNeeded; - - Reference = data.GetUInt32(offset, Endian.Little); - offset += 4; - - PublicKeyAlgorithm = (EpAuthPacketPublicKeyAlgorithm)data[offset++]; - - var cl = data.GetUInt16(offset, Endian.Little); - offset += 2; - - if (NotEnough(offset, ends, cl)) - return -dataLengthNeeded; - - Challenge = data.Clip(offset, cl); - - offset += cl; - - } - else if (Action == EpAuthPacketAction.EstablishNewSession) - { - // Nothing here - } - else if (Action == EpAuthPacketAction.EstablishResumeSession) - { - if (NotEnough(offset, ends, 1)) - return -dataLengthNeeded; - - var sessionLength = data[offset++]; - - if (NotEnough(offset, ends, sessionLength)) - return -dataLengthNeeded; - - SessionId = data.Clip(offset, sessionLength); - - offset += sessionLength; - } - - else if (Action == EpAuthPacketAction.EncryptKeyExchange) - { - if (NotEnough(offset, ends, 2)) - return -dataLengthNeeded; - - var keyLength = data.GetUInt16(offset, Endian.Little); - - offset += 2; - - if (NotEnough(offset, ends, keyLength)) - return -dataLengthNeeded; - - AsymetricEncryptionKey = data.Clip(offset, keyLength); - - offset += keyLength; - } - - else if (Action == EpAuthPacketAction.RegisterEndToEndKey - || Action == EpAuthPacketAction.RegisterHomomorphic) - { - if (NotEnough(offset, ends, 3)) - return -dataLengthNeeded; - - PublicKeyAlgorithm = (EpAuthPacketPublicKeyAlgorithm)data[offset++]; - - var keyLength = data.GetUInt16(offset, Endian.Little); - - offset += 2; - - if (NotEnough(offset, ends, keyLength)) - return -dataLengthNeeded; - - AsymetricEncryptionKey = data.Clip(offset, keyLength); - - offset += keyLength; - - } + // remove last two reserved LSBs + Action = (EpAuthPacketAction)(data[offset++]);// & 0xFC); } else if (Command == EpAuthPacketCommand.Event) { - - Event = (EpAuthPacketEvent)data[offset++]; - - if (Event == EpAuthPacketEvent.ErrorTerminate - || Event == EpAuthPacketEvent.ErrorMustEncrypt - || Event == EpAuthPacketEvent.ErrorRetry) - { - if (NotEnough(offset, ends, 3)) - return -dataLengthNeeded; - - ErrorCode = data[offset++]; - var msgLength = data.GetUInt16(offset, Endian.Little); - offset += 2; - - if (NotEnough(offset, ends, msgLength)) - return -dataLengthNeeded; - - - Message = data.GetString(offset, msgLength); - - offset += msgLength; - } - else if (Event == EpAuthPacketEvent.IndicationEstablished) - { - if (NotEnough(offset, ends, 2)) - return -dataLengthNeeded; - - var sessionLength = data[offset++]; - - if (NotEnough(offset, ends, sessionLength)) - return -dataLengthNeeded; - - SessionId = data.Clip(offset, sessionLength); - - offset += sessionLength; - - if (NotEnough(offset, ends, 1)) - return -dataLengthNeeded; - - var accountLength = data[offset++]; - - if (NotEnough(offset, ends, accountLength)) - return -dataLengthNeeded; - - AccountId = data.Clip(offset, accountLength); - - offset += accountLength; - } - - else if (Event == EpAuthPacketEvent.IAuthPlain - || Event == EpAuthPacketEvent.IAuthHashed - || Event == EpAuthPacketEvent.IAuthEncrypted) - { - if (NotEnough(offset, ends, 1)) - return -dataLengthNeeded; - - DataType = ParsedTDU.Parse(data, offset, ends); - - if (DataType.Value.Class == TDUClass.Invalid) - return -(int)DataType.Value.TotalLength; - - offset += (uint)DataType.Value.TotalLength; - - } + // remove last two reserved LSBs + Event = (EpAuthPacketEvent)(data[offset++]);// & 0xFC); + } + else + { + return -1; // invalid command } + if (hasTdu) + { + if (NotEnough(offset, ends, 1)) + return -dataLengthNeeded; + + Tdu = ParsedTdu.Parse(data, offset, ends); + + if (Tdu.Value.Class == TduClass.Invalid) + return -(int)Tdu.Value.TotalLength; + + offset += (uint)Tdu.Value.TotalLength; + + } return offset - oOffset; diff --git a/Esiur/Net/Packets/EpAuthPacketAcknowledge.cs b/Esiur/Net/Packets/EpAuthPacketAcknowledge.cs deleted file mode 100644 index 7fc2f3b..0000000 --- a/Esiur/Net/Packets/EpAuthPacketAcknowledge.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Esiur.Net.Packets -{ - public enum EpAuthPacketAcknowledge : byte - { - NoAuthNoAuth = 0x40, // 0b01000000, - NoAuthCredentials = 0x44, // 0b01000100, - NoAuthToken = 0x48, //0b01001000, - NoAuthCertificate = 0x4c, //0b01001100, - CredentialsNoAuth = 0x50, //0b01010000, - CredentialsCredentials = 0x54, //0b01010100, - CredentialsToken = 0x58, //0b01011000, - CredentialsCertificate = 0x5c, //0b01011100, - TokenNoAuth = 0x60, //0b01100000, - TokenCredentials = 0x64, //0b01100100, - TokenToken = 0x68, //0b01101000, - TokenCertificate = 0x6c, //0b01101100, - CertificateNoAuth = 0x70, //0b01110000, - CertificateCredentials = 0x74, //0b01110100, - CertificateToken = 0x78, //0b01111000, - CertificateCertificate = 0x7c, // 0b01111100, - } -} diff --git a/Esiur/Net/Packets/EpAuthPacketAcknowledgement.cs b/Esiur/Net/Packets/EpAuthPacketAcknowledgement.cs new file mode 100644 index 0000000..bd8100a --- /dev/null +++ b/Esiur/Net/Packets/EpAuthPacketAcknowledgement.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Esiur.Net.Packets +{ + public enum EpAuthPacketAcknowledgement : byte + { + Denied = 0x40, // no reason, terminate connection + NotSupported = 0x41, // auth not supported, terminate connection + TrySupported = 0x42, // auth not supported, but other auth methods in the reply are supported. connection is still open + Retry = 0x43, // try another auth method, connection is still open + ProceedToHandshake = 0x44, // auth method accepted, proceed to handshake, connection is still open + ProceedToFinalHandshake = 0x45, // auth method accepted, proceed to final handshake, connection is still open + ProceedToEstablishSession = 0x46, // auth method accepted, proceed to establish session, connection is still open + SessionEstablished = 0x47, // session established, session Id provided, switch to session mode, connection is still open + } +} diff --git a/Esiur/Net/Packets/EpAuthPacketAction.cs b/Esiur/Net/Packets/EpAuthPacketAction.cs index a2da57f..913644b 100644 --- a/Esiur/Net/Packets/EpAuthPacketAction.cs +++ b/Esiur/Net/Packets/EpAuthPacketAction.cs @@ -6,26 +6,29 @@ namespace Esiur.Net.Packets { public enum EpAuthPacketAction : byte { - AuthenticateHash = 0x80, - AuthenticatePublicHash = 0x81, - AuthenticatePrivateHash = 0x82, - AuthenticatePublicPrivateHash = 0x83, + Handshake = 0x80, + FinalHandshake = 0x81, - AuthenticatePrivateHashCert = 0x88, - AuthenticatePublicPrivateHashCert = 0x89, + //AuthenticateHash = 0x80, + //AuthenticatePublicHash = 0x81, + //AuthenticatePrivateHash = 0x82, + //AuthenticatePublicPrivateHash = 0x83, - IAuthPlain = 0x90, - IAuthHashed = 0x91, - IAuthEncrypted = 0x92, + //AuthenticatePrivateHashCert = 0x88, + //AuthenticatePublicPrivateHashCert = 0x89, + + //IAuthPlain = 0x90, + //IAuthHashed = 0x91, + //IAuthEncrypted = 0x92, - EstablishNewSession = 0x98, - EstablishResumeSession = 0x99, + //EstablishNewSession = 0x98, + //EstablishResumeSession = 0x99, - EncryptKeyExchange = 0xA0, + //EncryptKeyExchange = 0xA0, - RegisterEndToEndKey = 0xA8, - RegisterHomomorphic = 0xA9, + //RegisterEndToEndKey = 0xA8, + //RegisterHomomorphic = 0xA9, } } diff --git a/Esiur/Net/Packets/EpAuthPacketAuthMode.cs b/Esiur/Net/Packets/EpAuthPacketAuthMode.cs new file mode 100644 index 0000000..6841b47 --- /dev/null +++ b/Esiur/Net/Packets/EpAuthPacketAuthMode.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Esiur.Net.Packets +{ + public enum EpAuthPacketAuthMode : byte + { + NoAuh = 0x0, + InitializerIdentity = 0x1, + ResponderIdentity = 0x2, + DualIdentity = 0x3, + + + //NoAuthNoAuth = 0x0, //0b00000000, + //NoAuthCredentials = 0x4, //0b00000100, + //NoAuthToken = 0x8, //0b00001000, + //NoAuthCertificate = 0xC, //0b00001100, + //CredentialsNoAuth = 0x10, //0b00010000, + //CredentialsCredentials = 0x14, //0b00010100, + //CredentialsToken = 0x18, //0b00011000, + //CredentialsCertificate = 0x1c, //0b00011100, + //TokenNoAuth = 0x20, //0b00100000, + //TokenCredentials = 0x24, //0b00100100, + //TokenToken = 0x28, //0b00101000, + //TokenCertificate = 0x2c, //0b00101100, + //CertificateNoAuth = 0x30, //0b00110000, + //CertificateCredentials = 0x34,// 0b00110100, + //CertificateToken = 0x38, //0b00111000, + //CertificateCertificate = 0x3c, //0b00111100, + } +} diff --git a/Esiur/Net/Packets/EpAuthPacketCommand.cs b/Esiur/Net/Packets/EpAuthPacketCommand.cs index 7cf7796..220f742 100644 --- a/Esiur/Net/Packets/EpAuthPacketCommand.cs +++ b/Esiur/Net/Packets/EpAuthPacketCommand.cs @@ -11,5 +11,4 @@ namespace Esiur.Net.Packets Action = 0x2, Event = 0x3, } - } diff --git a/Esiur/Net/Packets/EpAuthPacketEncryptionMode.cs b/Esiur/Net/Packets/EpAuthPacketEncryptionMode.cs new file mode 100644 index 0000000..d4983d6 --- /dev/null +++ b/Esiur/Net/Packets/EpAuthPacketEncryptionMode.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Esiur.Net.Packets +{ + public enum EpAuthPacketEncryptionMode + { + NoEncryption, + EncryptWithSessionKey, + EncryptWithSessionKeyAndAddress, + } +} diff --git a/Esiur/Net/Packets/EpAuthPacketHashAlgorithm.cs b/Esiur/Net/Packets/EpAuthPacketHashAlgorithm.cs deleted file mode 100644 index 044d21d..0000000 --- a/Esiur/Net/Packets/EpAuthPacketHashAlgorithm.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Esiur.Net.Packets -{ - public enum EpAuthPacketHashAlgorithm - { - SHA256, - SHA3, - } -} diff --git a/Esiur/Net/Packets/EpAuthPacketHeader.cs b/Esiur/Net/Packets/EpAuthPacketHeader.cs index 6750c93..f927cfd 100644 --- a/Esiur/Net/Packets/EpAuthPacketHeader.cs +++ b/Esiur/Net/Packets/EpAuthPacketHeader.cs @@ -6,24 +6,19 @@ namespace Esiur.Net.Packets { public enum EpAuthPacketHeader { - Version = 0, - Domain = 1, - SupportedAuthentications = 2, - SupportedHashAlgorithms = 3, - SupportedCiphers = 4, - SupportedCompression = 5, - SupportedPersonalAuth = 6, - Nonce = 7, - Username = 8, - TokenIndex = 9, - CertificateId = 10, - CachedCertificates = 11, - CipherType = 12, - CipherKey = 13, - SoftwareIdentity = 14, - Referrer = 15, - Time = 16, - Certificate = 17, - IPAddress = 18, + Version, + Domain, + SupportedAuthentications , + SupportedHashAlgorithms, + SupportedCiphers, + SupportedCompression, + SupportedMultiFactorAuthentications, + CipherType, + CipherKey, + SoftwareIdentity, + Referrer, + Time, + IPAddress, + AuthenticationData, } } diff --git a/Esiur/Net/Packets/EpAuthPacketInitialize.cs b/Esiur/Net/Packets/EpAuthPacketInitialize.cs deleted file mode 100644 index 93fbce7..0000000 --- a/Esiur/Net/Packets/EpAuthPacketInitialize.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Esiur.Net.Packets -{ - public enum EpAuthPacketInitialize - { - NoAuthNoAuth = 0x0, //0b00000000, - NoAuthCredentials = 0x4, //0b00000100, - NoAuthToken = 0x8, //0b00001000, - NoAuthCertificate = 0xC, //0b00001100, - CredentialsNoAuth = 0x10, //0b00010000, - CredentialsCredentials = 0x14, //0b00010100, - CredentialsToken = 0x18, //0b00011000, - CredentialsCertificate = 0x1c, //0b00011100, - TokenNoAuth = 0x20, //0b00100000, - TokenCredentials = 0x24, //0b00100100, - TokenToken = 0x28, //0b00101000, - TokenCertificate = 0x2c, //0b00101100, - CertificateNoAuth = 0x30, //0b00110000, - CertificateCredentials = 0x34,// 0b00110100, - CertificateToken = 0x38, //0b00111000, - CertificateCertificate = 0x3c, //0b00111100, - } -} diff --git a/Esiur/Net/Packets/EpAuthPacketPublicKeyAlgorithm.cs b/Esiur/Net/Packets/EpAuthPacketPublicKeyAlgorithm.cs deleted file mode 100644 index 6b464fa..0000000 --- a/Esiur/Net/Packets/EpAuthPacketPublicKeyAlgorithm.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Esiur.Net.Packets -{ - public enum EpAuthPacketPublicKeyAlgorithm - { - RSA = 0, - CKKS = 1, - } -} diff --git a/Esiur/Net/Packets/EpPacket.cs b/Esiur/Net/Packets/EpPacket.cs index 8a8f2fd..4a27a40 100644 --- a/Esiur/Net/Packets/EpPacket.cs +++ b/Esiur/Net/Packets/EpPacket.cs @@ -1,6 +1,6 @@ /* -Copyright (c) 2017-2025 Ahmed Kh. Zamil +Copyright (c) 2017-2026 Ahmed Kh. Zamil Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -44,7 +44,7 @@ class EpPacket : Packet public byte Extension { get; set; } - public ParsedTDU? DataType { get; set; } + public ParsedTdu? Tdu { get; set; } private uint dataLengthNeeded; @@ -124,16 +124,16 @@ class EpPacket : Packet if (NotEnough(offset, ends, 1)) return -dataLengthNeeded; - DataType = ParsedTDU.Parse(data, offset, ends); + Tdu = ParsedTdu.Parse(data, offset, ends); - if (DataType.Value.Class == TDUClass.Invalid) - return -(int)DataType.Value.TotalLength; + if (Tdu.Value.Class == TduClass.Invalid) + return -(int)Tdu.Value.TotalLength; - offset += (uint)DataType.Value.TotalLength; + offset += (uint)Tdu.Value.TotalLength; } else { - DataType = null; + Tdu = null; } return offset - originalOffset; diff --git a/Esiur/Net/Packets/EpPacketAttachInfo.cs b/Esiur/Net/Packets/EpPacketAttachInfo.cs index 0494074..7800b5f 100644 --- a/Esiur/Net/Packets/EpPacketAttachInfo.cs +++ b/Esiur/Net/Packets/EpPacketAttachInfo.cs @@ -10,9 +10,9 @@ struct EpPacketAttachInfo public string Link; public ulong Age; public byte[] Content; - public UUID TypeId; + public Uuid TypeId; - public EpPacketAttachInfo(UUID typeId, ulong age, string link, byte[] content) + public EpPacketAttachInfo(Uuid typeId, ulong age, string link, byte[] content) { TypeId = typeId; Age = age; diff --git a/Esiur/Net/Packets/HTTP/HTTPComposeOption.cs b/Esiur/Net/Packets/HTTP/HTTPComposeOption.cs index 782f96c..c74859b 100644 --- a/Esiur/Net/Packets/HTTP/HTTPComposeOption.cs +++ b/Esiur/Net/Packets/HTTP/HTTPComposeOption.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using System.Text; -namespace Esiur.Net.Packets.HTTP +namespace Esiur.Net.Packets.Http { - public enum HTTPComposeOption : int + public enum HttpComposeOption : int { AllCalculateLength, AllDontCalculateLength, diff --git a/Esiur/Net/Packets/HTTP/HTTPCookie.cs b/Esiur/Net/Packets/HTTP/HTTPCookie.cs index aac0fcf..8378404 100644 --- a/Esiur/Net/Packets/HTTP/HTTPCookie.cs +++ b/Esiur/Net/Packets/HTTP/HTTPCookie.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using System.Text; -namespace Esiur.Net.Packets.HTTP +namespace Esiur.Net.Packets.Http { - public struct HTTPCookie + public struct HttpCookie { public string Name; public string Value; @@ -13,7 +13,7 @@ namespace Esiur.Net.Packets.HTTP public bool HttpOnly; public string Domain; - public HTTPCookie(string name, string value) + public HttpCookie(string name, string value) { Name = name; Value = value; @@ -23,7 +23,7 @@ namespace Esiur.Net.Packets.HTTP Domain = null; } - public HTTPCookie(string name, string value, DateTime expires) + public HttpCookie(string name, string value, DateTime expires) { Name = name; Value = value; diff --git a/Esiur/Net/Packets/HTTP/HTTPMethod.cs b/Esiur/Net/Packets/HTTP/HTTPMethod.cs index 2fb3f62..3251ce5 100644 --- a/Esiur/Net/Packets/HTTP/HTTPMethod.cs +++ b/Esiur/Net/Packets/HTTP/HTTPMethod.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using System.Text; -namespace Esiur.Net.Packets.HTTP +namespace Esiur.Net.Packets.Http { - public enum HTTPMethod : byte + public enum HttpMethod : byte { GET, POST, diff --git a/Esiur/Net/Packets/HTTP/HTTPRequestPacket.cs b/Esiur/Net/Packets/HTTP/HTTPRequestPacket.cs index b699daa..2a41670 100644 --- a/Esiur/Net/Packets/HTTP/HTTPRequestPacket.cs +++ b/Esiur/Net/Packets/HTTP/HTTPRequestPacket.cs @@ -32,13 +32,13 @@ using Esiur.Data; using System.Net; using System.Text.Json.Serialization; -namespace Esiur.Net.Packets.HTTP; -public class HTTPRequestPacket : Packet +namespace Esiur.Net.Packets.Http; +public class HttpRequestPacket : Packet { public StringKeyList Query; - public HTTPMethod Method; + public HttpMethod Method; public StringKeyList Headers; public bool WSMode; @@ -52,28 +52,28 @@ public class HTTPRequestPacket : Packet public byte[] Message; - private HTTPMethod GetMethod(string method) + private HttpMethod GetMethod(string method) { switch (method.ToLower()) { case "get": - return HTTPMethod.GET; + return HttpMethod.GET; case "post": - return HTTPMethod.POST; + return HttpMethod.POST; case "head": - return HTTPMethod.HEAD; + return HttpMethod.HEAD; case "put": - return HTTPMethod.PUT; + return HttpMethod.PUT; case "delete": - return HTTPMethod.DELETE; + return HttpMethod.DELETE; case "options": - return HTTPMethod.OPTIONS; + return HttpMethod.OPTIONS; case "trace": - return HTTPMethod.TRACE; + return HttpMethod.TRACE; case "connect": - return HTTPMethod.CONNECT; + return HttpMethod.CONNECT; default: - return HTTPMethod.UNKNOWN; + return HttpMethod.UNKNOWN; } } @@ -219,7 +219,7 @@ public class HTTPRequestPacket : Packet } // Post Content-Length - if (Method == HTTPMethod.POST) + if (Method == HttpMethod.POST) { try { diff --git a/Esiur/Net/Packets/HTTP/HTTPResponseCode.cs b/Esiur/Net/Packets/HTTP/HTTPResponseCode.cs index 676aaed..17a095d 100644 --- a/Esiur/Net/Packets/HTTP/HTTPResponseCode.cs +++ b/Esiur/Net/Packets/HTTP/HTTPResponseCode.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using System.Text; -namespace Esiur.Net.Packets.HTTP +namespace Esiur.Net.Packets.Http { - public enum HTTPResponseCode : int + public enum HttpResponseCode : int { Switching = 101, OK = 200, diff --git a/Esiur/Net/Packets/HTTP/HTTPResponsePacket.cs b/Esiur/Net/Packets/HTTP/HTTPResponsePacket.cs index 79a5795..4cf4d4d 100644 --- a/Esiur/Net/Packets/HTTP/HTTPResponsePacket.cs +++ b/Esiur/Net/Packets/HTTP/HTTPResponsePacket.cs @@ -28,18 +28,18 @@ using System.Text; using Esiur.Misc; using Esiur.Data; -namespace Esiur.Net.Packets.HTTP; -public class HTTPResponsePacket : Packet +namespace Esiur.Net.Packets.Http; +public class HttpResponsePacket : Packet { public StringKeyList Headers { get; } = new StringKeyList(true); public string Version { get; set; } = "HTTP/1.1"; public byte[] Message; - public HTTPResponseCode Number { get; set; } = HTTPResponseCode.OK; + public HttpResponseCode Number { get; set; } = HttpResponseCode.OK; public string Text; - public List Cookies { get; } = new List(); + public List Cookies { get; } = new List(); public bool Handled; public override string ToString() @@ -51,11 +51,11 @@ public class HTTPResponsePacket : Packet + "\n\tMessage: " + (Message != null ? Message.Length.ToString() : "NULL"); } - private string MakeHeader(HTTPComposeOption options) + private string MakeHeader(HttpComposeOption options) { string header = $"{Version} {(int)Number} {Text}\r\nServer: Esiur {Global.Version}\r\nDate: {DateTime.Now.ToUniversalTime().ToString("r")}\r\n"; - if (options == HTTPComposeOption.AllCalculateLength) + if (options == HttpComposeOption.AllCalculateLength) Headers["Content-Length"] = Message?.Length.ToString() ?? "0"; foreach (var kv in Headers) @@ -75,16 +75,16 @@ public class HTTPResponsePacket : Packet } - public bool Compose(HTTPComposeOption options) + public bool Compose(HttpComposeOption options) { List msg = new List(); - if (options != HTTPComposeOption.DataOnly) + if (options != HttpComposeOption.DataOnly) { msg.AddRange(Encoding.UTF8.GetBytes(MakeHeader(options))); } - if (options != HTTPComposeOption.SpecifiedHeadersOnly) + if (options != HttpComposeOption.SpecifiedHeadersOnly) { if (Message != null) msg.AddRange(Message); @@ -97,7 +97,7 @@ public class HTTPResponsePacket : Packet public override bool Compose() { - return Compose(HTTPComposeOption.AllDontCalculateLength); + return Compose(HttpComposeOption.AllDontCalculateLength); } public override long Parse(byte[] data, uint offset, uint ends) @@ -129,7 +129,7 @@ public class HTTPResponsePacket : Packet if (sMethod.Length == 3) { Version = sMethod[0].Trim(); - Number = (HTTPResponseCode)Convert.ToInt32(sMethod[1].Trim()); + Number = (HttpResponseCode)Convert.ToInt32(sMethod[1].Trim()); Text = sMethod[2]; } @@ -163,7 +163,7 @@ public class HTTPResponsePacket : Packet if (cookie.Length >= 1) { string[] splitCookie = cookie[0].Split('='); - HTTPCookie c = new HTTPCookie(splitCookie[0], splitCookie[1]); + HttpCookie c = new HttpCookie(splitCookie[0], splitCookie[1]); for (int j = 1; j < cookie.Length; j++) { diff --git a/Esiur/Net/Ppap/DeterministicGenerator.cs b/Esiur/Net/Ppap/DeterministicGenerator.cs new file mode 100644 index 0000000..3ada496 --- /dev/null +++ b/Esiur/Net/Ppap/DeterministicGenerator.cs @@ -0,0 +1,249 @@ +using Org.BouncyCastle.Crypto; +using Org.BouncyCastle.Crypto.Prng; +using Org.BouncyCastle.Security; +using System; +using System.Collections.Generic; +using System.Text; + +namespace Esiur.Net.Ppap +{ + public class DeterministicGenerator + : SecureRandom + { + private static long counter = DateTime.UtcNow.Ticks; + + public byte[] value; + + private static long NextCounterValue() + { + return Interlocked.Increment(ref counter); + } + + private static readonly SecureRandom MasterRandom = new SecureRandom(new CryptoApiRandomGenerator()); + internal static readonly SecureRandom ArbitraryRandom = new SecureRandom(new VmpcRandomGenerator(), 16); + + private static DigestRandomGenerator CreatePrng(string digestName, bool autoSeed) + { + IDigest digest = DigestUtilities.GetDigest(digestName); + if (digest == null) + return null; + DigestRandomGenerator prng = new DigestRandomGenerator(digest); + if (autoSeed) + { + AutoSeed(prng, 2 * digest.GetDigestSize()); + } + return prng; + } + + public static new byte[] GetNextBytes(SecureRandom secureRandom, int length) + { + byte[] result = new byte[length]; + secureRandom.NextBytes(result); + return result; + } + + public static new SecureRandom GetInstance(string algorithm) + { + return GetInstance(algorithm, true); + } + + public static new SecureRandom GetInstance(string algorithm, bool autoSeed) + { + if (algorithm == null) + throw new ArgumentNullException(nameof(algorithm)); + + if (algorithm.EndsWith("PRNG", StringComparison.OrdinalIgnoreCase)) + { + string digestName = algorithm.Substring(0, algorithm.Length - "PRNG".Length); + + DigestRandomGenerator prng = CreatePrng(digestName, autoSeed); + if (prng != null) + return new SecureRandom(prng); + } + + throw new ArgumentException("Unrecognised PRNG algorithm: " + algorithm, "algorithm"); + } + + protected new readonly IRandomGenerator generator; + + public DeterministicGenerator(byte[] value) + : this(CreatePrng("SHA256", true)) + { + this.value = value; + } + + public DeterministicGenerator(IRandomGenerator generator) + + { + this.generator = generator; + } + + public DeterministicGenerator(IRandomGenerator generator, int autoSeedLengthInBytes) + + { + AutoSeed(generator, autoSeedLengthInBytes); + + this.generator = generator; + } + + public override byte[] GenerateSeed(int length) + { + return GetNextBytes(MasterRandom, length); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER + public override void GenerateSeed(Span seed) + { + MasterRandom.NextBytes(seed); + } +#endif + + public override void SetSeed(byte[] seed) + { + generator.AddSeedMaterial(seed); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER + public override void SetSeed(Span seed) + { + generator.AddSeedMaterial(seed); + } +#endif + + public override void SetSeed(long seed) + { + generator.AddSeedMaterial(seed); + } + + public override int Next() + { + return NextInt() & int.MaxValue; + } + + public override int Next(int maxValue) + { + if (maxValue < 2) + { + if (maxValue < 0) + throw new ArgumentOutOfRangeException("maxValue", "cannot be negative"); + + return 0; + } + + int bits; + + // Test whether maxValue is a power of 2 + if ((maxValue & (maxValue - 1)) == 0) + { + bits = NextInt() & int.MaxValue; + return (int)(((long)bits * maxValue) >> 31); + } + + int result; + do + { + bits = NextInt() & int.MaxValue; + result = bits % maxValue; + } + while (bits - result + (maxValue - 1) < 0); // Ignore results near overflow + + return result; + } + + public override int Next(int minValue, int maxValue) + { + if (maxValue <= minValue) + { + if (maxValue == minValue) + return minValue; + + throw new ArgumentException("maxValue cannot be less than minValue"); + } + + int diff = maxValue - minValue; + if (diff > 0) + return minValue + Next(diff); + + for (; ; ) + { + int i = NextInt(); + + if (i >= minValue && i < maxValue) + return i; + } + } + + public override void NextBytes(byte[] buf) + { + Buffer.BlockCopy(value, 0, buf, 0, buf.Length); + } + + public override void NextBytes(byte[] buf, int off, int len) + { + Buffer.BlockCopy(value, 0, buf, off, len); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER + public override void NextBytes(Span buffer) + { + if (generator != null) + { + generator.NextBytes(buffer); + } + else + { + byte[] tmp = new byte[buffer.Length]; + NextBytes(tmp); + tmp.CopyTo(buffer); + } + } +#endif + + private static readonly double DoubleScale = 1.0 / Convert.ToDouble(1L << 53); + + public override double NextDouble() + { + ulong x = (ulong)NextLong() >> 11; + + return Convert.ToDouble(x) * DoubleScale; + } + + public override int NextInt() + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER + Span bytes = stackalloc byte[4]; +#else + byte[] bytes = new byte[4]; +#endif + NextBytes(bytes); + return (int)0; + } + + public override long NextLong() + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER + Span bytes = stackalloc byte[8]; +#else + byte[] bytes = new byte[8]; +#endif + NextBytes(bytes); + return (long)0; + } + + private static void AutoSeed(IRandomGenerator generator, int seedLength) + { + generator.AddSeedMaterial(NextCounterValue()); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER + Span seed = seedLength <= 128 + ? stackalloc byte[seedLength] + : new byte[seedLength]; +#else + byte[] seed = new byte[seedLength]; +#endif + MasterRandom.NextBytes(seed); + generator.AddSeedMaterial(seed); + } + } + +} diff --git a/Esiur/Net/Ppap/KeyGenerator.cs b/Esiur/Net/Ppap/KeyGenerator.cs new file mode 100644 index 0000000..594508f --- /dev/null +++ b/Esiur/Net/Ppap/KeyGenerator.cs @@ -0,0 +1,61 @@ +using Org.BouncyCastle.Crypto.Generators; +using Org.BouncyCastle.Crypto.Parameters; +using System; +using System.Collections.Generic; +using System.Text; + +namespace Esiur.Net.Ppap +{ + internal class KeyGenerator + { + public static (byte[], byte[]) Gen(MLKemParameters parameters = null) + { + var random = new RandomGenerator(); + var keyGenParameters = new MLKemKeyGenerationParameters(random, parameters ?? MLKemParameters.ml_kem_768); + + var kyberKeyPairGenerator = new MLKemKeyPairGenerator(); + kyberKeyPairGenerator.Init(keyGenParameters); + + var keys = kyberKeyPairGenerator.GenerateKeyPair(); + return ((keys.Private as MLKemPrivateKeyParameters).GetEncoded(), + (keys.Public as MLKemPublicKeyParameters).GetEncoded()); + } + + + public static (byte[], byte[]) GenS(byte[] username, byte[] password, byte[] registrationNonce, Argon2Parameters argon2parameters = null, MLKemParameters mlkemParameters = null) + { + + var secret = new byte[username.Length + password.Length + registrationNonce.Length]; + Buffer.BlockCopy(username, 0, secret, 0, username.Length); + Buffer.BlockCopy(password, 0, secret, username.Length, password.Length); + Buffer.BlockCopy(registrationNonce, 0, secret, username.Length + password.Length, registrationNonce.Length); + + var output = new byte[64]; + //Argon2id.DeriveKey(output, secret, registrationNonce, ArgonIterations, ArgonMemory * 1024); + + var argon2 = new Argon2BytesGenerator(); + var argon2params = argon2parameters ?? new Argon2Parameters.Builder(Argon2Parameters.Argon2id) + .WithSalt(registrationNonce) + .WithMemoryAsKB(1024 * 10) + .WithIterations(3) + .WithParallelism(1) + .Build(); + + argon2.Init(argon2params); + var output2 = new byte[64]; + argon2.GenerateBytes(secret, output); + + + var random = new DeterministicGenerator(output); + var keyGenParameters = new MLKemKeyGenerationParameters(random, mlkemParameters ?? MLKemParameters.ml_kem_768); + + var kyberKeyPairGenerator = new MLKemKeyPairGenerator(); + kyberKeyPairGenerator.Init(keyGenParameters); + + var keys = kyberKeyPairGenerator.GenerateKeyPair(); + return ((keys.Private as MLKemPrivateKeyParameters).GetEncoded(), + (keys.Public as MLKemPublicKeyParameters).GetEncoded()); + + } + } +} diff --git a/Esiur/Net/Ppap/RandomGenerator.cs b/Esiur/Net/Ppap/RandomGenerator.cs new file mode 100644 index 0000000..775e197 --- /dev/null +++ b/Esiur/Net/Ppap/RandomGenerator.cs @@ -0,0 +1,247 @@ +using Org.BouncyCastle.Crypto; +using Org.BouncyCastle.Crypto.Prng; +using Org.BouncyCastle.Security; +using System; +using System.Collections.Generic; +using System.Text; + +namespace Esiur.Net.Ppap +{ + public class RandomGenerator + : SecureRandom + { + private static long counter = DateTime.UtcNow.Ticks; + + private static long NextCounterValue() + { + return Interlocked.Increment(ref counter); + } + + private static readonly SecureRandom MasterRandom = new SecureRandom(new CryptoApiRandomGenerator()); + internal static readonly SecureRandom ArbitraryRandom = new SecureRandom(new VmpcRandomGenerator(), 16); + + private static DigestRandomGenerator CreatePrng(string digestName, bool autoSeed) + { + IDigest digest = DigestUtilities.GetDigest(digestName); + if (digest == null) + return null; + DigestRandomGenerator prng = new DigestRandomGenerator(digest); + if (autoSeed) + { + AutoSeed(prng, 2 * digest.GetDigestSize()); + } + return prng; + } + + public static new byte[] GetNextBytes(SecureRandom secureRandom, int length) + { + byte[] result = new byte[length]; + secureRandom.NextBytes(result); + return result; + } + + public static new SecureRandom GetInstance(string algorithm) + { + return GetInstance(algorithm, true); + } + + public static new SecureRandom GetInstance(string algorithm, bool autoSeed) + { + if (algorithm == null) + throw new ArgumentNullException(nameof(algorithm)); + + if (algorithm.EndsWith("PRNG", StringComparison.OrdinalIgnoreCase)) + { + string digestName = algorithm.Substring(0, algorithm.Length - "PRNG".Length); + + DigestRandomGenerator prng = CreatePrng(digestName, autoSeed); + if (prng != null) + return new SecureRandom(prng); + } + + throw new ArgumentException("Unrecognised PRNG algorithm: " + algorithm, "algorithm"); + } + + protected new readonly IRandomGenerator generator; + + public RandomGenerator() + : this(CreatePrng("SHA256", true)) + { + + } + + public RandomGenerator(IRandomGenerator generator) + + { + this.generator = generator; + } + + public RandomGenerator(IRandomGenerator generator, int autoSeedLengthInBytes) + + { + AutoSeed(generator, autoSeedLengthInBytes); + + this.generator = generator; + } + + public override byte[] GenerateSeed(int length) + { + return GetNextBytes(MasterRandom, length); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER + public override void GenerateSeed(Span seed) + { + MasterRandom.NextBytes(seed); + } +#endif + + public override void SetSeed(byte[] seed) + { + generator.AddSeedMaterial(seed); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER + public override void SetSeed(Span seed) + { + generator.AddSeedMaterial(seed); + } +#endif + + public override void SetSeed(long seed) + { + generator.AddSeedMaterial(seed); + } + + public override int Next() + { + return NextInt() & int.MaxValue; + } + + public override int Next(int maxValue) + { + if (maxValue < 2) + { + if (maxValue < 0) + throw new ArgumentOutOfRangeException("maxValue", "cannot be negative"); + + return 0; + } + + int bits; + + // Test whether maxValue is a power of 2 + if ((maxValue & (maxValue - 1)) == 0) + { + bits = NextInt() & int.MaxValue; + return (int)(((long)bits * maxValue) >> 31); + } + + int result; + do + { + bits = NextInt() & int.MaxValue; + result = bits % maxValue; + } + while (bits - result + (maxValue - 1) < 0); // Ignore results near overflow + + return result; + } + + public override int Next(int minValue, int maxValue) + { + if (maxValue <= minValue) + { + if (maxValue == minValue) + return minValue; + + throw new ArgumentException("maxValue cannot be less than minValue"); + } + + int diff = maxValue - minValue; + if (diff > 0) + return minValue + Next(diff); + + for (; ; ) + { + int i = NextInt(); + + if (i >= minValue && i < maxValue) + return i; + } + } + + public override void NextBytes(byte[] buf) + { + generator.NextBytes(buf); + } + + public override void NextBytes(byte[] buf, int off, int len) + { + generator.NextBytes(buf, off, len); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER + public override void NextBytes(Span buffer) + { + if (generator != null) + { + generator.NextBytes(buffer); + } + else + { + byte[] tmp = new byte[buffer.Length]; + NextBytes(tmp); + tmp.CopyTo(buffer); + } + } +#endif + + private static readonly double DoubleScale = 1.0 / Convert.ToDouble(1L << 53); + + public override double NextDouble() + { + ulong x = (ulong)NextLong() >> 11; + + return Convert.ToDouble(x) * DoubleScale; + } + + public override int NextInt() + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER + Span bytes = stackalloc byte[4]; +#else + byte[] bytes = new byte[4]; +#endif + NextBytes(bytes); + return (int)0; + } + + public override long NextLong() + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER + Span bytes = stackalloc byte[8]; +#else + byte[] bytes = new byte[8]; +#endif + NextBytes(bytes); + return (long)0; + } + + private static void AutoSeed(IRandomGenerator generator, int seedLength) + { + generator.AddSeedMaterial(NextCounterValue()); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER + Span seed = seedLength <= 128 + ? stackalloc byte[seedLength] + : new byte[seedLength]; +#else + byte[] seed = new byte[seedLength]; +#endif + MasterRandom.NextBytes(seed); + generator.AddSeedMaterial(seed); + } + } + +} diff --git a/Esiur/Net/TCP/TCPConnection.cs b/Esiur/Net/TCP/TCPConnection.cs index 67689db..6365a6a 100644 --- a/Esiur/Net/TCP/TCPConnection.cs +++ b/Esiur/Net/TCP/TCPConnection.cs @@ -32,13 +32,13 @@ using System.Collections; using Esiur.Misc; using Esiur.Data; -namespace Esiur.Net.TCP; -public class TCPConnection : NetworkConnection +namespace Esiur.Net.Tcp; +public class TcpConnection : NetworkConnection { private KeyList variables = new KeyList(); - public TCPServer Server { get; internal set; } + public TcpServer Server { get; internal set; } public KeyList Variables { diff --git a/Esiur/Net/TCP/TCPFilter.cs b/Esiur/Net/TCP/TCPFilter.cs index 591bb5e..78a6fb9 100644 --- a/Esiur/Net/TCP/TCPFilter.cs +++ b/Esiur/Net/TCP/TCPFilter.cs @@ -32,9 +32,9 @@ using Esiur.Net.Sockets; using Esiur.Core; using Esiur.Resource; -namespace Esiur.Net.TCP; +namespace Esiur.Net.Tcp; -public abstract class TCPFilter : IResource +public abstract class TcpFilter : IResource { public Instance Instance @@ -48,17 +48,17 @@ public abstract class TCPFilter : IResource public abstract AsyncReply Trigger(ResourceTrigger trigger); - public virtual bool Connected(TCPConnection sender) + public virtual bool Connected(TcpConnection sender) { return false; } - public virtual bool Disconnected(TCPConnection sender) + public virtual bool Disconnected(TcpConnection sender) { return false; } - public abstract bool Execute(byte[] msg, NetworkBuffer data, TCPConnection sender); + public abstract bool Execute(byte[] msg, NetworkBuffer data, TcpConnection sender); public void Destroy() { diff --git a/Esiur/Net/TCP/TCPServer.cs b/Esiur/Net/TCP/TCPServer.cs index 26bb372..b95ad6d 100644 --- a/Esiur/Net/TCP/TCPServer.cs +++ b/Esiur/Net/TCP/TCPServer.cs @@ -34,8 +34,8 @@ using Esiur.Core; using System.Net; using Esiur.Resource; -namespace Esiur.Net.TCP; -public class TCPServer : NetworkServer, IResource +namespace Esiur.Net.Tcp; +public class TcpServer : NetworkServer, IResource { [Attribute] @@ -64,7 +64,7 @@ public class TCPServer : NetworkServer, IResource //} public Instance Instance { get; set; } - TCPFilter[] filters = null; + TcpFilter[] filters = null; public AsyncReply Trigger(ResourceTrigger trigger) { @@ -93,7 +93,7 @@ public class TCPServer : NetworkServer, IResource } else if (trigger == ResourceTrigger.SystemInitialized) { - Instance.Children().Then(x => filters = x); + Instance.Children().Then(x => filters = x); } return new AsyncReply(true); @@ -103,7 +103,7 @@ public class TCPServer : NetworkServer, IResource - internal bool Execute(TCPConnection sender, NetworkBuffer data) + internal bool Execute(TcpConnection sender, NetworkBuffer data) { if (filters == null) @@ -120,12 +120,12 @@ public class TCPServer : NetworkServer, IResource return false; } - private void SessionModified(TCPConnection session, string key, object newValue) + private void SessionModified(TcpConnection session, string key, object newValue) { } - protected override void ClientDisconnected(TCPConnection connection) + protected override void ClientDisconnected(TcpConnection connection) { if (filters == null) return; @@ -136,19 +136,19 @@ public class TCPServer : NetworkServer, IResource } } - public override void Add(TCPConnection connection) + public override void Add(TcpConnection connection) { connection.Server = this; base.Add(connection); } - public override void Remove(TCPConnection connection) + public override void Remove(TcpConnection connection) { connection.Server = null; base.Remove(connection); } - protected override void ClientConnected(TCPConnection connection) + protected override void ClientConnected(TcpConnection connection) { if (filters == null) return; diff --git a/Esiur/Net/TCP/TCPSession.cs b/Esiur/Net/TCP/TCPSession.cs index 3a4412d..5c7a99c 100644 --- a/Esiur/Net/TCP/TCPSession.cs +++ b/Esiur/Net/TCP/TCPSession.cs @@ -28,8 +28,8 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace Esiur.Net.TCP; -public class TCPSession : NetworkSession +namespace Esiur.Net.Tcp; +public class TcpSession : NetworkSession { } diff --git a/Esiur/Net/UDP/UDPFilter.cs b/Esiur/Net/UDP/UDPFilter.cs index b1ef087..4d7c226 100644 --- a/Esiur/Net/UDP/UDPFilter.cs +++ b/Esiur/Net/UDP/UDPFilter.cs @@ -33,7 +33,7 @@ using Esiur.Core; using Esiur.Resource; namespace Esiur.Net.UDP; -public abstract class UDPFilter : IResource +public abstract class UdpFilter : IResource { diff --git a/Esiur/Net/UDP/UDPServer.cs b/Esiur/Net/UDP/UDPServer.cs index 8fb1357..2d5c73c 100644 --- a/Esiur/Net/UDP/UDPServer.cs +++ b/Esiur/Net/UDP/UDPServer.cs @@ -40,11 +40,11 @@ namespace Esiur.Net.UDP; public EndPoint SenderPoint; public }*/ -public class UDPServer : IResource +public class UdpServer : IResource { Thread receiver; UdpClient udp; - UDPFilter[] filters = new UDPFilter[0]; + UdpFilter[] filters = new UdpFilter[0]; public event DestroyedEvent OnDestroy; @@ -80,7 +80,7 @@ public class UDPServer : IResource foreach (var child in filters) { - var f = child as UDPFilter; + var f = child as UdpFilter; try { @@ -195,7 +195,7 @@ public class UDPServer : IResource } else if (trigger == ResourceTrigger.SystemInitialized) { - filters = await Instance.Children(); + filters = await Instance.Children(); } return true; diff --git a/Esiur/Protocol/Authentication/HashAnonymousAuthenticator.cs b/Esiur/Protocol/Authentication/HashAnonymousAuthenticator.cs new file mode 100644 index 0000000..d685668 --- /dev/null +++ b/Esiur/Protocol/Authentication/HashAnonymousAuthenticator.cs @@ -0,0 +1,20 @@ +using Esiur.Security.Authority; +using System; +using System.Collections.Generic; +using System.Text; + +namespace Esiur.Protocol.Authentication +{ + public class HashAnonymousAuthenticator : IAuthenticationHandler + { + public AuthenticationResult Initiate(Session session) + { + throw new NotImplementedException(); + } + + public AuthenticationResult Process(object handshakePayload) + { + throw new NotImplementedException(); + } + } +} diff --git a/Esiur/Protocol/EpConnection.cs b/Esiur/Protocol/EpConnection.cs index 3e58eb3..9d40eb7 100644 --- a/Esiur/Protocol/EpConnection.cs +++ b/Esiur/Protocol/EpConnection.cs @@ -27,12 +27,13 @@ using Esiur.Data; using Esiur.Data.Types; using Esiur.Misc; using Esiur.Net; -using Esiur.Net.HTTP; +using Esiur.Net.Http; using Esiur.Net.Packets; -using Esiur.Net.Packets.HTTP; +using Esiur.Net.Packets.Http; using Esiur.Net.Sockets; using Esiur.Resource; using Esiur.Security.Authority; +using Esiur.Security.Cryptography; using Esiur.Security.Membership; using Microsoft.CodeAnalysis.CSharp.Syntax; using System; @@ -41,11 +42,13 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using System.Net; using System.Net.Sockets; +using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using System.Timers; +using static System.Collections.Specialized.BitVector32; namespace Esiur.Protocol; @@ -53,9 +56,9 @@ public partial class EpConnection : NetworkConnection, IStore { - public delegate void ProtocolGeneralHandler(EpConnection connection, ParsedTDU dataType, byte[] data); + public delegate void ProtocolGeneralHandler(EpConnection connection, ParsedTdu dataType, byte[] data); - public delegate void ProtocolRequestReplyHandler(EpConnection connection, uint callbackId, ParsedTDU dataType, byte[] data); + public delegate void ProtocolRequestReplyHandler(EpConnection connection, uint callbackId, ParsedTdu dataType, byte[] data); // Delegates public delegate void ReadyEvent(EpConnection sender); @@ -96,13 +99,15 @@ public partial class EpConnection : NetworkConnection, IStore AsyncReply openReply; - byte[] localPasswordOrToken; - bool ready, readyToEstablish; + + //byte[] localPasswordOrToken; + bool authenticated, readyToEstablish; string _hostname; ushort _port; bool initialPacket = true; + bool isInitiator = false; // Properties @@ -135,8 +140,8 @@ public partial class EpConnection : NetworkConnection, IStore public ExceptionLevel ExceptionLevel { get; set; } = ExceptionLevel.Code | ExceptionLevel.Message | ExceptionLevel.Source | ExceptionLevel.Trace; - [Attribute] - public Func> Authenticator { get; set; } + //[Attribute] + //public Func> Authenticator { get; set; } [Attribute] @@ -145,8 +150,8 @@ public partial class EpConnection : NetworkConnection, IStore [Attribute] public uint ReconnectInterval { get; set; } = 5; - [Attribute] - public string Username { get; set; } + //[Attribute] + //public string Username { get; set; } [Attribute] public bool UseWebSocket { get; set; } @@ -154,14 +159,14 @@ public partial class EpConnection : NetworkConnection, IStore [Attribute] public bool SecureWebSocket { get; set; } - [Attribute] - public string Password { get; set; } + //[Attribute] + //public string Password { get; set; } - [Attribute] - public string Token { get; set; } + //[Attribute] + //public string Token { get; set; } - [Attribute] - public ulong TokenIndex { get; set; } + //[Attribute] + //public ulong TokenIndex { get; set; } [Attribute] public string Domain { get; set; } @@ -218,10 +223,11 @@ public partial class EpConnection : NetworkConnection, IStore { base.Assign(socket); - session.LocalHeaders[EpAuthPacketHeader.IPAddress] = socket.RemoteEndPoint.Address.GetAddressBytes(); + session.LocalHeaders[EpAuthPacketHeader.IPAddress] + = socket.RemoteEndPoint.Address.GetAddressBytes(); if (socket.State == SocketState.Established && - session.AuthenticationType == AuthenticationType.Client) + isInitiator) { Declare(); } @@ -229,56 +235,40 @@ public partial class EpConnection : NetworkConnection, IStore private void Declare() { + //if (session.KeyExchanger != null) + //{ + // // create key + // var key = session.KeyExchanger.GetPublicKey(); + // session.LocalHeaders[EpAuthPacketHeader.CipherKey] = key; + //} - if (session.KeyExchanger != null) + + if (!isInitiator) + return; + + if (session.AuthenticationMode != AuthenticationMode.None) { - // create key - var key = session.KeyExchanger.GetPublicKey(); - session.LocalHeaders[EpAuthPacketHeader.CipherKey] = key; + if (session.AuthenticationHandler == null) + throw new Exception("Authentication handler must be assigned for the session."); + + var initAuthData = session.AuthenticationHandler.Initialize(session); + + session.LocalHeaders.Add(EpAuthPacketHeader.AuthenticationData, initAuthData); } - - if (session.LocalMethod == AuthenticationMethod.Credentials - && session.RemoteMethod == AuthenticationMethod.None) + if (session.EncryptionMode != EncryptionMode.None) { - // change to Map for compatibility - var headers = Codec.Compose(session.LocalHeaders.Select(x => new KeyValuePair((byte)x.Key, x.Value)), this.Instance.Warehouse, this); - - // declare (Credentials -> No Auth, No Enctypt) - SendParams() - .AddUInt8((byte)EpAuthPacketInitialize.CredentialsNoAuth) - .AddUInt8Array(headers) - .Done(); - - } - else if (session.LocalMethod == AuthenticationMethod.Token - && session.RemoteMethod == AuthenticationMethod.None) - { - // change to Map for compatibility - var headers = Codec.Compose(session.LocalHeaders.Select(x => new KeyValuePair((byte)x.Key, x.Value)), this.Instance.Warehouse, this); - - SendParams() - .AddUInt8((byte)EpAuthPacketInitialize.TokenNoAuth) - .AddUInt8Array(headers) - .Done(); - } - else if (session.LocalMethod == AuthenticationMethod.None - && session.RemoteMethod == AuthenticationMethod.None) - { - // change to Map for compatibility - var headers = Codec.Compose(session.LocalHeaders.Select(x => new KeyValuePair((byte)x.Key, x.Value)), this.Instance.Warehouse, this); - - // @REVIEW: MITM Attack can still occur - SendParams() - .AddUInt8((byte)EpAuthPacketInitialize.NoAuthNoAuth) - .AddUInt8Array(headers) - .Done(); - } - else - { - throw new NotImplementedException("Authentication method is not implemented."); + // get the handler } + // change to Map for compatibility + var headers = Codec.Compose(session.LocalHeaders.Select(x => new KeyValuePair((byte)x.Key, x.Value)), this.Instance.Warehouse, this); + + SendParams() + .AddUInt8((byte)(0x20 | ((byte)session.AuthenticationMode << 2) + | (byte)session.EncryptionMode)) + .AddUInt8Array(headers) + .Done(); } /// @@ -288,50 +278,52 @@ public partial class EpConnection : NetworkConnection, IStore /// Working domain. /// Username. /// Password. - public EpConnection(ISocket socket, string domain, string username, string password) + public EpConnection(ISocket socket, IAuthenticationHandler authenticationInitiator, Map headers) { this.session = new Session(); - session.AuthenticationType = AuthenticationType.Client; - session.LocalHeaders[EpAuthPacketHeader.Domain] = domain; - session.LocalHeaders[EpAuthPacketHeader.Username] = username; - session.LocalMethod = AuthenticationMethod.Credentials; - session.RemoteMethod = AuthenticationMethod.None; + //if (authenticationHandler.Type != AuthenticationType.Initiator) + // throw new Exception("" + session.AuthenticationType = AuthenticationMode.Initiator; + session.LocalHeaders = headers; + session.AuthenticationInitiator = authenticationInitiator; - this.localPasswordOrToken = DC.ToBytes(password); + //this.localPasswordOrToken = DC.ToBytes(password); init(); Assign(socket); } - public EpConnection(ISocket socket, string domain, ulong tokenIndex, string token) - { - this.session = new Session(); + //public EpConnection(ISocket socket, string domain, ulong tokenIndex, string token) + //{ + // this.session = new Session(); - session.AuthenticationType = AuthenticationType.Client; - session.LocalHeaders[EpAuthPacketHeader.Domain] = domain; - session.LocalHeaders[EpAuthPacketHeader.TokenIndex] = tokenIndex; - session.LocalMethod = AuthenticationMethod.Credentials; - session.RemoteMethod = AuthenticationMethod.None; - this.localPasswordOrToken = DC.ToBytes(token); + // session.AuthenticationType = AuthenticationType.Client; + // session.LocalHeaders[EpAuthPacketHeader.Domain] = domain; + // session.LocalHeaders[EpAuthPacketHeader.TokenIndex] = tokenIndex; + // session.LocalMethod = AuthenticationMethod.Credentials; + // session.RemoteMethod = AuthenticationMethod.None; + // this.localPasswordOrToken = DC.ToBytes(token); - init(); + // init(); - Assign(socket); - } + // Assign(socket); + //} /// /// Create a new instance of a distributed connection /// - public EpConnection() + public EpConnection(IAuthenticationHandler authenticationResponder) { session = new Session(); - session.AuthenticationType = AuthenticationType.Host; - session.LocalMethod = AuthenticationMethod.None; + session.AuthenticationType = AuthenticationMode.Responder; + session.AuthenticationResponder = authenticationResponder; + + authenticationResponder.Initiate(session); init(); } @@ -350,7 +342,7 @@ public partial class EpConnection : NetworkConnection, IStore } - public List> GetFinishedQueue() + public List> GetFinishedQueue() { var l = queue.Processed.ToArray().ToList(); queue.Processed.Clear(); @@ -374,7 +366,7 @@ public partial class EpConnection : NetworkConnection, IStore }); // set local nonce - session.LocalHeaders[EpAuthPacketHeader.Nonce] = Global.GenerateBytes(32); + //session.LocalHeaders[EpAuthPacketHeader.Nonce] = Global.GenerateBytes(32); keepAliveTimer = new System.Timers.Timer(KeepAliveInterval * 1000); keepAliveTimer.Elapsed += KeepAliveTimer_Elapsed; ; @@ -398,7 +390,7 @@ public partial class EpConnection : NetworkConnection, IStore SendRequest(EpPacketRequest.KeepAlive, now, interval) .Then(x => { - Jitter =Convert.ToUInt32(((object[])x)[1]); + Jitter = Convert.ToUInt32(((object[])x)[1]); keepAliveTimer.Start(); }).Error(ex => { @@ -425,7 +417,7 @@ public partial class EpConnection : NetworkConnection, IStore private uint processPacket(byte[] msg, uint offset, uint ends, NetworkBuffer data, int chunkId) { - if (ready) + if (authenticated) { var rt = packet.Parse(msg, offset, ends); @@ -440,7 +432,7 @@ public partial class EpConnection : NetworkConnection, IStore offset += (uint)rt; - if (packet.DataType == null) + if (packet.Tdu == null) return offset; //Console.WriteLine("Incoming: " + packet + " " + packet.CallbackId); @@ -448,7 +440,7 @@ public partial class EpConnection : NetworkConnection, IStore if (packet.Method == EpPacketMethod.Notification) { - var dt = packet.DataType.Value; + var dt = packet.Tdu.Value; switch (packet.Notification) { @@ -476,7 +468,7 @@ public partial class EpConnection : NetworkConnection, IStore } else if (packet.Method == EpPacketMethod.Request) { - var dt = packet.DataType.Value; + var dt = packet.Tdu.Value; switch (packet.Request) { @@ -548,7 +540,7 @@ public partial class EpConnection : NetworkConnection, IStore } else if (packet.Method == EpPacketMethod.Reply) { - var dt = packet.DataType.Value; + var dt = packet.Tdu.Value; switch (packet.Reply) { @@ -581,15 +573,13 @@ public partial class EpConnection : NetworkConnection, IStore } else if (packet.Method == EpPacketMethod.Extension) { - EpExtensionAction(packet.Extension, packet.DataType, msg); + EpExtensionAction(packet.Extension, packet.Tdu, msg); } } } else { - // check if the request through Websockets - if (initialPacket) { initialPacket = false; @@ -597,22 +587,22 @@ public partial class EpConnection : NetworkConnection, IStore if (msg.Length > 3 && Encoding.Default.GetString(msg, 0, 3) == "GET") { // Parse with http packet - var req = new HTTPRequestPacket(); + var req = new HttpRequestPacket(); var pSize = req.Parse(msg, 0, (uint)msg.Length); if (pSize > 0) { // check for WS upgrade - if (HTTPConnection.IsWebsocketRequest(req)) + if (HttpConnection.IsWebsocketRequest(req)) { Socket?.Unhold(); - var res = new HTTPResponsePacket(); + var res = new HttpResponsePacket(); - HTTPConnection.Upgrade(req, res); + HttpConnection.Upgrade(req, res); - res.Compose(HTTPComposeOption.AllCalculateLength); + res.Compose(HttpComposeOption.AllCalculateLength); Send(res.Data); // replace my socket with websockets var tcpSocket = this.Unassign(); @@ -622,9 +612,9 @@ public partial class EpConnection : NetworkConnection, IStore else { - var res = new HTTPResponsePacket(); - res.Number = HTTPResponseCode.BadRequest; - res.Compose(HTTPComposeOption.AllCalculateLength); + var res = new HttpResponsePacket(); + res.Number = HttpResponseCode.BadRequest; + res.Compose(HttpComposeOption.AllCalculateLength); Send(res.Data); //@TODO: kill the connection } @@ -651,712 +641,787 @@ public partial class EpConnection : NetworkConnection, IStore { offset += (uint)rt; - if (session.AuthenticationType == AuthenticationType.Host) + if (session.AuthenticationMethod == AuthenticationMethod.None) { - ProcessHostAuth(msg); + // establish session without authentication } - else if (session.AuthenticationType == AuthenticationType.Client) + + if (session.AuthenticationHandler == null) { - ProcessClientAuth(msg); + throw new Exception("No authentication handler assigned for the session."); } + + try + { + var result = session.AuthenticationHandler.Process(authPacket); + if (result.Ruling == AuthenticationRuling.Succeeded) + { + if (this.Instance == null) + { + Server.Instance.Warehouse.Put( + Server.Instance.Link + "/" + this.GetHashCode().ToString().Replace("/", "_"), this) + .Then(x => + { + session.AuthorizedIdentity = result.Identity; + + authenticated = true; + Status = EpConnectionStatus.Connected; + openReply?.Trigger(true); + openReply = null; + OnReady?.Invoke(this); + + Server?.Membership?.Login(session); + LoginDate = DateTime.Now; + + }).Error(x => + { + openReply?.TriggerError(x); + openReply = null; + }); + } + else + { + session.AuthorizedIdentity = result.Identity; + authenticated = true; + Status = EpConnectionStatus.Connected; + openReply?.Trigger(true); + openReply = null; + OnReady?.Invoke(this); + Server?.Membership?.Login(session); + } + } + else if (result.Ruling == AuthenticationRuling.InProgress) + { + SendParams() + .AddUInt8((byte)EpAuthPacketCommand.Acknowledge) + .AddUInt8Array(Codec.Compose( + result.HandshakePayload + , this.Instance.Warehouse, this)) + .Done(); + + } + else if (result.Ruling == AuthenticationRuling.Failed) + { + // Send the server side error + SendParams() + .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) + .AddUInt8Array(Codec.Compose( + new object[] {(ushort)result.ExceptionCode, + result.ExceptionMessage } + , this.Instance.Warehouse, this)) + .Done(); + } + } + catch (Exception ex) + { + // Send the server side error + SendParams() + .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) + .AddUInt8Array(Codec.Compose( + new object[] { (ushort)ExceptionCode.GeneralFailure, + ex.Message } + , this.Instance.Warehouse, this)) + .Done(); + } + } } return offset; } - private void ProcessClientAuth(byte[] data) - { - if (authPacket.Command == EpAuthPacketCommand.Acknowledge) - { - // if there is a mismatch in authentication - if (session.LocalMethod != authPacket.RemoteMethod - || session.RemoteMethod != authPacket.LocalMethod) - { - openReply?.TriggerError(new Exception("Peer refused authentication method.")); - openReply = null; - } - - // Parse remote headers - - var dataType = authPacket.DataType.Value; - - var (_, parsed) = Codec.ParseSync(dataType, Instance.Warehouse); - - var rt = (Map)parsed; - - session.RemoteHeaders = rt.Select(x => new KeyValuePair((EpAuthPacketHeader)x.Key, x.Value)); - - if (session.LocalMethod == AuthenticationMethod.None) - { - // send establish - SendParams() - .AddUInt8((byte)EpAuthPacketAction.EstablishNewSession) - .Done(); - } - else if (session.LocalMethod == AuthenticationMethod.Credentials - || session.LocalMethod == AuthenticationMethod.Token) - { - var remoteNonce = (byte[])session.RemoteHeaders[EpAuthPacketHeader.Nonce]; - var localNonce = (byte[])session.LocalHeaders[EpAuthPacketHeader.Nonce]; - - // send our hash - var hashFunc = SHA256.Create(); - // local nonce + password or token + remote nonce - var challenge = hashFunc.ComputeHash(new BinaryList() - .AddUInt8Array(localNonce) - .AddUInt8Array(localPasswordOrToken) - .AddUInt8Array(remoteNonce) - .ToArray()); - - SendParams() - .AddUInt8((byte)EpAuthPacketAction.AuthenticateHash) - .AddUInt8((byte)EpAuthPacketHashAlgorithm.SHA256) - .AddUInt16((ushort)challenge.Length) - .AddUInt8Array(challenge) - .Done(); - } - - } - else if (authPacket.Command == EpAuthPacketCommand.Action) - { - if (authPacket.Action == EpAuthPacketAction.AuthenticateHash) - { - var remoteNonce = (byte[])session.RemoteHeaders[EpAuthPacketHeader.Nonce]; - var localNonce = (byte[])session.LocalHeaders[EpAuthPacketHeader.Nonce]; - - // check if the server knows my password - var hashFunc = SHA256.Create(); - - var challenge = hashFunc.ComputeHash(new BinaryList() - .AddUInt8Array(remoteNonce) - .AddUInt8Array(localPasswordOrToken) - .AddUInt8Array(localNonce) - .ToArray()); - - - if (challenge.SequenceEqual(authPacket.Challenge)) - { - // send establish request - SendParams() - .AddUInt8((byte)EpAuthPacketAction.EstablishNewSession) - .Done(); - } - else - { - SendParams() - .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) - .AddUInt8((byte)ExceptionCode.ChallengeFailed) - .AddUInt16(16) - .AddString("Challenge Failed") - .Done(); - - } - } - } - else if (authPacket.Command == EpAuthPacketCommand.Event) - { - if (authPacket.Event == EpAuthPacketEvent.ErrorTerminate - || authPacket.Event == EpAuthPacketEvent.ErrorMustEncrypt - || authPacket.Event == EpAuthPacketEvent.ErrorRetry) - { - invalidCredentials = true; - openReply?.TriggerError(new AsyncException(ErrorType.Management, authPacket.ErrorCode, authPacket.Message)); - openReply = null; - OnError?.Invoke(this, authPacket.ErrorCode, authPacket.Message); - Close(); - } - else if (authPacket.Event == EpAuthPacketEvent.IndicationEstablished) - { - session.Id = authPacket.SessionId; - session.AuthorizedAccount = authPacket.AccountId.GetString(0, (uint)authPacket.AccountId.Length); - - ready = true; - Status = EpConnectionStatus.Connected; - - - // put it in the warehouse - - if (this.Instance == null) - { - Server.Instance.Warehouse.Put(Server + "/" + session.AuthorizedAccount.Replace("/", "_"), this) - .Then(x => - { - openReply?.Trigger(true); - OnReady?.Invoke(this); - openReply = null; - - - }).Error(x => - { - openReply?.TriggerError(x); - openReply = null; - }); - } - else - { - openReply?.Trigger(true); - openReply = null; - - OnReady?.Invoke(this); - } - - // start perodic keep alive timer - keepAliveTimer.Start(); - - } - else if (authPacket.Event == EpAuthPacketEvent.IAuthPlain) - { - var dataType = authPacket.DataType.Value; - var (_, parsed) = Codec.ParseSync(dataType, Instance.Warehouse); - var rt = (Map)parsed; - - var headers = rt.Select(x => new KeyValuePair((EpAuthPacketIAuthHeader)x.Key, x.Value)); - var iAuthRequest = new AuthorizationRequest(headers); - - if (Authenticator == null) - { - SendParams() - .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) - .AddUInt8((byte)ExceptionCode.NotSupported) - .AddUInt16(13) - .AddString("Not supported") - .Done(); - } - else - { - Authenticator(iAuthRequest).Then(response => - { - SendParams() - .AddUInt8((byte)EpAuthPacketAction.IAuthPlain) - .AddUInt32((uint)headers[EpAuthPacketIAuthHeader.Reference]) - .AddUInt8Array(Codec.Compose(response, this.Instance.Warehouse, this)) - .Done(); - }) - .Timeout(iAuthRequest.Timeout * 1000, - () => - { - SendParams() - .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) - .AddUInt8((byte)ExceptionCode.Timeout) - .AddUInt16(7) - .AddString("Timeout") - .Done(); - }); - } - } - else if (authPacket.Event == EpAuthPacketEvent.IAuthHashed) - { - var dataType = authPacket.DataType.Value; - var (_, parsed) = Codec.ParseSync(dataType, Instance.Warehouse); - var rt = (Map)parsed; - - - var headers = rt.Select(x => new KeyValuePair((EpAuthPacketIAuthHeader)x.Key, x.Value)); - var iAuthRequest = new AuthorizationRequest(headers); - - if (Authenticator == null) - { - SendParams() - .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) - .AddUInt8((byte)ExceptionCode.NotSupported) - .AddUInt16(13) - .AddString("Not supported") - .Done(); - } - else - { - - Authenticator(iAuthRequest).Then(response => - { - var sha = SHA256.Create(); - var hash = sha.ComputeHash(new BinaryList() - .AddUInt8Array((byte[])session.LocalHeaders[EpAuthPacketHeader.Nonce]) - .AddUInt8Array(Codec.Compose(response, this.Instance.Warehouse, this)) - .AddUInt8Array((byte[])session.RemoteHeaders[EpAuthPacketHeader.Nonce]) - .ToArray()); - - SendParams() - .AddUInt8((byte)EpAuthPacketAction.IAuthHashed) - .AddUInt32((uint)headers[EpAuthPacketIAuthHeader.Reference]) - .AddUInt8((byte)EpAuthPacketHashAlgorithm.SHA256) - .AddUInt16((ushort)hash.Length) - .AddUInt8Array(hash) - .Done(); - }) - .Timeout(iAuthRequest.Timeout * 1000, - () => - { - SendParams() - .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) - .AddUInt8((byte)ExceptionCode.Timeout) - .AddUInt16(7) - .AddString("Timeout") - .Done(); - }); - } - } - else if (authPacket.Event == EpAuthPacketEvent.IAuthEncrypted) - { - throw new NotImplementedException("IAuthEncrypted not implemented."); - } - } - } - - private void ProcessHostAuth(byte[] data) - { - if (authPacket.Command == EpAuthPacketCommand.Initialize) - { - // Parse headers - - var dataType = authPacket.DataType.Value; - - var (_, parsed) = Codec.ParseSync(dataType, Server.Instance.Warehouse); - - var rt = (Map)parsed; - - session.RemoteHeaders = rt.Select(x => new KeyValuePair((EpAuthPacketHeader)x.Key, x.Value)); - - session.RemoteMethod = authPacket.LocalMethod; - - - if (authPacket.Initialization == EpAuthPacketInitialize.CredentialsNoAuth) - { - try - { - - var username = (string)session.RemoteHeaders[EpAuthPacketHeader.Username]; - var domain = (string)session.RemoteHeaders[EpAuthPacketHeader.Domain]; - //var remoteNonce = (byte[])session.RemoteHeaders[EpAuthPacketHeader.Nonce]; - - if (Server.Membership == null) - { - var errMsg = DC.ToBytes("Membership not set."); - - SendParams() - .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) - .AddUInt8((byte)ExceptionCode.GeneralFailure) - .AddUInt16((ushort)errMsg.Length) - .AddUInt8Array(errMsg) - .Done(); - } - else Server.Membership.UserExists(username, domain).Then(x => - { - if (x != null) - { - session.AuthorizedAccount = x; - - var localHeaders = session.LocalHeaders.Select(x => new KeyValuePair((byte)x.Key, x.Value)); - - SendParams() - .AddUInt8((byte)EpAuthPacketAcknowledge.NoAuthCredentials) - .AddUInt8Array(Codec.Compose(localHeaders, Server.Instance.Warehouse, this)) - .Done(); - } - else - { - // Send user not found error - SendParams() - .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) - .AddUInt8((byte)ExceptionCode.UserOrTokenNotFound) - .AddUInt16(14) - .AddString("User not found") - .Done(); - } - }); - } - catch (Exception ex) - { - // Send the server side error - var errMsg = DC.ToBytes(ex.Message); - - SendParams() - .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) - .AddUInt8((byte)ExceptionCode.GeneralFailure) - .AddUInt16((ushort)errMsg.Length) - .AddUInt8Array(errMsg) - .Done(); - } - } - else if (authPacket.Initialization == EpAuthPacketInitialize.TokenNoAuth) - { - try - { - if (Server.Membership == null) - { - SendParams() - .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) - .AddUInt8((byte)ExceptionCode.UserOrTokenNotFound) - .AddUInt16(15) - .AddString("Token not found") - .Done(); - } - // Check if user and token exists - else - { - var tokenIndex = (ulong)session.RemoteHeaders[EpAuthPacketHeader.TokenIndex]; - var domain = (string)session.RemoteHeaders[EpAuthPacketHeader.Domain]; - //var nonce = (byte[])session.RemoteHeaders[EpAuthPacketHeader.Nonce]; - - Server.Membership.TokenExists(tokenIndex, domain).Then(x => - { - if (x != null) - { - session.AuthorizedAccount = x; - - var localHeaders = session.LocalHeaders.Select(x => new KeyValuePair((byte)x.Key, x.Value)); - - SendParams() - .AddUInt8((byte)EpAuthPacketAcknowledge.NoAuthToken) - .AddUInt8Array(Codec.Compose(localHeaders, this.Instance.Warehouse, this)) - .Done(); - - } - else - { - // Send token not found error. - SendParams() - .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) - .AddUInt8((byte)ExceptionCode.UserOrTokenNotFound) - .AddUInt16(15) - .AddString("Token not found") - .Done(); - } - }); - } - } - catch (Exception ex) - { - // Sender server side error. - - var errMsg = DC.ToBytes(ex.Message); - - SendParams() - .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) - .AddUInt8((byte)ExceptionCode.GeneralFailure) - .AddUInt16((ushort)errMsg.Length) - .AddUInt8Array(errMsg) - .Done(); - } - } - else if (authPacket.Initialization == EpAuthPacketInitialize.NoAuthNoAuth) - { - try - { - // Check if guests are allowed - if (Server.Membership?.GuestsAllowed ?? true) - { - var localHeaders = session.LocalHeaders.Select(x => new KeyValuePair((byte)x.Key, x.Value)); - - session.AuthorizedAccount = "g-" + Global.GenerateCode(); - - readyToEstablish = true; - - SendParams() - .AddUInt8((byte)EpAuthPacketAcknowledge.NoAuthNoAuth) - .AddUInt8Array(Codec.Compose(localHeaders,Server.Instance.Warehouse, this)) - .Done(); - } - else - { - // Send access denied error because the server does not allow guests. - SendParams() - .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) - .AddUInt8((byte)ExceptionCode.AccessDenied) - .AddUInt16(18) - .AddString("Guests not allowed") - .Done(); - } - } - catch (Exception ex) - { - // Send the server side error. - var errMsg = DC.ToBytes(ex.Message); - - SendParams() - .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) - .AddUInt8((byte)ExceptionCode.GeneralFailure) - .AddUInt16((ushort)errMsg.Length) - .AddUInt8Array(errMsg) - .Done(); - } - } - - } - else if (authPacket.Command == EpAuthPacketCommand.Action) - { - if (authPacket.Action == EpAuthPacketAction.AuthenticateHash) - { - var remoteHash = authPacket.Challenge; - AsyncReply reply = null; - - try - { - if (session.RemoteMethod == AuthenticationMethod.Credentials) - { - reply = Server.Membership.GetPassword((string)session.RemoteHeaders[EpAuthPacketHeader.Username], - (string)session.RemoteHeaders[EpAuthPacketHeader.Domain]); - } - else if (session.RemoteMethod == AuthenticationMethod.Token) - { - reply = Server.Membership.GetToken((ulong)session.RemoteHeaders[EpAuthPacketHeader.TokenIndex], - (string)session.RemoteHeaders[EpAuthPacketHeader.Domain]); - } - else - { - throw new NotImplementedException("Authentication method unsupported."); - } - - reply.Then((pw) => - { - if (pw != null) - { - var localNonce = (byte[])session.LocalHeaders[EpAuthPacketHeader.Nonce]; - var remoteNonce = (byte[])session.RemoteHeaders[EpAuthPacketHeader.Nonce]; - - var hashFunc = SHA256.Create(); - var hash = hashFunc.ComputeHash((new BinaryList()) - .AddUInt8Array(remoteNonce) - .AddUInt8Array(pw) - .AddUInt8Array(localNonce) - .ToArray()); - - if (hash.SequenceEqual(remoteHash)) - { - // send our hash - var localHash = hashFunc.ComputeHash((new BinaryList()) - .AddUInt8Array(localNonce) - .AddUInt8Array(pw) - .AddUInt8Array(remoteNonce) - .ToArray()); - - SendParams() - .AddUInt8((byte)EpAuthPacketAction.AuthenticateHash) - .AddUInt8((byte)EpAuthPacketHashAlgorithm.SHA256) - .AddUInt16((ushort)localHash.Length) - .AddUInt8Array(localHash) - .Done(); - - readyToEstablish = true; - } - else - { - //Global.Log("auth", LogType.Warning, "U:" + RemoteUsername + " IP:" + Socket.RemoteEndPoint.Address.ToString() + " S:DENIED"); - SendParams() - .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) - .AddUInt8((byte)ExceptionCode.AccessDenied) - .AddUInt16(13) - .AddString("Access Denied") - .Done(); - } - } - }); - } - catch (Exception ex) - { - var errMsg = DC.ToBytes(ex.Message); - - SendParams() - .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) - .AddUInt8((byte)ExceptionCode.GeneralFailure) - .AddUInt16((ushort)errMsg.Length) - .AddUInt8Array(errMsg) - .Done(); - } - } - else if (authPacket.Action == EpAuthPacketAction.IAuthPlain) - { - var reference = authPacket.Reference; - var dataType = authPacket.DataType.Value; - - var (_, value) = Codec.ParseSync(dataType, Instance.Warehouse); - - Server.Membership.AuthorizePlain(session, reference, value) - .Then(x => ProcessAuthorization(x)); - - - } - else if (authPacket.Action == EpAuthPacketAction.IAuthHashed) - { - var reference = authPacket.Reference; - var value = authPacket.Challenge; - var algorithm = authPacket.HashAlgorithm; - - Server.Membership.AuthorizeHashed(session, reference, algorithm, value) - .Then(x => ProcessAuthorization(x)); - - } - else if (authPacket.Action == EpAuthPacketAction.IAuthEncrypted) - { - var reference = authPacket.Reference; - var value = authPacket.Challenge; - var algorithm = authPacket.PublicKeyAlgorithm; - - Server.Membership.AuthorizeEncrypted(session, reference, algorithm, value) - .Then(x => ProcessAuthorization(x)); - } - else if (authPacket.Action == EpAuthPacketAction.EstablishNewSession) - { - if (readyToEstablish) - { - - if (Server.Membership == null) - { - ProcessAuthorization(null); - } - else - { - Server.Membership?.Authorize(session).Then(x => - { - ProcessAuthorization(x); - }); - } - - //Global.Log("auth", LogType.Warning, "U:" + RemoteUsername + " IP:" + Socket.RemoteEndPoint.Address.ToString() + " S:AUTH"); - - } - else - { - SendParams() - .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) - .AddUInt8((byte)ExceptionCode.GeneralFailure) - .AddUInt16(9) - .AddString("Not ready") - .Done(); - } - } - } - } - - internal void ProcessAuthorization(AuthorizationResults results) - { - if (results == null || results.Response == Security.Membership.AuthorizationResultsResponse.Success) - { - var r = new Random(); - session.Id = new byte[32]; - r.NextBytes(session.Id); - var accountId = session.AuthorizedAccount.ToBytes(); - - SendParams() - .AddUInt8((byte)EpAuthPacketEvent.IndicationEstablished) - .AddUInt8((byte)session.Id.Length) - .AddUInt8Array(session.Id) - .AddUInt8((byte)accountId.Length) - .AddUInt8Array(accountId) - .Done(); - - if (this.Instance == null) - { - Server.Instance.Warehouse.Put( - Server.Instance.Link + "/" + this.GetHashCode().ToString().Replace("/", "_"), this) - .Then(x => - { - ready = true; - Status = EpConnectionStatus.Connected; - openReply?.Trigger(true); - openReply = null; - OnReady?.Invoke(this); - - Server?.Membership?.Login(session); - LoginDate = DateTime.Now; - - }).Error(x => - { - openReply?.TriggerError(x); - openReply = null; - - }); - } - else - { - ready = true; - Status = EpConnectionStatus.Connected; - - openReply?.Trigger(true); - openReply = null; - - OnReady?.Invoke(this); - Server?.Membership?.Login(session); - } - } - else if (results.Response == Security.Membership.AuthorizationResultsResponse.Failed) - { - SendParams() - .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) - .AddUInt8((byte)ExceptionCode.ChallengeFailed) - .AddUInt16(21) - .AddString("Authentication failed") - .Done(); - } - else if (results.Response == Security.Membership.AuthorizationResultsResponse.Expired) - { - SendParams() - .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) - .AddUInt8((byte)ExceptionCode.Timeout) - .AddUInt16(22) - .AddString("Authentication expired") - .Done(); - } - else if (results.Response == Security.Membership.AuthorizationResultsResponse.ServiceUnavailable) - { - SendParams() - .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) - .AddUInt8((byte)ExceptionCode.GeneralFailure) - .AddUInt16(19) - .AddString("Service unavailable") - .Done(); - } - else if (results.Response == Security.Membership.AuthorizationResultsResponse.IAuthPlain) - { - var args = new Map() - { - [EpAuthPacketIAuthHeader.Reference] = results.Reference, - [EpAuthPacketIAuthHeader.Destination] = results.Destination, - [EpAuthPacketIAuthHeader.Trials] = results.Trials, - [EpAuthPacketIAuthHeader.Clue] = results.Clue, - [EpAuthPacketIAuthHeader.RequiredFormat] = results.RequiredFormat, - }.Select(m => new KeyValuePair((byte)m.Key, m.Value)); - - SendParams() - .AddUInt8((byte)EpAuthPacketEvent.IAuthPlain) - .AddUInt8Array(Codec.Compose(args, this.Instance.Warehouse, this)) - .Done(); - - } - else if (results.Response == Security.Membership.AuthorizationResultsResponse.IAuthHashed) - { - var args = new Map() - { - [EpAuthPacketIAuthHeader.Reference] = results.Reference, - [EpAuthPacketIAuthHeader.Destination] = results.Destination, - [EpAuthPacketIAuthHeader.Expire] = results.Expire, - //[EpAuthPacketIAuthHeader.Issue] = results.Issue, - [EpAuthPacketIAuthHeader.Clue] = results.Clue, - [EpAuthPacketIAuthHeader.RequiredFormat] = results.RequiredFormat, - }.Select(m => new KeyValuePair((byte)m.Key, m.Value)); - - SendParams() - .AddUInt8((byte)EpAuthPacketEvent.IAuthHashed) - .AddUInt8Array(Codec.Compose(args, Server.Instance.Warehouse, this)) - .Done(); - - } - else if (results.Response == Security.Membership.AuthorizationResultsResponse.IAuthEncrypted) - { - var args = new Map() - { - [EpAuthPacketIAuthHeader.Destination] = results.Destination, - [EpAuthPacketIAuthHeader.Expire] = results.Expire, - [EpAuthPacketIAuthHeader.Clue] = results.Clue, - [EpAuthPacketIAuthHeader.RequiredFormat] = results.RequiredFormat, - }.Select(m => new KeyValuePair((byte)m.Key, m.Value)); - - SendParams() - .AddUInt8((byte)EpAuthPacketEvent.IAuthEncrypted) - .AddUInt8Array(Codec.Compose(args, this.Instance.Warehouse, this)) - .Done(); - } - } + //private void ProcessClientAuth(byte[] data) + //{ + // if (authPacket.Command == EpAuthPacketCommand.Acknowledge) + // { + // // if there is a mismatch in authentication + // if (session.LocalMethod != authPacket.RemoteMethod + // || session.RemoteMethod != authPacket.LocalMethod) + // { + // openReply?.TriggerError(new Exception("Peer refused authentication method.")); + // openReply = null; + // } + + // // Parse remote headers + + // var dataType = authPacket.DataType.Value; + + // var (_, parsed) = Codec.ParseSync(dataType, Instance.Warehouse); + + // var rt = (Map)parsed; + + // session.RemoteHeaders = rt.Select(x => new KeyValuePair((EpAuthPacketHeader)x.Key, x.Value)); + + // if (session.LocalMethod == AuthenticationMethod.None) + // { + // // send establish + // SendParams() + // .AddUInt8((byte)EpAuthPacketAction.EstablishNewSession) + // .Done(); + // } + // else if (session.LocalMethod == AuthenticationMethod.Credentials + // || session.LocalMethod == AuthenticationMethod.Token) + // { + // var remoteNonce = (byte[])session.RemoteHeaders[EpAuthPacketHeader.Nonce]; + // var localNonce = (byte[])session.LocalHeaders[EpAuthPacketHeader.Nonce]; + + // // send our hash + // var hashFunc = SHA256.Create(); + // // local nonce + password or token + remote nonce + // var challenge = hashFunc.ComputeHash(new BinaryList() + // .AddUInt8Array(localNonce) + // .AddUInt8Array(localPasswordOrToken) + // .AddUInt8Array(remoteNonce) + // .ToArray()); + + // SendParams() + // .AddUInt8((byte)EpAuthPacketAction.AuthenticateHash) + // .AddUInt8((byte)EpAuthPacketHashAlgorithm.SHA256) + // .AddUInt16((ushort)challenge.Length) + // .AddUInt8Array(challenge) + // .Done(); + // } + + // } + // else if (authPacket.Command == EpAuthPacketCommand.Action) + // { + // if (authPacket.Action == EpAuthPacketAction.AuthenticateHash) + // { + // var remoteNonce = (byte[])session.RemoteHeaders[EpAuthPacketHeader.Nonce]; + // var localNonce = (byte[])session.LocalHeaders[EpAuthPacketHeader.Nonce]; + + // // check if the server knows my password + // var hashFunc = SHA256.Create(); + + // var challenge = hashFunc.ComputeHash(new BinaryList() + // .AddUInt8Array(remoteNonce) + // .AddUInt8Array(localPasswordOrToken) + // .AddUInt8Array(localNonce) + // .ToArray()); + + + // if (challenge.SequenceEqual(authPacket.Challenge)) + // { + // // send establish request + // SendParams() + // .AddUInt8((byte)EpAuthPacketAction.EstablishNewSession) + // .Done(); + // } + // else + // { + // SendParams() + // .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) + // .AddUInt8((byte)ExceptionCode.ChallengeFailed) + // .AddUInt16(16) + // .AddString("Challenge Failed") + // .Done(); + + // } + // } + // } + // else if (authPacket.Command == EpAuthPacketCommand.Event) + // { + // if (authPacket.Event == EpAuthPacketEvent.ErrorTerminate + // || authPacket.Event == EpAuthPacketEvent.ErrorMustEncrypt + // || authPacket.Event == EpAuthPacketEvent.ErrorRetry) + // { + // invalidCredentials = true; + // openReply?.TriggerError(new AsyncException(ErrorType.Management, authPacket.ErrorCode, authPacket.Message)); + // openReply = null; + // OnError?.Invoke(this, authPacket.ErrorCode, authPacket.Message); + // Close(); + // } + // else if (authPacket.Event == EpAuthPacketEvent.IndicationEstablished) + // { + // session.Id = authPacket.SessionId; + // session.AuthorizedAccount = authPacket.AccountId.GetString(0, (uint)authPacket.AccountId.Length); + + // ready = true; + // Status = EpConnectionStatus.Connected; + + + // // put it in the warehouse + + // if (this.Instance == null) + // { + // Server.Instance.Warehouse.Put(Server + "/" + session.AuthorizedAccount.Replace("/", "_"), this) + // .Then(x => + // { + // openReply?.Trigger(true); + // OnReady?.Invoke(this); + // openReply = null; + + + // }).Error(x => + // { + // openReply?.TriggerError(x); + // openReply = null; + // }); + // } + // else + // { + // openReply?.Trigger(true); + // openReply = null; + + // OnReady?.Invoke(this); + // } + + // // start perodic keep alive timer + // keepAliveTimer.Start(); + + // } + // else if (authPacket.Event == EpAuthPacketEvent.IAuthPlain) + // { + // var dataType = authPacket.DataType.Value; + // var (_, parsed) = Codec.ParseSync(dataType, Instance.Warehouse); + // var rt = (Map)parsed; + + // var headers = rt.Select(x => new KeyValuePair((EpAuthPacketIAuthHeader)x.Key, x.Value)); + // var iAuthRequest = new AuthorizationRequest(headers); + + // if (Authenticator == null) + // { + // SendParams() + // .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) + // .AddUInt8((byte)ExceptionCode.NotSupported) + // .AddUInt16(13) + // .AddString("Not supported") + // .Done(); + // } + // else + // { + // Authenticator(iAuthRequest).Then(response => + // { + // SendParams() + // .AddUInt8((byte)EpAuthPacketAction.IAuthPlain) + // .AddUInt32((uint)headers[EpAuthPacketIAuthHeader.Reference]) + // .AddUInt8Array(Codec.Compose(response, this.Instance.Warehouse, this)) + // .Done(); + // }) + // .Timeout(iAuthRequest.Timeout * 1000, + // () => + // { + // SendParams() + // .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) + // .AddUInt8((byte)ExceptionCode.Timeout) + // .AddUInt16(7) + // .AddString("Timeout") + // .Done(); + // }); + // } + // } + // else if (authPacket.Event == EpAuthPacketEvent.IAuthHashed) + // { + // var dataType = authPacket.DataType.Value; + // var (_, parsed) = Codec.ParseSync(dataType, Instance.Warehouse); + // var rt = (Map)parsed; + + + // var headers = rt.Select(x => new KeyValuePair((EpAuthPacketIAuthHeader)x.Key, x.Value)); + // var iAuthRequest = new AuthorizationRequest(headers); + + // if (Authenticator == null) + // { + // SendParams() + // .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) + // .AddUInt8((byte)ExceptionCode.NotSupported) + // .AddUInt16(13) + // .AddString("Not supported") + // .Done(); + // } + // else + // { + + // Authenticator(iAuthRequest).Then(response => + // { + // var sha = SHA256.Create(); + // var hash = sha.ComputeHash(new BinaryList() + // .AddUInt8Array((byte[])session.LocalHeaders[EpAuthPacketHeader.Nonce]) + // .AddUInt8Array(Codec.Compose(response, this.Instance.Warehouse, this)) + // .AddUInt8Array((byte[])session.RemoteHeaders[EpAuthPacketHeader.Nonce]) + // .ToArray()); + + // SendParams() + // .AddUInt8((byte)EpAuthPacketAction.IAuthHashed) + // .AddUInt32((uint)headers[EpAuthPacketIAuthHeader.Reference]) + // .AddUInt8((byte)EpAuthPacketHashAlgorithm.SHA256) + // .AddUInt16((ushort)hash.Length) + // .AddUInt8Array(hash) + // .Done(); + // }) + // .Timeout(iAuthRequest.Timeout * 1000, + // () => + // { + // SendParams() + // .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) + // .AddUInt8((byte)ExceptionCode.Timeout) + // .AddUInt16(7) + // .AddString("Timeout") + // .Done(); + // }); + // } + // } + // else if (authPacket.Event == EpAuthPacketEvent.IAuthEncrypted) + // { + // throw new NotImplementedException("IAuthEncrypted not implemented."); + // } + // } + //} + + //private void ProcessHostAuth(byte[] data) + //{ + // if (authPacket.Command == EpAuthPacketCommand.Initialize) + // { + // // Parse headers + + // var dataType = authPacket.DataType.Value; + + // var (_, parsed) = Codec.ParseSync(dataType, Server.Instance.Warehouse); + + // var rt = (Map)parsed; + + // session.RemoteHeaders = rt.Select(x => new KeyValuePair((EpAuthPacketHeader)x.Key, x.Value)); + + // session.RemoteMethod = authPacket.LocalMethod; + + + // if (authPacket.Initialization == EpAuthPacketInitialize.CredentialsNoAuth) + // { + // try + // { + + // var username = (string)session.RemoteHeaders[EpAuthPacketHeader.Username]; + // var domain = (string)session.RemoteHeaders[EpAuthPacketHeader.Domain]; + // //var remoteNonce = (byte[])session.RemoteHeaders[EpAuthPacketHeader.Nonce]; + + // if (Server.Membership == null) + // { + // var errMsg = DC.ToBytes("Membership not set."); + + // SendParams() + // .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) + // .AddUInt8((byte)ExceptionCode.GeneralFailure) + // .AddUInt16((ushort)errMsg.Length) + // .AddUInt8Array(errMsg) + // .Done(); + // } + // else Server.Membership.UserExists(username, domain).Then(x => + // { + // if (x != null) + // { + // session.AuthorizedAccount = x; + + // var localHeaders = session.LocalHeaders.Select(x => new KeyValuePair((byte)x.Key, x.Value)); + + // SendParams() + // .AddUInt8((byte)EpAuthPacketAcknowledge.NoAuthCredentials) + // .AddUInt8Array(Codec.Compose(localHeaders, Server.Instance.Warehouse, this)) + // .Done(); + // } + // else + // { + // // Send user not found error + // SendParams() + // .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) + // .AddUInt8((byte)ExceptionCode.UserOrTokenNotFound) + // .AddUInt16(14) + // .AddString("User not found") + // .Done(); + // } + // }); + // } + // catch (Exception ex) + // { + // // Send the server side error + // var errMsg = DC.ToBytes(ex.Message); + + // SendParams() + // .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) + // .AddUInt8((byte)ExceptionCode.GeneralFailure) + // .AddUInt16((ushort)errMsg.Length) + // .AddUInt8Array(errMsg) + // .Done(); + // } + // } + // else if (authPacket.Initialization == EpAuthPacketInitialize.TokenNoAuth) + // { + // try + // { + // if (Server.Membership == null) + // { + // SendParams() + // .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) + // .AddUInt8((byte)ExceptionCode.UserOrTokenNotFound) + // .AddUInt16(15) + // .AddString("Token not found") + // .Done(); + // } + // // Check if user and token exists + // else + // { + // var tokenIndex = (ulong)session.RemoteHeaders[EpAuthPacketHeader.TokenIndex]; + // var domain = (string)session.RemoteHeaders[EpAuthPacketHeader.Domain]; + // //var nonce = (byte[])session.RemoteHeaders[EpAuthPacketHeader.Nonce]; + + // Server.Membership.TokenExists(tokenIndex, domain).Then(x => + // { + // if (x != null) + // { + // session.AuthorizedAccount = x; + + // var localHeaders = session.LocalHeaders.Select(x => new KeyValuePair((byte)x.Key, x.Value)); + + // SendParams() + // .AddUInt8((byte)EpAuthPacketAcknowledge.NoAuthToken) + // .AddUInt8Array(Codec.Compose(localHeaders, this.Instance.Warehouse, this)) + // .Done(); + + // } + // else + // { + // // Send token not found error. + // SendParams() + // .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) + // .AddUInt8((byte)ExceptionCode.UserOrTokenNotFound) + // .AddUInt16(15) + // .AddString("Token not found") + // .Done(); + // } + // }); + // } + // } + // catch (Exception ex) + // { + // // Sender server side error. + + // var errMsg = DC.ToBytes(ex.Message); + + // SendParams() + // .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) + // .AddUInt8((byte)ExceptionCode.GeneralFailure) + // .AddUInt16((ushort)errMsg.Length) + // .AddUInt8Array(errMsg) + // .Done(); + // } + // } + // else if (authPacket.Initialization == EpAuthPacketInitialize.NoAuthNoAuth) + // { + // try + // { + // // Check if guests are allowed + // if (Server.Membership?.GuestsAllowed ?? true) + // { + // var localHeaders = session.LocalHeaders.Select(x => new KeyValuePair((byte)x.Key, x.Value)); + + // session.AuthorizedAccount = "g-" + Global.GenerateCode(); + + // readyToEstablish = true; + + // SendParams() + // .AddUInt8((byte)EpAuthPacketAcknowledge.NoAuthNoAuth) + // .AddUInt8Array(Codec.Compose(localHeaders,Server.Instance.Warehouse, this)) + // .Done(); + // } + // else + // { + // // Send access denied error because the server does not allow guests. + // SendParams() + // .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) + // .AddUInt8((byte)ExceptionCode.AccessDenied) + // .AddUInt16(18) + // .AddString("Guests not allowed") + // .Done(); + // } + // } + // catch (Exception ex) + // { + // // Send the server side error. + // var errMsg = DC.ToBytes(ex.Message); + + // SendParams() + // .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) + // .AddUInt8((byte)ExceptionCode.GeneralFailure) + // .AddUInt16((ushort)errMsg.Length) + // .AddUInt8Array(errMsg) + // .Done(); + // } + // } + + // } + // else if (authPacket.Command == EpAuthPacketCommand.Action) + // { + // if (authPacket.Action == EpAuthPacketAction.AuthenticateHash) + // { + // var remoteHash = authPacket.Challenge; + // AsyncReply reply = null; + + // try + // { + // if (session.RemoteMethod == AuthenticationMethod.Credentials) + // { + // reply = Server.Membership.GetPassword((string)session.RemoteHeaders[EpAuthPacketHeader.Username], + // (string)session.RemoteHeaders[EpAuthPacketHeader.Domain]); + // } + // else if (session.RemoteMethod == AuthenticationMethod.Token) + // { + // reply = Server.Membership.GetToken((ulong)session.RemoteHeaders[EpAuthPacketHeader.TokenIndex], + // (string)session.RemoteHeaders[EpAuthPacketHeader.Domain]); + // } + // else + // { + // throw new NotImplementedException("Authentication method unsupported."); + // } + + // reply.Then((pw) => + // { + // if (pw != null) + // { + // var localNonce = (byte[])session.LocalHeaders[EpAuthPacketHeader.Nonce]; + // var remoteNonce = (byte[])session.RemoteHeaders[EpAuthPacketHeader.Nonce]; + + // var hashFunc = SHA256.Create(); + // var hash = hashFunc.ComputeHash((new BinaryList()) + // .AddUInt8Array(remoteNonce) + // .AddUInt8Array(pw) + // .AddUInt8Array(localNonce) + // .ToArray()); + + // if (hash.SequenceEqual(remoteHash)) + // { + // // send our hash + // var localHash = hashFunc.ComputeHash((new BinaryList()) + // .AddUInt8Array(localNonce) + // .AddUInt8Array(pw) + // .AddUInt8Array(remoteNonce) + // .ToArray()); + + // SendParams() + // .AddUInt8((byte)EpAuthPacketAction.AuthenticateHash) + // .AddUInt8((byte)EpAuthPacketHashAlgorithm.SHA256) + // .AddUInt16((ushort)localHash.Length) + // .AddUInt8Array(localHash) + // .Done(); + + // readyToEstablish = true; + // } + // else + // { + // //Global.Log("auth", LogType.Warning, "U:" + RemoteUsername + " IP:" + Socket.RemoteEndPoint.Address.ToString() + " S:DENIED"); + // SendParams() + // .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) + // .AddUInt8((byte)ExceptionCode.AccessDenied) + // .AddUInt16(13) + // .AddString("Access Denied") + // .Done(); + // } + // } + // }); + // } + // catch (Exception ex) + // { + // var errMsg = DC.ToBytes(ex.Message); + + // SendParams() + // .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) + // .AddUInt8((byte)ExceptionCode.GeneralFailure) + // .AddUInt16((ushort)errMsg.Length) + // .AddUInt8Array(errMsg) + // .Done(); + // } + // } + // else if (authPacket.Action == EpAuthPacketAction.IAuthPlain) + // { + // var reference = authPacket.Reference; + // var dataType = authPacket.DataType.Value; + + // var (_, value) = Codec.ParseSync(dataType, Instance.Warehouse); + + // Server.Membership.AuthorizePlain(session, reference, value) + // .Then(x => ProcessAuthorization(x)); + + + // } + // else if (authPacket.Action == EpAuthPacketAction.IAuthHashed) + // { + // var reference = authPacket.Reference; + // var value = authPacket.Challenge; + // var algorithm = authPacket.HashAlgorithm; + + // Server.Membership.AuthorizeHashed(session, reference, algorithm, value) + // .Then(x => ProcessAuthorization(x)); + + // } + // else if (authPacket.Action == EpAuthPacketAction.IAuthEncrypted) + // { + // var reference = authPacket.Reference; + // var value = authPacket.Challenge; + // var algorithm = authPacket.PublicKeyAlgorithm; + + // Server.Membership.AuthorizeEncrypted(session, reference, algorithm, value) + // .Then(x => ProcessAuthorization(x)); + // } + // else if (authPacket.Action == EpAuthPacketAction.EstablishNewSession) + // { + // if (readyToEstablish) + // { + + // if (Server.Membership == null) + // { + // ProcessAuthorization(null); + // } + // else + // { + // Server.Membership?.Authorize(session).Then(x => + // { + // ProcessAuthorization(x); + // }); + // } + + // //Global.Log("auth", LogType.Warning, "U:" + RemoteUsername + " IP:" + Socket.RemoteEndPoint.Address.ToString() + " S:AUTH"); + + // } + // else + // { + // SendParams() + // .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) + // .AddUInt8((byte)ExceptionCode.GeneralFailure) + // .AddUInt16(9) + // .AddString("Not ready") + // .Done(); + // } + // } + // } + //} + + //internal void ProcessAuthorization(AuthorizationResults results) + //{ + // if (results == null || results.Response == Security.Membership.AuthorizationResultsResponse.Success) + // { + // var r = new Random(); + // session.Id = new byte[32]; + // r.NextBytes(session.Id); + // var accountId = session.AuthorizedAccount.ToBytes(); + + // SendParams() + // .AddUInt8((byte)EpAuthPacketEvent.IndicationEstablished) + // .AddUInt8((byte)session.Id.Length) + // .AddUInt8Array(session.Id) + // .AddUInt8((byte)accountId.Length) + // .AddUInt8Array(accountId) + // .Done(); + + // if (this.Instance == null) + // { + // Server.Instance.Warehouse.Put( + // Server.Instance.Link + "/" + this.GetHashCode().ToString().Replace("/", "_"), this) + // .Then(x => + // { + // ready = true; + // Status = EpConnectionStatus.Connected; + // openReply?.Trigger(true); + // openReply = null; + // OnReady?.Invoke(this); + + // Server?.Membership?.Login(session); + // LoginDate = DateTime.Now; + + // }).Error(x => + // { + // openReply?.TriggerError(x); + // openReply = null; + + // }); + // } + // else + // { + // ready = true; + // Status = EpConnectionStatus.Connected; + + // openReply?.Trigger(true); + // openReply = null; + + // OnReady?.Invoke(this); + // Server?.Membership?.Login(session); + // } + // } + // else if (results.Response == Security.Membership.AuthorizationResultsResponse.Failed) + // { + // SendParams() + // .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) + // .AddUInt8((byte)ExceptionCode.ChallengeFailed) + // .AddUInt16(21) + // .AddString("Authentication failed") + // .Done(); + // } + // else if (results.Response == Security.Membership.AuthorizationResultsResponse.Expired) + // { + // SendParams() + // .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) + // .AddUInt8((byte)ExceptionCode.Timeout) + // .AddUInt16(22) + // .AddString("Authentication expired") + // .Done(); + // } + // else if (results.Response == Security.Membership.AuthorizationResultsResponse.ServiceUnavailable) + // { + // SendParams() + // .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) + // .AddUInt8((byte)ExceptionCode.GeneralFailure) + // .AddUInt16(19) + // .AddString("Service unavailable") + // .Done(); + // } + // else if (results.Response == Security.Membership.AuthorizationResultsResponse.IAuthPlain) + // { + // var args = new Map() + // { + // [EpAuthPacketIAuthHeader.Reference] = results.Reference, + // [EpAuthPacketIAuthHeader.Destination] = results.Destination, + // [EpAuthPacketIAuthHeader.Trials] = results.Trials, + // [EpAuthPacketIAuthHeader.Clue] = results.Clue, + // [EpAuthPacketIAuthHeader.RequiredFormat] = results.RequiredFormat, + // }.Select(m => new KeyValuePair((byte)m.Key, m.Value)); + + // SendParams() + // .AddUInt8((byte)EpAuthPacketEvent.IAuthPlain) + // .AddUInt8Array(Codec.Compose(args, this.Instance.Warehouse, this)) + // .Done(); + + // } + // else if (results.Response == Security.Membership.AuthorizationResultsResponse.IAuthHashed) + // { + // var args = new Map() + // { + // [EpAuthPacketIAuthHeader.Reference] = results.Reference, + // [EpAuthPacketIAuthHeader.Destination] = results.Destination, + // [EpAuthPacketIAuthHeader.Expire] = results.Expire, + // //[EpAuthPacketIAuthHeader.Issue] = results.Issue, + // [EpAuthPacketIAuthHeader.Clue] = results.Clue, + // [EpAuthPacketIAuthHeader.RequiredFormat] = results.RequiredFormat, + // }.Select(m => new KeyValuePair((byte)m.Key, m.Value)); + + // SendParams() + // .AddUInt8((byte)EpAuthPacketEvent.IAuthHashed) + // .AddUInt8Array(Codec.Compose(args, Server.Instance.Warehouse, this)) + // .Done(); + + // } + // else if (results.Response == Security.Membership.AuthorizationResultsResponse.IAuthEncrypted) + // { + // var args = new Map() + // { + // [EpAuthPacketIAuthHeader.Destination] = results.Destination, + // [EpAuthPacketIAuthHeader.Expire] = results.Expire, + // [EpAuthPacketIAuthHeader.Clue] = results.Clue, + // [EpAuthPacketIAuthHeader.RequiredFormat] = results.RequiredFormat, + // }.Select(m => new KeyValuePair((byte)m.Key, m.Value)); + + // SendParams() + // .AddUInt8((byte)EpAuthPacketEvent.IAuthEncrypted) + // .AddUInt8Array(Codec.Compose(args, this.Instance.Warehouse, this)) + // .Done(); + // } + //} protected override void DataReceived(NetworkBuffer data) { @@ -1407,21 +1472,7 @@ public partial class EpConnection : NetworkConnection, IStore // assign domain from hostname if not provided var domain = Domain != null ? Domain : address; - if (Username != null // Instance.Attributes.ContainsKey("username") - && Password != null)/// Instance.Attributes.ContainsKey("password")) - { - return Connect(AuthenticationMethod.Credentials, null, address, port, Username, 0, DC.ToBytes(Password), domain); - } - else if (Token != null) - { - return Connect(AuthenticationMethod.Token, null, address, port, null, TokenIndex, DC.ToBytes(Token), domain); - } - else - { - - return Connect(AuthenticationMethod.None, null, address, port, null, 0, null, domain); - - } + return Connect(null, address, port, domain); } return new AsyncReply(true); @@ -1430,7 +1481,7 @@ public partial class EpConnection : NetworkConnection, IStore - public AsyncReply Connect(AuthenticationMethod method = AuthenticationMethod.Certificate, ISocket socket = null, string hostname = null, ushort port = 0, string username = null, ulong tokenIndex = 0, byte[] passwordOrToken = null, string domain = null) + public AsyncReply Connect(ISocket socket = null, string hostname = null, ushort port = 0, string domain = null) { if (openReply != null) throw new AsyncException(ErrorType.Exception, 0, "Connection in progress"); @@ -1442,27 +1493,10 @@ public partial class EpConnection : NetworkConnection, IStore if (hostname != null) { session = new Session(); - session.AuthenticationType = AuthenticationType.Client; - session.LocalMethod = method; - session.RemoteMethod = AuthenticationMethod.None; - + session.AuthenticationType = AuthenticationMode.Initiator; + //session.AuthenticationMethod = method; session.LocalHeaders[EpAuthPacketHeader.Domain] = domain; - session.LocalHeaders[EpAuthPacketHeader.Nonce] = Global.GenerateBytes(32); - if (method == AuthenticationMethod.Credentials) - { - session.LocalHeaders[EpAuthPacketHeader.Username] = username; - } - else if (method == AuthenticationMethod.Token) - { - session.LocalHeaders[EpAuthPacketHeader.TokenIndex] = tokenIndex; - } - else if (method == AuthenticationMethod.Certificate) - { - throw new NotImplementedException("Unsupported authentication method."); - } - - localPasswordOrToken = passwordOrToken; invalidCredentials = false; } @@ -1582,7 +1616,7 @@ public partial class EpConnection : NetworkConnection, IStore return true; } - + /// /// Store interface. /// @@ -1617,14 +1651,14 @@ public partial class EpConnection : NetworkConnection, IStore protected override void Connected() { - if (session.AuthenticationType == AuthenticationType.Client) + if (session.AuthenticationType == AuthenticationMode.Initiator) Declare(); } protected override void Disconnected() { // clean up - ready = false; + authenticated = false; readyToEstablish = false; Status = EpConnectionStatus.Closed; @@ -1704,7 +1738,7 @@ public partial class EpConnection : NetworkConnection, IStore UnsubscribeAll(); Instance.Warehouse.Remove(this); - if (ready) + if (authenticated) Server.Membership?.Logout(session); } @@ -1749,5 +1783,5 @@ public partial class EpConnection : NetworkConnection, IStore throw new NotImplementedException(); } - + } diff --git a/Esiur/Protocol/EpConnectionProtocol.cs b/Esiur/Protocol/EpConnectionProtocol.cs index 72dbca3..e6ed159 100644 --- a/Esiur/Protocol/EpConnectionProtocol.cs +++ b/Esiur/Protocol/EpConnectionProtocol.cs @@ -50,12 +50,12 @@ partial class EpConnection KeyList> suspendedResources = new KeyList>(); KeyList resourceRequests = new KeyList(); - KeyList> typeDefsByIdRequests = new KeyList>(); + KeyList> typeDefsByIdRequests = new KeyList>(); KeyList> typeDefsByNameRequests = new KeyList>(); - Dictionary typeDefs = new Dictionary(); + Dictionary typeDefs = new Dictionary(); KeyList requests = new KeyList(); @@ -186,7 +186,7 @@ partial class EpConnection } - public AsyncReply StaticCall(UUID typeId, byte index, object parameters) + public AsyncReply StaticCall(Uuid typeId, byte index, object parameters) { return SendRequest(EpPacketRequest.StaticCall, typeId, index, parameters); } @@ -270,7 +270,7 @@ partial class EpConnection SendReply(EpPacketReply.Chunk, callbackId, chunk); } - void EpReplyCompleted(uint callbackId, ParsedTDU dataType) + void EpReplyCompleted(uint callbackId, ParsedTdu dataType) { var req = requests.Take(callbackId); @@ -301,12 +301,12 @@ partial class EpConnection } } - void EpExtensionAction(byte actionId, ParsedTDU? dataType, byte[] data) + void EpExtensionAction(byte actionId, ParsedTdu? dataType, byte[] data) { // nothing is supported now } - void EpReplyPropagated(uint callbackId, ParsedTDU dataType, byte[] data) + void EpReplyPropagated(uint callbackId, ParsedTdu dataType, byte[] data) { var req = requests[callbackId]; @@ -330,7 +330,7 @@ partial class EpConnection } } - void EpReplyError(uint callbackId, ParsedTDU dataType, byte[] data, ErrorType type) + void EpReplyError(uint callbackId, ParsedTdu dataType, byte[] data, ErrorType type) { var req = requests.Take(callbackId); @@ -349,7 +349,7 @@ partial class EpConnection req.TriggerError(new AsyncException(type, errorCode, errorMsg)); } - void EpReplyProgress(uint callbackId, ParsedTDU dataType, byte[] data) + void EpReplyProgress(uint callbackId, ParsedTdu dataType, byte[] data) { var req = requests[callbackId]; @@ -368,7 +368,7 @@ partial class EpConnection req.TriggerProgress(ProgressType.Execution, current, total); } - void EpReplyWarning(uint callbackId, ParsedTDU dataType, byte[] data) + void EpReplyWarning(uint callbackId, ParsedTdu dataType, byte[] data) { var req = requests[callbackId]; @@ -389,7 +389,7 @@ partial class EpConnection - void EpReplyChunk(uint callbackId, ParsedTDU dataType) + void EpReplyChunk(uint callbackId, ParsedTdu dataType) { var req = requests[callbackId]; @@ -404,16 +404,16 @@ partial class EpConnection req.TriggerChunk(parsed); } - void EpNotificationResourceReassigned(ParsedTDU dataType) + void EpNotificationResourceReassigned(ParsedTdu dataType) { // uint resourceId, uint newResourceId } - void EpNotificationResourceMoved(ParsedTDU dataType, byte[] data) { } + void EpNotificationResourceMoved(ParsedTdu dataType, byte[] data) { } - void EpNotificationSystemFailure(ParsedTDU dataType, byte[] data) { } + void EpNotificationSystemFailure(ParsedTdu dataType, byte[] data) { } - void EpNotificationResourceDestroyed(ParsedTDU dataType, byte[] data) + void EpNotificationResourceDestroyed(ParsedTdu dataType, byte[] data) { var (size, rt) = Codec.ParseSync(dataType, Instance.Warehouse); @@ -444,7 +444,7 @@ partial class EpConnection } - void EpNotificationPropertyModified(ParsedTDU dataType) + void EpNotificationPropertyModified(ParsedTdu dataType) { // resourceId, index, value var (valueOffset, valueSize, args) = @@ -488,7 +488,7 @@ partial class EpConnection } - void EpNotificationEventOccurred(ParsedTDU dataType, byte[] data) + void EpNotificationEventOccurred(ParsedTdu dataType, byte[] data) { // resourceId, index, value var (valueOffset, valueSize, args) = @@ -537,7 +537,7 @@ partial class EpConnection }); } - void EpRequestAttachResource(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestAttachResource(uint callback, ParsedTdu dataType, byte[] data) { var (_, value) = Codec.ParseSync(dataType, Instance.Warehouse); @@ -579,7 +579,7 @@ partial class EpConnection }); } - void EpRequestReattachResource(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestReattachResource(uint callback, ParsedTdu dataType, byte[] data) { // resourceId, index, value var (valueOffset, valueSize, args) = @@ -627,7 +627,7 @@ partial class EpConnection }); } - void EpRequestDetachResource(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestDetachResource(uint callback, ParsedTdu dataType, byte[] data) { var (_, value) = Codec.ParseSync(dataType, Instance.Warehouse); @@ -658,7 +658,7 @@ partial class EpConnection }); } - void EpRequestCreateResource(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestCreateResource(uint callback, ParsedTdu dataType, byte[] data) { var (_, parsed) = Codec.ParseAsync(dataType, this, null); @@ -668,8 +668,8 @@ partial class EpConnection TypeDef type = null; - if (args[1] is UUID) - type = Instance.Warehouse.GetTypeDefById((UUID)args[1]); + if (args[1] is Uuid) + type = Instance.Warehouse.GetTypeDefById((Uuid)args[1]); else if (args[1] is string) type = Instance.Warehouse.GetTypeDefByName((string)args[1]); @@ -719,7 +719,7 @@ partial class EpConnection } - void EpRequestDeleteResource(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestDeleteResource(uint callback, ParsedTdu dataType, byte[] data) { var (_, value) = Codec.ParseSync(dataType, Instance.Warehouse); @@ -748,7 +748,7 @@ partial class EpConnection }); } - void EpRequestMoveResource(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestMoveResource(uint callback, ParsedTdu dataType, byte[] data) { var (offset, length, args) = DataDeserializer.LimitedCountListParser(data, dataType.Offset, @@ -789,12 +789,12 @@ partial class EpConnection - void EpRequestToken(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestToken(uint callback, ParsedTdu dataType, byte[] data) { // @TODO: To be implemented } - void EpRequestLinkTypeDefs(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestLinkTypeDefs(uint callback, ParsedTdu dataType, byte[] data) { var (_, value) = Codec.ParseSync(dataType, Instance.Warehouse); @@ -827,7 +827,7 @@ partial class EpConnection Instance.Warehouse.Query(resourceLink).Then(queryCallback); } - void EpRequestTypeDefByName(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestTypeDefByName(uint callback, ParsedTdu dataType, byte[] data) { var (_, value) = Codec.ParseSync(dataType, Instance.Warehouse); @@ -846,12 +846,12 @@ partial class EpConnection } } - void EpRequestTypeDefById(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestTypeDefById(uint callback, ParsedTdu dataType, byte[] data) { var (_, value) = Codec.ParseSync(dataType, Instance.Warehouse); - var typeId = (UUID)value; + var typeId = (Uuid)value; var t = Instance.Warehouse.GetTypeDefById(typeId); @@ -868,7 +868,7 @@ partial class EpConnection - void EpRequestTypeDefByResourceId(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestTypeDefByResourceId(uint callback, ParsedTdu dataType, byte[] data) { var (_, value) = Codec.ParseSync(dataType, Instance.Warehouse); @@ -891,7 +891,7 @@ partial class EpConnection - void EpRequestGetResourceIdByLink(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestGetResourceIdByLink(uint callback, ParsedTdu dataType, byte[] data) { var (_, parsed) = Codec.ParseSync(dataType, Instance.Warehouse); var resourceLink = (string)parsed; @@ -919,7 +919,7 @@ partial class EpConnection } - void EpRequestQueryResources(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestQueryResources(uint callback, ParsedTdu dataType, byte[] data) { var (_, parsed) = Codec.ParseSync(dataType, Instance.Warehouse); @@ -977,7 +977,7 @@ partial class EpConnection } - void EpRequestProcedureCall(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestProcedureCall(uint callback, ParsedTdu dataType, byte[] data) { var (offset, length, args) = DataDeserializer.LimitedCountListParser(data, dataType.Offset, dataType.ContentLength, Instance.Warehouse, 1); @@ -1037,12 +1037,12 @@ partial class EpConnection } } - void EpRequestStaticCall(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestStaticCall(uint callback, ParsedTdu dataType, byte[] data) { var (offset, length, args) = DataDeserializer.LimitedCountListParser(data, dataType.Offset, dataType.ContentLength, Instance.Warehouse, 2); - var typeId = new UUID((byte[])args[0]); + var typeId = new Uuid((byte[])args[0]); var index = (byte)args[1]; @@ -1114,7 +1114,7 @@ partial class EpConnection } } - void EpRequestInvokeFunction(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestInvokeFunction(uint callback, ParsedTdu dataType, byte[] data) { var (offset, length, args) = DataDeserializer.LimitedCountListParser(data, dataType.Offset, dataType.ContentLength, Instance.Warehouse, 2); @@ -1466,7 +1466,7 @@ partial class EpConnection } } - void EpRequestSubscribe(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestSubscribe(uint callback, ParsedTdu dataType, byte[] data) { var (offset, length, args) = DataDeserializer.LimitedCountListParser(data, dataType.Offset, @@ -1525,7 +1525,7 @@ partial class EpConnection } - void EpRequestUnsubscribe(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestUnsubscribe(uint callback, ParsedTdu dataType, byte[] data) { var (offset, length, args) = DataDeserializer.LimitedCountListParser(data, dataType.Offset, @@ -1586,7 +1586,7 @@ partial class EpConnection - void EpRequestSetProperty(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestSetProperty(uint callback, ParsedTdu dataType, byte[] data) { var (offset, length, args) = DataDeserializer.LimitedCountListParser(data, dataType.Offset, @@ -1719,7 +1719,7 @@ partial class EpConnection /// /// Type UUID. /// TypeSchema. - public AsyncReply GetTypeDefById(UUID typeId) + public AsyncReply GetTypeDefById(Uuid typeId) { if (typeDefs.ContainsKey(typeId)) return new AsyncReply(typeDefs[typeId]); @@ -1902,7 +1902,7 @@ partial class EpConnection // TypeId, Age, Link, Hops, PropertyValue[] var args = (object[])result; - var typeId = (UUID)args[0]; + var typeId = (Uuid)args[0]; var age = Convert.ToUInt64(args[1]); var link = (string)args[2]; var hops = (byte)args[3]; @@ -2156,7 +2156,7 @@ partial class EpConnection - void EpRequestKeepAlive(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestKeepAlive(uint callback, ParsedTdu dataType, byte[] data) { var (offset, length, args) = DataDeserializer.LimitedCountListParser(data, dataType.Offset, diff --git a/Esiur/Protocol/EpServer.cs b/Esiur/Protocol/EpServer.cs index 14be78f..e846bab 100644 --- a/Esiur/Protocol/EpServer.cs +++ b/Esiur/Protocol/EpServer.cs @@ -59,23 +59,23 @@ public class EpServer : NetworkServer, IResource get => membership; set { - if (membership != null) - membership.Authorization -= Membership_Authorization; + //if (membership != null) + // membership.Authorization -= Membership_Authorization; membership = value; - if (membership != null) - membership.Authorization += Membership_Authorization; + //if (membership != null) + // membership.Authorization += Membership_Authorization; } } - private void Membership_Authorization(AuthorizationIndication indication) - { - lock (Connections.SyncRoot) - foreach (var connection in Connections) - if (connection.Session == indication.Session) - connection.ProcessAuthorization(indication.Results); - } + //private void Membership_Authorization(AuthorizationIndication indication) + //{ + // lock (Connections.SyncRoot) + // foreach (var connection in Connections) + // if (connection.Session == indication.Session) + // connection.ProcessAuthorization(indication.Results); + //} [Attribute] public EntryPoint EntryPoint diff --git a/Esiur/Protocol/EpSession.cs b/Esiur/Protocol/EpSession.cs deleted file mode 100644 index d4b4303..0000000 --- a/Esiur/Protocol/EpSession.cs +++ /dev/null @@ -1,37 +0,0 @@ -/* - -Copyright (c) 2017 Ahmed Kh. Zamil - -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.Generic; -using System.Text; -using Esiur.Net; -using Esiur.Net.Sockets; -using Esiur.Security.Authority; - -namespace Esiur.Protocol; -public class EpSession : NetworkSession -{ - public Source Source { get; set; } - public Authentication Authentication { get; set; } -} diff --git a/Esiur/Proxy/TypeDefGenerator.cs b/Esiur/Proxy/TypeDefGenerator.cs index 091478b..f8bc579 100644 --- a/Esiur/Proxy/TypeDefGenerator.cs +++ b/Esiur/Proxy/TypeDefGenerator.cs @@ -140,28 +140,28 @@ public static class TypeDefGenerator } - static string GetTypeName(TRU tru, TypeDef[] typeDefs) + static string GetTypeName(Tru tru, TypeDef[] typeDefs) { string name; - if (tru.Identifier == TRUIdentifier.TypedResource)// == DataType.Resource) + if (tru.Identifier == TruIdentifier.TypedResource)// == DataType.Resource) name = typeDefs.First(x => x.Id == tru.UUID && (x.Kind == TypeDefKind.Resource)).Name; - else if (tru.Identifier == TRUIdentifier.TypedRecord) + else if (tru.Identifier == TruIdentifier.TypedRecord) name = typeDefs.First(x => x.Id == tru.UUID && x.Kind == TypeDefKind.Record).Name; - else if (tru.Identifier == TRUIdentifier.Enum) + else if (tru.Identifier == TruIdentifier.Enum) name = typeDefs.First(x => x.Id == tru.UUID && x.Kind == TypeDefKind.Enum).Name; - else if (tru.Identifier == TRUIdentifier.TypedList) + else if (tru.Identifier == TruIdentifier.TypedList) name = GetTypeName(tru.SubTypes[0], typeDefs) + "[]"; - else if (tru.Identifier == TRUIdentifier.TypedMap) + else if (tru.Identifier == TruIdentifier.TypedMap) name = "Map<" + GetTypeName(tru.SubTypes[0], typeDefs) + "," + GetTypeName(tru.SubTypes[1], typeDefs) + ">"; - else if (tru.Identifier == TRUIdentifier.Tuple2 || - tru.Identifier == TRUIdentifier.Tuple3 || - tru.Identifier == TRUIdentifier.Tuple4 || - tru.Identifier == TRUIdentifier.Tuple5 || - tru.Identifier == TRUIdentifier.Tuple6 || - tru.Identifier == TRUIdentifier.Tuple7) + else if (tru.Identifier == TruIdentifier.Tuple2 || + tru.Identifier == TruIdentifier.Tuple3 || + tru.Identifier == TruIdentifier.Tuple4 || + tru.Identifier == TruIdentifier.Tuple5 || + tru.Identifier == TruIdentifier.Tuple6 || + tru.Identifier == TruIdentifier.Tuple7) name = "(" + String.Join(",", tru.SubTypes.Select(x => GetTypeName(x, typeDefs))) + ")"; else @@ -169,26 +169,26 @@ public static class TypeDefGenerator name = tru.Identifier switch { - TRUIdentifier.Dynamic => "object", - TRUIdentifier.Bool => "bool", - TRUIdentifier.Char => "char", - TRUIdentifier.DateTime => "DateTime", - TRUIdentifier.Decimal => "decimal", - TRUIdentifier.Float32 => "float", - TRUIdentifier.Float64 => "double", - TRUIdentifier.Int16 => "short", - TRUIdentifier.Int32 => "int", - TRUIdentifier.Int64 => "long", - TRUIdentifier.Int8 => "sbyte", - TRUIdentifier.String => "string", - TRUIdentifier.Map => "Map", - TRUIdentifier.UInt16 => "ushort", - TRUIdentifier.UInt32 => "uint", - TRUIdentifier.UInt64 => "ulong", - TRUIdentifier.UInt8 => "byte", - TRUIdentifier.List => "object[]", - TRUIdentifier.Resource => "IResource", - TRUIdentifier.Record => "IRecord", + TruIdentifier.Dynamic => "object", + TruIdentifier.Bool => "bool", + TruIdentifier.Char => "char", + TruIdentifier.DateTime => "DateTime", + TruIdentifier.Decimal => "decimal", + TruIdentifier.Float32 => "float", + TruIdentifier.Float64 => "double", + TruIdentifier.Int16 => "short", + TruIdentifier.Int32 => "int", + TruIdentifier.Int64 => "long", + TruIdentifier.Int8 => "sbyte", + TruIdentifier.String => "string", + TruIdentifier.Map => "Map", + TruIdentifier.UInt16 => "ushort", + TruIdentifier.UInt32 => "uint", + TruIdentifier.UInt64 => "ulong", + TruIdentifier.UInt8 => "byte", + TruIdentifier.List => "object[]", + TruIdentifier.Resource => "IResource", + TruIdentifier.Record => "IRecord", _ => "object" }; } diff --git a/Esiur/Resource/Storable.cs b/Esiur/Resource/Storable.cs index c91c9aa..c73b7b5 100644 --- a/Esiur/Resource/Storable.cs +++ b/Esiur/Resource/Storable.cs @@ -40,7 +40,7 @@ public class Storable : global::System.Attribute SerializerFunction serializer; DeserializerFunction deserializer; - TRU dataType; + Tru dataType; public Storable() { @@ -57,12 +57,12 @@ public class Storable : global::System.Attribute get { return serializer; } } - public Storable(TRU type) + public Storable(Tru type) { this.dataType = type; } - public Storable(TRU type, SerializerFunction serializer, DeserializerFunction deserializer) + public Storable(Tru type, SerializerFunction serializer, DeserializerFunction deserializer) { this.dataType = type; this.serializer = serializer; diff --git a/Esiur/Resource/TypeIdAttribute.cs b/Esiur/Resource/TypeIdAttribute.cs index dcc52c8..eccf5a3 100644 --- a/Esiur/Resource/TypeIdAttribute.cs +++ b/Esiur/Resource/TypeIdAttribute.cs @@ -8,12 +8,12 @@ namespace Esiur.Resource [AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum)] public class TypeIdAttribute : Attribute { - public UUID Id { get; private set; } + public Uuid Id { get; private set; } public TypeIdAttribute(string id) { var data = DC.FromHex(id, null); - Id = new UUID(data); + Id = new Uuid(data); } } } diff --git a/Esiur/Resource/Warehouse.cs b/Esiur/Resource/Warehouse.cs index 55d4178..eba5f53 100644 --- a/Esiur/Resource/Warehouse.cs +++ b/Esiur/Resource/Warehouse.cs @@ -59,12 +59,12 @@ public class Warehouse uint resourceCounter = 0; - KeyList> typeDefs - = new KeyList>() + KeyList> typeDefs + = new KeyList>() { - [TypeDefKind.Resource] = new KeyList(), - [TypeDefKind.Record] = new KeyList(), - [TypeDefKind.Enum] = new KeyList(), + [TypeDefKind.Resource] = new KeyList(), + [TypeDefKind.Record] = new KeyList(), + [TypeDefKind.Enum] = new KeyList(), }; bool warehouseIsOpen = false; @@ -557,7 +557,7 @@ public class Warehouse /// /// typeId. /// TypeDef. - public TypeDef GetTypeDefById(UUID typeId, TypeDefKind? typeDefKind = null) + public TypeDef GetTypeDefById(Uuid typeId, TypeDefKind? typeDefKind = null) { if (typeDefKind == null) { diff --git a/Esiur/Security/Authority/AlienAuthentication.cs b/Esiur/Security/Authority/AlienAuthentication.cs deleted file mode 100644 index 871ecb8..0000000 --- a/Esiur/Security/Authority/AlienAuthentication.cs +++ /dev/null @@ -1,40 +0,0 @@ -/* - -Copyright (c) 2017 Ahmed Kh. Zamil - -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.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Esiur.Security.Authority; - -public class AlienAuthentication : Authentication -{ - public AlienAuthentication() : - base(AuthenticationType.Alien) - { - - } -} diff --git a/Esiur/Security/Authority/Authentication.cs b/Esiur/Security/Authority/Authentication.cs index ba31855..a065377 100644 --- a/Esiur/Security/Authority/Authentication.cs +++ b/Esiur/Security/Authority/Authentication.cs @@ -32,7 +32,7 @@ namespace Esiur.Security.Authority; public class Authentication { - AuthenticationType type; + AuthenticationMode type; public AuthenticationMethod Method { get; set; } @@ -52,12 +52,12 @@ public class Authentication set; } - public AuthenticationType Type + public AuthenticationMode Type { get => type; } - public Authentication(AuthenticationType type) + public Authentication(AuthenticationMode type) { this.type = type; } diff --git a/Esiur/Security/Authority/AuthenticationMethod.cs b/Esiur/Security/Authority/AuthenticationMethod.cs index 7bb4606..0c5a9a3 100644 --- a/Esiur/Security/Authority/AuthenticationMethod.cs +++ b/Esiur/Security/Authority/AuthenticationMethod.cs @@ -7,7 +7,12 @@ namespace Esiur.Security.Authority; public enum AuthenticationMethod : byte { None, - Credentials, - Token, - Certificate + PpapCredentialsAnonymous, + PpapCredentialsCredentials, + PpapCredentialsHec, + PpapHecAnonymous, + PpapHecCredentials, + PpapHecHec, + HashAnonymous, + } diff --git a/Esiur/Security/Authority/AuthenticationType.cs b/Esiur/Security/Authority/AuthenticationMode.cs similarity index 90% rename from Esiur/Security/Authority/AuthenticationType.cs rename to Esiur/Security/Authority/AuthenticationMode.cs index 6ebb97e..691bd50 100644 --- a/Esiur/Security/Authority/AuthenticationType.cs +++ b/Esiur/Security/Authority/AuthenticationMode.cs @@ -30,10 +30,10 @@ using System.Threading.Tasks; namespace Esiur.Security.Authority; -public enum AuthenticationType +public enum AuthenticationMode:byte { - Host, - CoHost, - Client, - Alien + None = 0x0, + InitializerIdentity = 0x1, + ResponderIdentity = 0x2, + DualIdentity = 0x3, } diff --git a/Esiur/Security/Authority/AuthenticationResult.cs b/Esiur/Security/Authority/AuthenticationResult.cs new file mode 100644 index 0000000..677226d --- /dev/null +++ b/Esiur/Security/Authority/AuthenticationResult.cs @@ -0,0 +1,28 @@ +using Esiur.Core; +using System; +using System.Collections.Generic; +using System.Text; + +namespace Esiur.Security.Authority +{ + public class AuthenticationResult + { + public AuthenticationRuling Ruling { get; internal set; } + public string Identity { get; internal set; } + + public object HandshakePayload { get; internal set; } + + public byte[] SessionKey { get; internal set; } + + public ExceptionCode? ExceptionCode { get; internal set; } + public string ExceptionMessage { get; internal set; } + + public AuthenticationResult(AuthenticationRuling ruling, string identity, object handshakePayload, byte[] sessionKey) + { + Ruling = ruling; + Identity = identity; + HandshakePayload = handshakePayload; + SessionKey = sessionKey; + } + } +} diff --git a/Esiur/Security/Authority/AuthenticationRuling.cs b/Esiur/Security/Authority/AuthenticationRuling.cs new file mode 100644 index 0000000..ba163f5 --- /dev/null +++ b/Esiur/Security/Authority/AuthenticationRuling.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Esiur.Security.Authority +{ + public enum AuthenticationRuling + { + Failed, + InProgress, + Succeeded, + } +} diff --git a/Esiur/Security/Authority/CACertificate.cs b/Esiur/Security/Authority/CACertificate.cs deleted file mode 100644 index 709beb2..0000000 --- a/Esiur/Security/Authority/CACertificate.cs +++ /dev/null @@ -1,201 +0,0 @@ -/* - -Copyright (c) 2017 Ahmed Kh. Zamil - -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 Esiur.Data; -using Esiur.Core; -using Esiur.Misc; -using Esiur.Security.Cryptography; -using Esiur.Security.Integrity; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Security.Cryptography; -using System.Text; -using System.Threading.Tasks; - -namespace Esiur.Security.Authority; - -public class CACertificate : Certificate -{ - - string name; - - public string Name - { - get { return name; } - } - - public CACertificate(byte[] data, uint offset, uint length, bool privateKeyIncluded = false) - : base(0, DateTime.MinValue, DateTime.MinValue, HashFunctionType.MD5) - { - - uint oOffset = offset; - - this.id = DC.GetUInt64(data, offset, Endian.Little); - offset += 8; - this.issueDate = DC.GetDateTime(data, offset, Endian.Little); - offset += 8; - this.expireDate = DC.GetDateTime(data, offset, Endian.Little); - offset += 8; - this.hashFunction = (HashFunctionType)(data[offset++] >> 4); - - - this.name = (Encoding.ASCII.GetString(data, (int)offset + 1, data[offset])); - offset += (uint)data[offset] + 1; - - - var aea = (AsymetricEncryptionAlgorithmType)(data[offset] >> 5); - - if (aea == AsymetricEncryptionAlgorithmType.RSA) - { - var key = new RSAParameters(); - uint exponentLength = (uint)data[offset++] & 0x1F; - - key.Exponent = DC.Clip(data, offset, exponentLength); - - offset += exponentLength; - - uint keySize = DC.GetUInt16(data, offset, Endian.Little); - offset += 2; - - key.Modulus = DC.Clip(data, offset, keySize); - - offset += keySize; - - // copy cert data - this.publicRawData = new byte[offset - oOffset]; - Buffer.BlockCopy(data, (int)oOffset, publicRawData, 0, publicRawData.Length); - - if (privateKeyIncluded) - { - uint privateKeyLength = (keySize * 3) + (keySize / 2); - uint halfKeySize = keySize / 2; - - privateRawData = DC.Clip(data, offset, privateKeyLength); - - key.D = DC.Clip(data, offset, keySize); - offset += keySize; - - key.DP = DC.Clip(data, offset, halfKeySize); - offset += halfKeySize; - - key.DQ = DC.Clip(data, offset, halfKeySize); - offset += halfKeySize; - - - key.InverseQ = DC.Clip(data, offset, halfKeySize); - offset += halfKeySize; - - key.P = DC.Clip(data, offset, halfKeySize); - offset += halfKeySize; - - key.Q = DC.Clip(data, offset, halfKeySize); - offset += halfKeySize; - - } - - // setup rsa - this.rsa = RSA.Create();// new RSACryptoServiceProvider(); - this.rsa.ImportParameters(key); - } - } - - public CACertificate(ulong id, string authorityName, DateTime issueDate, DateTime expireDate, - HashFunctionType hashFunction = HashFunctionType.SHA1, uint ip = 0, byte[] ip6 = null) - : base(id, issueDate, expireDate, hashFunction) - { - // assign type - - BinaryList cr = new BinaryList(); - - // make header - - cr.AddUInt64(id) - .AddDateTime(issueDate) - .AddDateTime(expireDate); - - - // hash function - cr.AddUInt8((byte)((byte)hashFunction << 4)); - this.hashFunction = hashFunction; - - // CA Name - this.name = authorityName; - cr.AddUInt8((byte)(authorityName.Length)) - .AddUInt8Array(Encoding.ASCII.GetBytes(authorityName)); - - // public key - rsa = RSA.Create();// new RSACryptoServiceProvider(2048); - rsa.KeySize = 2048; - RSAParameters dRSAKey = rsa.ExportParameters(true); - - - cr.AddUInt8((byte)dRSAKey.Exponent.Length) - .AddUInt8Array(dRSAKey.Exponent) - .AddUInt16((ushort)dRSAKey.Modulus.Length) - .AddUInt8Array(dRSAKey.Modulus); - - - publicRawData = cr.ToArray(); - - privateRawData = DC.Merge(dRSAKey.D, dRSAKey.DP, dRSAKey.DQ, dRSAKey.InverseQ, dRSAKey.P, dRSAKey.Q); - - } - - public override bool Save(string filename, bool includePrivate = false) - { - try - { - if (includePrivate) - File.WriteAllBytes(filename, new BinaryList() - .AddUInt8((byte)CertificateType.CAPrivate) - .AddUInt8Array(publicRawData) - .AddUInt8Array(privateRawData) - .ToArray()); - else - File.WriteAllBytes(filename, new BinaryList() - .AddUInt8((byte)CertificateType.CAPublic) - .AddUInt8Array(publicRawData).ToArray()); - - return true; - } - catch - { - return false; - } - } - - public override byte[] Serialize(bool includePrivate = false) - { - if (includePrivate) - return new BinaryList() - .AddUInt8Array(publicRawData) - .AddUInt8Array(privateRawData) - .ToArray(); - else - return publicRawData; - } - -} diff --git a/Esiur/Security/Authority/Certificate.cs b/Esiur/Security/Authority/Certificate.cs deleted file mode 100644 index d97e906..0000000 --- a/Esiur/Security/Authority/Certificate.cs +++ /dev/null @@ -1,221 +0,0 @@ -/* - -Copyright (c) 2019 - 2024 Ahmed Kh. Zamil - -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 Esiur.Data; -using Esiur.Core; -using Esiur.Misc; -using Esiur.Security.Cryptography; -using Esiur.Security.Integrity; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Security.Cryptography; -using System.Text; -using System.Threading.Tasks; - -namespace Esiur.Security.Authority; - -public abstract class Certificate -{ - protected DateTime issueDate, expireDate; - protected RSA rsa; - protected Aes aes; - - protected byte[] publicRawData; - protected byte[] privateRawData; - protected ulong id; - protected HashFunctionType hashFunction; - - public Certificate(ulong id, DateTime issueDate, DateTime expireDate, HashFunctionType hashFunction) - { - this.id = id; - this.issueDate = issueDate; - this.expireDate = expireDate; - this.hashFunction = hashFunction; - } - - public ulong Id - { - get { return id; } - } - - public AsymetricEncryptionAlgorithmType AsymetricEncryptionAlgorithm - { - get { return AsymetricEncryptionAlgorithmType.RSA; } - } - - public byte[] AsymetricEncrypt(byte[] message) - { - return rsa.Encrypt(message, RSAEncryptionPadding.OaepSHA512); - } - - - public byte[] AsymetricEncrypt(byte[] message, uint offset, uint length) - { - if (message.Length != length) - return rsa.Encrypt(DC.Clip(message, offset, length), RSAEncryptionPadding.OaepSHA512); - else - return rsa.Encrypt(message, RSAEncryptionPadding.OaepSHA512); - } - - public byte[] AsymetricDecrypt(byte[] message) - { - try - { - return rsa.Decrypt(message, RSAEncryptionPadding.OaepSHA512); - } - catch (Exception ex) - { - Global.Log("Certificate", LogType.Error, ex.ToString()); - return null; - } - } - - public byte[] AsymetricDecrypt(byte[] message, uint offset, uint length) - { - try - { - if (message.Length != length) - return rsa.Decrypt(DC.Clip(message, offset, length), RSAEncryptionPadding.OaepSHA512); - else - return rsa.Decrypt(message, RSAEncryptionPadding.OaepSHA512); - - } - catch (Exception ex) - { - Global.Log("Certificate", LogType.Error, ex.ToString()); - return null; - } - } - - public byte[] SymetricEncrypt(byte[] message, uint offset, uint length) - { - byte[] rt = null; - - using (var ms = new MemoryStream()) - { - using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write)) - cs.Write(message, (int)offset, (int)length); - - rt = ms.ToArray(); - } - - return rt; - } - - public byte[] SymetricEncrypt(byte[] message) - { - return SymetricEncrypt(message, 0, (uint)message.Length); - } - - public byte[] SymetricDecrypt(byte[] message, uint offset, uint length) - { - byte[] rt = null; - - using (var ms = new MemoryStream()) - { - using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write)) - cs.Write(message, (int)offset, (int)length); - - rt = ms.ToArray(); - } - - return rt; - } - - public byte[] SymetricDecrypt(byte[] message) - { - return SymetricDecrypt(message, 0, (uint)message.Length); - } - - public byte[] Sign(byte[] message) - { - return Sign(message, 0, (uint)message.Length); - } - - public byte[] Sign(byte[] message, uint offset, uint length) - { - if (hashFunction == HashFunctionType.SHA1) - return rsa.SignData(message, (int)offset, (int)length, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); - else if (hashFunction == HashFunctionType.MD5) - return rsa.SignData(message, (int)offset, (int)length, HashAlgorithmName.MD5, RSASignaturePadding.Pkcs1); - else if (hashFunction == HashFunctionType.SHA256) - return rsa.SignData(message, (int)offset, (int)length, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); - else if (hashFunction == HashFunctionType.SHA384) - return rsa.SignData(message, (int)offset, (int)length, HashAlgorithmName.SHA384, RSASignaturePadding.Pkcs1); - else if (hashFunction == HashFunctionType.SHA512) - return rsa.SignData(message, (int)offset, (int)length, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1); - - return null; - } - - public bool InitializeSymetricCipher(SymetricEncryptionAlgorithmType algorithm, int keyLength, byte[] key, byte[] iv) - { - if (algorithm == SymetricEncryptionAlgorithmType.AES) - { - if (keyLength == 0) // 128 bit - { - aes = Aes.Create(); - aes.Mode = CipherMode.CBC; - aes.Padding = PaddingMode.PKCS7; - aes.Key = key; - aes.IV = iv; - - return true; - } - } - - return false; - } - - - public abstract bool Save(string filename, bool includePrivate = false); - public abstract byte[] Serialize(bool includePrivate = false); - - public static Certificate Load(string filename) - { - byte[] ar = File.ReadAllBytes(filename); - var t = (CertificateType)ar[0]; - - switch (t) - { - case CertificateType.CAPublic: - return new CACertificate(ar, 1, (uint)ar.Length - 1); - case CertificateType.CAPrivate: - return new CACertificate(ar, 1, (uint)ar.Length - 1, true); - case CertificateType.DomainPublic: - return new DomainCertificate(ar, 1, (uint)ar.Length - 1); - case CertificateType.DomainPrivate: - return new DomainCertificate(ar, 1, (uint)ar.Length - 1, true); - case CertificateType.UserPublic: - return new UserCertificate(ar, 1, (uint)ar.Length - 1); - case CertificateType.UserPrivate: - return new UserCertificate(ar, 1, (uint)ar.Length - 1, true); - } - - return null; - } -} - diff --git a/Esiur/Security/Authority/CertificateType.cs b/Esiur/Security/Authority/CertificateType.cs deleted file mode 100644 index 3178c76..0000000 --- a/Esiur/Security/Authority/CertificateType.cs +++ /dev/null @@ -1,41 +0,0 @@ -/* - -Copyright (c) 2017 Ahmed Kh. Zamil - -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.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Esiur.Security.Authority; - -public enum CertificateType -{ - CAPublic = 0, - CAPrivate, - DomainPublic, - DomainPrivate, - UserPublic, - UserPrivate -} diff --git a/Esiur/Security/Authority/ClientAuthentication.cs b/Esiur/Security/Authority/ClientAuthentication.cs deleted file mode 100644 index ac83935..0000000 --- a/Esiur/Security/Authority/ClientAuthentication.cs +++ /dev/null @@ -1,70 +0,0 @@ -/* - -Copyright (c) 2017 Ahmed Kh. Zamil - -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.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Esiur.Security.Authority; -public class ClientAuthentication : Authentication -{ - /* - string username; - byte[] password; - string domain; - byte[] token; - UserCertificate certificate; - - public string Username => username; - public byte[] Password => password; - //public string Domain => domain; - public byte[] Token => token; - - public byte[] Nounce { get; set; } - */ - - public ClientAuthentication() - : base(AuthenticationType.Client) - { - - } - - - /* - public ClientAuthentication(byte[] token) - : base(AuthenticationType.Client) - { - this.token = token; - } - - public ClientAuthentication(string username, byte[] password) - : base(AuthenticationType.Client) - { - this.username = username; - this.password = password; - //this.domain = domain; - } - */ -} diff --git a/Esiur/Security/Authority/CoHostAuthentication.cs b/Esiur/Security/Authority/CoHostAuthentication.cs deleted file mode 100644 index e29942c..0000000 --- a/Esiur/Security/Authority/CoHostAuthentication.cs +++ /dev/null @@ -1,40 +0,0 @@ -/* - -Copyright (c) 2017 Ahmed Kh. Zamil - -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.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Esiur.Security.Authority; - -public class CoHostAuthentication : Authentication -{ - public CoHostAuthentication() - : base(AuthenticationType.CoHost) - { - - } -} diff --git a/Esiur/Security/Authority/DomainCertificate.cs b/Esiur/Security/Authority/DomainCertificate.cs deleted file mode 100644 index 1f12e05..0000000 --- a/Esiur/Security/Authority/DomainCertificate.cs +++ /dev/null @@ -1,249 +0,0 @@ -/* - -Copyright (c) 2017 Ahmed Kh. Zamil - -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 Esiur.Data; -using Esiur.Misc; -using Esiur.Security.Cryptography; -using Esiur.Security.Integrity; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Security.Cryptography; -using System.Text; -using System.Threading.Tasks; - -namespace Esiur.Security.Authority; - -public class DomainCertificate : Certificate -{ - uint ip; - byte[] ip6; - string domain; - - //CACertificate ca; - string caName; - ulong caId; - byte[] signature; - - string authorityName; - - public string AuthorityName - { - get { return authorityName; } - } - - public string Domain - { - get { return domain; } - } - - public byte[] Signature - { - get { return signature; } - } - - public uint IPAddress - { - get { return ip; } - } - - public byte[] IPv6Address - { - get { return ip6; } - } - - public DomainCertificate(byte[] data, uint offset, uint length, bool privateKeyIncluded = false) - : base(0, DateTime.MinValue, DateTime.MinValue, HashFunctionType.MD5) - { - var oOffset = offset; - - this.id = DC.GetUInt64(data, offset, Endian.Little); - offset += 8; - - // load IPs - this.ip = DC.GetUInt32(data, offset, Endian.Little); - offset += 4; - this.ip6 = DC.Clip(data, offset, 16); - - offset += 16; - - this.issueDate = DC.GetDateTime(data, offset, Endian.Little); - offset += 8; - this.expireDate = DC.GetDateTime(data, offset, Endian.Little); - offset += 8; - - this.domain = Encoding.ASCII.GetString(data, (int)offset + 1, data[offset]); - offset += (uint)data[offset] + 1; - - this.authorityName = (Encoding.ASCII.GetString(data, (int)offset + 1, data[offset])); - offset += (uint)data[offset] + 1; - - caId = DC.GetUInt64(data, offset, Endian.Little); - offset += 8; - - var aea = (AsymetricEncryptionAlgorithmType)(data[offset] >> 5); - - if (aea == AsymetricEncryptionAlgorithmType.RSA) - { - var key = new RSAParameters(); - uint exponentLength = (uint)data[offset++] & 0x1F; - - key.Exponent = DC.Clip(data, offset, exponentLength); - offset += exponentLength; - - uint keySize = DC.GetUInt16(data, offset, Endian.Little); - offset += 2; - - key.Modulus = DC.Clip(data, offset, keySize); - - offset += keySize; - - // copy cert data - publicRawData = new byte[offset - oOffset]; - Buffer.BlockCopy(data, (int)oOffset, publicRawData, 0, publicRawData.Length); - - if (privateKeyIncluded) - { - - uint privateKeyLength = (keySize * 3) + (keySize / 2); - privateRawData = DC.Clip(data, offset, privateKeyLength); - - uint halfKeySize = keySize / 2; - - key.D = DC.Clip(data, offset, keySize); - offset += keySize; - key.DP = DC.Clip(data, offset, halfKeySize); - offset += halfKeySize; - key.DQ = DC.Clip(data, offset, halfKeySize); - offset += halfKeySize; - key.InverseQ = DC.Clip(data, offset, halfKeySize); - offset += halfKeySize; - key.P = DC.Clip(data, offset, halfKeySize); - offset += halfKeySize; - key.Q = DC.Clip(data, offset, halfKeySize); - offset += halfKeySize; - - } - - // setup rsa - rsa = RSA.Create();// new RSACryptoServiceProvider(); - rsa.ImportParameters(key); - - this.signature = DC.Clip(data, offset, length - (offset - oOffset)); - - } - - } - - public DomainCertificate(ulong id, string domain, CACertificate authority, DateTime issueDate, - DateTime expireDate, HashFunctionType hashFunction = HashFunctionType.SHA1, uint ip = 0, byte[] ip6 = null) - : base(id, issueDate, expireDate, hashFunction) - { - // assign type - - var cr = new BinaryList(); - - // id - cr.AddUInt64(id); - - // ip - this.ip = ip; - this.ip6 = ip6; - - cr.AddUInt32(ip); - - - if (ip6?.Length == 16) - cr.AddUInt8Array(ip6); - else - cr.AddUInt8Array(new byte[16]); - - - cr.AddDateTime(issueDate) - .AddDateTime(expireDate); - - // domain - this.domain = domain; - cr.AddUInt8((byte)(domain.Length)) - .AddUInt8Array(Encoding.ASCII.GetBytes(domain)); - - // CA - this.caName = authority.Name; - cr.AddUInt8((byte)(authority.Name.Length)) - .AddUInt8Array(Encoding.ASCII.GetBytes(authority.Name)); - - this.authorityName = authority.Name; - - // CA Index - //co.KeyIndex = authority.KeyIndex; - this.caId = authority.Id; - cr.AddUInt64(caId); - - - // public key - rsa = RSA.Create();// new RSACryptoServiceProvider(2048); - rsa.KeySize = 2048; - RSAParameters dRSAKey = rsa.ExportParameters(true); - cr.AddUInt8((byte)dRSAKey.Exponent.Length) - .AddUInt8Array(dRSAKey.Exponent) - .AddUInt16((ushort)dRSAKey.Modulus.Length) - .AddUInt8Array(dRSAKey.Modulus); - - - publicRawData = cr.ToArray(); - - // private key - this.privateRawData = DC.Merge(dRSAKey.D, dRSAKey.DP, dRSAKey.DQ, dRSAKey.InverseQ, dRSAKey.P, dRSAKey.Q); - - this.signature = authority.Sign(publicRawData); - - } - - public override bool Save(string filename, bool includePrivate = false) - { - try - { - if (includePrivate) - File.WriteAllBytes(filename, DC.Merge(new byte[] { (byte)CertificateType.DomainPrivate }, publicRawData, signature, privateRawData)); - else - File.WriteAllBytes(filename, DC.Merge(new byte[] { (byte)CertificateType.DomainPublic }, publicRawData, signature)); - - return true; - } - catch - { - return false; - } - } - - public override byte[] Serialize(bool includePrivate = false) - { - if (includePrivate) - return DC.Merge(publicRawData, signature, privateRawData); - else - return DC.Merge(publicRawData, signature); - } - -} diff --git a/Esiur/Security/Authority/HostAuthentication.cs b/Esiur/Security/Authority/HostAuthentication.cs deleted file mode 100644 index c774cc8..0000000 --- a/Esiur/Security/Authority/HostAuthentication.cs +++ /dev/null @@ -1,41 +0,0 @@ -/* - -Copyright (c) 2017 Ahmed Kh. Zamil - -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.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Esiur.Security.Authority; -public class HostAuthentication : Authentication -{ - - public HostAuthentication() - : base(AuthenticationType.Host) - { - - } - -} diff --git a/Esiur/Security/Authority/IAuthenticationHandler.cs b/Esiur/Security/Authority/IAuthenticationHandler.cs new file mode 100644 index 0000000..aa84d6b --- /dev/null +++ b/Esiur/Security/Authority/IAuthenticationHandler.cs @@ -0,0 +1,18 @@ +using Esiur.Net.Packets; +using System; +using System.Collections.Generic; +using System.Text; + +namespace Esiur.Security.Authority +{ + public interface IAuthenticationHandler + { + public AuthenticationResult Initialize(Session session); + + public AuthenticationResult Process(object handshakePayload); + + public void Terminate(Session session); + + public void Update(Session session, object authData); + } +} diff --git a/Esiur/Security/Authority/IAuthenticationInitiator.cs b/Esiur/Security/Authority/IAuthenticationInitiator.cs new file mode 100644 index 0000000..a926b50 --- /dev/null +++ b/Esiur/Security/Authority/IAuthenticationInitiator.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Esiur.Security.Authority +{ + public interface IAuthenticationInitiator + { + public AuthenticationResult Initiate(Session session); + + public AuthenticationResult Process(object handshakePayload); + } +} diff --git a/Esiur/Security/Authority/IAuthenticationResponder.cs b/Esiur/Security/Authority/IAuthenticationResponder.cs new file mode 100644 index 0000000..e52d0a8 --- /dev/null +++ b/Esiur/Security/Authority/IAuthenticationResponder.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Esiur.Security.Authority +{ + public interface IAuthenticationResponder + { + public AuthenticationResult Process(Session session); + + } +} diff --git a/Esiur/Security/Authority/Session.cs b/Esiur/Security/Authority/Session.cs index cc387af..c804c0e 100644 --- a/Esiur/Security/Authority/Session.cs +++ b/Esiur/Security/Authority/Session.cs @@ -31,7 +31,6 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using Esiur.Security.Cryptography; -using static System.Collections.Specialized.BitVector32; using Esiur.Net.Packets; namespace Esiur.Security.Authority; @@ -44,21 +43,21 @@ public class Session - public IKeyExchanger KeyExchanger { get; set; } = null; + //public IKeyExchanger KeyExchanger { get; set; } = null; public ISymetricCipher SymetricCipher { get; set; } = null; public Map LocalHeaders { get; set; } = new Map(); public Map RemoteHeaders { get; set; } = new Map(); - public AuthenticationMethod LocalMethod { get; set; } - public AuthenticationMethod RemoteMethod { get; set; } + //public AuthenticationMethod AuthenticationMethod { get; set; } + //public AuthenticationMethod RemoteMethod { get; set; } - public AuthenticationType AuthenticationType { get; set; } + public AuthenticationMode AuthenticationMode { get; set; } + public EncryptionMode EncryptionMode { get; set; } + public IAuthenticationHandler AuthenticationHandler { get; set; } + //public IAuthenticationHandler AuthenticationResponder { get; set; } - public string AuthorizedAccount { get; set; } - - - + public string AuthorizedIdentity { get; set; } } diff --git a/Esiur/Security/Cryptography/EncryptionMode.cs b/Esiur/Security/Cryptography/EncryptionMode.cs new file mode 100644 index 0000000..0b5ff59 --- /dev/null +++ b/Esiur/Security/Cryptography/EncryptionMode.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Esiur.Security.Cryptography +{ + public enum EncryptionMode + { + None, + EncryptWithSessionKey, + EncryptWithSessionKeyAndAddress, + } + +} diff --git a/Tests/Distribution/Program.cs b/Tests/Distribution/Program.cs index 6b5b940..ecb9938 100644 --- a/Tests/Distribution/Program.cs +++ b/Tests/Distribution/Program.cs @@ -24,7 +24,7 @@ SOFTWARE. using Esiur.Data; using Esiur.Core; -using Esiur.Net.HTTP; +using Esiur.Net.Http; using Esiur.Net.Sockets; using Esiur.Resource; using Esiur.Security.Permissions; @@ -148,7 +148,7 @@ class Program var server = await wh.Put("sys/server", new EpServer() { Membership = membership }); - var web = await wh.Put("sys/web", new HTTPServer() { Port = 8088 }); + var web = await wh.Put("sys/web", new HttpServer() { Port = 8088 }); var service = await wh.Put("sys/service", new MyService()); var res1 = await wh.Put("sys/service/r1", new MyResource() { Description = "Testing 1", CategoryId = 10 }); @@ -177,7 +177,7 @@ class Program // sender.Send("Not found"); //}); - web.MapGet("/", (HTTPConnection sender) => + web.MapGet("/", (HttpConnection sender) => { sender.Send("Hello"); });