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:
Tom Bohar 2026-10-04 18:34:29 -04:00
commit 12ca25f911
426 changed files with 108239 additions and 7521 deletions

View file

@ -0,0 +1,112 @@
// ============================================================================
// RynthNet - CommandParser.cs
// Argument parsing for /rn and the UB-compatible /ub bc, /ub bct forms. Pure,
// so the harness tests it directly.
//
// UtilityBelt's syntax (docs: utilitybelt.gitlab.io/docs/tools/networking):
// /ub bc [millisecondDelay] <command>
// /ub bct <tag,tag|"some tag"> [millisecondDelay] <command>
// ============================================================================
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthNet;
internal static class CommandParser
{
/// <summary>"[delay] command": a leading all-digit word followed by more text is the delay in ms.</summary>
public static void DelayAndCommand(string rest, out int delayMs, out string command)
{
delayMs = 0;
command = (rest ?? "").Trim();
int sp = command.IndexOf(' ');
if (sp <= 0) return;
string first = command.Substring(0, sp);
foreach (char c in first)
if (c < '0' || c > '9') return;
if (first.Length > 7) return; // over 9999999 ms: not a delay
delayMs = int.Parse(first, System.Globalization.CultureInfo.InvariantCulture);
command = command.Substring(sp + 1).Trim();
}
/// <summary>
/// A comma-separated tag list (no spaces, or "quoted tags"), then the rest. False when no tag.
/// </summary>
public static bool TagsAndRest(string input, out List<string> tags, out string rest)
{
var list = new List<string>();
tags = list;
rest = "";
string s = (input ?? "").TrimStart();
int i = 0;
var current = new System.Text.StringBuilder();
bool quoted = false;
for (; i < s.Length; i++)
{
char c = s[i];
if (quoted)
{
if (c == '"') quoted = false;
else current.Append(c);
continue;
}
if (c == '"') { quoted = true; continue; }
if (c == ',') { Flush(); continue; }
if (char.IsWhiteSpace(c)) break;
current.Append(c);
}
Flush();
rest = i < s.Length ? s.Substring(i).Trim() : "";
return list.Count > 0;
void Flush()
{
string t = current.ToString().Trim();
current.Clear();
if (t.Length > 0 && !list.Exists(x => string.Equals(x, t, StringComparison.OrdinalIgnoreCase))) list.Add(t);
}
}
/// <summary>
/// "/rn tell &lt;character&gt; &lt;command&gt;". Names can have spaces: "Name, command" splits at the
/// comma (as AC's /tell does); otherwise the longest known name the text starts with wins,
/// else the first word.
/// </summary>
public static bool NameAndCommand(string input, IEnumerable<string> knownNames, out string name, out string command)
{
name = "";
command = "";
string s = (input ?? "").Trim();
if (s.Length == 0) return false;
int comma = s.IndexOf(',');
int slash = s.IndexOf('/');
if (comma > 0 && (slash < 0 || comma < slash))
{
name = s.Substring(0, comma).Trim();
command = s.Substring(comma + 1).Trim();
return name.Length > 0 && command.Length > 0;
}
string best = "";
foreach (string known in knownNames)
{
if (string.IsNullOrEmpty(known) || known.Length <= best.Length) continue;
if (s.Length > known.Length && s.StartsWith(known, StringComparison.OrdinalIgnoreCase) && s[known.Length] == ' ')
best = known;
}
if (best.Length > 0)
{
name = best;
command = s.Substring(best.Length).Trim();
return command.Length > 0;
}
int sp = s.IndexOf(' ');
if (sp <= 0) return false;
name = s.Substring(0, sp);
command = s.Substring(sp + 1).Trim();
return command.Length > 0;
}
}

View file

@ -0,0 +1,74 @@
// ============================================================================
// RynthNet - CommandPolicy.cs
// Whether a command another client sent may run here. Pure (no host calls),
// so the harness tests it directly.
//
// Order: remote commands off -> sender not trusted -> loop guard -> deny list
// -> allow list. The loop guard is not a setting: a received command may never
// broadcast again (/rn ..., /ub bc, /ub bct anywhere in it, e.g. behind
// /ub delay), or two clients could bounce a command between them forever.
// ============================================================================
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthNet;
internal static class CommandPolicy
{
/// <summary>Lower-cased, trimmed, single-spaced.</summary>
public static string Normalize(string text)
{
var parts = (text ?? "").Trim().Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
return string.Join(" ", parts).ToLowerInvariant();
}
/// <summary>True when the command would send commands to other clients again.</summary>
public static bool Rebroadcasts(string text)
{
string[] words = Normalize(text).Split(' ');
for (int i = 0; i < words.Length; i++)
{
if (words[i] == "/rn") return true;
if (words[i] == "/ub" && i + 1 < words.Length && words[i + 1] is "bc" or "bct") return true;
}
return false;
}
public static bool Check(string text, string sender, RynthNetPolicy s, out string why)
{
why = "";
string norm = Normalize(text);
if (norm.Length == 0) { why = "empty command"; return false; }
if (!s.AcceptRemoteCommands) { why = "remote commands are off here (/rn remote on)"; return false; }
if (s.TrustedSenders.Count > 0 && !Contains(s.TrustedSenders, sender))
{
why = $"{sender} is not in the trusted list here";
return false;
}
if (Rebroadcasts(norm)) { why = "a received command can't broadcast again"; return false; }
foreach (string d in s.Deny)
{
string p = Normalize(d);
if (p.Length > 0 && norm.StartsWith(p, StringComparison.Ordinal)) { why = $"denied here ({d})"; return false; }
}
if (s.Allow.Count > 0)
{
foreach (string a in s.Allow)
{
string p = Normalize(a);
if (p.Length > 0 && norm.StartsWith(p, StringComparison.Ordinal)) return true;
}
why = "not in the allow list here";
return false;
}
return true;
}
private static bool Contains(List<string> list, string value)
{
foreach (string s in list)
if (string.Equals(s, value, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
}

View file

@ -0,0 +1,152 @@
// ============================================================================
// RynthNet - NetInterface.cs
// RynthNet's side of the "RynthNet.Net" interface (Plugins/Shared/RynthNetApi.cs):
// the table RynthPluginQueryInterface hands out and the functions behind it.
// They run on the plugin pump thread (the caller's OnTick) and act on the
// current plugin instance. The table is freed in RynthPluginShutdown; callers
// resolve it again every tick.
// ============================================================================
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Plugin.RynthNet.Transport;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthNet;
internal static unsafe class NetInterface
{
private static RynthNetApiV1* _table;
private static IntPtr _out; // the last string handed back (valid until the next call)
public static IntPtr Query(string iface, uint version)
{
if (iface != RynthNetApiV1.InterfaceName || version == 0 || version > RynthNetApiV1.InterfaceVersion) return IntPtr.Zero;
if (PluginExports.Runtime.Plugin == null) return IntPtr.Zero;
if (_table == null)
{
var t = (RynthNetApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthNetApiV1));
t->Version = RynthNetApiV1.InterfaceVersion;
t->StructSize = (uint)sizeof(RynthNetApiV1);
t->IsOnline = &IsOnline;
t->GetClientsJson = &GetClientsJson;
t->GetSelfJson = &GetSelfJson;
t->SendCommand = &SendCommand;
t->Publish = &Publish;
t->Subscribe = &Subscribe;
t->PollChannel = &PollChannel;
t->GetTags = &GetTags;
t->SetTag = &SetTag;
_table = t;
}
return (IntPtr)_table;
}
/// <summary>Frees the table and the last string (plugin shutdown).</summary>
public static void Release()
{
var t = _table;
_table = null;
if (t != null) NativeMemory.Free(t);
IntPtr o = _out;
_out = IntPtr.Zero;
if (o != IntPtr.Zero) Marshal.FreeCoTaskMem(o);
}
private static RynthNetPlugin? P => PluginExports.Runtime.Plugin;
private static string In(byte* s) => s == null ? "" : Marshal.PtrToStringUTF8((IntPtr)s) ?? "";
private static int Out(byte** dst, string? value)
{
if (dst == null || value == null) return 0;
IntPtr fresh = Marshal.StringToCoTaskMemUTF8(value);
IntPtr old = _out;
_out = fresh;
if (old != IntPtr.Zero) Marshal.FreeCoTaskMem(old);
*dst = (byte*)fresh;
return 1;
}
private static NetTarget Target(int kind, byte* target) => kind switch
{
RynthNetApiV1.TargetTags => new NetTarget(TargetKind.Tags, In(target)),
RynthNetApiV1.TargetCharacter => new NetTarget(TargetKind.Character, In(target)),
_ => NetTarget.All,
};
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int IsOnline()
{
try { return P?.IsOnline == true ? 1 : 0; }
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetClientsJson(byte** json)
{
try { return Out(json, P?.ClientsJson()); }
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetSelfJson(byte** json)
{
try { return Out(json, P?.SelfJson()); }
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SendCommand(int kind, byte* target, byte* command, int delayMs, int flags)
{
try
{
var p = P;
if (p == null || kind < 0 || kind > 2) return -1;
var names = p.SendCommand(Target(kind, target), In(command), delayMs, (flags & RynthNetApiV1.FlagIncludeSelf) != 0, quiet: true);
return names?.Count ?? -1;
}
catch { return -1; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Publish(byte* channel, byte* message, int kind, byte* target)
{
try
{
var p = P;
if (p == null || kind < 0 || kind > 2) return -1;
return p.Publish(In(channel), In(message), Target(kind, target));
}
catch { return -1; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Subscribe(byte* channel, int on)
{
try { return P?.Subscribe(In(channel), on != 0) == true ? 1 : 0; }
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int PollChannel(byte* channel, byte** json)
{
try { return Out(json, P?.PollChannel(In(channel))); }
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetTags(byte** text)
{
try { return Out(text, P?.TagsText); }
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SetTag(byte* tag, int on)
{
try { return P?.SetTag(In(tag), on != 0, out _) == true ? 1 : 0; }
catch { return 0; }
}
}

View file

@ -0,0 +1,102 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthNet;
public static unsafe class PluginExports
{
internal static readonly RynthPluginRuntime<RynthNetPlugin> Runtime = new();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Init(RynthCoreApiNative* api) => Runtime.Init(api);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Shutdown()
{
Runtime.Shutdown(); // stops the transport: joins its thread and tasks
NetInterface.Release();
ReleaseSnapshot();
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetName() => RynthNetPlugin.NamePointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion() => RynthNetPlugin.VersionPointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Tick() => Runtime.OnTick();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLoginComplete() => Runtime.OnLoginComplete();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLogout() => Runtime.OnLogout();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag);
// Typed interface for other plugins (host GetPluginInterface, API v68): "RynthNet.Net" v1.
// Fixed signature: void* (const char* iface, uint version).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginQueryInterface", CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr QueryInterface(IntPtr ifaceAnsi, uint version)
{
try
{
string iface = ifaceAnsi == IntPtr.Zero ? "" : Marshal.PtrToStringAnsi(ifaceAnsi) ?? "";
return NetInterface.Query(iface, version);
}
catch
{
return IntPtr.Zero;
}
}
// Commands from other plugins (host SendPluginCommand): RynthAi forwards UtilityBelt's
// /ub bc, /ub bct, /ub netclients as ("ub", "bc ..."). Copied and queued; run in OnTick.
[UnmanagedCallersOnly(EntryPoint = "RynthPluginApplyRemoteCommand", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void ApplyRemoteCommand(IntPtr actionAnsi, IntPtr valueAnsi)
{
try
{
string action = actionAnsi != IntPtr.Zero ? Marshal.PtrToStringAnsi(actionAnsi) ?? "" : "";
string value = valueAnsi != IntPtr.Zero ? Marshal.PtrToStringAnsi(valueAnsi) ?? "" : "";
if (action.Length > 0) Runtime.Plugin?.EnqueueForwarded(action, value);
}
catch { }
}
// Snapshot for panels (host GetPluginSnapshotJson): {online,node,char,tags,clients:[...]}.
// Polled from other threads: a per-thread buffer, so no caller frees another's pointer
// (the RynthAi pattern). The string itself is rebuilt by OnTick twice a second.
[ThreadStatic] private static IntPtr _snapshotPtr;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetSnapshotJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetSnapshotJson()
{
try
{
string json = Runtime.Plugin?.Snapshot ?? "{\"online\":false,\"clients\":[]}";
IntPtr fresh = Marshal.StringToHGlobalAnsi(json);
IntPtr old = _snapshotPtr;
_snapshotPtr = fresh;
if (old != IntPtr.Zero) Marshal.FreeHGlobal(old);
return fresh;
}
catch
{
return IntPtr.Zero;
}
}
/// <summary>Frees this thread's snapshot buffer (Shutdown runs on the pump thread).</summary>
private static void ReleaseSnapshot()
{
IntPtr old = Interlocked.Exchange(ref _snapshotPtr, IntPtr.Zero);
if (old != IntPtr.Zero) Marshal.FreeHGlobal(old);
}
}

View file

@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<OutputType>Library</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<NativeLib>Shared</NativeLib>
<InvariantGlobalization>true</InvariantGlobalization>
<IlcOptimizationPreference>Size</IlcOptimizationPreference>
<StripSymbols>false</StripSymbols>
<RootNamespace>RynthCore.Plugin.RynthNet</RootNamespace>
<AssemblyName>RynthCore.Plugin.RynthNet</AssemblyName>
<Platforms>x86</Platforms>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
</ItemGroup>
<ItemGroup>
<!-- RynthNet's own interface (RynthNet.Net), and RynthAi's two it reads for the bot state. -->
<Compile Include="..\Shared\RynthNetApi.cs" Link="Shared\RynthNetApi.cs" />
<Compile Include="..\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
<Compile Include="..\Shared\RynthAiScriptApi.cs" Link="Shared\RynthAiScriptApi.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,391 @@
// ============================================================================
// RynthNet - RynthNetPlugin.Commands.cs
// /rn chat commands, and UtilityBelt's /ub bc, /ub bct, /ub netclients
// (forwarded by RynthAi's /ub layer, or typed when RynthAi isn't loaded).
// Pump thread only.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.Json;
using RynthCore.Plugin.RynthNet.Transport;
namespace RynthCore.Plugin.RynthNet;
public sealed partial class RynthNetPlugin
{
private void HandleLocal(NetNode node, string line)
{
string t = line.Trim();
if (t.StartsWith("/ub", StringComparison.OrdinalIgnoreCase))
{
HandleUb(node, t.Length > 3 ? t.Substring(3).Trim() : "");
return;
}
string rest = t.Length > 3 ? t.Substring(3).Trim() : "";
string verb = FirstWord(rest, out string args).ToLowerInvariant();
switch (verb)
{
case "":
case "help":
Help();
break;
case "bc": // every other client
case "bca": // every client, this one too
{
CommandParser.DelayAndCommand(args, out int delay, out string command);
Report(SendCommand(NetTarget.All, command, delay, includeSelf: verb == "bca"), command, "every client");
break;
}
case "bct": // clients with any of the tags (this one too when it has one)
{
if (!CommandParser.TagsAndRest(args, out List<string> tags, out string after))
{
ChatLine("usage: /rn bct <tag[,tag]> [delayMs] <command>");
break;
}
CommandParser.DelayAndCommand(after, out int delay, out string command);
var target = new NetTarget(TargetKind.Tags, string.Join(",", tags));
Report(SendCommand(target, command, delay, includeSelf: true), command, "tag " + string.Join(",", tags));
break;
}
case "tell": // one client, by character name
{
var known = node.GetPeers().Select(p => p.Identity.Character).Where(c => c.Length > 0);
if (!CommandParser.NameAndCommand(args, known, out string name, out string command))
{
ChatLine("usage: /rn tell <character>[,] <command>");
break;
}
if (!node.GetPeers().Any(p => string.Equals(p.Identity.Character, name, StringComparison.OrdinalIgnoreCase)))
{
ChatLine($"no client is playing {name} (/rn list).");
break;
}
Report(SendCommand(new NetTarget(TargetKind.Character, name), command, 0, includeSelf: false), command, name);
break;
}
case "list":
case "clients":
ListClients(node, args);
break;
case "tag":
case "tags":
TagCommand(args);
break;
case "status":
StatusCommand(node);
break;
case "remote":
RemoteCommand(args);
break;
case "allow":
ListSetting(p => p.Allow, "allow", args, "remote commands run only if they start with one of these (empty = all)");
break;
case "deny":
ListSetting(p => p.Deny, "deny", args, "remote commands starting with one of these never run");
break;
case "trust":
ListSetting(p => p.TrustedSenders, "trust", args, "only these characters' commands run here (empty = any of your clients)");
break;
case "followme":
{
if (!_loggedIn) { ChatLine("log in first."); break; }
NetTarget target = args.Length > 0 && CommandParser.TagsAndRest(args, out List<string> tags, out _)
? new NetTarget(TargetKind.Tags, string.Join(",", tags)) : NetTarget.All;
string command = "/ra follow " + _character;
Report(SendCommand(target, command, 0, includeSelf: false), command, target.Kind == TargetKind.All ? "every client" : "tag " + target.Value);
break;
}
case "usesel":
case "useselected":
{
uint sel = Host.GetSelectedItemId();
if (sel == 0) { ChatLine("select something first."); break; }
NetTarget target = args.Length > 0 && CommandParser.TagsAndRest(args, out List<string> tags, out _)
? new NetTarget(TargetKind.Tags, string.Join(",", tags)) : NetTarget.All;
// The same command UtilityBelt's network window sends (RynthAi's meta expressions run it).
string command = $"/ub mexec actiontryuseitem[wobjectfindbyid[{(int)sel}]]";
Report(SendCommand(target, command, 0, includeSelf: false), command, target.Kind == TargetKind.All ? "every client" : "tag " + target.Value);
break;
}
default:
ChatLine($"unknown command '{verb}'. /rn help lists them.");
break;
}
}
private void HandleUb(NetNode node, string rest)
{
string verb = FirstWord(rest, out string args).ToLowerInvariant();
switch (verb)
{
case "bc":
{
// UtilityBelt: runs on every client, this one included, the n-th remote after n x delay.
CommandParser.DelayAndCommand(args, out int delay, out string command);
Report(SendCommand(NetTarget.All, command, delay, includeSelf: true), command, "every client");
break;
}
case "bct":
{
if (!CommandParser.TagsAndRest(args, out List<string> tags, out string after))
{
ChatLine("usage: /ub bct <tag[,tag]> [millisecondDelay] <command>");
break;
}
CommandParser.DelayAndCommand(after, out int delay, out string command);
var target = new NetTarget(TargetKind.Tags, string.Join(",", tags));
Report(SendCommand(target, command, delay, includeSelf: true), command, "tag " + string.Join(",", tags));
break;
}
case "netclients":
ListClients(node, args);
break;
default:
ChatLine($"/ub {verb} isn't a network command.");
break;
}
}
private void Report(List<string>? names, string command, string to)
{
if (names == null) return;
if (names.Count == 0) { ChatLine($"nobody to send '{command}' to ({to}). /rn list shows the clients."); return; }
ChatLine($"'{command}' -> {string.Join(", ", names)}");
}
private static string FirstWord(string s, out string rest)
{
s = (s ?? "").Trim();
int sp = s.IndexOf(' ');
if (sp < 0) { rest = ""; return s; }
rest = s.Substring(sp + 1).Trim();
return s.Substring(0, sp);
}
private void Help()
{
ChatLine("=== RynthNet: your clients on this PC ===");
ChatLine("/rn bc [delayMs] <command> - run on every other client (delay staggers them)");
ChatLine("/rn bca [delayMs] <command> - run on every client, this one too");
ChatLine("/rn bct <tag[,tag]> [delayMs] <command> - run on clients with a tag (this one too if tagged)");
ChatLine("/rn tell <character>[,] <command> - run on one client");
ChatLine("/rn list [tag] - clients, tags, vitals, bot state");
ChatLine("/rn tag [list | add <tag> | remove <tag> | clear] - this character's tags");
ChatLine("/rn followme [tag] - the others /ra follow you; /rn usesel [tag] - they use your selection");
ChatLine("/rn status - this client; /rn remote on|off|default - run others' commands on this character");
ChatLine("/rn allow|deny|trust [list | add <x> | remove <x> | clear] - what may run here");
ChatLine("UtilityBelt's /ub bc, /ub bct and /ub netclients work too.");
}
// ── /rn list ────────────────────────────────────────────────────────────
private void ListClients(NetNode node, string args)
{
List<string> filter = new();
if (args.Length > 0) CommandParser.TagsAndRest(args, out filter, out _);
if (!node.IsRunning) { ChatLine("offline: " + (_offlineReason.Length > 0 ? _offlineReason : "stopped")); return; }
var peers = new List<PeerInfo>(node.GetPeers());
peers.Sort((a, b) => string.Compare(a.Identity.Character, b.Identity.Character, StringComparison.OrdinalIgnoreCase));
if (filter.Count > 0) peers.RemoveAll(p => !p.Identity.HasAnyTag(filter.ToArray()));
string mine = MyTags.Count > 0 ? " [" + string.Join(",", MyTags) + "]" : "";
ChatLine($"{peers.Count} other client(s){(filter.Count > 0 ? " tagged " + string.Join(",", filter) : "")}; you: {(_loggedIn ? _character : "not logged in")}{mine}");
long now = NetNode.NowMs;
foreach (PeerInfo p in peers)
ChatLine(" " + DescribePeer(p, now));
}
private static string DescribePeer(PeerInfo p, long now)
{
var sb = new StringBuilder();
NodeIdentity id = p.Identity;
sb.Append(id.Character.Length > 0 ? id.Character : "(not logged in)");
if (id.Tags.Length > 0) sb.Append(" [").Append(string.Join(",", id.Tags)).Append(']');
if (p.StatusJson.Length > 2 && now - p.StatusAtMs < 15_000)
{
try
{
using JsonDocument doc = JsonDocument.Parse(p.StatusJson);
JsonElement s = doc.RootElement;
if (Num(s, "hpMax") > 0)
sb.Append(CultureInfo.InvariantCulture, $" - H {Num(s, "hp"):0}/{Num(s, "hpMax"):0} S {Num(s, "st"):0}/{Num(s, "stMax"):0} M {Num(s, "mp"):0}/{Num(s, "mpMax"):0}");
if (s.TryGetProperty("ns", out JsonElement ns) && s.TryGetProperty("ew", out JsonElement ew)
&& ns.ValueKind == JsonValueKind.Number && ew.ValueKind == JsonValueKind.Number)
{
double n = ns.GetDouble(), e = ew.GetDouble();
sb.Append(CultureInfo.InvariantCulture, $" @ {Math.Abs(n):0.0}{(n >= 0 ? "N" : "S")} {Math.Abs(e):0.0}{(e >= 0 ? "E" : "W")}");
}
if (s.TryGetProperty("portal", out JsonElement portal) && portal.ValueKind == JsonValueKind.True) sb.Append(" (portal space)");
if (s.TryGetProperty("bot", out JsonElement bot) && bot.ValueKind == JsonValueKind.Object)
{
bool macro = bot.TryGetProperty("macro", out JsonElement m) && m.ValueKind == JsonValueKind.True;
string action = bot.TryGetProperty("action", out JsonElement a) && a.ValueKind == JsonValueKind.String ? a.GetString() ?? "" : "";
sb.Append(" - bot ").Append(macro ? "on" : "off");
if (macro && action.Length > 0 && action != "Default") sb.Append(": ").Append(action);
}
}
catch (JsonException) { }
}
else if (id.LoggedIn)
{
// Its pipe still answers (the transport has its own threads) but its game stopped
// ticking: a hung client shows here instead of vanishing.
sb.Append(p.StatusAtMs > 0
? string.Create(CultureInfo.InvariantCulture, $" - no status for {(now - p.StatusAtMs) / 1000} s")
: " - no status yet");
}
if (p.RttMs >= 0) sb.Append(CultureInfo.InvariantCulture, $" - {p.RttMs} ms");
return sb.ToString();
}
private static double Num(JsonElement e, string name)
=> e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number ? v.GetDouble() : 0;
// ── Tags and settings (per character, saved with merge: see RynthNetSettings) ──
private void TagCommand(string args)
{
string verb = FirstWord(args, out string value).ToLowerInvariant();
if (!_loggedIn) { ChatLine("log in first: tags belong to a character."); return; }
switch (verb)
{
case "":
case "list":
ChatLine(MyTags.Count > 0 ? $"{_character}'s tags: {string.Join(", ", MyTags)}" : $"{_character} has no tags. /rn tag add <tag>");
break;
case "add":
ChatLine(SetTag(value, on: true, out string whyAdd) ? $"tagged {_character}: {string.Join(", ", MyTags)}" : whyAdd);
break;
case "remove":
case "rm":
case "del":
if (!SetTag(value, on: false, out string whyRemove)) ChatLine(whyRemove);
else ChatLine(MyTags.Count > 0 ? $"{_character}'s tags: {string.Join(", ", MyTags)}" : $"{_character} has no tags now.");
break;
case "clear":
string key = CharacterKey;
if (UpdateSettings(s => s.Character(key).Tags.Clear())) ChatLine($"{_character} has no tags now.");
break;
default:
ChatLine("usage: /rn tag [list | add <tag> | remove <tag> | clear]");
break;
}
}
/// <summary>Adds or removes one of this character's tags, saves, tells the others.</summary>
internal bool SetTag(string tag, bool on, out string why)
{
why = "";
tag = (tag ?? "").Trim().Trim('"');
if (!_loggedIn) { why = "log in first: tags belong to a character."; return false; }
if (tag.Length == 0 || tag.Length > Wire.MaxTagLength || tag.Contains(',') || tag.Any(char.IsWhiteSpace))
{
why = $"a tag is 1-{Wire.MaxTagLength} characters, no spaces or commas.";
return false;
}
bool has = MyTags.Any(x => string.Equals(x, tag, StringComparison.OrdinalIgnoreCase));
if (on && has) { why = $"{_character} already has tag {tag}."; return false; }
if (on && MyTags.Count >= Wire.MaxTags) { why = $"at most {Wire.MaxTags} tags."; return false; }
if (!on && !has) { why = $"{_character} has no tag {tag}."; return false; }
string key = CharacterKey;
bool saved = UpdateSettings(s =>
{
List<string> tags = s.Character(key).Tags;
tags.RemoveAll(x => string.Equals(x, tag, StringComparison.OrdinalIgnoreCase));
if (on) tags.Add(tag);
});
if (!saved) why = "couldn't save the tag.";
return saved;
}
private void StatusCommand(NetNode node)
{
if (!node.IsRunning)
{
ChatLine("offline: " + (_offlineReason.Length > 0 ? _offlineReason : "stopped"));
return;
}
RynthNetPolicy p = MyPolicy;
bool own = _loggedIn && _settings.Characters.TryGetValue(CharacterKey, out RynthNetCharacter? c) && c.Policy != null;
ChatLine($"online as {node.NodeId} ({node.GetPeers().Length} other client(s)); pipe {node.PipeName}");
ChatLine($"remote commands: {(p.AcceptRemoteCommands ? "on" : "off")} ({(own ? "this character's own policy" : "defaults")}), " +
$"allow {p.Allow.Count}, deny {p.Deny.Count}, trusted {(p.TrustedSenders.Count == 0 ? "any" : p.TrustedSenders.Count.ToString(CultureInfo.InvariantCulture))}; " +
$"logged to chat: {(_settings.LogRemoteCommands ? "yes" : "no")}; status every {_settings.StatusIntervalMs} ms; RynthAi {(_rynthAiPresent ? "found" : "not loaded")}");
ChatLine("settings: " + RynthNetSettings.FilePath);
if (node.DroppedEvents > 0) ChatLine($"{node.DroppedEvents} network event(s) dropped (queue full).");
}
private void RemoteCommand(string args)
{
string a = string.Join(" ", args.Split(' ', StringSplitOptions.RemoveEmptyEntries)).ToLowerInvariant();
string key = CharacterKey;
if (a is "log on" or "log off")
{
bool log = a == "log on";
UpdateSettings(s => s.LogRemoteCommands = log);
}
else if (a is "on" or "off" or "default")
{
if (!_loggedIn) { ChatLine("log in first: the policy belongs to a character (the file's \"defaults\" cover the rest)."); return; }
if (a == "default")
UpdateSettings(s => { if (s.Characters.TryGetValue(key, out RynthNetCharacter? c)) c.Policy = null; });
else
{
bool on = a == "on";
UpdateSettings(s =>
{
RynthNetCharacter c = s.Character(key);
c.Policy ??= s.Defaults.Clone();
c.Policy.AcceptRemoteCommands = on;
});
}
}
else if (a.Length > 0)
{
ChatLine("usage: /rn remote on|off|default /rn remote log on|off");
return;
}
ChatLine($"commands from your other clients {(MyPolicy.AcceptRemoteCommands ? "run here" : "are refused here")}" +
$"{(_settings.LogRemoteCommands ? ", each one written to chat" : "")}.");
}
/// <summary>/rn allow|deny|trust: one of this character's policy lists (a copy of the defaults until changed).</summary>
private void ListSetting(Func<RynthNetPolicy, List<string>> select, string name, string args, string meaning)
{
string verb = FirstWord(args, out string value).ToLowerInvariant();
value = value.Trim();
if (verb is "" or "list")
{
List<string> list = select(MyPolicy);
ChatLine(list.Count == 0 ? $"{name}: empty ({meaning})." : $"{name}: {string.Join(" | ", list)}");
return;
}
if (verb is not ("add" or "remove" or "rm" or "clear") || (verb != "clear" && value.Length == 0))
{
ChatLine($"usage: /rn {name} [list | add <x> | remove <x> | clear] - {meaning}");
return;
}
if (!_loggedIn) { ChatLine("log in first: the policy belongs to a character (the file's \"defaults\" cover the rest)."); return; }
bool had = select(MyPolicy).Exists(x => string.Equals(x, value, StringComparison.OrdinalIgnoreCase));
string key = CharacterKey;
bool saved = UpdateSettings(s =>
{
RynthNetCharacter c = s.Character(key);
c.Policy ??= s.Defaults.Clone();
List<string> list = select(c.Policy);
if (verb == "clear") list.Clear();
else list.RemoveAll(x => string.Equals(x, value, StringComparison.OrdinalIgnoreCase));
if (verb == "add") list.Add(value);
});
if (!saved) return;
List<string> now = select(MyPolicy);
if (verb is "remove" or "rm" && !had) ChatLine($"{name} has no '{value}'.");
else ChatLine(now.Count == 0 ? $"{name}: empty." : $"{name}: {string.Join(" | ", now)}");
}
}

View file

@ -0,0 +1,246 @@
// ============================================================================
// RynthNet - RynthNetPlugin.Status.cs
// What this client shares (vitals, position, bot state; every
// StatusIntervalMs), the JSON views of the network (snapshot export, the
// RynthNet.Net interface) and channel subscriptions. Pump thread only.
// ============================================================================
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using RynthCore.Plugin.RynthNet.Transport;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthNet;
public sealed unsafe partial class RynthNetPlugin
{
private const int MaxChannelMessages = 256;
private const int MaxChannels = 32;
private readonly Dictionary<string, Queue<(string From, string Node, string Msg, long At)>> _channels =
new(StringComparer.OrdinalIgnoreCase);
private static string Json(Action<Utf8JsonWriter> body)
{
var buffer = new ArrayBufferWriter<byte>(512);
using (var w = new Utf8JsonWriter(buffer))
body(w);
return Encoding.UTF8.GetString(buffer.WrittenSpan);
}
// ── This client's status ────────────────────────────────────────────────
private void SendStatus(NetNode node)
{
string? bot = BotStatusJson();
string status = Json(w =>
{
w.WriteStartObject();
if (Host.TryGetPlayerVitals(out uint hp, out uint hpMax, out uint st, out uint stMax, out uint mp, out uint mpMax))
{
w.WriteNumber("hp", hp); w.WriteNumber("hpMax", hpMax);
w.WriteNumber("st", st); w.WriteNumber("stMax", stMax);
w.WriteNumber("mp", mp); w.WriteNumber("mpMax", mpMax);
}
if (Host.TryGetPlayerPose(out uint cell, out float x, out float y, out float z, out _, out _, out _, out _))
{
w.WriteNumber("cell", cell);
w.WriteNumber("x", Math.Round(x, 2)); w.WriteNumber("y", Math.Round(y, 2)); w.WriteNumber("z", Math.Round(z, 2));
}
if (Host.TryGetCurCoords(out double ns, out double ew))
{
w.WriteNumber("ns", Math.Round(ns, 3)); w.WriteNumber("ew", Math.Round(ew, 3));
}
if (Host.HasGetPlayerHeading && Host.TryGetPlayerHeading(out float heading))
w.WriteNumber("heading", Math.Round(heading, 1));
if (Host.HasIsPortaling) w.WriteBoolean("portal", Host.IsPortaling());
if (Host.HasGetBusyState) w.WriteNumber("busy", Host.GetBusyState());
if (Host.HasGetVitae && _playerId != 0) w.WriteNumber("vitae", Math.Round(Host.GetVitae(_playerId), 3));
if (bot != null)
{
try
{
w.WritePropertyName("bot");
w.WriteRawValue(bot); // validated: a bad string throws here, not in the peers
}
catch (Exception)
{
w.WriteNullValue();
}
}
w.WriteEndObject();
});
try { node.SetStatus(status); }
catch (Exception ex) { Host.Log("[RynthNet] status not sent: " + ex.Message); }
}
/// <summary>
/// RynthAi's state: its "RynthAi.Status" interface, else just the macro flag from
/// "RynthAi.Script" (an older RynthAi), else null. Resolved again every call: never cached.
/// </summary>
private string? BotStatusJson()
{
if (!Host.HasGetPluginInterface) return null;
try
{
var status = (RynthAiStatusApiV1*)Host.GetPluginInterface("RynthAi", RynthAiStatusApiV1.InterfaceName, RynthAiStatusApiV1.InterfaceVersion);
if (status != null && status->Version >= 1 && status->StructSize >= (uint)sizeof(RynthAiStatusApiV1) && status->GetStatusJson != null)
{
byte* r = null;
if (status->GetStatusJson(&r) != 0 && r != null)
{
string json = Marshal.PtrToStringUTF8((IntPtr)r) ?? "";
if (json.StartsWith('{')) return json;
}
return null;
}
var script = (RynthAiScriptApiV1*)Host.GetPluginInterface("RynthAi", RynthAiScriptApiV1.InterfaceName, RynthAiScriptApiV1.InterfaceVersion);
if (script != null && script->Version >= 1 && script->StructSize >= (uint)sizeof(RynthAiScriptApiV1) && script->IsMacroRunning != null)
return script->IsMacroRunning() != 0 ? "{\"macro\":true}" : "{\"macro\":false}";
}
catch (Exception ex)
{
Host.Log("[RynthNet] RynthAi status failed: " + ex.Message);
}
return null;
}
// ── JSON views ──────────────────────────────────────────────────────────
private static void WriteTags(Utf8JsonWriter w, string[] tags)
{
w.WriteStartArray("tags");
foreach (string t in tags) w.WriteStringValue(t);
w.WriteEndArray();
}
private static void WriteClients(Utf8JsonWriter w, NetNode node, long now)
{
var peers = new List<PeerInfo>(node.GetPeers());
peers.Sort((a, b) => string.Compare(a.Identity.Character, b.Identity.Character, StringComparison.OrdinalIgnoreCase));
w.WriteStartArray();
foreach (PeerInfo p in peers)
{
w.WriteStartObject();
w.WriteString("node", p.NodeId);
w.WriteNumber("pid", p.Pid);
w.WriteString("char", p.Identity.Character);
w.WriteString("world", p.Identity.World);
w.WriteBoolean("login", p.Identity.LoggedIn);
WriteTags(w, p.Identity.Tags);
w.WriteNumber("rtt", p.RttMs);
w.WritePropertyName("status");
if (p.StatusJson.Length > 2)
{
w.WriteRawValue(p.StatusJson);
w.WriteNumber("age", now - p.StatusAtMs);
}
else
{
w.WriteNullValue();
}
w.WriteEndObject();
}
w.WriteEndArray();
}
/// <summary>The other clients (RynthNet.Net GetClientsJson).</summary>
internal string ClientsJson()
{
NetNode? node = _node;
if (node == null) return "[]";
long now = NetNode.NowMs;
return Json(w => WriteClients(w, node, now));
}
/// <summary>This client (RynthNet.Net GetSelfJson).</summary>
internal string SelfJson()
{
NetNode? node = _node;
return Json(w =>
{
w.WriteStartObject();
w.WriteString("node", node?.NodeId ?? "");
w.WriteString("pipe", node?.PipeName ?? "");
w.WriteString("char", _loggedIn ? _character : "");
w.WriteString("world", _world);
w.WriteBoolean("login", _loggedIn);
WriteTags(w, new List<string>(MyTags).ToArray());
w.WriteBoolean("online", node?.IsRunning == true);
w.WriteEndObject();
});
}
/// <summary>What RynthPluginGetSnapshotJson serves (rebuilt twice a second for panels).</summary>
private string BuildSnapshotJson(NetNode node, long now) => Json(w =>
{
w.WriteStartObject();
w.WriteString("version", PluginVersion);
w.WriteBoolean("online", node.IsRunning);
if (!node.IsRunning) w.WriteString("offline", _offlineReason);
w.WriteString("node", node.NodeId);
w.WriteString("char", _loggedIn ? _character : "");
w.WriteString("world", _world);
w.WriteBoolean("login", _loggedIn);
WriteTags(w, new List<string>(MyTags).ToArray());
w.WriteBoolean("acceptRemote", MyPolicy.AcceptRemoteCommands);
w.WritePropertyName("clients");
WriteClients(w, node, now);
w.WriteEndObject();
});
// ── Channels (RynthNet.Net Publish / Subscribe / PollChannel) ───────────
internal bool Subscribe(string channel, bool on)
{
channel = (channel ?? "").Trim();
if (channel.Length == 0 || channel.Length > Wire.MaxName) return false;
if (!on)
{
_channels.Remove(channel);
return true;
}
if (_channels.ContainsKey(channel)) return true;
if (_channels.Count >= MaxChannels) return false;
_channels[channel] = new Queue<(string, string, string, long)>();
return true;
}
private void OnChannelMessage(NetEvent e)
{
NetNode? node = _node;
if (node == null || !_channels.TryGetValue(e.Channel, out var queue)) return;
if (!e.Target.Matches(node.Identity)) return;
if (queue.Count >= MaxChannelMessages) queue.Dequeue();
queue.Enqueue((e.From, e.NodeId, e.Text, e.AtMs));
}
internal string? PollChannel(string channel)
{
if (!_channels.TryGetValue((channel ?? "").Trim(), out var queue)) return null;
string json = Json(w =>
{
w.WriteStartArray();
foreach (var m in queue)
{
w.WriteStartObject();
w.WriteString("from", m.From);
w.WriteString("node", m.Node);
w.WriteString("msg", m.Msg);
w.WriteNumber("at", m.At);
w.WriteEndObject();
}
w.WriteEndArray();
});
queue.Clear();
return json;
}
internal string TagsText => string.Join("\n", MyTags);
internal bool IsOnline => _node?.IsRunning == true;
}

View file

@ -0,0 +1,440 @@
// ============================================================================
// RynthNet - RynthNetPlugin.cs
// UtilityBelt-style networking between the RynthCore clients on this PC:
// broadcast / tagged / targeted chat commands, a client list with tags, and
// shared vitals, position and bot state. Local only (same Windows user, named
// pipes, no TCP, no server process): see Transport/.
//
// Threads: the transport runs on its own threads and only queues. Everything
// here (host calls, running commands, chat) happens on the plugin pump thread
// in OnTick. OnChatBarEnter (AC's thread) and RynthPluginApplyRemoteCommand
// (the caller's thread) only queue. Shutdown stops and joins the transport.
// ============================================================================
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using RynthCore.Plugin.RynthNet.Transport;
using RynthCore.PluginCore;
namespace RynthCore.Plugin.RynthNet;
public sealed partial class RynthNetPlugin : RynthPluginBase
{
public const string PluginVersion = "0.1.0";
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthNet");
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi(PluginVersion);
private const int MaxScheduled = 256;
private const int RateWindowMs = 5000;
private const int RateMaxPerWindow = 20;
private NetNode? _node;
private string _offlineReason = "";
private RynthNetSettings _settings = new();
// Queued from other threads, drained in OnTick.
// TypedUb: a /ub network command typed in chat, which RynthAi (when loaded) also sees and forwards.
private readonly ConcurrentQueue<(string Line, bool TypedUb)> _localCommands = new();
private sealed record Scheduled(long DueMs, string Text, string From, bool Remote);
private readonly List<Scheduled> _scheduled = new();
private readonly Dictionary<string, (long Start, int Count)> _rate = new();
private readonly Dictionary<string, string> _peerNames = new(); // node id -> character last announced
private readonly Dictionary<string, string> _sent = new(); // command id -> text, for refusal messages
private readonly Queue<string> _sentOrder = new();
private int _commandSeq;
private uint _playerId;
private bool _loggedIn;
private string _character = "", _world = "", _account = "";
private long _nextStatusMs, _nextSnapshotMs, _nextAiCheckMs, _nextLoginProbeMs, _nextSettingsCheckMs;
private long _settingsStamp;
private volatile bool _rynthAiPresent;
private volatile string _snapshot = "{\"online\":false,\"clients\":[]}";
public override int Initialize()
{
_settings = RynthNetSettings.Load(out string? settingsError);
_settingsStamp = RynthNetSettings.FileStamp();
if (settingsError != null) Host.Log("[RynthNet] " + settingsError);
_node = new NetNode(new NetNodeOptions { App = "RynthNet/" + PluginVersion });
if (!_node.Start(out string error))
{
_offlineReason = error;
Host.Log("[RynthNet] offline: " + error);
}
PushIdentity();
DrainLogs();
Host.Log($"[RynthNet] {PluginVersion} initialized ({(_node.IsRunning ? "online" : "offline")}).");
return 0;
}
public override void Shutdown()
{
NetNode? node = _node;
_node = null;
if (node != null)
{
bool clean = node.Stop(2000);
while (node.TryDequeueLog(out string line)) Host.Log(line);
Host.Log(clean
? "[RynthNet] stopped: every pipe closed, every thread and task ended."
: $"[RynthNet] stop timed out: {node.RunningWorkers} worker(s) still running.");
}
_scheduled.Clear();
_channels.Clear();
_peerNames.Clear();
_rate.Clear();
while (_localCommands.TryDequeue(out _)) { }
}
// ── Game events ─────────────────────────────────────────────────────────
public override void OnLoginComplete()
{
ResolveCharacter();
}
public override void OnLogout()
{
_loggedIn = false;
_playerId = 0;
_scheduled.RemoveAll(s => s.Remote);
PushIdentity();
try { _node?.SetStatus("{}"); } catch { }
}
/// <summary>AC's thread: only queue.</summary>
public override void OnChatBarEnter(string? text, ref int eat)
{
string t = (text ?? "").Trim();
if (t.Equals("/rn", StringComparison.OrdinalIgnoreCase) || t.StartsWith("/rn ", StringComparison.OrdinalIgnoreCase))
{
_localCommands.Enqueue((t, false));
eat = 1;
return;
}
// UtilityBelt's network commands. Every plugin sees every line (eating doesn't stop the
// others), so with RynthAi loaded it handles /ub and forwards these here itself. Whether
// it is loaded is decided on the next tick, when the line is taken off the queue.
if (IsUbNetCommand(t))
{
_localCommands.Enqueue((t, true));
eat = 1;
}
}
private static bool IsUbNetCommand(string t)
=> t.StartsWith("/ub bc ", StringComparison.OrdinalIgnoreCase)
|| t.StartsWith("/ub bct ", StringComparison.OrdinalIgnoreCase)
|| t.Equals("/ub netclients", StringComparison.OrdinalIgnoreCase)
|| t.StartsWith("/ub netclients ", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Another plugin's command (host SendPluginCommand; any thread): ("ub", "bc ...") from
/// RynthAi's /ub layer, ("rn", "list") for /rn. Only queued.
/// </summary>
internal void EnqueueForwarded(string action, string value)
{
string a = (action ?? "").Trim().ToLowerInvariant();
string v = (value ?? "").Trim();
if (a is "ub" or "rn") _localCommands.Enqueue(("/" + a + (v.Length > 0 ? " " + v : ""), false));
}
// ── Tick ────────────────────────────────────────────────────────────────
public override void OnTick()
{
NetNode? node = _node;
if (node == null) return;
long now = NetNode.NowMs;
DrainLogs();
if (now >= _nextSettingsCheckMs)
{
_nextSettingsCheckMs = now + 5000;
ReloadSettingsIfChanged();
}
if (now >= _nextAiCheckMs)
{
_nextAiCheckMs = now + 3000;
_rynthAiPresent = RynthAiLoaded();
}
if (!_loggedIn && now >= _nextLoginProbeMs)
{
_nextLoginProbeMs = now + 2000;
if (Host.GetPlayerId() != 0 && (!Host.HasIsPlayerReady || Host.IsPlayerReady()))
ResolveCharacter(); // loaded (or reloaded) while already in the world
}
for (int i = 0; i < 64 && node.TryDequeueEvent(out NetEvent e); i++)
HandleEvent(node, e, now);
for (int i = 0; i < 16 && _localCommands.TryDequeue(out var queued); i++)
{
// A typed /ub bc: RynthAi, when loaded, saw the same line and forwards its own copy.
if (queued.TypedUb && RynthAiLoaded()) continue;
try { HandleLocal(node, queued.Line); }
catch (Exception ex) { ChatLine($"'{queued.Line}' failed: {ex.Message}"); }
}
RunScheduled(now);
if (now >= _nextStatusMs)
{
_nextStatusMs = now + _settings.StatusIntervalMs;
if (_loggedIn && node.IsRunning) SendStatus(node);
}
if (now >= _nextSnapshotMs)
{
_nextSnapshotMs = now + 500;
_snapshot = BuildSnapshotJson(node, now);
}
}
internal string Snapshot => _snapshot;
/// <summary>RynthAi is loaded and initialised right now (pump thread).</summary>
private bool RynthAiLoaded()
=> Host.HasGetPluginInterface && Host.GetPluginInterface("RynthAi", "RynthAi.Script", 1) != IntPtr.Zero;
private void DrainLogs()
{
NetNode? node = _node;
if (node == null) return;
for (int i = 0; i < 32 && node.TryDequeueLog(out string line); i++) Host.Log(line);
}
private void ResolveCharacter()
{
uint id = Host.GetPlayerId();
if (id == 0) return;
if (!Host.TryGetObjectName(id, out string name) || string.IsNullOrWhiteSpace(name)) return;
_playerId = id;
_character = name.Trim();
_world = Host.TryGetWorldName(out string world) ? world : "";
_account = Host.TryGetAccountName(out string account) ? account : "";
bool wasLoggedIn = _loggedIn;
_loggedIn = true;
PushIdentity();
if (!wasLoggedIn) _nextStatusMs = 0;
}
private string CharacterKey => RynthNetSettings.CharacterKey(_world, _character);
private IReadOnlyList<string> MyTags => _loggedIn ? _settings.TagsFor(CharacterKey) : Array.Empty<string>();
/// <summary>The command policy of the character logged in here (the defaults before login).</summary>
private RynthNetPolicy MyPolicy => _loggedIn ? _settings.PolicyFor(CharacterKey) : _settings.Defaults;
private void PushIdentity()
{
_node?.SetIdentity(new NodeIdentity
{
Character = _loggedIn ? _character : "",
World = _world,
Account = _account,
LoggedIn = _loggedIn,
Tags = MyTags.ToArray(),
App = "RynthNet/" + PluginVersion,
});
}
private void ChatLine(string text)
{
if (Host.HasWriteToChat) Host.WriteToChat("[RynthNet] " + text, 1);
else Host.Log("[RynthNet] " + text);
}
/// <summary>Applies one change to the shared settings file (merged with the other clients'), then pushes tags.</summary>
private bool UpdateSettings(Action<RynthNetSettings> change)
{
if (!RynthNetSettings.Update(change, out RynthNetSettings current, out string? error))
{
ChatLine("couldn't save settings: " + error);
return false;
}
_settings = current;
_settingsStamp = RynthNetSettings.FileStamp();
PushIdentity();
return true;
}
/// <summary>Picks up the file when it changed (edited by hand, or another client saved).</summary>
private void ReloadSettingsIfChanged()
{
long stamp = RynthNetSettings.FileStamp();
if (stamp == _settingsStamp) return;
_settingsStamp = stamp;
_settings = RynthNetSettings.Load(out string? error);
if (error != null) Host.Log("[RynthNet] " + error);
PushIdentity();
}
// ── Network events ──────────────────────────────────────────────────────
private void HandleEvent(NetNode node, NetEvent e, long now)
{
switch (e.Kind)
{
case NetEventKind.PeerJoined:
_peerNames[e.NodeId] = e.From;
if (_loggedIn && e.From.Length > 0) ChatLine($"{e.From} connected.");
break;
case NetEventKind.PeerUpdated:
{
// Clients connect at startup, before anyone is logged in: announce the character
// when it appears (or changes, or logs out).
string before = _peerNames.TryGetValue(e.NodeId, out string? b) ? b : "";
if (before == e.From) break;
_peerNames[e.NodeId] = e.From;
if (!_loggedIn) break;
if (before.Length == 0) ChatLine($"{e.From} connected.");
else if (e.From.Length == 0) ChatLine($"{before} logged out.");
else ChatLine($"{before} is now {e.From}.");
break;
}
case NetEventKind.PeerLeft:
if (_loggedIn && e.From.Length > 0) ChatLine($"{e.From} disconnected ({e.Text}).");
_peerNames.Remove(e.NodeId);
_rate.Remove(e.NodeId);
break;
case NetEventKind.Command:
OnRemoteCommand(node, e, now);
break;
case NetEventKind.Ack:
if (!e.Ok)
{
string what = _sent.TryGetValue(e.Id, out string? t) ? $"'{t}'" : "the command";
ChatLine($"{e.From} didn't run {what}: {e.Text}");
}
break;
case NetEventKind.Data:
OnChannelMessage(e);
break;
}
}
private void OnRemoteCommand(NetNode node, NetEvent e, long now)
{
if (!e.Target.Matches(node.Identity)) { Ack(node, e, false, "not addressed to this client"); return; }
if (!_loggedIn) { Ack(node, e, false, "not logged in"); return; }
if (!CommandPolicy.Check(e.Text, e.From, MyPolicy, out string why))
{
Host.Log($"[RynthNet] refused {e.From}: '{e.Text}': {why}");
Ack(node, e, false, why);
return;
}
if (!_rate.TryGetValue(e.NodeId, out var window) || now - window.Start > RateWindowMs) window = (now, 0);
if (window.Count >= RateMaxPerWindow)
{
Ack(node, e, false, $"too many commands (over {RateMaxPerWindow} in {RateWindowMs / 1000} s)");
return;
}
_rate[e.NodeId] = (window.Start, window.Count + 1);
if (_scheduled.Count >= MaxScheduled) { Ack(node, e, false, "command queue full"); return; }
_scheduled.Add(new Scheduled(now + e.DelayMs, e.Text, e.From, Remote: true));
Ack(node, e, true, "");
}
private static void Ack(NetNode node, NetEvent e, bool ok, string why) => node.SendTo(e.NodeId, Wire.Ack(e.Id, ok, why));
private void RunScheduled(long now)
{
if (_scheduled.Count == 0) return;
int ran = 0;
for (int i = 0; i < _scheduled.Count && ran < 4; i++)
{
Scheduled s = _scheduled[i];
if (s.DueMs > now) continue;
_scheduled.RemoveAt(i--);
ran++;
Execute(s);
}
}
private void Execute(Scheduled s)
{
if (s.Remote)
{
if (!_loggedIn) return;
if (_settings.LogRemoteCommands) ChatLine($"{s.From}: {s.Text}");
Host.Log($"[RynthNet] running for {s.From}: {s.Text}");
}
if (!Host.HasInvokeChatParser)
{
ChatLine("this engine can't run chat commands for plugins (no InvokeChatParser).");
return;
}
// Same as typing it: plugins (/ra, /ub, /lua...) get it first, then AC.
Host.InvokeChatParser(s.Text);
}
// ── Sending ─────────────────────────────────────────────────────────────
/// <summary>
/// Sends a command to the matching clients (sorted by name; the n-th gets n x delayMs) and,
/// with <paramref name="includeSelf"/>, runs it here first when this client matches.
/// Returns the names it went to ("you" for this client), or null with an error in chat.
/// </summary>
internal List<string>? SendCommand(NetTarget target, string command, int delayMs, bool includeSelf, bool quiet = false)
{
NetNode? node = _node;
command = (command ?? "").Trim();
if (command.Length == 0) { if (!quiet) ChatLine("no command given."); return null; }
if (command.Length > Wire.MaxText) { if (!quiet) ChatLine($"command too long (max {Wire.MaxText})."); return null; }
if (CommandPolicy.Rebroadcasts(command))
{
if (!quiet) ChatLine("a broadcast can't contain another broadcast (/rn, /ub bc, /ub bct).");
return null;
}
delayMs = Math.Clamp(delayMs, 0, 600_000);
var names = new List<string>();
long now = NetNode.NowMs;
if (includeSelf && node != null && target.Matches(node.Identity))
{
_scheduled.Add(new Scheduled(now, command, "you", Remote: false));
names.Add("you");
}
if (node == null || !node.IsRunning) return names;
var peers = new List<PeerInfo>(node.GetPeers());
peers.Sort((a, b) => string.Compare(a.Identity.Character, b.Identity.Character, StringComparison.OrdinalIgnoreCase));
int n = 0;
foreach (PeerInfo p in peers)
{
if (!target.Matches(p.Identity)) continue;
n++;
string id = NewCommandId(node, command);
if (node.SendTo(p.NodeId, Wire.Command(id, target, command, delayMs * n)))
names.Add(p.Identity.Character.Length > 0 ? p.Identity.Character : "pid " + p.Pid);
}
return names;
}
private string NewCommandId(NetNode node, string command)
{
string id = node.NodeId + ":" + (++_commandSeq);
_sent[id] = command;
_sentOrder.Enqueue(id);
while (_sentOrder.Count > 128) _sent.Remove(_sentOrder.Dequeue());
return id;
}
/// <summary>Publishes a channel message to the matching clients. Returns how many, -1 when offline.</summary>
internal int Publish(string channel, string message, NetTarget target)
{
NetNode? node = _node;
if (node == null || !node.IsRunning) return -1;
channel = (channel ?? "").Trim();
if (channel.Length == 0 || channel.Length > Wire.MaxName) return -1;
if ((message ?? "").Length > Wire.MaxMessage) return -1;
return node.Broadcast(Wire.Data(channel, message ?? "", target), p => target.Matches(p.Identity));
}
}

View file

@ -0,0 +1,259 @@
// ============================================================================
// RynthNet - RynthNetSettings.cs
// C:\Games\RynthSuite\RynthNet\settings.json (RYNTHNET_DIR overrides the
// folder), read and written by hand with JsonDocument / Utf8JsonWriter (no
// reflection serializer: NativeAOT, and a collectible plugin must not leave
// its types in a process-wide cache).
//
// Every client on the PC shares the file, so a save never writes a stale copy:
// Update() takes a lock file (released by the OS if the process dies), reads
// the file again, applies one change and writes it back. Tags and the command
// policy are per character; "defaults" is the policy of characters that have
// none of their own.
//
// {
// "logRemoteCommands": true,
// "statusIntervalMs": 1000,
// "defaults": { "acceptRemoteCommands": true, "allow": [], "deny": [], "trustedSenders": [] },
// "characters": { "World|Name": { "tags": ["healer"], "policy": { ...same as defaults... } } }
// }
// ============================================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Threading;
namespace RynthCore.Plugin.RynthNet;
/// <summary>What another client's command must pass here (see CommandPolicy).</summary>
internal sealed class RynthNetPolicy
{
/// <summary>Master switch: run commands other clients send.</summary>
public bool AcceptRemoteCommands = true;
/// <summary>When not empty, a remote command runs only if it starts with one of these.</summary>
public List<string> Allow = new();
/// <summary>A remote command starting with one of these never runs.</summary>
public List<string> Deny = new();
/// <summary>When not empty, only these characters' commands run.</summary>
public List<string> TrustedSenders = new();
public RynthNetPolicy Clone() => new()
{
AcceptRemoteCommands = AcceptRemoteCommands,
Allow = new List<string>(Allow),
Deny = new List<string>(Deny),
TrustedSenders = new List<string>(TrustedSenders),
};
}
internal sealed class RynthNetCharacter
{
public List<string> Tags = new();
/// <summary>This character's own policy; null = the defaults.</summary>
public RynthNetPolicy? Policy;
}
internal sealed class RynthNetSettings
{
public const string DefaultFolder = @"C:\Games\RynthSuite\RynthNet";
/// <summary>The settings folder; RYNTHNET_DIR overrides it (tests, portable setups).</summary>
public static string Folder => Environment.GetEnvironmentVariable("RYNTHNET_DIR") is { Length: > 0 } dir ? dir : DefaultFolder;
public static string FilePath => Path.Combine(Folder, "settings.json");
private static string LockPath => Path.Combine(Folder, "settings.lock");
/// <summary>Write every command run for another client to chat, with who sent it.</summary>
public bool LogRemoteCommands = true;
/// <summary>How often this client's vitals, position and bot state go to the others (250..10000 ms).</summary>
public int StatusIntervalMs = 1000;
public RynthNetPolicy Defaults = new();
/// <summary>"world|character" -> tags and policy.</summary>
public Dictionary<string, RynthNetCharacter> Characters = new(StringComparer.OrdinalIgnoreCase);
public static string CharacterKey(string world, string character) => (world ?? "") + "|" + (character ?? "");
public RynthNetPolicy PolicyFor(string key)
=> Characters.TryGetValue(key, out RynthNetCharacter? c) && c.Policy != null ? c.Policy : Defaults;
public IReadOnlyList<string> TagsFor(string key)
=> Characters.TryGetValue(key, out RynthNetCharacter? c) ? c.Tags : Array.Empty<string>();
/// <summary>The character's entry, created when missing.</summary>
public RynthNetCharacter Character(string key)
{
if (!Characters.TryGetValue(key, out RynthNetCharacter? c))
{
c = new RynthNetCharacter();
Characters[key] = c;
}
return c;
}
/// <summary>The file's last write time (UTC ticks), 0 when there is none.</summary>
public static long FileStamp()
{
try { return File.Exists(FilePath) ? File.GetLastWriteTimeUtc(FilePath).Ticks : 0; }
catch { return 0; }
}
// ── Load / update ───────────────────────────────────────────────────────
public static RynthNetSettings Load(out string? error)
{
error = null;
try
{
return File.Exists(FilePath) ? Parse(File.ReadAllBytes(FilePath)) : new RynthNetSettings();
}
catch (Exception ex)
{
error = $"{FilePath}: {ex.Message} (using defaults)";
return new RynthNetSettings();
}
}
/// <summary>
/// Re-reads the file under the lock, applies <paramref name="change"/>, writes it back, and
/// returns what is now on disk (other clients' changes included). False with an error when
/// the file couldn't be read or written; nothing is written then.
/// </summary>
public static bool Update(Action<RynthNetSettings> change, out RynthNetSettings current, out string? error)
{
error = null;
current = new RynthNetSettings();
try
{
Directory.CreateDirectory(Folder);
using FileStream? gate = TakeLock();
RynthNetSettings s = File.Exists(FilePath) ? Parse(File.ReadAllBytes(FilePath)) : new RynthNetSettings();
change(s);
string tmp = FilePath + "." + Environment.ProcessId + ".tmp";
File.WriteAllBytes(tmp, s.Serialize());
File.Move(tmp, FilePath, overwrite: true);
current = s;
return true;
}
catch (Exception ex)
{
error = ex.Message;
return false;
}
}
/// <summary>An exclusive lock file (gone when closed or when the process dies). Null after ~1 s of trying.</summary>
private static FileStream? TakeLock()
{
for (int i = 0; i < 50; i++)
{
try
{
return new FileStream(LockPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, 1, FileOptions.DeleteOnClose);
}
catch (IOException)
{
Thread.Sleep(20);
}
catch (UnauthorizedAccessException)
{
Thread.Sleep(20); // a lock file being deleted by its previous holder
}
}
return null; // someone holds it far too long: go ahead rather than lose the change
}
// ── JSON ────────────────────────────────────────────────────────────────
private static RynthNetSettings Parse(byte[] bytes)
{
var s = new RynthNetSettings();
using JsonDocument doc = JsonDocument.Parse(bytes,
new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip, MaxDepth = 16 });
JsonElement r = doc.RootElement;
if (r.ValueKind != JsonValueKind.Object) return s;
s.LogRemoteCommands = Bool(r, "logRemoteCommands", s.LogRemoteCommands);
if (r.TryGetProperty("statusIntervalMs", out JsonElement si) && si.ValueKind == JsonValueKind.Number && si.TryGetInt32(out int ms))
s.StatusIntervalMs = Math.Clamp(ms, 250, 10_000);
if (r.TryGetProperty("defaults", out JsonElement d) && d.ValueKind == JsonValueKind.Object)
s.Defaults = ParsePolicy(d);
if (r.TryGetProperty("characters", out JsonElement chars) && chars.ValueKind == JsonValueKind.Object)
{
foreach (JsonProperty p in chars.EnumerateObject())
{
if (p.Value.ValueKind != JsonValueKind.Object) continue;
var c = new RynthNetCharacter { Tags = Strings(p.Value, "tags") };
if (p.Value.TryGetProperty("policy", out JsonElement pol) && pol.ValueKind == JsonValueKind.Object)
c.Policy = ParsePolicy(pol);
s.Characters[p.Name] = c;
}
}
return s;
}
private static RynthNetPolicy ParsePolicy(JsonElement e) => new()
{
AcceptRemoteCommands = Bool(e, "acceptRemoteCommands", true),
Allow = Strings(e, "allow"),
Deny = Strings(e, "deny"),
TrustedSenders = Strings(e, "trustedSenders"),
};
private byte[] Serialize()
{
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
{
w.WriteStartObject();
w.WriteBoolean("logRemoteCommands", LogRemoteCommands);
w.WriteNumber("statusIntervalMs", StatusIntervalMs);
w.WritePropertyName("defaults");
WritePolicy(w, Defaults);
w.WriteStartObject("characters");
foreach (var kv in Characters)
{
if (kv.Value.Tags.Count == 0 && kv.Value.Policy == null) continue;
w.WriteStartObject(kv.Key);
WriteList(w, "tags", kv.Value.Tags);
if (kv.Value.Policy != null)
{
w.WritePropertyName("policy");
WritePolicy(w, kv.Value.Policy);
}
w.WriteEndObject();
}
w.WriteEndObject();
w.WriteEndObject();
}
return ms.ToArray();
}
private static void WritePolicy(Utf8JsonWriter w, RynthNetPolicy p)
{
w.WriteStartObject();
w.WriteBoolean("acceptRemoteCommands", p.AcceptRemoteCommands);
WriteList(w, "allow", p.Allow);
WriteList(w, "deny", p.Deny);
WriteList(w, "trustedSenders", p.TrustedSenders);
w.WriteEndObject();
}
private static void WriteList(Utf8JsonWriter w, string name, List<string> items)
{
w.WriteStartArray(name);
foreach (string i in items) w.WriteStringValue(i);
w.WriteEndArray();
}
private static bool Bool(JsonElement r, string name, bool fallback)
=> r.TryGetProperty(name, out JsonElement v) ? v.ValueKind switch { JsonValueKind.True => true, JsonValueKind.False => false, _ => fallback } : fallback;
private static List<string> Strings(JsonElement r, string name)
{
var list = new List<string>();
if (r.TryGetProperty(name, out JsonElement a) && a.ValueKind == JsonValueKind.Array)
foreach (JsonElement e in a.EnumerateArray())
if (e.ValueKind == JsonValueKind.String && !string.IsNullOrWhiteSpace(e.GetString()))
list.Add(e.GetString()!.Trim());
return list;
}
}

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

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

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

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

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