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