Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #region Includes
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Linq;
- using ExtensionMethods;
- #endregion
- #region RemoveAll for Dictionary
- namespace ExtensionMethods
- {
- public static class Extensions
- {
- public static void RemoveAll<TKey, TValue>(this Dictionary<TKey, TValue> dict,
- Func<KeyValuePair<TKey, TValue>, bool> condition)
- {
- foreach (var cur in dict.Where(condition).ToList())
- dict.Remove(cur.Key);
- }
- }
- }
- #endregion
- namespace PTEmu.Network
- {
- public class FloodProtector
- {
- /// <summary>a list containing the ips connected and the respective interval</summary>
- private static SortedList<string, FloodCounter> floods = new SortedList<string, FloodCounter>();
- /// <summary>the wait interval(ms) to accept new connections from the same IP.</summary>
- private readonly int wait = 500;
- private readonly int packet_wait = 10;
- public bool HandlePacket(string id)
- {
- var p = floods[id];
- if (p.PacketWatch.ElapsedMilliseconds < packet_wait) // too much packets
- {
- p.PacketWatch.Reset();
- p.PacketWatch.Start();
- return false;
- }
- else
- {
- p.PacketWatch.Reset();
- p.PacketWatch.Start();
- return true;
- }
- }
- /// <summary>Handle continuous connect request</summary>
- /// <param name="id">IP</param>
- /// <returns>false if denied, true if OK</returns>
- public bool HandleConnect(string id)
- {
- System.Threading.Thread.Sleep(100);
- // he never connected to server. create a new key for him.
- if (!floods.ContainsKey(id))
- {
- var counter = new FloodCounter();
- counter.StopWatch = new Stopwatch();
- counter.PacketWatch = new Stopwatch();
- counter.StopWatch.Start(); // starts his counter
- counter.PacketWatch.Start();
- counter.Packet = 0;
- floods.Add(id, counter);
- return true; // return true, after all he never connected here.
- }
- else
- {
- var p = floods[id];
- var tick = p.StopWatch.ElapsedMilliseconds;
- // the interval wasnt satisfied and yet he's trying to connect again
- // so, we found this as an attack. return false and reset the counter.
- if (tick < wait)
- {
- p.StopWatch.Reset();
- p.StopWatch.Start();
- Clients.pInfo.RemoveAll<uint, AccountInfo>(n => n.Value.IP == id);
- return false;
- }
- else // he's not attacking, return true and reset the counter.
- {
- p.StopWatch.Reset();
- p.StopWatch.Start();
- return true;
- }
- }
- }
- #region struct
- private struct FloodCounter
- {
- private int packet_count;
- private Stopwatch k__BackingField;
- private Stopwatch pack;
- public Stopwatch PacketWatch
- {
- get { return pack; }
- set { pack = value; }
- }
- public int Packet
- {
- get { return packet_count; }
- set { packet_count = value; }
- }
- public Stopwatch StopWatch
- {
- get { return this.k__BackingField; }
- set { this.k__BackingField = value; }
- }
- }
- #endregion
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement