rust/src/libstd/sys/common/net.rs

627 lines
20 KiB
Rust
Raw Normal View History

// Copyright 2013-2014 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 prelude::v1::*;
use cmp;
use ffi::{CStr, CString};
use fmt;
use io::{self, Error, ErrorKind};
use libc::{c_int, c_char, c_void, c_uint};
use mem;
std: Stabilize APIs for the 1.6 release This commit is the standard API stabilization commit for the 1.6 release cycle. The list of issues and APIs below have all been through their cycle-long FCP and the libs team decisions are listed below Stabilized APIs * `Read::read_exact` * `ErrorKind::UnexpectedEof` (renamed from `UnexpectedEOF`) * libcore -- this was a bit of a nuanced stabilization, the crate itself is now marked as `#[stable]` and the methods appearing via traits for primitives like `char` and `str` are now also marked as stable. Note that the extension traits themeselves are marked as unstable as they're imported via the prelude. The `try!` macro was also moved from the standard library into libcore to have the same interface. Otherwise the functions all have copied stability from the standard library now. * The `#![no_std]` attribute * `fs::DirBuilder` * `fs::DirBuilder::new` * `fs::DirBuilder::recursive` * `fs::DirBuilder::create` * `os::unix::fs::DirBuilderExt` * `os::unix::fs::DirBuilderExt::mode` * `vec::Drain` * `vec::Vec::drain` * `string::Drain` * `string::String::drain` * `vec_deque::Drain` * `vec_deque::VecDeque::drain` * `collections::hash_map::Drain` * `collections::hash_map::HashMap::drain` * `collections::hash_set::Drain` * `collections::hash_set::HashSet::drain` * `collections::binary_heap::Drain` * `collections::binary_heap::BinaryHeap::drain` * `Vec::extend_from_slice` (renamed from `push_all`) * `Mutex::get_mut` * `Mutex::into_inner` * `RwLock::get_mut` * `RwLock::into_inner` * `Iterator::min_by_key` (renamed from `min_by`) * `Iterator::max_by_key` (renamed from `max_by`) Deprecated APIs * `ErrorKind::UnexpectedEOF` (renamed to `UnexpectedEof`) * `OsString::from_bytes` * `OsStr::to_cstring` * `OsStr::to_bytes` * `fs::walk_dir` and `fs::WalkDir` * `path::Components::peek` * `slice::bytes::MutableByteVector` * `slice::bytes::copy_memory` * `Vec::push_all` (renamed to `extend_from_slice`) * `Duration::span` * `IpAddr` * `SocketAddr::ip` * `Read::tee` * `io::Tee` * `Write::broadcast` * `io::Broadcast` * `Iterator::min_by` (renamed to `min_by_key`) * `Iterator::max_by` (renamed to `max_by_key`) * `net::lookup_addr` New APIs (still unstable) * `<[T]>::sort_by_key` (added to mirror `min_by_key`) Closes #27585 Closes #27704 Closes #27707 Closes #27710 Closes #27711 Closes #27727 Closes #27740 Closes #27744 Closes #27799 Closes #27801 cc #27801 (doesn't close as `Chars` is still unstable) Closes #28968
2015-12-03 01:31:49 +00:00
#[allow(deprecated)]
2016-02-27 23:02:48 +00:00
use net::{SocketAddr, Shutdown, IpAddr, Ipv4Addr, Ipv6Addr};
use ptr;
use str::from_utf8;
use sys::net::{cvt, cvt_r, cvt_gai, Socket, init, wrlen_t};
use sys::net::netc as c;
use sys_common::{AsInner, FromInner, IntoInner};
use time::Duration;
////////////////////////////////////////////////////////////////////////////////
// sockaddr and misc bindings
////////////////////////////////////////////////////////////////////////////////
pub fn setsockopt<T>(sock: &Socket, opt: c_int, val: c_int,
payload: T) -> io::Result<()> {
unsafe {
let payload = &payload as *const T as *const c_void;
try!(cvt(c::setsockopt(*sock.as_inner(), opt, val, payload,
mem::size_of::<T>() as c::socklen_t)));
Ok(())
}
}
pub fn getsockopt<T: Copy>(sock: &Socket, opt: c_int,
2016-02-27 23:02:48 +00:00
val: c_int) -> io::Result<T> { unsafe {
let mut slot: T = mem::zeroed();
let mut len = mem::size_of::<T>() as c::socklen_t;
try!(cvt(c::getsockopt(*sock.as_inner(), opt, val,
&mut slot as *mut _ as *mut _,
&mut len)));
assert_eq!(len as usize, mem::size_of::<T>());
Ok(slot)
}
}
fn sockname<F>(f: F) -> io::Result<SocketAddr>
where F: FnOnce(*mut c::sockaddr, *mut c::socklen_t) -> c_int
{
unsafe {
let mut storage: c::sockaddr_storage = mem::zeroed();
let mut len = mem::size_of_val(&storage) as c::socklen_t;
try!(cvt(f(&mut storage as *mut _ as *mut _, &mut len)));
sockaddr_to_addr(&storage, len as usize)
}
}
fn sockaddr_to_addr(storage: &c::sockaddr_storage,
len: usize) -> io::Result<SocketAddr> {
match storage.ss_family as c_int {
c::AF_INET => {
assert!(len as usize >= mem::size_of::<c::sockaddr_in>());
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 21:22:33 +00:00
Ok(SocketAddr::V4(FromInner::from_inner(unsafe {
*(storage as *const _ as *const c::sockaddr_in)
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 21:22:33 +00:00
})))
}
c::AF_INET6 => {
assert!(len as usize >= mem::size_of::<c::sockaddr_in6>());
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 21:22:33 +00:00
Ok(SocketAddr::V6(FromInner::from_inner(unsafe {
*(storage as *const _ as *const c::sockaddr_in6)
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 21:22:33 +00:00
})))
}
_ => {
Err(Error::new(ErrorKind::InvalidInput, "invalid argument"))
}
}
}
2016-02-27 23:02:48 +00:00
#[cfg(target_os = "android")]
fn to_ipv6mr_interface(value: u32) -> c_int {
value as c_int
2016-02-27 23:02:48 +00:00
}
#[cfg(not(target_os = "android"))]
fn to_ipv6mr_interface(value: u32) -> c_uint {
value as c_uint
2016-02-27 23:02:48 +00:00
}
////////////////////////////////////////////////////////////////////////////////
// get_host_addresses
////////////////////////////////////////////////////////////////////////////////
pub struct LookupHost {
original: *mut c::addrinfo,
cur: *mut c::addrinfo,
}
impl Iterator for LookupHost {
type Item = io::Result<SocketAddr>;
fn next(&mut self) -> Option<io::Result<SocketAddr>> {
unsafe {
if self.cur.is_null() { return None }
let ret = sockaddr_to_addr(mem::transmute((*self.cur).ai_addr),
(*self.cur).ai_addrlen as usize);
self.cur = (*self.cur).ai_next as *mut c::addrinfo;
Some(ret)
}
}
}
unsafe impl Sync for LookupHost {}
unsafe impl Send for LookupHost {}
impl Drop for LookupHost {
fn drop(&mut self) {
unsafe { c::freeaddrinfo(self.original) }
}
}
pub fn lookup_host(host: &str) -> io::Result<LookupHost> {
init();
std: Implement CString-related RFCs This commit is an implementation of [RFC 592][r592] and [RFC 840][r840]. These two RFCs tweak the behavior of `CString` and add a new `CStr` unsized slice type to the module. [r592]: https://github.com/rust-lang/rfcs/blob/master/text/0592-c-str-deref.md [r840]: https://github.com/rust-lang/rfcs/blob/master/text/0840-no-panic-in-c-string.md The new `CStr` type is only constructable via two methods: 1. By `deref`'ing from a `CString` 2. Unsafely via `CStr::from_ptr` The purpose of `CStr` is to be an unsized type which is a thin pointer to a `libc::c_char` (currently it is a fat pointer slice due to implementation limitations). Strings from C can be safely represented with a `CStr` and an appropriate lifetime as well. Consumers of `&CString` should now consume `&CStr` instead to allow producers to pass in C-originating strings instead of just Rust-allocated strings. A new constructor was added to `CString`, `new`, which takes `T: IntoBytes` instead of separate `from_slice` and `from_vec` methods (both have been deprecated in favor of `new`). The `new` method returns a `Result` instead of panicking. The error variant contains the relevant information about where the error happened and bytes (if present). Conversions are provided to the `io::Error` and `old_io::IoError` types via the `FromError` trait which translate to `InvalidInput`. This is a breaking change due to the modification of existing `#[unstable]` APIs and new deprecation, and more detailed information can be found in the two RFCs. Notable breakage includes: * All construction of `CString` now needs to use `new` and handle the outgoing `Result`. * Usage of `CString` as a byte slice now explicitly needs a `.as_bytes()` call. * The `as_slice*` methods have been removed in favor of just having the `as_bytes*` methods. Closes #22469 Closes #22470 [breaking-change]
2015-02-18 06:47:40 +00:00
let c_host = try!(CString::new(host));
let mut res = ptr::null_mut();
unsafe {
try!(cvt_gai(c::getaddrinfo(c_host.as_ptr(), ptr::null(), ptr::null(),
&mut res)));
Ok(LookupHost { original: res, cur: res })
}
}
////////////////////////////////////////////////////////////////////////////////
// lookup_addr
////////////////////////////////////////////////////////////////////////////////
std: Stabilize APIs for the 1.6 release This commit is the standard API stabilization commit for the 1.6 release cycle. The list of issues and APIs below have all been through their cycle-long FCP and the libs team decisions are listed below Stabilized APIs * `Read::read_exact` * `ErrorKind::UnexpectedEof` (renamed from `UnexpectedEOF`) * libcore -- this was a bit of a nuanced stabilization, the crate itself is now marked as `#[stable]` and the methods appearing via traits for primitives like `char` and `str` are now also marked as stable. Note that the extension traits themeselves are marked as unstable as they're imported via the prelude. The `try!` macro was also moved from the standard library into libcore to have the same interface. Otherwise the functions all have copied stability from the standard library now. * The `#![no_std]` attribute * `fs::DirBuilder` * `fs::DirBuilder::new` * `fs::DirBuilder::recursive` * `fs::DirBuilder::create` * `os::unix::fs::DirBuilderExt` * `os::unix::fs::DirBuilderExt::mode` * `vec::Drain` * `vec::Vec::drain` * `string::Drain` * `string::String::drain` * `vec_deque::Drain` * `vec_deque::VecDeque::drain` * `collections::hash_map::Drain` * `collections::hash_map::HashMap::drain` * `collections::hash_set::Drain` * `collections::hash_set::HashSet::drain` * `collections::binary_heap::Drain` * `collections::binary_heap::BinaryHeap::drain` * `Vec::extend_from_slice` (renamed from `push_all`) * `Mutex::get_mut` * `Mutex::into_inner` * `RwLock::get_mut` * `RwLock::into_inner` * `Iterator::min_by_key` (renamed from `min_by`) * `Iterator::max_by_key` (renamed from `max_by`) Deprecated APIs * `ErrorKind::UnexpectedEOF` (renamed to `UnexpectedEof`) * `OsString::from_bytes` * `OsStr::to_cstring` * `OsStr::to_bytes` * `fs::walk_dir` and `fs::WalkDir` * `path::Components::peek` * `slice::bytes::MutableByteVector` * `slice::bytes::copy_memory` * `Vec::push_all` (renamed to `extend_from_slice`) * `Duration::span` * `IpAddr` * `SocketAddr::ip` * `Read::tee` * `io::Tee` * `Write::broadcast` * `io::Broadcast` * `Iterator::min_by` (renamed to `min_by_key`) * `Iterator::max_by` (renamed to `max_by_key`) * `net::lookup_addr` New APIs (still unstable) * `<[T]>::sort_by_key` (added to mirror `min_by_key`) Closes #27585 Closes #27704 Closes #27707 Closes #27710 Closes #27711 Closes #27727 Closes #27740 Closes #27744 Closes #27799 Closes #27801 cc #27801 (doesn't close as `Chars` is still unstable) Closes #28968
2015-12-03 01:31:49 +00:00
#[allow(deprecated)]
pub fn lookup_addr(addr: &IpAddr) -> io::Result<String> {
init();
let saddr = SocketAddr::new(*addr, 0);
let (inner, len) = saddr.into_inner();
let mut hostbuf = [0 as c_char; c::NI_MAXHOST as usize];
let data = unsafe {
try!(cvt_gai(c::getnameinfo(inner, len,
hostbuf.as_mut_ptr(),
c::NI_MAXHOST,
ptr::null_mut(), 0, 0)));
CStr::from_ptr(hostbuf.as_ptr())
};
match from_utf8(data.to_bytes()) {
2015-09-07 22:36:29 +00:00
Ok(name) => Ok(name.to_owned()),
Err(_) => Err(io::Error::new(io::ErrorKind::Other,
"failed to lookup address information"))
}
}
////////////////////////////////////////////////////////////////////////////////
// TCP streams
////////////////////////////////////////////////////////////////////////////////
pub struct TcpStream {
inner: Socket,
}
impl TcpStream {
pub fn connect(addr: &SocketAddr) -> io::Result<TcpStream> {
init();
let sock = try!(Socket::new(addr, c::SOCK_STREAM));
let (addrp, len) = addr.into_inner();
try!(cvt_r(|| unsafe { c::connect(*sock.as_inner(), addrp, len) }));
Ok(TcpStream { inner: sock })
}
pub fn socket(&self) -> &Socket { &self.inner }
pub fn into_socket(self) -> Socket { self.inner }
pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
self.inner.set_timeout(dur, c::SO_RCVTIMEO)
}
pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
self.inner.set_timeout(dur, c::SO_SNDTIMEO)
}
pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
self.inner.timeout(c::SO_RCVTIMEO)
}
pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
self.inner.timeout(c::SO_SNDTIMEO)
}
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
self.inner.read(buf)
}
pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t;
let ret = try!(cvt(unsafe {
c::send(*self.inner.as_inner(),
buf.as_ptr() as *const c_void,
len,
0)
}));
Ok(ret as usize)
}
pub fn peer_addr(&self) -> io::Result<SocketAddr> {
sockname(|buf, len| unsafe {
c::getpeername(*self.inner.as_inner(), buf, len)
})
}
pub fn socket_addr(&self) -> io::Result<SocketAddr> {
sockname(|buf, len| unsafe {
c::getsockname(*self.inner.as_inner(), buf, len)
})
}
pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
self.inner.shutdown(how)
}
pub fn duplicate(&self) -> io::Result<TcpStream> {
self.inner.duplicate().map(|s| TcpStream { inner: s })
}
2016-02-27 22:15:19 +00:00
pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
self.inner.set_nodelay(nodelay)
2016-02-27 22:15:19 +00:00
}
pub fn nodelay(&self) -> io::Result<bool> {
self.inner.nodelay()
2016-02-27 22:15:19 +00:00
}
pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
setsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL, ttl as c_int)
}
pub fn ttl(&self) -> io::Result<u32> {
let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL));
Ok(raw as u32)
}
pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
setsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY, only_v6 as c_int)
}
pub fn only_v6(&self) -> io::Result<bool> {
let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY));
Ok(raw != 0)
}
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
let raw: c_int = try!(getsockopt(&self.inner, c::SOL_SOCKET, c::SO_ERROR));
if raw == 0 {
Ok(None)
} else {
Ok(Some(io::Error::from_raw_os_error(raw as i32)))
}
}
pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
self.inner.set_nonblocking(nonblocking)
}
}
impl FromInner<Socket> for TcpStream {
fn from_inner(socket: Socket) -> TcpStream {
TcpStream { inner: socket }
}
}
impl fmt::Debug for TcpStream {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut res = f.debug_struct("TcpStream");
if let Ok(addr) = self.socket_addr() {
res.field("addr", &addr);
}
if let Ok(peer) = self.peer_addr() {
res.field("peer", &peer);
}
let name = if cfg!(windows) {"socket"} else {"fd"};
res.field(name, &self.inner.as_inner())
.finish()
}
}
////////////////////////////////////////////////////////////////////////////////
// TCP listeners
////////////////////////////////////////////////////////////////////////////////
pub struct TcpListener {
inner: Socket,
}
impl TcpListener {
pub fn bind(addr: &SocketAddr) -> io::Result<TcpListener> {
init();
let sock = try!(Socket::new(addr, c::SOCK_STREAM));
// 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.
if !cfg!(windows) {
try!(setsockopt(&sock, c::SOL_SOCKET, c::SO_REUSEADDR,
1 as c_int));
}
// Bind our new socket
let (addrp, len) = addr.into_inner();
try!(cvt(unsafe { c::bind(*sock.as_inner(), addrp, len) }));
// Start listening
try!(cvt(unsafe { c::listen(*sock.as_inner(), 128) }));
Ok(TcpListener { inner: sock })
}
pub fn socket(&self) -> &Socket { &self.inner }
pub fn into_socket(self) -> Socket { self.inner }
pub fn socket_addr(&self) -> io::Result<SocketAddr> {
sockname(|buf, len| unsafe {
c::getsockname(*self.inner.as_inner(), buf, len)
})
}
pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
let mut storage: c::sockaddr_storage = unsafe { mem::zeroed() };
let mut len = mem::size_of_val(&storage) as c::socklen_t;
let sock = try!(self.inner.accept(&mut storage as *mut _ as *mut _,
&mut len));
let addr = try!(sockaddr_to_addr(&storage, len as usize));
Ok((TcpStream { inner: sock, }, addr))
}
pub fn duplicate(&self) -> io::Result<TcpListener> {
self.inner.duplicate().map(|s| TcpListener { inner: s })
}
2016-02-27 22:15:19 +00:00
pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
setsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL, ttl as c_int)
}
pub fn ttl(&self) -> io::Result<u32> {
let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL));
Ok(raw as u32)
}
pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
setsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY, only_v6 as c_int)
}
pub fn only_v6(&self) -> io::Result<bool> {
let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY));
Ok(raw != 0)
}
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
let raw: c_int = try!(getsockopt(&self.inner, c::SOL_SOCKET, c::SO_ERROR));
if raw == 0 {
Ok(None)
} else {
Ok(Some(io::Error::from_raw_os_error(raw as i32)))
}
}
pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
self.inner.set_nonblocking(nonblocking)
}
}
impl FromInner<Socket> for TcpListener {
fn from_inner(socket: Socket) -> TcpListener {
TcpListener { inner: socket }
}
}
impl fmt::Debug for TcpListener {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut res = f.debug_struct("TcpListener");
if let Ok(addr) = self.socket_addr() {
res.field("addr", &addr);
}
let name = if cfg!(windows) {"socket"} else {"fd"};
res.field(name, &self.inner.as_inner())
.finish()
}
}
////////////////////////////////////////////////////////////////////////////////
// UDP
////////////////////////////////////////////////////////////////////////////////
pub struct UdpSocket {
inner: Socket,
}
impl UdpSocket {
pub fn bind(addr: &SocketAddr) -> io::Result<UdpSocket> {
init();
let sock = try!(Socket::new(addr, c::SOCK_DGRAM));
let (addrp, len) = addr.into_inner();
try!(cvt(unsafe { c::bind(*sock.as_inner(), addrp, len) }));
Ok(UdpSocket { inner: sock })
}
pub fn socket(&self) -> &Socket { &self.inner }
pub fn into_socket(self) -> Socket { self.inner }
pub fn socket_addr(&self) -> io::Result<SocketAddr> {
sockname(|buf, len| unsafe {
c::getsockname(*self.inner.as_inner(), buf, len)
})
}
pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
let mut storage: c::sockaddr_storage = unsafe { mem::zeroed() };
let mut addrlen = mem::size_of_val(&storage) as c::socklen_t;
let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t;
let n = try!(cvt(unsafe {
c::recvfrom(*self.inner.as_inner(),
buf.as_mut_ptr() as *mut c_void,
len, 0,
&mut storage as *mut _ as *mut _, &mut addrlen)
}));
Ok((n as usize, try!(sockaddr_to_addr(&storage, addrlen as usize))))
}
pub fn send_to(&self, buf: &[u8], dst: &SocketAddr) -> io::Result<usize> {
let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t;
let (dstp, dstlen) = dst.into_inner();
let ret = try!(cvt(unsafe {
c::sendto(*self.inner.as_inner(),
buf.as_ptr() as *const c_void, len,
0, dstp, dstlen)
}));
Ok(ret as usize)
}
pub fn duplicate(&self) -> io::Result<UdpSocket> {
self.inner.duplicate().map(|s| UdpSocket { inner: s })
}
pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
self.inner.set_timeout(dur, c::SO_RCVTIMEO)
}
pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
self.inner.set_timeout(dur, c::SO_SNDTIMEO)
}
pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
self.inner.timeout(c::SO_RCVTIMEO)
}
pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
self.inner.timeout(c::SO_SNDTIMEO)
}
2016-02-27 23:02:48 +00:00
pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> {
setsockopt(&self.inner, c::SOL_SOCKET, c::SO_BROADCAST, broadcast as c_int)
}
pub fn broadcast(&self) -> io::Result<bool> {
let raw: c_int = try!(getsockopt(&self.inner, c::SOL_SOCKET, c::SO_BROADCAST));
Ok(raw != 0)
}
pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> {
setsockopt(&self.inner, c::IPPROTO_IP, c::IP_MULTICAST_LOOP, multicast_loop_v4 as c_int)
}
pub fn multicast_loop_v4(&self) -> io::Result<bool> {
let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IP, c::IP_MULTICAST_LOOP));
Ok(raw != 0)
}
pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> {
setsockopt(&self.inner, c::IPPROTO_IP, c::IP_MULTICAST_TTL, multicast_ttl_v4 as c_int)
}
pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IP, c::IP_MULTICAST_TTL));
Ok(raw as u32)
}
pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> {
setsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_MULTICAST_LOOP, multicast_loop_v6 as c_int)
}
pub fn multicast_loop_v6(&self) -> io::Result<bool> {
let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_MULTICAST_LOOP));
Ok(raw != 0)
}
pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr)
-> io::Result<()> {
let mreq = c::ip_mreq {
imr_multiaddr: *multiaddr.as_inner(),
imr_interface: *interface.as_inner(),
};
setsockopt(&self.inner, c::IPPROTO_IP, c::IP_ADD_MEMBERSHIP, mreq)
}
pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32)
-> io::Result<()> {
let mreq = c::ipv6_mreq {
ipv6mr_multiaddr: *multiaddr.as_inner(),
ipv6mr_interface: to_ipv6mr_interface(interface),
};
setsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_ADD_MEMBERSHIP, mreq)
}
pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr)
-> io::Result<()> {
let mreq = c::ip_mreq {
imr_multiaddr: *multiaddr.as_inner(),
imr_interface: *interface.as_inner(),
};
setsockopt(&self.inner, c::IPPROTO_IP, c::IP_DROP_MEMBERSHIP, mreq)
}
pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32)
-> io::Result<()> {
let mreq = c::ipv6_mreq {
ipv6mr_multiaddr: *multiaddr.as_inner(),
ipv6mr_interface: to_ipv6mr_interface(interface),
};
setsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_DROP_MEMBERSHIP, mreq)
}
pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
setsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL, ttl as c_int)
}
pub fn ttl(&self) -> io::Result<u32> {
let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL));
Ok(raw as u32)
}
pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
setsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY, only_v6 as c_int)
}
pub fn only_v6(&self) -> io::Result<bool> {
let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY));
Ok(raw != 0)
}
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
let raw: c_int = try!(getsockopt(&self.inner, c::SOL_SOCKET, c::SO_ERROR));
if raw == 0 {
Ok(None)
} else {
Ok(Some(io::Error::from_raw_os_error(raw as i32)))
}
}
pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
self.inner.set_nonblocking(nonblocking)
}
pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
self.inner.read(buf)
}
pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t;
let ret = try!(cvt(unsafe {
c::send(*self.inner.as_inner(),
buf.as_ptr() as *const c_void,
len,
0)
}));
Ok(ret as usize)
}
pub fn connect(&self, addr: &SocketAddr) -> io::Result<()> {
let (addrp, len) = addr.into_inner();
cvt_r(|| unsafe { c::connect(*self.inner.as_inner(), addrp, len) }).map(|_| ())
}
}
impl FromInner<Socket> for UdpSocket {
fn from_inner(socket: Socket) -> UdpSocket {
UdpSocket { inner: socket }
}
}
impl fmt::Debug for UdpSocket {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut res = f.debug_struct("UdpSocket");
if let Ok(addr) = self.socket_addr() {
res.field("addr", &addr);
}
let name = if cfg!(windows) {"socket"} else {"fd"};
res.field(name, &self.inner.as_inner())
.finish()
}
}