public MainWindow()
        {
            InitializeComponent();

            DdmPreferences.LogLevel = Managed.Adb.LogLevel.Verbose;
            Environment.SetEnvironmentVariable("ANDROID_SDK", @"D:\SDK\Android\sdk");
            AndroidDebugBridge bridge = AndroidDebugBridge.CreateBridge(System.IO.Path.Combine(Environment.GetEnvironmentVariable("ANDROID_SDK"), "platform-tools\\adb.exe"), true);
            while (!bridge.HasInitialDeviceList())
            {
                Thread.Sleep(1000);
            }
            device = bridge.DeviceMonitor.Devices[0];
            device.ExecuteShellCommand("am startservice --user 0 -n com.d8plus.smartarrow/.SmartArrowService", NullOutputReceiver.Instance);
            while (!device.HasClients)
            {
                Thread.Sleep(1000);
            }
            Mouse.AddPreviewMouseMoveHandler(this, (sender, e) =>
            {
                var po = e.GetPosition(this);
                //1080 x 1920
                int w = (int)(1080 * po.X / this.RenderSize.Width);
                int h = (int)(1920 * po.Y / this.RenderSize.Height);

                Debug.WriteLine(string.Format("move {0},{1}", w, h));
                device.ExecuteShellCommand(string.Format("echo move {0},{1} >> /sdcard/SmartArrow.event", w, h), NullOutputReceiver.Instance);
            });
            Observable.FromEventPattern<System.ComponentModel.CancelEventArgs>(this, "Closing").Subscribe(arg => {
                device.ExecuteShellCommand("am stopservice --user 0 -n com.d8plus.smartarrow/.SmartArrowService", NullOutputReceiver.Instance);
                arg.EventArgs.Cancel = false;
            });
        }
Beispiel #2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BusyBox"/> class.
 /// </summary>
 /// <param name="device">The device.</param>
 public BusyBox( Device device )
 {
     this.Device = device;
     Version = new System.Version ( "0.0.0.0" );
     Commands = new List<String> ( );
     CheckForBusyBox ( );
 }
Beispiel #3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Client"/> class.
        /// </summary>
        /// <param name="device">The device.</param>
        /// <param name="channel">The channel.</param>
        /// <param name="pid">The pid.</param>
        public Client( Device device, Socket channel, int pid )
        {
            this.Device = device;
            this.Channel = channel;
            this.ClientData = new ClientData ( pid );

            IsThreadUpdateEnabled = DdmPreferences.InitialThreadUpdate;
            IsHeapUpdateEnabled = DdmPreferences.InitialHeapUpdate;
            ConnectionState = ClientConnectionState.Init;
        }
Beispiel #4
0
        public override TaskResult Run(Managed.Adb.Device adbDevice)
        {
            TaskResult result   = new TaskResult();
            String     cmd      = String.Format("am start {0}/{1}", mPackgeName, mLaunchActivity);
            var        receiver = new LaunchAppReceiver();

            adbDevice.ExecuteShellCommand(cmd, receiver);
            //if (!String.IsNullOrEmpty(receiver.ErrorMessage)) {
            //    result.ok = false;
            //    result.Msg = receiver.ErrorMessage;
            //}
            return(result);
        }
        public override TaskResult Run(Managed.Adb.Device adbDevice)
        {
            TaskResult result = new TaskResult();

            //un install
            var apkInfo = APKInfo.ParseAPK(mPackgeLocation);

            try {
                if (adbDevice.PackageManager.Exists(apkInfo.PackgeName))
                {
                    adbDevice.UninstallPackage(apkInfo.PackgeName);
                }
            } catch {
            }

            LogWrapper.LogInfo("CanuSU:" + adbDevice.SerialNumber + ":" + adbDevice.CanSU());
            string          remoteFilePath = adbDevice.SyncPackageToDevice(mPackgeLocation);
            InstallReceiver receiver       = new InstallReceiver();
            String          cmd            = String.Format("pm install {1}{0}", remoteFilePath, true ? "-r " : String.Empty);

            if (adbDevice.CanSU())
            {
                adbDevice.ExecuteRootShellCommand(cmd, receiver);
            }
            else
            {
                adbDevice.ExecuteShellCommand(cmd, receiver);
            }

            if (!String.IsNullOrEmpty(receiver.ErrorMessage))
            {
                result.ok  = false;
                result.Msg = receiver.ErrorMessage;
            }
            return(result);
        }
 private void QueryNewDeviceForEnvironmentVariables( Device device )
 {
     try {
         if ( device.State != DeviceState.Offline && device.State != DeviceState.Unknown ) {
             device.RefreshEnvironmentVariables ( );
         }
     } catch ( IOException ) {
         // if we can't get the build info, it doesn't matter too much
     }
 }
        /// <summary>
        /// Creates the client.
        /// </summary>
        /// <param name="device">The device.</param>
        /// <param name="pid">The pid.</param>
        /// <param name="socket">The socket.</param>
        /// <param name="debuggerPort">The debugger port.</param>
        /// <param name="monitorThread">The monitor thread.</param>
        private void CreateClient( Device device, int pid, Socket socket, int debuggerPort, MonitorThread monitorThread )
        {
            /*
             * Successfully connected to something. Create a Client object, add
             * it to the list, and initiate the JDWP handshake.
             */

            Client client = new Client ( device, socket, pid );

            if ( client.SendHandshake ( ) ) {
                try {
                    if ( AndroidDebugBridge.ClientSupport ) {
                        client.ListenForDebugger ( debuggerPort );
                    }
                } catch ( IOException ) {
                    client.ClientData.DebuggerConnectionStatus = Managed.Adb.ClientData.DebuggerStatus.ERROR;
                    Log.e ( "ddms", "Can't bind to local {0} for debugger", debuggerPort );
                    // oh well
                }

                client.RequestAllocationStatus ( );
            } else {
                Log.e ( "ddms", "Handshake with {0} failed!", client );
                /*
                 * The handshake send failed. We could remove it now, but if the
                 * failure is "permanent" we'll just keep banging on it and
                 * getting the same result. Keep it in the list with its "error"
                 * state so we don't try to reopen it.
                 */
            }

            if ( client.IsValid ) {
                device.Clients.Add ( client );
                monitorThread.Clients.Add ( client );
            } else {
                client = null;
            }
        }
 /// <summary>
 /// Executes a shell command on the remote device
 /// </summary>
 /// <param name="endPoint">The end point.</param>
 /// <param name="command">The command.</param>
 /// <param name="device">The device.</param>
 /// <param name="rcvr">The RCVR.</param>
 /// <param name="maxTimeToOutputResponse">The max time to output response.</param>
 public void ExecuteRemoteRootCommand(IPEndPoint endPoint, String command, Device device, IShellOutputReceiver rcvr, int maxTimeToOutputResponse)
 {
     ExecuteRemoteCommand(endPoint, String.Format("su -c \"{0}\"", command), device, rcvr);
 }
Beispiel #9
0
        /// <summary>
        /// Reboots the specified device in to the specified mode.
        /// </summary>
        /// <param name="into">The into.</param>
        /// <param name="adbSockAddr">The adb sock addr.</param>
        /// <param name="device">The device.</param>
        public void Reboot(String into, IPEndPoint adbSockAddr, Device device)
        {
            byte[] request;
            if(string.IsNullOrEmpty(into)) {
                request = FormAdbRequest("reboot:");
            } else {
                request = FormAdbRequest("reboot:" + into);
            }

            using(ExecuteRawSocketCommand(adbSockAddr, device, request)) {
                // nothing to do...
            }
        }
Beispiel #10
0
 /// <summary>
 /// Lists the forward.
 /// </summary>
 /// <param name="address">The address.</param>
 /// <param name="device">The device.</param>
 /// <exception cref="System.NotImplementedException"></exception>
 public void ListForward(IPEndPoint address, Device device)
 {
     throw new NotImplementedException();
 }
Beispiel #11
0
 /// <summary>
 /// Executes a shell command on the remote device
 /// </summary>
 /// <param name="endPoint">The end point.</param>
 /// <param name="command">The command.</param>
 /// <param name="device">The device.</param>
 /// <param name="rcvr">The RCVR.</param>
 /// <remarks>
 /// Should check if you CanSU before calling this.
 /// </remarks>
 public void ExecuteRemoteRootCommand(IPEndPoint endPoint, String command, Device device, IShellOutputReceiver rcvr)
 {
     ExecuteRemoteRootCommand(endPoint, String.Format("su -c \"{0}\"", command), device, rcvr, int.MaxValue);
 }
 /// <summary>
 /// Reboots the specified adb socket address.
 /// </summary>
 /// <param name="adbSocketAddress">The adb socket address.</param>
 /// <param name="device">The device.</param>
 public void Reboot(IPEndPoint adbSocketAddress, Device device)
 {
     Reboot(string.Empty, adbSocketAddress, device);
 }
Beispiel #13
0
 public Device(Managed.Adb.Device adbDevice)
 {
     mADBDevice   = adbDevice;
     mTaskManager = new TaskManager(adbDevice);
 }
Beispiel #14
0
 public TaskManager(Managed.Adb.Device device)
 {
     mDevice = device;
 }
 /// <summary>
 /// Lists the forward.
 /// </summary>
 /// <param name="address">The address.</param>
 /// <param name="device">The device.</param>
 /// <exception cref="System.NotImplementedException"></exception>
 public void ListForward(IPEndPoint address, Device device)
 {
     throw new NotImplementedException();
 }
 /// <summary>
 /// Executes a shell command on the remote device
 /// </summary>
 /// <param name="endPoint">The socket end point</param>
 /// <param name="command">The command to execute</param>
 /// <param name="device">The device to execute on</param>
 /// <param name="rcvr">The shell output receiver</param>
 /// <exception cref="FileNotFoundException">Throws if the result is 'command': not found</exception>
 /// <exception cref="IOException">Throws if there is a problem reading / writing to the socket</exception>
 /// <exception cref="OperationCanceledException">Throws if the execution was canceled</exception>
 /// <exception cref="EndOfStreamException">Throws if the Socket.Receice ever returns -1</exception>
 public void ExecuteRemoteCommand(IPEndPoint endPoint, String command, Device device, IShellOutputReceiver rcvr)
 {
     ExecuteRemoteCommand(endPoint, command, device, rcvr, int.MaxValue);
 }
        /// <summary>
        /// Executes the remote command.
        /// </summary>
        /// <param name="endPoint">The end point.</param>
        /// <param name="command">The command.</param>
        /// <param name="device">The device.</param>
        /// <param name="rcvr">The RCVR.</param>
        /// <param name="maxTimeToOutputResponse">The max time to output response.</param>
        /// <exception cref="System.OperationCanceledException"></exception>
        /// <exception cref="System.IO.FileNotFoundException">
        /// </exception>
        /// <exception cref="Managed.Adb.Exceptions.UnknownOptionException"></exception>
        /// <exception cref="Managed.Adb.Exceptions.CommandAbortingException"></exception>
        /// <exception cref="Managed.Adb.Exceptions.PermissionDeniedException"></exception>
        /// <exception cref="Managed.Adb.Exceptions.ShellCommandUnresponsiveException"></exception>
        /// <exception cref="AdbException">failed submitting shell command</exception>
        /// <exception cref="UnknownOptionException"></exception>
        /// <exception cref="CommandAbortingException"></exception>
        /// <exception cref="PermissionDeniedException"></exception>
        public void ExecuteRemoteCommand(IPEndPoint endPoint, String command, Device device, IShellOutputReceiver rcvr, int maxTimeToOutputResponse)
        {
            using (var socket = ExecuteRawSocketCommand(endPoint, device, "shell:{0}".With(command))) {
                socket.ReceiveTimeout = maxTimeToOutputResponse;
                socket.SendTimeout    = maxTimeToOutputResponse;

                try {
                    byte[] data  = new byte[16384];
                    int    count = -1;
                    while (count != 0)
                    {
                        if (rcvr != null && rcvr.IsCancelled)
                        {
                            Log.w(TAG, "execute: cancelled");
                            throw new OperationCanceledException();
                        }

                        count = socket.Receive(data);
                        if (count == 0)
                        {
                            // we're at the end, we flush the output
                            rcvr.Flush();
                            Log.w(TAG, "execute '" + command + "' on '" + device + "' : EOF hit. Read: " + count);
                        }
                        else
                        {
                            string[] cmd   = command.Trim().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                            string   sdata = data.GetString(0, count, AdbHelper.DEFAULT_ENCODING);

                            var sdataTrimmed = sdata.Trim();
                            if (sdataTrimmed.EndsWith(String.Format("{0}: not found", cmd[0])))
                            {
                                Log.w(TAG, "The remote execution returned: '{0}: not found'", cmd[0]);
                                throw new FileNotFoundException(string.Format("The remote execution returned: '{0}: not found'", cmd[0]));
                            }

                            if (sdataTrimmed.EndsWith("No such file or directory"))
                            {
                                Log.w(TAG, "The remote execution returned: {0}", sdataTrimmed);
                                throw new FileNotFoundException(String.Format("The remote execution returned: {0}", sdataTrimmed));
                            }

                            // for "unknown options"
                            if (sdataTrimmed.Contains("Unknown option"))
                            {
                                Log.w(TAG, "The remote execution returned: {0}", sdataTrimmed);
                                throw new UnknownOptionException(sdataTrimmed);
                            }

                            // for "aborting" commands
                            if (sdataTrimmed.IsMatch("Aborting.$"))
                            {
                                Log.w(TAG, "The remote execution returned: {0}", sdataTrimmed);
                                throw new CommandAbortingException(sdataTrimmed);
                            }

                            // for busybox applets
                            // cmd: applet not found
                            if (sdataTrimmed.IsMatch("applet not found$") && cmd.Length > 1)
                            {
                                Log.w(TAG, "The remote execution returned: '{0}'", sdataTrimmed);
                                throw new FileNotFoundException(string.Format("The remote execution returned: '{0}'", sdataTrimmed));
                            }

                            // checks if the permission to execute the command was denied.
                            // workitem: 16822
                            if (sdataTrimmed.IsMatch("(permission|access) denied$"))
                            {
                                Log.w(TAG, "The remote execution returned: '{0}'", sdataTrimmed);
                                throw new PermissionDeniedException(String.Format("The remote execution returned: '{0}'", sdataTrimmed));
                            }

                            // Add the data to the receiver
                            if (rcvr != null)
                            {
                                rcvr.AddOutput(data, 0, count);
                            }
                        }
                    }
                } catch (SocketException) {
                    throw new ShellCommandUnresponsiveException();
                } finally {
                    rcvr.Flush();
                }
            }
        }
 private void QueryNewDeviceForMountingPoint( Device device )
 {
     try {
         if ( device.State != DeviceState.Offline && device.State != DeviceState.Unknown ) {
             device.RefreshMountPoints ( );
         }
     } catch ( IOException ) {
         // if we can't get the build info, it doesn't matter too much
     }
 }
 /// <summary>
 /// Executes a raw socket command.
 /// </summary>
 /// <param name="address">The address.</param>
 /// <param name="device">The device.</param>
 /// <param name="command">The command.</param>
 /// <returns></returns>
 /// <exception cref="AdbException">failed to submit the command: {0}.With(command)
 /// or
 /// Device rejected command: {0}.With(resp.Message)</exception>
 private Socket ExecuteRawSocketCommand(IPEndPoint address, Device device, string command)
 {
     return(ExecuteRawSocketCommand(address, device, FormAdbRequest(command)));
 }
        /// <summary>
        /// Sends the device monitoring request.
        /// </summary>
        /// <param name="socket">The socket.</param>
        /// <param name="device">The device.</param>
        /// <returns></returns>
        private bool SendDeviceMonitoringRequest( Socket socket, Device device )
        {
            AdbHelper.Instance.SetDevice ( socket, device );
            byte[] request = AdbHelper.Instance.FormAdbRequest ( "track-jdwp" );
            if ( !AdbHelper.Instance.Write ( socket, request ) ) {
                Log.e ( TAG, "Sending jdwp tracking request failed!" );
                socket.Close ( );
                throw new IOException ( );
            }
            AdbResponse resp = AdbHelper.Instance.ReadAdbResponse ( socket, false /* readDiagString */);
            if ( resp.IOSuccess == false ) {
                Log.e ( TAG, "Failed to read the adb response!" );
                socket.Close ( );
                throw new IOException ( );
            }

            if ( resp.Okay == false ) {
                // request was refused by adb!
                Log.e ( TAG, "adb refused request: " + resp.Message );
            }

            return resp.Okay;
        }
Beispiel #21
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FileListingService"/> class.
 /// </summary>
 /// <param name="device">The device.</param>
 public FileListingService( Device device )
     : this(device, device.BusyBox.Available)
 {
 }
Beispiel #22
0
 /// <summary>
 /// Executes a shell command on the remote device
 /// </summary>
 /// <param name="endPoint">The socket end point</param>
 /// <param name="command">The command to execute</param>
 /// <param name="device">The device to execute on</param>
 /// <param name="rcvr">The shell output receiver</param>
 /// <exception cref="FileNotFoundException">Throws if the result is 'command': not found</exception>
 /// <exception cref="IOException">Throws if there is a problem reading / writing to the socket</exception>
 /// <exception cref="OperationCanceledException">Throws if the execution was canceled</exception>
 /// <exception cref="EndOfStreamException">Throws if the Socket.Receice ever returns -1</exception>
 public void ExecuteRemoteCommand(IPEndPoint endPoint, String command, Device device, IShellOutputReceiver rcvr)
 {
     ExecuteRemoteCommand(endPoint, command, device, rcvr, int.MaxValue);
 }
Beispiel #23
0
 /// <summary>
 /// Removes the forward.
 /// </summary>
 /// <param name="address">The adb socket address.</param>
 /// <param name="device">The device.</param>
 /// <param name="localPort">The local port.</param>
 /// <returns></returns>
 public bool RemoveForward(IPEndPoint address, Device device, int localPort)
 {
     using(var socket = ExecuteRawSocketCommand(address, device, "host-serial:{0}:killforward:tcp:{1}".With(device.SerialNumber, localPort))) {
         // do nothing...
         return true;
     }
 }
Beispiel #24
0
 /// <summary>
 /// Executes a shell command on the remote device
 /// </summary>
 /// <param name="endPoint">The end point.</param>
 /// <param name="command">The command.</param>
 /// <param name="device">The device.</param>
 /// <param name="rcvr">The RCVR.</param>
 /// <param name="maxTimeToOutputResponse">The max time to output response.</param>
 public void ExecuteRemoteRootCommand(IPEndPoint endPoint, String command, Device device, IShellOutputReceiver rcvr, int maxTimeToOutputResponse)
 {
     ExecuteRemoteCommand(endPoint, String.Format("su -c \"{0}\"", command), device, rcvr);
 }
Beispiel #25
0
        /// <summary>
        /// Runs the Event log service on the Device, and provides its output to the LogReceiver.
        /// </summary>
        /// <param name="address">The address.</param>
        /// <param name="device">The device.</param>
        /// <param name="logName">Name of the log.</param>
        /// <param name="rcvr">The RCVR.</param>
        /// <exception cref="AdbException">failed asking for log</exception>
        /// <exception cref="Managed.Adb.Exceptions.AdbCommandRejectedException"></exception>
        public void RunLogService(IPEndPoint address, Device device, String logName, LogReceiver rcvr)
        {
            using(var socket = ExecuteRawSocketCommand(address, device, "log:{0}".With(logName))) {
                byte[] data = new byte[16384];
                using(var ms = new MemoryStream(data)) {
                    int offset = 0;

                    while(true) {
                        int count;
                        if(rcvr != null && rcvr.IsCancelled) {
                            break;
                        }
                        var buffer = new byte[4 * 1024];

                        count = socket.Receive(buffer);
                        if(count < 0) {
                            break;
                        } else if(count == 0) {
                            try {
                                Thread.Sleep(WAIT_TIME * 5);
                            } catch(ThreadInterruptedException) {
                            }
                        } else {
                            ms.Write(buffer, offset, count);
                            offset += count;
                            if(rcvr != null) {
                                var d = ms.ToArray();
                                rcvr.ParseNewData(d, 0, d.Length);
                            }
                        }
                    }
                }
            }
        }
Beispiel #26
0
 /// <summary>
 /// Reboots the specified adb socket address.
 /// </summary>
 /// <param name="adbSocketAddress">The adb socket address.</param>
 /// <param name="device">The device.</param>
 public void Reboot(IPEndPoint adbSocketAddress, Device device)
 {
     Reboot(string.Empty, adbSocketAddress, device);
 }
Beispiel #27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SyncService"/> class.
 /// </summary>
 /// <param name="address">The address.</param>
 /// <param name="device">The device.</param>
 public SyncService( IPEndPoint address, Device device )
 {
     Address = address;
     Device = device;
     Open ( );
 }
Beispiel #28
0
 /// <summary>
 /// Removes all forwards.
 /// </summary>
 /// <param name="address">The address.</param>
 /// <param name="device">The device.</param>
 /// <returns></returns>
 public bool RemoveAllForward(IPEndPoint address, Device device)
 {
     using(var socket = ExecuteRawSocketCommand(address, device, "host-serial:{0}:killforward-all".With(device.SerialNumber))) {
         // do nothing...
         return true;
     }
 }
 /// <summary>
 /// Executes a shell command on the remote device
 /// </summary>
 /// <param name="endPoint">The end point.</param>
 /// <param name="command">The command.</param>
 /// <param name="device">The device.</param>
 /// <param name="rcvr">The RCVR.</param>
 /// <remarks>
 /// Should check if you CanSU before calling this.
 /// </remarks>
 public void ExecuteRemoteRootCommand(IPEndPoint endPoint, String command, Device device, IShellOutputReceiver rcvr)
 {
     ExecuteRemoteRootCommand(endPoint, String.Format("su -c \"{0}\"", command), device, rcvr, int.MaxValue);
 }
Beispiel #30
0
 /// <summary>
 /// Runs the Event log service on the Device, and provides its output to the LogReceiver.
 /// </summary>
 /// <param name="address">The address.</param>
 /// <param name="device">The device.</param>
 /// <param name="rcvr">The RCVR.</param>
 public void RunEventLogService(IPEndPoint address, Device device, LogReceiver rcvr)
 {
     RunLogService(address, device, "events", rcvr);
 }
Beispiel #31
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PackageManager"/> class.
 /// </summary>
 /// <param name="device">The device.</param>
 public PackageManager( Device device )
 {
     Device = device;
     Packages = new Dictionary<string, FileEntry> ( );
 }
Beispiel #32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SyncService"/> class.
 /// </summary>
 /// <param name="device">The device.</param>
 public SyncService( Device device )
     : this(AndroidDebugBridge.SocketAddress, device)
 {
 }
Beispiel #33
0
 /// <summary>
 /// Executes a raw socket command.
 /// </summary>
 /// <param name="address">The address.</param>
 /// <param name="device">The device.</param>
 /// <param name="command">The command.</param>
 /// <returns></returns>
 /// <exception cref="AdbException">failed to submit the command: {0}.With(command)
 /// or
 /// Device rejected command: {0}.With(resp.Message)</exception>
 private Socket ExecuteRawSocketCommand(IPEndPoint address, Device device, string command)
 {
     return ExecuteRawSocketCommand(address, device, FormAdbRequest(command));
 }
Beispiel #34
0
 public abstract TaskResult Run(Managed.Adb.Device adbDevice);
Beispiel #35
0
        /// <summary>
        /// Executes the raw socket command.
        /// </summary>
        /// <param name="address">The address.</param>
        /// <param name="device">The device.</param>
        /// <param name="command">The command. Should call FormAdbRequest on the string to create the byte array.</param>
        /// <returns></returns>
        /// <exception cref="Managed.Adb.Exceptions.AdbException">
        /// Device is offline
        /// or
        /// failed to submit the command: {0}..With(command.GetString().Trim())
        /// or
        /// Device rejected command: {0}.With(resp.Message)
        /// </exception>
        /// <exception cref="AdbException">Device is offline.
        /// or
        /// failed to submit the command: {0}.With(command)
        /// or
        /// Device rejected command: {0}.With(resp.Message)</exception>
        private Socket ExecuteRawSocketCommand(IPEndPoint address, Device device, byte[] command)
        {
            if(device != null && !device.IsOnline) {
                throw new AdbException("Device is offline");
            }

            Socket adbChan = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            adbChan.Connect(address);
            adbChan.Blocking = true;
            if(device != null) {
                SetDevice(adbChan, device);
            }
            if(!Write(adbChan, command)) {
                throw new AdbException("failed to submit the command: {0}.".With(command.GetString().Trim()));
            }

            AdbResponse resp = ReadAdbResponse(adbChan, false /* readDiagString */);
            if(!resp.IOSuccess || !resp.Okay) {
                throw new AdbException("Device rejected command: {0}".With(resp.Message));
            }
            return adbChan;
        }
        /// <summary>
        /// Opens the client.
        /// </summary>
        /// <param name="device">The device.</param>
        /// <param name="pid">The pid.</param>
        /// <param name="port">The port.</param>
        /// <param name="monitorThread">The monitor thread.</param>
        private void OpenClient( Device device, int pid, int port, MonitorThread monitorThread )
        {
            Socket clientSocket;
            try {
                clientSocket = AdbHelper.Instance.CreatePassThroughConnection ( AndroidDebugBridge.SocketAddress, device, pid );

                clientSocket.Blocking = true;
            } catch ( IOException ioe ) {
                Log.w ( TAG, "Failed to connect to client {0}: {1}'", pid, ioe.Message );
                return;
            }

            CreateClient ( device, pid, clientSocket, port, monitorThread );
        }
Beispiel #37
0
        /// <summary>
        /// Creates the forward.
        /// </summary>
        /// <param name="adbSockAddr">The adb sock addr.</param>
        /// <param name="device">The device.</param>
        /// <param name="localPort">The local port.</param>
        /// <param name="remotePort">The remote port.</param>
        /// <returns></returns>
        /// <exception cref="Managed.Adb.Exceptions.AdbException">
        /// failed to submit the forward command.
        /// or
        /// Device rejected command:  + resp.Message
        /// </exception>
        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(String.Format("host-serial:{0}:forward:tcp:{1};tcp:{2}", //$NON-NLS-1$
                                device.SerialNumber, localPort, remotePort));

                if(!Write(adbChan, request)) {
                    throw new AdbException("failed to submit the forward command.");
                }

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

            return true;
        }
        private void QueryNewDeviceForInfo( Device device )
        {
            // TODO: do this in a separate thread.
            try {
                // first get the list of properties.
                if ( device.State != DeviceState.Offline && device.State != DeviceState.Unknown ) {
                    // get environment variables
                    QueryNewDeviceForEnvironmentVariables ( device );
                    // instead of getting the 3 hard coded ones, we use mount command and get them all...
                    // if that fails, then it automatically falls back to the hard coded ones.
                    QueryNewDeviceForMountingPoint ( device );

                    // now get the emulator Virtual Device name (if applicable).
                    if ( device.IsEmulator ) {
                        /*EmulatorConsole console = EmulatorConsole.getConsole ( device );
                        if ( console != null ) {
                            device.AvdName = console.AvdName;
                        }*/
                    }
                }
            } catch ( IOException ) {
                // if we can't get the build info, it doesn't matter too much
            }
        }
Beispiel #39
0
        /// <summary>
        /// Creates and connects a new pass-through socket, from the host to a port on the device.
        /// </summary>
        /// <param name="endpoint">The endpoint.</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="pid">the process pid to connect to.</param>
        /// <returns>
        /// The Socket
        /// </returns>
        /// <exception cref="Managed.Adb.Exceptions.AdbException">
        /// failed submitting request to ADB
        /// or
        /// connection request rejected:  + resp.Message
        /// </exception>
        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);

                byte[] req = CreateJdwpForwardRequest(pid);
                // Log.hexDump(req);

                if(!Write(socket, req))
                    throw new AdbException("failed submitting request to ADB"); //$NON-NLS-1$

                AdbResponse resp = ReadAdbResponse(socket, false /* readDiagString */);
                if(!resp.Okay)
                    throw new AdbException("connection request rejected: " + resp.Message); //$NON-NLS-1$

            } catch(AdbException ioe) {
                socket.Close();
                throw ioe;
            }

            return socket;
        }
        /// <summary>
        /// Removes the device.
        /// </summary>
        /// <param name="device">The device.</param>
        private void RemoveDevice( Device device )
        {
            //device.Clients.Clear ( );
            Devices.Remove ( device );

            Socket channel = device.ClientMonitoringSocket;
            if ( channel != null ) {
                try {
                    channel.Close ( );
                } catch ( IOException ) {
                    // doesn't really matter if the close fails.
                }
            }
        }
Beispiel #41
0
        /// <summary>
        /// Executes the remote command.
        /// </summary>
        /// <param name="endPoint">The end point.</param>
        /// <param name="command">The command.</param>
        /// <param name="device">The device.</param>
        /// <param name="rcvr">The RCVR.</param>
        /// <param name="maxTimeToOutputResponse">The max time to output response.</param>
        /// <exception cref="System.OperationCanceledException"></exception>
        /// <exception cref="System.IO.FileNotFoundException">
        /// </exception>
        /// <exception cref="Managed.Adb.Exceptions.UnknownOptionException"></exception>
        /// <exception cref="Managed.Adb.Exceptions.CommandAbortingException"></exception>
        /// <exception cref="Managed.Adb.Exceptions.PermissionDeniedException"></exception>
        /// <exception cref="Managed.Adb.Exceptions.ShellCommandUnresponsiveException"></exception>
        /// <exception cref="AdbException">failed submitting shell command</exception>
        /// <exception cref="UnknownOptionException"></exception>
        /// <exception cref="CommandAbortingException"></exception>
        /// <exception cref="PermissionDeniedException"></exception>
        public void ExecuteRemoteCommand(IPEndPoint endPoint, String command, Device device, IShellOutputReceiver rcvr, int maxTimeToOutputResponse)
        {
            using(var socket = ExecuteRawSocketCommand(endPoint, device, "shell:{0}".With(command))) {
                socket.ReceiveTimeout = maxTimeToOutputResponse;
                socket.SendTimeout = maxTimeToOutputResponse;

                try {
                    byte[] data = new byte[16384];
                    int count = -1;
                    while(count != 0) {

                        if(rcvr != null && rcvr.IsCancelled) {
                            Log.w(TAG, "execute: cancelled");
                            throw new OperationCanceledException();
                        }

                        count = socket.Receive(data);
                        if(count == 0) {
                            // we're at the end, we flush the output
                            rcvr.Flush();
                            Log.w(TAG, "execute '" + command + "' on '" + device + "' : EOF hit. Read: " + count);
                        } else {
                            string[] cmd = command.Trim().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                            string sdata = data.GetString(0, count, AdbHelper.DEFAULT_ENCODING);

                            var sdataTrimmed = sdata.Trim();
                            if(sdataTrimmed.EndsWith(String.Format("{0}: not found", cmd[0]))) {
                                Log.w(TAG, "The remote execution returned: '{0}: not found'", cmd[0]);
                                throw new FileNotFoundException(string.Format("The remote execution returned: '{0}: not found'", cmd[0]));
                            }

                            if(sdataTrimmed.EndsWith("No such file or directory")) {
                                Log.w(TAG, "The remote execution returned: {0}", sdataTrimmed);
                                throw new FileNotFoundException(String.Format("The remote execution returned: {0}", sdataTrimmed));
                            }

                            // for "unknown options"
                            if(sdataTrimmed.Contains("Unknown option")) {
                                Log.w(TAG, "The remote execution returned: {0}", sdataTrimmed);
                                throw new UnknownOptionException(sdataTrimmed);
                            }

                            // for "aborting" commands
                            if(sdataTrimmed.IsMatch("Aborting.$")) {
                                Log.w(TAG, "The remote execution returned: {0}", sdataTrimmed);
                                throw new CommandAbortingException(sdataTrimmed);
                            }

                            // for busybox applets
                            // cmd: applet not found
                            if(sdataTrimmed.IsMatch("applet not found$") && cmd.Length > 1) {
                                Log.w(TAG, "The remote execution returned: '{0}'", sdataTrimmed);
                                throw new FileNotFoundException(string.Format("The remote execution returned: '{0}'", sdataTrimmed));
                            }

                            // checks if the permission to execute the command was denied.
                            // workitem: 16822
                            if(sdataTrimmed.IsMatch("(permission|access) denied$")) {
                                Log.w(TAG, "The remote execution returned: '{0}'", sdataTrimmed);
                                throw new PermissionDeniedException(String.Format("The remote execution returned: '{0}'", sdataTrimmed));
                            }

                            // Add the data to the receiver
                            if(rcvr != null) {
                                rcvr.AddOutput(data, 0, count);
                            }

                        }
                    }
                } catch(SocketException) {
                    throw new ShellCommandUnresponsiveException();
                } finally {
                    rcvr.Flush();
                }
            }
        }
        private bool StartMonitoringDevice( Device device )
        {
            Socket socket = OpenAdbConnection ( );

            if ( socket != null ) {
                try {
                    bool result = SendDeviceMonitoringRequest ( socket, device );
                    if ( result ) {

                        /*if ( Selector == null ) {
                            StartDeviceMonitorThread ( );
                        }*/

                        device.ClientMonitoringSocket = socket;

                        lock ( Devices ) {
                            // always wakeup before doing the register. The synchronized block
                            // ensure that the selector won't select() before the end of this block.
                            // @see deviceClientMonitorLoop
                            //Selector.wakeup ( );

                            socket.Blocking = true;
                            //socket.register(mSelector, SelectionKey.OP_READ, device);
                        }

                        return true;
                    }
                } catch ( IOException e ) {
                    try {
                        // attempt to close the socket if needed.
                        socket.Close ( );
                    } catch ( IOException e1 ) {
                        // we can ignore that one. It may already have been closed.
                    }
                    Log.d ( TAG, "Connection Failure when starting to monitor device '{0}' : {1}", device, e.Message );
                }
            }

            return false;
        }
 /// <summary>
 /// Runs the Event log service on the Device, and provides its output to the LogReceiver.
 /// </summary>
 /// <param name="address">The address.</param>
 /// <param name="device">The device.</param>
 /// <param name="rcvr">The RCVR.</param>
 public void RunEventLogService(IPEndPoint address, Device device, LogReceiver rcvr)
 {
     RunLogService(address, device, "events", rcvr);
 }