Beispiel #1
0
        //-------------------------------------------------------------------------------------------------------------
        // Operations
        //-------------------------------------------------------------------------------------------------------------

        /**
         * Opens a socket to the indicated device at indicated address and port
         *
         * @exception   SocketException thrown when the socket parameters are invalid
         * @exception   AdbException    Thrown when an Adb error condition occurs
         *
         * @param   address The address.
         * @param   device  the device to connect to. Can be null in which case the connection will be to the first available
         *                  device.
         * @param   port    The port.
         *
         * @return  A Socket.
         */
        public Socket Open(IPAddress address, Device device, int port)
        {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                s.Connect(address, port);
                s.Blocking = true;
                s.NoDelay  = false;

                SetDevice(s, device?.SerialNumber);

                byte[] req = CreateAdbForwardRequest(null, port);
                Write(s, req);
                AdbResponse resp = ReadAdbResponse(s);
                if (!resp.Okay)
                {
                    throw new AdbException("connection request rejected");
                }
                s.Blocking = true;
            }
            catch (Exception)
            {
                s?.Close();
                throw;
            }
            return(s);
        }
Beispiel #2
0
        /** Asks the local ADB server to connect to the indicated device over IP */
        public bool Connect(IPEndPoint adbServerEP, string hostNameOrAddress, int port)
        // Returns success/fail
        {
            bool result = false;

            string addressAndPort = $"{hostNameOrAddress}:{port}";

            byte[] request = FormAdbRequest($"host:connect:{addressAndPort}");
            using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                socket.Connect(adbServerEP);
                socket.Blocking = true;
                Write(socket, request);

                // The response is a length-prefixed OKAY string
                AdbResponse resp = ReadAdbResponseWithDiagnosis(socket);
                if (resp.IOSuccess && resp.Okay)
                {
                    // The two 'success' cases are
                    //      "already connected to %s"
                    //      "connected to %s"
                    result = "already connected to".IsPrefixOf(resp.Message) || "connected to".IsPrefixOf(resp.Message);
                }
            }

            return(result);
        }
Beispiel #3
0
        public bool CreateForward(IPEndPoint adbSockAddr, Device device, int localPort, int remotePort)
        {
            Socket adbChan = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                adbChan.Connect(adbSockAddr);
                adbChan.Blocking = true;

                // host-serial should be different based on the transport...
                byte[] request = FormAdbRequest($"host-serial:{device.SerialNumber}:forward:tcp:{localPort};tcp:{remotePort}");

                Write(adbChan, request);

                AdbResponse resp = ReadAdbResponse(adbChan);
                if (!resp.IOSuccess || !resp.Okay)
                {
                    throw new AdbException("Device rejected command: " + resp.Message);
                }
            }
            finally
            {
                adbChan?.Close();
            }

            return(true);
        }
Beispiel #4
0
        public Socket CreatePassThroughConnection(IPEndPoint endpoint, Device device, int pid)
        {
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                socket.Connect(endpoint);
                socket.NoDelay = true;

                // if the device is not -1, then we first tell adb we're looking to talk to a specific device
                SetDevice(socket, device?.SerialNumber);

                byte[] req = CreateJdwpForwardRequest(pid);

                Write(socket, req);

                AdbResponse resp = ReadAdbResponse(socket);
                if (!resp.Okay)
                {
                    throw new AdbException("connection request rejected: " + resp.Message); //$NON-NLS-1$
                }
            }
            catch (Exception)
            {
                socket?.Close();
                throw;
            }

            return(socket);
        }
Beispiel #5
0
        /** Returns the  version number of the currently running ADB server */
        public int GetAdbServerVersion(IPEndPoint address)
        {
            using (Socket adbChan = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                byte[] request = FormAdbRequest("host:version");
                byte[] reply;

                adbChan.Connect(address);
                adbChan.Blocking = true;
                Write(adbChan, request);

                AdbResponse resp = ReadAdbResponse(adbChan);
                if (!resp.IOSuccess || !resp.Okay)
                {
                    Log.e(LOGGING_TAG, "Got timeout or unhappy response from ADB fb req: " + resp.Message);
                    return(-1);
                }

                // response is four hex bytes
                reply = new byte[4];
                Read(adbChan, reply);

                string lenHex = reply.GetString(DEFAULT_ENCODING);
                int    len    = int.Parse(lenHex, NumberStyles.HexNumber);

                // the server version (NOT the server protocol version)
                reply = new byte[len];
                Read(adbChan, reply);

                string sReply = reply.GetString(DEFAULT_ENCODING);
                return(int.Parse(sReply, NumberStyles.HexNumber));
            }
        }
Beispiel #6
0
        // Read and parse a response from the ADB server. Throw if we don't
        // get enough data from the server to form a response
        public AdbResponse ReadAdbResponseInternal(Socket socket, bool suppressLogging, bool readDiagString)
        {
            AdbResponse resp = new AdbResponse();

            byte[] reply = new byte[4];
            Read(socket, reply);    // throws
            resp.IOSuccess = true;
            resp.Okay      = IsOkay(reply);
            if (!resp.Okay)
            {
                readDiagString = true; // look for a reason after the FAIL
            }
            // not a loop -- use "while" so we can use "break"
            while (readDiagString)
            {
                // length string is in next 4 bytes
                byte[] lenBuf = new byte[4];
                Read(socket, lenBuf);   // throws

                string lenStr = ReplyToString(lenBuf);

                int len;
                try
                {
                    len = int.Parse(lenStr, NumberStyles.HexNumber);
                }
                catch (FormatException)
                {
                    Log.e(LOGGING_TAG, "Expected digits, got '{0}' : {1} {2} {3} {4}", lenStr, lenBuf[0], lenBuf[1], lenBuf[2], lenBuf[3]);
                    Log.e(LOGGING_TAG, "reply was {0}", ReplyToString(reply));
                    break;
                }

                byte[] msg = new byte[len];
                Read(socket, msg);

                resp.Message = ReplyToString(msg);
                if (!suppressLogging)
                {
                    Log.e(LOGGING_TAG, "reply='{0}', diag='{1}'", ReplyToString(reply), resp.Message);
                }

                break;
            }

            return(resp);
        }
Beispiel #7
0
        // throws on socket issues
        private Socket ExecuteRawSocketCommand(IPEndPoint address, string serialNumber, byte[] command)
        {
            Socket adbChan = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            adbChan.Connect(address);
            adbChan.Blocking = true;
            SetDevice(adbChan, serialNumber);
            Write(adbChan, command);

            AdbResponse resp = ReadAdbResponse(adbChan);

            if (!resp.IOSuccess || !resp.Okay)
            {
                throw new AdbException($"Device {serialNumber} rejected command: {resp.Message}");
            }
            return(adbChan);
        }
Beispiel #8
0
 public int KillAdb(IPEndPoint address)
 {
     byte[] request = FormAdbRequest("host:kill");
     using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
     {
         socket.Connect(address);
         socket.Blocking = true;
         Write(socket, request);
         AdbResponse resp = ReadAdbResponse(socket);
         if (!resp.IOSuccess || !resp.Okay)
         {
             Log.e(LOGGING_TAG, "Got timeout or unhappy response from ADB req: " + resp.Message);
             socket.Close();
             return(-1);
         }
         return(0);
     }
 }
Beispiel #9
0
        //---------------------------------------------------------------------------------------------------------------
        // Device tracking
        //---------------------------------------------------------------------------------------------------------------

        #region Device Tracking

        /**
         * Ask the ADB server to inform us of the connection and disconnection of devices
         *
         * @exception   IOException Thrown when an IO failure occurred.
         *
         * @return  true if it succeeds, false if it fails.
         */
        private bool RequestDeviceNotifications()
        {
            byte[] request = AdbHelper.Instance.FormAdbRequest("host:track-devices");
            AdbHelper.Instance.Write(this.socketTrackDevices, request);

            AdbResponse resp = AdbHelper.Instance.ReadAdbResponse(this.socketTrackDevices);

            if (!resp.IOSuccess)
            {
                Log.e(loggingTag, "Failed to read the adb response!");
                this.CloseSocket(ref this.socketTrackDevices);
                throw new IOException("Failed to read the adb response!");
            }

            if (!resp.Okay)
            {
                // request was refused by adb!
                Log.e(loggingTag, "adb refused request: {0}", resp.Message);
            }

            return(resp.Okay);
        }
Beispiel #10
0
        /// <summary>
        /// Opens this connection.
        /// </summary>
        /// <returns></returns>
        public bool Open()
        {
            if (IsOpen)
            {
                return(true);
            }

            try
            {
                Channel = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                Channel.Connect(this.Address);
                Channel.Blocking = true;

                // target a specific device
                AdbHelper.Instance.SetDevice(Channel, Device?.SerialNumber);

                byte[] request = AdbHelper.Instance.FormAdbRequest("sync:");
                AdbHelper.Instance.Write(Channel, request, -1, DdmPreferences.Timeout);

                AdbResponse resp = AdbHelper.Instance.ReadAdbResponse(Channel);

                if (!resp.IOSuccess || !resp.Okay)
                {
                    Log.w("ddms:syncservice", "Got timeout or unhappy response from ADB sync req: {0}", resp.Message);
                    Channel.Close();
                    Channel = null;
                    return(false);
                }
            }
            catch (IOException)
            {
                Close();
                throw;
            }

            return(true);
        }
Beispiel #11
0
        public void SetDevice(Socket adbChan, string serialNumber)
        {
            // if the device is not null, then we first tell adb we're looking to talk to a specific device
            if (serialNumber != null)
            {
                string msg          = "host:transport:" + serialNumber;
                byte[] device_query = FormAdbRequest(msg);

                Write(adbChan, device_query);

                AdbResponse resp = ReadAdbResponseNoLogging(adbChan);
                if (!resp.Okay)
                {
                    if (equalsIgnoreCase("device not found", resp.Message))
                    {
                        throw new DeviceNotFoundException(serialNumber);
                    }
                    else
                    {
                        throw new AdbException("device (" + serialNumber + ") request rejected: " + resp.Message);
                    }
                }
            }
        }
Beispiel #12
0
        // Read and parse a response from the ADB server. Throw if we don't
        // get enough data from the server to form a response
        public AdbResponse ReadAdbResponseInternal(Socket socket, bool suppressLogging, bool readDiagString)
            {
            AdbResponse resp = new AdbResponse();

            byte[] reply = new byte[4];
            Read(socket, reply);    // throws
            resp.IOSuccess      = true;
            resp.Okay           = IsOkay(reply);
            if (!resp.Okay)
                readDiagString = true; // look for a reason after the FAIL

            // not a loop -- use "while" so we can use "break"
            while (readDiagString)
                {
                // length string is in next 4 bytes
                byte[] lenBuf = new byte[4];
                Read(socket, lenBuf);   // throws

                string lenStr = ReplyToString(lenBuf);

                int len;
                try
                    {
                    len = int.Parse(lenStr, NumberStyles.HexNumber);
                    }
                catch (FormatException)
                    {
                    Log.e(LOGGING_TAG, "Expected digits, got '{0}' : {1} {2} {3} {4}", lenStr, lenBuf[0], lenBuf[1], lenBuf[2], lenBuf[3]);
                    Log.e(LOGGING_TAG, "reply was {0}", ReplyToString(reply));
                    break;
                    }

                byte[] msg = new byte[len];
                Read(socket, msg);

                resp.Message = ReplyToString(msg);
                if (!suppressLogging)
                    Log.e(LOGGING_TAG, "reply='{0}', diag='{1}'", ReplyToString(reply), resp.Message);

                break;
                }

            return resp;
            }
Beispiel #13
0
        public RawImage GetFrameBuffer(IPEndPoint adbSockAddr, Device device)
        {
            RawImage imageParams = new RawImage();

            byte[] request = FormAdbRequest("framebuffer:"); //$NON-NLS-1$
            byte[] nudge   = { 0 };
            byte[] reply;

            Socket adbChan = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                adbChan.Connect(adbSockAddr);
                adbChan.Blocking = true;

                // if the device is not -1, then we first tell adb we're looking to talk
                // to a specific device
                SetDevice(adbChan, device?.SerialNumber);
                Write(adbChan, request);

                AdbResponse resp = ReadAdbResponse(adbChan);
                if (!resp.IOSuccess || !resp.Okay)
                {
                    Log.v(LOGGING_TAG, "Got timeout or unhappy response from ADB fb req: " + resp.Message);
                    adbChan.Close();
                    return(null);
                }

                // first the protocol version.
                reply = new byte[4];
                Read(adbChan, reply);
                BinaryReader buf;
                int          version = 0;
                using (MemoryStream ms = new MemoryStream(reply))
                {
                    buf     = new BinaryReader(ms);
                    version = buf.ReadInt16();
                }

                // get the header size (this is a count of int)
                int headerSize = RawImage.GetHeaderSize(version);
                // read the header
                reply = new byte[headerSize * 4];
                Read(adbChan, reply);
                using (MemoryStream ms = new MemoryStream(reply))
                {
                    buf = new BinaryReader(ms);

                    // fill the RawImage with the header
                    if (imageParams.ReadHeader(version, buf) == false)
                    {
                        Log.v(LOGGING_TAG, "Unsupported protocol: " + version);
                        return(null);
                    }
                }

                Log.d(LOGGING_TAG, "image params: bpp=" + imageParams.Bpp + ", size="
                      + imageParams.Size + ", width=" + imageParams.Width
                      + ", height=" + imageParams.Height);

                Write(adbChan, nudge);

                reply = new byte[imageParams.Size];
                Read(adbChan, reply);
                imageParams.Data = reply;
            }
            finally
            {
                adbChan?.Close();
            }

            return(imageParams);
        }