예제 #1
0
        /// <summary>
        /// Runs a log service on the <seealso cref="Device"/>, and provides its output to the <seealso cref="LogReceiver"/>.
        /// <p/>This call is blocking until <seealso cref="LogReceiver#isCancelled()"/> returns true. </summary>
        /// <param name="adbSockAddr"> the socket address to connect to adb </param>
        /// <param name="device"> the Device on which to run the service </param>
        /// <param name="logName"> the name of the log file to output </param>
        /// <param name="rcvr"> the <seealso cref="LogReceiver"/> to receive the log output </param>
        /// <exception cref="TimeoutException"> in case of timeout on the connection. </exception>
        /// <exception cref="AdbCommandRejectedException"> if adb rejects the command </exception>
        /// <exception cref="IOException"> in case of I/O error on the connection. </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public static void runLogService(java.net.InetSocketAddress adbSockAddr, Device device, String logName, com.android.ddmlib.log.LogReceiver rcvr) throws TimeoutException, AdbCommandRejectedException, java.io.IOException
        public static void runLogService(EndPoint adbSockAddr, Device device, string logName, LogReceiver rcvr)
        {
            SocketChannel adbChan = null;

            try
            {
                adbChan = SocketChannel.open(adbSockAddr);
                adbChan.configureBlocking(false);

                // if the device is not -1, then we first tell adb we're looking to talk
                // to a specific device
                setDevice(adbChan, device);

                var request = formAdbRequest("log:" + logName);
                write(adbChan, request);

                AdbResponse resp = readAdbResponse(adbChan, false);                 // readDiagString
                if (resp.okay == false)
                {
                    throw new AdbCommandRejectedException(resp.message);
                }

                var        data = new byte[16384];
                ByteBuffer buf  = ByteBuffer.wrap(data);
                while (true)
                {
                    int count;

                    if (rcvr != null && rcvr.cancelled)
                    {
                        break;
                    }

                    count = adbChan.read(buf);
                    if (count < 0)
                    {
                        break;
                    }
                    else if (count == 0)
                    {
                        Thread.Sleep(WAIT_TIME * 5);
                    }
                    else
                    {
                        if (rcvr != null)
                        {
                            rcvr.parseNewData(buf.array(), buf.arrayOffset(), buf.position);
                        }
                        buf.rewind();
                    }
                }
            }
            finally
            {
                if (adbChan != null)
                {
                    adbChan.close();
                }
            }
        }
예제 #2
0
        public void ExecuteRemoteCommandUnresponsiveTest()
        {
            var device = new DeviceData()
            {
                Serial = "169.254.109.177:5555",
                State  = DeviceState.Online
            };

            var responses = new AdbResponse[]
            {
                AdbResponse.OK,
                AdbResponse.OK
            };

            var responseMessages = new string[] { };

            var requests = new string[]
            {
                "host:transport:169.254.109.177:5555",
                "shell:echo Hello, World"
            };

            var receiver = new ConsoleOutputReceiver();

            Assert.Throws <ShellCommandUnresponsiveException>(() => this.RunTest(
                                                                  responses,
                                                                  responseMessages,
                                                                  requests,
                                                                  null,
                                                                  () =>
            {
                this.TestClient.ExecuteRemoteCommand("echo Hello, World", device, receiver);
            }));
        }
예제 #3
0
        public void ListReverseForwardTest()
        {
            var responseMessages = new string[] {
                "(reverse) localabstract:scrcpy tcp:100\n(reverse) localabstract: scrcpy2 tcp:100\n(reverse) localabstract: scrcpy3 tcp:100\n"
            };
            var responses = new AdbResponse[]
            {
                AdbResponse.OK,
                AdbResponse.OK,
            };

            var requests = new string[]
            {
                "host:transport:169.254.109.177:5555",
                "reverse:list-forward"
            };

            ForwardData[] forwards = null;

            this.RunTest(
                responses,
                responseMessages,
                requests,
                () => forwards = this.TestClient.ListReverseForward(Device).ToArray());

            Assert.NotNull(forwards);
            Assert.Equal(3, forwards.Length);
            Assert.Equal("(reverse)", forwards[0].SerialNumber);
            Assert.Equal("localabstract:scrcpy", forwards[0].Local);
            Assert.Equal("tcp:100", forwards[0].Remote);
        }
예제 #4
0
        /// <summary>
        /// Remove a port forwarding between a local and a remote port. </summary>
        /// <param name="adbSockAddr"> the socket address to connect to adb </param>
        /// <param name="device"> the device on which to remove the port fowarding </param>
        /// <param name="localPort"> the local port of the forward </param>
        /// <param name="remotePort"> the remote port. </param>
        /// <exception cref="TimeoutException"> in case of timeout on the connection. </exception>
        /// <exception cref="AdbCommandRejectedException"> if adb rejects the command </exception>
        /// <exception cref="IOException"> in case of I/O error on the connection. </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public static void removeForward(java.net.InetSocketAddress adbSockAddr, Device device, int localPort, int remotePort) throws TimeoutException, AdbCommandRejectedException, java.io.IOException
        public static void removeForward(EndPoint adbSockAddr, Device device, int localPort, int remotePort)
        {
            SocketChannel adbChan = null;

            try
            {
                adbChan = SocketChannel.open(adbSockAddr);
                adbChan.configureBlocking(false);

                var request = formAdbRequest(string.Format("host-serial:{0}:killforward:tcp:{1:D};tcp:{2:D}", device.serialNumber, localPort, remotePort));                 //$NON-NLS-1$

                write(adbChan, request);

                AdbResponse resp = readAdbResponse(adbChan, false);                 // readDiagString
                if (resp.okay == false)
                {
                    Log.w("remove-forward", "Error creating forward: " + resp.message);
                    throw new AdbCommandRejectedException(resp.message);
                }
            }
            finally
            {
                if (adbChan != null)
                {
                    adbChan.close();
                }
            }
        }
예제 #5
0
        /// <summary>
        /// Reads the response from ADB after a command. </summary>
        /// <param name="chan"> The socket channel that is connected to adb. </param>
        /// <param name="readDiagString"> If true, we're expecting an OKAY response to be
        ///      followed by a diagnostic string. Otherwise, we only expect the
        ///      diagnostic string to follow a FAIL. </param>
        /// <exception cref="TimeoutException"> in case of timeout on the connection. </exception>
        /// <exception cref="IOException"> in case of I/O error on the connection. </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: static AdbResponse readAdbResponse(java.nio.channels.SocketChannel chan, boolean readDiagString) throws TimeoutException, java.io.IOException
        internal static AdbResponse readAdbResponse(SocketChannel chan, bool readDiagString)
        {
            AdbResponse resp = new AdbResponse();

            var reply = new byte[4];

            read(chan, reply);

            if (isOkay(reply))
            {
                resp.okay = true;
            }
            else
            {
                readDiagString = true;                 // look for a reason after the FAIL
                resp.okay      = false;
            }

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

                    string lenStr = replyToString(lenBuf);

                    int len;
                    try
                    {
                        len = Convert.ToInt32(lenStr, 16);
                    }
                    catch (SystemException)
                    {
                        Log.w("ddms", "Expected digits, got '" + lenStr + "': " + lenBuf[0] + " " + lenBuf[1] + " " + lenBuf[2] + " " + lenBuf[3]);
                        Log.w("ddms", "reply was " + replyToString(reply));
                        break;
                    }

                    var msg = new byte[len];
                    read(chan, msg);

                    resp.message = replyToString(msg);
                    Log.v("ddms", "Got reply '" + replyToString(reply) + "', diag='" + resp.message + "'");

                    break;
                }
            }
            catch (Exception)
            {
                // ignore those, since it's just reading the diagnose string, the response will
                // contain okay==false anyway.
            }

            return(resp);
        }
예제 #6
0
        public void Constructor_ValidatesArguments()
        {
            var response = new AdbResponse(AdbResponseStatus.OKAY, string.Empty);

            Assert.Equal(AdbResponseStatus.OKAY, response.Status);
            Assert.Equal(string.Empty, response.Message);

            response = new AdbResponse(AdbResponseStatus.FAIL, "ai");
            Assert.Equal(AdbResponseStatus.FAIL, response.Status);
            Assert.Equal("ai", response.Message);
        }
예제 #7
0
 public static AdbResponse Print(this AdbResponse response)
 {
     Console.Write(response.State + ":");
     try
     {
         Console.Write(response.DataAsString());
     }
     catch (Exception ex)
     {
         //Console.WriteLine(ex);
     }
     Console.Write("\n");
     return(response);
 }
예제 #8
0
        public void SetInvalidDeviceTest()
        {
            var requests = new string[]
            {
                "host:transport:169.254.109.177:5555"
            };

            this.RunTest(
                new AdbResponse[] { AdbResponse.FromError("device not found") },
                NoResponseMessages,
                requests,
                () =>
            {
                AdbClient.Instance.SetDevice(this.Socket, Device);
            });
        }
예제 #9
0
        public void SetDeviceOtherException()
        {
            var requests = new string[]
            {
                "host:transport:169.254.109.177:5555"
            };

            this.RunTest(
                new AdbResponse[] { AdbResponse.FromError("Too many cats.") },
                NoResponseMessages,
                requests,
                () =>
            {
                AdbClient.Instance.SetDevice(this.Socket, Device);
            });
        }
예제 #10
0
        public void SetInvalidDeviceTest()
        {
            var requests = new string[]
            {
                "host:transport:169.254.109.177:5555"
            };

            Assert.Throws <DeviceNotFoundException>(() => this.RunTest(
                                                        new AdbResponse[] { AdbResponse.FromError("device not found") },
                                                        NoResponseMessages,
                                                        requests,
                                                        () =>
            {
                this.Socket.SetDevice(Device);
            }));
        }
예제 #11
0
        public void SetDeviceOtherException()
        {
            var requests = new string[]
            {
                "host:transport:169.254.109.177:5555"
            };

            Assert.Throws <AdbException>(() => this.RunTest(
                                             new AdbResponse[] { AdbResponse.FromError("Too many cats.") },
                                             NoResponseMessages,
                                             requests,
                                             () =>
            {
                this.Socket.SetDevice(Device);
            }));
        }
예제 #12
0
        /// <summary>
        /// Reads the response from ADB after a command. </summary>
        /// <param name="readDiagString"> If true, we're expecting an OKAY response to be
        ///      followed by a diagnostic string. Otherwise, we only expect the
        ///      diagnostic string to follow a FAIL. </param>
        protected AdbResponse ReadAdbResponse(bool readDiagString)
        {
            var resp = new AdbResponse();

            var reply = new byte[4];

            Read(reply);

            if (IsOkay(reply))
            {
                resp.Okay = true;
            }
            else
            {
                readDiagString = true; // look for a reason after the FAIL
                resp.Okay      = false;
            }

            // not a loop -- use "while" so we can use "break"
            try
            {
                while (readDiagString)
                {
                    int len;
                    if (!TryReadHex4(out len))
                    {
                        break;
                    }

                    var msg = new byte[len];
                    Read(msg);

                    resp.Message = ReplyToString(msg);
                    //Log.v("ddms", "Got reply '" + replyToString(reply) + "', diag='" + resp.message + "'");

                    break;
                }
            }
            catch (Exception)
            {
                // ignore those, since it's just reading the diagnose string, the response will
                // contain okay==false anyway.
            }

            return(resp);
        }
예제 #13
0
        /// <summary>
        /// tells adb to talk to a specific device
        /// </summary>
        /// <param name="adbChan"> the socket connection to adb </param>
        /// <param name="device"> The device to talk to. </param>
        /// <exception cref="TimeoutException"> in case of timeout on the connection. </exception>
        /// <exception cref="AdbCommandRejectedException"> if adb rejects the command </exception>
        /// <exception cref="IOException"> in case of I/O error on the connection. </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: static void setDevice(java.nio.channels.SocketChannel adbChan, IDevice device) throws TimeoutException, AdbCommandRejectedException, java.io.IOException
        internal static void setDevice(SocketChannel adbChan, IDevice device)
        {
            // if the device is not -1, then we first tell adb we're looking to talk
            // to a specific device
            if (device != null)
            {
                string msg          = "host:transport:" + device.serialNumber;        //$NON-NLS-1$
                var    device_query = formAdbRequest(msg);

                write(adbChan, device_query);

                AdbResponse resp = readAdbResponse(adbChan, false);                 // readDiagString
                if (resp.okay == false)
                {
                    throw new AdbCommandRejectedException(resp.message, true);                     //errorDuringDeviceSelection
                }
            }
        }
예제 #14
0
        public void ReadLogTest()
        {
            var device = new DeviceData()
            {
                Serial = "169.254.109.177:5555",
                State  = DeviceState.Online
            };

            var responses = new AdbResponse[]
            {
                AdbResponse.OK,
                AdbResponse.OK
            };

            var responseMessages = new string[] { };

            var requests = new string[]
            {
                "host:transport:169.254.109.177:5555",
                "shell:logcat -B -b system"
            };

            var receiver = new ConsoleOutputReceiver();

            using (Stream stream = File.OpenRead("logcat.bin"))
                using (ShellStream shellStream = new ShellStream(stream, false))
                {
                    Collection <Logs.LogEntry> logs = new Collection <LogEntry>();
                    Action <LogEntry>          sink = (entry) => logs.Add(entry);

                    this.RunTest(
                        responses,
                        responseMessages,
                        requests,
                        shellStream,
                        () =>
                    {
                        this.TestClient.RunLogServiceAsync(device, sink, CancellationToken.None, Logs.LogId.System).Wait();
                    });

                    Assert.Equal(3, logs.Count());
                }
        }
예제 #15
0
        public void ReadLogTest()
        {
            var device = new DeviceData()
            {
                Serial = "169.254.109.177:5555",
                State  = DeviceState.Online
            };

            var responses = new AdbResponse[]
            {
                AdbResponse.OK,
                AdbResponse.OK
            };

            var responseMessages = new string[] { };

            var requests = new string[]
            {
                "host:transport:169.254.109.177:5555",
                "shell:logcat -B -b system"
            };

            var receiver = new ConsoleOutputReceiver();

            using (Stream stream = File.OpenRead("logcat.bin"))
                using (ShellStream shellStream = new ShellStream(stream, false))
                {
                    Logs.LogEntry[] logs = null;

                    this.RunTest(
                        responses,
                        responseMessages,
                        requests,
                        shellStream,
                        () =>
                    {
                        logs = AdbClient.Instance.RunLogService(device, Logs.LogId.System).ToArray();
                    });

                    Assert.AreEqual(3, logs.Count());
                }
        }
예제 #16
0
        public void GetHashCodeTest()
        {
            AdbResponse first = new AdbResponse()
            {
                IOSuccess = false,
                Message   = "Hi",
                Okay      = false,
                Timeout   = false
            };

            AdbResponse second = new AdbResponse()
            {
                IOSuccess = false,
                Message   = "Hi",
                Okay      = false,
                Timeout   = false
            };

            Assert.AreEqual(first.GetHashCode(), second.GetHashCode());
        }
예제 #17
0
        public void RemoveReverseForwardTest()
        {
            var requests = new string[]
            {
                "host:transport:169.254.109.177:5555",
                "reverse:killforward:localabstract:test"
            };

            var responses = new AdbResponse[]
            {
                AdbResponse.OK,
                AdbResponse.OK,
            };

            this.RunTest(
                responses,
                NoResponseMessages,
                requests,
                () => this.TestClient.RemoveReverseForward(Device, "localabstract:test"));
        }
예제 #18
0
        public void RemoveAllReversesTest()
        {
            var requests = new string[]
            {
                "host:transport:169.254.109.177:5555",
                "reverse:killforward-all"
            };

            var responses = new AdbResponse[]
            {
                AdbResponse.OK,
                AdbResponse.OK,
            };

            this.RunTest(
                responses,
                NoResponseMessages,
                requests,
                () => this.TestClient.RemoveAllReverseForwards(Device));
        }
예제 #19
0
        public void CreateDuplicateForwardTest()
        {
            var responses = new AdbResponse[]
            {
                AdbResponse.FromError("cannot rebind existing socket")
            };

            var requests = new string[]
            {
                "host-serial:169.254.109.177:5555:forward:norebind:tcp:1;tcp:2"
            };

            Assert.Throws <AdbException>(() => this.RunTest(
                                             responses,
                                             NoResponseMessages,
                                             requests,
                                             () =>
            {
                this.TestClient.CreateForward(Device, "tcp:1", "tcp:2", false);
            }));
        }
예제 #20
0
        public void ExecuteRemoteCommandTest()
        {
            var device = new DeviceData()
            {
                Serial = "169.254.109.177:5555",
                State  = DeviceState.Online
            };

            var responses = new AdbResponse[]
            {
                AdbResponse.OK,
                AdbResponse.OK
            };

            var responseMessages = new string[] { };

            var requests = new string[]
            {
                "host:transport:169.254.109.177:5555",
                "shell:echo Hello, World"
            };

            byte[]       streamData  = Encoding.ASCII.GetBytes("Hello, World\r\n");
            MemoryStream shellStream = new MemoryStream(streamData);

            var receiver = new ConsoleOutputReceiver();

            this.RunTest(
                responses,
                responseMessages,
                requests,
                shellStream,
                () =>
            {
                this.TestClient.ExecuteRemoteCommand("echo Hello, World", device, receiver);
            });

            Assert.Equal("Hello, World\r\n", receiver.ToString(), ignoreLineEndingDifferences: true);
        }
예제 #21
0
        public void EqualsTest()
        {
            AdbResponse first = new AdbResponse()
            {
                IOSuccess = false,
                Message   = "Hi",
                Okay      = false,
                Timeout   = false
            };

            AdbResponse second = new AdbResponse()
            {
                IOSuccess = true,
                Message   = "Hi",
                Okay      = false,
                Timeout   = false
            };

            Assert.IsFalse(first.Equals("some string"));
            Assert.IsFalse(first.Equals(second));
            Assert.IsTrue(first.Equals(first));
        }
예제 #22
0
        /// <summary>
        /// Create and connect a new pass-through socket, from the host to a port on
        /// the device.
        /// </summary>
        /// <param name="adbSockAddr"> </param>
        /// <param name="device"> the device to connect to. Can be null in which case the connection will be
        /// to the first available device. </param>
        /// <param name="devicePort"> the port we're opening </param>
        /// <exception cref="TimeoutException"> in case of timeout on the connection. </exception>
        /// <exception cref="IOException"> in case of I/O error on the connection. </exception>
        /// <exception cref="AdbCommandRejectedException"> if adb rejects the command </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public static java.nio.channels.SocketChannel open(java.net.InetSocketAddress adbSockAddr, Device device, int devicePort) throws java.io.IOException, TimeoutException, AdbCommandRejectedException
        public static SocketChannel open(EndPoint adbSockAddr, Device device, int devicePort)
        {
            SocketChannel adbChan = SocketChannel.open(adbSockAddr);

            try
            {
                adbChan.socket().NoDelay = true;
                adbChan.configureBlocking(false);

                // if the device is not -1, then we first tell adb we're looking to
                // talk to a specific device
                setDevice(adbChan, device);

                var req = createAdbForwardRequest(null, devicePort);
                // Log.hexDump(req);

                write(adbChan, req);

                AdbResponse resp = readAdbResponse(adbChan, false);
                if (resp.okay == false)
                {
                    throw new AdbCommandRejectedException(resp.message);
                }

                adbChan.configureBlocking(true);
            }
            catch (TimeoutException e)
            {
                adbChan.close();
                throw e;
            }
            catch (IOException e)
            {
                adbChan.close();
                throw e;
            }

            return(adbChan);
        }
예제 #23
0
 public void ToStringTest()
 {
     Assert.AreEqual("OK", AdbResponse.OK.ToString());
     Assert.AreEqual("Error: Huh?", AdbResponse.FromError("Huh?").ToString());
 }
예제 #24
0
        public void CreateDuplicateForwardTest()
        {
            var responses = new AdbResponse[]
            {
                AdbResponse.FromError("cannot rebind existing socket")
            };

            var requests = new string[]
            {
                "host-serial:169.254.109.177:5555:forward:norebind:tcp:1;tcp:2"
            };

            this.RunTest(
                responses,
                NoResponseMessages,
                requests,
                () =>
                {
                    AdbClient.Instance.CreateForward(Device, "tcp:1", "tcp:2", false);
                });
        }
예제 #25
0
        /// <summary>
        /// Reads the response from ADB after a command. </summary>
        /// <param name="readDiagString"> If true, we're expecting an OKAY response to be
        ///      followed by a diagnostic string. Otherwise, we only expect the
        ///      diagnostic string to follow a FAIL. </param>
        protected AdbResponse ReadAdbResponse(bool readDiagString)
        {
            var resp = new AdbResponse();

            var reply = new byte[4];
            Read(reply);

            if (IsOkay(reply))
            {
                resp.Okay = true;
            }
            else
            {
                readDiagString = true; // look for a reason after the FAIL
                resp.Okay = false;
            }

            // not a loop -- use "while" so we can use "break"
            try
            {
                while (readDiagString)
                {
                    int len;
                    if (!TryReadHex4(out len))
                        break;

                    var msg = new byte[len];
                    Read(msg);

                    resp.Message = ReplyToString(msg);
                    //Log.v("ddms", "Got reply '" + replyToString(reply) + "', diag='" + resp.message + "'");

                    break;
                }
            }
            catch (Exception)
            {
                // ignore those, since it's just reading the diagnose string, the response will
                // contain okay==false anyway.
            }

            return resp;
        }
예제 #26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AdbException"/> class with the
 /// specified client error message and <see cref="AdbResponse"/>
 /// </summary>
 /// <param name="message">
 /// The message that describes the error on the client side.
 /// </param>
 /// <param name="response">
 /// The <see cref="AdbResponse"/> that was sent by adb.
 /// </param>
 public AdbException(string message, AdbResponse response)
     : base(message)
 {
     this.AdbError = response.Message;
     this.Response = response;
 }
예제 #27
0
 public void RunCatLog(IPEndPoint address, IDevice device, string filePath)
 {
     if (device.IsOnline)
     {
         int    num    = 0x1400;
         Action action = null;
         Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         try
         {
             socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, 0));
             socket.ReceiveTimeout    = -1;
             socket.ReceiveBufferSize = num + 1;
             socket.Blocking          = true;
             socket.Connect(AndroidDebugBridge.SocketAddress);
             if (action == null)
             {
                 action = delegate
                 {
                     if (socket != null)
                     {
                         socket.Close();
                     }
                 };
             }
             CancelAction = action;
             AdbHelper.Instance.SetDevice(socket, device);
             byte[] data = AdbHelper.Instance.FormAdbRequest(string.Format("shell:cat {0}", filePath));
             //byte[] data = AdbHelper.Instance.FormAdbRequest(string.Format("log:{0}", filePath));
             if (!AdbHelper.Instance.Write(socket, data))
             {
                 throw new AdbException("failed submitting shell command");
             }
             AdbResponse response = AdbHelper.Instance.ReadAdbResponse(socket, false);
             if (!response.IOSuccess || !response.Okay)
             {
                 throw new AdbException("sad result from adb: " + response.Message);
             }
             byte[] buffer = new byte[num + 1];
             byte   num2   = 0;
             while (device.IsOnline && !IsCancelled)
             {
                 int num3 = socket.Receive(buffer);
                 if (num3 > 0)
                 {
                     using (MemoryStream stream = new MemoryStream())
                     {
                         for (int i = 0; i < num3; i++)
                         {
                             if ((((num3 > (i + 1)) && (buffer[i] == 13)) && (buffer[i + 1] == 10)) || ((num2 == 13) && (buffer[i] == 10)))
                             {
                                 stream.WriteByte(10);
                                 i++;
                             }
                             else
                             {
                                 stream.WriteByte(buffer[i]);
                             }
                             if (i == (num3 - 1))
                             {
                                 num2 = buffer[i];
                             }
                         }
                         this.ParseNewData(stream.ToArray(), 0, (int)stream.Length);
                     }
                 }
             }
         }
         catch (SocketException exception)
         {
             if (exception.SocketErrorCode != SocketError.ConnectionAborted)
             {
                 Log.e("Socket error while receiving response", exception);
             }
         }
         finally
         {
             if (socket != null)
             {
                 socket.Close();
                 socket.Dispose();
             }
         }
     }
 }
예제 #28
0
        /// <summary>
        /// Executes a shell command on the device and retrieve the output. The output is
        /// handed to <var>rcvr</var> as it arrives.
        /// </summary>
        /// <param name="adbSockAddr"> the <seealso cref="InetSocketAddress"/> to adb. </param>
        /// <param name="command"> the shell command to execute </param>
        /// <param name="device"> the <seealso cref="IDevice"/> on which to execute the command. </param>
        /// <param name="rcvr"> the <seealso cref="IShellOutputReceiver"/> that will receives the output of the shell
        ///            command </param>
        /// <param name="maxTimeToOutputResponse"> max time between command output. If more time passes
        ///            between command output, the method will throw
        ///            <seealso cref="ShellCommandUnresponsiveException"/>. A value of 0 means the method will
        ///            wait forever for command output and never throw. </param>
        /// <exception cref="TimeoutException"> in case of timeout on the connection when sending the command. </exception>
        /// <exception cref="AdbCommandRejectedException"> if adb rejects the command </exception>
        /// <exception cref="ShellCommandUnresponsiveException"> in case the shell command doesn't send any output
        ///            for a period longer than <var>maxTimeToOutputResponse</var>. </exception>
        /// <exception cref="IOException"> in case of I/O error on the connection.
        /// </exception>
        /// <seealso cref= DdmPreferences#getTimeOut() </seealso>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: static void executeRemoteCommand(java.net.InetSocketAddress adbSockAddr, String command, IDevice device, IShellOutputReceiver rcvr, int maxTimeToOutputResponse) throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException, java.io.IOException
        internal static void executeRemoteCommand(EndPoint adbSockAddr, string command, IDevice device, IShellOutputReceiver rcvr, int maxTimeToOutputResponse)
        {
            Log.v("ddms", "execute: running " + command);

            SocketChannel adbChan = null;

            try
            {
                adbChan = SocketChannel.open(adbSockAddr);
                adbChan.configureBlocking(false);

                // if the device is not -1, then we first tell adb we're looking to
                // talk
                // to a specific device
                setDevice(adbChan, device);

                var request = formAdbRequest("shell:" + command);                 //$NON-NLS-1$
                write(adbChan, request);

                AdbResponse resp = readAdbResponse(adbChan, false);                 // readDiagString
                if (resp.okay == false)
                {
                    Log.e("ddms", "ADB rejected shell command (" + command + "): " + resp.message);
                    throw new AdbCommandRejectedException(resp.message);
                }

                var        data = new byte[16384];
                ByteBuffer buf  = ByteBuffer.wrap(data);
                int        timeToResponseCount = 0;
                while (true)
                {
                    int count;

                    if (rcvr != null && rcvr.cancelled)
                    {
                        Log.v("ddms", "execute: cancelled");
                        break;
                    }

                    count = adbChan.read(buf);
                    if (count < 0)
                    {
                        // we're at the end, we flush the output
                        rcvr.flush();
                        Log.v("ddms", "execute '" + command + "' on '" + device + "' : EOF hit. Read: " + count);
                        break;
                    }
                    else if (count == 0)
                    {
                        int wait = WAIT_TIME * 5;
                        timeToResponseCount += wait;
                        if (maxTimeToOutputResponse > 0 && timeToResponseCount > maxTimeToOutputResponse)
                        {
                            throw new ShellCommandUnresponsiveException();
                        }
                        Thread.Sleep(wait);
                    }
                    else
                    {
                        // reset timeout
                        timeToResponseCount = 0;

                        // send data to receiver if present
                        if (rcvr != null)
                        {
                            rcvr.addOutput(buf.array(), buf.arrayOffset(), buf.position);
                        }
                        buf.rewind();
                    }
                }
            }
            finally
            {
                if (adbChan != null)
                {
                    adbChan.close();
                }
                Log.v("ddms", "execute: returning");
            }
        }
예제 #29
0
        public void ExecuteRemoteCommandTest()
        {
            var device = new DeviceData()
            {
                Serial = "169.254.109.177:5555",
                State = DeviceState.Online
            };

            var responses = new AdbResponse[]
            {
                AdbResponse.OK,
                AdbResponse.OK
            };

            var responseMessages = new string[] { };

            var requests = new string[]
            {
                "host:transport:169.254.109.177:5555",
                "shell:echo Hello, World"
            };

            byte[] streamData = Encoding.ASCII.GetBytes("Hello, World\r\n");
            MemoryStream shellStream = new MemoryStream(streamData);

            var receiver = new ConsoleOutputReceiver();

            this.RunTest(
                responses,
                responseMessages,
                requests,
                shellStream,
                () =>
                {
                    AdbClient.Instance.ExecuteRemoteCommand("echo Hello, World", device, receiver);
                });

            Assert.AreEqual("Hello, World\r\n", receiver.ToString());
        }
예제 #30
0
        public void ExecuteRemoteCommandUnresponsiveTest()
        {
            var device = new DeviceData()
            {
                Serial = "169.254.109.177:5555",
                State = DeviceState.Online
            };

            var responses = new AdbResponse[]
            {
                AdbResponse.OK,
                AdbResponse.OK
            };

            var responseMessages = new string[] { };

            var requests = new string[]
            {
                "host:transport:169.254.109.177:5555",
                "shell:echo Hello, World"
            };

            var receiver = new ConsoleOutputReceiver();

            this.RunTest(
                responses,
                responseMessages,
                requests,
                null,
                () =>
                {
                    AdbClient.Instance.ExecuteRemoteCommand("echo Hello, World", device, receiver);
                });
        }
예제 #31
0
        public void ReadLogTest()
        {
            var device = new DeviceData()
            {
                Serial = "169.254.109.177:5555",
                State = DeviceState.Online
            };

            var responses = new AdbResponse[]
            {
                AdbResponse.OK,
                AdbResponse.OK
            };

            var responseMessages = new string[] { };

            var requests = new string[]
            {
                "host:transport:169.254.109.177:5555",
                "shell:logcat -B -b system"
            };

            var receiver = new ConsoleOutputReceiver();

            using (Stream stream = File.OpenRead("logcat.bin"))
            using (ShellStream shellStream = new ShellStream(stream, false))
            {
                Logs.LogEntry[] logs = null;

                this.RunTest(
                    responses,
                    responseMessages,
                    requests,
                    shellStream,
                    () =>
                    {
                        logs = AdbClient.Instance.RunLogService(device, Logs.LogId.System).ToArray();
                    });

                Assert.AreEqual(3, logs.Count());
            }
        }
예제 #32
0
		/// <summary>
		/// Reads the response from ADB after a command. </summary>
		/// <param name="chan"> The socket channel that is connected to adb. </param>
		/// <param name="readDiagString"> If true, we're expecting an OKAY response to be
		///      followed by a diagnostic string. Otherwise, we only expect the
		///      diagnostic string to follow a FAIL. </param>
		/// <exception cref="TimeoutException"> in case of timeout on the connection. </exception>
		/// <exception cref="IOException"> in case of I/O error on the connection. </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: static AdbResponse readAdbResponse(java.nio.channels.SocketChannel chan, boolean readDiagString) throws TimeoutException, java.io.IOException
		internal static AdbResponse readAdbResponse(SocketChannel chan, bool readDiagString)
		{

			AdbResponse resp = new AdbResponse();

			var reply = new byte[4];
			read(chan, reply);

			if (isOkay(reply))
			{
				resp.okay = true;
			}
			else
			{
				readDiagString = true; // look for a reason after the FAIL
				resp.okay = false;
			}

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

					string lenStr = replyToString(lenBuf);

					int len;
					try
					{
						len = Convert.ToInt32(lenStr, 16);
					}
                    catch (SystemException)
					{
						Log.w("ddms", "Expected digits, got '" + lenStr + "': " + lenBuf[0] + " " + lenBuf[1] + " " + lenBuf[2] + " " + lenBuf[3]);
						Log.w("ddms", "reply was " + replyToString(reply));
						break;
					}

					var msg = new byte[len];
					read(chan, msg);

					resp.message = replyToString(msg);
					Log.v("ddms", "Got reply '" + replyToString(reply) + "', diag='" + resp.message + "'");

					break;
				}
			}
			catch (Exception)
			{
				// ignore those, since it's just reading the diagnose string, the response will
				// contain okay==false anyway.
			}

			return resp;
		}
예제 #33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AdbException"/> class with the
 /// specified client error message and <see cref="AdbResponse"/>
 /// </summary>
 /// <param name="message">
 /// The message that describes the error on the client side.
 /// </param>
 /// <param name="response">
 /// The <see cref="AdbResponse"/> that was sent by adb.
 /// </param>
 public AdbException(string message, AdbResponse response)
     : base(message)
 {
     this.AdbError = response.Message;
     this.Response = response;
 }
예제 #34
0
        /// <summary>
        /// Retrieve the frame buffer from the device. </summary>
        /// <exception cref="TimeoutException"> in case of timeout on the connection. </exception>
        /// <exception cref="AdbCommandRejectedException"> if adb rejects the command </exception>
        /// <exception cref="IOException"> in case of I/O error on the connection. </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: static RawImage getFrameBuffer(java.net.InetSocketAddress adbSockAddr, Device device) throws TimeoutException, AdbCommandRejectedException, java.io.IOException
        internal static RawImage getFrameBuffer(EndPoint adbSockAddr, Device device)
        {
            RawImage imageParams = new RawImage();
            var      request     = formAdbRequest("framebuffer:");    //$NON-NLS-1$

            byte[] nudge = { 0 };
            byte[] reply;

            SocketChannel adbChan = null;

            try
            {
                adbChan = SocketChannel.open(adbSockAddr);
                adbChan.configureBlocking(false);

                // if the device is not -1, then we first tell adb we're looking to talk
                // to a specific device
                setDevice(adbChan, device);

                write(adbChan, request);

                AdbResponse resp = readAdbResponse(adbChan, false);                 // readDiagString
                if (resp.okay == false)
                {
                    throw new AdbCommandRejectedException(resp.message);
                }

                // first the protocol version.
                reply = new byte[4];
                read(adbChan, reply);

                ByteBuffer buf = ByteBuffer.wrap(reply);
                buf.order = ByteOrder.LITTLE_ENDIAN;

                int version = buf.getInt();

                // 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);

                buf       = ByteBuffer.wrap(reply);
                buf.order = ByteOrder.LITTLE_ENDIAN;

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

                Log.d("ddms", "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
            {
                if (adbChan != null)
                {
                    adbChan.close();
                }
            }

            return(imageParams);
        }