HelperUtils.java 13 KB

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