TracingSyncService.java 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. package de.tudarmstadt.informatik.hostage.sync.tracing;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.io.OutputStream;
  6. import java.io.OutputStreamWriter;
  7. import java.io.StringWriter;
  8. import java.io.Writer;
  9. import java.net.HttpURLConnection;
  10. import java.net.URL;
  11. import java.security.KeyStore;
  12. import java.util.ArrayList;
  13. import java.util.HashMap;
  14. import java.util.Map;
  15. import org.apache.http.HttpResponse;
  16. import org.apache.http.HttpVersion;
  17. import org.apache.http.client.HttpClient;
  18. import org.apache.http.client.methods.HttpPost;
  19. import org.apache.http.conn.ClientConnectionManager;
  20. import org.apache.http.conn.scheme.PlainSocketFactory;
  21. import org.apache.http.conn.scheme.Scheme;
  22. import org.apache.http.conn.scheme.SchemeRegistry;
  23. import org.apache.http.conn.ssl.SSLSocketFactory;
  24. import org.apache.http.entity.StringEntity;
  25. import org.apache.http.impl.client.DefaultHttpClient;
  26. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
  27. import org.apache.http.params.BasicHttpParams;
  28. import org.apache.http.params.HttpParams;
  29. import org.apache.http.params.HttpProtocolParams;
  30. import org.apache.http.protocol.HTTP;
  31. import org.json.JSONException;
  32. import org.json.JSONObject;
  33. import android.app.IntentService;
  34. import android.content.Intent;
  35. import android.content.SharedPreferences;
  36. import android.content.SharedPreferences.Editor;
  37. import android.os.Bundle;
  38. import android.os.ResultReceiver;
  39. import android.preference.PreferenceManager;
  40. import android.util.Log;
  41. import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
  42. import de.tudarmstadt.informatik.hostage.logging.Record;
  43. import de.tudarmstadt.informatik.hostage.logging.SyncInfoRecord;
  44. import de.tudarmstadt.informatik.hostage.net.MySSLSocketFactory;
  45. import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
  46. import de.tudarmstadt.informatik.hostage.sync.android.SyncUtils;
  47. import de.tudarmstadt.informatik.hostage.ui.model.LogFilter;
  48. /**
  49. * Service that synchronizes with a specified remote server.
  50. *
  51. * @author Lars Pandikow
  52. */
  53. public class TracingSyncService extends IntentService {
  54. public static final String REMOTE_DEVICE = "de.tudarmstadt.informatik.hostage.REMOTE_DEVICE";
  55. public static final String ACTION_START_SYNC = "de.tudarmstadt.informatik.hostage.ACTION_START_SYNC";
  56. public static final String EXTRA_RECEIVER = "de.tudarmstadt.informatik.hostage.EXTRA_HANDLER";
  57. public static final String UPLOAD_SIZE = "de.tudarmstadt.informatik.hostage.UPLOAD_SIZE";
  58. public static final String UPLOAD_PROGRESS = "de.tudarmstadt.informatik.hostage.UPLOAD_PROGRESS";
  59. public static final int RECORD_UPLOADED = 0x00;
  60. public static final int SYNC_COMPLETE = 0x01;
  61. public static final int SYNC_ERROR = 0x02;
  62. private HttpClient httpClient;
  63. private ResultReceiver receiver;
  64. HostageDBOpenHelper dbh;
  65. SharedPreferences pref;
  66. Editor editor;
  67. public TracingSyncService() {
  68. super(TracingSyncService.class.getName());
  69. }
  70. @Override
  71. public void onCreate() {
  72. super.onCreate();
  73. pref = PreferenceManager.getDefaultSharedPreferences(this);
  74. editor = pref.edit();
  75. dbh = new HostageDBOpenHelper(this);
  76. }
  77. /**
  78. * The IntentService calls this method from the default worker thread with
  79. * the intent that started the service. When this method returns,
  80. * IntentService stops the service, as appropriate.
  81. */
  82. @Override
  83. protected void onHandleIntent(Intent intent) {
  84. if (intent != null) {
  85. final String action = intent.getAction();
  86. if (ACTION_START_SYNC.equals(action)) {
  87. receiver = intent.getParcelableExtra(EXTRA_RECEIVER);
  88. syncNewRecords();
  89. dbh.clearSyncInfos();
  90. if (receiver != null) {
  91. receiver.send(SYNC_COMPLETE, null);
  92. }
  93. }
  94. }
  95. }
  96. /**
  97. * Uploads all new Records to a server, specified in the settings.
  98. */
  99. private void syncNewRecords() {
  100. long lastSyncTime = pref.getLong("LAST_SYNC_TIME", 0);
  101. String serverAddress = pref.getString("pref_upload_server", "https://ssi.cased.de"); //"https://192.168.1.118:9999"
  102. LogFilter filter = new LogFilter();
  103. filter.setAboveTimestamp(lastSyncTime);
  104. ArrayList<Record> records = dbh.getRecordsForFilter(filter);
  105. StringWriter writer = new StringWriter();
  106. int size = records.size();
  107. int offset = 1;
  108. int currOffset = 1;
  109. boolean error = false;
  110. for (Record record : records) {
  111. SyncUtils.appendRecordToStringWriter(record, writer);
  112. if(currOffset == 5 || offset == size){
  113. boolean success = SyncUtils.uploadRecordsToServer(writer.toString(), serverAddress);
  114. Log.i("Tracing upload", "Upload of record: " + offset + "/" + size + ((success) ? " successful." : " failed."));
  115. if(!success){
  116. if(receiver != null){
  117. receiver.send(SYNC_ERROR, null);
  118. error = true;
  119. }
  120. break;
  121. }
  122. if (receiver != null) {
  123. Bundle data = new Bundle();
  124. data.putInt(UPLOAD_SIZE, size);
  125. data.putInt(UPLOAD_PROGRESS, offset);
  126. receiver.send(RECORD_UPLOADED, data);
  127. }
  128. writer.getBuffer().setLength(0);
  129. currOffset = 0;
  130. }
  131. offset++;
  132. currOffset++;
  133. }
  134. if(!error) pref.edit().putLong("LAST_SYNC_TIME", System.currentTimeMillis()).apply();
  135. }
  136. /**
  137. * Gets the data from the server and updates the database.
  138. */
  139. private void getRemoteData(String bssid, long timestamp) {
  140. HttpURLConnection connection;
  141. OutputStreamWriter request = null;
  142. URL url = null;
  143. String response = null;
  144. String parameters = "bssid=" + bssid;
  145. try {
  146. url = new URL("http://87.230.23.240/hostage/pull.php");
  147. connection = (HttpURLConnection) url.openConnection();
  148. connection.setDoOutput(true);
  149. connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
  150. connection.setRequestMethod("POST");
  151. request = new OutputStreamWriter(connection.getOutputStream());
  152. request.write(parameters);
  153. request.flush();
  154. request.close();
  155. String line = "";
  156. InputStreamReader isr = new InputStreamReader(connection.getInputStream());
  157. BufferedReader reader = new BufferedReader(isr);
  158. StringBuilder sb = new StringBuilder();
  159. while ((line = reader.readLine()) != null) {
  160. sb.append(line);
  161. }
  162. response = sb.toString();
  163. JSONObject jsonObj = new JSONObject(response);
  164. NetworkRecord net = new NetworkRecord();
  165. net.setBssid(jsonObj.getString("bssid"));
  166. net.setSsid(jsonObj.getString("ssid"));
  167. net.setLatitude(jsonObj.getDouble("latitude"));
  168. net.setLongitude(jsonObj.getDouble("longitude"));
  169. net.setTimestampLocation(jsonObj.getLong("timestamp"));
  170. SyncInfoRecord sync = new SyncInfoRecord();
  171. sync.setBSSID(jsonObj.getString("bssid"));
  172. sync.setDeviceID("-1");
  173. sync.setNumber_of_attacks(jsonObj.getLong("attacks"));
  174. sync.setNumber_of_portscans(jsonObj.getLong("portscans"));
  175. dbh.updateNetworkInformation(net);
  176. isr.close();
  177. reader.close();
  178. } catch (IOException e) {
  179. Log.i("NetworkTest", "Network Error: " + e);
  180. } catch (JSONException e) {
  181. e.printStackTrace();
  182. }
  183. }
  184. }