PrivilegedPort.java 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package de.tudarmstadt.informatik.hostage.system;
  2. import java.io.BufferedReader;
  3. import java.io.FileDescriptor;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import android.content.SharedPreferences;
  8. import android.net.LocalServerSocket;
  9. import android.net.LocalSocket;
  10. import android.preference.PreferenceManager;
  11. import android.util.Log;
  12. import de.tudarmstadt.informatik.hostage.Hostage;
  13. import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
  14. public class PrivilegedPort implements Runnable {
  15. public static enum TYPE {
  16. TCP, UDP
  17. }
  18. private final static String UNIX_PATH = "hostage";
  19. private final String LOG_TAG;
  20. private TYPE type;
  21. private int port;
  22. private FileDescriptor fd;
  23. public PrivilegedPort(TYPE type, int port) {
  24. LOG_TAG = String.format("HosTaGe (PortBinder %s %d)", type.toString(), port);
  25. this.type = type;
  26. this.port = port;
  27. try {
  28. new Thread(this).start();
  29. LocalServerSocket localServer = new LocalServerSocket(UNIX_PATH);
  30. LocalSocket localSocket = localServer.accept();
  31. while (localSocket.getInputStream().read() != -1)
  32. ;
  33. FileDescriptor[] fdArray;
  34. fdArray = localSocket.getAncillaryFileDescriptors();
  35. if (fdArray != null) {
  36. this.fd = fdArray[0];
  37. }
  38. localSocket.close();
  39. localServer.close();
  40. } catch (IOException e) {
  41. }
  42. }
  43. public FileDescriptor getFD() {
  44. return fd;
  45. }
  46. @Override
  47. public void run() {
  48. String porthack = Device.getPorthackFilepath();
  49. Log.i("privileged port", porthack);
  50. String command = String.format(porthack+" %s %d", type.toString(), port);
  51. try {
  52. Process p = new ProcessBuilder("su", "-c", command).start();
  53. if (p.waitFor() != 0) {
  54. logError(p.getErrorStream());
  55. }
  56. logOutput(p.getInputStream());
  57. } catch (IOException e) {
  58. } catch (InterruptedException e) {
  59. }
  60. }
  61. private void logOutput(InputStream stdout) throws IOException {
  62. BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));
  63. String line;
  64. while ((line = reader.readLine()) != null) {
  65. Log.d(LOG_TAG, line);
  66. }
  67. }
  68. private void logError(InputStream stderr) throws IOException {
  69. BufferedReader reader = new BufferedReader(new InputStreamReader(stderr));
  70. Log.e(LOG_TAG, reader.readLine());
  71. }
  72. }