tss_sapi/
utils.rs

1use std::env;
2use super::errors::*;
3use super::Context;
4
5/// Open a `Context` over a socket or the raw device based on the environment.
6///
7/// The TPM2 tools project relies on several environment variables to determine how
8/// to open the TPM2 context. If the environment variable `TPM2TOOLS_TCTI_NAME` is not
9/// present or has the value of "device" set, then a context is created pointing at
10/// a local device, with the device name pulled from the `TPM2TOOLS_DEVICE_FILE`
11/// environment variable.
12///
13/// If `TPM2TOOLS_TCTI_NAME` has the value "socket" set, then a context
14/// is created using a socket. The `TPM2TOOLS_SOCKET_ADDRESS` environment variable
15/// specifies the host to connect to and must be present. The `TPM2TOOLS_SOCKET_PORT`
16/// environment variable specifies the port to connect to and is optional.
17///
18/// # Examples
19///
20/// ```
21/// use tss_sapi::utils;
22///
23/// # fn foo() -> tss_sapi::Result<()> {
24/// let context = utils::open_context_from_env()?;
25/// # Ok(())
26/// # }
27/// ```
28pub fn open_context_from_env() -> Result<Context> {
29    // assume the device if the environment variable was not supplied
30    let tcti = env::var("TPM2TOOLS_TCTI_NAME").unwrap_or_else(|_| String::from("device"));
31
32    match tcti.as_str() {
33        #[cfg(feature = "tcti-socket")]
34        "socket" => {
35            let addr = env::var("TPM2TOOLS_SOCKET_ADDRESS").ok();
36            let port = match env::var("TPM2TOOLS_SOCKET_PORT").ok() {
37                None => None,
38                Some(v) => {
39                    Some(v.parse::<u16>().chain_err(|| "Unable to parse TPM2TOOLS_SOCKET_PORT")?)
40                }
41            };
42
43            // create a SAPI context and connect to the default TPM emulator
44            Context::socket(addr.as_ref().map(|v| v.as_ref()), port)
45                .chain_err(|| format!("Unable to connect to {:?}:{:?}", addr, port))
46        }
47        #[cfg(feature = "tcti-device")]
48        "device" => {
49            let dev = env::var("TPM2TOOLS_DEVICE_FILE").ok();
50
51            // create a SAPI context and connect to the
52            // device requested or the default device
53            Context::device(dev.as_ref().map(|v| v.as_ref()))
54                .chain_err(|| format!("Unable to connect to {:?}", dev))
55        }
56        _ => Err(ErrorKind::Msg("invalid TPM2TOOLS_TCTI_NAME value".into()).into()),
57    }
58}