Skip to content

Refactor part 4 #124

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 20 commits into from
Nov 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 21 additions & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,21 +1,34 @@
[package]
name = "socket2"
version = "0.4.0-dev"
authors = ["Alex Crichton <alex@alexcrichton.com>"]
license = "MIT/Apache-2.0"
readme = "README.md"
repository = "https://github.com/alexcrichton/socket2-rs"
homepage = "https://github.com/alexcrichton/socket2-rs"
name = "socket2"
version = "0.4.0-dev"
authors = ["Alex Crichton <alex@alexcrichton.com>"]
license = "MIT/Apache-2.0"
readme = "README.md"
repository = "https://github.com/rust-lang/socket2-rs"
homepage = "https://github.com/rust-lang/socket2-rs"
documentation = "https://docs.rs/socket2"
description = """
Utilities for handling networking sockets with a maximal amount of configuration
possible intended.
"""
edition = "2018"
keywords = ["io", "socket", "network"]
categories = ["api-bindings", "network-programming"]
edition = "2018"
include = [
"Cargo.toml",
"LICENSE-APACHE",
"LICENSE-MIT",
"README.md",
"src/**/*.rs",
]

[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]

[package.metadata.playground]
features = ["all"]

[target."cfg(windows)".dependencies.winapi]
version = "0.3.3"
features = ["handleapi", "ws2def", "ws2ipdef", "ws2tcpip", "minwindef"]
Expand Down
73 changes: 52 additions & 21 deletions src/socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,14 @@ use crate::{Domain, Protocol, SockAddr, Type};
/// [`TcpStream`]: std::net::TcpStream
/// [`UdpSocket`]: std::net::UdpSocket
///
/// # Notes
///
/// Some methods that set options on `Socket` require two system calls to set
/// there options without overwriting previously set options. We do this by
/// first getting the current settings, applying the desired changes and than
/// updating the settings. This means that the operation is **not** atomic. This
/// can lead to a data race when two threads are changing options in parallel.
///
/// # Examples
///
/// Creating a new socket setting all advisable flags.
Expand All @@ -58,19 +66,20 @@ use crate::{Domain, Protocol, SockAddr, Type};
/// #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux", target_os = "netbsd", target_os = "openbsd"))]
/// let ty = ty.cloexec();
///
/// // On windows set `WSA_FLAG_NO_HANDLE_INHERIT`.
/// #[cfg(windows)]
/// let ty = ty.no_inherit();
///
/// let socket = Socket::new(domain, ty, Some(protocol))?;
///
/// // On platforms that don't support `SOCK_CLOEXEC`, use `FD_CLOEXEC`.
/// #[cfg(all(not(windows), not(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux", target_os = "netbsd", target_os = "openbsd"))))]
/// socket.set_cloexec()?;
/// socket.set_cloexec(true)?;
///
/// // On macOS and iOS set `NOSIGPIPE`.
/// #[cfg(target_vendor = "apple")]
/// socket.set_nosigpipe()?;
/// socket.set_nosigpipe(true)?;
///
/// // On windows set `HANDLE_FLAG_INHERIT`.
/// #[cfg(windows)]
/// socket.set_no_inherit()?;
/// # drop(socket);
/// # Ok(())
/// # }
Expand Down Expand Up @@ -198,26 +207,44 @@ impl Socket {
sys::accept(self.inner).map(|(inner, addr)| (Socket { inner }, addr))
}

/// Returns the socket address of the local half of this TCP connection.
/// Returns the socket address of the local half of this socket.
///
/// # Notes
///
/// Depending on the OS this may return an error if the socket is not
/// [bound].
///
/// [bound]: Socket::bind
pub fn local_addr(&self) -> io::Result<SockAddr> {
self.inner().local_addr()
sys::getsockname(self.inner)
}

/// Returns the socket address of the remote peer of this TCP connection.
/// Returns the socket address of the remote peer of this socket.
///
/// # Notes
///
/// This returns an error if the socket is not [`connect`ed].
///
/// [`connect`ed]: Socket::connect
pub fn peer_addr(&self) -> io::Result<SockAddr> {
self.inner().peer_addr()
sys::getpeername(self.inner)
}

/// Creates a new independently owned handle to the underlying socket.
///
/// The returned `TcpStream` is a reference to the same stream that this
/// object references. Both handles will read and write the same stream of
/// data, and options set on one stream will be propagated to the other
/// stream.
/// # Notes
///
/// On Unix this uses `F_DUPFD_CLOEXEC` and thus sets the `FD_CLOEXEC` on
/// the returned socket.
///
/// On Windows this uses `WSA_FLAG_NO_HANDLE_INHERIT` setting inheriting to
/// false.
///
/// On Windows this can **not** be used function cannot be used on a
/// QOS-enabled socket, see
/// <https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsaduplicatesocketw>.
pub fn try_clone(&self) -> io::Result<Socket> {
self.inner()
.try_clone()
.map(|s| Socket { inner: s.inner() })
sys::try_clone(self.inner).map(|inner| Socket { inner })
}

/// Get the value of the `SO_ERROR` option on this socket.
Expand All @@ -226,23 +253,27 @@ impl Socket {
/// the field in the process. This can be useful for checking errors between
/// calls.
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
self.inner().take_error()
sys::take_error(self.inner)
}

/// Moves this TCP stream into or out of nonblocking mode.
///
/// On Unix this corresponds to calling fcntl, and on Windows this
/// corresponds to calling ioctlsocket.
/// # Notes
///
/// On Unix this corresponds to calling `fcntl` (un)setting `O_NONBLOCK`.
///
/// On Windows this corresponds to calling `ioctlsocket` (un)setting
/// `FIONBIO`.
pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
self.inner().set_nonblocking(nonblocking)
sys::set_nonblocking(self.inner, nonblocking)
}

/// Shuts down the read, write, or both halves of this connection.
///
/// This function will cause all pending and future I/O on the specified
/// portions to return immediately with an appropriate value.
pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
self.inner().shutdown(how)
sys::shutdown(self.inner, how)
}

/// Receives data on the socket from the remote address to which it is
Expand Down
Loading