Handler.java 8.7 KB

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