protected override void Read(PayloadReader reader)
 {
     EndpointID              = (byte)(reader.ReadByte() & 0x7F);
     GenericType             = (GenericType)reader.ReadByte();
     SpecificType            = reader.ReadSpecificType(GenericType);
     SupportedCommandClasses = reader.ReadBytes(reader.Length - reader.Position).Select(element => (CommandClass)element).ToArray();
 }
        protected override void Read(PayloadReader reader)
        {
            var commandClass = reader.ReadByte();

            CommandClass = (CommandClass)commandClass;
            Version      = reader.ReadByte();
        }
Beispiel #3
0
        internal ControllerMessage Decode(Message message, bool hasCallbackID)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            // create reader to deserialize the request
            using (var reader = new PayloadReader(message.Payload))
            {
                // read the function
                var function = (Function)reader.ReadByte();

                var callbackID = hasCallbackID ? reader.ReadByte() : default(byte?);

                // read the payload
                var payload = new Payload(reader.ReadBytes(reader.Length - reader.Position));

                if (message is ResponseMessage)
                {
                    return(new ControllerResponse(function, callbackID, payload));
                }
                if (message is EventMessage)
                {
                    return(new ControllerEvent(function, callbackID, payload));
                }

                throw new InvalidOperationException("Unknown message type");
            }
        }
Beispiel #4
0
 protected override void Read(PayloadReader reader)
 {
     CommandClass     = (CommandClass)reader.ReadByte();
     CommandID        = reader.ReadByte();
     SourceEndpointID = reader.ReadByte();
     TargetEndpointID = reader.ReadByte();
     Payload          = reader.ReadObject <Payload>();
 }
Beispiel #5
0
        protected override void Read(PayloadReader reader)
        {
            var libraryType = reader.ReadByte();

            LibraryType = Enum.IsDefined(typeof(LibraryType), libraryType) ? (LibraryType)libraryType : LibraryType.NotApplicable;

            ProtocolVersion    = reader.ReadByte().ToString("d") + "." + reader.ReadByte().ToString("d2");
            ApplicationVersion = reader.ReadByte().ToString("d") + "." + reader.ReadByte().ToString("d2");
        }
Beispiel #6
0
        protected virtual void Read(PayloadReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException(nameof(reader));
            }

            CommandClass = (CommandClass)reader.ReadByte();
            CommandID    = reader.ReadByte();
            Payload      = new Payload(reader.ReadBytes(reader.Length - reader.Position));
        }
Beispiel #7
0
        void IPayloadSerializable.Read(PayloadReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException(nameof(reader));
            }

            TransmissionState = (TransmissionState)reader.ReadByte();
            Unknown1          = reader.ReadByte();
            Unknown2          = reader.ReadByte();
        }
        protected override void Read(PayloadReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException(nameof(reader));
            }

            GroupID           = reader.ReadByte();
            MaxNodesSupported = reader.ReadByte();
            ReportsToFollow   = reader.ReadByte();
            Nodes             = reader.ReadBytes(reader.Length - reader.Position);
        }
        protected override void Read(PayloadReader reader)
        {
            var endpointsInfo = reader.ReadByte();

            IsDynamicNumberOfEndpoints  = (endpointsInfo & 0x80) > 0;
            AllEndpointsAreIdentical    = (endpointsInfo & 0x40) > 0;
            NumberOfIndividualEndpoints = (byte)(reader.ReadByte() & 0x7F);

            // For version 4 only.
            if (reader.Position < reader.Length)
            {
                NumberOfAggregatedEndpoints = (byte)(reader.ReadByte() & 0x7F);
            }
        }
Beispiel #10
0
        protected override void Read(PayloadReader reader)
        {
            CommandClass = (CommandClass)reader.ReadByte();
            CommandID    = reader.ReadByte();
            Payload      = new Payload(reader.ReadBytes(reader.Length - reader.Position - 2));

            var actualChecksum = reader.ReadInt16();
            var expectedChecksum = new byte[] { (byte)CommandClass, CommandID }.Concat(Payload.ToArray()).CalculateCrc16Checksum();

            if (actualChecksum != expectedChecksum)
            {
                throw new ChecksumException("CRC-16 encapsulated command checksum failure");
            }
        }
Beispiel #11
0
        void IPayloadSerializable.Read(PayloadReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException(nameof(reader));
            }

            var status = reader.ReadByte();

            Status = ReceiveStatus.None;
            if ((status & 0x01) > 0)
            {
                Status |= ReceiveStatus.RoutedBusy;
            }
            if ((status & 0x02) > 0)
            {
                Status |= ReceiveStatus.LowPower;
            }
            if ((status & 0x0C) == 0x00)
            {
                Status |= ReceiveStatus.TypeSingle;
            }
            if ((status & 0x0C) == 0x01)
            {
                Status |= ReceiveStatus.TypeBroad;
            }
            if ((status & 0x0C) == 0x10)
            {
                Status |= ReceiveStatus.TypeMulti;
            }
            if ((status & 0x10) > 0)
            {
                Status |= ReceiveStatus.TypeExplore;
            }
            if ((status & 0x40) > 0)
            {
                Status |= ReceiveStatus.ForeignFrame;
            }

            NodeID = reader.ReadByte();

            var commandLength = reader.ReadByte();
            var commandBytes  = reader.ReadBytes(commandLength);

            Command = Command.Parse(new Payload(commandBytes));
        }
Beispiel #12
0
        protected override void Read(PayloadReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException(nameof(reader));
            }

            Value = reader.ReadByte();
        }
        protected override void Read(PayloadReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException(nameof(reader));
            }

            SupportedGroupings = reader.ReadByte();
        }
        protected override void Read(PayloadReader reader)
        {
            GroupID           = reader.ReadByte();
            MaxNodesSupported = reader.ReadByte();
            ReportsToFollow   = reader.ReadByte();

            var payload = reader.ReadBytes(reader.Length - reader.Position);

            Nodes = payload.TakeWhile(element => element != MultiChannelAssociationReportMarker).ToArray();

            var endpointsPayload = payload.SkipWhile(element => element != MultiChannelAssociationReportMarker).Skip(1).ToArray();

            Endpoints = new EndpointAssociation[endpointsPayload.Length / 2];
            for (int i = 0, j = 0; i < Endpoints.Length; i++, j += 2)
            {
                Endpoints[i] = new EndpointAssociation(endpointsPayload[j], endpointsPayload[j + 1]);
            }
        }
        protected override void Read(PayloadReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException(nameof(reader));
            }

            Type  = (SensorType)reader.ReadByte();
            Value = reader.ReadDouble(out var scale);
            Unit  = GetUnit(Type, scale);
            Scale = scale;
        }
Beispiel #16
0
        public ApiSection(byte[] Data)
            : base()
        {
            ResolveList = new SortedList <string, SortedList <string, VirtualAddress> >();

            PayloadReader reader = new PayloadReader(Data);
            int           length = reader.ReadInteger();

            for (int i = 0; i < length; i++)
            {
                string lib_func = ((Libraries)reader.ReadByte()).ToString();
                string lib      = lib_func + ".dll";

                ResolveList.Add(lib, new SortedList <string, VirtualAddress>());
                short len = reader.ReadShort();
                for (int x = 0; x < len; x++)
                {
                    string func = ((Functions)reader.ReadByte()).ToString().Substring(lib_func.Length + 1);
                    ResolveList[lib].Add(func, new VirtualAddress(4, reader.ReadInteger()));
                }
            }
        }
Beispiel #17
0
        protected override void Read(PayloadReader reader)
        {
            Parameter = reader.ReadByte();
            Size      = (byte)(reader.ReadByte() & 0x07);

            switch (Size)
            {
            case 1:
                Value = reader.ReadByte();
                break;

            case 2:
                Value = reader.ReadInt16();
                break;

            case 4:
                Value = reader.ReadInt32();
                break;

            default:
                throw new NotSupportedException($"Size: {Size} is not supported");
            }
        }
        public object Deserialize(byte[] data)
        {
            PayloadReader pr = new PayloadReader(data);
            ObjectTypes Id = (ObjectTypes)pr.ReadByte();

            switch (Id)
            {
                case ObjectTypes.Null: return null;
                case ObjectTypes.Other:
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    bf.Binder = new DeserializationBinder();
                    return bf.Deserialize(new MemoryStream(pr.ReadBytes(pr.Length - pr.Position)));
                }
                case ObjectTypes.Byte: return pr.ReadByte();
                case ObjectTypes.Short: return pr.ReadShort();
                case ObjectTypes.UShort: return pr.ReadUShort();
                case ObjectTypes.Int: return pr.ReadInteger();
                case ObjectTypes.UINT: return pr.ReadUInteger();
                case ObjectTypes.Long: return pr.ReadLong();
                case ObjectTypes.Bool: return pr.ReadByte() == 1;
                case ObjectTypes.String: return pr.ReadString();
                case ObjectTypes.SolidBrush: return new SolidBrush(Color.FromArgb(pr.ReadByte(), pr.ReadByte(), pr.ReadByte(), pr.ReadByte()));
                case ObjectTypes.Rectangle: return new Rectangle(pr.ReadInteger(), pr.ReadInteger(), pr.ReadInteger(), pr.ReadInteger());
                case ObjectTypes.Size: return new Size(pr.ReadInteger(), pr.ReadInteger());
                case ObjectTypes.ByteArray: return pr.ReadBytes(pr.ReadInteger());
                case ObjectTypes.Bitmap:
                {
                    using (MemoryStream stream = new MemoryStream(pr.Buffer, pr.Position, pr.Length - pr.Position))
                    {
                        long oldPos = stream.Position;
                        Bitmap bmp = (Bitmap)Bitmap.FromStream(stream);
                        pr.Position += (int)(stream.Position - oldPos);
                        return bmp;
                    }
                }
                default: throw new Exception("Error deserializing");
            }
        }
Beispiel #19
0
 protected override void Read(PayloadReader reader)
 {
     Level   = (Powerlevel)reader.ReadByte();
     Timeout = TimeSpan.FromSeconds(reader.ReadByte());
 }
        public object onRequest(AClient connection, PayloadReader pr)
        {
            ReturnResult result = new ReturnResult(null, false);
            bool isDelegate = false;
            bool ReadFullHeader = false;

            try
            {
                int SharedClassId = pr.ReadInteger();
                int MethodId = pr.ReadInteger();
                isDelegate = pr.ReadByte() == 1;
                int DelegateId = isDelegate ? pr.ReadInteger() : 0;
                int DelegateClassId = isDelegate ? pr.ReadInteger() : 0;
                ReadFullHeader = true;

                if (connection.RemoteSharedClasses.ContainsKey(SharedClassId) ||
                    (isDelegate && connection.LocalSharedClasses.ContainsKey(DelegateClassId)))
                {
                    SharedClass sClass = isDelegate ? connection.LocalSharedClasses[SharedClassId] : connection.RemoteSharedClasses[SharedClassId];
                    SharedMethod sharedMethod = sClass.GetMethod(MethodId);

                    if (sharedMethod != null)
                    {
                        List<object> args = new List<object>();
                        List<Type> types = new List<Type>();
                        SortedList<int, SharedDelegate> SharedDelegates = new SortedList<int, SharedDelegate>();
                        SmartSerializer serializer = new SmartSerializer();

                        lock(sharedMethod.Delegates)
                        {
                            if(sharedMethod.Delegates.ContainsKey(DelegateId))
                            {
                                for (int i = 0; i < sharedMethod.Delegates[DelegateId].sharedMethod.ArgumentTypes.Length; i++)
                                {
                                    args.Add(serializer.Deserialize(pr.ReadBytes(pr.ReadInteger())));
                                }
                            }
                            else
                            {
                                for (int i = 0; i < sharedMethod.ArgumentTypes.Length; i++)
                                {
                                    args.Add(serializer.Deserialize(pr.ReadBytes(pr.ReadInteger())));
                                }
                            }
                        }

                        if (!isDelegate) //atm no support yet for delegate inside another delegate
                        {
                            for (int i = 0; i < sharedMethod.DelegateIndex.Count; i++)
                            {
                                if (pr.ReadByte() == 1)
                                {
                                    SharedDelegate del = pr.ReadObject<SharedDelegate>();
                                    del.sharedMethod.sharedClass = sClass;
                                    args[sharedMethod.DelegateIndex.Keys[i]] = DynamicDelegateCreator.CreateDelegate(del);
                                    SharedDelegates.Add(del.sharedMethod.DelegateId, del);
                                }
                            }
                        }

                        if (isDelegate)
                        {
                            //only show the result and not the actual ReturnResult type
                            return sharedMethod.Delegates[DelegateId].Delegate.DynamicInvoke(args.ToArray());
                        }
                        else
                        {
                            MethodInfo m = sClass.InitializedClass.GetType().GetMethod(sharedMethod.Name, sharedMethod.ArgumentTypes);

                            if (m.GetCustomAttributes(typeof(RemoteExecutionAttribute), false).Length == 0 &&
                                m.GetCustomAttributes(typeof(UncheckedRemoteExecutionAttribute), false).Length == 0)
                            {
                                return null;
                            }
                            result.ReturnValue = m.Invoke(sClass.InitializedClass, args.ToArray());
                        }
                    }
                }
            } catch (Exception ex)
            {
                if (isDelegate && ReadFullHeader)
                    throw ex;

                result.exceptionMessage = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                result.ExceptionOccured = true;
            }
            return result;
        }
        private void AynsReceive(IAsyncResult result)
        {
            int BytesTransferred = -1;
            try
            {
                BytesTransferred = Handle.EndReceive(result);

                SysLogger.Log("Received " + BytesTransferred, SysLogType.Network);

                if (BytesTransferred <= 0)
                {
                    Disconnect();
                    return;
                }
            }
            catch(Exception ex)
            {
                SysLogger.Log(ex.Message, SysLogType.Error);
                Disconnect();
                return;
            }

            try
            {
                //let's check the certificate
                if (Client.Server != null && Client.Server.serverProperties != null)
                {
                    if (Client.ConnectionTime > Client.Server.serverProperties.ClientTimeConnected)
                    {
                        //we need to wait till the time is right
                        Disconnect();
                        return;
                    }
                }

                this.LastPacketRecvSW = Stopwatch.StartNew();
                ReadableDataLen += BytesTransferred;
                DataIn += (ulong)BytesTransferred;
                bool Process = true;

                while (Process)
                {
                    if (ReceiveState == ReceiveType.Header)
                    {
                        Process = ReadableDataLen >= HEADER_SIZE;
                        if (ReadableDataLen >= HEADER_SIZE)
                        {
                            lock (HeaderEncryption)
                            {
                                headerConfuser.Deobfuscate(ref Buffer, ReadOffset);
                                HeaderEncryption.Decrypt(Buffer, ReadOffset, HEADER_SIZE);
                            }

                            using(PayloadReader pr = new PayloadReader(Buffer))
                            {
                                pr.Position = ReadOffset;
                                PayloadLen = pr.ReadThreeByteInteger();
                                CurPacketId = pr.ReadByte();
                                ConnectionId = pr.ReadUShort();
                                HeaderId = pr.ReadUShort();
                                HeaderChecksum = pr.ReadByte();
                                FeatureId = pr.ReadInteger();
                            }

                            byte ReChecksum = 0; //re-calculate the checksum
                            ReChecksum += (byte)PayloadLen;
                            ReChecksum += CurPacketId;
                            ReChecksum += (byte)ConnectionId;
                            ReChecksum += (byte)HeaderId;
                            ReChecksum += (byte)FeatureId;

                            if (ReChecksum != HeaderChecksum ||
                                PayloadLen >= MAX_PACKET_SIZE ||
                                PayloadLen < 0)
                            {
                                Disconnect();
                                return;
                            }

                            if(PayloadLen > Buffer.Length)
                            {
                                ResizeBuffer(PayloadLen);
                            }

                            TotalReceived = HEADER_SIZE;
                            ReadableDataLen -= HEADER_SIZE;
                            ReadOffset += HEADER_SIZE;
                            ReceiveState = ReceiveType.Payload;
                        }
                    }
                    else if (ReceiveState == ReceiveType.Payload)
                    {
                        Process = ReadableDataLen >= PayloadLen;
                        if (ReadableDataLen >= PayloadLen)
                        {
                            byte[] DecryptedBuffer = null;
                            int DecryptedBuffLen = 0;

                            messageHandler.DecryptMessage(this, Buffer, ReadOffset, PayloadLen, ref DecryptedBuffer, ref DecryptedBuffLen);

                            if (DecryptedBuffer == null)
                            {
                                //failed to decrypt data
                                Disconnect();
                                return;
                            }

                            TotalReceived += PayloadLen;

                            using (PayloadReader pr = new PayloadReader(DecryptedBuffer))
                            {
                                OperationalSocket OpSocket = null;
                                if (ConnectionId > 0)
                                {
                                    lock(OperationalSockets)
                                    {
                                        if (!OperationalSockets.TryGetValue(ConnectionId, out OpSocket))
                                        {
                                            //strange...
                                            Disconnect();
                                            return;
                                        }
                                    }
                                }

                                Type type = Headers.GetHeaderType(HeaderId);

                                if (type != null)
                                {
                                    Header header = Header.DeSerialize(type, pr);

                                    if(header == null)
                                    {
                                        Disconnect();
                                        return;
                                    }

                                    uint MessageId = pr.ReadUInteger();
                                    IMessage message = OpSocket != null ? OpSocket.MessageHandler.DeSerialize(pr, MessageId) : messageHandler.DeSerialize(pr, MessageId);

                                    if (message != null)
                                    {
                                        message.RawSize = TotalReceived;
                                        message.Header = header;

                                        if (!HandShakeCompleted)
                                        {
                                            if (message.GetType() == typeof(MsgHandshake))
                                            {
                                                //process the handshake messages straight away
                                                message.ProcessPayload(Client, null);
                                            }
                                        }
                                        else
                                        {
                                            ProcessMessage(new SystemPacket(header, message, ConnectionId, OpSocket));
                                        }
                                    }
                                }
                                else
                                {
                                    Disconnect();
                                    return;
                                }
                            }
                            TotalReceived = 0;

                            PacketsIn++;
                            ReadOffset += PayloadLen;
                            ReadableDataLen -= PayloadLen;
                            ReceiveState = ReceiveType.Header;
                        }
                    }
                }

                int len = ReceiveState == ReceiveType.Header ? HEADER_SIZE : PayloadLen;
                if (ReadOffset + len >= this.Buffer.Length)
                {
                    //no more room for this data size, at the end of the buffer ?

                    //copy the buffer to the beginning
                    Array.Copy(this.Buffer, ReadOffset, this.Buffer, 0, ReadableDataLen);

                    WriteOffset = ReadableDataLen;
                    ReadOffset = 0;
                }
                else
                {
                    //payload fits in the buffer from the current offset
                    //use BytesTransferred to write at the end of the payload
                    //so that the data is not split
                    WriteOffset += BytesTransferred;
                }

                if (Buffer.Length - WriteOffset > 0)
                {
                    Handle.BeginReceive(this.Buffer, WriteOffset, Buffer.Length - WriteOffset, SocketFlags.None, AynsReceive, null);
                }
                else
                {
                    //Shoudln't be even possible... very strange
                    Disconnect();
                }
            }
            catch(Exception ex)
            {
                //unexpected error, client might have disconnected itself, or else report this error
                SysLogger.Log(ex.Message, SysLogType.Error);
                Disconnect();
                return;
            }
        }
        private void AynsReceive(IAsyncResult result)
        {
            int BytesTransferred = -1;

            try
            {
                BytesTransferred = Handle.EndReceive(result);

                SysLogger.Log("Received " + BytesTransferred, SysLogType.Network);

                if (BytesTransferred <= 0)
                {
                    Disconnect();
                    return;
                }
            }
            catch (Exception ex)
            {
                SysLogger.Log(ex.Message, SysLogType.Error);
                Disconnect();
                return;
            }

            try
            {
                //let's check the certificate
                if (Client.Server != null && Client.Server.serverProperties != null)
                {
                    if (Client.ConnectionTime > Client.Server.serverProperties.ClientTimeConnected)
                    {
                        //we need to wait till the time is right
                        Disconnect();
                        return;
                    }
                }

                this.LastPacketRecvSW = Stopwatch.StartNew();
                ReadableDataLen      += BytesTransferred;
                DataIn += (ulong)BytesTransferred;
                bool Process = true;

                while (Process)
                {
                    if (ReceiveState == ReceiveType.Header)
                    {
                        Process = ReadableDataLen >= HEADER_SIZE;
                        if (ReadableDataLen >= HEADER_SIZE)
                        {
                            lock (HeaderEncryption)
                            {
                                headerConfuser.Deobfuscate(ref Buffer, ReadOffset);
                                HeaderEncryption.Decrypt(Buffer, ReadOffset, HEADER_SIZE);
                            }

                            using (PayloadReader pr = new PayloadReader(Buffer))
                            {
                                pr.Position    = ReadOffset;
                                PayloadLen     = pr.ReadThreeByteInteger();
                                CurPacketId    = pr.ReadByte();
                                ConnectionId   = pr.ReadUShort();
                                HeaderId       = pr.ReadUShort();
                                HeaderChecksum = pr.ReadByte();
                                FeatureId      = pr.ReadInteger();
                            }

                            byte ReChecksum = 0; //re-calculate the checksum
                            ReChecksum += (byte)PayloadLen;
                            ReChecksum += CurPacketId;
                            ReChecksum += (byte)ConnectionId;
                            ReChecksum += (byte)HeaderId;
                            ReChecksum += (byte)FeatureId;

                            if (ReChecksum != HeaderChecksum ||
                                PayloadLen >= MAX_PACKET_SIZE ||
                                PayloadLen < 0)
                            {
                                Disconnect();
                                return;
                            }

                            if (PayloadLen > Buffer.Length)
                            {
                                ResizeBuffer(PayloadLen);
                            }

                            TotalReceived    = HEADER_SIZE;
                            ReadableDataLen -= HEADER_SIZE;
                            ReadOffset      += HEADER_SIZE;
                            ReceiveState     = ReceiveType.Payload;
                        }
                    }
                    else if (ReceiveState == ReceiveType.Payload)
                    {
                        Process = ReadableDataLen >= PayloadLen;
                        if (ReadableDataLen >= PayloadLen)
                        {
                            byte[] DecryptedBuffer  = null;
                            int    DecryptedBuffLen = 0;

                            messageHandler.DecryptMessage(this, Buffer, ReadOffset, PayloadLen, ref DecryptedBuffer, ref DecryptedBuffLen);

                            if (DecryptedBuffer == null)
                            {
                                //failed to decrypt data
                                Disconnect();
                                return;
                            }

                            TotalReceived += PayloadLen;

                            using (PayloadReader pr = new PayloadReader(DecryptedBuffer))
                            {
                                OperationalSocket OpSocket = null;
                                if (ConnectionId > 0)
                                {
                                    lock (OperationalSockets)
                                    {
                                        if (!OperationalSockets.TryGetValue(ConnectionId, out OpSocket))
                                        {
                                            //strange...
                                            Disconnect();
                                            return;
                                        }
                                    }
                                }

                                Type type = Headers.GetHeaderType(HeaderId);

                                if (type != null)
                                {
                                    Header header = Header.DeSerialize(type, pr);

                                    if (header == null)
                                    {
                                        Disconnect();
                                        return;
                                    }

                                    uint     MessageId = pr.ReadUInteger();
                                    IMessage message   = OpSocket != null?OpSocket.MessageHandler.DeSerialize(pr, MessageId) : messageHandler.DeSerialize(pr, MessageId);

                                    if (message != null)
                                    {
                                        message.RawSize = TotalReceived;
                                        message.Header  = header;

                                        if (!HandShakeCompleted)
                                        {
                                            if (message.GetType() == typeof(MsgHandshake))
                                            {
                                                //process the handshake messages straight away
                                                message.ProcessPayload(Client, null);
                                            }
                                        }
                                        else
                                        {
                                            ProcessMessage(new SystemPacket(header, message, ConnectionId, OpSocket));
                                        }
                                    }
                                }
                                else
                                {
                                    Disconnect();
                                    return;
                                }
                            }
                            TotalReceived = 0;

                            PacketsIn++;
                            ReadOffset      += PayloadLen;
                            ReadableDataLen -= PayloadLen;
                            ReceiveState     = ReceiveType.Header;
                        }
                    }
                }

                int len = ReceiveState == ReceiveType.Header ? HEADER_SIZE : PayloadLen;
                if (ReadOffset + len >= this.Buffer.Length)
                {
                    //no more room for this data size, at the end of the buffer ?

                    //copy the buffer to the beginning
                    Array.Copy(this.Buffer, ReadOffset, this.Buffer, 0, ReadableDataLen);

                    WriteOffset = ReadableDataLen;
                    ReadOffset  = 0;
                }
                else
                {
                    //payload fits in the buffer from the current offset
                    //use BytesTransferred to write at the end of the payload
                    //so that the data is not split
                    WriteOffset += BytesTransferred;
                }

                if (Buffer.Length - WriteOffset > 0)
                {
                    Handle.BeginReceive(this.Buffer, WriteOffset, Buffer.Length - WriteOffset, SocketFlags.None, AynsReceive, null);
                }
                else
                {
                    //Shoudln't be even possible... very strange
                    Disconnect();
                }
            }
            catch (Exception ex)
            {
                //unexpected error, client might have disconnected itself, or else report this error
                SysLogger.Log(ex.Message, SysLogType.Error);
                Disconnect();
                return;
            }
        }
Beispiel #23
0
        public override void ProcessPayload(SSPClient client, OperationalSocket OpSocket)
        {
            ReturnResult   result = new ReturnResult(null, false);
            LiteCodeClient Client = OpSocket as LiteCodeClient;

            try
            {
                PayloadReader pr     = new PayloadReader(Data);
                SharedClass   sClass = null;

                if (Client.InitializedClasses.TryGetValue(SharedClassId, out sClass))
                {
                    SharedMethod sharedMethod = sClass.GetMethod(MethodId);

                    if (sharedMethod != null)
                    {
                        List <object> args  = new List <object>();
                        List <Type>   types = new List <Type>();
                        SortedList <int, SharedDelegate> SharedDelegates = new SortedList <int, SharedDelegate>();
                        SmartSerializer serializer = new SmartSerializer();

                        lock (sharedMethod.Delegates)
                        {
                            SharedDelegate sharedDel = null;
                            if (sharedMethod.Delegates.TryGetValue(DelegateId, out sharedDel))
                            {
                                for (int i = 0; i < sharedDel.sharedMethod.ArgumentTypes.Length; i++)
                                {
                                    args.Add(serializer.Deserialize(pr.ReadBytes(pr.ReadInteger())));
                                }
                            }
                            else
                            {
                                for (int i = 0; i < sharedMethod.ArgumentTypes.Length; i++)
                                {
                                    args.Add(serializer.Deserialize(pr.ReadBytes(pr.ReadInteger())));
                                }
                            }
                        }

                        if (!isDelegate) //atm no support yet for delegate inside another delegate
                        {
                            for (int i = 0; i < sharedMethod.DelegateIndex.Count; i++)
                            {
                                if (pr.ReadByte() == 1)
                                {
                                    SharedDelegate del = pr.ReadObject <SharedDelegate>();
                                    del.sharedMethod.sharedClass             = sClass;
                                    args[sharedMethod.DelegateIndex.Keys[i]] = DynamicDelegateCreator.CreateDelegate(del);
                                    SharedDelegates.Add(del.sharedMethod.DelegateId, del);
                                }
                            }
                        }

                        if (isDelegate)
                        {
                            result.ReturnValue = sharedMethod.Delegates[DelegateId].Delegate.DynamicInvoke(args.ToArray());
                        }
                        else
                        {
                            if (sharedMethod.CallCache == null)
                            {
                                MethodInfo methodInf = sClass.InitializedClass.GetType().GetMethod(sharedMethod.Name, sharedMethod.ArgumentTypes);
                                sharedMethod.CallCache = methodInf.Bind();
                            }
                            result.ReturnValue = sharedMethod.CallCache(sClass.InitializedClass, args.ToArray());

                            /*MethodInfo methodInf = sClass.InitializedClass.GetType().GetMethod(sharedMethod.Name, sharedMethod.ArgumentTypes);
                             * result.ReturnValue = methodInf.Invoke(sClass.InitializedClass, args.ToArray());*/
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result.exceptionMessage = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                result.ExceptionOccured = true;
                client.onException(ex.InnerException != null ? ex.InnerException : ex, ErrorType.UserLand);
            }

            if (RequireResultBack)
            {
                Client.Send(new MsgExecuteMethodResponse(RequestId, result));
            }
        }
        internal unsafe void AsyncSocketCallback(object o, SocketAsyncEventArgs e)
        {
            if (e.LastOperation == SocketAsyncOperation.ReceiveFrom)
            {
                try
                {
                    if (e.BytesTransferred >= 21)
                    {
                        if (!Connected)
                        {
                            return; //TCP Client is disconnected so don't process UDP packets
                        }
                        //before we process the packet, does the IP/LocalPort match ?
                        if (UdpHandshaked && BitConverter.ToUInt32(this.UdpEndPoint.Address.GetAddressBytes(), 0) !=
                            BitConverter.ToUInt32(((IPEndPoint)e.RemoteEndPoint).Address.GetAddressBytes(), 0))
                        {
                            //simply skip and don't disconnect TCP
                            //I'll add later a option to the server to disconnect or not just for safety reasons ;)
                            return;
                        }

                        //decrypt traffic here
                        PayloadReader pr       = new PayloadReader(e.Buffer);
                        decimal       clientId = pr.ReadDecimal();

                        //extra check
                        if (this.ClientId != clientId)
                        {
                            return;
                        }

                        UdpPAcketId packetId  = (UdpPAcketId)pr.ReadByte();
                        uint        MessageId = pr.ReadUInteger();

                        IMessage message = null;
                        try
                        {
                            message = Connection.messageHandler.HandleUdpMessage(pr, MessageId);

                            if (message != null)
                            {
                                message.RawSize = e.BytesTransferred;
                            }
                        }
                        catch (Exception ex)
                        {
                            return;
                        }


                        //process packet
                        if (UdpHandshaked)
                        {
                            switch (packetId)
                            {
                            case UdpPAcketId.Payload:
                            {
                                //onReceiveUdpMessage(message);
                                break;
                            }
                            }
                        }
                        else
                        {
                            MsgUdpHandshake HandshakeMsg = message as MsgUdpHandshake;
                            if (HandshakeMsg != null)
                            {
                                fixed(byte *ptr = HandshakeMsg.HandshakeCode, ptr2 = this.UdpHandshakeCode)
                                {
                                    if (NativeMethods.memcmp(ptr, ptr2, (uint)this.UdpHandshakeCode.Length) == 0)
                                    {
                                        this.UdpEndPoint = e.RemoteEndPoint as IPEndPoint;
                                        Connection.SendPayload(new MsgUdpValidation(new byte[] { 0x8F, 0xFF, 0x46, 0x4F, 0x37 }), PacketId.Unknown);
                                        UdpHandshaked       = true;
                                        UdpSyncObject.Value = true;
                                        UdpSyncObject.Pulse();
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    onException(ex, ErrorType.Core);
                }

                if (PeerSide == SecureSocketProtocol2.PeerSide.Client)
                {
                    if (!UdpHandle.ReceiveFromAsync(UdpAsyncReceiveEvent))
                    {
                        AsyncSocketCallback(null, UdpAsyncReceiveEvent);
                    }
                }
            }
            else
            {
            }
        }
Beispiel #25
0
        public IMessage DeCacheMessage(IMessage message, PayloadReader pr, ref bool isCached, ref IMessage CachedMessage, MessageHandler msgHandler)
        {
            lock (Messages)
            {
                uint Id = msgHandler.GetMessageId(message.GetType());
                isCached = pr.ReadBool();

                if (!Messages.TryGetValue(Id, out CachedMessage) && !isCached)
                {
                    CachedMessage = (IMessage)Activator.CreateInstance(message.GetType());
                    Messages.Add(Id, (IMessage)Activator.CreateInstance(message.GetType()));

                    FieldInfo[] _fields       = message.GetType().GetFields();
                    FieldInfo[] _cachedFields = CachedMessage.GetType().GetFields();

                    for (int i = 0; i < _fields.Length; i++)
                    {
                        //de-serialize objects
                        int oldPos = pr.Offset;
                        _fields[i].SetValue(message, pr.ReadObject());
                        pr.Offset = oldPos;
                        _fields[i].SetValue(Messages[Id], pr.ReadObject());
                    }
                    return(message);
                }

                FieldInfo[] fields      = message.GetType().GetFields();
                FieldInfo[] cacheFields = CachedMessage.GetType().GetFields();

                for (int i = 0; i < fields.Length; i++)
                {
                    MessageCacheType CacheType = (MessageCacheType)pr.ReadByte();
                    object           NewValue  = null;

                    switch (CacheType)
                    {
                    case MessageCacheType.Bool:
                    {
                        NewValue = pr.ReadBool();
                        break;
                    }

                    case MessageCacheType.Byte:
                    {
                        NewValue = pr.ReadByte();
                        break;
                    }

                    case MessageCacheType.ByteArray:
                    {
                        uint size = pr.ReadUInteger();
                        NewValue = pr.ReadBytes((int)size);
                        break;
                    }

                    case MessageCacheType.Decimal:
                    {
                        NewValue = pr.ReadDecimal();
                        break;
                    }

                    case MessageCacheType.Double:
                    {
                        NewValue = pr.ReadDouble();
                        break;
                    }

                    case MessageCacheType.Float:
                    {
                        NewValue = pr.ReadFloat();
                        break;
                    }

                    case MessageCacheType.Long:
                    {
                        NewValue = pr.ReadLong();
                        break;
                    }

                    case MessageCacheType.NULL:
                    {
                        NewValue = null;
                        break;
                    }

                    case MessageCacheType.OtherObject:
                    {
                        NewValue = pr.ReadObject();
                        break;
                    }

                    case MessageCacheType.Short:
                    {
                        NewValue = pr.ReadShort();
                        break;
                    }

                    case MessageCacheType.String:
                    {
                        NewValue = pr.ReadString();
                        break;
                    }

                    case MessageCacheType.Integer:
                    {
                        NewValue = pr.ReadInteger();
                        break;
                    }

                    case MessageCacheType.UInteger:
                    {
                        NewValue = pr.ReadUInteger();
                        break;
                    }

                    case MessageCacheType.ULong:
                    {
                        NewValue = pr.ReadULong();
                        break;
                    }

                    case MessageCacheType.UShort:
                    {
                        NewValue = pr.ReadUShort();
                        break;
                    }

                    case MessageCacheType.NotUpdated:
                    {
                        NewValue = cacheFields[i].GetValue(CachedMessage);
                        break;
                    }
                    }
                    fields[i].SetValue(message, NewValue);
                }
            }
            return(message);
        }
Beispiel #26
0
 protected override void Read(PayloadReader reader)
 {
     Interval     = TimeSpan.FromSeconds(reader.ReadInt24());
     TargetNodeID = reader.ReadByte();
 }
Beispiel #27
0
        public override void ProcessPayload(IClient client, IPlugin plugin = null)
        {
            ReturnResult result         = new ReturnResult(null, false);
            bool         isDelegate     = false;
            bool         ReadFullHeader = false;
            SSPClient    Client         = client as SSPClient;

            try
            {
                PayloadReader pr            = new PayloadReader(Data);
                int           SharedClassId = pr.ReadInteger();
                int           MethodId      = pr.ReadInteger();
                isDelegate = pr.ReadByte() == 1;
                int DelegateId      = isDelegate ? pr.ReadInteger() : 0;
                int DelegateClassId = isDelegate ? pr.ReadInteger() : 0;
                ReadFullHeader = true;

                if (Client.Connection.InitializedClasses.ContainsKey(SharedClassId))
                {
                    SharedClass  sClass       = Client.Connection.InitializedClasses[SharedClassId];
                    SharedMethod sharedMethod = sClass.GetMethod(MethodId);

                    if (sharedMethod != null)
                    {
                        List <object> args  = new List <object>();
                        List <Type>   types = new List <Type>();
                        SortedList <int, SharedDelegate> SharedDelegates = new SortedList <int, SharedDelegate>();
                        SmartSerializer serializer = new SmartSerializer();

                        lock (sharedMethod.Delegates)
                        {
                            if (sharedMethod.Delegates.ContainsKey(DelegateId))
                            {
                                for (int i = 0; i < sharedMethod.Delegates[DelegateId].sharedMethod.ArgumentTypes.Length; i++)
                                {
                                    args.Add(serializer.Deserialize(pr.ReadBytes(pr.ReadInteger())));
                                }
                            }
                            else
                            {
                                for (int i = 0; i < sharedMethod.ArgumentTypes.Length; i++)
                                {
                                    args.Add(serializer.Deserialize(pr.ReadBytes(pr.ReadInteger())));
                                }
                            }
                        }

                        if (!isDelegate) //atm no support yet for delegate inside another delegate
                        {
                            for (int i = 0; i < sharedMethod.DelegateIndex.Count; i++)
                            {
                                if (pr.ReadByte() == 1)
                                {
                                    SharedDelegate del = pr.ReadObject <SharedDelegate>();
                                    del.sharedMethod.sharedClass             = sClass;
                                    args[sharedMethod.DelegateIndex.Keys[i]] = DynamicDelegateCreator.CreateDelegate(del);
                                    SharedDelegates.Add(del.sharedMethod.DelegateId, del);
                                }
                            }
                        }

                        if (isDelegate)
                        {
                            result.ReturnValue = sharedMethod.Delegates[DelegateId].Delegate.DynamicInvoke(args.ToArray());
                        }
                        else
                        {
                            MethodInfo methodInf = sClass.InitializedClass.GetType().GetMethod(sharedMethod.Name, sharedMethod.ArgumentTypes);

                            if (methodInf.GetCustomAttributes(typeof(RemoteExecutionAttribute), false).Length == 0 &&
                                methodInf.GetCustomAttributes(typeof(UncheckedRemoteExecutionAttribute), false).Length == 0)
                            {
                                //return null;
                            }
                            result.ReturnValue = methodInf.Invoke(sClass.InitializedClass, args.ToArray());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //if (isDelegate && ReadFullHeader)
                //    throw ex;

                result.exceptionMessage = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                result.ExceptionOccured = true;
                client.onException(ex.InnerException != null ? ex.InnerException : ex, ErrorType.UserLand);
            }

            if (RequireResultBack)
            {
                Client.Connection.SendMessage(new MsgExecuteMethodResponse(RequestId, result), PacketId.LiteCodeResponse);
            }

            base.ProcessPayload(client, plugin);
        }
Beispiel #28
0
        public object onRequest(AClient connection, PayloadReader pr)
        {
            ReturnResult result         = new ReturnResult(null, false);
            bool         isDelegate     = false;
            bool         ReadFullHeader = false;

            try
            {
                int SharedClassId = pr.ReadInteger();
                int MethodId      = pr.ReadInteger();
                isDelegate = pr.ReadByte() == 1;
                int DelegateId      = isDelegate ? pr.ReadInteger() : 0;
                int DelegateClassId = isDelegate ? pr.ReadInteger() : 0;
                ReadFullHeader = true;

                if (connection.RemoteSharedClasses.ContainsKey(SharedClassId) ||
                    (isDelegate && connection.LocalSharedClasses.ContainsKey(DelegateClassId)))
                {
                    SharedClass  sClass       = isDelegate ? connection.LocalSharedClasses[SharedClassId] : connection.RemoteSharedClasses[SharedClassId];
                    SharedMethod sharedMethod = sClass.GetMethod(MethodId);

                    if (sharedMethod != null)
                    {
                        List <object> args  = new List <object>();
                        List <Type>   types = new List <Type>();
                        SortedList <int, SharedDelegate> SharedDelegates = new SortedList <int, SharedDelegate>();
                        SmartSerializer serializer = new SmartSerializer();

                        lock (sharedMethod.Delegates)
                        {
                            if (sharedMethod.Delegates.ContainsKey(DelegateId))
                            {
                                for (int i = 0; i < sharedMethod.Delegates[DelegateId].sharedMethod.ArgumentTypes.Length; i++)
                                {
                                    args.Add(serializer.Deserialize(pr.ReadBytes(pr.ReadInteger())));
                                }
                            }
                            else
                            {
                                for (int i = 0; i < sharedMethod.ArgumentTypes.Length; i++)
                                {
                                    args.Add(serializer.Deserialize(pr.ReadBytes(pr.ReadInteger())));
                                }
                            }
                        }

                        if (!isDelegate) //atm no support yet for delegate inside another delegate
                        {
                            for (int i = 0; i < sharedMethod.DelegateIndex.Count; i++)
                            {
                                if (pr.ReadByte() == 1)
                                {
                                    SharedDelegate del = pr.ReadObject <SharedDelegate>();
                                    del.sharedMethod.sharedClass             = sClass;
                                    args[sharedMethod.DelegateIndex.Keys[i]] = DynamicDelegateCreator.CreateDelegate(del);
                                    SharedDelegates.Add(del.sharedMethod.DelegateId, del);
                                }
                            }
                        }

                        if (isDelegate)
                        {
                            //only show the result and not the actual ReturnResult type
                            return(sharedMethod.Delegates[DelegateId].Delegate.DynamicInvoke(args.ToArray()));
                        }
                        else
                        {
                            MethodInfo m = sClass.InitializedClass.GetType().GetMethod(sharedMethod.Name, sharedMethod.ArgumentTypes);

                            if (m.GetCustomAttributes(typeof(RemoteExecutionAttribute), false).Length == 0 &&
                                m.GetCustomAttributes(typeof(UncheckedRemoteExecutionAttribute), false).Length == 0)
                            {
                                return(null);
                            }
                            result.ReturnValue = m.Invoke(sClass.InitializedClass, args.ToArray());
                        }
                    }
                }
            } catch (Exception ex)
            {
                if (isDelegate && ReadFullHeader)
                {
                    throw ex;
                }

                result.exceptionMessage = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                result.ExceptionOccured = true;
            }
            return(result);
        }
Beispiel #29
0
        public void OnLogin(ClientSession cs, InPacket ip)
        {
            PayloadReader pReader = new PayloadReader(ip.Payload);

            Database db = new Database();

            pReader.Skip(7);
            byte IDLength = pReader.ReadByte();

            UID = pReader.ReadString(IDLength);

            pReader.Skip(3);

            byte PWLength = pReader.ReadByte();

            UPW = pReader.ReadString(PWLength);

            if (db.OpenDB())
            {
                try
                {
                    MySqlDataReader sReader = db.Query("SELECT * FROM users WHERE LOGIN = @0 AND PASS = @1", UID, UPW);
                    Log.SqlQuerys(db.dbcmd.CommandText);

                    if (!sReader.HasRows)
                    {
                        Log.Inform("Falha no login. Usuário: {0}", UID);

                        try
                        {
                            PayloadWriter pWriter = new PayloadWriter();

                            byte[] plContent = { 0x00, 0x00, 0x00, 0x14 };
                            pWriter.WriteData(plContent);

                            pWriter.WriteData(IDLength * 2);
                            pWriter.WriteUnicodeString(UID);

                            byte[] plContent1 = { 0x00, 0x00, 0x00, 0x00, 0x00 };
                            pWriter.WriteData(plContent1);

                            OutPacket oPacket = new OutPacket(pWriter.GetCompressedPayload(CenterOpcodes.ENU_VERIFY_ACCOUNT_ACK),
                                                              cs._CryptoHandler, cs._AuthHandler, cs.Prefix, ++cs.Count);

                            cs.Send(oPacket);
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex.Message);
                            while (true)
                            {
                                ;
                            }
                        }
                    }
                    else
                    {
                        // Successful login.
                        Log.Inform("Novo login. Usuário: {0}", UID);

                        // Send server list first.
                        Log.Inform("Enviando a lista de servidores.");
                        SendServerList(cs);
                        SendChannelNews(cs);
                        SendShop(cs);
                        SendClientContentOpen(cs);
                        SendSocketTableInfo(cs);
                        SendCashbackRatio(cs);

                        //Log.Inform("로그인 성공 메시지를 전송합니다.", ID);

                        PayloadWriter pWritter = new PayloadWriter();

                        byte[] plContent = { 0x00, 0x00, 0x00, 0x00 };
                        pWritter.WriteData(plContent);
                        pWritter.WriteData(IDLength * 2);
                        pWritter.WriteUnicodeString(UID);
                        pWritter.WriteData(PWLength);
                        pWritter.WriteData(UPW);

                        byte[] plContent2 = Util.StringToByteArray("00 00 00 00 14 00 8E A7 C5 01 00 00 00 00 00 00 02 4B 52 00 05 A3 BD 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 00");
                        pWritter.WriteData(plContent2);

                        pWritter.WriteData(cs.MyLoading.GuildMarkURL.Length * 2);
                        pWritter.WriteUnicodeString(cs.MyLoading.GuildMarkURL);

                        byte[] plContent3 = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
                        pWritter.WriteData(plContent3);

                        int SHAi = cs.MyLoading.SHAFileList.Length;
                        pWritter.WriteData(SHAi);

                        for (int i = 0; i <= cs.MyLoading.SHAFileList.Length - 1; i++)
                        {
                            pWritter.WriteData(cs.MyLoading.SHAFileList[i].Length * 2);
                            pWritter.WriteUnicodeString(cs.MyLoading.SHAFileList[i]);
                            pWritter.WriteData(true);
                        }

                        byte[] plContent4 = Util.StringToByteArray("00 00 00 01 00 00 00 03 00 00 00 00 00 00 00 00 64 01 00 00 00 00 00 00 00 64 02 00 00 00 00 00 00 00 64 01 BF 80 00 00 FC 04 97 FF 00 00 00 00 00 00 00 00 00 00 00 00");
                        pWritter.WriteData(plContent4);

                        OutPacket oPacket = new OutPacket(pWritter.GetCompressedPayload(CenterOpcodes.ENU_VERIFY_ACCOUNT_ACK),
                                                          cs._CryptoHandler, cs._AuthHandler, cs.Prefix, ++cs.Count);

                        cs.Send(oPacket);
                    }

                    sReader.Close();
                    db.dbconn.Close();
                }
                catch (MySql.Data.MySqlClient.MySqlException ex)
                {
                    Log.Sql(ex.Message);
                    while (true)
                    {
                        ;
                    }
                }
            }
        }