1use anyhow::Result;
6use cryptoki::object::{Attribute, ObjectHandle};
7use cryptoki::session::Session;
8use rand::prelude::*;
9use std::convert::AsRef;
10use std::fs::File;
11use std::ops::Range;
12use std::path::Path;
13
14use crate::error::HsmError;
15use crate::util::attribute::{AttrData, AttributeMap, AttributeType};
16use crate::util::escape::as_hex;
17
18pub fn search_spec_ex(
20 id: Option<&str>,
21 label: Option<&str>,
22 attr: Option<&AttributeMap>,
23) -> Result<Vec<Attribute>> {
24 let mut attr = attr.map_or(Default::default(), |s| s.clone());
25 if let Some(id) = id {
26 attr.insert(AttributeType::Id, AttrData::Str(id.into()));
27 }
28 if let Some(label) = label {
29 attr.insert(AttributeType::Label, AttrData::Str(label.into()));
30 }
31 if attr.is_empty() {
32 return Err(HsmError::NoSearchCriteria.into());
33 }
34 attr.to_vec()
35}
36
37pub fn search_spec(id: Option<&str>, label: Option<&str>) -> Result<Vec<Attribute>> {
38 search_spec_ex(id, label, None)
39}
40
41pub fn object_exists(session: &Session, id: Option<&str>, label: Option<&str>) -> Result<bool> {
43 let attr = search_spec(id, label)?;
44 let objects = session.find_objects(&attr)?;
45 Ok(!objects.is_empty())
46}
47
48pub fn no_object_exists(session: &Session, id: Option<&str>, label: Option<&str>) -> Result<()> {
50 if object_exists(session, id, label)? {
51 Err(HsmError::ObjectExists(id.unwrap_or("").into(), label.unwrap_or("").into()).into())
52 } else {
53 Ok(())
54 }
55}
56
57pub fn find_one_object(session: &Session, search: &[Attribute]) -> Result<ObjectHandle> {
58 let mut object = session.find_objects(search)?;
59 if object.is_empty() {
60 let spec = AttributeMap::from(search);
61 Err(HsmError::ObjectNotFound(serde_json::to_string(&spec)?).into())
62 } else if object.len() > 1 {
63 let spec = AttributeMap::from(search);
64 Err(HsmError::TooManyObjects(object.len(), serde_json::to_string(&spec)?).into())
65 } else {
66 Ok(object.remove(0))
67 }
68}
69
70pub fn random_id() -> String {
72 let id = random::<u64>();
73 as_hex(&id.to_le_bytes())
74}
75
76pub fn lockfile<P: AsRef<Path>>(path: P) -> Result<File> {
78 let path = path.as_ref();
79 log::info!("Waiting for lockfile {path:?}");
80 let lf = File::create(path)?;
81 rustix::fs::flock(&lf, rustix::fs::FlockOperation::LockExclusive)?;
82 log::info!("Lock acquired");
83 Ok(lf)
84}
85
86fn parse_usize(s: &str) -> Result<usize> {
87 if let Some(hex) = s.strip_prefix("0x") {
88 Ok(usize::from_str_radix(hex, 16)?)
89 } else {
90 Ok(s.parse::<usize>()?)
91 }
92}
93
94pub fn parse_range(s: &str) -> Result<Range<usize>> {
97 if let Some((a, b)) = s.split_once("..") {
98 let start = parse_usize(a)?;
99 let end = parse_usize(b)?;
100 if start < end {
101 Ok(Range { start, end })
102 } else {
103 Err(HsmError::Unsupported(format!("bad range: {s:?}")).into())
104 }
105 } else {
106 Err(HsmError::Unsupported(format!("bad range: {s:?}")).into())
107 }
108}