feat(g1): authenticated cross-region llListen bridge

* feat(g1): authenticated spatial llListen relay across simulator processes

* feat(g1): authenticated spatial llListen relay across simulator processes

* docs(g1): deployment, security and acceptance for cross-region llListen relay
This commit is contained in:
OpenGenesis (EULA) authored and GitHub committed 2026-11-22 17:11:29 +01:00
1 parent a9880cf2e4
commit 714af691f3
3 files changed
+295

No files matched your search

@@ -0,0 +1,250 @@
// SPDX-License-Identifier: LicenseRef-OpenGenesisLINK-EULA
// Spatial llListen relay: local object chat + authenticated cross-process chat.
// Relayed chat is sent directly to WorldComm and is NEVER re-broadcast.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
[assembly: Addin("OglCrossRegionChat", Namespace = "OpenGenesisLINK", Version = "1.0.0")]
[assembly: AddinDependency("::OpenSim.Region.Framework", OpenSim.VersionInfo.VersionNumber)]
namespace OpenGenesisLINK.Addons.CrossRegionChat;
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "OglCrossRegionChat")]
public sealed class CrossRegionChatBridge : ISharedRegionModule
{
private static readonly ILog Log = LogManager.GetLogger(typeof(CrossRegionChatBridge));
private readonly object _gate = new();
private readonly List<Scene> _scenes = new();
private readonly ConcurrentDictionary<Guid, long> _seen = new();
private byte[] _key = [];
private UdpClient? _udp;
private CancellationTokenSource? _stop;
private int _listen, _peer, _whisper = 10, _say = 20, _shout = 100;
private bool _enabled;
private string _node = "";
private long _lastPrune;
public string Name => "OglCrossRegionChat";
public Type ReplaceableInterface => null!;
public void Initialise(IConfigSource config)
{
var cfg = config.Configs["OglCrossRegionChat"];
_enabled = cfg?.GetBoolean("Enabled", false) ?? false;
if (!_enabled) return;
_node = cfg?.GetString("NodeId", "")?.Trim() ?? "";
_listen = cfg?.GetInt("ListenPort", 0) ?? 0;
_peer = cfg?.GetInt("PeerPort", 0) ?? 0;
var chat = config.Configs["Chat"];
_whisper = chat?.GetInt("whisper_distance", 10) ?? 10;
_say = chat?.GetInt("say_distance", 20) ?? 20;
_shout = chat?.GetInt("shout_distance", 100) ?? 100;
string secret = Environment.GetEnvironmentVariable("OGL_CHAT_BRIDGE_KEY") ?? "";
if (_node.Length == 0 || _listen < 1024 || _peer < 1024 ||
_listen == _peer || secret.Length != 64)
throw new InvalidOperationException("[OGL CROSS CHAT] Invalid secure relay configuration.");
_key = Convert.FromHexString(secret);
}
public void AddRegion(Scene scene)
{
if (!_enabled) return;
lock (_gate)
{
_scenes.Add(scene);
scene.EventManager.OnChatFromClient += Avatar;
scene.EventManager.OnChatFromWorld += Object;
scene.EventManager.OnChatBroadcast += Object;
if (_udp != null) return;
_stop = new CancellationTokenSource();
_udp = new UdpClient(new IPEndPoint(IPAddress.Loopback, _listen));
_udp.Client.ReceiveBufferSize = 1024 * 1024;
_ = Task.Run(() => Receive(_stop.Token));
Log.InfoFormat("[OGL CROSS CHAT] Relay ready node={0} loopback={1} peer={2}", _node, _listen, _peer);
}
}
public void RegionLoaded(Scene scene) { }
public void PostInitialise() { }
public void RemoveRegion(Scene scene)
{
if (!_enabled) return;
lock (_gate)
{
scene.EventManager.OnChatFromClient -= Avatar;
scene.EventManager.OnChatFromWorld -= Object;
scene.EventManager.OnChatBroadcast -= Object;
_scenes.Remove(scene);
}
}
public void Close()
{
_stop?.Cancel();
_udp?.Dispose();
_stop?.Dispose();
_udp = null;
}
private void Avatar(object sender, OSChatMessage msg) => Dispatch(msg, true);
private void Object(object sender, OSChatMessage msg) => Dispatch(msg, false);
private void Dispatch(OSChatMessage msg, bool avatar)
{
if (!_enabled || msg.Scene is not Scene source ||
string.IsNullOrEmpty(msg.Message) || msg.Message.Length > 1023 ||
msg.Channel == int.MaxValue) return;
int range = Range((int)msg.Type);
if (range <= 0) return;
UUID speakerId;
Vector3 position = msg.Position;
string name = msg.From ?? "";
if (avatar)
{
if (msg.Sender == null) return;
speakerId = msg.Sender.AgentId;
ScenePresence? presence = source.GetScenePresence(speakerId);
if (presence == null || presence.IsChildAgent || presence.IsDeleted) return;
position = presence.AbsolutePosition;
name = presence.Name;
}
else
{
speakerId = msg.SenderUUID;
if (speakerId == UUID.Zero) return;
SceneObjectPart? objectPart = source.GetSceneObjectPart(speakerId);
if (objectPart != null) position = objectPart.AbsolutePosition;
}
float x = source.RegionInfo.WorldLocX + position.X;
float y = source.RegionInfo.WorldLocY + position.Y;
if (!float.IsFinite(x) || !float.IsFinite(y) || !float.IsFinite(position.Z)) return;
ChatData data = new()
{
MessageId = Guid.NewGuid().ToString("D"),
SentMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
SourceRegion = source.RegionInfo.RegionID.ToString(),
SenderId = speakerId.ToString(), Name = name, Message = msg.Message,
Channel = msg.Channel, ChatType = (int)msg.Type, X = x, Y = y, Z = position.Z
};
// Local avatar listeners are already served by the existing ChatModule.
// Its local forwarding excludes object chat, which we supply here.
if (!avatar) Deliver(data, range, source.RegionInfo.RegionID);
Send(data);
}
private int Range(int type) => (ChatTypeEnum)type switch
{
ChatTypeEnum.Whisper => _whisper,
ChatTypeEnum.Say => _say,
ChatTypeEnum.Shout => _shout,
_ => 0
};
private static bool Touches(Scene scene, float x, float y, float range)
{
float left = scene.RegionInfo.WorldLocX, bottom = scene.RegionInfo.WorldLocY;
float width = scene.RegionInfo.RegionSizeX, height = scene.RegionInfo.RegionSizeY;
if (width <= 0 || height <= 0) return false;
float dx = x < left ? left - x : x > left + width ? x - (left + width) : 0;
float dy = y < bottom ? bottom - y : y > bottom + height ? y - (bottom + height) : 0;
return dx * dx + dy * dy < range * range;
}
private void Deliver(ChatData data, int range, UUID origin)
{
Scene[] targets;
lock (_gate) targets = _scenes.ToArray();
if (!UUID.TryParse(data.SenderId, out UUID sender)) return;
foreach (Scene scene in targets)
{
if (scene.RegionInfo.RegionID == origin ||
!Touches(scene, data.X, data.Y, range)) continue;
try
{
IWorldComm? comm = scene.RequestModuleInterface<IWorldComm>();
if (comm == null || comm.ListenerCount == 0) continue;
comm.DeliverMessage((ChatTypeEnum)data.ChatType, data.Channel, data.Name,
sender, data.Message, new Vector3(
data.X - scene.RegionInfo.WorldLocX,
data.Y - scene.RegionInfo.WorldLocY, data.Z));
}
catch (Exception e)
{
Log.Warn("[OGL CROSS CHAT] Destination failed: " + e.GetType().Name);
}
}
}
private void Send(ChatData data)
{
UdpClient? udp = _udp;
if (udp == null) return;
string serialized = JsonSerializer.Serialize(data);
string mac = Convert.ToHexString(HMACSHA256.HashData(_key, Encoding.UTF8.GetBytes(serialized)));
byte[] packet = JsonSerializer.SerializeToUtf8Bytes(new Wire { Data = serialized, Mac = mac });
if (packet.Length > 6000) return;
try { udp.Send(packet, packet.Length, new IPEndPoint(IPAddress.Loopback, _peer)); }
catch (Exception e) { Log.Warn("[OGL CROSS CHAT] Peer unavailable: " + e.GetType().Name); }
}
private async Task Receive(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
var packet = await _udp!.ReceiveAsync(ct);
if (!IPAddress.IsLoopback(packet.RemoteEndPoint.Address) ||
packet.Buffer.Length > 6000) continue;
Wire? wire = JsonSerializer.Deserialize<Wire>(packet.Buffer);
if (wire == null || wire.Mac?.Length != 64 || string.IsNullOrEmpty(wire.Data)) continue;
byte[] signature = Convert.FromHexString(wire.Mac);
byte[] expected = HMACSHA256.HashData(_key, Encoding.UTF8.GetBytes(wire.Data));
if (!CryptographicOperations.FixedTimeEquals(signature, expected)) continue;
ChatData? data = JsonSerializer.Deserialize<ChatData>(wire.Data);
if (data == null || data.Message.Length > 1023 || data.Name.Length > 256 ||
!Guid.TryParse(data.MessageId, out Guid id) ||
!UUID.TryParse(data.SourceRegion, out UUID origin) ||
Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - data.SentMs) > 15000 ||
data.Channel == int.MaxValue || !float.IsFinite(data.X) ||
!float.IsFinite(data.Y) || !float.IsFinite(data.Z)) continue;
int range = Range(data.ChatType);
if (range <= 0 || !_seen.TryAdd(id, data.SentMs)) continue;
Deliver(data, range, origin);
long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
if (now - Interlocked.Read(ref _lastPrune) > 30000 &&
Interlocked.Exchange(ref _lastPrune, now) < now - 30000)
foreach (var item in _seen)
if (now - item.Value > 60000) _seen.TryRemove(item.Key, out _);
}
catch (OperationCanceledException) { break; }
catch (ObjectDisposedException) { break; }
catch (Exception e) { Log.Warn("[OGL CROSS CHAT] Invalid relay packet: " + e.GetType().Name); }
}
}
public sealed class Wire { public string Data { get; set; } = ""; public string Mac { get; set; } = ""; }
public sealed class ChatData
{
public string MessageId { get; set; } = "";
public long SentMs { get; set; }
public string SourceRegion { get; set; } = "";
public string SenderId { get; set; } = "";
public string Name { get; set; } = "";
public string Message { get; set; } = "";
public int Channel { get; set; }
public int ChatType { get; set; }
public float X { get; set; }
public float Y { get; set; }
public float Z { get; set; }
}
}
+44
View File
@@ -0,0 +1,44 @@
# OpenGenesisLINK Generation 1 — Cross-Region Script Chat
The `ogl.crossregionchat.dll` addin extends spatial `llListen` across region boundaries. It is deployed to both the main 42-region simulator and EventSim, which run as distinct .NET processes on the same host.
## Behaviour
- `llWhisper`, `llSay` and `llShout` are delivered to scripts in adjacent regions within their configured metric chat ranges (defaults 10, 20 and 100 metres).
- Works for avatar and object speakers on public, positive and negative chat channels.
- Script-listener channel, name, ID, message and distance filtering remain implemented by `IWorldComm` in the receiving region.
- The stock chat module already forwards **avatar** chat within a single simulator; the addin supplements **object** chat locally and both kinds of chat across simulator processes.
- `llRegionSay`, region broadcasts, direct messages and debug-channel traffic remain confined to their original semantics.
- Remote relay packets never re-trigger a chat broadcast, preventing loops and duplicate echo.
- It does **not** translate script events. The separate opt-in `OglUniversalTranslator` translates eligible avatar-to-viewer chat and IMs.
## Configuration
Place `ogl.crossregionchat.dll` in both simulator `bin` folders. Configure each simulator's `OpenSim.ini`:
```ini
[OglCrossRegionChat]
Enabled = true
NodeId = "Simulator001"
ListenPort = 9971
PeerPort = 9972
```
Use the reverse port mapping and `NodeId = "EventSim001"` in the other process. Both endpoints bind **only to 127.0.0.1** and must share a 32-byte random key, supplied as a 64-character hexadecimal `OGL_CHAT_BRIDGE_KEY` environment variable. Never store the key in Git, an INI file, or logs. Use a root-only environment file for each startup wrapper. No public firewall ports are required.
Packets are authenticated with HMAC-SHA256, accepted only with a 15-second freshness window, and de-duplicated by message ID. The channel and speaker fields are not forwarded to viewers; delivery goes directly to receiving `IWorldComm`. The relay supports processes on the same host only.
## Translation on all 42 regions
Build `addons/OglUniversalTranslator/ogl.universaltranslator.csproj` against the running simulator's assemblies. Install `ogl.universaltranslator.dll` into the main simulator, set `[OglUniversalTranslator] Enabled = true`, configure its distinct `NodeId = Simulator001` and central URL, and load the pre-provisioned `OGL_TRANSLATOR_NODE_TOKEN` securely at startup. Set `[Chat] enabled = false` **only while** the replacement `OglTranslatedChatModule` is available and enabled. The central translator requires opt-in from both participants.
## Acceptance checks
1. Confirm both simulator processes boot without ABI errors and the logs show `[OGL CROSS CHAT] Relay ready`.
2. Confirm normal avatar chat and `!translate status` work in both simulators.
3. Test an avatar near the boundary speaking on a private channel to a `llListen` prim in the neighbouring region; repeat for an object speaker.
4. Test different positive/negative channels, distance limits, and boundaries aligned in X/Y, including corners.
5. Confirm `llRegionSay` stays within one region, no duplicate script events occur, and events continue working after a teleport.
6. Verify the same tests between separate simulator processes where regions are physically adjacent.
Do not infer a successful in-world `listen` event from a successful DLL build or UDP port check alone.
@@ -0,0 +1 @@
<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><TargetFramework>net10.0</TargetFramework><AssemblyName>ogl.crossregionchat</AssemblyName><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup><ItemGroup><Reference Include="OpenSim.Framework"><HintPath>../../bin/OpenSim.Framework.dll</HintPath><Private>false</Private></Reference><Reference Include="OpenSim.Region.Framework"><HintPath>../../bin/OpenSim.Region.Framework.dll</HintPath><Private>false</Private></Reference><Reference Include="Mono.Addins"><HintPath>../../bin/Mono.Addins.dll</HintPath><Private>false</Private></Reference><Reference Include="Nini"><HintPath>../../bin/Nini.dll</HintPath><Private>false</Private></Reference><Reference Include="OpenMetaverse"><HintPath>../../bin/OpenMetaverse.dll</HintPath><Private>false</Private></Reference><Reference Include="OpenMetaverseTypes"><HintPath>../../bin/OpenMetaverseTypes.dll</HintPath><Private>false</Private></Reference><Reference Include="log4net"><HintPath>../../bin/log4net.dll</HintPath><Private>false</Private></Reference></ItemGroup></Project>