Ship authenticated remote transports in Unity package
This commit is contained in:
parent
c194bd4cc8
commit
99458dbb57
28 changed files with 309 additions and 53 deletions
|
|
@ -27,8 +27,8 @@ namespace GameCult.Mesh
|
|||
public IReadOnlyList<ICultMeshTransportConnector>? Connectors { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets streaming content connectors. TCP content delivery is used by default;
|
||||
/// applications may replace it or explicitly add legacy RUDP.
|
||||
/// Gets or sets streaming content connectors. HTTPS and loopback TCP content
|
||||
/// delivery are used by default; applications may replace them or explicitly add legacy RUDP.
|
||||
/// </summary>
|
||||
public IReadOnlyList<ICultMeshContentTransportConnector>? ContentConnectors { get; set; }
|
||||
|
||||
|
|
@ -184,6 +184,7 @@ namespace GameCult.Mesh
|
|||
},
|
||||
options.ContentConnectors ?? new ICultMeshContentTransportConnector[]
|
||||
{
|
||||
new CultMeshHttpsContentTransportConnector(),
|
||||
new CultMeshTcpContentTransportConnector()
|
||||
},
|
||||
options.RealtimeConnectors,
|
||||
|
|
|
|||
124
src/GameCult.Mesh/CultMeshHttpsContentTransport.cs
Normal file
124
src/GameCult.Mesh/CultMeshHttpsContentTransport.cs
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GameCult.Mesh
|
||||
{
|
||||
/// <summary>
|
||||
/// Opens immutable content over an Odin-certified HTTPS route. Provider
|
||||
/// identity comes from the verified route and TLS endpoint; the transfer
|
||||
/// service remains responsible for checking the advertised chunk hash.
|
||||
/// </summary>
|
||||
public sealed class CultMeshHttpsContentTransportConnector : ICultMeshContentTransportConnector
|
||||
{
|
||||
private readonly Func<HttpMessageHandler> _createHandler;
|
||||
|
||||
public CultMeshHttpsContentTransportConnector(Func<HttpMessageHandler>? createHandler = null)
|
||||
{
|
||||
_createHandler = createHandler ?? (() => new HttpClientHandler());
|
||||
}
|
||||
|
||||
public string ConnectorId => "https-content";
|
||||
public int Priority => 0;
|
||||
|
||||
public bool CanConnect(CultMeshTransportCandidate candidate) =>
|
||||
candidate != null &&
|
||||
Uri.TryCreate(candidate.Endpoint, UriKind.Absolute, out var endpoint) &&
|
||||
string.Equals(endpoint.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
public Task<ICultMeshContentTransport> ConnectAsync(
|
||||
CultMeshTransportCandidate candidate,
|
||||
CultMeshSessionTarget target,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (candidate == null) throw new ArgumentNullException(nameof(candidate));
|
||||
if (target == null) throw new ArgumentNullException(nameof(target));
|
||||
if (!CanConnect(candidate))
|
||||
throw new NotSupportedException($"HTTPS content connector does not support '{candidate.Endpoint}'.");
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
return Task.FromResult<ICultMeshContentTransport>(new CultMeshHttpsContentTransport(
|
||||
candidate.Endpoint,
|
||||
new HttpClient(_createHandler(), disposeHandler: true),
|
||||
target,
|
||||
candidate.Generation));
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class CultMeshHttpsContentTransport : ICultMeshContentTransport, ICultMeshVerifiedTransport
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly CultMeshSessionTarget _target;
|
||||
private readonly string _routeGeneration;
|
||||
private bool _disposed;
|
||||
|
||||
public CultMeshHttpsContentTransport(
|
||||
string endpoint,
|
||||
HttpClient client,
|
||||
CultMeshSessionTarget target,
|
||||
string routeGeneration)
|
||||
{
|
||||
Endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
|
||||
_client = client ?? throw new ArgumentNullException(nameof(client));
|
||||
_target = target ?? throw new ArgumentNullException(nameof(target));
|
||||
_routeGeneration = routeGeneration ?? string.Empty;
|
||||
}
|
||||
|
||||
public string TransportId => "https-content";
|
||||
public string Endpoint { get; }
|
||||
|
||||
public bool IsVerifiedFor(
|
||||
string verseId,
|
||||
string authorityRuntimeId,
|
||||
string protocolId,
|
||||
string routeGeneration) =>
|
||||
string.Equals(_target.VerseId, verseId, StringComparison.Ordinal) &&
|
||||
string.Equals(_target.AuthorityRuntimeId, authorityRuntimeId, StringComparison.Ordinal) &&
|
||||
string.Equals(CultMeshProtocols.Content.Value, protocolId, StringComparison.Ordinal) &&
|
||||
string.Equals(_routeGeneration, routeGeneration, StringComparison.Ordinal);
|
||||
|
||||
public async Task CopyChunkToAsync(
|
||||
CultMeshCdnChunkRef chunk,
|
||||
Stream destination,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(CultMeshHttpsContentTransport));
|
||||
if (chunk == null) throw new ArgumentNullException(nameof(chunk));
|
||||
if (destination == null) throw new ArgumentNullException(nameof(destination));
|
||||
if (!destination.CanWrite) throw new ArgumentException("Content destination must be writable.", nameof(destination));
|
||||
|
||||
var requestUri = BuildChunkUri(Endpoint, chunk);
|
||||
using var response = await _client.GetAsync(
|
||||
requestUri,
|
||||
HttpCompletionOption.ResponseHeadersRead,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
response.EnsureSuccessStatusCode();
|
||||
if (response.Content.Headers.ContentLength is long contentLength &&
|
||||
contentLength != chunk.SizeBytes)
|
||||
{
|
||||
throw new InvalidDataException(
|
||||
$"HTTPS content length {contentLength} did not match advertised chunk size {chunk.SizeBytes}.");
|
||||
}
|
||||
using var source = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
|
||||
await source.CopyToAsync(destination, 81920, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_client.Dispose();
|
||||
}
|
||||
|
||||
private static Uri BuildChunkUri(string endpoint, CultMeshCdnChunkRef chunk)
|
||||
{
|
||||
var builder = new UriBuilder(endpoint);
|
||||
var separator = string.IsNullOrWhiteSpace(builder.Query) ? string.Empty : builder.Query.TrimStart('?') + "&";
|
||||
builder.Query = separator +
|
||||
"chunkHash=" + Uri.EscapeDataString(CultMeshCdn.NormalizeHash(chunk.ChunkHash, nameof(chunk.ChunkHash))) +
|
||||
"&recordKey=" + Uri.EscapeDataString(chunk.RecordKey ?? string.Empty);
|
||||
return builder.Uri;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Net.WebSockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GameCult.Networking.WebSockets;
|
||||
|
||||
internal static class CultNetWebSocketMessageIO
|
||||
{
|
||||
public static Task SendAsync(WebSocket socket, byte[] payload, CancellationToken cancellationToken) =>
|
||||
socket.SendAsync(new ArraySegment<byte>(payload), WebSocketMessageType.Binary, true, cancellationToken);
|
||||
|
||||
public static async Task<byte[]?> ReceiveAsync(
|
||||
WebSocket socket,
|
||||
int maxMessageBytes,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var segment = new byte[Math.Min(16 * 1024, maxMessageBytes)];
|
||||
using var message = new MemoryStream();
|
||||
while (true)
|
||||
{
|
||||
var result = await socket.ReceiveAsync(new ArraySegment<byte>(segment), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (result.MessageType == WebSocketMessageType.Close) return null;
|
||||
if (result.MessageType != WebSocketMessageType.Binary)
|
||||
{
|
||||
await socket.CloseAsync(
|
||||
WebSocketCloseStatus.InvalidMessageType,
|
||||
"CultNet requires binary MessagePack WebSocket messages.",
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return null;
|
||||
}
|
||||
if (message.Length + result.Count > maxMessageBytes)
|
||||
{
|
||||
await socket.CloseAsync(
|
||||
WebSocketCloseStatus.MessageTooBig,
|
||||
"CultNet message exceeds the configured maximum.",
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return null;
|
||||
}
|
||||
message.Write(segment, 0, result.Count);
|
||||
if (result.EndOfMessage) return message.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -37,7 +37,7 @@ public sealed class CultNetWebSocketSchemaClient : ICultNetUriSchemaClient, ICul
|
|||
/// <inheritdoc />
|
||||
public void Connect(string host, int port)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(host);
|
||||
if (string.IsNullOrWhiteSpace(host)) throw new ArgumentException("Host is required.", nameof(host));
|
||||
if (port <= 0 || port > 65535) throw new ArgumentOutOfRangeException(nameof(port));
|
||||
ConnectAsync(new Uri($"ws://{host}:{port}/cultmesh"), CancellationToken.None)
|
||||
.GetAwaiter().GetResult();
|
||||
|
|
@ -46,7 +46,7 @@ public sealed class CultNetWebSocketSchemaClient : ICultNetUriSchemaClient, ICul
|
|||
/// <summary>Connects to an exact WebSocket route.</summary>
|
||||
public async Task ConnectAsync(Uri endpoint, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(endpoint);
|
||||
if (endpoint == null) throw new ArgumentNullException(nameof(endpoint));
|
||||
if (endpoint.Scheme is not ("ws" or "wss"))
|
||||
throw new ArgumentException("CultNet WebSocket endpoint must use ws:// or wss://.", nameof(endpoint));
|
||||
ThrowIfDisposed();
|
||||
|
|
@ -69,7 +69,7 @@ public sealed class CultNetWebSocketSchemaClient : ICultNetUriSchemaClient, ICul
|
|||
/// <inheritdoc />
|
||||
public void SendCultNet<T>(T message) where T : ICultNetSchemaMessage
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(message);
|
||||
if (message == null) throw new ArgumentNullException(nameof(message));
|
||||
ThrowIfDisposed();
|
||||
var socket = _socket;
|
||||
if (socket?.State != WebSocketState.Open)
|
||||
|
|
@ -92,7 +92,7 @@ public sealed class CultNetWebSocketSchemaClient : ICultNetUriSchemaClient, ICul
|
|||
/// <inheritdoc />
|
||||
public void OnCultNet<T>(Action<T> callback) where T : ICultNetSchemaMessage
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(callback);
|
||||
if (callback == null) throw new ArgumentNullException(nameof(callback));
|
||||
ThrowIfDisposed();
|
||||
lock (_handlerGate)
|
||||
{
|
||||
|
|
@ -161,6 +161,6 @@ public sealed class CultNetWebSocketSchemaClient : ICultNetUriSchemaClient, ICul
|
|||
|
||||
private void ThrowIfDisposed()
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(CultNetWebSocketSchemaClient));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -178,44 +178,6 @@ public sealed class CultNetWebSocketSchemaServer :
|
|||
}
|
||||
}
|
||||
|
||||
internal static class CultNetWebSocketMessageIO
|
||||
{
|
||||
public static Task SendAsync(WebSocket socket, byte[] payload, CancellationToken cancellationToken) =>
|
||||
socket.SendAsync(payload, WebSocketMessageType.Binary, true, cancellationToken);
|
||||
|
||||
public static async Task<byte[]?> ReceiveAsync(
|
||||
WebSocket socket,
|
||||
int maxMessageBytes,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var segment = new byte[Math.Min(16 * 1024, maxMessageBytes)];
|
||||
using var message = new MemoryStream();
|
||||
while (true)
|
||||
{
|
||||
var result = await socket.ReceiveAsync(segment, cancellationToken).ConfigureAwait(false);
|
||||
if (result.MessageType == WebSocketMessageType.Close) return null;
|
||||
if (result.MessageType != WebSocketMessageType.Binary)
|
||||
{
|
||||
await socket.CloseAsync(
|
||||
WebSocketCloseStatus.InvalidMessageType,
|
||||
"CultNet requires binary MessagePack WebSocket messages.",
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return null;
|
||||
}
|
||||
if (message.Length + result.Count > maxMessageBytes)
|
||||
{
|
||||
await socket.CloseAsync(
|
||||
WebSocketCloseStatus.MessageTooBig,
|
||||
"CultNet message exceeds the configured maximum.",
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return null;
|
||||
}
|
||||
message.Write(segment, 0, result.Count);
|
||||
if (result.EndOfMessage) return message.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>ASP.NET Core endpoint mapping for the CultNet WebSocket schema server.</summary>
|
||||
public static class CultNetWebSocketEndpointRouteBuilderExtensions
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,14 +1,18 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<TargetFrameworks>net10.0;netstandard2.1</TargetFrameworks>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<Description>CultNet schema-v0 WebSocket host adapter for browser and web runtimes</Description>
|
||||
<PackageId>GameCult.Networking.WebSockets</PackageId>
|
||||
<PackageTags>game;networking;websocket;cultnet;cultmesh</PackageTags>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ItemGroup Condition="'$(TargetFramework)' == 'net10.0'">
|
||||
<ProjectReference Include="..\GameCult.Networking\GameCult.Networking.csproj" />
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.1'">
|
||||
<ProjectReference Include="..\GameCult.Networking\GameCult.Networking.csproj" />
|
||||
<Compile Remove="CultNetWebSocketSchemaServer.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
|
|
|||
Loading…
Reference in a new issue