Пример #1
0
  private void listenFdServerSocket(final ParcelFileDescriptor tunPFD) throws Exception {
    final LocalServerSocket fdServerSocket = new LocalServerSocket("fdsock");
    try {

      ExecutorService executorService = Executors.newFixedThreadPool(16);
      while (isRunning()) {
        try {
          final LocalSocket fdSocket = fdServerSocket.accept();
          executorService.submit(
              new Runnable() {
                @Override
                public void run() {
                  try {
                    passFileDescriptor(fdSocket, tunPFD.getFileDescriptor());
                  } catch (Exception e) {
                    LogUtils.e("failed to handle fdsock", e);
                  }
                }
              });
        } catch (Exception e) {
          LogUtils.e("failed to handle fdsock", e);
        }
      }
      executorService.shutdown();
    } finally {
      fdServerSocket.close();
    }
  }
Пример #2
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!");
  }
Пример #3
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());
    }
  }
  /**
   * Runs the zygote in accept-and-fork mode. In this mode, each peer gets its own zygote spawner
   * process. This code is retained for reference only.
   *
   * @throws MethodAndArgsCaller in a child process when a main() should be executed.
   */
  private static void runForkMode() throws MethodAndArgsCaller {
    while (true) {
      ZygoteConnection peer = acceptCommandPeer();

      int pid;

      pid = Zygote.fork();

      if (pid == 0) {
        // The child process should handle the peer requests

        // The child does not accept any more connections
        try {
          sServerSocket.close();
        } catch (IOException ex) {
          Log.e(TAG, "Zygote Child: error closing sockets", ex);
        } finally {
          sServerSocket = null;
        }

        peer.run();
        break;
      } else if (pid > 0) {
        peer.closeSocket();
      } else {
        throw new RuntimeException("Error invoking fork()");
      }
    }
  }
 /** Waits for and accepts a single command connection. Throws RuntimeException on failure. */
 private static ZygoteConnection acceptCommandPeer() {
   try {
     return new ZygoteConnection(sServerSocket.accept());
   } catch (IOException ex) {
     throw new RuntimeException("IOException during accept()", ex);
   }
 }
Пример #6
0
  @Override
  public void onDestroy() {
    super.onDestroy();

    Log.i(TAG, "Stopping service");

    stopForeground(true);

    if (acceptor != null) {
      try {
        acceptor.close();
      } catch (IOException e) {
        // We don't care
      }
    }

    try {
      executor.shutdownNow();
      executor.awaitTermination(10, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
      // Too bad
    } finally {
      started = false;

      // Unfortunately, we have no way to clean up some Binder-based callbacks
      // (namely IRotationWatcher) on lower API levels without killing the process,
      // which will allow DeathRecipient to handle it on their side.
      Process.killProcess(Process.myPid());
    }
  }
 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);
 }
 public void release() {
   stop();
   try {
     lss.close();
   } catch (Exception ignore) {
   }
   super.release();
 }
  /** Close and clean up zygote sockets. Called on shutdown and on the child's exit path. */
  static void closeServerSocket() {
    try {
      if (sServerSocket != null) {
        FileDescriptor fd = sServerSocket.getFileDescriptor();
        sServerSocket.close();
        if (fd != null) {
          Os.close(fd);
        }
      }
    } catch (IOException ex) {
      Log.e(TAG, "Zygote:  error closing sockets", ex);
    } catch (ErrnoException ex) {
      Log.e(TAG, "Zygote:  error closing descriptor", ex);
    }

    sServerSocket = null;
  }
Пример #10
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);
    }
  }
Пример #11
0
    @Override
    public void interrupt() {
      super.interrupt();

      try {
        acceptor.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
Пример #12
0
  /** Close and clean up zygote sockets. Called on shutdown and on the child's exit path. */
  static void closeServerSocket() {
    try {
      if (sServerSocket != null) {
        sServerSocket.close();
      }
    } catch (IOException ex) {
      Log.e(TAG, "Zygote:  error closing sockets", ex);
    }

    sServerSocket = null;
  }
Пример #13
0
  /**
   * Runs the zygote process's select loop. Accepts new connections as they happen, and reads
   * commands from connections one spawn-request's worth at a time.
   *
   * @throws MethodAndArgsCaller in a child process when a main() should be executed.
   */
  private static void runSelectLoopMode() throws MethodAndArgsCaller {
    ArrayList<FileDescriptor> fds = new ArrayList();
    ArrayList<ZygoteConnection> peers = new ArrayList();
    FileDescriptor[] fdArray = new FileDescriptor[4];

    fds.add(sServerSocket.getFileDescriptor());
    peers.add(null);

    int loopCount = GC_LOOP_COUNT;
    while (true) {
      int index;

      /*
       * Call gc() before we block in select().
       * It's work that has to be done anyway, and it's better
       * to avoid making every child do it.  It will also
       * madvise() any free memory as a side-effect.
       *
       * Don't call it every time, because walking the entire
       * heap is a lot of overhead to free a few hundred bytes.
       */
      if (loopCount <= 0) {
        gc();
        loopCount = GC_LOOP_COUNT;
      } else {
        loopCount--;
      }

      try {
        fdArray = fds.toArray(fdArray);
        index = selectReadable(fdArray);
      } catch (IOException ex) {
        throw new RuntimeException("Error in select()", ex);
      }

      if (index < 0) {
        throw new RuntimeException("Error in select()");
      } else if (index == 0) {
        ZygoteConnection newPeer = acceptCommandPeer();
        peers.add(newPeer);
        fds.add(newPeer.getFileDesciptor());
      } else {
        boolean done;
        done = peers.get(index).runOnce();

        if (done) {
          peers.remove(index);
          fds.remove(index);
        }
      }
    }
  }
Пример #14
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!");
  }
Пример #15
0
    @Override
    public void run() {
      String socketName = acceptor.getLocalSocketAddress().getName();
      Log.i(TAG, String.format("Server listening on @%s", socketName));

      try {
        while (!isInterrupted()) {
          Connection conn = new Connection(acceptor.accept());
          executor.submit(conn);
        }
      } catch (IOException e) {
      } finally {
        Log.i(TAG, "Server stopping");

        try {
          acceptor.close();
        } catch (IOException e) {
        }

        stopSelf();
      }
    }
Пример #16
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) {
     }
   }
 }
  /**
   * Runs the zygote process's select loop. Accepts new connections as they happen, and reads
   * commands from connections one spawn-request's worth at a time.
   *
   * @throws MethodAndArgsCaller in a child process when a main() should be executed.
   */
  private static void runSelectLoop(String abiList) throws MethodAndArgsCaller {
    ArrayList<FileDescriptor> fds = new ArrayList<FileDescriptor>();
    ArrayList<ZygoteConnection> peers = new ArrayList<ZygoteConnection>();

    fds.add(sServerSocket.getFileDescriptor());
    peers.add(null);

    while (true) {
      StructPollfd[] pollFds = new StructPollfd[fds.size()];
      for (int i = 0; i < pollFds.length; ++i) {
        pollFds[i] = new StructPollfd();
        pollFds[i].fd = fds.get(i);
        pollFds[i].events = (short) POLLIN;
      }
      try {
        Os.poll(pollFds, -1);
      } catch (ErrnoException ex) {
        throw new RuntimeException("poll failed", ex);
      }
      for (int i = pollFds.length - 1; i >= 0; --i) {
        if ((pollFds[i].revents & POLLIN) == 0) {
          continue;
        }
        if (i == 0) {
          ZygoteConnection newPeer = acceptCommandPeer(abiList);
          peers.add(newPeer);
          fds.add(newPeer.getFileDesciptor());
        } else {
          boolean done = peers.get(i).runOnce();
          if (done) {
            peers.remove(i);
            fds.remove(i);
          }
        }
      }
    }
  }
  @Override
  public void onMessage(final DataChannel.Buffer inbuf) {

    ByteBuffer data = inbuf.data;
    if (inbuf.binary) {
      if (bStart) {
        try {
          if (writableByteChannel != null) {
            writableByteChannel.write(data);
          } else {
            Log.e(TAG, "writeableByteChannel is null");
          }
        } catch (Exception e) {
          Log.d(TAG, "os write fail:" + e);
        }
      }
    } else {
      int size = data.remaining();
      byte[] bytes = new byte[size];
      data.get(bytes);

      String command = new String(bytes);
      String[] cmd_split = command.split(":");
      String msgType = cmd_split[0];
      String msgKey = cmd_split[1];

      if (isAudioMessage(msgType)) {
        String audioMsg = "Get Audio: ";
        Log.d(TAG, audioMsg + command);

        if (msgKey.equalsIgnoreCase("SET")) {

          if (cmd_split[2].equalsIgnoreCase("OV")) {
            sourceType = SourceType.OV;
            setting = "";
          } else if (cmd_split[2].equalsIgnoreCase("RTSP")) {
            sourceType = SourceType.RTSP;
            // collect parameter after SET:
            // ex: 1. AUDIO:SET:RTSP:AAC:1:8000:1588:.....
            // ex: 2. AUDIO:SET:RTSP:mG711:1:....
            // ex: 3. AUDIO:SET:RTSP:aG711:1:....
            setting = command.substring(10, command.length());
            Log.d(TAG, setting);
          }
        }

        if (msgKey.equalsIgnoreCase("START")) {

          if (sourceType == SourceType.UNKNOWN) {
            Log.e(TAG, "Audio Something wrong!!");
            return;
          }

          audioMsg = audioMsg + "START";

          if (at != null) {
            at.setStop();
            at.interrupt();
            at = null;
          }

          if (nat != null) {
            nat.setStop();
            nat.interrupt();
            nat = null;
          }

          for (int jj = 0; jj < 10; jj++) {
            try {
              mSocketId = new Random().nextInt();
              mLss = new LocalServerSocket(LOCAL_ADDR + mSocketId);
              break;
            } catch (IOException e) {
              Log.e(TAG, "fail to create localserversocket :" + e);
            }
          }

          //    DECODE FLOW
          //
          //    Intermediary:                             Localsocket       MediaCodec inputBuffer
          //   MediaCodec outputBuffer
          //        Flow    : Data Channel =======> Sender ========> Receiver ==================>
          // Decoder =================> Display to surface/ Play by Audio Track
          //       Thread   : |<---Data Channel thread--->|          |<--------- Decode Thread
          // --------->|                 |<--------- Display/play Thread -------->|
          //
          mReceiver = new LocalSocket();
          try {
            mReceiver.connect(new LocalSocketAddress(LOCAL_ADDR + mSocketId));
            mReceiver.setReceiveBufferSize(100000);
            mReceiver.setSoTimeout(200);
            mSender = mLss.accept();
            mSender.setSendBufferSize(100000);
          } catch (IOException e) {
            Log.e(TAG, "fail to create mSender mReceiver :" + e);
            e.printStackTrace();
          }
          try {
            os = mSender.getOutputStream();
            writableByteChannel = Channels.newChannel(os);
            is = mReceiver.getInputStream();
          } catch (IOException e) {
            Log.e(TAG, "fail to get mSender mReceiver :" + e);
            e.printStackTrace();
          }
          bStart = true;

          if (sourceType == SourceType.OV) {
            // using self adpcm_ima decoder to decode audio
            at = new AudioThread(is);
            at.start();
          } else if (sourceType == SourceType.RTSP) {
            // using mediaCodec to decode audio
            nat = new NormalAudioThread(is, setting);
            nat.start();
          }
        }

        if (msgKey.equalsIgnoreCase("STOP")) {
          if (bStart) {
            audioMsg = audioMsg + "STOP";

            try {
              os.close();
              is.close();
              writableByteChannel.close();
              writableByteChannel = null;
              os = null;
              is = null;
            } catch (Exception e) {
              Log.e(TAG, "Close input/output stream error : " + e);
            }

            if (at != null) {
              at.setStop();
              at.interrupt();
              at = null;
            }

            if (nat != null) {
              nat.setStop();
              nat.interrupt();
              nat = null;
            }

            bStart = false;
          }
        }
      }
    }
  }
 /**
  * Return the server socket's underlying file descriptor, so that ZygoteConnection can pass it to
  * the native code for proper closure after a child process is forked off.
  */
 static FileDescriptor getServerSocketFileDescriptor() {
   return sServerSocket.getFileDescriptor();
 }
Пример #20
0
  public void testLocalConnections() throws IOException {
    // create client and server socket
    LocalServerSocket localServerSocket = new LocalServerSocket(mSockAddr);
    LocalSocket clientSocket = new LocalSocket();

    // establish connection between client and server
    LocalSocketAddress locSockAddr = new LocalSocketAddress(mSockAddr);
    assertFalse(clientSocket.isConnected());
    clientSocket.connect(locSockAddr);
    assertTrue(clientSocket.isConnected());
    LocalSocket serverSocket = localServerSocket.accept();

    Credentials credent = clientSocket.getPeerCredentials();
    assertTrue(0 != credent.getPid());

    // send data from client to server
    OutputStream clientOutStream = clientSocket.getOutputStream();
    clientOutStream.write(12);
    InputStream serverInStream = serverSocket.getInputStream();
    assertEquals(12, serverInStream.read());

    // send data from server to client
    OutputStream serverOutStream = serverSocket.getOutputStream();
    serverOutStream.write(3);
    InputStream clientInStream = clientSocket.getInputStream();
    assertEquals(3, clientInStream.read());

    // Test sending and receiving file descriptors
    clientSocket.setFileDescriptorsForSend(new FileDescriptor[] {FileDescriptor.in});
    clientOutStream.write(32);
    assertEquals(32, serverInStream.read());

    FileDescriptor[] out = serverSocket.getAncillaryFileDescriptors();
    assertEquals(1, out.length);
    FileDescriptor fd = clientSocket.getFileDescriptor();
    assertTrue(fd.valid());

    // shutdown input stream of client
    clientSocket.shutdownInput();
    assertEquals(-1, clientInStream.read());

    // shutdown output stream of client
    clientSocket.shutdownOutput();
    try {
      clientOutStream.write(10);
      fail("testLocalSocket shouldn't come to here");
    } catch (IOException e) {
      // expected
    }

    // shutdown input stream of server
    serverSocket.shutdownInput();
    assertEquals(-1, serverInStream.read());

    // shutdown output stream of server
    serverSocket.shutdownOutput();
    try {
      serverOutStream.write(10);
      fail("testLocalSocket shouldn't come to here");
    } catch (IOException e) {
      // expected
    }

    // close client socket
    clientSocket.close();
    try {
      clientInStream.read();
      fail("testLocalSocket shouldn't come to here");
    } catch (IOException e) {
      // expected
    }

    // close server socket
    serverSocket.close();
    try {
      serverInStream.read();
      fail("testLocalSocket shouldn't come to here");
    } catch (IOException e) {
      // expected
    }
  }