Repository navigation
Expand file tree
/
Copy pathPhotonServer.cs
More file actions
1382 lines (1254 loc) · 65.3 KB
/
Copy pathPhotonServer.cs
File metadata and controls
1382 lines (1254 loc) · 65.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace PhotonServer
{
// Per-connected-peer reliability + identity state. Implements IPlayer so a
// peer that has not yet entered a room (e.g. during the RoomCreating hook)
// can still be surfaced to plugins as the acting player.
public sealed class Peer : Api.IPlayer
{
public IPEndPoint EndPoint;
public UdpClient Socket; // socket this peer is connected on
public ushort PeerId;
public int Challenge;
// Outgoing reliable sequence numbers, per channel.
private readonly Dictionary<byte, int> _outSeq = new();
public int NextOutSeq(byte channel)
{
_outSeq.TryGetValue(channel, out int cur);
cur++;
_outSeq[channel] = cur;
return cur;
}
public bool InitDone;
public bool Authenticated;
// Serialization protocol: detected from the first parameter-bearing message.
public bool V18;
public bool ProtocolKnown;
public readonly DiffieHellman Dh = new();
// Master vs game-server role for this connection. A fresh connection is a
// "master" session; after a create/join redirect the client reconnects and
// authenticates with the issued token, which flips it into game mode.
public string? SessionToken;
public bool GameMode;
public string? PendingRoom;
public bool PendingCreate;
public long LastRecvMs; // for idle-timeout sweeps
// Room membership.
public Room? Room;
public int ActorNr;
public string? UserId;
public readonly Dictionary<object, object?> PlayerProperties = new();
// Inbound fragment reassembly, keyed by the fragment start sequence.
public sealed class FragmentAssembly
{
public byte[] Buffer = Array.Empty<byte>();
public int Total;
public int Count;
public int Received;
public byte Channel;
}
public readonly Dictionary<int, FragmentAssembly> Fragments = new();
// Inbound reliable commands are delivered at-least-once (client retransmits
// until ACKed). Track processed (channel, seq) so each is handled exactly once.
private readonly HashSet<long> _processedReliable = new();
public bool MarkProcessed(byte channel, int seq)
{
long key = ((long)channel << 32) | (uint)seq;
return _processedReliable.Add(key); // false if already present
}
// Outbound reliable commands awaiting ACK, keyed by (channel, seq).
public sealed class Unacked
{
public byte[] CommandBytes = null!;
public long LastSentMs;
public int Retries;
}
public readonly Dictionary<long, Unacked> UnackedCommands = new();
public void OnAckReceived(byte channel, int seq)
{
long key = ((long)channel << 32) | (uint)seq;
UnackedCommands.Remove(key);
}
public Peer(IPEndPoint ep, UdpClient socket, ushort id, int challenge)
{
EndPoint = ep; Socket = socket; PeerId = id; Challenge = challenge;
}
// ── IPlayer (plugin-facing read-only view of the acting connection) ──
int Api.IPlayer.ActorNr => ActorNr;
string? Api.IPlayer.UserId => UserId;
bool Api.IPlayer.IsInactive => false;
string? Api.IPlayer.NickName => PlayerProperties.TryGetValue((byte)255, out var n) ? n as string : null;
string? Api.IPlayer.Address => EndPoint?.ToString();
bool Api.IPlayer.IsV18 => V18;
System.Collections.Generic.IReadOnlyDictionary<object, object?> Api.IPlayer.Properties => PlayerProperties;
}
public sealed partial class PhotonServer
{
private readonly ServerConfig _config;
private readonly int[] _ports;
private readonly List<UdpClient> _sockets = new();
private readonly Stopwatch _clock = Stopwatch.StartNew();
private readonly Dictionary<IPEndPoint, Peer> _peers = new();
private readonly Dictionary<string, Room> _rooms = new(StringComparer.Ordinal);
private readonly Dictionary<string, Session> _sessions = new(StringComparer.Ordinal);
private readonly object _sync = new();
private ushort _nextPeerId = 0xC300;
// Address advertised to clients as the "game server" for create/join
// redirects. Same host as the master since we run combined on one port.
private readonly string _publicAddress;
// A session survives the master→game reconnect, carrying the pending room.
private sealed class Session
{
public string? PendingRoom;
public bool PendingCreate;
public long CreatedMs;
public string? UserId;
}
// Remove a peer's session unless a redirect is still pending on the master
// connection (the client is about to reconnect with this token).
private void CleanupSession(Peer peer)
{
if (peer.SessionToken == null) return;
if (!peer.GameMode &&
_sessions.TryGetValue(peer.SessionToken, out var s) && s.PendingRoom != null)
return; // keep alive for the imminent game-server reconnect
_sessions.Remove(peer.SessionToken);
}
// Retransmission tuning.
private const int RetransmitMs = 200;
private const int MaxRetries = 12;
// The server always sends packets with peer id 0x0000 in the header
// (observed on the wire).
private const ushort ServerHeaderPeerId = 0x0000;
public PhotonServer(ServerConfig config)
{
_config = config;
_hooks = new Api.HookRegistry((ctx, ex) => Log($"[Plugins] {ctx} threw: {ex.Message}"));
_ports = config.Ports;
// The game-server port the client redirects to is fixed by the SDK's
// ServerPortOverrides (UDP GameServer = 27002), so advertise that.
int gamePort = _ports.Contains(27002) ? 27002 : _ports[0];
_publicAddress = $"{config.PublicHost}:{gamePort}";
foreach (int p in _ports)
_sockets.Add(new UdpClient(new IPEndPoint(IPAddress.Any, p)));
}
public void Run()
{
Log($"[Server] Photon UDP server listening on ports: {string.Join(", ", _ports)}");
Log($"[Server] game-server redirect address (config PublicHost): {_publicAddress}");
if (_config.PublicHost is "127.0.0.1" or "localhost" or "0.0.0.0")
Log("[Server] NOTE: PublicHost is loopback — set it to your public IP/DNS in " +
"config.json so remote clients can reach the game server after redirect.");
StartRetransmitThread();
LoadPlugins();
StartConsoleThread();
// One receive loop per bound socket; all funnel into the same handler
// under the global lock.
var threads = new List<Thread>();
foreach (var sock in _sockets)
{
var s = sock;
var t = new Thread(() => ReceiveLoop(s)) { IsBackground = true };
t.Start();
threads.Add(t);
}
foreach (var t in threads) t.Join();
}
private void ReceiveLoop(UdpClient sock)
{
var remote = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
byte[] data;
IPEndPoint from;
try
{
data = sock.Receive(ref remote);
from = new IPEndPoint(remote.Address, remote.Port);
}
catch (SocketException) { continue; }
try { lock (_sync) HandleDatagram(data, from, sock); }
catch (Exception e) { Log($"[Server] handler error: {e}"); }
}
}
private uint Now => (uint)_clock.ElapsedMilliseconds;
private long NowMs => _clock.ElapsedMilliseconds;
// ── Outbound reliable retransmission ─────────────────────────────────
private void StartRetransmitThread()
{
var t = new Thread(() =>
{
while (true)
{
Thread.Sleep(50);
lock (_sync)
{
long now = NowMs;
// Expire redirect sessions the client never came back for.
foreach (var kv in _sessions.Where(s => s.Value.PendingRoom != null &&
now - s.Value.CreatedMs > 30000).ToList())
_sessions.Remove(kv.Key);
SweepInactiveActors(now);
foreach (var peer in _peers.Values.ToList())
{
// Idle-timeout sweep: drop peers that have gone silent
// (crashed clients that never sent a Disconnect).
if (_config.PeerTimeoutMs > 0 && now - peer.LastRecvMs > _config.PeerTimeoutMs)
{
Log($"[{peer.EndPoint}] idle timeout ({now - peer.LastRecvMs}ms) — dropping");
LeaveRoom(peer, willComeBack: true);
_peers.Remove(peer.EndPoint);
CleanupSession(peer);
_hooks.RaisePlayerDisconnected(peer);
continue;
}
foreach (var kv in peer.UnackedCommands.ToList())
{
var u = kv.Value;
if (now - u.LastSentMs < RetransmitMs) continue;
if (u.Retries >= MaxRetries)
{
peer.UnackedCommands.Remove(kv.Key);
continue;
}
u.Retries++;
u.LastSentMs = now;
SendPacket(peer, new[] { u.CommandBytes });
}
}
}
}
}) { IsBackground = true, Name = "Retransmit" };
t.Start();
}
// ── Datagram dispatch ────────────────────────────────────────────────
private void HandleDatagram(byte[] data, IPEndPoint from, UdpClient sock)
{
// 13-byte all-0x7D ping/echo → reflect verbatim (region latency probe).
if (IsPingEcho(data))
{
sock.Send(data, data.Length, from);
return;
}
var pkt = Wire.Parse(data, data.Length);
if (pkt == null) { Log($"[{from}] unparseable ({data.Length}b): {Hex(data, data.Length)}"); return; }
_peers.TryGetValue(from, out Peer? peer);
if (peer != null) peer.LastRecvMs = NowMs;
foreach (var cmd in pkt.Commands)
{
// Every reliable command (except Connect, handled specially)
// must be acknowledged, including control commands like type 12.
if (peer != null && cmd.IsReliable && cmd.Type != CommandType.Connect)
AckIfReliable(peer, pkt, cmd);
switch (cmd.Type)
{
case CommandType.Connect:
peer = HandleConnect(pkt, cmd, from, sock);
break;
case CommandType.Ack:
if (peer != null && cmd.Payload.Length >= 4)
peer.OnAckReceived(cmd.Channel, Wire.ReadI32(cmd.Payload, 0));
break;
case CommandType.Disconnect:
Log($"[{from}] DISCONNECT");
if (peer != null)
{
// A clean disconnect may still leave an inactive actor
// if the room has a PlayerTtl (the client can rejoin).
LeaveRoom(peer, willComeBack: true);
_peers.Remove(from);
CleanupSession(peer);
_hooks.RaisePlayerDisconnected(peer);
}
break;
case CommandType.Ping:
break;
case CommandType.SendReliable:
case CommandType.SendUnreliable:
if (peer == null) { Log($"[{from}] data from unknown peer, ignoring"); break; }
// Skip already-processed reliable retransmits (already ACKed above).
if (cmd.IsReliable && !peer.MarkProcessed(cmd.Channel, cmd.ReliableSeq))
break;
HandleMessage(peer, cmd);
break;
case CommandType.SendFragment:
if (peer == null) break;
if (!peer.MarkProcessed(cmd.Channel, cmd.ReliableSeq)) break; // dup fragment
HandleFragment(peer, cmd);
break;
default:
LogV($"[{from}] control command {(byte)cmd.Type} ch{cmd.Channel} seq{cmd.ReliableSeq} (acked)");
break;
}
}
}
// ── Connection handshake ─────────────────────────────────────────────
private Peer HandleConnect(PhotonPacket pkt, PhotonCommand cmd, IPEndPoint from, UdpClient sock)
{
ushort assignedId = _nextPeerId++;
var peer = new Peer(from, sock, assignedId, pkt.Challenge) { LastRecvMs = NowMs };
_peers[from] = peer;
Log($"[{from}] CONNECT → assigned peerId=0x{assignedId:X4} challenge=0x{pkt.Challenge:X8}");
// Reply: ACK(the connect) + VERIFY_CONNECT(with assigned peer id).
var ack = BuildAck(cmd.Channel, cmd.ReliableSeq, pkt.Timestamp);
var verify = BuildVerifyConnect(peer, cmd);
SendPacket(peer, new[] { ack, verify });
return peer;
}
// ── Fragment reassembly ──────────────────────────────────────────────
private void HandleFragment(Peer peer, PhotonCommand cmd)
{
if (!peer.Fragments.TryGetValue(cmd.FragStartSeq, out var asm))
{
if (cmd.FragTotalLength < 0 || cmd.FragTotalLength > 8 * 1024 * 1024)
{
Log($"[{peer.EndPoint}] fragment with bad total length {cmd.FragTotalLength}");
return;
}
asm = new Peer.FragmentAssembly
{
Buffer = new byte[cmd.FragTotalLength],
Total = cmd.FragTotalLength,
Count = cmd.FragCount,
Channel = cmd.Channel,
};
peer.Fragments[cmd.FragStartSeq] = asm;
}
if (cmd.FragOffset >= 0 && cmd.FragOffset + cmd.Payload.Length <= asm.Buffer.Length)
{
Array.Copy(cmd.Payload, 0, asm.Buffer, cmd.FragOffset, cmd.Payload.Length);
asm.Received++;
}
if (asm.Received >= asm.Count)
{
peer.Fragments.Remove(cmd.FragStartSeq);
LogV($"[{peer.EndPoint}] fragment complete: {asm.Total}b in {asm.Count} parts");
var synthetic = new PhotonCommand
{
Type = CommandType.SendReliable,
Channel = asm.Channel,
Payload = asm.Buffer,
ReliableSeq = cmd.FragStartSeq,
};
HandleMessage(peer, synthetic);
}
}
// ── Message (F3) handling ────────────────────────────────────────────
private void HandleMessage(Peer peer, PhotonCommand cmd)
{
byte[] payload = cmd.Payload;
if (payload.Length < 2 || payload[0] != Wire.Magic)
{
Log($"[{peer.EndPoint}] non-F3 data on ch{cmd.Channel}: {Hex(payload, payload.Length)}");
return;
}
byte rawType = payload[1];
var mtype = (MsgType)(rawType & 0x7F);
bool enc = (rawType & 0x80) != 0;
// Init (F3 00) → InitResponse (F3 01 00).
if (mtype == MsgType.Init)
{
Log($"[{peer.EndPoint}] INIT ({payload.Length}b) appId+version");
peer.InitDone = true;
var initResp = new byte[] { Wire.Magic, (byte)MsgType.InitResponse, 0x00 };
SendReliableMessage(peer, cmd.Channel, initResp);
return;
}
if (enc)
{
var key = peer.Dh.SharedKey;
if (key == null) { Log($"[{peer.EndPoint}] ENC but no key yet"); return; }
byte[] plain;
try { plain = PhotonCrypto.Decrypt(Slice(payload, 2), key); }
catch (Exception e) { Log($"[{peer.EndPoint}] DECRYPT FAILED: {e.Message}"); return; }
// Reconstruct a plaintext F3 message: magic + (type without enc bit) + body.
var full = new byte[2 + plain.Length];
full[0] = Wire.Magic;
full[1] = (byte)(rawType & 0x7F);
Array.Copy(plain, 0, full, 2, plain.Length);
try
{
var dmsg = ParseMessageDetect(peer, full);
LogV($"[{peer.EndPoint}] IN* {dmsg} (decrypted {plain.Length}b)");
if (dmsg != null) DispatchMessage(peer, cmd, dmsg);
}
catch (Exception e) { LogParseFail(peer, full, e); }
return;
}
try
{
var msg = ParseMessageDetect(peer, payload);
if (msg == null) { Log($"[{peer.EndPoint}] unparsed msg: {Hex(payload, payload.Length)}"); return; }
LogV($"[{peer.EndPoint}] IN {msg}");
DispatchMessage(peer, cmd, msg);
}
catch (Exception e) { LogParseFail(peer, payload, e); }
}
// Log the exact bytes when a message fails to parse/dispatch, so any
// remaining serialization gap is immediately diagnosable.
private void LogParseFail(Peer peer, byte[] payload, Exception e)
{
string proto = peer.ProtocolKnown ? (peer.V18 ? "V18" : "V16") : "?";
Log($"[{peer.EndPoint}] PARSE FAIL ({proto}) type=0x{(payload.Length > 1 ? payload[1] : 0):X2} " +
$"{e.Message} ({payload.Length}b) hex={Hex(payload, Math.Min(payload.Length, 160))}");
}
// Parse an F3 message, auto-detecting GpBinaryV16 vs V18 from the first
// parameter-bearing message (the game uses V18, the probe uses V16).
private PhotonMessage? ParseMessageDetect(Peer peer, byte[] payload)
{
if (peer.ProtocolKnown)
return peer.V18 ? GpBinaryV18.ParseMessage(payload, out _) : GpBinary.ParseMessage(payload);
// Prefer V18 only if it consumes the payload exactly; else fall back
// to V16. Encrypted messages carry no body to detect from — skip.
byte raw = payload.Length >= 2 ? payload[1] : (byte)0;
if ((raw & 0x80) == 0 && (raw & 0x7F) != (byte)MsgType.Init)
{
try
{
var m18 = GpBinaryV18.ParseMessage(payload, out int consumed);
if (m18 != null && consumed == payload.Length && m18.Parameters.Count > 0)
{
peer.V18 = true; peer.ProtocolKnown = true;
Log($"[{peer.EndPoint}] serialization protocol = GpBinaryV18");
return m18;
}
}
catch { /* not V18 */ }
}
var m16 = GpBinary.ParseMessage(payload);
if (m16 != null && m16.Parameters.Count > 0)
{
peer.V18 = false; peer.ProtocolKnown = true;
Log($"[{peer.EndPoint}] serialization protocol = GpBinaryV16");
}
return m16;
}
// Protocol-aware message builders (route to the peer's serializer).
private static byte[] BuildOpResp(Peer p, byte op, short ret, object? dbg, Dictionary<byte, object?>? pr)
=> p.V18 ? GpBinaryV18.BuildOpResponse(op, ret, dbg, pr) : GpBinary.BuildOpResponse(op, ret, dbg, pr);
private static byte[] BuildEvt(Peer p, byte ev, Dictionary<byte, object?>? pr)
=> p.V18 ? GpBinaryV18.BuildEvent(ev, pr) : GpBinary.BuildEvent(ev, pr);
private static byte[] BuildIntResp(Peer p, byte op, short ret, Dictionary<byte, object?>? pr)
=> p.V18 ? GpBinaryV18.BuildInternalOpResponse(op, ret, pr) : GpBinary.BuildInternalOpResponse(op, ret, pr);
private void DispatchMessage(Peer peer, PhotonCommand cmd, PhotonMessage msg)
{
switch (msg.Type)
{
case MsgType.InternalOpRequest:
HandleInternalOp(peer, cmd, msg);
break;
case MsgType.OperationRequest:
HandleOperation(peer, cmd, msg);
break;
default:
Log($"[{peer.EndPoint}] (no handler for {msg.Type})");
break;
}
}
private static byte[] Slice(byte[] b, int start)
{
var r = new byte[b.Length - start];
Array.Copy(b, start, r, 0, r.Length);
return r;
}
private void HandleInternalOp(Peer peer, PhotonCommand cmd, PhotonMessage msg)
{
if (msg.Code == 0) // ExchangeKeysForEncryption (Diffie-Hellman)
{
if (msg.Parameters.TryGetValue(1, out object? kv) && kv is byte[] clientPub && clientPub.Length == 96)
{
peer.Dh.DeriveShared(clientPub);
Log($"[{peer.EndPoint}] DH exchange — shared key derived ({peer.Dh.SharedKey!.Length}b)");
var resp = BuildIntResp(peer, 0, 0,
new Dictionary<byte, object?> { [1] = peer.Dh.PublicKey });
SendReliableMessage(peer, cmd.Channel, resp);
}
else
{
Log($"[{peer.EndPoint}] DH exchange — missing/short client key");
}
return;
}
Log($"[{peer.EndPoint}] INTERNAL op={msg.Code} — no handler");
}
private void HandleOperation(Peer peer, PhotonCommand cmd, PhotonMessage msg)
{
switch (msg.Code)
{
case OpCode.Authenticate:
{
// Optional AppId / AppVersion gating (only present on the first,
// master-side auth; the game-server re-auth carries only a token).
if (_config.RequireAppId != null &&
msg.Parameters.TryGetValue(Param.AppId, out var aid) && aid is string aids &&
aids != _config.RequireAppId)
{
SendReliableMessage(peer, cmd.Channel,
BuildOpResp(peer, OpCode.Authenticate, 32755, "Invalid AppId", null));
Log($"[{peer.EndPoint}] AUTH rejected (AppId '{aids}')");
break;
}
if (_config.RequireAppVersion != null &&
msg.Parameters.TryGetValue(Param.AppVersion, out var av) && av is string avs &&
avs != _config.RequireAppVersion)
{
SendReliableMessage(peer, cmd.Channel,
BuildOpResp(peer, OpCode.Authenticate, 32755, "Invalid AppVersion", null));
Log($"[{peer.EndPoint}] AUTH rejected (AppVersion '{avs}')");
break;
}
// A client-supplied UserId (param 225) enables rejoin across
// reconnects; otherwise assign a stable one.
string? clientUserId = msg.Parameters.TryGetValue(Param.UserId, out var uid) && uid is string uids && uids.Length > 0
? uids : null;
// Plugin gate: blacklist / protocol-restriction mods can reject
// the connection here (IP, UserId and protocol are all known).
string? authAppId = msg.Parameters.TryGetValue(Param.AppId, out var aidv) && aidv is string aidvs ? aidvs : null;
string? authAppVer = msg.Parameters.TryGetValue(Param.AppVersion, out var avv) && avv is string avvs ? avvs : null;
var authCtx = new Api.AuthContext(peer.EndPoint.ToString(), clientUserId, peer.V18, authAppId, authAppVer);
_hooks.RaisePlayerAuthenticating(authCtx);
if (authCtx.Cancel)
{
SendReliableMessage(peer, cmd.Channel, BuildOpResp(peer, OpCode.Authenticate,
authCtx.ReturnCode, authCtx.Message ?? "Authentication rejected", null));
Log($"[{peer.EndPoint}] AUTH rejected by plugin ({authCtx.Message})");
break;
}
peer.Authenticated = true;
// A token in [221] means the client is returning after a
// create/join redirect — resume that session in game mode.
string? inToken = msg.Parameters.TryGetValue(Param.Secret, out var sv) && sv is string ss ? ss : null;
if (inToken != null && _sessions.TryGetValue(inToken, out var sess) && sess.PendingRoom != null)
{
peer.SessionToken = inToken;
peer.GameMode = true;
peer.PendingRoom = sess.PendingRoom;
peer.PendingCreate = sess.PendingCreate;
peer.UserId = clientUserId ?? sess.UserId ?? Guid.NewGuid().ToString();
Log($"[{peer.EndPoint}] AUTH ok (GAME mode, pending room '{sess.PendingRoom}', user {peer.UserId})");
}
else
{
peer.UserId = clientUserId ?? Guid.NewGuid().ToString();
peer.SessionToken = Guid.NewGuid().ToString("N");
_sessions[peer.SessionToken] = new Session { CreatedMs = NowMs, UserId = peer.UserId };
Log($"[{peer.EndPoint}] AUTH ok (MASTER mode, user {peer.UserId})");
}
var resp = BuildOpResp(peer, OpCode.Authenticate, 0, null,
new Dictionary<byte, object?>
{
[Param.Secret] = peer.SessionToken,
[Param.UserId] = peer.UserId,
});
SendReliableMessage(peer, cmd.Channel, resp);
break;
}
case OpCode.JoinLobby:
{
var resp = BuildOpResp(peer, OpCode.JoinLobby, 0, null, null);
SendReliableMessage(peer, cmd.Channel, resp);
SendReliableMessage(peer, cmd.Channel, BuildGameListEvent(peer));
Log($"[{peer.EndPoint}] JOIN LOBBY ok ({_rooms.Count} room(s) listed)");
_hooks.RaiseLobbyJoined(peer);
break;
}
case OpCode.CreateGame: HandleCreateGame(peer, cmd, msg); break;
case OpCode.JoinGame: HandleJoinGame(peer, cmd, msg, createIfAbsent: false); break;
case OpCode.JoinRandomGame: HandleJoinRandom(peer, cmd, msg); break;
case OpCode.RaiseEvent: HandleRaiseEvent(peer, cmd, msg); break;
case OpCode.SetProperties: HandleSetProperties(peer, cmd, msg); break;
case OpCode.Leave: HandleLeaveOp(peer, cmd, msg); break;
case OpCode.ChangeGroups:
// Interest groups — accept silently.
break;
default:
Log($"[{peer.EndPoint}] op {msg.Code} — no handler yet");
break;
}
}
// ── Room operations ──────────────────────────────────────────────────
// On the master, create/join don't enter a room — they hand the client a
// game-server address (ourselves) plus its session token, and the client
// reconnects there before actually entering.
private bool RedirectIfMaster(Peer peer, PhotonCommand cmd, byte opCode, string roomName, bool isCreate)
{
if (peer.GameMode) return false;
if (peer.SessionToken != null && _sessions.TryGetValue(peer.SessionToken, out var sess))
{
sess.PendingRoom = roomName;
sess.PendingCreate = isCreate;
}
var resp = BuildOpResp(peer, opCode, 0, null, new Dictionary<byte, object?>
{
[Param.Address] = _publicAddress,
[Param.Secret] = peer.SessionToken,
[Param.GameId] = roomName,
});
SendReliableMessage(peer, cmd.Channel, resp);
Log($"[{peer.EndPoint}] {(isCreate ? "CREATE" : "JOIN")} '{roomName}' → redirect to {_publicAddress}");
return true;
}
private void HandleCreateGame(Peer peer, PhotonCommand cmd, PhotonMessage msg)
{
string name = msg.Parameters.TryGetValue(Param.GameId, out var g) && g is string s && s.Length > 0
? s : (peer.PendingRoom ?? Guid.NewGuid().ToString("N")[..8]);
if (RedirectIfMaster(peer, cmd, OpCode.CreateGame, name, isCreate: true)) return;
var room = new Room(name);
ApplyRoomOptions(room, msg);
// Plugin gate: naming-convention / property mods may reject the create
// (with a client-facing error code) or rewrite the name / limits / props.
var createCtx = new Api.RoomCreateContext(peer, name, room.MaxPlayers, room.IsOpen, room.IsVisible, room.Properties);
_hooks.RaiseRoomCreating(createCtx);
if (createCtx.Cancel)
{
SendReliableMessage(peer, cmd.Channel, BuildOpResp(peer, OpCode.CreateGame,
createCtx.ReturnCode, createCtx.Message ?? "Room rejected", null));
Log($"[{peer.EndPoint}] CREATE '{name}' rejected by plugin ({createCtx.Message})");
return;
}
// Apply any rewrites, keeping the well-known props in sync so the
// enter-room response and game list reflect the final values.
name = createCtx.Name;
room.Name = name;
room.MaxPlayers = createCtx.MaxPlayers;
room.IsOpen = createCtx.IsOpen;
room.IsVisible = createCtx.IsVisible;
room.Properties[(byte)255] = room.MaxPlayers;
room.Properties[(byte)253] = room.IsOpen;
room.Properties[(byte)254] = room.IsVisible;
if (_rooms.ContainsKey(name))
{
// Room exists → error (game already exists = 32766).
SendReliableMessage(peer, cmd.Channel,
BuildOpResp(peer, OpCode.CreateGame, 32766, "Game already exists", null));
Log($"[{peer.EndPoint}] CREATE '{name}' FAILED (exists)");
return;
}
if (_config.MaxRooms > 0 && _rooms.Count >= _config.MaxRooms)
{
SendReliableMessage(peer, cmd.Channel,
BuildOpResp(peer, OpCode.CreateGame, 32760, "Server room limit reached", null));
Log($"[{peer.EndPoint}] CREATE '{name}' FAILED (server at {_config.MaxRooms} rooms)");
return;
}
// Reject creation if the requested MaxPlayers exceeds the server's
// per-room cap.
if (_config.MaxPeersPerRoom > 0 && room.MaxPlayers > _config.MaxPeersPerRoom)
{
SendReliableMessage(peer, cmd.Channel, BuildOpResp(peer, OpCode.CreateGame, 32762,
$"MaxPlayers {room.MaxPlayers} exceeds server limit {_config.MaxPeersPerRoom}", null));
Log($"[{peer.EndPoint}] CREATE '{name}' FAILED (maxPlayers {room.MaxPlayers} > cap {_config.MaxPeersPerRoom})");
return;
}
_rooms[name] = room;
EnterRoom(peer, room, msg, OpCode.CreateGame);
_hooks.RaiseRoomCreated(room);
Log($"[{peer.EndPoint}] CREATE '{name}' ok (actor {peer.ActorNr}, master)");
}
private void HandleJoinGame(Peer peer, PhotonCommand cmd, PhotonMessage msg, bool createIfAbsent)
{
string name = msg.Parameters.TryGetValue(Param.GameId, out var g) && g is string s ? s : (peer.PendingRoom ?? "");
if (RedirectIfMaster(peer, cmd, OpCode.JoinGame, name, isCreate: false)) return;
// In game mode a create-turned-join (room already made by us) still enters.
if (peer.PendingCreate) createIfAbsent = true;
if (!_rooms.TryGetValue(name, out var room))
{
if (createIfAbsent)
{
room = new Room(name);
ApplyRoomOptions(room, msg);
_rooms[name] = room;
_hooks.RaiseRoomCreated(room);
}
else
{
// Game does not exist = 32758.
SendReliableMessage(peer, cmd.Channel,
BuildOpResp(peer, OpCode.JoinGame, 32758, "Game does not exist", null));
Log($"[{peer.EndPoint}] JOIN '{name}' FAILED (missing)");
return;
}
}
if (!room.IsOpen)
{
SendReliableMessage(peer, cmd.Channel,
BuildOpResp(peer, OpCode.JoinGame, 32764, "Game closed", null));
return;
}
// Plugin gate: a join can be rejected, or waved past the capacity limit
// (e.g. a whitelisted IP allowed into an otherwise-full room).
var joinCtx = new Api.JoinContext(peer, room);
_hooks.RaisePlayerJoining(joinCtx);
if (joinCtx.Cancel)
{
SendReliableMessage(peer, cmd.Channel, BuildOpResp(peer, OpCode.JoinGame,
joinCtx.ReturnCode, joinCtx.Message ?? "Join rejected", null));
Log($"[{peer.EndPoint}] JOIN '{name}' rejected by plugin ({joinCtx.Message})");
return;
}
if (!joinCtx.AllowOverCapacity && RoomIsFull(room))
{
SendReliableMessage(peer, cmd.Channel,
BuildOpResp(peer, OpCode.JoinGame, 32765, "Game full", null));
Log($"[{peer.EndPoint}] JOIN '{name}' FAILED (full)");
return;
}
EnterRoom(peer, room, msg, OpCode.JoinGame);
Log($"[{peer.EndPoint}] JOIN '{name}' ok (actor {peer.ActorNr})");
}
private void HandleJoinRandom(Peer peer, PhotonCommand cmd, PhotonMessage msg)
{
// Master picks a room and redirects; the client then joins it by name
// on the game server.
if (!peer.GameMode)
{
var pick = _rooms.Values.FirstOrDefault(r => r.IsOpen && r.IsVisible && !RoomIsFull(r));
if (pick == null)
{
SendReliableMessage(peer, cmd.Channel,
BuildOpResp(peer, OpCode.JoinRandomGame, 32760, "No match found", null));
return;
}
RedirectIfMaster(peer, cmd, OpCode.JoinRandomGame, pick.Name, isCreate: false);
return;
}
if (peer.PendingRoom != null && _rooms.TryGetValue(peer.PendingRoom, out var room))
{
EnterRoom(peer, room, msg, OpCode.JoinRandomGame);
Log($"[{peer.EndPoint}] JOIN RANDOM → '{room.Name}' (actor {peer.ActorNr})");
}
}
// Add the peer to a room and send the enter-room response + broadcast join.
private void EnterRoom(Peer peer, Room room, PhotonMessage msg, byte opCode)
{
// The joiner's own player properties come in param 249.
if (msg.Parameters.TryGetValue(Param.PlayerProperties, out var pp) &&
pp is Dictionary<object, object?> props)
{
peer.PlayerProperties.Clear();
foreach (var kv in props) peer.PlayerProperties[kv.Key] = kv.Value;
}
// Rejoin: an inactive actor with the same UserId reclaims its slot and
// actor number; otherwise a new actor is allocated.
var existing = room.FindInactiveByUserId(peer.UserId);
int actorNr;
bool rejoin = existing != null;
if (existing != null)
{
existing.IsInactive = false;
existing.Peer = peer;
actorNr = existing.ActorNr;
room.RecomputeMaster();
}
else
{
actorNr = room.AddMember(peer, peer.UserId);
}
peer.Room = room;
peer.ActorNr = actorNr;
var self = room.Members[actorNr];
self.Properties.Clear();
foreach (var kv in peer.PlayerProperties) self.Properties[kv.Key] = kv.Value;
// Build enter-room response: your actor number, all players' props, room props.
var allPlayers = new Dictionary<object, object?>();
foreach (var m in room.Members.Values)
{
var pd = new Dictionary<object, object?>();
foreach (var kv in m.Properties) pd[kv.Key] = kv.Value;
allPlayers[m.ActorNr] = pd;
}
// Room flag bits (param 191). Bit 2 is the "room entered" gate the
// client checks before firing OnJoinedRoom/OnCreatedRoom; echo the
// client's requested flags with that bit set.
byte flags = msg.Parameters.TryGetValue(Param.RoomFlags, out var fv)
? Convert.ToByte(fv) : (byte)0;
flags |= 0x04;
// Game (room) properties, plus the well-known MasterClientId key (248):
// the client reads room-property 248 into Room.MasterClientId
// (RoomInfo.InternalCacheProperties) and IsMasterClient is
// MasterClientId == LocalActorNr. Without it the first host has
// MasterClientId=0, is NOT recognised as master, and the game's
// master-only lobby setup never runs (character never spawns) until a
// later handoff sets it via the Leave event's param 203.
var gameProps = ToDict(room.Properties);
gameProps[(byte)Param.MasterClientKey] = room.MasterClientActor;
var respParams = new Dictionary<byte, object?>
{
[Param.ActorNr] = actorNr,
[Param.ActorList] = room.ActorNumbers,
[Param.PlayerProperties] = allPlayers,
[Param.GameProperties] = gameProps,
[Param.RoomFlags] = (int)flags,
};
SendReliableMessage(peer, 0, BuildOpResp(peer, opCode, 0, null, respParams));
// Replay cached events (buffered Instantiates etc.) so the joiner
// reconstructs existing room state.
foreach (var ce in room.EventCache)
{
SendReliableMessage(peer, 0, BuildEvt(peer, ce.Code, new Dictionary<byte, object?>
{
[Param.Data] = ce.Data,
[Param.ActorNr] = ce.Sender,
}));
}
if (room.EventCache.Count > 0)
LogV($"[{peer.EndPoint}] replayed {room.EventCache.Count} cached event(s)");
// Notify existing members that an actor joined/rejoined (Event 255).
BroadcastEvent(room, EvCode.Join, new Dictionary<byte, object?>
{
[Param.ActorNr] = actorNr,
[Param.ActorList] = room.ActorNumbers,
[Param.PlayerProperties] = ToDict(peer.PlayerProperties),
}, exceptActor: actorNr);
if (rejoin) Log($"[{peer.EndPoint}] REJOINED as actor {actorNr}");
_hooks.RaisePlayerJoined(room, self);
}
private void HandleLeaveOp(Peer peer, PhotonCommand cmd, PhotonMessage msg)
{
SendReliableMessage(peer, cmd.Channel, BuildOpResp(peer, OpCode.Leave, 0, null, null));
// The client can request to become inactive (willComeBack) via [233].
bool wantsInactive = msg.Parameters.TryGetValue(Param.IsInactive, out var iv) && iv is bool b && b;
LeaveRoom(peer, wantsInactive);
}
// Remove a peer from its room. When willComeBack is true and the room has a
// PlayerTtl, the actor is kept as inactive so it can rejoin; otherwise it is
// removed and its non-global cached events are pruned.
private void LeaveRoom(Peer peer, bool willComeBack)
{
var room = peer.Room;
if (room == null) return;
int actorNr = peer.ActorNr;
int oldMaster = room.MasterClientActor;
bool goInactive = willComeBack && room.PlayerTtl != 0 && room.Members.ContainsKey(actorNr);
if (goInactive)
{
var m = room.Members[actorNr];
m.IsInactive = true;
m.DeactivatedMs = NowMs;
m.Peer = null!;
room.RecomputeMaster();
}
else
{
room.RemoveMember(actorNr);
if (room.CleanupCacheOnLeave)
room.EventCache.RemoveAll(ce => ce.Sender == actorNr && !ce.Global);
}
_hooks.RaisePlayerLeft(room, peer);
peer.Room = null;
peer.ActorNr = 0;
var leaveParams = new Dictionary<byte, object?>
{
[Param.ActorNr] = actorNr,
[Param.ActorList] = room.ActorNumbers,
[Param.IsInactive] = goInactive,
};
// Only advertise a new master when it actually changed: the client fires
// OnMasterClientSwitched unconditionally whenever this param is present
// (it does not compare against the current master), so always sending it
// would spuriously re-fire the callback on every player's departure.
if (room.MasterClientActor != oldMaster && room.MasterClientActor != 0)
leaveParams[Param.MasterClientId] = room.MasterClientActor;
BroadcastEvent(room, EvCode.Leave, leaveParams);
Log($"[{peer.EndPoint}] {(goInactive ? "INACTIVE in" : "LEFT")} room '{room.Name}' " +
$"(actor {actorNr}); {room.PlayerCount} member(s)");
if (room.PlayerCount == 0)
DestroyRoom(room, "empty");
}
// Remove inactive actors whose PlayerTtl has elapsed, broadcasting a final
// (permanent) Leave for each. PlayerTtl <= 0 means never expire.
private void SweepInactiveActors(long now)
{
foreach (var room in _rooms.Values.ToList())
{
if (room.PlayerTtl <= 0) continue;
var expired = room.Members.Values
.Where(m => m.IsInactive && now - m.DeactivatedMs > room.PlayerTtl)
.Select(m => m.ActorNr).ToList();
foreach (var actorNr in expired)
{
int oldMaster = room.MasterClientActor;
room.RemoveMember(actorNr);
if (room.CleanupCacheOnLeave)
room.EventCache.RemoveAll(ce => ce.Sender == actorNr && !ce.Global);
var leaveParams = new Dictionary<byte, object?>
{
[Param.ActorNr] = actorNr,
[Param.ActorList] = room.ActorNumbers,
[Param.IsInactive] = false,
};
// Only signal a master change when it actually changed (see LeaveRoom).
if (room.MasterClientActor != oldMaster && room.MasterClientActor != 0)
leaveParams[Param.MasterClientId] = room.MasterClientActor;
BroadcastEvent(room, EvCode.Leave, leaveParams);
Log($"[Server] inactive actor {actorNr} in '{room.Name}' TTL-expired → removed");
}
if (room.PlayerCount == 0)
DestroyRoom(room, "empty");
}
}
// Remove cached events matching a filter (used by RemoveFromRoomCache).
// Matches by event code, and if the filter is a hashtable, requires every
// filter key/value to be present in the cached event's data.
private static int RemoveMatchingCache(Room room, byte evCode, object? filter)
{
var filterDict = filter as Dictionary<object, object?>;
int before = room.EventCache.Count;
room.EventCache.RemoveAll(ce =>
{
if (ce.Code != evCode) return false;
if (filterDict == null || filterDict.Count == 0) return true;
if (ce.Data is not Dictionary<object, object?> cd) return false;