ip/session monitoring

This commit is contained in:
Arndt Brenschede 2021-04-18 17:35:50 +02:00
parent 6d68589353
commit 8206a1ae84
2 changed files with 56 additions and 5 deletions

View file

@ -0,0 +1,42 @@
package btools.server;
import java.util.HashMap;
import java.util.Map;
public class IpAccessMonitor
{
private static Object sync = new Object();
private static HashMap<String,Long> ipAccess = new HashMap<String,Long>();
private static long MAX_IDLE = 900000; // 15 minutes
public static boolean touchIpAccess( String ip )
{
long t = System.currentTimeMillis();
synchronized( sync )
{
Long lastTime = ipAccess.get( ip );
if ( lastTime == null || t - lastTime.longValue() > MAX_IDLE )
{
ipAccess.put( ip, Long.valueOf( t ) );
cleanup(t);
return true; // new session detected
}
ipAccess.put( ip, Long.valueOf( t ) ); // touch existing session
return false;
}
}
private static void cleanup( long t )
{
HashMap<String,Long> newMap = new HashMap<String,Long>(ipAccess.size());
for( Map.Entry<String,Long> e : ipAccess.entrySet() )
{
if ( t - e.getValue().longValue() <= MAX_IDLE )
{
newMap.put( e.getKey(), e.getValue() );
}
}
ipAccess = newMap;
}
}

View file

@ -82,6 +82,7 @@ public class RouteServer extends Thread implements Comparable<RouteServer>
String getline = null;
String agent = null;
String encodings = null;
String xff = null; // X-Forwarded-For
// more headers until first empty line
for(;;)
@ -102,13 +103,18 @@ public class RouteServer extends Thread implements Comparable<RouteServer>
{
getline = line;
}
if ( line.startsWith( "User-Agent: " ) )
line = line.toLowerCase();
if ( line.startsWith( "user-agent: " ) )
{
agent = line.substring( "User-Agent: ".length() );
agent = line.substring( "user-agent: ".length() );
}
if ( line.startsWith( "Accept-Encoding: " ) )
if ( line.startsWith( "accept-encoding: " ) )
{
encodings = line.substring( "Accept-Encoding: ".length() );
encodings = line.substring( "accept-encoding: ".length() );
}
if ( line.startsWith( "x-forwarded-for: " ) )
{
xff = line.substring( "x-forwarded-for: ".length() );
}
}
@ -143,8 +149,11 @@ public class RouteServer extends Thread implements Comparable<RouteServer>
return;
}
InetAddress ip = clientSocket.getInetAddress();
System.out.println( formattedTimestamp() + " ip=" + (ip==null ? "null" : ip.toString() ) + " -> " + getline );
String sIp = xff == null ? (ip==null ? "null" : ip.toString() ) : xff;
String sessionMode = IpAccessMonitor.touchIpAccess( sIp ) ? " new " : " ";
System.out.println( formattedTimestamp() + sessionMode + " ip=" + sIp + " -> " + getline );
String url = getline.split(" ")[1];
HashMap<String,String> params = getUrlParams(url);