Advertisement
caffeinatedmike

adb_protocol.py

Nov 12th, 2018
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 27.57 KB | None | 0 0
  1. # Copyright 2014 Google Inc. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. #     http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """ADB protocol implementation.
  15.  
  16. Implements the ADB protocol as seen in android's adb/adbd binaries, but only the
  17. host side.
  18. """
  19.  
  20. import struct
  21. import time
  22. from io import BytesIO
  23. from adb import usb_exceptions
  24.  
  25. # For debugging
  26. import logging
  27. logger = logging.getLogger(__name__)
  28. logger.info("adb_protocol.py's logger setup complete.")
  29.  
  30. # Maximum amount of data in an ADB packet.
  31. MAX_ADB_DATA = 4096
  32. # ADB protocol version.
  33. VERSION = 0x01000000
  34.  
  35. # AUTH constants for arg0.
  36. AUTH_TOKEN = 1
  37. AUTH_SIGNATURE = 2
  38. AUTH_RSAPUBLICKEY = 3
  39.  
  40.  
  41. def find_backspace_runs(stdout_bytes, start_pos):
  42.     first_backspace_pos = stdout_bytes[start_pos:].find(b'\x08')
  43.     if first_backspace_pos == -1:
  44.         return -1, 0
  45.  
  46.     end_backspace_pos = (start_pos + first_backspace_pos) + 1
  47.     while True:
  48.         if chr(stdout_bytes[end_backspace_pos]) == '\b':
  49.             end_backspace_pos += 1
  50.         else:
  51.             break
  52.  
  53.     num_backspaces = end_backspace_pos - (start_pos + first_backspace_pos)
  54.  
  55.     return (start_pos + first_backspace_pos), num_backspaces
  56.  
  57.  
  58. class InvalidCommandError(Exception):
  59.     """Got an invalid command over USB."""
  60.  
  61.     def __init__(self, message, response_header, response_data):
  62.         logger.info('Now inside InvalidCommandError class def __init__ (line 62)')
  63.         logger.info('message: %s', str(message))
  64.         logger.info('response_header: %s', str(response_header))
  65.         logger.info('response_data: %s', str(response_data))
  66.         if response_header == b'FAIL':
  67.             message = 'Command failed, device said so. (%s)' % message
  68.         super(InvalidCommandError, self).__init__(
  69.             message, response_header, response_data)
  70.  
  71.  
  72. class InvalidResponseError(Exception):
  73.     """Got an invalid response to our command."""
  74.  
  75.  
  76. class InvalidChecksumError(Exception):
  77.     """Checksum of data didn't match expected checksum."""
  78.  
  79.  
  80. class InterleavedDataError(Exception):
  81.     """We only support command sent serially."""
  82.  
  83.  
  84. def MakeWireIDs(ids):
  85.     id_to_wire = {
  86.         cmd_id: sum(c << (i * 8) for i, c in enumerate(bytearray(cmd_id)))
  87.         for cmd_id in ids
  88.     }
  89.     wire_to_id = {wire: cmd_id for cmd_id, wire in id_to_wire.items()}
  90.     return id_to_wire, wire_to_id
  91.  
  92.  
  93. class AuthSigner(object):
  94.     """Signer for use with authenticated ADB, introduced in 4.4.x/KitKat."""
  95.  
  96.     def Sign(self, data):
  97.         """Signs given data using a private key."""
  98.         raise NotImplementedError()
  99.  
  100.     def GetPublicKey(self):
  101.         """Returns the public key in PEM format without headers or newlines."""
  102.         raise NotImplementedError()
  103.  
  104.  
  105. class _AdbConnection(object):
  106.     """ADB Connection."""
  107.  
  108.     def __init__(self, usb, local_id, remote_id, timeout_ms):
  109.         self.usb = usb
  110.         self.local_id = local_id
  111.         self.remote_id = remote_id
  112.         self.timeout_ms = timeout_ms
  113.  
  114.     def _Send(self, command, arg0, arg1, data=b''):
  115.         logger.info('Inside class _AdbConnection(object) def _Send (line 115)')
  116.         logger.info('command: %s', str(command))
  117.         logger.info('arg0: %s', str(arg0))
  118.         logger.info('arg1: %s', str(arg1))
  119.         logger.info('data: %s', str(data))
  120.         message = AdbMessage(command, arg0, arg1, data)
  121.         logger.info('message: %s', str(message))
  122.         message.Send(self.usb, self.timeout_ms)
  123.  
  124.     def Write(self, data):
  125.         """Write a packet and expect an Ack."""
  126.         self._Send(b'WRTE', arg0=self.local_id, arg1=self.remote_id, data=data)
  127.         # Expect an ack in response.
  128.         cmd, okay_data = self.ReadUntil(b'OKAY')
  129.         if cmd != b'OKAY':
  130.             if cmd == b'FAIL':
  131.                 raise usb_exceptions.AdbCommandFailureException(
  132.                     'Command failed.', okay_data)
  133.             raise InvalidCommandError(
  134.                 'Expected an OKAY in response to a WRITE, got %s (%s)',
  135.                 cmd, okay_data)
  136.         return len(data)
  137.  
  138.     def Okay(self):
  139.         self._Send(b'OKAY', arg0=self.local_id, arg1=self.remote_id)
  140.  
  141.     def ReadUntil(self, *expected_cmds):
  142.         """Read a packet, Ack any write packets."""
  143.         logger.info('Now inside _AdbConnection class def ReadUntil (line 143)')
  144.         logger.info('self.usb: %s', str(self.usb))
  145.         logger.info('expected_cmds: %s', str(expected_cmds))
  146.         logger.info('self.timeout_ms: %s', str(self.timeout_ms))
  147.         cmd, remote_id, local_id, data = AdbMessage.Read(
  148.             self.usb, expected_cmds, self.timeout_ms)
  149.         logger.info('Back inside _AdbConnection class def ReadUntil (line 149) after returning from AdbMessage.Read(...)')
  150.         logger.info('cmd: %s', str(cmd))
  151.         logger.info('remote_id: %s', str(remote_id))
  152.         logger.info('local_id: %s', str(local_id))
  153.         logger.info('data: %s', str(data))
  154.         logger.info('self.remote_id: %s', str(self.remote_id))
  155.         if local_id != 0 and self.local_id != local_id:
  156.             raise InterleavedDataError("We don't support multiple streams...")
  157.         if remote_id != 0 and self.remote_id != remote_id:
  158.             raise InvalidResponseError(
  159.                 'Incorrect remote id, expected %s got %s' % (
  160.                     self.remote_id, remote_id))
  161.         # Ack write packets.
  162.         if cmd == b'WRTE':
  163.             self.Okay()
  164.         return cmd, data
  165.  
  166.     def ReadUntilClose(self):
  167.         """Yield packets until a Close packet is received."""
  168.         while True:
  169.             cmd, data = self.ReadUntil(b'CLSE', b'WRTE')
  170.             logger.info('Now inside _AdbConnection class def ReadUntilClose (line 170) after turning from self.ReadUntil(...)')
  171.             logger.info('cmd: %s', str(cmd))
  172.             logger.info('data: %s', str(data))
  173.             if cmd == b'CLSE':
  174.                 logger.info("About to self._Send(b'CLSE', arg0=self.local_id, arg1=self.remote_id) from ReadUntilClose(self) (line 174)")
  175.                 logger.info('self.local_id: %s', str(self.local_id))
  176.                 logger.info('self.remote_id: %s', str(self.remote_id))
  177.                 self._Send(b'CLSE', arg0=self.local_id, arg1=self.remote_id)
  178.                 break
  179.             if cmd != b'WRTE':
  180.                 if cmd == b'FAIL':
  181.                     raise usb_exceptions.AdbCommandFailureException(
  182.                         'Command failed.', data)
  183.                 logger.info("About to raise InvalidCommandError because cmd was not b'WRTE' or b'FAIL' (line 183)")
  184.                 raise InvalidCommandError('Expected a WRITE or a CLOSE, got %s (%s)',
  185.                                           cmd, data)
  186.             yield data
  187.  
  188.     def Close(self):
  189.         self._Send(b'CLSE', arg0=self.local_id, arg1=self.remote_id)
  190.         cmd, data = self.ReadUntil(b'CLSE')
  191.         if cmd != b'CLSE':
  192.             if cmd == b'FAIL':
  193.                 raise usb_exceptions.AdbCommandFailureException('Command failed.', data)
  194.             raise InvalidCommandError('Expected a CLSE response, got %s (%s)',
  195.                                       cmd, data)
  196.  
  197.  
  198. class AdbMessage(object):
  199.     """ADB Protocol and message class.
  200.  
  201.    Protocol Notes
  202.  
  203.    local_id/remote_id:
  204.      Turns out the documentation is host/device ambidextrous, so local_id is the
  205.      id for 'the sender' and remote_id is for 'the recipient'. So since we're
  206.      only on the host, we'll re-document with host_id and device_id:
  207.  
  208.      OPEN(host_id, 0, 'shell:XXX')
  209.      READY/OKAY(device_id, host_id, '')
  210.      WRITE(0, host_id, 'data')
  211.      CLOSE(device_id, host_id, '')
  212.    """
  213.  
  214.     ids = [b'SYNC', b'CNXN', b'AUTH', b'OPEN', b'OKAY', b'CLSE', b'WRTE']
  215.     commands, constants = MakeWireIDs(ids)
  216.     # An ADB message is 6 words in little-endian.
  217.     format = b'<6I'
  218.  
  219.     connections = 0
  220.  
  221.     def __init__(self, command=None, arg0=None, arg1=None, data=b''):
  222.         self.command = self.commands[command]
  223.         self.magic = self.command ^ 0xFFFFFFFF
  224.         self.arg0 = arg0
  225.         self.arg1 = arg1
  226.         self.data = data
  227.  
  228.     @property
  229.     def checksum(self):
  230.         return self.CalculateChecksum(self.data)
  231.  
  232.     @staticmethod
  233.     def CalculateChecksum(data):
  234.         # The checksum is just a sum of all the bytes. I swear.
  235.         if isinstance(data, bytearray):
  236.             total = sum(data)
  237.         elif isinstance(data, bytes):
  238.             if data and isinstance(data[0], bytes):
  239.                 # Python 2 bytes (str) index as single-character strings.
  240.                 total = sum(map(ord, data))
  241.             else:
  242.                 # Python 3 bytes index as numbers (and PY2 empty strings sum() to 0)
  243.                 total = sum(data)
  244.         else:
  245.             # Unicode strings (should never see?)
  246.             total = sum(map(ord, data))
  247.         return total & 0xFFFFFFFF
  248.  
  249.     def Pack(self):
  250.         """Returns this message in an over-the-wire format."""
  251.         logger.info('Now inside def Pack(self) (line 251)')
  252.         logger.info('self.format: %s', str(self.format))
  253.         logger.info('self.command: %s', str(self.command))
  254.         logger.info('self.arg0: %s', str(self.arg0))
  255.         logger.info('self.arg1: %s', str(self.arg1))
  256.         logger.info('len(self.data)): %s', str(len(self.data)))
  257.         logger.info('self.checksum: %s', str(self.checksum))
  258.         logger.info('self.magic: %s', str(self.magic))
  259.         packed = struct.pack(self.format, self.command, self.arg0, self.arg1,
  260.                              len(self.data), self.checksum, self.magic)
  261.         logger.info('packed: %s', str(packed))
  262.         return packed
  263.  
  264.     @classmethod
  265.     def Unpack(cls, message):
  266.         try:
  267.             cmd, arg0, arg1, data_length, data_checksum, unused_magic = struct.unpack(
  268.                 cls.format, message)
  269.         except struct.error as e:
  270.             raise ValueError('Unable to unpack ADB command.', cls.format, message, e)
  271.         logger.info('Now inside def Unpack (line 271)')
  272.         logger.info('cls: %s', str(cls))
  273.         logger.info('message: %s', str(message))
  274.         logger.info('cmd: %s', str(cmd))
  275.         logger.info('arg0: %s', str(arg0))
  276.         logger.info('arg1: %s', str(arg1))
  277.         logger.info('data_length: %s', str(data_length))
  278.         logger.info('data_checksum: %s', str(data_checksum))
  279.         logger.info('unused_magic: %s', str(unused_magic))
  280.         return cmd, arg0, arg1, data_length, data_checksum
  281.  
  282.     def Send(self, usb, timeout_ms=None):
  283.         """Send this message over USB."""
  284.         usb.BulkWrite(self.Pack(), timeout_ms)
  285.         usb.BulkWrite(self.data, timeout_ms)
  286.  
  287.     @classmethod
  288.     def Read(cls, usb, expected_cmds, timeout_ms=None, total_timeout_ms=None):
  289.         """Receive a response from the device."""
  290.         total_timeout_ms = usb.Timeout(total_timeout_ms)
  291.         start = time.time()
  292.         while True:
  293.             msg = usb.BulkRead(24, timeout_ms)
  294.             cmd, arg0, arg1, data_length, data_checksum = cls.Unpack(msg)
  295.             command = cls.constants.get(cmd)
  296.             logger.info('Now inside def Read (line 296)')
  297.             logger.info('msg: %s', str(msg))
  298.             logger.info('cmd: %s', str(cmd))
  299.             logger.info('arg0: %s', str(arg0))
  300.             logger.info('arg1: %s', str(arg1))
  301.             logger.info('data_length: %s', str(data_length))
  302.             logger.info('data_checksum: %s', str(data_checksum))
  303.             logger.info('command: %s', str(command))
  304.             logger.info('expected_cmds: %s', str(expected_cmds))
  305.             if not command:
  306.                 logger.info('About to throw InvalidCommandError in def Read (line 306)')
  307.                 raise InvalidCommandError(
  308.                     'Unknown command: %x' % cmd, cmd, (arg0, arg1))
  309.             if command in expected_cmds:
  310.                 break
  311.  
  312.             if time.time() - start > total_timeout_ms:
  313.                 raise InvalidCommandError(
  314.                     'Never got one of the expected responses (%s)' % expected_cmds,
  315.                     cmd, (timeout_ms, total_timeout_ms))
  316.  
  317.         if data_length > 0:
  318.             data = bytearray()
  319.             while data_length > 0:
  320.                 temp = usb.BulkRead(data_length, timeout_ms)
  321.                 if len(temp) != data_length:
  322.                     print(
  323.                         "Data_length {} does not match actual number of bytes read: {}".format(data_length, len(temp)))
  324.                 data += temp
  325.  
  326.                 data_length -= len(temp)
  327.  
  328.             actual_checksum = cls.CalculateChecksum(data)
  329.             if actual_checksum != data_checksum:
  330.                 raise InvalidChecksumError(
  331.                     'Received checksum %s != %s', (actual_checksum, data_checksum))
  332.         else:
  333.             data = b''
  334.         return command, arg0, arg1, bytes(data)
  335.  
  336.     @classmethod
  337.     def Connect(cls, usb, banner=b'notadb', rsa_keys=None, auth_timeout_ms=100):
  338.         """Establish a new connection to the device.
  339.  
  340.        Args:
  341.          usb: A USBHandle with BulkRead and BulkWrite methods.
  342.          banner: A string to send as a host identifier.
  343.          rsa_keys: List of AuthSigner subclass instances to be used for
  344.              authentication. The device can either accept one of these via the Sign
  345.              method, or we will send the result of GetPublicKey from the first one
  346.              if the device doesn't accept any of them.
  347.          auth_timeout_ms: Timeout to wait for when sending a new public key. This
  348.              is only relevant when we send a new public key. The device shows a
  349.              dialog and this timeout is how long to wait for that dialog. If used
  350.              in automation, this should be low to catch such a case as a failure
  351.              quickly; while in interactive settings it should be high to allow
  352.              users to accept the dialog. We default to automation here, so it's low
  353.              by default.
  354.  
  355.        Returns:
  356.          The device's reported banner. Always starts with the state (device,
  357.              recovery, or sideload), sometimes includes information after a : with
  358.              various product information.
  359.  
  360.        Raises:
  361.          usb_exceptions.DeviceAuthError: When the device expects authentication,
  362.              but we weren't given any valid keys.
  363.          InvalidResponseError: When the device does authentication in an
  364.              unexpected way.
  365.        """
  366.         # In py3, convert unicode to bytes. In py2, convert str to bytes.
  367.         # It's later joined into a byte string, so in py2, this ends up kind of being a no-op.
  368.         if isinstance(banner, str):
  369.             banner = bytearray(banner, 'utf-8')
  370.  
  371.         msg = cls(
  372.             command=b'CNXN', arg0=VERSION, arg1=MAX_ADB_DATA,
  373.             data=b'host::%s\0' % banner)
  374.         msg.Send(usb)
  375.         cmd, arg0, arg1, banner = cls.Read(usb, [b'CNXN', b'AUTH'])
  376.         if cmd == b'AUTH':
  377.             if not rsa_keys:
  378.                 raise usb_exceptions.DeviceAuthError(
  379.                     'Device authentication required, no keys available.')
  380.             # Loop through our keys, signing the last 'banner' or token.
  381.             for rsa_key in rsa_keys:
  382.                 if arg0 != AUTH_TOKEN:
  383.                     raise InvalidResponseError(
  384.                         'Unknown AUTH response: %s %s %s' % (arg0, arg1, banner))
  385.  
  386.                 # Do not mangle the banner property here by converting it to a string
  387.                 signed_token = rsa_key.Sign(banner)
  388.                 msg = cls(
  389.                     command=b'AUTH', arg0=AUTH_SIGNATURE, arg1=0, data=signed_token)
  390.                 msg.Send(usb)
  391.                 cmd, arg0, unused_arg1, banner = cls.Read(usb, [b'CNXN', b'AUTH'])
  392.                 if cmd == b'CNXN':
  393.                     return banner
  394.             # None of the keys worked, so send a public key.
  395.             msg = cls(
  396.                 command=b'AUTH', arg0=AUTH_RSAPUBLICKEY, arg1=0,
  397.                 data=rsa_keys[0].GetPublicKey() + b'\0')
  398.             msg.Send(usb)
  399.             try:
  400.                 cmd, arg0, unused_arg1, banner = cls.Read(
  401.                     usb, [b'CNXN'], timeout_ms=auth_timeout_ms)
  402.             except usb_exceptions.ReadFailedError as e:
  403.                 if e.usb_error.value == -7:  # Timeout.
  404.                     raise usb_exceptions.DeviceAuthError(
  405.                         'Accept auth key on device, then retry.')
  406.                 raise
  407.             # This didn't time-out, so we got a CNXN response.
  408.             return banner
  409.         return banner
  410.  
  411.     @classmethod
  412.     def Open(cls, usb, destination, timeout_ms=None):
  413.         """Opens a new connection to the device via an OPEN message.
  414.  
  415.        Not the same as the posix 'open' or any other google3 Open methods.
  416.  
  417.        Args:
  418.          usb: USB device handle with BulkRead and BulkWrite methods.
  419.          destination: The service:command string.
  420.          timeout_ms: Timeout in milliseconds for USB packets.
  421.  
  422.        Raises:
  423.          InvalidResponseError: Wrong local_id sent to us.
  424.          InvalidCommandError: Didn't get a ready response.
  425.  
  426.        Returns:
  427.          The local connection id.
  428.        """
  429.         logger.info('Now inside def Open (line 429)')
  430.         logger.info('destination: %s', str(destination))
  431.         logger.info('cls: %s', str(cls))
  432.         logger.info('usb: %s', str(usb))
  433.         local_id = 1
  434.         msg = cls(
  435.             command=b'OPEN', arg0=local_id, arg1=0,
  436.             data=destination + b'\0')
  437.         logger.info('Sending msg: %s', str(msg))
  438.         msg.Send(usb, timeout_ms)
  439.         cmd, remote_id, their_local_id, _ = cls.Read(usb, [b'CLSE', b'OKAY'],
  440.                                                      timeout_ms=timeout_ms)
  441.         logger.info('Received following results from cls.Read. Now back inside Open')
  442.         logger.info('cmd: %s', str(cmd))
  443.         logger.info('remote_id: %s', str(remote_id))
  444.         logger.info('their_local_id: %s', str(their_local_id))
  445.         logger.info('_: %s', str(_))
  446.         if local_id != their_local_id:
  447.             raise InvalidResponseError(
  448.                 'Expected the local_id to be {}, got {}'.format(local_id, their_local_id))
  449.         if cmd == b'CLSE':
  450.             logger.info("Inside if cmd == b'CLSE': (line 450)")
  451.             # Some devices seem to be sending CLSE once more after a request, this *should* handle it
  452.             cmd, remote_id, their_local_id, _ = cls.Read(usb, [b'CLSE', b'OKAY'],
  453.                                                          timeout_ms=timeout_ms)
  454.             logger.info('cmd: %s', str(cmd))
  455.             logger.info('remote_id: %s', str(remote_id))
  456.             logger.info('their_local_id: %s', str(their_local_id))
  457.             logger.info('_: %s', str(_))
  458.            
  459.             # Device doesn't support this service.
  460.             if cmd == b'CLSE':
  461.                 return None
  462.         if cmd != b'OKAY':
  463.             logger.info("Inside if cmd != b'OKAY': (line 463)")
  464.             logger.info("About to raise an InvalidCommandError")
  465.             logger.info('cmd: %s', str(cmd))
  466.             logger.info('remote_id: %s', str(remote_id))
  467.             logger.info('their_local_id: %s', str(their_local_id))
  468.             raise InvalidCommandError('Expected a ready response, got {}'.format(cmd),
  469.                                       cmd, (remote_id, their_local_id))
  470.         return _AdbConnection(usb, local_id, remote_id, timeout_ms)
  471.  
  472.     @classmethod
  473.     def Command(cls, usb, service, command='', timeout_ms=None):
  474.         """One complete set of USB packets for a single command.
  475.  
  476.        Sends service:command in a new connection, reading the data for the
  477.        response. All the data is held in memory, large responses will be slow and
  478.        can fill up memory.
  479.  
  480.        Args:
  481.          usb: USB device handle with BulkRead and BulkWrite methods.
  482.          service: The service on the device to talk to.
  483.          command: The command to send to the service.
  484.          timeout_ms: Timeout for USB packets, in milliseconds.
  485.  
  486.        Raises:
  487.          InterleavedDataError: Multiple streams running over usb.
  488.          InvalidCommandError: Got an unexpected response command.
  489.  
  490.        Returns:
  491.          The response from the service.
  492.        """
  493.         result = ''.join(cls.StreamingCommand(usb, service, command, timeout_ms))
  494.         logger.info('from def Command returning result: %s', result)
  495.         return result
  496.  
  497.     @classmethod
  498.     def StreamingCommand(cls, usb, service, command='', timeout_ms=None):
  499.         """One complete set of USB packets for a single command.
  500.  
  501.        Sends service:command in a new connection, reading the data for the
  502.        response. All the data is held in memory, large responses will be slow and
  503.        can fill up memory.
  504.  
  505.        Args:
  506.          usb: USB device handle with BulkRead and BulkWrite methods.
  507.          service: The service on the device to talk to.
  508.          command: The command to send to the service.
  509.          timeout_ms: Timeout for USB packets, in milliseconds.
  510.  
  511.        Raises:
  512.          InterleavedDataError: Multiple streams running over usb.
  513.          InvalidCommandError: Got an unexpected response command.
  514.  
  515.        Yields:
  516.          The responses from the service.
  517.        """
  518.         logger.info("Inside StreamingCommand(cls, usb, service, command='', timeout_ms=None) (line 518)")
  519.         logger.info('command before type test: %s (%s)', str(command), str(type(command)))
  520.         if not isinstance(command, bytes):
  521.             command = command.encode('utf8')
  522.         logger.info('cls: %s', str(cls))
  523.         logger.info('usb: %s', str(usb))
  524.         logger.info('service: %s', str(service))
  525.         logger.info('command after type test: %s (%s)', str(command), str(type(command)))
  526.         logger.info('timeout_ms: %s', str(timeout_ms))
  527.         connection = cls.Open(
  528.             usb, destination=b'%s:%s' % (service, command),
  529.             timeout_ms=timeout_ms)
  530.         logger.info('connection: %s', str(connection))
  531.         for data in connection.ReadUntilClose():
  532.             logger.info("data.decode('utf8') (line 532): %s", str(data.decode('utf8')))
  533.             yield data.decode('utf8')
  534.  
  535.     @classmethod
  536.     def InteractiveShellCommand(cls, conn, cmd=None, strip_cmd=True, delim=None, strip_delim=True, clean_stdout=True):
  537.         """Retrieves stdout of the current InteractiveShell and sends a shell command if provided
  538.        TODO: Should we turn this into a yield based function so we can stream all output?
  539.  
  540.        Args:
  541.          conn: Instance of AdbConnection
  542.          cmd: Optional. Command to run on the target.
  543.          strip_cmd: Optional (default True). Strip command name from stdout.
  544.          delim: Optional. Delimiter to look for in the output to know when to stop expecting more output
  545.          (usually the shell prompt)
  546.          strip_delim: Optional (default True): Strip the provided delimiter from the output
  547.          clean_stdout: Cleanup the stdout stream of any backspaces and the characters that were deleted by the backspace
  548.        Returns:
  549.          The stdout from the shell command.
  550.        """
  551.  
  552.         if delim is not None and not isinstance(delim, bytes):
  553.             delim = delim.encode('utf-8')
  554.  
  555.         # Delimiter may be shell@hammerhead:/ $
  556.         # The user or directory could change, making the delimiter somthing like root@hammerhead:/data/local/tmp $
  557.         # Handle a partial delimiter to search on and clean up
  558.         if delim:
  559.             user_pos = delim.find(b'@')
  560.             dir_pos = delim.rfind(b':/')
  561.             if user_pos != -1 and dir_pos != -1:
  562.                 partial_delim = delim[user_pos:dir_pos + 1]  # e.g. @hammerhead:
  563.             else:
  564.                 partial_delim = delim
  565.         else:
  566.             partial_delim = None
  567.  
  568.         stdout = ''
  569.         stdout_stream = BytesIO()
  570.         original_cmd = ''
  571.  
  572.         try:
  573.  
  574.             if cmd:
  575.                 original_cmd = str(cmd)
  576.                 cmd += '\r'  # Required. Send a carriage return right after the cmd
  577.                 cmd = cmd.encode('utf8')
  578.  
  579.                 # Send the cmd raw
  580.                 bytes_written = conn.Write(cmd)
  581.  
  582.                 if delim:
  583.                     # Expect multiple WRTE cmds until the delim (usually terminal prompt) is detected
  584.  
  585.                     data = b''
  586.                     while partial_delim not in data:
  587.                         cmd, data = conn.ReadUntil(b'WRTE')
  588.                         stdout_stream.write(data)
  589.  
  590.                 else:
  591.                     # Otherwise, expect only a single WRTE
  592.                     cmd, data = conn.ReadUntil(b'WRTE')
  593.  
  594.                     # WRTE cmd from device will follow with stdout data
  595.                     stdout_stream.write(data)
  596.  
  597.             else:
  598.  
  599.                 # No cmd provided means we should just expect a single line from the terminal. Use this sparingly
  600.                 cmd, data = conn.ReadUntil(b'WRTE')
  601.                 if cmd == b'WRTE':
  602.                     # WRTE cmd from device will follow with stdout data
  603.                     stdout_stream.write(data)
  604.                 else:
  605.                     print("Unhandled cmd: {}".format(cmd))
  606.  
  607.             cleaned_stdout_stream = BytesIO()
  608.             if clean_stdout:
  609.                 stdout_bytes = stdout_stream.getvalue()
  610.  
  611.                 bsruns = {}  # Backspace runs tracking
  612.                 next_start_pos = 0
  613.                 last_run_pos, last_run_len = find_backspace_runs(stdout_bytes, next_start_pos)
  614.  
  615.                 if last_run_pos != -1 and last_run_len != 0:
  616.                     bsruns.update({last_run_pos: last_run_len})
  617.                     cleaned_stdout_stream.write(stdout_bytes[next_start_pos:(last_run_pos - last_run_len)])
  618.                     next_start_pos += last_run_pos + last_run_len
  619.  
  620.                 while last_run_pos != -1:
  621.                     last_run_pos, last_run_len = find_backspace_runs(stdout_bytes[next_start_pos:], next_start_pos)
  622.  
  623.                     if last_run_pos != -1:
  624.                         bsruns.update({last_run_pos: last_run_len})
  625.                         cleaned_stdout_stream.write(stdout_bytes[next_start_pos:(last_run_pos - last_run_len)])
  626.                         next_start_pos += last_run_pos + last_run_len
  627.  
  628.                 cleaned_stdout_stream.write(stdout_bytes[next_start_pos:])
  629.  
  630.             else:
  631.                 cleaned_stdout_stream.write(stdout_stream.getvalue())
  632.  
  633.             stdout = cleaned_stdout_stream.getvalue()
  634.  
  635.             # Strip original cmd that will come back in stdout
  636.             if original_cmd and strip_cmd:
  637.                 findstr = original_cmd.encode('utf-8') + b'\r\r\n'
  638.                 pos = stdout.find(findstr)
  639.                 while pos >= 0:
  640.                     stdout = stdout.replace(findstr, b'')
  641.                     pos = stdout.find(findstr)
  642.  
  643.                 if b'\r\r\n' in stdout:
  644.                     stdout = stdout.split(b'\r\r\n')[1]
  645.  
  646.             # Strip delim if requested
  647.             # TODO: Handling stripping partial delims here - not a deal breaker the way we're handling it now
  648.             if delim and strip_delim:
  649.                 stdout = stdout.replace(delim, b'')
  650.  
  651.             stdout = stdout.rstrip()
  652.  
  653.         except Exception as e:
  654.             print("InteractiveShell exception (most likely timeout): {}".format(e))
  655.  
  656.         return stdout
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement