Browse Source

merged hostage1

Alexander Brakowski 10 years ago
parent
commit
d56360fd29
71 changed files with 7608 additions and 6172 deletions
  1. 3 3
      .gitignore
  2. 73 76
      AndroidManifest.xml
  3. BIN
      assets/p
  4. 3 3
      native/Makefile
  5. 35 26
      native/bind.c
  6. BIN
      native/p
  7. BIN
      native/p.o
  8. 1 0
      project.properties
  9. 0 0
      res/drawable-hdpi/ic_action_done.png
  10. 0 0
      res/drawable-mdpi/ic_action_done.png
  11. 0 0
      res/drawable-xhdpi/ic_action_done.png
  12. 0 0
      res/drawable-xxxhdpi/ic_launcher.png
  13. 0 0
      res/drawable-xxxhdpi/ic_service_green.png
  14. 0 0
      res/drawable-xxxhdpi/ic_service_red.png
  15. 0 0
      res/drawable-xxxhdpi/ic_service_yellow.png
  16. 18 0
      res/layout/activity_bluetooth.xml
  17. 7 0
      res/layout/list_view_bluetooth_devices.xml
  18. 2 0
      res/values/protocols.xml
  19. 3 0
      res/values/strings_gui.xml
  20. 23 46
      src/de/tudarmstadt/informatik/hostage/Handler.java
  21. 77 137
      src/de/tudarmstadt/informatik/hostage/Hostage.java
  22. 27 34
      src/de/tudarmstadt/informatik/hostage/Listener.java
  23. 305 0
      src/de/tudarmstadt/informatik/hostage/deprecated/OldLogger.java
  24. 970 1022
      src/de/tudarmstadt/informatik/hostage/deprecated/UglyDbHelper.java
  25. 2 2
      src/de/tudarmstadt/informatik/hostage/location/MyLocationManager.java
  26. 0 30
      src/de/tudarmstadt/informatik/hostage/logging/LogResultReceiver.java
  27. 3 276
      src/de/tudarmstadt/informatik/hostage/logging/Logger.java
  28. 0 34
      src/de/tudarmstadt/informatik/hostage/logging/Record.java
  29. 1 3
      src/de/tudarmstadt/informatik/hostage/logging/formatter/TraCINgFormatter.java
  30. 47 0
      src/de/tudarmstadt/informatik/hostage/net/MyDatagramSocketFactory.java
  31. 14 50
      src/de/tudarmstadt/informatik/hostage/net/MyServerSocketFactory.java
  32. 4 3
      src/de/tudarmstadt/informatik/hostage/nio/Reader.java
  33. 0 1
      src/de/tudarmstadt/informatik/hostage/nio/Writer.java
  34. 44 0
      src/de/tudarmstadt/informatik/hostage/persistence/HostageDBContract.java
  35. 626 0
      src/de/tudarmstadt/informatik/hostage/persistence/HostageDBOpenHelper.java
  36. 11 14
      src/de/tudarmstadt/informatik/hostage/protocol/FTP.java
  37. 2 2
      src/de/tudarmstadt/informatik/hostage/protocol/GHOST.java
  38. 36 12
      src/de/tudarmstadt/informatik/hostage/protocol/HTTP.java
  39. 2 2
      src/de/tudarmstadt/informatik/hostage/protocol/HTTPS.java
  40. 4 4
      src/de/tudarmstadt/informatik/hostage/protocol/MySQL.java
  41. 124 5
      src/de/tudarmstadt/informatik/hostage/protocol/SIP.java
  42. 60 721
      src/de/tudarmstadt/informatik/hostage/protocol/SMB.java
  43. 103 0
      src/de/tudarmstadt/informatik/hostage/protocol/SMBUtils/NBDS.java
  44. 176 0
      src/de/tudarmstadt/informatik/hostage/protocol/SMBUtils/NBNS.java
  45. 96 0
      src/de/tudarmstadt/informatik/hostage/protocol/SMBUtils/NMB.java
  46. 58 0
      src/de/tudarmstadt/informatik/hostage/protocol/SMBUtils/NMBStringCoder.java
  47. 701 0
      src/de/tudarmstadt/informatik/hostage/protocol/SMBUtils/SMBPacket.java
  48. 9 0
      src/de/tudarmstadt/informatik/hostage/protocol/SMBUtils/Service.java
  49. 7 0
      src/de/tudarmstadt/informatik/hostage/protocol/SMBUtils/Type.java
  50. 12 18
      src/de/tudarmstadt/informatik/hostage/protocol/SSH.java
  51. 68 26
      src/de/tudarmstadt/informatik/hostage/protocol/TELNET.java
  52. 233 0
      src/de/tudarmstadt/informatik/hostage/provider/HostageContentProvider.java
  53. 368 305
      src/de/tudarmstadt/informatik/hostage/sync/BluetoothSync.java
  54. 169 185
      src/de/tudarmstadt/informatik/hostage/sync/NFCSync.java
  55. 61 0
      src/de/tudarmstadt/informatik/hostage/system/Device.java
  56. 0 68
      src/de/tudarmstadt/informatik/hostage/system/P.java
  57. 80 0
      src/de/tudarmstadt/informatik/hostage/system/PrivilegedPort.java
  58. 177 159
      src/de/tudarmstadt/informatik/hostage/ui/LogFilter.java
  59. 338 419
      src/de/tudarmstadt/informatik/hostage/ui/MainActivity.java
  60. 95 98
      src/de/tudarmstadt/informatik/hostage/ui/PlayGroundActivity.java
  61. 2 2
      src/de/tudarmstadt/informatik/hostage/ui/ViewLogTable.java
  62. 122 165
      src/de/tudarmstadt/informatik/hostage/ui2/activity/MainActivity.java
  63. 41 48
      src/de/tudarmstadt/informatik/hostage/ui2/adapter/ServicesListAdapter.java
  64. 193 197
      src/de/tudarmstadt/informatik/hostage/ui2/fragment/HomeFragment.java
  65. 108 109
      src/de/tudarmstadt/informatik/hostage/ui2/fragment/RecordDetailFragment.java
  66. 416 429
      src/de/tudarmstadt/informatik/hostage/ui2/fragment/RecordOverviewFragment.java
  67. 40 47
      src/de/tudarmstadt/informatik/hostage/ui2/fragment/ServicesFragment.java
  68. 4 6
      src/de/tudarmstadt/informatik/hostage/ui2/fragment/SettingsFragment.java
  69. 1377 1368
      src/de/tudarmstadt/informatik/hostage/ui2/fragment/StatisticsFragment.java
  70. 8 7
      src/de/tudarmstadt/informatik/hostage/ui2/fragment/ThreatMapFragment.java
  71. 19 10
      src/de/tudarmstadt/informatik/hostage/wrapper/Packet.java

+ 3 - 3
.gitignore

@@ -24,10 +24,10 @@ proguard/
 *.iws
 .idea/
 
-#Ignore some folders
+# Ignore some folders
 target/
 build/
 .gradle/
 gen-external-apklibs/
-native/p
-native/p.o
+native/build
+native/build.o

+ 73 - 76
AndroidManifest.xml

@@ -1,55 +1,50 @@
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-		  package="de.tudarmstadt.informatik.hostage"
-		  android:versionCode="1"
-		  android:versionName="1.0">
+    package="de.tudarmstadt.informatik.hostage"
+    android:versionCode="1"
+    android:versionName="1.0" >
 
-	<uses-sdk
-			android:minSdkVersion="14"
-			android:targetSdkVersion="19"/>
+    <uses-sdk
+        android:minSdkVersion="14"
+        android:targetSdkVersion="19" />
 
-	<uses-permission android:name="android.permission.VIBRATE"/>
-	<uses-permission android:name="android.permission.INTERNET"/>
-	<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_COARSE_LOCATION"/>
-	<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
-	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
-	<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
+    <uses-permission android:name="android.permission.VIBRATE" />
+    <uses-permission android:name="android.permission.INTERNET" />
+    <uses-permission android:name="android.permission.ACCESS_NETWORK_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.ACCESS_COARSE_LOCATION" />
+    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
+    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
 
-	<!-- Tell the system this app requires OpenGL ES 2.0. -->
-	<uses-feature android:glEsVersion="0x00020000" android:required="true"/>
-	<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
-	<uses-permission android:name="android.permission.BLUETOOTH"/>
-	<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
-	<uses-permission android:name="android.permission.NFC"/>
+    <uses-feature
+        android:name="android.hardware.nfc"
+        android:required="false" />
 
-	<uses-feature
-			android:name="android.hardware.nfc"
-			android:required="false"/>
+    <application
+        android:allowBackup="true"
+        android:allowClearUserData="true"
+        android:hardwareAccelerated="true"
+        android:icon="@drawable/ic_launcher"
+        android:installLocation="preferExternal"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme"
+        android:vmSafeMode="true" >
+        <meta-data
+            android:name="com.google.android.gms.version"
+            android:value="@integer/google_play_services_version" />
+        <meta-data
+            android:name="com.google.android.maps.v2.API_KEY"
+            android:value="AIzaSyCqh4bb4aMzvDcpDfiqHyXoAWFTQ6iNxe8" />
+
+        <activity
+            android:name="de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity"
+            android:configChanges="keyboardHidden|orientation|screenSize"
+            android:label="@string/app_name"
+            android:screenOrientation="portrait" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
 
-	<application
-			android:allowBackup="true"
-			android:icon="@drawable/ic_launcher"
-			android:label="@string/app_name"
-			android:theme="@style/AppTheme"
-			android:installLocation="preferExternal"
-			android:vmSafeMode="true"
-			android:allowClearUserData="true"
-			android:hardwareAccelerated="true">
-		<meta-data
-				android:name="com.google.android.gms.version"
-				android:value="14"/>
-		<meta-data
-				android:name="com.google.android.maps.v2.API_KEY"
-				android:value="AIzaSyCqh4bb4aMzvDcpDfiqHyXoAWFTQ6iNxe8"/>
-		<activity
-				android:name="de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity"
-				android:configChanges="keyboardHidden|orientation|screenSize"
-				android:label="@string/app_name"
-				android:screenOrientation="portrait">
-			<intent-filter>
-				<action android:name="android.intent.action.MAIN"/>
                 <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
         </activity>
@@ -66,10 +61,10 @@
             android:name="de.tudarmstadt.informatik.hostage.ui.ViewLogTable"
             android:label="@string/database" >
         </activity>
-	    <activity
-			    android:name=".ui2.activity.ProfileEditActivity"
-			    android:label="Edit Profile" >
-	    </activity>
+        <activity
+            android:name=".ui2.activity.ProfileEditActivity"
+            android:label="Edit Profile" >
+        </activity>
         <activity
             android:name="de.tudarmstadt.informatik.hostage.ui.SettingsActivity"
             android:label="@string/settings" >
@@ -82,36 +77,38 @@
             android:name="de.tudarmstadt.informatik.hostage.ui.PlayGroundActivity"
             android:label="@string/gui_playground" >
         </activity>
+        <activity
+            android:name="de.tudarmstadt.informatik.hostage.sync.BluetoothSync"
+            android:label="@string/gui_bluetooth"
+            android:theme="@android:style/Theme.Dialog" >
+        </activity>
         <activity
             android:name="de.tudarmstadt.informatik.hostage.sync.NFCSync"
-            android:label="@string/gui_playground" >
+            android:label="@string/gui_nfc"
+            android:theme="@android:style/Theme.Dialog" >
             <intent-filter>
                 <action android:name="android.nfc.action.NDEF_DISCOVERED" />
-				<category android:name="android.intent.category.LAUNCHER"/>
-			</intent-filter>
-		</activity>
-		<!--
-		<activity
-			android:name="de.tudarmstadt.informatik.hostage.ui.MainActivity"
-			android:configChanges="keyboardHidden|orientation|screenSize"
-			android:label="@string/app_name" >
-		</activity>
-		<activity
-			android:name="de.tudarmstadt.informatik.hostage.ui.ViewLog"
-			android:label="@string/statistics" >
-		</activity>
-		<activity
-			android:name="de.tudarmstadt.informatik.hostage.ui.ViewLogTable"
-			android:label="@string/database" >
-		</activity>
-		-->
 
-		<service android:name="de.tudarmstadt.informatik.hostage.HoneyService">
-		</service>
-		<service
-				android:name="de.tudarmstadt.informatik.hostage.logging.Logger"
-				android:exported="false">
-		</service>
-	</application>
+                <category android:name="android.intent.category.DEFAULT" />
+
+                <data android:mimeType="application/de.tudarmstadt.informatik.hostage" />
+            </intent-filter>
+        </activity>
+
+        <service
+            android:name="de.tudarmstadt.informatik.hostage.Hostage"
+            android:exported="false" >
+        </service>
+        <service
+            android:name="de.tudarmstadt.informatik.hostage.logging.Logger"
+            android:exported="false" >
+        </service>
+
+        <provider
+            android:name="de.tudarmstadt.informatik.hostage.provider.HostageContentProvider"
+            android:authorities="de.tudarmstadt.informatik.hostage.provider"
+            android:exported="false" >
+        </provider>
+    </application>
 
-</manifest>
+</manifest>

BIN
assets/p


+ 3 - 3
native/Makefile

@@ -3,9 +3,9 @@ x86: CC = i686-linux-android-gcc
 mips: CC = mipsel-linux-android-gcc
 CFLAGS = -Wall -g
 LDFLAGS = -llog
-SRC = p.c
+SRC = bind.c
 OBJ = $(SRC:.c=.o)
-EXE = p
+EXE = bind
 
 arm x86 mips: $(SRC) $(EXE)
 
@@ -19,4 +19,4 @@ clean:
 	rm -f *.o $(EXE)
 
 install:
-	adb push p /data/local
+	adb push bind /data/local

+ 35 - 26
native/p.c → native/bind.c

@@ -1,6 +1,6 @@
-#include <android/log.h>
 #include <errno.h>
 #include <netinet/in.h>
+#include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/socket.h>
@@ -9,20 +9,19 @@
 #include <sys/un.h>
 #include <unistd.h>
 
-#define  LOG_TAG "hostage: p"
-#define  LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
-#define  LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
-
 #define CONTROLLEN CMSG_LEN(sizeof(int))
 
 #define UNIX_PATH "hostage"
 
+#define TCP "TCP"
+#define UDP "UDP"
+
 int ipc_sock() {
 	int fd;
 	struct sockaddr_un addr;
 
 	if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
-		LOGE("Unable to create local socket: %d", errno);
+		perror("Unable to create local socket");
 		return -1;
 	}
 
@@ -30,22 +29,21 @@ int ipc_sock() {
 	addr.sun_family = AF_UNIX;
 	strncpy(&addr.sun_path[1], UNIX_PATH, strlen(UNIX_PATH));
 
-	if (connect(fd, (struct sockaddr*) &addr,
-			sizeof(sa_family_t) + strlen(UNIX_PATH) + 1) == -1) {
-		LOGE("Unable to connect local socket: %d", errno);
+	if (connect(fd, (struct sockaddr*) &addr, sizeof(sa_family_t) + strlen(UNIX_PATH) + 1) == -1) {
+		perror("Unable to connect local socket");
 		return -1;
 	}
 
 	return fd;
 }
 
-int net_sock(int port) {
+int net_sock(int type, int port) {
 	int fd;
-	int reuse = 1;
+	int reuseaddr = 1;
 	struct sockaddr_in addr;
 
-	if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
-		LOGE("Unable to create net socket: %d", errno);
+	if ((fd = socket(AF_INET, (type == 1 ? SOCK_STREAM : SOCK_DGRAM), (type == 1 ? IPPROTO_IP : IPPROTO_UDP))) == -1) {
+		perror("Unable to create net socket");
 		return -1;
 	}
 
@@ -54,19 +52,21 @@ int net_sock(int port) {
 	addr.sin_addr.s_addr = INADDR_ANY;
 	addr.sin_port = htons(port);
 
-	if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) == -1) {
-		LOGE("Unable to set socket options: %d", errno);
+	if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr)) == -1) {
+		perror("Unable to set socket options");
 		return -1;
 	}
 
 	if (bind(fd, (struct sockaddr *) &addr, sizeof(addr)) == -1) {
-		LOGE("Unable to bind net socket: %d", errno);
+		perror("Unable to bind net socket");
 		return -1;
 	}
 
-	if (listen(fd, 5) == -1) {
-		LOGE("Unable to listen net socket: %d", errno);
-		return -1;
+	if (type == 1) {
+		if (listen(fd, 5) == -1) {
+			perror("Unable to listen net socket");
+			return -1;
+		}
 	}
 
 	return fd;
@@ -95,21 +95,30 @@ int send_fd(int fd, int fd_to_send) {
 	*(int *) CMSG_DATA(cmptr) = fd_to_send;
 
 	if (sendmsg(fd, &msg, 0) == -1) {
-		LOGE("sendmsg failed: %d", errno);
+		perror("sendmsg failed");
 	}
 
 	return 0;
 }
 
 int main(int argc, char *argv[]) {
+	int type;
 	int port;
 	int ipc_fd, net_fd;
 
-	if (argc < 2) {
+	if (argc < 3) {
+		exit(EXIT_FAILURE);
+	}
+
+	if (strncmp(argv[1], TCP, 3) == 0) {
+		type = 1;
+	} else if (strncmp(argv[1], UDP, 3) == 0) {
+		type = 0;
+	} else {
 		exit(EXIT_FAILURE);
 	}
 
-	if ((port = atoi(argv[1])) < 1 || (port = atoi(argv[1])) > 65535) {
+	if ((port = atoi(argv[2])) < 1 || (port = atoi(argv[2])) > 65535) {
 		exit(EXIT_FAILURE);
 	}
 
@@ -117,18 +126,18 @@ int main(int argc, char *argv[]) {
 		close(ipc_fd);
 		exit(EXIT_FAILURE);
 	}
-	LOGD("ipc_fd: %d", ipc_fd);
+	printf("ipc_fd: %d\n", ipc_fd);
 
-	if ((net_fd = net_sock(port)) == -1) {
+	if ((net_fd = net_sock(type, port)) == -1) {
 		close(ipc_fd);
 		close(net_fd);
 		exit(EXIT_FAILURE);
 	}
-	LOGD("net_fd: %d", net_fd);
+	printf("net_fd: %d\n", net_fd);
 
 	int status;
 	status = send_fd(ipc_fd, net_fd);
-	LOGD("send_fd: %d", status);
+	printf("send_fd: %d\n", status);
 
 	close(ipc_fd);
 	close(net_fd);

BIN
native/p


BIN
native/p.o


+ 1 - 0
project.properties

@@ -15,3 +15,4 @@ target=android-19
 android.library=false
 
 
+android.library.reference.1=../google-play-services_lib

+ 0 - 0
res/drawable-hdpi/ic_action_done.png


+ 0 - 0
res/drawable-mdpi/ic_action_done.png


+ 0 - 0
res/drawable-xhdpi/ic_action_done.png


+ 0 - 0
res/drawable-xxxhdpi/ic_launcher.png


+ 0 - 0
res/drawable-xxxhdpi/ic_service_green.png


+ 0 - 0
res/drawable-xxxhdpi/ic_service_red.png


+ 0 - 0
res/drawable-xxxhdpi/ic_service_yellow.png


+ 18 - 0
res/layout/activity_bluetooth.xml

@@ -0,0 +1,18 @@
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="wrap_content"
+    android:orientation="vertical"
+    android:paddingBottom="@dimen/activity_vertical_margin"
+    android:paddingLeft="@dimen/activity_horizontal_margin"
+    android:paddingRight="@dimen/activity_horizontal_margin"
+    android:paddingTop="@dimen/activity_vertical_margin"
+    android:id="@+id/bluetoothLayout" >
+
+    <TextView
+        android:id="@+id/bluetoothInfoText"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        />
+
+</LinearLayout>

+ 7 - 0
res/layout/list_view_bluetooth_devices.xml

@@ -0,0 +1,7 @@
+<TextView xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@android:id/text1"
+    android:layout_width="match_parent"
+    android:layout_height="wrap_content"
+    android:textAppearance="?android:attr/textAppearanceSmall"
+    android:gravity="center_vertical"
+/>

+ 2 - 0
res/values/protocols.xml

@@ -8,6 +8,7 @@
         <item>HTTP</item>
         <item>HTTPS</item>
         <item>MySQL</item>
+        <item>SIP</item>
         <item>SMB</item>
         <item>SSH</item>
         <item>TELNET</item>
@@ -20,6 +21,7 @@
 		<item>A protocol to exchange or transfer hypertext. It is the foundation of data communication for the World Wide Web</item>
 		<item>The same as HTTP, but using a secure connections based on SSL/TLS</item>
 		<item>The world\'s second most widely used relational database management system</item>
+		<item>A protocol for VoIP (Voice over IP) services</item>
 		<item>A protocol used for providing shared access to files, printers, serial ports, and miscellaneous communications between nodes on a network</item>
 		<item>A network protocol that provides file access, file transfer, and file management functionalities over any reliable data stream</item>
 		<item>A network protocol used on the Internet or local area networks to provide a bidirectional interactive text-oriented communication facility using a virtual terminal connection</item>

+ 3 - 0
res/values/strings_gui.xml

@@ -27,5 +27,8 @@
     <string name="gui_ssid">SSID:</string>
     <string name="gui_statistics">Statistics</string>
     <string name="gui_status">Status</string>
+    <string name="gui_choose_device">Choose Device</string>
+    <string name="gui_nfc">NFC</string>
+    <string name="gui_bluetooth">Bluetooth</string>
     
 </resources>

+ 23 - 46
src/de/tudarmstadt/informatik/hostage/HoneyHandler.java → src/de/tudarmstadt/informatik/hostage/Handler.java

@@ -11,8 +11,8 @@ import android.content.SharedPreferences;
 import android.content.SharedPreferences.Editor;
 import android.preference.PreferenceManager;
 import android.util.Log;
+import de.tudarmstadt.informatik.hostage.location.MyLocationManager;
 import de.tudarmstadt.informatik.hostage.logging.Logger;
-import de.tudarmstadt.informatik.hostage.logging.MyLocationManager;
 import de.tudarmstadt.informatik.hostage.logging.Record;
 import de.tudarmstadt.informatik.hostage.logging.Record.TYPE;
 import de.tudarmstadt.informatik.hostage.nio.Reader;
@@ -28,12 +28,12 @@ import de.tudarmstadt.informatik.hostage.wrapper.Packet;
  * @author Mihai Plasoianu
  * @author Wulf Pfeiffer
  */
-public class HoneyHandler implements Runnable {
+public class Handler implements Runnable {
 
 	/** Time until the socket throws a time out. The time is in milliseconds. */
 	private int TIMEOUT;
 
-	private HoneyService service;
+	private Hostage service;
 	protected Protocol protocol;
 	private Socket client;
 	protected Thread thread;
@@ -44,7 +44,7 @@ public class HoneyHandler implements Runnable {
 	private String BSSID;
 	private String SSID;
 
-	private HoneyListener listener;
+	private Listener listener;
 
 	/**
 	 * Constructor of the class. Initializes class variables for communication
@@ -59,8 +59,7 @@ public class HoneyHandler implements Runnable {
 	 * @param client
 	 *            A Socket for the communication with a remote client.
 	 */
-	public HoneyHandler(HoneyService service, HoneyListener listener,
-			Protocol protocol, Socket client) {
+	public Handler(Hostage service, Listener listener, Protocol protocol, Socket client) {
 		this.service = service;
 		this.listener = listener;
 		this.protocol = protocol;
@@ -70,20 +69,14 @@ public class HoneyHandler implements Runnable {
 		}
 		this.client = client;
 		this.thread = new Thread(this);
-		SharedPreferences pref = PreferenceManager
-				.getDefaultSharedPreferences(service);
+		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(service);
 		TIMEOUT = pref.getInt("timeout", 30) * 1000;
 		// TODO ThreadSicher?
 		getAndIncrementAttackID(pref);
-		SharedPreferences connInfo = service.getSharedPreferences(
-				service.getString(R.string.connection_info),
-				Context.MODE_PRIVATE);
-		BSSID = connInfo.getString(
-				service.getString(R.string.connection_info_bssid), null);
-		SSID = connInfo.getString(
-				service.getString(R.string.connection_info_ssid), null);
-		externalIP = connInfo.getString(
-				service.getString(R.string.connection_info_external_ip), null);
+		SharedPreferences connInfo = service.getSharedPreferences(service.getString(R.string.connection_info), Context.MODE_PRIVATE);
+		BSSID = connInfo.getString(service.getString(R.string.connection_info_bssid), null);
+		SSID = connInfo.getString(service.getString(R.string.connection_info_ssid), null);
+		externalIP = connInfo.getString(service.getString(R.string.connection_info_external_ip), null);
 		setSoTimeout(client);
 		thread.start();
 	}
@@ -101,11 +94,8 @@ public class HoneyHandler implements Runnable {
 	 * Sets the interrupt flag of the thread and tries to close the socket.
 	 */
 	public void kill() {
-		service.notifyUI(
-				this.getClass().getName(),
-				new String[] { service.getString(R.string.broadcast_started),
-						protocol.toString(),
-						Integer.toString(listener.getPort()) });
+		service.notifyUI(this.getClass().getName(),
+				new String[] { service.getString(R.string.broadcast_started), protocol.toString(), Integer.toString(listener.getPort()) });
 		thread.interrupt();
 		try {
 			client.close();
@@ -125,11 +115,8 @@ public class HoneyHandler implements Runnable {
 	 */
 	@Override
 	public void run() {
-		service.notifyUI(
-				this.getClass().getName(),
-				new String[] { service.getString(R.string.broadcast_started),
-						protocol.toString(),
-						Integer.toString(listener.getPort()) });
+		service.notifyUI(this.getClass().getName(),
+				new String[] { service.getString(R.string.broadcast_started), protocol.toString(), Integer.toString(listener.getPort()) });
 		InputStream in;
 		OutputStream out;
 		try {
@@ -190,23 +177,17 @@ public class HoneyHandler implements Runnable {
 		record.setTimestamp(System.currentTimeMillis());
 		record.setExternalIP(externalIP);
 		record.setLocalIP(client.getLocalAddress().getHostAddress());
-		record.setLocalHost(client.getLocalAddress().getHostAddress());
 		record.setLocalPort(protocol.getPort());
 		record.setRemoteIP(client.getInetAddress().getHostAddress());
-		record.setRemoteHost(client.getInetAddress().getHostAddress());
 		record.setRemotePort(client.getPort());
 		record.setBssid(BSSID);
 		record.setSsid(SSID);
 		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());
+			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);
@@ -226,9 +207,8 @@ public class HoneyHandler implements Runnable {
 	 *            OutputStream of the socket.
 	 * @throws IOException
 	 */
-	protected void talkToClient(InputStream in, OutputStream out)
-			throws IOException {
-		Reader reader = new Reader(in);
+	protected void talkToClient(InputStream in, OutputStream out) throws IOException {
+		Reader reader = new Reader(in, protocol.toString());
 		Writer writer = new Writer(out);
 		Packet inputLine;
 		List<Packet> outputLine;
@@ -236,19 +216,16 @@ public class HoneyHandler implements Runnable {
 			outputLine = protocol.processMessage(null);
 			writer.write(outputLine);
 			for (Packet o : outputLine) {
-				Logger.log(HoneyService.getContext(),
-						createRecord(TYPE.SEND, o.toString()));
+				Logger.log(Hostage.getContext(), createRecord(TYPE.SEND, o.toString()));
 			}
 		}
 		while (!thread.isInterrupted() && (inputLine = reader.read()) != null) {
 			outputLine = protocol.processMessage(inputLine);
-			Logger.log(HoneyService.getContext(),
-					createRecord(TYPE.RECEIVE, inputLine.toString()));
+			Logger.log(Hostage.getContext(), createRecord(TYPE.RECEIVE, inputLine.toString()));
 			if (outputLine != null) {
 				writer.write(outputLine);
 				for (Packet o : outputLine) {
-					Logger.log(HoneyService.getContext(),
-							createRecord(TYPE.SEND, o.toString()));
+					Logger.log(Hostage.getContext(), createRecord(TYPE.SEND, o.toString()));
 				}
 			}
 			if (protocol.isClosed()) {

+ 77 - 137
src/de/tudarmstadt/informatik/hostage/HoneyService.java → src/de/tudarmstadt/informatik/hostage/Hostage.java

@@ -5,7 +5,6 @@ import java.io.InputStreamReader;
 import java.net.Socket;
 import java.security.SecureRandom;
 import java.util.ArrayList;
-import java.util.HashMap;
 import java.util.LinkedList;
 import java.util.List;
 
@@ -38,8 +37,8 @@ import android.support.v4.content.LocalBroadcastManager;
 import android.util.Log;
 import android.widget.Toast;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
-import de.tudarmstadt.informatik.hostage.logging.MyLocationManager;
-import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
+import de.tudarmstadt.informatik.hostage.location.MyLocationManager;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
 import de.tudarmstadt.informatik.hostage.protocol.HTTP;
 import de.tudarmstadt.informatik.hostage.protocol.Protocol;
 import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
@@ -54,13 +53,11 @@ import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
  * @author Lars Pandikow
  * @author Wulf Pfeiffer
  */
-public class HoneyService extends Service {
-
-	private HashMap<String, Boolean> mProtocolActiveAttacks;
+public class Hostage extends Service {
 
 	public class LocalBinder extends Binder {
-		public HoneyService getService() {
-			return HoneyService.this;
+		public Hostage getService() {
+			return Hostage.this;
 		}
 	}
 
@@ -72,14 +69,12 @@ public class HoneyService extends Service {
 	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" };
+			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()));
+				BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
 				while (!in.ready())
 					;
 				while (in.ready()) {
@@ -129,11 +124,9 @@ public class HoneyService extends Service {
 
 		@Override
 		protected void onPostExecute(String result) {
-			connectionInfoEditor.putString(
-					getString(R.string.connection_info_external_ip), result);
+			connectionInfoEditor.putString(getString(R.string.connection_info_external_ip), result);
 			connectionInfoEditor.commit();
-			notifyUI(this.getClass().getName(),
-					new String[] { getString(R.string.broadcast_connectivity) });
+			notifyUI(this.getClass().getName(), new String[] { getString(R.string.broadcast_connectivity) });
 		}
 	}
 
@@ -145,11 +138,11 @@ public class HoneyService extends Service {
 	 * @return context.
 	 */
 	public static Context getContext() {
-		return HoneyService.context;
+		return Hostage.context;
 	}
 
 	private LinkedList<Protocol> implementedProtocols;
-	private ArrayList<HoneyListener> listeners = new ArrayList<HoneyListener>();
+	private ArrayList<Listener> listeners = new ArrayList<Listener>();
 
 	private NotificationCompat.Builder builder;
 
@@ -167,21 +160,18 @@ public class HoneyService extends Service {
 	private BroadcastReceiver netReceiver = new BroadcastReceiver() {
 		@Override
 		public void onReceive(Context context, Intent intent) {
-			String bssid_old = connectionInfo.getString(
-					getString(R.string.connection_info_bssid), "");
+			String bssid_old = connectionInfo.getString(getString(R.string.connection_info_bssid), "");
 			String bssid_new = HelperUtils.getBSSID(context);
 			if (bssid_new == null || !bssid_new.equals(bssid_old)) {
 				deleteConnectionData();
 				updateConnectionInfo();
 				getLocationData();
-				notifyUI(
-						this.getClass().getName(),
-						new String[] { getString(R.string.broadcast_connectivity) });
+				notifyUI(this.getClass().getName(), new String[] { getString(R.string.broadcast_connectivity) });
 			}
 		}
 	};
 
-	public List<HoneyListener> getListeners() {
+	public List<Listener> getListeners() {
 		return listeners;
 	}
 
@@ -209,22 +199,30 @@ public class HoneyService extends Service {
 	 * @return Number of active connections
 	 */
 	public int getNumberOfActiveConnections(String protocolName, int port) {
-		for (HoneyListener listener : listeners) {
-			if (listener.getProtocolName().equals(protocolName)
-					&& listener.getPort() == port) {
+		for (Listener listener : listeners) {
+			if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
 				return listener.getHandlerCount();
 			}
 		}
 		return 0;
 	}
 
+	public boolean hasActiveAttacks() {
+		for (Listener listener : listeners) {
+			if (listener.getHandlerCount() > 0) {
+				return true;
+			}
+		}
+		return false;
+	}
+
 	/**
 	 * Determines if there any listener is currently running.
 	 * 
 	 * @return True if there is a running listener, else false.
 	 */
 	public boolean hasRunningListeners() {
-		for (HoneyListener listener : listeners) {
+		for (Listener listener : listeners) {
 			if (listener.isRunning())
 				return true;
 		}
@@ -255,9 +253,8 @@ public class HoneyService extends Service {
 	 * @return True if protocol is running, else false.
 	 */
 	public boolean isRunning(String protocolName, int port) {
-		for (HoneyListener listener : listeners) {
-			if (listener.getProtocolName().equals(protocolName)
-					&& listener.getPort() == port) {
+		for (Listener listener : listeners) {
+			if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
 				return listener.isRunning();
 			}
 		}
@@ -275,11 +272,8 @@ public class HoneyService extends Service {
 	public void notifyUI(String sender, String[] values) {
 		createNotification();
 		// Send Notification
-		if (sender.equals(HoneyHandler.class.getName())
-				&& values[0].equals(getString(R.string.broadcast_started))) {
-			this.mProtocolActiveAttacks.put(values[1], true);
-
-			//attackNotification();
+		if (sender.equals(Handler.class.getName()) && values[0].equals(R.string.broadcast_started)) {
+			attackNotification();
 		}
 		// Inform UI of Preference Change
 		Intent intent = new Intent(getString(R.string.broadcast));
@@ -297,22 +291,15 @@ public class HoneyService extends Service {
 	@Override
 	public void onCreate() {
 		super.onCreate();
-		HoneyService.context = getApplicationContext();
+		Hostage.context = getApplicationContext();
 		implementedProtocols = getImplementedProtocols();
-		connectionInfo = getSharedPreferences(
-				getString(R.string.connection_info), Context.MODE_PRIVATE);
+		connectionInfo = getSharedPreferences(getString(R.string.connection_info), Context.MODE_PRIVATE);
 		connectionInfoEditor = connectionInfo.edit();
-
-		mProtocolActiveAttacks = new HashMap<String, Boolean>();
-
 		createNotification();
 		registerNetReceiver();
 		updateConnectionInfo();
 		getLocationData();
-
-		String sharedPreferencePath = getString(R.string.shared_preference_path);
-		boolean useQotd = getSharedPreferences(sharedPreferencePath,
-				MODE_PRIVATE).getBoolean("useQotd", true);
+		boolean useQotd = context.getSharedPreferences(getString(R.string.shared_preference_path), Hostage.MODE_PRIVATE).getBoolean("useQotd", true);
 		if (useQotd) {
 			new QotdTask().execute(new String[] {});
 		}
@@ -353,37 +340,29 @@ public class HoneyService extends Service {
 	 *            The port number in which the listener should run.
 	 */
 	public boolean startListener(String protocolName, int port) {
-		for (HoneyListener listener : listeners) {
-			if (listener.getProtocolName().equals(protocolName)
-					&& listener.getPort() == port) {
+		for (Listener listener : listeners) {
+			if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
 				if (!listener.isRunning()) {
 					if (listener.start()) {
-						/*Toast.makeText(getApplicationContext(),
-								protocolName + " SERVICE STARTED!",
-								Toast.LENGTH_SHORT).show();*/
+						// Toast.makeText(getApplicationContext(), protocolName
+						// + " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
 						return true;
 					}
-					/*Toast.makeText(getApplicationContext(),
-							protocolName + " SERVICE COULD NOT BE STARTED!",
-							Toast.LENGTH_SHORT).show();*/
+					Toast.makeText(getApplicationContext(), protocolName + " SERVICE COULD NOT BE STARTED!", Toast.LENGTH_SHORT).show();
 					return false;
 				}
 
 			}
 		}
-
-		HoneyListener listener = createListener(protocolName, port);
+		Listener listener = createListener(protocolName, port);
 		if (listener != null) {
 			if (listener.start()) {
-				/*Toast.makeText(getApplicationContext(),
-						protocolName + " SERVICE STARTED!", Toast.LENGTH_SHORT)
-						.show();*/
+				// Toast.makeText(getApplicationContext(), protocolName +
+				// " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
 				return true;
 			}
 		}
-		/*Toast.makeText(getApplicationContext(),
-				protocolName + " SERVICE COULD NOT BE STARTED!",
-				Toast.LENGTH_SHORT).show();*/
+		Toast.makeText(getApplicationContext(), protocolName + " SERVICE COULD NOT BE STARTED!", Toast.LENGTH_SHORT).show();
 		return false;
 	}
 
@@ -391,13 +370,13 @@ public class HoneyService extends Service {
 	 * Starts all listeners which are not already running.
 	 */
 	public void startListeners() {
-		for (HoneyListener listener : listeners) {
+		for (Listener listener : listeners) {
 			if (!listener.isRunning()) {
 				listener.start();
 			}
 		}
-		Toast.makeText(getApplicationContext(), "SERVICES STARTED!",
-				Toast.LENGTH_SHORT).show();
+		// Toast.makeText(getApplicationContext(), "SERVICES STARTED!",
+		// Toast.LENGTH_SHORT).show();
 	}
 
 	/**
@@ -419,61 +398,51 @@ public class HoneyService extends Service {
 	 *            The port number in which the listener is running.
 	 */
 	public void stopListener(String protocolName, int port) {
-		for (HoneyListener listener : listeners) {
-			if (listener.getProtocolName().equals(protocolName)
-					&& listener.getPort() == port) {
+		for (Listener listener : listeners) {
+			if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
 				if (listener.isRunning()) {
 					listener.stop();
-					mProtocolActiveAttacks.remove(protocolName);
 				}
 			}
 		}
-		Toast.makeText(getApplicationContext(),
-				protocolName + " SERVICE STOPPED!", Toast.LENGTH_SHORT).show();
+		// Toast.makeText(getApplicationContext(), protocolName +
+		// " SERVICE STOPPED!", Toast.LENGTH_SHORT).show();
 	}
 
 	/**
 	 * Stops all running listeners.
 	 */
 	public void stopListeners() {
-		for (HoneyListener listener : listeners) {
+		for (Listener listener : listeners) {
 			if (listener.isRunning()) {
 				listener.stop();
-				mProtocolActiveAttacks.remove(listener.getProtocolName());
 			}
 		}
-		Toast.makeText(getApplicationContext(), "SERVICES STOPPED!",
-				Toast.LENGTH_SHORT).show();
+		// Toast.makeText(getApplicationContext(), "SERVICES STOPPED!",
+		// Toast.LENGTH_SHORT).show();
 	}
 
 	/**
 	 * Updates the notification when a attack is registered.
 	 */
 	private void attackNotification() {
-		SharedPreferences defaultPref = PreferenceManager
-				.getDefaultSharedPreferences(this);
-		String strRingtonePreference = defaultPref.getString(
-				"pref_notification_sound",
-				"content://settings/system/notification_sound");
-		builder = new NotificationCompat.Builder(this)
-				.setContentTitle(getString(R.string.app_name))
-				.setTicker("Honeypot under attack!")
-				.setContentText("Honeypot under attack!")
-				.setSmallIcon(R.drawable.ic_service_red).setAutoCancel(true)
-				.setWhen(System.currentTimeMillis())
+		SharedPreferences defaultPref = PreferenceManager.getDefaultSharedPreferences(this);
+		String strRingtonePreference = defaultPref.getString("pref_notification_sound", "content://settings/system/notification_sound");
+		builder = new NotificationCompat.Builder(this).setContentTitle(getString(R.string.app_name)).setTicker("Honeypot under attack!")
+				.setContentText("Honeypot under attack!").setSmallIcon(R.drawable.ic_service_red).setAutoCancel(true).setWhen(System.currentTimeMillis())
 				.setSound(Uri.parse(strRingtonePreference));
+		Intent launchIntent = new Intent(getApplicationContext(), MainActivity.class);
 		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
 		stackBuilder.addParentStack(MainActivity.class);
-		stackBuilder.addNextIntent(new Intent(this, MainActivity.class));
-		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
-				PendingIntent.FLAG_UPDATE_CURRENT);
+		stackBuilder.addNextIntent(launchIntent);
+		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
 		builder.setContentIntent(resultPendingIntent);
 		if (defaultPref.getBoolean("pref_vibration", false)) {
 			builder.setVibrate(new long[] { 100, 200, 100, 200 });
 		}
 
 		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
-		mNotificationManager.notify(2, builder.build());
+		mNotificationManager.notify(1, builder.build());
 	}
 
 	/**
@@ -485,21 +454,21 @@ public class HoneyService extends Service {
 	}
 
 	/**
-	 * Creates a Listener for a given protocol on a specific port. After
-	 * creation the Listener is not started. Checks if the protocol is
+	 * Creates a HoneyListener for a given protocol on a specific port. After
+	 * creation the HoneyListener is not started. Checks if the protocol is
 	 * implemented first.
 	 * 
 	 * @param protocolName
 	 *            Name of the protocol
 	 * @param port
-	 *            Port on which to start the Listener
+	 *            Port on which to start the HoneyListener
 	 * @return Returns the created HoneyListener, if creation failed returns
 	 *         null.
 	 */
-	private HoneyListener createListener(String protocolName, int port) {
+	private Listener createListener(String protocolName, int port) {
 		for (Protocol protocol : implementedProtocols) {
 			if (protocolName.equals(protocol.toString())) {
-				HoneyListener listener = new HoneyListener(this, protocol, port);
+				Listener listener = new Listener(this, protocol, port);
 				listeners.add(listener);
 				return listener;
 			}
@@ -511,25 +480,22 @@ public class HoneyService extends Service {
 	 * Creates a Notification in the notification bar.
 	 */
 	private void createNotification() {
-		UglyDbHelper dbh = new UglyDbHelper(this);
+		HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
 		boolean activeHandlers = false;
 		boolean bssidSeen = false;
 		boolean listening = false;
 
-		for (HoneyListener listener : listeners) {
+		for (Listener listener : listeners) {
 			if (listener.isRunning())
 				listening = true;
 			if (listener.getHandlerCount() > 0) {
 				activeHandlers = true;
 			}
-			if (dbh.bssidSeen(listener.getProtocolName(),
-					HelperUtils.getBSSID(getApplicationContext()))) {
+			if (dbh.bssidSeen(listener.getProtocolName(), HelperUtils.getBSSID(getApplicationContext()))) {
 				bssidSeen = true;
 			}
 		}
-		builder = new NotificationCompat.Builder(this).setContentTitle(
-				getString(R.string.app_name)).setWhen(
-				System.currentTimeMillis());
+		builder = new NotificationCompat.Builder(this).setContentTitle(getString(R.string.app_name)).setWhen(System.currentTimeMillis());
 		if (!listening) {
 			builder.setSmallIcon(R.drawable.ic_launcher);
 			builder.setContentText("HosTaGe is not active.");
@@ -543,17 +509,11 @@ public class HoneyService extends Service {
 			builder.setSmallIcon(R.drawable.ic_service_green);
 			builder.setContentText("Everything looks fine!");
 		}
+		Intent launchIntent = new Intent(getApplicationContext(), MainActivity.class);
 		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
 		stackBuilder.addParentStack(MainActivity.class);
-
-		Intent intent = MainActivity.getInstance().getIntent();
-		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
-				Intent.FLAG_ACTIVITY_SINGLE_TOP |
-				Intent.FLAG_ACTIVITY_NEW_TASK);
-		intent.setAction("SHOW_HOME");
-
-		stackBuilder.addNextIntent(intent);
-		PendingIntent resultPendingIntent = PendingIntent.getActivity(MainActivity.context, 0, intent, 0); //stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
+		stackBuilder.addNextIntent(launchIntent);
+		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
 		builder.setContentIntent(resultPendingIntent);
 		builder.setOngoing(true);
 		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
@@ -600,9 +560,7 @@ public class HoneyService extends Service {
 
 		for (String protocol : protocols) {
 			try {
-				implementedProtocols.add((Protocol) Class.forName(
-						String.format("%s.%s", packageName, protocol))
-						.newInstance());
+				implementedProtocols.add((Protocol) Class.forName(String.format("%s.%s", packageName, protocol)).newInstance());
 			} catch (Exception e) {
 				e.printStackTrace();
 			}
@@ -638,18 +596,6 @@ public class HoneyService extends Service {
 		unregisterReceiver(netReceiver);
 	}
 
-	public boolean hasProtocolActiveAttacks(String protocol){
-		if(!mProtocolActiveAttacks.containsKey(protocol)) return false;
-		return mProtocolActiveAttacks.get(protocol);
-	}
-
-	public boolean hasActiveAttacks(){
-		for(boolean b: mProtocolActiveAttacks.values()){
-			if(b) return true;
-		}
-
-		return false;
-	}
 	/**
 	 * Updates the connection info and saves them in the the SharedPreferences
 	 * for session data.
@@ -659,20 +605,14 @@ public class HoneyService extends Service {
 	 * @see MainActivity#CONNECTION_INFO
 	 */
 	private void updateConnectionInfo() {
-		SharedPreferences pref = context.getSharedPreferences(
-				getString(R.string.connection_info), Context.MODE_PRIVATE);
+		SharedPreferences pref = context.getSharedPreferences(getString(R.string.connection_info), Context.MODE_PRIVATE);
 		Editor editor = pref.edit();
-		editor.putString(getString(R.string.connection_info_ssid),
-				HelperUtils.getSSID(context));
-		editor.putString(getString(R.string.connection_info_bssid),
-				HelperUtils.getBSSID(context));
-		editor.putString(getString(R.string.connection_info_internal_ip),
-				HelperUtils.getInternalIP(context));
+		editor.putString(getString(R.string.connection_info_ssid), HelperUtils.getSSID(context));
+		editor.putString(getString(R.string.connection_info_bssid), HelperUtils.getBSSID(context));
+		editor.putString(getString(R.string.connection_info_internal_ip), HelperUtils.getInternalIP(context));
 		editor.commit();
 		SetExternalIPTask async = new SetExternalIPTask();
 		async.execute(new String[] { "http://ip2country.sourceforge.net/ip2c.php?format=JSON" });
-
-		this.mProtocolActiveAttacks.clear();
 	}
 
 }

+ 27 - 34
src/de/tudarmstadt/informatik/hostage/HoneyListener.java → src/de/tudarmstadt/informatik/hostage/Listener.java

@@ -11,27 +11,28 @@ import javax.net.ssl.SSLSocketFactory;
 
 import de.tudarmstadt.informatik.hostage.net.MyServerSocketFactory;
 import de.tudarmstadt.informatik.hostage.protocol.Protocol;
+import de.tudarmstadt.informatik.hostage.protocol.SMB;
 import de.tudarmstadt.informatik.hostage.protocol.SSLProtocol;
 
 /**
  * Protocol listener class:<br>
  * Creates a Socket on the port of a given protocol and listens for incoming
  * connections.<br>
- * For each connection creates a Socket and instantiate an {@link HoneyHandler}.
+ * For each connection creates a Socket and instantiate an {@link Handler}.
  * 
  * @author Mihai Plasoianu
  * 
  */
-public class HoneyListener implements Runnable {
+public class Listener implements Runnable {
 
-	private ArrayList<HoneyHandler> handlers = new ArrayList<HoneyHandler>();
+	private ArrayList<Handler> handlers = new ArrayList<Handler>();
 
 	private Protocol protocol;
 
 	private ServerSocket server;
 	private Thread thread;
 	private int port;
-	private HoneyService service;
+	private Hostage service;
 
 	private ConnectionRegister conReg;
 	private boolean running = false;
@@ -44,14 +45,14 @@ public class HoneyListener implements Runnable {
 	 * @param protocol
 	 *            The Protocol on which the listener is running.
 	 */
-	public HoneyListener(HoneyService service, Protocol protocol) {
+	public Listener(Hostage service, Protocol protocol) {
 		this.service = service;
 		this.protocol = protocol;
 		port = protocol.getPort();
 		conReg = new ConnectionRegister(service);
 	}
 
-	public HoneyListener(HoneyService service, Protocol protocol, int port) {
+	public Listener(Hostage service, Protocol protocol, int port) {
 		this.service = service;
 		this.protocol = protocol;
 		this.port = port;
@@ -98,9 +99,8 @@ public class HoneyListener implements Runnable {
 	 * Remove all terminated handlers from its internal ArrayList.
 	 */
 	public void refreshHandlers() {
-		for (Iterator<HoneyHandler> iterator = handlers.iterator(); iterator
-				.hasNext();) {
-			HoneyHandler handler = iterator.next();
+		for (Iterator<Handler> iterator = handlers.iterator(); iterator.hasNext();) {
+			Handler handler = iterator.next();
 			if (handler.isTerminated()) {
 				conReg.closeConnection();
 				iterator.remove();
@@ -113,7 +113,7 @@ public class HoneyListener implements Runnable {
 		while (!thread.isInterrupted()) {
 			addHandler();
 		}
-		for (HoneyHandler handler : handlers) {
+		for (Handler handler : handlers) {
 			handler.kill();
 		}
 	}
@@ -127,13 +127,13 @@ public class HoneyListener implements Runnable {
 			server = new MyServerSocketFactory().createServerSocket(port);
 			if (server == null)
 				return false;
+			if(protocol.toString().equals("SMB")) {
+				((SMB) protocol).setIP(Hostage.getContext().getSharedPreferences(Hostage.getContext().getString(R.string.connection_info), Hostage.MODE_PRIVATE).getString(Hostage.getContext().getString(R.string.connection_info_internal_ip), ""));
+			}
 			(this.thread = new Thread(this)).start();
 			running = true;
-			service.notifyUI(
-					this.getClass().getName(),
-					new String[] {
-							service.getString(R.string.broadcast_started),
-							protocol.toString(), Integer.toString(port) });
+			service.notifyUI(this.getClass().getName(),
+					new String[] { service.getString(R.string.broadcast_started), protocol.toString(), Integer.toString(port) });
 			return true;
 		} catch (Exception e) {
 			e.printStackTrace();
@@ -150,11 +150,8 @@ public class HoneyListener implements Runnable {
 			server.close();
 			thread.interrupt();
 			running = false;
-			service.notifyUI(
-					this.getClass().getName(),
-					new String[] {
-							service.getString(R.string.broadcast_stopped),
-							protocol.toString(), Integer.toString(port) });
+			service.notifyUI(this.getClass().getName(),
+					new String[] { service.getString(R.string.broadcast_stopped), protocol.toString(), Integer.toString(port) });
 		} catch (Exception e) {
 			e.printStackTrace();
 		}
@@ -162,7 +159,7 @@ public class HoneyListener implements Runnable {
 
 	/**
 	 * Waits for an incoming connection, accepts it and starts a
-	 * {@link HoneyHandler}
+	 * {@link Handler}
 	 */
 	private void addHandler() {
 		if (conReg.isConnectionFree()) {
@@ -182,7 +179,7 @@ public class HoneyListener implements Runnable {
 	}
 
 	/**
-	 * Creates a new instance of an {@link HoneyHandler}.
+	 * Creates a new instance of an {@link Handler}.
 	 * 
 	 * @param service
 	 *            The background service
@@ -192,29 +189,27 @@ public class HoneyListener implements Runnable {
 	 *            The Protocol the handler will run on
 	 * @param client
 	 *            The Socket the handler uses
-	 * @return A Instance of a {@link HoneyHandler} with the specified
+	 * @return A Instance of a {@link Handler} with the specified
 	 *         parameter.
 	 */
-	private HoneyHandler newInstance(HoneyService service,
-			HoneyListener listener, Protocol protocol, Socket client) {
-		return new HoneyHandler(service, listener, protocol, client);
+	private Handler newInstance(Hostage service, Listener listener, Protocol protocol, Socket client) {
+		return new Handler(service, listener, protocol, client);
 	}
 
 	/**
-	 * Starts a {@link HoneyHandler} with the given socket.
+	 * Starts a {@link Handler} with the given socket.
 	 * 
 	 * @param client
 	 *            The socket with the accepted connection.
 	 * @throws Exception
 	 */
 	private void startHandler(Socket client) throws Exception {
-		handlers.add(newInstance(service, this, protocol.getClass()
-				.newInstance(), client));
+		handlers.add(newInstance(service, this, protocol.getClass().newInstance(), client));
 	}
 
 	/**
 	 * Creates a SSLSocket out of the given socket and starts a
-	 * {@link HoneyHandler}.
+	 * {@link Handler}.
 	 * 
 	 * @param client
 	 *            The socket with the accepted connection.
@@ -223,10 +218,8 @@ public class HoneyListener implements Runnable {
 	private void startSecureHandler(Socket client) throws Exception {
 		SSLContext sslContext = ((SSLProtocol) protocol).getSSLContext();
 		SSLSocketFactory factory = sslContext.getSocketFactory();
-		SSLSocket sslClient = (SSLSocket) factory.createSocket(client, null,
-				client.getPort(), false);
+		SSLSocket sslClient = (SSLSocket) factory.createSocket(client, null, client.getPort(), false);
 		sslClient.setUseClientMode(false);
-		handlers.add(newInstance(service, this, protocol.getClass()
-				.newInstance(), sslClient));
+		handlers.add(newInstance(service, this, protocol.getClass().newInstance(), sslClient));
 	}
 }

+ 305 - 0
src/de/tudarmstadt/informatik/hostage/deprecated/OldLogger.java

@@ -0,0 +1,305 @@
+package de.tudarmstadt.informatik.hostage.deprecated;
+
+import java.util.ArrayList;
+
+import android.app.IntentService;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.ResultReceiver;
+import de.tudarmstadt.informatik.hostage.logging.Record;
+
+/**
+ * An {@link IntentService} subclass for handling asynchronous task requests in
+ * a service on a separate handler thread.
+ * 
+ * @author Mihai Plasoianu
+ */
+public class OldLogger 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 deleteAll(Context context) {
+		Intent intent = new Intent(context, OldLogger.class);
+		intent.setAction(ACTION_CLEAR_ALL);
+		context.startService(intent);
+	}
+
+	public static void deleteByBssid(Context context, String bssid) {
+		Intent intent = new Intent(context, OldLogger.class);
+		intent.setAction(ACTION_CLEAR_BSSID);
+		intent.putExtra(EXTRA_BSSID, bssid);
+		context.startService(intent);
+	}
+
+	public static void deleteByDate(Context context, long time) {
+		Intent intent = new Intent(context, OldLogger.class);
+		intent.setAction(ACTION_CLEAR_DATE);
+		intent.putExtra(EXTRA_PRIMITIVE, time);
+		context.startService(intent);
+	}
+
+	public static void getAllBssids(Context context, ResultReceiver receiver) {
+		Intent intent = new Intent(context, OldLogger.class);
+		intent.setAction(ACTION_GET_BSSID_ALL);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getAllRecords(Context context, ResultReceiver receiver) {
+		Intent intent = new Intent(context, OldLogger.class);
+		intent.setAction(ACTION_GET_RECORD_ALL);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getAttackCount(Context context, ResultReceiver receiver) {
+		Intent intent = new Intent(context, OldLogger.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, OldLogger.class);
+		intent.setAction(ACTION_GET_COUNT_PROTOCOL);
+		intent.putExtra(EXTRA_PROTOCOL, protocol);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getMaxAttackId(Context context, ResultReceiver receiver) {
+		Intent intent = new Intent(context, OldLogger.class);
+		intent.setAction(ACTION_GET_ATTACK_MAX);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getMinAttackId(Context context, ResultReceiver receiver) {
+		Intent intent = new Intent(context, OldLogger.class);
+		intent.setAction(ACTION_GET_ATTACK_MIN);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getRecordOfAttackId(Context context, long attack_id, ResultReceiver receiver) {
+		Intent intent = new Intent(context, OldLogger.class);
+		intent.setAction(ACTION_GET_RECORD_ID);
+		intent.putExtra(EXTRA_PRIMITIVE, attack_id);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getRecordOfEachAttack(Context context, int lastUploadedAttackId, ResultReceiver receiver) {
+		Intent intent = new Intent(context, OldLogger.class);
+		intent.setAction(ACTION_GET_RECORD_EACH);
+		intent.putExtra(EXTRA_PRIMITIVE, lastUploadedAttackId);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getSsid(Context context, String bssid, ResultReceiver receiver) {
+		Intent intent = new Intent(context, OldLogger.class);
+		intent.setAction(ACTION_GET_SSID_BSSID);
+		intent.putExtra(EXTRA_BSSID, bssid);
+		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, OldLogger.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 log(Context context, Record record) {
+		Intent intent = new Intent(context, OldLogger.class);
+		intent.setAction(ACTION_LOG);
+		intent.putExtra(EXTRA_RECORD, record);
+		context.startService(intent);
+	}
+
+	private UglyDbHelper mDbHelper;
+
+	public OldLogger() {
+		super("Logger");
+	}
+
+	@Override
+	public void onCreate() {
+		super.onCreate();
+		mDbHelper = new UglyDbHelper(getApplicationContext());
+	}
+
+	private boolean handleActionBssidSeen(String protocol, String bssid) {
+		return mDbHelper.bssidSeen(protocol, bssid);
+	}
+
+	/**
+	 * Delete all records.
+	 */
+	private void handleActionDeleteAll() {
+		mDbHelper.clearData();
+	}
+
+	private void handleActionDeleteByBssid(String bssid) {
+		mDbHelper.deleteByBSSID(bssid);
+	}
+
+	private void handleActionDeleteByDate(long time) {
+		mDbHelper.deleteByDate(time);
+	}
+
+	private String[] handleActionGetAllBssids() {
+		return mDbHelper.getAllBSSIDS();
+	}
+
+	private ArrayList<Record> handleActionGetAllRecords() {
+		return mDbHelper.getAllRecords();
+	}
+
+	private int handleActionGetAttackCount() {
+		return mDbHelper.getAttackCount();
+	}
+
+	private int handleActionGetAttackPerProtocolCount(String protocol) {
+		return mDbHelper.getAttackPerProtocolCount(protocol);
+	}
+
+	private long handleActionGetMaxAttackId() {
+		return mDbHelper.getHighestAttackId();
+	}
+
+	private long handleActionGetMinAttackId() {
+		return mDbHelper.getSmallestAttackId();
+	}
+
+	private Record handleActionGetRecordOfAttackId(long attack_id) {
+		return mDbHelper.getRecordOfAttackId(attack_id);
+	}
+
+	private ArrayList<Record> handleActionGetRecordOfEachAttack(int lastUploadedAttackId) {
+		return mDbHelper.getRecordOfEachAttack(lastUploadedAttackId);
+	}
+
+	private String handleActionGetSsid(String bssid) {
+		return mDbHelper.getSSID(bssid);
+	}
+
+	/**
+	 * Log a record.
+	 */
+	private void handleActionLog(Record record) {
+		mDbHelper.addRecord(record);
+	}
+
+	@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();
+			}
+		}
+	}
+
+}

+ 970 - 1022
src/de/tudarmstadt/informatik/hostage/logging/UglyDbHelper.java → src/de/tudarmstadt/informatik/hostage/deprecated/UglyDbHelper.java

@@ -1,1022 +1,970 @@
-package de.tudarmstadt.informatik.hostage.logging;
-
-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 java.util.ArrayList;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-
-import de.tudarmstadt.informatik.hostage.logging.Record.TYPE;
-import de.tudarmstadt.informatik.hostage.model.Profile;
-import de.tudarmstadt.informatik.hostage.ui.LogFilter;
-
-/**
- * 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 = 9;
-
-	// 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_PROFILES = "profiles";
-
-	// 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";
-
-	public static final String KEY_PROFILE_ID = "_profile_id";
-	public static final String KEY_PROFILE_NAME = "profile_name";
-	public static final String KEY_PROFILE_DESCRIPTION = "profile_description";
-	public static final String KEY_PROFILE_ICON = "profile_icon";
-	public static final String KEY_PROFILE_EDITABLE = "profile_editable";
-	public static final String KEY_PROFILE_ACTIVE = "profile_active";
-	public static final String KEY_PROFILE_ICON_NAME = "profile_icon_name";
-
-	// Database sql create statements
-	private static final String CREATE_PROFILE_TABLE = "CREATE TABLE "
-			+ TABLE_PROFILES + "("
-			+ KEY_PROFILE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
-			+ KEY_PROFILE_NAME + " TEXT,"
-			+ KEY_PROFILE_DESCRIPTION + " TEXT,"
-			+ KEY_PROFILE_ICON + " TEXT,"
-			+ KEY_PROFILE_ICON_NAME + " TEXT,"
-			+ KEY_PROFILE_EDITABLE + " INTEGER,"
-			+ KEY_PROFILE_ACTIVE + " INTEGER"
-			+ ")";
-
-	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_LOCAL_PORT + " INTEGER,"
-            + KEY_REMOTE_IP + " BLOB,"
-			+ KEY_REMOTE_HOSTNAME + " TEXT,"
-            + KEY_REMOTE_PORT + " INTEGER,"
-			+ KEY_BSSID + " TEXT,"
-            + "FOREIGN KEY(" + KEY_BSSID
-			+ ") REFERENCES " + TABLE_BSSIDS + "(" + KEY_BSSID + ")" + ")";
-
-	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"
-			+ ")";
-
-	public UglyDbHelper(Context context) {
-		super(context, DATABASE_NAME, null, DATABASE_VERSION);
-	}
-
-	  /*
-    // Contacts Table Columns names
-	private static final String KEY_ID = "_id";
-	private static final String KEY_ATTACK_ID = "_attack_id";
-	private static final String KEY_TYPE = "type";
-	private static final String KEY_TIME = "timestamp";
-	private static final String KEY_PACKET = "packet";
-	private static final String KEY_PROTOCOL = "protocol";
-	private static final String KEY_EXTERNAL_IP ="externalIP";
-	private static final String KEY_LOCAL_IP = "localIP";
-	private static final String KEY_LOCAL_HOSTNAME = "localHostName";
-	private static final String KEY_LOCAL_PORT = "localPort";
-	private static final String KEY_REMOTE_IP = "remoteIP";
-	private static final String KEY_REMOTE_HOSTNAME = "remoteHostName";
-	private static final String KEY_REMOTE_PORT = "remotePort";
-	private static final String KEY_BSSID = "_bssid";
-	private static final String KEY_SSID = "ssid";
-	private static final String KEY_LATITUDE = "latitude";
-	private static final String KEY_LONGITUDE = "longitude";
-	private static final String KEY_ACCURACY = "accuracy";
-	*/
-
-	/**
-	 * Gets all received {@link Record Records} for the specified information in the LogFilter ordered by date.
-	 * @return A ArrayList with all received {@link Record Records} for the LogFilter.
-	 */
-	public ArrayList<Record> getRecordsForFilter(LogFilter filter) {
-		ArrayList<Record> recordList = new ArrayList<Record>();
-		String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_ATTACK_INFO +  " JOIN " + TABLE_BSSIDS + " USING "+ "(" + KEY_BSSID + ")";
-
-		// TIMESTAMPS
-		selectQuery = selectQuery + " WHERE " + TABLE_RECORDS +"."+KEY_TIME;
-		selectQuery = selectQuery + " < " + filter.getBelowTimestamp();
-		selectQuery = selectQuery + " AND " + TABLE_RECORDS +"."+KEY_TIME;
-		selectQuery = selectQuery + " > " + filter.getAboveTimestamp();
-
-		if (filter.getBSSIDs() != null && filter.getBSSIDs().size() > 0) {
-			selectQuery = selectQuery + " AND ";
-			selectQuery = selectQuery + filter.getBSSIDQueryStatement(TABLE_BSSIDS, KEY_BSSID);
-		}
-		if (filter.getESSIDs() != null && filter.getESSIDs().size() > 0) {
-			selectQuery = selectQuery + " AND ";
-			selectQuery = selectQuery + filter.getESSIDQueryStatement(TABLE_BSSIDS, KEY_SSID);
-		}
-		if (filter.getProtocols() != null && filter.getProtocols().size() > 0) {
-			selectQuery = selectQuery + " AND ";
-			selectQuery = selectQuery + filter.getProtocolsQueryStatement(TABLE_ATTACK_INFO, KEY_PROTOCOL);
-		}
-
-        selectQuery = selectQuery + " GROUP BY " + TABLE_RECORDS+"."+KEY_ATTACK_ID;
-
-        if (filter.getSorttype() == LogFilter.SortType.timestamp){
-            //DESC
-            selectQuery = selectQuery + " ORDER BY " + filter.getSorttype() + " DESC";
-        } else {
-            selectQuery = selectQuery + " ORDER BY " + filter.getSorttype();
-        }
-
-
-
-		System.out.println(selectQuery);
-		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 all non duplicate Records For the key BSSID.
-	 * @return A ArrayList with received Records.
-	 */
-	public ArrayList<String> getUniqueBSSIDRecords(){
-		return this.getUniqueDataEntryForKeyType(KEY_BSSID, TABLE_BSSIDS);
-	}
-	/**
-	 * Gets all non duplicate Records For the key ESSID.
-	 * @return A ArrayList with received Records.
-	 */
-	public ArrayList<String> getUniqueESSIDRecords(){
-		return this.getUniqueDataEntryForKeyType(KEY_SSID, TABLE_BSSIDS);
-	}
-
-    public ArrayList<String> getUniqueESSIDRecordsForProtocol(String protocol){
-        return this.getUniqueIDForProtocol(KEY_SSID, protocol);
-    }
-    public ArrayList<String> getUniqueBSSIDRecordsForProtocol(String protocol){
-        return this.getUniqueIDForProtocol(KEY_BSSID, protocol);
-    }
-
-    private ArrayList<String> getUniqueIDForProtocol(String id, String protocol){
-        ArrayList<String> recordList = new ArrayList<String>();
-        String selectQuery = "SELECT DISTINCT " + id + " FROM " + TABLE_ATTACK_INFO + " JOIN " + TABLE_BSSIDS + " USING "+ "(" + KEY_BSSID + ") " + " WHERE " + TABLE_ATTACK_INFO + "."+ KEY_PROTOCOL + " = " + "'" + protocol + "'"+ " ORDER BY " + id; // " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN " + TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS +
-
-
-        // ORDERED BY TIME
-        System.out.println(selectQuery);
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(selectQuery, null);
-
-        // looping through all rows and adding to list
-        if (cursor.moveToFirst()) {
-            do {
-                String record = cursor.getString(0);
-                recordList.add(record);
-            } while (cursor.moveToNext());
-        }
-        cursor.close();
-
-        // return record list
-        db.close();
-        return recordList;
-    }
-
-	/**
-	 * Gets all non duplicate Data Entry For a specific KeyType ( e.g. BSSIDs).
-	 * @return A ArrayList with received Records.
-	 */
-	public ArrayList<String> getUniqueDataEntryForKeyType(String keyType, String table) {
-		ArrayList<String> recordList = new ArrayList<String>();
-		//String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN " + TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS;
-		String selectQuery = "SELECT DISTINCT " + keyType + " FROM " + table + " ORDER BY " + keyType; // " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN " + TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS +
-
-
-		// ORDERED BY TIME
-		System.out.println(selectQuery);
-		SQLiteDatabase db = this.getReadableDatabase();
-		Cursor cursor = db.rawQuery(selectQuery, null);
-
-		// looping through all rows and adding to list
-		if (cursor.moveToFirst()) {
-			do {
-				String record = cursor.getString(0);
-				recordList.add(record);
-			} while (cursor.moveToNext());
-		}
-		cursor.close();
-
-		// return record list
-		db.close();
-		return recordList;
-	}
-
-	/**
-	 * 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_LOCAL_PORT, record.getLocalPort());
-		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);
-	}
-
-	/**
-	 * 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;
-	}
-
-	public int numBssidSeen(String BSSID){
-		String countQuery = "SELECT  COUNT(*) FROM " + TABLE_ATTACK_INFO
-				+ " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ")" + " WHERE " + TABLE_BSSIDS+ "."+ KEY_BSSID + " = "
-				+ "'" + BSSID + "'";
-		SQLiteDatabase db = this.getReadableDatabase();
-		Cursor cursor = db.rawQuery(countQuery, null);
-		cursor.moveToFirst();
-		int result = cursor.getInt(0);
-		cursor.close();
-		db.close();
-		return result;
-	}
-
-	public int numBssidSeen(String protocol, String BSSID) {
-		String countQuery = "SELECT  COUNT(*) FROM " + TABLE_ATTACK_INFO
-				+ " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ")" + " WHERE " + TABLE_ATTACK_INFO + "." +  KEY_PROTOCOL
-				+ " = " + "'" + protocol + "'" + " AND " + TABLE_BSSIDS+ "."+ KEY_BSSID + " = "
-				+ "'" + BSSID + "'";
-		SQLiteDatabase db = this.getReadableDatabase();
-		Cursor cursor = db.rawQuery(countQuery, null);
-		cursor.moveToFirst();
-		int result = cursor.getInt(0);
-		cursor.close();
-		db.close();
-		return result;
-	}
-
-	/**
-	 * 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
-				+ " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ")" + " WHERE " + TABLE_ATTACK_INFO + "." +  KEY_PROTOCOL
-				+ " = " + "'" + protocol + "'" + " AND " + TABLE_BSSIDS+ "."+ KEY_BSSID + " = "
-				+ "'" + BSSID + "'";
-		SQLiteDatabase db = this.getReadableDatabase();
-		Cursor cursor = db.rawQuery(countQuery, null);
-		int result = cursor.getCount();
-		cursor.close();
-		db.close();
-		return result > 0;
-	}
-
-	/**
-	 * 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.delete(TABLE_PROFILES, null, null);
-		db.close();
-	}
-
-	/**
-	 * 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();
-	}
-
-	/**
-	 * 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 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 + " JOIN "
-				+ TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ")" + " WHERE " + KEY_TYPE + "='RECEIVE'"
-				+ " ORDER BY " + TABLE_RECORDS+ "."+ 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 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 + " JOIN "
-				+ TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ")";
-
-		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;
-	}
-
-	/**
-	 * 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 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;
-	}
-
-	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;
-	}
-
-	/**
-	 * 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 + " JOIN "
-				+ TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ")" + " WHERE " + TABLE_RECORDS+"."+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;
-	}
-
-	/**
-	 * 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;
-	}
-
-	/**
-	 * 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 + " JOIN "
-				+ TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ")" + " WHERE " + TABLE_RECORDS+"."+KEY_ATTACK_ID + " = " + attack_id
-				+ " GROUP BY " + TABLE_RECORDS+"."+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 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 + " JOIN "
-				+ TABLE_BSSIDS  + " USING " + "(" + KEY_BSSID + ")" + " GROUP BY " + TABLE_RECORDS+ "."+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;
-	}
-
-
-    /*
-    * Returns the Conversation of a specific attack id
-    * @param attack_id
-    *           Tha attack id to match the query against.
-    *
-    *  @return A arraylist with all {@link Record Records}s for an attack id.
-    *
-    * */
-    public ArrayList<Record> getConversationForAttackID(long attack_id) {
-        ArrayList<Record> recordList = new ArrayList<Record>();
-        String selectQuery = "SELECT  * FROM " + TABLE_RECORDS
-                + " NATURAL JOIN " + TABLE_ATTACK_INFO + " JOIN "
-                + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ")" + " WHERE " + TABLE_RECORDS+"."+KEY_ATTACK_ID + " = " + attack_id;
-
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(selectQuery, null);
-
-        if (cursor.moveToFirst()) {
-            do {
-                Record record = createRecord(cursor);
-                recordList.add(record);
-            } while (cursor.moveToNext());
-        }
-        cursor.close();
-
-        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 + " JOIN "
-				+ TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ")" + " WHERE " + TABLE_RECORDS+"."+KEY_ATTACK_ID + " > " + attack_id
-				+ " GROUP BY " + TABLE_RECORDS+"."+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 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;
-	}
-
-	/**
-	 * 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;
-	}
-
-	// Creating Tables
-	@Override
-	public void onCreate(SQLiteDatabase db) {
-		db.execSQL(CREATE_BSSID_TABLE);
-		db.execSQL(CREATE_ATTACK_INFO_TABLE);
-		db.execSQL(CREATE_RECORD_TABLE);
-		db.execSQL(CREATE_PROFILE_TABLE);
-	}
-
-	// 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_PROFILES);
-
-		// Create tables again
-		onCreate(db);
-	}
-
-	/**
-	 * Retrieves all the profiles from the database
-	 *
-	 * @return list of profiles
-	 */
-	public List<Profile> getAllProfiles(){
-		List<Profile> profiles = new LinkedList<Profile>();
-
-		// Select All Query
-		String selectQuery = "SELECT  * FROM " + TABLE_PROFILES;
-
-		SQLiteDatabase db = this.getWritableDatabase();
-		Cursor cursor = db.rawQuery(selectQuery, null);
-
-		// looping through all rows and adding to list
-		if (cursor.moveToFirst()) {
-			do {
-				Profile profile = new Profile(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getInt(5) == 1);
-
-				if(cursor.getInt(6) == 1){
-					profile.mActivated = true;
-				}
-
-				profile.mIconName = cursor.getString(4);
-
-				// Adding record to list
-				profiles.add(profile);
-			} while (cursor.moveToNext());
-		}
-		cursor.close();
-		db.close();
-		// return record list
-		return profiles;
-	}
-
-	/**
-	 * Persists the given profile into the database
-	 *
-	 * @param profile the profile which should be persisted
-	 *
-	 * @return
-	 */
-	public long persistProfile(Profile profile){
-		SQLiteDatabase db = this.getReadableDatabase();
-
-		ContentValues values = new ContentValues();
-
-		if(profile.mId != -1){
-			values.put(KEY_PROFILE_ID, profile.mId);
-		}
-
-		values.put(KEY_PROFILE_NAME, profile.mLabel);
-		values.put(KEY_PROFILE_DESCRIPTION, profile.mText);
-		values.put(KEY_PROFILE_ICON, profile.mIconPath);
-		values.put(KEY_PROFILE_ICON_NAME, profile.mIconName);
-		values.put(KEY_PROFILE_ACTIVE, profile.mActivated);
-		values.put(KEY_PROFILE_EDITABLE, profile.mEditable);
-
-		return db.replace(TABLE_PROFILES, null, values);
-	}
-
-
-	/**
-	 * private static final String CREATE_PROFILE_TABLE = "CREATE TABLE "
-	 + TABLE_PROFILES + "("
-	 + KEY_PROFILE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
-	 + KEY_PROFILE_NAME + " TEXT,"
-	 + KEY_PROFILE_DESCRIPTION + " TEXT,"
-	 + KEY_PROFILE_ICON + " TEXT,"
-	 + KEY_PROFILE_ICON_ID + " INTEGER,"
-	 + KEY_PROFILE_EDITABLE + " INTEGER,"
-	 + KEY_PROFILE_ACTIVE + " INTEGER"
-	 + ")";
-	 */
-	public Profile getProfile(int id) {
-		String selectQuery = "SELECT  * FROM " + TABLE_PROFILES + " WHERE " + TABLE_PROFILES + "." + KEY_PROFILE_ID + " = " + id;
-		SQLiteDatabase db = this.getReadableDatabase();
-
-		Cursor cursor = db.rawQuery(selectQuery, null);
-		Profile profile = null;
-
-		if (cursor.moveToFirst()) {
-			profile = new Profile(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getInt(5) == 1);
-
-			if(cursor.getInt(6) == 1){
-				profile.mActivated = true;
-			}
-
-			profile.mIconName = cursor.getString(5);
-		}
-
-		cursor.close();
-		db.close();
-
-		// return contact
-		return profile;
-	}
-
-	public void deleteProfile(int id){
-		SQLiteDatabase db = this.getReadableDatabase();
-
-		db.delete(TABLE_PROFILES, KEY_PROFILE_ID + "=?", new String[]{String.valueOf(id)});
-	}
-
-	public void updateNetworkInformation(
-			ArrayList<HashMap<String, Object>> networkInformation) {
-		Log.i("DatabaseHandler", "Starte updating");
-		for (HashMap<String, Object> values : networkInformation) {
-			updateNetworkInformation(values);
-		}
-	}
-
-	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();
-	}
-
-	/**
-	 * 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(TYPE.valueOf(cursor.getString(2)));
-		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.setLocalHost(cursor.getString(8));
-		record.setLocalPort(Integer.parseInt(cursor.getString(9)));
-
-		record.setRemoteIP(cursor.getString(10));
-		record.setRemoteHost(cursor.getString(11));
-		record.setRemotePort(Integer.parseInt(cursor.getString(12)));
-
-		record.setBssid(cursor.getString(13));
-		record.setSsid(cursor.getString(14));
-		record.setLatitude(Double.parseDouble(cursor.getString(15)));
-		record.setLongitude(Double.parseDouble(cursor.getString(16)));
-		record.setAccuracy(Float.parseFloat(cursor.getString(17)));
-		record.setTimestampLocation(cursor.getLong(18));
-
-		return record;
-	}
-}
+package de.tudarmstadt.informatik.hostage.deprecated;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+
+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.logging.Record;
+import de.tudarmstadt.informatik.hostage.logging.Record.TYPE;
+import de.tudarmstadt.informatik.hostage.model.Profile;
+import de.tudarmstadt.informatik.hostage.ui.LogFilter;
+
+/**
+ * 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 = "hostage.db";
+
+	// Contacts table names
+	private static final String TABLE_ATTACK_INFO = "attack";
+	private static final String TABLE_RECORDS = "packet";
+	private static final String TABLE_BSSIDS = "network";
+	private static final String TABLE_PROFILES = "profiles";
+
+	// 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 = "packet_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_PORT = "localPort";
+	public static final String KEY_REMOTE_IP = "remoteIP";
+	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";
+	public static final String KEY_GEO_TIMESTAMP = "geo_timestamp";
+
+	public static final String KEY_PROFILE_ID = "_profile_id";
+	public static final String KEY_PROFILE_NAME = "profile_name";
+	public static final String KEY_PROFILE_DESCRIPTION = "profile_description";
+	public static final String KEY_PROFILE_ICON = "profile_icon";
+	public static final String KEY_PROFILE_EDITABLE = "profile_editable";
+	public static final String KEY_PROFILE_ACTIVE = "profile_active";
+	public static final String KEY_PROFILE_ICON_NAME = "profile_icon_name";
+
+	// Database sql create statements
+	private static final String CREATE_PROFILE_TABLE = "CREATE TABLE " + TABLE_PROFILES + "(" + KEY_PROFILE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+			+ KEY_PROFILE_NAME + " TEXT," + KEY_PROFILE_DESCRIPTION + " TEXT," + KEY_PROFILE_ICON + " TEXT," + KEY_PROFILE_ICON_NAME + " TEXT,"
+			+ KEY_PROFILE_EDITABLE + " INTEGER," + KEY_PROFILE_ACTIVE + " INTEGER" + ")";
+
+	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_PORT + " INTEGER," + KEY_REMOTE_IP + " BLOB," + KEY_REMOTE_PORT
+			+ " INTEGER," + KEY_BSSID + " TEXT," + "FOREIGN KEY(" + KEY_BSSID + ") REFERENCES " + TABLE_BSSIDS + "(" + KEY_BSSID + ")" + ")";
+
+	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_GEO_TIMESTAMP + " INTEGER" + ")";
+
+	public UglyDbHelper(Context context) {
+		super(context, DATABASE_NAME, null, DATABASE_VERSION);
+	}
+
+	/*
+	 * // Contacts Table Columns names private static final String KEY_ID =
+	 * "_id"; private static final String KEY_ATTACK_ID = "_attack_id"; private
+	 * static final String KEY_TYPE = "type"; private static final String
+	 * KEY_TIME = "timestamp"; private static final String KEY_PACKET =
+	 * "packet"; private static final String KEY_PROTOCOL = "protocol"; private
+	 * static final String KEY_EXTERNAL_IP ="externalIP"; private static final
+	 * String KEY_LOCAL_IP = "localIP"; private static final String
+	 * KEY_LOCAL_HOSTNAME = "localHostName"; private static final String
+	 * KEY_LOCAL_PORT = "localPort"; private static final String KEY_REMOTE_IP =
+	 * "remoteIP"; private static final String KEY_REMOTE_HOSTNAME =
+	 * "remoteHostName"; private static final String KEY_REMOTE_PORT =
+	 * "remotePort"; private static final String KEY_BSSID = "_bssid"; private
+	 * static final String KEY_SSID = "ssid"; private static final String
+	 * KEY_LATITUDE = "latitude"; private static final String KEY_LONGITUDE =
+	 * "longitude"; private static final String KEY_ACCURACY = "accuracy";
+	 */
+
+	/**
+	 * Gets all received {@link Record Records} for the specified information in
+	 * the LogFilter ordered by date.
+	 * 
+	 * @return A ArrayList with all received {@link Record Records} for the
+	 *         LogFilter.
+	 */
+	public ArrayList<Record> getRecordsForFilter(LogFilter filter) {
+		ArrayList<Record> recordList = new ArrayList<Record>();
+		String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_ATTACK_INFO + " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID
+				+ ")";
+
+		// TIMESTAMPS
+		selectQuery = selectQuery + " WHERE " + TABLE_RECORDS + "." + KEY_TIME;
+		selectQuery = selectQuery + " < " + filter.getBelowTimestamp();
+		selectQuery = selectQuery + " AND " + TABLE_RECORDS + "." + KEY_TIME;
+		selectQuery = selectQuery + " > " + filter.getAboveTimestamp();
+
+		if (filter.getBSSIDs() != null && filter.getBSSIDs().size() > 0) {
+			selectQuery = selectQuery + " AND ";
+			selectQuery = selectQuery + filter.getBSSIDQueryStatement(TABLE_BSSIDS, KEY_BSSID);
+		}
+		if (filter.getESSIDs() != null && filter.getESSIDs().size() > 0) {
+			selectQuery = selectQuery + " AND ";
+			selectQuery = selectQuery + filter.getESSIDQueryStatement(TABLE_BSSIDS, KEY_SSID);
+		}
+		if (filter.getProtocols() != null && filter.getProtocols().size() > 0) {
+			selectQuery = selectQuery + " AND ";
+			selectQuery = selectQuery + filter.getProtocolsQueryStatement(TABLE_ATTACK_INFO, KEY_PROTOCOL);
+		}
+
+		selectQuery = selectQuery + " GROUP BY " + TABLE_RECORDS + "." + KEY_ATTACK_ID;
+
+		if (filter.getSorttype() == LogFilter.SortType.packet_timestamp) {
+			// DESC
+			selectQuery = selectQuery + " ORDER BY " + filter.getSorttype() + " DESC";
+		} else {
+			selectQuery = selectQuery + " ORDER BY " + filter.getSorttype();
+		}
+
+		System.out.println(selectQuery);
+		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 all non duplicate Records For the key BSSID.
+	 * 
+	 * @return A ArrayList with received Records.
+	 */
+	public ArrayList<String> getUniqueBSSIDRecords() {
+		return this.getUniqueDataEntryForKeyType(KEY_BSSID, TABLE_BSSIDS);
+	}
+
+	/**
+	 * Gets all non duplicate Records For the key ESSID.
+	 * 
+	 * @return A ArrayList with received Records.
+	 */
+	public ArrayList<String> getUniqueESSIDRecords() {
+		return this.getUniqueDataEntryForKeyType(KEY_SSID, TABLE_BSSIDS);
+	}
+
+	public ArrayList<String> getUniqueESSIDRecordsForProtocol(String protocol) {
+		return this.getUniqueIDForProtocol(KEY_SSID, protocol);
+	}
+
+	public ArrayList<String> getUniqueBSSIDRecordsForProtocol(String protocol) {
+		return this.getUniqueIDForProtocol(KEY_BSSID, protocol);
+	}
+
+	private ArrayList<String> getUniqueIDForProtocol(String id, String protocol) {
+		ArrayList<String> recordList = new ArrayList<String>();
+		String selectQuery = "SELECT DISTINCT " + id + " FROM " + TABLE_ATTACK_INFO + " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ") " + " WHERE "
+				+ TABLE_ATTACK_INFO + "." + KEY_PROTOCOL + " = " + "'" + protocol + "'" + " ORDER BY " + id; // " NATURAL JOIN "
+																												// +
+																												// TABLE_ATTACK_INFO
+																												// +
+																												// " NATURAL JOIN "
+																												// +
+																												// TABLE_BSSIDS
+																												// +
+																												// " NATURAL JOIN "
+																												// +
+																												// TABLE_PORTS
+																												// +
+
+		// ORDERED BY TIME
+		System.out.println(selectQuery);
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(selectQuery, null);
+
+		// looping through all rows and adding to list
+		if (cursor.moveToFirst()) {
+			do {
+				String record = cursor.getString(0);
+				recordList.add(record);
+			} while (cursor.moveToNext());
+		}
+		cursor.close();
+
+		// return record list
+		db.close();
+		return recordList;
+	}
+
+	/**
+	 * Gets all non duplicate Data Entry For a specific KeyType ( e.g. BSSIDs).
+	 * 
+	 * @return A ArrayList with received Records.
+	 */
+	public ArrayList<String> getUniqueDataEntryForKeyType(String keyType, String table) {
+		ArrayList<String> recordList = new ArrayList<String>();
+		// String selectQuery = "SELECT  * FROM " + TABLE_RECORDS +
+		// " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN " +
+		// TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS;
+		String selectQuery = "SELECT DISTINCT " + keyType + " FROM " + table + " ORDER BY " + keyType; // " NATURAL JOIN "
+																										// +
+																										// TABLE_ATTACK_INFO
+																										// +
+																										// " NATURAL JOIN "
+																										// +
+																										// TABLE_BSSIDS
+																										// +
+																										// " NATURAL JOIN "
+																										// +
+																										// TABLE_PORTS
+																										// +
+
+		// ORDERED BY TIME
+		System.out.println(selectQuery);
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(selectQuery, null);
+
+		// looping through all rows and adding to list
+		if (cursor.moveToFirst()) {
+			do {
+				String record = cursor.getString(0);
+				recordList.add(record);
+			} while (cursor.moveToNext());
+		}
+		cursor.close();
+
+		// return record list
+		db.close();
+		return recordList;
+	}
+
+	/**
+	 * 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_PORT, record.getLocalPort());
+		attackValues.put(KEY_REMOTE_IP, record.getRemoteIP()); // Log Remote IP
+		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);
+	}
+
+	/**
+	 * 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;
+	}
+
+	public int numBssidSeen(String BSSID) {
+		String countQuery = "SELECT  COUNT(*) FROM " + TABLE_ATTACK_INFO + " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ")" + " WHERE "
+				+ TABLE_BSSIDS + "." + KEY_BSSID + " = " + "'" + BSSID + "'";
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(countQuery, null);
+		cursor.moveToFirst();
+		int result = cursor.getInt(0);
+		cursor.close();
+		db.close();
+		return result;
+	}
+
+	public int numBssidSeen(String protocol, String BSSID) {
+		String countQuery = "SELECT  COUNT(*) FROM " + TABLE_ATTACK_INFO + " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ")" + " WHERE "
+				+ TABLE_ATTACK_INFO + "." + KEY_PROTOCOL + " = " + "'" + protocol + "'" + " AND " + TABLE_BSSIDS + "." + KEY_BSSID + " = " + "'" + BSSID + "'";
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(countQuery, null);
+		cursor.moveToFirst();
+		int result = cursor.getInt(0);
+		cursor.close();
+		db.close();
+		return result;
+	}
+
+	/**
+	 * 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 + " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ")" + " WHERE " + TABLE_ATTACK_INFO
+				+ "." + KEY_PROTOCOL + " = " + "'" + protocol + "'" + " AND " + TABLE_BSSIDS + "." + KEY_BSSID + " = " + "'" + BSSID + "'";
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(countQuery, null);
+		int result = cursor.getCount();
+		cursor.close();
+		db.close();
+		return result > 0;
+	}
+
+	/**
+	 * 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.delete(TABLE_PROFILES, null, null);
+		db.close();
+	}
+
+	/**
+	 * 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();
+	}
+
+	/**
+	 * 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 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 + " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID
+				+ ")" + " WHERE " + KEY_TYPE + "='RECEIVE'" + " ORDER BY " + TABLE_RECORDS + "." + 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 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 + " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID
+				+ ")";
+
+		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;
+	}
+
+	/**
+	 * 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 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;
+	}
+
+	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;
+	}
+
+	/**
+	 * 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 + " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID
+				+ ")" + " WHERE " + TABLE_RECORDS + "." + 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;
+	}
+
+	/**
+	 * 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;
+	}
+
+	/**
+	 * 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 + " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID
+				+ ")" + " WHERE " + TABLE_RECORDS + "." + KEY_ATTACK_ID + " = " + attack_id + " GROUP BY " + TABLE_RECORDS + "." + 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 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 + " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID
+				+ ")" + " GROUP BY " + TABLE_RECORDS + "." + 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;
+	}
+
+	/*
+	 * Returns the Conversation of a specific attack id
+	 * 
+	 * @param attack_id Tha attack id to match the query against.
+	 * 
+	 * @return A arraylist with all {@link Record Records}s for an attack id.
+	 */
+	public ArrayList<Record> getConversationForAttackID(long attack_id) {
+		ArrayList<Record> recordList = new ArrayList<Record>();
+		String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_ATTACK_INFO + " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID
+				+ ")" + " WHERE " + TABLE_RECORDS + "." + KEY_ATTACK_ID + " = " + attack_id;
+
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(selectQuery, null);
+
+		if (cursor.moveToFirst()) {
+			do {
+				Record record = createRecord(cursor);
+				recordList.add(record);
+			} while (cursor.moveToNext());
+		}
+		cursor.close();
+
+		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 + " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID
+				+ ")" + " WHERE " + TABLE_RECORDS + "." + KEY_ATTACK_ID + " > " + attack_id + " GROUP BY " + TABLE_RECORDS + "." + 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 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;
+	}
+
+	/**
+	 * 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;
+	}
+
+	// Creating Tables
+	@Override
+	public void onCreate(SQLiteDatabase db) {
+		db.execSQL(CREATE_BSSID_TABLE);
+		db.execSQL(CREATE_ATTACK_INFO_TABLE);
+		db.execSQL(CREATE_RECORD_TABLE);
+		db.execSQL(CREATE_PROFILE_TABLE);
+	}
+
+	// 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_PROFILES);
+
+		// Create tables again
+		onCreate(db);
+	}
+
+	/**
+	 * Retrieves all the profiles from the database
+	 * 
+	 * @return list of profiles
+	 */
+	public List<Profile> getAllProfiles() {
+		List<Profile> profiles = new LinkedList<Profile>();
+
+		// Select All Query
+		String selectQuery = "SELECT  * FROM " + TABLE_PROFILES;
+
+		SQLiteDatabase db = this.getWritableDatabase();
+		Cursor cursor = db.rawQuery(selectQuery, null);
+
+		// looping through all rows and adding to list
+		if (cursor.moveToFirst()) {
+			do {
+				Profile profile = new Profile(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getInt(5) == 1);
+
+				if (cursor.getInt(6) == 1) {
+					profile.mActivated = true;
+				}
+
+				profile.mIconName = cursor.getString(4);
+
+				// Adding record to list
+				profiles.add(profile);
+			} while (cursor.moveToNext());
+		}
+		cursor.close();
+		db.close();
+		// return record list
+		return profiles;
+	}
+
+	/**
+	 * Persists the given profile into the database
+	 * 
+	 * @param profile
+	 *            the profile which should be persisted
+	 * 
+	 * @return
+	 */
+	public long persistProfile(Profile profile) {
+		SQLiteDatabase db = this.getReadableDatabase();
+
+		ContentValues values = new ContentValues();
+
+		if (profile.mId != -1) {
+			values.put(KEY_PROFILE_ID, profile.mId);
+		}
+
+		values.put(KEY_PROFILE_NAME, profile.mLabel);
+		values.put(KEY_PROFILE_DESCRIPTION, profile.mText);
+		values.put(KEY_PROFILE_ICON, profile.mIconPath);
+		values.put(KEY_PROFILE_ICON_NAME, profile.mIconName);
+		values.put(KEY_PROFILE_ACTIVE, profile.mActivated);
+		values.put(KEY_PROFILE_EDITABLE, profile.mEditable);
+
+		return db.replace(TABLE_PROFILES, null, values);
+	}
+
+	/**
+	 * private static final String CREATE_PROFILE_TABLE = "CREATE TABLE " +
+	 * TABLE_PROFILES + "(" + KEY_PROFILE_ID +
+	 * " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_PROFILE_NAME + " TEXT," +
+	 * KEY_PROFILE_DESCRIPTION + " TEXT," + KEY_PROFILE_ICON + " TEXT," +
+	 * KEY_PROFILE_ICON_ID + " INTEGER," + KEY_PROFILE_EDITABLE + " INTEGER," +
+	 * KEY_PROFILE_ACTIVE + " INTEGER" + ")";
+	 */
+	public Profile getProfile(int id) {
+		String selectQuery = "SELECT  * FROM " + TABLE_PROFILES + " WHERE " + TABLE_PROFILES + "." + KEY_PROFILE_ID + " = " + id;
+		SQLiteDatabase db = this.getReadableDatabase();
+
+		Cursor cursor = db.rawQuery(selectQuery, null);
+		Profile profile = null;
+
+		if (cursor.moveToFirst()) {
+			profile = new Profile(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getInt(5) == 1);
+
+			if (cursor.getInt(6) == 1) {
+				profile.mActivated = true;
+			}
+
+			profile.mIconName = cursor.getString(5);
+		}
+
+		cursor.close();
+		db.close();
+
+		// return contact
+		return profile;
+	}
+
+	public void deleteProfile(int id) {
+		SQLiteDatabase db = this.getReadableDatabase();
+
+		db.delete(TABLE_PROFILES, KEY_PROFILE_ID + "=?", new String[] { String.valueOf(id) });
+	}
+
+	public void updateNetworkInformation(ArrayList<HashMap<String, Object>> networkInformation) {
+		Log.i("DatabaseHandler", "Starte updating");
+		for (HashMap<String, Object> values : networkInformation) {
+			updateNetworkInformation(values);
+		}
+	}
+
+	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();
+	}
+
+	/**
+	 * 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(TYPE.valueOf(cursor.getString(2)));
+		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.setLocalPort(Integer.parseInt(cursor.getString(8)));
+
+		record.setRemoteIP(cursor.getString(9));
+		record.setRemotePort(Integer.parseInt(cursor.getString(10)));
+
+		record.setBssid(cursor.getString(11));
+		record.setSsid(cursor.getString(12));
+		record.setLatitude(Double.parseDouble(cursor.getString(13)));
+		record.setLongitude(Double.parseDouble(cursor.getString(14)));
+		record.setAccuracy(Float.parseFloat(cursor.getString(15)));
+		record.setTimestampLocation(cursor.getLong(16));
+
+		return record;
+	}
+}

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/logging/MyLocationManager.java → src/de/tudarmstadt/informatik/hostage/location/MyLocationManager.java

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.logging;
+package de.tudarmstadt.informatik.hostage.location;
 
 import java.util.Timer;
 import java.util.TimerTask;
@@ -88,7 +88,7 @@ public class MyLocationManager {
 
 	/**
 	 * Start updating
-	 * {@link de.tudarmstadt.informatik.hostage.logging.MyLocationManager#newestLocatio
+	 * {@link de.tudarmstadt.informatik.hostage.location.MyLocationManager#newestLocatio
 	 * newestLocation} if a location provider is enabled and available.
 	 */
 	public void startUpdates() {

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

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

+ 3 - 276
src/de/tudarmstadt/informatik/hostage/logging/Logger.java

@@ -1,143 +1,15 @@
 package de.tudarmstadt.informatik.hostage.logging;
 
-import java.util.ArrayList;
-
 import android.app.IntentService;
 import android.content.Context;
 import android.content.Intent;
-import android.os.Bundle;
-import android.os.ResultReceiver;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
 
-/**
- * An {@link IntentService} subclass for handling asynchronous task requests in
- * a service on a separate handler thread.
- * 
- * @author Mihai Plasoianu
- */
 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 deleteAll(Context context) {
-		Intent intent = new Intent(context, Logger.class);
-		intent.setAction(ACTION_CLEAR_ALL);
-		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 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 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 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 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 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 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 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 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 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 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 log(Context context, Record record) {
 		Intent intent = new Intent(context, Logger.class);
@@ -146,7 +18,7 @@ public class Logger extends IntentService {
 		context.startService(intent);
 	}
 
-	private UglyDbHelper mDbHelper;
+	private HostageDBOpenHelper mDbHelper;
 
 	public Logger() {
 		super("Logger");
@@ -155,68 +27,9 @@ public class Logger extends IntentService {
 	@Override
 	public void onCreate() {
 		super.onCreate();
-		mDbHelper = new UglyDbHelper(getApplicationContext());
-	}
-
-	private boolean handleActionBssidSeen(String protocol, String bssid) {
-		return mDbHelper.bssidSeen(protocol, bssid);
-	}
-
-	/**
-	 * Delete all records.
-	 */
-	private void handleActionDeleteAll() {
-		mDbHelper.clearData();
-	}
-
-	private void handleActionDeleteByBssid(String bssid) {
-		mDbHelper.deleteByBSSID(bssid);
-	}
-
-	private void handleActionDeleteByDate(long time) {
-		mDbHelper.deleteByDate(time);
-	}
-
-	private String[] handleActionGetAllBssids() {
-		return mDbHelper.getAllBSSIDS();
-	}
-
-	private ArrayList<Record> handleActionGetAllRecords() {
-		return mDbHelper.getAllRecords();
-	}
-
-	private int handleActionGetAttackCount() {
-		return mDbHelper.getAttackCount();
-	}
-
-	private int handleActionGetAttackPerProtocolCount(String protocol) {
-		return mDbHelper.getAttackPerProtocolCount(protocol);
-	}
-
-	private long handleActionGetMaxAttackId() {
-		return mDbHelper.getHighestAttackId();
-	}
-
-	private long handleActionGetMinAttackId() {
-		return mDbHelper.getSmallestAttackId();
-	}
-
-	private Record handleActionGetRecordOfAttackId(long attack_id) {
-		return mDbHelper.getRecordOfAttackId(attack_id);
-	}
-
-	private ArrayList<Record> handleActionGetRecordOfEachAttack(
-			int lastUploadedAttackId) {
-		return mDbHelper.getRecordOfEachAttack(lastUploadedAttackId);
-	}
-
-	private String handleActionGetSsid(String bssid) {
-		return mDbHelper.getSSID(bssid);
+		mDbHelper = new HostageDBOpenHelper(getApplicationContext());
 	}
 
-	/**
-	 * Log a record.
-	 */
 	private void handleActionLog(Record record) {
 		mDbHelper.addRecord(record);
 	}
@@ -228,92 +41,6 @@ public class Logger extends IntentService {
 			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();
 			}
 		}
 	}

+ 0 - 34
src/de/tudarmstadt/informatik/hostage/logging/Record.java

@@ -4,18 +4,6 @@ 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>
- * 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}
- * 
- * @author Mihai Plasoianu
- * @author Lars Pandikow
- */
 public class Record implements Parcelable {
 
 	public static enum TYPE {
@@ -32,10 +20,8 @@ public class Record implements Parcelable {
 
 	// network
 	private String localIP;
-	private String localHost;
 	private int localPort;
 	private String remoteIP;
-	private String remoteHost;
 	private int remotePort;
 	private String externalIP;
 	private String bssid;
@@ -74,10 +60,8 @@ public class Record implements Parcelable {
 
 		// 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();
@@ -119,10 +103,6 @@ public class Record implements Parcelable {
 		return latitude;
 	}
 
-	public String getLocalHost() {
-		return localHost;
-	}
-
 	public String getLocalIP() {
 		return localIP;
 	}
@@ -143,10 +123,6 @@ public class Record implements Parcelable {
 		return protocol;
 	}
 
-	public String getRemoteHost() {
-		return remoteHost;
-	}
-
 	public String getRemoteIP() {
 		return remoteIP;
 	}
@@ -195,10 +171,6 @@ public class Record implements Parcelable {
 		this.latitude = latitude;
 	}
 
-	public void setLocalHost(String localHost) {
-		this.localHost = localHost;
-	}
-
 	public void setLocalIP(String localIP) {
 		this.localIP = localIP;
 	}
@@ -219,10 +191,6 @@ public class Record implements Parcelable {
 		this.protocol = protocol;
 	}
 
-	public void setRemoteHost(String remoteHost) {
-		this.remoteHost = remoteHost;
-	}
-
 	public void setRemoteIP(String remoteIP) {
 		this.remoteIP = remoteIP;
 	}
@@ -271,10 +239,8 @@ public class Record implements Parcelable {
 
 		// 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);

+ 1 - 3
src/de/tudarmstadt/informatik/hostage/logging/formatter/TraCINgFormatter.java

@@ -17,9 +17,7 @@ public class TraCINgFormatter extends Formatter {
 	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());
+						record.getProtocol(), record.getRemoteIP(), record.getRemotePort(), record.getExternalIP(), record.getLocalPort());
 	}
 
 }

+ 47 - 0
src/de/tudarmstadt/informatik/hostage/net/MyDatagramSocketFactory.java

@@ -0,0 +1,47 @@
+package de.tudarmstadt.informatik.hostage.net;
+
+import java.io.FileDescriptor;
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.net.DatagramSocket;
+import java.net.DatagramSocketImpl;
+
+import de.tudarmstadt.informatik.hostage.system.Device;
+import de.tudarmstadt.informatik.hostage.system.PrivilegedPort;
+import de.tudarmstadt.informatik.hostage.system.PrivilegedPort.TYPE;
+
+public class MyDatagramSocketFactory {
+
+	public DatagramSocket createDatagramSocket(int port) throws IOException {
+		DatagramSocket socket = null;
+		if (port > 1023) {
+			socket = new DatagramSocket(port);
+		} else if (Device.isPorthackInstalled()) {
+			FileDescriptor fd = new PrivilegedPort(TYPE.UDP, port).getFD();
+			socket = new DatagramSocket();
+			try {
+				DatagramSocketImpl impl = getImpl(socket);
+				injectFD(fd, impl);
+			} catch (NoSuchFieldException e) {
+			} catch (IllegalAccessException e) {
+			} catch (IllegalArgumentException e) {
+			}
+		}
+		return socket;
+	}
+
+	private DatagramSocketImpl getImpl(DatagramSocket socket) throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
+		Field implField = socket.getClass().getDeclaredField("impl");
+		implField.setAccessible(true);
+		return (DatagramSocketImpl) implField.get(socket);
+	}
+
+	private void injectFD(FileDescriptor fd, DatagramSocketImpl impl) throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
+		Class<?> plainDatagramSocketImplClazz = impl.getClass();
+		Class<?> datagramSocketImplClazz = plainDatagramSocketImplClazz.getSuperclass();
+		Field fdField = datagramSocketImplClazz.getDeclaredField("fd");
+		fdField.setAccessible(true);
+		fdField.set(impl, fd);
+	}
+
+}

+ 14 - 50
src/de/tudarmstadt/informatik/hostage/net/MyServerSocketFactory.java

@@ -10,21 +10,13 @@ import java.net.SocketImpl;
 
 import javax.net.ServerSocketFactory;
 
-import de.tudarmstadt.informatik.hostage.system.P;
+import de.tudarmstadt.informatik.hostage.system.Device;
+import de.tudarmstadt.informatik.hostage.system.PrivilegedPort;
+import de.tudarmstadt.informatik.hostage.system.PrivilegedPort.TYPE;
 import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
 
-/**
- * Server Socket Factory using file descriptors.
- * 
- * @author Mihai Plasoianu
- * @author Lars Pandikow
- */
 public class MyServerSocketFactory extends ServerSocketFactory {
 
-	/**
-	 * This method creates and returns a ServerSocket. A custom SocketImpl is
-	 * injected into the ServerSocket.
-	 */
 	@Override
 	public ServerSocket createServerSocket(int port) throws IOException {
 		ServerSocket socket = null;
@@ -32,75 +24,47 @@ public class MyServerSocketFactory extends ServerSocketFactory {
 			socket = new ServerSocket();
 			socket.setReuseAddress(true);
 			socket.bind(new InetSocketAddress(port));
-		} else if (MainActivity.porthackInstalled) {
-			FileDescriptor fd = new P(port).bindAndGetFD();
+		} else if (Device.isPorthackInstalled()) {
+			FileDescriptor fd = new PrivilegedPort(TYPE.TCP, port).getFD();
 			socket = new ServerSocket();
 			try {
 				SocketImpl impl = getImpl(socket);
 				injectFD(fd, impl);
-				injectImpl(impl, socket);
 				setBound(socket);
-			} catch (Exception e) {
-				e.printStackTrace();
+			} catch (NoSuchFieldException e) {
+			} catch (IllegalAccessException e) {
+			} catch (IllegalArgumentException e) {
 			}
 		}
 		return socket;
 	}
 
-	/**
-	 * Must override.
-	 */
 	@Override
-	public ServerSocket createServerSocket(int port, int backlog)
-			throws IOException {
+	public ServerSocket createServerSocket(int port, int backlog) throws IOException {
 		return createServerSocket(port);
 	}
 
-	/**
-	 * Must override.
-	 */
 	@Override
-	public ServerSocket createServerSocket(int port, int backlog,
-			InetAddress iAddress) throws IOException {
+	public ServerSocket createServerSocket(int port, int backlog, InetAddress iAddress) throws IOException {
 		return createServerSocket(port);
 	}
 
-	/**
-	 * Extracts the SocketImpl out of a ServerSocket.
-	 */
-	private SocketImpl getImpl(ServerSocket socket) throws Exception {
+	private SocketImpl getImpl(ServerSocket socket) throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
 		Field implField = socket.getClass().getDeclaredField("impl");
 		implField.setAccessible(true);
 		return (SocketImpl) implField.get(socket);
 	}
 
-	/**
-	 * Injects a FileDescriptor into a SocketImpl.
-	 */
-	private void injectFD(FileDescriptor fd, SocketImpl impl) throws Exception {
+	private void injectFD(FileDescriptor fd, SocketImpl impl) throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
 		Class<?> plainServerSocketImplClazz = impl.getClass();
-		Class<?> plainSocketImplClazz = plainServerSocketImplClazz
-				.getSuperclass();
+		Class<?> plainSocketImplClazz = plainServerSocketImplClazz.getSuperclass();
 		Class<?> socketImplClazz = plainSocketImplClazz.getSuperclass();
 		Field fdField = socketImplClazz.getDeclaredField("fd");
 		fdField.setAccessible(true);
 		fdField.set(impl, fd);
 	}
 
-	/**
-	 * Injects a SocketImpl into a ServerSocket.
-	 */
-	private void injectImpl(SocketImpl impl, ServerSocket socket)
-			throws Exception {
-		Field implField = socket.getClass().getDeclaredField("impl");
-		implField.setAccessible(true);
-		implField.set(socket, impl);
-	}
-
-	/**
-	 * Sets the isBound Field of a ServerSocket to true.
-	 */
-	private void setBound(ServerSocket socket) throws Exception {
+	private void setBound(ServerSocket socket) throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
 		Field boundField = socket.getClass().getDeclaredField("isBound");
 		boundField.setAccessible(true);
 		boundField.set(socket, true);

+ 4 - 3
src/de/tudarmstadt/informatik/hostage/nio/Reader.java

@@ -10,18 +10,19 @@ import de.tudarmstadt.informatik.hostage.wrapper.Packet;
 public class Reader {
 
 	BufferedInputStream in;
+	String protocol;
 
-	public Reader(InputStream in) {
+	public Reader(InputStream in, String protocol) {
 		this.in = new BufferedInputStream(in);
+		this.protocol = protocol;
 	}
 
 	public Packet read() throws IOException {
 		ByteArrayOutputStream payload = new ByteArrayOutputStream();
 		do {
 			payload.write(in.read());
-			Thread.yield();
 		} while (in.available() > 0);
-		return new Packet(payload.toByteArray());
+		return new Packet(payload.toByteArray(), protocol);
 	}
 
 }

+ 0 - 1
src/de/tudarmstadt/informatik/hostage/nio/Writer.java

@@ -18,7 +18,6 @@ public class Writer {
 	public void write(List<Packet> packets) throws IOException {
 		for (Packet packet : packets) {
 			out.write(packet.getBytes());
-			out.write('\n');
 		}
 		out.flush();
 	}

+ 44 - 0
src/de/tudarmstadt/informatik/hostage/persistence/HostageDBContract.java

@@ -0,0 +1,44 @@
+package de.tudarmstadt.informatik.hostage.persistence;
+
+import android.provider.BaseColumns;
+
+public final class HostageDBContract {
+
+	public static abstract class NetworkEntry implements BaseColumns {
+		public static final String TABLE_NAME = "network";
+		public static final String COLUMN_NAME_BSSID = "_bssid";
+		public static final String COLUMN_NAME_SSID = "ssid";
+		public static final String COLUMN_NAME_LATITUDE = "latitude";
+		public static final String COLUMN_NAME_LONGITUDE = "longitude";
+		public static final String COLUMN_NAME_ACCURACY = "accuracy";
+		public static final String COLUMN_NAME_GEO_TIMESTAMP = "geo_timestamp";
+
+		public static final String KEY_ID = COLUMN_NAME_BSSID;
+	}
+
+	public static abstract class AttackEntry implements BaseColumns {
+		public static final String TABLE_NAME = "attack";
+		public static final String COLUMN_NAME_ATTACK_ID = "_attack_id";
+		public static final String COLUMN_NAME_PROTOCOL = "protocol";
+		public static final String COLUMN_NAME_EXTERNAL_IP = "externalIP";
+		public static final String COLUMN_NAME_LOCAL_IP = "localIP";
+		public static final String COLUMN_NAME_LOCAL_PORT = "localPort";
+		public static final String COLUMN_NAME_REMOTE_IP = "remoteIP";
+		public static final String COLUMN_NAME_REMOTE_PORT = "remotePort";
+		public static final String COLUMN_NAME_BSSID = "_bssid";
+
+		public static final String KEY_ID = COLUMN_NAME_ATTACK_ID;
+	}
+
+	public static abstract class PacketEntry implements BaseColumns {
+		public static final String TABLE_NAME = "packet";
+		public static final String COLUMN_NAME_ID = "_id";
+		public static final String COLUMN_NAME_ATTACK_ID = "_attack_id";
+		public static final String COLUMN_NAME_TYPE = "type";
+		public static final String COLUMN_NAME_PACKET_TIMESTAMP = "packet_timestamp";
+		public static final String COLUMN_NAME_PACKET = "packet";
+
+		public static final String KEY_ID = COLUMN_NAME_ID;
+	}
+
+}

+ 626 - 0
src/de/tudarmstadt/informatik/hostage/persistence/HostageDBOpenHelper.java

@@ -0,0 +1,626 @@
+package de.tudarmstadt.informatik.hostage.persistence;
+
+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.logging.Record;
+import de.tudarmstadt.informatik.hostage.logging.Record.TYPE;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.AttackEntry;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.NetworkEntry;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.PacketEntry;
+
+public class HostageDBOpenHelper extends SQLiteOpenHelper {
+
+	private static final String DATABASE_NAME = "hostage.db";
+	private static final int DATABASE_VERSION = 1;
+
+	static {
+		StringBuilder networkSQLBuilder = new StringBuilder("CREATE TABLE ").append(NetworkEntry.TABLE_NAME).append("(");
+		networkSQLBuilder.append(NetworkEntry.COLUMN_NAME_BSSID).append(" TEXT PRIMARY KEY,");
+		networkSQLBuilder.append(NetworkEntry.COLUMN_NAME_SSID).append(" TEXT,");
+		networkSQLBuilder.append(NetworkEntry.COLUMN_NAME_LATITUDE).append(" INTEGER,");
+		networkSQLBuilder.append(NetworkEntry.COLUMN_NAME_LONGITUDE).append(" INTEGER,");
+		networkSQLBuilder.append(NetworkEntry.COLUMN_NAME_ACCURACY).append(" INTEGER,");
+		networkSQLBuilder.append(NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP).append(" INTEGER");
+		networkSQLBuilder.append(")");
+		SQL_CREATE_NETWORK_ENTRIES = networkSQLBuilder.toString();
+
+		StringBuilder attackSQLBuilder = new StringBuilder("CREATE TABLE ").append(AttackEntry.TABLE_NAME).append("(");
+		attackSQLBuilder.append(AttackEntry.COLUMN_NAME_ATTACK_ID).append(" INTEGER PRIMARY KEY,");
+		attackSQLBuilder.append(AttackEntry.COLUMN_NAME_PROTOCOL).append(" TEXT,");
+		attackSQLBuilder.append(AttackEntry.COLUMN_NAME_EXTERNAL_IP).append(" TEXT,");
+		attackSQLBuilder.append(AttackEntry.COLUMN_NAME_LOCAL_IP).append(" BLOB,");
+		attackSQLBuilder.append(AttackEntry.COLUMN_NAME_LOCAL_PORT).append(" INTEGER,");
+		attackSQLBuilder.append(AttackEntry.COLUMN_NAME_REMOTE_IP).append(" BLOB,");
+		attackSQLBuilder.append(AttackEntry.COLUMN_NAME_REMOTE_PORT).append(" INTEGER,");
+		attackSQLBuilder.append(AttackEntry.COLUMN_NAME_BSSID).append(" TEXT,");
+		attackSQLBuilder.append(String.format("FOREIGN KEY(%s) REFERENCES %s(%s)", AttackEntry.COLUMN_NAME_BSSID, NetworkEntry.TABLE_NAME,
+				NetworkEntry.COLUMN_NAME_BSSID));
+		attackSQLBuilder.append(")");
+		SQL_CREATE_ATTACK_ENTRIES = attackSQLBuilder.toString();
+
+		StringBuilder packetSQLBuilder = new StringBuilder("CREATE TABLE ").append(PacketEntry.TABLE_NAME).append("(");
+		packetSQLBuilder.append(PacketEntry.COLUMN_NAME_ID).append(" INTEGER NOT NULL,");
+		packetSQLBuilder.append(PacketEntry.COLUMN_NAME_ATTACK_ID).append(" INTEGER NOT NULL,");
+		packetSQLBuilder.append(PacketEntry.COLUMN_NAME_TYPE).append(" TEXT,");
+		packetSQLBuilder.append(PacketEntry.COLUMN_NAME_PACKET_TIMESTAMP).append(" INTEGER,");
+		packetSQLBuilder.append(PacketEntry.COLUMN_NAME_PACKET).append(" TEXT,");
+		packetSQLBuilder.append(String.format("PRIMARY KEY(%s,%s)", PacketEntry.COLUMN_NAME_ID, PacketEntry.COLUMN_NAME_ATTACK_ID));
+		packetSQLBuilder.append(String.format("FOREIGN KEY(%s) REFERENCES %s(%s)", PacketEntry.COLUMN_NAME_ATTACK_ID, AttackEntry.TABLE_NAME,
+				AttackEntry.COLUMN_NAME_ATTACK_ID));
+		packetSQLBuilder.append(")");
+		SQL_CREATE_PACKET_ENTRIES = packetSQLBuilder.toString();
+	}
+
+	private static final String SQL_CREATE_NETWORK_ENTRIES;
+	private static final String SQL_CREATE_ATTACK_ENTRIES;
+	private static final String SQL_CREATE_PACKET_ENTRIES;
+
+	private static final String SQL_DELETE_PACKET_ENTRIES = "DROP TABLE IF EXISTS " + PacketEntry.TABLE_NAME;
+	private static final String SQL_DELETE_ATTACK_ENTRIES = "DROP TABLE IF EXISTS " + AttackEntry.TABLE_NAME;
+	private static final String SQL_DELETE_NETWORK_ENTRIES = "DROP TABLE IF EXISTS " + NetworkEntry.TABLE_NAME;
+
+	public HostageDBOpenHelper(Context context) {
+		super(context, DATABASE_NAME, null, DATABASE_VERSION);
+	}
+
+	@Override
+	public void onCreate(SQLiteDatabase db) {
+		db.execSQL(SQL_CREATE_PACKET_ENTRIES);
+		db.execSQL(SQL_CREATE_ATTACK_ENTRIES);
+		db.execSQL(SQL_CREATE_NETWORK_ENTRIES);
+	}
+
+	@Override
+	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
+		db.execSQL(SQL_DELETE_PACKET_ENTRIES);
+		db.execSQL(SQL_DELETE_ATTACK_ENTRIES);
+		db.execSQL(SQL_DELETE_NETWORK_ENTRIES);
+		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(NetworkEntry.COLUMN_NAME_BSSID, record.getBssid());
+		bssidValues.put(NetworkEntry.COLUMN_NAME_SSID, record.getSsid());
+		bssidValues.put(NetworkEntry.COLUMN_NAME_LATITUDE, record.getLatitude());
+		bssidValues.put(NetworkEntry.COLUMN_NAME_LONGITUDE, record.getLongitude());
+		bssidValues.put(NetworkEntry.COLUMN_NAME_ACCURACY, record.getAccuracy());
+		bssidValues.put(NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP, record.getTimestampLocation());
+
+		ContentValues attackValues = new ContentValues();
+		attackValues.put(AttackEntry.COLUMN_NAME_ATTACK_ID, record.getAttack_id()); // Log
+																					// Attack
+																					// ID
+		attackValues.put(AttackEntry.COLUMN_NAME_PROTOCOL, record.getProtocol().toString());
+		attackValues.put(AttackEntry.COLUMN_NAME_EXTERNAL_IP, record.getExternalIP());
+		attackValues.put(AttackEntry.COLUMN_NAME_LOCAL_IP, record.getLocalIP()); // Log
+																					// Local
+																					// IP
+		attackValues.put(AttackEntry.COLUMN_NAME_LOCAL_PORT, record.getLocalPort());
+		attackValues.put(AttackEntry.COLUMN_NAME_REMOTE_IP, record.getRemoteIP()); // Log
+																					// Remote
+																					// IP
+		attackValues.put(AttackEntry.COLUMN_NAME_REMOTE_PORT, record.getRemotePort()); // Log
+																						// Remote
+																						// Port
+		attackValues.put(AttackEntry.COLUMN_NAME_BSSID, record.getBssid());
+
+		ContentValues recordValues = new ContentValues();
+		recordValues.put(PacketEntry.COLUMN_NAME_ID, record.getId()); // Log
+																		// Message
+																		// Number
+		recordValues.put(PacketEntry.COLUMN_NAME_ATTACK_ID, record.getAttack_id()); // Log
+																					// Attack
+																					// ID
+		recordValues.put(PacketEntry.COLUMN_NAME_TYPE, record.getType().name()); // Log
+																					// Type
+		recordValues.put(PacketEntry.COLUMN_NAME_PACKET_TIMESTAMP, record.getTimestamp()); // Log
+																							// Timestamp
+		recordValues.put(PacketEntry.COLUMN_NAME_PACKET, record.getPacket()); // Log
+																				// Packet
+
+		// Inserting Rows
+		db.insertWithOnConflict(AttackEntry.TABLE_NAME, null, attackValues, SQLiteDatabase.CONFLICT_REPLACE);
+		db.insert(PacketEntry.TABLE_NAME, null, recordValues);
+		db.close(); // Closing database connection
+		// Update Network Information
+		updateNetworkInformation(bssidValues);
+	}
+
+	/**
+	 * 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 " + NetworkEntry.TABLE_NAME + " WHERE " + NetworkEntry.COLUMN_NAME_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 " + AttackEntry.TABLE_NAME + " NATURAL JOIN " + NetworkEntry.TABLE_NAME + " WHERE "
+				+ AttackEntry.COLUMN_NAME_PROTOCOL + " = " + "'" + protocol + "'" + " AND " + NetworkEntry.COLUMN_NAME_BSSID + " = " + "'" + BSSID + "'";
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(countQuery, null);
+		int result = cursor.getCount();
+		cursor.close();
+		db.close();
+		return result > 0;
+	}
+
+	/**
+	 * Deletes all records from {@link #PacketEntry.TABLE_NAME}.
+	 */
+	public void clearData() {
+		SQLiteDatabase db = this.getReadableDatabase();
+		db.delete(PacketEntry.TABLE_NAME, null, null);
+		db.delete(AttackEntry.TABLE_NAME, null, null);
+		db.close();
+	}
+
+	/**
+	 * Deletes all records from {@link #PacketEntry.TABLE_NAME} with a specific BSSID.
+	 * 
+	 * @param bssid
+	 *            The BSSID to match against.
+	 */
+	public void deleteByBSSID(String bssid) {
+		SQLiteDatabase db = this.getReadableDatabase();
+		db.delete(NetworkEntry.TABLE_NAME, NetworkEntry.COLUMN_NAME_BSSID + " = ?", new String[] { bssid });
+		db.delete(AttackEntry.TABLE_NAME, AttackEntry.COLUMN_NAME_BSSID + " = ?", new String[] { bssid });
+		db.close();
+	}
+
+	/**
+	 * Deletes all records from {@link #PacketEntry.TABLE_NAME} 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 " + PacketEntry.TABLE_NAME + " WHERE " + PacketEntry.COLUMN_NAME_PACKET_TIMESTAMP + " < " + date;
+		db.execSQL(deleteQuery);
+		db.close();
+	}
+
+	/**
+	 * Returns a String array with all BSSIDs stored in the database.
+	 * 
+	 * @return String[] of all recorded BSSIDs.
+	 */
+	public String[] getAllBSSIDS() {
+		String selectQuery = "SELECT  * FROM " + NetworkEntry.TABLE_NAME;
+		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 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 " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " NATURAL JOIN "
+				+ NetworkEntry.TABLE_NAME + " WHERE " + PacketEntry.COLUMN_NAME_TYPE + "='RECEIVE'" + " ORDER BY " + PacketEntry.COLUMN_NAME_PACKET_TIMESTAMP;
+		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 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 " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " JOIN " + NetworkEntry.TABLE_NAME
+				+ " USING (_bssid)";
+
+		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;
+	}
+
+	/**
+	 * 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 " + AttackEntry.TABLE_NAME;
+		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 " + AttackEntry.TABLE_NAME + " WHERE " + AttackEntry.COLUMN_NAME_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 highest attack id stored in the database.
+	 * 
+	 * @return The highest attack id stored in the database.
+	 */
+	public long getHighestAttackId() {
+		String selectQuery = "SELECT MAX(" + AttackEntry.COLUMN_NAME_ATTACK_ID + ") FROM " + AttackEntry.TABLE_NAME;
+		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;
+	}
+
+	public ArrayList<HashMap<String, Object>> getNetworkInformation() {
+		String selectQuery = "SELECT  * FROM " + NetworkEntry.TABLE_NAME;
+		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(NetworkEntry.COLUMN_NAME_BSSID, cursor.getString(0));
+				values.put(NetworkEntry.COLUMN_NAME_SSID, cursor.getString(1));
+				values.put(NetworkEntry.COLUMN_NAME_LATITUDE, Double.parseDouble(cursor.getString(2)));
+				values.put(NetworkEntry.COLUMN_NAME_LONGITUDE, Double.parseDouble(cursor.getString(3)));
+				values.put(NetworkEntry.COLUMN_NAME_ACCURACY, Float.parseFloat(cursor.getString(4)));
+				values.put(NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP, cursor.getLong(5));
+				networkInformation.add(values);
+			} while (cursor.moveToNext());
+		}
+
+		cursor.close();
+		db.close();
+		return networkInformation;
+	}
+
+	/**
+	 * 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 " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " NATURAL JOIN "
+				+ NetworkEntry.TABLE_NAME + " WHERE " + PacketEntry.COLUMN_NAME_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;
+	}
+
+	/**
+	 * 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 " + PacketEntry.TABLE_NAME;
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(countQuery, null);
+		int result = cursor.getCount();
+		cursor.close();
+
+		// return count
+		db.close();
+		return result;
+	}
+
+	/**
+	 * 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 " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " NATURAL JOIN "
+				+ NetworkEntry.TABLE_NAME + " WHERE " + AttackEntry.COLUMN_NAME_ATTACK_ID + " = " + attack_id + " GROUP BY "
+				+ AttackEntry.COLUMN_NAME_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 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 " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " NATURAL JOIN "
+				+ NetworkEntry.TABLE_NAME + " GROUP BY " + AttackEntry.COLUMN_NAME_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 " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " NATURAL JOIN "
+				+ NetworkEntry.TABLE_NAME + " WHERE " + AttackEntry.COLUMN_NAME_ATTACK_ID + " > " + attack_id + " GROUP BY "
+				+ AttackEntry.COLUMN_NAME_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 smallest attack id stored in the database.
+	 * 
+	 * @return The smallest attack id stored in the database.
+	 */
+	public long getSmallestAttackId() {
+		String selectQuery = "SELECT MIN(" + AttackEntry.COLUMN_NAME_ATTACK_ID + ") FROM " + AttackEntry.TABLE_NAME;
+		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;
+	}
+
+	/**
+	 * 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 " + NetworkEntry.COLUMN_NAME_SSID + " FROM " + NetworkEntry.TABLE_NAME + " WHERE " + NetworkEntry.COLUMN_NAME_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;
+	}
+
+	public void updateNetworkInformation(ArrayList<HashMap<String, Object>> networkInformation) {
+		Log.i("DatabaseHandler", "Starte updating");
+		for (HashMap<String, Object> values : networkInformation) {
+			updateNetworkInformation(values);
+		}
+	}
+
+	public void updateNetworkInformation(HashMap<String, Object> networkInformation) {
+		SQLiteDatabase db = this.getReadableDatabase();
+		String bssid = (String) networkInformation.get(NetworkEntry.COLUMN_NAME_BSSID);
+		String bssidQuery = "SELECT  * FROM " + NetworkEntry.TABLE_NAME + " WHERE " + NetworkEntry.COLUMN_NAME_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(NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP)))
+			;
+		{
+			ContentValues bssidValues = new ContentValues();
+			bssidValues.put(NetworkEntry.COLUMN_NAME_BSSID, bssid);
+			bssidValues.put(NetworkEntry.COLUMN_NAME_SSID, (String) networkInformation.get(NetworkEntry.COLUMN_NAME_SSID));
+			bssidValues.put(NetworkEntry.COLUMN_NAME_LATITUDE, (double) (Double) networkInformation.get(NetworkEntry.COLUMN_NAME_LATITUDE));
+			bssidValues.put(NetworkEntry.COLUMN_NAME_LONGITUDE, (double) (Double) networkInformation.get(NetworkEntry.COLUMN_NAME_LONGITUDE));
+			bssidValues.put(NetworkEntry.COLUMN_NAME_ACCURACY, (float) (Float) networkInformation.get(NetworkEntry.COLUMN_NAME_ACCURACY));
+			bssidValues.put(NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP, (Long) networkInformation.get(NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP));
+			db.insertWithOnConflict(NetworkEntry.TABLE_NAME, null, bssidValues, SQLiteDatabase.CONFLICT_REPLACE);
+		}
+		cursor.close();
+		db.close();
+	}
+
+	/**
+	 * 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(TYPE.valueOf(cursor.getString(2)));
+		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.setLocalPort(Integer.parseInt(cursor.getString(8)));
+
+		record.setRemoteIP(cursor.getString(9));
+		record.setRemotePort(Integer.parseInt(cursor.getString(10)));
+
+		record.setBssid(cursor.getString(11));
+		record.setSsid(cursor.getString(12));
+		record.setLatitude(Double.parseDouble(cursor.getString(13)));
+		record.setLongitude(Double.parseDouble(cursor.getString(14)));
+		record.setAccuracy(Float.parseFloat(cursor.getString(15)));
+		record.setTimestampLocation(cursor.getLong(16));
+
+		return record;
+	}
+
+}

+ 11 - 14
src/de/tudarmstadt/informatik/hostage/protocol/FTP.java

@@ -27,11 +27,8 @@ public class FTP implements Protocol {
 
 	// commands
 	private static final String REPLY_CODE_220 = "220 Service ready for new user.";
-
 	private static final String REPLY_CODE_221 = "221 Service closing control connection.";
-
 	private static final String REPLY_CODE_230 = "230 User logged in.";
-
 	private static final String REPLY_CODE_331 = "331 User name ok, need password.";
 	private static final String REPLY_CODE_332 = "332 Need account for login.";
 	private static final String REPLY_CODE_421 = "421 Service not available, closing control connection.";
@@ -64,10 +61,10 @@ public class FTP implements Protocol {
 		case NONE:
 			if (request == null) {
 				state = STATE.OPEN;
-				responsePackets.add(new Packet(REPLY_CODE_220));
+				responsePackets.add(new Packet(REPLY_CODE_220 + "\r\n", toString()));
 			} else {
 				state = STATE.CLOSED;
-				responsePackets.add(new Packet(REPLY_CODE_421));
+				responsePackets.add(new Packet(REPLY_CODE_421 + "\r\n", toString()));
 			}
 			break;
 		case OPEN:
@@ -75,37 +72,37 @@ public class FTP implements Protocol {
 				state = STATE.CLOSED;
 				return null;
 			} else if (request.equals("USER \r\n")) {
-				responsePackets.add(new Packet(REPLY_CODE_501));
+				responsePackets.add(new Packet(REPLY_CODE_501 + "\r\n", toString()));
 			} else if (request.contains("USER")) {
 				state = STATE.USER;
-				responsePackets.add(new Packet(REPLY_CODE_331));
+				responsePackets.add(new Packet(REPLY_CODE_331 + "\r\n", toString()));
 			} else {
-				responsePackets.add(new Packet(REPLY_CODE_332));
+				responsePackets.add(new Packet(REPLY_CODE_332 + "\r\n", toString()));
 			}
 			break;
 		case USER:
 			if (request.equals("PASS \r\n")) {
 				state = STATE.OPEN;
-				responsePackets.add(new Packet(REPLY_CODE_501));
+				responsePackets.add(new Packet(REPLY_CODE_501 + "\r\n", toString()));
 			} else if (request.contains("PASS")) {
 				state = STATE.LOGGED_IN;
-				responsePackets.add(new Packet(REPLY_CODE_230));
+				responsePackets.add(new Packet(REPLY_CODE_230 + "\r\n", toString()));
 			} else {
 				state = STATE.CLOSED;
-				responsePackets.add(new Packet(REPLY_CODE_221));
+				responsePackets.add(new Packet(REPLY_CODE_221 + "\r\n", toString()));
 			}
 			break;
 		case LOGGED_IN:
 			if (request != null && !request.contains("QUIT")) {
-				responsePackets.add(new Packet(REPLY_CODE_500));
+				responsePackets.add(new Packet(REPLY_CODE_500 + "\r\n", toString()));
 			} else {
 				state = STATE.CLOSED;
-				responsePackets.add(new Packet(REPLY_CODE_221));
+				responsePackets.add(new Packet(REPLY_CODE_221 + "\r\n", toString()));
 			}
 			break;
 		default:
 			state = STATE.CLOSED;
-			responsePackets.add(new Packet(REPLY_CODE_421));
+			responsePackets.add(new Packet(REPLY_CODE_421 + "\r\n", toString()));
 		}
 		return responsePackets;
 	}

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/protocol/GHOST.java

@@ -43,7 +43,7 @@ public class GHOST implements Protocol {
 
 	@Override
 	public int getPort() {
-		return 5050; // TODO whats the default!? (1433)
+		return 1433;
 	}
 
 	@Override
@@ -84,7 +84,7 @@ public class GHOST implements Protocol {
 			}
 			byte[] mirrorResponse = new byte[availableBytes];
 			mirrorInputStream.read(mirrorResponse);
-			responsePackets.add(new Packet(mirrorResponse));
+			responsePackets.add(new Packet(mirrorResponse, toString()));
 		} catch (IOException e) {
 			e.printStackTrace();
 			responsePackets.add(requestPacket);

+ 36 - 12
src/de/tudarmstadt/informatik/hostage/protocol/HTTP.java

@@ -8,6 +8,9 @@ import java.util.List;
 import java.util.Locale;
 import java.util.TimeZone;
 
+import android.content.Context;
+import de.tudarmstadt.informatik.hostage.Hostage;
+import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
 import de.tudarmstadt.informatik.hostage.wrapper.Packet;
 
@@ -25,7 +28,7 @@ public class HTTP implements Protocol {
 	 * 
 	 * @return the formatted server time.
 	 */
-	private static String getServerTime() {
+	private String getServerTime() {
 		Calendar calendar = Calendar.getInstance();
 		SimpleDateFormat dateFormat = new SimpleDateFormat(
 				"EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
@@ -37,7 +40,7 @@ public class HTTP implements Protocol {
 	private String request = "";
 
 	// version stuff
-	private static String[][][] possibleHttpVersions = {
+	private String[][][] possibleHttpVersions = {
 			{
 					{ "Apache/2.0." },
 					{ "28", "32", "35", "36", "39", "40", "42", "43", "44",
@@ -51,22 +54,40 @@ public class HTTP implements Protocol {
 							"21", "22", "23", "24", "25" } },
 			{ { "Apache/2.3." },
 					{ "4", "5", "6", "8", "10", "11", "12", "14", "15", "16" } },
-			{ { "Apache/2.4." }, { "1", "2", "3", "4", "6" } } };
+			{ { "Apache/2.4." }, { "1", "2", "3", "4", "6" } },
+			{ { "Microsoft-IIS/" }, { "5.1", "7.0", "8.0" } } };
 
-	private static String serverVersion = initServerVersion();
+	private String serverVersion = initServerVersion();
 
-	private static String initServerVersion() {
+	private String initServerVersion() {
 		SecureRandom rndm = new SecureRandom();
 		int majorVersion = rndm.nextInt(possibleHttpVersions.length);
-		return possibleHttpVersions[majorVersion][0][0]
-				+ possibleHttpVersions[majorVersion][1][rndm
-						.nextInt(possibleHttpVersions[majorVersion][1].length)];
+		
+		String version;
+		String sharedPreferencePath = Hostage.getContext().getString(
+				R.string.shared_preference_path);
+		String profile = Hostage
+				.getContext()
+				.getSharedPreferences(sharedPreferencePath,
+						Context.MODE_PRIVATE).getString("os", "");
+		if (profile.equals("Windows 7") || profile.equals("Windows Server 2008")) {
+			version = "Microsoft-IIS/7.5";
+		} else if (profile.equals("Windows Server 2012") || profile.equals("Windows 8")) {
+			version = "Microsoft-IIS/8.0";
+		} else if (profile.equals("Windows XP")) {
+			version = "Microsoft-IIS/5.1";
+		} else {
+			version = possibleHttpVersions[majorVersion][0][0]
+					+ possibleHttpVersions[majorVersion][1][rndm
+					          .nextInt(possibleHttpVersions[majorVersion][1].length)];
+		}
+		
+		return version;
 	}
 
 	private String httpVersion = "HTTP/1.1";
 
-	private static String htmlDocumentContent = HelperUtils.getRandomString(32,
-			false);
+	private static String htmlDocumentContent = HelperUtils.getRandomString(32, false);
 
 	// request codes
 	private static final String OPTIONS = "OPTIONS";
@@ -136,7 +157,10 @@ public class HTTP implements Protocol {
 		List<Packet> responsePackets = new ArrayList<Packet>();
 		this.request = request;
 
-		if (!request.contains(httpVersion)) {
+		if (request.startsWith("G")) {
+			//weird if clause but required for https
+			responsePackets.add(buildPacket(STATUS_CODE_200, GET));
+		} else if (!request.contains(httpVersion)) {
 			responsePackets.add(buildPacket(STATUS_CODE_505, ""));
 		} else if (request.contains(GET)) {
 			responsePackets.add(buildPacket(STATUS_CODE_200, GET));
@@ -192,6 +216,6 @@ public class HTTP implements Protocol {
 		}
 
 		return new Packet(httpVersion + " " + code + headerPrefix
-				+ document.length() + headerSuffix + document);
+				+ document.length() + headerSuffix + document, toString());
 	}
 }

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/protocol/HTTPS.java

@@ -5,7 +5,7 @@ import java.security.KeyStore;
 import javax.net.ssl.KeyManagerFactory;
 import javax.net.ssl.SSLContext;
 
-import de.tudarmstadt.informatik.hostage.HoneyService;
+import de.tudarmstadt.informatik.hostage.Hostage;
 
 /**
  * HTTPS protocol. Extends HTTP. Implementation of RFC document 2818. It can handle the
@@ -30,7 +30,7 @@ public class HTTPS extends HTTP implements SSLProtocol {
 		try {
 			keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
 			keyStore.load(
-					HoneyService.getContext().getAssets().open(keyStoreName),
+					Hostage.getContext().getAssets().open(keyStoreName),
 					keyStorePassword);
 			keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory
 					.getDefaultAlgorithm());

+ 4 - 4
src/de/tudarmstadt/informatik/hostage/protocol/MySQL.java

@@ -30,7 +30,7 @@ public class MySQL implements Protocol {
 	private byte[] lastReceivedMessage;
 
 	// version stuff
-	private static String[][][] possibleMysqlVersions = {
+	private String[][][] possibleMysqlVersions = {
 			{ { "5.7." }, { "1", "2" } },
 			{
 					{ "5.6." },
@@ -38,9 +38,9 @@ public class MySQL implements Protocol {
 							"13", "14" } },
 			{ { "5.5." }, { "27", "28", "29", "30", "31", "32", "33", "34" } } };
 
-	private static String serverVersion = initMysqlVersion();
+	private String serverVersion = initMysqlVersion();
 
-	private static String initMysqlVersion() {
+	private String initMysqlVersion() {
 		SecureRandom rndm = new SecureRandom();
 		int majorVersion = rndm.nextInt(possibleMysqlVersions.length);
 		return possibleMysqlVersions[majorVersion][0][0]
@@ -183,6 +183,6 @@ public class MySQL implements Protocol {
 
 		byte[] wrappedResponse = HelperUtils.concat(packetLength, packetNumber,
 				response);
-		return new Packet(wrappedResponse);
+		return new Packet(wrappedResponse, toString());
 	}
 }

+ 124 - 5
src/de/tudarmstadt/informatik/hostage/protocol/SIP.java

@@ -1,10 +1,35 @@
 package de.tudarmstadt.informatik.hostage.protocol;
 
+import java.util.ArrayList;
 import java.util.List;
 
 import de.tudarmstadt.informatik.hostage.wrapper.Packet;
 
+/**
+ * SIP protocol. Implementation of RFC document 3261 It can handle the
+ * following requests: REGISTER, INVITE, ACK, BYE. For all other requests
+ * '400 Bad Request' will be replied.
+ * @author Wulf Pfeiffer
+ */
 public class SIP implements Protocol {
+	
+	private enum STATE {
+		NONE, CLOSED
+	}
+	
+	private STATE state = STATE.NONE;
+		
+	private static final String VERSION = "SIP/2.0";
+	private static final String REGISTER = "REGISTER";
+	private static final String INVITE = "INVITE";
+	private static final String ACK= "ACK";
+	private static final String BYE = "BYE";
+	private static final String STATUS_CODE_200 = "200 OK";
+	private static final String STATUS_CODE_400 = "400 Bad Request";
+	private static final String STATUS_CODE_505 = "505 Version Not Supported";
+	
+	private String header;
+	private String sdpPayload;
 
 	@Override
 	public int getPort() {
@@ -13,8 +38,7 @@ public class SIP implements Protocol {
 
 	@Override
 	public boolean isClosed() {
-		// TODO Auto-generated method stub
-		return true;
+		return (state == STATE.CLOSED);
 	}
 
 	@Override
@@ -23,14 +47,109 @@ public class SIP implements Protocol {
 	}
 
 	@Override
-	public List<Packet> processMessage(Packet packet) {
-		// TODO Auto-generated method stub
-		return null;
+	public List<Packet> processMessage(Packet requestPacket) {
+		String request = null;
+		if (requestPacket != null) {
+			request = requestPacket.toString();
+		}
+		List<Packet> responsePackets = new ArrayList<Packet>();
+		String[] lines = request.split("\r\n");
+		extractLines(lines);
+		
+		if(!lines[0].contains(VERSION)) {
+			responsePackets.add(getVersionNotSupportedResponse());
+			return responsePackets;
+		} else if(lines[0].contains(REGISTER)) {
+			responsePackets.add(getOkResponse());
+		} else if(lines[0].contains(INVITE)) {
+			responsePackets.add(getOkResponseWithSDP());
+		} else if(lines[0].contains(BYE)) {
+			responsePackets.add(getOkResponse());
+			state = STATE.CLOSED;
+		} else if(lines[0].contains(ACK)) {
+			//nothing to do here
+		} else {
+			responsePackets.add(getBadRequestResponse());
+		}
+		
+		return responsePackets;
 	}
 
 	@Override
 	public TALK_FIRST whoTalksFirst() {
 		return TALK_FIRST.CLIENT;
 	}
+	
+	@Override
+	public String toString() {
+		return "SIP";
+	}
+	
+	private void extractLines(String[] lines) {
+		header = "";
+		sdpPayload = "";
+		StringBuffer sbHeader = new StringBuffer();
+		StringBuffer sbSdp = new StringBuffer();
+		boolean recordHeader = false;
+		boolean recordSdp = false;
+		for (String line : lines) {
+			if (line.startsWith("Via:")) {
+				recordHeader = true;
+			} else if (line.startsWith("Max-Forwards")) {
+				recordHeader = false;
+				header = sbHeader.toString();
+			} else if(line.startsWith("v=")) {
+				recordSdp = true;
+			} else if(line.startsWith("a=")) {
+				sbSdp.append(line + "\r\n");
+				sdpPayload = sbSdp.toString();
+				break;
+			}
+			if(recordHeader) {
+				sbHeader.append(line + "\r\n");
+			} else if(recordSdp) {
+				sbSdp.append(line + "\r\n");
+			}
+		}
+	}
+	
+	private Packet getOkResponseWithSDP() {
+		StringBuffer sb = new StringBuffer();
+		sb.append(VERSION + " " + STATUS_CODE_200 + "\r\n");
+		sb.append(header);
+		sb.append("Content-Type: application/sdp\r\n");
+		sb.append("Content-Length:   " + sdpPayload.length() + "\r\n");
+		sb.append("\r\n");
+		sb.append(sdpPayload);
+
+		return new Packet(sb.toString(), toString());
+	}
+	
+	private Packet getOkResponse() {
+		StringBuffer sb = new StringBuffer();
+		sb.append(VERSION + " " + STATUS_CODE_200 + "\r\n");
+		sb.append(header);
+		sb.append("Content-Length:   0\r\n");
+		
+		return new Packet(sb.toString(), toString());
+	}
+	
+	private Packet getBadRequestResponse() {
+		StringBuffer sb = new StringBuffer();
+		sb.append(VERSION + " " + STATUS_CODE_400 + "\r\n");
+		sb.append(header);
+		sb.append("Content-Length:   0\r\n");
+		
+		return new Packet(sb.toString(), toString());
+	}
+	
+	private Packet getVersionNotSupportedResponse() {
+		StringBuffer sb = new StringBuffer();
+		sb.append(VERSION + " " + STATUS_CODE_505 + "\r\n");
+		sb.append(header);
+		sb.append("Content-Length:   0\r\n");
+		
+		return new Packet(sb.toString(), toString());
+	}
 
 }

+ 60 - 721
src/de/tudarmstadt/informatik/hostage/protocol/SMB.java

@@ -1,17 +1,14 @@
 package de.tudarmstadt.informatik.hostage.protocol;
 
-import java.nio.ByteBuffer;
 import java.security.SecureRandom;
 import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.GregorianCalendar;
 import java.util.List;
-import java.util.TimeZone;
 
-import android.content.Context;
-import de.tudarmstadt.informatik.hostage.HoneyService;
+import de.tudarmstadt.informatik.hostage.Hostage;
 import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
+import de.tudarmstadt.informatik.hostage.protocol.SMBUtils.NBNS;
+import de.tudarmstadt.informatik.hostage.protocol.SMBUtils.NMB;
+import de.tudarmstadt.informatik.hostage.protocol.SMBUtils.SMBPacket;
 import de.tudarmstadt.informatik.hostage.wrapper.Packet;
 
 /**
@@ -23,88 +20,53 @@ import de.tudarmstadt.informatik.hostage.wrapper.Packet;
  * @author Wulf Pfeiffer
  */
 public class SMB implements Protocol {
+	// message constants
+	private static final byte SMB_COM_CLOSE = 0x04;
+	private static final byte SMB_COM_TRANSACTION = 0x25;
+	private static final byte SMB_COM_ECHO = 0x2B;
+	private static final byte SMB_COM_TRANSACTION2 = 0x32;
+	private static final byte SMB_COM_TREE_DISCONNECT = 0x71;
+	private static final byte SMB_COM_NEGOTIATE = 0x72;
+	private static final byte SMB_COM_SESSION_SETUP_ANDX = 0x73;
+	private static final byte SMB_COM_TREE_CONNECT_ANDX = 0x75;
+	private static final byte SMB_COM_NT_CREATE_ANDX = (byte) 0xA2;
+	
 	/**
-	 * Represents the states of the protocol
+	 * Denotes in which state the protocol is right now
 	 */
-	private static enum STATE {
-		NONE, CONNECTED, AUTHENTICATED, LISTING, DISCONNECTED, CLOSED
-	}
+	private STATE state = STATE.NONE;
+	private byte[] lastMessage;
 
 	// version stuff
-	private static String[][] possibleSmbVersions = {
+	private String[][] possibleSmbVersions = {
 			{ "Windows 7 Professional 7600", "Windows 7 Professional 6.1" },
 			{ "Windows 8 Enterprise 9200", "Windows 8 Enterprise 9200" },
 			{ "Windows Server 2008 R2 Enterprise 7600", "Windows Server 2008 R2 Enterprise 6.1" },
 			{ "Windows Server 2012 Standard 6.2", "Windows Server 2012 Standard 6.2" },
 			{ "Unix", "Samba" },
-			{ "Windows 2002 Service Pack 2", "Windows 2002 5.1"}
+			{ "Windows 2002 Service Pack 2", "Windows 2002 5.1" }
 	};
-
+	
 	/**
-	 * Converts the current system time into a byte[] with windows specific time
-	 * 
-	 * @return current system time in windows format as byte[]
+	 * Represents the states of the protocol
 	 */
-	private static byte[] getTimeInBytes() {
-		long time = System.currentTimeMillis();
-		Calendar calend = Calendar.getInstance();
-		calend.setTimeZone(TimeZone.getTimeZone("UTC"));
-		calend.set(1601, 0, 01, 00, 00, 00);
-		time -= calend.getTimeInMillis();
-		time *= 10000;
-
-		byte[] timeInWindowsBytes = new byte[8];
-		byte[] timeInBytes = ByteBuffer.allocate(8).putLong(time).array();
-
-		for (int i = 0, j = 7; i < 8 && j > -1; i++, j--) {
-			timeInWindowsBytes[i] = (byte) (timeInBytes[j] & 0xff);
-		}
-
-		return timeInWindowsBytes;
+	private static enum STATE {
+		NONE, CONNECTED, AUTHENTICATED, LISTING, DISCONNECTED, CLOSED
 	}
-
-	/**
-	 * Converts the current timezone into a byte[] with windows specific format
-	 * 
-	 * @return current timezone in windows format as byte[]
-	 */
-	private static byte[] getTimeZoneInBytes() {
-		Integer offset = new GregorianCalendar().getTimeZone().getRawOffset() / 1000 / 60; // get
-																							// current
-																							// timezone
-																							// offset
-																							// in
-																							// minutes
-		char[] offsetChars = Integer.toBinaryString(offset).toCharArray();
-		boolean invert = false;
-		for (int i = offsetChars.length - 1; i > -1; i--) {
-			if (!invert && offsetChars[i] == '1') {
-				invert = true;
-			} else if (invert) {
-				offsetChars[i] = (offsetChars[i] == '0') ? '1' : '0';
-			}
-		}
-		char[] extendedChars = new char[31];
-		for (int i = 0; i < extendedChars.length - offsetChars.length; i++) {
-			extendedChars[i] = '1';
-		}
-		for (int i = 0; i < offsetChars.length; i++) {
-			extendedChars[i + extendedChars.length - offsetChars.length] = offsetChars[i];
-		}
-		int timezone = Integer.parseInt(new String(extendedChars), 2);
-		byte[] timezoneBytes = new byte[2];
-		timezoneBytes[1] = (byte) (timezone >> 8);
-		timezoneBytes[0] = (byte) (timezone);
-		return timezoneBytes;
+	
+	public void setIP(String ip) {
+//		new NMB(ip).start();
 	}
 
-	private static String[] initServerVersion() {
-		String sharedPreferencePath = HoneyService.getContext().getString(
+	private String[] initServerVersion() {
+		System.out.println("hi");
+		String sharedPreferencePath = Hostage.getContext().getString(
 				R.string.shared_preference_path);
-		String profile = HoneyService
+		System.out.println(sharedPreferencePath);
+		String profile = Hostage
 				.getContext()
 				.getSharedPreferences(sharedPreferencePath,
-						Context.MODE_PRIVATE).getString("profile", "");
+						Hostage.MODE_PRIVATE).getString("os", "");
 		System.out.println(profile);
 		if (profile.equals("Windows 7")) {
 			return possibleSmbVersions[0];
@@ -119,57 +81,13 @@ public class SMB implements Protocol {
 		} else if (profile.equals("Windows XP")) {
 			return possibleSmbVersions[5];
 		} else {
-			return possibleSmbVersions[new SecureRandom()
-					.nextInt(possibleSmbVersions.length)];
+			return possibleSmbVersions[new SecureRandom().nextInt(possibleSmbVersions.length)];
 		}
 	}
-
-	/**
-	 * Denotes in which state the protocol is right now
-	 */
-	private STATE state = STATE.NONE;
-
-	private byte[] lastMessage;
-
-	private static byte[] serverName = HelperUtils.fillWithZero(HelperUtils
-			.getRandomString(16, true).getBytes());
-
-	private static String[] serverVersion = initServerVersion();
-
-	private byte[] message = null;
-
-	private static final byte[] serverGUID = HelperUtils.randomBytes(16);
-
-	private boolean authenticateNext = false;
-
-	// components of a SMB packet
-	private byte[] serverComp = new byte[4];
-
-	private byte[] smbCommand = new byte[1];
-	private byte[] ntStat = new byte[4];
-
-	private byte[] smbFlags = new byte[1];
-	private byte[] smbFlags2 = new byte[2];
-	private byte[] processIDHigh = new byte[2];
-	private byte[] signature = new byte[8];
-	private byte[] reserved = new byte[2];
-	private byte[] treeID = new byte[2];
-	private byte[] processID = new byte[2];
-	private byte[] userID = new byte[2];
-	private byte[] multiplexID = new byte[2];
-	// message constants
-	private static final byte SMB_COM_CLOSE = 0x04;
-	private static final byte SMB_COM_TRANSACTION = 0x25;
-	private static final byte SMB_COM_ECHO = 0x2B;
-	private static final byte SMB_COM_TRANSACTION2 = 0x32;
-	private static final byte SMB_COM_TREE_DISCONNECT = 0x71;
-	private static final byte SMB_COM_NEGOTIATE = 0x72;
-
-	private static final byte SMB_COM_SESSION_SETUP_ANDX = 0x73;
-
-	private static final byte SMB_COM_TREE_CONNECT_ANDX = 0x75;
-
-	private static final byte SMB_COM_NT_CREATE_ANDX = (byte) 0xA2;
+	
+	//required to be declared down here, do not change position over initServerVersion() and possibleServerVersions!!
+	private String[] serverVersion = initServerVersion();
+	private SMBPacket smbPacket = new SMBPacket(serverVersion);
 
 	@Override
 	public int getPort() {
@@ -190,73 +108,75 @@ public class SMB implements Protocol {
 	public List<Packet> processMessage(Packet requestPacket) {
 		if (requestPacket != null)
 			lastMessage = requestPacket.getBytes();
-		parseMessageHeader(lastMessage);
-		byte smbCommand = getSmbCommand();
+		smbPacket.prepareNextResponse(lastMessage);
+		byte smbCommand = smbPacket.getSmbCommand();
+		byte[] response;
 		List<Packet> responsePackets = new ArrayList<Packet>();
 
 		switch (state) {
 		case NONE:
 			if (smbCommand == SMB_COM_NEGOTIATE) {
 				state = STATE.CONNECTED;
-				responsePackets.add(getNego());
+				response = smbPacket.getNego();
 			} else {
 				state = STATE.DISCONNECTED;
-				responsePackets.add(getTreeDisc());
+				response = smbPacket.getTreeDisc();
 			}
 			break;
 		case CONNECTED:
 			if (smbCommand == SMB_COM_SESSION_SETUP_ANDX) {
-				responsePackets.add(getSessSetup());
+				response = smbPacket.getSessSetup();
 			} else if (smbCommand == SMB_COM_TREE_CONNECT_ANDX) {
 				state = STATE.AUTHENTICATED;
-				responsePackets.add(getTreeCon());
+				response = smbPacket.getTreeCon();
 			} else {
 				state = STATE.DISCONNECTED;
-				responsePackets.add(getTreeDisc());
+				response = smbPacket.getTreeDisc();
 			}
 			break;
 		case AUTHENTICATED:
 			if (smbCommand == SMB_COM_NT_CREATE_ANDX) {
 				state = STATE.LISTING;
-				responsePackets.add(getNTCreate());
+				response = smbPacket.getNTCreate();
 			} else if (smbCommand == SMB_COM_ECHO) {
-				responsePackets.add(getEcho());
+				response = smbPacket.getEcho();
 			} else if (smbCommand == SMB_COM_TRANSACTION2) {
-				responsePackets.add(getTrans2());
+				response = smbPacket.getTrans2();
 			} else if (smbCommand == SMB_COM_CLOSE) {
-				responsePackets.add(getClose());
+				response = smbPacket.getClose();
 			} else if (smbCommand == SMB_COM_TREE_DISCONNECT) {
 				state = STATE.CLOSED;
-				responsePackets.add(getTreeDisc());
+				response = smbPacket.getTreeDisc();
 			} else {
 				state = STATE.DISCONNECTED;
-				responsePackets.add(getTreeDisc());
+				response = smbPacket.getTreeDisc();
 			}
 			break;
 		case LISTING:
 			if (smbCommand == SMB_COM_TRANSACTION) {
-				responsePackets.add(getTrans());
+				response = smbPacket.getTrans();
 			} else if (smbCommand == SMB_COM_CLOSE) {
-				responsePackets.add(getClose());
+				response = smbPacket.getClose();
 			} else if (smbCommand == SMB_COM_TREE_DISCONNECT) {
 				state = STATE.CLOSED;
-				responsePackets.add(getTreeDisc());
+				response = smbPacket.getTreeDisc();
 			} else if (smbCommand == SMB_COM_NEGOTIATE) {
 				state = STATE.CONNECTED;
-				responsePackets.add(getNego());
+				response = smbPacket.getNego();
 			} else {
 				state = STATE.DISCONNECTED;
-				responsePackets.add(getTreeDisc());
+				response = smbPacket.getTreeDisc();
 			}
 			break;
 		case DISCONNECTED:
 			state = STATE.CLOSED;
-			responsePackets.add(getTreeDisc());
+			response = smbPacket.getTreeDisc();
 			break;
 		default:
 			state = STATE.CLOSED;
-			responsePackets.add(getTreeDisc());
+			response = smbPacket.getTreeDisc();
 		}
+		responsePackets.add(new Packet(response, toString()));
 		return responsePackets;
 	}
 
@@ -269,585 +189,4 @@ public class SMB implements Protocol {
 	public TALK_FIRST whoTalksFirst() {
 		return TALK_FIRST.CLIENT;
 	}
-
-	/**
-	 * Evaluates what Dialects are offered by the client and which position the
-	 * used NT LM 0.12 dialect is at
-	 * 
-	 * @return position of the NT LM 0.12 dialect
-	 */
-	private byte[] evaluateDialect() {
-		byte[] dialectMsg = new byte[message.length - 39];
-		System.arraycopy(message, 39, dialectMsg, 0, message.length - 39);
-		short dialectNumber = 0;
-		for (int i = 0, start = 0; i < dialectMsg.length; i++) {
-			if (dialectMsg[i] == 0x00) {
-				byte[] dialect = new byte[i - start];
-				System.arraycopy(dialectMsg, start, dialect, 0, i - start);
-				if (HelperUtils.byteToStr(dialect).contains("NT LM 0.12")) {
-					return new byte[] { (byte) dialectNumber,
-							(byte) (dialectNumber >> 8) };
-				}
-				start = i + 1;
-				dialectNumber++;
-			}
-		}
-		return new byte[] { 0x00, 0x00 };
-	}
-
-	/**
-	 * Builds the close packet
-	 * 
-	 * @return close packet
-	 */
-	private Packet getClose() {
-		byte[] wordCount = { 0x00 };
-		byte[] byteCount = { 0x00, 0x00 };
-
-		smbCommand = new byte[] { 0x04 };
-
-		byte[] response = HelperUtils.concat(wordCount, byteCount);
-
-		return new Packet(wrapNetbios(wrapHeader(response)));
-	}
-
-	/**
-	 * Builds the DCERPC packet
-	 * 
-	 * @return DCERPC packet
-	 */
-	private byte[] getDceRpc(byte[] transSub, int length) {
-		byte[] majorVersion = { 0x05 };
-		byte[] minorVersion = { 0x00 };
-		byte[] packetType = null;
-		byte[] packetFlags = { 0x03 };
-		byte[] dataRepres = { 0x10, 0x00, 0x00, 0x00 };
-		byte[] fragLength = null;
-		byte[] authLength = { 0x00, 0x00 };
-		byte[] callID = null;
-		byte[] response = null;
-
-		if (transSub[0] == 0x00 && transSub[1] == 0x0b) {
-			packetType = new byte[] { 0x0c };
-			fragLength = new byte[] { 0x44, 0x00 };
-			callID = new byte[] { 0x01, 0x00, 0x00, 0x00 };
-			byte[] maxXmitFrag = { (byte) 0xb8, 0x10 };
-			byte[] maxRecvFrag = { (byte) 0xb8, 0x10 };
-			byte[] assocGroup = { 0x4a, 0x41, 0x00, 0x00 };
-			byte[] scndryAddrLen = { 0x0d, 0x00 };
-			byte[] scndryAddr = { 0x5c, 0x50, 0x49, 0x50, 0x45, 0x5c, 0x73,
-					0x72, 0x76, 0x73, 0x76, 0x63, 0x00, 0x00 };
-			byte[] numResults = { 0x01, 0x00, 0x00, 0x00 };
-			byte[] ctxItem = { 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, (byte) 0x88,
-					(byte) 0x8a, (byte) 0xeb, 0x1c, (byte) 0xc9, 0x11,
-					(byte) 0x9f, (byte) 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48,
-					0x60, 0x02, 0x00, 0x00, 0x00 };
-
-			response = HelperUtils.concat(majorVersion, minorVersion,
-					packetType, packetFlags, dataRepres, fragLength,
-					authLength, callID, maxXmitFrag, maxRecvFrag, assocGroup,
-					scndryAddrLen, scndryAddr, numResults, ctxItem);
-		} else if (transSub[0] == 0x00 && transSub[1] == 0x00) {
-			packetType = new byte[] { 0x02 };
-			byte[] tmp = ByteBuffer.allocate(4).putInt(length).array();
-			fragLength = new byte[] { tmp[3], tmp[2] };
-			callID = new byte[] { 0x02, 0x00, 0x00, 0x00 };
-			tmp = ByteBuffer.allocate(4).putInt(length - 24).array();
-			byte[] allocHint = new byte[] { tmp[3], tmp[2], tmp[1], tmp[0] };
-			byte[] contextID = { 0x00, 0x00 };
-			byte[] cancelCount = { 0x00, 0x00 };
-
-			response = HelperUtils.concat(majorVersion, minorVersion,
-					packetType, packetFlags, dataRepres, fragLength,
-					authLength, callID, allocHint, contextID, cancelCount);
-		}
-		return response;
-	}
-
-	/**
-	 * Builds the echo packet
-	 * 
-	 * @return echo packet
-	 */
-	private Packet getEcho() {
-		byte[] wordCount = { 0x01 };
-		byte[] echoSeq = { 0x01, 0x00 };
-		byte[] byteCount = { 0x10, 0x00 };
-		byte[] echoData = { (byte) 0xf0, (byte) 0xf0, (byte) 0xf0, (byte) 0xf0,
-				(byte) 0xf0, (byte) 0xf0, (byte) 0xf0, (byte) 0xf0,
-				(byte) 0xf0, (byte) 0xf0, (byte) 0xf0, (byte) 0xf0,
-				(byte) 0xf0, (byte) 0xf0, (byte) 0xf0, (byte) 0xf0 };
-		byte[] response = HelperUtils.concat(wordCount, echoSeq, byteCount,
-				echoData);
-		return new Packet(wrapNetbios(wrapHeader(response)));
-	}
-
-	/**
-	 * Builds the negotiate packet
-	 * 
-	 * @return negotiate packet
-	 */
-	private Packet getNego() {
-		byte[] wordCount = { 0x11 };
-		byte[] dialect = evaluateDialect();
-		byte[] secMode = { 0x03 };
-		byte[] maxMpxC = { 0x32, 0x00 };
-		byte[] maxVcs = { 0x01, 0x00 };
-		byte[] maxBufSize = { 0x04, 0x11, 0x00, 0x00 };
-		byte[] maxRawBuf = { 0x00, 0x00, 0x01, 0x00 };
-		byte[] sessionKey = { 0x00, 0x00, 0x00, 0x00 };
-		byte[] capabilities = { (byte) 0xfc, (byte) 0xe3, 0x01, (byte) 0x80 };
-		byte[] sysTime = getTimeInBytes();
-		byte[] timeZone = getTimeZoneInBytes();
-		byte[] keyLength = { 0x00 };
-		byte[] byteCount = { 0x3a, 0x00 };
-		byte[] guid = serverGUID;
-		byte[] secBlob = { 0x60, 0x28, 0x06, 0x06 };
-		byte[] oid = { 0x2b, 0x06, 0x01, 0x05, 0x05, 0x02 };
-		byte[] protectNeg = { (byte) 0xa0, 0x1e };
-		byte[] negToken = { 0x30, 0x1c, (byte) 0xa0, 0x1a, 0x30, 0x18 };
-		byte[] mechType = { 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01,
-				(byte) 0x82, 0x37, 0x02, 0x02, 0x1e };
-		byte[] mechType2 = { 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01,
-				(byte) 0x82, 0x37, 0x02, 0x02, 0x0a };
-
-		byte[] response = HelperUtils.concat(wordCount, dialect, secMode,
-				maxMpxC, maxVcs, maxBufSize, maxRawBuf, sessionKey,
-				capabilities, sysTime, timeZone, keyLength, byteCount, guid,
-				secBlob, oid, protectNeg, negToken, mechType, mechType2);
-		return new Packet(wrapNetbios(wrapHeader(response)));
-	}
-
-	/**
-	 * Builds the nt create packet
-	 * 
-	 * @return nt create packet
-	 */
-	private Packet getNTCreate() {
-		byte[] wordCount = { 0x22 };
-		byte[] andXCommand = { (byte) 0xff };
-		byte[] reserved = { 0x00 };
-		byte[] andXOffset = { 0x67, 0x00 };
-		byte[] oplockLevel = { 0x00 };
-		byte[] fid = { (byte) 0x00, 0x40 };
-		byte[] createAction = { 0x01, 0x00, 0x00, 0x00 };
-		byte[] created = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
-		byte[] lastAccess = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
-		byte[] lastWrite = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
-		byte[] change = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
-		byte[] fileAttributes = { (byte) 0x80, 0x00, 0x00, 0x00 };
-		byte[] allocationSize = { 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
-				0x00 };
-		byte[] endOfFile = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
-		byte[] fileType = { 0x02, 0x00 };
-		byte[] ipcState = { (byte) 0xff, 0x05 };
-		byte[] isDirectory = { 0x00 };
-		byte[] byteCount = { 0x00, 0x00 };
-
-		byte[] response = HelperUtils.concat(wordCount, andXCommand, reserved,
-				andXOffset, oplockLevel, fid, createAction, created,
-				lastAccess, lastWrite, change, fileAttributes, allocationSize,
-				endOfFile, fileType, ipcState, isDirectory, byteCount);
-		return new Packet(wrapNetbios(wrapHeader(response)));
-	}
-
-	/**
-	 * Builds the session setup packet
-	 * 
-	 * @ret urn session setup packet
-	 */
-	private Packet getSessSetup() {
-		if (authenticateNext) {
-			return new Packet(getSetupAuth());
-		} else {
-			authenticateNext = true;
-			return new Packet(getSetupChal());
-		}
-	}
-
-	/**
-	 * Builds the session setup packet for authentication required
-	 * 
-	 * @return session setup authentication packet
-	 */
-	private byte[] getSetupAuth() {
-		byte[] wordCount = { 0x04 };
-		byte[] andXCommand = { (byte) 0xff };
-		byte[] reserved = { 0x00 };
-		byte[] andXOffset = { (byte) 0xa2, 0x00 };
-		byte[] action = { 0x01, 0x00 };
-		byte[] secBlobLength;
-		byte[] byteCount;
-		byte[] secBlob = { (byte) 0xa1, 0x07, 0x30, 0x05, (byte) 0xa0, 0x03,
-				0x0a, 0x01, 0x00 };
-		byte[] nativOS = HelperUtils.fillWithZeroExtended(serverVersion[0]
-				.getBytes());
-		byte[] nativLanMngr = HelperUtils.fillWithZeroExtended(serverVersion[1]
-				.getBytes());
-
-		byte[] buffer = ByteBuffer.allocate(4).putInt(secBlob.length).array();
-		secBlobLength = new byte[] { buffer[3], buffer[2] };
-		buffer = ByteBuffer.allocate(4)
-				.putInt(secBlob.length + nativOS.length + nativLanMngr.length)
-				.array();
-		byteCount = new byte[] { buffer[3], buffer[2] };
-
-		byte[] response = HelperUtils.concat(wordCount, andXCommand, reserved,
-				andXOffset, action, secBlobLength, byteCount, secBlob, nativOS,
-				nativLanMngr);
-		return wrapNetbios(wrapHeader(response));
-	}
-
-	/**
-	 * Builds the session setup challange packet
-	 * 
-	 * @return session setup challange packet
-	 */
-	private byte[] getSetupChal() {
-		byte[] wordCount = { 0x04 };
-		byte[] andXCommand = { (byte) 0xff };
-		byte[] reserved = { 0x00 };
-		byte[] andXOffset = { 0x60, 0x01 };
-		byte[] action = { 0x00, 0x00 };
-		byte[] secBlobLength;
-		byte[] byteCount;
-		byte[] secBlob = { (byte) 0xa1, (byte) 0x81, (byte) 0xc4 };
-		byte[] negToken = { 0x30, (byte) 0x81, (byte) 0xc1, (byte) 0xa0, 0x03,
-				0x0a, 0x01 };
-		byte[] negResult = { 0x01 };
-		byte[] negToken2 = { (byte) 0xa1, 0x0c, 0x06, 0x0a };
-		byte[] supportedMech = { 0x2b, 0x06, 0x01, 0x04, 0x01, (byte) 0x82,
-				0x37, 0x02, 0x02, 0x0a };
-		byte[] negToken3 = { (byte) 0xa2, (byte) 0x81, (byte) 0xab, 0x04,
-				(byte) 0x81, (byte) 0xa8 };
-		byte[] ntlmsspId = { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00 };
-		byte[] nlmMsgType = { 0x02, 0x00, 0x00, 0x00 };
-		byte[] buffer = ByteBuffer.allocate(4).putInt(serverName.length)
-				.array();
-		byte[] targetNameLength = new byte[] { buffer[3], buffer[2] };
-		byte[] targetNameMaxLength = new byte[] { buffer[3], buffer[2] };
-		byte[] targetNameOffset = { 0x38, 0x00, 0x00, 0x00 };
-		byte[] flags = { 0x15, (byte) 0x82, (byte) 0x8a, 0x60 };
-		if (!serverVersion[0].contains("Unix")) {
-			flags[3] = (byte) (flags[3] | 0x02);
-		}
-		byte[] challenge = HelperUtils.randomBytes(8);
-		byte[] reserved2 = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
-		byte[] targetInfoLength = { 0x60, 0x00 };
-		byte[] targetInfoMaxLength = { 0x60, 0x00 };
-		byte[] targetInfoOffset = { 0x48, 0x00, 0x00, 0x00 };
-		byte[] version = null;
-		if (serverVersion[0].contains("Windows 7")
-				|| serverVersion[0].contains("Windows Server 2008")) {
-			version = new byte[] { 0x06, 0x01, (byte) 0xb0, 0x1d, 0x00, 0x00,
-					0x00, 0x0f };
-		} else if (serverVersion[0].contains("Windows 8")
-				|| serverVersion[0].contains("Windows Server 2012")) {
-			version = new byte[] { 0x06, 0x02, (byte) 0xf0, 0x23, 0x00, 0x00,
-					0x00, 0x0f };
-		}
-		// serverName
-		byte[] attributeNBDomain = { 0x02, 0x00, 0x10, 0x00 };
-		// serverName
-		byte[] attributeNBcomputer = { 0x01, 0x00, 0x10, 0x00 };
-		// serverName
-		byte[] attributeDNSDomain = { 0x04, 0x00, 0x10, 0x00 };
-		// serverName
-		byte[] attributeDNScomputer = { 0x03, 0x00, 0x10, 0x00 };
-		// serverName
-		byte[] attributeTimeStamp = { 0x07, 0x00, 0x08, 0x00 };
-		byte[] timeStamp = getTimeInBytes();
-		byte[] attributeEnd = { 0x00, 0x00, 0x00, 0x00 };
-		secBlob = HelperUtils.concat(secBlob, negToken, negResult, negToken2,
-				supportedMech, negToken3, ntlmsspId, nlmMsgType,
-				targetNameLength, targetNameMaxLength, targetNameOffset, flags,
-				challenge, reserved2, targetInfoLength, targetInfoMaxLength,
-				targetInfoOffset, version, serverName, attributeNBDomain,
-				serverName, attributeNBcomputer, serverName,
-				attributeDNSDomain, serverName, attributeDNScomputer,
-				serverName, attributeTimeStamp, timeStamp, attributeEnd);
-		byte[] nativOS = HelperUtils.fillWithZeroExtended(serverVersion[0]
-				.getBytes());
-		byte[] nativLanMngr = HelperUtils.fillWithZeroExtended(serverVersion[1]
-				.getBytes());
-		buffer = ByteBuffer.allocate(4).putInt(secBlob.length).array();
-		secBlobLength = new byte[] { buffer[3], buffer[2] };
-		buffer = ByteBuffer.allocate(4)
-				.putInt(secBlob.length + nativOS.length + nativLanMngr.length)
-				.array();
-		byteCount = new byte[] { buffer[3], buffer[2] };
-
-		ntStat = new byte[] { 0x16, 0x00, 0x00, (byte) 0xc0 };
-		userID = new byte[] { 0x00, 0x08 };
-
-		byte[] response = HelperUtils.concat(wordCount, andXCommand, reserved,
-				andXOffset, action, secBlobLength, byteCount, secBlob, nativOS,
-				nativLanMngr);
-		return wrapNetbios(wrapHeader(response));
-	}
-
-	/**
-	 * Returns the command number from the current message
-	 * 
-	 * @return command number
-	 */
-	private byte getSmbCommand() {
-		return smbCommand[0];
-	}
-
-	/**
-	 * Builds the trans packet
-	 * 
-	 * @return trans packet
-	 */
-	private Packet getTrans() {
-		byte[] transSub = getTransSub();
-		byte[] response = null;
-		if (transSub[0] == 0x00 && transSub[1] == 0x0b) { // bind_ack
-			byte[] wordCount = { 0x0a };
-			byte[] totalParamCount = { 0x00, 0x00 };
-			byte[] totalDataCount = { 0x44, 0x00 };
-			byte[] reserved = { 0x00, 0x00 };
-			byte[] paramCount = { 0x00, 0x00 };
-			byte[] paramOffset = { 0x38, 0x00 };
-			byte[] paramDisplace = { 0x00, 0x00 };
-			byte[] dataCount = { 0x44, 0x00 };
-			byte[] dataOffset = { 0x38, 0x00 };
-			byte[] dataDisplace = { 0x00, 0x00 };
-			byte[] setupCount = { 0x00 };
-			byte[] reserved2 = { 0x00 };
-			byte[] byteCount = { 0x45, 0x00 };
-			byte[] padding = { 0x00 };
-
-			byte[] dcerpc = getDceRpc(transSub, 0);
-
-			response = HelperUtils.concat(wordCount, totalParamCount,
-					totalDataCount, reserved, paramCount, paramOffset,
-					paramDisplace, dataCount, dataOffset, dataDisplace,
-					setupCount, reserved2, byteCount, padding, dcerpc);
-
-		} else if (transSub[0] == 0x00 && transSub[1] == 0x00) { // netShareEnumAll
-			byte[] wordCount = { 0x0a };
-			byte[] totalParamCount = { 0x00, 0x00 };
-			byte[] totalDataCount = { 0x20, 0x01 };
-			byte[] reserved = { 0x00, 0x00 };
-			byte[] paramCount = { 0x00, 0x00 };
-			byte[] paramOffset = { 0x38, 0x00 };
-			byte[] paramDisplace = { 0x00, 0x00 };
-			byte[] dataCount = { 0x20, 0x01 };
-			byte[] dataOffset = { 0x38, 0x00 };
-			byte[] dataDisplace = { 0x00, 0x00 };
-			byte[] setupCount = { 0x00 };
-			byte[] reserved2 = { 0x00 };
-			byte[] byteCount = new byte[2]/* = {0x21, 0x01} */;
-			byte[] padding = { 0x00 };
-
-			byte[] dcerpc = new byte[24];
-
-			byte[] levelPointer = { 0x01, 0x00, 0x00, 0x00 };
-			byte[] ctr = { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00 };
-			byte[] ctr1 = { 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x02, 0x00,
-					0x03, 0x00, 0x00, 0x00 };
-			byte[] array1Pointer = { 0x08, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,
-					(byte) 0x80, 0x0c, 0x00, 0x02, 0x00 };
-			byte[] array2Pointer = { 0x10, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,
-					(byte) 0x80, 0x14, 0x00, 0x02, 0x00 };
-			byte[] array3Pointer = { 0x18, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00,
-					(byte) 0x80, 0x1c, 0x00, 0x02, 0x00 };
-			byte[] array1 = { 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-					0x07, 0x00, 0x00, 0x00, 0x41, 0x00, 0x44, 0x00, 0x4d, 0x00,
-					0x49, 0x00, 0x4e, 0x00, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00,
-					0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x00,
-					0x00, 0x00, 0x52, 0x00, 0x65, 0x00, 0x6d, 0x00, 0x6f, 0x00,
-					0x74, 0x00, 0x65, 0x00, 0x20, 0x00, 0x41, 0x00, 0x64, 0x00,
-					0x6d, 0x00, 0x69, 0x00, 0x6e, 0x00, 0x00, 0x00 };
-			byte[] array2 = { 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
-					0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x43, 0x00, 0x24, 0x00,
-					0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00,
-					0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x44, 0x00, 0x65, 0x00,
-					0x66, 0x00, 0x61, 0x00, 0x75, 0x00, 0x6c, 0x00, 0x74, 0x00,
-					0x20, 0x00, 0x73, 0x00, 0x68, 0x00, 0x61, 0x00, 0x72, 0x00,
-					0x65, 0x00 };
-			byte[] array3 = { 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00,
-					0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x49, 0x00, 0x50, 0x00,
-					0x43, 0x00, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00,
-					0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00,
-					0x52, 0x00, 0x65, 0x00, 0x6d, 0x00, 0x6f, 0x00, 0x74, 0x00,
-					0x65, 0x00, 0x20, 0x00, 0x49, 0x00, 0x50, 0x00, 0x43, 0x00,
-					0x00, 0x00 };
-			byte[] totalEntries = { 0x00, 0x00, 0x03, 0x00, 0x00, 0x00 };
-			byte[] referentID = { 0x20, 0x00, 0x02, 0x00 };
-			byte[] resumeHandle = { 0x00, 0x00, 0x00, 0x00 };
-			byte[] windowsError = { 0x00, 0x00, 0x00, 0x00 };
-			int tmp = padding.length + dcerpc.length + levelPointer.length
-					+ ctr.length + ctr1.length + array1Pointer.length
-					+ array2Pointer.length + array3Pointer.length
-					+ array1.length + array2.length + array3.length
-					+ totalEntries.length + referentID.length
-					+ resumeHandle.length + windowsError.length;
-			byte[] tmp2 = ByteBuffer.allocate(4).putInt(tmp).array();
-			byteCount = new byte[] { tmp2[3], tmp2[2] };
-			dcerpc = getDceRpc(transSub, tmp - 1);
-
-			response = HelperUtils.concat(wordCount, totalParamCount,
-					totalDataCount, reserved, paramCount, paramOffset,
-					paramDisplace, dataCount, dataOffset, dataDisplace,
-					setupCount, reserved2, byteCount, padding, dcerpc,
-					levelPointer, ctr, ctr1, array1Pointer, array2Pointer,
-					array3Pointer, array1, array2, array3, totalEntries,
-					referentID, resumeHandle, windowsError);
-		}
-
-		return new Packet(wrapNetbios(wrapHeader(response)));
-	}
-
-	/**
-	 * Builds the trans2 packet
-	 * 
-	 * @return trans2 packet
-	 */
-	private Packet getTrans2() {
-		byte[] response = null;
-		byte[] wordCount = { 0x00 };
-		byte[] andXCommand = { 0x00, 0x00 };
-		ntStat = new byte[] { 0x22, 0x00, 0x00, (byte) 0xc0 };
-		response = HelperUtils.concat(wordCount, andXCommand);
-		return new Packet(wrapNetbios(wrapHeader(response)));
-	}
-
-	/**
-	 * Extracts the trans sub packet from message
-	 * 
-	 * @return trans sub packet
-	 */
-	private byte[] getTransSub() {
-		byte[] transSub = new byte[2];
-		if (smbCommand[0] == 0x32)
-			transSub = new byte[] { message[66], message[65] };
-		else if (smbCommand[0] == 0x25)
-			transSub = new byte[] { 0x00, message[90] };
-		else
-			transSub = new byte[] { 0x00, 0x00 };
-		return transSub;
-	}
-
-	/**
-	 * Builds the tree connect packet
-	 * 
-	 * @return tree connect packet
-	 */
-	private Packet getTreeCon() {
-		String str = HelperUtils.byteToStr(message);
-		byte[] wordCount = { 0x00 };
-		byte[] andXCommand = { 0x00, 0x00 };
-		byte[] response = null;
-		if (str.contains("IPC$") || str.contains("C$")) {
-			wordCount = new byte[] { 0x07 };
-			andXCommand = new byte[] { (byte) 0xff };
-			byte[] reserved = { 0x00 };
-			byte[] andXOffset = { 0x38, 0x00 };
-			byte[] optionalSupport = { 0x01, 0x00 };
-			byte[] maxShareAccess = { (byte) 0xff, (byte) 0xff, 0x1f, 0x00 };
-			byte[] guestMaxShareAccess = { (byte) 0xff, (byte) 0xff, 0x1f, 0x00 };
-			byte[] byteCount = { 0x07, 0x00 };
-			byte[] service = { 0x49, 0x50, 0x43, 0x00 };
-			byte[] extraParameters = { 0x00, 0x00, 0x00 };
-
-			treeID = new byte[] { 0x00, 0x08 };
-
-			response = HelperUtils.concat(wordCount, andXCommand, reserved,
-					andXOffset, optionalSupport, maxShareAccess,
-					guestMaxShareAccess, byteCount, service, extraParameters);
-		} else if (str.contains("ADMIN$")) {
-			ntStat = new byte[] { 0x22, 0x00, 0x00, (byte) 0xc0 };
-			response = HelperUtils.concat(wordCount, andXCommand);
-		} else {
-			ntStat = new byte[] { (byte) 0xcc, 0x00, 0x00, (byte) 0xc0 };
-			response = HelperUtils.concat(wordCount, andXCommand);
-		}
-
-		return new Packet(wrapNetbios(wrapHeader(response)));
-	}
-
-	/**
-	 * Builds the tree disconnect packet
-	 * 
-	 * @return tree disconnect packet
-	 */
-	private Packet getTreeDisc() {
-		byte[] wordCount = { 0x00 };
-		byte[] byteCount = { 0x00, 0x00 };
-
-		smbCommand[0] = 0x71;
-
-		byte[] response = HelperUtils.concat(wordCount, byteCount);
-
-		return new Packet(wrapNetbios(wrapHeader(response)));
-	}
-
-	/**
-	 * Breaks a message from the client down into its components
-	 * 
-	 * @param message
-	 *            that is analyzed
-	 */
-	private void parseMessageHeader(byte[] message) {
-		this.message = message;
-		serverComp = new byte[] { message[4], message[5], message[6],
-				message[7] };
-		smbCommand = new byte[] { message[8] };
-		ntStat = new byte[] { message[9], message[10], message[11], message[12] };
-		smbFlags = new byte[] { (byte) (message[13] | 0x80) }; // | 0x80 for
-																// mark response
-																// bit
-		smbFlags2 = new byte[] { message[14], message[15] };
-		processIDHigh = new byte[] { message[16], message[17] };
-		signature = new byte[] { message[18], message[19], message[20],
-				message[21], message[22], message[23], message[24], message[25] };
-		reserved = new byte[] { message[26], message[27] };
-		treeID = new byte[] { message[28], message[29] };
-		processID = new byte[] { message[30], message[31] };
-		userID = new byte[] { message[32], message[33] };
-		multiplexID = new byte[] { message[34], message[35] };
-	}
-
-	/**
-	 * Wraps the header around a response
-	 * 
-	 * @param response
-	 *            that is wrapped
-	 * @return wrapped response
-	 */
-	private byte[] wrapHeader(byte[] response) {
-		byte[] header = new byte[0];
-		return HelperUtils.concat(header, serverComp, smbCommand, ntStat,
-				smbFlags, smbFlags2, processIDHigh, signature, reserved,
-				treeID, processID, userID, multiplexID, response);
-	}
-
-	/**
-	 * Wraps the Netbios header around a response
-	 * 
-	 * @param response
-	 *            that is wrapped
-	 * @return wrapped response
-	 */
-	private byte[] wrapNetbios(byte[] response) {
-		byte[] netbios = { 0x00 };
-		byte[] buffer = ByteBuffer.allocate(4).putInt(response.length).array(); // allocate(4)
-																				// because
-																				// int
-																				// is
-																				// 4
-																				// bytes
-																				// long
-		byte[] netbiosLength = { buffer[1], buffer[2], buffer[3] }; // only
-																	// bytes 1-3
-																	// needed,
-																	// byte 0 is
-																	// not
-																	// needed
-		return HelperUtils.concat(netbios, netbiosLength, response);
-	}
-
 }

+ 103 - 0
src/de/tudarmstadt/informatik/hostage/protocol/SMBUtils/NBDS.java

@@ -0,0 +1,103 @@
+package de.tudarmstadt.informatik.hostage.protocol.SMBUtils;
+
+import java.nio.ByteBuffer;
+
+import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
+
+
+public class NBDS {
+	
+	private byte[] type;
+	private byte[] flags;
+	private byte[] id;
+	private byte[] srcIP;
+	private byte[] srcPort;
+	private byte[] length;
+	private byte[] offset;
+	private byte[] srcName;
+	private byte[] dstName;
+	private SMBPacket smb;
+	private SMBMailSlot smbMailSlot;
+	private MicrosoftWindowsBrowser microsoftWindowsBrowser;
+	
+	public NBDS(byte[] transactID, byte[] ip, byte[] addr, String src, String dst) {
+		type = new byte[]{0x11};
+		flags = new byte[]{0x0a};
+		id = transactID;
+		srcIP = addr;
+		srcPort = new byte[]{0x00, (byte) 0x8a};
+		offset = new byte[]{0x00, 0x00};
+		length = new byte[2];
+		srcName = NMBStringCoder.wrapNBNSName(NMBStringCoder.encodeNBNSName(src.getBytes()), Service.WORKSTATION);
+		dstName = NMBStringCoder.wrapNBNSName(NMBStringCoder.encodeNBNSName(dst.getBytes()), Service.LOCAL_MASTER_BROWSER);
+		smb = new SMBPacket(null);
+		smb.prepareNextResponse();
+		smbMailSlot = new SMBMailSlot();
+		microsoftWindowsBrowser = new MicrosoftWindowsBrowser(src);
+		byte[] buffer = HelperUtils.concat(srcName, dstName, smb.getTrans(), smbMailSlot.getBytes(), microsoftWindowsBrowser.getBytes());
+		byte[] lengthBuffer = ByteBuffer.allocate(4).putInt(buffer.length).array();
+		length[0] = lengthBuffer[2];
+		length[1] = lengthBuffer[3];
+	}
+	
+	public byte[] getBytes() {
+		return HelperUtils.concat(type, flags, id, srcIP, srcPort, length,
+				offset, srcName, dstName, smb.getTrans(), smbMailSlot.getBytes(), microsoftWindowsBrowser.getBytes());
+	}
+
+	private class SMBMailSlot {
+		private byte[] opcode;
+		private byte[] priority;
+		private byte[] smbclass;
+		private byte[] size;
+		private byte[] name;
+		
+		public SMBMailSlot() {
+			opcode = new byte[]{0x01, 0x00};
+			priority = new byte[]{0x01, 0x00};
+			smbclass = new byte[]{0x02, 0x00};
+			size = new byte[]{0x3e, 0x00};
+			name = HelperUtils.concat("\\MAILSLOT\\BROWSE".getBytes(), new byte[]{0x00}); 
+		}
+		
+		public byte[] getBytes() {
+			return HelperUtils.concat(opcode, priority, smbclass, size, name);
+		}
+	}
+	
+	private class MicrosoftWindowsBrowser {
+		private byte[] command;
+		private byte[] updateCount;
+		private byte[] updatePeriodicity;
+		private byte[] hostName;
+		private byte[] osMajorVersion;
+		private byte[] osMinorVersion;
+		private byte[] serverType;
+		private byte[] browserProtocolMajorVer;
+		private byte[] browserProtocolMinorVer;
+		private byte[] signature;
+		private byte[] hostComment;
+		
+		public MicrosoftWindowsBrowser(String name) {
+			command = new byte[]{0x01};
+			updateCount = new byte[]{0x00};
+			updatePeriodicity = new byte[]{0x60, (byte) 0xea, 0x00, 0x00};
+			hostName = HelperUtils.concat(name.getBytes(),
+					new byte[]{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00});
+			osMajorVersion = new byte[]{0x04};
+			osMinorVersion = new byte[]{0x09};
+			serverType = new byte[]{0x03, (byte) 0x9a, (byte) 0x81, 0x00};
+			browserProtocolMajorVer = new byte[]{0x0f};
+			browserProtocolMinorVer = new byte[]{0x01};
+			signature = new byte[]{0x55, (byte) 0xaa};
+			hostComment = HelperUtils.concat("Samba Server".getBytes(), new byte[]{0x00});
+		}
+		
+		public byte[] getBytes() {
+			return HelperUtils.concat(command, updateCount, updatePeriodicity,
+					hostName, osMajorVersion, osMinorVersion, serverType,
+					browserProtocolMajorVer, browserProtocolMinorVer,
+					signature, hostComment);
+		}
+	}
+}

+ 176 - 0
src/de/tudarmstadt/informatik/hostage/protocol/SMBUtils/NBNS.java

@@ -0,0 +1,176 @@
+package de.tudarmstadt.informatik.hostage.protocol.SMBUtils;
+
+import java.nio.ByteBuffer;
+
+import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
+
+
+public class NBNS {
+	
+	private byte[] transactID;
+	private byte[] flags;
+	private byte[] questions;
+	private byte[] answerRRs;
+	private byte[] authorityRRs;
+	private byte[] additionalRRs;
+	private byte[] payload;
+	private byte[] additional;
+	private byte[] addr;
+	private byte[] name;
+	private int type;
+	private int service;
+	
+	public NBNS(byte[] packet) {
+		transactID = new byte[]{packet[0], packet[1]};
+		flags = new byte[]{packet[2], packet[3]};
+		questions = new byte[]{packet[4], packet[5]};
+		answerRRs = new byte[]{packet[6], packet[7]};
+		authorityRRs = new byte[]{packet[8], packet[9]};
+		additionalRRs = new byte[]{packet[10], packet[11]};
+		int length = 0;
+		for (int i = 12; i < packet.length; i++, length++) {
+			if (packet[i] == 0x01) {
+				length++;
+				break;
+			}
+		}
+		payload = new byte[length];
+		for (int i = 0; i < payload.length; i++) {
+			payload[i] = packet[i+12];
+		}
+		additional = new byte[packet.length-12-length];
+		for (int i = 0; i < additional.length; i++) {
+			additional[i] = packet[i+12+length];
+		}
+	}
+	
+	public NBNS(byte[] transactID, String addr) {
+		this.transactID = transactID;
+		addressToBytes(addr);
+	}
+	
+	public NBNS(byte[] transactID, int type, int service, String name, String addr) {
+		this(transactID, addr);
+		this.type = type;
+		this.service = service;
+		setName(name);
+	}
+	
+	private void preparePacket() {
+		switch (type) {
+		case Type.REGISTRATION_UNIQUE:
+			prepareRegistrationPacket();
+			break;
+		case Type.REGISTRATION_GROUP:
+			prepareRegistrationPacket();
+			break;
+		case Type.NAME_QUERY:
+			prepareNameQueryPacket();
+			break;
+		default:
+		}
+	}
+	
+	private void prepareRegistrationPacket() {
+		flags = new byte[]{0x29, 0x10};
+		questions = new byte[]{0x00, 0x01};
+		answerRRs = new byte[]{0x00, 0x00};
+		authorityRRs = new byte[]{0x00, 0x00};
+		additionalRRs = new byte[]{0x00, 0x01};
+		payload = getPayload();
+		additional = getAdditionalRecords();
+	}
+	
+	private void prepareNameQueryPacket() {
+		flags = new byte[] {0x01, 0x10};
+		questions = new byte[]{0x00, 0x01};
+		answerRRs = new byte[]{0x00, 0x00};
+		authorityRRs = new byte[]{0x00, 0x00};
+		additionalRRs = new byte[]{0x00, 0x00};
+		payload = getPayload();
+	}
+	
+	private byte[] getPayload() {
+		byte[] payload = NMBStringCoder.wrapNBNSName(this.name, service);
+		byte[] type = {0x00, 0x20};
+		byte[] nbnsclass = {0x00, 0x01};
+		return HelperUtils.concat(payload, type, nbnsclass);
+	}
+		
+	private void addressToBytes(String addrString) {
+		String[] addrParts = addrString.split("\\.");
+		addr = new byte[4];
+		addr[0] = (byte)Integer.parseInt(addrParts[0]);
+		addr[1] = (byte)Integer.parseInt(addrParts[1]);
+		addr[2] = (byte)Integer.parseInt(addrParts[2]);
+		addr[3] = (byte)Integer.parseInt(addrParts[3]);
+	}
+	
+	public static byte[] getServiceBytes(int service) {
+		switch (service) {
+		case Service.SERVER:
+			return new byte[]{0x43, 0x41};
+		case Service.MESSENGER:
+			return new byte[]{0x41, 0x44};
+		case Service.WORKSTATION:
+			return new byte[]{0x41, 0x41};
+		case Service.BROWSER_ELECTION:
+			return new byte[]{0x42, 0x4f};
+		case Service.LOCAL_MASTER_BROWSER:
+			return new byte[]{0x42, 0x4e};
+		default:
+			return new byte[]{0x43, 0x41};
+		}
+	}
+
+	private byte[] getAdditionalRecords() {
+		byte[] name = {(byte) 0xc0, 0x0c};
+		byte[] type = {0x00, 0x20};
+		byte[] nbnsclass = {0x00, 0x01};
+		byte[] timeToLive = {0x00, 0x00, 0x00, 0x00};
+		byte[] nameFlags = ((this.type == Type.REGISTRATION_UNIQUE) ? new byte[]{0x00, 0x00} : new byte[]{0x08, 0x00});
+		byte[] buffer = ByteBuffer.allocate(4).putInt(nameFlags.length + addr.length).array();
+		byte[] length = {buffer[2], buffer[3]};
+		return HelperUtils.concat(name, type, nbnsclass, timeToLive, length, nameFlags, addr);
+	}
+	
+	public byte[] getNextPacket() {
+		preparePacket();
+		transactID[1] += 0x01;
+		return getBytes();
+	}
+
+	public byte[] getBytes() {
+		return HelperUtils.concat(transactID, flags, questions, answerRRs, authorityRRs, additionalRRs, payload, additional);
+	}
+
+	public void setName(String name) {
+		this.name = name.getBytes();
+		this.name = NMBStringCoder.encodeNBNSName(this.name);
+	}
+
+	public void setType(int type) {
+		this.type = type;
+	}
+
+	public void setService(int service) {
+		this.service = service;
+	}
+
+	public byte[] getAndIncrementTransactID() {
+		byte[] response = new byte[2];
+		response[0] = transactID[0];
+		response[1] = transactID[1];
+		transactID[1] += 0x01;
+		return response;
+	}
+
+	public byte[] getAddr() {
+		return addr;
+	}
+
+	public byte[] getName() {
+		return name;
+	}
+	
+}

+ 96 - 0
src/de/tudarmstadt/informatik/hostage/protocol/SMBUtils/NMB.java

@@ -0,0 +1,96 @@
+package de.tudarmstadt.informatik.hostage.protocol.SMBUtils;
+
+import java.io.IOException;
+import java.net.DatagramPacket;
+import java.net.DatagramSocket;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+
+public class NMB extends Thread {
+	
+	public static void main(String[] args) {
+		NMB nbns = new NMB("192.168.178.104", "ABCDEFG", "WORKGROUP");
+		nbns.start();
+	}
+	
+	private DatagramSocket nbnsSocket;
+	private DatagramSocket nbdsSocket;
+	private DatagramPacket packet;
+	private String ip;
+	private String[] ipParts;
+	private InetAddress dst;
+	private int nbnsPort = 137;
+	private int nbdsPort = 138;
+	private String username;
+	private String workgroup;
+	
+	public NMB(String ip, String username, String workgroup) {
+		super();
+		try {
+			this.username = username;
+			this.workgroup = workgroup;
+			nbnsSocket = new DatagramSocket(nbnsPort);
+			nbdsSocket = new DatagramSocket(nbdsPort);
+			this.ip = ip;
+			ipParts = ip.split("\\.");
+			String newHostAddr = ipParts[0] + "." + ipParts[1] + "." + ipParts[2] + ".255";
+			dst = InetAddress.getByName(newHostAddr);
+		} catch (UnknownHostException e) {
+			e.printStackTrace();
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+	}
+	
+	private void sendPacket(NBNS nbns) {
+		try {
+			byte[] packetBytes = nbns.getNextPacket();
+			packet = new DatagramPacket(packetBytes, packetBytes.length, dst, nbnsPort);
+			nbnsSocket.send(packet);
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+	}
+	
+	private void sendPacket(NBDS nbds) {
+		try {
+			byte[] packetBytes = nbds.getBytes();
+			packet = new DatagramPacket(packetBytes, packetBytes.length, dst, nbdsPort);
+			nbnsSocket.send(packet);
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+	}
+	
+	private void registrate() {
+		NBNS nbns = new NBNS(new byte[]{0x50, 0x00}, Type.REGISTRATION_UNIQUE, Service.SERVER, username, ip);
+		sendPacket(nbns);
+		
+		nbns.setService(Service.MESSENGER);
+		sendPacket(nbns);
+				
+		nbns.setService(Service.WORKSTATION);
+		sendPacket(nbns);
+			
+		nbns.setName(workgroup);
+		nbns.setType(Type.REGISTRATION_GROUP);
+		sendPacket(nbns);
+		
+		nbns.setService(Service.BROWSER_ELECTION);
+		sendPacket(nbns);
+		
+		NBDS nbds = new NBDS(new byte[]{0x50, 0x06}, nbns.getAndIncrementTransactID(), nbns.getAddr(), username, workgroup);
+		sendPacket(nbds);
+		
+		nbns.setType(Type.NAME_QUERY);
+		nbns.setService(Service.LOCAL_MASTER_BROWSER);
+		sendPacket(nbns);
+	}
+
+	public void run() {
+		registrate();
+		nbnsSocket.close();
+		nbdsSocket.close();
+	}
+	
+}

+ 58 - 0
src/de/tudarmstadt/informatik/hostage/protocol/SMBUtils/NMBStringCoder.java

@@ -0,0 +1,58 @@
+package de.tudarmstadt.informatik.hostage.protocol.SMBUtils;
+
+import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
+
+
+public class NMBStringCoder {
+
+	public static String decodeNBNSName(byte[] name) {
+		byte a_ascii = (byte) 'A';
+		byte[] reducedA = new byte[name.length];
+		for (int i = 0; i < name.length; i++) {
+			reducedA[i] = (byte)(name[i] - a_ascii);
+		}
+		byte[] converted = new byte[reducedA.length / 2];
+		for (int i = 0, j = 0; i < name.length && j < converted.length; i+=2, j++) {
+			byte b1 = (byte) (reducedA[i]<<4);
+			byte b2 = reducedA[i+1];
+			converted[j] = (byte) (b1 | b2);
+		}
+		return new String(converted);
+	}
+	
+	public static byte[] encodeNBNSName(byte[] name) {
+		byte a_ascii = (byte) 'A';
+		byte[] bytes = name;
+		byte[] converted = new byte[bytes.length * 2];
+		for (int i = 0, j = 0; i < bytes.length && j < converted.length; i++, j+=2) {
+			converted[j] = (byte)(bytes[i]>>4);
+			converted[j+1] = (byte)(bytes[i] & 0x0F);
+		}
+		byte[] addedA = new byte[converted.length];
+		for (int i = 0; i < converted.length; i++) {
+			addedA[i] = (byte) (converted[i] + a_ascii);
+		}
+		return addedA;
+	}
+	
+	public static byte[] wrapNBNSName(byte[] name, int service) {
+		byte[] nameStart = {0x20};
+		byte[] namePadding = null;
+		if (name.length < 32) {
+			int paddingLen = 32 - name.length;
+			namePadding = new byte[paddingLen];
+			for (int i = 0; i < namePadding.length; i+=2) {
+				if (i == namePadding.length-2) {
+					byte[] serviceBytes = NBNS.getServiceBytes(service);
+					namePadding[i] = serviceBytes[0];
+					namePadding[i+1] = serviceBytes[1];
+				} else {
+					namePadding[i] = 0x43;
+					namePadding[i+1] = 0x041;
+				}
+			}
+		}
+		byte[] nameEnd = {0x00};
+		return HelperUtils.concat(nameStart, name, namePadding, nameEnd);
+	}
+}

+ 701 - 0
src/de/tudarmstadt/informatik/hostage/protocol/SMBUtils/SMBPacket.java

@@ -0,0 +1,701 @@
+package de.tudarmstadt.informatik.hostage.protocol.SMBUtils;
+
+import java.nio.ByteBuffer;
+import java.util.Calendar;
+import java.util.GregorianCalendar;
+import java.util.TimeZone;
+
+import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
+
+/**
+ * SMBPacket
+ * 
+ * @author Wulf Pfeiffer
+ */
+public class SMBPacket {
+	
+	private String[] serverVersion;
+	private byte[] serverName = HelperUtils.fillWithZero(HelperUtils
+			.getRandomString(16, true).getBytes());
+	private byte[] message = null;
+	private static final byte[] serverGUID = HelperUtils.randomBytes(16);
+	private boolean authenticateNext = false;
+
+	// components of a SMB packet
+	private byte[] serverComp = new byte[4];
+	private byte[] smbCommand = new byte[1];
+	private byte[] ntStat = new byte[4];
+	private byte[] smbFlags = new byte[1];
+	private byte[] smbFlags2 = new byte[2];
+	private byte[] processIDHigh = new byte[2];
+	private byte[] signature = new byte[8];
+	private byte[] reserved = new byte[2];
+	private byte[] treeID = new byte[2];
+	private byte[] processID = new byte[2];
+	private byte[] userID = new byte[2];
+	private byte[] multiplexID = new byte[2];
+	
+	public SMBPacket(String[] serverVersion) {
+		this.serverVersion = serverVersion;
+	}
+	
+	public void prepareNextResponse() {
+		serverComp = new byte[] { (byte) 0xff, 0x53, 0x4d, 0x42 };
+		smbCommand = new byte[] { 0x25 };
+		ntStat = new byte[] { 0x00, 0x00, 0x00, 0x00 };
+		// | 0x80 for mark response bit
+		smbFlags = new byte[] { 0x00 }; 
+		smbFlags2 = new byte[] { 0x00, 0x00 };
+		processIDHigh = new byte[] { 0x00, 0x00 };
+		signature = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+		reserved = new byte[] { 0x00, 0x00 };
+		treeID = new byte[] { 0x00, 0x00 };
+		processID = new byte[] { 0x00, 0x00 };
+		userID = new byte[] { 0x00, 0x00 };
+		multiplexID = new byte[] { 0x00, 0x00 };
+	}
+	
+	public void prepareNextResponse(byte[] message) {
+		this.message = message;
+		serverComp = new byte[] { message[4], message[5], message[6],message[7] };
+		smbCommand = new byte[] { message[8] };
+		ntStat = new byte[] { message[9], message[10], message[11], message[12] };
+		// | 0x80 for mark response bit
+		smbFlags = new byte[] { (byte) (message[13] | 0x80) }; 
+		smbFlags2 = new byte[] { message[14], message[15] };
+		processIDHigh = new byte[] { message[16], message[17] };
+		signature = new byte[] { message[18], message[19], message[20],
+				message[21], message[22], message[23], message[24], message[25] };
+		reserved = new byte[] { message[26], message[27] };
+		treeID = new byte[] { message[28], message[29] };
+		processID = new byte[] { message[30], message[31] };
+		userID = new byte[] { message[32], message[33] };
+		multiplexID = new byte[] { message[34], message[35] };
+	}
+	
+	/**
+	 * Wraps the header around a response
+	 * 
+	 * @param response
+	 *            that is wrapped
+	 * @return wrapped response
+	 */
+	private byte[] wrapHeader(byte[] response) {
+		byte[] header = new byte[0];
+		return HelperUtils.concat(header, serverComp, smbCommand, ntStat,
+				smbFlags, smbFlags2, processIDHigh, signature, reserved,
+				treeID, processID, userID, multiplexID, response);
+	}
+
+	/**
+	 * Wraps the Netbios header around a response
+	 * 
+	 * @param response
+	 *            that is wrapped
+	 * @return wrapped response
+	 */
+	private byte[] wrapNetbios(byte[] response) {
+		byte[] netbios = { 0x00 };
+		// allocate(4) because int is 4 bytes long
+		byte[] buffer = ByteBuffer.allocate(4).putInt(response.length).array();
+		// only bytes 1-3 needed, byte 0 is not  needed
+		byte[] netbiosLength = { buffer[1], buffer[2], buffer[3] }; 
+		return HelperUtils.concat(netbios, netbiosLength, response);
+	}
+
+	/**
+	 * Evaluates what Dialects are offered by the client and which position the
+	 * used NT LM 0.12 dialect is at
+	 * 
+	 * @return position of the NT LM 0.12 dialect
+	 */
+	private byte[] evaluateDialect() {
+		byte[] dialectMsg = new byte[message.length - 39];
+		System.arraycopy(message, 39, dialectMsg, 0, message.length - 39);
+		short dialectNumber = 0;
+		for (int i = 0, start = 0; i < dialectMsg.length; i++) {
+			if (dialectMsg[i] == 0x00) {
+				byte[] dialect = new byte[i - start];
+				System.arraycopy(dialectMsg, start, dialect, 0, i - start);
+				if (HelperUtils.byteToStr(dialect).contains("NT LM 0.12")) {
+					return new byte[] { (byte) dialectNumber,
+							(byte) (dialectNumber >> 8) };
+				}
+				start = i + 1;
+				dialectNumber++;
+			}
+		}
+		return new byte[] { 0x00, 0x00 };
+	}
+
+	/**
+	 * Builds the close packet
+	 * 
+	 * @return close packet
+	 */
+	public byte[] getClose() {
+		byte[] wordCount = { 0x00 };
+		byte[] byteCount = { 0x00, 0x00 };
+
+		smbCommand = new byte[] { 0x04 };
+
+		byte[] response = HelperUtils.concat(wordCount, byteCount);
+
+		return wrapNetbios(wrapHeader(response));
+	}
+
+	/**
+	 * Builds the DCERPC packet
+	 * 
+	 * @return DCERPC packet
+	 */
+	public byte[] getDceRpc(byte[] transSub, int length) {
+		byte[] majorVersion = { 0x05 };
+		byte[] minorVersion = { 0x00 };
+		byte[] packetType = null;
+		byte[] packetFlags = { 0x03 };
+		byte[] dataRepres = { 0x10, 0x00, 0x00, 0x00 };
+		byte[] fragLength = null;
+		byte[] authLength = { 0x00, 0x00 };
+		byte[] callID = null;
+		byte[] response = null;
+
+		if (transSub[0] == 0x00 && transSub[1] == 0x0b) {
+			packetType = new byte[] { 0x0c };
+			fragLength = new byte[] { 0x44, 0x00 };
+			callID = new byte[] { 0x01, 0x00, 0x00, 0x00 };
+			byte[] maxXmitFrag = { (byte) 0xb8, 0x10 };
+			byte[] maxRecvFrag = { (byte) 0xb8, 0x10 };
+			byte[] assocGroup = { 0x4a, 0x41, 0x00, 0x00 };
+			byte[] scndryAddrLen = { 0x0d, 0x00 };
+			byte[] scndryAddr = { 0x5c, 0x50, 0x49, 0x50, 0x45, 0x5c, 0x73,
+					0x72, 0x76, 0x73, 0x76, 0x63, 0x00, 0x00 };
+			byte[] numResults = { 0x01, 0x00, 0x00, 0x00 };
+			byte[] ctxItem = { 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, (byte) 0x88,
+					(byte) 0x8a, (byte) 0xeb, 0x1c, (byte) 0xc9, 0x11,
+					(byte) 0x9f, (byte) 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48,
+					0x60, 0x02, 0x00, 0x00, 0x00 };
+
+			response = HelperUtils.concat(majorVersion, minorVersion,
+					packetType, packetFlags, dataRepres, fragLength,
+					authLength, callID, maxXmitFrag, maxRecvFrag, assocGroup,
+					scndryAddrLen, scndryAddr, numResults, ctxItem);
+		} else if (transSub[0] == 0x00 && transSub[1] == 0x00) {
+			packetType = new byte[] { 0x02 };
+			byte[] tmp = ByteBuffer.allocate(4).putInt(length).array();
+			fragLength = new byte[] { tmp[3], tmp[2] };
+			callID = new byte[] { 0x02, 0x00, 0x00, 0x00 };
+			tmp = ByteBuffer.allocate(4).putInt(length - 24).array();
+			byte[] allocHint = new byte[] { tmp[3], tmp[2], tmp[1], tmp[0] };
+			byte[] contextID = { 0x00, 0x00 };
+			byte[] cancelCount = { 0x00, 0x00 };
+
+			response = HelperUtils.concat(majorVersion, minorVersion,
+					packetType, packetFlags, dataRepres, fragLength,
+					authLength, callID, allocHint, contextID, cancelCount);
+		}
+		return response;
+	}
+
+	/**
+	 * Builds the echo packet
+	 * 
+	 * @return echo packet
+	 */
+	public byte[] getEcho() {
+		byte[] wordCount = { 0x01 };
+		byte[] echoSeq = { 0x01, 0x00 };
+		byte[] byteCount = { 0x10, 0x00 };
+		byte[] echoData = { (byte) 0xf0, (byte) 0xf0, (byte) 0xf0, (byte) 0xf0,
+				(byte) 0xf0, (byte) 0xf0, (byte) 0xf0, (byte) 0xf0,
+				(byte) 0xf0, (byte) 0xf0, (byte) 0xf0, (byte) 0xf0,
+				(byte) 0xf0, (byte) 0xf0, (byte) 0xf0, (byte) 0xf0 };
+		byte[] response = HelperUtils.concat(wordCount, echoSeq, byteCount,
+				echoData);
+		return wrapNetbios(wrapHeader(response));
+	}
+
+	/**
+	 * Builds the negotiate packet
+	 * 
+	 * @return negotiate packet
+	 */
+	public byte[] getNego() {
+		byte[] wordCount = { 0x11 };
+		byte[] dialect = evaluateDialect();
+		byte[] secMode = { 0x03 };
+		byte[] maxMpxC = { 0x32, 0x00 };
+		byte[] maxVcs = { 0x01, 0x00 };
+		byte[] maxBufSize = { 0x04, 0x11, 0x00, 0x00 };
+		byte[] maxRawBuf = { 0x00, 0x00, 0x01, 0x00 };
+		byte[] sessionKey = { 0x00, 0x00, 0x00, 0x00 };
+		byte[] capabilities = { (byte) 0xfc, (byte) 0xe3, 0x01, (byte) 0x80 };
+		byte[] sysTime = getTimeInBytes();
+		byte[] timeZone = getTimeZoneInBytes();
+		byte[] keyLength = { 0x00 };
+		byte[] byteCount = { 0x3a, 0x00 };
+		byte[] guid = serverGUID;
+		byte[] secBlob = { 0x60, 0x28, 0x06, 0x06 };
+		byte[] oid = { 0x2b, 0x06, 0x01, 0x05, 0x05, 0x02 };
+		byte[] protectNeg = { (byte) 0xa0, 0x1e };
+		byte[] negToken = { 0x30, 0x1c, (byte) 0xa0, 0x1a, 0x30, 0x18 };
+		byte[] mechType = { 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01,
+				(byte) 0x82, 0x37, 0x02, 0x02, 0x1e };
+		byte[] mechType2 = { 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01,
+				(byte) 0x82, 0x37, 0x02, 0x02, 0x0a };
+
+		byte[] response = HelperUtils.concat(wordCount, dialect, secMode,
+				maxMpxC, maxVcs, maxBufSize, maxRawBuf, sessionKey,
+				capabilities, sysTime, timeZone, keyLength, byteCount, guid,
+				secBlob, oid, protectNeg, negToken, mechType, mechType2);
+		return wrapNetbios(wrapHeader(response));
+	}
+
+	/**
+	 * Builds the nt create packet
+	 * 
+	 * @return nt create packet
+	 */
+	public byte[] getNTCreate() {
+		byte[] wordCount = { 0x22 };
+		byte[] andXCommand = { (byte) 0xff };
+		byte[] reserved = { 0x00 };
+		byte[] andXOffset = { 0x67, 0x00 };
+		byte[] oplockLevel = { 0x00 };
+		byte[] fid = { (byte) 0x00, 0x40 };
+		byte[] createAction = { 0x01, 0x00, 0x00, 0x00 };
+		byte[] created = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+		byte[] lastAccess = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+		byte[] lastWrite = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+		byte[] change = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+		byte[] fileAttributes = { (byte) 0x80, 0x00, 0x00, 0x00 };
+		byte[] allocationSize = { 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
+				0x00 };
+		byte[] endOfFile = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+		byte[] fileType = { 0x02, 0x00 };
+		byte[] ipcState = { (byte) 0xff, 0x05 };
+		byte[] isDirectory = { 0x00 };
+		byte[] byteCount = { 0x00, 0x00 };
+
+		byte[] response = HelperUtils.concat(wordCount, andXCommand, reserved,
+				andXOffset, oplockLevel, fid, createAction, created,
+				lastAccess, lastWrite, change, fileAttributes, allocationSize,
+				endOfFile, fileType, ipcState, isDirectory, byteCount);
+		return wrapNetbios(wrapHeader(response));
+	}
+
+	/**
+	 * Builds the session setup packet
+	 * 
+	 * @ret urn session setup packet
+	 */
+	public byte[] getSessSetup() {
+		if (authenticateNext) {
+			return getSetupAuth();
+		} else {
+			authenticateNext = true;
+			return getSetupChal();
+		}
+	}
+
+	/**
+	 * Builds the session setup packet for authentication required
+	 * 
+	 * @return session setup authentication packet
+	 */
+	private byte[] getSetupAuth() {
+		byte[] wordCount = { 0x04 };
+		byte[] andXCommand = { (byte) 0xff };
+		byte[] reserved = { 0x00 };
+		byte[] andXOffset = { (byte) 0xa2, 0x00 };
+		byte[] action = { 0x01, 0x00 };
+		byte[] secBlobLength;
+		byte[] byteCount;
+		byte[] secBlob = { (byte) 0xa1, 0x07, 0x30, 0x05, (byte) 0xa0, 0x03,
+				0x0a, 0x01, 0x00 };
+		byte[] nativOS = HelperUtils.fillWithZeroExtended(serverVersion[0]
+				.getBytes());
+		byte[] nativLanMngr = HelperUtils.fillWithZeroExtended(serverVersion[1]
+				.getBytes());
+
+		byte[] buffer = ByteBuffer.allocate(4).putInt(secBlob.length).array();
+		secBlobLength = new byte[] { buffer[3], buffer[2] };
+		buffer = ByteBuffer.allocate(4)
+				.putInt(secBlob.length + nativOS.length + nativLanMngr.length)
+				.array();
+		byteCount = new byte[] { buffer[3], buffer[2] };
+
+		byte[] response = HelperUtils.concat(wordCount, andXCommand, reserved,
+				andXOffset, action, secBlobLength, byteCount, secBlob, nativOS,
+				nativLanMngr);
+		return wrapNetbios(wrapHeader(response));
+	}
+
+	/**
+	 * Builds the session setup challange packet
+	 * 
+	 * @return session setup challange packet
+	 */
+	private byte[] getSetupChal() {
+		byte[] wordCount = { 0x04 };
+		byte[] andXCommand = { (byte) 0xff };
+		byte[] reserved = { 0x00 };
+		byte[] andXOffset = { 0x60, 0x01 };
+		byte[] action = { 0x00, 0x00 };
+		byte[] secBlobLength;
+		byte[] byteCount;
+		byte[] secBlob = { (byte) 0xa1, (byte) 0x81, (byte) 0xc4 };
+		byte[] negToken = { 0x30, (byte) 0x81, (byte) 0xc1, (byte) 0xa0, 0x03,
+				0x0a, 0x01 };
+		byte[] negResult = { 0x01 };
+		byte[] negToken2 = { (byte) 0xa1, 0x0c, 0x06, 0x0a };
+		byte[] supportedMech = { 0x2b, 0x06, 0x01, 0x04, 0x01, (byte) 0x82,
+				0x37, 0x02, 0x02, 0x0a };
+		byte[] negToken3 = { (byte) 0xa2, (byte) 0x81, (byte) 0xab, 0x04,
+				(byte) 0x81, (byte) 0xa8 };
+		byte[] ntlmsspId = { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00 };
+		byte[] nlmMsgType = { 0x02, 0x00, 0x00, 0x00 };
+		byte[] buffer = ByteBuffer.allocate(4).putInt(serverName.length)
+				.array();
+		byte[] targetNameLength = new byte[] { buffer[3], buffer[2] };
+		byte[] targetNameMaxLength = new byte[] { buffer[3], buffer[2] };
+		byte[] targetNameOffset = { 0x38, 0x00, 0x00, 0x00 };
+		byte[] flags = { 0x15, (byte) 0x82, (byte) 0x8a, 0x60 };
+		if (!serverVersion[0].contains("Unix")) {
+			flags[3] = (byte) (flags[3] | 0x02);
+		}
+		byte[] challenge = HelperUtils.randomBytes(8);
+		byte[] reserved2 = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+		byte[] targetInfoLength = { 0x60, 0x00 };
+		byte[] targetInfoMaxLength = { 0x60, 0x00 };
+		byte[] targetInfoOffset = { 0x48, 0x00, 0x00, 0x00 };
+		byte[] version = null;
+		if (serverVersion[0].contains("Windows 7")
+				|| serverVersion[0].contains("Windows Server 2008")) {
+			version = new byte[] { 0x06, 0x01, (byte) 0xb0, 0x1d, 0x00, 0x00,
+					0x00, 0x0f };
+		} else if (serverVersion[0].contains("Windows 8")
+				|| serverVersion[0].contains("Windows Server 2012")) {
+			version = new byte[] { 0x06, 0x02, (byte) 0xf0, 0x23, 0x00, 0x00,
+					0x00, 0x0f };
+		}
+		// serverName
+		byte[] attributeNBDomain = { 0x02, 0x00, 0x10, 0x00 };
+		// serverName
+		byte[] attributeNBcomputer = { 0x01, 0x00, 0x10, 0x00 };
+		// serverName
+		byte[] attributeDNSDomain = { 0x04, 0x00, 0x10, 0x00 };
+		// serverName
+		byte[] attributeDNScomputer = { 0x03, 0x00, 0x10, 0x00 };
+		// serverName
+		byte[] attributeTimeStamp = { 0x07, 0x00, 0x08, 0x00 };
+		byte[] timeStamp = getTimeInBytes();
+		byte[] attributeEnd = { 0x00, 0x00, 0x00, 0x00 };
+		secBlob = HelperUtils.concat(secBlob, negToken, negResult, negToken2,
+				supportedMech, negToken3, ntlmsspId, nlmMsgType,
+				targetNameLength, targetNameMaxLength, targetNameOffset, flags,
+				challenge, reserved2, targetInfoLength, targetInfoMaxLength,
+				targetInfoOffset, version, serverName, attributeNBDomain,
+				serverName, attributeNBcomputer, serverName,
+				attributeDNSDomain, serverName, attributeDNScomputer,
+				serverName, attributeTimeStamp, timeStamp, attributeEnd);
+		byte[] nativOS = HelperUtils.fillWithZeroExtended(serverVersion[0]
+				.getBytes());
+		byte[] nativLanMngr = HelperUtils.fillWithZeroExtended(serverVersion[1]
+				.getBytes());
+		buffer = ByteBuffer.allocate(4).putInt(secBlob.length).array();
+		secBlobLength = new byte[] { buffer[3], buffer[2] };
+		buffer = ByteBuffer.allocate(4)
+				.putInt(secBlob.length + nativOS.length + nativLanMngr.length)
+				.array();
+		byteCount = new byte[] { buffer[3], buffer[2] };
+
+		ntStat = new byte[] { 0x16, 0x00, 0x00, (byte) 0xc0 };
+		userID = new byte[] { 0x00, 0x08 };
+
+		byte[] response = HelperUtils.concat(wordCount, andXCommand, reserved,
+				andXOffset, action, secBlobLength, byteCount, secBlob, nativOS,
+				nativLanMngr);
+		return wrapNetbios(wrapHeader(response));
+	}
+
+	/**
+	 * Returns the command number from the current message
+	 * 
+	 * @return command number
+	 */
+	public byte getSmbCommand() {
+		return smbCommand[0];
+	}
+
+	/**
+	 * Builds the trans packet
+	 * 
+	 * @return trans packet
+	 */
+	public byte[] getTrans() {
+		byte[] transSub = getTransSub();
+		byte[] response = null;
+		
+		if (transSub[0] == (byte) 0xff) { // for NMB in host announcement, NOT smb protocol
+			System.out.println("Hi");
+			byte[] wordCount = { 0x11 };
+			byte[] totalParamCount = { 0x00, 0x00 };
+			byte[] totalDataCount = { 0x2d, 0x00 };
+			byte[] maxParamCount = { 0x00, 0x00 };
+			byte[] maxDataCount = { 0x00, 0x00 };
+			byte[] maxSetupCount = { 0x00 };
+			byte[] reserved = { 0x00 };
+			byte[] flags = { 0x00, 0x00 };
+			byte[] timeout = { 0x00, 0x00, 0x00, 0x00 };
+			byte[] reserved2 = { 0x00, 0x00 };
+			byte[] paramCount = { 0x00, 0x00 };
+			byte[] paramOffset = { 0x00, 0x00 };
+			byte[] dataCount = { 0x2d, 0x00 };
+			byte[] dataOffset = { 0x56, 0x00 };
+			byte[] setupCount = { 0x03 };
+			byte[] reserved3 = { 0x00 };
+			// no netbios header required for NMB!!
+			return wrapHeader(HelperUtils.concat(wordCount, totalParamCount, totalDataCount,
+					maxParamCount, maxDataCount, maxSetupCount, reserved, flags, timeout, reserved2,
+					paramCount, paramOffset, dataCount, dataOffset, setupCount, reserved3));
+		} else if (transSub[0] == 0x00 && transSub[1] == 0x0b) { // bind_ack
+			byte[] wordCount = { 0x0a };
+			byte[] totalParamCount = { 0x00, 0x00 };
+			byte[] totalDataCount = { 0x44, 0x00 };
+			byte[] reserved = { 0x00, 0x00 };
+			byte[] paramCount = { 0x00, 0x00 };
+			byte[] paramOffset = { 0x38, 0x00 };
+			byte[] paramDisplace = { 0x00, 0x00 };
+			byte[] dataCount = { 0x44, 0x00 };
+			byte[] dataOffset = { 0x38, 0x00 };
+			byte[] dataDisplace = { 0x00, 0x00 };
+			byte[] setupCount = { 0x00 };
+			byte[] reserved2 = { 0x00 };
+			byte[] byteCount = { 0x45, 0x00 };
+			byte[] padding = { 0x00 };
+
+			byte[] dcerpc = getDceRpc(transSub, 0);
+
+			response = HelperUtils.concat(wordCount, totalParamCount,
+					totalDataCount, reserved, paramCount, paramOffset,
+					paramDisplace, dataCount, dataOffset, dataDisplace,
+					setupCount, reserved2, byteCount, padding, dcerpc);
+
+		} else if (transSub[0] == 0x00 && transSub[1] == 0x00) { // netShareEnumAll
+			byte[] wordCount = { 0x0a };
+			byte[] totalParamCount = { 0x00, 0x00 };
+			byte[] totalDataCount = { 0x20, 0x01 };
+			byte[] reserved = { 0x00, 0x00 };
+			byte[] paramCount = { 0x00, 0x00 };
+			byte[] paramOffset = { 0x38, 0x00 };
+			byte[] paramDisplace = { 0x00, 0x00 };
+			byte[] dataCount = { 0x20, 0x01 };
+			byte[] dataOffset = { 0x38, 0x00 };
+			byte[] dataDisplace = { 0x00, 0x00 };
+			byte[] setupCount = { 0x00 };
+			byte[] reserved2 = { 0x00 };
+			byte[] byteCount = new byte[2]/* = {0x21, 0x01} */;
+			byte[] padding = { 0x00 };
+
+			byte[] dcerpc = new byte[24];
+
+			byte[] levelPointer = { 0x01, 0x00, 0x00, 0x00 };
+			byte[] ctr = { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00 };
+			byte[] ctr1 = { 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x02, 0x00,
+					0x03, 0x00, 0x00, 0x00 };
+			byte[] array1Pointer = { 0x08, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,
+					(byte) 0x80, 0x0c, 0x00, 0x02, 0x00 };
+			byte[] array2Pointer = { 0x10, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,
+					(byte) 0x80, 0x14, 0x00, 0x02, 0x00 };
+			byte[] array3Pointer = { 0x18, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00,
+					(byte) 0x80, 0x1c, 0x00, 0x02, 0x00 };
+			byte[] array1 = { 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+					0x07, 0x00, 0x00, 0x00, 0x41, 0x00, 0x44, 0x00, 0x4d, 0x00,
+					0x49, 0x00, 0x4e, 0x00, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00,
+					0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x00,
+					0x00, 0x00, 0x52, 0x00, 0x65, 0x00, 0x6d, 0x00, 0x6f, 0x00,
+					0x74, 0x00, 0x65, 0x00, 0x20, 0x00, 0x41, 0x00, 0x64, 0x00,
+					0x6d, 0x00, 0x69, 0x00, 0x6e, 0x00, 0x00, 0x00 };
+			byte[] array2 = { 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
+					0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x43, 0x00, 0x24, 0x00,
+					0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00,
+					0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x44, 0x00, 0x65, 0x00,
+					0x66, 0x00, 0x61, 0x00, 0x75, 0x00, 0x6c, 0x00, 0x74, 0x00,
+					0x20, 0x00, 0x73, 0x00, 0x68, 0x00, 0x61, 0x00, 0x72, 0x00,
+					0x65, 0x00 };
+			byte[] array3 = { 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00,
+					0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x49, 0x00, 0x50, 0x00,
+					0x43, 0x00, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00,
+					0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00,
+					0x52, 0x00, 0x65, 0x00, 0x6d, 0x00, 0x6f, 0x00, 0x74, 0x00,
+					0x65, 0x00, 0x20, 0x00, 0x49, 0x00, 0x50, 0x00, 0x43, 0x00,
+					0x00, 0x00 };
+			byte[] totalEntries = { 0x00, 0x00, 0x03, 0x00, 0x00, 0x00 };
+			byte[] referentID = { 0x20, 0x00, 0x02, 0x00 };
+			byte[] resumeHandle = { 0x00, 0x00, 0x00, 0x00 };
+			byte[] windowsError = { 0x00, 0x00, 0x00, 0x00 };
+			int tmp = padding.length + dcerpc.length + levelPointer.length
+					+ ctr.length + ctr1.length + array1Pointer.length
+					+ array2Pointer.length + array3Pointer.length
+					+ array1.length + array2.length + array3.length
+					+ totalEntries.length + referentID.length
+					+ resumeHandle.length + windowsError.length;
+			byte[] tmp2 = ByteBuffer.allocate(4).putInt(tmp).array();
+			byteCount = new byte[] { tmp2[3], tmp2[2] };
+			dcerpc = getDceRpc(transSub, tmp - 1);
+
+			response = HelperUtils.concat(wordCount, totalParamCount,
+					totalDataCount, reserved, paramCount, paramOffset,
+					paramDisplace, dataCount, dataOffset, dataDisplace,
+					setupCount, reserved2, byteCount, padding, dcerpc,
+					levelPointer, ctr, ctr1, array1Pointer, array2Pointer,
+					array3Pointer, array1, array2, array3, totalEntries,
+					referentID, resumeHandle, windowsError);
+		}
+
+		return wrapNetbios(wrapHeader(response));
+	}
+
+	/**
+	 * Builds the trans2 packet
+	 * 
+	 * @return trans2 packet
+	 */
+	public byte[] getTrans2() {
+		byte[] response = null;
+		byte[] wordCount = { 0x00 };
+		byte[] andXCommand = { 0x00, 0x00 };
+		ntStat = new byte[] { 0x22, 0x00, 0x00, (byte) 0xc0 };
+		response = HelperUtils.concat(wordCount, andXCommand);
+		return wrapNetbios(wrapHeader(response));
+	}
+
+	/**
+	 * Extracts the trans sub packet from message
+	 * 
+	 * @return trans sub packet
+	 */
+	private byte[] getTransSub() {
+		byte[] transSub = new byte[2];
+		if (smbCommand[0] == 0x32)
+			transSub = new byte[] { message[66], message[65] };
+		else if (smbCommand[0] == 0x25 && message != null)
+			transSub = new byte[] { 0x00, message[90] };
+		else if (smbCommand[0] == 0x25 && message == null)
+			transSub = new byte[] { (byte) 0xff };
+		else
+			transSub = new byte[] { 0x00, 0x00 };
+		return transSub;
+	}
+
+	/**
+	 * Builds the tree connect packet
+	 * 
+	 * @return tree connect packet
+	 */
+	public byte[] getTreeCon() {
+		String str = HelperUtils.byteToStr(message);
+		byte[] wordCount = { 0x00 };
+		byte[] andXCommand = { 0x00, 0x00 };
+		byte[] response = null;
+		if (str.contains("IPC$") || str.contains("C$")) {
+			wordCount = new byte[] { 0x07 };
+			andXCommand = new byte[] { (byte) 0xff };
+			byte[] reserved = { 0x00 };
+			byte[] andXOffset = { 0x38, 0x00 };
+			byte[] optionalSupport = { 0x01, 0x00 };
+			byte[] maxShareAccess = { (byte) 0xff, (byte) 0xff, 0x1f, 0x00 };
+			byte[] guestMaxShareAccess = { (byte) 0xff, (byte) 0xff, 0x1f, 0x00 };
+			byte[] byteCount = { 0x07, 0x00 };
+			byte[] service = { 0x49, 0x50, 0x43, 0x00 };
+			byte[] extraParameters = { 0x00, 0x00, 0x00 };
+
+			treeID = new byte[] { 0x00, 0x08 };
+
+			response = HelperUtils.concat(wordCount, andXCommand, reserved,
+					andXOffset, optionalSupport, maxShareAccess,
+					guestMaxShareAccess, byteCount, service, extraParameters);
+		} else if (str.contains("ADMIN$")) {
+			ntStat = new byte[] { 0x22, 0x00, 0x00, (byte) 0xc0 };
+			response = HelperUtils.concat(wordCount, andXCommand);
+		} else {
+			ntStat = new byte[] { (byte) 0xcc, 0x00, 0x00, (byte) 0xc0 };
+			response = HelperUtils.concat(wordCount, andXCommand);
+		}
+
+		return wrapNetbios(wrapHeader(response));
+	}
+
+	/**
+	 * Builds the tree disconnect packet
+	 * 
+	 * @return tree disconnect packet
+	 */
+	public byte[] getTreeDisc() {
+		byte[] wordCount = { 0x00 };
+		byte[] byteCount = { 0x00, 0x00 };
+
+		smbCommand[0] = 0x71;
+
+		byte[] response = HelperUtils.concat(wordCount, byteCount);
+
+		return wrapNetbios(wrapHeader(response));
+	}
+	
+
+	/**
+	 * Converts the current system time into a byte[] with windows specific time
+	 * 
+	 * @return current system time in windows format as byte[]
+	 */
+	private static byte[] getTimeInBytes() {
+		long time = System.currentTimeMillis();
+		Calendar calend = Calendar.getInstance();
+		calend.setTimeZone(TimeZone.getTimeZone("UTC"));
+		calend.set(1601, 0, 01, 00, 00, 00);
+		time -= calend.getTimeInMillis();
+		time *= 10000;
+
+		byte[] timeInWindowsBytes = new byte[8];
+		byte[] timeInBytes = ByteBuffer.allocate(8).putLong(time).array();
+
+		for (int i = 0, j = 7; i < 8 && j > -1; i++, j--) {
+			timeInWindowsBytes[i] = (byte) (timeInBytes[j] & 0xff);
+		}
+
+		return timeInWindowsBytes;
+	}
+
+	/**
+	 * Converts the current timezone into a byte[] with windows specific format
+	 * 
+	 * @return current timezone in windows format as byte[]
+	 */
+	private static byte[] getTimeZoneInBytes() {
+		// get current timezone offset in minutes
+		Integer offset = new GregorianCalendar().getTimeZone().getRawOffset() / 1000 / 60; 
+		char[] offsetChars = Integer.toBinaryString(offset).toCharArray();
+		boolean invert = false;
+		for (int i = offsetChars.length - 1; i > -1; i--) {
+			if (!invert && offsetChars[i] == '1') {
+				invert = true;
+			} else if (invert) {
+				offsetChars[i] = (offsetChars[i] == '0') ? '1' : '0';
+			}
+		}
+		char[] extendedChars = new char[31];
+		for (int i = 0; i < extendedChars.length - offsetChars.length; i++) {
+			extendedChars[i] = '1';
+		}
+		for (int i = 0; i < offsetChars.length; i++) {
+			extendedChars[i + extendedChars.length - offsetChars.length] = offsetChars[i];
+		}
+		int timezone = Integer.parseInt(new String(extendedChars), 2);
+		byte[] timezoneBytes = new byte[2];
+		timezoneBytes[1] = (byte) (timezone >> 8);
+		timezoneBytes[0] = (byte) (timezone);
+		return timezoneBytes;
+	}
+
+}

+ 9 - 0
src/de/tudarmstadt/informatik/hostage/protocol/SMBUtils/Service.java

@@ -0,0 +1,9 @@
+package de.tudarmstadt.informatik.hostage.protocol.SMBUtils;
+
+public class Service {
+	public static final int SERVER = 0;
+	public static final int MESSENGER = 1;
+	public static final int WORKSTATION = 2;
+	public static final int BROWSER_ELECTION = 3;
+	public static final int LOCAL_MASTER_BROWSER = 4;
+}

+ 7 - 0
src/de/tudarmstadt/informatik/hostage/protocol/SMBUtils/Type.java

@@ -0,0 +1,7 @@
+package de.tudarmstadt.informatik.hostage.protocol.SMBUtils;
+
+public class Type {
+	public static final int REGISTRATION_UNIQUE = 0;
+	public static final int REGISTRATION_GROUP = 1;
+	public static final int NAME_QUERY = 2;
+}

+ 12 - 18
src/de/tudarmstadt/informatik/hostage/protocol/SSH.java

@@ -44,7 +44,7 @@ public class SSH implements Protocol {
 	 *            that are converted
 	 * @return converted byte[] as int
 	 */
-	private static int byteToInt(byte[] bytes) {
+	private int byteToInt(byte[] bytes) {
 		int convertedInteger = 0;
 		for (int i = 0; i < bytes.length; i++) {
 			convertedInteger <<= 8;
@@ -53,7 +53,7 @@ public class SSH implements Protocol {
 		return convertedInteger;
 	}
 
-	private static String initSshType() {
+	private String initSshType() {
 		SecureRandom rnd = new SecureRandom();
 		int majorVersion = rnd.nextInt(possibleSshTypes.length);
 		return "OpenSSH_"
@@ -70,18 +70,18 @@ public class SSH implements Protocol {
 	private boolean useEncryption = false;
 
 	// version stuff
-	private static String[][][] possibleSshTypes = {
+	private String[][][] possibleSshTypes = {
 			{ { "3." }, { "4", "5", "6", "7", "8", "9" } },
 			{ { "4." }, { "0", "1", "2", "3", "4", "5", "6", "7", "9" } },
 			{ { "5." }, { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" } },
 			{ { "6." }, { "0", "1", "2", "3", "4" } } };
 
 	// server infos
-	private static String serverVersion = "SSH-2.0-";
+	private String serverVersion = "SSH-2.0-";
 
-	private static String serverType = initSshType();
+	private String serverType = initSshType();
 
-	private static String serverName = HelperUtils.getRandomString(16, false);
+	private String serverName = HelperUtils.getRandomString(16, false);
 
 	private int packetNumber = 0;
 
@@ -180,7 +180,7 @@ public class SSH implements Protocol {
 		switch (state) {
 		case NONE:
 			responsePackets
-					.add(new Packet(serverVersion + serverType + "\r\n"));
+					.add(new Packet(serverVersion + serverType + "\r\n", toString()));
 			state = STATE.SERVER_VERSION;
 			break;
 		case SERVER_VERSION:
@@ -584,13 +584,10 @@ public class SSH implements Protocol {
 	private Packet terminalReply(byte[] request) {
 		TypesReader tr = new TypesReader(request, 6);
 		String messsage = "";
-		System.out.println(HelperUtils.bytesToHexString(request));
 		try {
 			tr.readUINT32();
 			messsage = tr.readString();
-			System.out.println(messsage);
 			if (messsage.contains("\r")) {
-				System.out.println("hi");
 				if (command.toString().contains("exit")) {
 					state = STATE.CLOSED; // ugly style
 					return disconnectReply(2);
@@ -623,9 +620,8 @@ public class SSH implements Protocol {
 	 * @return wrapped packet.
 	 */
 	private Packet wrapPacket(byte[] response) {
-		int packetLength = 5 + response.length; // 4 byte packet length, 1 byte
-												// padding length, payload
-												// length
+		// 4 byte packet length, 1 byte padding length, payload length
+		int packetLength = 5 + response.length;
 		int paddingLengthCBS = cipherBlockSize
 				- (packetLength % cipherBlockSize);
 		int paddingLength8 = 8 - (packetLength % 8);
@@ -633,10 +629,8 @@ public class SSH implements Protocol {
 				: paddingLength8;
 		if (paddingLength < 4)
 			paddingLength += cipherBlockSize;
-		packetLength = packetLength + paddingLength - 4; // add padding string
-															// length to packet
-															// length
-
+		// add padding string length to packet length
+		packetLength = packetLength + paddingLength - 4; 
 		byte[] packetLen = ByteBuffer.allocate(4).putInt(packetLength).array();
 		byte[] paddingLen = { (byte) paddingLength };
 		byte[] paddingString = HelperUtils.randomBytes(paddingLength);
@@ -649,6 +643,6 @@ public class SSH implements Protocol {
 		}
 		packetNumber++;
 
-		return new Packet(wrappedResponse);
+		return new Packet(wrappedResponse, toString());
 	}
 }

+ 68 - 26
src/de/tudarmstadt/informatik/hostage/protocol/TELNET.java

@@ -3,6 +3,10 @@ package de.tudarmstadt.informatik.hostage.protocol;
 import java.util.ArrayList;
 import java.util.List;
 
+import android.content.Context;
+
+import de.tudarmstadt.informatik.hostage.Hostage;
+import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
 import de.tudarmstadt.informatik.hostage.wrapper.Packet;
 
@@ -12,6 +16,7 @@ import de.tudarmstadt.informatik.hostage.wrapper.Packet;
  * @author Wulf Pfeiffer
  */
 public class TELNET implements Protocol {
+	
 	/**
 	 * Represents the states of the protocol
 	 */
@@ -25,19 +30,26 @@ public class TELNET implements Protocol {
 	private STATE state = STATE.NONE;
 
 	/** user entered by the client */
-	private static byte[] user;
+	private byte[] user;
 
 	/** last command sent by the client */
 	private byte[] command;
 
 	/** name of the server */
-	private static String serverName = HelperUtils.getRandomString(16, false);
+	private String serverName = HelperUtils.getRandomString(16, false);
 
+	private String serverVersion = initServerVersion();
+	
+	private String login = initLogin();
+	
+	private String serverBanner = initServerBanner();
+	
 	/** command line prefix */
 	private static byte[] sessionToken = null;
 
 	/** options requested by the server */
-	private static final byte[] optionRequest = { (byte) 0xff, (byte) 0xfb,
+	private static final byte[] optionRequest = {
+			(byte) 0xff, (byte) 0xfb,
 			0x03, // will suppress go ahead
 			(byte) 0xff, (byte) 0xfb, 0x01 // will echo
 	};
@@ -77,13 +89,13 @@ public class TELNET implements Protocol {
 
 		switch (state) {
 		case NONE:
-			responsePackets.add(new Packet(optionRequest));
+			responsePackets.add(new Packet(optionRequest, toString()));
 			state = STATE.OPEN;
 			break;
 		case OPEN:
 			if (request != null) {
-				responsePackets.add(new Packet(getOptionResponse(request)));
-				responsePackets.add(new Packet(serverName + " login: "));
+				responsePackets.add(new Packet(getOptionResponse(request), toString()));
+				responsePackets.add(new Packet(login + "login: ", toString()));
 				state = STATE.LOGIN;
 			}
 			break;
@@ -95,22 +107,26 @@ public class TELNET implements Protocol {
 					byte[] buffer = new byte[request.length - 2];
 					System.arraycopy(request, 0, buffer, 0, request.length - 2);
 					user = HelperUtils.concat(user, buffer);
-					responsePackets.add(new Packet(buffer));
+					responsePackets.add(new Packet(buffer, toString()));
 				}
-				responsePackets.add(new Packet("\r\n"));
-				responsePackets.add(new Packet("Password: "));
+				responsePackets.add(new Packet("\r\n", toString()));
+				responsePackets.add(new Packet("password: ", toString()));
 				state = STATE.AUTHENTICATE;
-				sessionToken = HelperUtils.concat(sessionPrefix, user,
-						"@".getBytes(), serverName.getBytes(), sessionMiddle,
-						user, "@".getBytes(), serverName.getBytes(),
-						sessionSuffix);
+				if (serverVersion.contains("Windows")) {
+					sessionToken = HelperUtils.concat("C:\\Users\\".getBytes(), user, ">".getBytes());
+				} else {
+					sessionToken = HelperUtils.concat(sessionPrefix, user,
+							"@".getBytes(), serverName.getBytes(), sessionMiddle,
+							user, "@".getBytes(), serverName.getBytes(),
+							sessionSuffix);
+				}
 				break;
 			} else if (checkForByte(request, (byte) 0x7f) && user != null
 					&& user.length != 0) {
 				byte[] tmp = new byte[user.length - 1];
 				System.arraycopy(user, 0, tmp, 0, user.length - 1);
 				user = tmp;
-				responsePackets.add(new Packet("\b \b"));
+				responsePackets.add(new Packet("\b \b", toString()));
 				break;
 			} else if (!checkForByte(request, (byte) 0xff)) {
 				if (user == null)
@@ -124,11 +140,11 @@ public class TELNET implements Protocol {
 			if (request == null)
 				break;
 			else if (checkForByte(request, (byte) 0x0d)) {
-				responsePackets.add(new Packet("\r\n"));
-				responsePackets.add(new Packet(sessionToken));
+				responsePackets.add(new Packet("\r\n"+serverBanner, toString()));
+				responsePackets.add(new Packet(sessionToken, toString()));
 				state = STATE.LOGGED_IN;
 			} else if (checkForByte(request, (byte) 0x7f)) {
-				responsePackets.add(new Packet("\b \b"));
+				responsePackets.add(new Packet("\b \b", toString()));
 			}
 			break;
 		case LOGGED_IN:
@@ -139,20 +155,20 @@ public class TELNET implements Protocol {
 					byte[] buffer = new byte[request.length - 2];
 					System.arraycopy(request, 0, buffer, 0, request.length - 2);
 					command = HelperUtils.concat(command, buffer);
-					responsePackets.add(new Packet(buffer));
+					responsePackets.add(new Packet(buffer, toString()));
 				}
 				if (command == null) {
-					responsePackets.add(new Packet("\r\n"));
-					responsePackets.add(new Packet(sessionToken));
+					responsePackets.add(new Packet("\r\n", toString()));
+					responsePackets.add(new Packet(sessionToken, toString()));
 				} else if (new String(command).contains("exit")) {
-					responsePackets.add(new Packet("\r\nlogout\r\n"));
+					responsePackets.add(new Packet("\r\nlogout\r\n", toString()));
 					state = STATE.CLOSED;
 				} else {
 					String bash = "\r\n-bash: " + new String(command)
 							+ ": command not found";
-					responsePackets.add(new Packet(bash));
-					responsePackets.add(new Packet("\r\n"));
-					responsePackets.add(new Packet(sessionToken));
+					responsePackets.add(new Packet(bash, toString()));
+					responsePackets.add(new Packet("\r\n", toString()));
+					responsePackets.add(new Packet(sessionToken, toString()));
 					command = null;
 				}
 			} else if (checkForByte(request, (byte) 0x7f) && command != null
@@ -160,7 +176,7 @@ public class TELNET implements Protocol {
 				byte[] tmp = new byte[command.length - 1];
 				System.arraycopy(command, 0, tmp, 0, command.length - 1);
 				command = tmp;
-				responsePackets.add(new Packet("\b \b"));
+				responsePackets.add(new Packet("\b \b", toString()));
 				break;
 			} else if (!checkForByte(request, (byte) 0xff)) {
 				if (command == null)
@@ -171,7 +187,7 @@ public class TELNET implements Protocol {
 			}
 			break;
 		default:
-			responsePackets.add(new Packet("\r\nlogout\r\n"));
+			responsePackets.add(new Packet("\r\nlogout\r\n", toString()));
 			state = STATE.CLOSED;
 			break;
 		}
@@ -187,6 +203,32 @@ public class TELNET implements Protocol {
 	public TALK_FIRST whoTalksFirst() {
 		return TALK_FIRST.SERVER;
 	}
+	
+	private static String initServerVersion() {
+		String sharedPreferencePath = Hostage.getContext().getString(
+				R.string.shared_preference_path);
+		String profile = Hostage
+				.getContext()
+				.getSharedPreferences(sharedPreferencePath,
+						Context.MODE_PRIVATE).getString("os", "");
+		return profile;
+	}
+	
+	private String initServerBanner() {
+		if (serverVersion.contains("Windows")) {
+			return "\r\n*===============================================================\r\n"
+					+ "Microsoft Telnet Server.\r\n"
+					+ "*===============================================================\r\n";
+		}
+		return "";
+	}
+	
+	private String initLogin() {
+		if (serverVersion.contains("Windows")) {
+			return "Welcome to Microsoft Telnet Service \r\n\r\n";
+		}
+		return "Debian GNU/Linux 7.0\r\n";
+	}
 
 	/**
 	 * Checks a byte array for occurence of one byte.

+ 233 - 0
src/de/tudarmstadt/informatik/hostage/provider/HostageContentProvider.java

@@ -0,0 +1,233 @@
+package de.tudarmstadt.informatik.hostage.provider;
+
+import android.content.ContentProvider;
+import android.content.ContentUris;
+import android.content.ContentValues;
+import android.content.UriMatcher;
+import android.database.Cursor;
+import android.database.sqlite.SQLiteDatabase;
+import android.database.sqlite.SQLiteQueryBuilder;
+import android.net.Uri;
+import android.text.TextUtils;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.AttackEntry;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.NetworkEntry;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.PacketEntry;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
+
+public class HostageContentProvider extends ContentProvider {
+
+	public static final String AUTHORITY = "de.tudarmstadt.informatik.hostage.provider";
+
+	public static final Uri CONTENT_URI_NETWORK = Uri.parse("content://" + AUTHORITY + "/network");
+	public static final Uri CONTENT_URI_ATTACK = Uri.parse("content://" + AUTHORITY + "/attack");
+	public static final Uri CONTENT_URI_PACKET = Uri.parse("content://" + AUTHORITY + "/packet");
+
+	public static final Uri CONTENT_URI_RECORD_OVERVIEW = Uri.parse("content://" + AUTHORITY + "/record-overview");
+
+	private static final int NETWORK_ALL = 11;
+	private static final int NETWORK_ONE = 12;
+	private static final int ATTACK_ALL = 21;
+	private static final int ATTACK_ONE = 22;
+	private static final int PACKET_ALL = 31;
+	private static final int PACKET_ONE = 32;
+
+	private static final int NETWORK_OVERVIEW_ALL = 101;
+	private static final int NETWORK_OVERVIEW_ONE = 102;
+
+	private static final UriMatcher uriMatcher;
+
+	static {
+		uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
+		uriMatcher.addURI(AUTHORITY, "network", NETWORK_ALL);
+		uriMatcher.addURI(AUTHORITY, "network/#", NETWORK_ONE);
+		uriMatcher.addURI(AUTHORITY, "attack", ATTACK_ALL);
+		uriMatcher.addURI(AUTHORITY, "attack/#", ATTACK_ONE);
+		uriMatcher.addURI(AUTHORITY, "packet", PACKET_ALL);
+		uriMatcher.addURI(AUTHORITY, "packet/#", PACKET_ONE);
+		uriMatcher.addURI(AUTHORITY, "record-overview", NETWORK_OVERVIEW_ALL);
+		uriMatcher.addURI(AUTHORITY, "record-overview/#", NETWORK_OVERVIEW_ONE);
+	}
+
+	private HostageDBOpenHelper mDBOpenHelper;
+
+	@Override
+	public boolean onCreate() {
+		mDBOpenHelper = new HostageDBOpenHelper(getContext());
+		return true;
+	}
+
+	@Override
+	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
+		SQLiteDatabase db = mDBOpenHelper.getWritableDatabase();
+		SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
+
+		int uriMatch = uriMatcher.match(uri);
+
+		if (isNetworkUriMatch(uriMatch)) {
+			queryBuilder.setTables(NetworkEntry.TABLE_NAME);
+		} else if (isAttackUriMatch(uriMatch)) {
+			queryBuilder.setTables(AttackEntry.TABLE_NAME);
+		} else if (isPacketUriMatch(uriMatch)) {
+			queryBuilder.setTables(PacketEntry.TABLE_NAME);
+		}
+
+		if (uriMatch == NETWORK_ONE) {
+			String rowID = uri.getPathSegments().get(1);
+			queryBuilder.appendWhere(NetworkEntry.KEY_ID + "=" + rowID);
+		} else if (uriMatch == ATTACK_ONE) {
+			String rowID = uri.getPathSegments().get(1);
+			queryBuilder.appendWhere(AttackEntry.KEY_ID + "=" + rowID);
+		} else if (uriMatch == PACKET_ONE) {
+			String rowID = uri.getPathSegments().get(1);
+			queryBuilder.appendWhere(PacketEntry.KEY_ID + "=" + rowID);
+		}
+
+		Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
+		return cursor;
+	}
+
+	@Override
+	public int delete(Uri uri, String selection, String[] selectionArgs) {
+		SQLiteDatabase db = mDBOpenHelper.getWritableDatabase();
+
+		int uriMatch = uriMatcher.match(uri);
+
+		if (uriMatch == NETWORK_ONE) {
+			String rowID = uri.getPathSegments().get(1);
+			selection = NetworkEntry.KEY_ID + "=" + rowID + (!TextUtils.isEmpty(selection) ? "AND (" + selection + ")" : "");
+		} else if (uriMatch == ATTACK_ONE) {
+			String rowID = uri.getPathSegments().get(1);
+			selection = AttackEntry.KEY_ID + "=" + rowID + (!TextUtils.isEmpty(selection) ? "AND (" + selection + ")" : "");
+		} else if (uriMatch == PACKET_ONE) {
+			String rowID = uri.getPathSegments().get(1);
+			selection = PacketEntry.KEY_ID + "=" + rowID + (!TextUtils.isEmpty(selection) ? "AND (" + selection + ")" : "");
+		}
+
+		if (selection == null) {
+			selection = "1";
+		}
+
+		int deleteCount = 0;
+		if (isNetworkUriMatch(uriMatch)) {
+			deleteCount = db.delete(NetworkEntry.TABLE_NAME, selection, selectionArgs);
+		} else if (isAttackUriMatch(uriMatch)) {
+			deleteCount = db.delete(AttackEntry.TABLE_NAME, selection, selectionArgs);
+		} else if (isPacketUriMatch(uriMatch)) {
+			deleteCount = db.delete(PacketEntry.TABLE_NAME, selection, selectionArgs);
+		}
+
+		getContext().getContentResolver().notifyChange(uri, null);
+
+		return deleteCount;
+	}
+
+	@Override
+	public Uri insert(Uri uri, ContentValues values) {
+		SQLiteDatabase db = mDBOpenHelper.getWritableDatabase();
+
+		int uriMatch = uriMatcher.match(uri);
+
+		long id = -1;
+		Uri insertedId = null;
+		if (isNetworkUriMatch(uriMatch)) {
+			id = db.insert(NetworkEntry.TABLE_NAME, null, values);
+			if (id > -1) {
+				insertedId = ContentUris.withAppendedId(CONTENT_URI_NETWORK, id);
+			}
+		} else if (isAttackUriMatch(uriMatch)) {
+			id = db.insert(AttackEntry.TABLE_NAME, null, values);
+			if (id > -1) {
+				insertedId = ContentUris.withAppendedId(CONTENT_URI_NETWORK, id);
+			}
+		} else if (isPacketUriMatch(uriMatch)) {
+			id = db.insert(PacketEntry.TABLE_NAME, null, values);
+			if (id > -1) {
+				insertedId = ContentUris.withAppendedId(CONTENT_URI_NETWORK, id);
+			}
+		}
+
+		if (id > -1) {
+			getContext().getContentResolver().notifyChange(insertedId, null);
+			return insertedId;
+		}
+
+		return null;
+	}
+
+	@Override
+	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
+		SQLiteDatabase db = mDBOpenHelper.getWritableDatabase();
+
+		int uriMatch = uriMatcher.match(uri);
+
+		if (uriMatch == NETWORK_ONE) {
+			String rowID = uri.getPathSegments().get(1);
+			selection = NetworkEntry.KEY_ID + "=" + rowID + (!TextUtils.isEmpty(selection) ? "AND (" + selection + ")" : "");
+		} else if (uriMatch == ATTACK_ONE) {
+			String rowID = uri.getPathSegments().get(1);
+			selection = AttackEntry.KEY_ID + "=" + rowID + (!TextUtils.isEmpty(selection) ? "AND (" + selection + ")" : "");
+		} else if (uriMatch == PACKET_ONE) {
+			String rowID = uri.getPathSegments().get(1);
+			selection = PacketEntry.KEY_ID + "=" + rowID + (!TextUtils.isEmpty(selection) ? "AND (" + selection + ")" : "");
+		}
+
+		int updateCount = 0;
+		if (isNetworkUriMatch(uriMatch)) {
+			updateCount = db.update(NetworkEntry.TABLE_NAME, values, selection, selectionArgs);
+		} else if (isAttackUriMatch(uriMatch)) {
+			updateCount = db.update(AttackEntry.TABLE_NAME, values, selection, selectionArgs);
+		} else if (isPacketUriMatch(uriMatch)) {
+			updateCount = db.update(PacketEntry.TABLE_NAME, values, selection, selectionArgs);
+		}
+
+		getContext().getContentResolver().notifyChange(uri, null);
+
+		return updateCount;
+	}
+
+	@Override
+	public String getType(Uri uri) {
+		int uriMatch = uriMatcher.match(uri);
+
+		if (isNetworkUriMatch(uriMatch)) {
+			if (uriMatch == NETWORK_ONE) {
+				return "vnd.android.cursor.item/vnd.de.tudarmstadt.informatik.hostage.provider.network";
+			}
+			return "vnd.android.cursor.dir/vnd.de.tudarmstadt.informatik.hostage.provider.network";
+		} else if (isAttackUriMatch(uriMatch)) {
+			if (uriMatch == ATTACK_ONE) {
+				return "vnd.android.cursor.item/vnd.de.tudarmstadt.informatik.hostage.provider.attack";
+			}
+			return "vnd.android.cursor.dir/vnd.de.tudarmstadt.informatik.hostage.provider.attack";
+		} else if (isPacketUriMatch(uriMatch)) {
+			if (uriMatch == PACKET_ONE) {
+				return "vnd.android.cursor.item/vnd.de.tudarmstadt.informatik.hostage.provider.packet";
+			}
+			return "vnd.android.cursor.dir/vnd.de.tudarmstadt.informatik.hostage.provider.packet";
+		}
+
+		return null;
+	}
+
+	private boolean isNetworkUriMatch(int uriMatch) {
+		if (uriMatch == NETWORK_ALL || uriMatch == NETWORK_ONE) {
+			return true;
+		}
+		return false;
+	}
+
+	private boolean isAttackUriMatch(int uriMatch) {
+		if (uriMatch == ATTACK_ALL || uriMatch == ATTACK_ONE) {
+			return true;
+		}
+		return false;
+	}
+
+	private boolean isPacketUriMatch(int uriMatch) {
+		if (uriMatch == PACKET_ALL || uriMatch == PACKET_ONE) {
+			return true;
+		}
+		return false;
+	}
+
+}

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

@@ -1,305 +1,368 @@
-package de.tudarmstadt.informatik.hostage.sync;
-
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.UUID;
-
-import android.app.AlertDialog;
-import android.bluetooth.BluetoothAdapter;
-import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothServerSocket;
-import android.bluetooth.BluetoothSocket;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.widget.ArrayAdapter;
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
-
-public class BluetoothSync {
-
-	private class ClientThread extends Thread {
-		private final BluetoothSocket socket;
-
-		public ClientThread(BluetoothDevice device) {
-			BluetoothSocket tmp = null;
-			try {
-				tmp = device.createRfcommSocketToServiceRecord(serviceUUID);
-			} catch (IOException e) {
-			}
-			socket = tmp;
-		}
-
-		/** Will cancel an in-progress connection, and close the socket */
-		public void cancel() {
-			try {
-				socket.close();
-			} catch (IOException e) {
-			}
-		}
-
-		@Override
-		public void run() {
-
-			try {
-				socket.connect();
-			} catch (IOException connectException) {
-				// Unable to connect; close the socket and get out
-				try {
-					socket.close();
-				} catch (IOException closeException) {
-				}
-				return;
-			}
-
-			manageConnectedSocket(socket, CLIENT);
-		}
-	}
-
-	private class CommunicationThread extends Thread {
-		private final BluetoothSocket mmSocket;
-		private final ObjectInputStream objectInput;
-		private final ObjectOutputStream objectOuput;
-		private final int identifier;
-
-		public CommunicationThread(BluetoothSocket socket, int identifier) {
-			mmSocket = socket;
-			ObjectInputStream tmpIn = null;
-			ObjectOutputStream tmpOut = null;
-
-			// Get the input and output streams, using temp objects because
-			// member streams are final
-			try {
-				tmpOut = new ObjectOutputStream(socket.getOutputStream());
-				tmpIn = new ObjectInputStream(socket.getInputStream());
-			} catch (IOException e) {
-				e.printStackTrace();
-			}
-
-			objectInput = tmpIn;
-			objectOuput = tmpOut;
-			this.identifier = identifier;
-		}
-
-		/* Call this from the main activity to shutdown the connection */
-		public void cancel() {
-			try {
-				mmSocket.close();
-			} catch (IOException e) {
-			}
-		}
-
-		@Override
-		public void run() {
-			// Keep listening to the InputStream until an exception occurs
-			// while (true) {
-			try {
-				// TODO Ersetze dbh mit Logger
-				UglyDbHelper dbh = new UglyDbHelper(context);
-				ArrayList<HashMap<String, Object>> localNetworkInformation = dbh
-						.getNetworkInformation();
-				if (identifier == SERVER) {
-					// Read from the InputStream
-					ArrayList<HashMap<String, Object>> remoteNetworkInformation = (ArrayList<HashMap<String, Object>>) objectInput
-							.readObject();
-					;
-					dbh.updateNetworkInformation(remoteNetworkInformation);
-					objectOuput.writeObject(localNetworkInformation);
-				} else {
-					objectOuput.writeObject(localNetworkInformation);
-					// Read from the InputStream
-					ArrayList<HashMap<String, Object>> remoteNetworkInformation = (ArrayList<HashMap<String, Object>>) objectInput
-							.readObject();
-					dbh.updateNetworkInformation(remoteNetworkInformation);
-					mmSocket.close();
-				}
-			} catch (ClassNotFoundException e) {
-				e.printStackTrace();
-			} catch (IOException e) {
-				e.printStackTrace();
-			}
-			// }
-		}
-
-		/* Call this from the main activity to send data to the remote device */
-		public void write(ArrayList<HashMap<String, Object>> networkInformation) {
-			try {
-				objectOuput.writeObject(networkInformation);
-			} catch (IOException e) {
-				e.printStackTrace();
-			}
-		}
-	}
-
-	private class ServerThread extends Thread {
-		private final BluetoothServerSocket serverSocket;
-
-		public ServerThread() {
-			BluetoothServerSocket tmp = null;
-			try {
-				tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(
-						context.getResources().getString(R.string.app_name),
-						serviceUUID);
-			} catch (IOException e) {
-			}
-			serverSocket = tmp;
-		}
-
-		/** Will cancel the listening socket, and cause the thread to finish */
-		public void cancel() {
-			try {
-				serverSocket.close();
-			} catch (IOException e) {
-			}
-		}
-
-		@Override
-		public void run() {
-			BluetoothSocket socket = null;
-			while (true) {
-				try {
-					socket = serverSocket.accept();
-				} catch (IOException e) {
-					e.printStackTrace();
-					break;
-				}
-
-				if (socket != null) {
-					// Do work to manage the connection (in a separate thread)
-					manageConnectedSocket(socket, SERVER);
-					try {
-						serverSocket.close();
-					} catch (IOException e) {
-						e.printStackTrace();
-					}
-					break;
-				}
-			}
-		}
-	}
-
-	private final UUID serviceUUID;
-	private final int SERVER = 0;
-	private final int CLIENT = 1;
-
-	private BluetoothAdapter mBluetoothAdapter;
-	private Context context;
-
-	private ArrayAdapter<String> arrayAdapter;
-
-	private ServerThread serverThread;
-
-	private AlertDialog ad;
-
-	// Create a BroadcastReceiver for ACTION_FOUND
-	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
-		@Override
-		public void onReceive(Context context, Intent intent) {
-			String action = intent.getAction();
-			// When discovery finds a device
-			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
-				// Get the BluetoothDevice object from the Intent
-				BluetoothDevice device = intent
-						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
-				// Add the name and address to an array adapter to show in a
-				// ListView
-				arrayAdapter.add(device.getName() + "\n" + device.getAddress());
-				arrayAdapter.notifyDataSetChanged();
-			}
-		}
-	};
-
-	public BluetoothSync(Context context) {
-		this.context = context;
-		serviceUUID = UUID.fromString(context.getResources().getString(
-				R.string.UUID));
-		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
-	}
-
-	public boolean syncData() {
-		if (!bluetoothAvaible())
-			return false;
-		syncDataPassive();
-		return syncDataActive();
-	}
-
-	private boolean bluetoothAvaible() {
-		if (mBluetoothAdapter == null) {
-			// Device does not support Bluetooth
-			return false;
-		}
-		if (!mBluetoothAdapter.isEnabled()) {
-			Intent enableBtIntent = new Intent(
-					BluetoothAdapter.ACTION_REQUEST_ENABLE);
-			context.startActivity(enableBtIntent);
-			return false;
-		}
-		return true;
-	}
-
-	private void deviceDialog() {
-		AlertDialog.Builder builder = new AlertDialog.Builder(context);
-		// TODO in resources auslagern
-		builder.setTitle("Choose Device");
-		builder.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
-			@Override
-			public void onClick(DialogInterface dialog, int position) {
-				String deviceInfo = arrayAdapter.getItem(position);
-				String mac = deviceInfo.substring(deviceInfo.indexOf("\n") + 1);
-				ClientThread clientThread = new ClientThread(mBluetoothAdapter
-						.getRemoteDevice(mac));
-				clientThread.start();
-			}
-		});
-		// builder.create();
-		ad = builder.show();
-	}
-
-	private void manageConnectedSocket(BluetoothSocket socket, int identifier) {
-		if (identifier == SERVER) {
-			ad.dismiss();
-		}
-		mBluetoothAdapter.cancelDiscovery();
-		context.unregisterReceiver(mReceiver);
-		CommunicationThread commThread = new CommunicationThread(socket,
-				identifier);
-		commThread.start();
-	}
-
-	// Register the BroadcastReceiver
-	private void registerBroadcastReceiver() {
-		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
-		context.registerReceiver(mReceiver, filter); // Don't forget to
-														// unregister during
-														// onDestroy
-	}
-
-	private boolean syncDataActive() {
-		registerBroadcastReceiver();
-		arrayAdapter = new ArrayAdapter<String>(context,
-				android.R.layout.simple_list_item_1);
-		// Start scanning for devices
-		if (!mBluetoothAdapter.startDiscovery())
-			return false;
-
-		deviceDialog();
-		return true;
-	}
-
-	private void syncDataPassive() {
-		Intent discoverableIntent = new Intent(
-				BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
-		discoverableIntent.putExtra(
-				BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
-		context.startActivity(discoverableIntent);
-
-		serverThread = new ServerThread();
-		serverThread.start();
-	}
-
-}
+package de.tudarmstadt.informatik.hostage.sync;
+
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.UUID;
+
+import android.util.Log;
+import android.app.Activity;
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothDevice;
+import android.bluetooth.BluetoothServerSocket;
+import android.bluetooth.BluetoothSocket;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.view.View;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.LinearLayout;
+import android.widget.ListView;
+import android.widget.TextView;
+import android.widget.AdapterView.OnItemClickListener;
+import de.tudarmstadt.informatik.hostage.R;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
+
+public class BluetoothSync extends Activity{	
+	
+    private static final int CONNECTION_ESTABLISHED = 0x0;
+    private static final int CONNECTION_FAILED = 0x1;
+    private static final int MESSAGE_SENT = 0x2;
+    private static final int MESSAGE_RECIEVED = 0x3;
+    
+	private UUID serviceUUID;
+	
+	private BluetoothAdapter mBluetoothAdapter;
+	private ArrayAdapter<String> arrayAdapter;
+
+	private ServerThread serverThread;	
+	private ClientThread clientThread;
+	CommunicationThread commThread;
+	
+	TextView mInfoText;
+	ListView listView;
+	LinearLayout layout;
+	
+	
+	@Override
+	public void onCreate(Bundle savedInstanceState){
+		super.onCreate(savedInstanceState);
+		setContentView(R.layout.activity_bluetooth);		
+		
+		serviceUUID = UUID.fromString(getResources().getString(R.string.UUID));
+		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();					
+		arrayAdapter = new ArrayAdapter<String>(this, R.layout.list_view_bluetooth_devices);	
+		setLayoutElement();
+		registerBroadcastReceiver();
+				
+		if (mBluetoothAdapter == null) {
+			// Device does not support Bluetooth
+			mInfoText.setText("Bluetooth is not available on this device.");
+		}
+		else if (!mBluetoothAdapter.isEnabled()) {
+			mInfoText.setText("Enable Bluetooth before synchronizing.");
+			Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
+			startActivity(enableBtIntent);
+		} else {
+			startConnectionListener();
+			chooseDevice();
+		}
+	}
+		
+	
+	@Override
+	public void onDestroy(){
+		super.onDestroy();
+		if(mRecieverRegistered){
+			unregisterBroadcastReceiver();
+		}
+		if(commThread != null) {
+			commThread.cancel();
+		}
+		if(clientThread != null){
+			clientThread.cancel();
+		}
+		if(serverThread != null){
+			serverThread.cancel();
+		}
+	}
+	
+	private void chooseDevice(){
+		arrayAdapter.clear();
+		if (!mBluetoothAdapter.startDiscovery())
+			return;
+		mInfoText.setText("Choose Device for synchronizing:\n");
+		layout.addView(listView);
+		setContentView(layout);
+	}
+
+	private void startConnectionListener() {
+		Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
+		discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
+		startActivity(discoverableIntent);
+
+		serverThread = new ServerThread();
+		serverThread.start();
+	}
+		
+
+	private void manageConnectedSocket(BluetoothSocket socket) {
+		mBluetoothAdapter.cancelDiscovery();
+		unregisterBroadcastReceiver();
+		commThread = new CommunicationThread(socket);
+		commThread.start();
+		HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
+		ArrayList<HashMap<String, Object>> localNetworkInformation = dbh.getNetworkInformation();
+		commThread.write(localNetworkInformation);
+	}
+
+	private class ClientThread extends Thread {
+		private final BluetoothSocket socket;
+
+		public ClientThread(BluetoothDevice device) {
+			BluetoothSocket tmp = null;
+			try {
+				tmp = device.createRfcommSocketToServiceRecord(serviceUUID);
+			} catch (IOException e) {
+			}
+			socket = tmp;
+		}
+
+		/** Will cancel an in-progress connection, and close the socket */
+		public void cancel() {
+			try {
+				socket.close();
+			} catch (IOException e) {
+			}
+		}
+
+		@Override
+		public void run() {
+
+			try {
+				socket.connect();
+			} catch (IOException connectException) {
+				mHandler.obtainMessage(CONNECTION_FAILED).sendToTarget();
+				// Unable to connect; close the socket and get out
+				try {
+					socket.close();
+				} catch (IOException closeException) {
+				}
+				return;
+			}
+			mHandler.obtainMessage(CONNECTION_ESTABLISHED, socket).sendToTarget();
+			manageConnectedSocket(socket);
+		}
+	}
+
+	private class ServerThread extends Thread {
+		private final BluetoothServerSocket serverSocket;
+
+		public ServerThread() {
+			BluetoothServerSocket tmp = null;
+			try {
+				tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(getResources().getString(R.string.app_name), serviceUUID);
+			} catch (IOException e) {
+			}
+			serverSocket = tmp;
+		}
+
+		/** Will cancel the listening socket, and cause the thread to finish */
+		public void cancel() {
+			try {
+				serverSocket.close();
+			} catch (IOException e) {
+			}
+		}
+
+		@Override
+		public void run() {
+			BluetoothSocket socket = null;
+			while (true) {
+				try {
+					socket = serverSocket.accept();
+				} catch (IOException e) {
+					e.printStackTrace();
+					mHandler.obtainMessage(CONNECTION_FAILED).sendToTarget();
+					break;
+				}
+
+				if (socket != null) {
+					// Do work to manage the connection (in a separate thread)
+					manageConnectedSocket(socket);
+					mHandler.obtainMessage(CONNECTION_ESTABLISHED, socket).sendToTarget();
+					try {
+						serverSocket.close();
+					} catch (IOException e) {
+						e.printStackTrace();
+					}
+					break;
+				}
+			}
+		}
+	}
+	
+	private class CommunicationThread extends Thread {
+		private final BluetoothSocket mmSocket;
+		private final ObjectInputStream objectInput;
+		private final ObjectOutputStream objectOuput;
+
+		public CommunicationThread(BluetoothSocket socket) {
+			mmSocket = socket;
+			ObjectInputStream tmpIn = null;
+			ObjectOutputStream tmpOut = null;
+
+			// Get the input and output streams, using temp objects because
+			// member streams are final
+			try {
+				tmpOut = new ObjectOutputStream(socket.getOutputStream());
+				tmpIn = new ObjectInputStream(socket.getInputStream());
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+
+			objectInput = tmpIn;
+			objectOuput = tmpOut;
+		}
+
+		/* Call this from the main activity to shutdown the connection */
+		public void cancel() {
+			try {
+				mmSocket.close();
+			} catch (IOException e) {
+			}
+		}
+
+		@Override
+		public void run() {
+			// Keep listening to the InputStream until an exception occurs
+			while (true) {
+			try {
+				// TODO Ersetze dbh mit Logger
+				HostageDBOpenHelper dbh = new HostageDBOpenHelper(getContext());
+				// Read from the InputStream
+				ArrayList<HashMap<String, Object>> remoteNetworkInformation = (ArrayList<HashMap<String, Object>>) objectInput.readObject();
+				// update database
+				dbh.updateNetworkInformation(remoteNetworkInformation);	
+				mHandler.obtainMessage(MESSAGE_RECIEVED).sendToTarget();
+			} catch (ClassNotFoundException e) {
+				e.printStackTrace();
+			} catch (IOException e) {
+				e.printStackTrace();
+				break;
+			}
+			}
+		}
+
+		/* Call this from the main activity to send data to the remote device */
+		public void write(ArrayList<HashMap<String, Object>> networkInformation) {
+			try {
+				objectOuput.writeObject(networkInformation);
+				mHandler.obtainMessage(MESSAGE_SENT).sendToTarget();
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+		}
+	}
+
+
+	// Create a BroadcastReceiver for ACTION_FOUND
+	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
+		@Override
+		public void onReceive(Context context, Intent intent) {
+			String action = intent.getAction();
+			// When discovery finds a device
+			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
+				// Get the BluetoothDevice object from the Intent
+				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
+				// Add the name and address to an array adapter to show in a ListView
+				arrayAdapter.add(device.getName() + "\n" + device.getAddress());
+				arrayAdapter.notifyDataSetChanged();
+			}else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
+				int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
+				Log.i("BluetoothSync", state + "");
+				if(state == BluetoothAdapter.STATE_ON){
+					startConnectionListener();
+					chooseDevice();
+				}else if(state == BluetoothAdapter.STATE_OFF ||  state == BluetoothAdapter.STATE_TURNING_OFF){
+					mInfoText.setText("Enable Bluetooth before synchronizing.");
+					layout.removeView(listView);
+				}
+			}
+		}
+	};
+	
+	private boolean mRecieverRegistered = false;
+
+
+	// Register the BroadcastReceiver
+	private void registerBroadcastReceiver() {
+		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
+		filter.addAction(BluetoothAdapter. ACTION_STATE_CHANGED);
+		registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
+		mRecieverRegistered = true;
+	}
+	
+	private void unregisterBroadcastReceiver(){
+		unregisterReceiver(mReceiver);
+		mRecieverRegistered = false;
+	}
+	
+	private Context getContext(){
+		return this;
+	}
+	
+	private void setLayoutElement(){
+		mInfoText = (TextView) findViewById(R.id.bluetoothInfoText);
+		layout = (LinearLayout) findViewById(R.id.bluetoothLayout);
+		listView = new ListView(this);
+		listView.setAdapter(arrayAdapter);
+		listView.setOnItemClickListener(new OnItemClickListener() {
+			@Override
+			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
+				String deviceInfo = arrayAdapter.getItem(position);
+				String mac = deviceInfo.substring(deviceInfo.indexOf("\n") + 1);
+				clientThread = new ClientThread(mBluetoothAdapter.getRemoteDevice(mac));
+				clientThread.start();
+			}
+		});		
+	}	
+	
+	private boolean message_sent = false;
+	private boolean message_recieved = false;
+	
+	private Handler mHandler = new Handler() {
+
+        @Override
+        public void handleMessage(Message msg) {
+        	switch(msg.what){
+        		case CONNECTION_ESTABLISHED: 
+        			layout.removeView(listView);
+        			BluetoothSocket socket = (BluetoothSocket) msg.obj;
+        			String deviceName = socket.getRemoteDevice().getName();
+        			mInfoText.setText("Synchronizing with " + deviceName + "...");	
+        			break;
+        		case CONNECTION_FAILED: 
+        			mInfoText.setText("Synchronization failed!");
+        			break;
+        		case MESSAGE_SENT: 
+        			message_sent = true;
+        			if(message_recieved)
+        				mInfoText.setText("Synchronization successfull!");
+        			break;	
+        		case MESSAGE_RECIEVED: 
+        			message_recieved = true;
+        			if(message_sent)
+        				mInfoText.setText("Synchronization successfull!");
+        			break;	
+        	}        		
+        }
+};
+}

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

@@ -1,185 +1,169 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package de.tudarmstadt.informatik.hostage.sync;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import android.annotation.TargetApi;
-import android.app.Activity;
-import android.content.Intent;
-import android.nfc.NdefMessage;
-import android.nfc.NdefRecord;
-import android.nfc.NfcAdapter;
-import android.nfc.NfcAdapter.CreateNdefMessageCallback;
-import android.nfc.NfcAdapter.OnNdefPushCompleteCallback;
-import android.nfc.NfcEvent;
-import android.os.Build;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Message;
-import android.os.Parcelable;
-import android.util.Log;
-import android.widget.TextView;
-import android.widget.Toast;
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
-
-@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
-public class NFCSync extends Activity implements CreateNdefMessageCallback,
-		OnNdefPushCompleteCallback {
-	NfcAdapter mNfcAdapter;
-	TextView mInfoText;
-	private static final int MESSAGE_SENT = 1;
-
-	public static Object deserialize(byte[] data) throws IOException,
-			ClassNotFoundException {
-		ByteArrayInputStream in = new ByteArrayInputStream(data);
-		ObjectInputStream is = new ObjectInputStream(in);
-		return is.readObject();
-	}
-
-	public static byte[] serialize(Object obj) throws IOException {
-		ByteArrayOutputStream out = new ByteArrayOutputStream();
-		ObjectOutputStream os = new ObjectOutputStream(out);
-		os.writeObject(obj);
-		return out.toByteArray();
-	}
-
-	/** This handler receives a message from onNdefPushComplete */
-	private final Handler mHandler = new Handler() {
-		@Override
-		public void handleMessage(Message msg) {
-			switch (msg.what) {
-			case MESSAGE_SENT:
-				Toast.makeText(getApplicationContext(), "Message sent!",
-						Toast.LENGTH_LONG).show();
-				Log.i("NFC", "Message sent!");
-				break;
-			}
-		}
-	};
-
-	/**
-	 * Implementation for the CreateNdefMessageCallback interface
-	 */
-	@Override
-	public NdefMessage createNdefMessage(NfcEvent event) {
-		// Get Networkdata
-		UglyDbHelper dbh = new UglyDbHelper(this);
-		ArrayList<HashMap<String, Object>> localNetworkInformation = dbh
-				.getNetworkInformation();
-		Log.i("NFC", "Creating Message");
-		NdefMessage msg = null;
-		try {
-			msg = new NdefMessage(NdefRecord.createMime(
-					"application/de.tudarmstadt.informatik.hostage",
-					serialize(localNetworkInformation))
-			/**
-			 * The Android Application Record (AAR) is commented out. When a
-			 * device receives a push with an AAR in it, the application
-			 * specified in the AAR is guaranteed to run. The AAR overrides the
-			 * tag dispatch system. You can add it back in to guarantee that
-			 * this activity starts when receiving a beamed message. For now,
-			 * this code uses the tag dispatch system.
-			 */
-			// ,NdefRecord.createApplicationRecord("com.example.android.beam")
-			);
-		} catch (IOException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		}
-		return msg;
-	}
-
-	@Override
-	public void onCreate(Bundle savedInstanceState) {
-		super.onCreate(savedInstanceState);
-		setContentView(R.layout.activity_nfc);
-
-		mInfoText = (TextView) findViewById(R.id.record_details_text_ssid);
-		// Check for available NFC Adapter
-		mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
-		if (mNfcAdapter == null) {
-			mInfoText = (TextView) findViewById(R.id.record_details_text_ssid);
-			mInfoText.setText("NFC is not available on this device.");
-		} else {
-			// Register callback to set NDEF message
-			mNfcAdapter.setNdefPushMessageCallback(this, this);
-			// Register callback to listen for message-sent success
-			mNfcAdapter.setOnNdefPushCompleteCallback(this, this);
-		}
-	}
-
-	/**
-	 * Implementation for the OnNdefPushCompleteCallback interface
-	 */
-	@Override
-	public void onNdefPushComplete(NfcEvent arg0) {
-		// A handler is needed to send messages to the activity when this
-		// callback occurs, because it happens from a binder thread
-		mHandler.obtainMessage(MESSAGE_SENT).sendToTarget();
-	}
-
-	@Override
-	public void onNewIntent(Intent intent) {
-		// onResume gets called after this to handle the intent
-		setIntent(intent);
-	}
-
-	// HELPER
-
-	@Override
-	public void onResume() {
-		super.onResume();
-		// Check to see that the Activity started due to an Android Beam
-		if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
-			processIntent(getIntent());
-		}
-	}
-
-	/**
-	 * Parses the NDEF Message from the intent and prints to the TextView
-	 */
-	void processIntent(Intent intent) {
-		Parcelable[] rawMsgs = intent
-				.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
-		// only one message sent during the beam
-		NdefMessage msg = (NdefMessage) rawMsgs[0];
-		// record 0 contains the MIME type, record 1 is the AAR, if present
-		Object object;
-		Log.i("NFC", "Getting Message!");
-		try {
-			object = deserialize(msg.getRecords()[0].getPayload());
-			ArrayList<HashMap<String, Object>> remoteNetworkInformation = (ArrayList<HashMap<String, Object>>) object;
-			UglyDbHelper dbh = new UglyDbHelper(this);
-			dbh.updateNetworkInformation(remoteNetworkInformation);
-		} catch (ClassNotFoundException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		} catch (IOException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		}
-	}
-
-}
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package de.tudarmstadt.informatik.hostage.sync;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.ArrayList;
+import java.util.HashMap;
+
+import android.annotation.TargetApi;
+import android.app.Activity;
+import android.content.Intent;
+import android.nfc.NdefMessage;
+import android.nfc.NdefRecord;
+import android.nfc.NfcAdapter;
+import android.nfc.NfcAdapter.CreateNdefMessageCallback;
+import android.nfc.NfcAdapter.OnNdefPushCompleteCallback;
+import android.nfc.NfcEvent;
+import android.os.Build;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.os.Parcelable;
+import android.util.Log;
+import android.widget.TextView;
+import android.widget.Toast;
+import de.tudarmstadt.informatik.hostage.R;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
+
+@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
+public class NFCSync extends Activity implements CreateNdefMessageCallback, OnNdefPushCompleteCallback {
+	NfcAdapter mNfcAdapter;
+	TextView mInfoText;
+	private static final int MESSAGE_SENT = 1;
+
+
+
+	/** This handler receives a message from onNdefPushComplete */
+	private final Handler mHandler = new Handler() {
+		@Override
+		public void handleMessage(Message msg) {
+			switch (msg.what) {
+			case MESSAGE_SENT:
+				Toast.makeText(getApplicationContext(), "Message sent!", Toast.LENGTH_LONG).show();
+				Log.i("NFC", "Message sent!");
+				break;
+			}
+		}
+	};
+
+	/**
+	 * Implementation for the CreateNdefMessageCallback interface
+	 */
+	@Override
+	public NdefMessage createNdefMessage(NfcEvent event) {
+		// Get Networkdata
+		HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
+		ArrayList<HashMap<String, Object>> localNetworkInformation = dbh.getNetworkInformation();
+		Log.i("NFC", "Creating Message");
+		NdefMessage msg = null;
+		try {
+			msg = new NdefMessage(NdefRecord.createMime("application/de.tudarmstadt.informatik.hostage", serialize(localNetworkInformation))
+					
+			);
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+		return msg;
+	}
+
+	@Override
+	public void onCreate(Bundle savedInstanceState) {
+		super.onCreate(savedInstanceState);
+		setContentView(R.layout.activity_nfc);
+
+		mInfoText = (TextView) findViewById(R.id.record_details_text_ssid);
+		// Check for available NFC Adapter
+		mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
+		if (mNfcAdapter == null) {
+			mInfoText.setText("NFC is not available on this device.");
+		} else {
+			mInfoText.setText("Hold phones together to synchronize.");
+			// Register callback to set NDEF message
+			mNfcAdapter.setNdefPushMessageCallback(this, this);
+			// Register callback to listen for message-sent success
+			mNfcAdapter.setOnNdefPushCompleteCallback(this, this);
+		}
+	}
+
+	/**
+	 * Implementation for the OnNdefPushCompleteCallback interface
+	 */
+	@Override
+	public void onNdefPushComplete(NfcEvent arg0) {
+		// A handler is needed to send messages to the activity when this
+		// callback occurs, because it happens from a binder thread
+		mHandler.obtainMessage(MESSAGE_SENT).sendToTarget();
+	}
+
+	@Override
+	public void onNewIntent(Intent intent) {
+		// onResume gets called after this to handle the intent
+		setIntent(intent);
+	}
+
+	// HELPER
+
+	@Override
+	public void onResume() {
+		super.onResume();
+		// Check to see that the Activity started due to an Android Beam
+		if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
+			processIntent(getIntent());
+		}
+	}
+
+	/**
+	 * Parses the NDEF Message from the intent and prints to the TextView
+	 */
+	void processIntent(Intent intent) {
+		Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
+		// only one message sent during the beam
+		NdefMessage msg = (NdefMessage) rawMsgs[0];
+		// record 0 contains the MIME type, record 1 is the AAR, if present
+		Object object;
+		Log.i("NFC", "Getting Message!");
+		try {
+			object = deserialize(msg.getRecords()[0].getPayload());
+			ArrayList<HashMap<String, Object>> remoteNetworkInformation = (ArrayList<HashMap<String, Object>>) object;
+			HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
+			dbh.updateNetworkInformation(remoteNetworkInformation);
+		} catch (ClassNotFoundException e) {
+			e.printStackTrace();
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+	}
+	
+	private static Object deserialize(byte[] data) throws IOException, ClassNotFoundException {
+		ByteArrayInputStream in = new ByteArrayInputStream(data);
+		ObjectInputStream is = new ObjectInputStream(in);
+		return is.readObject();
+	}
+
+	private static byte[] serialize(Object obj) throws IOException {
+		ByteArrayOutputStream out = new ByteArrayOutputStream();
+		ObjectOutputStream os = new ObjectOutputStream(out);
+		os.writeObject(obj);
+		return out.toByteArray();
+	}
+
+}

+ 61 - 0
src/de/tudarmstadt/informatik/hostage/system/Device.java

@@ -0,0 +1,61 @@
+package de.tudarmstadt.informatik.hostage.system;
+
+import java.io.IOException;
+
+import android.util.Log;
+
+public class Device {
+
+	@SuppressWarnings("unused")
+	// DO NOT REMOVE, NEEDED FOR SINGLETON INITIALIZATION
+	private static final Device INSTANCE = new Device();
+
+	private static boolean initialized = false;
+	private static boolean root = false;
+	private static boolean pp = false;
+
+	private Device() {
+		new Thread(new Runnable() {
+			@Override
+			public void run() {
+				try {
+					String test = "[ -e /data/local/bind ]";
+					Process su = new ProcessBuilder("su", "-c", test).start();
+					switch (su.waitFor()) {
+					case 0:
+						root = true;
+						pp = true;
+						break;
+					case 1:
+						root = true;
+						pp = false;
+						break;
+					case 127:
+						root = false;
+						pp = false;
+						break;
+					}
+				} catch (InterruptedException e) {
+				} catch (IOException e) {
+				} finally {
+					initialized = true;
+					Log.d("hostage", "Root: " + Boolean.toString(root));
+					Log.d("hostage", "PP: " + Boolean.toString(pp));
+				}
+			}
+		}).start();
+	}
+
+	public static boolean isRooted() {
+		while (!initialized)
+			;
+		return root;
+	}
+
+	public static boolean isPorthackInstalled() {
+		while (!initialized)
+			;
+		return pp;
+	}
+
+}

+ 0 - 68
src/de/tudarmstadt/informatik/hostage/system/P.java

@@ -1,68 +0,0 @@
-package de.tudarmstadt.informatik.hostage.system;
-
-import java.io.FileDescriptor;
-
-import android.net.LocalServerSocket;
-import android.net.LocalSocket;
-
-/**
- * Receives a file descriptor through a unix domain socket.
- * 
- * @author Mihai Plasoianu
- */
-public class P implements Runnable {
-
-	/**
-	 * Path for UDS in abstract namespace.
-	 */
-	private final static String NAME = "hostage";
-
-	/**
-	 * Port to bind.
-	 */
-	private int port;
-
-	public P(int port) {
-		this.port = port;
-	}
-
-	/**
-	 * Start p, wait for connection and receive a file descriptor.
-	 */
-	public FileDescriptor bindAndGetFD() {
-		FileDescriptor fd = null;
-		try {
-			new Thread(this).start();
-			LocalServerSocket localServer = new LocalServerSocket(NAME);
-			LocalSocket localSocket = localServer.accept();
-			while (localSocket.getInputStream().read() != -1)
-				;
-			FileDescriptor[] fdArray;
-			fdArray = localSocket.getAncillaryFileDescriptors();
-			if (fdArray != null) {
-				fd = fdArray[0];
-			}
-			localSocket.close();
-			localServer.close();
-		} catch (Exception e) {
-			e.printStackTrace();
-		}
-		return fd;
-	}
-
-	/**
-	 * Run p in separate Thread.
-	 */
-	@Override
-	public void run() {
-		Process p;
-		try {
-			String command = String.format("/data/local/p %d", port);
-			p = Runtime.getRuntime().exec(new String[] { "su", "-c", command });
-			p.waitFor();
-		} catch (Exception e) {
-			e.printStackTrace();
-		}
-	}
-
-}

+ 80 - 0
src/de/tudarmstadt/informatik/hostage/system/PrivilegedPort.java

@@ -0,0 +1,80 @@
+package de.tudarmstadt.informatik.hostage.system;
+
+import java.io.BufferedReader;
+import java.io.FileDescriptor;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+
+import android.net.LocalServerSocket;
+import android.net.LocalSocket;
+import android.util.Log;
+
+public class PrivilegedPort implements Runnable {
+
+	public static enum TYPE {
+		TCP, UDP
+	}
+
+	private final static String UNIX_PATH = "hostage";
+
+	private final String LOG_TAG;
+
+	private TYPE type;
+	private int port;
+
+	private FileDescriptor fd;
+
+	public PrivilegedPort(TYPE type, int port) {
+		LOG_TAG = String.format("hostage (porthack %s %d)", type.toString(), port);
+		this.type = type;
+		this.port = port;
+		try {
+			new Thread(this).start();
+			LocalServerSocket localServer = new LocalServerSocket(UNIX_PATH);
+			LocalSocket localSocket = localServer.accept();
+			while (localSocket.getInputStream().read() != -1)
+				;
+			FileDescriptor[] fdArray;
+			fdArray = localSocket.getAncillaryFileDescriptors();
+			if (fdArray != null) {
+				this.fd = fdArray[0];
+			}
+			localSocket.close();
+			localServer.close();
+		} catch (IOException e) {
+		}
+	}
+
+	public FileDescriptor getFD() {
+		return fd;
+	}
+
+	@Override
+	public void run() {
+		String command = String.format("/data/local/bind %s %d", type.toString(), port);
+		try {
+			Process p = new ProcessBuilder("su", "-c", command).start();
+			if (p.waitFor() != 0) {
+				logError(p.getErrorStream());
+			}
+			logOutput(p.getInputStream());
+		} catch (IOException e) {
+		} catch (InterruptedException e) {
+		}
+	}
+
+	private void logOutput(InputStream stdout) throws IOException {
+		BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));
+		String line;
+		while ((line = reader.readLine()) != null) {
+			Log.d(LOG_TAG, line);
+		}
+	}
+
+	private void logError(InputStream stderr) throws IOException {
+		BufferedReader reader = new BufferedReader(new InputStreamReader(stderr));
+		Log.e(LOG_TAG, reader.readLine());
+	}
+
+}

+ 177 - 159
src/de/tudarmstadt/informatik/hostage/ui/LogFilter.java

@@ -1,16 +1,15 @@
 package de.tudarmstadt.informatik.hostage.ui;
 
-import android.os.Parcel;
-import android.os.Parcelable;
-
 import java.util.ArrayList;
 import java.util.HashMap;
 
+import android.os.Parcel;
+import android.os.Parcelable;
+
+public class LogFilter implements Parcelable {
 
-public class LogFilter implements Parcelable{
-	
 	public final static String LOG_FILTER_INTENT_KEY = "de.tudarmstadt.informatik.hostage.logfilter";
-	
+
 	private static final String TIMESTAMP_BELOW_KEY = "de.tudarmstadt.informatik.hostage.logfilter.timestampbelow";
 	private static final String TIMESTAMP_ABOVE_KEY = "de.tudarmstadt.informatik.hostage.logfilter.timestampabove";
 	private static final String PROTOCOLS_KEY = "de.tudarmstadt.informatik.hostage.logfilter.protocols";
@@ -18,210 +17,229 @@ public class LogFilter implements Parcelable{
 	private static final String BSSID_KEY = "de.tudarmstadt.informatik.hostage.logfilter.bssid";
 	private static final String SORTTYPE_KEY = "de.tudarmstadt.informatik.hostage.logfilter.sorttype";
 
-	public enum SortType{
-				timestamp(0),
-				protocol(1),
-				_bssid(1),
-				ssid(3),
-				//remoteHostName(5),
-				//lcaolHostName(6),
-				_attack_id(7),
-				_id(8);
-		        private final int id;
-		        SortType(int id) {
-		        	this.id = id;
-		        }
-		        public int getValue() { 
-		        	return id; 
-		        }
-		    }
-	
+	public enum SortType {
+		packet_timestamp(0), protocol(1), _bssid(1), ssid(3), _attack_id(7), _id(8);
+		private final int id;
+
+		SortType(int id) {
+			this.id = id;
+		}
+
+		public int getValue() {
+			return id;
+		}
+	}
+
 	public ArrayList<String> BSSIDs;
 	public ArrayList<String> ESSIDs;
 	public ArrayList<String> protocols;
-	
+
 	public boolean isNotEditable;
-	
+
 	public SortType sorttype;
 
 	public long belowTimestamp;
 	public long aboveTimestamp;
-	
-	
-	public LogFilter(){
+
+	public LogFilter() {
 		this.clear();
 
 	}
 
-    public void clear(){
-        this.belowTimestamp = Long.MAX_VALUE;
-        this.aboveTimestamp = Long.MIN_VALUE;
-        this.sorttype = SortType.timestamp;
-        this.BSSIDs = new ArrayList<String>();
-        this.ESSIDs = new ArrayList<String>();
-        this.protocols = new ArrayList<String>();
-    }
-
-	    public int describeContents() {
-	        return 0;
-	    }
-
-	    // write your object's data to the passed-in Parcel
-	    public void writeToParcel(Parcel out, int flags) {
-	        HashMap<String, ArrayList<String>> values =new HashMap<String,  ArrayList<String>>();
-	        if(this.BSSIDs != null && this.BSSIDs.size() > 0){
-	        	values.put(BSSID_KEY , this.getBSSIDs() );
-	        }
-	        if(this.ESSIDs != null && this.ESSIDs.size() > 0){
-	        	values.put(ESSID_KEY , this.getESSIDs() );
-	        }
-	        if(this.protocols != null && this.protocols.size() > 0){
-	        	values.put(PROTOCOLS_KEY , this.getProtocols() );
-	        }
-	        long timeArray[] = new long[] {this.aboveTimestamp, this.belowTimestamp};
-
-	        out.writeMap(values);
-	        out.writeInt(this.sorttype.getValue());
-	        out.writeDouble(timeArray.length);
-	        out.writeLongArray(timeArray);
-	        out.writeString(this.isNotEditable? "true" : "false");
-	    }
-
-	    
-	    public static final Parcelable.Creator<LogFilter> CREATOR = new Parcelable.Creator<LogFilter>() {
-	        public LogFilter createFromParcel(Parcel in) {
-	            return new LogFilter(in);
-	        }
-
-	        public LogFilter[] newArray(int size) {
-	            return new LogFilter[size];
-	        }
-	    };
-
-	    // example constructor that takes a Parcel and gives you an object populated with it's values
-	    private LogFilter(Parcel in) {
-	        //mData = in.readInt();
-	    	HashMap<String, ArrayList<String>> values = new HashMap<String, ArrayList<String>>();
-	    	in.readMap(values, ArrayList.class.getClassLoader());
-	    	
-	    	this.BSSIDs = values.get(BSSID_KEY);
-	    	this.ESSIDs = values.get(ESSID_KEY);
-	    	this.protocols = values.get(protocols);
-	    	
-	    	if(this.BSSIDs == null) this.BSSIDs = new ArrayList<String>();
-	    	if(this.ESSIDs == null) this.ESSIDs = new ArrayList<String>();
-	    	if(this.protocols == null) this.protocols = new ArrayList<String>();
-	    	
-	    	this.sorttype = SortType.values()[Math.min(in.readInt(), SortType.values().length)];
-	    	
-	    	int size = (int)in.readDouble();
-	    	long timeArray[] = new long[size];
-	    	in.readLongArray(timeArray);
-	    	
-	    	this.belowTimestamp = timeArray[1];
-	    	this.aboveTimestamp = timeArray[0];
-	    	
-	    	String bool = in.readString();
-	    	if(bool.equals("true")) this.isNotEditable = true;
-	    }
-	    
-	public boolean isNotEditable(){
+	public void clear() {
+		this.belowTimestamp = Long.MAX_VALUE;
+		this.aboveTimestamp = Long.MIN_VALUE;
+		this.sorttype = SortType.packet_timestamp;
+		this.BSSIDs = new ArrayList<String>();
+		this.ESSIDs = new ArrayList<String>();
+		this.protocols = new ArrayList<String>();
+	}
+
+	public int describeContents() {
+		return 0;
+	}
+
+	// write your object's data to the passed-in Parcel
+	public void writeToParcel(Parcel out, int flags) {
+		HashMap<String, ArrayList<String>> values = new HashMap<String, ArrayList<String>>();
+		if (this.BSSIDs != null && this.BSSIDs.size() > 0) {
+			values.put(BSSID_KEY, this.getBSSIDs());
+		}
+		if (this.ESSIDs != null && this.ESSIDs.size() > 0) {
+			values.put(ESSID_KEY, this.getESSIDs());
+		}
+		if (this.protocols != null && this.protocols.size() > 0) {
+			values.put(PROTOCOLS_KEY, this.getProtocols());
+		}
+		long timeArray[] = new long[] { this.aboveTimestamp, this.belowTimestamp };
+
+		out.writeMap(values);
+		out.writeInt(this.sorttype.getValue());
+		out.writeDouble(timeArray.length);
+		out.writeLongArray(timeArray);
+		out.writeString(this.isNotEditable ? "true" : "false");
+	}
+
+	public static final Parcelable.Creator<LogFilter> CREATOR = new Parcelable.Creator<LogFilter>() {
+		public LogFilter createFromParcel(Parcel in) {
+			return new LogFilter(in);
+		}
+
+		public LogFilter[] newArray(int size) {
+			return new LogFilter[size];
+		}
+	};
+
+	// example constructor that takes a Parcel and gives you an object populated
+	// with it's values
+	private LogFilter(Parcel in) {
+		// mData = in.readInt();
+		HashMap<String, ArrayList<String>> values = new HashMap<String, ArrayList<String>>();
+		in.readMap(values, ArrayList.class.getClassLoader());
+
+		this.BSSIDs = values.get(BSSID_KEY);
+		this.ESSIDs = values.get(ESSID_KEY);
+		this.protocols = values.get(protocols);
+
+		if (this.BSSIDs == null)
+			this.BSSIDs = new ArrayList<String>();
+		if (this.ESSIDs == null)
+			this.ESSIDs = new ArrayList<String>();
+		if (this.protocols == null)
+			this.protocols = new ArrayList<String>();
+
+		this.sorttype = SortType.values()[Math.min(in.readInt(), SortType.values().length)];
+
+		int size = (int) in.readDouble();
+		long timeArray[] = new long[size];
+		in.readLongArray(timeArray);
+
+		this.belowTimestamp = timeArray[1];
+		this.aboveTimestamp = timeArray[0];
+
+		String bool = in.readString();
+		if (bool.equals("true"))
+			this.isNotEditable = true;
+	}
+
+	public boolean isNotEditable() {
 		return this.isNotEditable;
 	}
-	public SortType getSorttype(){
+
+	public SortType getSorttype() {
 		return this.sorttype;
 	}
-	public ArrayList<String> getBSSIDs(){
+
+	public ArrayList<String> getBSSIDs() {
 		return this.BSSIDs;
 	}
-	public ArrayList<String> getESSIDs(){
+
+	public ArrayList<String> getESSIDs() {
 		return this.ESSIDs;
 	}
-	public ArrayList<String> getProtocols(){
+
+	public ArrayList<String> getProtocols() {
 		return this.protocols;
 	}
-	public void setIsNotEditable(boolean b){
+
+	public void setIsNotEditable(boolean b) {
 		this.isNotEditable = b;
 	}
-	
-	public long getBelowTimestamp(){
+
+	public long getBelowTimestamp() {
 		return this.belowTimestamp;
 	}
-	public long getAboveTimestamp(){
+
+	public long getAboveTimestamp() {
 		return this.aboveTimestamp;
 	}
-	public void setProtocols(ArrayList<String> protocols){
+
+	public void setProtocols(ArrayList<String> protocols) {
 		this.protocols = protocols;
 	}
-	public void setBSSIDs(ArrayList<String> bssids){
+
+	public void setBSSIDs(ArrayList<String> bssids) {
 		this.BSSIDs = bssids;
 	}
-	public void setESSIDs(ArrayList<String> essids){
+
+	public void setESSIDs(ArrayList<String> essids) {
 		this.ESSIDs = essids;
 	}
-	public void setAboveTimestamp(long timestamp){
+
+	public void setAboveTimestamp(long timestamp) {
 		this.aboveTimestamp = timestamp;
 	}
-	public void setBelowTimestamp(long timestamp){
+
+	public void setBelowTimestamp(long timestamp) {
 		this.belowTimestamp = timestamp;
 	}
-	public void setSorttype(SortType type){
+
+	public void setSorttype(SortType type) {
 		this.sorttype = type;
 	}
-	
-	
-	public String getBSSIDQueryStatement(String tablename, String key){
+
+	public String getBSSIDQueryStatement(String tablename, String key) {
 		return this.convertArrayListToQueryString(this.BSSIDs, tablename, key);
 	}
-	public String getESSIDQueryStatement(String tablename, String key){
-		return this.convertArrayListToQueryString(this.ESSIDs,tablename ,key);
-	}
-	public String getProtocolsQueryStatement(String tablename, String key){
-		return this.convertArrayListToQueryString(this.protocols,tablename, key);
-	}
-
-    public boolean isSet(){
-        boolean hasTime = this.hasATimestamp();
-        boolean hasBSSIDs = this.hasBSSIDs();
-        boolean hasESSIDs =this.hasESSIDs();
-        boolean hasProtocols = this.hasProtocols();
-
-        return hasBSSIDs || hasESSIDs || hasProtocols | hasTime;
-    }
-
-    public boolean hasBSSIDs(){
-        return  this.getBSSIDs().size() > 0;
-    }
-    public boolean hasESSIDs(){
-        return  this.getESSIDs().size() > 0;
-    }
-    public boolean hasProtocols(){
-        return  this.getProtocols().size() > 0;
-    }
-    public boolean hasAboveTimestamp(){
-        return this.aboveTimestamp != Long.MIN_VALUE;
-    }
-    public boolean hasBelowTimestamp(){
-        return this.belowTimestamp != Long.MAX_VALUE;
-    }
-    public boolean hasATimestamp(){
-        return this.hasBelowTimestamp()|| this.hasAboveTimestamp();
-    }
-	public String convertArrayListToQueryString(ArrayList<String> list, String table,  String key){
+
+	public String getESSIDQueryStatement(String tablename, String key) {
+		return this.convertArrayListToQueryString(this.ESSIDs, tablename, key);
+	}
+
+	public String getProtocolsQueryStatement(String tablename, String key) {
+		return this.convertArrayListToQueryString(this.protocols, tablename, key);
+	}
+
+	public boolean isSet() {
+		boolean hasTime = this.hasATimestamp();
+		boolean hasBSSIDs = this.hasBSSIDs();
+		boolean hasESSIDs = this.hasESSIDs();
+		boolean hasProtocols = this.hasProtocols();
+
+		return hasBSSIDs || hasESSIDs || hasProtocols | hasTime;
+	}
+
+	public boolean hasBSSIDs() {
+		return this.getBSSIDs().size() > 0;
+	}
+
+	public boolean hasESSIDs() {
+		return this.getESSIDs().size() > 0;
+	}
+
+	public boolean hasProtocols() {
+		return this.getProtocols().size() > 0;
+	}
+
+	public boolean hasAboveTimestamp() {
+		return this.aboveTimestamp != Long.MIN_VALUE;
+	}
+
+	public boolean hasBelowTimestamp() {
+		return this.belowTimestamp != Long.MAX_VALUE;
+	}
+
+	public boolean hasATimestamp() {
+		return this.hasBelowTimestamp() || this.hasAboveTimestamp();
+	}
+
+	public String convertArrayListToQueryString(ArrayList<String> list, String table, String key) {
 		String statement = "";
-		if (list == null) return statement;
+		if (list == null)
+			return statement;
 		statement = " ( ";
 
 		int i = 0, max = list.size();
-		for (String element : list){
+		for (String element : list) {
 			i++;
 			statement = statement + table + "." + key + " = " + "'" + element + "'";
-			if (i == max) continue;
-			statement = statement +" OR ";
+			if (i == max)
+				continue;
+			statement = statement + " OR ";
 		}
 		statement = statement + " ) ";
 
 		return statement;
 	}
-	
+
 }

+ 338 - 419
src/de/tudarmstadt/informatik/hostage/ui/MainActivity.java

@@ -1,10 +1,8 @@
 package de.tudarmstadt.informatik.hostage.ui;
 
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
 import java.util.ArrayList;
 import java.util.HashMap;
-import android.app.Activity;
+
 import android.app.ActivityManager;
 import android.app.ActivityManager.RunningServiceInfo;
 import android.content.BroadcastReceiver;
@@ -15,10 +13,9 @@ import android.content.IntentFilter;
 import android.content.ServiceConnection;
 import android.content.SharedPreferences;
 import android.os.Bundle;
-import android.os.Handler;
 import android.os.IBinder;
+import android.support.v4.app.FragmentActivity;
 import android.support.v4.content.LocalBroadcastManager;
-import android.util.Log;
 import android.view.GestureDetector;
 import android.view.GestureDetector.SimpleOnGestureListener;
 import android.view.Menu;
@@ -36,14 +33,10 @@ import android.widget.ListView;
 import android.widget.TextView;
 import android.widget.ToggleButton;
 import android.widget.ViewAnimator;
-import de.tudarmstadt.informatik.hostage.HoneyService;
-import de.tudarmstadt.informatik.hostage.HoneyService.LocalBinder;
+import de.tudarmstadt.informatik.hostage.Hostage;
+import de.tudarmstadt.informatik.hostage.Hostage.LocalBinder;
 import de.tudarmstadt.informatik.hostage.R;
-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.UglyDbHelper;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
 
 /**
  * MainActivity is the central activity for the GUI of the application.
@@ -58,15 +51,7 @@ import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
  * @author Lars Pandikow
  * @author Wulf Pfeiffer
  */
-public class MainActivity extends Activity implements Receiver {
-	/**
-	 * Flag for root acces. True if phone has root acces, else false.
-	 */
-	public static boolean isRooted = false;
-	/**
-	 * Flag for porthack. True if porthack is installed, else false.
-	 */
-	public static boolean porthackInstalled = false;
+public class MainActivity extends FragmentActivity {
 
 	/**
 	 * Integer representing a grey light.
@@ -85,10 +70,9 @@ public class MainActivity extends Activity implements Receiver {
 	 */
 	public static final int LIGHT_YELLOW = 0x04;
 
-	public LogResultReceiver logResultReceiver;
 	private SharedPreferences connectionInfo;
 
-	private HoneyService mService;
+	private Hostage mService;
 	private boolean serviceBound;
 
 	// variables for the swipe animation
@@ -102,80 +86,65 @@ public class MainActivity extends Activity implements Receiver {
 	private ListView listView;
 	private ListViewAdapter adapter;
 
-	private boolean isBssidSeen = false;
+	/**
+	 * Connection to bind the background service
+	 * 
+	 * @see Hostage
+	 */
+	private ServiceConnection mConnection = new ServiceConnection() {
+		/**
+		 * After the service is bound, check which has been clicked and start
+		 * it.
+		 * 
+		 * @see android.content.ServiceConnection#onServiceConnected(android.content.ComponentName)
+		 */
+		@Override
+		public void onServiceConnected(ComponentName name, IBinder service) {
+			mService = ((LocalBinder) service).getService();
+			serviceBound = true;
+			updateUI();
+		}
 
-	@Override
-	protected void onCreate(Bundle savedInstanceState) {
-		super.onCreate(savedInstanceState);
-		logResultReceiver = new LogResultReceiver(new Handler());
-		setContentView(R.layout.activity_main);
-		connectionInfo = getSharedPreferences(getString(R.string.connection_info), Context.MODE_PRIVATE);
-		
-		// Create dynamic view elements
-		initViewAnimator();
-		initListView();
-		// Initialize Class variables
-		checkRootAndPorthack();
-		startAndBind();
-	}
+		/**
+		 * After the service is unbound, delete reference.
+		 * 
+		 * @see android.content.ServiceConnection#onServiceDisconnected(android.content.ComponentName)
+		 */
+		@Override
+		public void onServiceDisconnected(ComponentName name) {
+			mService = null;
+			serviceBound = false;
+		}
 
-	@Override
-	public boolean onCreateOptionsMenu(Menu menu) {
-		getMenuInflater().inflate(R.menu.main, menu);
-		return true;
-	}
+	};
 
-	@Override
-	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:
+	/**
+	 * Receiver for custom broadcast.
+	 * 
+	 * @see #BROADCAST
+	 */
+	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
+		@Override
+		public void onReceive(Context context, Intent intent) {
+			// Update user interface.
+			updateUI();
+			updateConnectionInfText();
 		}
-		return super.onOptionsItemSelected(item);
-	}
-
-	@Override
-	protected void onStart() {
-		super.onStart();
-		// Register Broadcast Receiver
-		registerReceiver();
-		logResultReceiver.setReceiver(this);
-		// Bind service if running, else check for connection change and delete
-		// sessionData
-		if (isServiceRunning()) {
-			bindService(getServiceIntent(), mConnection, BIND_AUTO_CREATE);
-		} 
-		// Update UI
-		updateConnectionInfText();
-	}
+	};
 
-	@Override
-	protected void onStop() {
-		// Unregister Broadcast Receiver
-		unregisterReceiver();
-		logResultReceiver.setReceiver(null);
-		super.onStop();
-	}
+	SimpleOnGestureListener simpleOnGestureListener = new SimpleOnGestureListener() {
+		@Override
+		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
+			float sensitvity = 50;
+			if ((e1.getX() - e2.getX()) > sensitvity) {
+				swipeRightToLeft();
+			} else if ((e2.getX() - e1.getX()) > sensitvity) {
+				swipeLeftToRight();
+			}
 
-	@Override
-	protected void onDestroy() {
-		// Unbind running service
-		if(!mService.hasRunningListeners()){
-			stopAndUnbind();
+			return true;
 		}
-		super.onDestroy();
-	}
-
-	@Override
-	public void onReceiveResult(int resultCode, Bundle resultData) {
-		isBssidSeen = resultData.getBoolean("result");
-	}
+	};
 
 	/**
 	 * Called when User presses on/off button.
@@ -186,15 +155,15 @@ public class MainActivity extends Activity implements Receiver {
 		if (((ToggleButton) view).isChecked()) {
 			if (isParanoid()) {
 				String[] protocols = getResources().getStringArray(R.array.protocols);
-				for(String protocol: protocols){
-					mService.startListener(protocol);	
-				}						
+				for (String protocol: protocols) {
+					mService.startListener(protocol);
+				}
 			} else {
-				if(mService.isRunning("SMB")){
+				if (mService.isRunning("SMB")) {
 					mService.stopListener("SMB");
-				}else{
+				} else {
 					mService.startListener("SMB");
-				}	
+				}
 			}
 		} else {
 			mService.stopListeners();
@@ -202,6 +171,32 @@ public class MainActivity extends Activity implements Receiver {
 		}
 	}
 
+	@Override
+	public boolean onCreateOptionsMenu(Menu menu) {
+		getMenuInflater().inflate(R.menu.main, menu);
+		return true;
+	}
+
+	@Override
+	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);
+	}
+
+	@Override
+	public boolean onTouchEvent(MotionEvent event) {
+		return gestureDetector.onTouchEvent(event);
+	}
+
 	/**
 	 * Starts the ViewLog activity, when the Button is pressed.
 	 * 
@@ -217,126 +212,22 @@ public class MainActivity extends Activity implements Receiver {
 		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.
-	 */
-	private void startAndBind() {
-		startService(getServiceIntent());
-		bindService();
-	}
-
 	/**
 	 * Binds service to Activity
 	 * 
-	 * @see HoneyService
+	 * @see Hostage
 	 */
 	private void bindService() {
 		bindService(getServiceIntent(), mConnection, BIND_AUTO_CREATE);
 	}
 
-	/**
-	 * Stops service and unbinds it.
-	 * 
-	 * @see HoneyService
-	 */
-	private void stopAndUnbind() {
-		unbindService();
-		stopService(getServiceIntent());
-	}
-
-	/**
-	 * Unbinds service.
-	 * 
-	 * @see HoneyService
-	 */
-	private void unbindService() {
-		unbindService(mConnection);
-	}
-
-	/**
-	 * Connection to bind the background service
-	 * 
-	 * @see HoneyService
-	 */
-	private ServiceConnection mConnection = new ServiceConnection() {
-		/**
-		 * After the service is bound, check which has been clicked and start
-		 * it.
-		 * 
-		 * @see android.content.ServiceConnection#onServiceConnected(android.content.ComponentName)
-		 */
-		@Override
-		public void onServiceConnected(ComponentName name, IBinder service) {
-			mService = ((LocalBinder) service).getService();
-			serviceBound = true;
-			updateUI();
-		}
-
-		/**
-		 * After the service is unbound, delete reference.
-		 * 
-		 * @see android.content.ServiceConnection#onServiceDisconnected(android.content.ComponentName)
-		 */
-		@Override
-		public void onServiceDisconnected(ComponentName name) {
-			mService = null;
-			serviceBound = false;
-		}
-
-	};
-
-	/**
-	 * Checks if the phone ist rooted and if porthack is installed. Sets flags
-	 * {@link isRooted} and {@link porthackInstalled}
-	 */
-	private void checkRootAndPorthack() {
-		isRooted = false;
-		porthackInstalled = false;
-		Process p;
-		try {
-			String found = "Found";
-			String notFound = "Not found";
-			String command = "[ -f /data/local/p ] && echo " + found
-					+ " || echo " + notFound;
-			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;
-			}
-		} catch (Exception e) {
-			e.printStackTrace();
-		}
-		Log.i("MainAc", "Rooted: " + isRooted + " Porthack: "
-				+ porthackInstalled);
-	}
-
 	/**
 	 * Returns an intent to start HoneyService.
 	 * 
 	 * @return An Intent to start HoneyService
 	 */
 	private Intent getServiceIntent() {
-		return new Intent(this, HoneyService.class);
-	}
-
-	/**
-	 * Checks if user selected paranoid mode.
-	 * 
-	 * @return True when paranoid mode is selected, else returns false.
-	 */
-	private boolean isParanoid() {
-		return ((CheckBox) findViewById(R.id.checkBoxParanoid)).isChecked();
+		return new Intent(this, Hostage.class);
 	}
 
 	/**
@@ -366,226 +257,130 @@ public class MainActivity extends Activity implements Receiver {
 		listView.setOnItemClickListener(new OnItemClickListener() {
 
 			@Override
-			public void onItemClick(AdapterView<?> parent, View view,
-					int position, long id) {
-				String protocolName = (String) ((HashMap<?, ?>) adapter
-						.getItem(position)).get("protocol");
-				if(mService.isRunning(protocolName)){
+			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
+				String protocolName = (String) ((HashMap<?, ?>) adapter.getItem(position)).get("protocol");
+				if (mService.isRunning(protocolName)) {
 					mService.stopListener(protocolName);
-				}else{
+				} else {
 					mService.startListener(protocolName);
-				}				
+				}
 			}
 		});
 	}
-	
+
+	/**
+	 * Initializes variables for screen animation
+	 */
+	private void initViewAnimator() {
+		viewAnimator = (ViewAnimator) findViewById(R.id.viewAnimator);
+		gestureDetector = new GestureDetector(this, simpleOnGestureListener);
+
+		animFlipInLR = AnimationUtils.loadAnimation(this, R.anim.in_left_to_right);
+		animFlipOutLR = AnimationUtils.loadAnimation(this, R.anim.out_left_to_right);
+		animFlipInRL = AnimationUtils.loadAnimation(this, R.anim.in_right_to_left);
+		animFlipOutRL = AnimationUtils.loadAnimation(this, R.anim.out_right_to_left);
+	}
+
 	/**
-	 * Checks if a {@link HoneyService} instance is running.
+	 * Checks if user selected paranoid mode.
 	 * 
-	 * @return True if {@link HoneyService} is running, else false.
+	 * @return True when paranoid mode is selected, else returns false.
 	 */
-	private boolean isServiceRunning() {
-		ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
-		for (RunningServiceInfo service : manager
-				.getRunningServices(Integer.MAX_VALUE)) {
-			if (service.service.getClassName().equals(
-					HoneyService.class.getName())) {
-				return true;
-			}
-		}
-		return false;
+	private boolean isParanoid() {
+		return ((CheckBox) findViewById(R.id.checkBoxParanoid)).isChecked();
 	}
-	
+
 	/**
-	 * Checks if a {@link HoneyService} instance is running.
+	 * Checks if a {@link Hostage} instance is running.
 	 * 
-	 * @return True if {@link HoneyService} is running, else false.
+	 * @return True if {@link Hostage} is running, else false.
 	 */
 	private boolean isServiceBound() {
 		return serviceBound;
 	}
 
 	/**
-	 * Register broadcast receiver for custom broadcast.
+	 * Checks if a {@link Hostage} instance is running.
 	 * 
-	 * @see #BROADCAST
+	 * @return True if {@link Hostage} is running, else false.
 	 */
-	private void registerReceiver() {
-		LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
-				new IntentFilter(getString(R.string.broadcast)));
+	private boolean isServiceRunning() {
+		ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
+		for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
+			if (service.service.getClassName().equals(Hostage.class.getName())) {
+				return true;
+			}
+		}
+		return false;
 	}
 
 	/**
-	 * Unregisters broadcast receiver for custom broadcast.
+	 * Register broadcast receiver for custom broadcast.
 	 * 
 	 * @see #BROADCAST
 	 */
-	private void unregisterReceiver() {
-		LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
+	private void registerReceiver() {
+		LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, new IntentFilter(getString(R.string.broadcast)));
 	}
 
 	/**
-	 * Receiver for custom broadcast.
-	 * 
-	 * @see #BROADCAST
-	 */
-	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
-		@Override
-		public void onReceive(Context context, Intent intent) {
-			// Update user interface.
-			updateUI();
-			updateConnectionInfText();
-		}
-	};
+	 * 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() {
+		startService(getServiceIntent());
+		bindService();
+	}
 
 	/**
-	 * Updates Information shown by the GUI.
+	 * Stops service and unbinds it.
+	 * 
+	 * @see Hostage
 	 */
-	private void updateUI() {
-		boolean activeListeners = false;
-		boolean activeHandlers = 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)) {
-			if(isServiceBound()){
-				// Check if protocol is active
-				if (mService.isRunning(protocol)) {
-					activeListeners = true;
-					int handlerCount = mService.getNumberOfActiveConnections(protocol);
-					// Check if attacks have been recorded in this session.
-					if (handlerCount > 0) {
-						activeHandlers = true;
-						updateProtocolLight(LIGHT_RED, protocol);
-						updateProtocolConnections(handlerCount, protocol);
-					} else {
-						// Check if the bssid of the wireless network has already
-						// been recorded as infected.
-						Logger.isBssidSeen(getApplicationContext(), protocol,
-								HelperUtils.getBSSID(getApplicationContext()),
-								logResultReceiver);
-						UglyDbHelper dbh = new UglyDbHelper(this);
-						if (dbh.bssidSeen(protocol, connectionInfo.getString(getString(R.string.connection_info_bssid), null))) {
-							updateProtocolLight(LIGHT_YELLOW, protocol);
-							yellowLight = true;
-						} else {
-							updateProtocolLight(LIGHT_GREEN, protocol);
-						}
-						updateProtocolConnections(0, protocol);
-					}
-				} else {
-					updateProtocolLight(LIGHT_GREY, protocol);
-				}
-			}else{
-				updateProtocolLight(LIGHT_GREY, protocol);
-			}				
-		}
+	private void stopAndUnbind() {
+		unbindService();
+		stopService(getServiceIntent());
+	}
 
-		// Update the big attack indicator.
-		if (activeListeners) {
-			if (activeHandlers) {
-				updateStatusLight(LIGHT_RED);
-			} else {
-				if (yellowLight) {
-					updateStatusLight(LIGHT_YELLOW);
-				} else {
-					updateStatusLight(LIGHT_GREEN);
-				}
-			}
-			((ToggleButton) findViewById(R.id.toggleButtonOnOff))
-					.setChecked(true);
-			findViewById(R.id.checkBoxParanoid).setEnabled(false);
-		} else {
-			updateStatusLight(LIGHT_GREY);
-			((ToggleButton) findViewById(R.id.toggleButtonOnOff))
-					.setChecked(false);
-			findViewById(R.id.checkBoxParanoid).setEnabled(true);
+	/**
+	 * Called when a swipe to the Right is registered.
+	 */
+	private void swipeLeftToRight() {
+		if (viewAnimator.getDisplayedChild() == 1) {
+			viewAnimator.setInAnimation(animFlipInLR);
+			viewAnimator.setOutAnimation(animFlipOutLR);
+			viewAnimator.setDisplayedChild(0);
 		}
 	}
 
 	/**
-	 * Sets the big light indicator.
-	 * 
-	 * @param light
-	 *            Integer code to set the light color.
-	 * @see #LIGHT_GREY
-	 * @see #LIGHT_GREEN
-	 * @see #LIGHT_RED
-	 * @see #LIGHT_YELLOW
+	 * Called when a swipe to the Left is registered.
 	 */
-	private void updateStatusLight(int light) {
-		switch (light) {
-		case LIGHT_GREY:
-			((ImageView) findViewById(R.id.imageViewLight))
-					.setImageResource(R.drawable.light_grey_large);
-			break;
-		case LIGHT_GREEN:
-			((ImageView) findViewById(R.id.imageViewLight))
-					.setImageResource(R.drawable.light_green_large);
-			break;
-		case LIGHT_RED:
-			((ImageView) findViewById(R.id.imageViewLight))
-					.setImageResource(R.drawable.light_red_large);
-			break;
-		case LIGHT_YELLOW:
-			((ImageView) findViewById(R.id.imageViewLight))
-					.setImageResource(R.drawable.light_yellow_large);
-			break;
+	private void swipeRightToLeft() {
+		if (viewAnimator.getDisplayedChild() == 0) {
+			viewAnimator.setInAnimation(animFlipInRL);
+			viewAnimator.setOutAnimation(animFlipOutRL);
+			viewAnimator.setDisplayedChild(1);
 		}
 	}
 
 	/**
-	 * Sets the light indicator for a given protocol.
+	 * Unbinds service.
 	 * 
-	 * @param light
-	 *            Integer code to set the light color.
-	 * @param protocolName
-	 *            Name of the protocol which should be updated.
+	 * @see Hostage
 	 */
-	private void updateProtocolLight(int light, String protocolName) {
-		for (int i = 0; i < adapter.getCount(); ++i) {
-			HashMap<String, String> d = (HashMap<String, String>) adapter
-					.getItem(i);
-			if (d.get("protocol").equals(protocolName)) {
-				switch (light) {
-				case LIGHT_GREY:
-					d.put("light", String.valueOf(R.drawable.light_grey));
-					d.put("connections", "-");
-					break;
-				case LIGHT_GREEN:
-					d.put("light", String.valueOf(R.drawable.light_green));
-					break;
-				case LIGHT_RED:
-					d.put("light", String.valueOf(R.drawable.light_red));
-					break;
-				case LIGHT_YELLOW:
-					d.put("light", String.valueOf(R.drawable.light_yellow));
-					break;
-				}
-			}
-		}
-		adapter.notifyDataSetChanged();
+	private void unbindService() {
+		unbindService(mConnection);
 	}
 
 	/**
-	 * Sets the connections count for a given protocol.
+	 * Unregisters broadcast receiver for custom broadcast.
 	 * 
-	 * @param connections
-	 *            New value for recorded connections.
-	 * @param protocolName
-	 *            Name of the protocol which should be updated.
+	 * @see #BROADCAST
 	 */
-	private void updateProtocolConnections(int connections, String protocolName) {
-		for (int i = 0; i < adapter.getCount(); ++i) {
-			HashMap<String, String> d = ((HashMap<String, String>) adapter
-					.getItem(i));
-			if (d.get("protocol").equals(protocolName)) {
-				d.put("connections", String.valueOf(connections));
-			}
-		}
-		adapter.notifyDataSetChanged();
+	private void unregisterReceiver() {
+		LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
 	}
 
 	/**
@@ -597,7 +392,7 @@ public class MainActivity extends Activity implements Receiver {
 		TextView internalIPView = (TextView) findViewById(R.id.textViewInternalIPValue);
 		TextView externalIPView = (TextView) findViewById(R.id.textViewExternalIPValue);
 
-//		externalIPView.setText("Loading...");
+		// externalIPView.setText("Loading...");
 
 		// Get connection information
 		String ssid = connectionInfo.getString(getString(R.string.connection_info_ssid), null);
@@ -620,72 +415,196 @@ public class MainActivity extends Activity implements Receiver {
 			internalIPView.setText(internalIP);
 		else
 			internalIPView.setText("-");
-		
+
 		if (externalIP != null)
 			externalIPView.setText(externalIP);
 		else
 			externalIPView.setText("-");
 	}
 
-	/* ############# Help functions for animation ################## */
-
-	@Override
-	public boolean onTouchEvent(MotionEvent event) {
-		return gestureDetector.onTouchEvent(event);
+	/**
+	 * 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.
+	 */
+	private void updateProtocolConnections(int connections, String protocolName) {
+		for (int i = 0; i < adapter.getCount(); ++i) {
+			HashMap<String, String> d = (HashMap<String, String>) adapter.getItem(i);
+			if (d.get("protocol").equals(protocolName)) {
+				d.put("connections", String.valueOf(connections));
+			}
+		}
+		adapter.notifyDataSetChanged();
 	}
 
 	/**
-	 * Initializes variables for screen animation
+	 * 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.
 	 */
-	private void initViewAnimator() {
-		viewAnimator = (ViewAnimator) findViewById(R.id.viewAnimator);
-		gestureDetector = new GestureDetector(this, simpleOnGestureListener);
-
-		animFlipInLR = AnimationUtils.loadAnimation(this,
-				R.anim.in_left_to_right);
-		animFlipOutLR = AnimationUtils.loadAnimation(this,
-				R.anim.out_left_to_right);
-		animFlipInRL = AnimationUtils.loadAnimation(this,
-				R.anim.in_right_to_left);
-		animFlipOutRL = AnimationUtils.loadAnimation(this,
-				R.anim.out_right_to_left);
+	private void updateProtocolLight(int light, String protocolName) {
+		for (int i = 0; i < adapter.getCount(); ++i) {
+			HashMap<String, String> d = (HashMap<String, String>) adapter.getItem(i);
+			if (d.get("protocol").equals(protocolName)) {
+				switch (light) {
+				case LIGHT_GREY:
+					d.put("light", String.valueOf(R.drawable.light_grey));
+					d.put("connections", "-");
+					break;
+				case LIGHT_GREEN:
+					d.put("light", String.valueOf(R.drawable.light_green));
+					break;
+				case LIGHT_RED:
+					d.put("light", String.valueOf(R.drawable.light_red));
+					break;
+				case LIGHT_YELLOW:
+					d.put("light", String.valueOf(R.drawable.light_yellow));
+					break;
+				}
+			}
+		}
+		adapter.notifyDataSetChanged();
 	}
 
 	/**
-	 * Called when a swipe to the Left is registered.
+	 * Sets the big light indicator.
+	 * 
+	 * @param light
+	 *            Integer code to set the light color.
+	 * @see #LIGHT_GREY
+	 * @see #LIGHT_GREEN
+	 * @see #LIGHT_RED
+	 * @see #LIGHT_YELLOW
 	 */
-	private void swipeRightToLeft() {
-		if (viewAnimator.getDisplayedChild() == 0) {
-			viewAnimator.setInAnimation(animFlipInRL);
-			viewAnimator.setOutAnimation(animFlipOutRL);
-			viewAnimator.setDisplayedChild(1);
+	private void updateStatusLight(int light) {
+		switch (light) {
+		case LIGHT_GREY:
+			((ImageView) findViewById(R.id.imageViewLight)).setImageResource(R.drawable.light_grey_large);
+			break;
+		case LIGHT_GREEN:
+			((ImageView) findViewById(R.id.imageViewLight)).setImageResource(R.drawable.light_green_large);
+			break;
+		case LIGHT_RED:
+			((ImageView) findViewById(R.id.imageViewLight)).setImageResource(R.drawable.light_red_large);
+			break;
+		case LIGHT_YELLOW:
+			((ImageView) findViewById(R.id.imageViewLight)).setImageResource(R.drawable.light_yellow_large);
+			break;
 		}
 	}
 
+	/* ############# Help functions for animation ################## */
+
 	/**
-	 * Called when a swipe to the Right is registered.
+	 * Updates Information shown by the GUI.
 	 */
-	private void swipeLeftToRight() {
-		if (viewAnimator.getDisplayedChild() == 1) {
-			viewAnimator.setInAnimation(animFlipInLR);
-			viewAnimator.setOutAnimation(animFlipOutLR);
-			viewAnimator.setDisplayedChild(0);
+	private void updateUI() {
+		boolean activeListeners = false;
+		boolean activeHandlers = 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)) {
+			if (isServiceBound()) {
+				// Check if protocol is active
+				if (mService.isRunning(protocol)) {
+					activeListeners = true;
+					int handlerCount = mService.getNumberOfActiveConnections(protocol);
+					// Check if attacks have been recorded in this session.
+					if (handlerCount > 0) {
+						activeHandlers = true;
+						updateProtocolLight(LIGHT_RED, protocol);
+						updateProtocolConnections(handlerCount, protocol);
+					} else {
+						// Check if the bssid of the wireless network has
+						// already
+						// been recorded as infected.
+						HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
+						if (dbh.bssidSeen(protocol, connectionInfo.getString(getString(R.string.connection_info_bssid), null))) {
+							updateProtocolLight(LIGHT_YELLOW, protocol);
+							yellowLight = true;
+						} else {
+							updateProtocolLight(LIGHT_GREEN, protocol);
+						}
+						updateProtocolConnections(0, protocol);
+					}
+				} else {
+					updateProtocolLight(LIGHT_GREY, protocol);
+				}
+			} else {
+				updateProtocolLight(LIGHT_GREY, protocol);
+			}
 		}
-	}
 
-	SimpleOnGestureListener simpleOnGestureListener = new SimpleOnGestureListener() {
-		@Override
-		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
-				float velocityY) {
-			float sensitvity = 50;
-			if ((e1.getX() - e2.getX()) > sensitvity) {
-				swipeRightToLeft();
-			} else if ((e2.getX() - e1.getX()) > sensitvity) {
-				swipeLeftToRight();
+		// Update the big attack indicator.
+		if (activeListeners) {
+			if (activeHandlers) {
+				updateStatusLight(LIGHT_RED);
+			} else {
+				if (yellowLight) {
+					updateStatusLight(LIGHT_YELLOW);
+				} else {
+					updateStatusLight(LIGHT_GREEN);
+				}
 			}
+			((ToggleButton) findViewById(R.id.toggleButtonOnOff)).setChecked(true);
+			findViewById(R.id.checkBoxParanoid).setEnabled(false);
+		} else {
+			updateStatusLight(LIGHT_GREY);
+			((ToggleButton) findViewById(R.id.toggleButtonOnOff)).setChecked(false);
+			findViewById(R.id.checkBoxParanoid).setEnabled(true);
+		}
+	}
 
-			return true;
+	@Override
+	protected void onCreate(Bundle savedInstanceState) {
+		super.onCreate(savedInstanceState);
+		setContentView(R.layout.activity_main);
+		connectionInfo = getSharedPreferences(getString(R.string.connection_info), Context.MODE_PRIVATE);
+
+		// Create dynamic view elements
+		initViewAnimator();
+		initListView();
+		// Initialize Class variables
+		startAndBind();
+	}
+
+	@Override
+	protected void onDestroy() {
+		// Unbind running service
+		if (!mService.hasRunningListeners()) {
+			stopAndUnbind();
 		}
-	};
-	
+		super.onDestroy();
+	}
+
+	@Override
+	protected void onStart() {
+		super.onStart();
+		// Register Broadcast Receiver
+		registerReceiver();
+		// Bind service if running, else check for connection change and delete
+		// sessionData
+		if (isServiceRunning()) {
+			bindService(getServiceIntent(), mConnection, BIND_AUTO_CREATE);
+		}
+		// Update UI
+		updateConnectionInfText();
+	}
+
+	@Override
+	protected void onStop() {
+		// Unregister Broadcast Receiver
+		unregisterReceiver();
+		super.onStop();
+	}
+
 }

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

@@ -1,99 +1,96 @@
-package de.tudarmstadt.informatik.hostage.ui;
-
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Random;
-
-import android.app.Activity;
-import android.content.Intent;
-import android.os.Bundle;
-import android.view.Menu;
-import android.view.View;
-import android.widget.TextView;
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
-import de.tudarmstadt.informatik.hostage.sync.BluetoothSync;
-import de.tudarmstadt.informatik.hostage.sync.NFCSync;
-
-public class PlayGroundActivity extends Activity {
-
-	BluetoothSync bs;
-
-	public void createNetworkData(View view) {
-		Random rnd = new Random();
-		ArrayList<HashMap<String, Object>> fakeNetInfo = new ArrayList<HashMap<String, Object>>();
-		for (int i = 0; i < 25; i++) {
-			HashMap<String, Object> network = new HashMap<String, Object>();
-			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);
-		}
-
-		setNetworkInfoText();
-		new UglyDbHelper(this).updateNetworkInformation(fakeNetInfo);
-	}
-
-	@Override
-	public boolean onCreateOptionsMenu(Menu menu) {
-		getMenuInflater().inflate(R.menu.main, menu);
-		return true;
-	}
-
-	public void startNFC(View view) {
-		startActivity(new Intent(this, NFCSync.class));
-	}
-
-	public void syncData(View view) {
-		bs.syncData();
-	}
-
-	private String createRandomBSSID() {
-		Random rnd = new Random();
-		char[] symbols = new char[16];
-		for (int idx = 0; idx < 10; ++idx)
-			symbols[idx] = (char) ('0' + idx);
-		for (int idx = 10; idx < 16; ++idx)
-			symbols[idx] = (char) ('a' + idx - 10);
-
-		char[] buf = new char[17];
-		for (int i = 0; i < 18; i += 3) {
-			buf[i] = symbols[rnd.nextInt(symbols.length)];
-			buf[i + 1] = symbols[rnd.nextInt(symbols.length)];
-			if (i < 15) {
-				buf[i + 2] = ':';
-			}
-		}
-		return new String(buf);
-	}
-
-	private void setNetworkInfoText() {
-		UglyDbHelper dbh = new UglyDbHelper(this);
-		TextView bssids = (TextView) findViewById(R.id.textView1);
-		String text = "";
-		ArrayList<HashMap<String, Object>> netInfo = dbh
-				.getNetworkInformation();
-		for (HashMap<String, Object> network : netInfo) {
-			text = text + (String) network.get(UglyDbHelper.KEY_BSSID) + "\n"
-					+ (String) network.get(UglyDbHelper.KEY_SSID) + "\n"
-					+ network.get(UglyDbHelper.KEY_LATITUDE) + "\n"
-					+ network.get(UglyDbHelper.KEY_LONGITUDE) + "\n"
-					+ network.get(UglyDbHelper.KEY_ACCURACY) + "\n"
-					+ network.get(UglyDbHelper.KEY_TIME) + "\n\n";
-		}
-		bssids.setText(text);
-	}
-
-	@Override
-	protected void onCreate(Bundle savedInstanceState) {
-		super.onCreate(savedInstanceState);
-		setContentView(R.layout.activity_playground);
-		bs = new BluetoothSync(this);
-		setNetworkInfoText();
-	}
+package de.tudarmstadt.informatik.hostage.ui;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Random;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.os.Bundle;
+import android.view.Menu;
+import android.view.View;
+import android.widget.TextView;
+import de.tudarmstadt.informatik.hostage.R;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
+import de.tudarmstadt.informatik.hostage.sync.BluetoothSync;
+import de.tudarmstadt.informatik.hostage.sync.NFCSync;
+
+public class PlayGroundActivity extends Activity {
+
+
+	public void createNetworkData(View view) {
+		Random rnd = new Random();
+		ArrayList<HashMap<String, Object>> fakeNetInfo = new ArrayList<HashMap<String, Object>>();
+		for (int i = 0; i < 25; i++) {
+			HashMap<String, Object> network = new HashMap<String, Object>();
+			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_BSSID, createRandomBSSID());
+			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_SSID, new BigInteger(130, rnd).toString(32));
+			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_LATITUDE, rnd.nextDouble() * 360);
+			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_LONGITUDE, rnd.nextDouble() * 360);
+			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_ACCURACY, rnd.nextFloat());
+			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP, System.currentTimeMillis());
+			fakeNetInfo.add(network);
+		}
+
+		setNetworkInfoText();
+		new HostageDBOpenHelper(this).updateNetworkInformation(fakeNetInfo);
+	}
+
+	@Override
+	public boolean onCreateOptionsMenu(Menu menu) {
+		getMenuInflater().inflate(R.menu.main, menu);
+		return true;
+	}
+
+	public void startNFC(View view) {
+		startActivity(new Intent(this, NFCSync.class));
+	}
+
+	public void syncData(View view) {
+		startActivity(new Intent(this, BluetoothSync.class));
+	}
+
+	private String createRandomBSSID() {
+		Random rnd = new Random();
+		char[] symbols = new char[16];
+		for (int idx = 0; idx < 10; ++idx)
+			symbols[idx] = (char) ('0' + idx);
+		for (int idx = 10; idx < 16; ++idx)
+			symbols[idx] = (char) ('a' + idx - 10);
+
+		char[] buf = new char[17];
+		for (int i = 0; i < 18; i += 3) {
+			buf[i] = symbols[rnd.nextInt(symbols.length)];
+			buf[i + 1] = symbols[rnd.nextInt(symbols.length)];
+			if (i < 15) {
+				buf[i + 2] = ':';
+			}
+		}
+		return new String(buf);
+	}
+
+	private void setNetworkInfoText() {
+		HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
+		TextView bssids = (TextView) findViewById(R.id.textView1);
+		String text = "";
+		ArrayList<HashMap<String, Object>> netInfo = dbh.getNetworkInformation();
+		for (HashMap<String, Object> network : netInfo) {
+			text = text + (String) network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_BSSID) + "\n"
+					+ (String) network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_SSID) + "\n"
+					+ network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_LATITUDE) + "\n"
+					+ network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_LONGITUDE) + "\n"
+					+ network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_ACCURACY) + "\n"
+					+ network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP) + "\n\n";
+		}
+		bssids.setText(text);
+	}
+
+	@Override
+	protected void onCreate(Bundle savedInstanceState) {
+		super.onCreate(savedInstanceState);
+		setContentView(R.layout.activity_playground);
+		setNetworkInfoText();
+	}
 }

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

@@ -5,7 +5,7 @@ import android.os.Bundle;
 import android.widget.ScrollView;
 import android.widget.TextView;
 import de.tudarmstadt.informatik.hostage.logging.Record;
-import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
 
 /**
  * Creates a simple log view. Shows the Information for every attack. The format
@@ -19,7 +19,7 @@ public class ViewLogTable extends Activity {
 	@Override
 	protected void onCreate(Bundle savedInstanceState) {
 		super.onCreate(savedInstanceState);
-		UglyDbHelper dbh = new UglyDbHelper(getBaseContext());
+		HostageDBOpenHelper dbh = new HostageDBOpenHelper(getBaseContext());
 		StringBuffer log = new StringBuffer();
 		// Create a log entry for every attack in the Database
 		for (Record record : dbh.getAllRecords()) {

+ 122 - 165
src/de/tudarmstadt/informatik/hostage/ui2/activity/MainActivity.java

@@ -1,5 +1,8 @@
 package de.tudarmstadt.informatik.hostage.ui2.activity;
 
+import java.util.ArrayList;
+import java.util.HashMap;
+
 import android.app.ActionBar;
 import android.app.Activity;
 import android.app.ActivityManager;
@@ -27,14 +30,7 @@ import android.view.MenuItem;
 import android.view.View;
 import android.widget.AdapterView;
 import android.widget.ListView;
-
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import de.tudarmstadt.informatik.hostage.HoneyHandler;
-import de.tudarmstadt.informatik.hostage.HoneyService;
+import de.tudarmstadt.informatik.hostage.Hostage;
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.ui.LogFilter;
 import de.tudarmstadt.informatik.hostage.ui2.adapter.DrawerListAdapter;
@@ -57,16 +53,12 @@ import de.tudarmstadt.informatik.hostage.ui2.model.DrawerListItem;
 public class MainActivity extends Activity {
 	public static volatile Context context;
 
-	public static boolean isRooted = false;
-
-	public static boolean porthackInstalled = false;
-
 	/** singleton instance of the MainActivity **/
 	private static MainActivity sInstance = null;
 
 	public Fragment mDisplayedFragment;
 
-	public HoneyService mHoneyService;
+	public Hostage mHoneyService;
 
 	private DrawerLayout mDrawerLayout;
 
@@ -78,7 +70,7 @@ public class MainActivity extends Activity {
 
 	private CharSequence mTitle;
 
-    private MainMenuItem mSelectedMenuItem = null;
+	private MainMenuItem mSelectedMenuItem = null;
 
 	private ArrayList<DrawerListItem> mDrawerItems;
 
@@ -86,25 +78,26 @@ public class MainActivity extends Activity {
 
 	/**
 	 * Connection to bind the background service
-	 *
+	 * 
 	 * @see HoneyService
 	 */
 	private ServiceConnection mConnection = new ServiceConnection() {
 		/**
 		 * After the service is bound, check which has been clicked and start
 		 * it.
-		 *
-		 * @see android.content.ServiceConnection#onServiceConnected(android.content.ComponentName, android.os.IBinder)
+		 * 
+		 * @see android.content.ServiceConnection#onServiceConnected(android.content.ComponentName,
+		 *      android.os.IBinder)
 		 */
 		@Override
 		public void onServiceConnected(ComponentName name, IBinder service) {
-			mHoneyService = ((HoneyService.LocalBinder) service).getService();
+			mHoneyService = ((Hostage.LocalBinder) service).getService();
 			mServiceBound = true;
 		}
 
 		/**
 		 * After the service is unbound, delete reference.
-		 *
+		 * 
 		 * @see android.content.ServiceConnection#onServiceDisconnected(android.content.ComponentName)
 		 */
 		@Override
@@ -121,28 +114,35 @@ public class MainActivity extends Activity {
 
 	/**
 	 * Retrieve the singleton latest instance of the activity
+	 * 
 	 * @return MainActivity - the singleton instance
 	 */
-	public static MainActivity getInstance(){
-		assert(sInstance != null);
+	public static MainActivity getInstance() {
+		assert (sInstance != null);
 		return sInstance;
 	}
 
-	public static Context getContext(){
+	public static Context getContext() {
 		return MainActivity.context;
 	}
 
 	@Override
-	public void onStart(){
+	public void onStart() {
 		super.onStart();
 
 		registerReceiver();
 
-		if(isServiceRunning()){
+		if (isServiceRunning()) {
 			this.bindService();
 		}
 	}
 
+	@Override
+	public void onStop() {
+		this.unbindService();
+		super.onStop();
+	}
+
 	@Override
 	protected void onCreate(Bundle savedInstanceState) {
 		super.onCreate(savedInstanceState);
@@ -156,14 +156,12 @@ public class MainActivity extends Activity {
 		ThreatIndicatorGLRenderer.assets = getAssets();
 		ThreatIndicatorGLRenderer.setThreatLevel(ThreatIndicatorGLRenderer.ThreatLevel.NOT_MONITORING);
 		// set background color
-		TypedArray arr = getTheme().obtainStyledAttributes(
-				new int[] { android.R.color.background_light });
+		TypedArray arr = getTheme().obtainStyledAttributes(new int[] { android.R.color.background_light });
 		ThreatIndicatorGLRenderer.setBackgroundColor(arr.getColor(0, 0xFFFFFF));
 		arr.recycle();
 
 		ActionBar actionBar = getActionBar();
-		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE
-				| ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_HOME_AS_UP);
+		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_HOME_AS_UP);
 
 		mTitle = mDrawerTitle = getTitle();
 		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
@@ -175,13 +173,9 @@ public class MainActivity extends Activity {
 		mDrawerItems.add(new DrawerListItem(R.string.drawer_records, R.drawable.ic_menu_records));
 		mDrawerItems.add(new DrawerListItem(R.string.drawer_statistics, R.drawable.ic_menu_stats));
 		mDrawerItems.add(new DrawerListItem(R.string.drawer_services, R.drawable.ic_menu_set_as));
-		mDrawerItems.add(
-				new DrawerListItem(R.string.drawer_profile_manager, R.drawable.ic_menu_allfriends));
-		mDrawerItems.add(
-				new DrawerListItem(R.string.drawer_settings, R.drawable.ic_menu_preferences));
-		mDrawerItems.add(
-				new DrawerListItem(R.string.drawer_app_info, R.drawable.ic_menu_info_details));
-
+		mDrawerItems.add(new DrawerListItem(R.string.drawer_profile_manager, R.drawable.ic_menu_allfriends));
+		mDrawerItems.add(new DrawerListItem(R.string.drawer_settings, R.drawable.ic_menu_preferences));
+		mDrawerItems.add(new DrawerListItem(R.string.drawer_app_info, R.drawable.ic_menu_info_details));
 
 		DrawerListAdapter listAdapter = new DrawerListAdapter(this, mDrawerItems);
 
@@ -192,26 +186,29 @@ public class MainActivity extends Activity {
 		getActionBar().setHomeButtonEnabled(true);
 		getActionBar().setDisplayShowHomeEnabled(true);
 
-		mDrawerToggle = new ActionBarDrawerToggle(
-				this,                  /* host Activity */
-				mDrawerLayout,         /* DrawerLayout object */
-				R.drawable.ic_navigation_drawer,  /* nav drawer image to replace 'Up' caret */
-				R.string.drawer_open,  /* "open drawer" description for accessibility */
-				R.string.drawer_close  /* "close drawer" description for accessibility */
+		mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
+		mDrawerLayout, /* DrawerLayout object */
+		R.drawable.ic_navigation_drawer, /*
+										 * nav drawer image to replace 'Up'
+										 * caret
+										 */
+		R.string.drawer_open, /* "open drawer" description for accessibility */
+		R.string.drawer_close /* "close drawer" description for accessibility */
 		) {
 			public void onDrawerClosed(View view) {
 				getActionBar().setTitle(mTitle);
-				invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
+				invalidateOptionsMenu(); // creates call to
+											// onPrepareOptionsMenu()
 			}
 
 			public void onDrawerOpened(View drawerView) {
 				getActionBar().setTitle(mDrawerTitle);
-				invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
+				invalidateOptionsMenu(); // creates call to
+											// onPrepareOptionsMenu()
 			}
 		};
 		mDrawerLayout.setDrawerListener(mDrawerToggle);
 
-		checkRootAndPorthack();
 		startAndBind();
 
 		if (savedInstanceState == null) {
@@ -221,8 +218,7 @@ public class MainActivity extends Activity {
 	}
 
 	private void registerReceiver() {
-		LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
-				new IntentFilter(getString(R.string.broadcast)));
+		LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, new IntentFilter(getString(R.string.broadcast)));
 	}
 
 	private void unregisterReceiver() {
@@ -237,20 +233,21 @@ public class MainActivity extends Activity {
 			String sender = extras.getString("SENDER");
 			String[] values = extras.getStringArray("VALUES");
 
-			if(sender.equals(HoneyHandler.class.getName()) && values[0].equals(getString(R.string.broadcast_started))) {
+			if (sender.equals(Hostage.class.getName()) && values[0].equals(getString(R.string.broadcast_started))) {
 				mAttacksOnProtocol.put(values[1], true);
 			}
 		}
 	};
 
-	public boolean hasProtocolAttacks(String protocol){
-		if(!mAttacksOnProtocol.containsKey(protocol)) return false;
+	public boolean hasProtocolAttacks(String protocol) {
+		if (!mAttacksOnProtocol.containsKey(protocol))
+			return false;
 
 		return mAttacksOnProtocol.get(protocol);
 	}
 
 	public void startAndBind() {
-		if(!isServiceRunning()){
+		if (!isServiceRunning()) {
 			startService(getServiceIntent());
 		}
 
@@ -258,7 +255,7 @@ public class MainActivity extends Activity {
 	}
 
 	public void stopAndUnbind() {
-		if(mHoneyService != null){
+		if (mHoneyService != null) {
 			unbindService();
 		}
 
@@ -268,7 +265,7 @@ public class MainActivity extends Activity {
 	public void unbindService() {
 		try {
 			unbindService(mConnection);
-		} catch(IllegalArgumentException ex){
+		} catch (IllegalArgumentException ex) {
 			// somehow already unbound.
 		}
 	}
@@ -276,7 +273,7 @@ public class MainActivity extends Activity {
 	public void bindService() {
 		mAttacksOnProtocol.clear();
 		bindService(getServiceIntent(), mConnection, BIND_AUTO_CREATE);
-		//mServiceBound = true;
+		// mServiceBound = true;
 	}
 
 	@Override
@@ -286,19 +283,19 @@ public class MainActivity extends Activity {
 		unregisterReceiver();
 
 		// Unbind running service
-		if(!mHoneyService.hasRunningListeners()){
+		if (!mHoneyService.hasRunningListeners()) {
 			stopAndUnbind();
 		}
 	}
 
 	@Override
-	protected void onResume(){
+	protected void onResume() {
 		super.onResume();
 
 		String action = getIntent().getAction();
 
-		if(action != null && action.equals("SHOW_HOME")){
-			if(this.mDisplayedFragment != null && !this.mDisplayedFragment.getClass().equals(HomeFragment.class)){
+		if (action != null && action.equals("SHOW_HOME")) {
+			if (this.mDisplayedFragment != null && !this.mDisplayedFragment.getClass().equals(HomeFragment.class)) {
 				getFragmentManager().popBackStackImmediate(HomeFragment.class.getName(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
 				displayView(MainMenuItem.HOME.getValue());
 
@@ -314,9 +311,9 @@ public class MainActivity extends Activity {
 			return true;
 		}
 
-		if(item.getItemId() == android.R.id.home){
-			if(!mDrawerToggle.isDrawerIndicatorEnabled()){
-				if(!(this.mDisplayedFragment instanceof UpNavigatibleFragment)) {
+		if (item.getItemId() == android.R.id.home) {
+			if (!mDrawerToggle.isDrawerIndicatorEnabled()) {
+				if (!(this.mDisplayedFragment instanceof UpNavigatibleFragment)) {
 					mDrawerToggle.setDrawerIndicatorEnabled(true);
 					return true;
 				}
@@ -326,19 +323,19 @@ public class MainActivity extends Activity {
 				getFragmentManager().popBackStackImmediate(upNav.getUpFragment().getName(), 0);
 				this.mDisplayedFragment = getFragmentManager().findFragmentById(R.id.content_frame);
 				configureFragment();
-				/*Fragment frag = null;
-
-				try{
-					frag = (Fragment) upNav.getUpFragment().newInstance();
-				} catch (InstantiationException e) {
-					Log.i(null, "Could not create new instance of fragment");
-				} catch (IllegalAccessException e) {
-					Log.i(null, "Could not create new instance of fragment");
-				}
-
-				if(frag != null) this.injectFragment(frag);*/
-
-				if(!(this.mDisplayedFragment instanceof UpNavigatibleFragment) || !((UpNavigatibleFragment) this.mDisplayedFragment).isUpNavigatible()){
+				/*
+				 * Fragment frag = null;
+				 * 
+				 * try{ frag = (Fragment) upNav.getUpFragment().newInstance(); }
+				 * catch (InstantiationException e) { Log.i(null,
+				 * "Could not create new instance of fragment"); } catch
+				 * (IllegalAccessException e) { Log.i(null,
+				 * "Could not create new instance of fragment"); }
+				 * 
+				 * if(frag != null) this.injectFragment(frag);
+				 */
+
+				if (!(this.mDisplayedFragment instanceof UpNavigatibleFragment) || !((UpNavigatibleFragment) this.mDisplayedFragment).isUpNavigatible()) {
 					mDrawerToggle.setDrawerIndicatorEnabled(true);
 				} else {
 					mDrawerToggle.setDrawerIndicatorEnabled(false);
@@ -380,19 +377,19 @@ public class MainActivity extends Activity {
 		return this.mDisplayedFragment;
 	}
 
-	public void setDrawerIndicatorEnabled(boolean val){
+	public void setDrawerIndicatorEnabled(boolean val) {
 		mDrawerToggle.setDrawerIndicatorEnabled(val);
 	}
 
 	public void displayView(int position) {
 		MainMenuItem menuItemPosition = MainMenuItem.create(position);
 
-		if(this.mDisplayedFragment != null && this.mDisplayedFragment.getClass() == menuItemPosition.getKlass()) {
+		if (this.mDisplayedFragment != null && this.mDisplayedFragment.getClass() == menuItemPosition.getKlass()) {
 			mDrawerLayout.closeDrawer(mDrawerList);
 			return;
 		}
 
-        Fragment fragment = null;
+		Fragment fragment = null;
 
 		try {
 			fragment = (Fragment) menuItemPosition.getKlass().newInstance();
@@ -404,28 +401,28 @@ public class MainActivity extends Activity {
 
 		if (fragment != null) {
 			// update selected item and title, then close the drawer if needed
-            injectFragment(fragment);//, false, menuItemPosition);
+			injectFragment(fragment);// , false, menuItemPosition);
 
-		    mDrawerList.setItemChecked(position, true);
-		    mDrawerList.setSelection(position);
-		    setTitle(mDrawerItems.get(position).text);
-        }
+			mDrawerList.setItemChecked(position, true);
+			mDrawerList.setSelection(position);
+			setTitle(mDrawerItems.get(position).text);
+		}
 
 		mDrawerLayout.closeDrawer(mDrawerList);
 	}
 
-	public void injectFragment(Fragment fragment, boolean enableBack){
+	public void injectFragment(Fragment fragment, boolean enableBack) {
 		injectFragment(fragment);
 	}
 
-	public void injectFragment(Fragment fragment){
+	public void injectFragment(Fragment fragment) {
 		// set orientation fixed to portrait in home fragment
-		if(fragment instanceof UpNavigatibleFragment){
+		if (fragment instanceof UpNavigatibleFragment) {
 			UpNavigatibleFragment upFrag = (UpNavigatibleFragment) fragment;
-			if(upFrag.getUpFragment() == null){
+			if (upFrag.getUpFragment() == null) {
 				upFrag.setUpFragment(this.mDisplayedFragment.getClass());
 			}
-			if(upFrag.isUpNavigatible()){
+			if (upFrag.isUpNavigatible()) {
 				mDrawerToggle.setDrawerIndicatorEnabled(false);
 			}
 		}
@@ -444,21 +441,21 @@ public class MainActivity extends Activity {
 		this.mDisplayedFragment = fragment;
 	}
 
-	private void configureFragment(){
+	private void configureFragment() {
 		configureFragment(this.mDisplayedFragment);
 	}
 
-	private void configureFragment(Fragment fragment){
-		if(fragment == null) return;
+	private void configureFragment(Fragment fragment) {
+		if (fragment == null)
+			return;
 
-		if(fragment instanceof HomeFragment || fragment instanceof AboutFragment){
+		if (fragment instanceof HomeFragment || fragment instanceof AboutFragment) {
 			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT | ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
 		} else {
 			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
 		}
 
-		if(fragment instanceof StatisticsFragment ||
-				fragment instanceof RecordOverviewFragment){
+		if (fragment instanceof StatisticsFragment || fragment instanceof RecordOverviewFragment) {
 
 			Intent intent = this.getIntent();
 			intent.removeExtra(LogFilter.LOG_FILTER_INTENT_KEY);
@@ -467,14 +464,14 @@ public class MainActivity extends Activity {
 
 	@Override
 	public void onBackPressed() {
-		if(getFragmentManager().getBackStackEntryCount() == 1) {
+		if (getFragmentManager().getBackStackEntryCount() == 1) {
 			finish();
 		} else {
 			super.onBackPressed();
 			this.mDisplayedFragment = getFragmentManager().findFragmentById(R.id.content_frame);
 			configureFragment();
 
-			if(!(this.mDisplayedFragment instanceof UpNavigatibleFragment) || !((UpNavigatibleFragment) this.mDisplayedFragment).isUpNavigatible()){
+			if (!(this.mDisplayedFragment instanceof UpNavigatibleFragment) || !((UpNavigatibleFragment) this.mDisplayedFragment).isUpNavigatible()) {
 				mDrawerToggle.setDrawerIndicatorEnabled(true);
 			} else {
 				mDrawerToggle.setDrawerIndicatorEnabled(false);
@@ -484,16 +481,16 @@ public class MainActivity extends Activity {
 
 	@Override
 	public boolean onKeyDown(int keycode, KeyEvent e) {
-		switch(keycode) {
-			case KeyEvent.KEYCODE_MENU:
-				if(this.mDrawerToggle.isDrawerIndicatorEnabled()){
-					if(this.mDrawerLayout.isDrawerOpen(Gravity.LEFT)){
-						this.mDrawerLayout.closeDrawer(Gravity.LEFT);
-						return true;
-					}
-					this.mDrawerLayout.openDrawer(Gravity.LEFT);
+		switch (keycode) {
+		case KeyEvent.KEYCODE_MENU:
+			if (this.mDrawerToggle.isDrawerIndicatorEnabled()) {
+				if (this.mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
+					this.mDrawerLayout.closeDrawer(Gravity.LEFT);
+					return true;
 				}
-				return true;
+				this.mDrawerLayout.openDrawer(Gravity.LEFT);
+			}
+			return true;
 		}
 
 		return super.onKeyDown(keycode, e);
@@ -502,7 +499,7 @@ public class MainActivity extends Activity {
 	public static void displayBackStack(FragmentManager fm) {
 		int count = fm.getBackStackEntryCount();
 		Log.d("Backstack log", "There are " + count + " entries");
-		for(int i = 0; i<count; i++) {
+		for (int i = 0; i < count; i++) {
 			// Display Backstack-entry data like
 			String name = fm.getBackStackEntryAt(i).getName();
 			Log.d("Backstack log", "entry " + i + ": " + name);
@@ -510,61 +507,25 @@ public class MainActivity extends Activity {
 	}
 
 	public Intent getServiceIntent() {
-		return new Intent(this, HoneyService.class);
+		return new Intent(this, Hostage.class);
 	}
 
 	public Fragment getDisplayedFragment() {
 		return this.mDisplayedFragment;
 	}
 
-	/**
-	 * Checks if the phone ist rooted and if porthack is installed. Sets flags
-	 * {@link this.isRooted} and {@link this.porthackInstalled}
-	 */
-	private void checkRootAndPorthack() {
-		isRooted = false;
-		porthackInstalled = false;
-		Process p;
-		try {
-			String found = "Found";
-			String notFound = "Not found";
-			String command = "[ -f /data/local/p ] && echo " + found
-					+ " || echo " + notFound;
-			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;
-			}
-		} catch (Exception e) {
-			e.printStackTrace();
-		}
-		Log.i("MainAc", "Rooted: " + isRooted + " Porthack: "
-				+ porthackInstalled);
-	}
-
-	public HoneyService getHoneyService(){
+	public Hostage getHostageService() {
 		return this.mHoneyService;
 	}
 
-	public boolean isServiceBound(){
+	public boolean isServiceBound() {
 		return this.mServiceBound;
 	}
 
 	public boolean isServiceRunning() {
 		ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
-		for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(
-				Integer.MAX_VALUE)) {
-			if (service.service.getClassName().equals(
-					HoneyService.class.getName())) {
+		for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
+			if (service.service.getClassName().equals(Hostage.class.getName())) {
 				return true;
 			}
 		}
@@ -572,36 +533,32 @@ public class MainActivity extends Activity {
 	}
 
 	public enum MainMenuItem {
-        HOME(0, HomeFragment.class),
-        THREAT_MAP(1, ThreatMapFragment.class),
-        RECORDS(2, RecordOverviewFragment.class),
-		STATISTICS(3, StatisticsFragment.class),
-        SERVICES(4, ServicesFragment.class),
-        PROFILE_MANAGER(5, ProfileManagerFragment.class),
-        SETTINGS(6, SettingsFragment.class),
-        APPLICATION_INFO(7, AboutFragment.class);
-
-        private int value;
+		HOME(0, HomeFragment.class), THREAT_MAP(1, ThreatMapFragment.class), RECORDS(2, RecordOverviewFragment.class), STATISTICS(3, StatisticsFragment.class), SERVICES(
+				4, ServicesFragment.class), PROFILE_MANAGER(5, ProfileManagerFragment.class), SETTINGS(6, SettingsFragment.class), APPLICATION_INFO(7,
+				AboutFragment.class);
+
+		private int value;
 		private Class<?> klass;
 
-        private MainMenuItem(int value, Class<?> klass) {
-            this.value = value;
-            this.klass = klass;
-        }
+		private MainMenuItem(int value, Class<?> klass) {
+			this.value = value;
+			this.klass = klass;
+		}
 
-        static public MainMenuItem create(int value){
-            if (value < 0 || value  >= MainMenuItem.values().length) return MainMenuItem.HOME;
-            return  MainMenuItem.values()[value];
-        }
+		static public MainMenuItem create(int value) {
+			if (value < 0 || value >= MainMenuItem.values().length)
+				return MainMenuItem.HOME;
+			return MainMenuItem.values()[value];
+		}
 
 		public int getValue() {
 			return value;
 		}
 
-		public Class<?> getKlass(){
+		public Class<?> getKlass() {
 			return this.klass;
 		}
-    }
+	}
 
 	private class DrawerItemClickListener implements ListView.OnItemClickListener {
 		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

+ 41 - 48
src/de/tudarmstadt/informatik/hostage/ui2/adapter/ServicesListAdapter.java

@@ -1,5 +1,6 @@
 package de.tudarmstadt.informatik.hostage.ui2.adapter;
 
+import java.util.List;
 
 import android.annotation.TargetApi;
 import android.app.AlertDialog;
@@ -13,9 +14,6 @@ import android.widget.ArrayAdapter;
 import android.widget.CompoundButton;
 import android.widget.Switch;
 import android.widget.TextView;
-
-import java.util.List;
-
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
 import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
@@ -64,8 +62,7 @@ public class ServicesListAdapter extends ArrayAdapter<ServicesListItem> {
 
 	@Override
 	public View getView(final int position, View convertView, ViewGroup parent) {
-		LayoutInflater inflater = (LayoutInflater) context
-				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 		View rowView = convertView;
 
 		ViewHolder holder;
@@ -91,54 +88,50 @@ public class ServicesListAdapter extends ArrayAdapter<ServicesListItem> {
 
 		this.updateStatus(item, holder);
 
-		holder.activated.setOnCheckedChangeListener(
-				new CompoundButton.OnCheckedChangeListener() {
-					public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
-						ServicesListItem item = (ServicesListItem) buttonView.getTag();
-
-						if (!HelperUtils.isWifiConnected(mActivity)) {
-							new AlertDialog.Builder(mActivity)
-									.setTitle(R.string.information)
-									.setMessage(R.string.wifi_not_connected_msg)
-									.setPositiveButton(android.R.string.ok,
-											new DialogInterface.OnClickListener() {
-												public void onClick(DialogInterface dialog,
-														int which) {
-												}
-											})
-									.setIcon(android.R.drawable.ic_dialog_info).show();
-
-							buttonView.setChecked(false);
-						} else {
-							//check if switch is set to ON and start the concrete listener for the protocol
-							if (isChecked) {
-								if (!MainActivity.getInstance().getHoneyService().isRunning(item.protocol)) {
-									MainActivity.getInstance().getHoneyService().startListener(item.protocol);
-
-									//set the main switch to null, so that he won't react and starts all protocols
-									mServicesSwitch.setOnCheckedChangeListener(null);
-									mServicesSwitch.setChecked(true);
-									mServicesSwitch.setOnCheckedChangeListener(mListener);
-									buttonView.setChecked(true);
-								} else if (MainActivity.getInstance().getHoneyService().isRunning(item.protocol)) {
-									buttonView.setChecked(true);
-								}
-							} else {
-								if (MainActivity.getInstance().getHoneyService().isRunning(item.protocol)) {
-									MainActivity.getInstance().getHoneyService().stopListener(item.protocol);
+		holder.activated.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
+			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+				ServicesListItem item = (ServicesListItem) buttonView.getTag();
+
+				if (!HelperUtils.isWifiConnected(mActivity)) {
+					new AlertDialog.Builder(mActivity).setTitle(R.string.information).setMessage(R.string.wifi_not_connected_msg)
+							.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
+								public void onClick(DialogInterface dialog, int which) {
 								}
-								buttonView.setChecked(false);
-							}
+							}).setIcon(android.R.drawable.ic_dialog_info).show();
+
+					buttonView.setChecked(false);
+				} else {
+					// check if switch is set to ON and start the concrete
+					// listener for the protocol
+					if (isChecked) {
+						if (!MainActivity.getInstance().getHostageService().isRunning(item.protocol)) {
+							MainActivity.getInstance().getHostageService().startListener(item.protocol);
+
+							// set the main switch to null, so that he won't
+							// react and starts all protocols
+							mServicesSwitch.setOnCheckedChangeListener(null);
+							mServicesSwitch.setChecked(true);
+							mServicesSwitch.setOnCheckedChangeListener(mListener);
+							buttonView.setChecked(true);
+						} else if (MainActivity.getInstance().getHostageService().isRunning(item.protocol)) {
+							buttonView.setChecked(true);
+						}
+					} else {
+						if (MainActivity.getInstance().getHostageService().isRunning(item.protocol)) {
+							MainActivity.getInstance().getHostageService().stopListener(item.protocol);
 						}
+						buttonView.setChecked(false);
 					}
-				});
+				}
+			}
+		});
 		return rowView;
 	}
 
 	private void updateStatus(ServicesListItem item, ViewHolder holder) {
-		if (MainActivity.getInstance().getHoneyService().isRunning(item.protocol)) {
+		if (MainActivity.getInstance().getHostageService().isRunning(item.protocol)) {
 			holder.activated.setChecked(true);
-			if (!MainActivity.getInstance().getHoneyService().hasProtocolActiveAttacks(item.protocol)) {
+			if (!(MainActivity.getInstance().getHostageService().getNumberOfActiveConnections(item.protocol) > 0)) {
 				if (item.attacks > 0) {
 					setBackground(holder, R.drawable.services_circle_yellow);
 				} else {
@@ -146,7 +139,7 @@ public class ServicesListAdapter extends ArrayAdapter<ServicesListItem> {
 				}
 
 			} else {
-				if (MainActivity.getInstance().getHoneyService().hasProtocolActiveAttacks(item.protocol)) {
+				if (MainActivity.getInstance().getHostageService().getNumberOfActiveConnections(item.protocol) > 0) {
 					setBackground(holder, R.drawable.services_circle_red);
 				}
 			}
@@ -157,8 +150,8 @@ public class ServicesListAdapter extends ArrayAdapter<ServicesListItem> {
 			holder.activated.setChecked(false);
 			setBackground(holder, R.drawable.services_circle);
 		}
-		holder.recordedAttacks
-				.setText(String.format(MainActivity.getContext().getResources().getString(R.string.recorded_attacks) + "  %d", Integer.valueOf(item.attacks)));
+		holder.recordedAttacks.setText(String.format(MainActivity.getContext().getResources().getString(R.string.recorded_attacks) + "  %d",
+				Integer.valueOf(item.attacks)));
 	}
 
 	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)

+ 193 - 197
src/de/tudarmstadt/informatik/hostage/ui2/fragment/HomeFragment.java

@@ -1,4 +1,8 @@
 package de.tudarmstadt.informatik.hostage.ui2.fragment;
+
+import java.util.ArrayList;
+
+import android.annotation.SuppressLint;
 import android.app.Activity;
 import android.app.AlertDialog;
 import android.app.Fragment;
@@ -18,13 +22,10 @@ import android.widget.CompoundButton;
 import android.widget.ImageView;
 import android.widget.Switch;
 import android.widget.TextView;
-
-import java.util.ArrayList;
-
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
 import de.tudarmstadt.informatik.hostage.dao.ProfileManager;
-import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
+import de.tudarmstadt.informatik.hostage.deprecated.UglyDbHelper;
 import de.tudarmstadt.informatik.hostage.model.Profile;
 import de.tudarmstadt.informatik.hostage.ui.LogFilter;
 import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
@@ -35,7 +36,6 @@ import de.tudarmstadt.informatik.hostage.ui2.fragment.opengl.ThreatIndicatorGLRe
  * @created 13.01.14 19:06
  */
 
-
 public class HomeFragment extends Fragment {
 	private Switch mHomeSwitchConnection;
 	private TextView mHomeTextName;
@@ -71,45 +71,46 @@ public class HomeFragment extends Fragment {
 		mHomeConnectionInfoButton = (ImageView) rootView.findViewById(R.id.home_button_connection_info);
 	}
 
-	private void registerBroadcastReceiver(){
-		if(!mReceiverRegistered) {
+	private void registerBroadcastReceiver() {
+		if (!mReceiverRegistered) {
 			LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver, new IntentFilter(getString(R.string.broadcast)));
 			this.mReceiverRegistered = true;
 		}
 	}
 
-	private void unregisterBroadcastReceiver(){
-		if(mReceiverRegistered){
+	private void unregisterBroadcastReceiver() {
+		if (mReceiverRegistered) {
 			LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
 			this.mReceiverRegistered = false;
 		}
 	}
 
-	public HomeFragment(){}
+	public HomeFragment() {
+	}
 
-	public void setStateNotActive(boolean initial){
+	public void setStateNotActive(boolean initial) {
 		mHomeTextName.setTextColor(getResources().getColor(R.color.light_grey));
 		mHomeTextSecurity.setTextColor(getResources().getColor(R.color.light_grey));
 		mHomeTextAttacks.setTextColor(getResources().getColor(R.color.light_grey));
 		mHomeTextProfile.setTextColor(getResources().getColor(R.color.light_grey));
 		mHomeTextProfileHeader.setTextColor(getResources().getColor(R.color.light_grey));
 
-		if(!initial){
-	        ThreatIndicatorGLRenderer.setThreatLevel(ThreatIndicatorGLRenderer.ThreatLevel.NOT_MONITORING);
+		if (!initial) {
+			ThreatIndicatorGLRenderer.setThreatLevel(ThreatIndicatorGLRenderer.ThreatLevel.NOT_MONITORING);
 		}
 
 		mHomeSwitchConnection.setChecked(false);
 	}
 
-	public void setStateNotActive(){
+	public void setStateNotActive() {
 		setStateNotActive(false);
 	}
 
-	public void setStateActive(){
+	public void setStateActive() {
 		setStateActive(false);
 	}
 
-	public void setStateActive(boolean initial){
+	public void setStateActive(boolean initial) {
 		mHomeTextAttacks.setVisibility(View.VISIBLE);
 		mHomeTextSecurity.setVisibility(View.VISIBLE);
 
@@ -117,14 +118,14 @@ public class HomeFragment extends Fragment {
 		mHomeTextProfile.setTextColor(defaultTextColor);
 		mHomeTextProfileHeader.setTextColor(defaultTextColor);
 
-		if(!initial){
-	        ThreatIndicatorGLRenderer.setThreatLevel(ThreatIndicatorGLRenderer.ThreatLevel.NO_THREAT);
+		if (!initial) {
+			ThreatIndicatorGLRenderer.setThreatLevel(ThreatIndicatorGLRenderer.ThreatLevel.NO_THREAT);
 		}
 
 		mHomeSwitchConnection.setChecked(true);
 	}
 
-	public void setStateNotConnected(){
+	public void setStateNotConnected() {
 		mHomeTextSecurity.setVisibility(View.INVISIBLE);
 		mHomeTextAttacks.setVisibility(View.INVISIBLE);
 		mHomeTextProfile.setVisibility(View.INVISIBLE);
@@ -135,21 +136,21 @@ public class HomeFragment extends Fragment {
 		mHomeTextName.setText(R.string.not_connected);
 	}
 
-	public void setStateConnected(){
+	public void setStateConnected() {
 		mHomeTextProfile.setVisibility(View.VISIBLE);
 		mHomeTextProfileHeader.setVisibility(View.VISIBLE);
 		mHomeProfileImage.setVisibility(View.VISIBLE);
 		mHomeConnectionInfoButton.setVisibility(View.VISIBLE);
 	}
 
-	public void updateUI(){
+	public void updateUI() {
 		Profile profile = mProfileManager.getCurrentActivatedProfile();
-		if(profile != null){
+		if (profile != null) {
 			mHomeTextProfile.setText(profile.mLabel);
 			mHomeProfileImage.setImageBitmap(profile.getIconBitmap());
 		}
 
-		if(HelperUtils.isWifiConnected(getActivity())){
+		if (HelperUtils.isWifiConnected(getActivity())) {
 			setStateConnected();
 			mHomeTextName.setText(mConnectionInfo.getString(getString(R.string.connection_info_ssid), ""));
 		}
@@ -158,13 +159,13 @@ public class HomeFragment extends Fragment {
 		int totalAttacks = dbh.numBssidSeen(mConnectionInfo.getString(getString(R.string.connection_info_bssid), null));
 		ThreatIndicatorGLRenderer.ThreatLevel threatLevel = ThreatIndicatorGLRenderer.ThreatLevel.NOT_MONITORING;
 
-		if(MainActivity.getInstance().getHoneyService() != null){
-			if(MainActivity.getInstance().getHoneyService().hasRunningListeners()){
+		if (MainActivity.getInstance().getHostageService() != null) {
+			if (MainActivity.getInstance().getHostageService().hasRunningListeners()) {
 				hasActiveListeners = true;
 
-				if(MainActivity.getInstance().getHoneyService().hasActiveAttacks() && totalAttacks > 0){
+				if (MainActivity.getInstance().getHostageService().hasActiveAttacks() && totalAttacks > 0) {
 					threatLevel = ThreatIndicatorGLRenderer.ThreatLevel.LIVE_THREAT;
-				} else if(totalAttacks > 0){
+				} else if (totalAttacks > 0) {
 					threatLevel = ThreatIndicatorGLRenderer.ThreatLevel.PAST_THREAT;
 				} else {
 					threatLevel = ThreatIndicatorGLRenderer.ThreatLevel.NO_THREAT;
@@ -172,58 +173,61 @@ public class HomeFragment extends Fragment {
 			}
 		}
 
-		if(hasActiveListeners){
+		if (hasActiveListeners) {
 			setStateActive(true);
 
-			switch(threatLevel){
-				case NO_THREAT:
-					mHomeTextAttacks.setText(R.string.zero_attacks);
-					mHomeTextSecurity.setText(R.string.secure);
-					mHomeTextAttacks.setTextColor(getResources().getColor(R.color.holo_dark_green));
-					mHomeTextSecurity.setTextColor(getResources().getColor(R.color.holo_dark_green));
-					break;
-				case PAST_THREAT:
-					mHomeTextAttacks.setText(totalAttacks + (totalAttacks == 1 ? getResources().getString(R.string.attack) : getResources().getString(R.string.attacks)) + getResources().getString(R.string.recorded));
-					mHomeTextSecurity.setText(R.string.insecure);
-					mHomeTextAttacks.setTextColor(getResources().getColor(R.color.holo_yellow));
-					mHomeTextSecurity.setTextColor(getResources().getColor(R.color.holo_yellow));
-					break;
-				case LIVE_THREAT:
-					mHomeTextAttacks.setText(totalAttacks + (totalAttacks == 1 ? getResources().getString(R.string.attack) : getResources().getString(R.string.attacks)) +  getResources().getString(R.string.recorded));
-					mHomeTextSecurity.setText(R.string.insecure);
-					mHomeTextAttacks.setTextColor(getResources().getColor(R.color.holo_red));
-					mHomeTextSecurity.setTextColor(getResources().getColor(R.color.holo_red));
-					break;
+			switch (threatLevel) {
+			case NO_THREAT:
+				mHomeTextAttacks.setText(R.string.zero_attacks);
+				mHomeTextSecurity.setText(R.string.secure);
+				mHomeTextAttacks.setTextColor(getResources().getColor(R.color.holo_dark_green));
+				mHomeTextSecurity.setTextColor(getResources().getColor(R.color.holo_dark_green));
+				break;
+			case PAST_THREAT:
+				mHomeTextAttacks.setText(totalAttacks
+						+ (totalAttacks == 1 ? getResources().getString(R.string.attack) : getResources().getString(R.string.attacks))
+						+ getResources().getString(R.string.recorded));
+				mHomeTextSecurity.setText(R.string.insecure);
+				mHomeTextAttacks.setTextColor(getResources().getColor(R.color.holo_yellow));
+				mHomeTextSecurity.setTextColor(getResources().getColor(R.color.holo_yellow));
+				break;
+			case LIVE_THREAT:
+				mHomeTextAttacks.setText(totalAttacks
+						+ (totalAttacks == 1 ? getResources().getString(R.string.attack) : getResources().getString(R.string.attacks))
+						+ getResources().getString(R.string.recorded));
+				mHomeTextSecurity.setText(R.string.insecure);
+				mHomeTextAttacks.setTextColor(getResources().getColor(R.color.holo_red));
+				mHomeTextSecurity.setTextColor(getResources().getColor(R.color.holo_red));
+				break;
 			}
 
 			ThreatIndicatorGLRenderer.setThreatLevel(threatLevel);
 		} else {
 			setStateNotActive();
 
-			if(!HelperUtils.isWifiConnected(getActivity())){
+			if (!HelperUtils.isWifiConnected(getActivity())) {
 				setStateNotConnected();
 			}
 		}
 	}
 
-    @Override
-    public View onCreateView(LayoutInflater inflater, ViewGroup container,
-                             Bundle savedInstanceState) {
+	@Override
+	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 
-	    super.onCreateView(inflater, container, savedInstanceState);
+		super.onCreateView(inflater, container, savedInstanceState);
 
 		final Activity activity = getActivity();
 		if (activity != null) {
 			activity.setTitle(getResources().getString(R.string.drawer_overview));
 		}
 
-	    dbh = new UglyDbHelper(getActivity());
+		dbh = new UglyDbHelper(getActivity());
 
-	    mProfileManager = ProfileManager.getInstance();
+		mProfileManager = ProfileManager.getInstance();
 		mConnectionInfo = getActivity().getSharedPreferences(getString(R.string.connection_info), Context.MODE_PRIVATE);
 
-        rootView = inflater.inflate(R.layout.fragment_home, container, false);
-	    assignViews();
+		rootView = inflater.inflate(R.layout.fragment_home, container, false);
+		assignViews();
 
 		// hook up the connection info button
 		mHomeConnectionInfoButton.setOnClickListener(new View.OnClickListener() {
@@ -237,159 +241,151 @@ public class HomeFragment extends Fragment {
 			}
 		});
 
-	    defaultTextColor = mHomeTextName.getCurrentTextColor();
-
-	    setStateNotActive(true);
-	    setStateNotConnected();
-
-	    mReceiver = new BroadcastReceiver() {
-		    @Override
-		    public void onReceive(Context context, Intent intent) {
-			    if(getUserVisibleHint()) updateUI();
-		    }
-	    };
-	    registerBroadcastReceiver();
-
-	    updateUI();
-
-	    mHomeSwitchConnection = (Switch) rootView.findViewById(R.id.home_switch_connection);
-
-	    if(switchChangeListener == null){
-		    switchChangeListener = new CompoundButton.OnCheckedChangeListener() {
-			    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
-				    if(!HelperUtils.isWifiConnected(getActivity())){
-					    new AlertDialog.Builder(getActivity())
-							    .setTitle(R.string.information)
-							    .setMessage(R.string.wifi_not_connected_msg)
-							    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
-								    public void onClick(DialogInterface dialog, int which) {
-
-								    }
-							    })
-							    .setIcon(android.R.drawable.ic_dialog_info)
-							    .show();
-
-					    setStateNotActive();
-					    setStateNotConnected();
-				    } else {
-					    if(isChecked){
-						    boolean protocolActivated = false;
-						    if(ProfileManager.getInstance().getCurrentActivatedProfile() == null){
-							    for(String protocol: getResources().getStringArray(R.array.protocols)){
-								    if(!MainActivity.getInstance().getHoneyService().isRunning(protocol)){
-									    MainActivity.getInstance().getHoneyService().startListener(protocol);
-									    protocolActivated = true;
-								    }
-							    }
-						    } else {
-							    ProfileManager profileManager = ProfileManager.getInstance();
-
-							    if(profileManager.isRandomActive()){
-								    profileManager.randomizeProtocols(profileManager.getRandomProfile());
-							    }
-
-							    for(String protocol: profileManager.getCurrentActivatedProfile().getActiveProtocols()){
-								    if(protocol.equals("GHOST")) continue;
-
-								    if(!MainActivity.getInstance().getHoneyService().isRunning(protocol)) {
-									    MainActivity.getInstance().getHoneyService().startListener(protocol);
-									    protocolActivated = true;
-								    }
-							    }
-
-							    Profile currentProfile = profileManager.getCurrentActivatedProfile();
-
-							    if(currentProfile.mGhostActive){
-								    for(int port: currentProfile.getGhostPorts()){
-									    MainActivity.getInstance().getHoneyService().startListener("GHOST", port);
-									    protocolActivated = true;
-								    }
-							    }
-						    }
-
-						    if(protocolActivated){
-						        setStateActive();
-						    } else {
-							    new AlertDialog.Builder(getActivity())
-									    .setTitle(R.string.information)
-									    .setMessage(R.string.profile_no_services_msg)
-									    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
-										    public void onClick(DialogInterface dialog, int which) {
-
-										    }
-									    })
-									    .setIcon(android.R.drawable.ic_dialog_info)
-									    .show();
-
-							    setStateNotActive();
-						    }
-					    } else {
-						    if(MainActivity.getInstance().getHoneyService() != null){
-							    MainActivity.getInstance().getHoneyService().stopListeners();
-							    MainActivity.getInstance().stopAndUnbind();
-						    }
-						    setStateNotActive();
-					    }
-				    }
-			    }
-		    };
-	    }
-	    mHomeSwitchConnection.setOnCheckedChangeListener(switchChangeListener);
-
-	    rootView.findViewById(R.id.home_profile_details).setOnClickListener(
-		    new View.OnClickListener() {
-			    @Override
-			    public void onClick(View v) {
-					Fragment fragment = new ProfileManagerFragment();
-				    MainActivity.getInstance().injectFragment(fragment, false);
-			    }
-		    }
-	    );
-
-	    View.OnClickListener attackClickListener = new View.OnClickListener() {
-		    @Override
-		    public void onClick(View v) {
-			    String ssid = mConnectionInfo.getString(getString(R.string.connection_info_ssid), "");
-			    if(!ssid.isEmpty()){
-				    ArrayList<String> ssids = new ArrayList<String>();
-				    ssids.add(ssid);
-
-				    LogFilter filter = new LogFilter();
-				    filter.setESSIDs(ssids);
-
-				    RecordOverviewFragment recordOverviewFragment = new RecordOverviewFragment();
-				    recordOverviewFragment.setFilter(filter);
-				    recordOverviewFragment.setGroupKey("ESSID");
-
-				    MainActivity.getInstance().injectFragment(recordOverviewFragment);
-			    }
-		    }
-	    };
-
-	    mHomeTextAttacks.setOnClickListener(attackClickListener);
-	    mHomeTextSecurity.setOnClickListener(attackClickListener);
-
-        return rootView;
-    }
+		defaultTextColor = mHomeTextName.getCurrentTextColor();
 
-	@Override
-	public void onStop(){
-		super.onStop();
+		setStateNotActive(true);
+		setStateNotConnected();
+
+		mReceiver = new BroadcastReceiver() {
+			@SuppressLint("NewApi")
+			@Override
+			public void onReceive(Context context, Intent intent) {
+				if (getUserVisibleHint())
+					updateUI();
+			}
+		};
+		registerBroadcastReceiver();
+
+		updateUI();
+
+		mHomeSwitchConnection = (Switch) rootView.findViewById(R.id.home_switch_connection);
+
+		if (switchChangeListener == null) {
+			switchChangeListener = new CompoundButton.OnCheckedChangeListener() {
+				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+					if (!HelperUtils.isWifiConnected(getActivity())) {
+						new AlertDialog.Builder(getActivity()).setTitle(R.string.information).setMessage(R.string.wifi_not_connected_msg)
+								.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
+									public void onClick(DialogInterface dialog, int which) {
+
+									}
+								}).setIcon(android.R.drawable.ic_dialog_info).show();
+
+						setStateNotActive();
+						setStateNotConnected();
+					} else {
+						if (isChecked) {
+							boolean protocolActivated = false;
+							if (ProfileManager.getInstance().getCurrentActivatedProfile() == null) {
+								for (String protocol : getResources().getStringArray(R.array.protocols)) {
+									if (!MainActivity.getInstance().getHostageService().isRunning(protocol)) {
+										MainActivity.getInstance().getHostageService().startListener(protocol);
+										protocolActivated = true;
+									}
+								}
+							} else {
+								ProfileManager profileManager = ProfileManager.getInstance();
+
+								if (profileManager.isRandomActive()) {
+									profileManager.randomizeProtocols(profileManager.getRandomProfile());
+								}
+
+								for (String protocol : profileManager.getCurrentActivatedProfile().getActiveProtocols()) {
+									if (protocol.equals("GHOST"))
+										continue;
+
+									if (!MainActivity.getInstance().getHostageService().isRunning(protocol)) {
+										MainActivity.getInstance().getHostageService().startListener(protocol);
+										protocolActivated = true;
+									}
+								}
+
+								Profile currentProfile = profileManager.getCurrentActivatedProfile();
+
+								if (currentProfile.mGhostActive) {
+									for (int port : currentProfile.getGhostPorts()) {
+										MainActivity.getInstance().getHostageService().startListener("GHOST", port);
+										protocolActivated = true;
+									}
+								}
+							}
+
+							if (protocolActivated) {
+								setStateActive();
+							} else {
+								new AlertDialog.Builder(getActivity()).setTitle(R.string.information).setMessage(R.string.profile_no_services_msg)
+										.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
+											public void onClick(DialogInterface dialog, int which) {
+
+											}
+										}).setIcon(android.R.drawable.ic_dialog_info).show();
+
+								setStateNotActive();
+							}
+						} else {
+							if (MainActivity.getInstance().getHostageService() != null) {
+								MainActivity.getInstance().getHostageService().stopListeners();
+								MainActivity.getInstance().stopAndUnbind();
+							}
+							setStateNotActive();
+						}
+					}
+				}
+			};
+		}
+		mHomeSwitchConnection.setOnCheckedChangeListener(switchChangeListener);
+
+		rootView.findViewById(R.id.home_profile_details).setOnClickListener(new View.OnClickListener() {
+			@Override
+			public void onClick(View v) {
+				Fragment fragment = new ProfileManagerFragment();
+				MainActivity.getInstance().injectFragment(fragment, false);
+			}
+		});
+
+		View.OnClickListener attackClickListener = new View.OnClickListener() {
+			@Override
+			public void onClick(View v) {
+				String ssid = mConnectionInfo.getString(getString(R.string.connection_info_ssid), "");
+				if (!ssid.isEmpty()) {
+					ArrayList<String> ssids = new ArrayList<String>();
+					ssids.add(ssid);
 
+					LogFilter filter = new LogFilter();
+					filter.setESSIDs(ssids);
+
+					RecordOverviewFragment recordOverviewFragment = new RecordOverviewFragment();
+					recordOverviewFragment.setFilter(filter);
+					recordOverviewFragment.setGroupKey("ESSID");
+
+					MainActivity.getInstance().injectFragment(recordOverviewFragment);
+				}
+			}
+		};
+
+		mHomeTextAttacks.setOnClickListener(attackClickListener);
+		mHomeTextSecurity.setOnClickListener(attackClickListener);
+
+		return rootView;
+	}
+
+	@Override
+	public void onStop() {
 		unregisterBroadcastReceiver();
-		//mHomeSwitchConnection.setOnCheckedChangeListener(null);
+		// mHomeSwitchConnection.setOnCheckedChangeListener(null);
+		super.onStop();
 	}
 
 	@Override
-	public void onStart(){
+	public void onStart() {
 		super.onStart();
 		registerBroadcastReceiver();
 		updateUI();
-		//mHomeSwitchConnection.setOnCheckedChangeListener(switchChangeListener);
+		// mHomeSwitchConnection.setOnCheckedChangeListener(switchChangeListener);
 	}
 
 	@Override
-	public void onDestroy(){
+	public void onDestroy() {
 		super.onDestroy();
 		unregisterBroadcastReceiver();
 	}

+ 108 - 109
src/de/tudarmstadt/informatik/hostage/ui2/fragment/RecordDetailFragment.java

@@ -1,9 +1,10 @@
 package de.tudarmstadt.informatik.hostage.ui2.fragment;
 
-import android.annotation.SuppressLint;
+import java.util.ArrayList;
+import java.util.Date;
+
 import android.os.Bundle;
 import android.text.format.DateFormat;
-import android.text.method.ScrollingMovementMethod;
 import android.view.LayoutInflater;
 import android.view.Menu;
 import android.view.MenuInflater;
@@ -13,59 +14,59 @@ import android.view.ViewGroup;
 import android.widget.LinearLayout;
 import android.widget.ScrollView;
 import android.widget.TextView;
-import java.util.ArrayList;
-import java.util.Date;
-
 import de.tudarmstadt.informatik.hostage.R;
+import de.tudarmstadt.informatik.hostage.deprecated.UglyDbHelper;
 import de.tudarmstadt.informatik.hostage.logging.Record;
-import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
 
 /**
  * Created by Julien on 02.03.14.
  */
 public class RecordDetailFragment extends UpNavigatibleFragment {
-    private class Location{
-        private double longitude;
-        private double latitude;
-        private float accuracy;
-
-        public double getLatitude() {
-            return latitude;
-        }
-        public void setLatitude(double latitude) {
-            this.latitude = latitude;
-        }
-        public float getAccuracy() {
-            return accuracy;
-        }
+	private class Location {
+		private double longitude;
+		private double latitude;
+		private float accuracy;
+
+		public double getLatitude() {
+			return latitude;
+		}
+
+		public void setLatitude(double latitude) {
+			this.latitude = latitude;
+		}
+
+		public float getAccuracy() {
+			return accuracy;
+		}
 
 		public void setAccuracy(float accuracy) {
 			this.accuracy = accuracy;
 		}
 
-		public double getLongitude(){
-            return this.longitude;
-        }
-        public void setLongitude(double longitude){
-            this.longitude = longitude;
-        }
-
-        public Location(){
-            super();
-        }
-        public Location(double latitude, double longitude, float accuracy){
-            super();
-            this.latitude = latitude;
-            this.longitude = longitude;
-            this.accuracy = accuracy;
-        }
-    }
-
-    private Record record;
-    private UglyDbHelper dbh;
-    private View rootView;
-	private LayoutInflater mInflater;
+		public double getLongitude() {
+			return this.longitude;
+		}
 
+		public void setLongitude(double longitude) {
+			this.longitude = longitude;
+		}
+
+		public Location() {
+			super();
+		}
+
+		public Location(double latitude, double longitude, float accuracy) {
+			super();
+			this.latitude = latitude;
+			this.longitude = longitude;
+			this.accuracy = accuracy;
+		}
+	}
+
+	private Record record;
+	private UglyDbHelper dbh;
+	private View rootView;
+	private LayoutInflater mInflater;
 
 	private ScrollView mScrollView;
 	private LinearLayout mRecordOverviewConversation;
@@ -74,44 +75,43 @@ public class RecordDetailFragment extends UpNavigatibleFragment {
 	private TextView mRecordDetailsTextRemoteip;
 	private TextView mRecordDetailsTextProtocol;
 
-    public void setRecord(Record rec){
-        this.record = rec;
-    }
-    public Record getRecord(){
-        return this.record;
-    }
+	public void setRecord(Record rec) {
+		this.record = rec;
+	}
 
-    public int getLayoutId(){
-        //return R.layout.fragment_record_detail;
-	    return R.layout.fragment_record_overview;
-    }
+	public Record getRecord() {
+		return this.record;
+	}
 
-    public void onCreate(Bundle savedInstanceState) {
-        super.onCreate(savedInstanceState);
-        setHasOptionsMenu(true);
-    }
+	public int getLayoutId() {
+		// return R.layout.fragment_record_detail;
+		return R.layout.fragment_record_overview;
+	}
 
-    public View onCreateView(LayoutInflater inflater, ViewGroup container,
-                             Bundle savedInstanceState) {
-        super.onCreateView(inflater, container, savedInstanceState);
+	public void onCreate(Bundle savedInstanceState) {
+		super.onCreate(savedInstanceState);
+		setHasOptionsMenu(true);
+	}
 
-	    mInflater = inflater;
-	    getActivity().setTitle(record.getSsid());
+	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+		super.onCreateView(inflater, container, savedInstanceState);
 
-        this.dbh = new UglyDbHelper(this.getActivity().getBaseContext());
+		mInflater = inflater;
+		getActivity().setTitle(record.getSsid());
 
-        this.rootView = inflater.inflate(this.getLayoutId(), container, false);
-	    this.assignViews(rootView);
-        this.configurateRootView(rootView);
+		this.dbh = new UglyDbHelper(this.getActivity().getBaseContext());
 
+		this.rootView = inflater.inflate(this.getLayoutId(), container, false);
+		this.assignViews(rootView);
+		this.configurateRootView(rootView);
 
-        return rootView;
-    }
+		return rootView;
+	}
 
-    public void onStart() {
-        super.onStart();
+	public void onStart() {
+		super.onStart();
 
-    }
+	}
 
 	private void assignViews(View view) {
 		mScrollView = (ScrollView) view.findViewById(R.id.scrollView);
@@ -126,69 +126,68 @@ public class RecordDetailFragment extends UpNavigatibleFragment {
 
 		mRecordDetailsTextBssid.setText(record.getBssid());
 		mRecordDetailsTextSsid.setText(record.getSsid());
-		if(record.getRemoteIP() != null) mRecordDetailsTextRemoteip.setText(record.getRemoteIP() + ":" + record.getRemotePort());
+		if (record.getRemoteIP() != null)
+			mRecordDetailsTextRemoteip.setText(record.getRemoteIP() + ":" + record.getRemotePort());
 		mRecordDetailsTextProtocol.setText(record.getProtocol());
 
-	    ArrayList<Record> conversation = this.dbh.getConversationForAttackID(record.getAttack_id());
+		ArrayList<Record> conversation = this.dbh.getConversationForAttackID(record.getAttack_id());
 
-	    for(Record r: conversation){
-		    View row;
+		for (Record r : conversation) {
+			View row;
 
-		    String from = r.getLocalIP() == null ? "-" : r.getLocalIP() + ":" + r.getLocalPort();
-		    String to = r.getRemoteIP() == null ? "-" : r.getRemoteIP() + ":" + r.getRemotePort();
+			String from = r.getLocalIP() == null ? "-" : r.getLocalIP() + ":" + r.getLocalPort();
+			String to = r.getRemoteIP() == null ? "-" : r.getRemoteIP() + ":" + r.getRemotePort();
 
-		    if(r.getType() == Record.TYPE.SEND){
-			    row = mInflater.inflate(R.layout.fragment_record_conversation_sent, null);
-		    } else {
-			    row = mInflater.inflate(R.layout.fragment_record_conversation_received, null);
+			if (r.getType() == Record.TYPE.SEND) {
+				row = mInflater.inflate(R.layout.fragment_record_conversation_sent, null);
+			} else {
+				row = mInflater.inflate(R.layout.fragment_record_conversation_received, null);
 
-			    String tmp = from;
-			    from = to;
-			    to = tmp;
-		    }
+				String tmp = from;
+				from = to;
+				to = tmp;
+			}
 
-		    TextView conversationInfo = (TextView) row.findViewById(R.id.record_conversation_info);
-		    TextView conversationContent = (TextView) row.findViewById(R.id.record_conversation_content);
+			TextView conversationInfo = (TextView) row.findViewById(R.id.record_conversation_info);
+			TextView conversationContent = (TextView) row.findViewById(R.id.record_conversation_content);
 			conversationContent.setOnTouchListener(new View.OnTouchListener() {
 				@Override
 				public boolean onTouch(final View v, final MotionEvent motionEvent) {
 					if (v.getId() == R.id.record_conversation_content) {
 						v.getParent().requestDisallowInterceptTouchEvent(true);
 						switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
-							case MotionEvent.ACTION_UP:
-								v.getParent().requestDisallowInterceptTouchEvent(
-										false);
-								break;
+						case MotionEvent.ACTION_UP:
+							v.getParent().requestDisallowInterceptTouchEvent(false);
+							break;
 						}
 					}
 					return false;
 				}
 			});
 
-		    Date date = new Date(r.getTimestamp());
-		    conversationInfo.setText(String.format(getString(R.string.record_details_info), from, to, getDateAsString(date), getTimeAsString(date)));
-		    if(r.getPacket() != null) conversationContent.setText(r.getPacket());
-
-		    mRecordOverviewConversation.addView(row);
-	    }
-    }
+			Date date = new Date(r.getTimestamp());
+			conversationInfo.setText(String.format(getString(R.string.record_details_info), from, to, getDateAsString(date), getTimeAsString(date)));
+			if (r.getPacket() != null)
+				conversationContent.setText(r.getPacket());
 
+			mRecordOverviewConversation.addView(row);
+		}
+	}
 
-    /*****************************
-     *
-     *          Date Transform
-     *
-     * ***************************/
-    private String getDateAsString(Date date) {
+	/*****************************
+	 * 
+	 * Date Transform
+	 * 
+	 * ***************************/
+	private String getDateAsString(Date date) {
 		return DateFormat.getDateFormat(getActivity()).format(date);
-    }
+	}
 
-	private String getTimeAsString(Date date){
+	private String getTimeAsString(Date date) {
 		return DateFormat.getTimeFormat(getActivity()).format(date);
 	}
 
-
-    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
-        super.onCreateOptionsMenu(menu, inflater);
-    }
+	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
+		super.onCreateOptionsMenu(menu, inflater);
+	}
 }

File diff suppressed because it is too large
+ 416 - 429
src/de/tudarmstadt/informatik/hostage/ui2/fragment/RecordOverviewFragment.java


+ 40 - 47
src/de/tudarmstadt/informatik/hostage/ui2/fragment/ServicesFragment.java

@@ -1,7 +1,9 @@
 package de.tudarmstadt.informatik.hostage.ui2.fragment;
 
+import java.util.ArrayList;
 
 import android.app.AlertDialog;
+import android.app.Fragment;
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.DialogInterface;
@@ -9,7 +11,6 @@ import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.SharedPreferences;
 import android.os.Bundle;
-import android.app.Fragment;
 import android.support.v4.content.LocalBroadcastManager;
 import android.view.LayoutInflater;
 import android.view.View;
@@ -18,22 +19,18 @@ import android.widget.CompoundButton;
 import android.widget.ListView;
 import android.widget.Switch;
 import android.widget.TextView;
-
-import java.util.ArrayList;
-
-import de.tudarmstadt.informatik.hostage.HoneyHandler;
+import de.tudarmstadt.informatik.hostage.Handler;
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
-import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
+import de.tudarmstadt.informatik.hostage.deprecated.UglyDbHelper;
 import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
 import de.tudarmstadt.informatik.hostage.ui2.adapter.ServicesListAdapter;
 import de.tudarmstadt.informatik.hostage.ui2.model.ServicesListItem;
 
-
 /**
  * Created by Daniel Lazar on 05.02.14.
  */
-public class ServicesFragment extends Fragment{
+public class ServicesFragment extends Fragment {
 
 	private Switch mServicesSwitchService;
 	private TextView mServicesTextName;
@@ -56,8 +53,7 @@ public class ServicesFragment extends Fragment{
 
 	private boolean mReceiverRegistered = false;
 
-
-	private void assignViews(){
+	private void assignViews() {
 		mServicesSwitchService = (Switch) rootView.findViewById(R.id.service_switch_connection);
 		mServicesTextName = (TextView) rootView.findViewById(R.id.services_text_name);
 
@@ -71,15 +67,14 @@ public class ServicesFragment extends Fragment{
 
 	}
 
-	public void updateUI(){
-		if(!HelperUtils.isWifiConnected(getActivity())){
+	public void updateUI() {
+		if (!HelperUtils.isWifiConnected(getActivity())) {
 			mServicesSwitchService.setOnCheckedChangeListener(null);
 			setStateNotConnected();
 			setStateNotActive();
 			mServicesSwitchService.setOnCheckedChangeListener(switchChangeListener);
-		}
-		else {
-			if(MainActivity.getInstance().getHoneyService().hasRunningListeners()){
+		} else {
+			if (MainActivity.getInstance().getHostageService().hasRunningListeners()) {
 				setStateActive();
 			}
 
@@ -87,25 +82,27 @@ public class ServicesFragment extends Fragment{
 		}
 
 	}
-	public ServicesFragment(){}
 
-	private void registerBroadcastReceiver(){
-		if(!mReceiverRegistered){
+	public ServicesFragment() {
+	}
+
+	private void registerBroadcastReceiver() {
+		if (!mReceiverRegistered) {
 			mReceiver = new BroadcastReceiver() {
 				@Override
 				public void onReceive(Context context, Intent intent) {
 					String sender = intent.getStringExtra("SENDER");
 					String[] values = intent.getStringArrayExtra("VALUES");
 
-					if(sender.equals(HoneyHandler.class.getName()) && values[0].equals(getString(R.string.broadcast_started))){
-						for(ServicesListItem item: protocolList){
-							if(item.protocol.equals(values[1])){
+					if (sender.equals(Handler.class.getName()) && values[0].equals(getString(R.string.broadcast_started))) {
+						for (ServicesListItem item : protocolList) {
+							if (item.protocol.equals(values[1])) {
 								item.attacks = dbh.numBssidSeen(item.protocol, mConnectionInfo.getString(getString(R.string.connection_info_bssid), null));
 							}
 						}
 					}
 
-					if (!MainActivity.getInstance().getHoneyService().hasRunningListeners()) {
+					if (!MainActivity.getInstance().getHostageService().hasRunningListeners()) {
 						setStateNotActive();
 					} else {
 						setStateActive();
@@ -120,9 +117,8 @@ public class ServicesFragment extends Fragment{
 		}
 	}
 
-
 	@Override
-	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
+	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 
 		super.onCreateView(inflater, container, savedInstanceState);
 
@@ -136,11 +132,12 @@ public class ServicesFragment extends Fragment{
 
 		ListView list = (ListView) rootView.findViewById(R.id.services_list_view);
 
-		protocolList= new ArrayList<ServicesListItem>();
-		int i=0;
-		for(String protocol: protocols){
+		protocolList = new ArrayList<ServicesListItem>();
+		int i = 0;
+		for (String protocol : protocols) {
 			protocolList.add(new ServicesListItem(protocol));
-			protocolList.get(i).attacks = dbh.numBssidSeen(protocolList.get(i).protocol, mConnectionInfo.getString(getString(R.string.connection_info_bssid), null));
+			protocolList.get(i).attacks = dbh.numBssidSeen(protocolList.get(i).protocol,
+					mConnectionInfo.getString(getString(R.string.connection_info_bssid), null));
 			i++;
 		}
 
@@ -150,17 +147,12 @@ public class ServicesFragment extends Fragment{
 			switchChangeListener = new CompoundButton.OnCheckedChangeListener() {
 				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
 					if (!HelperUtils.isWifiConnected(getActivity())) {
-						new AlertDialog.Builder(getActivity())
-								.setTitle(R.string.information)
-								.setMessage(R.string.wifi_not_connected_msg)
-								.setPositiveButton(android.R.string.ok,
-										new DialogInterface.OnClickListener() {
-											public void onClick(DialogInterface dialog, int which) {
-
-											}
-										})
-								.setIcon(android.R.drawable.ic_dialog_info)
-								.show();
+						new AlertDialog.Builder(getActivity()).setTitle(R.string.information).setMessage(R.string.wifi_not_connected_msg)
+								.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
+									public void onClick(DialogInterface dialog, int which) {
+
+									}
+								}).setIcon(android.R.drawable.ic_dialog_info).show();
 
 						setStateNotActive();
 						setStateNotConnected();
@@ -168,13 +160,13 @@ public class ServicesFragment extends Fragment{
 						if (MainActivity.getInstance().isServiceBound()) {
 							if (isChecked) {
 								for (String protocol : protocols) {
-									if (!MainActivity.getInstance().getHoneyService().isRunning(protocol)) {
-										MainActivity.getInstance().getHoneyService().startListener(protocol);
+									if (!MainActivity.getInstance().getHostageService().isRunning(protocol)) {
+										MainActivity.getInstance().getHostageService().startListener(protocol);
 									}
 								}
 								setStateActive();
 							} else {
-								MainActivity.getInstance().getHoneyService().stopListeners();
+								MainActivity.getInstance().getHostageService().stopListeners();
 								MainActivity.getInstance().stopAndUnbind();
 								setStateNotActive();
 							}
@@ -197,14 +189,14 @@ public class ServicesFragment extends Fragment{
 	};
 
 	@Override
-	public void onStart(){
+	public void onStart() {
 		super.onStart();
 		registerBroadcastReceiver();
 		mServicesSwitchService.setOnCheckedChangeListener(switchChangeListener);
 	}
 
-	private void unregisterBroadcastReceiver(){
-		if(mReceiverRegistered){
+	private void unregisterBroadcastReceiver() {
+		if (mReceiverRegistered) {
 			LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
 			this.mReceiverRegistered = false;
 		}
@@ -223,12 +215,13 @@ public class ServicesFragment extends Fragment{
 	}
 
 	@Override
-	public void onStop(){
+	public void onStop() {
 		super.onStop();
 		mServicesSwitchService.setOnCheckedChangeListener(null);
 	}
+
 	@Override
-	public void onDestroy(){
+	public void onDestroy() {
 		super.onDestroy();
 		unregisterBroadcastReceiver();
 	}

+ 4 - 6
src/de/tudarmstadt/informatik/hostage/ui2/fragment/SettingsFragment.java

@@ -1,22 +1,20 @@
 package de.tudarmstadt.informatik.hostage.ui2.fragment;
 
-import android.app.Fragment;
 import android.app.FragmentManager;
 import android.os.Bundle;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.TextView;
-
 import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
+import de.tudarmstadt.informatik.hostage.system.Device;
 
 /**
  * @author Alexander Brakowski
  * @created 24.02.14 23:37
  */
 public class SettingsFragment extends UpNavigatibleFragment {
-	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
+	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 		super.onCreateView(inflater, container, savedInstanceState);
 		getActivity().setTitle(getResources().getString(R.string.drawer_settings));
 		View v = inflater.inflate(R.layout.fragment_settings, container, false);
@@ -24,7 +22,7 @@ public class SettingsFragment extends UpNavigatibleFragment {
 		TextView rootedText = (TextView) v.findViewById(R.id.settings_device_rooted);
 		TextView porthackText = (TextView) v.findViewById(R.id.settings_porthack_installed);
 
-		if(MainActivity.isRooted){
+		if (Device.isRooted()) {
 			rootedText.setText(R.string.yes);
 			rootedText.setTextColor(getResources().getColor(R.color.holo_dark_green));
 		} else {
@@ -32,7 +30,7 @@ public class SettingsFragment extends UpNavigatibleFragment {
 			rootedText.setTextColor(getResources().getColor(R.color.holo_red));
 		}
 
-		if(MainActivity.porthackInstalled){
+		if (Device.isPorthackInstalled()) {
 			porthackText.setText(R.string.yes);
 			porthackText.setTextColor(getResources().getColor(R.color.holo_dark_green));
 		} else {

+ 1377 - 1368
src/de/tudarmstadt/informatik/hostage/ui2/fragment/StatisticsFragment.java

@@ -1,5 +1,14 @@
 package de.tudarmstadt.informatik.hostage.ui2.fragment;
 
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Date;
+import java.util.HashMap;
+
 import android.annotation.SuppressLint;
 import android.app.Fragment;
 import android.app.FragmentManager;
@@ -25,18 +34,9 @@ import com.echo.holographlibrary.LinePoint;
 import com.echo.holographlibrary.PieGraph;
 import com.echo.holographlibrary.PieSlice;
 
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Date;
-import java.util.HashMap;
-
 import de.tudarmstadt.informatik.hostage.R;
+import de.tudarmstadt.informatik.hostage.deprecated.UglyDbHelper;
 import de.tudarmstadt.informatik.hostage.logging.Record;
-import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
 import de.tudarmstadt.informatik.hostage.ui.LogFilter;
 import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
 import de.tudarmstadt.informatik.hostage.ui2.adapter.StatisticListAdapter;
@@ -55,1416 +55,1425 @@ import de.tudarmstadt.informatik.hostage.ui2.popup.SplitPopupItem;
  */
 public class StatisticsFragment extends Fragment implements ChecklistDialog.ChecklistDialogListener, DateTimeDialogFragment.DateTimeDialogFragmentListener {
 
-    static final String FILTER_MENU_TITLE_BSSID = "BSSID";
-    static final String FILTER_MENU_TITLE_ESSID = "ESSID";
-    static final String FILTER_MENU_TITLE_PROTOCOLS = MainActivity.getContext().getString(R.string.stats_protocols);
-    static final String FILTER_MENU_TITLE_PROTOCOL = MainActivity.getContext().getString(R.string.rec_protocol);
-    static final String FILTER_MENU_TITLE_TIMESTAMP_BELOW = MainActivity.getContext().getString(R.string.rec_latest);
-    static final String FILTER_MENU_TITLE_TIMESTAMP_ABOVE = MainActivity.getContext().getString(R.string.rec_earliest);
+	static final String FILTER_MENU_TITLE_BSSID = "BSSID";
+	static final String FILTER_MENU_TITLE_ESSID = "ESSID";
+	static final String FILTER_MENU_TITLE_PROTOCOLS = MainActivity.getContext().getString(R.string.stats_protocols);
+	static final String FILTER_MENU_TITLE_PROTOCOL = MainActivity.getContext().getString(R.string.rec_protocol);
+	static final String FILTER_MENU_TITLE_TIMESTAMP_BELOW = MainActivity.getContext().getString(R.string.rec_latest);
+	static final String FILTER_MENU_TITLE_TIMESTAMP_ABOVE = MainActivity.getContext().getString(R.string.rec_earliest);
 
-    static final String FILTER_MENU_TITLE_REMOVE = MainActivity.getContext().getString(R.string.rec_reset_filter);
-    static final String FILTER_MENU_POPUP_TITLE = MainActivity.getContext().getString(R.string.rec_filter_by);
+	static final String FILTER_MENU_TITLE_REMOVE = MainActivity.getContext().getString(R.string.rec_reset_filter);
+	static final String FILTER_MENU_POPUP_TITLE = MainActivity.getContext().getString(R.string.rec_filter_by);
 
+	static final String MENU_TITLE_PROTOCOLS = MainActivity.getContext().getString(R.string.stats_protocols);
+	static final String MENU_TITLE_NETWORK = MainActivity.getContext().getString(R.string.stats_networks);
+	static final String MENU_TITLE_ATTACKS = MainActivity.getContext().getString(R.string.stats_attacks);
 
-    static final String MENU_TITLE_PROTOCOLS = MainActivity.getContext().getString(
-			R.string.stats_protocols);
-    static final String MENU_TITLE_NETWORK = MainActivity.getContext().getString(
-			R.string.stats_networks);
-    static final String MENU_TITLE_ATTACKS = MainActivity.getContext().getString(
-			R.string.stats_attacks);
+	static final String MENU_POPUP_TITLE = MainActivity.getContext().getString(R.string.stats_visualize);
 
-    static final String MENU_POPUP_TITLE = MainActivity.getContext().getString(
-			R.string.stats_visualize);
+	static final String CHART_TYPE_TITLE_BAR = MainActivity.getContext().getString(R.string.stats_bar_plot);
+	static final String CHART_TYPE_TITLE_PIE = MainActivity.getContext().getString(R.string.stats_pie_plot);
+	static final String CHART_TYPE_TITLE_LINE = MainActivity.getContext().getString(R.string.stats_line_plot);
 
-    static final String CHART_TYPE_TITLE_BAR = MainActivity.getContext().getString(
-			R.string.stats_bar_plot);
-    static final String CHART_TYPE_TITLE_PIE = MainActivity.getContext().getString(R.string.stats_pie_plot);
-    static final String CHART_TYPE_TITLE_LINE = MainActivity.getContext().getString(R.string.stats_line_plot);
+	static final String DIALOG_PROTOCOLS_TITLE = MainActivity.getContext().getString(R.string.stats_select_protocol_data);
+	static final String DIALOG_NETWORK_TITLE = MainActivity.getContext().getString(R.string.stats_select_network_data);
+	static final String DIALOG_ATTACK_TITLE = MainActivity.getContext().getString(R.string.stats_select_attack_data);
 
-    static final String DIALOG_PROTOCOLS_TITLE = MainActivity.getContext().getString(R.string.stats_select_protocol_data);
-    static final String DIALOG_NETWORK_TITLE = MainActivity.getContext().getString(R.string.stats_select_network_data);
-    static final String DIALOG_ATTACK_TITLE = MainActivity.getContext().getString(R.string.stats_select_attack_data);
+	static final String COMPARE_TITLE_AttacksPerProtocol = MainActivity.getContext().getString(R.string.stats_attacks_protocol);
+	static final String COMPARE_TITLE_UsesPerProtocol = MainActivity.getContext().getString(R.string.stats_uses_protocol);
+	static final String COMPARE_TITLE_AttacksPerDate = MainActivity.getContext().getString(R.string.stats_attacks_date);
+	static final String COMPARE_TITLE_AttacksPerTime = MainActivity.getContext().getString(R.string.stats_attacks_time);
+	static final String COMPARE_TITLE_AttacksPerBSSID = MainActivity.getContext().getString(R.string.stats_attacks_bssid);
+	static final String COMPARE_TITLE_AttacksPerESSID = MainActivity.getContext().getString(R.string.stats_attacks_essid);
+	static final String FILTER_MENU_PROTOCOL_SINGLE_CHOICE_TITLE = MainActivity.getContext().getString(R.string.stats_select_protocol);
 
-    static  final String COMPARE_TITLE_AttacksPerProtocol   = MainActivity.getContext().getString(R.string.stats_attacks_protocol);
-    static  final String COMPARE_TITLE_UsesPerProtocol      = MainActivity.getContext().getString(R.string.stats_uses_protocol);
-    static  final String COMPARE_TITLE_AttacksPerDate       = MainActivity.getContext().getString(R.string.stats_attacks_date);
-    static  final String COMPARE_TITLE_AttacksPerTime       = MainActivity.getContext().getString(R.string.stats_attacks_time);
-    static  final String COMPARE_TITLE_AttacksPerBSSID      = MainActivity.getContext().getString(R.string.stats_attacks_bssid);
-    static  final String COMPARE_TITLE_AttacksPerESSID      = MainActivity.getContext().getString(R.string.stats_attacks_essid);
-    static final String FILTER_MENU_PROTOCOL_SINGLE_CHOICE_TITLE = MainActivity.getContext().getString(R.string.stats_select_protocol);
+	static final String TABLE_HEADER_VALUE_TITLE_ATTACKS_COUNT = MainActivity.getContext().getString(R.string.stats_attacks_count);
+	static final String TABLE_HEADER_VALUE_TITLE_ATTACKS_PERCENTAGE = MainActivity.getContext().getString(R.string.stats_per_cent_all);
 
-    static final String TABLE_HEADER_VALUE_TITLE_ATTACKS_COUNT = MainActivity.getContext().getString(R.string.stats_attacks_count);
-    static final String TABLE_HEADER_VALUE_TITLE_ATTACKS_PERCENTAGE = MainActivity.getContext().getString(R.string.stats_per_cent_all);
+	static final String OTHER_CHART_TITLE = MainActivity.getContext().getString(R.string.stats_other);
 
+	// MINIMAL 2
+	static int MAX_NUMBER_OF_CHART_OBJECTS = 6;
 
-    static final String OTHER_CHART_TITLE = MainActivity.getContext().getString(R.string.stats_other);
+	private boolean wasBelowTimePicker;
 
-    // MINIMAL 2
-    static int MAX_NUMBER_OF_CHART_OBJECTS = 6;
+	private LogFilter filter;
+	private boolean showFilterButton;
 
-    private boolean wasBelowTimePicker;
+	private PieGraph pieGraph;
+	private LineGraph lineGraph;
+	private BarGraph barGraph;
 
-    private LogFilter filter;
-    private boolean showFilterButton;
+	private View rootView;
+	private View currentPlotView;
 
-    private PieGraph pieGraph;
-    private LineGraph lineGraph;
-    private BarGraph barGraph;
+	private ArrayList<Integer> colorList;
+	private ArrayList<PlotComparisonItem> currentData;
 
-    private View rootView;
-    private View currentPlotView;
+	private UglyDbHelper dbh;
 
+	private ListView legendListView;
 
-    private ArrayList<Integer> colorList;
-    private ArrayList<PlotComparisonItem> currentData;
+	private String selectedCompareData = COMPARE_TITLE_AttacksPerProtocol;
 
-    private UglyDbHelper dbh;
+	public enum ChartType {
+		PIE_CHART(0), BAR_CHART(1), LINE_CHART(2);
 
-    private ListView legendListView;
+		private int value;
 
+		private ChartType(int value) {
+			this.value = value;
+		}
 
+		static public ChartType create(int value) {
+			if (value < 0 || value >= ChartType.values().length)
+				return ChartType.PIE_CHART;
+			return ChartType.values()[value];
+		}
 
-    private String selectedCompareData = COMPARE_TITLE_AttacksPerProtocol;
+		public String toString() {
+			if (this.equals(ChartType.create(0))) {
+				return CHART_TYPE_TITLE_PIE;
+			}
+			if (this.equals(ChartType.create(1))) {
+				return CHART_TYPE_TITLE_BAR;
+			}
+			return CHART_TYPE_TITLE_LINE;
+		}
 
-    public enum ChartType {
-        PIE_CHART(0),
-        BAR_CHART(1),
-        LINE_CHART(2);
+	}
 
-        private int value;
+	private ImageButton getFilterButton() {
+		return (ImageButton) this.rootView.findViewById(R.id.FilterButton);
+	}
 
-        private ChartType(int value) {
-            this.value = value;
-        }
-        static public ChartType create(int value){
-            if (value < 0 || value  >= ChartType.values().length) return ChartType.PIE_CHART;
-            return  ChartType.values()[value];
-        }
+	public int getLayoutID() {
+		return R.layout.fragment_statistics;
+	}
 
-        public String toString(){
-            if (this.equals(ChartType.create(0))){
-                return CHART_TYPE_TITLE_PIE;
-            }
-            if (this.equals(ChartType.create(1))){
-                return CHART_TYPE_TITLE_BAR;
-            }
-            return CHART_TYPE_TITLE_LINE;
-        }
+	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 
-    }
+		super.onCreateView(inflater, container, savedInstanceState);
 
-    private ImageButton getFilterButton(){
-        return (ImageButton) this.rootView.findViewById(R.id.FilterButton);
-    }
+		getActivity().setTitle(getResources().getString(R.string.drawer_statistics));
 
-    public int getLayoutID(){
-        return R.layout.fragment_statistics;
-    }
+		dbh = new UglyDbHelper(this.getBaseContext());
 
-    public View onCreateView(LayoutInflater inflater, ViewGroup container,
-                             Bundle savedInstanceState) {
+		// Get the message from the intent
 
-	    super.onCreateView(inflater, container, savedInstanceState);
+		if (this.filter == null) {
+			Intent intent = this.getActivity().getIntent();
+			LogFilter filter = intent.getParcelableExtra(LogFilter.LOG_FILTER_INTENT_KEY);
+			if (filter == null) {
+				this.clearFilter();
+			} else {
+				this.filter = filter;
+			}
+		}
 
-	    getActivity().setTitle(getResources().getString(R.string.drawer_statistics));
+		this.rootView = inflater.inflate(this.getLayoutID(), container, false);
 
-        dbh = new UglyDbHelper(this.getBaseContext());
+		this.configureRootView(this.rootView);
 
-        // Get the message from the intent
+		return this.rootView;
+	}
 
-        if (this.filter == null){
-            Intent intent = this.getActivity().getIntent();
-            LogFilter filter = intent.getParcelableExtra(LogFilter.LOG_FILTER_INTENT_KEY);
-            if(filter == null){
-                this.clearFilter();
-            } else {
-                this.filter = filter;
-            }
-        }
+	@Override
+	public void onCreate(Bundle savedInstanceState) {
+		super.onCreate(savedInstanceState);
+		setHasOptionsMenu(true);
+		setRetainInstance(true);
+	}
 
-        this.rootView = inflater.inflate(this.getLayoutID(), container, false);
+	@Override
+	public void onConfigurationChanged(Configuration newConfig) {
+		super.onConfigurationChanged(newConfig);
+		LayoutInflater inflater = LayoutInflater.from(getActivity());
 
-        this.configureRootView(this.rootView);
+		ViewGroup container = (ViewGroup) this.getView();
+		container.removeAllViewsInLayout();
+		this.rootView = inflater.inflate(this.getLayoutID(), container, false);
+		container.addView(this.rootView);
 
-        return this.rootView;
-    }
+		this.configureRootView(this.rootView);
+	}
 
-    @Override
-    public void onCreate(Bundle savedInstanceState) {
-        super.onCreate(savedInstanceState);
-        setHasOptionsMenu(true);
-        setRetainInstance(true);
-    }
-
-    @Override
-    public void onConfigurationChanged(Configuration newConfig){
-        super.onConfigurationChanged(newConfig);
-        LayoutInflater inflater = LayoutInflater.from(getActivity());
-
-        ViewGroup container = (ViewGroup) this.getView();
-        container.removeAllViewsInLayout();
-        this.rootView = inflater.inflate(this.getLayoutID(), container, false);
-        container.addView(this.rootView);
-
-        this.configureRootView(this.rootView);
-    }
-
-    private Context getBaseContext(){
-        return this.getActivity().getBaseContext();
-    }
-
-    private Context getApplicationContext(){
-        return this.getActivity().getApplicationContext();
-    }
-
-    public void configureRootView(View rootView){
-        LinearLayout plotLayout = (LinearLayout) rootView.findViewById(R.id.plot_layout);
-        plotLayout.setWillNotDraw(false);
-        plotLayout.removeAllViews();
-
-        plotLayout.setWillNotDraw(false);
-
-        this.legendListView = (ListView) rootView.findViewById(R.id.legend_list_view);
-        this.legendListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
-            @Override
-            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
-                StatisticsFragment.this.userTappedOnLegendItem(i);
-            }
-        });
-        rootView.setWillNotDraw(false);
-
-        this.actualiseCurrentPlot();
-
-        ImageButton visualButton = (ImageButton) rootView.findViewById(R.id.plot_data_button);
-        visualButton.setOnClickListener(new View.OnClickListener() {
-            public void onClick(View v) {
-                StatisticsFragment.this.openBarSelectionMenuOnView(v);
-            }
-        });
-
-
-        ImageButton filterButton = this.getFilterButton();
-        filterButton.setOnClickListener(new View.OnClickListener() {
-            public void onClick(View v) {
-                StatisticsFragment.this.openFilterMenuOnView(v);
-            }
-        });
-
-        if (this.currentPlotView instanceof BarGraph){
-            this.setTitle("" + this.getCurrentSelectedProtocol() + ": " +this.selectedCompareData);
-        } else {
-            this.setTitle(this.selectedCompareData);
-        }
-    }
-
-    public void setTitle(String title){
-        TextView titleView = (TextView) this.rootView.findViewById(R.id.title_text_view);
-        if (title != null && titleView != null){
-            titleView.setText(title);
-            titleView.invalidate();
-        }
-    }
-
-    public String getTitle(){
-        TextView titleView = (TextView) this.rootView.findViewById(R.id.title_text_view);
-        if (titleView != null){
-            return "" + titleView.getText();
-        }
-        return "";
-    }
-
-    public void onStart() {
-        super.onStart();
-        this.actualiseCurrentPlot();
-        this.currentPlotView.invalidate();
-
-        if (this.currentPlotView instanceof BarGraph){
-            this.setTitle("" + this.getCurrentSelectedProtocol() + ": " +this.selectedCompareData);
-        } else {
-            this.setTitle(this.selectedCompareData);
-        }
-    }
-
-    public void setChartType(ChartType type){
-        boolean shouldChange = true;
-        this.clearFilter();
-        if (this.currentPlotView != null){
-            if (type == ChartType.PIE_CHART){
-                shouldChange = ! (this.currentPlotView instanceof PieGraph);
-                // SET FILTER BUTTON HIDDEN
-                ImageButton filterButton = this.getFilterButton();
-                if (filterButton != null) filterButton.setVisibility(View.GONE);
-            } else {
-                if (this.pieGraph != null)
-                     this.pieGraph.setVisibility(View.GONE);
-                // SHOW FILTER BUTTON
-                ImageButton filterButton = this.getFilterButton();
-                if (filterButton != null) filterButton.setVisibility(View.VISIBLE);
-            }
-            if (type == ChartType.LINE_CHART){
-                shouldChange = ! (this.currentPlotView instanceof LineGraph);
-            } else {
-                if (this.lineGraph != null)
-                     this.lineGraph.setVisibility(View.GONE);
-            }
-            if (type == ChartType.BAR_CHART){
-                shouldChange = ! (this.currentPlotView instanceof BarGraph);
-
-            } else {
-                if (this.barGraph != null)
-                    this.barGraph.setVisibility(View.GONE);
-
-            }
-        }
-        if (shouldChange){
-            this.currentPlotView = this.getPlotViewForType(type);
-            this.currentPlotView.setVisibility(View.VISIBLE);
-
-        }
-        this.actualiseCurrentPlot();
-
-    }
-
-    public View getPlotViewForType(ChartType type){
-        switch (type){
-            case PIE_CHART:
-                return this.getPieGraphView();
-            case LINE_CHART:
-                return this.getLineGraphView();
-            default:
-                return this.getBarGraphView();
-        }
-    }
-
-    public void actualiseLegendList(){
-        StatisticListAdapter adapter = new StatisticListAdapter(this.getApplicationContext(), this.currentData);
-        if (this.currentPlotView instanceof LineGraph){
-            adapter.setValueFormatter(new StatisticListAdapter.ValueFormatter() {
-                @Override
-                public String convertValueForItemToString(PlotComparisonItem item) {
-                    return String.format("%.02f", item.getValue2()) + " %" + " " + "("+ (item.getValue1().intValue())  +")";
-                }
-            });
-        } else {
-
-            adapter.setValueFormatter(new StatisticListAdapter.ValueFormatter() {
-                @Override
-                public String convertValueForItemToString(PlotComparisonItem item)  {
-                    int v = (int) item.getValue2().intValue();
-                    return "" + v;
-                }
-            });
-
-        }
-        this.legendListView.setAdapter(adapter);
-
-        TextView tableHeaderTitleView = (TextView) this.rootView.findViewById(R.id.table_header_title_textview);
-        TextView tableHeaderValueView = (TextView) this.rootView.findViewById(R.id.table_header_value_textview);
-        if (this.currentPlotView instanceof LineGraph){
-            tableHeaderTitleView.setText(FILTER_MENU_TITLE_ESSID);
-            tableHeaderValueView.setText(TABLE_HEADER_VALUE_TITLE_ATTACKS_PERCENTAGE);
-        }
-        if (this.currentPlotView instanceof PieGraph){
-            tableHeaderTitleView.setText(FILTER_MENU_TITLE_PROTOCOL);
-            tableHeaderValueView.setText(TABLE_HEADER_VALUE_TITLE_ATTACKS_COUNT);
-        }
-        if (this.currentPlotView instanceof BarGraph){
-            tableHeaderValueView.setText(TABLE_HEADER_VALUE_TITLE_ATTACKS_COUNT);
-            if (this.selectedCompareData.equals(COMPARE_TITLE_AttacksPerBSSID)){
-                tableHeaderTitleView.setText(FILTER_MENU_TITLE_BSSID);
-            } else {
-                tableHeaderTitleView.setText(FILTER_MENU_TITLE_ESSID);
-            }
-        }
-    }
-
-    /*
-    * MENU
-    * */
-    private void openBarSelectionMenuOnView(View anchorView){
-        SimplePopupTable visualiseMenu = new SimplePopupTable(this.getActivity(), new AbstractPopup.OnPopupItemClickListener() {
-            public void onItemClick(Object ob) {
-                if (ob instanceof AbstractPopupItem){
-                    AbstractPopupItem item = (AbstractPopupItem) ob;
-                    StatisticsFragment.this.userSelectMenuItem(item);
-                }
-            }
-        });
-        visualiseMenu.setTitle(MENU_POPUP_TITLE);
-        int id = 0;
-        for(String title : StatisticsFragment.this.getMenuTitles()){
-            SimplePopupItem item = new SimplePopupItem(this.getActivity());
-            item.setTitle(title);
-            item.setItemId(id);
-            item.setSelected(false);
-            visualiseMenu.addItem(item);
-            id++;
-        }
-        visualiseMenu.showOnView(anchorView);
-    }
-
-    private void userSelectMenuItem(AbstractPopupItem item){
-        // OPEN A DIALOG TO SPECIFY THE VISUALISE DATA
-        if (item.getTitle().equals(MENU_TITLE_PROTOCOLS)){
-            ChartType chartType = ChartType.PIE_CHART;
-            this.selectedCompareData = COMPARE_TITLE_AttacksPerProtocol;
-            this.setChartType(chartType);
-            this.setTitle(COMPARE_TITLE_AttacksPerProtocol);
-        }
-        if (item.getTitle().equals(MENU_TITLE_NETWORK)){
-            this.openNetworkDataDialog();
-        }
-        if (item.getTitle().equals(MENU_TITLE_ATTACKS)){
-            this.openAttackDataDialog();
-        }
-    }
-
-    private ArrayList<String> getMenuTitles(){
-        ArrayList<String> titles = new ArrayList<String>();
-        titles.add(MENU_TITLE_PROTOCOLS);
-        titles.add(MENU_TITLE_NETWORK);
-        titles.add(MENU_TITLE_ATTACKS);
-        return titles;
-    }
-
-    /*
-    * PLOT DATA DIALOGS
-    * */
-    private void openProtocolDataDialog(){
-        ArrayList<String> titles = this.getDialogProtocolDataTitle();
-        ChecklistDialog newFragment = new ChecklistDialog(DIALOG_PROTOCOLS_TITLE, titles, this.selectedData(titles), false , this);
-        newFragment.show(this.getActivity().getFragmentManager(), DIALOG_PROTOCOLS_TITLE);
-    }
-    private void openNetworkDataDialog(){
-        ArrayList<String> titles = this.getDialogNetworkDataTitle();
-        ChecklistDialog newFragment = new ChecklistDialog(DIALOG_NETWORK_TITLE, titles, this.selectedData(titles), false , this);
-        newFragment.show(this.getActivity().getFragmentManager(), DIALOG_NETWORK_TITLE);
-    }
-    private void openAttackDataDialog(){
-        ArrayList<String> titles = this.getDialogAttackDataTitle();
-        ChecklistDialog newFragment = new ChecklistDialog(DIALOG_ATTACK_TITLE, titles, this.selectedData(titles), false , this);
-        newFragment.show(this.getActivity().getFragmentManager(), DIALOG_ATTACK_TITLE);
-    }
-
-    /*
-    *
-    * DIALOG ACTION METHODS
-    *
-    * */
-    public void onDialogPositiveClick(ChecklistDialog dialog) {
-        String title = dialog.getTitle();
-        ArrayList<String> titles =dialog.getSelectedItemTitles();
-
-        if (title.equals(FILTER_MENU_TITLE_PROTOCOLS)){
-            //titles = titles.size() == 0 ? this.protocolTitles() : titles;
-            this.filter.setProtocols(titles);
-            this.actualiseCurrentPlot();
-            return;
-        }
-        if (title.equals(FILTER_MENU_PROTOCOL_SINGLE_CHOICE_TITLE)){
-            if (titles.size() == 0){
-                titles = new ArrayList<String>();
-                titles.add(this.protocolTitles().get(0));
-            }
-            this.filter.setProtocols(titles);
-
-            this.actualiseCurrentPlot();
-            String fragTitle = "" + this.getCurrentSelectedProtocol() + ": " + this.selectedCompareData;
-            this.setTitle(fragTitle);
-            return;
-        }
-        if (title.equals(FILTER_MENU_TITLE_ESSID)){
-            this.filter.setESSIDs(titles);
-            this.actualiseCurrentPlot();
-            return;
-        }
-        if (title.equals(FILTER_MENU_TITLE_BSSID)){
-            this.filter.setBSSIDs(titles);
-            this.actualiseCurrentPlot();
-            return;
-        }
-
-        if (titles.size() != 0){
-            String data = titles.get(0);
-            this.setTitle(data);
-            if (title.equals(DIALOG_PROTOCOLS_TITLE)){
-                ChartType chartType = ChartType.PIE_CHART;
-                this.selectedCompareData = data;
-                this.setChartType(chartType);
-            }
-            if (title.equals(DIALOG_ATTACK_TITLE)){
-                ChartType chartType = ChartType.LINE_CHART;
-                this.selectedCompareData = data;
-                this.setChartType(chartType);
-            }
-            if (title.equals(DIALOG_NETWORK_TITLE)){
-                ChartType chartType = ChartType.BAR_CHART;
-                this.selectedCompareData = data;
-                this.setChartType(chartType);
-
-                String fragTitle = "" + this.getCurrentSelectedProtocol() + ": " + this.selectedCompareData;
-                this.setTitle(fragTitle);
-            }
-        }
-
-    }
-
-    public void onDialogNegativeClick(ChecklistDialog dialog) {
-
-    }
-    /*
-    *
-    * DIALOG DATA
-    *
-    * */
-    private ArrayList<String> getDialogProtocolDataTitle(){
-        ArrayList<String> data = new ArrayList<String>();
-        data.add(COMPARE_TITLE_AttacksPerProtocol);
-        data.add(COMPARE_TITLE_UsesPerProtocol);
-        return data;
-    }
-    private ArrayList<String> getDialogAttackDataTitle(){
-        ArrayList<String> data = new ArrayList<String>();
-        data.add(COMPARE_TITLE_AttacksPerDate);
-        data.add(COMPARE_TITLE_AttacksPerTime);
-        return data;
-    }
-    private ArrayList<String> getDialogNetworkDataTitle(){
-        ArrayList<String> data = new ArrayList<String>();
-        data.add(COMPARE_TITLE_AttacksPerESSID);
-        data.add(COMPARE_TITLE_AttacksPerBSSID);
-        return data;
-    }
-    private boolean[] selectedData(ArrayList<String> data){
-        boolean[] selected = new boolean[data.size()];
-         // SET DEFAULT
-        selected[0] = true;
-        return selected;
-    }
-
-    /*
-    *
-    *  FILTER BUTTON
-    *
-    * */
-    private void openFilterMenuOnView(View anchor){
-        SimplePopupTable filterMenu = new SimplePopupTable(this.getActivity(), new AbstractPopup.OnPopupItemClickListener() {
-            public void onItemClick(Object ob) {
-                if (ob instanceof  AbstractPopupItem){
-                    AbstractPopupItem item = (AbstractPopupItem) ob;
-                    StatisticsFragment.this.onFilterMenuItemSelected(item);
-                }
-            }
-        });
-
-        filterMenu.setTitle(FILTER_MENU_POPUP_TITLE);
-        for(String title : StatisticsFragment.this.filterMenuTitles()){
-            AbstractPopupItem item = null;
-            if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_BELOW)) continue;
-            if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_ABOVE)){
-                item = new SplitPopupItem(this.getActivity());
-                item.setValue(SplitPopupItem.RIGHT_TITLE, FILTER_MENU_TITLE_TIMESTAMP_BELOW);
-                item.setValue(SplitPopupItem.LEFT_TITLE, FILTER_MENU_TITLE_TIMESTAMP_ABOVE);
-                if (this.filter.hasBelowTimestamp()){
-                    item.setValue(SplitPopupItem.RIGHT_SUBTITLE, this.getDateAsString(this.filter.belowTimestamp));
-                }
-                if (this.filter.hasAboveTimestamp()){
-                    item.setValue(SplitPopupItem.LEFT_SUBTITLE, this.getDateAsString(this.filter.aboveTimestamp));
-                }
-            } else {
-                item = new SimplePopupItem(this.getActivity());
-                item.setTitle(title);
-                ((SimplePopupItem)item).setSelected(this.isFilterSetForTitle(title));
-            }
-
-            filterMenu.addItem(item);
-        }
-        filterMenu.showOnView(anchor);
-    }
-
-    private void onFilterMenuItemSelected(AbstractPopupItem item){
-        if (item instanceof SplitPopupItem){
-            SplitPopupItem sItem = (SplitPopupItem) item;
-            this.wasBelowTimePicker = sItem.wasRightTouch;
-            if (this.wasBelowTimePicker){
-                this.openTimestampToFilterDialog();
-            } else {
-                this.openTimestampFromFilterDialog();
-            }
-            return;
-        }
-        String title = item.getTitle();
-        if (title.equals(FILTER_MENU_TITLE_ESSID)){
-            this.openESSIDFilterDialog();
-        }
-        if (title.equals(FILTER_MENU_TITLE_BSSID)){
-            this.openBSSIDFilterDialog();
-        }
-        if (title.equals(FILTER_MENU_TITLE_PROTOCOL)){
-            this.openFilterDialogSelectProtocol();
-        }
-        if (title.equals(FILTER_MENU_TITLE_PROTOCOLS)){
-            this.openProtocolsFilterDialog();
-        }
-        if (title.equals(FILTER_MENU_TITLE_REMOVE)){
-            this.clearFilter();
-            this.actualiseCurrentPlot();
-        }
-    }
-
-    private ArrayList<String> filterMenuTitles(){
-        ArrayList<String> titles = new ArrayList<String>();
-        if (this.currentPlotView instanceof LineGraph){
-            titles.add(FILTER_MENU_TITLE_ESSID);
-            titles.add(FILTER_MENU_TITLE_PROTOCOLS);
-            titles.add(FILTER_MENU_TITLE_TIMESTAMP_ABOVE);
-            if (this.filter.hasESSIDs() || this.filter.hasATimestamp() || (this.filter.getProtocols() != null  && this.filter.hasProtocols() && this.filter.getProtocols().size() != this.protocolTitles().size())){
-                titles.add(FILTER_MENU_TITLE_REMOVE);
-            }
-        } else {
-            titles.add(FILTER_MENU_TITLE_PROTOCOL);
-            String protocol = this.getCurrentSelectedProtocol();
-            if (protocol.length() > 0){
-                if (this.selectedCompareData.equals(COMPARE_TITLE_AttacksPerBSSID)){
-                    titles.add(FILTER_MENU_TITLE_BSSID);
-                } else {
-                    // DEFAULT
-                    titles.add(FILTER_MENU_TITLE_ESSID);
-                }
-            }
-            titles.add(FILTER_MENU_TITLE_TIMESTAMP_ABOVE);
-            if (this.filter.hasATimestamp() || this.filter.hasESSIDs() || this.filter.hasBSSIDs()
-                    || (this.currentPlotView instanceof LineGraph && this.filter.hasProtocols())){
-                titles.add(FILTER_MENU_TITLE_REMOVE);
-            }
-        }
-        return titles;
-    }
-
-    private void openProtocolsFilterDialog(){
-        ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_PROTOCOLS,
-                                                    this.protocolTitles(),
-                                                    this.selectedProtocols(),
-                                                    true ,
-                                                    this);
-        newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_PROTOCOLS);
-    }
-    private void openFilterDialogSelectProtocol(){
-        ArrayList<String> titles = this.protocolTitles();
-        boolean[] selected = new boolean[titles.size()];
-        int i = 0;
-        for (String title : titles){
-            selected[i] = title.equals(this.getCurrentSelectedProtocol());
-            i++;
-        }
-        ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_PROTOCOL_SINGLE_CHOICE_TITLE, titles, selected, false , this);
-        newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_PROTOCOL_SINGLE_CHOICE_TITLE);
-    }
-
-    private void openESSIDFilterDialog(){
-        ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_ESSID, this.essids(), this.selectedESSIDs(), true , this);
-        newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_ESSID);
-    }
-
-    private void openBSSIDFilterDialog(){
-        ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_BSSID, this.bssids(), this.selectedBSSIDs(), true , this);
-        newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_BSSID);
-    }
-
-    private void openTimestampFromFilterDialog(){
-        this.wasBelowTimePicker = false;
-        DateTimeDialogFragment newFragment = new DateTimeDialogFragment(this.getActivity());
-        newFragment.setDateChangeListener(this);
-        newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_TIMESTAMP_ABOVE);
-
-        if (this.filter.aboveTimestamp != Long.MIN_VALUE)newFragment.setDate(this.filter.aboveTimestamp);
-    }
-
-    private void openTimestampToFilterDialog(){
-        this.wasBelowTimePicker = true;
-        DateTimeDialogFragment newFragment = new DateTimeDialogFragment(this.getActivity());
-        newFragment.setDateChangeListener(this);
-        newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_TIMESTAMP_BELOW);
-        if (this.filter.belowTimestamp != Long.MAX_VALUE) newFragment.setDate(this.filter.belowTimestamp);
-    }
-
-    public ArrayList<String> essids(){
-        ArrayList<String> records;
-        if (this.currentPlotView instanceof BarGraph){
-            records = dbh.getUniqueESSIDRecordsForProtocol(this.getCurrentSelectedProtocol());
-        } else {
-            records = dbh.getUniqueESSIDRecords();
-        }
-        return records;
-    }
-    public boolean[] selectedESSIDs(){
-        ArrayList<String> essids = this.essids();
-        boolean[] selected = new boolean[essids.size()];
-
-        int i = 0;
-        for(String essid : essids){
-            selected[i] =(this.filter.getESSIDs().contains(essid));
-            i++;
-        }
-        return selected;
-    }
-
-    public ArrayList<String> bssids(){
-        ArrayList<String> records ;
-        if (this.currentPlotView instanceof BarGraph){
-            records = dbh.getUniqueBSSIDRecordsForProtocol(this.getCurrentSelectedProtocol());
-        } else {
-            records = dbh.getUniqueBSSIDRecords();
-        }
-        return records;
-    }
-    public boolean[] selectedBSSIDs(){
-        ArrayList<String> bssids = this.bssids();
-
-        boolean[] selected = new boolean[bssids.size()];
-
-        int i = 0;
-        for(String bssid : bssids){
-            selected[i] =(this.filter.getBSSIDs().contains(bssid));
-            i++;
-        }
-        return selected;
-    }
-
-    public void onDateTimePickerPositiveClick(DateTimeDialogFragment dialog) {
-        if(this.wasBelowTimePicker){
-            this.filter.setBelowTimestamp(dialog.getDate());
-        } else {
-            this.filter.setAboveTimestamp(dialog.getDate());
-        }
-        this.actualiseCurrentPlot();
-    }
-
-    public void onDateTimePickerNegativeClick(DateTimeDialogFragment dialog) {
-        if(this.wasBelowTimePicker){
-            this.filter.setBelowTimestamp(Long.MAX_VALUE);
-        } else {
-            this.filter.setAboveTimestamp(Long.MIN_VALUE);
-        }
-        this.actualiseCurrentPlot();
-    }
-
-
-    /*
-    *
-    *  PLOT TYPES
-    *
-    * **/
-    public PieGraph getPieGraphView(){
-        if (this.pieGraph == null) {
-            this.pieGraph = new PieGraph(this.getApplicationContext());
-            LinearLayout plotLayout = (LinearLayout) this.rootView.findViewById(R.id.plot_layout);
-            plotLayout.addView(this.pieGraph);
-            this.pieGraph.setOnSliceClickedListener(new PieGraph.OnSliceClickedListener() {
-                @Override
-                public void onClick(int index) {
-                    StatisticsFragment.this.onSliceClick(index);
-                }
-            });
-        }
-         return this.pieGraph;
-    }
-
-    public LineGraph getLineGraphView(){
-        if (this.lineGraph == null) {
-            this.lineGraph = new LineGraph(this.getActivity());
-            LinearLayout plotLayout = (LinearLayout) this.rootView.findViewById(R.id.plot_layout);
-            plotLayout.addView(this.lineGraph);
-            this.lineGraph.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT ));
-        }
-        return this.lineGraph;
-    }
-
-    public BarGraph getBarGraphView(){
-        if (this.barGraph == null) {
-            this.barGraph = new BarGraph(this.getActivity());
-            LinearLayout plotLayout = (LinearLayout) this.rootView.findViewById(R.id.plot_layout);
-            this.barGraph.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT ));
-            plotLayout.addView(this.barGraph);
-            this.barGraph.setShowBarText(false);
-            this.barGraph.setPopupImageID(R.drawable.popup_black);
-            this.barGraph.setOnBarClickedListener(new BarGraph.OnBarClickedListener() {
-                @Override
-                public void onClick(int i) {
-                    StatisticsFragment.this.onBarClick(i);
-                }
-            });
-        }
-        return this.barGraph;
-    }
-
-    /*
-    *  FEED PLOTS WITH DATA
-    * */
-    public void setPieGraphData(PieGraph piegraph){
-        this.currentData = this.getPieData();
-        if (this.currentData == null){
-            this.currentData = new ArrayList<PlotComparisonItem>();
-        }
-
-        this.pieGraph.removeSlices();
-
-        for (PlotComparisonItem item : this.currentData){
-            PieSlice slice = new PieSlice();
-            slice.setColor(item.getColor());
-            Double value2 = (Double) item.getValue2();
-            float v = value2.floatValue();
-            slice.setValue(v);
-            slice.setTitle(item.getTitle());
-            this.pieGraph.addSlice(slice);
-        }
-        this.pieGraph.invalidate();
-
-    }
-
-    public void setLineGraphData(LineGraph linegraph){
-        this.currentData = this.getLineData();
-        if (this.currentData == null){
-            this.currentData = new ArrayList<PlotComparisonItem>();
-        }
-
-        this.lineGraph.removeAllLines();
-        double rangeMax_Y = 0;
-        double rangeMin_Y = 0;
-
-        double rangeMax_X = 0;
-        double rangeMin_X = 0;
-
-        int count = 0;
-        for (PlotComparisonItem lineItem : this.currentData){
-            ArrayList<PlotComparisonItem> data = lineItem.getOtherData();
-            int index = 0;
-            Line l = new Line();
-            int lineColor = lineItem.getColor();
-            l.setColor(lineColor);
-
-            for (PlotComparisonItem pointItem : data){
-                LinePoint p = new LinePoint();
-                p.setX(pointItem.getValue1());
-                Double value2 = pointItem.getValue2();
-                p.setY(value2);
-                p.setColor(lineColor);
-                l.addPoint(p);
-                rangeMax_Y = Math.max(pointItem.getValue2(), rangeMax_Y);
-                rangeMax_X = Math.max(pointItem.getValue1(), rangeMax_X);
-
-                if (count != 0){
-                    rangeMin_Y = Math.min(pointItem.getValue2(), rangeMin_Y);
-                    rangeMin_X = Math.min(pointItem.getValue1(), rangeMin_X);
-                } else {
-                    rangeMin_Y = pointItem.getValue2();
-                    rangeMin_X = pointItem.getValue1();
-                }
-                index++;
-                count++;
-            }
-            this.lineGraph.addLine(l);
-        }
-        // add a bit more space
-        rangeMax_Y++;
-        rangeMin_Y--;
-
-        boolean shouldUseDate = this.selectedCompareData.equals(COMPARE_TITLE_AttacksPerDate);
-        if (shouldUseDate){
-            this.lineGraph.resetXLimits();
-
-            if (this.filter.hasBelowTimestamp()){
-                rangeMax_X = Math.max(this.filter.belowTimestamp, rangeMax_X);
-            }
-            if (this.filter.hasAboveTimestamp()){
-                rangeMin_X = Math.min(this.filter.aboveTimestamp, rangeMin_X);
-            }
-
-            double stepRange = (rangeMax_X - rangeMin_X)/(60*60*24*1000);
-            this.lineGraph.setxAxisStep(Math.max(1, (float) Math.min(stepRange, 4)));
-
-            this.lineGraph.setRangeX(rangeMin_X  , rangeMax_X);
-
-            this.lineGraph.setConverter(new LineGraph.AxisDataConverter() {
-                @Override
-                public String convertDataForX_Position(double x) {
-                    return StatisticsFragment.this.getDateAsDayString((long)x);
-                }
-                @Override
-                public  String convertDataForY_Position(double y){
-                    return "" + (long)y;
-                }
-            });
-        } else {
-            this.lineGraph.setxAxisStep(12.f);
-            this.lineGraph.setRangeX(0, 24);
-            this.lineGraph.setConverter(null);
-        }
-
-        int maxY = (int)(rangeMax_Y - rangeMin_Y);
-        this.lineGraph.setYAxisStep(Math.min(maxY, 5));
-        int yStep = (int)this.lineGraph.getyAxisStep();
-        if ((maxY % yStep) != 0) {
-            maxY = maxY + (yStep - (maxY % yStep));
-        }
-        this.lineGraph.setRangeY(rangeMin_Y, rangeMin_Y + maxY);
-        this.lineGraph.setLineToFill(0);
-        this.lineGraph.invalidate();
-    }
-
-    public void setBarGraphData(BarGraph bargraph){
-        this.currentData = this.getBarData();
-        if (this.currentData == null){
-            this.currentData = new ArrayList<PlotComparisonItem>();
-        }
-
-        ArrayList<Bar> bars = new ArrayList<Bar>();
-
-        for (PlotComparisonItem item : this.currentData){
-            Bar d = new Bar();
-            d.setColor(item.getColor());
-            Long value2 =  item.getValue2().longValue();
-            d.setName("" + value2);
-            d.setValue(value2.floatValue());
-            bars.add(d);
-        }
-
-        this.barGraph.setBars(bars);
-        this.barGraph.invalidate();
-    }
-
-    /*
-    *
-    *  FETCH & ACTUALISE RECORD DATA
-    *
-    * */
-    public ArrayList<Record> getFetchedRecords(){
-        if (this.filter == null) this.clearFilter();
-        return this.dbh.getRecordsForFilter(this.filter);
-    }
-
-     public void actualiseCurrentPlot(){
-         LinearLayout plotLayout = (LinearLayout) this.rootView.findViewById(R.id.plot_layout);
-        View plot = this.currentPlotView;
-         if (plot == null){
-             this.currentPlotView = this.getPieGraphView();
-             plot = this.currentPlotView;
-         }
-         if (plot.getParent() != null && !plot.getParent().equals(plotLayout)){
-             LinearLayout linLayout = (LinearLayout)plot.getParent();
-             linLayout.removeView(plot);
-             plot.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT ));
-             plotLayout.addView(plot);
-         }
-
-         if (plot.getVisibility() == View.GONE) plot.setVisibility(View.VISIBLE);
-
-        if (plot instanceof PieGraph){
-            PieGraph pie = (PieGraph) plot;
-            this.setPieGraphData(pie);
-            // HIDE FILTER BUTTON
-            ImageButton filterButton = this.getFilterButton();
-            if (filterButton != null) filterButton.setVisibility(View.GONE);
-        } else {
-            if (this.pieGraph != null){
-                this.pieGraph.setVisibility(View.GONE);
-                if (this.pieGraph.getParent() != null){
-                    plotLayout.removeView(this.pieGraph);
-                }
-            }
-            // SHOW FILTER BUTTON
-            ImageButton filterButton = this.getFilterButton();
-            if (filterButton != null) filterButton.setVisibility(View.VISIBLE);
-        }
-        if (plot instanceof BarGraph){
-            BarGraph bar = (BarGraph) plot;
-            this.setBarGraphData(bar);
-        } else {
-            if (this.barGraph != null){
-                this.barGraph.setVisibility(View.GONE);
-                if (this.barGraph.getParent() != null){
-                    plotLayout.removeView(this.barGraph);
-                }
-            }
-        }
-        if (plot instanceof LineGraph){
-           LineGraph line = (LineGraph)plot;
-           this.setLineGraphData(line);
-        }else {
-            if (this.lineGraph != null){
-                this.lineGraph.setVisibility(View.GONE);
-                if (this.lineGraph.getParent() != null){
-                    plotLayout.removeView(this.lineGraph);
-                }
-            }
-        }
-        plot.setVisibility(View.VISIBLE);
-         if (plot.getParent() == null){
-             plotLayout.addView(plot);
-         }
-         this.actualiseLegendList();
-         this.currentPlotView.bringToFront();
-         this.currentPlotView.invalidate();
-     }
-
-    public ArrayList<PlotComparisonItem> getPieData(){
-        // DEFAULT
-        return this.attacksPerProtocols();
-    }
-    public ArrayList<PlotComparisonItem> getBarData(){
-        String protocol = this.getCurrentSelectedProtocol();
-
-        if (protocol.length() > 0){
-            if (this.selectedCompareData.equals(COMPARE_TITLE_AttacksPerESSID)){
-                return this.attacksPerESSID(protocol);
-            }
-            // DEFAULT
-            return this.attacksPerBSSID(protocol);
-        }
-        // Nothing available
-        return new ArrayList<PlotComparisonItem>();
-    }
-    public ArrayList<PlotComparisonItem> getLineData(){
-        return this.attacksPerTime();
-    }
-
-    /*
-    *  DATA SOURCE
-    * */
+	private Context getBaseContext() {
+		return this.getActivity().getBaseContext();
+	}
 
-    /*PROTOCOLS OVERVIEW*/
-     public ArrayList<PlotComparisonItem> attacksPerProtocols(){
-        ArrayList<PlotComparisonItem> plotItems = new ArrayList<PlotComparisonItem>();
-         int index = 0;
-        for (String title : this.getSelectedProtocolTitles()){
-            int attacksCount = this.dbh.getAttackPerProtocolCount(title);
-            if (attacksCount == 0) continue;
-            PlotComparisonItem item = new PlotComparisonItem(title,this.getColor(index), 0., (double) attacksCount);
-            plotItems.add(item);
-            index++;
-        }
-         Collections.sort(plotItems, new Comparator<PlotComparisonItem>() {
-             @Override
-             public int compare(PlotComparisonItem s1, PlotComparisonItem s2) {
-                 return s2.getValue2().compareTo(s1.getValue2());
-             }
-         });
-         return this.resizeData(plotItems);
-    }
-    /*LINE PLOT DATA*/
-
-    public ArrayList<PlotComparisonItem> attacksPerTime(){
-        HashMap<String,HashMap<Long, ArrayList<Record> > > lineMap = new HashMap<String, HashMap<Long, ArrayList<Record>>>();
-
-        boolean shouldUseDate = this.selectedCompareData.equals(COMPARE_TITLE_AttacksPerDate);
-
-        ArrayList<Record> records = this.getFetchedRecords();
-        for (Record record : records){
-            long timestamp = record.getTimestamp();
-            long time = 0;
-            if (shouldUseDate){
-                time = this.getDateFromMilliseconds(timestamp);
-            } else {
-                time = this.getDayHourFromDate(timestamp);
-            }
-
-            // GET CORRECT MAP
-            HashMap<Long, ArrayList<Record> > recordMap;
-            String groupKey = record.getSsid();
-            if (lineMap.containsKey(groupKey)){
-                recordMap = lineMap.get(record.getSsid());
-            } else {
-                recordMap = new HashMap<Long, ArrayList<Record> >();
-                lineMap.put(groupKey, recordMap);
-            }
-
-            // GET LIST OF RECORDS
-            ArrayList<Record> list;
-            if (recordMap.containsKey(time)){
-                list = recordMap.get(time);
-            } else {
-                list = new ArrayList<Record>();
-                recordMap.put(time, list);
-            }
-            list.add(record);
-        }
-
-        ArrayList<PlotComparisonItem> plotItems = new ArrayList<PlotComparisonItem>();
-
-        int index = 0;
-        for (String groupKey : lineMap.keySet()){
-            HashMap<Long, ArrayList<Record> > recordMap = lineMap.get(groupKey);
-            ArrayList<PlotComparisonItem> singleLineItems = new ArrayList<PlotComparisonItem>();
-
-            int numbOfAttacks = 0;
-            for (long time : recordMap.keySet()){
-                ArrayList<Record>list = recordMap.get(time);
-                if (list.size() == 0) continue;
-                PlotComparisonItem item = new PlotComparisonItem(this.getHourAsTimeString(time), 0 , (double)time, (double) list.size());
-                singleLineItems.add(item);
-                numbOfAttacks +=list.size();
-            }
-
-            Collections.sort(singleLineItems, new Comparator<PlotComparisonItem>() {
-                @Override
-                public int compare(PlotComparisonItem s1, PlotComparisonItem s2) {
-                    return s1.getValue1().compareTo(s2.getValue1());
-                }
-            });
-
-            double itemValue = (((double)numbOfAttacks / (double)records.size())*100.);
-            PlotComparisonItem item = new PlotComparisonItem(groupKey, this.getColor(index), (double) numbOfAttacks, itemValue);
-            item.setOtherData(singleLineItems);
-            plotItems.add(item);
-            index++;
-        }
-        Collections.sort(plotItems, new Comparator<PlotComparisonItem>() {
-            @Override
-            public int compare(PlotComparisonItem s1, PlotComparisonItem s2) {
-                return s2.getValue2().compareTo(s1.getValue2());
-            }
-        });
-        return plotItems;
-    }
-    // BAR PLOT DATA
-    public ArrayList<PlotComparisonItem> attacksPerBSSID(String protocol){
-        LogFilter filter = new LogFilter();
-        ArrayList<String> protocollist = new ArrayList<String>();
-        filter.setAboveTimestamp(this.filter.getAboveTimestamp());
-        filter.setBelowTimestamp(this.filter.getBelowTimestamp());
-        filter.setBSSIDs(this.filter.getBSSIDs());
-        protocollist.add(protocol);
-        filter.setProtocols(protocollist);
-
-        ArrayList<PlotComparisonItem> plotItems = new ArrayList<PlotComparisonItem>();
-
-        HashMap<String, Integer> recordMap = new HashMap<String, Integer>();
-        ArrayList<Record> records = this.dbh.getRecordsForFilter(filter);
-        for (Record record : records){
-            int count = 0;
-            if (recordMap.containsKey(record.getBssid())){
-                count = recordMap.get(record.getBssid());
-            }
-            count++;
-            recordMap.put(record.getBssid(), count);
-        }
-        int index = 0;
-        for (String key : recordMap.keySet()){
-            double value = (double)recordMap.get(key);
-            if (value == 0.) continue;
-            PlotComparisonItem item = new PlotComparisonItem(key, this.getColor(index), 0., value);
-            plotItems.add(item);
-            index++;
-        }
-        Collections.sort(plotItems, new Comparator<PlotComparisonItem>() {
-            @Override
-            public int compare(PlotComparisonItem s1, PlotComparisonItem s2) {
-                return s2.getValue2().compareTo(s1.getValue2());
-            }
-        });
-        return this.resizeData(plotItems);
-    }
-    public ArrayList<PlotComparisonItem> attacksPerESSID(String protocol){
-        LogFilter filter = new LogFilter();
-        filter.setAboveTimestamp(this.filter.getAboveTimestamp());
-        filter.setBelowTimestamp(this.filter.getBelowTimestamp());
-        filter.setESSIDs(this.filter.getESSIDs());
-        ArrayList<String> protocollist = new ArrayList<String>();
-        protocollist.add(protocol);
-        filter.setProtocols(protocollist);
-
-        ArrayList<PlotComparisonItem> plotItems = new ArrayList<PlotComparisonItem>();
-
-        HashMap<String, Integer> recordMap = new HashMap<String, Integer>();
-        ArrayList<Record> records = this.dbh.getRecordsForFilter(filter);
-        for (Record record : records){
-            int count = 0;
-            if (recordMap.containsKey(record.getSsid())){
-                count = recordMap.get(record.getSsid());
-            }
-            count++;
-            recordMap.put(record.getSsid(), count);
-        }
-        int index = 0;
-        for (String key : recordMap.keySet()){
-            double value =  (double)recordMap.get(key);
-            if (value == 0.) continue;
-            PlotComparisonItem item = new PlotComparisonItem(key,this.getColor(index), 0. ,value);
-            plotItems.add(item);
-            index++;
-        }
-        Collections.sort(plotItems, new Comparator<PlotComparisonItem>() {
-            @Override
-            public int compare(PlotComparisonItem s1, PlotComparisonItem s2) {
-                return s2.getValue2().compareTo(s1.getValue2());
-            }
-        });
-
-        return this.resizeData(plotItems);
-    }
-
-
-    private ArrayList<PlotComparisonItem> resizeData(ArrayList<PlotComparisonItem> plotItems){
-        if (plotItems != null){
-            if (plotItems.size() > MAX_NUMBER_OF_CHART_OBJECTS && MAX_NUMBER_OF_CHART_OBJECTS > 1){
-                ArrayList<PlotComparisonItem> copy = new ArrayList<PlotComparisonItem>();
-                ArrayList<PlotComparisonItem> others = new ArrayList<PlotComparisonItem>();
-                double valueOfOthers = 0;
-
-                for (int i = 0; i < plotItems.size(); i++){
-                    if (i < MAX_NUMBER_OF_CHART_OBJECTS - 1){
-                        PlotComparisonItem item = plotItems.get(i);
-                        item.setColor(this.getColor(i));
-                        copy.add(plotItems.get(i));
-                    } else {
-                        PlotComparisonItem item = plotItems.get(i);
-                        others.add(item);
-                        valueOfOthers+=item.getValue2();
-                    }
-                }
-                PlotComparisonItem otherItem = new PlotComparisonItem(OTHER_CHART_TITLE, this.getOtherColor(), 0., valueOfOthers);
-                otherItem.setOtherData(others);
-                copy.add(otherItem);
-
-                Collections.sort(copy, new Comparator<PlotComparisonItem>() {
-                    @Override
-                    public int compare(PlotComparisonItem s1, PlotComparisonItem s2) {
-                        return s2.getValue2().compareTo(s1.getValue2());
-                    }
-                });
-
-                return copy;
-            }
-        }
-        return plotItems;
-    }
-
-    /*
-    * FILTER STUFF
-    * */
-     private String getCurrentSelectedProtocol(){
-         ArrayList<String> protocolTitles = this.getSelectedProtocolTitles();
-         if (protocolTitles != null && protocolTitles.size() != 0){
-             return  protocolTitles.get(0);
-         }
-         return this.protocolTitles().get(0);
-     }
-
-     public ArrayList<String> protocolTitles(){
-        ArrayList<String> titles = new ArrayList<String>();
-        for (String protocol : this.getResources().getStringArray(
-                R.array.protocols)) {
-            titles.add(protocol);
-        }
-        return titles;
-    }
-    public boolean[] selectedProtocols(){
-        ArrayList<String> protocols = this.protocolTitles();
-        boolean[] selected = new boolean[protocols.size()];
-
-        int i = 0;
-        for(String protocol : protocols){
-            selected[i] =(this.filter.protocols.contains(protocol));
-            i++;
-        }
-        return selected;
-    }
-    public ArrayList<String> getSelectedProtocolTitles(){
-        ArrayList<String> knownProtocols = this.protocolTitles();
-        if (this.filter.hasProtocols()){
-            ArrayList<String> titles = new ArrayList<String>();
-            int i =0;
-            for (boolean b : this.selectedProtocols()){
-                if (b){
-                    String title = knownProtocols.get(i);
-                    titles.add(title);
-                }
-                i++;
-            }
-            return titles;
-        }
-        return this.protocolTitles();
-    }
-    /*
-    *
-    * COLOR STUFF
-    *
-    * */
+	private Context getApplicationContext() {
+		return this.getActivity().getApplicationContext();
+	}
 
+	public void configureRootView(View rootView) {
+		LinearLayout plotLayout = (LinearLayout) rootView.findViewById(R.id.plot_layout);
+		plotLayout.setWillNotDraw(false);
+		plotLayout.removeAllViews();
+
+		plotLayout.setWillNotDraw(false);
+
+		this.legendListView = (ListView) rootView.findViewById(R.id.legend_list_view);
+		this.legendListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
+			@Override
+			public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
+				StatisticsFragment.this.userTappedOnLegendItem(i);
+			}
+		});
+		rootView.setWillNotDraw(false);
+
+		this.actualiseCurrentPlot();
+
+		ImageButton visualButton = (ImageButton) rootView.findViewById(R.id.plot_data_button);
+		visualButton.setOnClickListener(new View.OnClickListener() {
+			public void onClick(View v) {
+				StatisticsFragment.this.openBarSelectionMenuOnView(v);
+			}
+		});
+
+		ImageButton filterButton = this.getFilterButton();
+		filterButton.setOnClickListener(new View.OnClickListener() {
+			public void onClick(View v) {
+				StatisticsFragment.this.openFilterMenuOnView(v);
+			}
+		});
+
+		if (this.currentPlotView instanceof BarGraph) {
+			this.setTitle("" + this.getCurrentSelectedProtocol() + ": " + this.selectedCompareData);
+		} else {
+			this.setTitle(this.selectedCompareData);
+		}
+	}
+
+	public void setTitle(String title) {
+		TextView titleView = (TextView) this.rootView.findViewById(R.id.title_text_view);
+		if (title != null && titleView != null) {
+			titleView.setText(title);
+			titleView.invalidate();
+		}
+	}
+
+	public String getTitle() {
+		TextView titleView = (TextView) this.rootView.findViewById(R.id.title_text_view);
+		if (titleView != null) {
+			return "" + titleView.getText();
+		}
+		return "";
+	}
+
+	public void onStart() {
+		super.onStart();
+		this.actualiseCurrentPlot();
+		this.currentPlotView.invalidate();
+
+		if (this.currentPlotView instanceof BarGraph) {
+			this.setTitle("" + this.getCurrentSelectedProtocol() + ": " + this.selectedCompareData);
+		} else {
+			this.setTitle(this.selectedCompareData);
+		}
+	}
+
+	public void setChartType(ChartType type) {
+		boolean shouldChange = true;
+		this.clearFilter();
+		if (this.currentPlotView != null) {
+			if (type == ChartType.PIE_CHART) {
+				shouldChange = !(this.currentPlotView instanceof PieGraph);
+				// SET FILTER BUTTON HIDDEN
+				ImageButton filterButton = this.getFilterButton();
+				if (filterButton != null)
+					filterButton.setVisibility(View.GONE);
+			} else {
+				if (this.pieGraph != null)
+					this.pieGraph.setVisibility(View.GONE);
+				// SHOW FILTER BUTTON
+				ImageButton filterButton = this.getFilterButton();
+				if (filterButton != null)
+					filterButton.setVisibility(View.VISIBLE);
+			}
+			if (type == ChartType.LINE_CHART) {
+				shouldChange = !(this.currentPlotView instanceof LineGraph);
+			} else {
+				if (this.lineGraph != null)
+					this.lineGraph.setVisibility(View.GONE);
+			}
+			if (type == ChartType.BAR_CHART) {
+				shouldChange = !(this.currentPlotView instanceof BarGraph);
+
+			} else {
+				if (this.barGraph != null)
+					this.barGraph.setVisibility(View.GONE);
+
+			}
+		}
+		if (shouldChange) {
+			this.currentPlotView = this.getPlotViewForType(type);
+			this.currentPlotView.setVisibility(View.VISIBLE);
+
+		}
+		this.actualiseCurrentPlot();
+
+	}
+
+	public View getPlotViewForType(ChartType type) {
+		switch (type) {
+		case PIE_CHART:
+			return this.getPieGraphView();
+		case LINE_CHART:
+			return this.getLineGraphView();
+		default:
+			return this.getBarGraphView();
+		}
+	}
+
+	public void actualiseLegendList() {
+		StatisticListAdapter adapter = new StatisticListAdapter(this.getApplicationContext(), this.currentData);
+		if (this.currentPlotView instanceof LineGraph) {
+			adapter.setValueFormatter(new StatisticListAdapter.ValueFormatter() {
+				@Override
+				public String convertValueForItemToString(PlotComparisonItem item) {
+					return String.format("%.02f", item.getValue2()) + " %" + " " + "(" + (item.getValue1().intValue()) + ")";
+				}
+			});
+		} else {
+
+			adapter.setValueFormatter(new StatisticListAdapter.ValueFormatter() {
+				@Override
+				public String convertValueForItemToString(PlotComparisonItem item) {
+					int v = (int) item.getValue2().intValue();
+					return "" + v;
+				}
+			});
+
+		}
+		this.legendListView.setAdapter(adapter);
+
+		TextView tableHeaderTitleView = (TextView) this.rootView.findViewById(R.id.table_header_title_textview);
+		TextView tableHeaderValueView = (TextView) this.rootView.findViewById(R.id.table_header_value_textview);
+		if (this.currentPlotView instanceof LineGraph) {
+			tableHeaderTitleView.setText(FILTER_MENU_TITLE_ESSID);
+			tableHeaderValueView.setText(TABLE_HEADER_VALUE_TITLE_ATTACKS_PERCENTAGE);
+		}
+		if (this.currentPlotView instanceof PieGraph) {
+			tableHeaderTitleView.setText(FILTER_MENU_TITLE_PROTOCOL);
+			tableHeaderValueView.setText(TABLE_HEADER_VALUE_TITLE_ATTACKS_COUNT);
+		}
+		if (this.currentPlotView instanceof BarGraph) {
+			tableHeaderValueView.setText(TABLE_HEADER_VALUE_TITLE_ATTACKS_COUNT);
+			if (this.selectedCompareData.equals(COMPARE_TITLE_AttacksPerBSSID)) {
+				tableHeaderTitleView.setText(FILTER_MENU_TITLE_BSSID);
+			} else {
+				tableHeaderTitleView.setText(FILTER_MENU_TITLE_ESSID);
+			}
+		}
+	}
+
+	/*
+	 * MENU
+	 */
+	private void openBarSelectionMenuOnView(View anchorView) {
+		SimplePopupTable visualiseMenu = new SimplePopupTable(this.getActivity(), new AbstractPopup.OnPopupItemClickListener() {
+			public void onItemClick(Object ob) {
+				if (ob instanceof AbstractPopupItem) {
+					AbstractPopupItem item = (AbstractPopupItem) ob;
+					StatisticsFragment.this.userSelectMenuItem(item);
+				}
+			}
+		});
+		visualiseMenu.setTitle(MENU_POPUP_TITLE);
+		int id = 0;
+		for (String title : StatisticsFragment.this.getMenuTitles()) {
+			SimplePopupItem item = new SimplePopupItem(this.getActivity());
+			item.setTitle(title);
+			item.setItemId(id);
+			item.setSelected(false);
+			visualiseMenu.addItem(item);
+			id++;
+		}
+		visualiseMenu.showOnView(anchorView);
+	}
+
+	private void userSelectMenuItem(AbstractPopupItem item) {
+		// OPEN A DIALOG TO SPECIFY THE VISUALISE DATA
+		if (item.getTitle().equals(MENU_TITLE_PROTOCOLS)) {
+			ChartType chartType = ChartType.PIE_CHART;
+			this.selectedCompareData = COMPARE_TITLE_AttacksPerProtocol;
+			this.setChartType(chartType);
+			this.setTitle(COMPARE_TITLE_AttacksPerProtocol);
+		}
+		if (item.getTitle().equals(MENU_TITLE_NETWORK)) {
+			this.openNetworkDataDialog();
+		}
+		if (item.getTitle().equals(MENU_TITLE_ATTACKS)) {
+			this.openAttackDataDialog();
+		}
+	}
+
+	private ArrayList<String> getMenuTitles() {
+		ArrayList<String> titles = new ArrayList<String>();
+		titles.add(MENU_TITLE_PROTOCOLS);
+		titles.add(MENU_TITLE_NETWORK);
+		titles.add(MENU_TITLE_ATTACKS);
+		return titles;
+	}
+
+	/*
+	 * PLOT DATA DIALOGS
+	 */
+	private void openProtocolDataDialog() {
+		ArrayList<String> titles = this.getDialogProtocolDataTitle();
+		ChecklistDialog newFragment = new ChecklistDialog(DIALOG_PROTOCOLS_TITLE, titles, this.selectedData(titles), false, this);
+		newFragment.show(this.getActivity().getFragmentManager(), DIALOG_PROTOCOLS_TITLE);
+	}
+
+	private void openNetworkDataDialog() {
+		ArrayList<String> titles = this.getDialogNetworkDataTitle();
+		ChecklistDialog newFragment = new ChecklistDialog(DIALOG_NETWORK_TITLE, titles, this.selectedData(titles), false, this);
+		newFragment.show(this.getActivity().getFragmentManager(), DIALOG_NETWORK_TITLE);
+	}
+
+	private void openAttackDataDialog() {
+		ArrayList<String> titles = this.getDialogAttackDataTitle();
+		ChecklistDialog newFragment = new ChecklistDialog(DIALOG_ATTACK_TITLE, titles, this.selectedData(titles), false, this);
+		newFragment.show(this.getActivity().getFragmentManager(), DIALOG_ATTACK_TITLE);
+	}
+
+	/*
+	 * 
+	 * DIALOG ACTION METHODS
+	 */
+	public void onDialogPositiveClick(ChecklistDialog dialog) {
+		String title = dialog.getTitle();
+		ArrayList<String> titles = dialog.getSelectedItemTitles();
+
+		if (title.equals(FILTER_MENU_TITLE_PROTOCOLS)) {
+			// titles = titles.size() == 0 ? this.protocolTitles() : titles;
+			this.filter.setProtocols(titles);
+			this.actualiseCurrentPlot();
+			return;
+		}
+		if (title.equals(FILTER_MENU_PROTOCOL_SINGLE_CHOICE_TITLE)) {
+			if (titles.size() == 0) {
+				titles = new ArrayList<String>();
+				titles.add(this.protocolTitles().get(0));
+			}
+			this.filter.setProtocols(titles);
+
+			this.actualiseCurrentPlot();
+			String fragTitle = "" + this.getCurrentSelectedProtocol() + ": " + this.selectedCompareData;
+			this.setTitle(fragTitle);
+			return;
+		}
+		if (title.equals(FILTER_MENU_TITLE_ESSID)) {
+			this.filter.setESSIDs(titles);
+			this.actualiseCurrentPlot();
+			return;
+		}
+		if (title.equals(FILTER_MENU_TITLE_BSSID)) {
+			this.filter.setBSSIDs(titles);
+			this.actualiseCurrentPlot();
+			return;
+		}
+
+		if (titles.size() != 0) {
+			String data = titles.get(0);
+			this.setTitle(data);
+			if (title.equals(DIALOG_PROTOCOLS_TITLE)) {
+				ChartType chartType = ChartType.PIE_CHART;
+				this.selectedCompareData = data;
+				this.setChartType(chartType);
+			}
+			if (title.equals(DIALOG_ATTACK_TITLE)) {
+				ChartType chartType = ChartType.LINE_CHART;
+				this.selectedCompareData = data;
+				this.setChartType(chartType);
+			}
+			if (title.equals(DIALOG_NETWORK_TITLE)) {
+				ChartType chartType = ChartType.BAR_CHART;
+				this.selectedCompareData = data;
+				this.setChartType(chartType);
+
+				String fragTitle = "" + this.getCurrentSelectedProtocol() + ": " + this.selectedCompareData;
+				this.setTitle(fragTitle);
+			}
+		}
+
+	}
+
+	public void onDialogNegativeClick(ChecklistDialog dialog) {
+
+	}
+
+	/*
+	 * 
+	 * DIALOG DATA
+	 */
+	private ArrayList<String> getDialogProtocolDataTitle() {
+		ArrayList<String> data = new ArrayList<String>();
+		data.add(COMPARE_TITLE_AttacksPerProtocol);
+		data.add(COMPARE_TITLE_UsesPerProtocol);
+		return data;
+	}
+
+	private ArrayList<String> getDialogAttackDataTitle() {
+		ArrayList<String> data = new ArrayList<String>();
+		data.add(COMPARE_TITLE_AttacksPerDate);
+		data.add(COMPARE_TITLE_AttacksPerTime);
+		return data;
+	}
+
+	private ArrayList<String> getDialogNetworkDataTitle() {
+		ArrayList<String> data = new ArrayList<String>();
+		data.add(COMPARE_TITLE_AttacksPerESSID);
+		data.add(COMPARE_TITLE_AttacksPerBSSID);
+		return data;
+	}
+
+	private boolean[] selectedData(ArrayList<String> data) {
+		boolean[] selected = new boolean[data.size()];
+		// SET DEFAULT
+		selected[0] = true;
+		return selected;
+	}
+
+	/*
+	 * 
+	 * FILTER BUTTON
+	 */
+	private void openFilterMenuOnView(View anchor) {
+		SimplePopupTable filterMenu = new SimplePopupTable(this.getActivity(), new AbstractPopup.OnPopupItemClickListener() {
+			public void onItemClick(Object ob) {
+				if (ob instanceof AbstractPopupItem) {
+					AbstractPopupItem item = (AbstractPopupItem) ob;
+					StatisticsFragment.this.onFilterMenuItemSelected(item);
+				}
+			}
+		});
+
+		filterMenu.setTitle(FILTER_MENU_POPUP_TITLE);
+		for (String title : StatisticsFragment.this.filterMenuTitles()) {
+			AbstractPopupItem item = null;
+			if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_BELOW))
+				continue;
+			if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_ABOVE)) {
+				item = new SplitPopupItem(this.getActivity());
+				item.setValue(SplitPopupItem.RIGHT_TITLE, FILTER_MENU_TITLE_TIMESTAMP_BELOW);
+				item.setValue(SplitPopupItem.LEFT_TITLE, FILTER_MENU_TITLE_TIMESTAMP_ABOVE);
+				if (this.filter.hasBelowTimestamp()) {
+					item.setValue(SplitPopupItem.RIGHT_SUBTITLE, this.getDateAsString(this.filter.belowTimestamp));
+				}
+				if (this.filter.hasAboveTimestamp()) {
+					item.setValue(SplitPopupItem.LEFT_SUBTITLE, this.getDateAsString(this.filter.aboveTimestamp));
+				}
+			} else {
+				item = new SimplePopupItem(this.getActivity());
+				item.setTitle(title);
+				((SimplePopupItem) item).setSelected(this.isFilterSetForTitle(title));
+			}
+
+			filterMenu.addItem(item);
+		}
+		filterMenu.showOnView(anchor);
+	}
+
+	private void onFilterMenuItemSelected(AbstractPopupItem item) {
+		if (item instanceof SplitPopupItem) {
+			SplitPopupItem sItem = (SplitPopupItem) item;
+			this.wasBelowTimePicker = sItem.wasRightTouch;
+			if (this.wasBelowTimePicker) {
+				this.openTimestampToFilterDialog();
+			} else {
+				this.openTimestampFromFilterDialog();
+			}
+			return;
+		}
+		String title = item.getTitle();
+		if (title.equals(FILTER_MENU_TITLE_ESSID)) {
+			this.openESSIDFilterDialog();
+		}
+		if (title.equals(FILTER_MENU_TITLE_BSSID)) {
+			this.openBSSIDFilterDialog();
+		}
+		if (title.equals(FILTER_MENU_TITLE_PROTOCOL)) {
+			this.openFilterDialogSelectProtocol();
+		}
+		if (title.equals(FILTER_MENU_TITLE_PROTOCOLS)) {
+			this.openProtocolsFilterDialog();
+		}
+		if (title.equals(FILTER_MENU_TITLE_REMOVE)) {
+			this.clearFilter();
+			this.actualiseCurrentPlot();
+		}
+	}
+
+	private ArrayList<String> filterMenuTitles() {
+		ArrayList<String> titles = new ArrayList<String>();
+		if (this.currentPlotView instanceof LineGraph) {
+			titles.add(FILTER_MENU_TITLE_ESSID);
+			titles.add(FILTER_MENU_TITLE_PROTOCOLS);
+			titles.add(FILTER_MENU_TITLE_TIMESTAMP_ABOVE);
+			if (this.filter.hasESSIDs() || this.filter.hasATimestamp()
+					|| (this.filter.getProtocols() != null && this.filter.hasProtocols() && this.filter.getProtocols().size() != this.protocolTitles().size())) {
+				titles.add(FILTER_MENU_TITLE_REMOVE);
+			}
+		} else {
+			titles.add(FILTER_MENU_TITLE_PROTOCOL);
+			String protocol = this.getCurrentSelectedProtocol();
+			if (protocol.length() > 0) {
+				if (this.selectedCompareData.equals(COMPARE_TITLE_AttacksPerBSSID)) {
+					titles.add(FILTER_MENU_TITLE_BSSID);
+				} else {
+					// DEFAULT
+					titles.add(FILTER_MENU_TITLE_ESSID);
+				}
+			}
+			titles.add(FILTER_MENU_TITLE_TIMESTAMP_ABOVE);
+			if (this.filter.hasATimestamp() || this.filter.hasESSIDs() || this.filter.hasBSSIDs()
+					|| (this.currentPlotView instanceof LineGraph && this.filter.hasProtocols())) {
+				titles.add(FILTER_MENU_TITLE_REMOVE);
+			}
+		}
+		return titles;
+	}
+
+	private void openProtocolsFilterDialog() {
+		ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_PROTOCOLS, this.protocolTitles(), this.selectedProtocols(), true, this);
+		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_PROTOCOLS);
+	}
+
+	private void openFilterDialogSelectProtocol() {
+		ArrayList<String> titles = this.protocolTitles();
+		boolean[] selected = new boolean[titles.size()];
+		int i = 0;
+		for (String title : titles) {
+			selected[i] = title.equals(this.getCurrentSelectedProtocol());
+			i++;
+		}
+		ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_PROTOCOL_SINGLE_CHOICE_TITLE, titles, selected, false, this);
+		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_PROTOCOL_SINGLE_CHOICE_TITLE);
+	}
+
+	private void openESSIDFilterDialog() {
+		ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_ESSID, this.essids(), this.selectedESSIDs(), true, this);
+		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_ESSID);
+	}
 
-    public int getOtherColor(){
-        return Color.argb(255, 80, 80, 80); // grey
+	private void openBSSIDFilterDialog() {
+		ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_BSSID, this.bssids(), this.selectedBSSIDs(), true, this);
+		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_BSSID);
 	}
-	
-    public Integer getColor(int index) {
+
+	private void openTimestampFromFilterDialog() {
+		this.wasBelowTimePicker = false;
+		DateTimeDialogFragment newFragment = new DateTimeDialogFragment(this.getActivity());
+		newFragment.setDateChangeListener(this);
+		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_TIMESTAMP_ABOVE);
+
+		if (this.filter.aboveTimestamp != Long.MIN_VALUE)
+			newFragment.setDate(this.filter.aboveTimestamp);
+	}
+
+	private void openTimestampToFilterDialog() {
+		this.wasBelowTimePicker = true;
+		DateTimeDialogFragment newFragment = new DateTimeDialogFragment(this.getActivity());
+		newFragment.setDateChangeListener(this);
+		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_TIMESTAMP_BELOW);
+		if (this.filter.belowTimestamp != Long.MAX_VALUE)
+			newFragment.setDate(this.filter.belowTimestamp);
+	}
+
+	public ArrayList<String> essids() {
+		ArrayList<String> records;
+		if (this.currentPlotView instanceof BarGraph) {
+			records = dbh.getUniqueESSIDRecordsForProtocol(this.getCurrentSelectedProtocol());
+		} else {
+			records = dbh.getUniqueESSIDRecords();
+		}
+		return records;
+	}
+
+	public boolean[] selectedESSIDs() {
+		ArrayList<String> essids = this.essids();
+		boolean[] selected = new boolean[essids.size()];
+
+		int i = 0;
+		for (String essid : essids) {
+			selected[i] = (this.filter.getESSIDs().contains(essid));
+			i++;
+		}
+		return selected;
+	}
+
+	public ArrayList<String> bssids() {
+		ArrayList<String> records;
+		if (this.currentPlotView instanceof BarGraph) {
+			records = dbh.getUniqueBSSIDRecordsForProtocol(this.getCurrentSelectedProtocol());
+		} else {
+			records = dbh.getUniqueBSSIDRecords();
+		}
+		return records;
+	}
+
+	public boolean[] selectedBSSIDs() {
+		ArrayList<String> bssids = this.bssids();
+
+		boolean[] selected = new boolean[bssids.size()];
+
+		int i = 0;
+		for (String bssid : bssids) {
+			selected[i] = (this.filter.getBSSIDs().contains(bssid));
+			i++;
+		}
+		return selected;
+	}
+
+	public void onDateTimePickerPositiveClick(DateTimeDialogFragment dialog) {
+		if (this.wasBelowTimePicker) {
+			this.filter.setBelowTimestamp(dialog.getDate());
+		} else {
+			this.filter.setAboveTimestamp(dialog.getDate());
+		}
+		this.actualiseCurrentPlot();
+	}
+
+	public void onDateTimePickerNegativeClick(DateTimeDialogFragment dialog) {
+		if (this.wasBelowTimePicker) {
+			this.filter.setBelowTimestamp(Long.MAX_VALUE);
+		} else {
+			this.filter.setAboveTimestamp(Long.MIN_VALUE);
+		}
+		this.actualiseCurrentPlot();
+	}
+
+	/*
+	 * 
+	 * PLOT TYPES
+	 * 
+	 * *
+	 */
+	public PieGraph getPieGraphView() {
+		if (this.pieGraph == null) {
+			this.pieGraph = new PieGraph(this.getApplicationContext());
+			LinearLayout plotLayout = (LinearLayout) this.rootView.findViewById(R.id.plot_layout);
+			plotLayout.addView(this.pieGraph);
+			this.pieGraph.setOnSliceClickedListener(new PieGraph.OnSliceClickedListener() {
+				@Override
+				public void onClick(int index) {
+					StatisticsFragment.this.onSliceClick(index);
+				}
+			});
+		}
+		return this.pieGraph;
+	}
+
+	public LineGraph getLineGraphView() {
+		if (this.lineGraph == null) {
+			this.lineGraph = new LineGraph(this.getActivity());
+			LinearLayout plotLayout = (LinearLayout) this.rootView.findViewById(R.id.plot_layout);
+			plotLayout.addView(this.lineGraph);
+			this.lineGraph.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
+		}
+		return this.lineGraph;
+	}
+
+	public BarGraph getBarGraphView() {
+		if (this.barGraph == null) {
+			this.barGraph = new BarGraph(this.getActivity());
+			LinearLayout plotLayout = (LinearLayout) this.rootView.findViewById(R.id.plot_layout);
+			this.barGraph.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
+			plotLayout.addView(this.barGraph);
+			this.barGraph.setShowBarText(false);
+			this.barGraph.setPopupImageID(R.drawable.popup_black);
+			this.barGraph.setOnBarClickedListener(new BarGraph.OnBarClickedListener() {
+				@Override
+				public void onClick(int i) {
+					StatisticsFragment.this.onBarClick(i);
+				}
+			});
+		}
+		return this.barGraph;
+	}
+
+	/*
+	 * FEED PLOTS WITH DATA
+	 */
+	public void setPieGraphData(PieGraph piegraph) {
+		this.currentData = this.getPieData();
+		if (this.currentData == null) {
+			this.currentData = new ArrayList<PlotComparisonItem>();
+		}
+
+		this.pieGraph.removeSlices();
+
+		for (PlotComparisonItem item : this.currentData) {
+			PieSlice slice = new PieSlice();
+			slice.setColor(item.getColor());
+			Double value2 = (Double) item.getValue2();
+			float v = value2.floatValue();
+			slice.setValue(v);
+			slice.setTitle(item.getTitle());
+			this.pieGraph.addSlice(slice);
+		}
+		this.pieGraph.invalidate();
+
+	}
+
+	public void setLineGraphData(LineGraph linegraph) {
+		this.currentData = this.getLineData();
+		if (this.currentData == null) {
+			this.currentData = new ArrayList<PlotComparisonItem>();
+		}
+
+		this.lineGraph.removeAllLines();
+		double rangeMax_Y = 0;
+		double rangeMin_Y = 0;
+
+		double rangeMax_X = 0;
+		double rangeMin_X = 0;
+
+		int count = 0;
+		for (PlotComparisonItem lineItem : this.currentData) {
+			ArrayList<PlotComparisonItem> data = lineItem.getOtherData();
+			int index = 0;
+			Line l = new Line();
+			int lineColor = lineItem.getColor();
+			l.setColor(lineColor);
+
+			for (PlotComparisonItem pointItem : data) {
+				LinePoint p = new LinePoint();
+				p.setX(pointItem.getValue1());
+				Double value2 = pointItem.getValue2();
+				p.setY(value2);
+				p.setColor(lineColor);
+				l.addPoint(p);
+				rangeMax_Y = Math.max(pointItem.getValue2(), rangeMax_Y);
+				rangeMax_X = Math.max(pointItem.getValue1(), rangeMax_X);
+
+				if (count != 0) {
+					rangeMin_Y = Math.min(pointItem.getValue2(), rangeMin_Y);
+					rangeMin_X = Math.min(pointItem.getValue1(), rangeMin_X);
+				} else {
+					rangeMin_Y = pointItem.getValue2();
+					rangeMin_X = pointItem.getValue1();
+				}
+				index++;
+				count++;
+			}
+			this.lineGraph.addLine(l);
+		}
+		// add a bit more space
+		rangeMax_Y++;
+		rangeMin_Y--;
+
+		boolean shouldUseDate = this.selectedCompareData.equals(COMPARE_TITLE_AttacksPerDate);
+		if (shouldUseDate) {
+			this.lineGraph.resetXLimits();
+
+			if (this.filter.hasBelowTimestamp()) {
+				rangeMax_X = Math.max(this.filter.belowTimestamp, rangeMax_X);
+			}
+			if (this.filter.hasAboveTimestamp()) {
+				rangeMin_X = Math.min(this.filter.aboveTimestamp, rangeMin_X);
+			}
+
+			double stepRange = (rangeMax_X - rangeMin_X) / (60 * 60 * 24 * 1000);
+			this.lineGraph.setxAxisStep(Math.max(1, (float) Math.min(stepRange, 4)));
+
+			this.lineGraph.setRangeX(rangeMin_X, rangeMax_X);
+
+			this.lineGraph.setConverter(new LineGraph.AxisDataConverter() {
+				@Override
+				public String convertDataForX_Position(double x) {
+					return StatisticsFragment.this.getDateAsDayString((long) x);
+				}
+
+				@Override
+				public String convertDataForY_Position(double y) {
+					return "" + (long) y;
+				}
+			});
+		} else {
+			this.lineGraph.setxAxisStep(12.f);
+			this.lineGraph.setRangeX(0, 24);
+			this.lineGraph.setConverter(null);
+		}
+
+		int maxY = (int) (rangeMax_Y - rangeMin_Y);
+		this.lineGraph.setYAxisStep(Math.min(maxY, 5));
+		int yStep = (int) this.lineGraph.getyAxisStep();
+		if ((maxY % yStep) != 0) {
+			maxY = maxY + (yStep - (maxY % yStep));
+		}
+		this.lineGraph.setRangeY(rangeMin_Y, rangeMin_Y + maxY);
+		this.lineGraph.setLineToFill(0);
+		this.lineGraph.invalidate();
+	}
+
+	public void setBarGraphData(BarGraph bargraph) {
+		this.currentData = this.getBarData();
+		if (this.currentData == null) {
+			this.currentData = new ArrayList<PlotComparisonItem>();
+		}
+
+		ArrayList<Bar> bars = new ArrayList<Bar>();
+
+		for (PlotComparisonItem item : this.currentData) {
+			Bar d = new Bar();
+			d.setColor(item.getColor());
+			Long value2 = item.getValue2().longValue();
+			d.setName("" + value2);
+			d.setValue(value2.floatValue());
+			bars.add(d);
+		}
+
+		this.barGraph.setBars(bars);
+		this.barGraph.invalidate();
+	}
+
+	/*
+	 * 
+	 * FETCH & ACTUALISE RECORD DATA
+	 */
+	public ArrayList<Record> getFetchedRecords() {
+		if (this.filter == null)
+			this.clearFilter();
+		return this.dbh.getRecordsForFilter(this.filter);
+	}
+
+	public void actualiseCurrentPlot() {
+		LinearLayout plotLayout = (LinearLayout) this.rootView.findViewById(R.id.plot_layout);
+		View plot = this.currentPlotView;
+		if (plot == null) {
+			this.currentPlotView = this.getPieGraphView();
+			plot = this.currentPlotView;
+		}
+		if (plot.getParent() != null && !plot.getParent().equals(plotLayout)) {
+			LinearLayout linLayout = (LinearLayout) plot.getParent();
+			linLayout.removeView(plot);
+			plot.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
+			plotLayout.addView(plot);
+		}
+
+		if (plot.getVisibility() == View.GONE)
+			plot.setVisibility(View.VISIBLE);
+
+		if (plot instanceof PieGraph) {
+			PieGraph pie = (PieGraph) plot;
+			this.setPieGraphData(pie);
+			// HIDE FILTER BUTTON
+			ImageButton filterButton = this.getFilterButton();
+			if (filterButton != null)
+				filterButton.setVisibility(View.GONE);
+		} else {
+			if (this.pieGraph != null) {
+				this.pieGraph.setVisibility(View.GONE);
+				if (this.pieGraph.getParent() != null) {
+					plotLayout.removeView(this.pieGraph);
+				}
+			}
+			// SHOW FILTER BUTTON
+			ImageButton filterButton = this.getFilterButton();
+			if (filterButton != null)
+				filterButton.setVisibility(View.VISIBLE);
+		}
+		if (plot instanceof BarGraph) {
+			BarGraph bar = (BarGraph) plot;
+			this.setBarGraphData(bar);
+		} else {
+			if (this.barGraph != null) {
+				this.barGraph.setVisibility(View.GONE);
+				if (this.barGraph.getParent() != null) {
+					plotLayout.removeView(this.barGraph);
+				}
+			}
+		}
+		if (plot instanceof LineGraph) {
+			LineGraph line = (LineGraph) plot;
+			this.setLineGraphData(line);
+		} else {
+			if (this.lineGraph != null) {
+				this.lineGraph.setVisibility(View.GONE);
+				if (this.lineGraph.getParent() != null) {
+					plotLayout.removeView(this.lineGraph);
+				}
+			}
+		}
+		plot.setVisibility(View.VISIBLE);
+		if (plot.getParent() == null) {
+			plotLayout.addView(plot);
+		}
+		this.actualiseLegendList();
+		this.currentPlotView.bringToFront();
+		this.currentPlotView.invalidate();
+	}
+
+	public ArrayList<PlotComparisonItem> getPieData() {
+		// DEFAULT
+		return this.attacksPerProtocols();
+	}
+
+	public ArrayList<PlotComparisonItem> getBarData() {
+		String protocol = this.getCurrentSelectedProtocol();
+
+		if (protocol.length() > 0) {
+			if (this.selectedCompareData.equals(COMPARE_TITLE_AttacksPerESSID)) {
+				return this.attacksPerESSID(protocol);
+			}
+			// DEFAULT
+			return this.attacksPerBSSID(protocol);
+		}
+		// Nothing available
+		return new ArrayList<PlotComparisonItem>();
+	}
+
+	public ArrayList<PlotComparisonItem> getLineData() {
+		return this.attacksPerTime();
+	}
+
+	/*
+	 * DATA SOURCE
+	 */
+
+	/* PROTOCOLS OVERVIEW */
+	public ArrayList<PlotComparisonItem> attacksPerProtocols() {
+		ArrayList<PlotComparisonItem> plotItems = new ArrayList<PlotComparisonItem>();
+		int index = 0;
+		for (String title : this.getSelectedProtocolTitles()) {
+			int attacksCount = this.dbh.getAttackPerProtocolCount(title);
+			if (attacksCount == 0)
+				continue;
+			PlotComparisonItem item = new PlotComparisonItem(title, this.getColor(index), 0., (double) attacksCount);
+			plotItems.add(item);
+			index++;
+		}
+		Collections.sort(plotItems, new Comparator<PlotComparisonItem>() {
+			@Override
+			public int compare(PlotComparisonItem s1, PlotComparisonItem s2) {
+				return s2.getValue2().compareTo(s1.getValue2());
+			}
+		});
+		return this.resizeData(plotItems);
+	}
+
+	/* LINE PLOT DATA */
+
+	public ArrayList<PlotComparisonItem> attacksPerTime() {
+		HashMap<String, HashMap<Long, ArrayList<Record>>> lineMap = new HashMap<String, HashMap<Long, ArrayList<Record>>>();
+
+		boolean shouldUseDate = this.selectedCompareData.equals(COMPARE_TITLE_AttacksPerDate);
+
+		ArrayList<Record> records = this.getFetchedRecords();
+		for (Record record : records) {
+			long timestamp = record.getTimestamp();
+			long time = 0;
+			if (shouldUseDate) {
+				time = this.getDateFromMilliseconds(timestamp);
+			} else {
+				time = this.getDayHourFromDate(timestamp);
+			}
+
+			// GET CORRECT MAP
+			HashMap<Long, ArrayList<Record>> recordMap;
+			String groupKey = record.getSsid();
+			if (lineMap.containsKey(groupKey)) {
+				recordMap = lineMap.get(record.getSsid());
+			} else {
+				recordMap = new HashMap<Long, ArrayList<Record>>();
+				lineMap.put(groupKey, recordMap);
+			}
+
+			// GET LIST OF RECORDS
+			ArrayList<Record> list;
+			if (recordMap.containsKey(time)) {
+				list = recordMap.get(time);
+			} else {
+				list = new ArrayList<Record>();
+				recordMap.put(time, list);
+			}
+			list.add(record);
+		}
+
+		ArrayList<PlotComparisonItem> plotItems = new ArrayList<PlotComparisonItem>();
+
+		int index = 0;
+		for (String groupKey : lineMap.keySet()) {
+			HashMap<Long, ArrayList<Record>> recordMap = lineMap.get(groupKey);
+			ArrayList<PlotComparisonItem> singleLineItems = new ArrayList<PlotComparisonItem>();
+
+			int numbOfAttacks = 0;
+			for (long time : recordMap.keySet()) {
+				ArrayList<Record> list = recordMap.get(time);
+				if (list.size() == 0)
+					continue;
+				PlotComparisonItem item = new PlotComparisonItem(this.getHourAsTimeString(time), 0, (double) time, (double) list.size());
+				singleLineItems.add(item);
+				numbOfAttacks += list.size();
+			}
+
+			Collections.sort(singleLineItems, new Comparator<PlotComparisonItem>() {
+				@Override
+				public int compare(PlotComparisonItem s1, PlotComparisonItem s2) {
+					return s1.getValue1().compareTo(s2.getValue1());
+				}
+			});
+
+			double itemValue = (((double) numbOfAttacks / (double) records.size()) * 100.);
+			PlotComparisonItem item = new PlotComparisonItem(groupKey, this.getColor(index), (double) numbOfAttacks, itemValue);
+			item.setOtherData(singleLineItems);
+			plotItems.add(item);
+			index++;
+		}
+		Collections.sort(plotItems, new Comparator<PlotComparisonItem>() {
+			@Override
+			public int compare(PlotComparisonItem s1, PlotComparisonItem s2) {
+				return s2.getValue2().compareTo(s1.getValue2());
+			}
+		});
+		return plotItems;
+	}
+
+	// BAR PLOT DATA
+	public ArrayList<PlotComparisonItem> attacksPerBSSID(String protocol) {
+		LogFilter filter = new LogFilter();
+		ArrayList<String> protocollist = new ArrayList<String>();
+		filter.setAboveTimestamp(this.filter.getAboveTimestamp());
+		filter.setBelowTimestamp(this.filter.getBelowTimestamp());
+		filter.setBSSIDs(this.filter.getBSSIDs());
+		protocollist.add(protocol);
+		filter.setProtocols(protocollist);
+
+		ArrayList<PlotComparisonItem> plotItems = new ArrayList<PlotComparisonItem>();
+
+		HashMap<String, Integer> recordMap = new HashMap<String, Integer>();
+		ArrayList<Record> records = this.dbh.getRecordsForFilter(filter);
+		for (Record record : records) {
+			int count = 0;
+			if (recordMap.containsKey(record.getBssid())) {
+				count = recordMap.get(record.getBssid());
+			}
+			count++;
+			recordMap.put(record.getBssid(), count);
+		}
+		int index = 0;
+		for (String key : recordMap.keySet()) {
+			double value = (double) recordMap.get(key);
+			if (value == 0.)
+				continue;
+			PlotComparisonItem item = new PlotComparisonItem(key, this.getColor(index), 0., value);
+			plotItems.add(item);
+			index++;
+		}
+		Collections.sort(plotItems, new Comparator<PlotComparisonItem>() {
+			@Override
+			public int compare(PlotComparisonItem s1, PlotComparisonItem s2) {
+				return s2.getValue2().compareTo(s1.getValue2());
+			}
+		});
+		return this.resizeData(plotItems);
+	}
+
+	public ArrayList<PlotComparisonItem> attacksPerESSID(String protocol) {
+		LogFilter filter = new LogFilter();
+		filter.setAboveTimestamp(this.filter.getAboveTimestamp());
+		filter.setBelowTimestamp(this.filter.getBelowTimestamp());
+		filter.setESSIDs(this.filter.getESSIDs());
+		ArrayList<String> protocollist = new ArrayList<String>();
+		protocollist.add(protocol);
+		filter.setProtocols(protocollist);
+
+		ArrayList<PlotComparisonItem> plotItems = new ArrayList<PlotComparisonItem>();
+
+		HashMap<String, Integer> recordMap = new HashMap<String, Integer>();
+		ArrayList<Record> records = this.dbh.getRecordsForFilter(filter);
+		for (Record record : records) {
+			int count = 0;
+			if (recordMap.containsKey(record.getSsid())) {
+				count = recordMap.get(record.getSsid());
+			}
+			count++;
+			recordMap.put(record.getSsid(), count);
+		}
+		int index = 0;
+		for (String key : recordMap.keySet()) {
+			double value = (double) recordMap.get(key);
+			if (value == 0.)
+				continue;
+			PlotComparisonItem item = new PlotComparisonItem(key, this.getColor(index), 0., value);
+			plotItems.add(item);
+			index++;
+		}
+		Collections.sort(plotItems, new Comparator<PlotComparisonItem>() {
+			@Override
+			public int compare(PlotComparisonItem s1, PlotComparisonItem s2) {
+				return s2.getValue2().compareTo(s1.getValue2());
+			}
+		});
+
+		return this.resizeData(plotItems);
+	}
+
+	private ArrayList<PlotComparisonItem> resizeData(ArrayList<PlotComparisonItem> plotItems) {
+		if (plotItems != null) {
+			if (plotItems.size() > MAX_NUMBER_OF_CHART_OBJECTS && MAX_NUMBER_OF_CHART_OBJECTS > 1) {
+				ArrayList<PlotComparisonItem> copy = new ArrayList<PlotComparisonItem>();
+				ArrayList<PlotComparisonItem> others = new ArrayList<PlotComparisonItem>();
+				double valueOfOthers = 0;
+
+				for (int i = 0; i < plotItems.size(); i++) {
+					if (i < MAX_NUMBER_OF_CHART_OBJECTS - 1) {
+						PlotComparisonItem item = plotItems.get(i);
+						item.setColor(this.getColor(i));
+						copy.add(plotItems.get(i));
+					} else {
+						PlotComparisonItem item = plotItems.get(i);
+						others.add(item);
+						valueOfOthers += item.getValue2();
+					}
+				}
+				PlotComparisonItem otherItem = new PlotComparisonItem(OTHER_CHART_TITLE, this.getOtherColor(), 0., valueOfOthers);
+				otherItem.setOtherData(others);
+				copy.add(otherItem);
+
+				Collections.sort(copy, new Comparator<PlotComparisonItem>() {
+					@Override
+					public int compare(PlotComparisonItem s1, PlotComparisonItem s2) {
+						return s2.getValue2().compareTo(s1.getValue2());
+					}
+				});
+
+				return copy;
+			}
+		}
+		return plotItems;
+	}
+
+	/*
+	 * FILTER STUFF
+	 */
+	private String getCurrentSelectedProtocol() {
+		ArrayList<String> protocolTitles = this.getSelectedProtocolTitles();
+		if (protocolTitles != null && protocolTitles.size() != 0) {
+			return protocolTitles.get(0);
+		}
+		return this.protocolTitles().get(0);
+	}
+
+	public ArrayList<String> protocolTitles() {
+		ArrayList<String> titles = new ArrayList<String>();
+		for (String protocol : this.getResources().getStringArray(R.array.protocols)) {
+			titles.add(protocol);
+		}
+		return titles;
+	}
+
+	public boolean[] selectedProtocols() {
+		ArrayList<String> protocols = this.protocolTitles();
+		boolean[] selected = new boolean[protocols.size()];
+
+		int i = 0;
+		for (String protocol : protocols) {
+			selected[i] = (this.filter.protocols.contains(protocol));
+			i++;
+		}
+		return selected;
+	}
+
+	public ArrayList<String> getSelectedProtocolTitles() {
+		ArrayList<String> knownProtocols = this.protocolTitles();
+		if (this.filter.hasProtocols()) {
+			ArrayList<String> titles = new ArrayList<String>();
+			int i = 0;
+			for (boolean b : this.selectedProtocols()) {
+				if (b) {
+					String title = knownProtocols.get(i);
+					titles.add(title);
+				}
+				i++;
+			}
+			return titles;
+		}
+		return this.protocolTitles();
+	}
+
+	/*
+	 * 
+	 * COLOR STUFF
+	 */
+
+	public int getOtherColor() {
+		return Color.argb(255, 80, 80, 80); // grey
+	}
+
+	public Integer getColor(int index) {
 		return ColorSequenceGenerator.getColorForIndex(index);
-    }
-
-
-    public LinearLayout getPlotLayout(){
-        if (this.rootView != null){
-            return (LinearLayout) this.rootView.findViewById(R.id.plot_layout);
-        } else {
-            return null;
-        }
-    }
-
-    /**
-     *
-     *  FILTER STUFF
-     *
-     * */
-    private boolean isFilterSetForTitle(String title){
-        if (title.equals(FILTER_MENU_TITLE_BSSID)){
-            return this.filter.hasBSSIDs();
-        }
-        if (title.equals(FILTER_MENU_TITLE_ESSID)){
-            return this.filter.hasESSIDs();
-        }
-        if (title.equals(FILTER_MENU_TITLE_PROTOCOLS)){
-            return (this.filter.getProtocols() != null  && this.filter.hasProtocols() && this.filter.getProtocols().size() != this.protocolTitles().size());
-        }
-        if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_BELOW)){
-            return this.filter.hasBelowTimestamp();
-        }
-        if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_ABOVE)){
-            return this.filter.hasAboveTimestamp();
-        }
-        return false;
-    }
-
-    private void clearFilter(){
-        if(filter == null) this.filter = new LogFilter();
-        this.filter.clear();
-    }
-
-    /*
-    *
-    *  DATE TRANSFORMATION
-    *
-    */
-    public long getDayHourFromDate(long timeInMillis){
+	}
+
+	public LinearLayout getPlotLayout() {
+		if (this.rootView != null) {
+			return (LinearLayout) this.rootView.findViewById(R.id.plot_layout);
+		} else {
+			return null;
+		}
+	}
+
+	/**
+	 * 
+	 * FILTER STUFF
+	 * 
+	 * */
+	private boolean isFilterSetForTitle(String title) {
+		if (title.equals(FILTER_MENU_TITLE_BSSID)) {
+			return this.filter.hasBSSIDs();
+		}
+		if (title.equals(FILTER_MENU_TITLE_ESSID)) {
+			return this.filter.hasESSIDs();
+		}
+		if (title.equals(FILTER_MENU_TITLE_PROTOCOLS)) {
+			return (this.filter.getProtocols() != null && this.filter.hasProtocols() && this.filter.getProtocols().size() != this.protocolTitles().size());
+		}
+		if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_BELOW)) {
+			return this.filter.hasBelowTimestamp();
+		}
+		if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_ABOVE)) {
+			return this.filter.hasAboveTimestamp();
+		}
+		return false;
+	}
+
+	private void clearFilter() {
+		if (filter == null)
+			this.filter = new LogFilter();
+		this.filter.clear();
+	}
 
-        Calendar calendar = Calendar.getInstance();
+	/*
+	 * 
+	 * DATE TRANSFORMATION
+	 */
+	public long getDayHourFromDate(long timeInMillis) {
 
-        calendar.setTimeInMillis (timeInMillis);
-        int hour    = calendar.get(Calendar.HOUR_OF_DAY);
-        int min     = calendar.get(Calendar.MINUTE);
+		Calendar calendar = Calendar.getInstance();
 
-        return hour;
+		calendar.setTimeInMillis(timeInMillis);
+		int hour = calendar.get(Calendar.HOUR_OF_DAY);
+		int min = calendar.get(Calendar.MINUTE);
 
-    }
-    public long getDateFromMilliseconds(long timeInMillis){
-        long millisInDay = 60 * 60 * 24 * 1000;
-        return (timeInMillis / millisInDay) * millisInDay;
+		return hour;
 
-    }
+	}
+
+	public long getDateFromMilliseconds(long timeInMillis) {
+		long millisInDay = 60 * 60 * 24 * 1000;
+		return (timeInMillis / millisInDay) * millisInDay;
+
+	}
 
-    /*
+	/*
     *
     * */
-    private String getHourAsTimeString(long hour) {
-        return "" + hour + ":00";
-    }
-
-    static final DateFormat dateFormat = new SimpleDateFormat("d.M.yyyy");
-    @SuppressLint("SimpleDateFormat")
-    private String getDateAsDayString(long timeStamp) {
-        try {
-            Date netDate = (new Date(timeStamp));
-            return dateFormat.format(netDate);
-        } catch (Exception ex) {
-            return "xx";
-        }
-    }
-
-    @SuppressLint("SimpleDateFormat")
-    private String getDateAsString(long timeStamp) {
-
-        try {
-            DateFormat sdf = new SimpleDateFormat("H:mm  dd/MM/yyyy");
-            Date netDate = (new Date(timeStamp));
-            return sdf.format(netDate);
-        } catch (Exception ex) {
-            return "xx";
-        }
-    }
-
-
-    /**
-     * USERINTERACTION
-     */
-    private void userTappedOnLegendItem(int index){
-        if (index < this.currentData.size()){
-            PlotComparisonItem item = this.currentData.get(index);
-            ArrayList<String> selectedData;
-            String sortKey = null;
-            selectedData = new ArrayList<String>();
-
-            if (item.getOtherData() == null){
-                selectedData.add(item.getTitle());
-            } else {
-                for (PlotComparisonItem other : item.getOtherData()){
-                    selectedData.add(other.getTitle());
-                }
-            }
-            LogFilter filter = new LogFilter();
-            if (this.currentPlotView instanceof PieGraph){
-                filter.setProtocols(selectedData);
-            }
-            if (this.currentPlotView instanceof BarGraph){
-
-                if (this.selectedCompareData.equals(COMPARE_TITLE_AttacksPerESSID)){
-                    filter.setESSIDs(selectedData);
-                    sortKey = "ESSID";
-                } else {
-                    filter.setBSSIDs(selectedData);
-                    sortKey = "BSSID";
-                }
-                ArrayList<String> currentSelectedProtocol = new ArrayList<String>();
-                currentSelectedProtocol.add(this.getCurrentSelectedProtocol());
-                filter.setProtocols(currentSelectedProtocol);
-            }
-            if (this.currentPlotView instanceof  LineGraph){
-                selectedData = new ArrayList<String>();
-                selectedData.add(item.getTitle());
-                filter.setESSIDs(selectedData);
-                filter.setProtocols(this.filter.getProtocols());
-                sortKey = "ESSID";
-            }
-
-            if (this.filter.hasATimestamp()){
-                filter.setAboveTimestamp(this.filter.getAboveTimestamp());
-                filter.setBelowTimestamp(this.filter.getBelowTimestamp());
-            }
-
-            this.pushRecordOverviewForFilter(filter, sortKey);
-        }
-    }
-
-    public void onSliceClick(int index){
-
-    }
-    public void onBarClick(int index){
-        this.userTappedOnLegendItem(index);
-    }
-
-    private void pushRecordOverviewForFilter(LogFilter filter, String sortKey){
-
-        FragmentManager fm = this.getActivity().getFragmentManager();
-
-        if (fm != null){
-            RecordOverviewFragment newFragment = new RecordOverviewFragment();
-	        newFragment.setUpNavigatible(true);
-            newFragment.setFilter(filter);
-
-            if (sortKey != null && sortKey.length() != 0) newFragment.setGroupKey(sortKey);
-
-            MainActivity.getInstance().injectFragment(newFragment);
-
-        }
-
-    }
+	private String getHourAsTimeString(long hour) {
+		return "" + hour + ":00";
+	}
+
+	static final DateFormat dateFormat = new SimpleDateFormat("d.M.yyyy");
+
+	@SuppressLint("SimpleDateFormat")
+	private String getDateAsDayString(long timeStamp) {
+		try {
+			Date netDate = (new Date(timeStamp));
+			return dateFormat.format(netDate);
+		} catch (Exception ex) {
+			return "xx";
+		}
+	}
+
+	@SuppressLint("SimpleDateFormat")
+	private String getDateAsString(long timeStamp) {
+
+		try {
+			DateFormat sdf = new SimpleDateFormat("H:mm  dd/MM/yyyy");
+			Date netDate = (new Date(timeStamp));
+			return sdf.format(netDate);
+		} catch (Exception ex) {
+			return "xx";
+		}
+	}
+
+	/**
+	 * USERINTERACTION
+	 */
+	private void userTappedOnLegendItem(int index) {
+		if (index < this.currentData.size()) {
+			PlotComparisonItem item = this.currentData.get(index);
+			ArrayList<String> selectedData;
+			String sortKey = null;
+			selectedData = new ArrayList<String>();
+
+			if (item.getOtherData() == null) {
+				selectedData.add(item.getTitle());
+			} else {
+				for (PlotComparisonItem other : item.getOtherData()) {
+					selectedData.add(other.getTitle());
+				}
+			}
+			LogFilter filter = new LogFilter();
+			if (this.currentPlotView instanceof PieGraph) {
+				filter.setProtocols(selectedData);
+			}
+			if (this.currentPlotView instanceof BarGraph) {
+
+				if (this.selectedCompareData.equals(COMPARE_TITLE_AttacksPerESSID)) {
+					filter.setESSIDs(selectedData);
+					sortKey = "ESSID";
+				} else {
+					filter.setBSSIDs(selectedData);
+					sortKey = "BSSID";
+				}
+				ArrayList<String> currentSelectedProtocol = new ArrayList<String>();
+				currentSelectedProtocol.add(this.getCurrentSelectedProtocol());
+				filter.setProtocols(currentSelectedProtocol);
+			}
+			if (this.currentPlotView instanceof LineGraph) {
+				selectedData = new ArrayList<String>();
+				selectedData.add(item.getTitle());
+				filter.setESSIDs(selectedData);
+				filter.setProtocols(this.filter.getProtocols());
+				sortKey = "ESSID";
+			}
+
+			if (this.filter.hasATimestamp()) {
+				filter.setAboveTimestamp(this.filter.getAboveTimestamp());
+				filter.setBelowTimestamp(this.filter.getBelowTimestamp());
+			}
+
+			this.pushRecordOverviewForFilter(filter, sortKey);
+		}
+	}
 
+	public void onSliceClick(int index) {
+
+	}
+
+	public void onBarClick(int index) {
+		this.userTappedOnLegendItem(index);
+	}
+
+	private void pushRecordOverviewForFilter(LogFilter filter, String sortKey) {
+
+		FragmentManager fm = this.getActivity().getFragmentManager();
+
+		if (fm != null) {
+			RecordOverviewFragment newFragment = new RecordOverviewFragment();
+			newFragment.setUpNavigatible(true);
+			newFragment.setFilter(filter);
+
+			if (sortKey != null && sortKey.length() != 0)
+				newFragment.setGroupKey(sortKey);
+
+			MainActivity.getInstance().injectFragment(newFragment);
+
+		}
+
+	}
 
 }

+ 8 - 7
src/de/tudarmstadt/informatik/hostage/ui2/fragment/ThreatMapFragment.java

@@ -1,5 +1,12 @@
 package de.tudarmstadt.informatik.hostage.ui2.fragment;
 
+import static com.google.android.gms.common.GooglePlayServicesUtil.getErrorDialog;
+import static com.google.android.gms.common.GooglePlayServicesUtil.isGooglePlayServicesAvailable;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
 import android.app.Activity;
 import android.app.AlertDialog;
 import android.app.Fragment;
@@ -29,19 +36,13 @@ import com.google.android.gms.maps.model.LatLng;
 import com.google.android.gms.maps.model.Marker;
 import com.google.android.gms.maps.model.MarkerOptions;
 
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
-
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
+import de.tudarmstadt.informatik.hostage.deprecated.UglyDbHelper;
 import de.tudarmstadt.informatik.hostage.logging.Record;
-import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
 import de.tudarmstadt.informatik.hostage.ui.LogFilter;
 import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
 
-import static com.google.android.gms.common.GooglePlayServicesUtil.*;
-
 /**
  * ThreatMapFragment
  *

+ 19 - 10
src/de/tudarmstadt/informatik/hostage/wrapper/Packet.java

@@ -1,13 +1,17 @@
 package de.tudarmstadt.informatik.hostage.wrapper;
 
+import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
+
 /**
  * Wrapper class for the payload of a network packet.
  * 
  * @author Mihai Plasoianu
+ * @author Wulf Pfeiffer
  */
 public class Packet {
 
 	private byte[] payload;
+	private String protocol;
 
 	/**
 	 * Constructs Packet from byte[]
@@ -15,8 +19,9 @@ public class Packet {
 	 * @param payload
 	 *            The byte[] payload
 	 */
-	public Packet(byte[] payload) {
+	public Packet(byte[] payload, String protocol) {
 		this.payload = payload;
+		this.protocol = protocol;
 	}
 
 	/**
@@ -25,8 +30,9 @@ public class Packet {
 	 * @param payload
 	 *            The String payload
 	 */
-	public Packet(String payload) {
+	public Packet(String payload, String protocol) {
 		this.payload = payload.getBytes();
+		this.protocol = protocol;
 	}
 
 	/**
@@ -40,20 +46,23 @@ public class Packet {
 
 	/**
 	 * Returns a String representation of the payload.
+	 * If the payload contains a ASCII character the whole
+	 * String will be represented as a String of a byte values.
+	 * E.g.: the byte[] {0x01, 0x4A, 0x03} would look like
+	 * the String "01, 4A, 03".
+	 * Otherwise a normal String will be created with the payload.
 	 * 
 	 * @return String representation.
 	 */
 	@Override
 	public String toString() {
-		StringBuilder builder = new StringBuilder(payload.length);
-		for (int i = 0; i < payload.length; ++i) {
-			if (payload[i] < 32) {
-				builder.append("{0x").append(payload[i]).append("}");
-			} else {
-				builder.append(Character.toString((char) payload[i]));
-			}
+		if (protocol.equals("FTP") 
+				|| protocol.equals("HTTP") 
+				|| protocol.equals("HTTPS")) {
+			return new String(payload);
+		} else {
+			return HelperUtils.bytesToHexString(payload);
 		}
-		return builder.toString();
 	}
 
 }

Some files were not shown because too many files changed in this diff