Skip to main content

optee_utee/net/
optee.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 alloc::ffi::CString;
19use core::ptr;
20use optee_utee_sys as raw;
21
22use super::{Socket, SocketAdapter, SocketError};
23
24/// A setup parameter used for OP-TEE.
25pub struct Setup {
26    addr: CString,
27    port: u16,
28    version: raw::TEE_ipSocket_ipVersion,
29}
30
31impl Setup {
32    pub(crate) fn new(
33        addr: &str,
34        port: u16,
35        version: raw::TEE_ipSocket_ipVersion,
36    ) -> crate::Result<Self> {
37        Ok(Self {
38            addr: CString::new(addr).map_err(|_| crate::ErrorKind::BadParameters)?,
39            port,
40            version,
41        })
42    }
43    /// Construct a new IPv4 target parameter using the address and port. It
44    /// will return `BadParameters` if the address contains a `\0` character in
45    /// the middle.
46    pub fn new_v4(addr: &str, port: u16) -> crate::Result<Self> {
47        Self::new(addr, port, raw::TEE_ipSocket_ipVersion::TEE_IP_VERSION_4)
48    }
49    /// Construct a new IPv6 target parameter using the address and port. It
50    /// will return `BadParameters` if the address contains a `\0` character in
51    /// the middle.
52    pub fn new_v6(addr: &str, port: u16) -> crate::Result<Self> {
53        Self::new(addr, port, raw::TEE_ipSocket_ipVersion::TEE_IP_VERSION_6)
54    }
55}
56
57/// An adapter for TCP sockets in OP-TEE. Typically, it is not used directly,
58/// but can be employed for wrapper operations, such as traffic control within
59/// the TEE.
60pub struct TcpAdapter(raw::TEE_iSocketHandle);
61/// An adapter for UDP sockets in OP-TEE. Typically, it is not used directly,
62/// but can be employed for wrapper operations, such as traffic control within
63/// the TEE.
64pub struct UdpAdapter(raw::TEE_iSocketHandle);
65/// A TcpStream that is compatible with OP-TEE.
66pub type TcpStream = Socket<TcpAdapter>;
67/// A UdpSocket that is compatible with OP-TEE.
68pub type UdpSocket = Socket<UdpAdapter>;
69
70/// Maps a failed socket operation to a [`SocketError`], resolving the
71/// protocol-specific code that accompanies `TEE_ISOCKET_ERROR_PROTOCOL` and
72/// `TEE_ISOCKET_WARNING_PROTOCOL`.
73///
74/// `socket` must be the `TEE_iSocket` instance that created `handle`. The GP
75/// TEE Sockets API only allows a handle to be passed to methods of its own
76/// instance, and `error` reads the protocol state of that instance through it.
77fn handle_socket_operation_error(
78    socket: *const raw::TEE_iSocket,
79    handle: raw::TEE_iSocketHandle,
80    code: u32,
81) -> SocketError {
82    match code {
83        raw::TEE_ISOCKET_ERROR_PROTOCOL => {
84            let protocol_error = unsafe { ((*socket).error)(handle) };
85            SocketError::ErrorProtocol(protocol_error)
86        }
87        raw::TEE_ISOCKET_WARNING_PROTOCOL => {
88            let protocol_error = unsafe { ((*socket).error)(handle) };
89            SocketError::WarningProtocol(protocol_error)
90        }
91        _ => SocketError::from_raw_error(code, 0),
92    }
93}
94
95impl SocketAdapter for TcpAdapter {
96    type Setup = Setup;
97    type Handle = Self;
98
99    fn open(setup: Self::Setup) -> Result<Self::Handle, SocketError> {
100        let mut handle: raw::TEE_iSocketHandle = ptr::null_mut();
101        let mut protocol_error: u32 = 0;
102        let mut setup = raw::TEE_tcpSocket_Setup {
103            ipVersion: setup.version,
104            server_addr: setup.addr.as_ptr() as _,
105            server_port: setup.port,
106        };
107        let ret = unsafe {
108            ((*raw::TEE_tcpSocket).open)(
109                &mut handle,
110                &mut setup as *mut raw::TEE_tcpSocket_Setup as _,
111                &mut protocol_error,
112            )
113        };
114        match ret {
115            raw::TEE_SUCCESS => Ok(Self(handle)),
116            _ => Err(SocketError::from_raw_error(ret, protocol_error)),
117        }
118    }
119    fn send(handle: &mut Self::Handle, buf: &[u8], timeout: u32) -> Result<usize, SocketError> {
120        let mut length: u32 = buf.len() as _;
121        let ret = unsafe {
122            ((*raw::TEE_tcpSocket).send)(handle.0, buf.as_ptr() as _, &mut length, timeout)
123        };
124        match ret {
125            raw::TEE_SUCCESS => Ok(length as usize),
126            _ => Err(handle_socket_operation_error(
127                unsafe { raw::TEE_tcpSocket },
128                handle.0,
129                ret,
130            )),
131        }
132    }
133    fn recv(handle: &mut Self::Handle, buf: &mut [u8], timeout: u32) -> Result<usize, SocketError> {
134        let mut length: u32 = buf.len() as _;
135        let ret = unsafe {
136            ((*raw::TEE_tcpSocket).recv)(handle.0, buf.as_mut_ptr() as _, &mut length, timeout)
137        };
138        match ret {
139            raw::TEE_SUCCESS => Ok(length as usize),
140            _ => Err(handle_socket_operation_error(
141                unsafe { raw::TEE_tcpSocket },
142                handle.0,
143                ret,
144            )),
145        }
146    }
147}
148
149impl Drop for TcpAdapter {
150    fn drop(&mut self) {
151        // Ignore any errors on close.
152        unsafe {
153            ((*raw::TEE_tcpSocket).close)(self.0);
154        }
155    }
156}
157
158impl SocketAdapter for UdpAdapter {
159    type Setup = Setup;
160    type Handle = Self;
161
162    fn open(setup: Self::Setup) -> Result<Self::Handle, SocketError> {
163        let mut handle: raw::TEE_iSocketHandle = ptr::null_mut();
164        let mut protocol_error: u32 = 0;
165        let mut setup = raw::TEE_udpSocket_Setup {
166            ipVersion: setup.version,
167            server_addr: setup.addr.as_ptr() as _,
168            server_port: setup.port,
169        };
170        let ret = unsafe {
171            ((*raw::TEE_udpSocket).open)(
172                &mut handle,
173                &mut setup as *mut raw::TEE_udpSocket_Setup as _,
174                &mut protocol_error,
175            )
176        };
177        match ret {
178            raw::TEE_SUCCESS => Ok(Self(handle)),
179            _ => Err(SocketError::from_raw_error(ret, protocol_error)),
180        }
181    }
182    fn send(handle: &mut Self::Handle, buf: &[u8], timeout: u32) -> Result<usize, SocketError> {
183        let mut length: u32 = buf.len() as _;
184        let ret = unsafe {
185            ((*raw::TEE_udpSocket).send)(handle.0, buf.as_ptr() as _, &mut length, timeout)
186        };
187        match ret {
188            raw::TEE_SUCCESS => Ok(length as usize),
189            _ => Err(handle_socket_operation_error(
190                unsafe { raw::TEE_udpSocket },
191                handle.0,
192                ret,
193            )),
194        }
195    }
196    fn recv(handle: &mut Self::Handle, buf: &mut [u8], timeout: u32) -> Result<usize, SocketError> {
197        let mut length: u32 = buf.len() as _;
198        let ret = unsafe {
199            ((*raw::TEE_udpSocket).recv)(handle.0, buf.as_mut_ptr() as _, &mut length, timeout)
200        };
201        match ret {
202            raw::TEE_SUCCESS => Ok(length as usize),
203            _ => Err(handle_socket_operation_error(
204                unsafe { raw::TEE_udpSocket },
205                handle.0,
206                ret,
207            )),
208        }
209    }
210}
211
212impl Drop for UdpAdapter {
213    fn drop(&mut self) {
214        // Ignore any errors on close.
215        unsafe {
216            ((*raw::TEE_udpSocket).close)(self.0);
217        }
218    }
219}