2015-02-05 16:50:11 -08:00
|
|
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
|
|
|
|
|
// file at the top-level directory of this distribution and at
|
|
|
|
|
// http://rust-lang.org/COPYRIGHT.
|
|
|
|
|
//
|
|
|
|
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
|
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
|
|
|
|
// option. This file may not be copied, modified, or distributed
|
|
|
|
|
// except according to those terms.
|
|
|
|
|
|
|
|
|
|
use io;
|
|
|
|
|
use libc::consts::os::extra::INVALID_SOCKET;
|
|
|
|
|
use libc::{self, c_int, c_void};
|
|
|
|
|
use mem;
|
std: Stabilize the `net` module
This commit performs a stabilization pass over the std::net module,
incorporating the changes from RFC 923. Specifically, the following actions were
taken:
Stable functionality:
* `net` (the name)
* `Shutdown`
* `Shutdown::{Read, Write, Both}`
* `lookup_host`
* `LookupHost`
* `SocketAddr`
* `SocketAddr::{V4, V6}`
* `SocketAddr::port`
* `SocketAddrV4`
* `SocketAddrV4::{new, ip, port}`
* `SocketAddrV6`
* `SocketAddrV4::{new, ip, port, flowinfo, scope_id}`
* Common trait impls for socket addr structures
* `ToSocketAddrs`
* `ToSocketAddrs::Iter`
* `ToSocketAddrs::to_socket_addrs`
* `ToSocketAddrs for {SocketAddr*, (Ipv*Addr, u16), str, (str, u16)}`
* `Ipv4Addr`
* `Ipv4Addr::{new, octets, to_ipv6_compatible, to_ipv6_mapped}`
* `Ipv6Addr`
* `Ipv6Addr::{new, segments, to_ipv4}`
* `TcpStream`
* `TcpStream::connect`
* `TcpStream::{peer_addr, local_addr, shutdown, try_clone}`
* `{Read,Write} for {TcpStream, &TcpStream}`
* `TcpListener`
* `TcpListener::bind`
* `TcpListener::{local_addr, try_clone, accept, incoming}`
* `Incoming`
* `UdpSocket`
* `UdpSocket::bind`
* `UdpSocket::{recv_from, send_to, local_addr, try_clone}`
Unstable functionality:
* Extra methods on `Ipv{4,6}Addr` for various methods of inspecting the address
and determining qualities of it.
* Extra methods on `TcpStream` to configure various protocol options.
* Extra methods on `UdpSocket` to configure various protocol options.
Deprecated functionality:
* The `socket_addr` method has been renamed to `local_addr`
This commit is a breaking change due to the restructuring of the `SocketAddr`
type as well as the renaming of the `socket_addr` method. Migration should be
fairly straightforward, however, after accounting for the new level of
abstraction in `SocketAddr` (protocol distinction at the socket address level,
not the IP address).
[breaking-change]
2015-03-13 14:22:33 -07:00
|
|
|
use net::SocketAddr;
|
2015-04-17 23:45:55 -07:00
|
|
|
use num::One;
|
|
|
|
|
use ops::Neg;
|
2015-09-03 09:49:50 +03:00
|
|
|
use ptr;
|
2015-02-05 16:50:11 -08:00
|
|
|
use rt;
|
2015-05-27 11:18:36 +03:00
|
|
|
use sync::Once;
|
2015-05-26 23:47:03 -07:00
|
|
|
use sys;
|
2015-02-05 16:50:11 -08:00
|
|
|
use sys::c;
|
2015-07-15 23:31:24 -07:00
|
|
|
use sys_common::{AsInner, FromInner, IntoInner};
|
2015-05-26 23:47:03 -07:00
|
|
|
use sys_common::net::{setsockopt, getsockopt};
|
|
|
|
|
use time::Duration;
|
2015-02-05 16:50:11 -08:00
|
|
|
|
|
|
|
|
pub type wrlen_t = i32;
|
|
|
|
|
|
|
|
|
|
pub struct Socket(libc::SOCKET);
|
|
|
|
|
|
2015-02-23 23:50:32 +01:00
|
|
|
/// Checks whether the Windows socket interface has been started already, and
|
|
|
|
|
/// if not, starts it.
|
2015-02-05 16:50:11 -08:00
|
|
|
pub fn init() {
|
2015-05-27 11:18:36 +03:00
|
|
|
static START: Once = Once::new();
|
2015-02-05 16:50:11 -08:00
|
|
|
|
|
|
|
|
START.call_once(|| unsafe {
|
|
|
|
|
let mut data: c::WSADATA = mem::zeroed();
|
|
|
|
|
let ret = c::WSAStartup(0x202, // version 2.2
|
|
|
|
|
&mut data);
|
|
|
|
|
assert_eq!(ret, 0);
|
|
|
|
|
|
2015-03-24 16:55:35 -07:00
|
|
|
let _ = rt::at_exit(|| { c::WSACleanup(); });
|
2015-02-05 16:50:11 -08:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2015-02-23 23:50:32 +01:00
|
|
|
/// Returns the last error from the Windows socket interface.
|
2015-02-05 16:50:11 -08:00
|
|
|
fn last_error() -> io::Error {
|
2015-04-08 16:41:14 -07:00
|
|
|
io::Error::from_raw_os_error(unsafe { c::WSAGetLastError() })
|
2015-02-05 16:50:11 -08:00
|
|
|
}
|
|
|
|
|
|
2015-02-23 23:50:32 +01:00
|
|
|
/// Checks if the signed integer is the Windows constant `SOCKET_ERROR` (-1)
|
|
|
|
|
/// and if so, returns the last error from the Windows socket interface. . This
|
|
|
|
|
/// function must be called before another call to the socket API is made.
|
2015-04-17 23:45:55 -07:00
|
|
|
pub fn cvt<T: One + Neg<Output=T> + PartialEq>(t: T) -> io::Result<T> {
|
|
|
|
|
let one: T = T::one();
|
2015-02-05 16:50:11 -08:00
|
|
|
if t == -one {
|
|
|
|
|
Err(last_error())
|
|
|
|
|
} else {
|
|
|
|
|
Ok(t)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2015-02-23 23:50:32 +01:00
|
|
|
/// Provides the functionality of `cvt` for the return values of `getaddrinfo`
|
|
|
|
|
/// and similar, meaning that they return an error if the return value is 0.
|
2015-02-05 16:50:11 -08:00
|
|
|
pub fn cvt_gai(err: c_int) -> io::Result<()> {
|
|
|
|
|
if err == 0 { return Ok(()) }
|
|
|
|
|
cvt(err).map(|_| ())
|
|
|
|
|
}
|
|
|
|
|
|
2015-02-23 23:50:32 +01:00
|
|
|
/// Provides the functionality of `cvt` for a closure.
|
2015-04-17 23:45:55 -07:00
|
|
|
pub fn cvt_r<T, F>(mut f: F) -> io::Result<T>
|
|
|
|
|
where F: FnMut() -> T, T: One + Neg<Output=T> + PartialEq
|
|
|
|
|
{
|
2015-02-05 16:50:11 -08:00
|
|
|
cvt(f())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Socket {
|
|
|
|
|
pub fn new(addr: &SocketAddr, ty: c_int) -> io::Result<Socket> {
|
std: Stabilize the `net` module
This commit performs a stabilization pass over the std::net module,
incorporating the changes from RFC 923. Specifically, the following actions were
taken:
Stable functionality:
* `net` (the name)
* `Shutdown`
* `Shutdown::{Read, Write, Both}`
* `lookup_host`
* `LookupHost`
* `SocketAddr`
* `SocketAddr::{V4, V6}`
* `SocketAddr::port`
* `SocketAddrV4`
* `SocketAddrV4::{new, ip, port}`
* `SocketAddrV6`
* `SocketAddrV4::{new, ip, port, flowinfo, scope_id}`
* Common trait impls for socket addr structures
* `ToSocketAddrs`
* `ToSocketAddrs::Iter`
* `ToSocketAddrs::to_socket_addrs`
* `ToSocketAddrs for {SocketAddr*, (Ipv*Addr, u16), str, (str, u16)}`
* `Ipv4Addr`
* `Ipv4Addr::{new, octets, to_ipv6_compatible, to_ipv6_mapped}`
* `Ipv6Addr`
* `Ipv6Addr::{new, segments, to_ipv4}`
* `TcpStream`
* `TcpStream::connect`
* `TcpStream::{peer_addr, local_addr, shutdown, try_clone}`
* `{Read,Write} for {TcpStream, &TcpStream}`
* `TcpListener`
* `TcpListener::bind`
* `TcpListener::{local_addr, try_clone, accept, incoming}`
* `Incoming`
* `UdpSocket`
* `UdpSocket::bind`
* `UdpSocket::{recv_from, send_to, local_addr, try_clone}`
Unstable functionality:
* Extra methods on `Ipv{4,6}Addr` for various methods of inspecting the address
and determining qualities of it.
* Extra methods on `TcpStream` to configure various protocol options.
* Extra methods on `UdpSocket` to configure various protocol options.
Deprecated functionality:
* The `socket_addr` method has been renamed to `local_addr`
This commit is a breaking change due to the restructuring of the `SocketAddr`
type as well as the renaming of the `socket_addr` method. Migration should be
fairly straightforward, however, after accounting for the new level of
abstraction in `SocketAddr` (protocol distinction at the socket address level,
not the IP address).
[breaking-change]
2015-03-13 14:22:33 -07:00
|
|
|
let fam = match *addr {
|
|
|
|
|
SocketAddr::V4(..) => libc::AF_INET,
|
|
|
|
|
SocketAddr::V6(..) => libc::AF_INET6,
|
2015-02-05 16:50:11 -08:00
|
|
|
};
|
2015-06-29 09:46:35 -07:00
|
|
|
let socket = try!(unsafe {
|
2015-09-03 09:49:50 +03:00
|
|
|
match c::WSASocketW(fam, ty, 0, ptr::null_mut(), 0,
|
2015-06-29 09:46:35 -07:00
|
|
|
c::WSA_FLAG_OVERLAPPED) {
|
|
|
|
|
INVALID_SOCKET => Err(last_error()),
|
|
|
|
|
n => Ok(Socket(n)),
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
try!(socket.set_no_inherit());
|
|
|
|
|
Ok(socket)
|
2015-02-05 16:50:11 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn accept(&self, storage: *mut libc::sockaddr,
|
|
|
|
|
len: *mut libc::socklen_t) -> io::Result<Socket> {
|
2015-06-29 09:46:35 -07:00
|
|
|
let socket = try!(unsafe {
|
|
|
|
|
match libc::accept(self.0, storage, len) {
|
|
|
|
|
INVALID_SOCKET => Err(last_error()),
|
|
|
|
|
n => Ok(Socket(n)),
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
try!(socket.set_no_inherit());
|
|
|
|
|
Ok(socket)
|
2015-02-05 16:50:11 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn duplicate(&self) -> io::Result<Socket> {
|
2015-06-29 09:46:35 -07:00
|
|
|
let socket = try!(unsafe {
|
2015-02-05 16:50:11 -08:00
|
|
|
let mut info: c::WSAPROTOCOL_INFO = mem::zeroed();
|
|
|
|
|
try!(cvt(c::WSADuplicateSocketW(self.0,
|
|
|
|
|
c::GetCurrentProcessId(),
|
|
|
|
|
&mut info)));
|
|
|
|
|
match c::WSASocketW(info.iAddressFamily,
|
|
|
|
|
info.iSocketType,
|
|
|
|
|
info.iProtocol,
|
2015-04-08 15:43:37 -07:00
|
|
|
&mut info, 0,
|
2015-06-29 09:46:35 -07:00
|
|
|
c::WSA_FLAG_OVERLAPPED) {
|
2015-02-05 16:50:11 -08:00
|
|
|
INVALID_SOCKET => Err(last_error()),
|
|
|
|
|
n => Ok(Socket(n)),
|
|
|
|
|
}
|
2015-06-29 09:46:35 -07:00
|
|
|
});
|
|
|
|
|
try!(socket.set_no_inherit());
|
|
|
|
|
Ok(socket)
|
2015-02-05 16:50:11 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
|
|
|
|
|
// On unix when a socket is shut down all further reads return 0, so we
|
|
|
|
|
// do the same on windows to map a shut down socket to returning EOF.
|
|
|
|
|
unsafe {
|
|
|
|
|
match libc::recv(self.0, buf.as_mut_ptr() as *mut c_void,
|
|
|
|
|
buf.len() as i32, 0) {
|
|
|
|
|
-1 if c::WSAGetLastError() == c::WSAESHUTDOWN => Ok(0),
|
|
|
|
|
-1 => Err(last_error()),
|
|
|
|
|
n => Ok(n as usize)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2015-05-26 23:47:03 -07:00
|
|
|
|
|
|
|
|
pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> {
|
|
|
|
|
let timeout = match dur {
|
|
|
|
|
Some(dur) => {
|
|
|
|
|
let timeout = sys::dur2timeout(dur);
|
|
|
|
|
if timeout == 0 {
|
|
|
|
|
return Err(io::Error::new(io::ErrorKind::InvalidInput,
|
|
|
|
|
"cannot set a 0 duration timeout"));
|
|
|
|
|
}
|
|
|
|
|
timeout
|
|
|
|
|
}
|
|
|
|
|
None => 0
|
|
|
|
|
};
|
|
|
|
|
setsockopt(self, libc::SOL_SOCKET, kind, timeout)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
|
|
|
|
|
let raw: libc::DWORD = try!(getsockopt(self, libc::SOL_SOCKET, kind));
|
|
|
|
|
if raw == 0 {
|
|
|
|
|
Ok(None)
|
|
|
|
|
} else {
|
|
|
|
|
let secs = raw / 1000;
|
|
|
|
|
let nsec = (raw % 1000) * 1000000;
|
|
|
|
|
Ok(Some(Duration::new(secs as u64, nsec as u32)))
|
|
|
|
|
}
|
|
|
|
|
}
|
2015-06-29 09:46:35 -07:00
|
|
|
|
|
|
|
|
fn set_no_inherit(&self) -> io::Result<()> {
|
|
|
|
|
sys::cvt(unsafe {
|
|
|
|
|
c::SetHandleInformation(self.0 as libc::HANDLE,
|
|
|
|
|
c::HANDLE_FLAG_INHERIT, 0)
|
|
|
|
|
}).map(|_| ())
|
|
|
|
|
}
|
2015-02-05 16:50:11 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Drop for Socket {
|
|
|
|
|
fn drop(&mut self) {
|
std: Stabilize parts of std::os::platform::io
This commit stabilizes the platform-specific `io` modules, specifically around
the traits having to do with the raw representation of each object on each
platform.
Specifically, the following material was stabilized:
* `AsRaw{Fd,Socket,Handle}`
* `RawFd` (renamed from `Fd`)
* `RawHandle` (renamed from `Handle`)
* `RawSocket` (renamed from `Socket`)
* `AsRaw{Fd,Socket,Handle}` implementations
* `std::os::{unix, windows}::io`
The following material was added as `#[unstable]`:
* `FromRaw{Fd,Socket,Handle}`
* Implementations for various primitives
There are a number of future improvements that are possible to make to this
module, but this should cover a good bit of functionality desired from these
modules for now. Some specific future additions may include:
* `IntoRawXXX` traits to consume the raw representation and cancel the
auto-destructor.
* `Fd`, `Socket`, and `Handle` abstractions that behave like Rust objects and
have nice methods for various syscalls.
At this time though, these are considered backwards-compatible extensions and
will not be stabilized at this time.
This commit is a breaking change due to the addition of `Raw` in from of the
type aliases in each of the platform-specific modules.
[breaking-change]
2015-03-26 16:18:29 -07:00
|
|
|
let _ = unsafe { libc::closesocket(self.0) };
|
2015-02-05 16:50:11 -08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl AsInner<libc::SOCKET> for Socket {
|
|
|
|
|
fn as_inner(&self) -> &libc::SOCKET { &self.0 }
|
|
|
|
|
}
|
std: Stabilize parts of std::os::platform::io
This commit stabilizes the platform-specific `io` modules, specifically around
the traits having to do with the raw representation of each object on each
platform.
Specifically, the following material was stabilized:
* `AsRaw{Fd,Socket,Handle}`
* `RawFd` (renamed from `Fd`)
* `RawHandle` (renamed from `Handle`)
* `RawSocket` (renamed from `Socket`)
* `AsRaw{Fd,Socket,Handle}` implementations
* `std::os::{unix, windows}::io`
The following material was added as `#[unstable]`:
* `FromRaw{Fd,Socket,Handle}`
* Implementations for various primitives
There are a number of future improvements that are possible to make to this
module, but this should cover a good bit of functionality desired from these
modules for now. Some specific future additions may include:
* `IntoRawXXX` traits to consume the raw representation and cancel the
auto-destructor.
* `Fd`, `Socket`, and `Handle` abstractions that behave like Rust objects and
have nice methods for various syscalls.
At this time though, these are considered backwards-compatible extensions and
will not be stabilized at this time.
This commit is a breaking change due to the addition of `Raw` in from of the
type aliases in each of the platform-specific modules.
[breaking-change]
2015-03-26 16:18:29 -07:00
|
|
|
|
|
|
|
|
impl FromInner<libc::SOCKET> for Socket {
|
|
|
|
|
fn from_inner(sock: libc::SOCKET) -> Socket { Socket(sock) }
|
|
|
|
|
}
|
2015-07-15 23:31:24 -07:00
|
|
|
|
|
|
|
|
impl IntoInner<libc::SOCKET> for Socket {
|
|
|
|
|
fn into_inner(self) -> libc::SOCKET {
|
|
|
|
|
let ret = self.0;
|
|
|
|
|
mem::forget(self);
|
|
|
|
|
ret
|
|
|
|
|
}
|
|
|
|
|
}
|