blob: 49f766da85e3c9ec7e3b902344f3a1044aaaf128 [file] [log] [blame]
markdr5c9082d2017-10-20 13:58:06 -07001#!/usr/bin/python2
Alex Deymo6751bbe2017-03-21 11:20:02 -07002#
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
18"""Send an A/B update to an Android device over adb."""
19
20import argparse
21import BaseHTTPServer
Sen Jiang3b15b592017-09-26 18:21:04 -070022import hashlib
Alex Deymo6751bbe2017-03-21 11:20:02 -070023import logging
24import os
25import socket
26import subprocess
27import sys
28import threading
Sen Jiang144f9f82017-09-26 15:49:45 -070029import xml.etree.ElementTree
Alex Deymo6751bbe2017-03-21 11:20:02 -070030import zipfile
31
Sen Jianga1784b72017-08-09 17:42:36 -070032import update_payload.payload
33
Alex Deymo6751bbe2017-03-21 11:20:02 -070034
35# The path used to store the OTA package when applying the package from a file.
36OTA_PACKAGE_PATH = '/data/ota_package'
37
Sen Jianga1784b72017-08-09 17:42:36 -070038# The path to the payload public key on the device.
39PAYLOAD_KEY_PATH = '/etc/update_engine/update-payload-key.pub.pem'
40
41# The port on the device that update_engine should connect to.
42DEVICE_PORT = 1234
Alex Deymo6751bbe2017-03-21 11:20:02 -070043
44def CopyFileObjLength(fsrc, fdst, buffer_size=128 * 1024, copy_length=None):
45 """Copy from a file object to another.
46
47 This function is similar to shutil.copyfileobj except that it allows to copy
48 less than the full source file.
49
50 Args:
51 fsrc: source file object where to read from.
52 fdst: destination file object where to write to.
53 buffer_size: size of the copy buffer in memory.
54 copy_length: maximum number of bytes to copy, or None to copy everything.
55
56 Returns:
57 the number of bytes copied.
58 """
59 copied = 0
60 while True:
61 chunk_size = buffer_size
62 if copy_length is not None:
63 chunk_size = min(chunk_size, copy_length - copied)
64 if not chunk_size:
65 break
66 buf = fsrc.read(chunk_size)
67 if not buf:
68 break
69 fdst.write(buf)
70 copied += len(buf)
71 return copied
72
73
74class AndroidOTAPackage(object):
75 """Android update payload using the .zip format.
76
77 Android OTA packages traditionally used a .zip file to store the payload. When
78 applying A/B updates over the network, a payload binary is stored RAW inside
79 this .zip file which is used by update_engine to apply the payload. To do
80 this, an offset and size inside the .zip file are provided.
81 """
82
83 # Android OTA package file paths.
84 OTA_PAYLOAD_BIN = 'payload.bin'
85 OTA_PAYLOAD_PROPERTIES_TXT = 'payload_properties.txt'
Tianjie Xu3f9be772019-11-02 18:31:50 -070086 SECONDARY_OTA_PAYLOAD_BIN = 'secondary/payload.bin'
87 SECONDARY_OTA_PAYLOAD_PROPERTIES_TXT = 'secondary/payload_properties.txt'
Alex Deymo6751bbe2017-03-21 11:20:02 -070088
Tianjie Xu3f9be772019-11-02 18:31:50 -070089 def __init__(self, otafilename, secondary_payload=False):
Alex Deymo6751bbe2017-03-21 11:20:02 -070090 self.otafilename = otafilename
91
92 otazip = zipfile.ZipFile(otafilename, 'r')
Tianjie Xu3f9be772019-11-02 18:31:50 -070093 payload_entry = (self.SECONDARY_OTA_PAYLOAD_BIN if secondary_payload else
94 self.OTA_PAYLOAD_BIN)
95 payload_info = otazip.getinfo(payload_entry)
Shashikant Baviskarb1a9e082018-04-12 12:37:21 +090096 self.offset = payload_info.header_offset
97 self.offset += zipfile.sizeFileHeader
98 self.offset += len(payload_info.extra) + len(payload_info.filename)
Alex Deymo6751bbe2017-03-21 11:20:02 -070099 self.size = payload_info.file_size
Tianjie Xu3f9be772019-11-02 18:31:50 -0700100
101 property_entry = (self.SECONDARY_OTA_PAYLOAD_PROPERTIES_TXT if
102 secondary_payload else self.OTA_PAYLOAD_PROPERTIES_TXT)
103 self.properties = otazip.read(property_entry)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700104
105
106class UpdateHandler(BaseHTTPServer.BaseHTTPRequestHandler):
107 """A HTTPServer that supports single-range requests.
108
109 Attributes:
110 serving_payload: path to the only payload file we are serving.
Sen Jiang3b15b592017-09-26 18:21:04 -0700111 serving_range: the start offset and size tuple of the payload.
Alex Deymo6751bbe2017-03-21 11:20:02 -0700112 """
113
114 @staticmethod
Sen Jiang10485592017-08-15 18:20:24 -0700115 def _parse_range(range_str, file_size):
Alex Deymo6751bbe2017-03-21 11:20:02 -0700116 """Parse an HTTP range string.
117
118 Args:
119 range_str: HTTP Range header in the request, not including "Header:".
120 file_size: total size of the serving file.
121
122 Returns:
123 A tuple (start_range, end_range) with the range of bytes requested.
124 """
125 start_range = 0
126 end_range = file_size
127
128 if range_str:
129 range_str = range_str.split('=', 1)[1]
130 s, e = range_str.split('-', 1)
131 if s:
132 start_range = int(s)
133 if e:
134 end_range = int(e) + 1
135 elif e:
136 if int(e) < file_size:
137 start_range = file_size - int(e)
138 return start_range, end_range
139
140
141 def do_GET(self): # pylint: disable=invalid-name
142 """Reply with the requested payload file."""
143 if self.path != '/payload':
144 self.send_error(404, 'Unknown request')
145 return
146
147 if not self.serving_payload:
148 self.send_error(500, 'No serving payload set')
149 return
150
151 try:
152 f = open(self.serving_payload, 'rb')
153 except IOError:
154 self.send_error(404, 'File not found')
155 return
156 # Handle the range request.
157 if 'Range' in self.headers:
158 self.send_response(206)
159 else:
160 self.send_response(200)
161
Sen Jiang3b15b592017-09-26 18:21:04 -0700162 serving_start, serving_size = self.serving_range
Sen Jiang10485592017-08-15 18:20:24 -0700163 start_range, end_range = self._parse_range(self.headers.get('range'),
Sen Jiang3b15b592017-09-26 18:21:04 -0700164 serving_size)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700165 logging.info('Serving request for %s from %s [%d, %d) length: %d',
Sen Jiang3b15b592017-09-26 18:21:04 -0700166 self.path, self.serving_payload, serving_start + start_range,
167 serving_start + end_range, end_range - start_range)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700168
169 self.send_header('Accept-Ranges', 'bytes')
170 self.send_header('Content-Range',
171 'bytes ' + str(start_range) + '-' + str(end_range - 1) +
172 '/' + str(end_range - start_range))
173 self.send_header('Content-Length', end_range - start_range)
174
Sen Jiang3b15b592017-09-26 18:21:04 -0700175 stat = os.fstat(f.fileno())
Alex Deymo6751bbe2017-03-21 11:20:02 -0700176 self.send_header('Last-Modified', self.date_time_string(stat.st_mtime))
177 self.send_header('Content-type', 'application/octet-stream')
178 self.end_headers()
179
Sen Jiang3b15b592017-09-26 18:21:04 -0700180 f.seek(serving_start + start_range)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700181 CopyFileObjLength(f, self.wfile, copy_length=end_range - start_range)
182
183
Sen Jianga1784b72017-08-09 17:42:36 -0700184 def do_POST(self): # pylint: disable=invalid-name
185 """Reply with the omaha response xml."""
186 if self.path != '/update':
187 self.send_error(404, 'Unknown request')
188 return
189
190 if not self.serving_payload:
191 self.send_error(500, 'No serving payload set')
192 return
193
194 try:
195 f = open(self.serving_payload, 'rb')
196 except IOError:
197 self.send_error(404, 'File not found')
198 return
199
Sen Jiang144f9f82017-09-26 15:49:45 -0700200 content_length = int(self.headers.getheader('Content-Length'))
201 request_xml = self.rfile.read(content_length)
202 xml_root = xml.etree.ElementTree.fromstring(request_xml)
203 appid = None
204 for app in xml_root.iter('app'):
205 if 'appid' in app.attrib:
206 appid = app.attrib['appid']
207 break
208 if not appid:
209 self.send_error(400, 'No appid in Omaha request')
210 return
211
Sen Jianga1784b72017-08-09 17:42:36 -0700212 self.send_response(200)
213 self.send_header("Content-type", "text/xml")
214 self.end_headers()
215
Sen Jiang3b15b592017-09-26 18:21:04 -0700216 serving_start, serving_size = self.serving_range
217 sha256 = hashlib.sha256()
218 f.seek(serving_start)
219 bytes_to_hash = serving_size
220 while bytes_to_hash:
221 buf = f.read(min(bytes_to_hash, 1024 * 1024))
222 if not buf:
223 self.send_error(500, 'Payload too small')
224 return
225 sha256.update(buf)
226 bytes_to_hash -= len(buf)
227
228 payload = update_payload.Payload(f, payload_file_offset=serving_start)
Sen Jianga1784b72017-08-09 17:42:36 -0700229 payload.Init()
230
Sen Jiang144f9f82017-09-26 15:49:45 -0700231 response_xml = '''
Sen Jianga1784b72017-08-09 17:42:36 -0700232 <?xml version="1.0" encoding="UTF-8"?>
233 <response protocol="3.0">
Sen Jiang144f9f82017-09-26 15:49:45 -0700234 <app appid="{appid}">
Sen Jianga1784b72017-08-09 17:42:36 -0700235 <updatecheck status="ok">
236 <urls>
Sen Jiang144f9f82017-09-26 15:49:45 -0700237 <url codebase="http://127.0.0.1:{port}/"/>
Sen Jianga1784b72017-08-09 17:42:36 -0700238 </urls>
239 <manifest version="0.0.0.1">
240 <actions>
241 <action event="install" run="payload"/>
Sen Jiang144f9f82017-09-26 15:49:45 -0700242 <action event="postinstall" MetadataSize="{metadata_size}"/>
Sen Jianga1784b72017-08-09 17:42:36 -0700243 </actions>
244 <packages>
Sen Jiang144f9f82017-09-26 15:49:45 -0700245 <package hash_sha256="{payload_hash}" name="payload" size="{payload_size}"/>
Sen Jianga1784b72017-08-09 17:42:36 -0700246 </packages>
247 </manifest>
248 </updatecheck>
249 </app>
250 </response>
Sen Jiang144f9f82017-09-26 15:49:45 -0700251 '''.format(appid=appid, port=DEVICE_PORT,
Sen Jiang3b15b592017-09-26 18:21:04 -0700252 metadata_size=payload.metadata_size,
253 payload_hash=sha256.hexdigest(),
254 payload_size=serving_size)
Sen Jiang144f9f82017-09-26 15:49:45 -0700255 self.wfile.write(response_xml.strip())
Sen Jianga1784b72017-08-09 17:42:36 -0700256 return
257
258
Alex Deymo6751bbe2017-03-21 11:20:02 -0700259class ServerThread(threading.Thread):
260 """A thread for serving HTTP requests."""
261
Sen Jiang3b15b592017-09-26 18:21:04 -0700262 def __init__(self, ota_filename, serving_range):
Alex Deymo6751bbe2017-03-21 11:20:02 -0700263 threading.Thread.__init__(self)
Sen Jiang3b15b592017-09-26 18:21:04 -0700264 # serving_payload and serving_range are class attributes and the
265 # UpdateHandler class is instantiated with every request.
Alex Deymo6751bbe2017-03-21 11:20:02 -0700266 UpdateHandler.serving_payload = ota_filename
Sen Jiang3b15b592017-09-26 18:21:04 -0700267 UpdateHandler.serving_range = serving_range
Alex Deymo6751bbe2017-03-21 11:20:02 -0700268 self._httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 0), UpdateHandler)
269 self.port = self._httpd.server_port
270
271 def run(self):
272 try:
273 self._httpd.serve_forever()
274 except (KeyboardInterrupt, socket.error):
275 pass
276 logging.info('Server Terminated')
277
278 def StopServer(self):
279 self._httpd.socket.close()
280
281
Sen Jiang3b15b592017-09-26 18:21:04 -0700282def StartServer(ota_filename, serving_range):
283 t = ServerThread(ota_filename, serving_range)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700284 t.start()
285 return t
286
287
Tianjie Xu3f9be772019-11-02 18:31:50 -0700288def AndroidUpdateCommand(ota_filename, secondary, payload_url, extra_headers):
Alex Deymo6751bbe2017-03-21 11:20:02 -0700289 """Return the command to run to start the update in the Android device."""
Tianjie Xu3f9be772019-11-02 18:31:50 -0700290 ota = AndroidOTAPackage(ota_filename, secondary)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700291 headers = ota.properties
292 headers += 'USER_AGENT=Dalvik (something, something)\n'
Alex Deymo6751bbe2017-03-21 11:20:02 -0700293 headers += 'NETWORK_ID=0\n'
Sen Jiang6fbfd7d2017-10-31 16:16:56 -0700294 headers += extra_headers
Alex Deymo6751bbe2017-03-21 11:20:02 -0700295
296 return ['update_engine_client', '--update', '--follow',
297 '--payload=%s' % payload_url, '--offset=%d' % ota.offset,
298 '--size=%d' % ota.size, '--headers="%s"' % headers]
299
300
Sen Jianga1784b72017-08-09 17:42:36 -0700301def OmahaUpdateCommand(omaha_url):
302 """Return the command to run to start the update in a device using Omaha."""
303 return ['update_engine_client', '--update', '--follow',
304 '--omaha_url=%s' % omaha_url]
305
306
Alex Deymo6751bbe2017-03-21 11:20:02 -0700307class AdbHost(object):
308 """Represents a device connected via ADB."""
309
310 def __init__(self, device_serial=None):
311 """Construct an instance.
312
313 Args:
314 device_serial: options string serial number of attached device.
315 """
316 self._device_serial = device_serial
317 self._command_prefix = ['adb']
318 if self._device_serial:
319 self._command_prefix += ['-s', self._device_serial]
320
321 def adb(self, command):
322 """Run an ADB command like "adb push".
323
324 Args:
325 command: list of strings containing command and arguments to run
326
327 Returns:
328 the program's return code.
329
330 Raises:
331 subprocess.CalledProcessError on command exit != 0.
332 """
333 command = self._command_prefix + command
334 logging.info('Running: %s', ' '.join(str(x) for x in command))
335 p = subprocess.Popen(command, universal_newlines=True)
336 p.wait()
337 return p.returncode
338
Sen Jianga1784b72017-08-09 17:42:36 -0700339 def adb_output(self, command):
340 """Run an ADB command like "adb push" and return the output.
341
342 Args:
343 command: list of strings containing command and arguments to run
344
345 Returns:
346 the program's output as a string.
347
348 Raises:
349 subprocess.CalledProcessError on command exit != 0.
350 """
351 command = self._command_prefix + command
352 logging.info('Running: %s', ' '.join(str(x) for x in command))
353 return subprocess.check_output(command, universal_newlines=True)
354
Alex Deymo6751bbe2017-03-21 11:20:02 -0700355
356def main():
357 parser = argparse.ArgumentParser(description='Android A/B OTA helper.')
Sen Jiang3b15b592017-09-26 18:21:04 -0700358 parser.add_argument('otafile', metavar='PAYLOAD', type=str,
359 help='the OTA package file (a .zip file) or raw payload \
360 if device uses Omaha.')
Alex Deymo6751bbe2017-03-21 11:20:02 -0700361 parser.add_argument('--file', action='store_true',
362 help='Push the file to the device before updating.')
363 parser.add_argument('--no-push', action='store_true',
364 help='Skip the "push" command when using --file')
365 parser.add_argument('-s', type=str, default='', metavar='DEVICE',
366 help='The specific device to use.')
367 parser.add_argument('--no-verbose', action='store_true',
368 help='Less verbose output')
Sen Jianga1784b72017-08-09 17:42:36 -0700369 parser.add_argument('--public-key', type=str, default='',
370 help='Override the public key used to verify payload.')
Sen Jiang6fbfd7d2017-10-31 16:16:56 -0700371 parser.add_argument('--extra-headers', type=str, default='',
372 help='Extra headers to pass to the device.')
Tianjie Xu3f9be772019-11-02 18:31:50 -0700373 parser.add_argument('--secondary', action='store_true',
374 help='Update with the secondary payload in the package.')
Alex Deymo6751bbe2017-03-21 11:20:02 -0700375 args = parser.parse_args()
376 logging.basicConfig(
377 level=logging.WARNING if args.no_verbose else logging.INFO)
378
379 dut = AdbHost(args.s)
380
381 server_thread = None
382 # List of commands to execute on exit.
383 finalize_cmds = []
384 # Commands to execute when canceling an update.
385 cancel_cmd = ['shell', 'su', '0', 'update_engine_client', '--cancel']
386 # List of commands to perform the update.
387 cmds = []
388
Sen Jianga1784b72017-08-09 17:42:36 -0700389 help_cmd = ['shell', 'su', '0', 'update_engine_client', '--help']
390 use_omaha = 'omaha' in dut.adb_output(help_cmd)
391
Alex Deymo6751bbe2017-03-21 11:20:02 -0700392 if args.file:
393 # Update via pushing a file to /data.
394 device_ota_file = os.path.join(OTA_PACKAGE_PATH, 'debug.zip')
395 payload_url = 'file://' + device_ota_file
396 if not args.no_push:
Tao Baoabb45a52017-10-25 11:13:03 -0700397 data_local_tmp_file = '/data/local/tmp/debug.zip'
398 cmds.append(['push', args.otafile, data_local_tmp_file])
399 cmds.append(['shell', 'su', '0', 'mv', data_local_tmp_file,
400 device_ota_file])
401 cmds.append(['shell', 'su', '0', 'chcon',
402 'u:object_r:ota_package_file:s0', device_ota_file])
Alex Deymo6751bbe2017-03-21 11:20:02 -0700403 cmds.append(['shell', 'su', '0', 'chown', 'system:cache', device_ota_file])
404 cmds.append(['shell', 'su', '0', 'chmod', '0660', device_ota_file])
405 else:
406 # Update via sending the payload over the network with an "adb reverse"
407 # command.
Sen Jianga1784b72017-08-09 17:42:36 -0700408 payload_url = 'http://127.0.0.1:%d/payload' % DEVICE_PORT
Sen Jiang3b15b592017-09-26 18:21:04 -0700409 if use_omaha and zipfile.is_zipfile(args.otafile):
Tianjie Xu3f9be772019-11-02 18:31:50 -0700410 ota = AndroidOTAPackage(args.otafile, args.secondary)
Sen Jiang3b15b592017-09-26 18:21:04 -0700411 serving_range = (ota.offset, ota.size)
412 else:
413 serving_range = (0, os.stat(args.otafile).st_size)
414 server_thread = StartServer(args.otafile, serving_range)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700415 cmds.append(
Sen Jianga1784b72017-08-09 17:42:36 -0700416 ['reverse', 'tcp:%d' % DEVICE_PORT, 'tcp:%d' % server_thread.port])
417 finalize_cmds.append(['reverse', '--remove', 'tcp:%d' % DEVICE_PORT])
418
419 if args.public_key:
420 payload_key_dir = os.path.dirname(PAYLOAD_KEY_PATH)
421 cmds.append(
422 ['shell', 'su', '0', 'mount', '-t', 'tmpfs', 'tmpfs', payload_key_dir])
423 # Allow adb push to payload_key_dir
424 cmds.append(['shell', 'su', '0', 'chcon', 'u:object_r:shell_data_file:s0',
425 payload_key_dir])
426 cmds.append(['push', args.public_key, PAYLOAD_KEY_PATH])
427 # Allow update_engine to read it.
428 cmds.append(['shell', 'su', '0', 'chcon', '-R', 'u:object_r:system_file:s0',
429 payload_key_dir])
430 finalize_cmds.append(['shell', 'su', '0', 'umount', payload_key_dir])
Alex Deymo6751bbe2017-03-21 11:20:02 -0700431
432 try:
433 # The main update command using the configured payload_url.
Sen Jianga1784b72017-08-09 17:42:36 -0700434 if use_omaha:
435 update_cmd = \
436 OmahaUpdateCommand('http://127.0.0.1:%d/update' % DEVICE_PORT)
437 else:
Tianjie Xu3f9be772019-11-02 18:31:50 -0700438 update_cmd = AndroidUpdateCommand(args.otafile, args.secondary,
439 payload_url, args.extra_headers)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700440 cmds.append(['shell', 'su', '0'] + update_cmd)
441
442 for cmd in cmds:
443 dut.adb(cmd)
444 except KeyboardInterrupt:
445 dut.adb(cancel_cmd)
446 finally:
447 if server_thread:
448 server_thread.StopServer()
449 for cmd in finalize_cmds:
450 dut.adb(cmd)
451
452 return 0
453
454if __name__ == '__main__':
455 sys.exit(main())