Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 1 | # Copyright (C) 2008 The Android Open Source Project |
| 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 | |
Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 15 | import errno |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 16 | import getopt |
| 17 | import getpass |
| 18 | import os |
| 19 | import re |
| 20 | import shutil |
| 21 | import subprocess |
| 22 | import sys |
| 23 | import tempfile |
Doug Zongker | 048e7ca | 2009-06-15 14:31:53 -0700 | [diff] [blame] | 24 | import zipfile |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 25 | |
| 26 | # missing in Python 2.4 and before |
| 27 | if not hasattr(os, "SEEK_SET"): |
| 28 | os.SEEK_SET = 0 |
| 29 | |
| 30 | class Options(object): pass |
| 31 | OPTIONS = Options() |
| 32 | OPTIONS.signapk_jar = "out/host/linux-x86/framework/signapk.jar" |
Doug Zongker | 8e931bf | 2009-04-06 15:21:45 -0700 | [diff] [blame] | 33 | OPTIONS.dumpkey_jar = "out/host/linux-x86/framework/dumpkey.jar" |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 34 | OPTIONS.max_image_size = {} |
| 35 | OPTIONS.verbose = False |
| 36 | OPTIONS.tempfiles = [] |
| 37 | |
| 38 | |
| 39 | class ExternalError(RuntimeError): pass |
| 40 | |
| 41 | |
| 42 | def Run(args, **kwargs): |
| 43 | """Create and return a subprocess.Popen object, printing the command |
| 44 | line on the terminal if -v was specified.""" |
| 45 | if OPTIONS.verbose: |
| 46 | print " running: ", " ".join(args) |
| 47 | return subprocess.Popen(args, **kwargs) |
| 48 | |
| 49 | |
| 50 | def LoadBoardConfig(fn): |
| 51 | """Parse a board_config.mk file looking for lines that specify the |
| 52 | maximum size of various images, and parse them into the |
| 53 | OPTIONS.max_image_size dict.""" |
| 54 | OPTIONS.max_image_size = {} |
| 55 | for line in open(fn): |
| 56 | line = line.strip() |
| 57 | m = re.match(r"BOARD_(BOOT|RECOVERY|SYSTEM|USERDATA)IMAGE_MAX_SIZE" |
| 58 | r"\s*:=\s*(\d+)", line) |
| 59 | if not m: continue |
| 60 | |
| 61 | OPTIONS.max_image_size[m.group(1).lower() + ".img"] = int(m.group(2)) |
| 62 | |
| 63 | |
| 64 | def BuildAndAddBootableImage(sourcedir, targetname, output_zip): |
| 65 | """Take a kernel, cmdline, and ramdisk directory from the input (in |
| 66 | 'sourcedir'), and turn them into a boot image. Put the boot image |
| 67 | into the output zip file under the name 'targetname'.""" |
| 68 | |
| 69 | print "creating %s..." % (targetname,) |
| 70 | |
| 71 | img = BuildBootableImage(sourcedir) |
| 72 | |
| 73 | CheckSize(img, targetname) |
Doug Zongker | 048e7ca | 2009-06-15 14:31:53 -0700 | [diff] [blame] | 74 | ZipWriteStr(output_zip, targetname, img) |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 75 | |
| 76 | def BuildBootableImage(sourcedir): |
| 77 | """Take a kernel, cmdline, and ramdisk directory from the input (in |
| 78 | 'sourcedir'), and turn them into a boot image. Return the image data.""" |
| 79 | |
| 80 | ramdisk_img = tempfile.NamedTemporaryFile() |
| 81 | img = tempfile.NamedTemporaryFile() |
| 82 | |
| 83 | p1 = Run(["mkbootfs", os.path.join(sourcedir, "RAMDISK")], |
| 84 | stdout=subprocess.PIPE) |
Doug Zongker | 32da27a | 2009-05-29 09:35:56 -0700 | [diff] [blame] | 85 | p2 = Run(["minigzip"], |
| 86 | stdin=p1.stdout, stdout=ramdisk_img.file.fileno()) |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 87 | |
| 88 | p2.wait() |
| 89 | p1.wait() |
| 90 | assert p1.returncode == 0, "mkbootfs of %s ramdisk failed" % (targetname,) |
Doug Zongker | 32da27a | 2009-05-29 09:35:56 -0700 | [diff] [blame] | 91 | assert p2.returncode == 0, "minigzip of %s ramdisk failed" % (targetname,) |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 92 | |
| 93 | cmdline = open(os.path.join(sourcedir, "cmdline")).read().rstrip("\n") |
| 94 | p = Run(["mkbootimg", |
| 95 | "--kernel", os.path.join(sourcedir, "kernel"), |
| 96 | "--cmdline", cmdline, |
| 97 | "--ramdisk", ramdisk_img.name, |
| 98 | "--output", img.name], |
| 99 | stdout=subprocess.PIPE) |
| 100 | p.communicate() |
| 101 | assert p.returncode == 0, "mkbootimg of %s image failed" % (targetname,) |
| 102 | |
| 103 | img.seek(os.SEEK_SET, 0) |
| 104 | data = img.read() |
| 105 | |
| 106 | ramdisk_img.close() |
| 107 | img.close() |
| 108 | |
| 109 | return data |
| 110 | |
| 111 | |
| 112 | def AddRecovery(output_zip): |
| 113 | BuildAndAddBootableImage(os.path.join(OPTIONS.input_tmp, "RECOVERY"), |
| 114 | "recovery.img", output_zip) |
| 115 | |
| 116 | def AddBoot(output_zip): |
| 117 | BuildAndAddBootableImage(os.path.join(OPTIONS.input_tmp, "BOOT"), |
| 118 | "boot.img", output_zip) |
| 119 | |
| 120 | def UnzipTemp(filename): |
| 121 | """Unzip the given archive into a temporary directory and return the name.""" |
| 122 | |
| 123 | tmp = tempfile.mkdtemp(prefix="targetfiles-") |
| 124 | OPTIONS.tempfiles.append(tmp) |
| 125 | p = Run(["unzip", "-q", filename, "-d", tmp], stdout=subprocess.PIPE) |
| 126 | p.communicate() |
| 127 | if p.returncode != 0: |
| 128 | raise ExternalError("failed to unzip input target-files \"%s\"" % |
| 129 | (filename,)) |
| 130 | return tmp |
| 131 | |
| 132 | |
| 133 | def GetKeyPasswords(keylist): |
| 134 | """Given a list of keys, prompt the user to enter passwords for |
| 135 | those which require them. Return a {key: password} dict. password |
| 136 | will be None if the key has no password.""" |
| 137 | |
Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 138 | no_passwords = [] |
| 139 | need_passwords = [] |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 140 | devnull = open("/dev/null", "w+b") |
| 141 | for k in sorted(keylist): |
Doug Zongker | 43874f8 | 2009-04-14 14:05:15 -0700 | [diff] [blame] | 142 | # An empty-string key is used to mean don't re-sign this package. |
| 143 | # Obviously we don't need a password for this non-key. |
| 144 | if not k: |
Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 145 | no_passwords.append(k) |
Doug Zongker | 43874f8 | 2009-04-14 14:05:15 -0700 | [diff] [blame] | 146 | continue |
| 147 | |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 148 | p = subprocess.Popen(["openssl", "pkcs8", "-in", k+".pk8", |
| 149 | "-inform", "DER", "-nocrypt"], |
| 150 | stdin=devnull.fileno(), |
| 151 | stdout=devnull.fileno(), |
| 152 | stderr=subprocess.STDOUT) |
| 153 | p.communicate() |
| 154 | if p.returncode == 0: |
Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 155 | no_passwords.append(k) |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 156 | else: |
Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 157 | need_passwords.append(k) |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 158 | devnull.close() |
Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 159 | |
| 160 | key_passwords = PasswordManager().GetPasswords(need_passwords) |
| 161 | key_passwords.update(dict.fromkeys(no_passwords, None)) |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 162 | return key_passwords |
| 163 | |
| 164 | |
| 165 | def SignFile(input_name, output_name, key, password, align=None): |
| 166 | """Sign the input_name zip/jar/apk, producing output_name. Use the |
| 167 | given key and password (the latter may be None if the key does not |
| 168 | have a password. |
| 169 | |
| 170 | If align is an integer > 1, zipalign is run to align stored files in |
| 171 | the output zip on 'align'-byte boundaries. |
| 172 | """ |
| 173 | if align == 0 or align == 1: |
| 174 | align = None |
| 175 | |
| 176 | if align: |
| 177 | temp = tempfile.NamedTemporaryFile() |
| 178 | sign_name = temp.name |
| 179 | else: |
| 180 | sign_name = output_name |
| 181 | |
| 182 | p = subprocess.Popen(["java", "-jar", OPTIONS.signapk_jar, |
| 183 | key + ".x509.pem", |
| 184 | key + ".pk8", |
| 185 | input_name, sign_name], |
| 186 | stdin=subprocess.PIPE, |
| 187 | stdout=subprocess.PIPE) |
| 188 | if password is not None: |
| 189 | password += "\n" |
| 190 | p.communicate(password) |
| 191 | if p.returncode != 0: |
| 192 | raise ExternalError("signapk.jar failed: return code %s" % (p.returncode,)) |
| 193 | |
| 194 | if align: |
| 195 | p = subprocess.Popen(["zipalign", "-f", str(align), sign_name, output_name]) |
| 196 | p.communicate() |
| 197 | if p.returncode != 0: |
| 198 | raise ExternalError("zipalign failed: return code %s" % (p.returncode,)) |
| 199 | temp.close() |
| 200 | |
| 201 | |
| 202 | def CheckSize(data, target): |
| 203 | """Check the data string passed against the max size limit, if |
| 204 | any, for the given target. Raise exception if the data is too big. |
| 205 | Print a warning if the data is nearing the maximum size.""" |
| 206 | limit = OPTIONS.max_image_size.get(target, None) |
| 207 | if limit is None: return |
| 208 | |
| 209 | size = len(data) |
| 210 | pct = float(size) * 100.0 / limit |
| 211 | msg = "%s size (%d) is %.2f%% of limit (%d)" % (target, size, pct, limit) |
| 212 | if pct >= 99.0: |
| 213 | raise ExternalError(msg) |
| 214 | elif pct >= 95.0: |
| 215 | print |
| 216 | print " WARNING: ", msg |
| 217 | print |
| 218 | elif OPTIONS.verbose: |
| 219 | print " ", msg |
| 220 | |
| 221 | |
| 222 | COMMON_DOCSTRING = """ |
| 223 | -p (--path) <dir> |
| 224 | Prepend <dir> to the list of places to search for binaries run |
| 225 | by this script. |
| 226 | |
| 227 | -v (--verbose) |
| 228 | Show command lines being executed. |
| 229 | |
| 230 | -h (--help) |
| 231 | Display this usage message and exit. |
| 232 | """ |
| 233 | |
| 234 | def Usage(docstring): |
| 235 | print docstring.rstrip("\n") |
| 236 | print COMMON_DOCSTRING |
| 237 | |
| 238 | |
| 239 | def ParseOptions(argv, |
| 240 | docstring, |
| 241 | extra_opts="", extra_long_opts=(), |
| 242 | extra_option_handler=None): |
| 243 | """Parse the options in argv and return any arguments that aren't |
| 244 | flags. docstring is the calling module's docstring, to be displayed |
| 245 | for errors and -h. extra_opts and extra_long_opts are for flags |
| 246 | defined by the caller, which are processed by passing them to |
| 247 | extra_option_handler.""" |
| 248 | |
| 249 | try: |
| 250 | opts, args = getopt.getopt( |
| 251 | argv, "hvp:" + extra_opts, |
| 252 | ["help", "verbose", "path="] + list(extra_long_opts)) |
| 253 | except getopt.GetoptError, err: |
| 254 | Usage(docstring) |
| 255 | print "**", str(err), "**" |
| 256 | sys.exit(2) |
| 257 | |
| 258 | path_specified = False |
| 259 | |
| 260 | for o, a in opts: |
| 261 | if o in ("-h", "--help"): |
| 262 | Usage(docstring) |
| 263 | sys.exit() |
| 264 | elif o in ("-v", "--verbose"): |
| 265 | OPTIONS.verbose = True |
| 266 | elif o in ("-p", "--path"): |
| 267 | os.environ["PATH"] = a + os.pathsep + os.environ["PATH"] |
| 268 | path_specified = True |
| 269 | else: |
| 270 | if extra_option_handler is None or not extra_option_handler(o, a): |
| 271 | assert False, "unknown option \"%s\"" % (o,) |
| 272 | |
| 273 | if not path_specified: |
| 274 | os.environ["PATH"] = ("out/host/linux-x86/bin" + os.pathsep + |
| 275 | os.environ["PATH"]) |
| 276 | |
| 277 | return args |
| 278 | |
| 279 | |
| 280 | def Cleanup(): |
| 281 | for i in OPTIONS.tempfiles: |
| 282 | if os.path.isdir(i): |
| 283 | shutil.rmtree(i) |
| 284 | else: |
| 285 | os.remove(i) |
Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 286 | |
| 287 | |
| 288 | class PasswordManager(object): |
| 289 | def __init__(self): |
| 290 | self.editor = os.getenv("EDITOR", None) |
| 291 | self.pwfile = os.getenv("ANDROID_PW_FILE", None) |
| 292 | |
| 293 | def GetPasswords(self, items): |
| 294 | """Get passwords corresponding to each string in 'items', |
| 295 | returning a dict. (The dict may have keys in addition to the |
| 296 | values in 'items'.) |
| 297 | |
| 298 | Uses the passwords in $ANDROID_PW_FILE if available, letting the |
| 299 | user edit that file to add more needed passwords. If no editor is |
| 300 | available, or $ANDROID_PW_FILE isn't define, prompts the user |
| 301 | interactively in the ordinary way. |
| 302 | """ |
| 303 | |
| 304 | current = self.ReadFile() |
| 305 | |
| 306 | first = True |
| 307 | while True: |
| 308 | missing = [] |
| 309 | for i in items: |
| 310 | if i not in current or not current[i]: |
| 311 | missing.append(i) |
| 312 | # Are all the passwords already in the file? |
| 313 | if not missing: return current |
| 314 | |
| 315 | for i in missing: |
| 316 | current[i] = "" |
| 317 | |
| 318 | if not first: |
| 319 | print "key file %s still missing some passwords." % (self.pwfile,) |
| 320 | answer = raw_input("try to edit again? [y]> ").strip() |
| 321 | if answer and answer[0] not in 'yY': |
| 322 | raise RuntimeError("key passwords unavailable") |
| 323 | first = False |
| 324 | |
| 325 | current = self.UpdateAndReadFile(current) |
| 326 | |
| 327 | def PromptResult(self, current): |
| 328 | """Prompt the user to enter a value (password) for each key in |
| 329 | 'current' whose value is fales. Returns a new dict with all the |
| 330 | values. |
| 331 | """ |
| 332 | result = {} |
| 333 | for k, v in sorted(current.iteritems()): |
| 334 | if v: |
| 335 | result[k] = v |
| 336 | else: |
| 337 | while True: |
| 338 | result[k] = getpass.getpass("Enter password for %s key> " |
| 339 | % (k,)).strip() |
| 340 | if result[k]: break |
| 341 | return result |
| 342 | |
| 343 | def UpdateAndReadFile(self, current): |
| 344 | if not self.editor or not self.pwfile: |
| 345 | return self.PromptResult(current) |
| 346 | |
| 347 | f = open(self.pwfile, "w") |
| 348 | os.chmod(self.pwfile, 0600) |
| 349 | f.write("# Enter key passwords between the [[[ ]]] brackets.\n") |
| 350 | f.write("# (Additional spaces are harmless.)\n\n") |
| 351 | |
| 352 | first_line = None |
| 353 | sorted = [(not v, k, v) for (k, v) in current.iteritems()] |
| 354 | sorted.sort() |
| 355 | for i, (_, k, v) in enumerate(sorted): |
| 356 | f.write("[[[ %s ]]] %s\n" % (v, k)) |
| 357 | if not v and first_line is None: |
| 358 | # position cursor on first line with no password. |
| 359 | first_line = i + 4 |
| 360 | f.close() |
| 361 | |
| 362 | p = Run([self.editor, "+%d" % (first_line,), self.pwfile]) |
| 363 | _, _ = p.communicate() |
| 364 | |
| 365 | return self.ReadFile() |
| 366 | |
| 367 | def ReadFile(self): |
| 368 | result = {} |
| 369 | if self.pwfile is None: return result |
| 370 | try: |
| 371 | f = open(self.pwfile, "r") |
| 372 | for line in f: |
| 373 | line = line.strip() |
| 374 | if not line or line[0] == '#': continue |
| 375 | m = re.match(r"^\[\[\[\s*(.*?)\s*\]\]\]\s*(\S+)$", line) |
| 376 | if not m: |
| 377 | print "failed to parse password file: ", line |
| 378 | else: |
| 379 | result[m.group(2)] = m.group(1) |
| 380 | f.close() |
| 381 | except IOError, e: |
| 382 | if e.errno != errno.ENOENT: |
| 383 | print "error reading password file: ", str(e) |
| 384 | return result |
Doug Zongker | 048e7ca | 2009-06-15 14:31:53 -0700 | [diff] [blame] | 385 | |
| 386 | |
| 387 | def ZipWriteStr(zip, filename, data, perms=0644): |
| 388 | # use a fixed timestamp so the output is repeatable. |
| 389 | zinfo = zipfile.ZipInfo(filename=filename, |
| 390 | date_time=(2009, 1, 1, 0, 0, 0)) |
| 391 | zinfo.compress_type = zip.compression |
| 392 | zinfo.external_attr = perms << 16 |
| 393 | zip.writestr(zinfo, data) |