Esempio n. 1
0
        public void RegisterPacketHandlers()
        {
            var types = Assembly.GetAssembly(typeof(TPacketHandler))
                        .GetTypes()
                        .Where(x => x.IsSubclassOf(typeof(TPacketHandler)));

            foreach (var type in types)
            {
                var attributes = type.GetTypeInfo()
                                 .GetCustomAttributes()
                                 .OfType <PacketHandlerAttribute>()
                                 .ToList();

                foreach (var attribute in attributes)
                {
                    var header = attribute.Header;

                    if (!PacketHandlers.ContainsKey(header))
                    {
                        PacketHandlers[header] = new List <TPacketHandler>();
                    }

                    var handler = (TPacketHandler)Activator.CreateInstance(type);
                    PacketHandlers[header].Add(handler);
                }
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Removes a packet handler
        /// </summary>
        /// <param name="handler"></param>
        public bool UnregisterPacketHandler(IPacketHandler handler)
        {
            if (PacketHandlers.ContainsKey(handler.Type))
            {
                return(PacketHandlers[handler.Type].Remove(handler));
            }

            return(false);
        }
Esempio n. 3
0
 private void HandlePacket(RemoteClient client, IPacket packet)
 {
     if (!PacketHandlers.ContainsKey(packet.GetType()))
     {
         return;
     }
     //throw new InvalidOperationException("No packet handler registered for 0x" + packet.Id.ToString("X2"));
     PacketHandlers[packet.GetType()](client, this, packet);
 }
Esempio n. 4
0
        private void HandlePacket(IPacket packet)
        {
            var type = packet.GetType();

            if (PacketHandlers.ContainsKey(type))
            {
                PacketHandlers[type](this, packet);
            }
            //throw new InvalidOperationException("Recieved a packet we can't handle: " + packet.GetType().Name);
        }
        public static bool AddPacketHandler(PacketType packetType, PacketMethod handler)
        {
            bool result = false;

            lock (PacketHandlers) {
                if (!PacketHandlers.ContainsKey(packetType))
                {
                    PacketHandlers.Add(packetType, handler);
                    result = true;
                }
            }
            return(result);
        }
Esempio n. 6
0
 /// <summary>
 /// Registers a set of packet handlers to be used by new connections
 /// </summary>
 /// <param name="handlers">The handlers to register</param>
 public void RegisterPacketHandlers(IEnumerable <IPacketHandler> handlers)
 {
     foreach (IPacketHandler handler in handlers)
     {
         if (!PacketHandlers.ContainsKey(handler.Type))
         {
             PacketHandlers.Add(handler.Type, new List <IPacketHandler>(new[] { handler }));
         }
         else
         {
             PacketHandlers[handler.Type].Add(handler);
         }
     }
 }
        public void SetPacketHandler(ClientPacketId id, NetPacketHandler packetHandler)
        {
            if (packetHandler == null)
            {
                throw new ArgumentNullException(nameof(packetHandler));
            }

            if (PacketHandlers.ContainsKey(id))
            {
                throw new ArgumentException($"A packet handler is already registered for \"{id}\".", nameof(id));
            }

            PacketHandlers.Add(id, packetHandler);
        }
Esempio n. 8
0
        private void OnReceivedPacket(object sender, PacketEventArgs args)
        {
            var packet = args.Packet;

            //Console.WriteLine(packet.Type.ToString() + "," + packet.Opcode.ToString());
            if (PacketHandlers.ContainsKey(packet.Type))
            {
                if (PacketHandlers[packet.Type].ContainsKey(packet.Opcode))
                {
                    if (PacketHandlers[packet.Type][packet.Opcode] != null)
                    {
                        PacketHandlers[packet.Type][packet.Opcode](packet);
                    }
                }
            }
        }
Esempio n. 9
0
        /// <summary>
        /// The processing system
        /// </summary>
        /// <param name="bot">The bot to attach to</param>
        /// <param name="inPacket">The packet coming in</param>
        /// <param name="client">The client to attach to</param>
        public void Process(PalBot bot, Packet inPacket, Client client)
        {
            Packet packet;

            if (!CheckPacket(inPacket, out packet))
            {
                return;
            }

            if (PacketHandlers == null || PacketHandlers.Count == 0)
            {
                LoadPacketHandlers(bot);
            }

            if (!PacketHandlers.ContainsKey(packet.Command.ToUpper()))
            {
                bot.On.Trigger("pk", packet);
                return;
            }

            if (packet["COMPRESSION"] == "1")
            {
                packet.Payload = packet.DecompressPayload();
            }

            try
            {
                bot.Callbacks.Activate(packet);

                var plug = PacketHandlers[packet.Command.ToUpper()];
                var i    = (IPacketHandler)Activator.CreateInstance(plug);

                i.Bot    = bot;
                i.Client = client;
                i.Process(packet);
            }
            catch (Exception ex)
            {
                bot.On.Trigger("e", ex);
            }
        }
Esempio n. 10
0
        protected virtual async Task ProcessAsync(SocketAsyncEventArgs e)
        {
            if (e.SocketError == SocketError.Success && e.BytesTransferred > 0)
            {
                bool exception = false;

                try
                {
                    if (_cts.IsCancellationRequested)
                    {
                        return;
                    }

                    SocketAsyncEventArgs newArgs = Proxy.ListeningServer.SocketPool.Get();
                    newArgs.Completed += Operation_Completed;

                    if (ConnectionClient != null && !ConnectionClient.ReceiveAsync(newArgs))
                    {
                        Operation_Completed(this, newArgs);
                    }

                    await _sem.WaitAsync(_cts.Token);

                    var packets = PacketReader.Read(_processor, e.Buffer, e.Offset, e.BytesTransferred);

                    foreach (Packet packet in packets)
                    {
                        if (_cts.IsCancellationRequested)
                        {
                            return;
                        }

                        if (packet == null)
                        {
                            StarLog.DefaultLogger.Warn("Encountered null packet!");

                            continue;
                        }

                        try
                        {
                            packet.Direction = Direction;

                            Type pType = packet.GetType();
                            List <IPacketHandler> pHandlers = null;
                            if (PacketHandlers.ContainsKey(pType))
                            {
                                pHandlers = PacketHandlers[pType];

                                var tasks = new List <Task>();
                                foreach (IPacketHandler beforeHandler in pHandlers)
                                {
                                    tasks.Add(beforeHandler.HandleBeforeAsync(packet, this));
                                }

                                await Task.WhenAll(tasks);
                            }

                            EventHandler <PacketEventArgs> packetArgs = PacketReceived;
                            if (packetArgs != null)
                            {
                                packetArgs(this, new PacketEventArgs(Proxy, packet));
                            }

                            OtherConnection.FlushPacket(packet);

                            if (pHandlers != null)
                            {
                                var tasks = new List <Task>();
                                foreach (IPacketHandler sentHandler in pHandlers)
                                {
                                    tasks.Add(sentHandler.HandleAfterAsync(packet, this));
                                }

                                await Task.WhenAll(tasks);
                            }

                            EventHandler <PacketEventArgs> aPacketArgs = AfterPacketReceived;
                            if (aPacketArgs != null)
                            {
                                aPacketArgs(this, new PacketEventArgs(Proxy, packet));
                            }
                        }
                        catch (Exception ex)
                        {
                            ex.LogError();
                        }
                    }

                    _sem.Release();
                }
                catch (Exception)
                {
                    exception = true;
                }

                if (exception)
                {
                    await CloseAsync();
                }
            }
            else
            {
                await CloseAsync();
            }
        }
Esempio n. 11
0
        private void NetworkMessageReceived(IAsyncResult result)
        {
            IPEndPoint endPoint = default(IPEndPoint);
            var        payload  = NetworkClient.EndReceive(result, ref endPoint);

            NetworkClient.BeginReceive(NetworkMessageReceived, null);
            var stream = new BinaryReader(new MemoryStream(payload), Encoding.UTF8);
            AsymmetricKeyParameter key;
            RemoteNode             node = null;

            if (endPoint.Address.Equals(IPAddress.Loopback))
            {
                key = CryptoProvider.PublicKey;
            }
            else
            {
                node = GetNode(endPoint);
                if (node == null)
                {
                    return;
                }
                key = node.PublicKey;
            }
            try
            {
                var id          = stream.ReadString();
                var flags       = (MessageFlags)stream.ReadByte();
                var transaction = stream.ReadUInt32();
                var timestamp   = new DateTime(stream.ReadInt64(), DateTimeKind.Utc);
                if (node != null)
                {
                    // TODO: Evaluate this margin of error, and this whole system in general that prevents resubmission
                    if (Math.Abs((timestamp - node.PreviousMessageTimestamp).TotalSeconds) > 10)
                    {
                        return;
                    }
                    node.PreviousMessageTimestamp = timestamp;
                }
                if (PacketFactories.ContainsKey(id))
                {
                    var packet = PacketFactories[id]();
                    packet.Transaction = transaction;
                    packet.Read(stream);
                    int signatureLength = (int)(stream.BaseStream.Length - stream.BaseStream.Position);
                    int messageLength   = (int)stream.BaseStream.Position;
                    stream.BaseStream.Seek(0, SeekOrigin.Begin);
                    byte[] message   = new byte[messageLength];
                    byte[] signature = new byte[signatureLength];
                    stream.BaseStream.Read(message, 0, message.Length);
                    stream.BaseStream.Read(signature, 0, signature.Length);
                    // Verify signature
                    if (!CryptoProvider.VerifySignature(message, signature, key))
                    {
                        Console.WriteLine("Warning: Received internode network packet with bad signature from {0}", endPoint);
                    }
                    else
                    {
                        if (id == typeof(ConfirmationPacket).Name)
                        {
                            HandleConfirmation(packet);
                        }
                        else if (PacketHandlers.ContainsKey(id))
                        {
                            PacketHandlers[id](packet, endPoint, this);
                        }
                        else
                        {
                            Console.WriteLine("Warning: Unhandled internode network packet with ID {0}", id);
                        }
                        if ((flags & MessageFlags.PropegateTransaction) > 0 && endPoint.Address == IPAddress.Loopback)
                        {
                            foreach (var target in Network)
                            {
                                if (target != node)
                                {
                                    Send(packet, target.EndPoint);
                                }
                            }
                        }
                        if ((flags & MessageFlags.ConfirmationRequired) > 0)
                        {
                            Send(new ConfirmationPacket(transaction), endPoint); // TODO: Don't re-handle duplicate transactions
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Warning: Received unknown internode network packet ID {0}", id);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Warning: Error parsing internetwork message: {0}", e.GetType().Name);
            }
        }