| Andrew Lassalle | 165843c | 2019-11-05 13:30:34 -0800 | [diff] [blame] | 1 | #!/usr/bin/env python | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 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 |  | 
|  | 18 | """Send an A/B update to an Android device over adb.""" | 
|  | 19 |  | 
| Kelvin Zhang | 4b883ea | 2020-10-08 13:26:44 -0400 | [diff] [blame] | 20 | from __future__ import print_function | 
| Andrew Lassalle | 165843c | 2019-11-05 13:30:34 -0800 | [diff] [blame] | 21 | from __future__ import absolute_import | 
|  | 22 |  | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 23 | import argparse | 
| Kelvin Zhang | aba70ab | 2020-08-04 10:32:59 -0400 | [diff] [blame] | 24 | import binascii | 
| Sen Jiang | 3b15b59 | 2017-09-26 18:21:04 -0700 | [diff] [blame] | 25 | import hashlib | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 26 | import logging | 
|  | 27 | import os | 
|  | 28 | import socket | 
|  | 29 | import subprocess | 
|  | 30 | import sys | 
| Kelvin Zhang | aba70ab | 2020-08-04 10:32:59 -0400 | [diff] [blame] | 31 | import struct | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 32 | import threading | 
| Sen Jiang | 144f9f8 | 2017-09-26 15:49:45 -0700 | [diff] [blame] | 33 | import xml.etree.ElementTree | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 34 | import zipfile | 
|  | 35 |  | 
| Andrew Lassalle | 165843c | 2019-11-05 13:30:34 -0800 | [diff] [blame] | 36 | from six.moves import BaseHTTPServer | 
|  | 37 |  | 
| Sen Jiang | a1784b7 | 2017-08-09 17:42:36 -0700 | [diff] [blame] | 38 | import update_payload.payload | 
|  | 39 |  | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 40 |  | 
|  | 41 | # The path used to store the OTA package when applying the package from a file. | 
|  | 42 | OTA_PACKAGE_PATH = '/data/ota_package' | 
|  | 43 |  | 
| Sen Jiang | a1784b7 | 2017-08-09 17:42:36 -0700 | [diff] [blame] | 44 | # The path to the payload public key on the device. | 
|  | 45 | PAYLOAD_KEY_PATH = '/etc/update_engine/update-payload-key.pub.pem' | 
|  | 46 |  | 
|  | 47 | # The port on the device that update_engine should connect to. | 
|  | 48 | DEVICE_PORT = 1234 | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 49 |  | 
| Andrew Lassalle | 165843c | 2019-11-05 13:30:34 -0800 | [diff] [blame] | 50 |  | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 51 | def CopyFileObjLength(fsrc, fdst, buffer_size=128 * 1024, copy_length=None): | 
|  | 52 | """Copy from a file object to another. | 
|  | 53 |  | 
|  | 54 | This function is similar to shutil.copyfileobj except that it allows to copy | 
|  | 55 | less than the full source file. | 
|  | 56 |  | 
|  | 57 | Args: | 
|  | 58 | fsrc: source file object where to read from. | 
|  | 59 | fdst: destination file object where to write to. | 
|  | 60 | buffer_size: size of the copy buffer in memory. | 
|  | 61 | copy_length: maximum number of bytes to copy, or None to copy everything. | 
|  | 62 |  | 
|  | 63 | Returns: | 
|  | 64 | the number of bytes copied. | 
|  | 65 | """ | 
|  | 66 | copied = 0 | 
|  | 67 | while True: | 
|  | 68 | chunk_size = buffer_size | 
|  | 69 | if copy_length is not None: | 
|  | 70 | chunk_size = min(chunk_size, copy_length - copied) | 
|  | 71 | if not chunk_size: | 
|  | 72 | break | 
|  | 73 | buf = fsrc.read(chunk_size) | 
|  | 74 | if not buf: | 
|  | 75 | break | 
|  | 76 | fdst.write(buf) | 
|  | 77 | copied += len(buf) | 
|  | 78 | return copied | 
|  | 79 |  | 
|  | 80 |  | 
|  | 81 | class AndroidOTAPackage(object): | 
|  | 82 | """Android update payload using the .zip format. | 
|  | 83 |  | 
|  | 84 | Android OTA packages traditionally used a .zip file to store the payload. When | 
|  | 85 | applying A/B updates over the network, a payload binary is stored RAW inside | 
|  | 86 | this .zip file which is used by update_engine to apply the payload. To do | 
|  | 87 | this, an offset and size inside the .zip file are provided. | 
|  | 88 | """ | 
|  | 89 |  | 
|  | 90 | # Android OTA package file paths. | 
|  | 91 | OTA_PAYLOAD_BIN = 'payload.bin' | 
|  | 92 | OTA_PAYLOAD_PROPERTIES_TXT = 'payload_properties.txt' | 
| Tianjie Xu | 3f9be77 | 2019-11-02 18:31:50 -0700 | [diff] [blame] | 93 | SECONDARY_OTA_PAYLOAD_BIN = 'secondary/payload.bin' | 
|  | 94 | SECONDARY_OTA_PAYLOAD_PROPERTIES_TXT = 'secondary/payload_properties.txt' | 
| Kelvin Zhang | aba70ab | 2020-08-04 10:32:59 -0400 | [diff] [blame] | 95 | PAYLOAD_MAGIC_HEADER = b'CrAU' | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 96 |  | 
| Tianjie Xu | 3f9be77 | 2019-11-02 18:31:50 -0700 | [diff] [blame] | 97 | def __init__(self, otafilename, secondary_payload=False): | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 98 | self.otafilename = otafilename | 
|  | 99 |  | 
|  | 100 | otazip = zipfile.ZipFile(otafilename, 'r') | 
| Tianjie Xu | 3f9be77 | 2019-11-02 18:31:50 -0700 | [diff] [blame] | 101 | payload_entry = (self.SECONDARY_OTA_PAYLOAD_BIN if secondary_payload else | 
|  | 102 | self.OTA_PAYLOAD_BIN) | 
|  | 103 | payload_info = otazip.getinfo(payload_entry) | 
| Kelvin Zhang | aba70ab | 2020-08-04 10:32:59 -0400 | [diff] [blame] | 104 |  | 
|  | 105 | if payload_info.compress_type != 0: | 
|  | 106 | logging.error( | 
| Kelvin Zhang | 07676f5 | 2020-12-01 10:45:09 -0500 | [diff] [blame] | 107 | "Expected payload to be uncompressed, got compression method %d", | 
| Kelvin Zhang | aba70ab | 2020-08-04 10:32:59 -0400 | [diff] [blame] | 108 | payload_info.compress_type) | 
|  | 109 | # Don't use len(payload_info.extra). Because that returns size of extra | 
|  | 110 | # fields in central directory. We need to look at local file directory, | 
|  | 111 | # as these two might have different sizes. | 
|  | 112 | with open(otafilename, "rb") as fp: | 
|  | 113 | fp.seek(payload_info.header_offset) | 
|  | 114 | data = fp.read(zipfile.sizeFileHeader) | 
|  | 115 | fheader = struct.unpack(zipfile.structFileHeader, data) | 
|  | 116 | # Last two fields of local file header are filename length and | 
|  | 117 | # extra length | 
|  | 118 | filename_len = fheader[-2] | 
|  | 119 | extra_len = fheader[-1] | 
|  | 120 | self.offset = payload_info.header_offset | 
|  | 121 | self.offset += zipfile.sizeFileHeader | 
|  | 122 | self.offset += filename_len + extra_len | 
|  | 123 | self.size = payload_info.file_size | 
|  | 124 | fp.seek(self.offset) | 
|  | 125 | payload_header = fp.read(4) | 
|  | 126 | if payload_header != self.PAYLOAD_MAGIC_HEADER: | 
|  | 127 | logging.warning( | 
| Kelvin Zhang | 07676f5 | 2020-12-01 10:45:09 -0500 | [diff] [blame] | 128 | "Invalid header, expected %s, got %s." | 
| Kelvin Zhang | aba70ab | 2020-08-04 10:32:59 -0400 | [diff] [blame] | 129 | "Either the offset is not correct, or payload is corrupted", | 
|  | 130 | binascii.hexlify(self.PAYLOAD_MAGIC_HEADER), | 
| Kelvin Zhang | 07676f5 | 2020-12-01 10:45:09 -0500 | [diff] [blame] | 131 | binascii.hexlify(payload_header)) | 
| Tianjie Xu | 3f9be77 | 2019-11-02 18:31:50 -0700 | [diff] [blame] | 132 |  | 
|  | 133 | property_entry = (self.SECONDARY_OTA_PAYLOAD_PROPERTIES_TXT if | 
|  | 134 | secondary_payload else self.OTA_PAYLOAD_PROPERTIES_TXT) | 
|  | 135 | self.properties = otazip.read(property_entry) | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 136 |  | 
|  | 137 |  | 
|  | 138 | class UpdateHandler(BaseHTTPServer.BaseHTTPRequestHandler): | 
|  | 139 | """A HTTPServer that supports single-range requests. | 
|  | 140 |  | 
|  | 141 | Attributes: | 
|  | 142 | serving_payload: path to the only payload file we are serving. | 
| Sen Jiang | 3b15b59 | 2017-09-26 18:21:04 -0700 | [diff] [blame] | 143 | serving_range: the start offset and size tuple of the payload. | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 144 | """ | 
|  | 145 |  | 
|  | 146 | @staticmethod | 
| Sen Jiang | 1048559 | 2017-08-15 18:20:24 -0700 | [diff] [blame] | 147 | def _parse_range(range_str, file_size): | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 148 | """Parse an HTTP range string. | 
|  | 149 |  | 
|  | 150 | Args: | 
|  | 151 | range_str: HTTP Range header in the request, not including "Header:". | 
|  | 152 | file_size: total size of the serving file. | 
|  | 153 |  | 
|  | 154 | Returns: | 
|  | 155 | A tuple (start_range, end_range) with the range of bytes requested. | 
|  | 156 | """ | 
|  | 157 | start_range = 0 | 
|  | 158 | end_range = file_size | 
|  | 159 |  | 
|  | 160 | if range_str: | 
|  | 161 | range_str = range_str.split('=', 1)[1] | 
|  | 162 | s, e = range_str.split('-', 1) | 
|  | 163 | if s: | 
|  | 164 | start_range = int(s) | 
|  | 165 | if e: | 
|  | 166 | end_range = int(e) + 1 | 
|  | 167 | elif e: | 
|  | 168 | if int(e) < file_size: | 
|  | 169 | start_range = file_size - int(e) | 
|  | 170 | return start_range, end_range | 
|  | 171 |  | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 172 | def do_GET(self):  # pylint: disable=invalid-name | 
|  | 173 | """Reply with the requested payload file.""" | 
|  | 174 | if self.path != '/payload': | 
|  | 175 | self.send_error(404, 'Unknown request') | 
|  | 176 | return | 
|  | 177 |  | 
|  | 178 | if not self.serving_payload: | 
|  | 179 | self.send_error(500, 'No serving payload set') | 
|  | 180 | return | 
|  | 181 |  | 
|  | 182 | try: | 
|  | 183 | f = open(self.serving_payload, 'rb') | 
|  | 184 | except IOError: | 
|  | 185 | self.send_error(404, 'File not found') | 
|  | 186 | return | 
|  | 187 | # Handle the range request. | 
|  | 188 | if 'Range' in self.headers: | 
|  | 189 | self.send_response(206) | 
|  | 190 | else: | 
|  | 191 | self.send_response(200) | 
|  | 192 |  | 
| Sen Jiang | 3b15b59 | 2017-09-26 18:21:04 -0700 | [diff] [blame] | 193 | serving_start, serving_size = self.serving_range | 
| Sen Jiang | 1048559 | 2017-08-15 18:20:24 -0700 | [diff] [blame] | 194 | start_range, end_range = self._parse_range(self.headers.get('range'), | 
| Sen Jiang | 3b15b59 | 2017-09-26 18:21:04 -0700 | [diff] [blame] | 195 | serving_size) | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 196 | logging.info('Serving request for %s from %s [%d, %d) length: %d', | 
| Sen Jiang | 3b15b59 | 2017-09-26 18:21:04 -0700 | [diff] [blame] | 197 | self.path, self.serving_payload, serving_start + start_range, | 
|  | 198 | serving_start + end_range, end_range - start_range) | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 199 |  | 
|  | 200 | self.send_header('Accept-Ranges', 'bytes') | 
|  | 201 | self.send_header('Content-Range', | 
|  | 202 | 'bytes ' + str(start_range) + '-' + str(end_range - 1) + | 
|  | 203 | '/' + str(end_range - start_range)) | 
|  | 204 | self.send_header('Content-Length', end_range - start_range) | 
|  | 205 |  | 
| Sen Jiang | 3b15b59 | 2017-09-26 18:21:04 -0700 | [diff] [blame] | 206 | stat = os.fstat(f.fileno()) | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 207 | self.send_header('Last-Modified', self.date_time_string(stat.st_mtime)) | 
|  | 208 | self.send_header('Content-type', 'application/octet-stream') | 
|  | 209 | self.end_headers() | 
|  | 210 |  | 
| Sen Jiang | 3b15b59 | 2017-09-26 18:21:04 -0700 | [diff] [blame] | 211 | f.seek(serving_start + start_range) | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 212 | CopyFileObjLength(f, self.wfile, copy_length=end_range - start_range) | 
|  | 213 |  | 
| Sen Jiang | a1784b7 | 2017-08-09 17:42:36 -0700 | [diff] [blame] | 214 | def do_POST(self):  # pylint: disable=invalid-name | 
|  | 215 | """Reply with the omaha response xml.""" | 
|  | 216 | if self.path != '/update': | 
|  | 217 | self.send_error(404, 'Unknown request') | 
|  | 218 | return | 
|  | 219 |  | 
|  | 220 | if not self.serving_payload: | 
|  | 221 | self.send_error(500, 'No serving payload set') | 
|  | 222 | return | 
|  | 223 |  | 
|  | 224 | try: | 
|  | 225 | f = open(self.serving_payload, 'rb') | 
|  | 226 | except IOError: | 
|  | 227 | self.send_error(404, 'File not found') | 
|  | 228 | return | 
|  | 229 |  | 
| Sen Jiang | 144f9f8 | 2017-09-26 15:49:45 -0700 | [diff] [blame] | 230 | content_length = int(self.headers.getheader('Content-Length')) | 
|  | 231 | request_xml = self.rfile.read(content_length) | 
|  | 232 | xml_root = xml.etree.ElementTree.fromstring(request_xml) | 
|  | 233 | appid = None | 
|  | 234 | for app in xml_root.iter('app'): | 
|  | 235 | if 'appid' in app.attrib: | 
|  | 236 | appid = app.attrib['appid'] | 
|  | 237 | break | 
|  | 238 | if not appid: | 
|  | 239 | self.send_error(400, 'No appid in Omaha request') | 
|  | 240 | return | 
|  | 241 |  | 
| Sen Jiang | a1784b7 | 2017-08-09 17:42:36 -0700 | [diff] [blame] | 242 | self.send_response(200) | 
|  | 243 | self.send_header("Content-type", "text/xml") | 
|  | 244 | self.end_headers() | 
|  | 245 |  | 
| Sen Jiang | 3b15b59 | 2017-09-26 18:21:04 -0700 | [diff] [blame] | 246 | serving_start, serving_size = self.serving_range | 
|  | 247 | sha256 = hashlib.sha256() | 
|  | 248 | f.seek(serving_start) | 
|  | 249 | bytes_to_hash = serving_size | 
|  | 250 | while bytes_to_hash: | 
|  | 251 | buf = f.read(min(bytes_to_hash, 1024 * 1024)) | 
|  | 252 | if not buf: | 
|  | 253 | self.send_error(500, 'Payload too small') | 
|  | 254 | return | 
|  | 255 | sha256.update(buf) | 
|  | 256 | bytes_to_hash -= len(buf) | 
|  | 257 |  | 
|  | 258 | payload = update_payload.Payload(f, payload_file_offset=serving_start) | 
| Sen Jiang | a1784b7 | 2017-08-09 17:42:36 -0700 | [diff] [blame] | 259 | payload.Init() | 
|  | 260 |  | 
| Sen Jiang | 144f9f8 | 2017-09-26 15:49:45 -0700 | [diff] [blame] | 261 | response_xml = ''' | 
| Sen Jiang | a1784b7 | 2017-08-09 17:42:36 -0700 | [diff] [blame] | 262 | <?xml version="1.0" encoding="UTF-8"?> | 
|  | 263 | <response protocol="3.0"> | 
| Sen Jiang | 144f9f8 | 2017-09-26 15:49:45 -0700 | [diff] [blame] | 264 | <app appid="{appid}"> | 
| Sen Jiang | a1784b7 | 2017-08-09 17:42:36 -0700 | [diff] [blame] | 265 | <updatecheck status="ok"> | 
|  | 266 | <urls> | 
| Sen Jiang | 144f9f8 | 2017-09-26 15:49:45 -0700 | [diff] [blame] | 267 | <url codebase="http://127.0.0.1:{port}/"/> | 
| Sen Jiang | a1784b7 | 2017-08-09 17:42:36 -0700 | [diff] [blame] | 268 | </urls> | 
|  | 269 | <manifest version="0.0.0.1"> | 
|  | 270 | <actions> | 
|  | 271 | <action event="install" run="payload"/> | 
| Sen Jiang | 144f9f8 | 2017-09-26 15:49:45 -0700 | [diff] [blame] | 272 | <action event="postinstall" MetadataSize="{metadata_size}"/> | 
| Sen Jiang | a1784b7 | 2017-08-09 17:42:36 -0700 | [diff] [blame] | 273 | </actions> | 
|  | 274 | <packages> | 
| Sen Jiang | 144f9f8 | 2017-09-26 15:49:45 -0700 | [diff] [blame] | 275 | <package hash_sha256="{payload_hash}" name="payload" size="{payload_size}"/> | 
| Sen Jiang | a1784b7 | 2017-08-09 17:42:36 -0700 | [diff] [blame] | 276 | </packages> | 
|  | 277 | </manifest> | 
|  | 278 | </updatecheck> | 
|  | 279 | </app> | 
|  | 280 | </response> | 
| Sen Jiang | 144f9f8 | 2017-09-26 15:49:45 -0700 | [diff] [blame] | 281 | '''.format(appid=appid, port=DEVICE_PORT, | 
| Sen Jiang | 3b15b59 | 2017-09-26 18:21:04 -0700 | [diff] [blame] | 282 | metadata_size=payload.metadata_size, | 
|  | 283 | payload_hash=sha256.hexdigest(), | 
|  | 284 | payload_size=serving_size) | 
| Sen Jiang | 144f9f8 | 2017-09-26 15:49:45 -0700 | [diff] [blame] | 285 | self.wfile.write(response_xml.strip()) | 
| Sen Jiang | a1784b7 | 2017-08-09 17:42:36 -0700 | [diff] [blame] | 286 | return | 
|  | 287 |  | 
|  | 288 |  | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 289 | class ServerThread(threading.Thread): | 
|  | 290 | """A thread for serving HTTP requests.""" | 
|  | 291 |  | 
| Sen Jiang | 3b15b59 | 2017-09-26 18:21:04 -0700 | [diff] [blame] | 292 | def __init__(self, ota_filename, serving_range): | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 293 | threading.Thread.__init__(self) | 
| Sen Jiang | 3b15b59 | 2017-09-26 18:21:04 -0700 | [diff] [blame] | 294 | # serving_payload and serving_range are class attributes and the | 
|  | 295 | # UpdateHandler class is instantiated with every request. | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 296 | UpdateHandler.serving_payload = ota_filename | 
| Sen Jiang | 3b15b59 | 2017-09-26 18:21:04 -0700 | [diff] [blame] | 297 | UpdateHandler.serving_range = serving_range | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 298 | self._httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 0), UpdateHandler) | 
|  | 299 | self.port = self._httpd.server_port | 
|  | 300 |  | 
|  | 301 | def run(self): | 
|  | 302 | try: | 
|  | 303 | self._httpd.serve_forever() | 
|  | 304 | except (KeyboardInterrupt, socket.error): | 
|  | 305 | pass | 
|  | 306 | logging.info('Server Terminated') | 
|  | 307 |  | 
|  | 308 | def StopServer(self): | 
| Kelvin Zhang | 4b883ea | 2020-10-08 13:26:44 -0400 | [diff] [blame] | 309 | self._httpd.shutdown() | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 310 | self._httpd.socket.close() | 
|  | 311 |  | 
|  | 312 |  | 
| Sen Jiang | 3b15b59 | 2017-09-26 18:21:04 -0700 | [diff] [blame] | 313 | def StartServer(ota_filename, serving_range): | 
|  | 314 | t = ServerThread(ota_filename, serving_range) | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 315 | t.start() | 
|  | 316 | return t | 
|  | 317 |  | 
|  | 318 |  | 
| Tianjie Xu | 3f9be77 | 2019-11-02 18:31:50 -0700 | [diff] [blame] | 319 | def AndroidUpdateCommand(ota_filename, secondary, payload_url, extra_headers): | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 320 | """Return the command to run to start the update in the Android device.""" | 
| Tianjie Xu | 3f9be77 | 2019-11-02 18:31:50 -0700 | [diff] [blame] | 321 | ota = AndroidOTAPackage(ota_filename, secondary) | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 322 | headers = ota.properties | 
| Kelvin Zhang | 4b883ea | 2020-10-08 13:26:44 -0400 | [diff] [blame] | 323 | headers += b'USER_AGENT=Dalvik (something, something)\n' | 
|  | 324 | headers += b'NETWORK_ID=0\n' | 
|  | 325 | headers += extra_headers.encode() | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 326 |  | 
|  | 327 | return ['update_engine_client', '--update', '--follow', | 
|  | 328 | '--payload=%s' % payload_url, '--offset=%d' % ota.offset, | 
| Kelvin Zhang | 4b883ea | 2020-10-08 13:26:44 -0400 | [diff] [blame] | 329 | '--size=%d' % ota.size, '--headers="%s"' % headers.decode()] | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 330 |  | 
|  | 331 |  | 
| Sen Jiang | a1784b7 | 2017-08-09 17:42:36 -0700 | [diff] [blame] | 332 | def OmahaUpdateCommand(omaha_url): | 
|  | 333 | """Return the command to run to start the update in a device using Omaha.""" | 
|  | 334 | return ['update_engine_client', '--update', '--follow', | 
|  | 335 | '--omaha_url=%s' % omaha_url] | 
|  | 336 |  | 
|  | 337 |  | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 338 | class AdbHost(object): | 
|  | 339 | """Represents a device connected via ADB.""" | 
|  | 340 |  | 
|  | 341 | def __init__(self, device_serial=None): | 
|  | 342 | """Construct an instance. | 
|  | 343 |  | 
|  | 344 | Args: | 
|  | 345 | device_serial: options string serial number of attached device. | 
|  | 346 | """ | 
|  | 347 | self._device_serial = device_serial | 
|  | 348 | self._command_prefix = ['adb'] | 
|  | 349 | if self._device_serial: | 
|  | 350 | self._command_prefix += ['-s', self._device_serial] | 
|  | 351 |  | 
|  | 352 | def adb(self, command): | 
|  | 353 | """Run an ADB command like "adb push". | 
|  | 354 |  | 
|  | 355 | Args: | 
|  | 356 | command: list of strings containing command and arguments to run | 
|  | 357 |  | 
|  | 358 | Returns: | 
|  | 359 | the program's return code. | 
|  | 360 |  | 
|  | 361 | Raises: | 
|  | 362 | subprocess.CalledProcessError on command exit != 0. | 
|  | 363 | """ | 
|  | 364 | command = self._command_prefix + command | 
|  | 365 | logging.info('Running: %s', ' '.join(str(x) for x in command)) | 
|  | 366 | p = subprocess.Popen(command, universal_newlines=True) | 
|  | 367 | p.wait() | 
|  | 368 | return p.returncode | 
|  | 369 |  | 
| Sen Jiang | a1784b7 | 2017-08-09 17:42:36 -0700 | [diff] [blame] | 370 | def adb_output(self, command): | 
|  | 371 | """Run an ADB command like "adb push" and return the output. | 
|  | 372 |  | 
|  | 373 | Args: | 
|  | 374 | command: list of strings containing command and arguments to run | 
|  | 375 |  | 
|  | 376 | Returns: | 
|  | 377 | the program's output as a string. | 
|  | 378 |  | 
|  | 379 | Raises: | 
|  | 380 | subprocess.CalledProcessError on command exit != 0. | 
|  | 381 | """ | 
|  | 382 | command = self._command_prefix + command | 
|  | 383 | logging.info('Running: %s', ' '.join(str(x) for x in command)) | 
|  | 384 | return subprocess.check_output(command, universal_newlines=True) | 
|  | 385 |  | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 386 |  | 
|  | 387 | def main(): | 
|  | 388 | parser = argparse.ArgumentParser(description='Android A/B OTA helper.') | 
| Sen Jiang | 3b15b59 | 2017-09-26 18:21:04 -0700 | [diff] [blame] | 389 | parser.add_argument('otafile', metavar='PAYLOAD', type=str, | 
|  | 390 | help='the OTA package file (a .zip file) or raw payload \ | 
|  | 391 | if device uses Omaha.') | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 392 | parser.add_argument('--file', action='store_true', | 
|  | 393 | help='Push the file to the device before updating.') | 
|  | 394 | parser.add_argument('--no-push', action='store_true', | 
|  | 395 | help='Skip the "push" command when using --file') | 
|  | 396 | parser.add_argument('-s', type=str, default='', metavar='DEVICE', | 
|  | 397 | help='The specific device to use.') | 
|  | 398 | parser.add_argument('--no-verbose', action='store_true', | 
|  | 399 | help='Less verbose output') | 
| Sen Jiang | a1784b7 | 2017-08-09 17:42:36 -0700 | [diff] [blame] | 400 | parser.add_argument('--public-key', type=str, default='', | 
|  | 401 | help='Override the public key used to verify payload.') | 
| Sen Jiang | 6fbfd7d | 2017-10-31 16:16:56 -0700 | [diff] [blame] | 402 | parser.add_argument('--extra-headers', type=str, default='', | 
|  | 403 | help='Extra headers to pass to the device.') | 
| Tianjie Xu | 3f9be77 | 2019-11-02 18:31:50 -0700 | [diff] [blame] | 404 | parser.add_argument('--secondary', action='store_true', | 
|  | 405 | help='Update with the secondary payload in the package.') | 
| Kelvin Zhang | 8212f53 | 2020-11-13 16:00:00 -0500 | [diff] [blame] | 406 | parser.add_argument('--no-slot-switch', action='store_true', | 
|  | 407 | help='Do not perform slot switch after the update.') | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 408 | args = parser.parse_args() | 
|  | 409 | logging.basicConfig( | 
|  | 410 | level=logging.WARNING if args.no_verbose else logging.INFO) | 
|  | 411 |  | 
|  | 412 | dut = AdbHost(args.s) | 
|  | 413 |  | 
|  | 414 | server_thread = None | 
|  | 415 | # List of commands to execute on exit. | 
|  | 416 | finalize_cmds = [] | 
|  | 417 | # Commands to execute when canceling an update. | 
|  | 418 | cancel_cmd = ['shell', 'su', '0', 'update_engine_client', '--cancel'] | 
|  | 419 | # List of commands to perform the update. | 
|  | 420 | cmds = [] | 
|  | 421 |  | 
| Sen Jiang | a1784b7 | 2017-08-09 17:42:36 -0700 | [diff] [blame] | 422 | help_cmd = ['shell', 'su', '0', 'update_engine_client', '--help'] | 
|  | 423 | use_omaha = 'omaha' in dut.adb_output(help_cmd) | 
|  | 424 |  | 
| Kelvin Zhang | 8212f53 | 2020-11-13 16:00:00 -0500 | [diff] [blame] | 425 | if args.no_slot_switch: | 
|  | 426 | args.extra_headers += "\nSWITCH_SLOT_ON_REBOOT=0" | 
|  | 427 |  | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 428 | if args.file: | 
|  | 429 | # Update via pushing a file to /data. | 
|  | 430 | device_ota_file = os.path.join(OTA_PACKAGE_PATH, 'debug.zip') | 
|  | 431 | payload_url = 'file://' + device_ota_file | 
|  | 432 | if not args.no_push: | 
| Tao Bao | abb45a5 | 2017-10-25 11:13:03 -0700 | [diff] [blame] | 433 | data_local_tmp_file = '/data/local/tmp/debug.zip' | 
|  | 434 | cmds.append(['push', args.otafile, data_local_tmp_file]) | 
|  | 435 | cmds.append(['shell', 'su', '0', 'mv', data_local_tmp_file, | 
|  | 436 | device_ota_file]) | 
|  | 437 | cmds.append(['shell', 'su', '0', 'chcon', | 
|  | 438 | 'u:object_r:ota_package_file:s0', device_ota_file]) | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 439 | cmds.append(['shell', 'su', '0', 'chown', 'system:cache', device_ota_file]) | 
|  | 440 | cmds.append(['shell', 'su', '0', 'chmod', '0660', device_ota_file]) | 
|  | 441 | else: | 
|  | 442 | # Update via sending the payload over the network with an "adb reverse" | 
|  | 443 | # command. | 
| Sen Jiang | a1784b7 | 2017-08-09 17:42:36 -0700 | [diff] [blame] | 444 | payload_url = 'http://127.0.0.1:%d/payload' % DEVICE_PORT | 
| Sen Jiang | 3b15b59 | 2017-09-26 18:21:04 -0700 | [diff] [blame] | 445 | if use_omaha and zipfile.is_zipfile(args.otafile): | 
| Tianjie Xu | 3f9be77 | 2019-11-02 18:31:50 -0700 | [diff] [blame] | 446 | ota = AndroidOTAPackage(args.otafile, args.secondary) | 
| Sen Jiang | 3b15b59 | 2017-09-26 18:21:04 -0700 | [diff] [blame] | 447 | serving_range = (ota.offset, ota.size) | 
|  | 448 | else: | 
|  | 449 | serving_range = (0, os.stat(args.otafile).st_size) | 
|  | 450 | server_thread = StartServer(args.otafile, serving_range) | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 451 | cmds.append( | 
| Sen Jiang | a1784b7 | 2017-08-09 17:42:36 -0700 | [diff] [blame] | 452 | ['reverse', 'tcp:%d' % DEVICE_PORT, 'tcp:%d' % server_thread.port]) | 
|  | 453 | finalize_cmds.append(['reverse', '--remove', 'tcp:%d' % DEVICE_PORT]) | 
|  | 454 |  | 
|  | 455 | if args.public_key: | 
|  | 456 | payload_key_dir = os.path.dirname(PAYLOAD_KEY_PATH) | 
|  | 457 | cmds.append( | 
|  | 458 | ['shell', 'su', '0', 'mount', '-t', 'tmpfs', 'tmpfs', payload_key_dir]) | 
|  | 459 | # Allow adb push to payload_key_dir | 
|  | 460 | cmds.append(['shell', 'su', '0', 'chcon', 'u:object_r:shell_data_file:s0', | 
|  | 461 | payload_key_dir]) | 
|  | 462 | cmds.append(['push', args.public_key, PAYLOAD_KEY_PATH]) | 
|  | 463 | # Allow update_engine to read it. | 
|  | 464 | cmds.append(['shell', 'su', '0', 'chcon', '-R', 'u:object_r:system_file:s0', | 
|  | 465 | payload_key_dir]) | 
|  | 466 | finalize_cmds.append(['shell', 'su', '0', 'umount', payload_key_dir]) | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 467 |  | 
|  | 468 | try: | 
|  | 469 | # The main update command using the configured payload_url. | 
| Sen Jiang | a1784b7 | 2017-08-09 17:42:36 -0700 | [diff] [blame] | 470 | if use_omaha: | 
|  | 471 | update_cmd = \ | 
|  | 472 | OmahaUpdateCommand('http://127.0.0.1:%d/update' % DEVICE_PORT) | 
|  | 473 | else: | 
| Tianjie Xu | 3f9be77 | 2019-11-02 18:31:50 -0700 | [diff] [blame] | 474 | update_cmd = AndroidUpdateCommand(args.otafile, args.secondary, | 
|  | 475 | payload_url, args.extra_headers) | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 476 | cmds.append(['shell', 'su', '0'] + update_cmd) | 
|  | 477 |  | 
|  | 478 | for cmd in cmds: | 
|  | 479 | dut.adb(cmd) | 
|  | 480 | except KeyboardInterrupt: | 
|  | 481 | dut.adb(cancel_cmd) | 
|  | 482 | finally: | 
|  | 483 | if server_thread: | 
|  | 484 | server_thread.StopServer() | 
|  | 485 | for cmd in finalize_cmds: | 
|  | 486 | dut.adb(cmd) | 
|  | 487 |  | 
|  | 488 | return 0 | 
|  | 489 |  | 
| Andrew Lassalle | 165843c | 2019-11-05 13:30:34 -0800 | [diff] [blame] | 490 |  | 
| Alex Deymo | 6751bbe | 2017-03-21 11:20:02 -0700 | [diff] [blame] | 491 | if __name__ == '__main__': | 
|  | 492 | sys.exit(main()) |