RynthSuite as of 2026-10-04 (internal c94715f): RynthOracle (based on Oracle of Dereth by Advis Eveldan) and RynthInventory, RynthAi patrol doorways and rooms, healing priority, strict monster priority, finish the wounded target, slayer weapons, arcs when clear, blasts like rings, learn unknown spells, looting fixes, release 2026.10.4.6
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
c33e24a610
commit
12ca25f911
426 changed files with 108239 additions and 7521 deletions
91
Plugins/RynthCore.Plugin.RynthNet/Transport/NetModels.cs
Normal file
91
Plugins/RynthCore.Plugin.RynthNet/Transport/NetModels.cs
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
// ============================================================================
|
||||
// RynthNet - Transport/NetModels.cs
|
||||
// Plain data the transport hands to its consumer (the plugin, or the test
|
||||
// harness). Everything here is immutable once published, so the pump thread
|
||||
// can read it while the I/O threads keep running.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNet.Transport;
|
||||
|
||||
/// <summary>Who a client is. Sent in hello/ident; replaced as a whole, never mutated.</summary>
|
||||
public sealed class NodeIdentity
|
||||
{
|
||||
public string Character { get; init; } = "";
|
||||
public string World { get; init; } = "";
|
||||
public string Account { get; init; } = "";
|
||||
public bool LoggedIn { get; init; }
|
||||
public string[] Tags { get; init; } = Array.Empty<string>();
|
||||
public string App { get; init; } = "";
|
||||
|
||||
public bool HasAnyTag(string[] wanted)
|
||||
{
|
||||
foreach (string w in wanted)
|
||||
foreach (string t in Tags)
|
||||
if (string.Equals(t, w, StringComparison.OrdinalIgnoreCase)) return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A connected client as the pump thread sees it (a copy taken under the node's lock).</summary>
|
||||
public sealed class PeerInfo
|
||||
{
|
||||
public string NodeId { get; init; } = "";
|
||||
public int Pid { get; init; }
|
||||
public bool Outbound { get; init; }
|
||||
public NodeIdentity Identity { get; init; } = new();
|
||||
/// <summary>The last status object the client sent (raw JSON), or "" before the first one.</summary>
|
||||
public string StatusJson { get; init; } = "";
|
||||
public long StatusAtMs { get; init; }
|
||||
public long ConnectedAtMs { get; init; }
|
||||
public int RttMs { get; init; } = -1;
|
||||
}
|
||||
|
||||
/// <summary>Who a command or message is for. Receivers check it again against themselves.</summary>
|
||||
public enum TargetKind { All = 0, Tags = 1, Character = 2 }
|
||||
|
||||
public readonly record struct NetTarget(TargetKind Kind, string Value)
|
||||
{
|
||||
public static readonly NetTarget All = new(TargetKind.All, "");
|
||||
|
||||
public string KindName => Kind switch { TargetKind.Tags => "tags", TargetKind.Character => "char", _ => "all" };
|
||||
|
||||
public static NetTarget Parse(string? kind, string? value) => kind switch
|
||||
{
|
||||
"tags" => new NetTarget(TargetKind.Tags, value ?? ""),
|
||||
"char" => new NetTarget(TargetKind.Character, value ?? ""),
|
||||
_ => All,
|
||||
};
|
||||
|
||||
/// <summary>The comma-separated tag list of a Tags target.</summary>
|
||||
public string[] TagList => Kind == TargetKind.Tags
|
||||
? Value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
|
||||
: Array.Empty<string>();
|
||||
|
||||
public bool Matches(NodeIdentity id) => Kind switch
|
||||
{
|
||||
TargetKind.All => true,
|
||||
TargetKind.Tags => id.HasAnyTag(TagList),
|
||||
TargetKind.Character => string.Equals(id.Character, Value, StringComparison.OrdinalIgnoreCase),
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>What happened on the network, queued for the pump thread.</summary>
|
||||
public enum NetEventKind { PeerJoined, PeerLeft, PeerUpdated, Command, Ack, Data }
|
||||
|
||||
public sealed class NetEvent
|
||||
{
|
||||
public NetEventKind Kind { get; init; }
|
||||
public string NodeId { get; init; } = "";
|
||||
/// <summary>The sender's character name when the event was queued.</summary>
|
||||
public string From { get; init; } = "";
|
||||
public string Id { get; init; } = "";
|
||||
public NetTarget Target { get; init; }
|
||||
public string Text { get; init; } = "";
|
||||
public int DelayMs { get; init; }
|
||||
public bool Ok { get; init; }
|
||||
public string Channel { get; init; } = "";
|
||||
public long AtMs { get; init; }
|
||||
}
|
||||
671
Plugins/RynthCore.Plugin.RynthNet/Transport/NetNode.cs
Normal file
671
Plugins/RynthCore.Plugin.RynthNet/Transport/NetNode.cs
Normal file
|
|
@ -0,0 +1,671 @@
|
|||
// ============================================================================
|
||||
// RynthNet - Transport/NetNode.cs
|
||||
// One client's end of the local mesh. No server process, no hub:
|
||||
//
|
||||
// - Every client listens on its own pipe (RynthNet.1.<ns>.<pid>.<nonce>).
|
||||
// - A supervisor thread lists the namespace once a second and dials each
|
||||
// client whose (pid, node id) sorts above its own; the other side of each
|
||||
// pair dials it. So every pair has exactly one connection, nobody is
|
||||
// elected, and a crashed or frozen client only takes its own links down.
|
||||
// - Each connection is two tasks (read, write). Nothing here touches the
|
||||
// game or the host API: what arrives is queued (Events, Logs) for the
|
||||
// consumer's own thread.
|
||||
// - Stop() says bye, cancels everything, disposes every pipe and joins the
|
||||
// supervisor and every task with a timeout. It returns false if anything
|
||||
// was still running, so the caller can log it.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Pipes;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNet.Transport;
|
||||
|
||||
public sealed class NetNodeOptions
|
||||
{
|
||||
/// <summary>Pipe namespace; empty = this Windows user and session (the normal case). Tests pass their own.</summary>
|
||||
public string Namespace { get; init; } = "";
|
||||
public string App { get; init; } = "RynthNet";
|
||||
public int MaxPeers { get; init; } = 32;
|
||||
public int ScanIntervalMs { get; init; } = 1000;
|
||||
public int PingIntervalMs { get; init; } = 2000;
|
||||
public int TimeoutMs { get; init; } = 7000;
|
||||
public int HelloTimeoutMs { get; init; } = 5000;
|
||||
}
|
||||
|
||||
public sealed class NetNode : IDisposable
|
||||
{
|
||||
public static long NowMs => Environment.TickCount64;
|
||||
|
||||
private const int MaxEvents = 4096;
|
||||
private const int MaxLogs = 512;
|
||||
|
||||
private readonly NetNodeOptions _options;
|
||||
private readonly object _lock = new();
|
||||
private readonly List<PeerConnection> _connections = new(); // every live pipe
|
||||
private readonly Dictionary<string, PeerConnection> _peers = new(); // joined, by node id
|
||||
private readonly Dictionary<string, long> _badPipes = new(); // pipe name -> retry after (ms)
|
||||
private readonly List<Task> _tasks = new();
|
||||
private readonly ConcurrentQueue<NetEvent> _events = new();
|
||||
private readonly ConcurrentQueue<string> _logs = new();
|
||||
private int _eventCount, _logCount;
|
||||
private int _droppedEvents;
|
||||
|
||||
private CancellationTokenSource? _cts;
|
||||
private Thread? _supervisor;
|
||||
private NamedPipeServerStream? _firstServer;
|
||||
private volatile NodeIdentity _identity = new();
|
||||
private volatile string _statusJson = "";
|
||||
private int _started, _stopped;
|
||||
private volatile bool _listening;
|
||||
private string _ns = "";
|
||||
|
||||
public NetNode(NetNodeOptions? options = null)
|
||||
{
|
||||
_options = options ?? new NetNodeOptions();
|
||||
}
|
||||
|
||||
public int Pid { get; } = Environment.ProcessId;
|
||||
public string NodeId { get; private set; } = "";
|
||||
public string PipeName { get; private set; } = "";
|
||||
public bool IsListening => _listening;
|
||||
public bool IsRunning => Volatile.Read(ref _started) != 0 && Volatile.Read(ref _stopped) == 0;
|
||||
public int DroppedEvents => Volatile.Read(ref _droppedEvents);
|
||||
public NodeIdentity Identity => _identity;
|
||||
|
||||
// ── Consumer side (any thread) ──────────────────────────────────────────
|
||||
|
||||
public bool TryDequeueEvent(out NetEvent evt)
|
||||
{
|
||||
if (_events.TryDequeue(out evt!)) { Interlocked.Decrement(ref _eventCount); return true; }
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool TryDequeueLog(out string line)
|
||||
{
|
||||
if (_logs.TryDequeue(out line!)) { Interlocked.Decrement(ref _logCount); return true; }
|
||||
return false;
|
||||
}
|
||||
|
||||
internal void Log(string line)
|
||||
{
|
||||
if (Interlocked.Increment(ref _logCount) > MaxLogs) { Interlocked.Decrement(ref _logCount); return; }
|
||||
_logs.Enqueue(line);
|
||||
}
|
||||
|
||||
private void Raise(NetEvent evt)
|
||||
{
|
||||
if (Interlocked.Increment(ref _eventCount) > MaxEvents)
|
||||
{
|
||||
Interlocked.Decrement(ref _eventCount);
|
||||
Interlocked.Increment(ref _droppedEvents);
|
||||
return;
|
||||
}
|
||||
_events.Enqueue(evt);
|
||||
}
|
||||
|
||||
/// <summary>Copies of the joined clients.</summary>
|
||||
public PeerInfo[] GetPeers()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
var list = new PeerInfo[_peers.Count];
|
||||
int i = 0;
|
||||
foreach (PeerConnection p in _peers.Values)
|
||||
list[i++] = Snapshot(p);
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
||||
public PeerInfo? GetPeer(string nodeId)
|
||||
{
|
||||
lock (_lock) return _peers.TryGetValue(nodeId, out PeerConnection? p) ? Snapshot(p) : null;
|
||||
}
|
||||
|
||||
private static PeerInfo Snapshot(PeerConnection p) => new()
|
||||
{
|
||||
NodeId = p.NodeId,
|
||||
Pid = p.Pid,
|
||||
Outbound = p.Outbound,
|
||||
Identity = p.Identity,
|
||||
StatusJson = p.StatusJson,
|
||||
StatusAtMs = p.StatusAtMs,
|
||||
ConnectedAtMs = p.ConnectedAtMs,
|
||||
RttMs = p.RttMs,
|
||||
};
|
||||
|
||||
/// <summary>Replaces this client's identity and tells every connection (even ones still in hello).</summary>
|
||||
public void SetIdentity(NodeIdentity identity)
|
||||
{
|
||||
_identity = identity;
|
||||
if (!IsRunning) return;
|
||||
byte[] frame = Wire.Ident(identity);
|
||||
foreach (PeerConnection p in LiveConnections()) p.Send(frame);
|
||||
}
|
||||
|
||||
/// <summary>Replaces this client's status (one JSON object) and sends it to every client.</summary>
|
||||
public void SetStatus(string statusObjectJson)
|
||||
{
|
||||
byte[] frame = Wire.Status(statusObjectJson); // throws on invalid JSON: the caller's bug, not the peers'
|
||||
_statusJson = statusObjectJson;
|
||||
if (!IsRunning) return;
|
||||
foreach (PeerConnection p in LiveConnections()) p.Send(frame);
|
||||
}
|
||||
|
||||
/// <summary>Sends a prepared frame to one joined client. False when it isn't connected.</summary>
|
||||
public bool SendTo(string nodeId, byte[] frame)
|
||||
{
|
||||
PeerConnection? p;
|
||||
lock (_lock) _peers.TryGetValue(nodeId, out p);
|
||||
return p != null && p.Send(frame);
|
||||
}
|
||||
|
||||
/// <summary>Sends a prepared frame to every joined client the filter accepts. Returns how many.</summary>
|
||||
public int Broadcast(byte[] frame, Func<PeerInfo, bool>? filter = null)
|
||||
{
|
||||
var targets = new List<PeerConnection>();
|
||||
lock (_lock)
|
||||
{
|
||||
foreach (PeerConnection p in _peers.Values)
|
||||
if (filter == null || filter(Snapshot(p))) targets.Add(p);
|
||||
}
|
||||
int n = 0;
|
||||
foreach (PeerConnection p in targets)
|
||||
if (p.Send(frame)) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
private List<PeerConnection> LiveConnections()
|
||||
{
|
||||
lock (_lock) return new List<PeerConnection>(_connections);
|
||||
}
|
||||
|
||||
internal void Track(Task task)
|
||||
{
|
||||
lock (_lock) _tasks.Add(task);
|
||||
}
|
||||
|
||||
// ── Start / stop ────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Claims a pipe name and starts listening and discovering. False (with a reason) on failure.</summary>
|
||||
public bool Start(out string error)
|
||||
{
|
||||
error = "";
|
||||
if (Interlocked.Exchange(ref _started, 1) != 0) { error = "already started"; return false; }
|
||||
try
|
||||
{
|
||||
_ns = string.IsNullOrEmpty(_options.Namespace) ? PipeSecurityHelper.DefaultNamespace() : _options.Namespace;
|
||||
for (int attempt = 0; attempt < 3 && _firstServer == null; attempt++)
|
||||
{
|
||||
string nonce = PipeSecurityHelper.NewNonce();
|
||||
string name = PipeSecurityHelper.PipeName(_ns, Pid, nonce);
|
||||
try
|
||||
{
|
||||
_firstServer = PipeSecurityHelper.CreateServer(name, first: true);
|
||||
PipeName = name;
|
||||
NodeId = PipeSecurityHelper.NodeId(Pid, nonce);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
error = ex.Message; // the name exists already (someone else's): try another nonce
|
||||
}
|
||||
}
|
||||
if (_firstServer == null)
|
||||
{
|
||||
Interlocked.Exchange(ref _stopped, 1);
|
||||
error = "could not create the pipe: " + error;
|
||||
return false;
|
||||
}
|
||||
|
||||
_cts = new CancellationTokenSource();
|
||||
_listening = true;
|
||||
Track(Task.Run(AcceptLoopAsync));
|
||||
_supervisor = new Thread(SupervisorLoop) { IsBackground = true, Name = "RynthNet supervisor" };
|
||||
_supervisor.Start();
|
||||
Log($"[RynthNet] listening on {PipeName}");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Interlocked.Exchange(ref _stopped, 1);
|
||||
try { _firstServer?.Dispose(); } catch { }
|
||||
_firstServer = null;
|
||||
error = ex.GetType().Name + ": " + ex.Message;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Says bye, cancels, disposes every pipe, then waits up to <paramref name="timeoutMs"/> for
|
||||
/// the supervisor thread and every task. True when everything ended.
|
||||
/// </summary>
|
||||
public bool Stop(int timeoutMs = 2000)
|
||||
{
|
||||
if (Volatile.Read(ref _started) == 0) return true;
|
||||
if (Interlocked.Exchange(ref _stopped, 1) != 0) return true;
|
||||
long deadline = NowMs + timeoutMs;
|
||||
|
||||
// Goodbye first, so the others drop us at once instead of timing out.
|
||||
byte[] bye = Wire.Bye("shutdown");
|
||||
List<PeerConnection> live = LiveConnections();
|
||||
foreach (PeerConnection p in live) p.Send(bye);
|
||||
long byeDeadline = Math.Min(deadline, NowMs + 250);
|
||||
while (NowMs < byeDeadline)
|
||||
{
|
||||
bool flushed = true;
|
||||
foreach (PeerConnection p in live)
|
||||
if (!p.IsClosed && p.QueuedFrames > 0) { flushed = false; break; }
|
||||
if (flushed) break;
|
||||
Thread.Sleep(5);
|
||||
}
|
||||
|
||||
_listening = false;
|
||||
try { _cts?.Cancel(); } catch { }
|
||||
foreach (PeerConnection p in LiveConnections()) p.Close("shutdown");
|
||||
try { _firstServer?.Dispose(); } catch { }
|
||||
|
||||
bool clean = true;
|
||||
if (_supervisor != null)
|
||||
{
|
||||
int left = (int)Math.Max(0, deadline - NowMs);
|
||||
if (!_supervisor.Join(left)) clean = false;
|
||||
}
|
||||
// A task can start another while we wait (the accept loop admitting a last pipe), so
|
||||
// wait until a fresh look finds nothing running.
|
||||
while (true)
|
||||
{
|
||||
Task[] running;
|
||||
lock (_lock) running = _tasks.FindAll(t => !t.IsCompleted).ToArray();
|
||||
if (running.Length == 0) break;
|
||||
long left = deadline - NowMs;
|
||||
if (left <= 0) { clean = false; break; }
|
||||
try { Task.WaitAll(running, (int)left); }
|
||||
catch (AggregateException) { }
|
||||
}
|
||||
if (clean)
|
||||
{
|
||||
lock (_lock) _tasks.Clear();
|
||||
try { _cts?.Dispose(); } catch { }
|
||||
}
|
||||
return clean;
|
||||
}
|
||||
|
||||
public void Dispose() => Stop();
|
||||
|
||||
/// <summary>Threads and tasks of this node still running (0 after a clean Stop).</summary>
|
||||
public int RunningWorkers
|
||||
{
|
||||
get
|
||||
{
|
||||
int n = _supervisor != null && _supervisor.IsAlive ? 1 : 0;
|
||||
lock (_lock)
|
||||
foreach (Task t in _tasks)
|
||||
if (!t.IsCompleted) n++;
|
||||
return n;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Listening ───────────────────────────────────────────────────────────
|
||||
|
||||
private async Task AcceptLoopAsync()
|
||||
{
|
||||
CancellationToken ct = _cts!.Token;
|
||||
NamedPipeServerStream? server = _firstServer;
|
||||
_firstServer = null;
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
server ??= PipeSecurityHelper.CreateServer(PipeName, first: false);
|
||||
await server.WaitForConnectionAsync(ct).ConfigureAwait(false);
|
||||
NamedPipeServerStream accepted = server;
|
||||
server = null;
|
||||
Admit(accepted);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { server?.Dispose(); } catch { }
|
||||
server = null;
|
||||
if (ct.IsCancellationRequested) break;
|
||||
Log($"[RynthNet] listen error: {ex.GetType().Name}: {ex.Message}");
|
||||
try { await Task.Delay(500, ct).ConfigureAwait(false); }
|
||||
catch (OperationCanceledException) { break; }
|
||||
}
|
||||
}
|
||||
try { server?.Dispose(); } catch { }
|
||||
}
|
||||
|
||||
private void Admit(NamedPipeServerStream pipe)
|
||||
{
|
||||
int kernelPid = PipeSecurityHelper.ClientPid(pipe);
|
||||
PeerConnection peer;
|
||||
lock (_lock)
|
||||
{
|
||||
if (_connections.Count >= _options.MaxPeers * 2 || !IsRunning)
|
||||
{
|
||||
try { pipe.Dispose(); } catch { }
|
||||
return;
|
||||
}
|
||||
peer = new PeerConnection(this, pipe, outbound: false, expectedNodeId: "", kernelPid: kernelPid);
|
||||
_connections.Add(peer);
|
||||
}
|
||||
peer.Start(Wire.Hello(NodeId, Pid, _identity));
|
||||
}
|
||||
|
||||
// ── Discovery and dialing (supervisor thread) ───────────────────────────
|
||||
|
||||
private void SupervisorLoop()
|
||||
{
|
||||
CancellationToken ct = _cts!.Token;
|
||||
long nextScan = 0;
|
||||
bool scanErrorLogged = false;
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
long now = NowMs;
|
||||
if (now >= nextScan)
|
||||
{
|
||||
nextScan = now + _options.ScanIntervalMs;
|
||||
try
|
||||
{
|
||||
Scan(now, ct);
|
||||
scanErrorLogged = false;
|
||||
}
|
||||
catch (Exception ex) when (!scanErrorLogged)
|
||||
{
|
||||
scanErrorLogged = true;
|
||||
Log($"[RynthNet] discovery failed: {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
Housekeeping(NowMs);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"[RynthNet] supervisor: {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
ct.WaitHandle.WaitOne(200);
|
||||
}
|
||||
}
|
||||
|
||||
private void Scan(long now, CancellationToken ct)
|
||||
{
|
||||
List<string> names = PipeSecurityHelper.Discover(_ns);
|
||||
foreach (string name in names)
|
||||
{
|
||||
if (ct.IsCancellationRequested) return;
|
||||
if (name == PipeName) continue;
|
||||
if (!PipeSecurityHelper.TryParse(name, _ns, out int pid, out string nodeId)) continue;
|
||||
lock (_lock)
|
||||
{
|
||||
if (_badPipes.TryGetValue(name, out long retryAt) && now < retryAt) continue;
|
||||
if (_peers.ContainsKey(nodeId)) continue;
|
||||
bool pending = false;
|
||||
foreach (PeerConnection c in _connections)
|
||||
if (c.ExpectedNodeId == nodeId || c.NodeId == nodeId) { pending = true; break; }
|
||||
if (pending) continue;
|
||||
if (_connections.Count >= _options.MaxPeers) return;
|
||||
}
|
||||
// Exactly one side of each pair dials: the one whose (pid, node id) sorts first.
|
||||
if (!DialsFirst(Pid, NodeId, pid, nodeId)) continue;
|
||||
Dial(name, pid, nodeId, now);
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool DialsFirst(int myPid, string myNode, int theirPid, string theirNode)
|
||||
=> myPid != theirPid ? myPid < theirPid : string.CompareOrdinal(myNode, theirNode) < 0;
|
||||
|
||||
private void Dial(string name, int pid, string nodeId, long now)
|
||||
{
|
||||
var client = new NamedPipeClientStream(".", name, PipeDirection.InOut, PipeOptions.Asynchronous);
|
||||
try
|
||||
{
|
||||
client.Connect(300);
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
client.Dispose(); // every instance busy right now: next scan
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
client.Dispose();
|
||||
lock (_lock) _badPipes[name] = now + 5000;
|
||||
Log($"[RynthNet] can't open {name}: {ex.GetType().Name}: {ex.Message}");
|
||||
return;
|
||||
}
|
||||
if (!PipeSecurityHelper.VerifyServer(client, pid, out string why))
|
||||
{
|
||||
client.Dispose();
|
||||
lock (_lock) _badPipes[name] = now + 60_000;
|
||||
Log($"[RynthNet] refused {name}: {why}");
|
||||
return;
|
||||
}
|
||||
PeerConnection peer;
|
||||
lock (_lock)
|
||||
{
|
||||
if (!IsRunning) { client.Dispose(); return; }
|
||||
peer = new PeerConnection(this, client, outbound: true, expectedNodeId: nodeId, kernelPid: pid);
|
||||
_connections.Add(peer);
|
||||
}
|
||||
peer.Start(Wire.Hello(NodeId, Pid, _identity));
|
||||
}
|
||||
|
||||
private void Housekeeping(long now)
|
||||
{
|
||||
foreach (PeerConnection p in LiveConnections())
|
||||
{
|
||||
bool joined;
|
||||
lock (_lock) joined = p.Joined;
|
||||
if (!joined)
|
||||
{
|
||||
if (now - p.ConnectedAtMs > _options.HelloTimeoutMs) p.Close("no hello");
|
||||
}
|
||||
else if (now - p.LastReceiveMs > _options.TimeoutMs)
|
||||
{
|
||||
p.Close("timed out");
|
||||
}
|
||||
else if (now - p.LastPingMs >= _options.PingIntervalMs)
|
||||
{
|
||||
p.LastPingMs = now;
|
||||
p.Send(Wire.Ping(now));
|
||||
}
|
||||
}
|
||||
lock (_lock)
|
||||
{
|
||||
if (_badPipes.Count > 0)
|
||||
{
|
||||
var expired = new List<string>();
|
||||
foreach (var kv in _badPipes)
|
||||
if (now >= kv.Value) expired.Add(kv.Key);
|
||||
foreach (string k in expired) _badPipes.Remove(k);
|
||||
}
|
||||
_tasks.RemoveAll(t => t.IsCompleted);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Frames (I/O threads) ────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Handles one frame from a peer. False when the peer was closed because of it.</summary>
|
||||
internal bool OnFrame(PeerConnection peer, byte[] payload)
|
||||
{
|
||||
WireMessage? m = Wire.Parse(payload);
|
||||
if (m == null)
|
||||
{
|
||||
peer.Close("malformed frame");
|
||||
return false;
|
||||
}
|
||||
|
||||
bool joined;
|
||||
lock (_lock) joined = peer.Joined;
|
||||
if (!joined)
|
||||
{
|
||||
if (m.Type != "hello")
|
||||
{
|
||||
peer.Close("expected hello, got " + m.Type);
|
||||
return false;
|
||||
}
|
||||
return OnHello(peer, m);
|
||||
}
|
||||
|
||||
long now = NowMs;
|
||||
switch (m.Type)
|
||||
{
|
||||
case "ident":
|
||||
if (m.Identity == null) break;
|
||||
NodeIdentity updated;
|
||||
lock (_lock)
|
||||
{
|
||||
updated = new NodeIdentity
|
||||
{
|
||||
Character = m.Identity.Character,
|
||||
World = m.Identity.World,
|
||||
Account = m.Identity.Account,
|
||||
LoggedIn = m.Identity.LoggedIn,
|
||||
Tags = m.Identity.Tags,
|
||||
App = peer.Identity.App,
|
||||
};
|
||||
peer.Identity = updated;
|
||||
}
|
||||
Raise(new NetEvent { Kind = NetEventKind.PeerUpdated, NodeId = peer.NodeId, From = updated.Character, AtMs = now });
|
||||
break;
|
||||
case "status":
|
||||
lock (_lock)
|
||||
{
|
||||
peer.StatusJson = m.StatusJson;
|
||||
peer.StatusAtMs = now;
|
||||
}
|
||||
break;
|
||||
case "ping":
|
||||
peer.Send(Wire.Pong(m.Ts));
|
||||
break;
|
||||
case "pong":
|
||||
long rtt = now - m.Ts;
|
||||
if (rtt >= 0 && rtt < 60_000) peer.RttMs = (int)rtt;
|
||||
break;
|
||||
case "cmd":
|
||||
Raise(new NetEvent
|
||||
{
|
||||
Kind = NetEventKind.Command, NodeId = peer.NodeId, From = FromName(peer), Id = m.Id,
|
||||
Target = m.Target, Text = m.Text, DelayMs = m.DelayMs, AtMs = now,
|
||||
});
|
||||
break;
|
||||
case "ack":
|
||||
Raise(new NetEvent { Kind = NetEventKind.Ack, NodeId = peer.NodeId, From = FromName(peer), Id = m.Id, Ok = m.Ok, Text = m.Text, AtMs = now });
|
||||
break;
|
||||
case "data":
|
||||
Raise(new NetEvent
|
||||
{
|
||||
Kind = NetEventKind.Data, NodeId = peer.NodeId, From = FromName(peer), Channel = m.Channel,
|
||||
Text = m.Text, Target = m.Target, AtMs = now,
|
||||
});
|
||||
break;
|
||||
case "bye":
|
||||
peer.Close(m.Text.Length > 0 ? "left (" + m.Text + ")" : "left");
|
||||
return false;
|
||||
// "hello" again, or a type from a newer version: ignored.
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private string FromName(PeerConnection peer)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
string c = peer.Identity.Character;
|
||||
return c.Length > 0 ? c : "pid " + peer.Pid;
|
||||
}
|
||||
}
|
||||
|
||||
private bool OnHello(PeerConnection peer, WireMessage m)
|
||||
{
|
||||
if (m.Proto != Wire.Proto)
|
||||
{
|
||||
peer.Send(Wire.Bye("protocol " + Wire.Proto + " only"));
|
||||
peer.Close($"protocol {m.Proto} (this client speaks {Wire.Proto})");
|
||||
return false;
|
||||
}
|
||||
string expectedPrefix = m.Pid + ".";
|
||||
if (m.Pid <= 0 || !m.NodeId.StartsWith(expectedPrefix, StringComparison.Ordinal) || m.NodeId.Length != expectedPrefix.Length + 16)
|
||||
{
|
||||
peer.Close("bad hello (node id)");
|
||||
return false;
|
||||
}
|
||||
if (peer.Outbound && m.NodeId != peer.ExpectedNodeId)
|
||||
{
|
||||
peer.Close("hello from the wrong node");
|
||||
return false;
|
||||
}
|
||||
if (!peer.Outbound && peer.KernelPid != 0 && peer.KernelPid != m.Pid)
|
||||
{
|
||||
peer.Close($"hello claims pid {m.Pid}, the pipe says {peer.KernelPid}");
|
||||
return false;
|
||||
}
|
||||
if (m.NodeId == NodeId)
|
||||
{
|
||||
peer.Close("connected to itself");
|
||||
return false;
|
||||
}
|
||||
|
||||
NodeIdentity identity = m.Identity ?? new NodeIdentity();
|
||||
string? refused = null;
|
||||
lock (_lock)
|
||||
{
|
||||
if (_peers.ContainsKey(m.NodeId))
|
||||
refused = "duplicate connection"; // only in a restart race; the older link stays
|
||||
else if (_peers.Count >= _options.MaxPeers)
|
||||
refused = "too many clients";
|
||||
else
|
||||
{
|
||||
peer.NodeId = m.NodeId;
|
||||
peer.Pid = m.Pid;
|
||||
peer.Identity = identity;
|
||||
peer.Joined = true;
|
||||
_peers[m.NodeId] = peer;
|
||||
}
|
||||
}
|
||||
if (refused != null)
|
||||
{
|
||||
peer.Send(Wire.Bye(refused));
|
||||
peer.Close(refused);
|
||||
return false;
|
||||
}
|
||||
Raise(new NetEvent { Kind = NetEventKind.PeerJoined, NodeId = m.NodeId, From = identity.Character, AtMs = NowMs });
|
||||
Log($"[RynthNet] {Describe(identity, m.Pid)} connected ({(peer.Outbound ? "dialed" : "accepted")})");
|
||||
string status = _statusJson;
|
||||
if (status.Length > 0) peer.Send(Wire.Status(status));
|
||||
return true;
|
||||
}
|
||||
|
||||
internal void OnPeerClosed(PeerConnection peer, string reason)
|
||||
{
|
||||
bool wasJoined = false;
|
||||
NodeIdentity identity;
|
||||
lock (_lock)
|
||||
{
|
||||
_connections.Remove(peer);
|
||||
if (peer.Joined && _peers.TryGetValue(peer.NodeId, out PeerConnection? current) && ReferenceEquals(current, peer))
|
||||
{
|
||||
_peers.Remove(peer.NodeId);
|
||||
wasJoined = true;
|
||||
}
|
||||
identity = peer.Identity;
|
||||
}
|
||||
if (wasJoined)
|
||||
{
|
||||
Raise(new NetEvent { Kind = NetEventKind.PeerLeft, NodeId = peer.NodeId, From = identity.Character, Text = reason, AtMs = NowMs });
|
||||
Log($"[RynthNet] {Describe(identity, peer.Pid)} disconnected: {reason}");
|
||||
}
|
||||
}
|
||||
|
||||
private static string Describe(NodeIdentity id, int pid)
|
||||
=> id.Character.Length > 0 ? $"{id.Character} (pid {pid})" : $"pid {pid} (not logged in)";
|
||||
}
|
||||
152
Plugins/RynthCore.Plugin.RynthNet/Transport/PeerConnection.cs
Normal file
152
Plugins/RynthCore.Plugin.RynthNet/Transport/PeerConnection.cs
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
// ============================================================================
|
||||
// RynthNet - Transport/PeerConnection.cs
|
||||
// One pipe to one other client: a read loop and a write loop (two tasks),
|
||||
// a bounded send queue, and the peer's identity once its hello arrived.
|
||||
// Closing is idempotent and can come from either loop, the supervisor or
|
||||
// NetNode.Stop; it cancels both loops and disposes the pipe.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections.Concurrent;
|
||||
using System.IO;
|
||||
using System.IO.Pipes;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNet.Transport;
|
||||
|
||||
internal sealed class PeerConnection
|
||||
{
|
||||
/// <summary>Frames waiting to be written before the peer counts as stuck and is dropped.</summary>
|
||||
private const int MaxQueuedFrames = 512;
|
||||
|
||||
private readonly NetNode _node;
|
||||
private readonly PipeStream _pipe;
|
||||
private readonly CancellationTokenSource _cts = new();
|
||||
private readonly ConcurrentQueue<byte[]> _sendQueue = new();
|
||||
private readonly SemaphoreSlim _sendSignal = new(0);
|
||||
private int _queued;
|
||||
private int _closed;
|
||||
private long _lastReceiveMs;
|
||||
private long _lastPingMs;
|
||||
|
||||
public readonly bool Outbound;
|
||||
/// <summary>Outbound: the node id the pipe name promised. Inbound: empty until hello.</summary>
|
||||
public readonly string ExpectedNodeId;
|
||||
/// <summary>The other process id from the kernel (0 when unknown).</summary>
|
||||
public readonly int KernelPid;
|
||||
public readonly long ConnectedAtMs;
|
||||
|
||||
// Written under NetNode's lock.
|
||||
public string NodeId = "";
|
||||
public int Pid;
|
||||
public NodeIdentity Identity = new();
|
||||
public bool Joined;
|
||||
public string StatusJson = "";
|
||||
public long StatusAtMs;
|
||||
|
||||
public volatile int RttMs = -1;
|
||||
public string CloseReason { get; private set; } = "";
|
||||
|
||||
public PeerConnection(NetNode node, PipeStream pipe, bool outbound, string expectedNodeId, int kernelPid)
|
||||
{
|
||||
_node = node;
|
||||
_pipe = pipe;
|
||||
Outbound = outbound;
|
||||
ExpectedNodeId = expectedNodeId;
|
||||
KernelPid = kernelPid;
|
||||
ConnectedAtMs = NetNode.NowMs;
|
||||
_lastReceiveMs = ConnectedAtMs;
|
||||
}
|
||||
|
||||
public bool IsClosed => Volatile.Read(ref _closed) != 0;
|
||||
public int QueuedFrames => Volatile.Read(ref _queued);
|
||||
public long LastReceiveMs => Interlocked.Read(ref _lastReceiveMs);
|
||||
public long LastPingMs { get => Interlocked.Read(ref _lastPingMs); set => Interlocked.Exchange(ref _lastPingMs, value); }
|
||||
|
||||
/// <summary>Starts both loops; the hello frame goes first.</summary>
|
||||
public void Start(byte[] hello)
|
||||
{
|
||||
Send(hello);
|
||||
_node.Track(Task.Run(WriteLoopAsync));
|
||||
_node.Track(Task.Run(ReadLoopAsync));
|
||||
}
|
||||
|
||||
/// <summary>Queues a frame. Thread-safe. False when closed or when the peer stopped reading.</summary>
|
||||
public bool Send(byte[] frame)
|
||||
{
|
||||
if (IsClosed) return false;
|
||||
if (Interlocked.Increment(ref _queued) > MaxQueuedFrames)
|
||||
{
|
||||
Interlocked.Decrement(ref _queued);
|
||||
Close("stopped reading (send queue full)");
|
||||
return false;
|
||||
}
|
||||
_sendQueue.Enqueue(frame);
|
||||
try { _sendSignal.Release(); }
|
||||
catch (ObjectDisposedException) { }
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task WriteLoopAsync()
|
||||
{
|
||||
CancellationToken ct = _cts.Token;
|
||||
try
|
||||
{
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
await _sendSignal.WaitAsync(ct).ConfigureAwait(false);
|
||||
while (_sendQueue.TryDequeue(out byte[]? frame))
|
||||
{
|
||||
await _pipe.WriteAsync(frame, ct).ConfigureAwait(false);
|
||||
Interlocked.Decrement(ref _queued);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
catch (ObjectDisposedException) { Close("pipe closed"); }
|
||||
catch (IOException ex) { Close("write failed: " + ex.Message); }
|
||||
catch (Exception ex) { Close("write failed: " + ex.GetType().Name + ": " + ex.Message); }
|
||||
}
|
||||
|
||||
private async Task ReadLoopAsync()
|
||||
{
|
||||
CancellationToken ct = _cts.Token;
|
||||
byte[] header = new byte[4];
|
||||
try
|
||||
{
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
await _pipe.ReadExactlyAsync(header, ct).ConfigureAwait(false);
|
||||
int length = BinaryPrimitives.ReadInt32LittleEndian(header);
|
||||
if (length < 0 || length > Wire.MaxFrame)
|
||||
{
|
||||
Close($"bad frame length {length}");
|
||||
return;
|
||||
}
|
||||
Interlocked.Exchange(ref _lastReceiveMs, NetNode.NowMs);
|
||||
if (length == 0) continue; // keepalive
|
||||
byte[] payload = new byte[length];
|
||||
await _pipe.ReadExactlyAsync(payload, ct).ConfigureAwait(false);
|
||||
Interlocked.Exchange(ref _lastReceiveMs, NetNode.NowMs);
|
||||
if (!_node.OnFrame(this, payload)) return;
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
catch (EndOfStreamException) { Close("disconnected"); }
|
||||
catch (ObjectDisposedException) { Close("pipe closed"); }
|
||||
catch (IOException ex) { Close("read failed: " + ex.Message); }
|
||||
catch (Exception ex) { Close("read failed: " + ex.GetType().Name + ": " + ex.Message); }
|
||||
}
|
||||
|
||||
/// <summary>Idempotent: cancels both loops, disposes the pipe, tells the node.</summary>
|
||||
public void Close(string reason)
|
||||
{
|
||||
if (Interlocked.Exchange(ref _closed, 1) != 0) return;
|
||||
CloseReason = reason;
|
||||
try { _cts.Cancel(); } catch { }
|
||||
try { _pipe.Dispose(); } catch { }
|
||||
_node.OnPeerClosed(this, reason);
|
||||
}
|
||||
}
|
||||
169
Plugins/RynthCore.Plugin.RynthNet/Transport/PipeSecurity.cs
Normal file
169
Plugins/RynthCore.Plugin.RynthNet/Transport/PipeSecurity.cs
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
// ============================================================================
|
||||
// RynthNet - Transport/PipeSecurity.cs
|
||||
// Local-only, same-user-only named pipes.
|
||||
//
|
||||
// - Pipe names: RynthNet.1.<ns>.<pid>.<nonce>
|
||||
// ns = hash of (Windows user SID, Windows session id): clients of one
|
||||
// user in one session find each other; nobody else's are listed.
|
||||
// pid = the owning process, checked against the kernel after connecting.
|
||||
// nonce = random per start, so a name can't be guessed or pre-created.
|
||||
// - Server ACL: owner = current user; allow current user; deny NETWORK (no
|
||||
// SMB access to \\machine\pipe\..., even with the same credentials). Other
|
||||
// users, services and remote machines can't open the pipe at all.
|
||||
// - Client side: before sending anything, the dialer checks that the pipe's
|
||||
// owner is the current user (so another user's squatting pipe gets nothing)
|
||||
// and that the server process id matches the pid in the name.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.IO.Pipes;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.AccessControl;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Principal;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNet.Transport;
|
||||
|
||||
internal static class PipeSecurityHelper
|
||||
{
|
||||
public const string Prefix = "RynthNet.1.";
|
||||
private const string PipeRoot = @"\\.\pipe\";
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern int GetNamedPipeServerProcessId(IntPtr pipe, out uint serverProcessId);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern int GetNamedPipeClientProcessId(IntPtr pipe, out uint clientProcessId);
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern int ProcessIdToSessionId(uint processId, out uint sessionId);
|
||||
|
||||
private static SecurityIdentifier? _user;
|
||||
|
||||
public static SecurityIdentifier CurrentUser
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_user != null) return _user;
|
||||
using var identity = WindowsIdentity.GetCurrent();
|
||||
_user = identity.User ?? throw new InvalidOperationException("no user SID for this process");
|
||||
return _user;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The per-user, per-session namespace part of the pipe names.</summary>
|
||||
public static string DefaultNamespace()
|
||||
{
|
||||
uint session = 0;
|
||||
try { ProcessIdToSessionId((uint)Environment.ProcessId, out session); } catch { }
|
||||
byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(CurrentUser.Value + "|" + session.ToString(CultureInfo.InvariantCulture)));
|
||||
return Convert.ToHexString(hash, 0, 8).ToLowerInvariant();
|
||||
}
|
||||
|
||||
public static string NewNonce() => Convert.ToHexString(RandomNumberGenerator.GetBytes(8)).ToLowerInvariant();
|
||||
|
||||
public static string PipeName(string ns, int pid, string nonce) => $"{Prefix}{ns}.{pid}.{nonce}";
|
||||
|
||||
/// <summary>The node id is the pid and nonce: "pid.nonce".</summary>
|
||||
public static string NodeId(int pid, string nonce) => $"{pid}.{nonce}";
|
||||
|
||||
public static bool TryParse(string pipeName, string ns, out int pid, out string nodeId)
|
||||
{
|
||||
pid = 0;
|
||||
nodeId = "";
|
||||
string head = Prefix + ns + ".";
|
||||
if (!pipeName.StartsWith(head, StringComparison.Ordinal)) return false;
|
||||
string rest = pipeName.Substring(head.Length);
|
||||
int dot = rest.IndexOf('.');
|
||||
if (dot <= 0 || dot == rest.Length - 1) return false;
|
||||
if (!int.TryParse(rest.AsSpan(0, dot), NumberStyles.None, CultureInfo.InvariantCulture, out pid) || pid <= 0) return false;
|
||||
string nonce = rest.Substring(dot + 1);
|
||||
if (nonce.Length != 16) return false;
|
||||
foreach (char c in nonce)
|
||||
if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) return false;
|
||||
nodeId = NodeId(pid, nonce);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Names of the pipes in this namespace (live: a crashed client's pipe is gone with it).</summary>
|
||||
public static List<string> Discover(string ns)
|
||||
{
|
||||
var names = new List<string>();
|
||||
string head = Prefix + ns + ".";
|
||||
foreach (string path in Directory.EnumerateFiles(PipeRoot, head + "*"))
|
||||
{
|
||||
string name = path.StartsWith(PipeRoot, StringComparison.OrdinalIgnoreCase) ? path.Substring(PipeRoot.Length) : Path.GetFileName(path);
|
||||
if (name.StartsWith(head, StringComparison.Ordinal)) names.Add(name);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
private static PipeSecurity CreateSecurity()
|
||||
{
|
||||
var security = new PipeSecurity();
|
||||
SecurityIdentifier me = CurrentUser;
|
||||
security.SetOwner(me);
|
||||
security.SetAccessRuleProtection(isProtected: true, preserveInheritance: false);
|
||||
security.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.NetworkSid, null),
|
||||
PipeAccessRights.FullControl, AccessControlType.Deny));
|
||||
security.AddAccessRule(new PipeAccessRule(me, PipeAccessRights.FullControl, AccessControlType.Allow));
|
||||
return security;
|
||||
}
|
||||
|
||||
/// <summary>One listening instance. <paramref name="first"/> claims the name (fails if it exists).</summary>
|
||||
public static NamedPipeServerStream CreateServer(string pipeName, bool first)
|
||||
{
|
||||
PipeOptions options = PipeOptions.Asynchronous;
|
||||
if (first) options |= PipeOptions.FirstPipeInstance;
|
||||
return NamedPipeServerStreamAcl.Create(pipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances,
|
||||
PipeTransmissionMode.Byte, options, Wire.MaxFrame, Wire.MaxFrame, CreateSecurity());
|
||||
}
|
||||
|
||||
/// <summary>After connecting: is this our user's pipe, served by the process its name says?</summary>
|
||||
public static bool VerifyServer(NamedPipeClientStream pipe, int expectedPid, out string why)
|
||||
{
|
||||
why = "";
|
||||
try
|
||||
{
|
||||
PipeSecurity security = pipe.GetAccessControl();
|
||||
if (security.GetOwner(typeof(SecurityIdentifier)) is not SecurityIdentifier owner || owner != CurrentUser)
|
||||
{
|
||||
why = "pipe owned by another user";
|
||||
return false;
|
||||
}
|
||||
if (GetNamedPipeServerProcessId(pipe.SafePipeHandle.DangerousGetHandle(), out uint pid) == 0)
|
||||
{
|
||||
why = "server process unknown (error " + Marshal.GetLastWin32Error() + ")";
|
||||
return false;
|
||||
}
|
||||
if (pid != (uint)expectedPid)
|
||||
{
|
||||
why = $"server pid {pid} is not {expectedPid}";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
why = ex.GetType().Name + ": " + ex.Message;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The process id of the client connected to a server instance, 0 when unknown.</summary>
|
||||
public static int ClientPid(NamedPipeServerStream pipe)
|
||||
{
|
||||
try
|
||||
{
|
||||
return GetNamedPipeClientProcessId(pipe.SafePipeHandle.DangerousGetHandle(), out uint pid) != 0 ? (int)pid : 0;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
264
Plugins/RynthCore.Plugin.RynthNet/Transport/Wire.cs
Normal file
264
Plugins/RynthCore.Plugin.RynthNet/Transport/Wire.cs
Normal file
|
|
@ -0,0 +1,264 @@
|
|||
// ============================================================================
|
||||
// RynthNet - Transport/Wire.cs
|
||||
// The wire format: a frame is a 4-byte little-endian length followed by that
|
||||
// many bytes of UTF-8 JSON (one object). Written with Utf8JsonWriter and read
|
||||
// with JsonDocument: no reflection, safe under NativeAOT and in a collectible
|
||||
// plugin context.
|
||||
//
|
||||
// Every object has "t" (its type). hello also carries "proto" (the protocol
|
||||
// version); a peer with a different major version is refused. Unknown types
|
||||
// and unknown fields are ignored, so fields can be added without a bump.
|
||||
//
|
||||
// hello {t,proto,node,pid,app,char,world,acct,login,tags[]} first frame, both ways
|
||||
// ident {t,char,world,acct,login,tags[]} identity changed
|
||||
// status {t,s:{...}} vitals/position/bot, ~1 Hz
|
||||
// cmd {t,id,to:{k,v},text,delay} run a chat command
|
||||
// ack {t,id,ok,why} answer to cmd
|
||||
// data {t,ch,msg,to:{k,v}} channel message (plugins, Lua)
|
||||
// ping {t,ts} / pong {t,ts} liveness + round trip
|
||||
// bye {t,why} leaving on purpose
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNet.Transport;
|
||||
|
||||
public static class Wire
|
||||
{
|
||||
public const int Proto = 1;
|
||||
public const int MaxFrame = 64 * 1024;
|
||||
public const int MaxText = 1000;
|
||||
public const int MaxMessage = 16 * 1024;
|
||||
public const int MaxName = 64;
|
||||
public const int MaxTags = 32;
|
||||
public const int MaxTagLength = 32;
|
||||
|
||||
private static readonly JsonWriterOptions WriterOptions = new() { Indented = false, SkipValidation = false };
|
||||
private static readonly JsonDocumentOptions ReaderOptions = new() { MaxDepth = 16, AllowTrailingCommas = false, CommentHandling = JsonCommentHandling.Disallow };
|
||||
|
||||
// ── Building frames ─────────────────────────────────────────────────────
|
||||
|
||||
private static byte[] Frame(Action<Utf8JsonWriter> body)
|
||||
{
|
||||
var buffer = new ArrayBufferWriter<byte>(256);
|
||||
buffer.GetSpan(4);
|
||||
buffer.Advance(4); // room for the length prefix
|
||||
using (var w = new Utf8JsonWriter(buffer, WriterOptions))
|
||||
{
|
||||
w.WriteStartObject();
|
||||
body(w);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
byte[] frame = buffer.WrittenSpan.ToArray();
|
||||
int len = frame.Length - 4;
|
||||
if (len > MaxFrame) throw new InvalidOperationException($"frame too large ({len} bytes)");
|
||||
BinaryPrimitives.WriteInt32LittleEndian(frame, len);
|
||||
return frame;
|
||||
}
|
||||
|
||||
private static string Clip(string? s, int max) => string.IsNullOrEmpty(s) ? "" : (s.Length <= max ? s : s.Substring(0, max));
|
||||
|
||||
private static void WriteIdentity(Utf8JsonWriter w, NodeIdentity id)
|
||||
{
|
||||
w.WriteString("char", Clip(id.Character, MaxName));
|
||||
w.WriteString("world", Clip(id.World, MaxName));
|
||||
w.WriteString("acct", Clip(id.Account, MaxName));
|
||||
w.WriteBoolean("login", id.LoggedIn);
|
||||
w.WriteStartArray("tags");
|
||||
int n = 0;
|
||||
foreach (string t in id.Tags)
|
||||
{
|
||||
if (n++ >= MaxTags) break;
|
||||
w.WriteStringValue(Clip(t, MaxTagLength));
|
||||
}
|
||||
w.WriteEndArray();
|
||||
}
|
||||
|
||||
private static void WriteTarget(Utf8JsonWriter w, NetTarget to)
|
||||
{
|
||||
w.WriteStartObject("to");
|
||||
w.WriteString("k", to.KindName);
|
||||
w.WriteString("v", Clip(to.Value, 512));
|
||||
w.WriteEndObject();
|
||||
}
|
||||
|
||||
public static byte[] Hello(string nodeId, int pid, NodeIdentity id) => Frame(w =>
|
||||
{
|
||||
w.WriteString("t", "hello");
|
||||
w.WriteNumber("proto", Proto);
|
||||
w.WriteString("node", nodeId);
|
||||
w.WriteNumber("pid", pid);
|
||||
w.WriteString("app", Clip(id.App, MaxName));
|
||||
WriteIdentity(w, id);
|
||||
});
|
||||
|
||||
public static byte[] Ident(NodeIdentity id) => Frame(w =>
|
||||
{
|
||||
w.WriteString("t", "ident");
|
||||
WriteIdentity(w, id);
|
||||
});
|
||||
|
||||
/// <summary><paramref name="statusObjectJson"/> must be one JSON object (it is validated).</summary>
|
||||
public static byte[] Status(string statusObjectJson) => Frame(w =>
|
||||
{
|
||||
w.WriteString("t", "status");
|
||||
w.WritePropertyName("s");
|
||||
w.WriteRawValue(string.IsNullOrEmpty(statusObjectJson) ? "{}" : statusObjectJson);
|
||||
});
|
||||
|
||||
public static byte[] Command(string id, NetTarget to, string text, int delayMs) => Frame(w =>
|
||||
{
|
||||
w.WriteString("t", "cmd");
|
||||
w.WriteString("id", id);
|
||||
WriteTarget(w, to);
|
||||
w.WriteString("text", Clip(text, MaxText));
|
||||
w.WriteNumber("delay", Math.Clamp(delayMs, 0, 600_000));
|
||||
});
|
||||
|
||||
public static byte[] Ack(string id, bool ok, string why) => Frame(w =>
|
||||
{
|
||||
w.WriteString("t", "ack");
|
||||
w.WriteString("id", id);
|
||||
w.WriteBoolean("ok", ok);
|
||||
w.WriteString("why", Clip(why, 200));
|
||||
});
|
||||
|
||||
public static byte[] Data(string channel, string message, NetTarget to) => Frame(w =>
|
||||
{
|
||||
w.WriteString("t", "data");
|
||||
w.WriteString("ch", Clip(channel, MaxName));
|
||||
w.WriteString("msg", Clip(message, MaxMessage));
|
||||
WriteTarget(w, to);
|
||||
});
|
||||
|
||||
public static byte[] Ping(long ts) => Frame(w => { w.WriteString("t", "ping"); w.WriteNumber("ts", ts); });
|
||||
public static byte[] Pong(long ts) => Frame(w => { w.WriteString("t", "pong"); w.WriteNumber("ts", ts); });
|
||||
public static byte[] Bye(string why) => Frame(w => { w.WriteString("t", "bye"); w.WriteString("why", Clip(why, 200)); });
|
||||
|
||||
// ── Reading frames ──────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Parses one frame's payload. Returns null for anything malformed (the caller drops
|
||||
/// the connection); unknown types come back with only Type set (the caller ignores them).
|
||||
/// </summary>
|
||||
public static WireMessage? Parse(ReadOnlyMemory<byte> payload)
|
||||
{
|
||||
try
|
||||
{
|
||||
using JsonDocument doc = JsonDocument.Parse(payload, ReaderOptions);
|
||||
JsonElement root = doc.RootElement;
|
||||
if (root.ValueKind != JsonValueKind.Object) return null;
|
||||
string type = Str(root, "t");
|
||||
if (type.Length == 0) return null;
|
||||
var m = new WireMessage { Type = type };
|
||||
switch (type)
|
||||
{
|
||||
case "hello":
|
||||
m.Proto = Int(root, "proto");
|
||||
m.NodeId = Clip(Str(root, "node"), 80);
|
||||
m.Pid = Int(root, "pid");
|
||||
m.Identity = ReadIdentity(root, Clip(Str(root, "app"), MaxName));
|
||||
break;
|
||||
case "ident":
|
||||
m.Identity = ReadIdentity(root, "");
|
||||
break;
|
||||
case "status":
|
||||
if (root.TryGetProperty("s", out JsonElement s) && s.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
string raw = s.GetRawText();
|
||||
m.StatusJson = raw.Length <= MaxFrame ? raw : "";
|
||||
}
|
||||
break;
|
||||
case "cmd":
|
||||
m.Id = Clip(Str(root, "id"), 80);
|
||||
m.Target = ReadTarget(root);
|
||||
m.Text = Clip(Str(root, "text"), MaxText);
|
||||
m.DelayMs = Math.Clamp(Int(root, "delay"), 0, 600_000);
|
||||
break;
|
||||
case "ack":
|
||||
m.Id = Clip(Str(root, "id"), 80);
|
||||
m.Ok = root.TryGetProperty("ok", out JsonElement ok) && ok.ValueKind == JsonValueKind.True;
|
||||
m.Text = Clip(Str(root, "why"), 200);
|
||||
break;
|
||||
case "data":
|
||||
m.Channel = Clip(Str(root, "ch"), MaxName);
|
||||
m.Text = Clip(Str(root, "msg"), MaxMessage);
|
||||
m.Target = ReadTarget(root);
|
||||
break;
|
||||
case "ping":
|
||||
case "pong":
|
||||
m.Ts = Long(root, "ts");
|
||||
break;
|
||||
case "bye":
|
||||
m.Text = Clip(Str(root, "why"), 200);
|
||||
break;
|
||||
}
|
||||
return m;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static NodeIdentity ReadIdentity(JsonElement root, string app)
|
||||
{
|
||||
var tags = new List<string>();
|
||||
if (root.TryGetProperty("tags", out JsonElement arr) && arr.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (JsonElement t in arr.EnumerateArray())
|
||||
{
|
||||
if (tags.Count >= MaxTags) break;
|
||||
if (t.ValueKind != JsonValueKind.String) continue;
|
||||
string tag = Clip(t.GetString(), MaxTagLength).Trim();
|
||||
if (tag.Length > 0) tags.Add(tag);
|
||||
}
|
||||
}
|
||||
return new NodeIdentity
|
||||
{
|
||||
Character = Clip(Str(root, "char"), MaxName),
|
||||
World = Clip(Str(root, "world"), MaxName),
|
||||
Account = Clip(Str(root, "acct"), MaxName),
|
||||
LoggedIn = root.TryGetProperty("login", out JsonElement l) && l.ValueKind == JsonValueKind.True,
|
||||
Tags = tags.ToArray(),
|
||||
App = app,
|
||||
};
|
||||
}
|
||||
|
||||
private static NetTarget ReadTarget(JsonElement root)
|
||||
{
|
||||
if (!root.TryGetProperty("to", out JsonElement to) || to.ValueKind != JsonValueKind.Object) return NetTarget.All;
|
||||
return NetTarget.Parse(Str(to, "k"), Clip(Str(to, "v"), 512));
|
||||
}
|
||||
|
||||
private static string Str(JsonElement e, string name)
|
||||
=> e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : "";
|
||||
|
||||
private static int Int(JsonElement e, string name)
|
||||
=> e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : 0;
|
||||
|
||||
private static long Long(JsonElement e, string name)
|
||||
=> e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out long i) ? i : 0;
|
||||
}
|
||||
|
||||
/// <summary>One parsed frame. Only the fields of its <see cref="Type"/> are set.</summary>
|
||||
public sealed class WireMessage
|
||||
{
|
||||
public string Type = "";
|
||||
public int Proto;
|
||||
public string NodeId = "";
|
||||
public int Pid;
|
||||
public NodeIdentity? Identity;
|
||||
public string StatusJson = "";
|
||||
public string Id = "";
|
||||
public NetTarget Target = NetTarget.All;
|
||||
public string Text = "";
|
||||
public int DelayMs;
|
||||
public bool Ok;
|
||||
public string Channel = "";
|
||||
public long Ts;
|
||||
}
|
||||
Loading…
Reference in a new issue