1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
use crate::net::{TcpListener, TcpStream};

use std::fmt;
use std::io;
use std::net::SocketAddr;

#[cfg(unix)]
use std::os::unix::io::{AsRawFd, FromRawFd, RawFd};
#[cfg(windows)]
use std::os::windows::io::{AsRawSocket, FromRawSocket, IntoRawSocket, RawSocket};

/// A TCP socket that has not yet been converted to a `TcpStream` or
/// `TcpListener`.
///
/// `TcpSocket` wraps an operating system socket and enables the caller to
/// configure the socket before establishing a TCP connection or accepting
/// inbound connections. The caller is able to set socket option and explicitly
/// bind the socket with a socket address.
///
/// The underlying socket is closed when the `TcpSocket` value is dropped.
///
/// `TcpSocket` should only be used directly if the default configuration used
/// by `TcpStream::connect` and `TcpListener::bind` does not meet the required
/// use case.
///
/// Calling `TcpStream::connect("127.0.0.1:8080")` is equivalent to:
///
/// ```no_run
/// use tokio::net::TcpSocket;
///
/// use std::io;
///
/// #[tokio::main]
/// async fn main() -> io::Result<()> {
///     let addr = "127.0.0.1:8080".parse().unwrap();
///
///     let socket = TcpSocket::new_v4()?;
///     let stream = socket.connect(addr).await?;
/// # drop(stream);
///
///     Ok(())
/// }
/// ```
///
/// Calling `TcpListener::bind("127.0.0.1:8080")` is equivalent to:
///
/// ```no_run
/// use tokio::net::TcpSocket;
///
/// use std::io;
///
/// #[tokio::main]
/// async fn main() -> io::Result<()> {
///     let addr = "127.0.0.1:8080".parse().unwrap();
///
///     let socket = TcpSocket::new_v4()?;
///     // On platforms with Berkeley-derived sockets, this allows to quickly
///     // rebind a socket, without needing to wait for the OS to clean up the
///     // previous one.
///     //
///     // On Windows, this allows rebinding sockets which are actively in use,
///     // which allows “socket hijacking”, so we explicitly don't set it here.
///     // https://docs.microsoft.com/en-us/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse
///     socket.set_reuseaddr(true)?;
///     socket.bind(addr)?;
///
///     let listener = socket.listen(1024)?;
/// # drop(listener);
///
///     Ok(())
/// }
/// ```
///
/// Setting socket options not explicitly provided by `TcpSocket` may be done by
/// accessing the `RawFd`/`RawSocket` using [`AsRawFd`]/[`AsRawSocket`] and
/// setting the option with a crate like [`socket2`].
///
/// [`RawFd`]: https://doc.rust-lang.org/std/os/unix/io/type.RawFd.html
/// [`RawSocket`]: https://doc.rust-lang.org/std/os/windows/io/type.RawSocket.html
/// [`AsRawFd`]: https://doc.rust-lang.org/std/os/unix/io/trait.AsRawFd.html
/// [`AsRawSocket`]: https://doc.rust-lang.org/std/os/windows/io/trait.AsRawSocket.html
/// [`socket2`]: https://docs.rs/socket2/
pub struct TcpSocket {
    inner: mio::net::TcpSocket,
}

impl TcpSocket {
    /// Create a new socket configured for IPv4.
    ///
    /// Calls `socket(2)` with `AF_INET` and `SOCK_STREAM`.
    ///
    /// # Returns
    ///
    /// On success, the newly created `TcpSocket` is returned. If an error is
    /// encountered, it is returned instead.
    ///
    /// # Examples
    ///
    /// Create a new IPv4 socket and start listening.
    ///
    /// ```no_run
    /// use tokio::net::TcpSocket;
    ///
    /// use std::io;
    ///
    /// #[tokio::main]
    /// async fn main() -> io::Result<()> {
    ///     let addr = "127.0.0.1:8080".parse().unwrap();
    ///     let socket = TcpSocket::new_v4()?;
    ///     socket.bind(addr)?;
    ///
    ///     let listener = socket.listen(128)?;
    /// # drop(listener);
    ///     Ok(())
    /// }
    /// ```
    pub fn new_v4() -> io::Result<TcpSocket> {
        let inner = mio::net::TcpSocket::new_v4()?;
        Ok(TcpSocket { inner })
    }

    /// Create a new socket configured for IPv6.
    ///
    /// Calls `socket(2)` with `AF_INET6` and `SOCK_STREAM`.
    ///
    /// # Returns
    ///
    /// On success, the newly created `TcpSocket` is returned. If an error is
    /// encountered, it is returned instead.
    ///
    /// # Examples
    ///
    /// Create a new IPv6 socket and start listening.
    ///
    /// ```no_run
    /// use tokio::net::TcpSocket;
    ///
    /// use std::io;
    ///
    /// #[tokio::main]
    /// async fn main() -> io::Result<()> {
    ///     let addr = "[::1]:8080".parse().unwrap();
    ///     let socket = TcpSocket::new_v6()?;
    ///     socket.bind(addr)?;
    ///
    ///     let listener = socket.listen(128)?;
    /// # drop(listener);
    ///     Ok(())
    /// }
    /// ```
    pub fn new_v6() -> io::Result<TcpSocket> {
        let inner = mio::net::TcpSocket::new_v6()?;
        Ok(TcpSocket { inner })
    }

    /// Allow the socket to bind to an in-use address.
    ///
    /// Behavior is platform specific. Refer to the target platform's
    /// documentation for more details.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use tokio::net::TcpSocket;
    ///
    /// use std::io;
    ///
    /// #[tokio::main]
    /// async fn main() -> io::Result<()> {
    ///     let addr = "127.0.0.1:8080".parse().unwrap();
    ///
    ///     let socket = TcpSocket::new_v4()?;
    ///     socket.set_reuseaddr(true)?;
    ///     socket.bind(addr)?;
    ///
    ///     let listener = socket.listen(1024)?;
    /// # drop(listener);
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn set_reuseaddr(&self, reuseaddr: bool) -> io::Result<()> {
        self.inner.set_reuseaddr(reuseaddr)
    }

    /// Bind the socket to the given address.
    ///
    /// This calls the `bind(2)` operating-system function. Behavior is
    /// platform specific. Refer to the target platform's documentation for more
    /// details.
    ///
    /// # Examples
    ///
    /// Bind a socket before listening.
    ///
    /// ```no_run
    /// use tokio::net::TcpSocket;
    ///
    /// use std::io;
    ///
    /// #[tokio::main]
    /// async fn main() -> io::Result<()> {
    ///     let addr = "127.0.0.1:8080".parse().unwrap();
    ///
    ///     let socket = TcpSocket::new_v4()?;
    ///     socket.bind(addr)?;
    ///
    ///     let listener = socket.listen(1024)?;
    /// # drop(listener);
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn bind(&self, addr: SocketAddr) -> io::Result<()> {
        self.inner.bind(addr)
    }

    /// Establish a TCP connection with a peer at the specified socket address.
    ///
    /// The `TcpSocket` is consumed. Once the connection is established, a
    /// connected [`TcpStream`] is returned. If the connection fails, the
    /// encountered error is returned.
    ///
    /// [`TcpStream`]: TcpStream
    ///
    /// This calls the `connect(2)` operating-system function. Behavior is
    /// platform specific. Refer to the target platform's documentation for more
    /// details.
    ///
    /// # Examples
    ///
    /// Connecting to a peer.
    ///
    /// ```no_run
    /// use tokio::net::TcpSocket;
    ///
    /// use std::io;
    ///
    /// #[tokio::main]
    /// async fn main() -> io::Result<()> {
    ///     let addr = "127.0.0.1:8080".parse().unwrap();
    ///
    ///     let socket = TcpSocket::new_v4()?;
    ///     let stream = socket.connect(addr).await?;
    /// # drop(stream);
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn connect(self, addr: SocketAddr) -> io::Result<TcpStream> {
        let mio = self.inner.connect(addr)?;
        TcpStream::connect_mio(mio).await
    }

    /// Convert the socket into a `TcpListener`.
    ///
    /// `backlog` defines the maximum number of pending connections are queued
    /// by the operating system at any given time. Connection are removed from
    /// the queue with [`TcpListener::accept`]. When the queue is full, the
    /// operationg-system will start rejecting connections.
    ///
    /// [`TcpListener::accept`]: TcpListener::accept
    ///
    /// This calls the `listen(2)` operating-system function, marking the socket
    /// as a passive socket. Behavior is platform specific. Refer to the target
    /// platform's documentation for more details.
    ///
    /// # Examples
    ///
    /// Create a `TcpListener`.
    ///
    /// ```no_run
    /// use tokio::net::TcpSocket;
    ///
    /// use std::io;
    ///
    /// #[tokio::main]
    /// async fn main() -> io::Result<()> {
    ///     let addr = "127.0.0.1:8080".parse().unwrap();
    ///
    ///     let socket = TcpSocket::new_v4()?;
    ///     socket.bind(addr)?;
    ///
    ///     let listener = socket.listen(1024)?;
    /// # drop(listener);
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn listen(self, backlog: u32) -> io::Result<TcpListener> {
        let mio = self.inner.listen(backlog)?;
        TcpListener::new(mio)
    }
}

impl fmt::Debug for TcpSocket {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.inner.fmt(fmt)
    }
}

#[cfg(unix)]
impl AsRawFd for TcpSocket {
    fn as_raw_fd(&self) -> RawFd {
        self.inner.as_raw_fd()
    }
}

#[cfg(unix)]
impl FromRawFd for TcpSocket {
    /// Converts a `RawFd` to a `TcpSocket`.
    ///
    /// # Notes
    ///
    /// The caller is responsible for ensuring that the socket is in
    /// non-blocking mode.
    unsafe fn from_raw_fd(fd: RawFd) -> TcpSocket {
        let inner = mio::net::TcpSocket::from_raw_fd(fd);
        TcpSocket { inner }
    }
}

#[cfg(windows)]
impl IntoRawSocket for TcpSocket {
    fn into_raw_socket(self) -> RawSocket {
        self.inner.into_raw_socket()
    }
}

#[cfg(windows)]
impl AsRawSocket for TcpSocket {
    fn as_raw_socket(&self) -> RawSocket {
        self.inner.as_raw_socket()
    }
}

#[cfg(windows)]
impl FromRawSocket for TcpSocket {
    /// Converts a `RawSocket` to a `TcpStream`.
    ///
    /// # Notes
    ///
    /// The caller is responsible for ensuring that the socket is in
    /// non-blocking mode.
    unsafe fn from_raw_socket(socket: RawSocket) -> TcpSocket {
        let inner = mio::net::TcpSocket::from_raw_socket(socket);
        TcpSocket { inner }
    }
}