TracingSyncService.java 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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.OutputStreamWriter;
  6. import java.net.HttpURLConnection;
  7. import java.net.URL;
  8. import java.security.KeyStore;
  9. import java.util.ArrayList;
  10. import org.apache.http.HttpResponse;
  11. import org.apache.http.HttpVersion;
  12. import org.apache.http.client.HttpClient;
  13. import org.apache.http.client.methods.HttpPost;
  14. import org.apache.http.conn.ClientConnectionManager;
  15. import org.apache.http.conn.scheme.PlainSocketFactory;
  16. import org.apache.http.conn.scheme.Scheme;
  17. import org.apache.http.conn.scheme.SchemeRegistry;
  18. import org.apache.http.conn.ssl.SSLSocketFactory;
  19. import org.apache.http.entity.StringEntity;
  20. import org.apache.http.impl.client.DefaultHttpClient;
  21. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
  22. import org.apache.http.params.BasicHttpParams;
  23. import org.apache.http.params.HttpParams;
  24. import org.apache.http.params.HttpProtocolParams;
  25. import org.apache.http.protocol.HTTP;
  26. import android.app.IntentService;
  27. import android.content.Intent;
  28. import android.content.SharedPreferences;
  29. import android.content.SharedPreferences.Editor;
  30. import android.os.Bundle;
  31. import android.os.ResultReceiver;
  32. import android.preference.PreferenceManager;
  33. import android.util.Log;
  34. import de.tudarmstadt.informatik.hostage.logging.AttackRecord;
  35. import de.tudarmstadt.informatik.hostage.net.MySSLSocketFactory;
  36. import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
  37. /**
  38. * Service that synchronizes with a specified remote server.
  39. *
  40. * @author Lars Pandikow
  41. */
  42. public class TracingSyncService extends IntentService {
  43. public static final String REMOTE_DEVICE = "de.tudarmstadt.informatik.hostage.REMOTE_DEVICE";
  44. public static final String ACTION_START_SYNC = "de.tudarmstadt.informatik.hostage.ACTION_START_SYNC";
  45. public static final String EXTRA_RECEIVER = "de.tudarmstadt.informatik.hostage.EXTRA_HANDLER";
  46. public static final String UPLOAD_SIZE = "de.tudarmstadt.informatik.hostage.UPLOAD_SIZE";
  47. public static final String UPLOAD_PROGRESS = "de.tudarmstadt.informatik.hostage.UPLOAD_PROGRESS";
  48. public static final int RECORD_UPLOADED = 0x00;
  49. public static final int SYNC_COMPLETE = 0x01;
  50. private HttpClient httpClient;
  51. private ResultReceiver receiver;
  52. HostageDBOpenHelper dbh;
  53. SharedPreferences pref;
  54. Editor editor;
  55. public TracingSyncService() {
  56. super(TracingSyncService.class.getName());
  57. }
  58. @Override
  59. public void onCreate() {
  60. super.onCreate();
  61. pref = PreferenceManager.getDefaultSharedPreferences(this);
  62. editor = pref.edit();
  63. dbh = new HostageDBOpenHelper(this);
  64. }
  65. /**
  66. * The IntentService calls this method from the default worker thread with
  67. * the intent that started the service. When this method returns,
  68. * IntentService stops the service, as appropriate.
  69. */
  70. @Override
  71. protected void onHandleIntent(Intent intent) {
  72. if (intent != null) {
  73. final String action = intent.getAction();
  74. if (ACTION_START_SYNC.equals(action)) {
  75. receiver = intent.getParcelableExtra(EXTRA_RECEIVER);
  76. syncNewRecords();
  77. dbh.clearSyncInfos();
  78. if (receiver != null) {
  79. receiver.send(SYNC_COMPLETE, null);
  80. }
  81. }
  82. }
  83. }
  84. /**
  85. * Uploads all new Records to a server, specified in the settings.
  86. */
  87. private void syncNewRecords() {
  88. int lastUploadedAttackId = pref.getInt("LAST_UPLOADED_ATTACK_ID", -1);
  89. // String serverAddress = pref.getString("pref_upload",
  90. // "https://ssi.cased.de");
  91. String serverAddress = "http://87.230.23.240/hostage/push.php";
  92. ArrayList<AttackRecord> recordList = dbh.getRecordOfEachAttack(lastUploadedAttackId);
  93. int size = recordList.size();
  94. int offset = 1;
  95. for (AttackRecord record : recordList) {
  96. editor.putInt("LAST_UPLOADED_ATTACK_ID", lastUploadedAttackId + offset);
  97. editor.commit();
  98. boolean success = uploadSingleRecord(record, serverAddress);
  99. Log.i("Tracing upload", "Upload of record: " + offset + "/" + size + ((success) ? " successful." : " failed."));
  100. if (receiver != null) {
  101. Bundle data = new Bundle();
  102. data.putInt(UPLOAD_SIZE, size);
  103. data.putInt(UPLOAD_PROGRESS, offset);
  104. receiver.send(RECORD_UPLOADED, data);
  105. }
  106. offset++;
  107. // TODO pull
  108. // getRemoteData(record.getBssid(), record.getTimestamp());
  109. }
  110. }
  111. /**
  112. * Uploads a single Record to a server, specified in the settings.
  113. *
  114. * @param record
  115. * The Record to upload.
  116. * @serverAddress Address of the target server
  117. * @return True if the upload was successful, else false.
  118. */
  119. private boolean uploadSingleRecord(AttackRecord record, String serverAddress) {
  120. // Create a https client. Uses MySSLSocketFactory to accept all
  121. // certificates
  122. HttpPost httppost;
  123. try {
  124. httpClient = createHttpClient();
  125. // Create HttpPost
  126. httppost = new HttpPost(serverAddress);
  127. // Create JSON String of Record
  128. // TODO StringEntity se = new
  129. // StringEntity(record.toString(TraCINgFormatter.getInstance()));
  130. StringEntity se = new StringEntity("record=" + record.toJSON()); // FIXME
  131. httppost.addHeader("content-type", "application/x-www-form-urlencoded");
  132. httppost.setEntity(se);
  133. // Execute HttpPost
  134. HttpResponse response = httpClient.execute(httppost);
  135. Log.i("TracingSyncService", "Status Code: " + response.getStatusLine().getStatusCode());
  136. } catch (Exception e) {
  137. e.printStackTrace();
  138. return false;
  139. }
  140. return true;
  141. }
  142. /**
  143. * Gets the data from the server and updates the database.
  144. */
  145. private void getRemoteData(String bssid, long timestamp) {
  146. HttpURLConnection connection;
  147. OutputStreamWriter request = null;
  148. URL url = null;
  149. String response = null;
  150. String parameters = "bssid=" + bssid + "timestamp=" + timestamp;
  151. try {
  152. url = new URL("http://87.230.23.240/hostage/pull.php");
  153. connection = (HttpURLConnection) url.openConnection();
  154. connection.setDoOutput(true);
  155. connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
  156. connection.setRequestMethod("POST");
  157. request = new OutputStreamWriter(connection.getOutputStream());
  158. request.write(parameters);
  159. request.flush();
  160. request.close();
  161. String line = "";
  162. InputStreamReader isr = new InputStreamReader(connection.getInputStream());
  163. BufferedReader reader = new BufferedReader(isr);
  164. StringBuilder sb = new StringBuilder();
  165. while ((line = reader.readLine()) != null) {
  166. sb.append(line);
  167. }
  168. response = sb.toString();
  169. isr.close();
  170. reader.close();
  171. Log.d("TEST", response);
  172. } catch (IOException e) {
  173. Log.i("NetworkTest", "Network Error: " + e);
  174. }
  175. }
  176. /**
  177. * Creates a HttpClient with an own SSL Socket.
  178. *
  179. * @return HttpsClient who accepts accepts all certificates.
  180. * @see MySSLSocketFactory
  181. */
  182. private HttpClient createHttpClient() {
  183. try {
  184. KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
  185. trustStore.load(null, null);
  186. SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
  187. sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  188. HttpParams params = new BasicHttpParams();
  189. HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
  190. HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
  191. SchemeRegistry registry = new SchemeRegistry();
  192. registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
  193. registry.register(new Scheme("https", sf, 443));
  194. ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
  195. return new DefaultHttpClient(ccm, params);
  196. } catch (Exception e) {
  197. e.printStackTrace();
  198. return new DefaultHttpClient();
  199. }
  200. }
  201. }