Handler.java 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. package de.tudarmstadt.informatik.hostage;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.OutputStream;
  5. import java.net.Socket;
  6. import java.util.List;
  7. import android.content.Context;
  8. import android.content.Intent;
  9. import android.content.SharedPreferences;
  10. import android.content.SharedPreferences.Editor;
  11. import android.preference.PreferenceManager;
  12. import android.util.Log;
  13. import de.tudarmstadt.informatik.hostage.location.MyLocationManager;
  14. import de.tudarmstadt.informatik.hostage.logging.AttackRecord;
  15. import de.tudarmstadt.informatik.hostage.logging.Logger;
  16. import de.tudarmstadt.informatik.hostage.logging.MessageRecord;
  17. import de.tudarmstadt.informatik.hostage.logging.MessageRecord.TYPE;
  18. import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
  19. import de.tudarmstadt.informatik.hostage.nio.Reader;
  20. import de.tudarmstadt.informatik.hostage.nio.Writer;
  21. import de.tudarmstadt.informatik.hostage.protocol.GHOST;
  22. import de.tudarmstadt.informatik.hostage.protocol.Protocol;
  23. import de.tudarmstadt.informatik.hostage.protocol.Protocol.TALK_FIRST;
  24. import de.tudarmstadt.informatik.hostage.sync.tracing.TracingSyncService;
  25. import de.tudarmstadt.informatik.hostage.wrapper.Packet;
  26. /**
  27. * Abstract class for a connection handler using a given protocol.
  28. *
  29. * @author Mihai Plasoianu
  30. * @author Wulf Pfeiffer
  31. * @author Lars Pandikow
  32. */
  33. public class Handler implements Runnable {
  34. /** Time until the socket throws a time out. The time is in milliseconds. */
  35. private int TIMEOUT;
  36. private Hostage service;
  37. protected Protocol protocol;
  38. private Socket client;
  39. protected Thread thread;
  40. SharedPreferences pref;
  41. private int attack_id;
  42. private int message_id = 0;
  43. private String externalIP;
  44. private String BSSID;
  45. private String SSID;
  46. private boolean logged;
  47. private Listener listener;
  48. /**
  49. * Constructor of the class. Initializes class variables for communication
  50. * and logging. Then starts itself in a new Thread.
  51. *
  52. * @param service
  53. * The background service.
  54. * @param listener
  55. * The Listener that called the service.
  56. * @param protocol
  57. * The protocol on which the handler is running.
  58. * @param client
  59. * A Socket for the communication with a remote client.
  60. */
  61. public Handler(Hostage service, Listener listener, Protocol protocol, Socket client) {
  62. this.service = service;
  63. this.listener = listener;
  64. this.protocol = protocol;
  65. if (protocol.toString().equals("GHOST")) {
  66. ((GHOST) protocol).setAttackerIP(client.getInetAddress());
  67. ((GHOST) protocol).setCurrentPort(listener.getPort());
  68. }
  69. this.client = client;
  70. this.thread = new Thread(this);
  71. pref = PreferenceManager.getDefaultSharedPreferences(service);
  72. TIMEOUT = pref.getInt("timeout", 30) * 1000;
  73. getAndIncrementAttackID(pref);
  74. SharedPreferences connInfo = service.getSharedPreferences(service.getString(R.string.connection_info), Context.MODE_PRIVATE);
  75. BSSID = connInfo.getString(service.getString(R.string.connection_info_bssid), null);
  76. SSID = connInfo.getString(service.getString(R.string.connection_info_ssid), null);
  77. externalIP = connInfo.getString(service.getString(R.string.connection_info_external_ip), null);
  78. setSoTimeout(client);
  79. logged = false;
  80. thread.start();
  81. }
  82. /**
  83. * Determines if the interrupt flag of the thread is set.
  84. *
  85. * @return True when the flag is set, else false.
  86. */
  87. public boolean isTerminated() {
  88. return thread.isInterrupted();
  89. }
  90. /**
  91. * Sets the interrupt flag of the thread and tries to close the socket.
  92. */
  93. public void kill() {
  94. service.notifyUI(this.getClass().getName(),
  95. new String[] { service.getString(R.string.broadcast_started), protocol.toString(), Integer.toString(listener.getPort()) });
  96. thread.interrupt();
  97. try {
  98. client.close();
  99. } catch (Exception e) {
  100. }
  101. boolean upload = pref.getBoolean("pref_auto_synchronize", false);
  102. if(upload){
  103. Intent intent = new Intent(service, TracingSyncService.class);
  104. intent.setAction(TracingSyncService.ACTION_START_SYNC);
  105. service.startService(intent);
  106. }
  107. //TODO kann ConcurrentModificationException auslösen, da über collection iteriert wird während elemente entfernt werden
  108. listener.refreshHandlers();
  109. }
  110. /**
  111. * Creates InputStream and OutputStream for the socket. Starts communication
  112. * with client. When the client closes the connection or a time out occurs
  113. * the handler is finished.
  114. */
  115. @Override
  116. public void run() {
  117. service.notifyUI(this.getClass().getName(),
  118. new String[] { service.getString(R.string.broadcast_started), protocol.toString(), Integer.toString(listener.getPort()) });
  119. InputStream in;
  120. OutputStream out;
  121. try {
  122. in = client.getInputStream();
  123. out = client.getOutputStream();
  124. talkToClient(in, out);
  125. } catch (Exception e) {
  126. e.printStackTrace();
  127. }
  128. kill();
  129. }
  130. /**
  131. * Gets attack ID for the attack. Also increases the attack ID counter by
  132. * one. Method is synchronized for thread safety.
  133. *
  134. * @param pref
  135. * The default SharedPreference of the application
  136. * @return Unique integer attack ID
  137. */
  138. private synchronized void getAndIncrementAttackID(SharedPreferences pref) {
  139. Editor editor = pref.edit();
  140. attack_id = pref.getInt("ATTACK_ID_COUNTER", 0);
  141. editor.putInt("ATTACK_ID_COUNTER", attack_id + 1);
  142. editor.commit();
  143. }
  144. /**
  145. * Set the timeout of the socket to the hard coded time out variable.
  146. *
  147. * @param client
  148. * The socket
  149. * @see #TIMEOUT
  150. */
  151. private void setSoTimeout(Socket client) {
  152. try {
  153. client.setSoTimeout(TIMEOUT);
  154. } catch (Exception e) {
  155. e.printStackTrace();
  156. }
  157. }
  158. /**
  159. * Creates a MessageRecord for a message exchanged with a client.
  160. *
  161. * @param type
  162. * The type of the message.
  163. * @param packet
  164. * The content of the message.
  165. * @return The Record representing the communication message.
  166. */
  167. protected MessageRecord createMessageRecord(TYPE type, String packet) {
  168. MessageRecord record = new MessageRecord();
  169. record.setId(message_id++);
  170. record.setAttack_id(attack_id);
  171. record.setType(type);
  172. record.setTimestamp(System.currentTimeMillis());
  173. record.setPacket(packet);
  174. return record;
  175. }
  176. /**
  177. * Creates a AttackRecord for a specific attack from a client.
  178. *
  179. * @return The AttackRecord representing the attack.
  180. */
  181. protected AttackRecord createAttackRecord() {
  182. AttackRecord record = new AttackRecord();
  183. record.setAttack_id(attack_id);
  184. record.setProtocol(protocol.toString());
  185. record.setExternalIP(externalIP);
  186. record.setLocalIP(client.getLocalAddress().getHostAddress());
  187. record.setLocalPort(client.getLocalPort());
  188. record.setRemoteIP(client.getInetAddress().getHostAddress());
  189. record.setRemotePort(client.getPort());
  190. record.setBssid(BSSID);
  191. return record;
  192. }
  193. /**
  194. * Creates a NetworkRecord containing information about the current network.
  195. *
  196. * @return The NetworkRecord representing the current network.
  197. */
  198. protected NetworkRecord createNetworkRecord() {
  199. NetworkRecord record = new NetworkRecord();
  200. record.setBssid(BSSID);
  201. record.setSsid(SSID);
  202. if (MyLocationManager.getNewestLocation() != null) {
  203. record.setLatitude(MyLocationManager.getNewestLocation().getLatitude());
  204. record.setLongitude(MyLocationManager.getNewestLocation().getLongitude());
  205. record.setAccuracy(MyLocationManager.getNewestLocation().getAccuracy());
  206. record.setTimestampLocation(MyLocationManager.getNewestLocation().getTime());
  207. } else {
  208. record.setLatitude(0.0);
  209. record.setLongitude(0.0);
  210. record.setAccuracy(Float.MAX_VALUE);
  211. record.setTimestampLocation(0);
  212. }
  213. return record;
  214. }
  215. private void log(TYPE type, String packet){
  216. if(!logged){
  217. Logger.log(Hostage.getContext(), createNetworkRecord());
  218. Logger.log(Hostage.getContext(), createAttackRecord());
  219. logged = true;
  220. }
  221. Logger.log(Hostage.getContext(), createMessageRecord(type, packet));
  222. }
  223. /**
  224. * Communicates with a client using the corresponding protocol
  225. * implementation.
  226. *
  227. * @param in
  228. * InputStream of the socket.
  229. * @param out
  230. * OutputStream of the socket.
  231. * @throws IOException
  232. */
  233. protected void talkToClient(InputStream in, OutputStream out) throws IOException {
  234. Reader reader = new Reader(in, protocol.toString());
  235. Writer writer = new Writer(out);
  236. Packet inputLine;
  237. List<Packet> outputLine;
  238. if (protocol.whoTalksFirst() == TALK_FIRST.SERVER) {
  239. outputLine = protocol.processMessage(null);
  240. writer.write(outputLine);
  241. for (Packet o : outputLine) {
  242. log(TYPE.SEND, o.toString());
  243. }
  244. }
  245. while (!thread.isInterrupted() && (inputLine = reader.read()) != null) {
  246. outputLine = protocol.processMessage(inputLine);
  247. log(TYPE.RECEIVE, inputLine.toString());
  248. if (outputLine != null) {
  249. writer.write(outputLine);
  250. for (Packet o : outputLine) {
  251. log(TYPE.SEND, o.toString());
  252. }
  253. }
  254. if (protocol.isClosed()) {
  255. break;
  256. }
  257. }
  258. }
  259. }