private static bool Prefix(ref ZNet __instance, ZRpc rpc, ZPackage pkg) { if (__instance.IsServer()) { string self = ""; if (pkg.Size() > 32) { pkg.SetPos(pkg.Size() - 32 - 1); if (pkg.ReadByte() == (byte)32) { pkg.SetPos(pkg.GetPos() - 1); self = pkg.ReadString(); } } ZLog.Log((object)("[AntiMods]: Got client hash: " + self + "\nmine: " + VACPlugin.PluginsHash)); ZLog.LogWarning("Plugins Hash is Equals: " + !self.Equals(VACPlugin.PluginsHash) + " ForceMods: " + VACPlugin.forcesamemods.Value); ZLog.LogWarning("Is in Admin List: " + !ZNet.instance.m_adminList.Contains(rpc.GetSocket().GetHostName()) + "Admin Bypass: "******"[AntiMods]: Kicking Client: " + rpc.GetSocket().GetEndPointString() + " (incompatible mods)")); rpc.Invoke("Error", (object)num); return(false); } ZLog.Log((object)("[AntiMods]: Accepting Client: " + rpc.GetSocket().GetEndPointString())); } return(true); }
// code borrowed from https://github.com/Valheim-Modding/Wiki/wiki/Server-Validated-RPC-System and modified public static void RPC_RequestSetWeather(long sender, ZPackage pkg) { if (pkg != null && pkg.Size() > 0) { // Check that our Package is not null, and if it isn't check that it isn't empty. ZNetPeer peer = ZNet.instance.GetPeer(sender); // Get the Peer from the sender, to later check the SteamID against our Adminlist. if (peer != null) { // Confirm the peer exists string peerSteamID = ((ZSteamSocket)peer.m_socket).GetPeerID().m_SteamID.ToString(); // Get the SteamID from peer. if ( ZNet.instance.m_adminList != null && ZNet.instance.m_adminList.Contains(peerSteamID) ) { // Check that the SteamID is in our Admin List. string msg = pkg.ReadString(); // Read the message from the user. pkg.SetPos(0); // Reset the position of our cursor so the client's can re-read the package. ZRoutedRpc.instance.InvokeRoutedRPC(0L, "EventSetWeather", new object[] { pkg }); // Send our Event to all Clients. 0L specifies that it will be sent to everybody EnvMan.instance.m_debugEnv = msg; } } else { ZPackage newPkg = new ZPackage(); // Create a new ZPackage. newPkg.Write("You aren't an Admin!"); // Tell them what's going on. ZRoutedRpc.instance.InvokeRoutedRPC(sender, "BadRequestMsg", new object[] { newPkg }); // Send the error message. } } }
public static void OnServerCheckPin(ZRpc client, ZPackage data) { if (!Store.IsSharingPin()) { return; } data.SetPos(0); Utility.Log("Client checked pin by server"); var pin = ExplorationDatabase.UnpackPin(data); var state = data.ReadBool(); foreach (var clientPin in ExplorationDatabase.ClientPins.ToList()) { if (UtilityPin.ArePinsEqual(clientPin, pin)) { clientPin.Checked = state; var mapPin = UtilityPin.GetMapPin(clientPin); if (mapPin != null) { mapPin.m_checked = state; } } } }
public static void OnClientRemovePin(ZRpc client, ZPackage pinData) { if (!Store.IsSharingPin()) { return; } pinData.SetPos(0); var znet = Traverse.Create(typeof(ZNet)).Field("m_instance").GetValue() as ZNet; var mPeers = Traverse.Create((znet)).Field("m_peers").GetValue() as List <ZNetPeer>; var pin = ExplorationDatabase.UnpackPin(pinData); ExplorationDatabase.RemovePinEqual(pin); Utility.Log("Server deleted pin by client"); foreach (var peer in mPeers) { if (peer.IsReady()) { if (peer.m_rpc == client) { continue; } peer.m_rpc.Invoke("OnServerRemovePin", (object)ExplorationDatabase.PackPin(pin)); } } if (client != null) { OnServerRemovePin(null, ExplorationDatabase.PackPin(pin)); } }
public static void OnServerRemovePin(ZRpc _, ZPackage pinData) { if (!Store.IsSharingPin()) { return; } pinData.SetPos(0); Utility.Log("Client deleted pin by server"); var pin = ExplorationDatabase.UnpackPin(pinData); foreach (var clientPin in ExplorationDatabase.ClientPins.ToList()) { if (UtilityPin.ArePinsEqual(clientPin, pin)) { ExplorationDatabase.ClientPins.Remove(clientPin); } } var mapPin = UtilityPin.GetMapPin(pin); if (mapPin == null) { return; } _Minimap.RemovePin(_Minimap._instance, mapPin); }
/// <summary> /// Coroutine to send a package to a single target. Compresses and fragments the package if necessary. /// </summary> /// <param name="target"></param> /// <param name="package"></param> /// <returns></returns> public IEnumerator SendPackageRoutine(long target, ZPackage package) { if (!ZNet.instance) { return(Enumerable.Empty <object>().GetEnumerator()); } List <ZNetPeer> peers = ZRoutedRpc.instance.m_peers; if (target == ZRoutedRpc.instance.m_id || target == ZRoutedRpc.Everybody) { byte[] originalData = package.GetArray(); ZPackage jotunnpackage = new ZPackage(); jotunnpackage.Write(originalData); jotunnpackage.SetPos(0); ZNet.instance.StartCoroutine( HandlePackageRoutine(ZRoutedRpc.instance.m_id, jotunnpackage, JOTUNN_PACKAGE)); } else { peers = peers.Where(p => p.m_uid == target).ToList(); } return(SendPackageRoutine(peers, package)); }
private void ZSteamSocket_Send(ZSteamSocket self, ZPackage pkg) { if (!(_isModEnabled.Value && _isOutputEnabled.Value)) { return; } pkg.SetPos(0); int methodHash = pkg.ReadInt(); if (methodHash == 0) { Logger.LogMessage($"Sending RPC Ping to {self.GetHostName()}"); } else { try { string method = pkg.ReadString(); if (method == "RoutedRPC") { ZPackage wrapped = pkg.ReadPackage(); _ = wrapped.ReadInt(); method = pkg.ReadString(); } Logger.LogMessage($"Sending RPC {method} to {self.GetHostName()}"); } catch (Exception) { } } }
private void ZSteamSocket_Recv(ZSteamSocket self, ZPackage pkg) { if (!(_isModEnabled.Value && _isOutputEnabled.Value)) { return; } if (pkg != null) { int methodHash = pkg.ReadInt(); if (methodHash == 0) { Logger.LogMessage($"Received RPC Ping"); } else { try { string method = pkg.ReadString(); if (method == "RoutedRPC") { ZPackage wrapped = pkg.ReadPackage(); _ = wrapped.ReadInt(); method = pkg.ReadString(); } Logger.LogMessage($"Received RPC {method}"); } catch (Exception) { } } pkg.SetPos(0); } }
public static void RPC_RequestSetTime(long sender, ZPackage pkg) { if (pkg != null && pkg.Size() > 0) { // Check that our Package is not null, and if it isn't check that it isn't empty. ZNetPeer peer = ZNet.instance.GetPeer(sender); // Get the Peer from the sender, to later check the SteamID against our Adminlist. if (peer != null) { // Confirm the peer exists string peerSteamID = ((ZSteamSocket)peer.m_socket).GetPeerID().m_SteamID.ToString(); // Get the SteamID from peer. if ( ZNet.instance.m_adminList != null && ZNet.instance.m_adminList.Contains(peerSteamID) ) { // Check that the SteamID is in our Admin List. // set server tod String tod_str = pkg.ReadString(); if (tod_str == "sync") { pkg.Clear(); tod_str = EnvMan.instance.m_debugTime.ToString(); pkg.Write(tod_str); } float tod = float.Parse(tod_str); if (tod < 0f) { EnvMan.instance.m_debugTimeOfDay = false; } else { EnvMan.instance.m_debugTimeOfDay = true; EnvMan.instance.m_debugTime = Mathf.Clamp01(tod); } pkg.SetPos(0); string msg = pkg.ReadString(); // Read the message from the user. pkg.SetPos(0); // Reset the position of our cursor so the client's can re-read the package. ZRoutedRpc.instance.InvokeRoutedRPC(0L, "EventSetTime", new object[] { pkg }); // Send our Event to all Clients. 0L specifies that it will be sent to everybody UnityEngine.Debug.Log("changing time of day..."); } } else { ZPackage newPkg = new ZPackage(); // Create a new ZPackage. newPkg.Write("You aren't an Admin!"); // Tell them what's going on. ZRoutedRpc.instance.InvokeRoutedRPC(sender, "BadRequestMsg", new object[] { newPkg }); // Send the error message. } } }
public static void OnReceiveMapDataInitial(ZRpc client, ZPackage mapData) { if (!Store.IsSharingMap()) { return; } mapData.SetPos(0); var chunk = mapData.ReadInt(); //Utility.Log("Client received initial map data by server chunk " + (chunk+1) + "/" + CHUNKS); var explored = ExplorationDatabase.UnpackBoolArray(mapData, ExplorationDatabase.MapSizeSquared / CHUNKS); var startIndex = chunk * (ExplorationDatabase.MapSizeSquared / CHUNKS); for (var index = 0; index < explored.Length; index++) { if (explored[index]) { _Minimap.Explore(_Minimap._instance, (startIndex + index) % ExplorationDatabase.MapSize, (startIndex + index) / ExplorationDatabase.MapSize); } } var fogTexture = Traverse.Create((_Minimap._instance)).Field("m_fogTexture").GetValue() as Texture2D; fogTexture.Apply(); _ZNet._instance.StartCoroutine(SendChunkToServer(client, chunk)); // var explored = ExplorationDatabase.UnpackBoolArray(mapData); // // for (var index = 0; index < explored.Length; index++) // { // if (explored[index]) // { // _Minimap.Explore(_Minimap._instance, index % ExplorationDatabase.MapSize, index / ExplorationDatabase.MapSize); // } // } // // var fogTexture = Traverse.Create((_Minimap._instance)).Field("m_fogTexture").GetValue() as Texture2D; // fogTexture.Apply(); // // explored = Traverse.Create(_Minimap._instance).Field("m_explored").GetValue() as bool[]; // var z = ExplorationDatabase.PackBoolArray(explored); // if (_ZNet.IsServer(_ZNet._instance)) // { // OnClientInitialData(null, z); // } // else // { // var znet = Traverse.Create(typeof(ZNet)).Field("m_instance").GetValue() as ZNet; // ZRpc server = _ZNet.GetServerRPC(znet); // server.Invoke("OnClientInitialData", (object) z); // } }
public static void SendMapDataToClient(long peerId, string mapData) { ZPackage zpg = new ZPackage(); var mapdataArray = new object[] { mapData }; zpg.Write(mapData); zpg.SetPos(0); Utils.Log($"Sending mapdata size: {mapData.Length} to client {peerId}."); ZNet.instance.m_routedRpc.InvokeRoutedRPC(peerId, "ReceiveMapData", (object)zpg); }
// TODO: Move to ExplorationMapSync.cs public static void OnReceiveMapData(ZRpc client, ZPackage mapData) { mapData.SetPos(0); var x = mapData.ReadInt(); var y = mapData.ReadInt(); var m = Traverse.Create(typeof(Minimap)).Field("m_instance").GetValue() as Minimap; var flag = _Minimap.Explore(m, x, y); _dirty = flag || _dirty; }
public static ZPackage PackPin(PinData pin, bool skipSetPos = false) { var z = new ZPackage(); z.Write(pin.Name); z.Write(pin.Pos); z.Write((int)pin.Type); z.Write(pin.Checked); if (!skipSetPos) { z.SetPos(0); } return(z); }
public static ZPackage Default() { var z = new ZPackage(); z.Write((int)3); z.Write(MapSize); for (var i = 0; i < MapSizeSquared; i++) { z.Write(false); } z.Write((int)0); z.SetPos(0); return(z); }
private static void SendModVersionToClient(long peerID, string instancePluginVersion) { if (!ZNet.instance.IsDedicated() || !ZNet.instance.IsServer()) { return; } ZPackage zpg = new ZPackage(); var version = new object[] { instancePluginVersion }; ZRpc.Serialize(version, ref zpg); zpg.SetPos(0); Utils.Log($"Sending mod version {version} to client to be checked."); ZNet.instance.m_routedRpc.InvokeRoutedRPC(peerID, "CheckMapSharingModVersion", (object)zpg); }
public static void OnServerAddPin(ZRpc client, ZPackage pinData) { if (!Store.IsSharingPin()) { return; } pinData.SetPos(0); var pin = ExplorationDatabase.UnpackPin(pinData); _Minimap.AddPin(_Minimap._instance, pin.Pos, pin.Type, pin.Name, false, pin.Checked, 0); ExplorationDatabase.ClientPins.Add(pin); Utility.Log("Client received pin by server"); }
public static ZPackage PackPins(List <PinData> pins) { var z = new ZPackage(); z.Write((int)pins.Count); foreach (var pin in pins) { z.Write(pin.Name); z.Write(pin.Pos); z.Write((int)pin.Type); z.Write(pin.Checked); } z.SetPos(0); Utility.Log("Packing pins: " + pins.Count); return(z); }
public static void OnClientInitialData(ZRpc client, ZPackage mapData) { if (!Store.IsSharingMap()) { return; } mapData.SetPos(0); var chunk = mapData.ReadInt(); var startIndex = chunk * (ExplorationDatabase.MapSizeSquared / CHUNKS); var size = ExplorationDatabase.MapSizeSquared / CHUNKS; //Utility.Log("Server received initial map data by client chunk " + (chunk+1) + "/" + CHUNKS); ExplorationDatabase.MergeExplorationArray(ExplorationDatabase.UnpackBoolArray(mapData, size), startIndex, size); SendChunkToClient(client, chunk + 1); }
public void Initialize(BountyInfo bounty, string monsterID, bool isAdd) { _zdo.Set(BountyIDKey, bounty.ID); var pkg = new ZPackage(); bounty.ToPackage(pkg); pkg.SetPos(0); _zdo.Set(BountyDataKey, pkg.GetBase64()); _zdo.Set(MonsterIDKey, monsterID); _zdo.Set(IsAddKey, isAdd); _zdo.Set(BountyTargetNameKey, GetTargetName(_character.m_name, isAdd, bounty.TargetName)); _character.SetLevel(GetTargetLevel(bounty, monsterID, isAdd)); _character.SetMaxHealth(GetModifiedMaxHealth(_character, bounty, isAdd)); _character.m_baseAI.SetPatrolPoint(); Reinitialize(); }
private static void ServerTransmitMapData(ZPackage zpkg) { var rString = zpkg.ReadString(); zpkg.SetPos(0); var validData = MapData.ParseReceivedMapData(rString, out var sentFrom, out var sentTo, out var pluginVersion, out var pins, out var mapData); if (validData) { Debug.Log($"Valid map data found retransmitting..."); var peer = ZNet.instance.GetPeerByPlayerName(sentTo); if (peer != null) { Utils.Log($"Retransmitting Map Data to {peer.m_playerName}"); SendMapDataToClient(peer.m_uid, rString); } } }
/// <summary> /// Apply exploration data to local map (server and client) /// </summary> /// <param name="mapData"></param> public static void ApplyMapData(ZPackage mapData) { try { var isServer = ZNet.instance.IsServerInstance(); mapData.SetPos(0); using (var gz = new ZlibStream(mapData.m_stream, CompressionMode.Decompress)) { using (var br = new BinaryReader(gz)) { var state = br.ReadBoolean(); var idx = 0; while (idx < Minimap.instance.m_explored.Length) { var count = br.ReadInt32(); while (count > 0) { if (state && !isServer) { // Use local helper to prevent enqueuing again for sending ExploreLocal(idx % Minimap.instance.m_textureSize, idx / Minimap.instance.m_textureSize); } else if (state) { Minimap.instance.m_explored[idx] |= state; } idx++; count--; } state = !state; } } } } catch (Exception ex) { Logger.LogError($"Application of mapdata gone wrong.{Environment.NewLine}{ex.Message}{Environment.NewLine}{ex.StackTrace}"); Logger.LogError("Texture size: " + Minimap.instance.m_textureSize); } }
private static void SendConfigToClient(long peerID) { if (!ZNet.instance.IsDedicated() || !ZNet.instance.IsServer()) { return; } Utils.Log("Sending server side configs to client."); ZPackage zpg = new ZPackage(); var configSettings = Settings.MapSettings.ServerConfigs; var settings = new List <object>(); foreach (var configSetting in configSettings) { Utils.Log($"Forcing server config on client: {configSetting.Key}: {Settings.MapSettings.ConfigEntries[configSetting.Key].BoxedValue}"); var settingsValue = Settings.MapSettings.ConfigEntries[configSetting.Key].BoxedValue; settings.Add(settingsValue); } ZRpc.Serialize(settings.ToArray(), ref zpg); zpg.SetPos(0); ZNet.instance.m_routedRpc.InvokeRoutedRPC(peerID, "SetMapSharingConfigValues", (object)zpg); }
public static void OnClientCheckPin(ZRpc client, ZPackage data) { if (!Store.IsSharingPin()) { return; } data.SetPos(0); Utility.Log("Server checked pin by client"); var pin = ExplorationDatabase.UnpackPin(data); var state = data.ReadBool(); ExplorationDatabase.SetPinState(pin, state); var znet = Traverse.Create(typeof(ZNet)).Field("m_instance").GetValue() as ZNet; var mPeers = Traverse.Create((znet)).Field("m_peers").GetValue() as List <ZNetPeer>; foreach (var peer in mPeers) { if (peer.IsReady()) { if (peer.m_rpc == client) { continue; } var z = ExplorationDatabase.PackPin(pin, true); z.Write(state); peer.m_rpc.Invoke("OnServerCheckPin", (object)z); } } if (client != null) { var z = ExplorationDatabase.PackPin(pin, true); z.Write(state); OnServerCheckPin(null, z); } }
/// <summary> /// Create from ZPackage /// </summary> /// <param name="pkg"></param> public ModuleVersionData(ZPackage pkg) { try { // Needed !! pkg.SetPos(0); ValheimVersion = new System.Version(pkg.ReadInt(), pkg.ReadInt(), pkg.ReadInt()); var numberOfModules = pkg.ReadInt(); while (numberOfModules > 0) { Modules.Add(new Tuple <string, System.Version, CompatibilityLevel, VersionStrictness>(pkg.ReadString(), new System.Version(pkg.ReadInt(), pkg.ReadInt(), pkg.ReadInt()), (CompatibilityLevel)pkg.ReadInt(), (VersionStrictness)pkg.ReadInt())); numberOfModules--; } } catch (Exception ex) { Logger.LogError("Could not deserialize version message data from zPackage"); Logger.LogError(ex.Message); } }
public static void RPC_RequestSetVisible(long sender, ZPackage pkg) { ZNetPeer peer = ZNet.instance.GetPeer(sender); // Get the Peer from the sender, to later check the SteamID against our Adminlist. if (peer != null) { // Confirm the peer exists string peerSteamID = ((ZSteamSocket)peer.m_socket).GetPeerID().m_SteamID.ToString(); // Get the SteamID from peer. if ( ZNet.instance.m_adminList != null && ZNet.instance.m_adminList.Contains(peerSteamID) ) { // Check that the SteamID is in our Admin List. // set server tod string name = pkg.ReadString(); bool vis = pkg.ReadBool(); if (!vis && !GamanMaker.invisible_players.Contains(name)) { GamanMaker.invisible_players.Add(name); } else if (vis && GamanMaker.invisible_players.Contains(name)) { GamanMaker.invisible_players.Remove(name); } pkg.SetPos(0); ZRoutedRpc.instance.InvokeRoutedRPC(0L, "EventSetVisible", new object[] { pkg }); } } else { ZPackage newPkg = new ZPackage(); // Create a new ZPackage. newPkg.Write("You aren't an Admin!"); // Tell them what's going on. ZRoutedRpc.instance.InvokeRoutedRPC(sender, "BadRequestMsg", new object[] { newPkg }); // Send the error message. } }
public static bool Prefix(ref ZRoutedRpc __instance, ref ZRoutedRpc.RoutedRPCData rpcData) { if (VPlusChatFilter.isEnabled.Value) { if (rpcData.m_methodHash == "ChatMessage".GetStableHashCode()) { ZPackage payload = rpcData.m_parameters; VPlusChatFilter.chatFilterLogger.LogDebug("ChatMessage Sent"); payload.SetPos(0); VPlusChatFilter.chatFilterLogger.LogDebug("Size of package is " + payload.Size()); VPlusChatFilter.chatFilterLogger.LogDebug("Read byte test : " + payload.ReadInt()); payload.SetPos(0); Vector3 headPoint = payload.ReadVector3(); VPlusChatFilter.chatFilterLogger.LogDebug("Read head : " + headPoint.ToString()); int messageType = payload.ReadInt(); VPlusChatFilter.chatFilterLogger.LogDebug("Read type : " + messageType); string playerName = payload.ReadString(); VPlusChatFilter.chatFilterLogger.LogDebug("Read name : " + playerName); string message = payload.ReadString(); VPlusChatFilter.chatFilterLogger.LogDebug("Read message : " + message); var profanities = FamilyFriendlyfier.filter.DetectAllProfanities(message, true); if (profanities.Count > 0) { foreach (string bannable in profanities) { VPlusChatFilter.chatFilterLogger.LogInfo("Bad word from " + playerName + " : " + bannable); } message = FamilyFriendlyfier.filter.CensorString(message, VPlusChatFilter.replaceKey.Value[0]); } VPlusChatFilter.chatFilterLogger.LogDebug("New message : " + message); ZPackage newpayload = new ZPackage(); ZRpc.Serialize(new object[] { headPoint, messageType, playerName, message }, ref newpayload); rpcData.m_parameters = newpayload; } else if (rpcData.m_methodHash == "Say".GetStableHashCode()) { ZPackage payload = rpcData.m_parameters; VPlusChatFilter.chatFilterLogger.LogDebug("Say Sent"); payload.SetPos(0); VPlusChatFilter.chatFilterLogger.LogDebug("Size of package is " + payload.Size()); VPlusChatFilter.chatFilterLogger.LogDebug("Read byte test : " + payload.ReadInt()); payload.SetPos(0); int messageType = payload.ReadInt(); VPlusChatFilter.chatFilterLogger.LogDebug("Read type : " + messageType); string playerName = payload.ReadString(); VPlusChatFilter.chatFilterLogger.LogDebug("Read name : " + playerName); string message = payload.ReadString(); VPlusChatFilter.chatFilterLogger.LogDebug("Read message : " + message); var profanities = FamilyFriendlyfier.filter.DetectAllProfanities(message, true); if (profanities.Count > 0) { foreach (string bannable in profanities) { VPlusChatFilter.chatFilterLogger.LogInfo("Bad word from " + playerName + " : " + bannable); } message = FamilyFriendlyfier.filter.CensorString(message, VPlusChatFilter.replaceKey.Value[0]); } VPlusChatFilter.chatFilterLogger.LogDebug("New message : " + message); ZPackage newpayload = new ZPackage(); ZRpc.Serialize(new object[] { messageType, playerName, message }, ref newpayload); rpcData.m_parameters = newpayload; } ZPackage zpackage = new ZPackage(); rpcData.Serialize(zpackage); if (__instance.m_server) { if (rpcData.m_targetPeerID != 0L) { ZNetPeer peer = __instance.GetPeer(rpcData.m_targetPeerID); if (peer != null && peer.IsReady()) { peer.m_rpc.Invoke("RoutedRPC", new object[] { zpackage }); return(false); } return(false); } else { using (List <ZNetPeer> .Enumerator enumerator = __instance.m_peers.GetEnumerator()) { while (enumerator.MoveNext()) { ZNetPeer znetPeer = enumerator.Current; if (rpcData.m_senderPeerID != znetPeer.m_uid && znetPeer.IsReady()) { znetPeer.m_rpc.Invoke("RoutedRPC", new object[] { zpackage }); } } return(false); } } } foreach (ZNetPeer znetPeer2 in __instance.m_peers) { if (znetPeer2.IsReady()) { znetPeer2.m_rpc.Invoke("RoutedRPC", new object[] { zpackage }); } } } return(true); }