Exemple #1
0
        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);
        }
Exemple #2
0
        /// <summary>
        ///     Apply a partial config to server and send to other clients.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="configPkg"></param>
        internal void RPC_Jotunn_ApplyConfig(long sender, ZPackage configPkg)
        {
            if (ZNet.instance.IsClientInstance())
            {
                if (configPkg != null && configPkg.Size() > 0 && sender == ZNet.instance.GetServerPeer().m_uid)
                {
                    Logger.LogDebug("Received configuration data from server");
                    ApplyConfigZPackage(configPkg);
                }
            }

            if (ZNet.instance.IsServerInstance() || ZNet.instance.IsLocalInstance())
            {
                // Is package not empty and is sender admin?
                if (configPkg != null && configPkg.Size() > 0 && ZNet.instance.m_adminList.Contains(ZNet.instance.GetPeer(sender)?.m_socket?.GetHostName()))
                {
                    Logger.LogDebug($"Received configuration data from client {sender}");

                    // Send to all other clients
                    foreach (var peer in ZNet.instance.m_peers.Where(x => x.m_uid != sender))
                    {
                        ZRoutedRpc.instance.InvokeRoutedRPC(peer.m_uid, nameof(RPC_Jotunn_ApplyConfig), configPkg);
                    }

                    // Apply config locally
                    ApplyConfigZPackage(configPkg);
                }
            }
        }
Exemple #3
0
 // 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.
         }
     }
 }
Exemple #4
0
        public static void RPC_ConfigSync(long sender, ZPackage configPkg)
        {
            if (ZNet.m_isServer) //Server
            {
                Logger.LogInfo($"Sending configuration data to peer #{sender}");

                if (Configuration.Current == null)
                {
                    Configuration.LoadConfiguration();
                }

                var pkg  = new ZPackage();
                var data = Configuration.Current.GetSyncableSections();

                //Add number of clean lines to package
                pkg.Write(data);

                ZRoutedRpc.instance.InvokeRoutedRPC(sender, nameof(RPC_ConfigSync), pkg);
            }
            else //Client
            {
                if (configPkg != null && configPkg.Size() > 0 && sender == ZRoutedRpc.instance.GetServerPeerID()
                    ) // Validate the message is from the server and not another client.
                {
                    Logger.LogInfo("Received configuration data from server.");

                    var receivedConfig = new Configuration();
                    Configuration.LoadFromIniString(receivedConfig, configPkg.ReadString());

                    Configuration.SetSyncableValues(receivedConfig);
                }
            }
        }
Exemple #5
0
        /// <summary>
        ///     RPC to handle initial sync to a new peer
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="teleporterZPackage"></param>
        public static void RPC_TeleporterSyncInit(long sender, ZPackage teleporterZPackage)
        {
            // SERVER SIDE
            if (ZNet.instance.IsServerInstance() || ZNet.instance.IsLocalInstance())
            {
                Logger.LogInfo($"Sending portal data to peer #{sender}");

                var portals = PortalList.GetPortals();

                if (ZNet.instance.IsLocalInstance())
                {
                    UpdatePins(portals);
                }

                var package = portals.ToZPackage();
                ZRoutedRpc.instance.InvokeRoutedRPC(sender, nameof(RPC_TeleporterSyncInit), package);
            }

            // CLIENT SIDE
            if (ZNet.instance.IsClientInstance())
            {
                if (teleporterZPackage != null && teleporterZPackage.Size() > 0 && sender == ZRoutedRpc.instance.GetServerPeerID())
                {
                    // Read package and create pins from portal list
                    Logger.LogInfo("Received portal data from server");

                    portalsFromServer = PortalList.FromZPackage(teleporterZPackage);

                    UpdatePins(portalsFromServer);
                }
            }
        }
Exemple #6
0
        private static void RPC_DropThatReceiveDataTest(ZRpc rpc, ZPackage pkg)
        {
            int packageSize = pkg.Size();

            ReceivedCount++;
            ReceivedBytes += packageSize;

            Log.LogInfo($"Received package {ReceivedCount} with size {packageSize}. Total received: {ReceivedBytes}");
        }
Exemple #7
0
        /// <summary>
        ///     Receive and handle an incoming package
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="package"></param>
        internal void ReceivePackage(long sender, ZPackage package)
        {
            if (package == null || package.Size() <= 0)
            {
                return;
            }

            Logger.LogDebug($"[{ID}] Received package");
            try
            {
                CacheExpirations.RemoveAll(kv =>
                {
                    if (kv.Key < DateTimeOffset.Now.Ticks)
                    {
                        PackageCache.Remove(kv.Value);
                        return(true);
                    }

                    return(false);
                });

                byte packageFlags = package.ReadByte();

                if ((packageFlags & FRAGMENTED_PACKAGE) != 0)
                {
                    long   uniqueIdentifier = package.ReadLong();
                    string cacheKey         = sender.ToString() + uniqueIdentifier;
                    int    fragment         = package.ReadInt();
                    int    fragments        = package.ReadInt();

                    if (!PackageCache.TryGetValue(cacheKey, out SortedDictionary <int, byte[]> dataFragments))
                    {
                        dataFragments          = new SortedDictionary <int, byte[]>();
                        PackageCache[cacheKey] = dataFragments;
                        CacheExpirations.Add(new KeyValuePair <long, string>(DateTimeOffset.Now.AddSeconds(60).Ticks, cacheKey));
                    }

                    dataFragments.Add(fragment, package.ReadByteArray());

                    if (dataFragments.Count < fragments)
                    {
                        return;
                    }

                    PackageCache.Remove(cacheKey);

                    package      = new ZPackage(dataFragments.Values.SelectMany(a => a).ToArray());
                    packageFlags = package.ReadByte();
                }

                ZNet.instance.StartCoroutine(HandlePackageRoutine(sender, package, packageFlags));
            }
            catch (Exception e)
            {
                Logger.LogWarning($"[{ID}] Error caught while applying package: {e}");
            }
        }
Exemple #8
0
        /// <summary>
        ///     Coroutine to send a package to a list of peers. Compresses and fragments the package if necessary.
        /// </summary>
        /// <param name="peers"></param>
        /// <param name="package"></param>
        /// <returns></returns>
        public IEnumerator SendPackageRoutine(List <ZNetPeer> peers, ZPackage package)
        {
            if (!ZNet.instance)
            {
                yield break;
            }

            if (peers.Count == 0)
            {
                yield break;
            }

            try
            {
                ++SendCount;

                byte[]   originalData  = package.GetArray();
                ZPackage jotunnpackage = new ZPackage();
                jotunnpackage.Write(JOTUNN_PACKAGE);
                jotunnpackage.Write(originalData);
                package = jotunnpackage;

                const int compressMinSize = 10000;

                if (package.Size() > compressMinSize)
                {
                    byte[] rawData = package.GetArray();
                    Logger.LogDebug($"[{ID}] Compressing package with length {rawData.Length}");

                    ZPackage compressedPackage = new ZPackage();
                    compressedPackage.Write(COMPRESSED_PACKAGE);
                    MemoryStream output = new MemoryStream();
                    using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal))
                    {
                        deflateStream.Write(rawData, 0, rawData.Length);
                    }

                    compressedPackage.Write(output.ToArray());
                    package = compressedPackage;
                }

                List <IEnumerator <bool> > writers =
                    peers.Where(peer => peer.IsReady()).Select(p => SendToPeer(p, package)).ToList();
                writers.RemoveAll(writer => !writer.MoveNext());
                while (writers.Count > 0)
                {
                    yield return(null);

                    writers.RemoveAll(writer => !writer.MoveNext());
                }
            }
            finally
            {
                --SendCount;
            }
        }
 // Token: 0x0600098C RID: 2444 RVA: 0x0004612C File Offset: 0x0004432C
 public void Send(ZPackage pkg)
 {
     if (pkg.Size() == 0)
     {
         return;
     }
     if (!this.IsConnected())
     {
         return;
     }
     byte[] array = pkg.GetArray();
     this.m_sendQueue.Enqueue(array);
     this.SendQueuedPackages();
 }
Exemple #10
0
 public static void ProcessZDOs(long sender, ZPackage pkg)
 {
     //Def_handy_portals.logger.LogWarning("ProcessZDOs pkg.size:" + pkg.Size());
     if (pkg != null && pkg.Size() > 0)
     {
         int count = pkg.ReadInt();
         //Def_handy_portals.logger.LogWarning("zdos count: " + count);
         while (count > 0)
         {
             ZDOID zdoid = pkg.ReadZDOID();
             //Def_handy_portals.logger.LogWarning("zdoid: " + zdoid + "prefab: ");
             count--;
         }
     }
 }
Exemple #11
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.
                }
            }
        }
Exemple #12
0
        // public static void OnClientSkillUpdate(long sender, String playerName, String skill, int level){
        //     // EpicTitles.Log.LogInfo($"Received SkillUpdate from {playerName} on {skill}:{level}");
        //     var byteLevel = (byte)level;
        //     if (byteLevel % 10 == 0) {
        //         // send the notification to other peers
        //         // EpicTitles.Log.LogInfo($"Sending notification of SkillRankUp of {playerName} on {skill}");
        //         var _playerName = playerName;
        //         if (playerName == "Tomu") _playerName = "Paloma";
        //         // TODO use Message() on Player class!
        //         NotifityOtherClients(sender, $"{_playerName} is now a {PatchedSkills.getSkillRank(byteLevel)} {PatchedSkills.getSkillTitle(skill)}!");
        //     }

        //     updateLadder(playerName, skill, byteLevel);
        //     // if (skillLadders.ContainsKey(skill))
        //     //     skillLadders[skill][playerName] = byteLevel;
        //     // else
        //     //     skillLadders[skill] = new Dictionary<string, byte>(){{playerName, byteLevel}};
        // }

        // public static void OnSpawnedClientSkillUpdate(long sender, String playerName, ZPackage pkg){
        public static void OnClientSkillUpdate(long sender, String playerName, ZPackage pkg)
        {
            if (pkg != null && pkg.Size() > 0)
            {
                int numLines = pkg.ReadInt();
                if (numLines == 0)
                {
                    EpicTitles.Log.LogError("Got zero line config file from server. Cannot load.");
                    return;
                }

                for (int i = 0; i < numLines; i++)
                {
                    string    line   = pkg.ReadString();
                    string [] words  = line.Split(':');
                    string    skill  = words[0].ToLower();
                    string    _skill = words[0];
                    byte      level  = Byte.Parse(words[1]);

                    EpicTitles.Log.LogInfo($"{playerName}|RECEIVED SKILL:{_skill}:{level}");

                    updateLadder(playerName, skill, level);

                    // if (skillLadders.ContainsKey(skill))
                    //     skillLadders[skill][playerName] = byteLevel;
                    // else
                    //     skillLadders[skill] = new Dictionary<string, byte>(){{playerName, byteLevel}};
                    if (numLines == 1)   // OnSkillLevelup
                    {
                        if (level % 10 == 0)
                        {
                            // send the notification to other peers
                            // EpicTitles.Log.LogInfo($"Sending notification of SkillRankUp of {playerName} on {skill}");
                            var _playerName = playerName;
                            if (playerName == "Tomu")
                            {
                                _playerName = "Paloma";
                            }
                            // TODO use Message() on Player class!
                            NotifityOtherClients(sender, _playerName, _skill, level);
                        }
                    }
                }
                // EpicTitles.Log.LogError($"{playerName}: {item.m_info.m_skill}=>{item.m_level}");
                // item.m_info.m_icon SKILL ICON!
            }
        }
 public static void RPC_SyncServerConfig(long sender, ZPackage pkg)
 {
     if (ZNet.IsServer() && _ServerIsAuthoritative.Value)
     {
         SendConfigToClient(sender);
     }
     else if (!ZNet.IsServer() && pkg != null && pkg.Size() > 0)
     {
         //Only read configs from the server.
         long?serverPeerID = AccessTools.Method(typeof(ZRoutedRpc), "GetServerPeerID").Invoke(ZRoutedRpc.instance, null) as long?;
         if (serverPeerID == sender)
         {
             //Client handle recieving config
             ReadConfigPkg(pkg);
         }
     }
 }
 // Token: 0x060009AB RID: 2475 RVA: 0x0004694C File Offset: 0x00044B4C
 public void Send(ZPackage pkg)
 {
     if (pkg.Size() == 0)
     {
         return;
     }
     if (!this.IsConnected())
     {
         return;
     }
     byte[] array  = pkg.GetArray();
     byte[] bytes  = BitConverter.GetBytes(array.Length);
     byte[] array2 = new byte[array.Length + bytes.Length];
     bytes.CopyTo(array2, 0);
     array.CopyTo(array2, 4);
     this.m_sendQueue.Enqueue(array);
     this.SendQueuedPackages();
 }
 // Token: 0x06000992 RID: 2450 RVA: 0x00046288 File Offset: 0x00044488
 public ZPackage Recv()
 {
     if (!this.IsConnected())
     {
         return(null);
     }
     IntPtr[] array = new IntPtr[1];
     if (SteamNetworkingSockets.ReceiveMessagesOnConnection(this.m_con, array, 1) == 1)
     {
         SteamNetworkingMessage_t steamNetworkingMessage_t = Marshal.PtrToStructure <SteamNetworkingMessage_t>(array[0]);
         byte[] array2 = new byte[steamNetworkingMessage_t.m_cbSize];
         Marshal.Copy(steamNetworkingMessage_t.m_pData, array2, 0, steamNetworkingMessage_t.m_cbSize);
         ZPackage zpackage = new ZPackage(array2);
         steamNetworkingMessage_t.m_pfnRelease = array[0];
         steamNetworkingMessage_t.Release();
         this.m_totalRecv += zpackage.Size();
         this.m_gotData    = true;
         return(zpackage);
     }
     return(null);
 }
Exemple #16
0
    // Token: 0x06000944 RID: 2372 RVA: 0x00044954 File Offset: 0x00042B54
    public void Send(ZPackage pkg)
    {
        if (pkg.Size() == 0)
        {
            return;
        }
        if (this.m_socket == null || !this.m_socket.Connected)
        {
            return;
        }
        byte[] array  = pkg.GetArray();
        byte[] bytes  = BitConverter.GetBytes(array.Length);
        byte[] array2 = new byte[array.Length + bytes.Length];
        bytes.CopyTo(array2, 0);
        array.CopyTo(array2, 4);
        this.m_sendMutex.WaitOne();
        if (!this.m_isSending)
        {
            if (array2.Length > 10485760)
            {
                ZLog.LogError("Too big data package: " + array2.Length);
            }
            try
            {
                this.m_totalSent += array2.Length;
                this.m_socket.GetStream().BeginWrite(array2, 0, array2.Length, new AsyncCallback(this.PkgSent), this.m_socket);
                this.m_isSending = true;
                goto IL_E6;
            }
            catch (Exception arg)
            {
                ZLog.Log("Handled exception in ZSocket:Send:" + arg);
                this.Close();
                goto IL_E6;
            }
        }
        this.m_sendQueue.Enqueue(array2);
IL_E6:
        this.m_sendMutex.ReleaseMutex();
    }
Exemple #17
0
 // Token: 0x06000908 RID: 2312 RVA: 0x00043190 File Offset: 0x00041390
 public bool Update(float dt)
 {
     if (!this.m_socket.IsConnected())
     {
         return(false);
     }
     for (ZPackage zpackage = this.m_socket.Recv(); zpackage != null; zpackage = this.m_socket.Recv())
     {
         this.m_recvPackages++;
         this.m_recvData += zpackage.Size();
         try
         {
             this.HandlePackage(zpackage);
         }
         catch (Exception arg)
         {
             ZLog.Log("Exception in ZRpc::HandlePackage: " + arg);
         }
     }
     this.UpdatePing(dt);
     return(true);
 }
Exemple #18
0
    // Token: 0x0600092A RID: 2346 RVA: 0x000440C8 File Offset: 0x000422C8
    public void Send(ZPackage pkg)
    {
        if (pkg.Size() == 0)
        {
            return;
        }
        if (this.m_socket == null || !this.m_socket.Connected)
        {
            return;
        }
        byte[] array = pkg.GetArray();
        byte[] bytes = BitConverter.GetBytes(array.Length);
        this.m_sendMutex.WaitOne();
        if (!this.m_isSending)
        {
            if (array.Length > 10485760)
            {
                ZLog.LogError("Too big data package: " + array.Length);
            }
            try
            {
                this.m_totalSent += bytes.Length;
                this.m_socket.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, new AsyncCallback(this.PkgSent), null);
                this.m_isSending = true;
                this.m_sendQueue.Enqueue(array);
                goto IL_DA;
            }
            catch (Exception arg)
            {
                ZLog.Log("Handled exception in ZSocket:Send:" + arg);
                this.Disconnect();
                goto IL_DA;
            }
        }
        this.m_sendQueue.Enqueue(bytes);
        this.m_sendQueue.Enqueue(array);
IL_DA:
        this.m_sendMutex.ReleaseMutex();
    }
 public static void ReadConfigPkg(ZPackage pkg)
 {
     if (!ZNet.IsServer())
     {
         int entries = 0;
         while (pkg.GetPos() != pkg.Size())
         {
             string configKey = pkg.ReadString();
             string stringVal = pkg.ReadString();
             entries++;
             if (Config.Instance._configEntries.ContainsKey(configKey))
             {
                 Config.Instance._configEntries[configKey].SetSerializedValue(stringVal);
                 Logger.LogInfo($"Applied Server Authoritative config pair => {configKey}: {stringVal}");
             }
             else
             {
                 Logger.LogError($"Recieved config key we dont have locally. Possible Version Mismatch. {configKey}: {stringVal}");
             }
         }
         Logger.LogInfo($"Applied {entries} config pairs");
     }
 }
Exemple #20
0
 // Token: 0x06000915 RID: 2325 RVA: 0x00043503 File Offset: 0x00041703
 private void SendPackage(ZPackage pkg)
 {
     this.m_sentPackages++;
     this.m_sentData += pkg.Size();
     this.m_socket.Send(this.m_pkg);
 }
Exemple #21
0
    // Token: 0x060007D2 RID: 2002 RVA: 0x0003D744 File Offset: 0x0003B944
    private bool SendZDOs(ZDOMan.ZDOPeer peer, bool flush)
    {
        int sendQueueSize = peer.m_peer.m_socket.GetSendQueueSize();

        if (!flush && sendQueueSize > 10240)
        {
            return(false);
        }
        int num = 10240 - sendQueueSize;

        if (num < 2048)
        {
            return(false);
        }
        this.m_tempToSync.Clear();
        this.CreateSyncList(peer, this.m_tempToSync);
        if (this.m_tempToSync.Count == 0 && peer.m_invalidSector.Count == 0)
        {
            return(false);
        }
        ZPackage zpackage = new ZPackage();
        bool     flag     = false;

        if (peer.m_invalidSector.Count > 0)
        {
            flag = true;
            zpackage.Write(peer.m_invalidSector.Count);
            foreach (ZDOID id in peer.m_invalidSector)
            {
                zpackage.Write(id);
            }
            peer.m_invalidSector.Clear();
        }
        else
        {
            zpackage.Write(0);
        }
        float    time      = Time.time;
        ZPackage zpackage2 = new ZPackage();
        bool     flag2     = false;
        int      num2      = 0;

        while (num2 < this.m_tempToSync.Count && zpackage.Size() <= num)
        {
            ZDO zdo = this.m_tempToSync[num2];
            peer.m_forceSend.Remove(zdo.m_uid);
            if (!ZNet.instance.IsServer())
            {
                this.m_clientChangeQueue.Remove(zdo.m_uid);
            }
            if (peer.ShouldSend(zdo))
            {
                zpackage.Write(zdo.m_uid);
                zpackage.Write(zdo.m_ownerRevision);
                zpackage.Write(zdo.m_dataRevision);
                zpackage.Write(zdo.m_owner);
                zpackage.Write(zdo.GetPosition());
                zpackage2.Clear();
                zdo.Serialize(zpackage2);
                zpackage.Write(zpackage2);
                peer.m_zdos[zdo.m_uid] = new ZDOMan.ZDOPeer.PeerZDOInfo(zdo.m_dataRevision, zdo.m_ownerRevision, time);
                flag2 = true;
                this.m_zdosSent++;
            }
            num2++;
        }
        zpackage.Write(ZDOID.None);
        if (flag2 || flag)
        {
            peer.m_peer.m_rpc.Invoke("ZDOData", new object[]
            {
                zpackage
            });
        }
        return(flag2 || flag);
    }
Exemple #22
0
        public static void RPC_VPlusConfigSync(long sender, ZPackage configPkg)
        {
            if (ZNet.m_isServer) //Server
            {
                if (!Configuration.Current.Server.serverSyncsConfig)
                {
                    return;
                }

                ZPackage      pkg             = new ZPackage();
                List <string> cleanConfigData = new List <string>();

                IniData configdata = Configuration.Current.ConfigData;


                foreach (var prop in typeof(Configuration).GetProperties())
                {
                    var keyName = prop.Name;
                    var method  = prop.PropertyType.GetMethod("HasNeedsServerSync", BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance);

                    if (method != null)
                    {
                        var  instance           = prop.GetValue(Configuration.Current, null);
                        bool HasNeedsServerSync = (bool)method.Invoke(instance, new object[] { });
                        if (HasNeedsServerSync)
                        {
                            cleanConfigData.Add($"[{keyName}]");
                            bool hasEnableProperty = false;
                            if (configdata[keyName] != null)
                            {
                                configdata[keyName].ClearComments();
                                IEnumerator <KeyData> iterator = configdata[keyName].GetEnumerator();
                                while (iterator.MoveNext())
                                {
                                    KeyData keyData = iterator.Current;
                                    if (keyData.KeyName.Equals("enabled"))
                                    {
                                        hasEnableProperty = true;
                                    }
                                    cleanConfigData.Add($"{keyData.KeyName}={keyData.Value}");
                                }
                            }
                            if (!hasEnableProperty)
                            {
                                cleanConfigData.Add("enabled = false");
                            }
                        }
                    }
                }

                //Add number of clean lines to package
                pkg.Write(cleanConfigData.Count);

                //Add each line to the package
                foreach (string line in cleanConfigData)
                {
                    pkg.Write(line);

                    ZLog.Log("SENTCONFIG: " + line);
                }

                ZRoutedRpc.instance.InvokeRoutedRPC(sender, "VPlusConfigSync", new object[]
                {
                    pkg
                });

                ZLog.Log("VPlus configuration synced to peer #" + sender);
            }
            else //Client
            {
                if (configPkg != null &&
                    configPkg.Size() > 0 &&
                    sender == ZRoutedRpc.instance.GetServerPeerID()) //Validate the message is from the server and not another client.
                {
                    int numLines = configPkg.ReadInt();

                    if (numLines == 0)
                    {
                        ZLog.LogWarning("Got zero line config file from server. Cannot load.");
                        return;
                    }

                    using (MemoryStream memStream = new MemoryStream())
                    {
                        using (StreamWriter tmpWriter = new StreamWriter(memStream))
                        {
                            for (int i = 0; i < numLines; i++)
                            {
                                string line = configPkg.ReadString();

                                tmpWriter.WriteLine(line);

                                ZLog.Log("CONFIGDATA: " + line);
                            }

                            tmpWriter.Flush();      //Flush to memStream
                            memStream.Position = 0; //Rewind stream

                            ConfigurationExtra.LoadConfigurationFromStream(memStream);

                            // Needed to make sure client is using server configuration as dayLength is setup before
                            // TimeManipulation.SetupDayLength(); DEACTIVATED

                            ZLog.Log("Successfully synced VPlus configuration from server.");
                        }
                    }
                }
            }
        }
Exemple #23
0
        /// <summary>
        ///     Coroutine to send a package to an actual peer.
        /// </summary>
        /// <param name="peer"></param>
        /// <param name="package"></param>
        /// <returns></returns>
        private IEnumerator <bool> SendToPeer(ZNetPeer peer, ZPackage package)
        {
            ZRoutedRpc rpc = ZRoutedRpc.instance;

            if (rpc == null)
            {
                yield break;
            }

            const int packageSliceSize     = 250000;
            const int maximumSendQueueSize = 20000;

            IEnumerable <bool> WaitForQueue()
            {
                float timeout = Time.time + 30;

                while (peer.m_socket.GetSendQueueSize() > maximumSendQueueSize)
                {
                    if (Time.time > timeout)
                    {
                        Logger.LogInfo($"Disconnecting {peer.m_uid} after 30 seconds sending timeout");
                        peer.m_rpc.Invoke("Error", ZNet.ConnectionStatus.ErrorConnectFailed);
                        ZNet.instance.Disconnect(peer);
                        yield break;
                    }

                    yield return(false);
                }
            }

            void Send(ZPackage pkg)
            {
                rpc.InvokeRoutedRPC(peer.m_uid, ID, pkg);
            }

            if (package.Size() > packageSliceSize)
            {
                byte[] data              = package.GetArray();
                int    fragments         = (int)(1 + (data.LongLength - 1) / packageSliceSize);
                long   packageIdentifier = ++PackageCount;
                for (int fragment = 0; fragment < fragments; fragment++)
                {
                    foreach (bool wait in WaitForQueue())
                    {
                        yield return(wait);
                    }

                    if (!peer.m_socket.IsConnected())
                    {
                        yield break;
                    }

                    ZPackage fragmentedPackage = new ZPackage();
                    fragmentedPackage.Write(FRAGMENTED_PACKAGE);
                    fragmentedPackage.Write(packageIdentifier);
                    fragmentedPackage.Write(fragment);
                    fragmentedPackage.Write(fragments);
                    fragmentedPackage.Write(data.Skip(packageSliceSize * fragment).Take(packageSliceSize).ToArray());

                    Logger.LogDebug($"[{ID}] Sending fragmented package {packageIdentifier}:{fragment}");
                    Send(fragmentedPackage);

                    if (fragment != fragments - 1)
                    {
                        yield return(true);
                    }
                }
            }
            else
            {
                foreach (bool wait in WaitForQueue())
                {
                    yield return(wait);
                }

                Logger.LogDebug($"[{ID}] Sending package");
                Send(package);
            }
        }
        public static void RPC_VPlusConfigSync(long sender, ZPackage configPkg)
        {
            if (ZNet.m_isServer) //Server
            {
                if (!Configuration.Current.Server.serverSyncsConfig)
                {
                    return;
                }

                ZPackage pkg = new ZPackage();

                string[]      rawConfigData   = File.ReadAllLines(ConfigurationExtra.ConfigIniPath);
                List <string> cleanConfigData = new List <string>();

                for (int i = 0; i < rawConfigData.Length; i++)
                {
                    if (rawConfigData[i].Trim().StartsWith(";") ||
                        rawConfigData[i].Trim().StartsWith("#"))
                    {
                        continue;                                          //Skip comments
                    }
                    if (rawConfigData[i].Trim().IsNullOrWhiteSpace())
                    {
                        continue;                                               //Skip blank lines
                    }
                    //Add to clean data
                    cleanConfigData.Add(rawConfigData[i]);
                }

                //Add number of clean lines to package
                pkg.Write(cleanConfigData.Count);

                //Add each line to the package
                foreach (string line in cleanConfigData)
                {
                    pkg.Write(line);

                    ZLog.Log("SENTCONFIG: " + line);
                }

                ZRoutedRpc.instance.InvokeRoutedRPC(sender, "VPlusConfigSync", new object[]
                {
                    pkg
                });

                ZLog.Log("VPlus configuration synced to peer #" + sender);
            }
            else //Client
            {
                if (configPkg != null &&
                    configPkg.Size() > 0 &&
                    sender == ZRoutedRpc.instance.GetServerPeerID()) //Validate the message is from the server and not another client.
                {
                    int numLines = configPkg.ReadInt();

                    if (numLines == 0)
                    {
                        ZLog.LogWarning("Got zero line config file from server. Cannot load.");
                        return;
                    }

                    using (MemoryStream memStream = new MemoryStream())
                    {
                        using (StreamWriter tmpWriter = new StreamWriter(memStream))
                        {
                            for (int i = 0; i < numLines; i++)
                            {
                                string line = configPkg.ReadString();

                                tmpWriter.WriteLine(line);

                                ZLog.Log("CONFIGDATA: " + line);
                            }

                            tmpWriter.Flush();      //Flush to memStream
                            memStream.Position = 0; //Rewind stream

                            Configuration.Current = ConfigurationExtra.LoadFromIni(memStream);

                            // Needed to make sure client is using server configuration as dayLength is setup before
                            TimeManipulation.SetupDayLength();

                            ZLog.Log("Successfully synced VPlus configuration from server.");
                        }
                    }
                }
            }
        }
 public static void AddZone(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 permissionnode   = "HackShardGaming.WoV-Zones.Add";
             string peerSteamID      = ((ZSteamSocket)peer.m_socket).GetPeerID().m_SteamID.ToString(); // Get the SteamID from peer.
             bool   PlayerPermission = ValheimPermissions.ValheimDB.CheckUserPermission(peerSteamID, permissionnode);
             if (PlayerPermission)
             {
                 string   msg     = pkg.ReadString();
                 string[] results = msg.Split(' ');
                 string   Name    = results[0];
                 Debug.Log($"C-<S AddZone (RPC Call)");
                 string Type = results[1];
                 ZoneHandler.ZoneTypes zt = ZoneHandler.FindZoneType(results[1]);
                 if (zt.Name != Type)
                 {
                     msg = $"ERROR: The requested Zone Type {Type} does not exist!";
                     Util.RoutedBroadcast(sender, msg);
                     return;
                 }
                 int Priority = Int32.Parse(results[2]);
                 if (Priority < 1 || Priority > 5)
                 {
                     msg = $"ERROR: The requested Priority {Priority} is out of bounds! (Priorities are ranged from 1-5)!";
                     Util.RoutedBroadcast(sender, msg);
                     return;
                 }
                 string Shape = results[3];
                 if (Shape.ToLower() != "circle" && Shape.ToLower() != "square")
                 {
                     msg = $"ERROR: The requested Shape: {Shape} is incorrectly formated! (Shapes can either be circle or square only)";
                     Util.RoutedBroadcast(sender, msg);
                     return;
                 }
                 Single i = new float();
                 string X = results[4];
                 if (!Single.TryParse(X, out i))
                 {
                     msg = $"ERROR: The requested X {X} is incorrectly formated! (Correct Format is 0.0)!";
                     Util.RoutedBroadcast(sender, msg);
                     return;
                 }
                 string Y = results[5];
                 if (!Single.TryParse(Y, out i))
                 {
                     msg = $"ERROR: The requested Y {Y} is incorrectly formated! (Correct Format is 0.0)!";
                     Util.RoutedBroadcast(sender, msg);
                     return;
                 }
                 string R = results[6];
                 if (!Single.TryParse(R, out i))
                 {
                     msg = $"ERROR: The requested Radius {R} is incorrectly formated! (Correct Format is 0.0)!";
                     Util.RoutedBroadcast(sender, msg);
                     return;
                 }
                 string addline = Name + " " + Type + " " + Priority + " " + Shape + " " + X + " " + Y + " " + R;
                 File.AppendAllText(WorldofValheimZones.ZonePath.Value, addline + Environment.NewLine);
             }
             else
             {
                 Util.RoutedBroadcast(sender, $"Sorry! You do not have the permission to use !AddZone (Required Permission: {permissionnode})");
                 Debug.Log($"An unauthorized user {peerSteamID} attempted to use the AddZone RPC!");
                 string msg = pkg.ReadString();
                 Debug.Log($"Here is a log of the attempted AddZone {msg}");
             }
         }
     }
 }
 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);
 }