Browse Source

Logging-System überarbeitet und als IntentService implementiert.
Performance deutlich gesteigert. Aufgabentrennung im Code viel
deutlicher. Record ist Parcelable statt Serializable (über 10x höhere
Performance auf Android). Formatter für logging überarbeitet, Singleton,
ressourcenschonend implementiert.
TODO: ViewLog und ViewLogTable kaputt, da Antworten vom IntentService
noch nicht richtig empfangen werden.

MiP 10 years ago
parent
commit
8b36e01daa
30 changed files with 2668 additions and 1972 deletions
  1. 26 21
      AndroidManifest.xml
  2. 4 0
      lint.xml
  3. 82 48
      src/de/tudarmstadt/informatik/hostage/HoneyHandler.java
  4. 161 126
      src/de/tudarmstadt/informatik/hostage/HoneyService.java
  5. 111 66
      src/de/tudarmstadt/informatik/hostage/commons/HelperUtils.java
  6. 0 14
      src/de/tudarmstadt/informatik/hostage/format/DefaultFormatter.java
  7. 0 46
      src/de/tudarmstadt/informatik/hostage/format/LogViewFormatter.java
  8. 0 64
      src/de/tudarmstadt/informatik/hostage/format/MySQLFormatter.java
  9. 0 17
      src/de/tudarmstadt/informatik/hostage/format/ProtocolFormatter.java
  10. 0 135
      src/de/tudarmstadt/informatik/hostage/format/SMBFormatter.java
  11. 0 99
      src/de/tudarmstadt/informatik/hostage/format/TELNETFormatter.java
  12. 0 597
      src/de/tudarmstadt/informatik/hostage/logging/DatabaseHandler.java
  13. 30 0
      src/de/tudarmstadt/informatik/hostage/logging/LogResultReceiver.java
  14. 311 80
      src/de/tudarmstadt/informatik/hostage/logging/Logger.java
  15. 162 183
      src/de/tudarmstadt/informatik/hostage/logging/Record.java
  16. 0 89
      src/de/tudarmstadt/informatik/hostage/logging/SQLLogger.java
  17. 694 0
      src/de/tudarmstadt/informatik/hostage/logging/UglyDbHelper.java
  18. 28 0
      src/de/tudarmstadt/informatik/hostage/logging/formatter/DefaultFormatter.java
  19. 23 0
      src/de/tudarmstadt/informatik/hostage/logging/formatter/Formatter.java
  20. 25 0
      src/de/tudarmstadt/informatik/hostage/logging/formatter/TraCINgFormatter.java
  21. 103 0
      src/de/tudarmstadt/informatik/hostage/logging/formatter/protocol/MySQL.java
  22. 45 0
      src/de/tudarmstadt/informatik/hostage/logging/formatter/protocol/ProtocolFormatter.java
  23. 225 0
      src/de/tudarmstadt/informatik/hostage/logging/formatter/protocol/SMB.java
  24. 149 0
      src/de/tudarmstadt/informatik/hostage/logging/formatter/protocol/TELNET.java
  25. 2 2
      src/de/tudarmstadt/informatik/hostage/sync/BluetoothSync.java
  26. 3 3
      src/de/tudarmstadt/informatik/hostage/sync/NFCSync.java
  27. 268 212
      src/de/tudarmstadt/informatik/hostage/ui/MainActivity.java
  28. 15 15
      src/de/tudarmstadt/informatik/hostage/ui/PlayGroundActivity.java
  29. 189 145
      src/de/tudarmstadt/informatik/hostage/ui/ViewLog.java
  30. 12 10
      src/de/tudarmstadt/informatik/hostage/ui/ViewLogTable.java

+ 26 - 21
AndroidManifest.xml

@@ -13,13 +13,14 @@
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
-    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
+    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
     <uses-permission android:name="android.permission.BLUETOOTH" />
     <uses-permission android:name="android.permission.BLUETOOTH" />
     <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
     <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
     <uses-permission android:name="android.permission.NFC" />
     <uses-permission android:name="android.permission.NFC" />
-    
+
     <uses-feature
     <uses-feature
-    android:name="android.hardware.nfc" android:required="false" />
+        android:name="android.hardware.nfc"
+        android:required="false" />
 
 
     <application
     <application
         android:allowBackup="true"
         android:allowBackup="true"
@@ -28,49 +29,53 @@
         android:theme="@style/AppTheme" >
         android:theme="@style/AppTheme" >
         <activity
         <activity
             android:name="de.tudarmstadt.informatik.hostage.ui.MainActivity"
             android:name="de.tudarmstadt.informatik.hostage.ui.MainActivity"
-            android:label="@string/app_name" 
-            android:configChanges="keyboardHidden|orientation|screenSize">
+            android:configChanges="keyboardHidden|orientation|screenSize"
+            android:label="@string/app_name" >
             <intent-filter>
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
                 <action android:name="android.intent.action.MAIN" />
+
                 <category android:name="android.intent.category.LAUNCHER" />
                 <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
             </intent-filter>
         </activity>
         </activity>
+        <!--
         <activity
         <activity
             android:name="de.tudarmstadt.informatik.hostage.ui.ViewLog"
             android:name="de.tudarmstadt.informatik.hostage.ui.ViewLog"
             android:label="@string/statistics" >
             android:label="@string/statistics" >
         </activity>
         </activity>
-       	<activity
+        <activity
             android:name="de.tudarmstadt.informatik.hostage.ui.ViewLogTable"
             android:name="de.tudarmstadt.informatik.hostage.ui.ViewLogTable"
             android:label="@string/database" >
             android:label="@string/database" >
         </activity>
         </activity>
-        
-       	<activity
+        -->
+        <activity
             android:name="de.tudarmstadt.informatik.hostage.ui.SettingsActivity"
             android:name="de.tudarmstadt.informatik.hostage.ui.SettingsActivity"
             android:label="@string/settings" >
             android:label="@string/settings" >
         </activity>
         </activity>
-        
-       	<activity
+        <activity
             android:name="de.tudarmstadt.informatik.hostage.ui.AboutActivity"
             android:name="de.tudarmstadt.informatik.hostage.ui.AboutActivity"
             android:label="@string/action_about" >
             android:label="@string/action_about" >
         </activity>
         </activity>
-       
-       	<activity
+        <activity
             android:name="de.tudarmstadt.informatik.hostage.ui.PlayGroundActivity"
             android:name="de.tudarmstadt.informatik.hostage.ui.PlayGroundActivity"
             android:label="@string/playground" >
             android:label="@string/playground" >
         </activity>
         </activity>
-       	
-       <activity
+        <activity
             android:name="de.tudarmstadt.informatik.hostage.sync.NFCSync"
             android:name="de.tudarmstadt.informatik.hostage.sync.NFCSync"
             android:label="@string/playground" >
             android:label="@string/playground" >
             <intent-filter>
             <intent-filter>
-  				<action android:name="android.nfc.action.NDEF_DISCOVERED" />
-  				<category android:name="android.intent.category.DEFAULT" />
-  				<data android:mimeType="application/de.tudarmstadt.informatik.hostage" />
-			</intent-filter>
+                <action android:name="android.nfc.action.NDEF_DISCOVERED" />
+
+                <category android:name="android.intent.category.DEFAULT" />
+
+                <data android:mimeType="application/de.tudarmstadt.informatik.hostage" />
+            </intent-filter>
         </activity>
         </activity>
-       	
-        <service 
-            android:name="de.tudarmstadt.informatik.hostage.HoneyService" >
+
+        <service android:name="de.tudarmstadt.informatik.hostage.HoneyService" >
+        </service>
+        <service
+            android:name="de.tudarmstadt.informatik.hostage.logging.Logger"
+            android:exported="false" >
         </service>
         </service>
     </application>
     </application>
 
 

+ 4 - 0
lint.xml

@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<lint>
+    <issue id="DefaultLocale" severity="ignore" />
+</lint>

+ 82 - 48
src/de/tudarmstadt/informatik/hostage/HoneyHandler.java

@@ -21,16 +21,21 @@ import de.tudarmstadt.informatik.hostage.protocol.Protocol;
 import de.tudarmstadt.informatik.hostage.protocol.Protocol.TALK_FIRST;
 import de.tudarmstadt.informatik.hostage.protocol.Protocol.TALK_FIRST;
 import de.tudarmstadt.informatik.hostage.ui.MainActivity;
 import de.tudarmstadt.informatik.hostage.ui.MainActivity;
 import de.tudarmstadt.informatik.hostage.wrapper.Packet;
 import de.tudarmstadt.informatik.hostage.wrapper.Packet;
+
 /**
 /**
  * Abstract class for a connection handler using a given protocol.
  * Abstract class for a connection handler using a given protocol.
- * @author Mihai Plasoianu 
+ * 
+ * @author Mihai Plasoianu
  * @author Wulf Pfeiffer
  * @author Wulf Pfeiffer
  */
  */
 public class HoneyHandler implements Runnable {
 public class HoneyHandler implements Runnable {
 
 
 	/** Time until the socket throws a time out. The time is in milliseconds. */
 	/** Time until the socket throws a time out. The time is in milliseconds. */
 	private int TIMEOUT;
 	private int TIMEOUT;
-	/** Time that a inputstream waits if no content is available to read again from stream. */
+	/**
+	 * Time that a inputstream waits if no content is available to read again
+	 * from stream.
+	 */
 	private int SLEEPTIME;
 	private int SLEEPTIME;
 
 
 	protected Protocol protocol;
 	protected Protocol protocol;
@@ -44,31 +49,35 @@ public class HoneyHandler implements Runnable {
 	private String SSID;
 	private String SSID;
 
 
 	private HoneyListener listener;
 	private HoneyListener listener;
-	protected Logger log;
-	
+
 	/**
 	/**
-	 * Constructor of the class.
-	 * Initializes class variables for communication and logging.
-	 * Then starts itself in a new Thread.
-	 * @param service The background service.
-	 * @param listener The Listener that called the service.
-	 * @param protocol The protocol on which the handler is running.
-	 * @param client A Socket for the communication with a remote client.
+	 * Constructor of the class. Initializes class variables for communication
+	 * and logging. Then starts itself in a new Thread.
+	 * 
+	 * @param service
+	 *            The background service.
+	 * @param listener
+	 *            The Listener that called the service.
+	 * @param protocol
+	 *            The protocol on which the handler is running.
+	 * @param client
+	 *            A Socket for the communication with a remote client.
 	 */
 	 */
 	public HoneyHandler(HoneyService service, HoneyListener listener,
 	public HoneyHandler(HoneyService service, HoneyListener listener,
 			Protocol protocol, Socket client) {
 			Protocol protocol, Socket client) {
 		this.listener = listener;
 		this.listener = listener;
-		this.log = service.getLog();
 		this.protocol = protocol;
 		this.protocol = protocol;
 		this.client = client;
 		this.client = client;
 		this.thread = new Thread(this);
 		this.thread = new Thread(this);
-		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(service);
+		SharedPreferences pref = PreferenceManager
+				.getDefaultSharedPreferences(service);
 		SLEEPTIME = pref.getInt("sleeptime", 500);
 		SLEEPTIME = pref.getInt("sleeptime", 500);
 		TIMEOUT = pref.getInt("timeout", 30) * 1000;
 		TIMEOUT = pref.getInt("timeout", 30) * 1000;
-		//TODO ThreadSicher?
+		// TODO ThreadSicher?
 		attack_id = getAndIncrementAttackID(pref);
 		attack_id = getAndIncrementAttackID(pref);
 		message_id = 0;
 		message_id = 0;
-		SharedPreferences sessionPref = service.getSharedPreferences(MainActivity.SESSION_DATA, Context.MODE_PRIVATE);
+		SharedPreferences sessionPref = service.getSharedPreferences(
+				MainActivity.SESSION_DATA, Context.MODE_PRIVATE);
 		BSSID = sessionPref.getString(MainActivity.BSSID, null);
 		BSSID = sessionPref.getString(MainActivity.BSSID, null);
 		SSID = sessionPref.getString(MainActivity.SSID, null);
 		SSID = sessionPref.getString(MainActivity.SSID, null);
 		externalIP = sessionPref.getString(MainActivity.EXTERNAL_IP, null);
 		externalIP = sessionPref.getString(MainActivity.EXTERNAL_IP, null);
@@ -78,7 +87,9 @@ public class HoneyHandler implements Runnable {
 
 
 	/**
 	/**
 	 * Set the timeout of the socket to the hard coded time out variable.
 	 * Set the timeout of the socket to the hard coded time out variable.
-	 * @param client The socket
+	 * 
+	 * @param client
+	 *            The socket
 	 * @see #TIMEOUT
 	 * @see #TIMEOUT
 	 */
 	 */
 	private void setSoTimeout(Socket client) {
 	private void setSoTimeout(Socket client) {
@@ -90,9 +101,9 @@ public class HoneyHandler implements Runnable {
 	}
 	}
 
 
 	/**
 	/**
-	 * Creates InputStream and OutputStream for the socket.
-	 * Starts communication with client.
-	 * When the client closes the connection or a time out occurs the handler is finished.
+	 * Creates InputStream and OutputStream for the socket. Starts communication
+	 * with client. When the client closes the connection or a time out occurs
+	 * the handler is finished.
 	 */
 	 */
 	@Override
 	@Override
 	public void run() {
 	public void run() {
@@ -123,6 +134,7 @@ public class HoneyHandler implements Runnable {
 
 
 	/**
 	/**
 	 * Determines if the interrupt flag of the thread is set.
 	 * Determines if the interrupt flag of the thread is set.
+	 * 
 	 * @return True when the flag is set, else false.
 	 * @return True when the flag is set, else false.
 	 */
 	 */
 	public boolean isTerminated() {
 	public boolean isTerminated() {
@@ -130,14 +142,19 @@ public class HoneyHandler implements Runnable {
 	}
 	}
 
 
 	/**
 	/**
-	 * Communicates with a client using the corresponding protocol implementation.
-	 * @param in InputStream of the socket.
-	 * @param out OutputStream of the socket.
+	 * Communicates with a client using the corresponding protocol
+	 * implementation.
+	 * 
+	 * @param in
+	 *            InputStream of the socket.
+	 * @param out
+	 *            OutputStream of the socket.
 	 * @throws IOException
 	 * @throws IOException
 	 */
 	 */
-	protected void talkToClient(InputStream in, OutputStream out) throws IOException {
+	protected void talkToClient(InputStream in, OutputStream out)
+			throws IOException {
 		ReaderWriter stream;
 		ReaderWriter stream;
-		if(protocol.getType().equals(byte[].class)) {
+		if (protocol.getType().equals(byte[].class)) {
 			stream = new ByteArrayReaderWriter(in, out, SLEEPTIME);
 			stream = new ByteArrayReaderWriter(in, out, SLEEPTIME);
 		} else {
 		} else {
 			stream = new StringReaderWriter(in, out);
 			stream = new StringReaderWriter(in, out);
@@ -148,16 +165,19 @@ public class HoneyHandler implements Runnable {
 			outputLine = protocol.processMessage(null);
 			outputLine = protocol.processMessage(null);
 			stream.write(outputLine);
 			stream.write(outputLine);
 			for (Packet o : outputLine) {
 			for (Packet o : outputLine) {
-				log.write(createRecord(TYPE.SEND, o.toString()));
+				Logger.log(HoneyService.getContext(),
+						createRecord(TYPE.SEND, o.toString()));
 			}
 			}
 		}
 		}
 		while (!thread.isInterrupted() && (inputLine = stream.read()) != null) {
 		while (!thread.isInterrupted() && (inputLine = stream.read()) != null) {
 			outputLine = protocol.processMessage(inputLine);
 			outputLine = protocol.processMessage(inputLine);
-			log.write(createRecord(TYPE.RECEIVE, inputLine.toString()));
+			Logger.log(HoneyService.getContext(),
+					createRecord(TYPE.RECEIVE, inputLine.toString()));
 			if (outputLine != null) {
 			if (outputLine != null) {
 				stream.write(outputLine);
 				stream.write(outputLine);
 				for (Packet o : outputLine) {
 				for (Packet o : outputLine) {
-					log.write(createRecord(TYPE.SEND, o.toString()));
+					Logger.log(HoneyService.getContext(),
+							createRecord(TYPE.SEND, o.toString()));
 				}
 				}
 			}
 			}
 			if (protocol.isClosed()) {
 			if (protocol.isClosed()) {
@@ -168,57 +188,71 @@ public class HoneyHandler implements Runnable {
 
 
 	/**
 	/**
 	 * Creates a Record for a message exchanged with a client.
 	 * Creates a Record for a message exchanged with a client.
-	 * @param type The type of the message.
-	 * @param packet The content of the message.
+	 * 
+	 * @param type
+	 *            The type of the message.
+	 * @param packet
+	 *            The content of the message.
 	 * @return The Record representing the communication message.
 	 * @return The Record representing the communication message.
 	 */
 	 */
 	protected Record createRecord(TYPE type, String packet) {
 	protected Record createRecord(TYPE type, String packet) {
 		Record record = new Record();
 		Record record = new Record();
-		record.setId(getAndIncrementMessageCounter());		
+		record.setId(getAndIncrementMessageCounter());
 		record.setAttack_id(attack_id);
 		record.setAttack_id(attack_id);
 		record.setProtocol(protocol.toString());
 		record.setProtocol(protocol.toString());
 		record.setType(type);
 		record.setType(type);
 		record.setTimestamp(System.currentTimeMillis());
 		record.setTimestamp(System.currentTimeMillis());
 		record.setExternalIP(externalIP);
 		record.setExternalIP(externalIP);
-		record.setLocalIP(client.getLocalAddress());
+		record.setLocalIP(client.getLocalAddress().getHostAddress());
+		record.setLocalHost(client.getLocalAddress().getHostName());
 		record.setLocalPort(protocol.getPort());
 		record.setLocalPort(protocol.getPort());
-		record.setRemoteIP(client.getInetAddress());
+		record.setRemoteIP(client.getInetAddress().getHostAddress());
+		record.setRemoteHost(client.getInetAddress().getHostName());
 		record.setRemotePort(client.getPort());
 		record.setRemotePort(client.getPort());
-		record.setBSSID(BSSID);
-		record.setSSID(SSID);
+		record.setBssid(BSSID);
+		record.setSsid(SSID);
 		record.setPacket(packet);
 		record.setPacket(packet);
-		if(MyLocationManager.getNewestLocation() != null){
-			record.setLatitude(MyLocationManager.getNewestLocation().getLatitude() );		
-			record.setLongitude(MyLocationManager.getNewestLocation().getLongitude() );
-			record.setAccuracy(MyLocationManager.getNewestLocation().getAccuracy() );
-			record.setTimestampLocation(MyLocationManager.getNewestLocation().getTime() );
-		}else {
-			record.setLatitude(0.0);		
+		if (MyLocationManager.getNewestLocation() != null) {
+			record.setLatitude(MyLocationManager.getNewestLocation()
+					.getLatitude());
+			record.setLongitude(MyLocationManager.getNewestLocation()
+					.getLongitude());
+			record.setAccuracy(MyLocationManager.getNewestLocation()
+					.getAccuracy());
+			record.setTimestampLocation(MyLocationManager.getNewestLocation()
+					.getTime());
+		} else {
+			record.setLatitude(0.0);
 			record.setLongitude(0.0);
 			record.setLongitude(0.0);
 			record.setAccuracy(Float.MAX_VALUE);
 			record.setAccuracy(Float.MAX_VALUE);
 			record.setTimestampLocation(0);
 			record.setTimestampLocation(0);
 		}
 		}
 		return record;
 		return record;
 	}
 	}
-	
+
 	/**
 	/**
-	 * Gets attack ID for the attack. Also increases the attack ID counter by one. Method is synchronized for thread safety.
-	 * @param pref The default SharedPreference of the application
+	 * Gets attack ID for the attack. Also increases the attack ID counter by
+	 * one. Method is synchronized for thread safety.
+	 * 
+	 * @param pref
+	 *            The default SharedPreference of the application
 	 * @return Unique integer attack ID
 	 * @return Unique integer attack ID
 	 */
 	 */
-	private synchronized int getAndIncrementAttackID(SharedPreferences pref){
+	private synchronized int getAndIncrementAttackID(SharedPreferences pref) {
 		Editor editor = pref.edit();
 		Editor editor = pref.edit();
 		int attackID = pref.getInt("ATTACK_ID_COUNTER", 0);
 		int attackID = pref.getInt("ATTACK_ID_COUNTER", 0);
 		editor.putInt("ATTACK_ID_COUNTER", attack_id + 1);
 		editor.putInt("ATTACK_ID_COUNTER", attack_id + 1);
 		editor.commit();
 		editor.commit();
 		return attackID;
 		return attackID;
 	}
 	}
-	
+
 	/**
 	/**
-	 * Gets current message ID for the record. Also increases the message ID counter by one. Method is synchronized for thread safety.
+	 * Gets current message ID for the record. Also increases the message ID
+	 * counter by one. Method is synchronized for thread safety.
+	 * 
 	 * @return Unique integer message ID
 	 * @return Unique integer message ID
 	 */
 	 */
-	private synchronized int getAndIncrementMessageCounter(){
+	private synchronized int getAndIncrementMessageCounter() {
 		int msgID = message_id;
 		int msgID = message_id;
 		message_id++;
 		message_id++;
 		return msgID;
 		return msgID;

+ 161 - 126
src/de/tudarmstadt/informatik/hostage/HoneyService.java

@@ -28,24 +28,35 @@ import android.support.v4.content.LocalBroadcastManager;
 import android.util.Log;
 import android.util.Log;
 import android.widget.Toast;
 import android.widget.Toast;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
-import de.tudarmstadt.informatik.hostage.logging.DatabaseHandler;
-import de.tudarmstadt.informatik.hostage.logging.Logger;
 import de.tudarmstadt.informatik.hostage.logging.MyLocationManager;
 import de.tudarmstadt.informatik.hostage.logging.MyLocationManager;
-import de.tudarmstadt.informatik.hostage.logging.SQLLogger;
+import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
 import de.tudarmstadt.informatik.hostage.protocol.Protocol;
 import de.tudarmstadt.informatik.hostage.protocol.Protocol;
 import de.tudarmstadt.informatik.hostage.protocol.ProtocolSettings;
 import de.tudarmstadt.informatik.hostage.protocol.ProtocolSettings;
 import de.tudarmstadt.informatik.hostage.ui.MainActivity;
 import de.tudarmstadt.informatik.hostage.ui.MainActivity;
+
 /**
 /**
  * Background service running as long as at least one protocol is active.
  * Background service running as long as at least one protocol is active.
- * Service controls start and stop of protocol listener.
- * Notifies GUI about events happening in the background.
- * Creates Notifications to inform the user what it happening.
- * @author Mihai Plasoianu 
+ * Service controls start and stop of protocol listener. Notifies GUI about
+ * events happening in the background. Creates Notifications to inform the user
+ * what it happening.
+ * 
+ * @author Mihai Plasoianu
  * @author Lars Pandikow
  * @author Lars Pandikow
  * @author Wulf Pfeiffer
  * @author Wulf Pfeiffer
  */
  */
 public class HoneyService extends Service {
 public class HoneyService extends Service {
 
 
+	private static Context context;
+
+	/**
+	 * Returns the application context.
+	 * 
+	 * @return context.
+	 */
+	public static Context getContext() {
+		return HoneyService.context;
+	}
+
 	private ArrayList<HoneyListener> listeners = new ArrayList<HoneyListener>();
 	private ArrayList<HoneyListener> listeners = new ArrayList<HoneyListener>();
 	private NotificationCompat.Builder builder;
 	private NotificationCompat.Builder builder;
 	private SharedPreferences sessionPref;
 	private SharedPreferences sessionPref;
@@ -55,12 +66,6 @@ public class HoneyService extends Service {
 		return listeners;
 		return listeners;
 	}
 	}
 
 
-	private Logger log;
-
-	public Logger getLog() {
-		return log;
-	}
-
 	private final IBinder mBinder = new LocalBinder();
 	private final IBinder mBinder = new LocalBinder();
 
 
 	public class LocalBinder extends Binder {
 	public class LocalBinder extends Binder {
@@ -77,8 +82,9 @@ public class HoneyService extends Service {
 	@Override
 	@Override
 	public void onCreate() {
 	public void onCreate() {
 		super.onCreate();
 		super.onCreate();
-		log = new SQLLogger(getApplicationContext());
-		sessionPref = getSharedPreferences(MainActivity.SESSION_DATA, Context.MODE_PRIVATE);
+		HoneyService.context = getApplicationContext();
+		sessionPref = getSharedPreferences(MainActivity.SESSION_DATA,
+				Context.MODE_PRIVATE);
 		editor = sessionPref.edit();
 		editor = sessionPref.edit();
 		createNotification();
 		createNotification();
 		for (Protocol protocol : getProtocolArray()) {
 		for (Protocol protocol : getProtocolArray()) {
@@ -86,15 +92,15 @@ public class HoneyService extends Service {
 		}
 		}
 		registerNetReceiver();
 		registerNetReceiver();
 		getLocationData();
 		getLocationData();
-		new QotdTask().execute(new String[]{});
+		new QotdTask().execute(new String[] {});
+	}
+
+	@Override
+	public int onStartCommand(Intent intent, int flags, int startId) {
+		// We want this service to continue running until it is explicitly
+		// stopped, so return sticky.
+		return START_STICKY;
 	}
 	}
-	
-    @Override
-    public int onStartCommand(Intent intent, int flags, int startId) {
-        // We want this service to continue running until it is explicitly
-        // stopped, so return sticky.
-        return START_STICKY;
-    }	
 
 
 	@Override
 	@Override
 	public void onDestroy() {
 	public void onDestroy() {
@@ -102,35 +108,37 @@ public class HoneyService extends Service {
 		super.onDestroy();
 		super.onDestroy();
 		unregisterNetReceiver();
 		unregisterNetReceiver();
 	}
 	}
-	
-	/** Starts an Instance of MyLocationManager to set the location within this class.
+
+	/**
+	 * Starts an Instance of MyLocationManager to set the location within this
+	 * class.
 	 */
 	 */
-	private void getLocationData(){
-		//TODO Put time and attempts in settings
+	private void getLocationData() {
+		// TODO Put time and attempts in settings
 		MyLocationManager locationManager = new MyLocationManager(this);
 		MyLocationManager locationManager = new MyLocationManager(this);
 		locationManager.getUpdates(60 * 1000, 3);
 		locationManager.getUpdates(60 * 1000, 3);
 	}
 	}
-	
+
 	/**
 	/**
 	 * Deletes all session related data.
 	 * Deletes all session related data.
 	 */
 	 */
-	private void deleteSessionData(){
-    	editor.clear();
-    	editor.commit();
+	private void deleteSessionData() {
+		editor.clear();
+		editor.commit();
 	}
 	}
-	
+
 	/**
 	/**
 	 * Register broadcast receiver for connectivity changes
 	 * Register broadcast receiver for connectivity changes
 	 */
 	 */
 	private void registerNetReceiver() {
 	private void registerNetReceiver() {
-	    // register BroadcastReceiver on network state changes	    
+		// register BroadcastReceiver on network state changes
 		IntentFilter intent = new IntentFilter();
 		IntentFilter intent = new IntentFilter();
-	    intent.addAction(ConnectivityManager.CONNECTIVITY_ACTION); //"android.net.conn.CONNECTIVITY_CHANGE"
-	    registerReceiver(netReceiver, intent);
+		intent.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // "android.net.conn.CONNECTIVITY_CHANGE"
+		registerReceiver(netReceiver, intent);
 	}
 	}
 
 
 	/**
 	/**
-	 *  Unregister broadcast receiver for connectivity changes
+	 * Unregister broadcast receiver for connectivity changes
 	 */
 	 */
 	private void unregisterNetReceiver() {
 	private void unregisterNetReceiver() {
 		unregisterReceiver(netReceiver);
 		unregisterReceiver(netReceiver);
@@ -138,57 +146,60 @@ public class HoneyService extends Service {
 
 
 	/**
 	/**
 	 * Receiver for connectivity change broadcast.
 	 * Receiver for connectivity change broadcast.
+	 * 
 	 * @see MainActivity#BROADCAST
 	 * @see MainActivity#BROADCAST
 	 */
 	 */
 	private BroadcastReceiver netReceiver = new BroadcastReceiver() {
 	private BroadcastReceiver netReceiver = new BroadcastReceiver() {
 		@Override
 		@Override
 		public void onReceive(Context context, Intent intent) {
 		public void onReceive(Context context, Intent intent) {
-				String bssid_old = sessionPref.getString(MainActivity.BSSID, "");
-				String bssid_new = HelperUtils.getBSSID(context);
-				//TODO INFORM UI
-				//TODO CHECK IF OTHER NETWORKS WORK TOO
-				if(bssid_new == null || !bssid_new.equals(bssid_old)){
-					getLocationData();
-					String[] protocols = getResources().getStringArray(R.array.protocols);
-					for (String protocol : protocols) {
-						editor.remove(protocol + MainActivity.HANDLER_COUNT);
-					}						
-					notifyUI("SERVICE", "CONNECTIVITY_CHANGE");
+			String bssid_old = sessionPref.getString(MainActivity.BSSID, "");
+			String bssid_new = HelperUtils.getBSSID(context);
+			// TODO INFORM UI
+			// TODO CHECK IF OTHER NETWORKS WORK TOO
+			if (bssid_new == null || !bssid_new.equals(bssid_old)) {
+				getLocationData();
+				String[] protocols = getResources().getStringArray(
+						R.array.protocols);
+				for (String protocol : protocols) {
+					editor.remove(protocol + MainActivity.HANDLER_COUNT);
 				}
 				}
+				notifyUI("SERVICE", "CONNECTIVITY_CHANGE");
+			}
 		}
 		}
-	};	
-
+	};
 
 
 	/**
 	/**
 	 * Creates a Notification in the notification bar.
 	 * Creates a Notification in the notification bar.
 	 */
 	 */
 	private void createNotification() {
 	private void createNotification() {
-		DatabaseHandler dbh = new DatabaseHandler(this);
+		UglyDbHelper dbh = new UglyDbHelper(this);
 		boolean activeHandlers = false;
 		boolean activeHandlers = false;
 		boolean bssidSeen = false;
 		boolean bssidSeen = false;
-		
-		for(String protocol : getResources().getStringArray(R.array.protocols)){
-			int handlerCount = sessionPref.getInt(protocol + MainActivity.HANDLER_COUNT, 0);
-			if(handlerCount > 0){
+
+		for (String protocol : getResources().getStringArray(R.array.protocols)) {
+			int handlerCount = sessionPref.getInt(protocol
+					+ MainActivity.HANDLER_COUNT, 0);
+			if (handlerCount > 0) {
 				activeHandlers = true;
 				activeHandlers = true;
 			}
 			}
-			if(dbh.bssidSeen(protocol, HelperUtils.getBSSID(getApplicationContext()))){
+			if (dbh.bssidSeen(protocol,
+					HelperUtils.getBSSID(getApplicationContext()))) {
 				bssidSeen = true;
 				bssidSeen = true;
 			}
 			}
 		}
 		}
-		builder = new NotificationCompat.Builder(this)
-										.setContentTitle(getString(R.string.app_name))
-										.setWhen(System.currentTimeMillis());	
-		if(activeHandlers){
+		builder = new NotificationCompat.Builder(this).setContentTitle(
+				getString(R.string.app_name)).setWhen(
+				System.currentTimeMillis());
+		if (activeHandlers) {
 			builder.setSmallIcon(R.drawable.ic_service_red);
 			builder.setSmallIcon(R.drawable.ic_service_red);
 			builder.setContentText("Network is infected!");
 			builder.setContentText("Network is infected!");
-		} else if(bssidSeen){
+		} else if (bssidSeen) {
 			builder.setSmallIcon(R.drawable.ic_service_yellow);
 			builder.setSmallIcon(R.drawable.ic_service_yellow);
 			builder.setContentText("Network has been infected in previous session!");
 			builder.setContentText("Network has been infected in previous session!");
-		} else{
+		} else {
 			builder.setSmallIcon(R.drawable.ic_service_green);
 			builder.setSmallIcon(R.drawable.ic_service_green);
 			builder.setContentText("Everything looks fine!");
 			builder.setContentText("Everything looks fine!");
-		}				
+		}
 		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
 		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
 		stackBuilder.addParentStack(MainActivity.class);
 		stackBuilder.addParentStack(MainActivity.class);
 		stackBuilder.addNextIntent(new Intent(this, MainActivity.class));
 		stackBuilder.addNextIntent(new Intent(this, MainActivity.class));
@@ -198,30 +209,32 @@ public class HoneyService extends Service {
 		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
 		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
 		mNotificationManager.notify(1, builder.build());
 		mNotificationManager.notify(1, builder.build());
 	}
 	}
-	
+
 	/**
 	/**
 	 * Updates the notification when a attack is registered.
 	 * Updates the notification when a attack is registered.
 	 */
 	 */
 	private void updateNotification() {
 	private void updateNotification() {
-		SharedPreferences defaultPref = PreferenceManager.getDefaultSharedPreferences(this);
-		String strRingtonePreference = defaultPref.getString("pref_notification_sound", "content://settings/system/notification_sound");  
+		SharedPreferences defaultPref = PreferenceManager
+				.getDefaultSharedPreferences(this);
+		String strRingtonePreference = defaultPref.getString(
+				"pref_notification_sound",
+				"content://settings/system/notification_sound");
 		builder = new NotificationCompat.Builder(this)
 		builder = new NotificationCompat.Builder(this)
 				.setContentTitle(getString(R.string.app_name))
 				.setContentTitle(getString(R.string.app_name))
 				.setTicker("Honeypot under attack!")
 				.setTicker("Honeypot under attack!")
 				.setContentText("Network is infected!")
 				.setContentText("Network is infected!")
-				.setSmallIcon(R.drawable.ic_service_red)
-				.setAutoCancel(true)
+				.setSmallIcon(R.drawable.ic_service_red).setAutoCancel(true)
 				.setWhen(System.currentTimeMillis())
 				.setWhen(System.currentTimeMillis())
-				.setSound(Uri.parse(strRingtonePreference)); 
+				.setSound(Uri.parse(strRingtonePreference));
 		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
 		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
 		stackBuilder.addParentStack(MainActivity.class);
 		stackBuilder.addParentStack(MainActivity.class);
 		stackBuilder.addNextIntent(new Intent(this, MainActivity.class));
 		stackBuilder.addNextIntent(new Intent(this, MainActivity.class));
 		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
 		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
 				PendingIntent.FLAG_UPDATE_CURRENT);
 				PendingIntent.FLAG_UPDATE_CURRENT);
 		builder.setContentIntent(resultPendingIntent);
 		builder.setContentIntent(resultPendingIntent);
-		if(defaultPref.getBoolean("pref_vibration", false)){
-			builder.setVibrate(new long[]{100, 200, 100, 200});
-		} 
+		if (defaultPref.getBoolean("pref_vibration", false)) {
+			builder.setVibrate(new long[] { 100, 200, 100, 200 });
+		}
 
 
 		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
 		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
 		mNotificationManager.notify(1, builder.build());
 		mNotificationManager.notify(1, builder.build());
@@ -235,10 +248,13 @@ public class HoneyService extends Service {
 		mNotificationManager.cancel(1);
 		mNotificationManager.cancel(1);
 	}
 	}
 
 
-
 	/**
 	/**
-	 * Creates a instance of each protocol defined in /res/values/protocols.xml and puts it in a List
-	 * @return ArrayList of {@link de.tudarmstadt.informatik.hostage.protocol.Protocol Protocol}
+	 * Creates a instance of each protocol defined in /res/values/protocols.xml
+	 * and puts it in a List
+	 * 
+	 * @return ArrayList of
+	 *         {@link de.tudarmstadt.informatik.hostage.protocol.Protocol
+	 *         Protocol}
 	 */
 	 */
 	private ArrayList<Protocol> getProtocolArray() {
 	private ArrayList<Protocol> getProtocolArray() {
 		String[] protocols = getResources().getStringArray(R.array.protocols);
 		String[] protocols = getResources().getStringArray(R.array.protocols);
@@ -256,29 +272,33 @@ public class HoneyService extends Service {
 		}
 		}
 		return protocolArray;
 		return protocolArray;
 	}
 	}
-	
+
 	/**
 	/**
 	 * Determines if there are running listeners.
 	 * Determines if there are running listeners.
+	 * 
 	 * @return True if there is a running listener, else false.
 	 * @return True if there is a running listener, else false.
 	 */
 	 */
-	public boolean hasRunningListeners(){
+	public boolean hasRunningListeners() {
 		for (HoneyListener listener : listeners) {
 		for (HoneyListener listener : listeners) {
-				if (listener.isRunning())
-					return true;
+			if (listener.isRunning())
+				return true;
 		}
 		}
 		return false;
 		return false;
 	}
 	}
 
 
 	/**
 	/**
 	 * Notifies the GUI about a event.
 	 * Notifies the GUI about a event.
-	 * @param protocol The protocol where the event happened.
-	 * @param key The key for the event.
+	 * 
+	 * @param protocol
+	 *            The protocol where the event happened.
+	 * @param key
+	 *            The key for the event.
 	 */
 	 */
 	public void notifyUI(String sender, String key) {
 	public void notifyUI(String sender, String key) {
 		// Send Notification
 		// Send Notification
-		if (key.equals(MainActivity.HANDLER_COUNT)){
+		if (key.equals(MainActivity.HANDLER_COUNT)) {
 			updateNotification();
 			updateNotification();
-		}else if(key.equals("CONNECTIVITY_CHANGE")){
+		} else if (key.equals("CONNECTIVITY_CHANGE")) {
 			createNotification();
 			createNotification();
 		}
 		}
 		Log.i("HoneyService", key);
 		Log.i("HoneyService", key);
@@ -287,18 +307,19 @@ public class HoneyService extends Service {
 		intent.putExtra("SENDER", sender);
 		intent.putExtra("SENDER", sender);
 		intent.putExtra("SENDER", key);
 		intent.putExtra("SENDER", key);
 		LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
 		LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
-	}	
-	
+	}
+
 	/**
 	/**
 	 * Starts all listeners which are not already running
 	 * Starts all listeners which are not already running
 	 */
 	 */
 	public void startListeners() {
 	public void startListeners() {
 		for (HoneyListener listener : listeners) {
 		for (HoneyListener listener : listeners) {
-			if(!listener.isRunning()){
+			if (!listener.isRunning()) {
 				listener.start();
 				listener.start();
 			}
 			}
 		}
 		}
-		Toast.makeText(getApplicationContext(), "SERVICES STARTED!", Toast.LENGTH_SHORT).show();
+		Toast.makeText(getApplicationContext(), "SERVICES STARTED!",
+				Toast.LENGTH_SHORT).show();
 	}
 	}
 
 
 	/**
 	/**
@@ -306,46 +327,55 @@ public class HoneyService extends Service {
 	 */
 	 */
 	public void stopListeners() {
 	public void stopListeners() {
 		for (HoneyListener listener : listeners) {
 		for (HoneyListener listener : listeners) {
-			if(listener.isRunning()){
+			if (listener.isRunning()) {
 				listener.stop();
 				listener.stop();
 			}
 			}
 		}
 		}
-		Toast.makeText(getApplicationContext(), "SERVICES STOPPED!", Toast.LENGTH_SHORT).show();
+		Toast.makeText(getApplicationContext(), "SERVICES STOPPED!",
+				Toast.LENGTH_SHORT).show();
 	}
 	}
 
 
 	/**
 	/**
 	 * Starts the listener for the specified protocol.
 	 * Starts the listener for the specified protocol.
-	 * @param protocolName Name of the protocol that should be started.
-	 */ 
+	 * 
+	 * @param protocolName
+	 *            Name of the protocol that should be started.
+	 */
 	public void startListener(String protocolName) {
 	public void startListener(String protocolName) {
 		for (HoneyListener listener : listeners) {
 		for (HoneyListener listener : listeners) {
 			if (listener.getProtocolName().equals(protocolName)) {
 			if (listener.getProtocolName().equals(protocolName)) {
-				if(!listener.isRunning()){
+				if (!listener.isRunning()) {
 					listener.start();
 					listener.start();
 				}
 				}
 			}
 			}
 		}
 		}
-		Toast.makeText(getApplicationContext(), protocolName + " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
+		Toast.makeText(getApplicationContext(),
+				protocolName + " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
 	}
 	}
 
 
 	/**
 	/**
 	 * Stops the listener for the specified protocol.
 	 * Stops the listener for the specified protocol.
-	 * @param protocolName Name of the protocol that should be stopped.
-	 */ 
+	 * 
+	 * @param protocolName
+	 *            Name of the protocol that should be stopped.
+	 */
 	public void stopListener(String protocolName) {
 	public void stopListener(String protocolName) {
 		for (HoneyListener listener : listeners) {
 		for (HoneyListener listener : listeners) {
 			if (listener.getProtocolName().equals(protocolName)) {
 			if (listener.getProtocolName().equals(protocolName)) {
-				if(listener.isRunning()){
+				if (listener.isRunning()) {
 					listener.stop();
 					listener.stop();
 				}
 				}
 			}
 			}
 		}
 		}
-		Toast.makeText(getApplicationContext(), protocolName + " SERVICE STOPPED!", Toast.LENGTH_SHORT).show();
+		Toast.makeText(getApplicationContext(),
+				protocolName + " SERVICE STOPPED!", Toast.LENGTH_SHORT).show();
 	}
 	}
 
 
 	/**
 	/**
 	 * Toggles a listener for specified protocol.
 	 * Toggles a listener for specified protocol.
-	 * @param protocolName Name of the protocol that should be toggled.
+	 * 
+	 * @param protocolName
+	 *            Name of the protocol that should be toggled.
 	 */
 	 */
 	public void toggleListener(String protocolName) {
 	public void toggleListener(String protocolName) {
 		for (HoneyListener listener : listeners) {
 		for (HoneyListener listener : listeners) {
@@ -358,38 +388,43 @@ public class HoneyService extends Service {
 			}
 			}
 		}
 		}
 	}
 	}
-	
+
 	/**
 	/**
 	 * Task for accuiring a qotd from one of four possible servers.
 	 * Task for accuiring a qotd from one of four possible servers.
+	 * 
 	 * @author Wulf Pfeiffer
 	 * @author Wulf Pfeiffer
 	 */
 	 */
-	private class QotdTask extends AsyncTask<String, Void, String>{	
-		 @Override
-		 protected String doInBackground(String... unused) {
-			 String[] sources = new String[]{"djxmmx.net", "ota.iambic.com", "alpha.mike-r.com", "electricbiscuit.org"};
-			 SecureRandom rndm = new SecureRandom();
-			 StringBuffer sb = new StringBuffer();
-			 try {
-				 Socket client = new Socket(sources[rndm.nextInt(4)], 17);
-				 BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));		
-				 while(!in.ready());
-				 while(in.ready()) {
-					 sb.append(in.readLine());
-				 }
-				 in.close();
-				 client.close();
-			 } catch (Exception e) {
-				 e.printStackTrace();
-			 }
-			 return sb.toString();
-		 }
-			 
-		 @Override
-		 protected void onPostExecute(String result){
-			 if (result != null)
-				 ProtocolSettings.setHttpQotd(result);
-			 else
-				 ProtocolSettings.setHttpQotd(new String(HelperUtils.getRandomString(100, false)));
-		 }
+	private class QotdTask extends AsyncTask<String, Void, String> {
+		@Override
+		protected String doInBackground(String... unused) {
+			String[] sources = new String[] { "djxmmx.net", "ota.iambic.com",
+					"alpha.mike-r.com", "electricbiscuit.org" };
+			SecureRandom rndm = new SecureRandom();
+			StringBuffer sb = new StringBuffer();
+			try {
+				Socket client = new Socket(sources[rndm.nextInt(4)], 17);
+				BufferedReader in = new BufferedReader(new InputStreamReader(
+						client.getInputStream()));
+				while (!in.ready())
+					;
+				while (in.ready()) {
+					sb.append(in.readLine());
+				}
+				in.close();
+				client.close();
+			} catch (Exception e) {
+				e.printStackTrace();
+			}
+			return sb.toString();
+		}
+
+		@Override
+		protected void onPostExecute(String result) {
+			if (result != null)
+				ProtocolSettings.setHttpQotd(result);
+			else
+				ProtocolSettings.setHttpQotd(new String(HelperUtils
+						.getRandomString(100, false)));
+		}
 	};
 	};
 }
 }

+ 111 - 66
src/de/tudarmstadt/informatik/hostage/commons/HelperUtils.java

@@ -30,19 +30,23 @@ import android.os.Environment;
 import android.preference.PreferenceManager;
 import android.preference.PreferenceManager;
 import android.text.TextUtils;
 import android.text.TextUtils;
 import de.tudarmstadt.informatik.hostage.logging.Record;
 import de.tudarmstadt.informatik.hostage.logging.Record;
+import de.tudarmstadt.informatik.hostage.logging.formatter.TraCINgFormatter;
 import de.tudarmstadt.informatik.hostage.net.MySSLSocketFactory;
 import de.tudarmstadt.informatik.hostage.net.MySSLSocketFactory;
 
 
 /**
 /**
  * Helper class with some static methods for general usage.
  * Helper class with some static methods for general usage.
+ * 
  * @author Lars Pandikow
  * @author Lars Pandikow
  * @author Wulf Pfeiffer
  * @author Wulf Pfeiffer
- *
+ * 
  */
  */
 public final class HelperUtils {
 public final class HelperUtils {
 
 
 	/**
 	/**
 	 * Gets SSID of the wireless network.
 	 * Gets SSID of the wireless network.
-	 * @param context Needs a context to get system recourses
+	 * 
+	 * @param context
+	 *            Needs a context to get system recourses
 	 * @return SSID of wireless network if connected, else null.
 	 * @return SSID of wireless network if connected, else null.
 	 */
 	 */
 	public static String getSSID(Context context) {
 	public static String getSSID(Context context) {
@@ -65,7 +69,9 @@ public final class HelperUtils {
 
 
 	/**
 	/**
 	 * Gets BSSID of the wireless network.
 	 * Gets BSSID of the wireless network.
-	 * @param context Needs a context to get system recourses.
+	 * 
+	 * @param context
+	 *            Needs a context to get system recourses.
 	 * @return BSSID of wireless network if connected, else null.
 	 * @return BSSID of wireless network if connected, else null.
 	 */
 	 */
 	public static String getBSSID(Context context) {
 	public static String getBSSID(Context context) {
@@ -88,8 +94,11 @@ public final class HelperUtils {
 
 
 	/**
 	/**
 	 * Gets internal IP address of the device in a wireless network.
 	 * Gets internal IP address of the device in a wireless network.
-	 * @param context Needs a context to get system recourses.
-	 * @return internal IP of the device in a wireless network if connected, else null.
+	 * 
+	 * @param context
+	 *            Needs a context to get system recourses.
+	 * @return internal IP of the device in a wireless network if connected,
+	 *         else null.
 	 */
 	 */
 	public static String getInternalIP(Context context) {
 	public static String getInternalIP(Context context) {
 		String ipAddress = null;
 		String ipAddress = null;
@@ -118,11 +127,13 @@ public final class HelperUtils {
 		return new byte[] { (byte) ((bytes) & 0xff),
 		return new byte[] { (byte) ((bytes) & 0xff),
 				(byte) ((bytes >>> 8) & 0xff), (byte) ((bytes >>> 16) & 0xff),
 				(byte) ((bytes >>> 8) & 0xff), (byte) ((bytes >>> 16) & 0xff),
 				(byte) ((bytes >>> 24) & 0xff) };
 				(byte) ((bytes >>> 24) & 0xff) };
-	} 
+	}
 
 
 	/**
 	/**
 	 * Checks if external storage is available for read and write.
 	 * Checks if external storage is available for read and write.
-	 * @return True if external storage is available for read and write, else false.
+	 * 
+	 * @return True if external storage is available for read and write, else
+	 *         false.
 	 */
 	 */
 	public static boolean isExternalStorageWritable() {
 	public static boolean isExternalStorageWritable() {
 		String state = Environment.getExternalStorageState();
 		String state = Environment.getExternalStorageState();
@@ -134,6 +145,7 @@ public final class HelperUtils {
 
 
 	/**
 	/**
 	 * Creates a HttpClient with an own SSL Socket.
 	 * Creates a HttpClient with an own SSL Socket.
+	 * 
 	 * @return HttpsClient who accepts accepts all certificates.
 	 * @return HttpsClient who accepts accepts all certificates.
 	 * @see MySSLSocketFactory
 	 * @see MySSLSocketFactory
 	 */
 	 */
@@ -164,46 +176,56 @@ public final class HelperUtils {
 			return new DefaultHttpClient();
 			return new DefaultHttpClient();
 		}
 		}
 	}
 	}
-	
+
 	/**
 	/**
 	 * Uploads a single Record to a server, specified in the settings.
 	 * Uploads a single Record to a server, specified in the settings.
-	 * @param record The Record to upload.
+	 * 
+	 * @param record
+	 *            The Record to upload.
 	 * @return True if the upload was successful, else false.
 	 * @return True if the upload was successful, else false.
 	 */
 	 */
-	public static boolean uploadSingleRecord(Context context, Record record){
-	  	// Create a https client. Uses MySSLSocketFactory to accept all certificates
+	public static boolean uploadSingleRecord(Context context, Record record) {
+		// Create a https client. Uses MySSLSocketFactory to accept all
+		// certificates
 		HttpClient httpclient = HelperUtils.createHttpClient();
 		HttpClient httpclient = HelperUtils.createHttpClient();
 		HttpPost httppost;
 		HttpPost httppost;
 		try {
 		try {
 			// Create HttpPost
 			// Create HttpPost
-			httppost = new HttpPost(PreferenceManager.getDefaultSharedPreferences(context).getString("pref_upload", "https://ssi.cased.de"));
+			httppost = new HttpPost(PreferenceManager
+					.getDefaultSharedPreferences(context).getString(
+							"pref_upload", "https://ssi.cased.de"));
 			// Create JSON String of Record
 			// Create JSON String of Record
-			StringEntity se = new StringEntity(record.toString(0x01));
+			StringEntity se = new StringEntity(record.toString(TraCINgFormatter
+					.getInstance()));
 			httppost.setEntity(se);
 			httppost.setEntity(se);
 			// Execute HttpPost
 			// Execute HttpPost
 			httpclient.execute(httppost);
 			httpclient.execute(httppost);
 		} catch (Exception e) {
 		} catch (Exception e) {
 			e.printStackTrace();
 			e.printStackTrace();
 			return false;
 			return false;
-		}		
+		}
 		return true;
 		return true;
 	}
 	}
-	
+
 	/**
 	/**
 	 * Concatenates several byte arrays.
 	 * Concatenates several byte arrays.
-	 * @param bytes The byte arrays.
-	 * @return A single byte arrays containing all the bytes from the given arrays in the order they are given.
+	 * 
+	 * @param bytes
+	 *            The byte arrays.
+	 * @return A single byte arrays containing all the bytes from the given
+	 *         arrays in the order they are given.
 	 */
 	 */
 	public static byte[] concat(byte[]... bytes) {
 	public static byte[] concat(byte[]... bytes) {
 		int newSize = 0;
 		int newSize = 0;
 		for (byte[] b : bytes)
 		for (byte[] b : bytes)
-			if(b != null) newSize += b.length;
+			if (b != null)
+				newSize += b.length;
 		byte[] dst = new byte[newSize];
 		byte[] dst = new byte[newSize];
 
 
 		int currentPos = 0;
 		int currentPos = 0;
 		int newPos;
 		int newPos;
 		for (byte[] b : bytes) {
 		for (byte[] b : bytes) {
-			if(b != null) {
+			if (b != null) {
 				newPos = b.length;
 				newPos = b.length;
 				System.arraycopy(b, 0, dst, currentPos, newPos);
 				System.arraycopy(b, 0, dst, currentPos, newPos);
 				currentPos += newPos;
 				currentPos += newPos;
@@ -211,10 +233,13 @@ public final class HelperUtils {
 		}
 		}
 		return dst;
 		return dst;
 	}
 	}
-	
+
 	/**
 	/**
-	 * Converts a byte[] to a String, but only characters in ASCII between 32 and 127
-	 * @param bytes that are converted
+	 * Converts a byte[] to a String, but only characters in ASCII between 32
+	 * and 127
+	 * 
+	 * @param bytes
+	 *            that are converted
 	 * @return converted String
 	 * @return converted String
 	 */
 	 */
 	public static String byteToStr(byte[] bytes) {
 	public static String byteToStr(byte[] bytes) {
@@ -230,97 +255,117 @@ public final class HelperUtils {
 
 
 	/**
 	/**
 	 * Determines if a character is in ASCII between 32 and 126
 	 * Determines if a character is in ASCII between 32 and 126
-	 * @param character that is checked 
+	 * 
+	 * @param character
+	 *            that is checked
 	 * @return true if the character is between 32 and 126, else false
 	 * @return true if the character is between 32 and 126, else false
 	 */
 	 */
 	private static boolean isLetter(char character) {
 	private static boolean isLetter(char character) {
 		return (character > 31 && character < 127);
 		return (character > 31 && character < 127);
 	}
 	}
-	
+
 	/**
 	/**
-	 * Converts a byte array into a hexadecimal String, e.g. {0x00, 0x01} to "00, 01". 
-	 * @param bytes that will be converted.
+	 * Converts a byte array into a hexadecimal String, e.g. {0x00, 0x01} to
+	 * "00, 01".
+	 * 
+	 * @param bytes
+	 *            that will be converted.
 	 * @return converted String.
 	 * @return converted String.
 	 */
 	 */
 	public static String bytesToHexString(byte[] bytes) {
 	public static String bytesToHexString(byte[] bytes) {
 		char[] hexArray = "0123456789ABCDEF".toCharArray();
 		char[] hexArray = "0123456789ABCDEF".toCharArray();
-	    int v;
-	    StringBuffer buffer = new StringBuffer();
-	    for(int j = 0; j < bytes.length; j++ ) {
-	        v = bytes[j] & 0xFF;
-	        buffer.append(hexArray[v >>> 4]);
-	        buffer.append(hexArray[v & 0x0F]);
-	        if(j < bytes.length-1) buffer.append(", ");
-	    }
-	    return buffer.toString();
+		int v;
+		StringBuffer buffer = new StringBuffer();
+		for (int j = 0; j < bytes.length; j++) {
+			v = bytes[j] & 0xFF;
+			buffer.append(hexArray[v >>> 4]);
+			buffer.append(hexArray[v & 0x0F]);
+			if (j < bytes.length - 1)
+				buffer.append(", ");
+		}
+		return buffer.toString();
 	}
 	}
-	
+
 	/**
 	/**
-	 * Converts a String into a byte array, e.g. "00, 01" to {0x00, 0x01}. 
-	 * @param string that will be converted.
+	 * Converts a String into a byte array, e.g. "00, 01" to {0x00, 0x01}.
+	 * 
+	 * @param string
+	 *            that will be converted.
 	 * @return converted byte array.
 	 * @return converted byte array.
 	 */
 	 */
 	public static byte[] hexStringToBytes(String string) {
 	public static byte[] hexStringToBytes(String string) {
-	    String[] hexStrings = string.split(", ");
-	    byte[] bytes = new byte[hexStrings.length];
-	    for(int j = 0; j < hexStrings.length; j++ ) {
-	    	bytes[j] = (byte) ((Character.digit(hexStrings[j].charAt(0), 16) << 4)
-                    + Character.digit(hexStrings[j].charAt(1), 16));
-	    }
-	    return bytes;
+		String[] hexStrings = string.split(", ");
+		byte[] bytes = new byte[hexStrings.length];
+		for (int j = 0; j < hexStrings.length; j++) {
+			bytes[j] = (byte) ((Character.digit(hexStrings[j].charAt(0), 16) << 4) + Character
+					.digit(hexStrings[j].charAt(1), 16));
+		}
+		return bytes;
 	}
 	}
-	
+
 	/**
 	/**
-	 * Produces a random String.
-	 * The String can be of random length with a maximum length, or it can be forced to have the length that was given.
-	 * @param length maximal / forced length of String.
-	 * @param forceLength forces the String to be exact the given length instead of maximum
+	 * Produces a random String. The String can be of random length with a
+	 * maximum length, or it can be forced to have the length that was given.
+	 * 
+	 * @param length
+	 *            maximal / forced length of String.
+	 * @param forceLength
+	 *            forces the String to be exact the given length instead of
+	 *            maximum
 	 * @return random String.
 	 * @return random String.
 	 */
 	 */
 	public static String getRandomString(int length, boolean forceLength) {
 	public static String getRandomString(int length, boolean forceLength) {
 		SecureRandom rndm = new SecureRandom();
 		SecureRandom rndm = new SecureRandom();
 		char[] c = new char[forceLength ? length : rndm.nextInt(length)];
 		char[] c = new char[forceLength ? length : rndm.nextInt(length)];
-		for(int i = 0; i < c.length; i++) {
-			c[i] = (char) (rndm.nextInt(95)+32);
+		for (int i = 0; i < c.length; i++) {
+			c[i] = (char) (rndm.nextInt(95) + 32);
 		}
 		}
 		return new String(c);
 		return new String(c);
 	}
 	}
-	
+
 	/**
 	/**
-	 * Puts a 0x00 byte between each byte and another 2 0x00 bytes at the end of a byte array.
-	 * @param bytes that need to be filled with 0x00.
+	 * Puts a 0x00 byte between each byte and another 2 0x00 bytes at the end of
+	 * a byte array.
+	 * 
+	 * @param bytes
+	 *            that need to be filled with 0x00.
 	 * @return filled byte array.
 	 * @return filled byte array.
 	 */
 	 */
 	public static byte[] fillWithZeroExtended(byte[] bytes) {
 	public static byte[] fillWithZeroExtended(byte[] bytes) {
 		byte[] zeroBytes = fillWithZero(bytes);
 		byte[] zeroBytes = fillWithZero(bytes);
-		byte[] newBytes = new byte[zeroBytes.length+2];
-		newBytes = HelperUtils.concat(zeroBytes, new byte[]{0x00, 0x00});
+		byte[] newBytes = new byte[zeroBytes.length + 2];
+		newBytes = HelperUtils.concat(zeroBytes, new byte[] { 0x00, 0x00 });
 		return newBytes;
 		return newBytes;
 	}
 	}
-	
+
 	/**
 	/**
 	 * Puts a 0x00 byte between each byte in a byte array.
 	 * Puts a 0x00 byte between each byte in a byte array.
-	 * @param bytes that need to be filled with 0x00.
+	 * 
+	 * @param bytes
+	 *            that need to be filled with 0x00.
 	 * @return filled byte array.
 	 * @return filled byte array.
 	 */
 	 */
 	public static byte[] fillWithZero(byte[] bytes) {
 	public static byte[] fillWithZero(byte[] bytes) {
 		byte[] newBytes = new byte[(bytes.length * 2)];
 		byte[] newBytes = new byte[(bytes.length * 2)];
-		for(int i = 0, j = 0; i < bytes.length && j < newBytes.length; i++, j=j+2) {
+		for (int i = 0, j = 0; i < bytes.length && j < newBytes.length; i++, j = j + 2) {
 			newBytes[j] = bytes[i];
 			newBytes[j] = bytes[i];
-			newBytes[j+1] = 0x00;
+			newBytes[j + 1] = 0x00;
 		}
 		}
 		return newBytes;
 		return newBytes;
 	}
 	}
-	
+
 	/**
 	/**
-	 * Turns around the values of an byte[], e.g. {0x00, 0x01, 0x02} turns into {0x02, 0x01, 0x00}.
-	 * @param bytes array that is turned.
+	 * Turns around the values of an byte[], e.g. {0x00, 0x01, 0x02} turns into
+	 * {0x02, 0x01, 0x00}.
+	 * 
+	 * @param bytes
+	 *            array that is turned.
 	 * @return turned array.
 	 * @return turned array.
 	 */
 	 */
 	public static byte[] turnByteArray(byte[] bytes) {
 	public static byte[] turnByteArray(byte[] bytes) {
 		byte[] tmp = new byte[bytes.length];
 		byte[] tmp = new byte[bytes.length];
-		for(int i = 0; i < bytes.length; i++) {
-			tmp[i] = bytes[bytes.length-1-i];
+		for (int i = 0; i < bytes.length; i++) {
+			tmp[i] = bytes[bytes.length - 1 - i];
 		}
 		}
 		return tmp;
 		return tmp;
 	}
 	}

+ 0 - 14
src/de/tudarmstadt/informatik/hostage/format/DefaultFormatter.java

@@ -1,14 +0,0 @@
-package de.tudarmstadt.informatik.hostage.format;
-
-/**
- * Default log view formatter.
- * 
- * @author Wulf Pfeiffer
- */
-public class DefaultFormatter implements ProtocolFormatter {
-
-	public String format(String packet) {
-		return packet;
-	}
-
-}

+ 0 - 46
src/de/tudarmstadt/informatik/hostage/format/LogViewFormatter.java

@@ -1,46 +0,0 @@
-package de.tudarmstadt.informatik.hostage.format;
-
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.ui.MainActivity;
-
-/**
- * Log view formatter used to format packet contents for the log view.
- * @author Wulf Pfeiffer
- */
-public class LogViewFormatter {
-	
-	/**
-	 * Formats the content of a packet giving it a specific format specified by a ProtocolFormatter. 
-	 * @param protocol that is used for packet.
-	 * @param packet content.
-	 * @return formatted String of the packet content.
-	 */
-	public static String format(String protocol, String packet) {		
-		return getFormatter(protocol).format(packet);
-	}
-	
-	/**
-	 * Loads a ProtocolFormatter for a protocol.
-	 * If the protocol has its own formatter, with the name *protocol name*Formatter and it is located in .format package, it is loaded,
-	 * else a default formatter is loaded.
-	 * @param protocol that a formatter should be loaded for.
-	 * @return the loaded formatter.
-	 */
-	private static ProtocolFormatter getFormatter(String protocol) {
-		String[] protocols = MainActivity.getContext().getResources().getStringArray(R.array.protocols);
-		String packageName = ProtocolFormatter.class.getPackage().getName();
-		ProtocolFormatter formatter = new DefaultFormatter();
-
-		for (String prot : protocols) {
-			try {
-				if(protocol.equals(prot)) formatter = (ProtocolFormatter) Class.forName(
-						String.format("%s.%s", packageName, protocol+"Formatter"))
-						.newInstance();
-			} catch (Exception e) {
-				e.printStackTrace();
-			}
-		}
-		return formatter;
-	}
-
-}

+ 0 - 64
src/de/tudarmstadt/informatik/hostage/format/MySQLFormatter.java

@@ -1,64 +0,0 @@
-package de.tudarmstadt.informatik.hostage.format;
-
-import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
-
-/**
- * MySQL log view formatter.
- * @author Wulf Pfeiffer
- */
-public class MySQLFormatter implements ProtocolFormatter {
-
-	public String format(String packet) {
-		byte[] bytes = HelperUtils.hexStringToBytes(packet);
-		String command = "Command: " + getCommand(bytes) + "\n";
-		String content = "Content: " + HelperUtils.byteToStr(bytes) + "\n";
-		return command + content;
-	}
-	
-	/**
-	 * Checks a packet for its command code and returns the name of this command.
-	 * @param bytes to check.
-	 * @return name of the command.
-	 */
-	private String getCommand(byte[] bytes) {
-		//if packet number is 1 server started conversation so it must be login
-		if(bytes.length < 5) return "";
-		if(bytes[3] == 0x01) return "Login request"; 
-		//else check for command code
-		switch(bytes[4]) {
-		case 0x00: return "COM_SLEEP";
-		case 0x01: return "COM_QUIT";
-		case 0x02: return "COM_INIT_DB";
-		case 0x03: return "COM_QUERY";
-		case 0x04: return "COM_FIELD_LIST";
-		case 0x05: return "COM_CREATE_DB";
-		case 0x06: return "COM_DROP_DB";
-		case 0x07: return "COM_REFRESH";
-		case 0x08: return "COM_SHUTDOWN";
-		case 0x09: return "COM_STATISTICS";
-		case 0x0a: return "COM_PROCESS_INFO";
-		case 0x0b: return "COM_CONNECT";
-		case 0x0c: return "COM_PROCESS_KILL";
-		case 0x0d: return "COM_DEBUG";
-		case 0x0e: return "COM_PING";
-		case 0x0f: return "COM_TIME";
-		case 0x10: return "COM_DELAYED_INSERT";
-		case 0x11: return "COM_CHANGE_USER";
-		case 0x12: return "COM_BINLOG_DUMP";
-		case 0x13: return "COM_TABLE_DUMP";
-		case 0x14: return "COM_CONNECT_OUT";
-		case 0x15: return "COM_REGISTER_SLAVE";
-		case 0x16: return "COM_STMT_PREPARE";
-		case 0x17: return "COM_STMT_EXECUTE";
-		case 0x18: return "COM_STMT_SEND_LONG_DATA";
-		case 0x19: return "COM_STMT_CLOSE";
-		case 0x1a: return "COM_STMT_RESET";
-		case 0x1b: return "COM_SET_OPTION";
-		case 0x1c: return "COM_STMT_FETCH";
-		case 0x1d: return "COM_DAEMON";
-		case 0x1e: return "COM_BINLOG_DUMP_GTID";
-		default: return "unkown command";
-		}
-	}
-
-}

+ 0 - 17
src/de/tudarmstadt/informatik/hostage/format/ProtocolFormatter.java

@@ -1,17 +0,0 @@
-package de.tudarmstadt.informatik.hostage.format;
-
-/**
- * Interface for log view formatter.
- * This class provides functionality to format the presentation of specific protocols.
- * @author Wulf Pfeiffer
- */
-public interface ProtocolFormatter {
-
-	/**
-	 * Formats the content of packet. The packet content can be a normal String or a hexadecimal String,
-	 * depending of the type of the protocol. ByteArray protocols receive hexdecimal String, else normal Strings.
-	 * @param packet that should be formatted.
-	 * @return new format of the packet content.
-	 */
-	String format(String packet);
-}

+ 0 - 135
src/de/tudarmstadt/informatik/hostage/format/SMBFormatter.java

@@ -1,135 +0,0 @@
-package de.tudarmstadt.informatik.hostage.format;
-
-import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
-
-/**
- * SMB log view formatter.
- * @author Wulf Pfeiffer
- */
-public class SMBFormatter implements ProtocolFormatter {
-
-	public String format(String packet) {
-		byte[] bytes = HelperUtils.hexStringToBytes(packet);
-		byte cmd = bytes[8]; //command code located at 8
-		StringBuffer buffer = new StringBuffer();
-		buffer.append("Command: ");
-		buffer.append(getCommandString(cmd));
-		buffer.append("\n");
-		buffer.append("Content: ");
-		buffer.append(getContent(cmd, bytes));
-		
-		return buffer.toString();
-	}
-	
-	/**
-	 * Checks command code for its command code and returns the name of this command.
-	 * @param command as byte.
-	 * @return command name as String.
-	 */
-	private String getCommandString(byte command) {
-		switch(command) {
-		case 0x00: return "SMB_COM_CREATE_DIRECTORY";
-		case 0x01: return "SMB_COM_DELETE_DIRECTORY";
-		case 0x02: return "SMB_COM_OPEN";
-		case 0x03: return "SMB_COM_CREATE";
-		case 0x04: return "SMB_COM_CLOSE";
-		case 0x05: return "SMB_COM_FLUSH";
-		case 0x06: return "SMB_COM_DELETE";
-		case 0x07: return "SMB_COM_RENAME";
-		case 0x08: return "SMB_COM_QUERY_INFORMATION";
-		case 0x09: return "SMB_COM_SET_INFORMATION";
-		case 0x0A: return "SMB_COM_READ";
-		case 0x0B: return "SMB_COM_WRITE";
-		case 0x0C: return "SMB_COM_LOCK_BYTE_RANGE";
-		case 0x0D: return "SMB_COM_UNLOCK_BYTE_RANGE";
-		case 0x0E: return "SMB_COM_CREATE_TEMPORARY";
-		case 0x0F: return "SMB_COM_CREATE_NEW";
-		case 0x10: return "SMB_COM_CHECK_DIRECTORY";
-		case 0x11: return "SMB_COM_PROCESS_EXIT";
-		case 0x12: return "SMB_COM_SEEK";
-		case 0x13: return "SMB_COM_LOCK_AND_READ";
-		case 0x14: return "SMB_COM_WRITE_AND_UNLOCK";
-		case 0x1A: return "SMB_COM_READ_RAW";
-		case 0x1B: return "SMB_COM_READ_MPX";
-		case 0x1C: return "SMB_COM_READ_MPX_SECONDARY";
-		case 0x1D: return "SMB_COM_WRITE_RAW";
-		case 0x1E: return "SMB_COM_WRITE_MPX";
-		case 0x1F: return "SMB_COM_WRITE_MPX_SECONDARY";
-		case 0x20: return "SMB_COM_WRITE_COMPLETE";
-		case 0x21: return "SMB_COM_QUERY_SERVER";
-		case 0x22: return "SMB_COM_SET_INFORMATION2";
-		case 0x23: return "SMB_COM_QUERY_INFORMATION2";
-		case 0x24: return "SMB_COM_LOCKING_ANDX";
-		case 0x25: return "SMB_COM_TRANSACTION";
-		case 0x26: return "SMB_COM_TRANSACTION_SECONDARY";
-		case 0x27: return "SMB_COM_IOCTL";
-		case 0x28: return "SMB_COM_IOCTL_SECONDARY";
-		case 0x29: return "SMB_COM_COPY";
-		case 0x2A: return "SMB_COM_MOVE";
-		case 0x2B: return "SMB_COM_ECHO";
-		case 0x2C: return "SMB_COM_WRITE_AND_CLOSE";
-		case 0x2D: return "SMB_COM_OPEN_ANDX";
-		case 0x2E: return "SMB_COM_READ_ANDX";
-		case 0x2F: return "SMB_COM_WRITE_ANDX";
-		case 0x30: return "SMB_COM_NEW_FILE_SIZE";
-		case 0x31: return "SMB_COM_CLOSE_AND_TREE_DISC";
-		case 0x32: return "SMB_COM_TRANSACTION2";
-		case 0x33: return "SMB_COM_TRANSACTION2_SECONDARY";
-		case 0x34: return "SMB_COM_FIND_CLOSE2";
-		case 0x35: return "SMB_COM_FIND_NOTIFY_CLOSE";
-		case 0x70: return "SMB_COM_TREE_CONNECT";
-		case 0x71: return "SMB_COM_TREE_DISCONNECT";
-		case 0x72: return "SMB_COM_NEGOTIATE";
-		case 0x73: return "SMB_COM_SESSION_SETUP_ANDX";
-		case 0x74: return "SMB_COM_LOGOFF_ANDX";
-		case 0x75: return "SMB_COM_TREE_CONNECT_ANDX";
-		case (byte)0x80: return "SMB_COM_QUERY_INFORMATION_DISK";
-		case (byte)0x81: return "SMB_COM_SEARCH";
-		case (byte)0x82: return "SMB_COM_FIND";
-		case (byte)0x83: return "SMB_COM_FIND_UNIQUE";
-		case (byte)0x84: return "SMB_COM_FIND_CLOSE";
-		case (byte)0xA0: return "SMB_COM_NT_TRANSACT";
-		case (byte)0xA1: return "SMB_COM_NT_TRANSACT_SECONDARY";
-		case (byte)0xA2: return "SMB_COM_NT_CREATE_ANDX";
-		case (byte)0xA4: return "SMB_COM_NT_CANCEL";
-		case (byte)0xA5: return "SMB_COM_NT_RENAME";
-		case (byte)0xC0: return "SMB_COM_OPEN_PRINT_FILE";
-		case (byte)0xC1: return "SMB_COM_WRITE_PRINT_FILE";
-		case (byte)0xC2: return "SMB_COM_CLOSE_PRINT_FILE";
-		case (byte)0xC3: return "SMB_COM_GET_PRINT_QUEUE";
-		case (byte)0xD8: return "SMB_COM_READ_BULK";
-		case (byte)0xD9: return "SMB_COM_WRITE_BULK";
-		case (byte)0xDA: return "SMB_COM_WRITE_BULK_DATA";
-		case (byte)0xFF: return "SMB_COM_NONE";
-		default: return "Unknown Command";
-		}
-	}
-	
-	/**
-	 * Returns the content of a packet as a String value, depending on its command code
-	 * @param command of the packet.
-	 * @param packet content as byte array. 
-	 * @return content as a String.
-	 */
-	private String getContent(byte command, byte[] packet) {
-		switch(command) {
-		case 0x72: return get0x72content(packet);
-		case 0x73: return HelperUtils.byteToStr(packet);
-		case (byte) 0xa2: return HelperUtils.byteToStr(packet);
-		case 0x25: return HelperUtils.byteToStr(packet);
-		default: return "";
-		}
-	}
-	
-	/**
-	 * Returns the content of a packet with command code 0x72.
-	 * @param packet content as byte array.
-	 * @return content as String.
-	 */
-	private String get0x72content(byte[] packet) {
-		byte[] content = new byte[packet.length-39];
-		System.arraycopy(packet, 39, content, 0, content.length);
-		return HelperUtils.byteToStr(content);
-	}
-
-}

+ 0 - 99
src/de/tudarmstadt/informatik/hostage/format/TELNETFormatter.java

@@ -1,99 +0,0 @@
-package de.tudarmstadt.informatik.hostage.format;
-
-import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
-
-/**
- * Telnet log view formatter.
- * 
- * @author Wulf Pfeiffer
- */
-public class TELNETFormatter implements ProtocolFormatter {
-
-	public String format(String packet) {
-		byte[] bytes = HelperUtils.hexStringToBytes(packet);
-		String options = "Options:\n" + checkForOptions(bytes) + "\n";
-		String content = "Content: " + HelperUtils.byteToStr(bytes);
-		return options + content;
-	}
-
-	/**
-	 * Checks a packet for option commands and returns their names as Strings.
-	 * @param bytes that are checked.
-	 * @return names of the option commands as String.
-	 */
-	private String checkForOptions(byte[] bytes) {
-		StringBuffer options = new StringBuffer();
-		for (int i = 0; i < bytes.length; i++) {
-			if (bytes[i] == (byte) 0xff && i + 2 < bytes.length) {
-				options.append(checkMode(bytes[i + 1]));
-				// option name
-				options.append(checkCommand(bytes[i + 2]));
-			}
-		}
-		return options.toString();
-	}
-	
-	/**
-	 * Checks a byte for its mode value.
-	 * @param b byte that is checked.
-	 * @return name of the mode.
-	 */
-	private String checkMode(byte b) {
-		switch (b) {
-		case (byte) 0xfb:	return " WILL ";
-		case (byte) 0xfc:	return " WON'T ";
-		case (byte) 0xfd:	return " DO ";
-		case (byte) 0xfe:	return " DON'T ";
-		default:			return " unkown command ";
-		}
-	}
-	
-	/**
-	 * Checks a byte for its command value.
-	 * @param b byte that is checked.
-	 * @return name of the command.
-	 */
-	private String checkCommand(byte b) {
-		switch (b) {
-		case 0x00:	return "Binary Transmission\n";
-		case 0x01:	return "Echo\n";
-		case 0x02:	return "Reconnection\n";
-		case 0x03:	return "Suppress Go Ahead\n";
-		case 0x04:	return "Approx Message Size Negotiation\n";
-		case 0x05:	return "Status\n";
-		case 0x06:	return "Timing Mark\n";
-		case 0x07:	return "Remote Controlled Trans and Echo\n";
-		case 0x08:	return "Output Line Width\n";
-		case 0x09:	return "Output Page Size\n";
-		case 0x0a:	return "Output Carriage-Return Disposition\n";
-		case 0x0b:	return "Output Horizontal Tab Stops\n";
-		case 0x0c:	return "Output Horizontal Tab Disposition\n";
-		case 0x0d:	return "Output Formfeed Disposition\n";
-		case 0x0e:	return "Output Vertical Tabstops\n";
-		case 0x0f:	return "Output Vertical Tab Disposition\n";
-		case 0x10:	return "Output Linefeed Disposition\n";
-		case 0x11:	return "Extended ASCII\n";
-		case 0x12:	return "Logout\n";
-		case 0x13:	return "Byte Macro\n";
-		case 0x14:	return "Data Entry Terminal\n";
-		case 0x15:	return "SUPDUP\n";
-		case 0x16:	return "SUPDUP Output\n";
-		case 0x17:	return "Send Location\n";
-		case 0x18:	return "Terminal Type\n";
-		case 0x19:	return "End of Record\n";
-		case 0x1a:	return "TACACS User Identification\n";
-		case 0x1b:	return "Output Marking\n";
-		case 0x1c:	return "Terminal Location Number\n";
-		case 0x1d:	return "Telnet 3270 Regime\n";
-		case 0x1e:	return "X.3 PAD\n";
-		case 0x1f:	return "Negotiate About Window Size\n";
-		case 0x20:	return "Terminal Speed\n";
-		case 0x21:	return "Remote Flow Control\n";
-		case 0x22:	return "Linemode\n";
-		case 0x23:	return "X Display Location\n";
-		case (byte) 0xff:	return "Extended-Options-List\n";
-		default:	return "unknown option\n";
-		}
-	}
-
-}

+ 0 - 597
src/de/tudarmstadt/informatik/hostage/logging/DatabaseHandler.java

@@ -1,597 +0,0 @@
-package de.tudarmstadt.informatik.hostage.logging;
-
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.logging.Record.TYPE;
-import de.tudarmstadt.informatik.hostage.protocol.Protocol;
-import android.content.ContentValues;
-import android.content.Context;
-import android.database.Cursor;
-import android.database.sqlite.SQLiteDatabase;
-import android.database.sqlite.SQLiteOpenHelper;
-import android.util.Log;
-/**
- * This class creates SQL tables and handles all access to the database.<br>
- * It contains several methods with predefined queries to extract different kinds of information from the database.<br>
- * The database contains two tables: {@link #TABLE_RECORDS} and {@link #TABLE_BSSIDS}:<br>
- * {@link #TABLE_RECORDS} contains all logging information of a single message record except the SSID.<br>
- * {@link #TABLE_BSSIDS} contains the BSSID of all recorded Networks and the corresponding SSID.<br>
- * @author Lars Pandikow
- */
-public class DatabaseHandler extends SQLiteOpenHelper {
-
-	// All Static variables
-	// Database Version
-	private static final int DATABASE_VERSION = 1;
-
-	// Database Name
-	private static final String DATABASE_NAME = "recordManager";
-
-	// Contacts table names
-	private static final String TABLE_ATTACK_INFO = "attack_info";
-	private static final String TABLE_RECORDS = "records";
-	private static final String TABLE_BSSIDS = "bssids";
-	private static final String TABLE_PORTS = "ports";
-
-	// Contacts Table Columns names
-	public static final String KEY_ID = "_id";
-	public static final String KEY_ATTACK_ID = "_attack_id";
-	public static final String KEY_TYPE = "type";
-	public static final String KEY_TIME = "timestamp";
-	public static final String KEY_PACKET = "packet";
-	public static final String KEY_PROTOCOL = "protocol";
-	public static final String KEY_EXTERNAL_IP ="externalIP";
-	public static final String KEY_LOCAL_IP = "localIP";
-	public static final String KEY_LOCAL_HOSTNAME = "localHostName";
-	public static final String KEY_LOCAL_PORT = "localPort";
-	public static final String KEY_REMOTE_IP = "remoteIP";
-	public static final String KEY_REMOTE_HOSTNAME = "remoteHostName";
-	public static final String KEY_REMOTE_PORT = "remotePort";
-	public static final String KEY_BSSID = "_bssid";
-	public static final String KEY_SSID = "ssid";
-	public static final String KEY_LATITUDE = "latitude";
-	public static final String KEY_LONGITUDE = "longitude";
-	public static final String KEY_ACCURACY = "accuracy";
-
-	
-	// Database sql create statements
-	private static final String CREATE_RECORD_TABLE = "CREATE TABLE " + TABLE_RECORDS + "(" 
-			+ KEY_ID + " INTEGER NOT NULL," + KEY_ATTACK_ID + " INTEGER NOT NULL," 
-			+ KEY_TYPE + " TEXT," + KEY_TIME + " INTEGER," +  KEY_PACKET + " TEXT," 
-			+ "FOREIGN KEY("+ KEY_ATTACK_ID +") REFERENCES " + TABLE_ATTACK_INFO + "("+KEY_ATTACK_ID+")" 
-			+ "PRIMARY KEY("+ KEY_ID + ", " + KEY_ATTACK_ID + ")"
-			+ ")";
-	
-	private static final String CREATE_ATTACK_INFO_TABLE = "CREATE TABLE " + TABLE_ATTACK_INFO + "(" 
-			+ KEY_ATTACK_ID + " INTEGER PRIMARY KEY," + KEY_PROTOCOL + " TEXT,"
-			+ KEY_EXTERNAL_IP + " TEXT," + KEY_LOCAL_IP + " BLOB," + KEY_LOCAL_HOSTNAME + " TEXT," 
-			+ KEY_REMOTE_IP + " BLOB," + KEY_REMOTE_HOSTNAME + " TEXT," + KEY_REMOTE_PORT + " INTEGER," + KEY_BSSID + " TEXT," 
-			+ "FOREIGN KEY("+ KEY_BSSID +") REFERENCES " + TABLE_BSSIDS + "("+KEY_BSSID+")" 
-			+ "FOREIGN KEY("+ KEY_PROTOCOL +") REFERENCES " + TABLE_PORTS + "("+KEY_PROTOCOL+")" 
-			+ ")";
-	
-	private static final String CREATE_BSSID_TABLE = "CREATE TABLE " + TABLE_BSSIDS + "(" 
-			+ KEY_BSSID + " TEXT PRIMARY KEY," + KEY_SSID + " TEXT," + KEY_LATITUDE + " INTEGER,"
-			+ KEY_LONGITUDE + " INTEGER," + KEY_ACCURACY + " INTEGER," + KEY_TIME + " INTEGER"
-			+ ")";
-	
-	private static final String CREATE_PORT_TABLE = "CREATE TABLE " + TABLE_PORTS + "(" 
-			+ KEY_PROTOCOL + " TEXT PRIMARY KEY," + KEY_LOCAL_PORT + " INTEGER"
-			+ ")";
-
-	private Context context;
-	
-	public DatabaseHandler(Context context) {
-		super(context, DATABASE_NAME, null, DATABASE_VERSION);
-		this.context = context;
-	}
-
-	// Creating Tables
-	@Override
-	public void onCreate(SQLiteDatabase db) {
-		db.execSQL(CREATE_PORT_TABLE);
-		db.execSQL(CREATE_BSSID_TABLE);
-		db.execSQL(CREATE_ATTACK_INFO_TABLE);
-		db.execSQL(CREATE_RECORD_TABLE);
-				
-		String[] protocols = context.getResources().getStringArray(R.array.protocols);
-		String packageName = Protocol.class.getPackage().getName();
-
-		//Initialize Port Table
-		for (String protocol : protocols) {
-			try {				
-				int port = ((Protocol) Class.forName(String.format("%s.%s", packageName, protocol)).newInstance()).getPort();
-		        db.execSQL("INSERT INTO " + TABLE_PORTS + " VALUES ( '" + protocol + "'," + port + ")");
-			} catch (Exception e) {
-				e.printStackTrace();
-			}
-		}
-	}
-	
-	// Upgrading database
-	@Override
-	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
-		// Drop older table if existed
-		db.execSQL("DROP TABLE IF EXISTS " + TABLE_RECORDS);
-		db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTACK_INFO);
-		db.execSQL("DROP TABLE IF EXISTS " + TABLE_BSSIDS);
-		db.execSQL("DROP TABLE IF EXISTS " + TABLE_PORTS);
-		
-		// Create tables again
-		onCreate(db);
-	}
-
-	/**
-	 * Adds a given {@link Record}  to the database.
-	 * @param record The added {@link Record} .
-	 */
-	public void addRecord(Record record) {
-		SQLiteDatabase db = this.getWritableDatabase();
-
-		HashMap<String, Object> bssidValues = new HashMap<String, Object>();
-		bssidValues.put(KEY_BSSID, record.getBSSID());
-		bssidValues.put(KEY_SSID, record.getSSID());
-		bssidValues.put(KEY_LATITUDE, record.getLatitude());
-		bssidValues.put(KEY_LONGITUDE, record.getLongitude());
-		bssidValues.put(KEY_ACCURACY, record.getAccuracy());
-		bssidValues.put(KEY_TIME, record.getTimestampLocation());
-		
-		ContentValues attackValues = new ContentValues();
-		attackValues.put(KEY_ATTACK_ID, record.getAttack_id()); // Log Attack ID
-		attackValues.put(KEY_PROTOCOL, record.getProtocol().toString());
-		attackValues.put(KEY_EXTERNAL_IP, record.getExternalIP());
-		attackValues.put(KEY_LOCAL_IP, record.getLocalIP().getAddress()); // Log Local IP
-		attackValues.put(KEY_LOCAL_HOSTNAME, record.getLocalIP().getHostName());
-		attackValues.put(KEY_REMOTE_IP, record.getRemoteIP().getAddress()); // Log Remote IP
-		attackValues.put(KEY_REMOTE_HOSTNAME, record.getRemoteIP().getHostName());
-		attackValues.put(KEY_REMOTE_PORT, record.getRemotePort()); // Log Remote Port
-		attackValues.put(KEY_BSSID, record.getBSSID());
-		
-		ContentValues recordValues = new ContentValues();
-		recordValues.put(KEY_ID, record.getId()); // Log Message Number
-		recordValues.put(KEY_ATTACK_ID, record.getAttack_id()); // Log Attack ID
-		recordValues.put(KEY_TYPE, record.getType().name()); // Log Type
-		recordValues.put(KEY_TIME, record.getTimestamp()); // Log Timestamp
-		recordValues.put(KEY_PACKET, record.getPacket()); // Log Packet
-		
-
-		
-		
-		// Inserting Rows		
-		db.insertWithOnConflict(TABLE_ATTACK_INFO, null, attackValues, SQLiteDatabase.CONFLICT_REPLACE);
-		db.insert(TABLE_RECORDS, null, recordValues);
-		db.close(); // Closing database connection
-		// Update Network Information
-		updateNetworkInformation(bssidValues);
-	}
-	
-	/**
-	 * Creates a {@link Record} from a Cursor. If the cursor does not show to a valid data structure a runtime exception is thrown.
-	 * @param cursor
-	 * @return Returns the created {@link Record} .
-	 */
-	private Record createRecord(Cursor cursor){
-		Record record = new Record();
-		try {
-		record.setId(Integer.parseInt(cursor.getString(0)));
-		record.setAttack_id(cursor.getLong(1));
-		record.setType(cursor.getString(2).equals("SEND") ? TYPE.SEND : TYPE.RECEIVE);
-		record.setTimestamp(cursor.getLong(3));
-		record.setPacket(cursor.getString(4));
-		record.setProtocol(cursor.getString(5));
-		record.setExternalIP(cursor.getString(6));
-		record.setLocalIP(InetAddress.getByAddress(cursor.getString(8), cursor.getBlob(7)));
-		record.setRemoteIP(InetAddress.getByAddress(cursor.getString(10), cursor.getBlob(9)));
-		record.setRemotePort(Integer.parseInt(cursor.getString(11)));
-		record.setBSSID(cursor.getString(12));
-		record.setSSID(cursor.getString(13));
-		record.setLatitude(Double.parseDouble(cursor.getString(14)));
-		record.setLongitude(Double.parseDouble(cursor.getString(15)));
-		record.setAccuracy(Float.parseFloat(cursor.getString(16)));
-		record.setTimestampLocation(cursor.getLong(17));
-		record.setLocalPort(Integer.parseInt(cursor.getString(18)));
-		} catch (UnknownHostException e) {
-			e.printStackTrace();
-		}
-		return record;
-	}
-
-	/**
-	 * Gets a single {@link Record} with the given ID from the database.
-	 * @param id The ID of the {@link Record};
-	 * @return The {@link Record}.
-	 */
-	public Record getRecord(int id) {
-		String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN " + TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS + " WHERE " + KEY_ID + " = " + id;
-		SQLiteDatabase db = this.getReadableDatabase();
-
-		Cursor cursor = db.rawQuery(selectQuery, null);
-		Record record = null;
-		if (cursor.moveToFirst()){
-			record = createRecord(cursor);
-		} 
-		
-        cursor.close();
-		db.close();
-		// return contact
-		return record;
-	}
-
-	/**
-	 * Gets all {@link Record Records} saved in the database. 
-	 * @return A ArrayList of all the {@link Record Records} in the Database.
-	 */
-	public ArrayList<Record> getAllRecords() {
-		ArrayList<Record> recordList = new ArrayList<Record>();
-		// Select All Query
-		String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN " + TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS;
-
-		SQLiteDatabase db = this.getWritableDatabase();
-		Cursor cursor = db.rawQuery(selectQuery, null);
-
-		Log.i("Database", "Start loop");
-		// looping through all rows and adding to list
-		if (cursor.moveToFirst()) {
-			do {
-				Log.i("Database", "Add Record");
-				Record record = createRecord(cursor);				
-				// Adding record to list
-				recordList.add(record);
-			} while (cursor.moveToNext());
-		}
-        cursor.close();
-		db.close();
-		// return record list
-		return recordList;
-	}
-    
-	/**
-	 * Gets a single {@link Record} with the given attack id from the database.
-	 * @param attack_id The attack id of the {@link Record};
-	 * @return The {@link Record}.
-	 */
-    public Record getRecordOfAttackId(long attack_id) {
-        String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN " + TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS + " WHERE " + KEY_ATTACK_ID + " = " + attack_id + " GROUP BY " + KEY_ATTACK_ID;
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(selectQuery, null);
-        Record record = null;
-        
-		if (cursor.moveToFirst()) {
-				record = createRecord(cursor);
-		}
-        cursor.close();
- 
-        // return record list
-        db.close();
-        return record;
-    }
-    
-	/**
-	 * Gets all received {@link Record Records} for every attack identified by its attack id and ordered by date.
-	 * @return A ArrayList with all received {@link Record Records} for each attack id in the Database.
-	 */
-    public ArrayList<Record> getAllReceivedRecordsOfEachAttack() {
-    	ArrayList<Record> recordList = new ArrayList<Record>();
-        String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN " + TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS + " WHERE " + KEY_TYPE + "='RECEIVE'" + " ORDER BY " + KEY_TIME;
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(selectQuery, null);
-		
-        // looping through all rows and adding to list
-		if (cursor.moveToFirst()) {
-			do {
-				Record record = createRecord(cursor);
-				// Adding record to list
-				recordList.add(record);
-			} while (cursor.moveToNext());
-		}       
-        cursor.close();
- 
-        // return record list
-        db.close();
-        return recordList;
-    }
-    
-	/**
-	 * Gets a representative {@link Record} for every attack identified by its attack id.
-	 * @return A ArrayList with one {@link Record Records} for each attack id in the Database.
-	 */
-    public ArrayList<Record> getRecordOfEachAttack() {
-    	ArrayList<Record> recordList = new ArrayList<Record>();
-        String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN " + TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS + " GROUP BY " + KEY_ATTACK_ID;
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(selectQuery, null);
-		
-        // looping through all rows and adding to list
-		if (cursor.moveToFirst()) {
-			do {
-				Record record = createRecord(cursor);
-				// Adding record to list
-				recordList.add(record);
-			} while (cursor.moveToNext());
-		}       
-        cursor.close();
- 
-        // return record list
-        db.close();
-        return recordList;
-    }
-    
-	/**
-	 * Gets a representative {@link Record} for every attack with a higher attack id than the specified.
-	 * @param attack_id The attack id to match the query against.
-	 * @return A ArrayList with one {@link Record Records} for each attack id higher than the given.
-	 */
-    public ArrayList<Record> getRecordOfEachAttack(long attack_id) {
-    	ArrayList<Record> recordList = new ArrayList<Record>();
-        String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN " + TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS + " WHERE " + KEY_ATTACK_ID + " > " + attack_id + " GROUP BY " + KEY_ATTACK_ID;
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(selectQuery, null);
-		
-        // looping through all rows and adding to list
-		if (cursor.moveToFirst()) {
-			do {
-				Record record = createRecord(cursor);
-				// Adding record to list
-				recordList.add(record);
-			} while (cursor.moveToNext()); 
-		}       
-        cursor.close();
- 
-        // return count
-        db.close();
-        return recordList;
-    }
-	
-	/**
-	 * Determines the number of {@link Record Records} in the database.
-	 * @return The number of {@link Record Records} in the database.
-	 */
-    public int getRecordCount() {
-        String countQuery = "SELECT  * FROM " + TABLE_RECORDS;
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(countQuery, null);
-       int result = cursor.getCount();
-       cursor.close();
- 
-        // return count
-        db.close();
-        return result;
-    }
-    
-	/**
-	 * Determines the number of different attack_ids in the database.
-	 * @return The number of different attack_ids in the database.
-	 */
-    public int getAttackCount() {
-        String countQuery = "SELECT  * FROM " + TABLE_ATTACK_INFO;
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(countQuery, null);
-        int result = cursor.getCount();
-        cursor.close();
- 
-        // return count
-        db.close();
-        return result;
-    }
-    
-	/**
-	 * Determines the number of different attack_ids for a specific protocol in the database.
-	 * @param protocol The String representation of the {@link de.tudarmstadt.informatik.hostage.protocol.Protocol Protocol}
-	 * @return The number of different attack_ids in the database.
-	 */
-    public int getAttackPerProtokolCount(String protocol) {
-        String countQuery = "SELECT  * FROM " + TABLE_ATTACK_INFO + " WHERE " + KEY_PROTOCOL + " = " + "'" + protocol + "'";
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(countQuery, null);
-        int result = cursor.getCount();
-        cursor.close();
- 
-        // return count
-        db.close();
-        return result;
-    }
-    
-   /**
-    * Determines the smallest attack id stored in the database.
-    * @return The smallest attack id stored in the database.
-    */
-    public long getSmallestAttackId(){
-    	String selectQuery = "SELECT MIN(" + KEY_ATTACK_ID +") FROM " + TABLE_ATTACK_INFO;
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(selectQuery, null);        
-        int result;
-        
-        if (cursor.moveToFirst()) {
-        	result = cursor.getInt(0);
-        } else{
-        	result = -1;
-        }        
-    	cursor.close();
-    	db.close();
-    	return result;
-    }
-    
-    /**
-     * Determines the highest attack id stored in the database.
-     * @return The highest attack id stored in the database.
-     */
-    public long getHighestAttackId(){
-    	String selectQuery = "SELECT MAX(" + KEY_ATTACK_ID +") FROM " + TABLE_ATTACK_INFO;
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(selectQuery, null);
-        int result;
-        
-        if (cursor.moveToFirst()) {
-        	result = cursor.getInt(0);
-        } else{
-        	result = -1;
-        }        
-    	cursor.close();
-    	db.close();
-    	return result;
-    }
-   
-    /**
-     * Determines if a network with given BSSID has already been recorded as malicious.
-     * @param BSSID The BSSID of the network.
-     * @return True if an attack has been recorded in a network with the given BSSID, else false.
-     */
-    public boolean bssidSeen(String BSSID){
-        String countQuery = "SELECT  * FROM " + TABLE_BSSIDS + " WHERE "  + KEY_BSSID + " = " + "'" + BSSID + "'";
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(countQuery, null);
-        int result = cursor.getCount();
-        cursor.close();
-        db.close();
-        return result > 0;        
-    }
-    
-    
-    /**
-     * Determines if an attack has been recorded on a specific protocol in a network with a given BSSID.
-     * @param protocol The {@link de.tudarmstadt.informatik.hostage.protocol.Protocol Protocol} to inspect.
-     * @param BSSID The BSSID of the network.
-     * @return True if an attack on the given protocol has been recorded in a network with the given BSSID, else false.
-     */
-    public boolean bssidSeen(String protocol, String BSSID){
-        String countQuery = "SELECT  * FROM " + TABLE_ATTACK_INFO + " NATURAL JOIN " + TABLE_BSSIDS+ " WHERE " + KEY_PROTOCOL + " = " + "'" + protocol + "'" + " AND " + KEY_BSSID + " = " + "'" + BSSID + "'";
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(countQuery, null);
-        int result = cursor.getCount();
-        cursor.close();
-        db.close();
-        return result > 0;        
-    }
-    
-    /**
-     * Returns a String array with all BSSIDs stored in the database.
-     * @return String[] of all recorded BSSIDs.
-     */
-    public String[] getAllBSSIDS(){
-        String selectQuery = "SELECT  * FROM " + TABLE_BSSIDS;
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(selectQuery, null);
-        String[] bssidList = new String[cursor.getCount()];
-        int counter = 0;
-        // looping through all rows and adding to list
-		if (cursor.moveToFirst()) {
-			do {
-				bssidList[counter] = cursor.getString(0);
-				counter++;
-			} while (cursor.moveToNext());
-		}       
-        cursor.close();
-        db.close();
-        return bssidList;
-    }
-    
-    /**
-     * Gets the last recorded SSID to a given BSSID.
-     * @param bssid The BSSID to match against.
-     * @return A String of the last SSID or null if the BSSID is not in the database.
-     */
-    public String getSSID(String bssid){
-    	String selectQuery = "SELECT "+ KEY_SSID +" FROM " + TABLE_BSSIDS + " WHERE " + KEY_BSSID + " = " + "'" + bssid + "'";
-    	SQLiteDatabase db = this.getReadableDatabase();
-    	Cursor cursor = db.rawQuery(selectQuery, null);
-    	String ssid = null;
-    	if(cursor.moveToFirst()){
-    		ssid = cursor.getString(0);
-    	}
-        cursor.close();
-        db.close();
-        return ssid;
-    }
-    
-    /**
-     * Deletes all records from {@link #TABLE_RECORDS} with a specific BSSID.
-     * @param bssid The BSSID to match against.
-     */
-    public void deleteByBSSID(String bssid){
-    	SQLiteDatabase db = this.getReadableDatabase();
-    	db.delete(TABLE_RECORDS, KEY_BSSID + " = ?", new String[]{bssid});
-    	db.delete(TABLE_ATTACK_INFO, KEY_BSSID + " = ?", new String[]{bssid});
-    	db.close();
-    }
-    
-  //TODO Delete statement �berarbeiten
-    /**
-     * Deletes all records from {@link #TABLE_RECORDS} with a time stamp smaller then the given
-     * @param date A Date represented in milliseconds.
-     */
-    public void deleteByDate(long date){
-    	SQLiteDatabase db = this.getReadableDatabase();
-    	String deleteQuery = "DELETE  FROM " + TABLE_RECORDS + " WHERE " + KEY_TIME + " < " + date;
-    	//TODO Delete statement �berarbeiten
-//    	String deleteQuery2 = "DELETE "
-    	db.execSQL(deleteQuery);
-    	db.close();
-    }
-    
-    /**
-     *  Deletes all records from {@link #TABLE_RECORDS}.
-     */
-    public void clearData(){
-    	SQLiteDatabase db = this.getReadableDatabase();
-        db.delete(TABLE_RECORDS, null, null);
-        db.delete(TABLE_ATTACK_INFO, null, null);
-        db.close();
-    }
-    
-    public ArrayList<HashMap<String, Object>> getNetworkInformation(){
-        String selectQuery = "SELECT  * FROM " + TABLE_BSSIDS;
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(selectQuery, null);
-    	
-        ArrayList<HashMap<String, Object>> networkInformation = new ArrayList<HashMap<String, Object>>();
-    	
-        // looping through all rows and adding to list
-		if (cursor.moveToFirst()) {
-			do {
-				HashMap<String, Object> values = new HashMap<String, Object>();
-				values.put(KEY_BSSID, cursor.getString(0));
-				values.put(KEY_SSID, cursor.getString(1));
-				values.put(KEY_LATITUDE, Double.parseDouble(cursor.getString(2)));
-				values.put(KEY_LONGITUDE, Double.parseDouble(cursor.getString(3)));
-				values.put(KEY_ACCURACY, Float.parseFloat(cursor.getString(4)));
-				values.put(KEY_TIME, cursor.getLong(5));
-				networkInformation.add(values);
-			} while (cursor.moveToNext());
-		}              
-		
-		cursor.close();        
-        db.close();        
-    	return networkInformation;
-    }
-    
-    public void updateNetworkInformation(HashMap<String, Object> networkInformation){ 
-        SQLiteDatabase db = this.getReadableDatabase();
-		String bssid = (String) networkInformation.get(KEY_BSSID);
-		String bssidQuery = "SELECT  * FROM " + TABLE_BSSIDS + " WHERE "  + KEY_BSSID + " = " + "'" + bssid + "'";
-        Cursor cursor = db.rawQuery(bssidQuery, null);
-        int result = cursor.getCount();
-        if( cursor != null && cursor.moveToFirst() && (result <= 0 || cursor.getLong(5) < (Long) networkInformation.get(KEY_TIME)));{
-        	ContentValues bssidValues = new ContentValues();
-    		bssidValues.put(KEY_BSSID, bssid);
-    		bssidValues.put(KEY_SSID, (String) networkInformation.get(KEY_SSID));
-    		bssidValues.put(KEY_LATITUDE, (double)(Double) networkInformation.get(KEY_LATITUDE));
-    		bssidValues.put(KEY_LONGITUDE, (double)(Double) networkInformation.get(KEY_LONGITUDE));
-    		bssidValues.put(KEY_ACCURACY, (float)(Float) networkInformation.get(KEY_ACCURACY));
-    		bssidValues.put(KEY_TIME, (Long) networkInformation.get(KEY_TIME));
-        	db.insertWithOnConflict(TABLE_BSSIDS, null, bssidValues, SQLiteDatabase.CONFLICT_REPLACE);
-        }    		
-        cursor.close();  
-        db.close();
-    }
-    
-    public void updateNetworkInformation(ArrayList<HashMap<String, Object>> networkInformation){ 
-    	Log.i("DatabaseHandler", "Starte updating");
-    	for(HashMap<String, Object> values : networkInformation){
-    		updateNetworkInformation(values);
-    	}	        
-    }
-}

+ 30 - 0
src/de/tudarmstadt/informatik/hostage/logging/LogResultReceiver.java

@@ -0,0 +1,30 @@
+package de.tudarmstadt.informatik.hostage.logging;
+
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.ResultReceiver;
+
+public class LogResultReceiver extends ResultReceiver {
+
+	private Receiver mReceiver;
+
+	public void setReceiver(Receiver receiver) {
+		mReceiver = receiver;
+	}
+
+	public LogResultReceiver(Handler handler) {
+		super(handler);
+	}
+
+	public interface Receiver {
+		public void onReceiveResult(int resultCode, Bundle resultData);
+	}
+
+	@Override
+	protected void onReceiveResult(int resultCode, Bundle resultData) {
+		if (mReceiver != null) {
+			mReceiver.onReceiveResult(resultCode, resultData);
+		}
+	}
+
+}

+ 311 - 80
src/de/tudarmstadt/informatik/hostage/logging/Logger.java

@@ -1,90 +1,321 @@
 package de.tudarmstadt.informatik.hostage.logging;
 package de.tudarmstadt.informatik.hostage.logging;
 
 
 import java.util.ArrayList;
 import java.util.ArrayList;
+
+import android.app.IntentService;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.ResultReceiver;
+
 /**
 /**
- * Interface to define which functionality is needed for a Logger in this application.
- * @author Mihai Plasoianu 
- * @author Lars Pandikow
- *
+ * An {@link IntentService} subclass for handling asynchronous task requests in
+ * a service on a separate handler thread.
+ * 
+ * @author Mihai Plasoianu
  */
  */
-public interface Logger {
-	/**
-	 * Write a single Record to the log.
-	 * @param record The Record that has to be added.
-	 */
-	void write(Record record);
-	
-	/**
-	 * Returns all saved Records.
-	 * @return ArrayList which contains all Records from the log.
-	 */
-	ArrayList<Record> getAllRecords();
-	/**
-	 * Returns a single Record as representative for each attack with an attack id higher then the given.
-	 * @param lastUploadedAttackId The threshold value for attack id's
-	 * @return ArrayList which contains one Record for each attack.
-	 */
-	ArrayList<Record> getRecordOfEachAttack(int lastUploadedAttackId);
-	/**
-	 * 
-	 * @param attack_id Attack id of the record
-	 * @return A Record with a specific attack id, or null if there is no Record with such an attack id.
-	 */
-	Record getRecordOfAttackId(long attack_id);
-	
-	/**
-	 * Determines the number of recorded attacks.
-	 * @return he Number of Attacks.
-	 */
-	int getAttackCount();	
-	/**
-	 * Returns the number of recorded attack for a specific protocol.
-	 * @param protocol The considered protocol.
-	 * @return The Number of recorded attacks per protocol.
-	 */
-	int getAttackPerProtokolCount(String protocol);
-	/**
-	 * Finds the smallest saved attack id.
-	 * @return The smallest saved attack id.
-	 */
-	long getSmallestAttackId();
-	/**
-	 * Finds the highest saved attack id.
-	 * @return The highest saved attack id.
-	 */
-	long getHighestAttackId();
-	
-	/**
-	 * Determines if an attack on a given protocol has already been recorded in a network with a specific BSSID.
-	 * @param protocol The considered protocol.
-	 * @param bssid The considered BSSID.
-	 * @return True if there has been a attack on a protocol in a network with the given BSSID, else returns false.
-	 */
-	boolean bssidSeen(String protocol, String bssid);
-	/**
-	 * Returns all BSSIDs in which an attack has been recorded.
-	 * @return String arrays with all recorded BSSIDs
-	 */
-	String[] getAllBSSIDS();
-	/**
-	 * Returns the last known SSID of a network with a specific BSSID.
-	 * @param bssid The considered BSSID.
-	 * @return String representation of the searched SSID, or null if there is no entry with the given BSSID
-	 */
-	String getSSID(String bssid);
-	
-	/**
-	 * Deletes all Records with a smaller time stamp than the given.
-	 * @param time The time stamp to compare with.
-	 */
-	void deleteByDate(long time);
+public class Logger extends IntentService {
+
+	private static final String ACTION_LOG = "de.tudarmstadt.informatik.hostage.action.LOG";
+	private static final String ACTION_GET_RECORD_ALL = "de.tudarmstadt.informatik.hostage.action.GET_RECORD_ALL";
+	private static final String ACTION_GET_RECORD_EACH = "de.tudarmstadt.informatik.hostage.action.GET_RECORD_EACH";
+	private static final String ACTION_GET_RECORD_ID = "de.tudarmstadt.informatik.hostage.action.GET_RECORD_ID";
+	private static final String ACTION_GET_COUNT_ALL = "de.tudarmstadt.informatik.hostage.action.GET_COUNT_ALL";
+	private static final String ACTION_GET_COUNT_PROTOCOL = "de.tudarmstadt.informatik.hostage.action.GET_COUNT_PROTOCOL";
+	private static final String ACTION_GET_ATTACK_MIN = "de.tudarmstadt.informatik.hostage.action.GET_ATTACK_MIN";
+	private static final String ACTION_GET_ATTACK_MAX = "de.tudarmstadt.informatik.hostage.action.GET_ATTACK_MAX";
+	private static final String ACTION_IS_BSSID_SEEN = "de.tudarmstadt.informatik.hostage.action.IS_BSSID_SEEN";
+	private static final String ACTION_GET_BSSID_ALL = "de.tudarmstadt.informatik.hostage.action.GET_BSSID_ALL";
+	private static final String ACTION_GET_SSID_BSSID = "de.tudarmstadt.informatik.hostage.action.GET_SSID_BSSID";
+	private static final String ACTION_CLEAR_DATE = "de.tudarmstadt.informatik.hostage.action.CLEAR_DATE";
+	private static final String ACTION_CLEAR_BSSID = "de.tudarmstadt.informatik.hostage.action.CLEAR_BSSID";
+	private static final String ACTION_CLEAR_ALL = "de.tudarmstadt.informatik.hostage.action.CLEAR_ALL";
+
+	private static final String EXTRA_RECORD = "de.tudarmstadt.informatik.hostage.extra.RECORD";
+	private static final String EXTRA_PROTOCOL = "de.tudarmstadt.informatik.hostage.extra.PROTOCOL";
+	private static final String EXTRA_BSSID = "de.tudarmstadt.informatik.hostage.extra.BSSID";
+	private static final String EXTRA_PRIMITIVE = "de.tudarmstadt.informatik.hostage.extra.PRIMITIVE";
+
+	private static final String RESULT_RECEIVER = "de.tudarmstadt.informatik.hostage.RESULT_RECEIVER";
+
+	public static void log(Context context, Record record) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_LOG);
+		intent.putExtra(EXTRA_RECORD, record);
+		context.startService(intent);
+	}
+
+	public static void getAllRecords(Context context, ResultReceiver receiver) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_GET_RECORD_ALL);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getRecordOfEachAttack(Context context,
+			int lastUploadedAttackId, ResultReceiver receiver) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_GET_RECORD_EACH);
+		intent.putExtra(EXTRA_PRIMITIVE, lastUploadedAttackId);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getRecordOfAttackId(Context context, long attack_id,
+			ResultReceiver receiver) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_GET_RECORD_ID);
+		intent.putExtra(EXTRA_PRIMITIVE, attack_id);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getAttackCount(Context context, ResultReceiver receiver) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_GET_COUNT_ALL);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getAttackPerProtocolCount(Context context,
+			String protocol, ResultReceiver receiver) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_GET_COUNT_PROTOCOL);
+		intent.putExtra(EXTRA_PROTOCOL, protocol);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getMinAttackId(Context context, ResultReceiver receiver) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_GET_ATTACK_MIN);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getMaxAttackId(Context context, ResultReceiver receiver) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_GET_ATTACK_MAX);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void isBssidSeen(Context context, String protocol,
+			String bssid, ResultReceiver receiver) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_IS_BSSID_SEEN);
+		intent.putExtra(EXTRA_PROTOCOL, protocol);
+		intent.putExtra(EXTRA_BSSID, bssid);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getAllBssids(Context context, ResultReceiver receiver) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_GET_BSSID_ALL);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getSsid(Context context, String bssid,
+			ResultReceiver receiver) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_GET_SSID_BSSID);
+		intent.putExtra(EXTRA_BSSID, bssid);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void deleteByDate(Context context, long time) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_CLEAR_DATE);
+		intent.putExtra(EXTRA_PRIMITIVE, time);
+		context.startService(intent);
+	}
+
+	public static void deleteByBssid(Context context, String bssid) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_CLEAR_BSSID);
+		intent.putExtra(EXTRA_BSSID, bssid);
+		context.startService(intent);
+	}
+
+	public static void deleteAll(Context context) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_CLEAR_ALL);
+		context.startService(intent);
+	}
+
+	private UglyDbHelper mDbHelper;
+
+	public Logger() {
+		super("Logger");
+	}
+
+	@Override
+	public void onCreate() {
+		super.onCreate();
+		mDbHelper = new UglyDbHelper(getApplicationContext());
+	}
+
+	@Override
+	protected void onHandleIntent(Intent intent) {
+		if (intent != null) {
+			final String action = intent.getAction();
+			if (ACTION_LOG.equals(action)) {
+				final Record record = intent.getParcelableExtra(EXTRA_RECORD);
+				handleActionLog(record);
+			} else if (ACTION_GET_RECORD_ALL.equals(action)) {
+				ResultReceiver receiver = intent
+						.getParcelableExtra(RESULT_RECEIVER);
+				ArrayList<Record> r = handleActionGetAllRecords();
+				Bundle result = new Bundle();
+				result.putParcelableArrayList("result", r);
+				receiver.send(0, result);
+			} else if (ACTION_GET_RECORD_EACH.equals(action)) {
+				final int lastUploadedAttackId = intent.getIntExtra(
+						EXTRA_PRIMITIVE, -1);
+				ResultReceiver receiver = intent
+						.getParcelableExtra(RESULT_RECEIVER);
+				ArrayList<Record> r = handleActionGetRecordOfEachAttack(lastUploadedAttackId);
+				Bundle result = new Bundle();
+				result.putParcelableArrayList("result", r);
+				receiver.send(0, result);
+			} else if (ACTION_GET_RECORD_ID.equals(action)) {
+				final int attack_id = intent.getIntExtra(EXTRA_PRIMITIVE, -1);
+				ResultReceiver receiver = intent
+						.getParcelableExtra(RESULT_RECEIVER);
+				Record r = handleActionGetRecordOfAttackId(attack_id);
+				Bundle result = new Bundle();
+				result.putParcelable("result", r);
+				receiver.send(0, result);
+			} else if (ACTION_GET_COUNT_ALL.equals(action)) {
+				ResultReceiver receiver = intent
+						.getParcelableExtra(RESULT_RECEIVER);
+				int r = handleActionGetAttackCount();
+				Bundle result = new Bundle();
+				result.putInt("result", r);
+				receiver.send(0, result);
+			} else if (ACTION_GET_COUNT_PROTOCOL.equals(action)) {
+				final String protocol = intent.getStringExtra(EXTRA_PROTOCOL);
+				ResultReceiver receiver = intent
+						.getParcelableExtra(RESULT_RECEIVER);
+				int r = handleActionGetAttackPerProtocolCount(protocol);
+				Bundle result = new Bundle();
+				result.putInt("result", r);
+				receiver.send(0, result);
+			} else if (ACTION_GET_ATTACK_MIN.equals(action)) {
+				ResultReceiver receiver = intent
+						.getParcelableExtra(RESULT_RECEIVER);
+				long r = handleActionGetMinAttackId();
+				Bundle result = new Bundle();
+				result.putLong("result", r);
+				receiver.send(0, result);
+				handleActionGetMinAttackId();
+			} else if (ACTION_GET_ATTACK_MAX.equals(action)) {
+				ResultReceiver receiver = intent
+						.getParcelableExtra(RESULT_RECEIVER);
+				long r = handleActionGetMaxAttackId();
+				Bundle result = new Bundle();
+				result.putLong("result", r);
+				receiver.send(0, result);
+			} else if (ACTION_IS_BSSID_SEEN.equals(action)) {
+				final String protocol = intent.getStringExtra(EXTRA_PROTOCOL);
+				final String bssid = intent.getStringExtra(EXTRA_BSSID);
+				ResultReceiver receiver = intent
+						.getParcelableExtra(RESULT_RECEIVER);
+				boolean r = handleActionBssidSeen(protocol, bssid);
+				Bundle result = new Bundle();
+				result.putBoolean("result", r);
+				receiver.send(0, result);
+			} else if (ACTION_GET_BSSID_ALL.equals(action)) {
+				ResultReceiver receiver = intent
+						.getParcelableExtra(RESULT_RECEIVER);
+				String[] r = handleActionGetAllBssids();
+				Bundle result = new Bundle();
+				result.putStringArray("result", r);
+				receiver.send(0, result);
+			} else if (ACTION_GET_SSID_BSSID.equals(action)) {
+				final String bssid = intent.getStringExtra(EXTRA_BSSID);
+				ResultReceiver receiver = intent
+						.getParcelableExtra(RESULT_RECEIVER);
+				String r = handleActionGetSsid(bssid);
+				Bundle result = new Bundle();
+				result.putString("result", r);
+				receiver.send(0, result);
+			} else if (ACTION_CLEAR_DATE.equals(action)) {
+				final long time = intent.getLongExtra(EXTRA_PRIMITIVE, -1L);
+				handleActionDeleteByDate(time);
+			} else if (ACTION_CLEAR_BSSID.equals(action)) {
+				final String bssid = intent.getStringExtra(EXTRA_BSSID);
+				handleActionDeleteByBssid(bssid);
+			} else if (ACTION_CLEAR_ALL.equals(action)) {
+				handleActionDeleteAll();
+			}
+		}
+	}
+
 	/**
 	/**
-	 * Deletes all Record which contain the given BSSID.
-	 * @param bssid The BSSID to compare with.
+	 * Log a record.
 	 */
 	 */
-	void deleteByBSSID(String bssid);
+	private void handleActionLog(Record record) {
+		mDbHelper.addRecord(record);
+	}
+
+	private ArrayList<Record> handleActionGetAllRecords() {
+		return mDbHelper.getAllRecords();
+	}
+
+	private ArrayList<Record> handleActionGetRecordOfEachAttack(
+			int lastUploadedAttackId) {
+		return mDbHelper.getRecordOfEachAttack(lastUploadedAttackId);
+	}
+
+	private Record handleActionGetRecordOfAttackId(long attack_id) {
+		return mDbHelper.getRecordOfAttackId(attack_id);
+	}
+
+	private int handleActionGetAttackCount() {
+		return mDbHelper.getAttackCount();
+	}
+
+	private int handleActionGetAttackPerProtocolCount(String protocol) {
+		return mDbHelper.getAttackPerProtocolCount(protocol);
+	}
+
+	private long handleActionGetMinAttackId() {
+		return mDbHelper.getSmallestAttackId();
+	}
+
+	private long handleActionGetMaxAttackId() {
+		return mDbHelper.getHighestAttackId();
+	}
+
+	private boolean handleActionBssidSeen(String protocol, String bssid) {
+		return mDbHelper.bssidSeen(protocol, bssid);
+	}
+
+	private String[] handleActionGetAllBssids() {
+		return mDbHelper.getAllBSSIDS();
+	}
+
+	private String handleActionGetSsid(String bssid) {
+		return mDbHelper.getSSID(bssid);
+	}
+
+	private void handleActionDeleteByDate(long time) {
+		mDbHelper.deleteByDate(time);
+	}
+
+	private void handleActionDeleteByBssid(String bssid) {
+		mDbHelper.deleteByBSSID(bssid);
+	}
+
 	/**
 	/**
-	 * Resets complete log file.
+	 * Delete all records.
 	 */
 	 */
-	void clearData();
+	private void handleActionDeleteAll() {
+		mDbHelper.clearData();
+	}
+
 }
 }

+ 162 - 183
src/de/tudarmstadt/informatik/hostage/logging/Record.java

@@ -1,311 +1,290 @@
 package de.tudarmstadt.informatik.hostage.logging;
 package de.tudarmstadt.informatik.hostage.logging;
 
 
-import java.io.Serializable;
-import java.net.InetAddress;
-
-import de.tudarmstadt.informatik.hostage.format.LogViewFormatter;
+import android.os.Parcel;
+import android.os.Parcelable;
+import de.tudarmstadt.informatik.hostage.logging.formatter.Formatter;
 
 
 /**
 /**
  * This class defines the attributes of a record.<br>
  * This class defines the attributes of a record.<br>
- * A Record is a single message exchanged between the application and an attacker.<br>
- * The class has no own functionality except for getter and setter methods.
- * To change the logging mechanism you have to to change the logger in {@link de.tudarmstadt.informatik.hostage.HoneyService HoneyService} and 
+ * A Record is a single message exchanged between the application and an
+ * attacker.<br>
+ * The class has no own functionality except for getter and setter methods. To
+ * change the logging mechanism you have to to change the logger in
+ * {@link de.tudarmstadt.informatik.hostage.HoneyService HoneyService} and
  * {@link de.tudarmstadt.informatik.hostage.ui.ViewLog ViewLog}
  * {@link de.tudarmstadt.informatik.hostage.ui.ViewLog ViewLog}
- * @author Mihai Plasoianu 
+ * 
+ * @author Mihai Plasoianu
  * @author Lars Pandikow
  * @author Lars Pandikow
  */
  */
-public class Record implements Serializable {
-
-	private static final long serialVersionUID = 1L;
+public class Record implements Parcelable {
 
 
 	public static enum TYPE {
 	public static enum TYPE {
 		SEND, RECEIVE
 		SEND, RECEIVE
 	};
 	};
 
 
+	// attack
 	private int id;
 	private int id;
 	private long attack_id;
 	private long attack_id;
+	private long timestamp;
 	private String protocol;
 	private String protocol;
 	private TYPE type;
 	private TYPE type;
-	private long timestamp;
-	private String externalIP;
-	private InetAddress localIP;
+	private String packet;
+
+	// network
+	private String localIP;
+	private String localHost;
 	private int localPort;
 	private int localPort;
-	private InetAddress remoteIP;
+	private String remoteIP;
+	private String remoteHost;
 	private int remotePort;
 	private int remotePort;
-	private String BSSID;
-	private String SSID;
+	private String externalIP;
+	private String bssid;
+	private String ssid;
+
+	// location
+	private long timestampLocation;
 	private double latitude;
 	private double latitude;
 	private double longitude;
 	private double longitude;
 	private float accuracy;
 	private float accuracy;
-	private long timestampLocation;
-	private String packet;	
 
 
+	@Override
+	public int describeContents() {
+		return 0;
+	}
+
+	@Override
+	public void writeToParcel(Parcel dest, int flags) {
+		// attack
+		dest.writeInt(id);
+		dest.writeLong(attack_id);
+		dest.writeLong(timestamp);
+		dest.writeString(protocol);
+		dest.writeString(type.name());
+		dest.writeString(packet);
+
+		// network
+		dest.writeString(localIP);
+		dest.writeString(localHost);
+		dest.writeInt(localPort);
+		dest.writeString(remoteIP);
+		dest.writeString(remoteHost);
+		dest.writeInt(remotePort);
+		dest.writeString(externalIP);
+		dest.writeString(bssid);
+		dest.writeString(ssid);
+
+		// location
+		dest.writeLong(timestampLocation);
+		dest.writeDouble(latitude);
+		dest.writeDouble(longitude);
+		dest.writeFloat(accuracy);
+	}
+
+	public static final Parcelable.Creator<Record> CREATOR = new Parcelable.Creator<Record>() {
+
+		@Override
+		public Record createFromParcel(Parcel source) {
+			return new Record(source);
+		}
 
 
+		@Override
+		public Record[] newArray(int size) {
+			return new Record[size];
+		}
+	};
+
+	public Record() {
+	}
+
+	public Record(Parcel source) {
+		// attack
+		this.id = source.readInt();
+		this.attack_id = source.readLong();
+		this.timestamp = source.readLong();
+		this.protocol = source.readString();
+		this.type = TYPE.valueOf(source.readString());
+		this.packet = source.readString();
+
+		// network
+		this.localIP = source.readString();
+		this.localHost = source.readString();
+		this.localPort = source.readInt();
+		this.remoteIP = source.readString();
+		this.remoteHost = source.readString();
+		this.remotePort = source.readInt();
+		this.externalIP = source.readString();
+		this.bssid = source.readString();
+		this.ssid = source.readString();
+
+		// location
+		this.timestampLocation = source.readLong();
+		this.latitude = source.readDouble();
+		this.longitude = source.readDouble();
+		this.accuracy = source.readFloat();
+	}
 
 
-	/**
-	 * @return the id
-	 */
 	public int getId() {
 	public int getId() {
 		return id;
 		return id;
 	}
 	}
 
 
-	/**
-	 * @param id the id to set
-	 */
 	public void setId(int id) {
 	public void setId(int id) {
 		this.id = id;
 		this.id = id;
 	}
 	}
 
 
-	/**
-	 * @return the attack_id
-	 */
 	public long getAttack_id() {
 	public long getAttack_id() {
 		return attack_id;
 		return attack_id;
 	}
 	}
 
 
-	/**
-	 * @param attack_id the attack_id to set
-	 */
 	public void setAttack_id(long attack_id) {
 	public void setAttack_id(long attack_id) {
 		this.attack_id = attack_id;
 		this.attack_id = attack_id;
 	}
 	}
 
 
-	/**
-	 * @return the protocol
-	 */
+	public long getTimestamp() {
+		return timestamp;
+	}
+
+	public void setTimestamp(long timestamp) {
+		this.timestamp = timestamp;
+	}
+
 	public String getProtocol() {
 	public String getProtocol() {
 		return protocol;
 		return protocol;
 	}
 	}
 
 
-	/**
-	 * @param protocol the protocol to set
-	 */
 	public void setProtocol(String protocol) {
 	public void setProtocol(String protocol) {
 		this.protocol = protocol;
 		this.protocol = protocol;
 	}
 	}
 
 
-	/**
-	 * @return the type
-	 */
 	public TYPE getType() {
 	public TYPE getType() {
 		return type;
 		return type;
 	}
 	}
 
 
-	/**
-	 * @param type the type to set
-	 */
 	public void setType(TYPE type) {
 	public void setType(TYPE type) {
 		this.type = type;
 		this.type = type;
 	}
 	}
 
 
-	/**
-	 * @return the timestamp
-	 */
-	public long getTimestamp() {
-		return timestamp;
+	public String getPacket() {
+		return packet;
 	}
 	}
 
 
-	/**
-	 * @param timestamp the timestamp to set
-	 */
-	public void setTimestamp(long timestamp) {
-		this.timestamp = timestamp;
+	public void setPacket(String packet) {
+		this.packet = packet;
 	}
 	}
 
 
-	/**
-	 * @return the externalIP
-	 */
-	public String getExternalIP() {
-		return externalIP;
+	public String getLocalIP() {
+		return localIP;
 	}
 	}
 
 
-	/**
-	 * @param externalIP the externalIP to set
-	 */
-	public void setExternalIP(String externalIP) {
-		this.externalIP = externalIP;
+	public void setLocalIP(String localIP) {
+		this.localIP = localIP;
 	}
 	}
 
 
-	/**
-	 * @return the localIP
-	 */
-	public InetAddress getLocalIP() {
-		return localIP;
+	public String getLocalHost() {
+		return localHost;
 	}
 	}
 
 
-	/**
-	 * @param localIP the localIP to set
-	 */
-	public void setLocalIP(InetAddress localIP) {
-		this.localIP = localIP;
+	public void setLocalHost(String localHost) {
+		this.localHost = localHost;
 	}
 	}
 
 
-	/**
-	 * @return the localPort
-	 */
 	public int getLocalPort() {
 	public int getLocalPort() {
 		return localPort;
 		return localPort;
 	}
 	}
 
 
-	/**
-	 * @param localPort the localPort to set
-	 */
 	public void setLocalPort(int localPort) {
 	public void setLocalPort(int localPort) {
 		this.localPort = localPort;
 		this.localPort = localPort;
 	}
 	}
 
 
-	/**
-	 * @return the remoteIP
-	 */
-	public InetAddress getRemoteIP() {
+	public String getRemoteIP() {
 		return remoteIP;
 		return remoteIP;
 	}
 	}
 
 
-	/**
-	 * @param remoteIP the remoteIP to set
-	 */
-	public void setRemoteIP(InetAddress remoteIP) {
+	public void setRemoteIP(String remoteIP) {
 		this.remoteIP = remoteIP;
 		this.remoteIP = remoteIP;
 	}
 	}
 
 
-	/**
-	 * @return the remotePort
-	 */
+	public String getRemoteHost() {
+		return remoteHost;
+	}
+
+	public void setRemoteHost(String remoteHost) {
+		this.remoteHost = remoteHost;
+	}
+
 	public int getRemotePort() {
 	public int getRemotePort() {
 		return remotePort;
 		return remotePort;
 	}
 	}
 
 
-	/**
-	 * @param remotePort the remotePort to set
-	 */
 	public void setRemotePort(int remotePort) {
 	public void setRemotePort(int remotePort) {
 		this.remotePort = remotePort;
 		this.remotePort = remotePort;
 	}
 	}
 
 
-	/**
-	 * @return the bSSID
-	 */
-	public String getBSSID() {
-		return BSSID;
+	public String getExternalIP() {
+		return externalIP;
+	}
+
+	public void setExternalIP(String externalIP) {
+		this.externalIP = externalIP;
+	}
+
+	public String getBssid() {
+		return bssid;
 	}
 	}
 
 
-	/**
-	 * @param bSSID the bSSID to set
-	 */
-	public void setBSSID(String bSSID) {
-		BSSID = bSSID;
+	public void setBssid(String bssid) {
+		this.bssid = bssid;
 	}
 	}
 
 
-	/**
-	 * @return the sSID
-	 */
-	public String getSSID() {
-		return SSID;
+	public String getSsid() {
+		return ssid;
 	}
 	}
 
 
-	/**
-	 * @param sSID the sSID to set
-	 */
-	public void setSSID(String sSID) {
-		SSID = sSID;
+	public void setSsid(String ssid) {
+		this.ssid = ssid;
+	}
+
+	public long getTimestampLocation() {
+		return timestampLocation;
+	}
+
+	public void setTimestampLocation(long timestampLocation) {
+		this.timestampLocation = timestampLocation;
 	}
 	}
 
 
-	/**
-	 * @return the latitude
-	 */
 	public double getLatitude() {
 	public double getLatitude() {
 		return latitude;
 		return latitude;
 	}
 	}
 
 
-	/**
-	 * @param latitude the latitude to set
-	 */
 	public void setLatitude(double latitude) {
 	public void setLatitude(double latitude) {
 		this.latitude = latitude;
 		this.latitude = latitude;
 	}
 	}
 
 
-	/**
-	 * @return the longitude
-	 */
 	public double getLongitude() {
 	public double getLongitude() {
 		return longitude;
 		return longitude;
 	}
 	}
 
 
-	/**
-	 * @param longitude the longitude to set
-	 */
 	public void setLongitude(double longitude) {
 	public void setLongitude(double longitude) {
 		this.longitude = longitude;
 		this.longitude = longitude;
 	}
 	}
 
 
-	/**
-	 * @return the accuracy
-	 */
 	public float getAccuracy() {
 	public float getAccuracy() {
 		return accuracy;
 		return accuracy;
 	}
 	}
 
 
-	/**
-	 * @param accuracy the accuracy to set
-	 */
 	public void setAccuracy(float accuracy) {
 	public void setAccuracy(float accuracy) {
 		this.accuracy = accuracy;
 		this.accuracy = accuracy;
 	}
 	}
 
 
-	/**
-	 * @return the timestampLocation
-	 */
-	public long getTimestampLocation() {
-		return timestampLocation;
-	}
-
-	/**
-	 * @param timestampLocation the timestampLocation to set
-	 */
-	public void setTimestampLocation(long timestampLocation) {
-		this.timestampLocation = timestampLocation;
-	}
-
-	/**
-	 * @return the packet
-	 */
-	public String getPacket() {
-		return packet;
-	}
-
-	/**
-	 * @param packet the packet to set
-	 */
-	public void setPacket(String packet) {
-		this.packet = packet;
-	}
-
 	@Override
 	@Override
 	public String toString() {
 	public String toString() {
-		return String.format("%d %s [%d,%s:%d,%s:%d,%s]", attack_id,
-				((type == TYPE.SEND) ? "SEND" : "RECEIVE"), timestamp,
-				localIP.getHostAddress(), localPort, remoteIP.getHostAddress(),
-				remotePort, LogViewFormatter.format(getProtocol(), getPacket()));
-	}
-	
-	/**
-	 * Returns a string representation after a chosen format. Formats should be defined in /res/values/arrays.xml to use with {@link de.tudarmstadt.informatik.hostage.ui.ViewLog#exportDatabase(android.view.View) exportDatabase(...)}
-	 * The Integer representation of the format is equal to its position in the format array.
-	 * @param format Integer representation of the format.
-	 * @return A string representation after chosen format.
-	 */
-	public String toString(int format){
-		// Choose String Format
-		switch (format){
-			// ViewLogTable format: contains all important information about an attack.
-			case 0: 
-				return String.format("%d: %s %s\nIn %s\n(%s)\nFrom [%s:%d]\nTo [%s:%d]\nLatitude: %f\nLongitude: %f\n%s\n\n", attack_id, protocol, ((type == TYPE.SEND) ? "SEND" : "RECEIVE"), SSID, BSSID, remoteIP.getHostAddress(), remotePort, localIP.getHostAddress(), localPort, getLatitude(), getLongitude(), LogViewFormatter.format(getProtocol(), getPacket()));	
-			// TraCINg Upload format, replaces internal ip's with external ip of network
-			case 1: 
-				return String.format("{ \"sensor\":{\"type\": \"Honeypot\", \"name\": \"HOsTaGe\"}, \"type\": \"%s\", \"src\":{\"ip\": \"%s\", \"port\": %d}, \"dst\":{\"ip\": \"%s\", \"port\": %d} }", protocol + " server access", externalIP, remotePort, externalIP, localPort);
-			default:
-				return toString();
+		return toString(null);
+	}
+
+	public String toString(Formatter formatter) {
+		if (null == formatter) {
+			return Formatter.getDefault().format(this);
 		}
 		}
+		return formatter.format(this);
 	}
 	}
-	
+
 }
 }

+ 0 - 89
src/de/tudarmstadt/informatik/hostage/logging/SQLLogger.java

@@ -1,89 +0,0 @@
-package de.tudarmstadt.informatik.hostage.logging;
-
-import java.util.ArrayList;
-
-import android.content.Context;
-/**
- * Implementation of the Logger interface using the {@link DatabaseHandler} to create a SQL database.
- * @author Lars Pandikow
- *
- */
-public class SQLLogger implements Logger{
-	Context context;
-	DatabaseHandler dbh;
-	
-	public SQLLogger(Context context){
-		this.context = context;
-		dbh = new DatabaseHandler(context);	
-	}
-
-	@Override
-	public synchronized void write(Record record) {
-		dbh.addRecord(record);
-	}
-
-	@Override
-	public ArrayList<Record> getAllRecords() {
-		return dbh.getAllRecords();
-	}
-
-	@Override
-	public ArrayList<Record> getRecordOfEachAttack(int lastUploadedAttackId) {
-		return dbh.getRecordOfEachAttack(lastUploadedAttackId);
-	}
-
-	@Override
-	public Record getRecordOfAttackId(long attack_id) {
-		return dbh.getRecordOfAttackId(attack_id);
-	}
-
-	@Override
-	public int getAttackCount() {
-		return dbh.getAttackCount();
-	}
-
-	@Override
-	public int getAttackPerProtokolCount(String protocol) {
-		return dbh.getAttackPerProtokolCount(protocol);
-	}
-
-	@Override
-	public long getSmallestAttackId() {
-		return dbh.getSmallestAttackId();
-	}
-
-	@Override
-	public long getHighestAttackId() {
-		return dbh.getHighestAttackId();
-	}
-
-	@Override
-	public boolean bssidSeen(String protocol, String bssid) {
-		return dbh.bssidSeen(protocol, bssid);
-	}
-
-	@Override
-	public String[] getAllBSSIDS() {
-		return dbh.getAllBSSIDS();
-	}
-
-	@Override
-	public String getSSID(String bssid) {
-		return dbh.getSSID(bssid);
-	}
-
-	@Override
-	public void deleteByDate(long time) {
-		dbh.deleteByDate(time);		
-	}
-
-	@Override
-	public void deleteByBSSID(String bssid) {
-		dbh.deleteByBSSID(bssid);
-	}
-
-	@Override
-	public void clearData() {
-		dbh.clearData();
-	}
-}

+ 694 - 0
src/de/tudarmstadt/informatik/hostage/logging/UglyDbHelper.java

@@ -0,0 +1,694 @@
+package de.tudarmstadt.informatik.hostage.logging;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+
+import android.content.ContentValues;
+import android.content.Context;
+import android.database.Cursor;
+import android.database.sqlite.SQLiteDatabase;
+import android.database.sqlite.SQLiteOpenHelper;
+import android.util.Log;
+import de.tudarmstadt.informatik.hostage.R;
+import de.tudarmstadt.informatik.hostage.logging.Record.TYPE;
+import de.tudarmstadt.informatik.hostage.protocol.Protocol;
+
+/**
+ * This class creates SQL tables and handles all access to the database.<br>
+ * It contains several methods with predefined queries to extract different
+ * kinds of information from the database.<br>
+ * The database contains two tables: {@link #TABLE_RECORDS} and
+ * {@link #TABLE_BSSIDS}:<br>
+ * {@link #TABLE_RECORDS} contains all logging information of a single message
+ * record except the SSID.<br>
+ * {@link #TABLE_BSSIDS} contains the BSSID of all recorded Networks and the
+ * corresponding SSID.<br>
+ * 
+ * @author Lars Pandikow
+ */
+public class UglyDbHelper extends SQLiteOpenHelper {
+
+	// All Static variables
+	// Database Version
+	private static final int DATABASE_VERSION = 1;
+
+	// Database Name
+	private static final String DATABASE_NAME = "recordManager";
+
+	// Contacts table names
+	private static final String TABLE_ATTACK_INFO = "attack_info";
+	private static final String TABLE_RECORDS = "records";
+	private static final String TABLE_BSSIDS = "bssids";
+	private static final String TABLE_PORTS = "ports";
+
+	// Contacts Table Columns names
+	public static final String KEY_ID = "_id";
+	public static final String KEY_ATTACK_ID = "_attack_id";
+	public static final String KEY_TYPE = "type";
+	public static final String KEY_TIME = "timestamp";
+	public static final String KEY_PACKET = "packet";
+	public static final String KEY_PROTOCOL = "protocol";
+	public static final String KEY_EXTERNAL_IP = "externalIP";
+	public static final String KEY_LOCAL_IP = "localIP";
+	public static final String KEY_LOCAL_HOSTNAME = "localHostName";
+	public static final String KEY_LOCAL_PORT = "localPort";
+	public static final String KEY_REMOTE_IP = "remoteIP";
+	public static final String KEY_REMOTE_HOSTNAME = "remoteHostName";
+	public static final String KEY_REMOTE_PORT = "remotePort";
+	public static final String KEY_BSSID = "_bssid";
+	public static final String KEY_SSID = "ssid";
+	public static final String KEY_LATITUDE = "latitude";
+	public static final String KEY_LONGITUDE = "longitude";
+	public static final String KEY_ACCURACY = "accuracy";
+
+	// Database sql create statements
+	private static final String CREATE_RECORD_TABLE = "CREATE TABLE "
+			+ TABLE_RECORDS + "(" + KEY_ID + " INTEGER NOT NULL,"
+			+ KEY_ATTACK_ID + " INTEGER NOT NULL," + KEY_TYPE + " TEXT,"
+			+ KEY_TIME + " INTEGER," + KEY_PACKET + " TEXT," + "FOREIGN KEY("
+			+ KEY_ATTACK_ID + ") REFERENCES " + TABLE_ATTACK_INFO + "("
+			+ KEY_ATTACK_ID + ")" + "PRIMARY KEY(" + KEY_ID + ", "
+			+ KEY_ATTACK_ID + ")" + ")";
+
+	private static final String CREATE_ATTACK_INFO_TABLE = "CREATE TABLE "
+			+ TABLE_ATTACK_INFO + "(" + KEY_ATTACK_ID + " INTEGER PRIMARY KEY,"
+			+ KEY_PROTOCOL + " TEXT," + KEY_EXTERNAL_IP + " TEXT,"
+			+ KEY_LOCAL_IP + " BLOB," + KEY_LOCAL_HOSTNAME + " TEXT,"
+			+ KEY_REMOTE_IP + " BLOB," + KEY_REMOTE_HOSTNAME + " TEXT,"
+			+ KEY_REMOTE_PORT + " INTEGER," + KEY_BSSID + " TEXT,"
+			+ "FOREIGN KEY(" + KEY_BSSID + ") REFERENCES " + TABLE_BSSIDS + "("
+			+ KEY_BSSID + ")" + "FOREIGN KEY(" + KEY_PROTOCOL + ") REFERENCES "
+			+ TABLE_PORTS + "(" + KEY_PROTOCOL + ")" + ")";
+
+	private static final String CREATE_BSSID_TABLE = "CREATE TABLE "
+			+ TABLE_BSSIDS + "(" + KEY_BSSID + " TEXT PRIMARY KEY," + KEY_SSID
+			+ " TEXT," + KEY_LATITUDE + " INTEGER," + KEY_LONGITUDE
+			+ " INTEGER," + KEY_ACCURACY + " INTEGER," + KEY_TIME + " INTEGER"
+			+ ")";
+
+	private static final String CREATE_PORT_TABLE = "CREATE TABLE "
+			+ TABLE_PORTS + "(" + KEY_PROTOCOL + " TEXT PRIMARY KEY,"
+			+ KEY_LOCAL_PORT + " INTEGER" + ")";
+
+	private Context context;
+
+	public UglyDbHelper(Context context) {
+		super(context, DATABASE_NAME, null, DATABASE_VERSION);
+		this.context = context;
+	}
+
+	// Creating Tables
+	@Override
+	public void onCreate(SQLiteDatabase db) {
+		db.execSQL(CREATE_PORT_TABLE);
+		db.execSQL(CREATE_BSSID_TABLE);
+		db.execSQL(CREATE_ATTACK_INFO_TABLE);
+		db.execSQL(CREATE_RECORD_TABLE);
+
+		String[] protocols = context.getResources().getStringArray(
+				R.array.protocols);
+		String packageName = Protocol.class.getPackage().getName();
+
+		// Initialize Port Table
+		for (String protocol : protocols) {
+			try {
+				int port = ((Protocol) Class.forName(
+						String.format("%s.%s", packageName, protocol))
+						.newInstance()).getPort();
+				db.execSQL("INSERT INTO " + TABLE_PORTS + " VALUES ( '"
+						+ protocol + "'," + port + ")");
+			} catch (Exception e) {
+				e.printStackTrace();
+			}
+		}
+	}
+
+	// Upgrading database
+	@Override
+	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
+		// Drop older table if existed
+		db.execSQL("DROP TABLE IF EXISTS " + TABLE_RECORDS);
+		db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTACK_INFO);
+		db.execSQL("DROP TABLE IF EXISTS " + TABLE_BSSIDS);
+		db.execSQL("DROP TABLE IF EXISTS " + TABLE_PORTS);
+
+		// Create tables again
+		onCreate(db);
+	}
+
+	/**
+	 * Adds a given {@link Record} to the database.
+	 * 
+	 * @param record
+	 *            The added {@link Record} .
+	 */
+	public void addRecord(Record record) {
+		SQLiteDatabase db = this.getWritableDatabase();
+
+		HashMap<String, Object> bssidValues = new HashMap<String, Object>();
+		bssidValues.put(KEY_BSSID, record.getBssid());
+		bssidValues.put(KEY_SSID, record.getSsid());
+		bssidValues.put(KEY_LATITUDE, record.getLatitude());
+		bssidValues.put(KEY_LONGITUDE, record.getLongitude());
+		bssidValues.put(KEY_ACCURACY, record.getAccuracy());
+		bssidValues.put(KEY_TIME, record.getTimestampLocation());
+
+		ContentValues attackValues = new ContentValues();
+		attackValues.put(KEY_ATTACK_ID, record.getAttack_id()); // Log Attack ID
+		attackValues.put(KEY_PROTOCOL, record.getProtocol().toString());
+		attackValues.put(KEY_EXTERNAL_IP, record.getExternalIP());
+		attackValues.put(KEY_LOCAL_IP, record.getLocalIP()); // Log Local IP
+		attackValues.put(KEY_LOCAL_HOSTNAME, record.getLocalHost());
+		attackValues.put(KEY_REMOTE_IP, record.getRemoteIP()); // Log Remote IP
+		attackValues.put(KEY_REMOTE_HOSTNAME, record.getRemoteHost());
+		attackValues.put(KEY_REMOTE_PORT, record.getRemotePort()); // Log Remote
+																	// Port
+		attackValues.put(KEY_BSSID, record.getBssid());
+
+		ContentValues recordValues = new ContentValues();
+		recordValues.put(KEY_ID, record.getId()); // Log Message Number
+		recordValues.put(KEY_ATTACK_ID, record.getAttack_id()); // Log Attack ID
+		recordValues.put(KEY_TYPE, record.getType().name()); // Log Type
+		recordValues.put(KEY_TIME, record.getTimestamp()); // Log Timestamp
+		recordValues.put(KEY_PACKET, record.getPacket()); // Log Packet
+
+		// Inserting Rows
+		db.insertWithOnConflict(TABLE_ATTACK_INFO, null, attackValues,
+				SQLiteDatabase.CONFLICT_REPLACE);
+		db.insert(TABLE_RECORDS, null, recordValues);
+		db.close(); // Closing database connection
+		// Update Network Information
+		updateNetworkInformation(bssidValues);
+	}
+
+	/**
+	 * Creates a {@link Record} from a Cursor. If the cursor does not show to a
+	 * valid data structure a runtime exception is thrown.
+	 * 
+	 * @param cursor
+	 * @return Returns the created {@link Record} .
+	 */
+	private Record createRecord(Cursor cursor) {
+		Record record = new Record();
+		record.setId(Integer.parseInt(cursor.getString(0)));
+		record.setAttack_id(cursor.getLong(1));
+		record.setType(cursor.getString(2).equals("SEND") ? TYPE.SEND
+				: TYPE.RECEIVE);
+		record.setTimestamp(cursor.getLong(3));
+		record.setPacket(cursor.getString(4));
+		record.setProtocol(cursor.getString(5));
+		record.setExternalIP(cursor.getString(6));
+		record.setLocalIP(cursor.getString(7));
+		record.setRemoteIP(cursor.getString(9));
+		record.setRemotePort(Integer.parseInt(cursor.getString(11)));
+		record.setBssid(cursor.getString(12));
+		record.setSsid(cursor.getString(13));
+		record.setLatitude(Double.parseDouble(cursor.getString(14)));
+		record.setLongitude(Double.parseDouble(cursor.getString(15)));
+		record.setAccuracy(Float.parseFloat(cursor.getString(16)));
+		record.setTimestampLocation(cursor.getLong(17));
+		record.setLocalPort(Integer.parseInt(cursor.getString(18)));
+		return record;
+	}
+
+	/**
+	 * Gets a single {@link Record} with the given ID from the database.
+	 * 
+	 * @param id
+	 *            The ID of the {@link Record};
+	 * @return The {@link Record}.
+	 */
+	public Record getRecord(int id) {
+		String selectQuery = "SELECT  * FROM " + TABLE_RECORDS
+				+ " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN "
+				+ TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS + " WHERE "
+				+ KEY_ID + " = " + id;
+		SQLiteDatabase db = this.getReadableDatabase();
+
+		Cursor cursor = db.rawQuery(selectQuery, null);
+		Record record = null;
+		if (cursor.moveToFirst()) {
+			record = createRecord(cursor);
+		}
+
+		cursor.close();
+		db.close();
+		// return contact
+		return record;
+	}
+
+	/**
+	 * Gets all {@link Record Records} saved in the database.
+	 * 
+	 * @return A ArrayList of all the {@link Record Records} in the Database.
+	 */
+	public ArrayList<Record> getAllRecords() {
+		ArrayList<Record> recordList = new ArrayList<Record>();
+		// Select All Query
+		String selectQuery = "SELECT  * FROM " + TABLE_RECORDS
+				+ " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN "
+				+ TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS;
+
+		SQLiteDatabase db = this.getWritableDatabase();
+		Cursor cursor = db.rawQuery(selectQuery, null);
+
+		Log.i("Database", "Start loop");
+		// looping through all rows and adding to list
+		if (cursor.moveToFirst()) {
+			do {
+				Log.i("Database", "Add Record");
+				Record record = createRecord(cursor);
+				// Adding record to list
+				recordList.add(record);
+			} while (cursor.moveToNext());
+		}
+		cursor.close();
+		db.close();
+		// return record list
+		return recordList;
+	}
+
+	/**
+	 * Gets a single {@link Record} with the given attack id from the database.
+	 * 
+	 * @param attack_id
+	 *            The attack id of the {@link Record};
+	 * @return The {@link Record}.
+	 */
+	public Record getRecordOfAttackId(long attack_id) {
+		String selectQuery = "SELECT  * FROM " + TABLE_RECORDS
+				+ " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN "
+				+ TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS + " WHERE "
+				+ KEY_ATTACK_ID + " = " + attack_id + " GROUP BY "
+				+ KEY_ATTACK_ID;
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(selectQuery, null);
+		Record record = null;
+
+		if (cursor.moveToFirst()) {
+			record = createRecord(cursor);
+		}
+		cursor.close();
+
+		// return record list
+		db.close();
+		return record;
+	}
+
+	/**
+	 * Gets all received {@link Record Records} for every attack identified by
+	 * its attack id and ordered by date.
+	 * 
+	 * @return A ArrayList with all received {@link Record Records} for each
+	 *         attack id in the Database.
+	 */
+	public ArrayList<Record> getAllReceivedRecordsOfEachAttack() {
+		ArrayList<Record> recordList = new ArrayList<Record>();
+		String selectQuery = "SELECT  * FROM " + TABLE_RECORDS
+				+ " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN "
+				+ TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS + " WHERE "
+				+ KEY_TYPE + "='RECEIVE'" + " ORDER BY " + KEY_TIME;
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(selectQuery, null);
+
+		// looping through all rows and adding to list
+		if (cursor.moveToFirst()) {
+			do {
+				Record record = createRecord(cursor);
+				// Adding record to list
+				recordList.add(record);
+			} while (cursor.moveToNext());
+		}
+		cursor.close();
+
+		// return record list
+		db.close();
+		return recordList;
+	}
+
+	/**
+	 * Gets a representative {@link Record} for every attack identified by its
+	 * attack id.
+	 * 
+	 * @return A ArrayList with one {@link Record Records} for each attack id in
+	 *         the Database.
+	 */
+	public ArrayList<Record> getRecordOfEachAttack() {
+		ArrayList<Record> recordList = new ArrayList<Record>();
+		String selectQuery = "SELECT  * FROM " + TABLE_RECORDS
+				+ " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN "
+				+ TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS + " GROUP BY "
+				+ KEY_ATTACK_ID;
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(selectQuery, null);
+
+		// looping through all rows and adding to list
+		if (cursor.moveToFirst()) {
+			do {
+				Record record = createRecord(cursor);
+				// Adding record to list
+				recordList.add(record);
+			} while (cursor.moveToNext());
+		}
+		cursor.close();
+
+		// return record list
+		db.close();
+		return recordList;
+	}
+
+	/**
+	 * Gets a representative {@link Record} for every attack with a higher
+	 * attack id than the specified.
+	 * 
+	 * @param attack_id
+	 *            The attack id to match the query against.
+	 * @return A ArrayList with one {@link Record Records} for each attack id
+	 *         higher than the given.
+	 */
+	public ArrayList<Record> getRecordOfEachAttack(long attack_id) {
+		ArrayList<Record> recordList = new ArrayList<Record>();
+		String selectQuery = "SELECT  * FROM " + TABLE_RECORDS
+				+ " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN "
+				+ TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS + " WHERE "
+				+ KEY_ATTACK_ID + " > " + attack_id + " GROUP BY "
+				+ KEY_ATTACK_ID;
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(selectQuery, null);
+
+		// looping through all rows and adding to list
+		if (cursor.moveToFirst()) {
+			do {
+				Record record = createRecord(cursor);
+				// Adding record to list
+				recordList.add(record);
+			} while (cursor.moveToNext());
+		}
+		cursor.close();
+
+		// return count
+		db.close();
+		return recordList;
+	}
+
+	/**
+	 * Determines the number of {@link Record Records} in the database.
+	 * 
+	 * @return The number of {@link Record Records} in the database.
+	 */
+	public int getRecordCount() {
+		String countQuery = "SELECT  * FROM " + TABLE_RECORDS;
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(countQuery, null);
+		int result = cursor.getCount();
+		cursor.close();
+
+		// return count
+		db.close();
+		return result;
+	}
+
+	/**
+	 * Determines the number of different attack_ids in the database.
+	 * 
+	 * @return The number of different attack_ids in the database.
+	 */
+	public int getAttackCount() {
+		String countQuery = "SELECT  * FROM " + TABLE_ATTACK_INFO;
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(countQuery, null);
+		int result = cursor.getCount();
+		cursor.close();
+
+		// return count
+		db.close();
+		return result;
+	}
+
+	/**
+	 * Determines the number of different attack_ids for a specific protocol in
+	 * the database.
+	 * 
+	 * @param protocol
+	 *            The String representation of the
+	 *            {@link de.tudarmstadt.informatik.hostage.protocol.Protocol
+	 *            Protocol}
+	 * @return The number of different attack_ids in the database.
+	 */
+	public int getAttackPerProtocolCount(String protocol) {
+		String countQuery = "SELECT  * FROM " + TABLE_ATTACK_INFO + " WHERE "
+				+ KEY_PROTOCOL + " = " + "'" + protocol + "'";
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(countQuery, null);
+		int result = cursor.getCount();
+		cursor.close();
+
+		// return count
+		db.close();
+		return result;
+	}
+
+	/**
+	 * Determines the smallest attack id stored in the database.
+	 * 
+	 * @return The smallest attack id stored in the database.
+	 */
+	public long getSmallestAttackId() {
+		String selectQuery = "SELECT MIN(" + KEY_ATTACK_ID + ") FROM "
+				+ TABLE_ATTACK_INFO;
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(selectQuery, null);
+		int result;
+
+		if (cursor.moveToFirst()) {
+			result = cursor.getInt(0);
+		} else {
+			result = -1;
+		}
+		cursor.close();
+		db.close();
+		return result;
+	}
+
+	/**
+	 * Determines the highest attack id stored in the database.
+	 * 
+	 * @return The highest attack id stored in the database.
+	 */
+	public long getHighestAttackId() {
+		String selectQuery = "SELECT MAX(" + KEY_ATTACK_ID + ") FROM "
+				+ TABLE_ATTACK_INFO;
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(selectQuery, null);
+		int result;
+
+		if (cursor.moveToFirst()) {
+			result = cursor.getInt(0);
+		} else {
+			result = -1;
+		}
+		cursor.close();
+		db.close();
+		return result;
+	}
+
+	/**
+	 * Determines if a network with given BSSID has already been recorded as
+	 * malicious.
+	 * 
+	 * @param BSSID
+	 *            The BSSID of the network.
+	 * @return True if an attack has been recorded in a network with the given
+	 *         BSSID, else false.
+	 */
+	public boolean bssidSeen(String BSSID) {
+		String countQuery = "SELECT  * FROM " + TABLE_BSSIDS + " WHERE "
+				+ KEY_BSSID + " = " + "'" + BSSID + "'";
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(countQuery, null);
+		int result = cursor.getCount();
+		cursor.close();
+		db.close();
+		return result > 0;
+	}
+
+	/**
+	 * Determines if an attack has been recorded on a specific protocol in a
+	 * network with a given BSSID.
+	 * 
+	 * @param protocol
+	 *            The
+	 *            {@link de.tudarmstadt.informatik.hostage.protocol.Protocol
+	 *            Protocol} to inspect.
+	 * @param BSSID
+	 *            The BSSID of the network.
+	 * @return True if an attack on the given protocol has been recorded in a
+	 *         network with the given BSSID, else false.
+	 */
+	public boolean bssidSeen(String protocol, String BSSID) {
+		String countQuery = "SELECT  * FROM " + TABLE_ATTACK_INFO
+				+ " NATURAL JOIN " + TABLE_BSSIDS + " WHERE " + KEY_PROTOCOL
+				+ " = " + "'" + protocol + "'" + " AND " + KEY_BSSID + " = "
+				+ "'" + BSSID + "'";
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(countQuery, null);
+		int result = cursor.getCount();
+		cursor.close();
+		db.close();
+		return result > 0;
+	}
+
+	/**
+	 * Returns a String array with all BSSIDs stored in the database.
+	 * 
+	 * @return String[] of all recorded BSSIDs.
+	 */
+	public String[] getAllBSSIDS() {
+		String selectQuery = "SELECT  * FROM " + TABLE_BSSIDS;
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(selectQuery, null);
+		String[] bssidList = new String[cursor.getCount()];
+		int counter = 0;
+		// looping through all rows and adding to list
+		if (cursor.moveToFirst()) {
+			do {
+				bssidList[counter] = cursor.getString(0);
+				counter++;
+			} while (cursor.moveToNext());
+		}
+		cursor.close();
+		db.close();
+		return bssidList;
+	}
+
+	/**
+	 * Gets the last recorded SSID to a given BSSID.
+	 * 
+	 * @param bssid
+	 *            The BSSID to match against.
+	 * @return A String of the last SSID or null if the BSSID is not in the
+	 *         database.
+	 */
+	public String getSSID(String bssid) {
+		String selectQuery = "SELECT " + KEY_SSID + " FROM " + TABLE_BSSIDS
+				+ " WHERE " + KEY_BSSID + " = " + "'" + bssid + "'";
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(selectQuery, null);
+		String ssid = null;
+		if (cursor.moveToFirst()) {
+			ssid = cursor.getString(0);
+		}
+		cursor.close();
+		db.close();
+		return ssid;
+	}
+
+	/**
+	 * Deletes all records from {@link #TABLE_RECORDS} with a specific BSSID.
+	 * 
+	 * @param bssid
+	 *            The BSSID to match against.
+	 */
+	public void deleteByBSSID(String bssid) {
+		SQLiteDatabase db = this.getReadableDatabase();
+		db.delete(TABLE_RECORDS, KEY_BSSID + " = ?", new String[] { bssid });
+		db.delete(TABLE_ATTACK_INFO, KEY_BSSID + " = ?", new String[] { bssid });
+		db.close();
+	}
+
+	// TODO Delete statement �berarbeiten
+	/**
+	 * Deletes all records from {@link #TABLE_RECORDS} with a time stamp smaller
+	 * then the given
+	 * 
+	 * @param date
+	 *            A Date represented in milliseconds.
+	 */
+	public void deleteByDate(long date) {
+		SQLiteDatabase db = this.getReadableDatabase();
+		String deleteQuery = "DELETE  FROM " + TABLE_RECORDS + " WHERE "
+				+ KEY_TIME + " < " + date;
+		// TODO Delete statement �berarbeiten
+		// String deleteQuery2 = "DELETE "
+		db.execSQL(deleteQuery);
+		db.close();
+	}
+
+	/**
+	 * Deletes all records from {@link #TABLE_RECORDS}.
+	 */
+	public void clearData() {
+		SQLiteDatabase db = this.getReadableDatabase();
+		db.delete(TABLE_RECORDS, null, null);
+		db.delete(TABLE_ATTACK_INFO, null, null);
+		db.close();
+	}
+
+	public ArrayList<HashMap<String, Object>> getNetworkInformation() {
+		String selectQuery = "SELECT  * FROM " + TABLE_BSSIDS;
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(selectQuery, null);
+
+		ArrayList<HashMap<String, Object>> networkInformation = new ArrayList<HashMap<String, Object>>();
+
+		// looping through all rows and adding to list
+		if (cursor.moveToFirst()) {
+			do {
+				HashMap<String, Object> values = new HashMap<String, Object>();
+				values.put(KEY_BSSID, cursor.getString(0));
+				values.put(KEY_SSID, cursor.getString(1));
+				values.put(KEY_LATITUDE,
+						Double.parseDouble(cursor.getString(2)));
+				values.put(KEY_LONGITUDE,
+						Double.parseDouble(cursor.getString(3)));
+				values.put(KEY_ACCURACY, Float.parseFloat(cursor.getString(4)));
+				values.put(KEY_TIME, cursor.getLong(5));
+				networkInformation.add(values);
+			} while (cursor.moveToNext());
+		}
+
+		cursor.close();
+		db.close();
+		return networkInformation;
+	}
+
+	public void updateNetworkInformation(
+			HashMap<String, Object> networkInformation) {
+		SQLiteDatabase db = this.getReadableDatabase();
+		String bssid = (String) networkInformation.get(KEY_BSSID);
+		String bssidQuery = "SELECT  * FROM " + TABLE_BSSIDS + " WHERE "
+				+ KEY_BSSID + " = " + "'" + bssid + "'";
+		Cursor cursor = db.rawQuery(bssidQuery, null);
+		int result = cursor.getCount();
+		if (cursor != null
+				&& cursor.moveToFirst()
+				&& (result <= 0 || cursor.getLong(5) < (Long) networkInformation
+						.get(KEY_TIME)))
+			;
+		{
+			ContentValues bssidValues = new ContentValues();
+			bssidValues.put(KEY_BSSID, bssid);
+			bssidValues
+					.put(KEY_SSID, (String) networkInformation.get(KEY_SSID));
+			bssidValues.put(KEY_LATITUDE,
+					(double) (Double) networkInformation.get(KEY_LATITUDE));
+			bssidValues.put(KEY_LONGITUDE,
+					(double) (Double) networkInformation.get(KEY_LONGITUDE));
+			bssidValues.put(KEY_ACCURACY,
+					(float) (Float) networkInformation.get(KEY_ACCURACY));
+			bssidValues.put(KEY_TIME, (Long) networkInformation.get(KEY_TIME));
+			db.insertWithOnConflict(TABLE_BSSIDS, null, bssidValues,
+					SQLiteDatabase.CONFLICT_REPLACE);
+		}
+		cursor.close();
+		db.close();
+	}
+
+	public void updateNetworkInformation(
+			ArrayList<HashMap<String, Object>> networkInformation) {
+		Log.i("DatabaseHandler", "Starte updating");
+		for (HashMap<String, Object> values : networkInformation) {
+			updateNetworkInformation(values);
+		}
+	}
+}

+ 28 - 0
src/de/tudarmstadt/informatik/hostage/logging/formatter/DefaultFormatter.java

@@ -0,0 +1,28 @@
+package de.tudarmstadt.informatik.hostage.logging.formatter;
+
+import de.tudarmstadt.informatik.hostage.logging.Record;
+import de.tudarmstadt.informatik.hostage.logging.formatter.protocol.ProtocolFormatter;
+
+public class DefaultFormatter extends Formatter {
+
+	private static DefaultFormatter INSTANCE = new DefaultFormatter();
+
+	private DefaultFormatter() {
+	}
+
+	public static DefaultFormatter getInstance() {
+		return INSTANCE;
+	}
+
+	@Override
+	public synchronized String format(Record record) {
+		ProtocolFormatter formatter = ProtocolFormatter.getFormatter(record
+				.getProtocol());
+		return String.format("%d %s [%d,%s:%d,%s:%d,%s]",
+				record.getAttack_id(), record.getType().name(),
+				record.getTimestamp(), record.getLocalIP(),
+				record.getLocalPort(), record.getRemoteIP(),
+				record.getRemotePort(), formatter.format(record.getPacket()));
+	}
+
+}

+ 23 - 0
src/de/tudarmstadt/informatik/hostage/logging/formatter/Formatter.java

@@ -0,0 +1,23 @@
+package de.tudarmstadt.informatik.hostage.logging.formatter;
+
+import de.tudarmstadt.informatik.hostage.logging.Record;
+
+public abstract class Formatter {
+
+	/**
+	 * @return Instance of DefaultFormatter.
+	 */
+	public static Formatter getDefault() {
+		return DefaultFormatter.getInstance();
+	}
+
+	/**
+	 * Formats a record.
+	 * 
+	 * @param record
+	 *            Record to format.
+	 * @return Formatted human-readable String.
+	 */
+	abstract public String format(Record record);
+
+}

+ 25 - 0
src/de/tudarmstadt/informatik/hostage/logging/formatter/TraCINgFormatter.java

@@ -0,0 +1,25 @@
+package de.tudarmstadt.informatik.hostage.logging.formatter;
+
+import de.tudarmstadt.informatik.hostage.logging.Record;
+
+public class TraCINgFormatter extends Formatter {
+
+	private static TraCINgFormatter INSTANCE = new TraCINgFormatter();
+
+	private TraCINgFormatter() {
+	}
+
+	public static TraCINgFormatter getInstance() {
+		return INSTANCE;
+	}
+
+	@Override
+	public synchronized String format(Record record) {
+		return String
+				.format("{ \"sensor\":{\"type\": \"Honeypot\", \"name\": \"HosTaGe\"}, \"type\": \"%s server access\", \"src\":{\"ip\": \"%s\", \"port\": %d}, \"dst\":{\"ip\": \"%s\", \"port\": %d} }",
+						record.getProtocol(), record.getRemoteIP(),
+						record.getRemotePort(), record.getExternalIP(),
+						record.getLocalPort());
+	}
+
+}

+ 103 - 0
src/de/tudarmstadt/informatik/hostage/logging/formatter/protocol/MySQL.java

@@ -0,0 +1,103 @@
+package de.tudarmstadt.informatik.hostage.logging.formatter.protocol;
+
+import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
+
+/**
+ * MySQL log view formatter.
+ * 
+ * @author Wulf Pfeiffer
+ */
+public class MySQL extends ProtocolFormatter {
+
+	@Override
+	public String format(String packet) {
+		byte[] bytes = HelperUtils.hexStringToBytes(packet);
+		String command = "Command: " + getCommand(bytes) + "\n";
+		String content = "Content: " + HelperUtils.byteToStr(bytes) + "\n";
+		return command + content;
+	}
+
+	/**
+	 * Checks a packet for its command code and returns the name of this
+	 * command.
+	 * 
+	 * @param bytes
+	 *            to check.
+	 * @return name of the command.
+	 */
+	private String getCommand(byte[] bytes) {
+		// if packet number is 1 server started conversation so it must be login
+		if (bytes.length < 5)
+			return "";
+		if (bytes[3] == 0x01)
+			return "Login request";
+		// else check for command code
+		switch (bytes[4]) {
+		case 0x00:
+			return "COM_SLEEP";
+		case 0x01:
+			return "COM_QUIT";
+		case 0x02:
+			return "COM_INIT_DB";
+		case 0x03:
+			return "COM_QUERY";
+		case 0x04:
+			return "COM_FIELD_LIST";
+		case 0x05:
+			return "COM_CREATE_DB";
+		case 0x06:
+			return "COM_DROP_DB";
+		case 0x07:
+			return "COM_REFRESH";
+		case 0x08:
+			return "COM_SHUTDOWN";
+		case 0x09:
+			return "COM_STATISTICS";
+		case 0x0a:
+			return "COM_PROCESS_INFO";
+		case 0x0b:
+			return "COM_CONNECT";
+		case 0x0c:
+			return "COM_PROCESS_KILL";
+		case 0x0d:
+			return "COM_DEBUG";
+		case 0x0e:
+			return "COM_PING";
+		case 0x0f:
+			return "COM_TIME";
+		case 0x10:
+			return "COM_DELAYED_INSERT";
+		case 0x11:
+			return "COM_CHANGE_USER";
+		case 0x12:
+			return "COM_BINLOG_DUMP";
+		case 0x13:
+			return "COM_TABLE_DUMP";
+		case 0x14:
+			return "COM_CONNECT_OUT";
+		case 0x15:
+			return "COM_REGISTER_SLAVE";
+		case 0x16:
+			return "COM_STMT_PREPARE";
+		case 0x17:
+			return "COM_STMT_EXECUTE";
+		case 0x18:
+			return "COM_STMT_SEND_LONG_DATA";
+		case 0x19:
+			return "COM_STMT_CLOSE";
+		case 0x1a:
+			return "COM_STMT_RESET";
+		case 0x1b:
+			return "COM_SET_OPTION";
+		case 0x1c:
+			return "COM_STMT_FETCH";
+		case 0x1d:
+			return "COM_DAEMON";
+		case 0x1e:
+			return "COM_BINLOG_DUMP_GTID";
+		default:
+			return "unkown command";
+		}
+	}
+
+}

+ 45 - 0
src/de/tudarmstadt/informatik/hostage/logging/formatter/protocol/ProtocolFormatter.java

@@ -0,0 +1,45 @@
+package de.tudarmstadt.informatik.hostage.logging.formatter.protocol;
+
+/**
+ * Protocol formatter. This class provides functionality to format the packet as
+ * a human-readable string of a specific protocol. Custom formatters should
+ * inherit from this class.
+ * 
+ * @author Wulf Pfeiffer
+ * @author Mihai Plasoianu
+ */
+public class ProtocolFormatter {
+
+	/**
+	 * Formats the content of packet. The packet content is represented as
+	 * string or hex, depending on the protocol.
+	 * 
+	 * @param packet
+	 *            Packet to format.
+	 * @return Formatted string.
+	 */
+	public String format(String packet) {
+		return packet;
+	}
+
+	/**
+	 * Loads a protocol formatter for a protocol. Load a class matching
+	 * {protocol} located in logging.formatter.protocol, default formatter
+	 * otherwise.
+	 * 
+	 * @param protocolName
+	 *            String representation of a protocol.
+	 * @return The protocol formatter.
+	 */
+	public static ProtocolFormatter getFormatter(String protocolName) {
+		String packageName = ProtocolFormatter.class.getPackage().getName();
+		String className = String.format("%s.%s", packageName, protocolName);
+		// TODO Auf Singletons umstellen und newInstance() sparen.
+		try {
+			return (ProtocolFormatter) Class.forName(className).newInstance();
+		} catch (ReflectiveOperationException e) {
+			return new ProtocolFormatter();
+		}
+	}
+
+}

+ 225 - 0
src/de/tudarmstadt/informatik/hostage/logging/formatter/protocol/SMB.java

@@ -0,0 +1,225 @@
+package de.tudarmstadt.informatik.hostage.logging.formatter.protocol;
+
+import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
+
+/**
+ * SMB log view formatter.
+ * 
+ * @author Wulf Pfeiffer
+ */
+public class SMB extends ProtocolFormatter {
+
+	@Override
+	public String format(String packet) {
+		byte[] bytes = HelperUtils.hexStringToBytes(packet);
+		byte cmd = bytes[8]; // command code located at 8
+		StringBuffer buffer = new StringBuffer();
+		buffer.append("Command: ");
+		buffer.append(getCommandString(cmd));
+		buffer.append("\n");
+		buffer.append("Content: ");
+		buffer.append(getContent(cmd, bytes));
+
+		return buffer.toString();
+	}
+
+	/**
+	 * Checks command code for its command code and returns the name of this
+	 * command.
+	 * 
+	 * @param command
+	 *            as byte.
+	 * @return command name as String.
+	 */
+	private String getCommandString(byte command) {
+		switch (command) {
+		case 0x00:
+			return "SMB_COM_CREATE_DIRECTORY";
+		case 0x01:
+			return "SMB_COM_DELETE_DIRECTORY";
+		case 0x02:
+			return "SMB_COM_OPEN";
+		case 0x03:
+			return "SMB_COM_CREATE";
+		case 0x04:
+			return "SMB_COM_CLOSE";
+		case 0x05:
+			return "SMB_COM_FLUSH";
+		case 0x06:
+			return "SMB_COM_DELETE";
+		case 0x07:
+			return "SMB_COM_RENAME";
+		case 0x08:
+			return "SMB_COM_QUERY_INFORMATION";
+		case 0x09:
+			return "SMB_COM_SET_INFORMATION";
+		case 0x0A:
+			return "SMB_COM_READ";
+		case 0x0B:
+			return "SMB_COM_WRITE";
+		case 0x0C:
+			return "SMB_COM_LOCK_BYTE_RANGE";
+		case 0x0D:
+			return "SMB_COM_UNLOCK_BYTE_RANGE";
+		case 0x0E:
+			return "SMB_COM_CREATE_TEMPORARY";
+		case 0x0F:
+			return "SMB_COM_CREATE_NEW";
+		case 0x10:
+			return "SMB_COM_CHECK_DIRECTORY";
+		case 0x11:
+			return "SMB_COM_PROCESS_EXIT";
+		case 0x12:
+			return "SMB_COM_SEEK";
+		case 0x13:
+			return "SMB_COM_LOCK_AND_READ";
+		case 0x14:
+			return "SMB_COM_WRITE_AND_UNLOCK";
+		case 0x1A:
+			return "SMB_COM_READ_RAW";
+		case 0x1B:
+			return "SMB_COM_READ_MPX";
+		case 0x1C:
+			return "SMB_COM_READ_MPX_SECONDARY";
+		case 0x1D:
+			return "SMB_COM_WRITE_RAW";
+		case 0x1E:
+			return "SMB_COM_WRITE_MPX";
+		case 0x1F:
+			return "SMB_COM_WRITE_MPX_SECONDARY";
+		case 0x20:
+			return "SMB_COM_WRITE_COMPLETE";
+		case 0x21:
+			return "SMB_COM_QUERY_SERVER";
+		case 0x22:
+			return "SMB_COM_SET_INFORMATION2";
+		case 0x23:
+			return "SMB_COM_QUERY_INFORMATION2";
+		case 0x24:
+			return "SMB_COM_LOCKING_ANDX";
+		case 0x25:
+			return "SMB_COM_TRANSACTION";
+		case 0x26:
+			return "SMB_COM_TRANSACTION_SECONDARY";
+		case 0x27:
+			return "SMB_COM_IOCTL";
+		case 0x28:
+			return "SMB_COM_IOCTL_SECONDARY";
+		case 0x29:
+			return "SMB_COM_COPY";
+		case 0x2A:
+			return "SMB_COM_MOVE";
+		case 0x2B:
+			return "SMB_COM_ECHO";
+		case 0x2C:
+			return "SMB_COM_WRITE_AND_CLOSE";
+		case 0x2D:
+			return "SMB_COM_OPEN_ANDX";
+		case 0x2E:
+			return "SMB_COM_READ_ANDX";
+		case 0x2F:
+			return "SMB_COM_WRITE_ANDX";
+		case 0x30:
+			return "SMB_COM_NEW_FILE_SIZE";
+		case 0x31:
+			return "SMB_COM_CLOSE_AND_TREE_DISC";
+		case 0x32:
+			return "SMB_COM_TRANSACTION2";
+		case 0x33:
+			return "SMB_COM_TRANSACTION2_SECONDARY";
+		case 0x34:
+			return "SMB_COM_FIND_CLOSE2";
+		case 0x35:
+			return "SMB_COM_FIND_NOTIFY_CLOSE";
+		case 0x70:
+			return "SMB_COM_TREE_CONNECT";
+		case 0x71:
+			return "SMB_COM_TREE_DISCONNECT";
+		case 0x72:
+			return "SMB_COM_NEGOTIATE";
+		case 0x73:
+			return "SMB_COM_SESSION_SETUP_ANDX";
+		case 0x74:
+			return "SMB_COM_LOGOFF_ANDX";
+		case 0x75:
+			return "SMB_COM_TREE_CONNECT_ANDX";
+		case (byte) 0x80:
+			return "SMB_COM_QUERY_INFORMATION_DISK";
+		case (byte) 0x81:
+			return "SMB_COM_SEARCH";
+		case (byte) 0x82:
+			return "SMB_COM_FIND";
+		case (byte) 0x83:
+			return "SMB_COM_FIND_UNIQUE";
+		case (byte) 0x84:
+			return "SMB_COM_FIND_CLOSE";
+		case (byte) 0xA0:
+			return "SMB_COM_NT_TRANSACT";
+		case (byte) 0xA1:
+			return "SMB_COM_NT_TRANSACT_SECONDARY";
+		case (byte) 0xA2:
+			return "SMB_COM_NT_CREATE_ANDX";
+		case (byte) 0xA4:
+			return "SMB_COM_NT_CANCEL";
+		case (byte) 0xA5:
+			return "SMB_COM_NT_RENAME";
+		case (byte) 0xC0:
+			return "SMB_COM_OPEN_PRINT_FILE";
+		case (byte) 0xC1:
+			return "SMB_COM_WRITE_PRINT_FILE";
+		case (byte) 0xC2:
+			return "SMB_COM_CLOSE_PRINT_FILE";
+		case (byte) 0xC3:
+			return "SMB_COM_GET_PRINT_QUEUE";
+		case (byte) 0xD8:
+			return "SMB_COM_READ_BULK";
+		case (byte) 0xD9:
+			return "SMB_COM_WRITE_BULK";
+		case (byte) 0xDA:
+			return "SMB_COM_WRITE_BULK_DATA";
+		case (byte) 0xFF:
+			return "SMB_COM_NONE";
+		default:
+			return "Unknown Command";
+		}
+	}
+
+	/**
+	 * Returns the content of a packet as a String value, depending on its
+	 * command code
+	 * 
+	 * @param command
+	 *            of the packet.
+	 * @param packet
+	 *            content as byte array.
+	 * @return content as a String.
+	 */
+	private String getContent(byte command, byte[] packet) {
+		switch (command) {
+		case 0x72:
+			return get0x72content(packet);
+		case 0x73:
+			return HelperUtils.byteToStr(packet);
+		case (byte) 0xa2:
+			return HelperUtils.byteToStr(packet);
+		case 0x25:
+			return HelperUtils.byteToStr(packet);
+		default:
+			return "";
+		}
+	}
+
+	/**
+	 * Returns the content of a packet with command code 0x72.
+	 * 
+	 * @param packet
+	 *            content as byte array.
+	 * @return content as String.
+	 */
+	private String get0x72content(byte[] packet) {
+		byte[] content = new byte[packet.length - 39];
+		System.arraycopy(packet, 39, content, 0, content.length);
+		return HelperUtils.byteToStr(content);
+	}
+
+}

+ 149 - 0
src/de/tudarmstadt/informatik/hostage/logging/formatter/protocol/TELNET.java

@@ -0,0 +1,149 @@
+package de.tudarmstadt.informatik.hostage.logging.formatter.protocol;
+
+import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
+
+/**
+ * Telnet log view formatter.
+ * 
+ * @author Wulf Pfeiffer
+ */
+public class TELNET extends ProtocolFormatter {
+
+	@Override
+	public String format(String packet) {
+		byte[] bytes = HelperUtils.hexStringToBytes(packet);
+		String options = "Options:\n" + checkForOptions(bytes) + "\n";
+		String content = "Content: " + HelperUtils.byteToStr(bytes);
+		return options + content;
+	}
+
+	/**
+	 * Checks a packet for option commands and returns their names as Strings.
+	 * 
+	 * @param bytes
+	 *            that are checked.
+	 * @return names of the option commands as String.
+	 */
+	private String checkForOptions(byte[] bytes) {
+		StringBuffer options = new StringBuffer();
+		for (int i = 0; i < bytes.length; i++) {
+			if (bytes[i] == (byte) 0xff && i + 2 < bytes.length) {
+				options.append(checkMode(bytes[i + 1]));
+				// option name
+				options.append(checkCommand(bytes[i + 2]));
+			}
+		}
+		return options.toString();
+	}
+
+	/**
+	 * Checks a byte for its mode value.
+	 * 
+	 * @param b
+	 *            byte that is checked.
+	 * @return name of the mode.
+	 */
+	private String checkMode(byte b) {
+		switch (b) {
+		case (byte) 0xfb:
+			return " WILL ";
+		case (byte) 0xfc:
+			return " WON'T ";
+		case (byte) 0xfd:
+			return " DO ";
+		case (byte) 0xfe:
+			return " DON'T ";
+		default:
+			return " unkown command ";
+		}
+	}
+
+	/**
+	 * Checks a byte for its command value.
+	 * 
+	 * @param b
+	 *            byte that is checked.
+	 * @return name of the command.
+	 */
+	private String checkCommand(byte b) {
+		switch (b) {
+		case 0x00:
+			return "Binary Transmission\n";
+		case 0x01:
+			return "Echo\n";
+		case 0x02:
+			return "Reconnection\n";
+		case 0x03:
+			return "Suppress Go Ahead\n";
+		case 0x04:
+			return "Approx Message Size Negotiation\n";
+		case 0x05:
+			return "Status\n";
+		case 0x06:
+			return "Timing Mark\n";
+		case 0x07:
+			return "Remote Controlled Trans and Echo\n";
+		case 0x08:
+			return "Output Line Width\n";
+		case 0x09:
+			return "Output Page Size\n";
+		case 0x0a:
+			return "Output Carriage-Return Disposition\n";
+		case 0x0b:
+			return "Output Horizontal Tab Stops\n";
+		case 0x0c:
+			return "Output Horizontal Tab Disposition\n";
+		case 0x0d:
+			return "Output Formfeed Disposition\n";
+		case 0x0e:
+			return "Output Vertical Tabstops\n";
+		case 0x0f:
+			return "Output Vertical Tab Disposition\n";
+		case 0x10:
+			return "Output Linefeed Disposition\n";
+		case 0x11:
+			return "Extended ASCII\n";
+		case 0x12:
+			return "Logout\n";
+		case 0x13:
+			return "Byte Macro\n";
+		case 0x14:
+			return "Data Entry Terminal\n";
+		case 0x15:
+			return "SUPDUP\n";
+		case 0x16:
+			return "SUPDUP Output\n";
+		case 0x17:
+			return "Send Location\n";
+		case 0x18:
+			return "Terminal Type\n";
+		case 0x19:
+			return "End of Record\n";
+		case 0x1a:
+			return "TACACS User Identification\n";
+		case 0x1b:
+			return "Output Marking\n";
+		case 0x1c:
+			return "Terminal Location Number\n";
+		case 0x1d:
+			return "Telnet 3270 Regime\n";
+		case 0x1e:
+			return "X.3 PAD\n";
+		case 0x1f:
+			return "Negotiate About Window Size\n";
+		case 0x20:
+			return "Terminal Speed\n";
+		case 0x21:
+			return "Remote Flow Control\n";
+		case 0x22:
+			return "Linemode\n";
+		case 0x23:
+			return "X Display Location\n";
+		case (byte) 0xff:
+			return "Extended-Options-List\n";
+		default:
+			return "unknown option\n";
+		}
+	}
+
+}

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/sync/BluetoothSync.java

@@ -19,7 +19,7 @@ import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.IntentFilter;
 import android.widget.ArrayAdapter;
 import android.widget.ArrayAdapter;
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.logging.DatabaseHandler;
+import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
 
 
 public class BluetoothSync{
 public class BluetoothSync{
 	
 	
@@ -233,7 +233,7 @@ public class BluetoothSync{
 	        // Keep listening to the InputStream until an exception occurs
 	        // Keep listening to the InputStream until an exception occurs
 //	        while (true) {
 //	        while (true) {
 	            try {
 	            try {
-	            	DatabaseHandler dbh = new DatabaseHandler(context);
+	            	UglyDbHelper dbh = new UglyDbHelper(context);
             		ArrayList<HashMap<String, Object>> localNetworkInformation = dbh.getNetworkInformation();
             		ArrayList<HashMap<String, Object>> localNetworkInformation = dbh.getNetworkInformation();
 	            	if(identifier == SERVER){
 	            	if(identifier == SERVER){
 		                // Read from the InputStream 
 		                // Read from the InputStream 

+ 3 - 3
src/de/tudarmstadt/informatik/hostage/sync/NFCSync.java

@@ -43,7 +43,7 @@ import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.HashMap;
 
 
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.logging.DatabaseHandler;
+import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
 
 
 
 
 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@@ -78,7 +78,7 @@ public class NFCSync extends Activity implements CreateNdefMessageCallback,
     @Override
     @Override
     public NdefMessage createNdefMessage(NfcEvent event) {
     public NdefMessage createNdefMessage(NfcEvent event) {
     	// Get Networkdata
     	// Get Networkdata
-    	DatabaseHandler dbh = new DatabaseHandler(this);
+    	UglyDbHelper dbh = new UglyDbHelper(this);
 		ArrayList<HashMap<String, Object>> localNetworkInformation = dbh.getNetworkInformation();
 		ArrayList<HashMap<String, Object>> localNetworkInformation = dbh.getNetworkInformation();
 		Log.i("NFC", "Creating Message");
 		Log.i("NFC", "Creating Message");
         NdefMessage msg = null;
         NdefMessage msg = null;
@@ -154,7 +154,7 @@ public class NFCSync extends Activity implements CreateNdefMessageCallback,
 		try {
 		try {
 			object = deserialize(msg.getRecords()[0].getPayload());
 			object = deserialize(msg.getRecords()[0].getPayload());
 	    	ArrayList<HashMap<String, Object>> remoteNetworkInformation = (ArrayList<HashMap<String, Object>>) object;
 	    	ArrayList<HashMap<String, Object>> remoteNetworkInformation = (ArrayList<HashMap<String, Object>>) object;
-	    	DatabaseHandler dbh = new DatabaseHandler(this);
+	    	UglyDbHelper dbh = new UglyDbHelper(this);
 	    	dbh.updateNetworkInformation(remoteNetworkInformation);
 	    	dbh.updateNetworkInformation(remoteNetworkInformation);
 		} catch (ClassNotFoundException e) {
 		} catch (ClassNotFoundException e) {
 			// TODO Auto-generated catch block
 			// TODO Auto-generated catch block

+ 268 - 212
src/de/tudarmstadt/informatik/hostage/ui/MainActivity.java

@@ -1,8 +1,6 @@
 package de.tudarmstadt.informatik.hostage.ui;
 package de.tudarmstadt.informatik.hostage.ui;
 
 
 import java.io.BufferedReader;
 import java.io.BufferedReader;
-import java.io.DataInputStream;
-import java.io.File;
 import java.io.InputStreamReader;
 import java.io.InputStreamReader;
 import java.util.ArrayList;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.HashMap;
@@ -29,6 +27,7 @@ import android.content.SharedPreferences.Editor;
 import android.net.ConnectivityManager;
 import android.net.ConnectivityManager;
 import android.os.AsyncTask;
 import android.os.AsyncTask;
 import android.os.Bundle;
 import android.os.Bundle;
+import android.os.Handler;
 import android.os.IBinder;
 import android.os.IBinder;
 import android.support.v4.content.LocalBroadcastManager;
 import android.support.v4.content.LocalBroadcastManager;
 import android.util.Log;
 import android.util.Log;
@@ -47,35 +46,39 @@ import android.widget.CheckBox;
 import android.widget.ImageView;
 import android.widget.ImageView;
 import android.widget.ListView;
 import android.widget.ListView;
 import android.widget.TextView;
 import android.widget.TextView;
-import android.widget.Toast;
 import android.widget.ToggleButton;
 import android.widget.ToggleButton;
 import android.widget.ViewAnimator;
 import android.widget.ViewAnimator;
 import de.tudarmstadt.informatik.hostage.HoneyService;
 import de.tudarmstadt.informatik.hostage.HoneyService;
 import de.tudarmstadt.informatik.hostage.HoneyService.LocalBinder;
 import de.tudarmstadt.informatik.hostage.HoneyService.LocalBinder;
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
+import de.tudarmstadt.informatik.hostage.logging.LogResultReceiver;
+import de.tudarmstadt.informatik.hostage.logging.LogResultReceiver.Receiver;
 import de.tudarmstadt.informatik.hostage.logging.Logger;
 import de.tudarmstadt.informatik.hostage.logging.Logger;
-import de.tudarmstadt.informatik.hostage.logging.SQLLogger;
+
 /**
 /**
  * MainActivity is the central activity for the GUI of the application.
  * MainActivity is the central activity for the GUI of the application.
- * MainActivity is launched when the application is first started.
- * It shows the user: <br>
+ * MainActivity is launched when the application is first started. It shows the
+ * user: <br>
  * - information about the network<br>
  * - information about the network<br>
  * - light indicators for recorded attacks on each protocol<br>
  * - light indicators for recorded attacks on each protocol<br>
  * - amount of attacks on each protocols<br>
  * - amount of attacks on each protocols<br>
  * The user can start and stop services.
  * The user can start and stop services.
+ * 
  * @author Mihai Plasoianu
  * @author Mihai Plasoianu
  * @author Lars Pandikow
  * @author Lars Pandikow
  * @author Wulf Pfeiffer
  * @author Wulf Pfeiffer
  */
  */
-public class MainActivity extends Activity {
+public class MainActivity extends Activity implements Receiver {
 	// String constants for whole application
 	// String constants for whole application
 	/**
 	/**
-	 * Used for Broadcast between service and GUI. String: "de.tudarmstadt.informatik.hostage.BROADCAST"
+	 * Used for Broadcast between service and GUI. String:
+	 * "de.tudarmstadt.informatik.hostage.BROADCAST"
 	 */
 	 */
 	public static final String BROADCAST = "de.tudarmstadt.informatik.hostage.BROADCAST";
 	public static final String BROADCAST = "de.tudarmstadt.informatik.hostage.BROADCAST";
 	/**
 	/**
-	 * Used to store session related data in a SharedPrefereces. String: "de.tudarmstadt.informatik.hostage.SESSION_DATA"
+	 * Used to store session related data in a SharedPrefereces. String:
+	 * "de.tudarmstadt.informatik.hostage.SESSION_DATA"
 	 */
 	 */
 	public static final String SESSION_DATA = "de.tudarmstadt.informatik.hostage.SESSION_DATA";
 	public static final String SESSION_DATA = "de.tudarmstadt.informatik.hostage.SESSION_DATA";
 	public static final String LISTENER = "_LISTENER";
 	public static final String LISTENER = "_LISTENER";
@@ -84,7 +87,7 @@ public class MainActivity extends Activity {
 	public static final String BSSID = "BSSID";
 	public static final String BSSID = "BSSID";
 	public static final String INTERNAL_IP = "INTERNAL_IP";
 	public static final String INTERNAL_IP = "INTERNAL_IP";
 	public static final String EXTERNAL_IP = "EXTERNAL_IP";
 	public static final String EXTERNAL_IP = "EXTERNAL_IP";
-	
+
 	/**
 	/**
 	 * Flag for root acces. True if phone has root acces, else false.
 	 * Flag for root acces. True if phone has root acces, else false.
 	 */
 	 */
@@ -110,15 +113,15 @@ public class MainActivity extends Activity {
 	 * Integer representing a yellow light.
 	 * Integer representing a yellow light.
 	 */
 	 */
 	public static final int LIGHT_YELLOW = 0x04;
 	public static final int LIGHT_YELLOW = 0x04;
-	
-    private static Context context;
 
 
+	private static Context context;
+
+	public LogResultReceiver logResultReceiver;
 
 
 	private HoneyService mService;
 	private HoneyService mService;
 	private boolean serviceBound;
 	private boolean serviceBound;
 	private SharedPreferences sessionPref;
 	private SharedPreferences sessionPref;
 	private Editor sessionEditor;
 	private Editor sessionEditor;
-	private Logger logger;
 
 
 	// variables for the swipe animation
 	// variables for the swipe animation
 	private ViewAnimator viewAnimator;
 	private ViewAnimator viewAnimator;
@@ -130,22 +133,24 @@ public class MainActivity extends Activity {
 
 
 	private ListView listView;
 	private ListView listView;
 	private ListViewAdapter adapter;
 	private ListViewAdapter adapter;
-	
+
 	private String protocolClicked;
 	private String protocolClicked;
-	
-	
+
+	private boolean isBssidSeen = false;
+
 	@Override
 	@Override
 	protected void onCreate(Bundle savedInstanceState) {
 	protected void onCreate(Bundle savedInstanceState) {
 		super.onCreate(savedInstanceState);
 		super.onCreate(savedInstanceState);
-        MainActivity.context = getApplicationContext();	//set context
+		MainActivity.context = getApplicationContext(); // set context
+		logResultReceiver = new LogResultReceiver(new Handler());
 		setContentView(R.layout.activity_main);
 		setContentView(R.layout.activity_main);
-		
+
 		// Create dynamic view elements
 		// Create dynamic view elements
 		initViewAnimator();
 		initViewAnimator();
 		initListView();
 		initListView();
 		// Initialize Class variables
 		// Initialize Class variables
-		sessionPref = getSharedPreferences(MainActivity.SESSION_DATA, Context.MODE_PRIVATE);
-		logger = new SQLLogger(this);
+		sessionPref = getSharedPreferences(MainActivity.SESSION_DATA,
+				Context.MODE_PRIVATE);
 		sessionEditor = sessionPref.edit();
 		sessionEditor = sessionPref.edit();
 		checkRootAndPorthack();
 		checkRootAndPorthack();
 	}
 	}
@@ -155,35 +160,37 @@ public class MainActivity extends Activity {
 		getMenuInflater().inflate(R.menu.main, menu);
 		getMenuInflater().inflate(R.menu.main, menu);
 		return true;
 		return true;
 	}
 	}
-	
+
 	@Override
 	@Override
 	public boolean onOptionsItemSelected(MenuItem item) {
 	public boolean onOptionsItemSelected(MenuItem item) {
-	    // Handle item selection
-	    switch (item.getItemId()) {
-	        case R.id.action_settings:
-	            startActivity(new Intent(this, SettingsActivity.class));
-	            break;
-	        case R.id.action_about:
-	            startActivity(new Intent(this, AboutActivity.class));
-	            break;
-	        default:
-	    }
-        return super.onOptionsItemSelected(item);
+		// Handle item selection
+		switch (item.getItemId()) {
+		case R.id.action_settings:
+			startActivity(new Intent(this, SettingsActivity.class));
+			break;
+		case R.id.action_about:
+			startActivity(new Intent(this, AboutActivity.class));
+			break;
+		default:
+		}
+		return super.onOptionsItemSelected(item);
 	}
 	}
 
 
 	@Override
 	@Override
 	protected void onStart() {
 	protected void onStart() {
 		super.onStart();
 		super.onStart();
-		//Register Broadcast Receiver
+		// Register Broadcast Receiver
 		registerReceiver();
 		registerReceiver();
 		registerNetReceiver();
 		registerNetReceiver();
-		// Bind service if running, else check for connection change and delete sessionData
+		logResultReceiver.setReceiver(this);
+		// Bind service if running, else check for connection change and delete
+		// sessionData
 		if (isServiceRunning()) {
 		if (isServiceRunning()) {
 			bindService(getServiceIntent(), mConnection, BIND_AUTO_CREATE);
 			bindService(getServiceIntent(), mConnection, BIND_AUTO_CREATE);
 		} else {
 		} else {
 			String bssid_old = sessionPref.getString(MainActivity.BSSID, "");
 			String bssid_old = sessionPref.getString(MainActivity.BSSID, "");
 			String bssid_new = HelperUtils.getBSSID(this);
 			String bssid_new = HelperUtils.getBSSID(this);
-			if(bssid_new == null || !bssid_new.equals(bssid_old)){
+			if (bssid_new == null || !bssid_new.equals(bssid_old)) {
 				deleteSessionData();
 				deleteSessionData();
 			}
 			}
 		}
 		}
@@ -194,27 +201,34 @@ public class MainActivity extends Activity {
 
 
 	@Override
 	@Override
 	protected void onStop() {
 	protected void onStop() {
-		//Unbind running service
+		// Unbind running service
 		if (isServiceRunning()) {
 		if (isServiceRunning()) {
 			unbindService(mConnection);
 			unbindService(mConnection);
 		}
 		}
 		// Unregister Broadcast Receiver
 		// Unregister Broadcast Receiver
 		unregisterNetReceiver();
 		unregisterNetReceiver();
 		unregisterReceiver();
 		unregisterReceiver();
+		logResultReceiver.setReceiver(null);
 		super.onStop();
 		super.onStop();
 	}
 	}
-	
+
 	@Override
 	@Override
-	protected void onDestroy(){
+	protected void onDestroy() {
 		super.onDestroy();
 		super.onDestroy();
 		// If service not running delete session data
 		// If service not running delete session data
-		if(!isServiceRunning()){
+		if (!isServiceRunning()) {
 			deleteSessionData();
 			deleteSessionData();
 		}
 		}
 	}
 	}
 
 
+	@Override
+	public void onReceiveResult(int resultCode, Bundle resultData) {
+		isBssidSeen = resultData.getBoolean("result");
+	}
+
 	/**
 	/**
 	 * Called when User presses on/off button.
 	 * Called when User presses on/off button.
+	 * 
 	 * @param view
 	 * @param view
 	 */
 	 */
 	public void buttonOnOffClick(View view) {
 	public void buttonOnOffClick(View view) {
@@ -223,129 +237,141 @@ public class MainActivity extends Activity {
 				protocolClicked = "PANIC";
 				protocolClicked = "PANIC";
 			} else {
 			} else {
 				protocolClicked = "SMB";
 				protocolClicked = "SMB";
-			}			
+			}
 			startAndBind();
 			startAndBind();
 		} else {
 		} else {
 			mService.stopListeners();
 			mService.stopListeners();
 			stopAndUnbind();
 			stopAndUnbind();
 		}
 		}
 	}
 	}
-	
+
 	/**
 	/**
 	 * Starts the ViewLog activity, when the Button is pressed.
 	 * Starts the ViewLog activity, when the Button is pressed.
+	 * 
 	 * @see ViewLog
 	 * @see ViewLog
-	 * @param view View elements which triggers the method call.
+	 * @param view
+	 *            View elements which triggers the method call.
 	 */
 	 */
-	public void showLog(View view){
+	public void showLog(View view) {
 		startActivity(new Intent(this, ViewLog.class));
 		startActivity(new Intent(this, ViewLog.class));
 	}
 	}
-	
-	public void startPlayGround(View view){
+
+	public void startPlayGround(View view) {
 		startActivity(new Intent(this, PlayGroundActivity.class));
 		startActivity(new Intent(this, PlayGroundActivity.class));
 	}
 	}
 
 
 	/**
 	/**
-	 * If mobile phone is connected to a wireless network starts the background service ands binds itself to it.
-	 * Else notifies the user that service could not be started.
+	 * If mobile phone is connected to a wireless network starts the background
+	 * service ands binds itself to it. Else notifies the user that service
+	 * could not be started.
 	 */
 	 */
 	private void startAndBind() {
 	private void startAndBind() {
 		startService(getServiceIntent());
 		startService(getServiceIntent());
-		bindService();	
+		bindService();
 	}
 	}
-	
+
 	/**
 	/**
 	 * Binds service to Activity
 	 * Binds service to Activity
+	 * 
 	 * @see HoneyService
 	 * @see HoneyService
 	 */
 	 */
-	private void bindService(){
+	private void bindService() {
 		bindService(getServiceIntent(), mConnection, BIND_AUTO_CREATE);
 		bindService(getServiceIntent(), mConnection, BIND_AUTO_CREATE);
 		serviceBound = true;
 		serviceBound = true;
 	}
 	}
 
 
 	/**
 	/**
 	 * Stops service and unbinds it.
 	 * Stops service and unbinds it.
+	 * 
 	 * @see HoneyService
 	 * @see HoneyService
 	 */
 	 */
 	private void stopAndUnbind() {
 	private void stopAndUnbind() {
 		unbindService();
 		unbindService();
 		stopService(getServiceIntent());
 		stopService(getServiceIntent());
 	}
 	}
-	
+
 	/**
 	/**
 	 * Unbinds service.
 	 * Unbinds service.
+	 * 
 	 * @see HoneyService
 	 * @see HoneyService
 	 */
 	 */
-	private void unbindService(){
+	private void unbindService() {
 		unbindService(mConnection);
 		unbindService(mConnection);
 		serviceBound = false;
 		serviceBound = false;
 	}
 	}
-	
+
 	/**
 	/**
 	 * Connection to bind the background service
 	 * Connection to bind the background service
+	 * 
 	 * @see HoneyService
 	 * @see HoneyService
 	 */
 	 */
 	private ServiceConnection mConnection = new ServiceConnection() {
 	private ServiceConnection mConnection = new ServiceConnection() {
-		/** 
-		 * After the service is bound, check which has been clicked and start it.
+		/**
+		 * After the service is bound, check which has been clicked and start
+		 * it.
+		 * 
 		 * @see android.content.ServiceConnection#onServiceConnected(android.content.ComponentName)
 		 * @see android.content.ServiceConnection#onServiceConnected(android.content.ComponentName)
 		 */
 		 */
 		@Override
 		@Override
 		public void onServiceConnected(ComponentName name, IBinder service) {
 		public void onServiceConnected(ComponentName name, IBinder service) {
 			mService = ((LocalBinder) service).getService();
 			mService = ((LocalBinder) service).getService();
-			if(protocolClicked != null && protocolClicked.equals("PANIC")){
+			if (protocolClicked != null && protocolClicked.equals("PANIC")) {
 				mService.startListeners();
 				mService.startListeners();
-			}else if (protocolClicked != null){
+			} else if (protocolClicked != null) {
 				mService.toggleListener(protocolClicked);
 				mService.toggleListener(protocolClicked);
 			}
 			}
 			protocolClicked = null;
 			protocolClicked = null;
 		}
 		}
-		
+
 		/**
 		/**
 		 * After the service is unbound, delete reference.
 		 * After the service is unbound, delete reference.
+		 * 
 		 * @see android.content.ServiceConnection#onServiceDisconnected(android.content.ComponentName)
 		 * @see android.content.ServiceConnection#onServiceDisconnected(android.content.ComponentName)
 		 */
 		 */
 		@Override
 		@Override
 		public void onServiceDisconnected(ComponentName name) {
 		public void onServiceDisconnected(ComponentName name) {
-			mService = null;			
+			mService = null;
 		}
 		}
 
 
 	};
 	};
-	
+
 	/**
 	/**
-	 * Checks if the phone ist rooted and if porthack is installed. Sets flags {@link isRooted} and {@link porthackInstalled}
+	 * Checks if the phone ist rooted and if porthack is installed. Sets flags
+	 * {@link isRooted} and {@link porthackInstalled}
 	 */
 	 */
-	private void checkRootAndPorthack(){
+	private void checkRootAndPorthack() {
 		isRooted = false;
 		isRooted = false;
 		porthackInstalled = false;
 		porthackInstalled = false;
 		Process p;
 		Process p;
 		try {
 		try {
 			String found = "Found";
 			String found = "Found";
 			String notFound = "Not found";
 			String notFound = "Not found";
-			String command = "[ -f /data/local/p ] && echo " + found + " || echo " + notFound;
+			String command = "[ -f /data/local/p ] && echo " + found
+					+ " || echo " + notFound;
 			p = Runtime.getRuntime().exec(new String[] { "su", "-c", command });
 			p = Runtime.getRuntime().exec(new String[] { "su", "-c", command });
-			BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));			
- /*           int av = 
-            byte[] b = new byte[av];
-            if (av != 0) {                
-                in.read(b);
-            }
-   */         
-            String echoResponse = in.readLine();
-            Log.i("MainAc", echoResponse);
-            if(echoResponse.equals(found)){
-            	isRooted = true;
-            	porthackInstalled = true;
-            } else if(echoResponse.equals(notFound)){
-            	isRooted = true;
-            }
+			BufferedReader in = new BufferedReader(new InputStreamReader(
+					p.getInputStream()));
+			/*
+			 * int av = byte[] b = new byte[av]; if (av != 0) { in.read(b); }
+			 */
+			String echoResponse = in.readLine();
+			Log.i("MainAc", echoResponse);
+			if (echoResponse.equals(found)) {
+				isRooted = true;
+				porthackInstalled = true;
+			} else if (echoResponse.equals(notFound)) {
+				isRooted = true;
+			}
 		} catch (Exception e) {
 		} catch (Exception e) {
 			e.printStackTrace();
 			e.printStackTrace();
-		}	    
-		Log.i("MainAc", "Rooted: " + isRooted + " Porthack: " + porthackInstalled);
+		}
+		Log.i("MainAc", "Rooted: " + isRooted + " Porthack: "
+				+ porthackInstalled);
 	}
 	}
-	
+
 	/**
 	/**
 	 * Returns an intent to start HoneyService.
 	 * Returns an intent to start HoneyService.
+	 * 
 	 * @return An Intent to start HoneyService
 	 * @return An Intent to start HoneyService
 	 */
 	 */
 	private Intent getServiceIntent() {
 	private Intent getServiceIntent() {
@@ -354,6 +380,7 @@ public class MainActivity extends Activity {
 
 
 	/**
 	/**
 	 * Checks if user selected paranoid mode.
 	 * Checks if user selected paranoid mode.
+	 * 
 	 * @return True when paranoid mode is selected, else returns false.
 	 * @return True when paranoid mode is selected, else returns false.
 	 */
 	 */
 	private boolean isParanoid() {
 	private boolean isParanoid() {
@@ -361,7 +388,8 @@ public class MainActivity extends Activity {
 	}
 	}
 
 
 	/**
 	/**
-	 * Initializes the ListView. Creating its contents dynamic from protocol res/values/protocols.xml
+	 * Initializes the ListView. Creating its contents dynamic from protocol
+	 * res/values/protocols.xml
 	 */
 	 */
 	private void initListView() {
 	private void initListView() {
 		ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
 		ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
@@ -391,42 +419,46 @@ public class MainActivity extends Activity {
 				String protocolName = (String) ((HashMap<?, ?>) adapter
 				String protocolName = (String) ((HashMap<?, ?>) adapter
 						.getItem(position)).get("protocol");
 						.getItem(position)).get("protocol");
 				if (isServiceRunning()) {
 				if (isServiceRunning()) {
-					mService.toggleListener(protocolName);	
-					if(!mService.hasRunningListeners()){
+					mService.toggleListener(protocolName);
+					if (!mService.hasRunningListeners()) {
 						stopAndUnbind();
 						stopAndUnbind();
 					}
 					}
-				}else{
+				} else {
 					protocolClicked = protocolName;
 					protocolClicked = protocolName;
 					startAndBind();
 					startAndBind();
-				}											
+				}
 			}
 			}
 		});
 		});
 	}
 	}
 
 
 	/**
 	/**
 	 * Checks if a {@link HoneyService} instance is running.
 	 * Checks if a {@link HoneyService} instance is running.
-	 * @return True if {@link HoneyService}  is running, else false.
+	 * 
+	 * @return True if {@link HoneyService} is running, else false.
 	 */
 	 */
 	private boolean isServiceRunning() {
 	private boolean isServiceRunning() {
 		ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
 		ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
-		for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
-			if (service.service.getClassName().equals(HoneyService.class.getName())) {
+		for (RunningServiceInfo service : manager
+				.getRunningServices(Integer.MAX_VALUE)) {
+			if (service.service.getClassName().equals(
+					HoneyService.class.getName())) {
 				return true;
 				return true;
 			}
 			}
 		}
 		}
 		return false;
 		return false;
 	}
 	}
-	
+
 	/**
 	/**
 	 * Deletes all session related Data.
 	 * Deletes all session related Data.
 	 */
 	 */
-	private void deleteSessionData(){
-    	sessionEditor.clear();
-    	sessionEditor.commit();
+	private void deleteSessionData() {
+		sessionEditor.clear();
+		sessionEditor.commit();
 	}
 	}
 
 
 	/**
 	/**
 	 * Register broadcast receiver for custom broadcast.
 	 * Register broadcast receiver for custom broadcast.
+	 * 
 	 * @see #BROADCAST
 	 * @see #BROADCAST
 	 */
 	 */
 	private void registerReceiver() {
 	private void registerReceiver() {
@@ -436,14 +468,16 @@ public class MainActivity extends Activity {
 
 
 	/**
 	/**
 	 * Unregisters broadcast receiver for custom broadcast.
 	 * Unregisters broadcast receiver for custom broadcast.
+	 * 
 	 * @see #BROADCAST
 	 * @see #BROADCAST
 	 */
 	 */
 	private void unregisterReceiver() {
 	private void unregisterReceiver() {
 		LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
 		LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
 	}
 	}
-	
+
 	/**
 	/**
 	 * Receiver for custom broadcast.
 	 * Receiver for custom broadcast.
+	 * 
 	 * @see #BROADCAST
 	 * @see #BROADCAST
 	 */
 	 */
 	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
 	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@@ -456,12 +490,13 @@ public class MainActivity extends Activity {
 
 
 	/**
 	/**
 	 * Register broadcast receiver for network state changes.
 	 * Register broadcast receiver for network state changes.
+	 * 
 	 * @see ConnectivityManager#CONNECTIVITY_ACTION
 	 * @see ConnectivityManager#CONNECTIVITY_ACTION
 	 */
 	 */
-	private void registerNetReceiver() {   
+	private void registerNetReceiver() {
 		IntentFilter intent = new IntentFilter();
 		IntentFilter intent = new IntentFilter();
-	    intent.addAction(ConnectivityManager.CONNECTIVITY_ACTION); //"android.net.conn.CONNECTIVITY_CHANGE"
-	    registerReceiver(netReceiver, intent);
+		intent.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // "android.net.conn.CONNECTIVITY_CHANGE"
+		registerReceiver(netReceiver, intent);
 	}
 	}
 
 
 	/**
 	/**
@@ -477,63 +512,70 @@ public class MainActivity extends Activity {
 	private BroadcastReceiver netReceiver = new BroadcastReceiver() {
 	private BroadcastReceiver netReceiver = new BroadcastReceiver() {
 		@Override
 		@Override
 		public void onReceive(Context context, Intent intent) {
 		public void onReceive(Context context, Intent intent) {
-/*			String bssid_old = sessionPref.getString(BSSID, "");
-			String bssid_new = HelperUtils.getBSSID(context);
-
-			if ((bssid_new == null || !bssid_new.equals(bssid_old)) && serviceBound) {
-				Toast.makeText(getApplicationContext(),"Connection changed! Services stopped!", Toast.LENGTH_LONG).show();
-				unbindService();
-			}	
-*/			
+			/*
+			 * String bssid_old = sessionPref.getString(BSSID, ""); String
+			 * bssid_new = HelperUtils.getBSSID(context);
+			 * 
+			 * if ((bssid_new == null || !bssid_new.equals(bssid_old)) &&
+			 * serviceBound) { Toast.makeText(getApplicationContext(),
+			 * "Connection changed! Services stopped!",
+			 * Toast.LENGTH_LONG).show(); unbindService(); }
+			 */
 			updateConnectionInfText();
 			updateConnectionInfText();
 		}
 		}
-	};	
+	};
 
 
 	/**
 	/**
 	 * Updates Information shown by the GUI.
 	 * Updates Information shown by the GUI.
 	 */
 	 */
-	private void updateUI() {		
+	private void updateUI() {
 		boolean activeListeners = false;
 		boolean activeListeners = false;
 		boolean activeHandlers = false;
 		boolean activeHandlers = false;
 		boolean yellowLight = false;
 		boolean yellowLight = false;
-		
-		//Check for all protocols if listeners are active and attacks have been recorded
-		//Update protocol lights and connection information.
-		for(String protocol : getResources().getStringArray(R.array.protocols)){
-			//Check if protocol is active
-			if(sessionPref.getBoolean(protocol + LISTENER, false)){
+
+		// Check for all protocols if listeners are active and attacks have been
+		// recorded
+		// Update protocol lights and connection information.
+		for (String protocol : getResources().getStringArray(R.array.protocols)) {
+			// Check if protocol is active
+			if (sessionPref.getBoolean(protocol + LISTENER, false)) {
 				activeListeners = true;
 				activeListeners = true;
-				int handlerCount = sessionPref.getInt(protocol + HANDLER_COUNT, 0);
-				//Check if attacks have been recorded in this session.
-				if(handlerCount > 0){
+				int handlerCount = sessionPref.getInt(protocol + HANDLER_COUNT,
+						0);
+				// Check if attacks have been recorded in this session.
+				if (handlerCount > 0) {
 					activeHandlers = true;
 					activeHandlers = true;
 					updateProtocolLight(LIGHT_RED, protocol);
 					updateProtocolLight(LIGHT_RED, protocol);
 					updateProtocolConnections(handlerCount, protocol);
 					updateProtocolConnections(handlerCount, protocol);
-				} else{
-					//Check if the bssid of the wireless network has already been recorded as infected.
-					if(logger.bssidSeen(protocol, HelperUtils.getBSSID(getApplicationContext()))){
+				} else {
+					// Check if the bssid of the wireless network has already
+					// been recorded as infected.
+					Logger.isBssidSeen(getApplicationContext(), protocol,
+							HelperUtils.getBSSID(getApplicationContext()),
+							logResultReceiver);
+					if (isBssidSeen) {
 						updateProtocolLight(LIGHT_YELLOW, protocol);
 						updateProtocolLight(LIGHT_YELLOW, protocol);
 						yellowLight = true;
 						yellowLight = true;
-					} else{
-						updateProtocolLight(LIGHT_GREEN, protocol);						
+					} else {
+						updateProtocolLight(LIGHT_GREEN, protocol);
 					}
 					}
 					updateProtocolConnections(0, protocol);
 					updateProtocolConnections(0, protocol);
 				}
 				}
-			}else{
+			} else {
 				updateProtocolLight(LIGHT_GREY, protocol);
 				updateProtocolLight(LIGHT_GREY, protocol);
 			}
 			}
 		}
 		}
 
 
-		//Update the big attack indicator.
+		// Update the big attack indicator.
 		if (activeListeners) {
 		if (activeListeners) {
 			if (activeHandlers) {
 			if (activeHandlers) {
 				updateStatusLight(LIGHT_RED);
 				updateStatusLight(LIGHT_RED);
 			} else {
 			} else {
-				if(yellowLight){
+				if (yellowLight) {
 					updateStatusLight(LIGHT_YELLOW);
 					updateStatusLight(LIGHT_YELLOW);
 				} else {
 				} else {
 					updateStatusLight(LIGHT_GREEN);
 					updateStatusLight(LIGHT_GREEN);
-				}					
+				}
 			}
 			}
 			((ToggleButton) findViewById(R.id.toggleButtonOnOff))
 			((ToggleButton) findViewById(R.id.toggleButtonOnOff))
 					.setChecked(true);
 					.setChecked(true);
@@ -548,8 +590,10 @@ public class MainActivity extends Activity {
 
 
 	/**
 	/**
 	 * Sets the big light indicator.
 	 * Sets the big light indicator.
-	 * @param light Integer code to set the light color.
-	 * @see #LIGHT_GREY 
+	 * 
+	 * @param light
+	 *            Integer code to set the light color.
+	 * @see #LIGHT_GREY
 	 * @see #LIGHT_GREEN
 	 * @see #LIGHT_GREEN
 	 * @see #LIGHT_RED
 	 * @see #LIGHT_RED
 	 * @see #LIGHT_YELLOW
 	 * @see #LIGHT_YELLOW
@@ -577,8 +621,11 @@ public class MainActivity extends Activity {
 
 
 	/**
 	/**
 	 * Sets the light indicator for a given protocol.
 	 * Sets the light indicator for a given protocol.
-	 * @param light Integer code to set the light color.
-	 * @param protocolName Name of the protocol which should be updated.
+	 * 
+	 * @param light
+	 *            Integer code to set the light color.
+	 * @param protocolName
+	 *            Name of the protocol which should be updated.
 	 */
 	 */
 	private void updateProtocolLight(int light, String protocolName) {
 	private void updateProtocolLight(int light, String protocolName) {
 		for (int i = 0; i < adapter.getCount(); ++i) {
 		for (int i = 0; i < adapter.getCount(); ++i) {
@@ -607,8 +654,11 @@ public class MainActivity extends Activity {
 
 
 	/**
 	/**
 	 * Sets the connections count for a given protocol.
 	 * Sets the connections count for a given protocol.
-	 * @param connections New value for recorded connections.
-	 * @param protocolName Name of the protocol which should be updated.
+	 * 
+	 * @param connections
+	 *            New value for recorded connections.
+	 * @param protocolName
+	 *            Name of the protocol which should be updated.
 	 */
 	 */
 	private void updateProtocolConnections(int connections, String protocolName) {
 	private void updateProtocolConnections(int connections, String protocolName) {
 		for (int i = 0; i < adapter.getCount(); ++i) {
 		for (int i = 0; i < adapter.getCount(); ++i) {
@@ -625,100 +675,105 @@ public class MainActivity extends Activity {
 	 * Gets Information about connection state and updates the GUI.
 	 * Gets Information about connection state and updates the GUI.
 	 */
 	 */
 	private void updateConnectionInfText() {
 	private void updateConnectionInfText() {
-					TextView ssidView = (TextView) findViewById(R.id.textViewSSIDValue);
-					TextView bssidView = (TextView) findViewById(R.id.textViewBSSIDValue);
-					TextView internalIPView = (TextView) findViewById(R.id.textViewInternalIPValue);
-					TextView externalIPView = (TextView) findViewById(R.id.textViewExternalIPValue);
-
-					externalIPView.setText("Loading...");
-					
-					//Update the connection information
-					updateConnectionInfo();
-					SetExternalIPTask async = new SetExternalIPTask();
-					async.execute(new String[]{"http://ip2country.sourceforge.net/ip2c.php?format=JSON"});
-					
-					//Get connection information
-					String ssid = sessionPref.getString(SSID, null);
-					String bssid = sessionPref.getString(BSSID, null);
-					String internalIP = sessionPref.getString(INTERNAL_IP, null);
-					
-					//Set text fields
-					if (ssid != null)
-						ssidView.setText(ssid);
-					else
-						ssidView.setText("-");
-					
-					if (bssid != null)
-						bssidView.setText(bssid);
-					else
-						bssidView.setText("-");
-					
-					if (internalIP != null)
-						internalIPView.setText(internalIP);
-					else
-						internalIPView.setText("-");
-	}
-	
-	/**
-	 * Updates the connection info and saves them in the the SharedPreferences for session data.
-	 * @param context Needs a context to get system recourses.
+		TextView ssidView = (TextView) findViewById(R.id.textViewSSIDValue);
+		TextView bssidView = (TextView) findViewById(R.id.textViewBSSIDValue);
+		TextView internalIPView = (TextView) findViewById(R.id.textViewInternalIPValue);
+		TextView externalIPView = (TextView) findViewById(R.id.textViewExternalIPValue);
+
+		externalIPView.setText("Loading...");
+
+		// Update the connection information
+		updateConnectionInfo();
+		SetExternalIPTask async = new SetExternalIPTask();
+		async.execute(new String[] { "http://ip2country.sourceforge.net/ip2c.php?format=JSON" });
+
+		// Get connection information
+		String ssid = sessionPref.getString(SSID, null);
+		String bssid = sessionPref.getString(BSSID, null);
+		String internalIP = sessionPref.getString(INTERNAL_IP, null);
+
+		// Set text fields
+		if (ssid != null)
+			ssidView.setText(ssid);
+		else
+			ssidView.setText("-");
+
+		if (bssid != null)
+			bssidView.setText(bssid);
+		else
+			bssidView.setText("-");
+
+		if (internalIP != null)
+			internalIPView.setText(internalIP);
+		else
+			internalIPView.setText("-");
+	}
+
+	/**
+	 * Updates the connection info and saves them in the the SharedPreferences
+	 * for session data.
+	 * 
+	 * @param context
+	 *            Needs a context to get system recourses.
 	 * @see MainActivity#SESSION_DATA
 	 * @see MainActivity#SESSION_DATA
 	 */
 	 */
-	private void updateConnectionInfo() {	
-		SharedPreferences pref = context.getSharedPreferences(MainActivity.SESSION_DATA, Context.MODE_PRIVATE);
+	private void updateConnectionInfo() {
+		SharedPreferences pref = context.getSharedPreferences(
+				MainActivity.SESSION_DATA, Context.MODE_PRIVATE);
 		Editor editor = pref.edit();
 		Editor editor = pref.edit();
 		editor.putString(MainActivity.SSID, HelperUtils.getSSID(context));
 		editor.putString(MainActivity.SSID, HelperUtils.getSSID(context));
 		editor.putString(MainActivity.BSSID, HelperUtils.getBSSID(context));
 		editor.putString(MainActivity.BSSID, HelperUtils.getBSSID(context));
-		editor.putString(MainActivity.INTERNAL_IP, HelperUtils.getInternalIP(context));
+		editor.putString(MainActivity.INTERNAL_IP,
+				HelperUtils.getInternalIP(context));
 		editor.commit();
 		editor.commit();
-	}	
-	
+	}
+
 	/**
 	/**
 	 * Task to find out the external IP.
 	 * Task to find out the external IP.
+	 * 
 	 * @author Lars Pandikow
 	 * @author Lars Pandikow
 	 */
 	 */
-	private class SetExternalIPTask extends AsyncTask<String, Void, String>{	
-		 @Override
-		    protected String doInBackground(String... url) {
-		   	 String ipAddress = null;
-					try {
-						HttpClient httpclient = new DefaultHttpClient();
-						HttpGet httpget = new HttpGet(url[0]);
-						HttpResponse response;
-
-						response = httpclient.execute(httpget);
-
-						HttpEntity entity = response.getEntity();
-						entity.getContentLength();
-						String str = EntityUtils.toString(entity);
-						JSONObject json_data = new JSONObject(str);
-						ipAddress = json_data.getString("ip");
-					} catch (Exception e) {
-						e.printStackTrace();
-					}
-			return ipAddress;
-		    }
-			 
-			@Override
-			protected void onPostExecute(String result){
-				sessionEditor.putString(MainActivity.EXTERNAL_IP, result);
-				sessionEditor.commit();
-				TextView externalIPView = (TextView) findViewById(R.id.textViewExternalIPValue);
-				if (result != null)
-					externalIPView.setText(result);
-				else
-					externalIPView.setText("-");	
+	private class SetExternalIPTask extends AsyncTask<String, Void, String> {
+		@Override
+		protected String doInBackground(String... url) {
+			String ipAddress = null;
+			try {
+				HttpClient httpclient = new DefaultHttpClient();
+				HttpGet httpget = new HttpGet(url[0]);
+				HttpResponse response;
+
+				response = httpclient.execute(httpget);
+
+				HttpEntity entity = response.getEntity();
+				entity.getContentLength();
+				String str = EntityUtils.toString(entity);
+				JSONObject json_data = new JSONObject(str);
+				ipAddress = json_data.getString("ip");
+			} catch (Exception e) {
+				e.printStackTrace();
 			}
 			}
-		};
+			return ipAddress;
+		}
 
 
+		@Override
+		protected void onPostExecute(String result) {
+			sessionEditor.putString(MainActivity.EXTERNAL_IP, result);
+			sessionEditor.commit();
+			TextView externalIPView = (TextView) findViewById(R.id.textViewExternalIPValue);
+			if (result != null)
+				externalIPView.setText(result);
+			else
+				externalIPView.setText("-");
+		}
+	};
+
+	/* ############# Help functions for animation ################## */
 
 
-	/*############# Help functions for animation ##################*/
-	
 	@Override
 	@Override
 	public boolean onTouchEvent(MotionEvent event) {
 	public boolean onTouchEvent(MotionEvent event) {
 		return gestureDetector.onTouchEvent(event);
 		return gestureDetector.onTouchEvent(event);
 	}
 	}
-	
+
 	/**
 	/**
 	 * Initializes variables for screen animation
 	 * Initializes variables for screen animation
 	 */
 	 */
@@ -735,7 +790,7 @@ public class MainActivity extends Activity {
 		animFlipOutRL = AnimationUtils.loadAnimation(this,
 		animFlipOutRL = AnimationUtils.loadAnimation(this,
 				R.anim.out_right_to_left);
 				R.anim.out_right_to_left);
 	}
 	}
-	
+
 	/**
 	/**
 	 * Called when a swipe to the Left is registered.
 	 * Called when a swipe to the Left is registered.
 	 */
 	 */
@@ -775,9 +830,10 @@ public class MainActivity extends Activity {
 
 
 	/**
 	/**
 	 * Returns the context of the App.
 	 * Returns the context of the App.
+	 * 
 	 * @return context.
 	 * @return context.
 	 */
 	 */
-    public static Context getContext() {
-        return MainActivity.context;
-    }
+	public static Context getContext() {
+		return MainActivity.context;
+	}
 }
 }

+ 15 - 15
src/de/tudarmstadt/informatik/hostage/ui/PlayGroundActivity.java

@@ -12,7 +12,7 @@ import android.view.Menu;
 import android.view.View;
 import android.view.View;
 import android.widget.TextView;
 import android.widget.TextView;
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.logging.DatabaseHandler;
+import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
 import de.tudarmstadt.informatik.hostage.sync.BluetoothSync;
 import de.tudarmstadt.informatik.hostage.sync.BluetoothSync;
 import de.tudarmstadt.informatik.hostage.sync.NFCSync;
 import de.tudarmstadt.informatik.hostage.sync.NFCSync;
 
 
@@ -35,17 +35,17 @@ public class PlayGroundActivity extends Activity{
 	}
 	}
 	
 	
 	private void setNetworkInfoText(){		
 	private void setNetworkInfoText(){		
-		DatabaseHandler dbh = new DatabaseHandler(this);
+		UglyDbHelper dbh = new UglyDbHelper(this);
 		TextView bssids = (TextView) findViewById(R.id.textView1);
 		TextView bssids = (TextView) findViewById(R.id.textView1);
 		String text = "";
 		String text = "";
 		ArrayList<HashMap<String, Object>> netInfo = dbh.getNetworkInformation();
 		ArrayList<HashMap<String, Object>> netInfo = dbh.getNetworkInformation();
 		for(HashMap<String, Object> network : netInfo){
 		for(HashMap<String, Object> network : netInfo){
-			text = text + (String) network.get(DatabaseHandler.KEY_BSSID) + "\n"
-    					+ (String) network.get(DatabaseHandler.KEY_SSID) + "\n"
-    					+ (double)(Double) network.get(DatabaseHandler.KEY_LATITUDE) + "\n"
-    			 		+ (double)(Double) network.get(DatabaseHandler.KEY_LONGITUDE) + "\n"
-    			 		+ (float)(Float) network.get(DatabaseHandler.KEY_ACCURACY) + "\n"
-    			 		+ (long) (Long) network.get(DatabaseHandler.KEY_TIME) + "\n\n";			
+			text = text + (String) network.get(UglyDbHelper.KEY_BSSID) + "\n"
+    					+ (String) network.get(UglyDbHelper.KEY_SSID) + "\n"
+    					+ (double)(Double) network.get(UglyDbHelper.KEY_LATITUDE) + "\n"
+    			 		+ (double)(Double) network.get(UglyDbHelper.KEY_LONGITUDE) + "\n"
+    			 		+ (float)(Float) network.get(UglyDbHelper.KEY_ACCURACY) + "\n"
+    			 		+ (long) (Long) network.get(UglyDbHelper.KEY_TIME) + "\n\n";			
 		}
 		}
 		bssids.setText(text);
 		bssids.setText(text);
 	}
 	}
@@ -62,17 +62,17 @@ public class PlayGroundActivity extends Activity{
 		ArrayList<HashMap<String, Object>> fakeNetInfo = new ArrayList<HashMap<String, Object>>();
 		ArrayList<HashMap<String, Object>> fakeNetInfo = new ArrayList<HashMap<String, Object>>();
 		for(int i = 0; i < 25; i++){
 		for(int i = 0; i < 25; i++){
 			HashMap<String, Object> network = new HashMap<String, Object>();
 			HashMap<String, Object> network = new HashMap<String, Object>();
-			network.put(DatabaseHandler.KEY_BSSID, createRandomBSSID());
-			network.put(DatabaseHandler.KEY_SSID, new BigInteger(130, rnd).toString(32));
-			network.put(DatabaseHandler.KEY_LATITUDE, rnd.nextDouble() * 360);
-			network.put(DatabaseHandler.KEY_LONGITUDE, rnd.nextDouble() * 360);
-			network.put(DatabaseHandler.KEY_ACCURACY, rnd.nextFloat());
-			network.put(DatabaseHandler.KEY_TIME, System.currentTimeMillis());
+			network.put(UglyDbHelper.KEY_BSSID, createRandomBSSID());
+			network.put(UglyDbHelper.KEY_SSID, new BigInteger(130, rnd).toString(32));
+			network.put(UglyDbHelper.KEY_LATITUDE, rnd.nextDouble() * 360);
+			network.put(UglyDbHelper.KEY_LONGITUDE, rnd.nextDouble() * 360);
+			network.put(UglyDbHelper.KEY_ACCURACY, rnd.nextFloat());
+			network.put(UglyDbHelper.KEY_TIME, System.currentTimeMillis());
 			fakeNetInfo.add(network);
 			fakeNetInfo.add(network);
 		}
 		}
 
 
 		setNetworkInfoText();
 		setNetworkInfoText();
-		new DatabaseHandler(this).updateNetworkInformation(fakeNetInfo);
+		new UglyDbHelper(this).updateNetworkInformation(fakeNetInfo);
 	}
 	}
 	
 	
 	private String createRandomBSSID(){
 	private String createRandomBSSID(){

+ 189 - 145
src/de/tudarmstadt/informatik/hostage/ui/ViewLog.java

@@ -40,24 +40,24 @@ import android.widget.TimePicker;
 import android.widget.Toast;
 import android.widget.Toast;
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
-import de.tudarmstadt.informatik.hostage.logging.Logger;
 import de.tudarmstadt.informatik.hostage.logging.Record;
 import de.tudarmstadt.informatik.hostage.logging.Record;
-import de.tudarmstadt.informatik.hostage.logging.SQLLogger;
+import de.tudarmstadt.informatik.hostage.logging.formatter.TraCINgFormatter;
+
 /**
 /**
- * ViewLog shows Statistics about the recorded Attacks.
- * It also offers the user several options to perform actions with the database.
- * This includes:<br>
+ * ViewLog shows Statistics about the recorded Attacks. It also offers the user
+ * several options to perform actions with the database. This includes:<br>
  * - show records,<br>
  * - show records,<br>
  * - export records,<br>
  * - export records,<br>
  * - upload records,<br>
  * - upload records,<br>
  * - and delete records.
  * - and delete records.
+ * 
  * @author Lars Pandikow
  * @author Lars Pandikow
  */
  */
 public class ViewLog extends Activity {
 public class ViewLog extends Activity {
-	
-	private final SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm", Locale.US);
 
 
-	private Logger logger;
+	private final SimpleDateFormat sdf = new SimpleDateFormat(
+			"MMM dd,yyyy HH:mm", Locale.US);
+
 	private SharedPreferences pref;
 	private SharedPreferences pref;
 	private Editor editor;
 	private Editor editor;
 
 
@@ -65,7 +65,6 @@ public class ViewLog extends Activity {
 	protected void onCreate(Bundle savedInstanceState) {
 	protected void onCreate(Bundle savedInstanceState) {
 		super.onCreate(savedInstanceState);
 		super.onCreate(savedInstanceState);
 		setContentView(R.layout.activity_viewlog);
 		setContentView(R.layout.activity_viewlog);
-		logger = new SQLLogger(this);
 		pref = PreferenceManager.getDefaultSharedPreferences(this);
 		pref = PreferenceManager.getDefaultSharedPreferences(this);
 		editor = pref.edit();
 		editor = pref.edit();
 		initStatistic();
 		initStatistic();
@@ -79,23 +78,25 @@ public class ViewLog extends Activity {
 
 
 	@Override
 	@Override
 	public boolean onOptionsItemSelected(MenuItem item) {
 	public boolean onOptionsItemSelected(MenuItem item) {
-	    // Handle item selection
-	    switch (item.getItemId()) {
-	        case R.id.action_settings:
-	            startActivity(new Intent(this, SettingsActivity.class));
-	            break;
-	        case R.id.action_about:
-	            startActivity(new Intent(this, AboutActivity.class));
-	            break;
-	        default:
-	    }
-        return super.onOptionsItemSelected(item);
+		// Handle item selection
+		switch (item.getItemId()) {
+		case R.id.action_settings:
+			startActivity(new Intent(this, SettingsActivity.class));
+			break;
+		case R.id.action_about:
+			startActivity(new Intent(this, AboutActivity.class));
+			break;
+		default:
+		}
+		return super.onOptionsItemSelected(item);
 	}
 	}
 
 
 	/**
 	/**
-	 * Creates a Dialog to choose export format.
-	 * Then calls {@link ViewLog#exportDatabase(int)}
-	 * @param view View elements which triggers the method call.
+	 * Creates a Dialog to choose export format. Then calls
+	 * {@link ViewLog#exportDatabase(int)}
+	 * 
+	 * @param view
+	 *            View elements which triggers the method call.
 	 */
 	 */
 	public void exportDatabase(View view) {
 	public void exportDatabase(View view) {
 		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 		AlertDialog.Builder builder = new AlertDialog.Builder(this);
@@ -108,77 +109,102 @@ public class ViewLog extends Activity {
 		builder.create();
 		builder.create();
 		builder.show();
 		builder.show();
 	}
 	}
-	
+
 	/**
 	/**
-	 * Exports all records in a given format. Before exporting checks export location from preferences.
-	 * @param format Integer coded export format
+	 * Exports all records in a given format. Before exporting checks export
+	 * location from preferences.
+	 * 
+	 * @param format
+	 *            Integer coded export format
 	 * @see Record#toString(int)
 	 * @see Record#toString(int)
 	 */
 	 */
-	private void exportDatabase(int format){
+	private void exportDatabase(int format) {
 		try {
 		try {
 			FileOutputStream log;
 			FileOutputStream log;
-			String filename = "hostage_" + format + "_" + System.currentTimeMillis() + ".log";
-			boolean externalStorage = pref.getBoolean("pref_external_storage", false);
-			String externalLocation = pref.getString("pref_external_location", "");
-			if(externalStorage){
-				String root = Environment.getExternalStorageDirectory().toString();
-				if(root != null && HelperUtils.isExternalStorageWritable()){					
+			String filename = "hostage_" + format + "_"
+					+ System.currentTimeMillis() + ".log";
+			boolean externalStorage = pref.getBoolean("pref_external_storage",
+					false);
+			String externalLocation = pref.getString("pref_external_location",
+					"");
+			if (externalStorage) {
+				String root = Environment.getExternalStorageDirectory()
+						.toString();
+				if (root != null && HelperUtils.isExternalStorageWritable()) {
 					File dir = new File(root + externalLocation);
 					File dir = new File(root + externalLocation);
 					dir.mkdirs();
 					dir.mkdirs();
 					File file = new File(dir, filename);
 					File file = new File(dir, filename);
 					log = new FileOutputStream(file);
 					log = new FileOutputStream(file);
-				}else {
-					Toast.makeText(this, "Could not write to SD Card", Toast.LENGTH_SHORT).show();
+				} else {
+					Toast.makeText(this, "Could not write to SD Card",
+							Toast.LENGTH_SHORT).show();
 					return;
 					return;
 				}
 				}
 
 
-			} else{
-				log = this.openFileOutput("hostage_" + format + "_" + System.currentTimeMillis() + ".log", Context.MODE_PRIVATE);
+			} else {
+				log = this.openFileOutput(
+						"hostage_" + format + "_" + System.currentTimeMillis()
+								+ ".log", Context.MODE_PRIVATE);
 			}
 			}
-			
-			ArrayList<Record> records = logger.getAllRecords();
-			for(Record record : records){
-					log.write((record.toString(format)).getBytes());
+
+			ArrayList<Record> records = null;// logger.getAllRecords();
+			for (Record record : records) {
+				log.write((record.toString((format == 1) ? TraCINgFormatter
+						.getInstance() : null)).getBytes());
 			}
 			}
 			log.flush();
 			log.flush();
 			log.close();
 			log.close();
-			Toast.makeText(this, externalStorage ? filename + " saved on external memory! " + externalLocation : filename + " saved on internal memory!", Toast.LENGTH_LONG).show();
+			Toast.makeText(
+					this,
+					externalStorage ? filename + " saved on external memory! "
+							+ externalLocation : filename
+							+ " saved on internal memory!", Toast.LENGTH_LONG)
+					.show();
 		} catch (Exception e) {
 		} catch (Exception e) {
-			Toast.makeText(this, "Could not write to SD Card", Toast.LENGTH_SHORT).show();
+			Toast.makeText(this, "Could not write to SD Card",
+					Toast.LENGTH_SHORT).show();
 			e.printStackTrace();
 			e.printStackTrace();
-		}	
+		}
 	}
 	}
-	
+
 	/**
 	/**
-	 * Uploads a JSON Representation of each attack to a server, specified in the preferences.<br>
-	 * The method only uploads information about attacks that have net been uploaded yet.<br>
-	 * The local and remote IP of each record will be replaced with the external IP of then device at the time of the upload.
-	 * For the Upload it uses a HttpPost with a HttpsClient, which does not validate any certificates.<br>
+	 * Uploads a JSON Representation of each attack to a server, specified in
+	 * the preferences.<br>
+	 * The method only uploads information about attacks that have net been
+	 * uploaded yet.<br>
+	 * The local and remote IP of each record will be replaced with the external
+	 * IP of then device at the time of the upload. For the Upload it uses a
+	 * HttpPost with a HttpsClient, which does not validate any certificates.<br>
 	 * The Upload runs in its own Thread.<br>
 	 * The Upload runs in its own Thread.<br>
-	 * While uploading the method also creates a notification to inform the user about the status of the upload.<br>
+	 * While uploading the method also creates a notification to inform the user
+	 * about the status of the upload.<br>
 	 * <b>Only uploads Records with a external IP that is not null!
 	 * <b>Only uploads Records with a external IP that is not null!
-	 * @param  view View elements which triggers the method call.
+	 * 
+	 * @param view
+	 *            View elements which triggers the method call.
 	 * @see de.tudarmstadt.informatik.hostage.net.MySSLSocketFactory
 	 * @see de.tudarmstadt.informatik.hostage.net.MySSLSocketFactory
 	 */
 	 */
-	public void uploadDatabase(View view){
-		//Create a Notification
+	public void uploadDatabase(View view) {
+		// Create a Notification
 		final NotificationCompat.Builder builder;
 		final NotificationCompat.Builder builder;
 		final NotificationManager mNotifyManager;
 		final NotificationManager mNotifyManager;
-		final int lastUploadedAttackId = pref.getInt("LAST_UPLOADED_ATTACK_ID", -1);
+		final int lastUploadedAttackId = pref.getInt("LAST_UPLOADED_ATTACK_ID",
+				-1);
 		int currentAttackId = pref.getInt("ATTACK_ID_COUNTER", 0);
 		int currentAttackId = pref.getInt("ATTACK_ID_COUNTER", 0);
 		// Check if there are new records to upload
 		// Check if there are new records to upload
-		if(lastUploadedAttackId == currentAttackId -1){
+		if (lastUploadedAttackId == currentAttackId - 1) {
 			// Inform user that no upload is necessary
 			// Inform user that no upload is necessary
-			Toast.makeText(this, "All data have already been uploaded.", Toast.LENGTH_SHORT).show();
+			Toast.makeText(this, "All data have already been uploaded.",
+					Toast.LENGTH_SHORT).show();
 			return;
 			return;
 		}
 		}
 		// Build and show Upload Notification in notification bar
 		// Build and show Upload Notification in notification bar
 		builder = new NotificationCompat.Builder(this)
 		builder = new NotificationCompat.Builder(this)
-							.setContentTitle(this.getString(R.string.app_name))
-							.setContentText("Upload in progress...")
-							.setTicker("Uploading Data...")
-							.setSmallIcon(R.drawable.ic_launcher)	
-							.setWhen(System.currentTimeMillis());	
+				.setContentTitle(this.getString(R.string.app_name))
+				.setContentText("Upload in progress...")
+				.setTicker("Uploading Data...")
+				.setSmallIcon(R.drawable.ic_launcher)
+				.setWhen(System.currentTimeMillis());
 		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
 		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
 		stackBuilder.addParentStack(MainActivity.class);
 		stackBuilder.addParentStack(MainActivity.class);
 		stackBuilder.addNextIntent(new Intent());
 		stackBuilder.addNextIntent(new Intent());
@@ -192,67 +218,71 @@ public class ViewLog extends Activity {
 		final Context context = this;
 		final Context context = this;
 		// Create a new Thread for upload
 		// Create a new Thread for upload
 		new Thread(new Runnable() {
 		new Thread(new Runnable() {
-			  public void run() {	
-					// get RecordList
-					ArrayList<Record> recordList = logger.getRecordOfEachAttack(lastUploadedAttackId);
-					final int progressMax = recordList.size();		
-					Log.i("SQLLogger", "Logs to upload: " + progressMax);	
-							
-							int progressBarStatus = 0;
-							int retry_counter = 0;
-							while(progressBarStatus < progressMax){
-								Record record = recordList.get(progressBarStatus);
-								// Only upload records with a saved external ip
-								if(record.getExternalIP() != null){
-									retry_counter = 0;
-									if(HelperUtils.uploadSingleRecord(context, record)){
-										// Update Notification progress bar
-										progressBarStatus++;								
-										builder.setProgress(progressMax, progressBarStatus, false);
-					                     // Update the progress bar
-										mNotifyManager.notify(2, builder.build());
-									}else{
-										retry_counter++;
-										if(retry_counter == 3){
-											retry_counter = 0;
-											progressBarStatus++;
-										}	
-									}						
-								}
-							}	
-							
-					if(progressBarStatus == progressMax){
-						// When the loop is finished, updates the notification
-			            builder.setContentText("Upload complete")
-			            	   .setTicker("Upload complete")
-			            // Removes the progress bar
-			                   .setProgress(0,0,false);
-			            mNotifyManager.notify(2, builder.build());
-			        }
-			}}).start();
-		editor.putInt("LAST_UPLOADED_ATTACK_ID",currentAttackId - 1);
-		editor.commit();				
-	}
-	
+			public void run() {
+				// get RecordList
+				ArrayList<Record> recordList = null;// logger.getRecordOfEachAttack(lastUploadedAttackId);
+				final int progressMax = recordList.size();
+				Log.i("SQLLogger", "Logs to upload: " + progressMax);
+
+				int progressBarStatus = 0;
+				int retry_counter = 0;
+				while (progressBarStatus < progressMax) {
+					Record record = recordList.get(progressBarStatus);
+					// Only upload records with a saved external ip
+					if (record.getExternalIP() != null) {
+						retry_counter = 0;
+						if (HelperUtils.uploadSingleRecord(context, record)) {
+							// Update Notification progress bar
+							progressBarStatus++;
+							builder.setProgress(progressMax, progressBarStatus,
+									false);
+							// Update the progress bar
+							mNotifyManager.notify(2, builder.build());
+						} else {
+							retry_counter++;
+							if (retry_counter == 3) {
+								retry_counter = 0;
+								progressBarStatus++;
+							}
+						}
+					}
+				}
 
 
+				if (progressBarStatus == progressMax) {
+					// When the loop is finished, updates the notification
+					builder.setContentText("Upload complete")
+							.setTicker("Upload complete")
+							// Removes the progress bar
+							.setProgress(0, 0, false);
+					mNotifyManager.notify(2, builder.build());
+				}
+			}
+		}).start();
+		editor.putInt("LAST_UPLOADED_ATTACK_ID", currentAttackId - 1);
+		editor.commit();
+	}
 
 
 	/**
 	/**
 	 * Starts a ViewLogTable Activity.
 	 * Starts a ViewLogTable Activity.
-	 * @param view View elements which triggers the method call.
+	 * 
+	 * @param view
+	 *            View elements which triggers the method call.
 	 * @see ViewLogTable
 	 * @see ViewLogTable
 	 */
 	 */
 	public void showLog(View view) {
 	public void showLog(View view) {
 		startActivity(new Intent(this, ViewLogTable.class));
 		startActivity(new Intent(this, ViewLogTable.class));
-		//TODO Delete
-		
+		// TODO Delete
+
 	}
 	}
 
 
 	/**
 	/**
-	 * Creates a Dialog that lets the user decide which criteria he want to use to delete records.
-	 * Then calls the corresponding method.<br>
-	 * The possible criteria are coded in /res/values/arrays.xml
-	 * To add a criteria add a String to the array and extend the switch statement.
-	 * @param view View elements which triggers the method call.
+	 * Creates a Dialog that lets the user decide which criteria he want to use
+	 * to delete records. Then calls the corresponding method.<br>
+	 * The possible criteria are coded in /res/values/arrays.xml To add a
+	 * criteria add a String to the array and extend the switch statement.
+	 * 
+	 * @param view
+	 *            View elements which triggers the method call.
 	 * @see ViewLog#deleteByBSSID()
 	 * @see ViewLog#deleteByBSSID()
 	 * @see ViewLog#deleteByDate()
 	 * @see ViewLog#deleteByDate()
 	 * @see ViewLog#deleteAll()
 	 * @see ViewLog#deleteAll()
@@ -278,25 +308,28 @@ public class ViewLog extends Activity {
 		builder.create();
 		builder.create();
 		builder.show();
 		builder.show();
 	}
 	}
-	
+
 	/**
 	/**
-	 * Shows a List with all recorded BSSIDs.
-	 * If a BSSID is selected the method calls {@link Logger#deleteByBSSID(String)} to delete all records with the chosen BSSID
-	 * @see Logger#deleteByBSSID
+	 * Shows a List with all recorded BSSIDs. If a BSSID is selected the method
+	 * calls {@link ILogger#deleteByBSSID(String)} to delete all records with
+	 * the chosen BSSID
+	 * 
+	 * @see ILogger#deleteByBSSID
 	 */
 	 */
 	private void deleteByBSSID() {
 	private void deleteByBSSID() {
 		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 		AlertDialog.Builder builder = new AlertDialog.Builder(this);
-		final String[] bssidArray = logger.getAllBSSIDS();
+		final String[] bssidArray = null;// logger.getAllBSSIDS();
 		final String[] strings = new String[bssidArray.length];
 		final String[] strings = new String[bssidArray.length];
-		for(int i = 0; i < bssidArray.length; i++){
-			strings[i] = bssidArray[i] + " (" + logger.getSSID(bssidArray[i]) +")";
+		for (int i = 0; i < bssidArray.length; i++) {
+			strings[i] = bssidArray[i] + " (" // + logger.getSSID(bssidArray[i])
+					+ ")";
 		}
 		}
 		builder.setTitle(R.string.delete_dialog_title);
 		builder.setTitle(R.string.delete_dialog_title);
 		builder.setItems(strings, new DialogInterface.OnClickListener() {
 		builder.setItems(strings, new DialogInterface.OnClickListener() {
 			@SuppressLint("NewApi")
 			@SuppressLint("NewApi")
 			public void onClick(DialogInterface dialog, int position) {
 			public void onClick(DialogInterface dialog, int position) {
-				
-				logger.deleteByBSSID(bssidArray[position]);
+
+				// logger.deleteByBSSID(bssidArray[position]);
 				Toast.makeText(
 				Toast.makeText(
 						getApplicationContext(),
 						getApplicationContext(),
 						"All entries with bssid '" + bssidArray[position]
 						"All entries with bssid '" + bssidArray[position]
@@ -315,13 +348,13 @@ public class ViewLog extends Activity {
 	}
 	}
 
 
 	/**
 	/**
-	 * Creates a DatePicking Dialog where the user can choose a date. Afterwards {@link ViewLog#deleteByDate(int, int, int)} is called.
+	 * Creates a DatePicking Dialog where the user can choose a date. Afterwards
+	 * {@link ViewLog#deleteByDate(int, int, int)} is called.
 	 */
 	 */
 	private void deleteByDate() {
 	private void deleteByDate() {
 		showDialog(0);
 		showDialog(0);
 	}
 	}
 
 
-
 	@Override
 	@Override
 	protected Dialog onCreateDialog(int id) {
 	protected Dialog onCreateDialog(int id) {
 		switch (id) {
 		switch (id) {
@@ -330,18 +363,24 @@ public class ViewLog extends Activity {
 			int pYear = cal.get(Calendar.YEAR);
 			int pYear = cal.get(Calendar.YEAR);
 			int pMonth = cal.get(Calendar.MONTH);
 			int pMonth = cal.get(Calendar.MONTH);
 			int pDay = cal.get(Calendar.DAY_OF_MONTH);
 			int pDay = cal.get(Calendar.DAY_OF_MONTH);
-			return new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
-				public void onDateSet(DatePicker view, int year, int monthOfYear,
-						int dayOfMonth) {deleteByDate(year, monthOfYear, dayOfMonth);}}
-			, pYear, pMonth, pDay);
+			return new DatePickerDialog(this,
+					new DatePickerDialog.OnDateSetListener() {
+						public void onDateSet(DatePicker view, int year,
+								int monthOfYear, int dayOfMonth) {
+							deleteByDate(year, monthOfYear, dayOfMonth);
+						}
+					}, pYear, pMonth, pDay);
 		}
 		}
 		return null;
 		return null;
 	}
 	}
 
 
 	/**
 	/**
-	 * Shows a Dialog with the given date and ask him to confirm deleting records that are older than the shown date.
-	 * When the user confirms {@link Logger#deleteByDate(long)} is called with a long representation of the Date.
-	 * If the user cancels the Dialog nothing happens and the dialog disappears.
+	 * Shows a Dialog with the given date and ask him to confirm deleting
+	 * records that are older than the shown date. When the user confirms
+	 * {@link ILogger#deleteByDate(long)} is called with a long representation
+	 * of the Date. If the user cancels the Dialog nothing happens and the
+	 * dialog disappears.
+	 * 
 	 * @param year
 	 * @param year
 	 * @param monthOfYear
 	 * @param monthOfYear
 	 * @param dayOfMonth
 	 * @param dayOfMonth
@@ -360,7 +399,7 @@ public class ViewLog extends Activity {
 							public void onClick(DialogInterface dialog, int id) {
 							public void onClick(DialogInterface dialog, int id) {
 								long time = calendar.getTimeInMillis();
 								long time = calendar.getTimeInMillis();
 								// Delete Data
 								// Delete Data
-								logger.deleteByDate(time);
+								// logger.deleteByDate(time);
 								Toast.makeText(getApplicationContext(),
 								Toast.makeText(getApplicationContext(),
 										"Data sets deleted!",
 										"Data sets deleted!",
 										Toast.LENGTH_SHORT).show();
 										Toast.LENGTH_SHORT).show();
@@ -386,9 +425,10 @@ public class ViewLog extends Activity {
 	}
 	}
 
 
 	/**
 	/**
-	 * Shows a Dialog to confirm that the database should be cleared.
-	 * If confirmed {@link SQLLogger#clearData()} is called.
-	 * @see Logger#clearData()
+	 * Shows a Dialog to confirm that the database should be cleared. If
+	 * confirmed {@link SQLLogger#clearData()} is called.
+	 * 
+	 * @see ILogger#clearData()
 	 */
 	 */
 	private void deleteAll() {
 	private void deleteAll() {
 		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 		AlertDialog.Builder builder = new AlertDialog.Builder(this);
@@ -398,7 +438,7 @@ public class ViewLog extends Activity {
 							@SuppressLint("NewApi")
 							@SuppressLint("NewApi")
 							public void onClick(DialogInterface dialog, int id) {
 							public void onClick(DialogInterface dialog, int id) {
 								// Clear all Data
 								// Clear all Data
-								logger.clearData();
+								// logger.clearData();
 								editor.putInt("ATTACK_ID_COUNTER", 0);
 								editor.putInt("ATTACK_ID_COUNTER", 0);
 								editor.putInt("LAST_UPLOADED_ATTACK_ID", -1);
 								editor.putInt("LAST_UPLOADED_ATTACK_ID", -1);
 								editor.commit();
 								editor.commit();
@@ -427,10 +467,12 @@ public class ViewLog extends Activity {
 	}
 	}
 
 
 	/**
 	/**
-	 * Initializes the Statistics. Creates a table row for every protocol and checks the dabase for the attack count.
-	 * Calls {@link ViewLog#setFirstAndLastAttack()} to set the TextViews.
-	 * @see Logger#getAttackCount()
-	 * @see Logger#getAttackPerProtokolCount(String)
+	 * Initializes the Statistics. Creates a table row for every protocol and
+	 * checks the dabase for the attack count. Calls
+	 * {@link ViewLog#setFirstAndLastAttack()} to set the TextViews.
+	 * 
+	 * @see ILogger#getAttackCount()
+	 * @see ILogger#getAttackPerProtocolCount(String)
 	 */
 	 */
 	private void initStatistic() {
 	private void initStatistic() {
 		TableLayout table = (TableLayout) findViewById(R.id.layoutContainer);
 		TableLayout table = (TableLayout) findViewById(R.id.layoutContainer);
@@ -456,9 +498,10 @@ public class ViewLog extends Activity {
 			value.setPadding(3, 0, 3, 0);
 			value.setPadding(3, 0, 3, 0);
 			row.addView(value);
 			row.addView(value);
 			if (protocol.equals("Total")) {
 			if (protocol.equals("Total")) {
-				value.setText("" + logger.getAttackCount());
+				value.setText(""); // + logger.getAttackCount());
 			} else {
 			} else {
-				value.setText("" + logger.getAttackPerProtokolCount(protocol));
+				value.setText("");// +
+									// logger.getAttackPerProtocolCount(protocol));
 			}
 			}
 			table.addView(row);
 			table.addView(row);
 		}
 		}
@@ -467,13 +510,14 @@ public class ViewLog extends Activity {
 
 
 	/**
 	/**
 	 * Sets the TextViews for first and last attack.
 	 * Sets the TextViews for first and last attack.
-	 * @see Logger#getSmallestAttackId()
-	 * @see Logger#getHighestAttackId()
-	 * @see Logger#getRecordOfAttackId(long)
+	 * 
+	 * @see ILogger#getSmallestAttackId()
+	 * @see ILogger#getHighestAttackId()
+	 * @see ILogger#getRecordOfAttackId(long)
 	 */
 	 */
 	private void setFirstAndLastAttack() {
 	private void setFirstAndLastAttack() {
-		Record firstAttack = logger.getRecordOfAttackId(logger.getSmallestAttackId());
-		Record lastAttack = logger.getRecordOfAttackId(logger.getHighestAttackId());
+		Record firstAttack = null;// logger.getRecordOfAttackId(logger.getSmallestAttackId());
+		Record lastAttack = null;// logger.getRecordOfAttackId(logger.getHighestAttackId());
 		if (firstAttack != null) {
 		if (firstAttack != null) {
 			Date resultdate = new Date(firstAttack.getTimestamp());
 			Date resultdate = new Date(firstAttack.getTimestamp());
 			TextView text = (TextView) findViewById(R.id.textFirstAttackValue);
 			TextView text = (TextView) findViewById(R.id.textFirstAttackValue);

+ 12 - 10
src/de/tudarmstadt/informatik/hostage/ui/ViewLogTable.java

@@ -4,26 +4,28 @@ import android.app.Activity;
 import android.os.Bundle;
 import android.os.Bundle;
 import android.widget.ScrollView;
 import android.widget.ScrollView;
 import android.widget.TextView;
 import android.widget.TextView;
-import de.tudarmstadt.informatik.hostage.logging.DatabaseHandler;
+import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
 import de.tudarmstadt.informatik.hostage.logging.Record;
 import de.tudarmstadt.informatik.hostage.logging.Record;
 
 
 /**
 /**
- * Creates a simple log view. Shows the Information for every attack. The format ist defined in {@link Record#toString(int)}.
+ * Creates a simple log view. Shows the Information for every attack. The format
+ * ist defined in {@link Record#toString(int)}.
+ * 
  * @author Lars Pandikow
  * @author Lars Pandikow
- *
+ * 
  */
  */
-public class ViewLogTable extends Activity{
-	
+public class ViewLogTable extends Activity {
+
 	@Override
 	@Override
 	protected void onCreate(Bundle savedInstanceState) {
 	protected void onCreate(Bundle savedInstanceState) {
 		super.onCreate(savedInstanceState);
 		super.onCreate(savedInstanceState);
-		DatabaseHandler dbh = new DatabaseHandler(getBaseContext());
+		UglyDbHelper dbh = new UglyDbHelper(getBaseContext());
 		StringBuffer log = new StringBuffer();
 		StringBuffer log = new StringBuffer();
-		//Create a log entry for every attack in the Database
-		for(Record record: dbh.getAllRecords()) {
-			log.append(record.toString(0));
+		// Create a log entry for every attack in the Database
+		for (Record record : dbh.getAllRecords()) {
+			log.append(record.toString());
 		}
 		}
-		
+
 		ScrollView scroll = new ScrollView(this);
 		ScrollView scroll = new ScrollView(this);
 		TextView text = new TextView(getApplicationContext());
 		TextView text = new TextView(getApplicationContext());
 		text.setText(log);
 		text.setText(log);