-
-
Notifications
You must be signed in to change notification settings - Fork 65
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: moving message handling out of networkplayer (#818)
Making NetworkPlayer do less things, Server or client should handle message instead of player. Makes registering message simpler, no need to wait for player to Connect to register message. BREAKING CHANGE: RegisterHandler functions now exist on MessageHandler On Server and Client BREAKING CHANGE: NetworkAuthenticator now use Setup methods that should be used to register messages
- Loading branch information
1 parent
056dc48
commit b2e9d96
Showing
45 changed files
with
597 additions
and
374 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,143 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.IO; | ||
using Mirage.Logging; | ||
using Mirage.Serialization; | ||
using UnityEngine; | ||
|
||
namespace Mirage | ||
{ | ||
public class MessageHandler : IMessageReceiver | ||
{ | ||
static readonly ILogger logger = LogFactory.GetLogger(typeof(MessageHandler)); | ||
|
||
readonly bool disconnectOnException; | ||
|
||
// Handles network messages on client and server | ||
internal delegate void NetworkMessageDelegate(INetworkPlayer player, NetworkReader reader); | ||
|
||
// message handlers for this connection | ||
internal readonly Dictionary<int, NetworkMessageDelegate> messageHandlers = new Dictionary<int, NetworkMessageDelegate>(); | ||
|
||
public MessageHandler(bool disconnectOnException) | ||
{ | ||
this.disconnectOnException = disconnectOnException; | ||
} | ||
|
||
private static NetworkMessageDelegate MessageWrapper<T>(MessageDelegateWithPlayer<T> handler) | ||
{ | ||
void AdapterFunction(INetworkPlayer player, NetworkReader reader) | ||
{ | ||
T message = NetworkDiagnostics.ReadWithDiagnostics<T>(reader); | ||
|
||
handler.Invoke(player, message); | ||
} | ||
return AdapterFunction; | ||
} | ||
|
||
/// <summary> | ||
/// Register a handler for a particular message type. | ||
/// <para>There are several system message types which you can add handlers for. You can also add your own message types.</para> | ||
/// </summary> | ||
/// <typeparam name="T">Message type</typeparam> | ||
/// <param name="handler">Function handler which will be invoked for when this message type is received.</param> | ||
/// <param name="requireAuthentication">True if the message requires an authenticated connection</param> | ||
public void RegisterHandler<T>(MessageDelegateWithPlayer<T> handler) | ||
{ | ||
int msgType = MessagePacker.GetId<T>(); | ||
if (logger.filterLogType == LogType.Log && messageHandlers.ContainsKey(msgType)) | ||
{ | ||
logger.Log("RegisterHandler replacing " + msgType); | ||
} | ||
messageHandlers[msgType] = MessageWrapper(handler); | ||
} | ||
|
||
/// <summary> | ||
/// Register a handler for a particular message type. | ||
/// <para>There are several system message types which you can add handlers for. You can also add your own message types.</para> | ||
/// </summary> | ||
/// <typeparam name="T">Message type</typeparam> | ||
/// <param name="handler">Function handler which will be invoked for when this message type is received.</param> | ||
/// <param name="requireAuthentication">True if the message requires an authenticated connection</param> | ||
public void RegisterHandler<T>(MessageDelegate<T> handler) | ||
{ | ||
RegisterHandler<T>((_, value) => { handler(value); }); | ||
} | ||
|
||
/// <summary> | ||
/// Unregister a handler for a particular message type. | ||
/// <para>Note: Messages dont need to be unregister when server or client stops as MessageHandler will be re-created next time server or client starts</para> | ||
/// </summary> | ||
/// <typeparam name="T">Message type</typeparam> | ||
public void UnregisterHandler<T>() | ||
{ | ||
int msgType = MessagePacker.GetId<T>(); | ||
messageHandlers.Remove(msgType); | ||
} | ||
|
||
/// <summary> | ||
/// Clear all registered callback handlers. | ||
/// </summary> | ||
public void ClearHandlers() | ||
{ | ||
messageHandlers.Clear(); | ||
} | ||
|
||
|
||
internal void InvokeHandler(INetworkPlayer player, int msgType, NetworkReader reader) | ||
{ | ||
if (messageHandlers.TryGetValue(msgType, out NetworkMessageDelegate msgDelegate)) | ||
{ | ||
msgDelegate.Invoke(player, reader); | ||
} | ||
else | ||
{ | ||
try | ||
{ | ||
Type type = MessagePacker.GetMessageType(msgType); | ||
throw new InvalidDataException($"Unexpected message {type} received in {this}. Did you register a handler for it?"); | ||
} | ||
catch (KeyNotFoundException) | ||
{ | ||
throw new InvalidDataException($"Unexpected message ID {msgType} received in {this}. May be due to no existing RegisterHandler for this message."); | ||
} | ||
} | ||
} | ||
|
||
public void HandleMessage(INetworkPlayer player, ArraySegment<byte> packet) | ||
{ | ||
using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(packet)) | ||
{ | ||
// protect against attackers trying to send invalid data packets | ||
// exception could be throw if: | ||
// - invalid headers | ||
// - invalid message ids | ||
// - invalid data causing exceptions | ||
// - negative ReadBytesAndSize prefixes | ||
// - invalid utf8 strings | ||
// - etc. | ||
// | ||
// if exception is caught, disconnect the attacker to stop any further attacks | ||
|
||
try | ||
{ | ||
int msgType = MessagePacker.UnpackId(networkReader); | ||
InvokeHandler(player, msgType, networkReader); | ||
} | ||
catch (InvalidDataException ex) | ||
{ | ||
logger.Log(ex.ToString()); | ||
} | ||
catch (Exception e) | ||
{ | ||
string disconnectMessage = disconnectOnException ? ", Closed connection: {this}" : ""; | ||
logger.LogError($"{e.GetType()} in Message handler (see stack below){disconnectMessage}\n{e}"); | ||
if (disconnectOnException) | ||
{ | ||
player.Disconnect(); | ||
} | ||
} | ||
} | ||
} | ||
} | ||
} |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.