Skip to content
This repository has been archived by the owner on Jan 10, 2023. It is now read-only.

Commit

Permalink
Many, many str/bytes fixes for Python3 compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
fahhem committed Jun 8, 2017
1 parent 0a52659 commit 288d964
Show file tree
Hide file tree
Showing 7 changed files with 156 additions and 144 deletions.
26 changes: 13 additions & 13 deletions adb/adb_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def ConnectDevice(
If serial specifies a TCP address:port, then a TCP connection is
used instead of a USB connection.
"""
if serial and ':' in serial:
if serial and b':' in serial:
handle = common.TcpHandle(serial)
else:
handle = common.UsbHandle.FindAndOpen(
Expand Down Expand Up @@ -98,7 +98,7 @@ def Connect(cls, usb, banner=None, **kwargs):
banner = socket.gethostname()
device_state = cls.protocol_handler.Connect(usb, banner=banner, **kwargs)
# Remove banner and colons after device state (state::banner)
device_state = device_state.split(':')[0]
device_state = device_state.split(b':')[0]
return cls(usb, device_state)

@classmethod
Expand Down Expand Up @@ -151,7 +151,7 @@ def Push(self, source_file, device_filename, mtime='0', timeout_ms=None):
source_file = open(source_file)

connection = self.protocol_handler.Open(
self.handle, destination='sync:', timeout_ms=timeout_ms)
self.handle, destination=b'sync:', timeout_ms=timeout_ms)
self.filesync_handler.Push(connection, source_file, device_filename,
mtime=int(mtime))
connection.Close()
Expand All @@ -172,7 +172,7 @@ def Pull(self, device_filename, dest_file='', timeout_ms=None):
elif isinstance(dest_file, str):
dest_file = open(dest_file, 'w')
connection = self.protocol_handler.Open(
self.handle, destination='sync:',
self.handle, destination=b'sync:',
timeout_ms=timeout_ms)
self.filesync_handler.Pull(connection, device_filename, dest_file)
connection.Close()
Expand All @@ -183,7 +183,7 @@ def Pull(self, device_filename, dest_file='', timeout_ms=None):

def Stat(self, device_filename):
"""Get a file's stat() information."""
connection = self.protocol_handler.Open(self.handle, destination='sync:')
connection = self.protocol_handler.Open(self.handle, destination=b'sync:')
mode, size, mtime = self.filesync_handler.Stat(
connection, device_filename)
connection.Close()
Expand All @@ -195,35 +195,35 @@ def List(self, device_path):
Args:
device_path: Directory to list.
"""
connection = self.protocol_handler.Open(self.handle, destination='sync:')
connection = self.protocol_handler.Open(self.handle, destination=b'sync:')
listing = self.filesync_handler.List(connection, device_path)
connection.Close()
return listing

def Reboot(self, destination=''):
def Reboot(self, destination=b''):
"""Reboot the device.
Args:
destination: Specify 'bootloader' for fastboot.
"""
self.protocol_handler.Open(self.handle, 'reboot:%s' % destination)
self.protocol_handler.Open(self.handle, b'reboot:%s' % destination)

def RebootBootloader(self):
"""Reboot device into fastboot."""
self.Reboot('bootloader')
self.Reboot(b'bootloader')

def Remount(self):
"""Remount / as read-write."""
return self.protocol_handler.Command(self.handle, service='remount')
return self.protocol_handler.Command(self.handle, service=b'remount')

def Root(self):
"""Restart adbd as root on the device."""
return self.protocol_handler.Command(self.handle, service='root')
return self.protocol_handler.Command(self.handle, service=b'root')

def Shell(self, command, timeout_ms=None):
"""Run command on the device, returning the output."""
return self.protocol_handler.Command(
self.handle, service='shell', command=command,
self.handle, service=b'shell', command=command,
timeout_ms=timeout_ms)

def StreamingShell(self, command, timeout_ms=None):
Expand All @@ -237,7 +237,7 @@ def StreamingShell(self, command, timeout_ms=None):
The responses from the shell command.
"""
return self.protocol_handler.StreamingCommand(
self.handle, service='shell', command=command,
self.handle, service=b'shell', command=command,
timeout_ms=timeout_ms)

def Logcat(self, options, timeout_ms=None):
Expand Down
94 changes: 47 additions & 47 deletions adb/adb_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class InvalidCommandError(Exception):
"""Got an invalid command over USB."""

def __init__(self, message, response_header, response_data):
if response_header == 'FAIL':
if response_header == b'FAIL':
message = 'Command failed, device said so. (%s)' % message
super(InvalidCommandError, self).__init__(
message, response_header, response_data)
Expand All @@ -58,7 +58,7 @@ class InterleavedDataError(Exception):

def MakeWireIDs(ids):
id_to_wire = {
cmd_id: sum(ord(c) << (i * 8) for i, c in enumerate(cmd_id))
cmd_id: sum(c << (i * 8) for i, c in enumerate(bytearray(cmd_id)))
for cmd_id in ids
}
wire_to_id = {wire: cmd_id for cmd_id, wire in id_to_wire.items()}
Expand Down Expand Up @@ -86,17 +86,17 @@ def __init__(self, usb, local_id, remote_id, timeout_ms):
self.remote_id = remote_id
self.timeout_ms = timeout_ms

def _Send(self, command, arg0, arg1, data=''):
def _Send(self, command, arg0, arg1, data=b''):
message = AdbMessage(command, arg0, arg1, data)
message.Send(self.usb, self.timeout_ms)

def Write(self, data):
"""Write a packet and expect an Ack."""
self._Send('WRTE', arg0=self.local_id, arg1=self.remote_id, data=data)
self._Send(b'WRTE', arg0=self.local_id, arg1=self.remote_id, data=data)
# Expect an ack in response.
cmd, okay_data = self.ReadUntil('OKAY')
if cmd != 'OKAY':
if cmd == 'FAIL':
cmd, okay_data = self.ReadUntil(b'OKAY')
if cmd != b'OKAY':
if cmd == b'FAIL':
raise usb_exceptions.AdbCommandFailureException(
'Command failed.', okay_data)
raise InvalidCommandError(
Expand All @@ -105,7 +105,7 @@ def Write(self, data):
return len(data)

def Okay(self):
self._Send('OKAY', arg0=self.local_id, arg1=self.remote_id)
self._Send(b'OKAY', arg0=self.local_id, arg1=self.remote_id)

def ReadUntil(self, *expected_cmds):
"""Read a packet, Ack any write packets."""
Expand All @@ -118,30 +118,30 @@ def ReadUntil(self, *expected_cmds):
'Incorrect remote id, expected %s got %s' % (
self.remote_id, remote_id))
# Ack write packets.
if cmd == 'WRTE':
if cmd == b'WRTE':
self.Okay()
return cmd, data

def ReadUntilClose(self):
"""Yield packets until a Close packet is received."""
while True:
cmd, data = self.ReadUntil('CLSE', 'WRTE')
if cmd == 'CLSE':
self._Send('CLSE', arg0=self.local_id, arg1=self.remote_id)
cmd, data = self.ReadUntil(b'CLSE', b'WRTE')
if cmd == b'CLSE':
self._Send(b'CLSE', arg0=self.local_id, arg1=self.remote_id)
break
if cmd != 'WRTE':
if cmd == 'FAIL':
if cmd != b'WRTE':
if cmd == b'FAIL':
raise usb_exceptions.AdbCommandFailureException(
'Command failed.', data)
raise InvalidCommandError('Expected a WRITE or a CLOSE, got %s (%s)',
cmd, data)
yield data

def Close(self):
self._Send('CLSE', arg0=self.local_id, arg1=self.remote_id)
cmd, data = self.ReadUntil('CLSE')
if cmd != 'CLSE':
if cmd == 'FAIL':
self._Send(b'CLSE', arg0=self.local_id, arg1=self.remote_id)
cmd, data = self.ReadUntil(b'CLSE')
if cmd != b'CLSE':
if cmd == b'FAIL':
raise usb_exceptions.AdbCommandFailureException('Command failed.', data)
raise InvalidCommandError('Expected a CLSE response, got %s (%s)',
cmd, data)
Expand All @@ -163,14 +163,14 @@ class AdbMessage(object):
CLOSE(device_id, host_id, '')
"""

ids = ['SYNC', 'CNXN', 'AUTH', 'OPEN', 'OKAY', 'CLSE', 'WRTE']
ids = [b'SYNC', b'CNXN', b'AUTH', b'OPEN', b'OKAY', b'CLSE', b'WRTE']
commands, constants = MakeWireIDs(ids)
# An ADB message is 6 words in little-endian.
format = '<6I'
format = b'<6I'

connections = 0

def __init__(self, command=None, arg0=None, arg1=None, data=''):
def __init__(self, command=None, arg0=None, arg1=None, data=b''):
self.command = self.commands[command]
self.magic = self.command ^ 0xFFFFFFFF
self.arg0 = arg0
Expand Down Expand Up @@ -232,13 +232,10 @@ def Read(cls, usb, expected_cmds, timeout_ms=None, total_timeout_ms=None):
cmd, (timeout_ms, total_timeout_ms))

if data_length > 0:
data = ''
data = bytearray()
while data_length > 0:
temp = usb.BulkRead(data_length, timeout_ms)
if isinstance(temp, bytes):
data += temp.decode('ascii')
else:
data += temp
data += temp

data_length -= len(temp)

Expand All @@ -247,11 +244,11 @@ def Read(cls, usb, expected_cmds, timeout_ms=None, total_timeout_ms=None):
raise InvalidChecksumError(
'Received checksum %s != %s', (actual_checksum, data_checksum))
else:
data = ''
return command, arg0, arg1, data
data = b''
return command, arg0, arg1, bytes(data)

@classmethod
def Connect(cls, usb, banner='notadb', rsa_keys=None, auth_timeout_ms=100):
def Connect(cls, usb, banner=b'notadb', rsa_keys=None, auth_timeout_ms=100):
"""Establish a new connection to the device.
Args:
Expand Down Expand Up @@ -281,11 +278,11 @@ def Connect(cls, usb, banner='notadb', rsa_keys=None, auth_timeout_ms=100):
unexpected way.
"""
msg = cls(
command='CNXN', arg0=VERSION, arg1=MAX_ADB_DATA,
data='host::%s\0' % banner)
command=b'CNXN', arg0=VERSION, arg1=MAX_ADB_DATA,
data=b'host::%s\0' % banner)
msg.Send(usb)
cmd, arg0, arg1, banner = cls.Read(usb, ['CNXN', 'AUTH'])
if cmd == 'AUTH':
cmd, arg0, arg1, banner = cls.Read(usb, [b'CNXN', b'AUTH'])
if cmd == b'AUTH':
if not rsa_keys:
raise usb_exceptions.DeviceAuthError(
'Device authentication required, no keys available.')
Expand All @@ -297,19 +294,19 @@ def Connect(cls, usb, banner='notadb', rsa_keys=None, auth_timeout_ms=100):

signed_token = rsa_key.Sign(str(banner))
msg = cls(
command='AUTH', arg0=AUTH_SIGNATURE, arg1=0, data=signed_token)
command=b'AUTH', arg0=AUTH_SIGNATURE, arg1=0, data=signed_token)
msg.Send(usb)
cmd, arg0, unused_arg1, banner = cls.Read(usb, ['CNXN', 'AUTH'])
if cmd == 'CNXN':
cmd, arg0, unused_arg1, banner = cls.Read(usb, [b'CNXN', b'AUTH'])
if cmd == b'CNXN':
return banner
# None of the keys worked, so send a public key.
msg = cls(
command='AUTH', arg0=AUTH_RSAPUBLICKEY, arg1=0,
data=rsa_keys[0].GetPublicKey() + '\0')
command=b'AUTH', arg0=AUTH_RSAPUBLICKEY, arg1=0,
data=rsa_keys[0].GetPublicKey() + b'\0')
msg.Send(usb)
try:
cmd, arg0, unused_arg1, banner = cls.Read(
usb, ['CNXN'], timeout_ms=auth_timeout_ms)
usb, [b'CNXN'], timeout_ms=auth_timeout_ms)
except usb_exceptions.ReadFailedError as e:
if e.usb_error.value == -7: # Timeout.
raise usb_exceptions.DeviceAuthError(
Expand Down Expand Up @@ -339,18 +336,18 @@ def Open(cls, usb, destination, timeout_ms=None):
"""
local_id = 1
msg = cls(
command='OPEN', arg0=local_id, arg1=0,
data=destination + '\0')
command=b'OPEN', arg0=local_id, arg1=0,
data=destination + b'\0')
msg.Send(usb, timeout_ms)
cmd, remote_id, their_local_id, _ = cls.Read(usb, ['CLSE', 'OKAY'],
cmd, remote_id, their_local_id, _ = cls.Read(usb, [b'CLSE', b'OKAY'],
timeout_ms=timeout_ms)
if local_id != their_local_id:
raise InvalidResponseError(
'Expected the local_id to be %s, got %s' % (local_id, their_local_id))
if cmd == 'CLSE':
if cmd == b'CLSE':
# Device doesn't support this service.
return None
if cmd != 'OKAY':
if cmd != b'OKAY':
raise InvalidCommandError('Expected a ready response, got %s' % cmd,
cmd, (remote_id, their_local_id))
return _AdbConnection(usb, local_id, remote_id, timeout_ms)
Expand Down Expand Up @@ -399,7 +396,10 @@ def StreamingCommand(cls, usb, service, command='', timeout_ms=None):
Yields:
The responses from the service.
"""
connection = cls.Open(usb, destination='%s:%s' % (service, command),
timeout_ms=timeout_ms)
if isinstance(command, str):
command = command.encode('utf8')
connection = cls.Open(
usb, destination=b'%s:%s' % (service, command),
timeout_ms=timeout_ms)
for data in connection.ReadUntilClose():
yield str(data)
yield data.decode('utf8')
Loading

0 comments on commit 288d964

Please sign in to comment.