cli/
lib.rs

1// SPDX-License-Identifier: GPL-3-0-or-later
2// Copyright (c) 2025 Opinsys Oy
3// Copyright (c) 2024-2025 Jarkko Sakkinen
4
5#![deny(clippy::all)]
6#![deny(clippy::pedantic)]
7
8pub mod auth;
9pub mod cli;
10pub mod command;
11pub mod crypto;
12pub mod device;
13pub mod handle;
14pub mod io;
15pub mod job;
16pub mod key;
17pub mod pcr;
18pub mod policy;
19pub mod print;
20pub mod spinner;
21pub mod template;
22pub mod vtpm;
23
24/// A global flag to signal graceful teardown of the application.
25///
26/// Set by the Ctrl-C handler to allow the main loop to finish its current
27/// operation and perform necessary teardown (e.g., flushing TPM contexts)
28/// before exiting.
29pub static TEARDOWN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
30
31/// Serialize a type implementing `TpmBuild` type into `Vec<u8>`.
32///
33/// # Errors
34///
35/// Returns a `TpmError` if the object cannot be serialized into the buffer.
36pub fn write_object<T: tpm2_protocol::TpmBuild>(
37    obj: &T,
38) -> Result<Vec<u8>, tpm2_protocol::TpmError> {
39    let mut buf = vec![0u8; tpm2_protocol::constant::TPM_MAX_COMMAND_SIZE];
40    let len = {
41        let mut writer = tpm2_protocol::TpmWriter::new(&mut buf);
42        obj.build(&mut writer)?;
43        writer.len()
44    };
45    buf.truncate(len);
46    Ok(buf)
47}
48
49/// Parses a hexadecimal string with an optional "0x" prefix into a `u32`.
50///
51/// # Errors
52///
53/// Returns an error if the string is not a valid hexadecimal number.
54pub fn parse_hex_u32(hex_str: &str) -> Result<u32, std::num::ParseIntError> {
55    let hex_str = hex_str.strip_prefix("0x").unwrap_or(hex_str);
56    u32::from_str_radix(hex_str, 16)
57}