| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
use errno::{set_errno, Errno}; |
| 5 |
use s2n_tls::{ |
| 6 |
config::Config, |
| 7 |
connection::{Builder, Connection}, |
| 8 |
enums::{Blinding, CallbackResult, Mode}, |
| 9 |
error::Error, |
| 10 |
}; |
| 11 |
use std::{ |
| 12 |
fmt, |
| 13 |
future::Future, |
| 14 |
io, |
| 15 |
os::raw::{c_int, c_void}, |
| 16 |
pin::Pin, |
| 17 |
task::{ |
| 18 |
Context, Poll, |
| 19 |
Poll::{Pending, Ready}, |
| 20 |
}, |
| 21 |
}; |
| 22 |
use tokio::{ |
| 23 |
io::{AsyncRead, AsyncWrite, ReadBuf}, |
| 24 |
time::{sleep, Duration, Sleep}, |
| 25 |
}; |
| 26 |
|
| 27 |
|
| 28 |
mod task; |
| 29 |
use task::waker::debug_assert_contract as debug_assert_waker_contract; |
| 30 |
|
| 31 |
macro_rules! ready { |
| 32 |
($x:expr) => { |
| 33 |
match $x { |
| 34 |
Ready(r) => r, |
| 35 |
Pending => return Pending, |
| 36 |
} |
| 37 |
}; |
| 38 |
} |
| 39 |
|
| 40 |
#[derive(Clone)] |
| 41 |
pub struct TlsAcceptor<B: Builder = Config> |
| 42 |
where |
| 43 |
<B as Builder>::Output: Unpin, |
| 44 |
{ |
| 45 |
builder: B, |
| 46 |
} |
| 47 |
|
| 48 |
impl<B: Builder> TlsAcceptor<B> |
| 49 |
where |
| 50 |
<B as Builder>::Output: Unpin, |
| 51 |
{ |
| 52 |
pub fn new(builder: B) -> Self { |
| 53 |
TlsAcceptor { builder } |
| 54 |
} |
| 55 |
|
| 56 |
pub async fn accept<S>(&self, stream: S) -> Result<TlsStream<S, B::Output>, Error> |
| 57 |
where |
| 58 |
S: AsyncRead + AsyncWrite + Unpin, |
| 59 |
{ |
| 60 |
let conn = self.builder.build_connection(Mode::Server)?; |
| 61 |
TlsStream::open(conn, stream).await |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
#[derive(Clone)] |
| 66 |
pub struct TlsConnector<B: Builder = Config> |
| 67 |
where |
| 68 |
<B as Builder>::Output: Unpin, |
| 69 |
{ |
| 70 |
builder: B, |
| 71 |
} |
| 72 |
|
| 73 |
impl<B: Builder> TlsConnector<B> |
| 74 |
where |
| 75 |
<B as Builder>::Output: Unpin, |
| 76 |
{ |
| 77 |
pub fn new(builder: B) -> Self { |
| 78 |
TlsConnector { builder } |
| 79 |
} |
| 80 |
|
| 81 |
pub async fn connect<S>( |
| 82 |
&self, |
| 83 |
domain: &str, |
| 84 |
stream: S, |
| 85 |
) -> Result<TlsStream<S, B::Output>, Error> |
| 86 |
where |
| 87 |
S: AsyncRead + AsyncWrite + Unpin, |
| 88 |
{ |
| 89 |
let mut conn = self.builder.build_connection(Mode::Client)?; |
| 90 |
conn.as_mut().set_server_name(domain)?; |
| 91 |
TlsStream::open(conn, stream).await |
| 92 |
} |
| 93 |
} |
| 94 |
|
| 95 |
struct TlsHandshake<'a, S, C> |
| 96 |
where |
| 97 |
C: AsRef<Connection> + AsMut<Connection> + Unpin, |
| 98 |
S: AsyncRead + AsyncWrite + Unpin, |
| 99 |
{ |
| 100 |
tls: &'a mut TlsStream<S, C>, |
| 101 |
error: Option<Error>, |
| 102 |
} |
| 103 |
|
| 104 |
impl<S, C> Future for TlsHandshake<'_, S, C> |
| 105 |
where |
| 106 |
C: AsRef<Connection> + AsMut<Connection> + Unpin, |
| 107 |
S: AsyncRead + AsyncWrite + Unpin, |
| 108 |
{ |
| 109 |
type Output = Result<(), Error>; |
| 110 |
|
| 111 |
fn poll(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> { |
| 112 |
debug_assert_waker_contract(ctx, |ctx| { |
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
let result = match self.error.take() { |
| 118 |
Some(err) => Err(err), |
| 119 |
None => { |
| 120 |
let handshake_poll = self.tls.with_io(ctx, |context| { |
| 121 |
let conn = context.get_mut().as_mut(); |
| 122 |
conn.poll_negotiate().map(|r| r.map(|_| ())) |
| 123 |
}); |
| 124 |
ready!(handshake_poll) |
| 125 |
} |
| 126 |
}; |
| 127 |
|
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
|
| 132 |
|
| 133 |
match result { |
| 134 |
Ok(r) => Ok(r).into(), |
| 135 |
Err(e) if e.is_retryable() => Err(e).into(), |
| 136 |
Err(e) => match Pin::new(&mut self.tls).poll_shutdown(ctx) { |
| 137 |
Pending => { |
| 138 |
self.error = Some(e); |
| 139 |
Pending |
| 140 |
} |
| 141 |
Ready(_) => Err(e).into(), |
| 142 |
}, |
| 143 |
} |
| 144 |
}) |
| 145 |
} |
| 146 |
} |
| 147 |
|
| 148 |
pub struct TlsStream<S, C = Connection> |
| 149 |
where |
| 150 |
C: AsRef<Connection> + AsMut<Connection> + Unpin, |
| 151 |
S: AsyncRead + AsyncWrite + Unpin, |
| 152 |
{ |
| 153 |
conn: C, |
| 154 |
stream: S, |
| 155 |
blinding: Option<Pin<Box<Sleep>>>, |
| 156 |
shutdown_error: Option<Error>, |
| 157 |
} |
| 158 |
|
| 159 |
impl<S, C> TlsStream<S, C> |
| 160 |
where |
| 161 |
C: AsRef<Connection> + AsMut<Connection> + Unpin, |
| 162 |
S: AsyncRead + AsyncWrite + Unpin, |
| 163 |
{ |
| 164 |
|
| 165 |
pub fn get_ref(&self) -> &S { |
| 166 |
&self.stream |
| 167 |
} |
| 168 |
|
| 169 |
|
| 170 |
pub fn get_mut(&mut self) -> &mut S { |
| 171 |
&mut self.stream |
| 172 |
} |
| 173 |
|
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
|
| 178 |
|
| 179 |
|
| 180 |
|
| 181 |
|
| 182 |
|
| 183 |
|
| 184 |
pub fn into_parts(self) -> (C, S) { |
| 185 |
(self.conn, self.stream) |
| 186 |
} |
| 187 |
|
| 188 |
|
| 189 |
|
| 190 |
|
| 191 |
|
| 192 |
|
| 193 |
pub fn from_parts(conn: C, stream: S) -> Self { |
| 194 |
TlsStream { |
| 195 |
conn, |
| 196 |
stream, |
| 197 |
blinding: None, |
| 198 |
shutdown_error: None, |
| 199 |
} |
| 200 |
} |
| 201 |
|
| 202 |
async fn open(conn: C, stream: S) -> Result<Self, Error> { |
| 203 |
let mut tls = TlsStream { |
| 204 |
conn, |
| 205 |
stream, |
| 206 |
blinding: None, |
| 207 |
shutdown_error: None, |
| 208 |
}; |
| 209 |
TlsHandshake { |
| 210 |
tls: &mut tls, |
| 211 |
error: None, |
| 212 |
} |
| 213 |
.await?; |
| 214 |
Ok(tls) |
| 215 |
} |
| 216 |
|
| 217 |
fn with_io<F, R>(&mut self, ctx: &mut Context, action: F) -> Poll<Result<R, Error>> |
| 218 |
where |
| 219 |
F: FnOnce(Pin<&mut Self>) -> Poll<Result<R, Error>>, |
| 220 |
{ |
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
unsafe { |
| 226 |
let context = self as *mut Self as *mut c_void; |
| 227 |
|
| 228 |
self.as_mut().set_receive_callback(Some(Self::recv_io_cb))?; |
| 229 |
self.as_mut().set_send_callback(Some(Self::send_io_cb))?; |
| 230 |
self.as_mut().set_receive_context(context)?; |
| 231 |
self.as_mut().set_send_context(context)?; |
| 232 |
self.as_mut().set_waker(Some(ctx.waker()))?; |
| 233 |
self.as_mut().set_blinding(Blinding::SelfService)?; |
| 234 |
|
| 235 |
let result = action(Pin::new(self)); |
| 236 |
|
| 237 |
self.as_mut().set_receive_callback(None)?; |
| 238 |
self.as_mut().set_send_callback(None)?; |
| 239 |
self.as_mut().set_receive_context(std::ptr::null_mut())?; |
| 240 |
self.as_mut().set_send_context(std::ptr::null_mut())?; |
| 241 |
self.as_mut().set_waker(None)?; |
| 242 |
result |
| 243 |
} |
| 244 |
} |
| 245 |
|
| 246 |
fn poll_io<F>(ctx: *mut c_void, action: F) -> c_int |
| 247 |
where |
| 248 |
F: FnOnce(Pin<&mut S>, &mut Context) -> Poll<Result<usize, std::io::Error>>, |
| 249 |
{ |
| 250 |
debug_assert_ne!(ctx, std::ptr::null_mut()); |
| 251 |
let tls = unsafe { &mut *(ctx as *mut Self) }; |
| 252 |
|
| 253 |
let mut async_context = Context::from_waker(tls.conn.as_ref().waker().unwrap()); |
| 254 |
let stream = Pin::new(&mut tls.stream); |
| 255 |
|
| 256 |
let res = debug_assert_waker_contract(&mut async_context, |async_context| { |
| 257 |
action(stream, async_context) |
| 258 |
}); |
| 259 |
|
| 260 |
match res { |
| 261 |
Poll::Ready(Ok(len)) => len as c_int, |
| 262 |
Poll::Pending => { |
| 263 |
set_errno(Errno(libc::EWOULDBLOCK)); |
| 264 |
CallbackResult::Failure.into() |
| 265 |
} |
| 266 |
_ => CallbackResult::Failure.into(), |
| 267 |
} |
| 268 |
} |
| 269 |
|
| 270 |
unsafe extern "C" fn recv_io_cb(ctx: *mut c_void, buf: *mut u8, len: u32) -> c_int { |
| 271 |
Self::poll_io(ctx, |stream, async_context| { |
| 272 |
let len: usize = len.try_into().unwrap(); |
| 273 |
let mut dest = ReadBuf::new(std::slice::from_raw_parts_mut(buf, len)); |
| 274 |
stream |
| 275 |
.poll_read(async_context, &mut dest) |
| 276 |
.map_ok(|_| dest.filled().len()) |
| 277 |
}) |
| 278 |
} |
| 279 |
|
| 280 |
unsafe extern "C" fn send_io_cb(ctx: *mut c_void, buf: *const u8, len: u32) -> c_int { |
| 281 |
Self::poll_io(ctx, |stream, async_context| { |
| 282 |
let len: usize = len.try_into().unwrap(); |
| 283 |
let src = std::slice::from_raw_parts(buf, len); |
| 284 |
stream.poll_write(async_context, src) |
| 285 |
}) |
| 286 |
} |
| 287 |
|
| 288 |
|
| 289 |
|
| 290 |
|
| 291 |
|
| 292 |
|
| 293 |
|
| 294 |
|
| 295 |
|
| 296 |
|
| 297 |
|
| 298 |
|
| 299 |
|
| 300 |
pub fn poll_blinding(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Result<(), Error>> { |
| 301 |
debug_assert_waker_contract(ctx, |ctx| { |
| 302 |
let tls = self.get_mut(); |
| 303 |
|
| 304 |
if tls.blinding.is_none() { |
| 305 |
let delay = tls.as_ref().remaining_blinding_delay()?; |
| 306 |
if !delay.is_zero() { |
| 307 |
|
| 308 |
|
| 309 |
let safety = Duration::from_millis(1); |
| 310 |
tls.blinding = Some(Box::pin(sleep(delay.saturating_add(safety)))); |
| 311 |
} |
| 312 |
}; |
| 313 |
|
| 314 |
if let Some(timer) = tls.blinding.as_mut() { |
| 315 |
ready!(timer.as_mut().poll(ctx)); |
| 316 |
tls.blinding = None; |
| 317 |
} |
| 318 |
|
| 319 |
Poll::Ready(Ok(())) |
| 320 |
}) |
| 321 |
} |
| 322 |
|
| 323 |
pub async fn apply_blinding(&mut self) -> Result<(), Error> { |
| 324 |
ApplyBlinding { stream: self }.await |
| 325 |
} |
| 326 |
} |
| 327 |
|
| 328 |
impl<S, C> AsRef<Connection> for TlsStream<S, C> |
| 329 |
where |
| 330 |
C: AsRef<Connection> + AsMut<Connection> + Unpin, |
| 331 |
S: AsyncRead + AsyncWrite + Unpin, |
| 332 |
{ |
| 333 |
fn as_ref(&self) -> &Connection { |
| 334 |
self.conn.as_ref() |
| 335 |
} |
| 336 |
} |
| 337 |
|
| 338 |
impl<S, C> AsMut<Connection> for TlsStream<S, C> |
| 339 |
where |
| 340 |
C: AsRef<Connection> + AsMut<Connection> + Unpin, |
| 341 |
S: AsyncRead + AsyncWrite + Unpin, |
| 342 |
{ |
| 343 |
fn as_mut(&mut self) -> &mut Connection { |
| 344 |
self.conn.as_mut() |
| 345 |
} |
| 346 |
} |
| 347 |
|
| 348 |
impl<S, C> AsyncRead for TlsStream<S, C> |
| 349 |
where |
| 350 |
C: AsRef<Connection> + AsMut<Connection> + Unpin, |
| 351 |
S: AsyncRead + AsyncWrite + Unpin, |
| 352 |
{ |
| 353 |
fn poll_read( |
| 354 |
self: Pin<&mut Self>, |
| 355 |
ctx: &mut Context<'_>, |
| 356 |
buf: &mut ReadBuf<'_>, |
| 357 |
) -> Poll<io::Result<()>> { |
| 358 |
let tls = self.get_mut(); |
| 359 |
tls.with_io(ctx, |mut context| { |
| 360 |
context |
| 361 |
.conn |
| 362 |
.as_mut() |
| 363 |
|
| 364 |
|
| 365 |
.poll_recv_uninitialized(unsafe { buf.unfilled_mut() }) |
| 366 |
.map_ok(|size| { |
| 367 |
unsafe { |
| 368 |
|
| 369 |
|
| 370 |
|
| 371 |
buf.assume_init(size); |
| 372 |
} |
| 373 |
buf.advance(size); |
| 374 |
}) |
| 375 |
}) |
| 376 |
.map_err(io::Error::from) |
| 377 |
} |
| 378 |
} |
| 379 |
|
| 380 |
impl<S, C> AsyncWrite for TlsStream<S, C> |
| 381 |
where |
| 382 |
C: AsRef<Connection> + AsMut<Connection> + Unpin, |
| 383 |
S: AsyncRead + AsyncWrite + Unpin, |
| 384 |
{ |
| 385 |
fn poll_write( |
| 386 |
self: Pin<&mut Self>, |
| 387 |
ctx: &mut Context<'_>, |
| 388 |
buf: &[u8], |
| 389 |
) -> Poll<io::Result<usize>> { |
| 390 |
let tls = self.get_mut(); |
| 391 |
tls.with_io(ctx, |mut context| context.conn.as_mut().poll_send(buf)) |
| 392 |
.map_err(io::Error::from) |
| 393 |
} |
| 394 |
|
| 395 |
fn poll_flush(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<io::Result<()>> { |
| 396 |
let tls = self.get_mut(); |
| 397 |
|
| 398 |
ready!(tls.with_io(ctx, |mut context| { |
| 399 |
context.conn.as_mut().poll_flush().map(|r| r.map(|_| ())) |
| 400 |
})) |
| 401 |
.map_err(io::Error::from)?; |
| 402 |
|
| 403 |
Pin::new(&mut tls.stream).poll_flush(ctx) |
| 404 |
} |
| 405 |
|
| 406 |
fn poll_shutdown(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<io::Result<()>> { |
| 407 |
debug_assert_waker_contract(ctx, |ctx| { |
| 408 |
ready!(self.as_mut().poll_blinding(ctx))?; |
| 409 |
|
| 410 |
|
| 411 |
if self.shutdown_error.is_none() { |
| 412 |
let result = ready!(self.as_mut().with_io(ctx, |mut context| { |
| 413 |
context |
| 414 |
.conn |
| 415 |
.as_mut() |
| 416 |
.poll_shutdown_send() |
| 417 |
.map(|r| r.map(|_| ())) |
| 418 |
})); |
| 419 |
if let Err(error) = result { |
| 420 |
self.shutdown_error = Some(error); |
| 421 |
|
| 422 |
|
| 423 |
} |
| 424 |
}; |
| 425 |
|
| 426 |
let tcp_result = ready!(Pin::new(&mut self.as_mut().stream).poll_shutdown(ctx)); |
| 427 |
|
| 428 |
if let Some(err) = self.shutdown_error.take() { |
| 429 |
|
| 430 |
|
| 431 |
|
| 432 |
|
| 433 |
|
| 434 |
let next_error = Error::application("Shutdown called again after error".into()); |
| 435 |
self.shutdown_error = Some(next_error); |
| 436 |
|
| 437 |
Ready(Err(io::Error::from(err))) |
| 438 |
} else { |
| 439 |
Ready(tcp_result) |
| 440 |
} |
| 441 |
}) |
| 442 |
} |
| 443 |
} |
| 444 |
|
| 445 |
impl<S, C> fmt::Debug for TlsStream<S, C> |
| 446 |
where |
| 447 |
C: AsRef<Connection> + AsMut<Connection> + Unpin, |
| 448 |
S: AsyncRead + AsyncWrite + Unpin, |
| 449 |
{ |
| 450 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 451 |
f.debug_struct("TlsStream") |
| 452 |
.field("connection", self.as_ref()) |
| 453 |
.finish() |
| 454 |
} |
| 455 |
} |
| 456 |
|
| 457 |
struct ApplyBlinding<'a, S, C> |
| 458 |
where |
| 459 |
C: AsRef<Connection> + AsMut<Connection> + Unpin, |
| 460 |
S: AsyncRead + AsyncWrite + Unpin, |
| 461 |
{ |
| 462 |
stream: &'a mut TlsStream<S, C>, |
| 463 |
} |
| 464 |
|
| 465 |
impl<S, C> Future for ApplyBlinding<'_, S, C> |
| 466 |
where |
| 467 |
C: AsRef<Connection> + AsMut<Connection> + Unpin, |
| 468 |
S: AsyncRead + AsyncWrite + Unpin, |
| 469 |
{ |
| 470 |
type Output = Result<(), Error>; |
| 471 |
|
| 472 |
fn poll(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> { |
| 473 |
Pin::new(&mut *self.as_mut().stream).poll_blinding(ctx) |
| 474 |
} |
| 475 |
} |