fix(deps): bound SQLx pool maintenance and reserve idle counters
This commit is contained in:
1 parent
7aa854de26
commit
284eb8180e
113 files changed
+21092
-2
No files matched your search
+6
@@ -0,0 +1,6 @@
|
||||
mod socket;
|
||||
pub mod tls;
|
||||
|
||||
pub use socket::{
|
||||
connect_tcp, connect_uds, BufferedSocket, Socket, SocketIntoBox, WithSocket, WriteBuffer,
|
||||
};
|
||||
+329
@@ -0,0 +1,329 @@
|
||||
use crate::error::Error;
|
||||
use crate::net::Socket;
|
||||
use bytes::BytesMut;
|
||||
use std::ops::ControlFlow;
|
||||
use std::{cmp, io};
|
||||
|
||||
use crate::io::{AsyncRead, AsyncReadExt, ProtocolDecode, ProtocolEncode};
|
||||
|
||||
// Tokio, async-std, and std all use this as the default capacity for their buffered I/O.
|
||||
const DEFAULT_BUF_SIZE: usize = 8192;
|
||||
|
||||
pub struct BufferedSocket<S> {
|
||||
socket: S,
|
||||
write_buf: WriteBuffer,
|
||||
read_buf: ReadBuffer,
|
||||
}
|
||||
|
||||
pub struct WriteBuffer {
|
||||
buf: Vec<u8>,
|
||||
bytes_written: usize,
|
||||
bytes_flushed: usize,
|
||||
}
|
||||
|
||||
pub struct ReadBuffer {
|
||||
read: BytesMut,
|
||||
available: BytesMut,
|
||||
}
|
||||
|
||||
impl<S: Socket> BufferedSocket<S> {
|
||||
pub fn new(socket: S) -> Self
|
||||
where
|
||||
S: Sized,
|
||||
{
|
||||
BufferedSocket {
|
||||
socket,
|
||||
write_buf: WriteBuffer {
|
||||
buf: Vec::with_capacity(DEFAULT_BUF_SIZE),
|
||||
bytes_written: 0,
|
||||
bytes_flushed: 0,
|
||||
},
|
||||
read_buf: ReadBuffer {
|
||||
read: BytesMut::new(),
|
||||
available: BytesMut::with_capacity(DEFAULT_BUF_SIZE),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn read_buffered(&mut self, len: usize) -> Result<BytesMut, Error> {
|
||||
self.try_read(|buf| {
|
||||
Ok(if buf.len() < len {
|
||||
ControlFlow::Continue(len)
|
||||
} else {
|
||||
ControlFlow::Break(buf.split_to(len))
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Retryable read operation.
|
||||
///
|
||||
/// The callback should check the contents of the buffer passed to it and either:
|
||||
///
|
||||
/// * Remove a full message from the buffer and return [`ControlFlow::Break`], or:
|
||||
/// * Return [`ControlFlow::Continue`] with the expected _total_ length of the buffer,
|
||||
/// _without_ modifying it.
|
||||
///
|
||||
/// Cancel-safe as long as the callback does not modify the passed `BytesMut`
|
||||
/// before returning [`ControlFlow::Continue`].
|
||||
pub async fn try_read<F, R>(&mut self, mut try_read: F) -> Result<R, Error>
|
||||
where
|
||||
F: FnMut(&mut BytesMut) -> Result<ControlFlow<R, usize>, Error>,
|
||||
{
|
||||
loop {
|
||||
let read_len = match try_read(&mut self.read_buf.read)? {
|
||||
ControlFlow::Continue(read_len) => read_len,
|
||||
ControlFlow::Break(ret) => return Ok(ret),
|
||||
};
|
||||
|
||||
self.read_buf.read(read_len, &mut self.socket).await?;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write_buffer(&self) -> &WriteBuffer {
|
||||
&self.write_buf
|
||||
}
|
||||
|
||||
pub fn write_buffer_mut(&mut self) -> &mut WriteBuffer {
|
||||
&mut self.write_buf
|
||||
}
|
||||
|
||||
pub async fn read<'de, T>(&mut self, byte_len: usize) -> Result<T, Error>
|
||||
where
|
||||
T: ProtocolDecode<'de, ()>,
|
||||
{
|
||||
self.read_with(byte_len, ()).await
|
||||
}
|
||||
|
||||
pub async fn read_with<'de, T, C>(&mut self, byte_len: usize, context: C) -> Result<T, Error>
|
||||
where
|
||||
T: ProtocolDecode<'de, C>,
|
||||
{
|
||||
T::decode_with(self.read_buffered(byte_len).await?.freeze(), context)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn write<'en, T>(&mut self, value: T) -> Result<(), Error>
|
||||
where
|
||||
T: ProtocolEncode<'en, ()>,
|
||||
{
|
||||
self.write_with(value, ())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn write_with<'en, T, C>(&mut self, value: T, context: C) -> Result<(), Error>
|
||||
where
|
||||
T: ProtocolEncode<'en, C>,
|
||||
{
|
||||
value.encode_with(self.write_buf.buf_mut(), context)?;
|
||||
self.write_buf.bytes_written = self.write_buf.buf.len();
|
||||
self.write_buf.sanity_check();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn flush(&mut self) -> io::Result<()> {
|
||||
while !self.write_buf.is_empty() {
|
||||
let written = self.socket.write(self.write_buf.get()).await?;
|
||||
self.write_buf.consume(written);
|
||||
self.write_buf.sanity_check();
|
||||
}
|
||||
|
||||
self.socket.flush().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn shutdown(&mut self) -> io::Result<()> {
|
||||
self.flush().await?;
|
||||
self.socket.shutdown().await
|
||||
}
|
||||
|
||||
pub fn shrink_buffers(&mut self) {
|
||||
// Won't drop data still in the buffer.
|
||||
self.write_buf.shrink();
|
||||
self.read_buf.shrink();
|
||||
}
|
||||
|
||||
pub fn into_inner(self) -> S {
|
||||
self.socket
|
||||
}
|
||||
|
||||
pub fn boxed(self) -> BufferedSocket<Box<dyn Socket>> {
|
||||
BufferedSocket {
|
||||
socket: Box::new(self.socket),
|
||||
write_buf: self.write_buf,
|
||||
read_buf: self.read_buf,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WriteBuffer {
|
||||
fn sanity_check(&self) {
|
||||
assert_ne!(self.buf.capacity(), 0);
|
||||
assert!(self.bytes_written <= self.buf.len());
|
||||
assert!(self.bytes_flushed <= self.bytes_written);
|
||||
}
|
||||
|
||||
pub fn buf_mut(&mut self) -> &mut Vec<u8> {
|
||||
self.buf.truncate(self.bytes_written);
|
||||
self.sanity_check();
|
||||
&mut self.buf
|
||||
}
|
||||
|
||||
pub fn init_remaining_mut(&mut self) -> &mut [u8] {
|
||||
self.buf.resize(self.buf.capacity(), 0);
|
||||
self.sanity_check();
|
||||
&mut self.buf[self.bytes_written..]
|
||||
}
|
||||
|
||||
pub fn put_slice(&mut self, slice: &[u8]) {
|
||||
// If we already have an initialized area that can fit the slice,
|
||||
// don't change `self.buf.len()`
|
||||
if let Some(dest) = self.buf[self.bytes_written..].get_mut(..slice.len()) {
|
||||
dest.copy_from_slice(slice);
|
||||
} else {
|
||||
self.buf.truncate(self.bytes_written);
|
||||
self.buf.extend_from_slice(slice);
|
||||
}
|
||||
self.advance(slice.len());
|
||||
self.sanity_check();
|
||||
}
|
||||
|
||||
pub fn advance(&mut self, amt: usize) {
|
||||
let new_bytes_written = self
|
||||
.bytes_written
|
||||
.checked_add(amt)
|
||||
.expect("self.bytes_written + amt overflowed");
|
||||
|
||||
assert!(new_bytes_written <= self.buf.len());
|
||||
|
||||
self.bytes_written = new_bytes_written;
|
||||
|
||||
self.sanity_check();
|
||||
}
|
||||
|
||||
/// Read into the buffer from `source`, returning the number of bytes read.
|
||||
///
|
||||
/// The buffer is automatically advanced by the number of bytes read.
|
||||
pub async fn read_from(&mut self, mut source: impl AsyncRead + Unpin) -> io::Result<usize> {
|
||||
let read = match () {
|
||||
// Tokio lets us read into the buffer without zeroing first
|
||||
#[cfg(feature = "_rt-tokio")]
|
||||
_ => source.read_buf(self.buf_mut()).await?,
|
||||
#[cfg(not(feature = "_rt-tokio"))]
|
||||
_ => source.read(self.init_remaining_mut()).await?,
|
||||
};
|
||||
|
||||
if read > 0 {
|
||||
self.advance(read);
|
||||
}
|
||||
|
||||
Ok(read)
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.bytes_flushed >= self.bytes_written
|
||||
}
|
||||
|
||||
pub fn is_full(&self) -> bool {
|
||||
self.bytes_written == self.buf.len()
|
||||
}
|
||||
|
||||
pub fn get(&self) -> &[u8] {
|
||||
&self.buf[self.bytes_flushed..self.bytes_written]
|
||||
}
|
||||
|
||||
pub fn get_mut(&mut self) -> &mut [u8] {
|
||||
&mut self.buf[self.bytes_flushed..self.bytes_written]
|
||||
}
|
||||
|
||||
pub fn shrink(&mut self) {
|
||||
if self.bytes_flushed > 0 {
|
||||
// Move any data that remains to be flushed to the beginning of the buffer,
|
||||
// if necessary.
|
||||
self.buf
|
||||
.copy_within(self.bytes_flushed..self.bytes_written, 0);
|
||||
self.bytes_written -= self.bytes_flushed;
|
||||
self.bytes_flushed = 0
|
||||
}
|
||||
|
||||
// Drop excess capacity.
|
||||
self.buf
|
||||
.truncate(cmp::max(self.bytes_written, DEFAULT_BUF_SIZE));
|
||||
self.buf.shrink_to_fit();
|
||||
}
|
||||
|
||||
fn consume(&mut self, amt: usize) {
|
||||
let new_bytes_flushed = self
|
||||
.bytes_flushed
|
||||
.checked_add(amt)
|
||||
.expect("self.bytes_flushed + amt overflowed");
|
||||
|
||||
assert!(new_bytes_flushed <= self.bytes_written);
|
||||
|
||||
self.bytes_flushed = new_bytes_flushed;
|
||||
|
||||
if self.bytes_flushed == self.bytes_written {
|
||||
// Reset cursors to zero if we've consumed the whole buffer
|
||||
self.bytes_flushed = 0;
|
||||
self.bytes_written = 0;
|
||||
}
|
||||
|
||||
self.sanity_check();
|
||||
}
|
||||
}
|
||||
|
||||
impl ReadBuffer {
|
||||
async fn read(&mut self, len: usize, socket: &mut impl Socket) -> io::Result<()> {
|
||||
// Because of how `BytesMut` works, we should only be shifting capacity back and forth
|
||||
// between `read` and `available` unless we have to read an oversize message.
|
||||
while self.read.len() < len {
|
||||
self.reserve(len - self.read.len());
|
||||
|
||||
let read = socket.read(&mut self.available).await?;
|
||||
|
||||
if read == 0 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::UnexpectedEof,
|
||||
format!(
|
||||
"expected to read {} bytes, got {} bytes at EOF",
|
||||
len,
|
||||
self.read.len()
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
self.advance(read);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reserve(&mut self, amt: usize) {
|
||||
if let Some(additional) = amt.checked_sub(self.available.capacity()) {
|
||||
self.available.reserve(additional);
|
||||
}
|
||||
}
|
||||
|
||||
fn advance(&mut self, amt: usize) {
|
||||
self.read.unsplit(self.available.split_to(amt));
|
||||
}
|
||||
|
||||
fn shrink(&mut self) {
|
||||
if self.available.capacity() > DEFAULT_BUF_SIZE {
|
||||
// `BytesMut` doesn't have a way to shrink its capacity,
|
||||
// but we only use `available` for spare capacity anyway so we can just replace it.
|
||||
//
|
||||
// If `self.read` still contains data on the next call to `advance` then this might
|
||||
// force a memcpy as they'll no longer be pointing to the same allocation,
|
||||
// but that's kind of unavoidable.
|
||||
//
|
||||
// The `async-std` impl of `Socket` will also need to re-zero the buffer,
|
||||
// but that's also kind of unavoidable.
|
||||
//
|
||||
// We should be warning the user not to call this often.
|
||||
self.available = BytesMut::with_capacity(DEFAULT_BUF_SIZE);
|
||||
}
|
||||
}
|
||||
}
|
||||
+294
@@ -0,0 +1,294 @@
|
||||
use std::future::Future;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::pin::Pin;
|
||||
use std::task::{ready, Context, Poll};
|
||||
|
||||
pub use buffered::{BufferedSocket, WriteBuffer};
|
||||
use bytes::BufMut;
|
||||
use cfg_if::cfg_if;
|
||||
|
||||
use crate::io::ReadBuf;
|
||||
|
||||
mod buffered;
|
||||
|
||||
pub trait Socket: Send + Sync + Unpin + 'static {
|
||||
fn try_read(&mut self, buf: &mut dyn ReadBuf) -> io::Result<usize>;
|
||||
|
||||
fn try_write(&mut self, buf: &[u8]) -> io::Result<usize>;
|
||||
|
||||
fn poll_read_ready(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>>;
|
||||
|
||||
fn poll_write_ready(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>>;
|
||||
|
||||
fn poll_flush(&mut self, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
// `flush()` is a no-op for TCP/UDS
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
|
||||
fn poll_shutdown(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>>;
|
||||
|
||||
fn read<'a, B: ReadBuf>(&'a mut self, buf: &'a mut B) -> Read<'a, Self, B>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
Read { socket: self, buf }
|
||||
}
|
||||
|
||||
fn write<'a>(&'a mut self, buf: &'a [u8]) -> Write<'a, Self>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
Write { socket: self, buf }
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> Flush<'_, Self>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
Flush { socket: self }
|
||||
}
|
||||
|
||||
fn shutdown(&mut self) -> Shutdown<'_, Self>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
Shutdown { socket: self }
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Read<'a, S: ?Sized, B> {
|
||||
socket: &'a mut S,
|
||||
buf: &'a mut B,
|
||||
}
|
||||
|
||||
impl<S: ?Sized, B> Future for Read<'_, S, B>
|
||||
where
|
||||
S: Socket,
|
||||
B: ReadBuf,
|
||||
{
|
||||
type Output = io::Result<usize>;
|
||||
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
let this = &mut *self;
|
||||
|
||||
while this.buf.has_remaining_mut() {
|
||||
match this.socket.try_read(&mut *this.buf) {
|
||||
Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
|
||||
ready!(this.socket.poll_read_ready(cx))?;
|
||||
}
|
||||
ready => return Poll::Ready(ready),
|
||||
}
|
||||
}
|
||||
|
||||
Poll::Ready(Ok(0))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Write<'a, S: ?Sized> {
|
||||
socket: &'a mut S,
|
||||
buf: &'a [u8],
|
||||
}
|
||||
|
||||
impl<S: ?Sized> Future for Write<'_, S>
|
||||
where
|
||||
S: Socket,
|
||||
{
|
||||
type Output = io::Result<usize>;
|
||||
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
let this = &mut *self;
|
||||
|
||||
while !this.buf.is_empty() {
|
||||
match this.socket.try_write(this.buf) {
|
||||
Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
|
||||
ready!(this.socket.poll_write_ready(cx))?;
|
||||
}
|
||||
ready => return Poll::Ready(ready),
|
||||
}
|
||||
}
|
||||
|
||||
Poll::Ready(Ok(0))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Flush<'a, S: ?Sized> {
|
||||
socket: &'a mut S,
|
||||
}
|
||||
|
||||
impl<S: Socket + ?Sized> Future for Flush<'_, S> {
|
||||
type Output = io::Result<()>;
|
||||
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
self.socket.poll_flush(cx)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Shutdown<'a, S: ?Sized> {
|
||||
socket: &'a mut S,
|
||||
}
|
||||
|
||||
impl<S: ?Sized> Future for Shutdown<'_, S>
|
||||
where
|
||||
S: Socket,
|
||||
{
|
||||
type Output = io::Result<()>;
|
||||
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
self.socket.poll_shutdown(cx)
|
||||
}
|
||||
}
|
||||
|
||||
pub trait WithSocket {
|
||||
type Output;
|
||||
|
||||
fn with_socket<S: Socket>(self, socket: S) -> impl Future<Output = Self::Output> + Send;
|
||||
}
|
||||
|
||||
pub struct SocketIntoBox;
|
||||
|
||||
impl WithSocket for SocketIntoBox {
|
||||
type Output = Box<dyn Socket>;
|
||||
|
||||
async fn with_socket<S: Socket>(self, socket: S) -> Self::Output {
|
||||
Box::new(socket)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: Socket + ?Sized> Socket for Box<S> {
|
||||
fn try_read(&mut self, buf: &mut dyn ReadBuf) -> io::Result<usize> {
|
||||
(**self).try_read(buf)
|
||||
}
|
||||
|
||||
fn try_write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
(**self).try_write(buf)
|
||||
}
|
||||
|
||||
fn poll_read_ready(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
(**self).poll_read_ready(cx)
|
||||
}
|
||||
|
||||
fn poll_write_ready(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
(**self).poll_write_ready(cx)
|
||||
}
|
||||
|
||||
fn poll_flush(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
(**self).poll_flush(cx)
|
||||
}
|
||||
|
||||
fn poll_shutdown(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
(**self).poll_shutdown(cx)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn connect_tcp<Ws: WithSocket>(
|
||||
host: &str,
|
||||
port: u16,
|
||||
with_socket: Ws,
|
||||
) -> crate::Result<Ws::Output> {
|
||||
#[cfg(feature = "_rt-tokio")]
|
||||
if crate::rt::rt_tokio::available() {
|
||||
return Ok(with_socket
|
||||
.with_socket(tokio::net::TcpStream::connect((host, port)).await?)
|
||||
.await);
|
||||
}
|
||||
|
||||
cfg_if! {
|
||||
if #[cfg(feature = "_rt-async-io")] {
|
||||
Ok(with_socket.with_socket(connect_tcp_async_io(host, port).await?).await)
|
||||
} else {
|
||||
crate::rt::missing_rt((host, port, with_socket))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a TCP socket to `host` and `port`.
|
||||
///
|
||||
/// If `host` is a hostname, attempt to connect to each address it resolves to.
|
||||
///
|
||||
/// This implements the same behavior as [`tokio::net::TcpStream::connect()`].
|
||||
#[cfg(feature = "_rt-async-io")]
|
||||
async fn connect_tcp_async_io(host: &str, port: u16) -> crate::Result<impl Socket> {
|
||||
use async_io::Async;
|
||||
use std::net::{IpAddr, TcpStream, ToSocketAddrs};
|
||||
|
||||
// IPv6 addresses in URLs will be wrapped in brackets and the `url` crate doesn't trim those.
|
||||
let host = host.trim_matches(&['[', ']'][..]);
|
||||
|
||||
if let Ok(addr) = host.parse::<IpAddr>() {
|
||||
return Ok(Async::<TcpStream>::connect((addr, port)).await?);
|
||||
}
|
||||
|
||||
let host = host.to_string();
|
||||
|
||||
let addresses = crate::rt::spawn_blocking(move || {
|
||||
let addr = (host.as_str(), port);
|
||||
ToSocketAddrs::to_socket_addrs(&addr)
|
||||
})
|
||||
.await?;
|
||||
|
||||
let mut last_err = None;
|
||||
|
||||
// Loop through all the Socket Addresses that the hostname resolves to
|
||||
for socket_addr in addresses {
|
||||
match Async::<TcpStream>::connect(socket_addr).await {
|
||||
Ok(stream) => return Ok(stream),
|
||||
Err(e) => last_err = Some(e),
|
||||
}
|
||||
}
|
||||
|
||||
// If we reach this point, it means we failed to connect to any of the addresses.
|
||||
// Return the last error we encountered, or a custom error if the hostname didn't resolve to any address.
|
||||
Err(last_err
|
||||
.unwrap_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::AddrNotAvailable,
|
||||
"Hostname did not resolve to any addresses",
|
||||
)
|
||||
})
|
||||
.into())
|
||||
}
|
||||
|
||||
/// Connect a Unix Domain Socket at the given path.
|
||||
///
|
||||
/// Returns an error if Unix Domain Sockets are not supported on this platform.
|
||||
pub async fn connect_uds<P: AsRef<Path>, Ws: WithSocket>(
|
||||
path: P,
|
||||
with_socket: Ws,
|
||||
) -> crate::Result<Ws::Output> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
#[cfg(feature = "_rt-tokio")]
|
||||
if crate::rt::rt_tokio::available() {
|
||||
use tokio::net::UnixStream;
|
||||
|
||||
let stream = UnixStream::connect(path).await?;
|
||||
|
||||
return Ok(with_socket.with_socket(stream).await);
|
||||
}
|
||||
|
||||
cfg_if! {
|
||||
if #[cfg(feature = "_rt-async-io")] {
|
||||
use async_io::Async;
|
||||
use std::os::unix::net::UnixStream;
|
||||
|
||||
let stream = Async::<UnixStream>::connect(path).await?;
|
||||
|
||||
Ok(with_socket.with_socket(stream).await)
|
||||
} else {
|
||||
crate::rt::missing_rt((path, with_socket))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
drop((path, with_socket));
|
||||
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"Unix domain sockets are not supported on this platform",
|
||||
)
|
||||
.into())
|
||||
}
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
#![allow(dead_code)]
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::error::Error;
|
||||
use crate::net::socket::WithSocket;
|
||||
use crate::net::Socket;
|
||||
|
||||
#[cfg(feature = "_tls-rustls")]
|
||||
mod tls_rustls;
|
||||
|
||||
#[cfg(feature = "_tls-native-tls")]
|
||||
mod tls_native_tls;
|
||||
|
||||
mod util;
|
||||
|
||||
/// X.509 Certificate input, either a file path or a PEM encoded inline certificate(s).
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum CertificateInput {
|
||||
/// PEM encoded certificate(s)
|
||||
Inline(Vec<u8>),
|
||||
/// Path to a file containing PEM encoded certificate(s)
|
||||
File(PathBuf),
|
||||
}
|
||||
|
||||
impl From<String> for CertificateInput {
|
||||
fn from(value: String) -> Self {
|
||||
// Leading and trailing whitespace/newlines
|
||||
let trimmed = value.trim();
|
||||
|
||||
// Heuristic for PEM encoded inputs:
|
||||
// https://tools.ietf.org/html/rfc7468
|
||||
if trimmed.starts_with("-----BEGIN") && trimmed.ends_with("-----") {
|
||||
CertificateInput::Inline(value.as_bytes().to_vec())
|
||||
} else {
|
||||
CertificateInput::File(PathBuf::from(value))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CertificateInput {
|
||||
async fn data(&self) -> Result<Vec<u8>, std::io::Error> {
|
||||
use crate::fs;
|
||||
match self {
|
||||
CertificateInput::Inline(v) => Ok(v.clone()),
|
||||
CertificateInput::File(path) => fs::read(path).await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for CertificateInput {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
CertificateInput::Inline(v) => write!(f, "{}", String::from_utf8_lossy(v.as_slice())),
|
||||
CertificateInput::File(path) => write!(f, "file: {}", path.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TlsConfig<'a> {
|
||||
pub accept_invalid_certs: bool,
|
||||
pub accept_invalid_hostnames: bool,
|
||||
pub hostname: &'a str,
|
||||
pub root_cert_path: Option<&'a CertificateInput>,
|
||||
pub client_cert_path: Option<&'a CertificateInput>,
|
||||
pub client_key_path: Option<&'a CertificateInput>,
|
||||
}
|
||||
|
||||
pub async fn handshake<S, Ws>(
|
||||
socket: S,
|
||||
config: TlsConfig<'_>,
|
||||
with_socket: Ws,
|
||||
) -> crate::Result<Ws::Output>
|
||||
where
|
||||
S: Socket,
|
||||
Ws: WithSocket,
|
||||
{
|
||||
#[cfg(feature = "_tls-native-tls")]
|
||||
return Ok(with_socket
|
||||
.with_socket(tls_native_tls::handshake(socket, config).await?)
|
||||
.await);
|
||||
|
||||
#[cfg(all(feature = "_tls-rustls", not(feature = "_tls-native-tls")))]
|
||||
return Ok(with_socket
|
||||
.with_socket(tls_rustls::handshake(socket, config).await?)
|
||||
.await);
|
||||
|
||||
#[cfg(not(any(feature = "_tls-native-tls", feature = "_tls-rustls")))]
|
||||
{
|
||||
drop((socket, config, with_socket));
|
||||
panic!("one of the `runtime-*-native-tls` or `runtime-*-rustls` features must be enabled")
|
||||
}
|
||||
}
|
||||
|
||||
pub fn available() -> bool {
|
||||
cfg!(any(feature = "_tls-native-tls", feature = "_tls-rustls"))
|
||||
}
|
||||
|
||||
pub fn error_if_unavailable() -> crate::Result<()> {
|
||||
if !available() {
|
||||
return Err(Error::tls(
|
||||
"TLS upgrade required by connect options \
|
||||
but SQLx was built without TLS support enabled",
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
use std::io::{self, Read, Write};
|
||||
|
||||
use crate::io::ReadBuf;
|
||||
use crate::net::tls::util::StdSocket;
|
||||
use crate::net::tls::TlsConfig;
|
||||
use crate::net::Socket;
|
||||
use crate::rt;
|
||||
use crate::Error;
|
||||
|
||||
use native_tls::{HandshakeError, Identity};
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
pub struct NativeTlsSocket<S: Socket> {
|
||||
stream: native_tls::TlsStream<StdSocket<S>>,
|
||||
}
|
||||
|
||||
impl<S: Socket> Socket for NativeTlsSocket<S> {
|
||||
fn try_read(&mut self, buf: &mut dyn ReadBuf) -> io::Result<usize> {
|
||||
self.stream.read(buf.init_mut())
|
||||
}
|
||||
|
||||
fn try_write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
self.stream.write(buf)
|
||||
}
|
||||
|
||||
fn poll_read_ready(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
self.stream.get_mut().poll_ready(cx)
|
||||
}
|
||||
|
||||
fn poll_write_ready(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
self.stream.get_mut().poll_ready(cx)
|
||||
}
|
||||
|
||||
fn poll_shutdown(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
match self.stream.shutdown() {
|
||||
Err(e) if e.kind() == io::ErrorKind::WouldBlock => self.stream.get_mut().poll_ready(cx),
|
||||
ready => Poll::Ready(ready),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn handshake<S: Socket>(
|
||||
socket: S,
|
||||
config: TlsConfig<'_>,
|
||||
) -> crate::Result<NativeTlsSocket<S>> {
|
||||
let mut builder = native_tls::TlsConnector::builder();
|
||||
|
||||
builder
|
||||
.danger_accept_invalid_certs(config.accept_invalid_certs)
|
||||
.danger_accept_invalid_hostnames(config.accept_invalid_hostnames);
|
||||
|
||||
if let Some(root_cert_path) = config.root_cert_path {
|
||||
let data = root_cert_path.data().await?;
|
||||
builder.add_root_certificate(native_tls::Certificate::from_pem(&data).map_err(Error::tls)?);
|
||||
}
|
||||
|
||||
// authentication using user's key-file and its associated certificate
|
||||
if let (Some(cert_path), Some(key_path)) = (config.client_cert_path, config.client_key_path) {
|
||||
let cert_path = cert_path.data().await?;
|
||||
let key_path = key_path.data().await?;
|
||||
let identity = Identity::from_pkcs8(&cert_path, &key_path).map_err(Error::tls)?;
|
||||
builder.identity(identity);
|
||||
}
|
||||
|
||||
// The openssl TlsConnector synchronously loads certificates from files.
|
||||
// Loading these files can block for tens of milliseconds.
|
||||
let connector = rt::spawn_blocking(move || builder.build())
|
||||
.await
|
||||
.map_err(Error::tls)?;
|
||||
|
||||
let mut mid_handshake = match connector.connect(config.hostname, StdSocket::new(socket)) {
|
||||
Ok(tls_stream) => return Ok(NativeTlsSocket { stream: tls_stream }),
|
||||
Err(HandshakeError::Failure(e)) => return Err(Error::tls(e)),
|
||||
Err(HandshakeError::WouldBlock(mid_handshake)) => mid_handshake,
|
||||
};
|
||||
|
||||
loop {
|
||||
mid_handshake.get_mut().ready().await?;
|
||||
|
||||
match mid_handshake.handshake() {
|
||||
Ok(tls_stream) => return Ok(NativeTlsSocket { stream: tls_stream }),
|
||||
Err(HandshakeError::Failure(e)) => return Err(Error::tls(e)),
|
||||
Err(HandshakeError::WouldBlock(mid_handshake_)) => {
|
||||
mid_handshake = mid_handshake_;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+340
@@ -0,0 +1,340 @@
|
||||
use std::future;
|
||||
use std::io::{self, Read, Write};
|
||||
use std::sync::Arc;
|
||||
use std::task::{ready, Context, Poll};
|
||||
|
||||
use rustls::{
|
||||
client::{
|
||||
danger::{ServerCertVerified, ServerCertVerifier},
|
||||
WebPkiServerVerifier,
|
||||
},
|
||||
crypto::{verify_tls12_signature, verify_tls13_signature, CryptoProvider},
|
||||
pki_types::{
|
||||
pem::{self, PemObject},
|
||||
CertificateDer, PrivateKeyDer, ServerName, UnixTime,
|
||||
},
|
||||
CertificateError, ClientConfig, ClientConnection, Error as TlsError, RootCertStore,
|
||||
};
|
||||
|
||||
use crate::error::Error;
|
||||
use crate::io::ReadBuf;
|
||||
use crate::net::tls::util::StdSocket;
|
||||
use crate::net::tls::TlsConfig;
|
||||
use crate::net::Socket;
|
||||
|
||||
pub struct RustlsSocket<S: Socket> {
|
||||
inner: StdSocket<S>,
|
||||
state: ClientConnection,
|
||||
close_notify_sent: bool,
|
||||
}
|
||||
|
||||
impl<S: Socket> RustlsSocket<S> {
|
||||
fn poll_complete_io(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
loop {
|
||||
match self.state.complete_io(&mut self.inner) {
|
||||
Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
|
||||
ready!(self.inner.poll_ready(cx))?;
|
||||
}
|
||||
ready => return Poll::Ready(ready.map(|_| ())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn complete_io(&mut self) -> io::Result<()> {
|
||||
future::poll_fn(|cx| self.poll_complete_io(cx)).await
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: Socket> Socket for RustlsSocket<S> {
|
||||
fn try_read(&mut self, buf: &mut dyn ReadBuf) -> io::Result<usize> {
|
||||
self.state.reader().read(buf.init_mut())
|
||||
}
|
||||
|
||||
fn try_write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
match self.state.writer().write(buf) {
|
||||
// Returns a zero-length write when the buffer is full.
|
||||
Ok(0) => Err(io::ErrorKind::WouldBlock.into()),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_read_ready(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
self.poll_complete_io(cx)
|
||||
}
|
||||
|
||||
fn poll_write_ready(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
self.poll_complete_io(cx)
|
||||
}
|
||||
|
||||
fn poll_flush(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
self.poll_complete_io(cx)
|
||||
}
|
||||
|
||||
fn poll_shutdown(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
if !self.close_notify_sent {
|
||||
self.state.send_close_notify();
|
||||
self.close_notify_sent = true;
|
||||
}
|
||||
|
||||
ready!(self.poll_complete_io(cx))?;
|
||||
|
||||
// Server can close socket as soon as it receives the connection shutdown request.
|
||||
// We shouldn't expect it to stick around for the TLS session to close cleanly.
|
||||
// https://security.stackexchange.com/a/82034
|
||||
let _ = ready!(self.inner.socket.poll_shutdown(cx));
|
||||
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn handshake<S>(socket: S, tls_config: TlsConfig<'_>) -> Result<RustlsSocket<S>, Error>
|
||||
where
|
||||
S: Socket,
|
||||
{
|
||||
#[cfg(all(
|
||||
feature = "_tls-rustls-aws-lc-rs",
|
||||
not(feature = "_tls-rustls-ring-webpki"),
|
||||
not(feature = "_tls-rustls-ring-native-roots")
|
||||
))]
|
||||
let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider());
|
||||
#[cfg(any(
|
||||
feature = "_tls-rustls-ring-webpki",
|
||||
feature = "_tls-rustls-ring-native-roots"
|
||||
))]
|
||||
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
||||
|
||||
// Unwrapping is safe here because we use a default provider.
|
||||
let config = ClientConfig::builder_with_provider(provider.clone())
|
||||
.with_safe_default_protocol_versions()
|
||||
.unwrap();
|
||||
|
||||
// authentication using user's key and its associated certificate
|
||||
let user_auth = match (tls_config.client_cert_path, tls_config.client_key_path) {
|
||||
(Some(cert_path), Some(key_path)) => {
|
||||
let cert_chain = certs_from_pem(cert_path.data().await?)?;
|
||||
let key_der = private_key_from_pem(key_path.data().await?)?;
|
||||
Some((cert_chain, key_der))
|
||||
}
|
||||
(None, None) => None,
|
||||
(_, _) => {
|
||||
return Err(Error::Configuration(
|
||||
"user auth key and certs must be given together".into(),
|
||||
))
|
||||
}
|
||||
};
|
||||
|
||||
let config = if tls_config.accept_invalid_certs {
|
||||
if let Some(user_auth) = user_auth {
|
||||
config
|
||||
.dangerous()
|
||||
.with_custom_certificate_verifier(Arc::new(DummyTlsVerifier { provider }))
|
||||
.with_client_auth_cert(user_auth.0, user_auth.1)
|
||||
.map_err(Error::tls)?
|
||||
} else {
|
||||
config
|
||||
.dangerous()
|
||||
.with_custom_certificate_verifier(Arc::new(DummyTlsVerifier { provider }))
|
||||
.with_no_client_auth()
|
||||
}
|
||||
} else {
|
||||
let mut cert_store = import_root_certs();
|
||||
|
||||
if let Some(ca) = tls_config.root_cert_path {
|
||||
let data = ca.data().await?;
|
||||
|
||||
for result in CertificateDer::pem_slice_iter(&data) {
|
||||
let Ok(cert) = result else {
|
||||
return Err(Error::Tls(format!("Invalid certificate {ca}").into()));
|
||||
};
|
||||
|
||||
cert_store.add(cert).map_err(|err| Error::Tls(err.into()))?;
|
||||
}
|
||||
}
|
||||
|
||||
if tls_config.accept_invalid_hostnames {
|
||||
let verifier = WebPkiServerVerifier::builder(Arc::new(cert_store))
|
||||
.build()
|
||||
.map_err(|err| Error::Tls(err.into()))?;
|
||||
|
||||
if let Some(user_auth) = user_auth {
|
||||
config
|
||||
.dangerous()
|
||||
.with_custom_certificate_verifier(Arc::new(NoHostnameTlsVerifier { verifier }))
|
||||
.with_client_auth_cert(user_auth.0, user_auth.1)
|
||||
.map_err(Error::tls)?
|
||||
} else {
|
||||
config
|
||||
.dangerous()
|
||||
.with_custom_certificate_verifier(Arc::new(NoHostnameTlsVerifier { verifier }))
|
||||
.with_no_client_auth()
|
||||
}
|
||||
} else if let Some(user_auth) = user_auth {
|
||||
config
|
||||
.with_root_certificates(cert_store)
|
||||
.with_client_auth_cert(user_auth.0, user_auth.1)
|
||||
.map_err(Error::tls)?
|
||||
} else {
|
||||
config
|
||||
.with_root_certificates(cert_store)
|
||||
.with_no_client_auth()
|
||||
}
|
||||
};
|
||||
|
||||
let host = ServerName::try_from(tls_config.hostname.to_owned()).map_err(Error::tls)?;
|
||||
|
||||
let mut socket = RustlsSocket {
|
||||
inner: StdSocket::new(socket),
|
||||
state: ClientConnection::new(Arc::new(config), host).map_err(Error::tls)?,
|
||||
close_notify_sent: false,
|
||||
};
|
||||
|
||||
// Performs the TLS handshake or bails
|
||||
socket.complete_io().await?;
|
||||
|
||||
Ok(socket)
|
||||
}
|
||||
|
||||
fn certs_from_pem(pem: Vec<u8>) -> Result<Vec<CertificateDer<'static>>, Error> {
|
||||
CertificateDer::pem_slice_iter(&pem)
|
||||
.map(|result| result.map_err(|err| Error::Tls(err.into())))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn private_key_from_pem(pem: Vec<u8>) -> Result<PrivateKeyDer<'static>, Error> {
|
||||
match PrivateKeyDer::from_pem_slice(&pem) {
|
||||
Ok(key) => Ok(key),
|
||||
Err(pem::Error::NoItemsFound) => Err(Error::Configuration("no keys found pem file".into())),
|
||||
Err(e) => Err(Error::Configuration(e.to_string().into())),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "webpki-roots", not(feature = "rustls-native-certs")))]
|
||||
fn import_root_certs() -> RootCertStore {
|
||||
RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned())
|
||||
}
|
||||
|
||||
#[cfg(feature = "rustls-native-certs")]
|
||||
fn import_root_certs() -> RootCertStore {
|
||||
let mut root_cert_store = RootCertStore::empty();
|
||||
|
||||
let load_results = rustls_native_certs::load_native_certs();
|
||||
for e in load_results.errors {
|
||||
log::warn!("Error loading native certificates: {e:?}");
|
||||
}
|
||||
for cert in load_results.certs {
|
||||
if let Err(e) = root_cert_store.add(cert) {
|
||||
log::warn!("rustls failed to parse native certificate: {e:?}");
|
||||
}
|
||||
}
|
||||
|
||||
root_cert_store
|
||||
}
|
||||
|
||||
// Not currently used but allows for a "tls-rustls-no-roots" feature.
|
||||
#[cfg(not(any(feature = "rustls-native-certs", feature = "webpki-roots")))]
|
||||
fn import_root_certs() -> RootCertStore {
|
||||
RootCertStore::empty()
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct DummyTlsVerifier {
|
||||
provider: Arc<CryptoProvider>,
|
||||
}
|
||||
|
||||
impl ServerCertVerifier for DummyTlsVerifier {
|
||||
fn verify_server_cert(
|
||||
&self,
|
||||
_end_entity: &CertificateDer<'_>,
|
||||
_intermediates: &[CertificateDer<'_>],
|
||||
_server_name: &ServerName<'_>,
|
||||
_ocsp_response: &[u8],
|
||||
_now: UnixTime,
|
||||
) -> Result<ServerCertVerified, TlsError> {
|
||||
Ok(ServerCertVerified::assertion())
|
||||
}
|
||||
|
||||
fn verify_tls12_signature(
|
||||
&self,
|
||||
message: &[u8],
|
||||
cert: &CertificateDer<'_>,
|
||||
dss: &rustls::DigitallySignedStruct,
|
||||
) -> Result<rustls::client::danger::HandshakeSignatureValid, TlsError> {
|
||||
verify_tls12_signature(
|
||||
message,
|
||||
cert,
|
||||
dss,
|
||||
&self.provider.signature_verification_algorithms,
|
||||
)
|
||||
}
|
||||
|
||||
fn verify_tls13_signature(
|
||||
&self,
|
||||
message: &[u8],
|
||||
cert: &CertificateDer<'_>,
|
||||
dss: &rustls::DigitallySignedStruct,
|
||||
) -> Result<rustls::client::danger::HandshakeSignatureValid, TlsError> {
|
||||
verify_tls13_signature(
|
||||
message,
|
||||
cert,
|
||||
dss,
|
||||
&self.provider.signature_verification_algorithms,
|
||||
)
|
||||
}
|
||||
|
||||
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
|
||||
self.provider
|
||||
.signature_verification_algorithms
|
||||
.supported_schemes()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct NoHostnameTlsVerifier {
|
||||
verifier: Arc<WebPkiServerVerifier>,
|
||||
}
|
||||
|
||||
impl ServerCertVerifier for NoHostnameTlsVerifier {
|
||||
fn verify_server_cert(
|
||||
&self,
|
||||
end_entity: &CertificateDer<'_>,
|
||||
intermediates: &[CertificateDer<'_>],
|
||||
server_name: &ServerName<'_>,
|
||||
ocsp_response: &[u8],
|
||||
now: UnixTime,
|
||||
) -> Result<ServerCertVerified, TlsError> {
|
||||
match self.verifier.verify_server_cert(
|
||||
end_entity,
|
||||
intermediates,
|
||||
server_name,
|
||||
ocsp_response,
|
||||
now,
|
||||
) {
|
||||
Err(TlsError::InvalidCertificate(
|
||||
CertificateError::NotValidForName | CertificateError::NotValidForNameContext { .. },
|
||||
)) => Ok(ServerCertVerified::assertion()),
|
||||
res => res,
|
||||
}
|
||||
}
|
||||
|
||||
fn verify_tls12_signature(
|
||||
&self,
|
||||
message: &[u8],
|
||||
cert: &CertificateDer<'_>,
|
||||
dss: &rustls::DigitallySignedStruct,
|
||||
) -> Result<rustls::client::danger::HandshakeSignatureValid, TlsError> {
|
||||
self.verifier.verify_tls12_signature(message, cert, dss)
|
||||
}
|
||||
|
||||
fn verify_tls13_signature(
|
||||
&self,
|
||||
message: &[u8],
|
||||
cert: &CertificateDer<'_>,
|
||||
dss: &rustls::DigitallySignedStruct,
|
||||
) -> Result<rustls::client::danger::HandshakeSignatureValid, TlsError> {
|
||||
self.verifier.verify_tls13_signature(message, cert, dss)
|
||||
}
|
||||
|
||||
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
|
||||
self.verifier.supported_verify_schemes()
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
use crate::net::Socket;
|
||||
|
||||
use std::future;
|
||||
use std::io::{self, Read, Write};
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
pub struct StdSocket<S> {
|
||||
pub socket: S,
|
||||
wants_read: bool,
|
||||
wants_write: bool,
|
||||
}
|
||||
|
||||
impl<S: Socket> StdSocket<S> {
|
||||
pub fn new(socket: S) -> Self {
|
||||
Self {
|
||||
socket,
|
||||
wants_read: false,
|
||||
wants_write: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `Ready` if a previously blocked read _or_ write may now proceed.
|
||||
///
|
||||
/// If both a read and a write were attempted, to avoid deadlocks this returns `Ready`
|
||||
/// when _either_ direction is ready, not necessarily both.
|
||||
pub fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
// Return `Ready` without waiting if the caller hasn't tried to do I/O in either direction.
|
||||
let mut ready = !(self.wants_read || self.wants_write);
|
||||
|
||||
if self.wants_write && self.socket.poll_write_ready(cx)?.is_ready() {
|
||||
self.wants_write = false;
|
||||
ready |= true;
|
||||
}
|
||||
|
||||
if self.wants_read && self.socket.poll_read_ready(cx)?.is_ready() {
|
||||
self.wants_read = false;
|
||||
ready |= true;
|
||||
}
|
||||
|
||||
if ready {
|
||||
Poll::Ready(Ok(()))
|
||||
} else {
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns successfully if a previously blocked read _or_ write may now proceed.
|
||||
///
|
||||
/// If both a read and a write were attempted, to avoid deadlocks this returns when _either_
|
||||
/// direction is ready, not necessarily both.
|
||||
pub async fn ready(&mut self) -> io::Result<()> {
|
||||
future::poll_fn(|cx| self.poll_ready(cx)).await
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: Socket> Read for StdSocket<S> {
|
||||
fn read(&mut self, mut buf: &mut [u8]) -> io::Result<usize> {
|
||||
self.wants_read = true;
|
||||
let read = self.socket.try_read(&mut buf)?;
|
||||
self.wants_read = false;
|
||||
|
||||
Ok(read)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: Socket> Write for StdSocket<S> {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
self.wants_write = true;
|
||||
let written = self.socket.try_write(buf)?;
|
||||
self.wants_write = false;
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
// NOTE: TCP sockets and unix sockets are both no-ops for flushes
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user