package de.tudarmstadt.informatik.hostage;

import android.util.Log;

/**
 * Class used to detect port scans. 
 * We assume a port scan if at least 2 different ports get a connection in a small amount of time.
 *
 */
public class ConnectionGuard {

	private final static ConnectionGuard INSTANCE = new ConnectionGuard();

	private ConnectionGuard() {
	}

	/**
	 * Intervall between 2 connection in wich we assume a port scan
	 */
	public final static long ONE_SECOND_IN_NANOSECONDS = 1000000000;

	private static long lastTimestamp = 0;
	private static String lastIP = "";
	private static int lastPort = 0;

	/**
	 * Register a connection for port scan detection. Stores information about the last connection.
	 * @param port The local port used for communication.
	 * @param ip The IP address of the remote device.
	 * @return True if a port scan has been detected.
	 */
	public synchronized static boolean registerConnection(int port, String ip) {
		long timestamp = System.nanoTime();		
		boolean result = detectedPortscan(port, ip, timestamp);
		
		lastTimestamp = timestamp;
		lastIP = ip;
		lastPort = port;
		return result;
	}
	
	/**
	 * Check if the new connection is part of a port scan attack.
	 * @param port The local port used for communication.
	 * @param ip The IP address of the remote device.
	 * @return True if a port scan has been detected.
	 */
	public synchronized static boolean detectedPortscan(int port, String ip){
		return detectedPortscan(port, ip, System.nanoTime());
	}
	
	/**
	 * Check if the new connection is part of a port scan attack.
	 * @param port The local port used for communication.
	 * @param ip The IP address of the remote device.
	 * @param timestamp Time stamp of connection
	 * @return True if a port scan has been detected.
	 */
	private synchronized static boolean detectedPortscan(int port, String ip, long timestamp) {
		Log.i("Alte Werte:", "LastTime: " + lastTimestamp + " ,LastIP: " + lastIP + ", lastPort:" + port);
		Log.i("Alte Werte:", "Time: " + timestamp + " ,IP: " + ip + ", Port:" + port);
		boolean result = false;
		boolean firstConnection = (lastTimestamp == 0);
		boolean belowThreshold = ((timestamp - lastTimestamp) < ONE_SECOND_IN_NANOSECONDS);
		boolean sameIP = (lastIP.equals(ip));
		boolean samePort = (lastPort == port);
		if (!firstConnection && sameIP && belowThreshold && !samePort) {
			result = true;
		}
		
		return result;
	}
}
