From bfb40202793f2f7f2c9c73272f01a477b23edfa2 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 4 Nov 2018 21:34:48 -0500 Subject: rewrite multiplayer sync to use generic callbacks from client/server for better extensibility (#480) --- src/SMAPI/Events/ModMessageReceivedEventArgs.cs | 2 +- src/SMAPI/Framework/Networking/MessageType.cs | 26 +++ src/SMAPI/Framework/Networking/MultiplayerPeer.cs | 6 +- src/SMAPI/Framework/Networking/SLidgrenClient.cs | 37 ++-- src/SMAPI/Framework/Networking/SLidgrenServer.cs | 122 +++++++++++- src/SMAPI/Framework/SCore.cs | 2 +- src/SMAPI/Framework/SMultiplayer.cs | 226 +++++++++++++--------- src/SMAPI/Patches/LidgrenServerPatch.cs | 89 +++++++++ src/SMAPI/Patches/NetworkingPatch.cs | 103 ---------- src/SMAPI/StardewModdingAPI.csproj | 3 +- 10 files changed, 383 insertions(+), 233 deletions(-) create mode 100644 src/SMAPI/Framework/Networking/MessageType.cs create mode 100644 src/SMAPI/Patches/LidgrenServerPatch.cs delete mode 100644 src/SMAPI/Patches/NetworkingPatch.cs (limited to 'src') diff --git a/src/SMAPI/Events/ModMessageReceivedEventArgs.cs b/src/SMAPI/Events/ModMessageReceivedEventArgs.cs index b1960a22..49366ec6 100644 --- a/src/SMAPI/Events/ModMessageReceivedEventArgs.cs +++ b/src/SMAPI/Events/ModMessageReceivedEventArgs.cs @@ -3,7 +3,7 @@ using StardewModdingAPI.Framework.Networking; namespace StardewModdingAPI.Events { - /// Event arguments when a mod receives a message over the network. + /// Event arguments for an event. public class ModMessageReceivedEventArgs : EventArgs { /********* diff --git a/src/SMAPI/Framework/Networking/MessageType.cs b/src/SMAPI/Framework/Networking/MessageType.cs new file mode 100644 index 00000000..bd9acfa9 --- /dev/null +++ b/src/SMAPI/Framework/Networking/MessageType.cs @@ -0,0 +1,26 @@ +using StardewValley; + +namespace StardewModdingAPI.Framework.Networking +{ + /// Network message types recognised by SMAPI and Stardew Valley. + internal enum MessageType : byte + { + /********* + ** SMAPI + *********/ + /// A data message intended for mods to consume. + ModMessage = 254, + + /// Metadata context about a player synced by SMAPI. + ModContext = 255, + + /********* + ** Vanilla + *********/ + /// Metadata about the host server sent to a farmhand. + ServerIntroduction = Multiplayer.serverIntroduction, + + /// Metadata about a player sent to a farmhand or server. + PlayerIntroduction = Multiplayer.playerIntroduction + } +} diff --git a/src/SMAPI/Framework/Networking/MultiplayerPeer.cs b/src/SMAPI/Framework/Networking/MultiplayerPeer.cs index c7f8ffad..e703dbb1 100644 --- a/src/SMAPI/Framework/Networking/MultiplayerPeer.cs +++ b/src/SMAPI/Framework/Networking/MultiplayerPeer.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; using System.Linq; using Lidgren.Network; -using StardewValley; using StardewValley.Network; namespace StardewModdingAPI.Framework.Networking @@ -95,7 +94,8 @@ namespace StardewModdingAPI.Framework.Networking /// The player's unique ID. /// The metadata to copy. /// The client through which to send messages. - public static MultiplayerPeer ForConnectionToHost(long playerID, RemoteContextModel model, SLidgrenClient client) + /// Whether this connection is for the host player. + public static MultiplayerPeer ForConnectionToHost(long playerID, RemoteContextModel model, SLidgrenClient client, bool isHost) { return new MultiplayerPeer( playerID: playerID, @@ -103,7 +103,7 @@ namespace StardewModdingAPI.Framework.Networking server: null, serverConnection: null, client: client, - isHost: true + isHost: isHost ); } diff --git a/src/SMAPI/Framework/Networking/SLidgrenClient.cs b/src/SMAPI/Framework/Networking/SLidgrenClient.cs index 9dfdba15..c05e6b76 100644 --- a/src/SMAPI/Framework/Networking/SLidgrenClient.cs +++ b/src/SMAPI/Framework/Networking/SLidgrenClient.cs @@ -1,44 +1,38 @@ using System; -using StardewValley; using StardewValley.Network; namespace StardewModdingAPI.Framework.Networking { - /// A multiplayer client used to connect to a hosted server. This is an implementation of that adds support for SMAPI's metadata context exchange. + /// A multiplayer client used to connect to a hosted server. This is an implementation of with callbacks for SMAPI functionality. internal class SLidgrenClient : LidgrenClient { /********* ** Properties *********/ - /// Get the metadata to include in a metadata message sent to other players. - private readonly Func GetMetadataMessageFields; - - /// The method to call when receiving a custom SMAPI message from the server, which returns whether the message was processed. - private readonly Func TryProcessMessage; + /// A callback to raise when receiving a message. This receives the client instance, incoming message, and a callback to run the default logic. + private readonly Action OnProcessingMessage; + /// A callback to raise when sending a message. This receives the client instance, outgoing message, and a callback to run the default logic. + private readonly Action OnSendingMessage; /********* ** Public methods *********/ /// Construct an instance. /// The remote address being connected. - /// Get the metadata to include in a metadata message sent to other players. - /// The method to call when receiving a custom SMAPI message from the server, which returns whether the message was processed.. - public SLidgrenClient(string address, Func getMetadataMessageFields, Func tryProcessMessage) + /// A callback to raise when receiving a message. This receives the client instance, incoming message, and a callback to run the default logic. + /// A callback to raise when sending a message. This receives the client instance, outgoing message, and a callback to run the default logic. + public SLidgrenClient(string address, Action onProcessingMessage, Action onSendingMessage) : base(address) { - this.GetMetadataMessageFields = getMetadataMessageFields; - this.TryProcessMessage = tryProcessMessage; + this.OnProcessingMessage = onProcessingMessage; + this.OnSendingMessage = onSendingMessage; } - /// Send the metadata needed to connect with a remote server. - public override void sendPlayerIntroduction() + /// Send a message to the connected peer. + public override void sendMessage(OutgoingMessage message) { - // send custom intro - if (this.getUserID() != "") - Game1.player.userID.Value = this.getUserID(); - this.sendMessage(SMultiplayer.ContextSyncMessageID, this.GetMetadataMessageFields()); - base.sendPlayerIntroduction(); + this.OnSendingMessage(this, message, () => base.sendMessage(message)); } @@ -49,10 +43,7 @@ namespace StardewModdingAPI.Framework.Networking /// The message to process. protected override void processIncomingMessage(IncomingMessage message) { - if (this.TryProcessMessage(this, message)) - return; - - base.processIncomingMessage(message); + this.OnProcessingMessage(this, message, () => base.processIncomingMessage(message)); } } } diff --git a/src/SMAPI/Framework/Networking/SLidgrenServer.cs b/src/SMAPI/Framework/Networking/SLidgrenServer.cs index 971eb66d..060b433b 100644 --- a/src/SMAPI/Framework/Networking/SLidgrenServer.cs +++ b/src/SMAPI/Framework/Networking/SLidgrenServer.cs @@ -1,5 +1,11 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; using System.Reflection; using Lidgren.Network; +using StardewModdingAPI.Framework.Reflection; +using StardewModdingAPI.Patches; +using StardewValley; using StardewValley.Network; namespace StardewModdingAPI.Framework.Networking @@ -10,8 +16,27 @@ namespace StardewModdingAPI.Framework.Networking /********* ** Properties *********/ - /// A method which sends a message through a specific connection. - private readonly MethodInfo SendMessageToConnectionMethod; + + /// The constructor for the internal NetBufferReadStream type. + private readonly ConstructorInfo NetBufferReadStreamConstructor = SLidgrenServer.GetNetBufferReadStreamConstructor(); + + /// The constructor for the internal NetBufferWriteStream type. + private readonly ConstructorInfo NetBufferWriteStreamConstructor = SLidgrenServer.GetNetBufferWriteStreamConstructor(); + + /// A method which reads farmer data from the given binary reader. + private readonly Func ReadFarmer; + + /// A callback to raise when receiving a message. This receives the server instance, raw/parsed incoming message, and a callback to run the default logic. + private readonly Action OnProcessingMessage; + + /// A callback to raise when sending a message. This receives the server instance, outgoing connection, outgoing message, target player ID, and a callback to run the default logic. + private readonly Action OnSendingMessage; + + /// The peer connections. + private readonly Bimap Peers; + + /// The underlying net server. + private readonly IReflectedField Server; /********* @@ -19,18 +44,105 @@ namespace StardewModdingAPI.Framework.Networking *********/ /// Construct an instance. /// The underlying game server. - public SLidgrenServer(IGameServer gameServer) + /// Simplifies access to private code. + /// A method which reads farmer data from the given binary reader. + /// A callback to raise when receiving a message. This receives the server instance, raw/parsed incoming message, and a callback to run the default logic. + /// A callback to raise when sending a message. This receives the server instance, outgoing connection, outgoing message, and a callback to run the default logic. + public SLidgrenServer(IGameServer gameServer, Reflector reflection, Func readFarmer, Action onProcessingMessage, Action onSendingMessage) : base(gameServer) { - this.SendMessageToConnectionMethod = typeof(LidgrenServer).GetMethod(nameof(LidgrenServer.sendMessage), BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(NetConnection), typeof(OutgoingMessage) }, null); + this.ReadFarmer = readFarmer; + this.OnProcessingMessage = onProcessingMessage; + this.OnSendingMessage = onSendingMessage; + this.Peers = reflection.GetField>(this, "peers").GetValue(); + this.Server = reflection.GetField(this, "server"); } /// Send a message to a remote server. /// The network connection. /// The message to send. + /// This is an implementation of which calls . This method is invoked via . public void SendMessage(NetConnection connection, OutgoingMessage message) { - this.SendMessageToConnectionMethod.Invoke(this, new object[] { connection, message }); + this.OnSendingMessage(this, connection, message, () => + { + NetServer server = this.Server.GetValue(); + NetOutgoingMessage netMessage = server.CreateMessage(); + using (Stream bufferWriteStream = (Stream)this.NetBufferWriteStreamConstructor.Invoke(new object[] { netMessage })) + using (BinaryWriter writer = new BinaryWriter(bufferWriteStream)) + message.Write(writer); + + server.SendMessage(netMessage, connection, NetDeliveryMethod.ReliableOrdered); + }); + } + + /// Parse a data message from a client. + /// The raw network message to parse. + /// This is an implementation of which calls . This method is invoked via . + [SuppressMessage("ReSharper", "AccessToDisposedClosure", Justification = "The callback is invoked synchronously.")] + public bool ParseDataMessageFromClient(NetIncomingMessage rawMessage) + { + // add hook to call multiplayer core + NetConnection peer = rawMessage.SenderConnection; + using (IncomingMessage message = new IncomingMessage()) + using (Stream readStream = (Stream)this.NetBufferReadStreamConstructor.Invoke(new object[] { rawMessage })) + using (BinaryReader reader = new BinaryReader(readStream)) + { + while (rawMessage.LengthBits - rawMessage.Position >= 8) + { + message.Read(reader); + this.OnProcessingMessage(this, rawMessage, message, () => + { + if (this.Peers.ContainsLeft(message.FarmerID) && this.Peers[message.FarmerID] == peer) + this.gameServer.processIncomingMessage(message); + else if (message.MessageType == Multiplayer.playerIntroduction) + { + NetFarmerRoot farmer = this.ReadFarmer(message.Reader); + this.gameServer.checkFarmhandRequest("", farmer, msg => this.SendMessage(peer, msg), () => this.Peers[farmer.Value.UniqueMultiplayerID] = peer); + } + }); + } + } + + return false; + } + + + /********* + ** Private methods + *********/ + /// Get the constructor for the internal NetBufferReadStream type. + private static ConstructorInfo GetNetBufferReadStreamConstructor() + { + // get type + string typeName = $"StardewValley.Network.NetBufferReadStream, {Constants.GameAssemblyName}"; + Type type = Type.GetType(typeName); + if (type == null) + throw new InvalidOperationException($"Can't find type: {typeName}"); + + // get constructor + ConstructorInfo constructor = type.GetConstructor(new[] { typeof(NetBuffer) }); + if (constructor == null) + throw new InvalidOperationException($"Can't find constructor for type: {typeName}"); + + return constructor; + } + + /// Get the constructor for the internal NetBufferWriteStream type. + private static ConstructorInfo GetNetBufferWriteStreamConstructor() + { + // get type + string typeName = $"StardewValley.Network.NetBufferWriteStream, {Constants.GameAssemblyName}"; + Type type = Type.GetType(typeName); + if (type == null) + throw new InvalidOperationException($"Can't find type: {typeName}"); + + // get constructor + ConstructorInfo constructor = type.GetConstructor(new[] { typeof(NetBuffer) }); + if (constructor == null) + throw new InvalidOperationException($"Can't find constructor for type: {typeName}"); + + return constructor; } } } diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index ca343389..f078acba 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -162,7 +162,7 @@ namespace StardewModdingAPI.Framework // apply game patches new GamePatcher(this.Monitor).Apply( new DialogueErrorPatch(this.MonitorForGame, this.Reflection), - new NetworkingPatch() + new LidgrenServerPatch() ); } diff --git a/src/SMAPI/Framework/SMultiplayer.cs b/src/SMAPI/Framework/SMultiplayer.cs index e4f912d2..70f1a89a 100644 --- a/src/SMAPI/Framework/SMultiplayer.cs +++ b/src/SMAPI/Framework/SMultiplayer.cs @@ -14,6 +14,17 @@ using StardewValley.Network; namespace StardewModdingAPI.Framework { /// SMAPI's implementation of the game's core multiplayer logic. + /// + /// SMAPI syncs mod context to all players through the host as such: + /// 1. Farmhand sends ModContext + PlayerIntro. + /// 2. If host receives ModContext: it stores the context, replies with known contexts, and forwards it to other farmhands. + /// 3. If host receives PlayerIntro before ModContext: it stores a 'vanilla player' context, and forwards it to other farmhands. + /// 4. If farmhand receives ModContext: it stores it. + /// 5. If farmhand receives ServerIntro without a preceding ModContext: it stores a 'vanilla host' context. + /// 6. If farmhand receives PlayerIntro without a preceding ModContext AND it's not the host peer: it stores a 'vanilla player' context. + /// + /// Once a farmhand/server stored a context, messages can be sent to that player through the SMAPI APIs. + /// internal class SMultiplayer : Multiplayer { /********* @@ -47,12 +58,6 @@ namespace StardewModdingAPI.Framework /********* ** Accessors *********/ - /// The message ID for a SMAPI message containing context about a player. - public const byte ContextSyncMessageID = 255; - - /// The message ID for a mod message. - public const byte ModMessageID = 254; - /// The metadata for each connected peer. public IDictionary Peers { get; } = new Dictionary(); @@ -107,7 +112,7 @@ namespace StardewModdingAPI.Framework if (client is LidgrenClient) { string address = this.Reflection.GetField(client, "address").GetValue(); - return new SLidgrenClient(address, this.GetContextSyncMessageFields, this.TryProcessMessageFromServer); + return new SLidgrenClient(address, this.OnClientProcessingMessage, this.OnClientSendingMessage); } return client; @@ -120,56 +125,78 @@ namespace StardewModdingAPI.Framework if (server is LidgrenServer) { IGameServer gameServer = this.Reflection.GetField(server, "gameServer").GetValue(); - return new SLidgrenServer(gameServer); + return new SLidgrenServer(gameServer, this.Reflection, this.readFarmer, this.OnServerProcessingMessage, this.OnServerSendingMessage); } return server; } - /// Process an incoming network message from an unknown farmhand, usually a player whose connection hasn't been approved yet. + /// A callback raised when sending a network message as the host player. + /// The server sending the message. + /// The connection to which a message is being sent. + /// The message being sent. + /// Send the underlying message. + protected void OnServerSendingMessage(SLidgrenServer server, NetConnection connection, OutgoingMessage message, Action resume) + { + resume(); + } + + /// A callback raised when sending a message as a farmhand. + /// The client sending the message. + /// The message being sent. + /// Send the underlying message. + protected void OnClientSendingMessage(SLidgrenClient client, OutgoingMessage message, Action resume) + { + switch (message.MessageType) + { + // sync mod context (step 1) + case (byte)MessageType.PlayerIntroduction: + client.sendMessage((byte)MessageType.ModContext, this.GetContextSyncMessageFields()); + resume(); + break; + + // run default logic + default: + resume(); + break; + } + } + + /// Process an incoming network message as the host player. /// The server instance that received the connection. /// The raw network message that was received. /// The message to process. - public void ProcessMessageFromUnknownFarmhand(Server server, NetIncomingMessage rawMessage, IncomingMessage message) + /// Process the message using the game's default logic. + public void OnServerProcessingMessage(SLidgrenServer server, NetIncomingMessage rawMessage, IncomingMessage message, Action resume) { - // ignore invalid message (farmhands should only receive messages from the server) - if (!Game1.IsMasterGame) - return; switch (message.MessageType) { - // sync SMAPI context with connected instances - case SMultiplayer.ContextSyncMessageID: + // sync mod context (step 2) + case (byte)MessageType.ModContext: { - // get server - if (!(server is SLidgrenServer customServer)) + // parse message + RemoteContextModel model = this.ReadContext(message.Reader); + this.Monitor.Log($"Received context for farmhand {message.FarmerID} running {(model != null ? $"SMAPI {model.ApiVersion} with {model.Mods.Length} mods" : "vanilla")}.", LogLevel.Trace); + + // store peer + MultiplayerPeer newPeer = MultiplayerPeer.ForConnectionToFarmhand(message.FarmerID, model, server, rawMessage.SenderConnection); + if (this.Peers.ContainsKey(message.FarmerID)) { - this.Monitor.Log($"Received context from farmhand {message.FarmerID} via unknown client {server.GetType().FullName}. Mods will not be able to sync data to that player.", LogLevel.Warn); + this.Monitor.Log($"Rejected mod context from farmhand {message.FarmerID}: already received context for that player.", LogLevel.Error); return; } + this.Peers[message.FarmerID] = newPeer; - // parse message - string data = message.Reader.ReadString(); - RemoteContextModel model = this.JsonHelper.Deserialise(data); - if (model.ApiVersion == null) - model = null; // no data available for unmodded players - - // log info - if (model != null) - this.Monitor.Log($"Received context for farmhand {message.FarmerID} running SMAPI {model.ApiVersion} with {model.Mods.Length} mods{(this.VerboseLogging ? $": {data}" : "")}.", LogLevel.Trace); - else - this.Monitor.Log($"Received context for farmhand {message.FarmerID} running vanilla{(this.VerboseLogging ? $": {data}" : "")}.", LogLevel.Trace); - - // store peer - MultiplayerPeer newPeer = this.Peers[message.FarmerID] = MultiplayerPeer.ForConnectionToFarmhand(message.FarmerID, model, customServer, rawMessage.SenderConnection); + // reply with own context + this.VerboseLog(" Replying with host context..."); + newPeer.SendMessage(new OutgoingMessage((byte)MessageType.ModContext, Game1.player.UniqueMultiplayerID, this.GetContextSyncMessageFields())); - // reply with known contexts - this.VerboseLog(" Replying with context for current player..."); - newPeer.SendMessage(new OutgoingMessage(SMultiplayer.ContextSyncMessageID, Game1.player.UniqueMultiplayerID, this.GetContextSyncMessageFields())); + // reply with other players' context foreach (MultiplayerPeer otherPeer in this.Peers.Values.Where(p => p.PlayerID != newPeer.PlayerID)) { this.VerboseLog($" Replying with context for player {otherPeer.PlayerID}..."); - newPeer.SendMessage(new OutgoingMessage(SMultiplayer.ContextSyncMessageID, otherPeer.PlayerID, this.GetContextSyncMessageFields(otherPeer))); + newPeer.SendMessage(new OutgoingMessage((byte)MessageType.ModContext, otherPeer.PlayerID, this.GetContextSyncMessageFields(otherPeer))); } // forward to other peers @@ -179,107 +206,103 @@ namespace StardewModdingAPI.Framework foreach (MultiplayerPeer otherPeer in this.Peers.Values.Where(p => p.PlayerID != newPeer.PlayerID)) { this.VerboseLog($" Forwarding context to player {otherPeer.PlayerID}..."); - otherPeer.SendMessage(new OutgoingMessage(SMultiplayer.ContextSyncMessageID, newPeer.PlayerID, fields)); + otherPeer.SendMessage(new OutgoingMessage((byte)MessageType.ModContext, newPeer.PlayerID, fields)); } } } break; - // handle intro from unmodded player - case Multiplayer.playerIntroduction: - if (!this.Peers.ContainsKey(message.FarmerID)) + // handle player intro + case (byte)MessageType.PlayerIntroduction: { - // get server - if (!(server is SLidgrenServer customServer)) + // get peer + if (!this.Peers.TryGetValue(message.FarmerID, out MultiplayerPeer peer)) { - this.Monitor.Log($"Received connection from farmhand {message.FarmerID} with unknown client {server.GetType().FullName}. Mods will not be able to sync data to that player.", LogLevel.Warn); - return; + this.Monitor.Log($"Received connection for vanilla player {message.FarmerID}.", LogLevel.Trace); + this.Peers[message.FarmerID] = peer = MultiplayerPeer.ForConnectionToFarmhand(message.FarmerID, null, server, rawMessage.SenderConnection); } - // store peer - this.Monitor.Log($"Received connection for vanilla player {message.FarmerID}.", LogLevel.Trace); - var peer = MultiplayerPeer.ForConnectionToFarmhand(message.FarmerID, null, customServer, rawMessage.SenderConnection); - this.Peers[message.FarmerID] = peer; - if (peer.IsHost) - this.HostPeer = peer; } break; // handle mod message - case SMultiplayer.ModMessageID: - this.ReceiveModMessage(message); - break; - } - } - - /// Process an incoming message from an approved connection. - /// The message to process. - public override void processIncomingMessage(IncomingMessage message) - { - switch (message.MessageType) - { - // handle mod message - case SMultiplayer.ModMessageID: + case (byte)MessageType.ModMessage: this.ReceiveModMessage(message); break; - // let game process message default: - base.processIncomingMessage(message); + resume(); break; } - } - /// Process an incoming network message from the server. + /// Process an incoming network message as a farmhand. /// The client instance that received the connection. /// The message to process. + /// Process the message using the game's default logic. /// Returns whether the message was handled. - public bool TryProcessMessageFromServer(SLidgrenClient client, IncomingMessage message) + public void OnClientProcessingMessage(SLidgrenClient client, IncomingMessage message, Action resume) { + if (message.MessageType != Multiplayer.farmerDelta && message.MessageType != Multiplayer.locationDelta && message.MessageType != Multiplayer.teamDelta && message.MessageType != Multiplayer.worldDelta) + this.Monitor.Log($"CLIENT RECV {(MessageType)message.MessageType} {message.FarmerID}", LogLevel.Alert); + switch (message.MessageType) { - // receive SMAPI context from a connected player - case SMultiplayer.ContextSyncMessageID: + // mod context sync (step 4) + case (byte)MessageType.ModContext: { // parse message - string data = message.Reader.ReadString(); - RemoteContextModel model = this.JsonHelper.Deserialise(data); - - // log info - if (model != null) - this.Monitor.Log($"Received context for {(model.IsHost ? "host" : "farmhand")} {message.FarmerID} running SMAPI {model.ApiVersion} with {model.Mods.Length} mods{(this.VerboseLogging ? $": {data}" : "")}.", LogLevel.Trace); - else - this.Monitor.Log($"Received context for player {message.FarmerID} running vanilla{(this.VerboseLogging ? $": {data}" : "")}.", LogLevel.Trace); + RemoteContextModel model = this.ReadContext(message.Reader); + this.Monitor.Log($"Received context for {(model?.IsHost == true ? "host" : "farmhand")} {message.FarmerID} running {(model != null ? $"SMAPI {model.ApiVersion} with {model.Mods.Length} mods" : "vanilla")}.", LogLevel.Trace); // store peer - MultiplayerPeer peer = MultiplayerPeer.ForConnectionToHost(message.FarmerID, model, client); + MultiplayerPeer peer = MultiplayerPeer.ForConnectionToHost(message.FarmerID, model, client, model?.IsHost ?? this.HostPeer == null); + if (peer.IsHost && this.HostPeer != null) + { + this.Monitor.Log($"Rejected mod context from host player {peer.PlayerID}: already received host data from {(peer.PlayerID == this.HostPeer.PlayerID ? "that player" : $"player {peer.PlayerID}")}.", LogLevel.Error); + return; + } this.Peers[message.FarmerID] = peer; if (peer.IsHost) this.HostPeer = peer; } - return true; + break; - // handle intro from unmodded player - case Multiplayer.playerIntroduction: - if (!this.Peers.ContainsKey(message.FarmerID)) + // handle server intro + case (byte)MessageType.ServerIntroduction: { // store peer - this.Monitor.Log($"Received connection for vanilla player {message.FarmerID}.", LogLevel.Trace); - var peer = MultiplayerPeer.ForConnectionToHost(message.FarmerID, null, client); - this.Peers[message.FarmerID] = peer; - if (peer.IsHost) - this.HostPeer = peer; + if (!this.Peers.ContainsKey(message.FarmerID) && this.HostPeer == null) + { + this.Monitor.Log($"Received connection for vanilla host {message.FarmerID}.", LogLevel.Trace); + this.Peers[message.FarmerID] = MultiplayerPeer.ForConnectionToHost(message.FarmerID, null, client, isHost: true); + } + resume(); + break; + } + + // handle player intro + case (byte)MessageType.PlayerIntroduction: + { + // store peer + if (!this.Peers.TryGetValue(message.FarmerID, out MultiplayerPeer peer)) + { + peer = MultiplayerPeer.ForConnectionToHost(message.FarmerID, null, client, isHost: this.HostPeer == null); + this.Monitor.Log($"Received connection for vanilla {(peer.IsHost ? "host" : "farmhand")} {message.FarmerID}.", LogLevel.Trace); + this.Peers[message.FarmerID] = peer; + if (peer.IsHost) + this.HostPeer = peer; + } } - return false; // handle mod message - case SMultiplayer.ModMessageID: + case (byte)MessageType.ModMessage: this.ReceiveModMessage(message); - return true; + break; default: - return false; + resume(); + break; } } @@ -352,12 +375,12 @@ namespace StardewModdingAPI.Framework if (playerIDs == null || playerIDs.Contains(peer.PlayerID)) { model.ToPlayerIDs = new[] { peer.PlayerID }; - peer.SendMessage(new OutgoingMessage(SMultiplayer.ModMessageID, peer.PlayerID, data)); + peer.SendMessage(new OutgoingMessage((byte)MessageType.ModMessage, peer.PlayerID, data)); } } } else if (this.HostPeer != null && this.HostPeer.HasSmapi) - this.HostPeer.SendMessage(new OutgoingMessage(SMultiplayer.ModMessageID, this.HostPeer.PlayerID, data)); + this.HostPeer.SendMessage(new OutgoingMessage((byte)MessageType.ModMessage, this.HostPeer.PlayerID, data)); else this.VerboseLog(" Can't send message because no valid connections were found."); @@ -367,6 +390,17 @@ namespace StardewModdingAPI.Framework /********* ** Private methods *********/ + /// Read the metadata context for a player. + /// The stream reader. + private RemoteContextModel ReadContext(BinaryReader reader) + { + string data = reader.ReadString(); + RemoteContextModel model = this.JsonHelper.Deserialise(data); + return model.ApiVersion != null + ? model + : null; // no data available for unmodded players + } + /// Receive a mod message sent from another player's mods. /// The raw message to parse. private void ReceiveModMessage(IncomingMessage message) @@ -392,7 +426,7 @@ namespace StardewModdingAPI.Framework { newModel.ToPlayerIDs = new[] { peer.PlayerID }; this.VerboseLog($" Forwarding message to player {peer.PlayerID}."); - peer.SendMessage(new OutgoingMessage(SMultiplayer.ModMessageID, peer.PlayerID, this.JsonHelper.Serialise(newModel, Formatting.None))); + peer.SendMessage(new OutgoingMessage((byte)MessageType.ModMessage, peer.PlayerID, this.JsonHelper.Serialise(newModel, Formatting.None))); } } } diff --git a/src/SMAPI/Patches/LidgrenServerPatch.cs b/src/SMAPI/Patches/LidgrenServerPatch.cs new file mode 100644 index 00000000..6f937665 --- /dev/null +++ b/src/SMAPI/Patches/LidgrenServerPatch.cs @@ -0,0 +1,89 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Reflection; +using Harmony; +using Lidgren.Network; +using StardewModdingAPI.Framework; +using StardewModdingAPI.Framework.Networking; +using StardewModdingAPI.Framework.Patching; +using StardewValley; +using StardewValley.Network; + +namespace StardewModdingAPI.Patches +{ + /// A Harmony patch to let SMAPI override methods. + internal class LidgrenServerPatch : IHarmonyPatch + { + /********* + ** Accessors + *********/ + /// A unique name for this patch. + public string Name => $"{nameof(LidgrenServerPatch)}"; + + + /********* + ** Public methods + *********/ + /// Apply the Harmony patch. + /// The Harmony instance. + public void Apply(HarmonyInstance harmony) + { + // override parseDataMessageFromClient + { + MethodInfo method = AccessTools.Method(typeof(LidgrenServer), "parseDataMessageFromClient"); + MethodInfo prefix = AccessTools.Method(this.GetType(), nameof(LidgrenServerPatch.Prefix_LidgrenServer_ParseDataMessageFromClient)); + harmony.Patch(method, new HarmonyMethod(prefix), null); + } + + // override sendMessage + { + MethodInfo method = typeof(LidgrenServer).GetMethod("sendMessage", BindingFlags.NonPublic | BindingFlags.Instance, null, new [] { typeof(NetConnection), typeof(OutgoingMessage) }, null); + MethodInfo prefix = AccessTools.Method(this.GetType(), nameof(LidgrenServerPatch.Prefix_LidgrenServer_SendMessage)); + harmony.Patch(method, new HarmonyMethod(prefix), null); + } + } + + + /********* + ** Private methods + *********/ + /// The method to call instead of the method. + /// The instance being patched. + /// The raw network message to parse. + /// The private peers field on the instance. + /// The private gameServer field on the instance. + /// Returns whether to execute the original method. + /// This method must be static for Harmony to work correctly. See the Harmony documentation before renaming arguments. + [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Argument names are defined by Harmony.")] + private static bool Prefix_LidgrenServer_ParseDataMessageFromClient(LidgrenServer __instance, NetIncomingMessage dataMsg, Bimap ___peers, IGameServer ___gameServer) + { + if (__instance is SLidgrenServer smapiServer) + { + smapiServer.ParseDataMessageFromClient(dataMsg); + return false; + } + + return true; + } + + /// The method to call instead of the method. + /// The instance being patched. + /// The connection to which to send the message. + /// The private peers field on the instance. + /// The private gameServer field on the instance. + /// Returns whether to execute the original method. + /// This method must be static for Harmony to work correctly. See the Harmony documentation before renaming arguments. + [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Argument names are defined by Harmony.")] + private static bool Prefix_LidgrenServer_SendMessage(LidgrenServer __instance, NetConnection connection, OutgoingMessage message, Bimap ___peers, IGameServer ___gameServer) + { + if (__instance is SLidgrenServer smapiServer) + { + smapiServer.SendMessage(connection, message); + return false; + } + + return true; + } + } +} diff --git a/src/SMAPI/Patches/NetworkingPatch.cs b/src/SMAPI/Patches/NetworkingPatch.cs deleted file mode 100644 index 12ccf84c..00000000 --- a/src/SMAPI/Patches/NetworkingPatch.cs +++ /dev/null @@ -1,103 +0,0 @@ -using System; -using System.Diagnostics.CodeAnalysis; -using System.IO; -using System.Reflection; -using Harmony; -using Lidgren.Network; -using StardewModdingAPI.Framework; -using StardewModdingAPI.Framework.Networking; -using StardewModdingAPI.Framework.Patching; -using StardewValley; -using StardewValley.Network; - -namespace StardewModdingAPI.Patches -{ - /// A Harmony patch to enable the SMAPI multiplayer metadata handshake. - internal class NetworkingPatch : IHarmonyPatch - { - /********* - ** Properties - *********/ - /// The constructor for the internal NetBufferReadStream type. - private static readonly ConstructorInfo NetBufferReadStreamConstructor = NetworkingPatch.GetNetBufferReadStreamConstructor(); - - - /********* - ** Accessors - *********/ - /// A unique name for this patch. - public string Name => $"{nameof(NetworkingPatch)}"; - - - /********* - ** Public methods - *********/ - /// Apply the Harmony patch. - /// The Harmony instance. - public void Apply(HarmonyInstance harmony) - { - MethodInfo method = AccessTools.Method(typeof(LidgrenServer), "parseDataMessageFromClient"); - MethodInfo prefix = AccessTools.Method(this.GetType(), nameof(NetworkingPatch.Prefix_LidgrenServer_ParseDataMessageFromClient)); - harmony.Patch(method, new HarmonyMethod(prefix), null); - } - - - /********* - ** Private methods - *********/ - /// The method to call instead of the method. - /// The instance being patched. - /// The raw network message to parse. - /// The private peers field on the instance. - /// The private gameServer field on the instance. - /// Returns whether to execute the original method. - /// This method must be static for Harmony to work correctly. See the Harmony documentation before renaming arguments. - [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Argument names are defined by Harmony.")] - private static bool Prefix_LidgrenServer_ParseDataMessageFromClient(LidgrenServer __instance, NetIncomingMessage dataMsg, Bimap ___peers, IGameServer ___gameServer) - { - // get SMAPI overrides - SMultiplayer multiplayer = ((SGame)Game1.game1).Multiplayer; - SLidgrenServer server = (SLidgrenServer)__instance; - - // add hook to call multiplayer core - NetConnection peer = dataMsg.SenderConnection; - using (IncomingMessage message = new IncomingMessage()) - using (Stream readStream = (Stream)NetworkingPatch.NetBufferReadStreamConstructor.Invoke(new object[] { dataMsg })) - using (BinaryReader reader = new BinaryReader(readStream)) - { - while (dataMsg.LengthBits - dataMsg.Position >= 8) - { - message.Read(reader); - if (___peers.ContainsLeft(message.FarmerID) && ___peers[message.FarmerID] == peer) - ___gameServer.processIncomingMessage(message); - else if (message.MessageType == Multiplayer.playerIntroduction) - { - NetFarmerRoot farmer = multiplayer.readFarmer(message.Reader); - ___gameServer.checkFarmhandRequest("", farmer, msg => server.SendMessage(peer, msg), () => ___peers[farmer.Value.UniqueMultiplayerID] = peer); - } - else - multiplayer.ProcessMessageFromUnknownFarmhand(__instance, dataMsg, message); // added hook - } - } - - return false; - } - - /// Get the constructor for the internal NetBufferReadStream type. - private static ConstructorInfo GetNetBufferReadStreamConstructor() - { - // get type - string typeName = $"StardewValley.Network.NetBufferReadStream, {Constants.GameAssemblyName}"; - Type type = Type.GetType(typeName); - if (type == null) - throw new InvalidOperationException($"Can't find type: {typeName}"); - - // get constructor - ConstructorInfo constructor = type.GetConstructor(new[] { typeof(NetBuffer) }); - if (constructor == null) - throw new InvalidOperationException($"Can't find constructor for type: {typeName}"); - - return constructor; - } - } -} diff --git a/src/SMAPI/StardewModdingAPI.csproj b/src/SMAPI/StardewModdingAPI.csproj index 11fa5d35..dfe55eb9 100644 --- a/src/SMAPI/StardewModdingAPI.csproj +++ b/src/SMAPI/StardewModdingAPI.csproj @@ -174,6 +174,7 @@ + @@ -322,7 +323,7 @@ - + -- cgit