update_device.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. #!/usr/bin/python2
  2. #
  3. # Copyright (C) 2017 The Android Open Source Project
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. """Send an A/B update to an Android device over adb."""
  18. import argparse
  19. import BaseHTTPServer
  20. import hashlib
  21. import logging
  22. import os
  23. import socket
  24. import subprocess
  25. import sys
  26. import threading
  27. import xml.etree.ElementTree
  28. import zipfile
  29. import update_payload.payload
  30. # The path used to store the OTA package when applying the package from a file.
  31. OTA_PACKAGE_PATH = '/data/ota_package'
  32. # The path to the payload public key on the device.
  33. PAYLOAD_KEY_PATH = '/etc/update_engine/update-payload-key.pub.pem'
  34. # The port on the device that update_engine should connect to.
  35. DEVICE_PORT = 1234
  36. def CopyFileObjLength(fsrc, fdst, buffer_size=128 * 1024, copy_length=None):
  37. """Copy from a file object to another.
  38. This function is similar to shutil.copyfileobj except that it allows to copy
  39. less than the full source file.
  40. Args:
  41. fsrc: source file object where to read from.
  42. fdst: destination file object where to write to.
  43. buffer_size: size of the copy buffer in memory.
  44. copy_length: maximum number of bytes to copy, or None to copy everything.
  45. Returns:
  46. the number of bytes copied.
  47. """
  48. copied = 0
  49. while True:
  50. chunk_size = buffer_size
  51. if copy_length is not None:
  52. chunk_size = min(chunk_size, copy_length - copied)
  53. if not chunk_size:
  54. break
  55. buf = fsrc.read(chunk_size)
  56. if not buf:
  57. break
  58. fdst.write(buf)
  59. copied += len(buf)
  60. return copied
  61. class AndroidOTAPackage(object):
  62. """Android update payload using the .zip format.
  63. Android OTA packages traditionally used a .zip file to store the payload. When
  64. applying A/B updates over the network, a payload binary is stored RAW inside
  65. this .zip file which is used by update_engine to apply the payload. To do
  66. this, an offset and size inside the .zip file are provided.
  67. """
  68. # Android OTA package file paths.
  69. OTA_PAYLOAD_BIN = 'payload.bin'
  70. OTA_PAYLOAD_PROPERTIES_TXT = 'payload_properties.txt'
  71. def __init__(self, otafilename):
  72. self.otafilename = otafilename
  73. otazip = zipfile.ZipFile(otafilename, 'r')
  74. payload_info = otazip.getinfo(self.OTA_PAYLOAD_BIN)
  75. self.offset = payload_info.header_offset
  76. self.offset += zipfile.sizeFileHeader
  77. self.offset += len(payload_info.extra) + len(payload_info.filename)
  78. self.size = payload_info.file_size
  79. self.properties = otazip.read(self.OTA_PAYLOAD_PROPERTIES_TXT)
  80. class UpdateHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  81. """A HTTPServer that supports single-range requests.
  82. Attributes:
  83. serving_payload: path to the only payload file we are serving.
  84. serving_range: the start offset and size tuple of the payload.
  85. """
  86. @staticmethod
  87. def _parse_range(range_str, file_size):
  88. """Parse an HTTP range string.
  89. Args:
  90. range_str: HTTP Range header in the request, not including "Header:".
  91. file_size: total size of the serving file.
  92. Returns:
  93. A tuple (start_range, end_range) with the range of bytes requested.
  94. """
  95. start_range = 0
  96. end_range = file_size
  97. if range_str:
  98. range_str = range_str.split('=', 1)[1]
  99. s, e = range_str.split('-', 1)
  100. if s:
  101. start_range = int(s)
  102. if e:
  103. end_range = int(e) + 1
  104. elif e:
  105. if int(e) < file_size:
  106. start_range = file_size - int(e)
  107. return start_range, end_range
  108. def do_GET(self): # pylint: disable=invalid-name
  109. """Reply with the requested payload file."""
  110. if self.path != '/payload':
  111. self.send_error(404, 'Unknown request')
  112. return
  113. if not self.serving_payload:
  114. self.send_error(500, 'No serving payload set')
  115. return
  116. try:
  117. f = open(self.serving_payload, 'rb')
  118. except IOError:
  119. self.send_error(404, 'File not found')
  120. return
  121. # Handle the range request.
  122. if 'Range' in self.headers:
  123. self.send_response(206)
  124. else:
  125. self.send_response(200)
  126. serving_start, serving_size = self.serving_range
  127. start_range, end_range = self._parse_range(self.headers.get('range'),
  128. serving_size)
  129. logging.info('Serving request for %s from %s [%d, %d) length: %d',
  130. self.path, self.serving_payload, serving_start + start_range,
  131. serving_start + end_range, end_range - start_range)
  132. self.send_header('Accept-Ranges', 'bytes')
  133. self.send_header('Content-Range',
  134. 'bytes ' + str(start_range) + '-' + str(end_range - 1) +
  135. '/' + str(end_range - start_range))
  136. self.send_header('Content-Length', end_range - start_range)
  137. stat = os.fstat(f.fileno())
  138. self.send_header('Last-Modified', self.date_time_string(stat.st_mtime))
  139. self.send_header('Content-type', 'application/octet-stream')
  140. self.end_headers()
  141. f.seek(serving_start + start_range)
  142. CopyFileObjLength(f, self.wfile, copy_length=end_range - start_range)
  143. def do_POST(self): # pylint: disable=invalid-name
  144. """Reply with the omaha response xml."""
  145. if self.path != '/update':
  146. self.send_error(404, 'Unknown request')
  147. return
  148. if not self.serving_payload:
  149. self.send_error(500, 'No serving payload set')
  150. return
  151. try:
  152. f = open(self.serving_payload, 'rb')
  153. except IOError:
  154. self.send_error(404, 'File not found')
  155. return
  156. content_length = int(self.headers.getheader('Content-Length'))
  157. request_xml = self.rfile.read(content_length)
  158. xml_root = xml.etree.ElementTree.fromstring(request_xml)
  159. appid = None
  160. for app in xml_root.iter('app'):
  161. if 'appid' in app.attrib:
  162. appid = app.attrib['appid']
  163. break
  164. if not appid:
  165. self.send_error(400, 'No appid in Omaha request')
  166. return
  167. self.send_response(200)
  168. self.send_header("Content-type", "text/xml")
  169. self.end_headers()
  170. serving_start, serving_size = self.serving_range
  171. sha256 = hashlib.sha256()
  172. f.seek(serving_start)
  173. bytes_to_hash = serving_size
  174. while bytes_to_hash:
  175. buf = f.read(min(bytes_to_hash, 1024 * 1024))
  176. if not buf:
  177. self.send_error(500, 'Payload too small')
  178. return
  179. sha256.update(buf)
  180. bytes_to_hash -= len(buf)
  181. payload = update_payload.Payload(f, payload_file_offset=serving_start)
  182. payload.Init()
  183. response_xml = '''
  184. <?xml version="1.0" encoding="UTF-8"?>
  185. <response protocol="3.0">
  186. <app appid="{appid}">
  187. <updatecheck status="ok">
  188. <urls>
  189. <url codebase="http://127.0.0.1:{port}/"/>
  190. </urls>
  191. <manifest version="0.0.0.1">
  192. <actions>
  193. <action event="install" run="payload"/>
  194. <action event="postinstall" MetadataSize="{metadata_size}"/>
  195. </actions>
  196. <packages>
  197. <package hash_sha256="{payload_hash}" name="payload" size="{payload_size}"/>
  198. </packages>
  199. </manifest>
  200. </updatecheck>
  201. </app>
  202. </response>
  203. '''.format(appid=appid, port=DEVICE_PORT,
  204. metadata_size=payload.metadata_size,
  205. payload_hash=sha256.hexdigest(),
  206. payload_size=serving_size)
  207. self.wfile.write(response_xml.strip())
  208. return
  209. class ServerThread(threading.Thread):
  210. """A thread for serving HTTP requests."""
  211. def __init__(self, ota_filename, serving_range):
  212. threading.Thread.__init__(self)
  213. # serving_payload and serving_range are class attributes and the
  214. # UpdateHandler class is instantiated with every request.
  215. UpdateHandler.serving_payload = ota_filename
  216. UpdateHandler.serving_range = serving_range
  217. self._httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 0), UpdateHandler)
  218. self.port = self._httpd.server_port
  219. def run(self):
  220. try:
  221. self._httpd.serve_forever()
  222. except (KeyboardInterrupt, socket.error):
  223. pass
  224. logging.info('Server Terminated')
  225. def StopServer(self):
  226. self._httpd.socket.close()
  227. def StartServer(ota_filename, serving_range):
  228. t = ServerThread(ota_filename, serving_range)
  229. t.start()
  230. return t
  231. def AndroidUpdateCommand(ota_filename, payload_url, extra_headers):
  232. """Return the command to run to start the update in the Android device."""
  233. ota = AndroidOTAPackage(ota_filename)
  234. headers = ota.properties
  235. headers += 'USER_AGENT=Dalvik (something, something)\n'
  236. headers += 'NETWORK_ID=0\n'
  237. headers += extra_headers
  238. return ['update_engine_client', '--update', '--follow',
  239. '--payload=%s' % payload_url, '--offset=%d' % ota.offset,
  240. '--size=%d' % ota.size, '--headers="%s"' % headers]
  241. def OmahaUpdateCommand(omaha_url):
  242. """Return the command to run to start the update in a device using Omaha."""
  243. return ['update_engine_client', '--update', '--follow',
  244. '--omaha_url=%s' % omaha_url]
  245. class AdbHost(object):
  246. """Represents a device connected via ADB."""
  247. def __init__(self, device_serial=None):
  248. """Construct an instance.
  249. Args:
  250. device_serial: options string serial number of attached device.
  251. """
  252. self._device_serial = device_serial
  253. self._command_prefix = ['adb']
  254. if self._device_serial:
  255. self._command_prefix += ['-s', self._device_serial]
  256. def adb(self, command):
  257. """Run an ADB command like "adb push".
  258. Args:
  259. command: list of strings containing command and arguments to run
  260. Returns:
  261. the program's return code.
  262. Raises:
  263. subprocess.CalledProcessError on command exit != 0.
  264. """
  265. command = self._command_prefix + command
  266. logging.info('Running: %s', ' '.join(str(x) for x in command))
  267. p = subprocess.Popen(command, universal_newlines=True)
  268. p.wait()
  269. return p.returncode
  270. def adb_output(self, command):
  271. """Run an ADB command like "adb push" and return the output.
  272. Args:
  273. command: list of strings containing command and arguments to run
  274. Returns:
  275. the program's output as a string.
  276. Raises:
  277. subprocess.CalledProcessError on command exit != 0.
  278. """
  279. command = self._command_prefix + command
  280. logging.info('Running: %s', ' '.join(str(x) for x in command))
  281. return subprocess.check_output(command, universal_newlines=True)
  282. def main():
  283. parser = argparse.ArgumentParser(description='Android A/B OTA helper.')
  284. parser.add_argument('otafile', metavar='PAYLOAD', type=str,
  285. help='the OTA package file (a .zip file) or raw payload \
  286. if device uses Omaha.')
  287. parser.add_argument('--file', action='store_true',
  288. help='Push the file to the device before updating.')
  289. parser.add_argument('--no-push', action='store_true',
  290. help='Skip the "push" command when using --file')
  291. parser.add_argument('-s', type=str, default='', metavar='DEVICE',
  292. help='The specific device to use.')
  293. parser.add_argument('--no-verbose', action='store_true',
  294. help='Less verbose output')
  295. parser.add_argument('--public-key', type=str, default='',
  296. help='Override the public key used to verify payload.')
  297. parser.add_argument('--extra-headers', type=str, default='',
  298. help='Extra headers to pass to the device.')
  299. args = parser.parse_args()
  300. logging.basicConfig(
  301. level=logging.WARNING if args.no_verbose else logging.INFO)
  302. dut = AdbHost(args.s)
  303. server_thread = None
  304. # List of commands to execute on exit.
  305. finalize_cmds = []
  306. # Commands to execute when canceling an update.
  307. cancel_cmd = ['shell', 'su', '0', 'update_engine_client', '--cancel']
  308. # List of commands to perform the update.
  309. cmds = []
  310. help_cmd = ['shell', 'su', '0', 'update_engine_client', '--help']
  311. use_omaha = 'omaha' in dut.adb_output(help_cmd)
  312. if args.file:
  313. # Update via pushing a file to /data.
  314. device_ota_file = os.path.join(OTA_PACKAGE_PATH, 'debug.zip')
  315. payload_url = 'file://' + device_ota_file
  316. if not args.no_push:
  317. data_local_tmp_file = '/data/local/tmp/debug.zip'
  318. cmds.append(['push', args.otafile, data_local_tmp_file])
  319. cmds.append(['shell', 'su', '0', 'mv', data_local_tmp_file,
  320. device_ota_file])
  321. cmds.append(['shell', 'su', '0', 'chcon',
  322. 'u:object_r:ota_package_file:s0', device_ota_file])
  323. cmds.append(['shell', 'su', '0', 'chown', 'system:cache', device_ota_file])
  324. cmds.append(['shell', 'su', '0', 'chmod', '0660', device_ota_file])
  325. else:
  326. # Update via sending the payload over the network with an "adb reverse"
  327. # command.
  328. payload_url = 'http://127.0.0.1:%d/payload' % DEVICE_PORT
  329. if use_omaha and zipfile.is_zipfile(args.otafile):
  330. ota = AndroidOTAPackage(args.otafile)
  331. serving_range = (ota.offset, ota.size)
  332. else:
  333. serving_range = (0, os.stat(args.otafile).st_size)
  334. server_thread = StartServer(args.otafile, serving_range)
  335. cmds.append(
  336. ['reverse', 'tcp:%d' % DEVICE_PORT, 'tcp:%d' % server_thread.port])
  337. finalize_cmds.append(['reverse', '--remove', 'tcp:%d' % DEVICE_PORT])
  338. if args.public_key:
  339. payload_key_dir = os.path.dirname(PAYLOAD_KEY_PATH)
  340. cmds.append(
  341. ['shell', 'su', '0', 'mount', '-t', 'tmpfs', 'tmpfs', payload_key_dir])
  342. # Allow adb push to payload_key_dir
  343. cmds.append(['shell', 'su', '0', 'chcon', 'u:object_r:shell_data_file:s0',
  344. payload_key_dir])
  345. cmds.append(['push', args.public_key, PAYLOAD_KEY_PATH])
  346. # Allow update_engine to read it.
  347. cmds.append(['shell', 'su', '0', 'chcon', '-R', 'u:object_r:system_file:s0',
  348. payload_key_dir])
  349. finalize_cmds.append(['shell', 'su', '0', 'umount', payload_key_dir])
  350. try:
  351. # The main update command using the configured payload_url.
  352. if use_omaha:
  353. update_cmd = \
  354. OmahaUpdateCommand('http://127.0.0.1:%d/update' % DEVICE_PORT)
  355. else:
  356. update_cmd = \
  357. AndroidUpdateCommand(args.otafile, payload_url, args.extra_headers)
  358. cmds.append(['shell', 'su', '0'] + update_cmd)
  359. for cmd in cmds:
  360. dut.adb(cmd)
  361. except KeyboardInterrupt:
  362. dut.adb(cancel_cmd)
  363. finally:
  364. if server_thread:
  365. server_thread.StopServer()
  366. for cmd in finalize_cmds:
  367. dut.adb(cmd)
  368. return 0
  369. if __name__ == '__main__':
  370. sys.exit(main())