Compare commits
2 Commits
6de712910f
...
bf4924c4d6
| Author | SHA1 | Date | |
|---|---|---|---|
| bf4924c4d6 | |||
| acaf5fee14 |
8
.gitignore
vendored
8
.gitignore
vendored
@ -21,3 +21,11 @@
|
||||
|
||||
#backups
|
||||
.old*/
|
||||
|
||||
#secrets
|
||||
*.pem
|
||||
*.key
|
||||
*.csr
|
||||
*.crt
|
||||
*.pfx
|
||||
*.config.json
|
||||
|
||||
@ -1,14 +1,14 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<Version>1.0.0</Version>
|
||||
<Version>0.0.1</Version>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Meum.Client\Meum.Client.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="DTLib" Version="1.6.0" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@ -8,6 +8,7 @@ using System.Reflection;
|
||||
using DTLib.Console;
|
||||
using DTLib.Demystifier;
|
||||
using DTLib.Extensions;
|
||||
using DTLib.Logging;
|
||||
|
||||
namespace Meum.Client.CLI;
|
||||
|
||||
@ -33,51 +34,70 @@ class Program
|
||||
{
|
||||
Console.OutputEncoding = StringConverter.UTF8;
|
||||
Console.InputEncoding = StringConverter.UTF8;
|
||||
ColoredConsole.ResetColor();
|
||||
var v = Assembly.GetExecutingAssembly().GetName().Version;
|
||||
string title = $"Meum CLI v{v?.ToString(3) ?? "Null"}";
|
||||
Console.Title = title;
|
||||
ColoredConsole.WriteTitle(title, '=', fg: ConsoleColor.Cyan);
|
||||
ColoredConsole.WriteLine(greeting_art, fg: ConsoleColor.Magenta);
|
||||
ColoredConsole.WriteHLine('=', fg: ConsoleColor.Cyan);
|
||||
|
||||
UserAddress? userAddress = null;
|
||||
DnsEndPoint? serverEndPoint = null;
|
||||
string? serverAddress = null;
|
||||
while (true)
|
||||
ColoredConsole.Clear();
|
||||
var loggerRoot = new ConsoleLogger();
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
if(userAddress == null)
|
||||
{
|
||||
var addrstr = ColoredConsole.ReadLine("enter user address (name@server.xyz)", ConsoleColor.Blue);
|
||||
if (string.IsNullOrEmpty(addrstr))
|
||||
continue;
|
||||
userAddress = new(addrstr);
|
||||
}
|
||||
Client client = new(userAddress);
|
||||
if(serverEndPoint == null)
|
||||
{
|
||||
serverAddress = ColoredConsole.ReadLine("enter server address (server.xyz)", ConsoleColor.Blue);
|
||||
if (string.IsNullOrEmpty(serverAddress))
|
||||
{
|
||||
ColoredConsole.WriteLine("null address", ConsoleColor.Red);
|
||||
continue;
|
||||
}
|
||||
serverEndPoint = Network.ParseDnsEndPoint(serverAddress);
|
||||
ColoredConsole.WriteTitle(serverAddress, fg: ConsoleColor.Cyan);
|
||||
}
|
||||
var v = Assembly.GetExecutingAssembly().GetName().Version;
|
||||
string title = $"Meum CLI v{v?.ToString(3) ?? "Null"}";
|
||||
Console.Title = title;
|
||||
|
||||
ColoredConsole.WriteLine("connecting to the server...", ConsoleColor.Blue);
|
||||
var conn = await client.ConnectToServerAsync(serverEndPoint);
|
||||
await conn.PingAsync();
|
||||
await Task.Delay(-1);
|
||||
}
|
||||
catch (Exception ex)
|
||||
Functions.InitMsQuic(loggerRoot);
|
||||
|
||||
ColoredConsole.WriteTitle(title, '=', fg: ConsoleColor.Cyan);
|
||||
ColoredConsole.WriteLine(greeting_art, fg: ConsoleColor.Magenta);
|
||||
ColoredConsole.WriteHLine('=', fg: ConsoleColor.Cyan);
|
||||
|
||||
UserAddress? userAddress = null;
|
||||
DnsEndPoint? serverEndPoint = null;
|
||||
string? serverAddress = null;
|
||||
while (true)
|
||||
{
|
||||
ColoredConsole.WriteLine(ex.ToStringDemystified(), ConsoleColor.Red);
|
||||
try
|
||||
{
|
||||
if (userAddress == null)
|
||||
{
|
||||
ColoredConsole.Write("enter user address (name@server.xyz): ", ConsoleColor.Blue);
|
||||
var addrstr = ColoredConsole.ReadLine(ConsoleColor.Cyan);
|
||||
if (string.IsNullOrEmpty(addrstr))
|
||||
continue;
|
||||
userAddress = new(addrstr);
|
||||
}
|
||||
|
||||
Client client = new(loggerRoot);
|
||||
if (serverEndPoint == null)
|
||||
{
|
||||
ColoredConsole.Write("enter server address (server.xyz): ", ConsoleColor.Blue);
|
||||
serverAddress = ColoredConsole.ReadLine(ConsoleColor.Cyan);
|
||||
if (string.IsNullOrEmpty(serverAddress))
|
||||
{
|
||||
ColoredConsole.WriteLine("null address", ConsoleColor.Red);
|
||||
continue;
|
||||
}
|
||||
|
||||
serverEndPoint = Functions.ParseDnsEndPoint(serverAddress);
|
||||
ColoredConsole.WriteTitle(serverAddress, fg: ConsoleColor.Cyan);
|
||||
}
|
||||
|
||||
ColoredConsole.WriteLine("connecting to the server...", ConsoleColor.Blue);
|
||||
var conn = await client.ConnectToServerAsync(serverEndPoint);
|
||||
ColoredConsole.WriteLine("Connected to server", ConsoleColor.Green);
|
||||
|
||||
await Task.Delay(-1);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ColoredConsole.WriteLine(ex.ToStringDemystified(), ConsoleColor.Red);
|
||||
}
|
||||
}
|
||||
}
|
||||
// ColoredConsole.ResetColor();
|
||||
catch (Exception ex)
|
||||
{
|
||||
ColoredConsole.WriteLine(ex.ToStringDemystified(), ConsoleColor.Red);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Console.ResetColor();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -4,26 +4,63 @@ global using System.Threading;
|
||||
global using System.Threading.Tasks;
|
||||
global using Meum.Core;
|
||||
using System.Net;
|
||||
using System.Net.Quic;
|
||||
using System.Net.Security;
|
||||
using DTLib.Logging;
|
||||
|
||||
namespace Meum.Client;
|
||||
|
||||
public class Client
|
||||
{
|
||||
private readonly HashSet<ServerConnection> _connectedServers = new();
|
||||
public IReadOnlySet<ServerConnection> ConnectedServers => _connectedServers;
|
||||
private readonly ILogger _logger;
|
||||
|
||||
public UserAddress Address { get; }
|
||||
|
||||
public Client(UserAddress address)
|
||||
public Client(ILogger logger)
|
||||
{
|
||||
Address = address;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<ServerConnection> ConnectToServerAsync(DnsEndPoint serverEndPoint)
|
||||
public IReadOnlySet<ServerConnection> ConnectedServers => _connectedServers;
|
||||
|
||||
public UserAddress? Address { get; private set; }
|
||||
|
||||
public Task RegisterAsync(UserAddress address)
|
||||
{
|
||||
var serv = new ServerConnection(serverEndPoint);
|
||||
await serv.ConnectAsync();
|
||||
_connectedServers.Add(serv);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task LogInAsync(UserAddress address)
|
||||
{
|
||||
if(Address != null)
|
||||
throw new InvalidOperationException("Already logged in");
|
||||
Address = address;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public async Task<ServerConnection> ConnectToServerAsync(DnsEndPoint serverEndPoint, CancellationToken ct = default)
|
||||
{
|
||||
var quicConn = await QuicConnection.ConnectAsync(new QuicClientConnectionOptions
|
||||
{
|
||||
// TODO serverEndPoint
|
||||
RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, Constants.ServerPortDefault),
|
||||
DefaultStreamErrorCode = Constants.DefaultStreamErrorCode,
|
||||
DefaultCloseErrorCode = Constants.DefaultCloseErrorCode,
|
||||
ClientAuthenticationOptions = new SslClientAuthenticationOptions
|
||||
{
|
||||
ApplicationProtocols = Constants.ApplicationProtocols,
|
||||
TargetHost = serverEndPoint.Host
|
||||
}
|
||||
}, ct);
|
||||
|
||||
var timeOutCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeOutCts.CancelAfter(Constants.ConnectionTimeout);
|
||||
var serv = await ServerConnection.OpenAsync(quicConn,
|
||||
serverEndPoint,
|
||||
_logger,
|
||||
timeOutCts.Token);
|
||||
|
||||
if(!_connectedServers.Add(serv))
|
||||
throw new Exception($"Is already connected to server '{serverEndPoint.Host}'");
|
||||
return serv;
|
||||
}
|
||||
}
|
||||
@ -1,17 +1,13 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Meum.Core\Meum.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="DTLib" Version="1.6.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@ -1,47 +1,43 @@
|
||||
using System.Net;
|
||||
using System.Net.Quic;
|
||||
using System.Net.Security;
|
||||
using DTLib.Extensions;
|
||||
using DTLib.Logging;
|
||||
|
||||
namespace Meum.Client;
|
||||
|
||||
public class ServerConnection : IDisposable
|
||||
public class ServerConnection : IAsyncDisposable
|
||||
{
|
||||
private readonly QuicConnection _quicConnection;
|
||||
private readonly ILogger _logger;
|
||||
|
||||
public DnsEndPoint ServerEndPoint { get; }
|
||||
|
||||
private QuicConnection? _quicConnection;
|
||||
|
||||
public ServerConnection(DnsEndPoint serverEndPoint)
|
||||
private ServerConnection(QuicConnection quicConnection, DnsEndPoint serverEndPoint, ILogger logger)
|
||||
{
|
||||
ServerEndPoint = serverEndPoint;
|
||||
_quicConnection = quicConnection;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task ConnectAsync()
|
||||
public static async Task<ServerConnection> OpenAsync(QuicConnection quicConnection,
|
||||
DnsEndPoint serverEndPoint,
|
||||
ILogger logger,
|
||||
CancellationToken ct)
|
||||
{
|
||||
_quicConnection = await QuicConnection.ConnectAsync(new QuicClientConnectionOptions
|
||||
{
|
||||
RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, Network.ServerPortDefault),
|
||||
DefaultStreamErrorCode = Network.DefaultStreamErrorCode,
|
||||
DefaultCloseErrorCode = Network.DefaultCloseErrorCode,
|
||||
ClientAuthenticationOptions = new SslClientAuthenticationOptions
|
||||
{
|
||||
ApplicationProtocols = Network.ApplicationProtocols.ToList(),
|
||||
TargetHost = ServerEndPoint.Host
|
||||
}
|
||||
});
|
||||
var serverConnection = new ServerConnection(quicConnection, serverEndPoint, logger);
|
||||
|
||||
var systemStream = await quicConnection.OpenStreamAsync(QuicStreamType.Bidirectional, ct);
|
||||
await systemStream.SendPingReceivePong();
|
||||
return serverConnection;
|
||||
}
|
||||
|
||||
public async Task PingAsync()
|
||||
public override int GetHashCode()
|
||||
{
|
||||
var stream = await _quicConnection!.OpenOutboundStreamAsync(QuicStreamType.Bidirectional);
|
||||
await stream.WriteAsync("Ping\n".ToBytes());
|
||||
StreamReader reader = new StreamReader(stream);
|
||||
string line = await reader.ReadLineAsync() ?? String.Empty;
|
||||
Console.WriteLine(line);
|
||||
return _quicConnection.RemoteEndPoint.GetHashCode();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
_quicConnection?.DisposeAsync();
|
||||
await _quicConnection.DisposeAsync();
|
||||
}
|
||||
}
|
||||
20
Meum.Core/Constants.cs
Normal file
20
Meum.Core/Constants.cs
Normal file
@ -0,0 +1,20 @@
|
||||
global using System;
|
||||
global using System.Collections.Generic;
|
||||
global using System.Threading;
|
||||
global using System.Threading.Tasks;
|
||||
using System.Net.Security;
|
||||
|
||||
namespace Meum.Core;
|
||||
|
||||
public static class Constants
|
||||
{
|
||||
public static readonly List<SslApplicationProtocol> ApplicationProtocols =
|
||||
[
|
||||
new("Meum-1")
|
||||
];
|
||||
|
||||
public const int ServerPortDefault = 9320;
|
||||
public const long DefaultStreamErrorCode = 0xA;
|
||||
public const long DefaultCloseErrorCode = 0xB;
|
||||
public static readonly TimeSpan ConnectionTimeout = TimeSpan.FromSeconds(3);
|
||||
}
|
||||
@ -1,23 +1,24 @@
|
||||
global using System;
|
||||
global using System.Collections.Generic;
|
||||
global using System.Threading;
|
||||
global using System.Threading.Tasks;
|
||||
using System.Net;
|
||||
using System.Net.Security;
|
||||
using System.Net;
|
||||
using System.Net.Quic;
|
||||
using DTLib.Logging;
|
||||
using Unofficial.MsQuic;
|
||||
|
||||
namespace Meum.Core;
|
||||
|
||||
public static class Network
|
||||
public static class Functions
|
||||
{
|
||||
public static readonly SslApplicationProtocol[] ApplicationProtocols =
|
||||
[
|
||||
new("Meum-1")
|
||||
];
|
||||
|
||||
public const int ServerPortDefault = 9320;
|
||||
public const long DefaultStreamErrorCode = 0xA;
|
||||
public const long DefaultCloseErrorCode = 0xB;
|
||||
public static void InitMsQuic(ILogger? logger)
|
||||
{
|
||||
if (logger != null)
|
||||
{
|
||||
HarmonyMsQuicLoadFix.Apply(msg => logger.LogInfo(nameof(HarmonyMsQuicLoadFix), msg));
|
||||
using var netEventListener = new NetEventListener(logger);
|
||||
}
|
||||
else HarmonyMsQuicLoadFix.Apply();
|
||||
|
||||
if (!QuicConnection.IsSupported)
|
||||
throw new Exception("Quic is not supported, check for presence of libmsquic and openssl");
|
||||
}
|
||||
|
||||
public static bool IsValidDomainName(string name)
|
||||
{
|
||||
@ -32,7 +33,7 @@ public static class Network
|
||||
if (colon_index == -1)
|
||||
{
|
||||
host = address_str;
|
||||
port = ServerPortDefault;
|
||||
port = Constants.ServerPortDefault;
|
||||
}
|
||||
else
|
||||
{
|
||||
9
Meum.Core/Messages/AuthorizationRequest.cs
Normal file
9
Meum.Core/Messages/AuthorizationRequest.cs
Normal file
@ -0,0 +1,9 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Meum.Core.Messages;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public record struct AuthorizationRequest(byte[] hash)
|
||||
{
|
||||
|
||||
}
|
||||
28
Meum.Core/Messages/CodeMessage.cs
Normal file
28
Meum.Core/Messages/CodeMessage.cs
Normal file
@ -0,0 +1,28 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Meum.Core.Messages;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct CodeMessage
|
||||
{
|
||||
// 0xb65d6d - meum in 6-bit ascii encoding
|
||||
// 02 - CodeMessage
|
||||
private const uint correct_magic = 0xb65d6d01;
|
||||
|
||||
/// warning: check with <see cref="ThrowIfInvalid"/>
|
||||
public uint magic;
|
||||
/// warning: can be any int
|
||||
public MessageTypeCode type_code;
|
||||
|
||||
public CodeMessage(MessageTypeCode t)
|
||||
{
|
||||
magic = correct_magic;
|
||||
type_code = t;
|
||||
}
|
||||
|
||||
public void ThrowIfInvalid()
|
||||
{
|
||||
if(magic != correct_magic)
|
||||
throw new Exception($"Invalid CodeMessage magic: {magic}");
|
||||
}
|
||||
}
|
||||
34
Meum.Core/Messages/DataMessageHeader.cs
Normal file
34
Meum.Core/Messages/DataMessageHeader.cs
Normal file
@ -0,0 +1,34 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Meum.Core.Messages;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct DataMessageHeader
|
||||
{
|
||||
// 0xb65d6d - meum in 6-bit ascii encoding
|
||||
// 02 - DataMessageHeader
|
||||
private const uint correct_magic = 0xb65d6d02;
|
||||
|
||||
/// warning: check with <see cref="ThrowIfInvalid"/>
|
||||
public uint magic;
|
||||
/// warning: can be any int
|
||||
public MessageTypeCode type_code;
|
||||
/// warning: check with <see cref="ThrowIfInvalid"/>
|
||||
public int data_size;
|
||||
|
||||
|
||||
public DataMessageHeader(MessageTypeCode t, int size)
|
||||
{
|
||||
magic = correct_magic;
|
||||
type_code = t;
|
||||
data_size = size;
|
||||
}
|
||||
|
||||
public void ThrowIfInvalid()
|
||||
{
|
||||
if(magic != correct_magic)
|
||||
throw new Exception($"Invalid DataMessageHeader magic: {magic}");
|
||||
if(data_size < 1)
|
||||
throw new Exception($"Invalid DataMessageHeader data size: {data_size}");
|
||||
}
|
||||
}
|
||||
8
Meum.Core/Messages/MessageTypeCode.cs
Normal file
8
Meum.Core/Messages/MessageTypeCode.cs
Normal file
@ -0,0 +1,8 @@
|
||||
namespace Meum.Core.Messages;
|
||||
|
||||
public enum MessageTypeCode
|
||||
{
|
||||
Ping, Pong,
|
||||
RegistrationRequest, RegistrationResponse,
|
||||
AuthorizationRequest, AuthorizationResponse,
|
||||
}
|
||||
@ -1,5 +1,12 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Unofficial.MsQuic" Version="2.4.6" />
|
||||
<PackageReference Include="DTLib" Version="1.7.3" />
|
||||
<PackageReference Include="Unofficial.MsQuic" Version="2.4.10" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
37
Meum.Core/NetEventListener.cs
Normal file
37
Meum.Core/NetEventListener.cs
Normal file
@ -0,0 +1,37 @@
|
||||
using System.Diagnostics.Tracing;
|
||||
using System.Linq;
|
||||
using DTLib.Logging;
|
||||
|
||||
namespace Meum.Core;
|
||||
|
||||
internal class NetEventListener(ILogger _logger) : EventListener
|
||||
{
|
||||
protected override void OnEventSourceCreated(EventSource eventSource)
|
||||
{
|
||||
// Filter for NetEventSource
|
||||
if (eventSource.Name.Contains("System.Net"))
|
||||
{
|
||||
EnableEvents(eventSource, EventLevel.LogAlways, EventKeywords.All);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnEventWritten(EventWrittenEventArgs eventData)
|
||||
{
|
||||
LogSeverity severity = eventData.Level switch
|
||||
{
|
||||
EventLevel.LogAlways => LogSeverity.Info,
|
||||
EventLevel.Critical => LogSeverity.Error,
|
||||
EventLevel.Error => LogSeverity.Error,
|
||||
EventLevel.Warning => LogSeverity.Warn,
|
||||
EventLevel.Informational => LogSeverity.Info,
|
||||
EventLevel.Verbose => LogSeverity.Debug,
|
||||
_ => throw new ArgumentOutOfRangeException(eventData.Level.ToString())
|
||||
};
|
||||
IEnumerable<object?> payload = eventData.Payload ?? Enumerable.Empty<object?>();
|
||||
var message = string.Join(", ", payload);
|
||||
string context = eventData.EventSource.Name;
|
||||
if (context.Contains("System.Net.Quic"))
|
||||
context = "MsQuic";
|
||||
_logger.Log(context, severity, message);
|
||||
}
|
||||
}
|
||||
24
Meum.Core/QuicExtensions.cs
Normal file
24
Meum.Core/QuicExtensions.cs
Normal file
@ -0,0 +1,24 @@
|
||||
using System.Net.Quic;
|
||||
|
||||
namespace Meum.Core;
|
||||
|
||||
public static class QuicExtensions
|
||||
{
|
||||
public static async Task<QuicStreamWrapper> AcceptStreamAsync(this QuicConnection conn,
|
||||
QuicStreamType streamType, CancellationToken ct = default)
|
||||
{
|
||||
var s = await conn.AcceptInboundStreamAsync(ct);
|
||||
if (s.Type != streamType)
|
||||
throw new Exception($"Accepted stream type is invalid: {s.Type} instead of {streamType}");
|
||||
var w = new QuicStreamWrapper(s);
|
||||
return w;
|
||||
}
|
||||
|
||||
public static async Task<QuicStreamWrapper> OpenStreamAsync(this QuicConnection conn,
|
||||
QuicStreamType streamType, CancellationToken ct = default)
|
||||
{
|
||||
var s = await conn.OpenOutboundStreamAsync(streamType, ct);
|
||||
var w = new QuicStreamWrapper(s);
|
||||
return w;
|
||||
}
|
||||
}
|
||||
100
Meum.Core/QuicStreamWrapper.cs
Normal file
100
Meum.Core/QuicStreamWrapper.cs
Normal file
@ -0,0 +1,100 @@
|
||||
using System.Buffers;
|
||||
using System.Net.Quic;
|
||||
using System.Runtime.InteropServices;
|
||||
using Meum.Core.Messages;
|
||||
|
||||
namespace Meum.Core;
|
||||
|
||||
public class QuicStreamWrapper : IAsyncDisposable
|
||||
{
|
||||
private QuicStream _stream;
|
||||
|
||||
public QuicStreamWrapper(QuicStream stream)
|
||||
{
|
||||
_stream = stream;
|
||||
}
|
||||
|
||||
public async ValueTask<T> ReadStructAsync<T>(CancellationToken ct = default)
|
||||
where T : struct
|
||||
{
|
||||
byte[] buffer = ArrayPool<byte>.Shared.Rent(Marshal.SizeOf(typeof(T)));
|
||||
var handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
|
||||
try
|
||||
{
|
||||
await _stream.ReadExactlyAsync(buffer, ct);
|
||||
return (T) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T))!;
|
||||
}
|
||||
finally
|
||||
{
|
||||
handle.Free();
|
||||
ArrayPool<byte>.Shared.Return(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
public ValueTask WriteStructAsync<T>(T msg_struct, CancellationToken ct = default)
|
||||
where T : struct
|
||||
{
|
||||
byte[] buffer = ArrayPool<byte>.Shared.Rent(Marshal.SizeOf(typeof(T)));
|
||||
var handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
|
||||
try
|
||||
{
|
||||
Marshal.StructureToPtr(msg_struct, handle.AddrOfPinnedObject(), false);
|
||||
return _stream.WriteAsync(buffer, ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
handle.Free();
|
||||
ArrayPool<byte>.Shared.Return(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
public ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken ct = default)
|
||||
=> _stream.ReadAsync(buffer, ct);
|
||||
|
||||
public ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken ct = default)
|
||||
=> _stream.WriteAsync(buffer, ct);
|
||||
|
||||
public ValueTask WriteCodeMessageAsync(MessageTypeCode messageTypeCode, CancellationToken ct = default)
|
||||
{
|
||||
CodeMessage m = new CodeMessage(messageTypeCode);
|
||||
return WriteStructAsync(m, ct);
|
||||
}
|
||||
|
||||
public async ValueTask<MessageTypeCode> ReadCodeMessageAsync(CancellationToken ct = default)
|
||||
{
|
||||
CodeMessage m = await ReadStructAsync<CodeMessage>(ct);
|
||||
m.ThrowIfInvalid();
|
||||
return m.type_code;
|
||||
}
|
||||
|
||||
public async ValueTask<DataMessageHeader> ReadDataMessageHeaderAsync(CancellationToken ct = default)
|
||||
{
|
||||
var m = await ReadStructAsync<DataMessageHeader>(ct);
|
||||
m.ThrowIfInvalid();
|
||||
return m;
|
||||
}
|
||||
|
||||
|
||||
public async Task ReceivePingSendPong()
|
||||
{
|
||||
var messageCode = await ReadCodeMessageAsync();
|
||||
if(messageCode != MessageTypeCode.Ping)
|
||||
throw new Exception($"Failed to test application protocol: expected Ping, got {messageCode}");
|
||||
await WriteCodeMessageAsync(MessageTypeCode.Pong);
|
||||
}
|
||||
|
||||
|
||||
public async Task SendPingReceivePong()
|
||||
{
|
||||
await WriteCodeMessageAsync(MessageTypeCode.Ping);
|
||||
var messageCode = await ReadCodeMessageAsync();
|
||||
if(messageCode != MessageTypeCode.Pong)
|
||||
throw new Exception($"Failed to test application protocol: expected Pong, got {messageCode}");
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
_stream.Close();
|
||||
await _stream.DisposeAsync();
|
||||
}
|
||||
}
|
||||
@ -26,7 +26,7 @@ public class UserAddress
|
||||
throw new FormatException($"Invalid user name '{Name}' in address '{addrstr}'");
|
||||
string serverstr = addrstr.Substring(at_index + 1);
|
||||
|
||||
RegistrationServer = Network.ParseDnsEndPoint(serverstr);
|
||||
RegistrationServer = Functions.ParseDnsEndPoint(serverstr);
|
||||
}
|
||||
|
||||
public override string ToString() => Full;
|
||||
|
||||
57
Meum.Server/ClientConnection.cs
Normal file
57
Meum.Server/ClientConnection.cs
Normal file
@ -0,0 +1,57 @@
|
||||
using System.Net.Quic;
|
||||
using DTLib.Logging;
|
||||
using Meum.Core.Messages;
|
||||
|
||||
namespace Meum.Server;
|
||||
|
||||
public class ClientConnection : IAsyncDisposable
|
||||
{
|
||||
private readonly QuicConnection _quicConnection;
|
||||
private QuicStreamWrapper _systemStream;
|
||||
private ILogger _logger;
|
||||
|
||||
private ClientConnection(QuicConnection quicConnection, QuicStreamWrapper systemStream, ILogger logger)
|
||||
{
|
||||
_quicConnection = quicConnection;
|
||||
_systemStream = systemStream;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public static async Task<ClientConnection> OpenAsync(
|
||||
QuicConnection quicConnection,
|
||||
ILogger logger,
|
||||
CancellationToken ct)
|
||||
{
|
||||
|
||||
var systemStream = await quicConnection.AcceptStreamAsync(QuicStreamType.Bidirectional, ct);
|
||||
await systemStream.ReceivePingSendPong();
|
||||
var clientConnection = new ClientConnection(quicConnection, systemStream, logger);
|
||||
|
||||
DataMessageHeader header = await systemStream.ReadDataMessageHeaderAsync(ct);
|
||||
switch (header.type_code)
|
||||
{
|
||||
case MessageTypeCode.RegistrationRequest:
|
||||
|
||||
break;
|
||||
case MessageTypeCode.AuthorizationRequest:
|
||||
// if (authorized)
|
||||
// clientConnection.HandleClientRequestsAsync()
|
||||
break;
|
||||
default:
|
||||
throw new Exception($"New connection sent unexpected message: {header.type_code}");
|
||||
}
|
||||
|
||||
return clientConnection;
|
||||
}
|
||||
|
||||
|
||||
// private async void HandleClientRequestsAsync(CancellationToken ct = default)
|
||||
// {
|
||||
//
|
||||
// }
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await _quicConnection.DisposeAsync();
|
||||
}
|
||||
}
|
||||
@ -1,11 +0,0 @@
|
||||
using Meum.Core;
|
||||
|
||||
namespace Meum.Server;
|
||||
|
||||
public class Config
|
||||
{
|
||||
public string listener_ip { get; set; } = "127.0.0.1";
|
||||
public int listener_port { get; set; } = Network.ServerPortDefault;
|
||||
public string certificate_path { get; set; } = "self-signed.pem";
|
||||
public string? key_path { get; set; } = "self-signed.key";
|
||||
}
|
||||
@ -1,13 +1,14 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<Version>0.0.1</Version>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Meum.Core\Meum.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="DTLib" Version="1.6.0" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@ -3,62 +3,37 @@ global using System.Collections.Generic;
|
||||
global using System.Threading;
|
||||
global using System.Threading.Tasks;
|
||||
global using Meum.Core;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Quic;
|
||||
using System.Net.Security;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using DTLib.Console;
|
||||
using DTLib.Demystifier;
|
||||
using DTLib.Extensions;
|
||||
using DTLib.Filesystem;
|
||||
using DTLib.Logging;
|
||||
|
||||
namespace Meum.Server;
|
||||
|
||||
class Program
|
||||
static class Program
|
||||
{
|
||||
static readonly IOPath config_path = "Meum.Server.config.json";
|
||||
|
||||
static async Task Main(string[] args)
|
||||
{
|
||||
try
|
||||
{
|
||||
var config = new Config();
|
||||
var certificate = X509Certificate2.CreateFromPemFile(config.certificate_path, config.key_path);
|
||||
if(!certificate.Verify())
|
||||
throw new Exception("Certificate is not valid");
|
||||
var serverConnectionOptions = new QuicServerConnectionOptions
|
||||
{
|
||||
DefaultStreamErrorCode = Network.DefaultStreamErrorCode,
|
||||
DefaultCloseErrorCode = Network.DefaultCloseErrorCode,
|
||||
ServerAuthenticationOptions = new SslServerAuthenticationOptions
|
||||
{
|
||||
ApplicationProtocols = Network.ApplicationProtocols.ToList(),
|
||||
ServerCertificate = certificate,
|
||||
ClientCertificateRequired = false
|
||||
}
|
||||
};
|
||||
var listenerOptions = new QuicListenerOptions
|
||||
{
|
||||
ListenEndPoint = new IPEndPoint(IPAddress.Parse(config.listener_ip), config.listener_port),
|
||||
ApplicationProtocols = Network.ApplicationProtocols.ToList(),
|
||||
ConnectionOptionsCallback = (_, _, _) => ValueTask.FromResult(serverConnectionOptions)
|
||||
};
|
||||
var listener = await QuicListener.ListenAsync(listenerOptions);
|
||||
var config = ServerConfig.LoadOrCreate(config_path);
|
||||
var logger = new ConsoleLogger();
|
||||
Functions.InitMsQuic(logger);
|
||||
|
||||
var server = new Server(config, logger);
|
||||
await server.ListenAsync();
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
var conn = await listener.AcceptConnectionAsync();
|
||||
var stream = await conn.AcceptInboundStreamAsync();
|
||||
StreamReader reader = new(stream);
|
||||
string line = await reader.ReadLineAsync() ?? "";
|
||||
Console.WriteLine(line);
|
||||
await stream.WriteAsync("Pong\n".ToBytes());
|
||||
await conn.CloseAsync(Network.DefaultCloseErrorCode);
|
||||
var conn = await server.AcceptConnectionAsync();
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ColoredConsole.WriteLine(ex.ToStringDemystified(), ConsoleColor.Red);
|
||||
logger.LogError("Main", ex.ToStringDemystified());
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -66,5 +41,9 @@ class Program
|
||||
{
|
||||
ColoredConsole.WriteLine(ex.ToStringDemystified(), ConsoleColor.Red);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Console.ResetColor();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,4 @@
|
||||
## Create self-signed certificate
|
||||
```sh
|
||||
dotnet dev-certs https -ep bin/Debug/net8.0/self-signed.pfx --trust --format PEM --no-password
|
||||
dotnet dev-certs https -ep bin/Debug/net9.0/self-signed.pem --trust --format PEM --no-password
|
||||
```
|
||||
66
Meum.Server/Server.cs
Normal file
66
Meum.Server/Server.cs
Normal file
@ -0,0 +1,66 @@
|
||||
using System.Net;
|
||||
using System.Net.Quic;
|
||||
using System.Net.Security;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using DTLib.Logging;
|
||||
|
||||
namespace Meum.Server;
|
||||
|
||||
public class Server
|
||||
{
|
||||
private readonly ServerConfig _config;
|
||||
private readonly X509Certificate _certificate;
|
||||
private readonly ILogger _logger;
|
||||
private QuicListener? _listener;
|
||||
|
||||
|
||||
public Server(ServerConfig config, ILogger logger, X509Certificate? certificate = null)
|
||||
{
|
||||
_config = config;
|
||||
_logger = logger;
|
||||
_certificate = certificate ??
|
||||
X509Certificate2.CreateFromPemFile(config.certificate_path, config.key_path);
|
||||
}
|
||||
|
||||
public async ValueTask ListenAsync()
|
||||
{
|
||||
var serverConnectionOptions = new QuicServerConnectionOptions
|
||||
{
|
||||
DefaultStreamErrorCode = Constants.DefaultStreamErrorCode,
|
||||
DefaultCloseErrorCode = Constants.DefaultCloseErrorCode,
|
||||
ServerAuthenticationOptions = new SslServerAuthenticationOptions
|
||||
{
|
||||
ApplicationProtocols = Constants.ApplicationProtocols,
|
||||
ServerCertificate = _certificate,
|
||||
ClientCertificateRequired = false
|
||||
}
|
||||
};
|
||||
var listenerOptions = new QuicListenerOptions
|
||||
{
|
||||
ListenEndPoint = new IPEndPoint(IPAddress.Parse(_config.listener_ip), _config.listener_port),
|
||||
ApplicationProtocols = Constants.ApplicationProtocols,
|
||||
ConnectionOptionsCallback = (_, _, _) => ValueTask.FromResult(serverConnectionOptions)
|
||||
};
|
||||
_listener = await QuicListener.ListenAsync(listenerOptions);
|
||||
}
|
||||
|
||||
|
||||
public async Task<ClientConnection> AcceptConnectionAsync(CancellationToken ct = default)
|
||||
{
|
||||
if (_listener == null)
|
||||
throw new Exception("Server is not listening");
|
||||
|
||||
while (true)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var quicConnection = await _listener.AcceptConnectionAsync(ct);
|
||||
var timeOutCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeOutCts.CancelAfter(Constants.ConnectionTimeout);
|
||||
var clientConnection = await ClientConnection.OpenAsync(
|
||||
quicConnection,
|
||||
_logger,
|
||||
timeOutCts.Token);
|
||||
return clientConnection;
|
||||
}
|
||||
}
|
||||
}
|
||||
39
Meum.Server/ServerConfig.cs
Normal file
39
Meum.Server/ServerConfig.cs
Normal file
@ -0,0 +1,39 @@
|
||||
using System.Text.Json;
|
||||
using DTLib.Filesystem;
|
||||
|
||||
namespace Meum.Server;
|
||||
|
||||
public class ServerConfig
|
||||
{
|
||||
public string listener_ip { get; set; } = "127.0.0.1";
|
||||
public int listener_port { get; set; } = Constants.ServerPortDefault;
|
||||
public string certificate_path { get; set; } = "self-signed.pem";
|
||||
public string? key_path { get; set; } = "self-signed.key";
|
||||
|
||||
private static JsonSerializerOptions _serializerOptions = new()
|
||||
{
|
||||
WriteIndented = true,
|
||||
};
|
||||
|
||||
public void Save(IOPath file_path)
|
||||
{
|
||||
string serialized = JsonSerializer.Serialize(this, _serializerOptions);
|
||||
if (string.IsNullOrEmpty(serialized))
|
||||
throw new Exception("can't serialize config");
|
||||
File.WriteAllText(file_path, serialized);
|
||||
}
|
||||
|
||||
public static ServerConfig LoadOrCreate(IOPath file_path)
|
||||
{
|
||||
if(File.Exists(file_path))
|
||||
{
|
||||
string serialized = File.ReadAllText(file_path);
|
||||
return JsonSerializer.Deserialize<ServerConfig>(serialized)
|
||||
?? throw new Exception("can't deserialize config");
|
||||
}
|
||||
|
||||
var c = new ServerConfig();
|
||||
c.Save(file_path);
|
||||
return c;
|
||||
}
|
||||
}
|
||||
1
Meum.sln
1
Meum.sln
@ -9,6 +9,7 @@ EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "solution_items", "solution_items", "{9375C0E5-DB78-4E77-869B-F9F7DC2651D1}"
|
||||
ProjectSection(SolutionItems) = preProject
|
||||
Directory.Build.props = Directory.Build.props
|
||||
.gitignore = .gitignore
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Meum.Client", "Meum.Client\Meum.Client.csproj", "{6DADE8A1-B363-4888-BB9B-72282B9AC769}"
|
||||
|
||||
Loading…
Reference in New Issue
Block a user