the files

This commit is contained in:
niko
2026-10-14 06:59:51 +02:00
parent f6175893fc
commit 2040419525
1855 changed files with 6735668 additions and 0 deletions
+66
View File
@@ -0,0 +1,66 @@
namespace CampusNet.Services;
/// <summary>Photon LoadBalancing operation / parameter / event codes (standard values; the ones in the capture are marked).</summary>
public static class Op
{
public const byte GetRegions = 220, Authenticate = 230, AuthenticateOnce = 231, JoinLobby = 229, LeaveLobby = 228,
CreateGame = 227, JoinGame = 226, JoinRandomGame = 225, Leave = 254, RaiseEvent = 253, SetProperties = 252,
GetProperties = 251, ChangeGroups = 248, FindFriends = 222, GetLobbyStats = 221, WebRpc = 219,
ServerSettings = 218, GetGameList = 217;
}
public static class P
{
public const byte RoomName = 255, ActorNr = 254, TargetActorNr = 253, ActorList = 252, Properties = 251,
Broadcast = 250, PlayerProperties = 249, GameProperties = 248, Cache = 247, ReceiverGroup = 246,
Data = 245, Code = 244, CleanupCacheOnLeave = 241, Group = 240, Remove = 239, Add = 238,
PublishUserId = 239, EmptyRoomTtl = 236, PlayerTtl = 235, IsInactive = 233, CheckUserOnJoin = 232,
ExpectedValues = 231, Address = 230, PeerCount = 229, GameCount = 228, MasterPeerCount = 227,
UserId = 225, ApplicationId = 224, MatchMakingType = 223, GameList = 222, Secret = 221,
AppVersion = 220, AzureNodeInfo = 219, AzureLocalNodeId = 218, ClientAuthenticationType = 217,
ClientAuthenticationData = 216, JoinMode = 215, ClientAuthenticationParams = 214, LobbyName = 213,
LobbyType = 212, LobbyStats = 211, Region = 210, UriPath = 209, RpcCallParams = 208,
RpcCallRetCode = 207, RpcCallRetMessage = 206, CacheSliceIndex = 205, Plugins = 204,
MasterClientId = 203, RoomOptionFlags = 191;
}
public static class Ev
{
public const byte Join = 255, Leave = 254, PropertiesChanged = 253, ErrorInfo = 251, CacheSliceChanged = 224,
AppStats = 226, GameList = 230, GameListUpdate = 229;
}
/// <summary>Well-known game (room) property keys.</summary>
public static class GameProp
{
public const byte MaxPlayers = 255, IsVisible = 254, IsOpen = 253, PlayerCount = 252, Removed = 251,
PropsListedInLobby = 250, CleanupCacheOnLeave = 249, MasterClientId = 248, ExpectedUsers = 247,
PlayerTtl = 246, EmptyRoomTtl = 245;
}
/// <summary>Well-known actor (player) property keys.</summary>
public static class PlayerProp
{
public const byte NickName = 255, IsInactive = 254, UserId = 253;
}
public static class Rc
{
public const short Ok = 0, OperationNotAllowedInCurrentState = -3, InvalidOperation = -2, InternalServerError = -1,
InvalidAuthentication = 32767, GameIdAlreadyExists = 32766, GameFull = 32765, GameClosed = 32764,
NoRandomMatchFound = 32760, GameDoesNotExist = 32758, MaxCcuReached = 32757, InvalidRegion = 32756,
CustomAuthenticationFailed = 32755, AuthenticationTicketExpired = 32753, PluginReportedError = 32752,
PluginMismatch = 32751, JoinFailedPeerAlreadyJoined = 32750, JoinFailedFoundInactiveJoiner = 32749,
JoinFailedWithRejoinerNotFound = 32748, JoinFailedFoundExcludedUserId = 32747,
JoinFailedFoundActiveJoiner = 32746, HttpLimitReached = 32745, ExternalHttpCallFailed = 32744,
SlotError = 32742, InvalidEncryptionParameters = 32741;
}
public static class Cache
{
public const byte DoNotCache = 0, MergeCache = 1, ReplaceCache = 2, RemoveCache = 3, AddToRoomCache = 4,
AddToRoomCacheGlobal = 5, RemoveFromRoomCache = 6, RemoveFromRoomCacheForActorsLeft = 7,
SliceIncreaseIndex = 10, SliceSetIndex = 11, SlicePurgeIndex = 12, SlicePurgeUpToIndex = 13;
}
public static class Receivers { public const byte Others = 0, All = 1, MasterClient = 2; }
+158
View File
@@ -0,0 +1,158 @@
using System.Text;
using CampusNet.Net;
using CampusNet.Protocol;
namespace CampusNet.Services;
/// <summary>
/// Per-peer state above the transport: protocol init, the encryption handshake, and dispatch of
/// decoded operation requests to the role (name/master/game) handler. Replies go back plaintext
/// (the client only decrypts messages carrying the 0x80 flag).
/// </summary>
public sealed class Connection
{
public readonly PhotonUdpServer Server;
public readonly PhotonUdpServer.Peer Peer;
public string AppName = "";
public bool InitDone;
public bool Proto18; // client spoke GpBinary 1.8 in its Init (Photon Voice/Chat libs); PUN is 1.6
public PhotonCrypto? Crypto;
public string? UserId; // set by Authenticate
public string NickName = "";
public Room? Room; // game server only
public Actor? Actor;
public bool InLobby;
public readonly DateTime ConnectedAt = DateTime.UtcNow;
public long Sent, Received;
public readonly TokenBucket Ops = new(Guard.OpsPerSec, Guard.OpsBurst);
public readonly TokenBucket EventBytes = new(Guard.EventBytesPerSec, Guard.EventBytesBurst);
/// <summary>
/// Charge one operation (and, for RaiseEvent, its payload) against this connection's budget.
/// False = drop it. A connection that keeps exceeding the budget is kicked and its IP cooled -
/// that is the RPC-spam / "cheer crash" defence: the flood never reaches the other players.
/// </summary>
public bool Charge(int payloadBytes, string what)
{
long now = Environment.TickCount64;
bool ok = Ops.Take(1, now);
if (ok && payloadBytes > 0) ok = EventBytes.Take(payloadBytes, now);
if (ok) return true;
var b = Ops.DroppedSince > 0 ? Ops : EventBytes;
if (b.DroppedSince == 1) Log.Warn($"{Tag}: over budget ({what}) - dropping (ops {Guard.OpsPerSec}/s, event bytes {Guard.EventBytesPerSec}/s)");
if (b.DroppedSince >= Guard.OpKickAfter)
{
Log.Warn($"{Tag}: kicked - {b.Dropped} operations dropped, {b.DroppedSince} in a row ({what})");
Server.Kick(Peer, "operation flood", Guard.OpFloodBanSec); // shorter than the transport ban: a shared NAT is punished less
}
return false;
}
public Connection(PhotonUdpServer server, PhotonUdpServer.Peer peer) { Server = server; Peer = peer; }
public string Tag => $"{Server.Name}:{Peer}{(UserId != null ? " u" + UserId : "")}{(Actor != null ? " a" + Actor.Nr : "")}";
// ---------------------------------------------------------------- sending
public void SendResponse(byte opCode, short rc, string? debug, Dictionary<byte, object?> p, bool reliable = true)
{
var msg = Proto18 ? GpBinary18.OperationResponseMessage(opCode, rc, debug, p) : GpBinary16.OperationResponseMessage(opCode, rc, debug, p);
Send(msg, reliable);
}
public void SendResponse(byte opCode, Dictionary<byte, object?> p) => SendResponse(opCode, Rc.Ok, null, p);
public void SendError(byte opCode, short rc, string debug) => SendResponse(opCode, rc, debug, new());
public void SendEvent(byte code, Dictionary<byte, object?> p, bool reliable = true)
=> Send(Proto18 ? GpBinary18.EventMessage(code, p) : GpBinary16.EventMessage(code, p), reliable);
public void Send(byte[] message, bool reliable = true)
{
Sent++;
if (reliable) Server.SendReliable(Peer, message); else Server.SendUnreliable(Peer, message);
}
public void Disconnect(string why) => Server.Disconnect(Peer, why);
// ---------------------------------------------------------------- receiving
/// <summary>Decode one message; returns the operation to handle, or null when handled here (init / encryption).</summary>
public GpBinary16.OperationRequest? Decode(byte[] message, out bool encryptedRequest)
{
encryptedRequest = false;
Received++;
if (message.Length < 2 || message[0] != GpBinary16.Magic)
{
Log.Warn($"{Tag}: bad message magic {message[0]:x2}"); return null;
}
byte type = message[1];
bool encrypted = (type & GpBinary16.EncryptedFlag) != 0;
type &= 0x7F;
ReadOnlySpan<byte> body = message.AsSpan(2);
if (type == GpBinary16.MsgInit)
{
// protoMajor, protoMinor, 1e 41 06 19 00, app name (32 bytes)
Proto18 = body.Length >= 2 && body[1] >= 8;
AppName = body.Length >= 39 ? Encoding.ASCII.GetString(body.Slice(7, 32)).TrimEnd('\0') : "";
InitDone = true;
Send(GpBinary16.InitResponse());
Log.Info($"{Tag}: init app='{AppName}' protocol 1.{(Proto18 ? 8 : 6)}");
return null;
}
byte[] plain;
if (encrypted)
{
if (Crypto == null) { Log.Warn($"{Tag}: encrypted message before key exchange"); return null; }
var dec = Crypto.TryDecryptAdaptive(body.ToArray(), b => LooksLikeOperation(b));
if (dec == null) { Log.Warn($"{Tag}: could not decrypt message type {type} ({body.Length} bytes) - no candidate key parsed"); return null; }
plain = dec; encryptedRequest = true;
}
else plain = body.ToArray();
if (type == GpBinary16.MsgInternalOperationRequest)
{
var iop = ReadOp(plain);
if (iop.Code == 0) // InitEncryption: param 1 = client's DH public key
{
Crypto = new PhotonCrypto();
if (iop.Params.TryGetValue(1, out var k) && k is byte[] clientKey) Crypto.DeriveSharedKey(clientKey);
var kp = new Dictionary<byte, object?> { [1] = Crypto.PublicKey };
Send(Proto18 ? GpBinary18.OperationResponseMessage(0, 0, null, kp, internalOp: true) : GpBinary16.OperationResponseMessage(0, 0, null, kp, internalOp: true));
Log.Info($"{Tag}: key exchange done");
}
else if (iop.Code == 1) // Ping (internal) - answer with the client's timestamp echoed
{
Send(Proto18 ? GpBinary18.OperationResponseMessage(1, 0, null, iop.Params, internalOp: true) : GpBinary16.OperationResponseMessage(1, 0, null, iop.Params, internalOp: true));
}
else Log.Warn($"{Tag}: internal op {iop.Code} ignored");
return null;
}
if (type == GpBinary16.MsgOperationRequest)
return ReadOp(plain);
Log.Warn($"{Tag}: unexpected message type {type}");
return null;
}
private GpBinary16.OperationRequest ReadOp(byte[] plain)
{
var op = Proto18 ? GpBinary18.ReadOperationRequest(plain) : GpBinary16.ReadOperationRequest(plain);
op.PayloadBytes = plain.Length;
return op;
}
private bool LooksLikeOperation(byte[] b)
{
try { var op = ReadOp(b); return op.Params.Count <= 64; }
catch { return false; }
}
}
public static class Log
{
public static bool Debug = Environment.GetEnvironmentVariable("CAMPUSNET_DEBUG") == "1";
public static void Info(string s) => Console.WriteLine($"{DateTime.UtcNow:HH:mm:ss.fff} {s}");
public static void Warn(string s) => Console.WriteLine($"{DateTime.UtcNow:HH:mm:ss.fff} WARN {s}");
public static void Dbg(string s) { if (Debug) Console.WriteLine($"{DateTime.UtcNow:HH:mm:ss.fff} dbg {s}"); }
}
+510
View File
@@ -0,0 +1,510 @@
using System.Collections;
using CampusNet.Net;
using CampusNet.Protocol;
namespace CampusNet.Services;
/// <summary>The game-server side: rooms, actors, events (with PUN's event cache), properties, groups.</summary>
public static class GameService
{
public static void Handle(Connection c, GpBinary16.OperationRequest op, bool reliable)
{
int payload = op.Code == Op.RaiseEvent ? op.PayloadBytes : 0;
if (payload > Guard.MaxEventBytes)
{
Log.Warn($"{c.Tag}: event of {payload} bytes refused (cap {Guard.MaxEventBytes})");
c.SendError(op.Code, Rc.InvalidOperation, "Event too large");
return;
}
if (!c.Charge(payload, $"op {op.Code}")) return;
switch (op.Code)
{
case Op.CreateGame:
case Op.JoinGame: Join(c, op); return;
case Op.Leave: Leave(c, op); return;
case Op.RaiseEvent: RaiseEvent(c, op, reliable); return;
case Op.SetProperties: SetProperties(c, op); return;
case Op.GetProperties: GetProperties(c, op); return;
case Op.ChangeGroups: ChangeGroups(c, op); return;
case Op.ServerSettings: c.SendResponse(op.Code, new()); return;
default:
Log.Warn($"{c.Tag}: game op {op.Code} not implemented {LoadBalancingApp.DescribeParams(op.Params)}");
c.SendError(op.Code, Rc.InvalidOperation, "Operation not supported");
return;
}
}
// ---------------------------------------------------------------- join / create
private static void Join(Connection c, GpBinary16.OperationRequest op)
{
if (c.Room != null) { c.SendError(op.Code, Rc.OperationNotAllowedInCurrentState, "Already in a game"); return; }
string name = op.Params.GetValueOrDefault(P.RoomName) as string ?? "";
if (name.Length == 0) { c.SendError(op.Code, Rc.InvalidOperation, "Missing game id"); return; }
int joinMode = LoadBalancingApp.ToInt(op.Params.GetValueOrDefault(P.JoinMode)); // 0 default, 1 CreateIfNotExists, 2 JoinOrRejoin, 3 RejoinOnly
Room room;
bool created;
if (op.Code == Op.CreateGame) room = Rooms.GetOrCreate(name, out created);
else
{
var existing = Rooms.Get(name);
if (existing == null && joinMode != 1) { c.SendError(op.Code, Rc.GameDoesNotExist, "Game does not exist"); return; }
room = existing ?? Rooms.GetOrCreate(name, out _);
created = existing == null;
}
Actor actor;
var joinerProps = op.Params.GetValueOrDefault(P.PlayerProperties) as Hashtable ?? new Hashtable();
var cachedEvents = new List<CachedEvent>();
var others = new List<Connection>();
lock (room.Sync)
{
if (created || room.Actors.Count == 0 && room.Props.Count == 0)
{
if (op.Params.GetValueOrDefault(P.GameProperties) is Hashtable gp) Room.Merge(room.Props, gp);
room.PlayerTtl = LoadBalancingApp.ToInt(op.Params.GetValueOrDefault(P.PlayerTtl));
room.EmptyRoomTtl = LoadBalancingApp.ToInt(op.Params.GetValueOrDefault(P.EmptyRoomTtl));
if (room.Props[GameProp.PlayerTtl] is int pt) room.PlayerTtl = pt;
if (room.Props[GameProp.EmptyRoomTtl] is int et) room.EmptyRoomTtl = et;
Log.Info($"{c.Tag}: created room '{name}' props={GpBinary16.Describe(room.Props)}");
}
var rejoin = room.FindByUserId(c.UserId!);
if (rejoin != null)
{
if (!rejoin.Inactive && rejoin.Conn != null && rejoin.Conn != c)
{
// Same user connected twice: the newer connection wins (the old one is stale).
Log.Warn($"{c.Tag}: user already in '{name}' as actor {rejoin.Nr} - replacing the old connection");
var old = rejoin.Conn; old.Room = null; old.Actor = null;
try { old.Disconnect("replaced by a new connection"); } catch { }
}
actor = rejoin;
actor.Inactive = false; actor.Conn = c;
Room.Merge(actor.Props, joinerProps);
}
else
{
if (!room.IsOpen && joinMode != 3) { c.SendError(op.Code, Rc.GameClosed, "Game closed"); return; }
if (room.MaxPlayers > 0 && room.ActiveCount >= room.MaxPlayers) { c.SendError(op.Code, Rc.GameFull, "Game full"); return; }
actor = new Actor { Nr = room.NextActorNr++, UserId = c.UserId!, Conn = c };
Room.Merge(actor.Props, joinerProps);
if (!actor.Props.ContainsKey(PlayerProp.NickName) && c.NickName.Length > 0) actor.Props[PlayerProp.NickName] = c.NickName;
room.Actors[actor.Nr] = actor;
}
c.Room = room; c.Actor = actor;
foreach (var a in room.Actors.Values)
if (a.Conn != null && a.Conn != c && !a.Inactive) others.Add(a.Conn);
cachedEvents.AddRange(room.Cache);
foreach (var a in room.Actors.Values) cachedEvents.AddRange(a.OwnCache);
// Response: my actor number, everyone's properties, the room's, and the active actor list.
c.SendResponse(op.Code, new Dictionary<byte, object?>
{
[P.ActorNr] = actor.Nr,
[P.ActorList] = room.ActorList(),
[P.PlayerProperties] = room.AllPlayerProps(),
[P.GameProperties] = room.GamePropsForClient(),
[P.RoomName] = name
});
// Join event to everyone including the joiner (PUN sets up its own player from it).
var joinEv = new Dictionary<byte, object?>
{
[P.ActorNr] = actor.Nr,
[P.PlayerProperties] = Room.PlayerPropsForClient(actor),
[P.ActorList] = room.ActorList()
};
c.SendEvent(Ev.Join, joinEv);
foreach (var o in others) o.SendEvent(Ev.Join, joinEv);
}
// Replay the cache so the late joiner sees every instantiate / cached RPC in order.
foreach (var ev in cachedEvents)
c.SendEvent(ev.Code, EventParams(ev.ActorNr, ev.Data));
Log.Info($"{c.Tag}: joined '{name}' as actor {actor.Nr} ({room.ActiveCount} active, {cachedEvents.Count} cached events replayed)");
}
private static Dictionary<byte, object?> EventParams(int senderActor, object? data)
{
var p = new Dictionary<byte, object?> { [P.ActorNr] = senderActor };
if (data != null) p[P.Data] = data;
return p;
}
// ---------------------------------------------------------------- leave
private static void Leave(Connection c, GpBinary16.OperationRequest op)
{
bool inactive = op.Params.GetValueOrDefault(P.IsInactive) is bool b && b;
RemoveFromRoom(c, inactive, "leave");
c.SendResponse(op.Code, new());
}
public static void OnConnectionLost(Connection c) => RemoveFromRoom(c, becomeInactive: true, why: "disconnect");
private static void RemoveFromRoom(Connection c, bool becomeInactive, string why)
{
var room = c.Room; var actor = c.Actor;
if (room == null || actor == null) return;
c.Room = null; c.Actor = null;
List<Connection> others;
int master; bool removed;
lock (room.Sync)
{
if (actor.Conn != c) return; // already superseded
actor.Conn = null;
bool keep = becomeInactive && room.PlayerTtl != 0;
if (keep) { actor.Inactive = true; actor.InactiveSince = DateTime.UtcNow; removed = false; }
else
{
room.Actors.Remove(actor.Nr); removed = true;
// Cached events by this actor go unless they were cached "global".
room.Cache.RemoveAll(e => e.ActorNr == actor.Nr);
}
master = room.MasterClientId;
others = room.Actors.Values.Where(a => a.Conn != null && !a.Inactive).Select(a => a.Conn!).ToList();
if (room.ActiveCount == 0) room.EmptySince = DateTime.UtcNow;
}
var ev = new Dictionary<byte, object?>
{
[P.ActorNr] = actor.Nr,
[P.IsInactive] = !removed,
[P.MasterClientId] = master
};
foreach (var o in others) o.SendEvent(Ev.Leave, ev);
Log.Info($"{c.Tag}: left '{room.Name}' ({why}, {(removed ? "removed" : "inactive")}), master now {master}");
MaybeRemoveRoom(room);
}
private static void MaybeRemoveRoom(Room room)
{
lock (room.Sync)
{
if (room.Actors.Values.Any(a => !a.Inactive)) return;
if (room.EmptyRoomTtl > 0 && (DateTime.UtcNow - room.EmptySince).TotalMilliseconds < room.EmptyRoomTtl) return;
if (room.Actors.Values.Any(a => a.Inactive) && room.PlayerTtl < 0) return; // PlayerTtl -1 = keep forever
}
Rooms.Remove(room.Name);
Log.Info($"room '{room.Name}' removed (empty)");
}
private static DateTime _lastStats = DateTime.MinValue;
/// <summary>Periodic: expire inactive actors past PlayerTtl and empty rooms past EmptyRoomTtl.</summary>
public static void Sweep()
{
bool stats = (DateTime.UtcNow - _lastStats).TotalSeconds >= 15;
if (stats) _lastStats = DateTime.UtcNow;
foreach (var room in Rooms.All())
{
// Every 15 s, for rooms with company: who raised what, and where it went. This is the
// trace for "the other player doesn't move" - it shows whether the mover's events
// arrive at all, whether they are unreliable, which interest group they carry, and
// whether anyone was subscribed to receive them.
if (stats)
{
lock (room.Sync)
{
if (room.ActiveCount >= 2)
{
foreach (var a in room.Actors.Values)
{
if (a.Raised == 0 && a.Conn == null) continue;
string codes = string.Join(" ", a.RaisedByCode.OrderByDescending(kv => kv.Value).Take(8).Select(kv => $"{kv.Key}:{kv.Value}"));
string groups = a.RaisedByGroup.Count == 0 ? "-" : string.Join(" ", a.RaisedByGroup.OrderByDescending(kv => kv.Value).Take(6).Select(kv => $"g{kv.Key}:{kv.Value}"));
string subs = a.Groups.Count == 0 ? "none" : (a.Groups.Count > 12 ? $"{a.Groups.Count} groups" : string.Join(",", a.Groups.OrderBy(g => g)));
Log.Info($"stats '{room.Name}' actor {a.Nr} u{a.UserId}{(a.Inactive ? " (inactive)" : "")}: raised {a.Raised} ({a.RaisedUnreliable} unreliable), delivered {a.Delivered}, no-recipient {a.DroppedNoRecipient}, codes [{codes}], sent-in-groups [{groups}], subscribed [{subs}], recv {a.Conn?.Sent ?? 0} msgs, rtt {a.Conn?.Peer.Rtt ?? 0}ms");
a.Raised = a.RaisedUnreliable = a.Delivered = a.DroppedNoRecipient = 0;
a.RaisedByCode.Clear(); a.RaisedByGroup.Clear();
}
}
}
}
List<Connection> others = new(); List<int> expired = new(); int master;
lock (room.Sync)
{
foreach (var a in room.Actors.Values.Where(a => a.Inactive).ToList())
{
if (room.PlayerTtl > 0 && (DateTime.UtcNow - a.InactiveSince).TotalMilliseconds > room.PlayerTtl)
{
room.Actors.Remove(a.Nr); room.Cache.RemoveAll(e => e.ActorNr == a.Nr); expired.Add(a.Nr);
}
}
master = room.MasterClientId;
if (expired.Count > 0) others = room.Actors.Values.Where(a => a.Conn != null && !a.Inactive).Select(a => a.Conn!).ToList();
}
foreach (var nr in expired)
foreach (var o in others)
o.SendEvent(Ev.Leave, new Dictionary<byte, object?> { [P.ActorNr] = nr, [P.IsInactive] = false, [P.MasterClientId] = master });
MaybeRemoveRoom(room);
}
}
// ---------------------------------------------------------------- events
private static readonly string[] TraceRooms = (Environment.GetEnvironmentVariable("CAMPUSNET_TRACE_ROOM") ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
private static readonly HashSet<string> TraceUsers = new((Environment.GetEnvironmentVariable("CAMPUSNET_TRACE_USER") ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries));
private static readonly string TraceRoom = (TraceRooms.Length > 0 || TraceUsers.Count > 0) ? "on" : "";
private static bool Traced(Room room) => TraceRooms.Any(t => room.Name.Contains(t, StringComparison.OrdinalIgnoreCase));
// A traced user's rooms are traced too (private instances carry no room id in their name).
private static bool Traced(Room room, Actor me) => Traced(room) || TraceUsers.Contains(me.UserId ?? "") || room.Actors.Values.Any(a => TraceUsers.Contains(a.UserId ?? ""));
/// <summary>The actor numbers in a RaiseEvent's target list, whatever container they arrived in.</summary>
private static int[]? ActorTargets(object? v)
{
switch (v)
{
case null: return null;
case int[] n: return n;
case byte[] b: return b.Select(x => (int)x).ToArray();
case short[] sh: return sh.Select(x => (int)x).ToArray();
case TypedArray ta: return ta.Items.Select(LoadBalancingApp.ToInt).ToArray();
case object?[] oa: return oa.Select(LoadBalancingApp.ToInt).ToArray();
default:
Log.Warn($"RaiseEvent: unrecognised target-actor list type {v.GetType().Name} - treated as none");
return null;
}
}
private static void RaiseEvent(Connection c, GpBinary16.OperationRequest op, bool reliable)
{
var room = c.Room; var me = c.Actor;
if (room == null || me == null) { c.SendError(op.Code, Rc.OperationNotAllowedInCurrentState, "Not in a game"); return; }
byte code = (byte)LoadBalancingApp.ToInt(op.Params.GetValueOrDefault(P.Code));
var data = op.Params.GetValueOrDefault(P.Data);
byte cache = (byte)LoadBalancingApp.ToInt(op.Params.GetValueOrDefault(P.Cache));
byte receivers = (byte)LoadBalancingApp.ToInt(op.Params.GetValueOrDefault(P.ReceiverGroup));
byte group = (byte)LoadBalancingApp.ToInt(op.Params.GetValueOrDefault(P.Group));
// Target actors (252). PUN spells this int[] ('n'), which is all that was matched before;
// a typed array of ints / an object[] / a byte[] decodes to something else and used to be
// silently treated as "no targets" - the event then went by receiver group instead.
var targets = ActorTargets(op.Params.GetValueOrDefault(P.ActorList));
var recipients = new List<Connection>();
lock (room.Sync)
{
bool isMaster = me.Nr == room.MasterClientId;
switch (cache)
{
case Cache.AddToRoomCache:
case Cache.AddToRoomCacheGlobal:
if (room.Cache.Count >= Guard.MaxRoomCache)
{
if (room.Cache.Count == Guard.MaxRoomCache) Log.Warn($"{c.Tag}: room '{room.Name}' cache full ({Guard.MaxRoomCache}) - new cached events are delivered but not kept");
break;
}
room.Cache.Add(new CachedEvent { ActorNr = cache == Cache.AddToRoomCacheGlobal ? 0 : me.Nr, Code = code, Data = data, Group = group }); break;
case Cache.RemoveFromRoomCache:
// Only the master client may purge OTHER actors' cached events (PUN's DestroyAll /
// scene-object cleanup); everyone else can only take back their own, so one client
// cannot wipe everybody's instantiations out from under late joiners.
room.Cache.RemoveAll(e => (isMaster || e.ActorNr == me.Nr) && CacheFilterMatch(e, targets, op.Params.ContainsKey(P.Code) ? code : null, data as Hashtable)); break;
case Cache.RemoveFromRoomCacheForActorsLeft:
room.Cache.RemoveAll(e => e.ActorNr != 0 && !room.Actors.ContainsKey(e.ActorNr)); break;
case Cache.MergeCache:
{
var existing = me.OwnCache.FirstOrDefault(e => e.Code == code);
if (existing != null && existing.Data is Hashtable eh && data is Hashtable dh) Room.Merge(eh, dh);
else if (existing != null) existing.Data = data;
else if (me.OwnCache.Count < Guard.MaxActorCache) me.OwnCache.Add(new CachedEvent { ActorNr = me.Nr, Code = code, Data = data, Group = group });
break;
}
case Cache.ReplaceCache:
me.OwnCache.RemoveAll(e => e.Code == code);
if (data != null && me.OwnCache.Count < Guard.MaxActorCache) me.OwnCache.Add(new CachedEvent { ActorNr = me.Nr, Code = code, Data = data, Group = group });
break;
case Cache.RemoveCache:
me.OwnCache.RemoveAll(e => e.Code == code); break;
}
if (targets != null)
{
foreach (var nr in targets)
if (room.Actors.TryGetValue(nr, out var a) && a.Conn != null && !a.Inactive) recipients.Add(a.Conn);
}
else if (receivers == Receivers.MasterClient)
{
if (room.Actors.TryGetValue(room.MasterClientId, out var m) && m.Conn != null) recipients.Add(m.Conn);
}
else
{
foreach (var a in room.Actors.Values)
{
if (a.Conn == null || a.Inactive) continue;
if (a == me && receivers != Receivers.All) continue;
if (group != 0 && !a.Groups.Contains(group)) continue;
recipients.Add(a.Conn);
}
}
}
// A pure cache-manipulation call (no code / no data) has nothing to deliver.
bool deliver = op.Params.ContainsKey(P.Code) && !(cache >= Cache.RemoveFromRoomCache && cache <= Cache.RemoveFromRoomCacheForActorsLeft && data == null);
// Room trace (CAMPUSNET_TRACE_ROOM=<substring of the room name>): every non-transform event
// with its size, routing and - for RPC-shaped payloads - the readable strings inside (RR RPC
// method names are plain text on the wire). Used to see what a "Rooms 2.0" authority
// handshake actually sends, without the firehose of CAMPUSNET_DEBUG.
if (TraceRoom.Length > 0 && code != 28 && Traced(room, me))
{
string strs = "";
try
{
var found = new List<string>();
void Scan(object? o, int depth)
{
if (o == null || depth > 4 || found.Count >= 6) return;
if (o is string str) { if (str.Length >= 3 && str.Length <= 80) found.Add(str); return; }
if (o is byte[] bytes)
{
var sb = new System.Text.StringBuilder();
foreach (var bt in bytes)
{
if (bt >= 32 && bt < 127) sb.Append((char)bt);
else { if (sb.Length >= 5 && found.Count < 6) found.Add(sb.ToString()); sb.Clear(); }
}
if (sb.Length >= 5 && found.Count < 6) found.Add(sb.ToString());
return;
}
if (o is Hashtable ht) { foreach (DictionaryEntry e in ht) { Scan(e.Key, depth + 1); Scan(e.Value, depth + 1); } return; }
if (o is System.Collections.IEnumerable en) { int n = 0; foreach (var x in en) { if (n++ > 64) break; Scan(x, depth + 1); } }
}
Scan(data, 0);
if (found.Count > 0) strs = " strs=[" + string.Join(" | ", found) + "]";
}
catch { }
// Every op parameter with its decoded CLR type, so a receiver-group / target-list field
// that arrives in an unexpected encoding is visible instead of silently ignored.
string keys = "[" + string.Join(",", op.Params.Select(kv => $"{kv.Key}:{(kv.Value == null ? "null" : kv.Value is TypedArray ta ? $"TypedArray<{(char)ta.ElemType}>" : kv.Value.GetType().Name)}")) + "]";
Log.Info($"trace '{room.Name}' a{me.Nr} u{me.UserId}: ev {code} {op.PayloadBytes}B cache={cache} recv={receivers} group={group} targets=[{(targets == null ? "-" : string.Join(",", targets))}] -> {recipients.Count} recipient(s){(deliver ? "" : " (cache-only)")} keys={keys}{strs}");
}
if (deliver)
{
var msg = GpBinary16.EventMessage(code, EventParams(me.Nr, data));
foreach (var r in recipients) r.Send(msg, reliable);
}
lock (room.Sync)
{
me.Raised++; if (!reliable) me.RaisedUnreliable++;
me.RaisedByCode[code] = me.RaisedByCode.GetValueOrDefault(code) + 1;
if (group != 0) me.RaisedByGroup[group] = me.RaisedByGroup.GetValueOrDefault(group) + 1;
if (deliver) { me.Delivered += recipients.Count; if (recipients.Count == 0) me.DroppedNoRecipient++; }
}
if (reliable) c.SendResponse(op.Code, new()); // PUN expects the ack'd response for reliable raises
}
private static bool CacheFilterMatch(CachedEvent e, int[]? actors, byte? code, Hashtable? dataFilter)
{
if (actors != null && actors.Length > 0 && !actors.Contains(e.ActorNr)) return false;
if (code != null && e.Code != code) return false;
if (dataFilter != null)
{
if (e.Data is not Hashtable h) return false;
foreach (DictionaryEntry f in dataFilter)
if (!h.ContainsKey(f.Key) || !Room.ValuesEqual(h[f.Key], f.Value)) return false;
}
return true;
}
// ---------------------------------------------------------------- properties
private static void SetProperties(Connection c, GpBinary16.OperationRequest op)
{
var room = c.Room; var me = c.Actor;
if (room == null || me == null) { c.SendError(op.Code, Rc.OperationNotAllowedInCurrentState, "Not in a game"); return; }
var props = op.Params.GetValueOrDefault(P.Properties) as Hashtable ?? new Hashtable();
var expected = op.Params.GetValueOrDefault(P.ExpectedValues) as Hashtable;
bool broadcast = op.Params.GetValueOrDefault(P.Broadcast) is bool b && b;
int target = LoadBalancingApp.ToInt(op.Params.GetValueOrDefault(P.ActorNr)); // 0 = room properties
Hashtable changed; List<Connection> recipients = new();
lock (room.Sync)
{
Hashtable store;
if (target == 0) store = room.Props;
else
{
if (!room.Actors.TryGetValue(target, out var a)) { c.SendError(op.Code, Rc.InvalidOperation, "No such actor"); return; }
// A client writes its own player properties; only the master client may write
// another actor's (PUN never does this from a plain client, a modified one would -
// it is how a "bot" renames or re-flags other players).
if (target != me.Nr && me.Nr != room.MasterClientId)
{
Log.Warn($"{c.Tag}: tried to set actor {target}'s properties - refused");
c.SendError(op.Code, Rc.InvalidOperation, "Not your actor");
return;
}
store = a.Props;
}
if (!Room.CasMatches(store, expected))
{
c.SendError(op.Code, Rc.InvalidOperation, "CAS failed"); // PUN treats this rc as the CAS miss
return;
}
changed = Room.Merge(store, props);
if (target == 0 && changed.ContainsKey(GameProp.PlayerTtl) && changed[GameProp.PlayerTtl] is int pt) room.PlayerTtl = pt;
if (target == 0 && changed.ContainsKey(GameProp.EmptyRoomTtl) && changed[GameProp.EmptyRoomTtl] is int et) room.EmptyRoomTtl = et;
foreach (var a in room.Actors.Values)
if (a.Conn != null && !a.Inactive && (broadcast || a.Conn != c)) recipients.Add(a.Conn);
}
c.SendResponse(op.Code, new());
// Player-property writes are rare (join, avatar/state changes) - log the keys and sizes so a
// "others don't see my new outfit" report can be matched against what actually crossed the wire.
if (target != 0 || (TraceRoom.Length > 0 && Traced(room, me)))
{
var desc = string.Join(", ", changed.Keys.Cast<object>().Select(k => $"{k}={(changed[k] is byte[] ba ? ba.Length + "B" : changed[k] is string str ? str.Length + "ch" : changed[k] is Hashtable ? "table" : changed[k]?.ToString() ?? "null")}"));
Log.Info($"{c.Tag}: {(target == 0 ? "room" : "player")} props on {(target == 0 ? "room" : "actor " + target)} [{desc}] cas={(expected != null)} -> {recipients.Count} recipient(s){(broadcast ? " (broadcast)" : "")}");
}
if (broadcast || recipients.Count > 0)
{
var ev = new Dictionary<byte, object?> { [P.TargetActorNr] = target, [P.Properties] = changed, [P.ActorNr] = me.Nr };
var msg = GpBinary16.EventMessage(Ev.PropertiesChanged, ev);
foreach (var r in recipients) if (broadcast || r != c) r.Send(msg);
}
}
private static void GetProperties(Connection c, GpBinary16.OperationRequest op)
{
var room = c.Room;
if (room == null) { c.SendError(op.Code, Rc.OperationNotAllowedInCurrentState, "Not in a game"); return; }
var resp = new Dictionary<byte, object?>();
lock (room.Sync)
{
resp[P.GameProperties] = room.GamePropsForClient();
resp[P.PlayerProperties] = room.AllPlayerProps();
}
c.SendResponse(op.Code, resp);
}
private static void ChangeGroups(Connection c, GpBinary16.OperationRequest op)
{
var me = c.Actor; var room = c.Room;
if (room == null || me == null) { c.SendError(op.Code, Rc.OperationNotAllowedInCurrentState, "Not in a game"); return; }
lock (room.Sync)
{
// null = all groups; empty array = none
if (op.Params.TryGetValue(P.Remove, out var rem))
{
if (rem == null) me.Groups.Clear();
else foreach (var g in AsBytes(rem)) me.Groups.Remove(g);
}
if (op.Params.TryGetValue(P.Add, out var add))
{
if (add == null) for (int g = 1; g < 256; g++) me.Groups.Add((byte)g);
else foreach (var g in AsBytes(add)) me.Groups.Add(g);
}
Log.Info($"{c.Tag}: groups now [{(me.Groups.Count > 12 ? me.Groups.Count + " groups" : string.Join(",", me.Groups.OrderBy(g => g)))}] (remove={(op.Params.TryGetValue(P.Remove, out var rr) ? (rr == null ? "all" : GpBinary16.Describe(rr)) : "-")} add={(op.Params.TryGetValue(P.Add, out var aa) ? (aa == null ? "all" : GpBinary16.Describe(aa)) : "-")})");
}
c.SendResponse(op.Code, new());
}
private static IEnumerable<byte> AsBytes(object v) => v switch
{
byte[] b => b,
TypedArray ta => ta.Items.Select(x => (byte)LoadBalancingApp.ToInt(x)),
int[] n => n.Select(x => (byte)x),
_ => Array.Empty<byte>()
};
}
+297
View File
@@ -0,0 +1,297 @@
using System.Collections;
using CampusNet.Net;
using CampusNet.Protocol;
namespace CampusNet.Services;
public enum Role { NameServer, Master, Game }
/// <summary>
/// The Photon LoadBalancing application: one instance per role/port. The client walks
/// NameServer (GetRegions/Authenticate → master address) → Master (Authenticate, JoinGame → game
/// address) → Game (Authenticate, JoinGame, RaiseEvent/SetProperties/Leave). All three run in this
/// process and share the room registry, so "addresses" are just this host's ports.
/// </summary>
public sealed class LoadBalancingApp
{
public readonly Role Role;
public readonly PhotonUdpServer Server;
public readonly string PublicHost;
public readonly int MasterPort, GamePort;
private static readonly object AppStatsSync = new();
public LoadBalancingApp(Role role, PhotonUdpServer server, string publicHost, int masterPort, int gamePort)
{
Role = role; Server = server; PublicHost = publicHost; MasterPort = masterPort; GamePort = gamePort;
server.OnConnect += p => p.Session = new Connection(server, p);
server.OnMessage += OnMessage;
server.OnDisconnect += OnDisconnect;
}
private static Connection C(PhotonUdpServer.Peer p) => (Connection)(p.Session ??= null!);
private void OnMessage(PhotonUdpServer.Peer peer, byte[] message, bool reliable)
{
if (peer.Session is not Connection c) { c = new Connection(Server, peer); peer.Session = c; }
GpBinary16.OperationRequest? op;
try { op = c.Decode(message, out _); }
catch (Exception ex) { Log.Warn($"{c.Tag}: decode failed: {ex.Message} [{Convert.ToHexString(message.AsSpan(0, Math.Min(48, message.Length)))}]"); return; }
if (op == null) return;
if (Log.Debug) Log.Dbg($"{c.Tag} <- op {op.Code} {DescribeParams(op.Params)}");
try { Handle(c, op, reliable); }
catch (Exception ex)
{
Log.Warn($"{c.Tag}: op {op.Code} failed: {ex}");
c.SendError(op.Code, Rc.InternalServerError, ex.Message);
}
}
private void OnDisconnect(PhotonUdpServer.Peer peer)
{
if (peer.Session is not Connection c) return;
if (Role == Role.Game && c.Room != null) GameService.OnConnectionLost(c);
}
private void Handle(Connection c, GpBinary16.OperationRequest op, bool reliable)
{
switch (op.Code)
{
case Op.GetRegions: HandleGetRegions(c, op); return;
case Op.Authenticate:
case Op.AuthenticateOnce: HandleAuthenticate(c, op); return;
}
if (c.UserId == null) { c.SendError(op.Code, Rc.OperationNotAllowedInCurrentState, "Not authenticated"); return; }
if (Role != Role.Game && !c.Charge(0, $"op {op.Code}")) return;
switch (Role)
{
case Role.Master: HandleMaster(c, op); return;
case Role.Game: GameService.Handle(c, op, reliable); return;
default: c.SendError(op.Code, Rc.InvalidOperation, "Not on this server"); return;
}
}
// ---------------------------------------------------------------- name server
private void HandleGetRegions(Connection c, GpBinary16.OperationRequest op)
{
c.SendResponse(Op.GetRegions, new Dictionary<byte, object?>
{
[P.Region] = new[] { "us" },
[P.Address] = new[] { $"{PublicHost}:{MasterPort}" }
});
}
private void HandleAuthenticate(Connection c, GpBinary16.OperationRequest op)
{
string? userId = null, nick = "";
if (Role == Role.NameServer)
{
// Custom auth: the Campus photonAuthToken rides in ClientAuthenticationData (216); a
// few builds put it in the params string (214) instead. Fall back to the UserId (225).
// Rec Room sends the JWT as the BYTES of ClientAuthenticationParams (214), not a string.
string? token = null;
foreach (var key in new[] { P.ClientAuthenticationData, P.ClientAuthenticationParams })
{
var raw = op.Params.GetValueOrDefault(key);
var str = raw as string ?? (raw is byte[] rb ? System.Text.Encoding.UTF8.GetString(rb) : null);
if (string.IsNullOrEmpty(str)) continue;
if (str.StartsWith("token=")) str = str[6..];
// Rec Room's auth data is JSON: {"accountId":"6","accessToken":"<the game session JWT>"}.
if (str.StartsWith("{"))
{
try
{
using var doc = System.Text.Json.JsonDocument.Parse(str);
if (doc.RootElement.TryGetProperty("accessToken", out var at)) str = at.GetString() ?? str;
}
catch { }
}
if (Tokens.ValidateCampusJwt(str) != null) { token = str; break; }
token ??= str;
}
var v = Tokens.ValidateCampusJwt(token);
if (v != null) userId = v.Value.userId;
else if (op.Params.GetValueOrDefault(P.UserId) is string uid && uid.Length > 0 && AllowUnsignedUserId) userId = uid;
if (userId == null)
{
Log.Warn($"{c.Tag}: authentication rejected (token {(token == null ? "absent" : "invalid")}) params={DescribeParams(op.Params)} token='{token}'");
if (op.Params.GetValueOrDefault(P.ClientAuthenticationParams) is byte[] rawp) Log.Warn($"{c.Tag}: 214 hex={Convert.ToHexString(rawp.AsSpan(0, Math.Min(64, rawp.Length)))}");
c.SendError(op.Code, Rc.CustomAuthenticationFailed, "Invalid token");
return;
}
nick = op.Params.GetValueOrDefault(P.UriPath) as string ?? "";
}
else
{
var s = Tokens.ValidateSecret(op.Params.GetValueOrDefault(P.Secret) as string);
if (s == null)
{
Log.Warn($"{c.Tag}: bad secret on {Role}");
c.SendError(op.Code, Rc.InvalidAuthentication, "Invalid secret");
return;
}
userId = s.Value.userId; nick = s.Value.nick;
}
c.UserId = userId; c.NickName = nick ?? "";
string secret = Tokens.MintSecret(userId, c.NickName);
var resp = new Dictionary<byte, object?> { [P.Secret] = secret, [P.UserId] = userId };
if (Role == Role.NameServer) resp[P.Address] = $"{PublicHost}:{MasterPort}";
c.SendResponse(op.Code, resp);
Log.Info($"{c.Tag}: authenticated on {Role} (app '{c.AppName}')");
if (Role == Role.Master) SendAppStats(c);
}
public static bool AllowUnsignedUserId = Environment.GetEnvironmentVariable("CAMPUSNET_ALLOW_UNSIGNED") == "1";
// ---------------------------------------------------------------- master
private void SendAppStats(Connection c)
{
int peers = Server.PeerCount;
c.SendEvent(Ev.AppStats, new Dictionary<byte, object?>
{
[P.MasterPeerCount] = peers,
[P.PeerCount] = Rooms.All().Sum(r => r.ActiveCount),
[P.GameCount] = Rooms.Count
}, reliable: false);
}
private void HandleMaster(Connection c, GpBinary16.OperationRequest op)
{
switch (op.Code)
{
case Op.JoinLobby:
c.InLobby = true;
c.SendResponse(op.Code, new());
c.SendEvent(Ev.GameList, new Dictionary<byte, object?> { [P.GameList] = GameListHashtable() });
return;
case Op.LeaveLobby:
c.InLobby = false;
c.SendResponse(op.Code, new());
return;
case Op.CreateGame:
case Op.JoinGame:
{
string name = op.Params.GetValueOrDefault(P.RoomName) as string ?? "";
if (name.Length == 0) name = Guid.NewGuid().ToString("N");
int joinMode = ToInt(op.Params.GetValueOrDefault(P.JoinMode));
var room = Rooms.Get(name);
if (op.Code == Op.JoinGame && room == null && joinMode == 0)
{
c.SendError(op.Code, Rc.GameDoesNotExist, "Game does not exist"); return;
}
if (op.Code == Op.CreateGame && room != null && joinMode == 0)
{
c.SendError(op.Code, Rc.GameIdAlreadyExists, "A game with the specified id already exist"); return;
}
if (room != null)
{
lock (room.Sync)
{
bool rejoin = room.FindByUserId(c.UserId!) != null;
if (!rejoin && !room.IsOpen) { c.SendError(op.Code, Rc.GameClosed, "Game closed"); return; }
if (!rejoin && room.MaxPlayers > 0 && room.ActiveCount >= room.MaxPlayers) { c.SendError(op.Code, Rc.GameFull, "Game full"); return; }
}
}
c.SendResponse(op.Code, new Dictionary<byte, object?>
{
[P.Address] = $"{PublicHost}:{GamePort}",
[P.Secret] = Tokens.MintSecret(c.UserId!, c.NickName),
[P.RoomName] = name
});
Log.Info($"{c.Tag}: {(op.Code == Op.CreateGame ? "create" : "join")} '{name}' -> game server");
return;
}
case Op.JoinRandomGame:
{
var expected = op.Params.GetValueOrDefault(P.GameProperties) as Hashtable;
Room? pick = null;
foreach (var r in Rooms.All())
{
lock (r.Sync)
{
if (!r.IsOpen || !r.IsVisible) continue;
if (r.MaxPlayers > 0 && r.ActiveCount >= r.MaxPlayers) continue;
if (expected != null && !Room.CasMatches(r.Props, expected)) continue;
pick = r; break;
}
}
if (pick == null) { c.SendError(op.Code, Rc.NoRandomMatchFound, "No match found"); return; }
c.SendResponse(op.Code, new Dictionary<byte, object?>
{
[P.Address] = $"{PublicHost}:{GamePort}",
[P.Secret] = Tokens.MintSecret(c.UserId!, c.NickName),
[P.RoomName] = pick.Name
});
return;
}
case Op.GetGameList:
c.SendResponse(op.Code, new Dictionary<byte, object?> { [P.GameList] = GameListHashtable() });
return;
case Op.FindFriends:
{
var ids = op.Params.GetValueOrDefault((byte)1) as string[] ?? Array.Empty<string>();
var online = new bool[ids.Length]; var rooms = new string[ids.Length];
for (int i = 0; i < ids.Length; i++)
{
rooms[i] = "";
foreach (var r in Rooms.All())
{
Actor? a; lock (r.Sync) a = r.FindByUserId(ids[i]);
if (a != null && !a.Inactive) { online[i] = true; rooms[i] = r.Name; break; }
}
}
c.SendResponse(op.Code, new Dictionary<byte, object?>
{
[1] = new TypedArray((byte)'o', online.Cast<object?>().ToArray()),
[2] = rooms
});
return;
}
case Op.GetLobbyStats:
c.SendResponse(op.Code, new Dictionary<byte, object?>
{
[P.LobbyName] = new[] { "" }, [P.LobbyType] = new TypedArray((byte)'b', new object?[] { (byte)0 }),
[P.PeerCount] = new[] { Server.PeerCount }, [P.GameCount] = new[] { Rooms.Count }
});
return;
case Op.SetProperties:
case Op.RaiseEvent:
c.SendResponse(op.Code, new()); // harmless on the master
return;
case Op.ServerSettings:
c.SendResponse(op.Code, new());
return;
default:
Log.Warn($"{c.Tag}: master op {op.Code} not implemented {DescribeParams(op.Params)}");
c.SendError(op.Code, Rc.InvalidOperation, "Operation not supported");
return;
}
}
private static Hashtable GameListHashtable()
{
var h = new Hashtable();
foreach (var r in Rooms.All())
{
lock (r.Sync)
{
if (!r.IsVisible) continue;
var props = new Hashtable();
if (r.Props[GameProp.PropsListedInLobby] is string[] listed)
foreach (var k in listed) if (r.Props.ContainsKey(k)) props[k] = r.Props[k];
props[GameProp.PlayerCount] = (byte)r.ActiveCount;
props[GameProp.MaxPlayers] = (byte)Math.Clamp(r.MaxPlayers, 0, 255);
props[GameProp.IsOpen] = r.IsOpen;
props[GameProp.IsVisible] = r.IsVisible;
h[r.Name] = props;
}
}
return h;
}
public static int ToInt(object? v) => v switch { null => 0, byte b => b, short s => s, int i => i, long l => (int)l, bool o => o ? 1 : 0, _ => 0 };
public static string DescribeParams(IReadOnlyDictionary<byte, object?> p)
=> "{" + string.Join(", ", p.Select(e => $"{e.Key}={GpBinary16.Describe(e.Value)}")) + "}";
}
+142
View File
@@ -0,0 +1,142 @@
using System.Collections;
using CampusNet.Protocol;
namespace CampusNet.Services;
public sealed class Actor
{
public int Nr;
public string UserId = "";
public Connection? Conn; // null while inactive (disconnected with PlayerTtl)
public readonly Hashtable Props = new();
public bool Inactive;
public DateTime InactiveSince;
public readonly HashSet<byte> Groups = new(); // interest groups (0 = always)
public readonly List<CachedEvent> OwnCache = new(); // MergeCache / ReplaceCache per actor (legacy)
// Traffic counters for the periodic room summary (see GameService.Sweep): what this actor
// raised, how much of it was unreliable, per event code, and how many recipients it reached.
public long Raised, RaisedUnreliable, Delivered, DroppedNoRecipient;
public readonly Dictionary<byte, int> RaisedByCode = new();
public readonly Dictionary<byte, int> RaisedByGroup = new();
}
public sealed class CachedEvent
{
public int ActorNr; public byte Code; public object? Data; public byte Group;
}
/// <summary>A game room: actors, properties, and the event cache PUN relies on for late joiners.</summary>
public sealed class Room
{
public readonly string Name;
public readonly Hashtable Props = new(); // byte system keys + custom keys
public readonly SortedDictionary<int, Actor> Actors = new();
public readonly List<CachedEvent> Cache = new(); // AddToRoomCache / AddToRoomCacheGlobal, in order
public int NextActorNr = 1;
public int PlayerTtl, EmptyRoomTtl;
public DateTime EmptySince = DateTime.UtcNow;
public readonly object Sync = new();
public readonly DateTime CreatedAt = DateTime.UtcNow;
public Room(string name) { Name = name; }
public int MaxPlayers => Props[GameProp.MaxPlayers] is byte b ? b : (Props[GameProp.MaxPlayers] is int i ? i : 0);
public bool IsOpen => Props[GameProp.IsOpen] is bool o ? o : true;
public bool IsVisible => Props[GameProp.IsVisible] is bool v ? v : true;
public int ActiveCount => Actors.Values.Count(a => !a.Inactive);
public int MasterClientId => Actors.Values.Where(a => !a.Inactive).Select(a => a.Nr).DefaultIfEmpty(0).Min();
public Actor? FindByUserId(string userId) => Actors.Values.FirstOrDefault(a => a.UserId == userId);
/// <summary>Game properties as sent to clients: stored props plus the live system values.</summary>
public Hashtable GamePropsForClient()
{
var h = new Hashtable();
foreach (DictionaryEntry e in Props) h[e.Key] = e.Value;
h[GameProp.MasterClientId] = MasterClientId;
h[GameProp.PlayerCount] = (byte)ActiveCount;
if (!h.ContainsKey(GameProp.IsOpen)) h[GameProp.IsOpen] = true;
if (!h.ContainsKey(GameProp.IsVisible)) h[GameProp.IsVisible] = true;
return h;
}
/// <summary>All players' properties keyed by actor number (what the join response carries).</summary>
public Hashtable AllPlayerProps()
{
var h = new Hashtable();
foreach (var a in Actors.Values) h[a.Nr] = PlayerPropsForClient(a);
return h;
}
public static Hashtable PlayerPropsForClient(Actor a)
{
var h = new Hashtable();
foreach (DictionaryEntry e in a.Props) h[e.Key] = e.Value;
h[PlayerProp.UserId] = a.UserId;
h[PlayerProp.IsInactive] = a.Inactive;
if (!h.ContainsKey(PlayerProp.NickName)) h[PlayerProp.NickName] = "";
return h;
}
public int[] ActorList() => Actors.Values.Where(a => !a.Inactive).Select(a => a.Nr).ToArray();
/// <summary>Copy props from a client hashtable into a store, honouring the "null removes" rule; returns the changed subset.</summary>
public static Hashtable Merge(Hashtable target, Hashtable incoming)
{
var changed = new Hashtable();
foreach (DictionaryEntry e in incoming)
{
if (e.Value == null) { if (target.ContainsKey(e.Key)) { target.Remove(e.Key); changed[e.Key] = null; } }
else { target[e.Key] = e.Value; changed[e.Key] = e.Value; }
}
return changed;
}
/// <summary>Check-and-set: every expected value must match the current one (both absent counts as match).</summary>
public static bool CasMatches(Hashtable target, Hashtable? expected)
{
if (expected == null) return true;
foreach (DictionaryEntry e in expected)
{
var cur = target[e.Key];
if (!ValuesEqual(cur, e.Value)) return false;
}
return true;
}
public static bool ValuesEqual(object? a, object? b)
{
if (a == null || b == null) return a == null && b == null;
if (a is byte[] ab && b is byte[] bb) return ab.AsSpan().SequenceEqual(bb);
if (a is Array aa && b is Array ba)
{
if (aa.Length != ba.Length) return false;
for (int i = 0; i < aa.Length; i++) if (!ValuesEqual(aa.GetValue(i), ba.GetValue(i))) return false;
return true;
}
if (a is CustomValue ca && b is CustomValue cb) return ca.Code == cb.Code && ca.Data.AsSpan().SequenceEqual(cb.Data);
try { return Convert.ToDouble(a) == Convert.ToDouble(b); } catch { }
return a.Equals(b);
}
}
/// <summary>Every room this process hosts (master and game share it - one process).</summary>
public static class Rooms
{
private static readonly Dictionary<string, Room> _rooms = new();
public static readonly object Sync = new();
public static Room? Get(string name) { lock (Sync) return _rooms.TryGetValue(name, out var r) ? r : null; }
public static Room GetOrCreate(string name, out bool created)
{
lock (Sync)
{
if (_rooms.TryGetValue(name, out var r)) { created = false; return r; }
r = new Room(name); _rooms[name] = r; created = true; return r;
}
}
public static void Remove(string name) { lock (Sync) _rooms.Remove(name); }
public static List<Room> All() { lock (Sync) return _rooms.Values.ToList(); }
public static int Count { get { lock (Sync) return _rooms.Count; } }
}
+70
View File
@@ -0,0 +1,70 @@
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
namespace CampusNet.Services;
/// <summary>
/// Two tokens live here. (1) The Campus server's photonAuthToken - an HS256 JWT (sub = account id,
/// aud = photon room id) the client presents as custom-auth data on the name server; validated with the
/// shared key. (2) The "secret" this server mints for the master/game hops (Photon hands the client an
/// opaque secret after the first Authenticate and the client presents it on the next server).
/// </summary>
public static class Tokens
{
public static string Key = Environment.GetEnvironmentVariable("CAMPUSNET_JWT_KEY")
?? Environment.GetEnvironmentVariable("CAMPUS_KEY")
?? "fI0wlalapwWIAKW0PJFOlwaalwWOFjNWmnemNWIwal";
private static byte[] Hmac(string data) => HMACSHA256.HashData(Encoding.UTF8.GetBytes(Key), Encoding.UTF8.GetBytes(data));
private static string B64Url(byte[] b) => Convert.ToBase64String(b).TrimEnd('=').Replace('+', '-').Replace('/', '_');
private static byte[] FromB64Url(string s)
{
s = s.Replace('-', '+').Replace('_', '/');
while (s.Length % 4 != 0) s += "=";
return Convert.FromBase64String(s);
}
/// <summary>Validate the Campus JWT; returns (accountId, audience/room) or null.</summary>
public static (string userId, string? aud)? ValidateCampusJwt(string? jwt)
{
if (string.IsNullOrEmpty(jwt)) return null;
var parts = jwt.Split('.');
if (parts.Length != 3) return null;
try
{
var expected = B64Url(Hmac(parts[0] + "." + parts[1]));
if (!CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(expected), Encoding.ASCII.GetBytes(parts[2]))) return null;
using var doc = JsonDocument.Parse(FromB64Url(parts[1]));
var root = doc.RootElement;
string? sub = root.TryGetProperty("sub", out var s) ? s.ToString() : null;
string? aud = root.TryGetProperty("aud", out var a) ? a.ToString() : null;
return sub == null ? null : (sub, aud);
}
catch { return null; }
}
/// <summary>Mint the master/game "secret": userId|nick|expiry, HMAC-signed.</summary>
public static string MintSecret(string userId, string nick)
{
long exp = DateTimeOffset.UtcNow.AddHours(12).ToUnixTimeSeconds();
string body = $"{userId}|{nick}|{exp}";
return B64Url(Encoding.UTF8.GetBytes(body)) + "." + B64Url(Hmac(body));
}
public static (string userId, string nick)? ValidateSecret(string? secret)
{
if (string.IsNullOrEmpty(secret)) return null;
var i = secret.IndexOf('.');
if (i <= 0) return null;
try
{
string body = Encoding.UTF8.GetString(FromB64Url(secret[..i]));
if (B64Url(Hmac(body)) != secret[(i + 1)..]) return null;
var f = body.Split('|');
if (f.Length != 3 || !long.TryParse(f[2], out var exp) || exp < DateTimeOffset.UtcNow.ToUnixTimeSeconds()) return null;
return (f[0], f[1]);
}
catch { return null; }
}
}