Split compos_key_service.

Split the code that implements the service from the code that starts
it as a binder service. This is preparation for also allowing it to be
started in a VM.

Bug: 193603140
Test: Run compos_key_host, connect to it via compos_key_cmd
Change-Id: I8f223ef19c9490dc349e1f677f670eedcf09dead
diff --git a/compos/Android.bp b/compos/Android.bp
index 1eb6716..ba270b8 100644
--- a/compos/Android.bp
+++ b/compos/Android.bp
@@ -67,8 +67,8 @@
 }
 
 rust_binary {
-    name: "compos_key_service",
-    srcs: ["src/compos_key_service.rs"],
+    name: "compos_key_host",
+    srcs: ["src/compos_key_host_main.rs"],
     edition: "2018",
     rustlibs: [
         "compos_aidl_interface-rust",
diff --git a/compos/apex/Android.bp b/compos/apex/Android.bp
index 2dded99..c4ab321 100644
--- a/compos/apex/Android.bp
+++ b/compos/apex/Android.bp
@@ -38,7 +38,7 @@
 
     binaries: [
         "compos_key_cmd",
-        "compos_key_service",
+        "compos_key_host",
         "compsvc",
         "compsvc_worker",
         "pvm_exec",
diff --git a/compos/src/compos_key_host_main.rs b/compos/src/compos_key_host_main.rs
new file mode 100644
index 0000000..28b069a
--- /dev/null
+++ b/compos/src/compos_key_host_main.rs
@@ -0,0 +1,45 @@
+// Copyright 2021, The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! Run the CompOS key management service in the host, using normal Binder.
+
+mod compos_key_service;
+
+use crate::compos_key_service::CompOsKeyService;
+use anyhow::{Context, Result};
+use compos_aidl_interface::aidl::com::android::compos::ICompOsKeyService::BnCompOsKeyService;
+use compos_aidl_interface::binder::{add_service, BinderFeatures, ProcessState};
+use log::{info, Level};
+
+const LOG_TAG: &str = "CompOsKeyService";
+const OUR_SERVICE_NAME: &str = "android.system.composkeyservice";
+
+fn main() -> Result<()> {
+    android_logger::init_once(
+        android_logger::Config::default().with_tag(LOG_TAG).with_min_level(Level::Trace),
+    );
+
+    // We need to start the thread pool for Binder to work properly.
+    ProcessState::start_thread_pool();
+
+    let service = CompOsKeyService::new()?;
+    let service = BnCompOsKeyService::new_binder(service, BinderFeatures::default());
+
+    add_service(OUR_SERVICE_NAME, service.as_binder()).context("Adding service failed")?;
+    info!("It's alive!");
+
+    ProcessState::join_thread_pool();
+
+    Ok(())
+}
diff --git a/compos/src/compos_key_service.rs b/compos/src/compos_key_service.rs
index 993ef20..6b62e0f 100644
--- a/compos/src/compos_key_service.rs
+++ b/compos/src/compos_key_service.rs
@@ -27,22 +27,17 @@
 };
 use anyhow::{anyhow, Context, Result};
 use compos_aidl_interface::aidl::com::android::compos::{
-    CompOsKeyData::CompOsKeyData,
-    ICompOsKeyService::{BnCompOsKeyService, ICompOsKeyService},
+    CompOsKeyData::CompOsKeyData, ICompOsKeyService::ICompOsKeyService,
 };
 use compos_aidl_interface::binder::{
-    self, add_service, get_interface, BinderFeatures, ExceptionCode, Interface, ProcessState,
-    Status, Strong,
+    self, get_interface, ExceptionCode, Interface, Status, Strong,
 };
-use log::{info, warn, Level};
+use log::warn;
 use ring::rand::{SecureRandom, SystemRandom};
 use ring::signature;
 use scopeguard::ScopeGuard;
 use std::ffi::CString;
 
-const LOG_TAG: &str = "CompOsKeyService";
-const OUR_SERVICE_NAME: &str = "android.system.composkeyservice";
-
 const KEYSTORE_SERVICE_NAME: &str = "android.system.keystore2.IKeystoreService/default";
 const COMPOS_NAMESPACE: i64 = 101;
 const PURPOSE_SIGN: KeyParameter =
@@ -65,7 +60,7 @@
 const KEY_DESCRIPTOR: KeyDescriptor =
     KeyDescriptor { domain: Domain::BLOB, nspace: COMPOS_NAMESPACE, alias: None, blob: None };
 
-struct CompOsKeyService {
+pub struct CompOsKeyService {
     random: SystemRandom,
     security_level: Strong<dyn IKeystoreSecurityLevel>,
 }
@@ -99,13 +94,16 @@
 }
 
 impl CompOsKeyService {
-    fn new(keystore_service: &Strong<dyn IKeystoreService>) -> Self {
-        Self {
+    pub fn new() -> Result<Self> {
+        let keystore_service = get_interface::<dyn IKeystoreService>(KEYSTORE_SERVICE_NAME)
+            .context("No Keystore service")?;
+
+        Ok(Self {
             random: SystemRandom::new(),
             security_level: keystore_service
                 .getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT)
-                .unwrap(),
-        }
+                .context("Getting SecurityLevel failed")?,
+        })
     }
 
     fn do_generate(&self) -> Result<CompOsKeyData> {
@@ -165,24 +163,3 @@
         signature.ok_or_else(|| anyhow!("No signature returned"))
     }
 }
-
-fn main() -> Result<()> {
-    android_logger::init_once(
-        android_logger::Config::default().with_tag(LOG_TAG).with_min_level(Level::Trace),
-    );
-
-    // We need to start the thread pool for Binder to work properly.
-    ProcessState::start_thread_pool();
-
-    let keystore_service = get_interface::<dyn IKeystoreService>(KEYSTORE_SERVICE_NAME)
-        .context("No Keystore service")?;
-    let service = CompOsKeyService::new(&keystore_service);
-    let service = BnCompOsKeyService::new_binder(service, BinderFeatures::default());
-
-    add_service(OUR_SERVICE_NAME, service.as_binder()).context("Adding service failed")?;
-    info!("It's alive!");
-
-    ProcessState::join_thread_pool();
-
-    Ok(())
-}