Expand insertkeys.py script to allow union of files.

Allow script to union mac_permissions.xml files
specified using the BOARD_SEPOLICY_DIRS and
BOARD_SEPOLICY_UNION constructs.

Change-Id: I4fc65fd1ab4c612f25e966f030247e54a270b614
Signed-off-by: rpcraig <rpcraig@tycho.ncsc.mil>
diff --git a/Android.mk b/Android.mk
index 47b17a9..085a362 100644
--- a/Android.mk
+++ b/Android.mk
@@ -10,13 +10,6 @@
 MLS_SENS=1
 MLS_CATS=1024
 
-MAC_PERMISSION_FILE=mac_permissions.xml
-
-# Detect if someone tries to union the mac permissions policy file
-$(if $(filter $(MAC_PERMISSION_FILE), $(BOARD_SEPOLICY_UNION)), \
-    $(error Cannot specify $(MAC_PERMISSION_FILE) in BOARD_SEPOLICY_UNION) \
-)
-
 # Quick edge case error detection for BOARD_SEPOLICY_REPLACE.
 # Builds the singular path for each replace file.
 sepolicy_replace_paths :=
@@ -163,7 +156,7 @@
 ##################################
 include $(CLEAR_VARS)
 
-LOCAL_MODULE := $(MAC_PERMISSION_FILE)
+LOCAL_MODULE := mac_permissions.xml
 LOCAL_MODULE_CLASS := ETC
 LOCAL_MODULE_TAGS := optional
 LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)/security
@@ -176,17 +169,13 @@
 	@mkdir -p $(dir $@)
 	$(hide) m4 -s $^ > $@
 
-# Build mac_permissions.xml
-$(MAC_PERMISSION_FILE).tmp := $(intermediates)/$(MAC_PERMISSION_FILE).tmp
-$($(MAC_PERMISSION_FILE).tmp) : $(call build_policy, $(MAC_PERMISSION_FILE))
-	@mkdir -p $(dir $@)
-	$(hide) cp $^ $@
+ALL_MAC_PERMS_FILES := $(call build_policy, $(LOCAL_MODULE))
 
-$(LOCAL_BUILT_MODULE) : $($(MAC_PERMISSION_FILE).tmp) $(mac_perms_keys.tmp) $(HOST_OUT_EXECUTABLES)/insertkeys.py
+$(LOCAL_BUILT_MODULE) : $(mac_perms_keys.tmp) $(HOST_OUT_EXECUTABLES)/insertkeys.py $(ALL_MAC_PERMS_FILES)
 	@mkdir -p $(dir $@)
-	$(HOST_OUT_EXECUTABLES)/insertkeys.py -t $(TARGET_BUILD_VARIANT) -c $(TOP) $(mac_perms_keys.tmp) -o $@ $<
+	$(hide) $(HOST_OUT_EXECUTABLES)/insertkeys.py -t $(TARGET_BUILD_VARIANT) -c $(TOP) $< -o $@ $(ALL_MAC_PERMS_FILES)
 
-$(MAC_PERMISSION_FILE).tmp :=
+mac_perms_keys.tmp :=
 ##################################
 
 build_policy :=
diff --git a/README b/README
index 135d377..debdf2e 100644
--- a/README
+++ b/README
@@ -55,7 +55,7 @@
 is useful if you have numerous config directories that contain a file
 and you want to NOT include a particular file in your resulting
 policy file, either by UNION or REPLACE.
-Eg.) Suppose the follwoing:
+Eg.) Suppose the following:
      BOARD_SEPOLICY_DIRS := X Y
      BOARD_SEPOLICY_REPLACE := A
      BOARD_SEPOLICY_IGNORE := X/A
@@ -87,21 +87,20 @@
     that is referenced in seapp_contexts.
 
     This file can be replaced through BOARD_SEPOLICY_REPLACE containing the
-    value "mac_permissions.xml", however, appending (UNION) does NOT exist
-    and will cause a build time failure. It is important to note the final
-    processed version of this file is stripped of comments and whitespace.
-    This is to preserve space on the system.img. If one wishes to view it in
-    a more human friendly format, the "tidy" or "xmllint" command will assist
-    you.
+    value "mac_permissions.xml", or appended to by using the BOARD_SEPOLICY_UNION
+    variable. It is important to note the final processed version of this file
+    is stripped of comments and whitespace. This is to preserve space on the
+    system.img. If one wishes to view it in a more human friendly format,
+    the "tidy" or "xmllint" command will assist you.
 
   TOOLING:
     insertkeys.py
       Is a helper script for mapping arbitrary tags in the signature stanzas of
       mac_permissions.xml to public keys found in pem files. This script takes
-      a mac_permissions.xml file and configuration file in order to operate.
+      a mac_permissions.xml file(s) and configuration file in order to operate.
       Details of the configuration file (keys.conf) can be found in the subsection
-      keys.conf. This script is also responsible for stipping the comments and
-      whitespace from the xml file.
+      keys.conf. This tool is also responsible for stripping the comments and
+      whitespace during processing.
 
       keys.conf
         The keys.conf file is used for controlling the mapping of "tags" found in
diff --git a/tools/insertkeys.py b/tools/insertkeys.py
index e4eeb43..509c43f 100755
--- a/tools/insertkeys.py
+++ b/tools/insertkeys.py
@@ -116,12 +116,16 @@
         handler.ContentHandler.__init__(self)
         self._keyMap = keyMap
         self._out = out
-
-    def startDocument(self):
         self._out.write(ReplaceTags.XML_ENCODING_TAG)
         self._out.write("<!-- AUTOGENERATED FILE DO NOT MODIFY -->")
+        self._out.write("<policy>")
+
+    def __del__(self):
+        self._out.write("</policy>")
 
     def startElement(self, tag, attrs):
+        if tag == ReplaceTags.POLICY_TAG:
+            return
 
         self._out.write('<' + tag)
 
@@ -140,6 +144,9 @@
             self._out.write('/>')
 
     def endElement(self, tag):
+        if tag == ReplaceTags.POLICY_TAG:
+            return
+
         if tag in ReplaceTags.TAGS_WITH_CHILDREN:
             self._out.write('</%s>' % tag)
 
@@ -157,10 +164,11 @@
 
     # Intentional double space to line up equls signs and opening " for
     # readability.
-    usage  = "usage: %prog [options] CONFIG_FILE MAC_PERMISSIONS_FILE\n"
-    usage += "This tool allows one to configure an automatic inclusion "
-    usage += "of signing keys into the mac_permision.xml file from the "
-    usage += "pem files."
+    usage  = "usage: %prog [options] CONFIG_FILE MAC_PERMISSIONS_FILE [MAC_PERMISSIONS_FILE...]\n"
+    usage += "This tool allows one to configure an automatic inclusion\n"
+    usage += "of signing keys into the mac_permision.xml file(s) from the\n"
+    usage += "pem files. If mulitple mac_permision.xml files are included\n"
+    usage += "then they are unioned to produce a final version."
 
     version = "%prog " + str(__VERSION)
 
@@ -180,11 +188,10 @@
     parser.add_option("-t", "--target-build-variant", default="eng", dest="target_build_variant",
                       help="Specify the TARGET_BUILD_VARIANT, defaults to eng")
 
-
     (options, args) = parser.parse_args()
 
-    if len(args) != 2:
-        parser.error("Must specify a config file (keys.conf) AND mac_permissions.xml file!")
+    if len(args) < 2:
+        parser.error("Must specify a config file (keys.conf) AND mac_permissions.xml file(s)!")
 
     logging.basicConfig(level=logging.INFO if options.verbose == True else logging.WARN)
 
@@ -205,4 +212,5 @@
     # Generate the XML file with markup replaced with keys
     parser = make_parser()
     parser.setContentHandler(ReplaceTags(key_map, output_file))
-    parser.parse(args[1])
+    for f in args[1:]:
+        parser.parse(f)