Пример #1
0
        private static NetworkMessageDelegate MessageHandler <T>(Action <INetworkPlayer, T> handler)
        {
            void AdapterFunction(INetworkPlayer player, NetworkReader reader, int channelId)
            {
                // protect against DOS attacks if attackers try to send invalid
                // data packets to crash the server/client. there are a thousand
                // ways to cause an exception in data handling:
                // - invalid headers
                // - invalid message ids
                // - invalid data causing exceptions
                // - negative ReadBytesAndSize prefixes
                // - invalid utf8 strings
                // - etc.
                //
                // let's catch them all and then disconnect that connection to avoid
                // further attacks.
                var message = default(T);

                try
                {
                    message = reader.Read <T>();
                }
                finally
                {
                    NetworkDiagnostics.OnReceive(message, channelId, reader.Length);
                }

                handler(player, message);
            }

            return(AdapterFunction);
        }
Пример #2
0
        /// <summary>
        /// Calls <see cref="Reader{T}.Read"/> and measures number of bytes read
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="reader"></param>
        /// <returns></returns>
        internal static T ReadWithDiagnostics <T>(NetworkReader reader)
        {
            var message = default(T);

            // record start position for NetworkDiagnostics because reader might contain multiple messages if using batching
            int startPos = reader.BitPosition;

            try
            {
                message = reader.Read <T>();
            }
            finally
            {
                int endPos     = reader.BitPosition;
                int byteLength = (endPos - startPos) / 8;
                NetworkDiagnostics.OnReceive(message, byteLength);
            }

            return(message);
        }