Example #1
0
  public static void releaseLocalSocket() {
    Log.i(Global.TAG, " --------------releaseLocalSocket start!");
    try {
      if (videoReceiverLocalSocket != null) {
        videoReceiverLocalSocket.close();
        videoReceiverLocalSocket = null;
      }
      if (videoSenderLocalSocket != null) {
        videoSenderLocalSocket.close();
        videoSenderLocalSocket = null;
      }
      if (videoLocalServerSocket != null) {
        videoLocalServerSocket.close();
        videoLocalServerSocket = null;
      }

      if (audioReceiverLocalSocket != null) {
        audioReceiverLocalSocket.close();
        audioReceiverLocalSocket = null;
      }
      if (audioSenderLocalSocket != null) {
        audioSenderLocalSocket.close();
        audioSenderLocalSocket = null;
      }
      if (audioLocalServerSocket != null) {
        audioLocalServerSocket.close();
        audioLocalServerSocket = null;
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
    Log.i(Global.TAG, " --------------releaseLocalSocket end!");
  }
 private void createSockets() throws IOException {
   receiver = new LocalSocket();
   receiver.connect(new LocalSocketAddress("net.majorkernelpanic.librtp-" + socketId));
   receiver.setReceiveBufferSize(500000);
   sender = lss.accept();
   sender.setSendBufferSize(500000);
 }
Example #3
0
 public void run() {
   ls = new LocalSocket();
   lsa = new LocalSocketAddress("/data/local/tmp/ShellPhoneSocket");
   try {
     ls.bind(lsa);
     ls.connect(lsa);
   } catch (IOException e) {
     e.printStackTrace();
   }
   while (!Thread.currentThread().isInterrupted()) {
     try {
       BufferedReader in = new BufferedReader(new InputStreamReader(ls.getInputStream()));
       while ((line = in.readLine()) != null) {
         handler.post(
             new Runnable() {
               @Override
               public void run() {
                 call(line);
                 // update
               }
             });
       }
       break;
     } catch (Exception e) {
       handler.post(
           new Runnable() {
             @Override
             public void run() {
               // interrupted connection
             }
           });
       e.printStackTrace();
     }
   }
 }
 private void closeSockets() {
   try {
     sender.close();
     receiver.close();
   } catch (Exception ignore) {
   }
 }
 @Override
 public void setSocketTimeout(int timeout) {
   try {
     mSocket.setSoTimeout(timeout);
   } catch (IOException e) {
     Util.throwIfNot(mSocket.isClosed());
   }
 }
    static ZygoteState connect(String socketAddress, int tries) throws ZygoteStartFailedEx {
      LocalSocket zygoteSocket = null;
      DataInputStream zygoteInputStream = null;
      BufferedWriter zygoteWriter = null;

      /*
       * See bug #811181: Sometimes runtime can make it up before zygote.
       * Really, we'd like to do something better to avoid this condition,
       * but for now just wait a bit...
       *
       * TODO: This bug was filed in 2007. Get rid of this code. The zygote
       * forks the system_server so it shouldn't be possible for the zygote
       * socket to be brought up after the system_server is.
       */
      for (int i = 0; i < tries; i++) {
        if (i > 0) {
          try {
            Log.i(LOG_TAG, "Zygote not up yet, sleeping...");
            Thread.sleep(ZYGOTE_RETRY_MILLIS);
          } catch (InterruptedException ex) {
            throw new ZygoteStartFailedEx(ex);
          }
        }

        try {
          zygoteSocket = new LocalSocket();
          zygoteSocket.connect(
              new LocalSocketAddress(socketAddress, LocalSocketAddress.Namespace.RESERVED));

          zygoteInputStream = new DataInputStream(zygoteSocket.getInputStream());

          zygoteWriter =
              new BufferedWriter(new OutputStreamWriter(zygoteSocket.getOutputStream()), 256);
          break;
        } catch (IOException ex) {
          if (zygoteSocket != null) {
            try {
              zygoteSocket.close();
            } catch (IOException ex2) {
              Log.e(LOG_TAG, "I/O exception on close after exception", ex2);
            }
          }

          zygoteSocket = null;
        }
      }

      if (zygoteSocket == null) {
        throw new ZygoteStartFailedEx("connect failed");
      }

      String abiListString = getAbiList(zygoteWriter, zygoteInputStream);
      Log.i("Zygote", "Process: zygote socket opened, supported ABIS: " + abiListString);

      return new ZygoteState(
          zygoteSocket, zygoteInputStream, zygoteWriter, Arrays.asList(abiListString.split(",")));
    }
 @Override
 public int getSocketTimeout() {
   try {
     return mSocket.getSoTimeout();
   } catch (IOException e) {
     Util.throwIfNot(mSocket.isClosed());
     return -1;
   }
 }
Example #8
0
 private void passFileDescriptor(LocalSocket fdSocket, FileDescriptor tunFD) throws Exception {
   OutputStream outputStream = fdSocket.getOutputStream();
   InputStream inputStream = fdSocket.getInputStream();
   try {
     BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream), 1);
     String request = reader.readLine();
     String[] parts = request.split(",");
     LogUtils.i("current open tcp sockets: " + tcpSockets.size());
     LogUtils.i("current open udp sockets: " + udpSockets.size());
     if ("TUN".equals(parts[0])) {
       fdSocket.setFileDescriptorsForSend(new FileDescriptor[] {tunFD});
       outputStream.write('*');
     } else if ("OPEN UDP".equals(parts[0])) {
       String socketId = parts[1];
       passUdpFileDescriptor(fdSocket, outputStream, socketId);
     } else if ("OPEN TCP".equals(parts[0])) {
       String socketId = parts[1];
       String dstIp = parts[2];
       int dstPort = Integer.parseInt(parts[3]);
       int connectTimeout = Integer.parseInt(parts[4]);
       passTcpFileDescriptor(fdSocket, outputStream, socketId, dstIp, dstPort, connectTimeout);
     } else if ("CLOSE UDP".equals(parts[0])) {
       String socketId = parts[1];
       DatagramSocket sock = udpSockets.get(socketId);
       if (sock != null) {
         udpSockets.remove(socketId);
         sock.close();
       }
     } else if ("CLOSE TCP".equals(parts[0])) {
       String socketId = parts[1];
       Socket sock = tcpSockets.get(socketId);
       if (sock != null) {
         tcpSockets.remove(socketId);
         sock.close();
       }
     } else {
       throw new UnsupportedOperationException("fdsock unable to handle: " + request);
     }
   } finally {
     try {
       inputStream.close();
     } catch (Exception e) {
       LogUtils.e("failed to close input stream", e);
     }
     try {
       outputStream.close();
     } catch (Exception e) {
       LogUtils.e("failed to close output stream", e);
     }
     fdSocket.close();
   }
 }
Example #9
0
  public void listen() {
    try {
      LocalServerSocket server = new LocalServerSocket(SOCKET_ADDRESS);

      LocalSocket receiver = server.accept();
      if (receiver != null) {
        InputStream input = receiver.getInputStream();

        byte[] buffer = new byte[1024];
        // simply for java.util.ArrayList
        boolean rec = true;
        while (rec) {
          int read = input.read(buffer);
          if (read == -1) {
            rec = false;
            Log.e(TAG, "-1 read in socket");
            break;
          }
          if (!isRecording) rec = false;
          if (!headerfound) {
            int i = ByteArrayFinder.find(buffer, pattern);
            if (i != -1) {
              headerfound = true;
              handleData(tmpch, header);
              handleData(tmpch, pattern);
              try {
                tmp = new byte[read - (i + pattern.length)];
                System.arraycopy(buffer, i + pattern.length, tmp, 0, read - (i + pattern.length));
                handleData(tmpch, tmp);
                Log.i(TAG, "Paquet: " + count);
                count++;
              } catch (Exception e) {
              }
            }
          } else {
            tmp = new byte[read];
            System.arraycopy(buffer, 0, tmp, 0, read);
            handleData(tmpch, tmp);
            Log.i(TAG, "Paquet: " + count);
            count++;
          }
          // out.write(buffer, 0, readed);
        }
        headerfound = false;
      }
    } catch (IOException e) {
      Log.e(getClass().getName(), e.getMessage());
    }
  }
Example #10
0
 private void passTcpFileDescriptor(
     LocalSocket fdSocket,
     OutputStream outputStream,
     String socketId,
     String dstIp,
     int dstPort,
     int connectTimeout)
     throws Exception {
   Socket sock = new Socket();
   sock.setTcpNoDelay(true); // force file descriptor being created
   if (protect(sock)) {
     try {
       sock.connect(new InetSocketAddress(dstIp, dstPort), connectTimeout);
       ParcelFileDescriptor fd = ParcelFileDescriptor.fromSocket(sock);
       tcpSockets.put(socketId, sock);
       fdSocket.setFileDescriptorsForSend(new FileDescriptor[] {fd.getFileDescriptor()});
       outputStream.write('*');
       outputStream.flush();
       fd.detachFd();
     } catch (ConnectException e) {
       LogUtils.e("connect " + dstIp + ":" + dstPort + " failed");
       outputStream.write('!');
       sock.close();
     } catch (SocketTimeoutException e) {
       LogUtils.e("connect " + dstIp + ":" + dstPort + " failed");
       outputStream.write('!');
       sock.close();
     } finally {
       outputStream.flush();
     }
   } else {
     LogUtils.e("protect tcp socket failed");
   }
 }
Example #11
0
  /**
   * Constructs instance from connected socket.
   *
   * @param socket non-null; connected socket
   * @throws IOException
   */
  ZygoteConnection(LocalSocket socket) throws IOException {
    mSocket = socket;

    mSocketOutStream = new DataOutputStream(socket.getOutputStream());

    mSocketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()), 256);

    mSocket.setSoTimeout(CONNECTION_TIMEOUT_MILLIS);

    try {
      peer = mSocket.getPeerCredentials();
    } catch (IOException ex) {
      Log.e(TAG, "Cannot read peer credentials", ex);
      throw ex;
    }
  }
Example #12
0
 /** Closes socket associated with this connection. */
 void closeSocket() {
   try {
     mSocket.close();
   } catch (IOException ex) {
     Log.e(TAG, "Exception while closing command " + "socket in parent", ex);
   }
 }
Example #13
0
  public void constructorVideo() {
    // ctx = c;
    // this.channel = chan;

    th =
        new Thread(
            new Runnable() {

              public void run() {
                listen();
              }
            });
    th.start();

    try {
      Thread.sleep(1000);
    } catch (Exception e) {
    }

    ls = new LocalSocket();
    try {
      ls.connect(new LocalSocketAddress(SOCKET_ADDRESS));
    } catch (IOException e) {
      // stop();
    }
    camera = Camera.open();
  }
Example #14
0
  public void init() {
    try {
      localLoop = new LocalServerSocket("videoserver");
      localReceiver = new LocalSocket();
      localReceiver.connect(localLoop.getLocalSocketAddress());
      localReceiver.setReceiveBufferSize(LOCAL_BUFF_SIZE);
      localReceiver.setSendBufferSize(LOCAL_BUFF_SIZE);

      localSender = localLoop.accept();
      localSender.setReceiveBufferSize(LOCAL_BUFF_SIZE);
      localSender.setSendBufferSize(LOCAL_BUFF_SIZE);

      Log.d(LOG_TAG, "Done: init()");
    } catch (IOException e) {
      Log.e(LOG_TAG, "Error in initializing local socket: " + e);
    }
  }
 public LocalSocketSessionInputBuffer(LocalSocket socket, int bufferSize, HttpParams params)
     throws IOException {
   if (HttpConnectionParams.isStaleCheckingEnabled(params)) {
     throw new UnsupportedOperationException(
         "Stale connection checking should not be used for local sockets");
   }
   init(socket.getInputStream(), bufferSize, params);
 }
    void close() {
      try {
        socket.close();
      } catch (IOException ex) {
        Log.e(LOG_TAG, "I/O exception on routine close", ex);
      }

      mClosed = true;
    }
  private void startLocalClient(String name, String message) throws Exception {
    // Construct a local socket
    LocalSocket clientSocket = new LocalSocket();
    try {
      // Set the socket namespace
      LocalSocketAddress.Namespace namespace;
      if (isFilesystemSocket(name)) {
        namespace = LocalSocketAddress.Namespace.FILESYSTEM;
      } else {
        namespace = LocalSocketAddress.Namespace.ABSTRACT;
      }

      // Construct local socket address
      LocalSocketAddress address = new LocalSocketAddress(name, namespace);

      // Connect to local socket
      logMessage("Connecting to " + name);
      clientSocket.connect(address);
      logMessage("Connected.");
      // Get message as bytes
      byte[] messageBytes = message.getBytes();
      // Send message bytes to the socket
      logMessage("Sending to the socket...");
      OutputStream outputStream = clientSocket.getOutputStream();
      outputStream.write(messageBytes);
      logMessage(String.format("Sent %d bytes: %s", messageBytes.length, message));

      // Receive the message back from the socket
      logMessage("Receiving from the socket...");
      InputStream inputStream = clientSocket.getInputStream();
      int readSize = inputStream.read(messageBytes);

      String receivedMessage = new String(messageBytes, 0, readSize);
      logMessage(String.format("Received %d bytes: %s", readSize, receivedMessage));

      // Close streams
      outputStream.close();
      inputStream.close();

    } finally {
      // Close the local socket
      clientSocket.close();
    }
  }
 public void prepare() throws IllegalStateException, IOException {
   if (mode == MODE_STREAMING) {
     createSockets();
     // We write the ouput of the camera in a local socket instead of a file !
     // This one little trick makes streaming feasible quiet simply: data from the camera
     // can then be manipulated at the other end of the socket
     setOutputFile(sender.getFileDescriptor());
   }
   super.prepare();
 }
Example #19
0
      @Override
      public void interrupt() {
        super.interrupt();

        try {
          socket.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
 private void close(boolean doFlush) throws IOException {
   if (!mOpen) {
     return;
   }
   mOpen = false;
   if (doFlush) {
     doFlush();
   }
   mSocket.close();
 }
Example #21
0
 public void close() {
   if (localReceiver != null) {
     try {
       localReceiver.close();
     } catch (IOException e) {
     }
   }
   if (localSender != null) {
     try {
       localSender.close();
     } catch (IOException e) {
     }
   }
   if (localLoop != null) {
     try {
       localLoop.close();
     } catch (IOException e) {
     }
   }
 }
  private boolean connect() {
    if (mSocket != null) {
      return true;
    }
    Slog.i(TAG, "connecting...");
    try {
      mSocket = new LocalSocket();

      LocalSocketAddress address =
          new LocalSocketAddress("installd", LocalSocketAddress.Namespace.RESERVED);

      mSocket.connect(address);

      mIn = mSocket.getInputStream();
      mOut = mSocket.getOutputStream();
    } catch (IOException ex) {
      disconnect();
      return false;
    }
    return true;
  }
  private void closeSocket() {
    try {
      if (mOutputStream != null) mOutputStream.close();
    } catch (IOException e) {
      Slog.e(TAG, "Failed closing output stream: " + e);
    }

    try {
      mSocket.close();
    } catch (IOException ex) {
      Slog.e(TAG, "Failed closing socket: " + ex);
    }
  }
Example #24
0
  public static void initLocalSocket() {
    Log.i(Global.TAG, " --------------initLocalSocket start!");
    try {
      if (videoReceiverLocalSocket == null) {

        videoLocalServerSocket = new LocalServerSocket("VideoCamera");

        videoReceiverLocalSocket = new LocalSocket();
        videoReceiverLocalSocket.connect(new LocalSocketAddress("VideoCamera"));
        videoReceiverLocalSocket.setReceiveBufferSize(20480); // 500000
        videoReceiverLocalSocket.setSendBufferSize(20480); //

        videoSenderLocalSocket = videoLocalServerSocket.accept();
        videoSenderLocalSocket.setReceiveBufferSize(20480);
        videoSenderLocalSocket.setSendBufferSize(20480);
      }
      // audio
      if (audioLocalServerSocket == null) {
        audioLocalServerSocket = new LocalServerSocket("AudioCamera");

        audioReceiverLocalSocket = new LocalSocket();
        audioReceiverLocalSocket.connect(new LocalSocketAddress("AudioCamera"));
        audioReceiverLocalSocket.setReceiveBufferSize(20480);
        audioReceiverLocalSocket.setSendBufferSize(20480); //

        audioSenderLocalSocket = audioLocalServerSocket.accept();
        audioSenderLocalSocket.setReceiveBufferSize(20480);
        audioSenderLocalSocket.setSendBufferSize(20480);
      }

      Log.i(
          Global.TAG, " --------------initLocalSocket ended!receiver==" + videoReceiverLocalSocket);
      Log.i(Global.TAG, " --------------initLocalSocket ended!sender==" + videoSenderLocalSocket);
    } catch (IOException e) {
      e.printStackTrace();
      releaseLocalSocket();
    }
    Log.i(Global.TAG, " --------------initLocalSocket end!");
  }
  private void listenToSocket() throws IOException {
    try {
      byte[] buffer = new byte[BUFFER_SIZE];
      LocalSocketAddress address =
          new LocalSocketAddress(ADBD_SOCKET, LocalSocketAddress.Namespace.RESERVED);
      InputStream inputStream = null;

      mSocket = new LocalSocket();
      mSocket.connect(address);

      mOutputStream = mSocket.getOutputStream();
      inputStream = mSocket.getInputStream();

      while (true) {
        int count = inputStream.read(buffer);
        if (count < 0) {
          Slog.e(TAG, "got " + count + " reading");
          break;
        }

        if (buffer[0] == 'P' && buffer[1] == 'K') {
          String key = new String(Arrays.copyOfRange(buffer, 2, count));
          Slog.d(TAG, "Received public key: " + key);
          Message msg = mHandler.obtainMessage(UsbDebuggingHandler.MESSAGE_ADB_CONFIRM);
          msg.obj = key;
          mHandler.sendMessage(msg);
        } else {
          Slog.e(TAG, "Wrong message: " + (new String(Arrays.copyOfRange(buffer, 0, 2))));
          break;
        }
      }
    } catch (IOException ex) {
      Slog.e(TAG, "Communication error: ", ex);
      throw ex;
    } finally {
      closeSocket();
    }
  }
Example #26
0
 private void passUdpFileDescriptor(
     LocalSocket fdSocket, OutputStream outputStream, String socketId) throws Exception {
   DatagramSocket sock = new DatagramSocket();
   if (protect(sock)) {
     ParcelFileDescriptor fd = ParcelFileDescriptor.fromDatagramSocket(sock);
     udpSockets.put(socketId, sock);
     fdSocket.setFileDescriptorsForSend(new FileDescriptor[] {fd.getFileDescriptor()});
     outputStream.write('*');
     outputStream.flush();
     fd.detachFd();
   } else {
     LogUtils.e("protect udp socket failed");
   }
 }
    public Boolean setup() {
      // if work as wave data generator, do not need the local data server
      if (mIsWorkAsGenerator) return true;

      try {
        if (mLocalSocket == null) {
          mLocalSocket = new LocalSocket();
        }

        if (mSocketAddress == null) {
          mSocketAddress =
              new LocalSocketAddress(
                  DATA_SERVER_SOCKET_NAME, LocalSocketAddress.Namespace.ABSTRACT);
        }
        mLocalSocket.connect(mSocketAddress);

      } catch (IOException ex) {
        Log.d(TAG, "Create local socket failed", ex);
        mLocalSocket = null;
      }

      if (mLocalSocket == null) return false;

      try {
        mLocalInputStream = mLocalSocket.getInputStream();
        mLocalOutputStream = mLocalSocket.getOutputStream();
      } catch (IOException e) {
        mLocalSocket = null;
        mLocalInputStream = null;
        mLocalOutputStream = null;
        Log.e(TAG, "temp sockets not created", e);
      }

      if (mLocalSocket == null) return false;

      return true;
    }
 public void cancel() {
   mShouldRunning = false;
   try {
     if (mBluetoothSocket != null) {
       mBluetoothSocket.close();
       mBluetoothSocket = null;
     }
     if (mLocalSocket != null) {
       mLocalSocket.close();
       mLocalSocket = null;
     }
   } catch (IOException e) {
     Log.e(TAG, "Stop data bridger failed", e);
   }
 }
 private void disconnect() {
   Slog.i(TAG, "disconnecting...");
   try {
     if (mSocket != null) mSocket.close();
   } catch (IOException ex) {
   }
   try {
     if (mIn != null) mIn.close();
   } catch (IOException ex) {
   }
   try {
     if (mOut != null) mOut.close();
   } catch (IOException ex) {
   }
   mSocket = null;
   mIn = null;
   mOut = null;
 }
Example #30
0
  private boolean prepareVideoRecorder() {
    mMediaRecorder = new MediaRecorder();

    // Step 1: Unlock and set camera to MediaRecorder
    camera.unlock();
    mMediaRecorder.setCamera(camera);

    // Step 2: Set sources
    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);

    // Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
    // mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));

    // Step 3: Set output format and encoding (for versions prior to API Level 8)
    mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
    mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263);

    // Step 4: Set output file
    mMediaRecorder.setOutputFile(ls.getFileDescriptor());

    // Step 5: Set the preview output
    // mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
    mMediaRecorder.setPreviewDisplay(holder.getSurface());

    Log.i(TAG, "Surface valid: " + holder.getSurface().isValid());

    /*mMediaRecorder.setVideoSize(176, 144);
    mMediaRecorder.setVideoFrameRate(20);
    mMediaRecorder.setAudioChannels(1);
    */

    // Step 6: Prepare configured MediaRecorder
    try {
      mMediaRecorder.prepare();
    } catch (Exception e) {
      Log.d(TAG, "Exception preparing MediaRecorder: " + e.getMessage());
      releaseMediaRecorder();
      return false;
    }
    return true;
  }