Ejemplo n.º 1
0
 public void RegisterPacketHandler(IPacketHandler handler)
 {
     if (PacketHandlers.All(p => p.GetType() != handler.GetType()))
     {
         _packetHandlers.Add(handler);
     }
 }
Ejemplo n.º 2
0
        internal void OnNetworkStream(Network.ByteInStream stream)
        {
#if !DEBUG
            try
            {
#endif
            while (stream.Stream.CanRead)
            {
                byte           handlerId = stream.ReadByte();
                IPacketHandler handler   = packetHandlers[handlerId];

                if (handler == null)
                {
                    log.Error("No packet handler for id #{0} found, can't process byte stream", handlerId);
                    return;
                }

                if (!handler.OnPacket(handlerId, this, stream))
                {
                    log.Error("Handler '{0}' failed processing byte stream", handler.GetType().GetPrettyName());
                    return;
                }
            }
#if !DEBUG
        }

        catch (Exception exn)
        {
            log.Error(exn);
        }
#endif
        }
Ejemplo n.º 3
0
		public void HandlePacketTimeout(object sender, ElapsedEventArgs e)
		{
			string source = ((m_client.Account != null) ? m_client.Account.Name : m_client.TcpEndpoint);
			if (log.IsErrorEnabled)
				log.Error("Thread " + m_handlerThreadID + " - Handler " + m_activePacketHandler.GetType() +
				          " takes too much time (>10000ms) <" + source + "> " + "!");
		}
Ejemplo n.º 4
0
        public void HandlePacketTimeout(object sender, ElapsedEventArgs e)
        {
            string source = (_client.Account != null) ? _client.Account.Name : _client.TcpEndpoint;

            if (Log.IsErrorEnabled)
            {
                Log.Error($"Thread {_handlerThreadId} - Handler {_activePacketHandler.GetType()} takes too much time (>10000ms) <{source}> !");
            }
        }
Ejemplo n.º 5
0
        public void HandlePacket(GSPacketIn packet)
        {
            int code = packet.Code;

            Statistics.BytesIn += packet.Length;
            Statistics.PacketsIn++;

            IPacketHandler packetHandler = null;

            if (code < m_packetHandlers.Length)
            {
                packetHandler = m_packetHandlers[code];
            }
            else if (log.IsErrorEnabled)
            {
                log.ErrorFormat("Received packet code is outside of m_packetHandlers array bounds! " + m_client.ToString());
                log.Error(Marshal.ToHexDump(
                              String.Format("===> <{2}> Packet 0x{0:X2} (0x{1:X2}) length: {3} (ThreadId={4})", code, code ^ 168, m_client.TcpEndpoint, packet.Length, Thread.CurrentThread.ManagedThreadId),
                              packet.Buffer));
            }

            if (packetHandler != null)
            {
                long start = Environment.TickCount;
                try
                {
                    packetHandler.HandlePacket(m_client, packet);
                }
                catch (Exception e)
                {
                    if (log.IsErrorEnabled)
                    {
                        string client = m_client.TcpEndpoint;
                        log.Error("Error while processing packet (handler=" + packetHandler.GetType().FullName + "  client: " + client + ")", e);
                        log.Error(Marshal.ToHexDump("Package Buffer:", packet.Buffer, 0, packet.Length));
                    }
                }

                long timeUsed = Environment.TickCount - start;

                m_activePacketHandler = null;
                if (log.IsDebugEnabled)
                {
                    log.Debug("Package process Time:" + timeUsed + "ms!");
                }
                if (timeUsed > 1000)
                {
                    string source = m_client.TcpEndpoint;
                    if (log.IsWarnEnabled)
                    {
                        log.Warn("(" + source + ") Handle packet Thread " + Thread.CurrentThread.ManagedThreadId + " " + packetHandler + " took " + timeUsed + "ms!");
                    }
                }
            }
        }
Ejemplo n.º 6
0
        public virtual void HandlePacket(int code, GamePacket packet)
        {
            if (packet == null)
            {
                log.Error("Packet is null!");
                return;
            }

            IPacketHandler handler = null;

            if (m_packagesHandlers.ContainsKey(code))
            {
                handler = m_packagesHandlers[code];
            }
            else
            {
                log.ErrorFormat("Receive package's code is not exists! Code: {0}", code);
                log.Error(Marshal.ToHexDump(string.Format("Code: {0}", code), packet.Buffer, 0, packet.Length));
                return;
            }

            long timeUsed = Environment.TickCount;

            try
            {
                handler.HandlePacket(m_client, packet);
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Error while processing package (handler={0})", handler.GetType().FullName);
                log.Error("Handle package error!", ex);
            }

            timeUsed = Environment.TickCount - timeUsed;

            log.InfoFormat("Package process time: {0}ms", timeUsed);

            if (timeUsed > 1000)
            {
                log.WarnFormat("Handle package thread {0} {1} took {2}ms!", System.Threading.Thread.CurrentThread.ManagedThreadId, handler, timeUsed);
            }
        }
Ejemplo n.º 7
0
		/// <summary>
		/// Registers a packet handler
		/// </summary>
		/// <param name="handler">The packet handler to register</param>
		/// <param name="packetCode">The packet ID to register it with</param>
		public void RegisterPacketHandler(int packetCode, IPacketHandler handler, IPacketHandler[] packetHandlers)
		{
			if (packetHandlers[packetCode] != null)
			{
				log.InfoFormat("Overwriting Client Packet Code {0}, with handler {1} in PacketProcessor", packetCode, handler.GetType().FullName);
			}

            packetHandlers[packetCode] = handler;
		}
 public void AddPacketHandler(IPAddress remoteAddress, String sharedSecret, IPacketHandler packetHandler)
 {
     _log.Info($"Adding packet handler of type {packetHandler.GetType()} for remote IP {remoteAddress} to {_serverType}Server");
     _packetHandlerRepository.AddPacketHandler(remoteAddress, packetHandler, sharedSecret);
 }
        /// <summary>
        /// Parses a packet and gets a response packet from the handler
        /// </summary>
        /// <param name="packetHandler"></param>
        /// <param name="sharedSecret"></param>
        /// <param name="packetBytes"></param>
        /// <param name="remoteEndpoint"></param>
        /// <returns></returns>
        internal IRadiusPacket GetResponsePacket(IPacketHandler packetHandler, String sharedSecret, Byte[] packetBytes, IPEndPoint remoteEndpoint)
        {
            var requestPacket = RadiusPacket.Parse(packetBytes, _dictionary, Encoding.UTF8.GetBytes(sharedSecret));

            _log.Info($"Received {requestPacket.Code} from {remoteEndpoint} Id={requestPacket.Identifier}");

            if (_log.IsDebugEnabled)
            {
                DumpPacket(requestPacket);
            }
            _log.Debug(packetBytes.ToHexString());

            // Handle status server requests in server outside packet handler
            if (requestPacket.Code == PacketCode.StatusServer)
            {
                var responseCode = _serverType == RadiusServerType.Authentication ? PacketCode.AccessAccept : PacketCode.AccountingResponse;
                _log.Debug($"Sending {responseCode} for StatusServer request from {remoteEndpoint}");
                return(requestPacket.CreateResponsePacket(responseCode));
            }

            _log.Debug($"Handling packet for remote ip {remoteEndpoint.Address} with {packetHandler.GetType()}");

            var sw             = Stopwatch.StartNew();
            var responsePacket = packetHandler.HandlePacket(requestPacket);

            sw.Stop();
            _log.Debug($"{remoteEndpoint} Id={responsePacket.Identifier}, Received {responsePacket.Code} from handler in {sw.ElapsedMilliseconds}ms");
            if (sw.ElapsedMilliseconds >= 5000)
            {
                _log.Warn($"Slow response for Id {responsePacket.Identifier}, check logs");
            }

            if (requestPacket.Attributes.ContainsKey("Proxy-State"))
            {
                responsePacket.Attributes.Add("Proxy-State", requestPacket.Attributes.SingleOrDefault(o => o.Key == "Proxy-State").Value);
            }

            return(responsePacket);
        }
Ejemplo n.º 10
0
		public void HandlePacket(GSPacketIn packet)
		{
			if (packet == null || m_client == null)
				return;

			int code = packet.ID;

			Statistics.BytesIn += packet.PacketSize;
			Statistics.PacketsIn++;

			SavePacket(packet);

			IPacketHandler packetHandler = null;
			if (code < m_packetHandlers.Length)
			{
				packetHandler = m_packetHandlers[code];
			}

			else if (log.IsErrorEnabled)
			{
				log.ErrorFormat("Received packet code is outside of m_packetHandlers array bounds! " + m_client);
				log.Error(Marshal.ToHexDump(
				          	String.Format("===> <{2}> Packet 0x{0:X2} (0x{1:X2}) length: {3} (ThreadId={4})", code, code ^ 168,
				          	              (m_client.Account != null) ? m_client.Account.Name : m_client.TcpEndpoint,
				          	              packet.PacketSize, Thread.CurrentThread.ManagedThreadId),
				          	packet.ToArray()));
			}

			// make sure we can handle this packet at this stage
			var preprocess = m_packetPreprocessor.CanProcessPacket(m_client, packet);
			if(!preprocess)
			{
                // this packet can't be processed by this client right now, for whatever reason
                log.Info("PacketPreprocessor: Preprocessor prevents handling of a packet with packet.ID=" + packet.ID);
				return;
			}

			if (packetHandler != null)
			{
				Timer monitorTimer = null;
				if (log.IsDebugEnabled)
				{
					try
					{
						monitorTimer = new Timer(10000);
						m_activePacketHandler = packetHandler;
						m_handlerThreadID = Thread.CurrentThread.ManagedThreadId;
						monitorTimer.Elapsed += HandlePacketTimeout;
						monitorTimer.Start();
					}
					catch (Exception e)
					{
						if (log.IsErrorEnabled)
							log.Error("Starting packet monitor timer", e);

						if (monitorTimer != null)
						{
							monitorTimer.Stop();
							monitorTimer.Close();
							monitorTimer = null;
						}
					}
				}

#if LOGACTIVESTACKS
				//Put the current thread into the active thread list!
				//No need to lock the hashtable since we created it
				//synchronized! One reader, multiple writers supported!
				m_activePacketThreads.Add(Thread.CurrentThread, m_client);
#endif
				long start = Environment.TickCount;
				try
				{
					packetHandler.HandlePacket(m_client, packet);
				}
				catch (Exception e)
				{
					if (log.IsErrorEnabled)
					{
						string client = (m_client == null ? "null" : m_client.ToString());
						log.Error(
							"Error while processing packet (handler=" + packetHandler.GetType().FullName + "  client: " + client + ")", e);
					}
				}
#if LOGACTIVESTACKS
				finally
				{
					//Remove the thread from the active list after execution
					//No need to lock the hashtable since we created it
					//synchronized! One reader, multiple writers supported!
					m_activePacketThreads.Remove(Thread.CurrentThread);
				}
#endif
				long timeUsed = Environment.TickCount - start;
				if (monitorTimer != null)
				{
					monitorTimer.Stop();
					monitorTimer.Close();
				}
				m_activePacketHandler = null;
				if (timeUsed > 1000)
				{
					string source = ((m_client.Account != null) ? m_client.Account.Name : m_client.TcpEndpoint);
					if (log.IsWarnEnabled)
						log.Warn("(" + source + ") Handle packet Thread " + Thread.CurrentThread.ManagedThreadId + " " + packetHandler +
						         " took " + timeUsed + "ms!");
				}
			}
		}
Ejemplo n.º 11
0
		/// <summary>
		/// Registers a packet handler
		/// </summary>
		/// <param name="handler">The packet handler to register</param>
		/// <param name="packetCode">The packet ID to register it with</param>
		public void RegisterPacketHandler(int packetCode, IPacketHandler handler, IPacketHandler[] packetHandlers)
		{
			if (packetHandlers[packetCode] != null)
			{
				log.InfoFormat("Overwriting Client Packet Code {0}, with handler {1} in PacketProcessor", packetCode, handler.GetType().FullName);
			}

            packetHandlers[packetCode] = handler;
		}
Ejemplo n.º 12
0
        public static void SpamTrash(this IPacketHandler h, IEntity ent)
        {
            const int defaultShortSize = 1024; // size used for short size opcodes

            var s = Server();
            var p = Player(s);

            void Spam(int size, bool randomSize, int op)
            {
                var iterations = (int)Math.Pow(2, 13);

                for (var i = 0; i < iterations; i++)
                {
                    Blob b = randomSize
                        ? RandomData(Rng.Next(0, size + 1))
                        : RandomData(size);

                    h.Handle(ent, PacketMessage.Success((byte)op, b));
                }
            }

            if (PacketDb == null)
            {
                var dirBuild = Path.GetDirectoryName(typeof(MockServer).GetTypeInfo().Assembly.Location);
                PacketDb = new JsonPacketDatabase(Path.Combine(dirBuild, "packet-lengths.json"));
            }

            foreach (var op in h.Handles)
            {
                // chose size    
                var size = PacketDb.GetIncoming(op);
                switch (size)
                {
                    case PacketLength.NextByte:
                        Spam(byte.MaxValue, true, op);
                        break;
                    case PacketLength.NextShort:
                        Spam(defaultShortSize, true, op);
                        break;
                    case PacketLength.Undefined: throw new NotSupportedException($"Undefined packet in {h.GetType().Name}");
                    default:
                        var finalSize = (int) size;
                        if (finalSize == 0)
                            return;

                        Spam(finalSize, false, op);
                        break;
                }
            }
        }
Ejemplo n.º 13
0
        public void HandlePacket(GSPacketIn packet)
        {
            int code = (int)packet.Code;

            Statistics.BytesIn   += (long)packet.Length;
            Statistics.PacketsIn += 1L;
            IPacketHandler packetHandler = null;

            if (code < PacketProcessor.m_packetHandlers.Length)
            {
                packetHandler = PacketProcessor.m_packetHandlers[code];
                Console.WriteLine(string.Concat(new object[]
                {
                    "ClientID: " + packet.ClientID,
                    " received code: ",
                    code,
                    " <",
                    string.Format("0x{0:x}", code),
                    ">"
                }));
                Console.WriteLine(" ==>" + packetHandler.ToString());
            }

            if (code < PacketProcessor.m_packetHandlers.Length)
            {
                packetHandler = PacketProcessor.m_packetHandlers[code];
                try
                {
                    packetHandler.ToString();
                    goto IL_157;
                }
                catch
                {
                    Console.WriteLine("______________ERROR______________");
                    Console.WriteLine(string.Concat(new object[]
                    {
                        "___ Received code: ",
                        code,
                        " <",
                        string.Format("0x{0:x}", code),
                        "> ____"
                    }));
                    Console.WriteLine("_________________________________");
                    goto IL_157;
                }
            }
            if (PacketProcessor.log.IsErrorEnabled)
            {
                PacketProcessor.log.ErrorFormat("Received packet code is outside of m_packetHandlers array bounds! " + this.m_client.ToString(), new object[0]);
                PacketProcessor.log.Error(Marshal.ToHexDump(string.Format("===> <{2}> Packet 0x{0:X2} (0x{1:X2}) length: {3} (ThreadId={4})", new object[]
                {
                    code,
                    code ^ 168,
                    this.m_client.TcpEndpoint,
                    packet.Length,
                    Thread.CurrentThread.ManagedThreadId
                }), packet.Buffer));
            }
IL_157:
            if (packetHandler != null)
            {
                long num = (long)Environment.TickCount;
                try
                {
                    if (this.m_client != null && packet != null && this.m_client.TcpEndpoint != "not connected")
                    {
                        packetHandler.HandlePacket(this.m_client, packet);
                    }
                }
                catch (Exception exception)
                {
                    if (PacketProcessor.log.IsErrorEnabled)
                    {
                        string tcpEndpoint = this.m_client.TcpEndpoint;
                        PacketProcessor.log.Error(string.Concat(new string[]
                        {
                            "Error while processing packet (handler=",
                            packetHandler.GetType().FullName,
                            "  client: ",
                            tcpEndpoint,
                            ")"
                        }), exception);
                        PacketProcessor.log.Error(Marshal.ToHexDump("Package Buffer:", packet.Buffer, 0, packet.Length));
                    }
                }
                long num2 = (long)Environment.TickCount - num;
                this.m_activePacketHandler = null;
                if (PacketProcessor.log.IsDebugEnabled)
                {
                    PacketProcessor.log.Debug("Package process Time:" + num2 + "ms!");
                }
                if (num2 > 1000L)
                {
                    string tcpEndpoint2 = this.m_client.TcpEndpoint;
                    if (PacketProcessor.log.IsWarnEnabled)
                    {
                        PacketProcessor.log.Warn(string.Concat(new object[]
                        {
                            "(",
                            tcpEndpoint2,
                            ") Handle packet Thread ",
                            Thread.CurrentThread.ManagedThreadId,
                            " ",
                            packetHandler,
                            " took ",
                            num2,
                            "ms!"
                        }));
                    }
                }
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Registers a packet handler
        /// </summary>
        /// <param name="handler">The packet handler to register</param>
        /// <param name="packetCode">The packet ID to register it with</param>
        public static void RegisterPacketHandler(int packetCode, IPacketHandler handler)
        {
            if (m_packetHandlers[packetCode] != null)
            {
                log.InfoFormat("Overwriting Client Packet Code {0}, with handler {1}", packetCode, handler.GetType().FullName);
            }

            m_packetHandlers[packetCode] = handler;
        }
Ejemplo n.º 15
0
		/// <summary>
		/// Registers a packet handler
		/// </summary>
		/// <param name="handler">The packet handler to register</param>
		/// <param name="packetCode">The packet ID to register it with</param>
		public static void RegisterPacketHandler(int packetCode, IPacketHandler handler)
		{
			if (m_packetHandlers[packetCode] != null)
			{
				log.InfoFormat("Overwriting Client Packet Code {0}, with handler {1}", packetCode, handler.GetType().FullName);
			}
			
			m_packetHandlers[packetCode] = handler;
		}
Ejemplo n.º 16
0
        public void HandlePacket(GSPacketIn packet)
        {
            if (packet == null || _client == null)
            {
                return;
            }

            int code = packet.ID;

            Statistics.BytesIn += packet.PacketSize;
            Statistics.PacketsIn++;

            SavePacket(packet);

            IPacketHandler packetHandler = null;

            if (code < _packetHandlers.Length)
            {
                packetHandler = _packetHandlers[code];
            }

            else if (Log.IsErrorEnabled)
            {
                Log.Error($"Received packet code is outside of m_packetHandlers array bounds! {_client}");
                Log.Error(Marshal.ToHexDump($"===> <{(_client.Account != null ? _client.Account.Name : _client.TcpEndpoint)}> Packet 0x{code:X2} (0x{code ^ 168:X2}) length: {packet.PacketSize} (ThreadId={Thread.CurrentThread.ManagedThreadId})", packet.ToArray()));
            }

            // make sure we can handle this packet at this stage
            var preprocess = _packetPreprocessor.CanProcessPacket(_client, packet);

            if (!preprocess)
            {
                // this packet can't be processed by this client right now, for whatever reason
                Log.Info($"PacketPreprocessor: Preprocessor prevents handling of a packet with packet.ID={packet.ID}");
                return;
            }

            if (packetHandler != null)
            {
                Timer monitorTimer = null;
                if (Log.IsDebugEnabled)
                {
                    try
                    {
                        monitorTimer          = new Timer(10000);
                        _activePacketHandler  = packetHandler;
                        _handlerThreadId      = Thread.CurrentThread.ManagedThreadId;
                        monitorTimer.Elapsed += HandlePacketTimeout;
                        monitorTimer.Start();
                    }
                    catch (Exception e)
                    {
                        if (Log.IsErrorEnabled)
                        {
                            Log.Error("Starting packet monitor timer", e);
                        }

                        if (monitorTimer != null)
                        {
                            monitorTimer.Stop();
                            monitorTimer.Close();
                            monitorTimer = null;
                        }
                    }
                }

#if LOGACTIVESTACKS
                // Put the current thread into the active thread list!
                // No need to lock the hashtable since we created it
                // synchronized! One reader, multiple writers supported!
                ActivePacketThreads.Add(Thread.CurrentThread, _client);
#endif
                long start = Environment.TickCount;
                try
                {
                    packetHandler.HandlePacket(_client, packet);
                }
                catch (Exception e)
                {
                    if (Log.IsErrorEnabled)
                    {
                        string client = _client?.ToString() ?? "null";
                        Log.Error($"Error while processing packet (handler={packetHandler.GetType().FullName}  client: {client})", e);
                    }
                }
#if LOGACTIVESTACKS
                finally
                {
                    // Remove the thread from the active list after execution
                    // No need to lock the hashtable since we created it
                    // synchronized! One reader, multiple writers supported!
                    ActivePacketThreads.Remove(Thread.CurrentThread);
                }
#endif
                long timeUsed = Environment.TickCount - start;
                if (monitorTimer != null)
                {
                    monitorTimer.Stop();
                    monitorTimer.Close();
                }

                _activePacketHandler = null;
                if (timeUsed > 1000)
                {
                    string source = _client.Account != null ? _client.Account.Name : _client.TcpEndpoint;
                    if (Log.IsWarnEnabled)
                    {
                        Log.Warn($"({source}) Handle packet Thread {Thread.CurrentThread.ManagedThreadId} {packetHandler} took {timeUsed}ms!");
                    }
                }
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Registers a packet handler
        /// </summary>
        /// <param name="handler">The packet handler to register</param>
        /// <param name="packetCode">The packet ID to register it with</param>
        public void RegisterPacketHandler(int packetCode, IPacketHandler handler, IPacketHandler[] packetHandlers)
        {
            if (packetHandlers[packetCode] != null)
            {
                Log.Info($"Overwriting Client Packet Code {packetCode}, with handler {handler.GetType().FullName} in PacketProcessor");
            }

            packetHandlers[packetCode] = handler;
        }
Ejemplo n.º 18
0
        public void HandlePacket(GSPacketIn packet)
        {
            int code = (int)packet.Code;

            Statistics.BytesIn   += (long)packet.Length;
            Statistics.PacketsIn += 1L;
            IPacketHandler packetHandler = null;

            if (code < PacketProcessor.m_packetHandlers.Length)
            {
                packetHandler = PacketProcessor.m_packetHandlers[code];
            }
            else
            {
                {
                    PacketProcessor.log.ErrorFormat("Received packet code is outside of m_packetHandlers array bounds! " + this.m_client.ToString(), new object[0]);
                    PacketProcessor.log.Error(Marshal.ToHexDump(string.Format("===> <{2}> Packet 0x{0:X2} (0x{1:X2}) length: {3} (ThreadId={4})", new object[]
                    {
                        code,
                        code ^ 168,
                        this.m_client.TcpEndpoint,
                        packet.Length,
                        Thread.CurrentThread.ManagedThreadId
                    }), packet.Buffer));
                }
            }

            if (packetHandler != null)
            {
                long start = (long)Environment.TickCount;
                try
                {
                    packetHandler.HandlePacket(this.m_client, packet);
                }
                catch (Exception e)
                {
                    {
                        string client = this.m_client.TcpEndpoint;
                        PacketProcessor.log.Error(string.Concat(new string[]
                        {
                            "Error while processing packet (handler=",
                            packetHandler.GetType().FullName,
                            "  client: ",
                            client,
                            ")"
                        }), e);
                        PacketProcessor.log.Error(Marshal.ToHexDump("Package Buffer:", packet.Buffer, 0, packet.Length));
                    }
                }
                long timeUsed = (long)Environment.TickCount - start;
                this.m_activePacketHandler = null;
                if (timeUsed > 1000L)
                {
                    string source = this.m_client.TcpEndpoint;

                    PacketProcessor.log.Warn(string.Concat(new object[]
                    {
                        "(",
                        source,
                        ") Handle packet Thread ",
                        Thread.CurrentThread.ManagedThreadId,
                        " ",
                        packetHandler,
                        " took ",
                        timeUsed,
                        "ms!"
                    }));
                }
            }
        }