Compare commits
No commits in common. "bf4924c4d62910f59b726a448d94b61dcb9abb44" and "6de712910f0edca132d1824559d5c97e32cfe8f5" have entirely different histories.
bf4924c4d6
...
6de712910f
8
.gitignore
vendored
8
.gitignore
vendored
@ -21,11 +21,3 @@
|
||||
|
||||
#backups
|
||||
.old*/
|
||||
|
||||
#secrets
|
||||
*.pem
|
||||
*.key
|
||||
*.csr
|
||||
*.crt
|
||||
*.pfx
|
||||
*.config.json
|
||||
|
||||
@ -1,14 +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>
|
||||
<Version>1.0.0</Version>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Meum.Client\Meum.Client.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="DTLib" Version="1.6.0" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@ -8,7 +8,6 @@ using System.Reflection;
|
||||
using DTLib.Console;
|
||||
using DTLib.Demystifier;
|
||||
using DTLib.Extensions;
|
||||
using DTLib.Logging;
|
||||
|
||||
namespace Meum.Client.CLI;
|
||||
|
||||
@ -34,16 +33,10 @@ class Program
|
||||
{
|
||||
Console.OutputEncoding = StringConverter.UTF8;
|
||||
Console.InputEncoding = StringConverter.UTF8;
|
||||
ColoredConsole.Clear();
|
||||
var loggerRoot = new ConsoleLogger();
|
||||
try
|
||||
{
|
||||
ColoredConsole.ResetColor();
|
||||
var v = Assembly.GetExecutingAssembly().GetName().Version;
|
||||
string title = $"Meum CLI v{v?.ToString(3) ?? "Null"}";
|
||||
Console.Title = title;
|
||||
|
||||
Functions.InitMsQuic(loggerRoot);
|
||||
|
||||
ColoredConsole.WriteTitle(title, '=', fg: ConsoleColor.Cyan);
|
||||
ColoredConsole.WriteLine(greeting_art, fg: ConsoleColor.Magenta);
|
||||
ColoredConsole.WriteHLine('=', fg: ConsoleColor.Cyan);
|
||||
@ -55,34 +48,29 @@ class Program
|
||||
{
|
||||
try
|
||||
{
|
||||
if (userAddress == null)
|
||||
if(userAddress == null)
|
||||
{
|
||||
ColoredConsole.Write("enter user address (name@server.xyz): ", ConsoleColor.Blue);
|
||||
var addrstr = ColoredConsole.ReadLine(ConsoleColor.Cyan);
|
||||
var addrstr = ColoredConsole.ReadLine("enter user address (name@server.xyz)", ConsoleColor.Blue);
|
||||
if (string.IsNullOrEmpty(addrstr))
|
||||
continue;
|
||||
userAddress = new(addrstr);
|
||||
}
|
||||
|
||||
Client client = new(loggerRoot);
|
||||
if (serverEndPoint == null)
|
||||
Client client = new(userAddress);
|
||||
if(serverEndPoint == null)
|
||||
{
|
||||
ColoredConsole.Write("enter server address (server.xyz): ", ConsoleColor.Blue);
|
||||
serverAddress = ColoredConsole.ReadLine(ConsoleColor.Cyan);
|
||||
serverAddress = ColoredConsole.ReadLine("enter server address (server.xyz)", ConsoleColor.Blue);
|
||||
if (string.IsNullOrEmpty(serverAddress))
|
||||
{
|
||||
ColoredConsole.WriteLine("null address", ConsoleColor.Red);
|
||||
continue;
|
||||
}
|
||||
|
||||
serverEndPoint = Functions.ParseDnsEndPoint(serverAddress);
|
||||
serverEndPoint = Network.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 conn.PingAsync();
|
||||
await Task.Delay(-1);
|
||||
}
|
||||
catch (Exception ex)
|
||||
@ -90,14 +78,6 @@ class Program
|
||||
ColoredConsole.WriteLine(ex.ToStringDemystified(), ConsoleColor.Red);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ColoredConsole.WriteLine(ex.ToStringDemystified(), ConsoleColor.Red);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Console.ResetColor();
|
||||
}
|
||||
// ColoredConsole.ResetColor();
|
||||
}
|
||||
}
|
||||
|
||||
@ -4,63 +4,26 @@ 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();
|
||||
private readonly ILogger _logger;
|
||||
|
||||
public Client(ILogger logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public IReadOnlySet<ServerConnection> ConnectedServers => _connectedServers;
|
||||
|
||||
public UserAddress? Address { get; private set; }
|
||||
public UserAddress Address { get; }
|
||||
|
||||
public Task RegisterAsync(UserAddress address)
|
||||
public Client(UserAddress address)
|
||||
{
|
||||
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)
|
||||
public async Task<ServerConnection> ConnectToServerAsync(DnsEndPoint serverEndPoint)
|
||||
{
|
||||
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}'");
|
||||
var serv = new ServerConnection(serverEndPoint);
|
||||
await serv.ConnectAsync();
|
||||
_connectedServers.Add(serv);
|
||||
return serv;
|
||||
}
|
||||
}
|
||||
@ -1,13 +1,17 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<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,43 +1,47 @@
|
||||
using System.Net;
|
||||
using System.Net.Quic;
|
||||
using DTLib.Logging;
|
||||
using System.Net.Security;
|
||||
using DTLib.Extensions;
|
||||
|
||||
namespace Meum.Client;
|
||||
|
||||
public class ServerConnection : IAsyncDisposable
|
||||
public class ServerConnection : IDisposable
|
||||
{
|
||||
private readonly QuicConnection _quicConnection;
|
||||
private readonly ILogger _logger;
|
||||
|
||||
public DnsEndPoint ServerEndPoint { get; }
|
||||
|
||||
private QuicConnection? _quicConnection;
|
||||
|
||||
private ServerConnection(QuicConnection quicConnection, DnsEndPoint serverEndPoint, ILogger logger)
|
||||
public ServerConnection(DnsEndPoint serverEndPoint)
|
||||
{
|
||||
ServerEndPoint = serverEndPoint;
|
||||
_quicConnection = quicConnection;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public static async Task<ServerConnection> OpenAsync(QuicConnection quicConnection,
|
||||
DnsEndPoint serverEndPoint,
|
||||
ILogger logger,
|
||||
CancellationToken ct)
|
||||
public async Task ConnectAsync()
|
||||
{
|
||||
var serverConnection = new ServerConnection(quicConnection, serverEndPoint, logger);
|
||||
|
||||
var systemStream = await quicConnection.OpenStreamAsync(QuicStreamType.Bidirectional, ct);
|
||||
await systemStream.SendPingReceivePong();
|
||||
return serverConnection;
|
||||
_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
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public override int GetHashCode()
|
||||
public async Task PingAsync()
|
||||
{
|
||||
return _quicConnection.RemoteEndPoint.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);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
public void Dispose()
|
||||
{
|
||||
await _quicConnection.DisposeAsync();
|
||||
_quicConnection?.DisposeAsync();
|
||||
}
|
||||
}
|
||||
@ -1,20 +0,0 @@
|
||||
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,9 +0,0 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Meum.Core.Messages;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public record struct AuthorizationRequest(byte[] hash)
|
||||
{
|
||||
|
||||
}
|
||||
@ -1,28 +0,0 @@
|
||||
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}");
|
||||
}
|
||||
}
|
||||
@ -1,34 +0,0 @@
|
||||
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}");
|
||||
}
|
||||
}
|
||||
@ -1,8 +0,0 @@
|
||||
namespace Meum.Core.Messages;
|
||||
|
||||
public enum MessageTypeCode
|
||||
{
|
||||
Ping, Pong,
|
||||
RegistrationRequest, RegistrationResponse,
|
||||
AuthorizationRequest, AuthorizationResponse,
|
||||
}
|
||||
@ -1,12 +1,5 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="DTLib" Version="1.7.3" />
|
||||
<PackageReference Include="Unofficial.MsQuic" Version="2.4.10" />
|
||||
<PackageReference Include="Unofficial.MsQuic" Version="2.4.6" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@ -1,37 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@ -1,24 +1,23 @@
|
||||
using System.Net;
|
||||
using System.Net.Quic;
|
||||
using DTLib.Logging;
|
||||
using Unofficial.MsQuic;
|
||||
global using System;
|
||||
global using System.Collections.Generic;
|
||||
global using System.Threading;
|
||||
global using System.Threading.Tasks;
|
||||
using System.Net;
|
||||
using System.Net.Security;
|
||||
|
||||
namespace Meum.Core;
|
||||
|
||||
public static class Functions
|
||||
public static class Network
|
||||
{
|
||||
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();
|
||||
public static readonly SslApplicationProtocol[] ApplicationProtocols =
|
||||
[
|
||||
new("Meum-1")
|
||||
];
|
||||
|
||||
public const int ServerPortDefault = 9320;
|
||||
public const long DefaultStreamErrorCode = 0xA;
|
||||
public const long DefaultCloseErrorCode = 0xB;
|
||||
|
||||
if (!QuicConnection.IsSupported)
|
||||
throw new Exception("Quic is not supported, check for presence of libmsquic and openssl");
|
||||
}
|
||||
|
||||
public static bool IsValidDomainName(string name)
|
||||
{
|
||||
@ -33,7 +32,7 @@ public static class Functions
|
||||
if (colon_index == -1)
|
||||
{
|
||||
host = address_str;
|
||||
port = Constants.ServerPortDefault;
|
||||
port = ServerPortDefault;
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -1,24 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@ -1,100 +0,0 @@
|
||||
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 = Functions.ParseDnsEndPoint(serverstr);
|
||||
RegistrationServer = Network.ParseDnsEndPoint(serverstr);
|
||||
}
|
||||
|
||||
public override string ToString() => Full;
|
||||
|
||||
@ -1,57 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
11
Meum.Server/Config.cs
Normal file
11
Meum.Server/Config.cs
Normal file
@ -0,0 +1,11 @@
|
||||
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,14 +1,13 @@
|
||||
<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,37 +3,62 @@ 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.Filesystem;
|
||||
using DTLib.Logging;
|
||||
using DTLib.Extensions;
|
||||
|
||||
namespace Meum.Server;
|
||||
|
||||
static class Program
|
||||
class Program
|
||||
{
|
||||
static readonly IOPath config_path = "Meum.Server.config.json";
|
||||
|
||||
static async Task Main(string[] args)
|
||||
{
|
||||
try
|
||||
{
|
||||
var config = ServerConfig.LoadOrCreate(config_path);
|
||||
var logger = new ConsoleLogger();
|
||||
Functions.InitMsQuic(logger);
|
||||
|
||||
var server = new Server(config, logger);
|
||||
await server.ListenAsync();
|
||||
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);
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
var conn = await server.AcceptConnectionAsync();
|
||||
|
||||
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);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError("Main", ex.ToStringDemystified());
|
||||
ColoredConsole.WriteLine(ex.ToStringDemystified(), ConsoleColor.Red);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -41,9 +66,5 @@ static 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/net9.0/self-signed.pem --trust --format PEM --no-password
|
||||
dotnet dev-certs https -ep bin/Debug/net8.0/self-signed.pfx --trust --format PEM --no-password
|
||||
```
|
||||
@ -1,66 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,39 +0,0 @@
|
||||
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,7 +9,6 @@ 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