Merge "Fix updater include generation w/installclean"
diff --git a/Android.mk b/Android.mk
index f8e5ac2..58b8a22 100644
--- a/Android.mk
+++ b/Android.mk
@@ -144,15 +144,12 @@
 # libverifier (static library)
 # ===============================
 include $(CLEAR_VARS)
-LOCAL_CLANG := true
 LOCAL_MODULE := libverifier
 LOCAL_MODULE_TAGS := tests
 LOCAL_SRC_FILES := \
     asn1_decoder.cpp \
-    verifier.cpp \
-    ui.cpp
+    verifier.cpp
 LOCAL_STATIC_LIBRARIES := \
-    libminui \
     libcrypto_utils \
     libcrypto \
     libbase
diff --git a/asn1_decoder.cpp b/asn1_decoder.cpp
index e7aef78..ca4ee52 100644
--- a/asn1_decoder.cpp
+++ b/asn1_decoder.cpp
@@ -22,9 +22,9 @@
 
 
 typedef struct asn1_context {
-    size_t length;
-    uint8_t* p;
-    int app_type;
+  size_t length;
+  const uint8_t* p;
+  int app_type;
 } asn1_context_t;
 
 
@@ -38,7 +38,7 @@
 static const int kTagSet = 0x31;
 static const int kTagConstructed = 0xA0;
 
-asn1_context_t* asn1_context_new(uint8_t* buffer, size_t length) {
+asn1_context_t* asn1_context_new(const uint8_t* buffer, size_t length) {
     asn1_context_t* ctx = (asn1_context_t*) calloc(1, sizeof(asn1_context_t));
     if (ctx == NULL) {
         return NULL;
@@ -168,7 +168,7 @@
     return true;
 }
 
-bool asn1_oid_get(asn1_context_t* ctx, uint8_t** oid, size_t* length) {
+bool asn1_oid_get(asn1_context_t* ctx, const uint8_t** oid, size_t* length) {
     if (get_byte(ctx) != kTagOid) {
         return false;
     }
@@ -179,7 +179,7 @@
     return true;
 }
 
-bool asn1_octet_string_get(asn1_context_t* ctx, uint8_t** octet_string, size_t* length) {
+bool asn1_octet_string_get(asn1_context_t* ctx, const uint8_t** octet_string, size_t* length) {
     if (get_byte(ctx) != kTagOctetString) {
         return false;
     }
diff --git a/asn1_decoder.h b/asn1_decoder.h
index b17141c..fbd118f 100644
--- a/asn1_decoder.h
+++ b/asn1_decoder.h
@@ -22,7 +22,7 @@
 
 typedef struct asn1_context asn1_context_t;
 
-asn1_context_t* asn1_context_new(uint8_t* buffer, size_t length);
+asn1_context_t* asn1_context_new(const uint8_t* buffer, size_t length);
 void asn1_context_free(asn1_context_t* ctx);
 asn1_context_t* asn1_constructed_get(asn1_context_t* ctx);
 bool asn1_constructed_skip_all(asn1_context_t* ctx);
@@ -30,7 +30,7 @@
 asn1_context_t* asn1_sequence_get(asn1_context_t* ctx);
 asn1_context_t* asn1_set_get(asn1_context_t* ctx);
 bool asn1_sequence_next(asn1_context_t* seq);
-bool asn1_oid_get(asn1_context_t* ctx, uint8_t** oid, size_t* length);
-bool asn1_octet_string_get(asn1_context_t* ctx, uint8_t** octet_string, size_t* length);
+bool asn1_oid_get(asn1_context_t* ctx, const uint8_t** oid, size_t* length);
+bool asn1_octet_string_get(asn1_context_t* ctx, const uint8_t** octet_string, size_t* length);
 
 #endif /* ASN1_DECODER_H_ */
diff --git a/install.cpp b/install.cpp
index ce89e0d..db8fb97 100644
--- a/install.cpp
+++ b/install.cpp
@@ -27,6 +27,7 @@
 #include <unistd.h>
 
 #include <chrono>
+#include <functional>
 #include <limits>
 #include <map>
 #include <string>
@@ -578,23 +579,24 @@
 }
 
 bool verify_package(const unsigned char* package_data, size_t package_size) {
-    std::vector<Certificate> loadedKeys;
-    if (!load_keys(PUBLIC_KEYS_FILE, loadedKeys)) {
-        LOG(ERROR) << "Failed to load keys";
-        return false;
-    }
-    LOG(INFO) << loadedKeys.size() << " key(s) loaded from " << PUBLIC_KEYS_FILE;
+  std::vector<Certificate> loadedKeys;
+  if (!load_keys(PUBLIC_KEYS_FILE, loadedKeys)) {
+    LOG(ERROR) << "Failed to load keys";
+    return false;
+  }
+  LOG(INFO) << loadedKeys.size() << " key(s) loaded from " << PUBLIC_KEYS_FILE;
 
-    // Verify package.
-    ui->Print("Verifying update package...\n");
-    auto t0 = std::chrono::system_clock::now();
-    int err = verify_file(const_cast<unsigned char*>(package_data), package_size, loadedKeys);
-    std::chrono::duration<double> duration = std::chrono::system_clock::now() - t0;
-    ui->Print("Update package verification took %.1f s (result %d).\n", duration.count(), err);
-    if (err != VERIFY_SUCCESS) {
-        LOG(ERROR) << "Signature verification failed";
-        LOG(ERROR) << "error: " << kZipVerificationFailure;
-        return false;
-    }
-    return true;
+  // Verify package.
+  ui->Print("Verifying update package...\n");
+  auto t0 = std::chrono::system_clock::now();
+  int err = verify_file(package_data, package_size, loadedKeys,
+                        std::bind(&RecoveryUI::SetProgress, ui, std::placeholders::_1));
+  std::chrono::duration<double> duration = std::chrono::system_clock::now() - t0;
+  ui->Print("Update package verification took %.1f s (result %d).\n", duration.count(), err);
+  if (err != VERIFY_SUCCESS) {
+    LOG(ERROR) << "Signature verification failed";
+    LOG(ERROR) << "error: " << kZipVerificationFailure;
+    return false;
+  }
+  return true;
 }
diff --git a/tests/Android.mk b/tests/Android.mk
index 65f736d..ff6e14c 100644
--- a/tests/Android.mk
+++ b/tests/Android.mk
@@ -120,7 +120,6 @@
     libupdater \
     libbootloader_message \
     libverifier \
-    libminui \
     libotautil \
     libmounts \
     libdivsufsort \
diff --git a/tests/component/verifier_test.cpp b/tests/component/verifier_test.cpp
index b740af9..07a8c96 100644
--- a/tests/component/verifier_test.cpp
+++ b/tests/component/verifier_test.cpp
@@ -22,93 +22,34 @@
 #include <sys/stat.h>
 #include <sys/types.h>
 
-#include <memory>
 #include <string>
 #include <vector>
 
-#include <openssl/sha.h>
-
+#include <android-base/file.h>
 #include <android-base/stringprintf.h>
-#include <ziparchive/zip_archive.h>
+#include <android-base/test_utils.h>
 
-#include "common.h"
 #include "common/test_constants.h"
 #include "otautil/SysUtil.h"
-#include "ui.h"
 #include "verifier.h"
 
-RecoveryUI* ui = NULL;
-
-class MockUI : public RecoveryUI {
-  bool Init(const std::string&) override {
-    return true;
-  }
-  void SetStage(int, int) override {}
-  void SetBackground(Icon /*icon*/) override {}
-  void SetSystemUpdateText(bool /*security_update*/) override {}
-
-  void SetProgressType(ProgressType /*determinate*/) override {}
-  void ShowProgress(float /*portion*/, float /*seconds*/) override {}
-  void SetProgress(float /*fraction*/) override {}
-
-  void ShowText(bool /*visible*/) override {}
-  bool IsTextVisible() override {
-    return false;
-  }
-  bool WasTextEverVisible() override {
-    return false;
-  }
-  void Print(const char* fmt, ...) override {
-    va_list ap;
-    va_start(ap, fmt);
-    vfprintf(stderr, fmt, ap);
-    va_end(ap);
-  }
-  void PrintOnScreenOnly(const char* fmt, ...) override {
-    va_list ap;
-    va_start(ap, fmt);
-    vfprintf(stderr, fmt, ap);
-    va_end(ap);
-  }
-  void ShowFile(const char*) override {}
-
-  void StartMenu(const char* const* /*headers*/, const char* const* /*items*/,
-                 int /*initial_selection*/) override {}
-  int SelectMenu(int /*sel*/) override {
-    return 0;
-  }
-  void EndMenu() override {}
-};
-
-void
-ui_print(const char* format, ...) {
-    va_list ap;
-    va_start(ap, format);
-    vfprintf(stdout, format, ap);
-    va_end(ap);
-}
-
 class VerifierTest : public testing::TestWithParam<std::vector<std::string>> {
-  public:
-    MemMapping memmap;
-    std::vector<Certificate> certs;
-
-    virtual void SetUp() {
-        std::vector<std::string> args = GetParam();
-        std::string package = from_testdata_base(args[0]);
-        if (sysMapFile(package.c_str(), &memmap) != 0) {
-            FAIL() << "Failed to mmap " << package << ": " << strerror(errno) << "\n";
-        }
-
-        for (auto it = ++(args.cbegin()); it != args.cend(); ++it) {
-            std::string public_key_file = from_testdata_base("testkey_" + *it + ".txt");
-            ASSERT_TRUE(load_keys(public_key_file.c_str(), certs));
-        }
+ protected:
+  void SetUp() override {
+    std::vector<std::string> args = GetParam();
+    std::string package = from_testdata_base(args[0]);
+    if (sysMapFile(package.c_str(), &memmap) != 0) {
+      FAIL() << "Failed to mmap " << package << ": " << strerror(errno) << "\n";
     }
 
-    static void SetUpTestCase() {
-        ui = new MockUI();
+    for (auto it = ++args.cbegin(); it != args.cend(); ++it) {
+      std::string public_key_file = from_testdata_base("testkey_" + *it + ".txt");
+      ASSERT_TRUE(load_keys(public_key_file.c_str(), certs));
     }
+  }
+
+  MemMapping memmap;
+  std::vector<Certificate> certs;
 };
 
 class VerifierSuccessTest : public VerifierTest {
@@ -117,48 +58,105 @@
 class VerifierFailureTest : public VerifierTest {
 };
 
+TEST(VerifierTest, load_keys_multiple_keys) {
+  std::string testkey_v4;
+  ASSERT_TRUE(android::base::ReadFileToString(from_testdata_base("testkey_v4.txt"), &testkey_v4));
+
+  std::string testkey_v3;
+  ASSERT_TRUE(android::base::ReadFileToString(from_testdata_base("testkey_v3.txt"), &testkey_v3));
+
+  std::string keys = testkey_v4 + "," + testkey_v3 + "," + testkey_v4;
+  TemporaryFile key_file1;
+  ASSERT_TRUE(android::base::WriteStringToFile(keys, key_file1.path));
+  std::vector<Certificate> certs;
+  ASSERT_TRUE(load_keys(key_file1.path, certs));
+  ASSERT_EQ(3U, certs.size());
+}
+
+TEST(VerifierTest, load_keys_invalid_keys) {
+  std::vector<Certificate> certs;
+  ASSERT_FALSE(load_keys("/doesntexist", certs));
+
+  // Empty file.
+  TemporaryFile key_file1;
+  ASSERT_FALSE(load_keys(key_file1.path, certs));
+
+  // Invalid contents.
+  ASSERT_TRUE(android::base::WriteStringToFile("invalid", key_file1.path));
+  ASSERT_FALSE(load_keys(key_file1.path, certs));
+
+  std::string testkey_v4;
+  ASSERT_TRUE(android::base::ReadFileToString(from_testdata_base("testkey_v4.txt"), &testkey_v4));
+
+  // Invalid key version: "v4 ..." => "v6 ...".
+  std::string invalid_key2(testkey_v4);
+  invalid_key2[1] = '6';
+  TemporaryFile key_file2;
+  ASSERT_TRUE(android::base::WriteStringToFile(invalid_key2, key_file2.path));
+  ASSERT_FALSE(load_keys(key_file2.path, certs));
+
+  // Invalid key content: inserted extra bytes ",2209831334".
+  std::string invalid_key3(testkey_v4);
+  invalid_key3.insert(invalid_key2.size() - 2, ",2209831334");
+  TemporaryFile key_file3;
+  ASSERT_TRUE(android::base::WriteStringToFile(invalid_key3, key_file3.path));
+  ASSERT_FALSE(load_keys(key_file3.path, certs));
+
+  // Invalid key: the last key must not end with an extra ','.
+  std::string invalid_key4 = testkey_v4 + ",";
+  TemporaryFile key_file4;
+  ASSERT_TRUE(android::base::WriteStringToFile(invalid_key4, key_file4.path));
+  ASSERT_FALSE(load_keys(key_file4.path, certs));
+
+  // Invalid key separator.
+  std::string invalid_key5 = testkey_v4 + ";" + testkey_v4;
+  TemporaryFile key_file5;
+  ASSERT_TRUE(android::base::WriteStringToFile(invalid_key5, key_file5.path));
+  ASSERT_FALSE(load_keys(key_file5.path, certs));
+}
+
 TEST_P(VerifierSuccessTest, VerifySucceed) {
-    ASSERT_EQ(verify_file(memmap.addr, memmap.length, certs), VERIFY_SUCCESS);
+  ASSERT_EQ(verify_file(memmap.addr, memmap.length, certs, nullptr), VERIFY_SUCCESS);
 }
 
 TEST_P(VerifierFailureTest, VerifyFailure) {
-    ASSERT_EQ(verify_file(memmap.addr, memmap.length, certs), VERIFY_FAILURE);
+  ASSERT_EQ(verify_file(memmap.addr, memmap.length, certs, nullptr), VERIFY_FAILURE);
 }
 
 INSTANTIATE_TEST_CASE_P(SingleKeySuccess, VerifierSuccessTest,
-        ::testing::Values(
-            std::vector<std::string>({"otasigned_v1.zip", "v1"}),
-            std::vector<std::string>({"otasigned_v2.zip", "v2"}),
-            std::vector<std::string>({"otasigned_v3.zip", "v3"}),
-            std::vector<std::string>({"otasigned_v4.zip", "v4"}),
-            std::vector<std::string>({"otasigned_v5.zip", "v5"})));
+    ::testing::Values(
+      std::vector<std::string>({"otasigned_v1.zip", "v1"}),
+      std::vector<std::string>({"otasigned_v2.zip", "v2"}),
+      std::vector<std::string>({"otasigned_v3.zip", "v3"}),
+      std::vector<std::string>({"otasigned_v4.zip", "v4"}),
+      std::vector<std::string>({"otasigned_v5.zip", "v5"})));
 
 INSTANTIATE_TEST_CASE_P(MultiKeySuccess, VerifierSuccessTest,
-        ::testing::Values(
-            std::vector<std::string>({"otasigned_v1.zip", "v1", "v2"}),
-            std::vector<std::string>({"otasigned_v2.zip", "v5", "v2"}),
-            std::vector<std::string>({"otasigned_v3.zip", "v5", "v1", "v3"}),
-            std::vector<std::string>({"otasigned_v4.zip", "v5", "v1", "v4"}),
-            std::vector<std::string>({"otasigned_v5.zip", "v4", "v1", "v5"})));
+    ::testing::Values(
+      std::vector<std::string>({"otasigned_v1.zip", "v1", "v2"}),
+      std::vector<std::string>({"otasigned_v2.zip", "v5", "v2"}),
+      std::vector<std::string>({"otasigned_v3.zip", "v5", "v1", "v3"}),
+      std::vector<std::string>({"otasigned_v4.zip", "v5", "v1", "v4"}),
+      std::vector<std::string>({"otasigned_v5.zip", "v4", "v1", "v5"})));
 
 INSTANTIATE_TEST_CASE_P(WrongKey, VerifierFailureTest,
-        ::testing::Values(
-            std::vector<std::string>({"otasigned_v1.zip", "v2"}),
-            std::vector<std::string>({"otasigned_v2.zip", "v1"}),
-            std::vector<std::string>({"otasigned_v3.zip", "v5"}),
-            std::vector<std::string>({"otasigned_v4.zip", "v5"}),
-            std::vector<std::string>({"otasigned_v5.zip", "v3"})));
+    ::testing::Values(
+      std::vector<std::string>({"otasigned_v1.zip", "v2"}),
+      std::vector<std::string>({"otasigned_v2.zip", "v1"}),
+      std::vector<std::string>({"otasigned_v3.zip", "v5"}),
+      std::vector<std::string>({"otasigned_v4.zip", "v5"}),
+      std::vector<std::string>({"otasigned_v5.zip", "v3"})));
 
 INSTANTIATE_TEST_CASE_P(WrongHash, VerifierFailureTest,
-        ::testing::Values(
-            std::vector<std::string>({"otasigned_v1.zip", "v3"}),
-            std::vector<std::string>({"otasigned_v2.zip", "v4"}),
-            std::vector<std::string>({"otasigned_v3.zip", "v1"}),
-            std::vector<std::string>({"otasigned_v4.zip", "v2"})));
+    ::testing::Values(
+      std::vector<std::string>({"otasigned_v1.zip", "v3"}),
+      std::vector<std::string>({"otasigned_v2.zip", "v4"}),
+      std::vector<std::string>({"otasigned_v3.zip", "v1"}),
+      std::vector<std::string>({"otasigned_v4.zip", "v2"})));
 
 INSTANTIATE_TEST_CASE_P(BadPackage, VerifierFailureTest,
-        ::testing::Values(
-            std::vector<std::string>({"random.zip", "v1"}),
-            std::vector<std::string>({"fake-eocd.zip", "v1"}),
-            std::vector<std::string>({"alter-metadata.zip", "v1"}),
-            std::vector<std::string>({"alter-footer.zip", "v1"})));
+    ::testing::Values(
+      std::vector<std::string>({"random.zip", "v1"}),
+      std::vector<std::string>({"fake-eocd.zip", "v1"}),
+      std::vector<std::string>({"alter-metadata.zip", "v1"}),
+      std::vector<std::string>({"alter-footer.zip", "v1"})));
diff --git a/tests/unit/asn1_decoder_test.cpp b/tests/unit/asn1_decoder_test.cpp
index af96d87..997639d 100644
--- a/tests/unit/asn1_decoder_test.cpp
+++ b/tests/unit/asn1_decoder_test.cpp
@@ -39,7 +39,7 @@
     EXPECT_EQ(NULL, asn1_set_get(ctx));
     EXPECT_FALSE(asn1_sequence_next(ctx));
 
-    uint8_t* junk;
+    const uint8_t* junk;
     size_t length;
     EXPECT_FALSE(asn1_oid_get(ctx, &junk, &length));
     EXPECT_FALSE(asn1_octet_string_get(ctx, &junk, &length));
@@ -68,7 +68,7 @@
     asn1_context_t* ptr = asn1_constructed_get(ctx);
     ASSERT_NE((asn1_context_t*)NULL, ptr);
     EXPECT_EQ(5, asn1_constructed_type(ptr));
-    uint8_t* oid;
+    const uint8_t* oid;
     size_t length;
     EXPECT_FALSE(asn1_oid_get(ptr, &oid, &length));
     asn1_context_free(ptr);
@@ -81,7 +81,7 @@
     asn1_context_t* ptr = asn1_constructed_get(ctx);
     ASSERT_NE((asn1_context_t*)NULL, ptr);
     EXPECT_EQ(5, asn1_constructed_type(ptr));
-    uint8_t* oid;
+    const uint8_t* oid;
     size_t length;
     ASSERT_TRUE(asn1_oid_get(ptr, &oid, &length));
     EXPECT_EQ(1U, length);
@@ -103,7 +103,7 @@
                             0x06, 0x01, 0xA5, };
     asn1_context_t* ctx = asn1_context_new(data, sizeof(data));
     ASSERT_TRUE(asn1_constructed_skip_all(ctx));
-    uint8_t* oid;
+    const uint8_t* oid;
     size_t length;
     ASSERT_TRUE(asn1_oid_get(ctx, &oid, &length));
     EXPECT_EQ(1U, length);
@@ -123,7 +123,7 @@
     asn1_context_t* ctx = asn1_context_new(data, sizeof(data));
     asn1_context_t* ptr = asn1_sequence_get(ctx);
     ASSERT_NE((asn1_context_t*)NULL, ptr);
-    uint8_t* oid;
+    const uint8_t* oid;
     size_t length;
     EXPECT_FALSE(asn1_oid_get(ptr, &oid, &length));
     asn1_context_free(ptr);
@@ -135,7 +135,7 @@
     asn1_context_t* ctx = asn1_context_new(data, sizeof(data));
     asn1_context_t* ptr = asn1_sequence_get(ctx);
     ASSERT_NE((asn1_context_t*)NULL, ptr);
-    uint8_t* oid;
+    const uint8_t* oid;
     size_t length;
     ASSERT_TRUE(asn1_oid_get(ptr, &oid, &length));
     EXPECT_EQ(1U, length);
@@ -156,7 +156,7 @@
     asn1_context_t* ctx = asn1_context_new(data, sizeof(data));
     asn1_context_t* ptr = asn1_set_get(ctx);
     ASSERT_NE((asn1_context_t*)NULL, ptr);
-    uint8_t* oid;
+    const uint8_t* oid;
     size_t length;
     EXPECT_FALSE(asn1_oid_get(ptr, &oid, &length));
     asn1_context_free(ptr);
@@ -168,7 +168,7 @@
     asn1_context_t* ctx = asn1_context_new(data, sizeof(data));
     asn1_context_t* ptr = asn1_set_get(ctx);
     ASSERT_NE((asn1_context_t*)NULL, ptr);
-    uint8_t* oid;
+    const uint8_t* oid;
     size_t length;
     ASSERT_TRUE(asn1_oid_get(ptr, &oid, &length));
     EXPECT_EQ(1U, length);
@@ -180,7 +180,7 @@
 TEST_F(Asn1DecoderTest, OidGet_LengthZero_Failure) {
     uint8_t data[] = { 0x06, 0x00, 0x01, };
     asn1_context_t* ctx = asn1_context_new(data, sizeof(data));
-    uint8_t* oid;
+    const uint8_t* oid;
     size_t length;
     EXPECT_FALSE(asn1_oid_get(ctx, &oid, &length));
     asn1_context_free(ctx);
@@ -189,7 +189,7 @@
 TEST_F(Asn1DecoderTest, OidGet_TooSmall_Failure) {
     uint8_t data[] = { 0x06, 0x01, };
     asn1_context_t* ctx = asn1_context_new(data, sizeof(data));
-    uint8_t* oid;
+    const uint8_t* oid;
     size_t length;
     EXPECT_FALSE(asn1_oid_get(ctx, &oid, &length));
     asn1_context_free(ctx);
@@ -198,7 +198,7 @@
 TEST_F(Asn1DecoderTest, OidGet_Success) {
     uint8_t data[] = { 0x06, 0x01, 0x99, };
     asn1_context_t* ctx = asn1_context_new(data, sizeof(data));
-    uint8_t* oid;
+    const uint8_t* oid;
     size_t length;
     ASSERT_TRUE(asn1_oid_get(ctx, &oid, &length));
     EXPECT_EQ(1U, length);
@@ -209,7 +209,7 @@
 TEST_F(Asn1DecoderTest, OctetStringGet_LengthZero_Failure) {
     uint8_t data[] = { 0x04, 0x00, 0x55, };
     asn1_context_t* ctx = asn1_context_new(data, sizeof(data));
-    uint8_t* string;
+    const uint8_t* string;
     size_t length;
     ASSERT_FALSE(asn1_octet_string_get(ctx, &string, &length));
     asn1_context_free(ctx);
@@ -218,7 +218,7 @@
 TEST_F(Asn1DecoderTest, OctetStringGet_TooSmall_Failure) {
     uint8_t data[] = { 0x04, 0x01, };
     asn1_context_t* ctx = asn1_context_new(data, sizeof(data));
-    uint8_t* string;
+    const uint8_t* string;
     size_t length;
     ASSERT_FALSE(asn1_octet_string_get(ctx, &string, &length));
     asn1_context_free(ctx);
@@ -227,7 +227,7 @@
 TEST_F(Asn1DecoderTest, OctetStringGet_Success) {
     uint8_t data[] = { 0x04, 0x01, 0xAA, };
     asn1_context_t* ctx = asn1_context_new(data, sizeof(data));
-    uint8_t* string;
+    const uint8_t* string;
     size_t length;
     ASSERT_TRUE(asn1_octet_string_get(ctx, &string, &length));
     EXPECT_EQ(1U, length);
diff --git a/verifier.cpp b/verifier.cpp
index 44098f7..fa344d7 100644
--- a/verifier.cpp
+++ b/verifier.cpp
@@ -22,7 +22,9 @@
 #include <string.h>
 
 #include <algorithm>
+#include <functional>
 #include <memory>
+#include <vector>
 
 #include <android-base/logging.h>
 #include <openssl/bn.h>
@@ -30,9 +32,7 @@
 #include <openssl/obj_mac.h>
 
 #include "asn1_decoder.h"
-#include "common.h"
 #include "print_sha1.h"
-#include "ui.h"
 
 static constexpr size_t MiB = 1024 * 1024;
 
@@ -61,248 +61,238 @@
  *             SEQUENCE (SignatureAlgorithmIdentifier)
  *             OCTET STRING (SignatureValue)
  */
-static bool read_pkcs7(uint8_t* pkcs7_der, size_t pkcs7_der_len, uint8_t** sig_der,
-        size_t* sig_der_length) {
-    asn1_context_t* ctx = asn1_context_new(pkcs7_der, pkcs7_der_len);
-    if (ctx == NULL) {
-        return false;
-    }
+static bool read_pkcs7(const uint8_t* pkcs7_der, size_t pkcs7_der_len,
+                       std::vector<uint8_t>* sig_der) {
+  CHECK(sig_der != nullptr);
+  sig_der->clear();
 
-    asn1_context_t* pkcs7_seq = asn1_sequence_get(ctx);
-    if (pkcs7_seq != NULL && asn1_sequence_next(pkcs7_seq)) {
-        asn1_context_t *signed_data_app = asn1_constructed_get(pkcs7_seq);
-        if (signed_data_app != NULL) {
-            asn1_context_t* signed_data_seq = asn1_sequence_get(signed_data_app);
-            if (signed_data_seq != NULL
-                    && asn1_sequence_next(signed_data_seq)
-                    && asn1_sequence_next(signed_data_seq)
-                    && asn1_sequence_next(signed_data_seq)
-                    && asn1_constructed_skip_all(signed_data_seq)) {
-                asn1_context_t *sig_set = asn1_set_get(signed_data_seq);
-                if (sig_set != NULL) {
-                    asn1_context_t* sig_seq = asn1_sequence_get(sig_set);
-                    if (sig_seq != NULL
-                            && asn1_sequence_next(sig_seq)
-                            && asn1_sequence_next(sig_seq)
-                            && asn1_sequence_next(sig_seq)
-                            && asn1_sequence_next(sig_seq)) {
-                        uint8_t* sig_der_ptr;
-                        if (asn1_octet_string_get(sig_seq, &sig_der_ptr, sig_der_length)) {
-                            *sig_der = (uint8_t*) malloc(*sig_der_length);
-                            if (*sig_der != NULL) {
-                                memcpy(*sig_der, sig_der_ptr, *sig_der_length);
-                            }
-                        }
-                        asn1_context_free(sig_seq);
-                    }
-                    asn1_context_free(sig_set);
-                }
-                asn1_context_free(signed_data_seq);
+  asn1_context_t* ctx = asn1_context_new(pkcs7_der, pkcs7_der_len);
+  if (ctx == NULL) {
+    return false;
+  }
+
+  asn1_context_t* pkcs7_seq = asn1_sequence_get(ctx);
+  if (pkcs7_seq != NULL && asn1_sequence_next(pkcs7_seq)) {
+    asn1_context_t *signed_data_app = asn1_constructed_get(pkcs7_seq);
+    if (signed_data_app != NULL) {
+      asn1_context_t* signed_data_seq = asn1_sequence_get(signed_data_app);
+      if (signed_data_seq != NULL
+          && asn1_sequence_next(signed_data_seq)
+          && asn1_sequence_next(signed_data_seq)
+          && asn1_sequence_next(signed_data_seq)
+          && asn1_constructed_skip_all(signed_data_seq)) {
+        asn1_context_t *sig_set = asn1_set_get(signed_data_seq);
+        if (sig_set != NULL) {
+          asn1_context_t* sig_seq = asn1_sequence_get(sig_set);
+          if (sig_seq != NULL
+              && asn1_sequence_next(sig_seq)
+              && asn1_sequence_next(sig_seq)
+              && asn1_sequence_next(sig_seq)
+              && asn1_sequence_next(sig_seq)) {
+            const uint8_t* sig_der_ptr;
+            size_t sig_der_length;
+            if (asn1_octet_string_get(sig_seq, &sig_der_ptr, &sig_der_length)) {
+              sig_der->resize(sig_der_length);
+              std::copy(sig_der_ptr, sig_der_ptr + sig_der_length, sig_der->begin());
             }
-            asn1_context_free(signed_data_app);
+            asn1_context_free(sig_seq);
+          }
+          asn1_context_free(sig_set);
         }
-        asn1_context_free(pkcs7_seq);
+        asn1_context_free(signed_data_seq);
+      }
+      asn1_context_free(signed_data_app);
     }
-    asn1_context_free(ctx);
+    asn1_context_free(pkcs7_seq);
+  }
+  asn1_context_free(ctx);
 
-    return *sig_der != NULL;
+  return !sig_der->empty();
 }
 
-// Look for an RSA signature embedded in the .ZIP file comment given
-// the path to the zip.  Verify it matches one of the given public
-// keys.
-//
-// Return VERIFY_SUCCESS, VERIFY_FAILURE (if any error is encountered
-// or no key matches the signature).
+/*
+ * Looks for an RSA signature embedded in the .ZIP file comment given the path to the zip. Verifies
+ * that it matches one of the given public keys. A callback function can be optionally provided for
+ * posting the progress.
+ *
+ * Returns VERIFY_SUCCESS or VERIFY_FAILURE (if any error is encountered or no key matches the
+ * signature).
+ */
+int verify_file(const unsigned char* addr, size_t length, const std::vector<Certificate>& keys,
+                const std::function<void(float)>& set_progress) {
+  if (set_progress) {
+    set_progress(0.0);
+  }
 
-int verify_file(unsigned char* addr, size_t length,
-                const std::vector<Certificate>& keys) {
-    ui->SetProgress(0.0);
-
-    // An archive with a whole-file signature will end in six bytes:
-    //
-    //   (2-byte signature start) $ff $ff (2-byte comment size)
-    //
-    // (As far as the ZIP format is concerned, these are part of the
-    // archive comment.)  We start by reading this footer, this tells
-    // us how far back from the end we have to start reading to find
-    // the whole comment.
+  // An archive with a whole-file signature will end in six bytes:
+  //
+  //   (2-byte signature start) $ff $ff (2-byte comment size)
+  //
+  // (As far as the ZIP format is concerned, these are part of the archive comment.) We start by
+  // reading this footer, this tells us how far back from the end we have to start reading to find
+  // the whole comment.
 
 #define FOOTER_SIZE 6
 
-    if (length < FOOTER_SIZE) {
-        LOG(ERROR) << "not big enough to contain footer";
-        return VERIFY_FAILURE;
-    }
+  if (length < FOOTER_SIZE) {
+    LOG(ERROR) << "not big enough to contain footer";
+    return VERIFY_FAILURE;
+  }
 
-    unsigned char* footer = addr + length - FOOTER_SIZE;
+  const unsigned char* footer = addr + length - FOOTER_SIZE;
 
-    if (footer[2] != 0xff || footer[3] != 0xff) {
-        LOG(ERROR) << "footer is wrong";
-        return VERIFY_FAILURE;
-    }
+  if (footer[2] != 0xff || footer[3] != 0xff) {
+    LOG(ERROR) << "footer is wrong";
+    return VERIFY_FAILURE;
+  }
 
-    size_t comment_size = footer[4] + (footer[5] << 8);
-    size_t signature_start = footer[0] + (footer[1] << 8);
-    LOG(INFO) << "comment is " << comment_size << " bytes; signature is " << signature_start
-              << " bytes from end";
+  size_t comment_size = footer[4] + (footer[5] << 8);
+  size_t signature_start = footer[0] + (footer[1] << 8);
+  LOG(INFO) << "comment is " << comment_size << " bytes; signature is " << signature_start
+            << " bytes from end";
 
-    if (signature_start <= FOOTER_SIZE) {
-        LOG(ERROR) << "Signature start is in the footer";
-        return VERIFY_FAILURE;
-    }
+  if (signature_start <= FOOTER_SIZE) {
+    LOG(ERROR) << "Signature start is in the footer";
+    return VERIFY_FAILURE;
+  }
 
 #define EOCD_HEADER_SIZE 22
 
-    // The end-of-central-directory record is 22 bytes plus any
-    // comment length.
-    size_t eocd_size = comment_size + EOCD_HEADER_SIZE;
+  // The end-of-central-directory record is 22 bytes plus any comment length.
+  size_t eocd_size = comment_size + EOCD_HEADER_SIZE;
 
-    if (length < eocd_size) {
-        LOG(ERROR) << "not big enough to contain EOCD";
-        return VERIFY_FAILURE;
-    }
-
-    // Determine how much of the file is covered by the signature.
-    // This is everything except the signature data and length, which
-    // includes all of the EOCD except for the comment length field (2
-    // bytes) and the comment data.
-    size_t signed_len = length - eocd_size + EOCD_HEADER_SIZE - 2;
-
-    unsigned char* eocd = addr + length - eocd_size;
-
-    // If this is really is the EOCD record, it will begin with the
-    // magic number $50 $4b $05 $06.
-    if (eocd[0] != 0x50 || eocd[1] != 0x4b ||
-        eocd[2] != 0x05 || eocd[3] != 0x06) {
-        LOG(ERROR) << "signature length doesn't match EOCD marker";
-        return VERIFY_FAILURE;
-    }
-
-    for (size_t i = 4; i < eocd_size-3; ++i) {
-        if (eocd[i  ] == 0x50 && eocd[i+1] == 0x4b &&
-            eocd[i+2] == 0x05 && eocd[i+3] == 0x06) {
-            // if the sequence $50 $4b $05 $06 appears anywhere after
-            // the real one, libziparchive will find the later (wrong) one,
-            // which could be exploitable.  Fail verification if
-            // this sequence occurs anywhere after the real one.
-            LOG(ERROR) << "EOCD marker occurs after start of EOCD";
-            return VERIFY_FAILURE;
-        }
-    }
-
-    bool need_sha1 = false;
-    bool need_sha256 = false;
-    for (const auto& key : keys) {
-        switch (key.hash_len) {
-            case SHA_DIGEST_LENGTH: need_sha1 = true; break;
-            case SHA256_DIGEST_LENGTH: need_sha256 = true; break;
-        }
-    }
-
-    SHA_CTX sha1_ctx;
-    SHA256_CTX sha256_ctx;
-    SHA1_Init(&sha1_ctx);
-    SHA256_Init(&sha256_ctx);
-
-    double frac = -1.0;
-    size_t so_far = 0;
-    while (so_far < signed_len) {
-        // On a Nexus 5X, experiment showed 16MiB beat 1MiB by 6% faster for a
-        // 1196MiB full OTA and 60% for an 89MiB incremental OTA.
-        // http://b/28135231.
-        size_t size = std::min(signed_len - so_far, 16 * MiB);
-
-        if (need_sha1) SHA1_Update(&sha1_ctx, addr + so_far, size);
-        if (need_sha256) SHA256_Update(&sha256_ctx, addr + so_far, size);
-        so_far += size;
-
-        double f = so_far / (double)signed_len;
-        if (f > frac + 0.02 || size == so_far) {
-            ui->SetProgress(f);
-            frac = f;
-        }
-    }
-
-    uint8_t sha1[SHA_DIGEST_LENGTH];
-    SHA1_Final(sha1, &sha1_ctx);
-    uint8_t sha256[SHA256_DIGEST_LENGTH];
-    SHA256_Final(sha256, &sha256_ctx);
-
-    uint8_t* sig_der = nullptr;
-    size_t sig_der_length = 0;
-
-    uint8_t* signature = eocd + eocd_size - signature_start;
-    size_t signature_size = signature_start - FOOTER_SIZE;
-
-    LOG(INFO) << "signature (offset: " << std::hex << (length - signature_start) << ", length: "
-              << signature_size << "): " << print_hex(signature, signature_size);
-
-    if (!read_pkcs7(signature, signature_size, &sig_der, &sig_der_length)) {
-        LOG(ERROR) << "Could not find signature DER block";
-        return VERIFY_FAILURE;
-    }
-
-    /*
-     * Check to make sure at least one of the keys matches the signature. Since
-     * any key can match, we need to try each before determining a verification
-     * failure has happened.
-     */
-    size_t i = 0;
-    for (const auto& key : keys) {
-        const uint8_t* hash;
-        int hash_nid;
-        switch (key.hash_len) {
-            case SHA_DIGEST_LENGTH:
-                hash = sha1;
-                hash_nid = NID_sha1;
-                break;
-            case SHA256_DIGEST_LENGTH:
-                hash = sha256;
-                hash_nid = NID_sha256;
-                break;
-            default:
-                continue;
-        }
-
-        // The 6 bytes is the "(signature_start) $ff $ff (comment_size)" that
-        // the signing tool appends after the signature itself.
-        if (key.key_type == Certificate::KEY_TYPE_RSA) {
-            if (!RSA_verify(hash_nid, hash, key.hash_len, sig_der,
-                            sig_der_length, key.rsa.get())) {
-                LOG(INFO) << "failed to verify against RSA key " << i;
-                continue;
-            }
-
-            LOG(INFO) << "whole-file signature verified against RSA key " << i;
-            free(sig_der);
-            return VERIFY_SUCCESS;
-        } else if (key.key_type == Certificate::KEY_TYPE_EC
-                && key.hash_len == SHA256_DIGEST_LENGTH) {
-            if (!ECDSA_verify(0, hash, key.hash_len, sig_der,
-                              sig_der_length, key.ec.get())) {
-                LOG(INFO) << "failed to verify against EC key " << i;
-                continue;
-            }
-
-            LOG(INFO) << "whole-file signature verified against EC key " << i;
-            free(sig_der);
-            return VERIFY_SUCCESS;
-        } else {
-            LOG(INFO) << "Unknown key type " << key.key_type;
-        }
-        i++;
-    }
-
-    if (need_sha1) {
-        LOG(INFO) << "SHA-1 digest: " << print_hex(sha1, SHA_DIGEST_LENGTH);
-    }
-    if (need_sha256) {
-        LOG(INFO) << "SHA-256 digest: " << print_hex(sha256, SHA256_DIGEST_LENGTH);
-    }
-    free(sig_der);
-    LOG(ERROR) << "failed to verify whole-file signature";
+  if (length < eocd_size) {
+    LOG(ERROR) << "not big enough to contain EOCD";
     return VERIFY_FAILURE;
+  }
+
+  // Determine how much of the file is covered by the signature. This is everything except the
+  // signature data and length, which includes all of the EOCD except for the comment length field
+  // (2 bytes) and the comment data.
+  size_t signed_len = length - eocd_size + EOCD_HEADER_SIZE - 2;
+
+  const unsigned char* eocd = addr + length - eocd_size;
+
+  // If this is really is the EOCD record, it will begin with the magic number $50 $4b $05 $06.
+  if (eocd[0] != 0x50 || eocd[1] != 0x4b || eocd[2] != 0x05 || eocd[3] != 0x06) {
+    LOG(ERROR) << "signature length doesn't match EOCD marker";
+    return VERIFY_FAILURE;
+  }
+
+  for (size_t i = 4; i < eocd_size-3; ++i) {
+    if (eocd[i] == 0x50 && eocd[i+1] == 0x4b && eocd[i+2] == 0x05 && eocd[i+3] == 0x06) {
+      // If the sequence $50 $4b $05 $06 appears anywhere after the real one, libziparchive will
+      // find the later (wrong) one, which could be exploitable. Fail the verification if this
+      // sequence occurs anywhere after the real one.
+      LOG(ERROR) << "EOCD marker occurs after start of EOCD";
+      return VERIFY_FAILURE;
+    }
+  }
+
+  bool need_sha1 = false;
+  bool need_sha256 = false;
+  for (const auto& key : keys) {
+    switch (key.hash_len) {
+      case SHA_DIGEST_LENGTH: need_sha1 = true; break;
+      case SHA256_DIGEST_LENGTH: need_sha256 = true; break;
+    }
+  }
+
+  SHA_CTX sha1_ctx;
+  SHA256_CTX sha256_ctx;
+  SHA1_Init(&sha1_ctx);
+  SHA256_Init(&sha256_ctx);
+
+  double frac = -1.0;
+  size_t so_far = 0;
+  while (so_far < signed_len) {
+    // On a Nexus 5X, experiment showed 16MiB beat 1MiB by 6% faster for a
+    // 1196MiB full OTA and 60% for an 89MiB incremental OTA.
+    // http://b/28135231.
+    size_t size = std::min(signed_len - so_far, 16 * MiB);
+
+    if (need_sha1) SHA1_Update(&sha1_ctx, addr + so_far, size);
+    if (need_sha256) SHA256_Update(&sha256_ctx, addr + so_far, size);
+    so_far += size;
+
+    if (set_progress) {
+      double f = so_far / (double)signed_len;
+      if (f > frac + 0.02 || size == so_far) {
+        set_progress(f);
+        frac = f;
+      }
+    }
+  }
+
+  uint8_t sha1[SHA_DIGEST_LENGTH];
+  SHA1_Final(sha1, &sha1_ctx);
+  uint8_t sha256[SHA256_DIGEST_LENGTH];
+  SHA256_Final(sha256, &sha256_ctx);
+
+  const uint8_t* signature = eocd + eocd_size - signature_start;
+  size_t signature_size = signature_start - FOOTER_SIZE;
+
+  LOG(INFO) << "signature (offset: " << std::hex << (length - signature_start) << ", length: "
+            << signature_size << "): " << print_hex(signature, signature_size);
+
+  std::vector<uint8_t> sig_der;
+  if (!read_pkcs7(signature, signature_size, &sig_der)) {
+    LOG(ERROR) << "Could not find signature DER block";
+    return VERIFY_FAILURE;
+  }
+
+  // Check to make sure at least one of the keys matches the signature. Since any key can match,
+  // we need to try each before determining a verification failure has happened.
+  size_t i = 0;
+  for (const auto& key : keys) {
+    const uint8_t* hash;
+    int hash_nid;
+    switch (key.hash_len) {
+      case SHA_DIGEST_LENGTH:
+        hash = sha1;
+        hash_nid = NID_sha1;
+        break;
+      case SHA256_DIGEST_LENGTH:
+        hash = sha256;
+        hash_nid = NID_sha256;
+        break;
+      default:
+        continue;
+    }
+
+    // The 6 bytes is the "(signature_start) $ff $ff (comment_size)" that the signing tool appends
+    // after the signature itself.
+    if (key.key_type == Certificate::KEY_TYPE_RSA) {
+      if (!RSA_verify(hash_nid, hash, key.hash_len, sig_der.data(), sig_der.size(),
+                      key.rsa.get())) {
+        LOG(INFO) << "failed to verify against RSA key " << i;
+        continue;
+      }
+
+      LOG(INFO) << "whole-file signature verified against RSA key " << i;
+      return VERIFY_SUCCESS;
+    } else if (key.key_type == Certificate::KEY_TYPE_EC && key.hash_len == SHA256_DIGEST_LENGTH) {
+      if (!ECDSA_verify(0, hash, key.hash_len, sig_der.data(), sig_der.size(), key.ec.get())) {
+        LOG(INFO) << "failed to verify against EC key " << i;
+        continue;
+      }
+
+      LOG(INFO) << "whole-file signature verified against EC key " << i;
+      return VERIFY_SUCCESS;
+    } else {
+      LOG(INFO) << "Unknown key type " << key.key_type;
+    }
+    i++;
+  }
+
+  if (need_sha1) {
+    LOG(INFO) << "SHA-1 digest: " << print_hex(sha1, SHA_DIGEST_LENGTH);
+  }
+  if (need_sha256) {
+    LOG(INFO) << "SHA-256 digest: " << print_hex(sha256, SHA256_DIGEST_LENGTH);
+  }
+  LOG(ERROR) << "failed to verify whole-file signature";
+  return VERIFY_FAILURE;
 }
 
 std::unique_ptr<RSA, RSADeleter> parse_rsa_key(FILE* file, uint32_t exponent) {
diff --git a/verifier.h b/verifier.h
index 58083fe..6bee749 100644
--- a/verifier.h
+++ b/verifier.h
@@ -17,6 +17,7 @@
 #ifndef _RECOVERY_VERIFIER_H
 #define _RECOVERY_VERIFIER_H
 
+#include <functional>
 #include <memory>
 #include <vector>
 
@@ -58,13 +59,14 @@
     std::unique_ptr<EC_KEY, ECKEYDeleter> ec;
 };
 
-/* addr and length define a an update package file that has been
- * loaded (or mmap'ed, or whatever) into memory.  Verify that the file
- * is signed and the signature matches one of the given keys.  Return
- * one of the constants below.
+/*
+ * 'addr' and 'length' define an update package file that has been loaded (or mmap'ed, or
+ * whatever) into memory. Verifies that the file is signed and the signature matches one of the
+ * given keys. It optionally accepts a callback function for posting the progress to. Returns one
+ * of the constants of VERIFY_SUCCESS and VERIFY_FAILURE.
  */
-int verify_file(unsigned char* addr, size_t length,
-                const std::vector<Certificate>& keys);
+int verify_file(const unsigned char* addr, size_t length, const std::vector<Certificate>& keys,
+                const std::function<void(float)>& set_progress = nullptr);
 
 bool load_keys(const char* filename, std::vector<Certificate>& certs);