ViewLog.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. private final SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm", Locale.US);
  61. private Logger logger;
  62. private SharedPreferences pref;
  63. private Editor editor;
  64. @Override
  65. protected void onCreate(Bundle savedInstanceState) {
  66. super.onCreate(savedInstanceState);
  67. setContentView(R.layout.activity_viewlog);
  68. logger = new SQLLogger(this);
  69. pref = PreferenceManager.getDefaultSharedPreferences(this);
  70. editor = pref.edit();
  71. initStatistic();
  72. }
  73. @Override
  74. public boolean onCreateOptionsMenu(Menu menu) {
  75. getMenuInflater().inflate(R.menu.main, menu);
  76. return true;
  77. }
  78. @Override
  79. public boolean onOptionsItemSelected(MenuItem item) {
  80. // Handle item selection
  81. switch (item.getItemId()) {
  82. case R.id.action_settings:
  83. startActivity(new Intent(this, SettingsActivity.class));
  84. break;
  85. case R.id.action_about:
  86. startActivity(new Intent(this, AboutActivity.class));
  87. break;
  88. default:
  89. }
  90. return super.onOptionsItemSelected(item);
  91. }
  92. /**
  93. * Creates a Dialog to choose export format.
  94. * Then calls {@link ViewLog#exportDatabase(int)}
  95. * @param view View elements which triggers the method call.
  96. */
  97. public void exportDatabase(View view) {
  98. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  99. builder.setTitle(R.string.export_dialog_title);
  100. builder.setItems(R.array.format, new DialogInterface.OnClickListener() {
  101. public void onClick(DialogInterface dialog, int position) {
  102. exportDatabase(position);
  103. }
  104. });
  105. builder.create();
  106. builder.show();
  107. }
  108. /**
  109. * Exports all records in a given format. Before exporting checks export location from preferences.
  110. * @param format Integer coded export format
  111. * @see Record#toString(int)
  112. */
  113. private void exportDatabase(int format){
  114. try {
  115. FileOutputStream log;
  116. String filename = "hostage_" + format + "_" + System.currentTimeMillis() + ".log";
  117. boolean externalStorage = pref.getBoolean("pref_external_storage", false);
  118. String externalLocation = pref.getString("pref_external_location", "");
  119. if(externalStorage){
  120. String root = Environment.getExternalStorageDirectory().toString();
  121. if(root != null && HelperUtils.isExternalStorageWritable()){
  122. File dir = new File(root + externalLocation);
  123. dir.mkdirs();
  124. File file = new File(dir, filename);
  125. log = new FileOutputStream(file);
  126. }else {
  127. Toast.makeText(this, "Could not write to SD Card", Toast.LENGTH_SHORT).show();
  128. return;
  129. }
  130. } else{
  131. log = this.openFileOutput("hostage_" + format + "_" + System.currentTimeMillis() + ".log", Context.MODE_PRIVATE);
  132. }
  133. ArrayList<Record> records = logger.getAllRecords();
  134. for(Record record : records){
  135. log.write((record.toString(format) + "\n").getBytes());
  136. }
  137. log.flush();
  138. log.close();
  139. Toast.makeText(this, externalStorage ? filename + " saved on external memory! " + externalLocation : filename + " saved on internal memory!", Toast.LENGTH_LONG).show();
  140. } catch (Exception e) {
  141. Toast.makeText(this, "Could not write to SD Card", Toast.LENGTH_SHORT).show();
  142. e.printStackTrace();
  143. }
  144. }
  145. /**
  146. * Uploads a JSON Representation of each attack to a server, specified in the preferences.<br>
  147. * The method only uploads information about attacks that have net been uploaded yet.<br>
  148. * The local and remote IP of each record will be replaced with the external IP of then device at the time of the upload.
  149. * For the Upload it uses a HttpPost with a HttpsClient, which does not validate any certificates.<br>
  150. * The Upload runs in its own Thread.<br>
  151. * While uploading the method also creates a notification to inform the user about the status of the upload.<br>
  152. * <b>Only uploads Records with a external IP that is not null!
  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. final Context context = this;
  186. // Create a new Thread for upload
  187. new Thread(new Runnable() {
  188. public void run() {
  189. // get RecordList
  190. ArrayList<Record> recordList = logger.getRecordOfEachAttack(lastUploadedAttackId);
  191. final int progressMax = recordList.size();
  192. Log.i("SQLLogger", "Logs to upload: " + progressMax);
  193. int progressBarStatus = 0;
  194. int retry_counter = 0;
  195. while(progressBarStatus < progressMax){
  196. Record record = recordList.get(progressBarStatus);
  197. // Only upload records with a saved external ip
  198. if(record.getExternalIP() != null){
  199. retry_counter = 0;
  200. if(HelperUtils.uploadSingleRecord(context, record)){
  201. // Update Notification progress bar
  202. progressBarStatus++;
  203. builder.setProgress(progressMax, progressBarStatus, false);
  204. // Update the progress bar
  205. mNotifyManager.notify(2, builder.build());
  206. }else{
  207. retry_counter++;
  208. if(retry_counter == 3){
  209. retry_counter = 0;
  210. progressBarStatus++;
  211. }
  212. }
  213. }
  214. }
  215. if(progressBarStatus == progressMax){
  216. // When the loop is finished, updates the notification
  217. builder.setContentText("Upload complete")
  218. .setTicker("Upload complete")
  219. // Removes the progress bar
  220. .setProgress(0,0,false);
  221. mNotifyManager.notify(2, builder.build());
  222. }
  223. }}).start();
  224. editor.putInt("LAST_UPLOADED_ATTACK_ID",currentAttackId - 1);
  225. editor.commit();
  226. }
  227. /**
  228. * Starts a ViewLogTable Activity.
  229. * @param view View elements which triggers the method call.
  230. * @see ViewLogTable
  231. */
  232. public void showLog(View view) {
  233. startActivity(new Intent(this, ViewLogTable.class));
  234. }
  235. /**
  236. * Creates a Dialog that lets the user decide which criteria he want to use to delete records.
  237. * Then calls the corresponding method.<br>
  238. * The possible criteria are coded in /res/values/arrays.xml
  239. * To add a criteria add a String to the array and extend the switch statement.
  240. * @param view View elements which triggers the method call.
  241. * @see ViewLog#deleteByBSSID()
  242. * @see ViewLog#deleteByDate()
  243. * @see ViewLog#deleteAll()
  244. */
  245. public void deleteLog(View view) {
  246. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  247. builder.setTitle(R.string.delete_dialog_title);
  248. builder.setItems(R.array.delete_criteria,
  249. new DialogInterface.OnClickListener() {
  250. public void onClick(DialogInterface dialog, int position) {
  251. switch (position) {
  252. case 0:
  253. deleteByBSSID();
  254. break;
  255. case 1:
  256. deleteByDate();
  257. break;
  258. case 2:
  259. deleteAll();
  260. }
  261. }
  262. });
  263. builder.create();
  264. builder.show();
  265. }
  266. /**
  267. * Shows a List with all recorded BSSIDs.
  268. * If a BSSID is selected the method calls {@link Logger#deleteByBSSID(String)} to delete all records with the chosen BSSID
  269. * @see Logger#deleteByBSSID
  270. */
  271. private void deleteByBSSID() {
  272. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  273. final String[] bssidArray = logger.getAllBSSIDS();
  274. final String[] strings = new String[bssidArray.length];
  275. for(int i = 0; i < bssidArray.length; i++){
  276. strings[i] = bssidArray[i] + " (" + logger.getSSID(bssidArray[i]) +")";
  277. }
  278. builder.setTitle(R.string.delete_dialog_title);
  279. builder.setItems(strings, new DialogInterface.OnClickListener() {
  280. @SuppressLint("NewApi")
  281. public void onClick(DialogInterface dialog, int position) {
  282. logger.deleteByBSSID(bssidArray[position]);
  283. Toast.makeText(
  284. getApplicationContext(),
  285. "All entries with bssid '" + bssidArray[position]
  286. + "' deleted.", Toast.LENGTH_SHORT).show();
  287. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
  288. recreate();
  289. } else {
  290. Intent intent = getIntent();
  291. finish();
  292. startActivity(intent);
  293. }
  294. }
  295. });
  296. builder.create();
  297. builder.show();
  298. }
  299. /**
  300. * Creates a DatePicking Dialog where the user can choose a date. Afterwards {@link ViewLog#deleteByDate(int, int, int)} is called.
  301. */
  302. private void deleteByDate() {
  303. showDialog(0);
  304. }
  305. @Override
  306. protected Dialog onCreateDialog(int id) {
  307. switch (id) {
  308. case 0:
  309. final Calendar cal = Calendar.getInstance();
  310. int pYear = cal.get(Calendar.YEAR);
  311. int pMonth = cal.get(Calendar.MONTH);
  312. int pDay = cal.get(Calendar.DAY_OF_MONTH);
  313. return new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
  314. public void onDateSet(DatePicker view, int year, int monthOfYear,
  315. int dayOfMonth) {deleteByDate(year, monthOfYear, dayOfMonth);}}
  316. , pYear, pMonth, pDay);
  317. }
  318. return null;
  319. }
  320. /**
  321. * Shows a Dialog with the given date and ask him to confirm deleting records that are older than the shown date.
  322. * When the user confirms {@link Logger#deleteByDate(long)} is called with a long representation of the Date.
  323. * If the user cancels the Dialog nothing happens and the dialog disappears.
  324. * @param year
  325. * @param monthOfYear
  326. * @param dayOfMonth
  327. */
  328. private void deleteByDate(int year, int monthOfYear, int dayOfMonth) {
  329. TimePicker timePicker = new TimePicker(this);
  330. final Calendar calendar = Calendar.getInstance();
  331. calendar.set(year, monthOfYear, dayOfMonth,
  332. timePicker.getCurrentHour(), timePicker.getCurrentMinute(), 0);
  333. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  334. builder.setTitle(R.string.dialog_clear_database_date)
  335. .setMessage(sdf.format(calendar.getTime()))
  336. .setPositiveButton(R.string.delete,
  337. new DialogInterface.OnClickListener() {
  338. @SuppressLint("NewApi")
  339. public void onClick(DialogInterface dialog, int id) {
  340. long time = calendar.getTimeInMillis();
  341. // Delete Data
  342. logger.deleteByDate(time);
  343. Toast.makeText(getApplicationContext(),
  344. "Data sets deleted!",
  345. Toast.LENGTH_SHORT).show();
  346. // Recreate the activity
  347. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
  348. recreate();
  349. } else {
  350. Intent intent = getIntent();
  351. finish();
  352. startActivity(intent);
  353. }
  354. }
  355. })
  356. .setNegativeButton(R.string.cancel,
  357. new DialogInterface.OnClickListener() {
  358. public void onClick(DialogInterface dialog, int id) {
  359. // User cancelled the dialog
  360. }
  361. });
  362. // Create the AlertDialog object
  363. builder.create();
  364. builder.show();
  365. }
  366. /**
  367. * Shows a Dialog to confirm that the database should be cleared.
  368. * If confirmed {@link SQLLogger#clearData()} is called.
  369. * @see Logger#clearData()
  370. */
  371. private void deleteAll() {
  372. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  373. builder.setMessage(R.string.dialog_clear_database)
  374. .setPositiveButton(R.string.clear,
  375. new DialogInterface.OnClickListener() {
  376. @SuppressLint("NewApi")
  377. public void onClick(DialogInterface dialog, int id) {
  378. // Clear all Data
  379. logger.clearData();
  380. editor.putInt("ATTACK_ID_COUNTER", 0);
  381. editor.putInt("LAST_UPLOADED_ATTACK_ID", -1);
  382. editor.commit();
  383. Toast.makeText(getApplicationContext(),
  384. "Database cleared!", Toast.LENGTH_SHORT)
  385. .show();
  386. // Recreate the activity
  387. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
  388. recreate();
  389. } else {
  390. Intent intent = getIntent();
  391. finish();
  392. startActivity(intent);
  393. }
  394. }
  395. })
  396. .setNegativeButton(R.string.cancel,
  397. new DialogInterface.OnClickListener() {
  398. public void onClick(DialogInterface dialog, int id) {
  399. // User cancelled the dialog
  400. }
  401. });
  402. // Create the AlertDialog object
  403. builder.create();
  404. builder.show();
  405. }
  406. /**
  407. * Initializes the Statistics. Creates a table row for every protocol and checks the dabase for the attack count.
  408. * Calls {@link ViewLog#setFirstAndLastAttack()} to set the TextViews.
  409. * @see Logger#getAttackCount()
  410. * @see Logger#getAttackPerProtokolCount(String)
  411. */
  412. private void initStatistic() {
  413. TableLayout table = (TableLayout) findViewById(R.id.layoutContainer);
  414. ArrayList<String> protocols = new ArrayList<String>();
  415. protocols.add("Total");
  416. protocols.addAll(Arrays.asList(getResources().getStringArray(
  417. R.array.protocols)));
  418. for (String protocol : protocols) {
  419. TableRow row = new TableRow(this);
  420. TextView protocolName = new TextView(this);
  421. protocolName.setBackgroundResource(R.color.dark_grey);
  422. protocolName.setText(protocol);
  423. protocolName.setTextAppearance(this,
  424. android.R.style.TextAppearance_Medium);
  425. protocolName.setPadding(6, 0, 0, 0);
  426. row.addView(protocolName);
  427. TextView value = new TextView(this);
  428. value.setBackgroundResource(R.color.light_grey);
  429. value.setTextAppearance(this, android.R.style.TextAppearance_Medium);
  430. value.setGravity(Gravity.RIGHT);
  431. value.setPadding(3, 0, 3, 0);
  432. row.addView(value);
  433. if (protocol.equals("Total")) {
  434. value.setText("" + logger.getAttackCount());
  435. } else {
  436. value.setText("" + logger.getAttackPerProtokolCount(protocol));
  437. }
  438. table.addView(row);
  439. }
  440. setFirstAndLastAttack();
  441. }
  442. /**
  443. * Sets the TextViews for first and last attack.
  444. * @see Logger#getSmallestAttackId()
  445. * @see Logger#getHighestAttackId()
  446. * @see Logger#getRecordOfAttackId(long)
  447. */
  448. private void setFirstAndLastAttack() {
  449. Record firstAttack = logger.getRecordOfAttackId(logger.getSmallestAttackId());
  450. Record lastAttack = logger.getRecordOfAttackId(logger.getHighestAttackId());
  451. if (firstAttack != null) {
  452. Date resultdate = new Date(firstAttack.getTimestamp());
  453. TextView text = (TextView) findViewById(R.id.textFirstAttackValue);
  454. text.setText(sdf.format(resultdate));
  455. text = (TextView) findViewById(R.id.textLastAttackValue);
  456. resultdate = new Date(lastAttack.getTimestamp());
  457. text.setText(sdf.format(resultdate));
  458. } else {
  459. TextView text = (TextView) findViewById(R.id.textFirstAttackValue);
  460. text.setText("-");
  461. text = (TextView) findViewById(R.id.textLastAttackValue);
  462. text.setText("-");
  463. }
  464. }
  465. }