Beispiel #1
0
        public void Serialization()
        {
            var dict = new Dictionary <Type, ushort> {
                { typeof(string), 0 }, { typeof(int), 1 }
            };
            TypeMap map = new TypeMap(dict);

            byte[] buffer = new byte[20480];
            var    writer = new BufferValueWriter(buffer);

            map.Serialize(null, writer);
            writer.Flush();

            var reader = new BufferValueReader(buffer);

            map = new TypeMap();
            map.Deserialize(null, reader);

            Type type;

            Assert.IsTrue(map.TryGetType(0, out type));
            Assert.AreEqual(typeof(string), type);
            Assert.IsTrue(map.TryGetType(1, out type));
            Assert.AreEqual(typeof(int), type);

            ushort id;

            Assert.IsFalse(map.GetTypeId(typeof(string), out id));
            Assert.AreEqual(0, id);
            Assert.IsFalse(map.GetTypeId(typeof(int), out id));
            Assert.AreEqual(1, id);
        }
        public void ISerializable()
        {
            byte[] buffer = new byte[20480];
            var    writer = new BufferValueWriter(buffer);

            SerializableTester tester = new SerializableTester
            {
                Name    = "MONKEY!",
                Numbers = new[] { 1, 2, 4, 8, 16, 32 }
            };

            var test = new AsyncTest();

            tester.SerializeCalled += test.PassHandler;

            writer.Write(context, tester);
            writer.Flush();

            var reader     = new BufferValueReader(buffer);
            var serialized = SerializerExtensions.Read <SerializableTester> (reader, context);

            Assert.IsNotNull(serialized);
            Assert.AreEqual(tester.Name, serialized.Name);
            Assert.IsTrue(tester.Numbers.SequenceEqual(serialized.Numbers), "Numbers does not match");

            test.Assert(1000);
        }
Beispiel #3
0
        public void Serialize()
        {
            var crypto = new RSACryptoServiceProvider();

            var p = new RSAAsymmetricKey(crypto.ExportCspBlob(true));

            byte[] buffer = new byte[20480];
            var    writer = new BufferValueWriter(buffer);

            p.Serialize(null, writer);
            int len = writer.Length;

            writer.Flush();

            var reader = new BufferValueReader(buffer);
            var key    = new RSAAsymmetricKey(null, reader);

            Assert.AreEqual(len, reader.Position);

            Assert.IsNull(key.D);
            Assert.IsNull(key.DP);
            Assert.IsNull(key.DQ);
            AssertArrayMatches(p.Exponent, key.Exponent);
            Assert.IsNull(key.InverseQ);
            AssertArrayMatches(p.Modulus, key.Modulus);
            Assert.IsNull(key.P);
            Assert.IsNull(key.Q);

            Assert.IsNotNull(key.PublicSignature);
        }
Beispiel #4
0
        public void Serialize()
        {
            var person  = new Person("first");
            var person2 = new Person("second");

            list.Add(person);
            server.DequeueAndAssertMessage <BuddyListMessage>();
            list.Add(person2);
            server.DequeueAndAssertMessage <BuddyListMessage>();

            var writer = new BufferValueWriter(new byte[1024]);

            list.Serialize(clientContext, writer);

            server.AssertNoMessage();

            var reader = new BufferValueReader(writer.Buffer);

            list.Deserialize(clientContext, reader);

            Assert.AreEqual(writer.Length, reader.Position);

            server.AssertNoMessage();

            CollectionAssert.Contains(list, person);
            CollectionAssert.Contains(list, person2);
        }
        internal void DecryptMessage(MessageHeader header, ref BufferValueReader r)
        {
            int c = 0;

                        #if TRACE
            c = GetNextCallId();
                        #endif

            //Trace.WriteLineIf (NTrace.TraceVerbose, "Entering", String.Format ("{0}:{2} {1}:DecryptMessage({3},{4})", this.typeName, c, connectionId, header.IV.Length, r.Position));

            int payloadLength = r.ReadInt32();

            AesManaged am = AES;
            if (am == null)
            {
                return;
            }

            ICryptoTransform decryptor;
            lock (am)
            {
                am.IV     = header.IV;
                decryptor = am.CreateDecryptor();
            }

            byte[] message = decryptor.TransformFinalBlock(r.Buffer, r.Position, payloadLength);
            r.Position += payloadLength;             // Advance original reader position
            r           = new BufferValueReader(message);

            //Trace.WriteLineIf (NTrace.TraceVerbose, "Exiting", String.Format ("{0}:{2} {1}:DecryptMessage({3},{4},{5})", this.typeName, c, connectionId, header.IV.Length, r.Position, message.Length));
        }
        public List <Message> BufferMessages(byte[] buffer)
        {
            int offset    = 0;
            int moffset   = 0;
            int remaining = buffer.Length;

            MessageHeader header = null;
            var           reader = new BufferValueReader(buffer);

            return(BufferMessages(ref buffer, ref offset, ref moffset, ref remaining, ref header, ref reader));
        }
Beispiel #7
0
        public void Enum()
        {
            byte[] buffer = new byte[1024];
            var writer = new BufferValueWriter (buffer);
            writer.Write (context, TestEnum.High);
            int len = writer.Length;
            writer.Flush();

            var reader = new BufferValueReader (buffer);

            Assert.AreEqual (TestEnum.High, reader.Read<TestEnum> (context));
            Assert.AreEqual (len, reader.Position);
        }
        public void ReadWriteLongSet()
        {
            var writer = new BufferValueWriter (new byte[1]);

            for (int i = 0; i < 20480; ++i)
                writer.WriteInt32(i);

            writer.Flush();

            var reader = new BufferValueReader (writer.Buffer);
            for (int i = 0; i < 20480; ++i)
                Assert.AreEqual(i, reader.ReadInt32());
        }
Beispiel #9
0
        public void ReadWriteUniversalDate()
        {
            byte[] buffer = new byte[20480];
            var    writer = new BufferValueWriter(buffer);

            DateTime d = DateTime.Now;

            writer.WriteUniversalDate(d);
            writer.Flush();

            var reader = new BufferValueReader(buffer);

            Assert.AreEqual(d.ToUniversalTime(), reader.ReadUniversalDate());
        }
Beispiel #10
0
        public void ReadWriteUniversalDate()
        {
            byte[] buffer = new byte[20480];
            var writer = new BufferValueWriter (buffer);

            DateTime d = DateTime.Now;

            writer.WriteUniversalDate (d);
            writer.Flush();

            var reader = new BufferValueReader (buffer);

            Assert.AreEqual (d.ToUniversalTime(), reader.ReadUniversalDate());
        }
Beispiel #11
0
        public void ReadWrite7BitInt()
        {
            var writer = new BufferValueWriter (new byte[20480]);

            writer.Write7BitEncodedInt (Int32.MinValue);
            writer.Write7BitEncodedInt (0);
            writer.Write7BitEncodedInt (Int32.MaxValue);
            writer.Flush();

            var reader = new BufferValueReader (writer.Buffer);

            Assert.AreEqual (Int32.MinValue, reader.Read7BitEncodedInt());
            Assert.AreEqual (0, reader.Read7BitEncodedInt());
            Assert.AreEqual (Int32.MaxValue, reader.Read7BitEncodedInt());
        }
Beispiel #12
0
        public void Enum()
        {
            byte[] buffer = new byte[1024];
            var    writer = new BufferValueWriter(buffer);

            writer.Write(context, TestEnum.High);
            int len = writer.Length;

            writer.Flush();

            var reader = new BufferValueReader(buffer);

            Assert.AreEqual(TestEnum.High, reader.Read <TestEnum> (context));
            Assert.AreEqual(len, reader.Position);
        }
Beispiel #13
0
        public void ReadWrite7BitInt()
        {
            var writer = new BufferValueWriter(new byte[20480]);

            writer.Write7BitEncodedInt(Int32.MinValue);
            writer.Write7BitEncodedInt(0);
            writer.Write7BitEncodedInt(Int32.MaxValue);
            writer.Flush();

            var reader = new BufferValueReader(writer.Buffer);

            Assert.AreEqual(Int32.MinValue, reader.Read7BitEncodedInt());
            Assert.AreEqual(0, reader.Read7BitEncodedInt());
            Assert.AreEqual(Int32.MaxValue, reader.Read7BitEncodedInt());
        }
Beispiel #14
0
        public void Serializer()
        {
            byte[] buffer = new byte[1024];
            var    writer = new BufferValueWriter(buffer);

            var c = SerializationContextTests.GetContext(MockProtocol.Instance);
            var p = new Protocol(42, 248);

            p.Serialize(c, writer);
            writer.Flush();

            var reader = new BufferValueReader(buffer);
            var p2     = new Protocol(c, reader);

            Assert.AreEqual(p.id, p2.id);
            Assert.AreEqual(p.Version, p2.Version);
        }
Beispiel #15
0
        public void ReadWriteLongSet()
        {
            var writer = new BufferValueWriter(new byte[1]);

            for (int i = 0; i < 20480; ++i)
            {
                writer.WriteInt32(i);
            }

            writer.Flush();

            var reader = new BufferValueReader(writer.Buffer);

            for (int i = 0; i < 20480; ++i)
            {
                Assert.AreEqual(i, reader.ReadInt32());
            }
        }
Beispiel #16
0
		public void Serialize()
		{
			var person = new Person ("foobar") {
				Nickname = "MyNickname",
				Avatar = "MyAvatar",
				Status = Status.Away
			};

			byte[] buffer = new byte[2048];
			var bufferWriter = new BufferValueWriter (buffer);

			person.Serialize (null, bufferWriter);

			var bufferReader = new BufferValueReader (buffer);
			var person2 = new Person (null, bufferReader);

			Assert.AreEqual (person.Identity, person2.Identity);
			Assert.AreEqual (person.Nickname, person2.Nickname);
			Assert.AreEqual (person.Avatar, person2.Avatar);
			Assert.AreEqual (person.Status, person2.Status);
		}
        private void Receive(object sender, SocketAsyncEventArgs args)
        {
            var               cnd    = (Tuple <Socket, BufferValueReader>)args.UserToken;
            Socket            socket = cnd.Item1;
            BufferValueReader reader = cnd.Item2;

            if (args.BytesTransferred == 0 || args.SocketError != SocketError.Success)
            {
                reader.Dispose();
                args.Dispose();
                Interlocked.Decrement(ref this.pendingAsync);
                return;
            }

            int offset = args.Offset;

            reader.Position = offset;

            MessageHeader header = null;

            // We don't currently support partial messages, so an incomplete message is a bad one.
            if (!this.connectionlessSerializer.TryGetHeader(reader, args.BytesTransferred, ref header) || header.Message == null)
            {
                Interlocked.Decrement(ref this.pendingAsync);
                StartReceive(socket, args, reader);
                return;
            }

            if (header.ConnectionId == 0)
            {
                HandleConnectionlessMessage(args, header, ref reader);
            }
            else
            {
                HandleConnectionMessage(args, header, ref reader);
            }

            Interlocked.Decrement(ref this.pendingAsync);
            StartReceive(socket, args, reader);
        }
Beispiel #18
0
        public void Serialize()
        {
            var person = new Person("foobar")
            {
                Nickname = "MyNickname",
                Avatar   = "MyAvatar",
                Status   = Status.Away
            };

            byte[] buffer       = new byte[2048];
            var    bufferWriter = new BufferValueWriter(buffer);

            person.Serialize(null, bufferWriter);

            var bufferReader = new BufferValueReader(buffer);
            var person2      = new Person(null, bufferReader);

            Assert.AreEqual(person.Identity, person2.Identity);
            Assert.AreEqual(person.Nickname, person2.Nickname);
            Assert.AreEqual(person.Avatar, person2.Avatar);
            Assert.AreEqual(person.Status, person2.Status);
        }
        private void StartReceive(Socket socket, SocketAsyncEventArgs args, BufferValueReader reader)
        {
            if (!this.running)
            {
                return;
            }

            Interlocked.Increment(ref this.pendingAsync);

            try
            {
                args.SetBuffer(0, args.Buffer.Length);
                while (!socket.ReceiveFromAsync(args))
                {
                    Receive(this, args);
                }
            }
            catch (ObjectDisposedException)             // Socket is disposed, we're done.
            {
                Interlocked.Decrement(ref this.pendingAsync);
            }
        }
Beispiel #20
0
        // [Test] Testing core APIs that now have NETFX_CORE turned on everywhere
        public void Serializable()
        {
            var inner = new Exception("Inner exception");
            var ex    = new InvalidOperationException("Don't do this, fool.", inner);

            byte[] buffer = new byte[20480];
            var    writer = new BufferValueWriter(buffer);

            writer.Write(context, ex);
            writer.Flush();

            var reader = new BufferValueReader(buffer);

            InvalidOperationException ioex = SerializerExtensions.Read <InvalidOperationException> (reader, context);

            Assert.IsNotNull(ioex);
            Assert.AreEqual(ex.Message, ioex.Message);
            Assert.AreEqual(ex.StackTrace, ioex.StackTrace);

            Assert.IsNotNull(ioex.InnerException);
            Assert.AreEqual(inner.Message, ioex.InnerException.Message);
            Assert.AreEqual(inner.StackTrace, ioex.InnerException.StackTrace);
        }
Beispiel #21
0
        internal void Receive(MessageEventArgs e)
        {
            var context = new SerializationContext();
            var writer  = new BufferValueWriter(new byte[1024]);

            e.Message.WritePayload(context, writer);

            var reader  = new BufferValueReader(writer.Buffer);
            var message = e.Message.Protocol.Create(e.Message.MessageType);

            message.ReadPayload(context, reader);
            message.Header = e.Message.Header;

            var tmessage = (e.Message as TempestMessage);

            if (tmessage == null)
            {
                OnMessageReceived(new MessageEventArgs(e.Connection, message));
            }
            else
            {
                OnTempestMessageReceived(new MessageEventArgs(e.Connection, message));
            }
        }
Beispiel #22
0
        public void Serialization()
        {
            var dict = new Dictionary<Type, ushort> { { typeof (string), 0 }, { typeof (int), 1 } };
            TypeMap map = new TypeMap (dict);

            byte[] buffer = new byte[20480];
            var writer = new BufferValueWriter (buffer);
            map.Serialize (null, writer);
            writer.Flush();

            var reader = new BufferValueReader (buffer);
            map = new TypeMap();
            map.Deserialize (null, reader);

            Type type;
            Assert.IsTrue (map.TryGetType (0, out type));
            Assert.AreEqual (typeof (string), type);
            Assert.IsTrue (map.TryGetType (1, out type));
            Assert.AreEqual (typeof (int), type);

            ushort id;
            Assert.IsFalse (map.GetTypeId (typeof (string), out id));
            Assert.AreEqual (0, id);
            Assert.IsFalse (map.GetTypeId (typeof (int), out id));
            Assert.AreEqual (1, id);
        }
        public void ValueReaderCtor()
        {
            byte[] buffer = new byte[20480];
            var writer = new BufferValueWriter (buffer);

            ValueReaderTester test = new ValueReaderTester ("TheName");

            writer.Write (context, test);
            writer.Flush();

            var reader = new BufferValueReader (buffer);
            var serialized = SerializerExtensions.Read<ValueReaderTester> (reader, context);

            Assert.AreEqual (test.Name, serialized.Name);
        }
        public void SerializableTypeContainingNonSerializableField()
        {
            byte[] buffer = new byte[20480];
            var writer = new BufferValueWriter (buffer);

            ObjectSerializer serializer = ObjectSerializer.GetSerializer (typeof (SerializableWithNonSerializableField));

            var test = new SerializableWithNonSerializableField (2, 3, "hi");

            serializer.Serialize (context, writer, test);
            writer.Flush();

            var reader = new BufferValueReader (buffer);
            var serialized = (SerializableWithNonSerializableField)serializer.Deserialize (context, reader);

            Assert.AreEqual (2, serialized.X);
            Assert.AreEqual (3, serialized.Y);
            Assert.AreEqual ("hi", serialized.Content);
        }
        public void PrimitiveAsObject()
        {
            byte[] buffer = new byte[1024];
            var writer = new BufferValueWriter (buffer);

            writer.Write (context, (object)20f);
            writer.Flush();

            var reader = new BufferValueReader (buffer);
            object value = SerializerExtensions.Read<object> (reader, context);

            Assert.IsNotNull (value);
            Assert.AreEqual (20f, value);
        }
		protected virtual void HandleConnectionMessage (SocketAsyncEventArgs args, MessageHeader header, ref BufferValueReader reader)
		{
			UdpConnection connection;
			if (!TryGetConnection (header.ConnectionId, out connection))
				return;

			byte[] buffer = args.Buffer;
			int offset = args.Offset;
			int moffset = offset;
			int remaining = args.BytesTransferred;

			MessageSerializer serializer = connection.serializer;
			if (serializer == null)
				return;

			if (header.State == HeaderState.IV)
			{
				serializer.DecryptMessage (header, ref reader);
				header.IsStillEncrypted = false;

				if (!serializer.TryGetHeader (reader, args.BytesTransferred, ref header))
					return;
			}

			List<Message> messages = serializer.BufferMessages (ref buffer, ref offset, ref moffset, ref remaining, ref header, ref reader);
			if (messages != null) {
				foreach (Message message in messages)
					connection.Receive (message);
			}

			reader.Position = 0;
		}
        public bool TryGetHeader(BufferValueReader reader, int remaining, ref MessageHeader header)
        {
            string callCategory = null;

                        #if TRACE
            int c = GetNextCallId();
            callCategory = String.Format("{0} {1}:TryGetHeader({2},{3})", this.connectionType, c, reader.Position, remaining);
                        #endif
            Trace.WriteLineIf(NTrace.TraceVerbose, String.Format("Entering {0}", (header == null) ? "without existing header" : "with existing header"), callCategory);

            int mlen; bool isContinued; Message msg = null; Protocol p;

            int headerLength = BaseHeaderLength;

            if (header == null)
            {
                header = new MessageHeader();
            }
            else if (header.State == HeaderState.Complete)
            {
                return(true);
            }
            else if (header.HeaderLength > 0)
            {
                headerLength = header.HeaderLength;
            }

            try
            {
                if (header.State >= HeaderState.Protocol)
                {
                    p = header.Protocol;
                }
                else
                {
                    byte pid = reader.ReadByte();

                    if (!this.protocols.TryGetValue(pid, out p))
                    {
                        Trace.WriteLineIf(NTrace.TraceWarning, "Exiting (Protocol " + pid + " not found)", callCategory);
                        return(true);
                    }

                    header.Protocol = p;
                    header.State    = HeaderState.Protocol;
                    if (this.serializationContext == null)
                    {
                        if (this.connection != null)
                        {
                            this.serializationContext = new SerializationContext(this.connection, this.protocols);
                        }
                        else
                        {
                            this.serializationContext = new SerializationContext(this.protocols);
                        }
                    }

                    header.SerializationContext = this.serializationContext;
                }

                if (header.State < HeaderState.CID)
                {
                    header.ConnectionId = reader.ReadInt32();
                    header.State        = HeaderState.CID;
                }

                if (header.State >= HeaderState.Type)
                {
                    msg = header.Message;
                }
                else
                {
                    ushort type = reader.ReadUInt16();

                    msg          = header.Message = p.Create(type);
                    header.State = HeaderState.Type;

                    if (msg == null)
                    {
                        Trace.WriteLineIf(NTrace.TraceWarning, "Exiting (Message " + type + " not found)", callCategory);
                        return(true);
                    }

                    msg.Header = header;

                    if (msg.Encrypted)
                    {
                        header.IsStillEncrypted = true;
                    }

                    Trace.WriteLineIf(NTrace.TraceVerbose, String.Format("Have " + msg.GetType().Name), callCategory);
                }

                if (header.State >= HeaderState.Length)
                {
                    mlen = header.MessageLength;
                }
                else
                {
                    mlen = reader.ReadInt32();

                    if (mlen <= 0)
                    {
                        Trace.WriteLineIf(NTrace.TraceWarning, "Exiting (length invalid)", callCategory);
                        return(true);
                    }

                    header.MessageLength = mlen;
                    header.State         = HeaderState.Length;

                    Trace.WriteLineIf(NTrace.TraceVerbose, String.Format("Have message of length: {0}", mlen), callCategory);
                }

                if (header.State == HeaderState.IV)
                {
                    if (header.IsStillEncrypted)
                    {
                        Trace.WriteLineIf(NTrace.TraceVerbose, "Exiting (message not buffered)", callCategory);
                        return(!(remaining < mlen));
                    }
                    else if (header.Message.Encrypted)
                    {
                        reader.Position = 0;
                    }
                }
                else if (msg.Encrypted)                // && AES != null)
                {
                    int ivLength = reader.ReadInt32(); //AES.IV.Length;
                    headerLength += ivLength + sizeof(int);

                    if (remaining < headerLength)
                    {
                        reader.Position -= sizeof(int);
                        Trace.WriteLineIf(NTrace.TraceVerbose, "Exiting (header not buffered (IV))", callCategory);
                        return(false);
                    }

                    byte[] iv = reader.ReadBytes(ivLength);

                    header.HeaderLength = headerLength;
                    header.State        = HeaderState.IV;
                    header.IV           = iv;

                    if (remaining < mlen)
                    {
                        Trace.WriteLineIf(NTrace.TraceVerbose, "Exiting (message not buffered)", callCategory);
                        return(false);
                    }

                    Trace.WriteLineIf(NTrace.TraceVerbose, "Exiting (need to decrypt)", callCategory);
                    return(true);
                }

                if (header.State < HeaderState.MessageId)
                {
                    int identV = reader.ReadInt32();
                    header.MessageId  = identV & ~ResponseFlag;
                    header.IsResponse = (identV & ResponseFlag) == ResponseFlag;

                    header.State = (header.IsResponse) ? HeaderState.MessageId : HeaderState.Complete;

                    Trace.WriteLineIf(NTrace.TraceVerbose, "Have message ID: " + header.MessageId, callCategory);
                }

                if (header.State < HeaderState.ResponseMessageId)
                {
                    header.ResponseMessageId = reader.ReadInt32();
                    header.State             = HeaderState.Complete;

                    Trace.WriteLineIf(NTrace.TraceVerbose, "Have message in resoponse to ID: " + header.ResponseMessageId);
                }

                Trace.WriteLineIf(NTrace.TraceVerbose, "Exiting", callCategory);
                return(true);
            }
            catch (Exception ex)
            {
                Trace.WriteLineIf(NTrace.TraceError, "Exiting (error): " + ex, callCategory);
                header = null;
                return(true);
            }
        }
		private void StartReceive (Socket socket, SocketAsyncEventArgs args, BufferValueReader reader)
		{
			if (!this.running)
				return;

			Interlocked.Increment (ref this.pendingAsync);

			try
			{
				args.SetBuffer (0, args.Buffer.Length);
				while (!socket.ReceiveFromAsync (args))
					Receive (this, args);
			}
			catch (ObjectDisposedException) // Socket is disposed, we're done.
			{
				Interlocked.Decrement (ref this.pendingAsync);
			}
		}
        protected virtual void HandleConnectionMessage(SocketAsyncEventArgs args, MessageHeader header, ref BufferValueReader reader)
        {
            UdpConnection connection;

            if (!TryGetConnection(header.ConnectionId, out connection))
            {
                return;
            }

            byte[] buffer    = args.Buffer;
            int    offset    = args.Offset;
            int    moffset   = offset;
            int    remaining = args.BytesTransferred;

            MessageSerializer serializer = connection.serializer;

            if (serializer == null)
            {
                return;
            }

            if (header.State == HeaderState.IV)
            {
                serializer.DecryptMessage(header, ref reader);
                header.IsStillEncrypted = false;

                if (!serializer.TryGetHeader(reader, args.BytesTransferred, ref header))
                {
                    return;
                }
            }

            List <Message> messages = serializer.BufferMessages(ref buffer, ref offset, ref moffset, ref remaining, ref header, ref reader);

            if (messages != null)
            {
                foreach (Message message in messages)
                {
                    connection.Receive(message);
                }
            }

            reader.Position = 0;
        }
		private void HandleConnectionlessMessage (SocketAsyncEventArgs args, MessageHeader header, ref BufferValueReader reader)
		{
			byte[] buffer = args.Buffer;

			int bufferOffset = 0;
			int messageOffset = 0;
			int remaining = args.BytesTransferred;

			List<Message> messages = this.connectionlessSerializer.BufferMessages (ref buffer, ref bufferOffset, ref messageOffset, ref remaining, ref header, ref reader);
			if (messages == null)
				return;

			foreach (Message m in messages)
			{
				var tempestMessage = m as TempestMessage;
				if (tempestMessage != null)
					OnConnectionlessTempestMessage (tempestMessage, args.RemoteEndPoint.ToTarget());
				else
					OnConnectionlessMessageReceived (new ConnectionlessMessageEventArgs (m, args.RemoteEndPoint.ToTarget(), this));
			}
		}
        public void Contracted()
        {
            byte[] buffer = new byte[20480];
            var writer = new BufferValueWriter (buffer);

            ISerializableTester test = new SerializableTester
            {
                Name = "MONKEY!",
                Numbers = new[] { 1, 2, 4, 8, 16, 32 }
            };

            writer.Write (context, test);
            writer.Flush();

            var reader = new BufferValueReader (buffer);
            var serialized = SerializerExtensions.Read<ISerializableTester> (reader, context);

            Assert.IsNotNull (serialized);
            Assert.AreEqual (test.Name, serialized.Name);
            Assert.IsTrue (test.Numbers.SequenceEqual (serialized.Numbers), "Numbers does not match");
        }
        private void HandleConnectionlessMessage(SocketAsyncEventArgs args, MessageHeader header, ref BufferValueReader reader)
        {
            byte[] buffer = args.Buffer;

            int bufferOffset  = 0;
            int messageOffset = 0;
            int remaining     = args.BytesTransferred;

            List <Message> messages = this.connectionlessSerializer.BufferMessages(ref buffer, ref bufferOffset, ref messageOffset, ref remaining, ref header, ref reader);

            if (messages == null)
            {
                return;
            }

            foreach (Message m in messages)
            {
                var tempestMessage = m as TempestMessage;
                if (tempestMessage != null)
                {
                    OnConnectionlessTempestMessage(tempestMessage, args.RemoteEndPoint.ToTarget());
                }
                else
                {
                    OnConnectionlessMessageReceived(new ConnectionlessMessageEventArgs(m, args.RemoteEndPoint.ToTarget(), this));
                }
            }
        }
Beispiel #33
0
        public void Serializer()
        {
            byte[] buffer = new byte[1024];
            var writer = new BufferValueWriter (buffer);

            var c = SerializationContextTests.GetContext (MockProtocol.Instance);
            var p = new Protocol (42, 248);
            p.Serialize (c, writer);
            writer.Flush();

            var reader = new BufferValueReader (buffer);
            var p2 = new Protocol (c, reader);

            Assert.AreEqual (p.id, p2.id);
            Assert.AreEqual (p.Version, p2.Version);
        }
Beispiel #34
0
        // [Test] Testing core APIs that now have NETFX_CORE turned on everywhere
        public void Serializable()
        {
            var inner = new Exception ("Inner exception");
            var ex = new InvalidOperationException ("Don't do this, fool.", inner);

            byte[] buffer = new byte[20480];
            var writer = new BufferValueWriter (buffer);

            writer.Write (context, ex);
            writer.Flush();

            var reader = new BufferValueReader (buffer);

            InvalidOperationException ioex = SerializerExtensions.Read<InvalidOperationException> (reader, context);

            Assert.IsNotNull (ioex);
            Assert.AreEqual (ex.Message, ioex.Message);
            Assert.AreEqual (ex.StackTrace, ioex.StackTrace);

            Assert.IsNotNull (ioex.InnerException);
            Assert.AreEqual (inner.Message, ioex.InnerException.Message);
            Assert.AreEqual (inner.StackTrace, ioex.InnerException.StackTrace);
        }
        List <Message> BufferMessages(ref byte[] buffer, ref int bufferOffset, ref int messageOffset, ref int remainingData, ref MessageHeader header, ref BufferValueReader reader, Func <MessageHeader, bool> messageIdCallback = null)
        {
            List <Message> messages = new List <Message>();

            string callCategory = null;

                        #if TRACE
            int c = GetNextCallId();
            callCategory = String.Format("{0} {1}:BufferMessages({2},{3},{4},{5},{6})", this.connectionType, c, buffer.Length, bufferOffset, messageOffset, remainingData, reader.Position);
                        #endif
            Trace.WriteLineIf(NTrace.TraceVerbose, "Entering", callCategory);

            BufferValueReader currentReader = reader;

            int length = 0;
            while (remainingData >= BaseHeaderLength)
            {
                if (!TryGetHeader(currentReader, remainingData, ref header))
                {
                    Trace.WriteLineIf(NTrace.TraceVerbose, "Message not ready", callCategory);
                    break;
                }

                if (header == null || header.Message == null)
                {
                    header = null;
                    Disconnect();
                    Trace.WriteLineIf(NTrace.TraceVerbose, "Exiting (header not found)", callCategory);
                    return(null);
                }

                length = header.MessageLength;
                if (length > MaxMessageSize)
                {
                    header = null;
                    Disconnect();
                    Trace.WriteLineIf(NTrace.TraceVerbose, "Exiting (bad message size)", callCategory);
                    return(null);
                }

                if (header.State == HeaderState.IV)
                {
                    DecryptMessage(header, ref currentReader);
                    header.IsStillEncrypted = false;
                    continue;
                }

                if (messageIdCallback != null && !messageIdCallback(header))
                {
                    header = null;
                    Disconnect();
                    Trace.WriteLineIf(NTrace.TraceVerbose, "Exiting (message id callback was false)", callCategory);
                    return(null);
                }

                if (remainingData < length)
                {
                    bufferOffset += remainingData;
                    Trace.WriteLineIf(NTrace.TraceVerbose, String.Format("Message not fully received (boffset={0})", bufferOffset), callCategory);
                    break;
                }

                try
                {
                    Trace.WriteLineIf(NTrace.TraceVerbose, String.Format("Reading payload for message {0}", header.Message), callCategory);
                    header.Message.ReadPayload(header.SerializationContext, currentReader);

                    if (!header.Message.Encrypted && header.Message.Authenticated)
                    {
                        // Zero out length for message signing comparison
                                                #if SAFE
                        for (int i = LengthOffset + messageOffset; i < LengthOffset + sizeof(int) + messageOffset; ++i)
                        {
                            buffer[i] = 0;
                        }
                                                #else
                        fixed(byte *bptr = buffer)
                        * ((int *)(bptr + (LengthOffset + messageOffset))) = 0;
                                                #endif

                        int    payloadLength = reader.Position;
                        byte[] signature     = reader.ReadBytes();
                        if (!VerifyMessage(this.signingHashAlgorithm, header.Message, signature, buffer, messageOffset, payloadLength - messageOffset))
                        {
                            Disconnect(ConnectionResult.MessageAuthenticationFailed);
                            Trace.WriteLineIf(NTrace.TraceVerbose, "Exiting (message auth failed)", callCategory);
                            return(null);
                        }
                    }
                } catch (Exception ex) {
                    header = null;
                    Disconnect();
                    Trace.WriteLineIf(NTrace.TraceVerbose, "Exiting for error: " + ex, callCategory);
                    return(null);
                }

                messages.Add(header.Message);

                currentReader = reader;
                header        = null;

                if (length < buffer.Length)
                {
                    messageOffset += length;
                    bufferOffset   = messageOffset;
                    remainingData -= length;
                }
                else
                {
                    messageOffset          = 0;
                    bufferOffset           = 0;
                    remainingData          = 0;
                    currentReader.Position = 0;
                }

                Trace.WriteLineIf(NTrace.TraceVerbose, String.Format("EOL: moffset={0},boffest={1},rdata={2},rpos={3}", messageOffset, bufferOffset, remainingData, reader.Position), callCategory);
            }

            if (remainingData > 0 || messageOffset + BaseHeaderLength >= buffer.Length)
            {
                Trace.WriteLineIf(NTrace.TraceVerbose, (remainingData > 0) ? String.Format("Data remaining: {0:N0}", remainingData) : "Insufficient room for a header", callCategory);

                int knownRoomNeeded = (remainingData > BaseHeaderLength) ? remainingData : BaseHeaderLength;
                if (header != null && remainingData >= BaseHeaderLength)
                {
                    knownRoomNeeded = header.MessageLength;
                }

                int pos = reader.Position - messageOffset;

                Trace.WriteLineIf(NTrace.TraceVerbose, String.Format("Room needed: {0:N0} bytes", knownRoomNeeded), callCategory);
                if (messageOffset + knownRoomNeeded <= buffer.Length)
                {
                    // bufferOffset is only moved on complete headers, so it's still == messageOffset.
                    bufferOffset = messageOffset + remainingData;
                    //reader.Position = pos;

                    Trace.WriteLineIf(NTrace.TraceVerbose, String.Format("Exiting (sufficient room; boffest={0},rpos={1})", bufferOffset, pos), callCategory);
                    return(messages);
                }

                byte[] destinationBuffer = buffer;
                if (knownRoomNeeded > buffer.Length)
                {
                    reader.Dispose();

                    destinationBuffer = new byte[header.MessageLength];
                    reader            = new BufferValueReader(destinationBuffer);
                }

                Buffer.BlockCopy(buffer, messageOffset, destinationBuffer, 0, remainingData);
                reader.Position = pos;
                messageOffset   = 0;
                bufferOffset    = remainingData;
                buffer          = destinationBuffer;

                Trace.WriteLineIf(NTrace.TraceVerbose, String.Format("Exiting (moved message to front, moffset={1},boffset={2},rpos={0})", reader.Position, messageOffset, bufferOffset), callCategory);
            }
            else
            {
                Trace.WriteLineIf(NTrace.TraceVerbose, "Exiting", callCategory);
            }

            return(messages);
        }
Beispiel #36
0
        public void ISerializable()
        {
            byte[] buffer = new byte[20480];
            var writer = new BufferValueWriter (buffer);

            SerializableTester tester = new SerializableTester
            {
                Name = "MONKEY!",
                Numbers = new[] { 1, 2, 4, 8, 16, 32 }
            };

            var test = new AsyncTest();
            tester.SerializeCalled += test.PassHandler;

            writer.Write (context, tester);
            writer.Flush();

            var reader = new BufferValueReader (buffer);
            var serialized = SerializerExtensions.Read<SerializableTester> (reader, context);

            Assert.IsNotNull (serialized);
            Assert.AreEqual (tester.Name, serialized.Name);
            Assert.IsTrue (tester.Numbers.SequenceEqual (serialized.Numbers), "Numbers does not match");

            test.Assert (1000);
        }
Beispiel #37
0
		public void Serialize()
		{
			var person = new Person ("first");
			var person2 = new Person ("second");
			list.Add (person);
			server.DequeueAndAssertMessage<BuddyListMessage>();
			list.Add (person2);
			server.DequeueAndAssertMessage<BuddyListMessage>();

			var writer = new BufferValueWriter (new byte[1024]);
			list.Serialize (clientContext, writer);

			server.AssertNoMessage();

			var reader = new BufferValueReader (writer.Buffer);
			list.Deserialize (clientContext, reader);

			Assert.AreEqual (writer.Length, reader.Position);

			server.AssertNoMessage();

			CollectionAssert.Contains (list, person);
			CollectionAssert.Contains (list, person2);
		}