Merge "apkdmverity: use uuid v1" am: 9d231b75cc am: 2db88c7331

Original change: https://android-review.googlesource.com/c/platform/packages/modules/Virtualization/+/1728854

Change-Id: Iab353d2605611b3a0a4b78d6167225d97a655590
diff --git a/apkverity/Cargo.toml b/apkverity/Cargo.toml
index bd0ab01..43100e5 100644
--- a/apkverity/Cargo.toml
+++ b/apkverity/Cargo.toml
@@ -13,7 +13,7 @@
 nix = "0.21"
 num-derive = "0.3"
 num-traits = "0.2"
-uuid = { version = "0.8", features = ["v4"] }
+uuid = { version = "0.8", features = ["v1"] }
 
 [dev-dependencies]
 tempfile = "3.2"
diff --git a/apkverity/src/dm.rs b/apkverity/src/dm.rs
index d1cd2eb..ec4248c 100644
--- a/apkverity/src/dm.rs
+++ b/apkverity/src/dm.rs
@@ -34,7 +34,6 @@
 use std::mem::size_of;
 use std::os::unix::io::AsRawFd;
 use std::path::{Path, PathBuf};
-use uuid::Uuid;
 
 mod sys;
 mod verity;
@@ -138,7 +137,7 @@
     pub fn create_device(&self, name: &str, target: &DmVerityTarget) -> Result<PathBuf> {
         // Step 1: create an empty device
         let mut data = DmIoctl::new(&name)?;
-        data.set_uuid(&uuid())?;
+        data.set_uuid(&uuid()?)?;
         dm_dev_create(&self, &mut data)?;
 
         // Step 2: load table onto the device
@@ -176,10 +175,14 @@
 }
 
 /// Used to derive a UUID that uniquely identifies a device mapper device when creating it.
-// TODO(jiyong): the v4 is a randomly generated UUID. We might want another version of UUID (e.g.
-// v3) where we can specify the namespace so that we can easily identify UUID's created for this
-// purpose. For now, this random UUID is fine because we are expected to have only "one" instance
-// of dm-verity device in Microdroid.
-fn uuid() -> String {
-    String::from(Uuid::new_v4().to_hyphenated().encode_lower(&mut Uuid::encode_buffer()))
+fn uuid() -> Result<String> {
+    use std::time::{SystemTime, UNIX_EPOCH};
+    use uuid::v1::{Context, Timestamp};
+    use uuid::Uuid;
+
+    let context = Context::new(0);
+    let now = SystemTime::now().duration_since(UNIX_EPOCH)?;
+    let ts = Timestamp::from_unix(&context, now.as_secs(), now.subsec_nanos());
+    let uuid = Uuid::new_v1(ts, "apkver".as_bytes())?;
+    Ok(String::from(uuid.to_hyphenated().encode_lower(&mut Uuid::encode_buffer())))
 }