ViewLog.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. package de.tudarmstadt.informatik.hostage.ui;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.net.InetAddress;
  5. import java.text.SimpleDateFormat;
  6. import java.util.ArrayList;
  7. import java.util.Arrays;
  8. import java.util.Calendar;
  9. import java.util.Date;
  10. import java.util.Locale;
  11. import org.apache.http.HttpResponse;
  12. import org.apache.http.client.HttpClient;
  13. import org.apache.http.client.methods.HttpPost;
  14. import org.apache.http.entity.StringEntity;
  15. import de.tudarmstadt.informatik.hostage.R;
  16. import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
  17. import de.tudarmstadt.informatik.hostage.logging.Logger;
  18. import de.tudarmstadt.informatik.hostage.logging.Record;
  19. import de.tudarmstadt.informatik.hostage.logging.SQLLogger;
  20. import android.annotation.SuppressLint;
  21. import android.app.Activity;
  22. import android.app.AlertDialog;
  23. import android.app.DatePickerDialog;
  24. import android.app.Dialog;
  25. import android.app.NotificationManager;
  26. import android.app.PendingIntent;
  27. import android.content.Context;
  28. import android.content.DialogInterface;
  29. import android.content.Intent;
  30. import android.content.SharedPreferences;
  31. import android.content.SharedPreferences.Editor;
  32. import android.os.Build;
  33. import android.os.Bundle;
  34. import android.os.Environment;
  35. import android.preference.PreferenceManager;
  36. import android.support.v4.app.NotificationCompat;
  37. import android.support.v4.app.TaskStackBuilder;
  38. import android.util.Log;
  39. import android.view.Gravity;
  40. import android.view.Menu;
  41. import android.view.MenuItem;
  42. import android.view.View;
  43. import android.widget.DatePicker;
  44. import android.widget.TableLayout;
  45. import android.widget.TableRow;
  46. import android.widget.TextView;
  47. import android.widget.TimePicker;
  48. import android.widget.Toast;
  49. /**
  50. * ViewLog shows Statistics about the recorded Attacks.
  51. * It also offers the user several options to perform actions with the database.
  52. * This includes:<br>
  53. * - show records,<br>
  54. * - export records,<br>
  55. * - upload records,<br>
  56. * - and delete records.
  57. * @author Lars Pandikow
  58. */
  59. public class ViewLog extends Activity {
  60. public static final int JSON = 0x01;
  61. private final SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm", Locale.US);
  62. private Logger logger;
  63. private SharedPreferences pref;
  64. private Editor editor;
  65. @Override
  66. protected void onCreate(Bundle savedInstanceState) {
  67. super.onCreate(savedInstanceState);
  68. setContentView(R.layout.activity_viewlog);
  69. logger = new SQLLogger(this);
  70. pref = PreferenceManager.getDefaultSharedPreferences(this);
  71. editor = pref.edit();
  72. initStatistic();
  73. }
  74. @Override
  75. public boolean onCreateOptionsMenu(Menu menu) {
  76. getMenuInflater().inflate(R.menu.main, menu);
  77. return true;
  78. }
  79. @Override
  80. public boolean onOptionsItemSelected(MenuItem item) {
  81. // Handle item selection
  82. switch (item.getItemId()) {
  83. case R.id.action_settings:
  84. startActivity(new Intent(this, SettingsActivity.class));
  85. break;
  86. case R.id.action_about:
  87. startActivity(new Intent(this, AboutActivity.class));
  88. break;
  89. default:
  90. }
  91. return super.onOptionsItemSelected(item);
  92. }
  93. /**
  94. * Creates a Dialog to choose export format.
  95. * Then calls {@link ViewLog#exportDatabase(int)}
  96. * @param view View elements which triggers the method call.
  97. */
  98. public void exportDatabase(View view) {
  99. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  100. builder.setTitle(R.string.export_dialog_title);
  101. builder.setItems(R.array.format, new DialogInterface.OnClickListener() {
  102. public void onClick(DialogInterface dialog, int position) {
  103. exportDatabase(position);
  104. }
  105. });
  106. builder.create();
  107. builder.show();
  108. }
  109. /**
  110. * Exports all records in a given format. Before exporting checks export location from preferences.
  111. * @param format Integer coded export format
  112. * @see Record#toString(int)
  113. */
  114. private void exportDatabase(int format){
  115. try {
  116. FileOutputStream log;
  117. String filename = "hostage_" + format + "_" + System.currentTimeMillis() + ".log";
  118. boolean externalStorage = pref.getBoolean("pref_external_storage", false);
  119. String externalLocation = pref.getString("pref_external_location", "");
  120. if(externalStorage){
  121. String root = Environment.getExternalStorageDirectory().toString();
  122. if(root != null && HelperUtils.isExternalStorageWritable()){
  123. File dir = new File(root + externalLocation);
  124. dir.mkdirs();
  125. File file = new File(dir, filename);
  126. log = new FileOutputStream(file);
  127. }else {
  128. Toast.makeText(this, "Could not write to SD Card", Toast.LENGTH_SHORT).show();
  129. return;
  130. }
  131. } else{
  132. log = this.openFileOutput("hostage_" + format + "_" + System.currentTimeMillis() + ".log", Context.MODE_PRIVATE);
  133. }
  134. ArrayList<Record> records = logger.getAllRecords();
  135. for(Record record : records){
  136. log.write((record.toString(format) + "\n").getBytes());
  137. }
  138. log.flush();
  139. log.close();
  140. Toast.makeText(this, externalStorage ? filename + " saved on external memory! " + externalLocation : filename + " saved on internal memory!", Toast.LENGTH_LONG).show();
  141. } catch (Exception e) {
  142. Toast.makeText(this, "Could not write to SD Card", Toast.LENGTH_SHORT).show();
  143. e.printStackTrace();
  144. }
  145. }
  146. /**
  147. * Uploads a JSON Representation of each attack to a server, specified in the preferences.<br>
  148. * The method only uploads information about attacks that have net been uploaded yet.<br>
  149. * The local and remote IP of each record will be replaced with the external IP of then device at the time of the upload.
  150. * For the Upload it uses a HttpPost with a HttpsClient, which does not validate any certificates.<br>
  151. * The Upload runs in its own Thread.<br>
  152. * While uploading the method also creates a notification to inform the user about the status of the upload.
  153. * @param view View elements which triggers the method call.
  154. * @see de.tudarmstadt.informatik.hostage.net.MySSLSocketFactory
  155. */
  156. public void uploadDatabase(View view){
  157. //Create a Notification
  158. final NotificationCompat.Builder builder;
  159. final NotificationManager mNotifyManager;
  160. final int lastUploadedAttackId = pref.getInt("LAST_UPLOADED_ATTACK_ID", -1);
  161. int currentAttackId = pref.getInt("ATTACK_ID_COUNTER", 0);
  162. // Check if there are new records to upload
  163. if(lastUploadedAttackId == currentAttackId -1){
  164. // Inform user that no upload is necessary
  165. Toast.makeText(this, "All data have already been uploaded.", Toast.LENGTH_SHORT).show();
  166. return;
  167. }
  168. // Build and show Upload Notification in notification bar
  169. builder = new NotificationCompat.Builder(this)
  170. .setContentTitle(this.getString(R.string.app_name))
  171. .setContentText("Upload in progress...")
  172. .setTicker("Uploading Data...")
  173. .setSmallIcon(R.drawable.ic_launcher)
  174. .setWhen(System.currentTimeMillis());
  175. TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
  176. stackBuilder.addParentStack(MainActivity.class);
  177. stackBuilder.addNextIntent(new Intent());
  178. PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
  179. PendingIntent.FLAG_UPDATE_CURRENT);
  180. builder.setContentIntent(resultPendingIntent);
  181. builder.setAutoCancel(true);
  182. builder.setOnlyAlertOnce(false);
  183. mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  184. mNotifyManager.notify(2, builder.build());
  185. // Create a new Thread for upload
  186. new Thread(new Runnable() {
  187. public void run() {
  188. // Create a https client. Uses MySSLSocketFactory to accept all certificates
  189. HttpClient httpclient = HelperUtils.createHttpClient();
  190. // get RecordList
  191. ArrayList<Record> recordList = logger.getRecordOfEachAttack(lastUploadedAttackId);
  192. final int progressMax = recordList.size();
  193. Log.i("SQLLogger", "Logs to upload: " + progressMax);
  194. HttpPost httppost;
  195. int progressBarStatus = 0;
  196. int retry_counter = 0;
  197. while(progressBarStatus < progressMax){
  198. Record record = recordList.get(progressBarStatus);
  199. if(record.getExternalIP() != null){
  200. Log.i("SQLLogger", "Uploading log: " + progressBarStatus);
  201. try {
  202. // Create HttpPost
  203. httppost = new HttpPost(pref.getString("pref_upload", "https://ssi.cased.de"));
  204. // Create JSON String of Record
  205. StringEntity se = new StringEntity(record.toString(JSON));
  206. httppost.setEntity(se);
  207. // Execute HttpPost
  208. HttpResponse response = httpclient.execute(httppost);
  209. Log.i("SQLLogger", "Statuscode of log " + progressBarStatus + ": " + " " + response.getStatusLine().getReasonPhrase());
  210. Log.i("SQLLogger", "Statuscode of log " + progressBarStatus + ": " + " " + response.getStatusLine().getStatusCode());
  211. retry_counter = 0;
  212. // Update Notification progress bar
  213. progressBarStatus++;
  214. builder.setProgress(progressMax, progressBarStatus, false);
  215. // Update the progress bar
  216. mNotifyManager.notify(2, builder.build());
  217. } catch (Exception e) {
  218. retry_counter++;
  219. if(retry_counter == 3){
  220. retry_counter = 0;
  221. progressBarStatus++;
  222. Log.i("SQLLogger", "Upload of log " + progressBarStatus + " failed. Continue with next log");
  223. } else {
  224. Log.i("SQLLogger", "Upload of log " + progressBarStatus + " failed...retry");
  225. }
  226. e.printStackTrace();
  227. }
  228. }
  229. }
  230. if(progressBarStatus == progressMax){
  231. // When the loop is finished, updates the notification
  232. builder.setContentText("Upload complete")
  233. .setTicker("Upload complete")
  234. // Removes the progress bar
  235. .setProgress(0,0,false);
  236. mNotifyManager.notify(2, builder.build());
  237. }
  238. }}).start();
  239. editor.putInt("LAST_UPLOADED_ATTACK_ID",currentAttackId - 1);
  240. editor.commit();
  241. }
  242. /**
  243. * Starts a ViewLogTable Activity.
  244. * @param view View elements which triggers the method call.
  245. * @see ViewLogTable
  246. */
  247. public void showLog(View view) {
  248. startActivity(new Intent(this, ViewLogTable.class));
  249. }
  250. /**
  251. * Creates a Dialog that lets the user decide which criteria he want to use to delete records.
  252. * Then calls the corresponding method.<br>
  253. * The possible criteria are coded in /res/values/arrays.xml
  254. * To add a criteria add a String to the array and extend the switch statement.
  255. * @param view View elements which triggers the method call.
  256. * @see ViewLog#deleteByBSSID()
  257. * @see ViewLog#deleteByDate()
  258. * @see ViewLog#deleteAll()
  259. */
  260. public void deleteLog(View view) {
  261. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  262. builder.setTitle(R.string.delete_dialog_title);
  263. builder.setItems(R.array.delete_criteria,
  264. new DialogInterface.OnClickListener() {
  265. public void onClick(DialogInterface dialog, int position) {
  266. switch (position) {
  267. case 0:
  268. deleteByBSSID();
  269. break;
  270. case 1:
  271. deleteByDate();
  272. break;
  273. case 2:
  274. deleteAll();
  275. }
  276. }
  277. });
  278. builder.create();
  279. builder.show();
  280. }
  281. /**
  282. * Shows a List with all recorded BSSIDs.
  283. * If a BSSID is selected the method calls {@link Logger#deleteByBSSID(String)} to delete all records with the chosen BSSID
  284. * @see Logger#deleteByBSSID
  285. */
  286. private void deleteByBSSID() {
  287. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  288. final String[] bssidArray = logger.getAllBSSIDS();
  289. final String[] strings = new String[bssidArray.length];
  290. for(int i = 0; i < bssidArray.length; i++){
  291. strings[i] = bssidArray[i] + " (" + logger.getSSID(bssidArray[i]) +")";
  292. }
  293. builder.setTitle(R.string.delete_dialog_title);
  294. builder.setItems(strings, new DialogInterface.OnClickListener() {
  295. @SuppressLint("NewApi")
  296. public void onClick(DialogInterface dialog, int position) {
  297. logger.deleteByBSSID(bssidArray[position]);
  298. Toast.makeText(
  299. getApplicationContext(),
  300. "All entries with bssid '" + bssidArray[position]
  301. + "' deleted.", Toast.LENGTH_SHORT).show();
  302. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
  303. recreate();
  304. } else {
  305. Intent intent = getIntent();
  306. finish();
  307. startActivity(intent);
  308. }
  309. }
  310. });
  311. builder.create();
  312. builder.show();
  313. }
  314. /**
  315. * Creates a DatePicking Dialog where the user can choose a date. Afterwards {@link ViewLog#deleteByDate(int, int, int)} is called.
  316. */
  317. private void deleteByDate() {
  318. showDialog(0);
  319. }
  320. @Override
  321. protected Dialog onCreateDialog(int id) {
  322. switch (id) {
  323. case 0:
  324. final Calendar cal = Calendar.getInstance();
  325. int pYear = cal.get(Calendar.YEAR);
  326. int pMonth = cal.get(Calendar.MONTH);
  327. int pDay = cal.get(Calendar.DAY_OF_MONTH);
  328. return new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
  329. public void onDateSet(DatePicker view, int year, int monthOfYear,
  330. int dayOfMonth) {deleteByDate(year, monthOfYear, dayOfMonth);}}
  331. , pYear, pMonth, pDay);
  332. }
  333. return null;
  334. }
  335. /**
  336. * Shows a Dialog with the given date and ask him to confirm deleting records that are older than the shown date.
  337. * When the user confirms {@link Logger#deleteByDate(long)} is called with a long representation of the Date.
  338. * If the user cancels the Dialog nothing happens and the dialog disappears.
  339. * @param year
  340. * @param monthOfYear
  341. * @param dayOfMonth
  342. */
  343. private void deleteByDate(int year, int monthOfYear, int dayOfMonth) {
  344. TimePicker timePicker = new TimePicker(this);
  345. final Calendar calendar = Calendar.getInstance();
  346. calendar.set(year, monthOfYear, dayOfMonth,
  347. timePicker.getCurrentHour(), timePicker.getCurrentMinute(), 0);
  348. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  349. builder.setTitle(R.string.dialog_clear_database_date)
  350. .setMessage(sdf.format(calendar.getTime()))
  351. .setPositiveButton(R.string.delete,
  352. new DialogInterface.OnClickListener() {
  353. @SuppressLint("NewApi")
  354. public void onClick(DialogInterface dialog, int id) {
  355. long time = calendar.getTimeInMillis();
  356. // Delete Data
  357. logger.deleteByDate(time);
  358. Toast.makeText(getApplicationContext(),
  359. "Data sets deleted!",
  360. Toast.LENGTH_SHORT).show();
  361. // Recreate the activity
  362. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
  363. recreate();
  364. } else {
  365. Intent intent = getIntent();
  366. finish();
  367. startActivity(intent);
  368. }
  369. }
  370. })
  371. .setNegativeButton(R.string.cancel,
  372. new DialogInterface.OnClickListener() {
  373. public void onClick(DialogInterface dialog, int id) {
  374. // User cancelled the dialog
  375. }
  376. });
  377. // Create the AlertDialog object
  378. builder.create();
  379. builder.show();
  380. }
  381. /**
  382. * Shows a Dialog to confirm that the database should be cleared.
  383. * If confirmed {@link SQLLogger#clearData()} is called.
  384. * @see Logger#clearData()
  385. */
  386. private void deleteAll() {
  387. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  388. builder.setMessage(R.string.dialog_clear_database)
  389. .setPositiveButton(R.string.clear,
  390. new DialogInterface.OnClickListener() {
  391. @SuppressLint("NewApi")
  392. public void onClick(DialogInterface dialog, int id) {
  393. // Clear all Data
  394. logger.clearData();
  395. editor.putInt("ATTACK_ID_COUNTER", 0);
  396. editor.putInt("LAST_UPLOADED_ATTACK_ID", -1);
  397. editor.commit();
  398. Toast.makeText(getApplicationContext(),
  399. "Database cleared!", Toast.LENGTH_SHORT)
  400. .show();
  401. // Recreate the activity
  402. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
  403. recreate();
  404. } else {
  405. Intent intent = getIntent();
  406. finish();
  407. startActivity(intent);
  408. }
  409. }
  410. })
  411. .setNegativeButton(R.string.cancel,
  412. new DialogInterface.OnClickListener() {
  413. public void onClick(DialogInterface dialog, int id) {
  414. // User cancelled the dialog
  415. }
  416. });
  417. // Create the AlertDialog object
  418. builder.create();
  419. builder.show();
  420. }
  421. /**
  422. * Initializes the Statistics. Creates a table row for every protocol and checks the dabase for the attack count.
  423. * Calls {@link ViewLog#setFirstAndLastAttack()} to set the TextViews.
  424. * @see Logger#getAttackCount()
  425. * @see Logger#getAttackPerProtokolCount(String)
  426. */
  427. private void initStatistic() {
  428. TableLayout table = (TableLayout) findViewById(R.id.layoutContainer);
  429. ArrayList<String> protocols = new ArrayList<String>();
  430. protocols.add("Total");
  431. protocols.addAll(Arrays.asList(getResources().getStringArray(
  432. R.array.protocols)));
  433. for (String protocol : protocols) {
  434. TableRow row = new TableRow(this);
  435. TextView protocolName = new TextView(this);
  436. protocolName.setBackgroundResource(R.color.dark_grey);
  437. protocolName.setText(protocol);
  438. protocolName.setTextAppearance(this,
  439. android.R.style.TextAppearance_Medium);
  440. protocolName.setPadding(6, 0, 0, 0);
  441. row.addView(protocolName);
  442. TextView value = new TextView(this);
  443. value.setBackgroundResource(R.color.light_grey);
  444. value.setTextAppearance(this, android.R.style.TextAppearance_Medium);
  445. value.setGravity(Gravity.RIGHT);
  446. value.setPadding(3, 0, 3, 0);
  447. row.addView(value);
  448. if (protocol.equals("Total")) {
  449. value.setText("" + logger.getAttackCount());
  450. } else {
  451. value.setText("" + logger.getAttackPerProtokolCount(protocol));
  452. }
  453. table.addView(row);
  454. }
  455. setFirstAndLastAttack();
  456. }
  457. /**
  458. * Sets the TextViews for first and last attack.
  459. * @see Logger#getSmallestAttackId()
  460. * @see Logger#getHighestAttackId()
  461. * @see Logger#getRecordOfAttackId(long)
  462. */
  463. private void setFirstAndLastAttack() {
  464. Record firstAttack = logger.getRecordOfAttackId(logger.getSmallestAttackId());
  465. Record lastAttack = logger.getRecordOfAttackId(logger.getHighestAttackId());
  466. if (firstAttack != null) {
  467. Date resultdate = new Date(firstAttack.getTimestamp());
  468. TextView text = (TextView) findViewById(R.id.textFirstAttackValue);
  469. text.setText(sdf.format(resultdate));
  470. text = (TextView) findViewById(R.id.textLastAttackValue);
  471. resultdate = new Date(lastAttack.getTimestamp());
  472. text.setText(sdf.format(resultdate));
  473. } else {
  474. TextView text = (TextView) findViewById(R.id.textFirstAttackValue);
  475. text.setText("-");
  476. text = (TextView) findViewById(R.id.textLastAttackValue);
  477. text.setText("-");
  478. }
  479. }
  480. }