Skip to main content

sqlx_core/net/socket/
mod.rs

1use std::future::Future;
2use std::io;
3use std::path::Path;
4use std::pin::Pin;
5use std::task::{ready, Context, Poll};
6
7use crate::io::ReadBuf;
8use crate::net::SocketHost;
9pub use buffered::{BufferedSocket, WriteBuffer};
10use bytes::BufMut;
11use cfg_if::cfg_if;
12
13mod buffered;
14
15pub trait Socket: Send + Sync + Unpin + 'static {
16    fn try_read(&mut self, buf: &mut dyn ReadBuf) -> io::Result<usize>;
17
18    fn try_write(&mut self, buf: &[u8]) -> io::Result<usize>;
19
20    fn poll_read_ready(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>>;
21
22    fn poll_write_ready(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>>;
23
24    fn poll_flush(&mut self, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
25        // `flush()` is a no-op for TCP/UDS
26        Poll::Ready(Ok(()))
27    }
28
29    fn poll_shutdown(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>>;
30
31    fn read<'a, B: ReadBuf>(&'a mut self, buf: &'a mut B) -> Read<'a, Self, B>
32    where
33        Self: Sized,
34    {
35        Read { socket: self, buf }
36    }
37
38    fn write<'a>(&'a mut self, buf: &'a [u8]) -> Write<'a, Self>
39    where
40        Self: Sized,
41    {
42        Write { socket: self, buf }
43    }
44
45    fn flush(&mut self) -> Flush<'_, Self>
46    where
47        Self: Sized,
48    {
49        Flush { socket: self }
50    }
51
52    fn shutdown(&mut self) -> Shutdown<'_, Self>
53    where
54        Self: Sized,
55    {
56        Shutdown { socket: self }
57    }
58}
59
60pub struct Read<'a, S: ?Sized, B> {
61    socket: &'a mut S,
62    buf: &'a mut B,
63}
64
65impl<S: ?Sized, B> Future for Read<'_, S, B>
66where
67    S: Socket,
68    B: ReadBuf,
69{
70    type Output = io::Result<usize>;
71
72    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
73        let this = &mut *self;
74
75        while this.buf.has_remaining_mut() {
76            match this.socket.try_read(&mut *this.buf) {
77                Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
78                    ready!(this.socket.poll_read_ready(cx))?;
79                }
80                ready => return Poll::Ready(ready),
81            }
82        }
83
84        Poll::Ready(Ok(0))
85    }
86}
87
88pub struct Write<'a, S: ?Sized> {
89    socket: &'a mut S,
90    buf: &'a [u8],
91}
92
93impl<S: ?Sized> Future for Write<'_, S>
94where
95    S: Socket,
96{
97    type Output = io::Result<usize>;
98
99    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
100        let this = &mut *self;
101
102        while !this.buf.is_empty() {
103            match this.socket.try_write(this.buf) {
104                Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
105                    ready!(this.socket.poll_write_ready(cx))?;
106                }
107                ready => return Poll::Ready(ready),
108            }
109        }
110
111        Poll::Ready(Ok(0))
112    }
113}
114
115pub struct Flush<'a, S: ?Sized> {
116    socket: &'a mut S,
117}
118
119impl<S: Socket + ?Sized> Future for Flush<'_, S> {
120    type Output = io::Result<()>;
121
122    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
123        self.socket.poll_flush(cx)
124    }
125}
126
127pub struct Shutdown<'a, S: ?Sized> {
128    socket: &'a mut S,
129}
130
131impl<S: ?Sized> Future for Shutdown<'_, S>
132where
133    S: Socket,
134{
135    type Output = io::Result<()>;
136
137    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
138        self.socket.poll_shutdown(cx)
139    }
140}
141
142pub trait WithSocket {
143    type Output;
144
145    fn with_socket<S: Socket>(self, socket: S) -> impl Future<Output = Self::Output> + Send;
146}
147
148pub struct SocketIntoBox;
149
150impl WithSocket for SocketIntoBox {
151    type Output = Box<dyn Socket>;
152
153    async fn with_socket<S: Socket>(self, socket: S) -> Self::Output {
154        Box::new(socket)
155    }
156}
157
158impl<S: Socket + ?Sized> Socket for Box<S> {
159    fn try_read(&mut self, buf: &mut dyn ReadBuf) -> io::Result<usize> {
160        (**self).try_read(buf)
161    }
162
163    fn try_write(&mut self, buf: &[u8]) -> io::Result<usize> {
164        (**self).try_write(buf)
165    }
166
167    fn poll_read_ready(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
168        (**self).poll_read_ready(cx)
169    }
170
171    fn poll_write_ready(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
172        (**self).poll_write_ready(cx)
173    }
174
175    fn poll_flush(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
176        (**self).poll_flush(cx)
177    }
178
179    fn poll_shutdown(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
180        (**self).poll_shutdown(cx)
181    }
182}
183
184pub async fn connect_tcp<Ws: WithSocket>(
185    host: SocketHost<'_>,
186    port: u16,
187    with_socket: Ws,
188) -> crate::Result<Ws::Output> {
189    #[cfg(feature = "_rt-tokio")]
190    if crate::rt::rt_tokio::available() {
191        use tokio::net::TcpStream;
192
193        let socket = match host.try_as_ip() {
194            Ok(addr) => TcpStream::connect((addr, port)).await?,
195            Err(host) => TcpStream::connect((host, port)).await?,
196        };
197
198        socket.set_nodelay(true)?;
199        return Ok(with_socket.with_socket(socket).await);
200    }
201
202    cfg_if! {
203        if #[cfg(feature = "_rt-async-io")] {
204            Ok(with_socket.with_socket(connect_tcp_async_io(host, port).await?).await)
205        } else {
206            crate::rt::missing_rt((host.try_as_ip(), port, with_socket))
207        }
208    }
209}
210
211/// Open a TCP socket to `host` and `port`.
212///
213/// If `host` is a hostname, attempt to connect to each address it resolves to.
214///
215/// This implements the same behavior as [`tokio::net::TcpStream::connect()`] and additionally sets the `TCP_NODELAY` flag.
216#[cfg(feature = "_rt-async-io")]
217async fn connect_tcp_async_io(host: SocketHost<'_>, port: u16) -> crate::Result<impl Socket> {
218    use async_io::Async;
219    use std::net::{TcpStream, ToSocketAddrs};
220
221    let host: Box<str> = match host.try_as_ip() {
222        Ok(addr) => {
223            let socket = Async::<TcpStream>::connect((addr, port)).await?;
224            socket.get_ref().set_nodelay(true)?;
225            return Ok(socket);
226        }
227        Err(host) => host.into(),
228    };
229
230    let addresses =
231        crate::rt::spawn_blocking(move || ToSocketAddrs::to_socket_addrs(&(&host[..], port)))
232            .await?;
233
234    let mut last_err = None;
235
236    // Loop through all the Socket Addresses that the hostname resolves to
237    for socket_addr in addresses {
238        match Async::<TcpStream>::connect(socket_addr).await {
239            Ok(stream) => {
240                stream.get_ref().set_nodelay(true)?;
241                return Ok(stream);
242            }
243            Err(e) => last_err = Some(e),
244        }
245    }
246
247    // If we reach this point, it means we failed to connect to any of the addresses.
248    // Return the last error we encountered, or a custom error if the hostname didn't resolve to any address.
249    Err(last_err
250        .unwrap_or_else(|| {
251            io::Error::new(
252                io::ErrorKind::AddrNotAvailable,
253                "Hostname did not resolve to any addresses",
254            )
255        })
256        .into())
257}
258
259/// Connect a Unix Domain Socket at the given path.
260///
261/// Returns an error if Unix Domain Sockets are not supported on this platform.
262pub async fn connect_uds<P: AsRef<Path>, Ws: WithSocket>(
263    path: P,
264    with_socket: Ws,
265) -> crate::Result<Ws::Output> {
266    #[cfg(unix)]
267    {
268        #[cfg(feature = "_rt-tokio")]
269        if crate::rt::rt_tokio::available() {
270            use tokio::net::UnixStream;
271
272            let stream = UnixStream::connect(path).await?;
273
274            return Ok(with_socket.with_socket(stream).await);
275        }
276
277        cfg_if! {
278            if #[cfg(feature = "_rt-async-io")] {
279                use async_io::Async;
280                use std::os::unix::net::UnixStream;
281
282                let stream = Async::<UnixStream>::connect(path).await?;
283
284                Ok(with_socket.with_socket(stream).await)
285            } else {
286                crate::rt::missing_rt((path, with_socket))
287            }
288        }
289    }
290
291    #[cfg(not(unix))]
292    {
293        drop((path, with_socket));
294
295        Err(io::Error::new(
296            io::ErrorKind::Unsupported,
297            "Unix domain sockets are not supported on this platform",
298        )
299        .into())
300    }
301}