Skip to content

Add Socket::new_raw #125

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

Closed
wants to merge 11 commits into from
Closed
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", "web-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
138 changes: 88 additions & 50 deletions src/socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,39 +43,6 @@ use crate::{Domain, Protocol, SockAddr, Type};
///
/// # Examples
///
/// Creating a new socket setting all advisable flags.
///
#[cfg_attr(feature = "all", doc = "```")] // Protocol::cloexec requires the `all` feature.
#[cfg_attr(not(feature = "all"), doc = "```ignore")]
/// # fn main() -> std::io::Result<()> {
/// use socket2::{Protocol, Domain, Type, Socket};
///
/// let domain = Domain::IPV4;
/// let ty = Type::STREAM;
/// let protocol = Protocol::TCP;
///
/// // On platforms that support it set `SOCK_CLOEXEC`.
/// #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux", target_os = "netbsd", target_os = "openbsd"))]
/// let ty = ty.cloexec();
///
/// 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()?;
///
/// // On macOS and iOS set `NOSIGPIPE`.
/// #[cfg(target_vendor = "apple")]
/// socket.set_nosigpipe()?;
///
/// // On windows set `HANDLE_FLAG_INHERIT`.
/// #[cfg(windows)]
/// socket.set_no_inherit()?;
/// # drop(socket);
/// # Ok(())
/// # }
/// ```
///
/// ```no_run
/// # fn main() -> std::io::Result<()> {
/// use std::net::{SocketAddr, TcpListener};
Expand All @@ -101,6 +68,55 @@ pub struct Socket {
}

impl Socket {
/// Creates a new socket ready to be configured.
///
/// This function corresponds to `socket(2)` on Unix and `WSASocketW` on
/// Windows and creates a new socket. Unlike `Socket::new_raw` this sets the
/// most commonly used flags in the fastest possible way.
///
/// On Unix this sets the `CLOEXEC` flag. Furthermore on macOS and iOS
/// `NOSIGPIPE` is set.
///
/// On Windows the `HANDLE_FLAG_INHERIT` is set to zero.
pub fn new(domain: Domain, ty: Type, protocol: Option<Protocol>) -> io::Result<Socket> {
// On platforms that support it set `SOCK_CLOEXEC`.
#[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_raw(domain, ty, 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()?;

// On macOS and iOS set `NOSIGPIPE`.
#[cfg(target_vendor = "apple")]
socket._set_nosigpipe()?;

Ok(socket)
}

/// Creates a new socket ready to be configured.
///
/// This function corresponds to `socket(2)` on Unix and `WSASocketW` on
Expand All @@ -123,7 +139,7 @@ impl Socket {
///
/// See the `Socket` documentation for a full example of setting all the
/// above mentioned flags.
pub fn new(domain: Domain, ty: Type, protocol: Option<Protocol>) -> io::Result<Socket> {
pub fn new_raw(domain: Domain, ty: Type, protocol: Option<Protocol>) -> io::Result<Socket> {
let protocol = protocol.map(|p| p.0).unwrap_or(0);
sys::socket(domain.0, ty.0, protocol).map(|inner| Socket { inner })
}
Expand Down Expand Up @@ -198,26 +214,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 +260,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