HelperUtils.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. package de.tudarmstadt.informatik.hostage.commons;
  2. import junit.framework.Assert;
  3. import org.apache.http.HttpVersion;
  4. import org.apache.http.client.HttpClient;
  5. import org.apache.http.client.methods.HttpPost;
  6. import org.apache.http.conn.ClientConnectionManager;
  7. import org.apache.http.conn.scheme.PlainSocketFactory;
  8. import org.apache.http.conn.scheme.Scheme;
  9. import org.apache.http.conn.scheme.SchemeRegistry;
  10. import org.apache.http.conn.ssl.SSLSocketFactory;
  11. import org.apache.http.entity.StringEntity;
  12. import org.apache.http.impl.client.DefaultHttpClient;
  13. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
  14. import org.apache.http.params.BasicHttpParams;
  15. import org.apache.http.params.HttpParams;
  16. import org.apache.http.params.HttpProtocolParams;
  17. import org.apache.http.protocol.HTTP;
  18. import java.io.BufferedReader;
  19. import java.io.File;
  20. import java.io.FileNotFoundException;
  21. import java.io.FileOutputStream;
  22. import java.io.IOException;
  23. import java.io.InputStream;
  24. import java.io.InputStreamReader;
  25. import java.io.OutputStream;
  26. import java.net.InetAddress;
  27. import java.net.UnknownHostException;
  28. import java.security.KeyStore;
  29. import java.security.SecureRandom;
  30. import android.app.Activity;
  31. import android.content.Context;
  32. import android.content.res.AssetManager;
  33. import android.net.ConnectivityManager;
  34. import android.net.NetworkInfo;
  35. import android.net.wifi.WifiInfo;
  36. import android.net.wifi.WifiManager;
  37. import android.os.Environment;
  38. import android.preference.PreferenceManager;
  39. import android.text.TextUtils;
  40. import android.util.Log;
  41. import de.tudarmstadt.informatik.hostage.logging.Record;
  42. import de.tudarmstadt.informatik.hostage.logging.formatter.TraCINgFormatter;
  43. import de.tudarmstadt.informatik.hostage.net.MySSLSocketFactory;
  44. import de.tudarmstadt.informatik.hostage.system.Device;
  45. import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
  46. /**
  47. * Helper class with some static methods for general usage.
  48. *
  49. * @author Lars Pandikow
  50. * @author Wulf Pfeiffer
  51. *
  52. */
  53. public final class HelperUtils {
  54. /**
  55. * Converts a byte array into a hexadecimal String, e.g. {0x00, 0x01} to
  56. * "00, 01".
  57. *
  58. * @param bytes
  59. * that will be converted.
  60. * @return converted String.
  61. */
  62. public static String bytesToHexString(byte[] bytes) {
  63. char[] hexArray = "0123456789ABCDEF".toCharArray();
  64. int v;
  65. StringBuffer buffer = new StringBuffer();
  66. for (int j = 0; j < bytes.length; j++) {
  67. v = bytes[j] & 0xFF;
  68. buffer.append(hexArray[v >>> 4]);
  69. buffer.append(hexArray[v & 0x0F]);
  70. if (j < bytes.length - 1)
  71. buffer.append(", ");
  72. }
  73. return buffer.toString();
  74. }
  75. /**
  76. * Converts a byte[] to a String, but only characters in ASCII between 32
  77. * and 127
  78. *
  79. * @param bytes
  80. * that are converted
  81. * @return converted String
  82. */
  83. public static String byteToStr(byte[] bytes) {
  84. int size = 0;
  85. for(byte b : bytes) {
  86. if(isLetter((char) b)) {
  87. size++;
  88. }
  89. }
  90. char[] chars = new char[size];
  91. for (int i = 0, j = 0; i < bytes.length && j < size; i++) {
  92. if (isLetter((char) bytes[i])) {
  93. chars[j] = (char) bytes[i];
  94. j++;
  95. }
  96. }
  97. return new String(chars);
  98. }
  99. /**
  100. * Concatenates several byte arrays.
  101. *
  102. * @param bytes
  103. * The byte arrays.
  104. * @return A single byte arrays containing all the bytes from the given
  105. * arrays in the order they are given.
  106. */
  107. public static byte[] concat(byte[]... bytes) {
  108. int newSize = 0;
  109. for (byte[] b : bytes)
  110. if (b != null)
  111. newSize += b.length;
  112. byte[] dst = new byte[newSize];
  113. int currentPos = 0;
  114. int newPos;
  115. for (byte[] b : bytes) {
  116. if (b != null) {
  117. newPos = b.length;
  118. System.arraycopy(b, 0, dst, currentPos, newPos);
  119. currentPos += newPos;
  120. }
  121. }
  122. return dst;
  123. }
  124. /**
  125. * Puts a 0x00 byte between each byte in a byte array.
  126. *
  127. * @param bytes
  128. * that need to be filled with 0x00.
  129. * @return filled byte array.
  130. */
  131. public static byte[] fillWithZero(byte[] bytes) {
  132. byte[] newBytes = new byte[(bytes.length * 2)];
  133. for (int i = 0, j = 0; i < bytes.length && j < newBytes.length; i++, j = j + 2) {
  134. newBytes[j] = bytes[i];
  135. newBytes[j + 1] = 0x00;
  136. }
  137. return newBytes;
  138. }
  139. /**
  140. * Puts a 0x00 byte between each byte and another 2 0x00 bytes at the end of
  141. * a byte array.
  142. *
  143. * @param bytes
  144. * that need to be filled with 0x00.
  145. * @return filled byte array.
  146. */
  147. public static byte[] fillWithZeroExtended(byte[] bytes) {
  148. byte[] zeroBytes = fillWithZero(bytes);
  149. byte[] newBytes = new byte[zeroBytes.length + 2];
  150. newBytes = HelperUtils.concat(zeroBytes, new byte[] { 0x00, 0x00 });
  151. return newBytes;
  152. }
  153. /**
  154. * Gets BSSID of the wireless network.
  155. *
  156. * @param context
  157. * Needs a context to get system recourses.
  158. * @return BSSID of wireless network if connected, else null.
  159. */
  160. public static String getBSSID(Context context) {
  161. String bssid = null;
  162. ConnectivityManager connManager = (ConnectivityManager) context
  163. .getSystemService(Context.CONNECTIVITY_SERVICE);
  164. NetworkInfo networkInfo = connManager
  165. .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  166. if (networkInfo != null && networkInfo.isConnected()) {
  167. final WifiManager wifiManager = (WifiManager) context
  168. .getSystemService(Context.WIFI_SERVICE);
  169. final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
  170. if (connectionInfo != null
  171. && !TextUtils.isEmpty(connectionInfo.getSSID())) {
  172. bssid = connectionInfo.getBSSID();
  173. }
  174. }
  175. return bssid;
  176. }
  177. public static HttpClient createHttpClient() {
  178. try {
  179. KeyStore trustStore = KeyStore.getInstance(KeyStore
  180. .getDefaultType());
  181. trustStore.load(null, null);
  182. SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
  183. sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  184. HttpParams params = new BasicHttpParams();
  185. HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
  186. HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
  187. SchemeRegistry registry = new SchemeRegistry();
  188. registry.register(new Scheme("http", PlainSocketFactory
  189. .getSocketFactory(), 80));
  190. registry.register(new Scheme("https", sf, 443));
  191. ClientConnectionManager ccm = new ThreadSafeClientConnManager(
  192. params, registry);
  193. return new DefaultHttpClient(ccm, params);
  194. } catch (Exception e) {
  195. e.printStackTrace();
  196. return new DefaultHttpClient();
  197. }
  198. }
  199. public static boolean uploadSingleRecord(Context context, Record record) {
  200. // Create a https client. Uses MySSLSocketFactory to accept all
  201. // certificates
  202. HttpClient httpclient = HelperUtils.createHttpClient();
  203. HttpPost httppost;
  204. try {
  205. // Create HttpPost
  206. httppost = new HttpPost(PreferenceManager
  207. .getDefaultSharedPreferences(context).getString(
  208. "pref_upload", "https://ssi.cased.de"));
  209. // Create JSON String of Record
  210. StringEntity se = new StringEntity(record.toString(TraCINgFormatter.getInstance()));
  211. httppost.setEntity(se);
  212. // Execute HttpPost
  213. httpclient.execute(httppost);
  214. } catch (Exception e) {
  215. e.printStackTrace();
  216. return false;
  217. }
  218. return true;
  219. }
  220. /**
  221. * Gets internal IP address of the device in a wireless network.
  222. *
  223. * @param context
  224. * Needs a context to get system recourses.
  225. * @return internal IP of the device in a wireless network if connected,
  226. * else null.
  227. */
  228. public static String getInternalIP(Context context) {
  229. String ipAddress = null;
  230. ConnectivityManager connManager = (ConnectivityManager) context
  231. .getSystemService(Context.CONNECTIVITY_SERVICE);
  232. NetworkInfo networkInfo = connManager
  233. .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  234. if (networkInfo != null && networkInfo.isConnected()) {
  235. final WifiManager wifiManager = (WifiManager) context
  236. .getSystemService(Context.WIFI_SERVICE);
  237. final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
  238. if (connectionInfo != null) {
  239. try {
  240. ipAddress = InetAddress.getByAddress(
  241. unpackInetAddress(connectionInfo.getIpAddress()))
  242. .getHostAddress();
  243. } catch (UnknownHostException e) {
  244. e.printStackTrace();
  245. }
  246. }
  247. }
  248. return ipAddress;
  249. }
  250. /**
  251. * Gets SSID of the wireless network.
  252. *
  253. * @param context
  254. * Needs a context to get system recourses
  255. * @return SSID of wireless network if connected, else null.
  256. */
  257. public static String getSSID(Context context) {
  258. String ssid = null;
  259. ConnectivityManager connManager = (ConnectivityManager) context
  260. .getSystemService(Context.CONNECTIVITY_SERVICE);
  261. NetworkInfo networkInfo = connManager
  262. .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  263. if (networkInfo != null && networkInfo.isConnected()) {
  264. final WifiManager wifiManager = (WifiManager) context
  265. .getSystemService(Context.WIFI_SERVICE);
  266. final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
  267. if (connectionInfo != null
  268. && !TextUtils.isEmpty(connectionInfo.getSSID())) {
  269. ssid = connectionInfo.getSSID();
  270. if (ssid.startsWith("\"") && ssid.endsWith("\"")) { // trim those quotes
  271. ssid = ssid.substring(1, ssid.length() - 1);
  272. }
  273. }
  274. }
  275. return ssid;
  276. }
  277. /**
  278. * Gets the mac address of the devicek.
  279. *
  280. * @param context
  281. * Needs a context to get system recourses
  282. * @return MAC address of the device.
  283. */
  284. public static String getMacAdress(Context context) {
  285. String mac = null;
  286. WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
  287. WifiInfo connectionInfo = wifiManager.getConnectionInfo();
  288. mac = connectionInfo.getMacAddress();
  289. return mac;
  290. }
  291. /**
  292. * Produces a random String. The String can be of random length (minimum 1)
  293. * with a maximum length, or it can be forced to have the length that was
  294. * given.
  295. *
  296. * @param length
  297. * maximal / forced length of String.
  298. * @param forceLength
  299. * forces the String to be exact the given length instead of
  300. * maximum
  301. * @return random String.
  302. */
  303. public static String getRandomString(int length, boolean forceLength) {
  304. SecureRandom rndm = new SecureRandom();
  305. char[] c = new char[forceLength ? length : rndm.nextInt(length - 1) + 1];
  306. for (int i = 0; i < c.length; i++) {
  307. c[i] = (char) (rndm.nextInt(95) + 32);
  308. }
  309. return new String(c);
  310. }
  311. /**
  312. * Converts a String into a byte array, e.g. "00, 01" to {0x00, 0x01}.
  313. *
  314. * @param string
  315. * that will be converted.
  316. * @return converted byte array.
  317. */
  318. public static byte[] hexStringToBytes(String string) {
  319. String[] hexStrings = string.split(", ");
  320. byte[] bytes = new byte[hexStrings.length];
  321. for (int j = 0; j < hexStrings.length; j++) {
  322. bytes[j] = (byte) ((Character.digit(hexStrings[j].charAt(0), 16) << 4) + Character
  323. .digit(hexStrings[j].charAt(1), 16));
  324. }
  325. return bytes;
  326. }
  327. /**
  328. * Generates a random byte[] of a specified size
  329. *
  330. * @param size
  331. * of the byte[]
  332. * @return random byte[]
  333. */
  334. public static byte[] randomBytes(int size) {
  335. byte[] bytes = new byte[size];
  336. SecureRandom rdm = new SecureRandom();
  337. rdm.nextBytes(bytes);
  338. return bytes;
  339. }
  340. /**
  341. * Turns around the values of an byte[], e.g. {0x00, 0x01, 0x02} turns into
  342. * {0x02, 0x01, 0x00}.
  343. *
  344. * @param bytes
  345. * array that is turned.
  346. * @return turned array.
  347. */
  348. public static byte[] turnByteArray(byte[] bytes) {
  349. byte[] tmp = new byte[bytes.length];
  350. for (int i = 0; i < bytes.length; i++) {
  351. tmp[i] = bytes[bytes.length - 1 - i];
  352. }
  353. return tmp;
  354. }
  355. /**
  356. * Determines if a character is in ASCII between 32 and 126
  357. *
  358. * @param character
  359. * that is checked
  360. * @return true if the character is between 32 and 126, else false
  361. */
  362. private static boolean isLetter(char character) {
  363. return (character > 31 && character < 127);
  364. }
  365. public static byte[] unpackInetAddress(int bytes) {
  366. return new byte[] { (byte) ((bytes) & 0xff),
  367. (byte) ((bytes >>> 8) & 0xff), (byte) ((bytes >>> 16) & 0xff),
  368. (byte) ((bytes >>> 24) & 0xff) };
  369. }
  370. public static int packInetAddress(byte[] bytes) {
  371. /*
  372. FUCK YOU JAVA!!! WHY DON'T YOU HAVE UNSIGNED TYPES???
  373. */
  374. long b0 = bytes[0]; if (b0 < 0) b0 = 256 + b0;
  375. long b1 = bytes[1]; if (b1 < 0) b1 = 256 + b1;
  376. long b2 = bytes[2]; if (b2 < 0) b2 = 256 + b2;
  377. long b3 = bytes[3]; if (b3 < 0) b3 = 256 + b3;
  378. long packed = b0 | (b1 << 8) | (b2 << 16) | (b3 << 24);
  379. if (packed >= (1l << 31)) {
  380. packed -= (1l << 32) - 1l;
  381. }
  382. return (int)packed;
  383. }
  384. public static String inetAddressToString(int address) {
  385. return String.valueOf(address & 0xFF) + "."
  386. + String.valueOf((address >>> 8) & 0xFF) + "."
  387. + String.valueOf((address >>> 16) & 0xFF) + "."
  388. + String.valueOf((address >>> 24) & 0xFF);
  389. }
  390. public static boolean isWifiConnected(Context context){
  391. if(context == null) return false;
  392. ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  393. NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  394. return mWifi.isConnected();
  395. }
  396. public static boolean isNetworkAvailable(Context context) {
  397. if(context == null) return false;
  398. ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  399. NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
  400. return activeNetworkInfo != null && activeNetworkInfo.isConnected();
  401. }
  402. public static int getRedirectedPort(int port){
  403. return port + 1024 + 27113;
  404. }
  405. }