Skip to content

Commit cecb88b

Browse files
committed
fix: clippy warning and misc changes
1 parent 311d7e6 commit cecb88b

File tree

15 files changed

+324
-280
lines changed

15 files changed

+324
-280
lines changed

ktls-sys/src/bindings.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,17 @@
55
pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>, [T; 0]);
66
impl<T> __IncompleteArrayField<T> {
77
#[inline]
8+
#[must_use]
89
pub const fn new() -> Self {
910
__IncompleteArrayField(::std::marker::PhantomData, [])
1011
}
1112
#[inline]
1213
pub fn as_ptr(&self) -> *const T {
13-
self as *const _ as *const T
14+
std::ptr::from_ref(self).cast::<T>()
1415
}
1516
#[inline]
1617
pub fn as_mut_ptr(&mut self) -> *mut T {
17-
self as *mut _ as *mut T
18+
std::ptr::from_mut(self).cast::<T>()
1819
}
1920
#[inline]
2021
pub unsafe fn as_slice(&self, len: usize) -> &[T] {

ktls/Cargo.toml

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,13 @@ rcgen = { version = "0.14.3" }
3131
tokio = { version = "1.40", features = ["io-util", "macros", "net", "rt-multi-thread", "signal", "time"] }
3232

3333
[features]
34-
default = ["tls12", "feature-tokio"]
34+
default = ["tls12", "async-io-tokio"]
3535

3636
# Enables rustls/tls12
3737
tls12 = ["rustls/tls12"]
3838

39-
# Implements `AsyncRead` and `AsyncWrite` traits for `KtlsStream`
40-
feature-tokio = ["dep:tokio"]
39+
# Expose some low-level APIs
40+
raw-api = []
41+
42+
# Implements tokio's `AsyncRead` and `AsyncWrite` traits for `KtlsStream`
43+
async-io-tokio = ["dep:tokio"]

ktls/examples/client.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22
33
mod common;
44

5-
use core::time::Duration;
65
use std::error::Error;
76
use std::sync::Arc;
7+
use std::time::Duration;
88

99
use rustls::pki_types::ServerName;
1010
use rustls::ClientConfig;

ktls/src/error.rs

Lines changed: 30 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,84 +1,67 @@
11
//! Error types for the `ktls` crate
22
3-
use std::{fmt, io};
3+
use std::io;
44

55
use rustls::SupportedCipherSuite;
66

7-
#[derive(Debug, thiserror::Error)]
87
#[non_exhaustive]
8+
#[derive(Debug, thiserror::Error)]
99
/// Unified error type for this crate
1010
pub enum Error {
1111
#[error("kTLS is not supported by the current kernel")]
1212
/// kTLS is not supported by the current kernel.
1313
Unsupported,
1414

1515
#[error("the negotiated cipher suite [{0:?}] is not supported")]
16-
/// The negotiated cipher suite is not supported.
17-
UnsupportedCipherSuite(SupportedCipherSuite),
16+
/// The negotiated cipher suite is not supported by this crate.
17+
UnknownCipherSuite(SupportedCipherSuite),
18+
19+
#[error(transparent)]
20+
/// Invalid crypto material, e.g., wrong size key or IV.
21+
InvalidCryptoInfo(#[from] InvalidCryptoInfo),
1822

1923
#[error("failed to extract connection secrets from rustls connection: {0}")]
24+
/// Failed to extract connection secrets from rustls connection, e.g., not
25+
/// have `config.enable_secret_extraction` set to true
2026
ExtractSecrets(#[source] rustls::Error),
2127

22-
#[error("the peer closed the connection before the TLS handshake could be completed")]
23-
/// The peer closed the connection before the TLS handshake could be
24-
/// completed.
25-
ConnectionClosedBeforeHandshakeCompleted,
26-
2728
#[error(transparent)]
2829
/// General IO error.
2930
IO(#[from] io::Error),
3031

31-
#[error("failed to create rustls connection: {0}")]
32+
#[error("The peer closed the connection before the TLS handshake could be completed")]
33+
/// (Reserved) The peer closed the connection before the TLS handshake could
34+
/// be completed.
35+
ConnectionClosedBeforeHandshakeCompleted,
36+
37+
#[error("Failed to create rustls unbuffered connection: {0}")]
38+
/// (Reserved)
3239
Config(#[source] rustls::Error),
3340

34-
#[error("an error occurred during the handshake: {0}")]
41+
#[error("An error occurred during handshake: {0}")]
42+
/// (Reserved)
3543
Handshake(#[source] rustls::Error),
3644
}
3745

3846
impl From<Error> for io::Error {
3947
fn from(error: Error) -> Self {
4048
match error {
4149
Error::IO(error) => error,
42-
_ => io::Error::other(error),
50+
_ => Self::other(error),
4351
}
4452
}
4553
}
4654

55+
#[derive(Debug)]
4756
#[derive(thiserror::Error)]
48-
#[error("{error}")]
49-
pub struct TryConnectError<IO, Conn> {
50-
#[source]
51-
pub error: Error,
52-
pub socket: Option<IO>,
53-
pub conn: Option<Conn>,
54-
}
55-
56-
impl<IO, Conn> fmt::Debug for TryConnectError<IO, Conn> {
57-
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58-
f.debug_struct("TryConnectError")
59-
.field("error", &self.error)
60-
.finish_non_exhaustive()
61-
}
62-
}
63-
64-
impl<IO, Conn> From<Error> for TryConnectError<IO, Conn> {
65-
fn from(error: Error) -> Self {
66-
Self {
67-
error,
68-
socket: None,
69-
conn: None,
70-
}
71-
}
72-
}
73-
74-
impl<IO, Conn> From<TryConnectError<IO, Conn>> for Error {
75-
fn from(value: TryConnectError<IO, Conn>) -> Self {
76-
value.error
77-
}
78-
}
57+
/// Crypto material is invalid, e.g., wrong size key or IV.
58+
#[non_exhaustive]
59+
pub enum InvalidCryptoInfo {
60+
#[error("Wrong size key")]
61+
/// The provided key has an incorrect size (unlikely).
62+
WrongSizeKey,
7963

80-
impl<IO, Conn> From<TryConnectError<IO, Conn>> for io::Error {
81-
fn from(error: TryConnectError<IO, Conn>) -> Self {
82-
error.error.into()
83-
}
64+
#[error("Wrong size iv")]
65+
/// The provided IV has an incorrect size (unlikely).
66+
WrongSizeIv,
8467
}

ktls/src/ffi.rs

Lines changed: 30 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
33
use std::ffi::c_void;
44
use std::os::fd::RawFd;
5-
use std::{io, mem};
5+
use std::{io, mem, ptr};
66

77
// Yes, really. cmsg components are aligned to [libc::c_long]
88
pub(crate) struct Cmsg<const N: usize> {
@@ -15,9 +15,8 @@ impl<const N: usize> Cmsg<N> {
1515
pub(crate) fn new(level: i32, typ: i32, data: [u8; N]) -> Self {
1616
Self {
1717
hdr: libc::cmsghdr {
18-
// on Linux this is a usize, on macOS this is a u32
19-
#[allow(clippy::unnecessary_cast)]
20-
cmsg_len: (mem::offset_of!(Self, data) + N) as _,
18+
// on Linux this is a usize
19+
cmsg_len: mem::offset_of!(Self, data) + N,
2120
cmsg_level: level,
2221
cmsg_type: typ,
2322
},
@@ -42,24 +41,29 @@ impl<const N: usize> Cmsg<N> {
4241
/// A wrapper around [`libc::sendmsg`].
4342
pub(crate) fn sendmsg<const N: usize>(
4443
fd: RawFd,
45-
data: &[io::IoSlice<'_>],
44+
data: &mut [io::IoSlice<'_>],
4645
cmsg: Option<&Cmsg<N>>,
4746
flags: i32,
4847
) -> io::Result<usize> {
49-
let mut msg: libc::msghdr = unsafe { std::mem::zeroed() };
48+
#[allow(unsafe_code)]
49+
// SAFETY: zeroed is fine for msghdr as we will set all the fields we use.
50+
let mut msg: libc::msghdr = unsafe { mem::zeroed() };
5051

5152
if let Some(cmsg) = cmsg {
52-
msg.msg_control = cmsg as *const _ as *mut c_void;
53-
msg.msg_controllen = std::mem::size_of_val(cmsg);
53+
msg.msg_control = ptr::from_ref(cmsg) as *mut c_void;
54+
msg.msg_controllen = size_of_val(cmsg);
5455
}
5556

56-
msg.msg_iov = data.as_ptr() as *const _ as *mut libc::iovec;
57+
msg.msg_iov = ptr::from_mut(data).cast();
5758
msg.msg_iovlen = data.len();
5859

60+
#[allow(unsafe_code)]
61+
// SAFETY: syscall
5962
let ret = unsafe { libc::sendmsg(fd, &msg, flags) };
6063
match ret {
61-
-1 => Err(io::Error::last_os_error()),
62-
len => Ok(len as usize),
64+
..0 => Err(io::Error::last_os_error()),
65+
#[allow(clippy::cast_sign_loss)]
66+
len @ 0.. => Ok(len as usize),
6367
}
6468
}
6569

@@ -79,10 +83,13 @@ pub(crate) fn recvmsg_whole<const N: usize>(
7983
}
8084

8185
loop {
82-
let mut msg: libc::msghdr = unsafe { std::mem::zeroed() };
86+
#[allow(unsafe_code)]
87+
// SAFETY: zeroed is fine for msghdr as we will set all the fields we use.
88+
let mut msg: libc::msghdr = unsafe { mem::zeroed() };
89+
8390
if let Some(cmsg) = cmsg.as_deref_mut() {
84-
msg.msg_control = cmsg as *mut _ as *mut c_void;
85-
msg.msg_controllen = std::mem::size_of_val(cmsg);
91+
msg.msg_control = ptr::from_mut(cmsg).cast();
92+
msg.msg_controllen = size_of_val(cmsg);
8693
}
8794

8895
if data.spare_capacity_mut().is_empty() {
@@ -91,23 +98,28 @@ pub(crate) fn recvmsg_whole<const N: usize>(
9198

9299
let spare = data.spare_capacity_mut();
93100
let mut iov = libc::iovec {
94-
iov_base: spare.as_mut_ptr() as *mut c_void,
101+
iov_base: spare.as_mut_ptr().cast(),
95102
iov_len: spare.len(),
96103
};
97104

98105
msg.msg_iov = &mut iov;
99106
msg.msg_iovlen = 1;
100107

108+
#[allow(unsafe_code)]
101109
// SAFETY: We have made sure to initialize msg with valid pointers (or NULL).
102110
let ret = unsafe { libc::recvmsg(fd, &mut msg, flags) };
103111
let count = match ret {
104-
-1 => return Err(io::Error::last_os_error()),
105-
len => len as usize,
112+
..0 => return Err(io::Error::last_os_error()),
113+
#[allow(clippy::cast_sign_loss)]
114+
len @ 0.. => len as usize,
106115
};
107116

117+
#[allow(unsafe_code)]
108118
// SAFETY: recvmsg has just written count to the bytes in the spare capacity of
109119
// the vector.
110-
unsafe { data.set_len(data.len() + count) };
120+
unsafe {
121+
data.set_len(data.len() + count);
122+
};
111123

112124
if msg.msg_flags & libc::MSG_EOR != 0 {
113125
break Ok(msg.msg_flags);

ktls/src/lib.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,22 @@
11
#![doc = include_str!("../README.md")]
2+
#![warn(
3+
unsafe_code,
4+
unused_must_use,
5+
clippy::alloc_instead_of_core,
6+
clippy::exhaustive_enums,
7+
clippy::exhaustive_structs,
8+
clippy::manual_let_else,
9+
clippy::use_self,
10+
clippy::upper_case_acronyms,
11+
elided_lifetimes_in_paths,
12+
missing_docs,
13+
trivial_casts,
14+
trivial_numeric_casts,
15+
unreachable_pub,
16+
unused_import_braces,
17+
unused_extern_crates,
18+
unused_qualifications
19+
)]
220

321
#[cfg(not(target_os = "linux"))]
422
compile_error!("This crate only supports Linux");

ktls/src/protocol.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ macro_rules! c_enum {
2121
impl $name {
2222
$(
2323
$( #[$vattr] )*
24-
pub const $variant: Self = Self($value);
24+
$vis const $variant: Self = Self($value);
2525
)*
2626
}
2727

@@ -65,10 +65,10 @@ macro_rules! c_enum {
6565
}
6666
}
6767

68-
/// KeyUpdate, not requested
68+
/// `KeyUpdate`, not requested
6969
pub(crate) const KEY_UPDATE_NOT_REQUESTED: u8 = 0;
7070

71-
/// KeyUpdate, requested
71+
/// `KeyUpdate`, requested
7272
pub(crate) const KEY_UPDATE_REQUESTED: u8 = 1;
7373

7474
c_enum! {

ktls/src/setup.rs

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,27 @@
1-
//! This module provides low-level APIs to setup a kTLS connection.
1+
//! Transport Layer Security (TLS) is a Upper Layer Protocol (ULP) that runs
2+
//! over TCP. TLS provides end-to-end data integrity and confidentiality.
3+
//!
4+
//! Once the TCP connection is established, sets the TLS ULP, which allows us to
5+
//! set/get TLS socket options.
6+
//!
7+
//! This module provides the [`setup_ulp`] function, which sets the ULP (Upper
8+
//! Layer Protocol) to TLS for a TCP socket. The user can also determine whether
9+
//! the kernel supports kTLS with [`setup_ulp`].
10+
//!
11+
//! After the TLS handshake is completed, we have all the parameters required to
12+
//! move the data-path to the kernel. There is a separate socket option for
13+
//! moving the transmit and the receive into the kernel.
14+
//!
15+
//! This module provides the low-level [`setup_tls_params`] function (when
16+
//! feature `raw-api` is enabled), which sets the Kernel TLS parameters on the
17+
//! TCP socket, allowing the kernel to handle encryption and decryption of the
18+
//! TLS data.
219
3-
pub(crate) mod tls;
20+
mod tls;
421
mod ulp;
522

6-
pub use tls::setup_tls_params;
23+
#[cfg(not(feature = "raw-api"))]
24+
pub(crate) use tls::{setup_tls_params, setup_tls_params_rx, setup_tls_params_tx};
25+
#[cfg(feature = "raw-api")]
26+
pub use tls::{setup_tls_params, setup_tls_params_rx, setup_tls_params_tx};
727
pub use ulp::{setup_ulp, SetupError};

0 commit comments

Comments
 (0)