Skip to main content

optee_utee/
ta_session.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use crate::{Result, TeeParams, Uuid, tee_check_with_origin};
19use optee_utee_sys as raw;
20
21pub struct TaSessionBuilder<'a> {
22    target_uuid: Uuid,
23    timeout: u32,
24    params: Option<TeeParams<'a>>,
25}
26
27impl<'a> TaSessionBuilder<'a> {
28    /// Creates a new builder for the given TA UUID.
29    pub fn new(uuid: Uuid) -> Self {
30        Self {
31            target_uuid: uuid,
32            timeout: raw::TEE_TIMEOUT_INFINITE,
33            params: None,
34        }
35    }
36
37    /// Sets a custom timeout for the session opening.
38    pub fn with_timeout(mut self, timeout: u32) -> Self {
39        self.timeout = timeout;
40        self
41    }
42
43    /// Sets the parameters to be passed during session opening.
44    pub fn with_params(mut self, params: TeeParams<'a>) -> Self {
45        self.params = Some(params);
46        self
47    }
48
49    /// Builds and opens the `TaSession`. Returns an error if the session fails to open.
50    pub fn build(mut self) -> Result<TaSession> {
51        let mut err_origin: u32 = 0;
52        let mut raw_session: raw::TEE_TASessionHandle = core::ptr::null_mut();
53        // Store the raw parameters in their final location before taking a pointer to them.
54        // `TEE_Param` is `Copy`, so taking the pointer before moving the array into the
55        // `Option` could leave the pointer referring to the old stack location.
56        let raw_param_types = self.params.as_ref().map_or(0, TeeParams::raw_param_types);
57        let mut raw_params_opt = self.params.as_mut().map(|params| params.as_raw());
58        let raw_params_ptr = raw_params_opt
59            .as_mut()
60            .map_or(core::ptr::null_mut(), |raw_params| raw_params.as_mut_ptr());
61
62        // SAFETY:
63        // self.target_uuid.as_raw_ptr() provides a valid pointer to the UUID.
64        // raw_params.as_mut_ptr() provides a valid pointer to the parameters.
65        // The remaining arguments are either valid values or null/mut pointers as expected by the C API.
66        // For parameters that are intended to be modified by the call, the buffer constraints are checked later in update_from_raw().
67        tee_check_with_origin(
68            unsafe {
69                raw::TEE_OpenTASession(
70                    self.target_uuid.as_raw_ptr(),
71                    self.timeout,
72                    raw_param_types,
73                    raw_params_ptr,
74                    &mut raw_session,
75                    &mut err_origin,
76                )
77            },
78            err_origin,
79        )?;
80        // From this point on, ensure every error path closes the opened session.
81        let session = TaSession { raw: raw_session };
82        if let (Some(params), Some(raw_params)) = (&mut self.params, raw_params_opt) {
83            params.update_from_raw(&raw_params)?;
84        }
85
86        Ok(session)
87    }
88}
89
90pub struct TaSession {
91    raw: raw::TEE_TASessionHandle,
92}
93
94impl TaSession {
95    /// Invokes a command with the provided parameters using the session's default timeout.
96    /// Returns the result directly without allowing further method chaining.
97    pub fn invoke_command(&mut self, command_id: u32, params: &mut TeeParams) -> Result<()> {
98        self.invoke_command_with_timeout(command_id, params, raw::TEE_TIMEOUT_INFINITE)
99    }
100
101    pub fn invoke_command_with_timeout(
102        &mut self,
103        command_id: u32,
104        params: &mut TeeParams,
105        timeout: u32,
106    ) -> Result<()> {
107        let mut err_origin: u32 = 0;
108        let mut raw_params = params.as_raw();
109        let param_types = params.raw_param_types();
110
111        // SAFETY:
112        // self.raw is a valid pointer to an active session handle.
113        // raw_params.as_mut_ptr() yields a valid mutable pointer to the parameters array.
114        // The remaining arguments are either valid values or null/mutable pointers, as expected by the C API.
115        // For parameters that are intended to be modified by the call, the buffer constraints are checked later in update_from_raw().
116        tee_check_with_origin(
117            unsafe {
118                raw::TEE_InvokeTACommand(
119                    self.raw,
120                    timeout,
121                    command_id,
122                    param_types,
123                    raw_params.as_mut_ptr(),
124                    &mut err_origin,
125                )
126            },
127            err_origin,
128        )?;
129        // Update the parameters with the results
130        params.update_from_raw(&raw_params)?;
131        Ok(())
132    }
133}
134
135// Drop implementation to close the session
136impl Drop for TaSession {
137    fn drop(&mut self) {
138        // SAFETY:
139        // self.raw is a valid pointer to an active session handle.
140        // The function call is expected to clean up the session resources.
141        unsafe {
142            raw::TEE_CloseTASession(self.raw);
143        }
144    }
145}