2
0
mirror of https://github.com/esiur/esiur-dotnet.git synced 2026-04-03 20:08:21 +00:00
This commit is contained in:
2026-04-02 19:42:54 +03:00
parent 4fae21deaf
commit 74830eea0c
82 changed files with 2501 additions and 3008 deletions

View File

@@ -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<HTTPServer>("sys/http", new HTTPServer() { Port = 8888 });
var http = await wh.Put<HttpServer>("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();
}

View File

@@ -64,7 +64,7 @@ public class BinaryList
}
public BinaryList AddUUID(UUID value)
public BinaryList AddUUID(Uuid value)
{
list.AddRange(value.Data);
return this;

View File

@@ -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<Type, Composer> Composers = new Dictionary<Type, Composer>()
{
@@ -347,7 +347,7 @@ public static class Codec
//[typeof(List<byte?>)] = 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<object>)] = 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);
}

View File

@@ -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)

View File

@@ -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<object>();
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<object>();
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<IRecord>();
@@ -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<IRecord>();
@@ -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<IResource>();
@@ -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<IResource>();
@@ -771,7 +771,7 @@ public static class DataDeserializer
return rt.ToArray();
}
public static AsyncBag<object> ListParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence)
public static AsyncBag<object> ListParserAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence)
{
//var rt = new AsyncBag<object>();
@@ -806,8 +806,8 @@ public static class DataDeserializer
//var list = new List<object>();
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<object>();
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<object>();
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<TRU>();
var trus = new List<Tru>();
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<object>();
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<TRU>();
var trus = new List<Tru>();
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<object>();
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<PropertyValue>();
ListParserAsync(new ParsedTDU() { Data = data, Offset = offset, ContentLength = length }
ListParserAsync(new ParsedTdu() { Data = data, Offset = offset, ContentLength = length }
, connection, requestSequence).Then(x =>
{

View File

@@ -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<byte>;
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<int>)value);
}
else if (tru.Identifier == TRUIdentifier.Int64)
else if (tru.Identifier == TruIdentifier.Int64)
{
composed = GroupInt64Codec.Encode((IList<long>)value);
}
else if (tru.Identifier == TRUIdentifier.Int16)
else if (tru.Identifier == TruIdentifier.Int16)
{
composed = GroupInt16Codec.Encode((IList<short>)value);
}
else if (tru.Identifier == TRUIdentifier.UInt32)
else if (tru.Identifier == TruIdentifier.UInt32)
{
composed = GroupUInt32Codec.Encode((IList<uint>)value);
}
else if (tru.Identifier == TRUIdentifier.UInt64)
else if (tru.Identifier == TruIdentifier.UInt64)
{
composed = GroupUInt64Codec.Encode((IList<ulong>)value);
}
else if (tru.Identifier == TRUIdentifier.UInt16)
else if (tru.Identifier == TruIdentifier.UInt16)
{
composed = GroupUInt16Codec.Encode((IList<ushort>)value);
}
else if (tru.Identifier == TRUIdentifier.Enum)
else if (tru.Identifier == TruIdentifier.Enum)
{
var rt = new List<byte>();
@@ -587,21 +587,21 @@ public static class DataSerializer
{
var rt = new List<byte>();
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<byte>();
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<byte>();
@@ -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<byte>();
@@ -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<byte>();
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<byte>();
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<byte>();
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<byte>();
@@ -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());
}

View File

@@ -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,

View File

@@ -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))

View File

@@ -4,7 +4,7 @@ using System.Text;
namespace Esiur.Data
{
public enum TDUClass
public enum TduClass
{
Fixed = 0x0,
Dynamic = 0x1,

View File

@@ -4,7 +4,7 @@ using System.Text;
namespace Esiur.Data
{
public enum TDUIdentifier
public enum TduIdentifier
{
Null = 0x0,
False = 0x1,

View File

@@ -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<TDUIdentifier, TRUIdentifier> typesMap = new Map<TDUIdentifier, TRUIdentifier>()
static Map<TduIdentifier, TruIdentifier> typesMap = new Map<TduIdentifier, TruIdentifier>()
{
[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<Type, TRU> _cache = new Dictionary<Type, TRU>();
private static Dictionary<Type, Tru> _cache = new Dictionary<Type, Tru>();
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<object, object>)
|| type == typeof(Dictionary<object, object>))
{
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));
}
}

View File

@@ -4,7 +4,7 @@ using System.Text;
namespace Esiur.Data
{
public enum TRUIdentifier
public enum TruIdentifier
{
Void = 0x0,
Dynamic = 0x1,

View File

@@ -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;

View File

@@ -13,7 +13,7 @@ public class ConstantDef : MemberDef
public object Value { get; set; }
public Map<string, string> 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<AnnotationAttribute>(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}`");

View File

@@ -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}`");

View File

@@ -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}`");

View File

@@ -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}`");

View File

@@ -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<string, string> 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<TypeIdAttribute>();
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;
}

View File

@@ -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);
}

View File

@@ -39,6 +39,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="BouncyCastle.Cryptography" Version="2.6.2" />
<PackageReference Include="Microsoft.Bcl.AsyncInterfaces" Version="10.0.2" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.14.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="4.14.0" PrivateAssets="all" />
@@ -60,6 +61,10 @@
<ItemGroup>
<Compile Remove="Data\NullabilityInfo.cs" />
<Compile Remove="Data\NullabilityInfoContext.cs" />
<Compile Remove="Net\Packets\EpAuthPacketAuthMode.cs" />
<Compile Remove="Security\Authority\AuthenticationMethod.cs" />
<Compile Remove="Security\Authority\IAuthenticationInitiator.cs" />
<Compile Remove="Security\Authority\IAuthenticationResponder.cs" />
</ItemGroup>
@@ -69,7 +74,11 @@
<None Include="Data\Types\ArgumentDef.cs" />
<None Include="Data\Types\AttributeDef.cs" />
<None Include="LICENSE" Pack="true" PackagePath=""></None>
<None Include="Net\Packets\EpAuthPacketAuthMode.cs" />
<None Include="README.md" Pack="true" PackagePath="" />
<None Include="Security\Authority\AuthenticationMethod.cs" />
<None Include="Security\Authority\IAuthenticationInitiator.cs" />
<None Include="Security\Authority\IAuthenticationResponder.cs" />
</ItemGroup>

View File

@@ -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<string, object> Variables { get; } = new KeyList<string, object>();
@@ -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);

View File

@@ -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<bool> Execute(HTTPConnection sender);
public abstract AsyncReply<bool> 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;
}

View File

@@ -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<HTTPConnection>, IResource
namespace Esiur.Net.Http;
public class HttpServer : NetworkServer<HttpConnection>, IResource
{
Dictionary<string, HTTPSession> sessions = new Dictionary<string, HTTPSession>();
HTTPFilter[] filters = new HTTPFilter[0];
Dictionary<string, HttpSession> sessions = new Dictionary<string, HttpSession>();
HttpFilter[] filters = new HttpFilter[0];
Dictionary<HTTPMethod, List<RouteInfo>> routes = new()
Dictionary<Packets.Http.HttpMethod, List<RouteInfo>> routes = new()
{
[HTTPMethod.GET] = new List<RouteInfo>(),
[HTTPMethod.POST] = new List<RouteInfo>(),
[HTTPMethod.HEAD] = new List<RouteInfo>(),
[HTTPMethod.OPTIONS] = new List<RouteInfo>(),
[HTTPMethod.UNKNOWN] = new List<RouteInfo>(),
[HTTPMethod.DELETE] = new List<RouteInfo>(),
[HTTPMethod.TRACE] = new List<RouteInfo>(),
[HTTPMethod.CONNECT] = new List<RouteInfo>(),
[HTTPMethod.PUT] = new List<RouteInfo>()
[Packets.Http.HttpMethod.GET] = new List<RouteInfo>(),
[Packets.Http.HttpMethod.POST] = new List<RouteInfo>(),
[Packets.Http.HttpMethod.HEAD] = new List<RouteInfo>(),
[Packets.Http.HttpMethod.OPTIONS] = new List<RouteInfo>(),
[Packets.Http.HttpMethod.UNKNOWN] = new List<RouteInfo>(),
[Packets.Http.HttpMethod.DELETE] = new List<RouteInfo>(),
[Packets.Http.HttpMethod.TRACE] = new List<RouteInfo>(),
[Packets.Http.HttpMethod.CONNECT] = new List<RouteInfo>(),
[Packets.Http.HttpMethod.PUT] = new List<RouteInfo>()
};
//List<RouteInfo> GetRoutes = new List<RouteInfo>();
@@ -86,7 +86,7 @@ public class HTTPServer : NetworkServer<HTTPConnection>, 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<HTTPConnection>, 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<HTTPConnection>, 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<HTTPConnection>, 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<HTTPConnection>, 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<HTTPConnection>, 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<HTTPConnection>, IResource
}
else if (trigger == ResourceTrigger.SystemInitialized)
{
filters = await Instance.Children<HTTPFilter>();
filters = await Instance.Children<HttpFilter>();
}
return true;
@@ -337,19 +337,19 @@ public class HTTPServer : NetworkServer<HTTPConnection>, 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.)
//{

View File

@@ -35,11 +35,11 @@ using Esiur.Data;
using Esiur.Misc;
using Esiur.Core;
namespace Esiur.Net.HTTP;
public class HTTPSession : IDestructible //<T> where T : TClient
namespace Esiur.Net.Http;
public class HttpSession : IDestructible //<T> 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 //<T> where T : TClient
get { return variables; }
}
public HTTPSession()
public HttpSession()
{
variables = new KeyList<string, object>();
variables.OnModified += new KeyList<string, object>.Modified(VariablesModified);

View File

@@ -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<bool> Execute(HTTPConnection sender)
public override AsyncReply<bool> Execute(HttpConnection sender)
{
if (sender.Request.URL != "EP")
return new AsyncReply<bool>(false);

View File

@@ -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<bool> Execute(HTTPConnection sender)
public override AsyncReply<bool> Execute(HttpConnection sender)
{
if (sender.IsWebsocketRequest())

View File

@@ -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;

View File

@@ -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,
}
}

View File

@@ -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
}
}

View File

@@ -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,
}
}

View File

@@ -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,
}
}

View File

@@ -11,5 +11,4 @@ namespace Esiur.Net.Packets
Action = 0x2,
Event = 0x3,
}
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Esiur.Net.Packets
{
public enum EpAuthPacketEncryptionMode
{
NoEncryption,
EncryptWithSessionKey,
EncryptWithSessionKeyAndAddress,
}
}

View File

@@ -1,12 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Esiur.Net.Packets
{
public enum EpAuthPacketHashAlgorithm
{
SHA256,
SHA3,
}
}

View File

@@ -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,
}
}

View File

@@ -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,
}
}

View File

@@ -1,12 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Esiur.Net.Packets
{
public enum EpAuthPacketPublicKeyAlgorithm
{
RSA = 0,
CKKS = 1,
}
}

View File

@@ -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;

View File

@@ -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;

View File

@@ -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,

View File

@@ -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;

View File

@@ -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,

View File

@@ -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
{

View File

@@ -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,

View File

@@ -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<HTTPCookie> Cookies { get; } = new List<HTTPCookie>();
public List<HttpCookie> Cookies { get; } = new List<HttpCookie>();
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<byte> msg = new List<byte>();
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++)
{

View File

@@ -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<byte> 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<byte> 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<byte> 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<byte> 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<byte> 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<byte> seed = seedLength <= 128
? stackalloc byte[seedLength]
: new byte[seedLength];
#else
byte[] seed = new byte[seedLength];
#endif
MasterRandom.NextBytes(seed);
generator.AddSeedMaterial(seed);
}
}
}

View File

@@ -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());
}
}
}

View File

@@ -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<byte> 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<byte> 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<byte> 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<byte> 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<byte> 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<byte> seed = seedLength <= 128
? stackalloc byte[seedLength]
: new byte[seedLength];
#else
byte[] seed = new byte[seedLength];
#endif
MasterRandom.NextBytes(seed);
generator.AddSeedMaterial(seed);
}
}
}

View File

@@ -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<string, object> variables = new KeyList<string, object>();
public TCPServer Server { get; internal set; }
public TcpServer Server { get; internal set; }
public KeyList<string, object> Variables
{

View File

@@ -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<bool> 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()
{

View File

@@ -34,8 +34,8 @@ using Esiur.Core;
using System.Net;
using Esiur.Resource;
namespace Esiur.Net.TCP;
public class TCPServer : NetworkServer<TCPConnection>, IResource
namespace Esiur.Net.Tcp;
public class TcpServer : NetworkServer<TcpConnection>, IResource
{
[Attribute]
@@ -64,7 +64,7 @@ public class TCPServer : NetworkServer<TCPConnection>, IResource
//}
public Instance Instance { get; set; }
TCPFilter[] filters = null;
TcpFilter[] filters = null;
public AsyncReply<bool> Trigger(ResourceTrigger trigger)
{
@@ -93,7 +93,7 @@ public class TCPServer : NetworkServer<TCPConnection>, IResource
}
else if (trigger == ResourceTrigger.SystemInitialized)
{
Instance.Children<TCPFilter>().Then(x => filters = x);
Instance.Children<TcpFilter>().Then(x => filters = x);
}
return new AsyncReply<bool>(true);
@@ -103,7 +103,7 @@ public class TCPServer : NetworkServer<TCPConnection>, 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<TCPConnection>, 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<TCPConnection>, 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;

View File

@@ -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
{
}

View File

@@ -33,7 +33,7 @@ using Esiur.Core;
using Esiur.Resource;
namespace Esiur.Net.UDP;
public abstract class UDPFilter : IResource
public abstract class UdpFilter : IResource
{

View File

@@ -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<UDPFilter>();
filters = await Instance.Children<UdpFilter>();
}
return true;

View File

@@ -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();
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -50,12 +50,12 @@ partial class EpConnection
KeyList<uint, WeakReference<EpResource>> suspendedResources = new KeyList<uint, WeakReference<EpResource>>();
KeyList<uint, EpResourceAttachRequestInfo> resourceRequests = new KeyList<uint, EpResourceAttachRequestInfo>();
KeyList<UUID, AsyncReply<TypeDef>> typeDefsByIdRequests = new KeyList<UUID, AsyncReply<TypeDef>>();
KeyList<Uuid, AsyncReply<TypeDef>> typeDefsByIdRequests = new KeyList<Uuid, AsyncReply<TypeDef>>();
KeyList<string, AsyncReply<TypeDef>> typeDefsByNameRequests = new KeyList<string, AsyncReply<TypeDef>>();
Dictionary<UUID, TypeDef> typeDefs = new Dictionary<UUID, TypeDef>();
Dictionary<Uuid, TypeDef> typeDefs = new Dictionary<Uuid, TypeDef>();
KeyList<uint, AsyncReply> requests = new KeyList<uint, AsyncReply>();
@@ -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
/// </summary>
/// <param name="typeId">Type UUID.</param>
/// <returns>TypeSchema.</returns>
public AsyncReply<TypeDef> GetTypeDefById(UUID typeId)
public AsyncReply<TypeDef> GetTypeDefById(Uuid typeId)
{
if (typeDefs.ContainsKey(typeId))
return new AsyncReply<TypeDef>(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,

View File

@@ -59,23 +59,23 @@ public class EpServer : NetworkServer<EpConnection>, 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

View File

@@ -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; }
}

View File

@@ -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<object, object>",
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<object, object>",
TruIdentifier.UInt16 => "ushort",
TruIdentifier.UInt32 => "uint",
TruIdentifier.UInt64 => "ulong",
TruIdentifier.UInt8 => "byte",
TruIdentifier.List => "object[]",
TruIdentifier.Resource => "IResource",
TruIdentifier.Record => "IRecord",
_ => "object"
};
}

View File

@@ -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;

View File

@@ -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);
}
}
}

View File

@@ -59,12 +59,12 @@ public class Warehouse
uint resourceCounter = 0;
KeyList<TypeDefKind, KeyList<UUID, TypeDef>> typeDefs
= new KeyList<TypeDefKind, KeyList<UUID, TypeDef>>()
KeyList<TypeDefKind, KeyList<Uuid, TypeDef>> typeDefs
= new KeyList<TypeDefKind, KeyList<Uuid, TypeDef>>()
{
[TypeDefKind.Resource] = new KeyList<UUID, TypeDef>(),
[TypeDefKind.Record] = new KeyList<UUID, TypeDef>(),
[TypeDefKind.Enum] = new KeyList<UUID, TypeDef>(),
[TypeDefKind.Resource] = new KeyList<Uuid, TypeDef>(),
[TypeDefKind.Record] = new KeyList<Uuid, TypeDef>(),
[TypeDefKind.Enum] = new KeyList<Uuid, TypeDef>(),
};
bool warehouseIsOpen = false;
@@ -557,7 +557,7 @@ public class Warehouse
/// </summary>
/// <param name="typeId">typeId.</param>
/// <returns>TypeDef.</returns>
public TypeDef GetTypeDefById(UUID typeId, TypeDefKind? typeDefKind = null)
public TypeDef GetTypeDefById(Uuid typeId, TypeDefKind? typeDefKind = null)
{
if (typeDefKind == null)
{

View File

@@ -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)
{
}
}

View File

@@ -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;
}

View File

@@ -7,7 +7,12 @@ namespace Esiur.Security.Authority;
public enum AuthenticationMethod : byte
{
None,
Credentials,
Token,
Certificate
PpapCredentialsAnonymous,
PpapCredentialsCredentials,
PpapCredentialsHec,
PpapHecAnonymous,
PpapHecCredentials,
PpapHecHec,
HashAnonymous,
}

View File

@@ -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,
}

View File

@@ -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;
}
}
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Esiur.Security.Authority
{
public enum AuthenticationRuling
{
Failed,
InProgress,
Succeeded,
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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
}

View File

@@ -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;
}
*/
}

View File

@@ -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)
{
}
}

View File

@@ -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);
}
}

View File

@@ -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)
{
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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<EpAuthPacketHeader, object> LocalHeaders { get; set; } = new Map<EpAuthPacketHeader, object>();
public Map<EpAuthPacketHeader, object> RemoteHeaders { get; set; } = new Map<EpAuthPacketHeader, object>();
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; }
}

View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Esiur.Security.Cryptography
{
public enum EncryptionMode
{
None,
EncryptWithSessionKey,
EncryptWithSessionKeyAndAddress,
}
}

View File

@@ -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");
});