add "EXTERNAL" as special value of LOCAL_CERTIFICATE

Setting LOCAL_CERTIFICATE to "EXTERNAL" now marks an apk (either a
prebuilt or otherwise) as needing the default test key within the
system, but one that should be signed after the target_files is
produced but before sign_target_files_apks does the rest of the
signing.  (We use this to ship apps on the system that are signed by
third parties, like Facebook.)
diff --git a/tools/releasetools/common.py b/tools/releasetools/common.py
index 0e17a5f..ab6678a 100644
--- a/tools/releasetools/common.py
+++ b/tools/releasetools/common.py
@@ -37,6 +37,11 @@
 OPTIONS.device_specific = None
 OPTIONS.extras = {}
 
+
+# Values for "certificate" in apkcerts that mean special things.
+SPECIAL_CERT_STRINGS = ("PRESIGNED", "EXTERNAL")
+
+
 class ExternalError(RuntimeError): pass
 
 
@@ -166,9 +171,8 @@
   need_passwords = []
   devnull = open("/dev/null", "w+b")
   for k in sorted(keylist):
-    # An empty-string key is used to mean don't re-sign this package.
-    # Obviously we don't need a password for this non-key.
-    if not k:
+    # We don't need a password for things that aren't really keys.
+    if k in SPECIAL_CERT_STRINGS:
       no_passwords.append(k)
       continue
 
@@ -254,6 +258,28 @@
     print "  ", msg
 
 
+def ReadApkCerts(tf_zip):
+  """Given a target_files ZipFile, parse the META/apkcerts.txt file
+  and return a {package: cert} dict."""
+  certmap = {}
+  for line in tf_zip.read("META/apkcerts.txt").split("\n"):
+    line = line.strip()
+    if not line: continue
+    m = re.match(r'^name="(.*)"\s+certificate="(.*)"\s+'
+                 r'private_key="(.*)"$', line)
+    if m:
+      name, cert, privkey = m.groups()
+      if cert in SPECIAL_CERT_STRINGS and not privkey:
+        certmap[name] = cert
+      elif (cert.endswith(".x509.pem") and
+            privkey.endswith(".pk8") and
+            cert[:-9] == privkey[:-4]):
+        certmap[name] = cert[:-9]
+      else:
+        raise ValueError("failed to parse line from apkcerts.txt:\n" + line)
+  return certmap
+
+
 COMMON_DOCSTRING = """
   -p  (--path)  <dir>
       Prepend <dir>/bin to the list of places to search for binaries