-
Notifications
You must be signed in to change notification settings - Fork 428
/
NetworkingManager.cs
1130 lines (1001 loc) · 53.8 KB
/
NetworkingManager.cs
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;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using MLAPI.Logging;
using UnityEngine.SceneManagement;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using MLAPI.Configuration;
using MLAPI.Security;
using MLAPI.Internal;
using MLAPI.Profiling;
using MLAPI.Serialization;
using MLAPI.Transports;
using BitStream = MLAPI.Serialization.BitStream;
using MLAPI.Connection;
using MLAPI.LagCompensation;
using MLAPI.Messaging;
using MLAPI.SceneManagement;
using MLAPI.Serialization.Pooled;
using MLAPI.Spawning;
namespace MLAPI
{
/// <summary>
/// The main component of the library
/// </summary>
[AddComponentMenu("MLAPI/NetworkingManager", -100)]
public class NetworkingManager : MonoBehaviour
{
/// <summary>
/// A syncronized time, represents the time in seconds since the server application started. Is replicated across all clients
/// </summary>
public float NetworkTime { get; internal set; }
/// <summary>
/// Gets or sets if the NetworkingManager should be marked as DontDestroyOnLoad
/// </summary>
[HideInInspector]
public bool DontDestroy = true;
/// <summary>
/// Gets or sets if the application should be set to run in background
/// </summary>
[HideInInspector]
public bool RunInBackground = true;
/// <summary>
/// The log level to use
/// </summary>
[HideInInspector]
public LogLevel LogLevel = LogLevel.Normal;
/// <summary>
/// The singleton instance of the NetworkingManager
/// </summary>
[Obsolete("Use Singleton instead", false)]
public static NetworkingManager singleton => Singleton;
/// <summary>
/// The singleton instance of the NetworkingManager
/// </summary>
public static NetworkingManager Singleton { get; private set; }
/// <summary>
/// Gets the networkId of the server
/// </summary>
public ulong ServerClientId => NetworkConfig.NetworkTransport != null ? NetworkConfig.NetworkTransport.ServerClientId : throw new NullReferenceException("The transport in the active NetworkConfig is null");
/// <summary>
/// The clientId the server calls the local client by, only valid for clients
/// </summary>
public ulong LocalClientId
{
get
{
if (IsServer) return NetworkConfig.NetworkTransport.ServerClientId;
else return localClientId;
}
internal set
{
localClientId = value;
}
}
private ulong localClientId;
/// <summary>
/// Gets a dictionary of connected clients and their clientId keys
/// </summary>
public readonly Dictionary<ulong, NetworkedClient> ConnectedClients = new Dictionary<ulong, NetworkedClient>();
/// <summary>
/// Gets a list of connected clients
/// </summary>
public readonly List<NetworkedClient> ConnectedClientsList = new List<NetworkedClient>();
/// <summary>
/// Gets a dictionary of the clients that have been accepted by the transport but are still pending by the MLAPI.
/// </summary>
public readonly Dictionary<ulong, PendingClient> PendingClients = new Dictionary<ulong, PendingClient>();
/// <summary>
/// Gets wheter or not a server is running
/// </summary>
[Obsolete("Use IsServer instead", false)]
public bool isServer => IsServer;
/// <summary>
/// Gets wheter or not a server is running
/// </summary>
public bool IsServer { get; internal set; }
/// <summary>
/// Gets wheter or not a client is running
/// </summary>
[Obsolete("Use IsClient instead", false)]
public bool isClient => IsClient;
/// <summary>
/// Gets wheter or not a client is running
/// </summary>
public bool IsClient { get; internal set; }
/// <summary>
/// Gets if we are running as host
/// </summary>
[Obsolete("Use IsHost instead", false)]
public bool isHost => IsHost;
/// <summary>
/// Gets if we are running as host
/// </summary>
public bool IsHost => IsServer && IsClient;
/// <summary>
/// Gets wheter or not we are listening for connections
/// </summary>
[Obsolete("Use IsListening instead", false)]
public bool isListening => IsListening;
/// <summary>
/// Gets wheter or not we are listening for connections
/// </summary>
public bool IsListening { get; internal set; }
/// <summary>
/// Gets if we are connected as a client
/// </summary>
[Obsolete("Use IsConnectedClient instead", false)]
public bool isConnectedClients => IsConnectedClient;
/// <summary>
/// Gets if we are connected as a client
/// </summary>
public bool IsConnectedClient { get; internal set; }
/// <summary>
/// The callback to invoke once a client connects
/// </summary>
public Action<ulong> OnClientConnectedCallback = null;
/// <summary>
/// The callback to invoke when a client disconnects
/// </summary>
public Action<ulong> OnClientDisconnectCallback = null;
/// <summary>
/// The callback to invoke once the server is ready
/// </summary>
public Action OnServerStarted = null;
/// <summary>
/// Delegate type called when connection has been approved
/// </summary>
/// <param name="clientId">The clientId of the approved client</param>
/// <param name="prefabHash">The prefabHash to use for the client</param>
/// <param name="approved">Wheter or not the client was approved</param>
/// <param name="position">The position to spawn the client at</param>
/// <param name="rotation">The rotation to spawn the client with</param>
public delegate void ConnectionApprovedDelegate(ulong clientId, ulong? prefabHash, bool approved, Vector3? position, Quaternion? rotation);
/// <summary>
/// The callback to invoke during connection approval
/// </summary>
public Action<byte[], ulong, ConnectionApprovedDelegate> ConnectionApprovalCallback = null;
/// <summary>
/// The current NetworkingConfiguration
/// </summary>
[HideInInspector]
public NetworkConfig NetworkConfig;
/// <summary>
/// Delegate used for incoming custom messages
/// </summary>
/// <param name="clientId">The clientId that sent the message</param>
/// <param name="stream">The stream containing the message data</param>
public delegate void CustomMessageDelegete(ulong clientId, Stream stream);
/// <summary>
/// Event invoked when custom messages arrive
/// </summary>
public event CustomMessageDelegete OnIncomingCustomMessage;
/// <summary>
/// The current hostname we are connected to, used to validate certificate
/// </summary>
public string ConnectedHostname { get; private set; }
internal byte[] clientAesKey;
internal static event Action OnSingletonReady;
internal void InvokeOnIncomingCustomMessage(ulong clientId, Stream stream)
{
if (OnIncomingCustomMessage != null) OnIncomingCustomMessage(clientId, stream);
}
/// <summary>
/// Sends custom message to a list of clients
/// </summary>
/// <param name="clientIds">The clients to send to, sends to everyone if null</param>
/// <param name="stream">The message stream containing the data</param>
/// <param name="channel">The channel to send the data on</param>
/// <param name="security">The security settings to apply to the message</param>
public void SendCustomMessage(List<ulong> clientIds, BitStream stream, string channel = null, SecuritySendFlags security = SecuritySendFlags.None)
{
if (!IsServer)
{
if (LogHelper.CurrentLogLevel <= LogLevel.Error) LogHelper.LogWarning("Can not send custom message to multiple users as a client");
return;
}
if (clientIds == null)
{
for (int i = 0; i < ConnectedClientsList.Count; i++)
{
InternalMessageSender.Send(ConnectedClientsList[i].ClientId, MLAPIConstants.MLAPI_CUSTOM_MESSAGE, string.IsNullOrEmpty(channel) ? "MLAPI_DEFAULT_MESSAGE" : channel, stream, security, null);
}
}
else
{
for (int i = 0; i < clientIds.Count; i++)
{
InternalMessageSender.Send(clientIds[i], MLAPIConstants.MLAPI_CUSTOM_MESSAGE, string.IsNullOrEmpty(channel) ? "MLAPI_DEFAULT_MESSAGE" : channel, stream, security, null);
}
}
}
/// <summary>
/// Sends a custom message to a specific client
/// </summary>
/// <param name="clientId">The client to send the message to</param>
/// <param name="stream">The message stream containing the data</param>
/// <param name="channel">The channel tos end the data on</param>
/// <param name="security">The security settings to apply to the message</param>
public void SendCustomMessage(ulong clientId, BitStream stream, string channel = null, SecuritySendFlags security = SecuritySendFlags.None)
{
InternalMessageSender.Send(clientId, MLAPIConstants.MLAPI_CUSTOM_MESSAGE, string.IsNullOrEmpty(channel) ? "MLAPI_DEFAULT_MESSAGE" : channel, stream, security, null);
}
private void OnValidate()
{
if (NetworkConfig == null)
return; //May occur when the component is added
if (GetComponentInChildren<NetworkedObject>() != null)
{
if (LogHelper.CurrentLogLevel <= LogLevel.Normal) LogHelper.LogWarning("The NetworkingManager cannot be a NetworkedObject. This will lead to weird side effects.");
}
if (!NetworkConfig.RegisteredScenes.Contains(SceneManager.GetActiveScene().name))
{
if (LogHelper.CurrentLogLevel <= LogLevel.Normal) LogHelper.LogWarning("The active scene is not registered as a networked scene. The MLAPI has added it");
NetworkConfig.RegisteredScenes.Add(SceneManager.GetActiveScene().name);
}
// TODO: Show which two prefab generators that collide
HashSet<ulong> hashes = new HashSet<ulong>();
for (int i = 0; i < NetworkConfig.NetworkedPrefabs.Count; i++)
{
if (hashes.Contains(NetworkConfig.NetworkedPrefabs[i].Hash))
{
if (LogHelper.CurrentLogLevel <= LogLevel.Normal) LogHelper.LogError("PrefabHash collision! You have two prefabs with the same hash. This is not supported");
}
hashes.Add(NetworkConfig.NetworkedPrefabs[i].Hash);
}
int playerPrefabCount = NetworkConfig.NetworkedPrefabs.Count(x => x.PlayerPrefab == true);
if (playerPrefabCount == 0)
{
if (LogHelper.CurrentLogLevel <= LogLevel.Normal) LogHelper.LogWarning("There is no NetworkedPrefab marked as a PlayerPrefab");
}
else if (playerPrefabCount > 1)
{
if (LogHelper.CurrentLogLevel <= LogLevel.Normal) LogHelper.LogWarning("Only one networked prefab can be marked as a player prefab");
}
else NetworkConfig.PlayerPrefabHash = NetworkConfig.NetworkedPrefabs.Find(x => x.PlayerPrefab == true).Hash;
}
private void Init(bool server)
{
if (LogHelper.CurrentLogLevel <= LogLevel.Developer) LogHelper.LogInfo("Init()");
LocalClientId = 0;
NetworkTime = 0f;
lastSendTickTime = 0f;
lastEventTickTime = 0f;
lastReceiveTickTime = 0f;
eventOvershootCounter = 0f;
PendingClients.Clear();
ConnectedClients.Clear();
ConnectedClientsList.Clear();
ResponseMessageManager.Clear();
SpawnManager.SpawnedObjects.Clear();
SpawnManager.SpawnedObjectsList.Clear();
SpawnManager.releasedNetworkObjectIds.Clear();
SpawnManager.pendingSoftSyncObjects.Clear();
SpawnManager.customSpawnHandlers.Clear();
SpawnManager.customDestroyHandlers.Clear();
NetworkSceneManager.registeredSceneNames.Clear();
NetworkSceneManager.sceneIndexToString.Clear();
NetworkSceneManager.sceneNameToIndex.Clear();
NetworkSceneManager.sceneSwitchProgresses.Clear();
if (NetworkConfig.NetworkTransport == null)
{
if (LogHelper.CurrentLogLevel <= LogLevel.Error) LogHelper.LogError("No transport has been selected!");
return;
}
try
{
string pfx = NetworkConfig.ServerBase64PfxCertificate.Trim();
if (server && NetworkConfig.EnableEncryption && NetworkConfig.SignKeyExchange && !string.IsNullOrEmpty(pfx))
{
try
{
byte[] decodedPfx = Convert.FromBase64String(pfx);
NetworkConfig.ServerX509Certificate = new X509Certificate2(decodedPfx);
if (!NetworkConfig.ServerX509Certificate.HasPrivateKey)
{
if (LogHelper.CurrentLogLevel <= LogLevel.Normal) LogHelper.LogWarning("The imported PFX file did not have a private key");
}
}
catch (FormatException ex)
{
if (LogHelper.CurrentLogLevel <= LogLevel.Error) LogHelper.LogError("Parsing PFX failed: " + ex.ToString());
}
}
}
catch (CryptographicException ex)
{
if (LogHelper.CurrentLogLevel <= LogLevel.Error) LogHelper.LogError("Importing of certificate failed: " + ex.ToString());
}
NetworkConfig.RegisteredScenes.Sort();
for (int i = 0; i < NetworkConfig.RegisteredScenes.Count; i++)
{
NetworkSceneManager.registeredSceneNames.Add(NetworkConfig.RegisteredScenes[i]);
NetworkSceneManager.sceneIndexToString.Add((uint) i, NetworkConfig.RegisteredScenes[i]);
NetworkSceneManager.sceneNameToIndex.Add(NetworkConfig.RegisteredScenes[i], (uint) i);
}
NetworkSceneManager.SetCurrentSceneIndex();
NetworkConfig.NetworkTransport.Init();
}
/// <summary>
/// Starts a server
/// </summary>
public void StartServer()
{
if (LogHelper.CurrentLogLevel <= LogLevel.Developer) LogHelper.LogInfo("StartServer()");
if (IsServer || IsClient)
{
if (LogHelper.CurrentLogLevel <= LogLevel.Normal) LogHelper.LogWarning("Cannot start server while an instance is already running");
return;
}
if (NetworkConfig.ConnectionApproval)
{
if (ConnectionApprovalCallback == null)
{
if (LogHelper.CurrentLogLevel <= LogLevel.Normal) LogHelper.LogWarning("No ConnectionApproval callback defined. Connection approval will timeout");
}
}
Init(true);
NetworkConfig.NetworkTransport.StartServer();
IsServer = true;
IsClient = false;
IsListening = true;
SpawnManager.ServerSpawnSceneObjectsOnStartSweep();
if (OnServerStarted != null)
OnServerStarted.Invoke();
}
/// <summary>
/// Starts a client
/// </summary>
public void StartClient()
{
if (LogHelper.CurrentLogLevel <= LogLevel.Developer) LogHelper.LogInfo("StartClient()");
if (IsServer || IsClient)
{
if (LogHelper.CurrentLogLevel <= LogLevel.Normal) LogHelper.LogWarning("Cannot start client while an instance is already running");
return;
}
Init(false);
NetworkConfig.NetworkTransport.StartClient();
IsServer = false;
IsClient = true;
IsListening = true;
}
/// <summary>
/// Stops the running server
/// </summary>
public void StopServer()
{
if (LogHelper.CurrentLogLevel <= LogLevel.Developer) LogHelper.LogInfo("StopServer()");
HashSet<ulong> disconnectedIds = new HashSet<ulong>();
//Don't know if I have to disconnect the clients. I'm assuming the NetworkTransport does all the cleaning on shtudown. But this way the clients get a disconnect message from server (so long it does't get lost)
foreach (KeyValuePair<ulong, NetworkedClient> pair in ConnectedClients)
{
if (!disconnectedIds.Contains(pair.Key))
{
disconnectedIds.Add(pair.Key);
if (pair.Key == NetworkConfig.NetworkTransport.ServerClientId)
continue;
NetworkConfig.NetworkTransport.DisconnectRemoteClient(pair.Key);
}
}
foreach (KeyValuePair<ulong, PendingClient> pair in PendingClients)
{
if(!disconnectedIds.Contains(pair.Key))
{
disconnectedIds.Add(pair.Key);
if (pair.Key == NetworkConfig.NetworkTransport.ServerClientId)
continue;
NetworkConfig.NetworkTransport.DisconnectRemoteClient(pair.Key);
}
}
IsServer = false;
Shutdown();
}
/// <summary>
/// Stops the running host
/// </summary>
public void StopHost()
{
if (LogHelper.CurrentLogLevel <= LogLevel.Developer) LogHelper.LogInfo("StopHost()");
IsServer = false;
IsClient = false;
StopServer();
//We don't stop client since we dont actually have a transport connection to our own host. We just handle host messages directly in the MLAPI
}
/// <summary>
/// Stops the running client
/// </summary>
public void StopClient()
{
if (LogHelper.CurrentLogLevel <= LogLevel.Developer) LogHelper.LogInfo("StopClient()");
IsClient = false;
NetworkConfig.NetworkTransport.DisconnectLocalClient();
IsConnectedClient = false;
Shutdown();
}
/// <summary>
/// Starts a Host
/// </summary>
public void StartHost(Vector3? position = null, Quaternion? rotation = null, ulong? prefabHash = null, Stream payloadStream = null)
{
if (LogHelper.CurrentLogLevel <= LogLevel.Developer) LogHelper.LogInfo("StartHost()");
if (IsServer || IsClient)
{
if (LogHelper.CurrentLogLevel <= LogLevel.Normal) LogHelper.LogWarning("Cannot start host while an instance is already running");
return;
}
if (NetworkConfig.ConnectionApproval)
{
if (ConnectionApprovalCallback == null)
{
if (LogHelper.CurrentLogLevel <= LogLevel.Normal) LogHelper.LogWarning("No ConnectionApproval callback defined. Connection approval will timeout");
}
}
Init(true);
NetworkConfig.NetworkTransport.StartServer();
IsServer = true;
IsClient = true;
IsListening = true;
ulong hostClientId = NetworkConfig.NetworkTransport.ServerClientId;
ConnectedClients.Add(hostClientId, new NetworkedClient()
{
ClientId = hostClientId
});
ConnectedClientsList.Add(ConnectedClients[hostClientId]);
NetworkedObject netObject = SpawnManager.CreateLocalNetworkedObject(false, 0, (prefabHash == null ? NetworkConfig.PlayerPrefabHash : prefabHash.Value), position, rotation);
SpawnManager.SpawnNetworkedObjectLocally(netObject, SpawnManager.GetNetworkObjectId(), false, true, hostClientId, payloadStream, payloadStream != null, payloadStream == null ? 0 : (int)payloadStream.Length, false, false);
if (netObject.CheckObjectVisibility == null || netObject.CheckObjectVisibility(hostClientId))
{
netObject.observers.Add(hostClientId);
}
SpawnManager.ServerSpawnSceneObjectsOnStartSweep();
if (OnServerStarted != null)
OnServerStarted.Invoke();
}
private void OnEnable()
{
if (Singleton != null && Singleton != this)
{
Destroy(this.gameObject);
}
else
{
Singleton = this;
if (OnSingletonReady != null) OnSingletonReady();
if (DontDestroy)
DontDestroyOnLoad(gameObject);
if (RunInBackground)
Application.runInBackground = true;
}
}
private void OnDestroy()
{
if (Singleton != null && Singleton == this)
{
Singleton = null;
Shutdown();
}
}
private void Shutdown()
{
if (LogHelper.CurrentLogLevel <= LogLevel.Developer) LogHelper.LogInfo("Shutdown()");
NetworkProfiler.Stop();
IsListening = false;
IsServer = false;
IsClient = false;
SpawnManager.DestroyNonSceneObjects();
if (NetworkConfig != null && NetworkConfig.NetworkTransport != null) //The Transport is set during Init time, thus it is possible for the Transport to be null
NetworkConfig.NetworkTransport.Shutdown();
}
private float lastReceiveTickTime;
private float lastSendTickTime;
private float lastEventTickTime;
private float eventOvershootCounter;
private float lastTimeSyncTime;
private void Update()
{
if(IsListening)
{
if ((NetworkTime - lastSendTickTime >= (1f / NetworkConfig.SendTickrate)) || NetworkConfig.SendTickrate <= 0)
{
if (NetworkConfig.EnableNetworkedVar)
{
NetworkedObject.NetworkedBehaviourUpdate();
}
foreach (KeyValuePair<ulong, NetworkedClient> pair in ConnectedClients)
{
NetworkConfig.NetworkTransport.FlushSendQueue(pair.Key);
if (LogHelper.CurrentLogLevel <= LogLevel.Developer) LogHelper.LogInfo("Send Pending Queue: " + pair.Key);
}
lastSendTickTime = NetworkTime;
}
if ((NetworkTime - lastReceiveTickTime >= (1f / NetworkConfig.ReceiveTickrate)) || NetworkConfig.ReceiveTickrate <= 0)
{
NetworkProfiler.StartTick(TickType.Receive);
NetEventType eventType;
int processedEvents = 0;
do
{
processedEvents++;
eventType = NetworkConfig.NetworkTransport.PollEvent(out ulong clientId, out string channelName, out ArraySegment<byte> payload);
switch (eventType)
{
case NetEventType.Connect:
NetworkProfiler.StartEvent(TickType.Receive, (uint)payload.Count, channelName, "TRANSPORT_CONNECT");
if (IsServer)
{
if (LogHelper.CurrentLogLevel <= LogLevel.Developer) LogHelper.LogInfo("Client Connected");
#if !DISABLE_CRYPTOGRAPHY
if (NetworkConfig.EnableEncryption)
{
// This client is required to complete the crypto-hail exchange.
using (PooledBitStream hailStream = PooledBitStream.Get())
{
using (PooledBitWriter hailWriter = PooledBitWriter.Get(hailStream))
{
if (NetworkConfig.SignKeyExchange)
{
// Write certificate
hailWriter.WriteByteArray(NetworkConfig.ServerX509CertificateBytes);
}
// Write key exchange public part
EllipticDiffieHellman diffieHellman = new EllipticDiffieHellman(EllipticDiffieHellman.DEFAULT_CURVE, EllipticDiffieHellman.DEFAULT_GENERATOR, EllipticDiffieHellman.DEFAULT_ORDER);
byte[] diffieHellmanPublicPart = diffieHellman.GetPublicKey();
hailWriter.WriteByteArray(diffieHellmanPublicPart);
PendingClients.Add(clientId, new PendingClient()
{
ClientId = clientId,
ConnectionState = PendingClient.State.PendingHail,
KeyExchange = diffieHellman
});
if (NetworkConfig.SignKeyExchange)
{
// Write public part signature (signed by certificate private)
X509Certificate2 certificate = NetworkConfig.ServerX509Certificate;
if (!certificate.HasPrivateKey) throw new CryptographicException("[MLAPI] No private key was found in server certificate. Unable to sign key exchange");
RSACryptoServiceProvider rsa = certificate.PrivateKey as RSACryptoServiceProvider;
if (rsa != null)
{
using (SHA256Managed sha = new SHA256Managed())
{
hailWriter.WriteByteArray(rsa.SignData(diffieHellmanPublicPart, sha));
}
}
else
{
throw new CryptographicException("[MLAPI] Only RSA certificates are supported. No valid RSA key was found");
}
}
}
// Send the hail
InternalMessageSender.Send(clientId, MLAPIConstants.MLAPI_CERTIFICATE_HAIL, "MLAPI_INTERNAL", hailStream, SecuritySendFlags.None, null, true);
}
}
else
{
#endif
PendingClients.Add(clientId, new PendingClient()
{
ClientId = clientId,
ConnectionState = PendingClient.State.PendingConnection
});
#if !DISABLE_CRYPTOGRAPHY
}
#endif
StartCoroutine(ApprovalTimeout(clientId));
}
else
{
if (LogHelper.CurrentLogLevel <= LogLevel.Developer) LogHelper.LogInfo("Connected");
if (!NetworkConfig.EnableEncryption) SendConnectionRequest();
StartCoroutine(ApprovalTimeout(clientId));
}
NetworkProfiler.EndEvent();
break;
case NetEventType.Data:
if (LogHelper.CurrentLogLevel <= LogLevel.Developer) LogHelper.LogInfo($"Incoming Data From {clientId} : {payload.Count} bytes");
HandleIncomingData(clientId, channelName, payload);
break;
case NetEventType.Disconnect:
NetworkProfiler.StartEvent(TickType.Receive, 0, "NONE", "TRANSPORT_DISCONNECT");
if (LogHelper.CurrentLogLevel <= LogLevel.Developer) LogHelper.LogInfo("Disconnect Event From " + clientId);
if (IsServer)
OnClientDisconnectFromServer(clientId);
else
{
IsConnectedClient = false;
StopClient();
}
if (OnClientDisconnectCallback != null)
OnClientDisconnectCallback.Invoke(clientId);
NetworkProfiler.EndEvent();
break;
}
// Only do another iteration if: there are no more messages AND (there is no limit to max events or we have processed less than the maximum)
} while (IsListening && (eventType != NetEventType.Nothing && (NetworkConfig.MaxReceiveEventsPerTickRate <= 0 || processedEvents < NetworkConfig.MaxReceiveEventsPerTickRate)));
lastReceiveTickTime = NetworkTime;
NetworkProfiler.EndTick();
}
if (IsServer && ((NetworkTime - lastEventTickTime >= (1f / NetworkConfig.EventTickrate))))
{
NetworkProfiler.StartTick(TickType.Event);
eventOvershootCounter += ((NetworkTime - lastEventTickTime) - (1f / NetworkConfig.EventTickrate));
LagCompensationManager.AddFrames();
ResponseMessageManager.CheckTimeouts();
lastEventTickTime = NetworkTime;
NetworkProfiler.EndTick();
}
else if (IsServer && eventOvershootCounter >= ((1f / NetworkConfig.EventTickrate)))
{
NetworkProfiler.StartTick(TickType.Event);
//We run this one to compensate for previous update overshoots.
eventOvershootCounter -= (1f / NetworkConfig.EventTickrate);
LagCompensationManager.AddFrames();
NetworkProfiler.EndTick();
}
if (IsServer && NetworkConfig.EnableTimeResync && NetworkTime - lastTimeSyncTime >= 30)
{
NetworkProfiler.StartTick(TickType.Event);
SyncTime();
lastTimeSyncTime = NetworkTime;
NetworkProfiler.EndTick();
}
NetworkTime += Time.unscaledDeltaTime;
}
}
internal void SendConnectionRequest()
{
using (PooledBitStream stream = PooledBitStream.Get())
{
using (PooledBitWriter writer = PooledBitWriter.Get(stream))
{
writer.WriteUInt64Packed(NetworkConfig.GetConfig());
if (NetworkConfig.ConnectionApproval)
writer.WriteByteArray(NetworkConfig.ConnectionData);
}
InternalMessageSender.Send(ServerClientId, MLAPIConstants.MLAPI_CONNECTION_REQUEST, "MLAPI_INTERNAL", stream, SecuritySendFlags.Authenticated | SecuritySendFlags.Encrypted, null, true);
}
}
private IEnumerator ApprovalTimeout(ulong clientId)
{
float timeStarted = NetworkTime;
//We yield every frame incase a pending client disconnects and someone else gets its connection id
while (NetworkTime - timeStarted < NetworkConfig.ClientConnectionBufferTimeout && PendingClients.ContainsKey(clientId))
{
yield return null;
}
if (PendingClients.ContainsKey(clientId) && !ConnectedClients.ContainsKey(clientId))
{
// Timeout
if (LogHelper.CurrentLogLevel <= LogLevel.Developer) LogHelper.LogInfo("Client " + clientId + " Handshake Timed Out");
DisconnectClient(clientId);
}
}
internal IEnumerator TimeOutSwitchSceneProgress(SceneSwitchProgress switchSceneProgress)
{
yield return new WaitForSecondsRealtime(NetworkConfig.LoadSceneTimeOut);
switchSceneProgress.SetTimedOut();
}
private void HandleIncomingData(ulong clientId, string channelName, ArraySegment<byte> data)
{
if (LogHelper.CurrentLogLevel <= LogLevel.Developer) LogHelper.LogInfo("Unwrapping Data Header");
using (BitStream inputStream = new BitStream(data.Array))
{
inputStream.SetLength(data.Count + data.Offset);
inputStream.Position = data.Offset;
using (BitStream messageStream = MessagePacker.UnwrapMessage(inputStream, clientId, out byte messageType, out SecuritySendFlags security))
{
if (messageStream == null)
{
if (LogHelper.CurrentLogLevel <= LogLevel.Error) LogHelper.LogError("Message unwrap could not be completed. Was the header corrupt? Crypto error?");
return;
}
else if (messageType == MLAPIConstants.INVALID)
{
if (LogHelper.CurrentLogLevel <= LogLevel.Error) LogHelper.LogError("Message unwrap read an invalid messageType");
return;
}
uint headerByteSize = (uint)Arithmetic.VarIntSize(messageType);
NetworkProfiler.StartEvent(TickType.Receive, (uint)(data.Count - headerByteSize), channelName, messageType);
if (LogHelper.CurrentLogLevel <= LogLevel.Developer) LogHelper.LogInfo("Data Header: messageType=" + messageType);
// Client tried to send a network message that was not the connection request before he was accepted.
if (IsServer && (NetworkConfig.EnableEncryption && PendingClients.ContainsKey(clientId) && PendingClients[clientId].ConnectionState == PendingClient.State.PendingHail && messageType != MLAPIConstants.MLAPI_CERTIFICATE_HAIL_RESPONSE) ||
(PendingClients.ContainsKey(clientId) && PendingClients[clientId].ConnectionState == PendingClient.State.PendingConnection && messageType != MLAPIConstants.MLAPI_CONNECTION_REQUEST))
{
if (LogHelper.CurrentLogLevel <= LogLevel.Normal) LogHelper.LogWarning("Message recieved from clientId " + clientId + " before it has been accepted");
return;
}
#region INTERNAL MESSAGE
switch (messageType)
{
case MLAPIConstants.MLAPI_CONNECTION_REQUEST:
if (IsServer)
InternalMessageHandler.HandleConnectionRequest(clientId, messageStream);
break;
case MLAPIConstants.MLAPI_CONNECTION_APPROVED:
if (IsClient)
InternalMessageHandler.HandleConnectionApproved(clientId, messageStream);
break;
case MLAPIConstants.MLAPI_ADD_OBJECT:
if (IsClient) InternalMessageHandler.HandleAddObject(clientId, messageStream);
break;
case MLAPIConstants.MLAPI_DESTROY_OBJECT:
if (IsClient) InternalMessageHandler.HandleDestroyObject(clientId, messageStream);
break;
case MLAPIConstants.MLAPI_SWITCH_SCENE:
if (IsClient) InternalMessageHandler.HandleSwitchScene(clientId, messageStream);
break;
case MLAPIConstants.MLAPI_CHANGE_OWNER:
if (IsClient) InternalMessageHandler.HandleChangeOwner(clientId, messageStream);
break;
case MLAPIConstants.MLAPI_ADD_OBJECTS:
if (IsClient) InternalMessageHandler.HandleAddObjects(clientId, messageStream);
break;
case MLAPIConstants.MLAPI_TIME_SYNC:
if (IsClient) InternalMessageHandler.HandleTimeSync(clientId, messageStream);
break;
case MLAPIConstants.MLAPI_NETWORKED_VAR_DELTA:
InternalMessageHandler.HandleNetworkedVarDelta(clientId, messageStream);
break;
case MLAPIConstants.MLAPI_NETWORKED_VAR_UPDATE:
InternalMessageHandler.HandleNetworkedVarUpdate(clientId, messageStream);
break;
case MLAPIConstants.MLAPI_SERVER_RPC:
if (IsServer) InternalMessageHandler.HandleServerRPC(clientId, messageStream);
break;
case MLAPIConstants.MLAPI_SERVER_RPC_REQUEST:
if (IsServer) InternalMessageHandler.HandleServerRPCRequest(clientId, messageStream, channelName, security);
break;
case MLAPIConstants.MLAPI_SERVER_RPC_RESPONSE:
if (IsClient) InternalMessageHandler.HandleServerRPCResponse(clientId, messageStream);
break;
case MLAPIConstants.MLAPI_CLIENT_RPC:
if (IsClient) InternalMessageHandler.HandleClientRPC(clientId, messageStream);
break;
case MLAPIConstants.MLAPI_CLIENT_RPC_REQUEST:
if (IsClient) InternalMessageHandler.HandleClientRPCRequest(clientId, messageStream, channelName, security);
break;
case MLAPIConstants.MLAPI_CLIENT_RPC_RESPONSE:
if (IsServer) InternalMessageHandler.HandleClientRPCResponse(clientId, messageStream);
break;
case MLAPIConstants.MLAPI_CUSTOM_MESSAGE:
InternalMessageHandler.HandleCustomMessage(clientId, messageStream);
break;
#if !DISABLE_CRYPTOGRAPHY
case MLAPIConstants.MLAPI_CERTIFICATE_HAIL:
if (IsClient) InternalMessageHandler.HandleHailRequest(clientId, messageStream);
break;
case MLAPIConstants.MLAPI_CERTIFICATE_HAIL_RESPONSE:
if (IsServer) InternalMessageHandler.HandleHailResponse(clientId, messageStream);
break;
case MLAPIConstants.MLAPI_GREETINGS:
if (IsClient) InternalMessageHandler.HandleGreetings(clientId, messageStream);
break;
#endif
case MLAPIConstants.MLAPI_CLIENT_SWITCH_SCENE_COMPLETED:
if (IsServer) InternalMessageHandler.HandleClientSwitchSceneCompleted(clientId, messageStream);
break;
default:
if (LogHelper.CurrentLogLevel <= LogLevel.Error) LogHelper.LogError("Read unrecognized messageType " + messageType);
break;
}
#endregion
NetworkProfiler.EndEvent();
}
}
}
internal void DisconnectClient(ulong clientId)
{
if (!IsServer)
return;
if (ConnectedClients.ContainsKey(clientId))
ConnectedClients.Remove(clientId);
if (PendingClients.ContainsKey(clientId))
PendingClients.Remove(clientId);
for (int i = ConnectedClientsList.Count - 1; i > -1; i--)
{
if (ConnectedClientsList[i].ClientId == clientId)
ConnectedClientsList.RemoveAt(i);
}
NetworkConfig.NetworkTransport.DisconnectRemoteClient(clientId);
}
internal void OnClientDisconnectFromServer(ulong clientId)
{
if (PendingClients.ContainsKey(clientId))
PendingClients.Remove(clientId);
if (ConnectedClients.ContainsKey(clientId))
{
if (IsServer)
{
if (ConnectedClients[clientId].PlayerObject != null)
{
if (SpawnManager.customDestroyHandlers.ContainsKey(ConnectedClients[clientId].PlayerObject.PrefabHash))
{
SpawnManager.customDestroyHandlers[ConnectedClients[clientId].PlayerObject.PrefabHash](ConnectedClients[clientId].PlayerObject);
SpawnManager.OnDestroyObject(ConnectedClients[clientId].PlayerObject.NetworkId, false);
}
else
{
Destroy(ConnectedClients[clientId].PlayerObject.gameObject);
}
}
for (int i = 0; i < ConnectedClients[clientId].OwnedObjects.Count; i++)
{
if (ConnectedClients[clientId].OwnedObjects[i] != null)
{
if (!ConnectedClients[clientId].OwnedObjects[i].DontDestroyWithOwner)
{
if (SpawnManager.customDestroyHandlers.ContainsKey(ConnectedClients[clientId].OwnedObjects[i].PrefabHash))
{
SpawnManager.customDestroyHandlers[ConnectedClients[clientId].OwnedObjects[i].PrefabHash](ConnectedClients[clientId].OwnedObjects[i]);
SpawnManager.OnDestroyObject(ConnectedClients[clientId].OwnedObjects[i].NetworkId, false);
}
else
{
Destroy(ConnectedClients[clientId].OwnedObjects[i].gameObject);
}
}
else
{
ConnectedClients[clientId].OwnedObjects[i].RemoveOwnership();
}
}
}
// TODO: Could(should?) be replaced with more memory per client, by storing the visiblity
for (int i = 0; i < SpawnManager.SpawnedObjectsList.Count; i++)
{
SpawnManager.SpawnedObjectsList[i].observers.Remove(clientId);
}
}
for (int i = 0; i < ConnectedClientsList.Count; i++)
{
if (ConnectedClientsList[i].ClientId == clientId)
{
ConnectedClientsList.RemoveAt(i);
break;
}
}
ConnectedClients.Remove(clientId);
}
}
private void SyncTime()
{
if (LogHelper.CurrentLogLevel <= LogLevel.Developer) LogHelper.LogInfo("Syncing Time To Clients");
using (PooledBitStream stream = PooledBitStream.Get())
{
using (PooledBitWriter writer = PooledBitWriter.Get(stream))
{
writer.WriteSinglePacked(NetworkTime);
InternalMessageSender.Send(MLAPIConstants.MLAPI_TIME_SYNC, "MLAPI_TIME_SYNC", stream, SecuritySendFlags.None, null);
}
}
}
private readonly List<NetworkedObject> _observedObjects = new List<NetworkedObject>();
internal void HandleApproval(ulong clientId, ulong? prefabHash, bool approved, Vector3? position, Quaternion? rotation)
{
if(approved)
{
// Inform new client it got approved
byte[] aesKey = PendingClients.ContainsKey(clientId) ? PendingClients[clientId].AesKey : null;
if (PendingClients.ContainsKey(clientId))
PendingClients.Remove(clientId);
NetworkedClient client = new NetworkedClient()
{
ClientId = clientId,
#if !DISABLE_CRYPTOGRAPHY
AesKey = aesKey
#endif
};
ConnectedClients.Add(clientId, client);
ConnectedClientsList.Add(client);
NetworkedObject netObject = SpawnManager.CreateLocalNetworkedObject(false, 0, (prefabHash == null ? NetworkConfig.PlayerPrefabHash : prefabHash.Value), position, rotation);
SpawnManager.SpawnNetworkedObjectLocally(netObject, SpawnManager.GetNetworkObjectId(), false, true, clientId, null, false, 0, false, false);
ConnectedClients[clientId].PlayerObject = netObject;