Throttle IP connections. Fixes #4
This commit is contained in:
parent
016ed9488d
commit
9451b1c123
|
@ -1,22 +1,31 @@
|
|||
package me.StevenLawson.BukkitTelnet;
|
||||
|
||||
import me.StevenLawson.BukkitTelnet.session.ClientSession;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.net.InetAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import me.StevenLawson.BukkitTelnet.session.ClientSession;
|
||||
|
||||
public class SocketListener extends Thread
|
||||
{
|
||||
public static long LISTEN_THRESHOLD_MILLIS = 10000;
|
||||
private final ServerSocket serverSocket;
|
||||
private final List<ClientSession> clientSessions;
|
||||
private final Map<InetAddress, Long> recentIPs;
|
||||
|
||||
public SocketListener(ServerSocket serverSocket)
|
||||
{
|
||||
this.serverSocket = serverSocket;
|
||||
this.clientSessions = new ArrayList<ClientSession>();
|
||||
this.recentIPs = new HashMap<InetAddress, Long>();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -35,6 +44,51 @@ public class SocketListener extends Thread
|
|||
continue;
|
||||
}
|
||||
|
||||
// Remove old entries
|
||||
final Iterator<Entry<InetAddress, Long>> it = recentIPs.entrySet().iterator();
|
||||
Entry<InetAddress, Long> entry;
|
||||
while (it.hasNext())
|
||||
{
|
||||
if (it.next().getValue() + LISTEN_THRESHOLD_MILLIS < System.currentTimeMillis())
|
||||
{
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
|
||||
final InetAddress addr = clientSocket.getInetAddress();
|
||||
if (addr == null)
|
||||
{
|
||||
return; // Socket is not connected
|
||||
}
|
||||
|
||||
// Connect Threshold
|
||||
if (recentIPs.containsKey(addr))
|
||||
{
|
||||
recentIPs.put(addr, System.currentTimeMillis());
|
||||
|
||||
try
|
||||
{
|
||||
final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
|
||||
writer.write("Connection throttled. Please wait a minute and try again.\r\n");
|
||||
writer.flush();
|
||||
}
|
||||
catch (IOException ignored)
|
||||
{
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
clientSocket.close();
|
||||
}
|
||||
catch (IOException ignored)
|
||||
{
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
recentIPs.put(addr, System.currentTimeMillis());
|
||||
|
||||
final ClientSession clientSession = new ClientSession(clientSocket);
|
||||
clientSessions.add(clientSession);
|
||||
clientSession.start();
|
||||
|
|
Loading…
Reference in New Issue