void RecvMoveStopHorizontal(IIPSocket conn, BitStream r)
 {
     User user;
     if ((user = TryGetUser(conn)) != null && (user.IsMovingLeft || user.IsMovingRight))
     {
         if (user.IsPeerTrading)
             return;
         user.StopMovingHorizontal();
     }
 }
 static void AssertRestOfStreamIsZero(BitStream data)
 {
     if (!RestOfStreamIsZero(data))
     {
         const string errmsg = "Encountered msgID = 0, but there was set bits remaining in the stream.";
         if (log.IsWarnEnabled)
             log.WarnFormat(errmsg);
         Debug.Fail(errmsg);
     }
 }
        void RecvMoveStopVertical(IIPSocket conn, BitStream r)
        {
            User user;
            if ((user = TryGetUser(conn)) != null && (user.IsMovingUp || user.IsMovingDown))
            {
                if (user.IsPeerTrading)
                    return;

                user.StopMovingVertical();
            }
        }
        void RecvMoveUp(IIPSocket conn, BitStream r)
        {
            User user;
            if ((user = TryGetUser(conn)) != null && !user.IsMovingUp)
            {
                if (user.IsPeerTrading)
                    return;

                user.MoveUp();
            }
        }
        void RecvJump(IIPSocket conn, BitStream r)
        {
            User user;
            if (((user = TryGetUser(conn)) != null) && user.CanJump)
            {
                if (user.IsPeerTrading)
                    return;

                user.Jump();
            }
        }
        /// <summary>
        /// Invokes the <see cref="IMessageProcessor"/> for handle processing a message block.
        /// </summary>
        /// <param name="socket">The <see cref="IIPSocket"/> that the data came from.</param>
        /// <param name="processor">The <see cref="IMessageProcessor"/> to invoke.</param>
        /// <param name="reader">The <see cref="BitStream"/> containing the data to process.</param>
        protected override void InvokeProcessor(IIPSocket socket, IMessageProcessor processor, BitStream reader)
        {
            // Invoke the processor as normal, but keeping track of the bit position before and after invoking
            var startBits = reader.PositionBits;

            base.InvokeProcessor(socket, processor, reader);

            var endBits = reader.PositionBits;

            // Update the stats
            _stats.HandleProcessorInvoked(processor.MsgID, endBits - startBits);
        }
Beispiel #7
0
        /// <summary>
        /// Determines whether or not a connection request should be accepted.
        /// </summary>
        /// <param name="ip">The IPv4 address the remote connection is coming from.</param>
        /// <param name="port">The port that the remote connection is coming from.</param>
        /// <param name="data">The data sent along with the connection request.</param>
        /// <returns>
        /// If null or empty, the connection will be accepted. Otherwise, return a non-empty string containing the reason
        /// as to why the connection is to be rejected to reject the connection.
        /// </returns>
        protected override string AcceptConnect(uint ip, ushort port, BitStream data)
        {
            // Check for too many connections from the IP
            var maxConnsPerIP = ServerSettings.Default.MaxConnectionsPerIP;
            if (maxConnsPerIP > 0)
            {
                var connsFromIP = Connections.Count(x => x.IP == ip);
                if (connsFromIP >= maxConnsPerIP)
                    return GameMessageHelper.AsString(GameMessage.DisconnectTooManyConnectionsFromIP);
            }

            return base.AcceptConnect(ip, port, data);
        }
        public void ReadWriteFromHelperUsingPropertyTest()
        {
            var bs = new BitStream(512);
            var a = new ClassB { A = "asdf", B = 512 };
            var b = new ClassB();

            a.WriteState(bs);

            bs.PositionBits = 0;

            b.ReadState(bs);

            Assert.AreEqual(a.A, b.A);
            Assert.AreEqual(a.B, b.B);
        }
        /// <summary>
        /// Copies the values of this NPCChatConditionalCollectionBase to another NPCChatConditionalCollectionBase.
        /// </summary>
        /// <param name="dest">The NPCChatConditionalCollectionBase to copy the values into.</param>
        public void CopyValuesTo(NPCChatConditionalCollectionBase dest)
        {
            var stream = new BitStream(256);

            using (var writer = BinaryValueWriter.Create(stream))
            {
                Write(writer);
            }

            stream.PositionBits = 0;

            var reader = BinaryValueReader.Create(stream);

            dest.Read(reader);
        }
Beispiel #10
0
        public void ReadWriteFromInterfaceTest()
        {
            var bs = new BitStream(512);
            var a = new ClassA { A = "asdf", B = 512 };
            var b = new ClassA();

            a.WriteState(bs);

            bs.PositionBits = 0;

            b.ReadState(bs);

            Assert.AreEqual(a.A, b.A);
            Assert.AreEqual(a.B, b.B);
        }
        /// <summary>
        /// Sends data to the <see cref="INetworkSender"/>. This method is thread-safe.
        /// </summary>
        /// <param name="sender">The <see cref="INetworkSender"/> to use to send the data.</param>
        /// <param name="data">BitStream containing the data to send to the User.</param>
        /// <param name="messageType">The <see cref="ServerMessageType"/> to use for sending the <paramref name="data"/>.</param>
        public static void Send(this INetworkSender sender, BitStream data, ServerMessageType messageType)
        {
            if (!sender.IsConnected)
            {
                const string errmsg = "Send to `{0}` failed - not connected.";
                if (log.IsErrorEnabled)
                    log.ErrorFormat(errmsg, sender);
                return;
            }

            NetDeliveryMethod method;
            int seqChannel;
            messageType.GetDeliveryMethod(out method, out seqChannel);

            sender.Send(data, method, seqChannel);
        }
Beispiel #12
0
        /// <summary>
        /// When overridden in the derived class, allows for handling received data from an <see cref="IIPSocket"/>.
        /// </summary>
        /// <param name="sender">The <see cref="IIPSocket"/> that the data came from.</param>
        /// <param name="data">The data that was received.</param>
        protected override void OnReceiveData(IIPSocket sender, BitStream data)
        {
            base.OnReceiveData(sender, data);

            try
            {
                // Process the data
                _messageProcessorManager.Process(sender, data);
            }
            catch (Exception ex)
            {
                const string errmsg = "Failed to process received data from `{0}`. Exception: {1}";
                if (log.IsWarnEnabled)
                    log.WarnFormat(errmsg, sender, ex);
                Debug.Fail(string.Format(errmsg, sender, ex));
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="EditorNPCChatConditionalCollection"/> class.
        /// </summary>
        /// <param name="source">The source <see cref="NPCChatConditionalCollectionBase"/> to copy the values from. If null,
        /// no values are copied.</param>
        public EditorNPCChatConditionalCollection(NPCChatConditionalCollectionBase source)
        {
            if (source == null)
                return;

            var stream = new BitStream(256);

            using (var writer = BinaryValueWriter.Create(stream))
            {
                source.Write(writer);
            }

            stream.PositionBits = 0;

            IValueReader reader = BinaryValueReader.Create(stream);

            Read(reader);
        }
Beispiel #14
0
        public ParticleModifier DeepCopy()
        {
            // Create the deep copy by serializing to/from an IValueWriter
            using (var bs = new BitStream())
            {
                // Write
                using (var writer = BinaryValueWriter.Create(bs, false))
                {
                    Write(writer);
                }

                bs.Position = 0;

                // Read
                var reader = BinaryValueReader.Create(bs, false);
                return Read(reader);
            }
        }
Beispiel #15
0
        static void TestSyncNullable(string propertyName, object value)
        {
            // Get the property
            var property = typeof(NullableTestClass).GetProperty(propertyName);

            // Set the value and ensure it was set correctly
            var cSrc = new NullableTestClass();
            property.SetValue(cSrc, value, null);
            Assert.AreEqual(value, property.GetValue(cSrc, null));

            // Serialize
            var bs = new BitStream();
            cSrc.Serialize(bs);

            // Deserialize
            var cDest = new NullableTestClass();
            bs.PositionBits = 0;
            cDest.Deserialize(bs);

            // Check
            Assert.AreEqual(value, property.GetValue(cDest, null));
        }
Beispiel #16
0
        public void ExceptionWhenNotSupportsCastOperationsTest()
        {
#pragma warning disable 219
            object o;
#pragma warning restore 219

            var bs = new BitStream(128);

            Assert.Throws<MethodAccessException>(() => o = EnumHelper<EVULong>.BitsRequired);
            Assert.Throws<MethodAccessException>(() => o = EnumHelper<EVULong>.MaxValue);
            Assert.Throws<MethodAccessException>(() => o = EnumHelper<EVULong>.MinValue);
            Assert.Throws<MethodAccessException>(() => o = EnumHelper<EVULong>.GetToIntFunc());
            Assert.Throws<MethodAccessException>(() => o = EnumHelper<EVULong>.GetFromIntFunc());
            Assert.Throws<MethodAccessException>(() => o = EnumHelper<EVULong>.FromInt(1));
            Assert.Throws<MethodAccessException>(() => o = EnumHelper<EVULong>.ToInt(EVULong.A));
            Assert.Throws<MethodAccessException>(() => EnumHelper<EVULong>.WriteValue(bs, EVULong.A));
            Assert.Throws<MethodAccessException>(() => EnumHelper<EVULong>.WriteValue(bs, "test", EVULong.A));

            bs.PositionBits = 0;

            Assert.Throws<MethodAccessException>(() => o = EnumHelper<EVULong>.ReadValue(bs));
            Assert.Throws<MethodAccessException>(() => o = EnumHelper<EVULong>.ReadValue(bs, "test"));
        }
Beispiel #17
0
        /// <summary>
        /// Handles <see cref="QuestInfoMessages.AddActiveQuest"/>.
        /// </summary>
        /// <param name="bs">The <see cref="BitStream"/> to read from.</param>
        void ReadAddActiveQuest(BitStream bs)
        {
            var questID = bs.ReadQuestID();

            // Ensure the quest isn't already in the active list
            if (_activeQuests.BinarySearch(questID) >= 0)
                return;

            // Add
            _activeQuests.Add(questID);
            _activeQuests.Sort();

            // Raise events
            OnActiveQuestAdded(questID);

            if (ActiveQuestAdded != null)
                ActiveQuestAdded.Raise(this, EventArgsHelper.Create(questID));
        }
Beispiel #18
0
        /// <summary>
        /// Reads the data from the server related to the user quest information. This should only be used by the client.
        /// </summary>
        /// <param name="bs">The <see cref="BitStream"/> containing the data.</param>
        public void Read(BitStream bs)
        {
            var id = bs.ReadEnum<QuestInfoMessages>();
            switch (id)
            {
                case QuestInfoMessages.AddCompletedQuest:
                    ReadAddCompletedQuest(bs);
                    break;

                case QuestInfoMessages.AddActiveQuest:
                    ReadAddActiveQuest(bs);
                    break;

                case QuestInfoMessages.RemoveActiveQuest:
                    ReadRemoveActiveQuest(bs);
                    break;

                case QuestInfoMessages.LoadInitialValues:
                    ReadLoadInitialValues(bs);
                    break;

                default:
                    const string errmsg = "Unknown QuestInfoMessages value `{0}`. Could not parse!";
                    var err = string.Format(errmsg, id);
                    log.Fatal(err);
                    Debug.Fail(err);
                    return;
            }
        }
Beispiel #19
0
 /// <summary>
 /// Appends a message to a <see cref="BitStream"/> for synchronizing the client's quest information for when
 /// a quest is removed from the active quests.
 /// The message is then read and handled by the receiver using <see cref="UserQuestInformation.Read"/>.
 /// </summary>
 /// <param name="bs">The <see cref="BitStream"/> to append the message to.</param>
 /// <param name="questID">The ID of the removed active quest.</param>
 public static void WriteRemoveActiveQuest(BitStream bs, QuestID questID)
 {
     bs.WriteEnum(QuestInfoMessages.RemoveActiveQuest);
     bs.Write(questID);
 }
Beispiel #20
0
        /// <summary>
        /// Appends a message to a <see cref="BitStream"/> for synchronizing all of the client's quest information.
        /// The message is then read and handled by the receiver using <see cref="UserQuestInformation.Read"/>.
        /// </summary>
        /// <param name="bs">The <see cref="BitStream"/> to append the message to.</param>
        /// <param name="completedQuests">All of the completed quests.</param>
        /// <param name="activeQuests">All of the active quests.</param>
        public static void WriteQuestInfo(BitStream bs, IEnumerable<QuestID> completedQuests, IEnumerable<QuestID> activeQuests)
        {
            completedQuests = completedQuests.ToImmutable();
            activeQuests = activeQuests.ToImmutable();

            bs.WriteEnum(QuestInfoMessages.RemoveActiveQuest);

            // Write the completed quests
            bs.Write((ushort)completedQuests.Count());
            foreach (var q in completedQuests)
            {
                bs.Write(q);
            }

            // Write the active quests
            bs.Write((byte)activeQuests.Count());
            foreach (var q in activeQuests)
            {
                bs.Write(q);
            }
        }
Beispiel #21
0
 /// <summary>
 /// Appends a message to a <see cref="BitStream"/> for synchronizing the client's quest information for when
 /// a quest is completed.
 /// The message is then read and handled by the receiver using <see cref="UserQuestInformation.Read"/>.
 /// </summary>
 /// <param name="bs">The <see cref="BitStream"/> to append the message to.</param>
 /// <param name="questID">The ID of the completed quest.</param>
 public static void WriteAddCompletedQuest(BitStream bs, QuestID questID)
 {
     bs.WriteEnum(QuestInfoMessages.AddCompletedQuest);
     bs.Write(questID);
 }
Beispiel #22
0
        /// <summary>
        /// Handles <see cref="QuestInfoMessages.RemoveActiveQuest"/>.
        /// </summary>
        /// <param name="bs">The <see cref="BitStream"/> to read from.</param>
        void ReadRemoveActiveQuest(BitStream bs)
        {
            var questID = bs.ReadQuestID();

            // Ensure the quest is in the active list
            int index;
            if ((index = _activeQuests.BinarySearch(questID)) < 0)
                return;

            Debug.Assert(_activeQuests[index] == questID);

            // Remove
            _activeQuests.RemoveAt(index);

            // Raise events
            OnActiveQuestRemoved(questID);

            if (ActiveQuestRemoved != null)
                ActiveQuestRemoved.Raise(this, EventArgsHelper.Create(questID));
        }
Beispiel #23
0
        /// <summary>
        /// Handles <see cref="QuestInfoMessages.LoadInitialValues"/>.
        /// </summary>
        /// <param name="bs">The <see cref="BitStream"/> to read from.</param>
        void ReadLoadInitialValues(BitStream bs)
        {
            _completedQuests.Clear();
            _activeQuests.Clear();

            // Read completed quests
            var count = bs.ReadByte();
            for (var i = 0; i < count; i++)
            {
                _completedQuests.Add(bs.ReadQuestID());
            }

            // Read Active quests
            count = bs.ReadByte();
            for (var i = 0; i < count; i++)
            {
                _activeQuests.Add(bs.ReadQuestID());
            }

            // Raise events
            OnLoaded();

            if (Loaded != null)
                Loaded.Raise(this, EventArgs.Empty);
        }
Beispiel #24
0
        /// <summary>
        /// Handles <see cref="QuestInfoMessages.AddCompletedQuest"/>.
        /// </summary>
        /// <param name="bs">The <see cref="BitStream"/> to read from.</param>
        void ReadAddCompletedQuest(BitStream bs)
        {
            var questID = bs.ReadQuestID();

            // Ensure the quest isn't already in the completed list
            if (_completedQuests.BinarySearch(questID) >= 0)
                return;

            // Add
            _completedQuests.Add(questID);
            _completedQuests.Sort();

            // Raise events
            OnCompletedQuestAdded(questID);

            if (CompletedQuestAdded != null)
                CompletedQuestAdded.Raise(this, EventArgsHelper.Create(questID));
        }
        void RecvGetOnlineUsers(IIPSocket conn, BitStream r)
        {
            User myUser;
            if ((myUser = TryGetUser(conn)) == null)
                return;

            var allUsers = Server.World.GetUsers();
            var orderedUsers = allUsers.OrderBy(x => !x.Permissions.IsSet(UserPermissions.None)).ThenBy(x => x.Name).ToList();
            string onlineUsers = string.Empty;

            foreach (var user in orderedUsers)
            {
                if (myUser == user)
                    continue;

                onlineUsers += user.Name + ";";
            }

            using (var pw = ServerPacket.ReceiveAllUsers(onlineUsers))
            {
                myUser.Send(pw, ServerMessageType.GUI);
            }
        }
        /// <summary>
        /// Sends data to the other end of the connection.
        /// </summary>
        /// <param name="data">Data to send.</param>
        /// <param name="deliveryMethod">The method to use to deliver the message. This determines how reliability, ordering,
        /// and sequencing will be handled.</param>
        /// <param name="sequenceChannel">The sequence channel to use to deliver the message. Only valid when
        /// <paramref name="deliveryMethod"/> is not equal to <see cref="NetDeliveryMethod.Unreliable"/> or
        /// <see cref="NetDeliveryMethod.ReliableUnordered"/>. Must also be a value greater than or equal to 0 and
        /// less than <see cref="NetConstants.NetChannelsPerDeliveryMethod"/>.</param>
        /// <returns>
        /// True if the <paramref name="data"/> was successfully enqueued for sending; otherwise false.
        /// </returns>
        /// <exception cref="NetException"><paramref name="deliveryMethod"/> equals <see cref="NetDeliveryMethod.Unreliable"/>
        /// or <see cref="NetDeliveryMethod.ReliableUnordered"/> and <paramref name="sequenceChannel"/> is non-zero.</exception>
        /// <exception cref="NetException"><paramref name="sequenceChannel"/> is less than 0 or greater than or equal to
        /// <see cref="NetConstants.NetChannelsPerDeliveryMethod"/>.</exception>
        /// <exception cref="NetException"><paramref name="deliveryMethod"/> equals <see cref="NetDeliveryMethod.Unknown"/>.</exception>
        public bool Send(BitStream data, NetDeliveryMethod deliveryMethod, int sequenceChannel = 0)
        {
            var sock = RemoteSocket;
            if (sock == null)
            {
                const string errmsg = "Could not send data - connection not established!";
                if (log.IsErrorEnabled)
                    log.Error(errmsg);
                Debug.Fail(errmsg);
                return false;
            }

            try
            {
                var ret = sock.Send(data, deliveryMethod, sequenceChannel);
                if (!ret)
                    Debug.Fail("Sending to server failed.");
                return ret;
            }
            catch (Exception ex)
            {
                const string errmsg = "Failed to send data. Exception: {0}";
                if (log.IsErrorEnabled)
                    log.ErrorFormat(errmsg, ex);
                Debug.Fail(string.Format(errmsg, ex));
                return false;
            }
        }
        /// <summary>
        /// Attempts to connects to the server.
        /// </summary>
        /// <param name="host">The server address.</param>
        /// <param name="port">The server port.</param>
        /// <param name="approvalMessage">The initial message to send to the server when making the connection. This can
        /// be utilized by the server to provide additional information for determining whether or not to accept the connection.
        /// Or, can be null to send nothing.</param>
        /// <returns>
        /// True if the connection attempt was successfully started. Does not mean that the connection was established, but
        /// just that it can be attempted. Will return false if a connection is already established or being established.
        /// </returns>
        public bool Connect(string host, int port, BitStream approvalMessage = null)
        {
            if (_local.ConnectionsCount > 0)
                return false;

            NetConnection conn;

            if (approvalMessage != null && approvalMessage.LengthBits > 0)
            {
                // Connect with approval message
                var netOutMsg = SocketHelper.GetNetOutgoingMessage(_local, approvalMessage.LengthBytes);
                approvalMessage.CopyTo(netOutMsg);

                conn = _local.Connect(host, port, netOutMsg);
            }
            else
            {
                // Connect without approval message
                conn = _local.Connect(host, port);
            }

            // Check if connection successful
            if (conn == null)
            {
                Debug.Fail("conn is null. Why?");
                return false;
            }

            // Store the remote connection as an IPSocket
            _remote = IPSocket.Create(conn);

            return true;
        }
        void RecvSaveFriends(IIPSocket conn, BitStream r)
        {
            var account = TryGetAccount(conn);
            if (account == null)
                return;

            account.SetFriends(r.ReadString());
        }
 /// <summary>
 /// When overridden in the derived class, allows for handling received data from an <see cref="IIPSocket"/>.
 /// </summary>
 /// <param name="sender">The <see cref="IIPSocket"/> that the data came from.</param>
 /// <param name="data">The data that was received. This <see cref="BitStream"/> instance is reused internally, so it
 /// is vital that you do NOT hold a reference to it when this method returns. This should be no problem since you should
 /// not be holding onto raw received data anyways, but if you must, you can always make a deep copy.</param>
 protected virtual void OnReceiveData(IIPSocket sender, BitStream data)
 {
 }
        void RecvSendPrivateMessage(IIPSocket conn, BitStream r)
        {

            string TargetName = r.ReadString();
            string Text = r.ReadString();

            // Get the user to send the message to
            User TargetChar = World.FindUser(TargetName);

            string PrivateMessage = TargetName + " Says: " + Text;

            using (var pw = ServerPacket.ReceivePrivateMessage(PrivateMessage))
            {
                TargetChar.Send(pw, ServerMessageType.GUIChat);
            }
        }