adb_protocol.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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. Implements the ADB protocol as seen in android's adb/adbd binaries, but only the
  16. host side.
  17. """
  18. import struct
  19. import time
  20. from io import BytesIO
  21. from adb import usb_exceptions
  22. # Maximum amount of data in an ADB packet.
  23. MAX_ADB_DATA = 4096
  24. # ADB protocol version.
  25. VERSION = 0x01000000
  26. # AUTH constants for arg0.
  27. AUTH_TOKEN = 1
  28. AUTH_SIGNATURE = 2
  29. AUTH_RSAPUBLICKEY = 3
  30. def find_backspace_runs(stdout_bytes, start_pos):
  31. first_backspace_pos = stdout_bytes[start_pos:].find(b'\x08')
  32. if first_backspace_pos == -1:
  33. return -1, 0
  34. end_backspace_pos = (start_pos + first_backspace_pos) + 1
  35. while True:
  36. if chr(stdout_bytes[end_backspace_pos]) == '\b':
  37. end_backspace_pos += 1
  38. else:
  39. break
  40. num_backspaces = end_backspace_pos - (start_pos + first_backspace_pos)
  41. return (start_pos + first_backspace_pos), num_backspaces
  42. class InvalidCommandError(Exception):
  43. """Got an invalid command over USB."""
  44. def __init__(self, message, response_header, response_data):
  45. if response_header == b'FAIL':
  46. message = 'Command failed, device said so. (%s)' % message
  47. super(InvalidCommandError, self).__init__(
  48. message, response_header, response_data)
  49. class InvalidResponseError(Exception):
  50. """Got an invalid response to our command."""
  51. class InvalidChecksumError(Exception):
  52. """Checksum of data didn't match expected checksum."""
  53. class InterleavedDataError(Exception):
  54. """We only support command sent serially."""
  55. def MakeWireIDs(ids):
  56. id_to_wire = {
  57. cmd_id: sum(c << (i * 8) for i, c in enumerate(bytearray(cmd_id)))
  58. for cmd_id in ids
  59. }
  60. wire_to_id = {wire: cmd_id for cmd_id, wire in id_to_wire.items()}
  61. return id_to_wire, wire_to_id
  62. class AuthSigner(object):
  63. """Signer for use with authenticated ADB, introduced in 4.4.x/KitKat."""
  64. def Sign(self, data):
  65. """Signs given data using a private key."""
  66. raise NotImplementedError()
  67. def GetPublicKey(self):
  68. """Returns the public key in PEM format without headers or newlines."""
  69. raise NotImplementedError()
  70. class _AdbConnection(object):
  71. """ADB Connection."""
  72. def __init__(self, usb, local_id, remote_id, timeout_ms):
  73. self.usb = usb
  74. self.local_id = local_id
  75. self.remote_id = remote_id
  76. self.timeout_ms = timeout_ms
  77. def _Send(self, command, arg0, arg1, data=b''):
  78. message = AdbMessage(command, arg0, arg1, data)
  79. message.Send(self.usb, self.timeout_ms)
  80. def Write(self, data):
  81. """Write a packet and expect an Ack."""
  82. self._Send(b'WRTE', arg0=self.local_id, arg1=self.remote_id, data=data)
  83. # Expect an ack in response.
  84. cmd, okay_data = self.ReadUntil(b'OKAY')
  85. if cmd != b'OKAY':
  86. if cmd == b'FAIL':
  87. raise usb_exceptions.AdbCommandFailureException(
  88. 'Command failed.', okay_data)
  89. raise InvalidCommandError(
  90. 'Expected an OKAY in response to a WRITE, got %s (%s)',
  91. cmd, okay_data)
  92. return len(data)
  93. def Okay(self):
  94. self._Send(b'OKAY', arg0=self.local_id, arg1=self.remote_id)
  95. def ReadUntil(self, *expected_cmds):
  96. """Read a packet, Ack any write packets."""
  97. cmd, remote_id, local_id, data = AdbMessage.Read(
  98. self.usb, expected_cmds, self.timeout_ms)
  99. if local_id != 0 and self.local_id != local_id:
  100. raise InterleavedDataError("We don't support multiple streams...")
  101. if remote_id != 0 and self.remote_id != remote_id:
  102. raise InvalidResponseError(
  103. 'Incorrect remote id, expected %s got %s' % (
  104. self.remote_id, remote_id))
  105. # Ack write packets.
  106. if cmd == b'WRTE':
  107. self.Okay()
  108. return cmd, data
  109. def ReadUntilClose(self):
  110. """Yield packets until a Close packet is received."""
  111. while True:
  112. cmd, data = self.ReadUntil(b'CLSE', b'WRTE')
  113. if cmd == b'CLSE':
  114. self._Send(b'CLSE', arg0=self.local_id, arg1=self.remote_id)
  115. break
  116. if cmd != b'WRTE':
  117. if cmd == b'FAIL':
  118. raise usb_exceptions.AdbCommandFailureException(
  119. 'Command failed.', data)
  120. raise InvalidCommandError('Expected a WRITE or a CLOSE, got %s (%s)',
  121. cmd, data)
  122. yield data
  123. def Close(self):
  124. self._Send(b'CLSE', arg0=self.local_id, arg1=self.remote_id)
  125. cmd, data = self.ReadUntil(b'CLSE')
  126. if cmd != b'CLSE':
  127. if cmd == b'FAIL':
  128. raise usb_exceptions.AdbCommandFailureException('Command failed.', data)
  129. raise InvalidCommandError('Expected a CLSE response, got %s (%s)',
  130. cmd, data)
  131. class AdbMessage(object):
  132. """ADB Protocol and message class.
  133. Protocol Notes
  134. local_id/remote_id:
  135. Turns out the documentation is host/device ambidextrous, so local_id is the
  136. id for 'the sender' and remote_id is for 'the recipient'. So since we're
  137. only on the host, we'll re-document with host_id and device_id:
  138. OPEN(host_id, 0, 'shell:XXX')
  139. READY/OKAY(device_id, host_id, '')
  140. WRITE(0, host_id, 'data')
  141. CLOSE(device_id, host_id, '')
  142. """
  143. ids = [b'SYNC', b'CNXN', b'AUTH', b'OPEN', b'OKAY', b'CLSE', b'WRTE']
  144. commands, constants = MakeWireIDs(ids)
  145. # An ADB message is 6 words in little-endian.
  146. format = b'<6I'
  147. connections = 0
  148. def __init__(self, command=None, arg0=None, arg1=None, data=b''):
  149. self.command = self.commands[command]
  150. self.magic = self.command ^ 0xFFFFFFFF
  151. self.arg0 = arg0
  152. self.arg1 = arg1
  153. self.data = data
  154. @property
  155. def checksum(self):
  156. return self.CalculateChecksum(self.data)
  157. @staticmethod
  158. def CalculateChecksum(data):
  159. # The checksum is just a sum of all the bytes. I swear.
  160. if isinstance(data, bytearray):
  161. total = sum(data)
  162. elif isinstance(data, bytes):
  163. if data and isinstance(data[0], bytes):
  164. # Python 2 bytes (str) index as single-character strings.
  165. total = sum(map(ord, data))
  166. else:
  167. # Python 3 bytes index as numbers (and PY2 empty strings sum() to 0)
  168. total = sum(data)
  169. else:
  170. # Unicode strings (should never see?)
  171. total = sum(map(ord, data))
  172. return total & 0xFFFFFFFF
  173. def Pack(self):
  174. """Returns this message in an over-the-wire format."""
  175. return struct.pack(self.format, self.command, self.arg0, self.arg1,
  176. len(self.data), self.checksum, self.magic)
  177. @classmethod
  178. def Unpack(cls, message):
  179. try:
  180. cmd, arg0, arg1, data_length, data_checksum, unused_magic = struct.unpack(
  181. cls.format, message)
  182. except struct.error as e:
  183. raise ValueError('Unable to unpack ADB command.', cls.format, message, e)
  184. return cmd, arg0, arg1, data_length, data_checksum
  185. def Send(self, usb, timeout_ms=None):
  186. """Send this message over USB."""
  187. usb.BulkWrite(self.Pack(), timeout_ms)
  188. usb.BulkWrite(self.data, timeout_ms)
  189. @classmethod
  190. def Read(cls, usb, expected_cmds, timeout_ms=None, total_timeout_ms=None):
  191. """Receive a response from the device."""
  192. total_timeout_ms = usb.Timeout(total_timeout_ms)
  193. start = time.time()
  194. while True:
  195. msg = usb.BulkRead(24, timeout_ms)
  196. cmd, arg0, arg1, data_length, data_checksum = cls.Unpack(msg)
  197. command = cls.constants.get(cmd)
  198. if not command:
  199. raise InvalidCommandError(
  200. 'Unknown command: %x' % cmd, cmd, (arg0, arg1))
  201. if command in expected_cmds:
  202. break
  203. if time.time() - start > total_timeout_ms:
  204. raise InvalidCommandError(
  205. 'Never got one of the expected responses (%s)' % expected_cmds,
  206. cmd, (timeout_ms, total_timeout_ms))
  207. if data_length > 0:
  208. data = bytearray()
  209. while data_length > 0:
  210. temp = usb.BulkRead(data_length, timeout_ms)
  211. if len(temp) != data_length:
  212. print(
  213. "Data_length {} does not match actual number of bytes read: {}".format(data_length, len(temp)))
  214. data += temp
  215. data_length -= len(temp)
  216. actual_checksum = cls.CalculateChecksum(data)
  217. if actual_checksum != data_checksum:
  218. raise InvalidChecksumError(
  219. 'Received checksum %s != %s', (actual_checksum, data_checksum))
  220. else:
  221. data = b''
  222. return command, arg0, arg1, bytes(data)
  223. @classmethod
  224. def Connect(cls, usb, banner=b'notadb', rsa_keys=None, auth_timeout_ms=100):
  225. """Establish a new connection to the device.
  226. Args:
  227. usb: A USBHandle with BulkRead and BulkWrite methods.
  228. banner: A string to send as a host identifier.
  229. rsa_keys: List of AuthSigner subclass instances to be used for
  230. authentication. The device can either accept one of these via the Sign
  231. method, or we will send the result of GetPublicKey from the first one
  232. if the device doesn't accept any of them.
  233. auth_timeout_ms: Timeout to wait for when sending a new public key. This
  234. is only relevant when we send a new public key. The device shows a
  235. dialog and this timeout is how long to wait for that dialog. If used
  236. in automation, this should be low to catch such a case as a failure
  237. quickly; while in interactive settings it should be high to allow
  238. users to accept the dialog. We default to automation here, so it's low
  239. by default.
  240. Returns:
  241. The device's reported banner. Always starts with the state (device,
  242. recovery, or sideload), sometimes includes information after a : with
  243. various product information.
  244. Raises:
  245. usb_exceptions.DeviceAuthError: When the device expects authentication,
  246. but we weren't given any valid keys.
  247. InvalidResponseError: When the device does authentication in an
  248. unexpected way.
  249. """
  250. # In py3, convert unicode to bytes. In py2, convert str to bytes.
  251. # It's later joined into a byte string, so in py2, this ends up kind of being a no-op.
  252. if isinstance(banner, str):
  253. banner = bytearray(banner, 'utf-8')
  254. msg = cls(
  255. command=b'CNXN', arg0=VERSION, arg1=MAX_ADB_DATA,
  256. data=b'host::%s\0' % banner)
  257. msg.Send(usb)
  258. cmd, arg0, arg1, banner = cls.Read(usb, [b'CNXN', b'AUTH'])
  259. if cmd == b'AUTH':
  260. if not rsa_keys:
  261. raise usb_exceptions.DeviceAuthError(
  262. 'Device authentication required, no keys available.')
  263. # Loop through our keys, signing the last 'banner' or token.
  264. for rsa_key in rsa_keys:
  265. if arg0 != AUTH_TOKEN:
  266. raise InvalidResponseError(
  267. 'Unknown AUTH response: %s %s %s' % (arg0, arg1, banner))
  268. # Do not mangle the banner property here by converting it to a string
  269. signed_token = rsa_key.Sign(banner)
  270. msg = cls(
  271. command=b'AUTH', arg0=AUTH_SIGNATURE, arg1=0, data=signed_token)
  272. msg.Send(usb)
  273. cmd, arg0, unused_arg1, banner = cls.Read(usb, [b'CNXN', b'AUTH'])
  274. if cmd == b'CNXN':
  275. return banner
  276. # None of the keys worked, so send a public key.
  277. msg = cls(
  278. command=b'AUTH', arg0=AUTH_RSAPUBLICKEY, arg1=0,
  279. data=rsa_keys[0].GetPublicKey() + b'\0')
  280. msg.Send(usb)
  281. try:
  282. cmd, arg0, unused_arg1, banner = cls.Read(
  283. usb, [b'CNXN'], timeout_ms=auth_timeout_ms)
  284. except usb_exceptions.ReadFailedError as e:
  285. if e.usb_error.value == -7: # Timeout.
  286. raise usb_exceptions.DeviceAuthError(
  287. 'Accept auth key on device, then retry.')
  288. raise
  289. # This didn't time-out, so we got a CNXN response.
  290. return banner
  291. return banner
  292. @classmethod
  293. def Open(cls, usb, destination, timeout_ms=None):
  294. """Opens a new connection to the device via an OPEN message.
  295. Not the same as the posix 'open' or any other google3 Open methods.
  296. Args:
  297. usb: USB device handle with BulkRead and BulkWrite methods.
  298. destination: The service:command string.
  299. timeout_ms: Timeout in milliseconds for USB packets.
  300. Raises:
  301. InvalidResponseError: Wrong local_id sent to us.
  302. InvalidCommandError: Didn't get a ready response.
  303. Returns:
  304. The local connection id.
  305. """
  306. local_id = 1
  307. msg = cls(
  308. command=b'OPEN', arg0=local_id, arg1=0,
  309. data=destination + b'\0')
  310. msg.Send(usb, timeout_ms)
  311. cmd, remote_id, their_local_id, _ = cls.Read(usb, [b'CLSE', b'OKAY'],
  312. timeout_ms=timeout_ms)
  313. if local_id != their_local_id:
  314. raise InvalidResponseError(
  315. 'Expected the local_id to be {}, got {}'.format(local_id, their_local_id))
  316. if cmd == b'CLSE':
  317. # Some devices seem to be sending CLSE once more after a request, this *should* handle it
  318. cmd, remote_id, their_local_id, _ = cls.Read(usb, [b'CLSE', b'OKAY'],
  319. timeout_ms=timeout_ms)
  320. # Device doesn't support this service.
  321. if cmd == b'CLSE':
  322. return None
  323. if cmd != b'OKAY':
  324. raise InvalidCommandError('Expected a ready response, got {}'.format(cmd),
  325. cmd, (remote_id, their_local_id))
  326. return _AdbConnection(usb, local_id, remote_id, timeout_ms)
  327. @classmethod
  328. def Command(cls, usb, service, command='', timeout_ms=None):
  329. """One complete set of USB packets for a single command.
  330. Sends service:command in a new connection, reading the data for the
  331. response. All the data is held in memory, large responses will be slow and
  332. can fill up memory.
  333. Args:
  334. usb: USB device handle with BulkRead and BulkWrite methods.
  335. service: The service on the device to talk to.
  336. command: The command to send to the service.
  337. timeout_ms: Timeout for USB packets, in milliseconds.
  338. Raises:
  339. InterleavedDataError: Multiple streams running over usb.
  340. InvalidCommandError: Got an unexpected response command.
  341. Returns:
  342. The response from the service.
  343. """
  344. return ''.join(cls.StreamingCommand(usb, service, command, timeout_ms))
  345. @classmethod
  346. def StreamingCommand(cls, usb, service, command='', timeout_ms=None):
  347. """One complete set of USB packets for a single command.
  348. Sends service:command in a new connection, reading the data for the
  349. response. All the data is held in memory, large responses will be slow and
  350. can fill up memory.
  351. Args:
  352. usb: USB device handle with BulkRead and BulkWrite methods.
  353. service: The service on the device to talk to.
  354. command: The command to send to the service.
  355. timeout_ms: Timeout for USB packets, in milliseconds.
  356. Raises:
  357. InterleavedDataError: Multiple streams running over usb.
  358. InvalidCommandError: Got an unexpected response command.
  359. Yields:
  360. The responses from the service.
  361. """
  362. if not isinstance(command, bytes):
  363. command = command.encode('utf8')
  364. connection = cls.Open(
  365. usb, destination=b'%s:%s' % (service, command),
  366. timeout_ms=timeout_ms)
  367. for data in connection.ReadUntilClose():
  368. yield data.decode('utf8')
  369. @classmethod
  370. def InteractiveShellCommand(cls, conn, cmd=None, strip_cmd=True, delim=None, strip_delim=True, clean_stdout=True):
  371. """Retrieves stdout of the current InteractiveShell and sends a shell command if provided
  372. TODO: Should we turn this into a yield based function so we can stream all output?
  373. Args:
  374. conn: Instance of AdbConnection
  375. cmd: Optional. Command to run on the target.
  376. strip_cmd: Optional (default True). Strip command name from stdout.
  377. delim: Optional. Delimiter to look for in the output to know when to stop expecting more output
  378. (usually the shell prompt)
  379. strip_delim: Optional (default True): Strip the provided delimiter from the output
  380. clean_stdout: Cleanup the stdout stream of any backspaces and the characters that were deleted by the backspace
  381. Returns:
  382. The stdout from the shell command.
  383. """
  384. if delim is not None and not isinstance(delim, bytes):
  385. delim = delim.encode('utf-8')
  386. # Delimiter may be shell@hammerhead:/ $
  387. # The user or directory could change, making the delimiter somthing like root@hammerhead:/data/local/tmp $
  388. # Handle a partial delimiter to search on and clean up
  389. if delim:
  390. user_pos = delim.find(b'@')
  391. dir_pos = delim.rfind(b':/')
  392. if user_pos != -1 and dir_pos != -1:
  393. partial_delim = delim[user_pos:dir_pos + 1] # e.g. @hammerhead:
  394. else:
  395. partial_delim = delim
  396. else:
  397. partial_delim = None
  398. stdout = ''
  399. stdout_stream = BytesIO()
  400. original_cmd = ''
  401. try:
  402. if cmd:
  403. original_cmd = str(cmd)
  404. cmd += '\r' # Required. Send a carriage return right after the cmd
  405. cmd = cmd.encode('utf8')
  406. # Send the cmd raw
  407. bytes_written = conn.Write(cmd)
  408. if delim:
  409. # Expect multiple WRTE cmds until the delim (usually terminal prompt) is detected
  410. data = b''
  411. while partial_delim not in data:
  412. cmd, data = conn.ReadUntil(b'WRTE')
  413. stdout_stream.write(data)
  414. else:
  415. # Otherwise, expect only a single WRTE
  416. cmd, data = conn.ReadUntil(b'WRTE')
  417. # WRTE cmd from device will follow with stdout data
  418. stdout_stream.write(data)
  419. else:
  420. # No cmd provided means we should just expect a single line from the terminal. Use this sparingly
  421. cmd, data = conn.ReadUntil(b'WRTE')
  422. if cmd == b'WRTE':
  423. # WRTE cmd from device will follow with stdout data
  424. stdout_stream.write(data)
  425. else:
  426. print("Unhandled cmd: {}".format(cmd))
  427. cleaned_stdout_stream = BytesIO()
  428. if clean_stdout:
  429. stdout_bytes = stdout_stream.getvalue()
  430. bsruns = {} # Backspace runs tracking
  431. next_start_pos = 0
  432. last_run_pos, last_run_len = find_backspace_runs(stdout_bytes, next_start_pos)
  433. if last_run_pos != -1 and last_run_len != 0:
  434. bsruns.update({last_run_pos: last_run_len})
  435. cleaned_stdout_stream.write(stdout_bytes[next_start_pos:(last_run_pos - last_run_len)])
  436. next_start_pos += last_run_pos + last_run_len
  437. while last_run_pos != -1:
  438. last_run_pos, last_run_len = find_backspace_runs(stdout_bytes[next_start_pos:], next_start_pos)
  439. if last_run_pos != -1:
  440. bsruns.update({last_run_pos: last_run_len})
  441. cleaned_stdout_stream.write(stdout_bytes[next_start_pos:(last_run_pos - last_run_len)])
  442. next_start_pos += last_run_pos + last_run_len
  443. cleaned_stdout_stream.write(stdout_bytes[next_start_pos:])
  444. else:
  445. cleaned_stdout_stream.write(stdout_stream.getvalue())
  446. stdout = cleaned_stdout_stream.getvalue()
  447. # Strip original cmd that will come back in stdout
  448. if original_cmd and strip_cmd:
  449. findstr = original_cmd.encode('utf-8') + b'\r\r\n'
  450. pos = stdout.find(findstr)
  451. while pos >= 0:
  452. stdout = stdout.replace(findstr, b'')
  453. pos = stdout.find(findstr)
  454. if b'\r\r\n' in stdout:
  455. stdout = stdout.split(b'\r\r\n')[1]
  456. # Strip delim if requested
  457. # TODO: Handling stripping partial delims here - not a deal breaker the way we're handling it now
  458. if delim and strip_delim:
  459. stdout = stdout.replace(delim, b'')
  460. stdout = stdout.rstrip()
  461. except Exception as e:
  462. print("InteractiveShell exception (most likely timeout): {}".format(e))
  463. return stdout